id
stringlengths
15
17
content
stringlengths
5.4k
1.04M
max_stars_repo_path
stringlengths
74
98
manybugs_data_1
/* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library. * * Directory Read Support Routines. */ #include "tiffiop.h" #define IGNORE 0 /* tag placeholder used below */ #ifdef HAVE_IEEEFP # define TIFFCvtIEEEFloatToNative(tif, n, fp) # define TIFFCvtIEEEDoubleToNative(tif, n, dp) #else extern void TIFFCvtIEEEFloatToNative(TIFF*, uint32, float*); extern void TIFFCvtIEEEDoubleToNative(TIFF*, uint32, double*); #endif static int EstimateStripByteCounts(TIFF*, TIFFDirEntry*, uint16); static void MissingRequired(TIFF*, const char*); static int CheckDirCount(TIFF*, TIFFDirEntry*, uint32); static tsize_t TIFFFetchData(TIFF*, TIFFDirEntry*, char*); static tsize_t TIFFFetchString(TIFF*, TIFFDirEntry*, char*); static float TIFFFetchRational(TIFF*, TIFFDirEntry*); static int TIFFFetchNormalTag(TIFF*, TIFFDirEntry*); static int TIFFFetchPerSampleShorts(TIFF*, TIFFDirEntry*, uint16*); static int TIFFFetchPerSampleLongs(TIFF*, TIFFDirEntry*, uint32*); static int TIFFFetchPerSampleAnys(TIFF*, TIFFDirEntry*, double*); static int TIFFFetchShortArray(TIFF*, TIFFDirEntry*, uint16*); static int TIFFFetchStripThing(TIFF*, TIFFDirEntry*, long, uint32**); static int TIFFFetchRefBlackWhite(TIFF*, TIFFDirEntry*); static float TIFFFetchFloat(TIFF*, TIFFDirEntry*); static int TIFFFetchFloatArray(TIFF*, TIFFDirEntry*, float*); static int TIFFFetchDoubleArray(TIFF*, TIFFDirEntry*, double*); static int TIFFFetchAnyArray(TIFF*, TIFFDirEntry*, double*); static int TIFFFetchShortPair(TIFF*, TIFFDirEntry*); static void ChopUpSingleUncompressedStrip(TIFF*); /* * Read the next TIFF directory from a file * and convert it to the internal format. * We read directories sequentially. */ int TIFFReadDirectory(TIFF* tif) { static const char module[] = "TIFFReadDirectory"; int n; TIFFDirectory* td; TIFFDirEntry *dp, *dir = NULL; uint16 iv; uint32 v; const TIFFFieldInfo* fip; size_t fix; uint16 dircount; toff_t nextdiroff; char* cp; int diroutoforderwarning = 0; toff_t* new_dirlist; tif->tif_diroff = tif->tif_nextdiroff; if (tif->tif_diroff == 0) /* no more directories */ return (0); /* * XXX: Trick to prevent IFD looping. The one can create TIFF file * with looped directory pointers. We will maintain a list of already * seen directories and check every IFD offset against this list. */ for (n = 0; n < tif->tif_dirnumber; n++) { if (tif->tif_dirlist[n] == tif->tif_diroff) return (0); } tif->tif_dirnumber++; new_dirlist = _TIFFrealloc(tif->tif_dirlist, tif->tif_dirnumber * sizeof(toff_t)); if (!new_dirlist) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Failed to allocate space for IFD list", tif->tif_name); return (0); } tif->tif_dirlist = new_dirlist; tif->tif_dirlist[tif->tif_dirnumber - 1] = tif->tif_diroff; /* * Cleanup any previous compression state. */ (*tif->tif_cleanup)(tif); tif->tif_curdir++; nextdiroff = 0; if (!isMapped(tif)) { if (!SeekOK(tif, tif->tif_diroff)) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Seek error accessing TIFF directory", tif->tif_name); return (0); } if (!ReadOK(tif, &dircount, sizeof (uint16))) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Can not read TIFF directory count", tif->tif_name); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); dir = (TIFFDirEntry *)_TIFFCheckMalloc(tif, dircount, sizeof (TIFFDirEntry), "to read TIFF directory"); if (dir == NULL) return (0); if (!ReadOK(tif, dir, dircount*sizeof (TIFFDirEntry))) { TIFFErrorExt(tif->tif_clientdata, module, "%.100s: Can not read TIFF directory", tif->tif_name); goto bad; } /* * Read offset to next directory for sequential scans. */ (void) ReadOK(tif, &nextdiroff, sizeof (uint32)); } else { toff_t off = tif->tif_diroff; if (off + sizeof (uint16) > tif->tif_size) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Can not read TIFF directory count", tif->tif_name); return (0); } else _TIFFmemcpy(&dircount, tif->tif_base + off, sizeof (uint16)); off += sizeof (uint16); if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); dir = (TIFFDirEntry *)_TIFFCheckMalloc(tif, dircount, sizeof (TIFFDirEntry), "to read TIFF directory"); if (dir == NULL) return (0); if (off + dircount*sizeof (TIFFDirEntry) > tif->tif_size) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Can not read TIFF directory", tif->tif_name); goto bad; } else { _TIFFmemcpy(dir, tif->tif_base + off, dircount*sizeof (TIFFDirEntry)); } off += dircount* sizeof (TIFFDirEntry); if (off + sizeof (uint32) <= tif->tif_size) _TIFFmemcpy(&nextdiroff, tif->tif_base+off, sizeof (uint32)); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong(&nextdiroff); tif->tif_nextdiroff = nextdiroff; tif->tif_flags &= ~TIFF_BEENWRITING; /* reset before new dir */ /* * Setup default value and then make a pass over * the fields to check type and tag information, * and to extract info required to size data * structures. A second pass is made afterwards * to read in everthing not taken in the first pass. */ td = &tif->tif_dir; /* free any old stuff and reinit */ TIFFFreeDirectory(tif); TIFFDefaultDirectory(tif); /* * Electronic Arts writes gray-scale TIFF files * without a PlanarConfiguration directory entry. * Thus we setup a default value here, even though * the TIFF spec says there is no default value. */ TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); /* * Sigh, we must make a separate pass through the * directory for the following reason: * * We must process the Compression tag in the first pass * in order to merge in codec-private tag definitions (otherwise * we may get complaints about unknown tags). However, the * Compression tag may be dependent on the SamplesPerPixel * tag value because older TIFF specs permited Compression * to be written as a SamplesPerPixel-count tag entry. * Thus if we don't first figure out the correct SamplesPerPixel * tag value then we may end up ignoring the Compression tag * value because it has an incorrect count value (if the * true value of SamplesPerPixel is not 1). * * It sure would have been nice if Aldus had really thought * this stuff through carefully. */ for (dp = dir, n = dircount; n > 0; n--, dp++) { if (tif->tif_flags & TIFF_SWAB) { TIFFSwabArrayOfShort(&dp->tdir_tag, 2); TIFFSwabArrayOfLong(&dp->tdir_count, 2); } if (dp->tdir_tag == TIFFTAG_SAMPLESPERPIXEL) { if (!TIFFFetchNormalTag(tif, dp)) goto bad; dp->tdir_tag = IGNORE; } } /* * First real pass over the directory. */ fix = 0; for (dp = dir, n = dircount; n > 0; n--, dp++) { if (fix >= tif->tif_nfields || dp->tdir_tag == IGNORE) continue; /* * Silicon Beach (at least) writes unordered * directory tags (violating the spec). Handle * it here, but be obnoxious (maybe they'll fix it?). */ if (dp->tdir_tag < tif->tif_fieldinfo[fix]->field_tag) { if (!diroutoforderwarning) { TIFFWarning(module, "%s: invalid TIFF directory; tags are not sorted in ascending order", tif->tif_name); diroutoforderwarning = 1; } fix = 0; /* O(n^2) */ } while (fix < tif->tif_nfields && tif->tif_fieldinfo[fix]->field_tag < dp->tdir_tag) fix++; if (fix >= tif->tif_nfields || tif->tif_fieldinfo[fix]->field_tag != dp->tdir_tag) { TIFFWarning(module, "%s: unknown field with tag %d (0x%x) encountered", tif->tif_name, dp->tdir_tag, dp->tdir_tag, dp->tdir_type); TIFFMergeFieldInfo( tif, _TIFFCreateAnonFieldInfo( tif, dp->tdir_tag, (TIFFDataType) dp->tdir_type ), 1 ); fix = 0; while (fix < tif->tif_nfields && tif->tif_fieldinfo[fix]->field_tag < dp->tdir_tag) fix++; } /* * Null out old tags that we ignore. */ if (tif->tif_fieldinfo[fix]->field_bit == FIELD_IGNORE) { ignore: dp->tdir_tag = IGNORE; continue; } /* * Check data type. */ fip = tif->tif_fieldinfo[fix]; while (dp->tdir_type != (unsigned short) fip->field_type && fix < tif->tif_nfields) { if (fip->field_type == TIFF_ANY) /* wildcard */ break; fip = tif->tif_fieldinfo[++fix]; if (fix >= tif->tif_nfields || fip->field_tag != dp->tdir_tag) { TIFFWarning(module, "%s: wrong data type %d for \"%s\"; tag ignored", tif->tif_name, dp->tdir_type, tif->tif_fieldinfo[fix-1]->field_name); goto ignore; } } /* * Check count if known in advance. */ if (fip->field_readcount != TIFF_VARIABLE && fip->field_readcount != TIFF_VARIABLE2) { uint32 expected = (fip->field_readcount == TIFF_SPP) ? (uint32) td->td_samplesperpixel : (uint32) fip->field_readcount; if (!CheckDirCount(tif, dp, expected)) goto ignore; } switch (dp->tdir_tag) { case TIFFTAG_COMPRESSION: /* * The 5.0 spec says the Compression tag has * one value, while earlier specs say it has * one value per sample. Because of this, we * accept the tag if one value is supplied. */ if (dp->tdir_count == 1) { v = TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset); if (!TIFFSetField(tif, dp->tdir_tag, (uint16)v)) goto bad; break; /* XXX: workaround for broken TIFFs */ } else if (dp->tdir_type == TIFF_LONG) { if (!TIFFFetchPerSampleLongs(tif, dp, &v) || !TIFFSetField(tif, dp->tdir_tag, (uint16)v)) goto bad; } else { if (!TIFFFetchPerSampleShorts(tif, dp, &iv) || !TIFFSetField(tif, dp->tdir_tag, iv)) goto bad; } dp->tdir_tag = IGNORE; break; case TIFFTAG_STRIPOFFSETS: case TIFFTAG_STRIPBYTECOUNTS: case TIFFTAG_TILEOFFSETS: case TIFFTAG_TILEBYTECOUNTS: TIFFSetFieldBit(tif, fip->field_bit); break; case TIFFTAG_IMAGEWIDTH: case TIFFTAG_IMAGELENGTH: case TIFFTAG_IMAGEDEPTH: case TIFFTAG_TILELENGTH: case TIFFTAG_TILEWIDTH: case TIFFTAG_TILEDEPTH: case TIFFTAG_PLANARCONFIG: case TIFFTAG_ROWSPERSTRIP: case TIFFTAG_EXTRASAMPLES: if (!TIFFFetchNormalTag(tif, dp)) goto bad; dp->tdir_tag = IGNORE; break; } } /* * Allocate directory structure and setup defaults. */ if (!TIFFFieldSet(tif, FIELD_IMAGEDIMENSIONS)) { MissingRequired(tif, "ImageLength"); goto bad; } if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG)) { MissingRequired(tif, "PlanarConfiguration"); goto bad; } /* * Setup appropriate structures (by strip or by tile) */ if (!TIFFFieldSet(tif, FIELD_TILEDIMENSIONS)) { td->td_nstrips = TIFFNumberOfStrips(tif); td->td_tilewidth = td->td_imagewidth; td->td_tilelength = td->td_rowsperstrip; td->td_tiledepth = td->td_imagedepth; tif->tif_flags &= ~TIFF_ISTILED; } else { td->td_nstrips = TIFFNumberOfTiles(tif); tif->tif_flags |= TIFF_ISTILED; } if (!td->td_nstrips) { TIFFErrorExt(tif->tif_clientdata, module, "%s: cannot handle zero number of %s", tif->tif_name, isTiled(tif) ? "tiles" : "strips"); goto bad; } td->td_stripsperimage = td->td_nstrips; if (td->td_planarconfig == PLANARCONFIG_SEPARATE) td->td_stripsperimage /= td->td_samplesperpixel; if (!TIFFFieldSet(tif, FIELD_STRIPOFFSETS)) { MissingRequired(tif, isTiled(tif) ? "TileOffsets" : "StripOffsets"); goto bad; } /* * Second pass: extract other information. */ for (dp = dir, n = dircount; n > 0; n--, dp++) { if (dp->tdir_tag == IGNORE) continue; switch (dp->tdir_tag) { case TIFFTAG_MINSAMPLEVALUE: case TIFFTAG_MAXSAMPLEVALUE: case TIFFTAG_BITSPERSAMPLE: case TIFFTAG_DATATYPE: case TIFFTAG_SAMPLEFORMAT: /* * The 5.0 spec says the Compression tag has * one value, while earlier specs say it has * one value per sample. Because of this, we * accept the tag if one value is supplied. * * The MinSampleValue, MaxSampleValue, BitsPerSample * DataType and SampleFormat tags are supposed to be * written as one value/sample, but some vendors * incorrectly write one value only -- so we accept * that as well (yech). Other vendors write correct * value for NumberOfSamples, but incorrect one for * BitsPerSample and friends, and we will read this * too. */ if (dp->tdir_count == 1) { v = TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset); if (!TIFFSetField(tif, dp->tdir_tag, (uint16)v)) goto bad; /* XXX: workaround for broken TIFFs */ } else if (dp->tdir_tag == TIFFTAG_BITSPERSAMPLE && dp->tdir_type == TIFF_LONG) { if (!TIFFFetchPerSampleLongs(tif, dp, &v) || !TIFFSetField(tif, dp->tdir_tag, (uint16)v)) goto bad; } else { if (!TIFFFetchPerSampleShorts(tif, dp, &iv) || !TIFFSetField(tif, dp->tdir_tag, iv)) goto bad; } break; case TIFFTAG_SMINSAMPLEVALUE: case TIFFTAG_SMAXSAMPLEVALUE: { double dv = 0.0; if (!TIFFFetchPerSampleAnys(tif, dp, &dv) || !TIFFSetField(tif, dp->tdir_tag, dv)) goto bad; } break; case TIFFTAG_STRIPOFFSETS: case TIFFTAG_TILEOFFSETS: if (!TIFFFetchStripThing(tif, dp, td->td_nstrips, &td->td_stripoffset)) goto bad; break; case TIFFTAG_STRIPBYTECOUNTS: case TIFFTAG_TILEBYTECOUNTS: if (!TIFFFetchStripThing(tif, dp, td->td_nstrips, &td->td_stripbytecount)) goto bad; break; case TIFFTAG_COLORMAP: case TIFFTAG_TRANSFERFUNCTION: /* * TransferFunction can have either 1x or 3x data * values; Colormap can have only 3x items. */ v = 1L<<td->td_bitspersample; if (dp->tdir_tag == TIFFTAG_COLORMAP || dp->tdir_count != v) { if (!CheckDirCount(tif, dp, 3 * v)) break; } v *= sizeof(uint16); cp = _TIFFCheckMalloc(tif, dp->tdir_count, sizeof (uint16), "to read \"TransferFunction\" tag"); if (cp != NULL) { if (TIFFFetchData(tif, dp, cp)) { /* * This deals with there being only * one array to apply to all samples. */ uint32 c = 1L << td->td_bitspersample; if (dp->tdir_count == c) v = 0L; TIFFSetField(tif, dp->tdir_tag, cp, cp+v, cp+2*v); } _TIFFfree(cp); } break; case TIFFTAG_PAGENUMBER: case TIFFTAG_HALFTONEHINTS: case TIFFTAG_YCBCRSUBSAMPLING: case TIFFTAG_DOTRANGE: (void) TIFFFetchShortPair(tif, dp); break; case TIFFTAG_REFERENCEBLACKWHITE: (void) TIFFFetchRefBlackWhite(tif, dp); break; /* BEGIN REV 4.0 COMPATIBILITY */ case TIFFTAG_OSUBFILETYPE: v = 0L; switch (TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset)) { case OFILETYPE_REDUCEDIMAGE: v = FILETYPE_REDUCEDIMAGE; break; case OFILETYPE_PAGE: v = FILETYPE_PAGE; break; } if (v) TIFFSetField(tif, TIFFTAG_SUBFILETYPE, v); break; /* END REV 4.0 COMPATIBILITY */ default: (void) TIFFFetchNormalTag(tif, dp); break; } } /* * Verify Palette image has a Colormap. */ if (td->td_photometric == PHOTOMETRIC_PALETTE && !TIFFFieldSet(tif, FIELD_COLORMAP)) { MissingRequired(tif, "Colormap"); goto bad; } /* * Attempt to deal with a missing StripByteCounts tag. */ if (!TIFFFieldSet(tif, FIELD_STRIPBYTECOUNTS)) { /* * Some manufacturers violate the spec by not giving * the size of the strips. In this case, assume there * is one uncompressed strip of data. */ if ((td->td_planarconfig == PLANARCONFIG_CONTIG && td->td_nstrips > 1) || (td->td_planarconfig == PLANARCONFIG_SEPARATE && td->td_nstrips != td->td_samplesperpixel)) { MissingRequired(tif, "StripByteCounts"); goto bad; } TIFFWarning(module, "%s: TIFF directory is missing required " "\"%s\" field, calculating from imagelength", tif->tif_name, _TIFFFieldWithTag(tif,TIFFTAG_STRIPBYTECOUNTS)->field_name); if (EstimateStripByteCounts(tif, dir, dircount) < 0) goto bad; /* * Assume we have wrong StripByteCount value (in case of single strip) in * following cases: * - it is equal to zero along with StripOffset; * - it is larger than file itself (in case of uncompressed image); * - it is smaller than the size of the bytes per row multiplied on the * number of rows. The last case should not be checked in the case of * writing new image, because we may do not know the exact strip size * until the whole image will be written and directory dumped out. */ #define BYTECOUNTLOOKSBAD \ ( (td->td_stripbytecount[0] == 0 && td->td_stripoffset[0] != 0) || \ (td->td_compression == COMPRESSION_NONE && \ td->td_stripbytecount[0] > TIFFGetFileSize(tif) - td->td_stripoffset[0]) || \ (tif->tif_mode == O_RDONLY && \ td->td_compression == COMPRESSION_NONE && \ td->td_stripbytecount[0] < TIFFScanlineSize(tif) * td->td_imagelength) ) } else if (td->td_nstrips == 1 && td->td_stripoffset[0] != 0 && BYTECOUNTLOOKSBAD) { /* * XXX: Plexus (and others) sometimes give a value of zero for * a tag when they don't know what the correct value is! Try * and handle the simple case of estimating the size of a one * strip image. */ TIFFWarning(module, "%s: Bogus \"%s\" field, ignoring and calculating from imagelength", tif->tif_name, _TIFFFieldWithTag(tif,TIFFTAG_STRIPBYTECOUNTS)->field_name); if(EstimateStripByteCounts(tif, dir, dircount) < 0) goto bad; } else if (td->td_nstrips > 1 && td->td_compression == COMPRESSION_NONE && td->td_stripbytecount[0] != td->td_stripbytecount[1]) { /* * XXX: Some vendors fill StripByteCount array with absolutely * wrong values (it can be equal to StripOffset array, for * example). Catch this case here. */ TIFFWarning(module, "%s: Wrong \"%s\" field, ignoring and calculating from imagelength", tif->tif_name, _TIFFFieldWithTag(tif,TIFFTAG_STRIPBYTECOUNTS)->field_name); if (EstimateStripByteCounts(tif, dir, dircount) < 0) goto bad; } if (dir) { _TIFFfree((char *)dir); dir = NULL; } if (!TIFFFieldSet(tif, FIELD_MAXSAMPLEVALUE)) td->td_maxsamplevalue = (uint16)((1L<<td->td_bitspersample)-1); /* * Setup default compression scheme. */ /* * XXX: We can optimize checking for the strip bounds using the sorted * bytecounts array. See also comments for TIFFAppendToStrip() * function in tif_write.c. */ if (td->td_nstrips > 1) { tstrip_t strip; td->td_stripbytecountsorted = 1; for (strip = 1; strip < td->td_nstrips; strip++) { if (td->td_stripoffset[strip - 1] > td->td_stripoffset[strip]) { td->td_stripbytecountsorted = 0; break; } } } if (!TIFFFieldSet(tif, FIELD_COMPRESSION)) TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE); /* * Some manufacturers make life difficult by writing * large amounts of uncompressed data as a single strip. * This is contrary to the recommendations of the spec. * The following makes an attempt at breaking such images * into strips closer to the recommended 8k bytes. A * side effect, however, is that the RowsPerStrip tag * value may be changed. */ if (td->td_nstrips == 1 && td->td_compression == COMPRESSION_NONE && (tif->tif_flags & (TIFF_STRIPCHOP|TIFF_ISTILED)) == TIFF_STRIPCHOP) ChopUpSingleUncompressedStrip(tif); /* * Reinitialize i/o since we are starting on a new directory. */ tif->tif_row = (uint32) -1; tif->tif_curstrip = (tstrip_t) -1; tif->tif_col = (uint32) -1; tif->tif_curtile = (ttile_t) -1; tif->tif_tilesize = (tsize_t) -1; tif->tif_scanlinesize = TIFFScanlineSize(tif); if (!tif->tif_scanlinesize) { TIFFErrorExt(tif->tif_clientdata, module, "%s: cannot handle zero scanline size", tif->tif_name); return (0); } if (isTiled(tif)) { tif->tif_tilesize = TIFFTileSize(tif); if (!tif->tif_tilesize) { TIFFErrorExt(tif->tif_clientdata, module, "%s: cannot handle zero tile size", tif->tif_name); return (0); } } else { if (!TIFFStripSize(tif)) { TIFFErrorExt(tif->tif_clientdata, module, "%s: cannot handle zero strip size", tif->tif_name); return (0); } } return (1); bad: if (dir) _TIFFfree(dir); return (0); } /* * Read custom directory from the arbitarry offset. * The code is very similar to TIFFReadDirectory(). */ int TIFFReadCustomDirectory(TIFF* tif, toff_t diroff, const TIFFFieldInfo info[], size_t n) { static const char module[] = "TIFFReadCustomDirectory"; TIFFDirectory* td = &tif->tif_dir; TIFFDirEntry *dp, *dir = NULL; const TIFFFieldInfo* fip; size_t fix; uint16 i, dircount; _TIFFSetupFieldInfo(tif, info, n); tif->tif_diroff = diroff; if (!isMapped(tif)) { if (!SeekOK(tif, diroff)) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Seek error accessing TIFF directory", tif->tif_name); return (0); } if (!ReadOK(tif, &dircount, sizeof (uint16))) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Can not read TIFF directory count", tif->tif_name); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); dir = (TIFFDirEntry *)_TIFFCheckMalloc(tif, dircount, sizeof (TIFFDirEntry), "to read TIFF directory"); if (dir == NULL) return (0); if (!ReadOK(tif, dir, dircount * sizeof (TIFFDirEntry))) { TIFFErrorExt(tif->tif_clientdata, module, "%.100s: Can not read TIFF directory", tif->tif_name); goto bad; } } else { toff_t off = diroff; if (off + sizeof (uint16) > tif->tif_size) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Can not read TIFF directory count", tif->tif_name); return (0); } else _TIFFmemcpy(&dircount, tif->tif_base + off, sizeof (uint16)); off += sizeof (uint16); if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); dir = (TIFFDirEntry *)_TIFFCheckMalloc(tif, dircount, sizeof (TIFFDirEntry), "to read TIFF directory"); if (dir == NULL) return (0); if (off + dircount * sizeof (TIFFDirEntry) > tif->tif_size) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Can not read TIFF directory", tif->tif_name); goto bad; } else { _TIFFmemcpy(dir, tif->tif_base + off, dircount * sizeof (TIFFDirEntry)); } } TIFFFreeDirectory(tif); fix = 0; for (dp = dir, i = dircount; i > 0; i--, dp++) { if (tif->tif_flags & TIFF_SWAB) { TIFFSwabArrayOfShort(&dp->tdir_tag, 2); TIFFSwabArrayOfLong(&dp->tdir_count, 2); } if (fix >= tif->tif_nfields || dp->tdir_tag == IGNORE) continue; while (fix < tif->tif_nfields && tif->tif_fieldinfo[fix]->field_tag < dp->tdir_tag) fix++; if (fix >= tif->tif_nfields || tif->tif_fieldinfo[fix]->field_tag != dp->tdir_tag) { TIFFWarning(module, "%s: unknown field with tag %d (0x%x) encountered", tif->tif_name, dp->tdir_tag, dp->tdir_tag, dp->tdir_type); TIFFMergeFieldInfo(tif, _TIFFCreateAnonFieldInfo(tif, dp->tdir_tag, (TIFFDataType)dp->tdir_type), 1); fix = 0; while (fix < tif->tif_nfields && tif->tif_fieldinfo[fix]->field_tag < dp->tdir_tag) fix++; } /* * Null out old tags that we ignore. */ if (tif->tif_fieldinfo[fix]->field_bit == FIELD_IGNORE) { ignore: dp->tdir_tag = IGNORE; continue; } /* * Check data type. */ fip = tif->tif_fieldinfo[fix]; while (dp->tdir_type != (unsigned short) fip->field_type && fix < tif->tif_nfields) { if (fip->field_type == TIFF_ANY) /* wildcard */ break; fip = tif->tif_fieldinfo[++fix]; if (fix >= tif->tif_nfields || fip->field_tag != dp->tdir_tag) { TIFFWarning(module, "%s: wrong data type %d for \"%s\"; tag ignored", tif->tif_name, dp->tdir_type, tif->tif_fieldinfo[fix-1]->field_name); goto ignore; } } /* * Check count if known in advance. */ if (fip->field_readcount != TIFF_VARIABLE && fip->field_readcount != TIFF_VARIABLE2) { uint32 expected = (fip->field_readcount == TIFF_SPP) ? (uint32) td->td_samplesperpixel : (uint32) fip->field_readcount; if (!CheckDirCount(tif, dp, expected)) goto ignore; } (void) TIFFFetchNormalTag(tif, dp); } if (dir) _TIFFfree(dir); return 1; bad: if (dir) _TIFFfree(dir); return 0; } /* * EXIF is important special case of custom IFD, so we have a special * function to read it. */ int TIFFReadEXIFDirectory(TIFF* tif, toff_t diroff) { return TIFFReadCustomDirectory(tif, diroff, exifFieldInfo, TIFFArrayCount(exifFieldInfo)); } static int EstimateStripByteCounts(TIFF* tif, TIFFDirEntry* dir, uint16 dircount) { static const char module[] = "EstimateStripByteCounts"; register TIFFDirEntry *dp; register TIFFDirectory *td = &tif->tif_dir; uint16 i; if (td->td_stripbytecount) _TIFFfree(td->td_stripbytecount); td->td_stripbytecount = (uint32*) _TIFFCheckMalloc(tif, td->td_nstrips, sizeof (uint32), "for \"StripByteCounts\" array"); if (td->td_compression != COMPRESSION_NONE) { uint32 space = (uint32)(sizeof (TIFFHeader) + sizeof (uint16) + (dircount * sizeof (TIFFDirEntry)) + sizeof (uint32)); toff_t filesize = TIFFGetFileSize(tif); uint16 n; /* calculate amount of space used by indirect values */ for (dp = dir, n = dircount; n > 0; n--, dp++) { uint32 cc = TIFFDataWidth((TIFFDataType) dp->tdir_type); if (cc == 0) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Cannot determine size of unknown tag type %d", tif->tif_name, dp->tdir_type); return -1; } cc = cc * dp->tdir_count; if (cc > sizeof (uint32)) space += cc; } space = filesize - space; if (td->td_planarconfig == PLANARCONFIG_SEPARATE) space /= td->td_samplesperpixel; for (i = 0; i < td->td_nstrips; i++) td->td_stripbytecount[i] = space; /* * This gross hack handles the case were the offset to * the last strip is past the place where we think the strip * should begin. Since a strip of data must be contiguous, * it's safe to assume that we've overestimated the amount * of data in the strip and trim this number back accordingly. */ i--; if (((toff_t)(td->td_stripoffset[i]+td->td_stripbytecount[i])) > filesize) td->td_stripbytecount[i] = filesize - td->td_stripoffset[i]; } else { uint32 rowbytes = TIFFScanlineSize(tif); uint32 rowsperstrip = td->td_imagelength/td->td_stripsperimage; for (i = 0; i < td->td_nstrips; i++) td->td_stripbytecount[i] = rowbytes*rowsperstrip; } TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS); if (!TIFFFieldSet(tif, FIELD_ROWSPERSTRIP)) td->td_rowsperstrip = td->td_imagelength; return 1; } static void MissingRequired(TIFF* tif, const char* tagname) { static const char module[] = "MissingRequired"; TIFFErrorExt(tif->tif_clientdata, module, "%s: TIFF directory is missing required \"%s\" field", tif->tif_name, tagname); } /* * Check the count field of a directory * entry against a known value. The caller * is expected to skip/ignore the tag if * there is a mismatch. */ static int CheckDirCount(TIFF* tif, TIFFDirEntry* dir, uint32 count) { if (count > dir->tdir_count) { TIFFWarning(tif->tif_name, "incorrect count for field \"%s\" (%lu, expecting %lu); tag ignored", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name, dir->tdir_count, count); return (0); } else if (count < dir->tdir_count) { TIFFWarning(tif->tif_name, "incorrect count for field \"%s\" (%lu, expecting %lu); tag trimmed", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name, dir->tdir_count, count); return (1); } return (1); } /* * Fetch a contiguous directory item. */ static tsize_t TIFFFetchData(TIFF* tif, TIFFDirEntry* dir, char* cp) { int w = TIFFDataWidth((TIFFDataType) dir->tdir_type); tsize_t cc = dir->tdir_count * w; if (!isMapped(tif)) { if (!SeekOK(tif, dir->tdir_offset)) goto bad; if (!ReadOK(tif, cp, cc)) goto bad; } else { if (dir->tdir_offset + cc > tif->tif_size) goto bad; _TIFFmemcpy(cp, tif->tif_base + dir->tdir_offset, cc); } if (tif->tif_flags & TIFF_SWAB) { switch (dir->tdir_type) { case TIFF_SHORT: case TIFF_SSHORT: TIFFSwabArrayOfShort((uint16*) cp, dir->tdir_count); break; case TIFF_LONG: case TIFF_SLONG: case TIFF_FLOAT: TIFFSwabArrayOfLong((uint32*) cp, dir->tdir_count); break; case TIFF_RATIONAL: case TIFF_SRATIONAL: TIFFSwabArrayOfLong((uint32*) cp, 2*dir->tdir_count); break; case TIFF_DOUBLE: TIFFSwabArrayOfDouble((double*) cp, dir->tdir_count); break; } } return (cc); bad: TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error fetching data for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); return ((tsize_t) 0); } /* * Fetch an ASCII item from the file. */ static tsize_t TIFFFetchString(TIFF* tif, TIFFDirEntry* dir, char* cp) { if (dir->tdir_count <= 4) { uint32 l = dir->tdir_offset; if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong(&l); _TIFFmemcpy(cp, &l, dir->tdir_count); return (1); } return (TIFFFetchData(tif, dir, cp)); } /* * Convert numerator+denominator to float. */ static int cvtRational(TIFF* tif, TIFFDirEntry* dir, uint32 num, uint32 denom, float* rv) { if (denom == 0) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "%s: Rational with zero denominator (num = %lu)", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name, num); return (0); } else { if (dir->tdir_type == TIFF_RATIONAL) *rv = ((float)num / (float)denom); else *rv = ((float)(int32)num / (float)(int32)denom); return (1); } } /* * Fetch a rational item from the file * at offset off and return the value * as a floating point number. */ static float TIFFFetchRational(TIFF* tif, TIFFDirEntry* dir) { uint32 l[2]; float v; return (!TIFFFetchData(tif, dir, (char *)l) || !cvtRational(tif, dir, l[0], l[1], &v) ? 1.0f : v); } /* * Fetch a single floating point value * from the offset field and return it * as a native float. */ static float TIFFFetchFloat(TIFF* tif, TIFFDirEntry* dir) { float v; int32 l = TIFFExtractData(tif, dir->tdir_type, dir->tdir_offset); _TIFFmemcpy(&v, &l, sizeof(float)); TIFFCvtIEEEFloatToNative(tif, 1, &v); return (v); } /* * Fetch an array of BYTE or SBYTE values. */ static int TIFFFetchByteArray(TIFF* tif, TIFFDirEntry* dir, uint8* v) { if (dir->tdir_count <= 4) { /* * Extract data from offset field. */ if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) { if (dir->tdir_type == TIFF_SBYTE) switch (dir->tdir_count) { case 4: v[3] = dir->tdir_offset & 0xff; case 3: v[2] = (dir->tdir_offset >> 8) & 0xff; case 2: v[1] = (dir->tdir_offset >> 16) & 0xff; case 1: v[0] = dir->tdir_offset >> 24; } else switch (dir->tdir_count) { case 4: v[3] = dir->tdir_offset & 0xff; case 3: v[2] = (dir->tdir_offset >> 8) & 0xff; case 2: v[1] = (dir->tdir_offset >> 16) & 0xff; case 1: v[0] = dir->tdir_offset >> 24; } } else { if (dir->tdir_type == TIFF_SBYTE) switch (dir->tdir_count) { case 4: v[3] = dir->tdir_offset >> 24; case 3: v[2] = (dir->tdir_offset >> 16) & 0xff; case 2: v[1] = (dir->tdir_offset >> 8) & 0xff; case 1: v[0] = dir->tdir_offset & 0xff; } else switch (dir->tdir_count) { case 4: v[3] = dir->tdir_offset >> 24; case 3: v[2] = (dir->tdir_offset >> 16) & 0xff; case 2: v[1] = (dir->tdir_offset >> 8) & 0xff; case 1: v[0] = dir->tdir_offset & 0xff; } } return (1); } else return (TIFFFetchData(tif, dir, (char*) v) != 0); /* XXX */ } /* * Fetch an array of SHORT or SSHORT values. */ static int TIFFFetchShortArray(TIFF* tif, TIFFDirEntry* dir, uint16* v) { if (dir->tdir_count <= 2) { if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) { switch (dir->tdir_count) { case 2: v[1] = (uint16) (dir->tdir_offset & 0xffff); case 1: v[0] = (uint16) (dir->tdir_offset >> 16); } } else { switch (dir->tdir_count) { case 2: v[1] = (uint16) (dir->tdir_offset >> 16); case 1: v[0] = (uint16) (dir->tdir_offset & 0xffff); } } return (1); } else return (TIFFFetchData(tif, dir, (char *)v) != 0); } /* * Fetch a pair of SHORT or BYTE values. Some tags may have either BYTE * or SHORT type and this function works with both ones. */ static int TIFFFetchShortPair(TIFF* tif, TIFFDirEntry* dir) { switch (dir->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: { uint8 v[4]; return TIFFFetchByteArray(tif, dir, v) && TIFFSetField(tif, dir->tdir_tag, v[0], v[1]); } case TIFF_SHORT: case TIFF_SSHORT: { uint16 v[4]; return TIFFFetchShortArray(tif, dir, v) && TIFFSetField(tif, dir->tdir_tag, v[0], v[1]); } default: return 0; } } /* * Fetch an array of LONG or SLONG values. */ static int TIFFFetchLongArray(TIFF* tif, TIFFDirEntry* dir, uint32* v) { if (dir->tdir_count == 1) { v[0] = dir->tdir_offset; return (1); } else return (TIFFFetchData(tif, dir, (char*) v) != 0); } /* * Fetch an array of RATIONAL or SRATIONAL values. */ static int TIFFFetchRationalArray(TIFF* tif, TIFFDirEntry* dir, float* v) { int ok = 0; uint32* l; l = (uint32*)_TIFFCheckMalloc(tif, dir->tdir_count, TIFFDataWidth((TIFFDataType) dir->tdir_type), "to fetch array of rationals"); if (l) { if (TIFFFetchData(tif, dir, (char *)l)) { uint32 i; for (i = 0; i < dir->tdir_count; i++) { ok = cvtRational(tif, dir, l[2*i+0], l[2*i+1], &v[i]); if (!ok) break; } } _TIFFfree((char *)l); } return (ok); } /* * Fetch an array of FLOAT values. */ static int TIFFFetchFloatArray(TIFF* tif, TIFFDirEntry* dir, float* v) { if (dir->tdir_count == 1) { v[0] = *(float*) &dir->tdir_offset; TIFFCvtIEEEFloatToNative(tif, dir->tdir_count, v); return (1); } else if (TIFFFetchData(tif, dir, (char*) v)) { TIFFCvtIEEEFloatToNative(tif, dir->tdir_count, v); return (1); } else return (0); } /* * Fetch an array of DOUBLE values. */ static int TIFFFetchDoubleArray(TIFF* tif, TIFFDirEntry* dir, double* v) { if (TIFFFetchData(tif, dir, (char*) v)) { TIFFCvtIEEEDoubleToNative(tif, dir->tdir_count, v); return (1); } else return (0); } /* * Fetch an array of ANY values. The actual values are * returned as doubles which should be able hold all the * types. Yes, there really should be an tany_t to avoid * this potential non-portability ... Note in particular * that we assume that the double return value vector is * large enough to read in any fundamental type. We use * that vector as a buffer to read in the base type vector * and then convert it in place to double (from end * to front of course). */ static int TIFFFetchAnyArray(TIFF* tif, TIFFDirEntry* dir, double* v) { int i; switch (dir->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: if (!TIFFFetchByteArray(tif, dir, (uint8*) v)) return (0); if (dir->tdir_type == TIFF_BYTE) { uint8* vp = (uint8*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } else { int8* vp = (int8*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_SHORT: case TIFF_SSHORT: if (!TIFFFetchShortArray(tif, dir, (uint16*) v)) return (0); if (dir->tdir_type == TIFF_SHORT) { uint16* vp = (uint16*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } else { int16* vp = (int16*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_LONG: case TIFF_SLONG: if (!TIFFFetchLongArray(tif, dir, (uint32*) v)) return (0); if (dir->tdir_type == TIFF_LONG) { uint32* vp = (uint32*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } else { int32* vp = (int32*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_RATIONAL: case TIFF_SRATIONAL: if (!TIFFFetchRationalArray(tif, dir, (float*) v)) return (0); { float* vp = (float*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_FLOAT: if (!TIFFFetchFloatArray(tif, dir, (float*) v)) return (0); { float* vp = (float*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_DOUBLE: return (TIFFFetchDoubleArray(tif, dir, (double*) v)); default: /* TIFF_NOTYPE */ /* TIFF_ASCII */ /* TIFF_UNDEFINED */ TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "cannot read TIFF_ANY type %d for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); return (0); } return (1); } /* * Fetch a tag that is not handled by special case code. */ static int TIFFFetchNormalTag(TIFF* tif, TIFFDirEntry* dp) { static const char mesg[] = "to fetch tag value"; int ok = 0; const TIFFFieldInfo* fip = _TIFFFieldWithTag(tif, dp->tdir_tag); if (dp->tdir_count > 1) { /* array of values */ char* cp = NULL; switch (dp->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: cp = _TIFFCheckMalloc(tif, dp->tdir_count, sizeof (uint8), mesg); ok = cp && TIFFFetchByteArray(tif, dp, (uint8*) cp); break; case TIFF_SHORT: case TIFF_SSHORT: cp = _TIFFCheckMalloc(tif, dp->tdir_count, sizeof (uint16), mesg); ok = cp && TIFFFetchShortArray(tif, dp, (uint16*) cp); break; case TIFF_LONG: case TIFF_SLONG: cp = _TIFFCheckMalloc(tif, dp->tdir_count, sizeof (uint32), mesg); ok = cp && TIFFFetchLongArray(tif, dp, (uint32*) cp); break; case TIFF_RATIONAL: case TIFF_SRATIONAL: cp = _TIFFCheckMalloc(tif, dp->tdir_count, sizeof (float), mesg); ok = cp && TIFFFetchRationalArray(tif, dp, (float*) cp); break; case TIFF_FLOAT: cp = _TIFFCheckMalloc(tif, dp->tdir_count, sizeof (float), mesg); ok = cp && TIFFFetchFloatArray(tif, dp, (float*) cp); break; case TIFF_DOUBLE: cp = _TIFFCheckMalloc(tif, dp->tdir_count, sizeof (double), mesg); ok = cp && TIFFFetchDoubleArray(tif, dp, (double*) cp); break; case TIFF_ASCII: case TIFF_UNDEFINED: /* bit of a cheat... */ /* * Some vendors write strings w/o the trailing * NULL byte, so always append one just in case. */ cp = _TIFFCheckMalloc(tif, dp->tdir_count+1, 1, mesg); if( (ok = (cp && TIFFFetchString(tif, dp, cp))) != 0 ) cp[dp->tdir_count] = '\0'; /* XXX */ break; } if (ok) { ok = (fip->field_passcount ? TIFFSetField(tif, dp->tdir_tag, dp->tdir_count, cp) : TIFFSetField(tif, dp->tdir_tag, cp)); } if (cp != NULL) _TIFFfree(cp); } else if (CheckDirCount(tif, dp, 1)) { /* singleton value */ switch (dp->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: case TIFF_SHORT: case TIFF_SSHORT: /* * If the tag is also acceptable as a LONG or SLONG * then TIFFSetField will expect an uint32 parameter * passed to it (through varargs). Thus, for machines * where sizeof (int) != sizeof (uint32) we must do * a careful check here. It's hard to say if this * is worth optimizing. * * NB: We use TIFFFieldWithTag here knowing that * it returns us the first entry in the table * for the tag and that that entry is for the * widest potential data type the tag may have. */ { TIFFDataType type = fip->field_type; if (type != TIFF_LONG && type != TIFF_SLONG) { uint16 v = (uint16) TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset); ok = (fip->field_passcount ? TIFFSetField(tif, dp->tdir_tag, 1, &v) : TIFFSetField(tif, dp->tdir_tag, v)); break; } } /* fall thru... */ case TIFF_LONG: case TIFF_SLONG: { uint32 v32 = TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset); ok = (fip->field_passcount ? TIFFSetField(tif, dp->tdir_tag, 1, &v32) : TIFFSetField(tif, dp->tdir_tag, v32)); } break; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: { float v = (dp->tdir_type == TIFF_FLOAT ? TIFFFetchFloat(tif, dp) : TIFFFetchRational(tif, dp)); ok = (fip->field_passcount ? TIFFSetField(tif, dp->tdir_tag, 1, &v) : TIFFSetField(tif, dp->tdir_tag, v)); } break; case TIFF_DOUBLE: { double v; ok = (TIFFFetchDoubleArray(tif, dp, &v) && (fip->field_passcount ? TIFFSetField(tif, dp->tdir_tag, 1, &v) : TIFFSetField(tif, dp->tdir_tag, v)) ); } break; case TIFF_ASCII: case TIFF_UNDEFINED: /* bit of a cheat... */ { char c[2]; if( (ok = (TIFFFetchString(tif, dp, c) != 0)) != 0 ) { c[1] = '\0'; /* XXX paranoid */ ok = (fip->field_passcount ? TIFFSetField(tif, dp->tdir_tag, 1, c) : TIFFSetField(tif, dp->tdir_tag, c)); } } break; } } return (ok); } #define NITEMS(x) (sizeof (x) / sizeof (x[0])) /* * Fetch samples/pixel short values for * the specified tag and verify that * all values are the same. */ static int TIFFFetchPerSampleShorts(TIFF* tif, TIFFDirEntry* dir, uint16* pl) { uint16 samples = tif->tif_dir.td_samplesperpixel; int status = 0; if (CheckDirCount(tif, dir, (uint32) samples)) { uint16 buf[10]; uint16* v = buf; if (dir->tdir_count > NITEMS(buf)) v = (uint16*) _TIFFCheckMalloc(tif, dir->tdir_count, sizeof(uint16), "to fetch per-sample values"); if (v && TIFFFetchShortArray(tif, dir, v)) { uint16 i; int check_count = dir->tdir_count; if( samples < check_count ) check_count = samples; for (i = 1; i < check_count; i++) if (v[i] != v[0]) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Cannot handle different per-sample values for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); goto bad; } *pl = v[0]; status = 1; } bad: if (v && v != buf) _TIFFfree(v); } return (status); } /* * Fetch samples/pixel long values for * the specified tag and verify that * all values are the same. */ static int TIFFFetchPerSampleLongs(TIFF* tif, TIFFDirEntry* dir, uint32* pl) { uint16 samples = tif->tif_dir.td_samplesperpixel; int status = 0; if (CheckDirCount(tif, dir, (uint32) samples)) { uint32 buf[10]; uint32* v = buf; if (dir->tdir_count > NITEMS(buf)) v = (uint32*) _TIFFCheckMalloc(tif, dir->tdir_count, sizeof(uint32), "to fetch per-sample values"); if (v && TIFFFetchLongArray(tif, dir, v)) { uint16 i; int check_count = dir->tdir_count; if( samples < check_count ) check_count = samples; for (i = 1; i < check_count; i++) if (v[i] != v[0]) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Cannot handle different per-sample values for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); goto bad; } *pl = v[0]; status = 1; } bad: if (v && v != buf) _TIFFfree(v); } return (status); } /* * Fetch samples/pixel ANY values for the specified tag and verify that all * values are the same. */ static int TIFFFetchPerSampleAnys(TIFF* tif, TIFFDirEntry* dir, double* pl) { uint16 samples = tif->tif_dir.td_samplesperpixel; int status = 0; if (CheckDirCount(tif, dir, (uint32) samples)) { double buf[10]; double* v = buf; if (dir->tdir_count > NITEMS(buf)) v = (double*) _TIFFCheckMalloc(tif, dir->tdir_count, sizeof (double), "to fetch per-sample values"); if (v && TIFFFetchAnyArray(tif, dir, v)) { uint16 i; int check_count = dir->tdir_count; if( samples < check_count ) check_count = samples; for (i = 1; i < check_count; i++) if (v[i] != v[0]) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Cannot handle different per-sample values for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); goto bad; } *pl = v[0]; status = 1; } bad: if (v && v != buf) _TIFFfree(v); } return (status); } #undef NITEMS /* * Fetch a set of offsets or lengths. * While this routine says "strips", in fact it's also used for tiles. */ static int TIFFFetchStripThing(TIFF* tif, TIFFDirEntry* dir, long nstrips, uint32** lpp) { register uint32* lp; int status; CheckDirCount(tif, dir, (uint32) nstrips); /* * Allocate space for strip information. */ if (*lpp == NULL && (*lpp = (uint32 *)_TIFFCheckMalloc(tif, nstrips, sizeof (uint32), "for strip array")) == NULL) return (0); lp = *lpp; _TIFFmemset( lp, 0, sizeof(uint32) * nstrips ); if (dir->tdir_type == (int)TIFF_SHORT) { /* * Handle uint16->uint32 expansion. */ uint16* dp = (uint16*) _TIFFCheckMalloc(tif, dir->tdir_count, sizeof (uint16), "to fetch strip tag"); if (dp == NULL) return (0); if( (status = TIFFFetchShortArray(tif, dir, dp)) != 0 ) { int i; for( i = 0; i < nstrips && i < (int) dir->tdir_count; i++ ) { lp[i] = dp[i]; } } _TIFFfree((char*) dp); } else if( nstrips != (int) dir->tdir_count ) { /* Special case to correct length */ uint32* dp = (uint32*) _TIFFCheckMalloc(tif, dir->tdir_count, sizeof (uint32), "to fetch strip tag"); if (dp == NULL) return (0); status = TIFFFetchLongArray(tif, dir, dp); if( status != 0 ) { int i; for( i = 0; i < nstrips && i < (int) dir->tdir_count; i++ ) { lp[i] = dp[i]; } } _TIFFfree( (char *) dp ); } else status = TIFFFetchLongArray(tif, dir, lp); return (status); } /* * Fetch and set the RefBlackWhite tag. */ static int TIFFFetchRefBlackWhite(TIFF* tif, TIFFDirEntry* dir) { static const char mesg[] = "for \"ReferenceBlackWhite\" array"; char* cp; int ok; if (dir->tdir_type == TIFF_RATIONAL) return (TIFFFetchNormalTag(tif, dir)); /* * Handle LONG's for backward compatibility. */ cp = _TIFFCheckMalloc(tif, dir->tdir_count, sizeof (uint32), mesg); if( (ok = (cp && TIFFFetchLongArray(tif, dir, (uint32*) cp))) != 0) { float* fp = (float*) _TIFFCheckMalloc(tif, dir->tdir_count, sizeof (float), mesg); if( (ok = (fp != NULL)) != 0 ) { uint32 i; for (i = 0; i < dir->tdir_count; i++) fp[i] = (float)((uint32*) cp)[i]; ok = TIFFSetField(tif, dir->tdir_tag, fp); _TIFFfree((char*) fp); } } if (cp) _TIFFfree(cp); return (ok); } /* * Replace a single strip (tile) of uncompressed data by * multiple strips (tiles), each approximately 8Kbytes. * This is useful for dealing with large images or * for dealing with machines with a limited amount * memory. */ static void ChopUpSingleUncompressedStrip(TIFF* tif) { register TIFFDirectory *td = &tif->tif_dir; uint32 bytecount = td->td_stripbytecount[0]; uint32 offset = td->td_stripoffset[0]; tsize_t rowbytes = TIFFVTileSize(tif, 1), stripbytes; tstrip_t strip, nstrips, rowsperstrip; uint32* newcounts; uint32* newoffsets; /* * Make the rows hold at least one scanline, but fill specified amount * of data if possible. */ #ifndef STRIP_SIZE_DEFAULT # define STRIP_SIZE_DEFAULT 8192 #endif if (rowbytes > STRIP_SIZE_DEFAULT) { stripbytes = rowbytes; rowsperstrip = 1; } else if (rowbytes > 0 ) { rowsperstrip = STRIP_SIZE_DEFAULT / rowbytes; stripbytes = rowbytes * rowsperstrip; } else return; #undef STRIP_SIZE_DEFAULT /* * never increase the number of strips in an image */ if (rowsperstrip >= td->td_rowsperstrip) return; nstrips = (tstrip_t) TIFFhowmany(bytecount, stripbytes); if( nstrips == 0 ) /* something is wonky, do nothing. */ return; newcounts = (uint32*) _TIFFCheckMalloc(tif, nstrips, sizeof (uint32), "for chopped \"StripByteCounts\" array"); newoffsets = (uint32*) _TIFFCheckMalloc(tif, nstrips, sizeof (uint32), "for chopped \"StripOffsets\" array"); if (newcounts == NULL || newoffsets == NULL) { /* * Unable to allocate new strip information, give * up and use the original one strip information. */ if (newcounts != NULL) _TIFFfree(newcounts); if (newoffsets != NULL) _TIFFfree(newoffsets); return; } /* * Fill the strip information arrays with new bytecounts and offsets * that reflect the broken-up format. */ for (strip = 0; strip < nstrips; strip++) { if (stripbytes > (tsize_t) bytecount) stripbytes = bytecount; newcounts[strip] = stripbytes; newoffsets[strip] = offset; offset += stripbytes; bytecount -= stripbytes; } /* * Replace old single strip info with multi-strip info. */ td->td_stripsperimage = td->td_nstrips = nstrips; TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, rowsperstrip); _TIFFfree(td->td_stripbytecount); _TIFFfree(td->td_stripoffset); td->td_stripbytecount = newcounts; td->td_stripoffset = newoffsets; td->td_stripbytecountsorted = 1; } /* vim: set ts=8 sts=8 sw=8 noet: */ /* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library. * * Directory Read Support Routines. */ #include "tiffiop.h" #define IGNORE 0 /* tag placeholder used below */ #ifdef HAVE_IEEEFP # define TIFFCvtIEEEFloatToNative(tif, n, fp) # define TIFFCvtIEEEDoubleToNative(tif, n, dp) #else extern void TIFFCvtIEEEFloatToNative(TIFF*, uint32, float*); extern void TIFFCvtIEEEDoubleToNative(TIFF*, uint32, double*); #endif static int EstimateStripByteCounts(TIFF*, TIFFDirEntry*, uint16); static void MissingRequired(TIFF*, const char*); static int CheckDirCount(TIFF*, TIFFDirEntry*, uint32); static tsize_t TIFFFetchData(TIFF*, TIFFDirEntry*, char*); static tsize_t TIFFFetchString(TIFF*, TIFFDirEntry*, char*); static float TIFFFetchRational(TIFF*, TIFFDirEntry*); static int TIFFFetchNormalTag(TIFF*, TIFFDirEntry*); static int TIFFFetchPerSampleShorts(TIFF*, TIFFDirEntry*, uint16*); static int TIFFFetchPerSampleLongs(TIFF*, TIFFDirEntry*, uint32*); static int TIFFFetchPerSampleAnys(TIFF*, TIFFDirEntry*, double*); static int TIFFFetchShortArray(TIFF*, TIFFDirEntry*, uint16*); static int TIFFFetchStripThing(TIFF*, TIFFDirEntry*, long, uint32**); static int TIFFFetchRefBlackWhite(TIFF*, TIFFDirEntry*); static float TIFFFetchFloat(TIFF*, TIFFDirEntry*); static int TIFFFetchFloatArray(TIFF*, TIFFDirEntry*, float*); static int TIFFFetchDoubleArray(TIFF*, TIFFDirEntry*, double*); static int TIFFFetchAnyArray(TIFF*, TIFFDirEntry*, double*); static int TIFFFetchShortPair(TIFF*, TIFFDirEntry*); static void ChopUpSingleUncompressedStrip(TIFF*); /* * Read the next TIFF directory from a file * and convert it to the internal format. * We read directories sequentially. */ int TIFFReadDirectory(TIFF* tif) { static const char module[] = "TIFFReadDirectory"; int n; TIFFDirectory* td; TIFFDirEntry *dp, *dir = NULL; uint16 iv; uint32 v; const TIFFFieldInfo* fip; size_t fix; uint16 dircount; toff_t nextdiroff; char* cp; int diroutoforderwarning = 0; toff_t* new_dirlist; tif->tif_diroff = tif->tif_nextdiroff; if (tif->tif_diroff == 0) /* no more directories */ return (0); /* * XXX: Trick to prevent IFD looping. The one can create TIFF file * with looped directory pointers. We will maintain a list of already * seen directories and check every IFD offset against this list. */ for (n = 0; n < tif->tif_dirnumber; n++) { if (tif->tif_dirlist[n] == tif->tif_diroff) return (0); } tif->tif_dirnumber++; new_dirlist = _TIFFrealloc(tif->tif_dirlist, tif->tif_dirnumber * sizeof(toff_t)); if (!new_dirlist) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Failed to allocate space for IFD list", tif->tif_name); return (0); } tif->tif_dirlist = new_dirlist; tif->tif_dirlist[tif->tif_dirnumber - 1] = tif->tif_diroff; /* * Cleanup any previous compression state. */ (*tif->tif_cleanup)(tif); tif->tif_curdir++; nextdiroff = 0; if (!isMapped(tif)) { if (!SeekOK(tif, tif->tif_diroff)) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Seek error accessing TIFF directory", tif->tif_name); return (0); } if (!ReadOK(tif, &dircount, sizeof (uint16))) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Can not read TIFF directory count", tif->tif_name); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); dir = (TIFFDirEntry *)_TIFFCheckMalloc(tif, dircount, sizeof (TIFFDirEntry), "to read TIFF directory"); if (dir == NULL) return (0); if (!ReadOK(tif, dir, dircount*sizeof (TIFFDirEntry))) { TIFFErrorExt(tif->tif_clientdata, module, "%.100s: Can not read TIFF directory", tif->tif_name); goto bad; } /* * Read offset to next directory for sequential scans. */ (void) ReadOK(tif, &nextdiroff, sizeof (uint32)); } else { toff_t off = tif->tif_diroff; if (off + sizeof (uint16) > tif->tif_size) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Can not read TIFF directory count", tif->tif_name); return (0); } else _TIFFmemcpy(&dircount, tif->tif_base + off, sizeof (uint16)); off += sizeof (uint16); if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); dir = (TIFFDirEntry *)_TIFFCheckMalloc(tif, dircount, sizeof (TIFFDirEntry), "to read TIFF directory"); if (dir == NULL) return (0); if (off + dircount*sizeof (TIFFDirEntry) > tif->tif_size) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Can not read TIFF directory", tif->tif_name); goto bad; } else { _TIFFmemcpy(dir, tif->tif_base + off, dircount*sizeof (TIFFDirEntry)); } off += dircount* sizeof (TIFFDirEntry); if (off + sizeof (uint32) <= tif->tif_size) _TIFFmemcpy(&nextdiroff, tif->tif_base+off, sizeof (uint32)); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong(&nextdiroff); tif->tif_nextdiroff = nextdiroff; tif->tif_flags &= ~TIFF_BEENWRITING; /* reset before new dir */ /* * Setup default value and then make a pass over * the fields to check type and tag information, * and to extract info required to size data * structures. A second pass is made afterwards * to read in everthing not taken in the first pass. */ td = &tif->tif_dir; /* free any old stuff and reinit */ TIFFFreeDirectory(tif); TIFFDefaultDirectory(tif); /* * Electronic Arts writes gray-scale TIFF files * without a PlanarConfiguration directory entry. * Thus we setup a default value here, even though * the TIFF spec says there is no default value. */ TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); /* * Sigh, we must make a separate pass through the * directory for the following reason: * * We must process the Compression tag in the first pass * in order to merge in codec-private tag definitions (otherwise * we may get complaints about unknown tags). However, the * Compression tag may be dependent on the SamplesPerPixel * tag value because older TIFF specs permited Compression * to be written as a SamplesPerPixel-count tag entry. * Thus if we don't first figure out the correct SamplesPerPixel * tag value then we may end up ignoring the Compression tag * value because it has an incorrect count value (if the * true value of SamplesPerPixel is not 1). * * It sure would have been nice if Aldus had really thought * this stuff through carefully. */ for (dp = dir, n = dircount; n > 0; n--, dp++) { if (tif->tif_flags & TIFF_SWAB) { TIFFSwabArrayOfShort(&dp->tdir_tag, 2); TIFFSwabArrayOfLong(&dp->tdir_count, 2); } if (dp->tdir_tag == TIFFTAG_SAMPLESPERPIXEL) { if (!TIFFFetchNormalTag(tif, dp)) goto bad; dp->tdir_tag = IGNORE; } } /* * First real pass over the directory. */ fix = 0; for (dp = dir, n = dircount; n > 0; n--, dp++) { if (fix >= tif->tif_nfields || dp->tdir_tag == IGNORE) continue; /* * Silicon Beach (at least) writes unordered * directory tags (violating the spec). Handle * it here, but be obnoxious (maybe they'll fix it?). */ if (dp->tdir_tag < tif->tif_fieldinfo[fix]->field_tag) { if (!diroutoforderwarning) { TIFFWarning(module, "%s: invalid TIFF directory; tags are not sorted in ascending order", tif->tif_name); diroutoforderwarning = 1; } fix = 0; /* O(n^2) */ } while (fix < tif->tif_nfields && tif->tif_fieldinfo[fix]->field_tag < dp->tdir_tag) fix++; if (fix >= tif->tif_nfields || tif->tif_fieldinfo[fix]->field_tag != dp->tdir_tag) { TIFFWarning(module, "%s: unknown field with tag %d (0x%x) encountered", tif->tif_name, dp->tdir_tag, dp->tdir_tag, dp->tdir_type); TIFFMergeFieldInfo( tif, _TIFFCreateAnonFieldInfo( tif, dp->tdir_tag, (TIFFDataType) dp->tdir_type ), 1 ); fix = 0; while (fix < tif->tif_nfields && tif->tif_fieldinfo[fix]->field_tag < dp->tdir_tag) fix++; } /* * Null out old tags that we ignore. */ if (tif->tif_fieldinfo[fix]->field_bit == FIELD_IGNORE) { ignore: dp->tdir_tag = IGNORE; continue; } /* * Check data type. */ fip = tif->tif_fieldinfo[fix]; while (dp->tdir_type != (unsigned short) fip->field_type && fix < tif->tif_nfields) { if (fip->field_type == TIFF_ANY) /* wildcard */ break; fip = tif->tif_fieldinfo[++fix]; if (fix >= tif->tif_nfields || fip->field_tag != dp->tdir_tag) { TIFFWarning(module, "%s: wrong data type %d for \"%s\"; tag ignored", tif->tif_name, dp->tdir_type, tif->tif_fieldinfo[fix-1]->field_name); goto ignore; } } /* * Check count if known in advance. */ if (fip->field_readcount != TIFF_VARIABLE && fip->field_readcount != TIFF_VARIABLE2) { uint32 expected = (fip->field_readcount == TIFF_SPP) ? (uint32) td->td_samplesperpixel : (uint32) fip->field_readcount; if (!CheckDirCount(tif, dp, expected)) goto ignore; } switch (dp->tdir_tag) { case TIFFTAG_COMPRESSION: /* * The 5.0 spec says the Compression tag has * one value, while earlier specs say it has * one value per sample. Because of this, we * accept the tag if one value is supplied. */ if (dp->tdir_count == 1) { v = TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset); if (!TIFFSetField(tif, dp->tdir_tag, (uint16)v)) goto bad; break; /* XXX: workaround for broken TIFFs */ } else if (dp->tdir_type == TIFF_LONG) { if (!TIFFFetchPerSampleLongs(tif, dp, &v) || !TIFFSetField(tif, dp->tdir_tag, (uint16)v)) goto bad; } else { if (!TIFFFetchPerSampleShorts(tif, dp, &iv) || !TIFFSetField(tif, dp->tdir_tag, iv)) goto bad; } dp->tdir_tag = IGNORE; break; case TIFFTAG_STRIPOFFSETS: case TIFFTAG_STRIPBYTECOUNTS: case TIFFTAG_TILEOFFSETS: case TIFFTAG_TILEBYTECOUNTS: TIFFSetFieldBit(tif, fip->field_bit); break; case TIFFTAG_IMAGEWIDTH: case TIFFTAG_IMAGELENGTH: case TIFFTAG_IMAGEDEPTH: case TIFFTAG_TILELENGTH: case TIFFTAG_TILEWIDTH: case TIFFTAG_TILEDEPTH: case TIFFTAG_PLANARCONFIG: case TIFFTAG_ROWSPERSTRIP: case TIFFTAG_EXTRASAMPLES: if (!TIFFFetchNormalTag(tif, dp)) goto bad; dp->tdir_tag = IGNORE; break; } } /* * Allocate directory structure and setup defaults. */ if (!TIFFFieldSet(tif, FIELD_IMAGEDIMENSIONS)) { MissingRequired(tif, "ImageLength"); goto bad; } if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG)) { MissingRequired(tif, "PlanarConfiguration"); goto bad; } /* * Setup appropriate structures (by strip or by tile) */ if (!TIFFFieldSet(tif, FIELD_TILEDIMENSIONS)) { td->td_nstrips = TIFFNumberOfStrips(tif); td->td_tilewidth = td->td_imagewidth; td->td_tilelength = td->td_rowsperstrip; td->td_tiledepth = td->td_imagedepth; tif->tif_flags &= ~TIFF_ISTILED; } else { td->td_nstrips = TIFFNumberOfTiles(tif); tif->tif_flags |= TIFF_ISTILED; } if (!td->td_nstrips) { TIFFErrorExt(tif->tif_clientdata, module, "%s: cannot handle zero number of %s", tif->tif_name, isTiled(tif) ? "tiles" : "strips"); goto bad; } td->td_stripsperimage = td->td_nstrips; if (td->td_planarconfig == PLANARCONFIG_SEPARATE) td->td_stripsperimage /= td->td_samplesperpixel; if (!TIFFFieldSet(tif, FIELD_STRIPOFFSETS)) { MissingRequired(tif, isTiled(tif) ? "TileOffsets" : "StripOffsets"); goto bad; } /* * Second pass: extract other information. */ for (dp = dir, n = dircount; n > 0; n--, dp++) { if (dp->tdir_tag == IGNORE) continue; switch (dp->tdir_tag) { case TIFFTAG_MINSAMPLEVALUE: case TIFFTAG_MAXSAMPLEVALUE: case TIFFTAG_BITSPERSAMPLE: case TIFFTAG_DATATYPE: case TIFFTAG_SAMPLEFORMAT: /* * The 5.0 spec says the Compression tag has * one value, while earlier specs say it has * one value per sample. Because of this, we * accept the tag if one value is supplied. * * The MinSampleValue, MaxSampleValue, BitsPerSample * DataType and SampleFormat tags are supposed to be * written as one value/sample, but some vendors * incorrectly write one value only -- so we accept * that as well (yech). Other vendors write correct * value for NumberOfSamples, but incorrect one for * BitsPerSample and friends, and we will read this * too. */ if (dp->tdir_count == 1) { v = TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset); if (!TIFFSetField(tif, dp->tdir_tag, (uint16)v)) goto bad; /* XXX: workaround for broken TIFFs */ } else if (dp->tdir_tag == TIFFTAG_BITSPERSAMPLE && dp->tdir_type == TIFF_LONG) { if (!TIFFFetchPerSampleLongs(tif, dp, &v) || !TIFFSetField(tif, dp->tdir_tag, (uint16)v)) goto bad; } else { if (!TIFFFetchPerSampleShorts(tif, dp, &iv) || !TIFFSetField(tif, dp->tdir_tag, iv)) goto bad; } break; case TIFFTAG_SMINSAMPLEVALUE: case TIFFTAG_SMAXSAMPLEVALUE: { double dv = 0.0; if (!TIFFFetchPerSampleAnys(tif, dp, &dv) || !TIFFSetField(tif, dp->tdir_tag, dv)) goto bad; } break; case TIFFTAG_STRIPOFFSETS: case TIFFTAG_TILEOFFSETS: if (!TIFFFetchStripThing(tif, dp, td->td_nstrips, &td->td_stripoffset)) goto bad; break; case TIFFTAG_STRIPBYTECOUNTS: case TIFFTAG_TILEBYTECOUNTS: if (!TIFFFetchStripThing(tif, dp, td->td_nstrips, &td->td_stripbytecount)) goto bad; break; case TIFFTAG_COLORMAP: case TIFFTAG_TRANSFERFUNCTION: /* * TransferFunction can have either 1x or 3x data * values; Colormap can have only 3x items. */ v = 1L<<td->td_bitspersample; if (dp->tdir_tag == TIFFTAG_COLORMAP || dp->tdir_count != v) { if (!CheckDirCount(tif, dp, 3 * v)) break; } v *= sizeof(uint16); cp = _TIFFCheckMalloc(tif, dp->tdir_count, sizeof (uint16), "to read \"TransferFunction\" tag"); if (cp != NULL) { if (TIFFFetchData(tif, dp, cp)) { /* * This deals with there being only * one array to apply to all samples. */ uint32 c = 1L << td->td_bitspersample; if (dp->tdir_count == c) v = 0L; TIFFSetField(tif, dp->tdir_tag, cp, cp+v, cp+2*v); } _TIFFfree(cp); } break; case TIFFTAG_PAGENUMBER: case TIFFTAG_HALFTONEHINTS: case TIFFTAG_YCBCRSUBSAMPLING: case TIFFTAG_DOTRANGE: (void) TIFFFetchShortPair(tif, dp); break; case TIFFTAG_REFERENCEBLACKWHITE: (void) TIFFFetchRefBlackWhite(tif, dp); break; /* BEGIN REV 4.0 COMPATIBILITY */ case TIFFTAG_OSUBFILETYPE: v = 0L; switch (TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset)) { case OFILETYPE_REDUCEDIMAGE: v = FILETYPE_REDUCEDIMAGE; break; case OFILETYPE_PAGE: v = FILETYPE_PAGE; break; } if (v) TIFFSetField(tif, TIFFTAG_SUBFILETYPE, v); break; /* END REV 4.0 COMPATIBILITY */ default: (void) TIFFFetchNormalTag(tif, dp); break; } } /* * Verify Palette image has a Colormap. */ if (td->td_photometric == PHOTOMETRIC_PALETTE && !TIFFFieldSet(tif, FIELD_COLORMAP)) { MissingRequired(tif, "Colormap"); goto bad; } /* * Attempt to deal with a missing StripByteCounts tag. */ if (!TIFFFieldSet(tif, FIELD_STRIPBYTECOUNTS)) { /* * Some manufacturers violate the spec by not giving * the size of the strips. In this case, assume there * is one uncompressed strip of data. */ if ((td->td_planarconfig == PLANARCONFIG_CONTIG && td->td_nstrips > 1) || (td->td_planarconfig == PLANARCONFIG_SEPARATE && td->td_nstrips != td->td_samplesperpixel)) { MissingRequired(tif, "StripByteCounts"); goto bad; } TIFFWarning(module, "%s: TIFF directory is missing required " "\"%s\" field, calculating from imagelength", tif->tif_name, _TIFFFieldWithTag(tif,TIFFTAG_STRIPBYTECOUNTS)->field_name); if (EstimateStripByteCounts(tif, dir, dircount) < 0) goto bad; /* * Assume we have wrong StripByteCount value (in case of single strip) in * following cases: * - it is equal to zero along with StripOffset; * - it is larger than file itself (in case of uncompressed image); * - it is smaller than the size of the bytes per row multiplied on the * number of rows. The last case should not be checked in the case of * writing new image, because we may do not know the exact strip size * until the whole image will be written and directory dumped out. */ #define BYTECOUNTLOOKSBAD \ ( (td->td_stripbytecount[0] == 0 && td->td_stripoffset[0] != 0) || \ (td->td_compression == COMPRESSION_NONE && \ td->td_stripbytecount[0] > TIFFGetFileSize(tif) - td->td_stripoffset[0]) || \ (tif->tif_mode == O_RDONLY && \ td->td_compression == COMPRESSION_NONE && \ td->td_stripbytecount[0] < TIFFScanlineSize(tif) * td->td_imagelength) ) } else if (td->td_nstrips == 1 && td->td_stripoffset[0] != 0 && BYTECOUNTLOOKSBAD) { /* * XXX: Plexus (and others) sometimes give a value of zero for * a tag when they don't know what the correct value is! Try * and handle the simple case of estimating the size of a one * strip image. */ TIFFWarning(module, "%s: Bogus \"%s\" field, ignoring and calculating from imagelength", tif->tif_name, _TIFFFieldWithTag(tif,TIFFTAG_STRIPBYTECOUNTS)->field_name); if(EstimateStripByteCounts(tif, dir, dircount) < 0) goto bad; } else if (td->td_nstrips > 2 && td->td_compression == COMPRESSION_NONE && td->td_stripbytecount[0] != td->td_stripbytecount[1]) { /* * XXX: Some vendors fill StripByteCount array with absolutely * wrong values (it can be equal to StripOffset array, for * example). Catch this case here. */ TIFFWarning(module, "%s: Wrong \"%s\" field, ignoring and calculating from imagelength", tif->tif_name, _TIFFFieldWithTag(tif,TIFFTAG_STRIPBYTECOUNTS)->field_name); if (EstimateStripByteCounts(tif, dir, dircount) < 0) goto bad; } if (dir) { _TIFFfree((char *)dir); dir = NULL; } if (!TIFFFieldSet(tif, FIELD_MAXSAMPLEVALUE)) td->td_maxsamplevalue = (uint16)((1L<<td->td_bitspersample)-1); /* * Setup default compression scheme. */ /* * XXX: We can optimize checking for the strip bounds using the sorted * bytecounts array. See also comments for TIFFAppendToStrip() * function in tif_write.c. */ if (td->td_nstrips > 1) { tstrip_t strip; td->td_stripbytecountsorted = 1; for (strip = 1; strip < td->td_nstrips; strip++) { if (td->td_stripoffset[strip - 1] > td->td_stripoffset[strip]) { td->td_stripbytecountsorted = 0; break; } } } if (!TIFFFieldSet(tif, FIELD_COMPRESSION)) TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE); /* * Some manufacturers make life difficult by writing * large amounts of uncompressed data as a single strip. * This is contrary to the recommendations of the spec. * The following makes an attempt at breaking such images * into strips closer to the recommended 8k bytes. A * side effect, however, is that the RowsPerStrip tag * value may be changed. */ if (td->td_nstrips == 1 && td->td_compression == COMPRESSION_NONE && (tif->tif_flags & (TIFF_STRIPCHOP|TIFF_ISTILED)) == TIFF_STRIPCHOP) ChopUpSingleUncompressedStrip(tif); /* * Reinitialize i/o since we are starting on a new directory. */ tif->tif_row = (uint32) -1; tif->tif_curstrip = (tstrip_t) -1; tif->tif_col = (uint32) -1; tif->tif_curtile = (ttile_t) -1; tif->tif_tilesize = (tsize_t) -1; tif->tif_scanlinesize = TIFFScanlineSize(tif); if (!tif->tif_scanlinesize) { TIFFErrorExt(tif->tif_clientdata, module, "%s: cannot handle zero scanline size", tif->tif_name); return (0); } if (isTiled(tif)) { tif->tif_tilesize = TIFFTileSize(tif); if (!tif->tif_tilesize) { TIFFErrorExt(tif->tif_clientdata, module, "%s: cannot handle zero tile size", tif->tif_name); return (0); } } else { if (!TIFFStripSize(tif)) { TIFFErrorExt(tif->tif_clientdata, module, "%s: cannot handle zero strip size", tif->tif_name); return (0); } } return (1); bad: if (dir) _TIFFfree(dir); return (0); } /* * Read custom directory from the arbitarry offset. * The code is very similar to TIFFReadDirectory(). */ int TIFFReadCustomDirectory(TIFF* tif, toff_t diroff, const TIFFFieldInfo info[], size_t n) { static const char module[] = "TIFFReadCustomDirectory"; TIFFDirectory* td = &tif->tif_dir; TIFFDirEntry *dp, *dir = NULL; const TIFFFieldInfo* fip; size_t fix; uint16 i, dircount; _TIFFSetupFieldInfo(tif, info, n); tif->tif_diroff = diroff; if (!isMapped(tif)) { if (!SeekOK(tif, diroff)) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Seek error accessing TIFF directory", tif->tif_name); return (0); } if (!ReadOK(tif, &dircount, sizeof (uint16))) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Can not read TIFF directory count", tif->tif_name); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); dir = (TIFFDirEntry *)_TIFFCheckMalloc(tif, dircount, sizeof (TIFFDirEntry), "to read TIFF directory"); if (dir == NULL) return (0); if (!ReadOK(tif, dir, dircount * sizeof (TIFFDirEntry))) { TIFFErrorExt(tif->tif_clientdata, module, "%.100s: Can not read TIFF directory", tif->tif_name); goto bad; } } else { toff_t off = diroff; if (off + sizeof (uint16) > tif->tif_size) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Can not read TIFF directory count", tif->tif_name); return (0); } else _TIFFmemcpy(&dircount, tif->tif_base + off, sizeof (uint16)); off += sizeof (uint16); if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); dir = (TIFFDirEntry *)_TIFFCheckMalloc(tif, dircount, sizeof (TIFFDirEntry), "to read TIFF directory"); if (dir == NULL) return (0); if (off + dircount * sizeof (TIFFDirEntry) > tif->tif_size) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Can not read TIFF directory", tif->tif_name); goto bad; } else { _TIFFmemcpy(dir, tif->tif_base + off, dircount * sizeof (TIFFDirEntry)); } } TIFFFreeDirectory(tif); fix = 0; for (dp = dir, i = dircount; i > 0; i--, dp++) { if (tif->tif_flags & TIFF_SWAB) { TIFFSwabArrayOfShort(&dp->tdir_tag, 2); TIFFSwabArrayOfLong(&dp->tdir_count, 2); } if (fix >= tif->tif_nfields || dp->tdir_tag == IGNORE) continue; while (fix < tif->tif_nfields && tif->tif_fieldinfo[fix]->field_tag < dp->tdir_tag) fix++; if (fix >= tif->tif_nfields || tif->tif_fieldinfo[fix]->field_tag != dp->tdir_tag) { TIFFWarning(module, "%s: unknown field with tag %d (0x%x) encountered", tif->tif_name, dp->tdir_tag, dp->tdir_tag, dp->tdir_type); TIFFMergeFieldInfo(tif, _TIFFCreateAnonFieldInfo(tif, dp->tdir_tag, (TIFFDataType)dp->tdir_type), 1); fix = 0; while (fix < tif->tif_nfields && tif->tif_fieldinfo[fix]->field_tag < dp->tdir_tag) fix++; } /* * Null out old tags that we ignore. */ if (tif->tif_fieldinfo[fix]->field_bit == FIELD_IGNORE) { ignore: dp->tdir_tag = IGNORE; continue; } /* * Check data type. */ fip = tif->tif_fieldinfo[fix]; while (dp->tdir_type != (unsigned short) fip->field_type && fix < tif->tif_nfields) { if (fip->field_type == TIFF_ANY) /* wildcard */ break; fip = tif->tif_fieldinfo[++fix]; if (fix >= tif->tif_nfields || fip->field_tag != dp->tdir_tag) { TIFFWarning(module, "%s: wrong data type %d for \"%s\"; tag ignored", tif->tif_name, dp->tdir_type, tif->tif_fieldinfo[fix-1]->field_name); goto ignore; } } /* * Check count if known in advance. */ if (fip->field_readcount != TIFF_VARIABLE && fip->field_readcount != TIFF_VARIABLE2) { uint32 expected = (fip->field_readcount == TIFF_SPP) ? (uint32) td->td_samplesperpixel : (uint32) fip->field_readcount; if (!CheckDirCount(tif, dp, expected)) goto ignore; } (void) TIFFFetchNormalTag(tif, dp); } if (dir) _TIFFfree(dir); return 1; bad: if (dir) _TIFFfree(dir); return 0; } /* * EXIF is important special case of custom IFD, so we have a special * function to read it. */ int TIFFReadEXIFDirectory(TIFF* tif, toff_t diroff) { return TIFFReadCustomDirectory(tif, diroff, exifFieldInfo, TIFFArrayCount(exifFieldInfo)); } static int EstimateStripByteCounts(TIFF* tif, TIFFDirEntry* dir, uint16 dircount) { static const char module[] = "EstimateStripByteCounts"; register TIFFDirEntry *dp; register TIFFDirectory *td = &tif->tif_dir; uint16 i; if (td->td_stripbytecount) _TIFFfree(td->td_stripbytecount); td->td_stripbytecount = (uint32*) _TIFFCheckMalloc(tif, td->td_nstrips, sizeof (uint32), "for \"StripByteCounts\" array"); if (td->td_compression != COMPRESSION_NONE) { uint32 space = (uint32)(sizeof (TIFFHeader) + sizeof (uint16) + (dircount * sizeof (TIFFDirEntry)) + sizeof (uint32)); toff_t filesize = TIFFGetFileSize(tif); uint16 n; /* calculate amount of space used by indirect values */ for (dp = dir, n = dircount; n > 0; n--, dp++) { uint32 cc = TIFFDataWidth((TIFFDataType) dp->tdir_type); if (cc == 0) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Cannot determine size of unknown tag type %d", tif->tif_name, dp->tdir_type); return -1; } cc = cc * dp->tdir_count; if (cc > sizeof (uint32)) space += cc; } space = filesize - space; if (td->td_planarconfig == PLANARCONFIG_SEPARATE) space /= td->td_samplesperpixel; for (i = 0; i < td->td_nstrips; i++) td->td_stripbytecount[i] = space; /* * This gross hack handles the case were the offset to * the last strip is past the place where we think the strip * should begin. Since a strip of data must be contiguous, * it's safe to assume that we've overestimated the amount * of data in the strip and trim this number back accordingly. */ i--; if (((toff_t)(td->td_stripoffset[i]+td->td_stripbytecount[i])) > filesize) td->td_stripbytecount[i] = filesize - td->td_stripoffset[i]; } else { uint32 rowbytes = TIFFScanlineSize(tif); uint32 rowsperstrip = td->td_imagelength/td->td_stripsperimage; for (i = 0; i < td->td_nstrips; i++) td->td_stripbytecount[i] = rowbytes*rowsperstrip; } TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS); if (!TIFFFieldSet(tif, FIELD_ROWSPERSTRIP)) td->td_rowsperstrip = td->td_imagelength; return 1; } static void MissingRequired(TIFF* tif, const char* tagname) { static const char module[] = "MissingRequired"; TIFFErrorExt(tif->tif_clientdata, module, "%s: TIFF directory is missing required \"%s\" field", tif->tif_name, tagname); } /* * Check the count field of a directory * entry against a known value. The caller * is expected to skip/ignore the tag if * there is a mismatch. */ static int CheckDirCount(TIFF* tif, TIFFDirEntry* dir, uint32 count) { if (count > dir->tdir_count) { TIFFWarning(tif->tif_name, "incorrect count for field \"%s\" (%lu, expecting %lu); tag ignored", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name, dir->tdir_count, count); return (0); } else if (count < dir->tdir_count) { TIFFWarning(tif->tif_name, "incorrect count for field \"%s\" (%lu, expecting %lu); tag trimmed", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name, dir->tdir_count, count); return (1); } return (1); } /* * Fetch a contiguous directory item. */ static tsize_t TIFFFetchData(TIFF* tif, TIFFDirEntry* dir, char* cp) { int w = TIFFDataWidth((TIFFDataType) dir->tdir_type); tsize_t cc = dir->tdir_count * w; if (!isMapped(tif)) { if (!SeekOK(tif, dir->tdir_offset)) goto bad; if (!ReadOK(tif, cp, cc)) goto bad; } else { if (dir->tdir_offset + cc > tif->tif_size) goto bad; _TIFFmemcpy(cp, tif->tif_base + dir->tdir_offset, cc); } if (tif->tif_flags & TIFF_SWAB) { switch (dir->tdir_type) { case TIFF_SHORT: case TIFF_SSHORT: TIFFSwabArrayOfShort((uint16*) cp, dir->tdir_count); break; case TIFF_LONG: case TIFF_SLONG: case TIFF_FLOAT: TIFFSwabArrayOfLong((uint32*) cp, dir->tdir_count); break; case TIFF_RATIONAL: case TIFF_SRATIONAL: TIFFSwabArrayOfLong((uint32*) cp, 2*dir->tdir_count); break; case TIFF_DOUBLE: TIFFSwabArrayOfDouble((double*) cp, dir->tdir_count); break; } } return (cc); bad: TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error fetching data for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); return ((tsize_t) 0); } /* * Fetch an ASCII item from the file. */ static tsize_t TIFFFetchString(TIFF* tif, TIFFDirEntry* dir, char* cp) { if (dir->tdir_count <= 4) { uint32 l = dir->tdir_offset; if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong(&l); _TIFFmemcpy(cp, &l, dir->tdir_count); return (1); } return (TIFFFetchData(tif, dir, cp)); } /* * Convert numerator+denominator to float. */ static int cvtRational(TIFF* tif, TIFFDirEntry* dir, uint32 num, uint32 denom, float* rv) { if (denom == 0) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "%s: Rational with zero denominator (num = %lu)", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name, num); return (0); } else { if (dir->tdir_type == TIFF_RATIONAL) *rv = ((float)num / (float)denom); else *rv = ((float)(int32)num / (float)(int32)denom); return (1); } } /* * Fetch a rational item from the file * at offset off and return the value * as a floating point number. */ static float TIFFFetchRational(TIFF* tif, TIFFDirEntry* dir) { uint32 l[2]; float v; return (!TIFFFetchData(tif, dir, (char *)l) || !cvtRational(tif, dir, l[0], l[1], &v) ? 1.0f : v); } /* * Fetch a single floating point value * from the offset field and return it * as a native float. */ static float TIFFFetchFloat(TIFF* tif, TIFFDirEntry* dir) { float v; int32 l = TIFFExtractData(tif, dir->tdir_type, dir->tdir_offset); _TIFFmemcpy(&v, &l, sizeof(float)); TIFFCvtIEEEFloatToNative(tif, 1, &v); return (v); } /* * Fetch an array of BYTE or SBYTE values. */ static int TIFFFetchByteArray(TIFF* tif, TIFFDirEntry* dir, uint8* v) { if (dir->tdir_count <= 4) { /* * Extract data from offset field. */ if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) { if (dir->tdir_type == TIFF_SBYTE) switch (dir->tdir_count) { case 4: v[3] = dir->tdir_offset & 0xff; case 3: v[2] = (dir->tdir_offset >> 8) & 0xff; case 2: v[1] = (dir->tdir_offset >> 16) & 0xff; case 1: v[0] = dir->tdir_offset >> 24; } else switch (dir->tdir_count) { case 4: v[3] = dir->tdir_offset & 0xff; case 3: v[2] = (dir->tdir_offset >> 8) & 0xff; case 2: v[1] = (dir->tdir_offset >> 16) & 0xff; case 1: v[0] = dir->tdir_offset >> 24; } } else { if (dir->tdir_type == TIFF_SBYTE) switch (dir->tdir_count) { case 4: v[3] = dir->tdir_offset >> 24; case 3: v[2] = (dir->tdir_offset >> 16) & 0xff; case 2: v[1] = (dir->tdir_offset >> 8) & 0xff; case 1: v[0] = dir->tdir_offset & 0xff; } else switch (dir->tdir_count) { case 4: v[3] = dir->tdir_offset >> 24; case 3: v[2] = (dir->tdir_offset >> 16) & 0xff; case 2: v[1] = (dir->tdir_offset >> 8) & 0xff; case 1: v[0] = dir->tdir_offset & 0xff; } } return (1); } else return (TIFFFetchData(tif, dir, (char*) v) != 0); /* XXX */ } /* * Fetch an array of SHORT or SSHORT values. */ static int TIFFFetchShortArray(TIFF* tif, TIFFDirEntry* dir, uint16* v) { if (dir->tdir_count <= 2) { if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) { switch (dir->tdir_count) { case 2: v[1] = (uint16) (dir->tdir_offset & 0xffff); case 1: v[0] = (uint16) (dir->tdir_offset >> 16); } } else { switch (dir->tdir_count) { case 2: v[1] = (uint16) (dir->tdir_offset >> 16); case 1: v[0] = (uint16) (dir->tdir_offset & 0xffff); } } return (1); } else return (TIFFFetchData(tif, dir, (char *)v) != 0); } /* * Fetch a pair of SHORT or BYTE values. Some tags may have either BYTE * or SHORT type and this function works with both ones. */ static int TIFFFetchShortPair(TIFF* tif, TIFFDirEntry* dir) { switch (dir->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: { uint8 v[4]; return TIFFFetchByteArray(tif, dir, v) && TIFFSetField(tif, dir->tdir_tag, v[0], v[1]); } case TIFF_SHORT: case TIFF_SSHORT: { uint16 v[4]; return TIFFFetchShortArray(tif, dir, v) && TIFFSetField(tif, dir->tdir_tag, v[0], v[1]); } default: return 0; } } /* * Fetch an array of LONG or SLONG values. */ static int TIFFFetchLongArray(TIFF* tif, TIFFDirEntry* dir, uint32* v) { if (dir->tdir_count == 1) { v[0] = dir->tdir_offset; return (1); } else return (TIFFFetchData(tif, dir, (char*) v) != 0); } /* * Fetch an array of RATIONAL or SRATIONAL values. */ static int TIFFFetchRationalArray(TIFF* tif, TIFFDirEntry* dir, float* v) { int ok = 0; uint32* l; l = (uint32*)_TIFFCheckMalloc(tif, dir->tdir_count, TIFFDataWidth((TIFFDataType) dir->tdir_type), "to fetch array of rationals"); if (l) { if (TIFFFetchData(tif, dir, (char *)l)) { uint32 i; for (i = 0; i < dir->tdir_count; i++) { ok = cvtRational(tif, dir, l[2*i+0], l[2*i+1], &v[i]); if (!ok) break; } } _TIFFfree((char *)l); } return (ok); } /* * Fetch an array of FLOAT values. */ static int TIFFFetchFloatArray(TIFF* tif, TIFFDirEntry* dir, float* v) { if (dir->tdir_count == 1) { v[0] = *(float*) &dir->tdir_offset; TIFFCvtIEEEFloatToNative(tif, dir->tdir_count, v); return (1); } else if (TIFFFetchData(tif, dir, (char*) v)) { TIFFCvtIEEEFloatToNative(tif, dir->tdir_count, v); return (1); } else return (0); } /* * Fetch an array of DOUBLE values. */ static int TIFFFetchDoubleArray(TIFF* tif, TIFFDirEntry* dir, double* v) { if (TIFFFetchData(tif, dir, (char*) v)) { TIFFCvtIEEEDoubleToNative(tif, dir->tdir_count, v); return (1); } else return (0); } /* * Fetch an array of ANY values. The actual values are * returned as doubles which should be able hold all the * types. Yes, there really should be an tany_t to avoid * this potential non-portability ... Note in particular * that we assume that the double return value vector is * large enough to read in any fundamental type. We use * that vector as a buffer to read in the base type vector * and then convert it in place to double (from end * to front of course). */ static int TIFFFetchAnyArray(TIFF* tif, TIFFDirEntry* dir, double* v) { int i; switch (dir->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: if (!TIFFFetchByteArray(tif, dir, (uint8*) v)) return (0); if (dir->tdir_type == TIFF_BYTE) { uint8* vp = (uint8*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } else { int8* vp = (int8*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_SHORT: case TIFF_SSHORT: if (!TIFFFetchShortArray(tif, dir, (uint16*) v)) return (0); if (dir->tdir_type == TIFF_SHORT) { uint16* vp = (uint16*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } else { int16* vp = (int16*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_LONG: case TIFF_SLONG: if (!TIFFFetchLongArray(tif, dir, (uint32*) v)) return (0); if (dir->tdir_type == TIFF_LONG) { uint32* vp = (uint32*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } else { int32* vp = (int32*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_RATIONAL: case TIFF_SRATIONAL: if (!TIFFFetchRationalArray(tif, dir, (float*) v)) return (0); { float* vp = (float*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_FLOAT: if (!TIFFFetchFloatArray(tif, dir, (float*) v)) return (0); { float* vp = (float*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_DOUBLE: return (TIFFFetchDoubleArray(tif, dir, (double*) v)); default: /* TIFF_NOTYPE */ /* TIFF_ASCII */ /* TIFF_UNDEFINED */ TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "cannot read TIFF_ANY type %d for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); return (0); } return (1); } /* * Fetch a tag that is not handled by special case code. */ static int TIFFFetchNormalTag(TIFF* tif, TIFFDirEntry* dp) { static const char mesg[] = "to fetch tag value"; int ok = 0; const TIFFFieldInfo* fip = _TIFFFieldWithTag(tif, dp->tdir_tag); if (dp->tdir_count > 1) { /* array of values */ char* cp = NULL; switch (dp->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: cp = _TIFFCheckMalloc(tif, dp->tdir_count, sizeof (uint8), mesg); ok = cp && TIFFFetchByteArray(tif, dp, (uint8*) cp); break; case TIFF_SHORT: case TIFF_SSHORT: cp = _TIFFCheckMalloc(tif, dp->tdir_count, sizeof (uint16), mesg); ok = cp && TIFFFetchShortArray(tif, dp, (uint16*) cp); break; case TIFF_LONG: case TIFF_SLONG: cp = _TIFFCheckMalloc(tif, dp->tdir_count, sizeof (uint32), mesg); ok = cp && TIFFFetchLongArray(tif, dp, (uint32*) cp); break; case TIFF_RATIONAL: case TIFF_SRATIONAL: cp = _TIFFCheckMalloc(tif, dp->tdir_count, sizeof (float), mesg); ok = cp && TIFFFetchRationalArray(tif, dp, (float*) cp); break; case TIFF_FLOAT: cp = _TIFFCheckMalloc(tif, dp->tdir_count, sizeof (float), mesg); ok = cp && TIFFFetchFloatArray(tif, dp, (float*) cp); break; case TIFF_DOUBLE: cp = _TIFFCheckMalloc(tif, dp->tdir_count, sizeof (double), mesg); ok = cp && TIFFFetchDoubleArray(tif, dp, (double*) cp); break; case TIFF_ASCII: case TIFF_UNDEFINED: /* bit of a cheat... */ /* * Some vendors write strings w/o the trailing * NULL byte, so always append one just in case. */ cp = _TIFFCheckMalloc(tif, dp->tdir_count+1, 1, mesg); if( (ok = (cp && TIFFFetchString(tif, dp, cp))) != 0 ) cp[dp->tdir_count] = '\0'; /* XXX */ break; } if (ok) { ok = (fip->field_passcount ? TIFFSetField(tif, dp->tdir_tag, dp->tdir_count, cp) : TIFFSetField(tif, dp->tdir_tag, cp)); } if (cp != NULL) _TIFFfree(cp); } else if (CheckDirCount(tif, dp, 1)) { /* singleton value */ switch (dp->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: case TIFF_SHORT: case TIFF_SSHORT: /* * If the tag is also acceptable as a LONG or SLONG * then TIFFSetField will expect an uint32 parameter * passed to it (through varargs). Thus, for machines * where sizeof (int) != sizeof (uint32) we must do * a careful check here. It's hard to say if this * is worth optimizing. * * NB: We use TIFFFieldWithTag here knowing that * it returns us the first entry in the table * for the tag and that that entry is for the * widest potential data type the tag may have. */ { TIFFDataType type = fip->field_type; if (type != TIFF_LONG && type != TIFF_SLONG) { uint16 v = (uint16) TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset); ok = (fip->field_passcount ? TIFFSetField(tif, dp->tdir_tag, 1, &v) : TIFFSetField(tif, dp->tdir_tag, v)); break; } } /* fall thru... */ case TIFF_LONG: case TIFF_SLONG: { uint32 v32 = TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset); ok = (fip->field_passcount ? TIFFSetField(tif, dp->tdir_tag, 1, &v32) : TIFFSetField(tif, dp->tdir_tag, v32)); } break; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: { float v = (dp->tdir_type == TIFF_FLOAT ? TIFFFetchFloat(tif, dp) : TIFFFetchRational(tif, dp)); ok = (fip->field_passcount ? TIFFSetField(tif, dp->tdir_tag, 1, &v) : TIFFSetField(tif, dp->tdir_tag, v)); } break; case TIFF_DOUBLE: { double v; ok = (TIFFFetchDoubleArray(tif, dp, &v) && (fip->field_passcount ? TIFFSetField(tif, dp->tdir_tag, 1, &v) : TIFFSetField(tif, dp->tdir_tag, v)) ); } break; case TIFF_ASCII: case TIFF_UNDEFINED: /* bit of a cheat... */ { char c[2]; if( (ok = (TIFFFetchString(tif, dp, c) != 0)) != 0 ) { c[1] = '\0'; /* XXX paranoid */ ok = (fip->field_passcount ? TIFFSetField(tif, dp->tdir_tag, 1, c) : TIFFSetField(tif, dp->tdir_tag, c)); } } break; } } return (ok); } #define NITEMS(x) (sizeof (x) / sizeof (x[0])) /* * Fetch samples/pixel short values for * the specified tag and verify that * all values are the same. */ static int TIFFFetchPerSampleShorts(TIFF* tif, TIFFDirEntry* dir, uint16* pl) { uint16 samples = tif->tif_dir.td_samplesperpixel; int status = 0; if (CheckDirCount(tif, dir, (uint32) samples)) { uint16 buf[10]; uint16* v = buf; if (dir->tdir_count > NITEMS(buf)) v = (uint16*) _TIFFCheckMalloc(tif, dir->tdir_count, sizeof(uint16), "to fetch per-sample values"); if (v && TIFFFetchShortArray(tif, dir, v)) { uint16 i; int check_count = dir->tdir_count; if( samples < check_count ) check_count = samples; for (i = 1; i < check_count; i++) if (v[i] != v[0]) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Cannot handle different per-sample values for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); goto bad; } *pl = v[0]; status = 1; } bad: if (v && v != buf) _TIFFfree(v); } return (status); } /* * Fetch samples/pixel long values for * the specified tag and verify that * all values are the same. */ static int TIFFFetchPerSampleLongs(TIFF* tif, TIFFDirEntry* dir, uint32* pl) { uint16 samples = tif->tif_dir.td_samplesperpixel; int status = 0; if (CheckDirCount(tif, dir, (uint32) samples)) { uint32 buf[10]; uint32* v = buf; if (dir->tdir_count > NITEMS(buf)) v = (uint32*) _TIFFCheckMalloc(tif, dir->tdir_count, sizeof(uint32), "to fetch per-sample values"); if (v && TIFFFetchLongArray(tif, dir, v)) { uint16 i; int check_count = dir->tdir_count; if( samples < check_count ) check_count = samples; for (i = 1; i < check_count; i++) if (v[i] != v[0]) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Cannot handle different per-sample values for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); goto bad; } *pl = v[0]; status = 1; } bad: if (v && v != buf) _TIFFfree(v); } return (status); } /* * Fetch samples/pixel ANY values for the specified tag and verify that all * values are the same. */ static int TIFFFetchPerSampleAnys(TIFF* tif, TIFFDirEntry* dir, double* pl) { uint16 samples = tif->tif_dir.td_samplesperpixel; int status = 0; if (CheckDirCount(tif, dir, (uint32) samples)) { double buf[10]; double* v = buf; if (dir->tdir_count > NITEMS(buf)) v = (double*) _TIFFCheckMalloc(tif, dir->tdir_count, sizeof (double), "to fetch per-sample values"); if (v && TIFFFetchAnyArray(tif, dir, v)) { uint16 i; int check_count = dir->tdir_count; if( samples < check_count ) check_count = samples; for (i = 1; i < check_count; i++) if (v[i] != v[0]) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Cannot handle different per-sample values for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); goto bad; } *pl = v[0]; status = 1; } bad: if (v && v != buf) _TIFFfree(v); } return (status); } #undef NITEMS /* * Fetch a set of offsets or lengths. * While this routine says "strips", in fact it's also used for tiles. */ static int TIFFFetchStripThing(TIFF* tif, TIFFDirEntry* dir, long nstrips, uint32** lpp) { register uint32* lp; int status; CheckDirCount(tif, dir, (uint32) nstrips); /* * Allocate space for strip information. */ if (*lpp == NULL && (*lpp = (uint32 *)_TIFFCheckMalloc(tif, nstrips, sizeof (uint32), "for strip array")) == NULL) return (0); lp = *lpp; _TIFFmemset( lp, 0, sizeof(uint32) * nstrips ); if (dir->tdir_type == (int)TIFF_SHORT) { /* * Handle uint16->uint32 expansion. */ uint16* dp = (uint16*) _TIFFCheckMalloc(tif, dir->tdir_count, sizeof (uint16), "to fetch strip tag"); if (dp == NULL) return (0); if( (status = TIFFFetchShortArray(tif, dir, dp)) != 0 ) { int i; for( i = 0; i < nstrips && i < (int) dir->tdir_count; i++ ) { lp[i] = dp[i]; } } _TIFFfree((char*) dp); } else if( nstrips != (int) dir->tdir_count ) { /* Special case to correct length */ uint32* dp = (uint32*) _TIFFCheckMalloc(tif, dir->tdir_count, sizeof (uint32), "to fetch strip tag"); if (dp == NULL) return (0); status = TIFFFetchLongArray(tif, dir, dp); if( status != 0 ) { int i; for( i = 0; i < nstrips && i < (int) dir->tdir_count; i++ ) { lp[i] = dp[i]; } } _TIFFfree( (char *) dp ); } else status = TIFFFetchLongArray(tif, dir, lp); return (status); } /* * Fetch and set the RefBlackWhite tag. */ static int TIFFFetchRefBlackWhite(TIFF* tif, TIFFDirEntry* dir) { static const char mesg[] = "for \"ReferenceBlackWhite\" array"; char* cp; int ok; if (dir->tdir_type == TIFF_RATIONAL) return (TIFFFetchNormalTag(tif, dir)); /* * Handle LONG's for backward compatibility. */ cp = _TIFFCheckMalloc(tif, dir->tdir_count, sizeof (uint32), mesg); if( (ok = (cp && TIFFFetchLongArray(tif, dir, (uint32*) cp))) != 0) { float* fp = (float*) _TIFFCheckMalloc(tif, dir->tdir_count, sizeof (float), mesg); if( (ok = (fp != NULL)) != 0 ) { uint32 i; for (i = 0; i < dir->tdir_count; i++) fp[i] = (float)((uint32*) cp)[i]; ok = TIFFSetField(tif, dir->tdir_tag, fp); _TIFFfree((char*) fp); } } if (cp) _TIFFfree(cp); return (ok); } /* * Replace a single strip (tile) of uncompressed data by * multiple strips (tiles), each approximately 8Kbytes. * This is useful for dealing with large images or * for dealing with machines with a limited amount * memory. */ static void ChopUpSingleUncompressedStrip(TIFF* tif) { register TIFFDirectory *td = &tif->tif_dir; uint32 bytecount = td->td_stripbytecount[0]; uint32 offset = td->td_stripoffset[0]; tsize_t rowbytes = TIFFVTileSize(tif, 1), stripbytes; tstrip_t strip, nstrips, rowsperstrip; uint32* newcounts; uint32* newoffsets; /* * Make the rows hold at least one scanline, but fill specified amount * of data if possible. */ #ifndef STRIP_SIZE_DEFAULT # define STRIP_SIZE_DEFAULT 8192 #endif if (rowbytes > STRIP_SIZE_DEFAULT) { stripbytes = rowbytes; rowsperstrip = 1; } else if (rowbytes > 0 ) { rowsperstrip = STRIP_SIZE_DEFAULT / rowbytes; stripbytes = rowbytes * rowsperstrip; } else return; #undef STRIP_SIZE_DEFAULT /* * never increase the number of strips in an image */ if (rowsperstrip >= td->td_rowsperstrip) return; nstrips = (tstrip_t) TIFFhowmany(bytecount, stripbytes); if( nstrips == 0 ) /* something is wonky, do nothing. */ return; newcounts = (uint32*) _TIFFCheckMalloc(tif, nstrips, sizeof (uint32), "for chopped \"StripByteCounts\" array"); newoffsets = (uint32*) _TIFFCheckMalloc(tif, nstrips, sizeof (uint32), "for chopped \"StripOffsets\" array"); if (newcounts == NULL || newoffsets == NULL) { /* * Unable to allocate new strip information, give * up and use the original one strip information. */ if (newcounts != NULL) _TIFFfree(newcounts); if (newoffsets != NULL) _TIFFfree(newoffsets); return; } /* * Fill the strip information arrays with new bytecounts and offsets * that reflect the broken-up format. */ for (strip = 0; strip < nstrips; strip++) { if (stripbytes > (tsize_t) bytecount) stripbytes = bytecount; newcounts[strip] = stripbytes; newoffsets[strip] = offset; offset += stripbytes; bytecount -= stripbytes; } /* * Replace old single strip info with multi-strip info. */ td->td_stripsperimage = td->td_nstrips = nstrips; TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, rowsperstrip); _TIFFfree(td->td_stripbytecount); _TIFFfree(td->td_stripoffset); td->td_stripbytecount = newcounts; td->td_stripoffset = newoffsets; td->td_stripbytecountsorted = 1; } /* vim: set ts=8 sts=8 sw=8 noet: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/libtiff_2005-12-21-3b848a7-3edb9cd.c
manybugs_data_2
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Omar Kilani <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" #include "ext/standard/php_smart_str.h" #include "utf8_to_utf16.h" #include "JSON_parser.h" #include "php_json.h" #include <zend_exceptions.h> static PHP_MINFO_FUNCTION(json); static PHP_FUNCTION(json_encode); static PHP_FUNCTION(json_decode); static PHP_FUNCTION(json_last_error); static const char digits[] = "0123456789abcdef"; zend_class_entry *php_json_serializable_ce; ZEND_DECLARE_MODULE_GLOBALS(json) /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_json_encode, 0, 0, 1) ZEND_ARG_INFO(0, value) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_json_decode, 0, 0, 1) ZEND_ARG_INFO(0, json) ZEND_ARG_INFO(0, assoc) ZEND_ARG_INFO(0, depth) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_json_last_error, 0) ZEND_END_ARG_INFO() /* }}} */ /* {{{ json_functions[] */ static const zend_function_entry json_functions[] = { PHP_FE(json_encode, arginfo_json_encode) PHP_FE(json_decode, arginfo_json_decode) PHP_FE(json_last_error, arginfo_json_last_error) PHP_FE_END }; /* }}} */ /* {{{ JsonSerializable methods */ ZEND_BEGIN_ARG_INFO(json_serialize_arginfo, 0) /* No arguments */ ZEND_END_ARG_INFO(); static const zend_function_entry json_serializable_interface[] = { PHP_ABSTRACT_ME(JsonSerializable, jsonSerialize, json_serialize_arginfo) PHP_FE_END }; /* }}} */ /* {{{ MINIT */ static PHP_MINIT_FUNCTION(json) { zend_class_entry ce; INIT_CLASS_ENTRY(ce, "JsonSerializable", json_serializable_interface); php_json_serializable_ce = zend_register_internal_interface(&ce TSRMLS_CC); REGISTER_LONG_CONSTANT("JSON_HEX_TAG", PHP_JSON_HEX_TAG, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_HEX_AMP", PHP_JSON_HEX_AMP, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_HEX_APOS", PHP_JSON_HEX_APOS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_HEX_QUOT", PHP_JSON_HEX_QUOT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_FORCE_OBJECT", PHP_JSON_FORCE_OBJECT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_NUMERIC_CHECK", PHP_JSON_NUMERIC_CHECK, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_UNESCAPED_SLASHES", PHP_JSON_UNESCAPED_SLASHES, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_PRETTY_PRINT", PHP_JSON_PRETTY_PRINT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_UNESCAPED_UNICODE", PHP_JSON_UNESCAPED_UNICODE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_ERROR_NONE", PHP_JSON_ERROR_NONE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_ERROR_DEPTH", PHP_JSON_ERROR_DEPTH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_ERROR_STATE_MISMATCH", PHP_JSON_ERROR_STATE_MISMATCH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_ERROR_CTRL_CHAR", PHP_JSON_ERROR_CTRL_CHAR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_ERROR_SYNTAX", PHP_JSON_ERROR_SYNTAX, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_ERROR_UTF8", PHP_JSON_ERROR_UTF8, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_OBJECT_AS_ARRAY", PHP_JSON_OBJECT_AS_ARRAY, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_BIGINT_AS_STRING", PHP_JSON_BIGINT_AS_STRING, CONST_CS | CONST_PERSISTENT); return SUCCESS; } /* }}} */ /* {{{ PHP_GINIT_FUNCTION */ static PHP_GINIT_FUNCTION(json) { json_globals->encoder_depth = 0; json_globals->error_code = 0; } /* }}} */ /* {{{ json_module_entry */ zend_module_entry json_module_entry = { STANDARD_MODULE_HEADER, "json", json_functions, PHP_MINIT(json), NULL, NULL, NULL, PHP_MINFO(json), PHP_JSON_VERSION, PHP_MODULE_GLOBALS(json), PHP_GINIT(json), NULL, NULL, STANDARD_MODULE_PROPERTIES_EX }; /* }}} */ #ifdef COMPILE_DL_JSON ZEND_GET_MODULE(json) #endif /* {{{ PHP_MINFO_FUNCTION */ static PHP_MINFO_FUNCTION(json) { php_info_print_table_start(); php_info_print_table_row(2, "json support", "enabled"); php_info_print_table_row(2, "json version", PHP_JSON_VERSION); php_info_print_table_end(); } /* }}} */ static void json_escape_string(smart_str *buf, char *s, int len, int options TSRMLS_DC); static int json_determine_array_type(zval **val TSRMLS_DC) /* {{{ */ { int i; HashTable *myht = HASH_OF(*val); i = myht ? zend_hash_num_elements(myht) : 0; if (i > 0) { char *key; ulong index, idx; uint key_len; HashPosition pos; zend_hash_internal_pointer_reset_ex(myht, &pos); idx = 0; for (;; zend_hash_move_forward_ex(myht, &pos)) { i = zend_hash_get_current_key_ex(myht, &key, &key_len, &index, 0, &pos); if (i == HASH_KEY_NON_EXISTANT) break; if (i == HASH_KEY_IS_STRING) { return 1; } else { if (index != idx) { return 1; } } idx++; } } return PHP_JSON_OUTPUT_ARRAY; } /* }}} */ /* {{{ Pretty printing support functions */ static inline void json_pretty_print_char(smart_str *buf, int options, char c TSRMLS_DC) /* {{{ */ { if (options & PHP_JSON_PRETTY_PRINT) { smart_str_appendc(buf, c); } } /* }}} */ static inline void json_pretty_print_indent(smart_str *buf, int options TSRMLS_DC) /* {{{ */ { int i; if (options & PHP_JSON_PRETTY_PRINT) { for (i = 0; i < JSON_G(encoder_depth); ++i) { smart_str_appendl(buf, " ", 4); } } } /* }}} */ /* }}} */ static void json_encode_array(smart_str *buf, zval **val, int options TSRMLS_DC) /* {{{ */ { int i, r; HashTable *myht; if (Z_TYPE_PP(val) == IS_ARRAY) { myht = HASH_OF(*val); r = (options & PHP_JSON_FORCE_OBJECT) ? PHP_JSON_OUTPUT_OBJECT : json_determine_array_type(val TSRMLS_CC); } else { myht = Z_OBJPROP_PP(val); r = PHP_JSON_OUTPUT_OBJECT; } if (myht && myht->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); smart_str_appendl(buf, "null", 4); return; } if (r == PHP_JSON_OUTPUT_ARRAY) { smart_str_appendc(buf, '['); } else { smart_str_appendc(buf, '{'); } json_pretty_print_char(buf, options, '\n' TSRMLS_CC); ++JSON_G(encoder_depth); i = myht ? zend_hash_num_elements(myht) : 0; if (i > 0) { char *key; zval **data; ulong index; uint key_len; HashPosition pos; HashTable *tmp_ht; int need_comma = 0; zend_hash_internal_pointer_reset_ex(myht, &pos); for (;; zend_hash_move_forward_ex(myht, &pos)) { i = zend_hash_get_current_key_ex(myht, &key, &key_len, &index, 0, &pos); if (i == HASH_KEY_NON_EXISTANT) break; if (zend_hash_get_current_data_ex(myht, (void **) &data, &pos) == SUCCESS) { tmp_ht = HASH_OF(*data); if (tmp_ht) { tmp_ht->nApplyCount++; } if (r == PHP_JSON_OUTPUT_ARRAY) { if (need_comma) { smart_str_appendc(buf, ','); json_pretty_print_char(buf, options, '\n' TSRMLS_CC); } else { need_comma = 1; } json_pretty_print_indent(buf, options TSRMLS_CC); php_json_encode(buf, *data, options TSRMLS_CC); } else if (r == PHP_JSON_OUTPUT_OBJECT) { if (i == HASH_KEY_IS_STRING) { if (key[0] == '\0' && Z_TYPE_PP(val) == IS_OBJECT) { /* Skip protected and private members. */ if (tmp_ht) { tmp_ht->nApplyCount--; } continue; } if (need_comma) { smart_str_appendc(buf, ','); json_pretty_print_char(buf, options, '\n' TSRMLS_CC); } else { need_comma = 1; } json_pretty_print_indent(buf, options TSRMLS_CC); json_escape_string(buf, key, key_len - 1, options TSRMLS_CC); smart_str_appendc(buf, ':'); json_pretty_print_char(buf, options, ' ' TSRMLS_CC); php_json_encode(buf, *data, options TSRMLS_CC); } else { if (need_comma) { smart_str_appendc(buf, ','); json_pretty_print_char(buf, options, '\n' TSRMLS_CC); } else { need_comma = 1; } json_pretty_print_indent(buf, options TSRMLS_CC); smart_str_appendc(buf, '"'); smart_str_append_long(buf, (long) index); smart_str_appendc(buf, '"'); smart_str_appendc(buf, ':'); json_pretty_print_char(buf, options, ' ' TSRMLS_CC); php_json_encode(buf, *data, options TSRMLS_CC); } } if (tmp_ht) { tmp_ht->nApplyCount--; } } } } --JSON_G(encoder_depth); json_pretty_print_char(buf, options, '\n' TSRMLS_CC); json_pretty_print_indent(buf, options TSRMLS_CC); if (r == PHP_JSON_OUTPUT_ARRAY) { smart_str_appendc(buf, ']'); } else { smart_str_appendc(buf, '}'); } } /* }}} */ #define REVERSE16(us) (((us & 0xf) << 12) | (((us >> 4) & 0xf) << 8) | (((us >> 8) & 0xf) << 4) | ((us >> 12) & 0xf)) static void json_escape_string(smart_str *buf, char *s, int len, int options TSRMLS_DC) /* {{{ */ { int pos = 0, ulen = 0; unsigned short us; unsigned short *utf16; if (len == 0) { smart_str_appendl(buf, "\"\"", 2); return; } if (options & PHP_JSON_NUMERIC_CHECK) { double d; int type; long p; if ((type = is_numeric_string(s, len, &p, &d, 0)) != 0) { if (type == IS_LONG) { smart_str_append_long(buf, p); } else if (type == IS_DOUBLE) { if (!zend_isinf(d) && !zend_isnan(d)) { char *tmp; int l = spprintf(&tmp, 0, "%.*k", (int) EG(precision), d); smart_str_appendl(buf, tmp, l); efree(tmp); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "double %.9g does not conform to the JSON spec, encoded as 0", d); smart_str_appendc(buf, '0'); } } return; } } utf16 = (options & PHP_JSON_UNESCAPED_UNICODE) ? NULL : (unsigned short *) safe_emalloc(len, sizeof(unsigned short), 0); ulen = utf8_to_utf16(utf16, s, len); if (ulen <= 0) { if (utf16) { efree(utf16); } if (ulen < 0) { JSON_G(error_code) = PHP_JSON_ERROR_UTF8; if (!PG(display_errors)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid UTF-8 sequence in argument"); } smart_str_appendl(buf, "null", 4); } else { smart_str_appendl(buf, "\"\"", 2); } return; } if (!(options & PHP_JSON_UNESCAPED_UNICODE)) { len = ulen; } smart_str_appendc(buf, '"'); while (pos < len) { us = (options & PHP_JSON_UNESCAPED_UNICODE) ? s[pos++] : utf16[pos++]; switch (us) { case '"': if (options & PHP_JSON_HEX_QUOT) { smart_str_appendl(buf, "\\u0022", 6); } else { smart_str_appendl(buf, "\\\"", 2); } break; case '\\': smart_str_appendl(buf, "\\\\", 2); break; case '/': if (options & PHP_JSON_UNESCAPED_SLASHES) { smart_str_appendc(buf, '/'); } else { smart_str_appendl(buf, "\\/", 2); } break; case '\b': smart_str_appendl(buf, "\\b", 2); break; case '\f': smart_str_appendl(buf, "\\f", 2); break; case '\n': smart_str_appendl(buf, "\\n", 2); break; case '\r': smart_str_appendl(buf, "\\r", 2); break; case '\t': smart_str_appendl(buf, "\\t", 2); break; case '<': if (options & PHP_JSON_HEX_TAG) { smart_str_appendl(buf, "\\u003C", 6); } else { smart_str_appendc(buf, '<'); } break; case '>': if (options & PHP_JSON_HEX_TAG) { smart_str_appendl(buf, "\\u003E", 6); } else { smart_str_appendc(buf, '>'); } break; case '&': if (options & PHP_JSON_HEX_AMP) { smart_str_appendl(buf, "\\u0026", 6); } else { smart_str_appendc(buf, '&'); } break; case '\'': if (options & PHP_JSON_HEX_APOS) { smart_str_appendl(buf, "\\u0027", 6); } else { smart_str_appendc(buf, '\''); } break; default: if (us >= ' ' && ((options & PHP_JSON_UNESCAPED_UNICODE) || (us & 127) == us)) { smart_str_appendc(buf, (unsigned char) us); } else { smart_str_appendl(buf, "\\u", 2); us = REVERSE16(us); smart_str_appendc(buf, digits[us & ((1 << 4) - 1)]); us >>= 4; smart_str_appendc(buf, digits[us & ((1 << 4) - 1)]); us >>= 4; smart_str_appendc(buf, digits[us & ((1 << 4) - 1)]); us >>= 4; smart_str_appendc(buf, digits[us & ((1 << 4) - 1)]); } break; } } smart_str_appendc(buf, '"'); if (utf16) { efree(utf16); } } /* }}} */ static void json_encode_serializable_object(smart_str *buf, zval *val, int options TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = Z_OBJCE_P(val); zval *retval = NULL, fname; ZVAL_STRING(&fname, "jsonSerialize", 0); if (FAILURE == call_user_function_ex(EG(function_table), &val, &fname, &retval, 0, NULL, 1, NULL TSRMLS_CC) || !retval) { zend_throw_exception_ex(NULL, 0 TSRMLS_CC, "Failed calling %s::jsonSerialize()", ce->name); smart_str_appendl(buf, "null", sizeof("null") - 1); return; } if (EG(exception)) { /* Error already raised */ zval_ptr_dtor(&retval); smart_str_appendl(buf, "null", sizeof("null") - 1); return; } if ((Z_TYPE_P(retval) == IS_OBJECT) && (Z_OBJ_HANDLE_P(retval) == Z_OBJ_HANDLE_P(val))) { /* Handle the case where jsonSerialize does: return $this; by going straight to encode array */ json_encode_array(buf, &retval, options TSRMLS_CC); } else { /* All other types, encode as normal */ php_json_encode(buf, retval, options TSRMLS_CC); } zval_ptr_dtor(&retval); } /* }}} */ PHP_JSON_API void php_json_encode(smart_str *buf, zval *val, int options TSRMLS_DC) /* {{{ */ { switch (Z_TYPE_P(val)) { case IS_NULL: smart_str_appendl(buf, "null", 4); break; case IS_BOOL: if (Z_BVAL_P(val)) { smart_str_appendl(buf, "true", 4); } else { smart_str_appendl(buf, "false", 5); } break; case IS_LONG: smart_str_append_long(buf, Z_LVAL_P(val)); break; case IS_DOUBLE: { char *d = NULL; int len; double dbl = Z_DVAL_P(val); if (!zend_isinf(dbl) && !zend_isnan(dbl)) { len = spprintf(&d, 0, "%.*k", (int) EG(precision), dbl); smart_str_appendl(buf, d, len); efree(d); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "double %.9g does not conform to the JSON spec, encoded as 0", dbl); smart_str_appendc(buf, '0'); } } break; case IS_STRING: json_escape_string(buf, Z_STRVAL_P(val), Z_STRLEN_P(val), options TSRMLS_CC); break; case IS_OBJECT: if (instanceof_function(Z_OBJCE_P(val), php_json_serializable_ce TSRMLS_CC)) { json_encode_serializable_object(buf, val, options TSRMLS_CC); break; } /* fallthrough -- Non-serializable object */ case IS_ARRAY: json_encode_array(buf, &val, options TSRMLS_CC); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "type is unsupported, encoded as null"); smart_str_appendl(buf, "null", 4); break; } return; } /* }}} */ PHP_JSON_API void php_json_decode_ex(zval *return_value, char *str, int str_len, int options, long depth TSRMLS_DC) /* {{{ */ { int utf16_len; zval *z; unsigned short *utf16; JSON_parser jp; utf16 = (unsigned short *) safe_emalloc((str_len+1), sizeof(unsigned short), 1); utf16_len = utf8_to_utf16(utf16, str, str_len); if (utf16_len <= 0) { if (utf16) { efree(utf16); } JSON_G(error_code) = PHP_JSON_ERROR_UTF8; RETURN_NULL(); } if (depth <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Depth must be greater than zero"); efree(utf16); RETURN_NULL(); } ALLOC_INIT_ZVAL(z); jp = new_JSON_parser(depth); if (parse_JSON_ex(jp, z, utf16, utf16_len, options TSRMLS_CC)) { *return_value = *z; } else { double d; int type; long p; RETVAL_NULL(); if (str_len == 4) { if (!strcasecmp(str, "null")) { /* We need to explicitly clear the error because its an actual NULL and not an error */ jp->error_code = PHP_JSON_ERROR_NONE; RETVAL_NULL(); } else if (!strcasecmp(str, "true")) { RETVAL_BOOL(1); } } else if (str_len == 5 && !strcasecmp(str, "false")) { RETVAL_BOOL(0); } if ((type = is_numeric_string(str, str_len, &p, &d, 0)) != 0) { if (type == IS_LONG) { RETVAL_LONG(p); } else if (type == IS_DOUBLE) { RETVAL_DOUBLE(d); } } if (Z_TYPE_P(return_value) != IS_NULL) { jp->error_code = PHP_JSON_ERROR_NONE; } zval_dtor(z); } FREE_ZVAL(z); efree(utf16); JSON_G(error_code) = jp->error_code; free_JSON_parser(jp); } /* }}} */ /* {{{ proto string json_encode(mixed data [, int options]) Returns the JSON representation of a value */ static PHP_FUNCTION(json_encode) { zval *parameter; smart_str buf = {0}; long options = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|l", &parameter, &options) == FAILURE) { return; } JSON_G(error_code) = PHP_JSON_ERROR_NONE; php_json_encode(&buf, parameter, options TSRMLS_CC); ZVAL_STRINGL(return_value, buf.c, buf.len, 1); smart_str_free(&buf); } /* }}} */ /* {{{ proto mixed json_decode(string json [, bool assoc [, long depth]]) Decodes the JSON representation into a PHP value */ static PHP_FUNCTION(json_decode) { char *str; int str_len; zend_bool assoc = 0; /* return JS objects as PHP objects by default */ long depth = JSON_PARSER_DEFAULT_DEPTH; long options = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|bll", &str, &str_len, &assoc, &depth, &options) == FAILURE) { return; } JSON_G(error_code) = 0; if (!str_len) { RETURN_NULL(); } /* For BC reasons, the bool $assoc overrides the long $options bit for PHP_JSON_OBJECT_AS_ARRAY */ if (assoc) { options |= PHP_JSON_OBJECT_AS_ARRAY; } else { options &= ~PHP_JSON_OBJECT_AS_ARRAY; } php_json_decode_ex(return_value, str, str_len, options, depth TSRMLS_CC); } /* }}} */ /* {{{ proto int json_last_error() Returns the error code of the last json_decode(). */ static PHP_FUNCTION(json_last_error) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(JSON_G(error_code)); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Omar Kilani <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" #include "ext/standard/php_smart_str.h" #include "utf8_to_utf16.h" #include "JSON_parser.h" #include "php_json.h" #include <zend_exceptions.h> static PHP_MINFO_FUNCTION(json); static PHP_FUNCTION(json_encode); static PHP_FUNCTION(json_decode); static PHP_FUNCTION(json_last_error); static const char digits[] = "0123456789abcdef"; zend_class_entry *php_json_serializable_ce; ZEND_DECLARE_MODULE_GLOBALS(json) /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_json_encode, 0, 0, 1) ZEND_ARG_INFO(0, value) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_json_decode, 0, 0, 1) ZEND_ARG_INFO(0, json) ZEND_ARG_INFO(0, assoc) ZEND_ARG_INFO(0, depth) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_json_last_error, 0) ZEND_END_ARG_INFO() /* }}} */ /* {{{ json_functions[] */ static const zend_function_entry json_functions[] = { PHP_FE(json_encode, arginfo_json_encode) PHP_FE(json_decode, arginfo_json_decode) PHP_FE(json_last_error, arginfo_json_last_error) PHP_FE_END }; /* }}} */ /* {{{ JsonSerializable methods */ ZEND_BEGIN_ARG_INFO(json_serialize_arginfo, 0) /* No arguments */ ZEND_END_ARG_INFO(); static const zend_function_entry json_serializable_interface[] = { PHP_ABSTRACT_ME(JsonSerializable, jsonSerialize, json_serialize_arginfo) PHP_FE_END }; /* }}} */ /* {{{ MINIT */ static PHP_MINIT_FUNCTION(json) { zend_class_entry ce; INIT_CLASS_ENTRY(ce, "JsonSerializable", json_serializable_interface); php_json_serializable_ce = zend_register_internal_interface(&ce TSRMLS_CC); REGISTER_LONG_CONSTANT("JSON_HEX_TAG", PHP_JSON_HEX_TAG, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_HEX_AMP", PHP_JSON_HEX_AMP, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_HEX_APOS", PHP_JSON_HEX_APOS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_HEX_QUOT", PHP_JSON_HEX_QUOT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_FORCE_OBJECT", PHP_JSON_FORCE_OBJECT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_NUMERIC_CHECK", PHP_JSON_NUMERIC_CHECK, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_UNESCAPED_SLASHES", PHP_JSON_UNESCAPED_SLASHES, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_PRETTY_PRINT", PHP_JSON_PRETTY_PRINT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_UNESCAPED_UNICODE", PHP_JSON_UNESCAPED_UNICODE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_ERROR_NONE", PHP_JSON_ERROR_NONE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_ERROR_DEPTH", PHP_JSON_ERROR_DEPTH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_ERROR_STATE_MISMATCH", PHP_JSON_ERROR_STATE_MISMATCH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_ERROR_CTRL_CHAR", PHP_JSON_ERROR_CTRL_CHAR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_ERROR_SYNTAX", PHP_JSON_ERROR_SYNTAX, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_ERROR_UTF8", PHP_JSON_ERROR_UTF8, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_OBJECT_AS_ARRAY", PHP_JSON_OBJECT_AS_ARRAY, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_BIGINT_AS_STRING", PHP_JSON_BIGINT_AS_STRING, CONST_CS | CONST_PERSISTENT); return SUCCESS; } /* }}} */ /* {{{ PHP_GINIT_FUNCTION */ static PHP_GINIT_FUNCTION(json) { json_globals->encoder_depth = 0; json_globals->error_code = 0; } /* }}} */ /* {{{ json_module_entry */ zend_module_entry json_module_entry = { STANDARD_MODULE_HEADER, "json", json_functions, PHP_MINIT(json), NULL, NULL, NULL, PHP_MINFO(json), PHP_JSON_VERSION, PHP_MODULE_GLOBALS(json), PHP_GINIT(json), NULL, NULL, STANDARD_MODULE_PROPERTIES_EX }; /* }}} */ #ifdef COMPILE_DL_JSON ZEND_GET_MODULE(json) #endif /* {{{ PHP_MINFO_FUNCTION */ static PHP_MINFO_FUNCTION(json) { php_info_print_table_start(); php_info_print_table_row(2, "json support", "enabled"); php_info_print_table_row(2, "json version", PHP_JSON_VERSION); php_info_print_table_end(); } /* }}} */ static void json_escape_string(smart_str *buf, char *s, int len, int options TSRMLS_DC); static int json_determine_array_type(zval **val TSRMLS_DC) /* {{{ */ { int i; HashTable *myht = HASH_OF(*val); i = myht ? zend_hash_num_elements(myht) : 0; if (i > 0) { char *key; ulong index, idx; uint key_len; HashPosition pos; zend_hash_internal_pointer_reset_ex(myht, &pos); idx = 0; for (;; zend_hash_move_forward_ex(myht, &pos)) { i = zend_hash_get_current_key_ex(myht, &key, &key_len, &index, 0, &pos); if (i == HASH_KEY_NON_EXISTANT) break; if (i == HASH_KEY_IS_STRING) { return 1; } else { if (index != idx) { return 1; } } idx++; } } return PHP_JSON_OUTPUT_ARRAY; } /* }}} */ /* {{{ Pretty printing support functions */ static inline void json_pretty_print_char(smart_str *buf, int options, char c TSRMLS_DC) /* {{{ */ { if (options & PHP_JSON_PRETTY_PRINT) { smart_str_appendc(buf, c); } } /* }}} */ static inline void json_pretty_print_indent(smart_str *buf, int options TSRMLS_DC) /* {{{ */ { int i; if (options & PHP_JSON_PRETTY_PRINT) { for (i = 0; i < JSON_G(encoder_depth); ++i) { smart_str_appendl(buf, " ", 4); } } } /* }}} */ /* }}} */ static void json_encode_array(smart_str *buf, zval **val, int options TSRMLS_DC) /* {{{ */ { int i, r; HashTable *myht; if (Z_TYPE_PP(val) == IS_ARRAY) { myht = HASH_OF(*val); r = (options & PHP_JSON_FORCE_OBJECT) ? PHP_JSON_OUTPUT_OBJECT : json_determine_array_type(val TSRMLS_CC); } else { myht = Z_OBJPROP_PP(val); r = PHP_JSON_OUTPUT_OBJECT; } if (myht && myht->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); smart_str_appendl(buf, "null", 4); return; } if (r == PHP_JSON_OUTPUT_ARRAY) { smart_str_appendc(buf, '['); } else { smart_str_appendc(buf, '{'); } json_pretty_print_char(buf, options, '\n' TSRMLS_CC); ++JSON_G(encoder_depth); i = myht ? zend_hash_num_elements(myht) : 0; if (i > 0) { char *key; zval **data; ulong index; uint key_len; HashPosition pos; HashTable *tmp_ht; int need_comma = 0; zend_hash_internal_pointer_reset_ex(myht, &pos); for (;; zend_hash_move_forward_ex(myht, &pos)) { i = zend_hash_get_current_key_ex(myht, &key, &key_len, &index, 0, &pos); if (i == HASH_KEY_NON_EXISTANT) break; if (zend_hash_get_current_data_ex(myht, (void **) &data, &pos) == SUCCESS) { tmp_ht = HASH_OF(*data); if (tmp_ht) { tmp_ht->nApplyCount++; } if (r == PHP_JSON_OUTPUT_ARRAY) { if (need_comma) { smart_str_appendc(buf, ','); json_pretty_print_char(buf, options, '\n' TSRMLS_CC); } else { need_comma = 1; } json_pretty_print_indent(buf, options TSRMLS_CC); php_json_encode(buf, *data, options TSRMLS_CC); } else if (r == PHP_JSON_OUTPUT_OBJECT) { if (i == HASH_KEY_IS_STRING) { if (key[0] == '\0' && Z_TYPE_PP(val) == IS_OBJECT) { /* Skip protected and private members. */ if (tmp_ht) { tmp_ht->nApplyCount--; } continue; } if (need_comma) { smart_str_appendc(buf, ','); json_pretty_print_char(buf, options, '\n' TSRMLS_CC); } else { need_comma = 1; } json_pretty_print_indent(buf, options TSRMLS_CC); json_escape_string(buf, key, key_len - 1, options & ~PHP_JSON_NUMERIC_CHECK TSRMLS_CC); smart_str_appendc(buf, ':'); json_pretty_print_char(buf, options, ' ' TSRMLS_CC); php_json_encode(buf, *data, options TSRMLS_CC); } else { if (need_comma) { smart_str_appendc(buf, ','); json_pretty_print_char(buf, options, '\n' TSRMLS_CC); } else { need_comma = 1; } json_pretty_print_indent(buf, options TSRMLS_CC); smart_str_appendc(buf, '"'); smart_str_append_long(buf, (long) index); smart_str_appendc(buf, '"'); smart_str_appendc(buf, ':'); json_pretty_print_char(buf, options, ' ' TSRMLS_CC); php_json_encode(buf, *data, options TSRMLS_CC); } } if (tmp_ht) { tmp_ht->nApplyCount--; } } } } --JSON_G(encoder_depth); json_pretty_print_char(buf, options, '\n' TSRMLS_CC); json_pretty_print_indent(buf, options TSRMLS_CC); if (r == PHP_JSON_OUTPUT_ARRAY) { smart_str_appendc(buf, ']'); } else { smart_str_appendc(buf, '}'); } } /* }}} */ #define REVERSE16(us) (((us & 0xf) << 12) | (((us >> 4) & 0xf) << 8) | (((us >> 8) & 0xf) << 4) | ((us >> 12) & 0xf)) static void json_escape_string(smart_str *buf, char *s, int len, int options TSRMLS_DC) /* {{{ */ { int pos = 0, ulen = 0; unsigned short us; unsigned short *utf16; if (len == 0) { smart_str_appendl(buf, "\"\"", 2); return; } if (options & PHP_JSON_NUMERIC_CHECK) { double d; int type; long p; if ((type = is_numeric_string(s, len, &p, &d, 0)) != 0) { if (type == IS_LONG) { smart_str_append_long(buf, p); } else if (type == IS_DOUBLE) { if (!zend_isinf(d) && !zend_isnan(d)) { char *tmp; int l = spprintf(&tmp, 0, "%.*k", (int) EG(precision), d); smart_str_appendl(buf, tmp, l); efree(tmp); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "double %.9g does not conform to the JSON spec, encoded as 0", d); smart_str_appendc(buf, '0'); } } return; } } utf16 = (options & PHP_JSON_UNESCAPED_UNICODE) ? NULL : (unsigned short *) safe_emalloc(len, sizeof(unsigned short), 0); ulen = utf8_to_utf16(utf16, s, len); if (ulen <= 0) { if (utf16) { efree(utf16); } if (ulen < 0) { JSON_G(error_code) = PHP_JSON_ERROR_UTF8; if (!PG(display_errors)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid UTF-8 sequence in argument"); } smart_str_appendl(buf, "null", 4); } else { smart_str_appendl(buf, "\"\"", 2); } return; } if (!(options & PHP_JSON_UNESCAPED_UNICODE)) { len = ulen; } smart_str_appendc(buf, '"'); while (pos < len) { us = (options & PHP_JSON_UNESCAPED_UNICODE) ? s[pos++] : utf16[pos++]; switch (us) { case '"': if (options & PHP_JSON_HEX_QUOT) { smart_str_appendl(buf, "\\u0022", 6); } else { smart_str_appendl(buf, "\\\"", 2); } break; case '\\': smart_str_appendl(buf, "\\\\", 2); break; case '/': if (options & PHP_JSON_UNESCAPED_SLASHES) { smart_str_appendc(buf, '/'); } else { smart_str_appendl(buf, "\\/", 2); } break; case '\b': smart_str_appendl(buf, "\\b", 2); break; case '\f': smart_str_appendl(buf, "\\f", 2); break; case '\n': smart_str_appendl(buf, "\\n", 2); break; case '\r': smart_str_appendl(buf, "\\r", 2); break; case '\t': smart_str_appendl(buf, "\\t", 2); break; case '<': if (options & PHP_JSON_HEX_TAG) { smart_str_appendl(buf, "\\u003C", 6); } else { smart_str_appendc(buf, '<'); } break; case '>': if (options & PHP_JSON_HEX_TAG) { smart_str_appendl(buf, "\\u003E", 6); } else { smart_str_appendc(buf, '>'); } break; case '&': if (options & PHP_JSON_HEX_AMP) { smart_str_appendl(buf, "\\u0026", 6); } else { smart_str_appendc(buf, '&'); } break; case '\'': if (options & PHP_JSON_HEX_APOS) { smart_str_appendl(buf, "\\u0027", 6); } else { smart_str_appendc(buf, '\''); } break; default: if (us >= ' ' && ((options & PHP_JSON_UNESCAPED_UNICODE) || (us & 127) == us)) { smart_str_appendc(buf, (unsigned char) us); } else { smart_str_appendl(buf, "\\u", 2); us = REVERSE16(us); smart_str_appendc(buf, digits[us & ((1 << 4) - 1)]); us >>= 4; smart_str_appendc(buf, digits[us & ((1 << 4) - 1)]); us >>= 4; smart_str_appendc(buf, digits[us & ((1 << 4) - 1)]); us >>= 4; smart_str_appendc(buf, digits[us & ((1 << 4) - 1)]); } break; } } smart_str_appendc(buf, '"'); if (utf16) { efree(utf16); } } /* }}} */ static void json_encode_serializable_object(smart_str *buf, zval *val, int options TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = Z_OBJCE_P(val); zval *retval = NULL, fname; ZVAL_STRING(&fname, "jsonSerialize", 0); if (FAILURE == call_user_function_ex(EG(function_table), &val, &fname, &retval, 0, NULL, 1, NULL TSRMLS_CC) || !retval) { zend_throw_exception_ex(NULL, 0 TSRMLS_CC, "Failed calling %s::jsonSerialize()", ce->name); smart_str_appendl(buf, "null", sizeof("null") - 1); return; } if (EG(exception)) { /* Error already raised */ zval_ptr_dtor(&retval); smart_str_appendl(buf, "null", sizeof("null") - 1); return; } if ((Z_TYPE_P(retval) == IS_OBJECT) && (Z_OBJ_HANDLE_P(retval) == Z_OBJ_HANDLE_P(val))) { /* Handle the case where jsonSerialize does: return $this; by going straight to encode array */ json_encode_array(buf, &retval, options TSRMLS_CC); } else { /* All other types, encode as normal */ php_json_encode(buf, retval, options TSRMLS_CC); } zval_ptr_dtor(&retval); } /* }}} */ PHP_JSON_API void php_json_encode(smart_str *buf, zval *val, int options TSRMLS_DC) /* {{{ */ { switch (Z_TYPE_P(val)) { case IS_NULL: smart_str_appendl(buf, "null", 4); break; case IS_BOOL: if (Z_BVAL_P(val)) { smart_str_appendl(buf, "true", 4); } else { smart_str_appendl(buf, "false", 5); } break; case IS_LONG: smart_str_append_long(buf, Z_LVAL_P(val)); break; case IS_DOUBLE: { char *d = NULL; int len; double dbl = Z_DVAL_P(val); if (!zend_isinf(dbl) && !zend_isnan(dbl)) { len = spprintf(&d, 0, "%.*k", (int) EG(precision), dbl); smart_str_appendl(buf, d, len); efree(d); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "double %.9g does not conform to the JSON spec, encoded as 0", dbl); smart_str_appendc(buf, '0'); } } break; case IS_STRING: json_escape_string(buf, Z_STRVAL_P(val), Z_STRLEN_P(val), options TSRMLS_CC); break; case IS_OBJECT: if (instanceof_function(Z_OBJCE_P(val), php_json_serializable_ce TSRMLS_CC)) { json_encode_serializable_object(buf, val, options TSRMLS_CC); break; } /* fallthrough -- Non-serializable object */ case IS_ARRAY: json_encode_array(buf, &val, options TSRMLS_CC); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "type is unsupported, encoded as null"); smart_str_appendl(buf, "null", 4); break; } return; } /* }}} */ PHP_JSON_API void php_json_decode_ex(zval *return_value, char *str, int str_len, int options, long depth TSRMLS_DC) /* {{{ */ { int utf16_len; zval *z; unsigned short *utf16; JSON_parser jp; utf16 = (unsigned short *) safe_emalloc((str_len+1), sizeof(unsigned short), 1); utf16_len = utf8_to_utf16(utf16, str, str_len); if (utf16_len <= 0) { if (utf16) { efree(utf16); } JSON_G(error_code) = PHP_JSON_ERROR_UTF8; RETURN_NULL(); } if (depth <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Depth must be greater than zero"); efree(utf16); RETURN_NULL(); } ALLOC_INIT_ZVAL(z); jp = new_JSON_parser(depth); if (parse_JSON_ex(jp, z, utf16, utf16_len, options TSRMLS_CC)) { *return_value = *z; } else { double d; int type; long p; RETVAL_NULL(); if (str_len == 4) { if (!strcasecmp(str, "null")) { /* We need to explicitly clear the error because its an actual NULL and not an error */ jp->error_code = PHP_JSON_ERROR_NONE; RETVAL_NULL(); } else if (!strcasecmp(str, "true")) { RETVAL_BOOL(1); } } else if (str_len == 5 && !strcasecmp(str, "false")) { RETVAL_BOOL(0); } if ((type = is_numeric_string(str, str_len, &p, &d, 0)) != 0) { if (type == IS_LONG) { RETVAL_LONG(p); } else if (type == IS_DOUBLE) { RETVAL_DOUBLE(d); } } if (Z_TYPE_P(return_value) != IS_NULL) { jp->error_code = PHP_JSON_ERROR_NONE; } zval_dtor(z); } FREE_ZVAL(z); efree(utf16); JSON_G(error_code) = jp->error_code; free_JSON_parser(jp); } /* }}} */ /* {{{ proto string json_encode(mixed data [, int options]) Returns the JSON representation of a value */ static PHP_FUNCTION(json_encode) { zval *parameter; smart_str buf = {0}; long options = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|l", &parameter, &options) == FAILURE) { return; } JSON_G(error_code) = PHP_JSON_ERROR_NONE; php_json_encode(&buf, parameter, options TSRMLS_CC); ZVAL_STRINGL(return_value, buf.c, buf.len, 1); smart_str_free(&buf); } /* }}} */ /* {{{ proto mixed json_decode(string json [, bool assoc [, long depth]]) Decodes the JSON representation into a PHP value */ static PHP_FUNCTION(json_decode) { char *str; int str_len; zend_bool assoc = 0; /* return JS objects as PHP objects by default */ long depth = JSON_PARSER_DEFAULT_DEPTH; long options = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|bll", &str, &str_len, &assoc, &depth, &options) == FAILURE) { return; } JSON_G(error_code) = 0; if (!str_len) { RETURN_NULL(); } /* For BC reasons, the bool $assoc overrides the long $options bit for PHP_JSON_OBJECT_AS_ARRAY */ if (assoc) { options |= PHP_JSON_OBJECT_AS_ARRAY; } else { options &= ~PHP_JSON_OBJECT_AS_ARRAY; } php_json_decode_ex(return_value, str, str_len, options, depth TSRMLS_CC); } /* }}} */ /* {{{ proto int json_last_error() Returns the error code of the last json_decode(). */ static PHP_FUNCTION(json_last_error) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(JSON_G(error_code)); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-10-16-1f78177e2b-d4ae4e79db.c
manybugs_data_3
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <zend_language_parser.h> #include "zend.h" #include "zend_compile.h" #include "zend_constants.h" #include "zend_llist.h" #include "zend_API.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "zend_multibyte.h" #include "zend_language_scanner.h" #define CONSTANT_EX(op_array, op) \ (op_array)->literals[op].constant #define CONSTANT(op) \ CONSTANT_EX(CG(active_op_array), op) #define SET_NODE(target, src) do { \ target ## _type = (src)->op_type; \ if ((src)->op_type == IS_CONST) { \ target.constant = zend_add_literal(CG(active_op_array), &(src)->u.constant TSRMLS_CC); \ } else { \ target = (src)->u.op; \ } \ } while (0) #define GET_NODE(target, src) do { \ (target)->op_type = src ## _type; \ if ((target)->op_type == IS_CONST) { \ (target)->u.constant = CONSTANT(src.constant); \ } else { \ (target)->u.op = src; \ (target)->EA = 0; \ } \ } while (0) #define COPY_NODE(target, src) do { \ target ## _type = src ## _type; \ target = src; \ } while (0) #define CALCULATE_LITERAL_HASH(num) do { \ if (IS_INTERNED(Z_STRVAL(CONSTANT(num)))) { \ Z_HASH_P(&CONSTANT(num)) = INTERNED_HASH(Z_STRVAL(CONSTANT(num))); \ } else { \ Z_HASH_P(&CONSTANT(num)) = zend_hash_func(Z_STRVAL(CONSTANT(num)), Z_STRLEN(CONSTANT(num))+1); \ } \ } while (0) #define GET_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot++; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ } \ } while (0) #define POLYMORPHIC_CACHE_SLOT_SIZE 2 #define GET_POLYMORPHIC_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot; \ CG(active_op_array)->last_cache_slot += POLYMORPHIC_CACHE_SLOT_SIZE; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 2] = NULL; \ } \ } while (0) #define FREE_POLYMORPHIC_CACHE_SLOT(literal) do { \ if (CG(active_op_array)->literals[literal].cache_slot == \ CG(active_op_array)->last_cache_slot - POLYMORPHIC_CACHE_SLOT_SIZE) { \ CG(active_op_array)->literals[literal].cache_slot = -1; \ CG(active_op_array)->last_cache_slot -= POLYMORPHIC_CACHE_SLOT_SIZE; \ } \ } while (0) ZEND_API zend_op_array *(*zend_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); ZEND_API zend_op_array *(*zend_compile_string)(zval *source_string, char *filename TSRMLS_DC); #ifndef ZTS ZEND_API zend_compiler_globals compiler_globals; ZEND_API zend_executor_globals executor_globals; #endif static void zend_duplicate_property_info(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = estrndup(property_info->name, property_info->name_length); } if (property_info->doc_comment) { property_info->doc_comment = estrndup(property_info->doc_comment, property_info->doc_comment_len); } } /* }}} */ static void zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = zend_strndup(property_info->name, property_info->name_length); } } /* }}} */ static void zend_destroy_property_info(zend_property_info *property_info) /* {{{ */ { str_efree(property_info->name); if (property_info->doc_comment) { efree((char*)property_info->doc_comment); } } /* }}} */ static void zend_destroy_property_info_internal(zend_property_info *property_info) /* {{{ */ { str_free((char*)property_info->name); } /* }}} */ static void build_runtime_defined_function_key(zval *result, const char *name, int name_length TSRMLS_DC) /* {{{ */ { char char_pos_buf[32]; uint char_pos_len; const char *filename; char_pos_len = zend_sprintf(char_pos_buf, "%p", LANG_SCNG(yy_text)); if (CG(active_op_array)->filename) { filename = CG(active_op_array)->filename; } else { filename = "-"; } /* NULL, name length, filename length, last accepting char position length */ result->value.str.len = 1+name_length+strlen(filename)+char_pos_len; /* must be binary safe */ result->value.str.val = (char *) safe_emalloc(result->value.str.len, 1, 1); result->value.str.val[0] = '\0'; sprintf(result->value.str.val+1, "%s%s%s", name, filename, char_pos_buf); result->type = IS_STRING; Z_SET_REFCOUNT_P(result, 1); } /* }}} */ static void init_compiler_declarables(TSRMLS_D) /* {{{ */ { Z_TYPE(CG(declarables).ticks) = IS_LONG; Z_LVAL(CG(declarables).ticks) = 0; } /* }}} */ void zend_init_compiler_context(TSRMLS_D) /* {{{ */ { CG(context).opcodes_size = (CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) ? INITIAL_INTERACTIVE_OP_ARRAY_SIZE : INITIAL_OP_ARRAY_SIZE; CG(context).vars_size = 0; CG(context).literals_size = 0; CG(context).current_brk_cont = -1; CG(context).backpatch_count = 0; CG(context).labels = NULL; } /* }}} */ void zend_init_compiler_data_structures(TSRMLS_D) /* {{{ */ { zend_stack_init(&CG(bp_stack)); zend_stack_init(&CG(function_call_stack)); zend_stack_init(&CG(switch_cond_stack)); zend_stack_init(&CG(foreach_copy_stack)); zend_stack_init(&CG(object_stack)); zend_stack_init(&CG(declare_stack)); CG(active_class_entry) = NULL; zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_stack_init(&CG(list_stack)); CG(in_compilation) = 0; CG(start_lineno) = 0; CG(current_namespace) = NULL; CG(in_namespace) = 0; CG(has_bracketed_namespaces) = 0; CG(current_import) = NULL; init_compiler_declarables(TSRMLS_C); zend_stack_init(&CG(context_stack)); CG(encoding_declared) = 0; } /* }}} */ ZEND_API void file_handle_dtor(zend_file_handle *fh) /* {{{ */ { TSRMLS_FETCH(); zend_file_handle_dtor(fh TSRMLS_CC); } /* }}} */ void init_compiler(TSRMLS_D) /* {{{ */ { CG(active_op_array) = NULL; zend_init_compiler_data_structures(TSRMLS_C); zend_init_rsrc_list(TSRMLS_C); zend_hash_init(&CG(filenames_table), 5, NULL, (dtor_func_t) free_estring, 0); zend_llist_init(&CG(open_files), sizeof(zend_file_handle), (void (*)(void *)) file_handle_dtor, 0); CG(unclean_shutdown) = 0; } /* }}} */ void shutdown_compiler(TSRMLS_D) /* {{{ */ { zend_stack_destroy(&CG(bp_stack)); zend_stack_destroy(&CG(function_call_stack)); zend_stack_destroy(&CG(switch_cond_stack)); zend_stack_destroy(&CG(foreach_copy_stack)); zend_stack_destroy(&CG(object_stack)); zend_stack_destroy(&CG(declare_stack)); zend_stack_destroy(&CG(list_stack)); zend_hash_destroy(&CG(filenames_table)); zend_llist_destroy(&CG(open_files)); zend_stack_destroy(&CG(context_stack)); } /* }}} */ ZEND_API char *zend_set_compiled_filename(const char *new_compiled_filename TSRMLS_DC) /* {{{ */ { char **pp, *p; int length = strlen(new_compiled_filename); if (zend_hash_find(&CG(filenames_table), new_compiled_filename, length+1, (void **) &pp) == SUCCESS) { CG(compiled_filename) = *pp; return *pp; } p = estrndup(new_compiled_filename, length); zend_hash_update(&CG(filenames_table), new_compiled_filename, length+1, &p, sizeof(char *), (void **) &pp); CG(compiled_filename) = p; return p; } /* }}} */ ZEND_API void zend_restore_compiled_filename(char *original_compiled_filename TSRMLS_DC) /* {{{ */ { CG(compiled_filename) = original_compiled_filename; } /* }}} */ ZEND_API char *zend_get_compiled_filename(TSRMLS_D) /* {{{ */ { return CG(compiled_filename); } /* }}} */ ZEND_API int zend_get_compiled_lineno(TSRMLS_D) /* {{{ */ { return CG(zend_lineno); } /* }}} */ ZEND_API zend_bool zend_is_compiling(TSRMLS_D) /* {{{ */ { return CG(in_compilation); } /* }}} */ static zend_uint get_temporary_variable(zend_op_array *op_array) /* {{{ */ { return (op_array->T)++ * ZEND_MM_ALIGNED_SIZE(sizeof(temp_variable)); } /* }}} */ static int lookup_cv(zend_op_array *op_array, char* name, int name_len, ulong hash TSRMLS_DC) /* {{{ */ { int i = 0; ulong hash_value = hash ? hash : zend_inline_hash_func(name, name_len+1); while (i < op_array->last_var) { if (op_array->vars[i].name == name || (op_array->vars[i].hash_value == hash_value && op_array->vars[i].name_len == name_len && memcmp(op_array->vars[i].name, name, name_len) == 0)) { str_efree(name); return i; } i++; } i = op_array->last_var; op_array->last_var++; if (op_array->last_var > CG(context).vars_size) { CG(context).vars_size += 16; /* FIXME */ op_array->vars = erealloc(op_array->vars, CG(context).vars_size * sizeof(zend_compiled_variable)); } op_array->vars[i].name = zend_new_interned_string(name, name_len + 1, 1 TSRMLS_CC); op_array->vars[i].name_len = name_len; op_array->vars[i].hash_value = hash_value; return i; } /* }}} */ void zend_del_literal(zend_op_array *op_array, int n) /* {{{ */ { zval_dtor(&CONSTANT_EX(op_array, n)); if (n + 1 == op_array->last_literal) { op_array->last_literal--; } else { Z_TYPE(CONSTANT_EX(op_array, n)) = IS_NULL; } } /* }}} */ /* Common part of zend_add_literal and zend_append_individual_literal */ static inline void zend_insert_literal(zend_op_array *op_array, const zval *zv, int literal_position TSRMLS_DC) /* {{{ */ { if (Z_TYPE_P(zv) == IS_STRING || Z_TYPE_P(zv) == IS_CONSTANT) { zval *z = (zval*)zv; Z_STRVAL_P(z) = (char*)zend_new_interned_string(Z_STRVAL_P(zv), Z_STRLEN_P(zv) + 1, 1 TSRMLS_CC); } CONSTANT_EX(op_array, literal_position) = *zv; Z_SET_REFCOUNT(CONSTANT_EX(op_array, literal_position), 2); Z_SET_ISREF(CONSTANT_EX(op_array, literal_position)); op_array->literals[literal_position].hash_value = 0; op_array->literals[literal_position].cache_slot = -1; } /* }}} */ /* Is used while compiling a function, using the context to keep track of an approximate size to avoid to relocate to often. Literals are truncated to actual size in the second compiler pass (pass_two()). */ int zend_add_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; if (i >= CG(context).literals_size) { while (i >= CG(context).literals_size) { CG(context).literals_size += 16; /* FIXME */ } op_array->literals = (zend_literal*)erealloc(op_array->literals, CG(context).literals_size * sizeof(zend_literal)); } zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ /* Is used after normal compilation to append an additional literal. Allocation is done precisely here. */ int zend_append_individual_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; op_array->literals = (zend_literal*)erealloc(op_array->literals, (i + 1) * sizeof(zend_literal)); zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ int zend_add_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_ns_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; const char *ns_separator; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); ns_separator = (const char*)zend_memrchr(Z_STRVAL_P(zv), '\\', Z_STRLEN_P(zv)) + 1; lc_len = Z_STRLEN_P(zv) - (ns_separator - Z_STRVAL_P(zv)); lc_name = zend_str_tolower_dup(ns_separator, lc_len); ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_class_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } if (Z_STRVAL_P(zv)[0] == '\\') { lc_len = Z_STRLEN_P(zv) - 1; lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv) + 1, lc_len); } else { lc_len = Z_STRLEN_P(zv); lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), lc_len); } ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); GET_CACHE_SLOT(ret); return ret; } /* }}} */ int zend_add_const_name_literal(zend_op_array *op_array, const zval *zv, int unqualified TSRMLS_DC) /* {{{ */ { int ret, tmp_literal; char *name, *tmp_name; const char *ns_separator; int name_len, ns_len; zval c; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } /* skip leading '\\' */ if (Z_STRVAL_P(zv)[0] == '\\') { name_len = Z_STRLEN_P(zv) - 1; name = Z_STRVAL_P(zv) + 1; } else { name_len = Z_STRLEN_P(zv); name = Z_STRVAL_P(zv); } ns_separator = zend_memrchr(name, '\\', name_len); if (ns_separator) { ns_len = ns_separator - name; } else { ns_len = 0; } if (ns_len) { /* lowercased namespace name & original constant name */ tmp_name = estrndup(name, name_len); zend_str_tolower(tmp_name, ns_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased namespace name & lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); } if (ns_len) { if (!unqualified) { return ret; } ns_len++; name += ns_len; name_len -= ns_len; } /* original constant name */ tmp_name = estrndup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); return ret; } /* }}} */ #define LITERAL_STRINGL(op, str, len, copy) do { \ zval _c; \ ZVAL_STRINGL(&_c, str, len, copy); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG(op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG_EX(op_array, op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(op_array, &_c TSRMLS_CC); \ } while (0) #define LITERAL_NULL(op) do { \ zval _c; \ INIT_ZVAL( _c); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) static inline zend_bool zend_is_function_or_method_call(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; return ((type & ZEND_PARSED_METHOD_CALL) || (type == ZEND_PARSED_FUNCTION_CALL)); } /* }}} */ void zend_do_binary_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_unary_op(zend_uchar op, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); GET_NODE(result, opline->result); SET_UNUSED(opline->op2); } /* }}} */ #define MAKE_NOP(opline) { opline->opcode = ZEND_NOP; memset(&opline->result,0,sizeof(opline->result)); memset(&opline->op1,0,sizeof(opline->op1)); memset(&opline->op2,0,sizeof(opline->op2)); opline->result_type=opline->op1_type=opline->op2_type=IS_UNUSED; } static void zend_do_op_data(zend_op *data_op, const znode *value TSRMLS_DC) /* {{{ */ { data_op->opcode = ZEND_OP_DATA; SET_NODE(data_op->op1, value); SET_UNUSED(data_op->op2); } /* }}} */ void zend_do_binary_assign_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; switch (last_op->opcode) { case ZEND_FETCH_OBJ_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, op2 TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; case ZEND_FETCH_DIM_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_DIM; zend_do_op_data(opline, op2 TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result,last_op->result); return; default: break; } } opline->opcode = op; SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void fetch_simple_variable_ex(znode *result, znode *varname, int bp, zend_uchar op TSRMLS_DC) /* {{{ */ { zend_op opline; zend_op *opline_ptr; zend_llist *fetch_list_ptr; if (varname->op_type == IS_CONST) { ulong hash = 0; if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } else if (IS_INTERNED(Z_STRVAL(varname->u.constant))) { hash = INTERNED_HASH(Z_STRVAL(varname->u.constant)); } if (!zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC) && !(varname->u.constant.value.str.len == (sizeof("this")-1) && !memcmp(varname->u.constant.value.str.val, "this", sizeof("this"))) && (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE)) { result->op_type = IS_CV; result->u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC); varname->u.constant.value.str.val = (char*)CG(active_op_array)->vars[result->u.op.var].name; result->EA = 0; return; } } if (bp) { opline_ptr = &opline; init_op(opline_ptr TSRMLS_CC); } else { opline_ptr = get_next_op(CG(active_op_array) TSRMLS_CC); } opline_ptr->opcode = op; opline_ptr->result_type = IS_VAR; opline_ptr->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline_ptr->op1, varname); GET_NODE(result, opline_ptr->result); SET_UNUSED(opline_ptr->op2); opline_ptr->extended_value = ZEND_FETCH_LOCAL; if (varname->op_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline_ptr->op1.constant); if (zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC)) { opline_ptr->extended_value = ZEND_FETCH_GLOBAL; } } if (bp) { zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); zend_llist_add_element(fetch_list_ptr, opline_ptr); } } /* }}} */ void fetch_simple_variable(znode *result, znode *varname, int bp TSRMLS_DC) /* {{{ */ { /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ fetch_simple_variable_ex(result, varname, bp, ZEND_FETCH_W TSRMLS_CC); } /* }}} */ void zend_do_fetch_static_member(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { znode class_node; zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline_ptr; zend_op opline; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); } zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (result->op_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[result->u.op.var].name), CG(active_op_array)->vars[result->u.op.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } GET_NODE(result,opline.result); opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; opline_ptr = &opline; zend_llist_add_element(fetch_list_ptr, &opline); } else { le = fetch_list_ptr->head; opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode != ZEND_FETCH_W && opline_ptr->op1_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[opline_ptr->op1.var].name), CG(active_op_array)->vars[opline_ptr->op1.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; COPY_NODE(opline_ptr->op1, opline.result); zend_llist_prepend_element(fetch_list_ptr, &opline); } else { if (opline_ptr->op1_type == IS_CONST) { GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op1.constant); } if (class_node.op_type == IS_CONST) { opline_ptr->op2_type = IS_CONST; opline_ptr->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline_ptr->op2, &class_node); } opline_ptr->extended_value |= ZEND_FETCH_STATIC_MEMBER; } } } /* }}} */ void fetch_array_begin(znode *result, znode *varname, znode *first_dim TSRMLS_DC) /* {{{ */ { fetch_simple_variable(result, varname, 1 TSRMLS_CC); fetch_array_dim(result, result, first_dim TSRMLS_CC); } /* }}} */ void fetch_array_dim(znode *result, const znode *parent, const znode *dim TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (zend_is_function_or_method_call(parent)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, parent); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_DIM_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, parent); SET_NODE(opline.op2, dim); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline.op2.constant)), Z_STRLEN(CONSTANT(opline.op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline.op2.constant)); ZVAL_LONG(&CONSTANT(opline.op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline.op2.constant); } } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void fetch_string_offset(znode *result, const znode *parent, const znode *offset TSRMLS_DC) /* {{{ */ { fetch_array_dim(result, parent, offset TSRMLS_CC); } /* }}} */ void zend_do_print(znode *result, const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->opcode = ZEND_PRINT; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_echo(const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ECHO; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_abstract_method(const znode *function_name, znode *modifiers, const znode *body TSRMLS_DC) /* {{{ */ { char *method_type; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { Z_LVAL(modifiers->u.constant) |= ZEND_ACC_ABSTRACT; method_type = "Interface"; } else { method_type = "Abstract"; } if (modifiers->u.constant.value.lval & ZEND_ACC_ABSTRACT) { if(modifiers->u.constant.value.lval & ZEND_ACC_PRIVATE) { zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot be declared private", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } if (Z_LVAL(body->u.constant) == ZEND_ACC_ABSTRACT) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_RAISE_ABSTRACT_ERROR; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } else { /* we had code in the function body */ zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot contain body", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } else { if (body->u.constant.value.lval == ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Non-abstract method %s::%s() must contain body", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } } /* }}} */ static zend_bool opline_is_fetch_this(const zend_op *opline TSRMLS_DC) /* {{{ */ { if ((opline->opcode == ZEND_FETCH_W) && (opline->op1_type == IS_CONST) && (Z_TYPE(CONSTANT(opline->op1.constant)) == IS_STRING) && (Z_HASH_P(&CONSTANT(opline->op1.constant)) == THIS_HASHVAL) && (Z_STRLEN(CONSTANT(opline->op1.constant)) == (sizeof("this")-1)) && !memcmp(Z_STRVAL(CONSTANT(opline->op1.constant)), "this", sizeof("this"))) { return 1; } else { return 0; } } /* }}} */ void zend_do_assign(znode *result, znode *variable, znode *value TSRMLS_DC) /* {{{ */ { int last_op_number; zend_op *opline; if (value->op_type == IS_CV) { zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (fetch_list_ptr && fetch_list_ptr->head) { opline = (zend_op *)fetch_list_ptr->head->data; if (opline->opcode == ZEND_FETCH_DIM_W && opline->op1_type == IS_CV && opline->op1.var == value->u.op.var) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_R; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->op1_type = IS_CONST; LITERAL_STRINGL(opline->op1, CG(active_op_array)->vars[value->u.op.var].name, CG(active_op_array)->vars[value->u.op.var].name_len, 1); CALCULATE_LITERAL_HASH(opline->op1.constant); SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_LOCAL; GET_NODE(value, opline->result); } } } zend_do_end_variable_parse(variable, BP_VAR_W, 0 TSRMLS_CC); last_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (variable->op_type == IS_CV) { if (variable->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (variable->op_type == IS_VAR) { int n = 0; while (last_op_number - n > 0) { zend_op *last_op; last_op = &CG(active_op_array)->opcodes[last_op_number-n-1]; if (last_op->result_type == IS_VAR && last_op->result.var == variable->u.op.var) { if (last_op->opcode == ZEND_FETCH_OBJ_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, value TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (last_op->opcode == ZEND_FETCH_DIM_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ /* TBFixed: this can realloc opcodes, leaving last_op pointing wrong */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_DIM; zend_do_op_data(opline, value TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (opline_is_fetch_this(last_op TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } else { break; } } n++; } } opline->opcode = ZEND_ASSIGN; SET_NODE(opline->op1, variable); SET_NODE(opline->op2, value); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_assign_ref(znode *result, const znode *lvar, const znode *rvar TSRMLS_DC) /* {{{ */ { zend_op *opline; if (lvar->op_type == IS_CV) { if (lvar->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (lvar->op_type == IS_VAR) { int last_op_number = get_next_op_number(CG(active_op_array)); if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline_is_fetch_this(opline TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ASSIGN_REF; if (zend_is_function_or_method_call(rvar)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } else if (rvar->EA & ZEND_PARSED_NEW) { opline->extended_value = ZEND_RETURNS_NEW; } else { opline->extended_value = 0; } if (result) { opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } else { opline->result_type = IS_UNUSED | EXT_TYPE_UNUSED; } SET_NODE(opline->op1, lvar); SET_NODE(opline->op2, rvar); } /* }}} */ static inline void do_begin_loop(TSRMLS_D) /* {{{ */ { zend_brk_cont_element *brk_cont_element; int parent; parent = CG(context).current_brk_cont; CG(context).current_brk_cont = CG(active_op_array)->last_brk_cont; brk_cont_element = get_next_brk_cont_element(CG(active_op_array)); brk_cont_element->start = get_next_op_number(CG(active_op_array)); brk_cont_element->parent = parent; } /* }}} */ static inline void do_end_loop(int cont_addr, int has_loop_var TSRMLS_DC) /* {{{ */ { if (!has_loop_var) { /* The start fileld is used to free temporary variables in case of exceptions. * We won't try to free something of we don't have loop variable. */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].start = -1; } CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = cont_addr; CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; } /* }}} */ void zend_do_while_cond(const znode *expr, znode *close_bracket_token TSRMLS_DC) /* {{{ */ { int while_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, expr); close_bracket_token->u.op.opline_num = while_cond_op_number; SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_while_end(const znode *while_token, const znode *close_bracket_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* add unconditional jump */ opline->opcode = ZEND_JMP; opline->op1.opline_num = while_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* update while's conditional jmp */ CG(active_op_array)->opcodes[close_bracket_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); do_end_loop(while_token->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_cond(const znode *expr, znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { int for_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZNZ; SET_NODE(opline->op1, expr); /* the conditional expression */ second_semicolon_token->u.op.opline_num = for_cond_op_number; SET_UNUSED(opline->op2); } /* }}} */ void zend_do_for_before_statement(const znode *cond_start, const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = cond_start->u.op.opline_num; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_end(const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = second_semicolon_token->u.op.opline_num+1; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_end_loop(second_semicolon_token->u.op.opline_num+1, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_pre_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_PRE_INC)?ZEND_PRE_INC_OBJ:ZEND_PRE_DEC_OBJ; last_op->result_type = IS_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_post_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_POST_INC)?ZEND_POST_INC_OBJ:ZEND_POST_DEC_OBJ; last_op->result_type = IS_TMP_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_if_cond(const znode *cond, znode *closing_bracket_token TSRMLS_DC) /* {{{ */ { int if_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); closing_bracket_token->u.op.opline_num = if_cond_op_number; SET_UNUSED(opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_if_after_statement(const znode *closing_bracket_token, unsigned char initialize TSRMLS_DC) /* {{{ */ { int if_end_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; /* save for backpatching */ if (initialize) { zend_llist jmp_list; zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); } zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &if_end_op_number); CG(active_op_array)->opcodes[closing_bracket_token->u.op.opline_num].op2.opline_num = if_end_op_number+1; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_if_end(TSRMLS_D) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_llist *jmp_list_ptr; zend_llist_element *le; zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); for (le=jmp_list_ptr->head; le; le = le->next) { CG(active_op_array)->opcodes[*((int *) le->data)].op1.opline_num = next_op_number; } zend_llist_destroy(jmp_list_ptr); zend_stack_del_top(&CG(bp_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_check_writable_variable(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; if (type & ZEND_PARSED_METHOD_CALL) { zend_error(E_COMPILE_ERROR, "Can't use method return value in write context"); } if (type == ZEND_PARSED_FUNCTION_CALL) { zend_error(E_COMPILE_ERROR, "Can't use function return value in write context"); } } /* }}} */ void zend_do_begin_variable_parse(TSRMLS_D) /* {{{ */ { zend_llist fetch_list; zend_llist_init(&fetch_list, sizeof(zend_op), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &fetch_list, sizeof(zend_llist)); } /* }}} */ void zend_do_end_variable_parse(znode *variable, int type, int arg_offset TSRMLS_DC) /* {{{ */ { zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline = NULL; zend_op *opline_ptr; zend_uint this_var = -1; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); le = fetch_list_ptr->head; /* TODO: $foo->x->y->z = 1 should fetch "x" and "y" for R or RW, not just W */ if (le) { opline_ptr = (zend_op *)le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { /* convert to FETCH_?(this) into IS_CV */ if (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE) { this_var = opline_ptr->result.var; if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), Z_STRVAL(CONSTANT(opline_ptr->op1.constant)), Z_STRLEN(CONSTANT(opline_ptr->op1.constant)), Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC); Z_TYPE(CONSTANT(opline_ptr->op1.constant)) = IS_NULL; } else { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); } le = le->next; if (variable->op_type == IS_VAR && variable->u.op.var == this_var) { variable->op_type = IS_CV; variable->u.op.var = CG(active_op_array)->this_var; } } else if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } while (le) { opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode == ZEND_SEPARATE) { if (type != BP_VAR_R && type != BP_VAR_IS) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); } le = le->next; continue; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); if (opline->op1_type == IS_VAR && opline->op1.var == this_var) { opline->op1_type = IS_CV; opline->op1.var = CG(active_op_array)->this_var; } switch (type) { case BP_VAR_R: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode -= 3; break; case BP_VAR_W: break; case BP_VAR_RW: opline->opcode += 3; break; case BP_VAR_IS: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode += 6; /* 3+3 */ break; case BP_VAR_FUNC_ARG: opline->opcode += 9; /* 3+3+3 */ opline->extended_value |= arg_offset; break; case BP_VAR_UNSET: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for unsetting"); } opline->opcode += 12; /* 3+3+3+3 */ break; } le = le->next; } if (opline && type == BP_VAR_W && arg_offset) { opline->extended_value |= ZEND_FETCH_MAKE_REF; } } zend_llist_destroy(fetch_list_ptr); zend_stack_del_top(&CG(bp_stack)); } /* }}} */ void zend_do_add_string(znode *result, const znode *op1, znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline; if (Z_STRLEN(op2->u.constant) > 1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_STRING; } else if (Z_STRLEN(op2->u.constant) == 1) { int ch = *Z_STRVAL(op2->u.constant); /* Free memory and use ZEND_ADD_CHAR in case of 1 character strings */ efree(Z_STRVAL(op2->u.constant)); ZVAL_LONG(&op2->u.constant, ch); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_CHAR; } else { /* String can be empty after a variable at the end of a heredoc */ efree(Z_STRVAL(op2->u.constant)); return; } if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_add_variable(znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_VAR; if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_free(znode *op1 TSRMLS_DC) /* {{{ */ { if (op1->op_type==IS_TMP_VAR) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else if (op1->op_type==IS_VAR) { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; while (opline->opcode == ZEND_END_SILENCE || opline->opcode == ZEND_EXT_FCALL_END || opline->opcode == ZEND_OP_DATA) { opline--; } if (opline->result_type == IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_FETCH_R || opline->opcode == ZEND_FETCH_DIM_R || opline->opcode == ZEND_FETCH_OBJ_R || opline->opcode == ZEND_QM_ASSIGN_VAR) { /* It's very rare and useless case. It's better to use additional FREE opcode and simplify the FETCH handlers their selves */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else { opline->result_type |= EXT_TYPE_UNUSED; } } else { while (opline>CG(active_op_array)->opcodes) { if (opline->opcode == ZEND_FETCH_DIM_R && opline->op1_type == IS_VAR && opline->op1.var == op1->u.op.var) { /* This should the end of a list() construct * Mark its result as unused */ opline->extended_value = ZEND_FETCH_STANDARD; break; } else if (opline->result_type==IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_NEW) { opline->result_type |= EXT_TYPE_UNUSED; } break; } opline--; } } } else if (op1->op_type == IS_CONST) { zval_dtor(&op1->u.constant); } } /* }}} */ int zend_do_verify_access_types(const znode *current_access_type, const znode *new_modifier) /* {{{ */ { if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_PPP_MASK) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Multiple access type modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_ABSTRACT) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Multiple abstract modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_STATIC) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Multiple static modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_FINAL) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Multiple final modifiers are not allowed"); } if (((Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)) & (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) == (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Cannot use the final modifier on an abstract class member"); } return (Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)); } /* }}} */ void zend_do_begin_function_declaration(znode *function_token, znode *function_name, int is_method, int return_reference, znode *fn_flags_znode TSRMLS_DC) /* {{{ */ { zend_op_array op_array; char *name = function_name->u.constant.value.str.val; int name_len = function_name->u.constant.value.str.len; int function_begin_line = function_token->u.op.opline_num; zend_uint fn_flags; const char *lcname; zend_bool orig_interactive; ALLOCA_FLAG(use_heap) if (is_method) { if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((Z_LVAL(fn_flags_znode->u.constant) & ~(ZEND_ACC_STATIC|ZEND_ACC_PUBLIC))) { zend_error(E_COMPILE_ERROR, "Access type for interface method %s::%s() must be omitted", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } Z_LVAL(fn_flags_znode->u.constant) |= ZEND_ACC_ABSTRACT; /* propagates to the rest of the parser */ } fn_flags = Z_LVAL(fn_flags_znode->u.constant); /* must be done *after* the above check */ } else { fn_flags = 0; } if ((fn_flags & ZEND_ACC_STATIC) && (fn_flags & ZEND_ACC_ABSTRACT) && !(CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_STRICT, "Static function %s%s%s() should not be abstract", is_method ? CG(active_class_entry)->name : "", is_method ? "::" : "", Z_STRVAL(function_name->u.constant)); } function_token->u.op_array = CG(active_op_array); orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(&op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; op_array.function_name = name; if (return_reference) { op_array.fn_flags |= ZEND_ACC_RETURN_REFERENCE; } op_array.fn_flags |= fn_flags; op_array.scope = is_method?CG(active_class_entry):NULL; op_array.prototype = NULL; op_array.line_start = zend_get_compiled_lineno(TSRMLS_C); if (is_method) { int result; lcname = zend_new_interned_string(zend_str_tolower_dup(name, name_len), name_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lcname)) { result = zend_hash_quick_add(&CG(active_class_entry)->function_table, lcname, name_len+1, INTERNED_HASH(lcname), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } else { result = zend_hash_add(&CG(active_class_entry)->function_table, lcname, name_len+1, &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } if (result == FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::%s()", CG(active_class_entry)->name, name); } zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); if (fn_flags & ZEND_ACC_ABSTRACT) { CG(active_class_entry)->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (!(fn_flags & ZEND_ACC_PPP_MASK)) { fn_flags |= ZEND_ACC_PUBLIC; } if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } } } else { char *class_lcname; class_lcname = do_alloca(CG(active_class_entry)->name_length + 1, use_heap); zend_str_tolower_copy(class_lcname, CG(active_class_entry)->name, CG(active_class_entry)->name_length); /* Improve after RC: cache the lowercase class name */ if ((CG(active_class_entry)->name_length == name_len) && ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT) && (!memcmp(class_lcname, lcname, name_len))) { if (!CG(active_class_entry)->constructor) { CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } } else if ((name_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)))) { if (CG(active_class_entry)->constructor) { zend_error(E_STRICT, "Redefining already defined constructor for class %s", CG(active_class_entry)->name); } CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1))) { CG(active_class_entry)->destructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1))) { CG(active_class_entry)->clone = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } CG(active_class_entry)->__call = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } CG(active_class_entry)->__callstatic = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } CG(active_class_entry)->__get = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } CG(active_class_entry)->__set = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } CG(active_class_entry)->__unset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } CG(active_class_entry)->__isset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } CG(active_class_entry)->__tostring = (zend_function *) CG(active_op_array); } else if (!(fn_flags & ZEND_ACC_STATIC)) { CG(active_op_array)->fn_flags |= ZEND_ACC_ALLOW_STATIC; } free_alloca(class_lcname, use_heap); } str_efree(lcname); } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zval key; if (CG(current_namespace)) { /* Prefix function name with current namespcae name */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, function_name TSRMLS_CC); op_array.function_name = Z_STRVAL(tmp.u.constant); name_len = Z_STRLEN(tmp.u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), name_len); } else { lcname = zend_str_tolower_dup(name, name_len); } opline->opcode = ZEND_DECLARE_FUNCTION; opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, name_len TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; LITERAL_STRINGL(opline->op2, lcname, name_len, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); opline->extended_value = ZEND_DECLARE_FUNCTION; zend_hash_quick_update(CG(function_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); } if (CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_NOP; opline->lineno = function_begin_line; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } { /* Push a seperator to the switch and foreach stacks */ zend_switch_entry switch_entry; switch_entry.cond.op_type = IS_UNUSED; switch_entry.default_case = 0; switch_entry.control_var = 0; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); { /* Foreach stack separator */ zend_op dummy_opline; dummy_opline.result_type = IS_UNUSED; dummy_opline.op1_type = IS_UNUSED; zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); } } if (CG(doc_comment)) { CG(active_op_array)->doc_comment = CG(doc_comment); CG(active_op_array)->doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_begin_lambda_function_declaration(znode *result, znode *function_token, int return_reference, int is_static TSRMLS_DC) /* {{{ */ { znode function_name; zend_op_array *current_op_array = CG(active_op_array); int current_op_number = get_next_op_number(CG(active_op_array)); zend_op *current_op; function_name.op_type = IS_CONST; ZVAL_STRINGL(&function_name.u.constant, "{closure}", sizeof("{closure}")-1, 1); zend_do_begin_function_declaration(function_token, &function_name, 0, return_reference, NULL TSRMLS_CC); result->op_type = IS_TMP_VAR; result->u.op.var = get_temporary_variable(current_op_array); current_op = &current_op_array->opcodes[current_op_number]; current_op->opcode = ZEND_DECLARE_LAMBDA_FUNCTION; zend_del_literal(current_op_array, current_op->op2.constant); SET_UNUSED(current_op->op2); SET_NODE(current_op->result, result); if (is_static) { CG(active_op_array)->fn_flags |= ZEND_ACC_STATIC; } CG(active_op_array)->fn_flags |= ZEND_ACC_CLOSURE; } /* }}} */ void zend_do_handle_exception(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_HANDLE_EXCEPTION; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_function_declaration(const znode *function_token TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; zend_do_extended_info(TSRMLS_C); zend_do_return(NULL, 0 TSRMLS_CC); pass_two(CG(active_op_array) TSRMLS_CC); zend_release_labels(TSRMLS_C); if (CG(active_class_entry)) { zend_check_magic_method_implementation(CG(active_class_entry), (zend_function*)CG(active_op_array), E_COMPILE_ERROR TSRMLS_CC); } else { /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(CG(active_op_array)->function_name); zend_str_tolower_copy(lcname, CG(active_op_array)->function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME)) && CG(active_op_array)->num_args != 1) { zend_error(E_COMPILE_ERROR, "%s() must take exactly 1 argument", ZEND_AUTOLOAD_FUNC_NAME); } } CG(active_op_array)->line_end = zend_get_compiled_lineno(TSRMLS_C); CG(active_op_array) = function_token->u.op_array; /* Pop the switch and foreach seperators */ zend_stack_del_top(&CG(switch_cond_stack)); zend_stack_del_top(&CG(foreach_copy_stack)); } /* }}} */ void zend_do_receive_arg(zend_uchar op, znode *varname, const znode *offset, const znode *initialization, znode *class_type, zend_uchar pass_by_reference TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_arg_info *cur_arg_info; znode var; if (class_type->op_type == IS_CONST && Z_TYPE(class_type->u.constant) == IS_STRING && Z_STRLEN(class_type->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_type->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } if (zend_is_auto_global_quick(Z_STRVAL(varname->u.constant), Z_STRLEN(varname->u.constant), 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign auto-global variable %s", Z_STRVAL(varname->u.constant)); } else { var.op_type = IS_CV; var.u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(varname->u.constant) = (char*)CG(active_op_array)->vars[var.u.op.var].name; var.EA = 0; if (CG(active_op_array)->vars[var.u.op.var].hash_value == THIS_HASHVAL && Z_STRLEN(varname->u.constant) == sizeof("this")-1 && !memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this")-1)) { if (CG(active_op_array)->scope && (CG(active_op_array)->fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } CG(active_op_array)->this_var = var.u.op.var; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->num_args++; opline->opcode = op; SET_NODE(opline->result, &var); SET_NODE(opline->op1, offset); if (op == ZEND_RECV_INIT) { SET_NODE(opline->op2, initialization); } else { CG(active_op_array)->required_num_args = CG(active_op_array)->num_args; SET_UNUSED(opline->op2); } CG(active_op_array)->arg_info = erealloc(CG(active_op_array)->arg_info, sizeof(zend_arg_info)*(CG(active_op_array)->num_args)); cur_arg_info = &CG(active_op_array)->arg_info[CG(active_op_array)->num_args-1]; cur_arg_info->name = zend_new_interned_string(estrndup(varname->u.constant.value.str.val, varname->u.constant.value.str.len), varname->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->name_len = varname->u.constant.value.str.len; cur_arg_info->type_hint = 0; cur_arg_info->allow_null = 1; cur_arg_info->pass_by_reference = pass_by_reference; cur_arg_info->class_name = NULL; cur_arg_info->class_name_len = 0; if (class_type->op_type != IS_UNUSED) { cur_arg_info->allow_null = 0; if (class_type->u.constant.type != IS_NULL) { if (class_type->u.constant.type == IS_ARRAY) { cur_arg_info->type_hint = IS_ARRAY; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else if (Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Default value for parameters with array type hint can only be an array or NULL"); } } } else if (class_type->u.constant.type == IS_CALLABLE) { cur_arg_info->type_hint = IS_CALLABLE; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with callable type hint can only be NULL"); } } } else { cur_arg_info->type_hint = IS_OBJECT; if (ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_type->u.constant), Z_STRLEN(class_type->u.constant))) { zend_resolve_class_name(class_type, opline->extended_value, 1 TSRMLS_CC); } Z_STRVAL(class_type->u.constant) = (char*)zend_new_interned_string(class_type->u.constant.value.str.val, class_type->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->class_name = class_type->u.constant.value.str.val; cur_arg_info->class_name_len = class_type->u.constant.value.str.len; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with a class type hint can only be NULL"); } } } } } } /* }}} */ int zend_do_begin_function_call(znode *function_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { zend_function *function; char *lcname; char *is_compound = memchr(Z_STRVAL(function_name->u.constant), '\\', Z_STRLEN(function_name->u.constant)); zend_resolve_non_class_name(function_name, check_namespace TSRMLS_CC); if (check_namespace && CG(current_namespace) && !is_compound) { /* We assume we call function from the current namespace if it is not prefixed. */ /* In run-time PHP will check for function with full name and internal function with short name */ zend_do_begin_dynamic_function_call(function_name, 1 TSRMLS_CC); return 1; } lcname = zend_str_tolower_dup(function_name->u.constant.value.str.val, function_name->u.constant.value.str.len); if ((zend_hash_find(CG(function_table), lcname, function_name->u.constant.value.str.len+1, (void **) &function)==FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_FUNCTIONS) && (function->type == ZEND_INTERNAL_FUNCTION))) { zend_do_begin_dynamic_function_call(function_name, 0 TSRMLS_CC); efree(lcname); return 1; /* Dynamic */ } efree(function_name->u.constant.value.str.val); function_name->u.constant.value.str.val = lcname; zend_stack_push(&CG(function_call_stack), (void *) &function, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 0; } /* }}} */ void zend_do_begin_method_call(znode *left_bracket TSRMLS_DC) /* {{{ */ { zend_op *last_op; int last_op_number; unsigned char *ptr = NULL; zend_do_end_variable_parse(left_bracket, BP_VAR_R, 0 TSRMLS_CC); zend_do_begin_variable_parse(TSRMLS_C); last_op_number = get_next_op_number(CG(active_op_array))-1; last_op = &CG(active_op_array)->opcodes[last_op_number]; if ((last_op->op2_type == IS_CONST) && (Z_TYPE(CONSTANT(last_op->op2.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(last_op->op2.constant)) == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !zend_binary_strcasecmp(Z_STRVAL(CONSTANT(last_op->op2.constant)), Z_STRLEN(CONSTANT(last_op->op2.constant)), ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1)) { zend_error(E_COMPILE_ERROR, "Cannot call __clone() method on objects - use 'clone $obj' instead"); } if (last_op->opcode == ZEND_FETCH_OBJ_R) { if (last_op->op2_type == IS_CONST) { zval name; name = CONSTANT(last_op->op2.constant); if (!IS_INTERNED(Z_STRVAL(name))) { Z_STRVAL(name) = estrndup(Z_STRVAL(name), Z_STRLEN(name)); } FREE_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); last_op->op2.constant = zend_add_func_name_literal(CG(active_op_array), &name TSRMLS_CC); GET_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); } last_op->opcode = ZEND_INIT_METHOD_CALL; SET_UNUSED(last_op->result); Z_LVAL(left_bracket->u.constant) = ZEND_INIT_FCALL_BY_NAME; } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (left_bracket->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &left_bracket->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, left_bracket); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_do_clone(znode *result, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CLONE; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_begin_dynamic_function_call(znode *function_name, int ns_call TSRMLS_DC) /* {{{ */ { unsigned char *ptr = NULL; zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (ns_call) { /* In run-time PHP will check for function with full name and internal function with short name */ opline->opcode = ZEND_INIT_NS_FCALL_BY_NAME; SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_ns_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (function_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, function_name); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_resolve_non_class_name(znode *element_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; int len; zval **ns; char *lcname, *compound = memchr(Z_STRVAL(element_name->u.constant), '\\', Z_STRLEN(element_name->u.constant)); if (Z_STRVAL(element_name->u.constant)[0] == '\\') { /* name starts with \ so it is known and unambiguos, nothing to do here but shorten it */ memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+1, Z_STRLEN(element_name->u.constant)); --Z_STRLEN(element_name->u.constant); return; } if(!check_namespace) { return; } if (compound && CG(current_import)) { len = compound - Z_STRVAL(element_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(element_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(element_name->u.constant) -= len; memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+len, Z_STRLEN(element_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, element_name TSRMLS_CC); *element_name = tmp; efree(lcname); return; } efree(lcname); } if (CG(current_namespace)) { tmp = *element_name; Z_STRLEN(tmp.u.constant) = sizeof("\\")-1 + Z_STRLEN(element_name->u.constant) + Z_STRLEN_P(CG(current_namespace)); Z_STRVAL(tmp.u.constant) = (char *) emalloc(Z_STRLEN(tmp.u.constant)+1); memcpy(Z_STRVAL(tmp.u.constant), Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace))]), "\\", sizeof("\\")-1); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace)) + sizeof("\\")-1]), Z_STRVAL(element_name->u.constant), Z_STRLEN(element_name->u.constant)+1); STR_FREE(Z_STRVAL(element_name->u.constant)); *element_name = tmp; } } /* }}} */ void zend_resolve_class_name(znode *class_name, ulong fetch_type, int check_ns_name TSRMLS_DC) /* {{{ */ { char *compound; char *lcname; zval **ns; znode tmp; int len; compound = memchr(Z_STRVAL(class_name->u.constant), '\\', Z_STRLEN(class_name->u.constant)); if (compound) { /* This is a compound class name that contains namespace prefix */ if (Z_STRVAL(class_name->u.constant)[0] == '\\') { /* The STRING name has "\" prefix */ Z_STRLEN(class_name->u.constant) -= 1; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+1, Z_STRLEN(class_name->u.constant)+1); Z_STRVAL(class_name->u.constant) = erealloc( Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1); if (ZEND_FETCH_CLASS_DEFAULT != zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "'\\%s' is an invalid class name", Z_STRVAL(class_name->u.constant)); } } else { if (CG(current_import)) { len = compound - Z_STRVAL(class_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(class_name->u.constant) -= len; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+len, Z_STRLEN(class_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; efree(lcname); return; } efree(lcname); } /* Here name is not prefixed with \ and not imported */ if (CG(current_namespace)) { tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } } } else if (CG(current_import) || CG(current_namespace)) { /* this is a plain name (without \) */ lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns) == SUCCESS) { /* The given name is an import name. Substitute it. */ zval_dtor(&class_name->u.constant); class_name->u.constant = **ns; zval_copy_ctor(&class_name->u.constant); } else if (CG(current_namespace)) { /* plain name, no import - prepend current namespace to it */ tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } efree(lcname); } } /* }}} */ void zend_do_fetch_class(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { long fetch_class_op_number; zend_op *opline; if (class_name->op_type == IS_CONST && Z_TYPE(class_name->u.constant) == IS_STRING && Z_STRLEN(class_name->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_name->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } fetch_class_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CLASS; SET_UNUSED(opline->op1); opline->extended_value = ZEND_FETCH_CLASS_GLOBAL; CG(catch_begin) = fetch_class_op_number; if (class_name->op_type == IS_CONST) { int fetch_type; fetch_type = zend_get_class_fetch_type(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); switch (fetch_type) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: SET_UNUSED(opline->op2); opline->extended_value = fetch_type; zval_dtor(&class_name->u.constant); break; default: zend_resolve_class_name(class_name, opline->extended_value, 0 TSRMLS_CC); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_name->u.constant TSRMLS_CC); break; } } else { SET_NODE(opline->op2, class_name); } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; /* FIXME: Hack so that INIT_FCALL_BY_NAME still knows this is a class */ GET_NODE(result, opline->result); result->EA = opline->extended_value; } /* }}} */ void zend_do_label(znode *label TSRMLS_DC) /* {{{ */ { zend_label dest; if (!CG(context).labels) { ALLOC_HASHTABLE(CG(context).labels); zend_hash_init(CG(context).labels, 4, NULL, NULL, 0); } dest.brk_cont = CG(context).current_brk_cont; dest.opline_num = get_next_op_number(CG(active_op_array)); if (zend_hash_add(CG(context).labels, Z_STRVAL(label->u.constant), Z_STRLEN(label->u.constant) + 1, (void**)&dest, sizeof(zend_label), NULL) == FAILURE) { zend_error(E_COMPILE_ERROR, "Label '%s' already defined", Z_STRVAL(label->u.constant)); } /* Done with label now */ zval_dtor(&label->u.constant); } /* }}} */ void zend_resolve_goto_label(zend_op_array *op_array, zend_op *opline, int pass2 TSRMLS_DC) /* {{{ */ { zend_label *dest; long current, distance; zval *label; if (pass2) { label = opline->op2.zv; } else { label = &CONSTANT_EX(op_array, opline->op2.constant); } if (CG(context).labels == NULL || zend_hash_find(CG(context).labels, Z_STRVAL_P(label), Z_STRLEN_P(label)+1, (void**)&dest) == FAILURE) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; zend_error(E_COMPILE_ERROR, "'goto' to undefined label '%s'", Z_STRVAL_P(label)); } else { /* Label is not defined. Delay to pass 2. */ INC_BPC(op_array); return; } } opline->op1.opline_num = dest->opline_num; zval_dtor(label); Z_TYPE_P(label) = IS_NULL; /* Check that we are not moving into loop or switch */ current = opline->extended_value; for (distance = 0; current != dest->brk_cont; distance++) { if (current == -1) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; } zend_error(E_COMPILE_ERROR, "'goto' into loop or switch statement is disallowed"); } current = op_array->brk_cont_array[current].parent; } if (distance == 0) { /* Nothing to break out of, optimize to ZEND_JMP */ opline->opcode = ZEND_JMP; opline->extended_value = 0; SET_UNUSED(opline->op2); } else { /* Set real break distance */ ZVAL_LONG(label, distance); } if (pass2) { DEC_BPC(op_array); } } /* }}} */ void zend_do_goto(const znode *label TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_GOTO; opline->extended_value = CG(context).current_brk_cont; SET_UNUSED(opline->op1); SET_NODE(opline->op2, label); zend_resolve_goto_label(CG(active_op_array), opline, 0 TSRMLS_CC); } /* }}} */ void zend_release_labels(TSRMLS_D) /* {{{ */ { if (CG(context).labels) { zend_hash_destroy(CG(context).labels); FREE_HASHTABLE(CG(context).labels); } if (!zend_stack_is_empty(&CG(context_stack))) { zend_compiler_context *ctx; zend_stack_top(&CG(context_stack), (void**)&ctx); CG(context) = *ctx; zend_stack_del_top(&CG(context_stack)); } } /* }}} */ void zend_do_build_full_name(znode *result, znode *prefix, znode *name, int is_class_member TSRMLS_DC) /* {{{ */ { zend_uint length; if (!result) { result = prefix; } else { *result = *prefix; } if (is_class_member) { length = sizeof("::")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "::", sizeof("::")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("::")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } else { length = sizeof("\\")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "\\", sizeof("\\")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("\\")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } } /* }}} */ int zend_do_begin_class_member_function_call(znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { znode class_node; unsigned char *ptr = NULL; zend_op *opline; if (method_name->op_type == IS_CONST) { char *lcname = zend_str_tolower_dup(Z_STRVAL(method_name->u.constant), Z_STRLEN(method_name->u.constant)); if ((sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == Z_STRLEN(method_name->u.constant) && memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == 0) { zval_dtor(&method_name->u.constant); method_name->op_type = IS_UNUSED; } efree(lcname); } if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; opline = get_next_op(CG(active_op_array) TSRMLS_CC); } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->extended_value = class_node.EA ; } opline->opcode = ZEND_INIT_STATIC_METHOD_CALL; if (class_node.op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, &class_node); } if (method_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &method_name->u.constant TSRMLS_CC); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } } else { SET_NODE(opline->op2, method_name); } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 1; /* Dynamic */ } /* }}} */ void zend_do_end_function_call(znode *function_name, znode *result, const znode *argument_list, int is_method, int is_dynamic_fcall TSRMLS_DC) /* {{{ */ { zend_op *opline; if (is_method && function_name && function_name->op_type == IS_UNUSED) { /* clone */ if (Z_LVAL(argument_list->u.constant) != 0) { zend_error(E_WARNING, "Clone method does not require arguments"); } opline = &CG(active_op_array)->opcodes[Z_LVAL(function_name->u.constant)]; } else { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (!is_method && !is_dynamic_fcall && function_name->op_type==IS_CONST) { opline->opcode = ZEND_DO_FCALL; SET_NODE(opline->op1, function_name); CALCULATE_LITERAL_HASH(opline->op1.constant); GET_CACHE_SLOT(opline->op1.constant); } else { opline->opcode = ZEND_DO_FCALL_BY_NAME; SET_UNUSED(opline->op1); } } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(result, opline->result) ; SET_UNUSED(opline->op2); zend_stack_del_top(&CG(function_call_stack)); opline->extended_value = Z_LVAL(argument_list->u.constant); } /* }}} */ void zend_do_pass_param(znode *param, zend_uchar op, int offset TSRMLS_DC) /* {{{ */ { zend_op *opline; int original_op=op; zend_function **function_ptr_ptr, *function_ptr; int send_by_reference; int send_function = 0; zend_stack_top(&CG(function_call_stack), (void **) &function_ptr_ptr); function_ptr = *function_ptr_ptr; if (original_op == ZEND_SEND_REF) { if (function_ptr && function_ptr->common.function_name && function_ptr->common.type == ZEND_USER_FUNCTION && !ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed; " "If you would like to pass argument by reference, modify the declaration of %s().", function_ptr->common.function_name); } else { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed"); } return; } if (function_ptr) { if (ARG_MAY_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { if (param->op_type & (IS_VAR|IS_CV) && original_op != ZEND_SEND_VAL) { send_by_reference = 1; if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION | ZEND_ARG_SEND_SILENT; } } else { op = ZEND_SEND_VAL; send_by_reference = 0; } } else { send_by_reference = ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset) ? ZEND_ARG_SEND_BY_REF : 0; } } else { send_by_reference = 0; } if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION; } else if (op == ZEND_SEND_VAL && (param->op_type & (IS_VAR|IS_CV))) { op = ZEND_SEND_VAR_NO_REF; } if (op!=ZEND_SEND_VAR_NO_REF && send_by_reference==ZEND_ARG_SEND_BY_REF) { /* change to passing by reference */ switch (param->op_type) { case IS_VAR: case IS_CV: op = ZEND_SEND_REF; break; default: zend_error(E_COMPILE_ERROR, "Only variables can be passed by reference"); break; } } if (original_op == ZEND_SEND_VAR) { switch (op) { case ZEND_SEND_VAR_NO_REF: zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); break; case ZEND_SEND_VAR: if (function_ptr) { zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(param, BP_VAR_FUNC_ARG, offset TSRMLS_CC); } break; case ZEND_SEND_REF: zend_do_end_variable_parse(param, BP_VAR_W, 0 TSRMLS_CC); break; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (op == ZEND_SEND_VAR_NO_REF) { if (function_ptr) { opline->extended_value = ZEND_ARG_COMPILE_TIME_BOUND | send_by_reference | send_function; } else { opline->extended_value = send_function; } } else { if (function_ptr) { opline->extended_value = ZEND_DO_FCALL; } else { opline->extended_value = ZEND_DO_FCALL_BY_NAME; } } opline->opcode = op; SET_NODE(opline->op1, param); opline->op2.opline_num = offset; SET_UNUSED(opline->op2); } /* }}} */ static int generate_free_switch_expr(const zend_switch_entry *switch_entry TSRMLS_DC) /* {{{ */ { zend_op *opline; if (switch_entry->cond.op_type != IS_VAR && switch_entry->cond.op_type != IS_TMP_VAR) { return (switch_entry->cond.op_type == IS_UNUSED); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry->cond); SET_UNUSED(opline->op2); opline->extended_value = 0; return 0; } /* }}} */ static int generate_free_foreach_copy(const zend_op *foreach_copy TSRMLS_DC) /* {{{ */ { zend_op *opline; /* If we reach the seperator then stop applying the stack */ if (foreach_copy->result_type == IS_UNUSED && foreach_copy->op1_type == IS_UNUSED) { return 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->result_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->result); SET_UNUSED(opline->op2); opline->extended_value = 1; if (foreach_copy->op1_type != IS_UNUSED) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->op1_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->op1); SET_UNUSED(opline->op2); opline->extended_value = 0; } return 0; } /* }}} */ void zend_do_return(znode *expr, int do_end_vparse TSRMLS_DC) /* {{{ */ { zend_op *opline; int start_op_number, end_op_number; if (do_end_vparse) { if ((CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) && !zend_is_function_or_method_call(expr)) { zend_do_end_variable_parse(expr, BP_VAR_W, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(expr, BP_VAR_R, 0 TSRMLS_CC); } } start_op_number = get_next_op_number(CG(active_op_array)); #ifdef ZTS zend_stack_apply_with_argument(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_switch_expr TSRMLS_CC); zend_stack_apply_with_argument(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_foreach_copy TSRMLS_CC); #else zend_stack_apply(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_switch_expr); zend_stack_apply(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_foreach_copy); #endif end_op_number = get_next_op_number(CG(active_op_array)); while (start_op_number < end_op_number) { CG(active_op_array)->opcodes[start_op_number].extended_value |= EXT_TYPE_FREE_ON_RETURN; start_op_number++; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) ? ZEND_RETURN_BY_REF : ZEND_RETURN; if (expr) { SET_NODE(opline->op1, expr); if (do_end_vparse && zend_is_function_or_method_call(expr)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } } else { opline->op1_type = IS_CONST; LITERAL_NULL(opline->op1); } SET_UNUSED(opline->op2); } /* }}} */ static int zend_add_try_element(zend_uint try_op TSRMLS_DC) /* {{{ */ { int try_catch_offset = CG(active_op_array)->last_try_catch++; CG(active_op_array)->try_catch_array = erealloc(CG(active_op_array)->try_catch_array, sizeof(zend_try_catch_element)*CG(active_op_array)->last_try_catch); CG(active_op_array)->try_catch_array[try_catch_offset].try_op = try_op; return try_catch_offset; } /* }}} */ static void zend_add_catch_element(int offset, zend_uint catch_op TSRMLS_DC) /* {{{ */ { CG(active_op_array)->try_catch_array[offset].catch_op = catch_op; } /* }}} */ void zend_do_first_catch(znode *open_parentheses TSRMLS_DC) /* {{{ */ { open_parentheses->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_initialize_try_catch_element(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist jmp_list; zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); zend_add_catch_element(try_token->u.op.opline_num, get_next_op_number(CG(active_op_array)) TSRMLS_CC); } /* }}} */ void zend_do_mark_last_catch(const znode *first_catch, const znode *last_additional_catch TSRMLS_DC) /* {{{ */ { CG(active_op_array)->last--; zend_do_if_end(TSRMLS_C); if (last_additional_catch->u.op.opline_num == -1) { CG(active_op_array)->opcodes[first_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[first_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } else { CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_try(znode *try_token TSRMLS_DC) /* {{{ */ { try_token->u.op.opline_num = zend_add_try_element(get_next_op_number(CG(active_op_array)) TSRMLS_CC); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_catch(znode *try_token, znode *class_name, znode *catch_var, znode *first_catch TSRMLS_DC) /* {{{ */ { long catch_op_number; zend_op *opline; znode catch_class; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); catch_class = *class_name; } else { zend_error(E_COMPILE_ERROR, "Bad class name in the catch statement"); } catch_op_number = get_next_op_number(CG(active_op_array)); if (first_catch) { first_catch->u.op.opline_num = catch_op_number; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CATCH; opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &catch_class.u.constant TSRMLS_CC); opline->op2_type = IS_CV; opline->op2.var = lookup_cv(CG(active_op_array), catch_var->u.constant.value.str.val, catch_var->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(catch_var->u.constant) = (char*)CG(active_op_array)->vars[opline->op2.var].name; opline->result.num = 0; /* 1 means it's the last catch in the block */ try_token->u.op.opline_num = catch_op_number; } /* }}} */ void zend_do_end_catch(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); CG(active_op_array)->opcodes[try_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_throw(const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_THROW; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); } /* }}} */ ZEND_API void function_add_ref(zend_function *function) /* {{{ */ { if (function->type == ZEND_USER_FUNCTION) { zend_op_array *op_array = &function->op_array; (*op_array->refcount)++; if (op_array->static_variables) { HashTable *static_variables = op_array->static_variables; zval *tmp_zval; ALLOC_HASHTABLE(op_array->static_variables); zend_hash_init(op_array->static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(op_array->static_variables, static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_zval, sizeof(zval *)); } op_array->run_time_cache = NULL; } } /* }}} */ static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */ { zend_function *function; if (!ce->parent) { return; } /* You cannot change create_object */ ce->create_object = ce->parent->create_object; /* Inherit special functions if needed */ if (!ce->get_iterator) { ce->get_iterator = ce->parent->get_iterator; } if (!ce->iterator_funcs.funcs) { ce->iterator_funcs.funcs = ce->parent->iterator_funcs.funcs; } if (!ce->__get) { ce->__get = ce->parent->__get; } if (!ce->__set) { ce->__set = ce->parent->__set; } if (!ce->__unset) { ce->__unset = ce->parent->__unset; } if (!ce->__isset) { ce->__isset = ce->parent->__isset; } if (!ce->__call) { ce->__call = ce->parent->__call; } if (!ce->__callstatic) { ce->__callstatic = ce->parent->__callstatic; } if (!ce->__tostring) { ce->__tostring = ce->parent->__tostring; } if (!ce->clone) { ce->clone = ce->parent->clone; } if(!ce->serialize) { ce->serialize = ce->parent->serialize; } if(!ce->unserialize) { ce->unserialize = ce->parent->unserialize; } if (!ce->destructor) { ce->destructor = ce->parent->destructor; } if (ce->constructor) { if (ce->parent->constructor && ce->parent->constructor->common.fn_flags & ZEND_ACC_FINAL) { zend_error(E_ERROR, "Cannot override final %s::%s() with %s::%s()", ce->parent->name, ce->parent->constructor->common.function_name, ce->name, ce->constructor->common.function_name ); } return; } if (zend_hash_find(&ce->parent->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), (void **)&function)==SUCCESS) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), function, sizeof(zend_function), NULL); function_add_ref(function); } else { /* Don't inherit the old style constructor if we already have the new style constructor */ char *lc_class_name; char *lc_parent_class_name; lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); if (!zend_hash_exists(&ce->function_table, lc_class_name, ce->name_length+1)) { lc_parent_class_name = zend_str_tolower_dup(ce->parent->name, ce->parent->name_length); if (!zend_hash_exists(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1) && zend_hash_find(&ce->parent->function_table, lc_parent_class_name, ce->parent->name_length+1, (void **)&function)==SUCCESS) { if (function->common.fn_flags & ZEND_ACC_CTOR) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1, function, sizeof(zend_function), NULL); function_add_ref(function); } } efree(lc_parent_class_name); } efree(lc_class_name); } ce->constructor = ce->parent->constructor; } /* }}} */ char *zend_visibility_string(zend_uint fn_flags) /* {{{ */ { if (fn_flags & ZEND_ACC_PRIVATE) { return "private"; } if (fn_flags & ZEND_ACC_PROTECTED) { return "protected"; } if (fn_flags & ZEND_ACC_PUBLIC) { return "public"; } return ""; } /* }}} */ static void do_inherit_method(zend_function *function) /* {{{ */ { /* The class entry of the derived function intentionally remains the same * as that of the parent class. That allows us to know in which context * we're running, and handle private method calls properly. */ function_add_ref(function); } /* }}} */ static zend_bool zend_do_perform_implementation_check(const zend_function *fe, const zend_function *proto TSRMLS_DC) /* {{{ */ { zend_uint i; /* If it's a user function then arg_info == NULL means we don't have any parameters but * we still need to do the arg number checks. We are only willing to ignore this for internal * functions because extensions don't always define arg_info. */ if (!proto || (!proto->common.arg_info && proto->common.type != ZEND_USER_FUNCTION)) { return 1; } /* Checks for constructors only if they are declared in an interface, * or explicitly marked as abstract */ if ((fe->common.fn_flags & ZEND_ACC_CTOR) && ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)) { return 1; } /* check number of arguments */ if (proto->common.required_num_args < fe->common.required_num_args || proto->common.num_args > fe->common.num_args) { return 0; } if (fe->common.type != ZEND_USER_FUNCTION && (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) != 0 && (fe->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) == 0) { return 0; } /* by-ref constraints on return values are covariant */ if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) { return 0; } for (i=0; i < proto->common.num_args; i++) { if (ZEND_LOG_XOR(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)) { /* Only one has a type hint and the other one doesn't */ return 0; } if (fe->common.arg_info[i].class_name && strcasecmp(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)!=0) { const char *colon; if (fe->common.type != ZEND_USER_FUNCTION) { return 0; } else if (strchr(proto->common.arg_info[i].class_name, '\\') != NULL || (colon = zend_memrchr(fe->common.arg_info[i].class_name, '\\', fe->common.arg_info[i].class_name_len)) == NULL || strcasecmp(colon+1, proto->common.arg_info[i].class_name) != 0) { zend_class_entry **fe_ce, **proto_ce; int found, found2; found = zend_lookup_class(fe->common.arg_info[i].class_name, fe->common.arg_info[i].class_name_len, &fe_ce TSRMLS_CC); found2 = zend_lookup_class(proto->common.arg_info[i].class_name, proto->common.arg_info[i].class_name_len, &proto_ce TSRMLS_CC); /* Check for class alias */ if (found != SUCCESS || found2 != SUCCESS || (*fe_ce)->type == ZEND_INTERNAL_CLASS || (*proto_ce)->type == ZEND_INTERNAL_CLASS || *fe_ce != *proto_ce) { return 0; } } } if (fe->common.arg_info[i].type_hint != proto->common.arg_info[i].type_hint) { /* Incompatible type hint */ return 0; } /* by-ref constraints on arguments are invariant */ if (fe->common.arg_info[i].pass_by_reference != proto->common.arg_info[i].pass_by_reference) { return 0; } } if (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) { for (i=proto->common.num_args; i < fe->common.num_args; i++) { if (!fe->common.arg_info[i].pass_by_reference) { return 0; } } } return 1; } /* }}} */ #define REALLOC_BUF_IF_EXCEED(buf, offset, length, size) \ if (UNEXPECTED(offset - buf + size >= length)) { \ length += size + 1; \ buf = erealloc(buf, length); \ } static char * zend_get_function_declaration(zend_function *fptr TSRMLS_DC) /* {{{ */ { char *offset, *buf; zend_uint length = 1024; offset = buf = (char *)emalloc(length * sizeof(char)); if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { *(offset++) = '&'; *(offset++) = ' '; } if (fptr->common.scope) { memcpy(offset, fptr->common.scope->name, fptr->common.scope->name_length); offset += fptr->common.scope->name_length; *(offset++) = ':'; *(offset++) = ':'; } { size_t name_len = strlen(fptr->common.function_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, name_len); memcpy(offset, fptr->common.function_name, name_len); offset += name_len; } *(offset++) = '('; if (fptr->common.arg_info) { zend_uint i, required; zend_arg_info *arg_info = fptr->common.arg_info; required = fptr->common.required_num_args; for (i = 0; i < fptr->common.num_args;) { if (arg_info->class_name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->class_name_len); memcpy(offset, arg_info->class_name, arg_info->class_name_len); offset += arg_info->class_name_len; *(offset++) = ' '; } else if (arg_info->type_hint) { zend_uint type_name_len; char *type_name = zend_get_type_by_const(arg_info->type_hint); type_name_len = strlen(type_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, type_name_len); memcpy(offset, type_name, type_name_len); offset += type_name_len; *(offset++) = ' '; } if (arg_info->pass_by_reference) { *(offset++) = '&'; } *(offset++) = '$'; if (arg_info->name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->name_len); memcpy(offset, arg_info->name, arg_info->name_len); offset += arg_info->name_len; } else { zend_uint idx = i; memcpy(offset, "param", 5); offset += 5; do { *(offset++) = (char) (idx % 10) + '0'; idx /= 10; } while (idx > 0); } if (i >= required) { *(offset++) = ' '; *(offset++) = '='; *(offset++) = ' '; if (fptr->type == ZEND_USER_FUNCTION) { zend_op *precv = NULL; { zend_uint idx = i; zend_op *op = ((zend_op_array *)fptr)->opcodes; zend_op *end = op + ((zend_op_array *)fptr)->last; ++idx; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT) && op->op1.num == (long)idx) { precv = op; } ++op; } } if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) { zval *zv, zv_copy; int use_copy; ALLOC_ZVAL(zv); *zv = *precv->op2.zv; zval_copy_ctor(zv); INIT_PZVAL(zv); zval_update_constant_ex(&zv, (void*)1, fptr->common.scope TSRMLS_CC); if (Z_TYPE_P(zv) == IS_BOOL) { if (Z_LVAL_P(zv)) { memcpy(offset, "true", 4); offset += 4; } else { memcpy(offset, "false", 5); offset += 5; } } else if (Z_TYPE_P(zv) == IS_NULL) { memcpy(offset, "NULL", 4); offset += 4; } else if (Z_TYPE_P(zv) == IS_STRING) { *(offset++) = '\''; REALLOC_BUF_IF_EXCEED(buf, offset, length, MIN(Z_STRLEN_P(zv), 10)); memcpy(offset, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 10)); offset += MIN(Z_STRLEN_P(zv), 10); if (Z_STRLEN_P(zv) > 10) { *(offset++) = '.'; *(offset++) = '.'; *(offset++) = '.'; } *(offset++) = '\''; } else if (Z_TYPE_P(zv) == IS_ARRAY) { memcpy(offset, "Array", 5); offset += 5; } else { zend_make_printable_zval(zv, &zv_copy, &use_copy); REALLOC_BUF_IF_EXCEED(buf, offset, length, Z_STRLEN(zv_copy)); memcpy(offset, Z_STRVAL(zv_copy), Z_STRLEN(zv_copy)); offset += Z_STRLEN(zv_copy); if (use_copy) { zval_dtor(&zv_copy); } } zval_ptr_dtor(&zv); } } else { memcpy(offset, "NULL", 4); offset += 4; } } if (++i < fptr->common.num_args) { *(offset++) = ','; *(offset++) = ' '; } arg_info++; REALLOC_BUF_IF_EXCEED(buf, offset, length, 32); } } *(offset++) = ')'; *offset = '\0'; return buf; } /* }}} */ static void do_inheritance_check_on_method(zend_function *child, zend_function *parent TSRMLS_DC) /* {{{ */ { zend_uint child_flags; zend_uint parent_flags = parent->common.fn_flags; if (parent->common.fn_flags & ZEND_ACC_ABSTRACT && parent->common.scope != (child->common.prototype ? child->common.prototype->common.scope : child->common.scope) && child->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_IMPLEMENTED_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Can't inherit abstract function %s::%s() (previously declared abstract in %s)", parent->common.scope->name, child->common.function_name, child->common.prototype ? child->common.prototype->common.scope->name : child->common.scope->name); } if (parent_flags & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot override final method %s::%s()", ZEND_FN_SCOPE_NAME(parent), child->common.function_name); } child_flags = child->common.fn_flags; /* You cannot change from static to non static and vice versa. */ if ((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC)) { if (child->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot make non static method %s::%s() static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } else { zend_error(E_COMPILE_ERROR, "Cannot make static method %s::%s() non static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } } /* Disallow making an inherited method abstract. */ if ((child_flags & ZEND_ACC_ABSTRACT) && !(parent_flags & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Cannot make non abstract method %s::%s() abstract in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } if (parent_flags & ZEND_ACC_CHANGED) { child->common.fn_flags |= ZEND_ACC_CHANGED; } else { /* Prevent derived classes from restricting access that was available in parent classes */ if ((child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::%s() must be %s (as in class %s)%s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if (((child_flags & ZEND_ACC_PPP_MASK) < (parent_flags & ZEND_ACC_PPP_MASK)) && ((parent_flags & ZEND_ACC_PPP_MASK) & ZEND_ACC_PRIVATE)) { child->common.fn_flags |= ZEND_ACC_CHANGED; } } if (parent_flags & ZEND_ACC_PRIVATE) { child->common.prototype = NULL; } else if (parent_flags & ZEND_ACC_ABSTRACT) { child->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; child->common.prototype = parent; } else if (!(parent->common.fn_flags & ZEND_ACC_CTOR) || (parent->common.prototype && (parent->common.prototype->common.scope->ce_flags & ZEND_ACC_INTERFACE))) { /* ctors only have a prototype if it comes from an interface */ child->common.prototype = parent->common.prototype ? parent->common.prototype : parent; } if (child->common.prototype && (child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { if (!zend_do_perform_implementation_check(child, child->common.prototype TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s::%s() must be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_get_function_declaration(child->common.prototype TSRMLS_CC)); } } else if (EG(error_reporting) & E_STRICT || EG(user_error_handler)) { /* Check E_STRICT (or custom error handler) before the check so that we save some time */ if (!zend_do_perform_implementation_check(child, parent TSRMLS_CC)) { char *method_prototype = zend_get_function_declaration(child->common.prototype TSRMLS_CC); zend_error(E_STRICT, "Declaration of %s::%s() should be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, method_prototype); efree(method_prototype); } } } /* }}} */ static zend_bool do_inherit_method_check(HashTable *child_function_table, zend_function *parent, const zend_hash_key *hash_key, zend_class_entry *child_ce) /* {{{ */ { zend_uint parent_flags = parent->common.fn_flags; zend_function *child; TSRMLS_FETCH(); if (zend_hash_quick_find(child_function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child)==FAILURE) { if (parent_flags & (ZEND_ACC_ABSTRACT)) { child_ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } return 1; /* method doesn't exist in child, copy from parent */ } do_inheritance_check_on_method(child, parent TSRMLS_CC); return 0; } /* }}} */ static zend_bool do_inherit_property_access_check(HashTable *target_ht, zend_property_info *parent_info, const zend_hash_key *hash_key, zend_class_entry *ce) /* {{{ */ { zend_property_info *child_info; zend_class_entry *parent_ce = ce->parent; if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW)) { if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { child_info->flags |= ZEND_ACC_CHANGED; } else { zend_hash_quick_update(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, parent_info, sizeof(zend_property_info), (void **) &child_info); if(ce->type & ZEND_INTERNAL_CLASS) { zend_duplicate_property_info_internal(child_info); } else { zend_duplicate_property_info(child_info); } child_info->flags &= ~ZEND_ACC_PRIVATE; /* it's not private anymore */ child_info->flags |= ZEND_ACC_SHADOW; /* but it's a shadow of private */ } return 0; /* don't copy access information to child */ } if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { if ((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s", (parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", parent_ce->name, hash_key->arKey, (child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ce->name, hash_key->arKey); } if(parent_info->flags & ZEND_ACC_CHANGED) { child_info->flags |= ZEND_ACC_CHANGED; } if ((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ce->name, hash_key->arKey, zend_visibility_string(parent_info->flags), parent_ce->name, (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if ((child_info->flags & ZEND_ACC_STATIC) == 0) { Z_DELREF_P(ce->default_properties_table[parent_info->offset]); ce->default_properties_table[parent_info->offset] = ce->default_properties_table[child_info->offset]; ce->default_properties_table[child_info->offset] = NULL; child_info->offset = parent_info->offset; } return 0; /* Don't copy from parent */ } else { return 1; /* Copy from parent */ } } /* }}} */ static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce TSRMLS_CC) == FAILURE) { zend_error(E_CORE_ERROR, "Class %s could not implement interface %s", ce->name, iface->name); } if (ce == iface) { zend_error(E_ERROR, "Interface %s cannot implement itself", ce->name); } } /* }}} */ ZEND_API void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface TSRMLS_DC) /* {{{ */ { /* expects interface to be contained in ce's interface list already */ zend_uint i, ce_num, if_num = iface->num_interfaces; zend_class_entry *entry; if (if_num==0) { return; } ce_num = ce->num_interfaces; if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } /* Inherit the interfaces, only if they're not already inherited by the class */ while (if_num--) { entry = iface->interfaces[if_num]; for (i = 0; i < ce_num; i++) { if (ce->interfaces[i] == entry) { break; } } if (i == ce_num) { ce->interfaces[ce->num_interfaces++] = entry; } } /* and now call the implementing handlers */ while (ce_num < ce->num_interfaces) { do_implement_interface(ce, ce->interfaces[ce_num++] TSRMLS_CC); } } /* }}} */ #ifdef ZTS static void zval_internal_ctor(zval **p) /* {{{ */ { zval *orig_ptr = *p; ALLOC_ZVAL(*p); MAKE_COPY_ZVAL(&orig_ptr, *p); } /* }}} */ # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) (((parent_ce)->type != (ce)->type) ? zval_internal_ctor : zval_add_ref)) #else # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) zval_add_ref) #endif ZEND_API void zend_do_inheritance(zend_class_entry *ce, zend_class_entry *parent_ce TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; if ((ce->ce_flags & ZEND_ACC_INTERFACE) && !(parent_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ce->name, parent_ce->name); } if (parent_ce->ce_flags & ZEND_ACC_FINAL_CLASS) { zend_error(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ce->name, parent_ce->name); } ce->parent = parent_ce; /* Copy serialize/unserialize callbacks */ if (!ce->serialize) { ce->serialize = parent_ce->serialize; } if (!ce->unserialize) { ce->unserialize = parent_ce->unserialize; } /* Inherit interfaces */ zend_do_inherit_interfaces(ce, parent_ce TSRMLS_CC); /* Inherit properties */ if (parent_ce->default_properties_count) { int i = ce->default_properties_count + parent_ce->default_properties_count; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_properties_count) { while (i-- > parent_ce->default_properties_count) { ce->default_properties_table[i] = ce->default_properties_table[i - parent_ce->default_properties_count]; } } for (i = 0; i < parent_ce->default_properties_count; i++) { ce->default_properties_table[i] = parent_ce->default_properties_table[i]; if (ce->default_properties_table[i]) { #ifdef ZTS if (parent_ce->type != ce->type) { zval *p; ALLOC_ZVAL(p); MAKE_COPY_ZVAL(&ce->default_properties_table[i], p); ce->default_properties_table[i] = p; } else { Z_ADDREF_P(ce->default_properties_table[i]); } #else Z_ADDREF_P(ce->default_properties_table[i]); #endif } } ce->default_properties_count += parent_ce->default_properties_count; } if (parent_ce->type != ce->type) { /* User class extends internal class */ zend_update_class_constants(parent_ce TSRMLS_CC); if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = erealloc(ce->default_static_members_table, sizeof(void*) * i); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&CE_STATIC_MEMBERS(parent_ce)[i]); ce->default_static_members_table[i] = CE_STATIC_MEMBERS(parent_ce)[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; ce->static_members_table = ce->default_static_members_table; } } else { if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&parent_ce->default_static_members_table[i]); ce->default_static_members_table[i] = parent_ce->default_static_members_table[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } } for (zend_hash_internal_pointer_reset(&ce->properties_info); zend_hash_get_current_data(&ce->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->properties_info)) { if (property_info->ce == ce) { if (property_info->flags & ZEND_ACC_STATIC) { property_info->offset += parent_ce->default_static_members_count; } else { property_info->offset += parent_ce->default_properties_count; } } } zend_hash_merge_ex(&ce->properties_info, &parent_ce->properties_info, (copy_ctor_func_t) (ce->type & ZEND_INTERNAL_CLASS ? zend_duplicate_property_info_internal : zend_duplicate_property_info), sizeof(zend_property_info), (merge_checker_func_t) do_inherit_property_access_check, ce); zend_hash_merge(&ce->constants_table, &parent_ce->constants_table, zval_property_ctor(parent_ce, ce), NULL, sizeof(zval *), 0); zend_hash_merge_ex(&ce->function_table, &parent_ce->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_inherit_parent_constructor(ce); if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS && ce->type == ZEND_INTERNAL_CLASS) { ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } else if (!(ce->ce_flags & ZEND_ACC_IMPLEMENT_INTERFACES) && !(ce->ce_flags & ZEND_ACC_IMPLEMENT_TRAITS)) { /* The verification will be done in runtime by ZEND_VERIFY_ABSTRACT_CLASS */ zend_verify_abstract_class(ce TSRMLS_CC); } ce->ce_flags |= parent_ce->ce_flags & ZEND_HAS_STATIC_IN_METHODS; } /* }}} */ static zend_bool do_inherit_constant_check(HashTable *child_constants_table, const zval **parent_constant, const zend_hash_key *hash_key, const zend_class_entry *iface) /* {{{ */ { zval **old_constant; if (zend_hash_quick_find(child_constants_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**)&old_constant) == SUCCESS) { if (*old_constant != *parent_constant) { zend_error(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", hash_key->arKey, iface->name); } return 0; } return 1; } /* }}} */ static int do_interface_constant_check(zval **val TSRMLS_DC, int num_args, va_list args, const zend_hash_key *key) /* {{{ */ { zend_class_entry **iface = va_arg(args, zend_class_entry**); do_inherit_constant_check(&(*iface)->constants_table, (const zval **) val, key, *iface); return ZEND_HASH_APPLY_KEEP; } /* }}} */ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_iface_num = ce->num_interfaces; zend_uint parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0; for (i = 0; i < ce->num_interfaces; i++) { if (ce->interfaces[i] == NULL) { memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i)); i--; } else if (ce->interfaces[i] == iface) { if (i < parent_iface_num) { ignore = 1; } else { zend_error(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ce->name, iface->name); } } } if (ignore) { /* Check for attempt to redeclare interface constants */ zend_hash_apply_with_arguments(&ce->constants_table TSRMLS_CC, (apply_func_args_t) do_interface_constant_check, 1, &iface); } else { if (ce->num_interfaces >= current_iface_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } } ce->interfaces[ce->num_interfaces++] = iface; zend_hash_merge_ex(&ce->constants_table, &iface->constants_table, (copy_ctor_func_t) zval_add_ref, sizeof(zval *), (merge_checker_func_t) do_inherit_constant_check, iface); zend_hash_merge_ex(&ce->function_table, &iface->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_implement_interface(ce, iface TSRMLS_CC); zend_do_inherit_interfaces(ce, iface TSRMLS_CC); } } /* }}} */ ZEND_API void zend_do_implement_trait(zend_class_entry *ce, zend_class_entry *trait TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_trait_num = ce->num_traits; zend_uint parent_trait_num = ce->parent ? ce->parent->num_traits : 0; for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == NULL) { memmove(ce->traits + i, ce->traits + i + 1, sizeof(zend_class_entry*) * (--ce->num_traits - i)); i--; } else if (ce->traits[i] == trait) { if (i < parent_trait_num) { ignore = 1; } } } if (!ignore) { if (ce->num_traits >= current_trait_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->traits = (zend_class_entry **) realloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } else { ce->traits = (zend_class_entry **) erealloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } } ce->traits[ce->num_traits++] = trait; } } /* }}} */ static int zend_traits_merge_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { size_t current; size_t i; size_t count; HashTable* resulting_table; HashTable** function_tables; zend_class_entry *ce; size_t collision = 0; size_t abstract_solved = 0; zend_function* other_trait_fn; current = va_arg(args, size_t); /* index of current trait */ count = va_arg(args, size_t); resulting_table = va_arg(args, HashTable*); function_tables = va_arg(args, HashTable**); ce = va_arg(args, zend_class_entry*); for (i = 0; i < count; i++) { if (i == current) { continue; /* just skip this, cause its the table this function is applied on */ } if (zend_hash_quick_find(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&other_trait_fn) == SUCCESS) { /* if it is an abstract method, there is no collision */ if (other_trait_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* In case both are abstract, just check prototype, but need to do that in both directions */ if ( !zend_do_perform_implementation_check(fn, other_trait_fn TSRMLS_CC) || !zend_do_perform_implementation_check(other_trait_fn, fn TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s must be compatible with %s", //ZEND_FN_SCOPE_NAME(fn), fn->common.function_name, //::%s() zend_get_function_declaration(fn TSRMLS_CC), zend_get_function_declaration(other_trait_fn TSRMLS_CC)); } } else { /* otherwise, do the full check */ do_inheritance_check_on_method(fn, other_trait_fn TSRMLS_CC); } /* we can savely free and remove it from other table */ zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } else { /* if it is not an abstract method, there is still no collision */ /* if fn is an abstract method */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible. Here, we already know other_trait_fn cannot be abstract, full check ok. */ do_inheritance_check_on_method(other_trait_fn, fn TSRMLS_CC); /* just mark as solved, will be added if its own trait is processed */ abstract_solved = 1; } else { /* but else, we have a collision of non-abstract methods */ collision++; zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } } } if (collision) { zend_function* class_fn; /* make sure method is not already overridden in class */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&class_fn) == FAILURE || class_fn->common.scope != ce) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because there are collisions with other trait methods on %s", fn->common.function_name, ce->name); } zend_function_dtor(fn); } else if (abstract_solved) { zend_function_dtor(fn); } else { /* Add it to result function table */ if (zend_hash_quick_add(resulting_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, fn, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating resulting trait method table", fn->common.function_name); } } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ /* {{{ Originates from php_runkit_function_copy_ctor Duplicate structures in an op_array where necessary to make an outright duplicate */ static void zend_traits_duplicate_function(zend_function *fe, zend_class_entry *target_ce, char *newname TSRMLS_DC) { zend_literal *literals_copy; zend_compiled_variable *dupvars; zend_op *opcode_copy; zval class_name_zv; int class_name_literal; int i; int number_of_literals; if (fe->op_array.static_variables) { HashTable *tmpHash; ALLOC_HASHTABLE(tmpHash); zend_hash_init(tmpHash, zend_hash_num_elements(fe->op_array.static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_apply_with_arguments(fe->op_array.static_variables TSRMLS_CC, (apply_func_args_t)zval_copy_static_var, 1, tmpHash); fe->op_array.static_variables = tmpHash; } number_of_literals = fe->op_array.last_literal; literals_copy = (zend_literal*)emalloc(number_of_literals * sizeof(zend_literal)); for (i = 0; i < number_of_literals; i++) { literals_copy[i] = fe->op_array.literals[i]; zval_copy_ctor(&literals_copy[i].constant); } fe->op_array.literals = literals_copy; fe->op_array.refcount = emalloc(sizeof(zend_uint)); *(fe->op_array.refcount) = 1; if (fe->op_array.vars) { i = fe->op_array.last_var; dupvars = safe_emalloc(fe->op_array.last_var, sizeof(zend_compiled_variable), 0); while (i > 0) { i--; dupvars[i].name = estrndup(fe->op_array.vars[i].name, fe->op_array.vars[i].name_len); dupvars[i].name_len = fe->op_array.vars[i].name_len; dupvars[i].hash_value = fe->op_array.vars[i].hash_value; } fe->op_array.vars = dupvars; } else { fe->op_array.vars = NULL; } opcode_copy = safe_emalloc(sizeof(zend_op), fe->op_array.last, 0); for(i = 0; i < fe->op_array.last; i++) { opcode_copy[i] = fe->op_array.opcodes[i]; if (opcode_copy[i].op1_type != IS_CONST) { switch (opcode_copy[i].opcode) { case ZEND_GOTO: case ZEND_JMP: if (opcode_copy[i].op1.jmp_addr && opcode_copy[i].op1.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op1.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op1.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op1.jmp_addr - fe->op_array.opcodes); } break; } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op1.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op1.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op1.zv = &fe->op_array.literals[class_name_literal].constant; } } if (opcode_copy[i].op2_type != IS_CONST) { switch (opcode_copy[i].opcode) { case ZEND_JMPZ: case ZEND_JMPNZ: case ZEND_JMPZ_EX: case ZEND_JMPNZ_EX: case ZEND_JMP_SET: case ZEND_JMP_SET_VAR: if (opcode_copy[i].op2.jmp_addr && opcode_copy[i].op2.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op2.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op2.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op2.jmp_addr - fe->op_array.opcodes); } break; } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op2.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op2.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op2.zv = &fe->op_array.literals[class_name_literal].constant; } } } fe->op_array.opcodes = opcode_copy; fe->op_array.function_name = newname; /* was setting it to fe which does not work since fe is stack allocated and not a stable address */ /* fe->op_array.prototype = fe->op_array.prototype; */ if (fe->op_array.arg_info) { zend_arg_info *tmpArginfo; tmpArginfo = safe_emalloc(sizeof(zend_arg_info), fe->op_array.num_args, 0); for(i = 0; i < fe->op_array.num_args; i++) { tmpArginfo[i] = fe->op_array.arg_info[i]; tmpArginfo[i].name = estrndup(tmpArginfo[i].name, tmpArginfo[i].name_len); if (tmpArginfo[i].class_name) { tmpArginfo[i].class_name = estrndup(tmpArginfo[i].class_name, tmpArginfo[i].class_name_len); } } fe->op_array.arg_info = tmpArginfo; } fe->op_array.doc_comment = estrndup(fe->op_array.doc_comment, fe->op_array.doc_comment_len); fe->op_array.try_catch_array = (zend_try_catch_element*)estrndup((char*)fe->op_array.try_catch_array, sizeof(zend_try_catch_element) * fe->op_array.last_try_catch); fe->op_array.brk_cont_array = (zend_brk_cont_element*)estrndup((char*)fe->op_array.brk_cont_array, sizeof(zend_brk_cont_element) * fe->op_array.last_brk_cont); } /* }}} */ static void zend_add_magic_methods(zend_class_entry* ce, const char* mname, uint mname_len, zend_function* fe TSRMLS_DC) /* {{{ */ { if (!strncmp(mname, ZEND_CLONE_FUNC_NAME, mname_len)) { ce->clone = fe; fe->common.fn_flags |= ZEND_ACC_CLONE; } else if (!strncmp(mname, ZEND_CONSTRUCTOR_FUNC_NAME, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } else if (!strncmp(mname, ZEND_DESTRUCTOR_FUNC_NAME, mname_len)) { ce->destructor = fe; fe->common.fn_flags |= ZEND_ACC_DTOR; } else if (!strncmp(mname, ZEND_GET_FUNC_NAME, mname_len)) { ce->__get = fe; } else if (!strncmp(mname, ZEND_SET_FUNC_NAME, mname_len)) { ce->__set = fe; } else if (!strncmp(mname, ZEND_CALL_FUNC_NAME, mname_len)) { ce->__call = fe; } else if (!strncmp(mname, ZEND_UNSET_FUNC_NAME, mname_len)) { ce->__unset = fe; } else if (!strncmp(mname, ZEND_ISSET_FUNC_NAME, mname_len)) { ce->__isset = fe; } else if (!strncmp(mname, ZEND_CALLSTATIC_FUNC_NAME, mname_len)) { ce->__callstatic = fe; } else if (!strncmp(mname, ZEND_TOSTRING_FUNC_NAME, mname_len)) { ce->__tostring = fe; } else if (ce->name_length + 1 == mname_len) { char *lowercase_name = emalloc(ce->name_length + 1); zend_str_tolower_copy(lowercase_name, ce->name, ce->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, ce->name_length + 1, 1 TSRMLS_CC); if (!memcmp(mname, lowercase_name, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } str_efree(lowercase_name); } } /* }}} */ static int zend_traits_merge_functions_to_class(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zend_class_entry *ce = va_arg(args, zend_class_entry*); int add = 0; zend_function* existing_fn = NULL; zend_function fn_copy, *fn_copy_p; zend_function* prototype = NULL; /* is used to determine the prototype according to the inheritance chain */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &existing_fn) == FAILURE) { add = 1; /* not found */ } else if (existing_fn->common.scope != ce) { add = 1; /* or inherited from other class or interface */ } if (add) { zend_function* parent_function; if (ce->parent && zend_hash_quick_find(&ce->parent->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &parent_function) != FAILURE) { prototype = parent_function; /* ->common.fn_flags |= ZEND_ACC_ABSTRACT; */ /* we got that method in the parent class, and are going to override it, except, if the trait is just asking to have an abstract method implemented. */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* then we clean up an skip this method */ zend_function_dtor(fn); return ZEND_HASH_APPLY_REMOVE; } } fn->common.scope = ce; fn->common.prototype = prototype; if (prototype && (prototype->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT || prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { fn->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; } else if (fn->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT) { /* remove ZEND_ACC_IMPLEMENTED_ABSTRACT flag, think it shouldn't be copied to class */ fn->common.fn_flags = fn->common.fn_flags - ZEND_ACC_IMPLEMENTED_ABSTRACT; } /* check whether the trait method fullfills the inheritance requirements */ if (prototype) { do_inheritance_check_on_method(fn, prototype TSRMLS_CC); } /* one more thing: make sure we properly implement an abstract method */ if (existing_fn && existing_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { do_inheritance_check_on_method(fn, existing_fn TSRMLS_CC); } /* delete inherited fn if the function to be added is not abstract */ if (existing_fn && existing_fn->common.scope != ce && (fn->common.fn_flags & ZEND_ACC_ABSTRACT) == 0) { /* it is just a reference which was added to the subclass while doing the inheritance, so we can deleted now, and will add the overriding method afterwards. Except, if we try to add an abstract function, then we should not delete the inherited one */ zend_hash_quick_del(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h); } if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (fn->op_array.static_variables) { ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, ce, estrdup(fn->common.function_name) TSRMLS_CC); if (zend_hash_quick_update(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, &fn_copy, sizeof(zend_function), (void**)&fn_copy_p)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating class method table", hash_key->arKey); } zend_add_magic_methods(ce, hash_key->arKey, hash_key->nKeyLength, fn_copy_p TSRMLS_CC); zend_function_dtor(fn); } else { zend_function_dtor(fn); } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ static int zend_traits_copy_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { HashTable* target; zend_class_entry *target_ce; zend_trait_alias** aliases; HashTable* exclude_table; char* lcname; unsigned int fnname_len; zend_function fn_copy; void* dummy; size_t i = 0; target = va_arg(args, HashTable*); target_ce = va_arg(args, zend_class_entry*); aliases = va_arg(args, zend_trait_alias**); exclude_table = va_arg(args, HashTable*); fnname_len = strlen(fn->common.function_name); /* apply aliases which are qualified with a class name, there should not be any ambiguity */ if (aliases) { while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias != NULL && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && aliases[i]->trait_method->mname_len == fnname_len && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(aliases[i]->alias, aliases[i]->alias_len) TSRMLS_CC); /* if it is 0, no modifieres has been changed */ if (aliases[i]->modifiers) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } lcname = zend_str_tolower_dup(aliases[i]->alias, aliases[i]->alias_len); if (zend_hash_add(target, lcname, aliases[i]->alias_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add aliased trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } efree(lcname); /** Record the trait from which this alias was resolved. */ if (!aliases[i]->trait_method->ce) { aliases[i]->trait_method->ce = fn->common.scope; } } i++; } } lcname = zend_str_tolower_dup(fn->common.function_name, fnname_len); if (exclude_table == NULL || zend_hash_find(exclude_table, lcname, fnname_len, &dummy) == FAILURE) { /* is not in hashtable, thus, function is not to be excluded */ fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(fn->common.function_name, fnname_len) TSRMLS_CC); /* apply aliases which are not qualified by a class name, or which have not * alias name, just setting visibility */ if (aliases) { i = 0; while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias == NULL && aliases[i]->modifiers != 0 && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && (aliases[i]->trait_method->mname_len == fnname_len) && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); /** Record the trait from which this alias was resolved. */ if (!aliases[i]->trait_method->ce) { aliases[i]->trait_method->ce = fn->common.scope; } } i++; } } if (zend_hash_add(target, lcname, fnname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } } efree(lcname); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* Copies function table entries to target function table with applied aliasing */ static void zend_traits_copy_trait_function_table(HashTable *target, zend_class_entry *target_ce, HashTable *source, zend_trait_alias** aliases, HashTable* exclude_table TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_arguments(source TSRMLS_CC, (apply_func_args_t)zend_traits_copy_functions, 4, target, target_ce, aliases, exclude_table); } /* }}} */ static void zend_traits_init_trait_structures(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i, j = 0; zend_trait_precedence *cur_precedence; zend_trait_method_reference *cur_method_ref; char *lcname; zend_bool method_exists; /* resolve class references */ if (ce->trait_precedences) { i = 0; while ((cur_precedence = ce->trait_precedences[i])) { /** Resolve classes for all precedence operations. */ if (cur_precedence->exclude_from_classes) { cur_method_ref = cur_precedence->trait_method; cur_precedence->trait_method->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); /** Ensure that the prefered method is actually available. */ lcname = zend_str_tolower_dup(cur_method_ref->method_name, cur_method_ref->mname_len); method_exists = zend_hash_exists(&cur_method_ref->ce->function_table, lcname, cur_method_ref->mname_len + 1); efree(lcname); if (!method_exists) { zend_error(E_COMPILE_ERROR, "A precedence rule was defined for %s::%s but this method does not exist", cur_method_ref->ce->name, cur_method_ref->method_name); } /** With the other traits, we are more permissive. We do not give errors for those. This allows to be more defensive in such definitions. */ j = 0; while (cur_precedence->exclude_from_classes[j]) { char* class_name = (char*)cur_precedence->exclude_from_classes[j]; zend_uint name_length = strlen(class_name); cur_precedence->exclude_from_classes[j] = zend_fetch_class(class_name, name_length, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); efree(class_name); j++; } } i++; } } if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { /** For all aliases with an explicit class name, resolve the class now. */ if (ce->trait_aliases[i]->trait_method->class_name) { cur_method_ref = ce->trait_aliases[i]->trait_method; cur_method_ref->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); /** And, ensure that the referenced method is resolvable, too. */ lcname = zend_str_tolower_dup(cur_method_ref->method_name, cur_method_ref->mname_len); method_exists = zend_hash_exists(&cur_method_ref->ce->function_table, lcname, cur_method_ref->mname_len + 1); efree(lcname); if (!method_exists) { zend_error(E_COMPILE_ERROR, "An alias was defined for %s::%s but this method does not exist", cur_method_ref->ce->name, cur_method_ref->method_name); } } i++; } } } /* }}} */ static void zend_traits_compile_exclude_table(HashTable* exclude_table, zend_trait_precedence **precedences, zend_class_entry *trait) /* {{{ */ { size_t i = 0, j; if (!precedences) { return; } while (precedences[i]) { if (precedences[i]->exclude_from_classes) { j = 0; while (precedences[i]->exclude_from_classes[j]) { if (precedences[i]->exclude_from_classes[j] == trait) { zend_uint lcname_len = precedences[i]->trait_method->mname_len; char *lcname = zend_str_tolower_dup(precedences[i]->trait_method->method_name, lcname_len); if (zend_hash_add(exclude_table, lcname, lcname_len, NULL, 0, NULL) == FAILURE) { efree(lcname); zend_error(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", precedences[i]->trait_method->method_name, trait->name); } efree(lcname); } ++j; } } ++i; } } /* }}} */ static void zend_do_traits_method_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { HashTable** function_tables; HashTable* resulting_table; HashTable exclude_table; size_t i; /* prepare copies of trait function tables for combination */ function_tables = malloc(sizeof(HashTable*) * ce->num_traits); resulting_table = (HashTable *) malloc(sizeof(HashTable)); /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(resulting_table, 10, NULL, NULL, 1, 0); for (i = 0; i < ce->num_traits; i++) { function_tables[i] = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(function_tables[i], ce->traits[i]->function_table.nNumOfElements, NULL, NULL, 1, 0); if (ce->trait_precedences) { /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(&exclude_table, 2, NULL, NULL, 0, 0); zend_traits_compile_exclude_table(&exclude_table, ce->trait_precedences, ce->traits[i]); /* copies functions, applies defined aliasing, and excludes unused trait methods */ zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, &exclude_table TSRMLS_CC); zend_hash_graceful_destroy(&exclude_table); } else { zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, NULL TSRMLS_CC); } } /* now merge trait methods */ for (i = 0; i < ce->num_traits; i++) { zend_hash_apply_with_arguments(function_tables[i] TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions, 5, i, ce->num_traits, resulting_table, function_tables, ce); } /* Now the resulting_table contains all trait methods we would have to * add to the class in the following step the methods are inserted into the method table * if there is already a method with the same name it is replaced iff ce != fn.scope * --> all inherited methods are overridden, methods defined in the class are left untouched */ zend_hash_apply_with_arguments(resulting_table TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions_to_class, 1, ce); /* free temporary function tables */ for (i = 0; i < ce->num_traits; i++) { /* zend_hash_destroy(function_tables[i]); */ zend_hash_graceful_destroy(function_tables[i]); free(function_tables[i]); } free(function_tables); /* free temporary resulting table */ /* zend_hash_destroy(resulting_table); */ zend_hash_graceful_destroy(resulting_table); free(resulting_table); } /* }}} */ static zend_class_entry* find_first_definition(zend_class_entry *ce, size_t current_trait, const char* prop_name, int prop_name_length, ulong prop_hash, zend_class_entry *coliding_ce) /* {{{ */ { size_t i; zend_property_info *coliding_prop; for (i = 0; (i < current_trait) && (i < ce->num_traits); i++) { if (zend_hash_quick_find(&ce->traits[i]->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS) { return ce->traits[i]; } } return coliding_ce; } /* }}} */ static void zend_do_traits_property_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i; zend_property_info *property_info; zend_property_info *coliding_prop; zval compare_result; const char* prop_name; int prop_name_length; ulong prop_hash; const char* class_name_unused; zend_bool prop_found; zend_bool not_compatible; zval* prop_value; /* In the following steps the properties are inserted into the property table * for that, a very strict approach is applied: * - check for compatibility, if not compatible with any property in class -> fatal * - if compatible, then strict notice */ for (i = 0; i < ce->num_traits; i++) { for (zend_hash_internal_pointer_reset(&ce->traits[i]->properties_info); zend_hash_get_current_data(&ce->traits[i]->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->traits[i]->properties_info)) { /* first get the unmangeld name if necessary, * then check whether the property is already there */ if ((property_info->flags & ZEND_ACC_PPP_MASK) == ZEND_ACC_PUBLIC) { prop_hash = property_info->h; prop_name = property_info->name; prop_name_length = property_info->name_length; prop_found = zend_hash_quick_find(&ce->properties_info, property_info->name, property_info->name_length+1, property_info->h, (void **) &coliding_prop) == SUCCESS; } else { /* for private and protected we need to unmangle the names */ zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name_unused, &prop_name); prop_name_length = strlen(prop_name); prop_hash = zend_get_hash_value(prop_name, prop_name_length + 1); prop_found = zend_hash_quick_find(&ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS; } /* next: check for conflicts with current class */ if (prop_found) { if (coliding_prop->flags & ZEND_ACC_SHADOW) { /* this one is inherited, lets look it up in its own class */ zend_hash_quick_find(&coliding_prop->ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop); } if ((coliding_prop->flags & ZEND_ACC_PPP_MASK) == (property_info->flags & ZEND_ACC_PPP_MASK)) { /* flags are identical, now the value needs to be checked */ if (property_info->flags & ZEND_ACC_STATIC) { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_static_members_table[coliding_prop->offset], ce->traits[i]->default_static_members_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } else { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_properties_table[coliding_prop->offset], ce->traits[i]->default_properties_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } } else { /* the flags are not identical, thus, we assume properties are not compatible */ not_compatible = 1; } if (not_compatible) { zend_error(E_COMPILE_ERROR, "%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } else { zend_error(E_STRICT, "%s and %s define the same property ($%s) in the composition of %s. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } } /* property not found, so lets add it */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); zend_declare_property_ex(ce, prop_name, prop_name_length, prop_value, property_info->flags, property_info->doc_comment, property_info->doc_comment_len TSRMLS_CC); } } } /* }}} */ static void zend_do_check_for_inconsistent_traits_aliasing(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { int i = 0; zend_trait_alias* cur_alias; char* lc_method_name; if (ce->trait_aliases) { while (ce->trait_aliases[i]) { cur_alias = ce->trait_aliases[i]; /** The trait for this alias has not been resolved, this means, this alias was not applied. Abort with an error. */ if (!cur_alias->trait_method->ce) { if (cur_alias->alias) { /** Plain old inconsistency/typo/bug */ zend_error(E_COMPILE_ERROR, "An alias (%s) was defined for method %s(), but this method does not exist", cur_alias->alias, cur_alias->trait_method->method_name); } else { /** Here are two possible cases: 1) this is an attempt to modifiy the visibility of a method introduce as part of another alias. Since that seems to violate the DRY principle, we check against it and abort. 2) it is just a plain old inconsitency/typo/bug as in the case where alias is set. */ lc_method_name = zend_str_tolower_dup(cur_alias->trait_method->method_name, cur_alias->trait_method->mname_len); if (zend_hash_exists(&ce->function_table, lc_method_name, cur_alias->trait_method->mname_len+1)) { efree(lc_method_name); zend_error(E_COMPILE_ERROR, "The modifiers for the trait alias %s() need to be changed in the same statment in which the alias is defined. Error", cur_alias->trait_method->method_name); } else { efree(lc_method_name); zend_error(E_COMPILE_ERROR, "The modifiers of the trait method %s() are changed, but this method does not exist. Error", cur_alias->trait_method->method_name); } } } i++; } } } /* }}} */ ZEND_API void zend_do_bind_traits(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { if (ce->num_traits <= 0) { return; } /* complete initialization of trait strutures in ce */ zend_traits_init_trait_structures(ce TSRMLS_CC); /* first care about all methods to be flattened into the class */ zend_do_traits_method_binding(ce TSRMLS_CC); /* Aliases which have not been applied indicate typos/bugs. */ zend_do_check_for_inconsistent_traits_aliasing(ce TSRMLS_CC); /* then flatten the properties into it, to, mostly to notfiy developer about problems */ zend_do_traits_property_binding(ce TSRMLS_CC); /* verify that all abstract methods from traits have been implemented */ zend_verify_abstract_class(ce TSRMLS_CC); /* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */ if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { ce->ce_flags -= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } } /* }}} */ ZEND_API int do_bind_function(const zend_op_array *op_array, zend_op *opline, HashTable *function_table, zend_bool compile_time) /* {{{ */ { zend_function *function; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } zend_hash_quick_find(function_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void *) &function); if (zend_hash_quick_add(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), function, sizeof(zend_function), NULL)==FAILURE) { int error_level = compile_time ? E_COMPILE_ERROR : E_ERROR; zend_function *old_function; if (zend_hash_quick_find(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), (void *) &old_function)==SUCCESS && old_function->type == ZEND_USER_FUNCTION && old_function->op_array.last > 0) { zend_error(error_level, "Cannot redeclare %s() (previously declared in %s:%d)", function->common.function_name, old_function->op_array.filename, old_function->op_array.opcodes[0].lineno); } else { zend_error(error_level, "Cannot redeclare %s()", function->common.function_name); } return FAILURE; } else { (*function->op_array.refcount)++; function->op_array.static_variables = NULL; /* NULL out the unbound function */ return SUCCESS; } } /* }}} */ void zend_add_trait_precedence(znode *precedence_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_precedences, precedence_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_add_trait_alias(znode *alias_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_aliases, alias_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_prepare_reference(znode *result, znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { zend_trait_method_reference *method_ref = emalloc(sizeof(zend_trait_method_reference)); method_ref->ce = NULL; /* REM: There should not be a need for copying, zend_do_begin_class_declaration is also just using that string */ if (class_name) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); method_ref->class_name = Z_STRVAL(class_name->u.constant); method_ref->cname_len = Z_STRLEN(class_name->u.constant); } else { method_ref->class_name = NULL; method_ref->cname_len = 0; } method_ref->method_name = Z_STRVAL(method_name->u.constant); method_ref->mname_len = Z_STRLEN(method_name->u.constant); result->u.op.ptr = method_ref; result->op_type = IS_TMP_VAR; } /* }}} */ void zend_prepare_trait_alias(znode *result, znode *method_reference, znode *modifiers, znode *alias TSRMLS_DC) /* {{{ */ { zend_trait_alias *trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_alias->modifiers = Z_LVAL(modifiers->u.constant); if (Z_LVAL(modifiers->u.constant) == ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot use 'static' as method modifier"); return; } if (alias) { trait_alias->alias = Z_STRVAL(alias->u.constant); trait_alias->alias_len = Z_STRLEN(alias->u.constant); } else { trait_alias->alias = NULL; } trait_alias->function = NULL; result->u.op.ptr = trait_alias; } /* }}} */ void zend_prepare_trait_precedence(znode *result, znode *method_reference, znode *trait_list TSRMLS_DC) /* {{{ */ { zend_trait_precedence *trait_precedence = emalloc(sizeof(zend_trait_precedence)); trait_precedence->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_precedence->exclude_from_classes = (zend_class_entry**) trait_list->u.op.ptr; trait_precedence->function = NULL; result->u.op.ptr = trait_precedence; } /* }}} */ ZEND_API zend_class_entry *do_bind_class(const zend_op_array* op_array, const zend_op *opline, HashTable *class_table, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } if (zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce)==FAILURE) { zend_error(E_COMPILE_ERROR, "Internal Zend error - Missing class information for %s", Z_STRVAL_P(op1)); return NULL; } else { ce = *pce; } ce->refcount++; if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), &ce, sizeof(zend_class_entry *), NULL)==FAILURE) { ce->refcount--; if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return NULL; } else { if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLEMENT_INTERFACES))) { zend_verify_abstract_class(ce TSRMLS_CC); } return ce; } } /* }}} */ ZEND_API zend_class_entry *do_bind_inherited_class(const zend_op_array *op_array, const zend_op *opline, HashTable *class_table, zend_class_entry *parent_ce, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; int found_ce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } found_ce = zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce); if (found_ce == FAILURE) { if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", Z_STRVAL_P(op2)); } return NULL; } else { ce = *pce; } if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ce->name, parent_ce->name); } else if ((parent_ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ce->name, parent_ce->name); } zend_do_inheritance(ce, parent_ce TSRMLS_CC); ce->refcount++; /* Register the derived class */ if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), pce, sizeof(zend_class_entry *), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return ce; } /* }}} */ void zend_do_early_binding(TSRMLS_D) /* {{{ */ { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; HashTable *table; while (opline->opcode == ZEND_TICKS && opline > CG(active_op_array)->opcodes) { opline--; } switch (opline->opcode) { case ZEND_DECLARE_FUNCTION: if (do_bind_function(CG(active_op_array), opline, CG(function_table), 1) == FAILURE) { return; } table = CG(function_table); break; case ZEND_DECLARE_CLASS: if (do_bind_class(CG(active_op_array), opline, CG(class_table), 1 TSRMLS_CC) == NULL) { return; } table = CG(class_table); break; case ZEND_DECLARE_INHERITED_CLASS: { zend_op *fetch_class_opline = opline-1; zval *parent_name; zend_class_entry **pce; parent_name = &CONSTANT(fetch_class_opline->op2.constant); if ((zend_lookup_class(Z_STRVAL_P(parent_name), Z_STRLEN_P(parent_name), &pce TSRMLS_CC) == FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_CLASSES) && ((*pce)->type == ZEND_INTERNAL_CLASS))) { if (CG(compiler_options) & ZEND_COMPILE_DELAYED_BINDING) { zend_uint *opline_num = &CG(active_op_array)->early_binding; while (*opline_num != -1) { opline_num = &CG(active_op_array)->opcodes[*opline_num].result.opline_num; } *opline_num = opline - CG(active_op_array)->opcodes; opline->opcode = ZEND_DECLARE_INHERITED_CLASS_DELAYED; opline->result_type = IS_UNUSED; opline->result.opline_num = -1; } return; } if (do_bind_inherited_class(CG(active_op_array), opline, CG(class_table), *pce, 1 TSRMLS_CC) == NULL) { return; } /* clear unnecessary ZEND_FETCH_CLASS opcode */ zend_del_literal(CG(active_op_array), fetch_class_opline->op2.constant); MAKE_NOP(fetch_class_opline); table = CG(class_table); break; } case ZEND_VERIFY_ABSTRACT_CLASS: case ZEND_ADD_INTERFACE: case ZEND_ADD_TRAIT: case ZEND_BIND_TRAITS: /* We currently don't early-bind classes that implement interfaces */ /* Classes with traits are handled exactly the same, no early-bind here */ return; default: zend_error(E_COMPILE_ERROR, "Invalid binding type"); return; } zend_hash_quick_del(table, Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant)), Z_HASH_P(&CONSTANT(opline->op1.constant))); zend_del_literal(CG(active_op_array), opline->op1.constant); zend_del_literal(CG(active_op_array), opline->op2.constant); MAKE_NOP(opline); } /* }}} */ ZEND_API void zend_do_delayed_early_binding(const zend_op_array *op_array TSRMLS_DC) /* {{{ */ { if (op_array->early_binding != -1) { zend_bool orig_in_compilation = CG(in_compilation); zend_uint opline_num = op_array->early_binding; zend_class_entry **pce; CG(in_compilation) = 1; while (opline_num != -1) { if (zend_lookup_class(Z_STRVAL_P(op_array->opcodes[opline_num-1].op2.zv), Z_STRLEN_P(op_array->opcodes[opline_num-1].op2.zv), &pce TSRMLS_CC) == SUCCESS) { do_bind_inherited_class(op_array, &op_array->opcodes[opline_num], EG(class_table), *pce, 0 TSRMLS_CC); } opline_num = op_array->opcodes[opline_num].result.opline_num; } CG(in_compilation) = orig_in_compilation; } } /* }}} */ void zend_do_boolean_or_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_or_end(znode *result, const znode *expr1, const znode *expr2, znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_boolean_and_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_and_end(znode *result, const znode *expr1, const znode *expr2, const znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_do_while_begin(TSRMLS_D) /* {{{ */ { do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_do_while_end(const znode *do_token, const znode *expr_open_bracket, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ; SET_NODE(opline->op1, expr); opline->op2.opline_num = do_token->u.op.opline_num; SET_UNUSED(opline->op2); do_end_loop(expr_open_bracket->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_brk_cont(zend_uchar op, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->op1.opline_num = CG(context).current_brk_cont; SET_UNUSED(opline->op1); if (expr) { if (expr->op_type != IS_CONST) { zend_error(E_COMPILE_ERROR, "'%s' operator with non-constant operand is no longer supported", op == ZEND_BRK ? "break" : "continue"); } else if (Z_TYPE(expr->u.constant) != IS_LONG || Z_LVAL(expr->u.constant) < 1) { zend_error(E_COMPILE_ERROR, "'%s' operator accepts only positive numbers", op == ZEND_BRK ? "break" : "continue"); } SET_NODE(opline->op2, expr); } else { LITERAL_LONG(opline->op2, 1); opline->op2_type = IS_CONST; } } /* }}} */ void zend_do_switch_cond(const znode *cond TSRMLS_DC) /* {{{ */ { zend_switch_entry switch_entry; switch_entry.cond = *cond; switch_entry.default_case = -1; switch_entry.control_var = -1; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_switch_end(const znode *case_list TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); /* add code to jmp to default case */ if (switch_entry_ptr->default_case != -1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->op1.opline_num = switch_entry_ptr->default_case; } if (case_list->op_type != IS_UNUSED) { /* non-empty switch */ int next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* remember break/continue loop information */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; if (switch_entry_ptr->cond.op_type==IS_VAR || switch_entry_ptr->cond.op_type==IS_TMP_VAR) { /* emit free for the switch condition*/ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry_ptr->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_UNUSED(opline->op2); } if (switch_entry_ptr->cond.op_type == IS_CONST) { zval_dtor(&switch_entry_ptr->cond.u.constant); } zend_stack_del_top(&CG(switch_cond_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_case_before_statement(const znode *case_list, znode *case_token, const znode *case_expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); int next_op_number; zend_switch_entry *switch_entry_ptr; znode result; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); if (switch_entry_ptr->control_var == -1) { switch_entry_ptr->control_var = get_temporary_variable(CG(active_op_array)); } opline->opcode = ZEND_CASE; opline->result.var = switch_entry_ptr->control_var; opline->result_type = IS_TMP_VAR; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_NODE(opline->op2, case_expr); if (opline->op1_type == IS_CONST) { zval_copy_ctor(&CONSTANT(opline->op1.constant)); } GET_NODE(&result, opline->result); next_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, &result); SET_UNUSED(opline->op2); case_token->u.op.opline_num = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_case_after_statement(znode *result, const znode *case_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); result->u.op.opline_num = next_op_number; switch (CG(active_op_array)->opcodes[case_token->u.op.opline_num].opcode) { case ZEND_JMP: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); break; case ZEND_JMPZ: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); break; } } /* }}} */ void zend_do_default_before_statement(const znode *case_list, znode *default_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); default_token->u.op.opline_num = next_op_number; next_op_number = get_next_op_number(CG(active_op_array)); switch_entry_ptr->default_case = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_begin_class_declaration(const znode *class_token, znode *class_name, const znode *parent_class_name TSRMLS_DC) /* {{{ */ { zend_op *opline; int doing_inheritance = 0; zend_class_entry *new_class_entry; char *lcname; int error = 0; zval **ns_name, key; if (CG(active_class_entry)) { zend_error(E_COMPILE_ERROR, "Class declarations may not be nested"); return; } lcname = zend_str_tolower_dup(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); if (!(strcmp(lcname, "self") && strcmp(lcname, "parent"))) { efree(lcname); zend_error(E_COMPILE_ERROR, "Cannot use '%s' as class name as it is reserved", Z_STRVAL(class_name->u.constant)); } /* Class name must not conflict with import names */ if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns_name) == SUCCESS) { error = 1; } if (CG(current_namespace)) { /* Prefix class name with name of current namespace */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); class_name = &tmp; efree(lcname); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); } if (error) { char *tmp = zend_str_tolower_dup(Z_STRVAL_PP(ns_name), Z_STRLEN_PP(ns_name)); if (Z_STRLEN_PP(ns_name) != Z_STRLEN(class_name->u.constant) || memcmp(tmp, lcname, Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "Cannot declare class %s because the name is already in use", Z_STRVAL(class_name->u.constant)); } efree(tmp); } new_class_entry = emalloc(sizeof(zend_class_entry)); new_class_entry->type = ZEND_USER_CLASS; new_class_entry->name = zend_new_interned_string(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1, 1 TSRMLS_CC); new_class_entry->name_length = Z_STRLEN(class_name->u.constant); zend_initialize_class_data(new_class_entry, 1 TSRMLS_CC); new_class_entry->info.user.filename = zend_get_compiled_filename(TSRMLS_C); new_class_entry->info.user.line_start = class_token->u.op.opline_num; new_class_entry->ce_flags |= class_token->EA; if (parent_class_name && parent_class_name->op_type != IS_UNUSED) { switch (parent_class_name->EA) { case ZEND_FETCH_CLASS_SELF: zend_error(E_COMPILE_ERROR, "Cannot use 'self' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_PARENT: zend_error(E_COMPILE_ERROR, "Cannot use 'parent' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use 'static' as class name as it is reserved"); break; default: break; } doing_inheritance = 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, new_class_entry->name_length TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; if (doing_inheritance) { /* Make sure a trait does not try to extend a class */ if ((new_class_entry->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "A trait (%s) cannot extend a class", new_class_entry->name); } opline->extended_value = parent_class_name->u.op.var; opline->opcode = ZEND_DECLARE_INHERITED_CLASS; } else { opline->opcode = ZEND_DECLARE_CLASS; } LITERAL_STRINGL(opline->op2, lcname, new_class_entry->name_length, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); zend_hash_quick_update(CG(class_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &new_class_entry, sizeof(zend_class_entry *), NULL); CG(active_class_entry) = new_class_entry; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(&CG(implementing_class), opline->result); if (CG(doc_comment)) { CG(active_class_entry)->info.user.doc_comment = CG(doc_comment); CG(active_class_entry)->info.user.doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ static void do_verify_abstract_class(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_VERIFY_ABSTRACT_CLASS; SET_NODE(opline->op1, &CG(implementing_class)); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_class_declaration(const znode *class_token, const znode *parent_token TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); if (ce->constructor) { ce->constructor->common.fn_flags |= ZEND_ACC_CTOR; if (ce->constructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Constructor %s::%s() cannot be static", ce->name, ce->constructor->common.function_name); } } if (ce->destructor) { ce->destructor->common.fn_flags |= ZEND_ACC_DTOR; if (ce->destructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Destructor %s::%s() cannot be static", ce->name, ce->destructor->common.function_name); } } if (ce->clone) { ce->clone->common.fn_flags |= ZEND_ACC_CLONE; if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static", ce->name, ce->clone->common.function_name); } } ce->info.user.line_end = zend_get_compiled_lineno(TSRMLS_C); /* Check for traits and proceed like with interfaces. * The only difference will be a combined handling of them in the end. * Thus, we need another opcode here. */ if (ce->num_traits > 0) { zend_op *opline; ce->traits = NULL; ce->num_traits = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_TRAITS; /* opcode generation: */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BIND_TRAITS; SET_NODE(opline->op1, &CG(implementing_class)); } if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) && ((parent_token->op_type != IS_UNUSED) || (ce->num_interfaces > 0))) { zend_verify_abstract_class(ce TSRMLS_CC); if (ce->num_interfaces) { do_verify_abstract_class(TSRMLS_C); } } /* Inherit interfaces; reset number to zero, we need it for above check and * will restore it during actual implementation. * The ZEND_ACC_IMPLEMENT_INTERFACES flag disables double call to * zend_verify_abstract_class() */ if (ce->num_interfaces > 0) { ce->interfaces = NULL; ce->num_interfaces = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_INTERFACES; } CG(active_class_entry) = NULL; } /* }}} */ void zend_do_implements_interface(znode *interface_name TSRMLS_DC) /* {{{ */ { zend_op *opline; /* Traits can not implement interfaces */ if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface on '%s' since it is a Trait", Z_STRVAL(interface_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(interface_name->u.constant), Z_STRLEN(interface_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface name as it is reserved", Z_STRVAL(interface_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_INTERFACE; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(interface_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = (opline->extended_value & ~ZEND_FETCH_CLASS_MASK) | ZEND_FETCH_CLASS_INTERFACE; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &interface_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_interfaces++; } /* }}} */ void zend_do_implements_trait(znode *trait_name TSRMLS_DC) /* {{{ */ { zend_op *opline; if ((CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Cannot use traits inside of interfaces. %s is used in %s", Z_STRVAL(trait_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(trait_name->u.constant), Z_STRLEN(trait_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as trait name as it is reserved", Z_STRVAL(trait_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_TRAIT; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(trait_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = ZEND_FETCH_CLASS_TRAIT; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &trait_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_traits++; } /* }}} */ ZEND_API void zend_mangle_property_name(char **dest, int *dest_length, const char *src1, int src1_length, const char *src2, int src2_length, int internal) /* {{{ */ { char *prop_name; int prop_name_length; prop_name_length = 1 + src1_length + 1 + src2_length; prop_name = pemalloc(prop_name_length + 1, internal); prop_name[0] = '\0'; memcpy(prop_name + 1, src1, src1_length+1); memcpy(prop_name + 1 + src1_length + 1, src2, src2_length+1); *dest = prop_name; *dest_length = prop_name_length; } /* }}} */ static int zend_strnlen(const char* s, int maxlen) /* {{{ */ { int len = 0; while (*s++ && maxlen--) len++; return len; } /* }}} */ ZEND_API int zend_unmangle_property_name(const char *mangled_property, int len, const char **class_name, const char **prop_name) /* {{{ */ { int class_name_len; *class_name = NULL; if (mangled_property[0]!=0) { *prop_name = mangled_property; return SUCCESS; } if (len < 3 || mangled_property[1]==0) { zend_error(E_NOTICE, "Illegal member variable name"); *prop_name = mangled_property; return FAILURE; } class_name_len = zend_strnlen(mangled_property+1, --len - 1) + 1; if (class_name_len >= len || mangled_property[class_name_len]!=0) { zend_error(E_NOTICE, "Corrupt member variable name"); *prop_name = mangled_property; return FAILURE; } *class_name = mangled_property+1; *prop_name = (*class_name)+class_name_len; return SUCCESS; } /* }}} */ void zend_do_declare_property(const znode *var_name, const znode *value, zend_uint access_type TSRMLS_DC) /* {{{ */ { zval *property; zend_property_info *existing_property_info; char *comment = NULL; int comment_len = 0; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Interfaces may not include member variables"); } if (access_type & ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Properties cannot be declared abstract"); } if (access_type & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot declare property %s::$%s final, the final modifier is allowed only for methods and classes", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } if (zend_hash_find(&CG(active_class_entry)->properties_info, var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, (void **) &existing_property_info)==SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::$%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } ALLOC_ZVAL(property); if (value) { *property = value->u.constant; } else { INIT_PZVAL(property); Z_TYPE_P(property) = IS_NULL; } if (CG(doc_comment)) { comment = CG(doc_comment); comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } zend_declare_property_ex(CG(active_class_entry), zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len + 1, 0 TSRMLS_CC), var_name->u.constant.value.str.len, property, access_type, comment, comment_len TSRMLS_CC); efree(var_name->u.constant.value.str.val); } /* }}} */ void zend_do_declare_class_constant(znode *var_name, const znode *value TSRMLS_DC) /* {{{ */ { zval *property; const char *cname = NULL; int result; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed in class constants"); return; } if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Traits cannot have constants"); return; } ALLOC_ZVAL(property); *property = value->u.constant; cname = zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, 0 TSRMLS_CC); if (IS_INTERNED(cname)) { result = zend_hash_quick_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, INTERNED_HASH(cname), &property, sizeof(zval *), NULL); } else { result = zend_hash_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, &property, sizeof(zval *), NULL); } if (result == FAILURE) { FREE_ZVAL(property); zend_error(E_COMPILE_ERROR, "Cannot redefine class constant %s::%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } FREE_PNODE(var_name); if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_fetch_property(znode *result, znode *object, const znode *property TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (object->op_type == IS_CV) { if (object->u.op.var == CG(active_op_array)->this_var) { object->op_type = IS_UNUSED; /* this means $this for objects */ } } else if (fetch_list_ptr->count == 1) { zend_llist_element *le = fetch_list_ptr->head; zend_op *opline_ptr = (zend_op *) le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); SET_UNUSED(opline_ptr->op1); /* this means $this for objects */ SET_NODE(opline_ptr->op2, property); /* if it was usual fetch, we change it to object fetch */ switch (opline_ptr->opcode) { case ZEND_FETCH_W: opline_ptr->opcode = ZEND_FETCH_OBJ_W; break; case ZEND_FETCH_R: opline_ptr->opcode = ZEND_FETCH_OBJ_R; break; case ZEND_FETCH_RW: opline_ptr->opcode = ZEND_FETCH_OBJ_RW; break; case ZEND_FETCH_IS: opline_ptr->opcode = ZEND_FETCH_OBJ_IS; break; case ZEND_FETCH_UNSET: opline_ptr->opcode = ZEND_FETCH_OBJ_UNSET; break; case ZEND_FETCH_FUNC_ARG: opline_ptr->opcode = ZEND_FETCH_OBJ_FUNC_ARG; break; } if (opline_ptr->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline_ptr->op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline_ptr->op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op2.constant); } GET_NODE(result, opline_ptr->result); return; } } if (zend_is_function_or_method_call(object)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, object); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_OBJ_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, object); SET_NODE(opline.op2, property); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline.op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op2.constant); } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void zend_do_halt_compiler_register(TSRMLS_D) /* {{{ */ { char *name, *cfilename; char haltoff[] = "__COMPILER_HALT_OFFSET__"; int len, clen; if (CG(has_bracketed_namespaces) && CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "__HALT_COMPILER() can only be used from the outermost scope"); } cfilename = zend_get_compiled_filename(TSRMLS_C); clen = strlen(cfilename); zend_mangle_property_name(&name, &len, haltoff, sizeof(haltoff) - 1, cfilename, clen, 0); zend_register_long_constant(name, len+1, zend_get_scanned_file_offset(TSRMLS_C), CONST_CS, 0 TSRMLS_CC); pefree(name, 0); if (CG(in_namespace)) { zend_do_end_namespace(TSRMLS_C); } } /* }}} */ void zend_do_push_object(const znode *object TSRMLS_DC) /* {{{ */ { zend_stack_push(&CG(object_stack), object, sizeof(znode)); } /* }}} */ void zend_do_pop_object(znode *object TSRMLS_DC) /* {{{ */ { if (object) { znode *tmp; zend_stack_top(&CG(object_stack), (void **) &tmp); *object = *tmp; } zend_stack_del_top(&CG(object_stack)); } /* }}} */ void zend_do_begin_new_object(znode *new_token, znode *class_type TSRMLS_DC) /* {{{ */ { zend_op *opline; unsigned char *ptr = NULL; new_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_NEW; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, class_type); SET_UNUSED(opline->op2); zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(unsigned char *)); } /* }}} */ void zend_do_end_new_object(znode *result, const znode *new_token, const znode *argument_list TSRMLS_DC) /* {{{ */ { znode ctor_result; zend_do_end_function_call(NULL, &ctor_result, argument_list, 1, 0 TSRMLS_CC); zend_do_free(&ctor_result TSRMLS_CC); CG(active_op_array)->opcodes[new_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, CG(active_op_array)->opcodes[new_token->u.op.opline_num].result); } /* }}} */ static zend_constant* zend_get_ct_const(const zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = NULL; if (Z_STRVAL_P(const_name)[0] == '\\') { if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name), (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name)-1); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name), (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } } else if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)+1, (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name)+1, (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } if (c->flags & CONST_CT_SUBST) { return c; } if (all_internal_constants_substitution && (c->flags & CONST_PERSISTENT) && !(CG(compiler_options) & ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION) && Z_TYPE(c->value) != IS_CONSTANT && Z_TYPE(c->value) != IS_CONSTANT_ARRAY) { return c; } return NULL; } /* }}} */ static int zend_constant_ct_subst(znode *result, zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = zend_get_ct_const(const_name, all_internal_constants_substitution TSRMLS_CC); if (c) { zval_dtor(const_name); result->op_type = IS_CONST; result->u.constant = c->value; zval_copy_ctor(&result->u.constant); INIT_PZVAL(&result->u.constant); return 1; } return 0; } /* }}} */ void zend_do_fetch_constant(znode *result, znode *constant_container, znode *constant_name, int mode, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; zend_op *opline; int type; char *compound; ulong fetch_type = 0; if (constant_container) { switch (mode) { case ZEND_CT: /* this is a class constant */ type = zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant)); if (ZEND_FETCH_CLASS_STATIC == type) { zend_error(E_ERROR, "\"static::\" is not allowed in compile-time constants"); } else if (ZEND_FETCH_CLASS_DEFAULT == type) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } zend_do_build_full_name(NULL, constant_container, constant_name, 1 TSRMLS_CC); *result = *constant_container; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: if (constant_container->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant))) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } else { zend_do_fetch_class(&tmp, constant_container TSRMLS_CC); constant_container = &tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); if (constant_container->op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &constant_container->u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, constant_container); } SET_NODE(opline->op2, constant_name); CALCULATE_LITERAL_HASH(opline->op2.constant); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } GET_NODE(result, opline->result); break; } return; } /* namespace constant */ /* only one that did not contain \ from the start can be converted to string if unknown */ switch (mode) { case ZEND_CT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); /* this is a namespace constant, or an unprefixed constant */ if (zend_constant_ct_subst(result, &constant_name->u.constant, 0 TSRMLS_CC)) { break; } zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(!compound) { fetch_type |= IS_CONSTANT_UNQUALIFIED; } *result = *constant_name; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(zend_constant_ct_subst(result, &constant_name->u.constant, 1 TSRMLS_CC)) { break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; if (compound) { /* the name is unambiguous */ opline->extended_value = 0; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } else { opline->extended_value = IS_CONSTANT_UNQUALIFIED; if (CG(current_namespace)) { opline->extended_value |= IS_CONSTANT_IN_NAMESPACE; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 1 TSRMLS_CC); } else { opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } } GET_CACHE_SLOT(opline->op2.constant); break; } } /* }}} */ void zend_do_shell_exec(znode *result, const znode *cmd TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); switch (cmd->op_type) { case IS_CONST: case IS_TMP_VAR: opline->opcode = ZEND_SEND_VAL; break; default: opline->opcode = ZEND_SEND_VAR; break; } SET_NODE(opline->op1, cmd); opline->op2.opline_num = 0; opline->extended_value = ZEND_DO_FCALL; SET_UNUSED(opline->op2); /* FIXME: exception support not added to this op2 */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DO_FCALL; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; LITERAL_STRINGL(opline->op1, estrndup("shell_exec", sizeof("shell_exec")-1), sizeof("shell_exec")-1, 0); CALCULATE_LITERAL_HASH(opline->op1.constant); opline->op1_type = IS_CONST; GET_CACHE_SLOT(opline->op1.constant); opline->extended_value = 1; SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_init_array(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_ARRAY; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; GET_NODE(result, opline->result); if (expr) { SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } } else { SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_array_element(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_ARRAY_ELEMENT; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_static_array_element(znode *result, znode *offset, const znode *expr) /* {{{ */ { zval *element; ALLOC_ZVAL(element); *element = expr->u.constant; if (offset) { switch (offset->u.constant.type & IS_CONSTANT_TYPE_MASK) { case IS_CONSTANT: /* Ugly hack to denote that this value has a constant index */ Z_TYPE_P(element) |= IS_CONSTANT_INDEX; Z_STRVAL(offset->u.constant) = erealloc(Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+1] = Z_TYPE(offset->u.constant); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+2] = 0; zend_symtable_update(result->u.constant.value.ht, Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_STRING: zend_symtable_update(result->u.constant.value.ht, offset->u.constant.value.str.val, offset->u.constant.value.str.len+1, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_NULL: zend_symtable_update(Z_ARRVAL(result->u.constant), "", 1, &element, sizeof(zval *), NULL); break; case IS_LONG: case IS_BOOL: zend_hash_index_update(Z_ARRVAL(result->u.constant), Z_LVAL(offset->u.constant), &element, sizeof(zval *), NULL); break; case IS_DOUBLE: zend_hash_index_update(Z_ARRVAL(result->u.constant), zend_dval_to_lval(Z_DVAL(offset->u.constant)), &element, sizeof(zval *), NULL); break; case IS_CONSTANT_ARRAY: zend_error(E_ERROR, "Illegal offset type"); break; } } else { zend_hash_next_index_insert(Z_ARRVAL(result->u.constant), &element, sizeof(zval *), NULL); } } /* }}} */ void zend_do_add_list_element(const znode *element TSRMLS_DC) /* {{{ */ { list_llist_element lle; if (element) { zend_check_writable_variable(element); lle.var = *element; zend_llist_copy(&lle.dimensions, &CG(dimension_llist)); zend_llist_prepend_element(&CG(list_llist), &lle); } (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_new_list_begin(TSRMLS_D) /* {{{ */ { int current_dimension = 0; zend_llist_add_element(&CG(dimension_llist), &current_dimension); } /* }}} */ void zend_do_new_list_end(TSRMLS_D) /* {{{ */ { zend_llist_remove_tail(&CG(dimension_llist)); (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_list_init(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(list_stack), &CG(list_llist), sizeof(zend_llist)); zend_stack_push(&CG(list_stack), &CG(dimension_llist), sizeof(zend_llist)); zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_do_new_list_begin(TSRMLS_C); } /* }}} */ void zend_do_list_end(znode *result, znode *expr TSRMLS_DC) /* {{{ */ { zend_llist_element *le; zend_llist_element *dimension; zend_op *opline; znode last_container; le = CG(list_llist).head; while (le) { zend_llist *tmp_dimension_llist = &((list_llist_element *)le->data)->dimensions; dimension = tmp_dimension_llist->head; while (dimension) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (dimension == tmp_dimension_llist->head) { /* first */ last_container = *expr; switch (expr->op_type) { case IS_VAR: case IS_CV: opline->opcode = ZEND_FETCH_DIM_R; break; case IS_TMP_VAR: opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; case IS_CONST: /* fetch_dim_tmp_var will handle this bogus fetch */ zval_copy_ctor(&expr->u.constant); opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; } opline->extended_value |= ZEND_FETCH_ADD_LOCK; } else { opline->opcode = ZEND_FETCH_DIM_R; } opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, &last_container); opline->op2_type = IS_CONST; LITERAL_LONG(opline->op2, *((int *) dimension->data)); GET_NODE(&last_container, opline->result); dimension = dimension->next; } ((list_llist_element *) le->data)->value = last_container; zend_llist_destroy(&((list_llist_element *) le->data)->dimensions); zend_do_assign(result, &((list_llist_element *) le->data)->var, &((list_llist_element *) le->data)->value TSRMLS_CC); zend_do_free(result TSRMLS_CC); le = le->next; } zend_llist_destroy(&CG(dimension_llist)); zend_llist_destroy(&CG(list_llist)); *result = *expr; { zend_llist *p; /* restore previous lists */ zend_stack_top(&CG(list_stack), (void **) &p); CG(dimension_llist) = *p; zend_stack_del_top(&CG(list_stack)); zend_stack_top(&CG(list_stack), (void **) &p); CG(list_llist) = *p; zend_stack_del_top(&CG(list_stack)); } } /* }}} */ void zend_init_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = emalloc(sizeof(void*) * 2); list[0] = item; list[1] = NULL; *(void**)result = list; } /* }}} */ void zend_add_to_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = *(void**)result; size_t n = 0; while (list && list[n]) { n++; } list = erealloc(list, sizeof(void*) * (n+2)); list[n] = item; list[n+1] = NULL; *(void**)result = list; } /* }}} */ void zend_do_fetch_static_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zval *tmp; zend_op *opline; znode lval; znode result; ALLOC_ZVAL(tmp); if (static_assignment) { *tmp = static_assignment->u.constant; } else { INIT_ZVAL(*tmp); } if (!CG(active_op_array)->static_variables) { if (CG(active_op_array)->scope) { CG(active_op_array)->scope->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } ALLOC_HASHTABLE(CG(active_op_array)->static_variables); zend_hash_init(CG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } zend_hash_update(CG(active_op_array)->static_variables, varname->u.constant.value.str.val, varname->u.constant.value.str.len+1, &tmp, sizeof(zval *), NULL); if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (fetch_type == ZEND_FETCH_LEXICAL) ? ZEND_FETCH_R : ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_STATIC; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ if (fetch_type == ZEND_FETCH_LEXICAL) { znode dummy; zend_do_begin_variable_parse(TSRMLS_C); zend_do_assign(&dummy, &lval, &result TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } else { zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); } CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_fetch_lexical_variable(znode *varname, zend_bool is_ref TSRMLS_DC) /* {{{ */ { znode value; if (Z_STRLEN(varname->u.constant) == sizeof("this") - 1 && memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this") - 1) == 0) { zend_error(E_COMPILE_ERROR, "Cannot use $this as lexical variable"); return; } value.op_type = IS_CONST; ZVAL_NULL(&value.u.constant); Z_TYPE(value.u.constant) |= is_ref ? IS_LEXICAL_REF : IS_LEXICAL_VAR; Z_SET_REFCOUNT_P(&value.u.constant, 1); Z_UNSET_ISREF_P(&value.u.constant); zend_do_fetch_static_variable(varname, &value, is_ref ? ZEND_FETCH_STATIC : ZEND_FETCH_LEXICAL TSRMLS_CC); } /* }}} */ void zend_do_fetch_global_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zend_op *opline; znode lval; znode result; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = fetch_type; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_cast(znode *result, const znode *expr, int type TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CAST; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } /* }}} */ void zend_do_include_or_eval(int type, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_do_extended_fcall_begin(TSRMLS_C); { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INCLUDE_OR_EVAL; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } zend_do_extended_fcall_end(TSRMLS_C); } /* }}} */ void zend_do_indirect_references(znode *result, const znode *num_references, znode *variable TSRMLS_DC) /* {{{ */ { int i; zend_do_end_variable_parse(variable, BP_VAR_R, 0 TSRMLS_CC); for (i=1; i<num_references->u.constant.value.lval; i++) { fetch_simple_variable_ex(result, variable, 0, ZEND_FETCH_R TSRMLS_CC); *variable = *result; } zend_do_begin_variable_parse(TSRMLS_C); fetch_simple_variable(result, variable, 1 TSRMLS_CC); /* there is a chance someone is accessing $this */ if (CG(active_op_array)->scope && CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } /* }}} */ void zend_do_unset(const znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_UNSET_VAR; SET_NODE(opline->op1, variable); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); opline->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_UNSET: last_op->opcode = ZEND_UNSET_VAR; SET_UNUSED(last_op->result); break; case ZEND_FETCH_DIM_UNSET: last_op->opcode = ZEND_UNSET_DIM; SET_UNUSED(last_op->result); break; case ZEND_FETCH_OBJ_UNSET: last_op->opcode = ZEND_UNSET_OBJ; SET_UNUSED(last_op->result); break; } } } /* }}} */ void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_do_end_variable_parse(variable, BP_VAR_IS, 0 TSRMLS_CC); zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { last_op = get_next_op(CG(active_op_array) TSRMLS_CC); last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; SET_NODE(last_op->op1, variable); SET_UNUSED(last_op->op2); last_op->result.var = get_temporary_variable(CG(active_op_array)); last_op->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; break; case ZEND_FETCH_DIM_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_DIM_OBJ; break; case ZEND_FETCH_OBJ_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_PROP_OBJ; break; } } last_op->result_type = IS_TMP_VAR; last_op->extended_value |= type; GET_NODE(result, last_op->result); } /* }}} */ void zend_do_instanceof(znode *result, const znode *expr, const znode *class_znode, int type TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline->opcode == ZEND_FETCH_CLASS) { opline->extended_value |= ZEND_FETCH_CLASS_NO_AUTOLOAD; } } if (expr->op_type == IS_CONST) { zend_error(E_COMPILE_ERROR, "instanceof expects an object instance, constant given"); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INSTANCEOF; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_NODE(opline->op2, class_znode); GET_NODE(result, opline->result); } /* }}} */ void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_bool is_variable; zend_bool push_container = 0; zend_op dummy_opline; if (variable) { if (zend_is_function_or_method_call(array)) { is_variable = 0; } else { is_variable = 1; } /* save the location of FETCH_W instruction(s) */ open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); zend_do_end_variable_parse(array, BP_VAR_W, 0 TSRMLS_CC); if (CG(active_op_array)->last > 0 && CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) { /* Only lock the container if we are fetching from a real container and not $this */ if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1_type == IS_VAR) { CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK; push_container = 1; } } } else { is_variable = 0; open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* save the location of FE_RESET */ foreach_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* Preform array reset */ opline->opcode = ZEND_FE_RESET; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, array); SET_UNUSED(opline->op2); opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0; COPY_NODE(dummy_opline.result, opline->result); if (push_container) { COPY_NODE(dummy_opline.op1, CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1); } else { dummy_opline.op1_type = IS_UNUSED; } zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); /* save the location of FE_FETCH */ as_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FE_FETCH; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); COPY_NODE(opline->op1, dummy_opline.result); opline->extended_value = 0; SET_UNUSED(opline->op2); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_OP_DATA; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); } /* }}} */ void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC) /* {{{ */ { zend_op *opline; znode dummy, value_node; zend_bool assign_by_ref=0; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num]; if (key->op_type != IS_UNUSED) { znode *tmp; /* switch between the key and value... */ tmp = key; key = value; value = tmp; /* Mark extended_value in case both key and value are being used */ opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; } if ((key->op_type != IS_UNUSED) && (key->EA & ZEND_PARSED_REFERENCE_VARIABLE)) { zend_error(E_COMPILE_ERROR, "Key element cannot be a reference"); } if (value->EA & ZEND_PARSED_REFERENCE_VARIABLE) { assign_by_ref = 1; if (!(opline-1)->extended_value) { zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression"); } /* Mark extended_value for assign-by-reference */ opline->extended_value |= ZEND_FE_FETCH_BYREF; CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; } else { zend_op *foreach_copy; zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.op.opline_num]; zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.op.opline_num]; /* Change "write context" into "read context" */ fetch->extended_value = 0; /* reset ZEND_FE_RESET_VARIABLE */ while (fetch != end) { --fetch; if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } if (fetch->opcode == ZEND_SEPARATE) { MAKE_NOP(fetch); } else { fetch->opcode -= 3; /* FETCH_W -> FETCH_R */ } } /* prevent double SWITCH_FREE */ zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy); foreach_copy->op1_type = IS_UNUSED; } GET_NODE(&value_node, opline->result); if (assign_by_ref) { zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); /* Mark FE_FETCH as IS_VAR as it holds the data directly as a value */ zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC); } else { zend_do_assign(&dummy, value, &value_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } if (key->op_type != IS_UNUSED) { znode key_node; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num+1]; opline->result_type = IS_TMP_VAR; opline->result.opline_num = get_temporary_variable(CG(active_op_array)); GET_NODE(&key_node, opline->result); zend_do_assign(&dummy, key, &key_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_foreach_end(const znode *foreach_token, const znode *as_token TSRMLS_DC) /* {{{ */ { zend_op *container_ptr; zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = as_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_RESET */ CG(active_op_array)->opcodes[as_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_FETCH */ do_end_loop(as_token->u.op.opline_num, 1 TSRMLS_CC); zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr); generate_free_foreach_copy(container_ptr TSRMLS_CC); zend_stack_del_top(&CG(foreach_copy_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_declare_begin(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(declare_stack), &CG(declarables), sizeof(zend_declarables)); } /* }}} */ void zend_do_declare_stmt(znode *var, znode *val TSRMLS_DC) /* {{{ */ { if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "ticks", sizeof("ticks")-1)) { convert_to_long(&val->u.constant); CG(declarables).ticks = val->u.constant; } else if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "encoding", sizeof("encoding")-1)) { if ((Z_TYPE(val->u.constant) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Cannot use constants as encoding"); } /* * Check that the pragma comes before any opcodes. If the compilation * got as far as this, the previous portion of the script must have been * parseable according to the .ini script_encoding setting. We still * want to tell them to put declare() at the top. */ { int num = CG(active_op_array)->last; /* ignore ZEND_EXT_STMT and ZEND_TICKS */ while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Encoding declaration pragma must be the very first statement in the script"); } } if (CG(multibyte)) { const zend_encoding *new_encoding, *old_encoding; zend_encoding_filter old_input_filter; CG(encoding_declared) = 1; convert_to_string(&val->u.constant); new_encoding = zend_multibyte_fetch_encoding(val->u.constant.value.str.val TSRMLS_CC); if (!new_encoding) { zend_error(E_COMPILE_WARNING, "Unsupported encoding [%s]", val->u.constant.value.str.val); } else { old_input_filter = LANG_SCNG(input_filter); old_encoding = LANG_SCNG(script_encoding); zend_multibyte_set_filter(new_encoding TSRMLS_CC); /* need to re-scan if input filter changed */ if (old_input_filter != LANG_SCNG(input_filter) || (old_input_filter && new_encoding != old_encoding)) { zend_multibyte_yyinput_again(old_input_filter, old_encoding TSRMLS_CC); } } } else { zend_error(E_COMPILE_WARNING, "declare(encoding=...) ignored because Zend multibyte feature is turned off by settings"); } zval_dtor(&val->u.constant); } else { zend_error(E_COMPILE_WARNING, "Unsupported declare '%s'", var->u.constant.value.str.val); zval_dtor(&val->u.constant); } zval_dtor(&var->u.constant); } /* }}} */ void zend_do_declare_end(const znode *declare_token TSRMLS_DC) /* {{{ */ { zend_declarables *declarables; zend_stack_top(&CG(declare_stack), (void **) &declarables); /* We should restore if there was more than (current - start) - (ticks?1:0) opcodes */ if ((get_next_op_number(CG(active_op_array)) - declare_token->u.op.opline_num) - ((Z_LVAL(CG(declarables).ticks))?1:0)) { CG(declarables) = *declarables; } } /* }}} */ void zend_do_exit(znode *result, const znode *message TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXIT; SET_NODE(opline->op1, message); SET_UNUSED(opline->op2); result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_BOOL; Z_LVAL(result->u.constant) = 1; } /* }}} */ void zend_do_begin_silence(znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BEGIN_SILENCE; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); GET_NODE(strudel_token, opline->result); } /* }}} */ void zend_do_end_silence(const znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_END_SILENCE; SET_NODE(opline->op1, strudel_token); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_jmp_set(const znode *value, znode *jmp_token, znode *colon_token TSRMLS_DC) /* {{{ */ { int op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (value->op_type == IS_VAR || value->op_type == IS_CV) { opline->opcode = ZEND_JMP_SET_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_JMP_SET; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, value); SET_UNUSED(opline->op2); GET_NODE(colon_token, opline->result); jmp_token->u.op .opline_num = op_number; INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_jmp_set_else(znode *result, const znode *false_value, const znode *jmp_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, colon_token); if (colon_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].opcode = ZEND_JMP_SET_VAR; CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } opline->extended_value = 0; SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_qm_op(const znode *cond, znode *qm_token TSRMLS_DC) /* {{{ */ { int jmpz_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); SET_UNUSED(opline->op2); opline->op2.opline_num = jmpz_op_number; GET_NODE(qm_token, opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_qm_true(const znode *true_value, znode *qm_token, znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->opcodes[qm_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array))+1; /* jmp over the ZEND_JMP */ if (true_value->op_type == IS_VAR || true_value->op_type == IS_CV) { opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, true_value); SET_UNUSED(opline->op2); GET_NODE(qm_token, opline->result); colon_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_qm_false(znode *result, const znode *false_value, const znode *qm_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, qm_token); if (qm_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].opcode = ZEND_QM_ASSIGN_VAR; CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[colon_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, opline->result); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_extended_info(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_STMT; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_begin(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_BEGIN; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_end(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_END; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_ticks(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_TICKS; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->extended_value = Z_LVAL(CG(declarables).ticks); } /* }}} */ zend_bool zend_is_auto_global_quick(const char *name, uint name_len, ulong hashval TSRMLS_DC) /* {{{ */ { zend_auto_global *auto_global; ulong hash = hashval ? hashval : zend_hash_func(name, name_len+1); if (zend_hash_quick_find(CG(auto_globals), name, name_len+1, hash, (void **) &auto_global)==SUCCESS) { if (auto_global->armed) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } return 1; } return 0; } /* }}} */ zend_bool zend_is_auto_global(const char *name, uint name_len TSRMLS_DC) /* {{{ */ { return zend_is_auto_global_quick(name, name_len, 0 TSRMLS_CC); } /* }}} */ int zend_register_auto_global(const char *name, uint name_len, zend_bool jit, zend_auto_global_callback auto_global_callback TSRMLS_DC) /* {{{ */ { zend_auto_global auto_global; auto_global.name = zend_new_interned_string((char*)name, name_len + 1, 0 TSRMLS_CC); auto_global.name_len = name_len; auto_global.auto_global_callback = auto_global_callback; auto_global.jit = jit; return zend_hash_add(CG(auto_globals), name, name_len+1, &auto_global, sizeof(zend_auto_global), NULL); } /* }}} */ static int zend_auto_global_init(zend_auto_global *auto_global TSRMLS_DC) /* {{{ */ { if (auto_global->jit) { auto_global->armed = 1; } else if (auto_global->auto_global_callback) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } else { auto_global->armed = 0; } return 0; } /* }}} */ ZEND_API void zend_activate_auto_globals(TSRMLS_D) /* {{{ */ { zend_hash_apply(CG(auto_globals), (apply_func_t) zend_auto_global_init TSRMLS_CC); } /* }}} */ int zendlex(znode *zendlval TSRMLS_DC) /* {{{ */ { int retval; if (CG(increment_lineno)) { CG(zend_lineno)++; CG(increment_lineno) = 0; } again: Z_TYPE(zendlval->u.constant) = IS_LONG; retval = lex_scan(&zendlval->u.constant TSRMLS_CC); switch (retval) { case T_COMMENT: case T_DOC_COMMENT: case T_OPEN_TAG: case T_WHITESPACE: goto again; case T_CLOSE_TAG: if (LANG_SCNG(yy_text)[LANG_SCNG(yy_leng)-1] != '>') { CG(increment_lineno) = 1; } if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { goto again; } retval = ';'; /* implicit ; */ break; case T_OPEN_TAG_WITH_ECHO: retval = T_ECHO; break; case T_END_HEREDOC: efree(Z_STRVAL(zendlval->u.constant)); break; } INIT_PZVAL(&zendlval->u.constant); zendlval->op_type = IS_CONST; return retval; } /* }}} */ ZEND_API void zend_initialize_class_data(zend_class_entry *ce, zend_bool nullify_handlers TSRMLS_DC) /* {{{ */ { zend_bool persistent_hashes = (ce->type == ZEND_INTERNAL_CLASS) ? 1 : 0; dtor_func_t zval_ptr_dtor_func = ((persistent_hashes) ? ZVAL_INTERNAL_PTR_DTOR : ZVAL_PTR_DTOR); ce->refcount = 1; ce->ce_flags = 0; ce->default_properties_table = NULL; ce->default_static_members_table = NULL; zend_hash_init_ex(&ce->properties_info, 0, NULL, (dtor_func_t) (persistent_hashes ? zend_destroy_property_info_internal : zend_destroy_property_info), persistent_hashes, 0); zend_hash_init_ex(&ce->constants_table, 0, NULL, zval_ptr_dtor_func, persistent_hashes, 0); zend_hash_init_ex(&ce->function_table, 0, NULL, ZEND_FUNCTION_DTOR, persistent_hashes, 0); if (ce->type == ZEND_INTERNAL_CLASS) { #ifdef ZTS int n = zend_hash_num_elements(CG(class_table)); if (CG(static_members_table) && n >= CG(last_static_member)) { /* Support for run-time declaration: dl() */ CG(last_static_member) = n+1; CG(static_members_table) = realloc(CG(static_members_table), (n+1)*sizeof(zval**)); CG(static_members_table)[n] = NULL; } ce->static_members_table = (zval**)(zend_intptr_t)n; #else ce->static_members_table = NULL; #endif } else { ce->static_members_table = ce->default_static_members_table; ce->info.user.doc_comment = NULL; ce->info.user.doc_comment_len = 0; } ce->default_properties_count = 0; ce->default_static_members_count = 0; if (nullify_handlers) { ce->constructor = NULL; ce->destructor = NULL; ce->clone = NULL; ce->__get = NULL; ce->__set = NULL; ce->__unset = NULL; ce->__isset = NULL; ce->__call = NULL; ce->__callstatic = NULL; ce->__tostring = NULL; ce->create_object = NULL; ce->get_iterator = NULL; ce->iterator_funcs.funcs = NULL; ce->interface_gets_implemented = NULL; ce->get_static_method = NULL; ce->parent = NULL; ce->num_interfaces = 0; ce->interfaces = NULL; ce->num_traits = 0; ce->traits = NULL; ce->trait_aliases = NULL; ce->trait_precedences = NULL; ce->serialize = NULL; ce->unserialize = NULL; ce->serialize_func = NULL; ce->unserialize_func = NULL; if (ce->type == ZEND_INTERNAL_CLASS) { ce->info.internal.module = NULL; ce->info.internal.builtin_functions = NULL; } } } /* }}} */ int zend_get_class_fetch_type(const char *class_name, uint class_name_len) /* {{{ */ { if ((class_name_len == sizeof("self")-1) && !memcmp(class_name, "self", sizeof("self")-1)) { return ZEND_FETCH_CLASS_SELF; } else if ((class_name_len == sizeof("parent")-1) && !memcmp(class_name, "parent", sizeof("parent")-1)) { return ZEND_FETCH_CLASS_PARENT; } else if ((class_name_len == sizeof("static")-1) && !memcmp(class_name, "static", sizeof("static")-1)) { return ZEND_FETCH_CLASS_STATIC; } else { return ZEND_FETCH_CLASS_DEFAULT; } } /* }}} */ ZEND_API const char* zend_get_compiled_variable_name(const zend_op_array *op_array, zend_uint var, int* name_len) /* {{{ */ { if (name_len) { *name_len = op_array->vars[var].name_len; } return op_array->vars[var].name; } /* }}} */ void zend_do_build_namespace_name(znode *result, znode *prefix, znode *name TSRMLS_DC) /* {{{ */ { if (prefix) { *result = *prefix; if (Z_TYPE(result->u.constant) == IS_STRING && Z_STRLEN(result->u.constant) == 0) { /* namespace\ */ if (CG(current_namespace)) { znode tmp; zval_dtor(&result->u.constant); tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(result, NULL, &tmp TSRMLS_CC); } } } else { result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_STRING; Z_STRVAL(result->u.constant) = NULL; Z_STRLEN(result->u.constant) = 0; } /* prefix = result */ zend_do_build_full_name(NULL, result, name, 0 TSRMLS_CC); } /* }}} */ void zend_do_begin_namespace(const znode *name, zend_bool with_bracket TSRMLS_DC) /* {{{ */ { char *lcname; /* handle mixed syntax declaration or nested namespaces */ if (!CG(has_bracketed_namespaces)) { if (CG(current_namespace)) { /* previous namespace declarations were unbracketed */ if (with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } } } else { /* previous namespace declarations were bracketed */ if (!with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } else if (CG(current_namespace) || CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "Namespace declarations cannot be nested"); } } if (((!with_bracket && !CG(current_namespace)) || (with_bracket && !CG(has_bracketed_namespaces))) && CG(active_op_array)->last > 0) { /* ignore ZEND_EXT_STMT and ZEND_TICKS */ int num = CG(active_op_array)->last; while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Namespace declaration statement has to be the very first statement in the script"); } } CG(in_namespace) = 1; if (with_bracket) { CG(has_bracketed_namespaces) = 1; } if (name) { lcname = zend_str_tolower_dup(Z_STRVAL(name->u.constant), Z_STRLEN(name->u.constant)); if (((Z_STRLEN(name->u.constant) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN(name->u.constant) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as namespace name", Z_STRVAL(name->u.constant)); } efree(lcname); if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); } else { ALLOC_ZVAL(CG(current_namespace)); } *CG(current_namespace) = name->u.constant; } else { if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_use(znode *ns_name, znode *new_name, int is_global TSRMLS_DC) /* {{{ */ { char *lcname; zval *name, *ns, tmp; zend_bool warn = 0; zend_class_entry **pce; if (!CG(current_import)) { CG(current_import) = emalloc(sizeof(HashTable)); zend_hash_init(CG(current_import), 0, NULL, ZVAL_PTR_DTOR, 0); } ALLOC_ZVAL(ns); *ns = ns_name->u.constant; if (new_name) { name = &new_name->u.constant; } else { const char *p; /* The form "use A\B" is eqivalent to "use A\B as B". So we extract the last part of compound name to use as a new_name */ name = &tmp; p = zend_memrchr(Z_STRVAL_P(ns), '\\', Z_STRLEN_P(ns)); if (p) { ZVAL_STRING(name, p+1, 1); } else { *name = *ns; zval_copy_ctor(name); warn = !is_global && !CG(current_namespace); } } lcname = zend_str_tolower_dup(Z_STRVAL_P(name), Z_STRLEN_P(name)); if (((Z_STRLEN_P(name) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN_P(name) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because '%s' is a special class name", Z_STRVAL_P(ns), Z_STRVAL_P(name), Z_STRVAL_P(name)); } if (CG(current_namespace)) { /* Prefix import name with current namespace name to avoid conflicts with classes */ char *c_ns_name = emalloc(Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) + 1); zend_str_tolower_copy(c_ns_name, Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); c_ns_name[Z_STRLEN_P(CG(current_namespace))] = '\\'; memcpy(c_ns_name+Z_STRLEN_P(CG(current_namespace))+1, lcname, Z_STRLEN_P(name)+1); if (zend_hash_exists(CG(class_table), c_ns_name, Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name)+1)) { char *tmp2 = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) || memcmp(tmp2, c_ns_name, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(tmp2); } efree(c_ns_name); } else if (zend_hash_find(CG(class_table), lcname, Z_STRLEN_P(name)+1, (void**)&pce) == SUCCESS && (*pce)->type == ZEND_USER_CLASS && (*pce)->info.user.filename == CG(compiled_filename)) { char *c_tmp = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(name) || memcmp(c_tmp, lcname, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(c_tmp); } if (zend_hash_add(CG(current_import), lcname, Z_STRLEN_P(name)+1, &ns, sizeof(zval*), NULL) != SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } if (warn) { if (!strcmp(Z_STRVAL_P(name), "strict")) { zend_error(E_COMPILE_ERROR, "You seem to be trying to use a different language..."); } zend_error(E_WARNING, "The use statement with non-compound name '%s' has no effect", Z_STRVAL_P(name)); } efree(lcname); zval_dtor(name); } /* }}} */ void zend_do_declare_constant(znode *name, znode *value TSRMLS_DC) /* {{{ */ { zend_op *opline; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed as constants"); } if (zend_get_ct_const(&name->u.constant, 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare constant '%s'", Z_STRVAL(name->u.constant)); } if (CG(current_namespace)) { /* Prefix constant name with name of current namespace, lowercased */ znode tmp; tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); Z_STRVAL(tmp.u.constant) = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), Z_STRLEN(tmp.u.constant)); zend_do_build_namespace_name(&tmp, &tmp, name TSRMLS_CC); *name = tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DECLARE_CONST; SET_UNUSED(opline->result); SET_NODE(opline->op1, name); SET_NODE(opline->op2, value); } /* }}} */ void zend_verify_namespace(TSRMLS_D) /* {{{ */ { if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "No code may exist outside of namespace {}"); } } /* }}} */ void zend_do_end_namespace(TSRMLS_D) /* {{{ */ { CG(in_namespace) = 0; if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_end_compilation(TSRMLS_D) /* {{{ */ { CG(has_bracketed_namespaces) = 0; zend_do_end_namespace(TSRMLS_C); } /* }}} */ /* {{{ zend_dirname Returns directory name component of path */ ZEND_API size_t zend_dirname(char *path, size_t len) { register char *end = path + len - 1; unsigned int len_adjust = 0; #ifdef PHP_WIN32 /* Note that on Win32 CWD is per drive (heritage from CP/M). * This means dirname("c:foo") maps to "c:." or "c:" - which means CWD on C: drive. */ if ((2 <= len) && isalpha((int)((unsigned char *)path)[0]) && (':' == path[1])) { /* Skip over the drive spec (if any) so as not to change */ path += 2; len_adjust += 2; if (2 == len) { /* Return "c:" on Win32 for dirname("c:"). * It would be more consistent to return "c:." * but that would require making the string *longer*. */ return len; } } #elif defined(NETWARE) /* * Find the first occurence of : from the left * move the path pointer to the position just after : * increment the len_adjust to the length of path till colon character(inclusive) * If there is no character beyond : simple return len */ char *colonpos = NULL; colonpos = strchr(path, ':'); if (colonpos != NULL) { len_adjust = ((colonpos - path) + 1); path += len_adjust; if (len_adjust == len) { return len; } } #endif if (len == 0) { /* Illegal use of this function */ return 0; } /* Strip trailing slashes */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { /* The path only contained slashes */ path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } /* Strip filename */ while (end >= path && !IS_SLASH_P(end)) { end--; } if (end < path) { /* No slash found, therefore return '.' */ #ifdef NETWARE if (len_adjust == 0) { path[0] = '.'; path[1] = '\0'; return 1; /* only one character */ } else { path[0] = '\0'; return len_adjust; } #else path[0] = '.'; path[1] = '\0'; return 1 + len_adjust; #endif } /* Strip slashes which came before the file name */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } *(end+1) = '\0'; return (size_t)(end + 1 - path) + len_adjust; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */ /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <zend_language_parser.h> #include "zend.h" #include "zend_compile.h" #include "zend_constants.h" #include "zend_llist.h" #include "zend_API.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "zend_multibyte.h" #include "zend_language_scanner.h" #define CONSTANT_EX(op_array, op) \ (op_array)->literals[op].constant #define CONSTANT(op) \ CONSTANT_EX(CG(active_op_array), op) #define SET_NODE(target, src) do { \ target ## _type = (src)->op_type; \ if ((src)->op_type == IS_CONST) { \ target.constant = zend_add_literal(CG(active_op_array), &(src)->u.constant TSRMLS_CC); \ } else { \ target = (src)->u.op; \ } \ } while (0) #define GET_NODE(target, src) do { \ (target)->op_type = src ## _type; \ if ((target)->op_type == IS_CONST) { \ (target)->u.constant = CONSTANT(src.constant); \ } else { \ (target)->u.op = src; \ (target)->EA = 0; \ } \ } while (0) #define COPY_NODE(target, src) do { \ target ## _type = src ## _type; \ target = src; \ } while (0) #define CALCULATE_LITERAL_HASH(num) do { \ if (IS_INTERNED(Z_STRVAL(CONSTANT(num)))) { \ Z_HASH_P(&CONSTANT(num)) = INTERNED_HASH(Z_STRVAL(CONSTANT(num))); \ } else { \ Z_HASH_P(&CONSTANT(num)) = zend_hash_func(Z_STRVAL(CONSTANT(num)), Z_STRLEN(CONSTANT(num))+1); \ } \ } while (0) #define GET_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot++; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ } \ } while (0) #define POLYMORPHIC_CACHE_SLOT_SIZE 2 #define GET_POLYMORPHIC_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot; \ CG(active_op_array)->last_cache_slot += POLYMORPHIC_CACHE_SLOT_SIZE; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 2] = NULL; \ } \ } while (0) #define FREE_POLYMORPHIC_CACHE_SLOT(literal) do { \ if (CG(active_op_array)->literals[literal].cache_slot == \ CG(active_op_array)->last_cache_slot - POLYMORPHIC_CACHE_SLOT_SIZE) { \ CG(active_op_array)->literals[literal].cache_slot = -1; \ CG(active_op_array)->last_cache_slot -= POLYMORPHIC_CACHE_SLOT_SIZE; \ } \ } while (0) ZEND_API zend_op_array *(*zend_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); ZEND_API zend_op_array *(*zend_compile_string)(zval *source_string, char *filename TSRMLS_DC); #ifndef ZTS ZEND_API zend_compiler_globals compiler_globals; ZEND_API zend_executor_globals executor_globals; #endif static void zend_duplicate_property_info(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = estrndup(property_info->name, property_info->name_length); } if (property_info->doc_comment) { property_info->doc_comment = estrndup(property_info->doc_comment, property_info->doc_comment_len); } } /* }}} */ static void zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = zend_strndup(property_info->name, property_info->name_length); } } /* }}} */ static void zend_destroy_property_info(zend_property_info *property_info) /* {{{ */ { str_efree(property_info->name); if (property_info->doc_comment) { efree((char*)property_info->doc_comment); } } /* }}} */ static void zend_destroy_property_info_internal(zend_property_info *property_info) /* {{{ */ { str_free((char*)property_info->name); } /* }}} */ static void build_runtime_defined_function_key(zval *result, const char *name, int name_length TSRMLS_DC) /* {{{ */ { char char_pos_buf[32]; uint char_pos_len; const char *filename; char_pos_len = zend_sprintf(char_pos_buf, "%p", LANG_SCNG(yy_text)); if (CG(active_op_array)->filename) { filename = CG(active_op_array)->filename; } else { filename = "-"; } /* NULL, name length, filename length, last accepting char position length */ result->value.str.len = 1+name_length+strlen(filename)+char_pos_len; /* must be binary safe */ result->value.str.val = (char *) safe_emalloc(result->value.str.len, 1, 1); result->value.str.val[0] = '\0'; sprintf(result->value.str.val+1, "%s%s%s", name, filename, char_pos_buf); result->type = IS_STRING; Z_SET_REFCOUNT_P(result, 1); } /* }}} */ static void init_compiler_declarables(TSRMLS_D) /* {{{ */ { Z_TYPE(CG(declarables).ticks) = IS_LONG; Z_LVAL(CG(declarables).ticks) = 0; } /* }}} */ void zend_init_compiler_context(TSRMLS_D) /* {{{ */ { CG(context).opcodes_size = (CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) ? INITIAL_INTERACTIVE_OP_ARRAY_SIZE : INITIAL_OP_ARRAY_SIZE; CG(context).vars_size = 0; CG(context).literals_size = 0; CG(context).current_brk_cont = -1; CG(context).backpatch_count = 0; CG(context).labels = NULL; } /* }}} */ void zend_init_compiler_data_structures(TSRMLS_D) /* {{{ */ { zend_stack_init(&CG(bp_stack)); zend_stack_init(&CG(function_call_stack)); zend_stack_init(&CG(switch_cond_stack)); zend_stack_init(&CG(foreach_copy_stack)); zend_stack_init(&CG(object_stack)); zend_stack_init(&CG(declare_stack)); CG(active_class_entry) = NULL; zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_stack_init(&CG(list_stack)); CG(in_compilation) = 0; CG(start_lineno) = 0; CG(current_namespace) = NULL; CG(in_namespace) = 0; CG(has_bracketed_namespaces) = 0; CG(current_import) = NULL; init_compiler_declarables(TSRMLS_C); zend_stack_init(&CG(context_stack)); CG(encoding_declared) = 0; } /* }}} */ ZEND_API void file_handle_dtor(zend_file_handle *fh) /* {{{ */ { TSRMLS_FETCH(); zend_file_handle_dtor(fh TSRMLS_CC); } /* }}} */ void init_compiler(TSRMLS_D) /* {{{ */ { CG(active_op_array) = NULL; zend_init_compiler_data_structures(TSRMLS_C); zend_init_rsrc_list(TSRMLS_C); zend_hash_init(&CG(filenames_table), 5, NULL, (dtor_func_t) free_estring, 0); zend_llist_init(&CG(open_files), sizeof(zend_file_handle), (void (*)(void *)) file_handle_dtor, 0); CG(unclean_shutdown) = 0; } /* }}} */ void shutdown_compiler(TSRMLS_D) /* {{{ */ { zend_stack_destroy(&CG(bp_stack)); zend_stack_destroy(&CG(function_call_stack)); zend_stack_destroy(&CG(switch_cond_stack)); zend_stack_destroy(&CG(foreach_copy_stack)); zend_stack_destroy(&CG(object_stack)); zend_stack_destroy(&CG(declare_stack)); zend_stack_destroy(&CG(list_stack)); zend_hash_destroy(&CG(filenames_table)); zend_llist_destroy(&CG(open_files)); zend_stack_destroy(&CG(context_stack)); } /* }}} */ ZEND_API char *zend_set_compiled_filename(const char *new_compiled_filename TSRMLS_DC) /* {{{ */ { char **pp, *p; int length = strlen(new_compiled_filename); if (zend_hash_find(&CG(filenames_table), new_compiled_filename, length+1, (void **) &pp) == SUCCESS) { CG(compiled_filename) = *pp; return *pp; } p = estrndup(new_compiled_filename, length); zend_hash_update(&CG(filenames_table), new_compiled_filename, length+1, &p, sizeof(char *), (void **) &pp); CG(compiled_filename) = p; return p; } /* }}} */ ZEND_API void zend_restore_compiled_filename(char *original_compiled_filename TSRMLS_DC) /* {{{ */ { CG(compiled_filename) = original_compiled_filename; } /* }}} */ ZEND_API char *zend_get_compiled_filename(TSRMLS_D) /* {{{ */ { return CG(compiled_filename); } /* }}} */ ZEND_API int zend_get_compiled_lineno(TSRMLS_D) /* {{{ */ { return CG(zend_lineno); } /* }}} */ ZEND_API zend_bool zend_is_compiling(TSRMLS_D) /* {{{ */ { return CG(in_compilation); } /* }}} */ static zend_uint get_temporary_variable(zend_op_array *op_array) /* {{{ */ { return (op_array->T)++ * ZEND_MM_ALIGNED_SIZE(sizeof(temp_variable)); } /* }}} */ static int lookup_cv(zend_op_array *op_array, char* name, int name_len, ulong hash TSRMLS_DC) /* {{{ */ { int i = 0; ulong hash_value = hash ? hash : zend_inline_hash_func(name, name_len+1); while (i < op_array->last_var) { if (op_array->vars[i].name == name || (op_array->vars[i].hash_value == hash_value && op_array->vars[i].name_len == name_len && memcmp(op_array->vars[i].name, name, name_len) == 0)) { str_efree(name); return i; } i++; } i = op_array->last_var; op_array->last_var++; if (op_array->last_var > CG(context).vars_size) { CG(context).vars_size += 16; /* FIXME */ op_array->vars = erealloc(op_array->vars, CG(context).vars_size * sizeof(zend_compiled_variable)); } op_array->vars[i].name = zend_new_interned_string(name, name_len + 1, 1 TSRMLS_CC); op_array->vars[i].name_len = name_len; op_array->vars[i].hash_value = hash_value; return i; } /* }}} */ void zend_del_literal(zend_op_array *op_array, int n) /* {{{ */ { zval_dtor(&CONSTANT_EX(op_array, n)); if (n + 1 == op_array->last_literal) { op_array->last_literal--; } else { Z_TYPE(CONSTANT_EX(op_array, n)) = IS_NULL; } } /* }}} */ /* Common part of zend_add_literal and zend_append_individual_literal */ static inline void zend_insert_literal(zend_op_array *op_array, const zval *zv, int literal_position TSRMLS_DC) /* {{{ */ { if (Z_TYPE_P(zv) == IS_STRING || Z_TYPE_P(zv) == IS_CONSTANT) { zval *z = (zval*)zv; Z_STRVAL_P(z) = (char*)zend_new_interned_string(Z_STRVAL_P(zv), Z_STRLEN_P(zv) + 1, 1 TSRMLS_CC); } CONSTANT_EX(op_array, literal_position) = *zv; Z_SET_REFCOUNT(CONSTANT_EX(op_array, literal_position), 2); Z_SET_ISREF(CONSTANT_EX(op_array, literal_position)); op_array->literals[literal_position].hash_value = 0; op_array->literals[literal_position].cache_slot = -1; } /* }}} */ /* Is used while compiling a function, using the context to keep track of an approximate size to avoid to relocate to often. Literals are truncated to actual size in the second compiler pass (pass_two()). */ int zend_add_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; if (i >= CG(context).literals_size) { while (i >= CG(context).literals_size) { CG(context).literals_size += 16; /* FIXME */ } op_array->literals = (zend_literal*)erealloc(op_array->literals, CG(context).literals_size * sizeof(zend_literal)); } zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ /* Is used after normal compilation to append an additional literal. Allocation is done precisely here. */ int zend_append_individual_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; op_array->literals = (zend_literal*)erealloc(op_array->literals, (i + 1) * sizeof(zend_literal)); zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ int zend_add_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_ns_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; const char *ns_separator; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); ns_separator = (const char*)zend_memrchr(Z_STRVAL_P(zv), '\\', Z_STRLEN_P(zv)) + 1; lc_len = Z_STRLEN_P(zv) - (ns_separator - Z_STRVAL_P(zv)); lc_name = zend_str_tolower_dup(ns_separator, lc_len); ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_class_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } if (Z_STRVAL_P(zv)[0] == '\\') { lc_len = Z_STRLEN_P(zv) - 1; lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv) + 1, lc_len); } else { lc_len = Z_STRLEN_P(zv); lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), lc_len); } ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); GET_CACHE_SLOT(ret); return ret; } /* }}} */ int zend_add_const_name_literal(zend_op_array *op_array, const zval *zv, int unqualified TSRMLS_DC) /* {{{ */ { int ret, tmp_literal; char *name, *tmp_name; const char *ns_separator; int name_len, ns_len; zval c; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } /* skip leading '\\' */ if (Z_STRVAL_P(zv)[0] == '\\') { name_len = Z_STRLEN_P(zv) - 1; name = Z_STRVAL_P(zv) + 1; } else { name_len = Z_STRLEN_P(zv); name = Z_STRVAL_P(zv); } ns_separator = zend_memrchr(name, '\\', name_len); if (ns_separator) { ns_len = ns_separator - name; } else { ns_len = 0; } if (ns_len) { /* lowercased namespace name & original constant name */ tmp_name = estrndup(name, name_len); zend_str_tolower(tmp_name, ns_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased namespace name & lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); } if (ns_len) { if (!unqualified) { return ret; } ns_len++; name += ns_len; name_len -= ns_len; } /* original constant name */ tmp_name = estrndup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); return ret; } /* }}} */ #define LITERAL_STRINGL(op, str, len, copy) do { \ zval _c; \ ZVAL_STRINGL(&_c, str, len, copy); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG(op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG_EX(op_array, op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(op_array, &_c TSRMLS_CC); \ } while (0) #define LITERAL_NULL(op) do { \ zval _c; \ INIT_ZVAL( _c); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) static inline zend_bool zend_is_function_or_method_call(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; return ((type & ZEND_PARSED_METHOD_CALL) || (type == ZEND_PARSED_FUNCTION_CALL)); } /* }}} */ void zend_do_binary_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_unary_op(zend_uchar op, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); GET_NODE(result, opline->result); SET_UNUSED(opline->op2); } /* }}} */ #define MAKE_NOP(opline) { opline->opcode = ZEND_NOP; memset(&opline->result,0,sizeof(opline->result)); memset(&opline->op1,0,sizeof(opline->op1)); memset(&opline->op2,0,sizeof(opline->op2)); opline->result_type=opline->op1_type=opline->op2_type=IS_UNUSED; } static void zend_do_op_data(zend_op *data_op, const znode *value TSRMLS_DC) /* {{{ */ { data_op->opcode = ZEND_OP_DATA; SET_NODE(data_op->op1, value); SET_UNUSED(data_op->op2); } /* }}} */ void zend_do_binary_assign_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; switch (last_op->opcode) { case ZEND_FETCH_OBJ_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, op2 TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; case ZEND_FETCH_DIM_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_DIM; zend_do_op_data(opline, op2 TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result,last_op->result); return; default: break; } } opline->opcode = op; SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void fetch_simple_variable_ex(znode *result, znode *varname, int bp, zend_uchar op TSRMLS_DC) /* {{{ */ { zend_op opline; zend_op *opline_ptr; zend_llist *fetch_list_ptr; if (varname->op_type == IS_CONST) { ulong hash = 0; if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } else if (IS_INTERNED(Z_STRVAL(varname->u.constant))) { hash = INTERNED_HASH(Z_STRVAL(varname->u.constant)); } if (!zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC) && !(varname->u.constant.value.str.len == (sizeof("this")-1) && !memcmp(varname->u.constant.value.str.val, "this", sizeof("this"))) && (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE)) { result->op_type = IS_CV; result->u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC); varname->u.constant.value.str.val = (char*)CG(active_op_array)->vars[result->u.op.var].name; result->EA = 0; return; } } if (bp) { opline_ptr = &opline; init_op(opline_ptr TSRMLS_CC); } else { opline_ptr = get_next_op(CG(active_op_array) TSRMLS_CC); } opline_ptr->opcode = op; opline_ptr->result_type = IS_VAR; opline_ptr->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline_ptr->op1, varname); GET_NODE(result, opline_ptr->result); SET_UNUSED(opline_ptr->op2); opline_ptr->extended_value = ZEND_FETCH_LOCAL; if (varname->op_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline_ptr->op1.constant); if (zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC)) { opline_ptr->extended_value = ZEND_FETCH_GLOBAL; } } if (bp) { zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); zend_llist_add_element(fetch_list_ptr, opline_ptr); } } /* }}} */ void fetch_simple_variable(znode *result, znode *varname, int bp TSRMLS_DC) /* {{{ */ { /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ fetch_simple_variable_ex(result, varname, bp, ZEND_FETCH_W TSRMLS_CC); } /* }}} */ void zend_do_fetch_static_member(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { znode class_node; zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline_ptr; zend_op opline; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); } zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (result->op_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[result->u.op.var].name), CG(active_op_array)->vars[result->u.op.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } GET_NODE(result,opline.result); opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; opline_ptr = &opline; zend_llist_add_element(fetch_list_ptr, &opline); } else { le = fetch_list_ptr->head; opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode != ZEND_FETCH_W && opline_ptr->op1_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[opline_ptr->op1.var].name), CG(active_op_array)->vars[opline_ptr->op1.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; COPY_NODE(opline_ptr->op1, opline.result); zend_llist_prepend_element(fetch_list_ptr, &opline); } else { if (opline_ptr->op1_type == IS_CONST) { GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op1.constant); } if (class_node.op_type == IS_CONST) { opline_ptr->op2_type = IS_CONST; opline_ptr->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline_ptr->op2, &class_node); } opline_ptr->extended_value |= ZEND_FETCH_STATIC_MEMBER; } } } /* }}} */ void fetch_array_begin(znode *result, znode *varname, znode *first_dim TSRMLS_DC) /* {{{ */ { fetch_simple_variable(result, varname, 1 TSRMLS_CC); fetch_array_dim(result, result, first_dim TSRMLS_CC); } /* }}} */ void fetch_array_dim(znode *result, const znode *parent, const znode *dim TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (zend_is_function_or_method_call(parent)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, parent); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_DIM_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, parent); SET_NODE(opline.op2, dim); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline.op2.constant)), Z_STRLEN(CONSTANT(opline.op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline.op2.constant)); ZVAL_LONG(&CONSTANT(opline.op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline.op2.constant); } } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void fetch_string_offset(znode *result, const znode *parent, const znode *offset TSRMLS_DC) /* {{{ */ { fetch_array_dim(result, parent, offset TSRMLS_CC); } /* }}} */ void zend_do_print(znode *result, const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->opcode = ZEND_PRINT; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_echo(const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ECHO; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_abstract_method(const znode *function_name, znode *modifiers, const znode *body TSRMLS_DC) /* {{{ */ { char *method_type; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { Z_LVAL(modifiers->u.constant) |= ZEND_ACC_ABSTRACT; method_type = "Interface"; } else { method_type = "Abstract"; } if (modifiers->u.constant.value.lval & ZEND_ACC_ABSTRACT) { if(modifiers->u.constant.value.lval & ZEND_ACC_PRIVATE) { zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot be declared private", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } if (Z_LVAL(body->u.constant) == ZEND_ACC_ABSTRACT) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_RAISE_ABSTRACT_ERROR; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } else { /* we had code in the function body */ zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot contain body", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } else { if (body->u.constant.value.lval == ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Non-abstract method %s::%s() must contain body", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } } /* }}} */ static zend_bool opline_is_fetch_this(const zend_op *opline TSRMLS_DC) /* {{{ */ { if ((opline->opcode == ZEND_FETCH_W) && (opline->op1_type == IS_CONST) && (Z_TYPE(CONSTANT(opline->op1.constant)) == IS_STRING) && (Z_HASH_P(&CONSTANT(opline->op1.constant)) == THIS_HASHVAL) && (Z_STRLEN(CONSTANT(opline->op1.constant)) == (sizeof("this")-1)) && !memcmp(Z_STRVAL(CONSTANT(opline->op1.constant)), "this", sizeof("this"))) { return 1; } else { return 0; } } /* }}} */ void zend_do_assign(znode *result, znode *variable, znode *value TSRMLS_DC) /* {{{ */ { int last_op_number; zend_op *opline; if (value->op_type == IS_CV) { zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (fetch_list_ptr && fetch_list_ptr->head) { opline = (zend_op *)fetch_list_ptr->head->data; if (opline->opcode == ZEND_FETCH_DIM_W && opline->op1_type == IS_CV && opline->op1.var == value->u.op.var) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_R; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->op1_type = IS_CONST; LITERAL_STRINGL(opline->op1, CG(active_op_array)->vars[value->u.op.var].name, CG(active_op_array)->vars[value->u.op.var].name_len, 1); CALCULATE_LITERAL_HASH(opline->op1.constant); SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_LOCAL; GET_NODE(value, opline->result); } } } zend_do_end_variable_parse(variable, BP_VAR_W, 0 TSRMLS_CC); last_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (variable->op_type == IS_CV) { if (variable->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (variable->op_type == IS_VAR) { int n = 0; while (last_op_number - n > 0) { zend_op *last_op; last_op = &CG(active_op_array)->opcodes[last_op_number-n-1]; if (last_op->result_type == IS_VAR && last_op->result.var == variable->u.op.var) { if (last_op->opcode == ZEND_FETCH_OBJ_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, value TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (last_op->opcode == ZEND_FETCH_DIM_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ /* TBFixed: this can realloc opcodes, leaving last_op pointing wrong */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_DIM; zend_do_op_data(opline, value TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (opline_is_fetch_this(last_op TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } else { break; } } n++; } } opline->opcode = ZEND_ASSIGN; SET_NODE(opline->op1, variable); SET_NODE(opline->op2, value); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_assign_ref(znode *result, const znode *lvar, const znode *rvar TSRMLS_DC) /* {{{ */ { zend_op *opline; if (lvar->op_type == IS_CV) { if (lvar->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (lvar->op_type == IS_VAR) { int last_op_number = get_next_op_number(CG(active_op_array)); if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline_is_fetch_this(opline TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ASSIGN_REF; if (zend_is_function_or_method_call(rvar)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } else if (rvar->EA & ZEND_PARSED_NEW) { opline->extended_value = ZEND_RETURNS_NEW; } else { opline->extended_value = 0; } if (result) { opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } else { opline->result_type = IS_UNUSED | EXT_TYPE_UNUSED; } SET_NODE(opline->op1, lvar); SET_NODE(opline->op2, rvar); } /* }}} */ static inline void do_begin_loop(TSRMLS_D) /* {{{ */ { zend_brk_cont_element *brk_cont_element; int parent; parent = CG(context).current_brk_cont; CG(context).current_brk_cont = CG(active_op_array)->last_brk_cont; brk_cont_element = get_next_brk_cont_element(CG(active_op_array)); brk_cont_element->start = get_next_op_number(CG(active_op_array)); brk_cont_element->parent = parent; } /* }}} */ static inline void do_end_loop(int cont_addr, int has_loop_var TSRMLS_DC) /* {{{ */ { if (!has_loop_var) { /* The start fileld is used to free temporary variables in case of exceptions. * We won't try to free something of we don't have loop variable. */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].start = -1; } CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = cont_addr; CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; } /* }}} */ void zend_do_while_cond(const znode *expr, znode *close_bracket_token TSRMLS_DC) /* {{{ */ { int while_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, expr); close_bracket_token->u.op.opline_num = while_cond_op_number; SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_while_end(const znode *while_token, const znode *close_bracket_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* add unconditional jump */ opline->opcode = ZEND_JMP; opline->op1.opline_num = while_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* update while's conditional jmp */ CG(active_op_array)->opcodes[close_bracket_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); do_end_loop(while_token->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_cond(const znode *expr, znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { int for_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZNZ; SET_NODE(opline->op1, expr); /* the conditional expression */ second_semicolon_token->u.op.opline_num = for_cond_op_number; SET_UNUSED(opline->op2); } /* }}} */ void zend_do_for_before_statement(const znode *cond_start, const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = cond_start->u.op.opline_num; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_end(const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = second_semicolon_token->u.op.opline_num+1; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_end_loop(second_semicolon_token->u.op.opline_num+1, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_pre_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_PRE_INC)?ZEND_PRE_INC_OBJ:ZEND_PRE_DEC_OBJ; last_op->result_type = IS_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_post_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_POST_INC)?ZEND_POST_INC_OBJ:ZEND_POST_DEC_OBJ; last_op->result_type = IS_TMP_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_if_cond(const znode *cond, znode *closing_bracket_token TSRMLS_DC) /* {{{ */ { int if_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); closing_bracket_token->u.op.opline_num = if_cond_op_number; SET_UNUSED(opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_if_after_statement(const znode *closing_bracket_token, unsigned char initialize TSRMLS_DC) /* {{{ */ { int if_end_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; /* save for backpatching */ if (initialize) { zend_llist jmp_list; zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); } zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &if_end_op_number); CG(active_op_array)->opcodes[closing_bracket_token->u.op.opline_num].op2.opline_num = if_end_op_number+1; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_if_end(TSRMLS_D) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_llist *jmp_list_ptr; zend_llist_element *le; zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); for (le=jmp_list_ptr->head; le; le = le->next) { CG(active_op_array)->opcodes[*((int *) le->data)].op1.opline_num = next_op_number; } zend_llist_destroy(jmp_list_ptr); zend_stack_del_top(&CG(bp_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_check_writable_variable(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; if (type & ZEND_PARSED_METHOD_CALL) { zend_error(E_COMPILE_ERROR, "Can't use method return value in write context"); } if (type == ZEND_PARSED_FUNCTION_CALL) { zend_error(E_COMPILE_ERROR, "Can't use function return value in write context"); } } /* }}} */ void zend_do_begin_variable_parse(TSRMLS_D) /* {{{ */ { zend_llist fetch_list; zend_llist_init(&fetch_list, sizeof(zend_op), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &fetch_list, sizeof(zend_llist)); } /* }}} */ void zend_do_end_variable_parse(znode *variable, int type, int arg_offset TSRMLS_DC) /* {{{ */ { zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline = NULL; zend_op *opline_ptr; zend_uint this_var = -1; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); le = fetch_list_ptr->head; /* TODO: $foo->x->y->z = 1 should fetch "x" and "y" for R or RW, not just W */ if (le) { opline_ptr = (zend_op *)le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { /* convert to FETCH_?(this) into IS_CV */ if (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE) { this_var = opline_ptr->result.var; if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), Z_STRVAL(CONSTANT(opline_ptr->op1.constant)), Z_STRLEN(CONSTANT(opline_ptr->op1.constant)), Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC); Z_TYPE(CONSTANT(opline_ptr->op1.constant)) = IS_NULL; } else { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); } le = le->next; if (variable->op_type == IS_VAR && variable->u.op.var == this_var) { variable->op_type = IS_CV; variable->u.op.var = CG(active_op_array)->this_var; } } else if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } while (le) { opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode == ZEND_SEPARATE) { if (type != BP_VAR_R && type != BP_VAR_IS) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); } le = le->next; continue; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); if (opline->op1_type == IS_VAR && opline->op1.var == this_var) { opline->op1_type = IS_CV; opline->op1.var = CG(active_op_array)->this_var; } switch (type) { case BP_VAR_R: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode -= 3; break; case BP_VAR_W: break; case BP_VAR_RW: opline->opcode += 3; break; case BP_VAR_IS: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode += 6; /* 3+3 */ break; case BP_VAR_FUNC_ARG: opline->opcode += 9; /* 3+3+3 */ opline->extended_value |= arg_offset; break; case BP_VAR_UNSET: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for unsetting"); } opline->opcode += 12; /* 3+3+3+3 */ break; } le = le->next; } if (opline && type == BP_VAR_W && arg_offset) { opline->extended_value |= ZEND_FETCH_MAKE_REF; } } zend_llist_destroy(fetch_list_ptr); zend_stack_del_top(&CG(bp_stack)); } /* }}} */ void zend_do_add_string(znode *result, const znode *op1, znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline; if (Z_STRLEN(op2->u.constant) > 1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_STRING; } else if (Z_STRLEN(op2->u.constant) == 1) { int ch = *Z_STRVAL(op2->u.constant); /* Free memory and use ZEND_ADD_CHAR in case of 1 character strings */ efree(Z_STRVAL(op2->u.constant)); ZVAL_LONG(&op2->u.constant, ch); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_CHAR; } else { /* String can be empty after a variable at the end of a heredoc */ efree(Z_STRVAL(op2->u.constant)); return; } if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_add_variable(znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_VAR; if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_free(znode *op1 TSRMLS_DC) /* {{{ */ { if (op1->op_type==IS_TMP_VAR) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else if (op1->op_type==IS_VAR) { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; while (opline->opcode == ZEND_END_SILENCE || opline->opcode == ZEND_EXT_FCALL_END || opline->opcode == ZEND_OP_DATA) { opline--; } if (opline->result_type == IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_FETCH_R || opline->opcode == ZEND_FETCH_DIM_R || opline->opcode == ZEND_FETCH_OBJ_R || opline->opcode == ZEND_QM_ASSIGN_VAR) { /* It's very rare and useless case. It's better to use additional FREE opcode and simplify the FETCH handlers their selves */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else { opline->result_type |= EXT_TYPE_UNUSED; } } else { while (opline>CG(active_op_array)->opcodes) { if (opline->opcode == ZEND_FETCH_DIM_R && opline->op1_type == IS_VAR && opline->op1.var == op1->u.op.var) { /* This should the end of a list() construct * Mark its result as unused */ opline->extended_value = ZEND_FETCH_STANDARD; break; } else if (opline->result_type==IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_NEW) { opline->result_type |= EXT_TYPE_UNUSED; } break; } opline--; } } } else if (op1->op_type == IS_CONST) { zval_dtor(&op1->u.constant); } } /* }}} */ int zend_do_verify_access_types(const znode *current_access_type, const znode *new_modifier) /* {{{ */ { if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_PPP_MASK) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Multiple access type modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_ABSTRACT) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Multiple abstract modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_STATIC) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Multiple static modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_FINAL) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Multiple final modifiers are not allowed"); } if (((Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)) & (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) == (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Cannot use the final modifier on an abstract class member"); } return (Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)); } /* }}} */ void zend_do_begin_function_declaration(znode *function_token, znode *function_name, int is_method, int return_reference, znode *fn_flags_znode TSRMLS_DC) /* {{{ */ { zend_op_array op_array; char *name = function_name->u.constant.value.str.val; int name_len = function_name->u.constant.value.str.len; int function_begin_line = function_token->u.op.opline_num; zend_uint fn_flags; const char *lcname; zend_bool orig_interactive; ALLOCA_FLAG(use_heap) if (is_method) { if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((Z_LVAL(fn_flags_znode->u.constant) & ~(ZEND_ACC_STATIC|ZEND_ACC_PUBLIC))) { zend_error(E_COMPILE_ERROR, "Access type for interface method %s::%s() must be omitted", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } Z_LVAL(fn_flags_znode->u.constant) |= ZEND_ACC_ABSTRACT; /* propagates to the rest of the parser */ } fn_flags = Z_LVAL(fn_flags_znode->u.constant); /* must be done *after* the above check */ } else { fn_flags = 0; } if ((fn_flags & ZEND_ACC_STATIC) && (fn_flags & ZEND_ACC_ABSTRACT) && !(CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_STRICT, "Static function %s%s%s() should not be abstract", is_method ? CG(active_class_entry)->name : "", is_method ? "::" : "", Z_STRVAL(function_name->u.constant)); } function_token->u.op_array = CG(active_op_array); orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(&op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; op_array.function_name = name; if (return_reference) { op_array.fn_flags |= ZEND_ACC_RETURN_REFERENCE; } op_array.fn_flags |= fn_flags; op_array.scope = is_method?CG(active_class_entry):NULL; op_array.prototype = NULL; op_array.line_start = zend_get_compiled_lineno(TSRMLS_C); if (is_method) { int result; lcname = zend_new_interned_string(zend_str_tolower_dup(name, name_len), name_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lcname)) { result = zend_hash_quick_add(&CG(active_class_entry)->function_table, lcname, name_len+1, INTERNED_HASH(lcname), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } else { result = zend_hash_add(&CG(active_class_entry)->function_table, lcname, name_len+1, &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } if (result == FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::%s()", CG(active_class_entry)->name, name); } zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); if (fn_flags & ZEND_ACC_ABSTRACT) { CG(active_class_entry)->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (!(fn_flags & ZEND_ACC_PPP_MASK)) { fn_flags |= ZEND_ACC_PUBLIC; } if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } } } else { char *class_lcname; class_lcname = do_alloca(CG(active_class_entry)->name_length + 1, use_heap); zend_str_tolower_copy(class_lcname, CG(active_class_entry)->name, CG(active_class_entry)->name_length); /* Improve after RC: cache the lowercase class name */ if ((CG(active_class_entry)->name_length == name_len) && ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT) && (!memcmp(class_lcname, lcname, name_len))) { if (!CG(active_class_entry)->constructor) { CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } } else if ((name_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)))) { if (CG(active_class_entry)->constructor) { zend_error(E_STRICT, "Redefining already defined constructor for class %s", CG(active_class_entry)->name); } CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1))) { CG(active_class_entry)->destructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1))) { CG(active_class_entry)->clone = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } CG(active_class_entry)->__call = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } CG(active_class_entry)->__callstatic = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } CG(active_class_entry)->__get = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } CG(active_class_entry)->__set = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } CG(active_class_entry)->__unset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } CG(active_class_entry)->__isset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } CG(active_class_entry)->__tostring = (zend_function *) CG(active_op_array); } else if (!(fn_flags & ZEND_ACC_STATIC)) { CG(active_op_array)->fn_flags |= ZEND_ACC_ALLOW_STATIC; } free_alloca(class_lcname, use_heap); } str_efree(lcname); } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zval key; if (CG(current_namespace)) { /* Prefix function name with current namespcae name */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, function_name TSRMLS_CC); op_array.function_name = Z_STRVAL(tmp.u.constant); name_len = Z_STRLEN(tmp.u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), name_len); } else { lcname = zend_str_tolower_dup(name, name_len); } opline->opcode = ZEND_DECLARE_FUNCTION; opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, name_len TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; LITERAL_STRINGL(opline->op2, lcname, name_len, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); opline->extended_value = ZEND_DECLARE_FUNCTION; zend_hash_quick_update(CG(function_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); } if (CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_NOP; opline->lineno = function_begin_line; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } { /* Push a seperator to the switch and foreach stacks */ zend_switch_entry switch_entry; switch_entry.cond.op_type = IS_UNUSED; switch_entry.default_case = 0; switch_entry.control_var = 0; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); { /* Foreach stack separator */ zend_op dummy_opline; dummy_opline.result_type = IS_UNUSED; dummy_opline.op1_type = IS_UNUSED; zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); } } if (CG(doc_comment)) { CG(active_op_array)->doc_comment = CG(doc_comment); CG(active_op_array)->doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_begin_lambda_function_declaration(znode *result, znode *function_token, int return_reference, int is_static TSRMLS_DC) /* {{{ */ { znode function_name; zend_op_array *current_op_array = CG(active_op_array); int current_op_number = get_next_op_number(CG(active_op_array)); zend_op *current_op; function_name.op_type = IS_CONST; ZVAL_STRINGL(&function_name.u.constant, "{closure}", sizeof("{closure}")-1, 1); zend_do_begin_function_declaration(function_token, &function_name, 0, return_reference, NULL TSRMLS_CC); result->op_type = IS_TMP_VAR; result->u.op.var = get_temporary_variable(current_op_array); current_op = &current_op_array->opcodes[current_op_number]; current_op->opcode = ZEND_DECLARE_LAMBDA_FUNCTION; zend_del_literal(current_op_array, current_op->op2.constant); SET_UNUSED(current_op->op2); SET_NODE(current_op->result, result); if (is_static) { CG(active_op_array)->fn_flags |= ZEND_ACC_STATIC; } CG(active_op_array)->fn_flags |= ZEND_ACC_CLOSURE; } /* }}} */ void zend_do_handle_exception(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_HANDLE_EXCEPTION; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_function_declaration(const znode *function_token TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; zend_do_extended_info(TSRMLS_C); zend_do_return(NULL, 0 TSRMLS_CC); pass_two(CG(active_op_array) TSRMLS_CC); zend_release_labels(TSRMLS_C); if (CG(active_class_entry)) { zend_check_magic_method_implementation(CG(active_class_entry), (zend_function*)CG(active_op_array), E_COMPILE_ERROR TSRMLS_CC); } else { /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(CG(active_op_array)->function_name); zend_str_tolower_copy(lcname, CG(active_op_array)->function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME)) && CG(active_op_array)->num_args != 1) { zend_error(E_COMPILE_ERROR, "%s() must take exactly 1 argument", ZEND_AUTOLOAD_FUNC_NAME); } } CG(active_op_array)->line_end = zend_get_compiled_lineno(TSRMLS_C); CG(active_op_array) = function_token->u.op_array; /* Pop the switch and foreach seperators */ zend_stack_del_top(&CG(switch_cond_stack)); zend_stack_del_top(&CG(foreach_copy_stack)); } /* }}} */ void zend_do_receive_arg(zend_uchar op, znode *varname, const znode *offset, const znode *initialization, znode *class_type, zend_uchar pass_by_reference TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_arg_info *cur_arg_info; znode var; if (class_type->op_type == IS_CONST && Z_TYPE(class_type->u.constant) == IS_STRING && Z_STRLEN(class_type->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_type->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } if (zend_is_auto_global_quick(Z_STRVAL(varname->u.constant), Z_STRLEN(varname->u.constant), 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign auto-global variable %s", Z_STRVAL(varname->u.constant)); } else { var.op_type = IS_CV; var.u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(varname->u.constant) = (char*)CG(active_op_array)->vars[var.u.op.var].name; var.EA = 0; if (CG(active_op_array)->vars[var.u.op.var].hash_value == THIS_HASHVAL && Z_STRLEN(varname->u.constant) == sizeof("this")-1 && !memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this")-1)) { if (CG(active_op_array)->scope && (CG(active_op_array)->fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } CG(active_op_array)->this_var = var.u.op.var; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->num_args++; opline->opcode = op; SET_NODE(opline->result, &var); SET_NODE(opline->op1, offset); if (op == ZEND_RECV_INIT) { SET_NODE(opline->op2, initialization); } else { CG(active_op_array)->required_num_args = CG(active_op_array)->num_args; SET_UNUSED(opline->op2); } CG(active_op_array)->arg_info = erealloc(CG(active_op_array)->arg_info, sizeof(zend_arg_info)*(CG(active_op_array)->num_args)); cur_arg_info = &CG(active_op_array)->arg_info[CG(active_op_array)->num_args-1]; cur_arg_info->name = zend_new_interned_string(estrndup(varname->u.constant.value.str.val, varname->u.constant.value.str.len), varname->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->name_len = varname->u.constant.value.str.len; cur_arg_info->type_hint = 0; cur_arg_info->allow_null = 1; cur_arg_info->pass_by_reference = pass_by_reference; cur_arg_info->class_name = NULL; cur_arg_info->class_name_len = 0; if (class_type->op_type != IS_UNUSED) { cur_arg_info->allow_null = 0; if (class_type->u.constant.type != IS_NULL) { if (class_type->u.constant.type == IS_ARRAY) { cur_arg_info->type_hint = IS_ARRAY; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else if (Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Default value for parameters with array type hint can only be an array or NULL"); } } } else if (class_type->u.constant.type == IS_CALLABLE) { cur_arg_info->type_hint = IS_CALLABLE; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with callable type hint can only be NULL"); } } } else { cur_arg_info->type_hint = IS_OBJECT; if (ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_type->u.constant), Z_STRLEN(class_type->u.constant))) { zend_resolve_class_name(class_type, opline->extended_value, 1 TSRMLS_CC); } Z_STRVAL(class_type->u.constant) = (char*)zend_new_interned_string(class_type->u.constant.value.str.val, class_type->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->class_name = class_type->u.constant.value.str.val; cur_arg_info->class_name_len = class_type->u.constant.value.str.len; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with a class type hint can only be NULL"); } } } } } } /* }}} */ int zend_do_begin_function_call(znode *function_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { zend_function *function; char *lcname; char *is_compound = memchr(Z_STRVAL(function_name->u.constant), '\\', Z_STRLEN(function_name->u.constant)); zend_resolve_non_class_name(function_name, check_namespace TSRMLS_CC); if (check_namespace && CG(current_namespace) && !is_compound) { /* We assume we call function from the current namespace if it is not prefixed. */ /* In run-time PHP will check for function with full name and internal function with short name */ zend_do_begin_dynamic_function_call(function_name, 1 TSRMLS_CC); return 1; } lcname = zend_str_tolower_dup(function_name->u.constant.value.str.val, function_name->u.constant.value.str.len); if ((zend_hash_find(CG(function_table), lcname, function_name->u.constant.value.str.len+1, (void **) &function)==FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_FUNCTIONS) && (function->type == ZEND_INTERNAL_FUNCTION))) { zend_do_begin_dynamic_function_call(function_name, 0 TSRMLS_CC); efree(lcname); return 1; /* Dynamic */ } efree(function_name->u.constant.value.str.val); function_name->u.constant.value.str.val = lcname; zend_stack_push(&CG(function_call_stack), (void *) &function, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 0; } /* }}} */ void zend_do_begin_method_call(znode *left_bracket TSRMLS_DC) /* {{{ */ { zend_op *last_op; int last_op_number; unsigned char *ptr = NULL; zend_do_end_variable_parse(left_bracket, BP_VAR_R, 0 TSRMLS_CC); zend_do_begin_variable_parse(TSRMLS_C); last_op_number = get_next_op_number(CG(active_op_array))-1; last_op = &CG(active_op_array)->opcodes[last_op_number]; if ((last_op->op2_type == IS_CONST) && (Z_TYPE(CONSTANT(last_op->op2.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(last_op->op2.constant)) == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !zend_binary_strcasecmp(Z_STRVAL(CONSTANT(last_op->op2.constant)), Z_STRLEN(CONSTANT(last_op->op2.constant)), ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1)) { zend_error(E_COMPILE_ERROR, "Cannot call __clone() method on objects - use 'clone $obj' instead"); } if (last_op->opcode == ZEND_FETCH_OBJ_R) { if (last_op->op2_type == IS_CONST) { zval name; name = CONSTANT(last_op->op2.constant); if (!IS_INTERNED(Z_STRVAL(name))) { Z_STRVAL(name) = estrndup(Z_STRVAL(name), Z_STRLEN(name)); } FREE_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); last_op->op2.constant = zend_add_func_name_literal(CG(active_op_array), &name TSRMLS_CC); GET_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); } last_op->opcode = ZEND_INIT_METHOD_CALL; SET_UNUSED(last_op->result); Z_LVAL(left_bracket->u.constant) = ZEND_INIT_FCALL_BY_NAME; } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (left_bracket->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &left_bracket->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, left_bracket); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_do_clone(znode *result, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CLONE; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_begin_dynamic_function_call(znode *function_name, int ns_call TSRMLS_DC) /* {{{ */ { unsigned char *ptr = NULL; zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (ns_call) { /* In run-time PHP will check for function with full name and internal function with short name */ opline->opcode = ZEND_INIT_NS_FCALL_BY_NAME; SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_ns_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (function_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, function_name); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_resolve_non_class_name(znode *element_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; int len; zval **ns; char *lcname, *compound = memchr(Z_STRVAL(element_name->u.constant), '\\', Z_STRLEN(element_name->u.constant)); if (Z_STRVAL(element_name->u.constant)[0] == '\\') { /* name starts with \ so it is known and unambiguos, nothing to do here but shorten it */ memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+1, Z_STRLEN(element_name->u.constant)); --Z_STRLEN(element_name->u.constant); return; } if(!check_namespace) { return; } if (compound && CG(current_import)) { len = compound - Z_STRVAL(element_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(element_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(element_name->u.constant) -= len; memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+len, Z_STRLEN(element_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, element_name TSRMLS_CC); *element_name = tmp; efree(lcname); return; } efree(lcname); } if (CG(current_namespace)) { tmp = *element_name; Z_STRLEN(tmp.u.constant) = sizeof("\\")-1 + Z_STRLEN(element_name->u.constant) + Z_STRLEN_P(CG(current_namespace)); Z_STRVAL(tmp.u.constant) = (char *) emalloc(Z_STRLEN(tmp.u.constant)+1); memcpy(Z_STRVAL(tmp.u.constant), Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace))]), "\\", sizeof("\\")-1); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace)) + sizeof("\\")-1]), Z_STRVAL(element_name->u.constant), Z_STRLEN(element_name->u.constant)+1); STR_FREE(Z_STRVAL(element_name->u.constant)); *element_name = tmp; } } /* }}} */ void zend_resolve_class_name(znode *class_name, ulong fetch_type, int check_ns_name TSRMLS_DC) /* {{{ */ { char *compound; char *lcname; zval **ns; znode tmp; int len; compound = memchr(Z_STRVAL(class_name->u.constant), '\\', Z_STRLEN(class_name->u.constant)); if (compound) { /* This is a compound class name that contains namespace prefix */ if (Z_STRVAL(class_name->u.constant)[0] == '\\') { /* The STRING name has "\" prefix */ Z_STRLEN(class_name->u.constant) -= 1; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+1, Z_STRLEN(class_name->u.constant)+1); Z_STRVAL(class_name->u.constant) = erealloc( Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1); if (ZEND_FETCH_CLASS_DEFAULT != zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "'\\%s' is an invalid class name", Z_STRVAL(class_name->u.constant)); } } else { if (CG(current_import)) { len = compound - Z_STRVAL(class_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(class_name->u.constant) -= len; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+len, Z_STRLEN(class_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; efree(lcname); return; } efree(lcname); } /* Here name is not prefixed with \ and not imported */ if (CG(current_namespace)) { tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } } } else if (CG(current_import) || CG(current_namespace)) { /* this is a plain name (without \) */ lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns) == SUCCESS) { /* The given name is an import name. Substitute it. */ zval_dtor(&class_name->u.constant); class_name->u.constant = **ns; zval_copy_ctor(&class_name->u.constant); } else if (CG(current_namespace)) { /* plain name, no import - prepend current namespace to it */ tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } efree(lcname); } } /* }}} */ void zend_do_fetch_class(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { long fetch_class_op_number; zend_op *opline; if (class_name->op_type == IS_CONST && Z_TYPE(class_name->u.constant) == IS_STRING && Z_STRLEN(class_name->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_name->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } fetch_class_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CLASS; SET_UNUSED(opline->op1); opline->extended_value = ZEND_FETCH_CLASS_GLOBAL; CG(catch_begin) = fetch_class_op_number; if (class_name->op_type == IS_CONST) { int fetch_type; fetch_type = zend_get_class_fetch_type(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); switch (fetch_type) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: SET_UNUSED(opline->op2); opline->extended_value = fetch_type; zval_dtor(&class_name->u.constant); break; default: zend_resolve_class_name(class_name, opline->extended_value, 0 TSRMLS_CC); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_name->u.constant TSRMLS_CC); break; } } else { SET_NODE(opline->op2, class_name); } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; /* FIXME: Hack so that INIT_FCALL_BY_NAME still knows this is a class */ GET_NODE(result, opline->result); result->EA = opline->extended_value; } /* }}} */ void zend_do_label(znode *label TSRMLS_DC) /* {{{ */ { zend_label dest; if (!CG(context).labels) { ALLOC_HASHTABLE(CG(context).labels); zend_hash_init(CG(context).labels, 4, NULL, NULL, 0); } dest.brk_cont = CG(context).current_brk_cont; dest.opline_num = get_next_op_number(CG(active_op_array)); if (zend_hash_add(CG(context).labels, Z_STRVAL(label->u.constant), Z_STRLEN(label->u.constant) + 1, (void**)&dest, sizeof(zend_label), NULL) == FAILURE) { zend_error(E_COMPILE_ERROR, "Label '%s' already defined", Z_STRVAL(label->u.constant)); } /* Done with label now */ zval_dtor(&label->u.constant); } /* }}} */ void zend_resolve_goto_label(zend_op_array *op_array, zend_op *opline, int pass2 TSRMLS_DC) /* {{{ */ { zend_label *dest; long current, distance; zval *label; if (pass2) { label = opline->op2.zv; } else { label = &CONSTANT_EX(op_array, opline->op2.constant); } if (CG(context).labels == NULL || zend_hash_find(CG(context).labels, Z_STRVAL_P(label), Z_STRLEN_P(label)+1, (void**)&dest) == FAILURE) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; zend_error(E_COMPILE_ERROR, "'goto' to undefined label '%s'", Z_STRVAL_P(label)); } else { /* Label is not defined. Delay to pass 2. */ INC_BPC(op_array); return; } } opline->op1.opline_num = dest->opline_num; zval_dtor(label); Z_TYPE_P(label) = IS_NULL; /* Check that we are not moving into loop or switch */ current = opline->extended_value; for (distance = 0; current != dest->brk_cont; distance++) { if (current == -1) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; } zend_error(E_COMPILE_ERROR, "'goto' into loop or switch statement is disallowed"); } current = op_array->brk_cont_array[current].parent; } if (distance == 0) { /* Nothing to break out of, optimize to ZEND_JMP */ opline->opcode = ZEND_JMP; opline->extended_value = 0; SET_UNUSED(opline->op2); } else { /* Set real break distance */ ZVAL_LONG(label, distance); } if (pass2) { DEC_BPC(op_array); } } /* }}} */ void zend_do_goto(const znode *label TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_GOTO; opline->extended_value = CG(context).current_brk_cont; SET_UNUSED(opline->op1); SET_NODE(opline->op2, label); zend_resolve_goto_label(CG(active_op_array), opline, 0 TSRMLS_CC); } /* }}} */ void zend_release_labels(TSRMLS_D) /* {{{ */ { if (CG(context).labels) { zend_hash_destroy(CG(context).labels); FREE_HASHTABLE(CG(context).labels); } if (!zend_stack_is_empty(&CG(context_stack))) { zend_compiler_context *ctx; zend_stack_top(&CG(context_stack), (void**)&ctx); CG(context) = *ctx; zend_stack_del_top(&CG(context_stack)); } } /* }}} */ void zend_do_build_full_name(znode *result, znode *prefix, znode *name, int is_class_member TSRMLS_DC) /* {{{ */ { zend_uint length; if (!result) { result = prefix; } else { *result = *prefix; } if (is_class_member) { length = sizeof("::")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "::", sizeof("::")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("::")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } else { length = sizeof("\\")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "\\", sizeof("\\")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("\\")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } } /* }}} */ int zend_do_begin_class_member_function_call(znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { znode class_node; unsigned char *ptr = NULL; zend_op *opline; if (method_name->op_type == IS_CONST) { char *lcname = zend_str_tolower_dup(Z_STRVAL(method_name->u.constant), Z_STRLEN(method_name->u.constant)); if ((sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == Z_STRLEN(method_name->u.constant) && memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == 0) { zval_dtor(&method_name->u.constant); method_name->op_type = IS_UNUSED; } efree(lcname); } if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; opline = get_next_op(CG(active_op_array) TSRMLS_CC); } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->extended_value = class_node.EA ; } opline->opcode = ZEND_INIT_STATIC_METHOD_CALL; if (class_node.op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, &class_node); } if (method_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &method_name->u.constant TSRMLS_CC); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } } else { SET_NODE(opline->op2, method_name); } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 1; /* Dynamic */ } /* }}} */ void zend_do_end_function_call(znode *function_name, znode *result, const znode *argument_list, int is_method, int is_dynamic_fcall TSRMLS_DC) /* {{{ */ { zend_op *opline; if (is_method && function_name && function_name->op_type == IS_UNUSED) { /* clone */ if (Z_LVAL(argument_list->u.constant) != 0) { zend_error(E_WARNING, "Clone method does not require arguments"); } opline = &CG(active_op_array)->opcodes[Z_LVAL(function_name->u.constant)]; } else { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (!is_method && !is_dynamic_fcall && function_name->op_type==IS_CONST) { opline->opcode = ZEND_DO_FCALL; SET_NODE(opline->op1, function_name); CALCULATE_LITERAL_HASH(opline->op1.constant); GET_CACHE_SLOT(opline->op1.constant); } else { opline->opcode = ZEND_DO_FCALL_BY_NAME; SET_UNUSED(opline->op1); } } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(result, opline->result) ; SET_UNUSED(opline->op2); zend_stack_del_top(&CG(function_call_stack)); opline->extended_value = Z_LVAL(argument_list->u.constant); } /* }}} */ void zend_do_pass_param(znode *param, zend_uchar op, int offset TSRMLS_DC) /* {{{ */ { zend_op *opline; int original_op=op; zend_function **function_ptr_ptr, *function_ptr; int send_by_reference; int send_function = 0; zend_stack_top(&CG(function_call_stack), (void **) &function_ptr_ptr); function_ptr = *function_ptr_ptr; if (original_op == ZEND_SEND_REF) { if (function_ptr && function_ptr->common.function_name && function_ptr->common.type == ZEND_USER_FUNCTION && !ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed; " "If you would like to pass argument by reference, modify the declaration of %s().", function_ptr->common.function_name); } else { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed"); } return; } if (function_ptr) { if (ARG_MAY_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { if (param->op_type & (IS_VAR|IS_CV) && original_op != ZEND_SEND_VAL) { send_by_reference = 1; if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION | ZEND_ARG_SEND_SILENT; } } else { op = ZEND_SEND_VAL; send_by_reference = 0; } } else { send_by_reference = ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset) ? ZEND_ARG_SEND_BY_REF : 0; } } else { send_by_reference = 0; } if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION; } else if (op == ZEND_SEND_VAL && (param->op_type & (IS_VAR|IS_CV))) { op = ZEND_SEND_VAR_NO_REF; } if (op!=ZEND_SEND_VAR_NO_REF && send_by_reference==ZEND_ARG_SEND_BY_REF) { /* change to passing by reference */ switch (param->op_type) { case IS_VAR: case IS_CV: op = ZEND_SEND_REF; break; default: zend_error(E_COMPILE_ERROR, "Only variables can be passed by reference"); break; } } if (original_op == ZEND_SEND_VAR) { switch (op) { case ZEND_SEND_VAR_NO_REF: zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); break; case ZEND_SEND_VAR: if (function_ptr) { zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(param, BP_VAR_FUNC_ARG, offset TSRMLS_CC); } break; case ZEND_SEND_REF: zend_do_end_variable_parse(param, BP_VAR_W, 0 TSRMLS_CC); break; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (op == ZEND_SEND_VAR_NO_REF) { if (function_ptr) { opline->extended_value = ZEND_ARG_COMPILE_TIME_BOUND | send_by_reference | send_function; } else { opline->extended_value = send_function; } } else { if (function_ptr) { opline->extended_value = ZEND_DO_FCALL; } else { opline->extended_value = ZEND_DO_FCALL_BY_NAME; } } opline->opcode = op; SET_NODE(opline->op1, param); opline->op2.opline_num = offset; SET_UNUSED(opline->op2); } /* }}} */ static int generate_free_switch_expr(const zend_switch_entry *switch_entry TSRMLS_DC) /* {{{ */ { zend_op *opline; if (switch_entry->cond.op_type != IS_VAR && switch_entry->cond.op_type != IS_TMP_VAR) { return (switch_entry->cond.op_type == IS_UNUSED); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry->cond); SET_UNUSED(opline->op2); opline->extended_value = 0; return 0; } /* }}} */ static int generate_free_foreach_copy(const zend_op *foreach_copy TSRMLS_DC) /* {{{ */ { zend_op *opline; /* If we reach the seperator then stop applying the stack */ if (foreach_copy->result_type == IS_UNUSED && foreach_copy->op1_type == IS_UNUSED) { return 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->result_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->result); SET_UNUSED(opline->op2); opline->extended_value = 1; if (foreach_copy->op1_type != IS_UNUSED) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->op1_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->op1); SET_UNUSED(opline->op2); opline->extended_value = 0; } return 0; } /* }}} */ void zend_do_return(znode *expr, int do_end_vparse TSRMLS_DC) /* {{{ */ { zend_op *opline; int start_op_number, end_op_number; if (do_end_vparse) { if ((CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) && !zend_is_function_or_method_call(expr)) { zend_do_end_variable_parse(expr, BP_VAR_W, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(expr, BP_VAR_R, 0 TSRMLS_CC); } } start_op_number = get_next_op_number(CG(active_op_array)); #ifdef ZTS zend_stack_apply_with_argument(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_switch_expr TSRMLS_CC); zend_stack_apply_with_argument(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_foreach_copy TSRMLS_CC); #else zend_stack_apply(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_switch_expr); zend_stack_apply(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_foreach_copy); #endif end_op_number = get_next_op_number(CG(active_op_array)); while (start_op_number < end_op_number) { CG(active_op_array)->opcodes[start_op_number].extended_value |= EXT_TYPE_FREE_ON_RETURN; start_op_number++; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) ? ZEND_RETURN_BY_REF : ZEND_RETURN; if (expr) { SET_NODE(opline->op1, expr); if (do_end_vparse && zend_is_function_or_method_call(expr)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } } else { opline->op1_type = IS_CONST; LITERAL_NULL(opline->op1); } SET_UNUSED(opline->op2); } /* }}} */ static int zend_add_try_element(zend_uint try_op TSRMLS_DC) /* {{{ */ { int try_catch_offset = CG(active_op_array)->last_try_catch++; CG(active_op_array)->try_catch_array = erealloc(CG(active_op_array)->try_catch_array, sizeof(zend_try_catch_element)*CG(active_op_array)->last_try_catch); CG(active_op_array)->try_catch_array[try_catch_offset].try_op = try_op; return try_catch_offset; } /* }}} */ static void zend_add_catch_element(int offset, zend_uint catch_op TSRMLS_DC) /* {{{ */ { CG(active_op_array)->try_catch_array[offset].catch_op = catch_op; } /* }}} */ void zend_do_first_catch(znode *open_parentheses TSRMLS_DC) /* {{{ */ { open_parentheses->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_initialize_try_catch_element(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist jmp_list; zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); zend_add_catch_element(try_token->u.op.opline_num, get_next_op_number(CG(active_op_array)) TSRMLS_CC); } /* }}} */ void zend_do_mark_last_catch(const znode *first_catch, const znode *last_additional_catch TSRMLS_DC) /* {{{ */ { CG(active_op_array)->last--; zend_do_if_end(TSRMLS_C); if (last_additional_catch->u.op.opline_num == -1) { CG(active_op_array)->opcodes[first_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[first_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } else { CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_try(znode *try_token TSRMLS_DC) /* {{{ */ { try_token->u.op.opline_num = zend_add_try_element(get_next_op_number(CG(active_op_array)) TSRMLS_CC); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_catch(znode *try_token, znode *class_name, znode *catch_var, znode *first_catch TSRMLS_DC) /* {{{ */ { long catch_op_number; zend_op *opline; znode catch_class; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); catch_class = *class_name; } else { zend_error(E_COMPILE_ERROR, "Bad class name in the catch statement"); } catch_op_number = get_next_op_number(CG(active_op_array)); if (first_catch) { first_catch->u.op.opline_num = catch_op_number; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CATCH; opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &catch_class.u.constant TSRMLS_CC); opline->op2_type = IS_CV; opline->op2.var = lookup_cv(CG(active_op_array), catch_var->u.constant.value.str.val, catch_var->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(catch_var->u.constant) = (char*)CG(active_op_array)->vars[opline->op2.var].name; opline->result.num = 0; /* 1 means it's the last catch in the block */ try_token->u.op.opline_num = catch_op_number; } /* }}} */ void zend_do_end_catch(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); CG(active_op_array)->opcodes[try_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_throw(const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_THROW; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); } /* }}} */ ZEND_API void function_add_ref(zend_function *function) /* {{{ */ { if (function->type == ZEND_USER_FUNCTION) { zend_op_array *op_array = &function->op_array; (*op_array->refcount)++; if (op_array->static_variables) { HashTable *static_variables = op_array->static_variables; zval *tmp_zval; ALLOC_HASHTABLE(op_array->static_variables); zend_hash_init(op_array->static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(op_array->static_variables, static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_zval, sizeof(zval *)); } op_array->run_time_cache = NULL; } } /* }}} */ static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */ { zend_function *function; if (!ce->parent) { return; } /* You cannot change create_object */ ce->create_object = ce->parent->create_object; /* Inherit special functions if needed */ if (!ce->get_iterator) { ce->get_iterator = ce->parent->get_iterator; } if (!ce->iterator_funcs.funcs) { ce->iterator_funcs.funcs = ce->parent->iterator_funcs.funcs; } if (!ce->__get) { ce->__get = ce->parent->__get; } if (!ce->__set) { ce->__set = ce->parent->__set; } if (!ce->__unset) { ce->__unset = ce->parent->__unset; } if (!ce->__isset) { ce->__isset = ce->parent->__isset; } if (!ce->__call) { ce->__call = ce->parent->__call; } if (!ce->__callstatic) { ce->__callstatic = ce->parent->__callstatic; } if (!ce->__tostring) { ce->__tostring = ce->parent->__tostring; } if (!ce->clone) { ce->clone = ce->parent->clone; } if(!ce->serialize) { ce->serialize = ce->parent->serialize; } if(!ce->unserialize) { ce->unserialize = ce->parent->unserialize; } if (!ce->destructor) { ce->destructor = ce->parent->destructor; } if (ce->constructor) { if (ce->parent->constructor && ce->parent->constructor->common.fn_flags & ZEND_ACC_FINAL) { zend_error(E_ERROR, "Cannot override final %s::%s() with %s::%s()", ce->parent->name, ce->parent->constructor->common.function_name, ce->name, ce->constructor->common.function_name ); } return; } if (zend_hash_find(&ce->parent->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), (void **)&function)==SUCCESS) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), function, sizeof(zend_function), NULL); function_add_ref(function); } else { /* Don't inherit the old style constructor if we already have the new style constructor */ char *lc_class_name; char *lc_parent_class_name; lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); if (!zend_hash_exists(&ce->function_table, lc_class_name, ce->name_length+1)) { lc_parent_class_name = zend_str_tolower_dup(ce->parent->name, ce->parent->name_length); if (!zend_hash_exists(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1) && zend_hash_find(&ce->parent->function_table, lc_parent_class_name, ce->parent->name_length+1, (void **)&function)==SUCCESS) { if (function->common.fn_flags & ZEND_ACC_CTOR) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1, function, sizeof(zend_function), NULL); function_add_ref(function); } } efree(lc_parent_class_name); } efree(lc_class_name); } ce->constructor = ce->parent->constructor; } /* }}} */ char *zend_visibility_string(zend_uint fn_flags) /* {{{ */ { if (fn_flags & ZEND_ACC_PRIVATE) { return "private"; } if (fn_flags & ZEND_ACC_PROTECTED) { return "protected"; } if (fn_flags & ZEND_ACC_PUBLIC) { return "public"; } return ""; } /* }}} */ static void do_inherit_method(zend_function *function) /* {{{ */ { /* The class entry of the derived function intentionally remains the same * as that of the parent class. That allows us to know in which context * we're running, and handle private method calls properly. */ function_add_ref(function); } /* }}} */ static zend_bool zend_do_perform_implementation_check(const zend_function *fe, const zend_function *proto TSRMLS_DC) /* {{{ */ { zend_uint i; /* If it's a user function then arg_info == NULL means we don't have any parameters but * we still need to do the arg number checks. We are only willing to ignore this for internal * functions because extensions don't always define arg_info. */ if (!proto || (!proto->common.arg_info && proto->common.type != ZEND_USER_FUNCTION)) { return 1; } /* Checks for constructors only if they are declared in an interface, * or explicitly marked as abstract */ if ((fe->common.fn_flags & ZEND_ACC_CTOR) && ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)) { return 1; } /* check number of arguments */ if (proto->common.required_num_args < fe->common.required_num_args || proto->common.num_args > fe->common.num_args) { return 0; } if (fe->common.type != ZEND_USER_FUNCTION && (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) != 0 && (fe->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) == 0) { return 0; } /* by-ref constraints on return values are covariant */ if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) { return 0; } for (i=0; i < proto->common.num_args; i++) { if (ZEND_LOG_XOR(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)) { /* Only one has a type hint and the other one doesn't */ return 0; } if (fe->common.arg_info[i].class_name && strcasecmp(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)!=0) { const char *colon; if (fe->common.type != ZEND_USER_FUNCTION) { return 0; } else if (strchr(proto->common.arg_info[i].class_name, '\\') != NULL || (colon = zend_memrchr(fe->common.arg_info[i].class_name, '\\', fe->common.arg_info[i].class_name_len)) == NULL || strcasecmp(colon+1, proto->common.arg_info[i].class_name) != 0) { zend_class_entry **fe_ce, **proto_ce; int found, found2; found = zend_lookup_class(fe->common.arg_info[i].class_name, fe->common.arg_info[i].class_name_len, &fe_ce TSRMLS_CC); found2 = zend_lookup_class(proto->common.arg_info[i].class_name, proto->common.arg_info[i].class_name_len, &proto_ce TSRMLS_CC); /* Check for class alias */ if (found != SUCCESS || found2 != SUCCESS || (*fe_ce)->type == ZEND_INTERNAL_CLASS || (*proto_ce)->type == ZEND_INTERNAL_CLASS || *fe_ce != *proto_ce) { return 0; } } } if (fe->common.arg_info[i].type_hint != proto->common.arg_info[i].type_hint) { /* Incompatible type hint */ return 0; } /* by-ref constraints on arguments are invariant */ if (fe->common.arg_info[i].pass_by_reference != proto->common.arg_info[i].pass_by_reference) { return 0; } } if (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) { for (i=proto->common.num_args; i < fe->common.num_args; i++) { if (!fe->common.arg_info[i].pass_by_reference) { return 0; } } } return 1; } /* }}} */ #define REALLOC_BUF_IF_EXCEED(buf, offset, length, size) \ if (UNEXPECTED(offset - buf + size >= length)) { \ length += size + 1; \ buf = erealloc(buf, length); \ } static char * zend_get_function_declaration(zend_function *fptr TSRMLS_DC) /* {{{ */ { char *offset, *buf; zend_uint length = 1024; offset = buf = (char *)emalloc(length * sizeof(char)); if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { *(offset++) = '&'; *(offset++) = ' '; } if (fptr->common.scope) { memcpy(offset, fptr->common.scope->name, fptr->common.scope->name_length); offset += fptr->common.scope->name_length; *(offset++) = ':'; *(offset++) = ':'; } { size_t name_len = strlen(fptr->common.function_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, name_len); memcpy(offset, fptr->common.function_name, name_len); offset += name_len; } *(offset++) = '('; if (fptr->common.arg_info) { zend_uint i, required; zend_arg_info *arg_info = fptr->common.arg_info; required = fptr->common.required_num_args; for (i = 0; i < fptr->common.num_args;) { if (arg_info->class_name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->class_name_len); memcpy(offset, arg_info->class_name, arg_info->class_name_len); offset += arg_info->class_name_len; *(offset++) = ' '; } else if (arg_info->type_hint) { zend_uint type_name_len; char *type_name = zend_get_type_by_const(arg_info->type_hint); type_name_len = strlen(type_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, type_name_len); memcpy(offset, type_name, type_name_len); offset += type_name_len; *(offset++) = ' '; } if (arg_info->pass_by_reference) { *(offset++) = '&'; } *(offset++) = '$'; if (arg_info->name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->name_len); memcpy(offset, arg_info->name, arg_info->name_len); offset += arg_info->name_len; } else { zend_uint idx = i; memcpy(offset, "param", 5); offset += 5; do { *(offset++) = (char) (idx % 10) + '0'; idx /= 10; } while (idx > 0); } if (i >= required) { *(offset++) = ' '; *(offset++) = '='; *(offset++) = ' '; if (fptr->type == ZEND_USER_FUNCTION) { zend_op *precv = NULL; { zend_uint idx = i; zend_op *op = ((zend_op_array *)fptr)->opcodes; zend_op *end = op + ((zend_op_array *)fptr)->last; ++idx; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT) && op->op1.num == (long)idx) { precv = op; } ++op; } } if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) { zval *zv, zv_copy; int use_copy; ALLOC_ZVAL(zv); *zv = *precv->op2.zv; zval_copy_ctor(zv); INIT_PZVAL(zv); zval_update_constant_ex(&zv, (void*)1, fptr->common.scope TSRMLS_CC); if (Z_TYPE_P(zv) == IS_BOOL) { if (Z_LVAL_P(zv)) { memcpy(offset, "true", 4); offset += 4; } else { memcpy(offset, "false", 5); offset += 5; } } else if (Z_TYPE_P(zv) == IS_NULL) { memcpy(offset, "NULL", 4); offset += 4; } else if (Z_TYPE_P(zv) == IS_STRING) { *(offset++) = '\''; REALLOC_BUF_IF_EXCEED(buf, offset, length, MIN(Z_STRLEN_P(zv), 10)); memcpy(offset, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 10)); offset += MIN(Z_STRLEN_P(zv), 10); if (Z_STRLEN_P(zv) > 10) { *(offset++) = '.'; *(offset++) = '.'; *(offset++) = '.'; } *(offset++) = '\''; } else if (Z_TYPE_P(zv) == IS_ARRAY) { memcpy(offset, "Array", 5); offset += 5; } else { zend_make_printable_zval(zv, &zv_copy, &use_copy); REALLOC_BUF_IF_EXCEED(buf, offset, length, Z_STRLEN(zv_copy)); memcpy(offset, Z_STRVAL(zv_copy), Z_STRLEN(zv_copy)); offset += Z_STRLEN(zv_copy); if (use_copy) { zval_dtor(&zv_copy); } } zval_ptr_dtor(&zv); } } else { memcpy(offset, "NULL", 4); offset += 4; } } if (++i < fptr->common.num_args) { *(offset++) = ','; *(offset++) = ' '; } arg_info++; REALLOC_BUF_IF_EXCEED(buf, offset, length, 32); } } *(offset++) = ')'; *offset = '\0'; return buf; } /* }}} */ static void do_inheritance_check_on_method(zend_function *child, zend_function *parent TSRMLS_DC) /* {{{ */ { zend_uint child_flags; zend_uint parent_flags = parent->common.fn_flags; if ((parent->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && parent->common.fn_flags & ZEND_ACC_ABSTRACT && parent->common.scope != (child->common.prototype ? child->common.prototype->common.scope : child->common.scope) && child->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_IMPLEMENTED_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Can't inherit abstract function %s::%s() (previously declared abstract in %s)", parent->common.scope->name, child->common.function_name, child->common.prototype ? child->common.prototype->common.scope->name : child->common.scope->name); } if (parent_flags & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot override final method %s::%s()", ZEND_FN_SCOPE_NAME(parent), child->common.function_name); } child_flags = child->common.fn_flags; /* You cannot change from static to non static and vice versa. */ if ((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC)) { if (child->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot make non static method %s::%s() static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } else { zend_error(E_COMPILE_ERROR, "Cannot make static method %s::%s() non static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } } /* Disallow making an inherited method abstract. */ if ((child_flags & ZEND_ACC_ABSTRACT) && !(parent_flags & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Cannot make non abstract method %s::%s() abstract in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } if (parent_flags & ZEND_ACC_CHANGED) { child->common.fn_flags |= ZEND_ACC_CHANGED; } else { /* Prevent derived classes from restricting access that was available in parent classes */ if ((child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::%s() must be %s (as in class %s)%s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if (((child_flags & ZEND_ACC_PPP_MASK) < (parent_flags & ZEND_ACC_PPP_MASK)) && ((parent_flags & ZEND_ACC_PPP_MASK) & ZEND_ACC_PRIVATE)) { child->common.fn_flags |= ZEND_ACC_CHANGED; } } if (parent_flags & ZEND_ACC_PRIVATE) { child->common.prototype = NULL; } else if (parent_flags & ZEND_ACC_ABSTRACT) { child->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; child->common.prototype = parent; } else if (!(parent->common.fn_flags & ZEND_ACC_CTOR) || (parent->common.prototype && (parent->common.prototype->common.scope->ce_flags & ZEND_ACC_INTERFACE))) { /* ctors only have a prototype if it comes from an interface */ child->common.prototype = parent->common.prototype ? parent->common.prototype : parent; } if (child->common.prototype && (child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { if (!zend_do_perform_implementation_check(child, child->common.prototype TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s::%s() must be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_get_function_declaration(child->common.prototype TSRMLS_CC)); } } else if (EG(error_reporting) & E_STRICT || EG(user_error_handler)) { /* Check E_STRICT (or custom error handler) before the check so that we save some time */ if (!zend_do_perform_implementation_check(child, parent TSRMLS_CC)) { char *method_prototype = zend_get_function_declaration(child->common.prototype TSRMLS_CC); zend_error(E_STRICT, "Declaration of %s::%s() should be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, method_prototype); efree(method_prototype); } } } /* }}} */ static zend_bool do_inherit_method_check(HashTable *child_function_table, zend_function *parent, const zend_hash_key *hash_key, zend_class_entry *child_ce) /* {{{ */ { zend_uint parent_flags = parent->common.fn_flags; zend_function *child; TSRMLS_FETCH(); if (zend_hash_quick_find(child_function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child)==FAILURE) { if (parent_flags & (ZEND_ACC_ABSTRACT)) { child_ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } return 1; /* method doesn't exist in child, copy from parent */ } do_inheritance_check_on_method(child, parent TSRMLS_CC); return 0; } /* }}} */ static zend_bool do_inherit_property_access_check(HashTable *target_ht, zend_property_info *parent_info, const zend_hash_key *hash_key, zend_class_entry *ce) /* {{{ */ { zend_property_info *child_info; zend_class_entry *parent_ce = ce->parent; if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW)) { if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { child_info->flags |= ZEND_ACC_CHANGED; } else { zend_hash_quick_update(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, parent_info, sizeof(zend_property_info), (void **) &child_info); if(ce->type & ZEND_INTERNAL_CLASS) { zend_duplicate_property_info_internal(child_info); } else { zend_duplicate_property_info(child_info); } child_info->flags &= ~ZEND_ACC_PRIVATE; /* it's not private anymore */ child_info->flags |= ZEND_ACC_SHADOW; /* but it's a shadow of private */ } return 0; /* don't copy access information to child */ } if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { if ((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s", (parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", parent_ce->name, hash_key->arKey, (child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ce->name, hash_key->arKey); } if(parent_info->flags & ZEND_ACC_CHANGED) { child_info->flags |= ZEND_ACC_CHANGED; } if ((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ce->name, hash_key->arKey, zend_visibility_string(parent_info->flags), parent_ce->name, (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if ((child_info->flags & ZEND_ACC_STATIC) == 0) { Z_DELREF_P(ce->default_properties_table[parent_info->offset]); ce->default_properties_table[parent_info->offset] = ce->default_properties_table[child_info->offset]; ce->default_properties_table[child_info->offset] = NULL; child_info->offset = parent_info->offset; } return 0; /* Don't copy from parent */ } else { return 1; /* Copy from parent */ } } /* }}} */ static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce TSRMLS_CC) == FAILURE) { zend_error(E_CORE_ERROR, "Class %s could not implement interface %s", ce->name, iface->name); } if (ce == iface) { zend_error(E_ERROR, "Interface %s cannot implement itself", ce->name); } } /* }}} */ ZEND_API void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface TSRMLS_DC) /* {{{ */ { /* expects interface to be contained in ce's interface list already */ zend_uint i, ce_num, if_num = iface->num_interfaces; zend_class_entry *entry; if (if_num==0) { return; } ce_num = ce->num_interfaces; if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } /* Inherit the interfaces, only if they're not already inherited by the class */ while (if_num--) { entry = iface->interfaces[if_num]; for (i = 0; i < ce_num; i++) { if (ce->interfaces[i] == entry) { break; } } if (i == ce_num) { ce->interfaces[ce->num_interfaces++] = entry; } } /* and now call the implementing handlers */ while (ce_num < ce->num_interfaces) { do_implement_interface(ce, ce->interfaces[ce_num++] TSRMLS_CC); } } /* }}} */ #ifdef ZTS static void zval_internal_ctor(zval **p) /* {{{ */ { zval *orig_ptr = *p; ALLOC_ZVAL(*p); MAKE_COPY_ZVAL(&orig_ptr, *p); } /* }}} */ # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) (((parent_ce)->type != (ce)->type) ? zval_internal_ctor : zval_add_ref)) #else # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) zval_add_ref) #endif ZEND_API void zend_do_inheritance(zend_class_entry *ce, zend_class_entry *parent_ce TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; if ((ce->ce_flags & ZEND_ACC_INTERFACE) && !(parent_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ce->name, parent_ce->name); } if (parent_ce->ce_flags & ZEND_ACC_FINAL_CLASS) { zend_error(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ce->name, parent_ce->name); } ce->parent = parent_ce; /* Copy serialize/unserialize callbacks */ if (!ce->serialize) { ce->serialize = parent_ce->serialize; } if (!ce->unserialize) { ce->unserialize = parent_ce->unserialize; } /* Inherit interfaces */ zend_do_inherit_interfaces(ce, parent_ce TSRMLS_CC); /* Inherit properties */ if (parent_ce->default_properties_count) { int i = ce->default_properties_count + parent_ce->default_properties_count; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_properties_count) { while (i-- > parent_ce->default_properties_count) { ce->default_properties_table[i] = ce->default_properties_table[i - parent_ce->default_properties_count]; } } for (i = 0; i < parent_ce->default_properties_count; i++) { ce->default_properties_table[i] = parent_ce->default_properties_table[i]; if (ce->default_properties_table[i]) { #ifdef ZTS if (parent_ce->type != ce->type) { zval *p; ALLOC_ZVAL(p); MAKE_COPY_ZVAL(&ce->default_properties_table[i], p); ce->default_properties_table[i] = p; } else { Z_ADDREF_P(ce->default_properties_table[i]); } #else Z_ADDREF_P(ce->default_properties_table[i]); #endif } } ce->default_properties_count += parent_ce->default_properties_count; } if (parent_ce->type != ce->type) { /* User class extends internal class */ zend_update_class_constants(parent_ce TSRMLS_CC); if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = erealloc(ce->default_static_members_table, sizeof(void*) * i); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&CE_STATIC_MEMBERS(parent_ce)[i]); ce->default_static_members_table[i] = CE_STATIC_MEMBERS(parent_ce)[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; ce->static_members_table = ce->default_static_members_table; } } else { if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&parent_ce->default_static_members_table[i]); ce->default_static_members_table[i] = parent_ce->default_static_members_table[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } } for (zend_hash_internal_pointer_reset(&ce->properties_info); zend_hash_get_current_data(&ce->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->properties_info)) { if (property_info->ce == ce) { if (property_info->flags & ZEND_ACC_STATIC) { property_info->offset += parent_ce->default_static_members_count; } else { property_info->offset += parent_ce->default_properties_count; } } } zend_hash_merge_ex(&ce->properties_info, &parent_ce->properties_info, (copy_ctor_func_t) (ce->type & ZEND_INTERNAL_CLASS ? zend_duplicate_property_info_internal : zend_duplicate_property_info), sizeof(zend_property_info), (merge_checker_func_t) do_inherit_property_access_check, ce); zend_hash_merge(&ce->constants_table, &parent_ce->constants_table, zval_property_ctor(parent_ce, ce), NULL, sizeof(zval *), 0); zend_hash_merge_ex(&ce->function_table, &parent_ce->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_inherit_parent_constructor(ce); if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS && ce->type == ZEND_INTERNAL_CLASS) { ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } else if (!(ce->ce_flags & ZEND_ACC_IMPLEMENT_INTERFACES) && !(ce->ce_flags & ZEND_ACC_IMPLEMENT_TRAITS)) { /* The verification will be done in runtime by ZEND_VERIFY_ABSTRACT_CLASS */ zend_verify_abstract_class(ce TSRMLS_CC); } ce->ce_flags |= parent_ce->ce_flags & ZEND_HAS_STATIC_IN_METHODS; } /* }}} */ static zend_bool do_inherit_constant_check(HashTable *child_constants_table, const zval **parent_constant, const zend_hash_key *hash_key, const zend_class_entry *iface) /* {{{ */ { zval **old_constant; if (zend_hash_quick_find(child_constants_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**)&old_constant) == SUCCESS) { if (*old_constant != *parent_constant) { zend_error(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", hash_key->arKey, iface->name); } return 0; } return 1; } /* }}} */ static int do_interface_constant_check(zval **val TSRMLS_DC, int num_args, va_list args, const zend_hash_key *key) /* {{{ */ { zend_class_entry **iface = va_arg(args, zend_class_entry**); do_inherit_constant_check(&(*iface)->constants_table, (const zval **) val, key, *iface); return ZEND_HASH_APPLY_KEEP; } /* }}} */ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_iface_num = ce->num_interfaces; zend_uint parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0; for (i = 0; i < ce->num_interfaces; i++) { if (ce->interfaces[i] == NULL) { memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i)); i--; } else if (ce->interfaces[i] == iface) { if (i < parent_iface_num) { ignore = 1; } else { zend_error(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ce->name, iface->name); } } } if (ignore) { /* Check for attempt to redeclare interface constants */ zend_hash_apply_with_arguments(&ce->constants_table TSRMLS_CC, (apply_func_args_t) do_interface_constant_check, 1, &iface); } else { if (ce->num_interfaces >= current_iface_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } } ce->interfaces[ce->num_interfaces++] = iface; zend_hash_merge_ex(&ce->constants_table, &iface->constants_table, (copy_ctor_func_t) zval_add_ref, sizeof(zval *), (merge_checker_func_t) do_inherit_constant_check, iface); zend_hash_merge_ex(&ce->function_table, &iface->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_implement_interface(ce, iface TSRMLS_CC); zend_do_inherit_interfaces(ce, iface TSRMLS_CC); } } /* }}} */ ZEND_API void zend_do_implement_trait(zend_class_entry *ce, zend_class_entry *trait TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_trait_num = ce->num_traits; zend_uint parent_trait_num = ce->parent ? ce->parent->num_traits : 0; for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == NULL) { memmove(ce->traits + i, ce->traits + i + 1, sizeof(zend_class_entry*) * (--ce->num_traits - i)); i--; } else if (ce->traits[i] == trait) { if (i < parent_trait_num) { ignore = 1; } } } if (!ignore) { if (ce->num_traits >= current_trait_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->traits = (zend_class_entry **) realloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } else { ce->traits = (zend_class_entry **) erealloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } } ce->traits[ce->num_traits++] = trait; } } /* }}} */ static int zend_traits_merge_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { size_t current; size_t i; size_t count; HashTable* resulting_table; HashTable** function_tables; zend_class_entry *ce; size_t collision = 0; size_t abstract_solved = 0; zend_function* other_trait_fn; current = va_arg(args, size_t); /* index of current trait */ count = va_arg(args, size_t); resulting_table = va_arg(args, HashTable*); function_tables = va_arg(args, HashTable**); ce = va_arg(args, zend_class_entry*); for (i = 0; i < count; i++) { if (i == current) { continue; /* just skip this, cause its the table this function is applied on */ } if (zend_hash_quick_find(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&other_trait_fn) == SUCCESS) { /* if it is an abstract method, there is no collision */ if (other_trait_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* In case both are abstract, just check prototype, but need to do that in both directions */ if ( !zend_do_perform_implementation_check(fn, other_trait_fn TSRMLS_CC) || !zend_do_perform_implementation_check(other_trait_fn, fn TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s must be compatible with %s", //ZEND_FN_SCOPE_NAME(fn), fn->common.function_name, //::%s() zend_get_function_declaration(fn TSRMLS_CC), zend_get_function_declaration(other_trait_fn TSRMLS_CC)); } } else { /* otherwise, do the full check */ do_inheritance_check_on_method(fn, other_trait_fn TSRMLS_CC); } /* we can savely free and remove it from other table */ zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } else { /* if it is not an abstract method, there is still no collision */ /* if fn is an abstract method */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible. Here, we already know other_trait_fn cannot be abstract, full check ok. */ do_inheritance_check_on_method(other_trait_fn, fn TSRMLS_CC); /* just mark as solved, will be added if its own trait is processed */ abstract_solved = 1; } else { /* but else, we have a collision of non-abstract methods */ collision++; zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } } } if (collision) { zend_function* class_fn; /* make sure method is not already overridden in class */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&class_fn) == FAILURE || class_fn->common.scope != ce) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because there are collisions with other trait methods on %s", fn->common.function_name, ce->name); } zend_function_dtor(fn); } else if (abstract_solved) { zend_function_dtor(fn); } else { /* Add it to result function table */ if (zend_hash_quick_add(resulting_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, fn, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating resulting trait method table", fn->common.function_name); } } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ /* {{{ Originates from php_runkit_function_copy_ctor Duplicate structures in an op_array where necessary to make an outright duplicate */ static void zend_traits_duplicate_function(zend_function *fe, zend_class_entry *target_ce, char *newname TSRMLS_DC) { zend_literal *literals_copy; zend_compiled_variable *dupvars; zend_op *opcode_copy; zval class_name_zv; int class_name_literal; int i; int number_of_literals; if (fe->op_array.static_variables) { HashTable *tmpHash; ALLOC_HASHTABLE(tmpHash); zend_hash_init(tmpHash, zend_hash_num_elements(fe->op_array.static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_apply_with_arguments(fe->op_array.static_variables TSRMLS_CC, (apply_func_args_t)zval_copy_static_var, 1, tmpHash); fe->op_array.static_variables = tmpHash; } number_of_literals = fe->op_array.last_literal; literals_copy = (zend_literal*)emalloc(number_of_literals * sizeof(zend_literal)); for (i = 0; i < number_of_literals; i++) { literals_copy[i] = fe->op_array.literals[i]; zval_copy_ctor(&literals_copy[i].constant); } fe->op_array.literals = literals_copy; fe->op_array.refcount = emalloc(sizeof(zend_uint)); *(fe->op_array.refcount) = 1; if (fe->op_array.vars) { i = fe->op_array.last_var; dupvars = safe_emalloc(fe->op_array.last_var, sizeof(zend_compiled_variable), 0); while (i > 0) { i--; dupvars[i].name = estrndup(fe->op_array.vars[i].name, fe->op_array.vars[i].name_len); dupvars[i].name_len = fe->op_array.vars[i].name_len; dupvars[i].hash_value = fe->op_array.vars[i].hash_value; } fe->op_array.vars = dupvars; } else { fe->op_array.vars = NULL; } opcode_copy = safe_emalloc(sizeof(zend_op), fe->op_array.last, 0); for(i = 0; i < fe->op_array.last; i++) { opcode_copy[i] = fe->op_array.opcodes[i]; if (opcode_copy[i].op1_type != IS_CONST) { switch (opcode_copy[i].opcode) { case ZEND_GOTO: case ZEND_JMP: if (opcode_copy[i].op1.jmp_addr && opcode_copy[i].op1.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op1.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op1.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op1.jmp_addr - fe->op_array.opcodes); } break; } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op1.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op1.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op1.zv = &fe->op_array.literals[class_name_literal].constant; } } if (opcode_copy[i].op2_type != IS_CONST) { switch (opcode_copy[i].opcode) { case ZEND_JMPZ: case ZEND_JMPNZ: case ZEND_JMPZ_EX: case ZEND_JMPNZ_EX: case ZEND_JMP_SET: case ZEND_JMP_SET_VAR: if (opcode_copy[i].op2.jmp_addr && opcode_copy[i].op2.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op2.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op2.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op2.jmp_addr - fe->op_array.opcodes); } break; } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op2.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op2.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op2.zv = &fe->op_array.literals[class_name_literal].constant; } } } fe->op_array.opcodes = opcode_copy; fe->op_array.function_name = newname; /* was setting it to fe which does not work since fe is stack allocated and not a stable address */ /* fe->op_array.prototype = fe->op_array.prototype; */ if (fe->op_array.arg_info) { zend_arg_info *tmpArginfo; tmpArginfo = safe_emalloc(sizeof(zend_arg_info), fe->op_array.num_args, 0); for(i = 0; i < fe->op_array.num_args; i++) { tmpArginfo[i] = fe->op_array.arg_info[i]; tmpArginfo[i].name = estrndup(tmpArginfo[i].name, tmpArginfo[i].name_len); if (tmpArginfo[i].class_name) { tmpArginfo[i].class_name = estrndup(tmpArginfo[i].class_name, tmpArginfo[i].class_name_len); } } fe->op_array.arg_info = tmpArginfo; } fe->op_array.doc_comment = estrndup(fe->op_array.doc_comment, fe->op_array.doc_comment_len); fe->op_array.try_catch_array = (zend_try_catch_element*)estrndup((char*)fe->op_array.try_catch_array, sizeof(zend_try_catch_element) * fe->op_array.last_try_catch); fe->op_array.brk_cont_array = (zend_brk_cont_element*)estrndup((char*)fe->op_array.brk_cont_array, sizeof(zend_brk_cont_element) * fe->op_array.last_brk_cont); } /* }}} */ static void zend_add_magic_methods(zend_class_entry* ce, const char* mname, uint mname_len, zend_function* fe TSRMLS_DC) /* {{{ */ { if (!strncmp(mname, ZEND_CLONE_FUNC_NAME, mname_len)) { ce->clone = fe; fe->common.fn_flags |= ZEND_ACC_CLONE; } else if (!strncmp(mname, ZEND_CONSTRUCTOR_FUNC_NAME, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } else if (!strncmp(mname, ZEND_DESTRUCTOR_FUNC_NAME, mname_len)) { ce->destructor = fe; fe->common.fn_flags |= ZEND_ACC_DTOR; } else if (!strncmp(mname, ZEND_GET_FUNC_NAME, mname_len)) { ce->__get = fe; } else if (!strncmp(mname, ZEND_SET_FUNC_NAME, mname_len)) { ce->__set = fe; } else if (!strncmp(mname, ZEND_CALL_FUNC_NAME, mname_len)) { ce->__call = fe; } else if (!strncmp(mname, ZEND_UNSET_FUNC_NAME, mname_len)) { ce->__unset = fe; } else if (!strncmp(mname, ZEND_ISSET_FUNC_NAME, mname_len)) { ce->__isset = fe; } else if (!strncmp(mname, ZEND_CALLSTATIC_FUNC_NAME, mname_len)) { ce->__callstatic = fe; } else if (!strncmp(mname, ZEND_TOSTRING_FUNC_NAME, mname_len)) { ce->__tostring = fe; } else if (ce->name_length + 1 == mname_len) { char *lowercase_name = emalloc(ce->name_length + 1); zend_str_tolower_copy(lowercase_name, ce->name, ce->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, ce->name_length + 1, 1 TSRMLS_CC); if (!memcmp(mname, lowercase_name, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } str_efree(lowercase_name); } } /* }}} */ static int zend_traits_merge_functions_to_class(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zend_class_entry *ce = va_arg(args, zend_class_entry*); int add = 0; zend_function* existing_fn = NULL; zend_function fn_copy, *fn_copy_p; zend_function* prototype = NULL; /* is used to determine the prototype according to the inheritance chain */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &existing_fn) == FAILURE) { add = 1; /* not found */ } else if (existing_fn->common.scope != ce) { add = 1; /* or inherited from other class or interface */ } if (add) { zend_function* parent_function; if (ce->parent && zend_hash_quick_find(&ce->parent->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &parent_function) != FAILURE) { prototype = parent_function; /* ->common.fn_flags |= ZEND_ACC_ABSTRACT; */ /* we got that method in the parent class, and are going to override it, except, if the trait is just asking to have an abstract method implemented. */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* then we clean up an skip this method */ zend_function_dtor(fn); return ZEND_HASH_APPLY_REMOVE; } } fn->common.scope = ce; fn->common.prototype = prototype; if (prototype && (prototype->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT || prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { fn->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; } else if (fn->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT) { /* remove ZEND_ACC_IMPLEMENTED_ABSTRACT flag, think it shouldn't be copied to class */ fn->common.fn_flags = fn->common.fn_flags - ZEND_ACC_IMPLEMENTED_ABSTRACT; } /* check whether the trait method fullfills the inheritance requirements */ if (prototype) { do_inheritance_check_on_method(fn, prototype TSRMLS_CC); } /* one more thing: make sure we properly implement an abstract method */ if (existing_fn && existing_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { do_inheritance_check_on_method(fn, existing_fn TSRMLS_CC); } /* delete inherited fn if the function to be added is not abstract */ if (existing_fn && existing_fn->common.scope != ce && (fn->common.fn_flags & ZEND_ACC_ABSTRACT) == 0) { /* it is just a reference which was added to the subclass while doing the inheritance, so we can deleted now, and will add the overriding method afterwards. Except, if we try to add an abstract function, then we should not delete the inherited one */ zend_hash_quick_del(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h); } if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (fn->op_array.static_variables) { ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, ce, estrdup(fn->common.function_name) TSRMLS_CC); if (zend_hash_quick_update(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, &fn_copy, sizeof(zend_function), (void**)&fn_copy_p)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating class method table", hash_key->arKey); } zend_add_magic_methods(ce, hash_key->arKey, hash_key->nKeyLength, fn_copy_p TSRMLS_CC); zend_function_dtor(fn); } else { zend_function_dtor(fn); } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ static int zend_traits_copy_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { HashTable* target; zend_class_entry *target_ce; zend_trait_alias** aliases; HashTable* exclude_table; char* lcname; unsigned int fnname_len; zend_function fn_copy; void* dummy; size_t i = 0; target = va_arg(args, HashTable*); target_ce = va_arg(args, zend_class_entry*); aliases = va_arg(args, zend_trait_alias**); exclude_table = va_arg(args, HashTable*); fnname_len = strlen(fn->common.function_name); /* apply aliases which are qualified with a class name, there should not be any ambiguity */ if (aliases) { while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias != NULL && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && aliases[i]->trait_method->mname_len == fnname_len && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(aliases[i]->alias, aliases[i]->alias_len) TSRMLS_CC); /* if it is 0, no modifieres has been changed */ if (aliases[i]->modifiers) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } lcname = zend_str_tolower_dup(aliases[i]->alias, aliases[i]->alias_len); if (zend_hash_add(target, lcname, aliases[i]->alias_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add aliased trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } efree(lcname); /** Record the trait from which this alias was resolved. */ if (!aliases[i]->trait_method->ce) { aliases[i]->trait_method->ce = fn->common.scope; } } i++; } } lcname = zend_str_tolower_dup(fn->common.function_name, fnname_len); if (exclude_table == NULL || zend_hash_find(exclude_table, lcname, fnname_len, &dummy) == FAILURE) { /* is not in hashtable, thus, function is not to be excluded */ fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(fn->common.function_name, fnname_len) TSRMLS_CC); /* apply aliases which are not qualified by a class name, or which have not * alias name, just setting visibility */ if (aliases) { i = 0; while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias == NULL && aliases[i]->modifiers != 0 && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && (aliases[i]->trait_method->mname_len == fnname_len) && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); /** Record the trait from which this alias was resolved. */ if (!aliases[i]->trait_method->ce) { aliases[i]->trait_method->ce = fn->common.scope; } } i++; } } if (zend_hash_add(target, lcname, fnname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } } efree(lcname); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* Copies function table entries to target function table with applied aliasing */ static void zend_traits_copy_trait_function_table(HashTable *target, zend_class_entry *target_ce, HashTable *source, zend_trait_alias** aliases, HashTable* exclude_table TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_arguments(source TSRMLS_CC, (apply_func_args_t)zend_traits_copy_functions, 4, target, target_ce, aliases, exclude_table); } /* }}} */ static void zend_traits_init_trait_structures(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i, j = 0; zend_trait_precedence *cur_precedence; zend_trait_method_reference *cur_method_ref; char *lcname; zend_bool method_exists; /* resolve class references */ if (ce->trait_precedences) { i = 0; while ((cur_precedence = ce->trait_precedences[i])) { /** Resolve classes for all precedence operations. */ if (cur_precedence->exclude_from_classes) { cur_method_ref = cur_precedence->trait_method; cur_precedence->trait_method->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); /** Ensure that the prefered method is actually available. */ lcname = zend_str_tolower_dup(cur_method_ref->method_name, cur_method_ref->mname_len); method_exists = zend_hash_exists(&cur_method_ref->ce->function_table, lcname, cur_method_ref->mname_len + 1); efree(lcname); if (!method_exists) { zend_error(E_COMPILE_ERROR, "A precedence rule was defined for %s::%s but this method does not exist", cur_method_ref->ce->name, cur_method_ref->method_name); } /** With the other traits, we are more permissive. We do not give errors for those. This allows to be more defensive in such definitions. */ j = 0; while (cur_precedence->exclude_from_classes[j]) { char* class_name = (char*)cur_precedence->exclude_from_classes[j]; zend_uint name_length = strlen(class_name); cur_precedence->exclude_from_classes[j] = zend_fetch_class(class_name, name_length, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); efree(class_name); j++; } } i++; } } if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { /** For all aliases with an explicit class name, resolve the class now. */ if (ce->trait_aliases[i]->trait_method->class_name) { cur_method_ref = ce->trait_aliases[i]->trait_method; cur_method_ref->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); /** And, ensure that the referenced method is resolvable, too. */ lcname = zend_str_tolower_dup(cur_method_ref->method_name, cur_method_ref->mname_len); method_exists = zend_hash_exists(&cur_method_ref->ce->function_table, lcname, cur_method_ref->mname_len + 1); efree(lcname); if (!method_exists) { zend_error(E_COMPILE_ERROR, "An alias was defined for %s::%s but this method does not exist", cur_method_ref->ce->name, cur_method_ref->method_name); } } i++; } } } /* }}} */ static void zend_traits_compile_exclude_table(HashTable* exclude_table, zend_trait_precedence **precedences, zend_class_entry *trait) /* {{{ */ { size_t i = 0, j; if (!precedences) { return; } while (precedences[i]) { if (precedences[i]->exclude_from_classes) { j = 0; while (precedences[i]->exclude_from_classes[j]) { if (precedences[i]->exclude_from_classes[j] == trait) { zend_uint lcname_len = precedences[i]->trait_method->mname_len; char *lcname = zend_str_tolower_dup(precedences[i]->trait_method->method_name, lcname_len); if (zend_hash_add(exclude_table, lcname, lcname_len, NULL, 0, NULL) == FAILURE) { efree(lcname); zend_error(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", precedences[i]->trait_method->method_name, trait->name); } efree(lcname); } ++j; } } ++i; } } /* }}} */ static void zend_do_traits_method_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { HashTable** function_tables; HashTable* resulting_table; HashTable exclude_table; size_t i; /* prepare copies of trait function tables for combination */ function_tables = malloc(sizeof(HashTable*) * ce->num_traits); resulting_table = (HashTable *) malloc(sizeof(HashTable)); /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(resulting_table, 10, NULL, NULL, 1, 0); for (i = 0; i < ce->num_traits; i++) { function_tables[i] = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(function_tables[i], ce->traits[i]->function_table.nNumOfElements, NULL, NULL, 1, 0); if (ce->trait_precedences) { /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(&exclude_table, 2, NULL, NULL, 0, 0); zend_traits_compile_exclude_table(&exclude_table, ce->trait_precedences, ce->traits[i]); /* copies functions, applies defined aliasing, and excludes unused trait methods */ zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, &exclude_table TSRMLS_CC); zend_hash_graceful_destroy(&exclude_table); } else { zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, NULL TSRMLS_CC); } } /* now merge trait methods */ for (i = 0; i < ce->num_traits; i++) { zend_hash_apply_with_arguments(function_tables[i] TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions, 5, i, ce->num_traits, resulting_table, function_tables, ce); } /* Now the resulting_table contains all trait methods we would have to * add to the class in the following step the methods are inserted into the method table * if there is already a method with the same name it is replaced iff ce != fn.scope * --> all inherited methods are overridden, methods defined in the class are left untouched */ zend_hash_apply_with_arguments(resulting_table TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions_to_class, 1, ce); /* free temporary function tables */ for (i = 0; i < ce->num_traits; i++) { /* zend_hash_destroy(function_tables[i]); */ zend_hash_graceful_destroy(function_tables[i]); free(function_tables[i]); } free(function_tables); /* free temporary resulting table */ /* zend_hash_destroy(resulting_table); */ zend_hash_graceful_destroy(resulting_table); free(resulting_table); } /* }}} */ static zend_class_entry* find_first_definition(zend_class_entry *ce, size_t current_trait, const char* prop_name, int prop_name_length, ulong prop_hash, zend_class_entry *coliding_ce) /* {{{ */ { size_t i; zend_property_info *coliding_prop; for (i = 0; (i < current_trait) && (i < ce->num_traits); i++) { if (zend_hash_quick_find(&ce->traits[i]->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS) { return ce->traits[i]; } } return coliding_ce; } /* }}} */ static void zend_do_traits_property_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i; zend_property_info *property_info; zend_property_info *coliding_prop; zval compare_result; const char* prop_name; int prop_name_length; ulong prop_hash; const char* class_name_unused; zend_bool prop_found; zend_bool not_compatible; zval* prop_value; /* In the following steps the properties are inserted into the property table * for that, a very strict approach is applied: * - check for compatibility, if not compatible with any property in class -> fatal * - if compatible, then strict notice */ for (i = 0; i < ce->num_traits; i++) { for (zend_hash_internal_pointer_reset(&ce->traits[i]->properties_info); zend_hash_get_current_data(&ce->traits[i]->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->traits[i]->properties_info)) { /* first get the unmangeld name if necessary, * then check whether the property is already there */ if ((property_info->flags & ZEND_ACC_PPP_MASK) == ZEND_ACC_PUBLIC) { prop_hash = property_info->h; prop_name = property_info->name; prop_name_length = property_info->name_length; prop_found = zend_hash_quick_find(&ce->properties_info, property_info->name, property_info->name_length+1, property_info->h, (void **) &coliding_prop) == SUCCESS; } else { /* for private and protected we need to unmangle the names */ zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name_unused, &prop_name); prop_name_length = strlen(prop_name); prop_hash = zend_get_hash_value(prop_name, prop_name_length + 1); prop_found = zend_hash_quick_find(&ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS; } /* next: check for conflicts with current class */ if (prop_found) { if (coliding_prop->flags & ZEND_ACC_SHADOW) { /* this one is inherited, lets look it up in its own class */ zend_hash_quick_find(&coliding_prop->ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop); } if ((coliding_prop->flags & ZEND_ACC_PPP_MASK) == (property_info->flags & ZEND_ACC_PPP_MASK)) { /* flags are identical, now the value needs to be checked */ if (property_info->flags & ZEND_ACC_STATIC) { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_static_members_table[coliding_prop->offset], ce->traits[i]->default_static_members_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } else { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_properties_table[coliding_prop->offset], ce->traits[i]->default_properties_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } } else { /* the flags are not identical, thus, we assume properties are not compatible */ not_compatible = 1; } if (not_compatible) { zend_error(E_COMPILE_ERROR, "%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } else { zend_error(E_STRICT, "%s and %s define the same property ($%s) in the composition of %s. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } } /* property not found, so lets add it */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); zend_declare_property_ex(ce, prop_name, prop_name_length, prop_value, property_info->flags, property_info->doc_comment, property_info->doc_comment_len TSRMLS_CC); } } } /* }}} */ static void zend_do_check_for_inconsistent_traits_aliasing(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { int i = 0; zend_trait_alias* cur_alias; char* lc_method_name; if (ce->trait_aliases) { while (ce->trait_aliases[i]) { cur_alias = ce->trait_aliases[i]; /** The trait for this alias has not been resolved, this means, this alias was not applied. Abort with an error. */ if (!cur_alias->trait_method->ce) { if (cur_alias->alias) { /** Plain old inconsistency/typo/bug */ zend_error(E_COMPILE_ERROR, "An alias (%s) was defined for method %s(), but this method does not exist", cur_alias->alias, cur_alias->trait_method->method_name); } else { /** Here are two possible cases: 1) this is an attempt to modifiy the visibility of a method introduce as part of another alias. Since that seems to violate the DRY principle, we check against it and abort. 2) it is just a plain old inconsitency/typo/bug as in the case where alias is set. */ lc_method_name = zend_str_tolower_dup(cur_alias->trait_method->method_name, cur_alias->trait_method->mname_len); if (zend_hash_exists(&ce->function_table, lc_method_name, cur_alias->trait_method->mname_len+1)) { efree(lc_method_name); zend_error(E_COMPILE_ERROR, "The modifiers for the trait alias %s() need to be changed in the same statment in which the alias is defined. Error", cur_alias->trait_method->method_name); } else { efree(lc_method_name); zend_error(E_COMPILE_ERROR, "The modifiers of the trait method %s() are changed, but this method does not exist. Error", cur_alias->trait_method->method_name); } } } i++; } } } /* }}} */ ZEND_API void zend_do_bind_traits(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { if (ce->num_traits <= 0) { return; } /* complete initialization of trait strutures in ce */ zend_traits_init_trait_structures(ce TSRMLS_CC); /* first care about all methods to be flattened into the class */ zend_do_traits_method_binding(ce TSRMLS_CC); /* Aliases which have not been applied indicate typos/bugs. */ zend_do_check_for_inconsistent_traits_aliasing(ce TSRMLS_CC); /* then flatten the properties into it, to, mostly to notfiy developer about problems */ zend_do_traits_property_binding(ce TSRMLS_CC); /* verify that all abstract methods from traits have been implemented */ zend_verify_abstract_class(ce TSRMLS_CC); /* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */ if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { ce->ce_flags -= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } } /* }}} */ ZEND_API int do_bind_function(const zend_op_array *op_array, zend_op *opline, HashTable *function_table, zend_bool compile_time) /* {{{ */ { zend_function *function; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } zend_hash_quick_find(function_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void *) &function); if (zend_hash_quick_add(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), function, sizeof(zend_function), NULL)==FAILURE) { int error_level = compile_time ? E_COMPILE_ERROR : E_ERROR; zend_function *old_function; if (zend_hash_quick_find(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), (void *) &old_function)==SUCCESS && old_function->type == ZEND_USER_FUNCTION && old_function->op_array.last > 0) { zend_error(error_level, "Cannot redeclare %s() (previously declared in %s:%d)", function->common.function_name, old_function->op_array.filename, old_function->op_array.opcodes[0].lineno); } else { zend_error(error_level, "Cannot redeclare %s()", function->common.function_name); } return FAILURE; } else { (*function->op_array.refcount)++; function->op_array.static_variables = NULL; /* NULL out the unbound function */ return SUCCESS; } } /* }}} */ void zend_add_trait_precedence(znode *precedence_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_precedences, precedence_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_add_trait_alias(znode *alias_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_aliases, alias_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_prepare_reference(znode *result, znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { zend_trait_method_reference *method_ref = emalloc(sizeof(zend_trait_method_reference)); method_ref->ce = NULL; /* REM: There should not be a need for copying, zend_do_begin_class_declaration is also just using that string */ if (class_name) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); method_ref->class_name = Z_STRVAL(class_name->u.constant); method_ref->cname_len = Z_STRLEN(class_name->u.constant); } else { method_ref->class_name = NULL; method_ref->cname_len = 0; } method_ref->method_name = Z_STRVAL(method_name->u.constant); method_ref->mname_len = Z_STRLEN(method_name->u.constant); result->u.op.ptr = method_ref; result->op_type = IS_TMP_VAR; } /* }}} */ void zend_prepare_trait_alias(znode *result, znode *method_reference, znode *modifiers, znode *alias TSRMLS_DC) /* {{{ */ { zend_trait_alias *trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_alias->modifiers = Z_LVAL(modifiers->u.constant); if (Z_LVAL(modifiers->u.constant) == ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot use 'static' as method modifier"); return; } if (alias) { trait_alias->alias = Z_STRVAL(alias->u.constant); trait_alias->alias_len = Z_STRLEN(alias->u.constant); } else { trait_alias->alias = NULL; } trait_alias->function = NULL; result->u.op.ptr = trait_alias; } /* }}} */ void zend_prepare_trait_precedence(znode *result, znode *method_reference, znode *trait_list TSRMLS_DC) /* {{{ */ { zend_trait_precedence *trait_precedence = emalloc(sizeof(zend_trait_precedence)); trait_precedence->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_precedence->exclude_from_classes = (zend_class_entry**) trait_list->u.op.ptr; trait_precedence->function = NULL; result->u.op.ptr = trait_precedence; } /* }}} */ ZEND_API zend_class_entry *do_bind_class(const zend_op_array* op_array, const zend_op *opline, HashTable *class_table, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } if (zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce)==FAILURE) { zend_error(E_COMPILE_ERROR, "Internal Zend error - Missing class information for %s", Z_STRVAL_P(op1)); return NULL; } else { ce = *pce; } ce->refcount++; if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), &ce, sizeof(zend_class_entry *), NULL)==FAILURE) { ce->refcount--; if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return NULL; } else { if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLEMENT_INTERFACES))) { zend_verify_abstract_class(ce TSRMLS_CC); } return ce; } } /* }}} */ ZEND_API zend_class_entry *do_bind_inherited_class(const zend_op_array *op_array, const zend_op *opline, HashTable *class_table, zend_class_entry *parent_ce, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; int found_ce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } found_ce = zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce); if (found_ce == FAILURE) { if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", Z_STRVAL_P(op2)); } return NULL; } else { ce = *pce; } if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ce->name, parent_ce->name); } else if ((parent_ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ce->name, parent_ce->name); } zend_do_inheritance(ce, parent_ce TSRMLS_CC); ce->refcount++; /* Register the derived class */ if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), pce, sizeof(zend_class_entry *), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return ce; } /* }}} */ void zend_do_early_binding(TSRMLS_D) /* {{{ */ { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; HashTable *table; while (opline->opcode == ZEND_TICKS && opline > CG(active_op_array)->opcodes) { opline--; } switch (opline->opcode) { case ZEND_DECLARE_FUNCTION: if (do_bind_function(CG(active_op_array), opline, CG(function_table), 1) == FAILURE) { return; } table = CG(function_table); break; case ZEND_DECLARE_CLASS: if (do_bind_class(CG(active_op_array), opline, CG(class_table), 1 TSRMLS_CC) == NULL) { return; } table = CG(class_table); break; case ZEND_DECLARE_INHERITED_CLASS: { zend_op *fetch_class_opline = opline-1; zval *parent_name; zend_class_entry **pce; parent_name = &CONSTANT(fetch_class_opline->op2.constant); if ((zend_lookup_class(Z_STRVAL_P(parent_name), Z_STRLEN_P(parent_name), &pce TSRMLS_CC) == FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_CLASSES) && ((*pce)->type == ZEND_INTERNAL_CLASS))) { if (CG(compiler_options) & ZEND_COMPILE_DELAYED_BINDING) { zend_uint *opline_num = &CG(active_op_array)->early_binding; while (*opline_num != -1) { opline_num = &CG(active_op_array)->opcodes[*opline_num].result.opline_num; } *opline_num = opline - CG(active_op_array)->opcodes; opline->opcode = ZEND_DECLARE_INHERITED_CLASS_DELAYED; opline->result_type = IS_UNUSED; opline->result.opline_num = -1; } return; } if (do_bind_inherited_class(CG(active_op_array), opline, CG(class_table), *pce, 1 TSRMLS_CC) == NULL) { return; } /* clear unnecessary ZEND_FETCH_CLASS opcode */ zend_del_literal(CG(active_op_array), fetch_class_opline->op2.constant); MAKE_NOP(fetch_class_opline); table = CG(class_table); break; } case ZEND_VERIFY_ABSTRACT_CLASS: case ZEND_ADD_INTERFACE: case ZEND_ADD_TRAIT: case ZEND_BIND_TRAITS: /* We currently don't early-bind classes that implement interfaces */ /* Classes with traits are handled exactly the same, no early-bind here */ return; default: zend_error(E_COMPILE_ERROR, "Invalid binding type"); return; } zend_hash_quick_del(table, Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant)), Z_HASH_P(&CONSTANT(opline->op1.constant))); zend_del_literal(CG(active_op_array), opline->op1.constant); zend_del_literal(CG(active_op_array), opline->op2.constant); MAKE_NOP(opline); } /* }}} */ ZEND_API void zend_do_delayed_early_binding(const zend_op_array *op_array TSRMLS_DC) /* {{{ */ { if (op_array->early_binding != -1) { zend_bool orig_in_compilation = CG(in_compilation); zend_uint opline_num = op_array->early_binding; zend_class_entry **pce; CG(in_compilation) = 1; while (opline_num != -1) { if (zend_lookup_class(Z_STRVAL_P(op_array->opcodes[opline_num-1].op2.zv), Z_STRLEN_P(op_array->opcodes[opline_num-1].op2.zv), &pce TSRMLS_CC) == SUCCESS) { do_bind_inherited_class(op_array, &op_array->opcodes[opline_num], EG(class_table), *pce, 0 TSRMLS_CC); } opline_num = op_array->opcodes[opline_num].result.opline_num; } CG(in_compilation) = orig_in_compilation; } } /* }}} */ void zend_do_boolean_or_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_or_end(znode *result, const znode *expr1, const znode *expr2, znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_boolean_and_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_and_end(znode *result, const znode *expr1, const znode *expr2, const znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_do_while_begin(TSRMLS_D) /* {{{ */ { do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_do_while_end(const znode *do_token, const znode *expr_open_bracket, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ; SET_NODE(opline->op1, expr); opline->op2.opline_num = do_token->u.op.opline_num; SET_UNUSED(opline->op2); do_end_loop(expr_open_bracket->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_brk_cont(zend_uchar op, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->op1.opline_num = CG(context).current_brk_cont; SET_UNUSED(opline->op1); if (expr) { if (expr->op_type != IS_CONST) { zend_error(E_COMPILE_ERROR, "'%s' operator with non-constant operand is no longer supported", op == ZEND_BRK ? "break" : "continue"); } else if (Z_TYPE(expr->u.constant) != IS_LONG || Z_LVAL(expr->u.constant) < 1) { zend_error(E_COMPILE_ERROR, "'%s' operator accepts only positive numbers", op == ZEND_BRK ? "break" : "continue"); } SET_NODE(opline->op2, expr); } else { LITERAL_LONG(opline->op2, 1); opline->op2_type = IS_CONST; } } /* }}} */ void zend_do_switch_cond(const znode *cond TSRMLS_DC) /* {{{ */ { zend_switch_entry switch_entry; switch_entry.cond = *cond; switch_entry.default_case = -1; switch_entry.control_var = -1; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_switch_end(const znode *case_list TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); /* add code to jmp to default case */ if (switch_entry_ptr->default_case != -1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->op1.opline_num = switch_entry_ptr->default_case; } if (case_list->op_type != IS_UNUSED) { /* non-empty switch */ int next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* remember break/continue loop information */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; if (switch_entry_ptr->cond.op_type==IS_VAR || switch_entry_ptr->cond.op_type==IS_TMP_VAR) { /* emit free for the switch condition*/ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry_ptr->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_UNUSED(opline->op2); } if (switch_entry_ptr->cond.op_type == IS_CONST) { zval_dtor(&switch_entry_ptr->cond.u.constant); } zend_stack_del_top(&CG(switch_cond_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_case_before_statement(const znode *case_list, znode *case_token, const znode *case_expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); int next_op_number; zend_switch_entry *switch_entry_ptr; znode result; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); if (switch_entry_ptr->control_var == -1) { switch_entry_ptr->control_var = get_temporary_variable(CG(active_op_array)); } opline->opcode = ZEND_CASE; opline->result.var = switch_entry_ptr->control_var; opline->result_type = IS_TMP_VAR; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_NODE(opline->op2, case_expr); if (opline->op1_type == IS_CONST) { zval_copy_ctor(&CONSTANT(opline->op1.constant)); } GET_NODE(&result, opline->result); next_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, &result); SET_UNUSED(opline->op2); case_token->u.op.opline_num = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_case_after_statement(znode *result, const znode *case_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); result->u.op.opline_num = next_op_number; switch (CG(active_op_array)->opcodes[case_token->u.op.opline_num].opcode) { case ZEND_JMP: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); break; case ZEND_JMPZ: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); break; } } /* }}} */ void zend_do_default_before_statement(const znode *case_list, znode *default_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); default_token->u.op.opline_num = next_op_number; next_op_number = get_next_op_number(CG(active_op_array)); switch_entry_ptr->default_case = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_begin_class_declaration(const znode *class_token, znode *class_name, const znode *parent_class_name TSRMLS_DC) /* {{{ */ { zend_op *opline; int doing_inheritance = 0; zend_class_entry *new_class_entry; char *lcname; int error = 0; zval **ns_name, key; if (CG(active_class_entry)) { zend_error(E_COMPILE_ERROR, "Class declarations may not be nested"); return; } lcname = zend_str_tolower_dup(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); if (!(strcmp(lcname, "self") && strcmp(lcname, "parent"))) { efree(lcname); zend_error(E_COMPILE_ERROR, "Cannot use '%s' as class name as it is reserved", Z_STRVAL(class_name->u.constant)); } /* Class name must not conflict with import names */ if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns_name) == SUCCESS) { error = 1; } if (CG(current_namespace)) { /* Prefix class name with name of current namespace */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); class_name = &tmp; efree(lcname); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); } if (error) { char *tmp = zend_str_tolower_dup(Z_STRVAL_PP(ns_name), Z_STRLEN_PP(ns_name)); if (Z_STRLEN_PP(ns_name) != Z_STRLEN(class_name->u.constant) || memcmp(tmp, lcname, Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "Cannot declare class %s because the name is already in use", Z_STRVAL(class_name->u.constant)); } efree(tmp); } new_class_entry = emalloc(sizeof(zend_class_entry)); new_class_entry->type = ZEND_USER_CLASS; new_class_entry->name = zend_new_interned_string(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1, 1 TSRMLS_CC); new_class_entry->name_length = Z_STRLEN(class_name->u.constant); zend_initialize_class_data(new_class_entry, 1 TSRMLS_CC); new_class_entry->info.user.filename = zend_get_compiled_filename(TSRMLS_C); new_class_entry->info.user.line_start = class_token->u.op.opline_num; new_class_entry->ce_flags |= class_token->EA; if (parent_class_name && parent_class_name->op_type != IS_UNUSED) { switch (parent_class_name->EA) { case ZEND_FETCH_CLASS_SELF: zend_error(E_COMPILE_ERROR, "Cannot use 'self' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_PARENT: zend_error(E_COMPILE_ERROR, "Cannot use 'parent' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use 'static' as class name as it is reserved"); break; default: break; } doing_inheritance = 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, new_class_entry->name_length TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; if (doing_inheritance) { /* Make sure a trait does not try to extend a class */ if ((new_class_entry->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "A trait (%s) cannot extend a class", new_class_entry->name); } opline->extended_value = parent_class_name->u.op.var; opline->opcode = ZEND_DECLARE_INHERITED_CLASS; } else { opline->opcode = ZEND_DECLARE_CLASS; } LITERAL_STRINGL(opline->op2, lcname, new_class_entry->name_length, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); zend_hash_quick_update(CG(class_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &new_class_entry, sizeof(zend_class_entry *), NULL); CG(active_class_entry) = new_class_entry; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(&CG(implementing_class), opline->result); if (CG(doc_comment)) { CG(active_class_entry)->info.user.doc_comment = CG(doc_comment); CG(active_class_entry)->info.user.doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ static void do_verify_abstract_class(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_VERIFY_ABSTRACT_CLASS; SET_NODE(opline->op1, &CG(implementing_class)); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_class_declaration(const znode *class_token, const znode *parent_token TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); if (ce->constructor) { ce->constructor->common.fn_flags |= ZEND_ACC_CTOR; if (ce->constructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Constructor %s::%s() cannot be static", ce->name, ce->constructor->common.function_name); } } if (ce->destructor) { ce->destructor->common.fn_flags |= ZEND_ACC_DTOR; if (ce->destructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Destructor %s::%s() cannot be static", ce->name, ce->destructor->common.function_name); } } if (ce->clone) { ce->clone->common.fn_flags |= ZEND_ACC_CLONE; if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static", ce->name, ce->clone->common.function_name); } } ce->info.user.line_end = zend_get_compiled_lineno(TSRMLS_C); /* Check for traits and proceed like with interfaces. * The only difference will be a combined handling of them in the end. * Thus, we need another opcode here. */ if (ce->num_traits > 0) { zend_op *opline; ce->traits = NULL; ce->num_traits = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_TRAITS; /* opcode generation: */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BIND_TRAITS; SET_NODE(opline->op1, &CG(implementing_class)); } if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) && ((parent_token->op_type != IS_UNUSED) || (ce->num_interfaces > 0))) { zend_verify_abstract_class(ce TSRMLS_CC); if (ce->num_interfaces) { do_verify_abstract_class(TSRMLS_C); } } /* Inherit interfaces; reset number to zero, we need it for above check and * will restore it during actual implementation. * The ZEND_ACC_IMPLEMENT_INTERFACES flag disables double call to * zend_verify_abstract_class() */ if (ce->num_interfaces > 0) { ce->interfaces = NULL; ce->num_interfaces = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_INTERFACES; } CG(active_class_entry) = NULL; } /* }}} */ void zend_do_implements_interface(znode *interface_name TSRMLS_DC) /* {{{ */ { zend_op *opline; /* Traits can not implement interfaces */ if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface on '%s' since it is a Trait", Z_STRVAL(interface_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(interface_name->u.constant), Z_STRLEN(interface_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface name as it is reserved", Z_STRVAL(interface_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_INTERFACE; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(interface_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = (opline->extended_value & ~ZEND_FETCH_CLASS_MASK) | ZEND_FETCH_CLASS_INTERFACE; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &interface_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_interfaces++; } /* }}} */ void zend_do_implements_trait(znode *trait_name TSRMLS_DC) /* {{{ */ { zend_op *opline; if ((CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Cannot use traits inside of interfaces. %s is used in %s", Z_STRVAL(trait_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(trait_name->u.constant), Z_STRLEN(trait_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as trait name as it is reserved", Z_STRVAL(trait_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_TRAIT; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(trait_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = ZEND_FETCH_CLASS_TRAIT; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &trait_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_traits++; } /* }}} */ ZEND_API void zend_mangle_property_name(char **dest, int *dest_length, const char *src1, int src1_length, const char *src2, int src2_length, int internal) /* {{{ */ { char *prop_name; int prop_name_length; prop_name_length = 1 + src1_length + 1 + src2_length; prop_name = pemalloc(prop_name_length + 1, internal); prop_name[0] = '\0'; memcpy(prop_name + 1, src1, src1_length+1); memcpy(prop_name + 1 + src1_length + 1, src2, src2_length+1); *dest = prop_name; *dest_length = prop_name_length; } /* }}} */ static int zend_strnlen(const char* s, int maxlen) /* {{{ */ { int len = 0; while (*s++ && maxlen--) len++; return len; } /* }}} */ ZEND_API int zend_unmangle_property_name(const char *mangled_property, int len, const char **class_name, const char **prop_name) /* {{{ */ { int class_name_len; *class_name = NULL; if (mangled_property[0]!=0) { *prop_name = mangled_property; return SUCCESS; } if (len < 3 || mangled_property[1]==0) { zend_error(E_NOTICE, "Illegal member variable name"); *prop_name = mangled_property; return FAILURE; } class_name_len = zend_strnlen(mangled_property+1, --len - 1) + 1; if (class_name_len >= len || mangled_property[class_name_len]!=0) { zend_error(E_NOTICE, "Corrupt member variable name"); *prop_name = mangled_property; return FAILURE; } *class_name = mangled_property+1; *prop_name = (*class_name)+class_name_len; return SUCCESS; } /* }}} */ void zend_do_declare_property(const znode *var_name, const znode *value, zend_uint access_type TSRMLS_DC) /* {{{ */ { zval *property; zend_property_info *existing_property_info; char *comment = NULL; int comment_len = 0; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Interfaces may not include member variables"); } if (access_type & ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Properties cannot be declared abstract"); } if (access_type & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot declare property %s::$%s final, the final modifier is allowed only for methods and classes", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } if (zend_hash_find(&CG(active_class_entry)->properties_info, var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, (void **) &existing_property_info)==SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::$%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } ALLOC_ZVAL(property); if (value) { *property = value->u.constant; } else { INIT_PZVAL(property); Z_TYPE_P(property) = IS_NULL; } if (CG(doc_comment)) { comment = CG(doc_comment); comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } zend_declare_property_ex(CG(active_class_entry), zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len + 1, 0 TSRMLS_CC), var_name->u.constant.value.str.len, property, access_type, comment, comment_len TSRMLS_CC); efree(var_name->u.constant.value.str.val); } /* }}} */ void zend_do_declare_class_constant(znode *var_name, const znode *value TSRMLS_DC) /* {{{ */ { zval *property; const char *cname = NULL; int result; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed in class constants"); return; } if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Traits cannot have constants"); return; } ALLOC_ZVAL(property); *property = value->u.constant; cname = zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, 0 TSRMLS_CC); if (IS_INTERNED(cname)) { result = zend_hash_quick_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, INTERNED_HASH(cname), &property, sizeof(zval *), NULL); } else { result = zend_hash_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, &property, sizeof(zval *), NULL); } if (result == FAILURE) { FREE_ZVAL(property); zend_error(E_COMPILE_ERROR, "Cannot redefine class constant %s::%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } FREE_PNODE(var_name); if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_fetch_property(znode *result, znode *object, const znode *property TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (object->op_type == IS_CV) { if (object->u.op.var == CG(active_op_array)->this_var) { object->op_type = IS_UNUSED; /* this means $this for objects */ } } else if (fetch_list_ptr->count == 1) { zend_llist_element *le = fetch_list_ptr->head; zend_op *opline_ptr = (zend_op *) le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); SET_UNUSED(opline_ptr->op1); /* this means $this for objects */ SET_NODE(opline_ptr->op2, property); /* if it was usual fetch, we change it to object fetch */ switch (opline_ptr->opcode) { case ZEND_FETCH_W: opline_ptr->opcode = ZEND_FETCH_OBJ_W; break; case ZEND_FETCH_R: opline_ptr->opcode = ZEND_FETCH_OBJ_R; break; case ZEND_FETCH_RW: opline_ptr->opcode = ZEND_FETCH_OBJ_RW; break; case ZEND_FETCH_IS: opline_ptr->opcode = ZEND_FETCH_OBJ_IS; break; case ZEND_FETCH_UNSET: opline_ptr->opcode = ZEND_FETCH_OBJ_UNSET; break; case ZEND_FETCH_FUNC_ARG: opline_ptr->opcode = ZEND_FETCH_OBJ_FUNC_ARG; break; } if (opline_ptr->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline_ptr->op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline_ptr->op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op2.constant); } GET_NODE(result, opline_ptr->result); return; } } if (zend_is_function_or_method_call(object)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, object); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_OBJ_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, object); SET_NODE(opline.op2, property); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline.op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op2.constant); } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void zend_do_halt_compiler_register(TSRMLS_D) /* {{{ */ { char *name, *cfilename; char haltoff[] = "__COMPILER_HALT_OFFSET__"; int len, clen; if (CG(has_bracketed_namespaces) && CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "__HALT_COMPILER() can only be used from the outermost scope"); } cfilename = zend_get_compiled_filename(TSRMLS_C); clen = strlen(cfilename); zend_mangle_property_name(&name, &len, haltoff, sizeof(haltoff) - 1, cfilename, clen, 0); zend_register_long_constant(name, len+1, zend_get_scanned_file_offset(TSRMLS_C), CONST_CS, 0 TSRMLS_CC); pefree(name, 0); if (CG(in_namespace)) { zend_do_end_namespace(TSRMLS_C); } } /* }}} */ void zend_do_push_object(const znode *object TSRMLS_DC) /* {{{ */ { zend_stack_push(&CG(object_stack), object, sizeof(znode)); } /* }}} */ void zend_do_pop_object(znode *object TSRMLS_DC) /* {{{ */ { if (object) { znode *tmp; zend_stack_top(&CG(object_stack), (void **) &tmp); *object = *tmp; } zend_stack_del_top(&CG(object_stack)); } /* }}} */ void zend_do_begin_new_object(znode *new_token, znode *class_type TSRMLS_DC) /* {{{ */ { zend_op *opline; unsigned char *ptr = NULL; new_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_NEW; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, class_type); SET_UNUSED(opline->op2); zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(unsigned char *)); } /* }}} */ void zend_do_end_new_object(znode *result, const znode *new_token, const znode *argument_list TSRMLS_DC) /* {{{ */ { znode ctor_result; zend_do_end_function_call(NULL, &ctor_result, argument_list, 1, 0 TSRMLS_CC); zend_do_free(&ctor_result TSRMLS_CC); CG(active_op_array)->opcodes[new_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, CG(active_op_array)->opcodes[new_token->u.op.opline_num].result); } /* }}} */ static zend_constant* zend_get_ct_const(const zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = NULL; if (Z_STRVAL_P(const_name)[0] == '\\') { if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name), (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name)-1); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name), (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } } else if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)+1, (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name)+1, (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } if (c->flags & CONST_CT_SUBST) { return c; } if (all_internal_constants_substitution && (c->flags & CONST_PERSISTENT) && !(CG(compiler_options) & ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION) && Z_TYPE(c->value) != IS_CONSTANT && Z_TYPE(c->value) != IS_CONSTANT_ARRAY) { return c; } return NULL; } /* }}} */ static int zend_constant_ct_subst(znode *result, zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = zend_get_ct_const(const_name, all_internal_constants_substitution TSRMLS_CC); if (c) { zval_dtor(const_name); result->op_type = IS_CONST; result->u.constant = c->value; zval_copy_ctor(&result->u.constant); INIT_PZVAL(&result->u.constant); return 1; } return 0; } /* }}} */ void zend_do_fetch_constant(znode *result, znode *constant_container, znode *constant_name, int mode, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; zend_op *opline; int type; char *compound; ulong fetch_type = 0; if (constant_container) { switch (mode) { case ZEND_CT: /* this is a class constant */ type = zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant)); if (ZEND_FETCH_CLASS_STATIC == type) { zend_error(E_ERROR, "\"static::\" is not allowed in compile-time constants"); } else if (ZEND_FETCH_CLASS_DEFAULT == type) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } zend_do_build_full_name(NULL, constant_container, constant_name, 1 TSRMLS_CC); *result = *constant_container; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: if (constant_container->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant))) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } else { zend_do_fetch_class(&tmp, constant_container TSRMLS_CC); constant_container = &tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); if (constant_container->op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &constant_container->u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, constant_container); } SET_NODE(opline->op2, constant_name); CALCULATE_LITERAL_HASH(opline->op2.constant); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } GET_NODE(result, opline->result); break; } return; } /* namespace constant */ /* only one that did not contain \ from the start can be converted to string if unknown */ switch (mode) { case ZEND_CT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); /* this is a namespace constant, or an unprefixed constant */ if (zend_constant_ct_subst(result, &constant_name->u.constant, 0 TSRMLS_CC)) { break; } zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(!compound) { fetch_type |= IS_CONSTANT_UNQUALIFIED; } *result = *constant_name; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(zend_constant_ct_subst(result, &constant_name->u.constant, 1 TSRMLS_CC)) { break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; if (compound) { /* the name is unambiguous */ opline->extended_value = 0; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } else { opline->extended_value = IS_CONSTANT_UNQUALIFIED; if (CG(current_namespace)) { opline->extended_value |= IS_CONSTANT_IN_NAMESPACE; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 1 TSRMLS_CC); } else { opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } } GET_CACHE_SLOT(opline->op2.constant); break; } } /* }}} */ void zend_do_shell_exec(znode *result, const znode *cmd TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); switch (cmd->op_type) { case IS_CONST: case IS_TMP_VAR: opline->opcode = ZEND_SEND_VAL; break; default: opline->opcode = ZEND_SEND_VAR; break; } SET_NODE(opline->op1, cmd); opline->op2.opline_num = 0; opline->extended_value = ZEND_DO_FCALL; SET_UNUSED(opline->op2); /* FIXME: exception support not added to this op2 */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DO_FCALL; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; LITERAL_STRINGL(opline->op1, estrndup("shell_exec", sizeof("shell_exec")-1), sizeof("shell_exec")-1, 0); CALCULATE_LITERAL_HASH(opline->op1.constant); opline->op1_type = IS_CONST; GET_CACHE_SLOT(opline->op1.constant); opline->extended_value = 1; SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_init_array(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_ARRAY; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; GET_NODE(result, opline->result); if (expr) { SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } } else { SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_array_element(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_ARRAY_ELEMENT; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_static_array_element(znode *result, znode *offset, const znode *expr) /* {{{ */ { zval *element; ALLOC_ZVAL(element); *element = expr->u.constant; if (offset) { switch (offset->u.constant.type & IS_CONSTANT_TYPE_MASK) { case IS_CONSTANT: /* Ugly hack to denote that this value has a constant index */ Z_TYPE_P(element) |= IS_CONSTANT_INDEX; Z_STRVAL(offset->u.constant) = erealloc(Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+1] = Z_TYPE(offset->u.constant); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+2] = 0; zend_symtable_update(result->u.constant.value.ht, Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_STRING: zend_symtable_update(result->u.constant.value.ht, offset->u.constant.value.str.val, offset->u.constant.value.str.len+1, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_NULL: zend_symtable_update(Z_ARRVAL(result->u.constant), "", 1, &element, sizeof(zval *), NULL); break; case IS_LONG: case IS_BOOL: zend_hash_index_update(Z_ARRVAL(result->u.constant), Z_LVAL(offset->u.constant), &element, sizeof(zval *), NULL); break; case IS_DOUBLE: zend_hash_index_update(Z_ARRVAL(result->u.constant), zend_dval_to_lval(Z_DVAL(offset->u.constant)), &element, sizeof(zval *), NULL); break; case IS_CONSTANT_ARRAY: zend_error(E_ERROR, "Illegal offset type"); break; } } else { zend_hash_next_index_insert(Z_ARRVAL(result->u.constant), &element, sizeof(zval *), NULL); } } /* }}} */ void zend_do_add_list_element(const znode *element TSRMLS_DC) /* {{{ */ { list_llist_element lle; if (element) { zend_check_writable_variable(element); lle.var = *element; zend_llist_copy(&lle.dimensions, &CG(dimension_llist)); zend_llist_prepend_element(&CG(list_llist), &lle); } (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_new_list_begin(TSRMLS_D) /* {{{ */ { int current_dimension = 0; zend_llist_add_element(&CG(dimension_llist), &current_dimension); } /* }}} */ void zend_do_new_list_end(TSRMLS_D) /* {{{ */ { zend_llist_remove_tail(&CG(dimension_llist)); (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_list_init(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(list_stack), &CG(list_llist), sizeof(zend_llist)); zend_stack_push(&CG(list_stack), &CG(dimension_llist), sizeof(zend_llist)); zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_do_new_list_begin(TSRMLS_C); } /* }}} */ void zend_do_list_end(znode *result, znode *expr TSRMLS_DC) /* {{{ */ { zend_llist_element *le; zend_llist_element *dimension; zend_op *opline; znode last_container; le = CG(list_llist).head; while (le) { zend_llist *tmp_dimension_llist = &((list_llist_element *)le->data)->dimensions; dimension = tmp_dimension_llist->head; while (dimension) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (dimension == tmp_dimension_llist->head) { /* first */ last_container = *expr; switch (expr->op_type) { case IS_VAR: case IS_CV: opline->opcode = ZEND_FETCH_DIM_R; break; case IS_TMP_VAR: opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; case IS_CONST: /* fetch_dim_tmp_var will handle this bogus fetch */ zval_copy_ctor(&expr->u.constant); opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; } opline->extended_value |= ZEND_FETCH_ADD_LOCK; } else { opline->opcode = ZEND_FETCH_DIM_R; } opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, &last_container); opline->op2_type = IS_CONST; LITERAL_LONG(opline->op2, *((int *) dimension->data)); GET_NODE(&last_container, opline->result); dimension = dimension->next; } ((list_llist_element *) le->data)->value = last_container; zend_llist_destroy(&((list_llist_element *) le->data)->dimensions); zend_do_assign(result, &((list_llist_element *) le->data)->var, &((list_llist_element *) le->data)->value TSRMLS_CC); zend_do_free(result TSRMLS_CC); le = le->next; } zend_llist_destroy(&CG(dimension_llist)); zend_llist_destroy(&CG(list_llist)); *result = *expr; { zend_llist *p; /* restore previous lists */ zend_stack_top(&CG(list_stack), (void **) &p); CG(dimension_llist) = *p; zend_stack_del_top(&CG(list_stack)); zend_stack_top(&CG(list_stack), (void **) &p); CG(list_llist) = *p; zend_stack_del_top(&CG(list_stack)); } } /* }}} */ void zend_init_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = emalloc(sizeof(void*) * 2); list[0] = item; list[1] = NULL; *(void**)result = list; } /* }}} */ void zend_add_to_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = *(void**)result; size_t n = 0; while (list && list[n]) { n++; } list = erealloc(list, sizeof(void*) * (n+2)); list[n] = item; list[n+1] = NULL; *(void**)result = list; } /* }}} */ void zend_do_fetch_static_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zval *tmp; zend_op *opline; znode lval; znode result; ALLOC_ZVAL(tmp); if (static_assignment) { *tmp = static_assignment->u.constant; } else { INIT_ZVAL(*tmp); } if (!CG(active_op_array)->static_variables) { if (CG(active_op_array)->scope) { CG(active_op_array)->scope->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } ALLOC_HASHTABLE(CG(active_op_array)->static_variables); zend_hash_init(CG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } zend_hash_update(CG(active_op_array)->static_variables, varname->u.constant.value.str.val, varname->u.constant.value.str.len+1, &tmp, sizeof(zval *), NULL); if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (fetch_type == ZEND_FETCH_LEXICAL) ? ZEND_FETCH_R : ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_STATIC; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ if (fetch_type == ZEND_FETCH_LEXICAL) { znode dummy; zend_do_begin_variable_parse(TSRMLS_C); zend_do_assign(&dummy, &lval, &result TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } else { zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); } CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_fetch_lexical_variable(znode *varname, zend_bool is_ref TSRMLS_DC) /* {{{ */ { znode value; if (Z_STRLEN(varname->u.constant) == sizeof("this") - 1 && memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this") - 1) == 0) { zend_error(E_COMPILE_ERROR, "Cannot use $this as lexical variable"); return; } value.op_type = IS_CONST; ZVAL_NULL(&value.u.constant); Z_TYPE(value.u.constant) |= is_ref ? IS_LEXICAL_REF : IS_LEXICAL_VAR; Z_SET_REFCOUNT_P(&value.u.constant, 1); Z_UNSET_ISREF_P(&value.u.constant); zend_do_fetch_static_variable(varname, &value, is_ref ? ZEND_FETCH_STATIC : ZEND_FETCH_LEXICAL TSRMLS_CC); } /* }}} */ void zend_do_fetch_global_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zend_op *opline; znode lval; znode result; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = fetch_type; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_cast(znode *result, const znode *expr, int type TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CAST; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } /* }}} */ void zend_do_include_or_eval(int type, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_do_extended_fcall_begin(TSRMLS_C); { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INCLUDE_OR_EVAL; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } zend_do_extended_fcall_end(TSRMLS_C); } /* }}} */ void zend_do_indirect_references(znode *result, const znode *num_references, znode *variable TSRMLS_DC) /* {{{ */ { int i; zend_do_end_variable_parse(variable, BP_VAR_R, 0 TSRMLS_CC); for (i=1; i<num_references->u.constant.value.lval; i++) { fetch_simple_variable_ex(result, variable, 0, ZEND_FETCH_R TSRMLS_CC); *variable = *result; } zend_do_begin_variable_parse(TSRMLS_C); fetch_simple_variable(result, variable, 1 TSRMLS_CC); /* there is a chance someone is accessing $this */ if (CG(active_op_array)->scope && CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } /* }}} */ void zend_do_unset(const znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_UNSET_VAR; SET_NODE(opline->op1, variable); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); opline->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_UNSET: last_op->opcode = ZEND_UNSET_VAR; SET_UNUSED(last_op->result); break; case ZEND_FETCH_DIM_UNSET: last_op->opcode = ZEND_UNSET_DIM; SET_UNUSED(last_op->result); break; case ZEND_FETCH_OBJ_UNSET: last_op->opcode = ZEND_UNSET_OBJ; SET_UNUSED(last_op->result); break; } } } /* }}} */ void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_do_end_variable_parse(variable, BP_VAR_IS, 0 TSRMLS_CC); zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { last_op = get_next_op(CG(active_op_array) TSRMLS_CC); last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; SET_NODE(last_op->op1, variable); SET_UNUSED(last_op->op2); last_op->result.var = get_temporary_variable(CG(active_op_array)); last_op->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; break; case ZEND_FETCH_DIM_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_DIM_OBJ; break; case ZEND_FETCH_OBJ_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_PROP_OBJ; break; } } last_op->result_type = IS_TMP_VAR; last_op->extended_value |= type; GET_NODE(result, last_op->result); } /* }}} */ void zend_do_instanceof(znode *result, const znode *expr, const znode *class_znode, int type TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline->opcode == ZEND_FETCH_CLASS) { opline->extended_value |= ZEND_FETCH_CLASS_NO_AUTOLOAD; } } if (expr->op_type == IS_CONST) { zend_error(E_COMPILE_ERROR, "instanceof expects an object instance, constant given"); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INSTANCEOF; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_NODE(opline->op2, class_znode); GET_NODE(result, opline->result); } /* }}} */ void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_bool is_variable; zend_bool push_container = 0; zend_op dummy_opline; if (variable) { if (zend_is_function_or_method_call(array)) { is_variable = 0; } else { is_variable = 1; } /* save the location of FETCH_W instruction(s) */ open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); zend_do_end_variable_parse(array, BP_VAR_W, 0 TSRMLS_CC); if (CG(active_op_array)->last > 0 && CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) { /* Only lock the container if we are fetching from a real container and not $this */ if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1_type == IS_VAR) { CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK; push_container = 1; } } } else { is_variable = 0; open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* save the location of FE_RESET */ foreach_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* Preform array reset */ opline->opcode = ZEND_FE_RESET; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, array); SET_UNUSED(opline->op2); opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0; COPY_NODE(dummy_opline.result, opline->result); if (push_container) { COPY_NODE(dummy_opline.op1, CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1); } else { dummy_opline.op1_type = IS_UNUSED; } zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); /* save the location of FE_FETCH */ as_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FE_FETCH; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); COPY_NODE(opline->op1, dummy_opline.result); opline->extended_value = 0; SET_UNUSED(opline->op2); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_OP_DATA; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); } /* }}} */ void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC) /* {{{ */ { zend_op *opline; znode dummy, value_node; zend_bool assign_by_ref=0; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num]; if (key->op_type != IS_UNUSED) { znode *tmp; /* switch between the key and value... */ tmp = key; key = value; value = tmp; /* Mark extended_value in case both key and value are being used */ opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; } if ((key->op_type != IS_UNUSED) && (key->EA & ZEND_PARSED_REFERENCE_VARIABLE)) { zend_error(E_COMPILE_ERROR, "Key element cannot be a reference"); } if (value->EA & ZEND_PARSED_REFERENCE_VARIABLE) { assign_by_ref = 1; if (!(opline-1)->extended_value) { zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression"); } /* Mark extended_value for assign-by-reference */ opline->extended_value |= ZEND_FE_FETCH_BYREF; CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; } else { zend_op *foreach_copy; zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.op.opline_num]; zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.op.opline_num]; /* Change "write context" into "read context" */ fetch->extended_value = 0; /* reset ZEND_FE_RESET_VARIABLE */ while (fetch != end) { --fetch; if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } if (fetch->opcode == ZEND_SEPARATE) { MAKE_NOP(fetch); } else { fetch->opcode -= 3; /* FETCH_W -> FETCH_R */ } } /* prevent double SWITCH_FREE */ zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy); foreach_copy->op1_type = IS_UNUSED; } GET_NODE(&value_node, opline->result); if (assign_by_ref) { zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); /* Mark FE_FETCH as IS_VAR as it holds the data directly as a value */ zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC); } else { zend_do_assign(&dummy, value, &value_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } if (key->op_type != IS_UNUSED) { znode key_node; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num+1]; opline->result_type = IS_TMP_VAR; opline->result.opline_num = get_temporary_variable(CG(active_op_array)); GET_NODE(&key_node, opline->result); zend_do_assign(&dummy, key, &key_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_foreach_end(const znode *foreach_token, const znode *as_token TSRMLS_DC) /* {{{ */ { zend_op *container_ptr; zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = as_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_RESET */ CG(active_op_array)->opcodes[as_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_FETCH */ do_end_loop(as_token->u.op.opline_num, 1 TSRMLS_CC); zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr); generate_free_foreach_copy(container_ptr TSRMLS_CC); zend_stack_del_top(&CG(foreach_copy_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_declare_begin(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(declare_stack), &CG(declarables), sizeof(zend_declarables)); } /* }}} */ void zend_do_declare_stmt(znode *var, znode *val TSRMLS_DC) /* {{{ */ { if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "ticks", sizeof("ticks")-1)) { convert_to_long(&val->u.constant); CG(declarables).ticks = val->u.constant; } else if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "encoding", sizeof("encoding")-1)) { if ((Z_TYPE(val->u.constant) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Cannot use constants as encoding"); } /* * Check that the pragma comes before any opcodes. If the compilation * got as far as this, the previous portion of the script must have been * parseable according to the .ini script_encoding setting. We still * want to tell them to put declare() at the top. */ { int num = CG(active_op_array)->last; /* ignore ZEND_EXT_STMT and ZEND_TICKS */ while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Encoding declaration pragma must be the very first statement in the script"); } } if (CG(multibyte)) { const zend_encoding *new_encoding, *old_encoding; zend_encoding_filter old_input_filter; CG(encoding_declared) = 1; convert_to_string(&val->u.constant); new_encoding = zend_multibyte_fetch_encoding(val->u.constant.value.str.val TSRMLS_CC); if (!new_encoding) { zend_error(E_COMPILE_WARNING, "Unsupported encoding [%s]", val->u.constant.value.str.val); } else { old_input_filter = LANG_SCNG(input_filter); old_encoding = LANG_SCNG(script_encoding); zend_multibyte_set_filter(new_encoding TSRMLS_CC); /* need to re-scan if input filter changed */ if (old_input_filter != LANG_SCNG(input_filter) || (old_input_filter && new_encoding != old_encoding)) { zend_multibyte_yyinput_again(old_input_filter, old_encoding TSRMLS_CC); } } } else { zend_error(E_COMPILE_WARNING, "declare(encoding=...) ignored because Zend multibyte feature is turned off by settings"); } zval_dtor(&val->u.constant); } else { zend_error(E_COMPILE_WARNING, "Unsupported declare '%s'", var->u.constant.value.str.val); zval_dtor(&val->u.constant); } zval_dtor(&var->u.constant); } /* }}} */ void zend_do_declare_end(const znode *declare_token TSRMLS_DC) /* {{{ */ { zend_declarables *declarables; zend_stack_top(&CG(declare_stack), (void **) &declarables); /* We should restore if there was more than (current - start) - (ticks?1:0) opcodes */ if ((get_next_op_number(CG(active_op_array)) - declare_token->u.op.opline_num) - ((Z_LVAL(CG(declarables).ticks))?1:0)) { CG(declarables) = *declarables; } } /* }}} */ void zend_do_exit(znode *result, const znode *message TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXIT; SET_NODE(opline->op1, message); SET_UNUSED(opline->op2); result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_BOOL; Z_LVAL(result->u.constant) = 1; } /* }}} */ void zend_do_begin_silence(znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BEGIN_SILENCE; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); GET_NODE(strudel_token, opline->result); } /* }}} */ void zend_do_end_silence(const znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_END_SILENCE; SET_NODE(opline->op1, strudel_token); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_jmp_set(const znode *value, znode *jmp_token, znode *colon_token TSRMLS_DC) /* {{{ */ { int op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (value->op_type == IS_VAR || value->op_type == IS_CV) { opline->opcode = ZEND_JMP_SET_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_JMP_SET; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, value); SET_UNUSED(opline->op2); GET_NODE(colon_token, opline->result); jmp_token->u.op .opline_num = op_number; INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_jmp_set_else(znode *result, const znode *false_value, const znode *jmp_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, colon_token); if (colon_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].opcode = ZEND_JMP_SET_VAR; CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } opline->extended_value = 0; SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_qm_op(const znode *cond, znode *qm_token TSRMLS_DC) /* {{{ */ { int jmpz_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); SET_UNUSED(opline->op2); opline->op2.opline_num = jmpz_op_number; GET_NODE(qm_token, opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_qm_true(const znode *true_value, znode *qm_token, znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->opcodes[qm_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array))+1; /* jmp over the ZEND_JMP */ if (true_value->op_type == IS_VAR || true_value->op_type == IS_CV) { opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, true_value); SET_UNUSED(opline->op2); GET_NODE(qm_token, opline->result); colon_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_qm_false(znode *result, const znode *false_value, const znode *qm_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, qm_token); if (qm_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].opcode = ZEND_QM_ASSIGN_VAR; CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[colon_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, opline->result); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_extended_info(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_STMT; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_begin(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_BEGIN; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_end(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_END; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_ticks(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_TICKS; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->extended_value = Z_LVAL(CG(declarables).ticks); } /* }}} */ zend_bool zend_is_auto_global_quick(const char *name, uint name_len, ulong hashval TSRMLS_DC) /* {{{ */ { zend_auto_global *auto_global; ulong hash = hashval ? hashval : zend_hash_func(name, name_len+1); if (zend_hash_quick_find(CG(auto_globals), name, name_len+1, hash, (void **) &auto_global)==SUCCESS) { if (auto_global->armed) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } return 1; } return 0; } /* }}} */ zend_bool zend_is_auto_global(const char *name, uint name_len TSRMLS_DC) /* {{{ */ { return zend_is_auto_global_quick(name, name_len, 0 TSRMLS_CC); } /* }}} */ int zend_register_auto_global(const char *name, uint name_len, zend_bool jit, zend_auto_global_callback auto_global_callback TSRMLS_DC) /* {{{ */ { zend_auto_global auto_global; auto_global.name = zend_new_interned_string((char*)name, name_len + 1, 0 TSRMLS_CC); auto_global.name_len = name_len; auto_global.auto_global_callback = auto_global_callback; auto_global.jit = jit; return zend_hash_add(CG(auto_globals), name, name_len+1, &auto_global, sizeof(zend_auto_global), NULL); } /* }}} */ static int zend_auto_global_init(zend_auto_global *auto_global TSRMLS_DC) /* {{{ */ { if (auto_global->jit) { auto_global->armed = 1; } else if (auto_global->auto_global_callback) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } else { auto_global->armed = 0; } return 0; } /* }}} */ ZEND_API void zend_activate_auto_globals(TSRMLS_D) /* {{{ */ { zend_hash_apply(CG(auto_globals), (apply_func_t) zend_auto_global_init TSRMLS_CC); } /* }}} */ int zendlex(znode *zendlval TSRMLS_DC) /* {{{ */ { int retval; if (CG(increment_lineno)) { CG(zend_lineno)++; CG(increment_lineno) = 0; } again: Z_TYPE(zendlval->u.constant) = IS_LONG; retval = lex_scan(&zendlval->u.constant TSRMLS_CC); switch (retval) { case T_COMMENT: case T_DOC_COMMENT: case T_OPEN_TAG: case T_WHITESPACE: goto again; case T_CLOSE_TAG: if (LANG_SCNG(yy_text)[LANG_SCNG(yy_leng)-1] != '>') { CG(increment_lineno) = 1; } if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { goto again; } retval = ';'; /* implicit ; */ break; case T_OPEN_TAG_WITH_ECHO: retval = T_ECHO; break; case T_END_HEREDOC: efree(Z_STRVAL(zendlval->u.constant)); break; } INIT_PZVAL(&zendlval->u.constant); zendlval->op_type = IS_CONST; return retval; } /* }}} */ ZEND_API void zend_initialize_class_data(zend_class_entry *ce, zend_bool nullify_handlers TSRMLS_DC) /* {{{ */ { zend_bool persistent_hashes = (ce->type == ZEND_INTERNAL_CLASS) ? 1 : 0; dtor_func_t zval_ptr_dtor_func = ((persistent_hashes) ? ZVAL_INTERNAL_PTR_DTOR : ZVAL_PTR_DTOR); ce->refcount = 1; ce->ce_flags = 0; ce->default_properties_table = NULL; ce->default_static_members_table = NULL; zend_hash_init_ex(&ce->properties_info, 0, NULL, (dtor_func_t) (persistent_hashes ? zend_destroy_property_info_internal : zend_destroy_property_info), persistent_hashes, 0); zend_hash_init_ex(&ce->constants_table, 0, NULL, zval_ptr_dtor_func, persistent_hashes, 0); zend_hash_init_ex(&ce->function_table, 0, NULL, ZEND_FUNCTION_DTOR, persistent_hashes, 0); if (ce->type == ZEND_INTERNAL_CLASS) { #ifdef ZTS int n = zend_hash_num_elements(CG(class_table)); if (CG(static_members_table) && n >= CG(last_static_member)) { /* Support for run-time declaration: dl() */ CG(last_static_member) = n+1; CG(static_members_table) = realloc(CG(static_members_table), (n+1)*sizeof(zval**)); CG(static_members_table)[n] = NULL; } ce->static_members_table = (zval**)(zend_intptr_t)n; #else ce->static_members_table = NULL; #endif } else { ce->static_members_table = ce->default_static_members_table; ce->info.user.doc_comment = NULL; ce->info.user.doc_comment_len = 0; } ce->default_properties_count = 0; ce->default_static_members_count = 0; if (nullify_handlers) { ce->constructor = NULL; ce->destructor = NULL; ce->clone = NULL; ce->__get = NULL; ce->__set = NULL; ce->__unset = NULL; ce->__isset = NULL; ce->__call = NULL; ce->__callstatic = NULL; ce->__tostring = NULL; ce->create_object = NULL; ce->get_iterator = NULL; ce->iterator_funcs.funcs = NULL; ce->interface_gets_implemented = NULL; ce->get_static_method = NULL; ce->parent = NULL; ce->num_interfaces = 0; ce->interfaces = NULL; ce->num_traits = 0; ce->traits = NULL; ce->trait_aliases = NULL; ce->trait_precedences = NULL; ce->serialize = NULL; ce->unserialize = NULL; ce->serialize_func = NULL; ce->unserialize_func = NULL; if (ce->type == ZEND_INTERNAL_CLASS) { ce->info.internal.module = NULL; ce->info.internal.builtin_functions = NULL; } } } /* }}} */ int zend_get_class_fetch_type(const char *class_name, uint class_name_len) /* {{{ */ { if ((class_name_len == sizeof("self")-1) && !memcmp(class_name, "self", sizeof("self")-1)) { return ZEND_FETCH_CLASS_SELF; } else if ((class_name_len == sizeof("parent")-1) && !memcmp(class_name, "parent", sizeof("parent")-1)) { return ZEND_FETCH_CLASS_PARENT; } else if ((class_name_len == sizeof("static")-1) && !memcmp(class_name, "static", sizeof("static")-1)) { return ZEND_FETCH_CLASS_STATIC; } else { return ZEND_FETCH_CLASS_DEFAULT; } } /* }}} */ ZEND_API const char* zend_get_compiled_variable_name(const zend_op_array *op_array, zend_uint var, int* name_len) /* {{{ */ { if (name_len) { *name_len = op_array->vars[var].name_len; } return op_array->vars[var].name; } /* }}} */ void zend_do_build_namespace_name(znode *result, znode *prefix, znode *name TSRMLS_DC) /* {{{ */ { if (prefix) { *result = *prefix; if (Z_TYPE(result->u.constant) == IS_STRING && Z_STRLEN(result->u.constant) == 0) { /* namespace\ */ if (CG(current_namespace)) { znode tmp; zval_dtor(&result->u.constant); tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(result, NULL, &tmp TSRMLS_CC); } } } else { result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_STRING; Z_STRVAL(result->u.constant) = NULL; Z_STRLEN(result->u.constant) = 0; } /* prefix = result */ zend_do_build_full_name(NULL, result, name, 0 TSRMLS_CC); } /* }}} */ void zend_do_begin_namespace(const znode *name, zend_bool with_bracket TSRMLS_DC) /* {{{ */ { char *lcname; /* handle mixed syntax declaration or nested namespaces */ if (!CG(has_bracketed_namespaces)) { if (CG(current_namespace)) { /* previous namespace declarations were unbracketed */ if (with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } } } else { /* previous namespace declarations were bracketed */ if (!with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } else if (CG(current_namespace) || CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "Namespace declarations cannot be nested"); } } if (((!with_bracket && !CG(current_namespace)) || (with_bracket && !CG(has_bracketed_namespaces))) && CG(active_op_array)->last > 0) { /* ignore ZEND_EXT_STMT and ZEND_TICKS */ int num = CG(active_op_array)->last; while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Namespace declaration statement has to be the very first statement in the script"); } } CG(in_namespace) = 1; if (with_bracket) { CG(has_bracketed_namespaces) = 1; } if (name) { lcname = zend_str_tolower_dup(Z_STRVAL(name->u.constant), Z_STRLEN(name->u.constant)); if (((Z_STRLEN(name->u.constant) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN(name->u.constant) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as namespace name", Z_STRVAL(name->u.constant)); } efree(lcname); if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); } else { ALLOC_ZVAL(CG(current_namespace)); } *CG(current_namespace) = name->u.constant; } else { if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_use(znode *ns_name, znode *new_name, int is_global TSRMLS_DC) /* {{{ */ { char *lcname; zval *name, *ns, tmp; zend_bool warn = 0; zend_class_entry **pce; if (!CG(current_import)) { CG(current_import) = emalloc(sizeof(HashTable)); zend_hash_init(CG(current_import), 0, NULL, ZVAL_PTR_DTOR, 0); } ALLOC_ZVAL(ns); *ns = ns_name->u.constant; if (new_name) { name = &new_name->u.constant; } else { const char *p; /* The form "use A\B" is eqivalent to "use A\B as B". So we extract the last part of compound name to use as a new_name */ name = &tmp; p = zend_memrchr(Z_STRVAL_P(ns), '\\', Z_STRLEN_P(ns)); if (p) { ZVAL_STRING(name, p+1, 1); } else { *name = *ns; zval_copy_ctor(name); warn = !is_global && !CG(current_namespace); } } lcname = zend_str_tolower_dup(Z_STRVAL_P(name), Z_STRLEN_P(name)); if (((Z_STRLEN_P(name) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN_P(name) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because '%s' is a special class name", Z_STRVAL_P(ns), Z_STRVAL_P(name), Z_STRVAL_P(name)); } if (CG(current_namespace)) { /* Prefix import name with current namespace name to avoid conflicts with classes */ char *c_ns_name = emalloc(Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) + 1); zend_str_tolower_copy(c_ns_name, Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); c_ns_name[Z_STRLEN_P(CG(current_namespace))] = '\\'; memcpy(c_ns_name+Z_STRLEN_P(CG(current_namespace))+1, lcname, Z_STRLEN_P(name)+1); if (zend_hash_exists(CG(class_table), c_ns_name, Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name)+1)) { char *tmp2 = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) || memcmp(tmp2, c_ns_name, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(tmp2); } efree(c_ns_name); } else if (zend_hash_find(CG(class_table), lcname, Z_STRLEN_P(name)+1, (void**)&pce) == SUCCESS && (*pce)->type == ZEND_USER_CLASS && (*pce)->info.user.filename == CG(compiled_filename)) { char *c_tmp = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(name) || memcmp(c_tmp, lcname, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(c_tmp); } if (zend_hash_add(CG(current_import), lcname, Z_STRLEN_P(name)+1, &ns, sizeof(zval*), NULL) != SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } if (warn) { if (!strcmp(Z_STRVAL_P(name), "strict")) { zend_error(E_COMPILE_ERROR, "You seem to be trying to use a different language..."); } zend_error(E_WARNING, "The use statement with non-compound name '%s' has no effect", Z_STRVAL_P(name)); } efree(lcname); zval_dtor(name); } /* }}} */ void zend_do_declare_constant(znode *name, znode *value TSRMLS_DC) /* {{{ */ { zend_op *opline; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed as constants"); } if (zend_get_ct_const(&name->u.constant, 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare constant '%s'", Z_STRVAL(name->u.constant)); } if (CG(current_namespace)) { /* Prefix constant name with name of current namespace, lowercased */ znode tmp; tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); Z_STRVAL(tmp.u.constant) = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), Z_STRLEN(tmp.u.constant)); zend_do_build_namespace_name(&tmp, &tmp, name TSRMLS_CC); *name = tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DECLARE_CONST; SET_UNUSED(opline->result); SET_NODE(opline->op1, name); SET_NODE(opline->op2, value); } /* }}} */ void zend_verify_namespace(TSRMLS_D) /* {{{ */ { if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "No code may exist outside of namespace {}"); } } /* }}} */ void zend_do_end_namespace(TSRMLS_D) /* {{{ */ { CG(in_namespace) = 0; if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_end_compilation(TSRMLS_D) /* {{{ */ { CG(has_bracketed_namespaces) = 0; zend_do_end_namespace(TSRMLS_C); } /* }}} */ /* {{{ zend_dirname Returns directory name component of path */ ZEND_API size_t zend_dirname(char *path, size_t len) { register char *end = path + len - 1; unsigned int len_adjust = 0; #ifdef PHP_WIN32 /* Note that on Win32 CWD is per drive (heritage from CP/M). * This means dirname("c:foo") maps to "c:." or "c:" - which means CWD on C: drive. */ if ((2 <= len) && isalpha((int)((unsigned char *)path)[0]) && (':' == path[1])) { /* Skip over the drive spec (if any) so as not to change */ path += 2; len_adjust += 2; if (2 == len) { /* Return "c:" on Win32 for dirname("c:"). * It would be more consistent to return "c:." * but that would require making the string *longer*. */ return len; } } #elif defined(NETWARE) /* * Find the first occurence of : from the left * move the path pointer to the position just after : * increment the len_adjust to the length of path till colon character(inclusive) * If there is no character beyond : simple return len */ char *colonpos = NULL; colonpos = strchr(path, ':'); if (colonpos != NULL) { len_adjust = ((colonpos - path) + 1); path += len_adjust; if (len_adjust == len) { return len; } } #endif if (len == 0) { /* Illegal use of this function */ return 0; } /* Strip trailing slashes */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { /* The path only contained slashes */ path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } /* Strip filename */ while (end >= path && !IS_SLASH_P(end)) { end--; } if (end < path) { /* No slash found, therefore return '.' */ #ifdef NETWARE if (len_adjust == 0) { path[0] = '.'; path[1] = '\0'; return 1; /* only one character */ } else { path[0] = '\0'; return len_adjust; } #else path[0] = '.'; path[1] = '\0'; return 1 + len_adjust; #endif } /* Strip slashes which came before the file name */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } *(end+1) = '\0'; return (size_t)(end + 1 - path) + len_adjust; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-11-19-51a4ae6576-bc810a443d.c
manybugs_data_4
#include <sys/types.h> #include <sys/stat.h> #include <limits.h> #include <errno.h> #include <fcntl.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <ctype.h> #include <assert.h> #include <stdio.h> #include "settings.h" #include "response.h" #include "keyvalue.h" #include "log.h" #include "stat_cache.h" #include "chunk.h" #include "connections.h" #include "plugin.h" #include "sys-socket.h" #include "sys-files.h" #include "sys-strings.h" int http_response_write_header(server *srv, connection *con, chunkqueue *raw) { buffer *b; size_t i; int have_date = 0; int have_server = 0; int allow_keep_alive = 0; b = chunkqueue_get_prepend_buffer(raw); if (con->request.http_version == HTTP_VERSION_1_1) { BUFFER_COPY_STRING_CONST(b, "HTTP/1.1 "); } else { BUFFER_COPY_STRING_CONST(b, "HTTP/1.0 "); } buffer_append_long(b, con->http_status); BUFFER_APPEND_STRING_CONST(b, " "); buffer_append_string(b, get_http_status_name(con->http_status)); if (con->response.transfer_encoding & HTTP_TRANSFER_ENCODING_CHUNKED) { response_header_overwrite(srv, con, CONST_STR_LEN("Transfer-Encoding"), CONST_STR_LEN("chunked")); allow_keep_alive = 1; } else if (con->response.content_length >= 0) { buffer_copy_off_t(srv->tmp_buf, con->response.content_length); response_header_overwrite(srv, con, CONST_STR_LEN("Content-Length"), srv->tmp_buf->ptr, srv->tmp_buf->used - 1); allow_keep_alive = 1; } /* keep-alive needs Content-Length or chunked encoding. */ if (!allow_keep_alive) con->keep_alive = 0; if (con->request.http_version != HTTP_VERSION_1_1 || con->keep_alive == 0) { if (con->keep_alive) { response_header_overwrite(srv, con, CONST_STR_LEN("Connection"), CONST_STR_LEN("keep-alive")); } else { response_header_overwrite(srv, con, CONST_STR_LEN("Connection"), CONST_STR_LEN("close")); } } /* add all headers */ for (i = 0; i < con->response.headers->used; i++) { data_string *ds; ds = (data_string *)con->response.headers->data[i]; if (ds->value->used && ds->key->used && 0 != strncmp(ds->key->ptr, "X-LIGHTTPD-", sizeof("X-LIGHTTPD-") - 1) && 0 != strcasecmp(ds->key->ptr, "X-Sendfile")) { if (buffer_is_equal_string(ds->key, CONST_STR_LEN("Date"))) have_date = 1; if (buffer_is_equal_string(ds->key, CONST_STR_LEN("Server"))) have_server = 1; BUFFER_APPEND_STRING_CONST(b, "\r\n"); buffer_append_string_buffer(b, ds->key); BUFFER_APPEND_STRING_CONST(b, ": "); buffer_append_string_buffer(b, ds->value); #if 0 log_error_write(srv, __FILE__, __LINE__, "bb", ds->key, ds->value); #endif } } if (!have_date) { /* HTTP/1.1 requires a Date: header */ BUFFER_APPEND_STRING_CONST(b, "\r\nDate: "); /* cache the generated timestamp */ if (srv->cur_ts != srv->last_generated_date_ts) { buffer_prepare_copy(srv->ts_date_str, 255); strftime(srv->ts_date_str->ptr, srv->ts_date_str->size - 1, "%a, %d %b %Y %H:%M:%S GMT", gmtime(&(srv->cur_ts))); srv->ts_date_str->used = strlen(srv->ts_date_str->ptr) + 1; srv->last_generated_date_ts = srv->cur_ts; } buffer_append_string_buffer(b, srv->ts_date_str); } if (!have_server) { if (buffer_is_empty(con->conf.server_tag)) { BUFFER_APPEND_STRING_CONST(b, "\r\nServer: " PACKAGE_NAME "/" PACKAGE_VERSION); } else { BUFFER_APPEND_STRING_CONST(b, "\r\nServer: "); buffer_append_string_buffer(b, con->conf.server_tag); } } BUFFER_APPEND_STRING_CONST(b, "\r\n\r\n"); con->bytes_header = b->used - 1; raw->bytes_in += b->used - 1; if (con->conf.log_response_header) { log_error_write(srv, __FILE__, __LINE__, "sSb", "Response-Header:", "\n", b); } return 0; } handler_t handle_get_backend(server *srv, connection *con) { handler_t r; /* looks like someone has already made a decision */ if (con->mode == DIRECT && (con->http_status != 0 && con->http_status != 200)) { /* remove a packets in the queue */ return HANDLER_FINISHED; } /* no decision yet, build conf->filename */ if (con->mode == DIRECT && con->physical.path->used == 0) { char *qstr; /* we only come here when we have to parse the full request again * * a HANDLER_COMEBACK from mod_rewrite and mod_fastcgi might be a * problem here as mod_setenv might get called multiple times * * fastcgi-auth might lead to a COMEBACK too * fastcgi again dead server too * * mod_compress might add headers twice too * * */ if (con->conf.log_condition_handling) { TRACE("run condition: %s", ""); } config_patch_connection(srv, con, COMP_SERVER_SOCKET); /* SERVERsocket */ /** * prepare strings * * - uri.path_raw * - uri.path (secure) * - uri.query * */ /** * Name according to RFC 2396 * * - scheme * - authority * - path * - query * * (scheme)://(authority)(path)?(query)#fragment * * */ buffer_copy_string(con->uri.scheme, con->conf.is_ssl ? "https" : "http"); buffer_copy_string_buffer(con->uri.authority, con->request.http_host); buffer_to_lower(con->uri.authority); config_patch_connection(srv, con, COMP_HTTP_HOST); /* Host: */ config_patch_connection(srv, con, COMP_HTTP_REMOTE_IP); /* Client-IP */ config_patch_connection(srv, con, COMP_HTTP_REFERER); /* Referer: */ config_patch_connection(srv, con, COMP_HTTP_USER_AGENT);/* User-Agent: */ config_patch_connection(srv, con, COMP_HTTP_COOKIE); /* Cookie: */ config_patch_connection(srv, con, COMP_HTTP_REQUEST_METHOD); /* REQUEST_METHOD */ /** their might be a fragment which has to be cut away */ if (NULL != (qstr = strchr(con->request.uri->ptr, '#'))) { con->request.uri->used = qstr - con->request.uri->ptr; con->request.uri->ptr[con->request.uri->used++] = '\0'; } /** extract query string from request.uri */ if (NULL != (qstr = strchr(con->request.uri->ptr, '?'))) { buffer_copy_string (con->uri.query, qstr + 1); buffer_copy_string_len(con->uri.path_raw, con->request.uri->ptr, qstr - con->request.uri->ptr); } else { buffer_reset (con->uri.query); buffer_copy_string_buffer(con->uri.path_raw, con->request.uri); } if (con->conf.log_request_handling) { TRACE("-- %s", "splitting Request-URI"); TRACE("Request-URI : %s", BUF_STR(con->request.uri)); TRACE("URI-scheme : %s", BUF_STR(con->uri.scheme)); TRACE("URI-authority: %s", BUF_STR(con->uri.authority)); TRACE("URI-path : %s", BUF_STR(con->uri.path_raw)); TRACE("URI-query : %s", BUF_STR(con->uri.query)); } /* disable keep-alive if requested */ if (con->request_count > con->conf.max_keep_alive_requests) { con->keep_alive = 0; } if (srv->sockets_disabled) { con->keep_alive = 0; } /** * * call plugins * * - based on the raw URL * */ switch(r = plugins_call_handle_uri_raw(srv, con)) { case HANDLER_GO_ON: break; case HANDLER_FINISHED: case HANDLER_COMEBACK: case HANDLER_WAIT_FOR_EVENT: case HANDLER_ERROR: return r; default: ERROR("plugins_call_handle_uri_raw() returned unexpected: %d", r); break; } /* build filename * * - decode url-encodings (e.g. %20 -> ' ') * - remove path-modifiers (e.g. /../) */ if (con->request.http_method == HTTP_METHOD_OPTIONS && con->uri.path_raw->ptr[0] == '*' && con->uri.path_raw->ptr[1] == '\0') { /* OPTIONS * ... */ buffer_copy_string_buffer(con->uri.path, con->uri.path_raw); } else { buffer_copy_string_buffer(srv->tmp_buf, con->uri.path_raw); buffer_urldecode_path(srv->tmp_buf); buffer_path_simplify(con->uri.path, srv->tmp_buf); } if (con->conf.log_request_handling) { TRACE("-- %s", "sanitizing URI"); TRACE("URI-path : %s", BUF_STR(con->uri.path)); } /** * * call plugins * * - based on the clean URL * */ config_patch_connection(srv, con, COMP_HTTP_URL); /* HTTPurl */ config_patch_connection(srv, con, COMP_HTTP_QUERY_STRING); /* HTTPqs */ /* do we have to downgrade to 1.0 ? */ if (!con->conf.allow_http11) { con->request.http_version = HTTP_VERSION_1_0; } switch(r = plugins_call_handle_uri_clean(srv, con)) { case HANDLER_GO_ON: break; case HANDLER_FINISHED: case HANDLER_COMEBACK: case HANDLER_WAIT_FOR_EVENT: case HANDLER_ERROR: return r; default: ERROR("plugins_call_handle_uri_clean() returned unexpected: %d", r); break; } if (con->request.http_method == HTTP_METHOD_OPTIONS && con->uri.path->ptr[0] == '*' && con->uri.path_raw->ptr[1] == '\0') { /* option requests are handled directly without checking the path */ response_header_insert(srv, con, CONST_STR_LEN("Allow"), CONST_STR_LEN("OPTIONS, GET, HEAD, POST")); con->http_status = 200; /* no more content to send */ con->send->is_closed = 1; return HANDLER_FINISHED; } /*** * * border * * logical filename (URI) becomes a physical filename here * * * */ /* 1. stat() * ... ISREG() -> ok, go on * ... ISDIR() -> index-file -> redirect * * 2. pathinfo() * ... ISREG() * * 3. -> 404 * */ /* * SEARCH DOCUMENT ROOT */ /* set a default */ buffer_copy_string_buffer(con->physical.doc_root, con->conf.document_root); buffer_copy_string_buffer(con->physical.rel_path, con->uri.path); filename_unix2local(con->physical.rel_path); #if defined(_WIN32) || defined(__CYGWIN__) /* strip dots and spaces from the end * * windows/dos handle those filenames as the same file * * foo == foo. == foo..... == "foo... " == "foo.. ./" * * This will affect PATHINFO in some cases * * on native windows we could prepend the filename with \\?\ to circumvent * this behaviour. I have no idea how to push this through cygwin * * */ if (con->physical.rel_path->used > 1) { buffer *b = con->physical.rel_path; size_t i; if (b->used > 2 && b->ptr[b->used-2] == '/' && (b->ptr[b->used-3] == ' ' || b->ptr[b->used-3] == '.')) { b->ptr[b->used--] = '\0'; } for (i = b->used - 2; b->used > 1; i--) { if (b->ptr[i] == ' ' || b->ptr[i] == '.') { b->ptr[b->used--] = '\0'; } else { break; } } } #endif if (con->conf.log_request_handling) { TRACE("-- %s", "before doc_root"); TRACE("Doc-Root : %s", BUF_STR(con->physical.doc_root)); TRACE("Rel-Path : %s", BUF_STR(con->physical.rel_path)); TRACE("Path : %s", BUF_STR(con->physical.path)); } /* the docroot plugin should set the doc_root and might also set the physical.path * for us (all vhost-plugins are supposed to set the doc_root) * */ switch(r = plugins_call_handle_docroot(srv, con)) { case HANDLER_GO_ON: break; case HANDLER_FINISHED: case HANDLER_COMEBACK: case HANDLER_WAIT_FOR_EVENT: case HANDLER_ERROR: return r; default: ERROR("plugins_call_handle_docroot() returned unexpected: %d", r); break; } /* The default Mac OS X and Windows filesystems can't distiguish between * upper- and lowercase, so convert to lowercase */ if (con->conf.force_lowercase_filenames) { buffer_to_lower(con->physical.rel_path); } /* the docroot plugins might set the servername; if they don't we take http-host */ if (buffer_is_empty(con->server_name)) { buffer_copy_string_buffer(con->server_name, con->uri.authority); } /** * create physical filename * -> physical.path = docroot + rel_path * */ buffer_copy_string_buffer(con->physical.path, con->physical.doc_root); PATHNAME_APPEND_SLASH(con->physical.path); buffer_copy_string_buffer(con->physical.basedir, con->physical.path); if (con->physical.rel_path->used && con->physical.rel_path->ptr[0] == DIR_SEPERATOR) { buffer_append_string_len(con->physical.path, con->physical.rel_path->ptr + 1, con->physical.rel_path->used - 2); } else { buffer_append_string_buffer(con->physical.path, con->physical.rel_path); } /* win32: directories can't have a trailing slash */ if (con->physical.path->ptr[con->physical.path->used - 2] == DIR_SEPERATOR) { con->physical.path->ptr[con->physical.path->used - 2] = '\0'; con->physical.path->used--; } if (con->conf.log_request_handling) { TRACE("-- %s", "after doc_root"); TRACE("Doc-Root : %s", BUF_STR(con->physical.doc_root)); TRACE("Rel-Path : %s", BUF_STR(con->physical.rel_path)); TRACE("Path : %s", BUF_STR(con->physical.path)); } switch(r = plugins_call_handle_physical(srv, con)) { case HANDLER_GO_ON: break; case HANDLER_FINISHED: case HANDLER_COMEBACK: case HANDLER_WAIT_FOR_EVENT: case HANDLER_ERROR: return r; default: ERROR("plugins_call_handle_physical() returned unexpected: %d", r); break; } config_patch_connection(srv, con, COMP_PHYSICAL_PATH); /* physical-path */ if (con->conf.log_request_handling) { TRACE("-- %s", "logical -> physical"); TRACE("Doc-Root : %s", BUF_STR(con->physical.doc_root)); TRACE("Rel-Path : %s", BUF_STR(con->physical.rel_path)); TRACE("Path : %s", BUF_STR(con->physical.path)); } } /* * No one took the file away from the normal path of execution yet (like mod_access) * * we don't have a backend yet, try to resolve the physical path and go on * */ if (con->mode == DIRECT) { char *slash = NULL; char *pathinfo = NULL; int found = 0; stat_cache_entry *sce = NULL; if (con->conf.log_request_handling) { TRACE("-- %s", "handling physical path"); TRACE("Path : %s", BUF_STR(con->physical.path)); } switch ((r = stat_cache_get_entry_async(srv, con, con->physical.path, &sce))) { case HANDLER_GO_ON: /* file exists */ if (con->conf.log_request_handling) { TRACE("-- %s", "file found"); TRACE("Path : %s", BUF_STR(con->physical.path)); } #ifdef HAVE_LSTAT if ((sce->is_symlink != 0) && !con->conf.follow_symlink) { con->http_status = 403; if (con->conf.log_request_handling) { TRACE("-- %s", "access denied due symlink restriction"); TRACE("Path : %s", BUF_STR(con->physical.path)); } buffer_reset(con->physical.path); return HANDLER_FINISHED; }; #endif if (S_ISDIR(sce->st.st_mode)) { if (con->uri.path->ptr[con->uri.path->used - 2] != '/') { /* redirect to .../ */ http_response_redirect_to_directory(srv, con); return HANDLER_FINISHED; } #ifdef HAVE_LSTAT } else if (!S_ISREG(sce->st.st_mode) && !sce->is_symlink) { #else } else if (!S_ISREG(sce->st.st_mode)) { #endif /* any special handling of non-reg files ?*/ } break; case HANDLER_WAIT_FOR_EVENT: return HANDLER_WAIT_FOR_EVENT; case HANDLER_ERROR: switch (errno) { case EACCES: con->http_status = 403; if (con->conf.log_request_handling) { TRACE("-- %s", "access denied"); TRACE("Path : %s", BUF_STR(con->physical.path)); } buffer_reset(con->physical.path); return HANDLER_FINISHED; case ENOENT: con->http_status = 404; if (con->conf.log_request_handling) { TRACE("-- %s", "file not found"); TRACE("Path : %s", BUF_STR(con->physical.path)); } buffer_reset(con->physical.path); return HANDLER_FINISHED; case ENOTDIR: /* PATH_INFO ! :) */ break; case EMFILE: return HANDLER_WAIT_FOR_FD; default: /* we have no idea what happened, so tell the user. */ con->http_status = 500; ERROR("checking file '%s' (%s) failed: %d (%s) -> sending status 500", BUF_STR(con->uri.path), BUF_STR(con->physical.path), errno, strerror(errno)); buffer_reset(con->physical.path); return HANDLER_FINISHED; } /* not found, perhaps PATHINFO */ buffer_copy_string_buffer(srv->tmp_buf, con->physical.path); do { struct stat st; if (slash) { buffer_copy_string_len(con->physical.path, srv->tmp_buf->ptr, slash - srv->tmp_buf->ptr); } else { buffer_copy_string_buffer(con->physical.path, srv->tmp_buf); } if (0 == stat(con->physical.path->ptr, &(st)) && S_ISREG(st.st_mode)) { found = 1; break; } if (pathinfo != NULL) { *pathinfo = '\0'; } slash = strrchr(srv->tmp_buf->ptr, '/'); if (pathinfo != NULL) { /* restore '/' */ *pathinfo = '/'; } if (slash) pathinfo = slash; } while ((found == 0) && (slash != NULL) && ((size_t)(slash - srv->tmp_buf->ptr) > (con->physical.basedir->used - 2))); if (found == 0) { /* no, it really doesn't exists */ con->http_status = 404; if (con->conf.log_file_not_found) { TRACE("file not found: %s -> %s", BUF_STR(con->uri.path), BUF_STR(con->physical.path)); } buffer_reset(con->physical.path); return HANDLER_FINISHED; } /* we have a PATHINFO */ if (pathinfo) { buffer_copy_string(con->request.pathinfo, pathinfo); /* * shorten uri.path */ con->uri.path->used -= strlen(pathinfo); con->uri.path->ptr[con->uri.path->used - 1] = '\0'; } if (con->conf.log_request_handling) { TRACE("-- %s", "after pathinfo check"); TRACE("Path : %s", BUF_STR(con->physical.path)); TRACE("URI : %s", BUF_STR(con->uri.path)); TRACE("Pathinfo : %s", BUF_STR(con->request.pathinfo)); } break; default: ERROR("stat_cache_get_entry_async() returned unexpected: %d", r); break; } config_patch_connection(srv, con, COMP_PHYSICAL_PATH_EXISTS); /* physical-path */ if (con->conf.log_request_handling) { TRACE("-- %s", "handling subrequest"); TRACE("Path : %s", BUF_STR(con->physical.path)); } /* call the handlers */ switch(r = plugins_call_handle_start_backend(srv, con)) { case HANDLER_GO_ON: case HANDLER_FINISHED: /* if we are still here, no one wanted the file; status 403 is ok I think */ default: if (con->conf.log_request_handling) { TRACE("-- %s", "subrequest finished"); } /* something strange happened */ return r; } } if (con->mode == DIRECT) { con->http_status = 403; TRACE("%s", "aaaaaaah, sending 403"); return HANDLER_FINISHED; } else { return HANDLER_GO_ON; } } #include <sys/types.h> #include <sys/stat.h> #include <limits.h> #include <errno.h> #include <fcntl.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <ctype.h> #include <assert.h> #include <stdio.h> #include "settings.h" #include "response.h" #include "keyvalue.h" #include "log.h" #include "stat_cache.h" #include "chunk.h" #include "connections.h" #include "plugin.h" #include "sys-socket.h" #include "sys-files.h" #include "sys-strings.h" int http_response_write_header(server *srv, connection *con, chunkqueue *raw) { buffer *b; size_t i; int have_date = 0; int have_server = 0; int allow_keep_alive = 0; b = chunkqueue_get_prepend_buffer(raw); if (con->request.http_version == HTTP_VERSION_1_1) { BUFFER_COPY_STRING_CONST(b, "HTTP/1.1 "); } else { BUFFER_COPY_STRING_CONST(b, "HTTP/1.0 "); } buffer_append_long(b, con->http_status); BUFFER_APPEND_STRING_CONST(b, " "); buffer_append_string(b, get_http_status_name(con->http_status)); if (con->response.transfer_encoding & HTTP_TRANSFER_ENCODING_CHUNKED) { response_header_overwrite(srv, con, CONST_STR_LEN("Transfer-Encoding"), CONST_STR_LEN("chunked")); allow_keep_alive = 1; } else if ((con->http_status >= 100 && con->http_status < 200) || con->http_status == 204 || con->http_status == 304) { /* 1xx, 204 and 304 never have a content-body -> * never have a Content-Length and are always * able to do keep-alive */ allow_keep_alive = 1; } else if (con->response.content_length >= 0) { buffer_copy_off_t(srv->tmp_buf, con->response.content_length); response_header_overwrite(srv, con, CONST_STR_LEN("Content-Length"), srv->tmp_buf->ptr, srv->tmp_buf->used - 1); allow_keep_alive = 1; } /* keep-alive needs Content-Length or chunked encoding. */ if (!allow_keep_alive) con->keep_alive = 0; if (con->request.http_version != HTTP_VERSION_1_1 || con->keep_alive == 0) { if (con->keep_alive) { response_header_overwrite(srv, con, CONST_STR_LEN("Connection"), CONST_STR_LEN("keep-alive")); } else { response_header_overwrite(srv, con, CONST_STR_LEN("Connection"), CONST_STR_LEN("close")); } } /* add all headers */ for (i = 0; i < con->response.headers->used; i++) { data_string *ds; ds = (data_string *)con->response.headers->data[i]; if (ds->value->used && ds->key->used && 0 != strncmp(ds->key->ptr, "X-LIGHTTPD-", sizeof("X-LIGHTTPD-") - 1) && 0 != strcasecmp(ds->key->ptr, "X-Sendfile")) { if (buffer_is_equal_string(ds->key, CONST_STR_LEN("Date"))) have_date = 1; if (buffer_is_equal_string(ds->key, CONST_STR_LEN("Server"))) have_server = 1; BUFFER_APPEND_STRING_CONST(b, "\r\n"); buffer_append_string_buffer(b, ds->key); BUFFER_APPEND_STRING_CONST(b, ": "); buffer_append_string_buffer(b, ds->value); #if 0 log_error_write(srv, __FILE__, __LINE__, "bb", ds->key, ds->value); #endif } } if (!have_date) { /* HTTP/1.1 requires a Date: header */ BUFFER_APPEND_STRING_CONST(b, "\r\nDate: "); /* cache the generated timestamp */ if (srv->cur_ts != srv->last_generated_date_ts) { buffer_prepare_copy(srv->ts_date_str, 255); strftime(srv->ts_date_str->ptr, srv->ts_date_str->size - 1, "%a, %d %b %Y %H:%M:%S GMT", gmtime(&(srv->cur_ts))); srv->ts_date_str->used = strlen(srv->ts_date_str->ptr) + 1; srv->last_generated_date_ts = srv->cur_ts; } buffer_append_string_buffer(b, srv->ts_date_str); } if (!have_server) { if (buffer_is_empty(con->conf.server_tag)) { BUFFER_APPEND_STRING_CONST(b, "\r\nServer: " PACKAGE_NAME "/" PACKAGE_VERSION); } else { BUFFER_APPEND_STRING_CONST(b, "\r\nServer: "); buffer_append_string_buffer(b, con->conf.server_tag); } } BUFFER_APPEND_STRING_CONST(b, "\r\n\r\n"); con->bytes_header = b->used - 1; raw->bytes_in += b->used - 1; if (con->conf.log_response_header) { log_error_write(srv, __FILE__, __LINE__, "sSb", "Response-Header:", "\n", b); } return 0; } handler_t handle_get_backend(server *srv, connection *con) { handler_t r; /* looks like someone has already made a decision */ if (con->mode == DIRECT && (con->http_status != 0 && con->http_status != 200)) { /* remove a packets in the queue */ return HANDLER_FINISHED; } /* no decision yet, build conf->filename */ if (con->mode == DIRECT && con->physical.path->used == 0) { char *qstr; /* we only come here when we have to parse the full request again * * a HANDLER_COMEBACK from mod_rewrite and mod_fastcgi might be a * problem here as mod_setenv might get called multiple times * * fastcgi-auth might lead to a COMEBACK too * fastcgi again dead server too * * mod_compress might add headers twice too * * */ if (con->conf.log_condition_handling) { TRACE("run condition: %s", ""); } config_patch_connection(srv, con, COMP_SERVER_SOCKET); /* SERVERsocket */ /** * prepare strings * * - uri.path_raw * - uri.path (secure) * - uri.query * */ /** * Name according to RFC 2396 * * - scheme * - authority * - path * - query * * (scheme)://(authority)(path)?(query)#fragment * * */ buffer_copy_string(con->uri.scheme, con->conf.is_ssl ? "https" : "http"); buffer_copy_string_buffer(con->uri.authority, con->request.http_host); buffer_to_lower(con->uri.authority); config_patch_connection(srv, con, COMP_HTTP_HOST); /* Host: */ config_patch_connection(srv, con, COMP_HTTP_REMOTE_IP); /* Client-IP */ config_patch_connection(srv, con, COMP_HTTP_REFERER); /* Referer: */ config_patch_connection(srv, con, COMP_HTTP_USER_AGENT);/* User-Agent: */ config_patch_connection(srv, con, COMP_HTTP_COOKIE); /* Cookie: */ config_patch_connection(srv, con, COMP_HTTP_REQUEST_METHOD); /* REQUEST_METHOD */ /** their might be a fragment which has to be cut away */ if (NULL != (qstr = strchr(con->request.uri->ptr, '#'))) { con->request.uri->used = qstr - con->request.uri->ptr; con->request.uri->ptr[con->request.uri->used++] = '\0'; } /** extract query string from request.uri */ if (NULL != (qstr = strchr(con->request.uri->ptr, '?'))) { buffer_copy_string (con->uri.query, qstr + 1); buffer_copy_string_len(con->uri.path_raw, con->request.uri->ptr, qstr - con->request.uri->ptr); } else { buffer_reset (con->uri.query); buffer_copy_string_buffer(con->uri.path_raw, con->request.uri); } if (con->conf.log_request_handling) { TRACE("-- %s", "splitting Request-URI"); TRACE("Request-URI : %s", BUF_STR(con->request.uri)); TRACE("URI-scheme : %s", BUF_STR(con->uri.scheme)); TRACE("URI-authority: %s", BUF_STR(con->uri.authority)); TRACE("URI-path : %s", BUF_STR(con->uri.path_raw)); TRACE("URI-query : %s", BUF_STR(con->uri.query)); } /* disable keep-alive if requested */ if (con->request_count > con->conf.max_keep_alive_requests) { con->keep_alive = 0; } if (srv->sockets_disabled) { con->keep_alive = 0; } /** * * call plugins * * - based on the raw URL * */ switch(r = plugins_call_handle_uri_raw(srv, con)) { case HANDLER_GO_ON: break; case HANDLER_FINISHED: case HANDLER_COMEBACK: case HANDLER_WAIT_FOR_EVENT: case HANDLER_ERROR: return r; default: ERROR("plugins_call_handle_uri_raw() returned unexpected: %d", r); break; } /* build filename * * - decode url-encodings (e.g. %20 -> ' ') * - remove path-modifiers (e.g. /../) */ if (con->request.http_method == HTTP_METHOD_OPTIONS && con->uri.path_raw->ptr[0] == '*' && con->uri.path_raw->ptr[1] == '\0') { /* OPTIONS * ... */ buffer_copy_string_buffer(con->uri.path, con->uri.path_raw); } else { buffer_copy_string_buffer(srv->tmp_buf, con->uri.path_raw); buffer_urldecode_path(srv->tmp_buf); buffer_path_simplify(con->uri.path, srv->tmp_buf); } if (con->conf.log_request_handling) { TRACE("-- %s", "sanitizing URI"); TRACE("URI-path : %s", BUF_STR(con->uri.path)); } /** * * call plugins * * - based on the clean URL * */ config_patch_connection(srv, con, COMP_HTTP_URL); /* HTTPurl */ config_patch_connection(srv, con, COMP_HTTP_QUERY_STRING); /* HTTPqs */ /* do we have to downgrade to 1.0 ? */ if (!con->conf.allow_http11) { con->request.http_version = HTTP_VERSION_1_0; } switch(r = plugins_call_handle_uri_clean(srv, con)) { case HANDLER_GO_ON: break; case HANDLER_FINISHED: case HANDLER_COMEBACK: case HANDLER_WAIT_FOR_EVENT: case HANDLER_ERROR: return r; default: ERROR("plugins_call_handle_uri_clean() returned unexpected: %d", r); break; } if (con->request.http_method == HTTP_METHOD_OPTIONS && con->uri.path->ptr[0] == '*' && con->uri.path_raw->ptr[1] == '\0') { /* option requests are handled directly without checking the path */ response_header_insert(srv, con, CONST_STR_LEN("Allow"), CONST_STR_LEN("OPTIONS, GET, HEAD, POST")); con->http_status = 200; /* no more content to send */ con->send->is_closed = 1; return HANDLER_FINISHED; } /*** * * border * * logical filename (URI) becomes a physical filename here * * * */ /* 1. stat() * ... ISREG() -> ok, go on * ... ISDIR() -> index-file -> redirect * * 2. pathinfo() * ... ISREG() * * 3. -> 404 * */ /* * SEARCH DOCUMENT ROOT */ /* set a default */ buffer_copy_string_buffer(con->physical.doc_root, con->conf.document_root); buffer_copy_string_buffer(con->physical.rel_path, con->uri.path); filename_unix2local(con->physical.rel_path); #if defined(_WIN32) || defined(__CYGWIN__) /* strip dots and spaces from the end * * windows/dos handle those filenames as the same file * * foo == foo. == foo..... == "foo... " == "foo.. ./" * * This will affect PATHINFO in some cases * * on native windows we could prepend the filename with \\?\ to circumvent * this behaviour. I have no idea how to push this through cygwin * * */ if (con->physical.rel_path->used > 1) { buffer *b = con->physical.rel_path; size_t i; if (b->used > 2 && b->ptr[b->used-2] == '/' && (b->ptr[b->used-3] == ' ' || b->ptr[b->used-3] == '.')) { b->ptr[b->used--] = '\0'; } for (i = b->used - 2; b->used > 1; i--) { if (b->ptr[i] == ' ' || b->ptr[i] == '.') { b->ptr[b->used--] = '\0'; } else { break; } } } #endif if (con->conf.log_request_handling) { TRACE("-- %s", "before doc_root"); TRACE("Doc-Root : %s", BUF_STR(con->physical.doc_root)); TRACE("Rel-Path : %s", BUF_STR(con->physical.rel_path)); TRACE("Path : %s", BUF_STR(con->physical.path)); } /* the docroot plugin should set the doc_root and might also set the physical.path * for us (all vhost-plugins are supposed to set the doc_root) * */ switch(r = plugins_call_handle_docroot(srv, con)) { case HANDLER_GO_ON: break; case HANDLER_FINISHED: case HANDLER_COMEBACK: case HANDLER_WAIT_FOR_EVENT: case HANDLER_ERROR: return r; default: ERROR("plugins_call_handle_docroot() returned unexpected: %d", r); break; } /* The default Mac OS X and Windows filesystems can't distiguish between * upper- and lowercase, so convert to lowercase */ if (con->conf.force_lowercase_filenames) { buffer_to_lower(con->physical.rel_path); } /* the docroot plugins might set the servername; if they don't we take http-host */ if (buffer_is_empty(con->server_name)) { buffer_copy_string_buffer(con->server_name, con->uri.authority); } /** * create physical filename * -> physical.path = docroot + rel_path * */ buffer_copy_string_buffer(con->physical.path, con->physical.doc_root); PATHNAME_APPEND_SLASH(con->physical.path); buffer_copy_string_buffer(con->physical.basedir, con->physical.path); if (con->physical.rel_path->used && con->physical.rel_path->ptr[0] == DIR_SEPERATOR) { buffer_append_string_len(con->physical.path, con->physical.rel_path->ptr + 1, con->physical.rel_path->used - 2); } else { buffer_append_string_buffer(con->physical.path, con->physical.rel_path); } /* win32: directories can't have a trailing slash */ if (con->physical.path->ptr[con->physical.path->used - 2] == DIR_SEPERATOR) { con->physical.path->ptr[con->physical.path->used - 2] = '\0'; con->physical.path->used--; } if (con->conf.log_request_handling) { TRACE("-- %s", "after doc_root"); TRACE("Doc-Root : %s", BUF_STR(con->physical.doc_root)); TRACE("Rel-Path : %s", BUF_STR(con->physical.rel_path)); TRACE("Path : %s", BUF_STR(con->physical.path)); } switch(r = plugins_call_handle_physical(srv, con)) { case HANDLER_GO_ON: break; case HANDLER_FINISHED: case HANDLER_COMEBACK: case HANDLER_WAIT_FOR_EVENT: case HANDLER_ERROR: return r; default: ERROR("plugins_call_handle_physical() returned unexpected: %d", r); break; } config_patch_connection(srv, con, COMP_PHYSICAL_PATH); /* physical-path */ if (con->conf.log_request_handling) { TRACE("-- %s", "logical -> physical"); TRACE("Doc-Root : %s", BUF_STR(con->physical.doc_root)); TRACE("Rel-Path : %s", BUF_STR(con->physical.rel_path)); TRACE("Path : %s", BUF_STR(con->physical.path)); } } /* * No one took the file away from the normal path of execution yet (like mod_access) * * we don't have a backend yet, try to resolve the physical path and go on * */ if (con->mode == DIRECT) { char *slash = NULL; char *pathinfo = NULL; int found = 0; stat_cache_entry *sce = NULL; if (con->conf.log_request_handling) { TRACE("-- %s", "handling physical path"); TRACE("Path : %s", BUF_STR(con->physical.path)); } switch ((r = stat_cache_get_entry_async(srv, con, con->physical.path, &sce))) { case HANDLER_GO_ON: /* file exists */ if (con->conf.log_request_handling) { TRACE("-- %s", "file found"); TRACE("Path : %s", BUF_STR(con->physical.path)); } #ifdef HAVE_LSTAT if ((sce->is_symlink != 0) && !con->conf.follow_symlink) { con->http_status = 403; if (con->conf.log_request_handling) { TRACE("-- %s", "access denied due symlink restriction"); TRACE("Path : %s", BUF_STR(con->physical.path)); } buffer_reset(con->physical.path); return HANDLER_FINISHED; }; #endif if (S_ISDIR(sce->st.st_mode)) { if (con->uri.path->ptr[con->uri.path->used - 2] != '/') { /* redirect to .../ */ http_response_redirect_to_directory(srv, con); return HANDLER_FINISHED; } #ifdef HAVE_LSTAT } else if (!S_ISREG(sce->st.st_mode) && !sce->is_symlink) { #else } else if (!S_ISREG(sce->st.st_mode)) { #endif /* any special handling of non-reg files ?*/ } break; case HANDLER_WAIT_FOR_EVENT: return HANDLER_WAIT_FOR_EVENT; case HANDLER_ERROR: switch (errno) { case EACCES: con->http_status = 403; if (con->conf.log_request_handling) { TRACE("-- %s", "access denied"); TRACE("Path : %s", BUF_STR(con->physical.path)); } buffer_reset(con->physical.path); return HANDLER_FINISHED; case ENOENT: con->http_status = 404; if (con->conf.log_request_handling) { TRACE("-- %s", "file not found"); TRACE("Path : %s", BUF_STR(con->physical.path)); } buffer_reset(con->physical.path); return HANDLER_FINISHED; case ENOTDIR: /* PATH_INFO ! :) */ break; case EMFILE: return HANDLER_WAIT_FOR_FD; default: /* we have no idea what happened, so tell the user. */ con->http_status = 500; ERROR("checking file '%s' (%s) failed: %d (%s) -> sending status 500", BUF_STR(con->uri.path), BUF_STR(con->physical.path), errno, strerror(errno)); buffer_reset(con->physical.path); return HANDLER_FINISHED; } /* not found, perhaps PATHINFO */ buffer_copy_string_buffer(srv->tmp_buf, con->physical.path); do { struct stat st; if (slash) { buffer_copy_string_len(con->physical.path, srv->tmp_buf->ptr, slash - srv->tmp_buf->ptr); } else { buffer_copy_string_buffer(con->physical.path, srv->tmp_buf); } if (0 == stat(con->physical.path->ptr, &(st)) && S_ISREG(st.st_mode)) { found = 1; break; } if (pathinfo != NULL) { *pathinfo = '\0'; } slash = strrchr(srv->tmp_buf->ptr, '/'); if (pathinfo != NULL) { /* restore '/' */ *pathinfo = '/'; } if (slash) pathinfo = slash; } while ((found == 0) && (slash != NULL) && ((size_t)(slash - srv->tmp_buf->ptr) > (con->physical.basedir->used - 2))); if (found == 0) { /* no, it really doesn't exists */ con->http_status = 404; if (con->conf.log_file_not_found) { TRACE("file not found: %s -> %s", BUF_STR(con->uri.path), BUF_STR(con->physical.path)); } buffer_reset(con->physical.path); return HANDLER_FINISHED; } /* we have a PATHINFO */ if (pathinfo) { buffer_copy_string(con->request.pathinfo, pathinfo); /* * shorten uri.path */ con->uri.path->used -= strlen(pathinfo); con->uri.path->ptr[con->uri.path->used - 1] = '\0'; } if (con->conf.log_request_handling) { TRACE("-- %s", "after pathinfo check"); TRACE("Path : %s", BUF_STR(con->physical.path)); TRACE("URI : %s", BUF_STR(con->uri.path)); TRACE("Pathinfo : %s", BUF_STR(con->request.pathinfo)); } break; default: ERROR("stat_cache_get_entry_async() returned unexpected: %d", r); break; } config_patch_connection(srv, con, COMP_PHYSICAL_PATH_EXISTS); /* physical-path */ if (con->conf.log_request_handling) { TRACE("-- %s", "handling subrequest"); TRACE("Path : %s", BUF_STR(con->physical.path)); } /* call the handlers */ switch(r = plugins_call_handle_start_backend(srv, con)) { case HANDLER_GO_ON: case HANDLER_FINISHED: /* if we are still here, no one wanted the file; status 403 is ok I think */ default: if (con->conf.log_request_handling) { TRACE("-- %s", "subrequest finished"); } /* something strange happened */ return r; } } if (con->mode == DIRECT) { con->http_status = 403; TRACE("%s", "aaaaaaah, sending 403"); return HANDLER_FINISHED; } else { return HANDLER_GO_ON; } }
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/lighttpd_1948-1949.c
manybugs_data_5
/* Signal module -- many thanks to Lance Ellinghaus */ /* XXX Signals should be recorded per thread, now we have thread state. */ #include "Python.h" #ifdef MS_WINDOWS #include <Windows.h> #ifdef HAVE_PROCESS_H #include <process.h> #endif #endif #ifdef HAVE_SIGNAL_H #include <signal.h> #endif #ifdef HAVE_SYS_STAT_H #include <sys/stat.h> #endif #ifdef HAVE_SYS_TIME_H #include <sys/time.h> #endif #if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK) # define PYPTHREAD_SIGMASK #endif #if defined(PYPTHREAD_SIGMASK) && defined(HAVE_PTHREAD_H) # include <pthread.h> #endif #ifndef SIG_ERR #define SIG_ERR ((PyOS_sighandler_t)(-1)) #endif #if defined(PYOS_OS2) && !defined(PYCC_GCC) #define NSIG 12 #include <process.h> #endif #ifndef NSIG # if defined(_NSIG) # define NSIG _NSIG /* For BSD/SysV */ # elif defined(_SIGMAX) # define NSIG (_SIGMAX + 1) /* For QNX */ # elif defined(SIGMAX) # define NSIG (SIGMAX + 1) /* For djgpp */ # else # define NSIG 64 /* Use a reasonable default value */ # endif #endif /* NOTES ON THE INTERACTION BETWEEN SIGNALS AND THREADS When threads are supported, we want the following semantics: - only the main thread can set a signal handler - any thread can get a signal handler - signals are only delivered to the main thread I.e. we don't support "synchronous signals" like SIGFPE (catching this doesn't make much sense in Python anyway) nor do we support signals as a means of inter-thread communication, since not all thread implementations support that (at least our thread library doesn't). We still have the problem that in some implementations signals generated by the keyboard (e.g. SIGINT) are delivered to all threads (e.g. SGI), while in others (e.g. Solaris) such signals are delivered to one random thread (an intermediate possibility would be to deliver it to the main thread -- POSIX?). For now, we have a working implementation that works in all three cases -- the handler ignores signals if getpid() isn't the same as in the main thread. XXX This is a hack. GNU pth is a user-space threading library, and as such, all threads run within the same process. In this case, if the currently running thread is not the main_thread, send the signal to the main_thread. */ #ifdef WITH_THREAD #include <sys/types.h> /* For pid_t */ #include "pythread.h" static long main_thread; static pid_t main_pid; #endif static struct { int tripped; PyObject *func; } Handlers[NSIG]; static sig_atomic_t wakeup_fd = -1; /* Speed up sigcheck() when none tripped */ static volatile sig_atomic_t is_tripped = 0; static PyObject *DefaultHandler; static PyObject *IgnoreHandler; static PyObject *IntHandler; /* On Solaris 8, gcc will produce a warning that the function declaration is not a prototype. This is caused by the definition of SIG_DFL as (void (*)())0; the correct declaration would have been (void (*)(int))0. */ static PyOS_sighandler_t old_siginthandler = SIG_DFL; #ifdef HAVE_GETITIMER static PyObject *ItimerError; /* auxiliary functions for setitimer/getitimer */ static void timeval_from_double(double d, struct timeval *tv) { tv->tv_sec = floor(d); tv->tv_usec = fmod(d, 1.0) * 1000000.0; } Py_LOCAL_INLINE(double) double_from_timeval(struct timeval *tv) { return tv->tv_sec + (double)(tv->tv_usec / 1000000.0); } static PyObject * itimer_retval(struct itimerval *iv) { PyObject *r, *v; r = PyTuple_New(2); if (r == NULL) return NULL; if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_value)))) { Py_DECREF(r); return NULL; } PyTuple_SET_ITEM(r, 0, v); if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_interval)))) { Py_DECREF(r); return NULL; } PyTuple_SET_ITEM(r, 1, v); return r; } #endif static PyObject * signal_default_int_handler(PyObject *self, PyObject *args) { PyErr_SetNone(PyExc_KeyboardInterrupt); return NULL; } PyDoc_STRVAR(default_int_handler_doc, "default_int_handler(...)\n\ \n\ The default handler for SIGINT installed by Python.\n\ It raises KeyboardInterrupt."); static int checksignals_witharg(void * unused) { return PyErr_CheckSignals(); } static void trip_signal(int sig_num) { Handlers[sig_num].tripped = 1; if (is_tripped) return; /* Set is_tripped after setting .tripped, as it gets cleared in PyErr_CheckSignals() before .tripped. */ is_tripped = 1; Py_AddPendingCall(checksignals_witharg, NULL); if (wakeup_fd != -1) write(wakeup_fd, "\0", 1); } static void signal_handler(int sig_num) { int save_errno = errno; #if defined(WITH_THREAD) && defined(WITH_PTH) if (PyThread_get_thread_ident() != main_thread) { pth_raise(*(pth_t *) main_thread, sig_num); } else #endif { #ifdef WITH_THREAD /* See NOTES section above */ if (getpid() == main_pid) #endif { trip_signal(sig_num); } #ifndef HAVE_SIGACTION #ifdef SIGCHLD /* To avoid infinite recursion, this signal remains reset until explicit re-instated. Don't clear the 'func' field as it is our pointer to the Python handler... */ if (sig_num != SIGCHLD) #endif /* If the handler was not set up with sigaction, reinstall it. See * Python/pythonrun.c for the implementation of PyOS_setsig which * makes this true. See also issue8354. */ PyOS_setsig(sig_num, signal_handler); #endif } /* Issue #10311: asynchronously executing signal handlers should not mutate errno under the feet of unsuspecting C code. */ errno = save_errno; } #ifdef HAVE_ALARM static PyObject * signal_alarm(PyObject *self, PyObject *args) { int t; if (!PyArg_ParseTuple(args, "i:alarm", &t)) return NULL; /* alarm() returns the number of seconds remaining */ return PyLong_FromLong((long)alarm(t)); } PyDoc_STRVAR(alarm_doc, "alarm(seconds)\n\ \n\ Arrange for SIGALRM to arrive after the given number of seconds."); #endif #ifdef HAVE_PAUSE static PyObject * signal_pause(PyObject *self) { Py_BEGIN_ALLOW_THREADS (void)pause(); Py_END_ALLOW_THREADS /* make sure that any exceptions that got raised are propagated * back into Python */ if (PyErr_CheckSignals()) return NULL; Py_INCREF(Py_None); return Py_None; } PyDoc_STRVAR(pause_doc, "pause()\n\ \n\ Wait until a signal arrives."); #endif static PyObject * signal_signal(PyObject *self, PyObject *args) { PyObject *obj; int sig_num; PyObject *old_handler; void (*func)(int); if (!PyArg_ParseTuple(args, "iO:signal", &sig_num, &obj)) return NULL; #ifdef MS_WINDOWS /* Validate that sig_num is one of the allowable signals */ switch (sig_num) { case SIGABRT: break; #ifdef SIGBREAK /* Issue #10003: SIGBREAK is not documented as permitted, but works and corresponds to CTRL_BREAK_EVENT. */ case SIGBREAK: break; #endif case SIGFPE: break; case SIGILL: break; case SIGINT: break; case SIGSEGV: break; case SIGTERM: break; default: PyErr_SetString(PyExc_ValueError, "invalid signal value"); return NULL; } #endif #ifdef WITH_THREAD if (PyThread_get_thread_ident() != main_thread) { PyErr_SetString(PyExc_ValueError, "signal only works in main thread"); return NULL; } #endif if (sig_num < 1 || sig_num >= NSIG) { PyErr_SetString(PyExc_ValueError, "signal number out of range"); return NULL; } if (obj == IgnoreHandler) func = SIG_IGN; else if (obj == DefaultHandler) func = SIG_DFL; else if (!PyCallable_Check(obj)) { PyErr_SetString(PyExc_TypeError, "signal handler must be signal.SIG_IGN, signal.SIG_DFL, or a callable object"); return NULL; } else func = signal_handler; if (PyOS_setsig(sig_num, func) == SIG_ERR) { PyErr_SetFromErrno(PyExc_RuntimeError); return NULL; } old_handler = Handlers[sig_num].func; Handlers[sig_num].tripped = 0; Py_INCREF(obj); Handlers[sig_num].func = obj; return old_handler; } PyDoc_STRVAR(signal_doc, "signal(sig, action) -> action\n\ \n\ Set the action for the given signal. The action can be SIG_DFL,\n\ SIG_IGN, or a callable Python object. The previous action is\n\ returned. See getsignal() for possible return values.\n\ \n\ *** IMPORTANT NOTICE ***\n\ A signal handler function is called with two arguments:\n\ the first is the signal number, the second is the interrupted stack frame."); static PyObject * signal_getsignal(PyObject *self, PyObject *args) { int sig_num; PyObject *old_handler; if (!PyArg_ParseTuple(args, "i:getsignal", &sig_num)) return NULL; if (sig_num < 1 || sig_num >= NSIG) { PyErr_SetString(PyExc_ValueError, "signal number out of range"); return NULL; } old_handler = Handlers[sig_num].func; Py_INCREF(old_handler); return old_handler; } PyDoc_STRVAR(getsignal_doc, "getsignal(sig) -> action\n\ \n\ Return the current action for the given signal. The return value can be:\n\ SIG_IGN -- if the signal is being ignored\n\ SIG_DFL -- if the default action for the signal is in effect\n\ None -- if an unknown handler is in effect\n\ anything else -- the callable Python object used as a handler"); #ifdef HAVE_SIGINTERRUPT PyDoc_STRVAR(siginterrupt_doc, "siginterrupt(sig, flag) -> None\n\ change system call restart behaviour: if flag is False, system calls\n\ will be restarted when interrupted by signal sig, else system calls\n\ will be interrupted."); static PyObject * signal_siginterrupt(PyObject *self, PyObject *args) { int sig_num; int flag; if (!PyArg_ParseTuple(args, "ii:siginterrupt", &sig_num, &flag)) return NULL; if (sig_num < 1 || sig_num >= NSIG) { PyErr_SetString(PyExc_ValueError, "signal number out of range"); return NULL; } if (siginterrupt(sig_num, flag)<0) { PyErr_SetFromErrno(PyExc_RuntimeError); return NULL; } Py_INCREF(Py_None); return Py_None; } #endif static PyObject * signal_set_wakeup_fd(PyObject *self, PyObject *args) { struct stat buf; int fd, old_fd; if (!PyArg_ParseTuple(args, "i:set_wakeup_fd", &fd)) return NULL; #ifdef WITH_THREAD if (PyThread_get_thread_ident() != main_thread) { PyErr_SetString(PyExc_ValueError, "set_wakeup_fd only works in main thread"); return NULL; } #endif if (fd != -1 && fstat(fd, &buf) != 0) { PyErr_SetString(PyExc_ValueError, "invalid fd"); return NULL; } old_fd = wakeup_fd; wakeup_fd = fd; return PyLong_FromLong(old_fd); } PyDoc_STRVAR(set_wakeup_fd_doc, "set_wakeup_fd(fd) -> fd\n\ \n\ Sets the fd to be written to (with '\\0') when a signal\n\ comes in. A library can use this to wakeup select or poll.\n\ The previous fd is returned.\n\ \n\ The fd must be non-blocking."); /* C API for the same, without all the error checking */ int PySignal_SetWakeupFd(int fd) { int old_fd = wakeup_fd; if (fd < 0) fd = -1; wakeup_fd = fd; return old_fd; } #ifdef HAVE_SETITIMER static PyObject * signal_setitimer(PyObject *self, PyObject *args) { double first; double interval = 0; int which; struct itimerval new, old; if(!PyArg_ParseTuple(args, "id|d:setitimer", &which, &first, &interval)) return NULL; timeval_from_double(first, &new.it_value); timeval_from_double(interval, &new.it_interval); /* Let OS check "which" value */ if (setitimer(which, &new, &old) != 0) { PyErr_SetFromErrno(ItimerError); return NULL; } return itimer_retval(&old); } PyDoc_STRVAR(setitimer_doc, "setitimer(which, seconds[, interval])\n\ \n\ Sets given itimer (one of ITIMER_REAL, ITIMER_VIRTUAL\n\ or ITIMER_PROF) to fire after value seconds and after\n\ that every interval seconds.\n\ The itimer can be cleared by setting seconds to zero.\n\ \n\ Returns old values as a tuple: (delay, interval)."); #endif #ifdef HAVE_GETITIMER static PyObject * signal_getitimer(PyObject *self, PyObject *args) { int which; struct itimerval old; if (!PyArg_ParseTuple(args, "i:getitimer", &which)) return NULL; if (getitimer(which, &old) != 0) { PyErr_SetFromErrno(ItimerError); return NULL; } return itimer_retval(&old); } PyDoc_STRVAR(getitimer_doc, "getitimer(which)\n\ \n\ Returns current value of given itimer."); #endif #if defined(PYPTHREAD_SIGMASK) || defined(HAVE_SIGWAIT) /* Convert an iterable to a sigset. Return 0 on success, return -1 and raise an exception on error. */ static int iterable_to_sigset(PyObject *iterable, sigset_t *mask) { int result = -1; PyObject *iterator, *item; long signum; int err; sigemptyset(mask); iterator = PyObject_GetIter(iterable); if (iterator == NULL) goto error; while (1) { item = PyIter_Next(iterator); if (item == NULL) { if (PyErr_Occurred()) goto error; else break; } signum = PyLong_AsLong(item); Py_DECREF(item); if (signum == -1 && PyErr_Occurred()) goto error; if (0 < signum && signum < NSIG) err = sigaddset(mask, (int)signum); else err = 1; if (err) { PyErr_Format(PyExc_ValueError, "signal number %ld out of range", signum); goto error; } } result = 0; error: Py_XDECREF(iterator); return result; } #endif #if defined(PYPTHREAD_SIGMASK) || defined(HAVE_SIGPENDING) static PyObject* sigset_to_set(sigset_t mask) { PyObject *signum, *result; int sig; result = PySet_New(0); if (result == NULL) return NULL; for (sig = 1; sig < NSIG; sig++) { if (sigismember(&mask, sig) != 1) continue; /* Handle the case where it is a member by adding the signal to the result list. Ignore the other cases because they mean the signal isn't a member of the mask or the signal was invalid, and an invalid signal must have been our fault in constructing the loop boundaries. */ signum = PyLong_FromLong(sig); if (signum == NULL) { Py_DECREF(result); return NULL; } if (PySet_Add(result, signum) == -1) { Py_DECREF(signum); Py_DECREF(result); return NULL; } Py_DECREF(signum); } return result; } #endif #ifdef PYPTHREAD_SIGMASK static PyObject * signal_pthread_sigmask(PyObject *self, PyObject *args) { int how; PyObject *signals; sigset_t mask, previous; int err; if (!PyArg_ParseTuple(args, "iO:pthread_sigmask", &how, &signals)) return NULL; if (iterable_to_sigset(signals, &mask)) return NULL; err = pthread_sigmask(how, &mask, &previous); if (err != 0) { errno = err; PyErr_SetFromErrno(PyExc_OSError); return NULL; } /* if signals was unblocked, signal handlers have been called */ if (PyErr_CheckSignals()) return NULL; return sigset_to_set(previous); } PyDoc_STRVAR(signal_pthread_sigmask_doc, "pthread_sigmask(how, mask) -> old mask\n\ \n\ Fetch and/or change the signal mask of the calling thread."); #endif /* #ifdef PYPTHREAD_SIGMASK */ #ifdef HAVE_SIGPENDING static PyObject * signal_sigpending(PyObject *self) { int err; sigset_t mask; err = sigpending(&mask); if (err) return PyErr_SetFromErrno(PyExc_OSError); return sigset_to_set(mask); } PyDoc_STRVAR(signal_sigpending_doc, "sigpending() -> list\n\ \n\ Examine pending signals."); #endif /* #ifdef HAVE_SIGPENDING */ #ifdef HAVE_SIGWAIT static PyObject * signal_sigwait(PyObject *self, PyObject *args) { PyObject *signals; sigset_t set; int err, signum; if (!PyArg_ParseTuple(args, "O:sigwait", &signals)) return NULL; if (iterable_to_sigset(signals, &set)) return NULL; err = sigwait(&set, &signum); if (err) { errno = err; return PyErr_SetFromErrno(PyExc_OSError); } return PyLong_FromLong(signum); } PyDoc_STRVAR(signal_sigwait_doc, "sigwait(sigset) -> signum\n\ \n\ Wait a signal."); #endif /* #ifdef HAVE_SIGPENDING */ #if defined(HAVE_PTHREAD_KILL) && defined(WITH_THREAD) static PyObject * signal_pthread_kill(PyObject *self, PyObject *args) { long tid; int signum; int err; if (!PyArg_ParseTuple(args, "li:pthread_kill", &tid, &signum)) return NULL; err = pthread_kill(tid, signum); if (err != 0) { errno = err; PyErr_SetFromErrno(PyExc_OSError); return NULL; } /* the signal may have been send to the current thread */ if (PyErr_CheckSignals()) return NULL; Py_RETURN_NONE; } PyDoc_STRVAR(signal_pthread_kill_doc, "pthread_kill(thread_id, signum)\n\ \n\ Send a signal to a thread."); #endif /* #if defined(HAVE_PTHREAD_KILL) && defined(WITH_THREAD) */ /* List of functions defined in the module */ static PyMethodDef signal_methods[] = { #ifdef HAVE_ALARM {"alarm", signal_alarm, METH_VARARGS, alarm_doc}, #endif #ifdef HAVE_SETITIMER {"setitimer", signal_setitimer, METH_VARARGS, setitimer_doc}, #endif #ifdef HAVE_GETITIMER {"getitimer", signal_getitimer, METH_VARARGS, getitimer_doc}, #endif {"signal", signal_signal, METH_VARARGS, signal_doc}, {"getsignal", signal_getsignal, METH_VARARGS, getsignal_doc}, {"set_wakeup_fd", signal_set_wakeup_fd, METH_VARARGS, set_wakeup_fd_doc}, #ifdef HAVE_SIGINTERRUPT {"siginterrupt", signal_siginterrupt, METH_VARARGS, siginterrupt_doc}, #endif #ifdef HAVE_PAUSE {"pause", (PyCFunction)signal_pause, METH_NOARGS, pause_doc}, #endif {"default_int_handler", signal_default_int_handler, METH_VARARGS, default_int_handler_doc}, #if defined(HAVE_PTHREAD_KILL) && defined(WITH_THREAD) {"pthread_kill", (PyCFunction)signal_pthread_kill, METH_VARARGS, signal_pthread_kill_doc}, #endif #ifdef PYPTHREAD_SIGMASK {"pthread_sigmask", (PyCFunction)signal_pthread_sigmask, METH_VARARGS, signal_pthread_sigmask_doc}, #endif #ifdef HAVE_SIGPENDING {"sigpending", (PyCFunction)signal_sigpending, METH_NOARGS, signal_sigpending_doc}, #endif #ifdef HAVE_SIGWAIT {"sigwait", (PyCFunction)signal_sigwait, METH_VARARGS, signal_sigwait_doc}, #endif {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(module_doc, "This module provides mechanisms to use signal handlers in Python.\n\ \n\ Functions:\n\ \n\ alarm() -- cause SIGALRM after a specified time [Unix only]\n\ setitimer() -- cause a signal (described below) after a specified\n\ float time and the timer may restart then [Unix only]\n\ getitimer() -- get current value of timer [Unix only]\n\ signal() -- set the action for a given signal\n\ getsignal() -- get the signal action for a given signal\n\ pause() -- wait until a signal arrives [Unix only]\n\ default_int_handler() -- default SIGINT handler\n\ \n\ signal constants:\n\ SIG_DFL -- used to refer to the system default handler\n\ SIG_IGN -- used to ignore the signal\n\ NSIG -- number of defined signals\n\ SIGINT, SIGTERM, etc. -- signal numbers\n\ \n\ itimer constants:\n\ ITIMER_REAL -- decrements in real time, and delivers SIGALRM upon\n\ expiration\n\ ITIMER_VIRTUAL -- decrements only when the process is executing,\n\ and delivers SIGVTALRM upon expiration\n\ ITIMER_PROF -- decrements both when the process is executing and\n\ when the system is executing on behalf of the process.\n\ Coupled with ITIMER_VIRTUAL, this timer is usually\n\ used to profile the time spent by the application\n\ in user and kernel space. SIGPROF is delivered upon\n\ expiration.\n\ \n\n\ *** IMPORTANT NOTICE ***\n\ A signal handler function is called with two arguments:\n\ the first is the signal number, the second is the interrupted stack frame."); static struct PyModuleDef signalmodule = { PyModuleDef_HEAD_INIT, "signal", module_doc, -1, signal_methods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_signal(void) { PyObject *m, *d, *x; int i; #ifdef WITH_THREAD main_thread = PyThread_get_thread_ident(); main_pid = getpid(); #endif /* Create the module and add the functions */ m = PyModule_Create(&signalmodule); if (m == NULL) return NULL; /* Add some symbolic constants to the module */ d = PyModule_GetDict(m); x = DefaultHandler = PyLong_FromVoidPtr((void *)SIG_DFL); if (!x || PyDict_SetItemString(d, "SIG_DFL", x) < 0) goto finally; x = IgnoreHandler = PyLong_FromVoidPtr((void *)SIG_IGN); if (!x || PyDict_SetItemString(d, "SIG_IGN", x) < 0) goto finally; x = PyLong_FromLong((long)NSIG); if (!x || PyDict_SetItemString(d, "NSIG", x) < 0) goto finally; Py_DECREF(x); #ifdef SIG_BLOCK if (PyModule_AddIntMacro(m, SIG_BLOCK)) goto finally; #endif #ifdef SIG_UNBLOCK if (PyModule_AddIntMacro(m, SIG_UNBLOCK)) goto finally; #endif #ifdef SIG_SETMASK if (PyModule_AddIntMacro(m, SIG_SETMASK)) goto finally; #endif x = IntHandler = PyDict_GetItemString(d, "default_int_handler"); if (!x) goto finally; Py_INCREF(IntHandler); Handlers[0].tripped = 0; for (i = 1; i < NSIG; i++) { void (*t)(int); t = PyOS_getsig(i); Handlers[i].tripped = 0; if (t == SIG_DFL) Handlers[i].func = DefaultHandler; else if (t == SIG_IGN) Handlers[i].func = IgnoreHandler; else Handlers[i].func = Py_None; /* None of our business */ Py_INCREF(Handlers[i].func); } if (Handlers[SIGINT].func == DefaultHandler) { /* Install default int handler */ Py_INCREF(IntHandler); Py_DECREF(Handlers[SIGINT].func); Handlers[SIGINT].func = IntHandler; old_siginthandler = PyOS_setsig(SIGINT, signal_handler); } #ifdef SIGHUP x = PyLong_FromLong(SIGHUP); PyDict_SetItemString(d, "SIGHUP", x); Py_XDECREF(x); #endif #ifdef SIGINT x = PyLong_FromLong(SIGINT); PyDict_SetItemString(d, "SIGINT", x); Py_XDECREF(x); #endif #ifdef SIGBREAK x = PyLong_FromLong(SIGBREAK); PyDict_SetItemString(d, "SIGBREAK", x); Py_XDECREF(x); #endif #ifdef SIGQUIT x = PyLong_FromLong(SIGQUIT); PyDict_SetItemString(d, "SIGQUIT", x); Py_XDECREF(x); #endif #ifdef SIGILL x = PyLong_FromLong(SIGILL); PyDict_SetItemString(d, "SIGILL", x); Py_XDECREF(x); #endif #ifdef SIGTRAP x = PyLong_FromLong(SIGTRAP); PyDict_SetItemString(d, "SIGTRAP", x); Py_XDECREF(x); #endif #ifdef SIGIOT x = PyLong_FromLong(SIGIOT); PyDict_SetItemString(d, "SIGIOT", x); Py_XDECREF(x); #endif #ifdef SIGABRT x = PyLong_FromLong(SIGABRT); PyDict_SetItemString(d, "SIGABRT", x); Py_XDECREF(x); #endif #ifdef SIGEMT x = PyLong_FromLong(SIGEMT); PyDict_SetItemString(d, "SIGEMT", x); Py_XDECREF(x); #endif #ifdef SIGFPE x = PyLong_FromLong(SIGFPE); PyDict_SetItemString(d, "SIGFPE", x); Py_XDECREF(x); #endif #ifdef SIGKILL x = PyLong_FromLong(SIGKILL); PyDict_SetItemString(d, "SIGKILL", x); Py_XDECREF(x); #endif #ifdef SIGBUS x = PyLong_FromLong(SIGBUS); PyDict_SetItemString(d, "SIGBUS", x); Py_XDECREF(x); #endif #ifdef SIGSEGV x = PyLong_FromLong(SIGSEGV); PyDict_SetItemString(d, "SIGSEGV", x); Py_XDECREF(x); #endif #ifdef SIGSYS x = PyLong_FromLong(SIGSYS); PyDict_SetItemString(d, "SIGSYS", x); Py_XDECREF(x); #endif #ifdef SIGPIPE x = PyLong_FromLong(SIGPIPE); PyDict_SetItemString(d, "SIGPIPE", x); Py_XDECREF(x); #endif #ifdef SIGALRM x = PyLong_FromLong(SIGALRM); PyDict_SetItemString(d, "SIGALRM", x); Py_XDECREF(x); #endif #ifdef SIGTERM x = PyLong_FromLong(SIGTERM); PyDict_SetItemString(d, "SIGTERM", x); Py_XDECREF(x); #endif #ifdef SIGUSR1 x = PyLong_FromLong(SIGUSR1); PyDict_SetItemString(d, "SIGUSR1", x); Py_XDECREF(x); #endif #ifdef SIGUSR2 x = PyLong_FromLong(SIGUSR2); PyDict_SetItemString(d, "SIGUSR2", x); Py_XDECREF(x); #endif #ifdef SIGCLD x = PyLong_FromLong(SIGCLD); PyDict_SetItemString(d, "SIGCLD", x); Py_XDECREF(x); #endif #ifdef SIGCHLD x = PyLong_FromLong(SIGCHLD); PyDict_SetItemString(d, "SIGCHLD", x); Py_XDECREF(x); #endif #ifdef SIGPWR x = PyLong_FromLong(SIGPWR); PyDict_SetItemString(d, "SIGPWR", x); Py_XDECREF(x); #endif #ifdef SIGIO x = PyLong_FromLong(SIGIO); PyDict_SetItemString(d, "SIGIO", x); Py_XDECREF(x); #endif #ifdef SIGURG x = PyLong_FromLong(SIGURG); PyDict_SetItemString(d, "SIGURG", x); Py_XDECREF(x); #endif #ifdef SIGWINCH x = PyLong_FromLong(SIGWINCH); PyDict_SetItemString(d, "SIGWINCH", x); Py_XDECREF(x); #endif #ifdef SIGPOLL x = PyLong_FromLong(SIGPOLL); PyDict_SetItemString(d, "SIGPOLL", x); Py_XDECREF(x); #endif #ifdef SIGSTOP x = PyLong_FromLong(SIGSTOP); PyDict_SetItemString(d, "SIGSTOP", x); Py_XDECREF(x); #endif #ifdef SIGTSTP x = PyLong_FromLong(SIGTSTP); PyDict_SetItemString(d, "SIGTSTP", x); Py_XDECREF(x); #endif #ifdef SIGCONT x = PyLong_FromLong(SIGCONT); PyDict_SetItemString(d, "SIGCONT", x); Py_XDECREF(x); #endif #ifdef SIGTTIN x = PyLong_FromLong(SIGTTIN); PyDict_SetItemString(d, "SIGTTIN", x); Py_XDECREF(x); #endif #ifdef SIGTTOU x = PyLong_FromLong(SIGTTOU); PyDict_SetItemString(d, "SIGTTOU", x); Py_XDECREF(x); #endif #ifdef SIGVTALRM x = PyLong_FromLong(SIGVTALRM); PyDict_SetItemString(d, "SIGVTALRM", x); Py_XDECREF(x); #endif #ifdef SIGPROF x = PyLong_FromLong(SIGPROF); PyDict_SetItemString(d, "SIGPROF", x); Py_XDECREF(x); #endif #ifdef SIGXCPU x = PyLong_FromLong(SIGXCPU); PyDict_SetItemString(d, "SIGXCPU", x); Py_XDECREF(x); #endif #ifdef SIGXFSZ x = PyLong_FromLong(SIGXFSZ); PyDict_SetItemString(d, "SIGXFSZ", x); Py_XDECREF(x); #endif #ifdef SIGRTMIN x = PyLong_FromLong(SIGRTMIN); PyDict_SetItemString(d, "SIGRTMIN", x); Py_XDECREF(x); #endif #ifdef SIGRTMAX x = PyLong_FromLong(SIGRTMAX); PyDict_SetItemString(d, "SIGRTMAX", x); Py_XDECREF(x); #endif #ifdef SIGINFO x = PyLong_FromLong(SIGINFO); PyDict_SetItemString(d, "SIGINFO", x); Py_XDECREF(x); #endif #ifdef ITIMER_REAL x = PyLong_FromLong(ITIMER_REAL); PyDict_SetItemString(d, "ITIMER_REAL", x); Py_DECREF(x); #endif #ifdef ITIMER_VIRTUAL x = PyLong_FromLong(ITIMER_VIRTUAL); PyDict_SetItemString(d, "ITIMER_VIRTUAL", x); Py_DECREF(x); #endif #ifdef ITIMER_PROF x = PyLong_FromLong(ITIMER_PROF); PyDict_SetItemString(d, "ITIMER_PROF", x); Py_DECREF(x); #endif #if defined (HAVE_SETITIMER) || defined (HAVE_GETITIMER) ItimerError = PyErr_NewException("signal.ItimerError", PyExc_IOError, NULL); if (ItimerError != NULL) PyDict_SetItemString(d, "ItimerError", ItimerError); #endif #ifdef CTRL_C_EVENT x = PyLong_FromLong(CTRL_C_EVENT); PyDict_SetItemString(d, "CTRL_C_EVENT", x); Py_DECREF(x); #endif #ifdef CTRL_BREAK_EVENT x = PyLong_FromLong(CTRL_BREAK_EVENT); PyDict_SetItemString(d, "CTRL_BREAK_EVENT", x); Py_DECREF(x); #endif if (PyErr_Occurred()) { Py_DECREF(m); m = NULL; } finally: return m; } static void finisignal(void) { int i; PyObject *func; PyOS_setsig(SIGINT, old_siginthandler); old_siginthandler = SIG_DFL; for (i = 1; i < NSIG; i++) { func = Handlers[i].func; Handlers[i].tripped = 0; Handlers[i].func = NULL; if (i != SIGINT && func != NULL && func != Py_None && func != DefaultHandler && func != IgnoreHandler) PyOS_setsig(i, SIG_DFL); Py_XDECREF(func); } Py_XDECREF(IntHandler); IntHandler = NULL; Py_XDECREF(DefaultHandler); DefaultHandler = NULL; Py_XDECREF(IgnoreHandler); IgnoreHandler = NULL; } /* Declared in pyerrors.h */ int PyErr_CheckSignals(void) { int i; PyObject *f; if (!is_tripped) return 0; #ifdef WITH_THREAD if (PyThread_get_thread_ident() != main_thread) return 0; #endif /* * The is_tripped variable is meant to speed up the calls to * PyErr_CheckSignals (both directly or via pending calls) when no * signal has arrived. This variable is set to 1 when a signal arrives * and it is set to 0 here, when we know some signals arrived. This way * we can run the registered handlers with no signals blocked. * * NOTE: with this approach we can have a situation where is_tripped is * 1 but we have no more signals to handle (Handlers[i].tripped * is 0 for every signal i). This won't do us any harm (except * we're gonna spent some cycles for nothing). This happens when * we receive a signal i after we zero is_tripped and before we * check Handlers[i].tripped. */ is_tripped = 0; if (!(f = (PyObject *)PyEval_GetFrame())) f = Py_None; for (i = 1; i < NSIG; i++) { if (Handlers[i].tripped) { PyObject *result = NULL; PyObject *arglist = Py_BuildValue("(iO)", i, f); Handlers[i].tripped = 0; if (arglist) { result = PyEval_CallObject(Handlers[i].func, arglist); Py_DECREF(arglist); } if (!result) return -1; Py_DECREF(result); } } return 0; } /* Replacements for intrcheck.c functionality * Declared in pyerrors.h */ void PyErr_SetInterrupt(void) { trip_signal(SIGINT); } void PyOS_InitInterrupts(void) { PyObject *m = PyInit_signal(); if (m) { _PyImport_FixupBuiltin(m, "signal"); Py_DECREF(m); } } void PyOS_FiniInterrupts(void) { finisignal(); } int PyOS_InterruptOccurred(void) { if (Handlers[SIGINT].tripped) { #ifdef WITH_THREAD if (PyThread_get_thread_ident() != main_thread) return 0; #endif Handlers[SIGINT].tripped = 0; return 1; } return 0; } void PyOS_AfterFork(void) { #ifdef WITH_THREAD _PyGILState_Reinit(); PyEval_ReInitThreads(); main_thread = PyThread_get_thread_ident(); main_pid = getpid(); _PyImport_ReInitLock(); PyThread_ReInitTLS(); #endif } /* Signal module -- many thanks to Lance Ellinghaus */ /* XXX Signals should be recorded per thread, now we have thread state. */ #include "Python.h" #ifdef MS_WINDOWS #include <Windows.h> #ifdef HAVE_PROCESS_H #include <process.h> #endif #endif #ifdef HAVE_SIGNAL_H #include <signal.h> #endif #ifdef HAVE_SYS_STAT_H #include <sys/stat.h> #endif #ifdef HAVE_SYS_TIME_H #include <sys/time.h> #endif #if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK) # define PYPTHREAD_SIGMASK #endif #if defined(PYPTHREAD_SIGMASK) && defined(HAVE_PTHREAD_H) # include <pthread.h> #endif #ifndef SIG_ERR #define SIG_ERR ((PyOS_sighandler_t)(-1)) #endif #if defined(PYOS_OS2) && !defined(PYCC_GCC) #define NSIG 12 #include <process.h> #endif #ifndef NSIG # if defined(_NSIG) # define NSIG _NSIG /* For BSD/SysV */ # elif defined(_SIGMAX) # define NSIG (_SIGMAX + 1) /* For QNX */ # elif defined(SIGMAX) # define NSIG (SIGMAX + 1) /* For djgpp */ # else # define NSIG 64 /* Use a reasonable default value */ # endif #endif /* NOTES ON THE INTERACTION BETWEEN SIGNALS AND THREADS When threads are supported, we want the following semantics: - only the main thread can set a signal handler - any thread can get a signal handler - signals are only delivered to the main thread I.e. we don't support "synchronous signals" like SIGFPE (catching this doesn't make much sense in Python anyway) nor do we support signals as a means of inter-thread communication, since not all thread implementations support that (at least our thread library doesn't). We still have the problem that in some implementations signals generated by the keyboard (e.g. SIGINT) are delivered to all threads (e.g. SGI), while in others (e.g. Solaris) such signals are delivered to one random thread (an intermediate possibility would be to deliver it to the main thread -- POSIX?). For now, we have a working implementation that works in all three cases -- the handler ignores signals if getpid() isn't the same as in the main thread. XXX This is a hack. GNU pth is a user-space threading library, and as such, all threads run within the same process. In this case, if the currently running thread is not the main_thread, send the signal to the main_thread. */ #ifdef WITH_THREAD #include <sys/types.h> /* For pid_t */ #include "pythread.h" static long main_thread; static pid_t main_pid; #endif static struct { int tripped; PyObject *func; } Handlers[NSIG]; static sig_atomic_t wakeup_fd = -1; /* Speed up sigcheck() when none tripped */ static volatile sig_atomic_t is_tripped = 0; static PyObject *DefaultHandler; static PyObject *IgnoreHandler; static PyObject *IntHandler; /* On Solaris 8, gcc will produce a warning that the function declaration is not a prototype. This is caused by the definition of SIG_DFL as (void (*)())0; the correct declaration would have been (void (*)(int))0. */ static PyOS_sighandler_t old_siginthandler = SIG_DFL; #ifdef HAVE_GETITIMER static PyObject *ItimerError; /* auxiliary functions for setitimer/getitimer */ static void timeval_from_double(double d, struct timeval *tv) { tv->tv_sec = floor(d); tv->tv_usec = fmod(d, 1.0) * 1000000.0; } Py_LOCAL_INLINE(double) double_from_timeval(struct timeval *tv) { return tv->tv_sec + (double)(tv->tv_usec / 1000000.0); } static PyObject * itimer_retval(struct itimerval *iv) { PyObject *r, *v; r = PyTuple_New(2); if (r == NULL) return NULL; if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_value)))) { Py_DECREF(r); return NULL; } PyTuple_SET_ITEM(r, 0, v); if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_interval)))) { Py_DECREF(r); return NULL; } PyTuple_SET_ITEM(r, 1, v); return r; } #endif static PyObject * signal_default_int_handler(PyObject *self, PyObject *args) { PyErr_SetNone(PyExc_KeyboardInterrupt); return NULL; } PyDoc_STRVAR(default_int_handler_doc, "default_int_handler(...)\n\ \n\ The default handler for SIGINT installed by Python.\n\ It raises KeyboardInterrupt."); static int checksignals_witharg(void * unused) { return PyErr_CheckSignals(); } static void trip_signal(int sig_num) { unsigned char byte; Handlers[sig_num].tripped = 1; if (is_tripped) return; /* Set is_tripped after setting .tripped, as it gets cleared in PyErr_CheckSignals() before .tripped. */ is_tripped = 1; Py_AddPendingCall(checksignals_witharg, NULL); if (wakeup_fd != -1) { byte = (unsigned char)sig_num; write(wakeup_fd, &byte, 1); } } static void signal_handler(int sig_num) { int save_errno = errno; #if defined(WITH_THREAD) && defined(WITH_PTH) if (PyThread_get_thread_ident() != main_thread) { pth_raise(*(pth_t *) main_thread, sig_num); } else #endif { #ifdef WITH_THREAD /* See NOTES section above */ if (getpid() == main_pid) #endif { trip_signal(sig_num); } #ifndef HAVE_SIGACTION #ifdef SIGCHLD /* To avoid infinite recursion, this signal remains reset until explicit re-instated. Don't clear the 'func' field as it is our pointer to the Python handler... */ if (sig_num != SIGCHLD) #endif /* If the handler was not set up with sigaction, reinstall it. See * Python/pythonrun.c for the implementation of PyOS_setsig which * makes this true. See also issue8354. */ PyOS_setsig(sig_num, signal_handler); #endif } /* Issue #10311: asynchronously executing signal handlers should not mutate errno under the feet of unsuspecting C code. */ errno = save_errno; } #ifdef HAVE_ALARM static PyObject * signal_alarm(PyObject *self, PyObject *args) { int t; if (!PyArg_ParseTuple(args, "i:alarm", &t)) return NULL; /* alarm() returns the number of seconds remaining */ return PyLong_FromLong((long)alarm(t)); } PyDoc_STRVAR(alarm_doc, "alarm(seconds)\n\ \n\ Arrange for SIGALRM to arrive after the given number of seconds."); #endif #ifdef HAVE_PAUSE static PyObject * signal_pause(PyObject *self) { Py_BEGIN_ALLOW_THREADS (void)pause(); Py_END_ALLOW_THREADS /* make sure that any exceptions that got raised are propagated * back into Python */ if (PyErr_CheckSignals()) return NULL; Py_INCREF(Py_None); return Py_None; } PyDoc_STRVAR(pause_doc, "pause()\n\ \n\ Wait until a signal arrives."); #endif static PyObject * signal_signal(PyObject *self, PyObject *args) { PyObject *obj; int sig_num; PyObject *old_handler; void (*func)(int); if (!PyArg_ParseTuple(args, "iO:signal", &sig_num, &obj)) return NULL; #ifdef MS_WINDOWS /* Validate that sig_num is one of the allowable signals */ switch (sig_num) { case SIGABRT: break; #ifdef SIGBREAK /* Issue #10003: SIGBREAK is not documented as permitted, but works and corresponds to CTRL_BREAK_EVENT. */ case SIGBREAK: break; #endif case SIGFPE: break; case SIGILL: break; case SIGINT: break; case SIGSEGV: break; case SIGTERM: break; default: PyErr_SetString(PyExc_ValueError, "invalid signal value"); return NULL; } #endif #ifdef WITH_THREAD if (PyThread_get_thread_ident() != main_thread) { PyErr_SetString(PyExc_ValueError, "signal only works in main thread"); return NULL; } #endif if (sig_num < 1 || sig_num >= NSIG) { PyErr_SetString(PyExc_ValueError, "signal number out of range"); return NULL; } if (obj == IgnoreHandler) func = SIG_IGN; else if (obj == DefaultHandler) func = SIG_DFL; else if (!PyCallable_Check(obj)) { PyErr_SetString(PyExc_TypeError, "signal handler must be signal.SIG_IGN, signal.SIG_DFL, or a callable object"); return NULL; } else func = signal_handler; if (PyOS_setsig(sig_num, func) == SIG_ERR) { PyErr_SetFromErrno(PyExc_RuntimeError); return NULL; } old_handler = Handlers[sig_num].func; Handlers[sig_num].tripped = 0; Py_INCREF(obj); Handlers[sig_num].func = obj; return old_handler; } PyDoc_STRVAR(signal_doc, "signal(sig, action) -> action\n\ \n\ Set the action for the given signal. The action can be SIG_DFL,\n\ SIG_IGN, or a callable Python object. The previous action is\n\ returned. See getsignal() for possible return values.\n\ \n\ *** IMPORTANT NOTICE ***\n\ A signal handler function is called with two arguments:\n\ the first is the signal number, the second is the interrupted stack frame."); static PyObject * signal_getsignal(PyObject *self, PyObject *args) { int sig_num; PyObject *old_handler; if (!PyArg_ParseTuple(args, "i:getsignal", &sig_num)) return NULL; if (sig_num < 1 || sig_num >= NSIG) { PyErr_SetString(PyExc_ValueError, "signal number out of range"); return NULL; } old_handler = Handlers[sig_num].func; Py_INCREF(old_handler); return old_handler; } PyDoc_STRVAR(getsignal_doc, "getsignal(sig) -> action\n\ \n\ Return the current action for the given signal. The return value can be:\n\ SIG_IGN -- if the signal is being ignored\n\ SIG_DFL -- if the default action for the signal is in effect\n\ None -- if an unknown handler is in effect\n\ anything else -- the callable Python object used as a handler"); #ifdef HAVE_SIGINTERRUPT PyDoc_STRVAR(siginterrupt_doc, "siginterrupt(sig, flag) -> None\n\ change system call restart behaviour: if flag is False, system calls\n\ will be restarted when interrupted by signal sig, else system calls\n\ will be interrupted."); static PyObject * signal_siginterrupt(PyObject *self, PyObject *args) { int sig_num; int flag; if (!PyArg_ParseTuple(args, "ii:siginterrupt", &sig_num, &flag)) return NULL; if (sig_num < 1 || sig_num >= NSIG) { PyErr_SetString(PyExc_ValueError, "signal number out of range"); return NULL; } if (siginterrupt(sig_num, flag)<0) { PyErr_SetFromErrno(PyExc_RuntimeError); return NULL; } Py_INCREF(Py_None); return Py_None; } #endif static PyObject * signal_set_wakeup_fd(PyObject *self, PyObject *args) { struct stat buf; int fd, old_fd; if (!PyArg_ParseTuple(args, "i:set_wakeup_fd", &fd)) return NULL; #ifdef WITH_THREAD if (PyThread_get_thread_ident() != main_thread) { PyErr_SetString(PyExc_ValueError, "set_wakeup_fd only works in main thread"); return NULL; } #endif if (fd != -1 && fstat(fd, &buf) != 0) { PyErr_SetString(PyExc_ValueError, "invalid fd"); return NULL; } old_fd = wakeup_fd; wakeup_fd = fd; return PyLong_FromLong(old_fd); } PyDoc_STRVAR(set_wakeup_fd_doc, "set_wakeup_fd(fd) -> fd\n\ \n\ Sets the fd to be written to (with '\\0') when a signal\n\ comes in. A library can use this to wakeup select or poll.\n\ The previous fd is returned.\n\ \n\ The fd must be non-blocking."); /* C API for the same, without all the error checking */ int PySignal_SetWakeupFd(int fd) { int old_fd = wakeup_fd; if (fd < 0) fd = -1; wakeup_fd = fd; return old_fd; } #ifdef HAVE_SETITIMER static PyObject * signal_setitimer(PyObject *self, PyObject *args) { double first; double interval = 0; int which; struct itimerval new, old; if(!PyArg_ParseTuple(args, "id|d:setitimer", &which, &first, &interval)) return NULL; timeval_from_double(first, &new.it_value); timeval_from_double(interval, &new.it_interval); /* Let OS check "which" value */ if (setitimer(which, &new, &old) != 0) { PyErr_SetFromErrno(ItimerError); return NULL; } return itimer_retval(&old); } PyDoc_STRVAR(setitimer_doc, "setitimer(which, seconds[, interval])\n\ \n\ Sets given itimer (one of ITIMER_REAL, ITIMER_VIRTUAL\n\ or ITIMER_PROF) to fire after value seconds and after\n\ that every interval seconds.\n\ The itimer can be cleared by setting seconds to zero.\n\ \n\ Returns old values as a tuple: (delay, interval)."); #endif #ifdef HAVE_GETITIMER static PyObject * signal_getitimer(PyObject *self, PyObject *args) { int which; struct itimerval old; if (!PyArg_ParseTuple(args, "i:getitimer", &which)) return NULL; if (getitimer(which, &old) != 0) { PyErr_SetFromErrno(ItimerError); return NULL; } return itimer_retval(&old); } PyDoc_STRVAR(getitimer_doc, "getitimer(which)\n\ \n\ Returns current value of given itimer."); #endif #if defined(PYPTHREAD_SIGMASK) || defined(HAVE_SIGWAIT) /* Convert an iterable to a sigset. Return 0 on success, return -1 and raise an exception on error. */ static int iterable_to_sigset(PyObject *iterable, sigset_t *mask) { int result = -1; PyObject *iterator, *item; long signum; int err; sigemptyset(mask); iterator = PyObject_GetIter(iterable); if (iterator == NULL) goto error; while (1) { item = PyIter_Next(iterator); if (item == NULL) { if (PyErr_Occurred()) goto error; else break; } signum = PyLong_AsLong(item); Py_DECREF(item); if (signum == -1 && PyErr_Occurred()) goto error; if (0 < signum && signum < NSIG) err = sigaddset(mask, (int)signum); else err = 1; if (err) { PyErr_Format(PyExc_ValueError, "signal number %ld out of range", signum); goto error; } } result = 0; error: Py_XDECREF(iterator); return result; } #endif #if defined(PYPTHREAD_SIGMASK) || defined(HAVE_SIGPENDING) static PyObject* sigset_to_set(sigset_t mask) { PyObject *signum, *result; int sig; result = PySet_New(0); if (result == NULL) return NULL; for (sig = 1; sig < NSIG; sig++) { if (sigismember(&mask, sig) != 1) continue; /* Handle the case where it is a member by adding the signal to the result list. Ignore the other cases because they mean the signal isn't a member of the mask or the signal was invalid, and an invalid signal must have been our fault in constructing the loop boundaries. */ signum = PyLong_FromLong(sig); if (signum == NULL) { Py_DECREF(result); return NULL; } if (PySet_Add(result, signum) == -1) { Py_DECREF(signum); Py_DECREF(result); return NULL; } Py_DECREF(signum); } return result; } #endif #ifdef PYPTHREAD_SIGMASK static PyObject * signal_pthread_sigmask(PyObject *self, PyObject *args) { int how; PyObject *signals; sigset_t mask, previous; int err; if (!PyArg_ParseTuple(args, "iO:pthread_sigmask", &how, &signals)) return NULL; if (iterable_to_sigset(signals, &mask)) return NULL; err = pthread_sigmask(how, &mask, &previous); if (err != 0) { errno = err; PyErr_SetFromErrno(PyExc_OSError); return NULL; } /* if signals was unblocked, signal handlers have been called */ if (PyErr_CheckSignals()) return NULL; return sigset_to_set(previous); } PyDoc_STRVAR(signal_pthread_sigmask_doc, "pthread_sigmask(how, mask) -> old mask\n\ \n\ Fetch and/or change the signal mask of the calling thread."); #endif /* #ifdef PYPTHREAD_SIGMASK */ #ifdef HAVE_SIGPENDING static PyObject * signal_sigpending(PyObject *self) { int err; sigset_t mask; err = sigpending(&mask); if (err) return PyErr_SetFromErrno(PyExc_OSError); return sigset_to_set(mask); } PyDoc_STRVAR(signal_sigpending_doc, "sigpending() -> list\n\ \n\ Examine pending signals."); #endif /* #ifdef HAVE_SIGPENDING */ #ifdef HAVE_SIGWAIT static PyObject * signal_sigwait(PyObject *self, PyObject *args) { PyObject *signals; sigset_t set; int err, signum; if (!PyArg_ParseTuple(args, "O:sigwait", &signals)) return NULL; if (iterable_to_sigset(signals, &set)) return NULL; err = sigwait(&set, &signum); if (err) { errno = err; return PyErr_SetFromErrno(PyExc_OSError); } return PyLong_FromLong(signum); } PyDoc_STRVAR(signal_sigwait_doc, "sigwait(sigset) -> signum\n\ \n\ Wait a signal."); #endif /* #ifdef HAVE_SIGPENDING */ #if defined(HAVE_PTHREAD_KILL) && defined(WITH_THREAD) static PyObject * signal_pthread_kill(PyObject *self, PyObject *args) { long tid; int signum; int err; if (!PyArg_ParseTuple(args, "li:pthread_kill", &tid, &signum)) return NULL; err = pthread_kill(tid, signum); if (err != 0) { errno = err; PyErr_SetFromErrno(PyExc_OSError); return NULL; } /* the signal may have been send to the current thread */ if (PyErr_CheckSignals()) return NULL; Py_RETURN_NONE; } PyDoc_STRVAR(signal_pthread_kill_doc, "pthread_kill(thread_id, signum)\n\ \n\ Send a signal to a thread."); #endif /* #if defined(HAVE_PTHREAD_KILL) && defined(WITH_THREAD) */ /* List of functions defined in the module */ static PyMethodDef signal_methods[] = { #ifdef HAVE_ALARM {"alarm", signal_alarm, METH_VARARGS, alarm_doc}, #endif #ifdef HAVE_SETITIMER {"setitimer", signal_setitimer, METH_VARARGS, setitimer_doc}, #endif #ifdef HAVE_GETITIMER {"getitimer", signal_getitimer, METH_VARARGS, getitimer_doc}, #endif {"signal", signal_signal, METH_VARARGS, signal_doc}, {"getsignal", signal_getsignal, METH_VARARGS, getsignal_doc}, {"set_wakeup_fd", signal_set_wakeup_fd, METH_VARARGS, set_wakeup_fd_doc}, #ifdef HAVE_SIGINTERRUPT {"siginterrupt", signal_siginterrupt, METH_VARARGS, siginterrupt_doc}, #endif #ifdef HAVE_PAUSE {"pause", (PyCFunction)signal_pause, METH_NOARGS, pause_doc}, #endif {"default_int_handler", signal_default_int_handler, METH_VARARGS, default_int_handler_doc}, #if defined(HAVE_PTHREAD_KILL) && defined(WITH_THREAD) {"pthread_kill", (PyCFunction)signal_pthread_kill, METH_VARARGS, signal_pthread_kill_doc}, #endif #ifdef PYPTHREAD_SIGMASK {"pthread_sigmask", (PyCFunction)signal_pthread_sigmask, METH_VARARGS, signal_pthread_sigmask_doc}, #endif #ifdef HAVE_SIGPENDING {"sigpending", (PyCFunction)signal_sigpending, METH_NOARGS, signal_sigpending_doc}, #endif #ifdef HAVE_SIGWAIT {"sigwait", (PyCFunction)signal_sigwait, METH_VARARGS, signal_sigwait_doc}, #endif {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(module_doc, "This module provides mechanisms to use signal handlers in Python.\n\ \n\ Functions:\n\ \n\ alarm() -- cause SIGALRM after a specified time [Unix only]\n\ setitimer() -- cause a signal (described below) after a specified\n\ float time and the timer may restart then [Unix only]\n\ getitimer() -- get current value of timer [Unix only]\n\ signal() -- set the action for a given signal\n\ getsignal() -- get the signal action for a given signal\n\ pause() -- wait until a signal arrives [Unix only]\n\ default_int_handler() -- default SIGINT handler\n\ \n\ signal constants:\n\ SIG_DFL -- used to refer to the system default handler\n\ SIG_IGN -- used to ignore the signal\n\ NSIG -- number of defined signals\n\ SIGINT, SIGTERM, etc. -- signal numbers\n\ \n\ itimer constants:\n\ ITIMER_REAL -- decrements in real time, and delivers SIGALRM upon\n\ expiration\n\ ITIMER_VIRTUAL -- decrements only when the process is executing,\n\ and delivers SIGVTALRM upon expiration\n\ ITIMER_PROF -- decrements both when the process is executing and\n\ when the system is executing on behalf of the process.\n\ Coupled with ITIMER_VIRTUAL, this timer is usually\n\ used to profile the time spent by the application\n\ in user and kernel space. SIGPROF is delivered upon\n\ expiration.\n\ \n\n\ *** IMPORTANT NOTICE ***\n\ A signal handler function is called with two arguments:\n\ the first is the signal number, the second is the interrupted stack frame."); static struct PyModuleDef signalmodule = { PyModuleDef_HEAD_INIT, "signal", module_doc, -1, signal_methods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_signal(void) { PyObject *m, *d, *x; int i; #ifdef WITH_THREAD main_thread = PyThread_get_thread_ident(); main_pid = getpid(); #endif /* Create the module and add the functions */ m = PyModule_Create(&signalmodule); if (m == NULL) return NULL; /* Add some symbolic constants to the module */ d = PyModule_GetDict(m); x = DefaultHandler = PyLong_FromVoidPtr((void *)SIG_DFL); if (!x || PyDict_SetItemString(d, "SIG_DFL", x) < 0) goto finally; x = IgnoreHandler = PyLong_FromVoidPtr((void *)SIG_IGN); if (!x || PyDict_SetItemString(d, "SIG_IGN", x) < 0) goto finally; x = PyLong_FromLong((long)NSIG); if (!x || PyDict_SetItemString(d, "NSIG", x) < 0) goto finally; Py_DECREF(x); #ifdef SIG_BLOCK if (PyModule_AddIntMacro(m, SIG_BLOCK)) goto finally; #endif #ifdef SIG_UNBLOCK if (PyModule_AddIntMacro(m, SIG_UNBLOCK)) goto finally; #endif #ifdef SIG_SETMASK if (PyModule_AddIntMacro(m, SIG_SETMASK)) goto finally; #endif x = IntHandler = PyDict_GetItemString(d, "default_int_handler"); if (!x) goto finally; Py_INCREF(IntHandler); Handlers[0].tripped = 0; for (i = 1; i < NSIG; i++) { void (*t)(int); t = PyOS_getsig(i); Handlers[i].tripped = 0; if (t == SIG_DFL) Handlers[i].func = DefaultHandler; else if (t == SIG_IGN) Handlers[i].func = IgnoreHandler; else Handlers[i].func = Py_None; /* None of our business */ Py_INCREF(Handlers[i].func); } if (Handlers[SIGINT].func == DefaultHandler) { /* Install default int handler */ Py_INCREF(IntHandler); Py_DECREF(Handlers[SIGINT].func); Handlers[SIGINT].func = IntHandler; old_siginthandler = PyOS_setsig(SIGINT, signal_handler); } #ifdef SIGHUP x = PyLong_FromLong(SIGHUP); PyDict_SetItemString(d, "SIGHUP", x); Py_XDECREF(x); #endif #ifdef SIGINT x = PyLong_FromLong(SIGINT); PyDict_SetItemString(d, "SIGINT", x); Py_XDECREF(x); #endif #ifdef SIGBREAK x = PyLong_FromLong(SIGBREAK); PyDict_SetItemString(d, "SIGBREAK", x); Py_XDECREF(x); #endif #ifdef SIGQUIT x = PyLong_FromLong(SIGQUIT); PyDict_SetItemString(d, "SIGQUIT", x); Py_XDECREF(x); #endif #ifdef SIGILL x = PyLong_FromLong(SIGILL); PyDict_SetItemString(d, "SIGILL", x); Py_XDECREF(x); #endif #ifdef SIGTRAP x = PyLong_FromLong(SIGTRAP); PyDict_SetItemString(d, "SIGTRAP", x); Py_XDECREF(x); #endif #ifdef SIGIOT x = PyLong_FromLong(SIGIOT); PyDict_SetItemString(d, "SIGIOT", x); Py_XDECREF(x); #endif #ifdef SIGABRT x = PyLong_FromLong(SIGABRT); PyDict_SetItemString(d, "SIGABRT", x); Py_XDECREF(x); #endif #ifdef SIGEMT x = PyLong_FromLong(SIGEMT); PyDict_SetItemString(d, "SIGEMT", x); Py_XDECREF(x); #endif #ifdef SIGFPE x = PyLong_FromLong(SIGFPE); PyDict_SetItemString(d, "SIGFPE", x); Py_XDECREF(x); #endif #ifdef SIGKILL x = PyLong_FromLong(SIGKILL); PyDict_SetItemString(d, "SIGKILL", x); Py_XDECREF(x); #endif #ifdef SIGBUS x = PyLong_FromLong(SIGBUS); PyDict_SetItemString(d, "SIGBUS", x); Py_XDECREF(x); #endif #ifdef SIGSEGV x = PyLong_FromLong(SIGSEGV); PyDict_SetItemString(d, "SIGSEGV", x); Py_XDECREF(x); #endif #ifdef SIGSYS x = PyLong_FromLong(SIGSYS); PyDict_SetItemString(d, "SIGSYS", x); Py_XDECREF(x); #endif #ifdef SIGPIPE x = PyLong_FromLong(SIGPIPE); PyDict_SetItemString(d, "SIGPIPE", x); Py_XDECREF(x); #endif #ifdef SIGALRM x = PyLong_FromLong(SIGALRM); PyDict_SetItemString(d, "SIGALRM", x); Py_XDECREF(x); #endif #ifdef SIGTERM x = PyLong_FromLong(SIGTERM); PyDict_SetItemString(d, "SIGTERM", x); Py_XDECREF(x); #endif #ifdef SIGUSR1 x = PyLong_FromLong(SIGUSR1); PyDict_SetItemString(d, "SIGUSR1", x); Py_XDECREF(x); #endif #ifdef SIGUSR2 x = PyLong_FromLong(SIGUSR2); PyDict_SetItemString(d, "SIGUSR2", x); Py_XDECREF(x); #endif #ifdef SIGCLD x = PyLong_FromLong(SIGCLD); PyDict_SetItemString(d, "SIGCLD", x); Py_XDECREF(x); #endif #ifdef SIGCHLD x = PyLong_FromLong(SIGCHLD); PyDict_SetItemString(d, "SIGCHLD", x); Py_XDECREF(x); #endif #ifdef SIGPWR x = PyLong_FromLong(SIGPWR); PyDict_SetItemString(d, "SIGPWR", x); Py_XDECREF(x); #endif #ifdef SIGIO x = PyLong_FromLong(SIGIO); PyDict_SetItemString(d, "SIGIO", x); Py_XDECREF(x); #endif #ifdef SIGURG x = PyLong_FromLong(SIGURG); PyDict_SetItemString(d, "SIGURG", x); Py_XDECREF(x); #endif #ifdef SIGWINCH x = PyLong_FromLong(SIGWINCH); PyDict_SetItemString(d, "SIGWINCH", x); Py_XDECREF(x); #endif #ifdef SIGPOLL x = PyLong_FromLong(SIGPOLL); PyDict_SetItemString(d, "SIGPOLL", x); Py_XDECREF(x); #endif #ifdef SIGSTOP x = PyLong_FromLong(SIGSTOP); PyDict_SetItemString(d, "SIGSTOP", x); Py_XDECREF(x); #endif #ifdef SIGTSTP x = PyLong_FromLong(SIGTSTP); PyDict_SetItemString(d, "SIGTSTP", x); Py_XDECREF(x); #endif #ifdef SIGCONT x = PyLong_FromLong(SIGCONT); PyDict_SetItemString(d, "SIGCONT", x); Py_XDECREF(x); #endif #ifdef SIGTTIN x = PyLong_FromLong(SIGTTIN); PyDict_SetItemString(d, "SIGTTIN", x); Py_XDECREF(x); #endif #ifdef SIGTTOU x = PyLong_FromLong(SIGTTOU); PyDict_SetItemString(d, "SIGTTOU", x); Py_XDECREF(x); #endif #ifdef SIGVTALRM x = PyLong_FromLong(SIGVTALRM); PyDict_SetItemString(d, "SIGVTALRM", x); Py_XDECREF(x); #endif #ifdef SIGPROF x = PyLong_FromLong(SIGPROF); PyDict_SetItemString(d, "SIGPROF", x); Py_XDECREF(x); #endif #ifdef SIGXCPU x = PyLong_FromLong(SIGXCPU); PyDict_SetItemString(d, "SIGXCPU", x); Py_XDECREF(x); #endif #ifdef SIGXFSZ x = PyLong_FromLong(SIGXFSZ); PyDict_SetItemString(d, "SIGXFSZ", x); Py_XDECREF(x); #endif #ifdef SIGRTMIN x = PyLong_FromLong(SIGRTMIN); PyDict_SetItemString(d, "SIGRTMIN", x); Py_XDECREF(x); #endif #ifdef SIGRTMAX x = PyLong_FromLong(SIGRTMAX); PyDict_SetItemString(d, "SIGRTMAX", x); Py_XDECREF(x); #endif #ifdef SIGINFO x = PyLong_FromLong(SIGINFO); PyDict_SetItemString(d, "SIGINFO", x); Py_XDECREF(x); #endif #ifdef ITIMER_REAL x = PyLong_FromLong(ITIMER_REAL); PyDict_SetItemString(d, "ITIMER_REAL", x); Py_DECREF(x); #endif #ifdef ITIMER_VIRTUAL x = PyLong_FromLong(ITIMER_VIRTUAL); PyDict_SetItemString(d, "ITIMER_VIRTUAL", x); Py_DECREF(x); #endif #ifdef ITIMER_PROF x = PyLong_FromLong(ITIMER_PROF); PyDict_SetItemString(d, "ITIMER_PROF", x); Py_DECREF(x); #endif #if defined (HAVE_SETITIMER) || defined (HAVE_GETITIMER) ItimerError = PyErr_NewException("signal.ItimerError", PyExc_IOError, NULL); if (ItimerError != NULL) PyDict_SetItemString(d, "ItimerError", ItimerError); #endif #ifdef CTRL_C_EVENT x = PyLong_FromLong(CTRL_C_EVENT); PyDict_SetItemString(d, "CTRL_C_EVENT", x); Py_DECREF(x); #endif #ifdef CTRL_BREAK_EVENT x = PyLong_FromLong(CTRL_BREAK_EVENT); PyDict_SetItemString(d, "CTRL_BREAK_EVENT", x); Py_DECREF(x); #endif if (PyErr_Occurred()) { Py_DECREF(m); m = NULL; } finally: return m; } static void finisignal(void) { int i; PyObject *func; PyOS_setsig(SIGINT, old_siginthandler); old_siginthandler = SIG_DFL; for (i = 1; i < NSIG; i++) { func = Handlers[i].func; Handlers[i].tripped = 0; Handlers[i].func = NULL; if (i != SIGINT && func != NULL && func != Py_None && func != DefaultHandler && func != IgnoreHandler) PyOS_setsig(i, SIG_DFL); Py_XDECREF(func); } Py_XDECREF(IntHandler); IntHandler = NULL; Py_XDECREF(DefaultHandler); DefaultHandler = NULL; Py_XDECREF(IgnoreHandler); IgnoreHandler = NULL; } /* Declared in pyerrors.h */ int PyErr_CheckSignals(void) { int i; PyObject *f; if (!is_tripped) return 0; #ifdef WITH_THREAD if (PyThread_get_thread_ident() != main_thread) return 0; #endif /* * The is_tripped variable is meant to speed up the calls to * PyErr_CheckSignals (both directly or via pending calls) when no * signal has arrived. This variable is set to 1 when a signal arrives * and it is set to 0 here, when we know some signals arrived. This way * we can run the registered handlers with no signals blocked. * * NOTE: with this approach we can have a situation where is_tripped is * 1 but we have no more signals to handle (Handlers[i].tripped * is 0 for every signal i). This won't do us any harm (except * we're gonna spent some cycles for nothing). This happens when * we receive a signal i after we zero is_tripped and before we * check Handlers[i].tripped. */ is_tripped = 0; if (!(f = (PyObject *)PyEval_GetFrame())) f = Py_None; for (i = 1; i < NSIG; i++) { if (Handlers[i].tripped) { PyObject *result = NULL; PyObject *arglist = Py_BuildValue("(iO)", i, f); Handlers[i].tripped = 0; if (arglist) { result = PyEval_CallObject(Handlers[i].func, arglist); Py_DECREF(arglist); } if (!result) return -1; Py_DECREF(result); } } return 0; } /* Replacements for intrcheck.c functionality * Declared in pyerrors.h */ void PyErr_SetInterrupt(void) { trip_signal(SIGINT); } void PyOS_InitInterrupts(void) { PyObject *m = PyInit_signal(); if (m) { _PyImport_FixupBuiltin(m, "signal"); Py_DECREF(m); } } void PyOS_FiniInterrupts(void) { finisignal(); } int PyOS_InterruptOccurred(void) { if (Handlers[SIGINT].tripped) { #ifdef WITH_THREAD if (PyThread_get_thread_ident() != main_thread) return 0; #endif Handlers[SIGINT].tripped = 0; return 1; } return 0; } void PyOS_AfterFork(void) { #ifdef WITH_THREAD _PyGILState_Reinit(); PyEval_ReInitThreads(); main_thread = PyThread_get_thread_ident(); main_pid = getpid(); _PyImport_ReInitLock(); PyThread_ReInitTLS(); #endif }
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/python_69934-69935.c
manybugs_data_6
/* * make sure _GNU_SOURCE is defined */ #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <sys/types.h> #include <sys/stat.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> /* only the defines on windows */ #include <errno.h> #include <time.h> #include <stdio.h> #include "base.h" #include "log.h" #include "buffer.h" #include "plugin.h" #include "inet_ntop_cache.h" #include "sys-socket.h" #include "sys-files.h" #ifdef HAVE_SYSLOG_H # include <syslog.h> #endif typedef struct { char key; enum { FORMAT_UNSET, FORMAT_UNSUPPORTED, FORMAT_PERCENT, FORMAT_REMOTE_HOST, FORMAT_REMOTE_IDENT, FORMAT_REMOTE_USER, FORMAT_TIMESTAMP, FORMAT_REQUEST_LINE, FORMAT_STATUS, FORMAT_BYTES_OUT_NO_HEADER, FORMAT_HEADER, FORMAT_REMOTE_ADDR, FORMAT_LOCAL_ADDR, FORMAT_COOKIE, FORMAT_TIME_USED_MS, FORMAT_ENV, FORMAT_FILENAME, FORMAT_REQUEST_PROTOCOL, FORMAT_REQUEST_METHOD, FORMAT_SERVER_PORT, FORMAT_QUERY_STRING, FORMAT_TIME_USED, FORMAT_URL, FORMAT_SERVER_NAME, FORMAT_HTTP_HOST, FORMAT_CONNECTION_STATUS, FORMAT_BYTES_IN, FORMAT_BYTES_OUT, FORMAT_RESPONSE_HEADER } type; } format_mapping; /** * * * "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" * */ const format_mapping fmap[] = { { '%', FORMAT_PERCENT }, { 'h', FORMAT_REMOTE_HOST }, { 'l', FORMAT_REMOTE_IDENT }, { 'u', FORMAT_REMOTE_USER }, { 't', FORMAT_TIMESTAMP }, { 'r', FORMAT_REQUEST_LINE }, { 's', FORMAT_STATUS }, { 'b', FORMAT_BYTES_OUT_NO_HEADER }, { 'i', FORMAT_HEADER }, { 'a', FORMAT_REMOTE_ADDR }, { 'A', FORMAT_LOCAL_ADDR }, { 'B', FORMAT_BYTES_OUT_NO_HEADER }, { 'C', FORMAT_COOKIE }, { 'D', FORMAT_TIME_USED_MS }, { 'e', FORMAT_ENV }, { 'f', FORMAT_FILENAME }, { 'H', FORMAT_REQUEST_PROTOCOL }, { 'm', FORMAT_REQUEST_METHOD }, { 'n', FORMAT_UNSUPPORTED }, /* we have no notes */ { 'p', FORMAT_SERVER_PORT }, { 'P', FORMAT_UNSUPPORTED }, /* we are only one process */ { 'q', FORMAT_QUERY_STRING }, { 'T', FORMAT_TIME_USED }, { 'U', FORMAT_URL }, /* w/o querystring */ { 'v', FORMAT_SERVER_NAME }, { 'V', FORMAT_HTTP_HOST }, { 'X', FORMAT_CONNECTION_STATUS }, { 'I', FORMAT_BYTES_IN }, { 'O', FORMAT_BYTES_OUT }, { 'o', FORMAT_RESPONSE_HEADER }, { '\0', FORMAT_UNSET } }; typedef struct { enum { FIELD_UNSET, FIELD_STRING, FIELD_FORMAT } type; buffer *string; int field; } format_field; typedef struct { format_field **ptr; size_t used; size_t size; } format_fields; typedef struct { buffer *access_logfile; buffer *format; unsigned short use_syslog; int log_access_fd; time_t last_generated_accesslog_ts; time_t *last_generated_accesslog_ts_ptr; buffer *access_logbuffer; buffer *ts_accesslog_str; format_fields *parsed_format; } plugin_config; typedef struct { PLUGIN_DATA; plugin_config **config_storage; plugin_config conf; } plugin_data; INIT_FUNC(mod_accesslog_init) { plugin_data *p; UNUSED(srv); p = calloc(1, sizeof(*p)); return p; } static void accesslog_append_escaped(buffer *dest, buffer *str) { /* replaces non-printable chars with \xHH where HH is the hex representation of the byte */ /* exceptions: " => \", \ => \\, whitespace chars => \n \t etc. */ buffer_prepare_append(dest, str->used - 1); for (unsigned int i = 0; i < str->used - 1; i++) { if (str->ptr[i] >= ' ' && str->ptr[i] <= '~') { /* printable chars */ buffer_append_string_len(dest, &str->ptr[i], 1); } else switch (str->ptr[i]) { case '"': BUFFER_APPEND_STRING_CONST(dest, "\\\""); break; case '\\': BUFFER_APPEND_STRING_CONST(dest, "\\\\"); break; case '\b': BUFFER_APPEND_STRING_CONST(dest, "\\b"); break; case '\n': BUFFER_APPEND_STRING_CONST(dest, "\\n"); break; case '\r': BUFFER_APPEND_STRING_CONST(dest, "\\r"); break; case '\t': BUFFER_APPEND_STRING_CONST(dest, "\\t"); break; case '\v': BUFFER_APPEND_STRING_CONST(dest, "\\v"); break; default: { /* non printable char => \xHH */ char hh[5] = {'\\','x',0,0,0}; char h = str->ptr[i] / 16; hh[2] = (h > 9) ? (h - 10 + 'A') : (h + '0'); h = str->ptr[i] % 16; hh[3] = (h > 9) ? (h - 10 + 'A') : (h + '0'); buffer_append_string_len(dest, &hh[0], 4); } break; } } } static int accesslog_parse_format(server *srv, format_fields *fields, buffer *format) { size_t i, j, k = 0, start = 0; for (i = 0; i < format->used - 1; i++) { switch(format->ptr[i]) { case '%': if (start != i) { /* copy the string */ if (fields->size == 0) { fields->size = 16; fields->used = 0; fields->ptr = malloc(fields->size * sizeof(format_field * )); } else if (fields->used == fields->size) { fields->size += 16; fields->ptr = realloc(fields->ptr, fields->size * sizeof(format_field * )); } fields->ptr[fields->used] = malloc(sizeof(format_field)); fields->ptr[fields->used]->type = FIELD_STRING; fields->ptr[fields->used]->string = buffer_init(); buffer_copy_string_len(fields->ptr[fields->used]->string, format->ptr + start, i - start); fields->used++; } /* we need a new field */ if (fields->size == 0) { fields->size = 16; fields->used = 0; fields->ptr = malloc(fields->size * sizeof(format_field * )); } else if (fields->used == fields->size) { fields->size += 16; fields->ptr = realloc(fields->ptr, fields->size * sizeof(format_field * )); } /* search for the terminating command */ switch (format->ptr[i+1]) { case '>': case '<': /* only for s */ for (j = 0; fmap[j].key != '\0'; j++) { if (fmap[j].key != format->ptr[i+2]) continue; /* found key */ fields->ptr[fields->used] = malloc(sizeof(format_field)); fields->ptr[fields->used]->type = FIELD_FORMAT; fields->ptr[fields->used]->field = fmap[j].type; fields->ptr[fields->used]->string = NULL; fields->used++; break; } if (fmap[j].key == '\0') { log_error_write(srv, __FILE__, __LINE__, "ss", "config: ", "failed"); return -1; } start = i + 3; break; case '{': /* go forward to } */ for (k = i+2; k < format->used - 1; k++) { if (format->ptr[k] == '}') break; } if (k == format->used - 1) { log_error_write(srv, __FILE__, __LINE__, "ss", "config: ", "failed"); return -1; } if (format->ptr[k+1] == '\0') { log_error_write(srv, __FILE__, __LINE__, "ss", "config: ", "failed"); return -1; } for (j = 0; fmap[j].key != '\0'; j++) { if (fmap[j].key != format->ptr[k+1]) continue; /* found key */ fields->ptr[fields->used] = malloc(sizeof(format_field)); fields->ptr[fields->used]->type = FIELD_FORMAT; fields->ptr[fields->used]->field = fmap[j].type; fields->ptr[fields->used]->string = buffer_init(); buffer_copy_string_len(fields->ptr[fields->used]->string, format->ptr + i + 2, k - (i + 2)); fields->used++; break; } if (fmap[j].key == '\0') { log_error_write(srv, __FILE__, __LINE__, "ss", "config: ", "failed"); return -1; } start = k + 2; break; default: for (j = 0; fmap[j].key != '\0'; j++) { if (fmap[j].key != format->ptr[i+1]) continue; /* found key */ fields->ptr[fields->used] = malloc(sizeof(format_field)); fields->ptr[fields->used]->type = FIELD_FORMAT; fields->ptr[fields->used]->field = fmap[j].type; fields->ptr[fields->used]->string = NULL; fields->used++; break; } if (fmap[j].key == '\0') { log_error_write(srv, __FILE__, __LINE__, "ss", "config: ", "failed"); return -1; } start = i + 2; break; } break; } } if (start < i) { /* copy the string */ if (fields->size == 0) { fields->size = 16; fields->used = 0; fields->ptr = malloc(fields->size * sizeof(format_field * )); } else if (fields->used == fields->size) { fields->size += 16; fields->ptr = realloc(fields->ptr, fields->size * sizeof(format_field * )); } fields->ptr[fields->used] = malloc(sizeof(format_field)); fields->ptr[fields->used]->type = FIELD_STRING; fields->ptr[fields->used]->string = buffer_init(); buffer_copy_string_len(fields->ptr[fields->used]->string, format->ptr + start, i - start); fields->used++; } return 0; } FREE_FUNC(mod_accesslog_free) { plugin_data *p = p_d; size_t i; if (!p) return HANDLER_GO_ON; if (p->config_storage) { for (i = 0; i < srv->config_context->used; i++) { plugin_config *s = p->config_storage[i]; if (!s) continue; if (s->access_logbuffer->used) { if (s->use_syslog) { # ifdef HAVE_SYSLOG_H if (s->access_logbuffer->used > 2) { syslog(LOG_INFO, "%*s", (int) s->access_logbuffer->used - 2, s->access_logbuffer->ptr); } # endif } else if (s->log_access_fd != -1) { write(s->log_access_fd, s->access_logbuffer->ptr, s->access_logbuffer->used - 1); } } if (s->log_access_fd != -1) close(s->log_access_fd); buffer_free(s->ts_accesslog_str); buffer_free(s->access_logbuffer); buffer_free(s->format); buffer_free(s->access_logfile); if (s->parsed_format) { size_t j; for (j = 0; j < s->parsed_format->used; j++) { if (s->parsed_format->ptr[j]->string) buffer_free(s->parsed_format->ptr[j]->string); free(s->parsed_format->ptr[j]); } free(s->parsed_format->ptr); free(s->parsed_format); } free(s); } free(p->config_storage); } free(p); return HANDLER_GO_ON; } SETDEFAULTS_FUNC(log_access_open) { plugin_data *p = p_d; size_t i = 0; config_values_t cv[] = { { "accesslog.filename", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, { "accesslog.use-syslog", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, { "accesslog.format", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, { NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET } }; if (!p) return HANDLER_ERROR; p->config_storage = calloc(1, srv->config_context->used * sizeof(specific_config *)); for (i = 0; i < srv->config_context->used; i++) { plugin_config *s; s = calloc(1, sizeof(plugin_config)); s->access_logfile = buffer_init(); s->format = buffer_init(); s->access_logbuffer = buffer_init(); s->ts_accesslog_str = buffer_init(); s->log_access_fd = -1; s->last_generated_accesslog_ts = 0; s->last_generated_accesslog_ts_ptr = &(s->last_generated_accesslog_ts); cv[0].destination = s->access_logfile; cv[1].destination = &(s->use_syslog); cv[2].destination = s->format; p->config_storage[i] = s; if (0 != config_insert_values_global(srv, ((data_config *)srv->config_context->data[i])->value, cv)) { return HANDLER_ERROR; } if (i == 0 && buffer_is_empty(s->format)) { /* set a default logfile string */ buffer_copy_string_len(s->format, CONST_STR_LEN("%h %V %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"")); } /* parse */ if (s->format->used) { s->parsed_format = calloc(1, sizeof(*(s->parsed_format))); if (-1 == accesslog_parse_format(srv, s->parsed_format, s->format)) { log_error_write(srv, __FILE__, __LINE__, "sb", "parsing accesslog-definition failed:", s->format); return HANDLER_ERROR; } #if 0 /* debugging */ for (j = 0; j < s->parsed_format->used; j++) { switch (s->parsed_format->ptr[j]->type) { case FIELD_FORMAT: log_error_write(srv, __FILE__, __LINE__, "ssds", "config:", "format", s->parsed_format->ptr[j]->field, s->parsed_format->ptr[j]->string ? s->parsed_format->ptr[j]->string->ptr : "" ); break; case FIELD_STRING: log_error_write(srv, __FILE__, __LINE__, "ssbs", "config:", "string '", s->parsed_format->ptr[j]->string, "'"); break; default: break; } } #endif } if (s->use_syslog) { /* ignore the next checks */ continue; } if (buffer_is_empty(s->access_logfile)) continue; if (s->access_logfile->ptr[0] == '|') { #ifdef HAVE_FORK /* create write pipe and spawn process */ int to_log_fds[2]; pid_t pid; if (pipe(to_log_fds)) { log_error_write(srv, __FILE__, __LINE__, "ss", "pipe failed: ", strerror(errno)); return HANDLER_ERROR; } /* fork, execve */ switch (pid = fork()) { case 0: /* child */ close(STDIN_FILENO); dup2(to_log_fds[0], STDIN_FILENO); close(to_log_fds[0]); /* not needed */ close(to_log_fds[1]); /* we don't need the client socket */ for (i = 3; i < 256; i++) { close(i); } /* exec the log-process (skip the | ) * */ execl("/bin/sh", "sh", "-c", s->access_logfile->ptr + 1, (char *)NULL); log_error_write(srv, __FILE__, __LINE__, "sss", "spawning log-process failed: ", strerror(errno), s->access_logfile->ptr + 1); exit(-1); break; case -1: /* error */ log_error_write(srv, __FILE__, __LINE__, "ss", "fork failed: ", strerror(errno)); break; default: close(to_log_fds[0]); s->log_access_fd = to_log_fds[1]; break; } #else return -1; #endif } else if (-1 == (s->log_access_fd = open(s->access_logfile->ptr, O_APPEND | O_WRONLY | O_CREAT | O_LARGEFILE, 0644))) { log_error_write(srv, __FILE__, __LINE__, "ssb", "opening access-log failed:", strerror(errno), s->access_logfile); return HANDLER_ERROR; } #ifndef _WIN32 fcntl(s->log_access_fd, F_SETFD, FD_CLOEXEC); #endif } return HANDLER_GO_ON; } SIGHUP_FUNC(log_access_cycle) { plugin_data *p = p_d; size_t i; if (!p->config_storage) return HANDLER_GO_ON; for (i = 0; i < srv->config_context->used; i++) { plugin_config *s = p->config_storage[i]; if (s->access_logbuffer->used) { if (s->use_syslog) { #ifdef HAVE_SYSLOG_H if (s->access_logbuffer->used > 2) { /* syslog appends a \n on its own */ syslog(LOG_INFO, "%*s", (int) s->access_logbuffer->used - 2, s->access_logbuffer->ptr); } #endif } else if (s->log_access_fd != -1) { write(s->log_access_fd, s->access_logbuffer->ptr, s->access_logbuffer->used - 1); } buffer_reset(s->access_logbuffer); } if (s->use_syslog == 0 && !buffer_is_empty(s->access_logfile) && s->access_logfile->ptr[0] != '|') { close(s->log_access_fd); if (-1 == (s->log_access_fd = open(s->access_logfile->ptr, O_APPEND | O_WRONLY | O_CREAT | O_LARGEFILE, 0644))) { log_error_write(srv, __FILE__, __LINE__, "ss", "cycling access-log failed:", strerror(errno)); return HANDLER_ERROR; } } } return HANDLER_GO_ON; } static int mod_accesslog_patch_connection(server *srv, connection *con, plugin_data *p) { size_t i, j; plugin_config *s = p->config_storage[0]; PATCH_OPTION(access_logfile); PATCH_OPTION(format); PATCH_OPTION(log_access_fd); PATCH_OPTION(last_generated_accesslog_ts_ptr); PATCH_OPTION(access_logbuffer); PATCH_OPTION(ts_accesslog_str); PATCH_OPTION(parsed_format); PATCH_OPTION(use_syslog); /* skip the first, the global context */ for (i = 1; i < srv->config_context->used; i++) { data_config *dc = (data_config *)srv->config_context->data[i]; s = p->config_storage[i]; /* condition didn't match */ if (!config_check_cond(srv, con, dc)) continue; /* merge config */ for (j = 0; j < dc->value->used; j++) { data_unset *du = dc->value->data[j]; if (buffer_is_equal_string(du->key, CONST_STR_LEN("accesslog.filename"))) { PATCH_OPTION(access_logfile); PATCH_OPTION(log_access_fd); PATCH_OPTION(last_generated_accesslog_ts_ptr); PATCH_OPTION(access_logbuffer); PATCH_OPTION(ts_accesslog_str); } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("accesslog.format"))) { PATCH_OPTION(format); PATCH_OPTION(parsed_format); } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("accesslog.use-syslog"))) { PATCH_OPTION(use_syslog); } } } return 0; } REQUESTDONE_FUNC(log_access_write) { plugin_data *p = p_d; buffer *b; size_t j; int newts = 0; data_string *ds; mod_accesslog_patch_connection(srv, con, p); b = p->conf.access_logbuffer; if (b->used == 0) { buffer_copy_string_len(b, CONST_STR_LEN("")); } for (j = 0; j < p->conf.parsed_format->used; j++) { switch(p->conf.parsed_format->ptr[j]->type) { case FIELD_STRING: buffer_append_string_buffer(b, p->conf.parsed_format->ptr[j]->string); break; case FIELD_FORMAT: switch(p->conf.parsed_format->ptr[j]->field) { case FORMAT_TIMESTAMP: /* cache the generated timestamp */ if (srv->cur_ts != *(p->conf.last_generated_accesslog_ts_ptr)) { struct tm tm; #if defined(HAVE_STRUCT_TM_GMTOFF) long scd, hrs, min; #endif buffer_prepare_copy(p->conf.ts_accesslog_str, 255); #if defined(HAVE_STRUCT_TM_GMTOFF) # ifdef HAVE_LOCALTIME_R localtime_r(&(srv->cur_ts), &tm); strftime(p->conf.ts_accesslog_str->ptr, p->conf.ts_accesslog_str->size - 1, "[%d/%b/%Y:%H:%M:%S ", &tm); # else strftime(p->conf.ts_accesslog_str->ptr, p->conf.ts_accesslog_str->size - 1, "[%d/%b/%Y:%H:%M:%S ", localtime(&(srv->cur_ts))); # endif p->conf.ts_accesslog_str->used = strlen(p->conf.ts_accesslog_str->ptr) + 1; buffer_append_string(p->conf.ts_accesslog_str, tm.tm_gmtoff >= 0 ? "+" : "-"); scd = abs(tm.tm_gmtoff); hrs = scd / 3600; min = (scd % 3600) / 60; /* hours */ if (hrs < 10) buffer_append_string_len(p->conf.ts_accesslog_str, CONST_STR_LEN("0")); buffer_append_long(p->conf.ts_accesslog_str, hrs); if (min < 10) buffer_append_string_len(p->conf.ts_accesslog_str, CONST_STR_LEN("0")); buffer_append_long(p->conf.ts_accesslog_str, min); buffer_append_string_len(p->conf.ts_accesslog_str, CONST_STR_LEN("]")); #else #ifdef HAVE_GMTIME_R gmtime_r(&(srv->cur_ts), &tm); strftime(p->conf.ts_accesslog_str->ptr, p->conf.ts_accesslog_str->size - 1, "[%d/%b/%Y:%H:%M:%S +0000]", &tm); #else strftime(p->conf.ts_accesslog_str->ptr, p->conf.ts_accesslog_str->size - 1, "[%d/%b/%Y:%H:%M:%S +0000]", gmtime(&(srv->cur_ts))); #endif p->conf.ts_accesslog_str->used = strlen(p->conf.ts_accesslog_str->ptr) + 1; #endif *(p->conf.last_generated_accesslog_ts_ptr) = srv->cur_ts; newts = 1; } buffer_append_string_buffer(b, p->conf.ts_accesslog_str); break; case FORMAT_REMOTE_HOST: /* handle inet_ntop cache */ buffer_append_string(b, inet_ntop_cache_get_ip(srv, &(con->dst_addr))); break; case FORMAT_REMOTE_IDENT: /* ident */ buffer_append_string_len(b, CONST_STR_LEN("-")); break; case FORMAT_REMOTE_USER: if (con->authed_user->used > 1) { buffer_append_string_buffer(b, con->authed_user); } else { buffer_append_string_len(b, CONST_STR_LEN("-")); } break; case FORMAT_REQUEST_LINE: buffer_append_string(b, get_http_method_name(con->request.http_method)); buffer_append_string_len(b, CONST_STR_LEN(" ")); accesslog_append_escaped(b, con->request.orig_uri); buffer_append_string_len(b, CONST_STR_LEN(" ")); buffer_append_string(b, get_http_version_name(con->request.http_version)); break; case FORMAT_STATUS: buffer_append_long(b, con->http_status); break; case FORMAT_BYTES_OUT_NO_HEADER: if (con->bytes_written > 0) { buffer_append_off_t(b, con->bytes_written - con->bytes_header <= 0 ? 0 : con->bytes_written - con->bytes_header); } else { buffer_append_string_len(b, CONST_STR_LEN("-")); } break; case FORMAT_HEADER: if (NULL != (ds = (data_string *)array_get_element(con->request.headers, CONST_BUF_LEN(p->conf.parsed_format->ptr[j]->string)))) { accesslog_append_escaped(b, ds->value); } else { buffer_append_string_len(b, CONST_STR_LEN("-")); } break; case FORMAT_RESPONSE_HEADER: if (NULL != (ds = (data_string *)array_get_element(con->response.headers, CONST_BUF_LEN(p->conf.parsed_format->ptr[j]->string)))) { accesslog_append_escaped(b, ds->value); } else { buffer_append_string_len(b, CONST_STR_LEN("-")); } break; case FORMAT_FILENAME: if (con->physical.path->used > 1) { buffer_append_string_buffer(b, con->physical.path); } else { buffer_append_string_len(b, CONST_STR_LEN("-")); } break; case FORMAT_BYTES_OUT: if (con->bytes_written > 0) { buffer_append_off_t(b, con->bytes_written); } else { buffer_append_string_len(b, CONST_STR_LEN("-")); } break; case FORMAT_BYTES_IN: if (con->bytes_read > 0) { buffer_append_off_t(b, con->bytes_read); } else { buffer_append_string_len(b, CONST_STR_LEN("-")); } break; case FORMAT_TIME_USED: buffer_append_long(b, srv->cur_ts - con->request_start); break; case FORMAT_SERVER_NAME: if (con->server_name->used > 1) { buffer_append_string_buffer(b, con->server_name); } else { buffer_append_string_len(b, CONST_STR_LEN("-")); } break; case FORMAT_HTTP_HOST: if (con->uri.authority->used > 1) { accesslog_append_escaped(b, con->uri.authority); } else { buffer_append_string_len(b, CONST_STR_LEN("-")); } break; case FORMAT_REQUEST_PROTOCOL: buffer_append_string(b, con->request.http_version == HTTP_VERSION_1_1 ? "HTTP/1.1" : "HTTP/1.0"); break; case FORMAT_REQUEST_METHOD: buffer_append_string(b, get_http_method_name(con->request.http_method)); break; case FORMAT_SERVER_PORT: buffer_append_long(b, srv->srvconf.port); break; case FORMAT_QUERY_STRING: accesslog_append_escaped(b, con->uri.query); break; case FORMAT_URL: accesslog_append_escaped(b, con->uri.path_raw); break; case FORMAT_CONNECTION_STATUS: switch(con->keep_alive) { case 0: buffer_append_string_len(b, CONST_STR_LEN("-")); break; default: buffer_append_string_len(b, CONST_STR_LEN("+")); break; } break; default: /* { 'a', FORMAT_REMOTE_ADDR }, { 'A', FORMAT_LOCAL_ADDR }, { 'C', FORMAT_COOKIE }, { 'D', FORMAT_TIME_USED_MS }, { 'e', FORMAT_ENV }, */ break; } break; default: break; } } buffer_append_string_len(b, CONST_STR_LEN("\n")); if (p->conf.use_syslog || /* syslog doesn't cache */ (p->conf.access_logfile->used && p->conf.access_logfile->ptr[0] != '|') || /* pipes don't cache */ newts || b->used > BUFFER_MAX_REUSE_SIZE) { if (p->conf.use_syslog) { #ifdef HAVE_SYSLOG_H if (b->used > 2) { /* syslog appends a \n on its own */ syslog(LOG_INFO, "%*s", (int) b->used - 2, b->ptr); } #endif } else if (p->conf.log_access_fd != -1) { write(p->conf.log_access_fd, b->ptr, b->used - 1); } buffer_reset(b); } return HANDLER_GO_ON; } LI_EXPORT int mod_accesslog_plugin_init(plugin *p); LI_EXPORT int mod_accesslog_plugin_init(plugin *p) { p->version = LIGHTTPD_VERSION_ID; p->name = buffer_init_string("accesslog"); p->init = mod_accesslog_init; p->set_defaults= log_access_open; p->cleanup = mod_accesslog_free; p->handle_response_done = log_access_write; p->handle_sighup = log_access_cycle; p->data = NULL; return 0; } /* * make sure _GNU_SOURCE is defined */ #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <sys/types.h> #include <sys/stat.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> /* only the defines on windows */ #include <errno.h> #include <time.h> #include <stdio.h> #include "base.h" #include "log.h" #include "buffer.h" #include "plugin.h" #include "inet_ntop_cache.h" #include "sys-socket.h" #include "sys-files.h" #ifdef HAVE_SYSLOG_H # include <syslog.h> #endif typedef struct { char key; enum { FORMAT_UNSET, FORMAT_UNSUPPORTED, FORMAT_PERCENT, FORMAT_REMOTE_HOST, FORMAT_REMOTE_IDENT, FORMAT_REMOTE_USER, FORMAT_TIMESTAMP, FORMAT_REQUEST_LINE, FORMAT_STATUS, FORMAT_BYTES_OUT_NO_HEADER, FORMAT_HEADER, FORMAT_REMOTE_ADDR, FORMAT_LOCAL_ADDR, FORMAT_COOKIE, FORMAT_TIME_USED_MS, FORMAT_ENV, FORMAT_FILENAME, FORMAT_REQUEST_PROTOCOL, FORMAT_REQUEST_METHOD, FORMAT_SERVER_PORT, FORMAT_QUERY_STRING, FORMAT_TIME_USED, FORMAT_URL, FORMAT_SERVER_NAME, FORMAT_HTTP_HOST, FORMAT_CONNECTION_STATUS, FORMAT_BYTES_IN, FORMAT_BYTES_OUT, FORMAT_RESPONSE_HEADER } type; } format_mapping; /** * * * "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" * */ const format_mapping fmap[] = { { '%', FORMAT_PERCENT }, { 'h', FORMAT_REMOTE_HOST }, { 'l', FORMAT_REMOTE_IDENT }, { 'u', FORMAT_REMOTE_USER }, { 't', FORMAT_TIMESTAMP }, { 'r', FORMAT_REQUEST_LINE }, { 's', FORMAT_STATUS }, { 'b', FORMAT_BYTES_OUT_NO_HEADER }, { 'i', FORMAT_HEADER }, { 'a', FORMAT_REMOTE_ADDR }, { 'A', FORMAT_LOCAL_ADDR }, { 'B', FORMAT_BYTES_OUT_NO_HEADER }, { 'C', FORMAT_COOKIE }, { 'D', FORMAT_TIME_USED_MS }, { 'e', FORMAT_ENV }, { 'f', FORMAT_FILENAME }, { 'H', FORMAT_REQUEST_PROTOCOL }, { 'm', FORMAT_REQUEST_METHOD }, { 'n', FORMAT_UNSUPPORTED }, /* we have no notes */ { 'p', FORMAT_SERVER_PORT }, { 'P', FORMAT_UNSUPPORTED }, /* we are only one process */ { 'q', FORMAT_QUERY_STRING }, { 'T', FORMAT_TIME_USED }, { 'U', FORMAT_URL }, /* w/o querystring */ { 'v', FORMAT_SERVER_NAME }, { 'V', FORMAT_HTTP_HOST }, { 'X', FORMAT_CONNECTION_STATUS }, { 'I', FORMAT_BYTES_IN }, { 'O', FORMAT_BYTES_OUT }, { 'o', FORMAT_RESPONSE_HEADER }, { '\0', FORMAT_UNSET } }; typedef struct { enum { FIELD_UNSET, FIELD_STRING, FIELD_FORMAT } type; buffer *string; int field; } format_field; typedef struct { format_field **ptr; size_t used; size_t size; } format_fields; typedef struct { buffer *access_logfile; buffer *format; unsigned short use_syslog; int log_access_fd; time_t last_generated_accesslog_ts; time_t *last_generated_accesslog_ts_ptr; buffer *access_logbuffer; buffer *ts_accesslog_str; format_fields *parsed_format; } plugin_config; typedef struct { PLUGIN_DATA; plugin_config **config_storage; plugin_config conf; } plugin_data; INIT_FUNC(mod_accesslog_init) { plugin_data *p; UNUSED(srv); p = calloc(1, sizeof(*p)); return p; } static void accesslog_append_escaped(buffer *dest, buffer *str) { /* replaces non-printable chars with \xHH where HH is the hex representation of the byte */ /* exceptions: " => \", \ => \\, whitespace chars => \n \t etc. */ if (str->used == 0) return; buffer_prepare_append(dest, str->used - 1); for (unsigned int i = 0; i < str->used - 1; i++) { if (str->ptr[i] >= ' ' && str->ptr[i] <= '~') { /* printable chars */ buffer_append_string_len(dest, &str->ptr[i], 1); } else switch (str->ptr[i]) { case '"': BUFFER_APPEND_STRING_CONST(dest, "\\\""); break; case '\\': BUFFER_APPEND_STRING_CONST(dest, "\\\\"); break; case '\b': BUFFER_APPEND_STRING_CONST(dest, "\\b"); break; case '\n': BUFFER_APPEND_STRING_CONST(dest, "\\n"); break; case '\r': BUFFER_APPEND_STRING_CONST(dest, "\\r"); break; case '\t': BUFFER_APPEND_STRING_CONST(dest, "\\t"); break; case '\v': BUFFER_APPEND_STRING_CONST(dest, "\\v"); break; default: { /* non printable char => \xHH */ char hh[5] = {'\\','x',0,0,0}; char h = str->ptr[i] / 16; hh[2] = (h > 9) ? (h - 10 + 'A') : (h + '0'); h = str->ptr[i] % 16; hh[3] = (h > 9) ? (h - 10 + 'A') : (h + '0'); buffer_append_string_len(dest, &hh[0], 4); } break; } } } static int accesslog_parse_format(server *srv, format_fields *fields, buffer *format) { size_t i, j, k = 0, start = 0; for (i = 0; i < format->used - 1; i++) { switch(format->ptr[i]) { case '%': if (start != i) { /* copy the string */ if (fields->size == 0) { fields->size = 16; fields->used = 0; fields->ptr = malloc(fields->size * sizeof(format_field * )); } else if (fields->used == fields->size) { fields->size += 16; fields->ptr = realloc(fields->ptr, fields->size * sizeof(format_field * )); } fields->ptr[fields->used] = malloc(sizeof(format_field)); fields->ptr[fields->used]->type = FIELD_STRING; fields->ptr[fields->used]->string = buffer_init(); buffer_copy_string_len(fields->ptr[fields->used]->string, format->ptr + start, i - start); fields->used++; } /* we need a new field */ if (fields->size == 0) { fields->size = 16; fields->used = 0; fields->ptr = malloc(fields->size * sizeof(format_field * )); } else if (fields->used == fields->size) { fields->size += 16; fields->ptr = realloc(fields->ptr, fields->size * sizeof(format_field * )); } /* search for the terminating command */ switch (format->ptr[i+1]) { case '>': case '<': /* only for s */ for (j = 0; fmap[j].key != '\0'; j++) { if (fmap[j].key != format->ptr[i+2]) continue; /* found key */ fields->ptr[fields->used] = malloc(sizeof(format_field)); fields->ptr[fields->used]->type = FIELD_FORMAT; fields->ptr[fields->used]->field = fmap[j].type; fields->ptr[fields->used]->string = NULL; fields->used++; break; } if (fmap[j].key == '\0') { log_error_write(srv, __FILE__, __LINE__, "ss", "config: ", "failed"); return -1; } start = i + 3; break; case '{': /* go forward to } */ for (k = i+2; k < format->used - 1; k++) { if (format->ptr[k] == '}') break; } if (k == format->used - 1) { log_error_write(srv, __FILE__, __LINE__, "ss", "config: ", "failed"); return -1; } if (format->ptr[k+1] == '\0') { log_error_write(srv, __FILE__, __LINE__, "ss", "config: ", "failed"); return -1; } for (j = 0; fmap[j].key != '\0'; j++) { if (fmap[j].key != format->ptr[k+1]) continue; /* found key */ fields->ptr[fields->used] = malloc(sizeof(format_field)); fields->ptr[fields->used]->type = FIELD_FORMAT; fields->ptr[fields->used]->field = fmap[j].type; fields->ptr[fields->used]->string = buffer_init(); buffer_copy_string_len(fields->ptr[fields->used]->string, format->ptr + i + 2, k - (i + 2)); fields->used++; break; } if (fmap[j].key == '\0') { log_error_write(srv, __FILE__, __LINE__, "ss", "config: ", "failed"); return -1; } start = k + 2; break; default: for (j = 0; fmap[j].key != '\0'; j++) { if (fmap[j].key != format->ptr[i+1]) continue; /* found key */ fields->ptr[fields->used] = malloc(sizeof(format_field)); fields->ptr[fields->used]->type = FIELD_FORMAT; fields->ptr[fields->used]->field = fmap[j].type; fields->ptr[fields->used]->string = NULL; fields->used++; break; } if (fmap[j].key == '\0') { log_error_write(srv, __FILE__, __LINE__, "ss", "config: ", "failed"); return -1; } start = i + 2; break; } break; } } if (start < i) { /* copy the string */ if (fields->size == 0) { fields->size = 16; fields->used = 0; fields->ptr = malloc(fields->size * sizeof(format_field * )); } else if (fields->used == fields->size) { fields->size += 16; fields->ptr = realloc(fields->ptr, fields->size * sizeof(format_field * )); } fields->ptr[fields->used] = malloc(sizeof(format_field)); fields->ptr[fields->used]->type = FIELD_STRING; fields->ptr[fields->used]->string = buffer_init(); buffer_copy_string_len(fields->ptr[fields->used]->string, format->ptr + start, i - start); fields->used++; } return 0; } FREE_FUNC(mod_accesslog_free) { plugin_data *p = p_d; size_t i; if (!p) return HANDLER_GO_ON; if (p->config_storage) { for (i = 0; i < srv->config_context->used; i++) { plugin_config *s = p->config_storage[i]; if (!s) continue; if (s->access_logbuffer->used) { if (s->use_syslog) { # ifdef HAVE_SYSLOG_H if (s->access_logbuffer->used > 2) { syslog(LOG_INFO, "%*s", (int) s->access_logbuffer->used - 2, s->access_logbuffer->ptr); } # endif } else if (s->log_access_fd != -1) { write(s->log_access_fd, s->access_logbuffer->ptr, s->access_logbuffer->used - 1); } } if (s->log_access_fd != -1) close(s->log_access_fd); buffer_free(s->ts_accesslog_str); buffer_free(s->access_logbuffer); buffer_free(s->format); buffer_free(s->access_logfile); if (s->parsed_format) { size_t j; for (j = 0; j < s->parsed_format->used; j++) { if (s->parsed_format->ptr[j]->string) buffer_free(s->parsed_format->ptr[j]->string); free(s->parsed_format->ptr[j]); } free(s->parsed_format->ptr); free(s->parsed_format); } free(s); } free(p->config_storage); } free(p); return HANDLER_GO_ON; } SETDEFAULTS_FUNC(log_access_open) { plugin_data *p = p_d; size_t i = 0; config_values_t cv[] = { { "accesslog.filename", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, { "accesslog.use-syslog", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, { "accesslog.format", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, { NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET } }; if (!p) return HANDLER_ERROR; p->config_storage = calloc(1, srv->config_context->used * sizeof(specific_config *)); for (i = 0; i < srv->config_context->used; i++) { plugin_config *s; s = calloc(1, sizeof(plugin_config)); s->access_logfile = buffer_init(); s->format = buffer_init(); s->access_logbuffer = buffer_init(); s->ts_accesslog_str = buffer_init(); s->log_access_fd = -1; s->last_generated_accesslog_ts = 0; s->last_generated_accesslog_ts_ptr = &(s->last_generated_accesslog_ts); cv[0].destination = s->access_logfile; cv[1].destination = &(s->use_syslog); cv[2].destination = s->format; p->config_storage[i] = s; if (0 != config_insert_values_global(srv, ((data_config *)srv->config_context->data[i])->value, cv)) { return HANDLER_ERROR; } if (i == 0 && buffer_is_empty(s->format)) { /* set a default logfile string */ buffer_copy_string_len(s->format, CONST_STR_LEN("%h %V %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"")); } /* parse */ if (s->format->used) { s->parsed_format = calloc(1, sizeof(*(s->parsed_format))); if (-1 == accesslog_parse_format(srv, s->parsed_format, s->format)) { log_error_write(srv, __FILE__, __LINE__, "sb", "parsing accesslog-definition failed:", s->format); return HANDLER_ERROR; } #if 0 /* debugging */ for (j = 0; j < s->parsed_format->used; j++) { switch (s->parsed_format->ptr[j]->type) { case FIELD_FORMAT: log_error_write(srv, __FILE__, __LINE__, "ssds", "config:", "format", s->parsed_format->ptr[j]->field, s->parsed_format->ptr[j]->string ? s->parsed_format->ptr[j]->string->ptr : "" ); break; case FIELD_STRING: log_error_write(srv, __FILE__, __LINE__, "ssbs", "config:", "string '", s->parsed_format->ptr[j]->string, "'"); break; default: break; } } #endif } if (s->use_syslog) { /* ignore the next checks */ continue; } if (buffer_is_empty(s->access_logfile)) continue; if (s->access_logfile->ptr[0] == '|') { #ifdef HAVE_FORK /* create write pipe and spawn process */ int to_log_fds[2]; pid_t pid; if (pipe(to_log_fds)) { log_error_write(srv, __FILE__, __LINE__, "ss", "pipe failed: ", strerror(errno)); return HANDLER_ERROR; } /* fork, execve */ switch (pid = fork()) { case 0: /* child */ close(STDIN_FILENO); dup2(to_log_fds[0], STDIN_FILENO); close(to_log_fds[0]); /* not needed */ close(to_log_fds[1]); /* we don't need the client socket */ for (i = 3; i < 256; i++) { close(i); } /* exec the log-process (skip the | ) * */ execl("/bin/sh", "sh", "-c", s->access_logfile->ptr + 1, (char *)NULL); log_error_write(srv, __FILE__, __LINE__, "sss", "spawning log-process failed: ", strerror(errno), s->access_logfile->ptr + 1); exit(-1); break; case -1: /* error */ log_error_write(srv, __FILE__, __LINE__, "ss", "fork failed: ", strerror(errno)); break; default: close(to_log_fds[0]); s->log_access_fd = to_log_fds[1]; break; } #else return -1; #endif } else if (-1 == (s->log_access_fd = open(s->access_logfile->ptr, O_APPEND | O_WRONLY | O_CREAT | O_LARGEFILE, 0644))) { log_error_write(srv, __FILE__, __LINE__, "ssb", "opening access-log failed:", strerror(errno), s->access_logfile); return HANDLER_ERROR; } #ifndef _WIN32 fcntl(s->log_access_fd, F_SETFD, FD_CLOEXEC); #endif } return HANDLER_GO_ON; } SIGHUP_FUNC(log_access_cycle) { plugin_data *p = p_d; size_t i; if (!p->config_storage) return HANDLER_GO_ON; for (i = 0; i < srv->config_context->used; i++) { plugin_config *s = p->config_storage[i]; if (s->access_logbuffer->used) { if (s->use_syslog) { #ifdef HAVE_SYSLOG_H if (s->access_logbuffer->used > 2) { /* syslog appends a \n on its own */ syslog(LOG_INFO, "%*s", (int) s->access_logbuffer->used - 2, s->access_logbuffer->ptr); } #endif } else if (s->log_access_fd != -1) { write(s->log_access_fd, s->access_logbuffer->ptr, s->access_logbuffer->used - 1); } buffer_reset(s->access_logbuffer); } if (s->use_syslog == 0 && !buffer_is_empty(s->access_logfile) && s->access_logfile->ptr[0] != '|') { close(s->log_access_fd); if (-1 == (s->log_access_fd = open(s->access_logfile->ptr, O_APPEND | O_WRONLY | O_CREAT | O_LARGEFILE, 0644))) { log_error_write(srv, __FILE__, __LINE__, "ss", "cycling access-log failed:", strerror(errno)); return HANDLER_ERROR; } } } return HANDLER_GO_ON; } static int mod_accesslog_patch_connection(server *srv, connection *con, plugin_data *p) { size_t i, j; plugin_config *s = p->config_storage[0]; PATCH_OPTION(access_logfile); PATCH_OPTION(format); PATCH_OPTION(log_access_fd); PATCH_OPTION(last_generated_accesslog_ts_ptr); PATCH_OPTION(access_logbuffer); PATCH_OPTION(ts_accesslog_str); PATCH_OPTION(parsed_format); PATCH_OPTION(use_syslog); /* skip the first, the global context */ for (i = 1; i < srv->config_context->used; i++) { data_config *dc = (data_config *)srv->config_context->data[i]; s = p->config_storage[i]; /* condition didn't match */ if (!config_check_cond(srv, con, dc)) continue; /* merge config */ for (j = 0; j < dc->value->used; j++) { data_unset *du = dc->value->data[j]; if (buffer_is_equal_string(du->key, CONST_STR_LEN("accesslog.filename"))) { PATCH_OPTION(access_logfile); PATCH_OPTION(log_access_fd); PATCH_OPTION(last_generated_accesslog_ts_ptr); PATCH_OPTION(access_logbuffer); PATCH_OPTION(ts_accesslog_str); } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("accesslog.format"))) { PATCH_OPTION(format); PATCH_OPTION(parsed_format); } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("accesslog.use-syslog"))) { PATCH_OPTION(use_syslog); } } } return 0; } REQUESTDONE_FUNC(log_access_write) { plugin_data *p = p_d; buffer *b; size_t j; int newts = 0; data_string *ds; mod_accesslog_patch_connection(srv, con, p); b = p->conf.access_logbuffer; if (b->used == 0) { buffer_copy_string_len(b, CONST_STR_LEN("")); } for (j = 0; j < p->conf.parsed_format->used; j++) { switch(p->conf.parsed_format->ptr[j]->type) { case FIELD_STRING: buffer_append_string_buffer(b, p->conf.parsed_format->ptr[j]->string); break; case FIELD_FORMAT: switch(p->conf.parsed_format->ptr[j]->field) { case FORMAT_TIMESTAMP: /* cache the generated timestamp */ if (srv->cur_ts != *(p->conf.last_generated_accesslog_ts_ptr)) { struct tm tm; #if defined(HAVE_STRUCT_TM_GMTOFF) long scd, hrs, min; #endif buffer_prepare_copy(p->conf.ts_accesslog_str, 255); #if defined(HAVE_STRUCT_TM_GMTOFF) # ifdef HAVE_LOCALTIME_R localtime_r(&(srv->cur_ts), &tm); strftime(p->conf.ts_accesslog_str->ptr, p->conf.ts_accesslog_str->size - 1, "[%d/%b/%Y:%H:%M:%S ", &tm); # else strftime(p->conf.ts_accesslog_str->ptr, p->conf.ts_accesslog_str->size - 1, "[%d/%b/%Y:%H:%M:%S ", localtime(&(srv->cur_ts))); # endif p->conf.ts_accesslog_str->used = strlen(p->conf.ts_accesslog_str->ptr) + 1; buffer_append_string(p->conf.ts_accesslog_str, tm.tm_gmtoff >= 0 ? "+" : "-"); scd = abs(tm.tm_gmtoff); hrs = scd / 3600; min = (scd % 3600) / 60; /* hours */ if (hrs < 10) buffer_append_string_len(p->conf.ts_accesslog_str, CONST_STR_LEN("0")); buffer_append_long(p->conf.ts_accesslog_str, hrs); if (min < 10) buffer_append_string_len(p->conf.ts_accesslog_str, CONST_STR_LEN("0")); buffer_append_long(p->conf.ts_accesslog_str, min); buffer_append_string_len(p->conf.ts_accesslog_str, CONST_STR_LEN("]")); #else #ifdef HAVE_GMTIME_R gmtime_r(&(srv->cur_ts), &tm); strftime(p->conf.ts_accesslog_str->ptr, p->conf.ts_accesslog_str->size - 1, "[%d/%b/%Y:%H:%M:%S +0000]", &tm); #else strftime(p->conf.ts_accesslog_str->ptr, p->conf.ts_accesslog_str->size - 1, "[%d/%b/%Y:%H:%M:%S +0000]", gmtime(&(srv->cur_ts))); #endif p->conf.ts_accesslog_str->used = strlen(p->conf.ts_accesslog_str->ptr) + 1; #endif *(p->conf.last_generated_accesslog_ts_ptr) = srv->cur_ts; newts = 1; } buffer_append_string_buffer(b, p->conf.ts_accesslog_str); break; case FORMAT_REMOTE_HOST: /* handle inet_ntop cache */ buffer_append_string(b, inet_ntop_cache_get_ip(srv, &(con->dst_addr))); break; case FORMAT_REMOTE_IDENT: /* ident */ buffer_append_string_len(b, CONST_STR_LEN("-")); break; case FORMAT_REMOTE_USER: if (con->authed_user->used > 1) { buffer_append_string_buffer(b, con->authed_user); } else { buffer_append_string_len(b, CONST_STR_LEN("-")); } break; case FORMAT_REQUEST_LINE: buffer_append_string(b, get_http_method_name(con->request.http_method)); buffer_append_string_len(b, CONST_STR_LEN(" ")); accesslog_append_escaped(b, con->request.orig_uri); buffer_append_string_len(b, CONST_STR_LEN(" ")); buffer_append_string(b, get_http_version_name(con->request.http_version)); break; case FORMAT_STATUS: buffer_append_long(b, con->http_status); break; case FORMAT_BYTES_OUT_NO_HEADER: if (con->bytes_written > 0) { buffer_append_off_t(b, con->bytes_written - con->bytes_header <= 0 ? 0 : con->bytes_written - con->bytes_header); } else { buffer_append_string_len(b, CONST_STR_LEN("-")); } break; case FORMAT_HEADER: if (NULL != (ds = (data_string *)array_get_element(con->request.headers, CONST_BUF_LEN(p->conf.parsed_format->ptr[j]->string)))) { accesslog_append_escaped(b, ds->value); } else { buffer_append_string_len(b, CONST_STR_LEN("-")); } break; case FORMAT_RESPONSE_HEADER: if (NULL != (ds = (data_string *)array_get_element(con->response.headers, CONST_BUF_LEN(p->conf.parsed_format->ptr[j]->string)))) { accesslog_append_escaped(b, ds->value); } else { buffer_append_string_len(b, CONST_STR_LEN("-")); } break; case FORMAT_FILENAME: if (con->physical.path->used > 1) { buffer_append_string_buffer(b, con->physical.path); } else { buffer_append_string_len(b, CONST_STR_LEN("-")); } break; case FORMAT_BYTES_OUT: if (con->bytes_written > 0) { buffer_append_off_t(b, con->bytes_written); } else { buffer_append_string_len(b, CONST_STR_LEN("-")); } break; case FORMAT_BYTES_IN: if (con->bytes_read > 0) { buffer_append_off_t(b, con->bytes_read); } else { buffer_append_string_len(b, CONST_STR_LEN("-")); } break; case FORMAT_TIME_USED: buffer_append_long(b, srv->cur_ts - con->request_start); break; case FORMAT_SERVER_NAME: if (con->server_name->used > 1) { buffer_append_string_buffer(b, con->server_name); } else { buffer_append_string_len(b, CONST_STR_LEN("-")); } break; case FORMAT_HTTP_HOST: if (con->uri.authority->used > 1) { accesslog_append_escaped(b, con->uri.authority); } else { buffer_append_string_len(b, CONST_STR_LEN("-")); } break; case FORMAT_REQUEST_PROTOCOL: buffer_append_string(b, con->request.http_version == HTTP_VERSION_1_1 ? "HTTP/1.1" : "HTTP/1.0"); break; case FORMAT_REQUEST_METHOD: buffer_append_string(b, get_http_method_name(con->request.http_method)); break; case FORMAT_SERVER_PORT: buffer_append_long(b, srv->srvconf.port); break; case FORMAT_QUERY_STRING: accesslog_append_escaped(b, con->uri.query); break; case FORMAT_URL: accesslog_append_escaped(b, con->uri.path_raw); break; case FORMAT_CONNECTION_STATUS: switch(con->keep_alive) { case 0: buffer_append_string_len(b, CONST_STR_LEN("-")); break; default: buffer_append_string_len(b, CONST_STR_LEN("+")); break; } break; default: /* { 'a', FORMAT_REMOTE_ADDR }, { 'A', FORMAT_LOCAL_ADDR }, { 'C', FORMAT_COOKIE }, { 'D', FORMAT_TIME_USED_MS }, { 'e', FORMAT_ENV }, */ break; } break; default: break; } } buffer_append_string_len(b, CONST_STR_LEN("\n")); if (p->conf.use_syslog || /* syslog doesn't cache */ (p->conf.access_logfile->used && p->conf.access_logfile->ptr[0] != '|') || /* pipes don't cache */ newts || b->used > BUFFER_MAX_REUSE_SIZE) { if (p->conf.use_syslog) { #ifdef HAVE_SYSLOG_H if (b->used > 2) { /* syslog appends a \n on its own */ syslog(LOG_INFO, "%*s", (int) b->used - 2, b->ptr); } #endif } else if (p->conf.log_access_fd != -1) { write(p->conf.log_access_fd, b->ptr, b->used - 1); } buffer_reset(b); } return HANDLER_GO_ON; } LI_EXPORT int mod_accesslog_plugin_init(plugin *p); LI_EXPORT int mod_accesslog_plugin_init(plugin *p) { p->version = LIGHTTPD_VERSION_ID; p->name = buffer_init_string("accesslog"); p->init = mod_accesslog_init; p->set_defaults= log_access_open; p->cleanup = mod_accesslog_free; p->handle_response_done = log_access_write; p->handle_sighup = log_access_cycle; p->data = NULL; return 0; }
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/lighttpd_2661-2662.c
manybugs_data_7
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Christian Seiler <[email protected]> | | Dmitry Stogov <[email protected]> | | Marcus Boerger <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "zend.h" #include "zend_API.h" #include "zend_closures.h" #include "zend_exceptions.h" #include "zend_interfaces.h" #include "zend_objects.h" #include "zend_objects_API.h" #include "zend_globals.h" #define ZEND_CLOSURE_PRINT_NAME "Closure object" #define ZEND_CLOSURE_PROPERTY_ERROR() \ zend_error(E_RECOVERABLE_ERROR, "Closure object cannot have properties") typedef struct _zend_closure { zend_object std; zend_function func; zval *this_ptr; HashTable *debug_info; } zend_closure; /* non-static since it needs to be referenced */ ZEND_API zend_class_entry *zend_ce_closure; static zend_object_handlers closure_handlers; ZEND_METHOD(Closure, __invoke) /* {{{ */ { zend_function *func = EG(current_execute_data)->function_state.function; zval ***arguments; zval *closure_result_ptr = NULL; arguments = emalloc(sizeof(zval**) * ZEND_NUM_ARGS()); if (zend_get_parameters_array_ex(ZEND_NUM_ARGS(), arguments) == FAILURE) { efree(arguments); zend_error(E_RECOVERABLE_ERROR, "Cannot get arguments for calling closure"); RETVAL_FALSE; } else if (call_user_function_ex(CG(function_table), NULL, this_ptr, &closure_result_ptr, ZEND_NUM_ARGS(), arguments, 1, NULL TSRMLS_CC) == FAILURE) { RETVAL_FALSE; } else if (closure_result_ptr) { if (Z_ISREF_P(closure_result_ptr) && return_value_ptr) { if (return_value) { zval_ptr_dtor(&return_value); } *return_value_ptr = closure_result_ptr; } else { RETVAL_ZVAL(closure_result_ptr, 1, 1); } } efree(arguments); /* destruct the function also, then - we have allocated it in get_method */ efree(func->internal_function.function_name); efree(func); } /* }}} */ /* {{{ proto Closure Closure::bindTo(object $to) Bind a closure to another object */ ZEND_METHOD(Closure, bindTo) /* {{{ */ { zval *newthis; zend_closure *closure = (zend_closure *)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "o!", &newthis) == FAILURE) { RETURN_NULL(); } zend_create_closure(return_value, &closure->func, newthis?Z_OBJCE_P(newthis):NULL, newthis TSRMLS_CC); } /* }}} */ /* {{{ proto Closure Closure::bind(object $to, Closure $old) Create a closure to with binding to another object */ ZEND_METHOD(Closure, bind) /* {{{ */ { zval *newthis, *zclosure; zend_closure *closure; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "o!O", &newthis, &zclosure, zend_ce_closure) == FAILURE) { RETURN_NULL(); } closure = (zend_closure *)zend_object_store_get_object(zclosure TSRMLS_CC); zend_create_closure(return_value, &closure->func, newthis?Z_OBJCE_P(newthis):NULL, newthis TSRMLS_CC); } /* }}} */ static zend_function *zend_closure_get_constructor(zval *object TSRMLS_DC) /* {{{ */ { zend_error(E_RECOVERABLE_ERROR, "Instantiation of 'Closure' is not allowed"); return NULL; } /* }}} */ static int zend_closure_compare_objects(zval *o1, zval *o2 TSRMLS_DC) /* {{{ */ { return (Z_OBJ_HANDLE_P(o1) != Z_OBJ_HANDLE_P(o2)); } /* }}} */ ZEND_API zend_function *zend_get_closure_invoke_method(zval *obj TSRMLS_DC) /* {{{ */ { zend_closure *closure = (zend_closure *)zend_object_store_get_object(obj TSRMLS_CC); zend_function *invoke = (zend_function*)emalloc(sizeof(zend_function)); invoke->common = closure->func.common; invoke->type = ZEND_INTERNAL_FUNCTION; invoke->internal_function.fn_flags = ZEND_ACC_PUBLIC | ZEND_ACC_CALL_VIA_HANDLER | (closure->func.common.fn_flags & ZEND_ACC_RETURN_REFERENCE); invoke->internal_function.handler = ZEND_MN(Closure___invoke); invoke->internal_function.module = 0; invoke->internal_function.scope = zend_ce_closure; invoke->internal_function.function_name = estrndup(ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME)-1); return invoke; } /* }}} */ ZEND_API const zend_function *zend_get_closure_method_def(zval *obj TSRMLS_DC) /* {{{ */ { zend_closure *closure = (zend_closure *)zend_object_store_get_object(obj TSRMLS_CC); return &closure->func; } /* }}} */ ZEND_API zval* zend_get_closure_this_ptr(zval *obj TSRMLS_DC) /* {{{ */ { zend_closure *closure = (zend_closure *)zend_object_store_get_object(obj TSRMLS_CC); return closure->this_ptr; } /* }}} */ static zend_function *zend_closure_get_method(zval **object_ptr, char *method_name, int method_len, const zend_literal *key TSRMLS_DC) /* {{{ */ { char *lc_name; ALLOCA_FLAG(use_heap) lc_name = do_alloca(method_len + 1, use_heap); zend_str_tolower_copy(lc_name, method_name, method_len); if ((method_len == sizeof(ZEND_INVOKE_FUNC_NAME)-1) && memcmp(lc_name, ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME)-1) == 0 ) { free_alloca(lc_name, use_heap); return zend_get_closure_invoke_method(*object_ptr TSRMLS_CC); } free_alloca(lc_name, use_heap); return std_object_handlers.get_method(object_ptr, method_name, method_len, key TSRMLS_CC); } /* }}} */ static zval *zend_closure_read_property(zval *object, zval *member, int type, const zend_literal *key TSRMLS_DC) /* {{{ */ { ZEND_CLOSURE_PROPERTY_ERROR(); Z_ADDREF(EG(uninitialized_zval)); return &EG(uninitialized_zval); } /* }}} */ static void zend_closure_write_property(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC) /* {{{ */ { ZEND_CLOSURE_PROPERTY_ERROR(); } /* }}} */ static zval **zend_closure_get_property_ptr_ptr(zval *object, zval *member, const zend_literal *key TSRMLS_DC) /* {{{ */ { ZEND_CLOSURE_PROPERTY_ERROR(); return NULL; } /* }}} */ static int zend_closure_has_property(zval *object, zval *member, int has_set_exists, const zend_literal *key TSRMLS_DC) /* {{{ */ { if (has_set_exists != 2) { ZEND_CLOSURE_PROPERTY_ERROR(); } return 0; } /* }}} */ static void zend_closure_unset_property(zval *object, zval *member, const zend_literal *key TSRMLS_DC) /* {{{ */ { ZEND_CLOSURE_PROPERTY_ERROR(); } /* }}} */ static void zend_closure_free_storage(void *object TSRMLS_DC) /* {{{ */ { zend_closure *closure = (zend_closure *)object; zend_object_std_dtor(&closure->std TSRMLS_CC); if (closure->func.type == ZEND_USER_FUNCTION) { zend_execute_data *ex = EG(current_execute_data); while (ex) { if (ex->op_array == &closure->func.op_array) { zend_error(E_ERROR, "Cannot destroy active lambda function"); } ex = ex->prev_execute_data; } destroy_op_array(&closure->func.op_array TSRMLS_CC); } if (closure->debug_info != NULL) { zend_hash_destroy(closure->debug_info); efree(closure->debug_info); } if (closure->this_ptr) { zval_ptr_dtor(&closure->this_ptr); } efree(closure); } /* }}} */ static zend_object_value zend_closure_new(zend_class_entry *class_type TSRMLS_DC) /* {{{ */ { zend_closure *closure; zend_object_value object; closure = emalloc(sizeof(zend_closure)); memset(closure, 0, sizeof(zend_closure)); zend_object_std_init(&closure->std, class_type TSRMLS_CC); object.handle = zend_objects_store_put(closure, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) zend_closure_free_storage, NULL TSRMLS_CC); object.handlers = &closure_handlers; return object; } /* }}} */ static zend_object_value zend_closure_clone(zval *zobject TSRMLS_DC) /* {{{ */ { zend_closure *closure = (zend_closure *)zend_object_store_get_object(zobject TSRMLS_CC); zval result; zend_create_closure(&result, &closure->func, closure->func.common.scope, closure->this_ptr TSRMLS_CC); return Z_OBJVAL(result); } /* }}} */ int zend_closure_get_closure(zval *obj, zend_class_entry **ce_ptr, zend_function **fptr_ptr, zval **zobj_ptr TSRMLS_DC) /* {{{ */ { zend_closure *closure; if (Z_TYPE_P(obj) != IS_OBJECT) { return FAILURE; } closure = (zend_closure *)zend_object_store_get_object(obj TSRMLS_CC); *fptr_ptr = &closure->func; if (closure->this_ptr) { if (zobj_ptr) { *zobj_ptr = closure->this_ptr; } *ce_ptr = Z_OBJCE_P(closure->this_ptr); } else { if (zobj_ptr) { *zobj_ptr = NULL; } *ce_ptr = closure->func.common.scope; } return SUCCESS; } /* }}} */ static HashTable *zend_closure_get_debug_info(zval *object, int *is_temp TSRMLS_DC) /* {{{ */ { zend_closure *closure = (zend_closure *)zend_object_store_get_object(object TSRMLS_CC); zval *val; struct _zend_arg_info *arg_info = closure->func.common.arg_info; *is_temp = 0; if (closure->debug_info == NULL) { ALLOC_HASHTABLE(closure->debug_info); zend_hash_init(closure->debug_info, 1, NULL, ZVAL_PTR_DTOR, 0); } if (closure->debug_info->nApplyCount == 0) { if (closure->func.type == ZEND_USER_FUNCTION && closure->func.op_array.static_variables) { HashTable *static_variables = closure->func.op_array.static_variables; MAKE_STD_ZVAL(val); array_init(val); zend_hash_copy(Z_ARRVAL_P(val), static_variables, (copy_ctor_func_t)zval_add_ref, NULL, sizeof(zval*)); zend_hash_update(closure->debug_info, "static", sizeof("static"), (void *) &val, sizeof(zval *), NULL); } if (closure->this_ptr) { Z_ADDREF_P(closure->this_ptr); zend_symtable_update(closure->debug_info, "this", sizeof("this"), (void *) &closure->this_ptr, sizeof(zval *), NULL); } if (arg_info) { zend_uint i, required = closure->func.common.required_num_args; MAKE_STD_ZVAL(val); array_init(val); for (i = 0; i < closure->func.common.num_args; i++) { char *name, *info; int name_len, info_len; if (arg_info->name) { name_len = zend_spprintf(&name, 0, "%s$%s", arg_info->pass_by_reference ? "&" : "", arg_info->name); } else { name_len = zend_spprintf(&name, 0, "%s$param%d", arg_info->pass_by_reference ? "&" : "", i + 1); } info_len = zend_spprintf(&info, 0, "%s", i >= required ? "<optional>" : "<required>"); add_assoc_stringl_ex(val, name, name_len + 1, info, info_len, 0); efree(name); arg_info++; } zend_hash_update(closure->debug_info, "parameter", sizeof("parameter"), (void *) &val, sizeof(zval *), NULL); } } return closure->debug_info; } /* }}} */ /* {{{ proto Closure::__construct() Private constructor preventing instantiation */ ZEND_METHOD(Closure, __construct) { zend_error(E_RECOVERABLE_ERROR, "Instantiation of 'Closure' is not allowed"); } /* }}} */ ZEND_BEGIN_ARG_INFO_EX(arginfo_closure_bindto, 0, 0, 0) ZEND_ARG_INFO(0, newthis) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_closure_bind, 0, 0, 0) ZEND_ARG_INFO(0, newthis) ZEND_ARG_INFO(0, closure) ZEND_END_ARG_INFO() static const zend_function_entry closure_functions[] = { ZEND_ME(Closure, __construct, NULL, ZEND_ACC_PRIVATE) ZEND_ME(Closure, bindTo, arginfo_closure_bindto, ZEND_ACC_PUBLIC) ZEND_ME(Closure, bind, arginfo_closure_bind, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) {NULL, NULL, NULL} }; void zend_register_closure_ce(TSRMLS_D) /* {{{ */ { zend_class_entry ce; INIT_CLASS_ENTRY(ce, "Closure", closure_functions); zend_ce_closure = zend_register_internal_class(&ce TSRMLS_CC); zend_ce_closure->ce_flags |= ZEND_ACC_FINAL_CLASS; zend_ce_closure->create_object = zend_closure_new; zend_ce_closure->serialize = zend_class_serialize_deny; zend_ce_closure->unserialize = zend_class_unserialize_deny; memcpy(&closure_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); closure_handlers.get_constructor = zend_closure_get_constructor; closure_handlers.get_method = zend_closure_get_method; closure_handlers.write_property = zend_closure_write_property; closure_handlers.read_property = zend_closure_read_property; closure_handlers.get_property_ptr_ptr = zend_closure_get_property_ptr_ptr; closure_handlers.has_property = zend_closure_has_property; closure_handlers.unset_property = zend_closure_unset_property; closure_handlers.compare_objects = zend_closure_compare_objects; closure_handlers.clone_obj = zend_closure_clone; closure_handlers.get_debug_info = zend_closure_get_debug_info; closure_handlers.get_closure = zend_closure_get_closure; } /* }}} */ ZEND_API void zend_create_closure(zval *res, zend_function *func, zend_class_entry *scope, zval *this_ptr TSRMLS_DC) /* {{{ */ { zend_closure *closure; object_init_ex(res, zend_ce_closure); closure = (zend_closure *)zend_object_store_get_object(res TSRMLS_CC); closure->func = *func; if (closure->func.type == ZEND_USER_FUNCTION) { if (closure->func.op_array.static_variables) { HashTable *static_variables = closure->func.op_array.static_variables; ALLOC_HASHTABLE(closure->func.op_array.static_variables); zend_hash_init(closure->func.op_array.static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_apply_with_arguments(static_variables TSRMLS_CC, (apply_func_args_t)zval_copy_static_var, 1, closure->func.op_array.static_variables); } closure->func.op_array.run_time_cache = NULL; (*closure->func.op_array.refcount)++; } else { /* verify that we aren't binding internal function to a wrong scope */ if(func->common.scope != NULL) { if(scope && !instanceof_function(scope, func->common.scope TSRMLS_CC)) { zend_error(E_WARNING, "Cannot bind function %s::%s to scope class %s", func->common.scope->name, func->common.function_name, scope->name); scope = NULL; } if(scope && this_ptr && (func->common.fn_flags & ZEND_ACC_STATIC) == 0 && !instanceof_function(Z_OBJCE_P(this_ptr), closure->func.common.scope TSRMLS_CC)) { zend_error(E_WARNING, "Cannot bind function %s::%s to object of class %s", func->common.scope->name, func->common.function_name, Z_OBJCE_P(this_ptr)->name); scope = NULL; this_ptr = NULL; } } else { /* if it's a free function, we won't set scope & this since they're meaningless */ this_ptr = NULL; scope = NULL; } } closure->func.common.scope = scope; if (scope) { closure->func.common.fn_flags |= ZEND_ACC_PUBLIC; if (this_ptr && (closure->func.common.fn_flags & ZEND_ACC_STATIC) == 0) { closure->this_ptr = this_ptr; Z_ADDREF_P(this_ptr); } else { closure->func.common.fn_flags |= ZEND_ACC_STATIC; closure->this_ptr = NULL; } } else { closure->this_ptr = NULL; } } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */ /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Christian Seiler <[email protected]> | | Dmitry Stogov <[email protected]> | | Marcus Boerger <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "zend.h" #include "zend_API.h" #include "zend_closures.h" #include "zend_exceptions.h" #include "zend_interfaces.h" #include "zend_objects.h" #include "zend_objects_API.h" #include "zend_globals.h" #define ZEND_CLOSURE_PRINT_NAME "Closure object" #define ZEND_CLOSURE_PROPERTY_ERROR() \ zend_error(E_RECOVERABLE_ERROR, "Closure object cannot have properties") typedef struct _zend_closure { zend_object std; zend_function func; zval *this_ptr; HashTable *debug_info; } zend_closure; /* non-static since it needs to be referenced */ ZEND_API zend_class_entry *zend_ce_closure; static zend_object_handlers closure_handlers; ZEND_METHOD(Closure, __invoke) /* {{{ */ { zend_function *func = EG(current_execute_data)->function_state.function; zval ***arguments; zval *closure_result_ptr = NULL; arguments = emalloc(sizeof(zval**) * ZEND_NUM_ARGS()); if (zend_get_parameters_array_ex(ZEND_NUM_ARGS(), arguments) == FAILURE) { efree(arguments); zend_error(E_RECOVERABLE_ERROR, "Cannot get arguments for calling closure"); RETVAL_FALSE; } else if (call_user_function_ex(CG(function_table), NULL, this_ptr, &closure_result_ptr, ZEND_NUM_ARGS(), arguments, 1, NULL TSRMLS_CC) == FAILURE) { RETVAL_FALSE; } else if (closure_result_ptr) { if (Z_ISREF_P(closure_result_ptr) && return_value_ptr) { if (return_value) { zval_ptr_dtor(&return_value); } *return_value_ptr = closure_result_ptr; } else { RETVAL_ZVAL(closure_result_ptr, 1, 1); } } efree(arguments); /* destruct the function also, then - we have allocated it in get_method */ efree(func->internal_function.function_name); efree(func); } /* }}} */ /* {{{ proto Closure Closure::bindTo(object $to) Bind a closure to another object */ ZEND_METHOD(Closure, bindTo) /* {{{ */ { zval *newthis; zend_closure *closure = (zend_closure *)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "o!", &newthis) == FAILURE) { RETURN_NULL(); } zend_create_closure(return_value, &closure->func, newthis?Z_OBJCE_P(newthis):NULL, newthis TSRMLS_CC); } /* }}} */ /* {{{ proto Closure Closure::bind(object $to, Closure $old) Create a closure to with binding to another object */ ZEND_METHOD(Closure, bind) /* {{{ */ { zval *newthis, *zclosure; zend_closure *closure; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "o!O", &newthis, &zclosure, zend_ce_closure) == FAILURE) { RETURN_NULL(); } closure = (zend_closure *)zend_object_store_get_object(zclosure TSRMLS_CC); zend_create_closure(return_value, &closure->func, newthis?Z_OBJCE_P(newthis):NULL, newthis TSRMLS_CC); } /* }}} */ static zend_function *zend_closure_get_constructor(zval *object TSRMLS_DC) /* {{{ */ { zend_error(E_RECOVERABLE_ERROR, "Instantiation of 'Closure' is not allowed"); return NULL; } /* }}} */ static int zend_closure_compare_objects(zval *o1, zval *o2 TSRMLS_DC) /* {{{ */ { return (Z_OBJ_HANDLE_P(o1) != Z_OBJ_HANDLE_P(o2)); } /* }}} */ ZEND_API zend_function *zend_get_closure_invoke_method(zval *obj TSRMLS_DC) /* {{{ */ { zend_closure *closure = (zend_closure *)zend_object_store_get_object(obj TSRMLS_CC); zend_function *invoke = (zend_function*)emalloc(sizeof(zend_function)); invoke->common = closure->func.common; invoke->type = ZEND_INTERNAL_FUNCTION; invoke->internal_function.fn_flags = ZEND_ACC_PUBLIC | ZEND_ACC_CALL_VIA_HANDLER | (closure->func.common.fn_flags & ZEND_ACC_RETURN_REFERENCE); invoke->internal_function.handler = ZEND_MN(Closure___invoke); invoke->internal_function.module = 0; invoke->internal_function.scope = zend_ce_closure; invoke->internal_function.function_name = estrndup(ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME)-1); return invoke; } /* }}} */ ZEND_API const zend_function *zend_get_closure_method_def(zval *obj TSRMLS_DC) /* {{{ */ { zend_closure *closure = (zend_closure *)zend_object_store_get_object(obj TSRMLS_CC); return &closure->func; } /* }}} */ ZEND_API zval* zend_get_closure_this_ptr(zval *obj TSRMLS_DC) /* {{{ */ { zend_closure *closure = (zend_closure *)zend_object_store_get_object(obj TSRMLS_CC); return closure->this_ptr; } /* }}} */ static zend_function *zend_closure_get_method(zval **object_ptr, char *method_name, int method_len, const zend_literal *key TSRMLS_DC) /* {{{ */ { char *lc_name; ALLOCA_FLAG(use_heap) lc_name = do_alloca(method_len + 1, use_heap); zend_str_tolower_copy(lc_name, method_name, method_len); if ((method_len == sizeof(ZEND_INVOKE_FUNC_NAME)-1) && memcmp(lc_name, ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME)-1) == 0 ) { free_alloca(lc_name, use_heap); return zend_get_closure_invoke_method(*object_ptr TSRMLS_CC); } free_alloca(lc_name, use_heap); return std_object_handlers.get_method(object_ptr, method_name, method_len, key TSRMLS_CC); } /* }}} */ static zval *zend_closure_read_property(zval *object, zval *member, int type, const zend_literal *key TSRMLS_DC) /* {{{ */ { ZEND_CLOSURE_PROPERTY_ERROR(); Z_ADDREF(EG(uninitialized_zval)); return &EG(uninitialized_zval); } /* }}} */ static void zend_closure_write_property(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC) /* {{{ */ { ZEND_CLOSURE_PROPERTY_ERROR(); } /* }}} */ static zval **zend_closure_get_property_ptr_ptr(zval *object, zval *member, const zend_literal *key TSRMLS_DC) /* {{{ */ { ZEND_CLOSURE_PROPERTY_ERROR(); return NULL; } /* }}} */ static int zend_closure_has_property(zval *object, zval *member, int has_set_exists, const zend_literal *key TSRMLS_DC) /* {{{ */ { if (has_set_exists != 2) { ZEND_CLOSURE_PROPERTY_ERROR(); } return 0; } /* }}} */ static void zend_closure_unset_property(zval *object, zval *member, const zend_literal *key TSRMLS_DC) /* {{{ */ { ZEND_CLOSURE_PROPERTY_ERROR(); } /* }}} */ static void zend_closure_free_storage(void *object TSRMLS_DC) /* {{{ */ { zend_closure *closure = (zend_closure *)object; zend_object_std_dtor(&closure->std TSRMLS_CC); if (closure->func.type == ZEND_USER_FUNCTION) { zend_execute_data *ex = EG(current_execute_data); while (ex) { if (ex->op_array == &closure->func.op_array) { zend_error(E_ERROR, "Cannot destroy active lambda function"); } ex = ex->prev_execute_data; } destroy_op_array(&closure->func.op_array TSRMLS_CC); } if (closure->debug_info != NULL) { zend_hash_destroy(closure->debug_info); efree(closure->debug_info); } if (closure->this_ptr) { zval_ptr_dtor(&closure->this_ptr); } efree(closure); } /* }}} */ static zend_object_value zend_closure_new(zend_class_entry *class_type TSRMLS_DC) /* {{{ */ { zend_closure *closure; zend_object_value object; closure = emalloc(sizeof(zend_closure)); memset(closure, 0, sizeof(zend_closure)); zend_object_std_init(&closure->std, class_type TSRMLS_CC); object.handle = zend_objects_store_put(closure, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) zend_closure_free_storage, NULL TSRMLS_CC); object.handlers = &closure_handlers; return object; } /* }}} */ static zend_object_value zend_closure_clone(zval *zobject TSRMLS_DC) /* {{{ */ { zend_closure *closure = (zend_closure *)zend_object_store_get_object(zobject TSRMLS_CC); zval result; zend_create_closure(&result, &closure->func, closure->func.common.scope, closure->this_ptr TSRMLS_CC); return Z_OBJVAL(result); } /* }}} */ int zend_closure_get_closure(zval *obj, zend_class_entry **ce_ptr, zend_function **fptr_ptr, zval **zobj_ptr TSRMLS_DC) /* {{{ */ { zend_closure *closure; if (Z_TYPE_P(obj) != IS_OBJECT) { return FAILURE; } closure = (zend_closure *)zend_object_store_get_object(obj TSRMLS_CC); *fptr_ptr = &closure->func; if (closure->this_ptr) { if (zobj_ptr) { *zobj_ptr = closure->this_ptr; } *ce_ptr = Z_OBJCE_P(closure->this_ptr); } else { if (zobj_ptr) { *zobj_ptr = NULL; } *ce_ptr = closure->func.common.scope; } return SUCCESS; } /* }}} */ static HashTable *zend_closure_get_debug_info(zval *object, int *is_temp TSRMLS_DC) /* {{{ */ { zend_closure *closure = (zend_closure *)zend_object_store_get_object(object TSRMLS_CC); zval *val; struct _zend_arg_info *arg_info = closure->func.common.arg_info; *is_temp = 0; if (closure->debug_info == NULL) { ALLOC_HASHTABLE(closure->debug_info); zend_hash_init(closure->debug_info, 1, NULL, ZVAL_PTR_DTOR, 0); } if (closure->debug_info->nApplyCount == 0) { if (closure->func.type == ZEND_USER_FUNCTION && closure->func.op_array.static_variables) { HashTable *static_variables = closure->func.op_array.static_variables; MAKE_STD_ZVAL(val); array_init(val); zend_hash_copy(Z_ARRVAL_P(val), static_variables, (copy_ctor_func_t)zval_add_ref, NULL, sizeof(zval*)); zend_hash_update(closure->debug_info, "static", sizeof("static"), (void *) &val, sizeof(zval *), NULL); } if (closure->this_ptr) { Z_ADDREF_P(closure->this_ptr); zend_symtable_update(closure->debug_info, "this", sizeof("this"), (void *) &closure->this_ptr, sizeof(zval *), NULL); } if (arg_info) { zend_uint i, required = closure->func.common.required_num_args; MAKE_STD_ZVAL(val); array_init(val); for (i = 0; i < closure->func.common.num_args; i++) { char *name, *info; int name_len, info_len; if (arg_info->name) { name_len = zend_spprintf(&name, 0, "%s$%s", arg_info->pass_by_reference ? "&" : "", arg_info->name); } else { name_len = zend_spprintf(&name, 0, "%s$param%d", arg_info->pass_by_reference ? "&" : "", i + 1); } info_len = zend_spprintf(&info, 0, "%s", i >= required ? "<optional>" : "<required>"); add_assoc_stringl_ex(val, name, name_len + 1, info, info_len, 0); efree(name); arg_info++; } zend_hash_update(closure->debug_info, "parameter", sizeof("parameter"), (void *) &val, sizeof(zval *), NULL); } } return closure->debug_info; } /* }}} */ /* {{{ proto Closure::__construct() Private constructor preventing instantiation */ ZEND_METHOD(Closure, __construct) { zend_error(E_RECOVERABLE_ERROR, "Instantiation of 'Closure' is not allowed"); } /* }}} */ ZEND_BEGIN_ARG_INFO_EX(arginfo_closure_bindto, 0, 0, 0) ZEND_ARG_INFO(0, newthis) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_closure_bind, 0, 0, 0) ZEND_ARG_INFO(0, newthis) ZEND_ARG_INFO(0, closure) ZEND_END_ARG_INFO() static const zend_function_entry closure_functions[] = { ZEND_ME(Closure, __construct, NULL, ZEND_ACC_PRIVATE) ZEND_ME(Closure, bindTo, arginfo_closure_bindto, ZEND_ACC_PUBLIC) ZEND_ME(Closure, bind, arginfo_closure_bind, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) {NULL, NULL, NULL} }; void zend_register_closure_ce(TSRMLS_D) /* {{{ */ { zend_class_entry ce; INIT_CLASS_ENTRY(ce, "Closure", closure_functions); zend_ce_closure = zend_register_internal_class(&ce TSRMLS_CC); zend_ce_closure->ce_flags |= ZEND_ACC_FINAL_CLASS; zend_ce_closure->create_object = zend_closure_new; zend_ce_closure->serialize = zend_class_serialize_deny; zend_ce_closure->unserialize = zend_class_unserialize_deny; memcpy(&closure_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); closure_handlers.get_constructor = zend_closure_get_constructor; closure_handlers.get_method = zend_closure_get_method; closure_handlers.write_property = zend_closure_write_property; closure_handlers.read_property = zend_closure_read_property; closure_handlers.get_property_ptr_ptr = zend_closure_get_property_ptr_ptr; closure_handlers.has_property = zend_closure_has_property; closure_handlers.unset_property = zend_closure_unset_property; closure_handlers.compare_objects = zend_closure_compare_objects; closure_handlers.clone_obj = zend_closure_clone; closure_handlers.get_debug_info = zend_closure_get_debug_info; closure_handlers.get_closure = zend_closure_get_closure; } /* }}} */ ZEND_API void zend_create_closure(zval *res, zend_function *func, zend_class_entry *scope, zval *this_ptr TSRMLS_DC) /* {{{ */ { zend_closure *closure; object_init_ex(res, zend_ce_closure); closure = (zend_closure *)zend_object_store_get_object(res TSRMLS_CC); closure->func = *func; closure->func.common.prototype = NULL; if (closure->func.type == ZEND_USER_FUNCTION) { if (closure->func.op_array.static_variables) { HashTable *static_variables = closure->func.op_array.static_variables; ALLOC_HASHTABLE(closure->func.op_array.static_variables); zend_hash_init(closure->func.op_array.static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_apply_with_arguments(static_variables TSRMLS_CC, (apply_func_args_t)zval_copy_static_var, 1, closure->func.op_array.static_variables); } closure->func.op_array.run_time_cache = NULL; (*closure->func.op_array.refcount)++; } else { /* verify that we aren't binding internal function to a wrong scope */ if(func->common.scope != NULL) { if(scope && !instanceof_function(scope, func->common.scope TSRMLS_CC)) { zend_error(E_WARNING, "Cannot bind function %s::%s to scope class %s", func->common.scope->name, func->common.function_name, scope->name); scope = NULL; } if(scope && this_ptr && (func->common.fn_flags & ZEND_ACC_STATIC) == 0 && !instanceof_function(Z_OBJCE_P(this_ptr), closure->func.common.scope TSRMLS_CC)) { zend_error(E_WARNING, "Cannot bind function %s::%s to object of class %s", func->common.scope->name, func->common.function_name, Z_OBJCE_P(this_ptr)->name); scope = NULL; this_ptr = NULL; } } else { /* if it's a free function, we won't set scope & this since they're meaningless */ this_ptr = NULL; scope = NULL; } } closure->func.common.scope = scope; if (scope) { closure->func.common.fn_flags |= ZEND_ACC_PUBLIC; if (this_ptr && (closure->func.common.fn_flags & ZEND_ACC_STATIC) == 0) { closure->this_ptr = this_ptr; Z_ADDREF_P(this_ptr); } else { closure->func.common.fn_flags |= ZEND_ACC_STATIC; closure->this_ptr = NULL; } } else { closure->this_ptr = NULL; } } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-04-19-11941b3fd2-821d7169d9.c
manybugs_data_8
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Jim Winstead <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <stdlib.h> #include <string.h> #include <ctype.h> #include <sys/types.h> #include "php.h" #include "url.h" #include "file.h" #ifdef _OSD_POSIX #ifndef APACHE #error On this EBCDIC platform, PHP is only supported as an Apache module. #else /*APACHE*/ #ifndef CHARSET_EBCDIC #define CHARSET_EBCDIC /* this machine uses EBCDIC, not ASCII! */ #endif #include "ebcdic.h" #endif /*APACHE*/ #endif /*_OSD_POSIX*/ /* {{{ free_url */ PHPAPI void php_url_free(php_url *theurl) { if (theurl->scheme) efree(theurl->scheme); if (theurl->user) efree(theurl->user); if (theurl->pass) efree(theurl->pass); if (theurl->host) efree(theurl->host); if (theurl->path) efree(theurl->path); if (theurl->query) efree(theurl->query); if (theurl->fragment) efree(theurl->fragment); efree(theurl); } /* }}} */ /* {{{ php_replace_controlchars */ PHPAPI char *php_replace_controlchars_ex(char *str, int len) { unsigned char *s = (unsigned char *)str; unsigned char *e = (unsigned char *)str + len; if (!str) { return (NULL); } while (s < e) { if (iscntrl(*s)) { *s='_'; } s++; } return (str); } /* }}} */ PHPAPI char *php_replace_controlchars(char *str) { return php_replace_controlchars_ex(str, strlen(str)); } PHPAPI php_url *php_url_parse(char const *str) { return php_url_parse_ex(str, strlen(str)); } /* {{{ php_url_parse */ PHPAPI php_url *php_url_parse_ex(char const *str, int length) { char port_buf[6]; php_url *ret = ecalloc(1, sizeof(php_url)); char const *s, *e, *p, *pp, *ue; s = str; ue = s + length; /* parse scheme */ if ((e = memchr(s, ':', length)) && (e - s)) { /* validate scheme */ p = s; while (p < e) { /* scheme = 1*[ lowalpha | digit | "+" | "-" | "." ] */ if (!isalpha(*p) && !isdigit(*p) && *p != '+' && *p != '.' && *p != '-') { if (e + 1 < ue) { goto parse_port; } else { goto just_path; } } p++; } if (*(e + 1) == '\0') { /* only scheme is available */ ret->scheme = estrndup(s, (e - s)); php_replace_controlchars_ex(ret->scheme, (e - s)); goto end; } /* * certain schemas like mailto: and zlib: may not have any / after them * this check ensures we support those. */ if (*(e+1) != '/') { /* check if the data we get is a port this allows us to * correctly parse things like a.com:80 */ p = e + 1; while (isdigit(*p)) { p++; } if ((*p == '\0' || *p == '/') && (p - e) < 7) { goto parse_port; } ret->scheme = estrndup(s, (e-s)); php_replace_controlchars_ex(ret->scheme, (e - s)); length -= ++e - s; s = e; goto just_path; } else { ret->scheme = estrndup(s, (e-s)); php_replace_controlchars_ex(ret->scheme, (e - s)); if (*(e+2) == '/') { s = e + 3; if (!strncasecmp("file", ret->scheme, sizeof("file"))) { if (*(e + 3) == '/') { /* support windows drive letters as in: file:///c:/somedir/file.txt */ if (*(e + 5) == ':') { s = e + 4; } goto nohost; } } } else { if (!strncasecmp("file", ret->scheme, sizeof("file"))) { s = e + 1; goto nohost; } else { length -= ++e - s; s = e; goto just_path; } } } } else if (e) { /* no scheme; starts with colon: look for port */ parse_port: p = e + 1; pp = p; while (pp-p < 6 && isdigit(*pp)) { pp++; } if (pp - p > 0 && pp - p < 6 && (*pp == '/' || *pp == '\0')) { long port; memcpy(port_buf, p, (pp - p)); port_buf[pp - p] = '\0'; port = strtol(port_buf, NULL, 10); if (port > 0 && port <= 65535) { ret->port = (unsigned short) port; } else { STR_FREE(ret->scheme); efree(ret); return NULL; } } else { goto just_path; } } else { just_path: ue = s + length; goto nohost; } e = ue; if (!(p = memchr(s, '/', (ue - s)))) { char *query, *fragment; query = memchr(s, '?', (ue - s)); fragment = memchr(s, '#', (ue - s)); if (query && fragment) { if (query > fragment) { p = e = fragment; } else { p = e = query; } } else if (query) { p = e = query; } else if (fragment) { p = e = fragment; } } else { e = p; } /* check for login and password */ if ((p = zend_memrchr(s, '@', (e-s)))) { if ((pp = memchr(s, ':', (p-s)))) { if ((pp-s) > 0) { ret->user = estrndup(s, (pp-s)); php_replace_controlchars_ex(ret->user, (pp - s)); } pp++; if (p-pp > 0) { ret->pass = estrndup(pp, (p-pp)); php_replace_controlchars_ex(ret->pass, (p-pp)); } } else { ret->user = estrndup(s, (p-s)); php_replace_controlchars_ex(ret->user, (p-s)); } s = p + 1; } /* check for port */ if (*s == '[' && *(e-1) == ']') { /* Short circuit portscan, we're dealing with an IPv6 embedded address */ p = s; } else { /* memrchr is a GNU specific extension Emulate for wide compatability */ for(p = e; *p != ':' && p >= s; p--); } if (p >= s && *p == ':') { if (!ret->port) { p++; if (e-p > 5) { /* port cannot be longer then 5 characters */ STR_FREE(ret->scheme); STR_FREE(ret->user); STR_FREE(ret->pass); efree(ret); return NULL; } else if (e - p > 0) { long port; memcpy(port_buf, p, (e - p)); port_buf[e - p] = '\0'; port = strtol(port_buf, NULL, 10); if (port > 0 && port <= 65535) { ret->port = (unsigned short)port; } else { STR_FREE(ret->scheme); STR_FREE(ret->user); STR_FREE(ret->pass); efree(ret); return NULL; } } p--; } } else { p = e; } /* check if we have a valid host, if we don't reject the string as url */ if ((p-s) < 1) { STR_FREE(ret->scheme); STR_FREE(ret->user); STR_FREE(ret->pass); efree(ret); return NULL; } ret->host = estrndup(s, (p-s)); php_replace_controlchars_ex(ret->host, (p - s)); if (e == ue) { return ret; } s = e; nohost: if ((p = memchr(s, '?', (ue - s)))) { pp = strchr(s, '#'); if (pp && pp < p) { p = pp; goto label_parse; } if (p - s) { ret->path = estrndup(s, (p-s)); php_replace_controlchars_ex(ret->path, (p - s)); } if (pp) { if (pp - ++p) { ret->query = estrndup(p, (pp-p)); php_replace_controlchars_ex(ret->query, (pp - p)); } p = pp; goto label_parse; } else if (++p - ue) { ret->query = estrndup(p, (ue-p)); php_replace_controlchars_ex(ret->query, (ue - p)); } } else if ((p = memchr(s, '#', (ue - s)))) { if (p - s) { ret->path = estrndup(s, (p-s)); php_replace_controlchars_ex(ret->path, (p - s)); } label_parse: p++; if (ue - p) { ret->fragment = estrndup(p, (ue-p)); php_replace_controlchars_ex(ret->fragment, (ue - p)); } } else { ret->path = estrndup(s, (ue-s)); php_replace_controlchars_ex(ret->path, (ue - s)); } end: return ret; } /* }}} */ /* {{{ proto mixed parse_url(string url, [int url_component]) Parse a URL and return its components */ PHP_FUNCTION(parse_url) { char *str; int str_len; php_url *resource; long key = -1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &str, &str_len, &key) == FAILURE) { return; } resource = php_url_parse_ex(str, str_len); if (resource == NULL) { /* @todo Find a method to determine why php_url_parse_ex() failed */ RETURN_FALSE; } if (key > -1) { switch (key) { case PHP_URL_SCHEME: if (resource->scheme != NULL) RETVAL_STRING(resource->scheme, 1); break; case PHP_URL_HOST: if (resource->host != NULL) RETVAL_STRING(resource->host, 1); break; case PHP_URL_PORT: if (resource->port != 0) RETVAL_LONG(resource->port); break; case PHP_URL_USER: if (resource->user != NULL) RETVAL_STRING(resource->user, 1); break; case PHP_URL_PASS: if (resource->pass != NULL) RETVAL_STRING(resource->pass, 1); break; case PHP_URL_PATH: if (resource->path != NULL) RETVAL_STRING(resource->path, 1); break; case PHP_URL_QUERY: if (resource->query != NULL) RETVAL_STRING(resource->query, 1); break; case PHP_URL_FRAGMENT: if (resource->fragment != NULL) RETVAL_STRING(resource->fragment, 1); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid URL component identifier %ld", key); RETVAL_FALSE; } goto done; } /* allocate an array for return */ array_init(return_value); /* add the various elements to the array */ if (resource->scheme != NULL) add_assoc_string(return_value, "scheme", resource->scheme, 1); if (resource->host != NULL) add_assoc_string(return_value, "host", resource->host, 1); if (resource->port != 0) add_assoc_long(return_value, "port", resource->port); if (resource->user != NULL) add_assoc_string(return_value, "user", resource->user, 1); if (resource->pass != NULL) add_assoc_string(return_value, "pass", resource->pass, 1); if (resource->path != NULL) add_assoc_string(return_value, "path", resource->path, 1); if (resource->query != NULL) add_assoc_string(return_value, "query", resource->query, 1); if (resource->fragment != NULL) add_assoc_string(return_value, "fragment", resource->fragment, 1); done: php_url_free(resource); } /* }}} */ /* {{{ php_htoi */ static int php_htoi(char *s) { int value; int c; c = ((unsigned char *)s)[0]; if (isupper(c)) c = tolower(c); value = (c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10) * 16; c = ((unsigned char *)s)[1]; if (isupper(c)) c = tolower(c); value += c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10; return (value); } /* }}} */ /* rfc1738: ...The characters ";", "/", "?", ":", "@", "=" and "&" are the characters which may be reserved for special meaning within a scheme... ...Thus, only alphanumerics, the special characters "$-_.+!*'(),", and reserved characters used for their reserved purposes may be used unencoded within a URL... For added safety, we only leave -_. unencoded. */ static unsigned char hexchars[] = "0123456789ABCDEF"; /* {{{ php_url_encode */ PHPAPI char *php_url_encode(char const *s, int len, int *new_length) { register unsigned char c; unsigned char *to, *start; unsigned char const *from, *end; from = (unsigned char *)s; end = (unsigned char *)s + len; start = to = (unsigned char *) safe_emalloc(3, len, 1); while (from < end) { c = *from++; if (c == ' ') { *to++ = '+'; #ifndef CHARSET_EBCDIC } else if ((c < '0' && c != '-' && c != '.') || (c < 'A' && c > '9') || (c > 'Z' && c < 'a' && c != '_') || (c > 'z')) { to[0] = '%'; to[1] = hexchars[c >> 4]; to[2] = hexchars[c & 15]; to += 3; #else /*CHARSET_EBCDIC*/ } else if (!isalnum(c) && strchr("_-.", c) == NULL) { /* Allow only alphanumeric chars and '_', '-', '.'; escape the rest */ to[0] = '%'; to[1] = hexchars[os_toascii[c] >> 4]; to[2] = hexchars[os_toascii[c] & 15]; to += 3; #endif /*CHARSET_EBCDIC*/ } else { *to++ = c; } } *to = 0; if (new_length) { *new_length = to - start; } return (char *) start; } /* }}} */ /* {{{ proto string urlencode(string str) URL-encodes string */ PHP_FUNCTION(urlencode) { char *in_str, *out_str; int in_str_len, out_str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str, &in_str_len) == FAILURE) { return; } out_str = php_url_encode(in_str, in_str_len, &out_str_len); RETURN_STRINGL(out_str, out_str_len, 0); } /* }}} */ /* {{{ proto string urldecode(string str) Decodes URL-encoded string */ PHP_FUNCTION(urldecode) { char *in_str, *out_str; int in_str_len, out_str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str, &in_str_len) == FAILURE) { return; } out_str = estrndup(in_str, in_str_len); out_str_len = php_url_decode(out_str, in_str_len); RETURN_STRINGL(out_str, out_str_len, 0); } /* }}} */ /* {{{ php_url_decode */ PHPAPI int php_url_decode(char *str, int len) { char *dest = str; char *data = str; while (len--) { if (*data == '+') { *dest = ' '; } else if (*data == '%' && len >= 2 && isxdigit((int) *(data + 1)) && isxdigit((int) *(data + 2))) { #ifndef CHARSET_EBCDIC *dest = (char) php_htoi(data + 1); #else *dest = os_toebcdic[(char) php_htoi(data + 1)]; #endif data += 2; len -= 2; } else { *dest = *data; } data++; dest++; } *dest = '\0'; return dest - str; } /* }}} */ /* {{{ php_raw_url_encode */ PHPAPI char *php_raw_url_encode(char const *s, int len, int *new_length) { register int x, y; unsigned char *str; str = (unsigned char *) safe_emalloc(3, len, 1); for (x = 0, y = 0; len--; x++, y++) { str[y] = (unsigned char) s[x]; #ifndef CHARSET_EBCDIC if ((str[y] < '0' && str[y] != '-' && str[y] != '.') || (str[y] < 'A' && str[y] > '9') || (str[y] > 'Z' && str[y] < 'a' && str[y] != '_') || (str[y] > 'z' && str[y] != '~')) { str[y++] = '%'; str[y++] = hexchars[(unsigned char) s[x] >> 4]; str[y] = hexchars[(unsigned char) s[x] & 15]; #else /*CHARSET_EBCDIC*/ if (!isalnum(str[y]) && strchr("_-.~", str[y]) != NULL) { str[y++] = '%'; str[y++] = hexchars[os_toascii[(unsigned char) s[x]] >> 4]; str[y] = hexchars[os_toascii[(unsigned char) s[x]] & 15]; #endif /*CHARSET_EBCDIC*/ } } str[y] = '\0'; if (new_length) { *new_length = y; } return ((char *) str); } /* }}} */ /* {{{ proto string rawurlencode(string str) URL-encodes string */ PHP_FUNCTION(rawurlencode) { char *in_str, *out_str; int in_str_len, out_str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str, &in_str_len) == FAILURE) { return; } out_str = php_raw_url_encode(in_str, in_str_len, &out_str_len); RETURN_STRINGL(out_str, out_str_len, 0); } /* }}} */ /* {{{ proto string rawurldecode(string str) Decodes URL-encodes string */ PHP_FUNCTION(rawurldecode) { char *in_str, *out_str; int in_str_len, out_str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str, &in_str_len) == FAILURE) { return; } out_str = estrndup(in_str, in_str_len); out_str_len = php_raw_url_decode(out_str, in_str_len); RETURN_STRINGL(out_str, out_str_len, 0); } /* }}} */ /* {{{ php_raw_url_decode */ PHPAPI int php_raw_url_decode(char *str, int len) { char *dest = str; char *data = str; while (len--) { if (*data == '%' && len >= 2 && isxdigit((int) *(data + 1)) && isxdigit((int) *(data + 2))) { #ifndef CHARSET_EBCDIC *dest = (char) php_htoi(data + 1); #else *dest = os_toebcdic[(char) php_htoi(data + 1)]; #endif data += 2; len -= 2; } else { *dest = *data; } data++; dest++; } *dest = '\0'; return dest - str; } /* }}} */ /* {{{ proto array get_headers(string url[, int format]) fetches all the headers sent by the server in response to a HTTP request */ PHP_FUNCTION(get_headers) { char *url; int url_len; php_stream_context *context; php_stream *stream; zval **prev_val, **hdr = NULL, **h; HashPosition pos; HashTable *hashT; long format = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &url, &url_len, &format) == FAILURE) { return; } context = FG(default_context) ? FG(default_context) : (FG(default_context) = php_stream_context_alloc(TSRMLS_C)); if (!(stream = php_stream_open_wrapper_ex(url, "r", REPORT_ERRORS | STREAM_USE_URL | STREAM_ONLY_GET_HEADERS, NULL, context))) { RETURN_FALSE; } if (!stream->wrapperdata || Z_TYPE_P(stream->wrapperdata) != IS_ARRAY) { php_stream_close(stream); RETURN_FALSE; } array_init(return_value); /* check for curl-wrappers that provide headers via a special "headers" element */ if (zend_hash_find(HASH_OF(stream->wrapperdata), "headers", sizeof("headers"), (void **)&h) != FAILURE && Z_TYPE_PP(h) == IS_ARRAY) { /* curl-wrappers don't load data until the 1st read */ if (!Z_ARRVAL_PP(h)->nNumOfElements) { php_stream_getc(stream); } zend_hash_find(HASH_OF(stream->wrapperdata), "headers", sizeof("headers"), (void **)&h); hashT = Z_ARRVAL_PP(h); } else { hashT = HASH_OF(stream->wrapperdata); } zend_hash_internal_pointer_reset_ex(hashT, &pos); while (zend_hash_get_current_data_ex(hashT, (void**)&hdr, &pos) != FAILURE) { if (!hdr || Z_TYPE_PP(hdr) != IS_STRING) { zend_hash_move_forward_ex(hashT, &pos); continue; } if (!format) { no_name_header: add_next_index_stringl(return_value, Z_STRVAL_PP(hdr), Z_STRLEN_PP(hdr), 1); } else { char c; char *s, *p; if ((p = strchr(Z_STRVAL_PP(hdr), ':'))) { c = *p; *p = '\0'; s = p + 1; while (isspace((int)*(unsigned char *)s)) { s++; } if (zend_hash_find(HASH_OF(return_value), Z_STRVAL_PP(hdr), (p - Z_STRVAL_PP(hdr) + 1), (void **) &prev_val) == FAILURE) { add_assoc_stringl_ex(return_value, Z_STRVAL_PP(hdr), (p - Z_STRVAL_PP(hdr) + 1), s, (Z_STRLEN_PP(hdr) - (s - Z_STRVAL_PP(hdr))), 1); } else { /* some headers may occur more then once, therefor we need to remake the string into an array */ convert_to_array(*prev_val); add_next_index_stringl(*prev_val, s, (Z_STRLEN_PP(hdr) - (s - Z_STRVAL_PP(hdr))), 1); } *p = c; } else { goto no_name_header; } } zend_hash_move_forward_ex(hashT, &pos); } php_stream_close(stream); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Jim Winstead <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <stdlib.h> #include <string.h> #include <ctype.h> #include <sys/types.h> #include "php.h" #include "url.h" #include "file.h" #ifdef _OSD_POSIX #ifndef APACHE #error On this EBCDIC platform, PHP is only supported as an Apache module. #else /*APACHE*/ #ifndef CHARSET_EBCDIC #define CHARSET_EBCDIC /* this machine uses EBCDIC, not ASCII! */ #endif #include "ebcdic.h" #endif /*APACHE*/ #endif /*_OSD_POSIX*/ /* {{{ free_url */ PHPAPI void php_url_free(php_url *theurl) { if (theurl->scheme) efree(theurl->scheme); if (theurl->user) efree(theurl->user); if (theurl->pass) efree(theurl->pass); if (theurl->host) efree(theurl->host); if (theurl->path) efree(theurl->path); if (theurl->query) efree(theurl->query); if (theurl->fragment) efree(theurl->fragment); efree(theurl); } /* }}} */ /* {{{ php_replace_controlchars */ PHPAPI char *php_replace_controlchars_ex(char *str, int len) { unsigned char *s = (unsigned char *)str; unsigned char *e = (unsigned char *)str + len; if (!str) { return (NULL); } while (s < e) { if (iscntrl(*s)) { *s='_'; } s++; } return (str); } /* }}} */ PHPAPI char *php_replace_controlchars(char *str) { return php_replace_controlchars_ex(str, strlen(str)); } PHPAPI php_url *php_url_parse(char const *str) { return php_url_parse_ex(str, strlen(str)); } /* {{{ php_url_parse */ PHPAPI php_url *php_url_parse_ex(char const *str, int length) { char port_buf[6]; php_url *ret = ecalloc(1, sizeof(php_url)); char const *s, *e, *p, *pp, *ue; s = str; ue = s + length; /* parse scheme */ if ((e = memchr(s, ':', length)) && (e - s)) { /* validate scheme */ p = s; while (p < e) { /* scheme = 1*[ lowalpha | digit | "+" | "-" | "." ] */ if (!isalpha(*p) && !isdigit(*p) && *p != '+' && *p != '.' && *p != '-') { if (e + 1 < ue) { goto parse_port; } else { goto just_path; } } p++; } if (*(e + 1) == '\0') { /* only scheme is available */ ret->scheme = estrndup(s, (e - s)); php_replace_controlchars_ex(ret->scheme, (e - s)); goto end; } /* * certain schemas like mailto: and zlib: may not have any / after them * this check ensures we support those. */ if (*(e+1) != '/') { /* check if the data we get is a port this allows us to * correctly parse things like a.com:80 */ p = e + 1; while (isdigit(*p)) { p++; } if ((*p == '\0' || *p == '/') && (p - e) < 7) { goto parse_port; } ret->scheme = estrndup(s, (e-s)); php_replace_controlchars_ex(ret->scheme, (e - s)); length -= ++e - s; s = e; goto just_path; } else { ret->scheme = estrndup(s, (e-s)); php_replace_controlchars_ex(ret->scheme, (e - s)); if (*(e+2) == '/') { s = e + 3; if (!strncasecmp("file", ret->scheme, sizeof("file"))) { if (*(e + 3) == '/') { /* support windows drive letters as in: file:///c:/somedir/file.txt */ if (*(e + 5) == ':') { s = e + 4; } goto nohost; } } } else { if (!strncasecmp("file", ret->scheme, sizeof("file"))) { s = e + 1; goto nohost; } else { length -= ++e - s; s = e; goto just_path; } } } } else if (e) { /* no scheme; starts with colon: look for port */ parse_port: p = e + 1; pp = p; while (pp-p < 6 && isdigit(*pp)) { pp++; } if (pp - p > 0 && pp - p < 6 && (*pp == '/' || *pp == '\0')) { long port; memcpy(port_buf, p, (pp - p)); port_buf[pp - p] = '\0'; port = strtol(port_buf, NULL, 10); if (port > 0 && port <= 65535) { ret->port = (unsigned short) port; } else { STR_FREE(ret->scheme); efree(ret); return NULL; } } else { goto just_path; } } else { just_path: ue = s + length; goto nohost; } e = ue; if (!(p = memchr(s, '/', (ue - s)))) { char *query, *fragment; query = memchr(s, '?', (ue - s)); fragment = memchr(s, '#', (ue - s)); if (query && fragment) { if (query > fragment) { p = e = fragment; } else { p = e = query; } } else if (query) { p = e = query; } else if (fragment) { p = e = fragment; } } else { e = p; } /* check for login and password */ if ((p = zend_memrchr(s, '@', (e-s)))) { if ((pp = memchr(s, ':', (p-s)))) { if ((pp-s) > 0) { ret->user = estrndup(s, (pp-s)); php_replace_controlchars_ex(ret->user, (pp - s)); } pp++; if (p-pp > 0) { ret->pass = estrndup(pp, (p-pp)); php_replace_controlchars_ex(ret->pass, (p-pp)); } } else { ret->user = estrndup(s, (p-s)); php_replace_controlchars_ex(ret->user, (p-s)); } s = p + 1; } /* check for port */ if (*s == '[' && *(e-1) == ']') { /* Short circuit portscan, we're dealing with an IPv6 embedded address */ p = s; } else { /* memrchr is a GNU specific extension Emulate for wide compatability */ for(p = e; *p != ':' && p >= s; p--); } if (p >= s && *p == ':') { if (!ret->port) { p++; if (e-p > 5) { /* port cannot be longer then 5 characters */ STR_FREE(ret->scheme); STR_FREE(ret->user); STR_FREE(ret->pass); efree(ret); return NULL; } else if (e - p > 0) { long port; memcpy(port_buf, p, (e - p)); port_buf[e - p] = '\0'; port = strtol(port_buf, NULL, 10); if (port > 0 && port <= 65535) { ret->port = (unsigned short)port; } else { STR_FREE(ret->scheme); STR_FREE(ret->user); STR_FREE(ret->pass); efree(ret); return NULL; } } p--; } } else { p = e; } /* check if we have a valid host, if we don't reject the string as url */ if ((p-s) < 1) { STR_FREE(ret->scheme); STR_FREE(ret->user); STR_FREE(ret->pass); efree(ret); return NULL; } ret->host = estrndup(s, (p-s)); php_replace_controlchars_ex(ret->host, (p - s)); if (e == ue) { return ret; } s = e; nohost: if ((p = memchr(s, '?', (ue - s)))) { pp = strchr(s, '#'); if (pp && pp < p) { if (pp - s) { ret->path = estrndup(s, (pp-s)); php_replace_controlchars_ex(ret->path, (pp - s)); } p = pp; goto label_parse; } if (p - s) { ret->path = estrndup(s, (p-s)); php_replace_controlchars_ex(ret->path, (p - s)); } if (pp) { if (pp - ++p) { ret->query = estrndup(p, (pp-p)); php_replace_controlchars_ex(ret->query, (pp - p)); } p = pp; goto label_parse; } else if (++p - ue) { ret->query = estrndup(p, (ue-p)); php_replace_controlchars_ex(ret->query, (ue - p)); } } else if ((p = memchr(s, '#', (ue - s)))) { if (p - s) { ret->path = estrndup(s, (p-s)); php_replace_controlchars_ex(ret->path, (p - s)); } label_parse: p++; if (ue - p) { ret->fragment = estrndup(p, (ue-p)); php_replace_controlchars_ex(ret->fragment, (ue - p)); } } else { ret->path = estrndup(s, (ue-s)); php_replace_controlchars_ex(ret->path, (ue - s)); } end: return ret; } /* }}} */ /* {{{ proto mixed parse_url(string url, [int url_component]) Parse a URL and return its components */ PHP_FUNCTION(parse_url) { char *str; int str_len; php_url *resource; long key = -1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &str, &str_len, &key) == FAILURE) { return; } resource = php_url_parse_ex(str, str_len); if (resource == NULL) { /* @todo Find a method to determine why php_url_parse_ex() failed */ RETURN_FALSE; } if (key > -1) { switch (key) { case PHP_URL_SCHEME: if (resource->scheme != NULL) RETVAL_STRING(resource->scheme, 1); break; case PHP_URL_HOST: if (resource->host != NULL) RETVAL_STRING(resource->host, 1); break; case PHP_URL_PORT: if (resource->port != 0) RETVAL_LONG(resource->port); break; case PHP_URL_USER: if (resource->user != NULL) RETVAL_STRING(resource->user, 1); break; case PHP_URL_PASS: if (resource->pass != NULL) RETVAL_STRING(resource->pass, 1); break; case PHP_URL_PATH: if (resource->path != NULL) RETVAL_STRING(resource->path, 1); break; case PHP_URL_QUERY: if (resource->query != NULL) RETVAL_STRING(resource->query, 1); break; case PHP_URL_FRAGMENT: if (resource->fragment != NULL) RETVAL_STRING(resource->fragment, 1); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid URL component identifier %ld", key); RETVAL_FALSE; } goto done; } /* allocate an array for return */ array_init(return_value); /* add the various elements to the array */ if (resource->scheme != NULL) add_assoc_string(return_value, "scheme", resource->scheme, 1); if (resource->host != NULL) add_assoc_string(return_value, "host", resource->host, 1); if (resource->port != 0) add_assoc_long(return_value, "port", resource->port); if (resource->user != NULL) add_assoc_string(return_value, "user", resource->user, 1); if (resource->pass != NULL) add_assoc_string(return_value, "pass", resource->pass, 1); if (resource->path != NULL) add_assoc_string(return_value, "path", resource->path, 1); if (resource->query != NULL) add_assoc_string(return_value, "query", resource->query, 1); if (resource->fragment != NULL) add_assoc_string(return_value, "fragment", resource->fragment, 1); done: php_url_free(resource); } /* }}} */ /* {{{ php_htoi */ static int php_htoi(char *s) { int value; int c; c = ((unsigned char *)s)[0]; if (isupper(c)) c = tolower(c); value = (c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10) * 16; c = ((unsigned char *)s)[1]; if (isupper(c)) c = tolower(c); value += c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10; return (value); } /* }}} */ /* rfc1738: ...The characters ";", "/", "?", ":", "@", "=" and "&" are the characters which may be reserved for special meaning within a scheme... ...Thus, only alphanumerics, the special characters "$-_.+!*'(),", and reserved characters used for their reserved purposes may be used unencoded within a URL... For added safety, we only leave -_. unencoded. */ static unsigned char hexchars[] = "0123456789ABCDEF"; /* {{{ php_url_encode */ PHPAPI char *php_url_encode(char const *s, int len, int *new_length) { register unsigned char c; unsigned char *to, *start; unsigned char const *from, *end; from = (unsigned char *)s; end = (unsigned char *)s + len; start = to = (unsigned char *) safe_emalloc(3, len, 1); while (from < end) { c = *from++; if (c == ' ') { *to++ = '+'; #ifndef CHARSET_EBCDIC } else if ((c < '0' && c != '-' && c != '.') || (c < 'A' && c > '9') || (c > 'Z' && c < 'a' && c != '_') || (c > 'z')) { to[0] = '%'; to[1] = hexchars[c >> 4]; to[2] = hexchars[c & 15]; to += 3; #else /*CHARSET_EBCDIC*/ } else if (!isalnum(c) && strchr("_-.", c) == NULL) { /* Allow only alphanumeric chars and '_', '-', '.'; escape the rest */ to[0] = '%'; to[1] = hexchars[os_toascii[c] >> 4]; to[2] = hexchars[os_toascii[c] & 15]; to += 3; #endif /*CHARSET_EBCDIC*/ } else { *to++ = c; } } *to = 0; if (new_length) { *new_length = to - start; } return (char *) start; } /* }}} */ /* {{{ proto string urlencode(string str) URL-encodes string */ PHP_FUNCTION(urlencode) { char *in_str, *out_str; int in_str_len, out_str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str, &in_str_len) == FAILURE) { return; } out_str = php_url_encode(in_str, in_str_len, &out_str_len); RETURN_STRINGL(out_str, out_str_len, 0); } /* }}} */ /* {{{ proto string urldecode(string str) Decodes URL-encoded string */ PHP_FUNCTION(urldecode) { char *in_str, *out_str; int in_str_len, out_str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str, &in_str_len) == FAILURE) { return; } out_str = estrndup(in_str, in_str_len); out_str_len = php_url_decode(out_str, in_str_len); RETURN_STRINGL(out_str, out_str_len, 0); } /* }}} */ /* {{{ php_url_decode */ PHPAPI int php_url_decode(char *str, int len) { char *dest = str; char *data = str; while (len--) { if (*data == '+') { *dest = ' '; } else if (*data == '%' && len >= 2 && isxdigit((int) *(data + 1)) && isxdigit((int) *(data + 2))) { #ifndef CHARSET_EBCDIC *dest = (char) php_htoi(data + 1); #else *dest = os_toebcdic[(char) php_htoi(data + 1)]; #endif data += 2; len -= 2; } else { *dest = *data; } data++; dest++; } *dest = '\0'; return dest - str; } /* }}} */ /* {{{ php_raw_url_encode */ PHPAPI char *php_raw_url_encode(char const *s, int len, int *new_length) { register int x, y; unsigned char *str; str = (unsigned char *) safe_emalloc(3, len, 1); for (x = 0, y = 0; len--; x++, y++) { str[y] = (unsigned char) s[x]; #ifndef CHARSET_EBCDIC if ((str[y] < '0' && str[y] != '-' && str[y] != '.') || (str[y] < 'A' && str[y] > '9') || (str[y] > 'Z' && str[y] < 'a' && str[y] != '_') || (str[y] > 'z' && str[y] != '~')) { str[y++] = '%'; str[y++] = hexchars[(unsigned char) s[x] >> 4]; str[y] = hexchars[(unsigned char) s[x] & 15]; #else /*CHARSET_EBCDIC*/ if (!isalnum(str[y]) && strchr("_-.~", str[y]) != NULL) { str[y++] = '%'; str[y++] = hexchars[os_toascii[(unsigned char) s[x]] >> 4]; str[y] = hexchars[os_toascii[(unsigned char) s[x]] & 15]; #endif /*CHARSET_EBCDIC*/ } } str[y] = '\0'; if (new_length) { *new_length = y; } return ((char *) str); } /* }}} */ /* {{{ proto string rawurlencode(string str) URL-encodes string */ PHP_FUNCTION(rawurlencode) { char *in_str, *out_str; int in_str_len, out_str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str, &in_str_len) == FAILURE) { return; } out_str = php_raw_url_encode(in_str, in_str_len, &out_str_len); RETURN_STRINGL(out_str, out_str_len, 0); } /* }}} */ /* {{{ proto string rawurldecode(string str) Decodes URL-encodes string */ PHP_FUNCTION(rawurldecode) { char *in_str, *out_str; int in_str_len, out_str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str, &in_str_len) == FAILURE) { return; } out_str = estrndup(in_str, in_str_len); out_str_len = php_raw_url_decode(out_str, in_str_len); RETURN_STRINGL(out_str, out_str_len, 0); } /* }}} */ /* {{{ php_raw_url_decode */ PHPAPI int php_raw_url_decode(char *str, int len) { char *dest = str; char *data = str; while (len--) { if (*data == '%' && len >= 2 && isxdigit((int) *(data + 1)) && isxdigit((int) *(data + 2))) { #ifndef CHARSET_EBCDIC *dest = (char) php_htoi(data + 1); #else *dest = os_toebcdic[(char) php_htoi(data + 1)]; #endif data += 2; len -= 2; } else { *dest = *data; } data++; dest++; } *dest = '\0'; return dest - str; } /* }}} */ /* {{{ proto array get_headers(string url[, int format]) fetches all the headers sent by the server in response to a HTTP request */ PHP_FUNCTION(get_headers) { char *url; int url_len; php_stream_context *context; php_stream *stream; zval **prev_val, **hdr = NULL, **h; HashPosition pos; HashTable *hashT; long format = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &url, &url_len, &format) == FAILURE) { return; } context = FG(default_context) ? FG(default_context) : (FG(default_context) = php_stream_context_alloc(TSRMLS_C)); if (!(stream = php_stream_open_wrapper_ex(url, "r", REPORT_ERRORS | STREAM_USE_URL | STREAM_ONLY_GET_HEADERS, NULL, context))) { RETURN_FALSE; } if (!stream->wrapperdata || Z_TYPE_P(stream->wrapperdata) != IS_ARRAY) { php_stream_close(stream); RETURN_FALSE; } array_init(return_value); /* check for curl-wrappers that provide headers via a special "headers" element */ if (zend_hash_find(HASH_OF(stream->wrapperdata), "headers", sizeof("headers"), (void **)&h) != FAILURE && Z_TYPE_PP(h) == IS_ARRAY) { /* curl-wrappers don't load data until the 1st read */ if (!Z_ARRVAL_PP(h)->nNumOfElements) { php_stream_getc(stream); } zend_hash_find(HASH_OF(stream->wrapperdata), "headers", sizeof("headers"), (void **)&h); hashT = Z_ARRVAL_PP(h); } else { hashT = HASH_OF(stream->wrapperdata); } zend_hash_internal_pointer_reset_ex(hashT, &pos); while (zend_hash_get_current_data_ex(hashT, (void**)&hdr, &pos) != FAILURE) { if (!hdr || Z_TYPE_PP(hdr) != IS_STRING) { zend_hash_move_forward_ex(hashT, &pos); continue; } if (!format) { no_name_header: add_next_index_stringl(return_value, Z_STRVAL_PP(hdr), Z_STRLEN_PP(hdr), 1); } else { char c; char *s, *p; if ((p = strchr(Z_STRVAL_PP(hdr), ':'))) { c = *p; *p = '\0'; s = p + 1; while (isspace((int)*(unsigned char *)s)) { s++; } if (zend_hash_find(HASH_OF(return_value), Z_STRVAL_PP(hdr), (p - Z_STRVAL_PP(hdr) + 1), (void **) &prev_val) == FAILURE) { add_assoc_stringl_ex(return_value, Z_STRVAL_PP(hdr), (p - Z_STRVAL_PP(hdr) + 1), s, (Z_STRLEN_PP(hdr) - (s - Z_STRVAL_PP(hdr))), 1); } else { /* some headers may occur more then once, therefor we need to remake the string into an array */ convert_to_array(*prev_val); add_next_index_stringl(*prev_val, s, (Z_STRLEN_PP(hdr) - (s - Z_STRVAL_PP(hdr))), 1); } *p = c; } else { goto no_name_header; } } zend_hash_move_forward_ex(hashT, &pos); } php_stream_close(stream); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-03-11-d890ece3fc-6e74d95f34.c
manybugs_data_9
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2012 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Sascha Schumann <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "php.h" #include "php_session.h" #include "mod_user.h" ps_module ps_mod_user = { PS_MOD(user) }; #define SESS_ZVAL_LONG(val, a) \ { \ MAKE_STD_ZVAL(a); \ ZVAL_LONG(a, val); \ } #define SESS_ZVAL_STRING(vl, a) \ { \ char *__vl = vl; \ SESS_ZVAL_STRINGN(__vl, strlen(__vl), a); \ } #define SESS_ZVAL_STRINGN(vl, ln, a) \ { \ MAKE_STD_ZVAL(a); \ ZVAL_STRINGL(a, vl, ln, 1); \ } static zval *ps_call_handler(zval *func, int argc, zval **argv TSRMLS_DC) { int i; zval *retval = NULL; MAKE_STD_ZVAL(retval); if (call_user_function(EG(function_table), NULL, func, retval, argc, argv TSRMLS_CC) == FAILURE) { zval_ptr_dtor(&retval); retval = NULL; } for (i = 0; i < argc; i++) { zval_ptr_dtor(&argv[i]); } return retval; } #define STDVARS \ zval *retval; \ int ret = FAILURE #define PSF(a) PS(mod_user_names).name.ps_##a #define FINISH \ if (retval) { \ convert_to_long(retval); \ ret = Z_LVAL_P(retval); \ zval_ptr_dtor(&retval); \ } \ return ret PS_OPEN_FUNC(user) { zval *args[2]; STDVARS; SESS_ZVAL_STRING((char*)save_path, args[0]); SESS_ZVAL_STRING((char*)session_name, args[1]); retval = ps_call_handler(PSF(open), 2, args TSRMLS_CC); PS(mod_user_implemented) = 1; FINISH; } PS_CLOSE_FUNC(user) { STDVARS; if (!PS(mod_user_implemented)) { /* already closed */ return SUCCESS; } retval = ps_call_handler(PSF(close), 0, NULL TSRMLS_CC); PS(mod_user_implemented) = 0; FINISH; } PS_READ_FUNC(user) { zval *args[1]; STDVARS; SESS_ZVAL_STRING((char*)key, args[0]); retval = ps_call_handler(PSF(read), 1, args TSRMLS_CC); if (retval) { if (Z_TYPE_P(retval) == IS_STRING) { *val = estrndup(Z_STRVAL_P(retval), Z_STRLEN_P(retval)); *vallen = Z_STRLEN_P(retval); ret = SUCCESS; } zval_ptr_dtor(&retval); } return ret; } PS_WRITE_FUNC(user) { zval *args[2]; STDVARS; SESS_ZVAL_STRING((char*)key, args[0]); SESS_ZVAL_STRINGN((char*)val, vallen, args[1]); retval = ps_call_handler(PSF(write), 2, args TSRMLS_CC); FINISH; } PS_DESTROY_FUNC(user) { zval *args[1]; STDVARS; SESS_ZVAL_STRING((char*)key, args[0]); retval = ps_call_handler(PSF(destroy), 1, args TSRMLS_CC); FINISH; } PS_GC_FUNC(user) { zval *args[1]; STDVARS; SESS_ZVAL_LONG(maxlifetime, args[0]); retval = ps_call_handler(PSF(gc), 1, args TSRMLS_CC); FINISH; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2012 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Sascha Schumann <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "php.h" #include "php_session.h" #include "mod_user.h" ps_module ps_mod_user = { PS_MOD(user) }; #define SESS_ZVAL_LONG(val, a) \ { \ MAKE_STD_ZVAL(a); \ ZVAL_LONG(a, val); \ } #define SESS_ZVAL_STRING(vl, a) \ { \ char *__vl = vl; \ SESS_ZVAL_STRINGN(__vl, strlen(__vl), a); \ } #define SESS_ZVAL_STRINGN(vl, ln, a) \ { \ MAKE_STD_ZVAL(a); \ ZVAL_STRINGL(a, vl, ln, 1); \ } static zval *ps_call_handler(zval *func, int argc, zval **argv TSRMLS_DC) { int i; zval *retval = NULL; MAKE_STD_ZVAL(retval); if (call_user_function(EG(function_table), NULL, func, retval, argc, argv TSRMLS_CC) == FAILURE) { zval_ptr_dtor(&retval); retval = NULL; } for (i = 0; i < argc; i++) { zval_ptr_dtor(&argv[i]); } return retval; } #define STDVARS \ zval *retval; \ int ret = FAILURE #define PSF(a) PS(mod_user_names).name.ps_##a #define FINISH \ if (retval) { \ convert_to_long(retval); \ ret = Z_LVAL_P(retval); \ zval_ptr_dtor(&retval); \ } \ return ret PS_OPEN_FUNC(user) { zval *args[2]; STDVARS; if (PSF(open) == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "user session functions not defined"); return FAILURE; } SESS_ZVAL_STRING((char*)save_path, args[0]); SESS_ZVAL_STRING((char*)session_name, args[1]); retval = ps_call_handler(PSF(open), 2, args TSRMLS_CC); PS(mod_user_implemented) = 1; FINISH; } PS_CLOSE_FUNC(user) { STDVARS; if (!PS(mod_user_implemented)) { /* already closed */ return SUCCESS; } retval = ps_call_handler(PSF(close), 0, NULL TSRMLS_CC); PS(mod_user_implemented) = 0; FINISH; } PS_READ_FUNC(user) { zval *args[1]; STDVARS; SESS_ZVAL_STRING((char*)key, args[0]); retval = ps_call_handler(PSF(read), 1, args TSRMLS_CC); if (retval) { if (Z_TYPE_P(retval) == IS_STRING) { *val = estrndup(Z_STRVAL_P(retval), Z_STRLEN_P(retval)); *vallen = Z_STRLEN_P(retval); ret = SUCCESS; } zval_ptr_dtor(&retval); } return ret; } PS_WRITE_FUNC(user) { zval *args[2]; STDVARS; SESS_ZVAL_STRING((char*)key, args[0]); SESS_ZVAL_STRINGN((char*)val, vallen, args[1]); retval = ps_call_handler(PSF(write), 2, args TSRMLS_CC); FINISH; } PS_DESTROY_FUNC(user) { zval *args[1]; STDVARS; SESS_ZVAL_STRING((char*)key, args[0]); retval = ps_call_handler(PSF(destroy), 1, args TSRMLS_CC); FINISH; } PS_GC_FUNC(user) { zval *args[1]; STDVARS; SESS_ZVAL_LONG(maxlifetime, args[0]); retval = ps_call_handler(PSF(gc), 1, args TSRMLS_CC); FINISH; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2012-01-27-544e36dfff-acaf9c5227.c
manybugs_data_10
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Marcus Boerger <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" #include "ext/standard/file.h" #include "ext/standard/php_string.h" #include "zend_compile.h" #include "zend_exceptions.h" #include "zend_interfaces.h" #include "php_spl.h" #include "spl_functions.h" #include "spl_engine.h" #include "spl_iterators.h" #include "spl_directory.h" #include "spl_exceptions.h" #include "php.h" #include "fopen_wrappers.h" #include "ext/standard/basic_functions.h" #include "ext/standard/php_filestat.h" #define SPL_HAS_FLAG(flags, test_flag) ((flags & test_flag) ? 1 : 0) /* declare the class handlers */ static zend_object_handlers spl_filesystem_object_handlers; /* decalre the class entry */ PHPAPI zend_class_entry *spl_ce_SplFileInfo; PHPAPI zend_class_entry *spl_ce_DirectoryIterator; PHPAPI zend_class_entry *spl_ce_FilesystemIterator; PHPAPI zend_class_entry *spl_ce_RecursiveDirectoryIterator; PHPAPI zend_class_entry *spl_ce_GlobIterator; PHPAPI zend_class_entry *spl_ce_SplFileObject; PHPAPI zend_class_entry *spl_ce_SplTempFileObject; static void spl_filesystem_file_free_line(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { if (intern->u.file.current_line) { efree(intern->u.file.current_line); intern->u.file.current_line = NULL; } if (intern->u.file.current_zval) { zval_ptr_dtor(&intern->u.file.current_zval); intern->u.file.current_zval = NULL; } } /* }}} */ static void spl_filesystem_object_free_storage(void *object TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern = (spl_filesystem_object*)object; if (intern->oth_handler && intern->oth_handler->dtor) { intern->oth_handler->dtor(intern TSRMLS_CC); } zend_object_std_dtor(&intern->std TSRMLS_CC); if (intern->_path) { efree(intern->_path); } if (intern->file_name) { efree(intern->file_name); } switch(intern->type) { case SPL_FS_INFO: break; case SPL_FS_DIR: if (intern->u.dir.dirp) { php_stream_close(intern->u.dir.dirp); intern->u.dir.dirp = NULL; } if (intern->u.dir.sub_path) { efree(intern->u.dir.sub_path); } break; case SPL_FS_FILE: if (intern->u.file.stream) { if (intern->u.file.zcontext) { /* zend_list_delref(Z_RESVAL_P(intern->zcontext));*/ } if (!intern->u.file.stream->is_persistent) { php_stream_free(intern->u.file.stream, PHP_STREAM_FREE_CLOSE); } else { php_stream_free(intern->u.file.stream, PHP_STREAM_FREE_CLOSE_PERSISTENT); } if (intern->u.file.open_mode) { efree(intern->u.file.open_mode); } if (intern->orig_path) { efree(intern->orig_path); } } spl_filesystem_file_free_line(intern TSRMLS_CC); break; } efree(object); } /* }}} */ /* {{{ spl_ce_dir_object_new */ /* creates the object by - allocating memory - initializing the object members - storing the object - setting it's handlers called from - clone - new */ static zend_object_value spl_filesystem_object_new_ex(zend_class_entry *class_type, spl_filesystem_object **obj TSRMLS_DC) { zend_object_value retval; spl_filesystem_object *intern; intern = emalloc(sizeof(spl_filesystem_object)); memset(intern, 0, sizeof(spl_filesystem_object)); /* intern->type = SPL_FS_INFO; done by set 0 */ intern->file_class = spl_ce_SplFileObject; intern->info_class = spl_ce_SplFileInfo; if (obj) *obj = intern; zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, (zend_objects_free_object_storage_t) spl_filesystem_object_free_storage, NULL TSRMLS_CC); retval.handlers = &spl_filesystem_object_handlers; return retval; } /* }}} */ /* {{{ spl_filesystem_object_new */ /* See spl_filesystem_object_new_ex */ static zend_object_value spl_filesystem_object_new(zend_class_entry *class_type TSRMLS_DC) { return spl_filesystem_object_new_ex(class_type, NULL TSRMLS_CC); } /* }}} */ PHPAPI char* spl_filesystem_object_get_path(spl_filesystem_object *intern, int *len TSRMLS_DC) /* {{{ */ { #ifdef HAVE_GLOB if (intern->type == SPL_FS_DIR) { if (php_stream_is(intern->u.dir.dirp ,&php_glob_stream_ops)) { return php_glob_stream_get_path(intern->u.dir.dirp, 0, len); } } #endif if (len) { *len = intern->_path_len; } return intern->_path; } /* }}} */ static inline void spl_filesystem_object_get_file_name(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH; if (!intern->file_name) { switch (intern->type) { case SPL_FS_INFO: case SPL_FS_FILE: php_error_docref(NULL TSRMLS_CC, E_ERROR, "Object not initialized"); break; case SPL_FS_DIR: intern->file_name_len = spprintf(&intern->file_name, 0, "%s%c%s", spl_filesystem_object_get_path(intern, NULL TSRMLS_CC), slash, intern->u.dir.entry.d_name); break; } } } /* }}} */ static int spl_filesystem_dir_read(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { if (!intern->u.dir.dirp || !php_stream_readdir(intern->u.dir.dirp, &intern->u.dir.entry)) { intern->u.dir.entry.d_name[0] = '\0'; return 0; } else { return 1; } } /* }}} */ #define IS_SLASH_AT(zs, pos) (IS_SLASH(zs[pos])) static inline int spl_filesystem_is_dot(const char * d_name) /* {{{ */ { return !strcmp(d_name, ".") || !strcmp(d_name, ".."); } /* }}} */ /* {{{ spl_filesystem_dir_open */ /* open a directory resource */ static void spl_filesystem_dir_open(spl_filesystem_object* intern, char *path TSRMLS_DC) { int skip_dots = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_SKIPDOTS); intern->type = SPL_FS_DIR; intern->_path_len = strlen(path); intern->u.dir.dirp = php_stream_opendir(path, REPORT_ERRORS, NULL); if (intern->_path_len > 1 && IS_SLASH_AT(path, intern->_path_len-1)) { intern->_path = estrndup(path, --intern->_path_len); } else { intern->_path = estrndup(path, intern->_path_len); } intern->u.dir.index = 0; if (EG(exception) || intern->u.dir.dirp == NULL) { /* throw exception: should've been already happened */ intern->u.dir.entry.d_name[0] = '\0'; } else { do { spl_filesystem_dir_read(intern TSRMLS_CC); } while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name)); } } /* }}} */ static int spl_filesystem_file_open(spl_filesystem_object *intern, int use_include_path, int silent TSRMLS_DC) /* {{{ */ { intern->type = SPL_FS_FILE; intern->u.file.context = php_stream_context_from_zval(intern->u.file.zcontext, 0); intern->u.file.stream = php_stream_open_wrapper_ex(intern->file_name, intern->u.file.open_mode, (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, intern->u.file.context); if (!intern->file_name_len || !intern->u.file.stream) { if (!EG(exception)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot open file '%s'", intern->file_name_len ? intern->file_name : ""); } intern->file_name = NULL; /* until here it is not a copy */ intern->u.file.open_mode = NULL; return FAILURE; } if (intern->u.file.zcontext) { zend_list_addref(Z_RESVAL_P(intern->u.file.zcontext)); } if (intern->file_name_len > 1 && IS_SLASH_AT(intern->file_name, intern->file_name_len-1)) { intern->file_name_len--; } intern->orig_path = estrndup(intern->u.file.stream->orig_path, strlen(intern->u.file.stream->orig_path)); intern->file_name = estrndup(intern->file_name, intern->file_name_len); intern->u.file.open_mode = estrndup(intern->u.file.open_mode, intern->u.file.open_mode_len); /* avoid reference counting in debug mode, thus do it manually */ ZVAL_RESOURCE(&intern->u.file.zresource, php_stream_get_resource_id(intern->u.file.stream)); Z_SET_REFCOUNT(intern->u.file.zresource, 1); intern->u.file.delimiter = ','; intern->u.file.enclosure = '"'; intern->u.file.escape = '\\'; zend_hash_find(&intern->std.ce->function_table, "getcurrentline", sizeof("getcurrentline"), (void **) &intern->u.file.func_getCurr); return SUCCESS; } /* }}} */ /* {{{ spl_filesystem_object_clone */ /* Local zend_object_value creation (on stack) Load the 'other' object Create a new empty object (See spl_filesystem_object_new_ex) Open the directory Clone other members (properties) */ static zend_object_value spl_filesystem_object_clone(zval *zobject TSRMLS_DC) { zend_object_value new_obj_val; zend_object *old_object; zend_object *new_object; zend_object_handle handle = Z_OBJ_HANDLE_P(zobject); spl_filesystem_object *intern; spl_filesystem_object *source; int index, skip_dots; old_object = zend_objects_get_address(zobject TSRMLS_CC); source = (spl_filesystem_object*)old_object; new_obj_val = spl_filesystem_object_new_ex(old_object->ce, &intern TSRMLS_CC); new_object = &intern->std; intern->flags = source->flags; switch (source->type) { case SPL_FS_INFO: intern->_path_len = source->_path_len; intern->_path = estrndup(source->_path, source->_path_len); intern->file_name_len = source->file_name_len; intern->file_name = estrndup(source->file_name, intern->file_name_len); break; case SPL_FS_DIR: spl_filesystem_dir_open(intern, source->_path TSRMLS_CC); /* read until we hit the position in which we were before */ skip_dots = SPL_HAS_FLAG(source->flags, SPL_FILE_DIR_SKIPDOTS); for(index = 0; index < source->u.dir.index; ++index) { do { spl_filesystem_dir_read(intern TSRMLS_CC); } while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name)); } intern->u.dir.index = index; break; case SPL_FS_FILE: php_error_docref(NULL TSRMLS_CC, E_ERROR, "An object of class %s cannot be cloned", old_object->ce->name); break; } intern->file_class = source->file_class; intern->info_class = source->info_class; intern->oth = source->oth; intern->oth_handler = source->oth_handler; zend_objects_clone_members(new_object, new_obj_val, old_object, handle TSRMLS_CC); if (intern->oth_handler && intern->oth_handler->clone) { intern->oth_handler->clone(source, intern TSRMLS_CC); } return new_obj_val; } /* }}} */ void spl_filesystem_info_set_filename(spl_filesystem_object *intern, char *path, int len, int use_copy TSRMLS_DC) /* {{{ */ { char *p1, *p2; intern->file_name = use_copy ? estrndup(path, len) : path; intern->file_name_len = len; while(IS_SLASH_AT(intern->file_name, intern->file_name_len-1) && intern->file_name_len > 1) { intern->file_name[intern->file_name_len-1] = 0; intern->file_name_len--; } p1 = strrchr(intern->file_name, '/'); #if defined(PHP_WIN32) || defined(NETWARE) p2 = strrchr(intern->file_name, '\\'); #else p2 = 0; #endif if (p1 || p2) { intern->_path_len = (p1 > p2 ? p1 : p2) - intern->file_name; } else { intern->_path_len = 0; } intern->_path = estrndup(path, intern->_path_len); } /* }}} */ static spl_filesystem_object * spl_filesystem_object_create_info(spl_filesystem_object *source, char *file_path, int file_path_len, int use_copy, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern; zval *arg1; zend_error_handling error_handling; if (!file_path || !file_path_len) { #if defined(PHP_WIN32) zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot create SplFileInfo for empty path"); if (file_path && !use_copy) { efree(file_path); } #else if (file_path && !use_copy) { efree(file_path); } use_copy = 1; file_path_len = 1; file_path = "/"; #endif return NULL; } zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); ce = ce ? ce : source->info_class; zend_update_class_constants(ce TSRMLS_CC); return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); Z_TYPE_P(return_value) = IS_OBJECT; if (ce->constructor->common.scope != spl_ce_SplFileInfo) { MAKE_STD_ZVAL(arg1); ZVAL_STRINGL(arg1, file_path, file_path_len, use_copy); zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1); zval_ptr_dtor(&arg1); } else { spl_filesystem_info_set_filename(intern, file_path, file_path_len, use_copy TSRMLS_CC); } zend_restore_error_handling(&error_handling TSRMLS_CC); return intern; } /* }}} */ static spl_filesystem_object * spl_filesystem_object_create_type(int ht, spl_filesystem_object *source, int type, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern; zend_bool use_include_path = 0; zval *arg1, *arg2; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); switch (source->type) { case SPL_FS_INFO: case SPL_FS_FILE: break; case SPL_FS_DIR: if (!source->u.dir.entry.d_name[0]) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Could not open file"); zend_restore_error_handling(&error_handling TSRMLS_CC); return NULL; } } switch (type) { case SPL_FS_INFO: ce = ce ? ce : source->info_class; zend_update_class_constants(ce TSRMLS_CC); return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); Z_TYPE_P(return_value) = IS_OBJECT; spl_filesystem_object_get_file_name(source TSRMLS_CC); if (ce->constructor->common.scope != spl_ce_SplFileInfo) { MAKE_STD_ZVAL(arg1); ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1); zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1); zval_ptr_dtor(&arg1); } else { intern->file_name = estrndup(source->file_name, source->file_name_len); intern->file_name_len = source->file_name_len; intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC); intern->_path = estrndup(intern->_path, intern->_path_len); } break; case SPL_FS_FILE: ce = ce ? ce : source->file_class; zend_update_class_constants(ce TSRMLS_CC); return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); Z_TYPE_P(return_value) = IS_OBJECT; spl_filesystem_object_get_file_name(source TSRMLS_CC); if (ce->constructor->common.scope != spl_ce_SplFileObject) { MAKE_STD_ZVAL(arg1); MAKE_STD_ZVAL(arg2); ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1); ZVAL_STRINGL(arg2, "r", 1, 1); zend_call_method_with_2_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1, arg2); zval_ptr_dtor(&arg1); zval_ptr_dtor(&arg2); } else { intern->file_name = source->file_name; intern->file_name_len = source->file_name_len; intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC); intern->_path = estrndup(intern->_path, intern->_path_len); intern->u.file.open_mode = "r"; intern->u.file.open_mode_len = 1; if (ht && zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sbr", &intern->u.file.open_mode, &intern->u.file.open_mode_len, &use_include_path, &intern->u.file.zcontext) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); intern->u.file.open_mode = NULL; intern->file_name = NULL; zval_dtor(return_value); Z_TYPE_P(return_value) = IS_NULL; return NULL; } if (spl_filesystem_file_open(intern, use_include_path, 0 TSRMLS_CC) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); zval_dtor(return_value); Z_TYPE_P(return_value) = IS_NULL; return NULL; } } break; case SPL_FS_DIR: zend_restore_error_handling(&error_handling TSRMLS_CC); zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Operation not supported"); return NULL; } zend_restore_error_handling(&error_handling TSRMLS_CC); return NULL; } /* }}} */ static int spl_filesystem_is_invalid_or_dot(const char * d_name) /* {{{ */ { return d_name[0] == '\0' || spl_filesystem_is_dot(d_name); } /* }}} */ static char *spl_filesystem_object_get_pathname(spl_filesystem_object *intern, int *len TSRMLS_DC) { /* {{{ */ switch (intern->type) { case SPL_FS_INFO: case SPL_FS_FILE: *len = intern->file_name_len; return intern->file_name; case SPL_FS_DIR: if (intern->u.dir.entry.d_name[0]) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); *len = intern->file_name_len; return intern->file_name; } } *len = 0; return NULL; } /* }}} */ static HashTable* spl_filesystem_object_get_debug_info(zval *obj, int *is_temp TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(obj TSRMLS_CC); HashTable *rv; zval *tmp, zrv; char *pnstr, *path; int pnlen, path_len; char stmp[2]; *is_temp = 1; if (!intern->std.properties) { rebuild_object_properties(&intern->std); } ALLOC_HASHTABLE(rv); ZEND_INIT_SYMTABLE_EX(rv, zend_hash_num_elements(intern->std.properties) + 3, 0); INIT_PZVAL(&zrv); Z_ARRVAL(zrv) = rv; zend_hash_copy(rv, intern->std.properties, (copy_ctor_func_t) zval_add_ref, (void *) &tmp, sizeof(zval *)); pnstr = spl_gen_private_prop_name(spl_ce_SplFileInfo, "pathName", sizeof("pathName")-1, &pnlen TSRMLS_CC); path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC); add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, path, path_len, 1); efree(pnstr); if (intern->file_name) { pnstr = spl_gen_private_prop_name(spl_ce_SplFileInfo, "fileName", sizeof("fileName")-1, &pnlen TSRMLS_CC); spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); if (path_len && path_len < intern->file_name_len) { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->file_name + path_len + 1, intern->file_name_len - (path_len + 1), 1); } else { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->file_name, intern->file_name_len, 1); } efree(pnstr); } if (intern->type == SPL_FS_DIR) { #ifdef HAVE_GLOB pnstr = spl_gen_private_prop_name(spl_ce_DirectoryIterator, "glob", sizeof("glob")-1, &pnlen TSRMLS_CC); if (php_stream_is(intern->u.dir.dirp ,&php_glob_stream_ops)) { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->_path, intern->_path_len, 1); } else { add_assoc_bool_ex(&zrv, pnstr, pnlen+1, 0); } efree(pnstr); #endif pnstr = spl_gen_private_prop_name(spl_ce_RecursiveDirectoryIterator, "subPathName", sizeof("subPathName")-1, &pnlen TSRMLS_CC); if (intern->u.dir.sub_path) { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->u.dir.sub_path, intern->u.dir.sub_path_len, 1); } else { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, "", 0, 1); } efree(pnstr); } if (intern->type == SPL_FS_FILE) { pnstr = spl_gen_private_prop_name(spl_ce_SplFileObject, "openMode", sizeof("openMode")-1, &pnlen TSRMLS_CC); add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->u.file.open_mode, intern->u.file.open_mode_len, 1); efree(pnstr); stmp[1] = '\0'; stmp[0] = intern->u.file.delimiter; pnstr = spl_gen_private_prop_name(spl_ce_SplFileObject, "delimiter", sizeof("delimiter")-1, &pnlen TSRMLS_CC); add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, stmp, 1, 1); efree(pnstr); stmp[0] = intern->u.file.enclosure; pnstr = spl_gen_private_prop_name(spl_ce_SplFileObject, "enclosure", sizeof("enclosure")-1, &pnlen TSRMLS_CC); add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, stmp, 1, 1); efree(pnstr); } return rv; } /* }}} */ #define DIT_CTOR_FLAGS 0x00000001 #define DIT_CTOR_GLOB 0x00000002 void spl_filesystem_object_construct(INTERNAL_FUNCTION_PARAMETERS, long ctor_flags) /* {{{ */ { spl_filesystem_object *intern; char *path; int parsed, len; long flags; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (SPL_HAS_FLAG(ctor_flags, DIT_CTOR_FLAGS)) { flags = SPL_FILE_DIR_KEY_AS_PATHNAME|SPL_FILE_DIR_CURRENT_AS_FILEINFO; parsed = zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &path, &len, &flags); } else { flags = SPL_FILE_DIR_KEY_AS_PATHNAME|SPL_FILE_DIR_CURRENT_AS_SELF; parsed = zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &path, &len); } if (SPL_HAS_FLAG(ctor_flags, SPL_FILE_DIR_SKIPDOTS)) { flags |= SPL_FILE_DIR_SKIPDOTS; } if (SPL_HAS_FLAG(ctor_flags, SPL_FILE_DIR_UNIXPATHS)) { flags |= SPL_FILE_DIR_UNIXPATHS; } if (parsed == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (!len) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Directory name must not be empty."); zend_restore_error_handling(&error_handling TSRMLS_CC); return; } intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); intern->flags = flags; #ifdef HAVE_GLOB if (SPL_HAS_FLAG(ctor_flags, DIT_CTOR_GLOB) && strstr(path, "glob://") != path) { spprintf(&path, 0, "glob://%s", path); spl_filesystem_dir_open(intern, path TSRMLS_CC); efree(path); } else #endif { spl_filesystem_dir_open(intern, path TSRMLS_CC); } intern->u.dir.is_recursive = instanceof_function(intern->std.ce, spl_ce_RecursiveDirectoryIterator TSRMLS_CC) ? 1 : 0; zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void DirectoryIterator::__construct(string path) Cronstructs a new dir iterator from a path. */ SPL_METHOD(DirectoryIterator, __construct) { spl_filesystem_object_construct(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto void DirectoryIterator::rewind() Rewind dir back to the start */ SPL_METHOD(DirectoryIterator, rewind) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } intern->u.dir.index = 0; if (intern->u.dir.dirp) { php_stream_rewinddir(intern->u.dir.dirp); } spl_filesystem_dir_read(intern TSRMLS_CC); } /* }}} */ /* {{{ proto string DirectoryIterator::key() Return current dir entry */ SPL_METHOD(DirectoryIterator, key) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.dirp) { RETURN_LONG(intern->u.dir.index); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto DirectoryIterator DirectoryIterator::current() Return this (needed for Iterator interface) */ SPL_METHOD(DirectoryIterator, current) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_ZVAL(getThis(), 1, 0); } /* }}} */ /* {{{ proto void DirectoryIterator::next() Move to next entry */ SPL_METHOD(DirectoryIterator, next) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); int skip_dots = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_SKIPDOTS); if (zend_parse_parameters_none() == FAILURE) { return; } intern->u.dir.index++; do { spl_filesystem_dir_read(intern TSRMLS_CC); } while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name)); if (intern->file_name) { efree(intern->file_name); intern->file_name = NULL; } } /* }}} */ /* {{{ proto void DirectoryIterator::seek(int position) Seek to the given position */ SPL_METHOD(DirectoryIterator, seek) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zval *retval = NULL; long pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &pos) == FAILURE) { return; } if (intern->u.dir.index > pos) { /* we first rewind */ zend_call_method_with_0_params(&this_ptr, Z_OBJCE_P(getThis()), &intern->u.dir.func_rewind, "rewind", &retval); if (retval) { zval_ptr_dtor(&retval); } } while (intern->u.dir.index < pos) { int valid = 0; zend_call_method_with_0_params(&this_ptr, Z_OBJCE_P(getThis()), &intern->u.dir.func_valid, "valid", &retval); if (retval) { valid = zend_is_true(retval); zval_ptr_dtor(&retval); } if (!valid) { break; } zend_call_method_with_0_params(&this_ptr, Z_OBJCE_P(getThis()), &intern->u.dir.func_next, "next", &retval); if (retval) { zval_ptr_dtor(&retval); } } } /* }}} */ /* {{{ proto string DirectoryIterator::valid() Check whether dir contains more entries */ SPL_METHOD(DirectoryIterator, valid) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(intern->u.dir.entry.d_name[0] != '\0'); } /* }}} */ /* {{{ proto string SplFileInfo::getPath() Return the path */ SPL_METHOD(SplFileInfo, getPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *path; int path_len; if (zend_parse_parameters_none() == FAILURE) { return; } path = spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); RETURN_STRINGL(path, path_len, 1); } /* }}} */ /* {{{ proto string SplFileInfo::getFilename() Return filename only */ SPL_METHOD(SplFileInfo, getFilename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); int path_len; if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); if (path_len && path_len < intern->file_name_len) { RETURN_STRINGL(intern->file_name + path_len + 1, intern->file_name_len - (path_len + 1), 1); } else { RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } } /* }}} */ /* {{{ proto string DirectoryIterator::getFilename() Return filename of current dir entry */ SPL_METHOD(DirectoryIterator, getFilename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_STRING(intern->u.dir.entry.d_name, 1); } /* }}} */ /* {{{ proto string SplFileInfo::getExtension() Returns file extension component of path */ SPL_METHOD(SplFileInfo, getExtension) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *fname = NULL; const char *p; size_t flen; int path_len, idx; if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); if (path_len && path_len < intern->file_name_len) { fname = intern->file_name + path_len + 1; flen = intern->file_name_len - (path_len + 1); } else { fname = intern->file_name; flen = intern->file_name_len; } php_basename(fname, flen, NULL, 0, &fname, &flen TSRMLS_CC); p = zend_memrchr(fname, '.', flen); if (p) { idx = p - fname; RETVAL_STRINGL(fname + idx + 1, flen - idx - 1, 1); efree(fname); return; } else { if (fname) { efree(fname); } RETURN_EMPTY_STRING(); } } /* }}}*/ /* {{{ proto string DirectoryIterator::getExtension() Returns the file extension component of path */ SPL_METHOD(DirectoryIterator, getExtension) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *fname = NULL; const char *p; size_t flen; int idx; if (zend_parse_parameters_none() == FAILURE) { return; } php_basename(intern->u.dir.entry.d_name, strlen(intern->u.dir.entry.d_name), NULL, 0, &fname, &flen TSRMLS_CC); p = zend_memrchr(fname, '.', flen); if (p) { idx = p - fname; RETVAL_STRINGL(fname + idx + 1, flen - idx - 1, 1); efree(fname); return; } else { if (fname) { efree(fname); } RETURN_EMPTY_STRING(); } } /* }}} */ /* {{{ proto string SplFileInfo::getBasename([string $suffix]) U Returns filename component of path */ SPL_METHOD(SplFileInfo, getBasename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *fname, *suffix = 0; size_t flen; int slen = 0, path_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &suffix, &slen) == FAILURE) { return; } spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); if (path_len && path_len < intern->file_name_len) { fname = intern->file_name + path_len + 1; flen = intern->file_name_len - (path_len + 1); } else { fname = intern->file_name; flen = intern->file_name_len; } php_basename(fname, flen, suffix, slen, &fname, &flen TSRMLS_CC); RETURN_STRINGL(fname, flen, 0); } /* }}}*/ /* {{{ proto string DirectoryIterator::getBasename([string $suffix]) U Returns filename component of current dir entry */ SPL_METHOD(DirectoryIterator, getBasename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *suffix = 0, *fname; int slen = 0; size_t flen; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &suffix, &slen) == FAILURE) { return; } php_basename(intern->u.dir.entry.d_name, strlen(intern->u.dir.entry.d_name), suffix, slen, &fname, &flen TSRMLS_CC); RETURN_STRINGL(fname, flen, 0); } /* }}} */ /* {{{ proto string SplFileInfo::getPathname() Return path and filename */ SPL_METHOD(SplFileInfo, getPathname) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *path; int path_len; if (zend_parse_parameters_none() == FAILURE) { return; } path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC); if (path != NULL) { RETURN_STRINGL(path, path_len, 1); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto string FilesystemIterator::key() Return getPathname() or getFilename() depending on flags */ SPL_METHOD(FilesystemIterator, key) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (SPL_FILE_DIR_KEY(intern, SPL_FILE_DIR_KEY_AS_FILENAME)) { RETURN_STRING(intern->u.dir.entry.d_name, 1); } else { spl_filesystem_object_get_file_name(intern TSRMLS_CC); RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } } /* }}} */ /* {{{ proto string FilesystemIterator::current() Return getFilename(), getFileInfo() or $this depending on flags */ SPL_METHOD(FilesystemIterator, current) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_PATHNAME)) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } else if (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_FILEINFO)) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); spl_filesystem_object_create_type(0, intern, SPL_FS_INFO, NULL, return_value TSRMLS_CC); } else { RETURN_ZVAL(getThis(), 1, 0); /*RETURN_STRING(intern->u.dir.entry.d_name, 1);*/ } } /* }}} */ /* {{{ proto bool DirectoryIterator::isDot() Returns true if current entry is '.' or '..' */ SPL_METHOD(DirectoryIterator, isDot) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(spl_filesystem_is_dot(intern->u.dir.entry.d_name)); } /* }}} */ /* {{{ proto void SplFileInfo::__construct(string file_name) Cronstructs a new SplFileInfo from a path. */ /* zend_replace_error_handling() is used to throw exceptions in case the constructor fails. Here we use this to ensure the object has a valid directory resource. When the constructor gets called the object is already created by the engine, so we must only call 'additional' initializations. */ SPL_METHOD(SplFileInfo, __construct) { spl_filesystem_object *intern; char *path; int len; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &path, &len) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_filesystem_info_set_filename(intern, path, len, 1 TSRMLS_CC); zend_restore_error_handling(&error_handling TSRMLS_CC); /* intern->type = SPL_FS_INFO; already set */ } /* }}} */ /* {{{ FileInfoFunction */ #define FileInfoFunction(func_name, func_num) \ SPL_METHOD(SplFileInfo, func_name) \ { \ spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); \ zend_error_handling error_handling; \ if (zend_parse_parameters_none() == FAILURE) { \ return; \ } \ \ zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);\ spl_filesystem_object_get_file_name(intern TSRMLS_CC); \ php_stat(intern->file_name, intern->file_name_len, func_num, return_value TSRMLS_CC); \ zend_restore_error_handling(&error_handling TSRMLS_CC); \ } /* }}} */ /* {{{ proto int SplFileInfo::getPerms() Get file permissions */ FileInfoFunction(getPerms, FS_PERMS) /* }}} */ /* {{{ proto int SplFileInfo::getInode() Get file inode */ FileInfoFunction(getInode, FS_INODE) /* }}} */ /* {{{ proto int SplFileInfo::getSize() Get file size */ FileInfoFunction(getSize, FS_SIZE) /* }}} */ /* {{{ proto int SplFileInfo::getOwner() Get file owner */ FileInfoFunction(getOwner, FS_OWNER) /* }}} */ /* {{{ proto int SplFileInfo::getGroup() Get file group */ FileInfoFunction(getGroup, FS_GROUP) /* }}} */ /* {{{ proto int SplFileInfo::getATime() Get last access time of file */ FileInfoFunction(getATime, FS_ATIME) /* }}} */ /* {{{ proto int SplFileInfo::getMTime() Get last modification time of file */ FileInfoFunction(getMTime, FS_MTIME) /* }}} */ /* {{{ proto int SplFileInfo::getCTime() Get inode modification time of file */ FileInfoFunction(getCTime, FS_CTIME) /* }}} */ /* {{{ proto string SplFileInfo::getType() Get file type */ FileInfoFunction(getType, FS_TYPE) /* }}} */ /* {{{ proto bool SplFileInfo::isWritable() Returns true if file can be written */ FileInfoFunction(isWritable, FS_IS_W) /* }}} */ /* {{{ proto bool SplFileInfo::isReadable() Returns true if file can be read */ FileInfoFunction(isReadable, FS_IS_R) /* }}} */ /* {{{ proto bool SplFileInfo::isExecutable() Returns true if file is executable */ FileInfoFunction(isExecutable, FS_IS_X) /* }}} */ /* {{{ proto bool SplFileInfo::isFile() Returns true if file is a regular file */ FileInfoFunction(isFile, FS_IS_FILE) /* }}} */ /* {{{ proto bool SplFileInfo::isDir() Returns true if file is directory */ FileInfoFunction(isDir, FS_IS_DIR) /* }}} */ /* {{{ proto bool SplFileInfo::isLink() Returns true if file is symbolic link */ FileInfoFunction(isLink, FS_IS_LINK) /* }}} */ /* {{{ proto string SplFileInfo::getLinkTarget() U Return the target of a symbolic link */ SPL_METHOD(SplFileInfo, getLinkTarget) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); int ret; char buff[MAXPATHLEN]; zend_error_handling error_handling; if (zend_parse_parameters_none() == FAILURE) { return; } zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); #if defined(PHP_WIN32) || HAVE_SYMLINK if (!IS_ABSOLUTE_PATH(intern->file_name, intern->file_name_len)) { char expanded_path[MAXPATHLEN]; /* TODO: Fix expand_filepath to do not resolve links but only expand the path (Pierre) */ if (!expand_filepath(intern->file_name, expanded_path TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "No such file or directory"); RETURN_FALSE; } ret = php_sys_readlink(expanded_path, buff, MAXPATHLEN - 1); } else { ret = php_sys_readlink(intern->file_name, buff, MAXPATHLEN-1); } #else ret = -1; /* always fail if not implemented */ #endif if (ret == -1) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Unable to read link %s, error: %s", intern->file_name, strerror(errno)); RETVAL_FALSE; } else { /* Append NULL to the end of the string */ buff[ret] = '\0'; RETVAL_STRINGL(buff, ret, 1); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ #if (!defined(__BEOS__) && !defined(NETWARE) && HAVE_REALPATH) || defined(ZTS) /* {{{ proto string SplFileInfo::getRealPath() Return the resolved path */ SPL_METHOD(SplFileInfo, getRealPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char buff[MAXPATHLEN]; char *filename; zend_error_handling error_handling; if (zend_parse_parameters_none() == FAILURE) { return; } zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); if (intern->type == SPL_FS_DIR && !intern->file_name && intern->u.dir.entry.d_name[0]) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); } if (intern->orig_path) { filename = intern->orig_path; } else { filename = intern->file_name; } if (filename && VCWD_REALPATH(filename, buff)) { #ifdef ZTS if (VCWD_ACCESS(buff, F_OK)) { RETVAL_FALSE; } else #endif RETVAL_STRING(buff, 1); } else { RETVAL_FALSE; } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ #endif /* {{{ proto SplFileObject SplFileInfo::openFile([string mode = 'r' [, bool use_include_path [, resource context]]]) Open the current file */ SPL_METHOD(SplFileInfo, openFile) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_filesystem_object_create_type(ht, intern, SPL_FS_FILE, NULL, return_value TSRMLS_CC); } /* }}} */ /* {{{ proto void SplFileInfo::setFileClass([string class_name]) Class to use in openFile() */ SPL_METHOD(SplFileInfo, setFileClass) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = spl_ce_SplFileObject; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { intern->file_class = ce; } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void SplFileInfo::setInfoClass([string class_name]) Class to use in getFileInfo(), getPathInfo() */ SPL_METHOD(SplFileInfo, setInfoClass) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = spl_ce_SplFileInfo; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { intern->info_class = ce; } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto SplFileInfo SplFileInfo::getFileInfo([string $class_name]) Get/copy file info */ SPL_METHOD(SplFileInfo, getFileInfo) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = intern->info_class; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { spl_filesystem_object_create_type(ht, intern, SPL_FS_INFO, ce, return_value TSRMLS_CC); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto SplFileInfo SplFileInfo::getPathInfo([string $class_name]) Get/copy file info */ SPL_METHOD(SplFileInfo, getPathInfo) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = intern->info_class; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { int path_len; char *path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC); if (path) { char *dpath = estrndup(path, path_len); path_len = php_dirname(dpath, path_len); spl_filesystem_object_create_info(intern, dpath, path_len, 1, ce, return_value TSRMLS_CC); efree(dpath); } } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void FilesystemIterator::__construct(string path [, int flags]) Cronstructs a new dir iterator from a path. */ SPL_METHOD(FilesystemIterator, __construct) { spl_filesystem_object_construct(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIT_CTOR_FLAGS | SPL_FILE_DIR_SKIPDOTS); } /* }}} */ /* {{{ proto void FilesystemIterator::rewind() Rewind dir back to the start */ SPL_METHOD(FilesystemIterator, rewind) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } intern->u.dir.index = 0; if (intern->u.dir.dirp) { php_stream_rewinddir(intern->u.dir.dirp); } do { spl_filesystem_dir_read(intern TSRMLS_CC); } while (spl_filesystem_is_dot(intern->u.dir.entry.d_name)); } /* }}} */ /* {{{ proto int FilesystemIterator::getFlags() Get handling flags */ SPL_METHOD(FilesystemIterator, getFlags) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(intern->flags & (SPL_FILE_DIR_KEY_MODE_MASK | SPL_FILE_DIR_CURRENT_MODE_MASK | SPL_FILE_DIR_OTHERS_MASK)); } /* }}} */ /* {{{ proto void FilesystemIterator::setFlags(long $flags) Set handling flags */ SPL_METHOD(FilesystemIterator, setFlags) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long flags; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &flags) == FAILURE) { return; } intern->flags &= ~(SPL_FILE_DIR_KEY_MODE_MASK|SPL_FILE_DIR_CURRENT_MODE_MASK|SPL_FILE_DIR_OTHERS_MASK); intern->flags |= ((SPL_FILE_DIR_KEY_MODE_MASK|SPL_FILE_DIR_CURRENT_MODE_MASK|SPL_FILE_DIR_OTHERS_MASK) & flags); } /* }}} */ /* {{{ proto bool RecursiveDirectoryIterator::hasChildren([bool $allow_links = false]) Returns whether current entry is a directory and not '.' or '..' */ SPL_METHOD(RecursiveDirectoryIterator, hasChildren) { zend_bool allow_links = 0; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &allow_links) == FAILURE) { return; } if (spl_filesystem_is_invalid_or_dot(intern->u.dir.entry.d_name)) { RETURN_FALSE; } else { spl_filesystem_object_get_file_name(intern TSRMLS_CC); if (!allow_links && !(intern->flags & SPL_FILE_DIR_FOLLOW_SYMLINKS)) { php_stat(intern->file_name, intern->file_name_len, FS_IS_LINK, return_value TSRMLS_CC); if (zend_is_true(return_value)) { RETURN_FALSE; } } php_stat(intern->file_name, intern->file_name_len, FS_IS_DIR, return_value TSRMLS_CC); } } /* }}} */ /* {{{ proto RecursiveDirectoryIterator DirectoryIterator::getChildren() Returns an iterator for the current entry if it is a directory */ SPL_METHOD(RecursiveDirectoryIterator, getChildren) { zval zpath, zflags; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_filesystem_object *subdir; char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH; if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_object_get_file_name(intern TSRMLS_CC); if (SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_CURRENT_AS_PATHNAME)) { RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } else { INIT_PZVAL(&zflags); INIT_PZVAL(&zpath); ZVAL_LONG(&zflags, intern->flags); ZVAL_STRINGL(&zpath, intern->file_name, intern->file_name_len, 0); spl_instantiate_arg_ex2(Z_OBJCE_P(getThis()), &return_value, 0, &zpath, &zflags TSRMLS_CC); subdir = (spl_filesystem_object*)zend_object_store_get_object(return_value TSRMLS_CC); if (subdir) { if (intern->u.dir.sub_path && intern->u.dir.sub_path[0]) { subdir->u.dir.sub_path_len = spprintf(&subdir->u.dir.sub_path, 0, "%s%c%s", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name); } else { subdir->u.dir.sub_path_len = strlen(intern->u.dir.entry.d_name); subdir->u.dir.sub_path = estrndup(intern->u.dir.entry.d_name, subdir->u.dir.sub_path_len); } subdir->info_class = intern->info_class; subdir->file_class = intern->file_class; subdir->oth = intern->oth; } } } /* }}} */ /* {{{ proto void RecursiveDirectoryIterator::getSubPath() Get sub path */ SPL_METHOD(RecursiveDirectoryIterator, getSubPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.sub_path) { RETURN_STRINGL(intern->u.dir.sub_path, intern->u.dir.sub_path_len, 1); } else { RETURN_STRINGL("", 0, 1); } } /* }}} */ /* {{{ proto void RecursiveDirectoryIterator::getSubPathname() Get sub path and file name */ SPL_METHOD(RecursiveDirectoryIterator, getSubPathname) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *sub_name; int len; char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH; if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.sub_path) { len = spprintf(&sub_name, 0, "%s%c%s", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name); RETURN_STRINGL(sub_name, len, 0); } else { RETURN_STRING(intern->u.dir.entry.d_name, 1); } } /* }}} */ /* {{{ proto int RecursiveDirectoryIterator::__construct(string path [, int flags]) Cronstructs a new dir iterator from a path. */ SPL_METHOD(RecursiveDirectoryIterator, __construct) { spl_filesystem_object_construct(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIT_CTOR_FLAGS); } /* }}} */ #ifdef HAVE_GLOB /* {{{ proto int GlobIterator::__construct(string path [, int flags]) Cronstructs a new dir iterator from a glob expression (no glob:// needed). */ SPL_METHOD(GlobIterator, __construct) { spl_filesystem_object_construct(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIT_CTOR_FLAGS|DIT_CTOR_GLOB); } /* }}} */ /* {{{ proto int GlobIterator::cont() Return the number of directories and files found by globbing */ SPL_METHOD(GlobIterator, count) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (php_stream_is(intern->u.dir.dirp ,&php_glob_stream_ops)) { RETURN_LONG(php_glob_stream_get_count(intern->u.dir.dirp, NULL)); } else { /* should not happen */ php_error_docref(NULL TSRMLS_CC, E_ERROR, "GlobIterator lost glob state"); } } /* }}} */ #endif /* HAVE_GLOB */ /* {{{ forward declarations to the iterator handlers */ static void spl_filesystem_dir_it_dtor(zend_object_iterator *iter TSRMLS_DC); static int spl_filesystem_dir_it_valid(zend_object_iterator *iter TSRMLS_DC); static void spl_filesystem_dir_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC); static int spl_filesystem_dir_it_current_key(zend_object_iterator *iter, char **str_key, uint *str_key_len, ulong *int_key TSRMLS_DC); static void spl_filesystem_dir_it_move_forward(zend_object_iterator *iter TSRMLS_DC); static void spl_filesystem_dir_it_rewind(zend_object_iterator *iter TSRMLS_DC); /* iterator handler table */ zend_object_iterator_funcs spl_filesystem_dir_it_funcs = { spl_filesystem_dir_it_dtor, spl_filesystem_dir_it_valid, spl_filesystem_dir_it_current_data, spl_filesystem_dir_it_current_key, spl_filesystem_dir_it_move_forward, spl_filesystem_dir_it_rewind }; /* }}} */ /* {{{ spl_ce_dir_get_iterator */ zend_object_iterator *spl_filesystem_dir_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) { spl_filesystem_iterator *iterator; spl_filesystem_object *dir_object; if (by_ref) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } dir_object = (spl_filesystem_object*)zend_object_store_get_object(object TSRMLS_CC); iterator = spl_filesystem_object_to_iterator(dir_object); Z_SET_REFCOUNT_P(object, Z_REFCOUNT_P(object) + 2); iterator->intern.data = (void*)object; iterator->intern.funcs = &spl_filesystem_dir_it_funcs; iterator->current = object; return (zend_object_iterator*)iterator; } /* }}} */ /* {{{ spl_filesystem_dir_it_dtor */ static void spl_filesystem_dir_it_dtor(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; zval *zfree = (zval*)iterator->intern.data; iterator->intern.data = NULL; /* mark as unused */ zval_ptr_dtor(&iterator->current); if (zfree) { zval_ptr_dtor(&zfree); } } /* }}} */ /* {{{ spl_filesystem_dir_it_valid */ static int spl_filesystem_dir_it_valid(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); return object->u.dir.entry.d_name[0] != '\0' ? SUCCESS : FAILURE; } /* }}} */ /* {{{ spl_filesystem_dir_it_current_data */ static void spl_filesystem_dir_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; *data = &iterator->current; } /* }}} */ /* {{{ spl_filesystem_dir_it_current_key */ static int spl_filesystem_dir_it_current_key(zend_object_iterator *iter, char **str_key, uint *str_key_len, ulong *int_key TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); *int_key = object->u.dir.index; return HASH_KEY_IS_LONG; } /* }}} */ /* {{{ spl_filesystem_dir_it_move_forward */ static void spl_filesystem_dir_it_move_forward(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); object->u.dir.index++; spl_filesystem_dir_read(object TSRMLS_CC); if (object->file_name) { efree(object->file_name); object->file_name = NULL; } } /* }}} */ /* {{{ spl_filesystem_dir_it_rewind */ static void spl_filesystem_dir_it_rewind(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); object->u.dir.index = 0; if (object->u.dir.dirp) { php_stream_rewinddir(object->u.dir.dirp); } spl_filesystem_dir_read(object TSRMLS_CC); } /* }}} */ /* {{{ spl_filesystem_tree_it_dtor */ static void spl_filesystem_tree_it_dtor(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; zval *zfree = (zval*)iterator->intern.data; if (iterator->current) { zval_ptr_dtor(&iterator->current); } iterator->intern.data = NULL; /* mark as unused */ /* free twice as we add ref twice */ zval_ptr_dtor(&zfree); zval_ptr_dtor(&zfree); } /* }}} */ /* {{{ spl_filesystem_tree_it_current_data */ static void spl_filesystem_tree_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator); if (SPL_FILE_DIR_CURRENT(object, SPL_FILE_DIR_CURRENT_AS_PATHNAME)) { if (!iterator->current) { ALLOC_INIT_ZVAL(iterator->current); spl_filesystem_object_get_file_name(object TSRMLS_CC); ZVAL_STRINGL(iterator->current, object->file_name, object->file_name_len, 1); } *data = &iterator->current; } else if (SPL_FILE_DIR_CURRENT(object, SPL_FILE_DIR_CURRENT_AS_FILEINFO)) { if (!iterator->current) { ALLOC_INIT_ZVAL(iterator->current); spl_filesystem_object_get_file_name(object TSRMLS_CC); spl_filesystem_object_create_type(0, object, SPL_FS_INFO, NULL, iterator->current TSRMLS_CC); } *data = &iterator->current; } else { *data = (zval**)&iterator->intern.data; } } /* }}} */ /* {{{ spl_filesystem_tree_it_current_key */ static int spl_filesystem_tree_it_current_key(zend_object_iterator *iter, char **str_key, uint *str_key_len, ulong *int_key TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); if (SPL_FILE_DIR_KEY(object, SPL_FILE_DIR_KEY_AS_FILENAME)) { *str_key_len = strlen(object->u.dir.entry.d_name) + 1; *str_key = estrndup(object->u.dir.entry.d_name, *str_key_len - 1); } else { spl_filesystem_object_get_file_name(object TSRMLS_CC); *str_key_len = object->file_name_len + 1; *str_key = estrndup(object->file_name, object->file_name_len); } return HASH_KEY_IS_STRING; } /* }}} */ /* {{{ spl_filesystem_tree_it_move_forward */ static void spl_filesystem_tree_it_move_forward(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator); object->u.dir.index++; do { spl_filesystem_dir_read(object TSRMLS_CC); } while (spl_filesystem_is_dot(object->u.dir.entry.d_name)); if (object->file_name) { efree(object->file_name); object->file_name = NULL; } if (iterator->current) { zval_ptr_dtor(&iterator->current); iterator->current = NULL; } } /* }}} */ /* {{{ spl_filesystem_tree_it_rewind */ static void spl_filesystem_tree_it_rewind(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator); object->u.dir.index = 0; if (object->u.dir.dirp) { php_stream_rewinddir(object->u.dir.dirp); } do { spl_filesystem_dir_read(object TSRMLS_CC); } while (spl_filesystem_is_dot(object->u.dir.entry.d_name)); if (iterator->current) { zval_ptr_dtor(&iterator->current); iterator->current = NULL; } } /* }}} */ /* {{{ iterator handler table */ zend_object_iterator_funcs spl_filesystem_tree_it_funcs = { spl_filesystem_tree_it_dtor, spl_filesystem_dir_it_valid, spl_filesystem_tree_it_current_data, spl_filesystem_tree_it_current_key, spl_filesystem_tree_it_move_forward, spl_filesystem_tree_it_rewind }; /* }}} */ /* {{{ spl_ce_dir_get_iterator */ zend_object_iterator *spl_filesystem_tree_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) { spl_filesystem_iterator *iterator; spl_filesystem_object *dir_object; if (by_ref) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } dir_object = (spl_filesystem_object*)zend_object_store_get_object(object TSRMLS_CC); iterator = spl_filesystem_object_to_iterator(dir_object); Z_SET_REFCOUNT_P(object, Z_REFCOUNT_P(object) + 2); iterator->intern.data = (void*)object; iterator->intern.funcs = &spl_filesystem_tree_it_funcs; iterator->current = NULL; return (zend_object_iterator*)iterator; } /* }}} */ /* {{{ spl_filesystem_object_cast */ static int spl_filesystem_object_cast(zval *readobj, zval *writeobj, int type TSRMLS_DC) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(readobj TSRMLS_CC); if (type == IS_STRING) { switch (intern->type) { case SPL_FS_INFO: case SPL_FS_FILE: if (readobj == writeobj) { zval retval; zval *retval_ptr = &retval; ZVAL_STRINGL(retval_ptr, intern->file_name, intern->file_name_len, 1); zval_dtor(readobj); ZVAL_ZVAL(writeobj, retval_ptr, 0, 0); } else { ZVAL_STRINGL(writeobj, intern->file_name, intern->file_name_len, 1); } return SUCCESS; case SPL_FS_DIR: if (readobj == writeobj) { zval retval; zval *retval_ptr = &retval; ZVAL_STRING(retval_ptr, intern->u.dir.entry.d_name, 1); zval_dtor(readobj); ZVAL_ZVAL(writeobj, retval_ptr, 0, 0); } else { ZVAL_STRING(writeobj, intern->u.dir.entry.d_name, 1); } return SUCCESS; } } if (readobj == writeobj) { zval_dtor(readobj); } ZVAL_NULL(writeobj); return FAILURE; } /* }}} */ /* {{{ declare method parameters */ /* supply a name and default to call by parameter */ ZEND_BEGIN_ARG_INFO(arginfo_info___construct, 0) ZEND_ARG_INFO(0, file_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_info_openFile, 0, 0, 0) ZEND_ARG_INFO(0, open_mode) ZEND_ARG_INFO(0, use_include_path) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_info_optinalFileClass, 0, 0, 0) ZEND_ARG_INFO(0, class_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_optinalSuffix, 0, 0, 0) ZEND_ARG_INFO(0, suffix) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_splfileinfo_void, 0) ZEND_END_ARG_INFO() /* the method table */ /* each method can have its own parameters and visibility */ static const zend_function_entry spl_SplFileInfo_functions[] = { SPL_ME(SplFileInfo, __construct, arginfo_info___construct, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getPath, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getFilename, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getExtension, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getBasename, arginfo_optinalSuffix, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getPathname, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getPerms, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getInode, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getSize, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getOwner, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getGroup, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getATime, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getMTime, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getCTime, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getType, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isWritable, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isReadable, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isExecutable, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isFile, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isDir, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isLink, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getLinkTarget, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) #if (!defined(__BEOS__) && !defined(NETWARE) && HAVE_REALPATH) || defined(ZTS) SPL_ME(SplFileInfo, getRealPath, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) #endif SPL_ME(SplFileInfo, getFileInfo, arginfo_info_optinalFileClass, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getPathInfo, arginfo_info_optinalFileClass, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, openFile, arginfo_info_openFile, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, setFileClass, arginfo_info_optinalFileClass, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, setInfoClass, arginfo_info_optinalFileClass, ZEND_ACC_PUBLIC) SPL_MA(SplFileInfo, __toString, SplFileInfo, getPathname, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; ZEND_BEGIN_ARG_INFO(arginfo_dir___construct, 0) ZEND_ARG_INFO(0, path) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_dir_it_seek, 0) ZEND_ARG_INFO(0, position) ZEND_END_ARG_INFO(); /* the method table */ /* each method can have its own parameters and visibility */ static const zend_function_entry spl_DirectoryIterator_functions[] = { SPL_ME(DirectoryIterator, __construct, arginfo_dir___construct, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, getFilename, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, getExtension, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, getBasename, arginfo_optinalSuffix, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, isDot, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, rewind, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, valid, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, key, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, current, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, next, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, seek, arginfo_dir_it_seek, ZEND_ACC_PUBLIC) SPL_MA(DirectoryIterator, __toString, DirectoryIterator, getFilename, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; ZEND_BEGIN_ARG_INFO_EX(arginfo_r_dir___construct, 0, 0, 1) ZEND_ARG_INFO(0, path) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_r_dir_hasChildren, 0, 0, 0) ZEND_ARG_INFO(0, allow_links) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_r_dir_setFlags, 0, 0, 0) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() static const zend_function_entry spl_FilesystemIterator_functions[] = { SPL_ME(FilesystemIterator, __construct, arginfo_r_dir___construct, ZEND_ACC_PUBLIC) SPL_ME(FilesystemIterator, rewind, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, next, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(FilesystemIterator, key, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(FilesystemIterator, current, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(FilesystemIterator, getFlags, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(FilesystemIterator, setFlags, arginfo_r_dir_setFlags, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; static const zend_function_entry spl_RecursiveDirectoryIterator_functions[] = { SPL_ME(RecursiveDirectoryIterator, __construct, arginfo_r_dir___construct, ZEND_ACC_PUBLIC) SPL_ME(RecursiveDirectoryIterator, hasChildren, arginfo_r_dir_hasChildren, ZEND_ACC_PUBLIC) SPL_ME(RecursiveDirectoryIterator, getChildren, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(RecursiveDirectoryIterator, getSubPath, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(RecursiveDirectoryIterator, getSubPathname,arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; #ifdef HAVE_GLOB static const zend_function_entry spl_GlobIterator_functions[] = { SPL_ME(GlobIterator, __construct, arginfo_r_dir___construct, ZEND_ACC_PUBLIC) SPL_ME(GlobIterator, count, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; #endif /* }}} */ static int spl_filesystem_file_read(spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */ { char *buf; size_t line_len = 0; int len; long line_add = (intern->u.file.current_line || intern->u.file.current_zval) ? 1 : 0; spl_filesystem_file_free_line(intern TSRMLS_CC); if (php_stream_eof(intern->u.file.stream)) { if (!silent) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot read from file %s", intern->file_name); } return FAILURE; } if (intern->u.file.max_line_len > 0) { buf = safe_emalloc((intern->u.file.max_line_len + 1), sizeof(char), 0); if (php_stream_get_line(intern->u.file.stream, buf, intern->u.file.max_line_len, &line_len) == NULL) { efree(buf); buf = NULL; } else { buf[line_len] = '\0'; } } else { buf = php_stream_get_line(intern->u.file.stream, NULL, 0, &line_len); } if (!buf) { intern->u.file.current_line = estrdup(""); intern->u.file.current_line_len = 0; } else { if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_DROP_NEW_LINE)) { line_len = strcspn(buf, "\r\n"); buf[line_len] = '\0'; } if (PG(magic_quotes_runtime)) { buf = php_addslashes(buf, line_len, &len, 1 TSRMLS_CC); line_len = len; } intern->u.file.current_line = buf; intern->u.file.current_line_len = line_len; } intern->u.file.current_line_num += line_add; return SUCCESS; } /* }}} */ static int spl_filesystem_file_call(spl_filesystem_object *intern, zend_function *func_ptr, int pass_num_args, zval *return_value, zval *arg2 TSRMLS_DC) /* {{{ */ { zend_fcall_info fci; zend_fcall_info_cache fcic; zval z_fname; zval * zresource_ptr = &intern->u.file.zresource, *retval; int result; int num_args = pass_num_args + (arg2 ? 2 : 1); zval ***params = (zval***)safe_emalloc(num_args, sizeof(zval**), 0); params[0] = &zresource_ptr; if (arg2) { params[1] = &arg2; } zend_get_parameters_array_ex(pass_num_args, params+(arg2 ? 2 : 1)); ZVAL_STRING(&z_fname, func_ptr->common.function_name, 0); fci.size = sizeof(fci); fci.function_table = EG(function_table); fci.object_ptr = NULL; fci.function_name = &z_fname; fci.retval_ptr_ptr = &retval; fci.param_count = num_args; fci.params = params; fci.no_separation = 1; fci.symbol_table = NULL; fcic.initialized = 1; fcic.function_handler = func_ptr; fcic.calling_scope = NULL; fcic.called_scope = NULL; fcic.object_ptr = NULL; result = zend_call_function(&fci, &fcic TSRMLS_CC); if (result == FAILURE) { RETVAL_FALSE; } else { ZVAL_ZVAL(return_value, retval, 1, 1); } efree(params); return result; } /* }}} */ #define FileFunctionCall(func_name, pass_num_args, arg2) /* {{{ */ \ { \ zend_function *func_ptr; \ int ret; \ ret = zend_hash_find(EG(function_table), #func_name, sizeof(#func_name), (void **) &func_ptr); \ if (ret != SUCCESS) { \ zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Internal error, function '%s' not found. Please report", #func_name); \ return; \ } \ spl_filesystem_file_call(intern, func_ptr, pass_num_args, return_value, arg2 TSRMLS_CC); \ } /* }}} */ static int spl_filesystem_file_read_csv(spl_filesystem_object *intern, char delimiter, char enclosure, char escape, zval *return_value TSRMLS_DC) /* {{{ */ { int ret = SUCCESS; do { ret = spl_filesystem_file_read(intern, 1 TSRMLS_CC); } while (ret == SUCCESS && !intern->u.file.current_line_len && SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY)); if (ret == SUCCESS) { size_t buf_len = intern->u.file.current_line_len; char *buf = estrndup(intern->u.file.current_line, buf_len); if (intern->u.file.current_zval) { zval_ptr_dtor(&intern->u.file.current_zval); } ALLOC_INIT_ZVAL(intern->u.file.current_zval); php_fgetcsv(intern->u.file.stream, delimiter, enclosure, escape, buf_len, buf, intern->u.file.current_zval TSRMLS_CC); if (return_value) { if (Z_TYPE_P(return_value) != IS_NULL) { zval_dtor(return_value); ZVAL_NULL(return_value); } ZVAL_ZVAL(return_value, intern->u.file.current_zval, 1, 0); } } return ret; } /* }}} */ static int spl_filesystem_file_read_line_ex(zval * this_ptr, spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */ { zval *retval = NULL; /* 1) use fgetcsv? 2) overloaded call the function, 3) do it directly */ if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) || intern->u.file.func_getCurr->common.scope != spl_ce_SplFileObject) { if (php_stream_eof(intern->u.file.stream)) { if (!silent) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot read from file %s", intern->file_name); } return FAILURE; } if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV)) { return spl_filesystem_file_read_csv(intern, intern->u.file.delimiter, intern->u.file.enclosure, intern->u.file.escape, NULL TSRMLS_CC); } else { zend_call_method_with_0_params(&this_ptr, Z_OBJCE_P(getThis()), &intern->u.file.func_getCurr, "getCurrentLine", &retval); } if (retval) { if (intern->u.file.current_line || intern->u.file.current_zval) { intern->u.file.current_line_num++; } spl_filesystem_file_free_line(intern TSRMLS_CC); if (Z_TYPE_P(retval) == IS_STRING) { intern->u.file.current_line = estrndup(Z_STRVAL_P(retval), Z_STRLEN_P(retval)); intern->u.file.current_line_len = Z_STRLEN_P(retval); } else { MAKE_STD_ZVAL(intern->u.file.current_zval); ZVAL_ZVAL(intern->u.file.current_zval, retval, 1, 0); } zval_ptr_dtor(&retval); return SUCCESS; } else { return FAILURE; } } else { return spl_filesystem_file_read(intern, silent TSRMLS_CC); } } /* }}} */ static int spl_filesystem_file_is_empty_line(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { if (intern->u.file.current_line) { return intern->u.file.current_line_len == 0; } else if (intern->u.file.current_zval) { switch(Z_TYPE_P(intern->u.file.current_zval)) { case IS_STRING: return Z_STRLEN_P(intern->u.file.current_zval) == 0; case IS_ARRAY: if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) && zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 1) { zval ** first = Z_ARRVAL_P(intern->u.file.current_zval)->pListHead->pData; return Z_TYPE_PP(first) == IS_STRING && Z_STRLEN_PP(first) == 0; } return zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 0; case IS_NULL: return 1; default: return 0; } } else { return 1; } } /* }}} */ static int spl_filesystem_file_read_line(zval * this_ptr, spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */ { int ret = spl_filesystem_file_read_line_ex(this_ptr, intern, silent TSRMLS_CC); while (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY) && ret == SUCCESS && spl_filesystem_file_is_empty_line(intern TSRMLS_CC)) { spl_filesystem_file_free_line(intern TSRMLS_CC); ret = spl_filesystem_file_read_line_ex(this_ptr, intern, silent TSRMLS_CC); } return ret; } /* }}} */ static void spl_filesystem_file_rewind(zval * this_ptr, spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { if (-1 == php_stream_rewind(intern->u.file.stream)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot rewind file %s", intern->file_name); } else { spl_filesystem_file_free_line(intern TSRMLS_CC); intern->u.file.current_line_num = 0; } if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_AHEAD)) { spl_filesystem_file_read_line(this_ptr, intern, 1 TSRMLS_CC); } } /* }}} */ /* {{{ proto void SplFileObject::__construct(string filename [, string mode = 'r' [, bool use_include_path [, resource context]]]]) Construct a new file object */ SPL_METHOD(SplFileObject, __construct) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_bool use_include_path = 0; char *p1, *p2; char *tmp_path; int tmp_path_len; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); intern->u.file.open_mode = "r"; intern->u.file.open_mode_len = 1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|sbr", &intern->file_name, &intern->file_name_len, &intern->u.file.open_mode, &intern->u.file.open_mode_len, &use_include_path, &intern->u.file.zcontext) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (spl_filesystem_file_open(intern, use_include_path, 0 TSRMLS_CC) == SUCCESS) { tmp_path_len = strlen(intern->u.file.stream->orig_path); if (tmp_path_len > 1 && IS_SLASH_AT(intern->u.file.stream->orig_path, tmp_path_len-1)) { tmp_path_len--; } tmp_path = estrndup(intern->u.file.stream->orig_path, tmp_path_len); p1 = strrchr(tmp_path, '/'); #if defined(PHP_WIN32) || defined(NETWARE) p2 = strrchr(tmp_path, '\\'); #else p2 = 0; #endif if (p1 || p2) { intern->_path_len = (p1 > p2 ? p1 : p2) - tmp_path; } else { intern->_path_len = 0; } efree(tmp_path); intern->_path = estrndup(intern->u.file.stream->orig_path, intern->_path_len); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void SplTempFileObject::__construct([int max_memory]) Construct a new temp file object */ SPL_METHOD(SplTempFileObject, __construct) { long max_memory = PHP_STREAM_MAX_MEM; char tmp_fname[48]; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &max_memory) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (max_memory < 0) { intern->file_name = "php://memory"; intern->file_name_len = 12; } else if (ZEND_NUM_ARGS()) { intern->file_name_len = slprintf(tmp_fname, sizeof(tmp_fname), "php://temp/maxmemory:%ld", max_memory); intern->file_name = tmp_fname; } else { intern->file_name = "php://temp"; intern->file_name_len = 10; } intern->u.file.open_mode = "wb"; intern->u.file.open_mode_len = 1; intern->u.file.zcontext = NULL; if (spl_filesystem_file_open(intern, 0, 0 TSRMLS_CC) == SUCCESS) { intern->_path_len = 0; intern->_path = estrndup("", 0); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void SplFileObject::rewind() Rewind the file and read the first line */ SPL_METHOD(SplFileObject, rewind) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC); } /* }}} */ /* {{{ proto void SplFileObject::eof() Return whether end of file is reached */ SPL_METHOD(SplFileObject, eof) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(php_stream_eof(intern->u.file.stream)); } /* }}} */ /* {{{ proto void SplFileObject::valid() Return !eof() */ SPL_METHOD(SplFileObject, valid) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_AHEAD)) { RETURN_BOOL(intern->u.file.current_line || intern->u.file.current_zval); } else { RETVAL_BOOL(!php_stream_eof(intern->u.file.stream)); } } /* }}} */ /* {{{ proto string SplFileObject::fgets() Rturn next line from file */ SPL_METHOD(SplFileObject, fgets) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (spl_filesystem_file_read(intern, 0 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1); } /* }}} */ /* {{{ proto string SplFileObject::current() Return current line from file */ SPL_METHOD(SplFileObject, current) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!intern->u.file.current_line && !intern->u.file.current_zval) { spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC); } if (intern->u.file.current_line && (!SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) || !intern->u.file.current_zval)) { RETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1); } else if (intern->u.file.current_zval) { RETURN_ZVAL(intern->u.file.current_zval, 1, 0); } RETURN_FALSE; } /* }}} */ /* {{{ proto int SplFileObject::key() Return line number */ SPL_METHOD(SplFileObject, key) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } /* Do not read the next line to support correct counting with fgetc() if (!intern->current_line) { spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC); } */ RETURN_LONG(intern->u.file.current_line_num); } /* }}} */ /* {{{ proto void SplFileObject::next() Read next line */ SPL_METHOD(SplFileObject, next) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_file_free_line(intern TSRMLS_CC); if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_AHEAD)) { spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC); } intern->u.file.current_line_num++; } /* }}} */ /* {{{ proto void SplFileObject::setFlags(int flags) Set file handling flags */ SPL_METHOD(SplFileObject, setFlags) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &intern->flags); } /* }}} */ /* {{{ proto int SplFileObject::getFlags() Get file handling flags */ SPL_METHOD(SplFileObject, getFlags) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(intern->flags & SPL_FILE_OBJECT_MASK); } /* }}} */ /* {{{ proto void SplFileObject::setMaxLineLen(int max_len) Set maximum line length */ SPL_METHOD(SplFileObject, setMaxLineLen) { long max_len; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &max_len) == FAILURE) { return; } if (max_len < 0) { zend_throw_exception_ex(spl_ce_DomainException, 0 TSRMLS_CC, "Maximum line length must be greater than or equal zero"); return; } intern->u.file.max_line_len = max_len; } /* }}} */ /* {{{ proto int SplFileObject::getMaxLineLen() Get maximum line length */ SPL_METHOD(SplFileObject, getMaxLineLen) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG((long)intern->u.file.max_line_len); } /* }}} */ /* {{{ proto bool SplFileObject::hasChildren() Return false */ SPL_METHOD(SplFileObject, hasChildren) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_FALSE; } /* }}} */ /* {{{ proto bool SplFileObject::getChildren() Read NULL */ SPL_METHOD(SplFileObject, getChildren) { if (zend_parse_parameters_none() == FAILURE) { return; } /* return NULL */ } /* }}} */ /* {{{ FileFunction */ #define FileFunction(func_name) \ SPL_METHOD(SplFileObject, func_name) \ { \ spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); \ FileFunctionCall(func_name, ZEND_NUM_ARGS(), NULL); \ } /* }}} */ /* {{{ proto array SplFileObject::fgetcsv([string delimiter [, string enclosure [, escape = '\\']]]) Return current line as csv */ SPL_METHOD(SplFileObject, fgetcsv) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter = intern->u.file.delimiter, enclosure = intern->u.file.enclosure, escape = intern->u.file.escape; char *delim = NULL, *enclo = NULL, *esc = NULL; int d_len = 0, e_len = 0, esc_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sss", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) { switch(ZEND_NUM_ARGS()) { case 3: if (esc_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character"); RETURN_FALSE; } escape = esc[0]; /* no break */ case 2: if (e_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } enclosure = enclo[0]; /* no break */ case 1: if (d_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } delimiter = delim[0]; /* no break */ case 0: break; } spl_filesystem_file_read_csv(intern, delimiter, enclosure, escape, return_value TSRMLS_CC); } } /* }}} */ /* {{{ proto int SplFileObject::fputcsv(array fields, [string delimiter [, string enclosure]]) Output a field array as a CSV line */ SPL_METHOD(SplFileObject, fputcsv) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter = intern->u.file.delimiter, enclosure = intern->u.file.enclosure, escape = intern->u.file.escape; char *delim = NULL, *enclo = NULL; int d_len = 0, e_len = 0, ret; zval *fields = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|ss", &fields, &delim, &d_len, &enclo, &e_len) == SUCCESS) { switch(ZEND_NUM_ARGS()) { case 3: if (e_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } enclosure = enclo[0]; /* no break */ case 2: if (d_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } delimiter = delim[0]; /* no break */ case 1: case 0: break; } ret = php_fputcsv(intern->u.file.stream, fields, delimiter, enclosure, escape TSRMLS_CC); RETURN_LONG(ret); } } /* }}} */ /* {{{ proto void SplFileObject::setCsvControl([string delimiter = ',' [, string enclosure = '"' [, string escape = '\\']]]) Set the delimiter and enclosure character used in fgetcsv */ SPL_METHOD(SplFileObject, setCsvControl) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter = ',', enclosure = '"', escape='\\'; char *delim = NULL, *enclo = NULL, *esc = NULL; int d_len = 0, e_len = 0, esc_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sss", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) { switch(ZEND_NUM_ARGS()) { case 3: if (esc_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character"); RETURN_FALSE; } escape = esc[0]; /* no break */ case 2: if (e_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } enclosure = enclo[0]; /* no break */ case 1: if (d_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } delimiter = delim[0]; /* no break */ case 0: break; } intern->u.file.delimiter = delimiter; intern->u.file.enclosure = enclosure; intern->u.file.escape = escape; } } /* }}} */ /* {{{ proto array SplFileObject::getCsvControl() Get the delimiter and enclosure character used in fgetcsv */ SPL_METHOD(SplFileObject, getCsvControl) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter[2], enclosure[2]; array_init(return_value); delimiter[0] = intern->u.file.delimiter; delimiter[1] = '\0'; enclosure[0] = intern->u.file.enclosure; enclosure[1] = '\0'; add_next_index_string(return_value, delimiter, 1); add_next_index_string(return_value, enclosure, 1); } /* }}} */ /* {{{ proto bool SplFileObject::flock(int operation [, int &wouldblock]) Portable file locking */ FileFunction(flock) /* }}} */ /* {{{ proto bool SplFileObject::fflush() Flush the file */ SPL_METHOD(SplFileObject, fflush) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); RETURN_BOOL(!php_stream_flush(intern->u.file.stream)); } /* }}} */ /* {{{ proto int SplFileObject::ftell() Return current file position */ SPL_METHOD(SplFileObject, ftell) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long ret = php_stream_tell(intern->u.file.stream); if (ret == -1) { RETURN_FALSE; } else { RETURN_LONG(ret); } } /* }}} */ /* {{{ proto int SplFileObject::fseek(int pos [, int whence = SEEK_SET]) Return current file position */ SPL_METHOD(SplFileObject, fseek) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long pos, whence = SEEK_SET; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|l", &pos, &whence) == FAILURE) { return; } spl_filesystem_file_free_line(intern TSRMLS_CC); RETURN_LONG(php_stream_seek(intern->u.file.stream, pos, whence)); } /* }}} */ /* {{{ proto int SplFileObject::fgetc() Get a character form the file */ SPL_METHOD(SplFileObject, fgetc) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char buf[2]; int result; spl_filesystem_file_free_line(intern TSRMLS_CC); result = php_stream_getc(intern->u.file.stream); if (result == EOF) { RETVAL_FALSE; } else { if (result == '\n') { intern->u.file.current_line_num++; } buf[0] = result; buf[1] = '\0'; RETURN_STRINGL(buf, 1, 1); } } /* }}} */ /* {{{ proto string SplFileObject::fgetss([string allowable_tags]) Get a line from file pointer and strip HTML tags */ SPL_METHOD(SplFileObject, fgetss) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zval *arg2 = NULL; MAKE_STD_ZVAL(arg2); if (intern->u.file.max_line_len > 0) { ZVAL_LONG(arg2, intern->u.file.max_line_len); } else { ZVAL_LONG(arg2, 1024); } spl_filesystem_file_free_line(intern TSRMLS_CC); intern->u.file.current_line_num++; FileFunctionCall(fgetss, ZEND_NUM_ARGS(), arg2); zval_ptr_dtor(&arg2); } /* }}} */ /* {{{ proto int SplFileObject::fpassthru() Output all remaining data from a file pointer */ SPL_METHOD(SplFileObject, fpassthru) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); RETURN_LONG(php_stream_passthru(intern->u.file.stream)); } /* }}} */ /* {{{ proto bool SplFileObject::fscanf(string format [, string ...]) Implements a mostly ANSI compatible fscanf() */ SPL_METHOD(SplFileObject, fscanf) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_filesystem_file_free_line(intern TSRMLS_CC); intern->u.file.current_line_num++; FileFunctionCall(fscanf, ZEND_NUM_ARGS(), NULL); } /* }}} */ /* {{{ proto mixed SplFileObject::fwrite(string str [, int length]) Binary-safe file write */ SPL_METHOD(SplFileObject, fwrite) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *str; int str_len; int ret; long length = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &str, &str_len, &length) == FAILURE) { return; } if (ZEND_NUM_ARGS() > 1) { str_len = MAX(0, MIN(length, str_len)); } if (!str_len) { RETURN_LONG(0); } if (PG(magic_quotes_runtime)) { str = estrndup(str, str_len); php_stripslashes(str, &str_len TSRMLS_CC); ret = php_stream_write(intern->u.file.stream, str, str_len); efree(str); RETURN_LONG(ret); } RETURN_LONG(php_stream_write(intern->u.file.stream, str, str_len)); } /* }}} */ /* {{{ proto bool SplFileObject::fstat() Stat() on a filehandle */ FileFunction(fstat) /* }}} */ /* {{{ proto bool SplFileObject::ftruncate(int size) Truncate file to 'size' length */ SPL_METHOD(SplFileObject, ftruncate) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long size; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &size) == FAILURE) { return; } if (!php_stream_truncate_supported(intern->u.file.stream)) { zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Can't truncate file %s", intern->file_name); RETURN_FALSE; } RETURN_BOOL(0 == php_stream_truncate_set_size(intern->u.file.stream, size)); } /* }}} */ /* {{{ proto void SplFileObject::seek(int line_pos) Seek to specified line */ SPL_METHOD(SplFileObject, seek) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long line_pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &line_pos) == FAILURE) { return; } if (line_pos < 0) { zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Can't seek file %s to negative line %ld", intern->file_name, line_pos); RETURN_FALSE; } spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC); while(intern->u.file.current_line_num < line_pos) { if (spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC) == FAILURE) { break; } } } /* }}} */ /* {{{ Function/Class/Method definitions */ ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object___construct, 0, 0, 1) ZEND_ARG_INFO(0, file_name) ZEND_ARG_INFO(0, open_mode) ZEND_ARG_INFO(0, use_include_path) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_file_object_setFlags, 0) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_file_object_setMaxLineLen, 0) ZEND_ARG_INFO(0, max_len) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fgetcsv, 0, 0, 0) ZEND_ARG_INFO(0, delimiter) ZEND_ARG_INFO(0, enclosure) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fputcsv, 0, 0, 1) ZEND_ARG_INFO(0, fields) ZEND_ARG_INFO(0, delimiter) ZEND_ARG_INFO(0, enclosure) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_flock, 0, 0, 1) ZEND_ARG_INFO(0, operation) ZEND_ARG_INFO(1, wouldblock) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fseek, 0, 0, 1) ZEND_ARG_INFO(0, pos) ZEND_ARG_INFO(0, whence) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fgetss, 0, 0, 0) ZEND_ARG_INFO(0, allowable_tags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fscanf, 1, 0, 1) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fwrite, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, length) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_ftruncate, 0, 0, 1) ZEND_ARG_INFO(0, size) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_seek, 0, 0, 1) ZEND_ARG_INFO(0, line_pos) ZEND_END_ARG_INFO() static const zend_function_entry spl_SplFileObject_functions[] = { SPL_ME(SplFileObject, __construct, arginfo_file_object___construct, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, rewind, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, eof, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, valid, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fgets, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fgetcsv, arginfo_file_object_fgetcsv, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fputcsv, arginfo_file_object_fputcsv, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, setCsvControl, arginfo_file_object_fgetcsv, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, getCsvControl, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, flock, arginfo_file_object_flock, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fflush, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, ftell, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fseek, arginfo_file_object_fseek, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fgetc, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fpassthru, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fgetss, arginfo_file_object_fgetss, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fscanf, arginfo_file_object_fscanf, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fwrite, arginfo_file_object_fwrite, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fstat, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, ftruncate, arginfo_file_object_ftruncate, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, current, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, key, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, next, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, setFlags, arginfo_file_object_setFlags, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, getFlags, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, setMaxLineLen, arginfo_file_object_setMaxLineLen, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, getMaxLineLen, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, hasChildren, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, getChildren, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, seek, arginfo_file_object_seek, ZEND_ACC_PUBLIC) /* mappings */ SPL_MA(SplFileObject, getCurrentLine, SplFileObject, fgets, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_MA(SplFileObject, __toString, SplFileObject, current, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; ZEND_BEGIN_ARG_INFO_EX(arginfo_temp_file_object___construct, 0, 0, 0) ZEND_ARG_INFO(0, max_memory) ZEND_END_ARG_INFO() static const zend_function_entry spl_SplTempFileObject_functions[] = { SPL_ME(SplTempFileObject, __construct, arginfo_temp_file_object___construct, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; /* }}} */ /* {{{ PHP_MINIT_FUNCTION(spl_directory) */ PHP_MINIT_FUNCTION(spl_directory) { REGISTER_SPL_STD_CLASS_EX(SplFileInfo, spl_filesystem_object_new, spl_SplFileInfo_functions); memcpy(&spl_filesystem_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); spl_filesystem_object_handlers.clone_obj = spl_filesystem_object_clone; spl_filesystem_object_handlers.cast_object = spl_filesystem_object_cast; spl_filesystem_object_handlers.get_debug_info = spl_filesystem_object_get_debug_info; spl_ce_SplFileInfo->serialize = zend_class_serialize_deny; spl_ce_SplFileInfo->unserialize = zend_class_unserialize_deny; REGISTER_SPL_SUB_CLASS_EX(DirectoryIterator, SplFileInfo, spl_filesystem_object_new, spl_DirectoryIterator_functions); zend_class_implements(spl_ce_DirectoryIterator TSRMLS_CC, 1, zend_ce_iterator); REGISTER_SPL_IMPLEMENTS(DirectoryIterator, SeekableIterator); spl_ce_DirectoryIterator->get_iterator = spl_filesystem_dir_get_iterator; REGISTER_SPL_SUB_CLASS_EX(FilesystemIterator, DirectoryIterator, spl_filesystem_object_new, spl_FilesystemIterator_functions); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_MODE_MASK", SPL_FILE_DIR_CURRENT_MODE_MASK); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_PATHNAME", SPL_FILE_DIR_CURRENT_AS_PATHNAME); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_FILEINFO", SPL_FILE_DIR_CURRENT_AS_FILEINFO); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_SELF", SPL_FILE_DIR_CURRENT_AS_SELF); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_MODE_MASK", SPL_FILE_DIR_KEY_MODE_MASK); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_AS_PATHNAME", SPL_FILE_DIR_KEY_AS_PATHNAME); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "FOLLOW_SYMLINKS", SPL_FILE_DIR_FOLLOW_SYMLINKS); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_AS_FILENAME", SPL_FILE_DIR_KEY_AS_FILENAME); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "NEW_CURRENT_AND_KEY", SPL_FILE_DIR_KEY_AS_FILENAME|SPL_FILE_DIR_CURRENT_AS_FILEINFO); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "SKIP_DOTS", SPL_FILE_DIR_SKIPDOTS); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "UNIX_PATHS", SPL_FILE_DIR_UNIXPATHS); spl_ce_FilesystemIterator->get_iterator = spl_filesystem_tree_get_iterator; REGISTER_SPL_SUB_CLASS_EX(RecursiveDirectoryIterator, FilesystemIterator, spl_filesystem_object_new, spl_RecursiveDirectoryIterator_functions); REGISTER_SPL_IMPLEMENTS(RecursiveDirectoryIterator, RecursiveIterator); #ifdef HAVE_GLOB REGISTER_SPL_SUB_CLASS_EX(GlobIterator, FilesystemIterator, spl_filesystem_object_new, spl_GlobIterator_functions); REGISTER_SPL_IMPLEMENTS(GlobIterator, Countable); #endif REGISTER_SPL_SUB_CLASS_EX(SplFileObject, SplFileInfo, spl_filesystem_object_new, spl_SplFileObject_functions); REGISTER_SPL_IMPLEMENTS(SplFileObject, RecursiveIterator); REGISTER_SPL_IMPLEMENTS(SplFileObject, SeekableIterator); REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "DROP_NEW_LINE", SPL_FILE_OBJECT_DROP_NEW_LINE); REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "READ_AHEAD", SPL_FILE_OBJECT_READ_AHEAD); REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "SKIP_EMPTY", SPL_FILE_OBJECT_SKIP_EMPTY); REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "READ_CSV", SPL_FILE_OBJECT_READ_CSV); REGISTER_SPL_SUB_CLASS_EX(SplTempFileObject, SplFileObject, spl_filesystem_object_new, spl_SplTempFileObject_functions); return SUCCESS; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Marcus Boerger <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" #include "ext/standard/file.h" #include "ext/standard/php_string.h" #include "zend_compile.h" #include "zend_exceptions.h" #include "zend_interfaces.h" #include "php_spl.h" #include "spl_functions.h" #include "spl_engine.h" #include "spl_iterators.h" #include "spl_directory.h" #include "spl_exceptions.h" #include "php.h" #include "fopen_wrappers.h" #include "ext/standard/basic_functions.h" #include "ext/standard/php_filestat.h" #define SPL_HAS_FLAG(flags, test_flag) ((flags & test_flag) ? 1 : 0) /* declare the class handlers */ static zend_object_handlers spl_filesystem_object_handlers; /* decalre the class entry */ PHPAPI zend_class_entry *spl_ce_SplFileInfo; PHPAPI zend_class_entry *spl_ce_DirectoryIterator; PHPAPI zend_class_entry *spl_ce_FilesystemIterator; PHPAPI zend_class_entry *spl_ce_RecursiveDirectoryIterator; PHPAPI zend_class_entry *spl_ce_GlobIterator; PHPAPI zend_class_entry *spl_ce_SplFileObject; PHPAPI zend_class_entry *spl_ce_SplTempFileObject; static void spl_filesystem_file_free_line(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { if (intern->u.file.current_line) { efree(intern->u.file.current_line); intern->u.file.current_line = NULL; } if (intern->u.file.current_zval) { zval_ptr_dtor(&intern->u.file.current_zval); intern->u.file.current_zval = NULL; } } /* }}} */ static void spl_filesystem_object_free_storage(void *object TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern = (spl_filesystem_object*)object; if (intern->oth_handler && intern->oth_handler->dtor) { intern->oth_handler->dtor(intern TSRMLS_CC); } zend_object_std_dtor(&intern->std TSRMLS_CC); if (intern->_path) { efree(intern->_path); } if (intern->file_name) { efree(intern->file_name); } switch(intern->type) { case SPL_FS_INFO: break; case SPL_FS_DIR: if (intern->u.dir.dirp) { php_stream_close(intern->u.dir.dirp); intern->u.dir.dirp = NULL; } if (intern->u.dir.sub_path) { efree(intern->u.dir.sub_path); } break; case SPL_FS_FILE: if (intern->u.file.stream) { if (intern->u.file.zcontext) { /* zend_list_delref(Z_RESVAL_P(intern->zcontext));*/ } if (!intern->u.file.stream->is_persistent) { php_stream_free(intern->u.file.stream, PHP_STREAM_FREE_CLOSE); } else { php_stream_free(intern->u.file.stream, PHP_STREAM_FREE_CLOSE_PERSISTENT); } if (intern->u.file.open_mode) { efree(intern->u.file.open_mode); } if (intern->orig_path) { efree(intern->orig_path); } } spl_filesystem_file_free_line(intern TSRMLS_CC); break; } efree(object); } /* }}} */ /* {{{ spl_ce_dir_object_new */ /* creates the object by - allocating memory - initializing the object members - storing the object - setting it's handlers called from - clone - new */ static zend_object_value spl_filesystem_object_new_ex(zend_class_entry *class_type, spl_filesystem_object **obj TSRMLS_DC) { zend_object_value retval; spl_filesystem_object *intern; intern = emalloc(sizeof(spl_filesystem_object)); memset(intern, 0, sizeof(spl_filesystem_object)); /* intern->type = SPL_FS_INFO; done by set 0 */ intern->file_class = spl_ce_SplFileObject; intern->info_class = spl_ce_SplFileInfo; if (obj) *obj = intern; zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, (zend_objects_free_object_storage_t) spl_filesystem_object_free_storage, NULL TSRMLS_CC); retval.handlers = &spl_filesystem_object_handlers; return retval; } /* }}} */ /* {{{ spl_filesystem_object_new */ /* See spl_filesystem_object_new_ex */ static zend_object_value spl_filesystem_object_new(zend_class_entry *class_type TSRMLS_DC) { return spl_filesystem_object_new_ex(class_type, NULL TSRMLS_CC); } /* }}} */ PHPAPI char* spl_filesystem_object_get_path(spl_filesystem_object *intern, int *len TSRMLS_DC) /* {{{ */ { #ifdef HAVE_GLOB if (intern->type == SPL_FS_DIR) { if (php_stream_is(intern->u.dir.dirp ,&php_glob_stream_ops)) { return php_glob_stream_get_path(intern->u.dir.dirp, 0, len); } } #endif if (len) { *len = intern->_path_len; } return intern->_path; } /* }}} */ static inline void spl_filesystem_object_get_file_name(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH; if (!intern->file_name) { switch (intern->type) { case SPL_FS_INFO: case SPL_FS_FILE: php_error_docref(NULL TSRMLS_CC, E_ERROR, "Object not initialized"); break; case SPL_FS_DIR: intern->file_name_len = spprintf(&intern->file_name, 0, "%s%c%s", spl_filesystem_object_get_path(intern, NULL TSRMLS_CC), slash, intern->u.dir.entry.d_name); break; } } } /* }}} */ static int spl_filesystem_dir_read(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { if (!intern->u.dir.dirp || !php_stream_readdir(intern->u.dir.dirp, &intern->u.dir.entry)) { intern->u.dir.entry.d_name[0] = '\0'; return 0; } else { return 1; } } /* }}} */ #define IS_SLASH_AT(zs, pos) (IS_SLASH(zs[pos])) static inline int spl_filesystem_is_dot(const char * d_name) /* {{{ */ { return !strcmp(d_name, ".") || !strcmp(d_name, ".."); } /* }}} */ /* {{{ spl_filesystem_dir_open */ /* open a directory resource */ static void spl_filesystem_dir_open(spl_filesystem_object* intern, char *path TSRMLS_DC) { int skip_dots = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_SKIPDOTS); intern->type = SPL_FS_DIR; intern->_path_len = strlen(path); intern->u.dir.dirp = php_stream_opendir(path, REPORT_ERRORS, NULL); if (intern->_path_len > 1 && IS_SLASH_AT(path, intern->_path_len-1)) { intern->_path = estrndup(path, --intern->_path_len); } else { intern->_path = estrndup(path, intern->_path_len); } intern->u.dir.index = 0; if (EG(exception) || intern->u.dir.dirp == NULL) { intern->u.dir.entry.d_name[0] = '\0'; if (!EG(exception)) { /* open failed w/out notice (turned to exception due to EH_THROW) */ zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Failed to open directory \"%s\"", path); } } else { do { spl_filesystem_dir_read(intern TSRMLS_CC); } while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name)); } } /* }}} */ static int spl_filesystem_file_open(spl_filesystem_object *intern, int use_include_path, int silent TSRMLS_DC) /* {{{ */ { intern->type = SPL_FS_FILE; intern->u.file.context = php_stream_context_from_zval(intern->u.file.zcontext, 0); intern->u.file.stream = php_stream_open_wrapper_ex(intern->file_name, intern->u.file.open_mode, (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, intern->u.file.context); if (!intern->file_name_len || !intern->u.file.stream) { if (!EG(exception)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot open file '%s'", intern->file_name_len ? intern->file_name : ""); } intern->file_name = NULL; /* until here it is not a copy */ intern->u.file.open_mode = NULL; return FAILURE; } if (intern->u.file.zcontext) { zend_list_addref(Z_RESVAL_P(intern->u.file.zcontext)); } if (intern->file_name_len > 1 && IS_SLASH_AT(intern->file_name, intern->file_name_len-1)) { intern->file_name_len--; } intern->orig_path = estrndup(intern->u.file.stream->orig_path, strlen(intern->u.file.stream->orig_path)); intern->file_name = estrndup(intern->file_name, intern->file_name_len); intern->u.file.open_mode = estrndup(intern->u.file.open_mode, intern->u.file.open_mode_len); /* avoid reference counting in debug mode, thus do it manually */ ZVAL_RESOURCE(&intern->u.file.zresource, php_stream_get_resource_id(intern->u.file.stream)); Z_SET_REFCOUNT(intern->u.file.zresource, 1); intern->u.file.delimiter = ','; intern->u.file.enclosure = '"'; intern->u.file.escape = '\\'; zend_hash_find(&intern->std.ce->function_table, "getcurrentline", sizeof("getcurrentline"), (void **) &intern->u.file.func_getCurr); return SUCCESS; } /* }}} */ /* {{{ spl_filesystem_object_clone */ /* Local zend_object_value creation (on stack) Load the 'other' object Create a new empty object (See spl_filesystem_object_new_ex) Open the directory Clone other members (properties) */ static zend_object_value spl_filesystem_object_clone(zval *zobject TSRMLS_DC) { zend_object_value new_obj_val; zend_object *old_object; zend_object *new_object; zend_object_handle handle = Z_OBJ_HANDLE_P(zobject); spl_filesystem_object *intern; spl_filesystem_object *source; int index, skip_dots; old_object = zend_objects_get_address(zobject TSRMLS_CC); source = (spl_filesystem_object*)old_object; new_obj_val = spl_filesystem_object_new_ex(old_object->ce, &intern TSRMLS_CC); new_object = &intern->std; intern->flags = source->flags; switch (source->type) { case SPL_FS_INFO: intern->_path_len = source->_path_len; intern->_path = estrndup(source->_path, source->_path_len); intern->file_name_len = source->file_name_len; intern->file_name = estrndup(source->file_name, intern->file_name_len); break; case SPL_FS_DIR: spl_filesystem_dir_open(intern, source->_path TSRMLS_CC); /* read until we hit the position in which we were before */ skip_dots = SPL_HAS_FLAG(source->flags, SPL_FILE_DIR_SKIPDOTS); for(index = 0; index < source->u.dir.index; ++index) { do { spl_filesystem_dir_read(intern TSRMLS_CC); } while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name)); } intern->u.dir.index = index; break; case SPL_FS_FILE: php_error_docref(NULL TSRMLS_CC, E_ERROR, "An object of class %s cannot be cloned", old_object->ce->name); break; } intern->file_class = source->file_class; intern->info_class = source->info_class; intern->oth = source->oth; intern->oth_handler = source->oth_handler; zend_objects_clone_members(new_object, new_obj_val, old_object, handle TSRMLS_CC); if (intern->oth_handler && intern->oth_handler->clone) { intern->oth_handler->clone(source, intern TSRMLS_CC); } return new_obj_val; } /* }}} */ void spl_filesystem_info_set_filename(spl_filesystem_object *intern, char *path, int len, int use_copy TSRMLS_DC) /* {{{ */ { char *p1, *p2; intern->file_name = use_copy ? estrndup(path, len) : path; intern->file_name_len = len; while(IS_SLASH_AT(intern->file_name, intern->file_name_len-1) && intern->file_name_len > 1) { intern->file_name[intern->file_name_len-1] = 0; intern->file_name_len--; } p1 = strrchr(intern->file_name, '/'); #if defined(PHP_WIN32) || defined(NETWARE) p2 = strrchr(intern->file_name, '\\'); #else p2 = 0; #endif if (p1 || p2) { intern->_path_len = (p1 > p2 ? p1 : p2) - intern->file_name; } else { intern->_path_len = 0; } intern->_path = estrndup(path, intern->_path_len); } /* }}} */ static spl_filesystem_object * spl_filesystem_object_create_info(spl_filesystem_object *source, char *file_path, int file_path_len, int use_copy, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern; zval *arg1; zend_error_handling error_handling; if (!file_path || !file_path_len) { #if defined(PHP_WIN32) zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot create SplFileInfo for empty path"); if (file_path && !use_copy) { efree(file_path); } #else if (file_path && !use_copy) { efree(file_path); } use_copy = 1; file_path_len = 1; file_path = "/"; #endif return NULL; } zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); ce = ce ? ce : source->info_class; zend_update_class_constants(ce TSRMLS_CC); return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); Z_TYPE_P(return_value) = IS_OBJECT; if (ce->constructor->common.scope != spl_ce_SplFileInfo) { MAKE_STD_ZVAL(arg1); ZVAL_STRINGL(arg1, file_path, file_path_len, use_copy); zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1); zval_ptr_dtor(&arg1); } else { spl_filesystem_info_set_filename(intern, file_path, file_path_len, use_copy TSRMLS_CC); } zend_restore_error_handling(&error_handling TSRMLS_CC); return intern; } /* }}} */ static spl_filesystem_object * spl_filesystem_object_create_type(int ht, spl_filesystem_object *source, int type, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern; zend_bool use_include_path = 0; zval *arg1, *arg2; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); switch (source->type) { case SPL_FS_INFO: case SPL_FS_FILE: break; case SPL_FS_DIR: if (!source->u.dir.entry.d_name[0]) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Could not open file"); zend_restore_error_handling(&error_handling TSRMLS_CC); return NULL; } } switch (type) { case SPL_FS_INFO: ce = ce ? ce : source->info_class; zend_update_class_constants(ce TSRMLS_CC); return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); Z_TYPE_P(return_value) = IS_OBJECT; spl_filesystem_object_get_file_name(source TSRMLS_CC); if (ce->constructor->common.scope != spl_ce_SplFileInfo) { MAKE_STD_ZVAL(arg1); ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1); zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1); zval_ptr_dtor(&arg1); } else { intern->file_name = estrndup(source->file_name, source->file_name_len); intern->file_name_len = source->file_name_len; intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC); intern->_path = estrndup(intern->_path, intern->_path_len); } break; case SPL_FS_FILE: ce = ce ? ce : source->file_class; zend_update_class_constants(ce TSRMLS_CC); return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); Z_TYPE_P(return_value) = IS_OBJECT; spl_filesystem_object_get_file_name(source TSRMLS_CC); if (ce->constructor->common.scope != spl_ce_SplFileObject) { MAKE_STD_ZVAL(arg1); MAKE_STD_ZVAL(arg2); ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1); ZVAL_STRINGL(arg2, "r", 1, 1); zend_call_method_with_2_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1, arg2); zval_ptr_dtor(&arg1); zval_ptr_dtor(&arg2); } else { intern->file_name = source->file_name; intern->file_name_len = source->file_name_len; intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC); intern->_path = estrndup(intern->_path, intern->_path_len); intern->u.file.open_mode = "r"; intern->u.file.open_mode_len = 1; if (ht && zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sbr", &intern->u.file.open_mode, &intern->u.file.open_mode_len, &use_include_path, &intern->u.file.zcontext) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); intern->u.file.open_mode = NULL; intern->file_name = NULL; zval_dtor(return_value); Z_TYPE_P(return_value) = IS_NULL; return NULL; } if (spl_filesystem_file_open(intern, use_include_path, 0 TSRMLS_CC) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); zval_dtor(return_value); Z_TYPE_P(return_value) = IS_NULL; return NULL; } } break; case SPL_FS_DIR: zend_restore_error_handling(&error_handling TSRMLS_CC); zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Operation not supported"); return NULL; } zend_restore_error_handling(&error_handling TSRMLS_CC); return NULL; } /* }}} */ static int spl_filesystem_is_invalid_or_dot(const char * d_name) /* {{{ */ { return d_name[0] == '\0' || spl_filesystem_is_dot(d_name); } /* }}} */ static char *spl_filesystem_object_get_pathname(spl_filesystem_object *intern, int *len TSRMLS_DC) { /* {{{ */ switch (intern->type) { case SPL_FS_INFO: case SPL_FS_FILE: *len = intern->file_name_len; return intern->file_name; case SPL_FS_DIR: if (intern->u.dir.entry.d_name[0]) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); *len = intern->file_name_len; return intern->file_name; } } *len = 0; return NULL; } /* }}} */ static HashTable* spl_filesystem_object_get_debug_info(zval *obj, int *is_temp TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(obj TSRMLS_CC); HashTable *rv; zval *tmp, zrv; char *pnstr, *path; int pnlen, path_len; char stmp[2]; *is_temp = 1; if (!intern->std.properties) { rebuild_object_properties(&intern->std); } ALLOC_HASHTABLE(rv); ZEND_INIT_SYMTABLE_EX(rv, zend_hash_num_elements(intern->std.properties) + 3, 0); INIT_PZVAL(&zrv); Z_ARRVAL(zrv) = rv; zend_hash_copy(rv, intern->std.properties, (copy_ctor_func_t) zval_add_ref, (void *) &tmp, sizeof(zval *)); pnstr = spl_gen_private_prop_name(spl_ce_SplFileInfo, "pathName", sizeof("pathName")-1, &pnlen TSRMLS_CC); path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC); add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, path, path_len, 1); efree(pnstr); if (intern->file_name) { pnstr = spl_gen_private_prop_name(spl_ce_SplFileInfo, "fileName", sizeof("fileName")-1, &pnlen TSRMLS_CC); spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); if (path_len && path_len < intern->file_name_len) { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->file_name + path_len + 1, intern->file_name_len - (path_len + 1), 1); } else { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->file_name, intern->file_name_len, 1); } efree(pnstr); } if (intern->type == SPL_FS_DIR) { #ifdef HAVE_GLOB pnstr = spl_gen_private_prop_name(spl_ce_DirectoryIterator, "glob", sizeof("glob")-1, &pnlen TSRMLS_CC); if (php_stream_is(intern->u.dir.dirp ,&php_glob_stream_ops)) { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->_path, intern->_path_len, 1); } else { add_assoc_bool_ex(&zrv, pnstr, pnlen+1, 0); } efree(pnstr); #endif pnstr = spl_gen_private_prop_name(spl_ce_RecursiveDirectoryIterator, "subPathName", sizeof("subPathName")-1, &pnlen TSRMLS_CC); if (intern->u.dir.sub_path) { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->u.dir.sub_path, intern->u.dir.sub_path_len, 1); } else { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, "", 0, 1); } efree(pnstr); } if (intern->type == SPL_FS_FILE) { pnstr = spl_gen_private_prop_name(spl_ce_SplFileObject, "openMode", sizeof("openMode")-1, &pnlen TSRMLS_CC); add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->u.file.open_mode, intern->u.file.open_mode_len, 1); efree(pnstr); stmp[1] = '\0'; stmp[0] = intern->u.file.delimiter; pnstr = spl_gen_private_prop_name(spl_ce_SplFileObject, "delimiter", sizeof("delimiter")-1, &pnlen TSRMLS_CC); add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, stmp, 1, 1); efree(pnstr); stmp[0] = intern->u.file.enclosure; pnstr = spl_gen_private_prop_name(spl_ce_SplFileObject, "enclosure", sizeof("enclosure")-1, &pnlen TSRMLS_CC); add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, stmp, 1, 1); efree(pnstr); } return rv; } /* }}} */ #define DIT_CTOR_FLAGS 0x00000001 #define DIT_CTOR_GLOB 0x00000002 void spl_filesystem_object_construct(INTERNAL_FUNCTION_PARAMETERS, long ctor_flags) /* {{{ */ { spl_filesystem_object *intern; char *path; int parsed, len; long flags; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (SPL_HAS_FLAG(ctor_flags, DIT_CTOR_FLAGS)) { flags = SPL_FILE_DIR_KEY_AS_PATHNAME|SPL_FILE_DIR_CURRENT_AS_FILEINFO; parsed = zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &path, &len, &flags); } else { flags = SPL_FILE_DIR_KEY_AS_PATHNAME|SPL_FILE_DIR_CURRENT_AS_SELF; parsed = zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &path, &len); } if (SPL_HAS_FLAG(ctor_flags, SPL_FILE_DIR_SKIPDOTS)) { flags |= SPL_FILE_DIR_SKIPDOTS; } if (SPL_HAS_FLAG(ctor_flags, SPL_FILE_DIR_UNIXPATHS)) { flags |= SPL_FILE_DIR_UNIXPATHS; } if (parsed == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (!len) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Directory name must not be empty."); zend_restore_error_handling(&error_handling TSRMLS_CC); return; } intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); intern->flags = flags; #ifdef HAVE_GLOB if (SPL_HAS_FLAG(ctor_flags, DIT_CTOR_GLOB) && strstr(path, "glob://") != path) { spprintf(&path, 0, "glob://%s", path); spl_filesystem_dir_open(intern, path TSRMLS_CC); efree(path); } else #endif { spl_filesystem_dir_open(intern, path TSRMLS_CC); } intern->u.dir.is_recursive = instanceof_function(intern->std.ce, spl_ce_RecursiveDirectoryIterator TSRMLS_CC) ? 1 : 0; zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void DirectoryIterator::__construct(string path) Cronstructs a new dir iterator from a path. */ SPL_METHOD(DirectoryIterator, __construct) { spl_filesystem_object_construct(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto void DirectoryIterator::rewind() Rewind dir back to the start */ SPL_METHOD(DirectoryIterator, rewind) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } intern->u.dir.index = 0; if (intern->u.dir.dirp) { php_stream_rewinddir(intern->u.dir.dirp); } spl_filesystem_dir_read(intern TSRMLS_CC); } /* }}} */ /* {{{ proto string DirectoryIterator::key() Return current dir entry */ SPL_METHOD(DirectoryIterator, key) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.dirp) { RETURN_LONG(intern->u.dir.index); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto DirectoryIterator DirectoryIterator::current() Return this (needed for Iterator interface) */ SPL_METHOD(DirectoryIterator, current) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_ZVAL(getThis(), 1, 0); } /* }}} */ /* {{{ proto void DirectoryIterator::next() Move to next entry */ SPL_METHOD(DirectoryIterator, next) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); int skip_dots = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_SKIPDOTS); if (zend_parse_parameters_none() == FAILURE) { return; } intern->u.dir.index++; do { spl_filesystem_dir_read(intern TSRMLS_CC); } while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name)); if (intern->file_name) { efree(intern->file_name); intern->file_name = NULL; } } /* }}} */ /* {{{ proto void DirectoryIterator::seek(int position) Seek to the given position */ SPL_METHOD(DirectoryIterator, seek) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zval *retval = NULL; long pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &pos) == FAILURE) { return; } if (intern->u.dir.index > pos) { /* we first rewind */ zend_call_method_with_0_params(&this_ptr, Z_OBJCE_P(getThis()), &intern->u.dir.func_rewind, "rewind", &retval); if (retval) { zval_ptr_dtor(&retval); } } while (intern->u.dir.index < pos) { int valid = 0; zend_call_method_with_0_params(&this_ptr, Z_OBJCE_P(getThis()), &intern->u.dir.func_valid, "valid", &retval); if (retval) { valid = zend_is_true(retval); zval_ptr_dtor(&retval); } if (!valid) { break; } zend_call_method_with_0_params(&this_ptr, Z_OBJCE_P(getThis()), &intern->u.dir.func_next, "next", &retval); if (retval) { zval_ptr_dtor(&retval); } } } /* }}} */ /* {{{ proto string DirectoryIterator::valid() Check whether dir contains more entries */ SPL_METHOD(DirectoryIterator, valid) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(intern->u.dir.entry.d_name[0] != '\0'); } /* }}} */ /* {{{ proto string SplFileInfo::getPath() Return the path */ SPL_METHOD(SplFileInfo, getPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *path; int path_len; if (zend_parse_parameters_none() == FAILURE) { return; } path = spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); RETURN_STRINGL(path, path_len, 1); } /* }}} */ /* {{{ proto string SplFileInfo::getFilename() Return filename only */ SPL_METHOD(SplFileInfo, getFilename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); int path_len; if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); if (path_len && path_len < intern->file_name_len) { RETURN_STRINGL(intern->file_name + path_len + 1, intern->file_name_len - (path_len + 1), 1); } else { RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } } /* }}} */ /* {{{ proto string DirectoryIterator::getFilename() Return filename of current dir entry */ SPL_METHOD(DirectoryIterator, getFilename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_STRING(intern->u.dir.entry.d_name, 1); } /* }}} */ /* {{{ proto string SplFileInfo::getExtension() Returns file extension component of path */ SPL_METHOD(SplFileInfo, getExtension) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *fname = NULL; const char *p; size_t flen; int path_len, idx; if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); if (path_len && path_len < intern->file_name_len) { fname = intern->file_name + path_len + 1; flen = intern->file_name_len - (path_len + 1); } else { fname = intern->file_name; flen = intern->file_name_len; } php_basename(fname, flen, NULL, 0, &fname, &flen TSRMLS_CC); p = zend_memrchr(fname, '.', flen); if (p) { idx = p - fname; RETVAL_STRINGL(fname + idx + 1, flen - idx - 1, 1); efree(fname); return; } else { if (fname) { efree(fname); } RETURN_EMPTY_STRING(); } } /* }}}*/ /* {{{ proto string DirectoryIterator::getExtension() Returns the file extension component of path */ SPL_METHOD(DirectoryIterator, getExtension) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *fname = NULL; const char *p; size_t flen; int idx; if (zend_parse_parameters_none() == FAILURE) { return; } php_basename(intern->u.dir.entry.d_name, strlen(intern->u.dir.entry.d_name), NULL, 0, &fname, &flen TSRMLS_CC); p = zend_memrchr(fname, '.', flen); if (p) { idx = p - fname; RETVAL_STRINGL(fname + idx + 1, flen - idx - 1, 1); efree(fname); return; } else { if (fname) { efree(fname); } RETURN_EMPTY_STRING(); } } /* }}} */ /* {{{ proto string SplFileInfo::getBasename([string $suffix]) U Returns filename component of path */ SPL_METHOD(SplFileInfo, getBasename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *fname, *suffix = 0; size_t flen; int slen = 0, path_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &suffix, &slen) == FAILURE) { return; } spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); if (path_len && path_len < intern->file_name_len) { fname = intern->file_name + path_len + 1; flen = intern->file_name_len - (path_len + 1); } else { fname = intern->file_name; flen = intern->file_name_len; } php_basename(fname, flen, suffix, slen, &fname, &flen TSRMLS_CC); RETURN_STRINGL(fname, flen, 0); } /* }}}*/ /* {{{ proto string DirectoryIterator::getBasename([string $suffix]) U Returns filename component of current dir entry */ SPL_METHOD(DirectoryIterator, getBasename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *suffix = 0, *fname; int slen = 0; size_t flen; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &suffix, &slen) == FAILURE) { return; } php_basename(intern->u.dir.entry.d_name, strlen(intern->u.dir.entry.d_name), suffix, slen, &fname, &flen TSRMLS_CC); RETURN_STRINGL(fname, flen, 0); } /* }}} */ /* {{{ proto string SplFileInfo::getPathname() Return path and filename */ SPL_METHOD(SplFileInfo, getPathname) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *path; int path_len; if (zend_parse_parameters_none() == FAILURE) { return; } path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC); if (path != NULL) { RETURN_STRINGL(path, path_len, 1); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto string FilesystemIterator::key() Return getPathname() or getFilename() depending on flags */ SPL_METHOD(FilesystemIterator, key) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (SPL_FILE_DIR_KEY(intern, SPL_FILE_DIR_KEY_AS_FILENAME)) { RETURN_STRING(intern->u.dir.entry.d_name, 1); } else { spl_filesystem_object_get_file_name(intern TSRMLS_CC); RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } } /* }}} */ /* {{{ proto string FilesystemIterator::current() Return getFilename(), getFileInfo() or $this depending on flags */ SPL_METHOD(FilesystemIterator, current) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_PATHNAME)) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } else if (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_FILEINFO)) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); spl_filesystem_object_create_type(0, intern, SPL_FS_INFO, NULL, return_value TSRMLS_CC); } else { RETURN_ZVAL(getThis(), 1, 0); /*RETURN_STRING(intern->u.dir.entry.d_name, 1);*/ } } /* }}} */ /* {{{ proto bool DirectoryIterator::isDot() Returns true if current entry is '.' or '..' */ SPL_METHOD(DirectoryIterator, isDot) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(spl_filesystem_is_dot(intern->u.dir.entry.d_name)); } /* }}} */ /* {{{ proto void SplFileInfo::__construct(string file_name) Cronstructs a new SplFileInfo from a path. */ /* zend_replace_error_handling() is used to throw exceptions in case the constructor fails. Here we use this to ensure the object has a valid directory resource. When the constructor gets called the object is already created by the engine, so we must only call 'additional' initializations. */ SPL_METHOD(SplFileInfo, __construct) { spl_filesystem_object *intern; char *path; int len; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &path, &len) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_filesystem_info_set_filename(intern, path, len, 1 TSRMLS_CC); zend_restore_error_handling(&error_handling TSRMLS_CC); /* intern->type = SPL_FS_INFO; already set */ } /* }}} */ /* {{{ FileInfoFunction */ #define FileInfoFunction(func_name, func_num) \ SPL_METHOD(SplFileInfo, func_name) \ { \ spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); \ zend_error_handling error_handling; \ if (zend_parse_parameters_none() == FAILURE) { \ return; \ } \ \ zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);\ spl_filesystem_object_get_file_name(intern TSRMLS_CC); \ php_stat(intern->file_name, intern->file_name_len, func_num, return_value TSRMLS_CC); \ zend_restore_error_handling(&error_handling TSRMLS_CC); \ } /* }}} */ /* {{{ proto int SplFileInfo::getPerms() Get file permissions */ FileInfoFunction(getPerms, FS_PERMS) /* }}} */ /* {{{ proto int SplFileInfo::getInode() Get file inode */ FileInfoFunction(getInode, FS_INODE) /* }}} */ /* {{{ proto int SplFileInfo::getSize() Get file size */ FileInfoFunction(getSize, FS_SIZE) /* }}} */ /* {{{ proto int SplFileInfo::getOwner() Get file owner */ FileInfoFunction(getOwner, FS_OWNER) /* }}} */ /* {{{ proto int SplFileInfo::getGroup() Get file group */ FileInfoFunction(getGroup, FS_GROUP) /* }}} */ /* {{{ proto int SplFileInfo::getATime() Get last access time of file */ FileInfoFunction(getATime, FS_ATIME) /* }}} */ /* {{{ proto int SplFileInfo::getMTime() Get last modification time of file */ FileInfoFunction(getMTime, FS_MTIME) /* }}} */ /* {{{ proto int SplFileInfo::getCTime() Get inode modification time of file */ FileInfoFunction(getCTime, FS_CTIME) /* }}} */ /* {{{ proto string SplFileInfo::getType() Get file type */ FileInfoFunction(getType, FS_TYPE) /* }}} */ /* {{{ proto bool SplFileInfo::isWritable() Returns true if file can be written */ FileInfoFunction(isWritable, FS_IS_W) /* }}} */ /* {{{ proto bool SplFileInfo::isReadable() Returns true if file can be read */ FileInfoFunction(isReadable, FS_IS_R) /* }}} */ /* {{{ proto bool SplFileInfo::isExecutable() Returns true if file is executable */ FileInfoFunction(isExecutable, FS_IS_X) /* }}} */ /* {{{ proto bool SplFileInfo::isFile() Returns true if file is a regular file */ FileInfoFunction(isFile, FS_IS_FILE) /* }}} */ /* {{{ proto bool SplFileInfo::isDir() Returns true if file is directory */ FileInfoFunction(isDir, FS_IS_DIR) /* }}} */ /* {{{ proto bool SplFileInfo::isLink() Returns true if file is symbolic link */ FileInfoFunction(isLink, FS_IS_LINK) /* }}} */ /* {{{ proto string SplFileInfo::getLinkTarget() U Return the target of a symbolic link */ SPL_METHOD(SplFileInfo, getLinkTarget) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); int ret; char buff[MAXPATHLEN]; zend_error_handling error_handling; if (zend_parse_parameters_none() == FAILURE) { return; } zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); #if defined(PHP_WIN32) || HAVE_SYMLINK if (!IS_ABSOLUTE_PATH(intern->file_name, intern->file_name_len)) { char expanded_path[MAXPATHLEN]; /* TODO: Fix expand_filepath to do not resolve links but only expand the path (Pierre) */ if (!expand_filepath(intern->file_name, expanded_path TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "No such file or directory"); RETURN_FALSE; } ret = php_sys_readlink(expanded_path, buff, MAXPATHLEN - 1); } else { ret = php_sys_readlink(intern->file_name, buff, MAXPATHLEN-1); } #else ret = -1; /* always fail if not implemented */ #endif if (ret == -1) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Unable to read link %s, error: %s", intern->file_name, strerror(errno)); RETVAL_FALSE; } else { /* Append NULL to the end of the string */ buff[ret] = '\0'; RETVAL_STRINGL(buff, ret, 1); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ #if (!defined(__BEOS__) && !defined(NETWARE) && HAVE_REALPATH) || defined(ZTS) /* {{{ proto string SplFileInfo::getRealPath() Return the resolved path */ SPL_METHOD(SplFileInfo, getRealPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char buff[MAXPATHLEN]; char *filename; zend_error_handling error_handling; if (zend_parse_parameters_none() == FAILURE) { return; } zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); if (intern->type == SPL_FS_DIR && !intern->file_name && intern->u.dir.entry.d_name[0]) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); } if (intern->orig_path) { filename = intern->orig_path; } else { filename = intern->file_name; } if (filename && VCWD_REALPATH(filename, buff)) { #ifdef ZTS if (VCWD_ACCESS(buff, F_OK)) { RETVAL_FALSE; } else #endif RETVAL_STRING(buff, 1); } else { RETVAL_FALSE; } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ #endif /* {{{ proto SplFileObject SplFileInfo::openFile([string mode = 'r' [, bool use_include_path [, resource context]]]) Open the current file */ SPL_METHOD(SplFileInfo, openFile) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_filesystem_object_create_type(ht, intern, SPL_FS_FILE, NULL, return_value TSRMLS_CC); } /* }}} */ /* {{{ proto void SplFileInfo::setFileClass([string class_name]) Class to use in openFile() */ SPL_METHOD(SplFileInfo, setFileClass) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = spl_ce_SplFileObject; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { intern->file_class = ce; } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void SplFileInfo::setInfoClass([string class_name]) Class to use in getFileInfo(), getPathInfo() */ SPL_METHOD(SplFileInfo, setInfoClass) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = spl_ce_SplFileInfo; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { intern->info_class = ce; } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto SplFileInfo SplFileInfo::getFileInfo([string $class_name]) Get/copy file info */ SPL_METHOD(SplFileInfo, getFileInfo) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = intern->info_class; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { spl_filesystem_object_create_type(ht, intern, SPL_FS_INFO, ce, return_value TSRMLS_CC); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto SplFileInfo SplFileInfo::getPathInfo([string $class_name]) Get/copy file info */ SPL_METHOD(SplFileInfo, getPathInfo) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = intern->info_class; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { int path_len; char *path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC); if (path) { char *dpath = estrndup(path, path_len); path_len = php_dirname(dpath, path_len); spl_filesystem_object_create_info(intern, dpath, path_len, 1, ce, return_value TSRMLS_CC); efree(dpath); } } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void FilesystemIterator::__construct(string path [, int flags]) Cronstructs a new dir iterator from a path. */ SPL_METHOD(FilesystemIterator, __construct) { spl_filesystem_object_construct(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIT_CTOR_FLAGS | SPL_FILE_DIR_SKIPDOTS); } /* }}} */ /* {{{ proto void FilesystemIterator::rewind() Rewind dir back to the start */ SPL_METHOD(FilesystemIterator, rewind) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } intern->u.dir.index = 0; if (intern->u.dir.dirp) { php_stream_rewinddir(intern->u.dir.dirp); } do { spl_filesystem_dir_read(intern TSRMLS_CC); } while (spl_filesystem_is_dot(intern->u.dir.entry.d_name)); } /* }}} */ /* {{{ proto int FilesystemIterator::getFlags() Get handling flags */ SPL_METHOD(FilesystemIterator, getFlags) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(intern->flags & (SPL_FILE_DIR_KEY_MODE_MASK | SPL_FILE_DIR_CURRENT_MODE_MASK | SPL_FILE_DIR_OTHERS_MASK)); } /* }}} */ /* {{{ proto void FilesystemIterator::setFlags(long $flags) Set handling flags */ SPL_METHOD(FilesystemIterator, setFlags) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long flags; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &flags) == FAILURE) { return; } intern->flags &= ~(SPL_FILE_DIR_KEY_MODE_MASK|SPL_FILE_DIR_CURRENT_MODE_MASK|SPL_FILE_DIR_OTHERS_MASK); intern->flags |= ((SPL_FILE_DIR_KEY_MODE_MASK|SPL_FILE_DIR_CURRENT_MODE_MASK|SPL_FILE_DIR_OTHERS_MASK) & flags); } /* }}} */ /* {{{ proto bool RecursiveDirectoryIterator::hasChildren([bool $allow_links = false]) Returns whether current entry is a directory and not '.' or '..' */ SPL_METHOD(RecursiveDirectoryIterator, hasChildren) { zend_bool allow_links = 0; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &allow_links) == FAILURE) { return; } if (spl_filesystem_is_invalid_or_dot(intern->u.dir.entry.d_name)) { RETURN_FALSE; } else { spl_filesystem_object_get_file_name(intern TSRMLS_CC); if (!allow_links && !(intern->flags & SPL_FILE_DIR_FOLLOW_SYMLINKS)) { php_stat(intern->file_name, intern->file_name_len, FS_IS_LINK, return_value TSRMLS_CC); if (zend_is_true(return_value)) { RETURN_FALSE; } } php_stat(intern->file_name, intern->file_name_len, FS_IS_DIR, return_value TSRMLS_CC); } } /* }}} */ /* {{{ proto RecursiveDirectoryIterator DirectoryIterator::getChildren() Returns an iterator for the current entry if it is a directory */ SPL_METHOD(RecursiveDirectoryIterator, getChildren) { zval zpath, zflags; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_filesystem_object *subdir; char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH; if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_object_get_file_name(intern TSRMLS_CC); if (SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_CURRENT_AS_PATHNAME)) { RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } else { INIT_PZVAL(&zflags); INIT_PZVAL(&zpath); ZVAL_LONG(&zflags, intern->flags); ZVAL_STRINGL(&zpath, intern->file_name, intern->file_name_len, 0); spl_instantiate_arg_ex2(Z_OBJCE_P(getThis()), &return_value, 0, &zpath, &zflags TSRMLS_CC); subdir = (spl_filesystem_object*)zend_object_store_get_object(return_value TSRMLS_CC); if (subdir) { if (intern->u.dir.sub_path && intern->u.dir.sub_path[0]) { subdir->u.dir.sub_path_len = spprintf(&subdir->u.dir.sub_path, 0, "%s%c%s", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name); } else { subdir->u.dir.sub_path_len = strlen(intern->u.dir.entry.d_name); subdir->u.dir.sub_path = estrndup(intern->u.dir.entry.d_name, subdir->u.dir.sub_path_len); } subdir->info_class = intern->info_class; subdir->file_class = intern->file_class; subdir->oth = intern->oth; } } } /* }}} */ /* {{{ proto void RecursiveDirectoryIterator::getSubPath() Get sub path */ SPL_METHOD(RecursiveDirectoryIterator, getSubPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.sub_path) { RETURN_STRINGL(intern->u.dir.sub_path, intern->u.dir.sub_path_len, 1); } else { RETURN_STRINGL("", 0, 1); } } /* }}} */ /* {{{ proto void RecursiveDirectoryIterator::getSubPathname() Get sub path and file name */ SPL_METHOD(RecursiveDirectoryIterator, getSubPathname) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *sub_name; int len; char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH; if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.sub_path) { len = spprintf(&sub_name, 0, "%s%c%s", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name); RETURN_STRINGL(sub_name, len, 0); } else { RETURN_STRING(intern->u.dir.entry.d_name, 1); } } /* }}} */ /* {{{ proto int RecursiveDirectoryIterator::__construct(string path [, int flags]) Cronstructs a new dir iterator from a path. */ SPL_METHOD(RecursiveDirectoryIterator, __construct) { spl_filesystem_object_construct(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIT_CTOR_FLAGS); } /* }}} */ #ifdef HAVE_GLOB /* {{{ proto int GlobIterator::__construct(string path [, int flags]) Cronstructs a new dir iterator from a glob expression (no glob:// needed). */ SPL_METHOD(GlobIterator, __construct) { spl_filesystem_object_construct(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIT_CTOR_FLAGS|DIT_CTOR_GLOB); } /* }}} */ /* {{{ proto int GlobIterator::cont() Return the number of directories and files found by globbing */ SPL_METHOD(GlobIterator, count) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (php_stream_is(intern->u.dir.dirp ,&php_glob_stream_ops)) { RETURN_LONG(php_glob_stream_get_count(intern->u.dir.dirp, NULL)); } else { /* should not happen */ php_error_docref(NULL TSRMLS_CC, E_ERROR, "GlobIterator lost glob state"); } } /* }}} */ #endif /* HAVE_GLOB */ /* {{{ forward declarations to the iterator handlers */ static void spl_filesystem_dir_it_dtor(zend_object_iterator *iter TSRMLS_DC); static int spl_filesystem_dir_it_valid(zend_object_iterator *iter TSRMLS_DC); static void spl_filesystem_dir_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC); static int spl_filesystem_dir_it_current_key(zend_object_iterator *iter, char **str_key, uint *str_key_len, ulong *int_key TSRMLS_DC); static void spl_filesystem_dir_it_move_forward(zend_object_iterator *iter TSRMLS_DC); static void spl_filesystem_dir_it_rewind(zend_object_iterator *iter TSRMLS_DC); /* iterator handler table */ zend_object_iterator_funcs spl_filesystem_dir_it_funcs = { spl_filesystem_dir_it_dtor, spl_filesystem_dir_it_valid, spl_filesystem_dir_it_current_data, spl_filesystem_dir_it_current_key, spl_filesystem_dir_it_move_forward, spl_filesystem_dir_it_rewind }; /* }}} */ /* {{{ spl_ce_dir_get_iterator */ zend_object_iterator *spl_filesystem_dir_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) { spl_filesystem_iterator *iterator; spl_filesystem_object *dir_object; if (by_ref) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } dir_object = (spl_filesystem_object*)zend_object_store_get_object(object TSRMLS_CC); iterator = spl_filesystem_object_to_iterator(dir_object); Z_SET_REFCOUNT_P(object, Z_REFCOUNT_P(object) + 2); iterator->intern.data = (void*)object; iterator->intern.funcs = &spl_filesystem_dir_it_funcs; iterator->current = object; return (zend_object_iterator*)iterator; } /* }}} */ /* {{{ spl_filesystem_dir_it_dtor */ static void spl_filesystem_dir_it_dtor(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; zval *zfree = (zval*)iterator->intern.data; iterator->intern.data = NULL; /* mark as unused */ zval_ptr_dtor(&iterator->current); if (zfree) { zval_ptr_dtor(&zfree); } } /* }}} */ /* {{{ spl_filesystem_dir_it_valid */ static int spl_filesystem_dir_it_valid(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); return object->u.dir.entry.d_name[0] != '\0' ? SUCCESS : FAILURE; } /* }}} */ /* {{{ spl_filesystem_dir_it_current_data */ static void spl_filesystem_dir_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; *data = &iterator->current; } /* }}} */ /* {{{ spl_filesystem_dir_it_current_key */ static int spl_filesystem_dir_it_current_key(zend_object_iterator *iter, char **str_key, uint *str_key_len, ulong *int_key TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); *int_key = object->u.dir.index; return HASH_KEY_IS_LONG; } /* }}} */ /* {{{ spl_filesystem_dir_it_move_forward */ static void spl_filesystem_dir_it_move_forward(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); object->u.dir.index++; spl_filesystem_dir_read(object TSRMLS_CC); if (object->file_name) { efree(object->file_name); object->file_name = NULL; } } /* }}} */ /* {{{ spl_filesystem_dir_it_rewind */ static void spl_filesystem_dir_it_rewind(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); object->u.dir.index = 0; if (object->u.dir.dirp) { php_stream_rewinddir(object->u.dir.dirp); } spl_filesystem_dir_read(object TSRMLS_CC); } /* }}} */ /* {{{ spl_filesystem_tree_it_dtor */ static void spl_filesystem_tree_it_dtor(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; zval *zfree = (zval*)iterator->intern.data; if (iterator->current) { zval_ptr_dtor(&iterator->current); } iterator->intern.data = NULL; /* mark as unused */ /* free twice as we add ref twice */ zval_ptr_dtor(&zfree); zval_ptr_dtor(&zfree); } /* }}} */ /* {{{ spl_filesystem_tree_it_current_data */ static void spl_filesystem_tree_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator); if (SPL_FILE_DIR_CURRENT(object, SPL_FILE_DIR_CURRENT_AS_PATHNAME)) { if (!iterator->current) { ALLOC_INIT_ZVAL(iterator->current); spl_filesystem_object_get_file_name(object TSRMLS_CC); ZVAL_STRINGL(iterator->current, object->file_name, object->file_name_len, 1); } *data = &iterator->current; } else if (SPL_FILE_DIR_CURRENT(object, SPL_FILE_DIR_CURRENT_AS_FILEINFO)) { if (!iterator->current) { ALLOC_INIT_ZVAL(iterator->current); spl_filesystem_object_get_file_name(object TSRMLS_CC); spl_filesystem_object_create_type(0, object, SPL_FS_INFO, NULL, iterator->current TSRMLS_CC); } *data = &iterator->current; } else { *data = (zval**)&iterator->intern.data; } } /* }}} */ /* {{{ spl_filesystem_tree_it_current_key */ static int spl_filesystem_tree_it_current_key(zend_object_iterator *iter, char **str_key, uint *str_key_len, ulong *int_key TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); if (SPL_FILE_DIR_KEY(object, SPL_FILE_DIR_KEY_AS_FILENAME)) { *str_key_len = strlen(object->u.dir.entry.d_name) + 1; *str_key = estrndup(object->u.dir.entry.d_name, *str_key_len - 1); } else { spl_filesystem_object_get_file_name(object TSRMLS_CC); *str_key_len = object->file_name_len + 1; *str_key = estrndup(object->file_name, object->file_name_len); } return HASH_KEY_IS_STRING; } /* }}} */ /* {{{ spl_filesystem_tree_it_move_forward */ static void spl_filesystem_tree_it_move_forward(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator); object->u.dir.index++; do { spl_filesystem_dir_read(object TSRMLS_CC); } while (spl_filesystem_is_dot(object->u.dir.entry.d_name)); if (object->file_name) { efree(object->file_name); object->file_name = NULL; } if (iterator->current) { zval_ptr_dtor(&iterator->current); iterator->current = NULL; } } /* }}} */ /* {{{ spl_filesystem_tree_it_rewind */ static void spl_filesystem_tree_it_rewind(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator); object->u.dir.index = 0; if (object->u.dir.dirp) { php_stream_rewinddir(object->u.dir.dirp); } do { spl_filesystem_dir_read(object TSRMLS_CC); } while (spl_filesystem_is_dot(object->u.dir.entry.d_name)); if (iterator->current) { zval_ptr_dtor(&iterator->current); iterator->current = NULL; } } /* }}} */ /* {{{ iterator handler table */ zend_object_iterator_funcs spl_filesystem_tree_it_funcs = { spl_filesystem_tree_it_dtor, spl_filesystem_dir_it_valid, spl_filesystem_tree_it_current_data, spl_filesystem_tree_it_current_key, spl_filesystem_tree_it_move_forward, spl_filesystem_tree_it_rewind }; /* }}} */ /* {{{ spl_ce_dir_get_iterator */ zend_object_iterator *spl_filesystem_tree_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) { spl_filesystem_iterator *iterator; spl_filesystem_object *dir_object; if (by_ref) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } dir_object = (spl_filesystem_object*)zend_object_store_get_object(object TSRMLS_CC); iterator = spl_filesystem_object_to_iterator(dir_object); Z_SET_REFCOUNT_P(object, Z_REFCOUNT_P(object) + 2); iterator->intern.data = (void*)object; iterator->intern.funcs = &spl_filesystem_tree_it_funcs; iterator->current = NULL; return (zend_object_iterator*)iterator; } /* }}} */ /* {{{ spl_filesystem_object_cast */ static int spl_filesystem_object_cast(zval *readobj, zval *writeobj, int type TSRMLS_DC) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(readobj TSRMLS_CC); if (type == IS_STRING) { switch (intern->type) { case SPL_FS_INFO: case SPL_FS_FILE: if (readobj == writeobj) { zval retval; zval *retval_ptr = &retval; ZVAL_STRINGL(retval_ptr, intern->file_name, intern->file_name_len, 1); zval_dtor(readobj); ZVAL_ZVAL(writeobj, retval_ptr, 0, 0); } else { ZVAL_STRINGL(writeobj, intern->file_name, intern->file_name_len, 1); } return SUCCESS; case SPL_FS_DIR: if (readobj == writeobj) { zval retval; zval *retval_ptr = &retval; ZVAL_STRING(retval_ptr, intern->u.dir.entry.d_name, 1); zval_dtor(readobj); ZVAL_ZVAL(writeobj, retval_ptr, 0, 0); } else { ZVAL_STRING(writeobj, intern->u.dir.entry.d_name, 1); } return SUCCESS; } } if (readobj == writeobj) { zval_dtor(readobj); } ZVAL_NULL(writeobj); return FAILURE; } /* }}} */ /* {{{ declare method parameters */ /* supply a name and default to call by parameter */ ZEND_BEGIN_ARG_INFO(arginfo_info___construct, 0) ZEND_ARG_INFO(0, file_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_info_openFile, 0, 0, 0) ZEND_ARG_INFO(0, open_mode) ZEND_ARG_INFO(0, use_include_path) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_info_optinalFileClass, 0, 0, 0) ZEND_ARG_INFO(0, class_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_optinalSuffix, 0, 0, 0) ZEND_ARG_INFO(0, suffix) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_splfileinfo_void, 0) ZEND_END_ARG_INFO() /* the method table */ /* each method can have its own parameters and visibility */ static const zend_function_entry spl_SplFileInfo_functions[] = { SPL_ME(SplFileInfo, __construct, arginfo_info___construct, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getPath, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getFilename, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getExtension, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getBasename, arginfo_optinalSuffix, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getPathname, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getPerms, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getInode, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getSize, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getOwner, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getGroup, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getATime, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getMTime, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getCTime, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getType, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isWritable, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isReadable, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isExecutable, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isFile, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isDir, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isLink, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getLinkTarget, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) #if (!defined(__BEOS__) && !defined(NETWARE) && HAVE_REALPATH) || defined(ZTS) SPL_ME(SplFileInfo, getRealPath, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) #endif SPL_ME(SplFileInfo, getFileInfo, arginfo_info_optinalFileClass, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getPathInfo, arginfo_info_optinalFileClass, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, openFile, arginfo_info_openFile, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, setFileClass, arginfo_info_optinalFileClass, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, setInfoClass, arginfo_info_optinalFileClass, ZEND_ACC_PUBLIC) SPL_MA(SplFileInfo, __toString, SplFileInfo, getPathname, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; ZEND_BEGIN_ARG_INFO(arginfo_dir___construct, 0) ZEND_ARG_INFO(0, path) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_dir_it_seek, 0) ZEND_ARG_INFO(0, position) ZEND_END_ARG_INFO(); /* the method table */ /* each method can have its own parameters and visibility */ static const zend_function_entry spl_DirectoryIterator_functions[] = { SPL_ME(DirectoryIterator, __construct, arginfo_dir___construct, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, getFilename, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, getExtension, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, getBasename, arginfo_optinalSuffix, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, isDot, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, rewind, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, valid, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, key, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, current, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, next, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, seek, arginfo_dir_it_seek, ZEND_ACC_PUBLIC) SPL_MA(DirectoryIterator, __toString, DirectoryIterator, getFilename, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; ZEND_BEGIN_ARG_INFO_EX(arginfo_r_dir___construct, 0, 0, 1) ZEND_ARG_INFO(0, path) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_r_dir_hasChildren, 0, 0, 0) ZEND_ARG_INFO(0, allow_links) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_r_dir_setFlags, 0, 0, 0) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() static const zend_function_entry spl_FilesystemIterator_functions[] = { SPL_ME(FilesystemIterator, __construct, arginfo_r_dir___construct, ZEND_ACC_PUBLIC) SPL_ME(FilesystemIterator, rewind, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, next, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(FilesystemIterator, key, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(FilesystemIterator, current, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(FilesystemIterator, getFlags, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(FilesystemIterator, setFlags, arginfo_r_dir_setFlags, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; static const zend_function_entry spl_RecursiveDirectoryIterator_functions[] = { SPL_ME(RecursiveDirectoryIterator, __construct, arginfo_r_dir___construct, ZEND_ACC_PUBLIC) SPL_ME(RecursiveDirectoryIterator, hasChildren, arginfo_r_dir_hasChildren, ZEND_ACC_PUBLIC) SPL_ME(RecursiveDirectoryIterator, getChildren, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(RecursiveDirectoryIterator, getSubPath, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(RecursiveDirectoryIterator, getSubPathname,arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; #ifdef HAVE_GLOB static const zend_function_entry spl_GlobIterator_functions[] = { SPL_ME(GlobIterator, __construct, arginfo_r_dir___construct, ZEND_ACC_PUBLIC) SPL_ME(GlobIterator, count, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; #endif /* }}} */ static int spl_filesystem_file_read(spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */ { char *buf; size_t line_len = 0; int len; long line_add = (intern->u.file.current_line || intern->u.file.current_zval) ? 1 : 0; spl_filesystem_file_free_line(intern TSRMLS_CC); if (php_stream_eof(intern->u.file.stream)) { if (!silent) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot read from file %s", intern->file_name); } return FAILURE; } if (intern->u.file.max_line_len > 0) { buf = safe_emalloc((intern->u.file.max_line_len + 1), sizeof(char), 0); if (php_stream_get_line(intern->u.file.stream, buf, intern->u.file.max_line_len, &line_len) == NULL) { efree(buf); buf = NULL; } else { buf[line_len] = '\0'; } } else { buf = php_stream_get_line(intern->u.file.stream, NULL, 0, &line_len); } if (!buf) { intern->u.file.current_line = estrdup(""); intern->u.file.current_line_len = 0; } else { if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_DROP_NEW_LINE)) { line_len = strcspn(buf, "\r\n"); buf[line_len] = '\0'; } if (PG(magic_quotes_runtime)) { buf = php_addslashes(buf, line_len, &len, 1 TSRMLS_CC); line_len = len; } intern->u.file.current_line = buf; intern->u.file.current_line_len = line_len; } intern->u.file.current_line_num += line_add; return SUCCESS; } /* }}} */ static int spl_filesystem_file_call(spl_filesystem_object *intern, zend_function *func_ptr, int pass_num_args, zval *return_value, zval *arg2 TSRMLS_DC) /* {{{ */ { zend_fcall_info fci; zend_fcall_info_cache fcic; zval z_fname; zval * zresource_ptr = &intern->u.file.zresource, *retval; int result; int num_args = pass_num_args + (arg2 ? 2 : 1); zval ***params = (zval***)safe_emalloc(num_args, sizeof(zval**), 0); params[0] = &zresource_ptr; if (arg2) { params[1] = &arg2; } zend_get_parameters_array_ex(pass_num_args, params+(arg2 ? 2 : 1)); ZVAL_STRING(&z_fname, func_ptr->common.function_name, 0); fci.size = sizeof(fci); fci.function_table = EG(function_table); fci.object_ptr = NULL; fci.function_name = &z_fname; fci.retval_ptr_ptr = &retval; fci.param_count = num_args; fci.params = params; fci.no_separation = 1; fci.symbol_table = NULL; fcic.initialized = 1; fcic.function_handler = func_ptr; fcic.calling_scope = NULL; fcic.called_scope = NULL; fcic.object_ptr = NULL; result = zend_call_function(&fci, &fcic TSRMLS_CC); if (result == FAILURE) { RETVAL_FALSE; } else { ZVAL_ZVAL(return_value, retval, 1, 1); } efree(params); return result; } /* }}} */ #define FileFunctionCall(func_name, pass_num_args, arg2) /* {{{ */ \ { \ zend_function *func_ptr; \ int ret; \ ret = zend_hash_find(EG(function_table), #func_name, sizeof(#func_name), (void **) &func_ptr); \ if (ret != SUCCESS) { \ zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Internal error, function '%s' not found. Please report", #func_name); \ return; \ } \ spl_filesystem_file_call(intern, func_ptr, pass_num_args, return_value, arg2 TSRMLS_CC); \ } /* }}} */ static int spl_filesystem_file_read_csv(spl_filesystem_object *intern, char delimiter, char enclosure, char escape, zval *return_value TSRMLS_DC) /* {{{ */ { int ret = SUCCESS; do { ret = spl_filesystem_file_read(intern, 1 TSRMLS_CC); } while (ret == SUCCESS && !intern->u.file.current_line_len && SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY)); if (ret == SUCCESS) { size_t buf_len = intern->u.file.current_line_len; char *buf = estrndup(intern->u.file.current_line, buf_len); if (intern->u.file.current_zval) { zval_ptr_dtor(&intern->u.file.current_zval); } ALLOC_INIT_ZVAL(intern->u.file.current_zval); php_fgetcsv(intern->u.file.stream, delimiter, enclosure, escape, buf_len, buf, intern->u.file.current_zval TSRMLS_CC); if (return_value) { if (Z_TYPE_P(return_value) != IS_NULL) { zval_dtor(return_value); ZVAL_NULL(return_value); } ZVAL_ZVAL(return_value, intern->u.file.current_zval, 1, 0); } } return ret; } /* }}} */ static int spl_filesystem_file_read_line_ex(zval * this_ptr, spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */ { zval *retval = NULL; /* 1) use fgetcsv? 2) overloaded call the function, 3) do it directly */ if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) || intern->u.file.func_getCurr->common.scope != spl_ce_SplFileObject) { if (php_stream_eof(intern->u.file.stream)) { if (!silent) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot read from file %s", intern->file_name); } return FAILURE; } if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV)) { return spl_filesystem_file_read_csv(intern, intern->u.file.delimiter, intern->u.file.enclosure, intern->u.file.escape, NULL TSRMLS_CC); } else { zend_call_method_with_0_params(&this_ptr, Z_OBJCE_P(getThis()), &intern->u.file.func_getCurr, "getCurrentLine", &retval); } if (retval) { if (intern->u.file.current_line || intern->u.file.current_zval) { intern->u.file.current_line_num++; } spl_filesystem_file_free_line(intern TSRMLS_CC); if (Z_TYPE_P(retval) == IS_STRING) { intern->u.file.current_line = estrndup(Z_STRVAL_P(retval), Z_STRLEN_P(retval)); intern->u.file.current_line_len = Z_STRLEN_P(retval); } else { MAKE_STD_ZVAL(intern->u.file.current_zval); ZVAL_ZVAL(intern->u.file.current_zval, retval, 1, 0); } zval_ptr_dtor(&retval); return SUCCESS; } else { return FAILURE; } } else { return spl_filesystem_file_read(intern, silent TSRMLS_CC); } } /* }}} */ static int spl_filesystem_file_is_empty_line(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { if (intern->u.file.current_line) { return intern->u.file.current_line_len == 0; } else if (intern->u.file.current_zval) { switch(Z_TYPE_P(intern->u.file.current_zval)) { case IS_STRING: return Z_STRLEN_P(intern->u.file.current_zval) == 0; case IS_ARRAY: if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) && zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 1) { zval ** first = Z_ARRVAL_P(intern->u.file.current_zval)->pListHead->pData; return Z_TYPE_PP(first) == IS_STRING && Z_STRLEN_PP(first) == 0; } return zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 0; case IS_NULL: return 1; default: return 0; } } else { return 1; } } /* }}} */ static int spl_filesystem_file_read_line(zval * this_ptr, spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */ { int ret = spl_filesystem_file_read_line_ex(this_ptr, intern, silent TSRMLS_CC); while (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY) && ret == SUCCESS && spl_filesystem_file_is_empty_line(intern TSRMLS_CC)) { spl_filesystem_file_free_line(intern TSRMLS_CC); ret = spl_filesystem_file_read_line_ex(this_ptr, intern, silent TSRMLS_CC); } return ret; } /* }}} */ static void spl_filesystem_file_rewind(zval * this_ptr, spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { if (-1 == php_stream_rewind(intern->u.file.stream)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot rewind file %s", intern->file_name); } else { spl_filesystem_file_free_line(intern TSRMLS_CC); intern->u.file.current_line_num = 0; } if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_AHEAD)) { spl_filesystem_file_read_line(this_ptr, intern, 1 TSRMLS_CC); } } /* }}} */ /* {{{ proto void SplFileObject::__construct(string filename [, string mode = 'r' [, bool use_include_path [, resource context]]]]) Construct a new file object */ SPL_METHOD(SplFileObject, __construct) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_bool use_include_path = 0; char *p1, *p2; char *tmp_path; int tmp_path_len; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); intern->u.file.open_mode = "r"; intern->u.file.open_mode_len = 1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|sbr", &intern->file_name, &intern->file_name_len, &intern->u.file.open_mode, &intern->u.file.open_mode_len, &use_include_path, &intern->u.file.zcontext) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (spl_filesystem_file_open(intern, use_include_path, 0 TSRMLS_CC) == SUCCESS) { tmp_path_len = strlen(intern->u.file.stream->orig_path); if (tmp_path_len > 1 && IS_SLASH_AT(intern->u.file.stream->orig_path, tmp_path_len-1)) { tmp_path_len--; } tmp_path = estrndup(intern->u.file.stream->orig_path, tmp_path_len); p1 = strrchr(tmp_path, '/'); #if defined(PHP_WIN32) || defined(NETWARE) p2 = strrchr(tmp_path, '\\'); #else p2 = 0; #endif if (p1 || p2) { intern->_path_len = (p1 > p2 ? p1 : p2) - tmp_path; } else { intern->_path_len = 0; } efree(tmp_path); intern->_path = estrndup(intern->u.file.stream->orig_path, intern->_path_len); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void SplTempFileObject::__construct([int max_memory]) Construct a new temp file object */ SPL_METHOD(SplTempFileObject, __construct) { long max_memory = PHP_STREAM_MAX_MEM; char tmp_fname[48]; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &max_memory) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (max_memory < 0) { intern->file_name = "php://memory"; intern->file_name_len = 12; } else if (ZEND_NUM_ARGS()) { intern->file_name_len = slprintf(tmp_fname, sizeof(tmp_fname), "php://temp/maxmemory:%ld", max_memory); intern->file_name = tmp_fname; } else { intern->file_name = "php://temp"; intern->file_name_len = 10; } intern->u.file.open_mode = "wb"; intern->u.file.open_mode_len = 1; intern->u.file.zcontext = NULL; if (spl_filesystem_file_open(intern, 0, 0 TSRMLS_CC) == SUCCESS) { intern->_path_len = 0; intern->_path = estrndup("", 0); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void SplFileObject::rewind() Rewind the file and read the first line */ SPL_METHOD(SplFileObject, rewind) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC); } /* }}} */ /* {{{ proto void SplFileObject::eof() Return whether end of file is reached */ SPL_METHOD(SplFileObject, eof) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(php_stream_eof(intern->u.file.stream)); } /* }}} */ /* {{{ proto void SplFileObject::valid() Return !eof() */ SPL_METHOD(SplFileObject, valid) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_AHEAD)) { RETURN_BOOL(intern->u.file.current_line || intern->u.file.current_zval); } else { RETVAL_BOOL(!php_stream_eof(intern->u.file.stream)); } } /* }}} */ /* {{{ proto string SplFileObject::fgets() Rturn next line from file */ SPL_METHOD(SplFileObject, fgets) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (spl_filesystem_file_read(intern, 0 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1); } /* }}} */ /* {{{ proto string SplFileObject::current() Return current line from file */ SPL_METHOD(SplFileObject, current) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!intern->u.file.current_line && !intern->u.file.current_zval) { spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC); } if (intern->u.file.current_line && (!SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) || !intern->u.file.current_zval)) { RETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1); } else if (intern->u.file.current_zval) { RETURN_ZVAL(intern->u.file.current_zval, 1, 0); } RETURN_FALSE; } /* }}} */ /* {{{ proto int SplFileObject::key() Return line number */ SPL_METHOD(SplFileObject, key) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } /* Do not read the next line to support correct counting with fgetc() if (!intern->current_line) { spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC); } */ RETURN_LONG(intern->u.file.current_line_num); } /* }}} */ /* {{{ proto void SplFileObject::next() Read next line */ SPL_METHOD(SplFileObject, next) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_file_free_line(intern TSRMLS_CC); if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_AHEAD)) { spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC); } intern->u.file.current_line_num++; } /* }}} */ /* {{{ proto void SplFileObject::setFlags(int flags) Set file handling flags */ SPL_METHOD(SplFileObject, setFlags) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &intern->flags); } /* }}} */ /* {{{ proto int SplFileObject::getFlags() Get file handling flags */ SPL_METHOD(SplFileObject, getFlags) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(intern->flags & SPL_FILE_OBJECT_MASK); } /* }}} */ /* {{{ proto void SplFileObject::setMaxLineLen(int max_len) Set maximum line length */ SPL_METHOD(SplFileObject, setMaxLineLen) { long max_len; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &max_len) == FAILURE) { return; } if (max_len < 0) { zend_throw_exception_ex(spl_ce_DomainException, 0 TSRMLS_CC, "Maximum line length must be greater than or equal zero"); return; } intern->u.file.max_line_len = max_len; } /* }}} */ /* {{{ proto int SplFileObject::getMaxLineLen() Get maximum line length */ SPL_METHOD(SplFileObject, getMaxLineLen) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG((long)intern->u.file.max_line_len); } /* }}} */ /* {{{ proto bool SplFileObject::hasChildren() Return false */ SPL_METHOD(SplFileObject, hasChildren) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_FALSE; } /* }}} */ /* {{{ proto bool SplFileObject::getChildren() Read NULL */ SPL_METHOD(SplFileObject, getChildren) { if (zend_parse_parameters_none() == FAILURE) { return; } /* return NULL */ } /* }}} */ /* {{{ FileFunction */ #define FileFunction(func_name) \ SPL_METHOD(SplFileObject, func_name) \ { \ spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); \ FileFunctionCall(func_name, ZEND_NUM_ARGS(), NULL); \ } /* }}} */ /* {{{ proto array SplFileObject::fgetcsv([string delimiter [, string enclosure [, escape = '\\']]]) Return current line as csv */ SPL_METHOD(SplFileObject, fgetcsv) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter = intern->u.file.delimiter, enclosure = intern->u.file.enclosure, escape = intern->u.file.escape; char *delim = NULL, *enclo = NULL, *esc = NULL; int d_len = 0, e_len = 0, esc_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sss", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) { switch(ZEND_NUM_ARGS()) { case 3: if (esc_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character"); RETURN_FALSE; } escape = esc[0]; /* no break */ case 2: if (e_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } enclosure = enclo[0]; /* no break */ case 1: if (d_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } delimiter = delim[0]; /* no break */ case 0: break; } spl_filesystem_file_read_csv(intern, delimiter, enclosure, escape, return_value TSRMLS_CC); } } /* }}} */ /* {{{ proto int SplFileObject::fputcsv(array fields, [string delimiter [, string enclosure]]) Output a field array as a CSV line */ SPL_METHOD(SplFileObject, fputcsv) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter = intern->u.file.delimiter, enclosure = intern->u.file.enclosure, escape = intern->u.file.escape; char *delim = NULL, *enclo = NULL; int d_len = 0, e_len = 0, ret; zval *fields = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|ss", &fields, &delim, &d_len, &enclo, &e_len) == SUCCESS) { switch(ZEND_NUM_ARGS()) { case 3: if (e_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } enclosure = enclo[0]; /* no break */ case 2: if (d_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } delimiter = delim[0]; /* no break */ case 1: case 0: break; } ret = php_fputcsv(intern->u.file.stream, fields, delimiter, enclosure, escape TSRMLS_CC); RETURN_LONG(ret); } } /* }}} */ /* {{{ proto void SplFileObject::setCsvControl([string delimiter = ',' [, string enclosure = '"' [, string escape = '\\']]]) Set the delimiter and enclosure character used in fgetcsv */ SPL_METHOD(SplFileObject, setCsvControl) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter = ',', enclosure = '"', escape='\\'; char *delim = NULL, *enclo = NULL, *esc = NULL; int d_len = 0, e_len = 0, esc_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sss", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) { switch(ZEND_NUM_ARGS()) { case 3: if (esc_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character"); RETURN_FALSE; } escape = esc[0]; /* no break */ case 2: if (e_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } enclosure = enclo[0]; /* no break */ case 1: if (d_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } delimiter = delim[0]; /* no break */ case 0: break; } intern->u.file.delimiter = delimiter; intern->u.file.enclosure = enclosure; intern->u.file.escape = escape; } } /* }}} */ /* {{{ proto array SplFileObject::getCsvControl() Get the delimiter and enclosure character used in fgetcsv */ SPL_METHOD(SplFileObject, getCsvControl) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter[2], enclosure[2]; array_init(return_value); delimiter[0] = intern->u.file.delimiter; delimiter[1] = '\0'; enclosure[0] = intern->u.file.enclosure; enclosure[1] = '\0'; add_next_index_string(return_value, delimiter, 1); add_next_index_string(return_value, enclosure, 1); } /* }}} */ /* {{{ proto bool SplFileObject::flock(int operation [, int &wouldblock]) Portable file locking */ FileFunction(flock) /* }}} */ /* {{{ proto bool SplFileObject::fflush() Flush the file */ SPL_METHOD(SplFileObject, fflush) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); RETURN_BOOL(!php_stream_flush(intern->u.file.stream)); } /* }}} */ /* {{{ proto int SplFileObject::ftell() Return current file position */ SPL_METHOD(SplFileObject, ftell) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long ret = php_stream_tell(intern->u.file.stream); if (ret == -1) { RETURN_FALSE; } else { RETURN_LONG(ret); } } /* }}} */ /* {{{ proto int SplFileObject::fseek(int pos [, int whence = SEEK_SET]) Return current file position */ SPL_METHOD(SplFileObject, fseek) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long pos, whence = SEEK_SET; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|l", &pos, &whence) == FAILURE) { return; } spl_filesystem_file_free_line(intern TSRMLS_CC); RETURN_LONG(php_stream_seek(intern->u.file.stream, pos, whence)); } /* }}} */ /* {{{ proto int SplFileObject::fgetc() Get a character form the file */ SPL_METHOD(SplFileObject, fgetc) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char buf[2]; int result; spl_filesystem_file_free_line(intern TSRMLS_CC); result = php_stream_getc(intern->u.file.stream); if (result == EOF) { RETVAL_FALSE; } else { if (result == '\n') { intern->u.file.current_line_num++; } buf[0] = result; buf[1] = '\0'; RETURN_STRINGL(buf, 1, 1); } } /* }}} */ /* {{{ proto string SplFileObject::fgetss([string allowable_tags]) Get a line from file pointer and strip HTML tags */ SPL_METHOD(SplFileObject, fgetss) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zval *arg2 = NULL; MAKE_STD_ZVAL(arg2); if (intern->u.file.max_line_len > 0) { ZVAL_LONG(arg2, intern->u.file.max_line_len); } else { ZVAL_LONG(arg2, 1024); } spl_filesystem_file_free_line(intern TSRMLS_CC); intern->u.file.current_line_num++; FileFunctionCall(fgetss, ZEND_NUM_ARGS(), arg2); zval_ptr_dtor(&arg2); } /* }}} */ /* {{{ proto int SplFileObject::fpassthru() Output all remaining data from a file pointer */ SPL_METHOD(SplFileObject, fpassthru) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); RETURN_LONG(php_stream_passthru(intern->u.file.stream)); } /* }}} */ /* {{{ proto bool SplFileObject::fscanf(string format [, string ...]) Implements a mostly ANSI compatible fscanf() */ SPL_METHOD(SplFileObject, fscanf) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_filesystem_file_free_line(intern TSRMLS_CC); intern->u.file.current_line_num++; FileFunctionCall(fscanf, ZEND_NUM_ARGS(), NULL); } /* }}} */ /* {{{ proto mixed SplFileObject::fwrite(string str [, int length]) Binary-safe file write */ SPL_METHOD(SplFileObject, fwrite) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *str; int str_len; int ret; long length = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &str, &str_len, &length) == FAILURE) { return; } if (ZEND_NUM_ARGS() > 1) { str_len = MAX(0, MIN(length, str_len)); } if (!str_len) { RETURN_LONG(0); } if (PG(magic_quotes_runtime)) { str = estrndup(str, str_len); php_stripslashes(str, &str_len TSRMLS_CC); ret = php_stream_write(intern->u.file.stream, str, str_len); efree(str); RETURN_LONG(ret); } RETURN_LONG(php_stream_write(intern->u.file.stream, str, str_len)); } /* }}} */ /* {{{ proto bool SplFileObject::fstat() Stat() on a filehandle */ FileFunction(fstat) /* }}} */ /* {{{ proto bool SplFileObject::ftruncate(int size) Truncate file to 'size' length */ SPL_METHOD(SplFileObject, ftruncate) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long size; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &size) == FAILURE) { return; } if (!php_stream_truncate_supported(intern->u.file.stream)) { zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Can't truncate file %s", intern->file_name); RETURN_FALSE; } RETURN_BOOL(0 == php_stream_truncate_set_size(intern->u.file.stream, size)); } /* }}} */ /* {{{ proto void SplFileObject::seek(int line_pos) Seek to specified line */ SPL_METHOD(SplFileObject, seek) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long line_pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &line_pos) == FAILURE) { return; } if (line_pos < 0) { zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Can't seek file %s to negative line %ld", intern->file_name, line_pos); RETURN_FALSE; } spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC); while(intern->u.file.current_line_num < line_pos) { if (spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC) == FAILURE) { break; } } } /* }}} */ /* {{{ Function/Class/Method definitions */ ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object___construct, 0, 0, 1) ZEND_ARG_INFO(0, file_name) ZEND_ARG_INFO(0, open_mode) ZEND_ARG_INFO(0, use_include_path) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_file_object_setFlags, 0) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_file_object_setMaxLineLen, 0) ZEND_ARG_INFO(0, max_len) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fgetcsv, 0, 0, 0) ZEND_ARG_INFO(0, delimiter) ZEND_ARG_INFO(0, enclosure) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fputcsv, 0, 0, 1) ZEND_ARG_INFO(0, fields) ZEND_ARG_INFO(0, delimiter) ZEND_ARG_INFO(0, enclosure) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_flock, 0, 0, 1) ZEND_ARG_INFO(0, operation) ZEND_ARG_INFO(1, wouldblock) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fseek, 0, 0, 1) ZEND_ARG_INFO(0, pos) ZEND_ARG_INFO(0, whence) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fgetss, 0, 0, 0) ZEND_ARG_INFO(0, allowable_tags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fscanf, 1, 0, 1) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fwrite, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, length) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_ftruncate, 0, 0, 1) ZEND_ARG_INFO(0, size) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_seek, 0, 0, 1) ZEND_ARG_INFO(0, line_pos) ZEND_END_ARG_INFO() static const zend_function_entry spl_SplFileObject_functions[] = { SPL_ME(SplFileObject, __construct, arginfo_file_object___construct, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, rewind, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, eof, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, valid, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fgets, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fgetcsv, arginfo_file_object_fgetcsv, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fputcsv, arginfo_file_object_fputcsv, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, setCsvControl, arginfo_file_object_fgetcsv, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, getCsvControl, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, flock, arginfo_file_object_flock, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fflush, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, ftell, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fseek, arginfo_file_object_fseek, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fgetc, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fpassthru, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fgetss, arginfo_file_object_fgetss, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fscanf, arginfo_file_object_fscanf, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fwrite, arginfo_file_object_fwrite, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fstat, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, ftruncate, arginfo_file_object_ftruncate, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, current, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, key, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, next, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, setFlags, arginfo_file_object_setFlags, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, getFlags, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, setMaxLineLen, arginfo_file_object_setMaxLineLen, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, getMaxLineLen, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, hasChildren, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, getChildren, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, seek, arginfo_file_object_seek, ZEND_ACC_PUBLIC) /* mappings */ SPL_MA(SplFileObject, getCurrentLine, SplFileObject, fgets, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_MA(SplFileObject, __toString, SplFileObject, current, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; ZEND_BEGIN_ARG_INFO_EX(arginfo_temp_file_object___construct, 0, 0, 0) ZEND_ARG_INFO(0, max_memory) ZEND_END_ARG_INFO() static const zend_function_entry spl_SplTempFileObject_functions[] = { SPL_ME(SplTempFileObject, __construct, arginfo_temp_file_object___construct, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; /* }}} */ /* {{{ PHP_MINIT_FUNCTION(spl_directory) */ PHP_MINIT_FUNCTION(spl_directory) { REGISTER_SPL_STD_CLASS_EX(SplFileInfo, spl_filesystem_object_new, spl_SplFileInfo_functions); memcpy(&spl_filesystem_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); spl_filesystem_object_handlers.clone_obj = spl_filesystem_object_clone; spl_filesystem_object_handlers.cast_object = spl_filesystem_object_cast; spl_filesystem_object_handlers.get_debug_info = spl_filesystem_object_get_debug_info; spl_ce_SplFileInfo->serialize = zend_class_serialize_deny; spl_ce_SplFileInfo->unserialize = zend_class_unserialize_deny; REGISTER_SPL_SUB_CLASS_EX(DirectoryIterator, SplFileInfo, spl_filesystem_object_new, spl_DirectoryIterator_functions); zend_class_implements(spl_ce_DirectoryIterator TSRMLS_CC, 1, zend_ce_iterator); REGISTER_SPL_IMPLEMENTS(DirectoryIterator, SeekableIterator); spl_ce_DirectoryIterator->get_iterator = spl_filesystem_dir_get_iterator; REGISTER_SPL_SUB_CLASS_EX(FilesystemIterator, DirectoryIterator, spl_filesystem_object_new, spl_FilesystemIterator_functions); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_MODE_MASK", SPL_FILE_DIR_CURRENT_MODE_MASK); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_PATHNAME", SPL_FILE_DIR_CURRENT_AS_PATHNAME); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_FILEINFO", SPL_FILE_DIR_CURRENT_AS_FILEINFO); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_SELF", SPL_FILE_DIR_CURRENT_AS_SELF); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_MODE_MASK", SPL_FILE_DIR_KEY_MODE_MASK); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_AS_PATHNAME", SPL_FILE_DIR_KEY_AS_PATHNAME); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "FOLLOW_SYMLINKS", SPL_FILE_DIR_FOLLOW_SYMLINKS); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_AS_FILENAME", SPL_FILE_DIR_KEY_AS_FILENAME); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "NEW_CURRENT_AND_KEY", SPL_FILE_DIR_KEY_AS_FILENAME|SPL_FILE_DIR_CURRENT_AS_FILEINFO); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "SKIP_DOTS", SPL_FILE_DIR_SKIPDOTS); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "UNIX_PATHS", SPL_FILE_DIR_UNIXPATHS); spl_ce_FilesystemIterator->get_iterator = spl_filesystem_tree_get_iterator; REGISTER_SPL_SUB_CLASS_EX(RecursiveDirectoryIterator, FilesystemIterator, spl_filesystem_object_new, spl_RecursiveDirectoryIterator_functions); REGISTER_SPL_IMPLEMENTS(RecursiveDirectoryIterator, RecursiveIterator); #ifdef HAVE_GLOB REGISTER_SPL_SUB_CLASS_EX(GlobIterator, FilesystemIterator, spl_filesystem_object_new, spl_GlobIterator_functions); REGISTER_SPL_IMPLEMENTS(GlobIterator, Countable); #endif REGISTER_SPL_SUB_CLASS_EX(SplFileObject, SplFileInfo, spl_filesystem_object_new, spl_SplFileObject_functions); REGISTER_SPL_IMPLEMENTS(SplFileObject, RecursiveIterator); REGISTER_SPL_IMPLEMENTS(SplFileObject, SeekableIterator); REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "DROP_NEW_LINE", SPL_FILE_OBJECT_DROP_NEW_LINE); REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "READ_AHEAD", SPL_FILE_OBJECT_READ_AHEAD); REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "SKIP_EMPTY", SPL_FILE_OBJECT_SKIP_EMPTY); REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "READ_CSV", SPL_FILE_OBJECT_READ_CSV); REGISTER_SPL_SUB_CLASS_EX(SplTempFileObject, SplFileObject, spl_filesystem_object_new, spl_SplTempFileObject_functions); return SUCCESS; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-03-19-5d0c948296-8deb11c0c3.c
manybugs_data_11
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <zend_language_parser.h> #include "zend.h" #include "zend_compile.h" #include "zend_constants.h" #include "zend_llist.h" #include "zend_API.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "zend_multibyte.h" #include "zend_language_scanner.h" #define CONSTANT_EX(op_array, op) \ (op_array)->literals[op].constant #define CONSTANT(op) \ CONSTANT_EX(CG(active_op_array), op) #define SET_NODE(target, src) do { \ target ## _type = (src)->op_type; \ if ((src)->op_type == IS_CONST) { \ target.constant = zend_add_literal(CG(active_op_array), &(src)->u.constant TSRMLS_CC); \ } else { \ target = (src)->u.op; \ } \ } while (0) #define GET_NODE(target, src) do { \ (target)->op_type = src ## _type; \ if ((target)->op_type == IS_CONST) { \ (target)->u.constant = CONSTANT(src.constant); \ } else { \ (target)->u.op = src; \ (target)->EA = 0; \ } \ } while (0) #define COPY_NODE(target, src) do { \ target ## _type = src ## _type; \ target = src; \ } while (0) #define CALCULATE_LITERAL_HASH(num) do { \ if (IS_INTERNED(Z_STRVAL(CONSTANT(num)))) { \ Z_HASH_P(&CONSTANT(num)) = INTERNED_HASH(Z_STRVAL(CONSTANT(num))); \ } else { \ Z_HASH_P(&CONSTANT(num)) = zend_hash_func(Z_STRVAL(CONSTANT(num)), Z_STRLEN(CONSTANT(num))+1); \ } \ } while (0) #define GET_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot++; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ } \ } while (0) #define POLYMORPHIC_CACHE_SLOT_SIZE 2 #define GET_POLYMORPHIC_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot; \ CG(active_op_array)->last_cache_slot += POLYMORPHIC_CACHE_SLOT_SIZE; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 2] = NULL; \ } \ } while (0) #define FREE_POLYMORPHIC_CACHE_SLOT(literal) do { \ if (CG(active_op_array)->literals[literal].cache_slot == \ CG(active_op_array)->last_cache_slot - POLYMORPHIC_CACHE_SLOT_SIZE) { \ CG(active_op_array)->literals[literal].cache_slot = -1; \ CG(active_op_array)->last_cache_slot -= POLYMORPHIC_CACHE_SLOT_SIZE; \ } \ } while (0) ZEND_API zend_op_array *(*zend_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); ZEND_API zend_op_array *(*zend_compile_string)(zval *source_string, char *filename TSRMLS_DC); #ifndef ZTS ZEND_API zend_compiler_globals compiler_globals; ZEND_API zend_executor_globals executor_globals; #endif static void zend_duplicate_property_info(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = estrndup(property_info->name, property_info->name_length); } if (property_info->doc_comment) { property_info->doc_comment = estrndup(property_info->doc_comment, property_info->doc_comment_len); } } /* }}} */ static void zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = zend_strndup(property_info->name, property_info->name_length); } } /* }}} */ static void zend_destroy_property_info(zend_property_info *property_info) /* {{{ */ { str_efree(property_info->name); if (property_info->doc_comment) { efree((char*)property_info->doc_comment); } } /* }}} */ static void zend_destroy_property_info_internal(zend_property_info *property_info) /* {{{ */ { str_free((char*)property_info->name); } /* }}} */ static void build_runtime_defined_function_key(zval *result, const char *name, int name_length TSRMLS_DC) /* {{{ */ { char char_pos_buf[32]; uint char_pos_len; const char *filename; char_pos_len = zend_sprintf(char_pos_buf, "%p", LANG_SCNG(yy_text)); if (CG(active_op_array)->filename) { filename = CG(active_op_array)->filename; } else { filename = "-"; } /* NULL, name length, filename length, last accepting char position length */ result->value.str.len = 1+name_length+strlen(filename)+char_pos_len; /* must be binary safe */ result->value.str.val = (char *) safe_emalloc(result->value.str.len, 1, 1); result->value.str.val[0] = '\0'; sprintf(result->value.str.val+1, "%s%s%s", name, filename, char_pos_buf); result->type = IS_STRING; Z_SET_REFCOUNT_P(result, 1); } /* }}} */ static void init_compiler_declarables(TSRMLS_D) /* {{{ */ { Z_TYPE(CG(declarables).ticks) = IS_LONG; Z_LVAL(CG(declarables).ticks) = 0; } /* }}} */ void zend_init_compiler_context(TSRMLS_D) /* {{{ */ { CG(context).opcodes_size = (CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) ? INITIAL_INTERACTIVE_OP_ARRAY_SIZE : INITIAL_OP_ARRAY_SIZE; CG(context).vars_size = 0; CG(context).literals_size = 0; CG(context).current_brk_cont = -1; CG(context).backpatch_count = 0; CG(context).labels = NULL; } /* }}} */ void zend_init_compiler_data_structures(TSRMLS_D) /* {{{ */ { zend_stack_init(&CG(bp_stack)); zend_stack_init(&CG(function_call_stack)); zend_stack_init(&CG(switch_cond_stack)); zend_stack_init(&CG(foreach_copy_stack)); zend_stack_init(&CG(object_stack)); zend_stack_init(&CG(declare_stack)); CG(active_class_entry) = NULL; zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_stack_init(&CG(list_stack)); CG(in_compilation) = 0; CG(start_lineno) = 0; CG(current_namespace) = NULL; CG(in_namespace) = 0; CG(has_bracketed_namespaces) = 0; CG(current_import) = NULL; init_compiler_declarables(TSRMLS_C); zend_stack_init(&CG(context_stack)); CG(encoding_declared) = 0; } /* }}} */ ZEND_API void file_handle_dtor(zend_file_handle *fh) /* {{{ */ { TSRMLS_FETCH(); zend_file_handle_dtor(fh TSRMLS_CC); } /* }}} */ void init_compiler(TSRMLS_D) /* {{{ */ { CG(active_op_array) = NULL; zend_init_compiler_data_structures(TSRMLS_C); zend_init_rsrc_list(TSRMLS_C); zend_hash_init(&CG(filenames_table), 5, NULL, (dtor_func_t) free_estring, 0); zend_llist_init(&CG(open_files), sizeof(zend_file_handle), (void (*)(void *)) file_handle_dtor, 0); CG(unclean_shutdown) = 0; } /* }}} */ void shutdown_compiler(TSRMLS_D) /* {{{ */ { zend_stack_destroy(&CG(bp_stack)); zend_stack_destroy(&CG(function_call_stack)); zend_stack_destroy(&CG(switch_cond_stack)); zend_stack_destroy(&CG(foreach_copy_stack)); zend_stack_destroy(&CG(object_stack)); zend_stack_destroy(&CG(declare_stack)); zend_stack_destroy(&CG(list_stack)); zend_hash_destroy(&CG(filenames_table)); zend_llist_destroy(&CG(open_files)); zend_stack_destroy(&CG(context_stack)); } /* }}} */ ZEND_API char *zend_set_compiled_filename(const char *new_compiled_filename TSRMLS_DC) /* {{{ */ { char **pp, *p; int length = strlen(new_compiled_filename); if (zend_hash_find(&CG(filenames_table), new_compiled_filename, length+1, (void **) &pp) == SUCCESS) { CG(compiled_filename) = *pp; return *pp; } p = estrndup(new_compiled_filename, length); zend_hash_update(&CG(filenames_table), new_compiled_filename, length+1, &p, sizeof(char *), (void **) &pp); CG(compiled_filename) = p; return p; } /* }}} */ ZEND_API void zend_restore_compiled_filename(char *original_compiled_filename TSRMLS_DC) /* {{{ */ { CG(compiled_filename) = original_compiled_filename; } /* }}} */ ZEND_API char *zend_get_compiled_filename(TSRMLS_D) /* {{{ */ { return CG(compiled_filename); } /* }}} */ ZEND_API int zend_get_compiled_lineno(TSRMLS_D) /* {{{ */ { return CG(zend_lineno); } /* }}} */ ZEND_API zend_bool zend_is_compiling(TSRMLS_D) /* {{{ */ { return CG(in_compilation); } /* }}} */ static zend_uint get_temporary_variable(zend_op_array *op_array) /* {{{ */ { return (op_array->T)++ * ZEND_MM_ALIGNED_SIZE(sizeof(temp_variable)); } /* }}} */ static int lookup_cv(zend_op_array *op_array, char* name, int name_len, ulong hash TSRMLS_DC) /* {{{ */ { int i = 0; ulong hash_value = hash ? hash : zend_inline_hash_func(name, name_len+1); while (i < op_array->last_var) { if (op_array->vars[i].name == name || (op_array->vars[i].hash_value == hash_value && op_array->vars[i].name_len == name_len && memcmp(op_array->vars[i].name, name, name_len) == 0)) { str_efree(name); return i; } i++; } i = op_array->last_var; op_array->last_var++; if (op_array->last_var > CG(context).vars_size) { CG(context).vars_size += 16; /* FIXME */ op_array->vars = erealloc(op_array->vars, CG(context).vars_size * sizeof(zend_compiled_variable)); } op_array->vars[i].name = zend_new_interned_string(name, name_len + 1, 1 TSRMLS_CC); op_array->vars[i].name_len = name_len; op_array->vars[i].hash_value = hash_value; return i; } /* }}} */ void zend_del_literal(zend_op_array *op_array, int n) /* {{{ */ { zval_dtor(&CONSTANT_EX(op_array, n)); if (n + 1 == op_array->last_literal) { op_array->last_literal--; } else { Z_TYPE(CONSTANT_EX(op_array, n)) = IS_NULL; } } /* }}} */ /* Common part of zend_add_literal and zend_append_individual_literal */ static inline void zend_insert_literal(zend_op_array *op_array, const zval *zv, int literal_position TSRMLS_DC) /* {{{ */ { if (Z_TYPE_P(zv) == IS_STRING || Z_TYPE_P(zv) == IS_CONSTANT) { zval *z = (zval*)zv; Z_STRVAL_P(z) = (char*)zend_new_interned_string(Z_STRVAL_P(zv), Z_STRLEN_P(zv) + 1, 1 TSRMLS_CC); } CONSTANT_EX(op_array, literal_position) = *zv; Z_SET_REFCOUNT(CONSTANT_EX(op_array, literal_position), 2); Z_SET_ISREF(CONSTANT_EX(op_array, literal_position)); op_array->literals[literal_position].hash_value = 0; op_array->literals[literal_position].cache_slot = -1; } /* }}} */ /* Is used while compiling a function, using the context to keep track of an approximate size to avoid to relocate to often. Literals are truncated to actual size in the second compiler pass (pass_two()). */ int zend_add_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; if (i >= CG(context).literals_size) { while (i >= CG(context).literals_size) { CG(context).literals_size += 16; /* FIXME */ } op_array->literals = (zend_literal*)erealloc(op_array->literals, CG(context).literals_size * sizeof(zend_literal)); } zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ /* Is used after normal compilation to append an additional literal. Allocation is done precisely here. */ int zend_append_individual_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; op_array->literals = (zend_literal*)erealloc(op_array->literals, (i + 1) * sizeof(zend_literal)); zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ int zend_add_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_ns_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; const char *ns_separator; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); ns_separator = (const char*)zend_memrchr(Z_STRVAL_P(zv), '\\', Z_STRLEN_P(zv)) + 1; lc_len = Z_STRLEN_P(zv) - (ns_separator - Z_STRVAL_P(zv)); lc_name = zend_str_tolower_dup(ns_separator, lc_len); ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_class_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } if (Z_STRVAL_P(zv)[0] == '\\') { lc_len = Z_STRLEN_P(zv) - 1; lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv) + 1, lc_len); } else { lc_len = Z_STRLEN_P(zv); lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), lc_len); } ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); GET_CACHE_SLOT(ret); return ret; } /* }}} */ int zend_add_const_name_literal(zend_op_array *op_array, const zval *zv, int unqualified TSRMLS_DC) /* {{{ */ { int ret, tmp_literal; char *name, *tmp_name; const char *ns_separator; int name_len, ns_len; zval c; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } /* skip leading '\\' */ if (Z_STRVAL_P(zv)[0] == '\\') { name_len = Z_STRLEN_P(zv) - 1; name = Z_STRVAL_P(zv) + 1; } else { name_len = Z_STRLEN_P(zv); name = Z_STRVAL_P(zv); } ns_separator = zend_memrchr(name, '\\', name_len); if (ns_separator) { ns_len = ns_separator - name; } else { ns_len = 0; } if (ns_len) { /* lowercased namespace name & original constant name */ tmp_name = estrndup(name, name_len); zend_str_tolower(tmp_name, ns_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased namespace name & lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); } if (ns_len) { if (!unqualified) { return ret; } ns_len++; name += ns_len; name_len -= ns_len; } /* original constant name */ tmp_name = estrndup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); return ret; } /* }}} */ #define LITERAL_STRINGL(op, str, len, copy) do { \ zval _c; \ ZVAL_STRINGL(&_c, str, len, copy); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG(op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG_EX(op_array, op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(op_array, &_c TSRMLS_CC); \ } while (0) #define LITERAL_NULL(op) do { \ zval _c; \ INIT_ZVAL( _c); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) static inline zend_bool zend_is_function_or_method_call(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; return ((type & ZEND_PARSED_METHOD_CALL) || (type == ZEND_PARSED_FUNCTION_CALL)); } /* }}} */ void zend_do_binary_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_unary_op(zend_uchar op, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); GET_NODE(result, opline->result); SET_UNUSED(opline->op2); } /* }}} */ #define MAKE_NOP(opline) { opline->opcode = ZEND_NOP; memset(&opline->result,0,sizeof(opline->result)); memset(&opline->op1,0,sizeof(opline->op1)); memset(&opline->op2,0,sizeof(opline->op2)); opline->result_type=opline->op1_type=opline->op2_type=IS_UNUSED; } static void zend_do_op_data(zend_op *data_op, const znode *value TSRMLS_DC) /* {{{ */ { data_op->opcode = ZEND_OP_DATA; SET_NODE(data_op->op1, value); SET_UNUSED(data_op->op2); } /* }}} */ void zend_do_binary_assign_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; switch (last_op->opcode) { case ZEND_FETCH_OBJ_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, op2 TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; case ZEND_FETCH_DIM_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_DIM; zend_do_op_data(opline, op2 TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result,last_op->result); return; default: break; } } opline->opcode = op; SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void fetch_simple_variable_ex(znode *result, znode *varname, int bp, zend_uchar op TSRMLS_DC) /* {{{ */ { zend_op opline; zend_op *opline_ptr; zend_llist *fetch_list_ptr; if (varname->op_type == IS_CONST) { ulong hash = 0; if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } else if (IS_INTERNED(Z_STRVAL(varname->u.constant))) { hash = INTERNED_HASH(Z_STRVAL(varname->u.constant)); } if (!zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC) && !(varname->u.constant.value.str.len == (sizeof("this")-1) && !memcmp(varname->u.constant.value.str.val, "this", sizeof("this"))) && (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE)) { result->op_type = IS_CV; result->u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC); varname->u.constant.value.str.val = (char*)CG(active_op_array)->vars[result->u.op.var].name; result->EA = 0; return; } } if (bp) { opline_ptr = &opline; init_op(opline_ptr TSRMLS_CC); } else { opline_ptr = get_next_op(CG(active_op_array) TSRMLS_CC); } opline_ptr->opcode = op; opline_ptr->result_type = IS_VAR; opline_ptr->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline_ptr->op1, varname); GET_NODE(result, opline_ptr->result); SET_UNUSED(opline_ptr->op2); opline_ptr->extended_value = ZEND_FETCH_LOCAL; if (varname->op_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline_ptr->op1.constant); if (zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC)) { opline_ptr->extended_value = ZEND_FETCH_GLOBAL; } } if (bp) { zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); zend_llist_add_element(fetch_list_ptr, opline_ptr); } } /* }}} */ void fetch_simple_variable(znode *result, znode *varname, int bp TSRMLS_DC) /* {{{ */ { /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ fetch_simple_variable_ex(result, varname, bp, ZEND_FETCH_W TSRMLS_CC); } /* }}} */ void zend_do_fetch_static_member(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { znode class_node; zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline_ptr; zend_op opline; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); } zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (result->op_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[result->u.op.var].name), CG(active_op_array)->vars[result->u.op.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } GET_NODE(result,opline.result); opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; opline_ptr = &opline; zend_llist_add_element(fetch_list_ptr, &opline); } else { le = fetch_list_ptr->head; opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode != ZEND_FETCH_W && opline_ptr->op1_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[opline_ptr->op1.var].name), CG(active_op_array)->vars[opline_ptr->op1.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; COPY_NODE(opline_ptr->op1, opline.result); zend_llist_prepend_element(fetch_list_ptr, &opline); } else { if (opline_ptr->op1_type == IS_CONST) { GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op1.constant); } if (class_node.op_type == IS_CONST) { opline_ptr->op2_type = IS_CONST; opline_ptr->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline_ptr->op2, &class_node); } opline_ptr->extended_value |= ZEND_FETCH_STATIC_MEMBER; } } } /* }}} */ void fetch_array_begin(znode *result, znode *varname, znode *first_dim TSRMLS_DC) /* {{{ */ { fetch_simple_variable(result, varname, 1 TSRMLS_CC); fetch_array_dim(result, result, first_dim TSRMLS_CC); } /* }}} */ void fetch_array_dim(znode *result, const znode *parent, const znode *dim TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (zend_is_function_or_method_call(parent)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, parent); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_DIM_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, parent); SET_NODE(opline.op2, dim); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline.op2.constant)), Z_STRLEN(CONSTANT(opline.op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline.op2.constant)); ZVAL_LONG(&CONSTANT(opline.op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline.op2.constant); } } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void fetch_string_offset(znode *result, const znode *parent, const znode *offset TSRMLS_DC) /* {{{ */ { fetch_array_dim(result, parent, offset TSRMLS_CC); } /* }}} */ void zend_do_print(znode *result, const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->opcode = ZEND_PRINT; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_echo(const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ECHO; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_abstract_method(const znode *function_name, znode *modifiers, const znode *body TSRMLS_DC) /* {{{ */ { char *method_type; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { Z_LVAL(modifiers->u.constant) |= ZEND_ACC_ABSTRACT; method_type = "Interface"; } else { method_type = "Abstract"; } if (modifiers->u.constant.value.lval & ZEND_ACC_ABSTRACT) { if(modifiers->u.constant.value.lval & ZEND_ACC_PRIVATE) { zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot be declared private", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } if (Z_LVAL(body->u.constant) == ZEND_ACC_ABSTRACT) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_RAISE_ABSTRACT_ERROR; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } else { /* we had code in the function body */ zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot contain body", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } else { if (body->u.constant.value.lval == ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Non-abstract method %s::%s() must contain body", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } } /* }}} */ static zend_bool opline_is_fetch_this(const zend_op *opline TSRMLS_DC) /* {{{ */ { if ((opline->opcode == ZEND_FETCH_W) && (opline->op1_type == IS_CONST) && (Z_TYPE(CONSTANT(opline->op1.constant)) == IS_STRING) && (Z_HASH_P(&CONSTANT(opline->op1.constant)) == THIS_HASHVAL) && (Z_STRLEN(CONSTANT(opline->op1.constant)) == (sizeof("this")-1)) && !memcmp(Z_STRVAL(CONSTANT(opline->op1.constant)), "this", sizeof("this"))) { return 1; } else { return 0; } } /* }}} */ void zend_do_assign(znode *result, znode *variable, znode *value TSRMLS_DC) /* {{{ */ { int last_op_number; zend_op *opline; if (value->op_type == IS_CV) { zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (fetch_list_ptr && fetch_list_ptr->head) { opline = (zend_op *)fetch_list_ptr->head->data; if (opline->opcode == ZEND_FETCH_DIM_W && opline->op1_type == IS_CV && opline->op1.var == value->u.op.var) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_R; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->op1_type = IS_CONST; LITERAL_STRINGL(opline->op1, CG(active_op_array)->vars[value->u.op.var].name, CG(active_op_array)->vars[value->u.op.var].name_len, 1); CALCULATE_LITERAL_HASH(opline->op1.constant); SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_LOCAL; GET_NODE(value, opline->result); } } } zend_do_end_variable_parse(variable, BP_VAR_W, 0 TSRMLS_CC); last_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (variable->op_type == IS_CV) { if (variable->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (variable->op_type == IS_VAR) { int n = 0; while (last_op_number - n > 0) { zend_op *last_op; last_op = &CG(active_op_array)->opcodes[last_op_number-n-1]; if (last_op->result_type == IS_VAR && last_op->result.var == variable->u.op.var) { if (last_op->opcode == ZEND_FETCH_OBJ_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, value TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (last_op->opcode == ZEND_FETCH_DIM_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ /* TBFixed: this can realloc opcodes, leaving last_op pointing wrong */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_DIM; zend_do_op_data(opline, value TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (opline_is_fetch_this(last_op TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } else { break; } } n++; } } opline->opcode = ZEND_ASSIGN; SET_NODE(opline->op1, variable); SET_NODE(opline->op2, value); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_assign_ref(znode *result, const znode *lvar, const znode *rvar TSRMLS_DC) /* {{{ */ { zend_op *opline; if (lvar->op_type == IS_CV) { if (lvar->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (lvar->op_type == IS_VAR) { int last_op_number = get_next_op_number(CG(active_op_array)); if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline_is_fetch_this(opline TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ASSIGN_REF; if (zend_is_function_or_method_call(rvar)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } else if (rvar->EA & ZEND_PARSED_NEW) { opline->extended_value = ZEND_RETURNS_NEW; } else { opline->extended_value = 0; } if (result) { opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } else { opline->result_type = IS_UNUSED | EXT_TYPE_UNUSED; } SET_NODE(opline->op1, lvar); SET_NODE(opline->op2, rvar); } /* }}} */ static inline void do_begin_loop(TSRMLS_D) /* {{{ */ { zend_brk_cont_element *brk_cont_element; int parent; parent = CG(context).current_brk_cont; CG(context).current_brk_cont = CG(active_op_array)->last_brk_cont; brk_cont_element = get_next_brk_cont_element(CG(active_op_array)); brk_cont_element->start = get_next_op_number(CG(active_op_array)); brk_cont_element->parent = parent; } /* }}} */ static inline void do_end_loop(int cont_addr, int has_loop_var TSRMLS_DC) /* {{{ */ { if (!has_loop_var) { /* The start fileld is used to free temporary variables in case of exceptions. * We won't try to free something of we don't have loop variable. */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].start = -1; } CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = cont_addr; CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; } /* }}} */ void zend_do_while_cond(const znode *expr, znode *close_bracket_token TSRMLS_DC) /* {{{ */ { int while_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, expr); close_bracket_token->u.op.opline_num = while_cond_op_number; SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_while_end(const znode *while_token, const znode *close_bracket_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* add unconditional jump */ opline->opcode = ZEND_JMP; opline->op1.opline_num = while_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* update while's conditional jmp */ CG(active_op_array)->opcodes[close_bracket_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); do_end_loop(while_token->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_cond(const znode *expr, znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { int for_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZNZ; SET_NODE(opline->op1, expr); /* the conditional expression */ second_semicolon_token->u.op.opline_num = for_cond_op_number; SET_UNUSED(opline->op2); } /* }}} */ void zend_do_for_before_statement(const znode *cond_start, const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = cond_start->u.op.opline_num; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_end(const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = second_semicolon_token->u.op.opline_num+1; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_end_loop(second_semicolon_token->u.op.opline_num+1, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_pre_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_PRE_INC)?ZEND_PRE_INC_OBJ:ZEND_PRE_DEC_OBJ; last_op->result_type = IS_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_post_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_POST_INC)?ZEND_POST_INC_OBJ:ZEND_POST_DEC_OBJ; last_op->result_type = IS_TMP_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_if_cond(const znode *cond, znode *closing_bracket_token TSRMLS_DC) /* {{{ */ { int if_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); closing_bracket_token->u.op.opline_num = if_cond_op_number; SET_UNUSED(opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_if_after_statement(const znode *closing_bracket_token, unsigned char initialize TSRMLS_DC) /* {{{ */ { int if_end_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; /* save for backpatching */ if (initialize) { zend_llist jmp_list; zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); } zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &if_end_op_number); CG(active_op_array)->opcodes[closing_bracket_token->u.op.opline_num].op2.opline_num = if_end_op_number+1; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_if_end(TSRMLS_D) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_llist *jmp_list_ptr; zend_llist_element *le; zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); for (le=jmp_list_ptr->head; le; le = le->next) { CG(active_op_array)->opcodes[*((int *) le->data)].op1.opline_num = next_op_number; } zend_llist_destroy(jmp_list_ptr); zend_stack_del_top(&CG(bp_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_check_writable_variable(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; if (type & ZEND_PARSED_METHOD_CALL) { zend_error(E_COMPILE_ERROR, "Can't use method return value in write context"); } if (type == ZEND_PARSED_FUNCTION_CALL) { zend_error(E_COMPILE_ERROR, "Can't use function return value in write context"); } } /* }}} */ void zend_do_begin_variable_parse(TSRMLS_D) /* {{{ */ { zend_llist fetch_list; zend_llist_init(&fetch_list, sizeof(zend_op), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &fetch_list, sizeof(zend_llist)); } /* }}} */ void zend_do_end_variable_parse(znode *variable, int type, int arg_offset TSRMLS_DC) /* {{{ */ { zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline = NULL; zend_op *opline_ptr; zend_uint this_var = -1; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); le = fetch_list_ptr->head; /* TODO: $foo->x->y->z = 1 should fetch "x" and "y" for R or RW, not just W */ if (le) { opline_ptr = (zend_op *)le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { /* convert to FETCH_?(this) into IS_CV */ if (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE) { this_var = opline_ptr->result.var; if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), Z_STRVAL(CONSTANT(opline_ptr->op1.constant)), Z_STRLEN(CONSTANT(opline_ptr->op1.constant)), Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC); Z_TYPE(CONSTANT(opline_ptr->op1.constant)) = IS_NULL; } else { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); } le = le->next; if (variable->op_type == IS_VAR && variable->u.op.var == this_var) { variable->op_type = IS_CV; variable->u.op.var = CG(active_op_array)->this_var; } } else if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } while (le) { opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode == ZEND_SEPARATE) { if (type != BP_VAR_R && type != BP_VAR_IS) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); } le = le->next; continue; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); if (opline->op1_type == IS_VAR && opline->op1.var == this_var) { opline->op1_type = IS_CV; opline->op1.var = CG(active_op_array)->this_var; } switch (type) { case BP_VAR_R: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode -= 3; break; case BP_VAR_W: break; case BP_VAR_RW: opline->opcode += 3; break; case BP_VAR_IS: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode += 6; /* 3+3 */ break; case BP_VAR_FUNC_ARG: opline->opcode += 9; /* 3+3+3 */ opline->extended_value |= arg_offset; break; case BP_VAR_UNSET: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for unsetting"); } opline->opcode += 12; /* 3+3+3+3 */ break; } le = le->next; } if (opline && type == BP_VAR_W && arg_offset) { opline->extended_value |= ZEND_FETCH_MAKE_REF; } } zend_llist_destroy(fetch_list_ptr); zend_stack_del_top(&CG(bp_stack)); } /* }}} */ void zend_do_add_string(znode *result, const znode *op1, znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline; if (Z_STRLEN(op2->u.constant) > 1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_STRING; } else if (Z_STRLEN(op2->u.constant) == 1) { int ch = *Z_STRVAL(op2->u.constant); /* Free memory and use ZEND_ADD_CHAR in case of 1 character strings */ efree(Z_STRVAL(op2->u.constant)); ZVAL_LONG(&op2->u.constant, ch); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_CHAR; } else { /* String can be empty after a variable at the end of a heredoc */ efree(Z_STRVAL(op2->u.constant)); return; } if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_add_variable(znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_VAR; if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_free(znode *op1 TSRMLS_DC) /* {{{ */ { if (op1->op_type==IS_TMP_VAR) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else if (op1->op_type==IS_VAR) { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; while (opline->opcode == ZEND_END_SILENCE || opline->opcode == ZEND_EXT_FCALL_END || opline->opcode == ZEND_OP_DATA) { opline--; } if (opline->result_type == IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_FETCH_R || opline->opcode == ZEND_FETCH_DIM_R || opline->opcode == ZEND_FETCH_OBJ_R || opline->opcode == ZEND_QM_ASSIGN_VAR) { /* It's very rare and useless case. It's better to use additional FREE opcode and simplify the FETCH handlers their selves */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else { opline->result_type |= EXT_TYPE_UNUSED; } } else { while (opline>CG(active_op_array)->opcodes) { if (opline->opcode == ZEND_FETCH_DIM_R && opline->op1_type == IS_VAR && opline->op1.var == op1->u.op.var) { /* This should the end of a list() construct * Mark its result as unused */ opline->extended_value = ZEND_FETCH_STANDARD; break; } else if (opline->result_type==IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_NEW) { opline->result_type |= EXT_TYPE_UNUSED; } break; } opline--; } } } else if (op1->op_type == IS_CONST) { zval_dtor(&op1->u.constant); } } /* }}} */ int zend_do_verify_access_types(const znode *current_access_type, const znode *new_modifier) /* {{{ */ { if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_PPP_MASK) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Multiple access type modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_ABSTRACT) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Multiple abstract modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_STATIC) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Multiple static modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_FINAL) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Multiple final modifiers are not allowed"); } if (((Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)) & (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) == (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Cannot use the final modifier on an abstract class member"); } return (Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)); } /* }}} */ void zend_do_begin_function_declaration(znode *function_token, znode *function_name, int is_method, int return_reference, znode *fn_flags_znode TSRMLS_DC) /* {{{ */ { zend_op_array op_array; char *name = function_name->u.constant.value.str.val; int name_len = function_name->u.constant.value.str.len; int function_begin_line = function_token->u.op.opline_num; zend_uint fn_flags; const char *lcname; zend_bool orig_interactive; ALLOCA_FLAG(use_heap) if (is_method) { if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((Z_LVAL(fn_flags_znode->u.constant) & ~(ZEND_ACC_STATIC|ZEND_ACC_PUBLIC))) { zend_error(E_COMPILE_ERROR, "Access type for interface method %s::%s() must be omitted", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } Z_LVAL(fn_flags_znode->u.constant) |= ZEND_ACC_ABSTRACT; /* propagates to the rest of the parser */ } fn_flags = Z_LVAL(fn_flags_znode->u.constant); /* must be done *after* the above check */ } else { fn_flags = 0; } if ((fn_flags & ZEND_ACC_STATIC) && (fn_flags & ZEND_ACC_ABSTRACT) && !(CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_STRICT, "Static function %s%s%s() should not be abstract", is_method ? CG(active_class_entry)->name : "", is_method ? "::" : "", Z_STRVAL(function_name->u.constant)); } function_token->u.op_array = CG(active_op_array); orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(&op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; op_array.function_name = name; if (return_reference) { op_array.fn_flags |= ZEND_ACC_RETURN_REFERENCE; } op_array.fn_flags |= fn_flags; op_array.scope = is_method?CG(active_class_entry):NULL; op_array.prototype = NULL; op_array.line_start = zend_get_compiled_lineno(TSRMLS_C); if (is_method) { int result; lcname = zend_new_interned_string(zend_str_tolower_dup(name, name_len), name_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lcname)) { result = zend_hash_quick_add(&CG(active_class_entry)->function_table, lcname, name_len+1, INTERNED_HASH(lcname), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } else { result = zend_hash_add(&CG(active_class_entry)->function_table, lcname, name_len+1, &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } if (result == FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::%s()", CG(active_class_entry)->name, name); } zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); if (fn_flags & ZEND_ACC_ABSTRACT) { CG(active_class_entry)->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (!(fn_flags & ZEND_ACC_PPP_MASK)) { fn_flags |= ZEND_ACC_PUBLIC; } if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } } } else { char *class_lcname; class_lcname = do_alloca(CG(active_class_entry)->name_length + 1, use_heap); zend_str_tolower_copy(class_lcname, CG(active_class_entry)->name, CG(active_class_entry)->name_length); /* Improve after RC: cache the lowercase class name */ if ((CG(active_class_entry)->name_length == name_len) && ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT) && (!memcmp(class_lcname, lcname, name_len))) { if (!CG(active_class_entry)->constructor) { CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } } else if ((name_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)))) { if (CG(active_class_entry)->constructor) { zend_error(E_STRICT, "Redefining already defined constructor for class %s", CG(active_class_entry)->name); } CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1))) { CG(active_class_entry)->destructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1))) { CG(active_class_entry)->clone = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } CG(active_class_entry)->__call = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } CG(active_class_entry)->__callstatic = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } CG(active_class_entry)->__get = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } CG(active_class_entry)->__set = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } CG(active_class_entry)->__unset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } CG(active_class_entry)->__isset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } CG(active_class_entry)->__tostring = (zend_function *) CG(active_op_array); } else if (!(fn_flags & ZEND_ACC_STATIC)) { CG(active_op_array)->fn_flags |= ZEND_ACC_ALLOW_STATIC; } free_alloca(class_lcname, use_heap); } str_efree(lcname); } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zval key; if (CG(current_namespace)) { /* Prefix function name with current namespcae name */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, function_name TSRMLS_CC); op_array.function_name = Z_STRVAL(tmp.u.constant); name_len = Z_STRLEN(tmp.u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), name_len); } else { lcname = zend_str_tolower_dup(name, name_len); } opline->opcode = ZEND_DECLARE_FUNCTION; opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, name_len TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; LITERAL_STRINGL(opline->op2, lcname, name_len, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); opline->extended_value = ZEND_DECLARE_FUNCTION; zend_hash_quick_update(CG(function_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); } if (CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_NOP; opline->lineno = function_begin_line; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } { /* Push a seperator to the switch and foreach stacks */ zend_switch_entry switch_entry; switch_entry.cond.op_type = IS_UNUSED; switch_entry.default_case = 0; switch_entry.control_var = 0; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); { /* Foreach stack separator */ zend_op dummy_opline; dummy_opline.result_type = IS_UNUSED; dummy_opline.op1_type = IS_UNUSED; zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); } } if (CG(doc_comment)) { CG(active_op_array)->doc_comment = CG(doc_comment); CG(active_op_array)->doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_begin_lambda_function_declaration(znode *result, znode *function_token, int return_reference, int is_static TSRMLS_DC) /* {{{ */ { znode function_name; zend_op_array *current_op_array = CG(active_op_array); int current_op_number = get_next_op_number(CG(active_op_array)); zend_op *current_op; function_name.op_type = IS_CONST; ZVAL_STRINGL(&function_name.u.constant, "{closure}", sizeof("{closure}")-1, 1); zend_do_begin_function_declaration(function_token, &function_name, 0, return_reference, NULL TSRMLS_CC); result->op_type = IS_TMP_VAR; result->u.op.var = get_temporary_variable(current_op_array); current_op = &current_op_array->opcodes[current_op_number]; current_op->opcode = ZEND_DECLARE_LAMBDA_FUNCTION; zend_del_literal(current_op_array, current_op->op2.constant); SET_UNUSED(current_op->op2); SET_NODE(current_op->result, result); if (is_static) { CG(active_op_array)->fn_flags |= ZEND_ACC_STATIC; } CG(active_op_array)->fn_flags |= ZEND_ACC_CLOSURE; } /* }}} */ void zend_do_handle_exception(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_HANDLE_EXCEPTION; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_function_declaration(const znode *function_token TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; zend_do_extended_info(TSRMLS_C); zend_do_return(NULL, 0 TSRMLS_CC); pass_two(CG(active_op_array) TSRMLS_CC); zend_release_labels(TSRMLS_C); if (CG(active_class_entry)) { zend_check_magic_method_implementation(CG(active_class_entry), (zend_function*)CG(active_op_array), E_COMPILE_ERROR TSRMLS_CC); } else { /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(CG(active_op_array)->function_name); zend_str_tolower_copy(lcname, CG(active_op_array)->function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME)) && CG(active_op_array)->num_args != 1) { zend_error(E_COMPILE_ERROR, "%s() must take exactly 1 argument", ZEND_AUTOLOAD_FUNC_NAME); } } CG(active_op_array)->line_end = zend_get_compiled_lineno(TSRMLS_C); CG(active_op_array) = function_token->u.op_array; /* Pop the switch and foreach seperators */ zend_stack_del_top(&CG(switch_cond_stack)); zend_stack_del_top(&CG(foreach_copy_stack)); } /* }}} */ void zend_do_receive_arg(zend_uchar op, znode *varname, const znode *offset, const znode *initialization, znode *class_type, zend_uchar pass_by_reference TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_arg_info *cur_arg_info; znode var; if (class_type->op_type == IS_CONST && Z_TYPE(class_type->u.constant) == IS_STRING && Z_STRLEN(class_type->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_type->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } if (zend_is_auto_global_quick(Z_STRVAL(varname->u.constant), Z_STRLEN(varname->u.constant), 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign auto-global variable %s", Z_STRVAL(varname->u.constant)); } else { var.op_type = IS_CV; var.u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(varname->u.constant) = (char*)CG(active_op_array)->vars[var.u.op.var].name; var.EA = 0; if (CG(active_op_array)->vars[var.u.op.var].hash_value == THIS_HASHVAL && Z_STRLEN(varname->u.constant) == sizeof("this")-1 && !memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this")-1)) { if (CG(active_op_array)->scope && (CG(active_op_array)->fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } CG(active_op_array)->this_var = var.u.op.var; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->num_args++; opline->opcode = op; SET_NODE(opline->result, &var); SET_NODE(opline->op1, offset); if (op == ZEND_RECV_INIT) { SET_NODE(opline->op2, initialization); } else { CG(active_op_array)->required_num_args = CG(active_op_array)->num_args; SET_UNUSED(opline->op2); } CG(active_op_array)->arg_info = erealloc(CG(active_op_array)->arg_info, sizeof(zend_arg_info)*(CG(active_op_array)->num_args)); cur_arg_info = &CG(active_op_array)->arg_info[CG(active_op_array)->num_args-1]; cur_arg_info->name = zend_new_interned_string(estrndup(varname->u.constant.value.str.val, varname->u.constant.value.str.len), varname->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->name_len = varname->u.constant.value.str.len; cur_arg_info->type_hint = 0; cur_arg_info->allow_null = 1; cur_arg_info->pass_by_reference = pass_by_reference; cur_arg_info->class_name = NULL; cur_arg_info->class_name_len = 0; if (class_type->op_type != IS_UNUSED) { cur_arg_info->allow_null = 0; if (class_type->u.constant.type != IS_NULL) { if (class_type->u.constant.type == IS_ARRAY) { cur_arg_info->type_hint = IS_ARRAY; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else if (Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Default value for parameters with array type hint can only be an array or NULL"); } } } else if (class_type->u.constant.type == IS_CALLABLE) { cur_arg_info->type_hint = IS_CALLABLE; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with callable type hint can only be NULL"); } } } else { cur_arg_info->type_hint = IS_OBJECT; if (ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_type->u.constant), Z_STRLEN(class_type->u.constant))) { zend_resolve_class_name(class_type, opline->extended_value, 1 TSRMLS_CC); } Z_STRVAL(class_type->u.constant) = (char*)zend_new_interned_string(class_type->u.constant.value.str.val, class_type->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->class_name = class_type->u.constant.value.str.val; cur_arg_info->class_name_len = class_type->u.constant.value.str.len; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with a class type hint can only be NULL"); } } } } } } /* }}} */ int zend_do_begin_function_call(znode *function_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { zend_function *function; char *lcname; char *is_compound = memchr(Z_STRVAL(function_name->u.constant), '\\', Z_STRLEN(function_name->u.constant)); zend_resolve_non_class_name(function_name, check_namespace TSRMLS_CC); if (check_namespace && CG(current_namespace) && !is_compound) { /* We assume we call function from the current namespace if it is not prefixed. */ /* In run-time PHP will check for function with full name and internal function with short name */ zend_do_begin_dynamic_function_call(function_name, 1 TSRMLS_CC); return 1; } lcname = zend_str_tolower_dup(function_name->u.constant.value.str.val, function_name->u.constant.value.str.len); if ((zend_hash_find(CG(function_table), lcname, function_name->u.constant.value.str.len+1, (void **) &function)==FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_FUNCTIONS) && (function->type == ZEND_INTERNAL_FUNCTION))) { zend_do_begin_dynamic_function_call(function_name, 0 TSRMLS_CC); efree(lcname); return 1; /* Dynamic */ } efree(function_name->u.constant.value.str.val); function_name->u.constant.value.str.val = lcname; zend_stack_push(&CG(function_call_stack), (void *) &function, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 0; } /* }}} */ void zend_do_begin_method_call(znode *left_bracket TSRMLS_DC) /* {{{ */ { zend_op *last_op; int last_op_number; unsigned char *ptr = NULL; zend_do_end_variable_parse(left_bracket, BP_VAR_R, 0 TSRMLS_CC); zend_do_begin_variable_parse(TSRMLS_C); last_op_number = get_next_op_number(CG(active_op_array))-1; last_op = &CG(active_op_array)->opcodes[last_op_number]; if ((last_op->op2_type == IS_CONST) && (Z_TYPE(CONSTANT(last_op->op2.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(last_op->op2.constant)) == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !zend_binary_strcasecmp(Z_STRVAL(CONSTANT(last_op->op2.constant)), Z_STRLEN(CONSTANT(last_op->op2.constant)), ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1)) { zend_error(E_COMPILE_ERROR, "Cannot call __clone() method on objects - use 'clone $obj' instead"); } if (last_op->opcode == ZEND_FETCH_OBJ_R) { if (last_op->op2_type == IS_CONST) { zval name; name = CONSTANT(last_op->op2.constant); if (!IS_INTERNED(Z_STRVAL(name))) { Z_STRVAL(name) = estrndup(Z_STRVAL(name), Z_STRLEN(name)); } FREE_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); last_op->op2.constant = zend_add_func_name_literal(CG(active_op_array), &name TSRMLS_CC); GET_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); } last_op->opcode = ZEND_INIT_METHOD_CALL; SET_UNUSED(last_op->result); Z_LVAL(left_bracket->u.constant) = ZEND_INIT_FCALL_BY_NAME; } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (left_bracket->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &left_bracket->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, left_bracket); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_do_clone(znode *result, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CLONE; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_begin_dynamic_function_call(znode *function_name, int ns_call TSRMLS_DC) /* {{{ */ { unsigned char *ptr = NULL; zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (ns_call) { /* In run-time PHP will check for function with full name and internal function with short name */ opline->opcode = ZEND_INIT_NS_FCALL_BY_NAME; SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_ns_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (function_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, function_name); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_resolve_non_class_name(znode *element_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; int len; zval **ns; char *lcname, *compound = memchr(Z_STRVAL(element_name->u.constant), '\\', Z_STRLEN(element_name->u.constant)); if (Z_STRVAL(element_name->u.constant)[0] == '\\') { /* name starts with \ so it is known and unambiguos, nothing to do here but shorten it */ memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+1, Z_STRLEN(element_name->u.constant)); --Z_STRLEN(element_name->u.constant); return; } if(!check_namespace) { return; } if (compound && CG(current_import)) { len = compound - Z_STRVAL(element_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(element_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(element_name->u.constant) -= len; memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+len, Z_STRLEN(element_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, element_name TSRMLS_CC); *element_name = tmp; efree(lcname); return; } efree(lcname); } if (CG(current_namespace)) { tmp = *element_name; Z_STRLEN(tmp.u.constant) = sizeof("\\")-1 + Z_STRLEN(element_name->u.constant) + Z_STRLEN_P(CG(current_namespace)); Z_STRVAL(tmp.u.constant) = (char *) emalloc(Z_STRLEN(tmp.u.constant)+1); memcpy(Z_STRVAL(tmp.u.constant), Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace))]), "\\", sizeof("\\")-1); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace)) + sizeof("\\")-1]), Z_STRVAL(element_name->u.constant), Z_STRLEN(element_name->u.constant)+1); STR_FREE(Z_STRVAL(element_name->u.constant)); *element_name = tmp; } } /* }}} */ void zend_resolve_class_name(znode *class_name, ulong fetch_type, int check_ns_name TSRMLS_DC) /* {{{ */ { char *compound; char *lcname; zval **ns; znode tmp; int len; compound = memchr(Z_STRVAL(class_name->u.constant), '\\', Z_STRLEN(class_name->u.constant)); if (compound) { /* This is a compound class name that contains namespace prefix */ if (Z_STRVAL(class_name->u.constant)[0] == '\\') { /* The STRING name has "\" prefix */ Z_STRLEN(class_name->u.constant) -= 1; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+1, Z_STRLEN(class_name->u.constant)+1); Z_STRVAL(class_name->u.constant) = erealloc( Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1); if (ZEND_FETCH_CLASS_DEFAULT != zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "'\\%s' is an invalid class name", Z_STRVAL(class_name->u.constant)); } } else { if (CG(current_import)) { len = compound - Z_STRVAL(class_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(class_name->u.constant) -= len; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+len, Z_STRLEN(class_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; efree(lcname); return; } efree(lcname); } /* Here name is not prefixed with \ and not imported */ if (CG(current_namespace)) { tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } } } else if (CG(current_import) || CG(current_namespace)) { /* this is a plain name (without \) */ lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns) == SUCCESS) { /* The given name is an import name. Substitute it. */ zval_dtor(&class_name->u.constant); class_name->u.constant = **ns; zval_copy_ctor(&class_name->u.constant); } else if (CG(current_namespace)) { /* plain name, no import - prepend current namespace to it */ tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } efree(lcname); } } /* }}} */ void zend_do_fetch_class(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { long fetch_class_op_number; zend_op *opline; if (class_name->op_type == IS_CONST && Z_TYPE(class_name->u.constant) == IS_STRING && Z_STRLEN(class_name->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_name->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } fetch_class_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CLASS; SET_UNUSED(opline->op1); opline->extended_value = ZEND_FETCH_CLASS_GLOBAL; CG(catch_begin) = fetch_class_op_number; if (class_name->op_type == IS_CONST) { int fetch_type; fetch_type = zend_get_class_fetch_type(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); switch (fetch_type) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: SET_UNUSED(opline->op2); opline->extended_value = fetch_type; zval_dtor(&class_name->u.constant); break; default: zend_resolve_class_name(class_name, opline->extended_value, 0 TSRMLS_CC); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_name->u.constant TSRMLS_CC); break; } } else { SET_NODE(opline->op2, class_name); } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; /* FIXME: Hack so that INIT_FCALL_BY_NAME still knows this is a class */ GET_NODE(result, opline->result); result->EA = opline->extended_value; } /* }}} */ void zend_do_label(znode *label TSRMLS_DC) /* {{{ */ { zend_label dest; if (!CG(context).labels) { ALLOC_HASHTABLE(CG(context).labels); zend_hash_init(CG(context).labels, 4, NULL, NULL, 0); } dest.brk_cont = CG(context).current_brk_cont; dest.opline_num = get_next_op_number(CG(active_op_array)); if (zend_hash_add(CG(context).labels, Z_STRVAL(label->u.constant), Z_STRLEN(label->u.constant) + 1, (void**)&dest, sizeof(zend_label), NULL) == FAILURE) { zend_error(E_COMPILE_ERROR, "Label '%s' already defined", Z_STRVAL(label->u.constant)); } /* Done with label now */ zval_dtor(&label->u.constant); } /* }}} */ void zend_resolve_goto_label(zend_op_array *op_array, zend_op *opline, int pass2 TSRMLS_DC) /* {{{ */ { zend_label *dest; long current, distance; zval *label; if (pass2) { label = opline->op2.zv; } else { label = &CONSTANT_EX(op_array, opline->op2.constant); } if (CG(context).labels == NULL || zend_hash_find(CG(context).labels, Z_STRVAL_P(label), Z_STRLEN_P(label)+1, (void**)&dest) == FAILURE) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; zend_error(E_COMPILE_ERROR, "'goto' to undefined label '%s'", Z_STRVAL_P(label)); } else { /* Label is not defined. Delay to pass 2. */ INC_BPC(op_array); return; } } opline->op1.opline_num = dest->opline_num; zval_dtor(label); Z_TYPE_P(label) = IS_NULL; /* Check that we are not moving into loop or switch */ current = opline->extended_value; for (distance = 0; current != dest->brk_cont; distance++) { if (current == -1) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; } zend_error(E_COMPILE_ERROR, "'goto' into loop or switch statement is disallowed"); } current = op_array->brk_cont_array[current].parent; } if (distance == 0) { /* Nothing to break out of, optimize to ZEND_JMP */ opline->opcode = ZEND_JMP; opline->extended_value = 0; SET_UNUSED(opline->op2); } else { /* Set real break distance */ ZVAL_LONG(label, distance); } if (pass2) { DEC_BPC(op_array); } } /* }}} */ void zend_do_goto(const znode *label TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_GOTO; opline->extended_value = CG(context).current_brk_cont; SET_UNUSED(opline->op1); SET_NODE(opline->op2, label); zend_resolve_goto_label(CG(active_op_array), opline, 0 TSRMLS_CC); } /* }}} */ void zend_release_labels(TSRMLS_D) /* {{{ */ { if (CG(context).labels) { zend_hash_destroy(CG(context).labels); FREE_HASHTABLE(CG(context).labels); } if (!zend_stack_is_empty(&CG(context_stack))) { zend_compiler_context *ctx; zend_stack_top(&CG(context_stack), (void**)&ctx); CG(context) = *ctx; zend_stack_del_top(&CG(context_stack)); } } /* }}} */ void zend_do_build_full_name(znode *result, znode *prefix, znode *name, int is_class_member TSRMLS_DC) /* {{{ */ { zend_uint length; if (!result) { result = prefix; } else { *result = *prefix; } if (is_class_member) { length = sizeof("::")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "::", sizeof("::")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("::")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } else { length = sizeof("\\")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "\\", sizeof("\\")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("\\")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } } /* }}} */ int zend_do_begin_class_member_function_call(znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { znode class_node; unsigned char *ptr = NULL; zend_op *opline; if (method_name->op_type == IS_CONST) { char *lcname = zend_str_tolower_dup(Z_STRVAL(method_name->u.constant), Z_STRLEN(method_name->u.constant)); if ((sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == Z_STRLEN(method_name->u.constant) && memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == 0) { zval_dtor(&method_name->u.constant); method_name->op_type = IS_UNUSED; } efree(lcname); } if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; opline = get_next_op(CG(active_op_array) TSRMLS_CC); } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->extended_value = class_node.EA ; } opline->opcode = ZEND_INIT_STATIC_METHOD_CALL; if (class_node.op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, &class_node); } if (method_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &method_name->u.constant TSRMLS_CC); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } } else { SET_NODE(opline->op2, method_name); } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 1; /* Dynamic */ } /* }}} */ void zend_do_end_function_call(znode *function_name, znode *result, const znode *argument_list, int is_method, int is_dynamic_fcall TSRMLS_DC) /* {{{ */ { zend_op *opline; if (is_method && function_name && function_name->op_type == IS_UNUSED) { /* clone */ if (Z_LVAL(argument_list->u.constant) != 0) { zend_error(E_WARNING, "Clone method does not require arguments"); } opline = &CG(active_op_array)->opcodes[Z_LVAL(function_name->u.constant)]; } else { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (!is_method && !is_dynamic_fcall && function_name->op_type==IS_CONST) { opline->opcode = ZEND_DO_FCALL; SET_NODE(opline->op1, function_name); CALCULATE_LITERAL_HASH(opline->op1.constant); GET_CACHE_SLOT(opline->op1.constant); } else { opline->opcode = ZEND_DO_FCALL_BY_NAME; SET_UNUSED(opline->op1); } } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(result, opline->result) ; SET_UNUSED(opline->op2); zend_stack_del_top(&CG(function_call_stack)); opline->extended_value = Z_LVAL(argument_list->u.constant); } /* }}} */ void zend_do_pass_param(znode *param, zend_uchar op, int offset TSRMLS_DC) /* {{{ */ { zend_op *opline; int original_op=op; zend_function **function_ptr_ptr, *function_ptr; int send_by_reference; int send_function = 0; zend_stack_top(&CG(function_call_stack), (void **) &function_ptr_ptr); function_ptr = *function_ptr_ptr; if (original_op == ZEND_SEND_REF) { if (function_ptr && function_ptr->common.function_name && function_ptr->common.type == ZEND_USER_FUNCTION && !ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed; " "If you would like to pass argument by reference, modify the declaration of %s().", function_ptr->common.function_name); } else { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed"); } return; } if (function_ptr) { if (ARG_MAY_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { if (param->op_type & (IS_VAR|IS_CV) && original_op != ZEND_SEND_VAL) { send_by_reference = 1; if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION | ZEND_ARG_SEND_SILENT; } } else { op = ZEND_SEND_VAL; send_by_reference = 0; } } else { send_by_reference = ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset) ? ZEND_ARG_SEND_BY_REF : 0; } } else { send_by_reference = 0; } if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION; } else if (op == ZEND_SEND_VAL && (param->op_type & (IS_VAR|IS_CV))) { op = ZEND_SEND_VAR_NO_REF; } if (op!=ZEND_SEND_VAR_NO_REF && send_by_reference==ZEND_ARG_SEND_BY_REF) { /* change to passing by reference */ switch (param->op_type) { case IS_VAR: case IS_CV: op = ZEND_SEND_REF; break; default: zend_error(E_COMPILE_ERROR, "Only variables can be passed by reference"); break; } } if (original_op == ZEND_SEND_VAR) { switch (op) { case ZEND_SEND_VAR_NO_REF: zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); break; case ZEND_SEND_VAR: if (function_ptr) { zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(param, BP_VAR_FUNC_ARG, offset TSRMLS_CC); } break; case ZEND_SEND_REF: zend_do_end_variable_parse(param, BP_VAR_W, 0 TSRMLS_CC); break; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (op == ZEND_SEND_VAR_NO_REF) { if (function_ptr) { opline->extended_value = ZEND_ARG_COMPILE_TIME_BOUND | send_by_reference | send_function; } else { opline->extended_value = send_function; } } else { if (function_ptr) { opline->extended_value = ZEND_DO_FCALL; } else { opline->extended_value = ZEND_DO_FCALL_BY_NAME; } } opline->opcode = op; SET_NODE(opline->op1, param); opline->op2.opline_num = offset; SET_UNUSED(opline->op2); } /* }}} */ static int generate_free_switch_expr(const zend_switch_entry *switch_entry TSRMLS_DC) /* {{{ */ { zend_op *opline; if (switch_entry->cond.op_type != IS_VAR && switch_entry->cond.op_type != IS_TMP_VAR) { return (switch_entry->cond.op_type == IS_UNUSED); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry->cond); SET_UNUSED(opline->op2); opline->extended_value = 0; return 0; } /* }}} */ static int generate_free_foreach_copy(const zend_op *foreach_copy TSRMLS_DC) /* {{{ */ { zend_op *opline; /* If we reach the seperator then stop applying the stack */ if (foreach_copy->result_type == IS_UNUSED && foreach_copy->op1_type == IS_UNUSED) { return 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->result_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->result); SET_UNUSED(opline->op2); opline->extended_value = 1; if (foreach_copy->op1_type != IS_UNUSED) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->op1_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->op1); SET_UNUSED(opline->op2); opline->extended_value = 0; } return 0; } /* }}} */ void zend_do_return(znode *expr, int do_end_vparse TSRMLS_DC) /* {{{ */ { zend_op *opline; int start_op_number, end_op_number; if (do_end_vparse) { if ((CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) && !zend_is_function_or_method_call(expr)) { zend_do_end_variable_parse(expr, BP_VAR_W, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(expr, BP_VAR_R, 0 TSRMLS_CC); } } start_op_number = get_next_op_number(CG(active_op_array)); #ifdef ZTS zend_stack_apply_with_argument(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_switch_expr TSRMLS_CC); zend_stack_apply_with_argument(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_foreach_copy TSRMLS_CC); #else zend_stack_apply(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_switch_expr); zend_stack_apply(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_foreach_copy); #endif end_op_number = get_next_op_number(CG(active_op_array)); while (start_op_number < end_op_number) { CG(active_op_array)->opcodes[start_op_number].extended_value |= EXT_TYPE_FREE_ON_RETURN; start_op_number++; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) ? ZEND_RETURN_BY_REF : ZEND_RETURN; if (expr) { SET_NODE(opline->op1, expr); if (do_end_vparse && zend_is_function_or_method_call(expr)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } } else { opline->op1_type = IS_CONST; LITERAL_NULL(opline->op1); } SET_UNUSED(opline->op2); } /* }}} */ static int zend_add_try_element(zend_uint try_op TSRMLS_DC) /* {{{ */ { int try_catch_offset = CG(active_op_array)->last_try_catch++; CG(active_op_array)->try_catch_array = erealloc(CG(active_op_array)->try_catch_array, sizeof(zend_try_catch_element)*CG(active_op_array)->last_try_catch); CG(active_op_array)->try_catch_array[try_catch_offset].try_op = try_op; return try_catch_offset; } /* }}} */ static void zend_add_catch_element(int offset, zend_uint catch_op TSRMLS_DC) /* {{{ */ { CG(active_op_array)->try_catch_array[offset].catch_op = catch_op; } /* }}} */ void zend_do_first_catch(znode *open_parentheses TSRMLS_DC) /* {{{ */ { open_parentheses->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_initialize_try_catch_element(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist jmp_list; zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); zend_add_catch_element(try_token->u.op.opline_num, get_next_op_number(CG(active_op_array)) TSRMLS_CC); } /* }}} */ void zend_do_mark_last_catch(const znode *first_catch, const znode *last_additional_catch TSRMLS_DC) /* {{{ */ { CG(active_op_array)->last--; zend_do_if_end(TSRMLS_C); if (last_additional_catch->u.op.opline_num == -1) { CG(active_op_array)->opcodes[first_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[first_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } else { CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_try(znode *try_token TSRMLS_DC) /* {{{ */ { try_token->u.op.opline_num = zend_add_try_element(get_next_op_number(CG(active_op_array)) TSRMLS_CC); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_catch(znode *try_token, znode *class_name, znode *catch_var, znode *first_catch TSRMLS_DC) /* {{{ */ { long catch_op_number; zend_op *opline; znode catch_class; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); catch_class = *class_name; } else { zend_error(E_COMPILE_ERROR, "Bad class name in the catch statement"); } catch_op_number = get_next_op_number(CG(active_op_array)); if (first_catch) { first_catch->u.op.opline_num = catch_op_number; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CATCH; opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &catch_class.u.constant TSRMLS_CC); opline->op2_type = IS_CV; opline->op2.var = lookup_cv(CG(active_op_array), catch_var->u.constant.value.str.val, catch_var->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(catch_var->u.constant) = (char*)CG(active_op_array)->vars[opline->op2.var].name; opline->result.num = 0; /* 1 means it's the last catch in the block */ try_token->u.op.opline_num = catch_op_number; } /* }}} */ void zend_do_end_catch(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); CG(active_op_array)->opcodes[try_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_throw(const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_THROW; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); } /* }}} */ ZEND_API void function_add_ref(zend_function *function) /* {{{ */ { if (function->type == ZEND_USER_FUNCTION) { zend_op_array *op_array = &function->op_array; (*op_array->refcount)++; if (op_array->static_variables) { HashTable *static_variables = op_array->static_variables; zval *tmp_zval; ALLOC_HASHTABLE(op_array->static_variables); zend_hash_init(op_array->static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(op_array->static_variables, static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_zval, sizeof(zval *)); } op_array->run_time_cache = NULL; } } /* }}} */ static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */ { zend_function *function; if (!ce->parent) { return; } /* You cannot change create_object */ ce->create_object = ce->parent->create_object; /* Inherit special functions if needed */ if (!ce->get_iterator) { ce->get_iterator = ce->parent->get_iterator; } if (!ce->iterator_funcs.funcs) { ce->iterator_funcs.funcs = ce->parent->iterator_funcs.funcs; } if (!ce->__get) { ce->__get = ce->parent->__get; } if (!ce->__set) { ce->__set = ce->parent->__set; } if (!ce->__unset) { ce->__unset = ce->parent->__unset; } if (!ce->__isset) { ce->__isset = ce->parent->__isset; } if (!ce->__call) { ce->__call = ce->parent->__call; } if (!ce->__callstatic) { ce->__callstatic = ce->parent->__callstatic; } if (!ce->__tostring) { ce->__tostring = ce->parent->__tostring; } if (!ce->clone) { ce->clone = ce->parent->clone; } if(!ce->serialize) { ce->serialize = ce->parent->serialize; } if(!ce->unserialize) { ce->unserialize = ce->parent->unserialize; } if (!ce->destructor) { ce->destructor = ce->parent->destructor; } if (ce->constructor) { if (ce->parent->constructor && ce->parent->constructor->common.fn_flags & ZEND_ACC_FINAL) { zend_error(E_ERROR, "Cannot override final %s::%s() with %s::%s()", ce->parent->name, ce->parent->constructor->common.function_name, ce->name, ce->constructor->common.function_name ); } return; } if (zend_hash_find(&ce->parent->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), (void **)&function)==SUCCESS) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), function, sizeof(zend_function), NULL); function_add_ref(function); } else { /* Don't inherit the old style constructor if we already have the new style constructor */ char *lc_class_name; char *lc_parent_class_name; lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); if (!zend_hash_exists(&ce->function_table, lc_class_name, ce->name_length+1)) { lc_parent_class_name = zend_str_tolower_dup(ce->parent->name, ce->parent->name_length); if (!zend_hash_exists(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1) && zend_hash_find(&ce->parent->function_table, lc_parent_class_name, ce->parent->name_length+1, (void **)&function)==SUCCESS) { if (function->common.fn_flags & ZEND_ACC_CTOR) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1, function, sizeof(zend_function), NULL); function_add_ref(function); } } efree(lc_parent_class_name); } efree(lc_class_name); } ce->constructor = ce->parent->constructor; } /* }}} */ char *zend_visibility_string(zend_uint fn_flags) /* {{{ */ { if (fn_flags & ZEND_ACC_PRIVATE) { return "private"; } if (fn_flags & ZEND_ACC_PROTECTED) { return "protected"; } if (fn_flags & ZEND_ACC_PUBLIC) { return "public"; } return ""; } /* }}} */ static void do_inherit_method(zend_function *function) /* {{{ */ { /* The class entry of the derived function intentionally remains the same * as that of the parent class. That allows us to know in which context * we're running, and handle private method calls properly. */ function_add_ref(function); } /* }}} */ static zend_bool zend_do_perform_implementation_check(const zend_function *fe, const zend_function *proto TSRMLS_DC) /* {{{ */ { zend_uint i; /* If it's a user function then arg_info == NULL means we don't have any parameters but * we still need to do the arg number checks. We are only willing to ignore this for internal * functions because extensions don't always define arg_info. */ if (!proto || (!proto->common.arg_info && proto->common.type != ZEND_USER_FUNCTION)) { return 1; } /* Checks for constructors only if they are declared in an interface, * or explicitly marked as abstract */ if ((fe->common.fn_flags & ZEND_ACC_CTOR) && ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)) { return 1; } /* check number of arguments */ if (proto->common.required_num_args < fe->common.required_num_args || proto->common.num_args > fe->common.num_args) { return 0; } if (fe->common.type != ZEND_USER_FUNCTION && (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) != 0 && (fe->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) == 0) { return 0; } /* by-ref constraints on return values are covariant */ if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) { return 0; } for (i=0; i < proto->common.num_args; i++) { if (ZEND_LOG_XOR(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)) { /* Only one has a type hint and the other one doesn't */ return 0; } if (fe->common.arg_info[i].class_name && strcasecmp(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)!=0) { const char *colon; if (fe->common.type != ZEND_USER_FUNCTION) { return 0; } else if (strchr(proto->common.arg_info[i].class_name, '\\') != NULL || (colon = zend_memrchr(fe->common.arg_info[i].class_name, '\\', fe->common.arg_info[i].class_name_len)) == NULL || strcasecmp(colon+1, proto->common.arg_info[i].class_name) != 0) { zend_class_entry **fe_ce, **proto_ce; int found, found2; found = zend_lookup_class(fe->common.arg_info[i].class_name, fe->common.arg_info[i].class_name_len, &fe_ce TSRMLS_CC); found2 = zend_lookup_class(proto->common.arg_info[i].class_name, proto->common.arg_info[i].class_name_len, &proto_ce TSRMLS_CC); /* Check for class alias */ if (found != SUCCESS || found2 != SUCCESS || (*fe_ce)->type == ZEND_INTERNAL_CLASS || (*proto_ce)->type == ZEND_INTERNAL_CLASS || *fe_ce != *proto_ce) { return 0; } } } if (fe->common.arg_info[i].type_hint != proto->common.arg_info[i].type_hint) { /* Incompatible type hint */ return 0; } /* by-ref constraints on arguments are invariant */ if (fe->common.arg_info[i].pass_by_reference != proto->common.arg_info[i].pass_by_reference) { return 0; } } if (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) { for (i=proto->common.num_args; i < fe->common.num_args; i++) { if (!fe->common.arg_info[i].pass_by_reference) { return 0; } } } return 1; } /* }}} */ #define REALLOC_BUF_IF_EXCEED(buf, offset, length, size) \ if (UNEXPECTED(offset - buf + size >= length)) { \ length += size + 1; \ buf = erealloc(buf, length); \ } static char * zend_get_function_declaration(zend_function *fptr TSRMLS_DC) /* {{{ */ { char *offset, *buf; zend_uint length = 1024; offset = buf = (char *)emalloc(length * sizeof(char)); if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { *(offset++) = '&'; *(offset++) = ' '; } if (fptr->common.scope) { memcpy(offset, fptr->common.scope->name, fptr->common.scope->name_length); offset += fptr->common.scope->name_length; *(offset++) = ':'; *(offset++) = ':'; } { size_t name_len = strlen(fptr->common.function_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, name_len); memcpy(offset, fptr->common.function_name, name_len); offset += name_len; } *(offset++) = '('; if (fptr->common.arg_info) { zend_uint i, required; zend_arg_info *arg_info = fptr->common.arg_info; required = fptr->common.required_num_args; for (i = 0; i < fptr->common.num_args;) { if (arg_info->class_name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->class_name_len); memcpy(offset, arg_info->class_name, arg_info->class_name_len); offset += arg_info->class_name_len; *(offset++) = ' '; } else if (arg_info->type_hint) { zend_uint type_name_len; char *type_name = zend_get_type_by_const(arg_info->type_hint); type_name_len = strlen(type_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, type_name_len); memcpy(offset, type_name, type_name_len); offset += type_name_len; *(offset++) = ' '; } if (arg_info->pass_by_reference) { *(offset++) = '&'; } *(offset++) = '$'; if (arg_info->name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->name_len); memcpy(offset, arg_info->name, arg_info->name_len); offset += arg_info->name_len; } else { zend_uint idx = i; memcpy(offset, "param", 5); offset += 5; do { *(offset++) = (char) (idx % 10) + '0'; idx /= 10; } while (idx > 0); } if (i >= required) { *(offset++) = ' '; *(offset++) = '='; *(offset++) = ' '; if (fptr->type == ZEND_USER_FUNCTION) { zend_op *precv = NULL; { zend_uint idx = i; zend_op *op = ((zend_op_array *)fptr)->opcodes; zend_op *end = op + ((zend_op_array *)fptr)->last; ++idx; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT) && op->op1.num == (long)idx) { precv = op; } ++op; } } if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) { zval *zv, zv_copy; int use_copy; ALLOC_ZVAL(zv); *zv = *precv->op2.zv; zval_copy_ctor(zv); INIT_PZVAL(zv); zval_update_constant_ex(&zv, (void*)1, fptr->common.scope TSRMLS_CC); if (Z_TYPE_P(zv) == IS_BOOL) { if (Z_LVAL_P(zv)) { memcpy(offset, "true", 4); offset += 4; } else { memcpy(offset, "false", 5); offset += 5; } } else if (Z_TYPE_P(zv) == IS_NULL) { memcpy(offset, "NULL", 4); offset += 4; } else if (Z_TYPE_P(zv) == IS_STRING) { *(offset++) = '\''; REALLOC_BUF_IF_EXCEED(buf, offset, length, MIN(Z_STRLEN_P(zv), 10)); memcpy(offset, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 10)); offset += MIN(Z_STRLEN_P(zv), 10); if (Z_STRLEN_P(zv) > 10) { *(offset++) = '.'; *(offset++) = '.'; *(offset++) = '.'; } *(offset++) = '\''; } else if (Z_TYPE_P(zv) == IS_ARRAY) { memcpy(offset, "Array", 5); offset += 5; } else { zend_make_printable_zval(zv, &zv_copy, &use_copy); REALLOC_BUF_IF_EXCEED(buf, offset, length, Z_STRLEN(zv_copy)); memcpy(offset, Z_STRVAL(zv_copy), Z_STRLEN(zv_copy)); offset += Z_STRLEN(zv_copy); if (use_copy) { zval_dtor(&zv_copy); } } zval_ptr_dtor(&zv); } } else { memcpy(offset, "NULL", 4); offset += 4; } } if (++i < fptr->common.num_args) { *(offset++) = ','; *(offset++) = ' '; } arg_info++; REALLOC_BUF_IF_EXCEED(buf, offset, length, 32); } } *(offset++) = ')'; *offset = '\0'; return buf; } /* }}} */ static void do_inheritance_check_on_method(zend_function *child, zend_function *parent TSRMLS_DC) /* {{{ */ { zend_uint child_flags; zend_uint parent_flags = parent->common.fn_flags; if ((parent->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && parent->common.fn_flags & ZEND_ACC_ABSTRACT && parent->common.scope != (child->common.prototype ? child->common.prototype->common.scope : child->common.scope) && child->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_IMPLEMENTED_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Can't inherit abstract function %s::%s() (previously declared abstract in %s)", parent->common.scope->name, child->common.function_name, child->common.prototype ? child->common.prototype->common.scope->name : child->common.scope->name); } if (parent_flags & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot override final method %s::%s()", ZEND_FN_SCOPE_NAME(parent), child->common.function_name); } child_flags = child->common.fn_flags; /* You cannot change from static to non static and vice versa. */ if ((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC)) { if (child->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot make non static method %s::%s() static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } else { zend_error(E_COMPILE_ERROR, "Cannot make static method %s::%s() non static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } } /* Disallow making an inherited method abstract. */ if ((child_flags & ZEND_ACC_ABSTRACT) && !(parent_flags & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Cannot make non abstract method %s::%s() abstract in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } if (parent_flags & ZEND_ACC_CHANGED) { child->common.fn_flags |= ZEND_ACC_CHANGED; } else { /* Prevent derived classes from restricting access that was available in parent classes */ if ((child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::%s() must be %s (as in class %s)%s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if (((child_flags & ZEND_ACC_PPP_MASK) < (parent_flags & ZEND_ACC_PPP_MASK)) && ((parent_flags & ZEND_ACC_PPP_MASK) & ZEND_ACC_PRIVATE)) { child->common.fn_flags |= ZEND_ACC_CHANGED; } } if (parent_flags & ZEND_ACC_PRIVATE) { child->common.prototype = NULL; } else if (parent_flags & ZEND_ACC_ABSTRACT) { child->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; child->common.prototype = parent; } else if (!(parent->common.fn_flags & ZEND_ACC_CTOR) || (parent->common.prototype && (parent->common.prototype->common.scope->ce_flags & ZEND_ACC_INTERFACE))) { /* ctors only have a prototype if it comes from an interface */ child->common.prototype = parent->common.prototype ? parent->common.prototype : parent; } if (child->common.prototype && (child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { if (!zend_do_perform_implementation_check(child, child->common.prototype TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s::%s() must be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_get_function_declaration(child->common.prototype TSRMLS_CC)); } } else if (EG(error_reporting) & E_STRICT || EG(user_error_handler)) { /* Check E_STRICT (or custom error handler) before the check so that we save some time */ if (!zend_do_perform_implementation_check(child, parent TSRMLS_CC)) { char *method_prototype = zend_get_function_declaration(child->common.prototype TSRMLS_CC); zend_error(E_STRICT, "Declaration of %s::%s() should be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, method_prototype); efree(method_prototype); } } } /* }}} */ static zend_bool do_inherit_method_check(HashTable *child_function_table, zend_function *parent, const zend_hash_key *hash_key, zend_class_entry *child_ce) /* {{{ */ { zend_uint parent_flags = parent->common.fn_flags; zend_function *child; TSRMLS_FETCH(); if (zend_hash_quick_find(child_function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child)==FAILURE) { if (parent_flags & (ZEND_ACC_ABSTRACT)) { child_ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } return 1; /* method doesn't exist in child, copy from parent */ } do_inheritance_check_on_method(child, parent TSRMLS_CC); return 0; } /* }}} */ static zend_bool do_inherit_property_access_check(HashTable *target_ht, zend_property_info *parent_info, const zend_hash_key *hash_key, zend_class_entry *ce) /* {{{ */ { zend_property_info *child_info; zend_class_entry *parent_ce = ce->parent; if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW)) { if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { child_info->flags |= ZEND_ACC_CHANGED; } else { zend_hash_quick_update(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, parent_info, sizeof(zend_property_info), (void **) &child_info); if(ce->type & ZEND_INTERNAL_CLASS) { zend_duplicate_property_info_internal(child_info); } else { zend_duplicate_property_info(child_info); } child_info->flags &= ~ZEND_ACC_PRIVATE; /* it's not private anymore */ child_info->flags |= ZEND_ACC_SHADOW; /* but it's a shadow of private */ } return 0; /* don't copy access information to child */ } if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { if ((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s", (parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", parent_ce->name, hash_key->arKey, (child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ce->name, hash_key->arKey); } if(parent_info->flags & ZEND_ACC_CHANGED) { child_info->flags |= ZEND_ACC_CHANGED; } if ((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ce->name, hash_key->arKey, zend_visibility_string(parent_info->flags), parent_ce->name, (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if ((child_info->flags & ZEND_ACC_STATIC) == 0) { Z_DELREF_P(ce->default_properties_table[parent_info->offset]); ce->default_properties_table[parent_info->offset] = ce->default_properties_table[child_info->offset]; ce->default_properties_table[child_info->offset] = NULL; child_info->offset = parent_info->offset; } return 0; /* Don't copy from parent */ } else { return 1; /* Copy from parent */ } } /* }}} */ static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce TSRMLS_CC) == FAILURE) { zend_error(E_CORE_ERROR, "Class %s could not implement interface %s", ce->name, iface->name); } if (ce == iface) { zend_error(E_ERROR, "Interface %s cannot implement itself", ce->name); } } /* }}} */ ZEND_API void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface TSRMLS_DC) /* {{{ */ { /* expects interface to be contained in ce's interface list already */ zend_uint i, ce_num, if_num = iface->num_interfaces; zend_class_entry *entry; if (if_num==0) { return; } ce_num = ce->num_interfaces; if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } /* Inherit the interfaces, only if they're not already inherited by the class */ while (if_num--) { entry = iface->interfaces[if_num]; for (i = 0; i < ce_num; i++) { if (ce->interfaces[i] == entry) { break; } } if (i == ce_num) { ce->interfaces[ce->num_interfaces++] = entry; } } /* and now call the implementing handlers */ while (ce_num < ce->num_interfaces) { do_implement_interface(ce, ce->interfaces[ce_num++] TSRMLS_CC); } } /* }}} */ #ifdef ZTS static void zval_internal_ctor(zval **p) /* {{{ */ { zval *orig_ptr = *p; ALLOC_ZVAL(*p); MAKE_COPY_ZVAL(&orig_ptr, *p); } /* }}} */ # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) (((parent_ce)->type != (ce)->type) ? zval_internal_ctor : zval_add_ref)) #else # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) zval_add_ref) #endif ZEND_API void zend_do_inheritance(zend_class_entry *ce, zend_class_entry *parent_ce TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; if ((ce->ce_flags & ZEND_ACC_INTERFACE) && !(parent_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ce->name, parent_ce->name); } if (parent_ce->ce_flags & ZEND_ACC_FINAL_CLASS) { zend_error(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ce->name, parent_ce->name); } ce->parent = parent_ce; /* Copy serialize/unserialize callbacks */ if (!ce->serialize) { ce->serialize = parent_ce->serialize; } if (!ce->unserialize) { ce->unserialize = parent_ce->unserialize; } /* Inherit interfaces */ zend_do_inherit_interfaces(ce, parent_ce TSRMLS_CC); /* Inherit properties */ if (parent_ce->default_properties_count) { int i = ce->default_properties_count + parent_ce->default_properties_count; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_properties_count) { while (i-- > parent_ce->default_properties_count) { ce->default_properties_table[i] = ce->default_properties_table[i - parent_ce->default_properties_count]; } } for (i = 0; i < parent_ce->default_properties_count; i++) { ce->default_properties_table[i] = parent_ce->default_properties_table[i]; if (ce->default_properties_table[i]) { #ifdef ZTS if (parent_ce->type != ce->type) { zval *p; ALLOC_ZVAL(p); MAKE_COPY_ZVAL(&ce->default_properties_table[i], p); ce->default_properties_table[i] = p; } else { Z_ADDREF_P(ce->default_properties_table[i]); } #else Z_ADDREF_P(ce->default_properties_table[i]); #endif } } ce->default_properties_count += parent_ce->default_properties_count; } if (parent_ce->type != ce->type) { /* User class extends internal class */ zend_update_class_constants(parent_ce TSRMLS_CC); if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = erealloc(ce->default_static_members_table, sizeof(void*) * i); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&CE_STATIC_MEMBERS(parent_ce)[i]); ce->default_static_members_table[i] = CE_STATIC_MEMBERS(parent_ce)[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; ce->static_members_table = ce->default_static_members_table; } } else { if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&parent_ce->default_static_members_table[i]); ce->default_static_members_table[i] = parent_ce->default_static_members_table[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } } for (zend_hash_internal_pointer_reset(&ce->properties_info); zend_hash_get_current_data(&ce->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->properties_info)) { if (property_info->ce == ce) { if (property_info->flags & ZEND_ACC_STATIC) { property_info->offset += parent_ce->default_static_members_count; } else { property_info->offset += parent_ce->default_properties_count; } } } zend_hash_merge_ex(&ce->properties_info, &parent_ce->properties_info, (copy_ctor_func_t) (ce->type & ZEND_INTERNAL_CLASS ? zend_duplicate_property_info_internal : zend_duplicate_property_info), sizeof(zend_property_info), (merge_checker_func_t) do_inherit_property_access_check, ce); zend_hash_merge(&ce->constants_table, &parent_ce->constants_table, zval_property_ctor(parent_ce, ce), NULL, sizeof(zval *), 0); zend_hash_merge_ex(&ce->function_table, &parent_ce->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_inherit_parent_constructor(ce); if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS && ce->type == ZEND_INTERNAL_CLASS) { ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } else if (!(ce->ce_flags & ZEND_ACC_IMPLEMENT_INTERFACES) && !(ce->ce_flags & ZEND_ACC_IMPLEMENT_TRAITS)) { /* The verification will be done in runtime by ZEND_VERIFY_ABSTRACT_CLASS */ zend_verify_abstract_class(ce TSRMLS_CC); } ce->ce_flags |= parent_ce->ce_flags & ZEND_HAS_STATIC_IN_METHODS; } /* }}} */ static zend_bool do_inherit_constant_check(HashTable *child_constants_table, const zval **parent_constant, const zend_hash_key *hash_key, const zend_class_entry *iface) /* {{{ */ { zval **old_constant; if (zend_hash_quick_find(child_constants_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**)&old_constant) == SUCCESS) { if (*old_constant != *parent_constant) { zend_error(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", hash_key->arKey, iface->name); } return 0; } return 1; } /* }}} */ static int do_interface_constant_check(zval **val TSRMLS_DC, int num_args, va_list args, const zend_hash_key *key) /* {{{ */ { zend_class_entry **iface = va_arg(args, zend_class_entry**); do_inherit_constant_check(&(*iface)->constants_table, (const zval **) val, key, *iface); return ZEND_HASH_APPLY_KEEP; } /* }}} */ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_iface_num = ce->num_interfaces; zend_uint parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0; for (i = 0; i < ce->num_interfaces; i++) { if (ce->interfaces[i] == NULL) { memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i)); i--; } else if (ce->interfaces[i] == iface) { if (i < parent_iface_num) { ignore = 1; } else { zend_error(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ce->name, iface->name); } } } if (ignore) { /* Check for attempt to redeclare interface constants */ zend_hash_apply_with_arguments(&ce->constants_table TSRMLS_CC, (apply_func_args_t) do_interface_constant_check, 1, &iface); } else { if (ce->num_interfaces >= current_iface_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } } ce->interfaces[ce->num_interfaces++] = iface; zend_hash_merge_ex(&ce->constants_table, &iface->constants_table, (copy_ctor_func_t) zval_add_ref, sizeof(zval *), (merge_checker_func_t) do_inherit_constant_check, iface); zend_hash_merge_ex(&ce->function_table, &iface->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_implement_interface(ce, iface TSRMLS_CC); zend_do_inherit_interfaces(ce, iface TSRMLS_CC); } } /* }}} */ ZEND_API void zend_do_implement_trait(zend_class_entry *ce, zend_class_entry *trait TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_trait_num = ce->num_traits; zend_uint parent_trait_num = ce->parent ? ce->parent->num_traits : 0; for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == NULL) { memmove(ce->traits + i, ce->traits + i + 1, sizeof(zend_class_entry*) * (--ce->num_traits - i)); i--; } else if (ce->traits[i] == trait) { if (i < parent_trait_num) { ignore = 1; } } } if (!ignore) { if (ce->num_traits >= current_trait_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->traits = (zend_class_entry **) realloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } else { ce->traits = (zend_class_entry **) erealloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } } ce->traits[ce->num_traits++] = trait; } } /* }}} */ static int zend_traits_merge_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { size_t current; size_t i; size_t count; HashTable* resulting_table; HashTable** function_tables; zend_class_entry *ce; size_t collision = 0; size_t abstract_solved = 0; zend_function* other_trait_fn; current = va_arg(args, size_t); /* index of current trait */ count = va_arg(args, size_t); resulting_table = va_arg(args, HashTable*); function_tables = va_arg(args, HashTable**); ce = va_arg(args, zend_class_entry*); for (i = 0; i < count; i++) { if (i == current) { continue; /* just skip this, cause its the table this function is applied on */ } if (zend_hash_quick_find(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&other_trait_fn) == SUCCESS) { /* if it is an abstract method, there is no collision */ if (other_trait_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* In case both are abstract, just check prototype, but need to do that in both directions */ if ( !zend_do_perform_implementation_check(fn, other_trait_fn TSRMLS_CC) || !zend_do_perform_implementation_check(other_trait_fn, fn TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s must be compatible with %s", //ZEND_FN_SCOPE_NAME(fn), fn->common.function_name, //::%s() zend_get_function_declaration(fn TSRMLS_CC), zend_get_function_declaration(other_trait_fn TSRMLS_CC)); } } else { /* otherwise, do the full check */ do_inheritance_check_on_method(fn, other_trait_fn TSRMLS_CC); } /* we can savely free and remove it from other table */ zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } else { /* if it is not an abstract method, there is still no collision */ /* if fn is an abstract method */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible. Here, we already know other_trait_fn cannot be abstract, full check ok. */ do_inheritance_check_on_method(other_trait_fn, fn TSRMLS_CC); /* just mark as solved, will be added if its own trait is processed */ abstract_solved = 1; } else { /* but else, we have a collision of non-abstract methods */ collision++; zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } } } if (collision) { zend_function* class_fn; /* make sure method is not already overridden in class */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&class_fn) == FAILURE || class_fn->common.scope != ce) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because there are collisions with other trait methods on %s", fn->common.function_name, ce->name); } zend_function_dtor(fn); } else if (abstract_solved) { zend_function_dtor(fn); } else { /* Add it to result function table */ if (zend_hash_quick_add(resulting_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, fn, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating resulting trait method table", fn->common.function_name); } } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ /* {{{ Originates from php_runkit_function_copy_ctor Duplicate structures in an op_array where necessary to make an outright duplicate */ static void zend_traits_duplicate_function(zend_function *fe, zend_class_entry *target_ce, char *newname TSRMLS_DC) { zend_literal *literals_copy; zend_compiled_variable *dupvars; zend_op *opcode_copy; zval class_name_zv; int class_name_literal; int i; int number_of_literals; if (fe->op_array.static_variables) { HashTable *tmpHash; ALLOC_HASHTABLE(tmpHash); zend_hash_init(tmpHash, zend_hash_num_elements(fe->op_array.static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_apply_with_arguments(fe->op_array.static_variables TSRMLS_CC, (apply_func_args_t)zval_copy_static_var, 1, tmpHash); fe->op_array.static_variables = tmpHash; } number_of_literals = fe->op_array.last_literal; literals_copy = (zend_literal*)emalloc(number_of_literals * sizeof(zend_literal)); for (i = 0; i < number_of_literals; i++) { literals_copy[i] = fe->op_array.literals[i]; zval_copy_ctor(&literals_copy[i].constant); } fe->op_array.literals = literals_copy; fe->op_array.refcount = emalloc(sizeof(zend_uint)); *(fe->op_array.refcount) = 1; if (fe->op_array.vars) { i = fe->op_array.last_var; dupvars = safe_emalloc(fe->op_array.last_var, sizeof(zend_compiled_variable), 0); while (i > 0) { i--; dupvars[i].name = estrndup(fe->op_array.vars[i].name, fe->op_array.vars[i].name_len); dupvars[i].name_len = fe->op_array.vars[i].name_len; dupvars[i].hash_value = fe->op_array.vars[i].hash_value; } fe->op_array.vars = dupvars; } else { fe->op_array.vars = NULL; } opcode_copy = safe_emalloc(sizeof(zend_op), fe->op_array.last, 0); for(i = 0; i < fe->op_array.last; i++) { opcode_copy[i] = fe->op_array.opcodes[i]; if (opcode_copy[i].op1_type != IS_CONST) { switch (opcode_copy[i].opcode) { case ZEND_GOTO: case ZEND_JMP: if (opcode_copy[i].op1.jmp_addr && opcode_copy[i].op1.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op1.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op1.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op1.jmp_addr - fe->op_array.opcodes); } break; } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op1.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op1.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op1.zv = &fe->op_array.literals[class_name_literal].constant; } } if (opcode_copy[i].op2_type != IS_CONST) { switch (opcode_copy[i].opcode) { case ZEND_JMPZ: case ZEND_JMPNZ: case ZEND_JMPZ_EX: case ZEND_JMPNZ_EX: case ZEND_JMP_SET: case ZEND_JMP_SET_VAR: if (opcode_copy[i].op2.jmp_addr && opcode_copy[i].op2.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op2.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op2.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op2.jmp_addr - fe->op_array.opcodes); } break; } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op2.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op2.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op2.zv = &fe->op_array.literals[class_name_literal].constant; } } } fe->op_array.opcodes = opcode_copy; fe->op_array.function_name = newname; /* was setting it to fe which does not work since fe is stack allocated and not a stable address */ /* fe->op_array.prototype = fe->op_array.prototype; */ if (fe->op_array.arg_info) { zend_arg_info *tmpArginfo; tmpArginfo = safe_emalloc(sizeof(zend_arg_info), fe->op_array.num_args, 0); for(i = 0; i < fe->op_array.num_args; i++) { tmpArginfo[i] = fe->op_array.arg_info[i]; tmpArginfo[i].name = estrndup(tmpArginfo[i].name, tmpArginfo[i].name_len); if (tmpArginfo[i].class_name) { tmpArginfo[i].class_name = estrndup(tmpArginfo[i].class_name, tmpArginfo[i].class_name_len); } } fe->op_array.arg_info = tmpArginfo; } fe->op_array.doc_comment = estrndup(fe->op_array.doc_comment, fe->op_array.doc_comment_len); fe->op_array.try_catch_array = (zend_try_catch_element*)estrndup((char*)fe->op_array.try_catch_array, sizeof(zend_try_catch_element) * fe->op_array.last_try_catch); fe->op_array.brk_cont_array = (zend_brk_cont_element*)estrndup((char*)fe->op_array.brk_cont_array, sizeof(zend_brk_cont_element) * fe->op_array.last_brk_cont); } /* }}} */ static void zend_add_magic_methods(zend_class_entry* ce, const char* mname, uint mname_len, zend_function* fe TSRMLS_DC) /* {{{ */ { if (!strncmp(mname, ZEND_CLONE_FUNC_NAME, mname_len)) { ce->clone = fe; fe->common.fn_flags |= ZEND_ACC_CLONE; } else if (!strncmp(mname, ZEND_CONSTRUCTOR_FUNC_NAME, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } else if (!strncmp(mname, ZEND_DESTRUCTOR_FUNC_NAME, mname_len)) { ce->destructor = fe; fe->common.fn_flags |= ZEND_ACC_DTOR; } else if (!strncmp(mname, ZEND_GET_FUNC_NAME, mname_len)) { ce->__get = fe; } else if (!strncmp(mname, ZEND_SET_FUNC_NAME, mname_len)) { ce->__set = fe; } else if (!strncmp(mname, ZEND_CALL_FUNC_NAME, mname_len)) { ce->__call = fe; } else if (!strncmp(mname, ZEND_UNSET_FUNC_NAME, mname_len)) { ce->__unset = fe; } else if (!strncmp(mname, ZEND_ISSET_FUNC_NAME, mname_len)) { ce->__isset = fe; } else if (!strncmp(mname, ZEND_CALLSTATIC_FUNC_NAME, mname_len)) { ce->__callstatic = fe; } else if (!strncmp(mname, ZEND_TOSTRING_FUNC_NAME, mname_len)) { ce->__tostring = fe; } else if (ce->name_length + 1 == mname_len) { char *lowercase_name = emalloc(ce->name_length + 1); zend_str_tolower_copy(lowercase_name, ce->name, ce->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, ce->name_length + 1, 1 TSRMLS_CC); if (!memcmp(mname, lowercase_name, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } str_efree(lowercase_name); } } /* }}} */ static int zend_traits_merge_functions_to_class(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zend_class_entry *ce = va_arg(args, zend_class_entry*); int add = 0; zend_function* existing_fn = NULL; zend_function fn_copy, *fn_copy_p; zend_function* prototype = NULL; /* is used to determine the prototype according to the inheritance chain */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &existing_fn) == FAILURE) { add = 1; /* not found */ } else if (existing_fn->common.scope != ce) { add = 1; /* or inherited from other class or interface */ } if (add) { zend_function* parent_function; if (ce->parent && zend_hash_quick_find(&ce->parent->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &parent_function) != FAILURE) { prototype = parent_function; /* ->common.fn_flags |= ZEND_ACC_ABSTRACT; */ /* we got that method in the parent class, and are going to override it, except, if the trait is just asking to have an abstract method implemented. */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* then we clean up an skip this method */ zend_function_dtor(fn); return ZEND_HASH_APPLY_REMOVE; } } fn->common.scope = ce; fn->common.prototype = prototype; if (prototype && (prototype->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT || prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { fn->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; } else if (fn->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT) { /* remove ZEND_ACC_IMPLEMENTED_ABSTRACT flag, think it shouldn't be copied to class */ fn->common.fn_flags = fn->common.fn_flags - ZEND_ACC_IMPLEMENTED_ABSTRACT; } /* check whether the trait method fullfills the inheritance requirements */ if (prototype) { do_inheritance_check_on_method(fn, prototype TSRMLS_CC); } /* one more thing: make sure we properly implement an abstract method */ if (existing_fn && existing_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { do_inheritance_check_on_method(fn, existing_fn TSRMLS_CC); } /* delete inherited fn if the function to be added is not abstract */ if (existing_fn && existing_fn->common.scope != ce && (fn->common.fn_flags & ZEND_ACC_ABSTRACT) == 0) { /* it is just a reference which was added to the subclass while doing the inheritance, so we can deleted now, and will add the overriding method afterwards. Except, if we try to add an abstract function, then we should not delete the inherited one */ zend_hash_quick_del(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h); } if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (fn->op_array.static_variables) { ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, ce, estrdup(fn->common.function_name) TSRMLS_CC); if (zend_hash_quick_update(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, &fn_copy, sizeof(zend_function), (void**)&fn_copy_p)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating class method table", hash_key->arKey); } zend_add_magic_methods(ce, hash_key->arKey, hash_key->nKeyLength, fn_copy_p TSRMLS_CC); zend_function_dtor(fn); } else { zend_function_dtor(fn); } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ static int zend_traits_copy_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { HashTable* target; zend_class_entry *target_ce; zend_trait_alias** aliases; HashTable* exclude_table; char* lcname; unsigned int fnname_len; zend_function fn_copy; void* dummy; size_t i = 0; target = va_arg(args, HashTable*); target_ce = va_arg(args, zend_class_entry*); aliases = va_arg(args, zend_trait_alias**); exclude_table = va_arg(args, HashTable*); fnname_len = strlen(fn->common.function_name); /* apply aliases which are qualified with a class name, there should not be any ambiguity */ if (aliases) { while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias != NULL && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && aliases[i]->trait_method->mname_len == fnname_len && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(aliases[i]->alias, aliases[i]->alias_len) TSRMLS_CC); /* if it is 0, no modifieres has been changed */ if (aliases[i]->modifiers) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } lcname = zend_str_tolower_dup(aliases[i]->alias, aliases[i]->alias_len); if (zend_hash_add(target, lcname, aliases[i]->alias_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add aliased trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } efree(lcname); /** Record the trait from which this alias was resolved. */ if (!aliases[i]->trait_method->ce) { aliases[i]->trait_method->ce = fn->common.scope; } } i++; } } lcname = zend_str_tolower_dup(fn->common.function_name, fnname_len); if (exclude_table == NULL || zend_hash_find(exclude_table, lcname, fnname_len, &dummy) == FAILURE) { /* is not in hashtable, thus, function is not to be excluded */ fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(fn->common.function_name, fnname_len) TSRMLS_CC); /* apply aliases which are not qualified by a class name, or which have not * alias name, just setting visibility */ if (aliases) { i = 0; while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias == NULL && aliases[i]->modifiers != 0 && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && (aliases[i]->trait_method->mname_len == fnname_len) && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); /** Record the trait from which this alias was resolved. */ if (!aliases[i]->trait_method->ce) { aliases[i]->trait_method->ce = fn->common.scope; } } i++; } } if (zend_hash_add(target, lcname, fnname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } } efree(lcname); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* Copies function table entries to target function table with applied aliasing */ static void zend_traits_copy_trait_function_table(HashTable *target, zend_class_entry *target_ce, HashTable *source, zend_trait_alias** aliases, HashTable* exclude_table TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_arguments(source TSRMLS_CC, (apply_func_args_t)zend_traits_copy_functions, 4, target, target_ce, aliases, exclude_table); } /* }}} */ static void zend_traits_init_trait_structures(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i, j = 0; zend_trait_precedence *cur_precedence; zend_trait_method_reference *cur_method_ref; char *lcname; zend_bool method_exists; /* resolve class references */ if (ce->trait_precedences) { i = 0; while ((cur_precedence = ce->trait_precedences[i])) { /** Resolve classes for all precedence operations. */ if (cur_precedence->exclude_from_classes) { cur_method_ref = cur_precedence->trait_method; cur_precedence->trait_method->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); /** Ensure that the prefered method is actually available. */ lcname = zend_str_tolower_dup(cur_method_ref->method_name, cur_method_ref->mname_len); method_exists = zend_hash_exists(&cur_method_ref->ce->function_table, lcname, cur_method_ref->mname_len + 1); efree(lcname); if (!method_exists) { zend_error(E_COMPILE_ERROR, "A precedence rule was defined for %s::%s but this method does not exist", cur_method_ref->ce->name, cur_method_ref->method_name); } /** With the other traits, we are more permissive. We do not give errors for those. This allows to be more defensive in such definitions. */ j = 0; while (cur_precedence->exclude_from_classes[j]) { char* class_name = (char*)cur_precedence->exclude_from_classes[j]; zend_uint name_length = strlen(class_name); cur_precedence->exclude_from_classes[j] = zend_fetch_class(class_name, name_length, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); efree(class_name); j++; } } i++; } } if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { /** For all aliases with an explicit class name, resolve the class now. */ if (ce->trait_aliases[i]->trait_method->class_name) { cur_method_ref = ce->trait_aliases[i]->trait_method; cur_method_ref->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); /** And, ensure that the referenced method is resolvable, too. */ lcname = zend_str_tolower_dup(cur_method_ref->method_name, cur_method_ref->mname_len); method_exists = zend_hash_exists(&cur_method_ref->ce->function_table, lcname, cur_method_ref->mname_len + 1); efree(lcname); if (!method_exists) { zend_error(E_COMPILE_ERROR, "An alias was defined for %s::%s but this method does not exist", cur_method_ref->ce->name, cur_method_ref->method_name); } } i++; } } } /* }}} */ static void zend_traits_compile_exclude_table(HashTable* exclude_table, zend_trait_precedence **precedences, zend_class_entry *trait) /* {{{ */ { size_t i = 0, j; if (!precedences) { return; } while (precedences[i]) { if (precedences[i]->exclude_from_classes) { j = 0; while (precedences[i]->exclude_from_classes[j]) { if (precedences[i]->exclude_from_classes[j] == trait) { zend_uint lcname_len = precedences[i]->trait_method->mname_len; char *lcname = zend_str_tolower_dup(precedences[i]->trait_method->method_name, lcname_len); if (zend_hash_add(exclude_table, lcname, lcname_len, NULL, 0, NULL) == FAILURE) { efree(lcname); zend_error(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", precedences[i]->trait_method->method_name, trait->name); } efree(lcname); } ++j; } } ++i; } } /* }}} */ static void zend_do_traits_method_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { HashTable** function_tables; HashTable* resulting_table; HashTable exclude_table; size_t i; /* prepare copies of trait function tables for combination */ function_tables = malloc(sizeof(HashTable*) * ce->num_traits); resulting_table = (HashTable *) malloc(sizeof(HashTable)); /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(resulting_table, 10, NULL, NULL, 1, 0); for (i = 0; i < ce->num_traits; i++) { function_tables[i] = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(function_tables[i], ce->traits[i]->function_table.nNumOfElements, NULL, NULL, 1, 0); if (ce->trait_precedences) { /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(&exclude_table, 2, NULL, NULL, 0, 0); zend_traits_compile_exclude_table(&exclude_table, ce->trait_precedences, ce->traits[i]); /* copies functions, applies defined aliasing, and excludes unused trait methods */ zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, &exclude_table TSRMLS_CC); zend_hash_graceful_destroy(&exclude_table); } else { zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, NULL TSRMLS_CC); } } /* now merge trait methods */ for (i = 0; i < ce->num_traits; i++) { zend_hash_apply_with_arguments(function_tables[i] TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions, 5, i, ce->num_traits, resulting_table, function_tables, ce); } /* Now the resulting_table contains all trait methods we would have to * add to the class in the following step the methods are inserted into the method table * if there is already a method with the same name it is replaced iff ce != fn.scope * --> all inherited methods are overridden, methods defined in the class are left untouched */ zend_hash_apply_with_arguments(resulting_table TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions_to_class, 1, ce); /* free temporary function tables */ for (i = 0; i < ce->num_traits; i++) { /* zend_hash_destroy(function_tables[i]); */ zend_hash_graceful_destroy(function_tables[i]); free(function_tables[i]); } free(function_tables); /* free temporary resulting table */ /* zend_hash_destroy(resulting_table); */ zend_hash_graceful_destroy(resulting_table); free(resulting_table); } /* }}} */ static zend_class_entry* find_first_definition(zend_class_entry *ce, size_t current_trait, const char* prop_name, int prop_name_length, ulong prop_hash, zend_class_entry *coliding_ce) /* {{{ */ { size_t i; zend_property_info *coliding_prop; for (i = 0; (i < current_trait) && (i < ce->num_traits); i++) { if (zend_hash_quick_find(&ce->traits[i]->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS) { return ce->traits[i]; } } return coliding_ce; } /* }}} */ static void zend_do_traits_property_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i; zend_property_info *property_info; zend_property_info *coliding_prop; zval compare_result; const char* prop_name; int prop_name_length; ulong prop_hash; const char* class_name_unused; zend_bool prop_found; zend_bool not_compatible; zval* prop_value; /* In the following steps the properties are inserted into the property table * for that, a very strict approach is applied: * - check for compatibility, if not compatible with any property in class -> fatal * - if compatible, then strict notice */ for (i = 0; i < ce->num_traits; i++) { for (zend_hash_internal_pointer_reset(&ce->traits[i]->properties_info); zend_hash_get_current_data(&ce->traits[i]->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->traits[i]->properties_info)) { /* first get the unmangeld name if necessary, * then check whether the property is already there */ if ((property_info->flags & ZEND_ACC_PPP_MASK) == ZEND_ACC_PUBLIC) { prop_hash = property_info->h; prop_name = property_info->name; prop_name_length = property_info->name_length; prop_found = zend_hash_quick_find(&ce->properties_info, property_info->name, property_info->name_length+1, property_info->h, (void **) &coliding_prop) == SUCCESS; } else { /* for private and protected we need to unmangle the names */ zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name_unused, &prop_name); prop_name_length = strlen(prop_name); prop_hash = zend_get_hash_value(prop_name, prop_name_length + 1); prop_found = zend_hash_quick_find(&ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS; } /* next: check for conflicts with current class */ if (prop_found) { if (coliding_prop->flags & ZEND_ACC_SHADOW) { /* this one is inherited, lets look it up in its own class */ zend_hash_quick_find(&coliding_prop->ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop); } if ( (coliding_prop->flags & (ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC)) == (property_info->flags & (ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC))) { /* flags are identical, now the value needs to be checked */ if (property_info->flags & ZEND_ACC_STATIC) { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_static_members_table[coliding_prop->offset], ce->traits[i]->default_static_members_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } else { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_properties_table[coliding_prop->offset], ce->traits[i]->default_properties_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } } else { /* the flags are not identical, thus, we assume properties are not compatible */ not_compatible = 1; } if (not_compatible) { zend_error(E_COMPILE_ERROR, "%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } else { zend_error(E_STRICT, "%s and %s define the same property ($%s) in the composition of %s. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } } /* property not found, so lets add it */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); zend_declare_property_ex(ce, prop_name, prop_name_length, prop_value, property_info->flags, property_info->doc_comment, property_info->doc_comment_len TSRMLS_CC); } } } /* }}} */ static void zend_do_check_for_inconsistent_traits_aliasing(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { int i = 0; zend_trait_alias* cur_alias; char* lc_method_name; if (ce->trait_aliases) { while (ce->trait_aliases[i]) { cur_alias = ce->trait_aliases[i]; /** The trait for this alias has not been resolved, this means, this alias was not applied. Abort with an error. */ if (!cur_alias->trait_method->ce) { if (cur_alias->alias) { /** Plain old inconsistency/typo/bug */ zend_error(E_COMPILE_ERROR, "An alias (%s) was defined for method %s(), but this method does not exist", cur_alias->alias, cur_alias->trait_method->method_name); } else { /** Here are two possible cases: 1) this is an attempt to modifiy the visibility of a method introduce as part of another alias. Since that seems to violate the DRY principle, we check against it and abort. 2) it is just a plain old inconsitency/typo/bug as in the case where alias is set. */ lc_method_name = zend_str_tolower_dup(cur_alias->trait_method->method_name, cur_alias->trait_method->mname_len); if (zend_hash_exists(&ce->function_table, lc_method_name, cur_alias->trait_method->mname_len+1)) { efree(lc_method_name); zend_error(E_COMPILE_ERROR, "The modifiers for the trait alias %s() need to be changed in the same statment in which the alias is defined. Error", cur_alias->trait_method->method_name); } else { efree(lc_method_name); zend_error(E_COMPILE_ERROR, "The modifiers of the trait method %s() are changed, but this method does not exist. Error", cur_alias->trait_method->method_name); } } } i++; } } } /* }}} */ ZEND_API void zend_do_bind_traits(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { if (ce->num_traits <= 0) { return; } /* complete initialization of trait strutures in ce */ zend_traits_init_trait_structures(ce TSRMLS_CC); /* first care about all methods to be flattened into the class */ zend_do_traits_method_binding(ce TSRMLS_CC); /* Aliases which have not been applied indicate typos/bugs. */ zend_do_check_for_inconsistent_traits_aliasing(ce TSRMLS_CC); /* then flatten the properties into it, to, mostly to notfiy developer about problems */ zend_do_traits_property_binding(ce TSRMLS_CC); /* verify that all abstract methods from traits have been implemented */ zend_verify_abstract_class(ce TSRMLS_CC); /* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */ if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { ce->ce_flags -= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } } /* }}} */ ZEND_API int do_bind_function(const zend_op_array *op_array, zend_op *opline, HashTable *function_table, zend_bool compile_time) /* {{{ */ { zend_function *function; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } zend_hash_quick_find(function_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void *) &function); if (zend_hash_quick_add(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), function, sizeof(zend_function), NULL)==FAILURE) { int error_level = compile_time ? E_COMPILE_ERROR : E_ERROR; zend_function *old_function; if (zend_hash_quick_find(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), (void *) &old_function)==SUCCESS && old_function->type == ZEND_USER_FUNCTION && old_function->op_array.last > 0) { zend_error(error_level, "Cannot redeclare %s() (previously declared in %s:%d)", function->common.function_name, old_function->op_array.filename, old_function->op_array.opcodes[0].lineno); } else { zend_error(error_level, "Cannot redeclare %s()", function->common.function_name); } return FAILURE; } else { (*function->op_array.refcount)++; function->op_array.static_variables = NULL; /* NULL out the unbound function */ return SUCCESS; } } /* }}} */ void zend_add_trait_precedence(znode *precedence_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_precedences, precedence_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_add_trait_alias(znode *alias_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_aliases, alias_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_prepare_reference(znode *result, znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { zend_trait_method_reference *method_ref = emalloc(sizeof(zend_trait_method_reference)); method_ref->ce = NULL; /* REM: There should not be a need for copying, zend_do_begin_class_declaration is also just using that string */ if (class_name) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); method_ref->class_name = Z_STRVAL(class_name->u.constant); method_ref->cname_len = Z_STRLEN(class_name->u.constant); } else { method_ref->class_name = NULL; method_ref->cname_len = 0; } method_ref->method_name = Z_STRVAL(method_name->u.constant); method_ref->mname_len = Z_STRLEN(method_name->u.constant); result->u.op.ptr = method_ref; result->op_type = IS_TMP_VAR; } /* }}} */ void zend_prepare_trait_alias(znode *result, znode *method_reference, znode *modifiers, znode *alias TSRMLS_DC) /* {{{ */ { zend_trait_alias *trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_alias->modifiers = Z_LVAL(modifiers->u.constant); if (Z_LVAL(modifiers->u.constant) == ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot use 'static' as method modifier"); return; } if (alias) { trait_alias->alias = Z_STRVAL(alias->u.constant); trait_alias->alias_len = Z_STRLEN(alias->u.constant); } else { trait_alias->alias = NULL; } trait_alias->function = NULL; result->u.op.ptr = trait_alias; } /* }}} */ void zend_prepare_trait_precedence(znode *result, znode *method_reference, znode *trait_list TSRMLS_DC) /* {{{ */ { zend_trait_precedence *trait_precedence = emalloc(sizeof(zend_trait_precedence)); trait_precedence->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_precedence->exclude_from_classes = (zend_class_entry**) trait_list->u.op.ptr; trait_precedence->function = NULL; result->u.op.ptr = trait_precedence; } /* }}} */ ZEND_API zend_class_entry *do_bind_class(const zend_op_array* op_array, const zend_op *opline, HashTable *class_table, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } if (zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce)==FAILURE) { zend_error(E_COMPILE_ERROR, "Internal Zend error - Missing class information for %s", Z_STRVAL_P(op1)); return NULL; } else { ce = *pce; } ce->refcount++; if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), &ce, sizeof(zend_class_entry *), NULL)==FAILURE) { ce->refcount--; if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return NULL; } else { if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLEMENT_INTERFACES))) { zend_verify_abstract_class(ce TSRMLS_CC); } return ce; } } /* }}} */ ZEND_API zend_class_entry *do_bind_inherited_class(const zend_op_array *op_array, const zend_op *opline, HashTable *class_table, zend_class_entry *parent_ce, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; int found_ce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } found_ce = zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce); if (found_ce == FAILURE) { if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", Z_STRVAL_P(op2)); } return NULL; } else { ce = *pce; } if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ce->name, parent_ce->name); } else if ((parent_ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ce->name, parent_ce->name); } zend_do_inheritance(ce, parent_ce TSRMLS_CC); ce->refcount++; /* Register the derived class */ if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), pce, sizeof(zend_class_entry *), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return ce; } /* }}} */ void zend_do_early_binding(TSRMLS_D) /* {{{ */ { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; HashTable *table; while (opline->opcode == ZEND_TICKS && opline > CG(active_op_array)->opcodes) { opline--; } switch (opline->opcode) { case ZEND_DECLARE_FUNCTION: if (do_bind_function(CG(active_op_array), opline, CG(function_table), 1) == FAILURE) { return; } table = CG(function_table); break; case ZEND_DECLARE_CLASS: if (do_bind_class(CG(active_op_array), opline, CG(class_table), 1 TSRMLS_CC) == NULL) { return; } table = CG(class_table); break; case ZEND_DECLARE_INHERITED_CLASS: { zend_op *fetch_class_opline = opline-1; zval *parent_name; zend_class_entry **pce; parent_name = &CONSTANT(fetch_class_opline->op2.constant); if ((zend_lookup_class(Z_STRVAL_P(parent_name), Z_STRLEN_P(parent_name), &pce TSRMLS_CC) == FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_CLASSES) && ((*pce)->type == ZEND_INTERNAL_CLASS))) { if (CG(compiler_options) & ZEND_COMPILE_DELAYED_BINDING) { zend_uint *opline_num = &CG(active_op_array)->early_binding; while (*opline_num != -1) { opline_num = &CG(active_op_array)->opcodes[*opline_num].result.opline_num; } *opline_num = opline - CG(active_op_array)->opcodes; opline->opcode = ZEND_DECLARE_INHERITED_CLASS_DELAYED; opline->result_type = IS_UNUSED; opline->result.opline_num = -1; } return; } if (do_bind_inherited_class(CG(active_op_array), opline, CG(class_table), *pce, 1 TSRMLS_CC) == NULL) { return; } /* clear unnecessary ZEND_FETCH_CLASS opcode */ zend_del_literal(CG(active_op_array), fetch_class_opline->op2.constant); MAKE_NOP(fetch_class_opline); table = CG(class_table); break; } case ZEND_VERIFY_ABSTRACT_CLASS: case ZEND_ADD_INTERFACE: case ZEND_ADD_TRAIT: case ZEND_BIND_TRAITS: /* We currently don't early-bind classes that implement interfaces */ /* Classes with traits are handled exactly the same, no early-bind here */ return; default: zend_error(E_COMPILE_ERROR, "Invalid binding type"); return; } zend_hash_quick_del(table, Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant)), Z_HASH_P(&CONSTANT(opline->op1.constant))); zend_del_literal(CG(active_op_array), opline->op1.constant); zend_del_literal(CG(active_op_array), opline->op2.constant); MAKE_NOP(opline); } /* }}} */ ZEND_API void zend_do_delayed_early_binding(const zend_op_array *op_array TSRMLS_DC) /* {{{ */ { if (op_array->early_binding != -1) { zend_bool orig_in_compilation = CG(in_compilation); zend_uint opline_num = op_array->early_binding; zend_class_entry **pce; CG(in_compilation) = 1; while (opline_num != -1) { if (zend_lookup_class(Z_STRVAL_P(op_array->opcodes[opline_num-1].op2.zv), Z_STRLEN_P(op_array->opcodes[opline_num-1].op2.zv), &pce TSRMLS_CC) == SUCCESS) { do_bind_inherited_class(op_array, &op_array->opcodes[opline_num], EG(class_table), *pce, 0 TSRMLS_CC); } opline_num = op_array->opcodes[opline_num].result.opline_num; } CG(in_compilation) = orig_in_compilation; } } /* }}} */ void zend_do_boolean_or_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_or_end(znode *result, const znode *expr1, const znode *expr2, znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_boolean_and_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_and_end(znode *result, const znode *expr1, const znode *expr2, const znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_do_while_begin(TSRMLS_D) /* {{{ */ { do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_do_while_end(const znode *do_token, const znode *expr_open_bracket, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ; SET_NODE(opline->op1, expr); opline->op2.opline_num = do_token->u.op.opline_num; SET_UNUSED(opline->op2); do_end_loop(expr_open_bracket->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_brk_cont(zend_uchar op, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->op1.opline_num = CG(context).current_brk_cont; SET_UNUSED(opline->op1); if (expr) { if (expr->op_type != IS_CONST) { zend_error(E_COMPILE_ERROR, "'%s' operator with non-constant operand is no longer supported", op == ZEND_BRK ? "break" : "continue"); } else if (Z_TYPE(expr->u.constant) != IS_LONG || Z_LVAL(expr->u.constant) < 1) { zend_error(E_COMPILE_ERROR, "'%s' operator accepts only positive numbers", op == ZEND_BRK ? "break" : "continue"); } SET_NODE(opline->op2, expr); } else { LITERAL_LONG(opline->op2, 1); opline->op2_type = IS_CONST; } } /* }}} */ void zend_do_switch_cond(const znode *cond TSRMLS_DC) /* {{{ */ { zend_switch_entry switch_entry; switch_entry.cond = *cond; switch_entry.default_case = -1; switch_entry.control_var = -1; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_switch_end(const znode *case_list TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); /* add code to jmp to default case */ if (switch_entry_ptr->default_case != -1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->op1.opline_num = switch_entry_ptr->default_case; } if (case_list->op_type != IS_UNUSED) { /* non-empty switch */ int next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* remember break/continue loop information */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; if (switch_entry_ptr->cond.op_type==IS_VAR || switch_entry_ptr->cond.op_type==IS_TMP_VAR) { /* emit free for the switch condition*/ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry_ptr->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_UNUSED(opline->op2); } if (switch_entry_ptr->cond.op_type == IS_CONST) { zval_dtor(&switch_entry_ptr->cond.u.constant); } zend_stack_del_top(&CG(switch_cond_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_case_before_statement(const znode *case_list, znode *case_token, const znode *case_expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); int next_op_number; zend_switch_entry *switch_entry_ptr; znode result; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); if (switch_entry_ptr->control_var == -1) { switch_entry_ptr->control_var = get_temporary_variable(CG(active_op_array)); } opline->opcode = ZEND_CASE; opline->result.var = switch_entry_ptr->control_var; opline->result_type = IS_TMP_VAR; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_NODE(opline->op2, case_expr); if (opline->op1_type == IS_CONST) { zval_copy_ctor(&CONSTANT(opline->op1.constant)); } GET_NODE(&result, opline->result); next_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, &result); SET_UNUSED(opline->op2); case_token->u.op.opline_num = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_case_after_statement(znode *result, const znode *case_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); result->u.op.opline_num = next_op_number; switch (CG(active_op_array)->opcodes[case_token->u.op.opline_num].opcode) { case ZEND_JMP: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); break; case ZEND_JMPZ: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); break; } } /* }}} */ void zend_do_default_before_statement(const znode *case_list, znode *default_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); default_token->u.op.opline_num = next_op_number; next_op_number = get_next_op_number(CG(active_op_array)); switch_entry_ptr->default_case = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_begin_class_declaration(const znode *class_token, znode *class_name, const znode *parent_class_name TSRMLS_DC) /* {{{ */ { zend_op *opline; int doing_inheritance = 0; zend_class_entry *new_class_entry; char *lcname; int error = 0; zval **ns_name, key; if (CG(active_class_entry)) { zend_error(E_COMPILE_ERROR, "Class declarations may not be nested"); return; } lcname = zend_str_tolower_dup(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); if (!(strcmp(lcname, "self") && strcmp(lcname, "parent"))) { efree(lcname); zend_error(E_COMPILE_ERROR, "Cannot use '%s' as class name as it is reserved", Z_STRVAL(class_name->u.constant)); } /* Class name must not conflict with import names */ if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns_name) == SUCCESS) { error = 1; } if (CG(current_namespace)) { /* Prefix class name with name of current namespace */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); class_name = &tmp; efree(lcname); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); } if (error) { char *tmp = zend_str_tolower_dup(Z_STRVAL_PP(ns_name), Z_STRLEN_PP(ns_name)); if (Z_STRLEN_PP(ns_name) != Z_STRLEN(class_name->u.constant) || memcmp(tmp, lcname, Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "Cannot declare class %s because the name is already in use", Z_STRVAL(class_name->u.constant)); } efree(tmp); } new_class_entry = emalloc(sizeof(zend_class_entry)); new_class_entry->type = ZEND_USER_CLASS; new_class_entry->name = zend_new_interned_string(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1, 1 TSRMLS_CC); new_class_entry->name_length = Z_STRLEN(class_name->u.constant); zend_initialize_class_data(new_class_entry, 1 TSRMLS_CC); new_class_entry->info.user.filename = zend_get_compiled_filename(TSRMLS_C); new_class_entry->info.user.line_start = class_token->u.op.opline_num; new_class_entry->ce_flags |= class_token->EA; if (parent_class_name && parent_class_name->op_type != IS_UNUSED) { switch (parent_class_name->EA) { case ZEND_FETCH_CLASS_SELF: zend_error(E_COMPILE_ERROR, "Cannot use 'self' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_PARENT: zend_error(E_COMPILE_ERROR, "Cannot use 'parent' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use 'static' as class name as it is reserved"); break; default: break; } doing_inheritance = 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, new_class_entry->name_length TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; if (doing_inheritance) { /* Make sure a trait does not try to extend a class */ if ((new_class_entry->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "A trait (%s) cannot extend a class", new_class_entry->name); } opline->extended_value = parent_class_name->u.op.var; opline->opcode = ZEND_DECLARE_INHERITED_CLASS; } else { opline->opcode = ZEND_DECLARE_CLASS; } LITERAL_STRINGL(opline->op2, lcname, new_class_entry->name_length, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); zend_hash_quick_update(CG(class_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &new_class_entry, sizeof(zend_class_entry *), NULL); CG(active_class_entry) = new_class_entry; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(&CG(implementing_class), opline->result); if (CG(doc_comment)) { CG(active_class_entry)->info.user.doc_comment = CG(doc_comment); CG(active_class_entry)->info.user.doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ static void do_verify_abstract_class(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_VERIFY_ABSTRACT_CLASS; SET_NODE(opline->op1, &CG(implementing_class)); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_class_declaration(const znode *class_token, const znode *parent_token TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); if (ce->constructor) { ce->constructor->common.fn_flags |= ZEND_ACC_CTOR; if (ce->constructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Constructor %s::%s() cannot be static", ce->name, ce->constructor->common.function_name); } } if (ce->destructor) { ce->destructor->common.fn_flags |= ZEND_ACC_DTOR; if (ce->destructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Destructor %s::%s() cannot be static", ce->name, ce->destructor->common.function_name); } } if (ce->clone) { ce->clone->common.fn_flags |= ZEND_ACC_CLONE; if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static", ce->name, ce->clone->common.function_name); } } ce->info.user.line_end = zend_get_compiled_lineno(TSRMLS_C); /* Check for traits and proceed like with interfaces. * The only difference will be a combined handling of them in the end. * Thus, we need another opcode here. */ if (ce->num_traits > 0) { zend_op *opline; ce->traits = NULL; ce->num_traits = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_TRAITS; /* opcode generation: */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BIND_TRAITS; SET_NODE(opline->op1, &CG(implementing_class)); } if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) && ((parent_token->op_type != IS_UNUSED) || (ce->num_interfaces > 0))) { zend_verify_abstract_class(ce TSRMLS_CC); if (ce->num_interfaces) { do_verify_abstract_class(TSRMLS_C); } } /* Inherit interfaces; reset number to zero, we need it for above check and * will restore it during actual implementation. * The ZEND_ACC_IMPLEMENT_INTERFACES flag disables double call to * zend_verify_abstract_class() */ if (ce->num_interfaces > 0) { ce->interfaces = NULL; ce->num_interfaces = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_INTERFACES; } CG(active_class_entry) = NULL; } /* }}} */ void zend_do_implements_interface(znode *interface_name TSRMLS_DC) /* {{{ */ { zend_op *opline; /* Traits can not implement interfaces */ if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface on '%s' since it is a Trait", Z_STRVAL(interface_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(interface_name->u.constant), Z_STRLEN(interface_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface name as it is reserved", Z_STRVAL(interface_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_INTERFACE; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(interface_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = (opline->extended_value & ~ZEND_FETCH_CLASS_MASK) | ZEND_FETCH_CLASS_INTERFACE; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &interface_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_interfaces++; } /* }}} */ void zend_do_implements_trait(znode *trait_name TSRMLS_DC) /* {{{ */ { zend_op *opline; if ((CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Cannot use traits inside of interfaces. %s is used in %s", Z_STRVAL(trait_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(trait_name->u.constant), Z_STRLEN(trait_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as trait name as it is reserved", Z_STRVAL(trait_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_TRAIT; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(trait_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = ZEND_FETCH_CLASS_TRAIT; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &trait_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_traits++; } /* }}} */ ZEND_API void zend_mangle_property_name(char **dest, int *dest_length, const char *src1, int src1_length, const char *src2, int src2_length, int internal) /* {{{ */ { char *prop_name; int prop_name_length; prop_name_length = 1 + src1_length + 1 + src2_length; prop_name = pemalloc(prop_name_length + 1, internal); prop_name[0] = '\0'; memcpy(prop_name + 1, src1, src1_length+1); memcpy(prop_name + 1 + src1_length + 1, src2, src2_length+1); *dest = prop_name; *dest_length = prop_name_length; } /* }}} */ static int zend_strnlen(const char* s, int maxlen) /* {{{ */ { int len = 0; while (*s++ && maxlen--) len++; return len; } /* }}} */ ZEND_API int zend_unmangle_property_name(const char *mangled_property, int len, const char **class_name, const char **prop_name) /* {{{ */ { int class_name_len; *class_name = NULL; if (mangled_property[0]!=0) { *prop_name = mangled_property; return SUCCESS; } if (len < 3 || mangled_property[1]==0) { zend_error(E_NOTICE, "Illegal member variable name"); *prop_name = mangled_property; return FAILURE; } class_name_len = zend_strnlen(mangled_property+1, --len - 1) + 1; if (class_name_len >= len || mangled_property[class_name_len]!=0) { zend_error(E_NOTICE, "Corrupt member variable name"); *prop_name = mangled_property; return FAILURE; } *class_name = mangled_property+1; *prop_name = (*class_name)+class_name_len; return SUCCESS; } /* }}} */ void zend_do_declare_property(const znode *var_name, const znode *value, zend_uint access_type TSRMLS_DC) /* {{{ */ { zval *property; zend_property_info *existing_property_info; char *comment = NULL; int comment_len = 0; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Interfaces may not include member variables"); } if (access_type & ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Properties cannot be declared abstract"); } if (access_type & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot declare property %s::$%s final, the final modifier is allowed only for methods and classes", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } if (zend_hash_find(&CG(active_class_entry)->properties_info, var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, (void **) &existing_property_info)==SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::$%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } ALLOC_ZVAL(property); if (value) { *property = value->u.constant; } else { INIT_PZVAL(property); Z_TYPE_P(property) = IS_NULL; } if (CG(doc_comment)) { comment = CG(doc_comment); comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } zend_declare_property_ex(CG(active_class_entry), zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len + 1, 0 TSRMLS_CC), var_name->u.constant.value.str.len, property, access_type, comment, comment_len TSRMLS_CC); efree(var_name->u.constant.value.str.val); } /* }}} */ void zend_do_declare_class_constant(znode *var_name, const znode *value TSRMLS_DC) /* {{{ */ { zval *property; const char *cname = NULL; int result; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed in class constants"); return; } if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Traits cannot have constants"); return; } ALLOC_ZVAL(property); *property = value->u.constant; cname = zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, 0 TSRMLS_CC); if (IS_INTERNED(cname)) { result = zend_hash_quick_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, INTERNED_HASH(cname), &property, sizeof(zval *), NULL); } else { result = zend_hash_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, &property, sizeof(zval *), NULL); } if (result == FAILURE) { FREE_ZVAL(property); zend_error(E_COMPILE_ERROR, "Cannot redefine class constant %s::%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } FREE_PNODE(var_name); if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_fetch_property(znode *result, znode *object, const znode *property TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (object->op_type == IS_CV) { if (object->u.op.var == CG(active_op_array)->this_var) { object->op_type = IS_UNUSED; /* this means $this for objects */ } } else if (fetch_list_ptr->count == 1) { zend_llist_element *le = fetch_list_ptr->head; zend_op *opline_ptr = (zend_op *) le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); SET_UNUSED(opline_ptr->op1); /* this means $this for objects */ SET_NODE(opline_ptr->op2, property); /* if it was usual fetch, we change it to object fetch */ switch (opline_ptr->opcode) { case ZEND_FETCH_W: opline_ptr->opcode = ZEND_FETCH_OBJ_W; break; case ZEND_FETCH_R: opline_ptr->opcode = ZEND_FETCH_OBJ_R; break; case ZEND_FETCH_RW: opline_ptr->opcode = ZEND_FETCH_OBJ_RW; break; case ZEND_FETCH_IS: opline_ptr->opcode = ZEND_FETCH_OBJ_IS; break; case ZEND_FETCH_UNSET: opline_ptr->opcode = ZEND_FETCH_OBJ_UNSET; break; case ZEND_FETCH_FUNC_ARG: opline_ptr->opcode = ZEND_FETCH_OBJ_FUNC_ARG; break; } if (opline_ptr->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline_ptr->op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline_ptr->op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op2.constant); } GET_NODE(result, opline_ptr->result); return; } } if (zend_is_function_or_method_call(object)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, object); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_OBJ_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, object); SET_NODE(opline.op2, property); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline.op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op2.constant); } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void zend_do_halt_compiler_register(TSRMLS_D) /* {{{ */ { char *name, *cfilename; char haltoff[] = "__COMPILER_HALT_OFFSET__"; int len, clen; if (CG(has_bracketed_namespaces) && CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "__HALT_COMPILER() can only be used from the outermost scope"); } cfilename = zend_get_compiled_filename(TSRMLS_C); clen = strlen(cfilename); zend_mangle_property_name(&name, &len, haltoff, sizeof(haltoff) - 1, cfilename, clen, 0); zend_register_long_constant(name, len+1, zend_get_scanned_file_offset(TSRMLS_C), CONST_CS, 0 TSRMLS_CC); pefree(name, 0); if (CG(in_namespace)) { zend_do_end_namespace(TSRMLS_C); } } /* }}} */ void zend_do_push_object(const znode *object TSRMLS_DC) /* {{{ */ { zend_stack_push(&CG(object_stack), object, sizeof(znode)); } /* }}} */ void zend_do_pop_object(znode *object TSRMLS_DC) /* {{{ */ { if (object) { znode *tmp; zend_stack_top(&CG(object_stack), (void **) &tmp); *object = *tmp; } zend_stack_del_top(&CG(object_stack)); } /* }}} */ void zend_do_begin_new_object(znode *new_token, znode *class_type TSRMLS_DC) /* {{{ */ { zend_op *opline; unsigned char *ptr = NULL; new_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_NEW; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, class_type); SET_UNUSED(opline->op2); zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(unsigned char *)); } /* }}} */ void zend_do_end_new_object(znode *result, const znode *new_token, const znode *argument_list TSRMLS_DC) /* {{{ */ { znode ctor_result; zend_do_end_function_call(NULL, &ctor_result, argument_list, 1, 0 TSRMLS_CC); zend_do_free(&ctor_result TSRMLS_CC); CG(active_op_array)->opcodes[new_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, CG(active_op_array)->opcodes[new_token->u.op.opline_num].result); } /* }}} */ static zend_constant* zend_get_ct_const(const zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = NULL; if (Z_STRVAL_P(const_name)[0] == '\\') { if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name), (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name)-1); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name), (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } } else if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)+1, (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name)+1, (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } if (c->flags & CONST_CT_SUBST) { return c; } if (all_internal_constants_substitution && (c->flags & CONST_PERSISTENT) && !(CG(compiler_options) & ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION) && Z_TYPE(c->value) != IS_CONSTANT && Z_TYPE(c->value) != IS_CONSTANT_ARRAY) { return c; } return NULL; } /* }}} */ static int zend_constant_ct_subst(znode *result, zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = zend_get_ct_const(const_name, all_internal_constants_substitution TSRMLS_CC); if (c) { zval_dtor(const_name); result->op_type = IS_CONST; result->u.constant = c->value; zval_copy_ctor(&result->u.constant); INIT_PZVAL(&result->u.constant); return 1; } return 0; } /* }}} */ void zend_do_fetch_constant(znode *result, znode *constant_container, znode *constant_name, int mode, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; zend_op *opline; int type; char *compound; ulong fetch_type = 0; if (constant_container) { switch (mode) { case ZEND_CT: /* this is a class constant */ type = zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant)); if (ZEND_FETCH_CLASS_STATIC == type) { zend_error(E_ERROR, "\"static::\" is not allowed in compile-time constants"); } else if (ZEND_FETCH_CLASS_DEFAULT == type) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } zend_do_build_full_name(NULL, constant_container, constant_name, 1 TSRMLS_CC); *result = *constant_container; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: if (constant_container->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant))) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } else { zend_do_fetch_class(&tmp, constant_container TSRMLS_CC); constant_container = &tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); if (constant_container->op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &constant_container->u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, constant_container); } SET_NODE(opline->op2, constant_name); CALCULATE_LITERAL_HASH(opline->op2.constant); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } GET_NODE(result, opline->result); break; } return; } /* namespace constant */ /* only one that did not contain \ from the start can be converted to string if unknown */ switch (mode) { case ZEND_CT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); /* this is a namespace constant, or an unprefixed constant */ if (zend_constant_ct_subst(result, &constant_name->u.constant, 0 TSRMLS_CC)) { break; } zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(!compound) { fetch_type |= IS_CONSTANT_UNQUALIFIED; } *result = *constant_name; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(zend_constant_ct_subst(result, &constant_name->u.constant, 1 TSRMLS_CC)) { break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; if (compound) { /* the name is unambiguous */ opline->extended_value = 0; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } else { opline->extended_value = IS_CONSTANT_UNQUALIFIED; if (CG(current_namespace)) { opline->extended_value |= IS_CONSTANT_IN_NAMESPACE; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 1 TSRMLS_CC); } else { opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } } GET_CACHE_SLOT(opline->op2.constant); break; } } /* }}} */ void zend_do_shell_exec(znode *result, const znode *cmd TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); switch (cmd->op_type) { case IS_CONST: case IS_TMP_VAR: opline->opcode = ZEND_SEND_VAL; break; default: opline->opcode = ZEND_SEND_VAR; break; } SET_NODE(opline->op1, cmd); opline->op2.opline_num = 0; opline->extended_value = ZEND_DO_FCALL; SET_UNUSED(opline->op2); /* FIXME: exception support not added to this op2 */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DO_FCALL; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; LITERAL_STRINGL(opline->op1, estrndup("shell_exec", sizeof("shell_exec")-1), sizeof("shell_exec")-1, 0); CALCULATE_LITERAL_HASH(opline->op1.constant); opline->op1_type = IS_CONST; GET_CACHE_SLOT(opline->op1.constant); opline->extended_value = 1; SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_init_array(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_ARRAY; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; GET_NODE(result, opline->result); if (expr) { SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } } else { SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_array_element(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_ARRAY_ELEMENT; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_static_array_element(znode *result, znode *offset, const znode *expr) /* {{{ */ { zval *element; ALLOC_ZVAL(element); *element = expr->u.constant; if (offset) { switch (offset->u.constant.type & IS_CONSTANT_TYPE_MASK) { case IS_CONSTANT: /* Ugly hack to denote that this value has a constant index */ Z_TYPE_P(element) |= IS_CONSTANT_INDEX; Z_STRVAL(offset->u.constant) = erealloc(Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+1] = Z_TYPE(offset->u.constant); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+2] = 0; zend_symtable_update(result->u.constant.value.ht, Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_STRING: zend_symtable_update(result->u.constant.value.ht, offset->u.constant.value.str.val, offset->u.constant.value.str.len+1, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_NULL: zend_symtable_update(Z_ARRVAL(result->u.constant), "", 1, &element, sizeof(zval *), NULL); break; case IS_LONG: case IS_BOOL: zend_hash_index_update(Z_ARRVAL(result->u.constant), Z_LVAL(offset->u.constant), &element, sizeof(zval *), NULL); break; case IS_DOUBLE: zend_hash_index_update(Z_ARRVAL(result->u.constant), zend_dval_to_lval(Z_DVAL(offset->u.constant)), &element, sizeof(zval *), NULL); break; case IS_CONSTANT_ARRAY: zend_error(E_ERROR, "Illegal offset type"); break; } } else { zend_hash_next_index_insert(Z_ARRVAL(result->u.constant), &element, sizeof(zval *), NULL); } } /* }}} */ void zend_do_add_list_element(const znode *element TSRMLS_DC) /* {{{ */ { list_llist_element lle; if (element) { zend_check_writable_variable(element); lle.var = *element; zend_llist_copy(&lle.dimensions, &CG(dimension_llist)); zend_llist_prepend_element(&CG(list_llist), &lle); } (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_new_list_begin(TSRMLS_D) /* {{{ */ { int current_dimension = 0; zend_llist_add_element(&CG(dimension_llist), &current_dimension); } /* }}} */ void zend_do_new_list_end(TSRMLS_D) /* {{{ */ { zend_llist_remove_tail(&CG(dimension_llist)); (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_list_init(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(list_stack), &CG(list_llist), sizeof(zend_llist)); zend_stack_push(&CG(list_stack), &CG(dimension_llist), sizeof(zend_llist)); zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_do_new_list_begin(TSRMLS_C); } /* }}} */ void zend_do_list_end(znode *result, znode *expr TSRMLS_DC) /* {{{ */ { zend_llist_element *le; zend_llist_element *dimension; zend_op *opline; znode last_container; le = CG(list_llist).head; while (le) { zend_llist *tmp_dimension_llist = &((list_llist_element *)le->data)->dimensions; dimension = tmp_dimension_llist->head; while (dimension) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (dimension == tmp_dimension_llist->head) { /* first */ last_container = *expr; switch (expr->op_type) { case IS_VAR: case IS_CV: opline->opcode = ZEND_FETCH_DIM_R; break; case IS_TMP_VAR: opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; case IS_CONST: /* fetch_dim_tmp_var will handle this bogus fetch */ zval_copy_ctor(&expr->u.constant); opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; } opline->extended_value |= ZEND_FETCH_ADD_LOCK; } else { opline->opcode = ZEND_FETCH_DIM_R; } opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, &last_container); opline->op2_type = IS_CONST; LITERAL_LONG(opline->op2, *((int *) dimension->data)); GET_NODE(&last_container, opline->result); dimension = dimension->next; } ((list_llist_element *) le->data)->value = last_container; zend_llist_destroy(&((list_llist_element *) le->data)->dimensions); zend_do_assign(result, &((list_llist_element *) le->data)->var, &((list_llist_element *) le->data)->value TSRMLS_CC); zend_do_free(result TSRMLS_CC); le = le->next; } zend_llist_destroy(&CG(dimension_llist)); zend_llist_destroy(&CG(list_llist)); *result = *expr; { zend_llist *p; /* restore previous lists */ zend_stack_top(&CG(list_stack), (void **) &p); CG(dimension_llist) = *p; zend_stack_del_top(&CG(list_stack)); zend_stack_top(&CG(list_stack), (void **) &p); CG(list_llist) = *p; zend_stack_del_top(&CG(list_stack)); } } /* }}} */ void zend_init_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = emalloc(sizeof(void*) * 2); list[0] = item; list[1] = NULL; *(void**)result = list; } /* }}} */ void zend_add_to_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = *(void**)result; size_t n = 0; while (list && list[n]) { n++; } list = erealloc(list, sizeof(void*) * (n+2)); list[n] = item; list[n+1] = NULL; *(void**)result = list; } /* }}} */ void zend_do_fetch_static_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zval *tmp; zend_op *opline; znode lval; znode result; ALLOC_ZVAL(tmp); if (static_assignment) { *tmp = static_assignment->u.constant; } else { INIT_ZVAL(*tmp); } if (!CG(active_op_array)->static_variables) { if (CG(active_op_array)->scope) { CG(active_op_array)->scope->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } ALLOC_HASHTABLE(CG(active_op_array)->static_variables); zend_hash_init(CG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } zend_hash_update(CG(active_op_array)->static_variables, varname->u.constant.value.str.val, varname->u.constant.value.str.len+1, &tmp, sizeof(zval *), NULL); if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (fetch_type == ZEND_FETCH_LEXICAL) ? ZEND_FETCH_R : ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_STATIC; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ if (fetch_type == ZEND_FETCH_LEXICAL) { znode dummy; zend_do_begin_variable_parse(TSRMLS_C); zend_do_assign(&dummy, &lval, &result TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } else { zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); } CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_fetch_lexical_variable(znode *varname, zend_bool is_ref TSRMLS_DC) /* {{{ */ { znode value; if (Z_STRLEN(varname->u.constant) == sizeof("this") - 1 && memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this") - 1) == 0) { zend_error(E_COMPILE_ERROR, "Cannot use $this as lexical variable"); return; } value.op_type = IS_CONST; ZVAL_NULL(&value.u.constant); Z_TYPE(value.u.constant) |= is_ref ? IS_LEXICAL_REF : IS_LEXICAL_VAR; Z_SET_REFCOUNT_P(&value.u.constant, 1); Z_UNSET_ISREF_P(&value.u.constant); zend_do_fetch_static_variable(varname, &value, is_ref ? ZEND_FETCH_STATIC : ZEND_FETCH_LEXICAL TSRMLS_CC); } /* }}} */ void zend_do_fetch_global_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zend_op *opline; znode lval; znode result; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = fetch_type; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_cast(znode *result, const znode *expr, int type TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CAST; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } /* }}} */ void zend_do_include_or_eval(int type, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_do_extended_fcall_begin(TSRMLS_C); { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INCLUDE_OR_EVAL; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } zend_do_extended_fcall_end(TSRMLS_C); } /* }}} */ void zend_do_indirect_references(znode *result, const znode *num_references, znode *variable TSRMLS_DC) /* {{{ */ { int i; zend_do_end_variable_parse(variable, BP_VAR_R, 0 TSRMLS_CC); for (i=1; i<num_references->u.constant.value.lval; i++) { fetch_simple_variable_ex(result, variable, 0, ZEND_FETCH_R TSRMLS_CC); *variable = *result; } zend_do_begin_variable_parse(TSRMLS_C); fetch_simple_variable(result, variable, 1 TSRMLS_CC); /* there is a chance someone is accessing $this */ if (CG(active_op_array)->scope && CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } /* }}} */ void zend_do_unset(const znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_UNSET_VAR; SET_NODE(opline->op1, variable); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); opline->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_UNSET: last_op->opcode = ZEND_UNSET_VAR; SET_UNUSED(last_op->result); break; case ZEND_FETCH_DIM_UNSET: last_op->opcode = ZEND_UNSET_DIM; SET_UNUSED(last_op->result); break; case ZEND_FETCH_OBJ_UNSET: last_op->opcode = ZEND_UNSET_OBJ; SET_UNUSED(last_op->result); break; } } } /* }}} */ void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_do_end_variable_parse(variable, BP_VAR_IS, 0 TSRMLS_CC); zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { last_op = get_next_op(CG(active_op_array) TSRMLS_CC); last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; SET_NODE(last_op->op1, variable); SET_UNUSED(last_op->op2); last_op->result.var = get_temporary_variable(CG(active_op_array)); last_op->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; break; case ZEND_FETCH_DIM_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_DIM_OBJ; break; case ZEND_FETCH_OBJ_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_PROP_OBJ; break; } } last_op->result_type = IS_TMP_VAR; last_op->extended_value |= type; GET_NODE(result, last_op->result); } /* }}} */ void zend_do_instanceof(znode *result, const znode *expr, const znode *class_znode, int type TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline->opcode == ZEND_FETCH_CLASS) { opline->extended_value |= ZEND_FETCH_CLASS_NO_AUTOLOAD; } } if (expr->op_type == IS_CONST) { zend_error(E_COMPILE_ERROR, "instanceof expects an object instance, constant given"); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INSTANCEOF; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_NODE(opline->op2, class_znode); GET_NODE(result, opline->result); } /* }}} */ void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_bool is_variable; zend_bool push_container = 0; zend_op dummy_opline; if (variable) { if (zend_is_function_or_method_call(array)) { is_variable = 0; } else { is_variable = 1; } /* save the location of FETCH_W instruction(s) */ open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); zend_do_end_variable_parse(array, BP_VAR_W, 0 TSRMLS_CC); if (CG(active_op_array)->last > 0 && CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) { /* Only lock the container if we are fetching from a real container and not $this */ if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1_type == IS_VAR) { CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK; push_container = 1; } } } else { is_variable = 0; open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* save the location of FE_RESET */ foreach_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* Preform array reset */ opline->opcode = ZEND_FE_RESET; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, array); SET_UNUSED(opline->op2); opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0; COPY_NODE(dummy_opline.result, opline->result); if (push_container) { COPY_NODE(dummy_opline.op1, CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1); } else { dummy_opline.op1_type = IS_UNUSED; } zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); /* save the location of FE_FETCH */ as_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FE_FETCH; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); COPY_NODE(opline->op1, dummy_opline.result); opline->extended_value = 0; SET_UNUSED(opline->op2); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_OP_DATA; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); } /* }}} */ void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC) /* {{{ */ { zend_op *opline; znode dummy, value_node; zend_bool assign_by_ref=0; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num]; if (key->op_type != IS_UNUSED) { znode *tmp; /* switch between the key and value... */ tmp = key; key = value; value = tmp; /* Mark extended_value in case both key and value are being used */ opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; } if ((key->op_type != IS_UNUSED) && (key->EA & ZEND_PARSED_REFERENCE_VARIABLE)) { zend_error(E_COMPILE_ERROR, "Key element cannot be a reference"); } if (value->EA & ZEND_PARSED_REFERENCE_VARIABLE) { assign_by_ref = 1; if (!(opline-1)->extended_value) { zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression"); } /* Mark extended_value for assign-by-reference */ opline->extended_value |= ZEND_FE_FETCH_BYREF; CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; } else { zend_op *foreach_copy; zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.op.opline_num]; zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.op.opline_num]; /* Change "write context" into "read context" */ fetch->extended_value = 0; /* reset ZEND_FE_RESET_VARIABLE */ while (fetch != end) { --fetch; if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } if (fetch->opcode == ZEND_SEPARATE) { MAKE_NOP(fetch); } else { fetch->opcode -= 3; /* FETCH_W -> FETCH_R */ } } /* prevent double SWITCH_FREE */ zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy); foreach_copy->op1_type = IS_UNUSED; } GET_NODE(&value_node, opline->result); if (assign_by_ref) { zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); /* Mark FE_FETCH as IS_VAR as it holds the data directly as a value */ zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC); } else { zend_do_assign(&dummy, value, &value_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } if (key->op_type != IS_UNUSED) { znode key_node; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num+1]; opline->result_type = IS_TMP_VAR; opline->result.opline_num = get_temporary_variable(CG(active_op_array)); GET_NODE(&key_node, opline->result); zend_do_assign(&dummy, key, &key_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_foreach_end(const znode *foreach_token, const znode *as_token TSRMLS_DC) /* {{{ */ { zend_op *container_ptr; zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = as_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_RESET */ CG(active_op_array)->opcodes[as_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_FETCH */ do_end_loop(as_token->u.op.opline_num, 1 TSRMLS_CC); zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr); generate_free_foreach_copy(container_ptr TSRMLS_CC); zend_stack_del_top(&CG(foreach_copy_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_declare_begin(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(declare_stack), &CG(declarables), sizeof(zend_declarables)); } /* }}} */ void zend_do_declare_stmt(znode *var, znode *val TSRMLS_DC) /* {{{ */ { if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "ticks", sizeof("ticks")-1)) { convert_to_long(&val->u.constant); CG(declarables).ticks = val->u.constant; } else if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "encoding", sizeof("encoding")-1)) { if ((Z_TYPE(val->u.constant) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Cannot use constants as encoding"); } /* * Check that the pragma comes before any opcodes. If the compilation * got as far as this, the previous portion of the script must have been * parseable according to the .ini script_encoding setting. We still * want to tell them to put declare() at the top. */ { int num = CG(active_op_array)->last; /* ignore ZEND_EXT_STMT and ZEND_TICKS */ while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Encoding declaration pragma must be the very first statement in the script"); } } if (CG(multibyte)) { const zend_encoding *new_encoding, *old_encoding; zend_encoding_filter old_input_filter; CG(encoding_declared) = 1; convert_to_string(&val->u.constant); new_encoding = zend_multibyte_fetch_encoding(val->u.constant.value.str.val TSRMLS_CC); if (!new_encoding) { zend_error(E_COMPILE_WARNING, "Unsupported encoding [%s]", val->u.constant.value.str.val); } else { old_input_filter = LANG_SCNG(input_filter); old_encoding = LANG_SCNG(script_encoding); zend_multibyte_set_filter(new_encoding TSRMLS_CC); /* need to re-scan if input filter changed */ if (old_input_filter != LANG_SCNG(input_filter) || (old_input_filter && new_encoding != old_encoding)) { zend_multibyte_yyinput_again(old_input_filter, old_encoding TSRMLS_CC); } } } else { zend_error(E_COMPILE_WARNING, "declare(encoding=...) ignored because Zend multibyte feature is turned off by settings"); } zval_dtor(&val->u.constant); } else { zend_error(E_COMPILE_WARNING, "Unsupported declare '%s'", var->u.constant.value.str.val); zval_dtor(&val->u.constant); } zval_dtor(&var->u.constant); } /* }}} */ void zend_do_declare_end(const znode *declare_token TSRMLS_DC) /* {{{ */ { zend_declarables *declarables; zend_stack_top(&CG(declare_stack), (void **) &declarables); /* We should restore if there was more than (current - start) - (ticks?1:0) opcodes */ if ((get_next_op_number(CG(active_op_array)) - declare_token->u.op.opline_num) - ((Z_LVAL(CG(declarables).ticks))?1:0)) { CG(declarables) = *declarables; } } /* }}} */ void zend_do_exit(znode *result, const znode *message TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXIT; SET_NODE(opline->op1, message); SET_UNUSED(opline->op2); result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_BOOL; Z_LVAL(result->u.constant) = 1; } /* }}} */ void zend_do_begin_silence(znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BEGIN_SILENCE; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); GET_NODE(strudel_token, opline->result); } /* }}} */ void zend_do_end_silence(const znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_END_SILENCE; SET_NODE(opline->op1, strudel_token); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_jmp_set(const znode *value, znode *jmp_token, znode *colon_token TSRMLS_DC) /* {{{ */ { int op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (value->op_type == IS_VAR || value->op_type == IS_CV) { opline->opcode = ZEND_JMP_SET_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_JMP_SET; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, value); SET_UNUSED(opline->op2); GET_NODE(colon_token, opline->result); jmp_token->u.op .opline_num = op_number; INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_jmp_set_else(znode *result, const znode *false_value, const znode *jmp_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, colon_token); if (colon_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].opcode = ZEND_JMP_SET_VAR; CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } opline->extended_value = 0; SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_qm_op(const znode *cond, znode *qm_token TSRMLS_DC) /* {{{ */ { int jmpz_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); SET_UNUSED(opline->op2); opline->op2.opline_num = jmpz_op_number; GET_NODE(qm_token, opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_qm_true(const znode *true_value, znode *qm_token, znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->opcodes[qm_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array))+1; /* jmp over the ZEND_JMP */ if (true_value->op_type == IS_VAR || true_value->op_type == IS_CV) { opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, true_value); SET_UNUSED(opline->op2); GET_NODE(qm_token, opline->result); colon_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_qm_false(znode *result, const znode *false_value, const znode *qm_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, qm_token); if (qm_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].opcode = ZEND_QM_ASSIGN_VAR; CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[colon_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, opline->result); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_extended_info(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_STMT; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_begin(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_BEGIN; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_end(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_END; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_ticks(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_TICKS; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->extended_value = Z_LVAL(CG(declarables).ticks); } /* }}} */ zend_bool zend_is_auto_global_quick(const char *name, uint name_len, ulong hashval TSRMLS_DC) /* {{{ */ { zend_auto_global *auto_global; ulong hash = hashval ? hashval : zend_hash_func(name, name_len+1); if (zend_hash_quick_find(CG(auto_globals), name, name_len+1, hash, (void **) &auto_global)==SUCCESS) { if (auto_global->armed) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } return 1; } return 0; } /* }}} */ zend_bool zend_is_auto_global(const char *name, uint name_len TSRMLS_DC) /* {{{ */ { return zend_is_auto_global_quick(name, name_len, 0 TSRMLS_CC); } /* }}} */ int zend_register_auto_global(const char *name, uint name_len, zend_bool jit, zend_auto_global_callback auto_global_callback TSRMLS_DC) /* {{{ */ { zend_auto_global auto_global; auto_global.name = zend_new_interned_string((char*)name, name_len + 1, 0 TSRMLS_CC); auto_global.name_len = name_len; auto_global.auto_global_callback = auto_global_callback; auto_global.jit = jit; return zend_hash_add(CG(auto_globals), name, name_len+1, &auto_global, sizeof(zend_auto_global), NULL); } /* }}} */ static int zend_auto_global_init(zend_auto_global *auto_global TSRMLS_DC) /* {{{ */ { if (auto_global->jit) { auto_global->armed = 1; } else if (auto_global->auto_global_callback) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } else { auto_global->armed = 0; } return 0; } /* }}} */ ZEND_API void zend_activate_auto_globals(TSRMLS_D) /* {{{ */ { zend_hash_apply(CG(auto_globals), (apply_func_t) zend_auto_global_init TSRMLS_CC); } /* }}} */ int zendlex(znode *zendlval TSRMLS_DC) /* {{{ */ { int retval; if (CG(increment_lineno)) { CG(zend_lineno)++; CG(increment_lineno) = 0; } again: Z_TYPE(zendlval->u.constant) = IS_LONG; retval = lex_scan(&zendlval->u.constant TSRMLS_CC); switch (retval) { case T_COMMENT: case T_DOC_COMMENT: case T_OPEN_TAG: case T_WHITESPACE: goto again; case T_CLOSE_TAG: if (LANG_SCNG(yy_text)[LANG_SCNG(yy_leng)-1] != '>') { CG(increment_lineno) = 1; } if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { goto again; } retval = ';'; /* implicit ; */ break; case T_OPEN_TAG_WITH_ECHO: retval = T_ECHO; break; case T_END_HEREDOC: efree(Z_STRVAL(zendlval->u.constant)); break; } INIT_PZVAL(&zendlval->u.constant); zendlval->op_type = IS_CONST; return retval; } /* }}} */ ZEND_API void zend_initialize_class_data(zend_class_entry *ce, zend_bool nullify_handlers TSRMLS_DC) /* {{{ */ { zend_bool persistent_hashes = (ce->type == ZEND_INTERNAL_CLASS) ? 1 : 0; dtor_func_t zval_ptr_dtor_func = ((persistent_hashes) ? ZVAL_INTERNAL_PTR_DTOR : ZVAL_PTR_DTOR); ce->refcount = 1; ce->ce_flags = 0; ce->default_properties_table = NULL; ce->default_static_members_table = NULL; zend_hash_init_ex(&ce->properties_info, 0, NULL, (dtor_func_t) (persistent_hashes ? zend_destroy_property_info_internal : zend_destroy_property_info), persistent_hashes, 0); zend_hash_init_ex(&ce->constants_table, 0, NULL, zval_ptr_dtor_func, persistent_hashes, 0); zend_hash_init_ex(&ce->function_table, 0, NULL, ZEND_FUNCTION_DTOR, persistent_hashes, 0); if (ce->type == ZEND_INTERNAL_CLASS) { #ifdef ZTS int n = zend_hash_num_elements(CG(class_table)); if (CG(static_members_table) && n >= CG(last_static_member)) { /* Support for run-time declaration: dl() */ CG(last_static_member) = n+1; CG(static_members_table) = realloc(CG(static_members_table), (n+1)*sizeof(zval**)); CG(static_members_table)[n] = NULL; } ce->static_members_table = (zval**)(zend_intptr_t)n; #else ce->static_members_table = NULL; #endif } else { ce->static_members_table = ce->default_static_members_table; ce->info.user.doc_comment = NULL; ce->info.user.doc_comment_len = 0; } ce->default_properties_count = 0; ce->default_static_members_count = 0; if (nullify_handlers) { ce->constructor = NULL; ce->destructor = NULL; ce->clone = NULL; ce->__get = NULL; ce->__set = NULL; ce->__unset = NULL; ce->__isset = NULL; ce->__call = NULL; ce->__callstatic = NULL; ce->__tostring = NULL; ce->create_object = NULL; ce->get_iterator = NULL; ce->iterator_funcs.funcs = NULL; ce->interface_gets_implemented = NULL; ce->get_static_method = NULL; ce->parent = NULL; ce->num_interfaces = 0; ce->interfaces = NULL; ce->num_traits = 0; ce->traits = NULL; ce->trait_aliases = NULL; ce->trait_precedences = NULL; ce->serialize = NULL; ce->unserialize = NULL; ce->serialize_func = NULL; ce->unserialize_func = NULL; if (ce->type == ZEND_INTERNAL_CLASS) { ce->info.internal.module = NULL; ce->info.internal.builtin_functions = NULL; } } } /* }}} */ int zend_get_class_fetch_type(const char *class_name, uint class_name_len) /* {{{ */ { if ((class_name_len == sizeof("self")-1) && !memcmp(class_name, "self", sizeof("self")-1)) { return ZEND_FETCH_CLASS_SELF; } else if ((class_name_len == sizeof("parent")-1) && !memcmp(class_name, "parent", sizeof("parent")-1)) { return ZEND_FETCH_CLASS_PARENT; } else if ((class_name_len == sizeof("static")-1) && !memcmp(class_name, "static", sizeof("static")-1)) { return ZEND_FETCH_CLASS_STATIC; } else { return ZEND_FETCH_CLASS_DEFAULT; } } /* }}} */ ZEND_API const char* zend_get_compiled_variable_name(const zend_op_array *op_array, zend_uint var, int* name_len) /* {{{ */ { if (name_len) { *name_len = op_array->vars[var].name_len; } return op_array->vars[var].name; } /* }}} */ void zend_do_build_namespace_name(znode *result, znode *prefix, znode *name TSRMLS_DC) /* {{{ */ { if (prefix) { *result = *prefix; if (Z_TYPE(result->u.constant) == IS_STRING && Z_STRLEN(result->u.constant) == 0) { /* namespace\ */ if (CG(current_namespace)) { znode tmp; zval_dtor(&result->u.constant); tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(result, NULL, &tmp TSRMLS_CC); } } } else { result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_STRING; Z_STRVAL(result->u.constant) = NULL; Z_STRLEN(result->u.constant) = 0; } /* prefix = result */ zend_do_build_full_name(NULL, result, name, 0 TSRMLS_CC); } /* }}} */ void zend_do_begin_namespace(const znode *name, zend_bool with_bracket TSRMLS_DC) /* {{{ */ { char *lcname; /* handle mixed syntax declaration or nested namespaces */ if (!CG(has_bracketed_namespaces)) { if (CG(current_namespace)) { /* previous namespace declarations were unbracketed */ if (with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } } } else { /* previous namespace declarations were bracketed */ if (!with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } else if (CG(current_namespace) || CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "Namespace declarations cannot be nested"); } } if (((!with_bracket && !CG(current_namespace)) || (with_bracket && !CG(has_bracketed_namespaces))) && CG(active_op_array)->last > 0) { /* ignore ZEND_EXT_STMT and ZEND_TICKS */ int num = CG(active_op_array)->last; while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Namespace declaration statement has to be the very first statement in the script"); } } CG(in_namespace) = 1; if (with_bracket) { CG(has_bracketed_namespaces) = 1; } if (name) { lcname = zend_str_tolower_dup(Z_STRVAL(name->u.constant), Z_STRLEN(name->u.constant)); if (((Z_STRLEN(name->u.constant) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN(name->u.constant) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as namespace name", Z_STRVAL(name->u.constant)); } efree(lcname); if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); } else { ALLOC_ZVAL(CG(current_namespace)); } *CG(current_namespace) = name->u.constant; } else { if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_use(znode *ns_name, znode *new_name, int is_global TSRMLS_DC) /* {{{ */ { char *lcname; zval *name, *ns, tmp; zend_bool warn = 0; zend_class_entry **pce; if (!CG(current_import)) { CG(current_import) = emalloc(sizeof(HashTable)); zend_hash_init(CG(current_import), 0, NULL, ZVAL_PTR_DTOR, 0); } ALLOC_ZVAL(ns); *ns = ns_name->u.constant; if (new_name) { name = &new_name->u.constant; } else { const char *p; /* The form "use A\B" is eqivalent to "use A\B as B". So we extract the last part of compound name to use as a new_name */ name = &tmp; p = zend_memrchr(Z_STRVAL_P(ns), '\\', Z_STRLEN_P(ns)); if (p) { ZVAL_STRING(name, p+1, 1); } else { *name = *ns; zval_copy_ctor(name); warn = !is_global && !CG(current_namespace); } } lcname = zend_str_tolower_dup(Z_STRVAL_P(name), Z_STRLEN_P(name)); if (((Z_STRLEN_P(name) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN_P(name) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because '%s' is a special class name", Z_STRVAL_P(ns), Z_STRVAL_P(name), Z_STRVAL_P(name)); } if (CG(current_namespace)) { /* Prefix import name with current namespace name to avoid conflicts with classes */ char *c_ns_name = emalloc(Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) + 1); zend_str_tolower_copy(c_ns_name, Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); c_ns_name[Z_STRLEN_P(CG(current_namespace))] = '\\'; memcpy(c_ns_name+Z_STRLEN_P(CG(current_namespace))+1, lcname, Z_STRLEN_P(name)+1); if (zend_hash_exists(CG(class_table), c_ns_name, Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name)+1)) { char *tmp2 = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) || memcmp(tmp2, c_ns_name, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(tmp2); } efree(c_ns_name); } else if (zend_hash_find(CG(class_table), lcname, Z_STRLEN_P(name)+1, (void**)&pce) == SUCCESS && (*pce)->type == ZEND_USER_CLASS && (*pce)->info.user.filename == CG(compiled_filename)) { char *c_tmp = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(name) || memcmp(c_tmp, lcname, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(c_tmp); } if (zend_hash_add(CG(current_import), lcname, Z_STRLEN_P(name)+1, &ns, sizeof(zval*), NULL) != SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } if (warn) { if (!strcmp(Z_STRVAL_P(name), "strict")) { zend_error(E_COMPILE_ERROR, "You seem to be trying to use a different language..."); } zend_error(E_WARNING, "The use statement with non-compound name '%s' has no effect", Z_STRVAL_P(name)); } efree(lcname); zval_dtor(name); } /* }}} */ void zend_do_declare_constant(znode *name, znode *value TSRMLS_DC) /* {{{ */ { zend_op *opline; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed as constants"); } if (zend_get_ct_const(&name->u.constant, 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare constant '%s'", Z_STRVAL(name->u.constant)); } if (CG(current_namespace)) { /* Prefix constant name with name of current namespace, lowercased */ znode tmp; tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); Z_STRVAL(tmp.u.constant) = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), Z_STRLEN(tmp.u.constant)); zend_do_build_namespace_name(&tmp, &tmp, name TSRMLS_CC); *name = tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DECLARE_CONST; SET_UNUSED(opline->result); SET_NODE(opline->op1, name); SET_NODE(opline->op2, value); } /* }}} */ void zend_verify_namespace(TSRMLS_D) /* {{{ */ { if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "No code may exist outside of namespace {}"); } } /* }}} */ void zend_do_end_namespace(TSRMLS_D) /* {{{ */ { CG(in_namespace) = 0; if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_end_compilation(TSRMLS_D) /* {{{ */ { CG(has_bracketed_namespaces) = 0; zend_do_end_namespace(TSRMLS_C); } /* }}} */ /* {{{ zend_dirname Returns directory name component of path */ ZEND_API size_t zend_dirname(char *path, size_t len) { register char *end = path + len - 1; unsigned int len_adjust = 0; #ifdef PHP_WIN32 /* Note that on Win32 CWD is per drive (heritage from CP/M). * This means dirname("c:foo") maps to "c:." or "c:" - which means CWD on C: drive. */ if ((2 <= len) && isalpha((int)((unsigned char *)path)[0]) && (':' == path[1])) { /* Skip over the drive spec (if any) so as not to change */ path += 2; len_adjust += 2; if (2 == len) { /* Return "c:" on Win32 for dirname("c:"). * It would be more consistent to return "c:." * but that would require making the string *longer*. */ return len; } } #elif defined(NETWARE) /* * Find the first occurence of : from the left * move the path pointer to the position just after : * increment the len_adjust to the length of path till colon character(inclusive) * If there is no character beyond : simple return len */ char *colonpos = NULL; colonpos = strchr(path, ':'); if (colonpos != NULL) { len_adjust = ((colonpos - path) + 1); path += len_adjust; if (len_adjust == len) { return len; } } #endif if (len == 0) { /* Illegal use of this function */ return 0; } /* Strip trailing slashes */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { /* The path only contained slashes */ path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } /* Strip filename */ while (end >= path && !IS_SLASH_P(end)) { end--; } if (end < path) { /* No slash found, therefore return '.' */ #ifdef NETWARE if (len_adjust == 0) { path[0] = '.'; path[1] = '\0'; return 1; /* only one character */ } else { path[0] = '\0'; return len_adjust; } #else path[0] = '.'; path[1] = '\0'; return 1 + len_adjust; #endif } /* Strip slashes which came before the file name */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } *(end+1) = '\0'; return (size_t)(end + 1 - path) + len_adjust; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */ /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <zend_language_parser.h> #include "zend.h" #include "zend_compile.h" #include "zend_constants.h" #include "zend_llist.h" #include "zend_API.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "zend_multibyte.h" #include "zend_language_scanner.h" #define CONSTANT_EX(op_array, op) \ (op_array)->literals[op].constant #define CONSTANT(op) \ CONSTANT_EX(CG(active_op_array), op) #define SET_NODE(target, src) do { \ target ## _type = (src)->op_type; \ if ((src)->op_type == IS_CONST) { \ target.constant = zend_add_literal(CG(active_op_array), &(src)->u.constant TSRMLS_CC); \ } else { \ target = (src)->u.op; \ } \ } while (0) #define GET_NODE(target, src) do { \ (target)->op_type = src ## _type; \ if ((target)->op_type == IS_CONST) { \ (target)->u.constant = CONSTANT(src.constant); \ } else { \ (target)->u.op = src; \ (target)->EA = 0; \ } \ } while (0) #define COPY_NODE(target, src) do { \ target ## _type = src ## _type; \ target = src; \ } while (0) #define CALCULATE_LITERAL_HASH(num) do { \ if (IS_INTERNED(Z_STRVAL(CONSTANT(num)))) { \ Z_HASH_P(&CONSTANT(num)) = INTERNED_HASH(Z_STRVAL(CONSTANT(num))); \ } else { \ Z_HASH_P(&CONSTANT(num)) = zend_hash_func(Z_STRVAL(CONSTANT(num)), Z_STRLEN(CONSTANT(num))+1); \ } \ } while (0) #define GET_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot++; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ } \ } while (0) #define POLYMORPHIC_CACHE_SLOT_SIZE 2 #define GET_POLYMORPHIC_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot; \ CG(active_op_array)->last_cache_slot += POLYMORPHIC_CACHE_SLOT_SIZE; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 2] = NULL; \ } \ } while (0) #define FREE_POLYMORPHIC_CACHE_SLOT(literal) do { \ if (CG(active_op_array)->literals[literal].cache_slot == \ CG(active_op_array)->last_cache_slot - POLYMORPHIC_CACHE_SLOT_SIZE) { \ CG(active_op_array)->literals[literal].cache_slot = -1; \ CG(active_op_array)->last_cache_slot -= POLYMORPHIC_CACHE_SLOT_SIZE; \ } \ } while (0) ZEND_API zend_op_array *(*zend_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); ZEND_API zend_op_array *(*zend_compile_string)(zval *source_string, char *filename TSRMLS_DC); #ifndef ZTS ZEND_API zend_compiler_globals compiler_globals; ZEND_API zend_executor_globals executor_globals; #endif static void zend_duplicate_property_info(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = estrndup(property_info->name, property_info->name_length); } if (property_info->doc_comment) { property_info->doc_comment = estrndup(property_info->doc_comment, property_info->doc_comment_len); } } /* }}} */ static void zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = zend_strndup(property_info->name, property_info->name_length); } } /* }}} */ static void zend_destroy_property_info(zend_property_info *property_info) /* {{{ */ { str_efree(property_info->name); if (property_info->doc_comment) { efree((char*)property_info->doc_comment); } } /* }}} */ static void zend_destroy_property_info_internal(zend_property_info *property_info) /* {{{ */ { str_free((char*)property_info->name); } /* }}} */ static void build_runtime_defined_function_key(zval *result, const char *name, int name_length TSRMLS_DC) /* {{{ */ { char char_pos_buf[32]; uint char_pos_len; const char *filename; char_pos_len = zend_sprintf(char_pos_buf, "%p", LANG_SCNG(yy_text)); if (CG(active_op_array)->filename) { filename = CG(active_op_array)->filename; } else { filename = "-"; } /* NULL, name length, filename length, last accepting char position length */ result->value.str.len = 1+name_length+strlen(filename)+char_pos_len; /* must be binary safe */ result->value.str.val = (char *) safe_emalloc(result->value.str.len, 1, 1); result->value.str.val[0] = '\0'; sprintf(result->value.str.val+1, "%s%s%s", name, filename, char_pos_buf); result->type = IS_STRING; Z_SET_REFCOUNT_P(result, 1); } /* }}} */ static void init_compiler_declarables(TSRMLS_D) /* {{{ */ { Z_TYPE(CG(declarables).ticks) = IS_LONG; Z_LVAL(CG(declarables).ticks) = 0; } /* }}} */ void zend_init_compiler_context(TSRMLS_D) /* {{{ */ { CG(context).opcodes_size = (CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) ? INITIAL_INTERACTIVE_OP_ARRAY_SIZE : INITIAL_OP_ARRAY_SIZE; CG(context).vars_size = 0; CG(context).literals_size = 0; CG(context).current_brk_cont = -1; CG(context).backpatch_count = 0; CG(context).labels = NULL; } /* }}} */ void zend_init_compiler_data_structures(TSRMLS_D) /* {{{ */ { zend_stack_init(&CG(bp_stack)); zend_stack_init(&CG(function_call_stack)); zend_stack_init(&CG(switch_cond_stack)); zend_stack_init(&CG(foreach_copy_stack)); zend_stack_init(&CG(object_stack)); zend_stack_init(&CG(declare_stack)); CG(active_class_entry) = NULL; zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_stack_init(&CG(list_stack)); CG(in_compilation) = 0; CG(start_lineno) = 0; CG(current_namespace) = NULL; CG(in_namespace) = 0; CG(has_bracketed_namespaces) = 0; CG(current_import) = NULL; init_compiler_declarables(TSRMLS_C); zend_stack_init(&CG(context_stack)); CG(encoding_declared) = 0; } /* }}} */ ZEND_API void file_handle_dtor(zend_file_handle *fh) /* {{{ */ { TSRMLS_FETCH(); zend_file_handle_dtor(fh TSRMLS_CC); } /* }}} */ void init_compiler(TSRMLS_D) /* {{{ */ { CG(active_op_array) = NULL; zend_init_compiler_data_structures(TSRMLS_C); zend_init_rsrc_list(TSRMLS_C); zend_hash_init(&CG(filenames_table), 5, NULL, (dtor_func_t) free_estring, 0); zend_llist_init(&CG(open_files), sizeof(zend_file_handle), (void (*)(void *)) file_handle_dtor, 0); CG(unclean_shutdown) = 0; } /* }}} */ void shutdown_compiler(TSRMLS_D) /* {{{ */ { zend_stack_destroy(&CG(bp_stack)); zend_stack_destroy(&CG(function_call_stack)); zend_stack_destroy(&CG(switch_cond_stack)); zend_stack_destroy(&CG(foreach_copy_stack)); zend_stack_destroy(&CG(object_stack)); zend_stack_destroy(&CG(declare_stack)); zend_stack_destroy(&CG(list_stack)); zend_hash_destroy(&CG(filenames_table)); zend_llist_destroy(&CG(open_files)); zend_stack_destroy(&CG(context_stack)); } /* }}} */ ZEND_API char *zend_set_compiled_filename(const char *new_compiled_filename TSRMLS_DC) /* {{{ */ { char **pp, *p; int length = strlen(new_compiled_filename); if (zend_hash_find(&CG(filenames_table), new_compiled_filename, length+1, (void **) &pp) == SUCCESS) { CG(compiled_filename) = *pp; return *pp; } p = estrndup(new_compiled_filename, length); zend_hash_update(&CG(filenames_table), new_compiled_filename, length+1, &p, sizeof(char *), (void **) &pp); CG(compiled_filename) = p; return p; } /* }}} */ ZEND_API void zend_restore_compiled_filename(char *original_compiled_filename TSRMLS_DC) /* {{{ */ { CG(compiled_filename) = original_compiled_filename; } /* }}} */ ZEND_API char *zend_get_compiled_filename(TSRMLS_D) /* {{{ */ { return CG(compiled_filename); } /* }}} */ ZEND_API int zend_get_compiled_lineno(TSRMLS_D) /* {{{ */ { return CG(zend_lineno); } /* }}} */ ZEND_API zend_bool zend_is_compiling(TSRMLS_D) /* {{{ */ { return CG(in_compilation); } /* }}} */ static zend_uint get_temporary_variable(zend_op_array *op_array) /* {{{ */ { return (op_array->T)++ * ZEND_MM_ALIGNED_SIZE(sizeof(temp_variable)); } /* }}} */ static int lookup_cv(zend_op_array *op_array, char* name, int name_len, ulong hash TSRMLS_DC) /* {{{ */ { int i = 0; ulong hash_value = hash ? hash : zend_inline_hash_func(name, name_len+1); while (i < op_array->last_var) { if (op_array->vars[i].name == name || (op_array->vars[i].hash_value == hash_value && op_array->vars[i].name_len == name_len && memcmp(op_array->vars[i].name, name, name_len) == 0)) { str_efree(name); return i; } i++; } i = op_array->last_var; op_array->last_var++; if (op_array->last_var > CG(context).vars_size) { CG(context).vars_size += 16; /* FIXME */ op_array->vars = erealloc(op_array->vars, CG(context).vars_size * sizeof(zend_compiled_variable)); } op_array->vars[i].name = zend_new_interned_string(name, name_len + 1, 1 TSRMLS_CC); op_array->vars[i].name_len = name_len; op_array->vars[i].hash_value = hash_value; return i; } /* }}} */ void zend_del_literal(zend_op_array *op_array, int n) /* {{{ */ { zval_dtor(&CONSTANT_EX(op_array, n)); if (n + 1 == op_array->last_literal) { op_array->last_literal--; } else { Z_TYPE(CONSTANT_EX(op_array, n)) = IS_NULL; } } /* }}} */ /* Common part of zend_add_literal and zend_append_individual_literal */ static inline void zend_insert_literal(zend_op_array *op_array, const zval *zv, int literal_position TSRMLS_DC) /* {{{ */ { if (Z_TYPE_P(zv) == IS_STRING || Z_TYPE_P(zv) == IS_CONSTANT) { zval *z = (zval*)zv; Z_STRVAL_P(z) = (char*)zend_new_interned_string(Z_STRVAL_P(zv), Z_STRLEN_P(zv) + 1, 1 TSRMLS_CC); } CONSTANT_EX(op_array, literal_position) = *zv; Z_SET_REFCOUNT(CONSTANT_EX(op_array, literal_position), 2); Z_SET_ISREF(CONSTANT_EX(op_array, literal_position)); op_array->literals[literal_position].hash_value = 0; op_array->literals[literal_position].cache_slot = -1; } /* }}} */ /* Is used while compiling a function, using the context to keep track of an approximate size to avoid to relocate to often. Literals are truncated to actual size in the second compiler pass (pass_two()). */ int zend_add_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; if (i >= CG(context).literals_size) { while (i >= CG(context).literals_size) { CG(context).literals_size += 16; /* FIXME */ } op_array->literals = (zend_literal*)erealloc(op_array->literals, CG(context).literals_size * sizeof(zend_literal)); } zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ /* Is used after normal compilation to append an additional literal. Allocation is done precisely here. */ int zend_append_individual_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; op_array->literals = (zend_literal*)erealloc(op_array->literals, (i + 1) * sizeof(zend_literal)); zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ int zend_add_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_ns_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; const char *ns_separator; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); ns_separator = (const char*)zend_memrchr(Z_STRVAL_P(zv), '\\', Z_STRLEN_P(zv)) + 1; lc_len = Z_STRLEN_P(zv) - (ns_separator - Z_STRVAL_P(zv)); lc_name = zend_str_tolower_dup(ns_separator, lc_len); ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_class_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } if (Z_STRVAL_P(zv)[0] == '\\') { lc_len = Z_STRLEN_P(zv) - 1; lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv) + 1, lc_len); } else { lc_len = Z_STRLEN_P(zv); lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), lc_len); } ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); GET_CACHE_SLOT(ret); return ret; } /* }}} */ int zend_add_const_name_literal(zend_op_array *op_array, const zval *zv, int unqualified TSRMLS_DC) /* {{{ */ { int ret, tmp_literal; char *name, *tmp_name; const char *ns_separator; int name_len, ns_len; zval c; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } /* skip leading '\\' */ if (Z_STRVAL_P(zv)[0] == '\\') { name_len = Z_STRLEN_P(zv) - 1; name = Z_STRVAL_P(zv) + 1; } else { name_len = Z_STRLEN_P(zv); name = Z_STRVAL_P(zv); } ns_separator = zend_memrchr(name, '\\', name_len); if (ns_separator) { ns_len = ns_separator - name; } else { ns_len = 0; } if (ns_len) { /* lowercased namespace name & original constant name */ tmp_name = estrndup(name, name_len); zend_str_tolower(tmp_name, ns_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased namespace name & lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); } if (ns_len) { if (!unqualified) { return ret; } ns_len++; name += ns_len; name_len -= ns_len; } /* original constant name */ tmp_name = estrndup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); return ret; } /* }}} */ #define LITERAL_STRINGL(op, str, len, copy) do { \ zval _c; \ ZVAL_STRINGL(&_c, str, len, copy); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG(op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG_EX(op_array, op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(op_array, &_c TSRMLS_CC); \ } while (0) #define LITERAL_NULL(op) do { \ zval _c; \ INIT_ZVAL( _c); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) static inline zend_bool zend_is_function_or_method_call(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; return ((type & ZEND_PARSED_METHOD_CALL) || (type == ZEND_PARSED_FUNCTION_CALL)); } /* }}} */ void zend_do_binary_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_unary_op(zend_uchar op, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); GET_NODE(result, opline->result); SET_UNUSED(opline->op2); } /* }}} */ #define MAKE_NOP(opline) { opline->opcode = ZEND_NOP; memset(&opline->result,0,sizeof(opline->result)); memset(&opline->op1,0,sizeof(opline->op1)); memset(&opline->op2,0,sizeof(opline->op2)); opline->result_type=opline->op1_type=opline->op2_type=IS_UNUSED; } static void zend_do_op_data(zend_op *data_op, const znode *value TSRMLS_DC) /* {{{ */ { data_op->opcode = ZEND_OP_DATA; SET_NODE(data_op->op1, value); SET_UNUSED(data_op->op2); } /* }}} */ void zend_do_binary_assign_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; switch (last_op->opcode) { case ZEND_FETCH_OBJ_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, op2 TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; case ZEND_FETCH_DIM_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_DIM; zend_do_op_data(opline, op2 TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result,last_op->result); return; default: break; } } opline->opcode = op; SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void fetch_simple_variable_ex(znode *result, znode *varname, int bp, zend_uchar op TSRMLS_DC) /* {{{ */ { zend_op opline; zend_op *opline_ptr; zend_llist *fetch_list_ptr; if (varname->op_type == IS_CONST) { ulong hash = 0; if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } else if (IS_INTERNED(Z_STRVAL(varname->u.constant))) { hash = INTERNED_HASH(Z_STRVAL(varname->u.constant)); } if (!zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC) && !(varname->u.constant.value.str.len == (sizeof("this")-1) && !memcmp(varname->u.constant.value.str.val, "this", sizeof("this"))) && (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE)) { result->op_type = IS_CV; result->u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC); varname->u.constant.value.str.val = (char*)CG(active_op_array)->vars[result->u.op.var].name; result->EA = 0; return; } } if (bp) { opline_ptr = &opline; init_op(opline_ptr TSRMLS_CC); } else { opline_ptr = get_next_op(CG(active_op_array) TSRMLS_CC); } opline_ptr->opcode = op; opline_ptr->result_type = IS_VAR; opline_ptr->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline_ptr->op1, varname); GET_NODE(result, opline_ptr->result); SET_UNUSED(opline_ptr->op2); opline_ptr->extended_value = ZEND_FETCH_LOCAL; if (varname->op_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline_ptr->op1.constant); if (zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC)) { opline_ptr->extended_value = ZEND_FETCH_GLOBAL; } } if (bp) { zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); zend_llist_add_element(fetch_list_ptr, opline_ptr); } } /* }}} */ void fetch_simple_variable(znode *result, znode *varname, int bp TSRMLS_DC) /* {{{ */ { /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ fetch_simple_variable_ex(result, varname, bp, ZEND_FETCH_W TSRMLS_CC); } /* }}} */ void zend_do_fetch_static_member(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { znode class_node; zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline_ptr; zend_op opline; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); } zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (result->op_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[result->u.op.var].name), CG(active_op_array)->vars[result->u.op.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } GET_NODE(result,opline.result); opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; opline_ptr = &opline; zend_llist_add_element(fetch_list_ptr, &opline); } else { le = fetch_list_ptr->head; opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode != ZEND_FETCH_W && opline_ptr->op1_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[opline_ptr->op1.var].name), CG(active_op_array)->vars[opline_ptr->op1.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; COPY_NODE(opline_ptr->op1, opline.result); zend_llist_prepend_element(fetch_list_ptr, &opline); } else { if (opline_ptr->op1_type == IS_CONST) { GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op1.constant); } if (class_node.op_type == IS_CONST) { opline_ptr->op2_type = IS_CONST; opline_ptr->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline_ptr->op2, &class_node); } opline_ptr->extended_value |= ZEND_FETCH_STATIC_MEMBER; } } } /* }}} */ void fetch_array_begin(znode *result, znode *varname, znode *first_dim TSRMLS_DC) /* {{{ */ { fetch_simple_variable(result, varname, 1 TSRMLS_CC); fetch_array_dim(result, result, first_dim TSRMLS_CC); } /* }}} */ void fetch_array_dim(znode *result, const znode *parent, const znode *dim TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (zend_is_function_or_method_call(parent)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, parent); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_DIM_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, parent); SET_NODE(opline.op2, dim); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline.op2.constant)), Z_STRLEN(CONSTANT(opline.op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline.op2.constant)); ZVAL_LONG(&CONSTANT(opline.op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline.op2.constant); } } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void fetch_string_offset(znode *result, const znode *parent, const znode *offset TSRMLS_DC) /* {{{ */ { fetch_array_dim(result, parent, offset TSRMLS_CC); } /* }}} */ void zend_do_print(znode *result, const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->opcode = ZEND_PRINT; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_echo(const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ECHO; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_abstract_method(const znode *function_name, znode *modifiers, const znode *body TSRMLS_DC) /* {{{ */ { char *method_type; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { Z_LVAL(modifiers->u.constant) |= ZEND_ACC_ABSTRACT; method_type = "Interface"; } else { method_type = "Abstract"; } if (modifiers->u.constant.value.lval & ZEND_ACC_ABSTRACT) { if(modifiers->u.constant.value.lval & ZEND_ACC_PRIVATE) { zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot be declared private", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } if (Z_LVAL(body->u.constant) == ZEND_ACC_ABSTRACT) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_RAISE_ABSTRACT_ERROR; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } else { /* we had code in the function body */ zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot contain body", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } else { if (body->u.constant.value.lval == ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Non-abstract method %s::%s() must contain body", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } } /* }}} */ static zend_bool opline_is_fetch_this(const zend_op *opline TSRMLS_DC) /* {{{ */ { if ((opline->opcode == ZEND_FETCH_W) && (opline->op1_type == IS_CONST) && (Z_TYPE(CONSTANT(opline->op1.constant)) == IS_STRING) && (Z_HASH_P(&CONSTANT(opline->op1.constant)) == THIS_HASHVAL) && (Z_STRLEN(CONSTANT(opline->op1.constant)) == (sizeof("this")-1)) && !memcmp(Z_STRVAL(CONSTANT(opline->op1.constant)), "this", sizeof("this"))) { return 1; } else { return 0; } } /* }}} */ void zend_do_assign(znode *result, znode *variable, znode *value TSRMLS_DC) /* {{{ */ { int last_op_number; zend_op *opline; if (value->op_type == IS_CV) { zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (fetch_list_ptr && fetch_list_ptr->head) { opline = (zend_op *)fetch_list_ptr->head->data; if (opline->opcode == ZEND_FETCH_DIM_W && opline->op1_type == IS_CV && opline->op1.var == value->u.op.var) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_R; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->op1_type = IS_CONST; LITERAL_STRINGL(opline->op1, CG(active_op_array)->vars[value->u.op.var].name, CG(active_op_array)->vars[value->u.op.var].name_len, 1); CALCULATE_LITERAL_HASH(opline->op1.constant); SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_LOCAL; GET_NODE(value, opline->result); } } } zend_do_end_variable_parse(variable, BP_VAR_W, 0 TSRMLS_CC); last_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (variable->op_type == IS_CV) { if (variable->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (variable->op_type == IS_VAR) { int n = 0; while (last_op_number - n > 0) { zend_op *last_op; last_op = &CG(active_op_array)->opcodes[last_op_number-n-1]; if (last_op->result_type == IS_VAR && last_op->result.var == variable->u.op.var) { if (last_op->opcode == ZEND_FETCH_OBJ_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, value TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (last_op->opcode == ZEND_FETCH_DIM_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ /* TBFixed: this can realloc opcodes, leaving last_op pointing wrong */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_DIM; zend_do_op_data(opline, value TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (opline_is_fetch_this(last_op TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } else { break; } } n++; } } opline->opcode = ZEND_ASSIGN; SET_NODE(opline->op1, variable); SET_NODE(opline->op2, value); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_assign_ref(znode *result, const znode *lvar, const znode *rvar TSRMLS_DC) /* {{{ */ { zend_op *opline; if (lvar->op_type == IS_CV) { if (lvar->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (lvar->op_type == IS_VAR) { int last_op_number = get_next_op_number(CG(active_op_array)); if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline_is_fetch_this(opline TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ASSIGN_REF; if (zend_is_function_or_method_call(rvar)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } else if (rvar->EA & ZEND_PARSED_NEW) { opline->extended_value = ZEND_RETURNS_NEW; } else { opline->extended_value = 0; } if (result) { opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } else { opline->result_type = IS_UNUSED | EXT_TYPE_UNUSED; } SET_NODE(opline->op1, lvar); SET_NODE(opline->op2, rvar); } /* }}} */ static inline void do_begin_loop(TSRMLS_D) /* {{{ */ { zend_brk_cont_element *brk_cont_element; int parent; parent = CG(context).current_brk_cont; CG(context).current_brk_cont = CG(active_op_array)->last_brk_cont; brk_cont_element = get_next_brk_cont_element(CG(active_op_array)); brk_cont_element->start = get_next_op_number(CG(active_op_array)); brk_cont_element->parent = parent; } /* }}} */ static inline void do_end_loop(int cont_addr, int has_loop_var TSRMLS_DC) /* {{{ */ { if (!has_loop_var) { /* The start fileld is used to free temporary variables in case of exceptions. * We won't try to free something of we don't have loop variable. */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].start = -1; } CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = cont_addr; CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; } /* }}} */ void zend_do_while_cond(const znode *expr, znode *close_bracket_token TSRMLS_DC) /* {{{ */ { int while_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, expr); close_bracket_token->u.op.opline_num = while_cond_op_number; SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_while_end(const znode *while_token, const znode *close_bracket_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* add unconditional jump */ opline->opcode = ZEND_JMP; opline->op1.opline_num = while_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* update while's conditional jmp */ CG(active_op_array)->opcodes[close_bracket_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); do_end_loop(while_token->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_cond(const znode *expr, znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { int for_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZNZ; SET_NODE(opline->op1, expr); /* the conditional expression */ second_semicolon_token->u.op.opline_num = for_cond_op_number; SET_UNUSED(opline->op2); } /* }}} */ void zend_do_for_before_statement(const znode *cond_start, const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = cond_start->u.op.opline_num; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_end(const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = second_semicolon_token->u.op.opline_num+1; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_end_loop(second_semicolon_token->u.op.opline_num+1, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_pre_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_PRE_INC)?ZEND_PRE_INC_OBJ:ZEND_PRE_DEC_OBJ; last_op->result_type = IS_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_post_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_POST_INC)?ZEND_POST_INC_OBJ:ZEND_POST_DEC_OBJ; last_op->result_type = IS_TMP_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_if_cond(const znode *cond, znode *closing_bracket_token TSRMLS_DC) /* {{{ */ { int if_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); closing_bracket_token->u.op.opline_num = if_cond_op_number; SET_UNUSED(opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_if_after_statement(const znode *closing_bracket_token, unsigned char initialize TSRMLS_DC) /* {{{ */ { int if_end_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; /* save for backpatching */ if (initialize) { zend_llist jmp_list; zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); } zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &if_end_op_number); CG(active_op_array)->opcodes[closing_bracket_token->u.op.opline_num].op2.opline_num = if_end_op_number+1; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_if_end(TSRMLS_D) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_llist *jmp_list_ptr; zend_llist_element *le; zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); for (le=jmp_list_ptr->head; le; le = le->next) { CG(active_op_array)->opcodes[*((int *) le->data)].op1.opline_num = next_op_number; } zend_llist_destroy(jmp_list_ptr); zend_stack_del_top(&CG(bp_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_check_writable_variable(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; if (type & ZEND_PARSED_METHOD_CALL) { zend_error(E_COMPILE_ERROR, "Can't use method return value in write context"); } if (type == ZEND_PARSED_FUNCTION_CALL) { zend_error(E_COMPILE_ERROR, "Can't use function return value in write context"); } } /* }}} */ void zend_do_begin_variable_parse(TSRMLS_D) /* {{{ */ { zend_llist fetch_list; zend_llist_init(&fetch_list, sizeof(zend_op), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &fetch_list, sizeof(zend_llist)); } /* }}} */ void zend_do_end_variable_parse(znode *variable, int type, int arg_offset TSRMLS_DC) /* {{{ */ { zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline = NULL; zend_op *opline_ptr; zend_uint this_var = -1; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); le = fetch_list_ptr->head; /* TODO: $foo->x->y->z = 1 should fetch "x" and "y" for R or RW, not just W */ if (le) { opline_ptr = (zend_op *)le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { /* convert to FETCH_?(this) into IS_CV */ if (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE) { this_var = opline_ptr->result.var; if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), Z_STRVAL(CONSTANT(opline_ptr->op1.constant)), Z_STRLEN(CONSTANT(opline_ptr->op1.constant)), Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC); Z_TYPE(CONSTANT(opline_ptr->op1.constant)) = IS_NULL; } else { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); } le = le->next; if (variable->op_type == IS_VAR && variable->u.op.var == this_var) { variable->op_type = IS_CV; variable->u.op.var = CG(active_op_array)->this_var; } } else if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } while (le) { opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode == ZEND_SEPARATE) { if (type != BP_VAR_R && type != BP_VAR_IS) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); } le = le->next; continue; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); if (opline->op1_type == IS_VAR && opline->op1.var == this_var) { opline->op1_type = IS_CV; opline->op1.var = CG(active_op_array)->this_var; } switch (type) { case BP_VAR_R: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode -= 3; break; case BP_VAR_W: break; case BP_VAR_RW: opline->opcode += 3; break; case BP_VAR_IS: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode += 6; /* 3+3 */ break; case BP_VAR_FUNC_ARG: opline->opcode += 9; /* 3+3+3 */ opline->extended_value |= arg_offset; break; case BP_VAR_UNSET: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for unsetting"); } opline->opcode += 12; /* 3+3+3+3 */ break; } le = le->next; } if (opline && type == BP_VAR_W && arg_offset) { opline->extended_value |= ZEND_FETCH_MAKE_REF; } } zend_llist_destroy(fetch_list_ptr); zend_stack_del_top(&CG(bp_stack)); } /* }}} */ void zend_do_add_string(znode *result, const znode *op1, znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline; if (Z_STRLEN(op2->u.constant) > 1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_STRING; } else if (Z_STRLEN(op2->u.constant) == 1) { int ch = *Z_STRVAL(op2->u.constant); /* Free memory and use ZEND_ADD_CHAR in case of 1 character strings */ efree(Z_STRVAL(op2->u.constant)); ZVAL_LONG(&op2->u.constant, ch); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_CHAR; } else { /* String can be empty after a variable at the end of a heredoc */ efree(Z_STRVAL(op2->u.constant)); return; } if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_add_variable(znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_VAR; if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_free(znode *op1 TSRMLS_DC) /* {{{ */ { if (op1->op_type==IS_TMP_VAR) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else if (op1->op_type==IS_VAR) { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; while (opline->opcode == ZEND_END_SILENCE || opline->opcode == ZEND_EXT_FCALL_END || opline->opcode == ZEND_OP_DATA) { opline--; } if (opline->result_type == IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_FETCH_R || opline->opcode == ZEND_FETCH_DIM_R || opline->opcode == ZEND_FETCH_OBJ_R || opline->opcode == ZEND_QM_ASSIGN_VAR) { /* It's very rare and useless case. It's better to use additional FREE opcode and simplify the FETCH handlers their selves */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else { opline->result_type |= EXT_TYPE_UNUSED; } } else { while (opline>CG(active_op_array)->opcodes) { if (opline->opcode == ZEND_FETCH_DIM_R && opline->op1_type == IS_VAR && opline->op1.var == op1->u.op.var) { /* This should the end of a list() construct * Mark its result as unused */ opline->extended_value = ZEND_FETCH_STANDARD; break; } else if (opline->result_type==IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_NEW) { opline->result_type |= EXT_TYPE_UNUSED; } break; } opline--; } } } else if (op1->op_type == IS_CONST) { zval_dtor(&op1->u.constant); } } /* }}} */ int zend_do_verify_access_types(const znode *current_access_type, const znode *new_modifier) /* {{{ */ { if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_PPP_MASK) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Multiple access type modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_ABSTRACT) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Multiple abstract modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_STATIC) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Multiple static modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_FINAL) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Multiple final modifiers are not allowed"); } if (((Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)) & (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) == (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Cannot use the final modifier on an abstract class member"); } return (Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)); } /* }}} */ void zend_do_begin_function_declaration(znode *function_token, znode *function_name, int is_method, int return_reference, znode *fn_flags_znode TSRMLS_DC) /* {{{ */ { zend_op_array op_array; char *name = function_name->u.constant.value.str.val; int name_len = function_name->u.constant.value.str.len; int function_begin_line = function_token->u.op.opline_num; zend_uint fn_flags; const char *lcname; zend_bool orig_interactive; ALLOCA_FLAG(use_heap) if (is_method) { if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((Z_LVAL(fn_flags_znode->u.constant) & ~(ZEND_ACC_STATIC|ZEND_ACC_PUBLIC))) { zend_error(E_COMPILE_ERROR, "Access type for interface method %s::%s() must be omitted", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } Z_LVAL(fn_flags_znode->u.constant) |= ZEND_ACC_ABSTRACT; /* propagates to the rest of the parser */ } fn_flags = Z_LVAL(fn_flags_znode->u.constant); /* must be done *after* the above check */ } else { fn_flags = 0; } if ((fn_flags & ZEND_ACC_STATIC) && (fn_flags & ZEND_ACC_ABSTRACT) && !(CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_STRICT, "Static function %s%s%s() should not be abstract", is_method ? CG(active_class_entry)->name : "", is_method ? "::" : "", Z_STRVAL(function_name->u.constant)); } function_token->u.op_array = CG(active_op_array); orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(&op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; op_array.function_name = name; if (return_reference) { op_array.fn_flags |= ZEND_ACC_RETURN_REFERENCE; } op_array.fn_flags |= fn_flags; op_array.scope = is_method?CG(active_class_entry):NULL; op_array.prototype = NULL; op_array.line_start = zend_get_compiled_lineno(TSRMLS_C); if (is_method) { int result; lcname = zend_new_interned_string(zend_str_tolower_dup(name, name_len), name_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lcname)) { result = zend_hash_quick_add(&CG(active_class_entry)->function_table, lcname, name_len+1, INTERNED_HASH(lcname), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } else { result = zend_hash_add(&CG(active_class_entry)->function_table, lcname, name_len+1, &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } if (result == FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::%s()", CG(active_class_entry)->name, name); } zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); if (fn_flags & ZEND_ACC_ABSTRACT) { CG(active_class_entry)->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (!(fn_flags & ZEND_ACC_PPP_MASK)) { fn_flags |= ZEND_ACC_PUBLIC; } if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } } } else { char *class_lcname; class_lcname = do_alloca(CG(active_class_entry)->name_length + 1, use_heap); zend_str_tolower_copy(class_lcname, CG(active_class_entry)->name, CG(active_class_entry)->name_length); /* Improve after RC: cache the lowercase class name */ if ((CG(active_class_entry)->name_length == name_len) && ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT) && (!memcmp(class_lcname, lcname, name_len))) { if (!CG(active_class_entry)->constructor) { CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } } else if ((name_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)))) { if (CG(active_class_entry)->constructor) { zend_error(E_STRICT, "Redefining already defined constructor for class %s", CG(active_class_entry)->name); } CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1))) { CG(active_class_entry)->destructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1))) { CG(active_class_entry)->clone = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } CG(active_class_entry)->__call = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } CG(active_class_entry)->__callstatic = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } CG(active_class_entry)->__get = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } CG(active_class_entry)->__set = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } CG(active_class_entry)->__unset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } CG(active_class_entry)->__isset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } CG(active_class_entry)->__tostring = (zend_function *) CG(active_op_array); } else if (!(fn_flags & ZEND_ACC_STATIC)) { CG(active_op_array)->fn_flags |= ZEND_ACC_ALLOW_STATIC; } free_alloca(class_lcname, use_heap); } str_efree(lcname); } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zval key; if (CG(current_namespace)) { /* Prefix function name with current namespcae name */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, function_name TSRMLS_CC); op_array.function_name = Z_STRVAL(tmp.u.constant); name_len = Z_STRLEN(tmp.u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), name_len); } else { lcname = zend_str_tolower_dup(name, name_len); } opline->opcode = ZEND_DECLARE_FUNCTION; opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, name_len TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; LITERAL_STRINGL(opline->op2, lcname, name_len, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); opline->extended_value = ZEND_DECLARE_FUNCTION; zend_hash_quick_update(CG(function_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); } if (CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_NOP; opline->lineno = function_begin_line; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } { /* Push a seperator to the switch and foreach stacks */ zend_switch_entry switch_entry; switch_entry.cond.op_type = IS_UNUSED; switch_entry.default_case = 0; switch_entry.control_var = 0; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); { /* Foreach stack separator */ zend_op dummy_opline; dummy_opline.result_type = IS_UNUSED; dummy_opline.op1_type = IS_UNUSED; zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); } } if (CG(doc_comment)) { CG(active_op_array)->doc_comment = CG(doc_comment); CG(active_op_array)->doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_begin_lambda_function_declaration(znode *result, znode *function_token, int return_reference, int is_static TSRMLS_DC) /* {{{ */ { znode function_name; zend_op_array *current_op_array = CG(active_op_array); int current_op_number = get_next_op_number(CG(active_op_array)); zend_op *current_op; function_name.op_type = IS_CONST; ZVAL_STRINGL(&function_name.u.constant, "{closure}", sizeof("{closure}")-1, 1); zend_do_begin_function_declaration(function_token, &function_name, 0, return_reference, NULL TSRMLS_CC); result->op_type = IS_TMP_VAR; result->u.op.var = get_temporary_variable(current_op_array); current_op = &current_op_array->opcodes[current_op_number]; current_op->opcode = ZEND_DECLARE_LAMBDA_FUNCTION; zend_del_literal(current_op_array, current_op->op2.constant); SET_UNUSED(current_op->op2); SET_NODE(current_op->result, result); if (is_static) { CG(active_op_array)->fn_flags |= ZEND_ACC_STATIC; } CG(active_op_array)->fn_flags |= ZEND_ACC_CLOSURE; } /* }}} */ void zend_do_handle_exception(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_HANDLE_EXCEPTION; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_function_declaration(const znode *function_token TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; zend_do_extended_info(TSRMLS_C); zend_do_return(NULL, 0 TSRMLS_CC); pass_two(CG(active_op_array) TSRMLS_CC); zend_release_labels(TSRMLS_C); if (CG(active_class_entry)) { zend_check_magic_method_implementation(CG(active_class_entry), (zend_function*)CG(active_op_array), E_COMPILE_ERROR TSRMLS_CC); } else { /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(CG(active_op_array)->function_name); zend_str_tolower_copy(lcname, CG(active_op_array)->function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME)) && CG(active_op_array)->num_args != 1) { zend_error(E_COMPILE_ERROR, "%s() must take exactly 1 argument", ZEND_AUTOLOAD_FUNC_NAME); } } CG(active_op_array)->line_end = zend_get_compiled_lineno(TSRMLS_C); CG(active_op_array) = function_token->u.op_array; /* Pop the switch and foreach seperators */ zend_stack_del_top(&CG(switch_cond_stack)); zend_stack_del_top(&CG(foreach_copy_stack)); } /* }}} */ void zend_do_receive_arg(zend_uchar op, znode *varname, const znode *offset, const znode *initialization, znode *class_type, zend_uchar pass_by_reference TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_arg_info *cur_arg_info; znode var; if (class_type->op_type == IS_CONST && Z_TYPE(class_type->u.constant) == IS_STRING && Z_STRLEN(class_type->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_type->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } if (zend_is_auto_global_quick(Z_STRVAL(varname->u.constant), Z_STRLEN(varname->u.constant), 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign auto-global variable %s", Z_STRVAL(varname->u.constant)); } else { var.op_type = IS_CV; var.u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(varname->u.constant) = (char*)CG(active_op_array)->vars[var.u.op.var].name; var.EA = 0; if (CG(active_op_array)->vars[var.u.op.var].hash_value == THIS_HASHVAL && Z_STRLEN(varname->u.constant) == sizeof("this")-1 && !memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this")-1)) { if (CG(active_op_array)->scope && (CG(active_op_array)->fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } CG(active_op_array)->this_var = var.u.op.var; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->num_args++; opline->opcode = op; SET_NODE(opline->result, &var); SET_NODE(opline->op1, offset); if (op == ZEND_RECV_INIT) { SET_NODE(opline->op2, initialization); } else { CG(active_op_array)->required_num_args = CG(active_op_array)->num_args; SET_UNUSED(opline->op2); } CG(active_op_array)->arg_info = erealloc(CG(active_op_array)->arg_info, sizeof(zend_arg_info)*(CG(active_op_array)->num_args)); cur_arg_info = &CG(active_op_array)->arg_info[CG(active_op_array)->num_args-1]; cur_arg_info->name = zend_new_interned_string(estrndup(varname->u.constant.value.str.val, varname->u.constant.value.str.len), varname->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->name_len = varname->u.constant.value.str.len; cur_arg_info->type_hint = 0; cur_arg_info->allow_null = 1; cur_arg_info->pass_by_reference = pass_by_reference; cur_arg_info->class_name = NULL; cur_arg_info->class_name_len = 0; if (class_type->op_type != IS_UNUSED) { cur_arg_info->allow_null = 0; if (class_type->u.constant.type != IS_NULL) { if (class_type->u.constant.type == IS_ARRAY) { cur_arg_info->type_hint = IS_ARRAY; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else if (Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Default value for parameters with array type hint can only be an array or NULL"); } } } else if (class_type->u.constant.type == IS_CALLABLE) { cur_arg_info->type_hint = IS_CALLABLE; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with callable type hint can only be NULL"); } } } else { cur_arg_info->type_hint = IS_OBJECT; if (ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_type->u.constant), Z_STRLEN(class_type->u.constant))) { zend_resolve_class_name(class_type, opline->extended_value, 1 TSRMLS_CC); } Z_STRVAL(class_type->u.constant) = (char*)zend_new_interned_string(class_type->u.constant.value.str.val, class_type->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->class_name = class_type->u.constant.value.str.val; cur_arg_info->class_name_len = class_type->u.constant.value.str.len; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with a class type hint can only be NULL"); } } } } } } /* }}} */ int zend_do_begin_function_call(znode *function_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { zend_function *function; char *lcname; char *is_compound = memchr(Z_STRVAL(function_name->u.constant), '\\', Z_STRLEN(function_name->u.constant)); zend_resolve_non_class_name(function_name, check_namespace TSRMLS_CC); if (check_namespace && CG(current_namespace) && !is_compound) { /* We assume we call function from the current namespace if it is not prefixed. */ /* In run-time PHP will check for function with full name and internal function with short name */ zend_do_begin_dynamic_function_call(function_name, 1 TSRMLS_CC); return 1; } lcname = zend_str_tolower_dup(function_name->u.constant.value.str.val, function_name->u.constant.value.str.len); if ((zend_hash_find(CG(function_table), lcname, function_name->u.constant.value.str.len+1, (void **) &function)==FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_FUNCTIONS) && (function->type == ZEND_INTERNAL_FUNCTION))) { zend_do_begin_dynamic_function_call(function_name, 0 TSRMLS_CC); efree(lcname); return 1; /* Dynamic */ } efree(function_name->u.constant.value.str.val); function_name->u.constant.value.str.val = lcname; zend_stack_push(&CG(function_call_stack), (void *) &function, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 0; } /* }}} */ void zend_do_begin_method_call(znode *left_bracket TSRMLS_DC) /* {{{ */ { zend_op *last_op; int last_op_number; unsigned char *ptr = NULL; zend_do_end_variable_parse(left_bracket, BP_VAR_R, 0 TSRMLS_CC); zend_do_begin_variable_parse(TSRMLS_C); last_op_number = get_next_op_number(CG(active_op_array))-1; last_op = &CG(active_op_array)->opcodes[last_op_number]; if ((last_op->op2_type == IS_CONST) && (Z_TYPE(CONSTANT(last_op->op2.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(last_op->op2.constant)) == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !zend_binary_strcasecmp(Z_STRVAL(CONSTANT(last_op->op2.constant)), Z_STRLEN(CONSTANT(last_op->op2.constant)), ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1)) { zend_error(E_COMPILE_ERROR, "Cannot call __clone() method on objects - use 'clone $obj' instead"); } if (last_op->opcode == ZEND_FETCH_OBJ_R) { if (last_op->op2_type == IS_CONST) { zval name; name = CONSTANT(last_op->op2.constant); if (!IS_INTERNED(Z_STRVAL(name))) { Z_STRVAL(name) = estrndup(Z_STRVAL(name), Z_STRLEN(name)); } FREE_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); last_op->op2.constant = zend_add_func_name_literal(CG(active_op_array), &name TSRMLS_CC); GET_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); } last_op->opcode = ZEND_INIT_METHOD_CALL; SET_UNUSED(last_op->result); Z_LVAL(left_bracket->u.constant) = ZEND_INIT_FCALL_BY_NAME; } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (left_bracket->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &left_bracket->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, left_bracket); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_do_clone(znode *result, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CLONE; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_begin_dynamic_function_call(znode *function_name, int ns_call TSRMLS_DC) /* {{{ */ { unsigned char *ptr = NULL; zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (ns_call) { /* In run-time PHP will check for function with full name and internal function with short name */ opline->opcode = ZEND_INIT_NS_FCALL_BY_NAME; SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_ns_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (function_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, function_name); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_resolve_non_class_name(znode *element_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; int len; zval **ns; char *lcname, *compound = memchr(Z_STRVAL(element_name->u.constant), '\\', Z_STRLEN(element_name->u.constant)); if (Z_STRVAL(element_name->u.constant)[0] == '\\') { /* name starts with \ so it is known and unambiguos, nothing to do here but shorten it */ memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+1, Z_STRLEN(element_name->u.constant)); --Z_STRLEN(element_name->u.constant); return; } if(!check_namespace) { return; } if (compound && CG(current_import)) { len = compound - Z_STRVAL(element_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(element_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(element_name->u.constant) -= len; memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+len, Z_STRLEN(element_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, element_name TSRMLS_CC); *element_name = tmp; efree(lcname); return; } efree(lcname); } if (CG(current_namespace)) { tmp = *element_name; Z_STRLEN(tmp.u.constant) = sizeof("\\")-1 + Z_STRLEN(element_name->u.constant) + Z_STRLEN_P(CG(current_namespace)); Z_STRVAL(tmp.u.constant) = (char *) emalloc(Z_STRLEN(tmp.u.constant)+1); memcpy(Z_STRVAL(tmp.u.constant), Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace))]), "\\", sizeof("\\")-1); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace)) + sizeof("\\")-1]), Z_STRVAL(element_name->u.constant), Z_STRLEN(element_name->u.constant)+1); STR_FREE(Z_STRVAL(element_name->u.constant)); *element_name = tmp; } } /* }}} */ void zend_resolve_class_name(znode *class_name, ulong fetch_type, int check_ns_name TSRMLS_DC) /* {{{ */ { char *compound; char *lcname; zval **ns; znode tmp; int len; compound = memchr(Z_STRVAL(class_name->u.constant), '\\', Z_STRLEN(class_name->u.constant)); if (compound) { /* This is a compound class name that contains namespace prefix */ if (Z_STRVAL(class_name->u.constant)[0] == '\\') { /* The STRING name has "\" prefix */ Z_STRLEN(class_name->u.constant) -= 1; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+1, Z_STRLEN(class_name->u.constant)+1); Z_STRVAL(class_name->u.constant) = erealloc( Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1); if (ZEND_FETCH_CLASS_DEFAULT != zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "'\\%s' is an invalid class name", Z_STRVAL(class_name->u.constant)); } } else { if (CG(current_import)) { len = compound - Z_STRVAL(class_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(class_name->u.constant) -= len; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+len, Z_STRLEN(class_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; efree(lcname); return; } efree(lcname); } /* Here name is not prefixed with \ and not imported */ if (CG(current_namespace)) { tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } } } else if (CG(current_import) || CG(current_namespace)) { /* this is a plain name (without \) */ lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns) == SUCCESS) { /* The given name is an import name. Substitute it. */ zval_dtor(&class_name->u.constant); class_name->u.constant = **ns; zval_copy_ctor(&class_name->u.constant); } else if (CG(current_namespace)) { /* plain name, no import - prepend current namespace to it */ tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } efree(lcname); } } /* }}} */ void zend_do_fetch_class(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { long fetch_class_op_number; zend_op *opline; if (class_name->op_type == IS_CONST && Z_TYPE(class_name->u.constant) == IS_STRING && Z_STRLEN(class_name->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_name->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } fetch_class_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CLASS; SET_UNUSED(opline->op1); opline->extended_value = ZEND_FETCH_CLASS_GLOBAL; CG(catch_begin) = fetch_class_op_number; if (class_name->op_type == IS_CONST) { int fetch_type; fetch_type = zend_get_class_fetch_type(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); switch (fetch_type) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: SET_UNUSED(opline->op2); opline->extended_value = fetch_type; zval_dtor(&class_name->u.constant); break; default: zend_resolve_class_name(class_name, opline->extended_value, 0 TSRMLS_CC); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_name->u.constant TSRMLS_CC); break; } } else { SET_NODE(opline->op2, class_name); } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; /* FIXME: Hack so that INIT_FCALL_BY_NAME still knows this is a class */ GET_NODE(result, opline->result); result->EA = opline->extended_value; } /* }}} */ void zend_do_label(znode *label TSRMLS_DC) /* {{{ */ { zend_label dest; if (!CG(context).labels) { ALLOC_HASHTABLE(CG(context).labels); zend_hash_init(CG(context).labels, 4, NULL, NULL, 0); } dest.brk_cont = CG(context).current_brk_cont; dest.opline_num = get_next_op_number(CG(active_op_array)); if (zend_hash_add(CG(context).labels, Z_STRVAL(label->u.constant), Z_STRLEN(label->u.constant) + 1, (void**)&dest, sizeof(zend_label), NULL) == FAILURE) { zend_error(E_COMPILE_ERROR, "Label '%s' already defined", Z_STRVAL(label->u.constant)); } /* Done with label now */ zval_dtor(&label->u.constant); } /* }}} */ void zend_resolve_goto_label(zend_op_array *op_array, zend_op *opline, int pass2 TSRMLS_DC) /* {{{ */ { zend_label *dest; long current, distance; zval *label; if (pass2) { label = opline->op2.zv; } else { label = &CONSTANT_EX(op_array, opline->op2.constant); } if (CG(context).labels == NULL || zend_hash_find(CG(context).labels, Z_STRVAL_P(label), Z_STRLEN_P(label)+1, (void**)&dest) == FAILURE) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; zend_error(E_COMPILE_ERROR, "'goto' to undefined label '%s'", Z_STRVAL_P(label)); } else { /* Label is not defined. Delay to pass 2. */ INC_BPC(op_array); return; } } opline->op1.opline_num = dest->opline_num; zval_dtor(label); Z_TYPE_P(label) = IS_NULL; /* Check that we are not moving into loop or switch */ current = opline->extended_value; for (distance = 0; current != dest->brk_cont; distance++) { if (current == -1) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; } zend_error(E_COMPILE_ERROR, "'goto' into loop or switch statement is disallowed"); } current = op_array->brk_cont_array[current].parent; } if (distance == 0) { /* Nothing to break out of, optimize to ZEND_JMP */ opline->opcode = ZEND_JMP; opline->extended_value = 0; SET_UNUSED(opline->op2); } else { /* Set real break distance */ ZVAL_LONG(label, distance); } if (pass2) { DEC_BPC(op_array); } } /* }}} */ void zend_do_goto(const znode *label TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_GOTO; opline->extended_value = CG(context).current_brk_cont; SET_UNUSED(opline->op1); SET_NODE(opline->op2, label); zend_resolve_goto_label(CG(active_op_array), opline, 0 TSRMLS_CC); } /* }}} */ void zend_release_labels(TSRMLS_D) /* {{{ */ { if (CG(context).labels) { zend_hash_destroy(CG(context).labels); FREE_HASHTABLE(CG(context).labels); } if (!zend_stack_is_empty(&CG(context_stack))) { zend_compiler_context *ctx; zend_stack_top(&CG(context_stack), (void**)&ctx); CG(context) = *ctx; zend_stack_del_top(&CG(context_stack)); } } /* }}} */ void zend_do_build_full_name(znode *result, znode *prefix, znode *name, int is_class_member TSRMLS_DC) /* {{{ */ { zend_uint length; if (!result) { result = prefix; } else { *result = *prefix; } if (is_class_member) { length = sizeof("::")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "::", sizeof("::")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("::")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } else { length = sizeof("\\")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "\\", sizeof("\\")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("\\")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } } /* }}} */ int zend_do_begin_class_member_function_call(znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { znode class_node; unsigned char *ptr = NULL; zend_op *opline; if (method_name->op_type == IS_CONST) { char *lcname = zend_str_tolower_dup(Z_STRVAL(method_name->u.constant), Z_STRLEN(method_name->u.constant)); if ((sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == Z_STRLEN(method_name->u.constant) && memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == 0) { zval_dtor(&method_name->u.constant); method_name->op_type = IS_UNUSED; } efree(lcname); } if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; opline = get_next_op(CG(active_op_array) TSRMLS_CC); } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->extended_value = class_node.EA ; } opline->opcode = ZEND_INIT_STATIC_METHOD_CALL; if (class_node.op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, &class_node); } if (method_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &method_name->u.constant TSRMLS_CC); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } } else { SET_NODE(opline->op2, method_name); } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 1; /* Dynamic */ } /* }}} */ void zend_do_end_function_call(znode *function_name, znode *result, const znode *argument_list, int is_method, int is_dynamic_fcall TSRMLS_DC) /* {{{ */ { zend_op *opline; if (is_method && function_name && function_name->op_type == IS_UNUSED) { /* clone */ if (Z_LVAL(argument_list->u.constant) != 0) { zend_error(E_WARNING, "Clone method does not require arguments"); } opline = &CG(active_op_array)->opcodes[Z_LVAL(function_name->u.constant)]; } else { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (!is_method && !is_dynamic_fcall && function_name->op_type==IS_CONST) { opline->opcode = ZEND_DO_FCALL; SET_NODE(opline->op1, function_name); CALCULATE_LITERAL_HASH(opline->op1.constant); GET_CACHE_SLOT(opline->op1.constant); } else { opline->opcode = ZEND_DO_FCALL_BY_NAME; SET_UNUSED(opline->op1); } } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(result, opline->result) ; SET_UNUSED(opline->op2); zend_stack_del_top(&CG(function_call_stack)); opline->extended_value = Z_LVAL(argument_list->u.constant); } /* }}} */ void zend_do_pass_param(znode *param, zend_uchar op, int offset TSRMLS_DC) /* {{{ */ { zend_op *opline; int original_op=op; zend_function **function_ptr_ptr, *function_ptr; int send_by_reference; int send_function = 0; zend_stack_top(&CG(function_call_stack), (void **) &function_ptr_ptr); function_ptr = *function_ptr_ptr; if (original_op == ZEND_SEND_REF) { if (function_ptr && function_ptr->common.function_name && function_ptr->common.type == ZEND_USER_FUNCTION && !ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed; " "If you would like to pass argument by reference, modify the declaration of %s().", function_ptr->common.function_name); } else { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed"); } return; } if (function_ptr) { if (ARG_MAY_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { if (param->op_type & (IS_VAR|IS_CV) && original_op != ZEND_SEND_VAL) { send_by_reference = 1; if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION | ZEND_ARG_SEND_SILENT; } } else { op = ZEND_SEND_VAL; send_by_reference = 0; } } else { send_by_reference = ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset) ? ZEND_ARG_SEND_BY_REF : 0; } } else { send_by_reference = 0; } if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION; } else if (op == ZEND_SEND_VAL && (param->op_type & (IS_VAR|IS_CV))) { op = ZEND_SEND_VAR_NO_REF; } if (op!=ZEND_SEND_VAR_NO_REF && send_by_reference==ZEND_ARG_SEND_BY_REF) { /* change to passing by reference */ switch (param->op_type) { case IS_VAR: case IS_CV: op = ZEND_SEND_REF; break; default: zend_error(E_COMPILE_ERROR, "Only variables can be passed by reference"); break; } } if (original_op == ZEND_SEND_VAR) { switch (op) { case ZEND_SEND_VAR_NO_REF: zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); break; case ZEND_SEND_VAR: if (function_ptr) { zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(param, BP_VAR_FUNC_ARG, offset TSRMLS_CC); } break; case ZEND_SEND_REF: zend_do_end_variable_parse(param, BP_VAR_W, 0 TSRMLS_CC); break; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (op == ZEND_SEND_VAR_NO_REF) { if (function_ptr) { opline->extended_value = ZEND_ARG_COMPILE_TIME_BOUND | send_by_reference | send_function; } else { opline->extended_value = send_function; } } else { if (function_ptr) { opline->extended_value = ZEND_DO_FCALL; } else { opline->extended_value = ZEND_DO_FCALL_BY_NAME; } } opline->opcode = op; SET_NODE(opline->op1, param); opline->op2.opline_num = offset; SET_UNUSED(opline->op2); } /* }}} */ static int generate_free_switch_expr(const zend_switch_entry *switch_entry TSRMLS_DC) /* {{{ */ { zend_op *opline; if (switch_entry->cond.op_type != IS_VAR && switch_entry->cond.op_type != IS_TMP_VAR) { return (switch_entry->cond.op_type == IS_UNUSED); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry->cond); SET_UNUSED(opline->op2); opline->extended_value = 0; return 0; } /* }}} */ static int generate_free_foreach_copy(const zend_op *foreach_copy TSRMLS_DC) /* {{{ */ { zend_op *opline; /* If we reach the seperator then stop applying the stack */ if (foreach_copy->result_type == IS_UNUSED && foreach_copy->op1_type == IS_UNUSED) { return 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->result_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->result); SET_UNUSED(opline->op2); opline->extended_value = 1; if (foreach_copy->op1_type != IS_UNUSED) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->op1_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->op1); SET_UNUSED(opline->op2); opline->extended_value = 0; } return 0; } /* }}} */ void zend_do_return(znode *expr, int do_end_vparse TSRMLS_DC) /* {{{ */ { zend_op *opline; int start_op_number, end_op_number; if (do_end_vparse) { if ((CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) && !zend_is_function_or_method_call(expr)) { zend_do_end_variable_parse(expr, BP_VAR_W, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(expr, BP_VAR_R, 0 TSRMLS_CC); } } start_op_number = get_next_op_number(CG(active_op_array)); #ifdef ZTS zend_stack_apply_with_argument(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_switch_expr TSRMLS_CC); zend_stack_apply_with_argument(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_foreach_copy TSRMLS_CC); #else zend_stack_apply(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_switch_expr); zend_stack_apply(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_foreach_copy); #endif end_op_number = get_next_op_number(CG(active_op_array)); while (start_op_number < end_op_number) { CG(active_op_array)->opcodes[start_op_number].extended_value |= EXT_TYPE_FREE_ON_RETURN; start_op_number++; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) ? ZEND_RETURN_BY_REF : ZEND_RETURN; if (expr) { SET_NODE(opline->op1, expr); if (do_end_vparse && zend_is_function_or_method_call(expr)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } } else { opline->op1_type = IS_CONST; LITERAL_NULL(opline->op1); } SET_UNUSED(opline->op2); } /* }}} */ static int zend_add_try_element(zend_uint try_op TSRMLS_DC) /* {{{ */ { int try_catch_offset = CG(active_op_array)->last_try_catch++; CG(active_op_array)->try_catch_array = erealloc(CG(active_op_array)->try_catch_array, sizeof(zend_try_catch_element)*CG(active_op_array)->last_try_catch); CG(active_op_array)->try_catch_array[try_catch_offset].try_op = try_op; return try_catch_offset; } /* }}} */ static void zend_add_catch_element(int offset, zend_uint catch_op TSRMLS_DC) /* {{{ */ { CG(active_op_array)->try_catch_array[offset].catch_op = catch_op; } /* }}} */ void zend_do_first_catch(znode *open_parentheses TSRMLS_DC) /* {{{ */ { open_parentheses->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_initialize_try_catch_element(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist jmp_list; zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); zend_add_catch_element(try_token->u.op.opline_num, get_next_op_number(CG(active_op_array)) TSRMLS_CC); } /* }}} */ void zend_do_mark_last_catch(const znode *first_catch, const znode *last_additional_catch TSRMLS_DC) /* {{{ */ { CG(active_op_array)->last--; zend_do_if_end(TSRMLS_C); if (last_additional_catch->u.op.opline_num == -1) { CG(active_op_array)->opcodes[first_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[first_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } else { CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_try(znode *try_token TSRMLS_DC) /* {{{ */ { try_token->u.op.opline_num = zend_add_try_element(get_next_op_number(CG(active_op_array)) TSRMLS_CC); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_catch(znode *try_token, znode *class_name, znode *catch_var, znode *first_catch TSRMLS_DC) /* {{{ */ { long catch_op_number; zend_op *opline; znode catch_class; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); catch_class = *class_name; } else { zend_error(E_COMPILE_ERROR, "Bad class name in the catch statement"); } catch_op_number = get_next_op_number(CG(active_op_array)); if (first_catch) { first_catch->u.op.opline_num = catch_op_number; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CATCH; opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &catch_class.u.constant TSRMLS_CC); opline->op2_type = IS_CV; opline->op2.var = lookup_cv(CG(active_op_array), catch_var->u.constant.value.str.val, catch_var->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(catch_var->u.constant) = (char*)CG(active_op_array)->vars[opline->op2.var].name; opline->result.num = 0; /* 1 means it's the last catch in the block */ try_token->u.op.opline_num = catch_op_number; } /* }}} */ void zend_do_end_catch(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); CG(active_op_array)->opcodes[try_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_throw(const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_THROW; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); } /* }}} */ ZEND_API void function_add_ref(zend_function *function) /* {{{ */ { if (function->type == ZEND_USER_FUNCTION) { zend_op_array *op_array = &function->op_array; (*op_array->refcount)++; if (op_array->static_variables) { HashTable *static_variables = op_array->static_variables; zval *tmp_zval; ALLOC_HASHTABLE(op_array->static_variables); zend_hash_init(op_array->static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(op_array->static_variables, static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_zval, sizeof(zval *)); } op_array->run_time_cache = NULL; } } /* }}} */ static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */ { zend_function *function, *new_function; if (!ce->parent) { return; } /* You cannot change create_object */ ce->create_object = ce->parent->create_object; /* Inherit special functions if needed */ if (!ce->get_iterator) { ce->get_iterator = ce->parent->get_iterator; } if (!ce->iterator_funcs.funcs) { ce->iterator_funcs.funcs = ce->parent->iterator_funcs.funcs; } if (!ce->__get) { ce->__get = ce->parent->__get; } if (!ce->__set) { ce->__set = ce->parent->__set; } if (!ce->__unset) { ce->__unset = ce->parent->__unset; } if (!ce->__isset) { ce->__isset = ce->parent->__isset; } if (!ce->__call) { ce->__call = ce->parent->__call; } if (!ce->__callstatic) { ce->__callstatic = ce->parent->__callstatic; } if (!ce->__tostring) { ce->__tostring = ce->parent->__tostring; } if (!ce->clone) { ce->clone = ce->parent->clone; } if(!ce->serialize) { ce->serialize = ce->parent->serialize; } if(!ce->unserialize) { ce->unserialize = ce->parent->unserialize; } if (!ce->destructor) { ce->destructor = ce->parent->destructor; } if (ce->constructor) { if (ce->parent->constructor && ce->parent->constructor->common.fn_flags & ZEND_ACC_FINAL) { zend_error(E_ERROR, "Cannot override final %s::%s() with %s::%s()", ce->parent->name, ce->parent->constructor->common.function_name, ce->name, ce->constructor->common.function_name ); } return; } if (zend_hash_find(&ce->parent->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), (void **)&function)==SUCCESS) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), function, sizeof(zend_function), (void**)&new_function); function_add_ref(new_function); } else { /* Don't inherit the old style constructor if we already have the new style constructor */ char *lc_class_name; char *lc_parent_class_name; lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); if (!zend_hash_exists(&ce->function_table, lc_class_name, ce->name_length+1)) { lc_parent_class_name = zend_str_tolower_dup(ce->parent->name, ce->parent->name_length); if (!zend_hash_exists(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1) && zend_hash_find(&ce->parent->function_table, lc_parent_class_name, ce->parent->name_length+1, (void **)&function)==SUCCESS) { if (function->common.fn_flags & ZEND_ACC_CTOR) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1, function, sizeof(zend_function), (void**)new_function); function_add_ref(new_function); } } efree(lc_parent_class_name); } efree(lc_class_name); } ce->constructor = ce->parent->constructor; } /* }}} */ char *zend_visibility_string(zend_uint fn_flags) /* {{{ */ { if (fn_flags & ZEND_ACC_PRIVATE) { return "private"; } if (fn_flags & ZEND_ACC_PROTECTED) { return "protected"; } if (fn_flags & ZEND_ACC_PUBLIC) { return "public"; } return ""; } /* }}} */ static void do_inherit_method(zend_function *function) /* {{{ */ { /* The class entry of the derived function intentionally remains the same * as that of the parent class. That allows us to know in which context * we're running, and handle private method calls properly. */ function_add_ref(function); } /* }}} */ static zend_bool zend_do_perform_implementation_check(const zend_function *fe, const zend_function *proto TSRMLS_DC) /* {{{ */ { zend_uint i; /* If it's a user function then arg_info == NULL means we don't have any parameters but * we still need to do the arg number checks. We are only willing to ignore this for internal * functions because extensions don't always define arg_info. */ if (!proto || (!proto->common.arg_info && proto->common.type != ZEND_USER_FUNCTION)) { return 1; } /* Checks for constructors only if they are declared in an interface, * or explicitly marked as abstract */ if ((fe->common.fn_flags & ZEND_ACC_CTOR) && ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)) { return 1; } /* check number of arguments */ if (proto->common.required_num_args < fe->common.required_num_args || proto->common.num_args > fe->common.num_args) { return 0; } if (fe->common.type != ZEND_USER_FUNCTION && (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) != 0 && (fe->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) == 0) { return 0; } /* by-ref constraints on return values are covariant */ if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) { return 0; } for (i=0; i < proto->common.num_args; i++) { if (ZEND_LOG_XOR(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)) { /* Only one has a type hint and the other one doesn't */ return 0; } if (fe->common.arg_info[i].class_name && strcasecmp(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)!=0) { const char *colon; if (fe->common.type != ZEND_USER_FUNCTION) { return 0; } else if (strchr(proto->common.arg_info[i].class_name, '\\') != NULL || (colon = zend_memrchr(fe->common.arg_info[i].class_name, '\\', fe->common.arg_info[i].class_name_len)) == NULL || strcasecmp(colon+1, proto->common.arg_info[i].class_name) != 0) { zend_class_entry **fe_ce, **proto_ce; int found, found2; found = zend_lookup_class(fe->common.arg_info[i].class_name, fe->common.arg_info[i].class_name_len, &fe_ce TSRMLS_CC); found2 = zend_lookup_class(proto->common.arg_info[i].class_name, proto->common.arg_info[i].class_name_len, &proto_ce TSRMLS_CC); /* Check for class alias */ if (found != SUCCESS || found2 != SUCCESS || (*fe_ce)->type == ZEND_INTERNAL_CLASS || (*proto_ce)->type == ZEND_INTERNAL_CLASS || *fe_ce != *proto_ce) { return 0; } } } if (fe->common.arg_info[i].type_hint != proto->common.arg_info[i].type_hint) { /* Incompatible type hint */ return 0; } /* by-ref constraints on arguments are invariant */ if (fe->common.arg_info[i].pass_by_reference != proto->common.arg_info[i].pass_by_reference) { return 0; } } if (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) { for (i=proto->common.num_args; i < fe->common.num_args; i++) { if (!fe->common.arg_info[i].pass_by_reference) { return 0; } } } return 1; } /* }}} */ #define REALLOC_BUF_IF_EXCEED(buf, offset, length, size) \ if (UNEXPECTED(offset - buf + size >= length)) { \ length += size + 1; \ buf = erealloc(buf, length); \ } static char * zend_get_function_declaration(zend_function *fptr TSRMLS_DC) /* {{{ */ { char *offset, *buf; zend_uint length = 1024; offset = buf = (char *)emalloc(length * sizeof(char)); if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { *(offset++) = '&'; *(offset++) = ' '; } if (fptr->common.scope) { memcpy(offset, fptr->common.scope->name, fptr->common.scope->name_length); offset += fptr->common.scope->name_length; *(offset++) = ':'; *(offset++) = ':'; } { size_t name_len = strlen(fptr->common.function_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, name_len); memcpy(offset, fptr->common.function_name, name_len); offset += name_len; } *(offset++) = '('; if (fptr->common.arg_info) { zend_uint i, required; zend_arg_info *arg_info = fptr->common.arg_info; required = fptr->common.required_num_args; for (i = 0; i < fptr->common.num_args;) { if (arg_info->class_name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->class_name_len); memcpy(offset, arg_info->class_name, arg_info->class_name_len); offset += arg_info->class_name_len; *(offset++) = ' '; } else if (arg_info->type_hint) { zend_uint type_name_len; char *type_name = zend_get_type_by_const(arg_info->type_hint); type_name_len = strlen(type_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, type_name_len); memcpy(offset, type_name, type_name_len); offset += type_name_len; *(offset++) = ' '; } if (arg_info->pass_by_reference) { *(offset++) = '&'; } *(offset++) = '$'; if (arg_info->name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->name_len); memcpy(offset, arg_info->name, arg_info->name_len); offset += arg_info->name_len; } else { zend_uint idx = i; memcpy(offset, "param", 5); offset += 5; do { *(offset++) = (char) (idx % 10) + '0'; idx /= 10; } while (idx > 0); } if (i >= required) { *(offset++) = ' '; *(offset++) = '='; *(offset++) = ' '; if (fptr->type == ZEND_USER_FUNCTION) { zend_op *precv = NULL; { zend_uint idx = i; zend_op *op = ((zend_op_array *)fptr)->opcodes; zend_op *end = op + ((zend_op_array *)fptr)->last; ++idx; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT) && op->op1.num == (long)idx) { precv = op; } ++op; } } if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) { zval *zv, zv_copy; int use_copy; ALLOC_ZVAL(zv); *zv = *precv->op2.zv; zval_copy_ctor(zv); INIT_PZVAL(zv); zval_update_constant_ex(&zv, (void*)1, fptr->common.scope TSRMLS_CC); if (Z_TYPE_P(zv) == IS_BOOL) { if (Z_LVAL_P(zv)) { memcpy(offset, "true", 4); offset += 4; } else { memcpy(offset, "false", 5); offset += 5; } } else if (Z_TYPE_P(zv) == IS_NULL) { memcpy(offset, "NULL", 4); offset += 4; } else if (Z_TYPE_P(zv) == IS_STRING) { *(offset++) = '\''; REALLOC_BUF_IF_EXCEED(buf, offset, length, MIN(Z_STRLEN_P(zv), 10)); memcpy(offset, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 10)); offset += MIN(Z_STRLEN_P(zv), 10); if (Z_STRLEN_P(zv) > 10) { *(offset++) = '.'; *(offset++) = '.'; *(offset++) = '.'; } *(offset++) = '\''; } else if (Z_TYPE_P(zv) == IS_ARRAY) { memcpy(offset, "Array", 5); offset += 5; } else { zend_make_printable_zval(zv, &zv_copy, &use_copy); REALLOC_BUF_IF_EXCEED(buf, offset, length, Z_STRLEN(zv_copy)); memcpy(offset, Z_STRVAL(zv_copy), Z_STRLEN(zv_copy)); offset += Z_STRLEN(zv_copy); if (use_copy) { zval_dtor(&zv_copy); } } zval_ptr_dtor(&zv); } } else { memcpy(offset, "NULL", 4); offset += 4; } } if (++i < fptr->common.num_args) { *(offset++) = ','; *(offset++) = ' '; } arg_info++; REALLOC_BUF_IF_EXCEED(buf, offset, length, 32); } } *(offset++) = ')'; *offset = '\0'; return buf; } /* }}} */ static void do_inheritance_check_on_method(zend_function *child, zend_function *parent TSRMLS_DC) /* {{{ */ { zend_uint child_flags; zend_uint parent_flags = parent->common.fn_flags; if ((parent->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && parent->common.fn_flags & ZEND_ACC_ABSTRACT && parent->common.scope != (child->common.prototype ? child->common.prototype->common.scope : child->common.scope) && child->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_IMPLEMENTED_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Can't inherit abstract function %s::%s() (previously declared abstract in %s)", parent->common.scope->name, child->common.function_name, child->common.prototype ? child->common.prototype->common.scope->name : child->common.scope->name); } if (parent_flags & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot override final method %s::%s()", ZEND_FN_SCOPE_NAME(parent), child->common.function_name); } child_flags = child->common.fn_flags; /* You cannot change from static to non static and vice versa. */ if ((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC)) { if (child->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot make non static method %s::%s() static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } else { zend_error(E_COMPILE_ERROR, "Cannot make static method %s::%s() non static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } } /* Disallow making an inherited method abstract. */ if ((child_flags & ZEND_ACC_ABSTRACT) && !(parent_flags & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Cannot make non abstract method %s::%s() abstract in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } if (parent_flags & ZEND_ACC_CHANGED) { child->common.fn_flags |= ZEND_ACC_CHANGED; } else { /* Prevent derived classes from restricting access that was available in parent classes */ if ((child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::%s() must be %s (as in class %s)%s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if (((child_flags & ZEND_ACC_PPP_MASK) < (parent_flags & ZEND_ACC_PPP_MASK)) && ((parent_flags & ZEND_ACC_PPP_MASK) & ZEND_ACC_PRIVATE)) { child->common.fn_flags |= ZEND_ACC_CHANGED; } } if (parent_flags & ZEND_ACC_PRIVATE) { child->common.prototype = NULL; } else if (parent_flags & ZEND_ACC_ABSTRACT) { child->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; child->common.prototype = parent; } else if (!(parent->common.fn_flags & ZEND_ACC_CTOR) || (parent->common.prototype && (parent->common.prototype->common.scope->ce_flags & ZEND_ACC_INTERFACE))) { /* ctors only have a prototype if it comes from an interface */ child->common.prototype = parent->common.prototype ? parent->common.prototype : parent; } if (child->common.prototype && (child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { if (!zend_do_perform_implementation_check(child, child->common.prototype TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s::%s() must be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_get_function_declaration(child->common.prototype TSRMLS_CC)); } } else if (EG(error_reporting) & E_STRICT || EG(user_error_handler)) { /* Check E_STRICT (or custom error handler) before the check so that we save some time */ if (!zend_do_perform_implementation_check(child, parent TSRMLS_CC)) { char *method_prototype = zend_get_function_declaration(child->common.prototype TSRMLS_CC); zend_error(E_STRICT, "Declaration of %s::%s() should be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, method_prototype); efree(method_prototype); } } } /* }}} */ static zend_bool do_inherit_method_check(HashTable *child_function_table, zend_function *parent, const zend_hash_key *hash_key, zend_class_entry *child_ce) /* {{{ */ { zend_uint parent_flags = parent->common.fn_flags; zend_function *child; TSRMLS_FETCH(); if (zend_hash_quick_find(child_function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child)==FAILURE) { if (parent_flags & (ZEND_ACC_ABSTRACT)) { child_ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } return 1; /* method doesn't exist in child, copy from parent */ } do_inheritance_check_on_method(child, parent TSRMLS_CC); return 0; } /* }}} */ static zend_bool do_inherit_property_access_check(HashTable *target_ht, zend_property_info *parent_info, const zend_hash_key *hash_key, zend_class_entry *ce) /* {{{ */ { zend_property_info *child_info; zend_class_entry *parent_ce = ce->parent; if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW)) { if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { child_info->flags |= ZEND_ACC_CHANGED; } else { zend_hash_quick_update(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, parent_info, sizeof(zend_property_info), (void **) &child_info); if(ce->type & ZEND_INTERNAL_CLASS) { zend_duplicate_property_info_internal(child_info); } else { zend_duplicate_property_info(child_info); } child_info->flags &= ~ZEND_ACC_PRIVATE; /* it's not private anymore */ child_info->flags |= ZEND_ACC_SHADOW; /* but it's a shadow of private */ } return 0; /* don't copy access information to child */ } if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { if ((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s", (parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", parent_ce->name, hash_key->arKey, (child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ce->name, hash_key->arKey); } if(parent_info->flags & ZEND_ACC_CHANGED) { child_info->flags |= ZEND_ACC_CHANGED; } if ((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ce->name, hash_key->arKey, zend_visibility_string(parent_info->flags), parent_ce->name, (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if ((child_info->flags & ZEND_ACC_STATIC) == 0) { Z_DELREF_P(ce->default_properties_table[parent_info->offset]); ce->default_properties_table[parent_info->offset] = ce->default_properties_table[child_info->offset]; ce->default_properties_table[child_info->offset] = NULL; child_info->offset = parent_info->offset; } return 0; /* Don't copy from parent */ } else { return 1; /* Copy from parent */ } } /* }}} */ static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce TSRMLS_CC) == FAILURE) { zend_error(E_CORE_ERROR, "Class %s could not implement interface %s", ce->name, iface->name); } if (ce == iface) { zend_error(E_ERROR, "Interface %s cannot implement itself", ce->name); } } /* }}} */ ZEND_API void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface TSRMLS_DC) /* {{{ */ { /* expects interface to be contained in ce's interface list already */ zend_uint i, ce_num, if_num = iface->num_interfaces; zend_class_entry *entry; if (if_num==0) { return; } ce_num = ce->num_interfaces; if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } /* Inherit the interfaces, only if they're not already inherited by the class */ while (if_num--) { entry = iface->interfaces[if_num]; for (i = 0; i < ce_num; i++) { if (ce->interfaces[i] == entry) { break; } } if (i == ce_num) { ce->interfaces[ce->num_interfaces++] = entry; } } /* and now call the implementing handlers */ while (ce_num < ce->num_interfaces) { do_implement_interface(ce, ce->interfaces[ce_num++] TSRMLS_CC); } } /* }}} */ #ifdef ZTS static void zval_internal_ctor(zval **p) /* {{{ */ { zval *orig_ptr = *p; ALLOC_ZVAL(*p); MAKE_COPY_ZVAL(&orig_ptr, *p); } /* }}} */ # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) (((parent_ce)->type != (ce)->type) ? zval_internal_ctor : zval_add_ref)) #else # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) zval_add_ref) #endif ZEND_API void zend_do_inheritance(zend_class_entry *ce, zend_class_entry *parent_ce TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; if ((ce->ce_flags & ZEND_ACC_INTERFACE) && !(parent_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ce->name, parent_ce->name); } if (parent_ce->ce_flags & ZEND_ACC_FINAL_CLASS) { zend_error(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ce->name, parent_ce->name); } ce->parent = parent_ce; /* Copy serialize/unserialize callbacks */ if (!ce->serialize) { ce->serialize = parent_ce->serialize; } if (!ce->unserialize) { ce->unserialize = parent_ce->unserialize; } /* Inherit interfaces */ zend_do_inherit_interfaces(ce, parent_ce TSRMLS_CC); /* Inherit properties */ if (parent_ce->default_properties_count) { int i = ce->default_properties_count + parent_ce->default_properties_count; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_properties_count) { while (i-- > parent_ce->default_properties_count) { ce->default_properties_table[i] = ce->default_properties_table[i - parent_ce->default_properties_count]; } } for (i = 0; i < parent_ce->default_properties_count; i++) { ce->default_properties_table[i] = parent_ce->default_properties_table[i]; if (ce->default_properties_table[i]) { #ifdef ZTS if (parent_ce->type != ce->type) { zval *p; ALLOC_ZVAL(p); MAKE_COPY_ZVAL(&ce->default_properties_table[i], p); ce->default_properties_table[i] = p; } else { Z_ADDREF_P(ce->default_properties_table[i]); } #else Z_ADDREF_P(ce->default_properties_table[i]); #endif } } ce->default_properties_count += parent_ce->default_properties_count; } if (parent_ce->type != ce->type) { /* User class extends internal class */ zend_update_class_constants(parent_ce TSRMLS_CC); if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = erealloc(ce->default_static_members_table, sizeof(void*) * i); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&CE_STATIC_MEMBERS(parent_ce)[i]); ce->default_static_members_table[i] = CE_STATIC_MEMBERS(parent_ce)[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; ce->static_members_table = ce->default_static_members_table; } } else { if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&parent_ce->default_static_members_table[i]); ce->default_static_members_table[i] = parent_ce->default_static_members_table[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } } for (zend_hash_internal_pointer_reset(&ce->properties_info); zend_hash_get_current_data(&ce->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->properties_info)) { if (property_info->ce == ce) { if (property_info->flags & ZEND_ACC_STATIC) { property_info->offset += parent_ce->default_static_members_count; } else { property_info->offset += parent_ce->default_properties_count; } } } zend_hash_merge_ex(&ce->properties_info, &parent_ce->properties_info, (copy_ctor_func_t) (ce->type & ZEND_INTERNAL_CLASS ? zend_duplicate_property_info_internal : zend_duplicate_property_info), sizeof(zend_property_info), (merge_checker_func_t) do_inherit_property_access_check, ce); zend_hash_merge(&ce->constants_table, &parent_ce->constants_table, zval_property_ctor(parent_ce, ce), NULL, sizeof(zval *), 0); zend_hash_merge_ex(&ce->function_table, &parent_ce->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_inherit_parent_constructor(ce); if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS && ce->type == ZEND_INTERNAL_CLASS) { ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } else if (!(ce->ce_flags & ZEND_ACC_IMPLEMENT_INTERFACES) && !(ce->ce_flags & ZEND_ACC_IMPLEMENT_TRAITS)) { /* The verification will be done in runtime by ZEND_VERIFY_ABSTRACT_CLASS */ zend_verify_abstract_class(ce TSRMLS_CC); } ce->ce_flags |= parent_ce->ce_flags & ZEND_HAS_STATIC_IN_METHODS; } /* }}} */ static zend_bool do_inherit_constant_check(HashTable *child_constants_table, const zval **parent_constant, const zend_hash_key *hash_key, const zend_class_entry *iface) /* {{{ */ { zval **old_constant; if (zend_hash_quick_find(child_constants_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**)&old_constant) == SUCCESS) { if (*old_constant != *parent_constant) { zend_error(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", hash_key->arKey, iface->name); } return 0; } return 1; } /* }}} */ static int do_interface_constant_check(zval **val TSRMLS_DC, int num_args, va_list args, const zend_hash_key *key) /* {{{ */ { zend_class_entry **iface = va_arg(args, zend_class_entry**); do_inherit_constant_check(&(*iface)->constants_table, (const zval **) val, key, *iface); return ZEND_HASH_APPLY_KEEP; } /* }}} */ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_iface_num = ce->num_interfaces; zend_uint parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0; for (i = 0; i < ce->num_interfaces; i++) { if (ce->interfaces[i] == NULL) { memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i)); i--; } else if (ce->interfaces[i] == iface) { if (i < parent_iface_num) { ignore = 1; } else { zend_error(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ce->name, iface->name); } } } if (ignore) { /* Check for attempt to redeclare interface constants */ zend_hash_apply_with_arguments(&ce->constants_table TSRMLS_CC, (apply_func_args_t) do_interface_constant_check, 1, &iface); } else { if (ce->num_interfaces >= current_iface_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } } ce->interfaces[ce->num_interfaces++] = iface; zend_hash_merge_ex(&ce->constants_table, &iface->constants_table, (copy_ctor_func_t) zval_add_ref, sizeof(zval *), (merge_checker_func_t) do_inherit_constant_check, iface); zend_hash_merge_ex(&ce->function_table, &iface->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_implement_interface(ce, iface TSRMLS_CC); zend_do_inherit_interfaces(ce, iface TSRMLS_CC); } } /* }}} */ ZEND_API void zend_do_implement_trait(zend_class_entry *ce, zend_class_entry *trait TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_trait_num = ce->num_traits; zend_uint parent_trait_num = ce->parent ? ce->parent->num_traits : 0; for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == NULL) { memmove(ce->traits + i, ce->traits + i + 1, sizeof(zend_class_entry*) * (--ce->num_traits - i)); i--; } else if (ce->traits[i] == trait) { if (i < parent_trait_num) { ignore = 1; } } } if (!ignore) { if (ce->num_traits >= current_trait_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->traits = (zend_class_entry **) realloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } else { ce->traits = (zend_class_entry **) erealloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } } ce->traits[ce->num_traits++] = trait; } } /* }}} */ static int zend_traits_merge_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { size_t current; size_t i; size_t count; HashTable* resulting_table; HashTable** function_tables; zend_class_entry *ce; size_t collision = 0; size_t abstract_solved = 0; zend_function* other_trait_fn; current = va_arg(args, size_t); /* index of current trait */ count = va_arg(args, size_t); resulting_table = va_arg(args, HashTable*); function_tables = va_arg(args, HashTable**); ce = va_arg(args, zend_class_entry*); for (i = 0; i < count; i++) { if (i == current) { continue; /* just skip this, cause its the table this function is applied on */ } if (zend_hash_quick_find(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&other_trait_fn) == SUCCESS) { /* if it is an abstract method, there is no collision */ if (other_trait_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* In case both are abstract, just check prototype, but need to do that in both directions */ if ( !zend_do_perform_implementation_check(fn, other_trait_fn TSRMLS_CC) || !zend_do_perform_implementation_check(other_trait_fn, fn TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s must be compatible with %s", //ZEND_FN_SCOPE_NAME(fn), fn->common.function_name, //::%s() zend_get_function_declaration(fn TSRMLS_CC), zend_get_function_declaration(other_trait_fn TSRMLS_CC)); } } else { /* otherwise, do the full check */ do_inheritance_check_on_method(fn, other_trait_fn TSRMLS_CC); } /* we can savely free and remove it from other table */ zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } else { /* if it is not an abstract method, there is still no collision */ /* if fn is an abstract method */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible. Here, we already know other_trait_fn cannot be abstract, full check ok. */ do_inheritance_check_on_method(other_trait_fn, fn TSRMLS_CC); /* just mark as solved, will be added if its own trait is processed */ abstract_solved = 1; } else { /* but else, we have a collision of non-abstract methods */ collision++; zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } } } if (collision) { zend_function* class_fn; /* make sure method is not already overridden in class */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&class_fn) == FAILURE || class_fn->common.scope != ce) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because there are collisions with other trait methods on %s", fn->common.function_name, ce->name); } zend_function_dtor(fn); } else if (abstract_solved) { zend_function_dtor(fn); } else { /* Add it to result function table */ if (zend_hash_quick_add(resulting_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, fn, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating resulting trait method table", fn->common.function_name); } } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ /* {{{ Originates from php_runkit_function_copy_ctor Duplicate structures in an op_array where necessary to make an outright duplicate */ static void zend_traits_duplicate_function(zend_function *fe, zend_class_entry *target_ce, char *newname TSRMLS_DC) { zend_literal *literals_copy; zend_compiled_variable *dupvars; zend_op *opcode_copy; zval class_name_zv; int class_name_literal; int i; int number_of_literals; if (fe->op_array.static_variables) { HashTable *tmpHash; ALLOC_HASHTABLE(tmpHash); zend_hash_init(tmpHash, zend_hash_num_elements(fe->op_array.static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_apply_with_arguments(fe->op_array.static_variables TSRMLS_CC, (apply_func_args_t)zval_copy_static_var, 1, tmpHash); fe->op_array.static_variables = tmpHash; } number_of_literals = fe->op_array.last_literal; literals_copy = (zend_literal*)emalloc(number_of_literals * sizeof(zend_literal)); for (i = 0; i < number_of_literals; i++) { literals_copy[i] = fe->op_array.literals[i]; zval_copy_ctor(&literals_copy[i].constant); } fe->op_array.literals = literals_copy; fe->op_array.refcount = emalloc(sizeof(zend_uint)); *(fe->op_array.refcount) = 1; if (fe->op_array.vars) { i = fe->op_array.last_var; dupvars = safe_emalloc(fe->op_array.last_var, sizeof(zend_compiled_variable), 0); while (i > 0) { i--; dupvars[i].name = estrndup(fe->op_array.vars[i].name, fe->op_array.vars[i].name_len); dupvars[i].name_len = fe->op_array.vars[i].name_len; dupvars[i].hash_value = fe->op_array.vars[i].hash_value; } fe->op_array.vars = dupvars; } else { fe->op_array.vars = NULL; } opcode_copy = safe_emalloc(sizeof(zend_op), fe->op_array.last, 0); for(i = 0; i < fe->op_array.last; i++) { opcode_copy[i] = fe->op_array.opcodes[i]; if (opcode_copy[i].op1_type != IS_CONST) { switch (opcode_copy[i].opcode) { case ZEND_GOTO: case ZEND_JMP: if (opcode_copy[i].op1.jmp_addr && opcode_copy[i].op1.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op1.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op1.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op1.jmp_addr - fe->op_array.opcodes); } break; } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op1.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op1.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op1.zv = &fe->op_array.literals[class_name_literal].constant; } } if (opcode_copy[i].op2_type != IS_CONST) { switch (opcode_copy[i].opcode) { case ZEND_JMPZ: case ZEND_JMPNZ: case ZEND_JMPZ_EX: case ZEND_JMPNZ_EX: case ZEND_JMP_SET: case ZEND_JMP_SET_VAR: if (opcode_copy[i].op2.jmp_addr && opcode_copy[i].op2.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op2.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op2.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op2.jmp_addr - fe->op_array.opcodes); } break; } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op2.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op2.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op2.zv = &fe->op_array.literals[class_name_literal].constant; } } } fe->op_array.opcodes = opcode_copy; fe->op_array.function_name = newname; /* was setting it to fe which does not work since fe is stack allocated and not a stable address */ /* fe->op_array.prototype = fe->op_array.prototype; */ if (fe->op_array.arg_info) { zend_arg_info *tmpArginfo; tmpArginfo = safe_emalloc(sizeof(zend_arg_info), fe->op_array.num_args, 0); for(i = 0; i < fe->op_array.num_args; i++) { tmpArginfo[i] = fe->op_array.arg_info[i]; tmpArginfo[i].name = estrndup(tmpArginfo[i].name, tmpArginfo[i].name_len); if (tmpArginfo[i].class_name) { tmpArginfo[i].class_name = estrndup(tmpArginfo[i].class_name, tmpArginfo[i].class_name_len); } } fe->op_array.arg_info = tmpArginfo; } fe->op_array.doc_comment = estrndup(fe->op_array.doc_comment, fe->op_array.doc_comment_len); fe->op_array.try_catch_array = (zend_try_catch_element*)estrndup((char*)fe->op_array.try_catch_array, sizeof(zend_try_catch_element) * fe->op_array.last_try_catch); fe->op_array.brk_cont_array = (zend_brk_cont_element*)estrndup((char*)fe->op_array.brk_cont_array, sizeof(zend_brk_cont_element) * fe->op_array.last_brk_cont); } /* }}} */ static void zend_add_magic_methods(zend_class_entry* ce, const char* mname, uint mname_len, zend_function* fe TSRMLS_DC) /* {{{ */ { if (!strncmp(mname, ZEND_CLONE_FUNC_NAME, mname_len)) { ce->clone = fe; fe->common.fn_flags |= ZEND_ACC_CLONE; } else if (!strncmp(mname, ZEND_CONSTRUCTOR_FUNC_NAME, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } else if (!strncmp(mname, ZEND_DESTRUCTOR_FUNC_NAME, mname_len)) { ce->destructor = fe; fe->common.fn_flags |= ZEND_ACC_DTOR; } else if (!strncmp(mname, ZEND_GET_FUNC_NAME, mname_len)) { ce->__get = fe; } else if (!strncmp(mname, ZEND_SET_FUNC_NAME, mname_len)) { ce->__set = fe; } else if (!strncmp(mname, ZEND_CALL_FUNC_NAME, mname_len)) { ce->__call = fe; } else if (!strncmp(mname, ZEND_UNSET_FUNC_NAME, mname_len)) { ce->__unset = fe; } else if (!strncmp(mname, ZEND_ISSET_FUNC_NAME, mname_len)) { ce->__isset = fe; } else if (!strncmp(mname, ZEND_CALLSTATIC_FUNC_NAME, mname_len)) { ce->__callstatic = fe; } else if (!strncmp(mname, ZEND_TOSTRING_FUNC_NAME, mname_len)) { ce->__tostring = fe; } else if (ce->name_length + 1 == mname_len) { char *lowercase_name = emalloc(ce->name_length + 1); zend_str_tolower_copy(lowercase_name, ce->name, ce->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, ce->name_length + 1, 1 TSRMLS_CC); if (!memcmp(mname, lowercase_name, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } str_efree(lowercase_name); } } /* }}} */ static int zend_traits_merge_functions_to_class(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zend_class_entry *ce = va_arg(args, zend_class_entry*); int add = 0; zend_function* existing_fn = NULL; zend_function fn_copy, *fn_copy_p; zend_function* prototype = NULL; /* is used to determine the prototype according to the inheritance chain */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &existing_fn) == FAILURE) { add = 1; /* not found */ } else if (existing_fn->common.scope != ce) { add = 1; /* or inherited from other class or interface */ } if (add) { zend_function* parent_function; if (ce->parent && zend_hash_quick_find(&ce->parent->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &parent_function) != FAILURE) { prototype = parent_function; /* ->common.fn_flags |= ZEND_ACC_ABSTRACT; */ /* we got that method in the parent class, and are going to override it, except, if the trait is just asking to have an abstract method implemented. */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* then we clean up an skip this method */ zend_function_dtor(fn); return ZEND_HASH_APPLY_REMOVE; } } fn->common.scope = ce; fn->common.prototype = prototype; if (prototype && (prototype->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT || prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { fn->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; } else if (fn->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT) { /* remove ZEND_ACC_IMPLEMENTED_ABSTRACT flag, think it shouldn't be copied to class */ fn->common.fn_flags = fn->common.fn_flags - ZEND_ACC_IMPLEMENTED_ABSTRACT; } /* check whether the trait method fullfills the inheritance requirements */ if (prototype) { do_inheritance_check_on_method(fn, prototype TSRMLS_CC); } /* one more thing: make sure we properly implement an abstract method */ if (existing_fn && existing_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { do_inheritance_check_on_method(fn, existing_fn TSRMLS_CC); } /* delete inherited fn if the function to be added is not abstract */ if (existing_fn && existing_fn->common.scope != ce && (fn->common.fn_flags & ZEND_ACC_ABSTRACT) == 0) { /* it is just a reference which was added to the subclass while doing the inheritance, so we can deleted now, and will add the overriding method afterwards. Except, if we try to add an abstract function, then we should not delete the inherited one */ zend_hash_quick_del(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h); } if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (fn->op_array.static_variables) { ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, ce, estrdup(fn->common.function_name) TSRMLS_CC); if (zend_hash_quick_update(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, &fn_copy, sizeof(zend_function), (void**)&fn_copy_p)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating class method table", hash_key->arKey); } zend_add_magic_methods(ce, hash_key->arKey, hash_key->nKeyLength, fn_copy_p TSRMLS_CC); zend_function_dtor(fn); } else { zend_function_dtor(fn); } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ static int zend_traits_copy_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { HashTable* target; zend_class_entry *target_ce; zend_trait_alias** aliases; HashTable* exclude_table; char* lcname; unsigned int fnname_len; zend_function fn_copy; void* dummy; size_t i = 0; target = va_arg(args, HashTable*); target_ce = va_arg(args, zend_class_entry*); aliases = va_arg(args, zend_trait_alias**); exclude_table = va_arg(args, HashTable*); fnname_len = strlen(fn->common.function_name); /* apply aliases which are qualified with a class name, there should not be any ambiguity */ if (aliases) { while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias != NULL && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && aliases[i]->trait_method->mname_len == fnname_len && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(aliases[i]->alias, aliases[i]->alias_len) TSRMLS_CC); /* if it is 0, no modifieres has been changed */ if (aliases[i]->modifiers) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } lcname = zend_str_tolower_dup(aliases[i]->alias, aliases[i]->alias_len); if (zend_hash_add(target, lcname, aliases[i]->alias_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add aliased trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } efree(lcname); /** Record the trait from which this alias was resolved. */ if (!aliases[i]->trait_method->ce) { aliases[i]->trait_method->ce = fn->common.scope; } } i++; } } lcname = zend_str_tolower_dup(fn->common.function_name, fnname_len); if (exclude_table == NULL || zend_hash_find(exclude_table, lcname, fnname_len, &dummy) == FAILURE) { /* is not in hashtable, thus, function is not to be excluded */ fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(fn->common.function_name, fnname_len) TSRMLS_CC); /* apply aliases which are not qualified by a class name, or which have not * alias name, just setting visibility */ if (aliases) { i = 0; while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias == NULL && aliases[i]->modifiers != 0 && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && (aliases[i]->trait_method->mname_len == fnname_len) && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); /** Record the trait from which this alias was resolved. */ if (!aliases[i]->trait_method->ce) { aliases[i]->trait_method->ce = fn->common.scope; } } i++; } } if (zend_hash_add(target, lcname, fnname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } } efree(lcname); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* Copies function table entries to target function table with applied aliasing */ static void zend_traits_copy_trait_function_table(HashTable *target, zend_class_entry *target_ce, HashTable *source, zend_trait_alias** aliases, HashTable* exclude_table TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_arguments(source TSRMLS_CC, (apply_func_args_t)zend_traits_copy_functions, 4, target, target_ce, aliases, exclude_table); } /* }}} */ static void zend_traits_init_trait_structures(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i, j = 0; zend_trait_precedence *cur_precedence; zend_trait_method_reference *cur_method_ref; char *lcname; zend_bool method_exists; /* resolve class references */ if (ce->trait_precedences) { i = 0; while ((cur_precedence = ce->trait_precedences[i])) { /** Resolve classes for all precedence operations. */ if (cur_precedence->exclude_from_classes) { cur_method_ref = cur_precedence->trait_method; cur_precedence->trait_method->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); /** Ensure that the prefered method is actually available. */ lcname = zend_str_tolower_dup(cur_method_ref->method_name, cur_method_ref->mname_len); method_exists = zend_hash_exists(&cur_method_ref->ce->function_table, lcname, cur_method_ref->mname_len + 1); efree(lcname); if (!method_exists) { zend_error(E_COMPILE_ERROR, "A precedence rule was defined for %s::%s but this method does not exist", cur_method_ref->ce->name, cur_method_ref->method_name); } /** With the other traits, we are more permissive. We do not give errors for those. This allows to be more defensive in such definitions. */ j = 0; while (cur_precedence->exclude_from_classes[j]) { char* class_name = (char*)cur_precedence->exclude_from_classes[j]; zend_uint name_length = strlen(class_name); cur_precedence->exclude_from_classes[j] = zend_fetch_class(class_name, name_length, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); efree(class_name); j++; } } i++; } } if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { /** For all aliases with an explicit class name, resolve the class now. */ if (ce->trait_aliases[i]->trait_method->class_name) { cur_method_ref = ce->trait_aliases[i]->trait_method; cur_method_ref->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); /** And, ensure that the referenced method is resolvable, too. */ lcname = zend_str_tolower_dup(cur_method_ref->method_name, cur_method_ref->mname_len); method_exists = zend_hash_exists(&cur_method_ref->ce->function_table, lcname, cur_method_ref->mname_len + 1); efree(lcname); if (!method_exists) { zend_error(E_COMPILE_ERROR, "An alias was defined for %s::%s but this method does not exist", cur_method_ref->ce->name, cur_method_ref->method_name); } } i++; } } } /* }}} */ static void zend_traits_compile_exclude_table(HashTable* exclude_table, zend_trait_precedence **precedences, zend_class_entry *trait) /* {{{ */ { size_t i = 0, j; if (!precedences) { return; } while (precedences[i]) { if (precedences[i]->exclude_from_classes) { j = 0; while (precedences[i]->exclude_from_classes[j]) { if (precedences[i]->exclude_from_classes[j] == trait) { zend_uint lcname_len = precedences[i]->trait_method->mname_len; char *lcname = zend_str_tolower_dup(precedences[i]->trait_method->method_name, lcname_len); if (zend_hash_add(exclude_table, lcname, lcname_len, NULL, 0, NULL) == FAILURE) { efree(lcname); zend_error(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", precedences[i]->trait_method->method_name, trait->name); } efree(lcname); } ++j; } } ++i; } } /* }}} */ static void zend_do_traits_method_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { HashTable** function_tables; HashTable* resulting_table; HashTable exclude_table; size_t i; /* prepare copies of trait function tables for combination */ function_tables = malloc(sizeof(HashTable*) * ce->num_traits); resulting_table = (HashTable *) malloc(sizeof(HashTable)); /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(resulting_table, 10, NULL, NULL, 1, 0); for (i = 0; i < ce->num_traits; i++) { function_tables[i] = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(function_tables[i], ce->traits[i]->function_table.nNumOfElements, NULL, NULL, 1, 0); if (ce->trait_precedences) { /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(&exclude_table, 2, NULL, NULL, 0, 0); zend_traits_compile_exclude_table(&exclude_table, ce->trait_precedences, ce->traits[i]); /* copies functions, applies defined aliasing, and excludes unused trait methods */ zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, &exclude_table TSRMLS_CC); zend_hash_graceful_destroy(&exclude_table); } else { zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, NULL TSRMLS_CC); } } /* now merge trait methods */ for (i = 0; i < ce->num_traits; i++) { zend_hash_apply_with_arguments(function_tables[i] TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions, 5, i, ce->num_traits, resulting_table, function_tables, ce); } /* Now the resulting_table contains all trait methods we would have to * add to the class in the following step the methods are inserted into the method table * if there is already a method with the same name it is replaced iff ce != fn.scope * --> all inherited methods are overridden, methods defined in the class are left untouched */ zend_hash_apply_with_arguments(resulting_table TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions_to_class, 1, ce); /* free temporary function tables */ for (i = 0; i < ce->num_traits; i++) { /* zend_hash_destroy(function_tables[i]); */ zend_hash_graceful_destroy(function_tables[i]); free(function_tables[i]); } free(function_tables); /* free temporary resulting table */ /* zend_hash_destroy(resulting_table); */ zend_hash_graceful_destroy(resulting_table); free(resulting_table); } /* }}} */ static zend_class_entry* find_first_definition(zend_class_entry *ce, size_t current_trait, const char* prop_name, int prop_name_length, ulong prop_hash, zend_class_entry *coliding_ce) /* {{{ */ { size_t i; zend_property_info *coliding_prop; for (i = 0; (i < current_trait) && (i < ce->num_traits); i++) { if (zend_hash_quick_find(&ce->traits[i]->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS) { return ce->traits[i]; } } return coliding_ce; } /* }}} */ static void zend_do_traits_property_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i; zend_property_info *property_info; zend_property_info *coliding_prop; zval compare_result; const char* prop_name; int prop_name_length; ulong prop_hash; const char* class_name_unused; zend_bool prop_found; zend_bool not_compatible; zval* prop_value; /* In the following steps the properties are inserted into the property table * for that, a very strict approach is applied: * - check for compatibility, if not compatible with any property in class -> fatal * - if compatible, then strict notice */ for (i = 0; i < ce->num_traits; i++) { for (zend_hash_internal_pointer_reset(&ce->traits[i]->properties_info); zend_hash_get_current_data(&ce->traits[i]->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->traits[i]->properties_info)) { /* first get the unmangeld name if necessary, * then check whether the property is already there */ if ((property_info->flags & ZEND_ACC_PPP_MASK) == ZEND_ACC_PUBLIC) { prop_hash = property_info->h; prop_name = property_info->name; prop_name_length = property_info->name_length; prop_found = zend_hash_quick_find(&ce->properties_info, property_info->name, property_info->name_length+1, property_info->h, (void **) &coliding_prop) == SUCCESS; } else { /* for private and protected we need to unmangle the names */ zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name_unused, &prop_name); prop_name_length = strlen(prop_name); prop_hash = zend_get_hash_value(prop_name, prop_name_length + 1); prop_found = zend_hash_quick_find(&ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS; } /* next: check for conflicts with current class */ if (prop_found) { if (coliding_prop->flags & ZEND_ACC_SHADOW) { /* this one is inherited, lets look it up in its own class */ zend_hash_quick_find(&coliding_prop->ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop); } if ( (coliding_prop->flags & (ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC)) == (property_info->flags & (ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC))) { /* flags are identical, now the value needs to be checked */ if (property_info->flags & ZEND_ACC_STATIC) { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_static_members_table[coliding_prop->offset], ce->traits[i]->default_static_members_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } else { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_properties_table[coliding_prop->offset], ce->traits[i]->default_properties_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } } else { /* the flags are not identical, thus, we assume properties are not compatible */ not_compatible = 1; } if (not_compatible) { zend_error(E_COMPILE_ERROR, "%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } else { zend_error(E_STRICT, "%s and %s define the same property ($%s) in the composition of %s. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } } /* property not found, so lets add it */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); zend_declare_property_ex(ce, prop_name, prop_name_length, prop_value, property_info->flags, property_info->doc_comment, property_info->doc_comment_len TSRMLS_CC); } } } /* }}} */ static void zend_do_check_for_inconsistent_traits_aliasing(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { int i = 0; zend_trait_alias* cur_alias; char* lc_method_name; if (ce->trait_aliases) { while (ce->trait_aliases[i]) { cur_alias = ce->trait_aliases[i]; /** The trait for this alias has not been resolved, this means, this alias was not applied. Abort with an error. */ if (!cur_alias->trait_method->ce) { if (cur_alias->alias) { /** Plain old inconsistency/typo/bug */ zend_error(E_COMPILE_ERROR, "An alias (%s) was defined for method %s(), but this method does not exist", cur_alias->alias, cur_alias->trait_method->method_name); } else { /** Here are two possible cases: 1) this is an attempt to modifiy the visibility of a method introduce as part of another alias. Since that seems to violate the DRY principle, we check against it and abort. 2) it is just a plain old inconsitency/typo/bug as in the case where alias is set. */ lc_method_name = zend_str_tolower_dup(cur_alias->trait_method->method_name, cur_alias->trait_method->mname_len); if (zend_hash_exists(&ce->function_table, lc_method_name, cur_alias->trait_method->mname_len+1)) { efree(lc_method_name); zend_error(E_COMPILE_ERROR, "The modifiers for the trait alias %s() need to be changed in the same statment in which the alias is defined. Error", cur_alias->trait_method->method_name); } else { efree(lc_method_name); zend_error(E_COMPILE_ERROR, "The modifiers of the trait method %s() are changed, but this method does not exist. Error", cur_alias->trait_method->method_name); } } } i++; } } } /* }}} */ ZEND_API void zend_do_bind_traits(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { if (ce->num_traits <= 0) { return; } /* complete initialization of trait strutures in ce */ zend_traits_init_trait_structures(ce TSRMLS_CC); /* first care about all methods to be flattened into the class */ zend_do_traits_method_binding(ce TSRMLS_CC); /* Aliases which have not been applied indicate typos/bugs. */ zend_do_check_for_inconsistent_traits_aliasing(ce TSRMLS_CC); /* then flatten the properties into it, to, mostly to notfiy developer about problems */ zend_do_traits_property_binding(ce TSRMLS_CC); /* verify that all abstract methods from traits have been implemented */ zend_verify_abstract_class(ce TSRMLS_CC); /* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */ if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { ce->ce_flags -= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } } /* }}} */ ZEND_API int do_bind_function(const zend_op_array *op_array, zend_op *opline, HashTable *function_table, zend_bool compile_time) /* {{{ */ { zend_function *function; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } zend_hash_quick_find(function_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void *) &function); if (zend_hash_quick_add(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), function, sizeof(zend_function), NULL)==FAILURE) { int error_level = compile_time ? E_COMPILE_ERROR : E_ERROR; zend_function *old_function; if (zend_hash_quick_find(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), (void *) &old_function)==SUCCESS && old_function->type == ZEND_USER_FUNCTION && old_function->op_array.last > 0) { zend_error(error_level, "Cannot redeclare %s() (previously declared in %s:%d)", function->common.function_name, old_function->op_array.filename, old_function->op_array.opcodes[0].lineno); } else { zend_error(error_level, "Cannot redeclare %s()", function->common.function_name); } return FAILURE; } else { (*function->op_array.refcount)++; function->op_array.static_variables = NULL; /* NULL out the unbound function */ return SUCCESS; } } /* }}} */ void zend_add_trait_precedence(znode *precedence_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_precedences, precedence_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_add_trait_alias(znode *alias_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_aliases, alias_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_prepare_reference(znode *result, znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { zend_trait_method_reference *method_ref = emalloc(sizeof(zend_trait_method_reference)); method_ref->ce = NULL; /* REM: There should not be a need for copying, zend_do_begin_class_declaration is also just using that string */ if (class_name) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); method_ref->class_name = Z_STRVAL(class_name->u.constant); method_ref->cname_len = Z_STRLEN(class_name->u.constant); } else { method_ref->class_name = NULL; method_ref->cname_len = 0; } method_ref->method_name = Z_STRVAL(method_name->u.constant); method_ref->mname_len = Z_STRLEN(method_name->u.constant); result->u.op.ptr = method_ref; result->op_type = IS_TMP_VAR; } /* }}} */ void zend_prepare_trait_alias(znode *result, znode *method_reference, znode *modifiers, znode *alias TSRMLS_DC) /* {{{ */ { zend_trait_alias *trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_alias->modifiers = Z_LVAL(modifiers->u.constant); if (Z_LVAL(modifiers->u.constant) == ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot use 'static' as method modifier"); return; } if (alias) { trait_alias->alias = Z_STRVAL(alias->u.constant); trait_alias->alias_len = Z_STRLEN(alias->u.constant); } else { trait_alias->alias = NULL; } trait_alias->function = NULL; result->u.op.ptr = trait_alias; } /* }}} */ void zend_prepare_trait_precedence(znode *result, znode *method_reference, znode *trait_list TSRMLS_DC) /* {{{ */ { zend_trait_precedence *trait_precedence = emalloc(sizeof(zend_trait_precedence)); trait_precedence->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_precedence->exclude_from_classes = (zend_class_entry**) trait_list->u.op.ptr; trait_precedence->function = NULL; result->u.op.ptr = trait_precedence; } /* }}} */ ZEND_API zend_class_entry *do_bind_class(const zend_op_array* op_array, const zend_op *opline, HashTable *class_table, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } if (zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce)==FAILURE) { zend_error(E_COMPILE_ERROR, "Internal Zend error - Missing class information for %s", Z_STRVAL_P(op1)); return NULL; } else { ce = *pce; } ce->refcount++; if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), &ce, sizeof(zend_class_entry *), NULL)==FAILURE) { ce->refcount--; if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return NULL; } else { if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLEMENT_INTERFACES))) { zend_verify_abstract_class(ce TSRMLS_CC); } return ce; } } /* }}} */ ZEND_API zend_class_entry *do_bind_inherited_class(const zend_op_array *op_array, const zend_op *opline, HashTable *class_table, zend_class_entry *parent_ce, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; int found_ce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } found_ce = zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce); if (found_ce == FAILURE) { if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", Z_STRVAL_P(op2)); } return NULL; } else { ce = *pce; } if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ce->name, parent_ce->name); } else if ((parent_ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ce->name, parent_ce->name); } zend_do_inheritance(ce, parent_ce TSRMLS_CC); ce->refcount++; /* Register the derived class */ if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), pce, sizeof(zend_class_entry *), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return ce; } /* }}} */ void zend_do_early_binding(TSRMLS_D) /* {{{ */ { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; HashTable *table; while (opline->opcode == ZEND_TICKS && opline > CG(active_op_array)->opcodes) { opline--; } switch (opline->opcode) { case ZEND_DECLARE_FUNCTION: if (do_bind_function(CG(active_op_array), opline, CG(function_table), 1) == FAILURE) { return; } table = CG(function_table); break; case ZEND_DECLARE_CLASS: if (do_bind_class(CG(active_op_array), opline, CG(class_table), 1 TSRMLS_CC) == NULL) { return; } table = CG(class_table); break; case ZEND_DECLARE_INHERITED_CLASS: { zend_op *fetch_class_opline = opline-1; zval *parent_name; zend_class_entry **pce; parent_name = &CONSTANT(fetch_class_opline->op2.constant); if ((zend_lookup_class(Z_STRVAL_P(parent_name), Z_STRLEN_P(parent_name), &pce TSRMLS_CC) == FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_CLASSES) && ((*pce)->type == ZEND_INTERNAL_CLASS))) { if (CG(compiler_options) & ZEND_COMPILE_DELAYED_BINDING) { zend_uint *opline_num = &CG(active_op_array)->early_binding; while (*opline_num != -1) { opline_num = &CG(active_op_array)->opcodes[*opline_num].result.opline_num; } *opline_num = opline - CG(active_op_array)->opcodes; opline->opcode = ZEND_DECLARE_INHERITED_CLASS_DELAYED; opline->result_type = IS_UNUSED; opline->result.opline_num = -1; } return; } if (do_bind_inherited_class(CG(active_op_array), opline, CG(class_table), *pce, 1 TSRMLS_CC) == NULL) { return; } /* clear unnecessary ZEND_FETCH_CLASS opcode */ zend_del_literal(CG(active_op_array), fetch_class_opline->op2.constant); MAKE_NOP(fetch_class_opline); table = CG(class_table); break; } case ZEND_VERIFY_ABSTRACT_CLASS: case ZEND_ADD_INTERFACE: case ZEND_ADD_TRAIT: case ZEND_BIND_TRAITS: /* We currently don't early-bind classes that implement interfaces */ /* Classes with traits are handled exactly the same, no early-bind here */ return; default: zend_error(E_COMPILE_ERROR, "Invalid binding type"); return; } zend_hash_quick_del(table, Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant)), Z_HASH_P(&CONSTANT(opline->op1.constant))); zend_del_literal(CG(active_op_array), opline->op1.constant); zend_del_literal(CG(active_op_array), opline->op2.constant); MAKE_NOP(opline); } /* }}} */ ZEND_API void zend_do_delayed_early_binding(const zend_op_array *op_array TSRMLS_DC) /* {{{ */ { if (op_array->early_binding != -1) { zend_bool orig_in_compilation = CG(in_compilation); zend_uint opline_num = op_array->early_binding; zend_class_entry **pce; CG(in_compilation) = 1; while (opline_num != -1) { if (zend_lookup_class(Z_STRVAL_P(op_array->opcodes[opline_num-1].op2.zv), Z_STRLEN_P(op_array->opcodes[opline_num-1].op2.zv), &pce TSRMLS_CC) == SUCCESS) { do_bind_inherited_class(op_array, &op_array->opcodes[opline_num], EG(class_table), *pce, 0 TSRMLS_CC); } opline_num = op_array->opcodes[opline_num].result.opline_num; } CG(in_compilation) = orig_in_compilation; } } /* }}} */ void zend_do_boolean_or_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_or_end(znode *result, const znode *expr1, const znode *expr2, znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_boolean_and_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_and_end(znode *result, const znode *expr1, const znode *expr2, const znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_do_while_begin(TSRMLS_D) /* {{{ */ { do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_do_while_end(const znode *do_token, const znode *expr_open_bracket, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ; SET_NODE(opline->op1, expr); opline->op2.opline_num = do_token->u.op.opline_num; SET_UNUSED(opline->op2); do_end_loop(expr_open_bracket->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_brk_cont(zend_uchar op, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->op1.opline_num = CG(context).current_brk_cont; SET_UNUSED(opline->op1); if (expr) { if (expr->op_type != IS_CONST) { zend_error(E_COMPILE_ERROR, "'%s' operator with non-constant operand is no longer supported", op == ZEND_BRK ? "break" : "continue"); } else if (Z_TYPE(expr->u.constant) != IS_LONG || Z_LVAL(expr->u.constant) < 1) { zend_error(E_COMPILE_ERROR, "'%s' operator accepts only positive numbers", op == ZEND_BRK ? "break" : "continue"); } SET_NODE(opline->op2, expr); } else { LITERAL_LONG(opline->op2, 1); opline->op2_type = IS_CONST; } } /* }}} */ void zend_do_switch_cond(const znode *cond TSRMLS_DC) /* {{{ */ { zend_switch_entry switch_entry; switch_entry.cond = *cond; switch_entry.default_case = -1; switch_entry.control_var = -1; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_switch_end(const znode *case_list TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); /* add code to jmp to default case */ if (switch_entry_ptr->default_case != -1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->op1.opline_num = switch_entry_ptr->default_case; } if (case_list->op_type != IS_UNUSED) { /* non-empty switch */ int next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* remember break/continue loop information */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; if (switch_entry_ptr->cond.op_type==IS_VAR || switch_entry_ptr->cond.op_type==IS_TMP_VAR) { /* emit free for the switch condition*/ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry_ptr->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_UNUSED(opline->op2); } if (switch_entry_ptr->cond.op_type == IS_CONST) { zval_dtor(&switch_entry_ptr->cond.u.constant); } zend_stack_del_top(&CG(switch_cond_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_case_before_statement(const znode *case_list, znode *case_token, const znode *case_expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); int next_op_number; zend_switch_entry *switch_entry_ptr; znode result; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); if (switch_entry_ptr->control_var == -1) { switch_entry_ptr->control_var = get_temporary_variable(CG(active_op_array)); } opline->opcode = ZEND_CASE; opline->result.var = switch_entry_ptr->control_var; opline->result_type = IS_TMP_VAR; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_NODE(opline->op2, case_expr); if (opline->op1_type == IS_CONST) { zval_copy_ctor(&CONSTANT(opline->op1.constant)); } GET_NODE(&result, opline->result); next_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, &result); SET_UNUSED(opline->op2); case_token->u.op.opline_num = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_case_after_statement(znode *result, const znode *case_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); result->u.op.opline_num = next_op_number; switch (CG(active_op_array)->opcodes[case_token->u.op.opline_num].opcode) { case ZEND_JMP: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); break; case ZEND_JMPZ: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); break; } } /* }}} */ void zend_do_default_before_statement(const znode *case_list, znode *default_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); default_token->u.op.opline_num = next_op_number; next_op_number = get_next_op_number(CG(active_op_array)); switch_entry_ptr->default_case = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_begin_class_declaration(const znode *class_token, znode *class_name, const znode *parent_class_name TSRMLS_DC) /* {{{ */ { zend_op *opline; int doing_inheritance = 0; zend_class_entry *new_class_entry; char *lcname; int error = 0; zval **ns_name, key; if (CG(active_class_entry)) { zend_error(E_COMPILE_ERROR, "Class declarations may not be nested"); return; } lcname = zend_str_tolower_dup(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); if (!(strcmp(lcname, "self") && strcmp(lcname, "parent"))) { efree(lcname); zend_error(E_COMPILE_ERROR, "Cannot use '%s' as class name as it is reserved", Z_STRVAL(class_name->u.constant)); } /* Class name must not conflict with import names */ if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns_name) == SUCCESS) { error = 1; } if (CG(current_namespace)) { /* Prefix class name with name of current namespace */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); class_name = &tmp; efree(lcname); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); } if (error) { char *tmp = zend_str_tolower_dup(Z_STRVAL_PP(ns_name), Z_STRLEN_PP(ns_name)); if (Z_STRLEN_PP(ns_name) != Z_STRLEN(class_name->u.constant) || memcmp(tmp, lcname, Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "Cannot declare class %s because the name is already in use", Z_STRVAL(class_name->u.constant)); } efree(tmp); } new_class_entry = emalloc(sizeof(zend_class_entry)); new_class_entry->type = ZEND_USER_CLASS; new_class_entry->name = zend_new_interned_string(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1, 1 TSRMLS_CC); new_class_entry->name_length = Z_STRLEN(class_name->u.constant); zend_initialize_class_data(new_class_entry, 1 TSRMLS_CC); new_class_entry->info.user.filename = zend_get_compiled_filename(TSRMLS_C); new_class_entry->info.user.line_start = class_token->u.op.opline_num; new_class_entry->ce_flags |= class_token->EA; if (parent_class_name && parent_class_name->op_type != IS_UNUSED) { switch (parent_class_name->EA) { case ZEND_FETCH_CLASS_SELF: zend_error(E_COMPILE_ERROR, "Cannot use 'self' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_PARENT: zend_error(E_COMPILE_ERROR, "Cannot use 'parent' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use 'static' as class name as it is reserved"); break; default: break; } doing_inheritance = 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, new_class_entry->name_length TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; if (doing_inheritance) { /* Make sure a trait does not try to extend a class */ if ((new_class_entry->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "A trait (%s) cannot extend a class", new_class_entry->name); } opline->extended_value = parent_class_name->u.op.var; opline->opcode = ZEND_DECLARE_INHERITED_CLASS; } else { opline->opcode = ZEND_DECLARE_CLASS; } LITERAL_STRINGL(opline->op2, lcname, new_class_entry->name_length, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); zend_hash_quick_update(CG(class_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &new_class_entry, sizeof(zend_class_entry *), NULL); CG(active_class_entry) = new_class_entry; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(&CG(implementing_class), opline->result); if (CG(doc_comment)) { CG(active_class_entry)->info.user.doc_comment = CG(doc_comment); CG(active_class_entry)->info.user.doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ static void do_verify_abstract_class(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_VERIFY_ABSTRACT_CLASS; SET_NODE(opline->op1, &CG(implementing_class)); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_class_declaration(const znode *class_token, const znode *parent_token TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); if (ce->constructor) { ce->constructor->common.fn_flags |= ZEND_ACC_CTOR; if (ce->constructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Constructor %s::%s() cannot be static", ce->name, ce->constructor->common.function_name); } } if (ce->destructor) { ce->destructor->common.fn_flags |= ZEND_ACC_DTOR; if (ce->destructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Destructor %s::%s() cannot be static", ce->name, ce->destructor->common.function_name); } } if (ce->clone) { ce->clone->common.fn_flags |= ZEND_ACC_CLONE; if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static", ce->name, ce->clone->common.function_name); } } ce->info.user.line_end = zend_get_compiled_lineno(TSRMLS_C); /* Check for traits and proceed like with interfaces. * The only difference will be a combined handling of them in the end. * Thus, we need another opcode here. */ if (ce->num_traits > 0) { zend_op *opline; ce->traits = NULL; ce->num_traits = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_TRAITS; /* opcode generation: */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BIND_TRAITS; SET_NODE(opline->op1, &CG(implementing_class)); } if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) && ((parent_token->op_type != IS_UNUSED) || (ce->num_interfaces > 0))) { zend_verify_abstract_class(ce TSRMLS_CC); if (ce->num_interfaces) { do_verify_abstract_class(TSRMLS_C); } } /* Inherit interfaces; reset number to zero, we need it for above check and * will restore it during actual implementation. * The ZEND_ACC_IMPLEMENT_INTERFACES flag disables double call to * zend_verify_abstract_class() */ if (ce->num_interfaces > 0) { ce->interfaces = NULL; ce->num_interfaces = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_INTERFACES; } CG(active_class_entry) = NULL; } /* }}} */ void zend_do_implements_interface(znode *interface_name TSRMLS_DC) /* {{{ */ { zend_op *opline; /* Traits can not implement interfaces */ if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface on '%s' since it is a Trait", Z_STRVAL(interface_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(interface_name->u.constant), Z_STRLEN(interface_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface name as it is reserved", Z_STRVAL(interface_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_INTERFACE; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(interface_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = (opline->extended_value & ~ZEND_FETCH_CLASS_MASK) | ZEND_FETCH_CLASS_INTERFACE; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &interface_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_interfaces++; } /* }}} */ void zend_do_implements_trait(znode *trait_name TSRMLS_DC) /* {{{ */ { zend_op *opline; if ((CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Cannot use traits inside of interfaces. %s is used in %s", Z_STRVAL(trait_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(trait_name->u.constant), Z_STRLEN(trait_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as trait name as it is reserved", Z_STRVAL(trait_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_TRAIT; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(trait_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = ZEND_FETCH_CLASS_TRAIT; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &trait_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_traits++; } /* }}} */ ZEND_API void zend_mangle_property_name(char **dest, int *dest_length, const char *src1, int src1_length, const char *src2, int src2_length, int internal) /* {{{ */ { char *prop_name; int prop_name_length; prop_name_length = 1 + src1_length + 1 + src2_length; prop_name = pemalloc(prop_name_length + 1, internal); prop_name[0] = '\0'; memcpy(prop_name + 1, src1, src1_length+1); memcpy(prop_name + 1 + src1_length + 1, src2, src2_length+1); *dest = prop_name; *dest_length = prop_name_length; } /* }}} */ static int zend_strnlen(const char* s, int maxlen) /* {{{ */ { int len = 0; while (*s++ && maxlen--) len++; return len; } /* }}} */ ZEND_API int zend_unmangle_property_name(const char *mangled_property, int len, const char **class_name, const char **prop_name) /* {{{ */ { int class_name_len; *class_name = NULL; if (mangled_property[0]!=0) { *prop_name = mangled_property; return SUCCESS; } if (len < 3 || mangled_property[1]==0) { zend_error(E_NOTICE, "Illegal member variable name"); *prop_name = mangled_property; return FAILURE; } class_name_len = zend_strnlen(mangled_property+1, --len - 1) + 1; if (class_name_len >= len || mangled_property[class_name_len]!=0) { zend_error(E_NOTICE, "Corrupt member variable name"); *prop_name = mangled_property; return FAILURE; } *class_name = mangled_property+1; *prop_name = (*class_name)+class_name_len; return SUCCESS; } /* }}} */ void zend_do_declare_property(const znode *var_name, const znode *value, zend_uint access_type TSRMLS_DC) /* {{{ */ { zval *property; zend_property_info *existing_property_info; char *comment = NULL; int comment_len = 0; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Interfaces may not include member variables"); } if (access_type & ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Properties cannot be declared abstract"); } if (access_type & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot declare property %s::$%s final, the final modifier is allowed only for methods and classes", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } if (zend_hash_find(&CG(active_class_entry)->properties_info, var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, (void **) &existing_property_info)==SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::$%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } ALLOC_ZVAL(property); if (value) { *property = value->u.constant; } else { INIT_PZVAL(property); Z_TYPE_P(property) = IS_NULL; } if (CG(doc_comment)) { comment = CG(doc_comment); comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } zend_declare_property_ex(CG(active_class_entry), zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len + 1, 0 TSRMLS_CC), var_name->u.constant.value.str.len, property, access_type, comment, comment_len TSRMLS_CC); efree(var_name->u.constant.value.str.val); } /* }}} */ void zend_do_declare_class_constant(znode *var_name, const znode *value TSRMLS_DC) /* {{{ */ { zval *property; const char *cname = NULL; int result; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed in class constants"); return; } if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Traits cannot have constants"); return; } ALLOC_ZVAL(property); *property = value->u.constant; cname = zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, 0 TSRMLS_CC); if (IS_INTERNED(cname)) { result = zend_hash_quick_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, INTERNED_HASH(cname), &property, sizeof(zval *), NULL); } else { result = zend_hash_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, &property, sizeof(zval *), NULL); } if (result == FAILURE) { FREE_ZVAL(property); zend_error(E_COMPILE_ERROR, "Cannot redefine class constant %s::%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } FREE_PNODE(var_name); if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_fetch_property(znode *result, znode *object, const znode *property TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (object->op_type == IS_CV) { if (object->u.op.var == CG(active_op_array)->this_var) { object->op_type = IS_UNUSED; /* this means $this for objects */ } } else if (fetch_list_ptr->count == 1) { zend_llist_element *le = fetch_list_ptr->head; zend_op *opline_ptr = (zend_op *) le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); SET_UNUSED(opline_ptr->op1); /* this means $this for objects */ SET_NODE(opline_ptr->op2, property); /* if it was usual fetch, we change it to object fetch */ switch (opline_ptr->opcode) { case ZEND_FETCH_W: opline_ptr->opcode = ZEND_FETCH_OBJ_W; break; case ZEND_FETCH_R: opline_ptr->opcode = ZEND_FETCH_OBJ_R; break; case ZEND_FETCH_RW: opline_ptr->opcode = ZEND_FETCH_OBJ_RW; break; case ZEND_FETCH_IS: opline_ptr->opcode = ZEND_FETCH_OBJ_IS; break; case ZEND_FETCH_UNSET: opline_ptr->opcode = ZEND_FETCH_OBJ_UNSET; break; case ZEND_FETCH_FUNC_ARG: opline_ptr->opcode = ZEND_FETCH_OBJ_FUNC_ARG; break; } if (opline_ptr->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline_ptr->op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline_ptr->op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op2.constant); } GET_NODE(result, opline_ptr->result); return; } } if (zend_is_function_or_method_call(object)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, object); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_OBJ_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, object); SET_NODE(opline.op2, property); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline.op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op2.constant); } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void zend_do_halt_compiler_register(TSRMLS_D) /* {{{ */ { char *name, *cfilename; char haltoff[] = "__COMPILER_HALT_OFFSET__"; int len, clen; if (CG(has_bracketed_namespaces) && CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "__HALT_COMPILER() can only be used from the outermost scope"); } cfilename = zend_get_compiled_filename(TSRMLS_C); clen = strlen(cfilename); zend_mangle_property_name(&name, &len, haltoff, sizeof(haltoff) - 1, cfilename, clen, 0); zend_register_long_constant(name, len+1, zend_get_scanned_file_offset(TSRMLS_C), CONST_CS, 0 TSRMLS_CC); pefree(name, 0); if (CG(in_namespace)) { zend_do_end_namespace(TSRMLS_C); } } /* }}} */ void zend_do_push_object(const znode *object TSRMLS_DC) /* {{{ */ { zend_stack_push(&CG(object_stack), object, sizeof(znode)); } /* }}} */ void zend_do_pop_object(znode *object TSRMLS_DC) /* {{{ */ { if (object) { znode *tmp; zend_stack_top(&CG(object_stack), (void **) &tmp); *object = *tmp; } zend_stack_del_top(&CG(object_stack)); } /* }}} */ void zend_do_begin_new_object(znode *new_token, znode *class_type TSRMLS_DC) /* {{{ */ { zend_op *opline; unsigned char *ptr = NULL; new_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_NEW; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, class_type); SET_UNUSED(opline->op2); zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(unsigned char *)); } /* }}} */ void zend_do_end_new_object(znode *result, const znode *new_token, const znode *argument_list TSRMLS_DC) /* {{{ */ { znode ctor_result; zend_do_end_function_call(NULL, &ctor_result, argument_list, 1, 0 TSRMLS_CC); zend_do_free(&ctor_result TSRMLS_CC); CG(active_op_array)->opcodes[new_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, CG(active_op_array)->opcodes[new_token->u.op.opline_num].result); } /* }}} */ static zend_constant* zend_get_ct_const(const zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = NULL; if (Z_STRVAL_P(const_name)[0] == '\\') { if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name), (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name)-1); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name), (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } } else if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)+1, (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name)+1, (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } if (c->flags & CONST_CT_SUBST) { return c; } if (all_internal_constants_substitution && (c->flags & CONST_PERSISTENT) && !(CG(compiler_options) & ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION) && Z_TYPE(c->value) != IS_CONSTANT && Z_TYPE(c->value) != IS_CONSTANT_ARRAY) { return c; } return NULL; } /* }}} */ static int zend_constant_ct_subst(znode *result, zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = zend_get_ct_const(const_name, all_internal_constants_substitution TSRMLS_CC); if (c) { zval_dtor(const_name); result->op_type = IS_CONST; result->u.constant = c->value; zval_copy_ctor(&result->u.constant); INIT_PZVAL(&result->u.constant); return 1; } return 0; } /* }}} */ void zend_do_fetch_constant(znode *result, znode *constant_container, znode *constant_name, int mode, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; zend_op *opline; int type; char *compound; ulong fetch_type = 0; if (constant_container) { switch (mode) { case ZEND_CT: /* this is a class constant */ type = zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant)); if (ZEND_FETCH_CLASS_STATIC == type) { zend_error(E_ERROR, "\"static::\" is not allowed in compile-time constants"); } else if (ZEND_FETCH_CLASS_DEFAULT == type) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } zend_do_build_full_name(NULL, constant_container, constant_name, 1 TSRMLS_CC); *result = *constant_container; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: if (constant_container->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant))) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } else { zend_do_fetch_class(&tmp, constant_container TSRMLS_CC); constant_container = &tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); if (constant_container->op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &constant_container->u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, constant_container); } SET_NODE(opline->op2, constant_name); CALCULATE_LITERAL_HASH(opline->op2.constant); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } GET_NODE(result, opline->result); break; } return; } /* namespace constant */ /* only one that did not contain \ from the start can be converted to string if unknown */ switch (mode) { case ZEND_CT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); /* this is a namespace constant, or an unprefixed constant */ if (zend_constant_ct_subst(result, &constant_name->u.constant, 0 TSRMLS_CC)) { break; } zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(!compound) { fetch_type |= IS_CONSTANT_UNQUALIFIED; } *result = *constant_name; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(zend_constant_ct_subst(result, &constant_name->u.constant, 1 TSRMLS_CC)) { break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; if (compound) { /* the name is unambiguous */ opline->extended_value = 0; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } else { opline->extended_value = IS_CONSTANT_UNQUALIFIED; if (CG(current_namespace)) { opline->extended_value |= IS_CONSTANT_IN_NAMESPACE; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 1 TSRMLS_CC); } else { opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } } GET_CACHE_SLOT(opline->op2.constant); break; } } /* }}} */ void zend_do_shell_exec(znode *result, const znode *cmd TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); switch (cmd->op_type) { case IS_CONST: case IS_TMP_VAR: opline->opcode = ZEND_SEND_VAL; break; default: opline->opcode = ZEND_SEND_VAR; break; } SET_NODE(opline->op1, cmd); opline->op2.opline_num = 0; opline->extended_value = ZEND_DO_FCALL; SET_UNUSED(opline->op2); /* FIXME: exception support not added to this op2 */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DO_FCALL; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; LITERAL_STRINGL(opline->op1, estrndup("shell_exec", sizeof("shell_exec")-1), sizeof("shell_exec")-1, 0); CALCULATE_LITERAL_HASH(opline->op1.constant); opline->op1_type = IS_CONST; GET_CACHE_SLOT(opline->op1.constant); opline->extended_value = 1; SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_init_array(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_ARRAY; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; GET_NODE(result, opline->result); if (expr) { SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } } else { SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_array_element(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_ARRAY_ELEMENT; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_static_array_element(znode *result, znode *offset, const znode *expr) /* {{{ */ { zval *element; ALLOC_ZVAL(element); *element = expr->u.constant; if (offset) { switch (offset->u.constant.type & IS_CONSTANT_TYPE_MASK) { case IS_CONSTANT: /* Ugly hack to denote that this value has a constant index */ Z_TYPE_P(element) |= IS_CONSTANT_INDEX; Z_STRVAL(offset->u.constant) = erealloc(Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+1] = Z_TYPE(offset->u.constant); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+2] = 0; zend_symtable_update(result->u.constant.value.ht, Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_STRING: zend_symtable_update(result->u.constant.value.ht, offset->u.constant.value.str.val, offset->u.constant.value.str.len+1, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_NULL: zend_symtable_update(Z_ARRVAL(result->u.constant), "", 1, &element, sizeof(zval *), NULL); break; case IS_LONG: case IS_BOOL: zend_hash_index_update(Z_ARRVAL(result->u.constant), Z_LVAL(offset->u.constant), &element, sizeof(zval *), NULL); break; case IS_DOUBLE: zend_hash_index_update(Z_ARRVAL(result->u.constant), zend_dval_to_lval(Z_DVAL(offset->u.constant)), &element, sizeof(zval *), NULL); break; case IS_CONSTANT_ARRAY: zend_error(E_ERROR, "Illegal offset type"); break; } } else { zend_hash_next_index_insert(Z_ARRVAL(result->u.constant), &element, sizeof(zval *), NULL); } } /* }}} */ void zend_do_add_list_element(const znode *element TSRMLS_DC) /* {{{ */ { list_llist_element lle; if (element) { zend_check_writable_variable(element); lle.var = *element; zend_llist_copy(&lle.dimensions, &CG(dimension_llist)); zend_llist_prepend_element(&CG(list_llist), &lle); } (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_new_list_begin(TSRMLS_D) /* {{{ */ { int current_dimension = 0; zend_llist_add_element(&CG(dimension_llist), &current_dimension); } /* }}} */ void zend_do_new_list_end(TSRMLS_D) /* {{{ */ { zend_llist_remove_tail(&CG(dimension_llist)); (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_list_init(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(list_stack), &CG(list_llist), sizeof(zend_llist)); zend_stack_push(&CG(list_stack), &CG(dimension_llist), sizeof(zend_llist)); zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_do_new_list_begin(TSRMLS_C); } /* }}} */ void zend_do_list_end(znode *result, znode *expr TSRMLS_DC) /* {{{ */ { zend_llist_element *le; zend_llist_element *dimension; zend_op *opline; znode last_container; le = CG(list_llist).head; while (le) { zend_llist *tmp_dimension_llist = &((list_llist_element *)le->data)->dimensions; dimension = tmp_dimension_llist->head; while (dimension) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (dimension == tmp_dimension_llist->head) { /* first */ last_container = *expr; switch (expr->op_type) { case IS_VAR: case IS_CV: opline->opcode = ZEND_FETCH_DIM_R; break; case IS_TMP_VAR: opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; case IS_CONST: /* fetch_dim_tmp_var will handle this bogus fetch */ zval_copy_ctor(&expr->u.constant); opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; } opline->extended_value |= ZEND_FETCH_ADD_LOCK; } else { opline->opcode = ZEND_FETCH_DIM_R; } opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, &last_container); opline->op2_type = IS_CONST; LITERAL_LONG(opline->op2, *((int *) dimension->data)); GET_NODE(&last_container, opline->result); dimension = dimension->next; } ((list_llist_element *) le->data)->value = last_container; zend_llist_destroy(&((list_llist_element *) le->data)->dimensions); zend_do_assign(result, &((list_llist_element *) le->data)->var, &((list_llist_element *) le->data)->value TSRMLS_CC); zend_do_free(result TSRMLS_CC); le = le->next; } zend_llist_destroy(&CG(dimension_llist)); zend_llist_destroy(&CG(list_llist)); *result = *expr; { zend_llist *p; /* restore previous lists */ zend_stack_top(&CG(list_stack), (void **) &p); CG(dimension_llist) = *p; zend_stack_del_top(&CG(list_stack)); zend_stack_top(&CG(list_stack), (void **) &p); CG(list_llist) = *p; zend_stack_del_top(&CG(list_stack)); } } /* }}} */ void zend_init_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = emalloc(sizeof(void*) * 2); list[0] = item; list[1] = NULL; *(void**)result = list; } /* }}} */ void zend_add_to_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = *(void**)result; size_t n = 0; while (list && list[n]) { n++; } list = erealloc(list, sizeof(void*) * (n+2)); list[n] = item; list[n+1] = NULL; *(void**)result = list; } /* }}} */ void zend_do_fetch_static_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zval *tmp; zend_op *opline; znode lval; znode result; ALLOC_ZVAL(tmp); if (static_assignment) { *tmp = static_assignment->u.constant; } else { INIT_ZVAL(*tmp); } if (!CG(active_op_array)->static_variables) { if (CG(active_op_array)->scope) { CG(active_op_array)->scope->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } ALLOC_HASHTABLE(CG(active_op_array)->static_variables); zend_hash_init(CG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } zend_hash_update(CG(active_op_array)->static_variables, varname->u.constant.value.str.val, varname->u.constant.value.str.len+1, &tmp, sizeof(zval *), NULL); if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (fetch_type == ZEND_FETCH_LEXICAL) ? ZEND_FETCH_R : ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_STATIC; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ if (fetch_type == ZEND_FETCH_LEXICAL) { znode dummy; zend_do_begin_variable_parse(TSRMLS_C); zend_do_assign(&dummy, &lval, &result TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } else { zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); } CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_fetch_lexical_variable(znode *varname, zend_bool is_ref TSRMLS_DC) /* {{{ */ { znode value; if (Z_STRLEN(varname->u.constant) == sizeof("this") - 1 && memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this") - 1) == 0) { zend_error(E_COMPILE_ERROR, "Cannot use $this as lexical variable"); return; } value.op_type = IS_CONST; ZVAL_NULL(&value.u.constant); Z_TYPE(value.u.constant) |= is_ref ? IS_LEXICAL_REF : IS_LEXICAL_VAR; Z_SET_REFCOUNT_P(&value.u.constant, 1); Z_UNSET_ISREF_P(&value.u.constant); zend_do_fetch_static_variable(varname, &value, is_ref ? ZEND_FETCH_STATIC : ZEND_FETCH_LEXICAL TSRMLS_CC); } /* }}} */ void zend_do_fetch_global_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zend_op *opline; znode lval; znode result; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = fetch_type; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_cast(znode *result, const znode *expr, int type TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CAST; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } /* }}} */ void zend_do_include_or_eval(int type, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_do_extended_fcall_begin(TSRMLS_C); { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INCLUDE_OR_EVAL; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } zend_do_extended_fcall_end(TSRMLS_C); } /* }}} */ void zend_do_indirect_references(znode *result, const znode *num_references, znode *variable TSRMLS_DC) /* {{{ */ { int i; zend_do_end_variable_parse(variable, BP_VAR_R, 0 TSRMLS_CC); for (i=1; i<num_references->u.constant.value.lval; i++) { fetch_simple_variable_ex(result, variable, 0, ZEND_FETCH_R TSRMLS_CC); *variable = *result; } zend_do_begin_variable_parse(TSRMLS_C); fetch_simple_variable(result, variable, 1 TSRMLS_CC); /* there is a chance someone is accessing $this */ if (CG(active_op_array)->scope && CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } /* }}} */ void zend_do_unset(const znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_UNSET_VAR; SET_NODE(opline->op1, variable); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); opline->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_UNSET: last_op->opcode = ZEND_UNSET_VAR; SET_UNUSED(last_op->result); break; case ZEND_FETCH_DIM_UNSET: last_op->opcode = ZEND_UNSET_DIM; SET_UNUSED(last_op->result); break; case ZEND_FETCH_OBJ_UNSET: last_op->opcode = ZEND_UNSET_OBJ; SET_UNUSED(last_op->result); break; } } } /* }}} */ void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_do_end_variable_parse(variable, BP_VAR_IS, 0 TSRMLS_CC); zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { last_op = get_next_op(CG(active_op_array) TSRMLS_CC); last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; SET_NODE(last_op->op1, variable); SET_UNUSED(last_op->op2); last_op->result.var = get_temporary_variable(CG(active_op_array)); last_op->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; break; case ZEND_FETCH_DIM_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_DIM_OBJ; break; case ZEND_FETCH_OBJ_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_PROP_OBJ; break; } } last_op->result_type = IS_TMP_VAR; last_op->extended_value |= type; GET_NODE(result, last_op->result); } /* }}} */ void zend_do_instanceof(znode *result, const znode *expr, const znode *class_znode, int type TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline->opcode == ZEND_FETCH_CLASS) { opline->extended_value |= ZEND_FETCH_CLASS_NO_AUTOLOAD; } } if (expr->op_type == IS_CONST) { zend_error(E_COMPILE_ERROR, "instanceof expects an object instance, constant given"); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INSTANCEOF; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_NODE(opline->op2, class_znode); GET_NODE(result, opline->result); } /* }}} */ void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_bool is_variable; zend_bool push_container = 0; zend_op dummy_opline; if (variable) { if (zend_is_function_or_method_call(array)) { is_variable = 0; } else { is_variable = 1; } /* save the location of FETCH_W instruction(s) */ open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); zend_do_end_variable_parse(array, BP_VAR_W, 0 TSRMLS_CC); if (CG(active_op_array)->last > 0 && CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) { /* Only lock the container if we are fetching from a real container and not $this */ if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1_type == IS_VAR) { CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK; push_container = 1; } } } else { is_variable = 0; open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* save the location of FE_RESET */ foreach_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* Preform array reset */ opline->opcode = ZEND_FE_RESET; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, array); SET_UNUSED(opline->op2); opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0; COPY_NODE(dummy_opline.result, opline->result); if (push_container) { COPY_NODE(dummy_opline.op1, CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1); } else { dummy_opline.op1_type = IS_UNUSED; } zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); /* save the location of FE_FETCH */ as_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FE_FETCH; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); COPY_NODE(opline->op1, dummy_opline.result); opline->extended_value = 0; SET_UNUSED(opline->op2); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_OP_DATA; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); } /* }}} */ void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC) /* {{{ */ { zend_op *opline; znode dummy, value_node; zend_bool assign_by_ref=0; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num]; if (key->op_type != IS_UNUSED) { znode *tmp; /* switch between the key and value... */ tmp = key; key = value; value = tmp; /* Mark extended_value in case both key and value are being used */ opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; } if ((key->op_type != IS_UNUSED) && (key->EA & ZEND_PARSED_REFERENCE_VARIABLE)) { zend_error(E_COMPILE_ERROR, "Key element cannot be a reference"); } if (value->EA & ZEND_PARSED_REFERENCE_VARIABLE) { assign_by_ref = 1; if (!(opline-1)->extended_value) { zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression"); } /* Mark extended_value for assign-by-reference */ opline->extended_value |= ZEND_FE_FETCH_BYREF; CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; } else { zend_op *foreach_copy; zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.op.opline_num]; zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.op.opline_num]; /* Change "write context" into "read context" */ fetch->extended_value = 0; /* reset ZEND_FE_RESET_VARIABLE */ while (fetch != end) { --fetch; if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } if (fetch->opcode == ZEND_SEPARATE) { MAKE_NOP(fetch); } else { fetch->opcode -= 3; /* FETCH_W -> FETCH_R */ } } /* prevent double SWITCH_FREE */ zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy); foreach_copy->op1_type = IS_UNUSED; } GET_NODE(&value_node, opline->result); if (assign_by_ref) { zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); /* Mark FE_FETCH as IS_VAR as it holds the data directly as a value */ zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC); } else { zend_do_assign(&dummy, value, &value_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } if (key->op_type != IS_UNUSED) { znode key_node; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num+1]; opline->result_type = IS_TMP_VAR; opline->result.opline_num = get_temporary_variable(CG(active_op_array)); GET_NODE(&key_node, opline->result); zend_do_assign(&dummy, key, &key_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_foreach_end(const znode *foreach_token, const znode *as_token TSRMLS_DC) /* {{{ */ { zend_op *container_ptr; zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = as_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_RESET */ CG(active_op_array)->opcodes[as_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_FETCH */ do_end_loop(as_token->u.op.opline_num, 1 TSRMLS_CC); zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr); generate_free_foreach_copy(container_ptr TSRMLS_CC); zend_stack_del_top(&CG(foreach_copy_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_declare_begin(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(declare_stack), &CG(declarables), sizeof(zend_declarables)); } /* }}} */ void zend_do_declare_stmt(znode *var, znode *val TSRMLS_DC) /* {{{ */ { if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "ticks", sizeof("ticks")-1)) { convert_to_long(&val->u.constant); CG(declarables).ticks = val->u.constant; } else if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "encoding", sizeof("encoding")-1)) { if ((Z_TYPE(val->u.constant) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Cannot use constants as encoding"); } /* * Check that the pragma comes before any opcodes. If the compilation * got as far as this, the previous portion of the script must have been * parseable according to the .ini script_encoding setting. We still * want to tell them to put declare() at the top. */ { int num = CG(active_op_array)->last; /* ignore ZEND_EXT_STMT and ZEND_TICKS */ while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Encoding declaration pragma must be the very first statement in the script"); } } if (CG(multibyte)) { const zend_encoding *new_encoding, *old_encoding; zend_encoding_filter old_input_filter; CG(encoding_declared) = 1; convert_to_string(&val->u.constant); new_encoding = zend_multibyte_fetch_encoding(val->u.constant.value.str.val TSRMLS_CC); if (!new_encoding) { zend_error(E_COMPILE_WARNING, "Unsupported encoding [%s]", val->u.constant.value.str.val); } else { old_input_filter = LANG_SCNG(input_filter); old_encoding = LANG_SCNG(script_encoding); zend_multibyte_set_filter(new_encoding TSRMLS_CC); /* need to re-scan if input filter changed */ if (old_input_filter != LANG_SCNG(input_filter) || (old_input_filter && new_encoding != old_encoding)) { zend_multibyte_yyinput_again(old_input_filter, old_encoding TSRMLS_CC); } } } else { zend_error(E_COMPILE_WARNING, "declare(encoding=...) ignored because Zend multibyte feature is turned off by settings"); } zval_dtor(&val->u.constant); } else { zend_error(E_COMPILE_WARNING, "Unsupported declare '%s'", var->u.constant.value.str.val); zval_dtor(&val->u.constant); } zval_dtor(&var->u.constant); } /* }}} */ void zend_do_declare_end(const znode *declare_token TSRMLS_DC) /* {{{ */ { zend_declarables *declarables; zend_stack_top(&CG(declare_stack), (void **) &declarables); /* We should restore if there was more than (current - start) - (ticks?1:0) opcodes */ if ((get_next_op_number(CG(active_op_array)) - declare_token->u.op.opline_num) - ((Z_LVAL(CG(declarables).ticks))?1:0)) { CG(declarables) = *declarables; } } /* }}} */ void zend_do_exit(znode *result, const znode *message TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXIT; SET_NODE(opline->op1, message); SET_UNUSED(opline->op2); result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_BOOL; Z_LVAL(result->u.constant) = 1; } /* }}} */ void zend_do_begin_silence(znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BEGIN_SILENCE; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); GET_NODE(strudel_token, opline->result); } /* }}} */ void zend_do_end_silence(const znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_END_SILENCE; SET_NODE(opline->op1, strudel_token); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_jmp_set(const znode *value, znode *jmp_token, znode *colon_token TSRMLS_DC) /* {{{ */ { int op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (value->op_type == IS_VAR || value->op_type == IS_CV) { opline->opcode = ZEND_JMP_SET_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_JMP_SET; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, value); SET_UNUSED(opline->op2); GET_NODE(colon_token, opline->result); jmp_token->u.op .opline_num = op_number; INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_jmp_set_else(znode *result, const znode *false_value, const znode *jmp_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, colon_token); if (colon_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].opcode = ZEND_JMP_SET_VAR; CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } opline->extended_value = 0; SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_qm_op(const znode *cond, znode *qm_token TSRMLS_DC) /* {{{ */ { int jmpz_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); SET_UNUSED(opline->op2); opline->op2.opline_num = jmpz_op_number; GET_NODE(qm_token, opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_qm_true(const znode *true_value, znode *qm_token, znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->opcodes[qm_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array))+1; /* jmp over the ZEND_JMP */ if (true_value->op_type == IS_VAR || true_value->op_type == IS_CV) { opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, true_value); SET_UNUSED(opline->op2); GET_NODE(qm_token, opline->result); colon_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_qm_false(znode *result, const znode *false_value, const znode *qm_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, qm_token); if (qm_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].opcode = ZEND_QM_ASSIGN_VAR; CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[colon_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, opline->result); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_extended_info(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_STMT; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_begin(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_BEGIN; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_end(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_END; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_ticks(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_TICKS; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->extended_value = Z_LVAL(CG(declarables).ticks); } /* }}} */ zend_bool zend_is_auto_global_quick(const char *name, uint name_len, ulong hashval TSRMLS_DC) /* {{{ */ { zend_auto_global *auto_global; ulong hash = hashval ? hashval : zend_hash_func(name, name_len+1); if (zend_hash_quick_find(CG(auto_globals), name, name_len+1, hash, (void **) &auto_global)==SUCCESS) { if (auto_global->armed) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } return 1; } return 0; } /* }}} */ zend_bool zend_is_auto_global(const char *name, uint name_len TSRMLS_DC) /* {{{ */ { return zend_is_auto_global_quick(name, name_len, 0 TSRMLS_CC); } /* }}} */ int zend_register_auto_global(const char *name, uint name_len, zend_bool jit, zend_auto_global_callback auto_global_callback TSRMLS_DC) /* {{{ */ { zend_auto_global auto_global; auto_global.name = zend_new_interned_string((char*)name, name_len + 1, 0 TSRMLS_CC); auto_global.name_len = name_len; auto_global.auto_global_callback = auto_global_callback; auto_global.jit = jit; return zend_hash_add(CG(auto_globals), name, name_len+1, &auto_global, sizeof(zend_auto_global), NULL); } /* }}} */ static int zend_auto_global_init(zend_auto_global *auto_global TSRMLS_DC) /* {{{ */ { if (auto_global->jit) { auto_global->armed = 1; } else if (auto_global->auto_global_callback) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } else { auto_global->armed = 0; } return 0; } /* }}} */ ZEND_API void zend_activate_auto_globals(TSRMLS_D) /* {{{ */ { zend_hash_apply(CG(auto_globals), (apply_func_t) zend_auto_global_init TSRMLS_CC); } /* }}} */ int zendlex(znode *zendlval TSRMLS_DC) /* {{{ */ { int retval; if (CG(increment_lineno)) { CG(zend_lineno)++; CG(increment_lineno) = 0; } again: Z_TYPE(zendlval->u.constant) = IS_LONG; retval = lex_scan(&zendlval->u.constant TSRMLS_CC); switch (retval) { case T_COMMENT: case T_DOC_COMMENT: case T_OPEN_TAG: case T_WHITESPACE: goto again; case T_CLOSE_TAG: if (LANG_SCNG(yy_text)[LANG_SCNG(yy_leng)-1] != '>') { CG(increment_lineno) = 1; } if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { goto again; } retval = ';'; /* implicit ; */ break; case T_OPEN_TAG_WITH_ECHO: retval = T_ECHO; break; case T_END_HEREDOC: efree(Z_STRVAL(zendlval->u.constant)); break; } INIT_PZVAL(&zendlval->u.constant); zendlval->op_type = IS_CONST; return retval; } /* }}} */ ZEND_API void zend_initialize_class_data(zend_class_entry *ce, zend_bool nullify_handlers TSRMLS_DC) /* {{{ */ { zend_bool persistent_hashes = (ce->type == ZEND_INTERNAL_CLASS) ? 1 : 0; dtor_func_t zval_ptr_dtor_func = ((persistent_hashes) ? ZVAL_INTERNAL_PTR_DTOR : ZVAL_PTR_DTOR); ce->refcount = 1; ce->ce_flags = 0; ce->default_properties_table = NULL; ce->default_static_members_table = NULL; zend_hash_init_ex(&ce->properties_info, 0, NULL, (dtor_func_t) (persistent_hashes ? zend_destroy_property_info_internal : zend_destroy_property_info), persistent_hashes, 0); zend_hash_init_ex(&ce->constants_table, 0, NULL, zval_ptr_dtor_func, persistent_hashes, 0); zend_hash_init_ex(&ce->function_table, 0, NULL, ZEND_FUNCTION_DTOR, persistent_hashes, 0); if (ce->type == ZEND_INTERNAL_CLASS) { #ifdef ZTS int n = zend_hash_num_elements(CG(class_table)); if (CG(static_members_table) && n >= CG(last_static_member)) { /* Support for run-time declaration: dl() */ CG(last_static_member) = n+1; CG(static_members_table) = realloc(CG(static_members_table), (n+1)*sizeof(zval**)); CG(static_members_table)[n] = NULL; } ce->static_members_table = (zval**)(zend_intptr_t)n; #else ce->static_members_table = NULL; #endif } else { ce->static_members_table = ce->default_static_members_table; ce->info.user.doc_comment = NULL; ce->info.user.doc_comment_len = 0; } ce->default_properties_count = 0; ce->default_static_members_count = 0; if (nullify_handlers) { ce->constructor = NULL; ce->destructor = NULL; ce->clone = NULL; ce->__get = NULL; ce->__set = NULL; ce->__unset = NULL; ce->__isset = NULL; ce->__call = NULL; ce->__callstatic = NULL; ce->__tostring = NULL; ce->create_object = NULL; ce->get_iterator = NULL; ce->iterator_funcs.funcs = NULL; ce->interface_gets_implemented = NULL; ce->get_static_method = NULL; ce->parent = NULL; ce->num_interfaces = 0; ce->interfaces = NULL; ce->num_traits = 0; ce->traits = NULL; ce->trait_aliases = NULL; ce->trait_precedences = NULL; ce->serialize = NULL; ce->unserialize = NULL; ce->serialize_func = NULL; ce->unserialize_func = NULL; if (ce->type == ZEND_INTERNAL_CLASS) { ce->info.internal.module = NULL; ce->info.internal.builtin_functions = NULL; } } } /* }}} */ int zend_get_class_fetch_type(const char *class_name, uint class_name_len) /* {{{ */ { if ((class_name_len == sizeof("self")-1) && !memcmp(class_name, "self", sizeof("self")-1)) { return ZEND_FETCH_CLASS_SELF; } else if ((class_name_len == sizeof("parent")-1) && !memcmp(class_name, "parent", sizeof("parent")-1)) { return ZEND_FETCH_CLASS_PARENT; } else if ((class_name_len == sizeof("static")-1) && !memcmp(class_name, "static", sizeof("static")-1)) { return ZEND_FETCH_CLASS_STATIC; } else { return ZEND_FETCH_CLASS_DEFAULT; } } /* }}} */ ZEND_API const char* zend_get_compiled_variable_name(const zend_op_array *op_array, zend_uint var, int* name_len) /* {{{ */ { if (name_len) { *name_len = op_array->vars[var].name_len; } return op_array->vars[var].name; } /* }}} */ void zend_do_build_namespace_name(znode *result, znode *prefix, znode *name TSRMLS_DC) /* {{{ */ { if (prefix) { *result = *prefix; if (Z_TYPE(result->u.constant) == IS_STRING && Z_STRLEN(result->u.constant) == 0) { /* namespace\ */ if (CG(current_namespace)) { znode tmp; zval_dtor(&result->u.constant); tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(result, NULL, &tmp TSRMLS_CC); } } } else { result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_STRING; Z_STRVAL(result->u.constant) = NULL; Z_STRLEN(result->u.constant) = 0; } /* prefix = result */ zend_do_build_full_name(NULL, result, name, 0 TSRMLS_CC); } /* }}} */ void zend_do_begin_namespace(const znode *name, zend_bool with_bracket TSRMLS_DC) /* {{{ */ { char *lcname; /* handle mixed syntax declaration or nested namespaces */ if (!CG(has_bracketed_namespaces)) { if (CG(current_namespace)) { /* previous namespace declarations were unbracketed */ if (with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } } } else { /* previous namespace declarations were bracketed */ if (!with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } else if (CG(current_namespace) || CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "Namespace declarations cannot be nested"); } } if (((!with_bracket && !CG(current_namespace)) || (with_bracket && !CG(has_bracketed_namespaces))) && CG(active_op_array)->last > 0) { /* ignore ZEND_EXT_STMT and ZEND_TICKS */ int num = CG(active_op_array)->last; while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Namespace declaration statement has to be the very first statement in the script"); } } CG(in_namespace) = 1; if (with_bracket) { CG(has_bracketed_namespaces) = 1; } if (name) { lcname = zend_str_tolower_dup(Z_STRVAL(name->u.constant), Z_STRLEN(name->u.constant)); if (((Z_STRLEN(name->u.constant) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN(name->u.constant) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as namespace name", Z_STRVAL(name->u.constant)); } efree(lcname); if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); } else { ALLOC_ZVAL(CG(current_namespace)); } *CG(current_namespace) = name->u.constant; } else { if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_use(znode *ns_name, znode *new_name, int is_global TSRMLS_DC) /* {{{ */ { char *lcname; zval *name, *ns, tmp; zend_bool warn = 0; zend_class_entry **pce; if (!CG(current_import)) { CG(current_import) = emalloc(sizeof(HashTable)); zend_hash_init(CG(current_import), 0, NULL, ZVAL_PTR_DTOR, 0); } ALLOC_ZVAL(ns); *ns = ns_name->u.constant; if (new_name) { name = &new_name->u.constant; } else { const char *p; /* The form "use A\B" is eqivalent to "use A\B as B". So we extract the last part of compound name to use as a new_name */ name = &tmp; p = zend_memrchr(Z_STRVAL_P(ns), '\\', Z_STRLEN_P(ns)); if (p) { ZVAL_STRING(name, p+1, 1); } else { *name = *ns; zval_copy_ctor(name); warn = !is_global && !CG(current_namespace); } } lcname = zend_str_tolower_dup(Z_STRVAL_P(name), Z_STRLEN_P(name)); if (((Z_STRLEN_P(name) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN_P(name) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because '%s' is a special class name", Z_STRVAL_P(ns), Z_STRVAL_P(name), Z_STRVAL_P(name)); } if (CG(current_namespace)) { /* Prefix import name with current namespace name to avoid conflicts with classes */ char *c_ns_name = emalloc(Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) + 1); zend_str_tolower_copy(c_ns_name, Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); c_ns_name[Z_STRLEN_P(CG(current_namespace))] = '\\'; memcpy(c_ns_name+Z_STRLEN_P(CG(current_namespace))+1, lcname, Z_STRLEN_P(name)+1); if (zend_hash_exists(CG(class_table), c_ns_name, Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name)+1)) { char *tmp2 = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) || memcmp(tmp2, c_ns_name, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(tmp2); } efree(c_ns_name); } else if (zend_hash_find(CG(class_table), lcname, Z_STRLEN_P(name)+1, (void**)&pce) == SUCCESS && (*pce)->type == ZEND_USER_CLASS && (*pce)->info.user.filename == CG(compiled_filename)) { char *c_tmp = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(name) || memcmp(c_tmp, lcname, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(c_tmp); } if (zend_hash_add(CG(current_import), lcname, Z_STRLEN_P(name)+1, &ns, sizeof(zval*), NULL) != SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } if (warn) { if (!strcmp(Z_STRVAL_P(name), "strict")) { zend_error(E_COMPILE_ERROR, "You seem to be trying to use a different language..."); } zend_error(E_WARNING, "The use statement with non-compound name '%s' has no effect", Z_STRVAL_P(name)); } efree(lcname); zval_dtor(name); } /* }}} */ void zend_do_declare_constant(znode *name, znode *value TSRMLS_DC) /* {{{ */ { zend_op *opline; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed as constants"); } if (zend_get_ct_const(&name->u.constant, 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare constant '%s'", Z_STRVAL(name->u.constant)); } if (CG(current_namespace)) { /* Prefix constant name with name of current namespace, lowercased */ znode tmp; tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); Z_STRVAL(tmp.u.constant) = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), Z_STRLEN(tmp.u.constant)); zend_do_build_namespace_name(&tmp, &tmp, name TSRMLS_CC); *name = tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DECLARE_CONST; SET_UNUSED(opline->result); SET_NODE(opline->op1, name); SET_NODE(opline->op2, value); } /* }}} */ void zend_verify_namespace(TSRMLS_D) /* {{{ */ { if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "No code may exist outside of namespace {}"); } } /* }}} */ void zend_do_end_namespace(TSRMLS_D) /* {{{ */ { CG(in_namespace) = 0; if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_end_compilation(TSRMLS_D) /* {{{ */ { CG(has_bracketed_namespaces) = 0; zend_do_end_namespace(TSRMLS_C); } /* }}} */ /* {{{ zend_dirname Returns directory name component of path */ ZEND_API size_t zend_dirname(char *path, size_t len) { register char *end = path + len - 1; unsigned int len_adjust = 0; #ifdef PHP_WIN32 /* Note that on Win32 CWD is per drive (heritage from CP/M). * This means dirname("c:foo") maps to "c:." or "c:" - which means CWD on C: drive. */ if ((2 <= len) && isalpha((int)((unsigned char *)path)[0]) && (':' == path[1])) { /* Skip over the drive spec (if any) so as not to change */ path += 2; len_adjust += 2; if (2 == len) { /* Return "c:" on Win32 for dirname("c:"). * It would be more consistent to return "c:." * but that would require making the string *longer*. */ return len; } } #elif defined(NETWARE) /* * Find the first occurence of : from the left * move the path pointer to the position just after : * increment the len_adjust to the length of path till colon character(inclusive) * If there is no character beyond : simple return len */ char *colonpos = NULL; colonpos = strchr(path, ':'); if (colonpos != NULL) { len_adjust = ((colonpos - path) + 1); path += len_adjust; if (len_adjust == len) { return len; } } #endif if (len == 0) { /* Illegal use of this function */ return 0; } /* Strip trailing slashes */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { /* The path only contained slashes */ path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } /* Strip filename */ while (end >= path && !IS_SLASH_P(end)) { end--; } if (end < path) { /* No slash found, therefore return '.' */ #ifdef NETWARE if (len_adjust == 0) { path[0] = '.'; path[1] = '\0'; return 1; /* only one character */ } else { path[0] = '\0'; return len_adjust; } #else path[0] = '.'; path[1] = '\0'; return 1 + len_adjust; #endif } /* Strip slashes which came before the file name */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } *(end+1) = '\0'; return (size_t)(end + 1 - path) + len_adjust; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-12-04-b3ad0b7af7-1d6c98a136.c
manybugs_data_12
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Marcus Boerger <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" #include "ext/standard/file.h" #include "ext/standard/php_string.h" #include "zend_compile.h" #include "zend_exceptions.h" #include "zend_interfaces.h" #include "php_spl.h" #include "spl_functions.h" #include "spl_engine.h" #include "spl_iterators.h" #include "spl_directory.h" #include "spl_exceptions.h" #include "php.h" #include "fopen_wrappers.h" #include "ext/standard/basic_functions.h" #include "ext/standard/php_filestat.h" #define SPL_HAS_FLAG(flags, test_flag) ((flags & test_flag) ? 1 : 0) /* declare the class handlers */ static zend_object_handlers spl_filesystem_object_handlers; /* includes handler to validate object state when retrieving methods */ static zend_object_handlers spl_filesystem_object_check_handlers; /* decalre the class entry */ PHPAPI zend_class_entry *spl_ce_SplFileInfo; PHPAPI zend_class_entry *spl_ce_DirectoryIterator; PHPAPI zend_class_entry *spl_ce_FilesystemIterator; PHPAPI zend_class_entry *spl_ce_RecursiveDirectoryIterator; PHPAPI zend_class_entry *spl_ce_GlobIterator; PHPAPI zend_class_entry *spl_ce_SplFileObject; PHPAPI zend_class_entry *spl_ce_SplTempFileObject; static void spl_filesystem_file_free_line(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { if (intern->u.file.current_line) { efree(intern->u.file.current_line); intern->u.file.current_line = NULL; } if (intern->u.file.current_zval) { zval_ptr_dtor(&intern->u.file.current_zval); intern->u.file.current_zval = NULL; } } /* }}} */ static void spl_filesystem_object_free_storage(void *object TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern = (spl_filesystem_object*)object; if (intern->oth_handler && intern->oth_handler->dtor) { intern->oth_handler->dtor(intern TSRMLS_CC); } zend_object_std_dtor(&intern->std TSRMLS_CC); if (intern->_path) { efree(intern->_path); } if (intern->file_name) { efree(intern->file_name); } switch(intern->type) { case SPL_FS_INFO: break; case SPL_FS_DIR: if (intern->u.dir.dirp) { php_stream_close(intern->u.dir.dirp); intern->u.dir.dirp = NULL; } if (intern->u.dir.sub_path) { efree(intern->u.dir.sub_path); } break; case SPL_FS_FILE: if (intern->u.file.stream) { if (intern->u.file.zcontext) { /* zend_list_delref(Z_RESVAL_P(intern->zcontext));*/ } if (!intern->u.file.stream->is_persistent) { php_stream_free(intern->u.file.stream, PHP_STREAM_FREE_CLOSE); } else { php_stream_free(intern->u.file.stream, PHP_STREAM_FREE_CLOSE_PERSISTENT); } if (intern->u.file.open_mode) { efree(intern->u.file.open_mode); } if (intern->orig_path) { efree(intern->orig_path); } } spl_filesystem_file_free_line(intern TSRMLS_CC); break; } efree(object); } /* }}} */ /* {{{ spl_ce_dir_object_new */ /* creates the object by - allocating memory - initializing the object members - storing the object - setting it's handlers called from - clone - new */ static zend_object_value spl_filesystem_object_new_ex(zend_class_entry *class_type, spl_filesystem_object **obj TSRMLS_DC) { zend_object_value retval; spl_filesystem_object *intern; intern = emalloc(sizeof(spl_filesystem_object)); memset(intern, 0, sizeof(spl_filesystem_object)); /* intern->type = SPL_FS_INFO; done by set 0 */ intern->file_class = spl_ce_SplFileObject; intern->info_class = spl_ce_SplFileInfo; if (obj) *obj = intern; zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, (zend_objects_free_object_storage_t) spl_filesystem_object_free_storage, NULL TSRMLS_CC); retval.handlers = &spl_filesystem_object_handlers; return retval; } /* }}} */ /* {{{ spl_filesystem_object_new */ /* See spl_filesystem_object_new_ex */ static zend_object_value spl_filesystem_object_new(zend_class_entry *class_type TSRMLS_DC) { return spl_filesystem_object_new_ex(class_type, NULL TSRMLS_CC); } /* }}} */ /* {{{ spl_filesystem_object_new_ex */ static zend_object_value spl_filesystem_object_new_check(zend_class_entry *class_type TSRMLS_DC) { zend_object_value ret = spl_filesystem_object_new_ex(class_type, NULL TSRMLS_CC); ret.handlers = &spl_filesystem_object_check_handlers; return ret; } /* }}} */ PHPAPI char* spl_filesystem_object_get_path(spl_filesystem_object *intern, int *len TSRMLS_DC) /* {{{ */ { #ifdef HAVE_GLOB if (intern->type == SPL_FS_DIR) { if (php_stream_is(intern->u.dir.dirp ,&php_glob_stream_ops)) { return php_glob_stream_get_path(intern->u.dir.dirp, 0, len); } } #endif if (len) { *len = intern->_path_len; } return intern->_path; } /* }}} */ static inline void spl_filesystem_object_get_file_name(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH; if (!intern->file_name) { switch (intern->type) { case SPL_FS_INFO: case SPL_FS_FILE: php_error_docref(NULL TSRMLS_CC, E_ERROR, "Object not initialized"); break; case SPL_FS_DIR: intern->file_name_len = spprintf(&intern->file_name, 0, "%s%c%s", spl_filesystem_object_get_path(intern, NULL TSRMLS_CC), slash, intern->u.dir.entry.d_name); break; } } } /* }}} */ static int spl_filesystem_dir_read(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { if (!intern->u.dir.dirp || !php_stream_readdir(intern->u.dir.dirp, &intern->u.dir.entry)) { intern->u.dir.entry.d_name[0] = '\0'; return 0; } else { return 1; } } /* }}} */ #define IS_SLASH_AT(zs, pos) (IS_SLASH(zs[pos])) static inline int spl_filesystem_is_dot(const char * d_name) /* {{{ */ { return !strcmp(d_name, ".") || !strcmp(d_name, ".."); } /* }}} */ /* {{{ spl_filesystem_dir_open */ /* open a directory resource */ static void spl_filesystem_dir_open(spl_filesystem_object* intern, char *path TSRMLS_DC) { int skip_dots = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_SKIPDOTS); intern->type = SPL_FS_DIR; intern->_path_len = strlen(path); intern->u.dir.dirp = php_stream_opendir(path, REPORT_ERRORS, FG(default_context)); if (intern->_path_len > 1 && IS_SLASH_AT(path, intern->_path_len-1)) { intern->_path = estrndup(path, --intern->_path_len); } else { intern->_path = estrndup(path, intern->_path_len); } intern->u.dir.index = 0; if (EG(exception) || intern->u.dir.dirp == NULL) { intern->u.dir.entry.d_name[0] = '\0'; if (!EG(exception)) { /* open failed w/out notice (turned to exception due to EH_THROW) */ zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Failed to open directory \"%s\"", path); } } else { do { spl_filesystem_dir_read(intern TSRMLS_CC); } while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name)); } } /* }}} */ static int spl_filesystem_file_open(spl_filesystem_object *intern, int use_include_path, int silent TSRMLS_DC) /* {{{ */ { zval tmp; intern->type = SPL_FS_FILE; php_stat(intern->file_name, intern->file_name_len, FS_IS_DIR, &tmp TSRMLS_CC); if (Z_LVAL(tmp)) { intern->u.file.open_mode = NULL; intern->file_name = NULL; zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Cannot use SplFileObject with directories"); return FAILURE; } intern->u.file.context = php_stream_context_from_zval(intern->u.file.zcontext, 0); intern->u.file.stream = php_stream_open_wrapper_ex(intern->file_name, intern->u.file.open_mode, (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, intern->u.file.context); if (!intern->file_name_len || !intern->u.file.stream) { if (!EG(exception)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot open file '%s'", intern->file_name_len ? intern->file_name : ""); } intern->file_name = NULL; /* until here it is not a copy */ intern->u.file.open_mode = NULL; return FAILURE; } if (intern->u.file.zcontext) { zend_list_addref(Z_RESVAL_P(intern->u.file.zcontext)); } if (intern->file_name_len > 1 && IS_SLASH_AT(intern->file_name, intern->file_name_len-1)) { intern->file_name_len--; } intern->orig_path = estrndup(intern->u.file.stream->orig_path, strlen(intern->u.file.stream->orig_path)); intern->file_name = estrndup(intern->file_name, intern->file_name_len); intern->u.file.open_mode = estrndup(intern->u.file.open_mode, intern->u.file.open_mode_len); /* avoid reference counting in debug mode, thus do it manually */ ZVAL_RESOURCE(&intern->u.file.zresource, php_stream_get_resource_id(intern->u.file.stream)); Z_SET_REFCOUNT(intern->u.file.zresource, 1); intern->u.file.delimiter = ','; intern->u.file.enclosure = '"'; intern->u.file.escape = '\\'; zend_hash_find(&intern->std.ce->function_table, "getcurrentline", sizeof("getcurrentline"), (void **) &intern->u.file.func_getCurr); return SUCCESS; } /* }}} */ /* {{{ spl_filesystem_object_clone */ /* Local zend_object_value creation (on stack) Load the 'other' object Create a new empty object (See spl_filesystem_object_new_ex) Open the directory Clone other members (properties) */ static zend_object_value spl_filesystem_object_clone(zval *zobject TSRMLS_DC) { zend_object_value new_obj_val; zend_object *old_object; zend_object *new_object; zend_object_handle handle = Z_OBJ_HANDLE_P(zobject); spl_filesystem_object *intern; spl_filesystem_object *source; int index, skip_dots; old_object = zend_objects_get_address(zobject TSRMLS_CC); source = (spl_filesystem_object*)old_object; new_obj_val = spl_filesystem_object_new_ex(old_object->ce, &intern TSRMLS_CC); new_object = &intern->std; intern->flags = source->flags; switch (source->type) { case SPL_FS_INFO: intern->_path_len = source->_path_len; intern->_path = estrndup(source->_path, source->_path_len); intern->file_name_len = source->file_name_len; intern->file_name = estrndup(source->file_name, intern->file_name_len); break; case SPL_FS_DIR: spl_filesystem_dir_open(intern, source->_path TSRMLS_CC); /* read until we hit the position in which we were before */ skip_dots = SPL_HAS_FLAG(source->flags, SPL_FILE_DIR_SKIPDOTS); for(index = 0; index < source->u.dir.index; ++index) { do { spl_filesystem_dir_read(intern TSRMLS_CC); } while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name)); } intern->u.dir.index = index; break; case SPL_FS_FILE: php_error_docref(NULL TSRMLS_CC, E_ERROR, "An object of class %s cannot be cloned", old_object->ce->name); break; } intern->file_class = source->file_class; intern->info_class = source->info_class; intern->oth = source->oth; intern->oth_handler = source->oth_handler; zend_objects_clone_members(new_object, new_obj_val, old_object, handle TSRMLS_CC); if (intern->oth_handler && intern->oth_handler->clone) { intern->oth_handler->clone(source, intern TSRMLS_CC); } return new_obj_val; } /* }}} */ void spl_filesystem_info_set_filename(spl_filesystem_object *intern, char *path, int len, int use_copy TSRMLS_DC) /* {{{ */ { char *p1, *p2; intern->file_name = use_copy ? estrndup(path, len) : path; intern->file_name_len = len; while(IS_SLASH_AT(intern->file_name, intern->file_name_len-1) && intern->file_name_len > 1) { intern->file_name[intern->file_name_len-1] = 0; intern->file_name_len--; } p1 = strrchr(intern->file_name, '/'); #if defined(PHP_WIN32) || defined(NETWARE) p2 = strrchr(intern->file_name, '\\'); #else p2 = 0; #endif if (p1 || p2) { intern->_path_len = (p1 > p2 ? p1 : p2) - intern->file_name; } else { intern->_path_len = 0; } intern->_path = estrndup(path, intern->_path_len); } /* }}} */ static spl_filesystem_object * spl_filesystem_object_create_info(spl_filesystem_object *source, char *file_path, int file_path_len, int use_copy, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern; zval *arg1; zend_error_handling error_handling; if (!file_path || !file_path_len) { #if defined(PHP_WIN32) zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot create SplFileInfo for empty path"); if (file_path && !use_copy) { efree(file_path); } #else if (file_path && !use_copy) { efree(file_path); } use_copy = 1; file_path_len = 1; file_path = "/"; #endif return NULL; } zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); ce = ce ? ce : source->info_class; zend_update_class_constants(ce TSRMLS_CC); return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); Z_TYPE_P(return_value) = IS_OBJECT; if (ce->constructor->common.scope != spl_ce_SplFileInfo) { MAKE_STD_ZVAL(arg1); ZVAL_STRINGL(arg1, file_path, file_path_len, use_copy); zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1); zval_ptr_dtor(&arg1); } else { spl_filesystem_info_set_filename(intern, file_path, file_path_len, use_copy TSRMLS_CC); } zend_restore_error_handling(&error_handling TSRMLS_CC); return intern; } /* }}} */ static spl_filesystem_object * spl_filesystem_object_create_type(int ht, spl_filesystem_object *source, int type, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern; zend_bool use_include_path = 0; zval *arg1, *arg2; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); switch (source->type) { case SPL_FS_INFO: case SPL_FS_FILE: break; case SPL_FS_DIR: if (!source->u.dir.entry.d_name[0]) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Could not open file"); zend_restore_error_handling(&error_handling TSRMLS_CC); return NULL; } } switch (type) { case SPL_FS_INFO: ce = ce ? ce : source->info_class; zend_update_class_constants(ce TSRMLS_CC); return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); Z_TYPE_P(return_value) = IS_OBJECT; spl_filesystem_object_get_file_name(source TSRMLS_CC); if (ce->constructor->common.scope != spl_ce_SplFileInfo) { MAKE_STD_ZVAL(arg1); ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1); zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1); zval_ptr_dtor(&arg1); } else { intern->file_name = estrndup(source->file_name, source->file_name_len); intern->file_name_len = source->file_name_len; intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC); intern->_path = estrndup(intern->_path, intern->_path_len); } break; case SPL_FS_FILE: ce = ce ? ce : source->file_class; zend_update_class_constants(ce TSRMLS_CC); return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); Z_TYPE_P(return_value) = IS_OBJECT; spl_filesystem_object_get_file_name(source TSRMLS_CC); if (ce->constructor->common.scope != spl_ce_SplFileObject) { MAKE_STD_ZVAL(arg1); MAKE_STD_ZVAL(arg2); ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1); ZVAL_STRINGL(arg2, "r", 1, 1); zend_call_method_with_2_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1, arg2); zval_ptr_dtor(&arg1); zval_ptr_dtor(&arg2); } else { intern->file_name = source->file_name; intern->file_name_len = source->file_name_len; intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC); intern->_path = estrndup(intern->_path, intern->_path_len); intern->u.file.open_mode = "r"; intern->u.file.open_mode_len = 1; if (ht && zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sbr", &intern->u.file.open_mode, &intern->u.file.open_mode_len, &use_include_path, &intern->u.file.zcontext) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); intern->u.file.open_mode = NULL; intern->file_name = NULL; zval_dtor(return_value); Z_TYPE_P(return_value) = IS_NULL; return NULL; } if (spl_filesystem_file_open(intern, use_include_path, 0 TSRMLS_CC) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); zval_dtor(return_value); Z_TYPE_P(return_value) = IS_NULL; return NULL; } } break; case SPL_FS_DIR: zend_restore_error_handling(&error_handling TSRMLS_CC); zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Operation not supported"); return NULL; } zend_restore_error_handling(&error_handling TSRMLS_CC); return NULL; } /* }}} */ static int spl_filesystem_is_invalid_or_dot(const char * d_name) /* {{{ */ { return d_name[0] == '\0' || spl_filesystem_is_dot(d_name); } /* }}} */ static char *spl_filesystem_object_get_pathname(spl_filesystem_object *intern, int *len TSRMLS_DC) { /* {{{ */ switch (intern->type) { case SPL_FS_INFO: case SPL_FS_FILE: *len = intern->file_name_len; return intern->file_name; case SPL_FS_DIR: if (intern->u.dir.entry.d_name[0]) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); *len = intern->file_name_len; return intern->file_name; } } *len = 0; return NULL; } /* }}} */ static HashTable* spl_filesystem_object_get_debug_info(zval *obj, int *is_temp TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(obj TSRMLS_CC); HashTable *rv; zval *tmp, zrv; char *pnstr, *path; int pnlen, path_len; char stmp[2]; *is_temp = 1; if (!intern->std.properties) { rebuild_object_properties(&intern->std); } ALLOC_HASHTABLE(rv); ZEND_INIT_SYMTABLE_EX(rv, zend_hash_num_elements(intern->std.properties) + 3, 0); INIT_PZVAL(&zrv); Z_ARRVAL(zrv) = rv; zend_hash_copy(rv, intern->std.properties, (copy_ctor_func_t) zval_add_ref, (void *) &tmp, sizeof(zval *)); pnstr = spl_gen_private_prop_name(spl_ce_SplFileInfo, "pathName", sizeof("pathName")-1, &pnlen TSRMLS_CC); path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC); add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, path, path_len, 1); efree(pnstr); if (intern->file_name) { pnstr = spl_gen_private_prop_name(spl_ce_SplFileInfo, "fileName", sizeof("fileName")-1, &pnlen TSRMLS_CC); spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); if (path_len && path_len < intern->file_name_len) { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->file_name + path_len + 1, intern->file_name_len - (path_len + 1), 1); } else { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->file_name, intern->file_name_len, 1); } efree(pnstr); } if (intern->type == SPL_FS_DIR) { #ifdef HAVE_GLOB pnstr = spl_gen_private_prop_name(spl_ce_DirectoryIterator, "glob", sizeof("glob")-1, &pnlen TSRMLS_CC); if (php_stream_is(intern->u.dir.dirp ,&php_glob_stream_ops)) { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->_path, intern->_path_len, 1); } else { add_assoc_bool_ex(&zrv, pnstr, pnlen+1, 0); } efree(pnstr); #endif pnstr = spl_gen_private_prop_name(spl_ce_RecursiveDirectoryIterator, "subPathName", sizeof("subPathName")-1, &pnlen TSRMLS_CC); if (intern->u.dir.sub_path) { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->u.dir.sub_path, intern->u.dir.sub_path_len, 1); } else { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, "", 0, 1); } efree(pnstr); } if (intern->type == SPL_FS_FILE) { pnstr = spl_gen_private_prop_name(spl_ce_SplFileObject, "openMode", sizeof("openMode")-1, &pnlen TSRMLS_CC); add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->u.file.open_mode, intern->u.file.open_mode_len, 1); efree(pnstr); stmp[1] = '\0'; stmp[0] = intern->u.file.delimiter; pnstr = spl_gen_private_prop_name(spl_ce_SplFileObject, "delimiter", sizeof("delimiter")-1, &pnlen TSRMLS_CC); add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, stmp, 1, 1); efree(pnstr); stmp[0] = intern->u.file.enclosure; pnstr = spl_gen_private_prop_name(spl_ce_SplFileObject, "enclosure", sizeof("enclosure")-1, &pnlen TSRMLS_CC); add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, stmp, 1, 1); efree(pnstr); } return rv; } /* }}} */ zend_function *spl_filesystem_object_get_method_check(zval **object_ptr, char *method, int method_len, const struct _zend_literal *key TSRMLS_DC) /* {{{ */ { spl_filesystem_object *fsobj = zend_object_store_get_object(*object_ptr TSRMLS_CC); if (fsobj->u.dir.entry.d_name[0] == '\0' && fsobj->orig_path == NULL) { method = "_bad_state_ex"; method_len = sizeof("_bad_state_ex") - 1; key = NULL; } return zend_get_std_object_handlers()->get_method(object_ptr, method, method_len, key TSRMLS_CC); } /* }}} */ #define DIT_CTOR_FLAGS 0x00000001 #define DIT_CTOR_GLOB 0x00000002 void spl_filesystem_object_construct(INTERNAL_FUNCTION_PARAMETERS, long ctor_flags) /* {{{ */ { spl_filesystem_object *intern; char *path; int parsed, len; long flags; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (SPL_HAS_FLAG(ctor_flags, DIT_CTOR_FLAGS)) { flags = SPL_FILE_DIR_KEY_AS_PATHNAME|SPL_FILE_DIR_CURRENT_AS_FILEINFO; parsed = zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &path, &len, &flags); } else { flags = SPL_FILE_DIR_KEY_AS_PATHNAME|SPL_FILE_DIR_CURRENT_AS_SELF; parsed = zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &path, &len); } if (SPL_HAS_FLAG(ctor_flags, SPL_FILE_DIR_SKIPDOTS)) { flags |= SPL_FILE_DIR_SKIPDOTS; } if (SPL_HAS_FLAG(ctor_flags, SPL_FILE_DIR_UNIXPATHS)) { flags |= SPL_FILE_DIR_UNIXPATHS; } if (parsed == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (!len) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Directory name must not be empty."); zend_restore_error_handling(&error_handling TSRMLS_CC); return; } intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); intern->flags = flags; #ifdef HAVE_GLOB if (SPL_HAS_FLAG(ctor_flags, DIT_CTOR_GLOB) && strstr(path, "glob://") != path) { spprintf(&path, 0, "glob://%s", path); spl_filesystem_dir_open(intern, path TSRMLS_CC); efree(path); } else #endif { spl_filesystem_dir_open(intern, path TSRMLS_CC); } intern->u.dir.is_recursive = instanceof_function(intern->std.ce, spl_ce_RecursiveDirectoryIterator TSRMLS_CC) ? 1 : 0; zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void DirectoryIterator::__construct(string path) Cronstructs a new dir iterator from a path. */ SPL_METHOD(DirectoryIterator, __construct) { spl_filesystem_object_construct(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto void DirectoryIterator::rewind() Rewind dir back to the start */ SPL_METHOD(DirectoryIterator, rewind) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } intern->u.dir.index = 0; if (intern->u.dir.dirp) { php_stream_rewinddir(intern->u.dir.dirp); } spl_filesystem_dir_read(intern TSRMLS_CC); } /* }}} */ /* {{{ proto string DirectoryIterator::key() Return current dir entry */ SPL_METHOD(DirectoryIterator, key) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.dirp) { RETURN_LONG(intern->u.dir.index); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto DirectoryIterator DirectoryIterator::current() Return this (needed for Iterator interface) */ SPL_METHOD(DirectoryIterator, current) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_ZVAL(getThis(), 1, 0); } /* }}} */ /* {{{ proto void DirectoryIterator::next() Move to next entry */ SPL_METHOD(DirectoryIterator, next) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); int skip_dots = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_SKIPDOTS); if (zend_parse_parameters_none() == FAILURE) { return; } intern->u.dir.index++; do { spl_filesystem_dir_read(intern TSRMLS_CC); } while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name)); if (intern->file_name) { efree(intern->file_name); intern->file_name = NULL; } } /* }}} */ /* {{{ proto void DirectoryIterator::seek(int position) Seek to the given position */ SPL_METHOD(DirectoryIterator, seek) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zval *retval = NULL; long pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &pos) == FAILURE) { return; } if (intern->u.dir.index > pos) { /* we first rewind */ zend_call_method_with_0_params(&this_ptr, Z_OBJCE_P(getThis()), &intern->u.dir.func_rewind, "rewind", &retval); if (retval) { zval_ptr_dtor(&retval); } } while (intern->u.dir.index < pos) { int valid = 0; zend_call_method_with_0_params(&this_ptr, Z_OBJCE_P(getThis()), &intern->u.dir.func_valid, "valid", &retval); if (retval) { valid = zend_is_true(retval); zval_ptr_dtor(&retval); } if (!valid) { break; } zend_call_method_with_0_params(&this_ptr, Z_OBJCE_P(getThis()), &intern->u.dir.func_next, "next", &retval); if (retval) { zval_ptr_dtor(&retval); } } } /* }}} */ /* {{{ proto string DirectoryIterator::valid() Check whether dir contains more entries */ SPL_METHOD(DirectoryIterator, valid) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(intern->u.dir.entry.d_name[0] != '\0'); } /* }}} */ /* {{{ proto string SplFileInfo::getPath() Return the path */ SPL_METHOD(SplFileInfo, getPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *path; int path_len; if (zend_parse_parameters_none() == FAILURE) { return; } path = spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); RETURN_STRINGL(path, path_len, 1); } /* }}} */ /* {{{ proto string SplFileInfo::getFilename() Return filename only */ SPL_METHOD(SplFileInfo, getFilename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); int path_len; if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); if (path_len && path_len < intern->file_name_len) { RETURN_STRINGL(intern->file_name + path_len + 1, intern->file_name_len - (path_len + 1), 1); } else { RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } } /* }}} */ /* {{{ proto string DirectoryIterator::getFilename() Return filename of current dir entry */ SPL_METHOD(DirectoryIterator, getFilename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_STRING(intern->u.dir.entry.d_name, 1); } /* }}} */ /* {{{ proto string SplFileInfo::getExtension() Returns file extension component of path */ SPL_METHOD(SplFileInfo, getExtension) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *fname = NULL; const char *p; size_t flen; int path_len, idx; if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); if (path_len && path_len < intern->file_name_len) { fname = intern->file_name + path_len + 1; flen = intern->file_name_len - (path_len + 1); } else { fname = intern->file_name; flen = intern->file_name_len; } php_basename(fname, flen, NULL, 0, &fname, &flen TSRMLS_CC); p = zend_memrchr(fname, '.', flen); if (p) { idx = p - fname; RETVAL_STRINGL(fname + idx + 1, flen - idx - 1, 1); efree(fname); return; } else { if (fname) { efree(fname); } RETURN_EMPTY_STRING(); } } /* }}}*/ /* {{{ proto string DirectoryIterator::getExtension() Returns the file extension component of path */ SPL_METHOD(DirectoryIterator, getExtension) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *fname = NULL; const char *p; size_t flen; int idx; if (zend_parse_parameters_none() == FAILURE) { return; } php_basename(intern->u.dir.entry.d_name, strlen(intern->u.dir.entry.d_name), NULL, 0, &fname, &flen TSRMLS_CC); p = zend_memrchr(fname, '.', flen); if (p) { idx = p - fname; RETVAL_STRINGL(fname + idx + 1, flen - idx - 1, 1); efree(fname); return; } else { if (fname) { efree(fname); } RETURN_EMPTY_STRING(); } } /* }}} */ /* {{{ proto string SplFileInfo::getBasename([string $suffix]) U Returns filename component of path */ SPL_METHOD(SplFileInfo, getBasename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *fname, *suffix = 0; size_t flen; int slen = 0, path_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &suffix, &slen) == FAILURE) { return; } spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); if (path_len && path_len < intern->file_name_len) { fname = intern->file_name + path_len + 1; flen = intern->file_name_len - (path_len + 1); } else { fname = intern->file_name; flen = intern->file_name_len; } php_basename(fname, flen, suffix, slen, &fname, &flen TSRMLS_CC); RETURN_STRINGL(fname, flen, 0); } /* }}}*/ /* {{{ proto string DirectoryIterator::getBasename([string $suffix]) U Returns filename component of current dir entry */ SPL_METHOD(DirectoryIterator, getBasename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *suffix = 0, *fname; int slen = 0; size_t flen; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &suffix, &slen) == FAILURE) { return; } php_basename(intern->u.dir.entry.d_name, strlen(intern->u.dir.entry.d_name), suffix, slen, &fname, &flen TSRMLS_CC); RETURN_STRINGL(fname, flen, 0); } /* }}} */ /* {{{ proto string SplFileInfo::getPathname() Return path and filename */ SPL_METHOD(SplFileInfo, getPathname) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *path; int path_len; if (zend_parse_parameters_none() == FAILURE) { return; } path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC); if (path != NULL) { RETURN_STRINGL(path, path_len, 1); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto string FilesystemIterator::key() Return getPathname() or getFilename() depending on flags */ SPL_METHOD(FilesystemIterator, key) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (SPL_FILE_DIR_KEY(intern, SPL_FILE_DIR_KEY_AS_FILENAME)) { RETURN_STRING(intern->u.dir.entry.d_name, 1); } else { spl_filesystem_object_get_file_name(intern TSRMLS_CC); RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } } /* }}} */ /* {{{ proto string FilesystemIterator::current() Return getFilename(), getFileInfo() or $this depending on flags */ SPL_METHOD(FilesystemIterator, current) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_PATHNAME)) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } else if (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_FILEINFO)) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); spl_filesystem_object_create_type(0, intern, SPL_FS_INFO, NULL, return_value TSRMLS_CC); } else { RETURN_ZVAL(getThis(), 1, 0); /*RETURN_STRING(intern->u.dir.entry.d_name, 1);*/ } } /* }}} */ /* {{{ proto bool DirectoryIterator::isDot() Returns true if current entry is '.' or '..' */ SPL_METHOD(DirectoryIterator, isDot) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(spl_filesystem_is_dot(intern->u.dir.entry.d_name)); } /* }}} */ /* {{{ proto void SplFileInfo::__construct(string file_name) Cronstructs a new SplFileInfo from a path. */ /* zend_replace_error_handling() is used to throw exceptions in case the constructor fails. Here we use this to ensure the object has a valid directory resource. When the constructor gets called the object is already created by the engine, so we must only call 'additional' initializations. */ SPL_METHOD(SplFileInfo, __construct) { spl_filesystem_object *intern; char *path; int len; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &path, &len) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_filesystem_info_set_filename(intern, path, len, 1 TSRMLS_CC); zend_restore_error_handling(&error_handling TSRMLS_CC); /* intern->type = SPL_FS_INFO; already set */ } /* }}} */ /* {{{ FileInfoFunction */ #define FileInfoFunction(func_name, func_num) \ SPL_METHOD(SplFileInfo, func_name) \ { \ spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); \ zend_error_handling error_handling; \ if (zend_parse_parameters_none() == FAILURE) { \ return; \ } \ \ zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);\ spl_filesystem_object_get_file_name(intern TSRMLS_CC); \ php_stat(intern->file_name, intern->file_name_len, func_num, return_value TSRMLS_CC); \ zend_restore_error_handling(&error_handling TSRMLS_CC); \ } /* }}} */ /* {{{ proto int SplFileInfo::getPerms() Get file permissions */ FileInfoFunction(getPerms, FS_PERMS) /* }}} */ /* {{{ proto int SplFileInfo::getInode() Get file inode */ FileInfoFunction(getInode, FS_INODE) /* }}} */ /* {{{ proto int SplFileInfo::getSize() Get file size */ FileInfoFunction(getSize, FS_SIZE) /* }}} */ /* {{{ proto int SplFileInfo::getOwner() Get file owner */ FileInfoFunction(getOwner, FS_OWNER) /* }}} */ /* {{{ proto int SplFileInfo::getGroup() Get file group */ FileInfoFunction(getGroup, FS_GROUP) /* }}} */ /* {{{ proto int SplFileInfo::getATime() Get last access time of file */ FileInfoFunction(getATime, FS_ATIME) /* }}} */ /* {{{ proto int SplFileInfo::getMTime() Get last modification time of file */ FileInfoFunction(getMTime, FS_MTIME) /* }}} */ /* {{{ proto int SplFileInfo::getCTime() Get inode modification time of file */ FileInfoFunction(getCTime, FS_CTIME) /* }}} */ /* {{{ proto string SplFileInfo::getType() Get file type */ FileInfoFunction(getType, FS_TYPE) /* }}} */ /* {{{ proto bool SplFileInfo::isWritable() Returns true if file can be written */ FileInfoFunction(isWritable, FS_IS_W) /* }}} */ /* {{{ proto bool SplFileInfo::isReadable() Returns true if file can be read */ FileInfoFunction(isReadable, FS_IS_R) /* }}} */ /* {{{ proto bool SplFileInfo::isExecutable() Returns true if file is executable */ FileInfoFunction(isExecutable, FS_IS_X) /* }}} */ /* {{{ proto bool SplFileInfo::isFile() Returns true if file is a regular file */ FileInfoFunction(isFile, FS_IS_FILE) /* }}} */ /* {{{ proto bool SplFileInfo::isDir() Returns true if file is directory */ FileInfoFunction(isDir, FS_IS_DIR) /* }}} */ /* {{{ proto bool SplFileInfo::isLink() Returns true if file is symbolic link */ FileInfoFunction(isLink, FS_IS_LINK) /* }}} */ /* {{{ proto string SplFileInfo::getLinkTarget() U Return the target of a symbolic link */ SPL_METHOD(SplFileInfo, getLinkTarget) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); int ret; char buff[MAXPATHLEN]; zend_error_handling error_handling; if (zend_parse_parameters_none() == FAILURE) { return; } zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); #if defined(PHP_WIN32) || HAVE_SYMLINK if (!IS_ABSOLUTE_PATH(intern->file_name, intern->file_name_len)) { char expanded_path[MAXPATHLEN]; if (!expand_filepath_with_mode(intern->file_name, expanded_path, NULL, 0, CWD_EXPAND TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "No such file or directory"); RETURN_FALSE; } ret = php_sys_readlink(expanded_path, buff, MAXPATHLEN - 1); } else { ret = php_sys_readlink(intern->file_name, buff, MAXPATHLEN-1); } #else ret = -1; /* always fail if not implemented */ #endif if (ret == -1) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Unable to read link %s, error: %s", intern->file_name, strerror(errno)); RETVAL_FALSE; } else { /* Append NULL to the end of the string */ buff[ret] = '\0'; RETVAL_STRINGL(buff, ret, 1); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ #if (!defined(__BEOS__) && !defined(NETWARE) && HAVE_REALPATH) || defined(ZTS) /* {{{ proto string SplFileInfo::getRealPath() Return the resolved path */ SPL_METHOD(SplFileInfo, getRealPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char buff[MAXPATHLEN]; char *filename; zend_error_handling error_handling; if (zend_parse_parameters_none() == FAILURE) { return; } zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); if (intern->type == SPL_FS_DIR && !intern->file_name && intern->u.dir.entry.d_name[0]) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); } if (intern->orig_path) { filename = intern->orig_path; } else { filename = intern->file_name; } if (filename && VCWD_REALPATH(filename, buff)) { #ifdef ZTS if (VCWD_ACCESS(buff, F_OK)) { RETVAL_FALSE; } else #endif RETVAL_STRING(buff, 1); } else { RETVAL_FALSE; } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ #endif /* {{{ proto SplFileObject SplFileInfo::openFile([string mode = 'r' [, bool use_include_path [, resource context]]]) Open the current file */ SPL_METHOD(SplFileInfo, openFile) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_filesystem_object_create_type(ht, intern, SPL_FS_FILE, NULL, return_value TSRMLS_CC); } /* }}} */ /* {{{ proto void SplFileInfo::setFileClass([string class_name]) Class to use in openFile() */ SPL_METHOD(SplFileInfo, setFileClass) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = spl_ce_SplFileObject; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { intern->file_class = ce; } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void SplFileInfo::setInfoClass([string class_name]) Class to use in getFileInfo(), getPathInfo() */ SPL_METHOD(SplFileInfo, setInfoClass) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = spl_ce_SplFileInfo; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { intern->info_class = ce; } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto SplFileInfo SplFileInfo::getFileInfo([string $class_name]) Get/copy file info */ SPL_METHOD(SplFileInfo, getFileInfo) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = intern->info_class; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { spl_filesystem_object_create_type(ht, intern, SPL_FS_INFO, ce, return_value TSRMLS_CC); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto SplFileInfo SplFileInfo::getPathInfo([string $class_name]) Get/copy file info */ SPL_METHOD(SplFileInfo, getPathInfo) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = intern->info_class; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { int path_len; char *path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC); if (path) { char *dpath = estrndup(path, path_len); path_len = php_dirname(dpath, path_len); spl_filesystem_object_create_info(intern, dpath, path_len, 1, ce, return_value TSRMLS_CC); efree(dpath); } } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ */ SPL_METHOD(SplFileInfo, _bad_state_ex) { zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "The parent constructor was not called: the object is in an " "invalid state "); } /* }}} */ /* {{{ proto void FilesystemIterator::__construct(string path [, int flags]) Cronstructs a new dir iterator from a path. */ SPL_METHOD(FilesystemIterator, __construct) { spl_filesystem_object_construct(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIT_CTOR_FLAGS | SPL_FILE_DIR_SKIPDOTS); } /* }}} */ /* {{{ proto void FilesystemIterator::rewind() Rewind dir back to the start */ SPL_METHOD(FilesystemIterator, rewind) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } intern->u.dir.index = 0; if (intern->u.dir.dirp) { php_stream_rewinddir(intern->u.dir.dirp); } do { spl_filesystem_dir_read(intern TSRMLS_CC); } while (spl_filesystem_is_dot(intern->u.dir.entry.d_name)); } /* }}} */ /* {{{ proto int FilesystemIterator::getFlags() Get handling flags */ SPL_METHOD(FilesystemIterator, getFlags) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(intern->flags & (SPL_FILE_DIR_KEY_MODE_MASK | SPL_FILE_DIR_CURRENT_MODE_MASK | SPL_FILE_DIR_OTHERS_MASK)); } /* }}} */ /* {{{ proto void FilesystemIterator::setFlags(long $flags) Set handling flags */ SPL_METHOD(FilesystemIterator, setFlags) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long flags; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &flags) == FAILURE) { return; } intern->flags &= ~(SPL_FILE_DIR_KEY_MODE_MASK|SPL_FILE_DIR_CURRENT_MODE_MASK|SPL_FILE_DIR_OTHERS_MASK); intern->flags |= ((SPL_FILE_DIR_KEY_MODE_MASK|SPL_FILE_DIR_CURRENT_MODE_MASK|SPL_FILE_DIR_OTHERS_MASK) & flags); } /* }}} */ /* {{{ proto bool RecursiveDirectoryIterator::hasChildren([bool $allow_links = false]) Returns whether current entry is a directory and not '.' or '..' */ SPL_METHOD(RecursiveDirectoryIterator, hasChildren) { zend_bool allow_links = 0; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &allow_links) == FAILURE) { return; } if (spl_filesystem_is_invalid_or_dot(intern->u.dir.entry.d_name)) { RETURN_FALSE; } else { spl_filesystem_object_get_file_name(intern TSRMLS_CC); if (!allow_links && !(intern->flags & SPL_FILE_DIR_FOLLOW_SYMLINKS)) { php_stat(intern->file_name, intern->file_name_len, FS_IS_LINK, return_value TSRMLS_CC); if (zend_is_true(return_value)) { RETURN_FALSE; } } php_stat(intern->file_name, intern->file_name_len, FS_IS_DIR, return_value TSRMLS_CC); } } /* }}} */ /* {{{ proto RecursiveDirectoryIterator DirectoryIterator::getChildren() Returns an iterator for the current entry if it is a directory */ SPL_METHOD(RecursiveDirectoryIterator, getChildren) { zval zpath, zflags; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_filesystem_object *subdir; char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH; if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_object_get_file_name(intern TSRMLS_CC); if (SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_CURRENT_AS_PATHNAME)) { RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } else { INIT_PZVAL(&zflags); INIT_PZVAL(&zpath); ZVAL_LONG(&zflags, intern->flags); ZVAL_STRINGL(&zpath, intern->file_name, intern->file_name_len, 0); spl_instantiate_arg_ex2(Z_OBJCE_P(getThis()), &return_value, 0, &zpath, &zflags TSRMLS_CC); subdir = (spl_filesystem_object*)zend_object_store_get_object(return_value TSRMLS_CC); if (subdir) { if (intern->u.dir.sub_path && intern->u.dir.sub_path[0]) { subdir->u.dir.sub_path_len = spprintf(&subdir->u.dir.sub_path, 0, "%s%c%s", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name); } else { subdir->u.dir.sub_path_len = strlen(intern->u.dir.entry.d_name); subdir->u.dir.sub_path = estrndup(intern->u.dir.entry.d_name, subdir->u.dir.sub_path_len); } subdir->info_class = intern->info_class; subdir->file_class = intern->file_class; subdir->oth = intern->oth; } } } /* }}} */ /* {{{ proto void RecursiveDirectoryIterator::getSubPath() Get sub path */ SPL_METHOD(RecursiveDirectoryIterator, getSubPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.sub_path) { RETURN_STRINGL(intern->u.dir.sub_path, intern->u.dir.sub_path_len, 1); } else { RETURN_STRINGL("", 0, 1); } } /* }}} */ /* {{{ proto void RecursiveDirectoryIterator::getSubPathname() Get sub path and file name */ SPL_METHOD(RecursiveDirectoryIterator, getSubPathname) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *sub_name; int len; char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH; if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.sub_path) { len = spprintf(&sub_name, 0, "%s%c%s", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name); RETURN_STRINGL(sub_name, len, 0); } else { RETURN_STRING(intern->u.dir.entry.d_name, 1); } } /* }}} */ /* {{{ proto int RecursiveDirectoryIterator::__construct(string path [, int flags]) Cronstructs a new dir iterator from a path. */ SPL_METHOD(RecursiveDirectoryIterator, __construct) { spl_filesystem_object_construct(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIT_CTOR_FLAGS); } /* }}} */ #ifdef HAVE_GLOB /* {{{ proto int GlobIterator::__construct(string path [, int flags]) Cronstructs a new dir iterator from a glob expression (no glob:// needed). */ SPL_METHOD(GlobIterator, __construct) { spl_filesystem_object_construct(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIT_CTOR_FLAGS|DIT_CTOR_GLOB); } /* }}} */ /* {{{ proto int GlobIterator::cont() Return the number of directories and files found by globbing */ SPL_METHOD(GlobIterator, count) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (php_stream_is(intern->u.dir.dirp ,&php_glob_stream_ops)) { RETURN_LONG(php_glob_stream_get_count(intern->u.dir.dirp, NULL)); } else { /* should not happen */ php_error_docref(NULL TSRMLS_CC, E_ERROR, "GlobIterator lost glob state"); } } /* }}} */ #endif /* HAVE_GLOB */ /* {{{ forward declarations to the iterator handlers */ static void spl_filesystem_dir_it_dtor(zend_object_iterator *iter TSRMLS_DC); static int spl_filesystem_dir_it_valid(zend_object_iterator *iter TSRMLS_DC); static void spl_filesystem_dir_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC); static int spl_filesystem_dir_it_current_key(zend_object_iterator *iter, char **str_key, uint *str_key_len, ulong *int_key TSRMLS_DC); static void spl_filesystem_dir_it_move_forward(zend_object_iterator *iter TSRMLS_DC); static void spl_filesystem_dir_it_rewind(zend_object_iterator *iter TSRMLS_DC); /* iterator handler table */ zend_object_iterator_funcs spl_filesystem_dir_it_funcs = { spl_filesystem_dir_it_dtor, spl_filesystem_dir_it_valid, spl_filesystem_dir_it_current_data, spl_filesystem_dir_it_current_key, spl_filesystem_dir_it_move_forward, spl_filesystem_dir_it_rewind }; /* }}} */ /* {{{ spl_ce_dir_get_iterator */ zend_object_iterator *spl_filesystem_dir_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) { spl_filesystem_iterator *iterator; spl_filesystem_object *dir_object; if (by_ref) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } dir_object = (spl_filesystem_object*)zend_object_store_get_object(object TSRMLS_CC); iterator = spl_filesystem_object_to_iterator(dir_object); Z_SET_REFCOUNT_P(object, Z_REFCOUNT_P(object) + 2); iterator->intern.data = (void*)object; iterator->intern.funcs = &spl_filesystem_dir_it_funcs; iterator->current = object; return (zend_object_iterator*)iterator; } /* }}} */ /* {{{ spl_filesystem_dir_it_dtor */ static void spl_filesystem_dir_it_dtor(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; zval *zfree = (zval*)iterator->intern.data; iterator->intern.data = NULL; /* mark as unused */ zval_ptr_dtor(&iterator->current); if (zfree) { zval_ptr_dtor(&zfree); } } /* }}} */ /* {{{ spl_filesystem_dir_it_valid */ static int spl_filesystem_dir_it_valid(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); return object->u.dir.entry.d_name[0] != '\0' ? SUCCESS : FAILURE; } /* }}} */ /* {{{ spl_filesystem_dir_it_current_data */ static void spl_filesystem_dir_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; *data = &iterator->current; } /* }}} */ /* {{{ spl_filesystem_dir_it_current_key */ static int spl_filesystem_dir_it_current_key(zend_object_iterator *iter, char **str_key, uint *str_key_len, ulong *int_key TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); *int_key = object->u.dir.index; return HASH_KEY_IS_LONG; } /* }}} */ /* {{{ spl_filesystem_dir_it_move_forward */ static void spl_filesystem_dir_it_move_forward(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); object->u.dir.index++; spl_filesystem_dir_read(object TSRMLS_CC); if (object->file_name) { efree(object->file_name); object->file_name = NULL; } } /* }}} */ /* {{{ spl_filesystem_dir_it_rewind */ static void spl_filesystem_dir_it_rewind(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); object->u.dir.index = 0; if (object->u.dir.dirp) { php_stream_rewinddir(object->u.dir.dirp); } spl_filesystem_dir_read(object TSRMLS_CC); } /* }}} */ /* {{{ spl_filesystem_tree_it_dtor */ static void spl_filesystem_tree_it_dtor(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; zval *zfree = (zval*)iterator->intern.data; if (iterator->current) { zval_ptr_dtor(&iterator->current); } iterator->intern.data = NULL; /* mark as unused */ /* free twice as we add ref twice */ zval_ptr_dtor(&zfree); zval_ptr_dtor(&zfree); } /* }}} */ /* {{{ spl_filesystem_tree_it_current_data */ static void spl_filesystem_tree_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator); if (SPL_FILE_DIR_CURRENT(object, SPL_FILE_DIR_CURRENT_AS_PATHNAME)) { if (!iterator->current) { ALLOC_INIT_ZVAL(iterator->current); spl_filesystem_object_get_file_name(object TSRMLS_CC); ZVAL_STRINGL(iterator->current, object->file_name, object->file_name_len, 1); } *data = &iterator->current; } else if (SPL_FILE_DIR_CURRENT(object, SPL_FILE_DIR_CURRENT_AS_FILEINFO)) { if (!iterator->current) { ALLOC_INIT_ZVAL(iterator->current); spl_filesystem_object_get_file_name(object TSRMLS_CC); spl_filesystem_object_create_type(0, object, SPL_FS_INFO, NULL, iterator->current TSRMLS_CC); } *data = &iterator->current; } else { *data = (zval**)&iterator->intern.data; } } /* }}} */ /* {{{ spl_filesystem_tree_it_current_key */ static int spl_filesystem_tree_it_current_key(zend_object_iterator *iter, char **str_key, uint *str_key_len, ulong *int_key TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); if (SPL_FILE_DIR_KEY(object, SPL_FILE_DIR_KEY_AS_FILENAME)) { *str_key_len = strlen(object->u.dir.entry.d_name) + 1; *str_key = estrndup(object->u.dir.entry.d_name, *str_key_len - 1); } else { spl_filesystem_object_get_file_name(object TSRMLS_CC); *str_key_len = object->file_name_len + 1; *str_key = estrndup(object->file_name, object->file_name_len); } return HASH_KEY_IS_STRING; } /* }}} */ /* {{{ spl_filesystem_tree_it_move_forward */ static void spl_filesystem_tree_it_move_forward(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator); object->u.dir.index++; do { spl_filesystem_dir_read(object TSRMLS_CC); } while (spl_filesystem_is_dot(object->u.dir.entry.d_name)); if (object->file_name) { efree(object->file_name); object->file_name = NULL; } if (iterator->current) { zval_ptr_dtor(&iterator->current); iterator->current = NULL; } } /* }}} */ /* {{{ spl_filesystem_tree_it_rewind */ static void spl_filesystem_tree_it_rewind(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator); object->u.dir.index = 0; if (object->u.dir.dirp) { php_stream_rewinddir(object->u.dir.dirp); } do { spl_filesystem_dir_read(object TSRMLS_CC); } while (spl_filesystem_is_dot(object->u.dir.entry.d_name)); if (iterator->current) { zval_ptr_dtor(&iterator->current); iterator->current = NULL; } } /* }}} */ /* {{{ iterator handler table */ zend_object_iterator_funcs spl_filesystem_tree_it_funcs = { spl_filesystem_tree_it_dtor, spl_filesystem_dir_it_valid, spl_filesystem_tree_it_current_data, spl_filesystem_tree_it_current_key, spl_filesystem_tree_it_move_forward, spl_filesystem_tree_it_rewind }; /* }}} */ /* {{{ spl_ce_dir_get_iterator */ zend_object_iterator *spl_filesystem_tree_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) { spl_filesystem_iterator *iterator; spl_filesystem_object *dir_object; if (by_ref) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } dir_object = (spl_filesystem_object*)zend_object_store_get_object(object TSRMLS_CC); iterator = spl_filesystem_object_to_iterator(dir_object); Z_SET_REFCOUNT_P(object, Z_REFCOUNT_P(object) + 2); iterator->intern.data = (void*)object; iterator->intern.funcs = &spl_filesystem_tree_it_funcs; iterator->current = NULL; return (zend_object_iterator*)iterator; } /* }}} */ /* {{{ spl_filesystem_object_cast */ static int spl_filesystem_object_cast(zval *readobj, zval *writeobj, int type TSRMLS_DC) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(readobj TSRMLS_CC); if (type == IS_STRING) { switch (intern->type) { case SPL_FS_INFO: case SPL_FS_FILE: if (readobj == writeobj) { zval retval; zval *retval_ptr = &retval; ZVAL_STRINGL(retval_ptr, intern->file_name, intern->file_name_len, 1); zval_dtor(readobj); ZVAL_ZVAL(writeobj, retval_ptr, 0, 0); } else { ZVAL_STRINGL(writeobj, intern->file_name, intern->file_name_len, 1); } return SUCCESS; case SPL_FS_DIR: if (readobj == writeobj) { zval retval; zval *retval_ptr = &retval; ZVAL_STRING(retval_ptr, intern->u.dir.entry.d_name, 1); zval_dtor(readobj); ZVAL_ZVAL(writeobj, retval_ptr, 0, 0); } else { ZVAL_STRING(writeobj, intern->u.dir.entry.d_name, 1); } return SUCCESS; } } if (readobj == writeobj) { zval_dtor(readobj); } ZVAL_NULL(writeobj); return FAILURE; } /* }}} */ /* {{{ declare method parameters */ /* supply a name and default to call by parameter */ ZEND_BEGIN_ARG_INFO(arginfo_info___construct, 0) ZEND_ARG_INFO(0, file_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_info_openFile, 0, 0, 0) ZEND_ARG_INFO(0, open_mode) ZEND_ARG_INFO(0, use_include_path) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_info_optinalFileClass, 0, 0, 0) ZEND_ARG_INFO(0, class_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_optinalSuffix, 0, 0, 0) ZEND_ARG_INFO(0, suffix) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_splfileinfo_void, 0) ZEND_END_ARG_INFO() /* the method table */ /* each method can have its own parameters and visibility */ static const zend_function_entry spl_SplFileInfo_functions[] = { SPL_ME(SplFileInfo, __construct, arginfo_info___construct, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getPath, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getFilename, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getExtension, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getBasename, arginfo_optinalSuffix, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getPathname, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getPerms, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getInode, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getSize, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getOwner, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getGroup, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getATime, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getMTime, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getCTime, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getType, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isWritable, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isReadable, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isExecutable, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isFile, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isDir, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isLink, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getLinkTarget, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) #if (!defined(__BEOS__) && !defined(NETWARE) && HAVE_REALPATH) || defined(ZTS) SPL_ME(SplFileInfo, getRealPath, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) #endif SPL_ME(SplFileInfo, getFileInfo, arginfo_info_optinalFileClass, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getPathInfo, arginfo_info_optinalFileClass, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, openFile, arginfo_info_openFile, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, setFileClass, arginfo_info_optinalFileClass, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, setInfoClass, arginfo_info_optinalFileClass, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, _bad_state_ex, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL) SPL_MA(SplFileInfo, __toString, SplFileInfo, getPathname, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) PHP_FE_END }; ZEND_BEGIN_ARG_INFO(arginfo_dir___construct, 0) ZEND_ARG_INFO(0, path) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_dir_it_seek, 0) ZEND_ARG_INFO(0, position) ZEND_END_ARG_INFO(); /* the method table */ /* each method can have its own parameters and visibility */ static const zend_function_entry spl_DirectoryIterator_functions[] = { SPL_ME(DirectoryIterator, __construct, arginfo_dir___construct, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, getFilename, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, getExtension, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, getBasename, arginfo_optinalSuffix, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, isDot, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, rewind, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, valid, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, key, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, current, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, next, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, seek, arginfo_dir_it_seek, ZEND_ACC_PUBLIC) SPL_MA(DirectoryIterator, __toString, DirectoryIterator, getFilename, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) PHP_FE_END }; ZEND_BEGIN_ARG_INFO_EX(arginfo_r_dir___construct, 0, 0, 1) ZEND_ARG_INFO(0, path) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_r_dir_hasChildren, 0, 0, 0) ZEND_ARG_INFO(0, allow_links) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_r_dir_setFlags, 0, 0, 0) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() static const zend_function_entry spl_FilesystemIterator_functions[] = { SPL_ME(FilesystemIterator, __construct, arginfo_r_dir___construct, ZEND_ACC_PUBLIC) SPL_ME(FilesystemIterator, rewind, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, next, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(FilesystemIterator, key, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(FilesystemIterator, current, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(FilesystemIterator, getFlags, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(FilesystemIterator, setFlags, arginfo_r_dir_setFlags, ZEND_ACC_PUBLIC) PHP_FE_END }; static const zend_function_entry spl_RecursiveDirectoryIterator_functions[] = { SPL_ME(RecursiveDirectoryIterator, __construct, arginfo_r_dir___construct, ZEND_ACC_PUBLIC) SPL_ME(RecursiveDirectoryIterator, hasChildren, arginfo_r_dir_hasChildren, ZEND_ACC_PUBLIC) SPL_ME(RecursiveDirectoryIterator, getChildren, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(RecursiveDirectoryIterator, getSubPath, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(RecursiveDirectoryIterator, getSubPathname,arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) PHP_FE_END }; #ifdef HAVE_GLOB static const zend_function_entry spl_GlobIterator_functions[] = { SPL_ME(GlobIterator, __construct, arginfo_r_dir___construct, ZEND_ACC_PUBLIC) SPL_ME(GlobIterator, count, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) PHP_FE_END }; #endif /* }}} */ static int spl_filesystem_file_read(spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */ { char *buf; size_t line_len = 0; long line_add = (intern->u.file.current_line || intern->u.file.current_zval) ? 1 : 0; spl_filesystem_file_free_line(intern TSRMLS_CC); if (php_stream_eof(intern->u.file.stream)) { if (!silent) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot read from file %s", intern->file_name); } return FAILURE; } if (intern->u.file.max_line_len > 0) { buf = safe_emalloc((intern->u.file.max_line_len + 1), sizeof(char), 0); if (php_stream_get_line(intern->u.file.stream, buf, intern->u.file.max_line_len, &line_len) == NULL) { efree(buf); buf = NULL; } else { buf[line_len] = '\0'; } } else { buf = php_stream_get_line(intern->u.file.stream, NULL, 0, &line_len); } if (!buf) { intern->u.file.current_line = estrdup(""); intern->u.file.current_line_len = 0; } else { if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_DROP_NEW_LINE)) { line_len = strcspn(buf, "\r\n"); buf[line_len] = '\0'; } intern->u.file.current_line = buf; intern->u.file.current_line_len = line_len; } intern->u.file.current_line_num += line_add; return SUCCESS; } /* }}} */ static int spl_filesystem_file_call(spl_filesystem_object *intern, zend_function *func_ptr, int pass_num_args, zval *return_value, zval *arg2 TSRMLS_DC) /* {{{ */ { zend_fcall_info fci; zend_fcall_info_cache fcic; zval z_fname; zval * zresource_ptr = &intern->u.file.zresource, *retval; int result; int num_args = pass_num_args + (arg2 ? 2 : 1); zval ***params = (zval***)safe_emalloc(num_args, sizeof(zval**), 0); params[0] = &zresource_ptr; if (arg2) { params[1] = &arg2; } zend_get_parameters_array_ex(pass_num_args, params+(arg2 ? 2 : 1)); ZVAL_STRING(&z_fname, func_ptr->common.function_name, 0); fci.size = sizeof(fci); fci.function_table = EG(function_table); fci.object_ptr = NULL; fci.function_name = &z_fname; fci.retval_ptr_ptr = &retval; fci.param_count = num_args; fci.params = params; fci.no_separation = 1; fci.symbol_table = NULL; fcic.initialized = 1; fcic.function_handler = func_ptr; fcic.calling_scope = NULL; fcic.called_scope = NULL; fcic.object_ptr = NULL; result = zend_call_function(&fci, &fcic TSRMLS_CC); if (result == FAILURE) { RETVAL_FALSE; } else { ZVAL_ZVAL(return_value, retval, 1, 1); } efree(params); return result; } /* }}} */ #define FileFunctionCall(func_name, pass_num_args, arg2) /* {{{ */ \ { \ zend_function *func_ptr; \ int ret; \ ret = zend_hash_find(EG(function_table), #func_name, sizeof(#func_name), (void **) &func_ptr); \ if (ret != SUCCESS) { \ zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Internal error, function '%s' not found. Please report", #func_name); \ return; \ } \ spl_filesystem_file_call(intern, func_ptr, pass_num_args, return_value, arg2 TSRMLS_CC); \ } /* }}} */ static int spl_filesystem_file_read_csv(spl_filesystem_object *intern, char delimiter, char enclosure, char escape, zval *return_value TSRMLS_DC) /* {{{ */ { int ret = SUCCESS; do { ret = spl_filesystem_file_read(intern, 1 TSRMLS_CC); } while (ret == SUCCESS && !intern->u.file.current_line_len && SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY)); if (ret == SUCCESS) { size_t buf_len = intern->u.file.current_line_len; char *buf = estrndup(intern->u.file.current_line, buf_len); if (intern->u.file.current_zval) { zval_ptr_dtor(&intern->u.file.current_zval); } ALLOC_INIT_ZVAL(intern->u.file.current_zval); php_fgetcsv(intern->u.file.stream, delimiter, enclosure, escape, buf_len, buf, intern->u.file.current_zval TSRMLS_CC); if (return_value) { if (Z_TYPE_P(return_value) != IS_NULL) { zval_dtor(return_value); ZVAL_NULL(return_value); } ZVAL_ZVAL(return_value, intern->u.file.current_zval, 1, 0); } } return ret; } /* }}} */ static int spl_filesystem_file_read_line_ex(zval * this_ptr, spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */ { zval *retval = NULL; /* 1) use fgetcsv? 2) overloaded call the function, 3) do it directly */ if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) || intern->u.file.func_getCurr->common.scope != spl_ce_SplFileObject) { if (php_stream_eof(intern->u.file.stream)) { if (!silent) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot read from file %s", intern->file_name); } return FAILURE; } if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV)) { return spl_filesystem_file_read_csv(intern, intern->u.file.delimiter, intern->u.file.enclosure, intern->u.file.escape, NULL TSRMLS_CC); } else { zend_call_method_with_0_params(&this_ptr, Z_OBJCE_P(getThis()), &intern->u.file.func_getCurr, "getCurrentLine", &retval); } if (retval) { if (intern->u.file.current_line || intern->u.file.current_zval) { intern->u.file.current_line_num++; } spl_filesystem_file_free_line(intern TSRMLS_CC); if (Z_TYPE_P(retval) == IS_STRING) { intern->u.file.current_line = estrndup(Z_STRVAL_P(retval), Z_STRLEN_P(retval)); intern->u.file.current_line_len = Z_STRLEN_P(retval); } else { MAKE_STD_ZVAL(intern->u.file.current_zval); ZVAL_ZVAL(intern->u.file.current_zval, retval, 1, 0); } zval_ptr_dtor(&retval); return SUCCESS; } else { return FAILURE; } } else { return spl_filesystem_file_read(intern, silent TSRMLS_CC); } } /* }}} */ static int spl_filesystem_file_is_empty_line(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { if (intern->u.file.current_line) { return intern->u.file.current_line_len == 0; } else if (intern->u.file.current_zval) { switch(Z_TYPE_P(intern->u.file.current_zval)) { case IS_STRING: return Z_STRLEN_P(intern->u.file.current_zval) == 0; case IS_ARRAY: if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) && zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 1) { zval ** first = Z_ARRVAL_P(intern->u.file.current_zval)->pListHead->pData; return Z_TYPE_PP(first) == IS_STRING && Z_STRLEN_PP(first) == 0; } return zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 0; case IS_NULL: return 1; default: return 0; } } else { return 1; } } /* }}} */ static int spl_filesystem_file_read_line(zval * this_ptr, spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */ { int ret = spl_filesystem_file_read_line_ex(this_ptr, intern, silent TSRMLS_CC); while (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY) && ret == SUCCESS && spl_filesystem_file_is_empty_line(intern TSRMLS_CC)) { spl_filesystem_file_free_line(intern TSRMLS_CC); ret = spl_filesystem_file_read_line_ex(this_ptr, intern, silent TSRMLS_CC); } return ret; } /* }}} */ static void spl_filesystem_file_rewind(zval * this_ptr, spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { if (-1 == php_stream_rewind(intern->u.file.stream)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot rewind file %s", intern->file_name); } else { spl_filesystem_file_free_line(intern TSRMLS_CC); intern->u.file.current_line_num = 0; } if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_AHEAD)) { spl_filesystem_file_read_line(this_ptr, intern, 1 TSRMLS_CC); } } /* }}} */ /* {{{ proto void SplFileObject::__construct(string filename [, string mode = 'r' [, bool use_include_path [, resource context]]]]) Construct a new file object */ SPL_METHOD(SplFileObject, __construct) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_bool use_include_path = 0; char *p1, *p2; char *tmp_path; int tmp_path_len; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); intern->u.file.open_mode = NULL; intern->u.file.open_mode_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|sbr", &intern->file_name, &intern->file_name_len, &intern->u.file.open_mode, &intern->u.file.open_mode_len, &use_include_path, &intern->u.file.zcontext) == FAILURE) { intern->u.file.open_mode = NULL; intern->file_name = NULL; zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (intern->u.file.open_mode == NULL) { intern->u.file.open_mode = "r"; intern->u.file.open_mode_len = 1; } if (spl_filesystem_file_open(intern, use_include_path, 0 TSRMLS_CC) == SUCCESS) { tmp_path_len = strlen(intern->u.file.stream->orig_path); if (tmp_path_len > 1 && IS_SLASH_AT(intern->u.file.stream->orig_path, tmp_path_len-1)) { tmp_path_len--; } tmp_path = estrndup(intern->u.file.stream->orig_path, tmp_path_len); p1 = strrchr(tmp_path, '/'); #if defined(PHP_WIN32) || defined(NETWARE) p2 = strrchr(tmp_path, '\\'); #else p2 = 0; #endif if (p1 || p2) { intern->_path_len = (p1 > p2 ? p1 : p2) - tmp_path; } else { intern->_path_len = 0; } efree(tmp_path); intern->_path = estrndup(intern->u.file.stream->orig_path, intern->_path_len); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void SplTempFileObject::__construct([int max_memory]) Construct a new temp file object */ SPL_METHOD(SplTempFileObject, __construct) { long max_memory = PHP_STREAM_MAX_MEM; char tmp_fname[48]; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &max_memory) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (max_memory < 0) { intern->file_name = "php://memory"; intern->file_name_len = 12; } else if (ZEND_NUM_ARGS()) { intern->file_name_len = slprintf(tmp_fname, sizeof(tmp_fname), "php://temp/maxmemory:%ld", max_memory); intern->file_name = tmp_fname; } else { intern->file_name = "php://temp"; intern->file_name_len = 10; } intern->u.file.open_mode = "wb"; intern->u.file.open_mode_len = 1; intern->u.file.zcontext = NULL; if (spl_filesystem_file_open(intern, 0, 0 TSRMLS_CC) == SUCCESS) { intern->_path_len = 0; intern->_path = estrndup("", 0); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void SplFileObject::rewind() Rewind the file and read the first line */ SPL_METHOD(SplFileObject, rewind) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC); } /* }}} */ /* {{{ proto void SplFileObject::eof() Return whether end of file is reached */ SPL_METHOD(SplFileObject, eof) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(php_stream_eof(intern->u.file.stream)); } /* }}} */ /* {{{ proto void SplFileObject::valid() Return !eof() */ SPL_METHOD(SplFileObject, valid) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_AHEAD)) { RETURN_BOOL(intern->u.file.current_line || intern->u.file.current_zval); } else { RETVAL_BOOL(!php_stream_eof(intern->u.file.stream)); } } /* }}} */ /* {{{ proto string SplFileObject::fgets() Rturn next line from file */ SPL_METHOD(SplFileObject, fgets) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (spl_filesystem_file_read(intern, 0 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1); } /* }}} */ /* {{{ proto string SplFileObject::current() Return current line from file */ SPL_METHOD(SplFileObject, current) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!intern->u.file.current_line && !intern->u.file.current_zval) { spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC); } if (intern->u.file.current_line && (!SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) || !intern->u.file.current_zval)) { RETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1); } else if (intern->u.file.current_zval) { RETURN_ZVAL(intern->u.file.current_zval, 1, 0); } RETURN_FALSE; } /* }}} */ /* {{{ proto int SplFileObject::key() Return line number */ SPL_METHOD(SplFileObject, key) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } /* Do not read the next line to support correct counting with fgetc() if (!intern->current_line) { spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC); } */ RETURN_LONG(intern->u.file.current_line_num); } /* }}} */ /* {{{ proto void SplFileObject::next() Read next line */ SPL_METHOD(SplFileObject, next) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_file_free_line(intern TSRMLS_CC); if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_AHEAD)) { spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC); } intern->u.file.current_line_num++; } /* }}} */ /* {{{ proto void SplFileObject::setFlags(int flags) Set file handling flags */ SPL_METHOD(SplFileObject, setFlags) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &intern->flags) == FAILURE) { return; } } /* }}} */ /* {{{ proto int SplFileObject::getFlags() Get file handling flags */ SPL_METHOD(SplFileObject, getFlags) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(intern->flags & SPL_FILE_OBJECT_MASK); } /* }}} */ /* {{{ proto void SplFileObject::setMaxLineLen(int max_len) Set maximum line length */ SPL_METHOD(SplFileObject, setMaxLineLen) { long max_len; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &max_len) == FAILURE) { return; } if (max_len < 0) { zend_throw_exception_ex(spl_ce_DomainException, 0 TSRMLS_CC, "Maximum line length must be greater than or equal zero"); return; } intern->u.file.max_line_len = max_len; } /* }}} */ /* {{{ proto int SplFileObject::getMaxLineLen() Get maximum line length */ SPL_METHOD(SplFileObject, getMaxLineLen) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG((long)intern->u.file.max_line_len); } /* }}} */ /* {{{ proto bool SplFileObject::hasChildren() Return false */ SPL_METHOD(SplFileObject, hasChildren) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_FALSE; } /* }}} */ /* {{{ proto bool SplFileObject::getChildren() Read NULL */ SPL_METHOD(SplFileObject, getChildren) { if (zend_parse_parameters_none() == FAILURE) { return; } /* return NULL */ } /* }}} */ /* {{{ FileFunction */ #define FileFunction(func_name) \ SPL_METHOD(SplFileObject, func_name) \ { \ spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); \ FileFunctionCall(func_name, ZEND_NUM_ARGS(), NULL); \ } /* }}} */ /* {{{ proto array SplFileObject::fgetcsv([string delimiter [, string enclosure [, escape = '\\']]]) Return current line as csv */ SPL_METHOD(SplFileObject, fgetcsv) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter = intern->u.file.delimiter, enclosure = intern->u.file.enclosure, escape = intern->u.file.escape; char *delim = NULL, *enclo = NULL, *esc = NULL; int d_len = 0, e_len = 0, esc_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sss", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) { switch(ZEND_NUM_ARGS()) { case 3: if (esc_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character"); RETURN_FALSE; } escape = esc[0]; /* no break */ case 2: if (e_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } enclosure = enclo[0]; /* no break */ case 1: if (d_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } delimiter = delim[0]; /* no break */ case 0: break; } spl_filesystem_file_read_csv(intern, delimiter, enclosure, escape, return_value TSRMLS_CC); } } /* }}} */ /* {{{ proto int SplFileObject::fputcsv(array fields, [string delimiter [, string enclosure]]) Output a field array as a CSV line */ SPL_METHOD(SplFileObject, fputcsv) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter = intern->u.file.delimiter, enclosure = intern->u.file.enclosure, escape = intern->u.file.escape; char *delim = NULL, *enclo = NULL; int d_len = 0, e_len = 0, ret; zval *fields = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|ss", &fields, &delim, &d_len, &enclo, &e_len) == SUCCESS) { switch(ZEND_NUM_ARGS()) { case 3: if (e_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } enclosure = enclo[0]; /* no break */ case 2: if (d_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } delimiter = delim[0]; /* no break */ case 1: case 0: break; } ret = php_fputcsv(intern->u.file.stream, fields, delimiter, enclosure, escape TSRMLS_CC); RETURN_LONG(ret); } } /* }}} */ /* {{{ proto void SplFileObject::setCsvControl([string delimiter = ',' [, string enclosure = '"' [, string escape = '\\']]]) Set the delimiter and enclosure character used in fgetcsv */ SPL_METHOD(SplFileObject, setCsvControl) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter = ',', enclosure = '"', escape='\\'; char *delim = NULL, *enclo = NULL, *esc = NULL; int d_len = 0, e_len = 0, esc_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sss", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) { switch(ZEND_NUM_ARGS()) { case 3: if (esc_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character"); RETURN_FALSE; } escape = esc[0]; /* no break */ case 2: if (e_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } enclosure = enclo[0]; /* no break */ case 1: if (d_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } delimiter = delim[0]; /* no break */ case 0: break; } intern->u.file.delimiter = delimiter; intern->u.file.enclosure = enclosure; intern->u.file.escape = escape; } } /* }}} */ /* {{{ proto array SplFileObject::getCsvControl() Get the delimiter and enclosure character used in fgetcsv */ SPL_METHOD(SplFileObject, getCsvControl) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter[2], enclosure[2]; array_init(return_value); delimiter[0] = intern->u.file.delimiter; delimiter[1] = '\0'; enclosure[0] = intern->u.file.enclosure; enclosure[1] = '\0'; add_next_index_string(return_value, delimiter, 1); add_next_index_string(return_value, enclosure, 1); } /* }}} */ /* {{{ proto bool SplFileObject::flock(int operation [, int &wouldblock]) Portable file locking */ FileFunction(flock) /* }}} */ /* {{{ proto bool SplFileObject::fflush() Flush the file */ SPL_METHOD(SplFileObject, fflush) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); RETURN_BOOL(!php_stream_flush(intern->u.file.stream)); } /* }}} */ /* {{{ proto int SplFileObject::ftell() Return current file position */ SPL_METHOD(SplFileObject, ftell) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long ret = php_stream_tell(intern->u.file.stream); if (ret == -1) { RETURN_FALSE; } else { RETURN_LONG(ret); } } /* }}} */ /* {{{ proto int SplFileObject::fseek(int pos [, int whence = SEEK_SET]) Return current file position */ SPL_METHOD(SplFileObject, fseek) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long pos, whence = SEEK_SET; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|l", &pos, &whence) == FAILURE) { return; } spl_filesystem_file_free_line(intern TSRMLS_CC); RETURN_LONG(php_stream_seek(intern->u.file.stream, pos, whence)); } /* }}} */ /* {{{ proto int SplFileObject::fgetc() Get a character form the file */ SPL_METHOD(SplFileObject, fgetc) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char buf[2]; int result; spl_filesystem_file_free_line(intern TSRMLS_CC); result = php_stream_getc(intern->u.file.stream); if (result == EOF) { RETVAL_FALSE; } else { if (result == '\n') { intern->u.file.current_line_num++; } buf[0] = result; buf[1] = '\0'; RETURN_STRINGL(buf, 1, 1); } } /* }}} */ /* {{{ proto string SplFileObject::fgetss([string allowable_tags]) Get a line from file pointer and strip HTML tags */ SPL_METHOD(SplFileObject, fgetss) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zval *arg2 = NULL; MAKE_STD_ZVAL(arg2); if (intern->u.file.max_line_len > 0) { ZVAL_LONG(arg2, intern->u.file.max_line_len); } else { ZVAL_LONG(arg2, 1024); } spl_filesystem_file_free_line(intern TSRMLS_CC); intern->u.file.current_line_num++; FileFunctionCall(fgetss, ZEND_NUM_ARGS(), arg2); zval_ptr_dtor(&arg2); } /* }}} */ /* {{{ proto int SplFileObject::fpassthru() Output all remaining data from a file pointer */ SPL_METHOD(SplFileObject, fpassthru) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); RETURN_LONG(php_stream_passthru(intern->u.file.stream)); } /* }}} */ /* {{{ proto bool SplFileObject::fscanf(string format [, string ...]) Implements a mostly ANSI compatible fscanf() */ SPL_METHOD(SplFileObject, fscanf) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_filesystem_file_free_line(intern TSRMLS_CC); intern->u.file.current_line_num++; FileFunctionCall(fscanf, ZEND_NUM_ARGS(), NULL); } /* }}} */ /* {{{ proto mixed SplFileObject::fwrite(string str [, int length]) Binary-safe file write */ SPL_METHOD(SplFileObject, fwrite) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *str; int str_len; long length = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &str, &str_len, &length) == FAILURE) { return; } if (ZEND_NUM_ARGS() > 1) { str_len = MAX(0, MIN(length, str_len)); } if (!str_len) { RETURN_LONG(0); } RETURN_LONG(php_stream_write(intern->u.file.stream, str, str_len)); } /* }}} */ /* {{{ proto bool SplFileObject::fstat() Stat() on a filehandle */ FileFunction(fstat) /* }}} */ /* {{{ proto bool SplFileObject::ftruncate(int size) Truncate file to 'size' length */ SPL_METHOD(SplFileObject, ftruncate) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long size; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &size) == FAILURE) { return; } if (!php_stream_truncate_supported(intern->u.file.stream)) { zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Can't truncate file %s", intern->file_name); RETURN_FALSE; } RETURN_BOOL(0 == php_stream_truncate_set_size(intern->u.file.stream, size)); } /* }}} */ /* {{{ proto void SplFileObject::seek(int line_pos) Seek to specified line */ SPL_METHOD(SplFileObject, seek) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long line_pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &line_pos) == FAILURE) { return; } if (line_pos < 0) { zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Can't seek file %s to negative line %ld", intern->file_name, line_pos); RETURN_FALSE; } spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC); while(intern->u.file.current_line_num < line_pos) { if (spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC) == FAILURE) { break; } } } /* }}} */ /* {{{ Function/Class/Method definitions */ ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object___construct, 0, 0, 1) ZEND_ARG_INFO(0, file_name) ZEND_ARG_INFO(0, open_mode) ZEND_ARG_INFO(0, use_include_path) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_file_object_setFlags, 0) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_file_object_setMaxLineLen, 0) ZEND_ARG_INFO(0, max_len) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fgetcsv, 0, 0, 0) ZEND_ARG_INFO(0, delimiter) ZEND_ARG_INFO(0, enclosure) ZEND_ARG_INFO(0, escape) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fputcsv, 0, 0, 1) ZEND_ARG_INFO(0, fields) ZEND_ARG_INFO(0, delimiter) ZEND_ARG_INFO(0, enclosure) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_flock, 0, 0, 1) ZEND_ARG_INFO(0, operation) ZEND_ARG_INFO(1, wouldblock) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fseek, 0, 0, 1) ZEND_ARG_INFO(0, pos) ZEND_ARG_INFO(0, whence) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fgetss, 0, 0, 0) ZEND_ARG_INFO(0, allowable_tags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fscanf, 1, 0, 1) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fwrite, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, length) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_ftruncate, 0, 0, 1) ZEND_ARG_INFO(0, size) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_seek, 0, 0, 1) ZEND_ARG_INFO(0, line_pos) ZEND_END_ARG_INFO() static const zend_function_entry spl_SplFileObject_functions[] = { SPL_ME(SplFileObject, __construct, arginfo_file_object___construct, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, rewind, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, eof, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, valid, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fgets, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fgetcsv, arginfo_file_object_fgetcsv, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fputcsv, arginfo_file_object_fputcsv, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, setCsvControl, arginfo_file_object_fgetcsv, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, getCsvControl, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, flock, arginfo_file_object_flock, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fflush, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, ftell, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fseek, arginfo_file_object_fseek, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fgetc, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fpassthru, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fgetss, arginfo_file_object_fgetss, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fscanf, arginfo_file_object_fscanf, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fwrite, arginfo_file_object_fwrite, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fstat, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, ftruncate, arginfo_file_object_ftruncate, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, current, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, key, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, next, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, setFlags, arginfo_file_object_setFlags, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, getFlags, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, setMaxLineLen, arginfo_file_object_setMaxLineLen, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, getMaxLineLen, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, hasChildren, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, getChildren, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, seek, arginfo_file_object_seek, ZEND_ACC_PUBLIC) /* mappings */ SPL_MA(SplFileObject, getCurrentLine, SplFileObject, fgets, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_MA(SplFileObject, __toString, SplFileObject, current, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) PHP_FE_END }; ZEND_BEGIN_ARG_INFO_EX(arginfo_temp_file_object___construct, 0, 0, 0) ZEND_ARG_INFO(0, max_memory) ZEND_END_ARG_INFO() static const zend_function_entry spl_SplTempFileObject_functions[] = { SPL_ME(SplTempFileObject, __construct, arginfo_temp_file_object___construct, ZEND_ACC_PUBLIC) PHP_FE_END }; /* }}} */ /* {{{ PHP_MINIT_FUNCTION(spl_directory) */ PHP_MINIT_FUNCTION(spl_directory) { REGISTER_SPL_STD_CLASS_EX(SplFileInfo, spl_filesystem_object_new, spl_SplFileInfo_functions); memcpy(&spl_filesystem_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); spl_filesystem_object_handlers.clone_obj = spl_filesystem_object_clone; spl_filesystem_object_handlers.cast_object = spl_filesystem_object_cast; spl_filesystem_object_handlers.get_debug_info = spl_filesystem_object_get_debug_info; spl_ce_SplFileInfo->serialize = zend_class_serialize_deny; spl_ce_SplFileInfo->unserialize = zend_class_unserialize_deny; REGISTER_SPL_SUB_CLASS_EX(DirectoryIterator, SplFileInfo, spl_filesystem_object_new, spl_DirectoryIterator_functions); zend_class_implements(spl_ce_DirectoryIterator TSRMLS_CC, 1, zend_ce_iterator); REGISTER_SPL_IMPLEMENTS(DirectoryIterator, SeekableIterator); spl_ce_DirectoryIterator->get_iterator = spl_filesystem_dir_get_iterator; REGISTER_SPL_SUB_CLASS_EX(FilesystemIterator, DirectoryIterator, spl_filesystem_object_new, spl_FilesystemIterator_functions); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_MODE_MASK", SPL_FILE_DIR_CURRENT_MODE_MASK); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_PATHNAME", SPL_FILE_DIR_CURRENT_AS_PATHNAME); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_FILEINFO", SPL_FILE_DIR_CURRENT_AS_FILEINFO); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_SELF", SPL_FILE_DIR_CURRENT_AS_SELF); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_MODE_MASK", SPL_FILE_DIR_KEY_MODE_MASK); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_AS_PATHNAME", SPL_FILE_DIR_KEY_AS_PATHNAME); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "FOLLOW_SYMLINKS", SPL_FILE_DIR_FOLLOW_SYMLINKS); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_AS_FILENAME", SPL_FILE_DIR_KEY_AS_FILENAME); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "NEW_CURRENT_AND_KEY", SPL_FILE_DIR_KEY_AS_FILENAME|SPL_FILE_DIR_CURRENT_AS_FILEINFO); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "SKIP_DOTS", SPL_FILE_DIR_SKIPDOTS); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "UNIX_PATHS", SPL_FILE_DIR_UNIXPATHS); spl_ce_FilesystemIterator->get_iterator = spl_filesystem_tree_get_iterator; REGISTER_SPL_SUB_CLASS_EX(RecursiveDirectoryIterator, FilesystemIterator, spl_filesystem_object_new, spl_RecursiveDirectoryIterator_functions); REGISTER_SPL_IMPLEMENTS(RecursiveDirectoryIterator, RecursiveIterator); memcpy(&spl_filesystem_object_check_handlers, &spl_filesystem_object_handlers, sizeof(zend_object_handlers)); spl_filesystem_object_check_handlers.get_method = spl_filesystem_object_get_method_check; #ifdef HAVE_GLOB REGISTER_SPL_SUB_CLASS_EX(GlobIterator, FilesystemIterator, spl_filesystem_object_new_check, spl_GlobIterator_functions); REGISTER_SPL_IMPLEMENTS(GlobIterator, Countable); #endif REGISTER_SPL_SUB_CLASS_EX(SplFileObject, SplFileInfo, spl_filesystem_object_new_check, spl_SplFileObject_functions); REGISTER_SPL_IMPLEMENTS(SplFileObject, RecursiveIterator); REGISTER_SPL_IMPLEMENTS(SplFileObject, SeekableIterator); REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "DROP_NEW_LINE", SPL_FILE_OBJECT_DROP_NEW_LINE); REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "READ_AHEAD", SPL_FILE_OBJECT_READ_AHEAD); REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "SKIP_EMPTY", SPL_FILE_OBJECT_SKIP_EMPTY); REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "READ_CSV", SPL_FILE_OBJECT_READ_CSV); REGISTER_SPL_SUB_CLASS_EX(SplTempFileObject, SplFileObject, spl_filesystem_object_new_check, spl_SplTempFileObject_functions); return SUCCESS; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Marcus Boerger <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" #include "ext/standard/file.h" #include "ext/standard/php_string.h" #include "zend_compile.h" #include "zend_exceptions.h" #include "zend_interfaces.h" #include "php_spl.h" #include "spl_functions.h" #include "spl_engine.h" #include "spl_iterators.h" #include "spl_directory.h" #include "spl_exceptions.h" #include "php.h" #include "fopen_wrappers.h" #include "ext/standard/basic_functions.h" #include "ext/standard/php_filestat.h" #define SPL_HAS_FLAG(flags, test_flag) ((flags & test_flag) ? 1 : 0) /* declare the class handlers */ static zend_object_handlers spl_filesystem_object_handlers; /* includes handler to validate object state when retrieving methods */ static zend_object_handlers spl_filesystem_object_check_handlers; /* decalre the class entry */ PHPAPI zend_class_entry *spl_ce_SplFileInfo; PHPAPI zend_class_entry *spl_ce_DirectoryIterator; PHPAPI zend_class_entry *spl_ce_FilesystemIterator; PHPAPI zend_class_entry *spl_ce_RecursiveDirectoryIterator; PHPAPI zend_class_entry *spl_ce_GlobIterator; PHPAPI zend_class_entry *spl_ce_SplFileObject; PHPAPI zend_class_entry *spl_ce_SplTempFileObject; static void spl_filesystem_file_free_line(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { if (intern->u.file.current_line) { efree(intern->u.file.current_line); intern->u.file.current_line = NULL; } if (intern->u.file.current_zval) { zval_ptr_dtor(&intern->u.file.current_zval); intern->u.file.current_zval = NULL; } } /* }}} */ static void spl_filesystem_object_free_storage(void *object TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern = (spl_filesystem_object*)object; if (intern->oth_handler && intern->oth_handler->dtor) { intern->oth_handler->dtor(intern TSRMLS_CC); } zend_object_std_dtor(&intern->std TSRMLS_CC); if (intern->_path) { efree(intern->_path); } if (intern->file_name) { efree(intern->file_name); } switch(intern->type) { case SPL_FS_INFO: break; case SPL_FS_DIR: if (intern->u.dir.dirp) { php_stream_close(intern->u.dir.dirp); intern->u.dir.dirp = NULL; } if (intern->u.dir.sub_path) { efree(intern->u.dir.sub_path); } break; case SPL_FS_FILE: if (intern->u.file.stream) { if (intern->u.file.zcontext) { /* zend_list_delref(Z_RESVAL_P(intern->zcontext));*/ } if (!intern->u.file.stream->is_persistent) { php_stream_free(intern->u.file.stream, PHP_STREAM_FREE_CLOSE); } else { php_stream_free(intern->u.file.stream, PHP_STREAM_FREE_CLOSE_PERSISTENT); } if (intern->u.file.open_mode) { efree(intern->u.file.open_mode); } if (intern->orig_path) { efree(intern->orig_path); } } spl_filesystem_file_free_line(intern TSRMLS_CC); break; } efree(object); } /* }}} */ /* {{{ spl_ce_dir_object_new */ /* creates the object by - allocating memory - initializing the object members - storing the object - setting it's handlers called from - clone - new */ static zend_object_value spl_filesystem_object_new_ex(zend_class_entry *class_type, spl_filesystem_object **obj TSRMLS_DC) { zend_object_value retval; spl_filesystem_object *intern; intern = emalloc(sizeof(spl_filesystem_object)); memset(intern, 0, sizeof(spl_filesystem_object)); /* intern->type = SPL_FS_INFO; done by set 0 */ intern->file_class = spl_ce_SplFileObject; intern->info_class = spl_ce_SplFileInfo; if (obj) *obj = intern; zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, (zend_objects_free_object_storage_t) spl_filesystem_object_free_storage, NULL TSRMLS_CC); retval.handlers = &spl_filesystem_object_handlers; return retval; } /* }}} */ /* {{{ spl_filesystem_object_new */ /* See spl_filesystem_object_new_ex */ static zend_object_value spl_filesystem_object_new(zend_class_entry *class_type TSRMLS_DC) { return spl_filesystem_object_new_ex(class_type, NULL TSRMLS_CC); } /* }}} */ /* {{{ spl_filesystem_object_new_ex */ static zend_object_value spl_filesystem_object_new_check(zend_class_entry *class_type TSRMLS_DC) { zend_object_value ret = spl_filesystem_object_new_ex(class_type, NULL TSRMLS_CC); ret.handlers = &spl_filesystem_object_check_handlers; return ret; } /* }}} */ PHPAPI char* spl_filesystem_object_get_path(spl_filesystem_object *intern, int *len TSRMLS_DC) /* {{{ */ { #ifdef HAVE_GLOB if (intern->type == SPL_FS_DIR) { if (php_stream_is(intern->u.dir.dirp ,&php_glob_stream_ops)) { return php_glob_stream_get_path(intern->u.dir.dirp, 0, len); } } #endif if (len) { *len = intern->_path_len; } return intern->_path; } /* }}} */ static inline void spl_filesystem_object_get_file_name(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH; if (!intern->file_name) { switch (intern->type) { case SPL_FS_INFO: case SPL_FS_FILE: php_error_docref(NULL TSRMLS_CC, E_ERROR, "Object not initialized"); break; case SPL_FS_DIR: intern->file_name_len = spprintf(&intern->file_name, 0, "%s%c%s", spl_filesystem_object_get_path(intern, NULL TSRMLS_CC), slash, intern->u.dir.entry.d_name); break; } } } /* }}} */ static int spl_filesystem_dir_read(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { if (!intern->u.dir.dirp || !php_stream_readdir(intern->u.dir.dirp, &intern->u.dir.entry)) { intern->u.dir.entry.d_name[0] = '\0'; return 0; } else { return 1; } } /* }}} */ #define IS_SLASH_AT(zs, pos) (IS_SLASH(zs[pos])) static inline int spl_filesystem_is_dot(const char * d_name) /* {{{ */ { return !strcmp(d_name, ".") || !strcmp(d_name, ".."); } /* }}} */ /* {{{ spl_filesystem_dir_open */ /* open a directory resource */ static void spl_filesystem_dir_open(spl_filesystem_object* intern, char *path TSRMLS_DC) { int skip_dots = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_SKIPDOTS); intern->type = SPL_FS_DIR; intern->_path_len = strlen(path); intern->u.dir.dirp = php_stream_opendir(path, REPORT_ERRORS, FG(default_context)); if (intern->_path_len > 1 && IS_SLASH_AT(path, intern->_path_len-1)) { intern->_path = estrndup(path, --intern->_path_len); } else { intern->_path = estrndup(path, intern->_path_len); } intern->u.dir.index = 0; if (EG(exception) || intern->u.dir.dirp == NULL) { intern->u.dir.entry.d_name[0] = '\0'; if (!EG(exception)) { /* open failed w/out notice (turned to exception due to EH_THROW) */ zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Failed to open directory \"%s\"", path); } } else { do { spl_filesystem_dir_read(intern TSRMLS_CC); } while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name)); } } /* }}} */ static int spl_filesystem_file_open(spl_filesystem_object *intern, int use_include_path, int silent TSRMLS_DC) /* {{{ */ { zval tmp; intern->type = SPL_FS_FILE; php_stat(intern->file_name, intern->file_name_len, FS_IS_DIR, &tmp TSRMLS_CC); if (Z_LVAL(tmp)) { intern->u.file.open_mode = NULL; intern->file_name = NULL; zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Cannot use SplFileObject with directories"); return FAILURE; } intern->u.file.context = php_stream_context_from_zval(intern->u.file.zcontext, 0); intern->u.file.stream = php_stream_open_wrapper_ex(intern->file_name, intern->u.file.open_mode, (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, intern->u.file.context); if (!intern->file_name_len || !intern->u.file.stream) { if (!EG(exception)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot open file '%s'", intern->file_name_len ? intern->file_name : ""); } intern->file_name = NULL; /* until here it is not a copy */ intern->u.file.open_mode = NULL; return FAILURE; } if (intern->u.file.zcontext) { zend_list_addref(Z_RESVAL_P(intern->u.file.zcontext)); } if (intern->file_name_len > 1 && IS_SLASH_AT(intern->file_name, intern->file_name_len-1)) { intern->file_name_len--; } intern->orig_path = estrndup(intern->u.file.stream->orig_path, strlen(intern->u.file.stream->orig_path)); intern->file_name = estrndup(intern->file_name, intern->file_name_len); intern->u.file.open_mode = estrndup(intern->u.file.open_mode, intern->u.file.open_mode_len); /* avoid reference counting in debug mode, thus do it manually */ ZVAL_RESOURCE(&intern->u.file.zresource, php_stream_get_resource_id(intern->u.file.stream)); Z_SET_REFCOUNT(intern->u.file.zresource, 1); intern->u.file.delimiter = ','; intern->u.file.enclosure = '"'; intern->u.file.escape = '\\'; zend_hash_find(&intern->std.ce->function_table, "getcurrentline", sizeof("getcurrentline"), (void **) &intern->u.file.func_getCurr); return SUCCESS; } /* }}} */ /* {{{ spl_filesystem_object_clone */ /* Local zend_object_value creation (on stack) Load the 'other' object Create a new empty object (See spl_filesystem_object_new_ex) Open the directory Clone other members (properties) */ static zend_object_value spl_filesystem_object_clone(zval *zobject TSRMLS_DC) { zend_object_value new_obj_val; zend_object *old_object; zend_object *new_object; zend_object_handle handle = Z_OBJ_HANDLE_P(zobject); spl_filesystem_object *intern; spl_filesystem_object *source; int index, skip_dots; old_object = zend_objects_get_address(zobject TSRMLS_CC); source = (spl_filesystem_object*)old_object; new_obj_val = spl_filesystem_object_new_ex(old_object->ce, &intern TSRMLS_CC); new_object = &intern->std; intern->flags = source->flags; switch (source->type) { case SPL_FS_INFO: intern->_path_len = source->_path_len; intern->_path = estrndup(source->_path, source->_path_len); intern->file_name_len = source->file_name_len; intern->file_name = estrndup(source->file_name, intern->file_name_len); break; case SPL_FS_DIR: spl_filesystem_dir_open(intern, source->_path TSRMLS_CC); /* read until we hit the position in which we were before */ skip_dots = SPL_HAS_FLAG(source->flags, SPL_FILE_DIR_SKIPDOTS); for(index = 0; index < source->u.dir.index; ++index) { do { spl_filesystem_dir_read(intern TSRMLS_CC); } while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name)); } intern->u.dir.index = index; break; case SPL_FS_FILE: php_error_docref(NULL TSRMLS_CC, E_ERROR, "An object of class %s cannot be cloned", old_object->ce->name); break; } intern->file_class = source->file_class; intern->info_class = source->info_class; intern->oth = source->oth; intern->oth_handler = source->oth_handler; zend_objects_clone_members(new_object, new_obj_val, old_object, handle TSRMLS_CC); if (intern->oth_handler && intern->oth_handler->clone) { intern->oth_handler->clone(source, intern TSRMLS_CC); } return new_obj_val; } /* }}} */ void spl_filesystem_info_set_filename(spl_filesystem_object *intern, char *path, int len, int use_copy TSRMLS_DC) /* {{{ */ { char *p1, *p2; intern->file_name = use_copy ? estrndup(path, len) : path; intern->file_name_len = len; while(IS_SLASH_AT(intern->file_name, intern->file_name_len-1) && intern->file_name_len > 1) { intern->file_name[intern->file_name_len-1] = 0; intern->file_name_len--; } p1 = strrchr(intern->file_name, '/'); #if defined(PHP_WIN32) || defined(NETWARE) p2 = strrchr(intern->file_name, '\\'); #else p2 = 0; #endif if (p1 || p2) { intern->_path_len = (p1 > p2 ? p1 : p2) - intern->file_name; } else { intern->_path_len = 0; } intern->_path = estrndup(path, intern->_path_len); } /* }}} */ static spl_filesystem_object * spl_filesystem_object_create_info(spl_filesystem_object *source, char *file_path, int file_path_len, int use_copy, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern; zval *arg1; zend_error_handling error_handling; if (!file_path || !file_path_len) { #if defined(PHP_WIN32) zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot create SplFileInfo for empty path"); if (file_path && !use_copy) { efree(file_path); } #else if (file_path && !use_copy) { efree(file_path); } use_copy = 1; file_path_len = 1; file_path = "/"; #endif return NULL; } zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); ce = ce ? ce : source->info_class; zend_update_class_constants(ce TSRMLS_CC); return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); Z_TYPE_P(return_value) = IS_OBJECT; if (ce->constructor->common.scope != spl_ce_SplFileInfo) { MAKE_STD_ZVAL(arg1); ZVAL_STRINGL(arg1, file_path, file_path_len, use_copy); zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1); zval_ptr_dtor(&arg1); } else { spl_filesystem_info_set_filename(intern, file_path, file_path_len, use_copy TSRMLS_CC); } zend_restore_error_handling(&error_handling TSRMLS_CC); return intern; } /* }}} */ static spl_filesystem_object * spl_filesystem_object_create_type(int ht, spl_filesystem_object *source, int type, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern; zend_bool use_include_path = 0; zval *arg1, *arg2; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); switch (source->type) { case SPL_FS_INFO: case SPL_FS_FILE: break; case SPL_FS_DIR: if (!source->u.dir.entry.d_name[0]) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Could not open file"); zend_restore_error_handling(&error_handling TSRMLS_CC); return NULL; } } switch (type) { case SPL_FS_INFO: ce = ce ? ce : source->info_class; zend_update_class_constants(ce TSRMLS_CC); return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); Z_TYPE_P(return_value) = IS_OBJECT; spl_filesystem_object_get_file_name(source TSRMLS_CC); if (ce->constructor->common.scope != spl_ce_SplFileInfo) { MAKE_STD_ZVAL(arg1); ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1); zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1); zval_ptr_dtor(&arg1); } else { intern->file_name = estrndup(source->file_name, source->file_name_len); intern->file_name_len = source->file_name_len; intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC); intern->_path = estrndup(intern->_path, intern->_path_len); } break; case SPL_FS_FILE: ce = ce ? ce : source->file_class; zend_update_class_constants(ce TSRMLS_CC); return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); Z_TYPE_P(return_value) = IS_OBJECT; spl_filesystem_object_get_file_name(source TSRMLS_CC); if (ce->constructor->common.scope != spl_ce_SplFileObject) { MAKE_STD_ZVAL(arg1); MAKE_STD_ZVAL(arg2); ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1); ZVAL_STRINGL(arg2, "r", 1, 1); zend_call_method_with_2_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1, arg2); zval_ptr_dtor(&arg1); zval_ptr_dtor(&arg2); } else { intern->file_name = source->file_name; intern->file_name_len = source->file_name_len; intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC); intern->_path = estrndup(intern->_path, intern->_path_len); intern->u.file.open_mode = "r"; intern->u.file.open_mode_len = 1; if (ht && zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sbr", &intern->u.file.open_mode, &intern->u.file.open_mode_len, &use_include_path, &intern->u.file.zcontext) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); intern->u.file.open_mode = NULL; intern->file_name = NULL; zval_dtor(return_value); Z_TYPE_P(return_value) = IS_NULL; return NULL; } if (spl_filesystem_file_open(intern, use_include_path, 0 TSRMLS_CC) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); zval_dtor(return_value); Z_TYPE_P(return_value) = IS_NULL; return NULL; } } break; case SPL_FS_DIR: zend_restore_error_handling(&error_handling TSRMLS_CC); zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Operation not supported"); return NULL; } zend_restore_error_handling(&error_handling TSRMLS_CC); return NULL; } /* }}} */ static int spl_filesystem_is_invalid_or_dot(const char * d_name) /* {{{ */ { return d_name[0] == '\0' || spl_filesystem_is_dot(d_name); } /* }}} */ static char *spl_filesystem_object_get_pathname(spl_filesystem_object *intern, int *len TSRMLS_DC) { /* {{{ */ switch (intern->type) { case SPL_FS_INFO: case SPL_FS_FILE: *len = intern->file_name_len; return intern->file_name; case SPL_FS_DIR: if (intern->u.dir.entry.d_name[0]) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); *len = intern->file_name_len; return intern->file_name; } } *len = 0; return NULL; } /* }}} */ static HashTable* spl_filesystem_object_get_debug_info(zval *obj, int *is_temp TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(obj TSRMLS_CC); HashTable *rv; zval *tmp, zrv; char *pnstr, *path; int pnlen, path_len; char stmp[2]; *is_temp = 1; if (!intern->std.properties) { rebuild_object_properties(&intern->std); } ALLOC_HASHTABLE(rv); ZEND_INIT_SYMTABLE_EX(rv, zend_hash_num_elements(intern->std.properties) + 3, 0); INIT_PZVAL(&zrv); Z_ARRVAL(zrv) = rv; zend_hash_copy(rv, intern->std.properties, (copy_ctor_func_t) zval_add_ref, (void *) &tmp, sizeof(zval *)); pnstr = spl_gen_private_prop_name(spl_ce_SplFileInfo, "pathName", sizeof("pathName")-1, &pnlen TSRMLS_CC); path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC); add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, path, path_len, 1); efree(pnstr); if (intern->file_name) { pnstr = spl_gen_private_prop_name(spl_ce_SplFileInfo, "fileName", sizeof("fileName")-1, &pnlen TSRMLS_CC); spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); if (path_len && path_len < intern->file_name_len) { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->file_name + path_len + 1, intern->file_name_len - (path_len + 1), 1); } else { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->file_name, intern->file_name_len, 1); } efree(pnstr); } if (intern->type == SPL_FS_DIR) { #ifdef HAVE_GLOB pnstr = spl_gen_private_prop_name(spl_ce_DirectoryIterator, "glob", sizeof("glob")-1, &pnlen TSRMLS_CC); if (php_stream_is(intern->u.dir.dirp ,&php_glob_stream_ops)) { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->_path, intern->_path_len, 1); } else { add_assoc_bool_ex(&zrv, pnstr, pnlen+1, 0); } efree(pnstr); #endif pnstr = spl_gen_private_prop_name(spl_ce_RecursiveDirectoryIterator, "subPathName", sizeof("subPathName")-1, &pnlen TSRMLS_CC); if (intern->u.dir.sub_path) { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->u.dir.sub_path, intern->u.dir.sub_path_len, 1); } else { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, "", 0, 1); } efree(pnstr); } if (intern->type == SPL_FS_FILE) { pnstr = spl_gen_private_prop_name(spl_ce_SplFileObject, "openMode", sizeof("openMode")-1, &pnlen TSRMLS_CC); add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->u.file.open_mode, intern->u.file.open_mode_len, 1); efree(pnstr); stmp[1] = '\0'; stmp[0] = intern->u.file.delimiter; pnstr = spl_gen_private_prop_name(spl_ce_SplFileObject, "delimiter", sizeof("delimiter")-1, &pnlen TSRMLS_CC); add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, stmp, 1, 1); efree(pnstr); stmp[0] = intern->u.file.enclosure; pnstr = spl_gen_private_prop_name(spl_ce_SplFileObject, "enclosure", sizeof("enclosure")-1, &pnlen TSRMLS_CC); add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, stmp, 1, 1); efree(pnstr); } return rv; } /* }}} */ zend_function *spl_filesystem_object_get_method_check(zval **object_ptr, char *method, int method_len, const struct _zend_literal *key TSRMLS_DC) /* {{{ */ { spl_filesystem_object *fsobj = zend_object_store_get_object(*object_ptr TSRMLS_CC); if (fsobj->u.dir.entry.d_name[0] == '\0' && fsobj->orig_path == NULL) { method = "_bad_state_ex"; method_len = sizeof("_bad_state_ex") - 1; key = NULL; } return zend_get_std_object_handlers()->get_method(object_ptr, method, method_len, key TSRMLS_CC); } /* }}} */ #define DIT_CTOR_FLAGS 0x00000001 #define DIT_CTOR_GLOB 0x00000002 void spl_filesystem_object_construct(INTERNAL_FUNCTION_PARAMETERS, long ctor_flags) /* {{{ */ { spl_filesystem_object *intern; char *path; int parsed, len; long flags; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (SPL_HAS_FLAG(ctor_flags, DIT_CTOR_FLAGS)) { flags = SPL_FILE_DIR_KEY_AS_PATHNAME|SPL_FILE_DIR_CURRENT_AS_FILEINFO; parsed = zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &path, &len, &flags); } else { flags = SPL_FILE_DIR_KEY_AS_PATHNAME|SPL_FILE_DIR_CURRENT_AS_SELF; parsed = zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &path, &len); } if (SPL_HAS_FLAG(ctor_flags, SPL_FILE_DIR_SKIPDOTS)) { flags |= SPL_FILE_DIR_SKIPDOTS; } if (SPL_HAS_FLAG(ctor_flags, SPL_FILE_DIR_UNIXPATHS)) { flags |= SPL_FILE_DIR_UNIXPATHS; } if (parsed == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (!len) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Directory name must not be empty."); zend_restore_error_handling(&error_handling TSRMLS_CC); return; } intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); intern->flags = flags; #ifdef HAVE_GLOB if (SPL_HAS_FLAG(ctor_flags, DIT_CTOR_GLOB) && strstr(path, "glob://") != path) { spprintf(&path, 0, "glob://%s", path); spl_filesystem_dir_open(intern, path TSRMLS_CC); efree(path); } else #endif { spl_filesystem_dir_open(intern, path TSRMLS_CC); } intern->u.dir.is_recursive = instanceof_function(intern->std.ce, spl_ce_RecursiveDirectoryIterator TSRMLS_CC) ? 1 : 0; zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void DirectoryIterator::__construct(string path) Cronstructs a new dir iterator from a path. */ SPL_METHOD(DirectoryIterator, __construct) { spl_filesystem_object_construct(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto void DirectoryIterator::rewind() Rewind dir back to the start */ SPL_METHOD(DirectoryIterator, rewind) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } intern->u.dir.index = 0; if (intern->u.dir.dirp) { php_stream_rewinddir(intern->u.dir.dirp); } spl_filesystem_dir_read(intern TSRMLS_CC); } /* }}} */ /* {{{ proto string DirectoryIterator::key() Return current dir entry */ SPL_METHOD(DirectoryIterator, key) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.dirp) { RETURN_LONG(intern->u.dir.index); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto DirectoryIterator DirectoryIterator::current() Return this (needed for Iterator interface) */ SPL_METHOD(DirectoryIterator, current) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_ZVAL(getThis(), 1, 0); } /* }}} */ /* {{{ proto void DirectoryIterator::next() Move to next entry */ SPL_METHOD(DirectoryIterator, next) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); int skip_dots = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_SKIPDOTS); if (zend_parse_parameters_none() == FAILURE) { return; } intern->u.dir.index++; do { spl_filesystem_dir_read(intern TSRMLS_CC); } while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name)); if (intern->file_name) { efree(intern->file_name); intern->file_name = NULL; } } /* }}} */ /* {{{ proto void DirectoryIterator::seek(int position) Seek to the given position */ SPL_METHOD(DirectoryIterator, seek) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zval *retval = NULL; long pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &pos) == FAILURE) { return; } if (intern->u.dir.index > pos) { /* we first rewind */ zend_call_method_with_0_params(&this_ptr, Z_OBJCE_P(getThis()), &intern->u.dir.func_rewind, "rewind", &retval); if (retval) { zval_ptr_dtor(&retval); } } while (intern->u.dir.index < pos) { int valid = 0; zend_call_method_with_0_params(&this_ptr, Z_OBJCE_P(getThis()), &intern->u.dir.func_valid, "valid", &retval); if (retval) { valid = zend_is_true(retval); zval_ptr_dtor(&retval); } if (!valid) { break; } zend_call_method_with_0_params(&this_ptr, Z_OBJCE_P(getThis()), &intern->u.dir.func_next, "next", &retval); if (retval) { zval_ptr_dtor(&retval); } } } /* }}} */ /* {{{ proto string DirectoryIterator::valid() Check whether dir contains more entries */ SPL_METHOD(DirectoryIterator, valid) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(intern->u.dir.entry.d_name[0] != '\0'); } /* }}} */ /* {{{ proto string SplFileInfo::getPath() Return the path */ SPL_METHOD(SplFileInfo, getPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *path; int path_len; if (zend_parse_parameters_none() == FAILURE) { return; } path = spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); RETURN_STRINGL(path, path_len, 1); } /* }}} */ /* {{{ proto string SplFileInfo::getFilename() Return filename only */ SPL_METHOD(SplFileInfo, getFilename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); int path_len; if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); if (path_len && path_len < intern->file_name_len) { RETURN_STRINGL(intern->file_name + path_len + 1, intern->file_name_len - (path_len + 1), 1); } else { RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } } /* }}} */ /* {{{ proto string DirectoryIterator::getFilename() Return filename of current dir entry */ SPL_METHOD(DirectoryIterator, getFilename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_STRING(intern->u.dir.entry.d_name, 1); } /* }}} */ /* {{{ proto string SplFileInfo::getExtension() Returns file extension component of path */ SPL_METHOD(SplFileInfo, getExtension) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *fname = NULL; const char *p; size_t flen; int path_len, idx; if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); if (path_len && path_len < intern->file_name_len) { fname = intern->file_name + path_len + 1; flen = intern->file_name_len - (path_len + 1); } else { fname = intern->file_name; flen = intern->file_name_len; } php_basename(fname, flen, NULL, 0, &fname, &flen TSRMLS_CC); p = zend_memrchr(fname, '.', flen); if (p) { idx = p - fname; RETVAL_STRINGL(fname + idx + 1, flen - idx - 1, 1); efree(fname); return; } else { if (fname) { efree(fname); } RETURN_EMPTY_STRING(); } } /* }}}*/ /* {{{ proto string DirectoryIterator::getExtension() Returns the file extension component of path */ SPL_METHOD(DirectoryIterator, getExtension) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *fname = NULL; const char *p; size_t flen; int idx; if (zend_parse_parameters_none() == FAILURE) { return; } php_basename(intern->u.dir.entry.d_name, strlen(intern->u.dir.entry.d_name), NULL, 0, &fname, &flen TSRMLS_CC); p = zend_memrchr(fname, '.', flen); if (p) { idx = p - fname; RETVAL_STRINGL(fname + idx + 1, flen - idx - 1, 1); efree(fname); return; } else { if (fname) { efree(fname); } RETURN_EMPTY_STRING(); } } /* }}} */ /* {{{ proto string SplFileInfo::getBasename([string $suffix]) U Returns filename component of path */ SPL_METHOD(SplFileInfo, getBasename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *fname, *suffix = 0; size_t flen; int slen = 0, path_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &suffix, &slen) == FAILURE) { return; } spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); if (path_len && path_len < intern->file_name_len) { fname = intern->file_name + path_len + 1; flen = intern->file_name_len - (path_len + 1); } else { fname = intern->file_name; flen = intern->file_name_len; } php_basename(fname, flen, suffix, slen, &fname, &flen TSRMLS_CC); RETURN_STRINGL(fname, flen, 0); } /* }}}*/ /* {{{ proto string DirectoryIterator::getBasename([string $suffix]) U Returns filename component of current dir entry */ SPL_METHOD(DirectoryIterator, getBasename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *suffix = 0, *fname; int slen = 0; size_t flen; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &suffix, &slen) == FAILURE) { return; } php_basename(intern->u.dir.entry.d_name, strlen(intern->u.dir.entry.d_name), suffix, slen, &fname, &flen TSRMLS_CC); RETURN_STRINGL(fname, flen, 0); } /* }}} */ /* {{{ proto string SplFileInfo::getPathname() Return path and filename */ SPL_METHOD(SplFileInfo, getPathname) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *path; int path_len; if (zend_parse_parameters_none() == FAILURE) { return; } path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC); if (path != NULL) { RETURN_STRINGL(path, path_len, 1); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto string FilesystemIterator::key() Return getPathname() or getFilename() depending on flags */ SPL_METHOD(FilesystemIterator, key) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (SPL_FILE_DIR_KEY(intern, SPL_FILE_DIR_KEY_AS_FILENAME)) { RETURN_STRING(intern->u.dir.entry.d_name, 1); } else { spl_filesystem_object_get_file_name(intern TSRMLS_CC); RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } } /* }}} */ /* {{{ proto string FilesystemIterator::current() Return getFilename(), getFileInfo() or $this depending on flags */ SPL_METHOD(FilesystemIterator, current) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_PATHNAME)) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } else if (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_FILEINFO)) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); spl_filesystem_object_create_type(0, intern, SPL_FS_INFO, NULL, return_value TSRMLS_CC); } else { RETURN_ZVAL(getThis(), 1, 0); /*RETURN_STRING(intern->u.dir.entry.d_name, 1);*/ } } /* }}} */ /* {{{ proto bool DirectoryIterator::isDot() Returns true if current entry is '.' or '..' */ SPL_METHOD(DirectoryIterator, isDot) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(spl_filesystem_is_dot(intern->u.dir.entry.d_name)); } /* }}} */ /* {{{ proto void SplFileInfo::__construct(string file_name) Cronstructs a new SplFileInfo from a path. */ /* zend_replace_error_handling() is used to throw exceptions in case the constructor fails. Here we use this to ensure the object has a valid directory resource. When the constructor gets called the object is already created by the engine, so we must only call 'additional' initializations. */ SPL_METHOD(SplFileInfo, __construct) { spl_filesystem_object *intern; char *path; int len; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &path, &len) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_filesystem_info_set_filename(intern, path, len, 1 TSRMLS_CC); zend_restore_error_handling(&error_handling TSRMLS_CC); /* intern->type = SPL_FS_INFO; already set */ } /* }}} */ /* {{{ FileInfoFunction */ #define FileInfoFunction(func_name, func_num) \ SPL_METHOD(SplFileInfo, func_name) \ { \ spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); \ zend_error_handling error_handling; \ if (zend_parse_parameters_none() == FAILURE) { \ return; \ } \ \ zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);\ spl_filesystem_object_get_file_name(intern TSRMLS_CC); \ php_stat(intern->file_name, intern->file_name_len, func_num, return_value TSRMLS_CC); \ zend_restore_error_handling(&error_handling TSRMLS_CC); \ } /* }}} */ /* {{{ proto int SplFileInfo::getPerms() Get file permissions */ FileInfoFunction(getPerms, FS_PERMS) /* }}} */ /* {{{ proto int SplFileInfo::getInode() Get file inode */ FileInfoFunction(getInode, FS_INODE) /* }}} */ /* {{{ proto int SplFileInfo::getSize() Get file size */ FileInfoFunction(getSize, FS_SIZE) /* }}} */ /* {{{ proto int SplFileInfo::getOwner() Get file owner */ FileInfoFunction(getOwner, FS_OWNER) /* }}} */ /* {{{ proto int SplFileInfo::getGroup() Get file group */ FileInfoFunction(getGroup, FS_GROUP) /* }}} */ /* {{{ proto int SplFileInfo::getATime() Get last access time of file */ FileInfoFunction(getATime, FS_ATIME) /* }}} */ /* {{{ proto int SplFileInfo::getMTime() Get last modification time of file */ FileInfoFunction(getMTime, FS_MTIME) /* }}} */ /* {{{ proto int SplFileInfo::getCTime() Get inode modification time of file */ FileInfoFunction(getCTime, FS_CTIME) /* }}} */ /* {{{ proto string SplFileInfo::getType() Get file type */ FileInfoFunction(getType, FS_TYPE) /* }}} */ /* {{{ proto bool SplFileInfo::isWritable() Returns true if file can be written */ FileInfoFunction(isWritable, FS_IS_W) /* }}} */ /* {{{ proto bool SplFileInfo::isReadable() Returns true if file can be read */ FileInfoFunction(isReadable, FS_IS_R) /* }}} */ /* {{{ proto bool SplFileInfo::isExecutable() Returns true if file is executable */ FileInfoFunction(isExecutable, FS_IS_X) /* }}} */ /* {{{ proto bool SplFileInfo::isFile() Returns true if file is a regular file */ FileInfoFunction(isFile, FS_IS_FILE) /* }}} */ /* {{{ proto bool SplFileInfo::isDir() Returns true if file is directory */ FileInfoFunction(isDir, FS_IS_DIR) /* }}} */ /* {{{ proto bool SplFileInfo::isLink() Returns true if file is symbolic link */ FileInfoFunction(isLink, FS_IS_LINK) /* }}} */ /* {{{ proto string SplFileInfo::getLinkTarget() U Return the target of a symbolic link */ SPL_METHOD(SplFileInfo, getLinkTarget) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); int ret; char buff[MAXPATHLEN]; zend_error_handling error_handling; if (zend_parse_parameters_none() == FAILURE) { return; } zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); #if defined(PHP_WIN32) || HAVE_SYMLINK if (intern->file_name == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty filename"); RETURN_FALSE; } else if (!IS_ABSOLUTE_PATH(intern->file_name, intern->file_name_len)) { char expanded_path[MAXPATHLEN]; if (!expand_filepath_with_mode(intern->file_name, expanded_path, NULL, 0, CWD_EXPAND TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "No such file or directory"); RETURN_FALSE; } ret = php_sys_readlink(expanded_path, buff, MAXPATHLEN - 1); } else { ret = php_sys_readlink(intern->file_name, buff, MAXPATHLEN-1); } #else ret = -1; /* always fail if not implemented */ #endif if (ret == -1) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Unable to read link %s, error: %s", intern->file_name, strerror(errno)); RETVAL_FALSE; } else { /* Append NULL to the end of the string */ buff[ret] = '\0'; RETVAL_STRINGL(buff, ret, 1); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ #if (!defined(__BEOS__) && !defined(NETWARE) && HAVE_REALPATH) || defined(ZTS) /* {{{ proto string SplFileInfo::getRealPath() Return the resolved path */ SPL_METHOD(SplFileInfo, getRealPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char buff[MAXPATHLEN]; char *filename; zend_error_handling error_handling; if (zend_parse_parameters_none() == FAILURE) { return; } zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); if (intern->type == SPL_FS_DIR && !intern->file_name && intern->u.dir.entry.d_name[0]) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); } if (intern->orig_path) { filename = intern->orig_path; } else { filename = intern->file_name; } if (filename && VCWD_REALPATH(filename, buff)) { #ifdef ZTS if (VCWD_ACCESS(buff, F_OK)) { RETVAL_FALSE; } else #endif RETVAL_STRING(buff, 1); } else { RETVAL_FALSE; } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ #endif /* {{{ proto SplFileObject SplFileInfo::openFile([string mode = 'r' [, bool use_include_path [, resource context]]]) Open the current file */ SPL_METHOD(SplFileInfo, openFile) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_filesystem_object_create_type(ht, intern, SPL_FS_FILE, NULL, return_value TSRMLS_CC); } /* }}} */ /* {{{ proto void SplFileInfo::setFileClass([string class_name]) Class to use in openFile() */ SPL_METHOD(SplFileInfo, setFileClass) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = spl_ce_SplFileObject; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { intern->file_class = ce; } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void SplFileInfo::setInfoClass([string class_name]) Class to use in getFileInfo(), getPathInfo() */ SPL_METHOD(SplFileInfo, setInfoClass) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = spl_ce_SplFileInfo; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { intern->info_class = ce; } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto SplFileInfo SplFileInfo::getFileInfo([string $class_name]) Get/copy file info */ SPL_METHOD(SplFileInfo, getFileInfo) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = intern->info_class; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { spl_filesystem_object_create_type(ht, intern, SPL_FS_INFO, ce, return_value TSRMLS_CC); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto SplFileInfo SplFileInfo::getPathInfo([string $class_name]) Get/copy file info */ SPL_METHOD(SplFileInfo, getPathInfo) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = intern->info_class; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { int path_len; char *path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC); if (path) { char *dpath = estrndup(path, path_len); path_len = php_dirname(dpath, path_len); spl_filesystem_object_create_info(intern, dpath, path_len, 1, ce, return_value TSRMLS_CC); efree(dpath); } } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ */ SPL_METHOD(SplFileInfo, _bad_state_ex) { zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "The parent constructor was not called: the object is in an " "invalid state "); } /* }}} */ /* {{{ proto void FilesystemIterator::__construct(string path [, int flags]) Cronstructs a new dir iterator from a path. */ SPL_METHOD(FilesystemIterator, __construct) { spl_filesystem_object_construct(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIT_CTOR_FLAGS | SPL_FILE_DIR_SKIPDOTS); } /* }}} */ /* {{{ proto void FilesystemIterator::rewind() Rewind dir back to the start */ SPL_METHOD(FilesystemIterator, rewind) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } intern->u.dir.index = 0; if (intern->u.dir.dirp) { php_stream_rewinddir(intern->u.dir.dirp); } do { spl_filesystem_dir_read(intern TSRMLS_CC); } while (spl_filesystem_is_dot(intern->u.dir.entry.d_name)); } /* }}} */ /* {{{ proto int FilesystemIterator::getFlags() Get handling flags */ SPL_METHOD(FilesystemIterator, getFlags) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(intern->flags & (SPL_FILE_DIR_KEY_MODE_MASK | SPL_FILE_DIR_CURRENT_MODE_MASK | SPL_FILE_DIR_OTHERS_MASK)); } /* }}} */ /* {{{ proto void FilesystemIterator::setFlags(long $flags) Set handling flags */ SPL_METHOD(FilesystemIterator, setFlags) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long flags; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &flags) == FAILURE) { return; } intern->flags &= ~(SPL_FILE_DIR_KEY_MODE_MASK|SPL_FILE_DIR_CURRENT_MODE_MASK|SPL_FILE_DIR_OTHERS_MASK); intern->flags |= ((SPL_FILE_DIR_KEY_MODE_MASK|SPL_FILE_DIR_CURRENT_MODE_MASK|SPL_FILE_DIR_OTHERS_MASK) & flags); } /* }}} */ /* {{{ proto bool RecursiveDirectoryIterator::hasChildren([bool $allow_links = false]) Returns whether current entry is a directory and not '.' or '..' */ SPL_METHOD(RecursiveDirectoryIterator, hasChildren) { zend_bool allow_links = 0; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &allow_links) == FAILURE) { return; } if (spl_filesystem_is_invalid_or_dot(intern->u.dir.entry.d_name)) { RETURN_FALSE; } else { spl_filesystem_object_get_file_name(intern TSRMLS_CC); if (!allow_links && !(intern->flags & SPL_FILE_DIR_FOLLOW_SYMLINKS)) { php_stat(intern->file_name, intern->file_name_len, FS_IS_LINK, return_value TSRMLS_CC); if (zend_is_true(return_value)) { RETURN_FALSE; } } php_stat(intern->file_name, intern->file_name_len, FS_IS_DIR, return_value TSRMLS_CC); } } /* }}} */ /* {{{ proto RecursiveDirectoryIterator DirectoryIterator::getChildren() Returns an iterator for the current entry if it is a directory */ SPL_METHOD(RecursiveDirectoryIterator, getChildren) { zval zpath, zflags; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_filesystem_object *subdir; char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH; if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_object_get_file_name(intern TSRMLS_CC); if (SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_CURRENT_AS_PATHNAME)) { RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } else { INIT_PZVAL(&zflags); INIT_PZVAL(&zpath); ZVAL_LONG(&zflags, intern->flags); ZVAL_STRINGL(&zpath, intern->file_name, intern->file_name_len, 0); spl_instantiate_arg_ex2(Z_OBJCE_P(getThis()), &return_value, 0, &zpath, &zflags TSRMLS_CC); subdir = (spl_filesystem_object*)zend_object_store_get_object(return_value TSRMLS_CC); if (subdir) { if (intern->u.dir.sub_path && intern->u.dir.sub_path[0]) { subdir->u.dir.sub_path_len = spprintf(&subdir->u.dir.sub_path, 0, "%s%c%s", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name); } else { subdir->u.dir.sub_path_len = strlen(intern->u.dir.entry.d_name); subdir->u.dir.sub_path = estrndup(intern->u.dir.entry.d_name, subdir->u.dir.sub_path_len); } subdir->info_class = intern->info_class; subdir->file_class = intern->file_class; subdir->oth = intern->oth; } } } /* }}} */ /* {{{ proto void RecursiveDirectoryIterator::getSubPath() Get sub path */ SPL_METHOD(RecursiveDirectoryIterator, getSubPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.sub_path) { RETURN_STRINGL(intern->u.dir.sub_path, intern->u.dir.sub_path_len, 1); } else { RETURN_STRINGL("", 0, 1); } } /* }}} */ /* {{{ proto void RecursiveDirectoryIterator::getSubPathname() Get sub path and file name */ SPL_METHOD(RecursiveDirectoryIterator, getSubPathname) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *sub_name; int len; char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH; if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.sub_path) { len = spprintf(&sub_name, 0, "%s%c%s", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name); RETURN_STRINGL(sub_name, len, 0); } else { RETURN_STRING(intern->u.dir.entry.d_name, 1); } } /* }}} */ /* {{{ proto int RecursiveDirectoryIterator::__construct(string path [, int flags]) Cronstructs a new dir iterator from a path. */ SPL_METHOD(RecursiveDirectoryIterator, __construct) { spl_filesystem_object_construct(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIT_CTOR_FLAGS); } /* }}} */ #ifdef HAVE_GLOB /* {{{ proto int GlobIterator::__construct(string path [, int flags]) Cronstructs a new dir iterator from a glob expression (no glob:// needed). */ SPL_METHOD(GlobIterator, __construct) { spl_filesystem_object_construct(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIT_CTOR_FLAGS|DIT_CTOR_GLOB); } /* }}} */ /* {{{ proto int GlobIterator::cont() Return the number of directories and files found by globbing */ SPL_METHOD(GlobIterator, count) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (php_stream_is(intern->u.dir.dirp ,&php_glob_stream_ops)) { RETURN_LONG(php_glob_stream_get_count(intern->u.dir.dirp, NULL)); } else { /* should not happen */ php_error_docref(NULL TSRMLS_CC, E_ERROR, "GlobIterator lost glob state"); } } /* }}} */ #endif /* HAVE_GLOB */ /* {{{ forward declarations to the iterator handlers */ static void spl_filesystem_dir_it_dtor(zend_object_iterator *iter TSRMLS_DC); static int spl_filesystem_dir_it_valid(zend_object_iterator *iter TSRMLS_DC); static void spl_filesystem_dir_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC); static int spl_filesystem_dir_it_current_key(zend_object_iterator *iter, char **str_key, uint *str_key_len, ulong *int_key TSRMLS_DC); static void spl_filesystem_dir_it_move_forward(zend_object_iterator *iter TSRMLS_DC); static void spl_filesystem_dir_it_rewind(zend_object_iterator *iter TSRMLS_DC); /* iterator handler table */ zend_object_iterator_funcs spl_filesystem_dir_it_funcs = { spl_filesystem_dir_it_dtor, spl_filesystem_dir_it_valid, spl_filesystem_dir_it_current_data, spl_filesystem_dir_it_current_key, spl_filesystem_dir_it_move_forward, spl_filesystem_dir_it_rewind }; /* }}} */ /* {{{ spl_ce_dir_get_iterator */ zend_object_iterator *spl_filesystem_dir_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) { spl_filesystem_iterator *iterator; spl_filesystem_object *dir_object; if (by_ref) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } dir_object = (spl_filesystem_object*)zend_object_store_get_object(object TSRMLS_CC); iterator = spl_filesystem_object_to_iterator(dir_object); Z_SET_REFCOUNT_P(object, Z_REFCOUNT_P(object) + 2); iterator->intern.data = (void*)object; iterator->intern.funcs = &spl_filesystem_dir_it_funcs; iterator->current = object; return (zend_object_iterator*)iterator; } /* }}} */ /* {{{ spl_filesystem_dir_it_dtor */ static void spl_filesystem_dir_it_dtor(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; zval *zfree = (zval*)iterator->intern.data; iterator->intern.data = NULL; /* mark as unused */ zval_ptr_dtor(&iterator->current); if (zfree) { zval_ptr_dtor(&zfree); } } /* }}} */ /* {{{ spl_filesystem_dir_it_valid */ static int spl_filesystem_dir_it_valid(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); return object->u.dir.entry.d_name[0] != '\0' ? SUCCESS : FAILURE; } /* }}} */ /* {{{ spl_filesystem_dir_it_current_data */ static void spl_filesystem_dir_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; *data = &iterator->current; } /* }}} */ /* {{{ spl_filesystem_dir_it_current_key */ static int spl_filesystem_dir_it_current_key(zend_object_iterator *iter, char **str_key, uint *str_key_len, ulong *int_key TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); *int_key = object->u.dir.index; return HASH_KEY_IS_LONG; } /* }}} */ /* {{{ spl_filesystem_dir_it_move_forward */ static void spl_filesystem_dir_it_move_forward(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); object->u.dir.index++; spl_filesystem_dir_read(object TSRMLS_CC); if (object->file_name) { efree(object->file_name); object->file_name = NULL; } } /* }}} */ /* {{{ spl_filesystem_dir_it_rewind */ static void spl_filesystem_dir_it_rewind(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); object->u.dir.index = 0; if (object->u.dir.dirp) { php_stream_rewinddir(object->u.dir.dirp); } spl_filesystem_dir_read(object TSRMLS_CC); } /* }}} */ /* {{{ spl_filesystem_tree_it_dtor */ static void spl_filesystem_tree_it_dtor(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; zval *zfree = (zval*)iterator->intern.data; if (iterator->current) { zval_ptr_dtor(&iterator->current); } iterator->intern.data = NULL; /* mark as unused */ /* free twice as we add ref twice */ zval_ptr_dtor(&zfree); zval_ptr_dtor(&zfree); } /* }}} */ /* {{{ spl_filesystem_tree_it_current_data */ static void spl_filesystem_tree_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator); if (SPL_FILE_DIR_CURRENT(object, SPL_FILE_DIR_CURRENT_AS_PATHNAME)) { if (!iterator->current) { ALLOC_INIT_ZVAL(iterator->current); spl_filesystem_object_get_file_name(object TSRMLS_CC); ZVAL_STRINGL(iterator->current, object->file_name, object->file_name_len, 1); } *data = &iterator->current; } else if (SPL_FILE_DIR_CURRENT(object, SPL_FILE_DIR_CURRENT_AS_FILEINFO)) { if (!iterator->current) { ALLOC_INIT_ZVAL(iterator->current); spl_filesystem_object_get_file_name(object TSRMLS_CC); spl_filesystem_object_create_type(0, object, SPL_FS_INFO, NULL, iterator->current TSRMLS_CC); } *data = &iterator->current; } else { *data = (zval**)&iterator->intern.data; } } /* }}} */ /* {{{ spl_filesystem_tree_it_current_key */ static int spl_filesystem_tree_it_current_key(zend_object_iterator *iter, char **str_key, uint *str_key_len, ulong *int_key TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); if (SPL_FILE_DIR_KEY(object, SPL_FILE_DIR_KEY_AS_FILENAME)) { *str_key_len = strlen(object->u.dir.entry.d_name) + 1; *str_key = estrndup(object->u.dir.entry.d_name, *str_key_len - 1); } else { spl_filesystem_object_get_file_name(object TSRMLS_CC); *str_key_len = object->file_name_len + 1; *str_key = estrndup(object->file_name, object->file_name_len); } return HASH_KEY_IS_STRING; } /* }}} */ /* {{{ spl_filesystem_tree_it_move_forward */ static void spl_filesystem_tree_it_move_forward(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator); object->u.dir.index++; do { spl_filesystem_dir_read(object TSRMLS_CC); } while (spl_filesystem_is_dot(object->u.dir.entry.d_name)); if (object->file_name) { efree(object->file_name); object->file_name = NULL; } if (iterator->current) { zval_ptr_dtor(&iterator->current); iterator->current = NULL; } } /* }}} */ /* {{{ spl_filesystem_tree_it_rewind */ static void spl_filesystem_tree_it_rewind(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator); object->u.dir.index = 0; if (object->u.dir.dirp) { php_stream_rewinddir(object->u.dir.dirp); } do { spl_filesystem_dir_read(object TSRMLS_CC); } while (spl_filesystem_is_dot(object->u.dir.entry.d_name)); if (iterator->current) { zval_ptr_dtor(&iterator->current); iterator->current = NULL; } } /* }}} */ /* {{{ iterator handler table */ zend_object_iterator_funcs spl_filesystem_tree_it_funcs = { spl_filesystem_tree_it_dtor, spl_filesystem_dir_it_valid, spl_filesystem_tree_it_current_data, spl_filesystem_tree_it_current_key, spl_filesystem_tree_it_move_forward, spl_filesystem_tree_it_rewind }; /* }}} */ /* {{{ spl_ce_dir_get_iterator */ zend_object_iterator *spl_filesystem_tree_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) { spl_filesystem_iterator *iterator; spl_filesystem_object *dir_object; if (by_ref) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } dir_object = (spl_filesystem_object*)zend_object_store_get_object(object TSRMLS_CC); iterator = spl_filesystem_object_to_iterator(dir_object); Z_SET_REFCOUNT_P(object, Z_REFCOUNT_P(object) + 2); iterator->intern.data = (void*)object; iterator->intern.funcs = &spl_filesystem_tree_it_funcs; iterator->current = NULL; return (zend_object_iterator*)iterator; } /* }}} */ /* {{{ spl_filesystem_object_cast */ static int spl_filesystem_object_cast(zval *readobj, zval *writeobj, int type TSRMLS_DC) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(readobj TSRMLS_CC); if (type == IS_STRING) { switch (intern->type) { case SPL_FS_INFO: case SPL_FS_FILE: if (readobj == writeobj) { zval retval; zval *retval_ptr = &retval; ZVAL_STRINGL(retval_ptr, intern->file_name, intern->file_name_len, 1); zval_dtor(readobj); ZVAL_ZVAL(writeobj, retval_ptr, 0, 0); } else { ZVAL_STRINGL(writeobj, intern->file_name, intern->file_name_len, 1); } return SUCCESS; case SPL_FS_DIR: if (readobj == writeobj) { zval retval; zval *retval_ptr = &retval; ZVAL_STRING(retval_ptr, intern->u.dir.entry.d_name, 1); zval_dtor(readobj); ZVAL_ZVAL(writeobj, retval_ptr, 0, 0); } else { ZVAL_STRING(writeobj, intern->u.dir.entry.d_name, 1); } return SUCCESS; } } if (readobj == writeobj) { zval_dtor(readobj); } ZVAL_NULL(writeobj); return FAILURE; } /* }}} */ /* {{{ declare method parameters */ /* supply a name and default to call by parameter */ ZEND_BEGIN_ARG_INFO(arginfo_info___construct, 0) ZEND_ARG_INFO(0, file_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_info_openFile, 0, 0, 0) ZEND_ARG_INFO(0, open_mode) ZEND_ARG_INFO(0, use_include_path) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_info_optinalFileClass, 0, 0, 0) ZEND_ARG_INFO(0, class_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_optinalSuffix, 0, 0, 0) ZEND_ARG_INFO(0, suffix) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_splfileinfo_void, 0) ZEND_END_ARG_INFO() /* the method table */ /* each method can have its own parameters and visibility */ static const zend_function_entry spl_SplFileInfo_functions[] = { SPL_ME(SplFileInfo, __construct, arginfo_info___construct, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getPath, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getFilename, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getExtension, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getBasename, arginfo_optinalSuffix, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getPathname, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getPerms, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getInode, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getSize, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getOwner, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getGroup, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getATime, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getMTime, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getCTime, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getType, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isWritable, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isReadable, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isExecutable, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isFile, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isDir, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isLink, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getLinkTarget, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) #if (!defined(__BEOS__) && !defined(NETWARE) && HAVE_REALPATH) || defined(ZTS) SPL_ME(SplFileInfo, getRealPath, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) #endif SPL_ME(SplFileInfo, getFileInfo, arginfo_info_optinalFileClass, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getPathInfo, arginfo_info_optinalFileClass, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, openFile, arginfo_info_openFile, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, setFileClass, arginfo_info_optinalFileClass, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, setInfoClass, arginfo_info_optinalFileClass, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, _bad_state_ex, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL) SPL_MA(SplFileInfo, __toString, SplFileInfo, getPathname, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) PHP_FE_END }; ZEND_BEGIN_ARG_INFO(arginfo_dir___construct, 0) ZEND_ARG_INFO(0, path) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_dir_it_seek, 0) ZEND_ARG_INFO(0, position) ZEND_END_ARG_INFO(); /* the method table */ /* each method can have its own parameters and visibility */ static const zend_function_entry spl_DirectoryIterator_functions[] = { SPL_ME(DirectoryIterator, __construct, arginfo_dir___construct, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, getFilename, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, getExtension, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, getBasename, arginfo_optinalSuffix, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, isDot, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, rewind, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, valid, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, key, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, current, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, next, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, seek, arginfo_dir_it_seek, ZEND_ACC_PUBLIC) SPL_MA(DirectoryIterator, __toString, DirectoryIterator, getFilename, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) PHP_FE_END }; ZEND_BEGIN_ARG_INFO_EX(arginfo_r_dir___construct, 0, 0, 1) ZEND_ARG_INFO(0, path) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_r_dir_hasChildren, 0, 0, 0) ZEND_ARG_INFO(0, allow_links) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_r_dir_setFlags, 0, 0, 0) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() static const zend_function_entry spl_FilesystemIterator_functions[] = { SPL_ME(FilesystemIterator, __construct, arginfo_r_dir___construct, ZEND_ACC_PUBLIC) SPL_ME(FilesystemIterator, rewind, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, next, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(FilesystemIterator, key, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(FilesystemIterator, current, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(FilesystemIterator, getFlags, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(FilesystemIterator, setFlags, arginfo_r_dir_setFlags, ZEND_ACC_PUBLIC) PHP_FE_END }; static const zend_function_entry spl_RecursiveDirectoryIterator_functions[] = { SPL_ME(RecursiveDirectoryIterator, __construct, arginfo_r_dir___construct, ZEND_ACC_PUBLIC) SPL_ME(RecursiveDirectoryIterator, hasChildren, arginfo_r_dir_hasChildren, ZEND_ACC_PUBLIC) SPL_ME(RecursiveDirectoryIterator, getChildren, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(RecursiveDirectoryIterator, getSubPath, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(RecursiveDirectoryIterator, getSubPathname,arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) PHP_FE_END }; #ifdef HAVE_GLOB static const zend_function_entry spl_GlobIterator_functions[] = { SPL_ME(GlobIterator, __construct, arginfo_r_dir___construct, ZEND_ACC_PUBLIC) SPL_ME(GlobIterator, count, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) PHP_FE_END }; #endif /* }}} */ static int spl_filesystem_file_read(spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */ { char *buf; size_t line_len = 0; long line_add = (intern->u.file.current_line || intern->u.file.current_zval) ? 1 : 0; spl_filesystem_file_free_line(intern TSRMLS_CC); if (php_stream_eof(intern->u.file.stream)) { if (!silent) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot read from file %s", intern->file_name); } return FAILURE; } if (intern->u.file.max_line_len > 0) { buf = safe_emalloc((intern->u.file.max_line_len + 1), sizeof(char), 0); if (php_stream_get_line(intern->u.file.stream, buf, intern->u.file.max_line_len, &line_len) == NULL) { efree(buf); buf = NULL; } else { buf[line_len] = '\0'; } } else { buf = php_stream_get_line(intern->u.file.stream, NULL, 0, &line_len); } if (!buf) { intern->u.file.current_line = estrdup(""); intern->u.file.current_line_len = 0; } else { if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_DROP_NEW_LINE)) { line_len = strcspn(buf, "\r\n"); buf[line_len] = '\0'; } intern->u.file.current_line = buf; intern->u.file.current_line_len = line_len; } intern->u.file.current_line_num += line_add; return SUCCESS; } /* }}} */ static int spl_filesystem_file_call(spl_filesystem_object *intern, zend_function *func_ptr, int pass_num_args, zval *return_value, zval *arg2 TSRMLS_DC) /* {{{ */ { zend_fcall_info fci; zend_fcall_info_cache fcic; zval z_fname; zval * zresource_ptr = &intern->u.file.zresource, *retval; int result; int num_args = pass_num_args + (arg2 ? 2 : 1); zval ***params = (zval***)safe_emalloc(num_args, sizeof(zval**), 0); params[0] = &zresource_ptr; if (arg2) { params[1] = &arg2; } zend_get_parameters_array_ex(pass_num_args, params+(arg2 ? 2 : 1)); ZVAL_STRING(&z_fname, func_ptr->common.function_name, 0); fci.size = sizeof(fci); fci.function_table = EG(function_table); fci.object_ptr = NULL; fci.function_name = &z_fname; fci.retval_ptr_ptr = &retval; fci.param_count = num_args; fci.params = params; fci.no_separation = 1; fci.symbol_table = NULL; fcic.initialized = 1; fcic.function_handler = func_ptr; fcic.calling_scope = NULL; fcic.called_scope = NULL; fcic.object_ptr = NULL; result = zend_call_function(&fci, &fcic TSRMLS_CC); if (result == FAILURE) { RETVAL_FALSE; } else { ZVAL_ZVAL(return_value, retval, 1, 1); } efree(params); return result; } /* }}} */ #define FileFunctionCall(func_name, pass_num_args, arg2) /* {{{ */ \ { \ zend_function *func_ptr; \ int ret; \ ret = zend_hash_find(EG(function_table), #func_name, sizeof(#func_name), (void **) &func_ptr); \ if (ret != SUCCESS) { \ zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Internal error, function '%s' not found. Please report", #func_name); \ return; \ } \ spl_filesystem_file_call(intern, func_ptr, pass_num_args, return_value, arg2 TSRMLS_CC); \ } /* }}} */ static int spl_filesystem_file_read_csv(spl_filesystem_object *intern, char delimiter, char enclosure, char escape, zval *return_value TSRMLS_DC) /* {{{ */ { int ret = SUCCESS; do { ret = spl_filesystem_file_read(intern, 1 TSRMLS_CC); } while (ret == SUCCESS && !intern->u.file.current_line_len && SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY)); if (ret == SUCCESS) { size_t buf_len = intern->u.file.current_line_len; char *buf = estrndup(intern->u.file.current_line, buf_len); if (intern->u.file.current_zval) { zval_ptr_dtor(&intern->u.file.current_zval); } ALLOC_INIT_ZVAL(intern->u.file.current_zval); php_fgetcsv(intern->u.file.stream, delimiter, enclosure, escape, buf_len, buf, intern->u.file.current_zval TSRMLS_CC); if (return_value) { if (Z_TYPE_P(return_value) != IS_NULL) { zval_dtor(return_value); ZVAL_NULL(return_value); } ZVAL_ZVAL(return_value, intern->u.file.current_zval, 1, 0); } } return ret; } /* }}} */ static int spl_filesystem_file_read_line_ex(zval * this_ptr, spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */ { zval *retval = NULL; /* 1) use fgetcsv? 2) overloaded call the function, 3) do it directly */ if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) || intern->u.file.func_getCurr->common.scope != spl_ce_SplFileObject) { if (php_stream_eof(intern->u.file.stream)) { if (!silent) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot read from file %s", intern->file_name); } return FAILURE; } if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV)) { return spl_filesystem_file_read_csv(intern, intern->u.file.delimiter, intern->u.file.enclosure, intern->u.file.escape, NULL TSRMLS_CC); } else { zend_call_method_with_0_params(&this_ptr, Z_OBJCE_P(getThis()), &intern->u.file.func_getCurr, "getCurrentLine", &retval); } if (retval) { if (intern->u.file.current_line || intern->u.file.current_zval) { intern->u.file.current_line_num++; } spl_filesystem_file_free_line(intern TSRMLS_CC); if (Z_TYPE_P(retval) == IS_STRING) { intern->u.file.current_line = estrndup(Z_STRVAL_P(retval), Z_STRLEN_P(retval)); intern->u.file.current_line_len = Z_STRLEN_P(retval); } else { MAKE_STD_ZVAL(intern->u.file.current_zval); ZVAL_ZVAL(intern->u.file.current_zval, retval, 1, 0); } zval_ptr_dtor(&retval); return SUCCESS; } else { return FAILURE; } } else { return spl_filesystem_file_read(intern, silent TSRMLS_CC); } } /* }}} */ static int spl_filesystem_file_is_empty_line(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { if (intern->u.file.current_line) { return intern->u.file.current_line_len == 0; } else if (intern->u.file.current_zval) { switch(Z_TYPE_P(intern->u.file.current_zval)) { case IS_STRING: return Z_STRLEN_P(intern->u.file.current_zval) == 0; case IS_ARRAY: if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) && zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 1) { zval ** first = Z_ARRVAL_P(intern->u.file.current_zval)->pListHead->pData; return Z_TYPE_PP(first) == IS_STRING && Z_STRLEN_PP(first) == 0; } return zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 0; case IS_NULL: return 1; default: return 0; } } else { return 1; } } /* }}} */ static int spl_filesystem_file_read_line(zval * this_ptr, spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */ { int ret = spl_filesystem_file_read_line_ex(this_ptr, intern, silent TSRMLS_CC); while (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY) && ret == SUCCESS && spl_filesystem_file_is_empty_line(intern TSRMLS_CC)) { spl_filesystem_file_free_line(intern TSRMLS_CC); ret = spl_filesystem_file_read_line_ex(this_ptr, intern, silent TSRMLS_CC); } return ret; } /* }}} */ static void spl_filesystem_file_rewind(zval * this_ptr, spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { if (-1 == php_stream_rewind(intern->u.file.stream)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot rewind file %s", intern->file_name); } else { spl_filesystem_file_free_line(intern TSRMLS_CC); intern->u.file.current_line_num = 0; } if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_AHEAD)) { spl_filesystem_file_read_line(this_ptr, intern, 1 TSRMLS_CC); } } /* }}} */ /* {{{ proto void SplFileObject::__construct(string filename [, string mode = 'r' [, bool use_include_path [, resource context]]]]) Construct a new file object */ SPL_METHOD(SplFileObject, __construct) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_bool use_include_path = 0; char *p1, *p2; char *tmp_path; int tmp_path_len; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); intern->u.file.open_mode = NULL; intern->u.file.open_mode_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|sbr", &intern->file_name, &intern->file_name_len, &intern->u.file.open_mode, &intern->u.file.open_mode_len, &use_include_path, &intern->u.file.zcontext) == FAILURE) { intern->u.file.open_mode = NULL; intern->file_name = NULL; zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (intern->u.file.open_mode == NULL) { intern->u.file.open_mode = "r"; intern->u.file.open_mode_len = 1; } if (spl_filesystem_file_open(intern, use_include_path, 0 TSRMLS_CC) == SUCCESS) { tmp_path_len = strlen(intern->u.file.stream->orig_path); if (tmp_path_len > 1 && IS_SLASH_AT(intern->u.file.stream->orig_path, tmp_path_len-1)) { tmp_path_len--; } tmp_path = estrndup(intern->u.file.stream->orig_path, tmp_path_len); p1 = strrchr(tmp_path, '/'); #if defined(PHP_WIN32) || defined(NETWARE) p2 = strrchr(tmp_path, '\\'); #else p2 = 0; #endif if (p1 || p2) { intern->_path_len = (p1 > p2 ? p1 : p2) - tmp_path; } else { intern->_path_len = 0; } efree(tmp_path); intern->_path = estrndup(intern->u.file.stream->orig_path, intern->_path_len); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void SplTempFileObject::__construct([int max_memory]) Construct a new temp file object */ SPL_METHOD(SplTempFileObject, __construct) { long max_memory = PHP_STREAM_MAX_MEM; char tmp_fname[48]; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &max_memory) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (max_memory < 0) { intern->file_name = "php://memory"; intern->file_name_len = 12; } else if (ZEND_NUM_ARGS()) { intern->file_name_len = slprintf(tmp_fname, sizeof(tmp_fname), "php://temp/maxmemory:%ld", max_memory); intern->file_name = tmp_fname; } else { intern->file_name = "php://temp"; intern->file_name_len = 10; } intern->u.file.open_mode = "wb"; intern->u.file.open_mode_len = 1; intern->u.file.zcontext = NULL; if (spl_filesystem_file_open(intern, 0, 0 TSRMLS_CC) == SUCCESS) { intern->_path_len = 0; intern->_path = estrndup("", 0); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void SplFileObject::rewind() Rewind the file and read the first line */ SPL_METHOD(SplFileObject, rewind) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC); } /* }}} */ /* {{{ proto void SplFileObject::eof() Return whether end of file is reached */ SPL_METHOD(SplFileObject, eof) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(php_stream_eof(intern->u.file.stream)); } /* }}} */ /* {{{ proto void SplFileObject::valid() Return !eof() */ SPL_METHOD(SplFileObject, valid) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_AHEAD)) { RETURN_BOOL(intern->u.file.current_line || intern->u.file.current_zval); } else { RETVAL_BOOL(!php_stream_eof(intern->u.file.stream)); } } /* }}} */ /* {{{ proto string SplFileObject::fgets() Rturn next line from file */ SPL_METHOD(SplFileObject, fgets) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (spl_filesystem_file_read(intern, 0 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1); } /* }}} */ /* {{{ proto string SplFileObject::current() Return current line from file */ SPL_METHOD(SplFileObject, current) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!intern->u.file.current_line && !intern->u.file.current_zval) { spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC); } if (intern->u.file.current_line && (!SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) || !intern->u.file.current_zval)) { RETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1); } else if (intern->u.file.current_zval) { RETURN_ZVAL(intern->u.file.current_zval, 1, 0); } RETURN_FALSE; } /* }}} */ /* {{{ proto int SplFileObject::key() Return line number */ SPL_METHOD(SplFileObject, key) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } /* Do not read the next line to support correct counting with fgetc() if (!intern->current_line) { spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC); } */ RETURN_LONG(intern->u.file.current_line_num); } /* }}} */ /* {{{ proto void SplFileObject::next() Read next line */ SPL_METHOD(SplFileObject, next) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_file_free_line(intern TSRMLS_CC); if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_AHEAD)) { spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC); } intern->u.file.current_line_num++; } /* }}} */ /* {{{ proto void SplFileObject::setFlags(int flags) Set file handling flags */ SPL_METHOD(SplFileObject, setFlags) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &intern->flags) == FAILURE) { return; } } /* }}} */ /* {{{ proto int SplFileObject::getFlags() Get file handling flags */ SPL_METHOD(SplFileObject, getFlags) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(intern->flags & SPL_FILE_OBJECT_MASK); } /* }}} */ /* {{{ proto void SplFileObject::setMaxLineLen(int max_len) Set maximum line length */ SPL_METHOD(SplFileObject, setMaxLineLen) { long max_len; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &max_len) == FAILURE) { return; } if (max_len < 0) { zend_throw_exception_ex(spl_ce_DomainException, 0 TSRMLS_CC, "Maximum line length must be greater than or equal zero"); return; } intern->u.file.max_line_len = max_len; } /* }}} */ /* {{{ proto int SplFileObject::getMaxLineLen() Get maximum line length */ SPL_METHOD(SplFileObject, getMaxLineLen) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG((long)intern->u.file.max_line_len); } /* }}} */ /* {{{ proto bool SplFileObject::hasChildren() Return false */ SPL_METHOD(SplFileObject, hasChildren) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_FALSE; } /* }}} */ /* {{{ proto bool SplFileObject::getChildren() Read NULL */ SPL_METHOD(SplFileObject, getChildren) { if (zend_parse_parameters_none() == FAILURE) { return; } /* return NULL */ } /* }}} */ /* {{{ FileFunction */ #define FileFunction(func_name) \ SPL_METHOD(SplFileObject, func_name) \ { \ spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); \ FileFunctionCall(func_name, ZEND_NUM_ARGS(), NULL); \ } /* }}} */ /* {{{ proto array SplFileObject::fgetcsv([string delimiter [, string enclosure [, escape = '\\']]]) Return current line as csv */ SPL_METHOD(SplFileObject, fgetcsv) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter = intern->u.file.delimiter, enclosure = intern->u.file.enclosure, escape = intern->u.file.escape; char *delim = NULL, *enclo = NULL, *esc = NULL; int d_len = 0, e_len = 0, esc_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sss", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) { switch(ZEND_NUM_ARGS()) { case 3: if (esc_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character"); RETURN_FALSE; } escape = esc[0]; /* no break */ case 2: if (e_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } enclosure = enclo[0]; /* no break */ case 1: if (d_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } delimiter = delim[0]; /* no break */ case 0: break; } spl_filesystem_file_read_csv(intern, delimiter, enclosure, escape, return_value TSRMLS_CC); } } /* }}} */ /* {{{ proto int SplFileObject::fputcsv(array fields, [string delimiter [, string enclosure]]) Output a field array as a CSV line */ SPL_METHOD(SplFileObject, fputcsv) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter = intern->u.file.delimiter, enclosure = intern->u.file.enclosure, escape = intern->u.file.escape; char *delim = NULL, *enclo = NULL; int d_len = 0, e_len = 0, ret; zval *fields = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|ss", &fields, &delim, &d_len, &enclo, &e_len) == SUCCESS) { switch(ZEND_NUM_ARGS()) { case 3: if (e_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } enclosure = enclo[0]; /* no break */ case 2: if (d_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } delimiter = delim[0]; /* no break */ case 1: case 0: break; } ret = php_fputcsv(intern->u.file.stream, fields, delimiter, enclosure, escape TSRMLS_CC); RETURN_LONG(ret); } } /* }}} */ /* {{{ proto void SplFileObject::setCsvControl([string delimiter = ',' [, string enclosure = '"' [, string escape = '\\']]]) Set the delimiter and enclosure character used in fgetcsv */ SPL_METHOD(SplFileObject, setCsvControl) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter = ',', enclosure = '"', escape='\\'; char *delim = NULL, *enclo = NULL, *esc = NULL; int d_len = 0, e_len = 0, esc_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sss", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) { switch(ZEND_NUM_ARGS()) { case 3: if (esc_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character"); RETURN_FALSE; } escape = esc[0]; /* no break */ case 2: if (e_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } enclosure = enclo[0]; /* no break */ case 1: if (d_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } delimiter = delim[0]; /* no break */ case 0: break; } intern->u.file.delimiter = delimiter; intern->u.file.enclosure = enclosure; intern->u.file.escape = escape; } } /* }}} */ /* {{{ proto array SplFileObject::getCsvControl() Get the delimiter and enclosure character used in fgetcsv */ SPL_METHOD(SplFileObject, getCsvControl) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter[2], enclosure[2]; array_init(return_value); delimiter[0] = intern->u.file.delimiter; delimiter[1] = '\0'; enclosure[0] = intern->u.file.enclosure; enclosure[1] = '\0'; add_next_index_string(return_value, delimiter, 1); add_next_index_string(return_value, enclosure, 1); } /* }}} */ /* {{{ proto bool SplFileObject::flock(int operation [, int &wouldblock]) Portable file locking */ FileFunction(flock) /* }}} */ /* {{{ proto bool SplFileObject::fflush() Flush the file */ SPL_METHOD(SplFileObject, fflush) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); RETURN_BOOL(!php_stream_flush(intern->u.file.stream)); } /* }}} */ /* {{{ proto int SplFileObject::ftell() Return current file position */ SPL_METHOD(SplFileObject, ftell) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long ret = php_stream_tell(intern->u.file.stream); if (ret == -1) { RETURN_FALSE; } else { RETURN_LONG(ret); } } /* }}} */ /* {{{ proto int SplFileObject::fseek(int pos [, int whence = SEEK_SET]) Return current file position */ SPL_METHOD(SplFileObject, fseek) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long pos, whence = SEEK_SET; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|l", &pos, &whence) == FAILURE) { return; } spl_filesystem_file_free_line(intern TSRMLS_CC); RETURN_LONG(php_stream_seek(intern->u.file.stream, pos, whence)); } /* }}} */ /* {{{ proto int SplFileObject::fgetc() Get a character form the file */ SPL_METHOD(SplFileObject, fgetc) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char buf[2]; int result; spl_filesystem_file_free_line(intern TSRMLS_CC); result = php_stream_getc(intern->u.file.stream); if (result == EOF) { RETVAL_FALSE; } else { if (result == '\n') { intern->u.file.current_line_num++; } buf[0] = result; buf[1] = '\0'; RETURN_STRINGL(buf, 1, 1); } } /* }}} */ /* {{{ proto string SplFileObject::fgetss([string allowable_tags]) Get a line from file pointer and strip HTML tags */ SPL_METHOD(SplFileObject, fgetss) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zval *arg2 = NULL; MAKE_STD_ZVAL(arg2); if (intern->u.file.max_line_len > 0) { ZVAL_LONG(arg2, intern->u.file.max_line_len); } else { ZVAL_LONG(arg2, 1024); } spl_filesystem_file_free_line(intern TSRMLS_CC); intern->u.file.current_line_num++; FileFunctionCall(fgetss, ZEND_NUM_ARGS(), arg2); zval_ptr_dtor(&arg2); } /* }}} */ /* {{{ proto int SplFileObject::fpassthru() Output all remaining data from a file pointer */ SPL_METHOD(SplFileObject, fpassthru) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); RETURN_LONG(php_stream_passthru(intern->u.file.stream)); } /* }}} */ /* {{{ proto bool SplFileObject::fscanf(string format [, string ...]) Implements a mostly ANSI compatible fscanf() */ SPL_METHOD(SplFileObject, fscanf) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_filesystem_file_free_line(intern TSRMLS_CC); intern->u.file.current_line_num++; FileFunctionCall(fscanf, ZEND_NUM_ARGS(), NULL); } /* }}} */ /* {{{ proto mixed SplFileObject::fwrite(string str [, int length]) Binary-safe file write */ SPL_METHOD(SplFileObject, fwrite) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *str; int str_len; long length = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &str, &str_len, &length) == FAILURE) { return; } if (ZEND_NUM_ARGS() > 1) { str_len = MAX(0, MIN(length, str_len)); } if (!str_len) { RETURN_LONG(0); } RETURN_LONG(php_stream_write(intern->u.file.stream, str, str_len)); } /* }}} */ /* {{{ proto bool SplFileObject::fstat() Stat() on a filehandle */ FileFunction(fstat) /* }}} */ /* {{{ proto bool SplFileObject::ftruncate(int size) Truncate file to 'size' length */ SPL_METHOD(SplFileObject, ftruncate) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long size; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &size) == FAILURE) { return; } if (!php_stream_truncate_supported(intern->u.file.stream)) { zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Can't truncate file %s", intern->file_name); RETURN_FALSE; } RETURN_BOOL(0 == php_stream_truncate_set_size(intern->u.file.stream, size)); } /* }}} */ /* {{{ proto void SplFileObject::seek(int line_pos) Seek to specified line */ SPL_METHOD(SplFileObject, seek) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long line_pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &line_pos) == FAILURE) { return; } if (line_pos < 0) { zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Can't seek file %s to negative line %ld", intern->file_name, line_pos); RETURN_FALSE; } spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC); while(intern->u.file.current_line_num < line_pos) { if (spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC) == FAILURE) { break; } } } /* }}} */ /* {{{ Function/Class/Method definitions */ ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object___construct, 0, 0, 1) ZEND_ARG_INFO(0, file_name) ZEND_ARG_INFO(0, open_mode) ZEND_ARG_INFO(0, use_include_path) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_file_object_setFlags, 0) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_file_object_setMaxLineLen, 0) ZEND_ARG_INFO(0, max_len) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fgetcsv, 0, 0, 0) ZEND_ARG_INFO(0, delimiter) ZEND_ARG_INFO(0, enclosure) ZEND_ARG_INFO(0, escape) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fputcsv, 0, 0, 1) ZEND_ARG_INFO(0, fields) ZEND_ARG_INFO(0, delimiter) ZEND_ARG_INFO(0, enclosure) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_flock, 0, 0, 1) ZEND_ARG_INFO(0, operation) ZEND_ARG_INFO(1, wouldblock) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fseek, 0, 0, 1) ZEND_ARG_INFO(0, pos) ZEND_ARG_INFO(0, whence) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fgetss, 0, 0, 0) ZEND_ARG_INFO(0, allowable_tags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fscanf, 1, 0, 1) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fwrite, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, length) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_ftruncate, 0, 0, 1) ZEND_ARG_INFO(0, size) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_seek, 0, 0, 1) ZEND_ARG_INFO(0, line_pos) ZEND_END_ARG_INFO() static const zend_function_entry spl_SplFileObject_functions[] = { SPL_ME(SplFileObject, __construct, arginfo_file_object___construct, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, rewind, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, eof, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, valid, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fgets, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fgetcsv, arginfo_file_object_fgetcsv, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fputcsv, arginfo_file_object_fputcsv, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, setCsvControl, arginfo_file_object_fgetcsv, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, getCsvControl, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, flock, arginfo_file_object_flock, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fflush, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, ftell, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fseek, arginfo_file_object_fseek, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fgetc, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fpassthru, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fgetss, arginfo_file_object_fgetss, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fscanf, arginfo_file_object_fscanf, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fwrite, arginfo_file_object_fwrite, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fstat, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, ftruncate, arginfo_file_object_ftruncate, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, current, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, key, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, next, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, setFlags, arginfo_file_object_setFlags, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, getFlags, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, setMaxLineLen, arginfo_file_object_setMaxLineLen, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, getMaxLineLen, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, hasChildren, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, getChildren, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, seek, arginfo_file_object_seek, ZEND_ACC_PUBLIC) /* mappings */ SPL_MA(SplFileObject, getCurrentLine, SplFileObject, fgets, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_MA(SplFileObject, __toString, SplFileObject, current, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) PHP_FE_END }; ZEND_BEGIN_ARG_INFO_EX(arginfo_temp_file_object___construct, 0, 0, 0) ZEND_ARG_INFO(0, max_memory) ZEND_END_ARG_INFO() static const zend_function_entry spl_SplTempFileObject_functions[] = { SPL_ME(SplTempFileObject, __construct, arginfo_temp_file_object___construct, ZEND_ACC_PUBLIC) PHP_FE_END }; /* }}} */ /* {{{ PHP_MINIT_FUNCTION(spl_directory) */ PHP_MINIT_FUNCTION(spl_directory) { REGISTER_SPL_STD_CLASS_EX(SplFileInfo, spl_filesystem_object_new, spl_SplFileInfo_functions); memcpy(&spl_filesystem_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); spl_filesystem_object_handlers.clone_obj = spl_filesystem_object_clone; spl_filesystem_object_handlers.cast_object = spl_filesystem_object_cast; spl_filesystem_object_handlers.get_debug_info = spl_filesystem_object_get_debug_info; spl_ce_SplFileInfo->serialize = zend_class_serialize_deny; spl_ce_SplFileInfo->unserialize = zend_class_unserialize_deny; REGISTER_SPL_SUB_CLASS_EX(DirectoryIterator, SplFileInfo, spl_filesystem_object_new, spl_DirectoryIterator_functions); zend_class_implements(spl_ce_DirectoryIterator TSRMLS_CC, 1, zend_ce_iterator); REGISTER_SPL_IMPLEMENTS(DirectoryIterator, SeekableIterator); spl_ce_DirectoryIterator->get_iterator = spl_filesystem_dir_get_iterator; REGISTER_SPL_SUB_CLASS_EX(FilesystemIterator, DirectoryIterator, spl_filesystem_object_new, spl_FilesystemIterator_functions); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_MODE_MASK", SPL_FILE_DIR_CURRENT_MODE_MASK); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_PATHNAME", SPL_FILE_DIR_CURRENT_AS_PATHNAME); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_FILEINFO", SPL_FILE_DIR_CURRENT_AS_FILEINFO); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_SELF", SPL_FILE_DIR_CURRENT_AS_SELF); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_MODE_MASK", SPL_FILE_DIR_KEY_MODE_MASK); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_AS_PATHNAME", SPL_FILE_DIR_KEY_AS_PATHNAME); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "FOLLOW_SYMLINKS", SPL_FILE_DIR_FOLLOW_SYMLINKS); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_AS_FILENAME", SPL_FILE_DIR_KEY_AS_FILENAME); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "NEW_CURRENT_AND_KEY", SPL_FILE_DIR_KEY_AS_FILENAME|SPL_FILE_DIR_CURRENT_AS_FILEINFO); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "SKIP_DOTS", SPL_FILE_DIR_SKIPDOTS); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "UNIX_PATHS", SPL_FILE_DIR_UNIXPATHS); spl_ce_FilesystemIterator->get_iterator = spl_filesystem_tree_get_iterator; REGISTER_SPL_SUB_CLASS_EX(RecursiveDirectoryIterator, FilesystemIterator, spl_filesystem_object_new, spl_RecursiveDirectoryIterator_functions); REGISTER_SPL_IMPLEMENTS(RecursiveDirectoryIterator, RecursiveIterator); memcpy(&spl_filesystem_object_check_handlers, &spl_filesystem_object_handlers, sizeof(zend_object_handlers)); spl_filesystem_object_check_handlers.get_method = spl_filesystem_object_get_method_check; #ifdef HAVE_GLOB REGISTER_SPL_SUB_CLASS_EX(GlobIterator, FilesystemIterator, spl_filesystem_object_new_check, spl_GlobIterator_functions); REGISTER_SPL_IMPLEMENTS(GlobIterator, Countable); #endif REGISTER_SPL_SUB_CLASS_EX(SplFileObject, SplFileInfo, spl_filesystem_object_new_check, spl_SplFileObject_functions); REGISTER_SPL_IMPLEMENTS(SplFileObject, RecursiveIterator); REGISTER_SPL_IMPLEMENTS(SplFileObject, SeekableIterator); REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "DROP_NEW_LINE", SPL_FILE_OBJECT_DROP_NEW_LINE); REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "READ_AHEAD", SPL_FILE_OBJECT_READ_AHEAD); REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "SKIP_EMPTY", SPL_FILE_OBJECT_SKIP_EMPTY); REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "READ_CSV", SPL_FILE_OBJECT_READ_CSV); REGISTER_SPL_SUB_CLASS_EX(SplTempFileObject, SplFileObject, spl_filesystem_object_new_check, spl_SplTempFileObject_functions); return SUCCESS; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-11-11-fcbfbea8d2-c1e510aea8.c
manybugs_data_13
/* Peephole optimizations for bytecode compiler. */ #include "Python.h" #include "Python-ast.h" #include "node.h" #include "ast.h" #include "code.h" #include "symtable.h" #include "opcode.h" #define GETARG(arr, i) ((int)((arr[i+2]<<8) + arr[i+1])) #define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD) #define CONDITIONAL_JUMP(op) (op==POP_JUMP_IF_FALSE || op==POP_JUMP_IF_TRUE \ || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP) #define ABSOLUTE_JUMP(op) (op==JUMP_ABSOLUTE || op==CONTINUE_LOOP \ || op==POP_JUMP_IF_FALSE || op==POP_JUMP_IF_TRUE \ || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP) #define JUMPS_ON_TRUE(op) (op==POP_JUMP_IF_TRUE || op==JUMP_IF_TRUE_OR_POP) #define GETJUMPTGT(arr, i) (GETARG(arr,i) + (ABSOLUTE_JUMP(arr[i]) ? 0 : i+3)) #define SETARG(arr, i, val) arr[i+2] = val>>8; arr[i+1] = val & 255 #define CODESIZE(op) (HAS_ARG(op) ? 3 : 1) #define ISBASICBLOCK(blocks, start, bytes) \ (blocks[start]==blocks[start+bytes-1]) #define CONST_STACK_CREATE() { \ const_stack_size = 256; \ const_stack = PyMem_New(PyObject *, const_stack_size); \ load_const_stack = PyMem_New(Py_ssize_t, const_stack_size); \ if (!const_stack || !load_const_stack) { \ PyErr_NoMemory(); \ goto exitError; \ } \ } #define CONST_STACK_DELETE() do { \ if (const_stack) \ PyMem_Free(const_stack); \ if (load_const_stack) \ PyMem_Free(load_const_stack); \ } while(0) #define CONST_STACK_LEN() (const_stack_top + 1) #define CONST_STACK_PUSH_OP(i) do { \ PyObject *_x; \ assert(codestr[i] == LOAD_CONST); \ assert(PyList_GET_SIZE(consts) > GETARG(codestr, i)); \ _x = PyList_GET_ITEM(consts, GETARG(codestr, i)); \ if (++const_stack_top >= const_stack_size) { \ const_stack_size *= 2; \ PyMem_Resize(const_stack, PyObject *, const_stack_size); \ PyMem_Resize(load_const_stack, Py_ssize_t, const_stack_size); \ if (!const_stack || !load_const_stack) { \ PyErr_NoMemory(); \ goto exitError; \ } \ } \ load_const_stack[const_stack_top] = i; \ const_stack[const_stack_top] = _x; \ in_consts = 1; \ } while(0) #define CONST_STACK_RESET() do { \ const_stack_top = -1; \ } while(0) #define CONST_STACK_TOP(x) \ const_stack[const_stack_top] #define CONST_STACK_LASTN(i) \ &const_stack[const_stack_top - i + 1] #define CONST_STACK_POP(i) do { \ assert(const_stack_top + 1 >= i); \ const_stack_top -= i; \ } while(0) #define CONST_STACK_OP_LASTN(i) \ ((const_stack_top >= i - 1) ? load_const_stack[const_stack_top - i + 1] : -1) /* Replace LOAD_CONST c1. LOAD_CONST c2 ... LOAD_CONST cn BUILD_TUPLE n with LOAD_CONST (c1, c2, ... cn). The consts table must still be in list form so that the new constant (c1, c2, ... cn) can be appended. Called with codestr pointing to the first LOAD_CONST. Bails out with no change if one or more of the LOAD_CONSTs is missing. Also works for BUILD_LIST and BUILT_SET when followed by an "in" or "not in" test; for BUILD_SET it assembles a frozenset rather than a tuple. */ static int tuple_of_constants(unsigned char *codestr, Py_ssize_t n, PyObject *consts, PyObject **objs) { PyObject *newconst, *constant; Py_ssize_t i, len_consts; /* Pre-conditions */ assert(PyList_CheckExact(consts)); /* Buildup new tuple of constants */ newconst = PyTuple_New(n); if (newconst == NULL) return 0; len_consts = PyList_GET_SIZE(consts); for (i=0 ; i<n ; i++) { constant = objs[i]; Py_INCREF(constant); PyTuple_SET_ITEM(newconst, i, constant); } /* If it's a BUILD_SET, use the PyTuple we just built to create a PyFrozenSet, and use that as the constant instead: */ if (codestr[0] == BUILD_SET) { PyObject *tuple = newconst; newconst = PyFrozenSet_New(tuple); Py_DECREF(tuple); if (newconst == NULL) return 0; } /* Append folded constant onto consts */ if (PyList_Append(consts, newconst)) { Py_DECREF(newconst); return 0; } Py_DECREF(newconst); /* Write NOPs over old LOAD_CONSTS and add a new LOAD_CONST newconst on top of the BUILD_TUPLE n */ codestr[0] = LOAD_CONST; SETARG(codestr, 0, len_consts); return 1; } /* Replace LOAD_CONST c1. LOAD_CONST c2 BINOP with LOAD_CONST binop(c1,c2) The consts table must still be in list form so that the new constant can be appended. Called with codestr pointing to the BINOP. Abandons the transformation if the folding fails (i.e. 1+'a'). If the new constant is a sequence, only folds when the size is below a threshold value. That keeps pyc files from becoming large in the presence of code like: (None,)*1000. */ static int fold_binops_on_constants(unsigned char *codestr, PyObject *consts, PyObject **objs) { PyObject *newconst, *v, *w; Py_ssize_t len_consts, size; int opcode; /* Pre-conditions */ assert(PyList_CheckExact(consts)); /* Create new constant */ v = objs[0]; w = objs[1]; opcode = codestr[0]; switch (opcode) { case BINARY_POWER: newconst = PyNumber_Power(v, w, Py_None); break; case BINARY_MULTIPLY: newconst = PyNumber_Multiply(v, w); break; case BINARY_TRUE_DIVIDE: newconst = PyNumber_TrueDivide(v, w); break; case BINARY_FLOOR_DIVIDE: newconst = PyNumber_FloorDivide(v, w); break; case BINARY_MODULO: newconst = PyNumber_Remainder(v, w); break; case BINARY_ADD: newconst = PyNumber_Add(v, w); break; case BINARY_SUBTRACT: newconst = PyNumber_Subtract(v, w); break; case BINARY_SUBSCR: newconst = PyObject_GetItem(v, w); break; case BINARY_LSHIFT: newconst = PyNumber_Lshift(v, w); break; case BINARY_RSHIFT: newconst = PyNumber_Rshift(v, w); break; case BINARY_AND: newconst = PyNumber_And(v, w); break; case BINARY_XOR: newconst = PyNumber_Xor(v, w); break; case BINARY_OR: newconst = PyNumber_Or(v, w); break; default: /* Called with an unknown opcode */ PyErr_Format(PyExc_SystemError, "unexpected binary operation %d on a constant", opcode); return 0; } if (newconst == NULL) { if(!PyErr_ExceptionMatches(PyExc_KeyboardInterrupt)) PyErr_Clear(); return 0; } size = PyObject_Size(newconst); if (size == -1) { if (PyErr_ExceptionMatches(PyExc_KeyboardInterrupt)) return 0; PyErr_Clear(); } else if (size > 20) { Py_DECREF(newconst); return 0; } /* Append folded constant into consts table */ len_consts = PyList_GET_SIZE(consts); if (PyList_Append(consts, newconst)) { Py_DECREF(newconst); return 0; } Py_DECREF(newconst); /* Write NOP NOP NOP NOP LOAD_CONST newconst */ codestr[-2] = LOAD_CONST; SETARG(codestr, -2, len_consts); return 1; } static int fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts, PyObject *v) { PyObject *newconst; Py_ssize_t len_consts; int opcode; /* Pre-conditions */ assert(PyList_CheckExact(consts)); assert(codestr[0] == LOAD_CONST); /* Create new constant */ opcode = codestr[3]; switch (opcode) { case UNARY_NEGATIVE: newconst = PyNumber_Negative(v); break; case UNARY_INVERT: newconst = PyNumber_Invert(v); break; case UNARY_POSITIVE: newconst = PyNumber_Positive(v); break; default: /* Called with an unknown opcode */ PyErr_Format(PyExc_SystemError, "unexpected unary operation %d on a constant", opcode); return 0; } if (newconst == NULL) { if(!PyErr_ExceptionMatches(PyExc_KeyboardInterrupt)) PyErr_Clear(); return 0; } /* Append folded constant into consts table */ len_consts = PyList_GET_SIZE(consts); if (PyList_Append(consts, newconst)) { Py_DECREF(newconst); return 0; } Py_DECREF(newconst); /* Write NOP LOAD_CONST newconst */ codestr[0] = NOP; codestr[1] = LOAD_CONST; SETARG(codestr, 1, len_consts); return 1; } static unsigned int * markblocks(unsigned char *code, Py_ssize_t len) { unsigned int *blocks = (unsigned int *)PyMem_Malloc(len*sizeof(int)); int i,j, opcode, blockcnt = 0; if (blocks == NULL) { PyErr_NoMemory(); return NULL; } memset(blocks, 0, len*sizeof(int)); /* Mark labels in the first pass */ for (i=0 ; i<len ; i+=CODESIZE(opcode)) { opcode = code[i]; switch (opcode) { case FOR_ITER: case JUMP_FORWARD: case JUMP_IF_FALSE_OR_POP: case JUMP_IF_TRUE_OR_POP: case POP_JUMP_IF_FALSE: case POP_JUMP_IF_TRUE: case JUMP_ABSOLUTE: case CONTINUE_LOOP: case SETUP_LOOP: case SETUP_EXCEPT: case SETUP_FINALLY: case SETUP_WITH: j = GETJUMPTGT(code, i); blocks[j] = 1; break; } } /* Build block numbers in the second pass */ for (i=0 ; i<len ; i++) { blockcnt += blocks[i]; /* increment blockcnt over labels */ blocks[i] = blockcnt; } return blocks; } /* Helper to replace LOAD_NAME None/True/False with LOAD_CONST Returns: 0 if no change, 1 if change, -1 if error */ static int load_global(unsigned char *codestr, Py_ssize_t i, char *name, PyObject *consts) { Py_ssize_t j; PyObject *obj; if (name == NULL) return 0; if (strcmp(name, "None") == 0) obj = Py_None; else if (strcmp(name, "True") == 0) obj = Py_True; else if (strcmp(name, "False") == 0) obj = Py_False; else return 0; for (j = 0; j < PyList_GET_SIZE(consts); j++) { if (PyList_GET_ITEM(consts, j) == obj) break; } if (j == PyList_GET_SIZE(consts)) { if (PyList_Append(consts, obj) < 0) return -1; } assert(PyList_GET_ITEM(consts, j) == obj); codestr[i] = LOAD_CONST; SETARG(codestr, i, j); return 1; } /* Perform basic peephole optimizations to components of a code object. The consts object should still be in list form to allow new constants to be appended. To keep the optimizer simple, it bails out (does nothing) for code that has a length over 32,700, and does not calculate extended arguments. That allows us to avoid overflow and sign issues. Likewise, it bails when the lineno table has complex encoding for gaps >= 255. EXTENDED_ARG can appear before MAKE_FUNCTION; in this case both opcodes are skipped. EXTENDED_ARG preceding any other opcode causes the optimizer to bail. Optimizations are restricted to simple transformations occuring within a single basic block. All transformations keep the code size the same or smaller. For those that reduce size, the gaps are initially filled with NOPs. Later those NOPs are removed and the jump addresses retargeted in a single pass. Line numbering is adjusted accordingly. */ PyObject * PyCode_Optimize(PyObject *code, PyObject* consts, PyObject *names, PyObject *lineno_obj) { Py_ssize_t i, j, codelen; int nops, h, adj; int tgt, tgttgt, opcode; unsigned char *codestr = NULL; unsigned char *lineno; int *addrmap = NULL; int new_line, cum_orig_line, last_line, tabsiz; PyObject **const_stack = NULL; Py_ssize_t *load_const_stack = NULL; Py_ssize_t const_stack_top = -1; Py_ssize_t const_stack_size = 0; int in_consts = 0; /* whether we are in a LOAD_CONST sequence */ unsigned int *blocks = NULL; char *name; /* Bail out if an exception is set */ if (PyErr_Occurred()) goto exitError; /* Bypass optimization when the lineno table is too complex */ assert(PyBytes_Check(lineno_obj)); lineno = (unsigned char*)PyBytes_AS_STRING(lineno_obj); tabsiz = PyBytes_GET_SIZE(lineno_obj); if (memchr(lineno, 255, tabsiz) != NULL) goto exitUnchanged; /* Avoid situations where jump retargeting could overflow */ assert(PyBytes_Check(code)); codelen = PyBytes_GET_SIZE(code); if (codelen > 32700) goto exitUnchanged; /* Make a modifiable copy of the code string */ codestr = (unsigned char *)PyMem_Malloc(codelen); if (codestr == NULL) goto exitError; codestr = (unsigned char *)memcpy(codestr, PyBytes_AS_STRING(code), codelen); /* Verify that RETURN_VALUE terminates the codestring. This allows the various transformation patterns to look ahead several instructions without additional checks to make sure they are not looking beyond the end of the code string. */ if (codestr[codelen-1] != RETURN_VALUE) goto exitUnchanged; /* Mapping to new jump targets after NOPs are removed */ addrmap = (int *)PyMem_Malloc(codelen * sizeof(int)); if (addrmap == NULL) goto exitError; blocks = markblocks(codestr, codelen); if (blocks == NULL) goto exitError; assert(PyList_Check(consts)); CONST_STACK_CREATE(); for (i=0 ; i<codelen ; i += CODESIZE(codestr[i])) { reoptimize_current: opcode = codestr[i]; if (!in_consts) { CONST_STACK_RESET(); } in_consts = 0; switch (opcode) { /* Replace UNARY_NOT POP_JUMP_IF_FALSE with POP_JUMP_IF_TRUE */ case UNARY_NOT: if (codestr[i+1] != POP_JUMP_IF_FALSE || !ISBASICBLOCK(blocks,i,4)) continue; j = GETARG(codestr, i+1); codestr[i] = POP_JUMP_IF_TRUE; SETARG(codestr, i, j); codestr[i+3] = NOP; goto reoptimize_current; /* not a is b --> a is not b not a in b --> a not in b not a is not b --> a is b not a not in b --> a in b */ case COMPARE_OP: j = GETARG(codestr, i); if (j < 6 || j > 9 || codestr[i+3] != UNARY_NOT || !ISBASICBLOCK(blocks,i,4)) continue; SETARG(codestr, i, (j^1)); codestr[i+3] = NOP; break; /* Replace LOAD_GLOBAL/LOAD_NAME None/True/False with LOAD_CONST None/True/False */ case LOAD_NAME: case LOAD_GLOBAL: j = GETARG(codestr, i); name = _PyUnicode_AsString(PyTuple_GET_ITEM(names, j)); h = load_global(codestr, i, name, consts); if (h < 0) goto exitError; else if (h == 0) continue; CONST_STACK_PUSH_OP(i); break; /* Skip over LOAD_CONST trueconst POP_JUMP_IF_FALSE xx. This improves "while 1" performance. */ case LOAD_CONST: CONST_STACK_PUSH_OP(i); j = GETARG(codestr, i); if (codestr[i+3] != POP_JUMP_IF_FALSE || !ISBASICBLOCK(blocks,i,6) || !PyObject_IsTrue(PyList_GET_ITEM(consts, j))) continue; memset(codestr+i, NOP, 6); CONST_STACK_RESET(); break; /* Try to fold tuples of constants (includes a case for lists and sets which are only used for "in" and "not in" tests). Skip over BUILD_SEQN 1 UNPACK_SEQN 1. Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2. Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */ case BUILD_TUPLE: case BUILD_LIST: case BUILD_SET: j = GETARG(codestr, i); if (j == 0) break; h = CONST_STACK_OP_LASTN(j); assert((h >= 0 || CONST_STACK_LEN() < j)); if (h >= 0 && j > 0 && j <= CONST_STACK_LEN() && ((opcode == BUILD_TUPLE && ISBASICBLOCK(blocks, h, i-h+3)) || ((opcode == BUILD_LIST || opcode == BUILD_SET) && codestr[i+3]==COMPARE_OP && ISBASICBLOCK(blocks, h, i-h+6) && (GETARG(codestr,i+3)==6 || GETARG(codestr,i+3)==7))) && tuple_of_constants(&codestr[i], j, consts, CONST_STACK_LASTN(j))) { assert(codestr[i] == LOAD_CONST); memset(&codestr[h], NOP, i - h); CONST_STACK_POP(j); CONST_STACK_PUSH_OP(i); break; } if (codestr[i+3] != UNPACK_SEQUENCE || !ISBASICBLOCK(blocks,i,6) || j != GETARG(codestr, i+3) || opcode == BUILD_SET) continue; if (j == 1) { memset(codestr+i, NOP, 6); } else if (j == 2) { codestr[i] = ROT_TWO; memset(codestr+i+1, NOP, 5); CONST_STACK_RESET(); } else if (j == 3) { codestr[i] = ROT_THREE; codestr[i+1] = ROT_TWO; memset(codestr+i+2, NOP, 4); CONST_STACK_RESET(); } break; /* Fold binary ops on constants. LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */ case BINARY_POWER: case BINARY_MULTIPLY: case BINARY_TRUE_DIVIDE: case BINARY_FLOOR_DIVIDE: case BINARY_MODULO: case BINARY_ADD: case BINARY_SUBTRACT: case BINARY_SUBSCR: case BINARY_LSHIFT: case BINARY_RSHIFT: case BINARY_AND: case BINARY_XOR: case BINARY_OR: /* NOTE: LOAD_CONST is saved at `i-2` since it has an arg while BINOP hasn't */ h = CONST_STACK_OP_LASTN(2); assert((h >= 0 || CONST_STACK_LEN() < 2)); if (h >= 0 && ISBASICBLOCK(blocks, h, i-h+1) && fold_binops_on_constants(&codestr[i], consts, CONST_STACK_LASTN(2))) { i -= 2; memset(&codestr[h], NOP, i - h); assert(codestr[i] == LOAD_CONST); CONST_STACK_POP(2); CONST_STACK_PUSH_OP(i); } break; /* Fold unary ops on constants. LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */ case UNARY_NEGATIVE: case UNARY_INVERT: case UNARY_POSITIVE: h = CONST_STACK_OP_LASTN(1); assert((h >= 0 || CONST_STACK_LEN() < 1)); if (h >= 0 && ISBASICBLOCK(blocks, h, i-h+1) && fold_unaryops_on_constants(&codestr[i-3], consts, CONST_STACK_TOP())) { i -= 2; assert(codestr[i] == LOAD_CONST); CONST_STACK_POP(1); CONST_STACK_PUSH_OP(i); } break; /* Simplify conditional jump to conditional jump where the result of the first test implies the success of a similar test or the failure of the opposite test. Arises in code like: "if a and b:" "if a or b:" "a and b or c" "(a and b) and c" x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z --> x:JUMP_IF_FALSE_OR_POP z x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z --> x:POP_JUMP_IF_FALSE y+3 where y+3 is the instruction following the second test. */ case JUMP_IF_FALSE_OR_POP: case JUMP_IF_TRUE_OR_POP: tgt = GETJUMPTGT(codestr, i); j = codestr[tgt]; if (CONDITIONAL_JUMP(j)) { /* NOTE: all possible jumps here are absolute! */ if (JUMPS_ON_TRUE(j) == JUMPS_ON_TRUE(opcode)) { /* The second jump will be taken iff the first is. */ tgttgt = GETJUMPTGT(codestr, tgt); /* The current opcode inherits its target's stack behaviour */ codestr[i] = j; SETARG(codestr, i, tgttgt); goto reoptimize_current; } else { /* The second jump is not taken if the first is (so jump past it), and all conditional jumps pop their argument when they're not taken (so change the first jump to pop its argument when it's taken). */ if (JUMPS_ON_TRUE(opcode)) codestr[i] = POP_JUMP_IF_TRUE; else codestr[i] = POP_JUMP_IF_FALSE; SETARG(codestr, i, (tgt + 3)); goto reoptimize_current; } } /* Intentional fallthrough */ /* Replace jumps to unconditional jumps */ case POP_JUMP_IF_FALSE: case POP_JUMP_IF_TRUE: case FOR_ITER: case JUMP_FORWARD: case JUMP_ABSOLUTE: case CONTINUE_LOOP: case SETUP_LOOP: case SETUP_EXCEPT: case SETUP_FINALLY: case SETUP_WITH: tgt = GETJUMPTGT(codestr, i); /* Replace JUMP_* to a RETURN into just a RETURN */ if (UNCONDITIONAL_JUMP(opcode) && codestr[tgt] == RETURN_VALUE) { codestr[i] = RETURN_VALUE; memset(codestr+i+1, NOP, 2); continue; } if (!UNCONDITIONAL_JUMP(codestr[tgt])) continue; tgttgt = GETJUMPTGT(codestr, tgt); if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */ opcode = JUMP_ABSOLUTE; if (!ABSOLUTE_JUMP(opcode)) tgttgt -= i + 3; /* Calc relative jump addr */ if (tgttgt < 0) /* No backward relative jumps */ continue; codestr[i] = opcode; SETARG(codestr, i, tgttgt); break; case EXTENDED_ARG: if (codestr[i+3] != MAKE_FUNCTION) goto exitUnchanged; /* don't visit MAKE_FUNCTION as GETARG will be wrong */ i += 3; break; /* Replace RETURN LOAD_CONST None RETURN with just RETURN */ /* Remove unreachable JUMPs after RETURN */ case RETURN_VALUE: if (i+4 >= codelen) continue; if (codestr[i+4] == RETURN_VALUE && ISBASICBLOCK(blocks,i,5)) memset(codestr+i+1, NOP, 4); else if (UNCONDITIONAL_JUMP(codestr[i+1]) && ISBASICBLOCK(blocks,i,4)) memset(codestr+i+1, NOP, 3); break; } } /* Fixup linenotab */ for (i=0, nops=0 ; i<codelen ; i += CODESIZE(codestr[i])) { addrmap[i] = i - nops; if (codestr[i] == NOP) nops++; } cum_orig_line = 0; last_line = 0; for (i=0 ; i < tabsiz ; i+=2) { cum_orig_line += lineno[i]; new_line = addrmap[cum_orig_line]; assert (new_line - last_line < 255); lineno[i] =((unsigned char)(new_line - last_line)); last_line = new_line; } /* Remove NOPs and fixup jump targets */ for (i=0, h=0 ; i<codelen ; ) { opcode = codestr[i]; switch (opcode) { case NOP: i++; continue; case JUMP_ABSOLUTE: case CONTINUE_LOOP: case POP_JUMP_IF_FALSE: case POP_JUMP_IF_TRUE: case JUMP_IF_FALSE_OR_POP: case JUMP_IF_TRUE_OR_POP: j = addrmap[GETARG(codestr, i)]; SETARG(codestr, i, j); break; case FOR_ITER: case JUMP_FORWARD: case SETUP_LOOP: case SETUP_EXCEPT: case SETUP_FINALLY: case SETUP_WITH: j = addrmap[GETARG(codestr, i) + i + 3] - addrmap[i] - 3; SETARG(codestr, i, j); break; } adj = CODESIZE(opcode); while (adj--) codestr[h++] = codestr[i++]; } assert(h + nops == codelen); code = PyBytes_FromStringAndSize((char *)codestr, h); CONST_STACK_DELETE(); PyMem_Free(addrmap); PyMem_Free(codestr); PyMem_Free(blocks); return code; exitError: code = NULL; exitUnchanged: CONST_STACK_DELETE(); if (blocks != NULL) PyMem_Free(blocks); if (addrmap != NULL) PyMem_Free(addrmap); if (codestr != NULL) PyMem_Free(codestr); Py_XINCREF(code); return code; } /* Peephole optimizations for bytecode compiler. */ #include "Python.h" #include "Python-ast.h" #include "node.h" #include "ast.h" #include "code.h" #include "symtable.h" #include "opcode.h" #define GETARG(arr, i) ((int)((arr[i+2]<<8) + arr[i+1])) #define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD) #define CONDITIONAL_JUMP(op) (op==POP_JUMP_IF_FALSE || op==POP_JUMP_IF_TRUE \ || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP) #define ABSOLUTE_JUMP(op) (op==JUMP_ABSOLUTE || op==CONTINUE_LOOP \ || op==POP_JUMP_IF_FALSE || op==POP_JUMP_IF_TRUE \ || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP) #define JUMPS_ON_TRUE(op) (op==POP_JUMP_IF_TRUE || op==JUMP_IF_TRUE_OR_POP) #define GETJUMPTGT(arr, i) (GETARG(arr,i) + (ABSOLUTE_JUMP(arr[i]) ? 0 : i+3)) #define SETARG(arr, i, val) arr[i+2] = val>>8; arr[i+1] = val & 255 #define CODESIZE(op) (HAS_ARG(op) ? 3 : 1) #define ISBASICBLOCK(blocks, start, bytes) \ (blocks[start]==blocks[start+bytes-1]) #define CONST_STACK_CREATE() { \ const_stack_size = 256; \ const_stack = PyMem_New(PyObject *, const_stack_size); \ load_const_stack = PyMem_New(Py_ssize_t, const_stack_size); \ if (!const_stack || !load_const_stack) { \ PyErr_NoMemory(); \ goto exitError; \ } \ } #define CONST_STACK_DELETE() do { \ if (const_stack) \ PyMem_Free(const_stack); \ if (load_const_stack) \ PyMem_Free(load_const_stack); \ } while(0) #define CONST_STACK_LEN() (const_stack_top + 1) #define CONST_STACK_PUSH_OP(i) do { \ PyObject *_x; \ assert(codestr[i] == LOAD_CONST); \ assert(PyList_GET_SIZE(consts) > GETARG(codestr, i)); \ _x = PyList_GET_ITEM(consts, GETARG(codestr, i)); \ if (++const_stack_top >= const_stack_size) { \ const_stack_size *= 2; \ PyMem_Resize(const_stack, PyObject *, const_stack_size); \ PyMem_Resize(load_const_stack, Py_ssize_t, const_stack_size); \ if (!const_stack || !load_const_stack) { \ PyErr_NoMemory(); \ goto exitError; \ } \ } \ load_const_stack[const_stack_top] = i; \ const_stack[const_stack_top] = _x; \ in_consts = 1; \ } while(0) #define CONST_STACK_RESET() do { \ const_stack_top = -1; \ } while(0) #define CONST_STACK_TOP(x) \ const_stack[const_stack_top] #define CONST_STACK_LASTN(i) \ &const_stack[const_stack_top - i + 1] #define CONST_STACK_POP(i) do { \ assert(const_stack_top + 1 >= i); \ const_stack_top -= i; \ } while(0) #define CONST_STACK_OP_LASTN(i) \ ((const_stack_top >= i - 1) ? load_const_stack[const_stack_top - i + 1] : -1) /* Replace LOAD_CONST c1. LOAD_CONST c2 ... LOAD_CONST cn BUILD_TUPLE n with LOAD_CONST (c1, c2, ... cn). The consts table must still be in list form so that the new constant (c1, c2, ... cn) can be appended. Called with codestr pointing to the first LOAD_CONST. Bails out with no change if one or more of the LOAD_CONSTs is missing. Also works for BUILD_LIST and BUILT_SET when followed by an "in" or "not in" test; for BUILD_SET it assembles a frozenset rather than a tuple. */ static int tuple_of_constants(unsigned char *codestr, Py_ssize_t n, PyObject *consts, PyObject **objs) { PyObject *newconst, *constant; Py_ssize_t i, len_consts; /* Pre-conditions */ assert(PyList_CheckExact(consts)); /* Buildup new tuple of constants */ newconst = PyTuple_New(n); if (newconst == NULL) return 0; len_consts = PyList_GET_SIZE(consts); for (i=0 ; i<n ; i++) { constant = objs[i]; Py_INCREF(constant); PyTuple_SET_ITEM(newconst, i, constant); } /* If it's a BUILD_SET, use the PyTuple we just built to create a PyFrozenSet, and use that as the constant instead: */ if (codestr[0] == BUILD_SET) { PyObject *tuple = newconst; newconst = PyFrozenSet_New(tuple); Py_DECREF(tuple); if (newconst == NULL) return 0; } /* Append folded constant onto consts */ if (PyList_Append(consts, newconst)) { Py_DECREF(newconst); return 0; } Py_DECREF(newconst); /* Write NOPs over old LOAD_CONSTS and add a new LOAD_CONST newconst on top of the BUILD_TUPLE n */ codestr[0] = LOAD_CONST; SETARG(codestr, 0, len_consts); return 1; } /* Replace LOAD_CONST c1. LOAD_CONST c2 BINOP with LOAD_CONST binop(c1,c2) The consts table must still be in list form so that the new constant can be appended. Called with codestr pointing to the BINOP. Abandons the transformation if the folding fails (i.e. 1+'a'). If the new constant is a sequence, only folds when the size is below a threshold value. That keeps pyc files from becoming large in the presence of code like: (None,)*1000. */ static int fold_binops_on_constants(unsigned char *codestr, PyObject *consts, PyObject **objs) { PyObject *newconst, *v, *w; Py_ssize_t len_consts, size; int opcode; /* Pre-conditions */ assert(PyList_CheckExact(consts)); /* Create new constant */ v = objs[0]; w = objs[1]; opcode = codestr[0]; switch (opcode) { case BINARY_POWER: newconst = PyNumber_Power(v, w, Py_None); break; case BINARY_MULTIPLY: newconst = PyNumber_Multiply(v, w); break; case BINARY_TRUE_DIVIDE: newconst = PyNumber_TrueDivide(v, w); break; case BINARY_FLOOR_DIVIDE: newconst = PyNumber_FloorDivide(v, w); break; case BINARY_MODULO: newconst = PyNumber_Remainder(v, w); break; case BINARY_ADD: newconst = PyNumber_Add(v, w); break; case BINARY_SUBTRACT: newconst = PyNumber_Subtract(v, w); break; case BINARY_SUBSCR: newconst = PyObject_GetItem(v, w); /* #5057: if v is unicode, there might be differences between wide and narrow builds in cases like '\U00012345'[0]. Wide builds will return a non-BMP char, whereas narrow builds will return a surrogate. In both the cases skip the optimization in order to produce compatible pycs. */ if (newconst != NULL && PyUnicode_Check(v) && PyUnicode_Check(newconst)) { Py_UNICODE ch = PyUnicode_AS_UNICODE(newconst)[0]; #ifdef Py_UNICODE_WIDE if (ch > 0xFFFF) { #else if (ch >= 0xD800 && ch <= 0xDFFF) { #endif Py_DECREF(newconst); return 0; } } break; case BINARY_LSHIFT: newconst = PyNumber_Lshift(v, w); break; case BINARY_RSHIFT: newconst = PyNumber_Rshift(v, w); break; case BINARY_AND: newconst = PyNumber_And(v, w); break; case BINARY_XOR: newconst = PyNumber_Xor(v, w); break; case BINARY_OR: newconst = PyNumber_Or(v, w); break; default: /* Called with an unknown opcode */ PyErr_Format(PyExc_SystemError, "unexpected binary operation %d on a constant", opcode); return 0; } if (newconst == NULL) { if(!PyErr_ExceptionMatches(PyExc_KeyboardInterrupt)) PyErr_Clear(); return 0; } size = PyObject_Size(newconst); if (size == -1) { if (PyErr_ExceptionMatches(PyExc_KeyboardInterrupt)) return 0; PyErr_Clear(); } else if (size > 20) { Py_DECREF(newconst); return 0; } /* Append folded constant into consts table */ len_consts = PyList_GET_SIZE(consts); if (PyList_Append(consts, newconst)) { Py_DECREF(newconst); return 0; } Py_DECREF(newconst); /* Write NOP NOP NOP NOP LOAD_CONST newconst */ codestr[-2] = LOAD_CONST; SETARG(codestr, -2, len_consts); return 1; } static int fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts, PyObject *v) { PyObject *newconst; Py_ssize_t len_consts; int opcode; /* Pre-conditions */ assert(PyList_CheckExact(consts)); assert(codestr[0] == LOAD_CONST); /* Create new constant */ opcode = codestr[3]; switch (opcode) { case UNARY_NEGATIVE: newconst = PyNumber_Negative(v); break; case UNARY_INVERT: newconst = PyNumber_Invert(v); break; case UNARY_POSITIVE: newconst = PyNumber_Positive(v); break; default: /* Called with an unknown opcode */ PyErr_Format(PyExc_SystemError, "unexpected unary operation %d on a constant", opcode); return 0; } if (newconst == NULL) { if(!PyErr_ExceptionMatches(PyExc_KeyboardInterrupt)) PyErr_Clear(); return 0; } /* Append folded constant into consts table */ len_consts = PyList_GET_SIZE(consts); if (PyList_Append(consts, newconst)) { Py_DECREF(newconst); return 0; } Py_DECREF(newconst); /* Write NOP LOAD_CONST newconst */ codestr[0] = NOP; codestr[1] = LOAD_CONST; SETARG(codestr, 1, len_consts); return 1; } static unsigned int * markblocks(unsigned char *code, Py_ssize_t len) { unsigned int *blocks = (unsigned int *)PyMem_Malloc(len*sizeof(int)); int i,j, opcode, blockcnt = 0; if (blocks == NULL) { PyErr_NoMemory(); return NULL; } memset(blocks, 0, len*sizeof(int)); /* Mark labels in the first pass */ for (i=0 ; i<len ; i+=CODESIZE(opcode)) { opcode = code[i]; switch (opcode) { case FOR_ITER: case JUMP_FORWARD: case JUMP_IF_FALSE_OR_POP: case JUMP_IF_TRUE_OR_POP: case POP_JUMP_IF_FALSE: case POP_JUMP_IF_TRUE: case JUMP_ABSOLUTE: case CONTINUE_LOOP: case SETUP_LOOP: case SETUP_EXCEPT: case SETUP_FINALLY: case SETUP_WITH: j = GETJUMPTGT(code, i); blocks[j] = 1; break; } } /* Build block numbers in the second pass */ for (i=0 ; i<len ; i++) { blockcnt += blocks[i]; /* increment blockcnt over labels */ blocks[i] = blockcnt; } return blocks; } /* Helper to replace LOAD_NAME None/True/False with LOAD_CONST Returns: 0 if no change, 1 if change, -1 if error */ static int load_global(unsigned char *codestr, Py_ssize_t i, char *name, PyObject *consts) { Py_ssize_t j; PyObject *obj; if (name == NULL) return 0; if (strcmp(name, "None") == 0) obj = Py_None; else if (strcmp(name, "True") == 0) obj = Py_True; else if (strcmp(name, "False") == 0) obj = Py_False; else return 0; for (j = 0; j < PyList_GET_SIZE(consts); j++) { if (PyList_GET_ITEM(consts, j) == obj) break; } if (j == PyList_GET_SIZE(consts)) { if (PyList_Append(consts, obj) < 0) return -1; } assert(PyList_GET_ITEM(consts, j) == obj); codestr[i] = LOAD_CONST; SETARG(codestr, i, j); return 1; } /* Perform basic peephole optimizations to components of a code object. The consts object should still be in list form to allow new constants to be appended. To keep the optimizer simple, it bails out (does nothing) for code that has a length over 32,700, and does not calculate extended arguments. That allows us to avoid overflow and sign issues. Likewise, it bails when the lineno table has complex encoding for gaps >= 255. EXTENDED_ARG can appear before MAKE_FUNCTION; in this case both opcodes are skipped. EXTENDED_ARG preceding any other opcode causes the optimizer to bail. Optimizations are restricted to simple transformations occuring within a single basic block. All transformations keep the code size the same or smaller. For those that reduce size, the gaps are initially filled with NOPs. Later those NOPs are removed and the jump addresses retargeted in a single pass. Line numbering is adjusted accordingly. */ PyObject * PyCode_Optimize(PyObject *code, PyObject* consts, PyObject *names, PyObject *lineno_obj) { Py_ssize_t i, j, codelen; int nops, h, adj; int tgt, tgttgt, opcode; unsigned char *codestr = NULL; unsigned char *lineno; int *addrmap = NULL; int new_line, cum_orig_line, last_line, tabsiz; PyObject **const_stack = NULL; Py_ssize_t *load_const_stack = NULL; Py_ssize_t const_stack_top = -1; Py_ssize_t const_stack_size = 0; int in_consts = 0; /* whether we are in a LOAD_CONST sequence */ unsigned int *blocks = NULL; char *name; /* Bail out if an exception is set */ if (PyErr_Occurred()) goto exitError; /* Bypass optimization when the lineno table is too complex */ assert(PyBytes_Check(lineno_obj)); lineno = (unsigned char*)PyBytes_AS_STRING(lineno_obj); tabsiz = PyBytes_GET_SIZE(lineno_obj); if (memchr(lineno, 255, tabsiz) != NULL) goto exitUnchanged; /* Avoid situations where jump retargeting could overflow */ assert(PyBytes_Check(code)); codelen = PyBytes_GET_SIZE(code); if (codelen > 32700) goto exitUnchanged; /* Make a modifiable copy of the code string */ codestr = (unsigned char *)PyMem_Malloc(codelen); if (codestr == NULL) goto exitError; codestr = (unsigned char *)memcpy(codestr, PyBytes_AS_STRING(code), codelen); /* Verify that RETURN_VALUE terminates the codestring. This allows the various transformation patterns to look ahead several instructions without additional checks to make sure they are not looking beyond the end of the code string. */ if (codestr[codelen-1] != RETURN_VALUE) goto exitUnchanged; /* Mapping to new jump targets after NOPs are removed */ addrmap = (int *)PyMem_Malloc(codelen * sizeof(int)); if (addrmap == NULL) goto exitError; blocks = markblocks(codestr, codelen); if (blocks == NULL) goto exitError; assert(PyList_Check(consts)); CONST_STACK_CREATE(); for (i=0 ; i<codelen ; i += CODESIZE(codestr[i])) { reoptimize_current: opcode = codestr[i]; if (!in_consts) { CONST_STACK_RESET(); } in_consts = 0; switch (opcode) { /* Replace UNARY_NOT POP_JUMP_IF_FALSE with POP_JUMP_IF_TRUE */ case UNARY_NOT: if (codestr[i+1] != POP_JUMP_IF_FALSE || !ISBASICBLOCK(blocks,i,4)) continue; j = GETARG(codestr, i+1); codestr[i] = POP_JUMP_IF_TRUE; SETARG(codestr, i, j); codestr[i+3] = NOP; goto reoptimize_current; /* not a is b --> a is not b not a in b --> a not in b not a is not b --> a is b not a not in b --> a in b */ case COMPARE_OP: j = GETARG(codestr, i); if (j < 6 || j > 9 || codestr[i+3] != UNARY_NOT || !ISBASICBLOCK(blocks,i,4)) continue; SETARG(codestr, i, (j^1)); codestr[i+3] = NOP; break; /* Replace LOAD_GLOBAL/LOAD_NAME None/True/False with LOAD_CONST None/True/False */ case LOAD_NAME: case LOAD_GLOBAL: j = GETARG(codestr, i); name = _PyUnicode_AsString(PyTuple_GET_ITEM(names, j)); h = load_global(codestr, i, name, consts); if (h < 0) goto exitError; else if (h == 0) continue; CONST_STACK_PUSH_OP(i); break; /* Skip over LOAD_CONST trueconst POP_JUMP_IF_FALSE xx. This improves "while 1" performance. */ case LOAD_CONST: CONST_STACK_PUSH_OP(i); j = GETARG(codestr, i); if (codestr[i+3] != POP_JUMP_IF_FALSE || !ISBASICBLOCK(blocks,i,6) || !PyObject_IsTrue(PyList_GET_ITEM(consts, j))) continue; memset(codestr+i, NOP, 6); CONST_STACK_RESET(); break; /* Try to fold tuples of constants (includes a case for lists and sets which are only used for "in" and "not in" tests). Skip over BUILD_SEQN 1 UNPACK_SEQN 1. Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2. Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */ case BUILD_TUPLE: case BUILD_LIST: case BUILD_SET: j = GETARG(codestr, i); if (j == 0) break; h = CONST_STACK_OP_LASTN(j); assert((h >= 0 || CONST_STACK_LEN() < j)); if (h >= 0 && j > 0 && j <= CONST_STACK_LEN() && ((opcode == BUILD_TUPLE && ISBASICBLOCK(blocks, h, i-h+3)) || ((opcode == BUILD_LIST || opcode == BUILD_SET) && codestr[i+3]==COMPARE_OP && ISBASICBLOCK(blocks, h, i-h+6) && (GETARG(codestr,i+3)==6 || GETARG(codestr,i+3)==7))) && tuple_of_constants(&codestr[i], j, consts, CONST_STACK_LASTN(j))) { assert(codestr[i] == LOAD_CONST); memset(&codestr[h], NOP, i - h); CONST_STACK_POP(j); CONST_STACK_PUSH_OP(i); break; } if (codestr[i+3] != UNPACK_SEQUENCE || !ISBASICBLOCK(blocks,i,6) || j != GETARG(codestr, i+3) || opcode == BUILD_SET) continue; if (j == 1) { memset(codestr+i, NOP, 6); } else if (j == 2) { codestr[i] = ROT_TWO; memset(codestr+i+1, NOP, 5); CONST_STACK_RESET(); } else if (j == 3) { codestr[i] = ROT_THREE; codestr[i+1] = ROT_TWO; memset(codestr+i+2, NOP, 4); CONST_STACK_RESET(); } break; /* Fold binary ops on constants. LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */ case BINARY_POWER: case BINARY_MULTIPLY: case BINARY_TRUE_DIVIDE: case BINARY_FLOOR_DIVIDE: case BINARY_MODULO: case BINARY_ADD: case BINARY_SUBTRACT: case BINARY_SUBSCR: case BINARY_LSHIFT: case BINARY_RSHIFT: case BINARY_AND: case BINARY_XOR: case BINARY_OR: /* NOTE: LOAD_CONST is saved at `i-2` since it has an arg while BINOP hasn't */ h = CONST_STACK_OP_LASTN(2); assert((h >= 0 || CONST_STACK_LEN() < 2)); if (h >= 0 && ISBASICBLOCK(blocks, h, i-h+1) && fold_binops_on_constants(&codestr[i], consts, CONST_STACK_LASTN(2))) { i -= 2; memset(&codestr[h], NOP, i - h); assert(codestr[i] == LOAD_CONST); CONST_STACK_POP(2); CONST_STACK_PUSH_OP(i); } break; /* Fold unary ops on constants. LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */ case UNARY_NEGATIVE: case UNARY_INVERT: case UNARY_POSITIVE: h = CONST_STACK_OP_LASTN(1); assert((h >= 0 || CONST_STACK_LEN() < 1)); if (h >= 0 && ISBASICBLOCK(blocks, h, i-h+1) && fold_unaryops_on_constants(&codestr[i-3], consts, CONST_STACK_TOP())) { i -= 2; assert(codestr[i] == LOAD_CONST); CONST_STACK_POP(1); CONST_STACK_PUSH_OP(i); } break; /* Simplify conditional jump to conditional jump where the result of the first test implies the success of a similar test or the failure of the opposite test. Arises in code like: "if a and b:" "if a or b:" "a and b or c" "(a and b) and c" x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z --> x:JUMP_IF_FALSE_OR_POP z x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z --> x:POP_JUMP_IF_FALSE y+3 where y+3 is the instruction following the second test. */ case JUMP_IF_FALSE_OR_POP: case JUMP_IF_TRUE_OR_POP: tgt = GETJUMPTGT(codestr, i); j = codestr[tgt]; if (CONDITIONAL_JUMP(j)) { /* NOTE: all possible jumps here are absolute! */ if (JUMPS_ON_TRUE(j) == JUMPS_ON_TRUE(opcode)) { /* The second jump will be taken iff the first is. */ tgttgt = GETJUMPTGT(codestr, tgt); /* The current opcode inherits its target's stack behaviour */ codestr[i] = j; SETARG(codestr, i, tgttgt); goto reoptimize_current; } else { /* The second jump is not taken if the first is (so jump past it), and all conditional jumps pop their argument when they're not taken (so change the first jump to pop its argument when it's taken). */ if (JUMPS_ON_TRUE(opcode)) codestr[i] = POP_JUMP_IF_TRUE; else codestr[i] = POP_JUMP_IF_FALSE; SETARG(codestr, i, (tgt + 3)); goto reoptimize_current; } } /* Intentional fallthrough */ /* Replace jumps to unconditional jumps */ case POP_JUMP_IF_FALSE: case POP_JUMP_IF_TRUE: case FOR_ITER: case JUMP_FORWARD: case JUMP_ABSOLUTE: case CONTINUE_LOOP: case SETUP_LOOP: case SETUP_EXCEPT: case SETUP_FINALLY: case SETUP_WITH: tgt = GETJUMPTGT(codestr, i); /* Replace JUMP_* to a RETURN into just a RETURN */ if (UNCONDITIONAL_JUMP(opcode) && codestr[tgt] == RETURN_VALUE) { codestr[i] = RETURN_VALUE; memset(codestr+i+1, NOP, 2); continue; } if (!UNCONDITIONAL_JUMP(codestr[tgt])) continue; tgttgt = GETJUMPTGT(codestr, tgt); if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */ opcode = JUMP_ABSOLUTE; if (!ABSOLUTE_JUMP(opcode)) tgttgt -= i + 3; /* Calc relative jump addr */ if (tgttgt < 0) /* No backward relative jumps */ continue; codestr[i] = opcode; SETARG(codestr, i, tgttgt); break; case EXTENDED_ARG: if (codestr[i+3] != MAKE_FUNCTION) goto exitUnchanged; /* don't visit MAKE_FUNCTION as GETARG will be wrong */ i += 3; break; /* Replace RETURN LOAD_CONST None RETURN with just RETURN */ /* Remove unreachable JUMPs after RETURN */ case RETURN_VALUE: if (i+4 >= codelen) continue; if (codestr[i+4] == RETURN_VALUE && ISBASICBLOCK(blocks,i,5)) memset(codestr+i+1, NOP, 4); else if (UNCONDITIONAL_JUMP(codestr[i+1]) && ISBASICBLOCK(blocks,i,4)) memset(codestr+i+1, NOP, 3); break; } } /* Fixup linenotab */ for (i=0, nops=0 ; i<codelen ; i += CODESIZE(codestr[i])) { addrmap[i] = i - nops; if (codestr[i] == NOP) nops++; } cum_orig_line = 0; last_line = 0; for (i=0 ; i < tabsiz ; i+=2) { cum_orig_line += lineno[i]; new_line = addrmap[cum_orig_line]; assert (new_line - last_line < 255); lineno[i] =((unsigned char)(new_line - last_line)); last_line = new_line; } /* Remove NOPs and fixup jump targets */ for (i=0, h=0 ; i<codelen ; ) { opcode = codestr[i]; switch (opcode) { case NOP: i++; continue; case JUMP_ABSOLUTE: case CONTINUE_LOOP: case POP_JUMP_IF_FALSE: case POP_JUMP_IF_TRUE: case JUMP_IF_FALSE_OR_POP: case JUMP_IF_TRUE_OR_POP: j = addrmap[GETARG(codestr, i)]; SETARG(codestr, i, j); break; case FOR_ITER: case JUMP_FORWARD: case SETUP_LOOP: case SETUP_EXCEPT: case SETUP_FINALLY: case SETUP_WITH: j = addrmap[GETARG(codestr, i) + i + 3] - addrmap[i] - 3; SETARG(codestr, i, j); break; } adj = CODESIZE(opcode); while (adj--) codestr[h++] = codestr[i++]; } assert(h + nops == codelen); code = PyBytes_FromStringAndSize((char *)codestr, h); CONST_STACK_DELETE(); PyMem_Free(addrmap); PyMem_Free(codestr); PyMem_Free(blocks); return code; exitError: code = NULL; exitUnchanged: CONST_STACK_DELETE(); if (blocks != NULL) PyMem_Free(blocks); if (addrmap != NULL) PyMem_Free(addrmap); if (codestr != NULL) PyMem_Free(codestr); Py_XINCREF(code); return code; }
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/python_69368-69372.c
manybugs_data_14
/* This file is part of drd, a thread error detector. Copyright (C) 2006-2011 Bart Van Assche <[email protected]>. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. The GNU General Public License is contained in the file COPYING. */ #include "drd_bitmap.h" #include "drd_thread_bitmap.h" #include "drd_vc.h" /* DRD_(vc_snprint)() */ /* Include several source files here in order to allow the compiler to */ /* do more inlining. */ #include "drd_bitmap.c" #include "drd_load_store.h" #include "drd_segment.c" #include "drd_thread.c" #include "drd_vc.c" #include "libvex_guest_offsets.h" /* STACK_POINTER_OFFSET: VEX register offset for the stack pointer register. */ #if defined(VGA_x86) #define STACK_POINTER_OFFSET OFFSET_x86_ESP #elif defined(VGA_amd64) #define STACK_POINTER_OFFSET OFFSET_amd64_RSP #elif defined(VGA_ppc32) #define STACK_POINTER_OFFSET OFFSET_ppc32_GPR1 #elif defined(VGA_ppc64) #define STACK_POINTER_OFFSET OFFSET_ppc64_GPR1 #elif defined(VGA_arm) #define STACK_POINTER_OFFSET OFFSET_arm_R13 #elif defined(VGA_s390x) #define STACK_POINTER_OFFSET OFFSET_s390x_r15 #else #error Unknown architecture. #endif /* Local variables. */ static Bool s_check_stack_accesses = False; static Bool s_first_race_only = False; /* Function definitions. */ Bool DRD_(get_check_stack_accesses)() { return s_check_stack_accesses; } void DRD_(set_check_stack_accesses)(const Bool c) { tl_assert(c == False || c == True); s_check_stack_accesses = c; } Bool DRD_(get_first_race_only)() { return s_first_race_only; } void DRD_(set_first_race_only)(const Bool fro) { tl_assert(fro == False || fro == True); s_first_race_only = fro; } void DRD_(trace_mem_access)(const Addr addr, const SizeT size, const BmAccessTypeT access_type, const HWord stored_value_hi, const HWord stored_value_lo) { if (DRD_(is_any_traced)(addr, addr + size)) { char* vc; vc = DRD_(vc_aprint)(DRD_(thread_get_vc)(DRD_(thread_get_running_tid)())); if (access_type == eStore && size <= sizeof(HWord)) { DRD_(trace_msg_w_bt)("store 0x%lx size %ld val %ld/0x%lx (thread %d /" " vc %s)", addr, size, stored_value_lo, stored_value_lo, DRD_(thread_get_running_tid)(), vc); } else if (access_type == eStore && size > sizeof(HWord)) { ULong sv; tl_assert(sizeof(HWord) == 4); sv = ((ULong)stored_value_hi << 32) | stored_value_lo; DRD_(trace_msg_w_bt)("store 0x%lx size %ld val %lld/0x%llx (thread %d" " / vc %s)", addr, size, sv, sv, DRD_(thread_get_running_tid)(), vc); } else { DRD_(trace_msg_w_bt)("%s 0x%lx size %ld (thread %d / vc %s)", access_type == eLoad ? "load " : access_type == eStore ? "store" : access_type == eStart ? "start" : access_type == eEnd ? "end " : "????", addr, size, DRD_(thread_get_running_tid)(), vc); } VG_(free)(vc); tl_assert(DRD_(DrdThreadIdToVgThreadId)(DRD_(thread_get_running_tid)()) == VG_(get_running_tid)()); } } static VG_REGPARM(2) void drd_trace_mem_load(const Addr addr, const SizeT size) { return DRD_(trace_mem_access)(addr, size, eLoad, 0, 0); } static VG_REGPARM(3) void drd_trace_mem_store(const Addr addr,const SizeT size, const HWord stored_value_hi, const HWord stored_value_lo) { return DRD_(trace_mem_access)(addr, size, eStore, stored_value_hi, stored_value_lo); } static void drd_report_race(const Addr addr, const SizeT size, const BmAccessTypeT access_type) { ThreadId vg_tid; vg_tid = VG_(get_running_tid)(); if (DRD_(thread_address_on_any_stack)(addr)) { #if 0 GenericErrInfo GEI = { .tid = DRD_(thread_get_running_tid)(), .addr = addr, }; VG_(maybe_record_error)(vg_tid, GenericErr, VG_(get_IP)(vg_tid), "--check-stack-var=no skips checking stack" " variables shared over threads", &GEI); #endif } else { DataRaceErrInfo drei = { .tid = DRD_(thread_get_running_tid)(), .addr = addr, .size = size, .access_type = access_type, }; VG_(maybe_record_error)(vg_tid, DataRaceErr, VG_(get_IP)(vg_tid), "Conflicting access", &drei); if (s_first_race_only) DRD_(start_suppression)(addr, addr + size, "first race only"); } } VG_REGPARM(2) void DRD_(trace_load)(Addr addr, SizeT size) { #ifdef ENABLE_DRD_CONSISTENCY_CHECKS /* The assert below has been commented out because of performance reasons.*/ tl_assert(DRD_(thread_get_running_tid)() == DRD_(VgThreadIdToDrdThreadId)(VG_(get_running_tid()))); #endif if (DRD_(running_thread_is_recording_loads)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_load_triggers_conflict(addr, addr + size) && ! DRD_(is_suppressed)(addr, addr + size)) { drd_report_race(addr, size, eLoad); } } static VG_REGPARM(1) void drd_trace_load_1(Addr addr) { if (DRD_(running_thread_is_recording_loads)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_load_1_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 1)) { drd_report_race(addr, 1, eLoad); } } static VG_REGPARM(1) void drd_trace_load_2(Addr addr) { if (DRD_(running_thread_is_recording_loads)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_load_2_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 2)) { drd_report_race(addr, 2, eLoad); } } static VG_REGPARM(1) void drd_trace_load_4(Addr addr) { if (DRD_(running_thread_is_recording_loads)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_load_4_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 4)) { drd_report_race(addr, 4, eLoad); } } static VG_REGPARM(1) void drd_trace_load_8(Addr addr) { if (DRD_(running_thread_is_recording_loads)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_load_8_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 8)) { drd_report_race(addr, 8, eLoad); } } VG_REGPARM(2) void DRD_(trace_store)(Addr addr, SizeT size) { #ifdef ENABLE_DRD_CONSISTENCY_CHECKS /* The assert below has been commented out because of performance reasons.*/ tl_assert(DRD_(thread_get_running_tid)() == DRD_(VgThreadIdToDrdThreadId)(VG_(get_running_tid()))); #endif if (DRD_(running_thread_is_recording_stores)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_store_triggers_conflict(addr, addr + size) && ! DRD_(is_suppressed)(addr, addr + size)) { drd_report_race(addr, size, eStore); } } static VG_REGPARM(1) void drd_trace_store_1(Addr addr) { if (DRD_(running_thread_is_recording_stores)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_store_1_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 1)) { drd_report_race(addr, 1, eStore); } } static VG_REGPARM(1) void drd_trace_store_2(Addr addr) { if (DRD_(running_thread_is_recording_stores)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_store_2_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 2)) { drd_report_race(addr, 2, eStore); } } static VG_REGPARM(1) void drd_trace_store_4(Addr addr) { if (DRD_(running_thread_is_recording_stores)() && (s_check_stack_accesses || !DRD_(thread_address_on_stack)(addr)) && bm_access_store_4_triggers_conflict(addr) && !DRD_(is_suppressed)(addr, addr + 4)) { drd_report_race(addr, 4, eStore); } } static VG_REGPARM(1) void drd_trace_store_8(Addr addr) { if (DRD_(running_thread_is_recording_stores)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_store_8_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 8)) { drd_report_race(addr, 8, eStore); } } /** * Return true if and only if addr_expr matches the pattern (SP) or * <offset>(SP). */ static Bool is_stack_access(IRSB* const bb, IRExpr* const addr_expr) { Bool result = False; if (addr_expr->tag == Iex_RdTmp) { int i; for (i = 0; i < bb->stmts_size; i++) { if (bb->stmts[i] && bb->stmts[i]->tag == Ist_WrTmp && bb->stmts[i]->Ist.WrTmp.tmp == addr_expr->Iex.RdTmp.tmp) { IRExpr* e = bb->stmts[i]->Ist.WrTmp.data; if (e->tag == Iex_Get && e->Iex.Get.offset == STACK_POINTER_OFFSET) { result = True; } //ppIRExpr(e); //VG_(printf)(" (%s)\n", result ? "True" : "False"); break; } } } return result; } static const IROp u_widen_irop[5][9] = { [Ity_I1 - Ity_I1] = { [4] = Iop_1Uto32, [8] = Iop_1Uto64 }, [Ity_I8 - Ity_I1] = { [4] = Iop_8Uto32, [8] = Iop_8Uto64 }, [Ity_I16 - Ity_I1] = { [4] = Iop_16Uto32, [8] = Iop_16Uto64 }, [Ity_I32 - Ity_I1] = { [8] = Iop_32Uto64 }, }; /** * Instrument the client code to trace a memory load (--trace-addr). */ static IRExpr* instr_trace_mem_load(IRSB* const bb, IRExpr* addr_expr, const HWord size) { IRTemp tmp; tmp = newIRTemp(bb->tyenv, typeOfIRExpr(bb->tyenv, addr_expr)); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, addr_expr)); addr_expr = IRExpr_RdTmp(tmp); addStmtToIRSB(bb, IRStmt_Dirty( unsafeIRDirty_0_N(/*regparms*/2, "drd_trace_mem_load", VG_(fnptr_to_fnentry) (drd_trace_mem_load), mkIRExprVec_2(addr_expr, mkIRExpr_HWord(size))))); return addr_expr; } /** * Instrument the client code to trace a memory store (--trace-addr). */ static void instr_trace_mem_store(IRSB* const bb, IRExpr* const addr_expr, IRExpr* data_expr_hi, IRExpr* data_expr_lo) { IRType ty_data_expr; HWord size; tl_assert(sizeof(HWord) == 4 || sizeof(HWord) == 8); tl_assert(!data_expr_hi || typeOfIRExpr(bb->tyenv, data_expr_hi) == Ity_I32); ty_data_expr = typeOfIRExpr(bb->tyenv, data_expr_lo); size = sizeofIRType(ty_data_expr); #if 0 // Test code if (ty_data_expr == Ity_I32) { IRTemp tmp = newIRTemp(bb->tyenv, Ity_F32); data_expr_lo = IRExpr_Unop(Iop_ReinterpI32asF32, data_expr_lo); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, data_expr_lo)); data_expr_lo = IRExpr_RdTmp(tmp); ty_data_expr = Ity_F32; } else if (ty_data_expr == Ity_I64) { IRTemp tmp = newIRTemp(bb->tyenv, Ity_F64); data_expr_lo = IRExpr_Unop(Iop_ReinterpI64asF64, data_expr_lo); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, data_expr_lo)); data_expr_lo = IRExpr_RdTmp(tmp); ty_data_expr = Ity_F64; } #endif if (ty_data_expr == Ity_F32) { IRTemp tmp = newIRTemp(bb->tyenv, Ity_I32); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, IRExpr_Unop(Iop_ReinterpF32asI32, data_expr_lo))); data_expr_lo = IRExpr_RdTmp(tmp); ty_data_expr = Ity_I32; } else if (ty_data_expr == Ity_F64) { IRTemp tmp = newIRTemp(bb->tyenv, Ity_I64); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, IRExpr_Unop(Iop_ReinterpF64asI64, data_expr_lo))); data_expr_lo = IRExpr_RdTmp(tmp); ty_data_expr = Ity_I64; } if (size == sizeof(HWord) && (ty_data_expr == Ity_I32 || ty_data_expr == Ity_I64)) { /* No conversion necessary */ } else { IROp widen_op; if (Ity_I1 <= ty_data_expr && ty_data_expr < Ity_I1 + sizeof(u_widen_irop)/sizeof(u_widen_irop[0])) { widen_op = u_widen_irop[ty_data_expr - Ity_I1][sizeof(HWord)]; if (!widen_op) widen_op = Iop_INVALID; } else { widen_op = Iop_INVALID; } if (widen_op != Iop_INVALID) { IRTemp tmp; /* Widen the integer expression to a HWord */ tmp = newIRTemp(bb->tyenv, sizeof(HWord) == 4 ? Ity_I32 : Ity_I64); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, IRExpr_Unop(widen_op, data_expr_lo))); data_expr_lo = IRExpr_RdTmp(tmp); } else if (size > sizeof(HWord) && !data_expr_hi && ty_data_expr == Ity_I64) { IRTemp tmp; tl_assert(sizeof(HWord) == 4); tl_assert(size == 8); tmp = newIRTemp(bb->tyenv, Ity_I32); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, IRExpr_Unop(Iop_64HIto32, data_expr_lo))); data_expr_hi = IRExpr_RdTmp(tmp); tmp = newIRTemp(bb->tyenv, Ity_I32); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, IRExpr_Unop(Iop_64to32, data_expr_lo))); data_expr_lo = IRExpr_RdTmp(tmp); } else { data_expr_lo = mkIRExpr_HWord(0); } } addStmtToIRSB(bb, IRStmt_Dirty( unsafeIRDirty_0_N(/*regparms*/3, "drd_trace_mem_store", VG_(fnptr_to_fnentry)(drd_trace_mem_store), mkIRExprVec_4(addr_expr, mkIRExpr_HWord(size), data_expr_hi ? data_expr_hi : mkIRExpr_HWord(0), data_expr_lo)))); } static void instrument_load(IRSB* const bb, IRExpr* const addr_expr, const HWord size) { IRExpr* size_expr; IRExpr** argv; IRDirty* di; if (!s_check_stack_accesses && is_stack_access(bb, addr_expr)) return; switch (size) { case 1: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_load_1", VG_(fnptr_to_fnentry)(drd_trace_load_1), argv); break; case 2: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_load_2", VG_(fnptr_to_fnentry)(drd_trace_load_2), argv); break; case 4: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_load_4", VG_(fnptr_to_fnentry)(drd_trace_load_4), argv); break; case 8: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_load_8", VG_(fnptr_to_fnentry)(drd_trace_load_8), argv); break; default: size_expr = mkIRExpr_HWord(size); argv = mkIRExprVec_2(addr_expr, size_expr); di = unsafeIRDirty_0_N(/*regparms*/2, "drd_trace_load", VG_(fnptr_to_fnentry)(DRD_(trace_load)), argv); break; } addStmtToIRSB(bb, IRStmt_Dirty(di)); } static void instrument_store(IRSB* const bb, IRExpr* addr_expr, IRExpr* const data_expr) { IRExpr* size_expr; IRExpr** argv; IRDirty* di; HWord size; size = sizeofIRType(typeOfIRExpr(bb->tyenv, data_expr)); if (UNLIKELY(DRD_(any_address_is_traced)())) { IRTemp tmp = newIRTemp(bb->tyenv, typeOfIRExpr(bb->tyenv, addr_expr)); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, addr_expr)); addr_expr = IRExpr_RdTmp(tmp); instr_trace_mem_store(bb, addr_expr, NULL, data_expr); } if (!s_check_stack_accesses && is_stack_access(bb, addr_expr)) return; switch (size) { case 1: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_store_1", VG_(fnptr_to_fnentry)(drd_trace_store_1), argv); break; case 2: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_store_2", VG_(fnptr_to_fnentry)(drd_trace_store_2), argv); break; case 4: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_store_4", VG_(fnptr_to_fnentry)(drd_trace_store_4), argv); break; case 8: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_store_8", VG_(fnptr_to_fnentry)(drd_trace_store_8), argv); break; default: size_expr = mkIRExpr_HWord(size); argv = mkIRExprVec_2(addr_expr, size_expr); di = unsafeIRDirty_0_N(/*regparms*/2, "drd_trace_store", VG_(fnptr_to_fnentry)(DRD_(trace_store)), argv); break; } addStmtToIRSB(bb, IRStmt_Dirty(di)); } IRSB* DRD_(instrument)(VgCallbackClosure* const closure, IRSB* const bb_in, VexGuestLayout* const layout, VexGuestExtents* const vge, IRType const gWordTy, IRType const hWordTy) { IRDirty* di; Int i; IRSB* bb; IRExpr** argv; Bool instrument = True; /* Set up BB */ bb = emptyIRSB(); bb->tyenv = deepCopyIRTypeEnv(bb_in->tyenv); bb->next = deepCopyIRExpr(bb_in->next); bb->jumpkind = bb_in->jumpkind; for (i = 0; i < bb_in->stmts_used; i++) { IRStmt* const st = bb_in->stmts[i]; tl_assert(st); tl_assert(isFlatIRStmt(st)); switch (st->tag) { /* Note: the code for not instrumenting the code in .plt */ /* sections is only necessary on CentOS 3.0 x86 (kernel 2.4.21 */ /* + glibc 2.3.2 + NPTL 0.60 + binutils 2.14.90.0.4). */ /* This is because on this platform dynamic library symbols are */ /* relocated in another way than by later binutils versions. The */ /* linker e.g. does not generate .got.plt sections on CentOS 3.0. */ case Ist_IMark: instrument = VG_(DebugInfo_sect_kind)(NULL, 0, st->Ist.IMark.addr) != Vg_SectPLT; addStmtToIRSB(bb, st); break; case Ist_MBE: switch (st->Ist.MBE.event) { case Imbe_Fence: break; /* not interesting */ default: tl_assert(0); } addStmtToIRSB(bb, st); break; case Ist_Store: if (instrument) instrument_store(bb, st->Ist.Store.addr, st->Ist.Store.data); addStmtToIRSB(bb, st); break; case Ist_WrTmp: if (instrument) { const IRExpr* const data = st->Ist.WrTmp.data; IRExpr* addr_expr = data->Iex.Load.addr; if (data->tag == Iex_Load) { if (UNLIKELY(DRD_(any_address_is_traced)())) { addr_expr = instr_trace_mem_load(bb, addr_expr, sizeofIRType(data->Iex.Load.ty)); } instrument_load(bb, data->Iex.Load.addr, sizeofIRType(data->Iex.Load.ty)); } } addStmtToIRSB(bb, st); break; case Ist_Dirty: if (instrument) { IRDirty* d = st->Ist.Dirty.details; IREffect const mFx = d->mFx; switch (mFx) { case Ifx_None: break; case Ifx_Read: case Ifx_Write: case Ifx_Modify: tl_assert(d->mAddr); tl_assert(d->mSize > 0); argv = mkIRExprVec_2(d->mAddr, mkIRExpr_HWord(d->mSize)); if (mFx == Ifx_Read || mFx == Ifx_Modify) { di = unsafeIRDirty_0_N( /*regparms*/2, "drd_trace_load", VG_(fnptr_to_fnentry)(DRD_(trace_load)), argv); addStmtToIRSB(bb, IRStmt_Dirty(di)); } if (mFx == Ifx_Write || mFx == Ifx_Modify) { di = unsafeIRDirty_0_N( /*regparms*/2, "drd_trace_store", VG_(fnptr_to_fnentry)(DRD_(trace_store)), argv); addStmtToIRSB(bb, IRStmt_Dirty(di)); } break; default: tl_assert(0); } } addStmtToIRSB(bb, st); break; case Ist_CAS: if (instrument) { /* * Treat compare-and-swap as a read. By handling atomic * instructions as read instructions no data races are reported * between conflicting atomic operations nor between atomic * operations and non-atomic reads. Conflicts between atomic * operations and non-atomic write operations are still reported * however. */ Int dataSize; IRCAS* cas = st->Ist.CAS.details; tl_assert(cas->addr != NULL); tl_assert(cas->dataLo != NULL); dataSize = sizeofIRType(typeOfIRExpr(bb->tyenv, cas->dataLo)); if (cas->dataHi != NULL) dataSize *= 2; /* since it's a doubleword-CAS */ if (UNLIKELY(DRD_(any_address_is_traced)())) instr_trace_mem_store(bb, cas->addr, cas->dataHi, cas->dataLo); instrument_load(bb, cas->addr, dataSize); } addStmtToIRSB(bb, st); break; case Ist_LLSC: { /* * Ignore store-conditionals (except for tracing), and handle * load-linked's exactly like normal loads. */ IRType dataTy; if (st->Ist.LLSC.storedata == NULL) { /* LL */ dataTy = typeOfIRTemp(bb_in->tyenv, st->Ist.LLSC.result); if (instrument) { IRExpr* addr_expr = st->Ist.LLSC.addr; if (UNLIKELY(DRD_(any_address_is_traced)())) addr_expr = instr_trace_mem_load(bb, addr_expr, sizeofIRType(dataTy)); instrument_load(bb, addr_expr, sizeofIRType(dataTy)); } } else { /* SC */ instr_trace_mem_store(bb, st->Ist.LLSC.addr, NULL, st->Ist.LLSC.storedata); } addStmtToIRSB(bb, st); break; } case Ist_NoOp: case Ist_AbiHint: case Ist_Put: case Ist_PutI: case Ist_Exit: /* None of these can contain any memory references. */ addStmtToIRSB(bb, st); break; default: ppIRStmt(st); tl_assert(0); } } return bb; } /* This file is part of drd, a thread error detector. Copyright (C) 2006-2011 Bart Van Assche <[email protected]>. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. The GNU General Public License is contained in the file COPYING. */ #include "drd_bitmap.h" #include "drd_thread_bitmap.h" #include "drd_vc.h" /* DRD_(vc_snprint)() */ /* Include several source files here in order to allow the compiler to */ /* do more inlining. */ #include "drd_bitmap.c" #include "drd_load_store.h" #include "drd_segment.c" #include "drd_thread.c" #include "drd_vc.c" #include "libvex_guest_offsets.h" /* STACK_POINTER_OFFSET: VEX register offset for the stack pointer register. */ #if defined(VGA_x86) #define STACK_POINTER_OFFSET OFFSET_x86_ESP #elif defined(VGA_amd64) #define STACK_POINTER_OFFSET OFFSET_amd64_RSP #elif defined(VGA_ppc32) #define STACK_POINTER_OFFSET OFFSET_ppc32_GPR1 #elif defined(VGA_ppc64) #define STACK_POINTER_OFFSET OFFSET_ppc64_GPR1 #elif defined(VGA_arm) #define STACK_POINTER_OFFSET OFFSET_arm_R13 #elif defined(VGA_s390x) #define STACK_POINTER_OFFSET OFFSET_s390x_r15 #else #error Unknown architecture. #endif /* Local variables. */ static Bool s_check_stack_accesses = False; static Bool s_first_race_only = False; /* Function definitions. */ Bool DRD_(get_check_stack_accesses)() { return s_check_stack_accesses; } void DRD_(set_check_stack_accesses)(const Bool c) { tl_assert(c == False || c == True); s_check_stack_accesses = c; } Bool DRD_(get_first_race_only)() { return s_first_race_only; } void DRD_(set_first_race_only)(const Bool fro) { tl_assert(fro == False || fro == True); s_first_race_only = fro; } void DRD_(trace_mem_access)(const Addr addr, const SizeT size, const BmAccessTypeT access_type, const HWord stored_value_hi, const HWord stored_value_lo) { if (DRD_(is_any_traced)(addr, addr + size)) { char* vc; vc = DRD_(vc_aprint)(DRD_(thread_get_vc)(DRD_(thread_get_running_tid)())); if (access_type == eStore && size <= sizeof(HWord)) { DRD_(trace_msg_w_bt)("store 0x%lx size %ld val %ld/0x%lx (thread %d /" " vc %s)", addr, size, stored_value_lo, stored_value_lo, DRD_(thread_get_running_tid)(), vc); } else if (access_type == eStore && size > sizeof(HWord)) { ULong sv; tl_assert(sizeof(HWord) == 4); sv = ((ULong)stored_value_hi << 32) | stored_value_lo; DRD_(trace_msg_w_bt)("store 0x%lx size %ld val %lld/0x%llx (thread %d" " / vc %s)", addr, size, sv, sv, DRD_(thread_get_running_tid)(), vc); } else { DRD_(trace_msg_w_bt)("%s 0x%lx size %ld (thread %d / vc %s)", access_type == eLoad ? "load " : access_type == eStore ? "store" : access_type == eStart ? "start" : access_type == eEnd ? "end " : "????", addr, size, DRD_(thread_get_running_tid)(), vc); } VG_(free)(vc); tl_assert(DRD_(DrdThreadIdToVgThreadId)(DRD_(thread_get_running_tid)()) == VG_(get_running_tid)()); } } static VG_REGPARM(2) void drd_trace_mem_load(const Addr addr, const SizeT size) { return DRD_(trace_mem_access)(addr, size, eLoad, 0, 0); } static VG_REGPARM(3) void drd_trace_mem_store(const Addr addr,const SizeT size, const HWord stored_value_hi, const HWord stored_value_lo) { return DRD_(trace_mem_access)(addr, size, eStore, stored_value_hi, stored_value_lo); } static void drd_report_race(const Addr addr, const SizeT size, const BmAccessTypeT access_type) { ThreadId vg_tid; vg_tid = VG_(get_running_tid)(); if (!DRD_(get_check_stack_accesses)() && DRD_(thread_address_on_any_stack)(addr)) { #if 0 GenericErrInfo GEI = { .tid = DRD_(thread_get_running_tid)(), .addr = addr, }; VG_(maybe_record_error)(vg_tid, GenericErr, VG_(get_IP)(vg_tid), "--check-stack-var=no skips checking stack" " variables shared over threads", &GEI); #endif } else { DataRaceErrInfo drei = { .tid = DRD_(thread_get_running_tid)(), .addr = addr, .size = size, .access_type = access_type, }; VG_(maybe_record_error)(vg_tid, DataRaceErr, VG_(get_IP)(vg_tid), "Conflicting access", &drei); if (s_first_race_only) DRD_(start_suppression)(addr, addr + size, "first race only"); } } VG_REGPARM(2) void DRD_(trace_load)(Addr addr, SizeT size) { #ifdef ENABLE_DRD_CONSISTENCY_CHECKS /* The assert below has been commented out because of performance reasons.*/ tl_assert(DRD_(thread_get_running_tid)() == DRD_(VgThreadIdToDrdThreadId)(VG_(get_running_tid()))); #endif if (DRD_(running_thread_is_recording_loads)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_load_triggers_conflict(addr, addr + size) && ! DRD_(is_suppressed)(addr, addr + size)) { drd_report_race(addr, size, eLoad); } } static VG_REGPARM(1) void drd_trace_load_1(Addr addr) { if (DRD_(running_thread_is_recording_loads)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_load_1_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 1)) { drd_report_race(addr, 1, eLoad); } } static VG_REGPARM(1) void drd_trace_load_2(Addr addr) { if (DRD_(running_thread_is_recording_loads)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_load_2_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 2)) { drd_report_race(addr, 2, eLoad); } } static VG_REGPARM(1) void drd_trace_load_4(Addr addr) { if (DRD_(running_thread_is_recording_loads)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_load_4_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 4)) { drd_report_race(addr, 4, eLoad); } } static VG_REGPARM(1) void drd_trace_load_8(Addr addr) { if (DRD_(running_thread_is_recording_loads)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_load_8_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 8)) { drd_report_race(addr, 8, eLoad); } } VG_REGPARM(2) void DRD_(trace_store)(Addr addr, SizeT size) { #ifdef ENABLE_DRD_CONSISTENCY_CHECKS /* The assert below has been commented out because of performance reasons.*/ tl_assert(DRD_(thread_get_running_tid)() == DRD_(VgThreadIdToDrdThreadId)(VG_(get_running_tid()))); #endif if (DRD_(running_thread_is_recording_stores)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_store_triggers_conflict(addr, addr + size) && ! DRD_(is_suppressed)(addr, addr + size)) { drd_report_race(addr, size, eStore); } } static VG_REGPARM(1) void drd_trace_store_1(Addr addr) { if (DRD_(running_thread_is_recording_stores)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_store_1_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 1)) { drd_report_race(addr, 1, eStore); } } static VG_REGPARM(1) void drd_trace_store_2(Addr addr) { if (DRD_(running_thread_is_recording_stores)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_store_2_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 2)) { drd_report_race(addr, 2, eStore); } } static VG_REGPARM(1) void drd_trace_store_4(Addr addr) { if (DRD_(running_thread_is_recording_stores)() && (s_check_stack_accesses || !DRD_(thread_address_on_stack)(addr)) && bm_access_store_4_triggers_conflict(addr) && !DRD_(is_suppressed)(addr, addr + 4)) { drd_report_race(addr, 4, eStore); } } static VG_REGPARM(1) void drd_trace_store_8(Addr addr) { if (DRD_(running_thread_is_recording_stores)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_store_8_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 8)) { drd_report_race(addr, 8, eStore); } } /** * Return true if and only if addr_expr matches the pattern (SP) or * <offset>(SP). */ static Bool is_stack_access(IRSB* const bb, IRExpr* const addr_expr) { Bool result = False; if (addr_expr->tag == Iex_RdTmp) { int i; for (i = 0; i < bb->stmts_size; i++) { if (bb->stmts[i] && bb->stmts[i]->tag == Ist_WrTmp && bb->stmts[i]->Ist.WrTmp.tmp == addr_expr->Iex.RdTmp.tmp) { IRExpr* e = bb->stmts[i]->Ist.WrTmp.data; if (e->tag == Iex_Get && e->Iex.Get.offset == STACK_POINTER_OFFSET) { result = True; } //ppIRExpr(e); //VG_(printf)(" (%s)\n", result ? "True" : "False"); break; } } } return result; } static const IROp u_widen_irop[5][9] = { [Ity_I1 - Ity_I1] = { [4] = Iop_1Uto32, [8] = Iop_1Uto64 }, [Ity_I8 - Ity_I1] = { [4] = Iop_8Uto32, [8] = Iop_8Uto64 }, [Ity_I16 - Ity_I1] = { [4] = Iop_16Uto32, [8] = Iop_16Uto64 }, [Ity_I32 - Ity_I1] = { [8] = Iop_32Uto64 }, }; /** * Instrument the client code to trace a memory load (--trace-addr). */ static IRExpr* instr_trace_mem_load(IRSB* const bb, IRExpr* addr_expr, const HWord size) { IRTemp tmp; tmp = newIRTemp(bb->tyenv, typeOfIRExpr(bb->tyenv, addr_expr)); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, addr_expr)); addr_expr = IRExpr_RdTmp(tmp); addStmtToIRSB(bb, IRStmt_Dirty( unsafeIRDirty_0_N(/*regparms*/2, "drd_trace_mem_load", VG_(fnptr_to_fnentry) (drd_trace_mem_load), mkIRExprVec_2(addr_expr, mkIRExpr_HWord(size))))); return addr_expr; } /** * Instrument the client code to trace a memory store (--trace-addr). */ static void instr_trace_mem_store(IRSB* const bb, IRExpr* const addr_expr, IRExpr* data_expr_hi, IRExpr* data_expr_lo) { IRType ty_data_expr; HWord size; tl_assert(sizeof(HWord) == 4 || sizeof(HWord) == 8); tl_assert(!data_expr_hi || typeOfIRExpr(bb->tyenv, data_expr_hi) == Ity_I32); ty_data_expr = typeOfIRExpr(bb->tyenv, data_expr_lo); size = sizeofIRType(ty_data_expr); #if 0 // Test code if (ty_data_expr == Ity_I32) { IRTemp tmp = newIRTemp(bb->tyenv, Ity_F32); data_expr_lo = IRExpr_Unop(Iop_ReinterpI32asF32, data_expr_lo); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, data_expr_lo)); data_expr_lo = IRExpr_RdTmp(tmp); ty_data_expr = Ity_F32; } else if (ty_data_expr == Ity_I64) { IRTemp tmp = newIRTemp(bb->tyenv, Ity_F64); data_expr_lo = IRExpr_Unop(Iop_ReinterpI64asF64, data_expr_lo); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, data_expr_lo)); data_expr_lo = IRExpr_RdTmp(tmp); ty_data_expr = Ity_F64; } #endif if (ty_data_expr == Ity_F32) { IRTemp tmp = newIRTemp(bb->tyenv, Ity_I32); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, IRExpr_Unop(Iop_ReinterpF32asI32, data_expr_lo))); data_expr_lo = IRExpr_RdTmp(tmp); ty_data_expr = Ity_I32; } else if (ty_data_expr == Ity_F64) { IRTemp tmp = newIRTemp(bb->tyenv, Ity_I64); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, IRExpr_Unop(Iop_ReinterpF64asI64, data_expr_lo))); data_expr_lo = IRExpr_RdTmp(tmp); ty_data_expr = Ity_I64; } if (size == sizeof(HWord) && (ty_data_expr == Ity_I32 || ty_data_expr == Ity_I64)) { /* No conversion necessary */ } else { IROp widen_op; if (Ity_I1 <= ty_data_expr && ty_data_expr < Ity_I1 + sizeof(u_widen_irop)/sizeof(u_widen_irop[0])) { widen_op = u_widen_irop[ty_data_expr - Ity_I1][sizeof(HWord)]; if (!widen_op) widen_op = Iop_INVALID; } else { widen_op = Iop_INVALID; } if (widen_op != Iop_INVALID) { IRTemp tmp; /* Widen the integer expression to a HWord */ tmp = newIRTemp(bb->tyenv, sizeof(HWord) == 4 ? Ity_I32 : Ity_I64); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, IRExpr_Unop(widen_op, data_expr_lo))); data_expr_lo = IRExpr_RdTmp(tmp); } else if (size > sizeof(HWord) && !data_expr_hi && ty_data_expr == Ity_I64) { IRTemp tmp; tl_assert(sizeof(HWord) == 4); tl_assert(size == 8); tmp = newIRTemp(bb->tyenv, Ity_I32); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, IRExpr_Unop(Iop_64HIto32, data_expr_lo))); data_expr_hi = IRExpr_RdTmp(tmp); tmp = newIRTemp(bb->tyenv, Ity_I32); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, IRExpr_Unop(Iop_64to32, data_expr_lo))); data_expr_lo = IRExpr_RdTmp(tmp); } else { data_expr_lo = mkIRExpr_HWord(0); } } addStmtToIRSB(bb, IRStmt_Dirty( unsafeIRDirty_0_N(/*regparms*/3, "drd_trace_mem_store", VG_(fnptr_to_fnentry)(drd_trace_mem_store), mkIRExprVec_4(addr_expr, mkIRExpr_HWord(size), data_expr_hi ? data_expr_hi : mkIRExpr_HWord(0), data_expr_lo)))); } static void instrument_load(IRSB* const bb, IRExpr* const addr_expr, const HWord size) { IRExpr* size_expr; IRExpr** argv; IRDirty* di; if (!s_check_stack_accesses && is_stack_access(bb, addr_expr)) return; switch (size) { case 1: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_load_1", VG_(fnptr_to_fnentry)(drd_trace_load_1), argv); break; case 2: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_load_2", VG_(fnptr_to_fnentry)(drd_trace_load_2), argv); break; case 4: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_load_4", VG_(fnptr_to_fnentry)(drd_trace_load_4), argv); break; case 8: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_load_8", VG_(fnptr_to_fnentry)(drd_trace_load_8), argv); break; default: size_expr = mkIRExpr_HWord(size); argv = mkIRExprVec_2(addr_expr, size_expr); di = unsafeIRDirty_0_N(/*regparms*/2, "drd_trace_load", VG_(fnptr_to_fnentry)(DRD_(trace_load)), argv); break; } addStmtToIRSB(bb, IRStmt_Dirty(di)); } static void instrument_store(IRSB* const bb, IRExpr* addr_expr, IRExpr* const data_expr) { IRExpr* size_expr; IRExpr** argv; IRDirty* di; HWord size; size = sizeofIRType(typeOfIRExpr(bb->tyenv, data_expr)); if (UNLIKELY(DRD_(any_address_is_traced)())) { IRTemp tmp = newIRTemp(bb->tyenv, typeOfIRExpr(bb->tyenv, addr_expr)); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, addr_expr)); addr_expr = IRExpr_RdTmp(tmp); instr_trace_mem_store(bb, addr_expr, NULL, data_expr); } if (!s_check_stack_accesses && is_stack_access(bb, addr_expr)) return; switch (size) { case 1: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_store_1", VG_(fnptr_to_fnentry)(drd_trace_store_1), argv); break; case 2: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_store_2", VG_(fnptr_to_fnentry)(drd_trace_store_2), argv); break; case 4: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_store_4", VG_(fnptr_to_fnentry)(drd_trace_store_4), argv); break; case 8: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_store_8", VG_(fnptr_to_fnentry)(drd_trace_store_8), argv); break; default: size_expr = mkIRExpr_HWord(size); argv = mkIRExprVec_2(addr_expr, size_expr); di = unsafeIRDirty_0_N(/*regparms*/2, "drd_trace_store", VG_(fnptr_to_fnentry)(DRD_(trace_store)), argv); break; } addStmtToIRSB(bb, IRStmt_Dirty(di)); } IRSB* DRD_(instrument)(VgCallbackClosure* const closure, IRSB* const bb_in, VexGuestLayout* const layout, VexGuestExtents* const vge, IRType const gWordTy, IRType const hWordTy) { IRDirty* di; Int i; IRSB* bb; IRExpr** argv; Bool instrument = True; /* Set up BB */ bb = emptyIRSB(); bb->tyenv = deepCopyIRTypeEnv(bb_in->tyenv); bb->next = deepCopyIRExpr(bb_in->next); bb->jumpkind = bb_in->jumpkind; for (i = 0; i < bb_in->stmts_used; i++) { IRStmt* const st = bb_in->stmts[i]; tl_assert(st); tl_assert(isFlatIRStmt(st)); switch (st->tag) { /* Note: the code for not instrumenting the code in .plt */ /* sections is only necessary on CentOS 3.0 x86 (kernel 2.4.21 */ /* + glibc 2.3.2 + NPTL 0.60 + binutils 2.14.90.0.4). */ /* This is because on this platform dynamic library symbols are */ /* relocated in another way than by later binutils versions. The */ /* linker e.g. does not generate .got.plt sections on CentOS 3.0. */ case Ist_IMark: instrument = VG_(DebugInfo_sect_kind)(NULL, 0, st->Ist.IMark.addr) != Vg_SectPLT; addStmtToIRSB(bb, st); break; case Ist_MBE: switch (st->Ist.MBE.event) { case Imbe_Fence: break; /* not interesting */ default: tl_assert(0); } addStmtToIRSB(bb, st); break; case Ist_Store: if (instrument) instrument_store(bb, st->Ist.Store.addr, st->Ist.Store.data); addStmtToIRSB(bb, st); break; case Ist_WrTmp: if (instrument) { const IRExpr* const data = st->Ist.WrTmp.data; IRExpr* addr_expr = data->Iex.Load.addr; if (data->tag == Iex_Load) { if (UNLIKELY(DRD_(any_address_is_traced)())) { addr_expr = instr_trace_mem_load(bb, addr_expr, sizeofIRType(data->Iex.Load.ty)); } instrument_load(bb, data->Iex.Load.addr, sizeofIRType(data->Iex.Load.ty)); } } addStmtToIRSB(bb, st); break; case Ist_Dirty: if (instrument) { IRDirty* d = st->Ist.Dirty.details; IREffect const mFx = d->mFx; switch (mFx) { case Ifx_None: break; case Ifx_Read: case Ifx_Write: case Ifx_Modify: tl_assert(d->mAddr); tl_assert(d->mSize > 0); argv = mkIRExprVec_2(d->mAddr, mkIRExpr_HWord(d->mSize)); if (mFx == Ifx_Read || mFx == Ifx_Modify) { di = unsafeIRDirty_0_N( /*regparms*/2, "drd_trace_load", VG_(fnptr_to_fnentry)(DRD_(trace_load)), argv); addStmtToIRSB(bb, IRStmt_Dirty(di)); } if (mFx == Ifx_Write || mFx == Ifx_Modify) { di = unsafeIRDirty_0_N( /*regparms*/2, "drd_trace_store", VG_(fnptr_to_fnentry)(DRD_(trace_store)), argv); addStmtToIRSB(bb, IRStmt_Dirty(di)); } break; default: tl_assert(0); } } addStmtToIRSB(bb, st); break; case Ist_CAS: if (instrument) { /* * Treat compare-and-swap as a read. By handling atomic * instructions as read instructions no data races are reported * between conflicting atomic operations nor between atomic * operations and non-atomic reads. Conflicts between atomic * operations and non-atomic write operations are still reported * however. */ Int dataSize; IRCAS* cas = st->Ist.CAS.details; tl_assert(cas->addr != NULL); tl_assert(cas->dataLo != NULL); dataSize = sizeofIRType(typeOfIRExpr(bb->tyenv, cas->dataLo)); if (cas->dataHi != NULL) dataSize *= 2; /* since it's a doubleword-CAS */ if (UNLIKELY(DRD_(any_address_is_traced)())) instr_trace_mem_store(bb, cas->addr, cas->dataHi, cas->dataLo); instrument_load(bb, cas->addr, dataSize); } addStmtToIRSB(bb, st); break; case Ist_LLSC: { /* * Ignore store-conditionals (except for tracing), and handle * load-linked's exactly like normal loads. */ IRType dataTy; if (st->Ist.LLSC.storedata == NULL) { /* LL */ dataTy = typeOfIRTemp(bb_in->tyenv, st->Ist.LLSC.result); if (instrument) { IRExpr* addr_expr = st->Ist.LLSC.addr; if (UNLIKELY(DRD_(any_address_is_traced)())) addr_expr = instr_trace_mem_load(bb, addr_expr, sizeofIRType(dataTy)); instrument_load(bb, addr_expr, sizeofIRType(dataTy)); } } else { /* SC */ instr_trace_mem_store(bb, st->Ist.LLSC.addr, NULL, st->Ist.LLSC.storedata); } addStmtToIRSB(bb, st); break; } case Ist_NoOp: case Ist_AbiHint: case Ist_Put: case Ist_PutI: case Ist_Exit: /* None of these can contain any memory references. */ addStmtToIRSB(bb, st); break; default: ppIRStmt(st); tl_assert(0); } } return bb; }
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/valgrind_12474-12475.c
manybugs_data_15
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | Andrei Zmievski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "zend.h" #include "zend_execute.h" #include "zend_API.h" #include "zend_modules.h" #include "zend_constants.h" #include "zend_exceptions.h" #include "zend_closures.h" #ifdef HAVE_STDARG_H #include <stdarg.h> #endif /* these variables are true statics/globals, and have to be mutex'ed on every access */ static int module_count=0; ZEND_API HashTable module_registry; static zend_module_entry **module_request_startup_handlers; static zend_module_entry **module_request_shutdown_handlers; static zend_module_entry **module_post_deactivate_handlers; static zend_class_entry **class_cleanup_handlers; /* this function doesn't check for too many parameters */ ZEND_API int zend_get_parameters(int ht, int param_count, ...) /* {{{ */ { void **p; int arg_count; va_list ptr; zval **param, *param_ptr; TSRMLS_FETCH(); p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } va_start(ptr, param_count); while (param_count-->0) { param = va_arg(ptr, zval **); param_ptr = *(p-arg_count); if (!PZVAL_IS_REF(param_ptr) && Z_REFCOUNT_P(param_ptr) > 1) { zval *new_tmp; ALLOC_ZVAL(new_tmp); *new_tmp = *param_ptr; zval_copy_ctor(new_tmp); INIT_PZVAL(new_tmp); param_ptr = new_tmp; Z_DELREF_P((zval *) *(p-arg_count)); *(p-arg_count) = param_ptr; } *param = param_ptr; arg_count--; } va_end(ptr); return SUCCESS; } /* }}} */ ZEND_API int _zend_get_parameters_array(int ht, int param_count, zval **argument_array TSRMLS_DC) /* {{{ */ { void **p; int arg_count; zval *param_ptr; p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } while (param_count-->0) { param_ptr = *(p-arg_count); if (!PZVAL_IS_REF(param_ptr) && Z_REFCOUNT_P(param_ptr) > 1) { zval *new_tmp; ALLOC_ZVAL(new_tmp); *new_tmp = *param_ptr; zval_copy_ctor(new_tmp); INIT_PZVAL(new_tmp); param_ptr = new_tmp; Z_DELREF_P((zval *) *(p-arg_count)); *(p-arg_count) = param_ptr; } *(argument_array++) = param_ptr; arg_count--; } return SUCCESS; } /* }}} */ /* Zend-optimized Extended functions */ /* this function doesn't check for too many parameters */ ZEND_API int zend_get_parameters_ex(int param_count, ...) /* {{{ */ { void **p; int arg_count; va_list ptr; zval ***param; TSRMLS_FETCH(); p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } va_start(ptr, param_count); while (param_count-->0) { param = va_arg(ptr, zval ***); *param = (zval **) p-(arg_count--); } va_end(ptr); return SUCCESS; } /* }}} */ ZEND_API int _zend_get_parameters_array_ex(int param_count, zval ***argument_array TSRMLS_DC) /* {{{ */ { void **p; int arg_count; p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } while (param_count-->0) { zval **value = (zval**)(p-arg_count); *(argument_array++) = value; arg_count--; } return SUCCESS; } /* }}} */ ZEND_API int zend_copy_parameters_array(int param_count, zval *argument_array TSRMLS_DC) /* {{{ */ { void **p; int arg_count; p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } while (param_count-->0) { zval **param = (zval **) p-(arg_count--); zval_add_ref(param); add_next_index_zval(argument_array, *param); } return SUCCESS; } /* }}} */ ZEND_API void zend_wrong_param_count(TSRMLS_D) /* {{{ */ { const char *space; const char *class_name = get_active_class_name(&space TSRMLS_CC); zend_error(E_WARNING, "Wrong parameter count for %s%s%s()", class_name, space, get_active_function_name(TSRMLS_C)); } /* }}} */ /* Argument parsing API -- andrei */ ZEND_API char *zend_get_type_by_const(int type) /* {{{ */ { switch(type) { case IS_BOOL: return "boolean"; case IS_LONG: return "integer"; case IS_DOUBLE: return "double"; case IS_STRING: return "string"; case IS_OBJECT: return "object"; case IS_RESOURCE: return "resource"; case IS_NULL: return "null"; case IS_CALLABLE: return "callable"; case IS_ARRAY: return "array"; default: return "unknown"; } } /* }}} */ ZEND_API char *zend_zval_type_name(const zval *arg) /* {{{ */ { return zend_get_type_by_const(Z_TYPE_P(arg)); } /* }}} */ ZEND_API zend_class_entry *zend_get_class_entry(const zval *zobject TSRMLS_DC) /* {{{ */ { if (Z_OBJ_HT_P(zobject)->get_class_entry) { return Z_OBJ_HT_P(zobject)->get_class_entry(zobject TSRMLS_CC); } else { zend_error(E_ERROR, "Class entry requested for an object without PHP class"); return NULL; } } /* }}} */ /* returns 1 if you need to copy result, 0 if it's already a copy */ ZEND_API int zend_get_object_classname(const zval *object, const char **class_name, zend_uint *class_name_len TSRMLS_DC) /* {{{ */ { if (Z_OBJ_HT_P(object)->get_class_name == NULL || Z_OBJ_HT_P(object)->get_class_name(object, class_name, class_name_len, 0 TSRMLS_CC) != SUCCESS) { zend_class_entry *ce = Z_OBJCE_P(object); *class_name = ce->name; *class_name_len = ce->name_length; return 1; } return 0; } /* }}} */ static int parse_arg_object_to_string(zval **arg, char **p, int *pl, int type TSRMLS_DC) /* {{{ */ { if (Z_OBJ_HANDLER_PP(arg, cast_object)) { SEPARATE_ZVAL_IF_NOT_REF(arg); if (Z_OBJ_HANDLER_PP(arg, cast_object)(*arg, *arg, type TSRMLS_CC) == SUCCESS) { *pl = Z_STRLEN_PP(arg); *p = Z_STRVAL_PP(arg); return SUCCESS; } } /* Standard PHP objects */ if (Z_OBJ_HT_PP(arg) == &std_object_handlers || !Z_OBJ_HANDLER_PP(arg, cast_object)) { SEPARATE_ZVAL_IF_NOT_REF(arg); if (zend_std_cast_object_tostring(*arg, *arg, type TSRMLS_CC) == SUCCESS) { *pl = Z_STRLEN_PP(arg); *p = Z_STRVAL_PP(arg); return SUCCESS; } } if (!Z_OBJ_HANDLER_PP(arg, cast_object) && Z_OBJ_HANDLER_PP(arg, get)) { int use_copy; zval *z = Z_OBJ_HANDLER_PP(arg, get)(*arg TSRMLS_CC); Z_ADDREF_P(z); if(Z_TYPE_P(z) != IS_OBJECT) { zval_dtor(*arg); Z_TYPE_P(*arg) = IS_NULL; zend_make_printable_zval(z, *arg, &use_copy); if (!use_copy) { ZVAL_ZVAL(*arg, z, 1, 1); } *pl = Z_STRLEN_PP(arg); *p = Z_STRVAL_PP(arg); return SUCCESS; } zval_ptr_dtor(&z); } return FAILURE; } /* }}} */ static const char *zend_parse_arg_impl(int arg_num, zval **arg, va_list *va, const char **spec, char **error, int *severity TSRMLS_DC) /* {{{ */ { const char *spec_walk = *spec; char c = *spec_walk++; int return_null = 0; /* scan through modifiers */ while (1) { if (*spec_walk == '/') { SEPARATE_ZVAL_IF_NOT_REF(arg); } else if (*spec_walk == '!') { if (Z_TYPE_PP(arg) == IS_NULL) { return_null = 1; } } else { break; } spec_walk++; } switch (c) { case 'l': case 'L': { long *p = va_arg(*va, long *); switch (Z_TYPE_PP(arg)) { case IS_STRING: { double d; int type; if ((type = is_numeric_string(Z_STRVAL_PP(arg), Z_STRLEN_PP(arg), p, &d, -1)) == 0) { return "long"; } else if (type == IS_DOUBLE) { if (c == 'L') { if (d > LONG_MAX) { *p = LONG_MAX; break; } else if (d < LONG_MIN) { *p = LONG_MIN; break; } } *p = zend_dval_to_lval(d); } } break; case IS_DOUBLE: if (c == 'L') { if (Z_DVAL_PP(arg) > LONG_MAX) { *p = LONG_MAX; break; } else if (Z_DVAL_PP(arg) < LONG_MIN) { *p = LONG_MIN; break; } } case IS_NULL: case IS_LONG: case IS_BOOL: convert_to_long_ex(arg); *p = Z_LVAL_PP(arg); break; case IS_ARRAY: case IS_OBJECT: case IS_RESOURCE: default: return "long"; } } break; case 'd': { double *p = va_arg(*va, double *); switch (Z_TYPE_PP(arg)) { case IS_STRING: { long l; int type; if ((type = is_numeric_string(Z_STRVAL_PP(arg), Z_STRLEN_PP(arg), &l, p, -1)) == 0) { return "double"; } else if (type == IS_LONG) { *p = (double) l; } } break; case IS_NULL: case IS_LONG: case IS_DOUBLE: case IS_BOOL: convert_to_double_ex(arg); *p = Z_DVAL_PP(arg); break; case IS_ARRAY: case IS_OBJECT: case IS_RESOURCE: default: return "double"; } } break; case 'p': case 's': { char **p = va_arg(*va, char **); int *pl = va_arg(*va, int *); switch (Z_TYPE_PP(arg)) { case IS_NULL: if (return_null) { *p = NULL; *pl = 0; break; } /* break omitted intentionally */ case IS_STRING: case IS_LONG: case IS_DOUBLE: case IS_BOOL: convert_to_string_ex(arg); if (UNEXPECTED(Z_ISREF_PP(arg) != 0)) { /* it's dangerous to return pointers to string buffer of referenced variable, because it can be clobbered throug magic callbacks */ SEPARATE_ZVAL(arg); } *p = Z_STRVAL_PP(arg); *pl = Z_STRLEN_PP(arg); if (c == 'p' && CHECK_ZVAL_NULL_PATH(*arg)) { return "a valid path"; } break; case IS_OBJECT: if (parse_arg_object_to_string(arg, p, pl, IS_STRING TSRMLS_CC) == SUCCESS) { if (c == 'p' && CHECK_ZVAL_NULL_PATH(*arg)) { return "a valid path"; } break; } case IS_ARRAY: case IS_RESOURCE: default: return c == 's' ? "string" : "a valid path"; } } break; case 'b': { zend_bool *p = va_arg(*va, zend_bool *); switch (Z_TYPE_PP(arg)) { case IS_NULL: case IS_STRING: case IS_LONG: case IS_DOUBLE: case IS_BOOL: convert_to_boolean_ex(arg); *p = Z_BVAL_PP(arg); break; case IS_ARRAY: case IS_OBJECT: case IS_RESOURCE: default: return "boolean"; } } break; case 'r': { zval **p = va_arg(*va, zval **); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_RESOURCE) { *p = *arg; } else { return "resource"; } } break; case 'A': case 'a': { zval **p = va_arg(*va, zval **); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_ARRAY || (c == 'A' && Z_TYPE_PP(arg) == IS_OBJECT)) { *p = *arg; } else { return "array"; } } break; case 'H': case 'h': { HashTable **p = va_arg(*va, HashTable **); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_ARRAY) { *p = Z_ARRVAL_PP(arg); } else if(c == 'H' && Z_TYPE_PP(arg) == IS_OBJECT) { *p = HASH_OF(*arg); if(*p == NULL) { return "array"; } } else { return "array"; } } break; case 'o': { zval **p = va_arg(*va, zval **); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_OBJECT) { *p = *arg; } else { return "object"; } } break; case 'O': { zval **p = va_arg(*va, zval **); zend_class_entry *ce = va_arg(*va, zend_class_entry *); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_OBJECT && (!ce || instanceof_function(Z_OBJCE_PP(arg), ce TSRMLS_CC))) { *p = *arg; } else { if (ce) { return ce->name; } else { return "object"; } } } break; case 'C': { zend_class_entry **lookup, **pce = va_arg(*va, zend_class_entry **); zend_class_entry *ce_base = *pce; if (return_null) { *pce = NULL; break; } convert_to_string_ex(arg); if (zend_lookup_class(Z_STRVAL_PP(arg), Z_STRLEN_PP(arg), &lookup TSRMLS_CC) == FAILURE) { *pce = NULL; } else { *pce = *lookup; } if (ce_base) { if ((!*pce || !instanceof_function(*pce, ce_base TSRMLS_CC))) { zend_spprintf(error, 0, "to be a class name derived from %s, '%s' given", ce_base->name, Z_STRVAL_PP(arg)); *pce = NULL; return ""; } } if (!*pce) { zend_spprintf(error, 0, "to be a valid class name, '%s' given", Z_STRVAL_PP(arg)); return ""; } break; } break; case 'f': { zend_fcall_info *fci = va_arg(*va, zend_fcall_info *); zend_fcall_info_cache *fcc = va_arg(*va, zend_fcall_info_cache *); char *is_callable_error = NULL; if (return_null) { fci->size = 0; fcc->initialized = 0; break; } if (zend_fcall_info_init(*arg, 0, fci, fcc, NULL, &is_callable_error TSRMLS_CC) == SUCCESS) { if (is_callable_error) { *severity = E_STRICT; zend_spprintf(error, 0, "to be a valid callback, %s", is_callable_error); efree(is_callable_error); *spec = spec_walk; return ""; } break; } else { if (is_callable_error) { *severity = E_WARNING; zend_spprintf(error, 0, "to be a valid callback, %s", is_callable_error); efree(is_callable_error); return ""; } else { return "valid callback"; } } } case 'z': { zval **p = va_arg(*va, zval **); if (return_null) { *p = NULL; } else { *p = *arg; } } break; case 'Z': { zval ***p = va_arg(*va, zval ***); if (return_null) { *p = NULL; } else { *p = arg; } } break; default: return "unknown"; } *spec = spec_walk; return NULL; } /* }}} */ static int zend_parse_arg(int arg_num, zval **arg, va_list *va, const char **spec, int quiet TSRMLS_DC) /* {{{ */ { const char *expected_type = NULL; char *error = NULL; int severity = E_WARNING; expected_type = zend_parse_arg_impl(arg_num, arg, va, spec, &error, &severity TSRMLS_CC); if (expected_type) { if (!quiet && (*expected_type || error)) { const char *space; const char *class_name = get_active_class_name(&space TSRMLS_CC); if (error) { zend_error(severity, "%s%s%s() expects parameter %d %s", class_name, space, get_active_function_name(TSRMLS_C), arg_num, error); efree(error); } else { zend_error(severity, "%s%s%s() expects parameter %d to be %s, %s given", class_name, space, get_active_function_name(TSRMLS_C), arg_num, expected_type, zend_zval_type_name(*arg)); } } if (severity != E_STRICT) { return FAILURE; } } return SUCCESS; } /* }}} */ static int zend_parse_va_args(int num_args, const char *type_spec, va_list *va, int flags TSRMLS_DC) /* {{{ */ { const char *spec_walk; int c, i; int min_num_args = -1; int max_num_args = 0; int post_varargs = 0; zval **arg; int arg_count; int quiet = flags & ZEND_PARSE_PARAMS_QUIET; zend_bool have_varargs = 0; zval ****varargs = NULL; int *n_varargs = NULL; for (spec_walk = type_spec; *spec_walk; spec_walk++) { c = *spec_walk; switch (c) { case 'l': case 'd': case 's': case 'b': case 'r': case 'a': case 'o': case 'O': case 'z': case 'Z': case 'C': case 'h': case 'f': case 'A': case 'H': case 'p': max_num_args++; break; case '|': min_num_args = max_num_args; break; case '/': case '!': /* Pass */ break; case '*': case '+': if (have_varargs) { if (!quiet) { zend_function *active_function = EG(current_execute_data)->function_state.function; const char *class_name = active_function->common.scope ? active_function->common.scope->name : ""; zend_error(E_WARNING, "%s%s%s(): only one varargs specifier (* or +) is permitted", class_name, class_name[0] ? "::" : "", active_function->common.function_name); } return FAILURE; } have_varargs = 1; /* we expect at least one parameter in varargs */ if (c == '+') { max_num_args++; } /* mark the beginning of varargs */ post_varargs = max_num_args; break; default: if (!quiet) { zend_function *active_function = EG(current_execute_data)->function_state.function; const char *class_name = active_function->common.scope ? active_function->common.scope->name : ""; zend_error(E_WARNING, "%s%s%s(): bad type specifier while parsing parameters", class_name, class_name[0] ? "::" : "", active_function->common.function_name); } return FAILURE; } } if (min_num_args < 0) { min_num_args = max_num_args; } if (have_varargs) { /* calculate how many required args are at the end of the specifier list */ post_varargs = max_num_args - post_varargs; max_num_args = -1; } if (num_args < min_num_args || (num_args > max_num_args && max_num_args > 0)) { if (!quiet) { zend_function *active_function = EG(current_execute_data)->function_state.function; const char *class_name = active_function->common.scope ? active_function->common.scope->name : ""; zend_error(E_WARNING, "%s%s%s() expects %s %d parameter%s, %d given", class_name, class_name[0] ? "::" : "", active_function->common.function_name, min_num_args == max_num_args ? "exactly" : num_args < min_num_args ? "at least" : "at most", num_args < min_num_args ? min_num_args : max_num_args, (num_args < min_num_args ? min_num_args : max_num_args) == 1 ? "" : "s", num_args); } return FAILURE; } arg_count = (int)(zend_uintptr_t) *(zend_vm_stack_top(TSRMLS_C) - 1); if (num_args > arg_count) { zend_error(E_WARNING, "%s(): could not obtain parameters for parsing", get_active_function_name(TSRMLS_C)); return FAILURE; } i = 0; while (num_args-- > 0) { if (*type_spec == '|') { type_spec++; } if (*type_spec == '*' || *type_spec == '+') { int num_varargs = num_args + 1 - post_varargs; /* eat up the passed in storage even if it won't be filled in with varargs */ varargs = va_arg(*va, zval ****); n_varargs = va_arg(*va, int *); type_spec++; if (num_varargs > 0) { int iv = 0; zval **p = (zval **) (zend_vm_stack_top(TSRMLS_C) - 1 - (arg_count - i)); *n_varargs = num_varargs; /* allocate space for array and store args */ *varargs = safe_emalloc(num_varargs, sizeof(zval **), 0); while (num_varargs-- > 0) { (*varargs)[iv++] = p++; } /* adjust how many args we have left and restart loop */ num_args = num_args + 1 - iv; i += iv; continue; } else { *varargs = NULL; *n_varargs = 0; } } arg = (zval **) (zend_vm_stack_top(TSRMLS_C) - 1 - (arg_count-i)); if (zend_parse_arg(i+1, arg, va, &type_spec, quiet TSRMLS_CC) == FAILURE) { /* clean up varargs array if it was used */ if (varargs && *varargs) { efree(*varargs); *varargs = NULL; } return FAILURE; } i++; } return SUCCESS; } /* }}} */ #define RETURN_IF_ZERO_ARGS(num_args, type_spec, quiet) { \ int __num_args = (num_args); \ \ if (0 == (type_spec)[0] && 0 != __num_args && !(quiet)) { \ const char *__space; \ const char * __class_name = get_active_class_name(&__space TSRMLS_CC); \ zend_error(E_WARNING, "%s%s%s() expects exactly 0 parameters, %d given", \ __class_name, __space, \ get_active_function_name(TSRMLS_C), __num_args); \ return FAILURE; \ }\ } ZEND_API int zend_parse_parameters_ex(int flags, int num_args TSRMLS_DC, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; RETURN_IF_ZERO_ARGS(num_args, type_spec, flags & ZEND_PARSE_PARAMS_QUIET); va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, flags TSRMLS_CC); va_end(va); return retval; } /* }}} */ ZEND_API int zend_parse_parameters(int num_args TSRMLS_DC, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; RETURN_IF_ZERO_ARGS(num_args, type_spec, 0); va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, 0 TSRMLS_CC); va_end(va); return retval; } /* }}} */ ZEND_API int zend_parse_method_parameters(int num_args TSRMLS_DC, zval *this_ptr, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; const char *p = type_spec; zval **object; zend_class_entry *ce; if (!this_ptr) { RETURN_IF_ZERO_ARGS(num_args, p, 0); va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, 0 TSRMLS_CC); va_end(va); } else { p++; RETURN_IF_ZERO_ARGS(num_args, p, 0); va_start(va, type_spec); object = va_arg(va, zval **); ce = va_arg(va, zend_class_entry *); *object = this_ptr; if (ce && !instanceof_function(Z_OBJCE_P(this_ptr), ce TSRMLS_CC)) { zend_error(E_CORE_ERROR, "%s::%s() must be derived from %s::%s", ce->name, get_active_function_name(TSRMLS_C), Z_OBJCE_P(this_ptr)->name, get_active_function_name(TSRMLS_C)); } retval = zend_parse_va_args(num_args, p, &va, 0 TSRMLS_CC); va_end(va); } return retval; } /* }}} */ ZEND_API int zend_parse_method_parameters_ex(int flags, int num_args TSRMLS_DC, zval *this_ptr, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; const char *p = type_spec; zval **object; zend_class_entry *ce; int quiet = flags & ZEND_PARSE_PARAMS_QUIET; if (!this_ptr) { RETURN_IF_ZERO_ARGS(num_args, p, quiet); va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, flags TSRMLS_CC); va_end(va); } else { p++; RETURN_IF_ZERO_ARGS(num_args, p, quiet); va_start(va, type_spec); object = va_arg(va, zval **); ce = va_arg(va, zend_class_entry *); *object = this_ptr; if (ce && !instanceof_function(Z_OBJCE_P(this_ptr), ce TSRMLS_CC)) { if (!quiet) { zend_error(E_CORE_ERROR, "%s::%s() must be derived from %s::%s", ce->name, get_active_function_name(TSRMLS_C), Z_OBJCE_P(this_ptr)->name, get_active_function_name(TSRMLS_C)); } va_end(va); return FAILURE; } retval = zend_parse_va_args(num_args, p, &va, flags TSRMLS_CC); va_end(va); } return retval; } /* }}} */ /* Argument parsing API -- andrei */ ZEND_API int _array_init(zval *arg, uint size ZEND_FILE_LINE_DC) /* {{{ */ { ALLOC_HASHTABLE_REL(Z_ARRVAL_P(arg)); _zend_hash_init(Z_ARRVAL_P(arg), size, NULL, ZVAL_PTR_DTOR, 0 ZEND_FILE_LINE_RELAY_CC); Z_TYPE_P(arg) = IS_ARRAY; return SUCCESS; } /* }}} */ static int zend_merge_property(zval **value TSRMLS_DC, int num_args, va_list args, const zend_hash_key *hash_key) /* {{{ */ { /* which name should a numeric property have ? */ if (hash_key->nKeyLength) { zval *obj = va_arg(args, zval *); zend_object_handlers *obj_ht = va_arg(args, zend_object_handlers *); zval *member; MAKE_STD_ZVAL(member); ZVAL_STRINGL(member, hash_key->arKey, hash_key->nKeyLength-1, 1); obj_ht->write_property(obj, member, *value, 0 TSRMLS_CC); zval_ptr_dtor(&member); } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* This function should be called after the constructor has been called * because it may call __set from the uninitialized object otherwise. */ ZEND_API void zend_merge_properties(zval *obj, HashTable *properties, int destroy_ht TSRMLS_DC) /* {{{ */ { const zend_object_handlers *obj_ht = Z_OBJ_HT_P(obj); zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE_P(obj); zend_hash_apply_with_arguments(properties TSRMLS_CC, (apply_func_args_t)zend_merge_property, 2, obj, obj_ht); EG(scope) = old_scope; if (destroy_ht) { zend_hash_destroy(properties); FREE_HASHTABLE(properties); } } /* }}} */ ZEND_API void zend_update_class_constants(zend_class_entry *class_type TSRMLS_DC) /* {{{ */ { if ((class_type->ce_flags & ZEND_ACC_CONSTANTS_UPDATED) == 0 || (!CE_STATIC_MEMBERS(class_type) && class_type->default_static_members_count)) { zend_class_entry **scope = EG(in_execution)?&EG(scope):&CG(active_class_entry); zend_class_entry *old_scope = *scope; int i; *scope = class_type; zend_hash_apply_with_argument(&class_type->constants_table, (apply_func_arg_t) zval_update_constant, (void*)1 TSRMLS_CC); for (i = 0; i < class_type->default_properties_count; i++) { if (class_type->default_properties_table[i]) { zval_update_constant(&class_type->default_properties_table[i], (void**)1 TSRMLS_CC); } } if (!CE_STATIC_MEMBERS(class_type) && class_type->default_static_members_count) { zval **p; if (class_type->parent) { zend_update_class_constants(class_type->parent TSRMLS_CC); } #if ZTS CG(static_members_table)[(zend_intptr_t)(class_type->static_members_table)] = emalloc(sizeof(zval*) * class_type->default_static_members_count); #else class_type->static_members_table = emalloc(sizeof(zval*) * class_type->default_static_members_count); #endif for (i = 0; i < class_type->default_static_members_count; i++) { p = &class_type->default_static_members_table[i]; if (Z_ISREF_PP(p) && class_type->parent && i < class_type->parent->default_static_members_count && *p == class_type->parent->default_static_members_table[i] && CE_STATIC_MEMBERS(class_type->parent)[i] ) { zval *q = CE_STATIC_MEMBERS(class_type->parent)[i]; Z_ADDREF_P(q); Z_SET_ISREF_P(q); CE_STATIC_MEMBERS(class_type)[i] = q; } else { zval *r; ALLOC_ZVAL(r); *r = **p; INIT_PZVAL(r); zval_copy_ctor(r); CE_STATIC_MEMBERS(class_type)[i] = r; } } } for (i = 0; i < class_type->default_static_members_count; i++) { zval_update_constant(&CE_STATIC_MEMBERS(class_type)[i], (void**)1 TSRMLS_CC); } *scope = old_scope; class_type->ce_flags |= ZEND_ACC_CONSTANTS_UPDATED; } } /* }}} */ ZEND_API void object_properties_init(zend_object *object, zend_class_entry *class_type) /* {{{ */ { int i; if (class_type->default_properties_count) { object->properties_table = emalloc(sizeof(zval*) * class_type->default_properties_count); for (i = 0; i < class_type->default_properties_count; i++) { object->properties_table[i] = class_type->default_properties_table[i]; if (class_type->default_properties_table[i]) { Z_ADDREF_P(object->properties_table[i]); } } object->properties = NULL; } } /* }}} */ /* This function requires 'properties' to contain all props declared in the * class and all props being public. If only a subset is given or the class * has protected members then you need to merge the properties seperately by * calling zend_merge_properties(). */ ZEND_API int _object_and_properties_init(zval *arg, zend_class_entry *class_type, HashTable *properties ZEND_FILE_LINE_DC TSRMLS_DC) /* {{{ */ { zend_object *object; if (class_type->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLICIT_ABSTRACT_CLASS|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) { char *what = class_type->ce_flags & ZEND_ACC_INTERFACE ? "interface" : "abstract class"; zend_error(E_ERROR, "Cannot instantiate %s %s", what, class_type->name); } zend_update_class_constants(class_type TSRMLS_CC); Z_TYPE_P(arg) = IS_OBJECT; if (class_type->create_object == NULL) { Z_OBJVAL_P(arg) = zend_objects_new(&object, class_type TSRMLS_CC); if (properties) { object->properties = properties; object->properties_table = NULL; } else { object_properties_init(object, class_type); } } else { Z_OBJVAL_P(arg) = class_type->create_object(class_type TSRMLS_CC); } return SUCCESS; } /* }}} */ ZEND_API int _object_init_ex(zval *arg, zend_class_entry *class_type ZEND_FILE_LINE_DC TSRMLS_DC) /* {{{ */ { return _object_and_properties_init(arg, class_type, 0 ZEND_FILE_LINE_RELAY_CC TSRMLS_CC); } /* }}} */ ZEND_API int _object_init(zval *arg ZEND_FILE_LINE_DC TSRMLS_DC) /* {{{ */ { return _object_init_ex(arg, zend_standard_class_def ZEND_FILE_LINE_RELAY_CC TSRMLS_CC); } /* }}} */ ZEND_API int add_assoc_function(zval *arg, const char *key, void (*function_ptr)(INTERNAL_FUNCTION_PARAMETERS)) /* {{{ */ { zend_error(E_WARNING, "add_assoc_function() is no longer supported"); return FAILURE; } /* }}} */ ZEND_API int add_assoc_long_ex(zval *arg, const char *key, uint key_len, long n) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, n); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_null_ex(zval *arg, const char *key, uint key_len) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_NULL(tmp); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_bool_ex(zval *arg, const char *key, uint key_len, int b) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_BOOL(tmp, b); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_resource_ex(zval *arg, const char *key, uint key_len, int r) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_RESOURCE(tmp, r); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_double_ex(zval *arg, const char *key, uint key_len, double d) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_string_ex(zval *arg, const char *key, uint key_len, char *str, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_stringl_ex(zval *arg, const char *key, uint key_len, char *str, uint length, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_zval_ex(zval *arg, const char *key, uint key_len, zval *value) /* {{{ */ { return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &value, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_long(zval *arg, ulong index, long n) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, n); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_null(zval *arg, ulong index) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_NULL(tmp); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_bool(zval *arg, ulong index, int b) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_BOOL(tmp, b); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_resource(zval *arg, ulong index, int r) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_RESOURCE(tmp, r); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_double(zval *arg, ulong index, double d) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_string(zval *arg, ulong index, const char *str, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_stringl(zval *arg, ulong index, const char *str, uint length, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_zval(zval *arg, ulong index, zval *value) /* {{{ */ { return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &value, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_long(zval *arg, long n) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, n); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_null(zval *arg) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_NULL(tmp); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_bool(zval *arg, int b) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_BOOL(tmp, b); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_resource(zval *arg, int r) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_RESOURCE(tmp, r); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_double(zval *arg, double d) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_string(zval *arg, const char *str, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_stringl(zval *arg, const char *str, uint length, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_zval(zval *arg, zval *value) /* {{{ */ { return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &value, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_get_assoc_string_ex(zval *arg, const char *key, uint key_len, const char *str, void **dest, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_assoc_stringl_ex(zval *arg, const char *key, uint key_len, const char *str, uint length, void **dest, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_index_long(zval *arg, ulong index, long l, void **dest) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, l); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_index_double(zval *arg, ulong index, double d, void **dest) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_index_string(zval *arg, ulong index, const char *str, void **dest, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_index_stringl(zval *arg, ulong index, const char *str, uint length, void **dest, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_property_long_ex(zval *arg, const char *key, uint key_len, long n TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, n); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_bool_ex(zval *arg, const char *key, uint key_len, int b TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_BOOL(tmp, b); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_null_ex(zval *arg, const char *key, uint key_len TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_NULL(tmp); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_resource_ex(zval *arg, const char *key, uint key_len, long n TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_RESOURCE(tmp, n); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_double_ex(zval *arg, const char *key, uint key_len, double d TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_string_ex(zval *arg, const char *key, uint key_len, const char *str, int duplicate TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_stringl_ex(zval *arg, const char *key, uint key_len, const char *str, uint length, int duplicate TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_zval_ex(zval *arg, const char *key, uint key_len, zval *value TSRMLS_DC) /* {{{ */ { zval *z_key; MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, value, 0 TSRMLS_CC); zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int zend_startup_module_ex(zend_module_entry *module TSRMLS_DC) /* {{{ */ { int name_len; char *lcname; if (module->module_started) { return SUCCESS; } module->module_started = 1; /* Check module dependencies */ if (module->deps) { const zend_module_dep *dep = module->deps; while (dep->name) { if (dep->type == MODULE_DEP_REQUIRED) { zend_module_entry *req_mod; name_len = strlen(dep->name); lcname = zend_str_tolower_dup(dep->name, name_len); if (zend_hash_find(&module_registry, lcname, name_len+1, (void**)&req_mod) == FAILURE || !req_mod->module_started) { efree(lcname); /* TODO: Check version relationship */ zend_error(E_CORE_WARNING, "Cannot load module '%s' because required module '%s' is not loaded", module->name, dep->name); module->module_started = 0; return FAILURE; } efree(lcname); } ++dep; } } /* Initialize module globals */ if (module->globals_size) { #ifdef ZTS ts_allocate_id(module->globals_id_ptr, module->globals_size, (ts_allocate_ctor) module->globals_ctor, (ts_allocate_dtor) module->globals_dtor); #else if (module->globals_ctor) { module->globals_ctor(module->globals_ptr TSRMLS_CC); } #endif } if (module->module_startup_func) { EG(current_module) = module; if (module->module_startup_func(module->type, module->module_number TSRMLS_CC)==FAILURE) { zend_error(E_CORE_ERROR,"Unable to start %s module", module->name); EG(current_module) = NULL; return FAILURE; } EG(current_module) = NULL; } return SUCCESS; } /* }}} */ static void zend_sort_modules(void *base, size_t count, size_t siz, compare_func_t compare TSRMLS_DC) /* {{{ */ { Bucket **b1 = base; Bucket **b2; Bucket **end = b1 + count; Bucket *tmp; zend_module_entry *m, *r; while (b1 < end) { try_again: m = (zend_module_entry*)(*b1)->pData; if (!m->module_started && m->deps) { const zend_module_dep *dep = m->deps; while (dep->name) { if (dep->type == MODULE_DEP_REQUIRED || dep->type == MODULE_DEP_OPTIONAL) { b2 = b1 + 1; while (b2 < end) { r = (zend_module_entry*)(*b2)->pData; if (strcasecmp(dep->name, r->name) == 0) { tmp = *b1; *b1 = *b2; *b2 = tmp; goto try_again; } b2++; } } dep++; } } b1++; } } /* }}} */ ZEND_API void zend_collect_module_handlers(TSRMLS_D) /* {{{ */ { HashPosition pos; zend_module_entry *module; int startup_count = 0; int shutdown_count = 0; int post_deactivate_count = 0; zend_class_entry **pce; int class_count = 0; /* Collect extensions with request startup/shutdown handlers */ for (zend_hash_internal_pointer_reset_ex(&module_registry, &pos); zend_hash_get_current_data_ex(&module_registry, (void *) &module, &pos) == SUCCESS; zend_hash_move_forward_ex(&module_registry, &pos)) { if (module->request_startup_func) { startup_count++; } if (module->request_shutdown_func) { shutdown_count++; } if (module->post_deactivate_func) { post_deactivate_count++; } } module_request_startup_handlers = (zend_module_entry**)malloc( sizeof(zend_module_entry*) * (startup_count + 1 + shutdown_count + 1 + post_deactivate_count + 1)); module_request_startup_handlers[startup_count] = NULL; module_request_shutdown_handlers = module_request_startup_handlers + startup_count + 1; module_request_shutdown_handlers[shutdown_count] = NULL; module_post_deactivate_handlers = module_request_shutdown_handlers + shutdown_count + 1; module_post_deactivate_handlers[post_deactivate_count] = NULL; startup_count = 0; for (zend_hash_internal_pointer_reset_ex(&module_registry, &pos); zend_hash_get_current_data_ex(&module_registry, (void *) &module, &pos) == SUCCESS; zend_hash_move_forward_ex(&module_registry, &pos)) { if (module->request_startup_func) { module_request_startup_handlers[startup_count++] = module; } if (module->request_shutdown_func) { module_request_shutdown_handlers[--shutdown_count] = module; } if (module->post_deactivate_func) { module_post_deactivate_handlers[--post_deactivate_count] = module; } } /* Collect internal classes with static members */ for (zend_hash_internal_pointer_reset_ex(CG(class_table), &pos); zend_hash_get_current_data_ex(CG(class_table), (void *) &pce, &pos) == SUCCESS; zend_hash_move_forward_ex(CG(class_table), &pos)) { if ((*pce)->type == ZEND_INTERNAL_CLASS && (*pce)->default_static_members_count > 0) { class_count++; } } class_cleanup_handlers = (zend_class_entry**)malloc( sizeof(zend_class_entry*) * (class_count + 1)); class_cleanup_handlers[class_count] = NULL; if (class_count) { for (zend_hash_internal_pointer_reset_ex(CG(class_table), &pos); zend_hash_get_current_data_ex(CG(class_table), (void *) &pce, &pos) == SUCCESS; zend_hash_move_forward_ex(CG(class_table), &pos)) { if ((*pce)->type == ZEND_INTERNAL_CLASS && (*pce)->default_static_members_count > 0) { class_cleanup_handlers[--class_count] = *pce; } } } } /* }}} */ ZEND_API int zend_startup_modules(TSRMLS_D) /* {{{ */ { zend_hash_sort(&module_registry, zend_sort_modules, NULL, 0 TSRMLS_CC); zend_hash_apply(&module_registry, (apply_func_t)zend_startup_module_ex TSRMLS_CC); return SUCCESS; } /* }}} */ ZEND_API void zend_destroy_modules(void) /* {{{ */ { free(class_cleanup_handlers); free(module_request_startup_handlers); zend_hash_graceful_reverse_destroy(&module_registry); } /* }}} */ ZEND_API zend_module_entry* zend_register_module_ex(zend_module_entry *module TSRMLS_DC) /* {{{ */ { int name_len; char *lcname; zend_module_entry *module_ptr; if (!module) { return NULL; } #if 0 zend_printf("%s: Registering module %d\n", module->name, module->module_number); #endif /* Check module dependencies */ if (module->deps) { const zend_module_dep *dep = module->deps; while (dep->name) { if (dep->type == MODULE_DEP_CONFLICTS) { name_len = strlen(dep->name); lcname = zend_str_tolower_dup(dep->name, name_len); if (zend_hash_exists(&module_registry, lcname, name_len+1)) { efree(lcname); /* TODO: Check version relationship */ zend_error(E_CORE_WARNING, "Cannot load module '%s' because conflicting module '%s' is already loaded", module->name, dep->name); return NULL; } efree(lcname); } ++dep; } } name_len = strlen(module->name); lcname = zend_str_tolower_dup(module->name, name_len); if (zend_hash_add(&module_registry, lcname, name_len+1, (void *)module, sizeof(zend_module_entry), (void**)&module_ptr)==FAILURE) { zend_error(E_CORE_WARNING, "Module '%s' already loaded", module->name); efree(lcname); return NULL; } efree(lcname); module = module_ptr; EG(current_module) = module; if (module->functions && zend_register_functions(NULL, module->functions, NULL, module->type TSRMLS_CC)==FAILURE) { EG(current_module) = NULL; zend_error(E_CORE_WARNING,"%s: Unable to register functions, unable to load", module->name); return NULL; } EG(current_module) = NULL; return module; } /* }}} */ ZEND_API zend_module_entry* zend_register_internal_module(zend_module_entry *module TSRMLS_DC) /* {{{ */ { module->module_number = zend_next_free_module(); module->type = MODULE_PERSISTENT; return zend_register_module_ex(module TSRMLS_CC); } /* }}} */ ZEND_API void zend_check_magic_method_implementation(const zend_class_entry *ce, const zend_function *fptr, int error_type TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(fptr->common.function_name); zend_str_tolower_copy(lcname, fptr->common.function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)) && fptr->common.num_args != 0) { zend_error(error_type, "Destructor %s::%s() cannot take arguments", ce->name, ZEND_DESTRUCTOR_FUNC_NAME); } else if (name_len == sizeof(ZEND_CLONE_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)) && fptr->common.num_args != 0) { zend_error(error_type, "Method %s::%s() cannot accept any arguments", ce->name, ZEND_CLONE_FUNC_NAME); } else if (name_len == sizeof(ZEND_GET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME))) { if (fptr->common.num_args != 1) { zend_error(error_type, "Method %s::%s() must take exactly 1 argument", ce->name, ZEND_GET_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_GET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_SET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME))) { if (fptr->common.num_args != 2) { zend_error(error_type, "Method %s::%s() must take exactly 2 arguments", ce->name, ZEND_SET_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1) || ARG_SHOULD_BE_SENT_BY_REF(fptr, 2)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_SET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_UNSET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME))) { if (fptr->common.num_args != 1) { zend_error(error_type, "Method %s::%s() must take exactly 1 argument", ce->name, ZEND_UNSET_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_UNSET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_ISSET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME))) { if (fptr->common.num_args != 1) { zend_error(error_type, "Method %s::%s() must take exactly 1 argument", ce->name, ZEND_ISSET_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_ISSET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_CALL_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME))) { if (fptr->common.num_args != 2) { zend_error(error_type, "Method %s::%s() must take exactly 2 arguments", ce->name, ZEND_CALL_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1) || ARG_SHOULD_BE_SENT_BY_REF(fptr, 2)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_CALL_FUNC_NAME); } } else if (name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) ) { if (fptr->common.num_args != 2) { zend_error(error_type, "Method %s::%s() must take exactly 2 arguments", ce->name, ZEND_CALLSTATIC_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1) || ARG_SHOULD_BE_SENT_BY_REF(fptr, 2)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_CALLSTATIC_FUNC_NAME); } } else if (name_len == sizeof(ZEND_TOSTRING_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && fptr->common.num_args != 0 ) { zend_error(error_type, "Method %s::%s() cannot take arguments", ce->name, ZEND_TOSTRING_FUNC_NAME); } } /* }}} */ /* registers all functions in *library_functions in the function hash */ ZEND_API int zend_register_functions(zend_class_entry *scope, const zend_function_entry *functions, HashTable *function_table, int type TSRMLS_DC) /* {{{ */ { const zend_function_entry *ptr = functions; zend_function function, *reg_function; zend_internal_function *internal_function = (zend_internal_function *)&function; int count=0, unload=0, result=0; HashTable *target_function_table = function_table; int error_type; zend_function *ctor = NULL, *dtor = NULL, *clone = NULL, *__get = NULL, *__set = NULL, *__unset = NULL, *__isset = NULL, *__call = NULL, *__callstatic = NULL, *__tostring = NULL; const char *lowercase_name; int fname_len; const char *lc_class_name = NULL; int class_name_len = 0; if (type==MODULE_PERSISTENT) { error_type = E_CORE_WARNING; } else { error_type = E_WARNING; } if (!target_function_table) { target_function_table = CG(function_table); } internal_function->type = ZEND_INTERNAL_FUNCTION; internal_function->module = EG(current_module); if (scope) { class_name_len = strlen(scope->name); if ((lc_class_name = zend_memrchr(scope->name, '\\', class_name_len))) { ++lc_class_name; class_name_len -= (lc_class_name - scope->name); lc_class_name = zend_str_tolower_dup(lc_class_name, class_name_len); } else { lc_class_name = zend_str_tolower_dup(scope->name, class_name_len); } } while (ptr->fname) { internal_function->handler = ptr->handler; internal_function->function_name = (char*)ptr->fname; internal_function->scope = scope; internal_function->prototype = NULL; if (ptr->flags) { if (!(ptr->flags & ZEND_ACC_PPP_MASK)) { if (ptr->flags != ZEND_ACC_DEPRECATED || scope) { zend_error(error_type, "Invalid access level for %s%s%s() - access must be exactly one of public, protected or private", scope ? scope->name : "", scope ? "::" : "", ptr->fname); } internal_function->fn_flags = ZEND_ACC_PUBLIC | ptr->flags; } else { internal_function->fn_flags = ptr->flags; } } else { internal_function->fn_flags = ZEND_ACC_PUBLIC; } if (ptr->arg_info) { zend_internal_function_info *info = (zend_internal_function_info*)ptr->arg_info; internal_function->arg_info = (zend_arg_info*)ptr->arg_info+1; internal_function->num_args = ptr->num_args; /* Currently you cannot denote that the function can accept less arguments than num_args */ if (info->required_num_args == -1) { internal_function->required_num_args = ptr->num_args; } else { internal_function->required_num_args = info->required_num_args; } if (info->pass_rest_by_reference) { if (info->pass_rest_by_reference == ZEND_SEND_PREFER_REF) { internal_function->fn_flags |= ZEND_ACC_PASS_REST_PREFER_REF; } else { internal_function->fn_flags |= ZEND_ACC_PASS_REST_BY_REFERENCE; } } if (info->return_reference) { internal_function->fn_flags |= ZEND_ACC_RETURN_REFERENCE; } } else { internal_function->arg_info = NULL; internal_function->num_args = 0; internal_function->required_num_args = 0; } if (ptr->flags & ZEND_ACC_ABSTRACT) { if (scope) { /* This is a class that must be abstract itself. Here we set the check info. */ scope->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; if (!(scope->ce_flags & ZEND_ACC_INTERFACE)) { /* Since the class is not an interface it needs to be declared as a abstract class. */ /* Since here we are handling internal functions only we can add the keyword flag. */ /* This time we set the flag for the keyword 'abstract'. */ scope->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } } if (ptr->flags & ZEND_ACC_STATIC && (!scope || !(scope->ce_flags & ZEND_ACC_INTERFACE))) { zend_error(error_type, "Static function %s%s%s() cannot be abstract", scope ? scope->name : "", scope ? "::" : "", ptr->fname); } } else { if (scope && (scope->ce_flags & ZEND_ACC_INTERFACE)) { efree((char*)lc_class_name); zend_error(error_type, "Interface %s cannot contain non abstract method %s()", scope->name, ptr->fname); return FAILURE; } if (!internal_function->handler) { if (scope) { efree((char*)lc_class_name); } zend_error(error_type, "Method %s%s%s() cannot be a NULL function", scope ? scope->name : "", scope ? "::" : "", ptr->fname); zend_unregister_functions(functions, count, target_function_table TSRMLS_CC); return FAILURE; } } fname_len = strlen(ptr->fname); lowercase_name = zend_new_interned_string(zend_str_tolower_dup(ptr->fname, fname_len), fname_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lowercase_name)) { result = zend_hash_quick_add(target_function_table, lowercase_name, fname_len+1, INTERNED_HASH(lowercase_name), &function, sizeof(zend_function), (void**)&reg_function); } else { result = zend_hash_add(target_function_table, lowercase_name, fname_len+1, &function, sizeof(zend_function), (void**)&reg_function); } if (result == FAILURE) { unload=1; str_efree(lowercase_name); break; } if (scope) { /* Look for ctor, dtor, clone * If it's an old-style constructor, store it only if we don't have * a constructor already. */ if ((fname_len == class_name_len) && !ctor && !memcmp(lowercase_name, lc_class_name, class_name_len+1)) { ctor = reg_function; } else if ((fname_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME))) { ctor = reg_function; } else if ((fname_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME))) { dtor = reg_function; if (internal_function->num_args) { zend_error(error_type, "Destructor %s::%s() cannot take arguments", scope->name, ptr->fname); } } else if ((fname_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME))) { clone = reg_function; } else if ((fname_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME))) { __call = reg_function; } else if ((fname_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME))) { __callstatic = reg_function; } else if ((fname_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME))) { __tostring = reg_function; } else if ((fname_len == sizeof(ZEND_GET_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME))) { __get = reg_function; } else if ((fname_len == sizeof(ZEND_SET_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME))) { __set = reg_function; } else if ((fname_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME))) { __unset = reg_function; } else if ((fname_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME))) { __isset = reg_function; } else { reg_function = NULL; } if (reg_function) { zend_check_magic_method_implementation(scope, reg_function, error_type TSRMLS_CC); } } ptr++; count++; str_efree(lowercase_name); } if (unload) { /* before unloading, display all remaining bad function in the module */ if (scope) { efree((char*)lc_class_name); } while (ptr->fname) { fname_len = strlen(ptr->fname); lowercase_name = zend_str_tolower_dup(ptr->fname, fname_len); if (zend_hash_exists(target_function_table, lowercase_name, fname_len+1)) { zend_error(error_type, "Function registration failed - duplicate name - %s%s%s", scope ? scope->name : "", scope ? "::" : "", ptr->fname); } efree((char*)lowercase_name); ptr++; } zend_unregister_functions(functions, count, target_function_table TSRMLS_CC); return FAILURE; } if (scope) { scope->constructor = ctor; scope->destructor = dtor; scope->clone = clone; scope->__call = __call; scope->__callstatic = __callstatic; scope->__tostring = __tostring; scope->__get = __get; scope->__set = __set; scope->__unset = __unset; scope->__isset = __isset; if (ctor) { ctor->common.fn_flags |= ZEND_ACC_CTOR; if (ctor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Constructor %s::%s() cannot be static", scope->name, ctor->common.function_name); } ctor->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (dtor) { dtor->common.fn_flags |= ZEND_ACC_DTOR; if (dtor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Destructor %s::%s() cannot be static", scope->name, dtor->common.function_name); } dtor->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (clone) { clone->common.fn_flags |= ZEND_ACC_CLONE; if (clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Constructor %s::%s() cannot be static", scope->name, clone->common.function_name); } clone->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__call) { if (__call->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __call->common.function_name); } __call->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__callstatic) { if (!(__callstatic->common.fn_flags & ZEND_ACC_STATIC)) { zend_error(error_type, "Method %s::%s() must be static", scope->name, __callstatic->common.function_name); } __callstatic->common.fn_flags |= ZEND_ACC_STATIC; } if (__tostring) { if (__tostring->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __tostring->common.function_name); } __tostring->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__get) { if (__get->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __get->common.function_name); } __get->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__set) { if (__set->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __set->common.function_name); } __set->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__unset) { if (__unset->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __unset->common.function_name); } __unset->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__isset) { if (__isset->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __isset->common.function_name); } __isset->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } efree((char*)lc_class_name); } return SUCCESS; } /* }}} */ /* count=-1 means erase all functions, otherwise, * erase the first count functions */ ZEND_API void zend_unregister_functions(const zend_function_entry *functions, int count, HashTable *function_table TSRMLS_DC) /* {{{ */ { const zend_function_entry *ptr = functions; int i=0; HashTable *target_function_table = function_table; if (!target_function_table) { target_function_table = CG(function_table); } while (ptr->fname) { if (count!=-1 && i>=count) { break; } #if 0 zend_printf("Unregistering %s()\n", ptr->fname); #endif zend_hash_del(target_function_table, ptr->fname, strlen(ptr->fname)+1); ptr++; i++; } } /* }}} */ ZEND_API int zend_startup_module(zend_module_entry *module) /* {{{ */ { TSRMLS_FETCH(); if ((module = zend_register_internal_module(module TSRMLS_CC)) != NULL && zend_startup_module_ex(module TSRMLS_CC) == SUCCESS) { return SUCCESS; } return FAILURE; } /* }}} */ ZEND_API int zend_get_module_started(const char *module_name) /* {{{ */ { zend_module_entry *module; return (zend_hash_find(&module_registry, module_name, strlen(module_name)+1, (void**)&module) == SUCCESS && module->module_started) ? SUCCESS : FAILURE; } /* }}} */ static int clean_module_class(const zend_class_entry **ce, int *module_number TSRMLS_DC) /* {{{ */ { if ((*ce)->type == ZEND_INTERNAL_CLASS && (*ce)->info.internal.module->module_number == *module_number) { return ZEND_HASH_APPLY_REMOVE; } else { return ZEND_HASH_APPLY_KEEP; } } /* }}} */ static void clean_module_classes(int module_number TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_argument(EG(class_table), (apply_func_arg_t) clean_module_class, (void *) &module_number TSRMLS_CC); } /* }}} */ void module_destructor(zend_module_entry *module) /* {{{ */ { TSRMLS_FETCH(); if (module->type == MODULE_TEMPORARY) { zend_clean_module_rsrc_dtors(module->module_number TSRMLS_CC); clean_module_constants(module->module_number TSRMLS_CC); clean_module_classes(module->module_number TSRMLS_CC); } if (module->module_started && module->module_shutdown_func) { #if 0 zend_printf("%s: Module shutdown\n", module->name); #endif module->module_shutdown_func(module->type, module->module_number TSRMLS_CC); } /* Deinitilaise module globals */ if (module->globals_size) { #ifdef ZTS ts_free_id(*module->globals_id_ptr); #else if (module->globals_dtor) { module->globals_dtor(module->globals_ptr TSRMLS_CC); } #endif } module->module_started=0; if (module->functions) { zend_unregister_functions(module->functions, -1, NULL TSRMLS_CC); } #if HAVE_LIBDL #if !(defined(NETWARE) && defined(APACHE_1_BUILD)) if (module->handle && !getenv("ZEND_DONT_UNLOAD_MODULES")) { DL_UNLOAD(module->handle); } #endif #endif } /* }}} */ void zend_activate_modules(TSRMLS_D) /* {{{ */ { zend_module_entry **p = module_request_startup_handlers; while (*p) { zend_module_entry *module = *p; if (module->request_startup_func(module->type, module->module_number TSRMLS_CC)==FAILURE) { zend_error(E_WARNING, "request_startup() for %s module failed", module->name); exit(1); } p++; } } /* }}} */ /* call request shutdown for all modules */ int module_registry_cleanup(zend_module_entry *module TSRMLS_DC) /* {{{ */ { if (module->request_shutdown_func) { #if 0 zend_printf("%s: Request shutdown\n", module->name); #endif module->request_shutdown_func(module->type, module->module_number TSRMLS_CC); } return 0; } /* }}} */ void zend_deactivate_modules(TSRMLS_D) /* {{{ */ { EG(opline_ptr) = NULL; /* we're no longer executing anything */ zend_try { if (EG(full_tables_cleanup)) { zend_hash_reverse_apply(&module_registry, (apply_func_t) module_registry_cleanup TSRMLS_CC); } else { zend_module_entry **p = module_request_shutdown_handlers; while (*p) { zend_module_entry *module = *p; module->request_shutdown_func(module->type, module->module_number TSRMLS_CC); p++; } } } zend_end_try(); } /* }}} */ ZEND_API void zend_cleanup_internal_classes(TSRMLS_D) /* {{{ */ { zend_class_entry **p = class_cleanup_handlers; while (*p) { zend_cleanup_internal_class_data(*p TSRMLS_CC); p++; } } /* }}} */ int module_registry_unload_temp(const zend_module_entry *module TSRMLS_DC) /* {{{ */ { return (module->type == MODULE_TEMPORARY) ? ZEND_HASH_APPLY_REMOVE : ZEND_HASH_APPLY_STOP; } /* }}} */ static int exec_done_cb(zend_module_entry *module TSRMLS_DC) /* {{{ */ { if (module->post_deactivate_func) { module->post_deactivate_func(); } return 0; } /* }}} */ void zend_post_deactivate_modules(TSRMLS_D) /* {{{ */ { if (EG(full_tables_cleanup)) { zend_hash_apply(&module_registry, (apply_func_t) exec_done_cb TSRMLS_CC); zend_hash_reverse_apply(&module_registry, (apply_func_t) module_registry_unload_temp TSRMLS_CC); } else { zend_module_entry **p = module_post_deactivate_handlers; while (*p) { zend_module_entry *module = *p; module->post_deactivate_func(); p++; } } } /* }}} */ /* return the next free module number */ int zend_next_free_module(void) /* {{{ */ { return ++module_count; } /* }}} */ static zend_class_entry *do_register_internal_class(zend_class_entry *orig_class_entry, zend_uint ce_flags TSRMLS_DC) /* {{{ */ { zend_class_entry *class_entry = malloc(sizeof(zend_class_entry)); char *lowercase_name = emalloc(orig_class_entry->name_length + 1); *class_entry = *orig_class_entry; class_entry->type = ZEND_INTERNAL_CLASS; zend_initialize_class_data(class_entry, 0 TSRMLS_CC); class_entry->ce_flags = ce_flags; class_entry->info.internal.module = EG(current_module); if (class_entry->info.internal.builtin_functions) { zend_register_functions(class_entry, class_entry->info.internal.builtin_functions, &class_entry->function_table, MODULE_PERSISTENT TSRMLS_CC); } zend_str_tolower_copy(lowercase_name, orig_class_entry->name, class_entry->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, class_entry->name_length + 1, 1 TSRMLS_CC); if (IS_INTERNED(lowercase_name)) { zend_hash_quick_update(CG(class_table), lowercase_name, class_entry->name_length+1, INTERNED_HASH(lowercase_name), &class_entry, sizeof(zend_class_entry *), NULL); } else { zend_hash_update(CG(class_table), lowercase_name, class_entry->name_length+1, &class_entry, sizeof(zend_class_entry *), NULL); } str_efree(lowercase_name); return class_entry; } /* }}} */ /* If parent_ce is not NULL then it inherits from parent_ce * If parent_ce is NULL and parent_name isn't then it looks for the parent and inherits from it * If both parent_ce and parent_name are NULL it does a regular class registration * If parent_name is specified but not found NULL is returned */ ZEND_API zend_class_entry *zend_register_internal_class_ex(zend_class_entry *class_entry, zend_class_entry *parent_ce, char *parent_name TSRMLS_DC) /* {{{ */ { zend_class_entry *register_class; if (!parent_ce && parent_name) { zend_class_entry **pce; if (zend_hash_find(CG(class_table), parent_name, strlen(parent_name)+1, (void **) &pce)==FAILURE) { return NULL; } else { parent_ce = *pce; } } register_class = zend_register_internal_class(class_entry TSRMLS_CC); if (parent_ce) { zend_do_inheritance(register_class, parent_ce TSRMLS_CC); } return register_class; } /* }}} */ ZEND_API void zend_class_implements(zend_class_entry *class_entry TSRMLS_DC, int num_interfaces, ...) /* {{{ */ { zend_class_entry *interface_entry; va_list interface_list; va_start(interface_list, num_interfaces); while (num_interfaces--) { interface_entry = va_arg(interface_list, zend_class_entry *); zend_do_implement_interface(class_entry, interface_entry TSRMLS_CC); } va_end(interface_list); } /* }}} */ /* A class that contains at least one abstract method automatically becomes an abstract class. */ ZEND_API zend_class_entry *zend_register_internal_class(zend_class_entry *orig_class_entry TSRMLS_DC) /* {{{ */ { return do_register_internal_class(orig_class_entry, 0 TSRMLS_CC); } /* }}} */ ZEND_API zend_class_entry *zend_register_internal_interface(zend_class_entry *orig_class_entry TSRMLS_DC) /* {{{ */ { return do_register_internal_class(orig_class_entry, ZEND_ACC_INTERFACE TSRMLS_CC); } /* }}} */ ZEND_API int zend_register_class_alias_ex(const char *name, int name_len, zend_class_entry *ce TSRMLS_DC) /* {{{ */ { char *lcname = zend_str_tolower_dup(name, name_len); int ret; ret = zend_hash_add(CG(class_table), lcname, name_len+1, &ce, sizeof(zend_class_entry *), NULL); efree(lcname); if (ret == SUCCESS) { ce->refcount++; } return ret; } /* }}} */ ZEND_API int zend_set_hash_symbol(zval *symbol, const char *name, int name_length, zend_bool is_ref, int num_symbol_tables, ...) /* {{{ */ { HashTable *symbol_table; va_list symbol_table_list; if (num_symbol_tables <= 0) return FAILURE; Z_SET_ISREF_TO_P(symbol, is_ref); va_start(symbol_table_list, num_symbol_tables); while (num_symbol_tables-- > 0) { symbol_table = va_arg(symbol_table_list, HashTable *); zend_hash_update(symbol_table, name, name_length + 1, &symbol, sizeof(zval *), NULL); zval_add_ref(&symbol); } va_end(symbol_table_list); return SUCCESS; } /* }}} */ /* Disabled functions support */ /* {{{ proto void display_disabled_function(void) Dummy function which displays an error when a disabled function is called. */ ZEND_API ZEND_FUNCTION(display_disabled_function) { zend_error(E_WARNING, "%s() has been disabled for security reasons", get_active_function_name(TSRMLS_C)); } /* }}} */ static zend_function_entry disabled_function[] = { ZEND_FE(display_disabled_function, NULL) ZEND_FE_END }; ZEND_API int zend_disable_function(char *function_name, uint function_name_length TSRMLS_DC) /* {{{ */ { if (zend_hash_del(CG(function_table), function_name, function_name_length+1)==FAILURE) { return FAILURE; } disabled_function[0].fname = function_name; return zend_register_functions(NULL, disabled_function, CG(function_table), MODULE_PERSISTENT TSRMLS_CC); } /* }}} */ static zend_object_value display_disabled_class(zend_class_entry *class_type TSRMLS_DC) /* {{{ */ { zend_object_value retval; zend_object *intern; retval = zend_objects_new(&intern, class_type TSRMLS_CC); zend_error(E_WARNING, "%s() has been disabled for security reasons", class_type->name); return retval; } /* }}} */ static const zend_function_entry disabled_class_new[] = { ZEND_FE_END }; ZEND_API int zend_disable_class(char *class_name, uint class_name_length TSRMLS_DC) /* {{{ */ { zend_class_entry disabled_class; zend_str_tolower(class_name, class_name_length); if (zend_hash_del(CG(class_table), class_name, class_name_length+1)==FAILURE) { return FAILURE; } INIT_OVERLOADED_CLASS_ENTRY_EX(disabled_class, class_name, class_name_length, disabled_class_new, NULL, NULL, NULL, NULL, NULL); disabled_class.create_object = display_disabled_class; disabled_class.name_length = class_name_length; zend_register_internal_class(&disabled_class TSRMLS_CC); return SUCCESS; } /* }}} */ static int zend_is_callable_check_class(const char *name, int name_len, zend_fcall_info_cache *fcc, int *strict_class, char **error TSRMLS_DC) /* {{{ */ { int ret = 0; zend_class_entry **pce; char *lcname = zend_str_tolower_dup(name, name_len); *strict_class = 0; if (name_len == sizeof("self") - 1 && !memcmp(lcname, "self", sizeof("self") - 1)) { if (!EG(scope)) { if (error) *error = estrdup("cannot access self:: when no class scope is active"); } else { fcc->called_scope = EG(called_scope); fcc->calling_scope = EG(scope); if (!fcc->object_ptr) { fcc->object_ptr = EG(This); } ret = 1; } } else if (name_len == sizeof("parent") - 1 && !memcmp(lcname, "parent", sizeof("parent") - 1)) { if (!EG(scope)) { if (error) *error = estrdup("cannot access parent:: when no class scope is active"); } else if (!EG(scope)->parent) { if (error) *error = estrdup("cannot access parent:: when current class scope has no parent"); } else { fcc->called_scope = EG(called_scope); fcc->calling_scope = EG(scope)->parent; if (!fcc->object_ptr) { fcc->object_ptr = EG(This); } *strict_class = 1; ret = 1; } } else if (name_len == sizeof("static") - 1 && !memcmp(lcname, "static", sizeof("static") - 1)) { if (!EG(called_scope)) { if (error) *error = estrdup("cannot access static:: when no class scope is active"); } else { fcc->called_scope = EG(called_scope); fcc->calling_scope = EG(called_scope); if (!fcc->object_ptr) { fcc->object_ptr = EG(This); } *strict_class = 1; ret = 1; } } else if (zend_lookup_class_ex(name, name_len, NULL, 1, &pce TSRMLS_CC) == SUCCESS) { zend_class_entry *scope = EG(active_op_array) ? EG(active_op_array)->scope : NULL; fcc->calling_scope = *pce; if (scope && !fcc->object_ptr && EG(This) && instanceof_function(Z_OBJCE_P(EG(This)), scope TSRMLS_CC) && instanceof_function(scope, fcc->calling_scope TSRMLS_CC)) { fcc->object_ptr = EG(This); fcc->called_scope = Z_OBJCE_P(fcc->object_ptr); } else { fcc->called_scope = fcc->object_ptr ? Z_OBJCE_P(fcc->object_ptr) : fcc->calling_scope; } *strict_class = 1; ret = 1; } else { if (error) zend_spprintf(error, 0, "class '%.*s' not found", name_len, name); } efree(lcname); return ret; } /* }}} */ static int zend_is_callable_check_func(int check_flags, zval *callable, zend_fcall_info_cache *fcc, int strict_class, char **error TSRMLS_DC) /* {{{ */ { zend_class_entry *ce_org = fcc->calling_scope; int retval = 0; char *mname, *lmname; const char *colon; int clen, mlen; zend_class_entry *last_scope; HashTable *ftable; int call_via_handler = 0; if (error) { *error = NULL; } fcc->calling_scope = NULL; fcc->function_handler = NULL; if (!ce_org) { /* Skip leading \ */ if (Z_STRVAL_P(callable)[0] == '\\') { mlen = Z_STRLEN_P(callable) - 1; mname = Z_STRVAL_P(callable) + 1; lmname = zend_str_tolower_dup(Z_STRVAL_P(callable) + 1, mlen); } else { mlen = Z_STRLEN_P(callable); mname = Z_STRVAL_P(callable); lmname = zend_str_tolower_dup(Z_STRVAL_P(callable), mlen); } /* Check if function with given name exists. * This may be a compound name that includes namespace name */ if (zend_hash_find(EG(function_table), lmname, mlen+1, (void**)&fcc->function_handler) == SUCCESS) { efree(lmname); return 1; } efree(lmname); } /* Split name into class/namespace and method/function names */ if ((colon = zend_memrchr(Z_STRVAL_P(callable), ':', Z_STRLEN_P(callable))) != NULL && colon > Z_STRVAL_P(callable) && *(colon-1) == ':' ) { colon--; clen = colon - Z_STRVAL_P(callable); mlen = Z_STRLEN_P(callable) - clen - 2; if (colon == Z_STRVAL_P(callable)) { if (error) zend_spprintf(error, 0, "invalid function name"); return 0; } /* This is a compound name. * Try to fetch class and then find static method. */ last_scope = EG(scope); if (ce_org) { EG(scope) = ce_org; } if (!zend_is_callable_check_class(Z_STRVAL_P(callable), clen, fcc, &strict_class, error TSRMLS_CC)) { EG(scope) = last_scope; return 0; } EG(scope) = last_scope; ftable = &fcc->calling_scope->function_table; if (ce_org && !instanceof_function(ce_org, fcc->calling_scope TSRMLS_CC)) { if (error) zend_spprintf(error, 0, "class '%s' is not a subclass of '%s'", ce_org->name, fcc->calling_scope->name); return 0; } mname = Z_STRVAL_P(callable) + clen + 2; } else if (ce_org) { /* Try to fetch find static method of given class. */ mlen = Z_STRLEN_P(callable); mname = Z_STRVAL_P(callable); ftable = &ce_org->function_table; fcc->calling_scope = ce_org; } else { /* We already checked for plain function before. */ if (error && !(check_flags & IS_CALLABLE_CHECK_SILENT)) { zend_spprintf(error, 0, "function '%s' not found or invalid function name", Z_STRVAL_P(callable)); } return 0; } lmname = zend_str_tolower_dup(mname, mlen); if (strict_class && fcc->calling_scope && mlen == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1 && !memcmp(lmname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME))) { fcc->function_handler = fcc->calling_scope->constructor; if (fcc->function_handler) { retval = 1; } } else if (zend_hash_find(ftable, lmname, mlen+1, (void**)&fcc->function_handler) == SUCCESS) { retval = 1; if ((fcc->function_handler->op_array.fn_flags & ZEND_ACC_CHANGED) && EG(scope) && instanceof_function(fcc->function_handler->common.scope, EG(scope) TSRMLS_CC)) { zend_function *priv_fbc; if (zend_hash_find(&EG(scope)->function_table, lmname, mlen+1, (void **) &priv_fbc)==SUCCESS && priv_fbc->common.fn_flags & ZEND_ACC_PRIVATE && priv_fbc->common.scope == EG(scope)) { fcc->function_handler = priv_fbc; } } if ((check_flags & IS_CALLABLE_CHECK_NO_ACCESS) == 0 && (fcc->calling_scope && (fcc->calling_scope->__call || fcc->calling_scope->__callstatic))) { if (fcc->function_handler->op_array.fn_flags & ZEND_ACC_PRIVATE) { if (!zend_check_private(fcc->function_handler, fcc->object_ptr ? Z_OBJCE_P(fcc->object_ptr) : EG(scope), lmname, mlen TSRMLS_CC)) { retval = 0; fcc->function_handler = NULL; goto get_function_via_handler; } } else if (fcc->function_handler->common.fn_flags & ZEND_ACC_PROTECTED) { if (!zend_check_protected(fcc->function_handler->common.scope, EG(scope))) { retval = 0; fcc->function_handler = NULL; goto get_function_via_handler; } } } } else { get_function_via_handler: if (fcc->object_ptr && fcc->calling_scope == ce_org) { if (strict_class && ce_org->__call) { fcc->function_handler = emalloc(sizeof(zend_internal_function)); fcc->function_handler->internal_function.type = ZEND_INTERNAL_FUNCTION; fcc->function_handler->internal_function.module = (ce_org->type == ZEND_INTERNAL_CLASS) ? ce_org->info.internal.module : NULL; fcc->function_handler->internal_function.handler = zend_std_call_user_call; fcc->function_handler->internal_function.arg_info = NULL; fcc->function_handler->internal_function.num_args = 0; fcc->function_handler->internal_function.scope = ce_org; fcc->function_handler->internal_function.fn_flags = ZEND_ACC_CALL_VIA_HANDLER; fcc->function_handler->internal_function.function_name = estrndup(mname, mlen); call_via_handler = 1; retval = 1; } else if (Z_OBJ_HT_P(fcc->object_ptr)->get_method) { fcc->function_handler = Z_OBJ_HT_P(fcc->object_ptr)->get_method(&fcc->object_ptr, mname, mlen, NULL TSRMLS_CC); if (fcc->function_handler) { if (strict_class && (!fcc->function_handler->common.scope || !instanceof_function(ce_org, fcc->function_handler->common.scope TSRMLS_CC))) { if ((fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) != 0) { if (fcc->function_handler->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fcc->function_handler->common.function_name); } efree(fcc->function_handler); } } else { retval = 1; call_via_handler = (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) != 0; } } } } else if (fcc->calling_scope) { if (fcc->calling_scope->get_static_method) { fcc->function_handler = fcc->calling_scope->get_static_method(fcc->calling_scope, mname, mlen TSRMLS_CC); } else { fcc->function_handler = zend_std_get_static_method(fcc->calling_scope, mname, mlen, NULL TSRMLS_CC); } if (fcc->function_handler) { retval = 1; call_via_handler = (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) != 0; if (call_via_handler && !fcc->object_ptr && EG(This) && Z_OBJ_HT_P(EG(This))->get_class_entry && instanceof_function(Z_OBJCE_P(EG(This)), fcc->calling_scope TSRMLS_CC)) { fcc->object_ptr = EG(This); } } } } if (retval) { if (fcc->calling_scope && !call_via_handler) { if (!fcc->object_ptr && !(fcc->function_handler->common.fn_flags & ZEND_ACC_STATIC)) { int severity; char *verb; if (fcc->function_handler->common.fn_flags & ZEND_ACC_ALLOW_STATIC) { severity = E_STRICT; verb = "should not"; } else { /* An internal function assumes $this is present and won't check that. So PHP would crash by allowing the call. */ severity = E_ERROR; verb = "cannot"; } if ((check_flags & IS_CALLABLE_CHECK_IS_STATIC) != 0) { retval = 0; } if (EG(This) && instanceof_function(Z_OBJCE_P(EG(This)), fcc->calling_scope TSRMLS_CC)) { fcc->object_ptr = EG(This); if (error) { zend_spprintf(error, 0, "non-static method %s::%s() %s be called statically, assuming $this from compatible context %s", fcc->calling_scope->name, fcc->function_handler->common.function_name, verb, Z_OBJCE_P(EG(This))->name); if (severity == E_ERROR) { retval = 0; } } else if (retval) { zend_error(severity, "Non-static method %s::%s() %s be called statically, assuming $this from compatible context %s", fcc->calling_scope->name, fcc->function_handler->common.function_name, verb, Z_OBJCE_P(EG(This))->name); } } else { if (error) { zend_spprintf(error, 0, "non-static method %s::%s() %s be called statically", fcc->calling_scope->name, fcc->function_handler->common.function_name, verb); if (severity == E_ERROR) { retval = 0; } } else if (retval) { zend_error(severity, "Non-static method %s::%s() %s be called statically", fcc->calling_scope->name, fcc->function_handler->common.function_name, verb); } } } if (retval && (check_flags & IS_CALLABLE_CHECK_NO_ACCESS) == 0) { if (fcc->function_handler->op_array.fn_flags & ZEND_ACC_PRIVATE) { if (!zend_check_private(fcc->function_handler, fcc->object_ptr ? Z_OBJCE_P(fcc->object_ptr) : EG(scope), lmname, mlen TSRMLS_CC)) { if (error) { if (*error) { efree(*error); } zend_spprintf(error, 0, "cannot access private method %s::%s()", fcc->calling_scope->name, fcc->function_handler->common.function_name); } retval = 0; } } else if ((fcc->function_handler->common.fn_flags & ZEND_ACC_PROTECTED)) { if (!zend_check_protected(fcc->function_handler->common.scope, EG(scope))) { if (error) { if (*error) { efree(*error); } zend_spprintf(error, 0, "cannot access protected method %s::%s()", fcc->calling_scope->name, fcc->function_handler->common.function_name); } retval = 0; } } } } } else if (error && !(check_flags & IS_CALLABLE_CHECK_SILENT)) { if (fcc->calling_scope) { if (error) zend_spprintf(error, 0, "class '%s' does not have a method '%s'", fcc->calling_scope->name, mname); } else { if (error) zend_spprintf(error, 0, "function '%s' does not exist", mname); } } efree(lmname); if (fcc->object_ptr) { fcc->called_scope = Z_OBJCE_P(fcc->object_ptr); } if (retval) { fcc->initialized = 1; } return retval; } /* }}} */ ZEND_API zend_bool zend_is_callable_ex(zval *callable, zval *object_ptr, uint check_flags, char **callable_name, int *callable_name_len, zend_fcall_info_cache *fcc, char **error TSRMLS_DC) /* {{{ */ { zend_bool ret; int callable_name_len_local; zend_fcall_info_cache fcc_local; if (callable_name) { *callable_name = NULL; } if (callable_name_len == NULL) { callable_name_len = &callable_name_len_local; } if (fcc == NULL) { fcc = &fcc_local; } if (error) { *error = NULL; } fcc->initialized = 0; fcc->calling_scope = NULL; fcc->called_scope = NULL; fcc->function_handler = NULL; fcc->calling_scope = NULL; fcc->object_ptr = NULL; if (object_ptr && Z_TYPE_P(object_ptr) != IS_OBJECT) { object_ptr = NULL; } if (object_ptr && (!EG(objects_store).object_buckets || !EG(objects_store).object_buckets[Z_OBJ_HANDLE_P(object_ptr)].valid)) { return 0; } switch (Z_TYPE_P(callable)) { case IS_STRING: if (object_ptr) { fcc->object_ptr = object_ptr; fcc->calling_scope = Z_OBJCE_P(object_ptr); if (callable_name) { char *ptr; *callable_name_len = fcc->calling_scope->name_length + Z_STRLEN_P(callable) + sizeof("::") - 1; ptr = *callable_name = emalloc(*callable_name_len + 1); memcpy(ptr, fcc->calling_scope->name, fcc->calling_scope->name_length); ptr += fcc->calling_scope->name_length; memcpy(ptr, "::", sizeof("::") - 1); ptr += sizeof("::") - 1; memcpy(ptr, Z_STRVAL_P(callable), Z_STRLEN_P(callable) + 1); } } else if (callable_name) { *callable_name = estrndup(Z_STRVAL_P(callable), Z_STRLEN_P(callable)); *callable_name_len = Z_STRLEN_P(callable); } if (check_flags & IS_CALLABLE_CHECK_SYNTAX_ONLY) { fcc->called_scope = fcc->calling_scope; return 1; } ret = zend_is_callable_check_func(check_flags, callable, fcc, 0, error TSRMLS_CC); if (fcc == &fcc_local && fcc->function_handler && ((fcc->function_handler->type == ZEND_INTERNAL_FUNCTION && (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER)) || fcc->function_handler->type == ZEND_OVERLOADED_FUNCTION_TEMPORARY || fcc->function_handler->type == ZEND_OVERLOADED_FUNCTION)) { if (fcc->function_handler->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fcc->function_handler->common.function_name); } efree(fcc->function_handler); } return ret; case IS_ARRAY: { zval **method = NULL; zval **obj = NULL; int strict_class = 0; if (zend_hash_num_elements(Z_ARRVAL_P(callable)) == 2) { zend_hash_index_find(Z_ARRVAL_P(callable), 0, (void **) &obj); zend_hash_index_find(Z_ARRVAL_P(callable), 1, (void **) &method); } if (obj && method && (Z_TYPE_PP(obj) == IS_OBJECT || Z_TYPE_PP(obj) == IS_STRING) && Z_TYPE_PP(method) == IS_STRING) { if (Z_TYPE_PP(obj) == IS_STRING) { if (callable_name) { char *ptr; *callable_name_len = Z_STRLEN_PP(obj) + Z_STRLEN_PP(method) + sizeof("::") - 1; ptr = *callable_name = emalloc(*callable_name_len + 1); memcpy(ptr, Z_STRVAL_PP(obj), Z_STRLEN_PP(obj)); ptr += Z_STRLEN_PP(obj); memcpy(ptr, "::", sizeof("::") - 1); ptr += sizeof("::") - 1; memcpy(ptr, Z_STRVAL_PP(method), Z_STRLEN_PP(method) + 1); } if (check_flags & IS_CALLABLE_CHECK_SYNTAX_ONLY) { return 1; } if (!zend_is_callable_check_class(Z_STRVAL_PP(obj), Z_STRLEN_PP(obj), fcc, &strict_class, error TSRMLS_CC)) { return 0; } } else { if (!EG(objects_store).object_buckets || !EG(objects_store).object_buckets[Z_OBJ_HANDLE_PP(obj)].valid) { return 0; } fcc->calling_scope = Z_OBJCE_PP(obj); /* TBFixed: what if it's overloaded? */ fcc->object_ptr = *obj; if (callable_name) { char *ptr; *callable_name_len = fcc->calling_scope->name_length + Z_STRLEN_PP(method) + sizeof("::") - 1; ptr = *callable_name = emalloc(*callable_name_len + 1); memcpy(ptr, fcc->calling_scope->name, fcc->calling_scope->name_length); ptr += fcc->calling_scope->name_length; memcpy(ptr, "::", sizeof("::") - 1); ptr += sizeof("::") - 1; memcpy(ptr, Z_STRVAL_PP(method), Z_STRLEN_PP(method) + 1); } if (check_flags & IS_CALLABLE_CHECK_SYNTAX_ONLY) { fcc->called_scope = fcc->calling_scope; return 1; } } ret = zend_is_callable_check_func(check_flags, *method, fcc, strict_class, error TSRMLS_CC); if (fcc == &fcc_local && fcc->function_handler && ((fcc->function_handler->type == ZEND_INTERNAL_FUNCTION && (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER)) || fcc->function_handler->type == ZEND_OVERLOADED_FUNCTION_TEMPORARY || fcc->function_handler->type == ZEND_OVERLOADED_FUNCTION)) { if (fcc->function_handler->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fcc->function_handler->common.function_name); } efree(fcc->function_handler); } return ret; } else { if (zend_hash_num_elements(Z_ARRVAL_P(callable)) == 2) { if (!obj || (Z_TYPE_PP(obj) != IS_STRING && Z_TYPE_PP(obj) != IS_OBJECT)) { if (error) zend_spprintf(error, 0, "first array member is not a valid class name or object"); } else { if (error) zend_spprintf(error, 0, "second array member is not a valid method"); } } else { if (error) zend_spprintf(error, 0, "array must have exactly two members"); } if (callable_name) { *callable_name = estrndup("Array", sizeof("Array")-1); *callable_name_len = sizeof("Array") - 1; } } } return 0; case IS_OBJECT: if (Z_OBJ_HANDLER_P(callable, get_closure) && Z_OBJ_HANDLER_P(callable, get_closure)(callable, &fcc->calling_scope, &fcc->function_handler, &fcc->object_ptr TSRMLS_CC) == SUCCESS) { fcc->called_scope = fcc->calling_scope; if (callable_name) { zend_class_entry *ce = Z_OBJCE_P(callable); /* TBFixed: what if it's overloaded? */ *callable_name_len = ce->name_length + sizeof("::__invoke") - 1; *callable_name = emalloc(*callable_name_len + 1); memcpy(*callable_name, ce->name, ce->name_length); memcpy((*callable_name) + ce->name_length, "::__invoke", sizeof("::__invoke")); } return 1; } /* break missing intentionally */ default: if (callable_name) { zval expr_copy; int use_copy; zend_make_printable_zval(callable, &expr_copy, &use_copy); *callable_name = estrndup(Z_STRVAL(expr_copy), Z_STRLEN(expr_copy)); *callable_name_len = Z_STRLEN(expr_copy); zval_dtor(&expr_copy); } if (error) zend_spprintf(error, 0, "no array or string given"); return 0; } } /* }}} */ ZEND_API zend_bool zend_is_callable(zval *callable, uint check_flags, char **callable_name TSRMLS_DC) /* {{{ */ { return zend_is_callable_ex(callable, NULL, check_flags, callable_name, NULL, NULL, NULL TSRMLS_CC); } /* }}} */ ZEND_API zend_bool zend_make_callable(zval *callable, char **callable_name TSRMLS_DC) /* {{{ */ { zend_fcall_info_cache fcc; if (zend_is_callable_ex(callable, NULL, IS_CALLABLE_STRICT, callable_name, NULL, &fcc, NULL TSRMLS_CC)) { if (Z_TYPE_P(callable) == IS_STRING && fcc.calling_scope) { zval_dtor(callable); array_init(callable); add_next_index_string(callable, fcc.calling_scope->name, 1); add_next_index_string(callable, fcc.function_handler->common.function_name, 1); } if (fcc.function_handler && ((fcc.function_handler->type == ZEND_INTERNAL_FUNCTION && (fcc.function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER)) || fcc.function_handler->type == ZEND_OVERLOADED_FUNCTION_TEMPORARY || fcc.function_handler->type == ZEND_OVERLOADED_FUNCTION)) { if (fcc.function_handler->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fcc.function_handler->common.function_name); } efree(fcc.function_handler); } return 1; } return 0; } /* }}} */ ZEND_API int zend_fcall_info_init(zval *callable, uint check_flags, zend_fcall_info *fci, zend_fcall_info_cache *fcc, char **callable_name, char **error TSRMLS_DC) /* {{{ */ { if (!zend_is_callable_ex(callable, NULL, check_flags, callable_name, NULL, fcc, error TSRMLS_CC)) { return FAILURE; } fci->size = sizeof(*fci); fci->function_table = fcc->calling_scope ? &fcc->calling_scope->function_table : EG(function_table); fci->object_ptr = fcc->object_ptr; fci->function_name = callable; fci->retval_ptr_ptr = NULL; fci->param_count = 0; fci->params = NULL; fci->no_separation = 1; fci->symbol_table = NULL; return SUCCESS; } /* }}} */ ZEND_API void zend_fcall_info_args_clear(zend_fcall_info *fci, int free_mem) /* {{{ */ { if (fci->params) { if (free_mem) { efree(fci->params); fci->params = NULL; } } fci->param_count = 0; } /* }}} */ ZEND_API void zend_fcall_info_args_save(zend_fcall_info *fci, int *param_count, zval ****params) /* {{{ */ { *param_count = fci->param_count; *params = fci->params; fci->param_count = 0; fci->params = NULL; } /* }}} */ ZEND_API void zend_fcall_info_args_restore(zend_fcall_info *fci, int param_count, zval ***params) /* {{{ */ { zend_fcall_info_args_clear(fci, 1); fci->param_count = param_count; fci->params = params; } /* }}} */ ZEND_API int zend_fcall_info_args(zend_fcall_info *fci, zval *args TSRMLS_DC) /* {{{ */ { HashPosition pos; zval **arg, ***params; zend_fcall_info_args_clear(fci, !args); if (!args) { return SUCCESS; } if (Z_TYPE_P(args) != IS_ARRAY) { return FAILURE; } fci->param_count = zend_hash_num_elements(Z_ARRVAL_P(args)); fci->params = params = (zval ***) erealloc(fci->params, fci->param_count * sizeof(zval **)); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(args), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(args), (void *) &arg, &pos) == SUCCESS) { *params++ = arg; zend_hash_move_forward_ex(Z_ARRVAL_P(args), &pos); } return SUCCESS; } /* }}} */ ZEND_API int zend_fcall_info_argp(zend_fcall_info *fci TSRMLS_DC, int argc, zval ***argv) /* {{{ */ { int i; if (argc < 0) { return FAILURE; } zend_fcall_info_args_clear(fci, !argc); if (argc) { fci->param_count = argc; fci->params = (zval ***) erealloc(fci->params, fci->param_count * sizeof(zval **)); for (i = 0; i < argc; ++i) { fci->params[i] = argv[i]; } } return SUCCESS; } /* }}} */ ZEND_API int zend_fcall_info_argv(zend_fcall_info *fci TSRMLS_DC, int argc, va_list *argv) /* {{{ */ { int i; zval **arg; if (argc < 0) { return FAILURE; } zend_fcall_info_args_clear(fci, !argc); if (argc) { fci->param_count = argc; fci->params = (zval ***) erealloc(fci->params, fci->param_count * sizeof(zval **)); for (i = 0; i < argc; ++i) { arg = va_arg(*argv, zval **); fci->params[i] = arg; } } return SUCCESS; } /* }}} */ ZEND_API int zend_fcall_info_argn(zend_fcall_info *fci TSRMLS_DC, int argc, ...) /* {{{ */ { int ret; va_list argv; va_start(argv, argc); ret = zend_fcall_info_argv(fci TSRMLS_CC, argc, &argv); va_end(argv); return ret; } /* }}} */ ZEND_API int zend_fcall_info_call(zend_fcall_info *fci, zend_fcall_info_cache *fcc, zval **retval_ptr_ptr, zval *args TSRMLS_DC) /* {{{ */ { zval *retval, ***org_params = NULL; int result, org_count = 0; fci->retval_ptr_ptr = retval_ptr_ptr ? retval_ptr_ptr : &retval; if (args) { zend_fcall_info_args_save(fci, &org_count, &org_params); zend_fcall_info_args(fci, args TSRMLS_CC); } result = zend_call_function(fci, fcc TSRMLS_CC); if (!retval_ptr_ptr && retval) { zval_ptr_dtor(&retval); } if (args) { zend_fcall_info_args_restore(fci, org_count, org_params); } return result; } /* }}} */ ZEND_API const char *zend_get_module_version(const char *module_name) /* {{{ */ { char *lname; int name_len = strlen(module_name); zend_module_entry *module; lname = zend_str_tolower_dup(module_name, name_len); if (zend_hash_find(&module_registry, lname, name_len + 1, (void**)&module) == FAILURE) { efree(lname); return NULL; } efree(lname); return module->version; } /* }}} */ ZEND_API int zend_declare_property_ex(zend_class_entry *ce, const char *name, int name_length, zval *property, int access_type, const char *doc_comment, int doc_comment_len TSRMLS_DC) /* {{{ */ { zend_property_info property_info, *property_info_ptr; const char *interned_name; ulong h = zend_get_hash_value(name, name_length+1); if (!(access_type & ZEND_ACC_PPP_MASK)) { access_type |= ZEND_ACC_PUBLIC; } if (access_type & ZEND_ACC_STATIC) { if (zend_hash_quick_find(&ce->properties_info, name, name_length + 1, h, (void**)&property_info_ptr) == SUCCESS && (property_info_ptr->flags & ZEND_ACC_STATIC) != 0) { property_info.offset = property_info_ptr->offset; zval_ptr_dtor(&ce->default_static_members_table[property_info.offset]); zend_hash_quick_del(&ce->properties_info, name, name_length + 1, h); } else { property_info.offset = ce->default_static_members_count++; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(zval*) * ce->default_static_members_count, ce->type == ZEND_INTERNAL_CLASS); } ce->default_static_members_table[property_info.offset] = property; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } else { if (zend_hash_quick_find(&ce->properties_info, name, name_length + 1, h, (void**)&property_info_ptr) == SUCCESS && (property_info_ptr->flags & ZEND_ACC_STATIC) == 0) { property_info.offset = property_info_ptr->offset; zval_ptr_dtor(&ce->default_properties_table[property_info.offset]); zend_hash_quick_del(&ce->properties_info, name, name_length + 1, h); } else { property_info.offset = ce->default_properties_count++; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(zval*) * ce->default_properties_count, ce->type == ZEND_INTERNAL_CLASS); } ce->default_properties_table[property_info.offset] = property; } if (ce->type & ZEND_INTERNAL_CLASS) { switch(Z_TYPE_P(property)) { case IS_ARRAY: case IS_CONSTANT_ARRAY: case IS_OBJECT: case IS_RESOURCE: zend_error(E_CORE_ERROR, "Internal zval's can't be arrays, objects or resources"); break; default: break; } } switch (access_type & ZEND_ACC_PPP_MASK) { case ZEND_ACC_PRIVATE: { char *priv_name; int priv_name_length; zend_mangle_property_name(&priv_name, &priv_name_length, ce->name, ce->name_length, name, name_length, ce->type & ZEND_INTERNAL_CLASS); property_info.name = priv_name; property_info.name_length = priv_name_length; } break; case ZEND_ACC_PROTECTED: { char *prot_name; int prot_name_length; zend_mangle_property_name(&prot_name, &prot_name_length, "*", 1, name, name_length, ce->type & ZEND_INTERNAL_CLASS); property_info.name = prot_name; property_info.name_length = prot_name_length; } break; case ZEND_ACC_PUBLIC: if (IS_INTERNED(name)) { property_info.name = (char*)name; } else { property_info.name = ce->type & ZEND_INTERNAL_CLASS ? zend_strndup(name, name_length) : estrndup(name, name_length); } property_info.name_length = name_length; break; } interned_name = zend_new_interned_string(property_info.name, property_info.name_length+1, 0 TSRMLS_CC); if (interned_name != property_info.name) { if (ce->type == ZEND_USER_CLASS) { efree((char*)property_info.name); } else { free((char*)property_info.name); } property_info.name = interned_name; } property_info.flags = access_type; property_info.h = (access_type & ZEND_ACC_PUBLIC) ? h : zend_get_hash_value(property_info.name, property_info.name_length+1); property_info.doc_comment = doc_comment; property_info.doc_comment_len = doc_comment_len; property_info.ce = ce; zend_hash_quick_update(&ce->properties_info, name, name_length+1, h, &property_info, sizeof(zend_property_info), NULL); return SUCCESS; } /* }}} */ ZEND_API int zend_declare_property(zend_class_entry *ce, const char *name, int name_length, zval *property, int access_type TSRMLS_DC) /* {{{ */ { return zend_declare_property_ex(ce, name, name_length, property, access_type, NULL, 0 TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_null(zend_class_entry *ce, const char *name, int name_length, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); } else { ALLOC_ZVAL(property); } INIT_ZVAL(*property); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_bool(zend_class_entry *ce, const char *name, int name_length, long value, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); } else { ALLOC_ZVAL(property); } INIT_PZVAL(property); ZVAL_BOOL(property, value); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_long(zend_class_entry *ce, const char *name, int name_length, long value, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); } else { ALLOC_ZVAL(property); } INIT_PZVAL(property); ZVAL_LONG(property, value); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_double(zend_class_entry *ce, const char *name, int name_length, double value, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); } else { ALLOC_ZVAL(property); } INIT_PZVAL(property); ZVAL_DOUBLE(property, value); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_string(zend_class_entry *ce, const char *name, int name_length, const char *value, int access_type TSRMLS_DC) /* {{{ */ { zval *property; int len = strlen(value); if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); ZVAL_STRINGL(property, zend_strndup(value, len), len, 0); } else { ALLOC_ZVAL(property); ZVAL_STRINGL(property, value, len, 1); } INIT_PZVAL(property); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_stringl(zend_class_entry *ce, const char *name, int name_length, const char *value, int value_len, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); ZVAL_STRINGL(property, zend_strndup(value, value_len), value_len, 0); } else { ALLOC_ZVAL(property); ZVAL_STRINGL(property, value, value_len, 1); } INIT_PZVAL(property); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant(zend_class_entry *ce, const char *name, size_t name_length, zval *value TSRMLS_DC) /* {{{ */ { return zend_hash_update(&ce->constants_table, name, name_length+1, &value, sizeof(zval *), NULL); } /* }}} */ ZEND_API int zend_declare_class_constant_null(zend_class_entry *ce, const char *name, size_t name_length TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); } else { ALLOC_ZVAL(constant); } ZVAL_NULL(constant); INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_long(zend_class_entry *ce, const char *name, size_t name_length, long value TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); } else { ALLOC_ZVAL(constant); } ZVAL_LONG(constant, value); INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_bool(zend_class_entry *ce, const char *name, size_t name_length, zend_bool value TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); } else { ALLOC_ZVAL(constant); } ZVAL_BOOL(constant, value); INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_double(zend_class_entry *ce, const char *name, size_t name_length, double value TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); } else { ALLOC_ZVAL(constant); } ZVAL_DOUBLE(constant, value); INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_stringl(zend_class_entry *ce, const char *name, size_t name_length, const char *value, size_t value_length TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); ZVAL_STRINGL(constant, zend_strndup(value, value_length), value_length, 0); } else { ALLOC_ZVAL(constant); ZVAL_STRINGL(constant, value, value_length, 1); } INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_string(zend_class_entry *ce, const char *name, size_t name_length, const char *value TSRMLS_DC) /* {{{ */ { return zend_declare_class_constant_stringl(ce, name, name_length, value, strlen(value) TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property(zend_class_entry *scope, zval *object, const char *name, int name_length, zval *value TSRMLS_DC) /* {{{ */ { zval *property; zend_class_entry *old_scope = EG(scope); EG(scope) = scope; if (!Z_OBJ_HT_P(object)->write_property) { const char *class_name; zend_uint class_name_len; zend_get_object_classname(object, &class_name, &class_name_len TSRMLS_CC); zend_error(E_CORE_ERROR, "Property %s of class %s cannot be updated", name, class_name); } MAKE_STD_ZVAL(property); ZVAL_STRINGL(property, name, name_length, 1); Z_OBJ_HT_P(object)->write_property(object, property, value, 0 TSRMLS_CC); zval_ptr_dtor(&property); EG(scope) = old_scope; } /* }}} */ ZEND_API void zend_update_property_null(zend_class_entry *scope, zval *object, const char *name, int name_length TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_NULL(tmp); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_bool(zend_class_entry *scope, zval *object, const char *name, int name_length, long value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_BOOL(tmp, value); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_long(zend_class_entry *scope, zval *object, const char *name, int name_length, long value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_LONG(tmp, value); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_double(zend_class_entry *scope, zval *object, const char *name, int name_length, double value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_DOUBLE(tmp, value); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_string(zend_class_entry *scope, zval *object, const char *name, int name_length, const char *value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_STRING(tmp, value, 1); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_stringl(zend_class_entry *scope, zval *object, const char *name, int name_length, const char *value, int value_len TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_STRINGL(tmp, value, value_len, 1); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property(zend_class_entry *scope, const char *name, int name_length, zval *value TSRMLS_DC) /* {{{ */ { zval **property; zend_class_entry *old_scope = EG(scope); EG(scope) = scope; property = zend_std_get_static_property(scope, name, name_length, 0, NULL TSRMLS_CC); EG(scope) = old_scope; if (!property) { return FAILURE; } else { if (*property != value) { if (PZVAL_IS_REF(*property)) { zval_dtor(*property); Z_TYPE_PP(property) = Z_TYPE_P(value); (*property)->value = value->value; if (Z_REFCOUNT_P(value) > 0) { zval_copy_ctor(*property); } } else { zval *garbage = *property; Z_ADDREF_P(value); if (PZVAL_IS_REF(value)) { SEPARATE_ZVAL(&value); } *property = value; zval_ptr_dtor(&garbage); } } return SUCCESS; } } /* }}} */ ZEND_API int zend_update_static_property_null(zend_class_entry *scope, const char *name, int name_length TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_NULL(tmp); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_bool(zend_class_entry *scope, const char *name, int name_length, long value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_BOOL(tmp, value); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_long(zend_class_entry *scope, const char *name, int name_length, long value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_LONG(tmp, value); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_double(zend_class_entry *scope, const char *name, int name_length, double value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_DOUBLE(tmp, value); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_string(zend_class_entry *scope, const char *name, int name_length, const char *value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_STRING(tmp, value, 1); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_stringl(zend_class_entry *scope, const char *name, int name_length, const char *value, int value_len TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_STRINGL(tmp, value, value_len, 1); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API zval *zend_read_property(zend_class_entry *scope, zval *object, const char *name, int name_length, zend_bool silent TSRMLS_DC) /* {{{ */ { zval *property, *value; zend_class_entry *old_scope = EG(scope); EG(scope) = scope; if (!Z_OBJ_HT_P(object)->read_property) { const char *class_name; zend_uint class_name_len; zend_get_object_classname(object, &class_name, &class_name_len TSRMLS_CC); zend_error(E_CORE_ERROR, "Property %s of class %s cannot be read", name, class_name); } MAKE_STD_ZVAL(property); ZVAL_STRINGL(property, name, name_length, 1); value = Z_OBJ_HT_P(object)->read_property(object, property, silent?BP_VAR_IS:BP_VAR_R, 0 TSRMLS_CC); zval_ptr_dtor(&property); EG(scope) = old_scope; return value; } /* }}} */ ZEND_API zval *zend_read_static_property(zend_class_entry *scope, const char *name, int name_length, zend_bool silent TSRMLS_DC) /* {{{ */ { zval **property; zend_class_entry *old_scope = EG(scope); EG(scope) = scope; property = zend_std_get_static_property(scope, name, name_length, silent, NULL TSRMLS_CC); EG(scope) = old_scope; return property?*property:NULL; } /* }}} */ ZEND_API void zend_save_error_handling(zend_error_handling *current TSRMLS_DC) /* {{{ */ { current->handling = EG(error_handling); current->exception = EG(exception_class); current->user_handler = EG(user_error_handler); if (current->user_handler) { Z_ADDREF_P(current->user_handler); } } /* }}} */ ZEND_API void zend_replace_error_handling(zend_error_handling_t error_handling, zend_class_entry *exception_class, zend_error_handling *current TSRMLS_DC) /* {{{ */ { if (current) { zend_save_error_handling(current TSRMLS_CC); if (error_handling != EH_NORMAL && EG(user_error_handler)) { zval_ptr_dtor(&EG(user_error_handler)); EG(user_error_handler) = NULL; } } EG(error_handling) = error_handling; EG(exception_class) = error_handling == EH_THROW ? exception_class : NULL; } /* }}} */ ZEND_API void zend_restore_error_handling(zend_error_handling *saved TSRMLS_DC) /* {{{ */ { EG(error_handling) = saved->handling; EG(exception_class) = saved->handling == EH_THROW ? saved->exception : NULL; if (saved->user_handler && saved->user_handler != EG(user_error_handler)) { if (EG(user_error_handler)) { zval_ptr_dtor(&EG(user_error_handler)); } EG(user_error_handler) = saved->user_handler; } else if (saved->user_handler) { zval_ptr_dtor(&saved->user_handler); } saved->user_handler = NULL; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */ /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | Andrei Zmievski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "zend.h" #include "zend_execute.h" #include "zend_API.h" #include "zend_modules.h" #include "zend_constants.h" #include "zend_exceptions.h" #include "zend_closures.h" #ifdef HAVE_STDARG_H #include <stdarg.h> #endif /* these variables are true statics/globals, and have to be mutex'ed on every access */ static int module_count=0; ZEND_API HashTable module_registry; static zend_module_entry **module_request_startup_handlers; static zend_module_entry **module_request_shutdown_handlers; static zend_module_entry **module_post_deactivate_handlers; static zend_class_entry **class_cleanup_handlers; /* this function doesn't check for too many parameters */ ZEND_API int zend_get_parameters(int ht, int param_count, ...) /* {{{ */ { void **p; int arg_count; va_list ptr; zval **param, *param_ptr; TSRMLS_FETCH(); p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } va_start(ptr, param_count); while (param_count-->0) { param = va_arg(ptr, zval **); param_ptr = *(p-arg_count); if (!PZVAL_IS_REF(param_ptr) && Z_REFCOUNT_P(param_ptr) > 1) { zval *new_tmp; ALLOC_ZVAL(new_tmp); *new_tmp = *param_ptr; zval_copy_ctor(new_tmp); INIT_PZVAL(new_tmp); param_ptr = new_tmp; Z_DELREF_P((zval *) *(p-arg_count)); *(p-arg_count) = param_ptr; } *param = param_ptr; arg_count--; } va_end(ptr); return SUCCESS; } /* }}} */ ZEND_API int _zend_get_parameters_array(int ht, int param_count, zval **argument_array TSRMLS_DC) /* {{{ */ { void **p; int arg_count; zval *param_ptr; p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } while (param_count-->0) { param_ptr = *(p-arg_count); if (!PZVAL_IS_REF(param_ptr) && Z_REFCOUNT_P(param_ptr) > 1) { zval *new_tmp; ALLOC_ZVAL(new_tmp); *new_tmp = *param_ptr; zval_copy_ctor(new_tmp); INIT_PZVAL(new_tmp); param_ptr = new_tmp; Z_DELREF_P((zval *) *(p-arg_count)); *(p-arg_count) = param_ptr; } *(argument_array++) = param_ptr; arg_count--; } return SUCCESS; } /* }}} */ /* Zend-optimized Extended functions */ /* this function doesn't check for too many parameters */ ZEND_API int zend_get_parameters_ex(int param_count, ...) /* {{{ */ { void **p; int arg_count; va_list ptr; zval ***param; TSRMLS_FETCH(); p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } va_start(ptr, param_count); while (param_count-->0) { param = va_arg(ptr, zval ***); *param = (zval **) p-(arg_count--); } va_end(ptr); return SUCCESS; } /* }}} */ ZEND_API int _zend_get_parameters_array_ex(int param_count, zval ***argument_array TSRMLS_DC) /* {{{ */ { void **p; int arg_count; p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } while (param_count-->0) { zval **value = (zval**)(p-arg_count); *(argument_array++) = value; arg_count--; } return SUCCESS; } /* }}} */ ZEND_API int zend_copy_parameters_array(int param_count, zval *argument_array TSRMLS_DC) /* {{{ */ { void **p; int arg_count; p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } while (param_count-->0) { zval **param = (zval **) p-(arg_count--); zval_add_ref(param); add_next_index_zval(argument_array, *param); } return SUCCESS; } /* }}} */ ZEND_API void zend_wrong_param_count(TSRMLS_D) /* {{{ */ { const char *space; const char *class_name = get_active_class_name(&space TSRMLS_CC); zend_error(E_WARNING, "Wrong parameter count for %s%s%s()", class_name, space, get_active_function_name(TSRMLS_C)); } /* }}} */ /* Argument parsing API -- andrei */ ZEND_API char *zend_get_type_by_const(int type) /* {{{ */ { switch(type) { case IS_BOOL: return "boolean"; case IS_LONG: return "integer"; case IS_DOUBLE: return "double"; case IS_STRING: return "string"; case IS_OBJECT: return "object"; case IS_RESOURCE: return "resource"; case IS_NULL: return "null"; case IS_CALLABLE: return "callable"; case IS_ARRAY: return "array"; default: return "unknown"; } } /* }}} */ ZEND_API char *zend_zval_type_name(const zval *arg) /* {{{ */ { return zend_get_type_by_const(Z_TYPE_P(arg)); } /* }}} */ ZEND_API zend_class_entry *zend_get_class_entry(const zval *zobject TSRMLS_DC) /* {{{ */ { if (Z_OBJ_HT_P(zobject)->get_class_entry) { return Z_OBJ_HT_P(zobject)->get_class_entry(zobject TSRMLS_CC); } else { zend_error(E_ERROR, "Class entry requested for an object without PHP class"); return NULL; } } /* }}} */ /* returns 1 if you need to copy result, 0 if it's already a copy */ ZEND_API int zend_get_object_classname(const zval *object, const char **class_name, zend_uint *class_name_len TSRMLS_DC) /* {{{ */ { if (Z_OBJ_HT_P(object)->get_class_name == NULL || Z_OBJ_HT_P(object)->get_class_name(object, class_name, class_name_len, 0 TSRMLS_CC) != SUCCESS) { zend_class_entry *ce = Z_OBJCE_P(object); *class_name = ce->name; *class_name_len = ce->name_length; return 1; } return 0; } /* }}} */ static int parse_arg_object_to_string(zval **arg, char **p, int *pl, int type TSRMLS_DC) /* {{{ */ { if (Z_OBJ_HANDLER_PP(arg, cast_object)) { SEPARATE_ZVAL_IF_NOT_REF(arg); if (Z_OBJ_HANDLER_PP(arg, cast_object)(*arg, *arg, type TSRMLS_CC) == SUCCESS) { *pl = Z_STRLEN_PP(arg); *p = Z_STRVAL_PP(arg); return SUCCESS; } } /* Standard PHP objects */ if (Z_OBJ_HT_PP(arg) == &std_object_handlers || !Z_OBJ_HANDLER_PP(arg, cast_object)) { SEPARATE_ZVAL_IF_NOT_REF(arg); if (zend_std_cast_object_tostring(*arg, *arg, type TSRMLS_CC) == SUCCESS) { *pl = Z_STRLEN_PP(arg); *p = Z_STRVAL_PP(arg); return SUCCESS; } } if (!Z_OBJ_HANDLER_PP(arg, cast_object) && Z_OBJ_HANDLER_PP(arg, get)) { int use_copy; zval *z = Z_OBJ_HANDLER_PP(arg, get)(*arg TSRMLS_CC); Z_ADDREF_P(z); if(Z_TYPE_P(z) != IS_OBJECT) { zval_dtor(*arg); Z_TYPE_P(*arg) = IS_NULL; zend_make_printable_zval(z, *arg, &use_copy); if (!use_copy) { ZVAL_ZVAL(*arg, z, 1, 1); } *pl = Z_STRLEN_PP(arg); *p = Z_STRVAL_PP(arg); return SUCCESS; } zval_ptr_dtor(&z); } return FAILURE; } /* }}} */ static const char *zend_parse_arg_impl(int arg_num, zval **arg, va_list *va, const char **spec, char **error, int *severity TSRMLS_DC) /* {{{ */ { const char *spec_walk = *spec; char c = *spec_walk++; int return_null = 0; /* scan through modifiers */ while (1) { if (*spec_walk == '/') { SEPARATE_ZVAL_IF_NOT_REF(arg); } else if (*spec_walk == '!') { if (Z_TYPE_PP(arg) == IS_NULL) { return_null = 1; } } else { break; } spec_walk++; } switch (c) { case 'l': case 'L': { long *p = va_arg(*va, long *); switch (Z_TYPE_PP(arg)) { case IS_STRING: { double d; int type; if ((type = is_numeric_string(Z_STRVAL_PP(arg), Z_STRLEN_PP(arg), p, &d, -1)) == 0) { return "long"; } else if (type == IS_DOUBLE) { if (c == 'L') { if (d > LONG_MAX) { *p = LONG_MAX; break; } else if (d < LONG_MIN) { *p = LONG_MIN; break; } } *p = zend_dval_to_lval(d); } } break; case IS_DOUBLE: if (c == 'L') { if (Z_DVAL_PP(arg) > LONG_MAX) { *p = LONG_MAX; break; } else if (Z_DVAL_PP(arg) < LONG_MIN) { *p = LONG_MIN; break; } } case IS_NULL: case IS_LONG: case IS_BOOL: convert_to_long_ex(arg); *p = Z_LVAL_PP(arg); break; case IS_ARRAY: case IS_OBJECT: case IS_RESOURCE: default: return "long"; } } break; case 'd': { double *p = va_arg(*va, double *); switch (Z_TYPE_PP(arg)) { case IS_STRING: { long l; int type; if ((type = is_numeric_string(Z_STRVAL_PP(arg), Z_STRLEN_PP(arg), &l, p, -1)) == 0) { return "double"; } else if (type == IS_LONG) { *p = (double) l; } } break; case IS_NULL: case IS_LONG: case IS_DOUBLE: case IS_BOOL: convert_to_double_ex(arg); *p = Z_DVAL_PP(arg); break; case IS_ARRAY: case IS_OBJECT: case IS_RESOURCE: default: return "double"; } } break; case 'p': case 's': { char **p = va_arg(*va, char **); int *pl = va_arg(*va, int *); switch (Z_TYPE_PP(arg)) { case IS_NULL: if (return_null) { *p = NULL; *pl = 0; break; } /* break omitted intentionally */ case IS_STRING: case IS_LONG: case IS_DOUBLE: case IS_BOOL: convert_to_string_ex(arg); if (UNEXPECTED(Z_ISREF_PP(arg) != 0)) { /* it's dangerous to return pointers to string buffer of referenced variable, because it can be clobbered throug magic callbacks */ SEPARATE_ZVAL(arg); } *p = Z_STRVAL_PP(arg); *pl = Z_STRLEN_PP(arg); if (c == 'p' && CHECK_ZVAL_NULL_PATH(*arg)) { return "a valid path"; } break; case IS_OBJECT: if (parse_arg_object_to_string(arg, p, pl, IS_STRING TSRMLS_CC) == SUCCESS) { if (c == 'p' && CHECK_ZVAL_NULL_PATH(*arg)) { return "a valid path"; } break; } case IS_ARRAY: case IS_RESOURCE: default: return c == 's' ? "string" : "a valid path"; } } break; case 'b': { zend_bool *p = va_arg(*va, zend_bool *); switch (Z_TYPE_PP(arg)) { case IS_NULL: case IS_STRING: case IS_LONG: case IS_DOUBLE: case IS_BOOL: convert_to_boolean_ex(arg); *p = Z_BVAL_PP(arg); break; case IS_ARRAY: case IS_OBJECT: case IS_RESOURCE: default: return "boolean"; } } break; case 'r': { zval **p = va_arg(*va, zval **); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_RESOURCE) { *p = *arg; } else { return "resource"; } } break; case 'A': case 'a': { zval **p = va_arg(*va, zval **); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_ARRAY || (c == 'A' && Z_TYPE_PP(arg) == IS_OBJECT)) { *p = *arg; } else { return "array"; } } break; case 'H': case 'h': { HashTable **p = va_arg(*va, HashTable **); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_ARRAY) { *p = Z_ARRVAL_PP(arg); } else if(c == 'H' && Z_TYPE_PP(arg) == IS_OBJECT) { *p = HASH_OF(*arg); if(*p == NULL) { return "array"; } } else { return "array"; } } break; case 'o': { zval **p = va_arg(*va, zval **); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_OBJECT) { *p = *arg; } else { return "object"; } } break; case 'O': { zval **p = va_arg(*va, zval **); zend_class_entry *ce = va_arg(*va, zend_class_entry *); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_OBJECT && (!ce || instanceof_function(Z_OBJCE_PP(arg), ce TSRMLS_CC))) { *p = *arg; } else { if (ce) { return ce->name; } else { return "object"; } } } break; case 'C': { zend_class_entry **lookup, **pce = va_arg(*va, zend_class_entry **); zend_class_entry *ce_base = *pce; if (return_null) { *pce = NULL; break; } convert_to_string_ex(arg); if (zend_lookup_class(Z_STRVAL_PP(arg), Z_STRLEN_PP(arg), &lookup TSRMLS_CC) == FAILURE) { *pce = NULL; } else { *pce = *lookup; } if (ce_base) { if ((!*pce || !instanceof_function(*pce, ce_base TSRMLS_CC))) { zend_spprintf(error, 0, "to be a class name derived from %s, '%s' given", ce_base->name, Z_STRVAL_PP(arg)); *pce = NULL; return ""; } } if (!*pce) { zend_spprintf(error, 0, "to be a valid class name, '%s' given", Z_STRVAL_PP(arg)); return ""; } break; } break; case 'f': { zend_fcall_info *fci = va_arg(*va, zend_fcall_info *); zend_fcall_info_cache *fcc = va_arg(*va, zend_fcall_info_cache *); char *is_callable_error = NULL; if (return_null) { fci->size = 0; fcc->initialized = 0; break; } if (zend_fcall_info_init(*arg, 0, fci, fcc, NULL, &is_callable_error TSRMLS_CC) == SUCCESS) { if (is_callable_error) { *severity = E_STRICT; zend_spprintf(error, 0, "to be a valid callback, %s", is_callable_error); efree(is_callable_error); *spec = spec_walk; return ""; } break; } else { if (is_callable_error) { *severity = E_WARNING; zend_spprintf(error, 0, "to be a valid callback, %s", is_callable_error); efree(is_callable_error); return ""; } else { return "valid callback"; } } } case 'z': { zval **p = va_arg(*va, zval **); if (return_null) { *p = NULL; } else { *p = *arg; } } break; case 'Z': { zval ***p = va_arg(*va, zval ***); if (return_null) { *p = NULL; } else { *p = arg; } } break; default: return "unknown"; } *spec = spec_walk; return NULL; } /* }}} */ static int zend_parse_arg(int arg_num, zval **arg, va_list *va, const char **spec, int quiet TSRMLS_DC) /* {{{ */ { const char *expected_type = NULL; char *error = NULL; int severity = E_WARNING; expected_type = zend_parse_arg_impl(arg_num, arg, va, spec, &error, &severity TSRMLS_CC); if (expected_type) { if (!quiet && (*expected_type || error)) { const char *space; const char *class_name = get_active_class_name(&space TSRMLS_CC); if (error) { zend_error(severity, "%s%s%s() expects parameter %d %s", class_name, space, get_active_function_name(TSRMLS_C), arg_num, error); efree(error); } else { zend_error(severity, "%s%s%s() expects parameter %d to be %s, %s given", class_name, space, get_active_function_name(TSRMLS_C), arg_num, expected_type, zend_zval_type_name(*arg)); } } if (severity != E_STRICT) { return FAILURE; } } return SUCCESS; } /* }}} */ static int zend_parse_va_args(int num_args, const char *type_spec, va_list *va, int flags TSRMLS_DC) /* {{{ */ { const char *spec_walk; int c, i; int min_num_args = -1; int max_num_args = 0; int post_varargs = 0; zval **arg; int arg_count; int quiet = flags & ZEND_PARSE_PARAMS_QUIET; zend_bool have_varargs = 0; zval ****varargs = NULL; int *n_varargs = NULL; for (spec_walk = type_spec; *spec_walk; spec_walk++) { c = *spec_walk; switch (c) { case 'l': case 'd': case 's': case 'b': case 'r': case 'a': case 'o': case 'O': case 'z': case 'Z': case 'C': case 'h': case 'f': case 'A': case 'H': case 'p': max_num_args++; break; case '|': min_num_args = max_num_args; break; case '/': case '!': /* Pass */ break; case '*': case '+': if (have_varargs) { if (!quiet) { zend_function *active_function = EG(current_execute_data)->function_state.function; const char *class_name = active_function->common.scope ? active_function->common.scope->name : ""; zend_error(E_WARNING, "%s%s%s(): only one varargs specifier (* or +) is permitted", class_name, class_name[0] ? "::" : "", active_function->common.function_name); } return FAILURE; } have_varargs = 1; /* we expect at least one parameter in varargs */ if (c == '+') { max_num_args++; } /* mark the beginning of varargs */ post_varargs = max_num_args; break; default: if (!quiet) { zend_function *active_function = EG(current_execute_data)->function_state.function; const char *class_name = active_function->common.scope ? active_function->common.scope->name : ""; zend_error(E_WARNING, "%s%s%s(): bad type specifier while parsing parameters", class_name, class_name[0] ? "::" : "", active_function->common.function_name); } return FAILURE; } } if (min_num_args < 0) { min_num_args = max_num_args; } if (have_varargs) { /* calculate how many required args are at the end of the specifier list */ post_varargs = max_num_args - post_varargs; max_num_args = -1; } if (num_args < min_num_args || (num_args > max_num_args && max_num_args > 0)) { if (!quiet) { zend_function *active_function = EG(current_execute_data)->function_state.function; const char *class_name = active_function->common.scope ? active_function->common.scope->name : ""; zend_error(E_WARNING, "%s%s%s() expects %s %d parameter%s, %d given", class_name, class_name[0] ? "::" : "", active_function->common.function_name, min_num_args == max_num_args ? "exactly" : num_args < min_num_args ? "at least" : "at most", num_args < min_num_args ? min_num_args : max_num_args, (num_args < min_num_args ? min_num_args : max_num_args) == 1 ? "" : "s", num_args); } return FAILURE; } arg_count = (int)(zend_uintptr_t) *(zend_vm_stack_top(TSRMLS_C) - 1); if (num_args > arg_count) { zend_error(E_WARNING, "%s(): could not obtain parameters for parsing", get_active_function_name(TSRMLS_C)); return FAILURE; } i = 0; while (num_args-- > 0) { if (*type_spec == '|') { type_spec++; } if (*type_spec == '*' || *type_spec == '+') { int num_varargs = num_args + 1 - post_varargs; /* eat up the passed in storage even if it won't be filled in with varargs */ varargs = va_arg(*va, zval ****); n_varargs = va_arg(*va, int *); type_spec++; if (num_varargs > 0) { int iv = 0; zval **p = (zval **) (zend_vm_stack_top(TSRMLS_C) - 1 - (arg_count - i)); *n_varargs = num_varargs; /* allocate space for array and store args */ *varargs = safe_emalloc(num_varargs, sizeof(zval **), 0); while (num_varargs-- > 0) { (*varargs)[iv++] = p++; } /* adjust how many args we have left and restart loop */ num_args = num_args + 1 - iv; i += iv; continue; } else { *varargs = NULL; *n_varargs = 0; } } arg = (zval **) (zend_vm_stack_top(TSRMLS_C) - 1 - (arg_count-i)); if (zend_parse_arg(i+1, arg, va, &type_spec, quiet TSRMLS_CC) == FAILURE) { /* clean up varargs array if it was used */ if (varargs && *varargs) { efree(*varargs); *varargs = NULL; } return FAILURE; } i++; } return SUCCESS; } /* }}} */ #define RETURN_IF_ZERO_ARGS(num_args, type_spec, quiet) { \ int __num_args = (num_args); \ \ if (0 == (type_spec)[0] && 0 != __num_args && !(quiet)) { \ const char *__space; \ const char * __class_name = get_active_class_name(&__space TSRMLS_CC); \ zend_error(E_WARNING, "%s%s%s() expects exactly 0 parameters, %d given", \ __class_name, __space, \ get_active_function_name(TSRMLS_C), __num_args); \ return FAILURE; \ }\ } ZEND_API int zend_parse_parameters_ex(int flags, int num_args TSRMLS_DC, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; RETURN_IF_ZERO_ARGS(num_args, type_spec, flags & ZEND_PARSE_PARAMS_QUIET); va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, flags TSRMLS_CC); va_end(va); return retval; } /* }}} */ ZEND_API int zend_parse_parameters(int num_args TSRMLS_DC, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; RETURN_IF_ZERO_ARGS(num_args, type_spec, 0); va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, 0 TSRMLS_CC); va_end(va); return retval; } /* }}} */ ZEND_API int zend_parse_method_parameters(int num_args TSRMLS_DC, zval *this_ptr, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; const char *p = type_spec; zval **object; zend_class_entry *ce; if (!this_ptr) { RETURN_IF_ZERO_ARGS(num_args, p, 0); va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, 0 TSRMLS_CC); va_end(va); } else { p++; RETURN_IF_ZERO_ARGS(num_args, p, 0); va_start(va, type_spec); object = va_arg(va, zval **); ce = va_arg(va, zend_class_entry *); *object = this_ptr; if (ce && !instanceof_function(Z_OBJCE_P(this_ptr), ce TSRMLS_CC)) { zend_error(E_CORE_ERROR, "%s::%s() must be derived from %s::%s", ce->name, get_active_function_name(TSRMLS_C), Z_OBJCE_P(this_ptr)->name, get_active_function_name(TSRMLS_C)); } retval = zend_parse_va_args(num_args, p, &va, 0 TSRMLS_CC); va_end(va); } return retval; } /* }}} */ ZEND_API int zend_parse_method_parameters_ex(int flags, int num_args TSRMLS_DC, zval *this_ptr, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; const char *p = type_spec; zval **object; zend_class_entry *ce; int quiet = flags & ZEND_PARSE_PARAMS_QUIET; if (!this_ptr) { RETURN_IF_ZERO_ARGS(num_args, p, quiet); va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, flags TSRMLS_CC); va_end(va); } else { p++; RETURN_IF_ZERO_ARGS(num_args, p, quiet); va_start(va, type_spec); object = va_arg(va, zval **); ce = va_arg(va, zend_class_entry *); *object = this_ptr; if (ce && !instanceof_function(Z_OBJCE_P(this_ptr), ce TSRMLS_CC)) { if (!quiet) { zend_error(E_CORE_ERROR, "%s::%s() must be derived from %s::%s", ce->name, get_active_function_name(TSRMLS_C), Z_OBJCE_P(this_ptr)->name, get_active_function_name(TSRMLS_C)); } va_end(va); return FAILURE; } retval = zend_parse_va_args(num_args, p, &va, flags TSRMLS_CC); va_end(va); } return retval; } /* }}} */ /* Argument parsing API -- andrei */ ZEND_API int _array_init(zval *arg, uint size ZEND_FILE_LINE_DC) /* {{{ */ { ALLOC_HASHTABLE_REL(Z_ARRVAL_P(arg)); _zend_hash_init(Z_ARRVAL_P(arg), size, NULL, ZVAL_PTR_DTOR, 0 ZEND_FILE_LINE_RELAY_CC); Z_TYPE_P(arg) = IS_ARRAY; return SUCCESS; } /* }}} */ static int zend_merge_property(zval **value TSRMLS_DC, int num_args, va_list args, const zend_hash_key *hash_key) /* {{{ */ { /* which name should a numeric property have ? */ if (hash_key->nKeyLength) { zval *obj = va_arg(args, zval *); zend_object_handlers *obj_ht = va_arg(args, zend_object_handlers *); zval *member; MAKE_STD_ZVAL(member); ZVAL_STRINGL(member, hash_key->arKey, hash_key->nKeyLength-1, 1); obj_ht->write_property(obj, member, *value, 0 TSRMLS_CC); zval_ptr_dtor(&member); } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* This function should be called after the constructor has been called * because it may call __set from the uninitialized object otherwise. */ ZEND_API void zend_merge_properties(zval *obj, HashTable *properties, int destroy_ht TSRMLS_DC) /* {{{ */ { const zend_object_handlers *obj_ht = Z_OBJ_HT_P(obj); zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE_P(obj); zend_hash_apply_with_arguments(properties TSRMLS_CC, (apply_func_args_t)zend_merge_property, 2, obj, obj_ht); EG(scope) = old_scope; if (destroy_ht) { zend_hash_destroy(properties); FREE_HASHTABLE(properties); } } /* }}} */ ZEND_API void zend_update_class_constants(zend_class_entry *class_type TSRMLS_DC) /* {{{ */ { if ((class_type->ce_flags & ZEND_ACC_CONSTANTS_UPDATED) == 0 || (!CE_STATIC_MEMBERS(class_type) && class_type->default_static_members_count)) { zend_class_entry **scope = EG(in_execution)?&EG(scope):&CG(active_class_entry); zend_class_entry *old_scope = *scope; int i; *scope = class_type; zend_hash_apply_with_argument(&class_type->constants_table, (apply_func_arg_t) zval_update_constant, (void*)1 TSRMLS_CC); for (i = 0; i < class_type->default_properties_count; i++) { if (class_type->default_properties_table[i]) { zval_update_constant(&class_type->default_properties_table[i], (void**)1 TSRMLS_CC); } } if (!CE_STATIC_MEMBERS(class_type) && class_type->default_static_members_count) { zval **p; if (class_type->parent) { zend_update_class_constants(class_type->parent TSRMLS_CC); } #if ZTS CG(static_members_table)[(zend_intptr_t)(class_type->static_members_table)] = emalloc(sizeof(zval*) * class_type->default_static_members_count); #else class_type->static_members_table = emalloc(sizeof(zval*) * class_type->default_static_members_count); #endif for (i = 0; i < class_type->default_static_members_count; i++) { p = &class_type->default_static_members_table[i]; if (Z_ISREF_PP(p) && class_type->parent && i < class_type->parent->default_static_members_count && *p == class_type->parent->default_static_members_table[i] && CE_STATIC_MEMBERS(class_type->parent)[i] ) { zval *q = CE_STATIC_MEMBERS(class_type->parent)[i]; Z_ADDREF_P(q); Z_SET_ISREF_P(q); CE_STATIC_MEMBERS(class_type)[i] = q; } else { zval *r; ALLOC_ZVAL(r); *r = **p; INIT_PZVAL(r); zval_copy_ctor(r); CE_STATIC_MEMBERS(class_type)[i] = r; } } } for (i = 0; i < class_type->default_static_members_count; i++) { zval_update_constant(&CE_STATIC_MEMBERS(class_type)[i], (void**)1 TSRMLS_CC); } *scope = old_scope; class_type->ce_flags |= ZEND_ACC_CONSTANTS_UPDATED; } } /* }}} */ ZEND_API void object_properties_init(zend_object *object, zend_class_entry *class_type) /* {{{ */ { int i; if (class_type->default_properties_count) { object->properties_table = emalloc(sizeof(zval*) * class_type->default_properties_count); for (i = 0; i < class_type->default_properties_count; i++) { object->properties_table[i] = class_type->default_properties_table[i]; if (class_type->default_properties_table[i]) { Z_ADDREF_P(object->properties_table[i]); } } object->properties = NULL; } } /* }}} */ /* This function requires 'properties' to contain all props declared in the * class and all props being public. If only a subset is given or the class * has protected members then you need to merge the properties seperately by * calling zend_merge_properties(). */ ZEND_API int _object_and_properties_init(zval *arg, zend_class_entry *class_type, HashTable *properties ZEND_FILE_LINE_DC TSRMLS_DC) /* {{{ */ { zend_object *object; if (class_type->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLICIT_ABSTRACT_CLASS|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) { char *what = (class_type->ce_flags & ZEND_ACC_INTERFACE) ? "interface" :((class_type->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) ? "trait" : "abstract class"; zend_error(E_ERROR, "Cannot instantiate %s %s", what, class_type->name); } zend_update_class_constants(class_type TSRMLS_CC); Z_TYPE_P(arg) = IS_OBJECT; if (class_type->create_object == NULL) { Z_OBJVAL_P(arg) = zend_objects_new(&object, class_type TSRMLS_CC); if (properties) { object->properties = properties; object->properties_table = NULL; } else { object_properties_init(object, class_type); } } else { Z_OBJVAL_P(arg) = class_type->create_object(class_type TSRMLS_CC); } return SUCCESS; } /* }}} */ ZEND_API int _object_init_ex(zval *arg, zend_class_entry *class_type ZEND_FILE_LINE_DC TSRMLS_DC) /* {{{ */ { return _object_and_properties_init(arg, class_type, 0 ZEND_FILE_LINE_RELAY_CC TSRMLS_CC); } /* }}} */ ZEND_API int _object_init(zval *arg ZEND_FILE_LINE_DC TSRMLS_DC) /* {{{ */ { return _object_init_ex(arg, zend_standard_class_def ZEND_FILE_LINE_RELAY_CC TSRMLS_CC); } /* }}} */ ZEND_API int add_assoc_function(zval *arg, const char *key, void (*function_ptr)(INTERNAL_FUNCTION_PARAMETERS)) /* {{{ */ { zend_error(E_WARNING, "add_assoc_function() is no longer supported"); return FAILURE; } /* }}} */ ZEND_API int add_assoc_long_ex(zval *arg, const char *key, uint key_len, long n) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, n); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_null_ex(zval *arg, const char *key, uint key_len) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_NULL(tmp); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_bool_ex(zval *arg, const char *key, uint key_len, int b) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_BOOL(tmp, b); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_resource_ex(zval *arg, const char *key, uint key_len, int r) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_RESOURCE(tmp, r); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_double_ex(zval *arg, const char *key, uint key_len, double d) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_string_ex(zval *arg, const char *key, uint key_len, char *str, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_stringl_ex(zval *arg, const char *key, uint key_len, char *str, uint length, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_zval_ex(zval *arg, const char *key, uint key_len, zval *value) /* {{{ */ { return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &value, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_long(zval *arg, ulong index, long n) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, n); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_null(zval *arg, ulong index) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_NULL(tmp); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_bool(zval *arg, ulong index, int b) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_BOOL(tmp, b); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_resource(zval *arg, ulong index, int r) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_RESOURCE(tmp, r); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_double(zval *arg, ulong index, double d) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_string(zval *arg, ulong index, const char *str, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_stringl(zval *arg, ulong index, const char *str, uint length, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_zval(zval *arg, ulong index, zval *value) /* {{{ */ { return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &value, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_long(zval *arg, long n) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, n); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_null(zval *arg) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_NULL(tmp); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_bool(zval *arg, int b) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_BOOL(tmp, b); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_resource(zval *arg, int r) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_RESOURCE(tmp, r); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_double(zval *arg, double d) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_string(zval *arg, const char *str, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_stringl(zval *arg, const char *str, uint length, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_zval(zval *arg, zval *value) /* {{{ */ { return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &value, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_get_assoc_string_ex(zval *arg, const char *key, uint key_len, const char *str, void **dest, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_assoc_stringl_ex(zval *arg, const char *key, uint key_len, const char *str, uint length, void **dest, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_index_long(zval *arg, ulong index, long l, void **dest) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, l); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_index_double(zval *arg, ulong index, double d, void **dest) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_index_string(zval *arg, ulong index, const char *str, void **dest, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_index_stringl(zval *arg, ulong index, const char *str, uint length, void **dest, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_property_long_ex(zval *arg, const char *key, uint key_len, long n TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, n); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_bool_ex(zval *arg, const char *key, uint key_len, int b TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_BOOL(tmp, b); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_null_ex(zval *arg, const char *key, uint key_len TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_NULL(tmp); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_resource_ex(zval *arg, const char *key, uint key_len, long n TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_RESOURCE(tmp, n); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_double_ex(zval *arg, const char *key, uint key_len, double d TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_string_ex(zval *arg, const char *key, uint key_len, const char *str, int duplicate TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_stringl_ex(zval *arg, const char *key, uint key_len, const char *str, uint length, int duplicate TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_zval_ex(zval *arg, const char *key, uint key_len, zval *value TSRMLS_DC) /* {{{ */ { zval *z_key; MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, value, 0 TSRMLS_CC); zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int zend_startup_module_ex(zend_module_entry *module TSRMLS_DC) /* {{{ */ { int name_len; char *lcname; if (module->module_started) { return SUCCESS; } module->module_started = 1; /* Check module dependencies */ if (module->deps) { const zend_module_dep *dep = module->deps; while (dep->name) { if (dep->type == MODULE_DEP_REQUIRED) { zend_module_entry *req_mod; name_len = strlen(dep->name); lcname = zend_str_tolower_dup(dep->name, name_len); if (zend_hash_find(&module_registry, lcname, name_len+1, (void**)&req_mod) == FAILURE || !req_mod->module_started) { efree(lcname); /* TODO: Check version relationship */ zend_error(E_CORE_WARNING, "Cannot load module '%s' because required module '%s' is not loaded", module->name, dep->name); module->module_started = 0; return FAILURE; } efree(lcname); } ++dep; } } /* Initialize module globals */ if (module->globals_size) { #ifdef ZTS ts_allocate_id(module->globals_id_ptr, module->globals_size, (ts_allocate_ctor) module->globals_ctor, (ts_allocate_dtor) module->globals_dtor); #else if (module->globals_ctor) { module->globals_ctor(module->globals_ptr TSRMLS_CC); } #endif } if (module->module_startup_func) { EG(current_module) = module; if (module->module_startup_func(module->type, module->module_number TSRMLS_CC)==FAILURE) { zend_error(E_CORE_ERROR,"Unable to start %s module", module->name); EG(current_module) = NULL; return FAILURE; } EG(current_module) = NULL; } return SUCCESS; } /* }}} */ static void zend_sort_modules(void *base, size_t count, size_t siz, compare_func_t compare TSRMLS_DC) /* {{{ */ { Bucket **b1 = base; Bucket **b2; Bucket **end = b1 + count; Bucket *tmp; zend_module_entry *m, *r; while (b1 < end) { try_again: m = (zend_module_entry*)(*b1)->pData; if (!m->module_started && m->deps) { const zend_module_dep *dep = m->deps; while (dep->name) { if (dep->type == MODULE_DEP_REQUIRED || dep->type == MODULE_DEP_OPTIONAL) { b2 = b1 + 1; while (b2 < end) { r = (zend_module_entry*)(*b2)->pData; if (strcasecmp(dep->name, r->name) == 0) { tmp = *b1; *b1 = *b2; *b2 = tmp; goto try_again; } b2++; } } dep++; } } b1++; } } /* }}} */ ZEND_API void zend_collect_module_handlers(TSRMLS_D) /* {{{ */ { HashPosition pos; zend_module_entry *module; int startup_count = 0; int shutdown_count = 0; int post_deactivate_count = 0; zend_class_entry **pce; int class_count = 0; /* Collect extensions with request startup/shutdown handlers */ for (zend_hash_internal_pointer_reset_ex(&module_registry, &pos); zend_hash_get_current_data_ex(&module_registry, (void *) &module, &pos) == SUCCESS; zend_hash_move_forward_ex(&module_registry, &pos)) { if (module->request_startup_func) { startup_count++; } if (module->request_shutdown_func) { shutdown_count++; } if (module->post_deactivate_func) { post_deactivate_count++; } } module_request_startup_handlers = (zend_module_entry**)malloc( sizeof(zend_module_entry*) * (startup_count + 1 + shutdown_count + 1 + post_deactivate_count + 1)); module_request_startup_handlers[startup_count] = NULL; module_request_shutdown_handlers = module_request_startup_handlers + startup_count + 1; module_request_shutdown_handlers[shutdown_count] = NULL; module_post_deactivate_handlers = module_request_shutdown_handlers + shutdown_count + 1; module_post_deactivate_handlers[post_deactivate_count] = NULL; startup_count = 0; for (zend_hash_internal_pointer_reset_ex(&module_registry, &pos); zend_hash_get_current_data_ex(&module_registry, (void *) &module, &pos) == SUCCESS; zend_hash_move_forward_ex(&module_registry, &pos)) { if (module->request_startup_func) { module_request_startup_handlers[startup_count++] = module; } if (module->request_shutdown_func) { module_request_shutdown_handlers[--shutdown_count] = module; } if (module->post_deactivate_func) { module_post_deactivate_handlers[--post_deactivate_count] = module; } } /* Collect internal classes with static members */ for (zend_hash_internal_pointer_reset_ex(CG(class_table), &pos); zend_hash_get_current_data_ex(CG(class_table), (void *) &pce, &pos) == SUCCESS; zend_hash_move_forward_ex(CG(class_table), &pos)) { if ((*pce)->type == ZEND_INTERNAL_CLASS && (*pce)->default_static_members_count > 0) { class_count++; } } class_cleanup_handlers = (zend_class_entry**)malloc( sizeof(zend_class_entry*) * (class_count + 1)); class_cleanup_handlers[class_count] = NULL; if (class_count) { for (zend_hash_internal_pointer_reset_ex(CG(class_table), &pos); zend_hash_get_current_data_ex(CG(class_table), (void *) &pce, &pos) == SUCCESS; zend_hash_move_forward_ex(CG(class_table), &pos)) { if ((*pce)->type == ZEND_INTERNAL_CLASS && (*pce)->default_static_members_count > 0) { class_cleanup_handlers[--class_count] = *pce; } } } } /* }}} */ ZEND_API int zend_startup_modules(TSRMLS_D) /* {{{ */ { zend_hash_sort(&module_registry, zend_sort_modules, NULL, 0 TSRMLS_CC); zend_hash_apply(&module_registry, (apply_func_t)zend_startup_module_ex TSRMLS_CC); return SUCCESS; } /* }}} */ ZEND_API void zend_destroy_modules(void) /* {{{ */ { free(class_cleanup_handlers); free(module_request_startup_handlers); zend_hash_graceful_reverse_destroy(&module_registry); } /* }}} */ ZEND_API zend_module_entry* zend_register_module_ex(zend_module_entry *module TSRMLS_DC) /* {{{ */ { int name_len; char *lcname; zend_module_entry *module_ptr; if (!module) { return NULL; } #if 0 zend_printf("%s: Registering module %d\n", module->name, module->module_number); #endif /* Check module dependencies */ if (module->deps) { const zend_module_dep *dep = module->deps; while (dep->name) { if (dep->type == MODULE_DEP_CONFLICTS) { name_len = strlen(dep->name); lcname = zend_str_tolower_dup(dep->name, name_len); if (zend_hash_exists(&module_registry, lcname, name_len+1)) { efree(lcname); /* TODO: Check version relationship */ zend_error(E_CORE_WARNING, "Cannot load module '%s' because conflicting module '%s' is already loaded", module->name, dep->name); return NULL; } efree(lcname); } ++dep; } } name_len = strlen(module->name); lcname = zend_str_tolower_dup(module->name, name_len); if (zend_hash_add(&module_registry, lcname, name_len+1, (void *)module, sizeof(zend_module_entry), (void**)&module_ptr)==FAILURE) { zend_error(E_CORE_WARNING, "Module '%s' already loaded", module->name); efree(lcname); return NULL; } efree(lcname); module = module_ptr; EG(current_module) = module; if (module->functions && zend_register_functions(NULL, module->functions, NULL, module->type TSRMLS_CC)==FAILURE) { EG(current_module) = NULL; zend_error(E_CORE_WARNING,"%s: Unable to register functions, unable to load", module->name); return NULL; } EG(current_module) = NULL; return module; } /* }}} */ ZEND_API zend_module_entry* zend_register_internal_module(zend_module_entry *module TSRMLS_DC) /* {{{ */ { module->module_number = zend_next_free_module(); module->type = MODULE_PERSISTENT; return zend_register_module_ex(module TSRMLS_CC); } /* }}} */ ZEND_API void zend_check_magic_method_implementation(const zend_class_entry *ce, const zend_function *fptr, int error_type TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(fptr->common.function_name); zend_str_tolower_copy(lcname, fptr->common.function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)) && fptr->common.num_args != 0) { zend_error(error_type, "Destructor %s::%s() cannot take arguments", ce->name, ZEND_DESTRUCTOR_FUNC_NAME); } else if (name_len == sizeof(ZEND_CLONE_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)) && fptr->common.num_args != 0) { zend_error(error_type, "Method %s::%s() cannot accept any arguments", ce->name, ZEND_CLONE_FUNC_NAME); } else if (name_len == sizeof(ZEND_GET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME))) { if (fptr->common.num_args != 1) { zend_error(error_type, "Method %s::%s() must take exactly 1 argument", ce->name, ZEND_GET_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_GET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_SET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME))) { if (fptr->common.num_args != 2) { zend_error(error_type, "Method %s::%s() must take exactly 2 arguments", ce->name, ZEND_SET_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1) || ARG_SHOULD_BE_SENT_BY_REF(fptr, 2)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_SET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_UNSET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME))) { if (fptr->common.num_args != 1) { zend_error(error_type, "Method %s::%s() must take exactly 1 argument", ce->name, ZEND_UNSET_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_UNSET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_ISSET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME))) { if (fptr->common.num_args != 1) { zend_error(error_type, "Method %s::%s() must take exactly 1 argument", ce->name, ZEND_ISSET_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_ISSET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_CALL_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME))) { if (fptr->common.num_args != 2) { zend_error(error_type, "Method %s::%s() must take exactly 2 arguments", ce->name, ZEND_CALL_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1) || ARG_SHOULD_BE_SENT_BY_REF(fptr, 2)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_CALL_FUNC_NAME); } } else if (name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) ) { if (fptr->common.num_args != 2) { zend_error(error_type, "Method %s::%s() must take exactly 2 arguments", ce->name, ZEND_CALLSTATIC_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1) || ARG_SHOULD_BE_SENT_BY_REF(fptr, 2)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_CALLSTATIC_FUNC_NAME); } } else if (name_len == sizeof(ZEND_TOSTRING_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && fptr->common.num_args != 0 ) { zend_error(error_type, "Method %s::%s() cannot take arguments", ce->name, ZEND_TOSTRING_FUNC_NAME); } } /* }}} */ /* registers all functions in *library_functions in the function hash */ ZEND_API int zend_register_functions(zend_class_entry *scope, const zend_function_entry *functions, HashTable *function_table, int type TSRMLS_DC) /* {{{ */ { const zend_function_entry *ptr = functions; zend_function function, *reg_function; zend_internal_function *internal_function = (zend_internal_function *)&function; int count=0, unload=0, result=0; HashTable *target_function_table = function_table; int error_type; zend_function *ctor = NULL, *dtor = NULL, *clone = NULL, *__get = NULL, *__set = NULL, *__unset = NULL, *__isset = NULL, *__call = NULL, *__callstatic = NULL, *__tostring = NULL; const char *lowercase_name; int fname_len; const char *lc_class_name = NULL; int class_name_len = 0; if (type==MODULE_PERSISTENT) { error_type = E_CORE_WARNING; } else { error_type = E_WARNING; } if (!target_function_table) { target_function_table = CG(function_table); } internal_function->type = ZEND_INTERNAL_FUNCTION; internal_function->module = EG(current_module); if (scope) { class_name_len = strlen(scope->name); if ((lc_class_name = zend_memrchr(scope->name, '\\', class_name_len))) { ++lc_class_name; class_name_len -= (lc_class_name - scope->name); lc_class_name = zend_str_tolower_dup(lc_class_name, class_name_len); } else { lc_class_name = zend_str_tolower_dup(scope->name, class_name_len); } } while (ptr->fname) { internal_function->handler = ptr->handler; internal_function->function_name = (char*)ptr->fname; internal_function->scope = scope; internal_function->prototype = NULL; if (ptr->flags) { if (!(ptr->flags & ZEND_ACC_PPP_MASK)) { if (ptr->flags != ZEND_ACC_DEPRECATED || scope) { zend_error(error_type, "Invalid access level for %s%s%s() - access must be exactly one of public, protected or private", scope ? scope->name : "", scope ? "::" : "", ptr->fname); } internal_function->fn_flags = ZEND_ACC_PUBLIC | ptr->flags; } else { internal_function->fn_flags = ptr->flags; } } else { internal_function->fn_flags = ZEND_ACC_PUBLIC; } if (ptr->arg_info) { zend_internal_function_info *info = (zend_internal_function_info*)ptr->arg_info; internal_function->arg_info = (zend_arg_info*)ptr->arg_info+1; internal_function->num_args = ptr->num_args; /* Currently you cannot denote that the function can accept less arguments than num_args */ if (info->required_num_args == -1) { internal_function->required_num_args = ptr->num_args; } else { internal_function->required_num_args = info->required_num_args; } if (info->pass_rest_by_reference) { if (info->pass_rest_by_reference == ZEND_SEND_PREFER_REF) { internal_function->fn_flags |= ZEND_ACC_PASS_REST_PREFER_REF; } else { internal_function->fn_flags |= ZEND_ACC_PASS_REST_BY_REFERENCE; } } if (info->return_reference) { internal_function->fn_flags |= ZEND_ACC_RETURN_REFERENCE; } } else { internal_function->arg_info = NULL; internal_function->num_args = 0; internal_function->required_num_args = 0; } if (ptr->flags & ZEND_ACC_ABSTRACT) { if (scope) { /* This is a class that must be abstract itself. Here we set the check info. */ scope->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; if (!(scope->ce_flags & ZEND_ACC_INTERFACE)) { /* Since the class is not an interface it needs to be declared as a abstract class. */ /* Since here we are handling internal functions only we can add the keyword flag. */ /* This time we set the flag for the keyword 'abstract'. */ scope->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } } if (ptr->flags & ZEND_ACC_STATIC && (!scope || !(scope->ce_flags & ZEND_ACC_INTERFACE))) { zend_error(error_type, "Static function %s%s%s() cannot be abstract", scope ? scope->name : "", scope ? "::" : "", ptr->fname); } } else { if (scope && (scope->ce_flags & ZEND_ACC_INTERFACE)) { efree((char*)lc_class_name); zend_error(error_type, "Interface %s cannot contain non abstract method %s()", scope->name, ptr->fname); return FAILURE; } if (!internal_function->handler) { if (scope) { efree((char*)lc_class_name); } zend_error(error_type, "Method %s%s%s() cannot be a NULL function", scope ? scope->name : "", scope ? "::" : "", ptr->fname); zend_unregister_functions(functions, count, target_function_table TSRMLS_CC); return FAILURE; } } fname_len = strlen(ptr->fname); lowercase_name = zend_new_interned_string(zend_str_tolower_dup(ptr->fname, fname_len), fname_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lowercase_name)) { result = zend_hash_quick_add(target_function_table, lowercase_name, fname_len+1, INTERNED_HASH(lowercase_name), &function, sizeof(zend_function), (void**)&reg_function); } else { result = zend_hash_add(target_function_table, lowercase_name, fname_len+1, &function, sizeof(zend_function), (void**)&reg_function); } if (result == FAILURE) { unload=1; str_efree(lowercase_name); break; } if (scope) { /* Look for ctor, dtor, clone * If it's an old-style constructor, store it only if we don't have * a constructor already. */ if ((fname_len == class_name_len) && !ctor && !memcmp(lowercase_name, lc_class_name, class_name_len+1)) { ctor = reg_function; } else if ((fname_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME))) { ctor = reg_function; } else if ((fname_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME))) { dtor = reg_function; if (internal_function->num_args) { zend_error(error_type, "Destructor %s::%s() cannot take arguments", scope->name, ptr->fname); } } else if ((fname_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME))) { clone = reg_function; } else if ((fname_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME))) { __call = reg_function; } else if ((fname_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME))) { __callstatic = reg_function; } else if ((fname_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME))) { __tostring = reg_function; } else if ((fname_len == sizeof(ZEND_GET_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME))) { __get = reg_function; } else if ((fname_len == sizeof(ZEND_SET_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME))) { __set = reg_function; } else if ((fname_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME))) { __unset = reg_function; } else if ((fname_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME))) { __isset = reg_function; } else { reg_function = NULL; } if (reg_function) { zend_check_magic_method_implementation(scope, reg_function, error_type TSRMLS_CC); } } ptr++; count++; str_efree(lowercase_name); } if (unload) { /* before unloading, display all remaining bad function in the module */ if (scope) { efree((char*)lc_class_name); } while (ptr->fname) { fname_len = strlen(ptr->fname); lowercase_name = zend_str_tolower_dup(ptr->fname, fname_len); if (zend_hash_exists(target_function_table, lowercase_name, fname_len+1)) { zend_error(error_type, "Function registration failed - duplicate name - %s%s%s", scope ? scope->name : "", scope ? "::" : "", ptr->fname); } efree((char*)lowercase_name); ptr++; } zend_unregister_functions(functions, count, target_function_table TSRMLS_CC); return FAILURE; } if (scope) { scope->constructor = ctor; scope->destructor = dtor; scope->clone = clone; scope->__call = __call; scope->__callstatic = __callstatic; scope->__tostring = __tostring; scope->__get = __get; scope->__set = __set; scope->__unset = __unset; scope->__isset = __isset; if (ctor) { ctor->common.fn_flags |= ZEND_ACC_CTOR; if (ctor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Constructor %s::%s() cannot be static", scope->name, ctor->common.function_name); } ctor->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (dtor) { dtor->common.fn_flags |= ZEND_ACC_DTOR; if (dtor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Destructor %s::%s() cannot be static", scope->name, dtor->common.function_name); } dtor->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (clone) { clone->common.fn_flags |= ZEND_ACC_CLONE; if (clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Constructor %s::%s() cannot be static", scope->name, clone->common.function_name); } clone->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__call) { if (__call->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __call->common.function_name); } __call->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__callstatic) { if (!(__callstatic->common.fn_flags & ZEND_ACC_STATIC)) { zend_error(error_type, "Method %s::%s() must be static", scope->name, __callstatic->common.function_name); } __callstatic->common.fn_flags |= ZEND_ACC_STATIC; } if (__tostring) { if (__tostring->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __tostring->common.function_name); } __tostring->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__get) { if (__get->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __get->common.function_name); } __get->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__set) { if (__set->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __set->common.function_name); } __set->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__unset) { if (__unset->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __unset->common.function_name); } __unset->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__isset) { if (__isset->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __isset->common.function_name); } __isset->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } efree((char*)lc_class_name); } return SUCCESS; } /* }}} */ /* count=-1 means erase all functions, otherwise, * erase the first count functions */ ZEND_API void zend_unregister_functions(const zend_function_entry *functions, int count, HashTable *function_table TSRMLS_DC) /* {{{ */ { const zend_function_entry *ptr = functions; int i=0; HashTable *target_function_table = function_table; if (!target_function_table) { target_function_table = CG(function_table); } while (ptr->fname) { if (count!=-1 && i>=count) { break; } #if 0 zend_printf("Unregistering %s()\n", ptr->fname); #endif zend_hash_del(target_function_table, ptr->fname, strlen(ptr->fname)+1); ptr++; i++; } } /* }}} */ ZEND_API int zend_startup_module(zend_module_entry *module) /* {{{ */ { TSRMLS_FETCH(); if ((module = zend_register_internal_module(module TSRMLS_CC)) != NULL && zend_startup_module_ex(module TSRMLS_CC) == SUCCESS) { return SUCCESS; } return FAILURE; } /* }}} */ ZEND_API int zend_get_module_started(const char *module_name) /* {{{ */ { zend_module_entry *module; return (zend_hash_find(&module_registry, module_name, strlen(module_name)+1, (void**)&module) == SUCCESS && module->module_started) ? SUCCESS : FAILURE; } /* }}} */ static int clean_module_class(const zend_class_entry **ce, int *module_number TSRMLS_DC) /* {{{ */ { if ((*ce)->type == ZEND_INTERNAL_CLASS && (*ce)->info.internal.module->module_number == *module_number) { return ZEND_HASH_APPLY_REMOVE; } else { return ZEND_HASH_APPLY_KEEP; } } /* }}} */ static void clean_module_classes(int module_number TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_argument(EG(class_table), (apply_func_arg_t) clean_module_class, (void *) &module_number TSRMLS_CC); } /* }}} */ void module_destructor(zend_module_entry *module) /* {{{ */ { TSRMLS_FETCH(); if (module->type == MODULE_TEMPORARY) { zend_clean_module_rsrc_dtors(module->module_number TSRMLS_CC); clean_module_constants(module->module_number TSRMLS_CC); clean_module_classes(module->module_number TSRMLS_CC); } if (module->module_started && module->module_shutdown_func) { #if 0 zend_printf("%s: Module shutdown\n", module->name); #endif module->module_shutdown_func(module->type, module->module_number TSRMLS_CC); } /* Deinitilaise module globals */ if (module->globals_size) { #ifdef ZTS ts_free_id(*module->globals_id_ptr); #else if (module->globals_dtor) { module->globals_dtor(module->globals_ptr TSRMLS_CC); } #endif } module->module_started=0; if (module->functions) { zend_unregister_functions(module->functions, -1, NULL TSRMLS_CC); } #if HAVE_LIBDL #if !(defined(NETWARE) && defined(APACHE_1_BUILD)) if (module->handle && !getenv("ZEND_DONT_UNLOAD_MODULES")) { DL_UNLOAD(module->handle); } #endif #endif } /* }}} */ void zend_activate_modules(TSRMLS_D) /* {{{ */ { zend_module_entry **p = module_request_startup_handlers; while (*p) { zend_module_entry *module = *p; if (module->request_startup_func(module->type, module->module_number TSRMLS_CC)==FAILURE) { zend_error(E_WARNING, "request_startup() for %s module failed", module->name); exit(1); } p++; } } /* }}} */ /* call request shutdown for all modules */ int module_registry_cleanup(zend_module_entry *module TSRMLS_DC) /* {{{ */ { if (module->request_shutdown_func) { #if 0 zend_printf("%s: Request shutdown\n", module->name); #endif module->request_shutdown_func(module->type, module->module_number TSRMLS_CC); } return 0; } /* }}} */ void zend_deactivate_modules(TSRMLS_D) /* {{{ */ { EG(opline_ptr) = NULL; /* we're no longer executing anything */ zend_try { if (EG(full_tables_cleanup)) { zend_hash_reverse_apply(&module_registry, (apply_func_t) module_registry_cleanup TSRMLS_CC); } else { zend_module_entry **p = module_request_shutdown_handlers; while (*p) { zend_module_entry *module = *p; module->request_shutdown_func(module->type, module->module_number TSRMLS_CC); p++; } } } zend_end_try(); } /* }}} */ ZEND_API void zend_cleanup_internal_classes(TSRMLS_D) /* {{{ */ { zend_class_entry **p = class_cleanup_handlers; while (*p) { zend_cleanup_internal_class_data(*p TSRMLS_CC); p++; } } /* }}} */ int module_registry_unload_temp(const zend_module_entry *module TSRMLS_DC) /* {{{ */ { return (module->type == MODULE_TEMPORARY) ? ZEND_HASH_APPLY_REMOVE : ZEND_HASH_APPLY_STOP; } /* }}} */ static int exec_done_cb(zend_module_entry *module TSRMLS_DC) /* {{{ */ { if (module->post_deactivate_func) { module->post_deactivate_func(); } return 0; } /* }}} */ void zend_post_deactivate_modules(TSRMLS_D) /* {{{ */ { if (EG(full_tables_cleanup)) { zend_hash_apply(&module_registry, (apply_func_t) exec_done_cb TSRMLS_CC); zend_hash_reverse_apply(&module_registry, (apply_func_t) module_registry_unload_temp TSRMLS_CC); } else { zend_module_entry **p = module_post_deactivate_handlers; while (*p) { zend_module_entry *module = *p; module->post_deactivate_func(); p++; } } } /* }}} */ /* return the next free module number */ int zend_next_free_module(void) /* {{{ */ { return ++module_count; } /* }}} */ static zend_class_entry *do_register_internal_class(zend_class_entry *orig_class_entry, zend_uint ce_flags TSRMLS_DC) /* {{{ */ { zend_class_entry *class_entry = malloc(sizeof(zend_class_entry)); char *lowercase_name = emalloc(orig_class_entry->name_length + 1); *class_entry = *orig_class_entry; class_entry->type = ZEND_INTERNAL_CLASS; zend_initialize_class_data(class_entry, 0 TSRMLS_CC); class_entry->ce_flags = ce_flags; class_entry->info.internal.module = EG(current_module); if (class_entry->info.internal.builtin_functions) { zend_register_functions(class_entry, class_entry->info.internal.builtin_functions, &class_entry->function_table, MODULE_PERSISTENT TSRMLS_CC); } zend_str_tolower_copy(lowercase_name, orig_class_entry->name, class_entry->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, class_entry->name_length + 1, 1 TSRMLS_CC); if (IS_INTERNED(lowercase_name)) { zend_hash_quick_update(CG(class_table), lowercase_name, class_entry->name_length+1, INTERNED_HASH(lowercase_name), &class_entry, sizeof(zend_class_entry *), NULL); } else { zend_hash_update(CG(class_table), lowercase_name, class_entry->name_length+1, &class_entry, sizeof(zend_class_entry *), NULL); } str_efree(lowercase_name); return class_entry; } /* }}} */ /* If parent_ce is not NULL then it inherits from parent_ce * If parent_ce is NULL and parent_name isn't then it looks for the parent and inherits from it * If both parent_ce and parent_name are NULL it does a regular class registration * If parent_name is specified but not found NULL is returned */ ZEND_API zend_class_entry *zend_register_internal_class_ex(zend_class_entry *class_entry, zend_class_entry *parent_ce, char *parent_name TSRMLS_DC) /* {{{ */ { zend_class_entry *register_class; if (!parent_ce && parent_name) { zend_class_entry **pce; if (zend_hash_find(CG(class_table), parent_name, strlen(parent_name)+1, (void **) &pce)==FAILURE) { return NULL; } else { parent_ce = *pce; } } register_class = zend_register_internal_class(class_entry TSRMLS_CC); if (parent_ce) { zend_do_inheritance(register_class, parent_ce TSRMLS_CC); } return register_class; } /* }}} */ ZEND_API void zend_class_implements(zend_class_entry *class_entry TSRMLS_DC, int num_interfaces, ...) /* {{{ */ { zend_class_entry *interface_entry; va_list interface_list; va_start(interface_list, num_interfaces); while (num_interfaces--) { interface_entry = va_arg(interface_list, zend_class_entry *); zend_do_implement_interface(class_entry, interface_entry TSRMLS_CC); } va_end(interface_list); } /* }}} */ /* A class that contains at least one abstract method automatically becomes an abstract class. */ ZEND_API zend_class_entry *zend_register_internal_class(zend_class_entry *orig_class_entry TSRMLS_DC) /* {{{ */ { return do_register_internal_class(orig_class_entry, 0 TSRMLS_CC); } /* }}} */ ZEND_API zend_class_entry *zend_register_internal_interface(zend_class_entry *orig_class_entry TSRMLS_DC) /* {{{ */ { return do_register_internal_class(orig_class_entry, ZEND_ACC_INTERFACE TSRMLS_CC); } /* }}} */ ZEND_API int zend_register_class_alias_ex(const char *name, int name_len, zend_class_entry *ce TSRMLS_DC) /* {{{ */ { char *lcname = zend_str_tolower_dup(name, name_len); int ret; ret = zend_hash_add(CG(class_table), lcname, name_len+1, &ce, sizeof(zend_class_entry *), NULL); efree(lcname); if (ret == SUCCESS) { ce->refcount++; } return ret; } /* }}} */ ZEND_API int zend_set_hash_symbol(zval *symbol, const char *name, int name_length, zend_bool is_ref, int num_symbol_tables, ...) /* {{{ */ { HashTable *symbol_table; va_list symbol_table_list; if (num_symbol_tables <= 0) return FAILURE; Z_SET_ISREF_TO_P(symbol, is_ref); va_start(symbol_table_list, num_symbol_tables); while (num_symbol_tables-- > 0) { symbol_table = va_arg(symbol_table_list, HashTable *); zend_hash_update(symbol_table, name, name_length + 1, &symbol, sizeof(zval *), NULL); zval_add_ref(&symbol); } va_end(symbol_table_list); return SUCCESS; } /* }}} */ /* Disabled functions support */ /* {{{ proto void display_disabled_function(void) Dummy function which displays an error when a disabled function is called. */ ZEND_API ZEND_FUNCTION(display_disabled_function) { zend_error(E_WARNING, "%s() has been disabled for security reasons", get_active_function_name(TSRMLS_C)); } /* }}} */ static zend_function_entry disabled_function[] = { ZEND_FE(display_disabled_function, NULL) ZEND_FE_END }; ZEND_API int zend_disable_function(char *function_name, uint function_name_length TSRMLS_DC) /* {{{ */ { if (zend_hash_del(CG(function_table), function_name, function_name_length+1)==FAILURE) { return FAILURE; } disabled_function[0].fname = function_name; return zend_register_functions(NULL, disabled_function, CG(function_table), MODULE_PERSISTENT TSRMLS_CC); } /* }}} */ static zend_object_value display_disabled_class(zend_class_entry *class_type TSRMLS_DC) /* {{{ */ { zend_object_value retval; zend_object *intern; retval = zend_objects_new(&intern, class_type TSRMLS_CC); zend_error(E_WARNING, "%s() has been disabled for security reasons", class_type->name); return retval; } /* }}} */ static const zend_function_entry disabled_class_new[] = { ZEND_FE_END }; ZEND_API int zend_disable_class(char *class_name, uint class_name_length TSRMLS_DC) /* {{{ */ { zend_class_entry disabled_class; zend_str_tolower(class_name, class_name_length); if (zend_hash_del(CG(class_table), class_name, class_name_length+1)==FAILURE) { return FAILURE; } INIT_OVERLOADED_CLASS_ENTRY_EX(disabled_class, class_name, class_name_length, disabled_class_new, NULL, NULL, NULL, NULL, NULL); disabled_class.create_object = display_disabled_class; disabled_class.name_length = class_name_length; zend_register_internal_class(&disabled_class TSRMLS_CC); return SUCCESS; } /* }}} */ static int zend_is_callable_check_class(const char *name, int name_len, zend_fcall_info_cache *fcc, int *strict_class, char **error TSRMLS_DC) /* {{{ */ { int ret = 0; zend_class_entry **pce; char *lcname = zend_str_tolower_dup(name, name_len); *strict_class = 0; if (name_len == sizeof("self") - 1 && !memcmp(lcname, "self", sizeof("self") - 1)) { if (!EG(scope)) { if (error) *error = estrdup("cannot access self:: when no class scope is active"); } else { fcc->called_scope = EG(called_scope); fcc->calling_scope = EG(scope); if (!fcc->object_ptr) { fcc->object_ptr = EG(This); } ret = 1; } } else if (name_len == sizeof("parent") - 1 && !memcmp(lcname, "parent", sizeof("parent") - 1)) { if (!EG(scope)) { if (error) *error = estrdup("cannot access parent:: when no class scope is active"); } else if (!EG(scope)->parent) { if (error) *error = estrdup("cannot access parent:: when current class scope has no parent"); } else { fcc->called_scope = EG(called_scope); fcc->calling_scope = EG(scope)->parent; if (!fcc->object_ptr) { fcc->object_ptr = EG(This); } *strict_class = 1; ret = 1; } } else if (name_len == sizeof("static") - 1 && !memcmp(lcname, "static", sizeof("static") - 1)) { if (!EG(called_scope)) { if (error) *error = estrdup("cannot access static:: when no class scope is active"); } else { fcc->called_scope = EG(called_scope); fcc->calling_scope = EG(called_scope); if (!fcc->object_ptr) { fcc->object_ptr = EG(This); } *strict_class = 1; ret = 1; } } else if (zend_lookup_class_ex(name, name_len, NULL, 1, &pce TSRMLS_CC) == SUCCESS) { zend_class_entry *scope = EG(active_op_array) ? EG(active_op_array)->scope : NULL; fcc->calling_scope = *pce; if (scope && !fcc->object_ptr && EG(This) && instanceof_function(Z_OBJCE_P(EG(This)), scope TSRMLS_CC) && instanceof_function(scope, fcc->calling_scope TSRMLS_CC)) { fcc->object_ptr = EG(This); fcc->called_scope = Z_OBJCE_P(fcc->object_ptr); } else { fcc->called_scope = fcc->object_ptr ? Z_OBJCE_P(fcc->object_ptr) : fcc->calling_scope; } *strict_class = 1; ret = 1; } else { if (error) zend_spprintf(error, 0, "class '%.*s' not found", name_len, name); } efree(lcname); return ret; } /* }}} */ static int zend_is_callable_check_func(int check_flags, zval *callable, zend_fcall_info_cache *fcc, int strict_class, char **error TSRMLS_DC) /* {{{ */ { zend_class_entry *ce_org = fcc->calling_scope; int retval = 0; char *mname, *lmname; const char *colon; int clen, mlen; zend_class_entry *last_scope; HashTable *ftable; int call_via_handler = 0; if (error) { *error = NULL; } fcc->calling_scope = NULL; fcc->function_handler = NULL; if (!ce_org) { /* Skip leading \ */ if (Z_STRVAL_P(callable)[0] == '\\') { mlen = Z_STRLEN_P(callable) - 1; mname = Z_STRVAL_P(callable) + 1; lmname = zend_str_tolower_dup(Z_STRVAL_P(callable) + 1, mlen); } else { mlen = Z_STRLEN_P(callable); mname = Z_STRVAL_P(callable); lmname = zend_str_tolower_dup(Z_STRVAL_P(callable), mlen); } /* Check if function with given name exists. * This may be a compound name that includes namespace name */ if (zend_hash_find(EG(function_table), lmname, mlen+1, (void**)&fcc->function_handler) == SUCCESS) { efree(lmname); return 1; } efree(lmname); } /* Split name into class/namespace and method/function names */ if ((colon = zend_memrchr(Z_STRVAL_P(callable), ':', Z_STRLEN_P(callable))) != NULL && colon > Z_STRVAL_P(callable) && *(colon-1) == ':' ) { colon--; clen = colon - Z_STRVAL_P(callable); mlen = Z_STRLEN_P(callable) - clen - 2; if (colon == Z_STRVAL_P(callable)) { if (error) zend_spprintf(error, 0, "invalid function name"); return 0; } /* This is a compound name. * Try to fetch class and then find static method. */ last_scope = EG(scope); if (ce_org) { EG(scope) = ce_org; } if (!zend_is_callable_check_class(Z_STRVAL_P(callable), clen, fcc, &strict_class, error TSRMLS_CC)) { EG(scope) = last_scope; return 0; } EG(scope) = last_scope; ftable = &fcc->calling_scope->function_table; if (ce_org && !instanceof_function(ce_org, fcc->calling_scope TSRMLS_CC)) { if (error) zend_spprintf(error, 0, "class '%s' is not a subclass of '%s'", ce_org->name, fcc->calling_scope->name); return 0; } mname = Z_STRVAL_P(callable) + clen + 2; } else if (ce_org) { /* Try to fetch find static method of given class. */ mlen = Z_STRLEN_P(callable); mname = Z_STRVAL_P(callable); ftable = &ce_org->function_table; fcc->calling_scope = ce_org; } else { /* We already checked for plain function before. */ if (error && !(check_flags & IS_CALLABLE_CHECK_SILENT)) { zend_spprintf(error, 0, "function '%s' not found or invalid function name", Z_STRVAL_P(callable)); } return 0; } lmname = zend_str_tolower_dup(mname, mlen); if (strict_class && fcc->calling_scope && mlen == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1 && !memcmp(lmname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME))) { fcc->function_handler = fcc->calling_scope->constructor; if (fcc->function_handler) { retval = 1; } } else if (zend_hash_find(ftable, lmname, mlen+1, (void**)&fcc->function_handler) == SUCCESS) { retval = 1; if ((fcc->function_handler->op_array.fn_flags & ZEND_ACC_CHANGED) && EG(scope) && instanceof_function(fcc->function_handler->common.scope, EG(scope) TSRMLS_CC)) { zend_function *priv_fbc; if (zend_hash_find(&EG(scope)->function_table, lmname, mlen+1, (void **) &priv_fbc)==SUCCESS && priv_fbc->common.fn_flags & ZEND_ACC_PRIVATE && priv_fbc->common.scope == EG(scope)) { fcc->function_handler = priv_fbc; } } if ((check_flags & IS_CALLABLE_CHECK_NO_ACCESS) == 0 && (fcc->calling_scope && (fcc->calling_scope->__call || fcc->calling_scope->__callstatic))) { if (fcc->function_handler->op_array.fn_flags & ZEND_ACC_PRIVATE) { if (!zend_check_private(fcc->function_handler, fcc->object_ptr ? Z_OBJCE_P(fcc->object_ptr) : EG(scope), lmname, mlen TSRMLS_CC)) { retval = 0; fcc->function_handler = NULL; goto get_function_via_handler; } } else if (fcc->function_handler->common.fn_flags & ZEND_ACC_PROTECTED) { if (!zend_check_protected(fcc->function_handler->common.scope, EG(scope))) { retval = 0; fcc->function_handler = NULL; goto get_function_via_handler; } } } } else { get_function_via_handler: if (fcc->object_ptr && fcc->calling_scope == ce_org) { if (strict_class && ce_org->__call) { fcc->function_handler = emalloc(sizeof(zend_internal_function)); fcc->function_handler->internal_function.type = ZEND_INTERNAL_FUNCTION; fcc->function_handler->internal_function.module = (ce_org->type == ZEND_INTERNAL_CLASS) ? ce_org->info.internal.module : NULL; fcc->function_handler->internal_function.handler = zend_std_call_user_call; fcc->function_handler->internal_function.arg_info = NULL; fcc->function_handler->internal_function.num_args = 0; fcc->function_handler->internal_function.scope = ce_org; fcc->function_handler->internal_function.fn_flags = ZEND_ACC_CALL_VIA_HANDLER; fcc->function_handler->internal_function.function_name = estrndup(mname, mlen); call_via_handler = 1; retval = 1; } else if (Z_OBJ_HT_P(fcc->object_ptr)->get_method) { fcc->function_handler = Z_OBJ_HT_P(fcc->object_ptr)->get_method(&fcc->object_ptr, mname, mlen, NULL TSRMLS_CC); if (fcc->function_handler) { if (strict_class && (!fcc->function_handler->common.scope || !instanceof_function(ce_org, fcc->function_handler->common.scope TSRMLS_CC))) { if ((fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) != 0) { if (fcc->function_handler->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fcc->function_handler->common.function_name); } efree(fcc->function_handler); } } else { retval = 1; call_via_handler = (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) != 0; } } } } else if (fcc->calling_scope) { if (fcc->calling_scope->get_static_method) { fcc->function_handler = fcc->calling_scope->get_static_method(fcc->calling_scope, mname, mlen TSRMLS_CC); } else { fcc->function_handler = zend_std_get_static_method(fcc->calling_scope, mname, mlen, NULL TSRMLS_CC); } if (fcc->function_handler) { retval = 1; call_via_handler = (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) != 0; if (call_via_handler && !fcc->object_ptr && EG(This) && Z_OBJ_HT_P(EG(This))->get_class_entry && instanceof_function(Z_OBJCE_P(EG(This)), fcc->calling_scope TSRMLS_CC)) { fcc->object_ptr = EG(This); } } } } if (retval) { if (fcc->calling_scope && !call_via_handler) { if (!fcc->object_ptr && !(fcc->function_handler->common.fn_flags & ZEND_ACC_STATIC)) { int severity; char *verb; if (fcc->function_handler->common.fn_flags & ZEND_ACC_ALLOW_STATIC) { severity = E_STRICT; verb = "should not"; } else { /* An internal function assumes $this is present and won't check that. So PHP would crash by allowing the call. */ severity = E_ERROR; verb = "cannot"; } if ((check_flags & IS_CALLABLE_CHECK_IS_STATIC) != 0) { retval = 0; } if (EG(This) && instanceof_function(Z_OBJCE_P(EG(This)), fcc->calling_scope TSRMLS_CC)) { fcc->object_ptr = EG(This); if (error) { zend_spprintf(error, 0, "non-static method %s::%s() %s be called statically, assuming $this from compatible context %s", fcc->calling_scope->name, fcc->function_handler->common.function_name, verb, Z_OBJCE_P(EG(This))->name); if (severity == E_ERROR) { retval = 0; } } else if (retval) { zend_error(severity, "Non-static method %s::%s() %s be called statically, assuming $this from compatible context %s", fcc->calling_scope->name, fcc->function_handler->common.function_name, verb, Z_OBJCE_P(EG(This))->name); } } else { if (error) { zend_spprintf(error, 0, "non-static method %s::%s() %s be called statically", fcc->calling_scope->name, fcc->function_handler->common.function_name, verb); if (severity == E_ERROR) { retval = 0; } } else if (retval) { zend_error(severity, "Non-static method %s::%s() %s be called statically", fcc->calling_scope->name, fcc->function_handler->common.function_name, verb); } } } if (retval && (check_flags & IS_CALLABLE_CHECK_NO_ACCESS) == 0) { if (fcc->function_handler->op_array.fn_flags & ZEND_ACC_PRIVATE) { if (!zend_check_private(fcc->function_handler, fcc->object_ptr ? Z_OBJCE_P(fcc->object_ptr) : EG(scope), lmname, mlen TSRMLS_CC)) { if (error) { if (*error) { efree(*error); } zend_spprintf(error, 0, "cannot access private method %s::%s()", fcc->calling_scope->name, fcc->function_handler->common.function_name); } retval = 0; } } else if ((fcc->function_handler->common.fn_flags & ZEND_ACC_PROTECTED)) { if (!zend_check_protected(fcc->function_handler->common.scope, EG(scope))) { if (error) { if (*error) { efree(*error); } zend_spprintf(error, 0, "cannot access protected method %s::%s()", fcc->calling_scope->name, fcc->function_handler->common.function_name); } retval = 0; } } } } } else if (error && !(check_flags & IS_CALLABLE_CHECK_SILENT)) { if (fcc->calling_scope) { if (error) zend_spprintf(error, 0, "class '%s' does not have a method '%s'", fcc->calling_scope->name, mname); } else { if (error) zend_spprintf(error, 0, "function '%s' does not exist", mname); } } efree(lmname); if (fcc->object_ptr) { fcc->called_scope = Z_OBJCE_P(fcc->object_ptr); } if (retval) { fcc->initialized = 1; } return retval; } /* }}} */ ZEND_API zend_bool zend_is_callable_ex(zval *callable, zval *object_ptr, uint check_flags, char **callable_name, int *callable_name_len, zend_fcall_info_cache *fcc, char **error TSRMLS_DC) /* {{{ */ { zend_bool ret; int callable_name_len_local; zend_fcall_info_cache fcc_local; if (callable_name) { *callable_name = NULL; } if (callable_name_len == NULL) { callable_name_len = &callable_name_len_local; } if (fcc == NULL) { fcc = &fcc_local; } if (error) { *error = NULL; } fcc->initialized = 0; fcc->calling_scope = NULL; fcc->called_scope = NULL; fcc->function_handler = NULL; fcc->calling_scope = NULL; fcc->object_ptr = NULL; if (object_ptr && Z_TYPE_P(object_ptr) != IS_OBJECT) { object_ptr = NULL; } if (object_ptr && (!EG(objects_store).object_buckets || !EG(objects_store).object_buckets[Z_OBJ_HANDLE_P(object_ptr)].valid)) { return 0; } switch (Z_TYPE_P(callable)) { case IS_STRING: if (object_ptr) { fcc->object_ptr = object_ptr; fcc->calling_scope = Z_OBJCE_P(object_ptr); if (callable_name) { char *ptr; *callable_name_len = fcc->calling_scope->name_length + Z_STRLEN_P(callable) + sizeof("::") - 1; ptr = *callable_name = emalloc(*callable_name_len + 1); memcpy(ptr, fcc->calling_scope->name, fcc->calling_scope->name_length); ptr += fcc->calling_scope->name_length; memcpy(ptr, "::", sizeof("::") - 1); ptr += sizeof("::") - 1; memcpy(ptr, Z_STRVAL_P(callable), Z_STRLEN_P(callable) + 1); } } else if (callable_name) { *callable_name = estrndup(Z_STRVAL_P(callable), Z_STRLEN_P(callable)); *callable_name_len = Z_STRLEN_P(callable); } if (check_flags & IS_CALLABLE_CHECK_SYNTAX_ONLY) { fcc->called_scope = fcc->calling_scope; return 1; } ret = zend_is_callable_check_func(check_flags, callable, fcc, 0, error TSRMLS_CC); if (fcc == &fcc_local && fcc->function_handler && ((fcc->function_handler->type == ZEND_INTERNAL_FUNCTION && (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER)) || fcc->function_handler->type == ZEND_OVERLOADED_FUNCTION_TEMPORARY || fcc->function_handler->type == ZEND_OVERLOADED_FUNCTION)) { if (fcc->function_handler->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fcc->function_handler->common.function_name); } efree(fcc->function_handler); } return ret; case IS_ARRAY: { zval **method = NULL; zval **obj = NULL; int strict_class = 0; if (zend_hash_num_elements(Z_ARRVAL_P(callable)) == 2) { zend_hash_index_find(Z_ARRVAL_P(callable), 0, (void **) &obj); zend_hash_index_find(Z_ARRVAL_P(callable), 1, (void **) &method); } if (obj && method && (Z_TYPE_PP(obj) == IS_OBJECT || Z_TYPE_PP(obj) == IS_STRING) && Z_TYPE_PP(method) == IS_STRING) { if (Z_TYPE_PP(obj) == IS_STRING) { if (callable_name) { char *ptr; *callable_name_len = Z_STRLEN_PP(obj) + Z_STRLEN_PP(method) + sizeof("::") - 1; ptr = *callable_name = emalloc(*callable_name_len + 1); memcpy(ptr, Z_STRVAL_PP(obj), Z_STRLEN_PP(obj)); ptr += Z_STRLEN_PP(obj); memcpy(ptr, "::", sizeof("::") - 1); ptr += sizeof("::") - 1; memcpy(ptr, Z_STRVAL_PP(method), Z_STRLEN_PP(method) + 1); } if (check_flags & IS_CALLABLE_CHECK_SYNTAX_ONLY) { return 1; } if (!zend_is_callable_check_class(Z_STRVAL_PP(obj), Z_STRLEN_PP(obj), fcc, &strict_class, error TSRMLS_CC)) { return 0; } } else { if (!EG(objects_store).object_buckets || !EG(objects_store).object_buckets[Z_OBJ_HANDLE_PP(obj)].valid) { return 0; } fcc->calling_scope = Z_OBJCE_PP(obj); /* TBFixed: what if it's overloaded? */ fcc->object_ptr = *obj; if (callable_name) { char *ptr; *callable_name_len = fcc->calling_scope->name_length + Z_STRLEN_PP(method) + sizeof("::") - 1; ptr = *callable_name = emalloc(*callable_name_len + 1); memcpy(ptr, fcc->calling_scope->name, fcc->calling_scope->name_length); ptr += fcc->calling_scope->name_length; memcpy(ptr, "::", sizeof("::") - 1); ptr += sizeof("::") - 1; memcpy(ptr, Z_STRVAL_PP(method), Z_STRLEN_PP(method) + 1); } if (check_flags & IS_CALLABLE_CHECK_SYNTAX_ONLY) { fcc->called_scope = fcc->calling_scope; return 1; } } ret = zend_is_callable_check_func(check_flags, *method, fcc, strict_class, error TSRMLS_CC); if (fcc == &fcc_local && fcc->function_handler && ((fcc->function_handler->type == ZEND_INTERNAL_FUNCTION && (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER)) || fcc->function_handler->type == ZEND_OVERLOADED_FUNCTION_TEMPORARY || fcc->function_handler->type == ZEND_OVERLOADED_FUNCTION)) { if (fcc->function_handler->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fcc->function_handler->common.function_name); } efree(fcc->function_handler); } return ret; } else { if (zend_hash_num_elements(Z_ARRVAL_P(callable)) == 2) { if (!obj || (Z_TYPE_PP(obj) != IS_STRING && Z_TYPE_PP(obj) != IS_OBJECT)) { if (error) zend_spprintf(error, 0, "first array member is not a valid class name or object"); } else { if (error) zend_spprintf(error, 0, "second array member is not a valid method"); } } else { if (error) zend_spprintf(error, 0, "array must have exactly two members"); } if (callable_name) { *callable_name = estrndup("Array", sizeof("Array")-1); *callable_name_len = sizeof("Array") - 1; } } } return 0; case IS_OBJECT: if (Z_OBJ_HANDLER_P(callable, get_closure) && Z_OBJ_HANDLER_P(callable, get_closure)(callable, &fcc->calling_scope, &fcc->function_handler, &fcc->object_ptr TSRMLS_CC) == SUCCESS) { fcc->called_scope = fcc->calling_scope; if (callable_name) { zend_class_entry *ce = Z_OBJCE_P(callable); /* TBFixed: what if it's overloaded? */ *callable_name_len = ce->name_length + sizeof("::__invoke") - 1; *callable_name = emalloc(*callable_name_len + 1); memcpy(*callable_name, ce->name, ce->name_length); memcpy((*callable_name) + ce->name_length, "::__invoke", sizeof("::__invoke")); } return 1; } /* break missing intentionally */ default: if (callable_name) { zval expr_copy; int use_copy; zend_make_printable_zval(callable, &expr_copy, &use_copy); *callable_name = estrndup(Z_STRVAL(expr_copy), Z_STRLEN(expr_copy)); *callable_name_len = Z_STRLEN(expr_copy); zval_dtor(&expr_copy); } if (error) zend_spprintf(error, 0, "no array or string given"); return 0; } } /* }}} */ ZEND_API zend_bool zend_is_callable(zval *callable, uint check_flags, char **callable_name TSRMLS_DC) /* {{{ */ { return zend_is_callable_ex(callable, NULL, check_flags, callable_name, NULL, NULL, NULL TSRMLS_CC); } /* }}} */ ZEND_API zend_bool zend_make_callable(zval *callable, char **callable_name TSRMLS_DC) /* {{{ */ { zend_fcall_info_cache fcc; if (zend_is_callable_ex(callable, NULL, IS_CALLABLE_STRICT, callable_name, NULL, &fcc, NULL TSRMLS_CC)) { if (Z_TYPE_P(callable) == IS_STRING && fcc.calling_scope) { zval_dtor(callable); array_init(callable); add_next_index_string(callable, fcc.calling_scope->name, 1); add_next_index_string(callable, fcc.function_handler->common.function_name, 1); } if (fcc.function_handler && ((fcc.function_handler->type == ZEND_INTERNAL_FUNCTION && (fcc.function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER)) || fcc.function_handler->type == ZEND_OVERLOADED_FUNCTION_TEMPORARY || fcc.function_handler->type == ZEND_OVERLOADED_FUNCTION)) { if (fcc.function_handler->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fcc.function_handler->common.function_name); } efree(fcc.function_handler); } return 1; } return 0; } /* }}} */ ZEND_API int zend_fcall_info_init(zval *callable, uint check_flags, zend_fcall_info *fci, zend_fcall_info_cache *fcc, char **callable_name, char **error TSRMLS_DC) /* {{{ */ { if (!zend_is_callable_ex(callable, NULL, check_flags, callable_name, NULL, fcc, error TSRMLS_CC)) { return FAILURE; } fci->size = sizeof(*fci); fci->function_table = fcc->calling_scope ? &fcc->calling_scope->function_table : EG(function_table); fci->object_ptr = fcc->object_ptr; fci->function_name = callable; fci->retval_ptr_ptr = NULL; fci->param_count = 0; fci->params = NULL; fci->no_separation = 1; fci->symbol_table = NULL; return SUCCESS; } /* }}} */ ZEND_API void zend_fcall_info_args_clear(zend_fcall_info *fci, int free_mem) /* {{{ */ { if (fci->params) { if (free_mem) { efree(fci->params); fci->params = NULL; } } fci->param_count = 0; } /* }}} */ ZEND_API void zend_fcall_info_args_save(zend_fcall_info *fci, int *param_count, zval ****params) /* {{{ */ { *param_count = fci->param_count; *params = fci->params; fci->param_count = 0; fci->params = NULL; } /* }}} */ ZEND_API void zend_fcall_info_args_restore(zend_fcall_info *fci, int param_count, zval ***params) /* {{{ */ { zend_fcall_info_args_clear(fci, 1); fci->param_count = param_count; fci->params = params; } /* }}} */ ZEND_API int zend_fcall_info_args(zend_fcall_info *fci, zval *args TSRMLS_DC) /* {{{ */ { HashPosition pos; zval **arg, ***params; zend_fcall_info_args_clear(fci, !args); if (!args) { return SUCCESS; } if (Z_TYPE_P(args) != IS_ARRAY) { return FAILURE; } fci->param_count = zend_hash_num_elements(Z_ARRVAL_P(args)); fci->params = params = (zval ***) erealloc(fci->params, fci->param_count * sizeof(zval **)); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(args), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(args), (void *) &arg, &pos) == SUCCESS) { *params++ = arg; zend_hash_move_forward_ex(Z_ARRVAL_P(args), &pos); } return SUCCESS; } /* }}} */ ZEND_API int zend_fcall_info_argp(zend_fcall_info *fci TSRMLS_DC, int argc, zval ***argv) /* {{{ */ { int i; if (argc < 0) { return FAILURE; } zend_fcall_info_args_clear(fci, !argc); if (argc) { fci->param_count = argc; fci->params = (zval ***) erealloc(fci->params, fci->param_count * sizeof(zval **)); for (i = 0; i < argc; ++i) { fci->params[i] = argv[i]; } } return SUCCESS; } /* }}} */ ZEND_API int zend_fcall_info_argv(zend_fcall_info *fci TSRMLS_DC, int argc, va_list *argv) /* {{{ */ { int i; zval **arg; if (argc < 0) { return FAILURE; } zend_fcall_info_args_clear(fci, !argc); if (argc) { fci->param_count = argc; fci->params = (zval ***) erealloc(fci->params, fci->param_count * sizeof(zval **)); for (i = 0; i < argc; ++i) { arg = va_arg(*argv, zval **); fci->params[i] = arg; } } return SUCCESS; } /* }}} */ ZEND_API int zend_fcall_info_argn(zend_fcall_info *fci TSRMLS_DC, int argc, ...) /* {{{ */ { int ret; va_list argv; va_start(argv, argc); ret = zend_fcall_info_argv(fci TSRMLS_CC, argc, &argv); va_end(argv); return ret; } /* }}} */ ZEND_API int zend_fcall_info_call(zend_fcall_info *fci, zend_fcall_info_cache *fcc, zval **retval_ptr_ptr, zval *args TSRMLS_DC) /* {{{ */ { zval *retval, ***org_params = NULL; int result, org_count = 0; fci->retval_ptr_ptr = retval_ptr_ptr ? retval_ptr_ptr : &retval; if (args) { zend_fcall_info_args_save(fci, &org_count, &org_params); zend_fcall_info_args(fci, args TSRMLS_CC); } result = zend_call_function(fci, fcc TSRMLS_CC); if (!retval_ptr_ptr && retval) { zval_ptr_dtor(&retval); } if (args) { zend_fcall_info_args_restore(fci, org_count, org_params); } return result; } /* }}} */ ZEND_API const char *zend_get_module_version(const char *module_name) /* {{{ */ { char *lname; int name_len = strlen(module_name); zend_module_entry *module; lname = zend_str_tolower_dup(module_name, name_len); if (zend_hash_find(&module_registry, lname, name_len + 1, (void**)&module) == FAILURE) { efree(lname); return NULL; } efree(lname); return module->version; } /* }}} */ ZEND_API int zend_declare_property_ex(zend_class_entry *ce, const char *name, int name_length, zval *property, int access_type, const char *doc_comment, int doc_comment_len TSRMLS_DC) /* {{{ */ { zend_property_info property_info, *property_info_ptr; const char *interned_name; ulong h = zend_get_hash_value(name, name_length+1); if (!(access_type & ZEND_ACC_PPP_MASK)) { access_type |= ZEND_ACC_PUBLIC; } if (access_type & ZEND_ACC_STATIC) { if (zend_hash_quick_find(&ce->properties_info, name, name_length + 1, h, (void**)&property_info_ptr) == SUCCESS && (property_info_ptr->flags & ZEND_ACC_STATIC) != 0) { property_info.offset = property_info_ptr->offset; zval_ptr_dtor(&ce->default_static_members_table[property_info.offset]); zend_hash_quick_del(&ce->properties_info, name, name_length + 1, h); } else { property_info.offset = ce->default_static_members_count++; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(zval*) * ce->default_static_members_count, ce->type == ZEND_INTERNAL_CLASS); } ce->default_static_members_table[property_info.offset] = property; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } else { if (zend_hash_quick_find(&ce->properties_info, name, name_length + 1, h, (void**)&property_info_ptr) == SUCCESS && (property_info_ptr->flags & ZEND_ACC_STATIC) == 0) { property_info.offset = property_info_ptr->offset; zval_ptr_dtor(&ce->default_properties_table[property_info.offset]); zend_hash_quick_del(&ce->properties_info, name, name_length + 1, h); } else { property_info.offset = ce->default_properties_count++; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(zval*) * ce->default_properties_count, ce->type == ZEND_INTERNAL_CLASS); } ce->default_properties_table[property_info.offset] = property; } if (ce->type & ZEND_INTERNAL_CLASS) { switch(Z_TYPE_P(property)) { case IS_ARRAY: case IS_CONSTANT_ARRAY: case IS_OBJECT: case IS_RESOURCE: zend_error(E_CORE_ERROR, "Internal zval's can't be arrays, objects or resources"); break; default: break; } } switch (access_type & ZEND_ACC_PPP_MASK) { case ZEND_ACC_PRIVATE: { char *priv_name; int priv_name_length; zend_mangle_property_name(&priv_name, &priv_name_length, ce->name, ce->name_length, name, name_length, ce->type & ZEND_INTERNAL_CLASS); property_info.name = priv_name; property_info.name_length = priv_name_length; } break; case ZEND_ACC_PROTECTED: { char *prot_name; int prot_name_length; zend_mangle_property_name(&prot_name, &prot_name_length, "*", 1, name, name_length, ce->type & ZEND_INTERNAL_CLASS); property_info.name = prot_name; property_info.name_length = prot_name_length; } break; case ZEND_ACC_PUBLIC: if (IS_INTERNED(name)) { property_info.name = (char*)name; } else { property_info.name = ce->type & ZEND_INTERNAL_CLASS ? zend_strndup(name, name_length) : estrndup(name, name_length); } property_info.name_length = name_length; break; } interned_name = zend_new_interned_string(property_info.name, property_info.name_length+1, 0 TSRMLS_CC); if (interned_name != property_info.name) { if (ce->type == ZEND_USER_CLASS) { efree((char*)property_info.name); } else { free((char*)property_info.name); } property_info.name = interned_name; } property_info.flags = access_type; property_info.h = (access_type & ZEND_ACC_PUBLIC) ? h : zend_get_hash_value(property_info.name, property_info.name_length+1); property_info.doc_comment = doc_comment; property_info.doc_comment_len = doc_comment_len; property_info.ce = ce; zend_hash_quick_update(&ce->properties_info, name, name_length+1, h, &property_info, sizeof(zend_property_info), NULL); return SUCCESS; } /* }}} */ ZEND_API int zend_declare_property(zend_class_entry *ce, const char *name, int name_length, zval *property, int access_type TSRMLS_DC) /* {{{ */ { return zend_declare_property_ex(ce, name, name_length, property, access_type, NULL, 0 TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_null(zend_class_entry *ce, const char *name, int name_length, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); } else { ALLOC_ZVAL(property); } INIT_ZVAL(*property); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_bool(zend_class_entry *ce, const char *name, int name_length, long value, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); } else { ALLOC_ZVAL(property); } INIT_PZVAL(property); ZVAL_BOOL(property, value); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_long(zend_class_entry *ce, const char *name, int name_length, long value, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); } else { ALLOC_ZVAL(property); } INIT_PZVAL(property); ZVAL_LONG(property, value); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_double(zend_class_entry *ce, const char *name, int name_length, double value, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); } else { ALLOC_ZVAL(property); } INIT_PZVAL(property); ZVAL_DOUBLE(property, value); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_string(zend_class_entry *ce, const char *name, int name_length, const char *value, int access_type TSRMLS_DC) /* {{{ */ { zval *property; int len = strlen(value); if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); ZVAL_STRINGL(property, zend_strndup(value, len), len, 0); } else { ALLOC_ZVAL(property); ZVAL_STRINGL(property, value, len, 1); } INIT_PZVAL(property); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_stringl(zend_class_entry *ce, const char *name, int name_length, const char *value, int value_len, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); ZVAL_STRINGL(property, zend_strndup(value, value_len), value_len, 0); } else { ALLOC_ZVAL(property); ZVAL_STRINGL(property, value, value_len, 1); } INIT_PZVAL(property); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant(zend_class_entry *ce, const char *name, size_t name_length, zval *value TSRMLS_DC) /* {{{ */ { return zend_hash_update(&ce->constants_table, name, name_length+1, &value, sizeof(zval *), NULL); } /* }}} */ ZEND_API int zend_declare_class_constant_null(zend_class_entry *ce, const char *name, size_t name_length TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); } else { ALLOC_ZVAL(constant); } ZVAL_NULL(constant); INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_long(zend_class_entry *ce, const char *name, size_t name_length, long value TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); } else { ALLOC_ZVAL(constant); } ZVAL_LONG(constant, value); INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_bool(zend_class_entry *ce, const char *name, size_t name_length, zend_bool value TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); } else { ALLOC_ZVAL(constant); } ZVAL_BOOL(constant, value); INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_double(zend_class_entry *ce, const char *name, size_t name_length, double value TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); } else { ALLOC_ZVAL(constant); } ZVAL_DOUBLE(constant, value); INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_stringl(zend_class_entry *ce, const char *name, size_t name_length, const char *value, size_t value_length TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); ZVAL_STRINGL(constant, zend_strndup(value, value_length), value_length, 0); } else { ALLOC_ZVAL(constant); ZVAL_STRINGL(constant, value, value_length, 1); } INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_string(zend_class_entry *ce, const char *name, size_t name_length, const char *value TSRMLS_DC) /* {{{ */ { return zend_declare_class_constant_stringl(ce, name, name_length, value, strlen(value) TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property(zend_class_entry *scope, zval *object, const char *name, int name_length, zval *value TSRMLS_DC) /* {{{ */ { zval *property; zend_class_entry *old_scope = EG(scope); EG(scope) = scope; if (!Z_OBJ_HT_P(object)->write_property) { const char *class_name; zend_uint class_name_len; zend_get_object_classname(object, &class_name, &class_name_len TSRMLS_CC); zend_error(E_CORE_ERROR, "Property %s of class %s cannot be updated", name, class_name); } MAKE_STD_ZVAL(property); ZVAL_STRINGL(property, name, name_length, 1); Z_OBJ_HT_P(object)->write_property(object, property, value, 0 TSRMLS_CC); zval_ptr_dtor(&property); EG(scope) = old_scope; } /* }}} */ ZEND_API void zend_update_property_null(zend_class_entry *scope, zval *object, const char *name, int name_length TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_NULL(tmp); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_bool(zend_class_entry *scope, zval *object, const char *name, int name_length, long value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_BOOL(tmp, value); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_long(zend_class_entry *scope, zval *object, const char *name, int name_length, long value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_LONG(tmp, value); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_double(zend_class_entry *scope, zval *object, const char *name, int name_length, double value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_DOUBLE(tmp, value); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_string(zend_class_entry *scope, zval *object, const char *name, int name_length, const char *value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_STRING(tmp, value, 1); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_stringl(zend_class_entry *scope, zval *object, const char *name, int name_length, const char *value, int value_len TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_STRINGL(tmp, value, value_len, 1); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property(zend_class_entry *scope, const char *name, int name_length, zval *value TSRMLS_DC) /* {{{ */ { zval **property; zend_class_entry *old_scope = EG(scope); EG(scope) = scope; property = zend_std_get_static_property(scope, name, name_length, 0, NULL TSRMLS_CC); EG(scope) = old_scope; if (!property) { return FAILURE; } else { if (*property != value) { if (PZVAL_IS_REF(*property)) { zval_dtor(*property); Z_TYPE_PP(property) = Z_TYPE_P(value); (*property)->value = value->value; if (Z_REFCOUNT_P(value) > 0) { zval_copy_ctor(*property); } } else { zval *garbage = *property; Z_ADDREF_P(value); if (PZVAL_IS_REF(value)) { SEPARATE_ZVAL(&value); } *property = value; zval_ptr_dtor(&garbage); } } return SUCCESS; } } /* }}} */ ZEND_API int zend_update_static_property_null(zend_class_entry *scope, const char *name, int name_length TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_NULL(tmp); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_bool(zend_class_entry *scope, const char *name, int name_length, long value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_BOOL(tmp, value); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_long(zend_class_entry *scope, const char *name, int name_length, long value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_LONG(tmp, value); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_double(zend_class_entry *scope, const char *name, int name_length, double value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_DOUBLE(tmp, value); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_string(zend_class_entry *scope, const char *name, int name_length, const char *value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_STRING(tmp, value, 1); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_stringl(zend_class_entry *scope, const char *name, int name_length, const char *value, int value_len TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_STRINGL(tmp, value, value_len, 1); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API zval *zend_read_property(zend_class_entry *scope, zval *object, const char *name, int name_length, zend_bool silent TSRMLS_DC) /* {{{ */ { zval *property, *value; zend_class_entry *old_scope = EG(scope); EG(scope) = scope; if (!Z_OBJ_HT_P(object)->read_property) { const char *class_name; zend_uint class_name_len; zend_get_object_classname(object, &class_name, &class_name_len TSRMLS_CC); zend_error(E_CORE_ERROR, "Property %s of class %s cannot be read", name, class_name); } MAKE_STD_ZVAL(property); ZVAL_STRINGL(property, name, name_length, 1); value = Z_OBJ_HT_P(object)->read_property(object, property, silent?BP_VAR_IS:BP_VAR_R, 0 TSRMLS_CC); zval_ptr_dtor(&property); EG(scope) = old_scope; return value; } /* }}} */ ZEND_API zval *zend_read_static_property(zend_class_entry *scope, const char *name, int name_length, zend_bool silent TSRMLS_DC) /* {{{ */ { zval **property; zend_class_entry *old_scope = EG(scope); EG(scope) = scope; property = zend_std_get_static_property(scope, name, name_length, silent, NULL TSRMLS_CC); EG(scope) = old_scope; return property?*property:NULL; } /* }}} */ ZEND_API void zend_save_error_handling(zend_error_handling *current TSRMLS_DC) /* {{{ */ { current->handling = EG(error_handling); current->exception = EG(exception_class); current->user_handler = EG(user_error_handler); if (current->user_handler) { Z_ADDREF_P(current->user_handler); } } /* }}} */ ZEND_API void zend_replace_error_handling(zend_error_handling_t error_handling, zend_class_entry *exception_class, zend_error_handling *current TSRMLS_DC) /* {{{ */ { if (current) { zend_save_error_handling(current TSRMLS_CC); if (error_handling != EH_NORMAL && EG(user_error_handler)) { zval_ptr_dtor(&EG(user_error_handler)); EG(user_error_handler) = NULL; } } EG(error_handling) = error_handling; EG(exception_class) = error_handling == EH_THROW ? exception_class : NULL; } /* }}} */ ZEND_API void zend_restore_error_handling(zend_error_handling *saved TSRMLS_DC) /* {{{ */ { EG(error_handling) = saved->handling; EG(exception_class) = saved->handling == EH_THROW ? saved->exception : NULL; if (saved->user_handler && saved->user_handler != EG(user_error_handler)) { if (EG(user_error_handler)) { zval_ptr_dtor(&EG(user_error_handler)); } EG(user_error_handler) = saved->user_handler; } else if (saved->user_handler) { zval_ptr_dtor(&saved->user_handler); } saved->user_handler = NULL; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-10-31-c4eb5f2387-2e5d5e5ac6.c
manybugs_data_16
/* Generated by re2c 0.13.5 on Fri Nov 25 16:42:37 2011 */ #line 1 "ext/date/lib/parse_date.re" /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2010 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Derick Rethans <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "timelib.h" #include <stdio.h> #include <ctype.h> #include <math.h> #include <assert.h> #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #ifdef HAVE_STRING_H #include <string.h> #else #include <strings.h> #endif #if defined(_MSC_VER) # define strtoll(s, f, b) _atoi64(s) #elif !defined(HAVE_STRTOLL) # if defined(HAVE_ATOLL) # define strtoll(s, f, b) atoll(s) # else # define strtoll(s, f, b) strtol(s, f, b) # endif #endif #define TIMELIB_UNSET -99999 #define TIMELIB_SECOND 1 #define TIMELIB_MINUTE 2 #define TIMELIB_HOUR 3 #define TIMELIB_DAY 4 #define TIMELIB_MONTH 5 #define TIMELIB_YEAR 6 #define TIMELIB_WEEKDAY 7 #define TIMELIB_SPECIAL 8 #define EOI 257 #define TIME 258 #define DATE 259 #define TIMELIB_XMLRPC_SOAP 260 #define TIMELIB_TIME12 261 #define TIMELIB_TIME24 262 #define TIMELIB_GNU_NOCOLON 263 #define TIMELIB_GNU_NOCOLON_TZ 264 #define TIMELIB_ISO_NOCOLON 265 #define TIMELIB_AMERICAN 266 #define TIMELIB_ISO_DATE 267 #define TIMELIB_DATE_FULL 268 #define TIMELIB_DATE_TEXT 269 #define TIMELIB_DATE_NOCOLON 270 #define TIMELIB_PG_YEARDAY 271 #define TIMELIB_PG_TEXT 272 #define TIMELIB_PG_REVERSE 273 #define TIMELIB_CLF 274 #define TIMELIB_DATE_NO_DAY 275 #define TIMELIB_SHORTDATE_WITH_TIME 276 #define TIMELIB_DATE_FULL_POINTED 277 #define TIMELIB_TIME24_WITH_ZONE 278 #define TIMELIB_ISO_WEEK 279 #define TIMELIB_LF_DAY_OF_MONTH 280 #define TIMELIB_WEEK_DAY_OF_MONTH 281 #define TIMELIB_TIMEZONE 300 #define TIMELIB_AGO 301 #define TIMELIB_RELATIVE 310 #define TIMELIB_ERROR 999 /* Some compilers like AIX, defines uchar in sys/types.h */ #undef uchar typedef unsigned char uchar; #define BSIZE 8192 #define YYCTYPE uchar #define YYCURSOR cursor #define YYLIMIT s->lim #define YYMARKER s->ptr #define YYFILL(n) return EOI; #define RET(i) {s->cur = cursor; return i;} #define timelib_string_free free #define TIMELIB_HAVE_TIME() { if (s->time->have_time) { add_error(s, "Double time specification"); timelib_string_free(str); return TIMELIB_ERROR; } else { s->time->have_time = 1; s->time->h = 0; s->time->i = 0; s->time->s = 0; s->time->f = 0; } } #define TIMELIB_UNHAVE_TIME() { s->time->have_time = 0; s->time->h = 0; s->time->i = 0; s->time->s = 0; s->time->f = 0; } #define TIMELIB_HAVE_DATE() { if (s->time->have_date) { add_error(s, "Double date specification"); timelib_string_free(str); return TIMELIB_ERROR; } else { s->time->have_date = 1; } } #define TIMELIB_UNHAVE_DATE() { s->time->have_date = 0; s->time->d = 0; s->time->m = 0; s->time->y = 0; } #define TIMELIB_HAVE_RELATIVE() { s->time->have_relative = 1; } #define TIMELIB_HAVE_WEEKDAY_RELATIVE() { s->time->have_relative = 1; s->time->relative.have_weekday_relative = 1; } #define TIMELIB_HAVE_SPECIAL_RELATIVE() { s->time->have_relative = 1; s->time->relative.have_special_relative = 1; } #define TIMELIB_HAVE_TZ() { s->cur = cursor; if (s->time->have_zone) { s->time->have_zone > 1 ? add_error(s, "Double timezone specification") : add_warning(s, "Double timezone specification"); timelib_string_free(str); s->time->have_zone++; return TIMELIB_ERROR; } else { s->time->have_zone++; } } #define TIMELIB_INIT s->cur = cursor; str = timelib_string(s); ptr = str #define TIMELIB_DEINIT timelib_string_free(str) #define TIMELIB_ADJUST_RELATIVE_WEEKDAY() if (in->time.have_weekday_relative && (in.rel.d > 0)) { in.rel.d -= 7; } #define TIMELIB_PROCESS_YEAR(x, l) { \ if (((x) == TIMELIB_UNSET) || ((l) >= 4)) { \ /* (x) = 0; */ \ } else if ((x) < 100) { \ if ((x) < 70) { \ (x) += 2000; \ } else { \ (x) += 1900; \ } \ } \ } #ifdef DEBUG_PARSER #define DEBUG_OUTPUT(s) printf("%s\n", s); #define YYDEBUG(s,c) { if (s != -1) { printf("state: %d ", s); printf("[%c]\n", c); } } #else #define DEBUG_OUTPUT(s) #define YYDEBUG(s,c) #endif #include "timelib_structs.h" typedef struct timelib_elems { unsigned int c; /* Number of elements */ char **v; /* Values */ } timelib_elems; typedef struct Scanner { int fd; uchar *lim, *str, *ptr, *cur, *tok, *pos; unsigned int line, len; struct timelib_error_container *errors; struct timelib_time *time; const timelib_tzdb *tzdb; } Scanner; typedef struct _timelib_lookup_table { const char *name; int type; int value; } timelib_lookup_table; typedef struct _timelib_relunit { const char *name; int unit; int multiplier; } timelib_relunit; #define HOUR(a) (int)(a * 60) /* The timezone table. */ const static timelib_tz_lookup_table timelib_timezone_lookup[] = { #include "timezonemap.h" { NULL, 0, 0, NULL }, }; const static timelib_tz_lookup_table timelib_timezone_fallbackmap[] = { #include "fallbackmap.h" { NULL, 0, 0, NULL }, }; const static timelib_tz_lookup_table timelib_timezone_utc[] = { { "utc", 0, 0, "UTC" }, }; static timelib_relunit const timelib_relunit_lookup[] = { { "sec", TIMELIB_SECOND, 1 }, { "secs", TIMELIB_SECOND, 1 }, { "second", TIMELIB_SECOND, 1 }, { "seconds", TIMELIB_SECOND, 1 }, { "min", TIMELIB_MINUTE, 1 }, { "mins", TIMELIB_MINUTE, 1 }, { "minute", TIMELIB_MINUTE, 1 }, { "minutes", TIMELIB_MINUTE, 1 }, { "hour", TIMELIB_HOUR, 1 }, { "hours", TIMELIB_HOUR, 1 }, { "day", TIMELIB_DAY, 1 }, { "days", TIMELIB_DAY, 1 }, { "week", TIMELIB_DAY, 7 }, { "weeks", TIMELIB_DAY, 7 }, { "fortnight", TIMELIB_DAY, 14 }, { "fortnights", TIMELIB_DAY, 14 }, { "forthnight", TIMELIB_DAY, 14 }, { "forthnights", TIMELIB_DAY, 14 }, { "month", TIMELIB_MONTH, 1 }, { "months", TIMELIB_MONTH, 1 }, { "year", TIMELIB_YEAR, 1 }, { "years", TIMELIB_YEAR, 1 }, { "monday", TIMELIB_WEEKDAY, 1 }, { "mon", TIMELIB_WEEKDAY, 1 }, { "tuesday", TIMELIB_WEEKDAY, 2 }, { "tue", TIMELIB_WEEKDAY, 2 }, { "wednesday", TIMELIB_WEEKDAY, 3 }, { "wed", TIMELIB_WEEKDAY, 3 }, { "thursday", TIMELIB_WEEKDAY, 4 }, { "thu", TIMELIB_WEEKDAY, 4 }, { "friday", TIMELIB_WEEKDAY, 5 }, { "fri", TIMELIB_WEEKDAY, 5 }, { "saturday", TIMELIB_WEEKDAY, 6 }, { "sat", TIMELIB_WEEKDAY, 6 }, { "sunday", TIMELIB_WEEKDAY, 0 }, { "sun", TIMELIB_WEEKDAY, 0 }, { "weekday", TIMELIB_SPECIAL, TIMELIB_SPECIAL_WEEKDAY }, { "weekdays", TIMELIB_SPECIAL, TIMELIB_SPECIAL_WEEKDAY }, { NULL, 0, 0 } }; /* The relative text table. */ static timelib_lookup_table const timelib_reltext_lookup[] = { { "first", 0, 1 }, { "next", 0, 1 }, { "second", 0, 2 }, { "third", 0, 3 }, { "fourth", 0, 4 }, { "fifth", 0, 5 }, { "sixth", 0, 6 }, { "seventh", 0, 7 }, { "eight", 0, 8 }, { "eighth", 0, 8 }, { "ninth", 0, 9 }, { "tenth", 0, 10 }, { "eleventh", 0, 11 }, { "twelfth", 0, 12 }, { "last", 0, -1 }, { "previous", 0, -1 }, { "this", 1, 0 }, { NULL, 1, 0 } }; /* The month table. */ static timelib_lookup_table const timelib_month_lookup[] = { { "jan", 0, 1 }, { "feb", 0, 2 }, { "mar", 0, 3 }, { "apr", 0, 4 }, { "may", 0, 5 }, { "jun", 0, 6 }, { "jul", 0, 7 }, { "aug", 0, 8 }, { "sep", 0, 9 }, { "sept", 0, 9 }, { "oct", 0, 10 }, { "nov", 0, 11 }, { "dec", 0, 12 }, { "i", 0, 1 }, { "ii", 0, 2 }, { "iii", 0, 3 }, { "iv", 0, 4 }, { "v", 0, 5 }, { "vi", 0, 6 }, { "vii", 0, 7 }, { "viii", 0, 8 }, { "ix", 0, 9 }, { "x", 0, 10 }, { "xi", 0, 11 }, { "xii", 0, 12 }, { "january", 0, 1 }, { "february", 0, 2 }, { "march", 0, 3 }, { "april", 0, 4 }, { "may", 0, 5 }, { "june", 0, 6 }, { "july", 0, 7 }, { "august", 0, 8 }, { "september", 0, 9 }, { "october", 0, 10 }, { "november", 0, 11 }, { "december", 0, 12 }, { NULL, 0, 0 } }; #if 0 static char* timelib_ltrim(char *s) { char *ptr = s; while (ptr[0] == ' ' || ptr[0] == '\t') { ptr++; } return ptr; } #endif #if 0 uchar *fill(Scanner *s, uchar *cursor){ if(!s->eof){ unsigned int cnt = s->tok - s->bot; if(cnt){ memcpy(s->bot, s->tok, s->lim - s->tok); s->tok = s->bot; s->ptr -= cnt; cursor -= cnt; s->pos -= cnt; s->lim -= cnt; } if((s->top - s->lim) < BSIZE){ uchar *buf = (uchar*) malloc(((s->lim - s->bot) + BSIZE)*sizeof(uchar)); memcpy(buf, s->tok, s->lim - s->tok); s->tok = buf; s->ptr = &buf[s->ptr - s->bot]; cursor = &buf[cursor - s->bot]; s->pos = &buf[s->pos - s->bot]; s->lim = &buf[s->lim - s->bot]; s->top = &s->lim[BSIZE]; free(s->bot); s->bot = buf; } if((cnt = read(s->fd, (char*) s->lim, BSIZE)) != BSIZE){ s->eof = &s->lim[cnt]; *(s->eof)++ = '\n'; } s->lim += cnt; } return cursor; } #endif static void add_warning(Scanner *s, char *error) { s->errors->warning_count++; s->errors->warning_messages = realloc(s->errors->warning_messages, s->errors->warning_count * sizeof(timelib_error_message)); s->errors->warning_messages[s->errors->warning_count - 1].position = s->tok ? s->tok - s->str : 0; s->errors->warning_messages[s->errors->warning_count - 1].character = s->tok ? *s->tok : 0; s->errors->warning_messages[s->errors->warning_count - 1].message = strdup(error); } static void add_error(Scanner *s, char *error) { s->errors->error_count++; s->errors->error_messages = realloc(s->errors->error_messages, s->errors->error_count * sizeof(timelib_error_message)); s->errors->error_messages[s->errors->error_count - 1].position = s->tok ? s->tok - s->str : 0; s->errors->error_messages[s->errors->error_count - 1].character = s->tok ? *s->tok : 0; s->errors->error_messages[s->errors->error_count - 1].message = strdup(error); } static void add_pbf_warning(Scanner *s, char *error, char *sptr, char *cptr) { s->errors->warning_count++; s->errors->warning_messages = realloc(s->errors->warning_messages, s->errors->warning_count * sizeof(timelib_error_message)); s->errors->warning_messages[s->errors->warning_count - 1].position = cptr - sptr; s->errors->warning_messages[s->errors->warning_count - 1].character = *cptr; s->errors->warning_messages[s->errors->warning_count - 1].message = strdup(error); } static void add_pbf_error(Scanner *s, char *error, char *sptr, char *cptr) { s->errors->error_count++; s->errors->error_messages = realloc(s->errors->error_messages, s->errors->error_count * sizeof(timelib_error_message)); s->errors->error_messages[s->errors->error_count - 1].position = cptr - sptr; s->errors->error_messages[s->errors->error_count - 1].character = *cptr; s->errors->error_messages[s->errors->error_count - 1].message = strdup(error); } static timelib_sll timelib_meridian(char **ptr, timelib_sll h) { timelib_sll retval = 0; while (!strchr("AaPp", **ptr)) { ++*ptr; } if (**ptr == 'a' || **ptr == 'A') { if (h == 12) { retval = -12; } } else if (h != 12) { retval = 12; } ++*ptr; if (**ptr == '.') { *ptr += 3; } else { ++*ptr; } return retval; } static timelib_sll timelib_meridian_with_check(char **ptr, timelib_sll h) { timelib_sll retval = 0; while (!strchr("AaPp", **ptr)) { ++*ptr; } if (**ptr == 'a' || **ptr == 'A') { if (h == 12) { retval = -12; } } else if (h != 12) { retval = 12; } ++*ptr; if (**ptr == '.') { ++*ptr; if (**ptr != 'm' && **ptr != 'M') { return TIMELIB_UNSET; } ++*ptr; if (**ptr != '.' ) { return TIMELIB_UNSET; } ++*ptr; } else if (**ptr == 'm' || **ptr == 'M') { ++*ptr; } else { return TIMELIB_UNSET; } return retval; } static char *timelib_string(Scanner *s) { char *tmp = calloc(1, s->cur - s->tok + 1); memcpy(tmp, s->tok, s->cur - s->tok); return tmp; } static timelib_sll timelib_get_nr_ex(char **ptr, int max_length, int *scanned_length) { char *begin, *end, *str; timelib_sll tmp_nr = TIMELIB_UNSET; int len = 0; while ((**ptr < '0') || (**ptr > '9')) { if (**ptr == '\0') { return TIMELIB_UNSET; } ++*ptr; } begin = *ptr; while ((**ptr >= '0') && (**ptr <= '9') && len < max_length) { ++*ptr; ++len; } end = *ptr; if (scanned_length) { *scanned_length = end - begin; } str = calloc(1, end - begin + 1); memcpy(str, begin, end - begin); tmp_nr = strtoll(str, NULL, 10); free(str); return tmp_nr; } static timelib_sll timelib_get_nr(char **ptr, int max_length) { return timelib_get_nr_ex(ptr, max_length, NULL); } static void timelib_skip_day_suffix(char **ptr) { if (isspace(**ptr)) { return; } if (!strncasecmp(*ptr, "nd", 2) || !strncasecmp(*ptr, "rd", 2) ||!strncasecmp(*ptr, "st", 2) || !strncasecmp(*ptr, "th", 2)) { *ptr += 2; } } static double timelib_get_frac_nr(char **ptr, int max_length) { char *begin, *end, *str; double tmp_nr = TIMELIB_UNSET; int len = 0; while ((**ptr != '.') && (**ptr != ':') && ((**ptr < '0') || (**ptr > '9'))) { if (**ptr == '\0') { return TIMELIB_UNSET; } ++*ptr; } begin = *ptr; while (((**ptr == '.') || (**ptr == ':') || ((**ptr >= '0') && (**ptr <= '9'))) && len < max_length) { ++*ptr; ++len; } end = *ptr; str = calloc(1, end - begin + 1); memcpy(str, begin, end - begin); if (str[0] == ':') { str[0] = '.'; } tmp_nr = strtod(str, NULL); free(str); return tmp_nr; } static timelib_ull timelib_get_unsigned_nr(char **ptr, int max_length) { timelib_ull dir = 1; while (((**ptr < '0') || (**ptr > '9')) && (**ptr != '+') && (**ptr != '-')) { if (**ptr == '\0') { return TIMELIB_UNSET; } ++*ptr; } while (**ptr == '+' || **ptr == '-') { if (**ptr == '-') { dir *= -1; } ++*ptr; } return dir * timelib_get_nr(ptr, max_length); } static long timelib_parse_tz_cor(char **ptr) { char *begin = *ptr, *end; long tmp; while (isdigit(**ptr) || **ptr == ':') { ++*ptr; } end = *ptr; switch (end - begin) { case 1: case 2: return HOUR(strtol(begin, NULL, 10)); break; case 3: case 4: if (begin[1] == ':') { tmp = HOUR(strtol(begin, NULL, 10)) + strtol(begin + 2, NULL, 10); return tmp; } else if (begin[2] == ':') { tmp = HOUR(strtol(begin, NULL, 10)) + strtol(begin + 3, NULL, 10); return tmp; } else { tmp = strtol(begin, NULL, 10); return HOUR(tmp / 100) + tmp % 100; } case 5: tmp = HOUR(strtol(begin, NULL, 10)) + strtol(begin + 3, NULL, 10); return tmp; } return 0; } static timelib_sll timelib_lookup_relative_text(char **ptr, int *behavior) { char *word; char *begin = *ptr, *end; timelib_sll value = 0; const timelib_lookup_table *tp; while ((**ptr >= 'A' && **ptr <= 'Z') || (**ptr >= 'a' && **ptr <= 'z')) { ++*ptr; } end = *ptr; word = calloc(1, end - begin + 1); memcpy(word, begin, end - begin); for (tp = timelib_reltext_lookup; tp->name; tp++) { if (strcasecmp(word, tp->name) == 0) { value = tp->value; *behavior = tp->type; } } free(word); return value; } static timelib_sll timelib_get_relative_text(char **ptr, int *behavior) { while (**ptr == ' ' || **ptr == '\t' || **ptr == '-' || **ptr == '/') { ++*ptr; } return timelib_lookup_relative_text(ptr, behavior); } static long timelib_lookup_month(char **ptr) { char *word; char *begin = *ptr, *end; long value = 0; const timelib_lookup_table *tp; while ((**ptr >= 'A' && **ptr <= 'Z') || (**ptr >= 'a' && **ptr <= 'z')) { ++*ptr; } end = *ptr; word = calloc(1, end - begin + 1); memcpy(word, begin, end - begin); for (tp = timelib_month_lookup; tp->name; tp++) { if (strcasecmp(word, tp->name) == 0) { value = tp->value; } } free(word); return value; } static long timelib_get_month(char **ptr) { while (**ptr == ' ' || **ptr == '\t' || **ptr == '-' || **ptr == '.' || **ptr == '/') { ++*ptr; } return timelib_lookup_month(ptr); } static void timelib_eat_spaces(char **ptr) { while (**ptr == ' ' || **ptr == '\t') { ++*ptr; } } static void timelib_eat_until_separator(char **ptr) { ++*ptr; while (strchr(" \t.,:;/-0123456789", **ptr) == NULL) { ++*ptr; } } static const timelib_relunit* timelib_lookup_relunit(char **ptr) { char *word; char *begin = *ptr, *end; const timelib_relunit *tp, *value = NULL; while (**ptr != '\0' && **ptr != ' ' && **ptr != ',' && **ptr != '\t') { ++*ptr; } end = *ptr; word = calloc(1, end - begin + 1); memcpy(word, begin, end - begin); for (tp = timelib_relunit_lookup; tp->name; tp++) { if (strcasecmp(word, tp->name) == 0) { value = tp; break; } } free(word); return value; } static void timelib_set_relative(char **ptr, timelib_sll amount, int behavior, Scanner *s) { const timelib_relunit* relunit; if (!(relunit = timelib_lookup_relunit(ptr))) { return; } switch (relunit->unit) { case TIMELIB_SECOND: s->time->relative.s += amount * relunit->multiplier; break; case TIMELIB_MINUTE: s->time->relative.i += amount * relunit->multiplier; break; case TIMELIB_HOUR: s->time->relative.h += amount * relunit->multiplier; break; case TIMELIB_DAY: s->time->relative.d += amount * relunit->multiplier; break; case TIMELIB_MONTH: s->time->relative.m += amount * relunit->multiplier; break; case TIMELIB_YEAR: s->time->relative.y += amount * relunit->multiplier; break; case TIMELIB_WEEKDAY: TIMELIB_HAVE_WEEKDAY_RELATIVE(); TIMELIB_UNHAVE_TIME(); s->time->relative.d += (amount > 0 ? amount - 1 : amount) * 7; s->time->relative.weekday = relunit->multiplier; s->time->relative.weekday_behavior = behavior; break; case TIMELIB_SPECIAL: TIMELIB_HAVE_SPECIAL_RELATIVE(); TIMELIB_UNHAVE_TIME(); s->time->relative.special.type = relunit->multiplier; s->time->relative.special.amount = amount; } } const static timelib_tz_lookup_table* zone_search(const char *word, long gmtoffset, int isdst) { int first_found = 0; const timelib_tz_lookup_table *tp, *first_found_elem = NULL; const timelib_tz_lookup_table *fmp; if (strcasecmp("utc", word) == 0 || strcasecmp("gmt", word) == 0) { return timelib_timezone_utc; } for (tp = timelib_timezone_lookup; tp->name; tp++) { if (strcasecmp(word, tp->name) == 0) { if (!first_found) { first_found = 1; first_found_elem = tp; if (gmtoffset == -1) { return tp; } } if (tp->gmtoffset == gmtoffset) { return tp; } } } if (first_found) { return first_found_elem; } for (tp = timelib_timezone_lookup; tp->name; tp++) { if (tp->full_tz_name && strcasecmp(word, tp->full_tz_name) == 0) { if (!first_found) { first_found = 1; first_found_elem = tp; if (gmtoffset == -1) { return tp; } } if (tp->gmtoffset == gmtoffset) { return tp; } } } if (first_found) { return first_found_elem; } /* Still didn't find anything, let's find the zone solely based on * offset/isdst then */ for (fmp = timelib_timezone_fallbackmap; fmp->name; fmp++) { if ((fmp->gmtoffset * 3600) == gmtoffset && fmp->type == isdst) { return fmp; } } return NULL; } static long timelib_lookup_zone(char **ptr, int *dst, char **tz_abbr, int *found) { char *word; char *begin = *ptr, *end; long value = 0; const timelib_tz_lookup_table *tp; while (**ptr != '\0' && **ptr != ')' && **ptr != ' ') { ++*ptr; } end = *ptr; word = calloc(1, end - begin + 1); memcpy(word, begin, end - begin); if ((tp = zone_search(word, -1, 0))) { value = -tp->gmtoffset / 60; *dst = tp->type; value += tp->type * 60; *found = 1; } else { *found = 0; } *tz_abbr = word; return value; } static long timelib_get_zone(char **ptr, int *dst, timelib_time *t, int *tz_not_found, const timelib_tzdb *tzdb) { timelib_tzinfo *res; long retval = 0; *tz_not_found = 0; while (**ptr == ' ' || **ptr == '\t' || **ptr == '(') { ++*ptr; } if ((*ptr)[0] == 'G' && (*ptr)[1] == 'M' && (*ptr)[2] == 'T' && ((*ptr)[3] == '+' || (*ptr)[3] == '-')) { *ptr += 3; } if (**ptr == '+') { ++*ptr; t->is_localtime = 1; t->zone_type = TIMELIB_ZONETYPE_OFFSET; *tz_not_found = 0; t->dst = 0; retval = -1 * timelib_parse_tz_cor(ptr); } else if (**ptr == '-') { ++*ptr; t->is_localtime = 1; t->zone_type = TIMELIB_ZONETYPE_OFFSET; *tz_not_found = 0; t->dst = 0; retval = timelib_parse_tz_cor(ptr); } else { int found = 0; long offset; char *tz_abbr; t->is_localtime = 1; offset = timelib_lookup_zone(ptr, dst, &tz_abbr, &found); if (found) { t->zone_type = TIMELIB_ZONETYPE_ABBR; } #if 0 /* If we found a TimeZone identifier, use it */ if (tz_name) { t->tz_info = timelib_parse_tzfile(tz_name); t->zone_type = TIMELIB_ZONETYPE_ID; } #endif /* If we have a TimeZone identifier to start with, use it */ if (strstr(tz_abbr, "/") || strcmp(tz_abbr, "UTC") == 0) { if ((res = timelib_parse_tzfile(tz_abbr, tzdb)) != NULL) { t->tz_info = res; t->zone_type = TIMELIB_ZONETYPE_ID; found++; } } if (found && t->zone_type != TIMELIB_ZONETYPE_ID) { timelib_time_tz_abbr_update(t, tz_abbr); } free(tz_abbr); *tz_not_found = (found == 0); retval = offset; } while (**ptr == ')') { ++*ptr; } return retval; } #define timelib_split_free(arg) { \ int i; \ for (i = 0; i < arg.c; i++) { \ free(arg.v[i]); \ } \ if (arg.v) { \ free(arg.v); \ } \ } static int scan(Scanner *s) { uchar *cursor = s->cur; char *str, *ptr = NULL; std: s->tok = cursor; s->len = 0; #line 997 "ext/date/lib/parse_date.re" #line 879 "ext/date/lib/parse_date.c" { YYCTYPE yych; unsigned int yyaccept = 0; static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 64, 160, 96, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 24, 24, 24, 88, 24, 24, 24, 88, 24, 24, 24, 24, 24, 88, 24, 24, 24, 88, 88, 88, 24, 24, 24, 24, 24, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; YYDEBUG(0, *YYCURSOR); if ((YYLIMIT - YYCURSOR) < 31) YYFILL(31); yych = *YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case 0x00: case '\n': goto yy52; case '\t': case ' ': goto yy49; case '(': goto yy46; case '+': case '-': goto yy31; case ',': case '.': goto yy51; case '0': goto yy26; case '1': goto yy27; case '2': goto yy28; case '3': goto yy29; case '4': case '5': case '6': case '7': case '8': case '9': goto yy30; case '@': goto yy12; case 'A': goto yy37; case 'B': goto yy18; case 'C': case 'H': case 'K': case 'Q': case 'R': case 'U': case 'Z': goto yy47; case 'D': goto yy41; case 'E': goto yy22; case 'F': goto yy14; case 'G': goto yy45; case 'I': goto yy32; case 'J': goto yy35; case 'L': goto yy16; case 'M': goto yy8; case 'N': goto yy6; case 'O': goto yy39; case 'P': goto yy24; case 'S': goto yy20; case 'T': goto yy10; case 'V': goto yy33; case 'W': goto yy43; case 'X': goto yy34; case 'Y': goto yy3; case 'a': goto yy38; case 'b': goto yy19; case 'c': case 'g': case 'h': case 'i': case 'k': case 'q': case 'r': case 'u': case 'v': case 'x': case 'z': goto yy48; case 'd': goto yy42; case 'e': goto yy23; case 'f': goto yy15; case 'j': goto yy36; case 'l': goto yy17; case 'm': goto yy9; case 'n': goto yy7; case 'o': goto yy40; case 'p': goto yy25; case 's': goto yy21; case 't': goto yy11; case 'w': goto yy44; case 'y': goto yy5; default: goto yy54; } yy2: YYDEBUG(2, *YYCURSOR); #line 1082 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("firstdayof | lastdayof"); TIMELIB_INIT; TIMELIB_HAVE_RELATIVE(); /* skip "last day of" or "first day of" */ if (*ptr == 'l') { s->time->relative.first_last_day_of = 2; } else { s->time->relative.first_last_day_of = 1; } TIMELIB_DEINIT; return TIMELIB_LF_DAY_OF_MONTH; } #line 1015 "ext/date/lib/parse_date.c" yy3: YYDEBUG(3, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= 'E') { if (yych <= ')') { if (yych >= ')') goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy141; goto yy1523; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy141; if (yych >= 'a') goto yy146; } else { if (yych <= 'e') goto yy1532; if (yych <= 'z') goto yy146; } } yy4: YYDEBUG(4, *YYCURSOR); #line 1676 "ext/date/lib/parse_date.re" { int tz_not_found; DEBUG_OUTPUT("tzcorrection | tz"); TIMELIB_INIT; TIMELIB_HAVE_TZ(); s->time->z = timelib_get_zone((char **) &ptr, &s->time->dst, s->time, &tz_not_found, s->tzdb); if (tz_not_found) { add_error(s, "The timezone could not be found in the database"); } TIMELIB_DEINIT; return TIMELIB_TIMEZONE; } #line 1051 "ext/date/lib/parse_date.c" yy5: YYDEBUG(5, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy141; goto yy1523; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; goto yy141; } else { if (yych <= 'e') goto yy1523; if (yych <= 'z') goto yy141; goto yy4; } } yy6: YYDEBUG(6, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= 'D') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy141; } else { if (yych <= 'H') { if (yych <= 'E') goto yy1494; goto yy141; } else { if (yych <= 'I') goto yy1495; if (yych <= 'N') goto yy141; goto yy1493; } } } else { if (yych <= 'h') { if (yych <= '`') { if (yych <= 'Z') goto yy141; goto yy4; } else { if (yych == 'e') goto yy1510; goto yy146; } } else { if (yych <= 'n') { if (yych <= 'i') goto yy1511; goto yy146; } else { if (yych <= 'o') goto yy1509; if (yych <= 'z') goto yy146; goto yy4; } } } yy7: YYDEBUG(7, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= 'D') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy141; } else { if (yych <= 'H') { if (yych <= 'E') goto yy1494; goto yy141; } else { if (yych <= 'I') goto yy1495; if (yych <= 'N') goto yy141; goto yy1493; } } } else { if (yych <= 'h') { if (yych <= '`') { if (yych <= 'Z') goto yy141; goto yy4; } else { if (yych == 'e') goto yy1494; goto yy141; } } else { if (yych <= 'n') { if (yych <= 'i') goto yy1495; goto yy141; } else { if (yych <= 'o') goto yy1493; if (yych <= 'z') goto yy141; goto yy4; } } } yy8: YYDEBUG(8, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy1463; } else { if (yych == 'I') goto yy1464; if (yych <= 'N') goto yy141; goto yy1465; } } else { if (yych <= 'h') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; if (yych <= 'a') goto yy1478; goto yy146; } else { if (yych <= 'n') { if (yych <= 'i') goto yy1479; goto yy146; } else { if (yych <= 'o') goto yy1480; if (yych <= 'z') goto yy146; goto yy4; } } } yy9: YYDEBUG(9, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy1463; } else { if (yych == 'I') goto yy1464; if (yych <= 'N') goto yy141; goto yy1465; } } else { if (yych <= 'h') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; if (yych <= 'a') goto yy1463; goto yy141; } else { if (yych <= 'n') { if (yych <= 'i') goto yy1464; goto yy141; } else { if (yych <= 'o') goto yy1465; if (yych <= 'z') goto yy141; goto yy4; } } } yy10: YYDEBUG(10, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case ')': goto yy140; case '0': case '1': goto yy1393; case '2': goto yy1394; case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy1395; case 'A': case 'B': case 'C': case 'D': case 'F': case 'G': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'V': case 'X': case 'Y': case 'Z': goto yy141; case 'E': goto yy1388; case 'H': goto yy1389; case 'O': goto yy1390; case 'U': goto yy1391; case 'W': goto yy1392; case 'a': case 'b': case 'c': case 'd': case 'f': case 'g': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'p': case 'q': case 'r': case 's': case 't': case 'v': case 'x': case 'y': case 'z': goto yy146; case 'e': goto yy1431; case 'h': goto yy1432; case 'o': goto yy1433; case 'u': goto yy1434; case 'w': goto yy1435; default: goto yy4; } yy11: YYDEBUG(11, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case ')': goto yy140; case '0': case '1': goto yy1393; case '2': goto yy1394; case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy1395; case 'A': case 'B': case 'C': case 'D': case 'F': case 'G': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'V': case 'X': case 'Y': case 'Z': case 'a': case 'b': case 'c': case 'd': case 'f': case 'g': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'p': case 'q': case 'r': case 's': case 't': case 'v': case 'x': case 'y': case 'z': goto yy141; case 'E': case 'e': goto yy1388; case 'H': case 'h': goto yy1389; case 'O': case 'o': goto yy1390; case 'U': case 'u': goto yy1391; case 'W': case 'w': goto yy1392; default: goto yy4; } yy12: YYDEBUG(12, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych == '-') goto yy1384; if (yych <= '/') goto yy13; if (yych <= '9') goto yy1385; yy13: YYDEBUG(13, *YYCURSOR); #line 1771 "ext/date/lib/parse_date.re" { add_error(s, "Unexpected character"); goto std; } #line 1367 "ext/date/lib/parse_date.c" yy14: YYDEBUG(14, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy141; goto yy1320; } } else { if (yych <= 'N') { if (yych == 'I') goto yy1321; goto yy141; } else { if (yych <= 'O') goto yy1322; if (yych <= 'Q') goto yy141; goto yy1323; } } } else { if (yych <= 'i') { if (yych <= 'd') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; goto yy146; } else { if (yych <= 'e') goto yy1361; if (yych <= 'h') goto yy146; goto yy1362; } } else { if (yych <= 'q') { if (yych == 'o') goto yy1363; goto yy146; } else { if (yych <= 'r') goto yy1364; if (yych <= 'z') goto yy146; goto yy4; } } } yy15: YYDEBUG(15, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy141; goto yy1320; } } else { if (yych <= 'N') { if (yych == 'I') goto yy1321; goto yy141; } else { if (yych <= 'O') goto yy1322; if (yych <= 'Q') goto yy141; goto yy1323; } } } else { if (yych <= 'i') { if (yych <= 'd') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; goto yy141; } else { if (yych <= 'e') goto yy1320; if (yych <= 'h') goto yy141; goto yy1321; } } else { if (yych <= 'q') { if (yych == 'o') goto yy1322; goto yy141; } else { if (yych <= 'r') goto yy1323; if (yych <= 'z') goto yy141; goto yy4; } } } yy16: YYDEBUG(16, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy1307; } else { if (yych <= '`') { if (yych <= 'Z') goto yy141; goto yy4; } else { if (yych <= 'a') goto yy1317; if (yych <= 'z') goto yy146; goto yy4; } } yy17: YYDEBUG(17, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy1307; } else { if (yych <= '`') { if (yych <= 'Z') goto yy141; goto yy4; } else { if (yych <= 'a') goto yy1307; if (yych <= 'z') goto yy141; goto yy4; } } yy18: YYDEBUG(18, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy1287; } else { if (yych <= '`') { if (yych <= 'Z') goto yy141; goto yy4; } else { if (yych <= 'a') goto yy1304; if (yych <= 'z') goto yy146; goto yy4; } } yy19: YYDEBUG(19, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy1287; } else { if (yych <= '`') { if (yych <= 'Z') goto yy141; goto yy4; } else { if (yych <= 'a') goto yy1287; if (yych <= 'z') goto yy141; goto yy4; } } yy20: YYDEBUG(20, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= 'D') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'A') goto yy1230; goto yy141; } } else { if (yych <= 'H') { if (yych <= 'E') goto yy1229; goto yy141; } else { if (yych <= 'I') goto yy1231; if (yych <= 'T') goto yy141; goto yy1232; } } } else { if (yych <= 'e') { if (yych <= '`') { if (yych <= 'Z') goto yy141; goto yy4; } else { if (yych <= 'a') goto yy1259; if (yych <= 'd') goto yy146; goto yy1258; } } else { if (yych <= 't') { if (yych == 'i') goto yy1260; goto yy146; } else { if (yych <= 'u') goto yy1261; if (yych <= 'z') goto yy146; goto yy4; } } } yy21: YYDEBUG(21, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= 'D') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'A') goto yy1230; goto yy141; } } else { if (yych <= 'H') { if (yych <= 'E') goto yy1229; goto yy141; } else { if (yych <= 'I') goto yy1231; if (yych <= 'T') goto yy141; goto yy1232; } } } else { if (yych <= 'e') { if (yych <= '`') { if (yych <= 'Z') goto yy141; goto yy4; } else { if (yych <= 'a') goto yy1230; if (yych <= 'd') goto yy141; goto yy1229; } } else { if (yych <= 't') { if (yych == 'i') goto yy1231; goto yy141; } else { if (yych <= 'u') goto yy1232; if (yych <= 'z') goto yy141; goto yy4; } } } yy22: YYDEBUG(22, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == 'I') goto yy1199; if (yych <= 'K') goto yy141; goto yy1200; } } else { if (yych <= 'i') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; if (yych <= 'h') goto yy146; goto yy1217; } else { if (yych == 'l') goto yy1218; if (yych <= 'z') goto yy146; goto yy4; } } yy23: YYDEBUG(23, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == 'I') goto yy1199; if (yych <= 'K') goto yy141; goto yy1200; } } else { if (yych <= 'i') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; if (yych <= 'h') goto yy141; goto yy1199; } else { if (yych == 'l') goto yy1200; if (yych <= 'z') goto yy141; goto yy4; } } yy24: YYDEBUG(24, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'Q') goto yy141; goto yy1098; } } else { if (yych <= 'q') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; goto yy146; } else { if (yych <= 'r') goto yy1192; if (yych <= 'z') goto yy146; goto yy4; } } yy25: YYDEBUG(25, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'Q') goto yy141; goto yy1098; } } else { if (yych <= 'q') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; goto yy141; } else { if (yych <= 'r') goto yy1098; if (yych <= 'z') goto yy141; goto yy4; } } yy26: YYDEBUG(26, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case '\t': goto yy1052; case ' ': case 'A': case 'D': case 'F': case 'H': case 'I': case 'J': case 'M': case 'N': case 'O': case 'S': case 'T': case 'V': case 'W': case 'X': case 'Y': case 'a': case 'd': case 'f': case 'h': case 'j': case 'm': case 'o': case 'w': case 'y': goto yy1054; case '-': goto yy473; case '.': goto yy1064; case '/': goto yy472; case '0': goto yy1097; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy1096; case ':': goto yy1065; case 'n': goto yy470; case 'r': goto yy471; case 's': goto yy464; case 't': goto yy468; default: goto yy13; } yy27: YYDEBUG(27, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case '\t': goto yy460; case ' ': case 'A': case 'D': case 'F': case 'H': case 'I': case 'J': case 'M': case 'N': case 'O': case 'P': case 'S': case 'T': case 'V': case 'W': case 'X': case 'Y': case 'a': case 'd': case 'f': case 'h': case 'j': case 'm': case 'o': case 'p': case 'w': case 'y': goto yy462; case '-': goto yy473; case '.': goto yy474; case '/': goto yy472; case '0': case '1': case '2': goto yy1096; case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy1063; case ':': goto yy483; case 'n': goto yy470; case 'r': goto yy471; case 's': goto yy464; case 't': goto yy468; default: goto yy13; } yy28: YYDEBUG(28, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case '\t': goto yy460; case ' ': case 'A': case 'D': case 'F': case 'H': case 'I': case 'J': case 'M': case 'N': case 'O': case 'P': case 'S': case 'T': case 'V': case 'W': case 'X': case 'Y': case 'a': case 'd': case 'f': case 'h': case 'j': case 'm': case 'o': case 'p': case 'w': case 'y': goto yy462; case '-': goto yy473; case '.': goto yy474; case '/': goto yy472; case '0': case '1': case '2': case '3': case '4': goto yy1063; case '5': case '6': case '7': case '8': case '9': goto yy1050; case ':': goto yy483; case 'n': goto yy470; case 'r': goto yy471; case 's': goto yy464; case 't': goto yy468; default: goto yy13; } yy29: YYDEBUG(29, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case '\t': goto yy460; case ' ': case 'A': case 'D': case 'F': case 'H': case 'I': case 'J': case 'M': case 'N': case 'O': case 'P': case 'S': case 'T': case 'V': case 'W': case 'X': case 'Y': case 'a': case 'd': case 'f': case 'h': case 'j': case 'm': case 'o': case 'p': case 'w': case 'y': goto yy462; case '-': goto yy473; case '.': goto yy474; case '/': goto yy472; case '0': case '1': goto yy1050; case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy469; case ':': goto yy483; case 'n': goto yy470; case 'r': goto yy471; case 's': goto yy464; case 't': goto yy468; default: goto yy13; } yy30: YYDEBUG(30, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case '\t': goto yy460; case ' ': case 'A': case 'D': case 'F': case 'H': case 'I': case 'J': case 'M': case 'N': case 'O': case 'P': case 'S': case 'T': case 'V': case 'W': case 'X': case 'Y': case 'a': case 'd': case 'f': case 'h': case 'j': case 'm': case 'o': case 'p': case 'w': case 'y': goto yy462; case '-': goto yy473; case '.': goto yy474; case '/': goto yy472; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy469; case ':': goto yy483; case 'n': goto yy470; case 'r': goto yy471; case 's': goto yy464; case 't': goto yy468; default: goto yy13; } yy31: YYDEBUG(31, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 4) { goto yy58; } YYDEBUG(-1, yych); switch (yych) { case '+': case '-': goto yy440; case '0': case '1': goto yy437; case '2': goto yy438; case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy439; default: goto yy13; } yy32: YYDEBUG(32, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy4; goto yy196; } else { if (yych == ' ') goto yy196; goto yy4; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; goto yy4; } else { if (yych == '/') goto yy4; goto yy196; } } } else { if (yych <= 'V') { if (yych <= 'H') { if (yych <= '@') goto yy4; goto yy141; } else { if (yych <= 'I') goto yy436; if (yych <= 'U') goto yy141; goto yy435; } } else { if (yych <= 'Z') { if (yych == 'X') goto yy435; goto yy141; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy146; goto yy4; } } } yy33: YYDEBUG(33, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ' ') { if (yych == '\t') goto yy196; if (yych <= 0x1F) goto yy4; goto yy196; } else { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy196; } } else { if (yych <= 'H') { if (yych <= '/') goto yy4; if (yych <= '9') goto yy196; if (yych <= '@') goto yy4; goto yy141; } else { if (yych <= 'Z') { if (yych <= 'I') goto yy432; goto yy141; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy146; goto yy4; } } } yy34: YYDEBUG(34, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ' ') { if (yych == '\t') goto yy196; if (yych <= 0x1F) goto yy4; goto yy196; } else { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy196; } } else { if (yych <= 'H') { if (yych <= '/') goto yy4; if (yych <= '9') goto yy196; if (yych <= '@') goto yy4; goto yy141; } else { if (yych <= 'Z') { if (yych <= 'I') goto yy430; goto yy141; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy146; goto yy4; } } } yy35: YYDEBUG(35, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'A') goto yy413; if (yych <= 'T') goto yy141; goto yy412; } } else { if (yych <= 'a') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; goto yy422; } else { if (yych == 'u') goto yy421; if (yych <= 'z') goto yy146; goto yy4; } } yy36: YYDEBUG(36, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'A') goto yy413; if (yych <= 'T') goto yy141; goto yy412; } } else { if (yych <= 'a') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; goto yy413; } else { if (yych == 'u') goto yy412; if (yych <= 'z') goto yy141; goto yy4; } } yy37: YYDEBUG(37, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= 'F') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy141; } else { if (yych <= 'O') { if (yych <= 'G') goto yy391; goto yy141; } else { if (yych <= 'P') goto yy390; if (yych <= 'T') goto yy141; goto yy389; } } } else { if (yych <= 'o') { if (yych <= '`') { if (yych <= 'Z') goto yy141; goto yy4; } else { if (yych == 'g') goto yy403; goto yy146; } } else { if (yych <= 't') { if (yych <= 'p') goto yy402; goto yy146; } else { if (yych <= 'u') goto yy401; if (yych <= 'z') goto yy146; goto yy4; } } } yy38: YYDEBUG(38, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= 'F') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy141; } else { if (yych <= 'O') { if (yych <= 'G') goto yy391; goto yy141; } else { if (yych <= 'P') goto yy390; if (yych <= 'T') goto yy141; goto yy389; } } } else { if (yych <= 'o') { if (yych <= '`') { if (yych <= 'Z') goto yy141; goto yy4; } else { if (yych == 'g') goto yy391; goto yy141; } } else { if (yych <= 't') { if (yych <= 'p') goto yy390; goto yy141; } else { if (yych <= 'u') goto yy389; if (yych <= 'z') goto yy141; goto yy4; } } } yy39: YYDEBUG(39, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'C') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'B') goto yy141; goto yy379; } } else { if (yych <= 'b') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; goto yy146; } else { if (yych <= 'c') goto yy384; if (yych <= 'z') goto yy146; goto yy4; } } yy40: YYDEBUG(40, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'C') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'B') goto yy141; goto yy379; } } else { if (yych <= 'b') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; goto yy141; } else { if (yych <= 'c') goto yy379; if (yych <= 'z') goto yy141; goto yy4; } } yy41: YYDEBUG(41, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy141; goto yy192; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; goto yy146; } else { if (yych <= 'e') goto yy370; if (yych <= 'z') goto yy146; goto yy4; } } yy42: YYDEBUG(42, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy141; goto yy192; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; goto yy141; } else { if (yych <= 'e') goto yy192; if (yych <= 'z') goto yy141; goto yy4; } } yy43: YYDEBUG(43, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy141; goto yy165; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; goto yy146; } else { if (yych <= 'e') goto yy179; if (yych <= 'z') goto yy146; goto yy4; } } yy44: YYDEBUG(44, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy141; goto yy165; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; goto yy141; } else { if (yych <= 'e') goto yy165; if (yych <= 'z') goto yy141; goto yy4; } } yy45: YYDEBUG(45, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy141; } else { if (yych <= 'Z') { if (yych <= 'M') goto yy157; goto yy141; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy146; goto yy4; } } yy46: YYDEBUG(46, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') goto yy13; if (yych <= 'Z') goto yy156; if (yych <= '`') goto yy13; if (yych <= 'z') goto yy156; goto yy13; yy47: YYDEBUG(47, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; if (yych <= 'z') goto yy146; goto yy4; } yy48: YYDEBUG(48, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; if (yych <= 'z') goto yy141; goto yy4; } yy49: YYDEBUG(49, *YYCURSOR); yyaccept = 2; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 4) { goto yy58; } if (yych <= '/') goto yy50; if (yych <= '9') goto yy55; yy50: YYDEBUG(50, *YYCURSOR); #line 1760 "ext/date/lib/parse_date.re" { goto std; } #line 2428 "ext/date/lib/parse_date.c" yy51: YYDEBUG(51, *YYCURSOR); yych = *++YYCURSOR; goto yy50; yy52: YYDEBUG(52, *YYCURSOR); ++YYCURSOR; YYDEBUG(53, *YYCURSOR); #line 1765 "ext/date/lib/parse_date.re" { s->pos = cursor; s->line++; goto std; } #line 2442 "ext/date/lib/parse_date.c" yy54: YYDEBUG(54, *YYCURSOR); yych = *++YYCURSOR; goto yy13; yy55: YYDEBUG(55, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 11) YYFILL(11); yych = *YYCURSOR; YYDEBUG(56, *YYCURSOR); if (yybm[0+yych] & 2) { goto yy55; } if (yych <= 'W') { if (yych <= 'F') { if (yych <= ' ') { if (yych == '\t') goto yy60; if (yych >= ' ') goto yy60; } else { if (yych == 'D') goto yy65; if (yych >= 'F') goto yy66; } } else { if (yych <= 'M') { if (yych == 'H') goto yy64; if (yych >= 'M') goto yy63; } else { if (yych <= 'S') { if (yych >= 'S') goto yy62; } else { if (yych <= 'T') goto yy69; if (yych >= 'W') goto yy68; } } } } else { if (yych <= 'l') { if (yych <= 'd') { if (yych == 'Y') goto yy67; if (yych >= 'd') goto yy65; } else { if (yych <= 'f') { if (yych >= 'f') goto yy66; } else { if (yych == 'h') goto yy64; } } } else { if (yych <= 't') { if (yych <= 'm') goto yy63; if (yych <= 'r') goto yy57; if (yych <= 's') goto yy62; goto yy69; } else { if (yych <= 'w') { if (yych >= 'w') goto yy68; } else { if (yych == 'y') goto yy67; } } } } yy57: YYDEBUG(57, *YYCURSOR); YYCURSOR = YYMARKER; if (yyaccept <= 16) { if (yyaccept <= 8) { if (yyaccept <= 4) { if (yyaccept <= 2) { if (yyaccept <= 1) { if (yyaccept <= 0) { goto yy4; } else { goto yy13; } } else { goto yy50; } } else { if (yyaccept <= 3) { goto yy73; } else { goto yy167; } } } else { if (yyaccept <= 6) { if (yyaccept <= 5) { goto yy194; } else { goto yy199; } } else { if (yyaccept <= 7) { goto yy223; } else { goto yy295; } } } } else { if (yyaccept <= 12) { if (yyaccept <= 10) { if (yyaccept <= 9) { goto yy393; } else { goto yy476; } } else { if (yyaccept <= 11) { goto yy491; } else { goto yy612; } } } else { if (yyaccept <= 14) { if (yyaccept <= 13) { goto yy657; } else { goto yy667; } } else { if (yyaccept <= 15) { goto yy764; } else { goto yy784; } } } } } else { if (yyaccept <= 25) { if (yyaccept <= 21) { if (yyaccept <= 19) { if (yyaccept <= 18) { if (yyaccept <= 17) { goto yy815; } else { goto yy822; } } else { goto yy849; } } else { if (yyaccept <= 20) { goto yy794; } else { goto yy455; } } } else { if (yyaccept <= 23) { if (yyaccept <= 22) { goto yy974; } else { goto yy843; } } else { if (yyaccept <= 24) { goto yy1068; } else { goto yy1076; } } } } else { if (yyaccept <= 29) { if (yyaccept <= 27) { if (yyaccept <= 26) { goto yy1118; } else { goto yy1142; } } else { if (yyaccept <= 28) { goto yy1295; } else { goto yy1417; } } } else { if (yyaccept <= 31) { if (yyaccept <= 30) { goto yy1420; } else { goto yy1500; } } else { if (yyaccept <= 32) { goto yy1508; } else { goto yy1531; } } } } } yy58: YYDEBUG(58, *YYCURSOR); ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; YYDEBUG(59, *YYCURSOR); if (yybm[0+yych] & 4) { goto yy58; } if (yych <= '/') goto yy57; if (yych <= '9') goto yy55; goto yy57; yy60: YYDEBUG(60, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 11) YYFILL(11); yych = *YYCURSOR; yy61: YYDEBUG(61, *YYCURSOR); if (yych <= 'W') { if (yych <= 'F') { if (yych <= ' ') { if (yych == '\t') goto yy60; if (yych <= 0x1F) goto yy57; goto yy60; } else { if (yych == 'D') goto yy65; if (yych <= 'E') goto yy57; goto yy66; } } else { if (yych <= 'M') { if (yych == 'H') goto yy64; if (yych <= 'L') goto yy57; goto yy63; } else { if (yych <= 'S') { if (yych <= 'R') goto yy57; } else { if (yych <= 'T') goto yy69; if (yych <= 'V') goto yy57; goto yy68; } } } } else { if (yych <= 'l') { if (yych <= 'd') { if (yych == 'Y') goto yy67; if (yych <= 'c') goto yy57; goto yy65; } else { if (yych <= 'f') { if (yych <= 'e') goto yy57; goto yy66; } else { if (yych == 'h') goto yy64; goto yy57; } } } else { if (yych <= 't') { if (yych <= 'm') goto yy63; if (yych <= 'r') goto yy57; if (yych >= 't') goto yy69; } else { if (yych <= 'w') { if (yych <= 'v') goto yy57; goto yy68; } else { if (yych == 'y') goto yy67; goto yy57; } } } } yy62: YYDEBUG(62, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= 'D') { if (yych == 'A') goto yy127; goto yy57; } else { if (yych <= 'E') goto yy128; if (yych <= 'T') goto yy57; goto yy126; } } else { if (yych <= 'd') { if (yych == 'a') goto yy127; goto yy57; } else { if (yych <= 'e') goto yy128; if (yych == 'u') goto yy126; goto yy57; } } yy63: YYDEBUG(63, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'I') goto yy118; if (yych <= 'N') goto yy57; goto yy117; } else { if (yych <= 'i') { if (yych <= 'h') goto yy57; goto yy118; } else { if (yych == 'o') goto yy117; goto yy57; } } yy64: YYDEBUG(64, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy115; if (yych == 'o') goto yy115; goto yy57; yy65: YYDEBUG(65, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy114; if (yych == 'a') goto yy114; goto yy57; yy66: YYDEBUG(66, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych == 'O') goto yy99; if (yych <= 'Q') goto yy57; goto yy98; } else { if (yych <= 'o') { if (yych <= 'n') goto yy57; goto yy99; } else { if (yych == 'r') goto yy98; goto yy57; } } yy67: YYDEBUG(67, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy95; if (yych == 'e') goto yy95; goto yy57; yy68: YYDEBUG(68, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy83; if (yych == 'e') goto yy83; goto yy57; yy69: YYDEBUG(69, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'H') goto yy70; if (yych <= 'T') goto yy57; goto yy71; } else { if (yych <= 'h') { if (yych <= 'g') goto yy57; } else { if (yych == 'u') goto yy71; goto yy57; } } yy70: YYDEBUG(70, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy78; if (yych == 'u') goto yy78; goto yy57; yy71: YYDEBUG(71, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy72; if (yych != 'e') goto yy57; yy72: YYDEBUG(72, *YYCURSOR); yyaccept = 3; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'S') goto yy74; if (yych == 's') goto yy74; yy73: YYDEBUG(73, *YYCURSOR); #line 1744 "ext/date/lib/parse_date.re" { timelib_ull i; DEBUG_OUTPUT("relative"); TIMELIB_INIT; TIMELIB_HAVE_RELATIVE(); while(*ptr) { i = timelib_get_unsigned_nr((char **) &ptr, 24); timelib_eat_spaces((char **) &ptr); timelib_set_relative((char **) &ptr, i, 1, s); } TIMELIB_DEINIT; return TIMELIB_RELATIVE; } #line 2844 "ext/date/lib/parse_date.c" yy74: YYDEBUG(74, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy75; if (yych != 'd') goto yy57; yy75: YYDEBUG(75, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy76; if (yych != 'a') goto yy57; yy76: YYDEBUG(76, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy77; if (yych != 'y') goto yy57; yy77: YYDEBUG(77, *YYCURSOR); yych = *++YYCURSOR; goto yy73; yy78: YYDEBUG(78, *YYCURSOR); yyaccept = 3; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'R') goto yy79; if (yych != 'r') goto yy73; yy79: YYDEBUG(79, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy80; if (yych != 's') goto yy57; yy80: YYDEBUG(80, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy81; if (yych != 'd') goto yy57; yy81: YYDEBUG(81, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy82; if (yych != 'a') goto yy57; yy82: YYDEBUG(82, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy77; if (yych == 'y') goto yy77; goto yy57; yy83: YYDEBUG(83, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= 'C') goto yy57; if (yych <= 'D') goto yy85; } else { if (yych <= 'c') goto yy57; if (yych <= 'd') goto yy85; if (yych >= 'f') goto yy57; } YYDEBUG(84, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'K') goto yy91; if (yych == 'k') goto yy91; goto yy57; yy85: YYDEBUG(85, *YYCURSOR); yyaccept = 3; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'N') goto yy86; if (yych != 'n') goto yy73; yy86: YYDEBUG(86, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy87; if (yych != 'e') goto yy57; yy87: YYDEBUG(87, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy88; if (yych != 's') goto yy57; yy88: YYDEBUG(88, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy89; if (yych != 'd') goto yy57; yy89: YYDEBUG(89, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy90; if (yych != 'a') goto yy57; yy90: YYDEBUG(90, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy77; if (yych == 'y') goto yy77; goto yy57; yy91: YYDEBUG(91, *YYCURSOR); yyaccept = 3; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych == 'D') goto yy92; if (yych <= 'R') goto yy73; goto yy77; } else { if (yych <= 'd') { if (yych <= 'c') goto yy73; } else { if (yych == 's') goto yy77; goto yy73; } } yy92: YYDEBUG(92, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy93; if (yych != 'a') goto yy57; yy93: YYDEBUG(93, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy94; if (yych != 'y') goto yy57; yy94: YYDEBUG(94, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy77; if (yych == 's') goto yy77; goto yy73; yy95: YYDEBUG(95, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy96; if (yych != 'a') goto yy57; yy96: YYDEBUG(96, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy97; if (yych != 'r') goto yy57; yy97: YYDEBUG(97, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy77; if (yych == 's') goto yy77; goto yy73; yy98: YYDEBUG(98, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy111; if (yych == 'i') goto yy111; goto yy57; yy99: YYDEBUG(99, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy100; if (yych != 'r') goto yy57; yy100: YYDEBUG(100, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy101; if (yych != 't') goto yy57; yy101: YYDEBUG(101, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych == 'H') goto yy103; if (yych <= 'M') goto yy57; } else { if (yych <= 'h') { if (yych <= 'g') goto yy57; goto yy103; } else { if (yych != 'n') goto yy57; } } YYDEBUG(102, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy108; if (yych == 'i') goto yy108; goto yy57; yy103: YYDEBUG(103, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy104; if (yych != 'n') goto yy57; yy104: YYDEBUG(104, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy105; if (yych != 'i') goto yy57; yy105: YYDEBUG(105, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy106; if (yych != 'g') goto yy57; yy106: YYDEBUG(106, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy107; if (yych != 'h') goto yy57; yy107: YYDEBUG(107, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy97; if (yych == 't') goto yy97; goto yy57; yy108: YYDEBUG(108, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy109; if (yych != 'g') goto yy57; yy109: YYDEBUG(109, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy110; if (yych != 'h') goto yy57; yy110: YYDEBUG(110, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy97; if (yych == 't') goto yy97; goto yy57; yy111: YYDEBUG(111, *YYCURSOR); yyaccept = 3; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'D') goto yy112; if (yych != 'd') goto yy73; yy112: YYDEBUG(112, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy113; if (yych != 'a') goto yy57; yy113: YYDEBUG(113, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy77; if (yych == 'y') goto yy77; goto yy57; yy114: YYDEBUG(114, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy97; if (yych == 'y') goto yy97; goto yy57; yy115: YYDEBUG(115, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy116; if (yych != 'u') goto yy57; yy116: YYDEBUG(116, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy97; if (yych == 'r') goto yy97; goto yy57; yy117: YYDEBUG(117, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy122; if (yych == 'n') goto yy122; goto yy57; yy118: YYDEBUG(118, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy119; if (yych != 'n') goto yy57; yy119: YYDEBUG(119, *YYCURSOR); yyaccept = 3; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'U') { if (yych == 'S') goto yy77; if (yych <= 'T') goto yy73; } else { if (yych <= 's') { if (yych <= 'r') goto yy73; goto yy77; } else { if (yych != 'u') goto yy73; } } YYDEBUG(120, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy121; if (yych != 't') goto yy57; yy121: YYDEBUG(121, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy97; if (yych == 'e') goto yy97; goto yy57; yy122: YYDEBUG(122, *YYCURSOR); yyaccept = 3; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych == 'D') goto yy123; if (yych <= 'S') goto yy73; goto yy124; } else { if (yych <= 'd') { if (yych <= 'c') goto yy73; } else { if (yych == 't') goto yy124; goto yy73; } } yy123: YYDEBUG(123, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy125; if (yych == 'a') goto yy125; goto yy57; yy124: YYDEBUG(124, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy97; if (yych == 'h') goto yy97; goto yy57; yy125: YYDEBUG(125, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy77; if (yych == 'y') goto yy77; goto yy57; yy126: YYDEBUG(126, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy137; if (yych == 'n') goto yy137; goto yy57; yy127: YYDEBUG(127, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy132; if (yych == 't') goto yy132; goto yy57; yy128: YYDEBUG(128, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy129; if (yych != 'c') goto yy57; yy129: YYDEBUG(129, *YYCURSOR); yyaccept = 3; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych == 'O') goto yy130; if (yych <= 'R') goto yy73; goto yy77; } else { if (yych <= 'o') { if (yych <= 'n') goto yy73; } else { if (yych == 's') goto yy77; goto yy73; } } yy130: YYDEBUG(130, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy131; if (yych != 'n') goto yy57; yy131: YYDEBUG(131, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy97; if (yych == 'd') goto yy97; goto yy57; yy132: YYDEBUG(132, *YYCURSOR); yyaccept = 3; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'U') goto yy133; if (yych != 'u') goto yy73; yy133: YYDEBUG(133, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy134; if (yych != 'r') goto yy57; yy134: YYDEBUG(134, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy135; if (yych != 'd') goto yy57; yy135: YYDEBUG(135, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy136; if (yych != 'a') goto yy57; yy136: YYDEBUG(136, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy77; if (yych == 'y') goto yy77; goto yy57; yy137: YYDEBUG(137, *YYCURSOR); yyaccept = 3; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'D') goto yy138; if (yych != 'd') goto yy73; yy138: YYDEBUG(138, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy139; if (yych != 'a') goto yy57; yy139: YYDEBUG(139, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy77; if (yych == 'y') goto yy77; goto yy57; yy140: YYDEBUG(140, *YYCURSOR); yych = *++YYCURSOR; goto yy4; yy141: YYDEBUG(141, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; if (yych >= '{') goto yy4; } yy142: YYDEBUG(142, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; if (yych >= '{') goto yy4; } yy143: YYDEBUG(143, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; if (yych >= '{') goto yy4; } yy144: YYDEBUG(144, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; if (yych >= '{') goto yy4; } yy145: YYDEBUG(145, *YYCURSOR); yych = *++YYCURSOR; if (yych == ')') goto yy140; goto yy4; yy146: YYDEBUG(146, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; goto yy148; } } else { if (yych <= '^') { if (yych <= '@') goto yy4; if (yych <= 'Z') goto yy142; goto yy4; } else { if (yych <= '_') goto yy148; if (yych <= '`') goto yy4; if (yych >= '{') goto yy4; } } yy147: YYDEBUG(147, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; } } else { if (yych <= '^') { if (yych <= '@') goto yy4; if (yych <= 'Z') goto yy143; goto yy4; } else { if (yych <= '_') goto yy148; if (yych <= '`') goto yy4; if (yych <= 'z') goto yy151; goto yy4; } } yy148: YYDEBUG(148, *YYCURSOR); ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yybm[0+yych] & 8) { goto yy149; } goto yy57; yy149: YYDEBUG(149, *YYCURSOR); yyaccept = 0; YYMARKER = ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; YYDEBUG(150, *YYCURSOR); if (yybm[0+yych] & 8) { goto yy149; } if (yych <= '.') { if (yych == '-') goto yy148; goto yy4; } else { if (yych <= '/') goto yy148; if (yych == '_') goto yy148; goto yy4; } yy151: YYDEBUG(151, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; goto yy148; } } else { if (yych <= '^') { if (yych <= '@') goto yy4; if (yych <= 'Z') goto yy144; goto yy4; } else { if (yych <= '_') goto yy148; if (yych <= '`') goto yy4; if (yych >= '{') goto yy4; } } yy152: YYDEBUG(152, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; goto yy148; } } else { if (yych <= '^') { if (yych <= '@') goto yy4; if (yych <= 'Z') goto yy145; goto yy4; } else { if (yych <= '_') goto yy148; if (yych <= '`') goto yy4; if (yych >= '{') goto yy4; } } yy153: YYDEBUG(153, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 16) { goto yy154; } if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych <= '/') { if (yych <= '.') goto yy4; goto yy148; } else { if (yych == '_') goto yy148; goto yy4; } } yy154: YYDEBUG(154, *YYCURSOR); ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; yy155: YYDEBUG(155, *YYCURSOR); if (yybm[0+yych] & 16) { goto yy154; } if (yych <= '.') { if (yych == '-') goto yy148; goto yy57; } else { if (yych <= '/') goto yy148; if (yych == '_') goto yy148; goto yy57; } yy156: YYDEBUG(156, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; if (yych <= 'z') goto yy141; goto yy4; } yy157: YYDEBUG(157, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy142; } else { if (yych <= 'Z') { if (yych >= 'U') goto yy142; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy142; goto yy4; } } YYDEBUG(158, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych != '+') goto yy4; } } else { if (yych <= 'Z') { if (yych <= '-') goto yy159; if (yych <= '@') goto yy4; goto yy143; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy143; goto yy4; } } yy159: YYDEBUG(159, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '1') goto yy160; if (yych <= '2') goto yy161; if (yych <= '9') goto yy162; goto yy57; yy160: YYDEBUG(160, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy4; if (yych <= '9') goto yy162; if (yych <= ':') goto yy163; goto yy4; yy161: YYDEBUG(161, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '5') { if (yych <= '/') goto yy4; if (yych >= '5') goto yy164; } else { if (yych <= '9') goto yy140; if (yych <= ':') goto yy163; goto yy4; } yy162: YYDEBUG(162, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy4; if (yych <= '5') goto yy164; if (yych <= '9') goto yy140; if (yych >= ';') goto yy4; yy163: YYDEBUG(163, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy4; if (yych <= '5') goto yy164; if (yych <= '9') goto yy140; goto yy4; yy164: YYDEBUG(164, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy4; if (yych <= '9') goto yy140; goto yy4; yy165: YYDEBUG(165, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'C') goto yy142; if (yych >= 'E') goto yy168; } } else { if (yych <= 'c') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'd') goto yy166; if (yych <= 'e') goto yy168; if (yych <= 'z') goto yy142; goto yy4; } } yy166: YYDEBUG(166, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= 'N') { if (yych <= ')') { if (yych >= ')') goto yy140; } else { if (yych <= '@') goto yy167; if (yych <= 'M') goto yy143; goto yy174; } } else { if (yych <= 'm') { if (yych <= 'Z') goto yy143; if (yych >= 'a') goto yy143; } else { if (yych <= 'n') goto yy174; if (yych <= 'z') goto yy143; } } yy167: YYDEBUG(167, *YYCURSOR); #line 1607 "ext/date/lib/parse_date.re" { const timelib_relunit* relunit; DEBUG_OUTPUT("daytext"); TIMELIB_INIT; TIMELIB_HAVE_RELATIVE(); TIMELIB_HAVE_WEEKDAY_RELATIVE(); TIMELIB_UNHAVE_TIME(); relunit = timelib_lookup_relunit((char**) &ptr); s->time->relative.weekday = relunit->multiplier; if (s->time->relative.weekday_behavior != 2) { s->time->relative.weekday_behavior = 1; } TIMELIB_DEINIT; return TIMELIB_WEEKDAY; } #line 3623 "ext/date/lib/parse_date.c" yy168: YYDEBUG(168, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'K') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'J') goto yy143; } } else { if (yych <= 'j') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'k') goto yy169; if (yych <= 'z') goto yy143; goto yy4; } } yy169: YYDEBUG(169, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'D') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'C') goto yy144; } } else { if (yych <= 'c') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'd') goto yy170; if (yych <= 'z') goto yy144; goto yy4; } } yy170: YYDEBUG(170, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; } else { if (yych <= '`') { if (yych <= 'Z') goto yy145; goto yy4; } else { if (yych <= 'a') goto yy171; if (yych <= 'z') goto yy145; goto yy4; } } yy171: YYDEBUG(171, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'X') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'Y') goto yy172; if (yych != 'y') goto yy4; } yy172: YYDEBUG(172, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy173; if (yych != 's') goto yy167; yy173: YYDEBUG(173, *YYCURSOR); yych = *++YYCURSOR; goto yy167; yy174: YYDEBUG(174, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy144; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'e') goto yy175; if (yych <= 'z') goto yy144; goto yy4; } } yy175: YYDEBUG(175, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'R') goto yy145; } } else { if (yych <= 'r') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 's') goto yy176; if (yych <= 'z') goto yy145; goto yy4; } } yy176: YYDEBUG(176, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'D') goto yy177; if (yych != 'd') goto yy4; } yy177: YYDEBUG(177, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy178; if (yych != 'a') goto yy57; yy178: YYDEBUG(178, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy173; if (yych == 'y') goto yy173; goto yy57; yy179: YYDEBUG(179, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych <= '/') { if (yych <= '.') goto yy4; goto yy148; } else { if (yych <= '@') goto yy4; if (yych <= 'C') goto yy142; goto yy166; } } } else { if (yych <= '`') { if (yych <= 'Z') { if (yych <= 'E') goto yy168; goto yy142; } else { if (yych == '_') goto yy148; goto yy4; } } else { if (yych <= 'd') { if (yych <= 'c') goto yy147; } else { if (yych <= 'e') goto yy181; if (yych <= 'z') goto yy147; goto yy4; } } } YYDEBUG(180, *YYCURSOR); yyaccept = 4; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'M') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy167; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy167; goto yy143; } } else { if (yych <= '_') { if (yych <= 'N') goto yy174; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy167; goto yy148; } else { if (yych <= 'm') { if (yych <= '`') goto yy167; goto yy151; } else { if (yych <= 'n') goto yy187; if (yych <= 'z') goto yy151; goto yy167; } } } yy181: YYDEBUG(181, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'J') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'K') goto yy169; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'j') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 'k') goto yy182; if (yych <= 'z') goto yy151; goto yy4; } } } yy182: YYDEBUG(182, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'D') goto yy170; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'c') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'd') goto yy183; if (yych <= 'z') goto yy152; goto yy4; } } } yy183: YYDEBUG(183, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '_') { if (yych <= 'A') goto yy171; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'a') goto yy184; if (yych <= 'z') goto yy153; goto yy4; } } yy184: YYDEBUG(184, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'X') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'Y') goto yy172; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'y') goto yy185; if (yych <= 'z') goto yy154; goto yy4; } } yy185: YYDEBUG(185, *YYCURSOR); yyaccept = 4; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '.') { if (yych == '-') goto yy148; goto yy167; } else { if (yych <= '/') goto yy148; if (yych <= 'R') goto yy167; goto yy173; } } else { if (yych <= '`') { if (yych == '_') goto yy148; goto yy167; } else { if (yych == 's') goto yy186; if (yych <= 'z') goto yy154; goto yy167; } } yy186: YYDEBUG(186, *YYCURSOR); yyaccept = 4; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 16) { goto yy154; } if (yych <= '.') { if (yych == '-') goto yy148; goto yy167; } else { if (yych <= '/') goto yy148; if (yych == '_') goto yy148; goto yy167; } yy187: YYDEBUG(187, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'E') goto yy175; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'd') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'e') goto yy188; if (yych <= 'z') goto yy152; goto yy4; } } } yy188: YYDEBUG(188, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'R') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'S') goto yy176; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'r') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 's') goto yy189; if (yych <= 'z') goto yy153; goto yy4; } } } yy189: YYDEBUG(189, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'D') goto yy177; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'd') goto yy190; if (yych <= 'z') goto yy154; goto yy4; } } yy190: YYDEBUG(190, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy178; if (yych != 'a') goto yy155; YYDEBUG(191, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy173; if (yych == 'y') goto yy186; goto yy155; yy192: YYDEBUG(192, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'C') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'B') goto yy142; } } else { if (yych <= 'b') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'c') goto yy193; if (yych <= 'z') goto yy142; goto yy4; } } yy193: YYDEBUG(193, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= '(') { if (yych <= '\t') { if (yych >= '\t') goto yy196; } else { if (yych == ' ') goto yy196; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; } else { if (yych <= '-') goto yy197; if (yych <= '.') goto yy196; } } } else { if (yych <= 'Z') { if (yych <= '@') { if (yych <= '9') goto yy196; } else { if (yych == 'E') goto yy202; goto yy143; } } else { if (yych <= 'd') { if (yych >= 'a') goto yy143; } else { if (yych <= 'e') goto yy202; if (yych <= 'z') goto yy143; } } } yy194: YYDEBUG(194, *YYCURSOR); #line 1666 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("monthtext"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->m = timelib_lookup_month((char **) &ptr); TIMELIB_DEINIT; return TIMELIB_DATE_TEXT; } #line 4152 "ext/date/lib/parse_date.c" yy195: YYDEBUG(195, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 21) YYFILL(21); yych = *YYCURSOR; yy196: YYDEBUG(196, *YYCURSOR); if (yybm[0+yych] & 32) { goto yy195; } if (yych <= '/') goto yy57; if (yych <= '2') goto yy198; if (yych <= '3') goto yy200; if (yych <= '9') goto yy201; goto yy57; yy197: YYDEBUG(197, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy196; if (yych <= '0') goto yy357; if (yych <= '2') goto yy358; if (yych <= '3') goto yy359; goto yy196; yy198: YYDEBUG(198, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'm') { if (yych <= '1') { if (yych <= '/') goto yy216; if (yych <= '0') goto yy298; goto yy299; } else { if (yych <= '2') goto yy355; if (yych <= '9') goto yy356; goto yy216; } } else { if (yych <= 'r') { if (yych <= 'n') goto yy212; if (yych <= 'q') goto yy216; goto yy213; } else { if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy199: YYDEBUG(199, *YYCURSOR); #line 1412 "ext/date/lib/parse_date.re" { int length = 0; DEBUG_OUTPUT("datetextual | datenoyear"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->m = timelib_get_month((char **) &ptr); s->time->d = timelib_get_nr((char **) &ptr, 2); s->time->y = timelib_get_nr_ex((char **) &ptr, 4, &length); TIMELIB_PROCESS_YEAR(s->time->y, length); TIMELIB_DEINIT; return TIMELIB_DATE_TEXT; } #line 4216 "ext/date/lib/parse_date.c" yy200: YYDEBUG(200, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'm') { if (yych <= '1') { if (yych <= '/') goto yy216; if (yych <= '0') goto yy298; goto yy299; } else { if (yych <= '2') goto yy209; if (yych <= '9') goto yy210; goto yy216; } } else { if (yych <= 'r') { if (yych <= 'n') goto yy212; if (yych <= 'q') goto yy216; goto yy213; } else { if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy201: YYDEBUG(201, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'm') { if (yych <= '1') { if (yych <= '/') goto yy216; if (yych <= '0') goto yy207; goto yy208; } else { if (yych <= '2') goto yy209; if (yych <= '9') goto yy210; goto yy216; } } else { if (yych <= 'r') { if (yych <= 'n') goto yy212; if (yych <= 'q') goto yy216; goto yy213; } else { if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy202: YYDEBUG(202, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'M') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'L') goto yy144; } } else { if (yych <= 'l') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'm') goto yy203; if (yych <= 'z') goto yy144; goto yy4; } } yy203: YYDEBUG(203, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'B') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'A') goto yy145; } } else { if (yych <= 'a') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'b') goto yy204; if (yych <= 'z') goto yy145; goto yy4; } } yy204: YYDEBUG(204, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'E') goto yy205; if (yych != 'e') goto yy4; } yy205: YYDEBUG(205, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy206; if (yych != 'r') goto yy57; yy206: YYDEBUG(206, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ' ') { if (yych == '\t') goto yy196; if (yych <= 0x1F) goto yy194; goto yy196; } else { if (yych <= '.') { if (yych <= ',') goto yy194; goto yy196; } else { if (yych <= '/') goto yy194; if (yych <= '9') goto yy196; goto yy194; } } yy207: YYDEBUG(207, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy221; goto yy57; } else { if (yych <= '0') goto yy296; if (yych <= '9') goto yy297; if (yych <= ':') goto yy221; goto yy57; } yy208: YYDEBUG(208, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy264; goto yy57; } else { if (yych <= '2') goto yy297; if (yych <= '9') goto yy296; if (yych <= ':') goto yy264; goto yy57; } yy209: YYDEBUG(209, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy264; goto yy57; } else { if (yych <= '4') goto yy296; if (yych <= '9') goto yy293; if (yych <= ':') goto yy264; goto yy57; } yy210: YYDEBUG(210, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy264; goto yy57; } else { if (yych <= '9') goto yy293; if (yych <= ':') goto yy264; goto yy57; } yy211: YYDEBUG(211, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); goto yy216; yy212: YYDEBUG(212, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); goto yy216; yy213: YYDEBUG(213, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); goto yy216; yy214: YYDEBUG(214, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); goto yy216; yy215: YYDEBUG(215, *YYCURSOR); yyaccept = 6; YYMARKER = ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 18) YYFILL(18); yych = *YYCURSOR; yy216: YYDEBUG(216, *YYCURSOR); if (yybm[0+yych] & 64) { goto yy215; } if (yych <= '2') { if (yych <= '/') goto yy199; if (yych <= '0') goto yy259; if (yych <= '1') goto yy260; goto yy261; } else { if (yych <= '9') goto yy262; if (yych != 'T') goto yy199; } YYDEBUG(217, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '1') goto yy218; if (yych <= '2') goto yy219; if (yych <= '9') goto yy220; goto yy57; yy218: YYDEBUG(218, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy221; goto yy57; } else { if (yych <= '9') goto yy220; if (yych <= ':') goto yy221; goto yy57; } yy219: YYDEBUG(219, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy221; goto yy57; } else { if (yych <= '4') goto yy220; if (yych == ':') goto yy221; goto yy57; } yy220: YYDEBUG(220, *YYCURSOR); yych = *++YYCURSOR; if (yych == '.') goto yy221; if (yych != ':') goto yy57; yy221: YYDEBUG(221, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy222; if (yych <= '9') goto yy224; goto yy57; yy222: YYDEBUG(222, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy225; } else { if (yych <= '9') goto yy224; if (yych <= ':') goto yy225; } yy223: YYDEBUG(223, *YYCURSOR); #line 1714 "ext/date/lib/parse_date.re" { int tz_not_found; DEBUG_OUTPUT("dateshortwithtimeshort | dateshortwithtimelong | dateshortwithtimelongtz"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->m = timelib_get_month((char **) &ptr); s->time->d = timelib_get_nr((char **) &ptr, 2); TIMELIB_HAVE_TIME(); s->time->h = timelib_get_nr((char **) &ptr, 2); s->time->i = timelib_get_nr((char **) &ptr, 2); if (*ptr == ':') { s->time->s = timelib_get_nr((char **) &ptr, 2); if (*ptr == '.') { s->time->f = timelib_get_frac_nr((char **) &ptr, 8); } } if (*ptr != '\0') { s->time->z = timelib_get_zone((char **) &ptr, &s->time->dst, s->time, &tz_not_found, s->tzdb); if (tz_not_found) { add_error(s, "The timezone could not be found in the database"); } } TIMELIB_DEINIT; return TIMELIB_SHORTDATE_WITH_TIME; } #line 4514 "ext/date/lib/parse_date.c" yy224: YYDEBUG(224, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy225; if (yych != ':') goto yy223; yy225: YYDEBUG(225, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy226; if (yych <= '6') goto yy227; if (yych <= '9') goto yy228; goto yy57; yy226: YYDEBUG(226, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy223; if (yych <= '9') goto yy229; goto yy223; yy227: YYDEBUG(227, *YYCURSOR); yych = *++YYCURSOR; if (yych == '0') goto yy229; goto yy223; yy228: YYDEBUG(228, *YYCURSOR); yych = *++YYCURSOR; goto yy223; yy229: YYDEBUG(229, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '*') { if (yych <= 0x1F) { if (yych == '\t') goto yy231; goto yy223; } else { if (yych <= ' ') goto yy231; if (yych == '(') goto yy231; goto yy223; } } else { if (yych <= '@') { if (yych == ',') goto yy223; if (yych <= '-') goto yy231; goto yy223; } else { if (yych <= 'Z') goto yy231; if (yych <= '`') goto yy223; if (yych <= 'z') goto yy231; goto yy223; } } yy230: YYDEBUG(230, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 9) YYFILL(9); yych = *YYCURSOR; yy231: YYDEBUG(231, *YYCURSOR); if (yych <= '+') { if (yych <= ' ') { if (yych == '\t') goto yy230; if (yych <= 0x1F) goto yy57; goto yy230; } else { if (yych == '(') goto yy234; if (yych <= '*') goto yy57; goto yy233; } } else { if (yych <= 'F') { if (yych == '-') goto yy233; if (yych <= '@') goto yy57; goto yy235; } else { if (yych <= 'Z') { if (yych >= 'H') goto yy235; } else { if (yych <= '`') goto yy57; if (yych <= 'z') goto yy236; goto yy57; } } } yy232: YYDEBUG(232, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych == ')') goto yy228; if (yych <= '@') goto yy223; goto yy237; } else { if (yych <= 'Z') { if (yych <= 'M') goto yy257; goto yy237; } else { if (yych <= '`') goto yy223; if (yych <= 'z') goto yy242; goto yy223; } } yy233: YYDEBUG(233, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '1') goto yy252; if (yych <= '2') goto yy253; if (yych <= '9') goto yy254; goto yy57; yy234: YYDEBUG(234, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') goto yy57; if (yych <= 'Z') goto yy236; if (yych <= '`') goto yy57; if (yych <= 'z') goto yy236; goto yy57; yy235: YYDEBUG(235, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') { if (yych == ')') goto yy228; goto yy223; } else { if (yych <= 'Z') goto yy237; if (yych <= '`') goto yy223; if (yych <= 'z') goto yy242; goto yy223; } yy236: YYDEBUG(236, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') { if (yych == ')') goto yy228; goto yy223; } else { if (yych <= 'Z') goto yy237; if (yych <= '`') goto yy223; if (yych >= '{') goto yy223; } yy237: YYDEBUG(237, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') { if (yych == ')') goto yy228; goto yy223; } else { if (yych <= 'Z') goto yy238; if (yych <= '`') goto yy223; if (yych >= '{') goto yy223; } yy238: YYDEBUG(238, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') { if (yych == ')') goto yy228; goto yy223; } else { if (yych <= 'Z') goto yy239; if (yych <= '`') goto yy223; if (yych >= '{') goto yy223; } yy239: YYDEBUG(239, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') { if (yych == ')') goto yy228; goto yy223; } else { if (yych <= 'Z') goto yy240; if (yych <= '`') goto yy223; if (yych >= '{') goto yy223; } yy240: YYDEBUG(240, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') { if (yych == ')') goto yy228; goto yy223; } else { if (yych <= 'Z') goto yy241; if (yych <= '`') goto yy223; if (yych >= '{') goto yy223; } yy241: YYDEBUG(241, *YYCURSOR); yych = *++YYCURSOR; if (yych == ')') goto yy228; goto yy223; yy242: YYDEBUG(242, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') { if (yych == ')') goto yy228; goto yy223; } else { if (yych == '.') goto yy223; goto yy244; } } else { if (yych <= '^') { if (yych <= '@') goto yy223; if (yych <= 'Z') goto yy238; goto yy223; } else { if (yych <= '_') goto yy244; if (yych <= '`') goto yy223; if (yych >= '{') goto yy223; } } yy243: YYDEBUG(243, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') { if (yych == ')') goto yy228; goto yy223; } else { if (yych == '.') goto yy223; } } else { if (yych <= '^') { if (yych <= '@') goto yy223; if (yych <= 'Z') goto yy239; goto yy223; } else { if (yych <= '_') goto yy244; if (yych <= '`') goto yy223; if (yych <= 'z') goto yy247; goto yy223; } } yy244: YYDEBUG(244, *YYCURSOR); ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yych <= '@') goto yy57; if (yych <= 'Z') goto yy245; if (yych <= '`') goto yy57; if (yych >= '{') goto yy57; yy245: YYDEBUG(245, *YYCURSOR); yyaccept = 7; YYMARKER = ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; YYDEBUG(246, *YYCURSOR); if (yych <= '@') { if (yych <= '-') { if (yych <= ',') goto yy223; goto yy244; } else { if (yych == '/') goto yy244; goto yy223; } } else { if (yych <= '_') { if (yych <= 'Z') goto yy245; if (yych <= '^') goto yy223; goto yy244; } else { if (yych <= '`') goto yy223; if (yych <= 'z') goto yy245; goto yy223; } } yy247: YYDEBUG(247, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') { if (yych == ')') goto yy228; goto yy223; } else { if (yych == '.') goto yy223; goto yy244; } } else { if (yych <= '^') { if (yych <= '@') goto yy223; if (yych <= 'Z') goto yy240; goto yy223; } else { if (yych <= '_') goto yy244; if (yych <= '`') goto yy223; if (yych >= '{') goto yy223; } } YYDEBUG(248, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') { if (yych == ')') goto yy228; goto yy223; } else { if (yych == '.') goto yy223; goto yy244; } } else { if (yych <= '^') { if (yych <= '@') goto yy223; if (yych <= 'Z') goto yy241; goto yy223; } else { if (yych <= '_') goto yy244; if (yych <= '`') goto yy223; if (yych >= '{') goto yy223; } } YYDEBUG(249, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ')') { if (yych <= '(') goto yy223; goto yy228; } else { if (yych == '-') goto yy244; goto yy223; } } else { if (yych <= '_') { if (yych <= '/') goto yy244; if (yych <= '^') goto yy223; goto yy244; } else { if (yych <= '`') goto yy223; if (yych >= '{') goto yy223; } } yy250: YYDEBUG(250, *YYCURSOR); ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; YYDEBUG(251, *YYCURSOR); if (yych <= '/') { if (yych == '-') goto yy244; if (yych <= '.') goto yy57; goto yy244; } else { if (yych <= '_') { if (yych <= '^') goto yy57; goto yy244; } else { if (yych <= '`') goto yy57; if (yych <= 'z') goto yy250; goto yy57; } } yy252: YYDEBUG(252, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy223; if (yych <= '9') goto yy254; if (yych <= ':') goto yy255; goto yy223; yy253: YYDEBUG(253, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '5') { if (yych <= '/') goto yy223; if (yych >= '5') goto yy256; } else { if (yych <= '9') goto yy228; if (yych <= ':') goto yy255; goto yy223; } yy254: YYDEBUG(254, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy223; if (yych <= '5') goto yy256; if (yych <= '9') goto yy228; if (yych >= ';') goto yy223; yy255: YYDEBUG(255, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy223; if (yych <= '5') goto yy256; if (yych <= '9') goto yy228; goto yy223; yy256: YYDEBUG(256, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy223; if (yych <= '9') goto yy228; goto yy223; yy257: YYDEBUG(257, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych == ')') goto yy228; if (yych <= '@') goto yy223; goto yy238; } else { if (yych <= 'Z') { if (yych >= 'U') goto yy238; } else { if (yych <= '`') goto yy223; if (yych <= 'z') goto yy238; goto yy223; } } YYDEBUG(258, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= ')') { if (yych <= '(') goto yy223; goto yy228; } else { if (yych == '+') goto yy233; goto yy223; } } else { if (yych <= 'Z') { if (yych <= '-') goto yy233; if (yych <= '@') goto yy223; goto yy239; } else { if (yych <= '`') goto yy223; if (yych <= 'z') goto yy239; goto yy223; } } yy259: YYDEBUG(259, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy221; goto yy199; } else { if (yych <= '0') goto yy291; if (yych <= '9') goto yy292; if (yych <= ':') goto yy221; goto yy199; } yy260: YYDEBUG(260, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy264; goto yy199; } else { if (yych <= '2') goto yy292; if (yych <= '9') goto yy291; if (yych <= ':') goto yy264; goto yy199; } yy261: YYDEBUG(261, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy264; goto yy199; } else { if (yych <= '4') goto yy291; if (yych <= '9') goto yy263; if (yych <= ':') goto yy264; goto yy199; } yy262: YYDEBUG(262, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy264; goto yy199; } else { if (yych <= '9') goto yy263; if (yych <= ':') goto yy264; goto yy199; } yy263: YYDEBUG(263, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy199; if (yych <= '9') goto yy289; goto yy199; yy264: YYDEBUG(264, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy265; if (yych <= '9') goto yy266; goto yy57; yy265: YYDEBUG(265, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy267; goto yy223; } else { if (yych <= '9') goto yy282; if (yych <= ':') goto yy267; goto yy223; } yy266: YYDEBUG(266, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy267; if (yych != ':') goto yy223; yy267: YYDEBUG(267, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy268; if (yych <= '6') goto yy269; if (yych <= '9') goto yy228; goto yy57; yy268: YYDEBUG(268, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy223; if (yych <= '9') goto yy270; goto yy223; yy269: YYDEBUG(269, *YYCURSOR); yych = *++YYCURSOR; if (yych != '0') goto yy223; yy270: YYDEBUG(270, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '*') { if (yych <= 0x1F) { if (yych == '\t') goto yy272; goto yy223; } else { if (yych <= ' ') goto yy272; if (yych == '(') goto yy272; goto yy223; } } else { if (yych <= '@') { if (yych == ',') goto yy223; if (yych <= '-') goto yy272; goto yy223; } else { if (yych <= 'Z') goto yy272; if (yych <= '`') goto yy223; if (yych <= 'z') goto yy272; goto yy223; } } yy271: YYDEBUG(271, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 9) YYFILL(9); yych = *YYCURSOR; yy272: YYDEBUG(272, *YYCURSOR); if (yych <= '@') { if (yych <= '\'') { if (yych <= '\t') { if (yych <= 0x08) goto yy57; goto yy271; } else { if (yych == ' ') goto yy271; goto yy57; } } else { if (yych <= '+') { if (yych <= '(') goto yy234; if (yych <= '*') goto yy57; goto yy233; } else { if (yych == '-') goto yy233; goto yy57; } } } else { if (yych <= 'Z') { if (yych <= 'G') { if (yych <= 'A') goto yy273; if (yych <= 'F') goto yy235; goto yy232; } else { if (yych != 'P') goto yy235; } } else { if (yych <= 'o') { if (yych <= '`') goto yy57; if (yych <= 'a') goto yy274; goto yy236; } else { if (yych <= 'p') goto yy274; if (yych <= 'z') goto yy236; goto yy57; } } } yy273: YYDEBUG(273, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'L') { if (yych <= '-') { if (yych == ')') goto yy228; goto yy223; } else { if (yych <= '.') goto yy275; if (yych <= '@') goto yy223; goto yy237; } } else { if (yych <= '`') { if (yych <= 'M') goto yy276; if (yych <= 'Z') goto yy237; goto yy223; } else { if (yych == 'm') goto yy281; if (yych <= 'z') goto yy242; goto yy223; } } yy274: YYDEBUG(274, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'L') { if (yych <= '-') { if (yych == ')') goto yy228; goto yy223; } else { if (yych <= '.') goto yy275; if (yych <= '@') goto yy223; goto yy237; } } else { if (yych <= '`') { if (yych <= 'M') goto yy276; if (yych <= 'Z') goto yy237; goto yy223; } else { if (yych == 'm') goto yy276; if (yych <= 'z') goto yy237; goto yy223; } } yy275: YYDEBUG(275, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy280; if (yych == 'm') goto yy280; goto yy57; yy276: YYDEBUG(276, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ')') { if (yych <= '\t') { if (yych <= 0x00) goto yy278; if (yych <= 0x08) goto yy223; goto yy278; } else { if (yych == ' ') goto yy278; if (yych <= '(') goto yy223; goto yy228; } } else { if (yych <= '@') { if (yych != '.') goto yy223; } else { if (yych <= 'Z') goto yy238; if (yych <= '`') goto yy223; if (yych <= 'z') goto yy238; goto yy223; } } yy277: YYDEBUG(277, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '\t') { if (yych <= 0x00) goto yy278; if (yych <= 0x08) goto yy57; } else { if (yych != ' ') goto yy57; } yy278: YYDEBUG(278, *YYCURSOR); ++YYCURSOR; YYDEBUG(279, *YYCURSOR); #line 1690 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("dateshortwithtimeshort12 | dateshortwithtimelong12"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->m = timelib_get_month((char **) &ptr); s->time->d = timelib_get_nr((char **) &ptr, 2); TIMELIB_HAVE_TIME(); s->time->h = timelib_get_nr((char **) &ptr, 2); s->time->i = timelib_get_nr((char **) &ptr, 2); if (*ptr == ':' || *ptr == '.') { s->time->s = timelib_get_nr((char **) &ptr, 2); if (*ptr == '.') { s->time->f = timelib_get_frac_nr((char **) &ptr, 8); } } s->time->h += timelib_meridian((char **) &ptr, s->time->h); TIMELIB_DEINIT; return TIMELIB_SHORTDATE_WITH_TIME; } #line 5235 "ext/date/lib/parse_date.c" yy280: YYDEBUG(280, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 0x1F) { if (yych <= 0x00) goto yy278; if (yych == '\t') goto yy278; goto yy57; } else { if (yych <= ' ') goto yy278; if (yych == '.') goto yy277; goto yy57; } yy281: YYDEBUG(281, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '-') { if (yych <= 0x1F) { if (yych <= 0x00) goto yy278; if (yych == '\t') goto yy278; goto yy223; } else { if (yych <= '(') { if (yych <= ' ') goto yy278; goto yy223; } else { if (yych <= ')') goto yy228; if (yych <= ',') goto yy223; goto yy244; } } } else { if (yych <= 'Z') { if (yych <= '.') goto yy277; if (yych <= '/') goto yy244; if (yych <= '@') goto yy223; goto yy238; } else { if (yych <= '_') { if (yych <= '^') goto yy223; goto yy244; } else { if (yych <= '`') goto yy223; if (yych <= 'z') goto yy243; goto yy223; } } } yy282: YYDEBUG(282, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ':') { if (yych <= ' ') { if (yych == '\t') goto yy283; if (yych <= 0x1F) goto yy223; } else { if (yych == '.') goto yy267; if (yych <= '9') goto yy223; goto yy267; } } else { if (yych <= 'P') { if (yych == 'A') goto yy285; if (yych <= 'O') goto yy223; goto yy285; } else { if (yych <= 'a') { if (yych <= '`') goto yy223; goto yy285; } else { if (yych == 'p') goto yy285; goto yy223; } } } yy283: YYDEBUG(283, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 5) YYFILL(5); yych = *YYCURSOR; YYDEBUG(284, *YYCURSOR); if (yych <= 'A') { if (yych <= 0x1F) { if (yych == '\t') goto yy283; goto yy57; } else { if (yych <= ' ') goto yy283; if (yych <= '@') goto yy57; } } else { if (yych <= '`') { if (yych != 'P') goto yy57; } else { if (yych <= 'a') goto yy285; if (yych != 'p') goto yy57; } } yy285: YYDEBUG(285, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych != '.') goto yy57; } else { if (yych <= 'M') goto yy287; if (yych == 'm') goto yy287; goto yy57; } yy286: YYDEBUG(286, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy287; if (yych != 'm') goto yy57; yy287: YYDEBUG(287, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 0x1F) { if (yych <= 0x00) goto yy278; if (yych == '\t') goto yy278; goto yy57; } else { if (yych <= ' ') goto yy278; if (yych != '.') goto yy57; } yy288: YYDEBUG(288, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '\t') { if (yych <= 0x00) goto yy278; if (yych <= 0x08) goto yy57; goto yy278; } else { if (yych == ' ') goto yy278; goto yy57; } yy289: YYDEBUG(289, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy199; if (yych >= ':') goto yy199; YYDEBUG(290, *YYCURSOR); yych = *++YYCURSOR; goto yy199; yy291: YYDEBUG(291, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy221; goto yy199; } else { if (yych <= '9') goto yy289; if (yych <= ':') goto yy221; goto yy199; } yy292: YYDEBUG(292, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy264; goto yy199; } else { if (yych <= '9') goto yy289; if (yych <= ':') goto yy264; goto yy199; } yy293: YYDEBUG(293, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; yy294: YYDEBUG(294, *YYCURSOR); ++YYCURSOR; yy295: YYDEBUG(295, *YYCURSOR); #line 1384 "ext/date/lib/parse_date.re" { int length = 0; DEBUG_OUTPUT("datenoday"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->m = timelib_get_month((char **) &ptr); s->time->y = timelib_get_nr_ex((char **) &ptr, 4, &length); s->time->d = 1; TIMELIB_PROCESS_YEAR(s->time->y, length); TIMELIB_DEINIT; return TIMELIB_DATE_NO_DAY; } #line 5426 "ext/date/lib/parse_date.c" yy296: YYDEBUG(296, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy221; goto yy57; } else { if (yych <= '9') goto yy294; if (yych <= ':') goto yy221; goto yy57; } yy297: YYDEBUG(297, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy264; goto yy57; } else { if (yych <= '9') goto yy294; if (yych <= ':') goto yy264; goto yy57; } yy298: YYDEBUG(298, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '/') { if (yych == '.') goto yy331; goto yy216; } else { if (yych <= '0') goto yy332; if (yych <= '1') goto yy302; if (yych <= '2') goto yy303; goto yy297; } } else { if (yych <= 'q') { if (yych <= ':') goto yy221; if (yych == 'n') goto yy212; goto yy216; } else { if (yych <= 'r') goto yy213; if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy299: YYDEBUG(299, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '/') { if (yych != '.') goto yy216; } else { if (yych <= '0') goto yy301; if (yych <= '1') goto yy302; if (yych <= '2') goto yy303; goto yy297; } } else { if (yych <= 'q') { if (yych <= ':') goto yy264; if (yych == 'n') goto yy212; goto yy216; } else { if (yych <= 'r') goto yy213; if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy300: YYDEBUG(300, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '1') { if (yych <= '/') goto yy216; if (yych <= '0') goto yy306; goto yy307; } else { if (yych <= '2') goto yy308; if (yych <= '5') goto yy309; if (yych <= '9') goto yy310; goto yy216; } yy301: YYDEBUG(301, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy264; goto yy57; } else { if (yych <= '0') goto yy304; if (yych <= '9') goto yy305; if (yych <= ':') goto yy264; goto yy57; } yy302: YYDEBUG(302, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy264; goto yy57; } else { if (yych <= '2') goto yy305; if (yych <= '9') goto yy304; if (yych <= ':') goto yy264; goto yy57; } yy303: YYDEBUG(303, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy264; goto yy57; } else { if (yych <= '4') goto yy304; if (yych <= '9') goto yy294; if (yych <= ':') goto yy264; goto yy57; } yy304: YYDEBUG(304, *YYCURSOR); yyaccept = 8; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy221; if (yych == ':') goto yy221; goto yy295; yy305: YYDEBUG(305, *YYCURSOR); yyaccept = 8; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy264; if (yych == ':') goto yy264; goto yy295; yy306: YYDEBUG(306, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy326; goto yy199; } else { if (yych <= '0') goto yy325; if (yych <= '9') goto yy330; if (yych <= ':') goto yy326; goto yy199; } yy307: YYDEBUG(307, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy311; goto yy199; } else { if (yych <= '2') goto yy330; if (yych <= '9') goto yy325; if (yych <= ':') goto yy311; goto yy199; } yy308: YYDEBUG(308, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy311; goto yy199; } else { if (yych <= '4') goto yy325; if (yych <= '9') goto yy324; if (yych <= ':') goto yy311; goto yy199; } yy309: YYDEBUG(309, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy311; goto yy199; } else { if (yych <= '9') goto yy324; if (yych <= ':') goto yy311; goto yy199; } yy310: YYDEBUG(310, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych != '.') goto yy199; } else { if (yych <= '9') goto yy263; if (yych >= ';') goto yy199; } yy311: YYDEBUG(311, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy312; if (yych <= '6') goto yy313; if (yych <= '9') goto yy266; goto yy57; yy312: YYDEBUG(312, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy267; goto yy223; } else { if (yych <= '9') goto yy314; if (yych <= ':') goto yy267; goto yy223; } yy313: YYDEBUG(313, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy267; goto yy223; } else { if (yych <= '0') goto yy270; if (yych == ':') goto yy267; goto yy223; } yy314: YYDEBUG(314, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= ' ') { if (yych == '\t') goto yy316; if (yych <= 0x1F) goto yy223; goto yy316; } else { if (yych <= '(') { if (yych <= '\'') goto yy223; goto yy316; } else { if (yych == '+') goto yy316; goto yy223; } } } else { if (yych <= ':') { if (yych <= '-') goto yy316; if (yych <= '.') goto yy267; if (yych <= '9') goto yy223; goto yy267; } else { if (yych <= 'Z') { if (yych <= '@') goto yy223; goto yy316; } else { if (yych <= '`') goto yy223; if (yych <= 'z') goto yy316; goto yy223; } } } yy315: YYDEBUG(315, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 9) YYFILL(9); yych = *YYCURSOR; yy316: YYDEBUG(316, *YYCURSOR); if (yych <= '@') { if (yych <= '\'') { if (yych <= '\t') { if (yych <= 0x08) goto yy57; goto yy315; } else { if (yych == ' ') goto yy315; goto yy57; } } else { if (yych <= '+') { if (yych <= '(') goto yy234; if (yych <= '*') goto yy57; goto yy233; } else { if (yych == '-') goto yy233; goto yy57; } } } else { if (yych <= 'Z') { if (yych <= 'G') { if (yych <= 'A') goto yy317; if (yych <= 'F') goto yy235; goto yy232; } else { if (yych != 'P') goto yy235; } } else { if (yych <= 'o') { if (yych <= '`') goto yy57; if (yych <= 'a') goto yy318; goto yy236; } else { if (yych <= 'p') goto yy318; if (yych <= 'z') goto yy236; goto yy57; } } } yy317: YYDEBUG(317, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'L') { if (yych <= '-') { if (yych == ')') goto yy228; goto yy223; } else { if (yych <= '.') goto yy320; if (yych <= '@') goto yy223; goto yy237; } } else { if (yych <= '`') { if (yych <= 'M') goto yy319; if (yych <= 'Z') goto yy237; goto yy223; } else { if (yych == 'm') goto yy323; if (yych <= 'z') goto yy242; goto yy223; } } yy318: YYDEBUG(318, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'L') { if (yych <= '-') { if (yych == ')') goto yy228; goto yy223; } else { if (yych <= '.') goto yy320; if (yych <= '@') goto yy223; goto yy237; } } else { if (yych <= '`') { if (yych <= 'M') goto yy319; if (yych <= 'Z') goto yy237; goto yy223; } else { if (yych == 'm') goto yy319; if (yych <= 'z') goto yy237; goto yy223; } } yy319: YYDEBUG(319, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ')') { if (yych <= '\t') { if (yych <= 0x00) goto yy278; if (yych <= 0x08) goto yy223; goto yy278; } else { if (yych == ' ') goto yy278; if (yych <= '(') goto yy223; goto yy228; } } else { if (yych <= '@') { if (yych == '.') goto yy322; goto yy223; } else { if (yych <= 'Z') goto yy238; if (yych <= '`') goto yy223; if (yych <= 'z') goto yy238; goto yy223; } } yy320: YYDEBUG(320, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy321; if (yych != 'm') goto yy57; yy321: YYDEBUG(321, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 0x1F) { if (yych <= 0x00) goto yy278; if (yych == '\t') goto yy278; goto yy57; } else { if (yych <= ' ') goto yy278; if (yych != '.') goto yy57; } yy322: YYDEBUG(322, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '\t') { if (yych <= 0x00) goto yy278; if (yych <= 0x08) goto yy57; goto yy278; } else { if (yych == ' ') goto yy278; goto yy57; } yy323: YYDEBUG(323, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '-') { if (yych <= 0x1F) { if (yych <= 0x00) goto yy278; if (yych == '\t') goto yy278; goto yy223; } else { if (yych <= '(') { if (yych <= ' ') goto yy278; goto yy223; } else { if (yych <= ')') goto yy228; if (yych <= ',') goto yy223; goto yy244; } } } else { if (yych <= 'Z') { if (yych <= '.') goto yy322; if (yych <= '/') goto yy244; if (yych <= '@') goto yy223; goto yy238; } else { if (yych <= '_') { if (yych <= '^') goto yy223; goto yy244; } else { if (yych <= '`') goto yy223; if (yych <= 'z') goto yy243; goto yy223; } } } yy324: YYDEBUG(324, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ':') { if (yych <= ' ') { if (yych == '\t') goto yy283; if (yych <= 0x1F) goto yy199; goto yy283; } else { if (yych <= '.') { if (yych <= '-') goto yy199; goto yy267; } else { if (yych <= '/') goto yy199; if (yych <= '9') goto yy289; goto yy267; } } } else { if (yych <= 'P') { if (yych == 'A') goto yy285; if (yych <= 'O') goto yy199; goto yy285; } else { if (yych <= 'a') { if (yych <= '`') goto yy199; goto yy285; } else { if (yych == 'p') goto yy285; goto yy199; } } } yy325: YYDEBUG(325, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ':') { if (yych <= ' ') { if (yych == '\t') goto yy283; if (yych <= 0x1F) goto yy199; goto yy283; } else { if (yych <= '.') { if (yych <= '-') goto yy199; } else { if (yych <= '/') goto yy199; if (yych <= '9') goto yy289; } } } else { if (yych <= 'P') { if (yych == 'A') goto yy285; if (yych <= 'O') goto yy199; goto yy285; } else { if (yych <= 'a') { if (yych <= '`') goto yy199; goto yy285; } else { if (yych == 'p') goto yy285; goto yy199; } } } yy326: YYDEBUG(326, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy327; if (yych <= '6') goto yy328; if (yych <= '9') goto yy224; goto yy57; yy327: YYDEBUG(327, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy225; goto yy223; } else { if (yych <= '9') goto yy329; if (yych <= ':') goto yy225; goto yy223; } yy328: YYDEBUG(328, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy225; goto yy223; } else { if (yych <= '0') goto yy270; if (yych == ':') goto yy225; goto yy223; } yy329: YYDEBUG(329, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= ' ') { if (yych == '\t') goto yy272; if (yych <= 0x1F) goto yy223; goto yy272; } else { if (yych <= '(') { if (yych <= '\'') goto yy223; goto yy272; } else { if (yych == '+') goto yy272; goto yy223; } } } else { if (yych <= ':') { if (yych <= '-') goto yy272; if (yych <= '.') goto yy225; if (yych <= '9') goto yy223; goto yy225; } else { if (yych <= 'Z') { if (yych <= '@') goto yy223; goto yy272; } else { if (yych <= '`') goto yy223; if (yych <= 'z') goto yy272; goto yy223; } } } yy330: YYDEBUG(330, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ':') { if (yych <= ' ') { if (yych == '\t') goto yy283; if (yych <= 0x1F) goto yy199; goto yy283; } else { if (yych <= '.') { if (yych <= '-') goto yy199; goto yy311; } else { if (yych <= '/') goto yy199; if (yych <= '9') goto yy289; goto yy311; } } } else { if (yych <= 'P') { if (yych == 'A') goto yy285; if (yych <= 'O') goto yy199; goto yy285; } else { if (yych <= 'a') { if (yych <= '`') goto yy199; goto yy285; } else { if (yych == 'p') goto yy285; goto yy199; } } } yy331: YYDEBUG(331, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '1') { if (yych <= '/') goto yy216; if (yych <= '0') goto yy333; goto yy334; } else { if (yych <= '2') goto yy335; if (yych <= '5') goto yy336; if (yych <= '9') goto yy337; goto yy216; } yy332: YYDEBUG(332, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy221; goto yy57; } else { if (yych <= '0') goto yy304; if (yych <= '9') goto yy305; if (yych <= ':') goto yy221; goto yy57; } yy333: YYDEBUG(333, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy350; goto yy199; } else { if (yych <= '0') goto yy349; if (yych <= '9') goto yy354; if (yych <= ':') goto yy350; goto yy199; } yy334: YYDEBUG(334, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy338; goto yy199; } else { if (yych <= '2') goto yy354; if (yych <= '9') goto yy349; if (yych <= ':') goto yy338; goto yy199; } yy335: YYDEBUG(335, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy338; goto yy199; } else { if (yych <= '4') goto yy349; if (yych <= '9') goto yy348; if (yych <= ':') goto yy338; goto yy199; } yy336: YYDEBUG(336, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy338; goto yy199; } else { if (yych <= '9') goto yy348; if (yych <= ':') goto yy338; goto yy199; } yy337: YYDEBUG(337, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych != '.') goto yy199; } else { if (yych <= '9') goto yy263; if (yych >= ';') goto yy199; } yy338: YYDEBUG(338, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy339; if (yych <= '6') goto yy340; if (yych <= '9') goto yy266; goto yy57; yy339: YYDEBUG(339, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy267; goto yy223; } else { if (yych <= '9') goto yy341; if (yych <= ':') goto yy267; goto yy223; } yy340: YYDEBUG(340, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy267; goto yy223; } else { if (yych <= '0') goto yy229; if (yych == ':') goto yy267; goto yy223; } yy341: YYDEBUG(341, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= ' ') { if (yych == '\t') goto yy343; if (yych <= 0x1F) goto yy223; goto yy343; } else { if (yych <= '(') { if (yych <= '\'') goto yy223; goto yy343; } else { if (yych == '+') goto yy343; goto yy223; } } } else { if (yych <= ':') { if (yych <= '-') goto yy343; if (yych <= '.') goto yy267; if (yych <= '9') goto yy223; goto yy267; } else { if (yych <= 'Z') { if (yych <= '@') goto yy223; goto yy343; } else { if (yych <= '`') goto yy223; if (yych <= 'z') goto yy343; goto yy223; } } } yy342: YYDEBUG(342, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 9) YYFILL(9); yych = *YYCURSOR; yy343: YYDEBUG(343, *YYCURSOR); if (yych <= '@') { if (yych <= '\'') { if (yych <= '\t') { if (yych <= 0x08) goto yy57; goto yy342; } else { if (yych == ' ') goto yy342; goto yy57; } } else { if (yych <= '+') { if (yych <= '(') goto yy234; if (yych <= '*') goto yy57; goto yy233; } else { if (yych == '-') goto yy233; goto yy57; } } } else { if (yych <= 'Z') { if (yych <= 'G') { if (yych <= 'A') goto yy344; if (yych <= 'F') goto yy235; goto yy232; } else { if (yych != 'P') goto yy235; } } else { if (yych <= 'o') { if (yych <= '`') goto yy57; if (yych <= 'a') goto yy345; goto yy236; } else { if (yych <= 'p') goto yy345; if (yych <= 'z') goto yy236; goto yy57; } } } yy344: YYDEBUG(344, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'L') { if (yych <= '-') { if (yych == ')') goto yy228; goto yy223; } else { if (yych <= '.') goto yy286; if (yych <= '@') goto yy223; goto yy237; } } else { if (yych <= '`') { if (yych <= 'M') goto yy346; if (yych <= 'Z') goto yy237; goto yy223; } else { if (yych == 'm') goto yy347; if (yych <= 'z') goto yy242; goto yy223; } } yy345: YYDEBUG(345, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'L') { if (yych <= '-') { if (yych == ')') goto yy228; goto yy223; } else { if (yych <= '.') goto yy286; if (yych <= '@') goto yy223; goto yy237; } } else { if (yych <= '`') { if (yych <= 'M') goto yy346; if (yych <= 'Z') goto yy237; goto yy223; } else { if (yych == 'm') goto yy346; if (yych <= 'z') goto yy237; goto yy223; } } yy346: YYDEBUG(346, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ')') { if (yych <= '\t') { if (yych <= 0x00) goto yy278; if (yych <= 0x08) goto yy223; goto yy278; } else { if (yych == ' ') goto yy278; if (yych <= '(') goto yy223; goto yy228; } } else { if (yych <= '@') { if (yych == '.') goto yy288; goto yy223; } else { if (yych <= 'Z') goto yy238; if (yych <= '`') goto yy223; if (yych <= 'z') goto yy238; goto yy223; } } yy347: YYDEBUG(347, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '-') { if (yych <= 0x1F) { if (yych <= 0x00) goto yy278; if (yych == '\t') goto yy278; goto yy223; } else { if (yych <= '(') { if (yych <= ' ') goto yy278; goto yy223; } else { if (yych <= ')') goto yy228; if (yych <= ',') goto yy223; goto yy244; } } } else { if (yych <= 'Z') { if (yych <= '.') goto yy288; if (yych <= '/') goto yy244; if (yych <= '@') goto yy223; goto yy238; } else { if (yych <= '_') { if (yych <= '^') goto yy223; goto yy244; } else { if (yych <= '`') goto yy223; if (yych <= 'z') goto yy243; goto yy223; } } } yy348: YYDEBUG(348, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy225; goto yy199; } else { if (yych <= '9') goto yy289; if (yych <= ':') goto yy225; goto yy199; } yy349: YYDEBUG(349, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych != '.') goto yy199; } else { if (yych <= '9') goto yy289; if (yych >= ';') goto yy199; } yy350: YYDEBUG(350, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy351; if (yych <= '6') goto yy352; if (yych <= '9') goto yy224; goto yy57; yy351: YYDEBUG(351, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy225; goto yy223; } else { if (yych <= '9') goto yy353; if (yych <= ':') goto yy225; goto yy223; } yy352: YYDEBUG(352, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy225; goto yy223; } else { if (yych <= '0') goto yy229; if (yych == ':') goto yy225; goto yy223; } yy353: YYDEBUG(353, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= ' ') { if (yych == '\t') goto yy231; if (yych <= 0x1F) goto yy223; goto yy231; } else { if (yych <= '(') { if (yych <= '\'') goto yy223; goto yy231; } else { if (yych == '+') goto yy231; goto yy223; } } } else { if (yych <= ':') { if (yych <= '-') goto yy231; if (yych <= '.') goto yy225; if (yych <= '9') goto yy223; goto yy225; } else { if (yych <= 'Z') { if (yych <= '@') goto yy223; goto yy231; } else { if (yych <= '`') goto yy223; if (yych <= 'z') goto yy231; goto yy223; } } } yy354: YYDEBUG(354, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy338; goto yy199; } else { if (yych <= '9') goto yy289; if (yych <= ':') goto yy338; goto yy199; } yy355: YYDEBUG(355, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '/') { if (yych == '.') goto yy300; goto yy216; } else { if (yych <= '0') goto yy332; if (yych <= '1') goto yy302; if (yych <= '2') goto yy303; goto yy297; } } else { if (yych <= 'q') { if (yych <= ':') goto yy264; if (yych == 'n') goto yy212; goto yy216; } else { if (yych <= 'r') goto yy213; if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy356: YYDEBUG(356, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '/') { if (yych == '.') goto yy300; goto yy216; } else { if (yych <= '0') goto yy332; if (yych <= '1') goto yy302; if (yych <= '2') goto yy303; goto yy297; } } else { if (yych <= 'q') { if (yych <= ':') goto yy264; if (yych == 'n') goto yy212; goto yy216; } else { if (yych <= 'r') goto yy213; if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy357: YYDEBUG(357, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'm') { if (yych <= '1') { if (yych <= '/') goto yy216; if (yych <= '0') goto yy360; goto yy361; } else { if (yych <= '2') goto yy368; if (yych <= '9') goto yy369; goto yy216; } } else { if (yych <= 'r') { if (yych <= 'n') goto yy212; if (yych <= 'q') goto yy216; goto yy213; } else { if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy358: YYDEBUG(358, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'm') { if (yych <= '1') { if (yych <= '/') goto yy216; if (yych <= '0') goto yy360; goto yy361; } else { if (yych <= '2') goto yy368; if (yych <= '9') goto yy369; goto yy216; } } else { if (yych <= 'r') { if (yych <= 'n') goto yy212; if (yych <= 'q') goto yy216; goto yy213; } else { if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy359: YYDEBUG(359, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'm') { if (yych <= '1') { if (yych <= '/') goto yy216; if (yych >= '1') goto yy361; } else { if (yych <= '2') goto yy209; if (yych <= '9') goto yy210; goto yy216; } } else { if (yych <= 'r') { if (yych <= 'n') goto yy212; if (yych <= 'q') goto yy216; goto yy213; } else { if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy360: YYDEBUG(360, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '/') { if (yych <= ',') goto yy216; if (yych <= '-') goto yy362; if (yych <= '.') goto yy331; goto yy216; } else { if (yych <= '0') goto yy332; if (yych <= '1') goto yy302; if (yych <= '2') goto yy303; goto yy297; } } else { if (yych <= 'q') { if (yych <= ':') goto yy221; if (yych == 'n') goto yy212; goto yy216; } else { if (yych <= 'r') goto yy213; if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy361: YYDEBUG(361, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '/') { if (yych <= ',') goto yy216; if (yych <= '-') goto yy362; if (yych <= '.') goto yy300; goto yy216; } else { if (yych <= '0') goto yy301; if (yych <= '1') goto yy302; if (yych <= '2') goto yy303; goto yy297; } } else { if (yych <= 'q') { if (yych <= ':') goto yy264; if (yych == 'n') goto yy212; goto yy216; } else { if (yych <= 'r') goto yy213; if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy362: YYDEBUG(362, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; YYDEBUG(363, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '/') goto yy364; if (yych <= '9') goto yy365; yy364: YYDEBUG(364, *YYCURSOR); #line 1528 "ext/date/lib/parse_date.re" { int length = 0; DEBUG_OUTPUT("pgtextshort"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->m = timelib_get_month((char **) &ptr); s->time->d = timelib_get_nr((char **) &ptr, 2); s->time->y = timelib_get_nr_ex((char **) &ptr, 4, &length); TIMELIB_PROCESS_YEAR(s->time->y, length); TIMELIB_DEINIT; return TIMELIB_PG_TEXT; } #line 6659 "ext/date/lib/parse_date.c" yy365: YYDEBUG(365, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy364; if (yych >= ':') goto yy364; YYDEBUG(366, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy364; if (yych >= ':') goto yy364; YYDEBUG(367, *YYCURSOR); yych = *++YYCURSOR; goto yy364; yy368: YYDEBUG(368, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '/') { if (yych <= ',') goto yy216; if (yych <= '-') goto yy362; if (yych <= '.') goto yy300; goto yy216; } else { if (yych <= '0') goto yy332; if (yych <= '1') goto yy302; if (yych <= '2') goto yy303; goto yy297; } } else { if (yych <= 'q') { if (yych <= ':') goto yy264; if (yych == 'n') goto yy212; goto yy216; } else { if (yych <= 'r') goto yy213; if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy369: YYDEBUG(369, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '/') { if (yych <= ',') goto yy216; if (yych <= '-') goto yy362; if (yych <= '.') goto yy300; goto yy216; } else { if (yych <= '0') goto yy332; if (yych <= '1') goto yy302; if (yych <= '2') goto yy303; goto yy297; } } else { if (yych <= 'q') { if (yych <= ':') goto yy264; if (yych == 'n') goto yy212; goto yy216; } else { if (yych <= 'r') goto yy213; if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy370: YYDEBUG(370, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'B') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'C') goto yy193; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'b') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'c') goto yy371; if (yych <= 'z') goto yy147; goto yy4; } } } yy371: YYDEBUG(371, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= '-') { if (yych <= ')') goto yy140; if (yych <= ',') goto yy194; } else { if (yych == '/') goto yy148; goto yy196; } } } else { if (yych <= '^') { if (yych <= 'D') { if (yych <= '@') goto yy194; goto yy143; } else { if (yych <= 'E') goto yy202; if (yych <= 'Z') goto yy143; goto yy194; } } else { if (yych <= 'd') { if (yych <= '_') goto yy148; if (yych <= '`') goto yy194; goto yy151; } else { if (yych <= 'e') goto yy373; if (yych <= 'z') goto yy151; goto yy194; } } } yy372: YYDEBUG(372, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 8) { goto yy149; } if (yych <= '/') goto yy196; if (yych <= '0') goto yy357; if (yych <= '2') goto yy358; if (yych <= '3') goto yy359; goto yy196; yy373: YYDEBUG(373, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'L') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'M') goto yy203; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'l') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'm') goto yy374; if (yych <= 'z') goto yy152; goto yy4; } } } yy374: YYDEBUG(374, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'A') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'B') goto yy204; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'a') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'b') goto yy375; if (yych <= 'z') goto yy153; goto yy4; } } } yy375: YYDEBUG(375, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'E') goto yy205; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'e') goto yy376; if (yych <= 'z') goto yy154; goto yy4; } } yy376: YYDEBUG(376, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy206; if (yych != 'r') goto yy155; yy377: YYDEBUG(377, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 16) { goto yy154; } if (yych <= '-') { if (yych <= 0x1F) { if (yych == '\t') goto yy196; goto yy194; } else { if (yych <= ' ') goto yy196; if (yych <= ',') goto yy194; } } else { if (yych <= '9') { if (yych == '/') goto yy148; goto yy196; } else { if (yych == '_') goto yy148; goto yy194; } } yy378: YYDEBUG(378, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 8) { goto yy149; } goto yy196; yy379: YYDEBUG(379, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy142; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 't') goto yy380; if (yych <= 'z') goto yy142; goto yy4; } } yy380: YYDEBUG(380, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; goto yy194; } else { if (yych <= '-') goto yy197; if (yych <= '.') goto yy196; goto yy194; } } } else { if (yych <= 'Z') { if (yych <= '@') { if (yych <= '9') goto yy196; goto yy194; } else { if (yych != 'O') goto yy143; } } else { if (yych <= 'n') { if (yych <= '`') goto yy194; goto yy143; } else { if (yych <= 'o') goto yy381; if (yych <= 'z') goto yy143; goto yy194; } } } yy381: YYDEBUG(381, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'B') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'A') goto yy144; } } else { if (yych <= 'a') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'b') goto yy382; if (yych <= 'z') goto yy144; goto yy4; } } yy382: YYDEBUG(382, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy145; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'e') goto yy383; if (yych <= 'z') goto yy145; goto yy4; } } yy383: YYDEBUG(383, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Q') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'R') goto yy206; if (yych == 'r') goto yy206; goto yy4; } yy384: YYDEBUG(384, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'T') goto yy380; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 't') goto yy385; if (yych <= 'z') goto yy147; goto yy4; } } } yy385: YYDEBUG(385, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= '-') { if (yych <= ')') goto yy140; if (yych <= ',') goto yy194; goto yy372; } else { if (yych == '/') goto yy148; goto yy196; } } } else { if (yych <= '^') { if (yych <= 'N') { if (yych <= '@') goto yy194; goto yy143; } else { if (yych <= 'O') goto yy381; if (yych <= 'Z') goto yy143; goto yy194; } } else { if (yych <= 'n') { if (yych <= '_') goto yy148; if (yych <= '`') goto yy194; goto yy151; } else { if (yych <= 'o') goto yy386; if (yych <= 'z') goto yy151; goto yy194; } } } yy386: YYDEBUG(386, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'A') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'B') goto yy382; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'a') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'b') goto yy387; if (yych <= 'z') goto yy152; goto yy4; } } } yy387: YYDEBUG(387, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'E') goto yy383; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'd') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'e') goto yy388; if (yych <= 'z') goto yy153; goto yy4; } } } yy388: YYDEBUG(388, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'Q') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'R') goto yy206; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'r') goto yy377; if (yych <= 'z') goto yy154; goto yy4; } } yy389: YYDEBUG(389, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'G') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'F') goto yy142; goto yy397; } } else { if (yych <= 'f') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'g') goto yy397; if (yych <= 'z') goto yy142; goto yy4; } } yy390: YYDEBUG(390, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'Q') goto yy142; goto yy394; } } else { if (yych <= 'q') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'r') goto yy394; if (yych <= 'z') goto yy142; goto yy4; } } yy391: YYDEBUG(391, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'N') goto yy142; } } else { if (yych <= 'n') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'o') goto yy392; if (yych <= 'z') goto yy142; goto yy4; } } yy392: YYDEBUG(392, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '@') { if (yych == ')') goto yy140; } else { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy393; if (yych <= 'z') goto yy143; } yy393: YYDEBUG(393, *YYCURSOR); #line 1586 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("ago"); TIMELIB_INIT; s->time->relative.y = 0 - s->time->relative.y; s->time->relative.m = 0 - s->time->relative.m; s->time->relative.d = 0 - s->time->relative.d; s->time->relative.h = 0 - s->time->relative.h; s->time->relative.i = 0 - s->time->relative.i; s->time->relative.s = 0 - s->time->relative.s; s->time->relative.weekday = 0 - s->time->relative.weekday; if (s->time->relative.weekday == 0) { s->time->relative.weekday = -7; } if (s->time->relative.have_special_relative && s->time->relative.special.type == TIMELIB_SPECIAL_WEEKDAY) { s->time->relative.special.amount = 0 - s->time->relative.special.amount; } TIMELIB_DEINIT; return TIMELIB_AGO; } #line 7317 "ext/date/lib/parse_date.c" yy394: YYDEBUG(394, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; goto yy194; } else { if (yych <= '-') goto yy197; if (yych <= '.') goto yy196; goto yy194; } } } else { if (yych <= 'Z') { if (yych <= '@') { if (yych <= '9') goto yy196; goto yy194; } else { if (yych != 'I') goto yy143; } } else { if (yych <= 'h') { if (yych <= '`') goto yy194; goto yy143; } else { if (yych <= 'i') goto yy395; if (yych <= 'z') goto yy143; goto yy194; } } } yy395: YYDEBUG(395, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'K') goto yy144; } } else { if (yych <= 'k') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'l') goto yy396; if (yych <= 'z') goto yy144; goto yy4; } } yy396: YYDEBUG(396, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= 0x1F) { if (yych == '\t') goto yy196; goto yy194; } else { if (yych <= ' ') goto yy196; if (yych == ')') goto yy140; goto yy194; } } else { if (yych <= '@') { if (yych == '/') goto yy194; if (yych <= '9') goto yy196; goto yy194; } else { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy194; if (yych <= 'z') goto yy145; goto yy194; } } yy397: YYDEBUG(397, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; goto yy194; } else { if (yych <= '-') goto yy197; if (yych <= '.') goto yy196; goto yy194; } } } else { if (yych <= 'Z') { if (yych <= '@') { if (yych <= '9') goto yy196; goto yy194; } else { if (yych != 'U') goto yy143; } } else { if (yych <= 't') { if (yych <= '`') goto yy194; goto yy143; } else { if (yych <= 'u') goto yy398; if (yych <= 'z') goto yy143; goto yy194; } } } yy398: YYDEBUG(398, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'R') goto yy144; } } else { if (yych <= 'r') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 's') goto yy399; if (yych <= 'z') goto yy144; goto yy4; } } yy399: YYDEBUG(399, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy145; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 't') goto yy400; if (yych <= 'z') goto yy145; goto yy4; } } yy400: YYDEBUG(400, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= '.') { if (yych <= ')') goto yy140; if (yych <= ',') goto yy194; goto yy196; } else { if (yych <= '/') goto yy194; if (yych <= '9') goto yy196; goto yy194; } } yy401: YYDEBUG(401, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'F') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'G') goto yy397; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'f') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'g') goto yy408; if (yych <= 'z') goto yy147; goto yy4; } } } yy402: YYDEBUG(402, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'Q') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'R') goto yy394; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'q') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'r') goto yy405; if (yych <= 'z') goto yy147; goto yy4; } } } yy403: YYDEBUG(403, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'N') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'O') goto yy392; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'n') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'o') goto yy404; if (yych <= 'z') goto yy147; goto yy4; } } } yy404: YYDEBUG(404, *YYCURSOR); yyaccept = 9; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy393; } else { if (yych == '.') goto yy393; goto yy148; } } else { if (yych <= '^') { if (yych <= '@') goto yy393; if (yych <= 'Z') goto yy143; goto yy393; } else { if (yych <= '_') goto yy148; if (yych <= '`') goto yy393; if (yych <= 'z') goto yy151; goto yy393; } } yy405: YYDEBUG(405, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= '-') { if (yych <= ')') goto yy140; if (yych <= ',') goto yy194; goto yy372; } else { if (yych == '/') goto yy148; goto yy196; } } } else { if (yych <= '^') { if (yych <= 'H') { if (yych <= '@') goto yy194; goto yy143; } else { if (yych <= 'I') goto yy395; if (yych <= 'Z') goto yy143; goto yy194; } } else { if (yych <= 'h') { if (yych <= '_') goto yy148; if (yych <= '`') goto yy194; goto yy151; } else { if (yych <= 'i') goto yy406; if (yych <= 'z') goto yy151; goto yy194; } } } yy406: YYDEBUG(406, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'K') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'L') goto yy396; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'k') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'l') goto yy407; if (yych <= 'z') goto yy152; goto yy4; } } } yy407: YYDEBUG(407, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ' ') { if (yych == '\t') goto yy196; if (yych <= 0x1F) goto yy194; goto yy196; } else { if (yych <= ')') { if (yych <= '(') goto yy194; goto yy140; } else { if (yych <= ',') goto yy194; if (yych <= '-') goto yy378; goto yy196; } } } else { if (yych <= 'Z') { if (yych <= '/') goto yy148; if (yych <= '9') goto yy196; if (yych <= '@') goto yy194; goto yy145; } else { if (yych <= '_') { if (yych <= '^') goto yy194; goto yy148; } else { if (yych <= '`') goto yy194; if (yych <= 'z') goto yy153; goto yy194; } } } yy408: YYDEBUG(408, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= '-') { if (yych <= ')') goto yy140; if (yych <= ',') goto yy194; goto yy372; } else { if (yych == '/') goto yy148; goto yy196; } } } else { if (yych <= '^') { if (yych <= 'T') { if (yych <= '@') goto yy194; goto yy143; } else { if (yych <= 'U') goto yy398; if (yych <= 'Z') goto yy143; goto yy194; } } else { if (yych <= 't') { if (yych <= '_') goto yy148; if (yych <= '`') goto yy194; goto yy151; } else { if (yych <= 'u') goto yy409; if (yych <= 'z') goto yy151; goto yy194; } } } yy409: YYDEBUG(409, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'R') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'S') goto yy399; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'r') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 's') goto yy410; if (yych <= 'z') goto yy152; goto yy4; } } } yy410: YYDEBUG(410, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'T') goto yy400; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 't') goto yy411; if (yych <= 'z') goto yy153; goto yy4; } } } yy411: YYDEBUG(411, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 16) { goto yy154; } if (yych <= ',') { if (yych <= 0x1F) { if (yych == '\t') goto yy196; goto yy194; } else { if (yych <= ' ') goto yy196; if (yych == ')') goto yy140; goto yy194; } } else { if (yych <= '/') { if (yych <= '-') goto yy378; if (yych <= '.') goto yy196; goto yy148; } else { if (yych <= '9') goto yy196; if (yych == '_') goto yy148; goto yy194; } } yy412: YYDEBUG(412, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == 'L') goto yy419; if (yych <= 'M') goto yy142; goto yy418; } } else { if (yych <= 'l') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; if (yych <= 'k') goto yy142; goto yy419; } else { if (yych == 'n') goto yy418; if (yych <= 'z') goto yy142; goto yy4; } } yy413: YYDEBUG(413, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'M') goto yy142; } } else { if (yych <= 'm') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'n') goto yy414; if (yych <= 'z') goto yy142; goto yy4; } } yy414: YYDEBUG(414, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; goto yy194; } else { if (yych <= '-') goto yy197; if (yych <= '.') goto yy196; goto yy194; } } } else { if (yych <= 'Z') { if (yych <= '@') { if (yych <= '9') goto yy196; goto yy194; } else { if (yych != 'U') goto yy143; } } else { if (yych <= 't') { if (yych <= '`') goto yy194; goto yy143; } else { if (yych <= 'u') goto yy415; if (yych <= 'z') goto yy143; goto yy194; } } } yy415: YYDEBUG(415, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; } else { if (yych <= '`') { if (yych <= 'Z') goto yy144; goto yy4; } else { if (yych <= 'a') goto yy416; if (yych <= 'z') goto yy144; goto yy4; } } yy416: YYDEBUG(416, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'Q') goto yy145; } } else { if (yych <= 'q') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'r') goto yy417; if (yych <= 'z') goto yy145; goto yy4; } } yy417: YYDEBUG(417, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'X') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'Y') goto yy206; if (yych == 'y') goto yy206; goto yy4; } yy418: YYDEBUG(418, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; goto yy194; } else { if (yych <= '-') goto yy197; if (yych <= '.') goto yy196; goto yy194; } } } else { if (yych <= 'Z') { if (yych <= '@') { if (yych <= '9') goto yy196; goto yy194; } else { if (yych == 'E') goto yy420; goto yy143; } } else { if (yych <= 'd') { if (yych <= '`') goto yy194; goto yy143; } else { if (yych <= 'e') goto yy420; if (yych <= 'z') goto yy143; goto yy194; } } } yy419: YYDEBUG(419, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; goto yy194; } else { if (yych <= '-') goto yy197; if (yych <= '.') goto yy196; goto yy194; } } } else { if (yych <= 'Z') { if (yych <= '@') { if (yych <= '9') goto yy196; goto yy194; } else { if (yych != 'Y') goto yy143; } } else { if (yych <= 'x') { if (yych <= '`') goto yy194; goto yy143; } else { if (yych <= 'y') goto yy420; if (yych <= 'z') goto yy143; goto yy194; } } } yy420: YYDEBUG(420, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= 0x1F) { if (yych == '\t') goto yy196; goto yy194; } else { if (yych <= ' ') goto yy196; if (yych == ')') goto yy140; goto yy194; } } else { if (yych <= '@') { if (yych == '/') goto yy194; if (yych <= '9') goto yy196; goto yy194; } else { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy194; if (yych <= 'z') goto yy144; goto yy194; } } yy421: YYDEBUG(421, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'M') { if (yych <= '.') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych == '-') goto yy148; goto yy4; } } else { if (yych <= '@') { if (yych <= '/') goto yy148; goto yy4; } else { if (yych == 'L') goto yy419; goto yy142; } } } else { if (yych <= '`') { if (yych <= 'Z') { if (yych <= 'N') goto yy418; goto yy142; } else { if (yych == '_') goto yy148; goto yy4; } } else { if (yych <= 'm') { if (yych == 'l') goto yy428; goto yy147; } else { if (yych <= 'n') goto yy427; if (yych <= 'z') goto yy147; goto yy4; } } } yy422: YYDEBUG(422, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'M') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'N') goto yy414; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'm') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'n') goto yy423; if (yych <= 'z') goto yy147; goto yy4; } } } yy423: YYDEBUG(423, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= '-') { if (yych <= ')') goto yy140; if (yych <= ',') goto yy194; goto yy372; } else { if (yych == '/') goto yy148; goto yy196; } } } else { if (yych <= '^') { if (yych <= 'T') { if (yych <= '@') goto yy194; goto yy143; } else { if (yych <= 'U') goto yy415; if (yych <= 'Z') goto yy143; goto yy194; } } else { if (yych <= 't') { if (yych <= '_') goto yy148; if (yych <= '`') goto yy194; goto yy151; } else { if (yych <= 'u') goto yy424; if (yych <= 'z') goto yy151; goto yy194; } } } yy424: YYDEBUG(424, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '_') { if (yych <= 'A') goto yy416; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'a') goto yy425; if (yych <= 'z') goto yy152; goto yy4; } } yy425: YYDEBUG(425, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'Q') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'R') goto yy417; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'q') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'r') goto yy426; if (yych <= 'z') goto yy153; goto yy4; } } } yy426: YYDEBUG(426, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'X') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'Y') goto yy206; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'y') goto yy377; if (yych <= 'z') goto yy154; goto yy4; } } yy427: YYDEBUG(427, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= '-') { if (yych <= ')') goto yy140; if (yych <= ',') goto yy194; goto yy372; } else { if (yych == '/') goto yy148; goto yy196; } } } else { if (yych <= '^') { if (yych <= 'D') { if (yych <= '@') goto yy194; goto yy143; } else { if (yych <= 'E') goto yy420; if (yych <= 'Z') goto yy143; goto yy194; } } else { if (yych <= 'd') { if (yych <= '_') goto yy148; if (yych <= '`') goto yy194; goto yy151; } else { if (yych <= 'e') goto yy429; if (yych <= 'z') goto yy151; goto yy194; } } } yy428: YYDEBUG(428, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= '-') { if (yych <= ')') goto yy140; if (yych <= ',') goto yy194; goto yy372; } else { if (yych == '/') goto yy148; goto yy196; } } } else { if (yych <= '^') { if (yych <= 'X') { if (yych <= '@') goto yy194; goto yy143; } else { if (yych <= 'Y') goto yy420; if (yych <= 'Z') goto yy143; goto yy194; } } else { if (yych <= 'x') { if (yych <= '_') goto yy148; if (yych <= '`') goto yy194; goto yy151; } else { if (yych <= 'y') goto yy429; if (yych <= 'z') goto yy151; goto yy194; } } } yy429: YYDEBUG(429, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ' ') { if (yych == '\t') goto yy196; if (yych <= 0x1F) goto yy194; goto yy196; } else { if (yych <= ')') { if (yych <= '(') goto yy194; goto yy140; } else { if (yych <= ',') goto yy194; if (yych <= '-') goto yy378; goto yy196; } } } else { if (yych <= 'Z') { if (yych <= '/') goto yy148; if (yych <= '9') goto yy196; if (yych <= '@') goto yy194; goto yy144; } else { if (yych <= '_') { if (yych <= '^') goto yy194; goto yy148; } else { if (yych <= '`') goto yy194; if (yych <= 'z') goto yy152; goto yy194; } } } yy430: YYDEBUG(430, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ' ') { if (yych == '\t') goto yy196; if (yych <= 0x1F) goto yy4; goto yy196; } else { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy196; } } else { if (yych <= 'H') { if (yych <= '/') goto yy4; if (yych <= '9') goto yy196; if (yych <= '@') goto yy4; goto yy142; } else { if (yych <= 'Z') { if (yych >= 'J') goto yy142; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy142; goto yy4; } } } yy431: YYDEBUG(431, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= 0x1F) { if (yych == '\t') goto yy196; goto yy4; } else { if (yych <= ' ') goto yy196; if (yych == ')') goto yy140; goto yy4; } } else { if (yych <= '@') { if (yych == '/') goto yy4; if (yych <= '9') goto yy196; goto yy4; } else { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; if (yych <= 'z') goto yy143; goto yy4; } } yy432: YYDEBUG(432, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ' ') { if (yych == '\t') goto yy196; if (yych <= 0x1F) goto yy4; goto yy196; } else { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy196; } } else { if (yych <= 'H') { if (yych <= '/') goto yy4; if (yych <= '9') goto yy196; if (yych <= '@') goto yy4; goto yy142; } else { if (yych <= 'Z') { if (yych >= 'J') goto yy142; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy142; goto yy4; } } } YYDEBUG(433, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ' ') { if (yych == '\t') goto yy196; if (yych <= 0x1F) goto yy4; goto yy196; } else { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy196; } } else { if (yych <= 'H') { if (yych <= '/') goto yy4; if (yych <= '9') goto yy196; if (yych <= '@') goto yy4; goto yy143; } else { if (yych <= 'Z') { if (yych >= 'J') goto yy143; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy143; goto yy4; } } } YYDEBUG(434, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= 0x1F) { if (yych == '\t') goto yy196; goto yy4; } else { if (yych <= ' ') goto yy196; if (yych == ')') goto yy140; goto yy4; } } else { if (yych <= '@') { if (yych == '/') goto yy4; if (yych <= '9') goto yy196; goto yy4; } else { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; if (yych <= 'z') goto yy144; goto yy4; } } yy435: YYDEBUG(435, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= 0x1F) { if (yych == '\t') goto yy196; goto yy4; } else { if (yych <= ' ') goto yy196; if (yych == ')') goto yy140; goto yy4; } } else { if (yych <= '@') { if (yych == '/') goto yy4; if (yych <= '9') goto yy196; goto yy4; } else { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; if (yych <= 'z') goto yy142; goto yy4; } } yy436: YYDEBUG(436, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ' ') { if (yych == '\t') goto yy196; if (yych <= 0x1F) goto yy4; goto yy196; } else { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy196; } } else { if (yych <= 'H') { if (yych <= '/') goto yy4; if (yych <= '9') goto yy196; if (yych <= '@') goto yy4; goto yy142; } else { if (yych <= 'Z') { if (yych <= 'I') goto yy431; goto yy142; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy142; goto yy4; } } } yy437: YYDEBUG(437, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'V') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy4; goto yy61; } else { if (yych <= '9') { if (yych <= '/') goto yy4; goto yy457; } else { if (yych <= ':') goto yy163; if (yych <= 'C') goto yy4; goto yy61; } } } else { if (yych <= 'H') { if (yych == 'F') goto yy61; if (yych <= 'G') goto yy4; goto yy61; } else { if (yych <= 'M') { if (yych <= 'L') goto yy4; goto yy61; } else { if (yych <= 'R') goto yy4; if (yych <= 'T') goto yy61; goto yy4; } } } } else { if (yych <= 'h') { if (yych <= 'c') { if (yych == 'X') goto yy4; if (yych <= 'Y') goto yy61; goto yy4; } else { if (yych <= 'e') { if (yych <= 'd') goto yy61; goto yy4; } else { if (yych == 'g') goto yy4; goto yy61; } } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych <= 'r') goto yy4; goto yy61; } else { if (yych <= 'w') { if (yych <= 'v') goto yy4; goto yy61; } else { if (yych == 'y') goto yy61; goto yy4; } } } } yy438: YYDEBUG(438, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych <= ':') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy4; goto yy61; } else { if (yych <= '4') { if (yych <= '/') goto yy4; goto yy457; } else { if (yych <= '5') goto yy442; if (yych <= '9') goto yy443; goto yy163; } } } else { if (yych <= 'G') { if (yych <= 'D') { if (yych <= 'C') goto yy4; goto yy61; } else { if (yych == 'F') goto yy61; goto yy4; } } else { if (yych <= 'L') { if (yych <= 'H') goto yy61; goto yy4; } else { if (yych <= 'M') goto yy61; if (yych <= 'R') goto yy4; goto yy61; } } } } else { if (yych <= 'g') { if (yych <= 'Y') { if (yych == 'W') goto yy61; if (yych <= 'X') goto yy4; goto yy61; } else { if (yych <= 'd') { if (yych <= 'c') goto yy4; goto yy61; } else { if (yych == 'f') goto yy61; goto yy4; } } } else { if (yych <= 't') { if (yych <= 'l') { if (yych <= 'h') goto yy61; goto yy4; } else { if (yych <= 'm') goto yy61; if (yych <= 'r') goto yy4; goto yy61; } } else { if (yych <= 'w') { if (yych <= 'v') goto yy4; goto yy61; } else { if (yych == 'y') goto yy61; goto yy4; } } } } yy439: YYDEBUG(439, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych <= 'C') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy4; goto yy61; } else { if (yych <= '5') { if (yych <= '/') goto yy4; goto yy442; } else { if (yych <= '9') goto yy443; if (yych <= ':') goto yy163; goto yy4; } } } else { if (yych <= 'G') { if (yych == 'E') goto yy4; if (yych <= 'F') goto yy61; goto yy4; } else { if (yych <= 'L') { if (yych <= 'H') goto yy61; goto yy4; } else { if (yych <= 'M') goto yy61; if (yych <= 'R') goto yy4; goto yy61; } } } } else { if (yych <= 'g') { if (yych <= 'Y') { if (yych == 'W') goto yy61; if (yych <= 'X') goto yy4; goto yy61; } else { if (yych <= 'd') { if (yych <= 'c') goto yy4; goto yy61; } else { if (yych == 'f') goto yy61; goto yy4; } } } else { if (yych <= 't') { if (yych <= 'l') { if (yych <= 'h') goto yy61; goto yy4; } else { if (yych <= 'm') goto yy61; if (yych <= 'r') goto yy4; goto yy61; } } else { if (yych <= 'w') { if (yych <= 'v') goto yy4; goto yy61; } else { if (yych == 'y') goto yy61; goto yy4; } } } } yy440: YYDEBUG(440, *YYCURSOR); ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; YYDEBUG(441, *YYCURSOR); if (yybm[0+yych] & 4) { goto yy58; } if (yych <= ',') { if (yych == '+') goto yy440; goto yy57; } else { if (yych <= '-') goto yy440; if (yych <= '/') goto yy57; if (yych <= '9') goto yy55; goto yy57; } yy442: YYDEBUG(442, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'V') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy4; goto yy61; } else { if (yych <= '/') goto yy4; if (yych <= '9') goto yy456; if (yych <= 'C') goto yy4; goto yy61; } } else { if (yych <= 'H') { if (yych == 'F') goto yy61; if (yych <= 'G') goto yy4; goto yy61; } else { if (yych <= 'M') { if (yych <= 'L') goto yy4; goto yy61; } else { if (yych <= 'R') goto yy4; if (yych <= 'T') goto yy61; goto yy4; } } } } else { if (yych <= 'h') { if (yych <= 'c') { if (yych == 'X') goto yy4; if (yych <= 'Y') goto yy61; goto yy4; } else { if (yych <= 'e') { if (yych <= 'd') goto yy61; goto yy4; } else { if (yych == 'g') goto yy4; goto yy61; } } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych <= 'r') goto yy4; goto yy61; } else { if (yych <= 'w') { if (yych <= 'v') goto yy4; goto yy61; } else { if (yych == 'y') goto yy61; goto yy4; } } } } yy443: YYDEBUG(443, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'V') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy4; goto yy61; } else { if (yych <= '/') goto yy4; if (yych <= '9') goto yy444; if (yych <= 'C') goto yy4; goto yy61; } } else { if (yych <= 'H') { if (yych == 'F') goto yy61; if (yych <= 'G') goto yy4; goto yy61; } else { if (yych <= 'M') { if (yych <= 'L') goto yy4; goto yy61; } else { if (yych <= 'R') goto yy4; if (yych <= 'T') goto yy61; goto yy4; } } } } else { if (yych <= 'h') { if (yych <= 'c') { if (yych == 'X') goto yy4; if (yych <= 'Y') goto yy61; goto yy4; } else { if (yych <= 'e') { if (yych <= 'd') goto yy61; goto yy4; } else { if (yych == 'g') goto yy4; goto yy61; } } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych <= 'r') goto yy4; goto yy61; } else { if (yych <= 'w') { if (yych <= 'v') goto yy4; goto yy61; } else { if (yych == 'y') goto yy61; goto yy4; } } } } yy444: YYDEBUG(444, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych >= ':') goto yy61; yy445: YYDEBUG(445, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 2) { goto yy55; } if (yych != '-') goto yy61; yy446: YYDEBUG(446, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '0') goto yy447; if (yych <= '1') goto yy448; goto yy57; yy447: YYDEBUG(447, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy449; goto yy57; yy448: YYDEBUG(448, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= '3') goto yy57; yy449: YYDEBUG(449, *YYCURSOR); yych = *++YYCURSOR; if (yych != '-') goto yy57; YYDEBUG(450, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '0') goto yy451; if (yych <= '2') goto yy452; if (yych <= '3') goto yy453; goto yy57; yy451: YYDEBUG(451, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy454; goto yy57; yy452: YYDEBUG(452, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy454; goto yy57; yy453: YYDEBUG(453, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= '2') goto yy57; yy454: YYDEBUG(454, *YYCURSOR); ++YYCURSOR; yy455: YYDEBUG(455, *YYCURSOR); #line 1289 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("iso8601date4 | iso8601date2 | iso8601dateslash | dateslash"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->y = timelib_get_unsigned_nr((char **) &ptr, 4); s->time->m = timelib_get_nr((char **) &ptr, 2); s->time->d = timelib_get_nr((char **) &ptr, 2); TIMELIB_DEINIT; return TIMELIB_ISO_DATE; } #line 9078 "ext/date/lib/parse_date.c" yy456: YYDEBUG(456, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'V') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy4; goto yy61; } else { if (yych <= '/') goto yy4; if (yych <= '9') goto yy445; if (yych <= 'C') goto yy4; goto yy61; } } else { if (yych <= 'H') { if (yych == 'F') goto yy61; if (yych <= 'G') goto yy4; goto yy61; } else { if (yych <= 'M') { if (yych <= 'L') goto yy4; goto yy61; } else { if (yych <= 'R') goto yy4; if (yych <= 'T') goto yy61; goto yy4; } } } } else { if (yych <= 'h') { if (yych <= 'c') { if (yych == 'X') goto yy4; if (yych <= 'Y') goto yy61; goto yy4; } else { if (yych <= 'e') { if (yych <= 'd') goto yy61; goto yy4; } else { if (yych == 'g') goto yy4; goto yy61; } } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych <= 'r') goto yy4; goto yy61; } else { if (yych <= 'w') { if (yych <= 'v') goto yy4; goto yy61; } else { if (yych == 'y') goto yy61; goto yy4; } } } } yy457: YYDEBUG(457, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych <= 'C') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy4; goto yy61; } else { if (yych <= '5') { if (yych <= '/') goto yy4; } else { if (yych <= '9') goto yy456; if (yych <= ':') goto yy163; goto yy4; } } } else { if (yych <= 'G') { if (yych == 'E') goto yy4; if (yych <= 'F') goto yy61; goto yy4; } else { if (yych <= 'L') { if (yych <= 'H') goto yy61; goto yy4; } else { if (yych <= 'M') goto yy61; if (yych <= 'R') goto yy4; goto yy61; } } } } else { if (yych <= 'g') { if (yych <= 'Y') { if (yych == 'W') goto yy61; if (yych <= 'X') goto yy4; goto yy61; } else { if (yych <= 'd') { if (yych <= 'c') goto yy4; goto yy61; } else { if (yych == 'f') goto yy61; goto yy4; } } } else { if (yych <= 't') { if (yych <= 'l') { if (yych <= 'h') goto yy61; goto yy4; } else { if (yych <= 'm') goto yy61; if (yych <= 'r') goto yy4; goto yy61; } } else { if (yych <= 'w') { if (yych <= 'v') goto yy4; goto yy61; } else { if (yych == 'y') goto yy61; goto yy4; } } } } YYDEBUG(458, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'V') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy4; goto yy61; } else { if (yych <= '/') goto yy4; if (yych <= '9') goto yy459; if (yych <= 'C') goto yy4; goto yy61; } } else { if (yych <= 'H') { if (yych == 'F') goto yy61; if (yych <= 'G') goto yy4; goto yy61; } else { if (yych <= 'M') { if (yych <= 'L') goto yy4; goto yy61; } else { if (yych <= 'R') goto yy4; if (yych <= 'T') goto yy61; goto yy4; } } } } else { if (yych <= 'h') { if (yych <= 'c') { if (yych == 'X') goto yy4; if (yych <= 'Y') goto yy61; goto yy4; } else { if (yych <= 'e') { if (yych <= 'd') goto yy61; goto yy4; } else { if (yych == 'g') goto yy4; goto yy61; } } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych <= 'r') goto yy4; goto yy61; } else { if (yych <= 'w') { if (yych <= 'v') goto yy4; goto yy61; } else { if (yych == 'y') goto yy61; goto yy4; } } } } yy459: YYDEBUG(459, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 2) { goto yy55; } if (yych <= 'V') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy4; goto yy61; } else { if (yych == '-') goto yy446; if (yych <= 'C') goto yy4; goto yy61; } } else { if (yych <= 'H') { if (yych == 'F') goto yy61; if (yych <= 'G') goto yy4; goto yy61; } else { if (yych <= 'M') { if (yych <= 'L') goto yy4; goto yy61; } else { if (yych <= 'R') goto yy4; if (yych <= 'T') goto yy61; goto yy4; } } } } else { if (yych <= 'h') { if (yych <= 'c') { if (yych == 'X') goto yy4; if (yych <= 'Y') goto yy61; goto yy4; } else { if (yych <= 'e') { if (yych <= 'd') goto yy61; goto yy4; } else { if (yych == 'g') goto yy4; goto yy61; } } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych <= 'r') goto yy4; goto yy61; } else { if (yych <= 'w') { if (yych <= 'v') goto yy4; goto yy61; } else { if (yych == 'y') goto yy61; goto yy4; } } } } yy460: YYDEBUG(460, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy462; if (yych <= '0') goto yy736; if (yych <= '1') goto yy737; if (yych <= '9') goto yy738; goto yy462; yy461: YYDEBUG(461, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 13) YYFILL(13); yych = *YYCURSOR; yy462: YYDEBUG(462, *YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case '\t': case ' ': goto yy461; case '-': case '.': goto yy577; case 'A': case 'a': goto yy480; case 'D': case 'd': goto yy466; case 'F': case 'f': goto yy467; case 'H': case 'h': goto yy64; case 'I': goto yy475; case 'J': case 'j': goto yy479; case 'M': case 'm': goto yy465; case 'N': case 'n': goto yy482; case 'O': case 'o': goto yy481; case 'P': case 'p': goto yy484; case 'S': case 's': goto yy463; case 'T': case 't': goto yy69; case 'V': goto yy477; case 'W': case 'w': goto yy68; case 'X': goto yy478; case 'Y': case 'y': goto yy67; default: goto yy57; } yy463: YYDEBUG(463, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= 'D') { if (yych == 'A') goto yy127; goto yy57; } else { if (yych <= 'E') goto yy1049; if (yych <= 'T') goto yy57; goto yy126; } } else { if (yych <= 'd') { if (yych == 'a') goto yy127; goto yy57; } else { if (yych <= 'e') goto yy1049; if (yych == 'u') goto yy126; goto yy57; } } yy464: YYDEBUG(464, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '`') { if (yych <= 'D') { if (yych == 'A') goto yy127; goto yy57; } else { if (yych <= 'E') goto yy1049; if (yych == 'U') goto yy126; goto yy57; } } else { if (yych <= 'e') { if (yych <= 'a') goto yy127; if (yych <= 'd') goto yy57; goto yy1049; } else { if (yych <= 's') goto yy57; if (yych <= 't') goto yy729; if (yych <= 'u') goto yy126; goto yy57; } } yy465: YYDEBUG(465, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= 'H') { if (yych == 'A') goto yy592; goto yy57; } else { if (yych <= 'I') goto yy118; if (yych <= 'N') goto yy57; goto yy117; } } else { if (yych <= 'h') { if (yych == 'a') goto yy592; goto yy57; } else { if (yych <= 'i') goto yy118; if (yych == 'o') goto yy117; goto yy57; } } yy466: YYDEBUG(466, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych == 'A') goto yy114; if (yych <= 'D') goto yy57; goto yy579; } else { if (yych <= 'a') { if (yych <= '`') goto yy57; goto yy114; } else { if (yych == 'e') goto yy579; goto yy57; } } yy467: YYDEBUG(467, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= 'N') { if (yych == 'E') goto yy595; goto yy57; } else { if (yych <= 'O') goto yy99; if (yych <= 'Q') goto yy57; goto yy98; } } else { if (yych <= 'n') { if (yych == 'e') goto yy595; goto yy57; } else { if (yych <= 'o') goto yy99; if (yych == 'r') goto yy98; goto yy57; } } yy468: YYDEBUG(468, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'H') goto yy70; if (yych <= 'T') goto yy57; goto yy71; } else { if (yych <= 'h') { if (yych <= 'g') goto yy57; goto yy1048; } else { if (yych == 'u') goto yy71; goto yy57; } } yy469: YYDEBUG(469, *YYCURSOR); yych = *++YYCURSOR; if (yych == '-') goto yy742; if (yych <= '/') goto yy61; if (yych <= '9') goto yy741; goto yy61; yy470: YYDEBUG(470, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'c') { if (yych == 'O') goto yy530; goto yy57; } else { if (yych <= 'd') goto yy729; if (yych == 'o') goto yy530; goto yy57; } yy471: YYDEBUG(471, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'd') goto yy729; goto yy57; yy472: YYDEBUG(472, *YYCURSOR); yych = *++YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case '0': case '1': case '2': goto yy666; case '3': goto yy668; case '4': case '5': case '6': case '7': case '8': case '9': goto yy669; case 'A': case 'a': goto yy673; case 'D': case 'd': goto yy677; case 'F': case 'f': goto yy671; case 'J': case 'j': goto yy670; case 'M': case 'm': goto yy672; case 'N': case 'n': goto yy676; case 'O': case 'o': goto yy675; case 'S': case 's': goto yy674; default: goto yy57; } yy473: YYDEBUG(473, *YYCURSOR); yych = *++YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case '0': goto yy616; case '1': goto yy617; case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy618; case 'A': case 'a': goto yy622; case 'D': case 'd': goto yy626; case 'F': case 'f': goto yy620; case 'J': case 'j': goto yy619; case 'M': case 'm': goto yy621; case 'N': case 'n': goto yy625; case 'O': case 'o': goto yy624; case 'S': case 's': goto yy623; default: goto yy578; } yy474: YYDEBUG(474, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '1') { if (yych <= '/') goto yy578; if (yych <= '0') goto yy568; goto yy569; } else { if (yych <= '5') goto yy570; if (yych <= '9') goto yy571; goto yy578; } yy475: YYDEBUG(475, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; if (yych <= '.') goto yy532; } } else { if (yych <= 'U') { if (yych <= '9') goto yy534; if (yych == 'I') goto yy567; } else { if (yych == 'W') goto yy476; if (yych <= 'X') goto yy540; } } yy476: YYDEBUG(476, *YYCURSOR); #line 1426 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("datenoyearrev"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->d = timelib_get_nr((char **) &ptr, 2); timelib_skip_day_suffix((char **) &ptr); s->time->m = timelib_get_month((char **) &ptr); TIMELIB_DEINIT; return TIMELIB_DATE_TEXT; } #line 9649 "ext/date/lib/parse_date.c" yy477: YYDEBUG(477, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= '\t') { if (yych <= 0x08) goto yy476; goto yy532; } else { if (yych == ' ') goto yy532; goto yy476; } } else { if (yych <= '9') { if (yych <= '.') goto yy532; if (yych <= '/') goto yy476; goto yy534; } else { if (yych == 'I') goto yy565; goto yy476; } } yy478: YYDEBUG(478, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= '\t') { if (yych <= 0x08) goto yy476; goto yy532; } else { if (yych == ' ') goto yy532; goto yy476; } } else { if (yych <= '9') { if (yych <= '.') goto yy532; if (yych <= '/') goto yy476; goto yy534; } else { if (yych == 'I') goto yy564; goto yy476; } } yy479: YYDEBUG(479, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'A') goto yy557; if (yych <= 'T') goto yy57; goto yy556; } else { if (yych <= 'a') { if (yych <= '`') goto yy57; goto yy557; } else { if (yych == 'u') goto yy556; goto yy57; } } yy480: YYDEBUG(480, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= 'L') { if (yych == '.') goto yy485; goto yy57; } else { if (yych <= 'M') goto yy486; if (yych == 'P') goto yy550; goto yy57; } } else { if (yych <= 'o') { if (yych <= 'U') goto yy549; if (yych == 'm') goto yy486; goto yy57; } else { if (yych <= 'p') goto yy550; if (yych == 'u') goto yy549; goto yy57; } } yy481: YYDEBUG(481, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy544; if (yych == 'c') goto yy544; goto yy57; yy482: YYDEBUG(482, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy530; if (yych == 'o') goto yy530; goto yy57; yy483: YYDEBUG(483, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy490; if (yych <= '9') goto yy492; goto yy57; yy484: YYDEBUG(484, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych != '.') goto yy57; } else { if (yych <= 'M') goto yy486; if (yych == 'm') goto yy486; goto yy57; } yy485: YYDEBUG(485, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy486; if (yych != 'm') goto yy57; yy486: YYDEBUG(486, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 0x1F) { if (yych <= 0x00) goto yy488; if (yych == '\t') goto yy488; goto yy57; } else { if (yych <= ' ') goto yy488; if (yych != '.') goto yy57; } YYDEBUG(487, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '\t') { if (yych <= 0x00) goto yy488; if (yych <= 0x08) goto yy57; } else { if (yych != ' ') goto yy57; } yy488: YYDEBUG(488, *YYCURSOR); ++YYCURSOR; YYDEBUG(489, *YYCURSOR); #line 1144 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("timetiny12 | timeshort12 | timelong12"); TIMELIB_INIT; TIMELIB_HAVE_TIME(); s->time->h = timelib_get_nr((char **) &ptr, 2); if (*ptr == ':' || *ptr == '.') { s->time->i = timelib_get_nr((char **) &ptr, 2); if (*ptr == ':' || *ptr == '.') { s->time->s = timelib_get_nr((char **) &ptr, 2); } } s->time->h += timelib_meridian((char **) &ptr, s->time->h); TIMELIB_DEINIT; return TIMELIB_TIME12; } #line 9806 "ext/date/lib/parse_date.c" yy490: YYDEBUG(490, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy493; } else { if (yych <= '9') goto yy507; if (yych <= ':') goto yy493; } yy491: YYDEBUG(491, *YYCURSOR); #line 1181 "ext/date/lib/parse_date.re" { int tz_not_found; DEBUG_OUTPUT("timeshort24 | timelong24 | iso8601long"); TIMELIB_INIT; TIMELIB_HAVE_TIME(); s->time->h = timelib_get_nr((char **) &ptr, 2); s->time->i = timelib_get_nr((char **) &ptr, 2); if (*ptr == ':' || *ptr == '.') { s->time->s = timelib_get_nr((char **) &ptr, 2); if (*ptr == '.') { s->time->f = timelib_get_frac_nr((char **) &ptr, 8); } } if (*ptr != '\0') { s->time->z = timelib_get_zone((char **) &ptr, &s->time->dst, s->time, &tz_not_found, s->tzdb); if (tz_not_found) { add_error(s, "The timezone could not be found in the database"); } } TIMELIB_DEINIT; return TIMELIB_TIME24_WITH_ZONE; } #line 9844 "ext/date/lib/parse_date.c" yy492: YYDEBUG(492, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy493; if (yych != ':') goto yy491; yy493: YYDEBUG(493, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy494; if (yych <= '6') goto yy495; if (yych <= '9') goto yy496; goto yy57; yy494: YYDEBUG(494, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy497; if (yych <= '/') goto yy491; if (yych <= '9') goto yy500; goto yy491; yy495: YYDEBUG(495, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy497; if (yych == '0') goto yy500; goto yy491; yy496: YYDEBUG(496, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych != '.') goto yy491; yy497: YYDEBUG(497, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; yy498: YYDEBUG(498, *YYCURSOR); ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; YYDEBUG(499, *YYCURSOR); if (yych <= '/') goto yy491; if (yych <= '9') goto yy498; goto yy491; yy500: YYDEBUG(500, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych <= 0x1F) { if (yych != '\t') goto yy491; } else { if (yych <= ' ') goto yy501; if (yych == '.') goto yy497; goto yy491; } } else { if (yych <= '`') { if (yych <= 'A') goto yy503; if (yych == 'P') goto yy503; goto yy491; } else { if (yych <= 'a') goto yy503; if (yych == 'p') goto yy503; goto yy491; } } yy501: YYDEBUG(501, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 5) YYFILL(5); yych = *YYCURSOR; YYDEBUG(502, *YYCURSOR); if (yych <= 'A') { if (yych <= 0x1F) { if (yych == '\t') goto yy501; goto yy57; } else { if (yych <= ' ') goto yy501; if (yych <= '@') goto yy57; } } else { if (yych <= '`') { if (yych != 'P') goto yy57; } else { if (yych <= 'a') goto yy503; if (yych != 'p') goto yy57; } } yy503: YYDEBUG(503, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych != '.') goto yy57; } else { if (yych <= 'M') goto yy505; if (yych == 'm') goto yy505; goto yy57; } YYDEBUG(504, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy505; if (yych != 'm') goto yy57; yy505: YYDEBUG(505, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 0x1F) { if (yych <= 0x00) goto yy488; if (yych == '\t') goto yy488; goto yy57; } else { if (yych <= ' ') goto yy488; if (yych != '.') goto yy57; } YYDEBUG(506, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '\t') { if (yych <= 0x00) goto yy488; if (yych <= 0x08) goto yy57; goto yy488; } else { if (yych == ' ') goto yy488; goto yy57; } yy507: YYDEBUG(507, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ':') { if (yych <= ' ') { if (yych == '\t') goto yy508; if (yych <= 0x1F) goto yy491; } else { if (yych == '.') goto yy493; if (yych <= '9') goto yy491; goto yy511; } } else { if (yych <= 'P') { if (yych == 'A') goto yy510; if (yych <= 'O') goto yy491; goto yy510; } else { if (yych <= 'a') { if (yych <= '`') goto yy491; goto yy510; } else { if (yych == 'p') goto yy510; goto yy491; } } } yy508: YYDEBUG(508, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 5) YYFILL(5); yych = *YYCURSOR; YYDEBUG(509, *YYCURSOR); if (yych <= 'A') { if (yych <= 0x1F) { if (yych == '\t') goto yy508; goto yy57; } else { if (yych <= ' ') goto yy508; if (yych <= '@') goto yy57; } } else { if (yych <= '`') { if (yych != 'P') goto yy57; } else { if (yych <= 'a') goto yy510; if (yych != 'p') goto yy57; } } yy510: YYDEBUG(510, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych == '.') goto yy527; goto yy57; } else { if (yych <= 'M') goto yy528; if (yych == 'm') goto yy528; goto yy57; } yy511: YYDEBUG(511, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy512; if (yych <= '6') goto yy513; if (yych <= '9') goto yy496; goto yy57; yy512: YYDEBUG(512, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy497; if (yych <= '/') goto yy491; if (yych <= '9') goto yy514; goto yy491; yy513: YYDEBUG(513, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy497; if (yych != '0') goto yy491; yy514: YYDEBUG(514, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ':') { if (yych <= ' ') { if (yych == '\t') goto yy501; if (yych <= 0x1F) goto yy491; goto yy501; } else { if (yych == '.') goto yy515; if (yych <= '9') goto yy491; goto yy516; } } else { if (yych <= 'P') { if (yych == 'A') goto yy503; if (yych <= 'O') goto yy491; goto yy503; } else { if (yych <= 'a') { if (yych <= '`') goto yy491; goto yy503; } else { if (yych == 'p') goto yy503; goto yy491; } } } yy515: YYDEBUG(515, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy525; goto yy57; yy516: YYDEBUG(516, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; yy517: YYDEBUG(517, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 5) YYFILL(5); yych = *YYCURSOR; YYDEBUG(518, *YYCURSOR); if (yych <= 'O') { if (yych <= '9') { if (yych <= '/') goto yy57; goto yy517; } else { if (yych != 'A') goto yy57; } } else { if (yych <= 'a') { if (yych <= 'P') goto yy519; if (yych <= '`') goto yy57; } else { if (yych != 'p') goto yy57; } } yy519: YYDEBUG(519, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych != '.') goto yy57; } else { if (yych <= 'M') goto yy521; if (yych == 'm') goto yy521; goto yy57; } YYDEBUG(520, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy521; if (yych != 'm') goto yy57; yy521: YYDEBUG(521, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 0x1F) { if (yych <= 0x00) goto yy523; if (yych == '\t') goto yy523; goto yy57; } else { if (yych <= ' ') goto yy523; if (yych != '.') goto yy57; } YYDEBUG(522, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '\t') { if (yych <= 0x00) goto yy523; if (yych <= 0x08) goto yy57; } else { if (yych != ' ') goto yy57; } yy523: YYDEBUG(523, *YYCURSOR); ++YYCURSOR; YYDEBUG(524, *YYCURSOR); #line 1161 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("mssqltime"); TIMELIB_INIT; TIMELIB_HAVE_TIME(); s->time->h = timelib_get_nr((char **) &ptr, 2); s->time->i = timelib_get_nr((char **) &ptr, 2); if (*ptr == ':' || *ptr == '.') { s->time->s = timelib_get_nr((char **) &ptr, 2); if (*ptr == ':' || *ptr == '.') { s->time->f = timelib_get_frac_nr((char **) &ptr, 8); } } timelib_eat_spaces((char **) &ptr); s->time->h += timelib_meridian((char **) &ptr, s->time->h); TIMELIB_DEINIT; return TIMELIB_TIME24_WITH_ZONE; } #line 10173 "ext/date/lib/parse_date.c" yy525: YYDEBUG(525, *YYCURSOR); yyaccept = 11; YYMARKER = ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 5) YYFILL(5); yych = *YYCURSOR; YYDEBUG(526, *YYCURSOR); if (yych <= 'O') { if (yych <= '9') { if (yych <= '/') goto yy491; goto yy525; } else { if (yych == 'A') goto yy519; goto yy491; } } else { if (yych <= 'a') { if (yych <= 'P') goto yy519; if (yych <= '`') goto yy491; goto yy519; } else { if (yych == 'p') goto yy519; goto yy491; } } yy527: YYDEBUG(527, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy528; if (yych != 'm') goto yy57; yy528: YYDEBUG(528, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 0x1F) { if (yych <= 0x00) goto yy488; if (yych == '\t') goto yy488; goto yy57; } else { if (yych <= ' ') goto yy488; if (yych != '.') goto yy57; } YYDEBUG(529, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '\t') { if (yych <= 0x00) goto yy488; if (yych <= 0x08) goto yy57; goto yy488; } else { if (yych == ' ') goto yy488; goto yy57; } yy530: YYDEBUG(530, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'V') goto yy531; if (yych != 'v') goto yy57; yy531: YYDEBUG(531, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych != '\t') goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; } } else { if (yych <= 'D') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'E') goto yy536; if (yych == 'e') goto yy536; goto yy476; } } yy532: YYDEBUG(532, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4); yych = *YYCURSOR; yy533: YYDEBUG(533, *YYCURSOR); if (yych <= ' ') { if (yych == '\t') goto yy532; if (yych <= 0x1F) goto yy57; goto yy532; } else { if (yych <= '.') { if (yych <= ',') goto yy57; goto yy532; } else { if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; } } yy534: YYDEBUG(534, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '/') goto yy535; if (yych <= '9') goto yy541; yy535: YYDEBUG(535, *YYCURSOR); #line 1343 "ext/date/lib/parse_date.re" { int length = 0; DEBUG_OUTPUT("datefull"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->d = timelib_get_nr((char **) &ptr, 2); timelib_skip_day_suffix((char **) &ptr); s->time->m = timelib_get_month((char **) &ptr); s->time->y = timelib_get_nr_ex((char **) &ptr, 4, &length); TIMELIB_PROCESS_YEAR(s->time->y, length); TIMELIB_DEINIT; return TIMELIB_DATE_FULL; } #line 10293 "ext/date/lib/parse_date.c" yy536: YYDEBUG(536, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy537; if (yych != 'm') goto yy57; yy537: YYDEBUG(537, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy538; if (yych != 'b') goto yy57; yy538: YYDEBUG(538, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy539; if (yych != 'e') goto yy57; yy539: YYDEBUG(539, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy540; if (yych != 'r') goto yy57; yy540: YYDEBUG(540, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ' ') { if (yych == '\t') goto yy532; if (yych <= 0x1F) goto yy476; goto yy532; } else { if (yych <= '.') { if (yych <= ',') goto yy476; goto yy532; } else { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } } yy541: YYDEBUG(541, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy535; if (yych >= ':') goto yy535; yy542: YYDEBUG(542, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy535; if (yych >= ':') goto yy535; YYDEBUG(543, *YYCURSOR); yych = *++YYCURSOR; goto yy535; yy544: YYDEBUG(544, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy545; if (yych != 't') goto yy57; yy545: YYDEBUG(545, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; goto yy532; } } else { if (yych <= 'N') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'O') goto yy546; if (yych != 'o') goto yy476; } } yy546: YYDEBUG(546, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy547; if (yych != 'b') goto yy57; yy547: YYDEBUG(547, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy548; if (yych != 'e') goto yy57; yy548: YYDEBUG(548, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy540; if (yych == 'r') goto yy540; goto yy57; yy549: YYDEBUG(549, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy553; if (yych == 'g') goto yy553; goto yy57; yy550: YYDEBUG(550, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy551; if (yych != 'r') goto yy57; yy551: YYDEBUG(551, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; goto yy532; } } else { if (yych <= 'H') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'I') goto yy552; if (yych != 'i') goto yy476; } } yy552: YYDEBUG(552, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy540; if (yych == 'l') goto yy540; goto yy57; yy553: YYDEBUG(553, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; goto yy532; } } else { if (yych <= 'T') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'U') goto yy554; if (yych != 'u') goto yy476; } } yy554: YYDEBUG(554, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy555; if (yych != 's') goto yy57; yy555: YYDEBUG(555, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy540; if (yych == 't') goto yy540; goto yy57; yy556: YYDEBUG(556, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych == 'L') goto yy563; if (yych <= 'M') goto yy57; goto yy562; } else { if (yych <= 'l') { if (yych <= 'k') goto yy57; goto yy563; } else { if (yych == 'n') goto yy562; goto yy57; } } yy557: YYDEBUG(557, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy558; if (yych != 'n') goto yy57; yy558: YYDEBUG(558, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; goto yy532; } } else { if (yych <= 'T') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'U') goto yy559; if (yych != 'u') goto yy476; } } yy559: YYDEBUG(559, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy560; if (yych != 'a') goto yy57; yy560: YYDEBUG(560, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy561; if (yych != 'r') goto yy57; yy561: YYDEBUG(561, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy540; if (yych == 'y') goto yy540; goto yy57; yy562: YYDEBUG(562, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; goto yy532; } } else { if (yych <= 'D') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'E') goto yy540; if (yych == 'e') goto yy540; goto yy476; } } yy563: YYDEBUG(563, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; goto yy532; } } else { if (yych <= 'X') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'Y') goto yy540; if (yych == 'y') goto yy540; goto yy476; } } yy564: YYDEBUG(564, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= '\t') { if (yych <= 0x08) goto yy476; goto yy532; } else { if (yych == ' ') goto yy532; goto yy476; } } else { if (yych <= '9') { if (yych <= '.') goto yy532; if (yych <= '/') goto yy476; goto yy534; } else { if (yych == 'I') goto yy540; goto yy476; } } yy565: YYDEBUG(565, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= '\t') { if (yych <= 0x08) goto yy476; goto yy532; } else { if (yych == ' ') goto yy532; goto yy476; } } else { if (yych <= '9') { if (yych <= '.') goto yy532; if (yych <= '/') goto yy476; goto yy534; } else { if (yych != 'I') goto yy476; } } YYDEBUG(566, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= '\t') { if (yych <= 0x08) goto yy476; goto yy532; } else { if (yych == ' ') goto yy532; goto yy476; } } else { if (yych <= '9') { if (yych <= '.') goto yy532; if (yych <= '/') goto yy476; goto yy534; } else { if (yych == 'I') goto yy540; goto yy476; } } yy567: YYDEBUG(567, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= '\t') { if (yych <= 0x08) goto yy476; goto yy532; } else { if (yych == ' ') goto yy532; goto yy476; } } else { if (yych <= '9') { if (yych <= '.') goto yy532; if (yych <= '/') goto yy476; goto yy534; } else { if (yych == 'I') goto yy540; goto yy476; } } yy568: YYDEBUG(568, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ',') goto yy491; if (yych <= '-') goto yy602; goto yy601; } else { if (yych <= '/') goto yy491; if (yych <= '9') goto yy615; if (yych <= ':') goto yy493; goto yy491; } yy569: YYDEBUG(569, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') goto yy491; if (yych <= '-') goto yy602; if (yych <= '.') goto yy601; goto yy491; } else { if (yych <= '2') goto yy615; if (yych <= '9') goto yy614; if (yych <= ':') goto yy493; goto yy491; } yy570: YYDEBUG(570, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ',') goto yy491; if (yych <= '-') goto yy602; goto yy601; } else { if (yych <= '/') goto yy491; if (yych <= '9') goto yy614; if (yych <= ':') goto yy493; goto yy491; } yy571: YYDEBUG(571, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ',') goto yy491; if (yych <= '-') goto yy602; goto yy601; } else { if (yych == ':') goto yy493; goto yy491; } yy572: YYDEBUG(572, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy595; if (yych == 'e') goto yy595; goto yy57; yy573: YYDEBUG(573, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy592; if (yych == 'a') goto yy592; goto yy57; yy574: YYDEBUG(574, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'P') goto yy550; if (yych <= 'T') goto yy57; goto yy549; } else { if (yych <= 'p') { if (yych <= 'o') goto yy57; goto yy550; } else { if (yych == 'u') goto yy549; goto yy57; } } yy575: YYDEBUG(575, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy585; if (yych == 'e') goto yy585; goto yy57; yy576: YYDEBUG(576, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy579; if (yych == 'e') goto yy579; goto yy57; yy577: YYDEBUG(577, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 13) YYFILL(13); yych = *YYCURSOR; yy578: YYDEBUG(578, *YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case '\t': case ' ': case '-': case '.': goto yy577; case 'A': case 'a': goto yy574; case 'D': case 'd': goto yy576; case 'F': case 'f': goto yy572; case 'I': goto yy475; case 'J': case 'j': goto yy479; case 'M': case 'm': goto yy573; case 'N': case 'n': goto yy482; case 'O': case 'o': goto yy481; case 'S': case 's': goto yy575; case 'V': goto yy477; case 'X': goto yy478; default: goto yy57; } yy579: YYDEBUG(579, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy580; if (yych != 'c') goto yy57; yy580: YYDEBUG(580, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; goto yy532; } } else { if (yych <= 'D') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'E') goto yy581; if (yych != 'e') goto yy476; } } yy581: YYDEBUG(581, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy582; if (yych != 'm') goto yy57; yy582: YYDEBUG(582, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy583; if (yych != 'b') goto yy57; yy583: YYDEBUG(583, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy584; if (yych != 'e') goto yy57; yy584: YYDEBUG(584, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy540; if (yych == 'r') goto yy540; goto yy57; yy585: YYDEBUG(585, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy586; if (yych != 'p') goto yy57; yy586: YYDEBUG(586, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; goto yy532; } } else { if (yych <= 'S') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'T') goto yy587; if (yych != 't') goto yy476; } } yy587: YYDEBUG(587, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; goto yy532; } } else { if (yych <= 'D') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'E') goto yy588; if (yych != 'e') goto yy476; } } yy588: YYDEBUG(588, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy589; if (yych != 'm') goto yy57; yy589: YYDEBUG(589, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy590; if (yych != 'b') goto yy57; yy590: YYDEBUG(590, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy591; if (yych != 'e') goto yy57; yy591: YYDEBUG(591, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy540; if (yych == 'r') goto yy540; goto yy57; yy592: YYDEBUG(592, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych == 'R') goto yy593; if (yych <= 'X') goto yy57; goto yy540; } else { if (yych <= 'r') { if (yych <= 'q') goto yy57; } else { if (yych == 'y') goto yy540; goto yy57; } } yy593: YYDEBUG(593, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; goto yy532; } } else { if (yych <= 'B') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'C') goto yy594; if (yych != 'c') goto yy476; } } yy594: YYDEBUG(594, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy540; if (yych == 'h') goto yy540; goto yy57; yy595: YYDEBUG(595, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy596; if (yych != 'b') goto yy57; yy596: YYDEBUG(596, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; goto yy532; } } else { if (yych <= 'Q') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'R') goto yy597; if (yych != 'r') goto yy476; } } yy597: YYDEBUG(597, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy598; if (yych != 'u') goto yy57; yy598: YYDEBUG(598, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy599; if (yych != 'a') goto yy57; yy599: YYDEBUG(599, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy600; if (yych != 'r') goto yy57; yy600: YYDEBUG(600, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy540; if (yych == 'y') goto yy540; goto yy57; yy601: YYDEBUG(601, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy608; if (yych <= '6') goto yy609; if (yych <= '9') goto yy610; goto yy57; yy602: YYDEBUG(602, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; YYDEBUG(603, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; yy604: YYDEBUG(604, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; yy605: YYDEBUG(605, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; YYDEBUG(606, *YYCURSOR); ++YYCURSOR; YYDEBUG(607, *YYCURSOR); #line 1358 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("pointed date YYYY"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->d = timelib_get_nr((char **) &ptr, 2); s->time->m = timelib_get_nr((char **) &ptr, 2); s->time->y = timelib_get_nr((char **) &ptr, 4); TIMELIB_DEINIT; return TIMELIB_DATE_FULL_POINTED; } #line 11041 "ext/date/lib/parse_date.c" yy608: YYDEBUG(608, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy497; if (yych <= '/') goto yy491; if (yych <= '9') goto yy613; goto yy491; yy609: YYDEBUG(609, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy497; goto yy491; } else { if (yych <= '0') goto yy613; if (yych <= '9') goto yy611; goto yy491; } yy610: YYDEBUG(610, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy497; if (yych <= '/') goto yy491; if (yych >= ':') goto yy491; yy611: YYDEBUG(611, *YYCURSOR); yyaccept = 12; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') goto yy612; if (yych <= '9') goto yy605; yy612: YYDEBUG(612, *YYCURSOR); #line 1370 "ext/date/lib/parse_date.re" { int length = 0; DEBUG_OUTPUT("pointed date YY"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->d = timelib_get_nr((char **) &ptr, 2); s->time->m = timelib_get_nr((char **) &ptr, 2); s->time->y = timelib_get_nr_ex((char **) &ptr, 2, &length); TIMELIB_PROCESS_YEAR(s->time->y, length); TIMELIB_DEINIT; return TIMELIB_DATE_FULL_POINTED; } #line 11090 "ext/date/lib/parse_date.c" yy613: YYDEBUG(613, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= ' ') { if (yych == '\t') goto yy501; if (yych <= 0x1F) goto yy491; goto yy501; } else { if (yych == '.') goto yy497; if (yych <= '/') goto yy491; goto yy605; } } else { if (yych <= 'P') { if (yych == 'A') goto yy503; if (yych <= 'O') goto yy491; goto yy503; } else { if (yych <= 'a') { if (yych <= '`') goto yy491; goto yy503; } else { if (yych == 'p') goto yy503; goto yy491; } } } yy614: YYDEBUG(614, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ':') { if (yych <= ' ') { if (yych == '\t') goto yy508; if (yych <= 0x1F) goto yy491; goto yy508; } else { if (yych == '.') goto yy493; if (yych <= '9') goto yy491; goto yy493; } } else { if (yych <= 'P') { if (yych == 'A') goto yy510; if (yych <= 'O') goto yy491; goto yy510; } else { if (yych <= 'a') { if (yych <= '`') goto yy491; goto yy510; } else { if (yych == 'p') goto yy510; goto yy491; } } } yy615: YYDEBUG(615, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ':') { if (yych <= ' ') { if (yych == '\t') goto yy508; if (yych <= 0x1F) goto yy491; goto yy508; } else { if (yych <= '-') { if (yych <= ',') goto yy491; goto yy602; } else { if (yych <= '.') goto yy601; if (yych <= '9') goto yy491; goto yy493; } } } else { if (yych <= 'P') { if (yych == 'A') goto yy510; if (yych <= 'O') goto yy491; goto yy510; } else { if (yych <= 'a') { if (yych <= '`') goto yy491; goto yy510; } else { if (yych == 'p') goto yy510; goto yy491; } } } yy616: YYDEBUG(616, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '.') { if (yych <= ',') goto yy57; if (yych <= '-') goto yy655; goto yy602; } else { if (yych <= '/') goto yy57; if (yych <= '9') goto yy618; goto yy57; } yy617: YYDEBUG(617, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '.') { if (yych <= ',') goto yy57; if (yych <= '-') goto yy655; goto yy602; } else { if (yych <= '/') goto yy57; if (yych >= '3') goto yy57; } yy618: YYDEBUG(618, *YYCURSOR); yych = *++YYCURSOR; if (yych <= ',') goto yy57; if (yych <= '-') goto yy655; if (yych <= '.') goto yy602; goto yy57; yy619: YYDEBUG(619, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'A') goto yy651; if (yych <= 'T') goto yy57; goto yy650; } else { if (yych <= 'a') { if (yych <= '`') goto yy57; goto yy651; } else { if (yych == 'u') goto yy650; goto yy57; } } yy620: YYDEBUG(620, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy648; if (yych == 'e') goto yy648; goto yy57; yy621: YYDEBUG(621, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy645; if (yych == 'a') goto yy645; goto yy57; yy622: YYDEBUG(622, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'P') goto yy642; if (yych <= 'T') goto yy57; goto yy641; } else { if (yych <= 'p') { if (yych <= 'o') goto yy57; goto yy642; } else { if (yych == 'u') goto yy641; goto yy57; } } yy623: YYDEBUG(623, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy638; if (yych == 'e') goto yy638; goto yy57; yy624: YYDEBUG(624, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy636; if (yych == 'c') goto yy636; goto yy57; yy625: YYDEBUG(625, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy634; if (yych == 'o') goto yy634; goto yy57; yy626: YYDEBUG(626, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy627; if (yych != 'e') goto yy57; yy627: YYDEBUG(627, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy628; if (yych != 'c') goto yy57; yy628: YYDEBUG(628, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; if (yych >= '.') goto yy532; } } else { if (yych <= 'D') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'E') goto yy581; if (yych == 'e') goto yy581; goto yy476; } } yy629: YYDEBUG(629, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy533; if (yych <= '0') goto yy630; if (yych <= '2') goto yy631; if (yych <= '3') goto yy632; goto yy533; yy630: YYDEBUG(630, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy535; if (yych <= '9') goto yy633; goto yy535; yy631: YYDEBUG(631, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy535; if (yych <= '9') goto yy633; goto yy535; yy632: YYDEBUG(632, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy535; if (yych <= '1') goto yy633; if (yych <= '9') goto yy541; goto yy535; yy633: YYDEBUG(633, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy535; if (yych <= '9') goto yy542; goto yy535; yy634: YYDEBUG(634, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'V') goto yy635; if (yych != 'v') goto yy57; yy635: YYDEBUG(635, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; if (yych <= '-') goto yy629; goto yy532; } } else { if (yych <= 'D') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'E') goto yy536; if (yych == 'e') goto yy536; goto yy476; } } yy636: YYDEBUG(636, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy637; if (yych != 't') goto yy57; yy637: YYDEBUG(637, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; if (yych <= '-') goto yy629; goto yy532; } } else { if (yych <= 'N') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'O') goto yy546; if (yych == 'o') goto yy546; goto yy476; } } yy638: YYDEBUG(638, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy639; if (yych != 'p') goto yy57; yy639: YYDEBUG(639, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; if (yych <= '-') goto yy629; goto yy532; } } else { if (yych <= 'S') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'T') goto yy640; if (yych != 't') goto yy476; } } yy640: YYDEBUG(640, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; if (yych <= '-') goto yy629; goto yy532; } } else { if (yych <= 'D') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'E') goto yy588; if (yych == 'e') goto yy588; goto yy476; } } yy641: YYDEBUG(641, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy644; if (yych == 'g') goto yy644; goto yy57; yy642: YYDEBUG(642, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy643; if (yych != 'r') goto yy57; yy643: YYDEBUG(643, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; if (yych <= '-') goto yy629; goto yy532; } } else { if (yych <= 'H') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'I') goto yy552; if (yych == 'i') goto yy552; goto yy476; } } yy644: YYDEBUG(644, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; if (yych <= '-') goto yy629; goto yy532; } } else { if (yych <= 'T') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'U') goto yy554; if (yych == 'u') goto yy554; goto yy476; } } yy645: YYDEBUG(645, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych == 'R') goto yy646; if (yych <= 'X') goto yy57; goto yy647; } else { if (yych <= 'r') { if (yych <= 'q') goto yy57; } else { if (yych == 'y') goto yy647; goto yy57; } } yy646: YYDEBUG(646, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; if (yych <= '-') goto yy629; goto yy532; } } else { if (yych <= 'B') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'C') goto yy594; if (yych == 'c') goto yy594; goto yy476; } } yy647: YYDEBUG(647, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= '\t') { if (yych <= 0x08) goto yy476; goto yy532; } else { if (yych == ' ') goto yy532; goto yy476; } } else { if (yych <= '.') { if (yych <= '-') goto yy629; goto yy532; } else { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } } yy648: YYDEBUG(648, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy649; if (yych != 'b') goto yy57; yy649: YYDEBUG(649, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; if (yych <= '-') goto yy629; goto yy532; } } else { if (yych <= 'Q') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'R') goto yy597; if (yych == 'r') goto yy597; goto yy476; } } yy650: YYDEBUG(650, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych == 'L') goto yy654; if (yych <= 'M') goto yy57; goto yy653; } else { if (yych <= 'l') { if (yych <= 'k') goto yy57; goto yy654; } else { if (yych == 'n') goto yy653; goto yy57; } } yy651: YYDEBUG(651, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy652; if (yych != 'n') goto yy57; yy652: YYDEBUG(652, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; if (yych <= '-') goto yy629; goto yy532; } } else { if (yych <= 'T') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'U') goto yy559; if (yych == 'u') goto yy559; goto yy476; } } yy653: YYDEBUG(653, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; if (yych <= '-') goto yy629; goto yy532; } } else { if (yych <= 'D') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'E') goto yy540; if (yych == 'e') goto yy540; goto yy476; } } yy654: YYDEBUG(654, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; if (yych <= '-') goto yy629; goto yy532; } } else { if (yych <= 'X') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'Y') goto yy540; if (yych == 'y') goto yy540; goto yy476; } } yy655: YYDEBUG(655, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '2') goto yy656; if (yych <= '3') goto yy658; if (yych <= '9') goto yy659; goto yy57; yy656: YYDEBUG(656, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy657; if (yych <= '9') goto yy665; if (yych >= 'n') goto yy661; } else { if (yych <= 'r') { if (yych >= 'r') goto yy662; } else { if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; } } yy657: YYDEBUG(657, *YYCURSOR); #line 1329 "ext/date/lib/parse_date.re" { int length = 0; DEBUG_OUTPUT("gnudateshort"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->y = timelib_get_nr_ex((char **) &ptr, 4, &length); s->time->m = timelib_get_nr((char **) &ptr, 2); s->time->d = timelib_get_nr((char **) &ptr, 2); TIMELIB_PROCESS_YEAR(s->time->y, length); TIMELIB_DEINIT; return TIMELIB_ISO_DATE; } #line 11744 "ext/date/lib/parse_date.c" yy658: YYDEBUG(658, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '1') { if (yych <= '/') goto yy657; goto yy665; } else { if (yych <= '9') goto yy604; if (yych <= 'm') goto yy657; goto yy661; } } else { if (yych <= 'r') { if (yych <= 'q') goto yy657; goto yy662; } else { if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; goto yy657; } } yy659: YYDEBUG(659, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy657; if (yych <= '9') goto yy604; if (yych <= 'm') goto yy657; goto yy661; } else { if (yych <= 'r') { if (yych <= 'q') goto yy657; goto yy662; } else { if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; goto yy657; } } yy660: YYDEBUG(660, *YYCURSOR); yych = *++YYCURSOR; if (yych == 't') goto yy664; goto yy57; yy661: YYDEBUG(661, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'd') goto yy664; goto yy57; yy662: YYDEBUG(662, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'd') goto yy664; goto yy57; yy663: YYDEBUG(663, *YYCURSOR); yych = *++YYCURSOR; if (yych != 'h') goto yy57; yy664: YYDEBUG(664, *YYCURSOR); yych = *++YYCURSOR; goto yy657; yy665: YYDEBUG(665, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy657; if (yych <= '9') goto yy605; if (yych <= 'm') goto yy657; goto yy661; } else { if (yych <= 'r') { if (yych <= 'q') goto yy657; goto yy662; } else { if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; goto yy657; } } yy666: YYDEBUG(666, *YYCURSOR); yyaccept = 14; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') { if (yych >= '/') goto yy723; } else { if (yych <= '9') goto yy669; if (yych >= 'n') goto yy720; } } else { if (yych <= 'r') { if (yych >= 'r') goto yy721; } else { if (yych <= 's') goto yy719; if (yych <= 't') goto yy722; } } yy667: YYDEBUG(667, *YYCURSOR); #line 1273 "ext/date/lib/parse_date.re" { int length = 0; DEBUG_OUTPUT("americanshort | american"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->m = timelib_get_nr((char **) &ptr, 2); s->time->d = timelib_get_nr((char **) &ptr, 2); if (*ptr == '/') { s->time->y = timelib_get_nr_ex((char **) &ptr, 4, &length); TIMELIB_PROCESS_YEAR(s->time->y, length); } TIMELIB_DEINIT; return TIMELIB_AMERICAN; } #line 11865 "ext/date/lib/parse_date.c" yy668: YYDEBUG(668, *YYCURSOR); yyaccept = 14; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') { if (yych <= '.') goto yy667; goto yy723; } else { if (yych <= '1') goto yy669; if (yych <= 'm') goto yy667; goto yy720; } } else { if (yych <= 'r') { if (yych <= 'q') goto yy667; goto yy721; } else { if (yych <= 's') goto yy719; if (yych <= 't') goto yy722; goto yy667; } } yy669: YYDEBUG(669, *YYCURSOR); yyaccept = 14; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych == '/') goto yy723; if (yych <= 'm') goto yy667; goto yy720; } else { if (yych <= 'r') { if (yych <= 'q') goto yy667; goto yy721; } else { if (yych <= 's') goto yy719; if (yych <= 't') goto yy722; goto yy667; } } yy670: YYDEBUG(670, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'A') goto yy718; if (yych <= 'T') goto yy57; goto yy717; } else { if (yych <= 'a') { if (yych <= '`') goto yy57; goto yy718; } else { if (yych == 'u') goto yy717; goto yy57; } } yy671: YYDEBUG(671, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy716; if (yych == 'e') goto yy716; goto yy57; yy672: YYDEBUG(672, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy715; if (yych == 'a') goto yy715; goto yy57; yy673: YYDEBUG(673, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'P') goto yy714; if (yych <= 'T') goto yy57; goto yy713; } else { if (yych <= 'p') { if (yych <= 'o') goto yy57; goto yy714; } else { if (yych == 'u') goto yy713; goto yy57; } } yy674: YYDEBUG(674, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy711; if (yych == 'e') goto yy711; goto yy57; yy675: YYDEBUG(675, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy710; if (yych == 'c') goto yy710; goto yy57; yy676: YYDEBUG(676, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy709; if (yych == 'o') goto yy709; goto yy57; yy677: YYDEBUG(677, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy678; if (yych != 'e') goto yy57; yy678: YYDEBUG(678, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy679; if (yych != 'c') goto yy57; yy679: YYDEBUG(679, *YYCURSOR); yych = *++YYCURSOR; if (yych != '/') goto yy57; yy680: YYDEBUG(680, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; YYDEBUG(681, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; YYDEBUG(682, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; YYDEBUG(683, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; YYDEBUG(684, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy57; YYDEBUG(685, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '1') goto yy686; if (yych <= '2') goto yy687; goto yy57; yy686: YYDEBUG(686, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy688; goto yy57; yy687: YYDEBUG(687, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= '5') goto yy57; yy688: YYDEBUG(688, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy57; YYDEBUG(689, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= '6') goto yy57; YYDEBUG(690, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; YYDEBUG(691, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy57; YYDEBUG(692, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy693; if (yych <= '6') goto yy694; goto yy57; yy693: YYDEBUG(693, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy695; goto yy57; yy694: YYDEBUG(694, *YYCURSOR); yych = *++YYCURSOR; if (yych != '0') goto yy57; yy695: YYDEBUG(695, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\t') goto yy696; if (yych != ' ') goto yy57; yy696: YYDEBUG(696, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 9) YYFILL(9); yych = *YYCURSOR; YYDEBUG(697, *YYCURSOR); if (yych <= '*') { if (yych <= '\t') { if (yych <= 0x08) goto yy57; goto yy696; } else { if (yych == ' ') goto yy696; goto yy57; } } else { if (yych <= '-') { if (yych == ',') goto yy57; goto yy699; } else { if (yych != 'G') goto yy57; } } YYDEBUG(698, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy707; goto yy57; yy699: YYDEBUG(699, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '1') goto yy700; if (yych <= '2') goto yy702; if (yych <= '9') goto yy703; goto yy57; yy700: YYDEBUG(700, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '/') goto yy701; if (yych <= '9') goto yy703; if (yych <= ':') goto yy704; yy701: YYDEBUG(701, *YYCURSOR); #line 1556 "ext/date/lib/parse_date.re" { int tz_not_found; DEBUG_OUTPUT("clf"); TIMELIB_INIT; TIMELIB_HAVE_TIME(); TIMELIB_HAVE_DATE(); s->time->d = timelib_get_nr((char **) &ptr, 2); s->time->m = timelib_get_month((char **) &ptr); s->time->y = timelib_get_nr((char **) &ptr, 4); s->time->h = timelib_get_nr((char **) &ptr, 2); s->time->i = timelib_get_nr((char **) &ptr, 2); s->time->s = timelib_get_nr((char **) &ptr, 2); s->time->z = timelib_get_zone((char **) &ptr, &s->time->dst, s->time, &tz_not_found, s->tzdb); if (tz_not_found) { add_error(s, "The timezone could not be found in the database"); } TIMELIB_DEINIT; return TIMELIB_CLF; } #line 12118 "ext/date/lib/parse_date.c" yy702: YYDEBUG(702, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '5') { if (yych <= '/') goto yy701; if (yych >= '5') goto yy705; } else { if (yych <= '9') goto yy706; if (yych <= ':') goto yy704; goto yy701; } yy703: YYDEBUG(703, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy701; if (yych <= '5') goto yy705; if (yych <= '9') goto yy706; if (yych >= ';') goto yy701; yy704: YYDEBUG(704, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy701; if (yych <= '5') goto yy705; if (yych <= '9') goto yy706; goto yy701; yy705: YYDEBUG(705, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy701; if (yych >= ':') goto yy701; yy706: YYDEBUG(706, *YYCURSOR); yych = *++YYCURSOR; goto yy701; yy707: YYDEBUG(707, *YYCURSOR); yych = *++YYCURSOR; if (yych != 'T') goto yy57; YYDEBUG(708, *YYCURSOR); yych = *++YYCURSOR; if (yych == '+') goto yy699; if (yych == '-') goto yy699; goto yy57; yy709: YYDEBUG(709, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'V') goto yy679; if (yych == 'v') goto yy679; goto yy57; yy710: YYDEBUG(710, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy679; if (yych == 't') goto yy679; goto yy57; yy711: YYDEBUG(711, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy712; if (yych != 'p') goto yy57; yy712: YYDEBUG(712, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych == '/') goto yy680; goto yy57; } else { if (yych <= 'T') goto yy679; if (yych == 't') goto yy679; goto yy57; } yy713: YYDEBUG(713, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy679; if (yych == 'g') goto yy679; goto yy57; yy714: YYDEBUG(714, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy679; if (yych == 'r') goto yy679; goto yy57; yy715: YYDEBUG(715, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych == 'R') goto yy679; if (yych <= 'X') goto yy57; goto yy679; } else { if (yych <= 'r') { if (yych <= 'q') goto yy57; goto yy679; } else { if (yych == 'y') goto yy679; goto yy57; } } yy716: YYDEBUG(716, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy679; if (yych == 'b') goto yy679; goto yy57; yy717: YYDEBUG(717, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych == 'L') goto yy679; if (yych <= 'M') goto yy57; goto yy679; } else { if (yych <= 'l') { if (yych <= 'k') goto yy57; goto yy679; } else { if (yych == 'n') goto yy679; goto yy57; } } yy718: YYDEBUG(718, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy679; if (yych == 'n') goto yy679; goto yy57; yy719: YYDEBUG(719, *YYCURSOR); yych = *++YYCURSOR; if (yych == 't') goto yy728; goto yy57; yy720: YYDEBUG(720, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'd') goto yy728; goto yy57; yy721: YYDEBUG(721, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'd') goto yy728; goto yy57; yy722: YYDEBUG(722, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'h') goto yy728; goto yy57; yy723: YYDEBUG(723, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; YYDEBUG(724, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy667; if (yych >= ':') goto yy667; YYDEBUG(725, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy667; if (yych >= ':') goto yy667; YYDEBUG(726, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy667; if (yych >= ':') goto yy667; YYDEBUG(727, *YYCURSOR); yych = *++YYCURSOR; goto yy667; yy728: YYDEBUG(728, *YYCURSOR); yyaccept = 14; yych = *(YYMARKER = ++YYCURSOR); if (yych == '/') goto yy723; goto yy667; yy729: YYDEBUG(729, *YYCURSOR); yych = *++YYCURSOR; if (yych <= ',') { if (yych == '\t') goto yy731; goto yy578; } else { if (yych <= '-') goto yy732; if (yych <= '.') goto yy731; if (yych >= '0') goto yy578; } yy730: YYDEBUG(730, *YYCURSOR); yych = *++YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case 'A': case 'a': goto yy673; case 'D': case 'd': goto yy677; case 'F': case 'f': goto yy671; case 'J': case 'j': goto yy670; case 'M': case 'm': goto yy672; case 'N': case 'n': goto yy676; case 'O': case 'o': goto yy675; case 'S': case 's': goto yy674; default: goto yy57; } yy731: YYDEBUG(731, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy578; if (yych <= '0') goto yy736; if (yych <= '1') goto yy737; if (yych <= '9') goto yy738; goto yy578; yy732: YYDEBUG(732, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy578; if (yych <= '0') goto yy733; if (yych <= '1') goto yy734; if (yych <= '9') goto yy735; goto yy578; yy733: YYDEBUG(733, *YYCURSOR); yych = *++YYCURSOR; if (yych <= ',') goto yy57; if (yych <= '.') goto yy602; if (yych <= '/') goto yy57; if (yych <= '9') goto yy735; goto yy57; yy734: YYDEBUG(734, *YYCURSOR); yych = *++YYCURSOR; if (yych <= ',') goto yy57; if (yych <= '.') goto yy602; if (yych <= '/') goto yy57; if (yych >= '3') goto yy57; yy735: YYDEBUG(735, *YYCURSOR); yych = *++YYCURSOR; if (yych <= ',') goto yy57; if (yych <= '.') goto yy602; goto yy57; yy736: YYDEBUG(736, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '.') { if (yych <= ',') goto yy57; if (yych <= '-') goto yy602; goto yy739; } else { if (yych <= '/') goto yy57; if (yych <= '9') goto yy738; goto yy57; } yy737: YYDEBUG(737, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '.') { if (yych <= ',') goto yy57; if (yych <= '-') goto yy602; goto yy739; } else { if (yych <= '/') goto yy57; if (yych >= '3') goto yy57; } yy738: YYDEBUG(738, *YYCURSOR); yych = *++YYCURSOR; if (yych <= ',') goto yy57; if (yych <= '-') goto yy602; if (yych >= '/') goto yy57; yy739: YYDEBUG(739, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; YYDEBUG(740, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy611; goto yy57; yy741: YYDEBUG(741, *YYCURSOR); yych = *++YYCURSOR; if (yych == '-') goto yy785; if (yych <= '/') goto yy61; if (yych <= '9') goto yy783; goto yy61; yy742: YYDEBUG(742, *YYCURSOR); yych = *++YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case '0': goto yy751; case '1': goto yy752; case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy753; case 'A': case 'a': goto yy746; case 'D': case 'd': goto yy750; case 'F': case 'f': goto yy744; case 'J': case 'j': goto yy743; case 'M': case 'm': goto yy745; case 'N': case 'n': goto yy749; case 'O': case 'o': goto yy748; case 'S': case 's': goto yy747; default: goto yy57; } yy743: YYDEBUG(743, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'A') goto yy782; if (yych <= 'T') goto yy57; goto yy781; } else { if (yych <= 'a') { if (yych <= '`') goto yy57; goto yy782; } else { if (yych == 'u') goto yy781; goto yy57; } } yy744: YYDEBUG(744, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy780; if (yych == 'e') goto yy780; goto yy57; yy745: YYDEBUG(745, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy779; if (yych == 'a') goto yy779; goto yy57; yy746: YYDEBUG(746, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'P') goto yy778; if (yych <= 'T') goto yy57; goto yy777; } else { if (yych <= 'p') { if (yych <= 'o') goto yy57; goto yy778; } else { if (yych == 'u') goto yy777; goto yy57; } } yy747: YYDEBUG(747, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy775; if (yych == 'e') goto yy775; goto yy57; yy748: YYDEBUG(748, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy774; if (yych == 'c') goto yy774; goto yy57; yy749: YYDEBUG(749, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy773; if (yych == 'o') goto yy773; goto yy57; yy750: YYDEBUG(750, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy765; if (yych == 'e') goto yy765; goto yy57; yy751: YYDEBUG(751, *YYCURSOR); yych = *++YYCURSOR; if (yych == '-') goto yy754; if (yych <= '/') goto yy57; if (yych <= '9') goto yy758; goto yy57; yy752: YYDEBUG(752, *YYCURSOR); yych = *++YYCURSOR; if (yych == '-') goto yy754; if (yych <= '/') goto yy57; if (yych <= '2') goto yy758; goto yy57; yy753: YYDEBUG(753, *YYCURSOR); yych = *++YYCURSOR; if (yych != '-') goto yy57; yy754: YYDEBUG(754, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '2') goto yy755; if (yych <= '3') goto yy756; if (yych <= '9') goto yy757; goto yy57; yy755: YYDEBUG(755, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy657; if (yych <= '9') goto yy757; if (yych <= 'm') goto yy657; goto yy661; } else { if (yych <= 'r') { if (yych <= 'q') goto yy657; goto yy662; } else { if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; goto yy657; } } yy756: YYDEBUG(756, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy657; if (yych <= '1') goto yy757; if (yych <= 'm') goto yy657; goto yy661; } else { if (yych <= 'r') { if (yych <= 'q') goto yy657; goto yy662; } else { if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; goto yy657; } } yy757: YYDEBUG(757, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'q') { if (yych == 'n') goto yy661; goto yy657; } else { if (yych <= 'r') goto yy662; if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; goto yy657; } yy758: YYDEBUG(758, *YYCURSOR); yych = *++YYCURSOR; if (yych != '-') goto yy57; YYDEBUG(759, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '2') { if (yych <= '/') goto yy57; if (yych >= '1') goto yy761; } else { if (yych <= '3') goto yy762; if (yych <= '9') goto yy757; goto yy57; } YYDEBUG(760, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy657; if (yych <= '9') goto yy763; if (yych <= 'm') goto yy657; goto yy661; } else { if (yych <= 'r') { if (yych <= 'q') goto yy657; goto yy662; } else { if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; goto yy657; } } yy761: YYDEBUG(761, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy657; if (yych <= '9') goto yy763; if (yych <= 'm') goto yy657; goto yy661; } else { if (yych <= 'r') { if (yych <= 'q') goto yy657; goto yy662; } else { if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; goto yy657; } } yy762: YYDEBUG(762, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy657; if (yych <= '1') goto yy763; if (yych <= 'm') goto yy657; goto yy661; } else { if (yych <= 'r') { if (yych <= 'q') goto yy657; goto yy662; } else { if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; goto yy657; } } yy763: YYDEBUG(763, *YYCURSOR); yyaccept = 15; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'q') { if (yych == 'n') goto yy661; } else { if (yych <= 'r') goto yy662; if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; } yy764: YYDEBUG(764, *YYCURSOR); #line 1301 "ext/date/lib/parse_date.re" { int length = 0; DEBUG_OUTPUT("iso8601date2"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->y = timelib_get_nr_ex((char **) &ptr, 4, &length); s->time->m = timelib_get_nr((char **) &ptr, 2); s->time->d = timelib_get_nr((char **) &ptr, 2); TIMELIB_PROCESS_YEAR(s->time->y, length); TIMELIB_DEINIT; return TIMELIB_ISO_DATE; } #line 12683 "ext/date/lib/parse_date.c" yy765: YYDEBUG(765, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy766; if (yych != 'c') goto yy57; yy766: YYDEBUG(766, *YYCURSOR); yych = *++YYCURSOR; if (yych != '-') goto yy57; yy767: YYDEBUG(767, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '0') goto yy768; if (yych <= '2') goto yy769; if (yych <= '3') goto yy770; goto yy57; yy768: YYDEBUG(768, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy771; goto yy57; yy769: YYDEBUG(769, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy771; goto yy57; yy770: YYDEBUG(770, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= '2') goto yy57; yy771: YYDEBUG(771, *YYCURSOR); ++YYCURSOR; YYDEBUG(772, *YYCURSOR); #line 1542 "ext/date/lib/parse_date.re" { int length = 0; DEBUG_OUTPUT("pgtextreverse"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->y = timelib_get_nr_ex((char **) &ptr, 4, &length); s->time->m = timelib_get_month((char **) &ptr); s->time->d = timelib_get_nr((char **) &ptr, 2); TIMELIB_PROCESS_YEAR(s->time->y, length); TIMELIB_DEINIT; return TIMELIB_PG_TEXT; } #line 12735 "ext/date/lib/parse_date.c" yy773: YYDEBUG(773, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'V') goto yy766; if (yych == 'v') goto yy766; goto yy57; yy774: YYDEBUG(774, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy766; if (yych == 't') goto yy766; goto yy57; yy775: YYDEBUG(775, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy776; if (yych != 'p') goto yy57; yy776: YYDEBUG(776, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych == '-') goto yy767; goto yy57; } else { if (yych <= 'T') goto yy766; if (yych == 't') goto yy766; goto yy57; } yy777: YYDEBUG(777, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy766; if (yych == 'g') goto yy766; goto yy57; yy778: YYDEBUG(778, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy766; if (yych == 'r') goto yy766; goto yy57; yy779: YYDEBUG(779, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych == 'R') goto yy766; if (yych <= 'X') goto yy57; goto yy766; } else { if (yych <= 'r') { if (yych <= 'q') goto yy57; goto yy766; } else { if (yych == 'y') goto yy766; goto yy57; } } yy780: YYDEBUG(780, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy766; if (yych == 'b') goto yy766; goto yy57; yy781: YYDEBUG(781, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych == 'L') goto yy766; if (yych <= 'M') goto yy57; goto yy766; } else { if (yych <= 'l') { if (yych <= 'k') goto yy57; goto yy766; } else { if (yych == 'n') goto yy766; goto yy57; } } yy782: YYDEBUG(782, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy766; if (yych == 'n') goto yy766; goto yy57; yy783: YYDEBUG(783, *YYCURSOR); yyaccept = 16; yych = *(YYMARKER = ++YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case '\t': case ' ': case 'A': case 'D': case 'F': case 'H': case 'I': case 'J': case 'M': case 'N': case 'O': case 'S': case 'T': case 'V': case 'X': case 'Y': case 'a': case 'd': case 'f': case 'h': case 'j': case 'm': case 'n': case 'o': case 's': case 't': case 'w': case 'y': goto yy791; case '-': goto yy788; case '.': goto yy792; case '/': goto yy789; case '0': goto yy805; case '1': goto yy806; case '2': goto yy808; case '3': goto yy809; case '4': case '5': case '6': case '7': case '8': case '9': goto yy55; case ':': goto yy807; case 'W': goto yy810; default: goto yy784; } yy784: YYDEBUG(784, *YYCURSOR); #line 1577 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("year4"); TIMELIB_INIT; s->time->y = timelib_get_nr((char **) &ptr, 4); TIMELIB_DEINIT; return TIMELIB_CLF; } #line 12881 "ext/date/lib/parse_date.c" yy785: YYDEBUG(785, *YYCURSOR); yych = *++YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case '0': goto yy786; case '1': goto yy787; case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy753; case 'A': case 'a': goto yy746; case 'D': case 'd': goto yy750; case 'F': case 'f': goto yy744; case 'J': case 'j': goto yy743; case 'M': case 'm': goto yy745; case 'N': case 'n': goto yy749; case 'O': case 'o': goto yy748; case 'S': case 's': goto yy747; default: goto yy57; } yy786: YYDEBUG(786, *YYCURSOR); yych = *++YYCURSOR; if (yych == '-') goto yy754; if (yych <= '/') goto yy57; if (yych <= '9') goto yy753; goto yy57; yy787: YYDEBUG(787, *YYCURSOR); yych = *++YYCURSOR; if (yych == '-') goto yy754; if (yych <= '/') goto yy57; if (yych <= '2') goto yy753; goto yy57; yy788: YYDEBUG(788, *YYCURSOR); yych = *++YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case '0': goto yy973; case '1': goto yy975; case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy976; case 'A': case 'a': goto yy967; case 'D': case 'd': goto yy971; case 'F': case 'f': goto yy965; case 'J': case 'j': goto yy964; case 'M': case 'm': goto yy966; case 'N': case 'n': goto yy970; case 'O': case 'o': goto yy969; case 'S': case 's': goto yy968; case 'W': goto yy972; default: goto yy939; } yy789: YYDEBUG(789, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '0') goto yy947; if (yych <= '1') goto yy948; if (yych <= '9') goto yy949; goto yy57; yy790: YYDEBUG(790, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 11) YYFILL(11); yych = *YYCURSOR; yy791: YYDEBUG(791, *YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case '\t': case ' ': goto yy790; case '-': case '.': goto yy938; case 'A': case 'a': goto yy800; case 'D': case 'd': goto yy804; case 'F': case 'f': goto yy798; case 'H': case 'h': goto yy64; case 'I': goto yy793; case 'J': case 'j': goto yy797; case 'M': case 'm': goto yy799; case 'N': case 'n': goto yy803; case 'O': case 'o': goto yy802; case 'S': case 's': goto yy801; case 'T': case 't': goto yy69; case 'V': goto yy795; case 'W': case 'w': goto yy68; case 'X': goto yy796; case 'Y': case 'y': goto yy67; default: goto yy57; } yy792: YYDEBUG(792, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy939; if (yych <= '0') goto yy931; if (yych <= '2') goto yy932; if (yych <= '3') goto yy933; goto yy939; yy793: YYDEBUG(793, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= 'U') { if (yych == 'I') goto yy930; } else { if (yych == 'W') goto yy794; if (yych <= 'X') goto yy884; } yy794: YYDEBUG(794, *YYCURSOR); #line 1398 "ext/date/lib/parse_date.re" { int length = 0; DEBUG_OUTPUT("datenodayrev"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->y = timelib_get_nr_ex((char **) &ptr, 4, &length); s->time->m = timelib_get_month((char **) &ptr); s->time->d = 1; TIMELIB_PROCESS_YEAR(s->time->y, length); TIMELIB_DEINIT; return TIMELIB_DATE_NO_DAY; } #line 13045 "ext/date/lib/parse_date.c" yy795: YYDEBUG(795, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy928; goto yy794; yy796: YYDEBUG(796, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy927; goto yy794; yy797: YYDEBUG(797, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'A') goto yy920; if (yych <= 'T') goto yy57; goto yy919; } else { if (yych <= 'a') { if (yych <= '`') goto yy57; goto yy920; } else { if (yych == 'u') goto yy919; goto yy57; } } yy798: YYDEBUG(798, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= 'N') { if (yych == 'E') goto yy913; goto yy57; } else { if (yych <= 'O') goto yy99; if (yych <= 'Q') goto yy57; goto yy98; } } else { if (yych <= 'n') { if (yych == 'e') goto yy913; goto yy57; } else { if (yych <= 'o') goto yy99; if (yych == 'r') goto yy98; goto yy57; } } yy799: YYDEBUG(799, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= 'H') { if (yych == 'A') goto yy910; goto yy57; } else { if (yych <= 'I') goto yy118; if (yych <= 'N') goto yy57; goto yy117; } } else { if (yych <= 'h') { if (yych == 'a') goto yy910; goto yy57; } else { if (yych <= 'i') goto yy118; if (yych == 'o') goto yy117; goto yy57; } } yy800: YYDEBUG(800, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'P') goto yy904; if (yych <= 'T') goto yy57; goto yy903; } else { if (yych <= 'p') { if (yych <= 'o') goto yy57; goto yy904; } else { if (yych == 'u') goto yy903; goto yy57; } } yy801: YYDEBUG(801, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= 'D') { if (yych == 'A') goto yy127; goto yy57; } else { if (yych <= 'E') goto yy896; if (yych <= 'T') goto yy57; goto yy126; } } else { if (yych <= 'd') { if (yych == 'a') goto yy127; goto yy57; } else { if (yych <= 'e') goto yy896; if (yych == 'u') goto yy126; goto yy57; } } yy802: YYDEBUG(802, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy891; if (yych == 'c') goto yy891; goto yy57; yy803: YYDEBUG(803, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy885; if (yych == 'o') goto yy885; goto yy57; yy804: YYDEBUG(804, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych == 'A') goto yy114; if (yych <= 'D') goto yy57; goto yy878; } else { if (yych <= 'a') { if (yych <= '`') goto yy57; goto yy114; } else { if (yych == 'e') goto yy878; goto yy57; } } yy805: YYDEBUG(805, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '0') goto yy875; if (yych <= '9') goto yy876; goto yy61; yy806: YYDEBUG(806, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '2') goto yy844; if (yych <= '9') goto yy823; goto yy61; yy807: YYDEBUG(807, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '0') goto yy824; if (yych <= '1') goto yy825; goto yy57; yy808: YYDEBUG(808, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '9') goto yy823; goto yy61; yy809: YYDEBUG(809, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '5') goto yy819; if (yych <= '6') goto yy820; if (yych <= '9') goto yy55; goto yy61; yy810: YYDEBUG(810, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '5') { if (yych <= '/') goto yy57; if (yych <= '0') goto yy811; if (yych <= '4') goto yy812; goto yy813; } else { if (yych <= 'E') { if (yych <= 'D') goto yy57; goto yy83; } else { if (yych == 'e') goto yy83; goto yy57; } } yy811: YYDEBUG(811, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '0') goto yy57; if (yych <= '9') goto yy814; goto yy57; yy812: YYDEBUG(812, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy814; goto yy57; yy813: YYDEBUG(813, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= '4') goto yy57; yy814: YYDEBUG(814, *YYCURSOR); yyaccept = 17; yych = *(YYMARKER = ++YYCURSOR); if (yych == '-') goto yy816; if (yych <= '/') goto yy815; if (yych <= '7') goto yy817; yy815: YYDEBUG(815, *YYCURSOR); #line 1509 "ext/date/lib/parse_date.re" { timelib_sll w, d; DEBUG_OUTPUT("isoweek"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); TIMELIB_HAVE_RELATIVE(); s->time->y = timelib_get_nr((char **) &ptr, 4); w = timelib_get_nr((char **) &ptr, 2); d = 1; s->time->m = 1; s->time->d = 1; s->time->relative.d = timelib_daynr_from_weeknr(s->time->y, w, d); TIMELIB_DEINIT; return TIMELIB_ISO_WEEK; } #line 13278 "ext/date/lib/parse_date.c" yy816: YYDEBUG(816, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= '8') goto yy57; yy817: YYDEBUG(817, *YYCURSOR); ++YYCURSOR; YYDEBUG(818, *YYCURSOR); #line 1490 "ext/date/lib/parse_date.re" { timelib_sll w, d; DEBUG_OUTPUT("isoweekday"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); TIMELIB_HAVE_RELATIVE(); s->time->y = timelib_get_nr((char **) &ptr, 4); w = timelib_get_nr((char **) &ptr, 2); d = timelib_get_nr((char **) &ptr, 1); s->time->m = 1; s->time->d = 1; s->time->relative.d = timelib_daynr_from_weeknr(s->time->y, w, d); TIMELIB_DEINIT; return TIMELIB_ISO_WEEK; } #line 13306 "ext/date/lib/parse_date.c" yy819: YYDEBUG(819, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '9') goto yy821; goto yy61; yy820: YYDEBUG(820, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '6') goto yy821; if (yych <= '9') goto yy55; goto yy61; yy821: YYDEBUG(821, *YYCURSOR); yyaccept = 18; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 2) { goto yy55; } if (yych <= 'W') { if (yych <= 'F') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych >= ' ') goto yy61; } else { if (yych == 'D') goto yy61; if (yych >= 'F') goto yy61; } } else { if (yych <= 'M') { if (yych == 'H') goto yy61; if (yych >= 'M') goto yy61; } else { if (yych <= 'R') goto yy822; if (yych <= 'T') goto yy61; if (yych >= 'W') goto yy61; } } } else { if (yych <= 'h') { if (yych <= 'd') { if (yych == 'Y') goto yy61; if (yych >= 'd') goto yy61; } else { if (yych == 'f') goto yy61; if (yych >= 'h') goto yy61; } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych >= 's') goto yy61; } else { if (yych <= 'w') { if (yych >= 'w') goto yy61; } else { if (yych == 'y') goto yy61; } } } } yy822: YYDEBUG(822, *YYCURSOR); #line 1476 "ext/date/lib/parse_date.re" { int length = 0; DEBUG_OUTPUT("pgydotd"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->y = timelib_get_nr_ex((char **) &ptr, 4, &length); s->time->d = timelib_get_nr((char **) &ptr, 3); s->time->m = 1; TIMELIB_PROCESS_YEAR(s->time->y, length); TIMELIB_DEINIT; return TIMELIB_PG_YEARDAY; } #line 13383 "ext/date/lib/parse_date.c" yy823: YYDEBUG(823, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '9') goto yy821; goto yy61; yy824: YYDEBUG(824, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy826; goto yy57; yy825: YYDEBUG(825, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= '3') goto yy57; yy826: YYDEBUG(826, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy57; YYDEBUG(827, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '0') goto yy828; if (yych <= '2') goto yy829; if (yych <= '3') goto yy830; goto yy57; yy828: YYDEBUG(828, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy831; goto yy57; yy829: YYDEBUG(829, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy831; goto yy57; yy830: YYDEBUG(830, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= '2') goto yy57; yy831: YYDEBUG(831, *YYCURSOR); yych = *++YYCURSOR; if (yych != ' ') goto yy57; YYDEBUG(832, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '1') goto yy833; if (yych <= '2') goto yy834; goto yy57; yy833: YYDEBUG(833, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy835; goto yy57; yy834: YYDEBUG(834, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= '5') goto yy57; yy835: YYDEBUG(835, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy57; YYDEBUG(836, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= '6') goto yy57; YYDEBUG(837, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; YYDEBUG(838, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy57; YYDEBUG(839, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy840; if (yych <= '6') goto yy841; goto yy57; yy840: YYDEBUG(840, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy842; goto yy57; yy841: YYDEBUG(841, *YYCURSOR); yych = *++YYCURSOR; if (yych != '0') goto yy57; yy842: YYDEBUG(842, *YYCURSOR); ++YYCURSOR; yy843: YYDEBUG(843, *YYCURSOR); #line 1450 "ext/date/lib/parse_date.re" { int tz_not_found; DEBUG_OUTPUT("xmlrpc | xmlrpcnocolon | soap | wddx | exif"); TIMELIB_INIT; TIMELIB_HAVE_TIME(); TIMELIB_HAVE_DATE(); s->time->y = timelib_get_nr((char **) &ptr, 4); s->time->m = timelib_get_nr((char **) &ptr, 2); s->time->d = timelib_get_nr((char **) &ptr, 2); s->time->h = timelib_get_nr((char **) &ptr, 2); s->time->i = timelib_get_nr((char **) &ptr, 2); s->time->s = timelib_get_nr((char **) &ptr, 2); if (*ptr == '.') { s->time->f = timelib_get_frac_nr((char **) &ptr, 9); if (*ptr) { /* timezone is optional */ s->time->z = timelib_get_zone((char **) &ptr, &s->time->dst, s->time, &tz_not_found, s->tzdb); if (tz_not_found) { add_error(s, "The timezone could not be found in the database"); } } } TIMELIB_DEINIT; return TIMELIB_XMLRPC_SOAP; } #line 13511 "ext/date/lib/parse_date.c" yy844: YYDEBUG(844, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '2') { if (yych <= '/') goto yy61; if (yych >= '1') goto yy846; } else { if (yych <= '3') goto yy847; if (yych <= '9') goto yy821; goto yy61; } yy845: YYDEBUG(845, *YYCURSOR); yyaccept = 18; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'V') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy822; goto yy61; } else { if (yych <= '/') goto yy822; if (yych <= '9') goto yy848; if (yych <= 'C') goto yy822; goto yy61; } } else { if (yych <= 'H') { if (yych == 'F') goto yy61; if (yych <= 'G') goto yy822; goto yy61; } else { if (yych <= 'M') { if (yych <= 'L') goto yy822; goto yy61; } else { if (yych <= 'R') goto yy822; if (yych <= 'T') goto yy61; goto yy822; } } } } else { if (yych <= 'h') { if (yych <= 'c') { if (yych == 'X') goto yy822; if (yych <= 'Y') goto yy61; goto yy822; } else { if (yych <= 'e') { if (yych <= 'd') goto yy61; goto yy822; } else { if (yych == 'g') goto yy822; goto yy61; } } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych <= 'r') goto yy822; goto yy61; } else { if (yych <= 'w') { if (yych <= 'v') goto yy822; goto yy61; } else { if (yych == 'y') goto yy61; goto yy822; } } } } yy846: YYDEBUG(846, *YYCURSOR); yyaccept = 18; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'V') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy822; goto yy61; } else { if (yych <= '/') goto yy822; if (yych <= '9') goto yy848; if (yych <= 'C') goto yy822; goto yy61; } } else { if (yych <= 'H') { if (yych == 'F') goto yy61; if (yych <= 'G') goto yy822; goto yy61; } else { if (yych <= 'M') { if (yych <= 'L') goto yy822; goto yy61; } else { if (yych <= 'R') goto yy822; if (yych <= 'T') goto yy61; goto yy822; } } } } else { if (yych <= 'h') { if (yych <= 'c') { if (yych == 'X') goto yy822; if (yych <= 'Y') goto yy61; goto yy822; } else { if (yych <= 'e') { if (yych <= 'd') goto yy61; goto yy822; } else { if (yych == 'g') goto yy822; goto yy61; } } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych <= 'r') goto yy822; goto yy61; } else { if (yych <= 'w') { if (yych <= 'v') goto yy822; goto yy61; } else { if (yych == 'y') goto yy61; goto yy822; } } } } yy847: YYDEBUG(847, *YYCURSOR); yyaccept = 18; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'V') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy822; goto yy61; } else { if (yych <= '1') { if (yych <= '/') goto yy822; } else { if (yych <= '9') goto yy55; if (yych <= 'C') goto yy822; goto yy61; } } } else { if (yych <= 'H') { if (yych == 'F') goto yy61; if (yych <= 'G') goto yy822; goto yy61; } else { if (yych <= 'M') { if (yych <= 'L') goto yy822; goto yy61; } else { if (yych <= 'R') goto yy822; if (yych <= 'T') goto yy61; goto yy822; } } } } else { if (yych <= 'h') { if (yych <= 'c') { if (yych == 'X') goto yy822; if (yych <= 'Y') goto yy61; goto yy822; } else { if (yych <= 'e') { if (yych <= 'd') goto yy61; goto yy822; } else { if (yych == 'g') goto yy822; goto yy61; } } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych <= 'r') goto yy822; goto yy61; } else { if (yych <= 'w') { if (yych <= 'v') goto yy822; goto yy61; } else { if (yych == 'y') goto yy61; goto yy822; } } } } yy848: YYDEBUG(848, *YYCURSOR); yyaccept = 19; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 2) { goto yy55; } if (yych <= 'W') { if (yych <= 'F') { if (yych <= ' ') { if (yych == '\t') goto yy60; if (yych >= ' ') goto yy60; } else { if (yych == 'D') goto yy65; if (yych >= 'F') goto yy66; } } else { if (yych <= 'M') { if (yych == 'H') goto yy64; if (yych >= 'M') goto yy63; } else { if (yych <= 'S') { if (yych >= 'S') goto yy62; } else { if (yych <= 'T') goto yy850; if (yych >= 'W') goto yy68; } } } } else { if (yych <= 'l') { if (yych <= 'd') { if (yych == 'Y') goto yy67; if (yych >= 'd') goto yy65; } else { if (yych <= 'f') { if (yych >= 'f') goto yy66; } else { if (yych == 'h') goto yy64; } } } else { if (yych <= 't') { if (yych <= 'm') goto yy63; if (yych <= 'r') goto yy849; if (yych <= 's') goto yy62; goto yy851; } else { if (yych <= 'w') { if (yych >= 'w') goto yy68; } else { if (yych == 'y') goto yy67; } } } } yy849: YYDEBUG(849, *YYCURSOR); #line 1438 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("datenocolon"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->y = timelib_get_nr((char **) &ptr, 4); s->time->m = timelib_get_nr((char **) &ptr, 2); s->time->d = timelib_get_nr((char **) &ptr, 2); TIMELIB_DEINIT; return TIMELIB_DATE_NOCOLON; } #line 13784 "ext/date/lib/parse_date.c" yy850: YYDEBUG(850, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'H') { if (yych <= '2') { if (yych <= '/') goto yy57; if (yych <= '1') goto yy865; goto yy866; } else { if (yych <= '9') goto yy867; if (yych <= 'G') goto yy57; goto yy70; } } else { if (yych <= 'g') { if (yych == 'U') goto yy71; goto yy57; } else { if (yych <= 'h') goto yy70; if (yych == 'u') goto yy71; goto yy57; } } yy851: YYDEBUG(851, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'H') { if (yych <= '2') { if (yych <= '/') goto yy57; if (yych >= '2') goto yy853; } else { if (yych <= '9') goto yy854; if (yych <= 'G') goto yy57; goto yy70; } } else { if (yych <= 'g') { if (yych == 'U') goto yy71; goto yy57; } else { if (yych <= 'h') goto yy70; if (yych == 'u') goto yy71; goto yy57; } } YYDEBUG(852, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy859; if (yych <= '9') goto yy854; goto yy57; yy853: YYDEBUG(853, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '4') goto yy859; if (yych <= '5') goto yy855; goto yy57; yy854: YYDEBUG(854, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= '6') goto yy57; yy855: YYDEBUG(855, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; yy856: YYDEBUG(856, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy857; if (yych <= '6') goto yy858; goto yy57; yy857: YYDEBUG(857, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy842; goto yy57; yy858: YYDEBUG(858, *YYCURSOR); yych = *++YYCURSOR; if (yych == '0') goto yy842; goto yy57; yy859: YYDEBUG(859, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy860; if (yych <= '9') goto yy856; goto yy57; yy860: YYDEBUG(860, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy861; if (yych <= '6') goto yy862; if (yych <= '9') goto yy856; goto yy57; yy861: YYDEBUG(861, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy863; if (yych <= '6') goto yy864; if (yych <= '9') goto yy842; goto yy57; yy862: YYDEBUG(862, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '0') goto yy863; if (yych <= '5') goto yy857; if (yych <= '6') goto yy858; goto yy57; yy863: YYDEBUG(863, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy843; if (yych <= '9') goto yy842; goto yy843; yy864: YYDEBUG(864, *YYCURSOR); yych = *++YYCURSOR; if (yych == '0') goto yy842; goto yy843; yy865: YYDEBUG(865, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy874; if (yych <= '9') goto yy867; if (yych <= ':') goto yy868; goto yy57; yy866: YYDEBUG(866, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '5') { if (yych <= '/') goto yy57; if (yych <= '4') goto yy874; goto yy855; } else { if (yych == ':') goto yy868; goto yy57; } yy867: YYDEBUG(867, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy855; if (yych != ':') goto yy57; yy868: YYDEBUG(868, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= '6') goto yy57; YYDEBUG(869, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; YYDEBUG(870, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy57; YYDEBUG(871, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy872; if (yych <= '6') goto yy873; goto yy57; yy872: YYDEBUG(872, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy842; goto yy57; yy873: YYDEBUG(873, *YYCURSOR); yych = *++YYCURSOR; if (yych == '0') goto yy842; goto yy57; yy874: YYDEBUG(874, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy860; if (yych <= '9') goto yy856; if (yych <= ':') goto yy868; goto yy57; yy875: YYDEBUG(875, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '2') { if (yych <= '/') goto yy61; if (yych <= '0') goto yy877; goto yy846; } else { if (yych <= '3') goto yy847; if (yych <= '9') goto yy821; goto yy61; } yy876: YYDEBUG(876, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '2') { if (yych <= '/') goto yy61; if (yych <= '0') goto yy845; goto yy846; } else { if (yych <= '3') goto yy847; if (yych <= '9') goto yy821; goto yy61; } yy877: YYDEBUG(877, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '9') goto yy848; goto yy61; yy878: YYDEBUG(878, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy879; if (yych != 'c') goto yy57; yy879: YYDEBUG(879, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'E') goto yy880; if (yych != 'e') goto yy794; yy880: YYDEBUG(880, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy881; if (yych != 'm') goto yy57; yy881: YYDEBUG(881, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy882; if (yych != 'b') goto yy57; yy882: YYDEBUG(882, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy883; if (yych != 'e') goto yy57; yy883: YYDEBUG(883, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy884; if (yych != 'r') goto yy57; yy884: YYDEBUG(884, *YYCURSOR); yych = *++YYCURSOR; goto yy794; yy885: YYDEBUG(885, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'V') goto yy886; if (yych != 'v') goto yy57; yy886: YYDEBUG(886, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'E') goto yy887; if (yych != 'e') goto yy794; yy887: YYDEBUG(887, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy888; if (yych != 'm') goto yy57; yy888: YYDEBUG(888, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy889; if (yych != 'b') goto yy57; yy889: YYDEBUG(889, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy890; if (yych != 'e') goto yy57; yy890: YYDEBUG(890, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy884; if (yych == 'r') goto yy884; goto yy57; yy891: YYDEBUG(891, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy892; if (yych != 't') goto yy57; yy892: YYDEBUG(892, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'O') goto yy893; if (yych != 'o') goto yy794; yy893: YYDEBUG(893, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy894; if (yych != 'b') goto yy57; yy894: YYDEBUG(894, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy895; if (yych != 'e') goto yy57; yy895: YYDEBUG(895, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy884; if (yych == 'r') goto yy884; goto yy57; yy896: YYDEBUG(896, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'P') { if (yych == 'C') goto yy129; if (yych <= 'O') goto yy57; } else { if (yych <= 'c') { if (yych <= 'b') goto yy57; goto yy129; } else { if (yych != 'p') goto yy57; } } yy897: YYDEBUG(897, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy898; if (yych != 't') goto yy794; yy898: YYDEBUG(898, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'E') goto yy899; if (yych != 'e') goto yy794; yy899: YYDEBUG(899, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy900; if (yych != 'm') goto yy57; yy900: YYDEBUG(900, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy901; if (yych != 'b') goto yy57; yy901: YYDEBUG(901, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy902; if (yych != 'e') goto yy57; yy902: YYDEBUG(902, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy884; if (yych == 'r') goto yy884; goto yy57; yy903: YYDEBUG(903, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy907; if (yych == 'g') goto yy907; goto yy57; yy904: YYDEBUG(904, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy905; if (yych != 'r') goto yy57; yy905: YYDEBUG(905, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'I') goto yy906; if (yych != 'i') goto yy794; yy906: YYDEBUG(906, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy884; if (yych == 'l') goto yy884; goto yy57; yy907: YYDEBUG(907, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'U') goto yy908; if (yych != 'u') goto yy794; yy908: YYDEBUG(908, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy909; if (yych != 's') goto yy57; yy909: YYDEBUG(909, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy884; if (yych == 't') goto yy884; goto yy57; yy910: YYDEBUG(910, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych == 'R') goto yy911; if (yych <= 'X') goto yy57; goto yy884; } else { if (yych <= 'r') { if (yych <= 'q') goto yy57; } else { if (yych == 'y') goto yy884; goto yy57; } } yy911: YYDEBUG(911, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'C') goto yy912; if (yych != 'c') goto yy794; yy912: YYDEBUG(912, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy884; if (yych == 'h') goto yy884; goto yy57; yy913: YYDEBUG(913, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy914; if (yych != 'b') goto yy57; yy914: YYDEBUG(914, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'R') goto yy915; if (yych != 'r') goto yy794; yy915: YYDEBUG(915, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy916; if (yych != 'u') goto yy57; yy916: YYDEBUG(916, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy917; if (yych != 'a') goto yy57; yy917: YYDEBUG(917, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy918; if (yych != 'r') goto yy57; yy918: YYDEBUG(918, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy884; if (yych == 'y') goto yy884; goto yy57; yy919: YYDEBUG(919, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych == 'L') goto yy926; if (yych <= 'M') goto yy57; goto yy925; } else { if (yych <= 'l') { if (yych <= 'k') goto yy57; goto yy926; } else { if (yych == 'n') goto yy925; goto yy57; } } yy920: YYDEBUG(920, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy921; if (yych != 'n') goto yy57; yy921: YYDEBUG(921, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'U') goto yy922; if (yych != 'u') goto yy794; yy922: YYDEBUG(922, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy923; if (yych != 'a') goto yy57; yy923: YYDEBUG(923, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy924; if (yych != 'r') goto yy57; yy924: YYDEBUG(924, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy884; if (yych == 'y') goto yy884; goto yy57; yy925: YYDEBUG(925, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy884; if (yych == 'e') goto yy884; goto yy794; yy926: YYDEBUG(926, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy884; if (yych == 'y') goto yy884; goto yy794; yy927: YYDEBUG(927, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy884; goto yy794; yy928: YYDEBUG(928, *YYCURSOR); yych = *++YYCURSOR; if (yych != 'I') goto yy794; YYDEBUG(929, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy884; goto yy794; yy930: YYDEBUG(930, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy884; goto yy794; yy931: YYDEBUG(931, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '0') goto yy946; if (yych <= '9') goto yy945; goto yy57; yy932: YYDEBUG(932, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy944; goto yy57; yy933: YYDEBUG(933, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy942; if (yych <= '6') goto yy941; goto yy57; yy934: YYDEBUG(934, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy913; if (yych == 'e') goto yy913; goto yy57; yy935: YYDEBUG(935, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy910; if (yych == 'a') goto yy910; goto yy57; yy936: YYDEBUG(936, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy940; if (yych == 'e') goto yy940; goto yy57; yy937: YYDEBUG(937, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy878; if (yych == 'e') goto yy878; goto yy57; yy938: YYDEBUG(938, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 9) YYFILL(9); yych = *YYCURSOR; yy939: YYDEBUG(939, *YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case '\t': case ' ': case '-': case '.': goto yy938; case 'A': case 'a': goto yy800; case 'D': case 'd': goto yy937; case 'F': case 'f': goto yy934; case 'I': goto yy793; case 'J': case 'j': goto yy797; case 'M': case 'm': goto yy935; case 'N': case 'n': goto yy803; case 'O': case 'o': goto yy802; case 'S': case 's': goto yy936; case 'V': goto yy795; case 'X': goto yy796; default: goto yy57; } yy940: YYDEBUG(940, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy897; if (yych == 'p') goto yy897; goto yy57; yy941: YYDEBUG(941, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '6') goto yy943; goto yy57; yy942: YYDEBUG(942, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; yy943: YYDEBUG(943, *YYCURSOR); yych = *++YYCURSOR; goto yy822; yy944: YYDEBUG(944, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy943; goto yy57; yy945: YYDEBUG(945, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy943; goto yy57; yy946: YYDEBUG(946, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '0') goto yy57; if (yych <= '9') goto yy943; goto yy57; yy947: YYDEBUG(947, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '.') goto yy57; if (yych <= '/') goto yy950; if (yych <= '9') goto yy958; goto yy57; yy948: YYDEBUG(948, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '.') goto yy57; if (yych <= '/') goto yy950; if (yych <= '2') goto yy958; goto yy57; yy949: YYDEBUG(949, *YYCURSOR); yych = *++YYCURSOR; if (yych != '/') goto yy57; yy950: YYDEBUG(950, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '2') goto yy951; if (yych <= '3') goto yy952; if (yych <= '9') goto yy953; goto yy57; yy951: YYDEBUG(951, *YYCURSOR); yyaccept = 21; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy455; if (yych <= '9') goto yy953; if (yych <= 'm') goto yy455; goto yy955; } else { if (yych <= 'r') { if (yych <= 'q') goto yy455; goto yy956; } else { if (yych <= 's') goto yy954; if (yych <= 't') goto yy957; goto yy455; } } yy952: YYDEBUG(952, *YYCURSOR); yyaccept = 21; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy455; if (yych <= '1') goto yy953; if (yych <= 'm') goto yy455; goto yy955; } else { if (yych <= 'r') { if (yych <= 'q') goto yy455; goto yy956; } else { if (yych <= 's') goto yy954; if (yych <= 't') goto yy957; goto yy455; } } yy953: YYDEBUG(953, *YYCURSOR); yyaccept = 21; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'q') { if (yych == 'n') goto yy955; goto yy455; } else { if (yych <= 'r') goto yy956; if (yych <= 's') goto yy954; if (yych <= 't') goto yy957; goto yy455; } yy954: YYDEBUG(954, *YYCURSOR); yych = *++YYCURSOR; if (yych == 't') goto yy454; goto yy57; yy955: YYDEBUG(955, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'd') goto yy454; goto yy57; yy956: YYDEBUG(956, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'd') goto yy454; goto yy57; yy957: YYDEBUG(957, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'h') goto yy454; goto yy57; yy958: YYDEBUG(958, *YYCURSOR); yych = *++YYCURSOR; if (yych != '/') goto yy57; YYDEBUG(959, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '2') { if (yych <= '/') goto yy57; if (yych >= '1') goto yy961; } else { if (yych <= '3') goto yy962; if (yych <= '9') goto yy953; goto yy57; } YYDEBUG(960, *YYCURSOR); yyaccept = 21; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy455; if (yych <= '9') goto yy963; if (yych <= 'm') goto yy455; goto yy955; } else { if (yych <= 'r') { if (yych <= 'q') goto yy455; goto yy956; } else { if (yych <= 's') goto yy954; if (yych <= 't') goto yy957; goto yy455; } } yy961: YYDEBUG(961, *YYCURSOR); yyaccept = 21; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy455; if (yych <= '9') goto yy963; if (yych <= 'm') goto yy455; goto yy955; } else { if (yych <= 'r') { if (yych <= 'q') goto yy455; goto yy956; } else { if (yych <= 's') goto yy954; if (yych <= 't') goto yy957; goto yy455; } } yy962: YYDEBUG(962, *YYCURSOR); yyaccept = 21; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy455; if (yych <= '1') goto yy963; if (yych <= 'm') goto yy455; goto yy955; } else { if (yych <= 'r') { if (yych <= 'q') goto yy455; goto yy956; } else { if (yych <= 's') goto yy954; if (yych <= 't') goto yy957; goto yy455; } } yy963: YYDEBUG(963, *YYCURSOR); yyaccept = 21; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych == '/') goto yy454; if (yych <= 'm') goto yy455; goto yy955; } else { if (yych <= 'r') { if (yych <= 'q') goto yy455; goto yy956; } else { if (yych <= 's') goto yy954; if (yych <= 't') goto yy957; goto yy455; } } yy964: YYDEBUG(964, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'A') goto yy1044; if (yych <= 'T') goto yy57; goto yy1043; } else { if (yych <= 'a') { if (yych <= '`') goto yy57; goto yy1044; } else { if (yych == 'u') goto yy1043; goto yy57; } } yy965: YYDEBUG(965, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy1041; if (yych == 'e') goto yy1041; goto yy57; yy966: YYDEBUG(966, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1038; if (yych == 'a') goto yy1038; goto yy57; yy967: YYDEBUG(967, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'P') goto yy1035; if (yych <= 'T') goto yy57; goto yy1034; } else { if (yych <= 'p') { if (yych <= 'o') goto yy57; goto yy1035; } else { if (yych == 'u') goto yy1034; goto yy57; } } yy968: YYDEBUG(968, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy1031; if (yych == 'e') goto yy1031; goto yy57; yy969: YYDEBUG(969, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy1029; if (yych == 'c') goto yy1029; goto yy57; yy970: YYDEBUG(970, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy1027; if (yych == 'o') goto yy1027; goto yy57; yy971: YYDEBUG(971, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy1025; if (yych == 'e') goto yy1025; goto yy57; yy972: YYDEBUG(972, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '0') goto yy811; if (yych <= '4') goto yy812; if (yych <= '5') goto yy813; goto yy57; yy973: YYDEBUG(973, *YYCURSOR); yyaccept = 22; yych = *(YYMARKER = ++YYCURSOR); if (yych == '-') goto yy977; if (yych <= '/') goto yy974; if (yych <= '9') goto yy996; yy974: YYDEBUG(974, *YYCURSOR); #line 1315 "ext/date/lib/parse_date.re" { int length = 0; DEBUG_OUTPUT("gnudateshorter"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->y = timelib_get_nr_ex((char **) &ptr, 4, &length); s->time->m = timelib_get_nr((char **) &ptr, 2); s->time->d = 1; TIMELIB_PROCESS_YEAR(s->time->y, length); TIMELIB_DEINIT; return TIMELIB_ISO_DATE; } #line 14717 "ext/date/lib/parse_date.c" yy975: YYDEBUG(975, *YYCURSOR); yyaccept = 22; yych = *(YYMARKER = ++YYCURSOR); if (yych == '-') goto yy977; if (yych <= '/') goto yy974; if (yych <= '2') goto yy996; goto yy974; yy976: YYDEBUG(976, *YYCURSOR); yyaccept = 22; yych = *(YYMARKER = ++YYCURSOR); if (yych != '-') goto yy974; yy977: YYDEBUG(977, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '2') goto yy978; if (yych <= '3') goto yy979; if (yych <= '9') goto yy980; goto yy57; yy978: YYDEBUG(978, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'm') { if (yych <= '9') { if (yych <= '/') goto yy657; goto yy980; } else { if (yych == 'T') goto yy985; goto yy657; } } else { if (yych <= 'r') { if (yych <= 'n') goto yy982; if (yych <= 'q') goto yy657; goto yy983; } else { if (yych <= 's') goto yy981; if (yych <= 't') goto yy984; goto yy657; } } yy979: YYDEBUG(979, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'm') { if (yych <= '1') { if (yych <= '/') goto yy657; } else { if (yych == 'T') goto yy985; goto yy657; } } else { if (yych <= 'r') { if (yych <= 'n') goto yy982; if (yych <= 'q') goto yy657; goto yy983; } else { if (yych <= 's') goto yy981; if (yych <= 't') goto yy984; goto yy657; } } yy980: YYDEBUG(980, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych == 'T') goto yy985; if (yych <= 'm') goto yy657; goto yy982; } else { if (yych <= 'r') { if (yych <= 'q') goto yy657; goto yy983; } else { if (yych <= 's') goto yy981; if (yych <= 't') goto yy984; goto yy657; } } yy981: YYDEBUG(981, *YYCURSOR); yych = *++YYCURSOR; if (yych == 't') goto yy995; goto yy57; yy982: YYDEBUG(982, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'd') goto yy995; goto yy57; yy983: YYDEBUG(983, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'd') goto yy995; goto yy57; yy984: YYDEBUG(984, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'h') goto yy995; goto yy57; yy985: YYDEBUG(985, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '1') goto yy986; if (yych <= '2') goto yy987; if (yych <= '9') goto yy988; goto yy57; yy986: YYDEBUG(986, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy988; if (yych <= ':') goto yy989; goto yy57; yy987: YYDEBUG(987, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '4') goto yy988; if (yych == ':') goto yy989; goto yy57; yy988: YYDEBUG(988, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy57; yy989: YYDEBUG(989, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy990; if (yych <= '9') goto yy991; goto yy57; yy990: YYDEBUG(990, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy991; if (yych <= ':') goto yy992; goto yy57; yy991: YYDEBUG(991, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy57; yy992: YYDEBUG(992, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy993; if (yych <= '6') goto yy994; if (yych <= '9') goto yy842; goto yy57; yy993: YYDEBUG(993, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy843; if (yych <= '9') goto yy842; goto yy843; yy994: YYDEBUG(994, *YYCURSOR); yych = *++YYCURSOR; if (yych == '0') goto yy842; goto yy843; yy995: YYDEBUG(995, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'T') goto yy985; goto yy657; yy996: YYDEBUG(996, *YYCURSOR); yyaccept = 22; yych = *(YYMARKER = ++YYCURSOR); if (yych != '-') goto yy974; YYDEBUG(997, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '2') { if (yych <= '/') goto yy57; if (yych >= '1') goto yy999; } else { if (yych <= '3') goto yy1000; if (yych <= '9') goto yy980; goto yy57; } YYDEBUG(998, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'm') { if (yych <= '9') { if (yych <= '/') goto yy657; goto yy1001; } else { if (yych == 'T') goto yy985; goto yy657; } } else { if (yych <= 'r') { if (yych <= 'n') goto yy982; if (yych <= 'q') goto yy657; goto yy983; } else { if (yych <= 's') goto yy981; if (yych <= 't') goto yy984; goto yy657; } } yy999: YYDEBUG(999, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'm') { if (yych <= '9') { if (yych <= '/') goto yy657; goto yy1001; } else { if (yych == 'T') goto yy985; goto yy657; } } else { if (yych <= 'r') { if (yych <= 'n') goto yy982; if (yych <= 'q') goto yy657; goto yy983; } else { if (yych <= 's') goto yy981; if (yych <= 't') goto yy984; goto yy657; } } yy1000: YYDEBUG(1000, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'm') { if (yych <= '1') { if (yych <= '/') goto yy657; } else { if (yych == 'T') goto yy985; goto yy657; } } else { if (yych <= 'r') { if (yych <= 'n') goto yy982; if (yych <= 'q') goto yy657; goto yy983; } else { if (yych <= 's') goto yy981; if (yych <= 't') goto yy984; goto yy657; } } yy1001: YYDEBUG(1001, *YYCURSOR); yyaccept = 21; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych == 'T') goto yy1002; if (yych <= 'm') goto yy455; goto yy982; } else { if (yych <= 'r') { if (yych <= 'q') goto yy455; goto yy983; } else { if (yych <= 's') goto yy981; if (yych <= 't') goto yy984; goto yy455; } } yy1002: YYDEBUG(1002, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '1') goto yy1003; if (yych <= '2') goto yy1004; if (yych <= '9') goto yy988; goto yy57; yy1003: YYDEBUG(1003, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy1005; if (yych <= ':') goto yy989; goto yy57; yy1004: YYDEBUG(1004, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '4') goto yy1005; if (yych == ':') goto yy989; goto yy57; yy1005: YYDEBUG(1005, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy57; YYDEBUG(1006, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy1007; if (yych <= '9') goto yy991; goto yy57; yy1007: YYDEBUG(1007, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy1008; if (yych <= ':') goto yy992; goto yy57; yy1008: YYDEBUG(1008, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy57; YYDEBUG(1009, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy1010; if (yych <= '6') goto yy1011; if (yych <= '9') goto yy842; goto yy57; yy1010: YYDEBUG(1010, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy843; if (yych <= '9') goto yy1012; goto yy843; yy1011: YYDEBUG(1011, *YYCURSOR); yych = *++YYCURSOR; if (yych != '0') goto yy843; yy1012: YYDEBUG(1012, *YYCURSOR); yyaccept = 23; yych = *(YYMARKER = ++YYCURSOR); if (yych != '.') goto yy843; YYDEBUG(1013, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; yy1014: YYDEBUG(1014, *YYCURSOR); yyaccept = 23; YYMARKER = ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 9) YYFILL(9); yych = *YYCURSOR; YYDEBUG(1015, *YYCURSOR); if (yych <= '-') { if (yych == '+') goto yy1017; if (yych <= ',') goto yy843; goto yy1017; } else { if (yych <= '9') { if (yych <= '/') goto yy843; goto yy1014; } else { if (yych != 'G') goto yy843; } } YYDEBUG(1016, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy1023; goto yy57; yy1017: YYDEBUG(1017, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '1') goto yy1018; if (yych <= '2') goto yy1019; if (yych <= '9') goto yy1020; goto yy57; yy1018: YYDEBUG(1018, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy843; if (yych <= '9') goto yy1020; if (yych <= ':') goto yy1021; goto yy843; yy1019: YYDEBUG(1019, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '5') { if (yych <= '/') goto yy843; if (yych >= '5') goto yy1022; } else { if (yych <= '9') goto yy842; if (yych <= ':') goto yy1021; goto yy843; } yy1020: YYDEBUG(1020, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy843; if (yych <= '5') goto yy1022; if (yych <= '9') goto yy842; if (yych >= ';') goto yy843; yy1021: YYDEBUG(1021, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy843; if (yych <= '5') goto yy1022; if (yych <= '9') goto yy842; goto yy843; yy1022: YYDEBUG(1022, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy843; if (yych <= '9') goto yy842; goto yy843; yy1023: YYDEBUG(1023, *YYCURSOR); yych = *++YYCURSOR; if (yych != 'T') goto yy57; YYDEBUG(1024, *YYCURSOR); yych = *++YYCURSOR; if (yych == '+') goto yy1017; if (yych == '-') goto yy1017; goto yy57; yy1025: YYDEBUG(1025, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy1026; if (yych != 'c') goto yy57; yy1026: YYDEBUG(1026, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych == '-') goto yy767; goto yy794; } else { if (yych <= 'E') goto yy880; if (yych == 'e') goto yy880; goto yy794; } yy1027: YYDEBUG(1027, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'V') goto yy1028; if (yych != 'v') goto yy57; yy1028: YYDEBUG(1028, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych == '-') goto yy767; goto yy794; } else { if (yych <= 'E') goto yy887; if (yych == 'e') goto yy887; goto yy794; } yy1029: YYDEBUG(1029, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy1030; if (yych != 't') goto yy57; yy1030: YYDEBUG(1030, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'N') { if (yych == '-') goto yy767; goto yy794; } else { if (yych <= 'O') goto yy893; if (yych == 'o') goto yy893; goto yy794; } yy1031: YYDEBUG(1031, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy1032; if (yych != 'p') goto yy57; yy1032: YYDEBUG(1032, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych == '-') goto yy767; goto yy794; } else { if (yych <= 'T') goto yy1033; if (yych != 't') goto yy794; } yy1033: YYDEBUG(1033, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych == '-') goto yy767; goto yy794; } else { if (yych <= 'E') goto yy899; if (yych == 'e') goto yy899; goto yy794; } yy1034: YYDEBUG(1034, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy1037; if (yych == 'g') goto yy1037; goto yy57; yy1035: YYDEBUG(1035, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy1036; if (yych != 'r') goto yy57; yy1036: YYDEBUG(1036, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'H') { if (yych == '-') goto yy767; goto yy794; } else { if (yych <= 'I') goto yy906; if (yych == 'i') goto yy906; goto yy794; } yy1037: YYDEBUG(1037, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych == '-') goto yy767; goto yy794; } else { if (yych <= 'U') goto yy908; if (yych == 'u') goto yy908; goto yy794; } yy1038: YYDEBUG(1038, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych == 'R') goto yy1039; if (yych <= 'X') goto yy57; goto yy1040; } else { if (yych <= 'r') { if (yych <= 'q') goto yy57; } else { if (yych == 'y') goto yy1040; goto yy57; } } yy1039: YYDEBUG(1039, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'B') { if (yych == '-') goto yy767; goto yy794; } else { if (yych <= 'C') goto yy912; if (yych == 'c') goto yy912; goto yy794; } yy1040: YYDEBUG(1040, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych == '-') goto yy767; goto yy794; yy1041: YYDEBUG(1041, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy1042; if (yych != 'b') goto yy57; yy1042: YYDEBUG(1042, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'Q') { if (yych == '-') goto yy767; goto yy794; } else { if (yych <= 'R') goto yy915; if (yych == 'r') goto yy915; goto yy794; } yy1043: YYDEBUG(1043, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych == 'L') goto yy1047; if (yych <= 'M') goto yy57; goto yy1046; } else { if (yych <= 'l') { if (yych <= 'k') goto yy57; goto yy1047; } else { if (yych == 'n') goto yy1046; goto yy57; } } yy1044: YYDEBUG(1044, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy1045; if (yych != 'n') goto yy57; yy1045: YYDEBUG(1045, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych == '-') goto yy767; goto yy794; } else { if (yych <= 'U') goto yy922; if (yych == 'u') goto yy922; goto yy794; } yy1046: YYDEBUG(1046, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych == '-') goto yy767; goto yy794; } else { if (yych <= 'E') goto yy884; if (yych == 'e') goto yy884; goto yy794; } yy1047: YYDEBUG(1047, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'X') { if (yych == '-') goto yy767; goto yy794; } else { if (yych <= 'Y') goto yy884; if (yych == 'y') goto yy884; goto yy794; } yy1048: YYDEBUG(1048, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '.') { if (yych <= '\t') { if (yych <= 0x08) goto yy578; goto yy731; } else { if (yych <= ',') goto yy578; if (yych <= '-') goto yy732; goto yy731; } } else { if (yych <= 'U') { if (yych <= '/') goto yy730; if (yych <= 'T') goto yy578; goto yy78; } else { if (yych == 'u') goto yy78; goto yy578; } } yy1049: YYDEBUG(1049, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'P') { if (yych == 'C') goto yy129; if (yych <= 'O') goto yy57; goto yy586; } else { if (yych <= 'c') { if (yych <= 'b') goto yy57; goto yy129; } else { if (yych == 'p') goto yy586; goto yy57; } } yy1050: YYDEBUG(1050, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '9') { if (yych <= ',') { if (yych == '\t') goto yy1052; goto yy1054; } else { if (yych <= '-') goto yy1051; if (yych <= '.') goto yy731; if (yych <= '/') goto yy730; goto yy741; } } else { if (yych <= 'q') { if (yych == 'n') goto yy470; goto yy1054; } else { if (yych <= 'r') goto yy471; if (yych <= 's') goto yy464; if (yych <= 't') goto yy468; goto yy1054; } } yy1051: YYDEBUG(1051, *YYCURSOR); yych = *++YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case '0': goto yy1055; case '1': goto yy1056; case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy618; case 'A': case 'a': goto yy622; case 'D': case 'd': goto yy626; case 'F': case 'f': goto yy620; case 'J': case 'j': goto yy619; case 'M': case 'm': goto yy621; case 'N': case 'n': goto yy625; case 'O': case 'o': goto yy624; case 'S': case 's': goto yy623; default: goto yy578; } yy1052: YYDEBUG(1052, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy1054; if (yych <= '0') goto yy736; if (yych <= '1') goto yy737; if (yych <= '9') goto yy738; goto yy1054; yy1053: YYDEBUG(1053, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 13) YYFILL(13); yych = *YYCURSOR; yy1054: YYDEBUG(1054, *YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case '\t': case ' ': goto yy1053; case '-': case '.': goto yy577; case 'A': case 'a': goto yy574; case 'D': case 'd': goto yy466; case 'F': case 'f': goto yy467; case 'H': case 'h': goto yy64; case 'I': goto yy475; case 'J': case 'j': goto yy479; case 'M': case 'm': goto yy465; case 'N': case 'n': goto yy482; case 'O': case 'o': goto yy481; case 'S': case 's': goto yy463; case 'T': case 't': goto yy69; case 'V': goto yy477; case 'W': case 'w': goto yy68; case 'X': goto yy478; case 'Y': case 'y': goto yy67; default: goto yy57; } yy1055: YYDEBUG(1055, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '.') { if (yych <= ',') goto yy57; if (yych <= '-') goto yy655; goto yy602; } else { if (yych <= '/') goto yy57; if (yych <= '9') goto yy1057; goto yy57; } yy1056: YYDEBUG(1056, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '.') { if (yych <= ',') goto yy57; if (yych <= '-') goto yy655; goto yy602; } else { if (yych <= '/') goto yy57; if (yych >= '3') goto yy57; } yy1057: YYDEBUG(1057, *YYCURSOR); yych = *++YYCURSOR; if (yych <= ',') goto yy57; if (yych <= '-') goto yy1058; if (yych <= '.') goto yy602; goto yy57; yy1058: YYDEBUG(1058, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '2') { if (yych <= '/') goto yy57; if (yych >= '1') goto yy1060; } else { if (yych <= '3') goto yy1061; if (yych <= '9') goto yy659; goto yy57; } YYDEBUG(1059, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy657; if (yych <= '9') goto yy1062; if (yych <= 'm') goto yy657; goto yy661; } else { if (yych <= 'r') { if (yych <= 'q') goto yy657; goto yy662; } else { if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; goto yy657; } } yy1060: YYDEBUG(1060, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy657; if (yych <= '9') goto yy1062; if (yych <= 'm') goto yy657; goto yy661; } else { if (yych <= 'r') { if (yych <= 'q') goto yy657; goto yy662; } else { if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; goto yy657; } } yy1061: YYDEBUG(1061, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '1') { if (yych <= '/') goto yy657; } else { if (yych <= '9') goto yy604; if (yych <= 'm') goto yy657; goto yy661; } } else { if (yych <= 'r') { if (yych <= 'q') goto yy657; goto yy662; } else { if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; goto yy657; } } yy1062: YYDEBUG(1062, *YYCURSOR); yyaccept = 15; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy764; if (yych <= '9') goto yy605; if (yych <= 'm') goto yy764; goto yy661; } else { if (yych <= 'r') { if (yych <= 'q') goto yy764; goto yy662; } else { if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; goto yy764; } } yy1063: YYDEBUG(1063, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '9') { if (yych <= '-') { if (yych == '\t') goto yy1052; if (yych <= ',') goto yy1054; goto yy1051; } else { if (yych <= '.') goto yy1064; if (yych <= '/') goto yy730; if (yych <= '5') goto yy1066; goto yy741; } } else { if (yych <= 'q') { if (yych <= ':') goto yy1065; if (yych == 'n') goto yy470; goto yy1054; } else { if (yych <= 'r') goto yy471; if (yych <= 's') goto yy464; if (yych <= 't') goto yy468; goto yy1054; } } yy1064: YYDEBUG(1064, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '1') { if (yych <= '/') goto yy578; if (yych <= '0') goto yy1088; goto yy1089; } else { if (yych <= '5') goto yy1090; if (yych <= '9') goto yy1091; goto yy578; } yy1065: YYDEBUG(1065, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy1083; if (yych <= '9') goto yy1084; goto yy57; yy1066: YYDEBUG(1066, *YYCURSOR); yych = *++YYCURSOR; if (yych == '-') goto yy785; if (yych <= '/') goto yy61; if (yych >= ':') goto yy61; YYDEBUG(1067, *YYCURSOR); yyaccept = 24; yych = *(YYMARKER = ++YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case '\t': case ' ': case 'A': case 'D': case 'F': case 'H': case 'I': case 'J': case 'M': case 'N': case 'O': case 'S': case 'T': case 'V': case 'X': case 'Y': case 'a': case 'd': case 'f': case 'h': case 'j': case 'm': case 'n': case 'o': case 's': case 't': case 'w': case 'y': goto yy791; case '-': goto yy788; case '.': goto yy792; case '/': goto yy789; case '0': goto yy1069; case '1': goto yy1070; case '2': goto yy1071; case '3': goto yy1072; case '4': case '5': goto yy1073; case '6': goto yy1074; case '7': case '8': case '9': goto yy55; case ':': goto yy807; case 'W': goto yy810; default: goto yy1068; } yy1068: YYDEBUG(1068, *YYCURSOR); #line 1207 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("gnunocolon"); TIMELIB_INIT; switch (s->time->have_time) { case 0: s->time->h = timelib_get_nr((char **) &ptr, 2); s->time->i = timelib_get_nr((char **) &ptr, 2); s->time->s = 0; break; case 1: s->time->y = timelib_get_nr((char **) &ptr, 4); break; default: TIMELIB_DEINIT; add_error(s, "Double time specification"); return TIMELIB_ERROR; } s->time->have_time++; TIMELIB_DEINIT; return TIMELIB_GNU_NOCOLON; } #line 15748 "ext/date/lib/parse_date.c" yy1069: YYDEBUG(1069, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '0') goto yy1081; if (yych <= '9') goto yy1082; goto yy61; yy1070: YYDEBUG(1070, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '2') goto yy1080; if (yych <= '9') goto yy1079; goto yy61; yy1071: YYDEBUG(1071, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '9') goto yy1079; goto yy61; yy1072: YYDEBUG(1072, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '5') goto yy1077; if (yych <= '6') goto yy1078; if (yych <= '9') goto yy1075; goto yy61; yy1073: YYDEBUG(1073, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '9') goto yy1075; goto yy61; yy1074: YYDEBUG(1074, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '0') goto yy1075; if (yych <= '9') goto yy55; goto yy61; yy1075: YYDEBUG(1075, *YYCURSOR); yyaccept = 25; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 2) { goto yy55; } if (yych <= 'W') { if (yych <= 'F') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych >= ' ') goto yy61; } else { if (yych == 'D') goto yy61; if (yych >= 'F') goto yy61; } } else { if (yych <= 'M') { if (yych == 'H') goto yy61; if (yych >= 'M') goto yy61; } else { if (yych <= 'R') goto yy1076; if (yych <= 'T') goto yy61; if (yych >= 'W') goto yy61; } } } else { if (yych <= 'h') { if (yych <= 'd') { if (yych == 'Y') goto yy61; if (yych >= 'd') goto yy61; } else { if (yych == 'f') goto yy61; if (yych >= 'h') goto yy61; } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych >= 's') goto yy61; } else { if (yych <= 'w') { if (yych >= 'w') goto yy61; } else { if (yych == 'y') goto yy61; } } } } yy1076: YYDEBUG(1076, *YYCURSOR); #line 1253 "ext/date/lib/parse_date.re" { int tz_not_found; DEBUG_OUTPUT("iso8601nocolon"); TIMELIB_INIT; TIMELIB_HAVE_TIME(); s->time->h = timelib_get_nr((char **) &ptr, 2); s->time->i = timelib_get_nr((char **) &ptr, 2); s->time->s = timelib_get_nr((char **) &ptr, 2); if (*ptr != '\0') { s->time->z = timelib_get_zone((char **) &ptr, &s->time->dst, s->time, &tz_not_found, s->tzdb); if (tz_not_found) { add_error(s, "The timezone could not be found in the database"); } } TIMELIB_DEINIT; return TIMELIB_ISO_NOCOLON; } #line 15859 "ext/date/lib/parse_date.c" yy1077: YYDEBUG(1077, *YYCURSOR); yyaccept = 25; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'V') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy1076; goto yy61; } else { if (yych <= '/') goto yy1076; if (yych <= '9') goto yy821; if (yych <= 'C') goto yy1076; goto yy61; } } else { if (yych <= 'H') { if (yych == 'F') goto yy61; if (yych <= 'G') goto yy1076; goto yy61; } else { if (yych <= 'M') { if (yych <= 'L') goto yy1076; goto yy61; } else { if (yych <= 'R') goto yy1076; if (yych <= 'T') goto yy61; goto yy1076; } } } } else { if (yych <= 'h') { if (yych <= 'c') { if (yych == 'X') goto yy1076; if (yych <= 'Y') goto yy61; goto yy1076; } else { if (yych <= 'e') { if (yych <= 'd') goto yy61; goto yy1076; } else { if (yych == 'g') goto yy1076; goto yy61; } } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych <= 'r') goto yy1076; goto yy61; } else { if (yych <= 'w') { if (yych <= 'v') goto yy1076; goto yy61; } else { if (yych == 'y') goto yy61; goto yy1076; } } } } yy1078: YYDEBUG(1078, *YYCURSOR); yyaccept = 25; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'V') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy1076; goto yy61; } else { if (yych <= '6') { if (yych <= '/') goto yy1076; goto yy821; } else { if (yych <= '9') goto yy55; if (yych <= 'C') goto yy1076; goto yy61; } } } else { if (yych <= 'H') { if (yych == 'F') goto yy61; if (yych <= 'G') goto yy1076; goto yy61; } else { if (yych <= 'M') { if (yych <= 'L') goto yy1076; goto yy61; } else { if (yych <= 'R') goto yy1076; if (yych <= 'T') goto yy61; goto yy1076; } } } } else { if (yych <= 'h') { if (yych <= 'c') { if (yych == 'X') goto yy1076; if (yych <= 'Y') goto yy61; goto yy1076; } else { if (yych <= 'e') { if (yych <= 'd') goto yy61; goto yy1076; } else { if (yych == 'g') goto yy1076; goto yy61; } } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych <= 'r') goto yy1076; goto yy61; } else { if (yych <= 'w') { if (yych <= 'v') goto yy1076; goto yy61; } else { if (yych == 'y') goto yy61; goto yy1076; } } } } yy1079: YYDEBUG(1079, *YYCURSOR); yyaccept = 25; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'V') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy1076; goto yy61; } else { if (yych <= '/') goto yy1076; if (yych <= '9') goto yy821; if (yych <= 'C') goto yy1076; goto yy61; } } else { if (yych <= 'H') { if (yych == 'F') goto yy61; if (yych <= 'G') goto yy1076; goto yy61; } else { if (yych <= 'M') { if (yych <= 'L') goto yy1076; goto yy61; } else { if (yych <= 'R') goto yy1076; if (yych <= 'T') goto yy61; goto yy1076; } } } } else { if (yych <= 'h') { if (yych <= 'c') { if (yych == 'X') goto yy1076; if (yych <= 'Y') goto yy61; goto yy1076; } else { if (yych <= 'e') { if (yych <= 'd') goto yy61; goto yy1076; } else { if (yych == 'g') goto yy1076; goto yy61; } } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych <= 'r') goto yy1076; goto yy61; } else { if (yych <= 'w') { if (yych <= 'v') goto yy1076; goto yy61; } else { if (yych == 'y') goto yy61; goto yy1076; } } } } yy1080: YYDEBUG(1080, *YYCURSOR); yyaccept = 25; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych <= '9') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy1076; goto yy61; } else { if (yych <= '0') { if (yych <= '/') goto yy1076; goto yy845; } else { if (yych <= '2') goto yy846; if (yych <= '3') goto yy847; goto yy821; } } } else { if (yych <= 'G') { if (yych <= 'D') { if (yych <= 'C') goto yy1076; goto yy61; } else { if (yych == 'F') goto yy61; goto yy1076; } } else { if (yych <= 'L') { if (yych <= 'H') goto yy61; goto yy1076; } else { if (yych <= 'M') goto yy61; if (yych <= 'R') goto yy1076; goto yy61; } } } } else { if (yych <= 'g') { if (yych <= 'Y') { if (yych == 'W') goto yy61; if (yych <= 'X') goto yy1076; goto yy61; } else { if (yych <= 'd') { if (yych <= 'c') goto yy1076; goto yy61; } else { if (yych == 'f') goto yy61; goto yy1076; } } } else { if (yych <= 't') { if (yych <= 'l') { if (yych <= 'h') goto yy61; goto yy1076; } else { if (yych <= 'm') goto yy61; if (yych <= 'r') goto yy1076; goto yy61; } } else { if (yych <= 'w') { if (yych <= 'v') goto yy1076; goto yy61; } else { if (yych == 'y') goto yy61; goto yy1076; } } } } yy1081: YYDEBUG(1081, *YYCURSOR); yyaccept = 25; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych <= '9') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy1076; goto yy61; } else { if (yych <= '0') { if (yych <= '/') goto yy1076; goto yy877; } else { if (yych <= '2') goto yy846; if (yych <= '3') goto yy847; goto yy821; } } } else { if (yych <= 'G') { if (yych <= 'D') { if (yych <= 'C') goto yy1076; goto yy61; } else { if (yych == 'F') goto yy61; goto yy1076; } } else { if (yych <= 'L') { if (yych <= 'H') goto yy61; goto yy1076; } else { if (yych <= 'M') goto yy61; if (yych <= 'R') goto yy1076; goto yy61; } } } } else { if (yych <= 'g') { if (yych <= 'Y') { if (yych == 'W') goto yy61; if (yych <= 'X') goto yy1076; goto yy61; } else { if (yych <= 'd') { if (yych <= 'c') goto yy1076; goto yy61; } else { if (yych == 'f') goto yy61; goto yy1076; } } } else { if (yych <= 't') { if (yych <= 'l') { if (yych <= 'h') goto yy61; goto yy1076; } else { if (yych <= 'm') goto yy61; if (yych <= 'r') goto yy1076; goto yy61; } } else { if (yych <= 'w') { if (yych <= 'v') goto yy1076; goto yy61; } else { if (yych == 'y') goto yy61; goto yy1076; } } } } yy1082: YYDEBUG(1082, *YYCURSOR); yyaccept = 25; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych <= '9') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy1076; goto yy61; } else { if (yych <= '0') { if (yych <= '/') goto yy1076; goto yy845; } else { if (yych <= '2') goto yy846; if (yych <= '3') goto yy847; goto yy821; } } } else { if (yych <= 'G') { if (yych <= 'D') { if (yych <= 'C') goto yy1076; goto yy61; } else { if (yych == 'F') goto yy61; goto yy1076; } } else { if (yych <= 'L') { if (yych <= 'H') goto yy61; goto yy1076; } else { if (yych <= 'M') goto yy61; if (yych <= 'R') goto yy1076; goto yy61; } } } } else { if (yych <= 'g') { if (yych <= 'Y') { if (yych == 'W') goto yy61; if (yych <= 'X') goto yy1076; goto yy61; } else { if (yych <= 'd') { if (yych <= 'c') goto yy1076; goto yy61; } else { if (yych == 'f') goto yy61; goto yy1076; } } } else { if (yych <= 't') { if (yych <= 'l') { if (yych <= 'h') goto yy61; goto yy1076; } else { if (yych <= 'm') goto yy61; if (yych <= 'r') goto yy1076; goto yy61; } } else { if (yych <= 'w') { if (yych <= 'v') goto yy1076; goto yy61; } else { if (yych == 'y') goto yy61; goto yy1076; } } } } yy1083: YYDEBUG(1083, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy1085; goto yy491; } else { if (yych <= '9') goto yy1084; if (yych <= ':') goto yy1085; goto yy491; } yy1084: YYDEBUG(1084, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy1085; if (yych != ':') goto yy491; yy1085: YYDEBUG(1085, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy1086; if (yych <= '6') goto yy1087; if (yych <= '9') goto yy496; goto yy57; yy1086: YYDEBUG(1086, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy497; if (yych <= '/') goto yy491; if (yych <= '9') goto yy496; goto yy491; yy1087: YYDEBUG(1087, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy497; if (yych == '0') goto yy496; goto yy491; yy1088: YYDEBUG(1088, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ',') goto yy491; if (yych <= '-') goto yy602; goto yy1092; } else { if (yych <= '/') goto yy491; if (yych <= '9') goto yy1091; if (yych <= ':') goto yy1085; goto yy491; } yy1089: YYDEBUG(1089, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') goto yy491; if (yych <= '-') goto yy602; if (yych <= '.') goto yy1092; goto yy491; } else { if (yych <= '2') goto yy1091; if (yych <= '9') goto yy1084; if (yych <= ':') goto yy1085; goto yy491; } yy1090: YYDEBUG(1090, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ',') goto yy491; if (yych <= '-') goto yy602; goto yy1092; } else { if (yych <= '/') goto yy491; if (yych <= '9') goto yy1084; if (yych <= ':') goto yy1085; goto yy491; } yy1091: YYDEBUG(1091, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ',') goto yy491; if (yych <= '-') goto yy602; } else { if (yych == ':') goto yy1085; goto yy491; } yy1092: YYDEBUG(1092, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy1093; if (yych <= '6') goto yy1094; if (yych <= '9') goto yy610; goto yy57; yy1093: YYDEBUG(1093, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy497; if (yych <= '/') goto yy491; if (yych <= '9') goto yy1095; goto yy491; yy1094: YYDEBUG(1094, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy497; goto yy491; } else { if (yych <= '0') goto yy1095; if (yych <= '9') goto yy611; goto yy491; } yy1095: YYDEBUG(1095, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy497; if (yych <= '/') goto yy491; if (yych <= '9') goto yy605; goto yy491; yy1096: YYDEBUG(1096, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '9') { if (yych <= '-') { if (yych == '\t') goto yy460; if (yych <= ',') goto yy462; goto yy1051; } else { if (yych <= '.') goto yy474; if (yych <= '/') goto yy472; if (yych <= '5') goto yy1066; goto yy741; } } else { if (yych <= 'q') { if (yych <= ':') goto yy483; if (yych == 'n') goto yy470; goto yy462; } else { if (yych <= 'r') goto yy471; if (yych <= 's') goto yy464; if (yych <= 't') goto yy468; goto yy462; } } yy1097: YYDEBUG(1097, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '9') { if (yych <= '-') { if (yych == '\t') goto yy1052; if (yych <= ',') goto yy1054; goto yy1051; } else { if (yych <= '.') goto yy1064; if (yych <= '/') goto yy472; if (yych <= '5') goto yy1066; goto yy741; } } else { if (yych <= 'q') { if (yych <= ':') goto yy1065; if (yych == 'n') goto yy470; goto yy1054; } else { if (yych <= 'r') goto yy471; if (yych <= 's') goto yy464; if (yych <= 't') goto yy468; goto yy1054; } } yy1098: YYDEBUG(1098, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy142; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'e') goto yy1099; if (yych <= 'z') goto yy142; goto yy4; } } yy1099: YYDEBUG(1099, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'V') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'U') goto yy143; } } else { if (yych <= 'u') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'v') goto yy1100; if (yych <= 'z') goto yy143; goto yy4; } } yy1100: YYDEBUG(1100, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'I') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'H') goto yy144; } } else { if (yych <= 'h') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'i') goto yy1101; if (yych <= 'z') goto yy144; goto yy4; } } yy1101: YYDEBUG(1101, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'N') goto yy145; } } else { if (yych <= 'n') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'o') goto yy1102; if (yych <= 'z') goto yy145; goto yy4; } } yy1102: YYDEBUG(1102, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'U') goto yy1103; if (yych != 'u') goto yy4; } yy1103: YYDEBUG(1103, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy1104; if (yych != 's') goto yy57; yy1104: YYDEBUG(1104, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\t') goto yy1105; if (yych != ' ') goto yy57; yy1105: YYDEBUG(1105, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 11) YYFILL(11); yych = *YYCURSOR; yy1106: YYDEBUG(1106, *YYCURSOR); if (yych <= 'W') { if (yych <= 'F') { if (yych <= ' ') { if (yych == '\t') goto yy1105; if (yych <= 0x1F) goto yy57; goto yy1105; } else { if (yych == 'D') goto yy1110; if (yych <= 'E') goto yy57; goto yy1111; } } else { if (yych <= 'M') { if (yych == 'H') goto yy1109; if (yych <= 'L') goto yy57; goto yy1108; } else { if (yych <= 'S') { if (yych <= 'R') goto yy57; } else { if (yych <= 'T') goto yy1114; if (yych <= 'V') goto yy57; goto yy1113; } } } } else { if (yych <= 'l') { if (yych <= 'd') { if (yych == 'Y') goto yy1112; if (yych <= 'c') goto yy57; goto yy1110; } else { if (yych <= 'f') { if (yych <= 'e') goto yy57; goto yy1111; } else { if (yych == 'h') goto yy1109; goto yy57; } } } else { if (yych <= 't') { if (yych <= 'm') goto yy1108; if (yych <= 'r') goto yy57; if (yych >= 't') goto yy1114; } else { if (yych <= 'w') { if (yych <= 'v') goto yy57; goto yy1113; } else { if (yych == 'y') goto yy1112; goto yy57; } } } } yy1107: YYDEBUG(1107, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= 'D') { if (yych == 'A') goto yy1179; goto yy57; } else { if (yych <= 'E') goto yy1180; if (yych <= 'T') goto yy57; goto yy1178; } } else { if (yych <= 'd') { if (yych == 'a') goto yy1179; goto yy57; } else { if (yych <= 'e') goto yy1180; if (yych == 'u') goto yy1178; goto yy57; } } yy1108: YYDEBUG(1108, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'I') goto yy1170; if (yych <= 'N') goto yy57; goto yy1169; } else { if (yych <= 'i') { if (yych <= 'h') goto yy57; goto yy1170; } else { if (yych == 'o') goto yy1169; goto yy57; } } yy1109: YYDEBUG(1109, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy1167; if (yych == 'o') goto yy1167; goto yy57; yy1110: YYDEBUG(1110, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1166; if (yych == 'a') goto yy1166; goto yy57; yy1111: YYDEBUG(1111, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych == 'O') goto yy1151; if (yych <= 'Q') goto yy57; goto yy1150; } else { if (yych <= 'o') { if (yych <= 'n') goto yy57; goto yy1151; } else { if (yych == 'r') goto yy1150; goto yy57; } } yy1112: YYDEBUG(1112, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy1147; if (yych == 'e') goto yy1147; goto yy57; yy1113: YYDEBUG(1113, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy1133; if (yych == 'e') goto yy1133; goto yy57; yy1114: YYDEBUG(1114, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'H') goto yy1115; if (yych <= 'T') goto yy57; goto yy1116; } else { if (yych <= 'h') { if (yych <= 'g') goto yy57; } else { if (yych == 'u') goto yy1116; goto yy57; } } yy1115: YYDEBUG(1115, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy1128; if (yych == 'u') goto yy1128; goto yy57; yy1116: YYDEBUG(1116, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy1117; if (yych != 'e') goto yy57; yy1117: YYDEBUG(1117, *YYCURSOR); yyaccept = 26; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ' ') { if (yych == '\t') goto yy1119; if (yych >= ' ') goto yy1119; } else { if (yych <= 'S') { if (yych >= 'S') goto yy1121; } else { if (yych == 's') goto yy1121; } } yy1118: YYDEBUG(1118, *YYCURSOR); #line 1649 "ext/date/lib/parse_date.re" { timelib_sll i; int behavior = 0; DEBUG_OUTPUT("relativetext"); TIMELIB_INIT; TIMELIB_HAVE_RELATIVE(); while(*ptr) { i = timelib_get_relative_text((char **) &ptr, &behavior); timelib_eat_spaces((char **) &ptr); timelib_set_relative((char **) &ptr, i, behavior, s); } TIMELIB_DEINIT; return TIMELIB_RELATIVE; } #line 16773 "ext/date/lib/parse_date.c" yy1119: YYDEBUG(1119, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; YYDEBUG(1120, *YYCURSOR); if (yych <= ' ') { if (yych == '\t') goto yy1119; if (yych <= 0x1F) goto yy57; goto yy1119; } else { if (yych <= 'O') { if (yych <= 'N') goto yy57; goto yy1125; } else { if (yych == 'o') goto yy1125; goto yy57; } } yy1121: YYDEBUG(1121, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy1122; if (yych != 'd') goto yy57; yy1122: YYDEBUG(1122, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1123; if (yych != 'a') goto yy57; yy1123: YYDEBUG(1123, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy1124; if (yych != 'y') goto yy57; yy1124: YYDEBUG(1124, *YYCURSOR); yyaccept = 26; yych = *(YYMARKER = ++YYCURSOR); if (yych == '\t') goto yy1119; if (yych == ' ') goto yy1119; goto yy1118; yy1125: YYDEBUG(1125, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy1126; if (yych != 'f') goto yy57; yy1126: YYDEBUG(1126, *YYCURSOR); ++YYCURSOR; YYDEBUG(1127, *YYCURSOR); #line 1122 "ext/date/lib/parse_date.re" { timelib_sll i; int behavior = 0; DEBUG_OUTPUT("weekdayof"); TIMELIB_INIT; TIMELIB_HAVE_RELATIVE(); TIMELIB_HAVE_SPECIAL_RELATIVE(); i = timelib_get_relative_text((char **) &ptr, &behavior); timelib_eat_spaces((char **) &ptr); if (i > 0) { /* first, second... etc */ s->time->relative.special.type = TIMELIB_SPECIAL_DAY_OF_WEEK_IN_MONTH; timelib_set_relative((char **) &ptr, i, 1, s); } else { /* last */ s->time->relative.special.type = TIMELIB_SPECIAL_LAST_DAY_OF_WEEK_IN_MONTH; timelib_set_relative((char **) &ptr, i, behavior, s); } TIMELIB_DEINIT; return TIMELIB_WEEK_DAY_OF_MONTH; } #line 16845 "ext/date/lib/parse_date.c" yy1128: YYDEBUG(1128, *YYCURSOR); yyaccept = 26; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ' ') { if (yych == '\t') goto yy1119; if (yych <= 0x1F) goto yy1118; goto yy1119; } else { if (yych <= 'R') { if (yych <= 'Q') goto yy1118; } else { if (yych != 'r') goto yy1118; } } YYDEBUG(1129, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy1130; if (yych != 's') goto yy57; yy1130: YYDEBUG(1130, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy1131; if (yych != 'd') goto yy57; yy1131: YYDEBUG(1131, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1132; if (yych != 'a') goto yy57; yy1132: YYDEBUG(1132, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy1124; if (yych == 'y') goto yy1124; goto yy57; yy1133: YYDEBUG(1133, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= 'C') goto yy57; if (yych <= 'D') goto yy1135; } else { if (yych <= 'c') goto yy57; if (yych <= 'd') goto yy1135; if (yych >= 'f') goto yy57; } YYDEBUG(1134, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'K') goto yy1141; if (yych == 'k') goto yy1141; goto yy57; yy1135: YYDEBUG(1135, *YYCURSOR); yyaccept = 26; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ' ') { if (yych == '\t') goto yy1119; if (yych <= 0x1F) goto yy1118; goto yy1119; } else { if (yych <= 'N') { if (yych <= 'M') goto yy1118; } else { if (yych != 'n') goto yy1118; } } YYDEBUG(1136, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy1137; if (yych != 'e') goto yy57; yy1137: YYDEBUG(1137, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy1138; if (yych != 's') goto yy57; yy1138: YYDEBUG(1138, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy1139; if (yych != 'd') goto yy57; yy1139: YYDEBUG(1139, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1140; if (yych != 'a') goto yy57; yy1140: YYDEBUG(1140, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy1124; if (yych == 'y') goto yy1124; goto yy57; yy1141: YYDEBUG(1141, *YYCURSOR); yyaccept = 27; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych == 'D') goto yy1144; if (yych >= 'S') goto yy1143; } else { if (yych <= 'd') { if (yych >= 'd') goto yy1144; } else { if (yych == 's') goto yy1143; } } yy1142: YYDEBUG(1142, *YYCURSOR); #line 1625 "ext/date/lib/parse_date.re" { timelib_sll i; int behavior = 0; DEBUG_OUTPUT("relativetextweek"); TIMELIB_INIT; TIMELIB_HAVE_RELATIVE(); while(*ptr) { i = timelib_get_relative_text((char **) &ptr, &behavior); timelib_eat_spaces((char **) &ptr); timelib_set_relative((char **) &ptr, i, behavior, s); s->time->relative.weekday_behavior = 2; /* to handle the format weekday + last/this/next week */ if (s->time->relative.have_weekday_relative == 0) { TIMELIB_HAVE_WEEKDAY_RELATIVE(); s->time->relative.weekday = 1; } } TIMELIB_DEINIT; return TIMELIB_RELATIVE; } #line 16976 "ext/date/lib/parse_date.c" yy1143: YYDEBUG(1143, *YYCURSOR); yych = *++YYCURSOR; goto yy1118; yy1144: YYDEBUG(1144, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1145; if (yych != 'a') goto yy57; yy1145: YYDEBUG(1145, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy1146; if (yych != 'y') goto yy57; yy1146: YYDEBUG(1146, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy1143; if (yych == 's') goto yy1143; goto yy1118; yy1147: YYDEBUG(1147, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1148; if (yych != 'a') goto yy57; yy1148: YYDEBUG(1148, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy1149; if (yych != 'r') goto yy57; yy1149: YYDEBUG(1149, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy1143; if (yych == 's') goto yy1143; goto yy1118; yy1150: YYDEBUG(1150, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy1163; if (yych == 'i') goto yy1163; goto yy57; yy1151: YYDEBUG(1151, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy1152; if (yych != 'r') goto yy57; yy1152: YYDEBUG(1152, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy1153; if (yych != 't') goto yy57; yy1153: YYDEBUG(1153, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych == 'H') goto yy1155; if (yych <= 'M') goto yy57; } else { if (yych <= 'h') { if (yych <= 'g') goto yy57; goto yy1155; } else { if (yych != 'n') goto yy57; } } YYDEBUG(1154, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy1160; if (yych == 'i') goto yy1160; goto yy57; yy1155: YYDEBUG(1155, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy1156; if (yych != 'n') goto yy57; yy1156: YYDEBUG(1156, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy1157; if (yych != 'i') goto yy57; yy1157: YYDEBUG(1157, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy1158; if (yych != 'g') goto yy57; yy1158: YYDEBUG(1158, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy1159; if (yych != 'h') goto yy57; yy1159: YYDEBUG(1159, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy1149; if (yych == 't') goto yy1149; goto yy57; yy1160: YYDEBUG(1160, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy1161; if (yych != 'g') goto yy57; yy1161: YYDEBUG(1161, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy1162; if (yych != 'h') goto yy57; yy1162: YYDEBUG(1162, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy1149; if (yych == 't') goto yy1149; goto yy57; yy1163: YYDEBUG(1163, *YYCURSOR); yyaccept = 26; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ' ') { if (yych == '\t') goto yy1119; if (yych <= 0x1F) goto yy1118; goto yy1119; } else { if (yych <= 'D') { if (yych <= 'C') goto yy1118; } else { if (yych != 'd') goto yy1118; } } YYDEBUG(1164, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1165; if (yych != 'a') goto yy57; yy1165: YYDEBUG(1165, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy1124; if (yych == 'y') goto yy1124; goto yy57; yy1166: YYDEBUG(1166, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy1149; if (yych == 'y') goto yy1149; goto yy57; yy1167: YYDEBUG(1167, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy1168; if (yych != 'u') goto yy57; yy1168: YYDEBUG(1168, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy1149; if (yych == 'r') goto yy1149; goto yy57; yy1169: YYDEBUG(1169, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy1174; if (yych == 'n') goto yy1174; goto yy57; yy1170: YYDEBUG(1170, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy1171; if (yych != 'n') goto yy57; yy1171: YYDEBUG(1171, *YYCURSOR); yyaccept = 26; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'U') { if (yych == 'S') goto yy1143; if (yych <= 'T') goto yy1118; } else { if (yych <= 's') { if (yych <= 'r') goto yy1118; goto yy1143; } else { if (yych != 'u') goto yy1118; } } YYDEBUG(1172, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy1173; if (yych != 't') goto yy57; yy1173: YYDEBUG(1173, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy1149; if (yych == 'e') goto yy1149; goto yy57; yy1174: YYDEBUG(1174, *YYCURSOR); yyaccept = 26; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych <= 0x1F) { if (yych == '\t') goto yy1119; goto yy1118; } else { if (yych <= ' ') goto yy1119; if (yych <= 'C') goto yy1118; } } else { if (yych <= 'c') { if (yych == 'T') goto yy1176; goto yy1118; } else { if (yych <= 'd') goto yy1175; if (yych == 't') goto yy1176; goto yy1118; } } yy1175: YYDEBUG(1175, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1177; if (yych == 'a') goto yy1177; goto yy57; yy1176: YYDEBUG(1176, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy1149; if (yych == 'h') goto yy1149; goto yy57; yy1177: YYDEBUG(1177, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy1124; if (yych == 'y') goto yy1124; goto yy57; yy1178: YYDEBUG(1178, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy1189; if (yych == 'n') goto yy1189; goto yy57; yy1179: YYDEBUG(1179, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy1184; if (yych == 't') goto yy1184; goto yy57; yy1180: YYDEBUG(1180, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy1181; if (yych != 'c') goto yy57; yy1181: YYDEBUG(1181, *YYCURSOR); yyaccept = 26; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych == 'O') goto yy1182; if (yych <= 'R') goto yy1118; goto yy1143; } else { if (yych <= 'o') { if (yych <= 'n') goto yy1118; } else { if (yych == 's') goto yy1143; goto yy1118; } } yy1182: YYDEBUG(1182, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy1183; if (yych != 'n') goto yy57; yy1183: YYDEBUG(1183, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy1149; if (yych == 'd') goto yy1149; goto yy57; yy1184: YYDEBUG(1184, *YYCURSOR); yyaccept = 26; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ' ') { if (yych == '\t') goto yy1119; if (yych <= 0x1F) goto yy1118; goto yy1119; } else { if (yych <= 'U') { if (yych <= 'T') goto yy1118; } else { if (yych != 'u') goto yy1118; } } YYDEBUG(1185, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy1186; if (yych != 'r') goto yy57; yy1186: YYDEBUG(1186, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy1187; if (yych != 'd') goto yy57; yy1187: YYDEBUG(1187, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1188; if (yych != 'a') goto yy57; yy1188: YYDEBUG(1188, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy1124; if (yych == 'y') goto yy1124; goto yy57; yy1189: YYDEBUG(1189, *YYCURSOR); yyaccept = 26; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ' ') { if (yych == '\t') goto yy1119; if (yych <= 0x1F) goto yy1118; goto yy1119; } else { if (yych <= 'D') { if (yych <= 'C') goto yy1118; } else { if (yych != 'd') goto yy1118; } } YYDEBUG(1190, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1191; if (yych != 'a') goto yy57; yy1191: YYDEBUG(1191, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy1124; if (yych == 'y') goto yy1124; goto yy57; yy1192: YYDEBUG(1192, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'E') goto yy1099; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'd') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'e') goto yy1193; if (yych <= 'z') goto yy147; goto yy4; } } } yy1193: YYDEBUG(1193, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'U') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'V') goto yy1100; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'u') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 'v') goto yy1194; if (yych <= 'z') goto yy151; goto yy4; } } } yy1194: YYDEBUG(1194, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'H') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'I') goto yy1101; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'h') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'i') goto yy1195; if (yych <= 'z') goto yy152; goto yy4; } } } yy1195: YYDEBUG(1195, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'N') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'O') goto yy1102; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'n') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'o') goto yy1196; if (yych <= 'z') goto yy153; goto yy4; } } } yy1196: YYDEBUG(1196, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'U') goto yy1103; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'u') goto yy1197; if (yych <= 'z') goto yy154; goto yy4; } } yy1197: YYDEBUG(1197, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy1104; if (yych != 's') goto yy155; YYDEBUG(1198, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 16) { goto yy154; } if (yych <= ',') { if (yych <= '\t') { if (yych <= 0x08) goto yy57; goto yy1105; } else { if (yych == ' ') goto yy1105; goto yy57; } } else { if (yych <= '/') { if (yych == '.') goto yy57; goto yy148; } else { if (yych == '_') goto yy148; goto yy57; } } yy1199: YYDEBUG(1199, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'G') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'F') goto yy142; goto yy1213; } } else { if (yych <= 'f') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'g') goto yy1213; if (yych <= 'z') goto yy142; goto yy4; } } yy1200: YYDEBUG(1200, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy142; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'e') goto yy1201; if (yych <= 'z') goto yy142; goto yy4; } } yy1201: YYDEBUG(1201, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'V') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'U') goto yy143; } } else { if (yych <= 'u') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'v') goto yy1202; if (yych <= 'z') goto yy143; goto yy4; } } yy1202: YYDEBUG(1202, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy144; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'e') goto yy1203; if (yych <= 'z') goto yy144; goto yy4; } } yy1203: YYDEBUG(1203, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'M') goto yy145; } } else { if (yych <= 'm') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'n') goto yy1204; if (yych <= 'z') goto yy145; goto yy4; } } yy1204: YYDEBUG(1204, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'T') goto yy1205; if (yych != 't') goto yy4; } yy1205: YYDEBUG(1205, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy1206; if (yych != 'h') goto yy57; yy1206: YYDEBUG(1206, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\t') goto yy1207; if (yych != ' ') goto yy57; yy1207: YYDEBUG(1207, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 11) YYFILL(11); yych = *YYCURSOR; yy1208: YYDEBUG(1208, *YYCURSOR); if (yych <= 'W') { if (yych <= 'F') { if (yych <= ' ') { if (yych == '\t') goto yy1207; if (yych <= 0x1F) goto yy57; goto yy1207; } else { if (yych == 'D') goto yy1110; if (yych <= 'E') goto yy57; goto yy1111; } } else { if (yych <= 'M') { if (yych == 'H') goto yy1109; if (yych <= 'L') goto yy57; goto yy1108; } else { if (yych <= 'S') { if (yych <= 'R') goto yy57; goto yy1107; } else { if (yych <= 'T') goto yy1114; if (yych <= 'V') goto yy57; } } } } else { if (yych <= 'l') { if (yych <= 'd') { if (yych == 'Y') goto yy1112; if (yych <= 'c') goto yy57; goto yy1110; } else { if (yych <= 'f') { if (yych <= 'e') goto yy57; goto yy1111; } else { if (yych == 'h') goto yy1109; goto yy57; } } } else { if (yych <= 't') { if (yych <= 'm') goto yy1108; if (yych <= 'r') goto yy57; if (yych <= 's') goto yy1107; goto yy1114; } else { if (yych <= 'w') { if (yych <= 'v') goto yy57; } else { if (yych == 'y') goto yy1112; goto yy57; } } } } YYDEBUG(1209, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy1210; if (yych != 'e') goto yy57; yy1210: YYDEBUG(1210, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= 'C') goto yy57; if (yych <= 'D') goto yy1135; } else { if (yych <= 'c') goto yy57; if (yych <= 'd') goto yy1135; if (yych >= 'f') goto yy57; } YYDEBUG(1211, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'K') goto yy1212; if (yych != 'k') goto yy57; yy1212: YYDEBUG(1212, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych == 'D') goto yy1144; if (yych <= 'R') goto yy57; goto yy1143; } else { if (yych <= 'd') { if (yych <= 'c') goto yy57; goto yy1144; } else { if (yych == 's') goto yy1143; goto yy57; } } yy1213: YYDEBUG(1213, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'H') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'G') goto yy143; } } else { if (yych <= 'g') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'h') goto yy1214; if (yych <= 'z') goto yy143; goto yy4; } } yy1214: YYDEBUG(1214, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy144; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 't') goto yy1215; if (yych <= 'z') goto yy144; goto yy4; } } yy1215: YYDEBUG(1215, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych <= 0x1F) { if (yych == '\t') goto yy1207; goto yy4; } else { if (yych <= ' ') goto yy1207; if (yych == ')') goto yy140; goto yy4; } } else { if (yych <= '`') { if (yych == 'H') goto yy1216; if (yych <= 'Z') goto yy145; goto yy4; } else { if (yych == 'h') goto yy1216; if (yych <= 'z') goto yy145; goto yy4; } } yy1216: YYDEBUG(1216, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy1207; goto yy4; } else { if (yych <= ' ') goto yy1207; if (yych == ')') goto yy140; goto yy4; } yy1217: YYDEBUG(1217, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'F') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'G') goto yy1213; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'f') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'g') goto yy1225; if (yych <= 'z') goto yy147; goto yy4; } } } yy1218: YYDEBUG(1218, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'E') goto yy1201; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'd') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'e') goto yy1219; if (yych <= 'z') goto yy147; goto yy4; } } } yy1219: YYDEBUG(1219, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'U') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'V') goto yy1202; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'u') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 'v') goto yy1220; if (yych <= 'z') goto yy151; goto yy4; } } } yy1220: YYDEBUG(1220, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'E') goto yy1203; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'd') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'e') goto yy1221; if (yych <= 'z') goto yy152; goto yy4; } } } yy1221: YYDEBUG(1221, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'M') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'N') goto yy1204; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'm') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'n') goto yy1222; if (yych <= 'z') goto yy153; goto yy4; } } } yy1222: YYDEBUG(1222, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'T') goto yy1205; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 't') goto yy1223; if (yych <= 'z') goto yy154; goto yy4; } } yy1223: YYDEBUG(1223, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy1206; if (yych != 'h') goto yy155; yy1224: YYDEBUG(1224, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 16) { goto yy154; } if (yych <= ',') { if (yych <= '\t') { if (yych <= 0x08) goto yy57; goto yy1207; } else { if (yych == ' ') goto yy1207; goto yy57; } } else { if (yych <= '/') { if (yych == '.') goto yy57; goto yy148; } else { if (yych == '_') goto yy148; goto yy57; } } yy1225: YYDEBUG(1225, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'G') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'H') goto yy1214; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'g') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 'h') goto yy1226; if (yych <= 'z') goto yy151; goto yy4; } } } yy1226: YYDEBUG(1226, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1215; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 't') goto yy1227; if (yych <= 'z') goto yy152; goto yy4; } } } yy1227: YYDEBUG(1227, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy4; goto yy1207; } else { if (yych == ' ') goto yy1207; goto yy4; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; goto yy148; } } } else { if (yych <= '^') { if (yych <= 'G') { if (yych <= '@') goto yy4; goto yy145; } else { if (yych <= 'H') goto yy1216; if (yych <= 'Z') goto yy145; goto yy4; } } else { if (yych <= 'g') { if (yych <= '_') goto yy148; if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'h') goto yy1228; if (yych <= 'z') goto yy153; goto yy4; } } } yy1228: YYDEBUG(1228, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 16) { goto yy154; } if (yych <= ')') { if (yych <= 0x1F) { if (yych == '\t') goto yy1207; goto yy4; } else { if (yych <= ' ') goto yy1207; if (yych <= '(') goto yy4; goto yy140; } } else { if (yych <= '.') { if (yych == '-') goto yy148; goto yy4; } else { if (yych <= '/') goto yy148; if (yych == '_') goto yy148; goto yy4; } } yy1229: YYDEBUG(1229, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'V') { if (yych <= 'B') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy142; } else { if (yych <= 'O') { if (yych <= 'C') goto yy1245; goto yy142; } else { if (yych <= 'P') goto yy1247; if (yych <= 'U') goto yy142; goto yy1246; } } } else { if (yych <= 'o') { if (yych <= '`') { if (yych <= 'Z') goto yy142; goto yy4; } else { if (yych == 'c') goto yy1245; goto yy142; } } else { if (yych <= 'u') { if (yych <= 'p') goto yy1247; goto yy142; } else { if (yych <= 'v') goto yy1246; if (yych <= 'z') goto yy142; goto yy4; } } } yy1230: YYDEBUG(1230, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy142; goto yy1240; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 't') goto yy1240; if (yych <= 'z') goto yy142; goto yy4; } } yy1231: YYDEBUG(1231, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'X') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'W') goto yy142; goto yy1237; } } else { if (yych <= 'w') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'x') goto yy1237; if (yych <= 'z') goto yy142; goto yy4; } } yy1232: YYDEBUG(1232, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'M') goto yy142; } } else { if (yych <= 'm') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'n') goto yy1233; if (yych <= 'z') goto yy142; goto yy4; } } yy1233: YYDEBUG(1233, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'D') { if (yych <= ')') { if (yych <= '(') goto yy167; goto yy140; } else { if (yych <= '@') goto yy167; if (yych <= 'C') goto yy143; } } else { if (yych <= 'c') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy167; goto yy143; } else { if (yych <= 'd') goto yy1234; if (yych <= 'z') goto yy143; goto yy167; } } yy1234: YYDEBUG(1234, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; } else { if (yych <= '`') { if (yych <= 'Z') goto yy144; goto yy4; } else { if (yych <= 'a') goto yy1235; if (yych <= 'z') goto yy144; goto yy4; } } yy1235: YYDEBUG(1235, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'X') goto yy145; } } else { if (yych <= 'x') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'y') goto yy1236; if (yych <= 'z') goto yy145; goto yy4; } } yy1236: YYDEBUG(1236, *YYCURSOR); yych = *++YYCURSOR; if (yych == ')') goto yy140; goto yy167; yy1237: YYDEBUG(1237, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy143; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 't') goto yy1238; if (yych <= 'z') goto yy143; goto yy4; } } yy1238: YYDEBUG(1238, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'H') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'G') goto yy144; } } else { if (yych <= 'g') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'h') goto yy1239; if (yych <= 'z') goto yy144; goto yy4; } } yy1239: YYDEBUG(1239, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy4; goto yy1207; } else { if (yych == ' ') goto yy1207; goto yy4; } } else { if (yych <= 'Z') { if (yych <= ')') goto yy140; if (yych <= '@') goto yy4; goto yy145; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy145; goto yy4; } } yy1240: YYDEBUG(1240, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= ')') { if (yych <= '(') goto yy167; goto yy140; } else { if (yych <= '@') goto yy167; if (yych <= 'T') goto yy143; } } else { if (yych <= 't') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy167; goto yy143; } else { if (yych <= 'u') goto yy1241; if (yych <= 'z') goto yy143; goto yy167; } } yy1241: YYDEBUG(1241, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'Q') goto yy144; } } else { if (yych <= 'q') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'r') goto yy1242; if (yych <= 'z') goto yy144; goto yy4; } } yy1242: YYDEBUG(1242, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'D') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'C') goto yy145; } } else { if (yych <= 'c') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'd') goto yy1243; if (yych <= 'z') goto yy145; goto yy4; } } yy1243: YYDEBUG(1243, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'A') goto yy1244; if (yych != 'a') goto yy4; } yy1244: YYDEBUG(1244, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy173; if (yych == 'y') goto yy173; goto yy57; yy1245: YYDEBUG(1245, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'N') goto yy143; goto yy1256; } } else { if (yych <= 'n') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'o') goto yy1256; if (yych <= 'z') goto yy143; goto yy4; } } yy1246: YYDEBUG(1246, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy143; goto yy1253; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'e') goto yy1253; if (yych <= 'z') goto yy143; goto yy4; } } yy1247: YYDEBUG(1247, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; goto yy194; } else { if (yych <= '-') goto yy197; if (yych <= '.') goto yy196; goto yy194; } } } else { if (yych <= 'Z') { if (yych <= '@') { if (yych <= '9') goto yy196; goto yy194; } else { if (yych != 'T') goto yy143; } } else { if (yych <= 's') { if (yych <= '`') goto yy194; goto yy143; } else { if (yych <= 't') goto yy1248; if (yych <= 'z') goto yy143; goto yy194; } } } yy1248: YYDEBUG(1248, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; goto yy194; } else { if (yych <= '-') goto yy197; if (yych <= '.') goto yy196; goto yy194; } } } else { if (yych <= 'Z') { if (yych <= '@') { if (yych <= '9') goto yy196; goto yy194; } else { if (yych != 'E') goto yy144; } } else { if (yych <= 'd') { if (yych <= '`') goto yy194; goto yy144; } else { if (yych <= 'e') goto yy1249; if (yych <= 'z') goto yy144; goto yy194; } } } yy1249: YYDEBUG(1249, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'M') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'L') goto yy145; } } else { if (yych <= 'l') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'm') goto yy1250; if (yych <= 'z') goto yy145; goto yy4; } } yy1250: YYDEBUG(1250, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'A') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'B') goto yy1251; if (yych != 'b') goto yy4; } yy1251: YYDEBUG(1251, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy1252; if (yych != 'e') goto yy57; yy1252: YYDEBUG(1252, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy206; if (yych == 'r') goto yy206; goto yy57; yy1253: YYDEBUG(1253, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'M') goto yy144; } } else { if (yych <= 'm') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'n') goto yy1254; if (yych <= 'z') goto yy144; goto yy4; } } yy1254: YYDEBUG(1254, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy145; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 't') goto yy1255; if (yych <= 'z') goto yy145; goto yy4; } } yy1255: YYDEBUG(1255, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'G') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'H') goto yy1206; if (yych == 'h') goto yy1206; goto yy4; } yy1256: YYDEBUG(1256, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'M') goto yy144; } } else { if (yych <= 'm') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'n') goto yy1257; if (yych <= 'z') goto yy144; goto yy4; } } yy1257: YYDEBUG(1257, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'D') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'C') goto yy145; goto yy1216; } } else { if (yych <= 'c') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'd') goto yy1216; if (yych <= 'z') goto yy145; goto yy4; } } yy1258: YYDEBUG(1258, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'U') { if (yych <= '/') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; goto yy148; } } else { if (yych <= 'C') { if (yych <= '@') goto yy4; if (yych <= 'B') goto yy142; goto yy1245; } else { if (yych == 'P') goto yy1247; goto yy142; } } } else { if (yych <= 'b') { if (yych <= '^') { if (yych <= 'V') goto yy1246; if (yych <= 'Z') goto yy142; goto yy4; } else { if (yych <= '_') goto yy148; if (yych <= '`') goto yy4; goto yy147; } } else { if (yych <= 'p') { if (yych <= 'c') goto yy1274; if (yych <= 'o') goto yy147; goto yy1276; } else { if (yych == 'v') goto yy1275; if (yych <= 'z') goto yy147; goto yy4; } } } yy1259: YYDEBUG(1259, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1240; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 't') goto yy1269; if (yych <= 'z') goto yy147; goto yy4; } } } yy1260: YYDEBUG(1260, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'W') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'X') goto yy1237; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'w') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'x') goto yy1266; if (yych <= 'z') goto yy147; goto yy4; } } } yy1261: YYDEBUG(1261, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'M') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'N') goto yy1233; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'm') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'n') goto yy1262; if (yych <= 'z') goto yy147; goto yy4; } } } yy1262: YYDEBUG(1262, *YYCURSOR); yyaccept = 4; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy167; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy167; goto yy143; } } else { if (yych <= '_') { if (yych <= 'D') goto yy1234; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy167; goto yy148; } else { if (yych <= 'c') { if (yych <= '`') goto yy167; goto yy151; } else { if (yych <= 'd') goto yy1263; if (yych <= 'z') goto yy151; goto yy167; } } } yy1263: YYDEBUG(1263, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '_') { if (yych <= 'A') goto yy1235; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'a') goto yy1264; if (yych <= 'z') goto yy152; goto yy4; } } yy1264: YYDEBUG(1264, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'X') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'Y') goto yy1236; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'x') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'y') goto yy1265; if (yych <= 'z') goto yy153; goto yy4; } } } yy1265: YYDEBUG(1265, *YYCURSOR); yyaccept = 4; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 16) { goto yy154; } if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy167; goto yy148; } else { if (yych <= '/') { if (yych <= '.') goto yy167; goto yy148; } else { if (yych == '_') goto yy148; goto yy167; } } yy1266: YYDEBUG(1266, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1238; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 't') goto yy1267; if (yych <= 'z') goto yy151; goto yy4; } } } yy1267: YYDEBUG(1267, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'G') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'H') goto yy1239; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'g') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'h') goto yy1268; if (yych <= 'z') goto yy152; goto yy4; } } } yy1268: YYDEBUG(1268, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '-') { if (yych <= ' ') { if (yych == '\t') goto yy1207; if (yych <= 0x1F) goto yy4; goto yy1207; } else { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } } else { if (yych <= 'Z') { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } else { if (yych <= '_') { if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy153; goto yy4; } } } yy1269: YYDEBUG(1269, *YYCURSOR); yyaccept = 4; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy167; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy167; goto yy143; } } else { if (yych <= '_') { if (yych <= 'U') goto yy1241; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy167; goto yy148; } else { if (yych <= 't') { if (yych <= '`') goto yy167; goto yy151; } else { if (yych <= 'u') goto yy1270; if (yych <= 'z') goto yy151; goto yy167; } } } yy1270: YYDEBUG(1270, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'Q') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'R') goto yy1242; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'q') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'r') goto yy1271; if (yych <= 'z') goto yy152; goto yy4; } } } yy1271: YYDEBUG(1271, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'D') goto yy1243; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'c') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'd') goto yy1272; if (yych <= 'z') goto yy153; goto yy4; } } } yy1272: YYDEBUG(1272, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '_') { if (yych <= 'A') goto yy1244; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'a') goto yy1273; if (yych <= 'z') goto yy154; goto yy4; } } yy1273: YYDEBUG(1273, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy173; if (yych == 'y') goto yy186; goto yy155; yy1274: YYDEBUG(1274, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'N') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'O') goto yy1256; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'n') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 'o') goto yy1285; if (yych <= 'z') goto yy151; goto yy4; } } } yy1275: YYDEBUG(1275, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'E') goto yy1253; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'd') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 'e') goto yy1282; if (yych <= 'z') goto yy151; goto yy4; } } } yy1276: YYDEBUG(1276, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= '-') { if (yych <= ')') goto yy140; if (yych <= ',') goto yy194; goto yy372; } else { if (yych == '/') goto yy148; goto yy196; } } } else { if (yych <= '^') { if (yych <= 'S') { if (yych <= '@') goto yy194; goto yy143; } else { if (yych <= 'T') goto yy1248; if (yych <= 'Z') goto yy143; goto yy194; } } else { if (yych <= 's') { if (yych <= '_') goto yy148; if (yych <= '`') goto yy194; goto yy151; } else { if (yych <= 't') goto yy1277; if (yych <= 'z') goto yy151; goto yy194; } } } yy1277: YYDEBUG(1277, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= '-') { if (yych <= ')') goto yy140; if (yych <= ',') goto yy194; goto yy372; } else { if (yych == '/') goto yy148; goto yy196; } } } else { if (yych <= '^') { if (yych <= 'D') { if (yych <= '@') goto yy194; goto yy144; } else { if (yych <= 'E') goto yy1249; if (yych <= 'Z') goto yy144; goto yy194; } } else { if (yych <= 'd') { if (yych <= '_') goto yy148; if (yych <= '`') goto yy194; goto yy152; } else { if (yych <= 'e') goto yy1278; if (yych <= 'z') goto yy152; goto yy194; } } } yy1278: YYDEBUG(1278, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'L') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'M') goto yy1250; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'l') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'm') goto yy1279; if (yych <= 'z') goto yy153; goto yy4; } } } yy1279: YYDEBUG(1279, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'A') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'B') goto yy1251; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'b') goto yy1280; if (yych <= 'z') goto yy154; goto yy4; } } yy1280: YYDEBUG(1280, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy1252; if (yych != 'e') goto yy155; YYDEBUG(1281, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy206; if (yych == 'r') goto yy377; goto yy155; yy1282: YYDEBUG(1282, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'M') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'N') goto yy1254; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'm') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'n') goto yy1283; if (yych <= 'z') goto yy152; goto yy4; } } } yy1283: YYDEBUG(1283, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1255; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 't') goto yy1284; if (yych <= 'z') goto yy153; goto yy4; } } } yy1284: YYDEBUG(1284, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'G') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'H') goto yy1206; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'h') goto yy1224; if (yych <= 'z') goto yy154; goto yy4; } } yy1285: YYDEBUG(1285, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'M') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'N') goto yy1257; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'm') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'n') goto yy1286; if (yych <= 'z') goto yy152; goto yy4; } } } yy1286: YYDEBUG(1286, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'D') goto yy1216; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'c') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'd') goto yy1228; if (yych <= 'z') goto yy153; goto yy4; } } } yy1287: YYDEBUG(1287, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'C') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'B') goto yy142; } } else { if (yych <= 'b') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'c') goto yy1288; if (yych <= 'z') goto yy142; goto yy4; } } yy1288: YYDEBUG(1288, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'K') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'J') goto yy143; } } else { if (yych <= 'j') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'k') goto yy1289; if (yych <= 'z') goto yy143; goto yy4; } } yy1289: YYDEBUG(1289, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ')') { if (yych == ' ') goto yy1290; if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= 'Z') { if (yych <= '@') goto yy4; goto yy144; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy144; goto yy4; } } yy1290: YYDEBUG(1290, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy1291; if (yych != 'o') goto yy57; yy1291: YYDEBUG(1291, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy1292; if (yych != 'f') goto yy57; yy1292: YYDEBUG(1292, *YYCURSOR); yych = *++YYCURSOR; if (yych != ' ') goto yy57; YYDEBUG(1293, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '1') goto yy1294; if (yych <= '2') goto yy1296; if (yych <= '9') goto yy1297; goto yy57; yy1294: YYDEBUG(1294, *YYCURSOR); yyaccept = 28; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') goto yy1298; if (yych <= '9') goto yy1297; goto yy1298; yy1295: YYDEBUG(1295, *YYCURSOR); #line 1099 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("backof | frontof"); TIMELIB_INIT; TIMELIB_UNHAVE_TIME(); TIMELIB_HAVE_TIME(); if (*ptr == 'b') { s->time->h = timelib_get_nr((char **) &ptr, 2); s->time->i = 15; } else { s->time->h = timelib_get_nr((char **) &ptr, 2) - 1; s->time->i = 45; } if (*ptr != '\0' ) { timelib_eat_spaces((char **) &ptr); s->time->h += timelib_meridian((char **) &ptr, s->time->h); } TIMELIB_DEINIT; return TIMELIB_LF_DAY_OF_MONTH; } #line 19675 "ext/date/lib/parse_date.c" yy1296: YYDEBUG(1296, *YYCURSOR); yyaccept = 28; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') goto yy1298; if (yych >= '5') goto yy1298; yy1297: YYDEBUG(1297, *YYCURSOR); yyaccept = 28; YYMARKER = ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 5) YYFILL(5); yych = *YYCURSOR; yy1298: YYDEBUG(1298, *YYCURSOR); if (yych <= 'A') { if (yych <= 0x1F) { if (yych == '\t') goto yy1297; goto yy1295; } else { if (yych <= ' ') goto yy1297; if (yych <= '@') goto yy1295; } } else { if (yych <= '`') { if (yych != 'P') goto yy1295; } else { if (yych <= 'a') goto yy1299; if (yych != 'p') goto yy1295; } } yy1299: YYDEBUG(1299, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych != '.') goto yy57; } else { if (yych <= 'M') goto yy1301; if (yych == 'm') goto yy1301; goto yy57; } YYDEBUG(1300, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy1301; if (yych != 'm') goto yy57; yy1301: YYDEBUG(1301, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 0x1F) { if (yych <= 0x00) goto yy1303; if (yych == '\t') goto yy1303; goto yy57; } else { if (yych <= ' ') goto yy1303; if (yych != '.') goto yy57; } YYDEBUG(1302, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '\t') { if (yych <= 0x00) goto yy1303; if (yych <= 0x08) goto yy57; } else { if (yych != ' ') goto yy57; } yy1303: YYDEBUG(1303, *YYCURSOR); yych = *++YYCURSOR; goto yy1295; yy1304: YYDEBUG(1304, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'B') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'C') goto yy1288; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'b') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'c') goto yy1305; if (yych <= 'z') goto yy147; goto yy4; } } } yy1305: YYDEBUG(1305, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'J') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'K') goto yy1289; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'j') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 'k') goto yy1306; if (yych <= 'z') goto yy151; goto yy4; } } } yy1306: YYDEBUG(1306, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= '(') { if (yych == ' ') goto yy1290; goto yy4; } else { if (yych <= ')') goto yy140; if (yych == '-') goto yy148; goto yy4; } } else { if (yych <= '^') { if (yych <= '/') goto yy148; if (yych <= '@') goto yy4; if (yych <= 'Z') goto yy144; goto yy4; } else { if (yych <= '_') goto yy148; if (yych <= '`') goto yy4; if (yych <= 'z') goto yy152; goto yy4; } } yy1307: YYDEBUG(1307, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'R') goto yy142; } } else { if (yych <= 'r') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 's') goto yy1308; if (yych <= 'z') goto yy142; goto yy4; } } yy1308: YYDEBUG(1308, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy143; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 't') goto yy1309; if (yych <= 'z') goto yy143; goto yy4; } } yy1309: YYDEBUG(1309, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy4; goto yy1105; } else { if (yych != ' ') goto yy4; } } else { if (yych <= 'Z') { if (yych <= ')') goto yy140; if (yych <= '@') goto yy4; goto yy144; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy144; goto yy4; } } yy1310: YYDEBUG(1310, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy1311; if (yych != 'd') goto yy1106; yy1311: YYDEBUG(1311, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1312; if (yych != 'a') goto yy57; yy1312: YYDEBUG(1312, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy1313; if (yych != 'y') goto yy57; yy1313: YYDEBUG(1313, *YYCURSOR); yyaccept = 26; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'R') { if (yych != ' ') goto yy1118; } else { if (yych <= 'S') goto yy1143; if (yych == 's') goto yy1143; goto yy1118; } YYDEBUG(1314, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy1315; if (yych != 'o') goto yy57; yy1315: YYDEBUG(1315, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy1316; if (yych != 'f') goto yy57; yy1316: YYDEBUG(1316, *YYCURSOR); yych = *++YYCURSOR; goto yy2; yy1317: YYDEBUG(1317, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'R') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'S') goto yy1308; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'r') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 's') goto yy1318; if (yych <= 'z') goto yy147; goto yy4; } } } yy1318: YYDEBUG(1318, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1309; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 't') goto yy1319; if (yych <= 'z') goto yy151; goto yy4; } } } yy1319: YYDEBUG(1319, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '-') { if (yych <= ' ') { if (yych == '\t') goto yy1105; if (yych <= 0x1F) goto yy4; goto yy1310; } else { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } } else { if (yych <= 'Z') { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } else { if (yych <= '_') { if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy152; goto yy4; } } } yy1320: YYDEBUG(1320, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'B') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'A') goto yy142; goto yy1356; } } else { if (yych <= 'a') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'b') goto yy1356; if (yych <= 'z') goto yy142; goto yy4; } } yy1321: YYDEBUG(1321, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == 'F') goto yy1346; if (yych <= 'Q') goto yy142; goto yy1345; } } else { if (yych <= 'f') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; if (yych <= 'e') goto yy142; goto yy1346; } else { if (yych == 'r') goto yy1345; if (yych <= 'z') goto yy142; goto yy4; } } yy1322: YYDEBUG(1322, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'T') goto yy142; goto yy1342; } } else { if (yych <= 't') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'u') goto yy1342; if (yych <= 'z') goto yy142; goto yy4; } } yy1323: YYDEBUG(1323, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == 'I') goto yy1325; if (yych <= 'N') goto yy142; } } else { if (yych <= 'i') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; if (yych <= 'h') goto yy142; goto yy1325; } else { if (yych == 'o') goto yy1324; if (yych <= 'z') goto yy142; goto yy4; } } yy1324: YYDEBUG(1324, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'M') goto yy143; goto yy1328; } } else { if (yych <= 'm') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'n') goto yy1328; if (yych <= 'z') goto yy143; goto yy4; } } yy1325: YYDEBUG(1325, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'D') { if (yych <= ')') { if (yych <= '(') goto yy167; goto yy140; } else { if (yych <= '@') goto yy167; if (yych <= 'C') goto yy143; } } else { if (yych <= 'c') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy167; goto yy143; } else { if (yych <= 'd') goto yy1326; if (yych <= 'z') goto yy143; goto yy167; } } yy1326: YYDEBUG(1326, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; } else { if (yych <= '`') { if (yych <= 'Z') goto yy144; goto yy4; } else { if (yych <= 'a') goto yy1327; if (yych <= 'z') goto yy144; goto yy4; } } yy1327: YYDEBUG(1327, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'X') goto yy145; goto yy1236; } } else { if (yych <= 'x') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'y') goto yy1236; if (yych <= 'z') goto yy145; goto yy4; } } yy1328: YYDEBUG(1328, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy144; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 't') goto yy1329; if (yych <= 'z') goto yy144; goto yy4; } } yy1329: YYDEBUG(1329, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ')') { if (yych == ' ') goto yy1330; if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= 'Z') { if (yych <= '@') goto yy4; goto yy145; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy145; goto yy4; } } yy1330: YYDEBUG(1330, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy1331; if (yych != 'o') goto yy57; yy1331: YYDEBUG(1331, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy1332; if (yych != 'f') goto yy57; yy1332: YYDEBUG(1332, *YYCURSOR); yych = *++YYCURSOR; if (yych != ' ') goto yy57; YYDEBUG(1333, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '1') goto yy1334; if (yych <= '2') goto yy1335; if (yych <= '9') goto yy1336; goto yy57; yy1334: YYDEBUG(1334, *YYCURSOR); yyaccept = 28; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') goto yy1337; if (yych <= '9') goto yy1336; goto yy1337; yy1335: YYDEBUG(1335, *YYCURSOR); yyaccept = 28; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') goto yy1337; if (yych >= '5') goto yy1337; yy1336: YYDEBUG(1336, *YYCURSOR); yyaccept = 28; YYMARKER = ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 5) YYFILL(5); yych = *YYCURSOR; yy1337: YYDEBUG(1337, *YYCURSOR); if (yych <= 'A') { if (yych <= 0x1F) { if (yych == '\t') goto yy1336; goto yy1295; } else { if (yych <= ' ') goto yy1336; if (yych <= '@') goto yy1295; } } else { if (yych <= '`') { if (yych != 'P') goto yy1295; } else { if (yych <= 'a') goto yy1338; if (yych != 'p') goto yy1295; } } yy1338: YYDEBUG(1338, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych != '.') goto yy57; } else { if (yych <= 'M') goto yy1340; if (yych == 'm') goto yy1340; goto yy57; } YYDEBUG(1339, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy1340; if (yych != 'm') goto yy57; yy1340: YYDEBUG(1340, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 0x1F) { if (yych <= 0x00) goto yy1303; if (yych == '\t') goto yy1303; goto yy57; } else { if (yych <= ' ') goto yy1303; if (yych != '.') goto yy57; } YYDEBUG(1341, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '\t') { if (yych <= 0x00) goto yy1303; if (yych <= 0x08) goto yy57; goto yy1303; } else { if (yych == ' ') goto yy1303; goto yy57; } yy1342: YYDEBUG(1342, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'Q') goto yy143; } } else { if (yych <= 'q') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'r') goto yy1343; if (yych <= 'z') goto yy143; goto yy4; } } yy1343: YYDEBUG(1343, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy144; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 't') goto yy1344; if (yych <= 'z') goto yy144; goto yy4; } } yy1344: YYDEBUG(1344, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'H') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'G') goto yy145; goto yy1216; } } else { if (yych <= 'g') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'h') goto yy1216; if (yych <= 'z') goto yy145; goto yy4; } } yy1345: YYDEBUG(1345, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'R') goto yy143; goto yy1348; } } else { if (yych <= 'r') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 's') goto yy1348; if (yych <= 'z') goto yy143; goto yy4; } } yy1346: YYDEBUG(1346, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy143; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 't') goto yy1347; if (yych <= 'z') goto yy143; goto yy4; } } yy1347: YYDEBUG(1347, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'H') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'G') goto yy144; goto yy1239; } } else { if (yych <= 'g') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'h') goto yy1239; if (yych <= 'z') goto yy144; goto yy4; } } yy1348: YYDEBUG(1348, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy144; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 't') goto yy1349; if (yych <= 'z') goto yy144; goto yy4; } } yy1349: YYDEBUG(1349, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy4; goto yy1207; } else { if (yych != ' ') goto yy4; } } else { if (yych <= 'Z') { if (yych <= ')') goto yy140; if (yych <= '@') goto yy4; goto yy145; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy145; goto yy4; } } yy1350: YYDEBUG(1350, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy1351; if (yych != 'd') goto yy1208; yy1351: YYDEBUG(1351, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1352; if (yych != 'a') goto yy57; yy1352: YYDEBUG(1352, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy1353; if (yych != 'y') goto yy57; yy1353: YYDEBUG(1353, *YYCURSOR); yyaccept = 26; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'R') { if (yych != ' ') goto yy1118; } else { if (yych <= 'S') goto yy1143; if (yych == 's') goto yy1143; goto yy1118; } YYDEBUG(1354, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy1355; if (yych != 'o') goto yy57; yy1355: YYDEBUG(1355, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy1316; if (yych == 'f') goto yy1316; goto yy57; yy1356: YYDEBUG(1356, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; goto yy194; } else { if (yych <= '-') goto yy197; if (yych <= '.') goto yy196; goto yy194; } } } else { if (yych <= 'Z') { if (yych <= '@') { if (yych <= '9') goto yy196; goto yy194; } else { if (yych != 'R') goto yy143; } } else { if (yych <= 'q') { if (yych <= '`') goto yy194; goto yy143; } else { if (yych <= 'r') goto yy1357; if (yych <= 'z') goto yy143; goto yy194; } } } yy1357: YYDEBUG(1357, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'T') goto yy144; } } else { if (yych <= 't') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'u') goto yy1358; if (yych <= 'z') goto yy144; goto yy4; } } yy1358: YYDEBUG(1358, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; } else { if (yych <= '`') { if (yych <= 'Z') goto yy145; goto yy4; } else { if (yych <= 'a') goto yy1359; if (yych <= 'z') goto yy145; goto yy4; } } yy1359: YYDEBUG(1359, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'Q') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'R') goto yy1360; if (yych != 'r') goto yy4; } yy1360: YYDEBUG(1360, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy206; if (yych == 'y') goto yy206; goto yy57; yy1361: YYDEBUG(1361, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'A') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'B') goto yy1356; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'a') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'b') goto yy1379; if (yych <= 'z') goto yy147; goto yy4; } } } yy1362: YYDEBUG(1362, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'Q') { if (yych <= '.') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych == '-') goto yy148; goto yy4; } } else { if (yych <= '@') { if (yych <= '/') goto yy148; goto yy4; } else { if (yych == 'F') goto yy1346; goto yy142; } } } else { if (yych <= '`') { if (yych <= 'Z') { if (yych <= 'R') goto yy1345; goto yy142; } else { if (yych == '_') goto yy148; goto yy4; } } else { if (yych <= 'q') { if (yych == 'f') goto yy1375; goto yy147; } else { if (yych <= 'r') goto yy1374; if (yych <= 'z') goto yy147; goto yy4; } } } yy1363: YYDEBUG(1363, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'U') goto yy1342; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 't') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'u') goto yy1371; if (yych <= 'z') goto yy147; goto yy4; } } } yy1364: YYDEBUG(1364, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'N') { if (yych <= '.') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych == '-') goto yy148; goto yy4; } } else { if (yych <= '@') { if (yych <= '/') goto yy148; goto yy4; } else { if (yych == 'I') goto yy1325; goto yy142; } } } else { if (yych <= '`') { if (yych <= 'Z') { if (yych <= 'O') goto yy1324; goto yy142; } else { if (yych == '_') goto yy148; goto yy4; } } else { if (yych <= 'n') { if (yych == 'i') goto yy1366; goto yy147; } else { if (yych <= 'o') goto yy1365; if (yych <= 'z') goto yy147; goto yy4; } } } yy1365: YYDEBUG(1365, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'M') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'N') goto yy1328; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'm') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 'n') goto yy1369; if (yych <= 'z') goto yy151; goto yy4; } } } yy1366: YYDEBUG(1366, *YYCURSOR); yyaccept = 4; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy167; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy167; goto yy143; } } else { if (yych <= '_') { if (yych <= 'D') goto yy1326; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy167; goto yy148; } else { if (yych <= 'c') { if (yych <= '`') goto yy167; goto yy151; } else { if (yych <= 'd') goto yy1367; if (yych <= 'z') goto yy151; goto yy167; } } } yy1367: YYDEBUG(1367, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '_') { if (yych <= 'A') goto yy1327; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'a') goto yy1368; if (yych <= 'z') goto yy152; goto yy4; } } yy1368: YYDEBUG(1368, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'X') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'Y') goto yy1236; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'x') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'y') goto yy1265; if (yych <= 'z') goto yy153; goto yy4; } } } yy1369: YYDEBUG(1369, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1329; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 't') goto yy1370; if (yych <= 'z') goto yy152; goto yy4; } } } yy1370: YYDEBUG(1370, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= '(') { if (yych == ' ') goto yy1330; goto yy4; } else { if (yych <= ')') goto yy140; if (yych == '-') goto yy148; goto yy4; } } else { if (yych <= '^') { if (yych <= '/') goto yy148; if (yych <= '@') goto yy4; if (yych <= 'Z') goto yy145; goto yy4; } else { if (yych <= '_') goto yy148; if (yych <= '`') goto yy4; if (yych <= 'z') goto yy153; goto yy4; } } yy1371: YYDEBUG(1371, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'Q') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'R') goto yy1343; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'q') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 'r') goto yy1372; if (yych <= 'z') goto yy151; goto yy4; } } } yy1372: YYDEBUG(1372, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1344; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 't') goto yy1373; if (yych <= 'z') goto yy152; goto yy4; } } } yy1373: YYDEBUG(1373, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'G') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'H') goto yy1216; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'g') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'h') goto yy1228; if (yych <= 'z') goto yy153; goto yy4; } } } yy1374: YYDEBUG(1374, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'R') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'S') goto yy1348; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'r') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 's') goto yy1377; if (yych <= 'z') goto yy151; goto yy4; } } } yy1375: YYDEBUG(1375, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1347; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 't') goto yy1376; if (yych <= 'z') goto yy151; goto yy4; } } } yy1376: YYDEBUG(1376, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'G') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'H') goto yy1239; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'g') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'h') goto yy1268; if (yych <= 'z') goto yy152; goto yy4; } } } yy1377: YYDEBUG(1377, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1349; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 't') goto yy1378; if (yych <= 'z') goto yy152; goto yy4; } } } yy1378: YYDEBUG(1378, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '-') { if (yych <= ' ') { if (yych == '\t') goto yy1207; if (yych <= 0x1F) goto yy4; goto yy1350; } else { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } } else { if (yych <= 'Z') { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } else { if (yych <= '_') { if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy153; goto yy4; } } } yy1379: YYDEBUG(1379, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= '-') { if (yych <= ')') goto yy140; if (yych <= ',') goto yy194; goto yy372; } else { if (yych == '/') goto yy148; goto yy196; } } } else { if (yych <= '^') { if (yych <= 'Q') { if (yych <= '@') goto yy194; goto yy143; } else { if (yych <= 'R') goto yy1357; if (yych <= 'Z') goto yy143; goto yy194; } } else { if (yych <= 'q') { if (yych <= '_') goto yy148; if (yych <= '`') goto yy194; goto yy151; } else { if (yych <= 'r') goto yy1380; if (yych <= 'z') goto yy151; goto yy194; } } } yy1380: YYDEBUG(1380, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'U') goto yy1358; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 't') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'u') goto yy1381; if (yych <= 'z') goto yy152; goto yy4; } } } yy1381: YYDEBUG(1381, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '_') { if (yych <= 'A') goto yy1359; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'a') goto yy1382; if (yych <= 'z') goto yy153; goto yy4; } } yy1382: YYDEBUG(1382, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'Q') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'R') goto yy1360; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'r') goto yy1383; if (yych <= 'z') goto yy154; goto yy4; } } yy1383: YYDEBUG(1383, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy206; if (yych == 'y') goto yy377; goto yy155; yy1384: YYDEBUG(1384, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; yy1385: YYDEBUG(1385, *YYCURSOR); ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; YYDEBUG(1386, *YYCURSOR); if (yych <= '/') goto yy1387; if (yych <= '9') goto yy1385; yy1387: YYDEBUG(1387, *YYCURSOR); #line 1057 "ext/date/lib/parse_date.re" { timelib_ull i; TIMELIB_INIT; TIMELIB_HAVE_RELATIVE(); TIMELIB_UNHAVE_DATE(); TIMELIB_UNHAVE_TIME(); TIMELIB_HAVE_TZ(); i = timelib_get_unsigned_nr((char **) &ptr, 24); s->time->y = 1970; s->time->m = 1; s->time->d = 1; s->time->h = s->time->i = s->time->s = 0; s->time->f = 0.0; s->time->relative.s += i; s->time->is_localtime = 1; s->time->zone_type = TIMELIB_ZONETYPE_OFFSET; s->time->z = 0; TIMELIB_DEINIT; return TIMELIB_RELATIVE; } #line 21390 "ext/date/lib/parse_date.c" yy1388: YYDEBUG(1388, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'M') goto yy142; goto yy1429; } } else { if (yych <= 'm') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'n') goto yy1429; if (yych <= 'z') goto yy142; goto yy4; } } yy1389: YYDEBUG(1389, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == 'I') goto yy1421; if (yych <= 'T') goto yy142; goto yy1422; } } else { if (yych <= 'i') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; if (yych <= 'h') goto yy142; goto yy1421; } else { if (yych == 'u') goto yy1422; if (yych <= 'z') goto yy142; goto yy4; } } yy1390: YYDEBUG(1390, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'M') { if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == 'D') goto yy1410; if (yych <= 'L') goto yy142; goto yy1411; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; if (yych <= 'c') goto yy142; goto yy1410; } else { if (yych == 'm') goto yy1411; if (yych <= 'z') goto yy142; goto yy4; } } yy1391: YYDEBUG(1391, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy142; goto yy1406; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'e') goto yy1406; if (yych <= 'z') goto yy142; goto yy4; } } yy1392: YYDEBUG(1392, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy142; goto yy1402; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'e') goto yy1402; if (yych <= 'z') goto yy142; goto yy4; } } yy1393: YYDEBUG(1393, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy1065; goto yy57; } else { if (yych <= '9') goto yy1396; if (yych <= ':') goto yy1065; goto yy57; } yy1394: YYDEBUG(1394, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy1065; goto yy57; } else { if (yych <= '4') goto yy1396; if (yych == ':') goto yy1065; goto yy57; } yy1395: YYDEBUG(1395, *YYCURSOR); yych = *++YYCURSOR; if (yych == '.') goto yy1065; if (yych == ':') goto yy1065; goto yy57; yy1396: YYDEBUG(1396, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy1065; goto yy57; } else { if (yych <= '5') goto yy1397; if (yych == ':') goto yy1065; goto yy57; } yy1397: YYDEBUG(1397, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; YYDEBUG(1398, *YYCURSOR); yyaccept = 24; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') goto yy1068; if (yych <= '5') goto yy1399; if (yych <= '6') goto yy1400; goto yy1068; yy1399: YYDEBUG(1399, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy1401; goto yy57; yy1400: YYDEBUG(1400, *YYCURSOR); yych = *++YYCURSOR; if (yych != '0') goto yy57; yy1401: YYDEBUG(1401, *YYCURSOR); yych = *++YYCURSOR; goto yy1076; yy1402: YYDEBUG(1402, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'K') goto yy143; } } else { if (yych <= 'k') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'l') goto yy1403; if (yych <= 'z') goto yy143; goto yy4; } } yy1403: YYDEBUG(1403, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'F') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'E') goto yy144; } } else { if (yych <= 'e') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'f') goto yy1404; if (yych <= 'z') goto yy144; goto yy4; } } yy1404: YYDEBUG(1404, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy145; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 't') goto yy1405; if (yych <= 'z') goto yy145; goto yy4; } } yy1405: YYDEBUG(1405, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'G') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'H') goto yy1206; if (yych == 'h') goto yy1206; goto yy4; } yy1406: YYDEBUG(1406, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= ')') { if (yych <= '(') goto yy167; goto yy140; } else { if (yych <= '@') goto yy167; if (yych <= 'R') goto yy143; } } else { if (yych <= 'r') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy167; goto yy143; } else { if (yych <= 's') goto yy1407; if (yych <= 'z') goto yy143; goto yy167; } } yy1407: YYDEBUG(1407, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'D') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'C') goto yy144; } } else { if (yych <= 'c') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'd') goto yy1408; if (yych <= 'z') goto yy144; goto yy4; } } yy1408: YYDEBUG(1408, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; } else { if (yych <= '`') { if (yych <= 'Z') goto yy145; goto yy4; } else { if (yych <= 'a') goto yy1409; if (yych <= 'z') goto yy145; goto yy4; } } yy1409: YYDEBUG(1409, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'X') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'Y') goto yy173; if (yych == 'y') goto yy173; goto yy4; } yy1410: YYDEBUG(1410, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy1418; } else { if (yych <= '`') { if (yych <= 'Z') goto yy143; goto yy4; } else { if (yych <= 'a') goto yy1418; if (yych <= 'z') goto yy143; goto yy4; } } yy1411: YYDEBUG(1411, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'N') goto yy143; } } else { if (yych <= 'n') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'o') goto yy1412; if (yych <= 'z') goto yy143; goto yy4; } } yy1412: YYDEBUG(1412, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'Q') goto yy144; } } else { if (yych <= 'q') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'r') goto yy1413; if (yych <= 'z') goto yy144; goto yy4; } } yy1413: YYDEBUG(1413, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'Q') goto yy145; } } else { if (yych <= 'q') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'r') goto yy1414; if (yych <= 'z') goto yy145; goto yy4; } } yy1414: YYDEBUG(1414, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'N') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'O') goto yy1415; if (yych != 'o') goto yy4; } yy1415: YYDEBUG(1415, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'W') goto yy1416; if (yych != 'w') goto yy57; yy1416: YYDEBUG(1416, *YYCURSOR); ++YYCURSOR; yy1417: YYDEBUG(1417, *YYCURSOR); #line 1045 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("tomorrow"); TIMELIB_INIT; TIMELIB_HAVE_RELATIVE(); TIMELIB_UNHAVE_TIME(); s->time->relative.d = 1; TIMELIB_DEINIT; return TIMELIB_RELATIVE; } #line 21837 "ext/date/lib/parse_date.c" yy1418: YYDEBUG(1418, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'X') goto yy144; } } else { if (yych <= 'x') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'y') goto yy1419; if (yych <= 'z') goto yy144; goto yy4; } } yy1419: YYDEBUG(1419, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '@') { if (yych == ')') goto yy140; } else { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy1420; if (yych <= 'z') goto yy145; } yy1420: YYDEBUG(1420, *YYCURSOR); #line 1035 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("midnight | today"); TIMELIB_INIT; TIMELIB_UNHAVE_TIME(); TIMELIB_DEINIT; return TIMELIB_RELATIVE; } #line 21881 "ext/date/lib/parse_date.c" yy1421: YYDEBUG(1421, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'Q') goto yy143; if (yych <= 'R') goto yy1427; goto yy1428; } } else { if (yych <= 'q') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'r') goto yy1427; if (yych <= 's') goto yy1428; if (yych <= 'z') goto yy143; goto yy4; } } yy1422: YYDEBUG(1422, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= ')') { if (yych <= '(') goto yy167; goto yy140; } else { if (yych <= '@') goto yy167; if (yych <= 'Q') goto yy143; } } else { if (yych <= 'q') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy167; goto yy143; } else { if (yych <= 'r') goto yy1423; if (yych <= 'z') goto yy143; goto yy167; } } yy1423: YYDEBUG(1423, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'R') goto yy144; } } else { if (yych <= 'r') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 's') goto yy1424; if (yych <= 'z') goto yy144; goto yy4; } } yy1424: YYDEBUG(1424, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'D') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'C') goto yy145; } } else { if (yych <= 'c') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'd') goto yy1425; if (yych <= 'z') goto yy145; goto yy4; } } yy1425: YYDEBUG(1425, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'A') goto yy1426; if (yych != 'a') goto yy4; } yy1426: YYDEBUG(1426, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy173; if (yych == 'y') goto yy173; goto yy57; yy1427: YYDEBUG(1427, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'D') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'C') goto yy144; goto yy1239; } } else { if (yych <= 'c') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'd') goto yy1239; if (yych <= 'z') goto yy144; goto yy4; } } yy1428: YYDEBUG(1428, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy4; goto yy1105; } else { if (yych == ' ') goto yy1105; goto yy4; } } else { if (yych <= 'Z') { if (yych <= ')') goto yy140; if (yych <= '@') goto yy4; goto yy144; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy144; goto yy4; } } yy1429: YYDEBUG(1429, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy143; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 't') goto yy1430; if (yych <= 'z') goto yy143; goto yy4; } } yy1430: YYDEBUG(1430, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'H') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'G') goto yy144; goto yy1239; } } else { if (yych <= 'g') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'h') goto yy1239; if (yych <= 'z') goto yy144; goto yy4; } } yy1431: YYDEBUG(1431, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'M') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'N') goto yy1429; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'm') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'n') goto yy1461; if (yych <= 'z') goto yy147; goto yy4; } } } yy1432: YYDEBUG(1432, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych <= '.') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych == '-') goto yy148; goto yy4; } } else { if (yych <= '@') { if (yych <= '/') goto yy148; goto yy4; } else { if (yych == 'I') goto yy1421; goto yy142; } } } else { if (yych <= '`') { if (yych <= 'Z') { if (yych <= 'U') goto yy1422; goto yy142; } else { if (yych == '_') goto yy148; goto yy4; } } else { if (yych <= 't') { if (yych == 'i') goto yy1453; goto yy147; } else { if (yych <= 'u') goto yy1454; if (yych <= 'z') goto yy147; goto yy4; } } } yy1433: YYDEBUG(1433, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'L') { if (yych <= '.') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych == '-') goto yy148; goto yy4; } } else { if (yych <= '@') { if (yych <= '/') goto yy148; goto yy4; } else { if (yych == 'D') goto yy1410; goto yy142; } } } else { if (yych <= '`') { if (yych <= 'Z') { if (yych <= 'M') goto yy1411; goto yy142; } else { if (yych == '_') goto yy148; goto yy4; } } else { if (yych <= 'l') { if (yych == 'd') goto yy1444; goto yy147; } else { if (yych <= 'm') goto yy1445; if (yych <= 'z') goto yy147; goto yy4; } } } yy1434: YYDEBUG(1434, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'E') goto yy1406; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'd') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'e') goto yy1440; if (yych <= 'z') goto yy147; goto yy4; } } } yy1435: YYDEBUG(1435, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'E') goto yy1402; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'd') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'e') goto yy1436; if (yych <= 'z') goto yy147; goto yy4; } } } yy1436: YYDEBUG(1436, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'K') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'L') goto yy1403; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'k') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 'l') goto yy1437; if (yych <= 'z') goto yy151; goto yy4; } } } yy1437: YYDEBUG(1437, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'E') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'F') goto yy1404; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'e') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'f') goto yy1438; if (yych <= 'z') goto yy152; goto yy4; } } } yy1438: YYDEBUG(1438, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1405; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 't') goto yy1439; if (yych <= 'z') goto yy153; goto yy4; } } } yy1439: YYDEBUG(1439, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'G') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'H') goto yy1206; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'h') goto yy1224; if (yych <= 'z') goto yy154; goto yy4; } } yy1440: YYDEBUG(1440, *YYCURSOR); yyaccept = 4; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'R') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy167; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy167; goto yy143; } } else { if (yych <= '_') { if (yych <= 'S') goto yy1407; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy167; goto yy148; } else { if (yych <= 'r') { if (yych <= '`') goto yy167; goto yy151; } else { if (yych <= 's') goto yy1441; if (yych <= 'z') goto yy151; goto yy167; } } } yy1441: YYDEBUG(1441, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'D') goto yy1408; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'c') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'd') goto yy1442; if (yych <= 'z') goto yy152; goto yy4; } } } yy1442: YYDEBUG(1442, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '_') { if (yych <= 'A') goto yy1409; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'a') goto yy1443; if (yych <= 'z') goto yy153; goto yy4; } } yy1443: YYDEBUG(1443, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'X') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'Y') goto yy173; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'y') goto yy186; if (yych <= 'z') goto yy154; goto yy4; } } yy1444: YYDEBUG(1444, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '_') { if (yych <= 'A') goto yy1418; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'a') goto yy1451; if (yych <= 'z') goto yy151; goto yy4; } } yy1445: YYDEBUG(1445, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'N') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'O') goto yy1412; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'n') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 'o') goto yy1446; if (yych <= 'z') goto yy151; goto yy4; } } } yy1446: YYDEBUG(1446, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'Q') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'R') goto yy1413; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'q') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'r') goto yy1447; if (yych <= 'z') goto yy152; goto yy4; } } } yy1447: YYDEBUG(1447, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'Q') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'R') goto yy1414; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'q') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'r') goto yy1448; if (yych <= 'z') goto yy153; goto yy4; } } } yy1448: YYDEBUG(1448, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'N') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'O') goto yy1415; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'o') goto yy1449; if (yych <= 'z') goto yy154; goto yy4; } } yy1449: YYDEBUG(1449, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'W') goto yy1416; if (yych != 'w') goto yy155; YYDEBUG(1450, *YYCURSOR); yyaccept = 29; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 16) { goto yy154; } if (yych <= '.') { if (yych == '-') goto yy148; goto yy1417; } else { if (yych <= '/') goto yy148; if (yych == '_') goto yy148; goto yy1417; } yy1451: YYDEBUG(1451, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'X') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'Y') goto yy1419; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'x') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'y') goto yy1452; if (yych <= 'z') goto yy152; goto yy4; } } } yy1452: YYDEBUG(1452, *YYCURSOR); yyaccept = 30; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy1420; } else { if (yych == '.') goto yy1420; goto yy148; } } else { if (yych <= '^') { if (yych <= '@') goto yy1420; if (yych <= 'Z') goto yy145; goto yy1420; } else { if (yych <= '_') goto yy148; if (yych <= '`') goto yy1420; if (yych <= 'z') goto yy153; goto yy1420; } } yy1453: YYDEBUG(1453, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'R') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych <= '/') { if (yych <= '.') goto yy4; goto yy148; } else { if (yych <= '@') goto yy4; if (yych <= 'Q') goto yy143; goto yy1427; } } } else { if (yych <= '`') { if (yych <= 'Z') { if (yych <= 'S') goto yy1428; goto yy143; } else { if (yych == '_') goto yy148; goto yy4; } } else { if (yych <= 'r') { if (yych <= 'q') goto yy151; goto yy1459; } else { if (yych <= 's') goto yy1460; if (yych <= 'z') goto yy151; goto yy4; } } } yy1454: YYDEBUG(1454, *YYCURSOR); yyaccept = 4; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'Q') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy167; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy167; goto yy143; } } else { if (yych <= '_') { if (yych <= 'R') goto yy1423; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy167; goto yy148; } else { if (yych <= 'q') { if (yych <= '`') goto yy167; goto yy151; } else { if (yych <= 'r') goto yy1455; if (yych <= 'z') goto yy151; goto yy167; } } } yy1455: YYDEBUG(1455, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'R') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'S') goto yy1424; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'r') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 's') goto yy1456; if (yych <= 'z') goto yy152; goto yy4; } } } yy1456: YYDEBUG(1456, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'D') goto yy1425; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'c') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'd') goto yy1457; if (yych <= 'z') goto yy153; goto yy4; } } } yy1457: YYDEBUG(1457, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '_') { if (yych <= 'A') goto yy1426; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'a') goto yy1458; if (yych <= 'z') goto yy154; goto yy4; } } yy1458: YYDEBUG(1458, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy173; if (yych == 'y') goto yy186; goto yy155; yy1459: YYDEBUG(1459, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'D') goto yy1239; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'c') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'd') goto yy1268; if (yych <= 'z') goto yy152; goto yy4; } } } yy1460: YYDEBUG(1460, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '-') { if (yych <= ' ') { if (yych == '\t') goto yy1105; if (yych <= 0x1F) goto yy4; goto yy1105; } else { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } } else { if (yych <= 'Z') { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } else { if (yych <= '_') { if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy152; goto yy4; } } } yy1461: YYDEBUG(1461, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1430; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 't') goto yy1462; if (yych <= 'z') goto yy151; goto yy4; } } } yy1462: YYDEBUG(1462, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'G') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'H') goto yy1239; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'g') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'h') goto yy1268; if (yych <= 'z') goto yy152; goto yy4; } } } yy1463: YYDEBUG(1463, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == 'R') goto yy1475; if (yych <= 'X') goto yy142; goto yy1476; } } else { if (yych <= 'r') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; if (yych <= 'q') goto yy142; goto yy1475; } else { if (yych == 'y') goto yy1476; if (yych <= 'z') goto yy142; goto yy4; } } yy1464: YYDEBUG(1464, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'D') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'C') goto yy142; goto yy1469; } } else { if (yych <= 'c') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'd') goto yy1469; if (yych <= 'z') goto yy142; goto yy4; } } yy1465: YYDEBUG(1465, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'M') goto yy142; } } else { if (yych <= 'm') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'n') goto yy1466; if (yych <= 'z') goto yy142; goto yy4; } } yy1466: YYDEBUG(1466, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'D') { if (yych <= ')') { if (yych <= '(') goto yy167; goto yy140; } else { if (yych <= '@') goto yy167; if (yych <= 'C') goto yy143; } } else { if (yych <= 'c') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy167; goto yy143; } else { if (yych <= 'd') goto yy1467; if (yych <= 'z') goto yy143; goto yy167; } } yy1467: YYDEBUG(1467, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; } else { if (yych <= '`') { if (yych <= 'Z') goto yy144; goto yy4; } else { if (yych <= 'a') goto yy1468; if (yych <= 'z') goto yy144; goto yy4; } } yy1468: YYDEBUG(1468, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'X') goto yy145; goto yy1236; } } else { if (yych <= 'x') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'y') goto yy1236; if (yych <= 'z') goto yy145; goto yy4; } } yy1469: YYDEBUG(1469, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'M') goto yy143; } } else { if (yych <= 'm') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'n') goto yy1470; if (yych <= 'z') goto yy143; goto yy4; } } yy1470: YYDEBUG(1470, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'I') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'H') goto yy144; } } else { if (yych <= 'h') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'i') goto yy1471; if (yych <= 'z') goto yy144; goto yy4; } } yy1471: YYDEBUG(1471, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'G') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'F') goto yy145; } } else { if (yych <= 'f') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'g') goto yy1472; if (yych <= 'z') goto yy145; goto yy4; } } yy1472: YYDEBUG(1472, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'G') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'H') goto yy1473; if (yych != 'h') goto yy4; } yy1473: YYDEBUG(1473, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy1474; if (yych != 't') goto yy57; yy1474: YYDEBUG(1474, *YYCURSOR); yych = *++YYCURSOR; goto yy1420; yy1475: YYDEBUG(1475, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; goto yy194; } else { if (yych <= '-') goto yy197; if (yych <= '.') goto yy196; goto yy194; } } } else { if (yych <= 'Z') { if (yych <= '@') { if (yych <= '9') goto yy196; goto yy194; } else { if (yych == 'C') goto yy1477; goto yy143; } } else { if (yych <= 'b') { if (yych <= '`') goto yy194; goto yy143; } else { if (yych <= 'c') goto yy1477; if (yych <= 'z') goto yy143; goto yy194; } } } yy1476: YYDEBUG(1476, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '-') { if (yych <= ' ') { if (yych == '\t') goto yy196; if (yych <= 0x1F) goto yy194; goto yy196; } else { if (yych == ')') goto yy140; if (yych <= ',') goto yy194; goto yy197; } } else { if (yych <= '@') { if (yych == '/') goto yy194; if (yych <= '9') goto yy196; goto yy194; } else { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy194; if (yych <= 'z') goto yy143; goto yy194; } } yy1477: YYDEBUG(1477, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'H') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'G') goto yy144; goto yy396; } } else { if (yych <= 'g') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'h') goto yy396; if (yych <= 'z') goto yy144; goto yy4; } } yy1478: YYDEBUG(1478, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'X') { if (yych <= '.') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych == '-') goto yy148; goto yy4; } } else { if (yych <= '@') { if (yych <= '/') goto yy148; goto yy4; } else { if (yych == 'R') goto yy1475; goto yy142; } } } else { if (yych <= '`') { if (yych <= 'Z') { if (yych <= 'Y') goto yy1476; goto yy142; } else { if (yych == '_') goto yy148; goto yy4; } } else { if (yych <= 'x') { if (yych == 'r') goto yy1490; goto yy147; } else { if (yych <= 'y') goto yy1491; if (yych <= 'z') goto yy147; goto yy4; } } } yy1479: YYDEBUG(1479, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'D') goto yy1469; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'c') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'd') goto yy1484; if (yych <= 'z') goto yy147; goto yy4; } } } yy1480: YYDEBUG(1480, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'M') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'N') goto yy1466; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'm') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'n') goto yy1481; if (yych <= 'z') goto yy147; goto yy4; } } } yy1481: YYDEBUG(1481, *YYCURSOR); yyaccept = 4; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy167; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy167; goto yy143; } } else { if (yych <= '_') { if (yych <= 'D') goto yy1467; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy167; goto yy148; } else { if (yych <= 'c') { if (yych <= '`') goto yy167; goto yy151; } else { if (yych <= 'd') goto yy1482; if (yych <= 'z') goto yy151; goto yy167; } } } yy1482: YYDEBUG(1482, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '_') { if (yych <= 'A') goto yy1468; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'a') goto yy1483; if (yych <= 'z') goto yy152; goto yy4; } } yy1483: YYDEBUG(1483, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'X') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'Y') goto yy1236; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'x') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'y') goto yy1265; if (yych <= 'z') goto yy153; goto yy4; } } } yy1484: YYDEBUG(1484, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'M') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'N') goto yy1470; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'm') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 'n') goto yy1485; if (yych <= 'z') goto yy151; goto yy4; } } } yy1485: YYDEBUG(1485, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'H') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'I') goto yy1471; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'h') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'i') goto yy1486; if (yych <= 'z') goto yy152; goto yy4; } } } yy1486: YYDEBUG(1486, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'F') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'G') goto yy1472; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'f') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'g') goto yy1487; if (yych <= 'z') goto yy153; goto yy4; } } } yy1487: YYDEBUG(1487, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'G') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'H') goto yy1473; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'h') goto yy1488; if (yych <= 'z') goto yy154; goto yy4; } } yy1488: YYDEBUG(1488, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy1474; if (yych != 't') goto yy155; YYDEBUG(1489, *YYCURSOR); yyaccept = 30; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 16) { goto yy154; } if (yych <= '.') { if (yych == '-') goto yy148; goto yy1420; } else { if (yych <= '/') goto yy148; if (yych == '_') goto yy148; goto yy1420; } yy1490: YYDEBUG(1490, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= '-') { if (yych <= ')') goto yy140; if (yych <= ',') goto yy194; goto yy372; } else { if (yych == '/') goto yy148; goto yy196; } } } else { if (yych <= '^') { if (yych <= 'B') { if (yych <= '@') goto yy194; goto yy143; } else { if (yych <= 'C') goto yy1477; if (yych <= 'Z') goto yy143; goto yy194; } } else { if (yych <= 'b') { if (yych <= '_') goto yy148; if (yych <= '`') goto yy194; goto yy151; } else { if (yych <= 'c') goto yy1492; if (yych <= 'z') goto yy151; goto yy194; } } } yy1491: YYDEBUG(1491, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ' ') { if (yych == '\t') goto yy196; if (yych <= 0x1F) goto yy194; goto yy196; } else { if (yych <= ')') { if (yych <= '(') goto yy194; goto yy140; } else { if (yych <= ',') goto yy194; if (yych <= '-') goto yy372; goto yy196; } } } else { if (yych <= 'Z') { if (yych <= '/') goto yy148; if (yych <= '9') goto yy196; if (yych <= '@') goto yy194; goto yy143; } else { if (yych <= '_') { if (yych <= '^') goto yy194; goto yy148; } else { if (yych <= '`') goto yy194; if (yych <= 'z') goto yy151; goto yy194; } } } yy1492: YYDEBUG(1492, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'G') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'H') goto yy396; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'g') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'h') goto yy407; if (yych <= 'z') goto yy152; goto yy4; } } } yy1493: YYDEBUG(1493, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'W') { if (yych <= 'N') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy142; } else { if (yych <= 'O') goto yy1501; if (yych <= 'U') goto yy142; if (yych <= 'V') goto yy1502; goto yy1499; } } else { if (yych <= 'o') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; if (yych <= 'n') goto yy142; goto yy1501; } else { if (yych <= 'v') { if (yych <= 'u') goto yy142; goto yy1502; } else { if (yych <= 'w') goto yy1499; if (yych <= 'z') goto yy142; goto yy4; } } } yy1494: YYDEBUG(1494, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'X') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'W') goto yy142; goto yy1498; } } else { if (yych <= 'w') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'x') goto yy1498; if (yych <= 'z') goto yy142; goto yy4; } } yy1495: YYDEBUG(1495, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'M') goto yy142; } } else { if (yych <= 'm') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'n') goto yy1496; if (yych <= 'z') goto yy142; goto yy4; } } yy1496: YYDEBUG(1496, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy143; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 't') goto yy1497; if (yych <= 'z') goto yy143; goto yy4; } } yy1497: YYDEBUG(1497, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'H') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'G') goto yy144; goto yy1239; } } else { if (yych <= 'g') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'h') goto yy1239; if (yych <= 'z') goto yy144; goto yy4; } } yy1498: YYDEBUG(1498, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy143; goto yy1428; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 't') goto yy1428; if (yych <= 'z') goto yy143; goto yy4; } } yy1499: YYDEBUG(1499, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '@') { if (yych == ')') goto yy140; } else { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy1500; if (yych <= 'z') goto yy143; } yy1500: YYDEBUG(1500, *YYCURSOR); #line 1014 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("now"); TIMELIB_INIT; TIMELIB_DEINIT; return TIMELIB_RELATIVE; } #line 23901 "ext/date/lib/parse_date.c" yy1501: YYDEBUG(1501, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'M') goto yy143; goto yy1507; } } else { if (yych <= 'm') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'n') goto yy1507; if (yych <= 'z') goto yy143; goto yy4; } } yy1502: YYDEBUG(1502, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; goto yy194; } else { if (yych <= '-') goto yy197; if (yych <= '.') goto yy196; goto yy194; } } } else { if (yych <= 'Z') { if (yych <= '@') { if (yych <= '9') goto yy196; goto yy194; } else { if (yych != 'E') goto yy143; } } else { if (yych <= 'd') { if (yych <= '`') goto yy194; goto yy143; } else { if (yych <= 'e') goto yy1503; if (yych <= 'z') goto yy143; goto yy194; } } } yy1503: YYDEBUG(1503, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'M') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'L') goto yy144; } } else { if (yych <= 'l') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'm') goto yy1504; if (yych <= 'z') goto yy144; goto yy4; } } yy1504: YYDEBUG(1504, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'B') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'A') goto yy145; } } else { if (yych <= 'a') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'b') goto yy1505; if (yych <= 'z') goto yy145; goto yy4; } } yy1505: YYDEBUG(1505, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'E') goto yy1506; if (yych != 'e') goto yy4; } yy1506: YYDEBUG(1506, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy206; if (yych == 'r') goto yy206; goto yy57; yy1507: YYDEBUG(1507, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '@') { if (yych == ')') goto yy140; } else { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy1508; if (yych <= 'z') goto yy144; } yy1508: YYDEBUG(1508, *YYCURSOR); #line 1023 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("noon"); TIMELIB_INIT; TIMELIB_UNHAVE_TIME(); TIMELIB_HAVE_TIME(); s->time->h = 12; TIMELIB_DEINIT; return TIMELIB_RELATIVE; } #line 24051 "ext/date/lib/parse_date.c" yy1509: YYDEBUG(1509, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'V') { if (yych <= '.') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych == '-') goto yy148; goto yy4; } } else { if (yych <= 'N') { if (yych <= '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } else { if (yych <= 'O') goto yy1501; if (yych <= 'U') goto yy142; goto yy1502; } } } else { if (yych <= 'n') { if (yych <= '^') { if (yych <= 'W') goto yy1499; if (yych <= 'Z') goto yy142; goto yy4; } else { if (yych <= '_') goto yy148; if (yych <= '`') goto yy4; goto yy147; } } else { if (yych <= 'v') { if (yych <= 'o') goto yy1516; if (yych <= 'u') goto yy147; goto yy1517; } else { if (yych <= 'w') goto yy1515; if (yych <= 'z') goto yy147; goto yy4; } } } yy1510: YYDEBUG(1510, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'W') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'X') goto yy1498; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'w') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'x') goto yy1514; if (yych <= 'z') goto yy147; goto yy4; } } } yy1511: YYDEBUG(1511, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'M') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'N') goto yy1496; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'm') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'n') goto yy1512; if (yych <= 'z') goto yy147; goto yy4; } } } yy1512: YYDEBUG(1512, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1497; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 't') goto yy1513; if (yych <= 'z') goto yy151; goto yy4; } } } yy1513: YYDEBUG(1513, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'G') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'H') goto yy1239; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'g') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'h') goto yy1268; if (yych <= 'z') goto yy152; goto yy4; } } } yy1514: YYDEBUG(1514, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1428; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 't') goto yy1460; if (yych <= 'z') goto yy151; goto yy4; } } } yy1515: YYDEBUG(1515, *YYCURSOR); yyaccept = 31; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy1500; } else { if (yych == '.') goto yy1500; goto yy148; } } else { if (yych <= '^') { if (yych <= '@') goto yy1500; if (yych <= 'Z') goto yy143; goto yy1500; } else { if (yych <= '_') goto yy148; if (yych <= '`') goto yy1500; if (yych <= 'z') goto yy151; goto yy1500; } } yy1516: YYDEBUG(1516, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'M') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'N') goto yy1507; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'm') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 'n') goto yy1522; if (yych <= 'z') goto yy151; goto yy4; } } } yy1517: YYDEBUG(1517, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= '-') { if (yych <= ')') goto yy140; if (yych <= ',') goto yy194; goto yy372; } else { if (yych == '/') goto yy148; goto yy196; } } } else { if (yych <= '^') { if (yych <= 'D') { if (yych <= '@') goto yy194; goto yy143; } else { if (yych <= 'E') goto yy1503; if (yych <= 'Z') goto yy143; goto yy194; } } else { if (yych <= 'd') { if (yych <= '_') goto yy148; if (yych <= '`') goto yy194; goto yy151; } else { if (yych <= 'e') goto yy1518; if (yych <= 'z') goto yy151; goto yy194; } } } yy1518: YYDEBUG(1518, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'L') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'M') goto yy1504; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'l') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'm') goto yy1519; if (yych <= 'z') goto yy152; goto yy4; } } } yy1519: YYDEBUG(1519, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'A') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'B') goto yy1505; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'a') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'b') goto yy1520; if (yych <= 'z') goto yy153; goto yy4; } } } yy1520: YYDEBUG(1520, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'E') goto yy1506; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'e') goto yy1521; if (yych <= 'z') goto yy154; goto yy4; } } yy1521: YYDEBUG(1521, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy206; if (yych == 'r') goto yy377; goto yy155; yy1522: YYDEBUG(1522, *YYCURSOR); yyaccept = 32; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy1508; } else { if (yych == '.') goto yy1508; goto yy148; } } else { if (yych <= '^') { if (yych <= '@') goto yy1508; if (yych <= 'Z') goto yy144; goto yy1508; } else { if (yych <= '_') goto yy148; if (yych <= '`') goto yy1508; if (yych <= 'z') goto yy152; goto yy1508; } } yy1523: YYDEBUG(1523, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'R') goto yy142; } } else { if (yych <= 'r') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 's') goto yy1524; if (yych <= 'z') goto yy142; goto yy4; } } yy1524: YYDEBUG(1524, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy143; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 't') goto yy1525; if (yych <= 'z') goto yy143; goto yy4; } } yy1525: YYDEBUG(1525, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy144; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'e') goto yy1526; if (yych <= 'z') goto yy144; goto yy4; } } yy1526: YYDEBUG(1526, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'Q') goto yy145; } } else { if (yych <= 'q') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'r') goto yy1527; if (yych <= 'z') goto yy145; goto yy4; } } yy1527: YYDEBUG(1527, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'D') goto yy1528; if (yych != 'd') goto yy4; } yy1528: YYDEBUG(1528, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1529; if (yych != 'a') goto yy57; yy1529: YYDEBUG(1529, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy1530; if (yych != 'y') goto yy57; yy1530: YYDEBUG(1530, *YYCURSOR); ++YYCURSOR; yy1531: YYDEBUG(1531, *YYCURSOR); #line 1002 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("yesterday"); TIMELIB_INIT; TIMELIB_HAVE_RELATIVE(); TIMELIB_UNHAVE_TIME(); s->time->relative.d = -1; TIMELIB_DEINIT; return TIMELIB_RELATIVE; } #line 24595 "ext/date/lib/parse_date.c" yy1532: YYDEBUG(1532, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'R') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'S') goto yy1524; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'r') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 's') goto yy1533; if (yych <= 'z') goto yy147; goto yy4; } } } yy1533: YYDEBUG(1533, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1525; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 't') goto yy1534; if (yych <= 'z') goto yy151; goto yy4; } } } yy1534: YYDEBUG(1534, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'E') goto yy1526; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'd') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'e') goto yy1535; if (yych <= 'z') goto yy152; goto yy4; } } } yy1535: YYDEBUG(1535, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'Q') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'R') goto yy1527; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'q') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'r') goto yy1536; if (yych <= 'z') goto yy153; goto yy4; } } } yy1536: YYDEBUG(1536, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'D') goto yy1528; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'd') goto yy1537; if (yych <= 'z') goto yy154; goto yy4; } } yy1537: YYDEBUG(1537, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1529; if (yych != 'a') goto yy155; YYDEBUG(1538, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy1530; if (yych != 'y') goto yy155; YYDEBUG(1539, *YYCURSOR); yyaccept = 33; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 16) { goto yy154; } if (yych <= '.') { if (yych == '-') goto yy148; goto yy1531; } else { if (yych <= '/') goto yy148; if (yych == '_') goto yy148; goto yy1531; } } #line 1775 "ext/date/lib/parse_date.re" } #define YYMAXFILL 31 timelib_time* timelib_strtotime(char *s, int len, struct timelib_error_container **errors, const timelib_tzdb *tzdb) { Scanner in; int t; char *e = s + len - 1; memset(&in, 0, sizeof(in)); in.errors = malloc(sizeof(struct timelib_error_container)); in.errors->warning_count = 0; in.errors->warning_messages = NULL; in.errors->error_count = 0; in.errors->error_messages = NULL; if (len > 0) { while (isspace(*s) && s < e) { s++; } while (isspace(*e) && e > s) { e--; } } if (e - s < 0) { in.time = timelib_time_ctor(); add_error(&in, "Empty string"); if (errors) { *errors = in.errors; } else { timelib_error_container_dtor(in.errors); } in.time->y = in.time->d = in.time->m = in.time->h = in.time->i = in.time->s = in.time->f = in.time->dst = in.time->z = TIMELIB_UNSET; in.time->is_localtime = in.time->zone_type = 0; return in.time; } e++; in.str = malloc((e - s) + YYMAXFILL); memset(in.str, 0, (e - s) + YYMAXFILL); memcpy(in.str, s, (e - s)); in.lim = in.str + (e - s) + YYMAXFILL; in.cur = in.str; in.time = timelib_time_ctor(); in.time->y = TIMELIB_UNSET; in.time->d = TIMELIB_UNSET; in.time->m = TIMELIB_UNSET; in.time->h = TIMELIB_UNSET; in.time->i = TIMELIB_UNSET; in.time->s = TIMELIB_UNSET; in.time->f = TIMELIB_UNSET; in.time->z = TIMELIB_UNSET; in.time->dst = TIMELIB_UNSET; in.tzdb = tzdb; in.time->is_localtime = 0; in.time->zone_type = 0; do { t = scan(&in); #ifdef DEBUG_PARSER printf("%d\n", t); #endif } while(t != EOI); /* do funky checking whether the parsed time was valid time */ if (in.time->have_time && !timelib_valid_time( in.time->h, in.time->i, in.time->s)) { add_warning(&in, "The parsed time was invalid"); } /* do funky checking whether the parsed date was valid date */ if (in.time->have_date && !timelib_valid_date( in.time->y, in.time->m, in.time->d)) { add_warning(&in, "The parsed date was invalid"); } free(in.str); if (errors) { *errors = in.errors; } else { timelib_error_container_dtor(in.errors); } return in.time; } #define TIMELIB_CHECK_NUMBER \ if (strchr("0123456789", *ptr) == NULL) \ { \ add_pbf_error(s, "Unexpected data found.", string, begin); \ } static void timelib_time_reset_fields(timelib_time *time) { assert(time != NULL); time->y = 1970; time->m = 1; time->d = 1; time->h = time->i = time->s = 0; time->f = 0.0; time->tz_info = NULL; } static void timelib_time_reset_unset_fields(timelib_time *time) { assert(time != NULL); if (time->y == TIMELIB_UNSET ) time->y = 1970; if (time->m == TIMELIB_UNSET ) time->m = 1; if (time->d == TIMELIB_UNSET ) time->d = 1; if (time->h == TIMELIB_UNSET ) time->h = 0; if (time->i == TIMELIB_UNSET ) time->i = 0; if (time->s == TIMELIB_UNSET ) time->s = 0; if (time->f == TIMELIB_UNSET ) time->f = 0.0; } timelib_time *timelib_parse_from_format(char *format, char *string, int len, timelib_error_container **errors, const timelib_tzdb *tzdb) { char *fptr = format; char *ptr = string; char *begin; timelib_sll tmp; Scanner in; Scanner *s = &in; int allow_extra = 0; memset(&in, 0, sizeof(in)); in.errors = malloc(sizeof(struct timelib_error_container)); in.errors->warning_count = 0; in.errors->warning_messages = NULL; in.errors->error_count = 0; in.errors->error_messages = NULL; in.time = timelib_time_ctor(); in.time->y = TIMELIB_UNSET; in.time->d = TIMELIB_UNSET; in.time->m = TIMELIB_UNSET; in.time->h = TIMELIB_UNSET; in.time->i = TIMELIB_UNSET; in.time->s = TIMELIB_UNSET; in.time->f = TIMELIB_UNSET; in.time->z = TIMELIB_UNSET; in.time->dst = TIMELIB_UNSET; in.tzdb = tzdb; in.time->is_localtime = 0; in.time->zone_type = 0; /* Loop over the format string */ while (*fptr && *ptr) { begin = ptr; switch (*fptr) { case 'D': /* three letter day */ case 'l': /* full day */ if (!timelib_lookup_relunit((char **) &ptr)) { add_pbf_error(s, "A textual day could not be found", string, begin); } break; case 'd': /* two digit day, with leading zero */ case 'j': /* two digit day, without leading zero */ TIMELIB_CHECK_NUMBER; if ((s->time->d = timelib_get_nr((char **) &ptr, 2)) == TIMELIB_UNSET) { add_pbf_error(s, "A two digit day could not be found", string, begin); } break; case 'S': /* day suffix, ignored, nor checked */ timelib_skip_day_suffix((char **) &ptr); break; case 'z': /* day of year - resets month (0 based) */ TIMELIB_CHECK_NUMBER; if ((tmp = timelib_get_nr((char **) &ptr, 3)) == TIMELIB_UNSET) { add_pbf_error(s, "A three digit day-of-year could not be found", string, begin); } else { s->time->m = 1; s->time->d = tmp + 1; } break; case 'm': /* two digit month, with leading zero */ case 'n': /* two digit month, without leading zero */ TIMELIB_CHECK_NUMBER; if ((s->time->m = timelib_get_nr((char **) &ptr, 2)) == TIMELIB_UNSET) { add_pbf_error(s, "A two digit month could not be found", string, begin); } break; case 'M': /* three letter month */ case 'F': /* full month */ tmp = timelib_lookup_month((char **) &ptr); if (!tmp) { add_pbf_error(s, "A textual month could not be found", string, begin); } else { s->time->m = tmp; } break; case 'y': /* two digit year */ { int length = 0; TIMELIB_CHECK_NUMBER; if ((s->time->y = timelib_get_nr_ex((char **) &ptr, 2, &length)) == TIMELIB_UNSET) { add_pbf_error(s, "A two digit year could not be found", string, begin); } TIMELIB_PROCESS_YEAR(s->time->y, length); } break; case 'Y': /* four digit year */ TIMELIB_CHECK_NUMBER; if ((s->time->y = timelib_get_nr((char **) &ptr, 4)) == TIMELIB_UNSET) { add_pbf_error(s, "A four digit year could not be found", string, begin); } break; case 'g': /* two digit hour, with leading zero */ case 'h': /* two digit hour, without leading zero */ TIMELIB_CHECK_NUMBER; if ((s->time->h = timelib_get_nr((char **) &ptr, 2)) == TIMELIB_UNSET) { add_pbf_error(s, "A two digit hour could not be found", string, begin); } if (s->time->h > 12) { add_pbf_error(s, "Hour can not be higher than 12", string, begin); } break; case 'G': /* two digit hour, with leading zero */ case 'H': /* two digit hour, without leading zero */ TIMELIB_CHECK_NUMBER; if ((s->time->h = timelib_get_nr((char **) &ptr, 2)) == TIMELIB_UNSET) { add_pbf_error(s, "A two digit hour could not be found", string, begin); } break; case 'a': /* am/pm/a.m./p.m. */ case 'A': /* AM/PM/A.M./P.M. */ if (s->time->h == TIMELIB_UNSET) { add_pbf_error(s, "Meridian can only come after an hour has been found", string, begin); } else if ((tmp = timelib_meridian_with_check((char **) &ptr, s->time->h)) == TIMELIB_UNSET) { add_pbf_error(s, "A meridian could not be found", string, begin); } else { s->time->h += tmp; } break; case 'i': /* two digit minute, with leading zero */ TIMELIB_CHECK_NUMBER; if ((s->time->i = timelib_get_nr((char **) &ptr, 2)) == TIMELIB_UNSET) { add_pbf_error(s, "A two digit minute could not be found", string, begin); } break; case 's': /* two digit second, with leading zero */ TIMELIB_CHECK_NUMBER; if ((s->time->s = timelib_get_nr((char **) &ptr, 2)) == TIMELIB_UNSET) { add_pbf_error(s, "A two digit second could not be found", string, begin); } break; case 'u': /* up to six digit millisecond */ { double f; char *tptr; TIMELIB_CHECK_NUMBER; tptr = ptr; if ((f = timelib_get_nr((char **) &ptr, 6)) == TIMELIB_UNSET || (ptr - tptr < 1)) { add_pbf_error(s, "A six digit millisecond could not be found", string, begin); } else { s->time->f = (f / pow(10, (ptr - tptr))); } } break; case ' ': /* any sort of whitespace (' ' and \t) */ timelib_eat_spaces((char **) &ptr); break; case 'U': /* epoch seconds */ TIMELIB_CHECK_NUMBER; TIMELIB_HAVE_RELATIVE(); tmp = timelib_get_unsigned_nr((char **) &ptr, 24); s->time->y = 1970; s->time->m = 1; s->time->d = 1; s->time->h = s->time->i = s->time->s = 0; s->time->f = 0.0; s->time->relative.s += tmp; s->time->is_localtime = 1; s->time->zone_type = TIMELIB_ZONETYPE_OFFSET; s->time->z = 0; break; case 'e': /* timezone */ case 'P': /* timezone */ case 'T': /* timezone */ case 'O': /* timezone */ { int tz_not_found; s->time->z = timelib_get_zone((char **) &ptr, &s->time->dst, s->time, &tz_not_found, s->tzdb); if (tz_not_found) { add_pbf_error(s, "The timezone could not be found in the database", string, begin); } } break; case '#': /* separation symbol */ if (*ptr == ';' || *ptr == ':' || *ptr == '/' || *ptr == '.' || *ptr == ',' || *ptr == '-' || *ptr == '(' || *ptr == ')') { ++ptr; } else { add_pbf_error(s, "The separation symbol ([;:/.,-]) could not be found", string, begin); } break; case ';': case ':': case '/': case '.': case ',': case '-': case '(': case ')': if (*ptr == *fptr) { ++ptr; } else { add_pbf_error(s, "The separation symbol could not be found", string, begin); } break; case '!': /* reset all fields to default */ timelib_time_reset_fields(s->time); break; /* break intentionally not missing */ case '|': /* reset all fields to default when not set */ timelib_time_reset_unset_fields(s->time); break; /* break intentionally not missing */ case '?': /* random char */ ++ptr; break; case '\\': /* escaped char */ *fptr++; if (*ptr == *fptr) { ++ptr; } else { add_pbf_error(s, "The escaped character could not be found", string, begin); } break; case '*': /* random chars until a separator or number ([ \t.,:;/-0123456789]) */ timelib_eat_until_separator((char **) &ptr); break; case '+': /* allow extra chars in the format */ allow_extra = 1; break; default: if (*fptr != *ptr) { add_pbf_error(s, "The format separator does not match", string, begin); } ptr++; } fptr++; } if (*ptr) { if (allow_extra) { add_pbf_warning(s, "Trailing data", string, ptr); } else { add_pbf_error(s, "Trailing data", string, ptr); } } /* ignore trailing +'s */ while (*fptr == '+') { fptr++; } if (*fptr) { /* Trailing | and ! specifiers are valid. */ int done = 0; while (*fptr && !done) { switch (*fptr++) { case '!': /* reset all fields to default */ timelib_time_reset_fields(s->time); break; case '|': /* reset all fields to default when not set */ timelib_time_reset_unset_fields(s->time); break; default: add_pbf_error(s, "Data missing", string, ptr); done = 1; } } } /* clean up a bit */ if (s->time->h != TIMELIB_UNSET || s->time->i != TIMELIB_UNSET || s->time->s != TIMELIB_UNSET) { if (s->time->h == TIMELIB_UNSET ) { s->time->h = 0; } if (s->time->i == TIMELIB_UNSET ) { s->time->i = 0; } if (s->time->s == TIMELIB_UNSET ) { s->time->s = 0; } } /* do funky checking whether the parsed time was valid time */ if (s->time->h != TIMELIB_UNSET && s->time->i != TIMELIB_UNSET && s->time->s != TIMELIB_UNSET && !timelib_valid_time( s->time->h, s->time->i, s->time->s)) { add_pbf_warning(s, "The parsed time was invalid", string, ptr); } /* do funky checking whether the parsed date was valid date */ if (s->time->y != TIMELIB_UNSET && s->time->m != TIMELIB_UNSET && s->time->d != TIMELIB_UNSET && !timelib_valid_date( s->time->y, s->time->m, s->time->d)) { add_pbf_warning(s, "The parsed date was invalid", string, ptr); } if (errors) { *errors = in.errors; } else { timelib_error_container_dtor(in.errors); } return in.time; } void timelib_fill_holes(timelib_time *parsed, timelib_time *now, int options) { if (!(options & TIMELIB_OVERRIDE_TIME) && parsed->have_date && !parsed->have_time) { parsed->h = 0; parsed->i = 0; parsed->s = 0; parsed->f = 0; } if (parsed->y == TIMELIB_UNSET) parsed->y = now->y != TIMELIB_UNSET ? now->y : 0; if (parsed->d == TIMELIB_UNSET) parsed->d = now->d != TIMELIB_UNSET ? now->d : 0; if (parsed->m == TIMELIB_UNSET) parsed->m = now->m != TIMELIB_UNSET ? now->m : 0; if (parsed->h == TIMELIB_UNSET) parsed->h = now->h != TIMELIB_UNSET ? now->h : 0; if (parsed->i == TIMELIB_UNSET) parsed->i = now->i != TIMELIB_UNSET ? now->i : 0; if (parsed->s == TIMELIB_UNSET) parsed->s = now->s != TIMELIB_UNSET ? now->s : 0; if (parsed->f == TIMELIB_UNSET) parsed->f = now->f != TIMELIB_UNSET ? now->f : 0; if (parsed->z == TIMELIB_UNSET) parsed->z = now->z != TIMELIB_UNSET ? now->z : 0; if (parsed->dst == TIMELIB_UNSET) parsed->dst = now->dst != TIMELIB_UNSET ? now->dst : 0; if (!parsed->tz_abbr) { parsed->tz_abbr = now->tz_abbr ? strdup(now->tz_abbr) : NULL; } if (!parsed->tz_info) { parsed->tz_info = now->tz_info ? (!(options & TIMELIB_NO_CLONE) ? timelib_tzinfo_clone(now->tz_info) : now->tz_info) : NULL; } if (parsed->zone_type == 0 && now->zone_type != 0) { parsed->zone_type = now->zone_type; /* parsed->tz_abbr = now->tz_abbr ? strdup(now->tz_abbr) : NULL; parsed->tz_info = now->tz_info ? timelib_tzinfo_clone(now->tz_info) : NULL; */ parsed->is_localtime = 1; } /* timelib_dump_date(parsed, 2); timelib_dump_date(now, 2); */ } char *timelib_timezone_id_from_abbr(const char *abbr, long gmtoffset, int isdst) { const timelib_tz_lookup_table *tp; tp = zone_search(abbr, gmtoffset, isdst); if (tp) { return (tp->full_tz_name); } else { return NULL; } } const timelib_tz_lookup_table *timelib_timezone_abbreviations_list(void) { return timelib_timezone_lookup; } #ifdef DEBUG_PARSER_STUB int main(void) { timelib_time time = timelib_strtotime("May 12"); printf ("%04d-%02d-%02d %02d:%02d:%02d.%-5d %+04d %1d", time.y, time.m, time.d, time.h, time.i, time.s, time.f, time.z, time.dst); if (time.have_relative) { printf ("%3dY %3dM %3dD / %3dH %3dM %3dS", time.relative.y, time.relative.m, time.relative.d, time.relative.h, time.relative.i, time.relative.s); } if (time.have_weekday_relative) { printf (" / %d", time.relative.weekday); } if (time.have_weeknr_day) { printf(" / %dW%d", time.relative.weeknr_day.weeknr, time.relative.weeknr_day.dayofweek); } return 0; } #endif /* * vim: syntax=c */ /* Generated by re2c 0.13.5 on Sat Nov 26 16:43:35 2011 */ #line 1 "ext/date/lib/parse_date.re" /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2010 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Derick Rethans <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "timelib.h" #include <stdio.h> #include <ctype.h> #include <math.h> #include <assert.h> #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #ifdef HAVE_STRING_H #include <string.h> #else #include <strings.h> #endif #if defined(_MSC_VER) # define strtoll(s, f, b) _atoi64(s) #elif !defined(HAVE_STRTOLL) # if defined(HAVE_ATOLL) # define strtoll(s, f, b) atoll(s) # else # define strtoll(s, f, b) strtol(s, f, b) # endif #endif #define TIMELIB_UNSET -99999 #define TIMELIB_SECOND 1 #define TIMELIB_MINUTE 2 #define TIMELIB_HOUR 3 #define TIMELIB_DAY 4 #define TIMELIB_MONTH 5 #define TIMELIB_YEAR 6 #define TIMELIB_WEEKDAY 7 #define TIMELIB_SPECIAL 8 #define EOI 257 #define TIME 258 #define DATE 259 #define TIMELIB_XMLRPC_SOAP 260 #define TIMELIB_TIME12 261 #define TIMELIB_TIME24 262 #define TIMELIB_GNU_NOCOLON 263 #define TIMELIB_GNU_NOCOLON_TZ 264 #define TIMELIB_ISO_NOCOLON 265 #define TIMELIB_AMERICAN 266 #define TIMELIB_ISO_DATE 267 #define TIMELIB_DATE_FULL 268 #define TIMELIB_DATE_TEXT 269 #define TIMELIB_DATE_NOCOLON 270 #define TIMELIB_PG_YEARDAY 271 #define TIMELIB_PG_TEXT 272 #define TIMELIB_PG_REVERSE 273 #define TIMELIB_CLF 274 #define TIMELIB_DATE_NO_DAY 275 #define TIMELIB_SHORTDATE_WITH_TIME 276 #define TIMELIB_DATE_FULL_POINTED 277 #define TIMELIB_TIME24_WITH_ZONE 278 #define TIMELIB_ISO_WEEK 279 #define TIMELIB_LF_DAY_OF_MONTH 280 #define TIMELIB_WEEK_DAY_OF_MONTH 281 #define TIMELIB_TIMEZONE 300 #define TIMELIB_AGO 301 #define TIMELIB_RELATIVE 310 #define TIMELIB_ERROR 999 /* Some compilers like AIX, defines uchar in sys/types.h */ #undef uchar typedef unsigned char uchar; #define BSIZE 8192 #define YYCTYPE uchar #define YYCURSOR cursor #define YYLIMIT s->lim #define YYMARKER s->ptr #define YYFILL(n) return EOI; #define RET(i) {s->cur = cursor; return i;} #define timelib_string_free free #define TIMELIB_HAVE_TIME() { if (s->time->have_time) { add_error(s, "Double time specification"); timelib_string_free(str); return TIMELIB_ERROR; } else { s->time->have_time = 1; s->time->h = 0; s->time->i = 0; s->time->s = 0; s->time->f = 0; } } #define TIMELIB_UNHAVE_TIME() { s->time->have_time = 0; s->time->h = 0; s->time->i = 0; s->time->s = 0; s->time->f = 0; } #define TIMELIB_HAVE_DATE() { if (s->time->have_date) { add_error(s, "Double date specification"); timelib_string_free(str); return TIMELIB_ERROR; } else { s->time->have_date = 1; } } #define TIMELIB_UNHAVE_DATE() { s->time->have_date = 0; s->time->d = 0; s->time->m = 0; s->time->y = 0; } #define TIMELIB_HAVE_RELATIVE() { s->time->have_relative = 1; } #define TIMELIB_HAVE_WEEKDAY_RELATIVE() { s->time->have_relative = 1; s->time->relative.have_weekday_relative = 1; } #define TIMELIB_HAVE_SPECIAL_RELATIVE() { s->time->have_relative = 1; s->time->relative.have_special_relative = 1; } #define TIMELIB_HAVE_TZ() { s->cur = cursor; if (s->time->have_zone) { s->time->have_zone > 1 ? add_error(s, "Double timezone specification") : add_warning(s, "Double timezone specification"); timelib_string_free(str); s->time->have_zone++; return TIMELIB_ERROR; } else { s->time->have_zone++; } } #define TIMELIB_INIT s->cur = cursor; str = timelib_string(s); ptr = str #define TIMELIB_DEINIT timelib_string_free(str) #define TIMELIB_ADJUST_RELATIVE_WEEKDAY() if (in->time.have_weekday_relative && (in.rel.d > 0)) { in.rel.d -= 7; } #define TIMELIB_PROCESS_YEAR(x, l) { \ if (((x) == TIMELIB_UNSET) || ((l) >= 4)) { \ /* (x) = 0; */ \ } else if ((x) < 100) { \ if ((x) < 70) { \ (x) += 2000; \ } else { \ (x) += 1900; \ } \ } \ } #ifdef DEBUG_PARSER #define DEBUG_OUTPUT(s) printf("%s\n", s); #define YYDEBUG(s,c) { if (s != -1) { printf("state: %d ", s); printf("[%c]\n", c); } } #else #define DEBUG_OUTPUT(s) #define YYDEBUG(s,c) #endif #include "timelib_structs.h" typedef struct timelib_elems { unsigned int c; /* Number of elements */ char **v; /* Values */ } timelib_elems; typedef struct Scanner { int fd; uchar *lim, *str, *ptr, *cur, *tok, *pos; unsigned int line, len; struct timelib_error_container *errors; struct timelib_time *time; const timelib_tzdb *tzdb; } Scanner; typedef struct _timelib_lookup_table { const char *name; int type; int value; } timelib_lookup_table; typedef struct _timelib_relunit { const char *name; int unit; int multiplier; } timelib_relunit; #define HOUR(a) (int)(a * 60) /* The timezone table. */ const static timelib_tz_lookup_table timelib_timezone_lookup[] = { #include "timezonemap.h" { NULL, 0, 0, NULL }, }; const static timelib_tz_lookup_table timelib_timezone_fallbackmap[] = { #include "fallbackmap.h" { NULL, 0, 0, NULL }, }; const static timelib_tz_lookup_table timelib_timezone_utc[] = { { "utc", 0, 0, "UTC" }, }; static timelib_relunit const timelib_relunit_lookup[] = { { "sec", TIMELIB_SECOND, 1 }, { "secs", TIMELIB_SECOND, 1 }, { "second", TIMELIB_SECOND, 1 }, { "seconds", TIMELIB_SECOND, 1 }, { "min", TIMELIB_MINUTE, 1 }, { "mins", TIMELIB_MINUTE, 1 }, { "minute", TIMELIB_MINUTE, 1 }, { "minutes", TIMELIB_MINUTE, 1 }, { "hour", TIMELIB_HOUR, 1 }, { "hours", TIMELIB_HOUR, 1 }, { "day", TIMELIB_DAY, 1 }, { "days", TIMELIB_DAY, 1 }, { "week", TIMELIB_DAY, 7 }, { "weeks", TIMELIB_DAY, 7 }, { "fortnight", TIMELIB_DAY, 14 }, { "fortnights", TIMELIB_DAY, 14 }, { "forthnight", TIMELIB_DAY, 14 }, { "forthnights", TIMELIB_DAY, 14 }, { "month", TIMELIB_MONTH, 1 }, { "months", TIMELIB_MONTH, 1 }, { "year", TIMELIB_YEAR, 1 }, { "years", TIMELIB_YEAR, 1 }, { "monday", TIMELIB_WEEKDAY, 1 }, { "mon", TIMELIB_WEEKDAY, 1 }, { "tuesday", TIMELIB_WEEKDAY, 2 }, { "tue", TIMELIB_WEEKDAY, 2 }, { "wednesday", TIMELIB_WEEKDAY, 3 }, { "wed", TIMELIB_WEEKDAY, 3 }, { "thursday", TIMELIB_WEEKDAY, 4 }, { "thu", TIMELIB_WEEKDAY, 4 }, { "friday", TIMELIB_WEEKDAY, 5 }, { "fri", TIMELIB_WEEKDAY, 5 }, { "saturday", TIMELIB_WEEKDAY, 6 }, { "sat", TIMELIB_WEEKDAY, 6 }, { "sunday", TIMELIB_WEEKDAY, 0 }, { "sun", TIMELIB_WEEKDAY, 0 }, { "weekday", TIMELIB_SPECIAL, TIMELIB_SPECIAL_WEEKDAY }, { "weekdays", TIMELIB_SPECIAL, TIMELIB_SPECIAL_WEEKDAY }, { NULL, 0, 0 } }; /* The relative text table. */ static timelib_lookup_table const timelib_reltext_lookup[] = { { "first", 0, 1 }, { "next", 0, 1 }, { "second", 0, 2 }, { "third", 0, 3 }, { "fourth", 0, 4 }, { "fifth", 0, 5 }, { "sixth", 0, 6 }, { "seventh", 0, 7 }, { "eight", 0, 8 }, { "eighth", 0, 8 }, { "ninth", 0, 9 }, { "tenth", 0, 10 }, { "eleventh", 0, 11 }, { "twelfth", 0, 12 }, { "last", 0, -1 }, { "previous", 0, -1 }, { "this", 1, 0 }, { NULL, 1, 0 } }; /* The month table. */ static timelib_lookup_table const timelib_month_lookup[] = { { "jan", 0, 1 }, { "feb", 0, 2 }, { "mar", 0, 3 }, { "apr", 0, 4 }, { "may", 0, 5 }, { "jun", 0, 6 }, { "jul", 0, 7 }, { "aug", 0, 8 }, { "sep", 0, 9 }, { "sept", 0, 9 }, { "oct", 0, 10 }, { "nov", 0, 11 }, { "dec", 0, 12 }, { "i", 0, 1 }, { "ii", 0, 2 }, { "iii", 0, 3 }, { "iv", 0, 4 }, { "v", 0, 5 }, { "vi", 0, 6 }, { "vii", 0, 7 }, { "viii", 0, 8 }, { "ix", 0, 9 }, { "x", 0, 10 }, { "xi", 0, 11 }, { "xii", 0, 12 }, { "january", 0, 1 }, { "february", 0, 2 }, { "march", 0, 3 }, { "april", 0, 4 }, { "may", 0, 5 }, { "june", 0, 6 }, { "july", 0, 7 }, { "august", 0, 8 }, { "september", 0, 9 }, { "october", 0, 10 }, { "november", 0, 11 }, { "december", 0, 12 }, { NULL, 0, 0 } }; #if 0 static char* timelib_ltrim(char *s) { char *ptr = s; while (ptr[0] == ' ' || ptr[0] == '\t') { ptr++; } return ptr; } #endif #if 0 uchar *fill(Scanner *s, uchar *cursor){ if(!s->eof){ unsigned int cnt = s->tok - s->bot; if(cnt){ memcpy(s->bot, s->tok, s->lim - s->tok); s->tok = s->bot; s->ptr -= cnt; cursor -= cnt; s->pos -= cnt; s->lim -= cnt; } if((s->top - s->lim) < BSIZE){ uchar *buf = (uchar*) malloc(((s->lim - s->bot) + BSIZE)*sizeof(uchar)); memcpy(buf, s->tok, s->lim - s->tok); s->tok = buf; s->ptr = &buf[s->ptr - s->bot]; cursor = &buf[cursor - s->bot]; s->pos = &buf[s->pos - s->bot]; s->lim = &buf[s->lim - s->bot]; s->top = &s->lim[BSIZE]; free(s->bot); s->bot = buf; } if((cnt = read(s->fd, (char*) s->lim, BSIZE)) != BSIZE){ s->eof = &s->lim[cnt]; *(s->eof)++ = '\n'; } s->lim += cnt; } return cursor; } #endif static void add_warning(Scanner *s, char *error) { s->errors->warning_count++; s->errors->warning_messages = realloc(s->errors->warning_messages, s->errors->warning_count * sizeof(timelib_error_message)); s->errors->warning_messages[s->errors->warning_count - 1].position = s->tok ? s->tok - s->str : 0; s->errors->warning_messages[s->errors->warning_count - 1].character = s->tok ? *s->tok : 0; s->errors->warning_messages[s->errors->warning_count - 1].message = strdup(error); } static void add_error(Scanner *s, char *error) { s->errors->error_count++; s->errors->error_messages = realloc(s->errors->error_messages, s->errors->error_count * sizeof(timelib_error_message)); s->errors->error_messages[s->errors->error_count - 1].position = s->tok ? s->tok - s->str : 0; s->errors->error_messages[s->errors->error_count - 1].character = s->tok ? *s->tok : 0; s->errors->error_messages[s->errors->error_count - 1].message = strdup(error); } static void add_pbf_warning(Scanner *s, char *error, char *sptr, char *cptr) { s->errors->warning_count++; s->errors->warning_messages = realloc(s->errors->warning_messages, s->errors->warning_count * sizeof(timelib_error_message)); s->errors->warning_messages[s->errors->warning_count - 1].position = cptr - sptr; s->errors->warning_messages[s->errors->warning_count - 1].character = *cptr; s->errors->warning_messages[s->errors->warning_count - 1].message = strdup(error); } static void add_pbf_error(Scanner *s, char *error, char *sptr, char *cptr) { s->errors->error_count++; s->errors->error_messages = realloc(s->errors->error_messages, s->errors->error_count * sizeof(timelib_error_message)); s->errors->error_messages[s->errors->error_count - 1].position = cptr - sptr; s->errors->error_messages[s->errors->error_count - 1].character = *cptr; s->errors->error_messages[s->errors->error_count - 1].message = strdup(error); } static timelib_sll timelib_meridian(char **ptr, timelib_sll h) { timelib_sll retval = 0; while (!strchr("AaPp", **ptr)) { ++*ptr; } if (**ptr == 'a' || **ptr == 'A') { if (h == 12) { retval = -12; } } else if (h != 12) { retval = 12; } ++*ptr; if (**ptr == '.') { *ptr += 3; } else { ++*ptr; } return retval; } static timelib_sll timelib_meridian_with_check(char **ptr, timelib_sll h) { timelib_sll retval = 0; while (!strchr("AaPp", **ptr)) { ++*ptr; } if (**ptr == 'a' || **ptr == 'A') { if (h == 12) { retval = -12; } } else if (h != 12) { retval = 12; } ++*ptr; if (**ptr == '.') { ++*ptr; if (**ptr != 'm' && **ptr != 'M') { return TIMELIB_UNSET; } ++*ptr; if (**ptr != '.' ) { return TIMELIB_UNSET; } ++*ptr; } else if (**ptr == 'm' || **ptr == 'M') { ++*ptr; } else { return TIMELIB_UNSET; } return retval; } static char *timelib_string(Scanner *s) { char *tmp = calloc(1, s->cur - s->tok + 1); memcpy(tmp, s->tok, s->cur - s->tok); return tmp; } static timelib_sll timelib_get_nr_ex(char **ptr, int max_length, int *scanned_length) { char *begin, *end, *str; timelib_sll tmp_nr = TIMELIB_UNSET; int len = 0; while ((**ptr < '0') || (**ptr > '9')) { if (**ptr == '\0') { return TIMELIB_UNSET; } ++*ptr; } begin = *ptr; while ((**ptr >= '0') && (**ptr <= '9') && len < max_length) { ++*ptr; ++len; } end = *ptr; if (scanned_length) { *scanned_length = end - begin; } str = calloc(1, end - begin + 1); memcpy(str, begin, end - begin); tmp_nr = strtoll(str, NULL, 10); free(str); return tmp_nr; } static timelib_sll timelib_get_nr(char **ptr, int max_length) { return timelib_get_nr_ex(ptr, max_length, NULL); } static void timelib_skip_day_suffix(char **ptr) { if (isspace(**ptr)) { return; } if (!strncasecmp(*ptr, "nd", 2) || !strncasecmp(*ptr, "rd", 2) ||!strncasecmp(*ptr, "st", 2) || !strncasecmp(*ptr, "th", 2)) { *ptr += 2; } } static double timelib_get_frac_nr(char **ptr, int max_length) { char *begin, *end, *str; double tmp_nr = TIMELIB_UNSET; int len = 0; while ((**ptr != '.') && (**ptr != ':') && ((**ptr < '0') || (**ptr > '9'))) { if (**ptr == '\0') { return TIMELIB_UNSET; } ++*ptr; } begin = *ptr; while (((**ptr == '.') || (**ptr == ':') || ((**ptr >= '0') && (**ptr <= '9'))) && len < max_length) { ++*ptr; ++len; } end = *ptr; str = calloc(1, end - begin + 1); memcpy(str, begin, end - begin); if (str[0] == ':') { str[0] = '.'; } tmp_nr = strtod(str, NULL); free(str); return tmp_nr; } static timelib_ull timelib_get_unsigned_nr(char **ptr, int max_length) { timelib_ull dir = 1; while (((**ptr < '0') || (**ptr > '9')) && (**ptr != '+') && (**ptr != '-')) { if (**ptr == '\0') { return TIMELIB_UNSET; } ++*ptr; } while (**ptr == '+' || **ptr == '-') { if (**ptr == '-') { dir *= -1; } ++*ptr; } return dir * timelib_get_nr(ptr, max_length); } static long timelib_parse_tz_cor(char **ptr) { char *begin = *ptr, *end; long tmp; while (isdigit(**ptr) || **ptr == ':') { ++*ptr; } end = *ptr; switch (end - begin) { case 1: case 2: return HOUR(strtol(begin, NULL, 10)); break; case 3: case 4: if (begin[1] == ':') { tmp = HOUR(strtol(begin, NULL, 10)) + strtol(begin + 2, NULL, 10); return tmp; } else if (begin[2] == ':') { tmp = HOUR(strtol(begin, NULL, 10)) + strtol(begin + 3, NULL, 10); return tmp; } else { tmp = strtol(begin, NULL, 10); return HOUR(tmp / 100) + tmp % 100; } case 5: tmp = HOUR(strtol(begin, NULL, 10)) + strtol(begin + 3, NULL, 10); return tmp; } return 0; } static timelib_sll timelib_lookup_relative_text(char **ptr, int *behavior) { char *word; char *begin = *ptr, *end; timelib_sll value = 0; const timelib_lookup_table *tp; while ((**ptr >= 'A' && **ptr <= 'Z') || (**ptr >= 'a' && **ptr <= 'z')) { ++*ptr; } end = *ptr; word = calloc(1, end - begin + 1); memcpy(word, begin, end - begin); for (tp = timelib_reltext_lookup; tp->name; tp++) { if (strcasecmp(word, tp->name) == 0) { value = tp->value; *behavior = tp->type; } } free(word); return value; } static timelib_sll timelib_get_relative_text(char **ptr, int *behavior) { while (**ptr == ' ' || **ptr == '\t' || **ptr == '-' || **ptr == '/') { ++*ptr; } return timelib_lookup_relative_text(ptr, behavior); } static long timelib_lookup_month(char **ptr) { char *word; char *begin = *ptr, *end; long value = 0; const timelib_lookup_table *tp; while ((**ptr >= 'A' && **ptr <= 'Z') || (**ptr >= 'a' && **ptr <= 'z')) { ++*ptr; } end = *ptr; word = calloc(1, end - begin + 1); memcpy(word, begin, end - begin); for (tp = timelib_month_lookup; tp->name; tp++) { if (strcasecmp(word, tp->name) == 0) { value = tp->value; } } free(word); return value; } static long timelib_get_month(char **ptr) { while (**ptr == ' ' || **ptr == '\t' || **ptr == '-' || **ptr == '.' || **ptr == '/') { ++*ptr; } return timelib_lookup_month(ptr); } static void timelib_eat_spaces(char **ptr) { while (**ptr == ' ' || **ptr == '\t') { ++*ptr; } } static void timelib_eat_until_separator(char **ptr) { ++*ptr; while (strchr(" \t.,:;/-0123456789", **ptr) == NULL) { ++*ptr; } } static const timelib_relunit* timelib_lookup_relunit(char **ptr) { char *word; char *begin = *ptr, *end; const timelib_relunit *tp, *value = NULL; while (**ptr != '\0' && **ptr != ' ' && **ptr != ',' && **ptr != '\t') { ++*ptr; } end = *ptr; word = calloc(1, end - begin + 1); memcpy(word, begin, end - begin); for (tp = timelib_relunit_lookup; tp->name; tp++) { if (strcasecmp(word, tp->name) == 0) { value = tp; break; } } free(word); return value; } static void timelib_set_relative(char **ptr, timelib_sll amount, int behavior, Scanner *s) { const timelib_relunit* relunit; if (!(relunit = timelib_lookup_relunit(ptr))) { return; } switch (relunit->unit) { case TIMELIB_SECOND: s->time->relative.s += amount * relunit->multiplier; break; case TIMELIB_MINUTE: s->time->relative.i += amount * relunit->multiplier; break; case TIMELIB_HOUR: s->time->relative.h += amount * relunit->multiplier; break; case TIMELIB_DAY: s->time->relative.d += amount * relunit->multiplier; break; case TIMELIB_MONTH: s->time->relative.m += amount * relunit->multiplier; break; case TIMELIB_YEAR: s->time->relative.y += amount * relunit->multiplier; break; case TIMELIB_WEEKDAY: TIMELIB_HAVE_WEEKDAY_RELATIVE(); TIMELIB_UNHAVE_TIME(); s->time->relative.d += (amount > 0 ? amount - 1 : amount) * 7; s->time->relative.weekday = relunit->multiplier; s->time->relative.weekday_behavior = behavior; break; case TIMELIB_SPECIAL: TIMELIB_HAVE_SPECIAL_RELATIVE(); TIMELIB_UNHAVE_TIME(); s->time->relative.special.type = relunit->multiplier; s->time->relative.special.amount = amount; } } const static timelib_tz_lookup_table* zone_search(const char *word, long gmtoffset, int isdst) { int first_found = 0; const timelib_tz_lookup_table *tp, *first_found_elem = NULL; const timelib_tz_lookup_table *fmp; if (strcasecmp("utc", word) == 0 || strcasecmp("gmt", word) == 0) { return timelib_timezone_utc; } for (tp = timelib_timezone_lookup; tp->name; tp++) { if (strcasecmp(word, tp->name) == 0) { if (!first_found) { first_found = 1; first_found_elem = tp; if (gmtoffset == -1) { return tp; } } if (tp->gmtoffset == gmtoffset) { return tp; } } } if (first_found) { return first_found_elem; } for (tp = timelib_timezone_lookup; tp->name; tp++) { if (tp->full_tz_name && strcasecmp(word, tp->full_tz_name) == 0) { if (!first_found) { first_found = 1; first_found_elem = tp; if (gmtoffset == -1) { return tp; } } if (tp->gmtoffset == gmtoffset) { return tp; } } } if (first_found) { return first_found_elem; } /* Still didn't find anything, let's find the zone solely based on * offset/isdst then */ for (fmp = timelib_timezone_fallbackmap; fmp->name; fmp++) { if ((fmp->gmtoffset * 3600) == gmtoffset && fmp->type == isdst) { return fmp; } } return NULL; } static long timelib_lookup_zone(char **ptr, int *dst, char **tz_abbr, int *found) { char *word; char *begin = *ptr, *end; long value = 0; const timelib_tz_lookup_table *tp; while (**ptr != '\0' && **ptr != ')' && **ptr != ' ') { ++*ptr; } end = *ptr; word = calloc(1, end - begin + 1); memcpy(word, begin, end - begin); if ((tp = zone_search(word, -1, 0))) { value = -tp->gmtoffset / 60; *dst = tp->type; value += tp->type * 60; *found = 1; } else { *found = 0; } *tz_abbr = word; return value; } static long timelib_get_zone(char **ptr, int *dst, timelib_time *t, int *tz_not_found, const timelib_tzdb *tzdb) { timelib_tzinfo *res; long retval = 0; *tz_not_found = 0; while (**ptr == ' ' || **ptr == '\t' || **ptr == '(') { ++*ptr; } if ((*ptr)[0] == 'G' && (*ptr)[1] == 'M' && (*ptr)[2] == 'T' && ((*ptr)[3] == '+' || (*ptr)[3] == '-')) { *ptr += 3; } if (**ptr == '+') { ++*ptr; t->is_localtime = 1; t->zone_type = TIMELIB_ZONETYPE_OFFSET; *tz_not_found = 0; t->dst = 0; retval = -1 * timelib_parse_tz_cor(ptr); } else if (**ptr == '-') { ++*ptr; t->is_localtime = 1; t->zone_type = TIMELIB_ZONETYPE_OFFSET; *tz_not_found = 0; t->dst = 0; retval = timelib_parse_tz_cor(ptr); } else { int found = 0; long offset; char *tz_abbr; t->is_localtime = 1; offset = timelib_lookup_zone(ptr, dst, &tz_abbr, &found); if (found) { t->zone_type = TIMELIB_ZONETYPE_ABBR; } #if 0 /* If we found a TimeZone identifier, use it */ if (tz_name) { t->tz_info = timelib_parse_tzfile(tz_name); t->zone_type = TIMELIB_ZONETYPE_ID; } #endif /* If we have a TimeZone identifier to start with, use it */ if (strstr(tz_abbr, "/") || strcmp(tz_abbr, "UTC") == 0) { if ((res = timelib_parse_tzfile(tz_abbr, tzdb)) != NULL) { t->tz_info = res; t->zone_type = TIMELIB_ZONETYPE_ID; found++; } } if (found && t->zone_type != TIMELIB_ZONETYPE_ID) { timelib_time_tz_abbr_update(t, tz_abbr); } free(tz_abbr); *tz_not_found = (found == 0); retval = offset; } while (**ptr == ')') { ++*ptr; } return retval; } #define timelib_split_free(arg) { \ int i; \ for (i = 0; i < arg.c; i++) { \ free(arg.v[i]); \ } \ if (arg.v) { \ free(arg.v); \ } \ } static int scan(Scanner *s) { uchar *cursor = s->cur; char *str, *ptr = NULL; std: s->tok = cursor; s->len = 0; #line 997 "ext/date/lib/parse_date.re" #line 879 "ext/date/lib/parse_date.c" { YYCTYPE yych; unsigned int yyaccept = 0; static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 64, 160, 96, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 0, 0, 0, 0, 0, 24, 24, 24, 88, 24, 24, 24, 88, 24, 24, 24, 24, 24, 88, 24, 24, 24, 88, 88, 88, 24, 24, 24, 24, 24, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; YYDEBUG(0, *YYCURSOR); if ((YYLIMIT - YYCURSOR) < 31) YYFILL(31); yych = *YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case 0x00: case '\n': goto yy52; case '\t': case ' ': goto yy49; case '(': goto yy46; case '+': case '-': goto yy31; case ',': case '.': goto yy51; case '0': goto yy26; case '1': goto yy27; case '2': goto yy28; case '3': goto yy29; case '4': case '5': case '6': case '7': case '8': case '9': goto yy30; case '@': goto yy12; case 'A': goto yy37; case 'B': goto yy18; case 'C': case 'H': case 'K': case 'Q': case 'R': case 'U': case 'Z': goto yy47; case 'D': goto yy41; case 'E': goto yy22; case 'F': goto yy14; case 'G': goto yy45; case 'I': goto yy32; case 'J': goto yy35; case 'L': goto yy16; case 'M': goto yy8; case 'N': goto yy6; case 'O': goto yy39; case 'P': goto yy24; case 'S': goto yy20; case 'T': goto yy10; case 'V': goto yy33; case 'W': goto yy43; case 'X': goto yy34; case 'Y': goto yy3; case 'a': goto yy38; case 'b': goto yy19; case 'c': case 'g': case 'h': case 'i': case 'k': case 'q': case 'r': case 'u': case 'v': case 'x': case 'z': goto yy48; case 'd': goto yy42; case 'e': goto yy23; case 'f': goto yy15; case 'j': goto yy36; case 'l': goto yy17; case 'm': goto yy9; case 'n': goto yy7; case 'o': goto yy40; case 'p': goto yy25; case 's': goto yy21; case 't': goto yy11; case 'w': goto yy44; case 'y': goto yy5; default: goto yy54; } yy2: YYDEBUG(2, *YYCURSOR); #line 1082 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("firstdayof | lastdayof"); TIMELIB_INIT; TIMELIB_HAVE_RELATIVE(); /* skip "last day of" or "first day of" */ if (*ptr == 'l') { s->time->relative.first_last_day_of = 2; } else { s->time->relative.first_last_day_of = 1; } TIMELIB_DEINIT; return TIMELIB_LF_DAY_OF_MONTH; } #line 1015 "ext/date/lib/parse_date.c" yy3: YYDEBUG(3, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= 'E') { if (yych <= ')') { if (yych >= ')') goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy141; goto yy1523; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy141; if (yych >= 'a') goto yy146; } else { if (yych <= 'e') goto yy1532; if (yych <= 'z') goto yy146; } } yy4: YYDEBUG(4, *YYCURSOR); #line 1676 "ext/date/lib/parse_date.re" { int tz_not_found; DEBUG_OUTPUT("tzcorrection | tz"); TIMELIB_INIT; TIMELIB_HAVE_TZ(); s->time->z = timelib_get_zone((char **) &ptr, &s->time->dst, s->time, &tz_not_found, s->tzdb); if (tz_not_found) { add_error(s, "The timezone could not be found in the database"); } TIMELIB_DEINIT; return TIMELIB_TIMEZONE; } #line 1051 "ext/date/lib/parse_date.c" yy5: YYDEBUG(5, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy141; goto yy1523; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; goto yy141; } else { if (yych <= 'e') goto yy1523; if (yych <= 'z') goto yy141; goto yy4; } } yy6: YYDEBUG(6, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= 'D') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy141; } else { if (yych <= 'H') { if (yych <= 'E') goto yy1494; goto yy141; } else { if (yych <= 'I') goto yy1495; if (yych <= 'N') goto yy141; goto yy1493; } } } else { if (yych <= 'h') { if (yych <= '`') { if (yych <= 'Z') goto yy141; goto yy4; } else { if (yych == 'e') goto yy1510; goto yy146; } } else { if (yych <= 'n') { if (yych <= 'i') goto yy1511; goto yy146; } else { if (yych <= 'o') goto yy1509; if (yych <= 'z') goto yy146; goto yy4; } } } yy7: YYDEBUG(7, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= 'D') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy141; } else { if (yych <= 'H') { if (yych <= 'E') goto yy1494; goto yy141; } else { if (yych <= 'I') goto yy1495; if (yych <= 'N') goto yy141; goto yy1493; } } } else { if (yych <= 'h') { if (yych <= '`') { if (yych <= 'Z') goto yy141; goto yy4; } else { if (yych == 'e') goto yy1494; goto yy141; } } else { if (yych <= 'n') { if (yych <= 'i') goto yy1495; goto yy141; } else { if (yych <= 'o') goto yy1493; if (yych <= 'z') goto yy141; goto yy4; } } } yy8: YYDEBUG(8, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy1463; } else { if (yych == 'I') goto yy1464; if (yych <= 'N') goto yy141; goto yy1465; } } else { if (yych <= 'h') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; if (yych <= 'a') goto yy1478; goto yy146; } else { if (yych <= 'n') { if (yych <= 'i') goto yy1479; goto yy146; } else { if (yych <= 'o') goto yy1480; if (yych <= 'z') goto yy146; goto yy4; } } } yy9: YYDEBUG(9, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy1463; } else { if (yych == 'I') goto yy1464; if (yych <= 'N') goto yy141; goto yy1465; } } else { if (yych <= 'h') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; if (yych <= 'a') goto yy1463; goto yy141; } else { if (yych <= 'n') { if (yych <= 'i') goto yy1464; goto yy141; } else { if (yych <= 'o') goto yy1465; if (yych <= 'z') goto yy141; goto yy4; } } } yy10: YYDEBUG(10, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case ')': goto yy140; case '0': case '1': goto yy1393; case '2': goto yy1394; case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy1395; case 'A': case 'B': case 'C': case 'D': case 'F': case 'G': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'V': case 'X': case 'Y': case 'Z': goto yy141; case 'E': goto yy1388; case 'H': goto yy1389; case 'O': goto yy1390; case 'U': goto yy1391; case 'W': goto yy1392; case 'a': case 'b': case 'c': case 'd': case 'f': case 'g': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'p': case 'q': case 'r': case 's': case 't': case 'v': case 'x': case 'y': case 'z': goto yy146; case 'e': goto yy1431; case 'h': goto yy1432; case 'o': goto yy1433; case 'u': goto yy1434; case 'w': goto yy1435; default: goto yy4; } yy11: YYDEBUG(11, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case ')': goto yy140; case '0': case '1': goto yy1393; case '2': goto yy1394; case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy1395; case 'A': case 'B': case 'C': case 'D': case 'F': case 'G': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'V': case 'X': case 'Y': case 'Z': case 'a': case 'b': case 'c': case 'd': case 'f': case 'g': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'p': case 'q': case 'r': case 's': case 't': case 'v': case 'x': case 'y': case 'z': goto yy141; case 'E': case 'e': goto yy1388; case 'H': case 'h': goto yy1389; case 'O': case 'o': goto yy1390; case 'U': case 'u': goto yy1391; case 'W': case 'w': goto yy1392; default: goto yy4; } yy12: YYDEBUG(12, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych == '-') goto yy1384; if (yych <= '/') goto yy13; if (yych <= '9') goto yy1385; yy13: YYDEBUG(13, *YYCURSOR); #line 1771 "ext/date/lib/parse_date.re" { add_error(s, "Unexpected character"); goto std; } #line 1367 "ext/date/lib/parse_date.c" yy14: YYDEBUG(14, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy141; goto yy1320; } } else { if (yych <= 'N') { if (yych == 'I') goto yy1321; goto yy141; } else { if (yych <= 'O') goto yy1322; if (yych <= 'Q') goto yy141; goto yy1323; } } } else { if (yych <= 'i') { if (yych <= 'd') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; goto yy146; } else { if (yych <= 'e') goto yy1361; if (yych <= 'h') goto yy146; goto yy1362; } } else { if (yych <= 'q') { if (yych == 'o') goto yy1363; goto yy146; } else { if (yych <= 'r') goto yy1364; if (yych <= 'z') goto yy146; goto yy4; } } } yy15: YYDEBUG(15, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy141; goto yy1320; } } else { if (yych <= 'N') { if (yych == 'I') goto yy1321; goto yy141; } else { if (yych <= 'O') goto yy1322; if (yych <= 'Q') goto yy141; goto yy1323; } } } else { if (yych <= 'i') { if (yych <= 'd') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; goto yy141; } else { if (yych <= 'e') goto yy1320; if (yych <= 'h') goto yy141; goto yy1321; } } else { if (yych <= 'q') { if (yych == 'o') goto yy1322; goto yy141; } else { if (yych <= 'r') goto yy1323; if (yych <= 'z') goto yy141; goto yy4; } } } yy16: YYDEBUG(16, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy1307; } else { if (yych <= '`') { if (yych <= 'Z') goto yy141; goto yy4; } else { if (yych <= 'a') goto yy1317; if (yych <= 'z') goto yy146; goto yy4; } } yy17: YYDEBUG(17, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy1307; } else { if (yych <= '`') { if (yych <= 'Z') goto yy141; goto yy4; } else { if (yych <= 'a') goto yy1307; if (yych <= 'z') goto yy141; goto yy4; } } yy18: YYDEBUG(18, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy1287; } else { if (yych <= '`') { if (yych <= 'Z') goto yy141; goto yy4; } else { if (yych <= 'a') goto yy1304; if (yych <= 'z') goto yy146; goto yy4; } } yy19: YYDEBUG(19, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy1287; } else { if (yych <= '`') { if (yych <= 'Z') goto yy141; goto yy4; } else { if (yych <= 'a') goto yy1287; if (yych <= 'z') goto yy141; goto yy4; } } yy20: YYDEBUG(20, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= 'D') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'A') goto yy1230; goto yy141; } } else { if (yych <= 'H') { if (yych <= 'E') goto yy1229; goto yy141; } else { if (yych <= 'I') goto yy1231; if (yych <= 'T') goto yy141; goto yy1232; } } } else { if (yych <= 'e') { if (yych <= '`') { if (yych <= 'Z') goto yy141; goto yy4; } else { if (yych <= 'a') goto yy1259; if (yych <= 'd') goto yy146; goto yy1258; } } else { if (yych <= 't') { if (yych == 'i') goto yy1260; goto yy146; } else { if (yych <= 'u') goto yy1261; if (yych <= 'z') goto yy146; goto yy4; } } } yy21: YYDEBUG(21, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= 'D') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'A') goto yy1230; goto yy141; } } else { if (yych <= 'H') { if (yych <= 'E') goto yy1229; goto yy141; } else { if (yych <= 'I') goto yy1231; if (yych <= 'T') goto yy141; goto yy1232; } } } else { if (yych <= 'e') { if (yych <= '`') { if (yych <= 'Z') goto yy141; goto yy4; } else { if (yych <= 'a') goto yy1230; if (yych <= 'd') goto yy141; goto yy1229; } } else { if (yych <= 't') { if (yych == 'i') goto yy1231; goto yy141; } else { if (yych <= 'u') goto yy1232; if (yych <= 'z') goto yy141; goto yy4; } } } yy22: YYDEBUG(22, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == 'I') goto yy1199; if (yych <= 'K') goto yy141; goto yy1200; } } else { if (yych <= 'i') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; if (yych <= 'h') goto yy146; goto yy1217; } else { if (yych == 'l') goto yy1218; if (yych <= 'z') goto yy146; goto yy4; } } yy23: YYDEBUG(23, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == 'I') goto yy1199; if (yych <= 'K') goto yy141; goto yy1200; } } else { if (yych <= 'i') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; if (yych <= 'h') goto yy141; goto yy1199; } else { if (yych == 'l') goto yy1200; if (yych <= 'z') goto yy141; goto yy4; } } yy24: YYDEBUG(24, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'Q') goto yy141; goto yy1098; } } else { if (yych <= 'q') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; goto yy146; } else { if (yych <= 'r') goto yy1192; if (yych <= 'z') goto yy146; goto yy4; } } yy25: YYDEBUG(25, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'Q') goto yy141; goto yy1098; } } else { if (yych <= 'q') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; goto yy141; } else { if (yych <= 'r') goto yy1098; if (yych <= 'z') goto yy141; goto yy4; } } yy26: YYDEBUG(26, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case '\t': goto yy1052; case ' ': case 'A': case 'D': case 'F': case 'H': case 'I': case 'J': case 'M': case 'N': case 'O': case 'S': case 'T': case 'V': case 'W': case 'X': case 'Y': case 'a': case 'd': case 'f': case 'h': case 'j': case 'm': case 'o': case 'w': case 'y': goto yy1054; case '-': goto yy473; case '.': goto yy1064; case '/': goto yy472; case '0': goto yy1097; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy1096; case ':': goto yy1065; case 'n': goto yy470; case 'r': goto yy471; case 's': goto yy464; case 't': goto yy468; default: goto yy13; } yy27: YYDEBUG(27, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case '\t': goto yy460; case ' ': case 'A': case 'D': case 'F': case 'H': case 'I': case 'J': case 'M': case 'N': case 'O': case 'P': case 'S': case 'T': case 'V': case 'W': case 'X': case 'Y': case 'a': case 'd': case 'f': case 'h': case 'j': case 'm': case 'o': case 'p': case 'w': case 'y': goto yy462; case '-': goto yy473; case '.': goto yy474; case '/': goto yy472; case '0': case '1': case '2': goto yy1096; case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy1063; case ':': goto yy483; case 'n': goto yy470; case 'r': goto yy471; case 's': goto yy464; case 't': goto yy468; default: goto yy13; } yy28: YYDEBUG(28, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case '\t': goto yy460; case ' ': case 'A': case 'D': case 'F': case 'H': case 'I': case 'J': case 'M': case 'N': case 'O': case 'P': case 'S': case 'T': case 'V': case 'W': case 'X': case 'Y': case 'a': case 'd': case 'f': case 'h': case 'j': case 'm': case 'o': case 'p': case 'w': case 'y': goto yy462; case '-': goto yy473; case '.': goto yy474; case '/': goto yy472; case '0': case '1': case '2': case '3': case '4': goto yy1063; case '5': case '6': case '7': case '8': case '9': goto yy1050; case ':': goto yy483; case 'n': goto yy470; case 'r': goto yy471; case 's': goto yy464; case 't': goto yy468; default: goto yy13; } yy29: YYDEBUG(29, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case '\t': goto yy460; case ' ': case 'A': case 'D': case 'F': case 'H': case 'I': case 'J': case 'M': case 'N': case 'O': case 'P': case 'S': case 'T': case 'V': case 'W': case 'X': case 'Y': case 'a': case 'd': case 'f': case 'h': case 'j': case 'm': case 'o': case 'p': case 'w': case 'y': goto yy462; case '-': goto yy473; case '.': goto yy474; case '/': goto yy472; case '0': case '1': goto yy1050; case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy469; case ':': goto yy483; case 'n': goto yy470; case 'r': goto yy471; case 's': goto yy464; case 't': goto yy468; default: goto yy13; } yy30: YYDEBUG(30, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case '\t': goto yy460; case ' ': case 'A': case 'D': case 'F': case 'H': case 'I': case 'J': case 'M': case 'N': case 'O': case 'P': case 'S': case 'T': case 'V': case 'W': case 'X': case 'Y': case 'a': case 'd': case 'f': case 'h': case 'j': case 'm': case 'o': case 'p': case 'w': case 'y': goto yy462; case '-': goto yy473; case '.': goto yy474; case '/': goto yy472; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy469; case ':': goto yy483; case 'n': goto yy470; case 'r': goto yy471; case 's': goto yy464; case 't': goto yy468; default: goto yy13; } yy31: YYDEBUG(31, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 4) { goto yy58; } YYDEBUG(-1, yych); switch (yych) { case '+': case '-': goto yy440; case '0': case '1': goto yy437; case '2': goto yy438; case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy439; default: goto yy13; } yy32: YYDEBUG(32, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy4; goto yy196; } else { if (yych == ' ') goto yy196; goto yy4; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; goto yy4; } else { if (yych == '/') goto yy4; goto yy196; } } } else { if (yych <= 'V') { if (yych <= 'H') { if (yych <= '@') goto yy4; goto yy141; } else { if (yych <= 'I') goto yy436; if (yych <= 'U') goto yy141; goto yy435; } } else { if (yych <= 'Z') { if (yych == 'X') goto yy435; goto yy141; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy146; goto yy4; } } } yy33: YYDEBUG(33, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ' ') { if (yych == '\t') goto yy196; if (yych <= 0x1F) goto yy4; goto yy196; } else { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy196; } } else { if (yych <= 'H') { if (yych <= '/') goto yy4; if (yych <= '9') goto yy196; if (yych <= '@') goto yy4; goto yy141; } else { if (yych <= 'Z') { if (yych <= 'I') goto yy432; goto yy141; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy146; goto yy4; } } } yy34: YYDEBUG(34, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ' ') { if (yych == '\t') goto yy196; if (yych <= 0x1F) goto yy4; goto yy196; } else { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy196; } } else { if (yych <= 'H') { if (yych <= '/') goto yy4; if (yych <= '9') goto yy196; if (yych <= '@') goto yy4; goto yy141; } else { if (yych <= 'Z') { if (yych <= 'I') goto yy430; goto yy141; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy146; goto yy4; } } } yy35: YYDEBUG(35, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'A') goto yy413; if (yych <= 'T') goto yy141; goto yy412; } } else { if (yych <= 'a') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; goto yy422; } else { if (yych == 'u') goto yy421; if (yych <= 'z') goto yy146; goto yy4; } } yy36: YYDEBUG(36, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'A') goto yy413; if (yych <= 'T') goto yy141; goto yy412; } } else { if (yych <= 'a') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; goto yy413; } else { if (yych == 'u') goto yy412; if (yych <= 'z') goto yy141; goto yy4; } } yy37: YYDEBUG(37, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= 'F') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy141; } else { if (yych <= 'O') { if (yych <= 'G') goto yy391; goto yy141; } else { if (yych <= 'P') goto yy390; if (yych <= 'T') goto yy141; goto yy389; } } } else { if (yych <= 'o') { if (yych <= '`') { if (yych <= 'Z') goto yy141; goto yy4; } else { if (yych == 'g') goto yy403; goto yy146; } } else { if (yych <= 't') { if (yych <= 'p') goto yy402; goto yy146; } else { if (yych <= 'u') goto yy401; if (yych <= 'z') goto yy146; goto yy4; } } } yy38: YYDEBUG(38, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= 'F') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy141; } else { if (yych <= 'O') { if (yych <= 'G') goto yy391; goto yy141; } else { if (yych <= 'P') goto yy390; if (yych <= 'T') goto yy141; goto yy389; } } } else { if (yych <= 'o') { if (yych <= '`') { if (yych <= 'Z') goto yy141; goto yy4; } else { if (yych == 'g') goto yy391; goto yy141; } } else { if (yych <= 't') { if (yych <= 'p') goto yy390; goto yy141; } else { if (yych <= 'u') goto yy389; if (yych <= 'z') goto yy141; goto yy4; } } } yy39: YYDEBUG(39, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'C') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'B') goto yy141; goto yy379; } } else { if (yych <= 'b') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; goto yy146; } else { if (yych <= 'c') goto yy384; if (yych <= 'z') goto yy146; goto yy4; } } yy40: YYDEBUG(40, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'C') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'B') goto yy141; goto yy379; } } else { if (yych <= 'b') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; goto yy141; } else { if (yych <= 'c') goto yy379; if (yych <= 'z') goto yy141; goto yy4; } } yy41: YYDEBUG(41, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy141; goto yy192; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; goto yy146; } else { if (yych <= 'e') goto yy370; if (yych <= 'z') goto yy146; goto yy4; } } yy42: YYDEBUG(42, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy141; goto yy192; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; goto yy141; } else { if (yych <= 'e') goto yy192; if (yych <= 'z') goto yy141; goto yy4; } } yy43: YYDEBUG(43, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy141; goto yy165; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; goto yy146; } else { if (yych <= 'e') goto yy179; if (yych <= 'z') goto yy146; goto yy4; } } yy44: YYDEBUG(44, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy141; goto yy165; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; goto yy141; } else { if (yych <= 'e') goto yy165; if (yych <= 'z') goto yy141; goto yy4; } } yy45: YYDEBUG(45, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy141; } else { if (yych <= 'Z') { if (yych <= 'M') goto yy157; goto yy141; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy146; goto yy4; } } yy46: YYDEBUG(46, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') goto yy13; if (yych <= 'Z') goto yy156; if (yych <= '`') goto yy13; if (yych <= 'z') goto yy156; goto yy13; yy47: YYDEBUG(47, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; if (yych <= 'z') goto yy146; goto yy4; } yy48: YYDEBUG(48, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; if (yych <= 'z') goto yy141; goto yy4; } yy49: YYDEBUG(49, *YYCURSOR); yyaccept = 2; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 4) { goto yy58; } if (yych <= '/') goto yy50; if (yych <= '9') goto yy55; yy50: YYDEBUG(50, *YYCURSOR); #line 1760 "ext/date/lib/parse_date.re" { goto std; } #line 2428 "ext/date/lib/parse_date.c" yy51: YYDEBUG(51, *YYCURSOR); yych = *++YYCURSOR; goto yy50; yy52: YYDEBUG(52, *YYCURSOR); ++YYCURSOR; YYDEBUG(53, *YYCURSOR); #line 1765 "ext/date/lib/parse_date.re" { s->pos = cursor; s->line++; goto std; } #line 2442 "ext/date/lib/parse_date.c" yy54: YYDEBUG(54, *YYCURSOR); yych = *++YYCURSOR; goto yy13; yy55: YYDEBUG(55, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 11) YYFILL(11); yych = *YYCURSOR; YYDEBUG(56, *YYCURSOR); if (yybm[0+yych] & 2) { goto yy55; } if (yych <= 'W') { if (yych <= 'F') { if (yych <= ' ') { if (yych == '\t') goto yy60; if (yych >= ' ') goto yy60; } else { if (yych == 'D') goto yy65; if (yych >= 'F') goto yy66; } } else { if (yych <= 'M') { if (yych == 'H') goto yy64; if (yych >= 'M') goto yy63; } else { if (yych <= 'S') { if (yych >= 'S') goto yy62; } else { if (yych <= 'T') goto yy69; if (yych >= 'W') goto yy68; } } } } else { if (yych <= 'l') { if (yych <= 'd') { if (yych == 'Y') goto yy67; if (yych >= 'd') goto yy65; } else { if (yych <= 'f') { if (yych >= 'f') goto yy66; } else { if (yych == 'h') goto yy64; } } } else { if (yych <= 't') { if (yych <= 'm') goto yy63; if (yych <= 'r') goto yy57; if (yych <= 's') goto yy62; goto yy69; } else { if (yych <= 'w') { if (yych >= 'w') goto yy68; } else { if (yych == 'y') goto yy67; } } } } yy57: YYDEBUG(57, *YYCURSOR); YYCURSOR = YYMARKER; if (yyaccept <= 16) { if (yyaccept <= 8) { if (yyaccept <= 4) { if (yyaccept <= 2) { if (yyaccept <= 1) { if (yyaccept <= 0) { goto yy4; } else { goto yy13; } } else { goto yy50; } } else { if (yyaccept <= 3) { goto yy73; } else { goto yy167; } } } else { if (yyaccept <= 6) { if (yyaccept <= 5) { goto yy194; } else { goto yy199; } } else { if (yyaccept <= 7) { goto yy223; } else { goto yy295; } } } } else { if (yyaccept <= 12) { if (yyaccept <= 10) { if (yyaccept <= 9) { goto yy393; } else { goto yy476; } } else { if (yyaccept <= 11) { goto yy491; } else { goto yy612; } } } else { if (yyaccept <= 14) { if (yyaccept <= 13) { goto yy657; } else { goto yy667; } } else { if (yyaccept <= 15) { goto yy764; } else { goto yy784; } } } } } else { if (yyaccept <= 25) { if (yyaccept <= 21) { if (yyaccept <= 19) { if (yyaccept <= 18) { if (yyaccept <= 17) { goto yy815; } else { goto yy822; } } else { goto yy849; } } else { if (yyaccept <= 20) { goto yy794; } else { goto yy455; } } } else { if (yyaccept <= 23) { if (yyaccept <= 22) { goto yy974; } else { goto yy843; } } else { if (yyaccept <= 24) { goto yy1068; } else { goto yy1076; } } } } else { if (yyaccept <= 29) { if (yyaccept <= 27) { if (yyaccept <= 26) { goto yy1118; } else { goto yy1142; } } else { if (yyaccept <= 28) { goto yy1295; } else { goto yy1417; } } } else { if (yyaccept <= 31) { if (yyaccept <= 30) { goto yy1420; } else { goto yy1500; } } else { if (yyaccept <= 32) { goto yy1508; } else { goto yy1531; } } } } } yy58: YYDEBUG(58, *YYCURSOR); ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; YYDEBUG(59, *YYCURSOR); if (yybm[0+yych] & 4) { goto yy58; } if (yych <= '/') goto yy57; if (yych <= '9') goto yy55; goto yy57; yy60: YYDEBUG(60, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 11) YYFILL(11); yych = *YYCURSOR; yy61: YYDEBUG(61, *YYCURSOR); if (yych <= 'W') { if (yych <= 'F') { if (yych <= ' ') { if (yych == '\t') goto yy60; if (yych <= 0x1F) goto yy57; goto yy60; } else { if (yych == 'D') goto yy65; if (yych <= 'E') goto yy57; goto yy66; } } else { if (yych <= 'M') { if (yych == 'H') goto yy64; if (yych <= 'L') goto yy57; goto yy63; } else { if (yych <= 'S') { if (yych <= 'R') goto yy57; } else { if (yych <= 'T') goto yy69; if (yych <= 'V') goto yy57; goto yy68; } } } } else { if (yych <= 'l') { if (yych <= 'd') { if (yych == 'Y') goto yy67; if (yych <= 'c') goto yy57; goto yy65; } else { if (yych <= 'f') { if (yych <= 'e') goto yy57; goto yy66; } else { if (yych == 'h') goto yy64; goto yy57; } } } else { if (yych <= 't') { if (yych <= 'm') goto yy63; if (yych <= 'r') goto yy57; if (yych >= 't') goto yy69; } else { if (yych <= 'w') { if (yych <= 'v') goto yy57; goto yy68; } else { if (yych == 'y') goto yy67; goto yy57; } } } } yy62: YYDEBUG(62, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= 'D') { if (yych == 'A') goto yy127; goto yy57; } else { if (yych <= 'E') goto yy128; if (yych <= 'T') goto yy57; goto yy126; } } else { if (yych <= 'd') { if (yych == 'a') goto yy127; goto yy57; } else { if (yych <= 'e') goto yy128; if (yych == 'u') goto yy126; goto yy57; } } yy63: YYDEBUG(63, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'I') goto yy118; if (yych <= 'N') goto yy57; goto yy117; } else { if (yych <= 'i') { if (yych <= 'h') goto yy57; goto yy118; } else { if (yych == 'o') goto yy117; goto yy57; } } yy64: YYDEBUG(64, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy115; if (yych == 'o') goto yy115; goto yy57; yy65: YYDEBUG(65, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy114; if (yych == 'a') goto yy114; goto yy57; yy66: YYDEBUG(66, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych == 'O') goto yy99; if (yych <= 'Q') goto yy57; goto yy98; } else { if (yych <= 'o') { if (yych <= 'n') goto yy57; goto yy99; } else { if (yych == 'r') goto yy98; goto yy57; } } yy67: YYDEBUG(67, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy95; if (yych == 'e') goto yy95; goto yy57; yy68: YYDEBUG(68, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy83; if (yych == 'e') goto yy83; goto yy57; yy69: YYDEBUG(69, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'H') goto yy70; if (yych <= 'T') goto yy57; goto yy71; } else { if (yych <= 'h') { if (yych <= 'g') goto yy57; } else { if (yych == 'u') goto yy71; goto yy57; } } yy70: YYDEBUG(70, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy78; if (yych == 'u') goto yy78; goto yy57; yy71: YYDEBUG(71, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy72; if (yych != 'e') goto yy57; yy72: YYDEBUG(72, *YYCURSOR); yyaccept = 3; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'S') goto yy74; if (yych == 's') goto yy74; yy73: YYDEBUG(73, *YYCURSOR); #line 1744 "ext/date/lib/parse_date.re" { timelib_ull i; DEBUG_OUTPUT("relative"); TIMELIB_INIT; TIMELIB_HAVE_RELATIVE(); while(*ptr) { i = timelib_get_unsigned_nr((char **) &ptr, 24); timelib_eat_spaces((char **) &ptr); timelib_set_relative((char **) &ptr, i, 1, s); } TIMELIB_DEINIT; return TIMELIB_RELATIVE; } #line 2844 "ext/date/lib/parse_date.c" yy74: YYDEBUG(74, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy75; if (yych != 'd') goto yy57; yy75: YYDEBUG(75, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy76; if (yych != 'a') goto yy57; yy76: YYDEBUG(76, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy77; if (yych != 'y') goto yy57; yy77: YYDEBUG(77, *YYCURSOR); yych = *++YYCURSOR; goto yy73; yy78: YYDEBUG(78, *YYCURSOR); yyaccept = 3; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'R') goto yy79; if (yych != 'r') goto yy73; yy79: YYDEBUG(79, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy80; if (yych != 's') goto yy57; yy80: YYDEBUG(80, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy81; if (yych != 'd') goto yy57; yy81: YYDEBUG(81, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy82; if (yych != 'a') goto yy57; yy82: YYDEBUG(82, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy77; if (yych == 'y') goto yy77; goto yy57; yy83: YYDEBUG(83, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= 'C') goto yy57; if (yych <= 'D') goto yy85; } else { if (yych <= 'c') goto yy57; if (yych <= 'd') goto yy85; if (yych >= 'f') goto yy57; } YYDEBUG(84, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'K') goto yy91; if (yych == 'k') goto yy91; goto yy57; yy85: YYDEBUG(85, *YYCURSOR); yyaccept = 3; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'N') goto yy86; if (yych != 'n') goto yy73; yy86: YYDEBUG(86, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy87; if (yych != 'e') goto yy57; yy87: YYDEBUG(87, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy88; if (yych != 's') goto yy57; yy88: YYDEBUG(88, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy89; if (yych != 'd') goto yy57; yy89: YYDEBUG(89, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy90; if (yych != 'a') goto yy57; yy90: YYDEBUG(90, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy77; if (yych == 'y') goto yy77; goto yy57; yy91: YYDEBUG(91, *YYCURSOR); yyaccept = 3; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych == 'D') goto yy92; if (yych <= 'R') goto yy73; goto yy77; } else { if (yych <= 'd') { if (yych <= 'c') goto yy73; } else { if (yych == 's') goto yy77; goto yy73; } } yy92: YYDEBUG(92, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy93; if (yych != 'a') goto yy57; yy93: YYDEBUG(93, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy94; if (yych != 'y') goto yy57; yy94: YYDEBUG(94, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy77; if (yych == 's') goto yy77; goto yy73; yy95: YYDEBUG(95, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy96; if (yych != 'a') goto yy57; yy96: YYDEBUG(96, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy97; if (yych != 'r') goto yy57; yy97: YYDEBUG(97, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy77; if (yych == 's') goto yy77; goto yy73; yy98: YYDEBUG(98, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy111; if (yych == 'i') goto yy111; goto yy57; yy99: YYDEBUG(99, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy100; if (yych != 'r') goto yy57; yy100: YYDEBUG(100, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy101; if (yych != 't') goto yy57; yy101: YYDEBUG(101, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych == 'H') goto yy103; if (yych <= 'M') goto yy57; } else { if (yych <= 'h') { if (yych <= 'g') goto yy57; goto yy103; } else { if (yych != 'n') goto yy57; } } YYDEBUG(102, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy108; if (yych == 'i') goto yy108; goto yy57; yy103: YYDEBUG(103, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy104; if (yych != 'n') goto yy57; yy104: YYDEBUG(104, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy105; if (yych != 'i') goto yy57; yy105: YYDEBUG(105, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy106; if (yych != 'g') goto yy57; yy106: YYDEBUG(106, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy107; if (yych != 'h') goto yy57; yy107: YYDEBUG(107, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy97; if (yych == 't') goto yy97; goto yy57; yy108: YYDEBUG(108, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy109; if (yych != 'g') goto yy57; yy109: YYDEBUG(109, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy110; if (yych != 'h') goto yy57; yy110: YYDEBUG(110, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy97; if (yych == 't') goto yy97; goto yy57; yy111: YYDEBUG(111, *YYCURSOR); yyaccept = 3; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'D') goto yy112; if (yych != 'd') goto yy73; yy112: YYDEBUG(112, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy113; if (yych != 'a') goto yy57; yy113: YYDEBUG(113, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy77; if (yych == 'y') goto yy77; goto yy57; yy114: YYDEBUG(114, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy97; if (yych == 'y') goto yy97; goto yy57; yy115: YYDEBUG(115, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy116; if (yych != 'u') goto yy57; yy116: YYDEBUG(116, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy97; if (yych == 'r') goto yy97; goto yy57; yy117: YYDEBUG(117, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy122; if (yych == 'n') goto yy122; goto yy57; yy118: YYDEBUG(118, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy119; if (yych != 'n') goto yy57; yy119: YYDEBUG(119, *YYCURSOR); yyaccept = 3; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'U') { if (yych == 'S') goto yy77; if (yych <= 'T') goto yy73; } else { if (yych <= 's') { if (yych <= 'r') goto yy73; goto yy77; } else { if (yych != 'u') goto yy73; } } YYDEBUG(120, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy121; if (yych != 't') goto yy57; yy121: YYDEBUG(121, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy97; if (yych == 'e') goto yy97; goto yy57; yy122: YYDEBUG(122, *YYCURSOR); yyaccept = 3; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych == 'D') goto yy123; if (yych <= 'S') goto yy73; goto yy124; } else { if (yych <= 'd') { if (yych <= 'c') goto yy73; } else { if (yych == 't') goto yy124; goto yy73; } } yy123: YYDEBUG(123, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy125; if (yych == 'a') goto yy125; goto yy57; yy124: YYDEBUG(124, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy97; if (yych == 'h') goto yy97; goto yy57; yy125: YYDEBUG(125, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy77; if (yych == 'y') goto yy77; goto yy57; yy126: YYDEBUG(126, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy137; if (yych == 'n') goto yy137; goto yy57; yy127: YYDEBUG(127, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy132; if (yych == 't') goto yy132; goto yy57; yy128: YYDEBUG(128, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy129; if (yych != 'c') goto yy57; yy129: YYDEBUG(129, *YYCURSOR); yyaccept = 3; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych == 'O') goto yy130; if (yych <= 'R') goto yy73; goto yy77; } else { if (yych <= 'o') { if (yych <= 'n') goto yy73; } else { if (yych == 's') goto yy77; goto yy73; } } yy130: YYDEBUG(130, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy131; if (yych != 'n') goto yy57; yy131: YYDEBUG(131, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy97; if (yych == 'd') goto yy97; goto yy57; yy132: YYDEBUG(132, *YYCURSOR); yyaccept = 3; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'U') goto yy133; if (yych != 'u') goto yy73; yy133: YYDEBUG(133, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy134; if (yych != 'r') goto yy57; yy134: YYDEBUG(134, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy135; if (yych != 'd') goto yy57; yy135: YYDEBUG(135, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy136; if (yych != 'a') goto yy57; yy136: YYDEBUG(136, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy77; if (yych == 'y') goto yy77; goto yy57; yy137: YYDEBUG(137, *YYCURSOR); yyaccept = 3; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'D') goto yy138; if (yych != 'd') goto yy73; yy138: YYDEBUG(138, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy139; if (yych != 'a') goto yy57; yy139: YYDEBUG(139, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy77; if (yych == 'y') goto yy77; goto yy57; yy140: YYDEBUG(140, *YYCURSOR); yych = *++YYCURSOR; goto yy4; yy141: YYDEBUG(141, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; if (yych >= '{') goto yy4; } yy142: YYDEBUG(142, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; if (yych >= '{') goto yy4; } yy143: YYDEBUG(143, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; if (yych >= '{') goto yy4; } yy144: YYDEBUG(144, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; if (yych >= '{') goto yy4; } yy145: YYDEBUG(145, *YYCURSOR); yych = *++YYCURSOR; if (yych == ')') goto yy140; goto yy4; yy146: YYDEBUG(146, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; goto yy148; } } else { if (yych <= '^') { if (yych <= '@') goto yy4; if (yych <= 'Z') goto yy142; goto yy4; } else { if (yych <= '_') goto yy148; if (yych <= '`') goto yy4; if (yych >= '{') goto yy4; } } yy147: YYDEBUG(147, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; } } else { if (yych <= '^') { if (yych <= '@') goto yy4; if (yych <= 'Z') goto yy143; goto yy4; } else { if (yych <= '_') goto yy148; if (yych <= '`') goto yy4; if (yych <= 'z') goto yy151; goto yy4; } } yy148: YYDEBUG(148, *YYCURSOR); ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yybm[0+yych] & 8) { goto yy149; } goto yy57; yy149: YYDEBUG(149, *YYCURSOR); yyaccept = 0; YYMARKER = ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; YYDEBUG(150, *YYCURSOR); if (yybm[0+yych] & 8) { goto yy149; } if (yych <= '.') { if (yych == '-') goto yy148; goto yy4; } else { if (yych <= '/') goto yy148; if (yych == '_') goto yy148; goto yy4; } yy151: YYDEBUG(151, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; goto yy148; } } else { if (yych <= '^') { if (yych <= '@') goto yy4; if (yych <= 'Z') goto yy144; goto yy4; } else { if (yych <= '_') goto yy148; if (yych <= '`') goto yy4; if (yych >= '{') goto yy4; } } yy152: YYDEBUG(152, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; goto yy148; } } else { if (yych <= '^') { if (yych <= '@') goto yy4; if (yych <= 'Z') goto yy145; goto yy4; } else { if (yych <= '_') goto yy148; if (yych <= '`') goto yy4; if (yych >= '{') goto yy4; } } yy153: YYDEBUG(153, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 16) { goto yy154; } if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych <= '/') { if (yych <= '.') goto yy4; goto yy148; } else { if (yych == '_') goto yy148; goto yy4; } } yy154: YYDEBUG(154, *YYCURSOR); ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; yy155: YYDEBUG(155, *YYCURSOR); if (yybm[0+yych] & 16) { goto yy154; } if (yych <= '.') { if (yych == '-') goto yy148; goto yy57; } else { if (yych <= '/') goto yy148; if (yych == '_') goto yy148; goto yy57; } yy156: YYDEBUG(156, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'Z') goto yy141; if (yych <= '`') goto yy4; if (yych <= 'z') goto yy141; goto yy4; } yy157: YYDEBUG(157, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy142; } else { if (yych <= 'Z') { if (yych >= 'U') goto yy142; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy142; goto yy4; } } YYDEBUG(158, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych != '+') goto yy4; } } else { if (yych <= 'Z') { if (yych <= '-') goto yy159; if (yych <= '@') goto yy4; goto yy143; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy143; goto yy4; } } yy159: YYDEBUG(159, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '1') goto yy160; if (yych <= '2') goto yy161; if (yych <= '9') goto yy162; goto yy57; yy160: YYDEBUG(160, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy4; if (yych <= '9') goto yy162; if (yych <= ':') goto yy163; goto yy4; yy161: YYDEBUG(161, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '5') { if (yych <= '/') goto yy4; if (yych >= '5') goto yy164; } else { if (yych <= '9') goto yy140; if (yych <= ':') goto yy163; goto yy4; } yy162: YYDEBUG(162, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy4; if (yych <= '5') goto yy164; if (yych <= '9') goto yy140; if (yych >= ';') goto yy4; yy163: YYDEBUG(163, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy4; if (yych <= '5') goto yy164; if (yych <= '9') goto yy140; goto yy4; yy164: YYDEBUG(164, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy4; if (yych <= '9') goto yy140; goto yy4; yy165: YYDEBUG(165, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'C') goto yy142; if (yych >= 'E') goto yy168; } } else { if (yych <= 'c') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'd') goto yy166; if (yych <= 'e') goto yy168; if (yych <= 'z') goto yy142; goto yy4; } } yy166: YYDEBUG(166, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= 'N') { if (yych <= ')') { if (yych >= ')') goto yy140; } else { if (yych <= '@') goto yy167; if (yych <= 'M') goto yy143; goto yy174; } } else { if (yych <= 'm') { if (yych <= 'Z') goto yy143; if (yych >= 'a') goto yy143; } else { if (yych <= 'n') goto yy174; if (yych <= 'z') goto yy143; } } yy167: YYDEBUG(167, *YYCURSOR); #line 1607 "ext/date/lib/parse_date.re" { const timelib_relunit* relunit; DEBUG_OUTPUT("daytext"); TIMELIB_INIT; TIMELIB_HAVE_RELATIVE(); TIMELIB_HAVE_WEEKDAY_RELATIVE(); TIMELIB_UNHAVE_TIME(); relunit = timelib_lookup_relunit((char**) &ptr); s->time->relative.weekday = relunit->multiplier; if (s->time->relative.weekday_behavior != 2) { s->time->relative.weekday_behavior = 1; } TIMELIB_DEINIT; return TIMELIB_WEEKDAY; } #line 3623 "ext/date/lib/parse_date.c" yy168: YYDEBUG(168, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'K') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'J') goto yy143; } } else { if (yych <= 'j') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'k') goto yy169; if (yych <= 'z') goto yy143; goto yy4; } } yy169: YYDEBUG(169, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'D') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'C') goto yy144; } } else { if (yych <= 'c') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'd') goto yy170; if (yych <= 'z') goto yy144; goto yy4; } } yy170: YYDEBUG(170, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; } else { if (yych <= '`') { if (yych <= 'Z') goto yy145; goto yy4; } else { if (yych <= 'a') goto yy171; if (yych <= 'z') goto yy145; goto yy4; } } yy171: YYDEBUG(171, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'X') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'Y') goto yy172; if (yych != 'y') goto yy4; } yy172: YYDEBUG(172, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy173; if (yych != 's') goto yy167; yy173: YYDEBUG(173, *YYCURSOR); yych = *++YYCURSOR; goto yy167; yy174: YYDEBUG(174, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy144; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'e') goto yy175; if (yych <= 'z') goto yy144; goto yy4; } } yy175: YYDEBUG(175, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'R') goto yy145; } } else { if (yych <= 'r') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 's') goto yy176; if (yych <= 'z') goto yy145; goto yy4; } } yy176: YYDEBUG(176, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'D') goto yy177; if (yych != 'd') goto yy4; } yy177: YYDEBUG(177, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy178; if (yych != 'a') goto yy57; yy178: YYDEBUG(178, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy173; if (yych == 'y') goto yy173; goto yy57; yy179: YYDEBUG(179, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych <= '/') { if (yych <= '.') goto yy4; goto yy148; } else { if (yych <= '@') goto yy4; if (yych <= 'C') goto yy142; goto yy166; } } } else { if (yych <= '`') { if (yych <= 'Z') { if (yych <= 'E') goto yy168; goto yy142; } else { if (yych == '_') goto yy148; goto yy4; } } else { if (yych <= 'd') { if (yych <= 'c') goto yy147; } else { if (yych <= 'e') goto yy181; if (yych <= 'z') goto yy147; goto yy4; } } } YYDEBUG(180, *YYCURSOR); yyaccept = 4; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'M') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy167; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy167; goto yy143; } } else { if (yych <= '_') { if (yych <= 'N') goto yy174; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy167; goto yy148; } else { if (yych <= 'm') { if (yych <= '`') goto yy167; goto yy151; } else { if (yych <= 'n') goto yy187; if (yych <= 'z') goto yy151; goto yy167; } } } yy181: YYDEBUG(181, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'J') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'K') goto yy169; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'j') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 'k') goto yy182; if (yych <= 'z') goto yy151; goto yy4; } } } yy182: YYDEBUG(182, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'D') goto yy170; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'c') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'd') goto yy183; if (yych <= 'z') goto yy152; goto yy4; } } } yy183: YYDEBUG(183, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '_') { if (yych <= 'A') goto yy171; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'a') goto yy184; if (yych <= 'z') goto yy153; goto yy4; } } yy184: YYDEBUG(184, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'X') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'Y') goto yy172; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'y') goto yy185; if (yych <= 'z') goto yy154; goto yy4; } } yy185: YYDEBUG(185, *YYCURSOR); yyaccept = 4; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '.') { if (yych == '-') goto yy148; goto yy167; } else { if (yych <= '/') goto yy148; if (yych <= 'R') goto yy167; goto yy173; } } else { if (yych <= '`') { if (yych == '_') goto yy148; goto yy167; } else { if (yych == 's') goto yy186; if (yych <= 'z') goto yy154; goto yy167; } } yy186: YYDEBUG(186, *YYCURSOR); yyaccept = 4; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 16) { goto yy154; } if (yych <= '.') { if (yych == '-') goto yy148; goto yy167; } else { if (yych <= '/') goto yy148; if (yych == '_') goto yy148; goto yy167; } yy187: YYDEBUG(187, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'E') goto yy175; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'd') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'e') goto yy188; if (yych <= 'z') goto yy152; goto yy4; } } } yy188: YYDEBUG(188, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'R') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'S') goto yy176; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'r') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 's') goto yy189; if (yych <= 'z') goto yy153; goto yy4; } } } yy189: YYDEBUG(189, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'D') goto yy177; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'd') goto yy190; if (yych <= 'z') goto yy154; goto yy4; } } yy190: YYDEBUG(190, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy178; if (yych != 'a') goto yy155; YYDEBUG(191, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy173; if (yych == 'y') goto yy186; goto yy155; yy192: YYDEBUG(192, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'C') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'B') goto yy142; } } else { if (yych <= 'b') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'c') goto yy193; if (yych <= 'z') goto yy142; goto yy4; } } yy193: YYDEBUG(193, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= '(') { if (yych <= '\t') { if (yych >= '\t') goto yy196; } else { if (yych == ' ') goto yy196; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; } else { if (yych <= '-') goto yy197; if (yych <= '.') goto yy196; } } } else { if (yych <= 'Z') { if (yych <= '@') { if (yych <= '9') goto yy196; } else { if (yych == 'E') goto yy202; goto yy143; } } else { if (yych <= 'd') { if (yych >= 'a') goto yy143; } else { if (yych <= 'e') goto yy202; if (yych <= 'z') goto yy143; } } } yy194: YYDEBUG(194, *YYCURSOR); #line 1666 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("monthtext"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->m = timelib_lookup_month((char **) &ptr); TIMELIB_DEINIT; return TIMELIB_DATE_TEXT; } #line 4152 "ext/date/lib/parse_date.c" yy195: YYDEBUG(195, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 21) YYFILL(21); yych = *YYCURSOR; yy196: YYDEBUG(196, *YYCURSOR); if (yybm[0+yych] & 32) { goto yy195; } if (yych <= '/') goto yy57; if (yych <= '2') goto yy198; if (yych <= '3') goto yy200; if (yych <= '9') goto yy201; goto yy57; yy197: YYDEBUG(197, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy196; if (yych <= '0') goto yy357; if (yych <= '2') goto yy358; if (yych <= '3') goto yy359; goto yy196; yy198: YYDEBUG(198, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'm') { if (yych <= '1') { if (yych <= '/') goto yy216; if (yych <= '0') goto yy298; goto yy299; } else { if (yych <= '2') goto yy355; if (yych <= '9') goto yy356; goto yy216; } } else { if (yych <= 'r') { if (yych <= 'n') goto yy212; if (yych <= 'q') goto yy216; goto yy213; } else { if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy199: YYDEBUG(199, *YYCURSOR); #line 1412 "ext/date/lib/parse_date.re" { int length = 0; DEBUG_OUTPUT("datetextual | datenoyear"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->m = timelib_get_month((char **) &ptr); s->time->d = timelib_get_nr((char **) &ptr, 2); s->time->y = timelib_get_nr_ex((char **) &ptr, 4, &length); TIMELIB_PROCESS_YEAR(s->time->y, length); TIMELIB_DEINIT; return TIMELIB_DATE_TEXT; } #line 4216 "ext/date/lib/parse_date.c" yy200: YYDEBUG(200, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'm') { if (yych <= '1') { if (yych <= '/') goto yy216; if (yych <= '0') goto yy298; goto yy299; } else { if (yych <= '2') goto yy209; if (yych <= '9') goto yy210; goto yy216; } } else { if (yych <= 'r') { if (yych <= 'n') goto yy212; if (yych <= 'q') goto yy216; goto yy213; } else { if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy201: YYDEBUG(201, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'm') { if (yych <= '1') { if (yych <= '/') goto yy216; if (yych <= '0') goto yy207; goto yy208; } else { if (yych <= '2') goto yy209; if (yych <= '9') goto yy210; goto yy216; } } else { if (yych <= 'r') { if (yych <= 'n') goto yy212; if (yych <= 'q') goto yy216; goto yy213; } else { if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy202: YYDEBUG(202, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'M') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'L') goto yy144; } } else { if (yych <= 'l') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'm') goto yy203; if (yych <= 'z') goto yy144; goto yy4; } } yy203: YYDEBUG(203, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'B') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'A') goto yy145; } } else { if (yych <= 'a') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'b') goto yy204; if (yych <= 'z') goto yy145; goto yy4; } } yy204: YYDEBUG(204, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'E') goto yy205; if (yych != 'e') goto yy4; } yy205: YYDEBUG(205, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy206; if (yych != 'r') goto yy57; yy206: YYDEBUG(206, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ' ') { if (yych == '\t') goto yy196; if (yych <= 0x1F) goto yy194; goto yy196; } else { if (yych <= '.') { if (yych <= ',') goto yy194; goto yy196; } else { if (yych <= '/') goto yy194; if (yych <= '9') goto yy196; goto yy194; } } yy207: YYDEBUG(207, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy221; goto yy57; } else { if (yych <= '0') goto yy296; if (yych <= '9') goto yy297; if (yych <= ':') goto yy221; goto yy57; } yy208: YYDEBUG(208, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy264; goto yy57; } else { if (yych <= '2') goto yy297; if (yych <= '9') goto yy296; if (yych <= ':') goto yy264; goto yy57; } yy209: YYDEBUG(209, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy264; goto yy57; } else { if (yych <= '4') goto yy296; if (yych <= '9') goto yy293; if (yych <= ':') goto yy264; goto yy57; } yy210: YYDEBUG(210, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy264; goto yy57; } else { if (yych <= '9') goto yy293; if (yych <= ':') goto yy264; goto yy57; } yy211: YYDEBUG(211, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); goto yy216; yy212: YYDEBUG(212, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); goto yy216; yy213: YYDEBUG(213, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); goto yy216; yy214: YYDEBUG(214, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); goto yy216; yy215: YYDEBUG(215, *YYCURSOR); yyaccept = 6; YYMARKER = ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 18) YYFILL(18); yych = *YYCURSOR; yy216: YYDEBUG(216, *YYCURSOR); if (yybm[0+yych] & 64) { goto yy215; } if (yych <= '2') { if (yych <= '/') goto yy199; if (yych <= '0') goto yy259; if (yych <= '1') goto yy260; goto yy261; } else { if (yych <= '9') goto yy262; if (yych != 'T') goto yy199; } YYDEBUG(217, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '1') goto yy218; if (yych <= '2') goto yy219; if (yych <= '9') goto yy220; goto yy57; yy218: YYDEBUG(218, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy221; goto yy57; } else { if (yych <= '9') goto yy220; if (yych <= ':') goto yy221; goto yy57; } yy219: YYDEBUG(219, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy221; goto yy57; } else { if (yych <= '4') goto yy220; if (yych == ':') goto yy221; goto yy57; } yy220: YYDEBUG(220, *YYCURSOR); yych = *++YYCURSOR; if (yych == '.') goto yy221; if (yych != ':') goto yy57; yy221: YYDEBUG(221, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy222; if (yych <= '9') goto yy224; goto yy57; yy222: YYDEBUG(222, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy225; } else { if (yych <= '9') goto yy224; if (yych <= ':') goto yy225; } yy223: YYDEBUG(223, *YYCURSOR); #line 1714 "ext/date/lib/parse_date.re" { int tz_not_found; DEBUG_OUTPUT("dateshortwithtimeshort | dateshortwithtimelong | dateshortwithtimelongtz"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->m = timelib_get_month((char **) &ptr); s->time->d = timelib_get_nr((char **) &ptr, 2); TIMELIB_HAVE_TIME(); s->time->h = timelib_get_nr((char **) &ptr, 2); s->time->i = timelib_get_nr((char **) &ptr, 2); if (*ptr == ':') { s->time->s = timelib_get_nr((char **) &ptr, 2); if (*ptr == '.') { s->time->f = timelib_get_frac_nr((char **) &ptr, 8); } } if (*ptr != '\0') { s->time->z = timelib_get_zone((char **) &ptr, &s->time->dst, s->time, &tz_not_found, s->tzdb); if (tz_not_found) { add_error(s, "The timezone could not be found in the database"); } } TIMELIB_DEINIT; return TIMELIB_SHORTDATE_WITH_TIME; } #line 4514 "ext/date/lib/parse_date.c" yy224: YYDEBUG(224, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy225; if (yych != ':') goto yy223; yy225: YYDEBUG(225, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy226; if (yych <= '6') goto yy227; if (yych <= '9') goto yy228; goto yy57; yy226: YYDEBUG(226, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy223; if (yych <= '9') goto yy229; goto yy223; yy227: YYDEBUG(227, *YYCURSOR); yych = *++YYCURSOR; if (yych == '0') goto yy229; goto yy223; yy228: YYDEBUG(228, *YYCURSOR); yych = *++YYCURSOR; goto yy223; yy229: YYDEBUG(229, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '*') { if (yych <= 0x1F) { if (yych == '\t') goto yy231; goto yy223; } else { if (yych <= ' ') goto yy231; if (yych == '(') goto yy231; goto yy223; } } else { if (yych <= '@') { if (yych == ',') goto yy223; if (yych <= '-') goto yy231; goto yy223; } else { if (yych <= 'Z') goto yy231; if (yych <= '`') goto yy223; if (yych <= 'z') goto yy231; goto yy223; } } yy230: YYDEBUG(230, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 9) YYFILL(9); yych = *YYCURSOR; yy231: YYDEBUG(231, *YYCURSOR); if (yych <= '+') { if (yych <= ' ') { if (yych == '\t') goto yy230; if (yych <= 0x1F) goto yy57; goto yy230; } else { if (yych == '(') goto yy234; if (yych <= '*') goto yy57; goto yy233; } } else { if (yych <= 'F') { if (yych == '-') goto yy233; if (yych <= '@') goto yy57; goto yy235; } else { if (yych <= 'Z') { if (yych >= 'H') goto yy235; } else { if (yych <= '`') goto yy57; if (yych <= 'z') goto yy236; goto yy57; } } } yy232: YYDEBUG(232, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych == ')') goto yy228; if (yych <= '@') goto yy223; goto yy237; } else { if (yych <= 'Z') { if (yych <= 'M') goto yy257; goto yy237; } else { if (yych <= '`') goto yy223; if (yych <= 'z') goto yy242; goto yy223; } } yy233: YYDEBUG(233, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '1') goto yy252; if (yych <= '2') goto yy253; if (yych <= '9') goto yy254; goto yy57; yy234: YYDEBUG(234, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') goto yy57; if (yych <= 'Z') goto yy236; if (yych <= '`') goto yy57; if (yych <= 'z') goto yy236; goto yy57; yy235: YYDEBUG(235, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') { if (yych == ')') goto yy228; goto yy223; } else { if (yych <= 'Z') goto yy237; if (yych <= '`') goto yy223; if (yych <= 'z') goto yy242; goto yy223; } yy236: YYDEBUG(236, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') { if (yych == ')') goto yy228; goto yy223; } else { if (yych <= 'Z') goto yy237; if (yych <= '`') goto yy223; if (yych >= '{') goto yy223; } yy237: YYDEBUG(237, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') { if (yych == ')') goto yy228; goto yy223; } else { if (yych <= 'Z') goto yy238; if (yych <= '`') goto yy223; if (yych >= '{') goto yy223; } yy238: YYDEBUG(238, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') { if (yych == ')') goto yy228; goto yy223; } else { if (yych <= 'Z') goto yy239; if (yych <= '`') goto yy223; if (yych >= '{') goto yy223; } yy239: YYDEBUG(239, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') { if (yych == ')') goto yy228; goto yy223; } else { if (yych <= 'Z') goto yy240; if (yych <= '`') goto yy223; if (yych >= '{') goto yy223; } yy240: YYDEBUG(240, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '@') { if (yych == ')') goto yy228; goto yy223; } else { if (yych <= 'Z') goto yy241; if (yych <= '`') goto yy223; if (yych >= '{') goto yy223; } yy241: YYDEBUG(241, *YYCURSOR); yych = *++YYCURSOR; if (yych == ')') goto yy228; goto yy223; yy242: YYDEBUG(242, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') { if (yych == ')') goto yy228; goto yy223; } else { if (yych == '.') goto yy223; goto yy244; } } else { if (yych <= '^') { if (yych <= '@') goto yy223; if (yych <= 'Z') goto yy238; goto yy223; } else { if (yych <= '_') goto yy244; if (yych <= '`') goto yy223; if (yych >= '{') goto yy223; } } yy243: YYDEBUG(243, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') { if (yych == ')') goto yy228; goto yy223; } else { if (yych == '.') goto yy223; } } else { if (yych <= '^') { if (yych <= '@') goto yy223; if (yych <= 'Z') goto yy239; goto yy223; } else { if (yych <= '_') goto yy244; if (yych <= '`') goto yy223; if (yych <= 'z') goto yy247; goto yy223; } } yy244: YYDEBUG(244, *YYCURSOR); ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yych <= '@') goto yy57; if (yych <= 'Z') goto yy245; if (yych <= '`') goto yy57; if (yych >= '{') goto yy57; yy245: YYDEBUG(245, *YYCURSOR); yyaccept = 7; YYMARKER = ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; YYDEBUG(246, *YYCURSOR); if (yych <= '@') { if (yych <= '-') { if (yych <= ',') goto yy223; goto yy244; } else { if (yych == '/') goto yy244; goto yy223; } } else { if (yych <= '_') { if (yych <= 'Z') goto yy245; if (yych <= '^') goto yy223; goto yy244; } else { if (yych <= '`') goto yy223; if (yych <= 'z') goto yy245; goto yy223; } } yy247: YYDEBUG(247, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') { if (yych == ')') goto yy228; goto yy223; } else { if (yych == '.') goto yy223; goto yy244; } } else { if (yych <= '^') { if (yych <= '@') goto yy223; if (yych <= 'Z') goto yy240; goto yy223; } else { if (yych <= '_') goto yy244; if (yych <= '`') goto yy223; if (yych >= '{') goto yy223; } } YYDEBUG(248, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') { if (yych == ')') goto yy228; goto yy223; } else { if (yych == '.') goto yy223; goto yy244; } } else { if (yych <= '^') { if (yych <= '@') goto yy223; if (yych <= 'Z') goto yy241; goto yy223; } else { if (yych <= '_') goto yy244; if (yych <= '`') goto yy223; if (yych >= '{') goto yy223; } } YYDEBUG(249, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ')') { if (yych <= '(') goto yy223; goto yy228; } else { if (yych == '-') goto yy244; goto yy223; } } else { if (yych <= '_') { if (yych <= '/') goto yy244; if (yych <= '^') goto yy223; goto yy244; } else { if (yych <= '`') goto yy223; if (yych >= '{') goto yy223; } } yy250: YYDEBUG(250, *YYCURSOR); ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; YYDEBUG(251, *YYCURSOR); if (yych <= '/') { if (yych == '-') goto yy244; if (yych <= '.') goto yy57; goto yy244; } else { if (yych <= '_') { if (yych <= '^') goto yy57; goto yy244; } else { if (yych <= '`') goto yy57; if (yych <= 'z') goto yy250; goto yy57; } } yy252: YYDEBUG(252, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy223; if (yych <= '9') goto yy254; if (yych <= ':') goto yy255; goto yy223; yy253: YYDEBUG(253, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '5') { if (yych <= '/') goto yy223; if (yych >= '5') goto yy256; } else { if (yych <= '9') goto yy228; if (yych <= ':') goto yy255; goto yy223; } yy254: YYDEBUG(254, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy223; if (yych <= '5') goto yy256; if (yych <= '9') goto yy228; if (yych >= ';') goto yy223; yy255: YYDEBUG(255, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy223; if (yych <= '5') goto yy256; if (yych <= '9') goto yy228; goto yy223; yy256: YYDEBUG(256, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy223; if (yych <= '9') goto yy228; goto yy223; yy257: YYDEBUG(257, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych == ')') goto yy228; if (yych <= '@') goto yy223; goto yy238; } else { if (yych <= 'Z') { if (yych >= 'U') goto yy238; } else { if (yych <= '`') goto yy223; if (yych <= 'z') goto yy238; goto yy223; } } YYDEBUG(258, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= ')') { if (yych <= '(') goto yy223; goto yy228; } else { if (yych == '+') goto yy233; goto yy223; } } else { if (yych <= 'Z') { if (yych <= '-') goto yy233; if (yych <= '@') goto yy223; goto yy239; } else { if (yych <= '`') goto yy223; if (yych <= 'z') goto yy239; goto yy223; } } yy259: YYDEBUG(259, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy221; goto yy199; } else { if (yych <= '0') goto yy291; if (yych <= '9') goto yy292; if (yych <= ':') goto yy221; goto yy199; } yy260: YYDEBUG(260, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy264; goto yy199; } else { if (yych <= '2') goto yy292; if (yych <= '9') goto yy291; if (yych <= ':') goto yy264; goto yy199; } yy261: YYDEBUG(261, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy264; goto yy199; } else { if (yych <= '4') goto yy291; if (yych <= '9') goto yy263; if (yych <= ':') goto yy264; goto yy199; } yy262: YYDEBUG(262, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy264; goto yy199; } else { if (yych <= '9') goto yy263; if (yych <= ':') goto yy264; goto yy199; } yy263: YYDEBUG(263, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy199; if (yych <= '9') goto yy289; goto yy199; yy264: YYDEBUG(264, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy265; if (yych <= '9') goto yy266; goto yy57; yy265: YYDEBUG(265, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy267; goto yy223; } else { if (yych <= '9') goto yy282; if (yych <= ':') goto yy267; goto yy223; } yy266: YYDEBUG(266, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy267; if (yych != ':') goto yy223; yy267: YYDEBUG(267, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy268; if (yych <= '6') goto yy269; if (yych <= '9') goto yy228; goto yy57; yy268: YYDEBUG(268, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy223; if (yych <= '9') goto yy270; goto yy223; yy269: YYDEBUG(269, *YYCURSOR); yych = *++YYCURSOR; if (yych != '0') goto yy223; yy270: YYDEBUG(270, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '*') { if (yych <= 0x1F) { if (yych == '\t') goto yy272; goto yy223; } else { if (yych <= ' ') goto yy272; if (yych == '(') goto yy272; goto yy223; } } else { if (yych <= '@') { if (yych == ',') goto yy223; if (yych <= '-') goto yy272; goto yy223; } else { if (yych <= 'Z') goto yy272; if (yych <= '`') goto yy223; if (yych <= 'z') goto yy272; goto yy223; } } yy271: YYDEBUG(271, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 9) YYFILL(9); yych = *YYCURSOR; yy272: YYDEBUG(272, *YYCURSOR); if (yych <= '@') { if (yych <= '\'') { if (yych <= '\t') { if (yych <= 0x08) goto yy57; goto yy271; } else { if (yych == ' ') goto yy271; goto yy57; } } else { if (yych <= '+') { if (yych <= '(') goto yy234; if (yych <= '*') goto yy57; goto yy233; } else { if (yych == '-') goto yy233; goto yy57; } } } else { if (yych <= 'Z') { if (yych <= 'G') { if (yych <= 'A') goto yy273; if (yych <= 'F') goto yy235; goto yy232; } else { if (yych != 'P') goto yy235; } } else { if (yych <= 'o') { if (yych <= '`') goto yy57; if (yych <= 'a') goto yy274; goto yy236; } else { if (yych <= 'p') goto yy274; if (yych <= 'z') goto yy236; goto yy57; } } } yy273: YYDEBUG(273, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'L') { if (yych <= '-') { if (yych == ')') goto yy228; goto yy223; } else { if (yych <= '.') goto yy275; if (yych <= '@') goto yy223; goto yy237; } } else { if (yych <= '`') { if (yych <= 'M') goto yy276; if (yych <= 'Z') goto yy237; goto yy223; } else { if (yych == 'm') goto yy281; if (yych <= 'z') goto yy242; goto yy223; } } yy274: YYDEBUG(274, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'L') { if (yych <= '-') { if (yych == ')') goto yy228; goto yy223; } else { if (yych <= '.') goto yy275; if (yych <= '@') goto yy223; goto yy237; } } else { if (yych <= '`') { if (yych <= 'M') goto yy276; if (yych <= 'Z') goto yy237; goto yy223; } else { if (yych == 'm') goto yy276; if (yych <= 'z') goto yy237; goto yy223; } } yy275: YYDEBUG(275, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy280; if (yych == 'm') goto yy280; goto yy57; yy276: YYDEBUG(276, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ')') { if (yych <= '\t') { if (yych <= 0x00) goto yy278; if (yych <= 0x08) goto yy223; goto yy278; } else { if (yych == ' ') goto yy278; if (yych <= '(') goto yy223; goto yy228; } } else { if (yych <= '@') { if (yych != '.') goto yy223; } else { if (yych <= 'Z') goto yy238; if (yych <= '`') goto yy223; if (yych <= 'z') goto yy238; goto yy223; } } yy277: YYDEBUG(277, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '\t') { if (yych <= 0x00) goto yy278; if (yych <= 0x08) goto yy57; } else { if (yych != ' ') goto yy57; } yy278: YYDEBUG(278, *YYCURSOR); ++YYCURSOR; YYDEBUG(279, *YYCURSOR); #line 1690 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("dateshortwithtimeshort12 | dateshortwithtimelong12"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->m = timelib_get_month((char **) &ptr); s->time->d = timelib_get_nr((char **) &ptr, 2); TIMELIB_HAVE_TIME(); s->time->h = timelib_get_nr((char **) &ptr, 2); s->time->i = timelib_get_nr((char **) &ptr, 2); if (*ptr == ':' || *ptr == '.') { s->time->s = timelib_get_nr((char **) &ptr, 2); if (*ptr == '.') { s->time->f = timelib_get_frac_nr((char **) &ptr, 8); } } s->time->h += timelib_meridian((char **) &ptr, s->time->h); TIMELIB_DEINIT; return TIMELIB_SHORTDATE_WITH_TIME; } #line 5235 "ext/date/lib/parse_date.c" yy280: YYDEBUG(280, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 0x1F) { if (yych <= 0x00) goto yy278; if (yych == '\t') goto yy278; goto yy57; } else { if (yych <= ' ') goto yy278; if (yych == '.') goto yy277; goto yy57; } yy281: YYDEBUG(281, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '-') { if (yych <= 0x1F) { if (yych <= 0x00) goto yy278; if (yych == '\t') goto yy278; goto yy223; } else { if (yych <= '(') { if (yych <= ' ') goto yy278; goto yy223; } else { if (yych <= ')') goto yy228; if (yych <= ',') goto yy223; goto yy244; } } } else { if (yych <= 'Z') { if (yych <= '.') goto yy277; if (yych <= '/') goto yy244; if (yych <= '@') goto yy223; goto yy238; } else { if (yych <= '_') { if (yych <= '^') goto yy223; goto yy244; } else { if (yych <= '`') goto yy223; if (yych <= 'z') goto yy243; goto yy223; } } } yy282: YYDEBUG(282, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ':') { if (yych <= ' ') { if (yych == '\t') goto yy283; if (yych <= 0x1F) goto yy223; } else { if (yych == '.') goto yy267; if (yych <= '9') goto yy223; goto yy267; } } else { if (yych <= 'P') { if (yych == 'A') goto yy285; if (yych <= 'O') goto yy223; goto yy285; } else { if (yych <= 'a') { if (yych <= '`') goto yy223; goto yy285; } else { if (yych == 'p') goto yy285; goto yy223; } } } yy283: YYDEBUG(283, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 5) YYFILL(5); yych = *YYCURSOR; YYDEBUG(284, *YYCURSOR); if (yych <= 'A') { if (yych <= 0x1F) { if (yych == '\t') goto yy283; goto yy57; } else { if (yych <= ' ') goto yy283; if (yych <= '@') goto yy57; } } else { if (yych <= '`') { if (yych != 'P') goto yy57; } else { if (yych <= 'a') goto yy285; if (yych != 'p') goto yy57; } } yy285: YYDEBUG(285, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych != '.') goto yy57; } else { if (yych <= 'M') goto yy287; if (yych == 'm') goto yy287; goto yy57; } yy286: YYDEBUG(286, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy287; if (yych != 'm') goto yy57; yy287: YYDEBUG(287, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 0x1F) { if (yych <= 0x00) goto yy278; if (yych == '\t') goto yy278; goto yy57; } else { if (yych <= ' ') goto yy278; if (yych != '.') goto yy57; } yy288: YYDEBUG(288, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '\t') { if (yych <= 0x00) goto yy278; if (yych <= 0x08) goto yy57; goto yy278; } else { if (yych == ' ') goto yy278; goto yy57; } yy289: YYDEBUG(289, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy199; if (yych >= ':') goto yy199; YYDEBUG(290, *YYCURSOR); yych = *++YYCURSOR; goto yy199; yy291: YYDEBUG(291, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy221; goto yy199; } else { if (yych <= '9') goto yy289; if (yych <= ':') goto yy221; goto yy199; } yy292: YYDEBUG(292, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy264; goto yy199; } else { if (yych <= '9') goto yy289; if (yych <= ':') goto yy264; goto yy199; } yy293: YYDEBUG(293, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; yy294: YYDEBUG(294, *YYCURSOR); ++YYCURSOR; yy295: YYDEBUG(295, *YYCURSOR); #line 1384 "ext/date/lib/parse_date.re" { int length = 0; DEBUG_OUTPUT("datenoday"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->m = timelib_get_month((char **) &ptr); s->time->y = timelib_get_nr_ex((char **) &ptr, 4, &length); s->time->d = 1; TIMELIB_PROCESS_YEAR(s->time->y, length); TIMELIB_DEINIT; return TIMELIB_DATE_NO_DAY; } #line 5426 "ext/date/lib/parse_date.c" yy296: YYDEBUG(296, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy221; goto yy57; } else { if (yych <= '9') goto yy294; if (yych <= ':') goto yy221; goto yy57; } yy297: YYDEBUG(297, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy264; goto yy57; } else { if (yych <= '9') goto yy294; if (yych <= ':') goto yy264; goto yy57; } yy298: YYDEBUG(298, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '/') { if (yych == '.') goto yy331; goto yy216; } else { if (yych <= '0') goto yy332; if (yych <= '1') goto yy302; if (yych <= '2') goto yy303; goto yy297; } } else { if (yych <= 'q') { if (yych <= ':') goto yy221; if (yych == 'n') goto yy212; goto yy216; } else { if (yych <= 'r') goto yy213; if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy299: YYDEBUG(299, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '/') { if (yych != '.') goto yy216; } else { if (yych <= '0') goto yy301; if (yych <= '1') goto yy302; if (yych <= '2') goto yy303; goto yy297; } } else { if (yych <= 'q') { if (yych <= ':') goto yy264; if (yych == 'n') goto yy212; goto yy216; } else { if (yych <= 'r') goto yy213; if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy300: YYDEBUG(300, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '1') { if (yych <= '/') goto yy216; if (yych <= '0') goto yy306; goto yy307; } else { if (yych <= '2') goto yy308; if (yych <= '5') goto yy309; if (yych <= '9') goto yy310; goto yy216; } yy301: YYDEBUG(301, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy264; goto yy57; } else { if (yych <= '0') goto yy304; if (yych <= '9') goto yy305; if (yych <= ':') goto yy264; goto yy57; } yy302: YYDEBUG(302, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy264; goto yy57; } else { if (yych <= '2') goto yy305; if (yych <= '9') goto yy304; if (yych <= ':') goto yy264; goto yy57; } yy303: YYDEBUG(303, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy264; goto yy57; } else { if (yych <= '4') goto yy304; if (yych <= '9') goto yy294; if (yych <= ':') goto yy264; goto yy57; } yy304: YYDEBUG(304, *YYCURSOR); yyaccept = 8; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy221; if (yych == ':') goto yy221; goto yy295; yy305: YYDEBUG(305, *YYCURSOR); yyaccept = 8; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy264; if (yych == ':') goto yy264; goto yy295; yy306: YYDEBUG(306, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy326; goto yy199; } else { if (yych <= '0') goto yy325; if (yych <= '9') goto yy330; if (yych <= ':') goto yy326; goto yy199; } yy307: YYDEBUG(307, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy311; goto yy199; } else { if (yych <= '2') goto yy330; if (yych <= '9') goto yy325; if (yych <= ':') goto yy311; goto yy199; } yy308: YYDEBUG(308, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy311; goto yy199; } else { if (yych <= '4') goto yy325; if (yych <= '9') goto yy324; if (yych <= ':') goto yy311; goto yy199; } yy309: YYDEBUG(309, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy311; goto yy199; } else { if (yych <= '9') goto yy324; if (yych <= ':') goto yy311; goto yy199; } yy310: YYDEBUG(310, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych != '.') goto yy199; } else { if (yych <= '9') goto yy263; if (yych >= ';') goto yy199; } yy311: YYDEBUG(311, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy312; if (yych <= '6') goto yy313; if (yych <= '9') goto yy266; goto yy57; yy312: YYDEBUG(312, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy267; goto yy223; } else { if (yych <= '9') goto yy314; if (yych <= ':') goto yy267; goto yy223; } yy313: YYDEBUG(313, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy267; goto yy223; } else { if (yych <= '0') goto yy270; if (yych == ':') goto yy267; goto yy223; } yy314: YYDEBUG(314, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= ' ') { if (yych == '\t') goto yy316; if (yych <= 0x1F) goto yy223; goto yy316; } else { if (yych <= '(') { if (yych <= '\'') goto yy223; goto yy316; } else { if (yych == '+') goto yy316; goto yy223; } } } else { if (yych <= ':') { if (yych <= '-') goto yy316; if (yych <= '.') goto yy267; if (yych <= '9') goto yy223; goto yy267; } else { if (yych <= 'Z') { if (yych <= '@') goto yy223; goto yy316; } else { if (yych <= '`') goto yy223; if (yych <= 'z') goto yy316; goto yy223; } } } yy315: YYDEBUG(315, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 9) YYFILL(9); yych = *YYCURSOR; yy316: YYDEBUG(316, *YYCURSOR); if (yych <= '@') { if (yych <= '\'') { if (yych <= '\t') { if (yych <= 0x08) goto yy57; goto yy315; } else { if (yych == ' ') goto yy315; goto yy57; } } else { if (yych <= '+') { if (yych <= '(') goto yy234; if (yych <= '*') goto yy57; goto yy233; } else { if (yych == '-') goto yy233; goto yy57; } } } else { if (yych <= 'Z') { if (yych <= 'G') { if (yych <= 'A') goto yy317; if (yych <= 'F') goto yy235; goto yy232; } else { if (yych != 'P') goto yy235; } } else { if (yych <= 'o') { if (yych <= '`') goto yy57; if (yych <= 'a') goto yy318; goto yy236; } else { if (yych <= 'p') goto yy318; if (yych <= 'z') goto yy236; goto yy57; } } } yy317: YYDEBUG(317, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'L') { if (yych <= '-') { if (yych == ')') goto yy228; goto yy223; } else { if (yych <= '.') goto yy320; if (yych <= '@') goto yy223; goto yy237; } } else { if (yych <= '`') { if (yych <= 'M') goto yy319; if (yych <= 'Z') goto yy237; goto yy223; } else { if (yych == 'm') goto yy323; if (yych <= 'z') goto yy242; goto yy223; } } yy318: YYDEBUG(318, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'L') { if (yych <= '-') { if (yych == ')') goto yy228; goto yy223; } else { if (yych <= '.') goto yy320; if (yych <= '@') goto yy223; goto yy237; } } else { if (yych <= '`') { if (yych <= 'M') goto yy319; if (yych <= 'Z') goto yy237; goto yy223; } else { if (yych == 'm') goto yy319; if (yych <= 'z') goto yy237; goto yy223; } } yy319: YYDEBUG(319, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ')') { if (yych <= '\t') { if (yych <= 0x00) goto yy278; if (yych <= 0x08) goto yy223; goto yy278; } else { if (yych == ' ') goto yy278; if (yych <= '(') goto yy223; goto yy228; } } else { if (yych <= '@') { if (yych == '.') goto yy322; goto yy223; } else { if (yych <= 'Z') goto yy238; if (yych <= '`') goto yy223; if (yych <= 'z') goto yy238; goto yy223; } } yy320: YYDEBUG(320, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy321; if (yych != 'm') goto yy57; yy321: YYDEBUG(321, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 0x1F) { if (yych <= 0x00) goto yy278; if (yych == '\t') goto yy278; goto yy57; } else { if (yych <= ' ') goto yy278; if (yych != '.') goto yy57; } yy322: YYDEBUG(322, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '\t') { if (yych <= 0x00) goto yy278; if (yych <= 0x08) goto yy57; goto yy278; } else { if (yych == ' ') goto yy278; goto yy57; } yy323: YYDEBUG(323, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '-') { if (yych <= 0x1F) { if (yych <= 0x00) goto yy278; if (yych == '\t') goto yy278; goto yy223; } else { if (yych <= '(') { if (yych <= ' ') goto yy278; goto yy223; } else { if (yych <= ')') goto yy228; if (yych <= ',') goto yy223; goto yy244; } } } else { if (yych <= 'Z') { if (yych <= '.') goto yy322; if (yych <= '/') goto yy244; if (yych <= '@') goto yy223; goto yy238; } else { if (yych <= '_') { if (yych <= '^') goto yy223; goto yy244; } else { if (yych <= '`') goto yy223; if (yych <= 'z') goto yy243; goto yy223; } } } yy324: YYDEBUG(324, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ':') { if (yych <= ' ') { if (yych == '\t') goto yy283; if (yych <= 0x1F) goto yy199; goto yy283; } else { if (yych <= '.') { if (yych <= '-') goto yy199; goto yy267; } else { if (yych <= '/') goto yy199; if (yych <= '9') goto yy289; goto yy267; } } } else { if (yych <= 'P') { if (yych == 'A') goto yy285; if (yych <= 'O') goto yy199; goto yy285; } else { if (yych <= 'a') { if (yych <= '`') goto yy199; goto yy285; } else { if (yych == 'p') goto yy285; goto yy199; } } } yy325: YYDEBUG(325, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ':') { if (yych <= ' ') { if (yych == '\t') goto yy283; if (yych <= 0x1F) goto yy199; goto yy283; } else { if (yych <= '.') { if (yych <= '-') goto yy199; } else { if (yych <= '/') goto yy199; if (yych <= '9') goto yy289; } } } else { if (yych <= 'P') { if (yych == 'A') goto yy285; if (yych <= 'O') goto yy199; goto yy285; } else { if (yych <= 'a') { if (yych <= '`') goto yy199; goto yy285; } else { if (yych == 'p') goto yy285; goto yy199; } } } yy326: YYDEBUG(326, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy327; if (yych <= '6') goto yy328; if (yych <= '9') goto yy224; goto yy57; yy327: YYDEBUG(327, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy225; goto yy223; } else { if (yych <= '9') goto yy329; if (yych <= ':') goto yy225; goto yy223; } yy328: YYDEBUG(328, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy225; goto yy223; } else { if (yych <= '0') goto yy270; if (yych == ':') goto yy225; goto yy223; } yy329: YYDEBUG(329, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= ' ') { if (yych == '\t') goto yy272; if (yych <= 0x1F) goto yy223; goto yy272; } else { if (yych <= '(') { if (yych <= '\'') goto yy223; goto yy272; } else { if (yych == '+') goto yy272; goto yy223; } } } else { if (yych <= ':') { if (yych <= '-') goto yy272; if (yych <= '.') goto yy225; if (yych <= '9') goto yy223; goto yy225; } else { if (yych <= 'Z') { if (yych <= '@') goto yy223; goto yy272; } else { if (yych <= '`') goto yy223; if (yych <= 'z') goto yy272; goto yy223; } } } yy330: YYDEBUG(330, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ':') { if (yych <= ' ') { if (yych == '\t') goto yy283; if (yych <= 0x1F) goto yy199; goto yy283; } else { if (yych <= '.') { if (yych <= '-') goto yy199; goto yy311; } else { if (yych <= '/') goto yy199; if (yych <= '9') goto yy289; goto yy311; } } } else { if (yych <= 'P') { if (yych == 'A') goto yy285; if (yych <= 'O') goto yy199; goto yy285; } else { if (yych <= 'a') { if (yych <= '`') goto yy199; goto yy285; } else { if (yych == 'p') goto yy285; goto yy199; } } } yy331: YYDEBUG(331, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '1') { if (yych <= '/') goto yy216; if (yych <= '0') goto yy333; goto yy334; } else { if (yych <= '2') goto yy335; if (yych <= '5') goto yy336; if (yych <= '9') goto yy337; goto yy216; } yy332: YYDEBUG(332, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy221; goto yy57; } else { if (yych <= '0') goto yy304; if (yych <= '9') goto yy305; if (yych <= ':') goto yy221; goto yy57; } yy333: YYDEBUG(333, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy350; goto yy199; } else { if (yych <= '0') goto yy349; if (yych <= '9') goto yy354; if (yych <= ':') goto yy350; goto yy199; } yy334: YYDEBUG(334, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy338; goto yy199; } else { if (yych <= '2') goto yy354; if (yych <= '9') goto yy349; if (yych <= ':') goto yy338; goto yy199; } yy335: YYDEBUG(335, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy338; goto yy199; } else { if (yych <= '4') goto yy349; if (yych <= '9') goto yy348; if (yych <= ':') goto yy338; goto yy199; } yy336: YYDEBUG(336, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy338; goto yy199; } else { if (yych <= '9') goto yy348; if (yych <= ':') goto yy338; goto yy199; } yy337: YYDEBUG(337, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych != '.') goto yy199; } else { if (yych <= '9') goto yy263; if (yych >= ';') goto yy199; } yy338: YYDEBUG(338, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy339; if (yych <= '6') goto yy340; if (yych <= '9') goto yy266; goto yy57; yy339: YYDEBUG(339, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy267; goto yy223; } else { if (yych <= '9') goto yy341; if (yych <= ':') goto yy267; goto yy223; } yy340: YYDEBUG(340, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy267; goto yy223; } else { if (yych <= '0') goto yy229; if (yych == ':') goto yy267; goto yy223; } yy341: YYDEBUG(341, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= ' ') { if (yych == '\t') goto yy343; if (yych <= 0x1F) goto yy223; goto yy343; } else { if (yych <= '(') { if (yych <= '\'') goto yy223; goto yy343; } else { if (yych == '+') goto yy343; goto yy223; } } } else { if (yych <= ':') { if (yych <= '-') goto yy343; if (yych <= '.') goto yy267; if (yych <= '9') goto yy223; goto yy267; } else { if (yych <= 'Z') { if (yych <= '@') goto yy223; goto yy343; } else { if (yych <= '`') goto yy223; if (yych <= 'z') goto yy343; goto yy223; } } } yy342: YYDEBUG(342, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 9) YYFILL(9); yych = *YYCURSOR; yy343: YYDEBUG(343, *YYCURSOR); if (yych <= '@') { if (yych <= '\'') { if (yych <= '\t') { if (yych <= 0x08) goto yy57; goto yy342; } else { if (yych == ' ') goto yy342; goto yy57; } } else { if (yych <= '+') { if (yych <= '(') goto yy234; if (yych <= '*') goto yy57; goto yy233; } else { if (yych == '-') goto yy233; goto yy57; } } } else { if (yych <= 'Z') { if (yych <= 'G') { if (yych <= 'A') goto yy344; if (yych <= 'F') goto yy235; goto yy232; } else { if (yych != 'P') goto yy235; } } else { if (yych <= 'o') { if (yych <= '`') goto yy57; if (yych <= 'a') goto yy345; goto yy236; } else { if (yych <= 'p') goto yy345; if (yych <= 'z') goto yy236; goto yy57; } } } yy344: YYDEBUG(344, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'L') { if (yych <= '-') { if (yych == ')') goto yy228; goto yy223; } else { if (yych <= '.') goto yy286; if (yych <= '@') goto yy223; goto yy237; } } else { if (yych <= '`') { if (yych <= 'M') goto yy346; if (yych <= 'Z') goto yy237; goto yy223; } else { if (yych == 'm') goto yy347; if (yych <= 'z') goto yy242; goto yy223; } } yy345: YYDEBUG(345, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'L') { if (yych <= '-') { if (yych == ')') goto yy228; goto yy223; } else { if (yych <= '.') goto yy286; if (yych <= '@') goto yy223; goto yy237; } } else { if (yych <= '`') { if (yych <= 'M') goto yy346; if (yych <= 'Z') goto yy237; goto yy223; } else { if (yych == 'm') goto yy346; if (yych <= 'z') goto yy237; goto yy223; } } yy346: YYDEBUG(346, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ')') { if (yych <= '\t') { if (yych <= 0x00) goto yy278; if (yych <= 0x08) goto yy223; goto yy278; } else { if (yych == ' ') goto yy278; if (yych <= '(') goto yy223; goto yy228; } } else { if (yych <= '@') { if (yych == '.') goto yy288; goto yy223; } else { if (yych <= 'Z') goto yy238; if (yych <= '`') goto yy223; if (yych <= 'z') goto yy238; goto yy223; } } yy347: YYDEBUG(347, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '-') { if (yych <= 0x1F) { if (yych <= 0x00) goto yy278; if (yych == '\t') goto yy278; goto yy223; } else { if (yych <= '(') { if (yych <= ' ') goto yy278; goto yy223; } else { if (yych <= ')') goto yy228; if (yych <= ',') goto yy223; goto yy244; } } } else { if (yych <= 'Z') { if (yych <= '.') goto yy288; if (yych <= '/') goto yy244; if (yych <= '@') goto yy223; goto yy238; } else { if (yych <= '_') { if (yych <= '^') goto yy223; goto yy244; } else { if (yych <= '`') goto yy223; if (yych <= 'z') goto yy243; goto yy223; } } } yy348: YYDEBUG(348, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy225; goto yy199; } else { if (yych <= '9') goto yy289; if (yych <= ':') goto yy225; goto yy199; } yy349: YYDEBUG(349, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych != '.') goto yy199; } else { if (yych <= '9') goto yy289; if (yych >= ';') goto yy199; } yy350: YYDEBUG(350, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy351; if (yych <= '6') goto yy352; if (yych <= '9') goto yy224; goto yy57; yy351: YYDEBUG(351, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy225; goto yy223; } else { if (yych <= '9') goto yy353; if (yych <= ':') goto yy225; goto yy223; } yy352: YYDEBUG(352, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy225; goto yy223; } else { if (yych <= '0') goto yy229; if (yych == ':') goto yy225; goto yy223; } yy353: YYDEBUG(353, *YYCURSOR); yyaccept = 7; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= ' ') { if (yych == '\t') goto yy231; if (yych <= 0x1F) goto yy223; goto yy231; } else { if (yych <= '(') { if (yych <= '\'') goto yy223; goto yy231; } else { if (yych == '+') goto yy231; goto yy223; } } } else { if (yych <= ':') { if (yych <= '-') goto yy231; if (yych <= '.') goto yy225; if (yych <= '9') goto yy223; goto yy225; } else { if (yych <= 'Z') { if (yych <= '@') goto yy223; goto yy231; } else { if (yych <= '`') goto yy223; if (yych <= 'z') goto yy231; goto yy223; } } } yy354: YYDEBUG(354, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy338; goto yy199; } else { if (yych <= '9') goto yy289; if (yych <= ':') goto yy338; goto yy199; } yy355: YYDEBUG(355, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '/') { if (yych == '.') goto yy300; goto yy216; } else { if (yych <= '0') goto yy332; if (yych <= '1') goto yy302; if (yych <= '2') goto yy303; goto yy297; } } else { if (yych <= 'q') { if (yych <= ':') goto yy264; if (yych == 'n') goto yy212; goto yy216; } else { if (yych <= 'r') goto yy213; if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy356: YYDEBUG(356, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '/') { if (yych == '.') goto yy300; goto yy216; } else { if (yych <= '0') goto yy332; if (yych <= '1') goto yy302; if (yych <= '2') goto yy303; goto yy297; } } else { if (yych <= 'q') { if (yych <= ':') goto yy264; if (yych == 'n') goto yy212; goto yy216; } else { if (yych <= 'r') goto yy213; if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy357: YYDEBUG(357, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'm') { if (yych <= '1') { if (yych <= '/') goto yy216; if (yych <= '0') goto yy360; goto yy361; } else { if (yych <= '2') goto yy368; if (yych <= '9') goto yy369; goto yy216; } } else { if (yych <= 'r') { if (yych <= 'n') goto yy212; if (yych <= 'q') goto yy216; goto yy213; } else { if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy358: YYDEBUG(358, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'm') { if (yych <= '1') { if (yych <= '/') goto yy216; if (yych <= '0') goto yy360; goto yy361; } else { if (yych <= '2') goto yy368; if (yych <= '9') goto yy369; goto yy216; } } else { if (yych <= 'r') { if (yych <= 'n') goto yy212; if (yych <= 'q') goto yy216; goto yy213; } else { if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy359: YYDEBUG(359, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'm') { if (yych <= '1') { if (yych <= '/') goto yy216; if (yych >= '1') goto yy361; } else { if (yych <= '2') goto yy209; if (yych <= '9') goto yy210; goto yy216; } } else { if (yych <= 'r') { if (yych <= 'n') goto yy212; if (yych <= 'q') goto yy216; goto yy213; } else { if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy360: YYDEBUG(360, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '/') { if (yych <= ',') goto yy216; if (yych <= '-') goto yy362; if (yych <= '.') goto yy331; goto yy216; } else { if (yych <= '0') goto yy332; if (yych <= '1') goto yy302; if (yych <= '2') goto yy303; goto yy297; } } else { if (yych <= 'q') { if (yych <= ':') goto yy221; if (yych == 'n') goto yy212; goto yy216; } else { if (yych <= 'r') goto yy213; if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy361: YYDEBUG(361, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '/') { if (yych <= ',') goto yy216; if (yych <= '-') goto yy362; if (yych <= '.') goto yy300; goto yy216; } else { if (yych <= '0') goto yy301; if (yych <= '1') goto yy302; if (yych <= '2') goto yy303; goto yy297; } } else { if (yych <= 'q') { if (yych <= ':') goto yy264; if (yych == 'n') goto yy212; goto yy216; } else { if (yych <= 'r') goto yy213; if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy362: YYDEBUG(362, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; YYDEBUG(363, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '/') goto yy364; if (yych <= '9') goto yy365; yy364: YYDEBUG(364, *YYCURSOR); #line 1528 "ext/date/lib/parse_date.re" { int length = 0; DEBUG_OUTPUT("pgtextshort"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->m = timelib_get_month((char **) &ptr); s->time->d = timelib_get_nr((char **) &ptr, 2); s->time->y = timelib_get_nr_ex((char **) &ptr, 4, &length); TIMELIB_PROCESS_YEAR(s->time->y, length); TIMELIB_DEINIT; return TIMELIB_PG_TEXT; } #line 6659 "ext/date/lib/parse_date.c" yy365: YYDEBUG(365, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy364; if (yych >= ':') goto yy364; YYDEBUG(366, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy364; if (yych >= ':') goto yy364; YYDEBUG(367, *YYCURSOR); yych = *++YYCURSOR; goto yy364; yy368: YYDEBUG(368, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '/') { if (yych <= ',') goto yy216; if (yych <= '-') goto yy362; if (yych <= '.') goto yy300; goto yy216; } else { if (yych <= '0') goto yy332; if (yych <= '1') goto yy302; if (yych <= '2') goto yy303; goto yy297; } } else { if (yych <= 'q') { if (yych <= ':') goto yy264; if (yych == 'n') goto yy212; goto yy216; } else { if (yych <= 'r') goto yy213; if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy369: YYDEBUG(369, *YYCURSOR); yyaccept = 6; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '/') { if (yych <= ',') goto yy216; if (yych <= '-') goto yy362; if (yych <= '.') goto yy300; goto yy216; } else { if (yych <= '0') goto yy332; if (yych <= '1') goto yy302; if (yych <= '2') goto yy303; goto yy297; } } else { if (yych <= 'q') { if (yych <= ':') goto yy264; if (yych == 'n') goto yy212; goto yy216; } else { if (yych <= 'r') goto yy213; if (yych <= 's') goto yy211; if (yych <= 't') goto yy214; goto yy216; } } yy370: YYDEBUG(370, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'B') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'C') goto yy193; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'b') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'c') goto yy371; if (yych <= 'z') goto yy147; goto yy4; } } } yy371: YYDEBUG(371, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= '-') { if (yych <= ')') goto yy140; if (yych <= ',') goto yy194; } else { if (yych == '/') goto yy148; goto yy196; } } } else { if (yych <= '^') { if (yych <= 'D') { if (yych <= '@') goto yy194; goto yy143; } else { if (yych <= 'E') goto yy202; if (yych <= 'Z') goto yy143; goto yy194; } } else { if (yych <= 'd') { if (yych <= '_') goto yy148; if (yych <= '`') goto yy194; goto yy151; } else { if (yych <= 'e') goto yy373; if (yych <= 'z') goto yy151; goto yy194; } } } yy372: YYDEBUG(372, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 8) { goto yy149; } if (yych <= '/') goto yy196; if (yych <= '0') goto yy357; if (yych <= '2') goto yy358; if (yych <= '3') goto yy359; goto yy196; yy373: YYDEBUG(373, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'L') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'M') goto yy203; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'l') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'm') goto yy374; if (yych <= 'z') goto yy152; goto yy4; } } } yy374: YYDEBUG(374, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'A') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'B') goto yy204; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'a') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'b') goto yy375; if (yych <= 'z') goto yy153; goto yy4; } } } yy375: YYDEBUG(375, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'E') goto yy205; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'e') goto yy376; if (yych <= 'z') goto yy154; goto yy4; } } yy376: YYDEBUG(376, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy206; if (yych != 'r') goto yy155; yy377: YYDEBUG(377, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 16) { goto yy154; } if (yych <= '-') { if (yych <= 0x1F) { if (yych == '\t') goto yy196; goto yy194; } else { if (yych <= ' ') goto yy196; if (yych <= ',') goto yy194; } } else { if (yych <= '9') { if (yych == '/') goto yy148; goto yy196; } else { if (yych == '_') goto yy148; goto yy194; } } yy378: YYDEBUG(378, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 8) { goto yy149; } goto yy196; yy379: YYDEBUG(379, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy142; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 't') goto yy380; if (yych <= 'z') goto yy142; goto yy4; } } yy380: YYDEBUG(380, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; goto yy194; } else { if (yych <= '-') goto yy197; if (yych <= '.') goto yy196; goto yy194; } } } else { if (yych <= 'Z') { if (yych <= '@') { if (yych <= '9') goto yy196; goto yy194; } else { if (yych != 'O') goto yy143; } } else { if (yych <= 'n') { if (yych <= '`') goto yy194; goto yy143; } else { if (yych <= 'o') goto yy381; if (yych <= 'z') goto yy143; goto yy194; } } } yy381: YYDEBUG(381, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'B') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'A') goto yy144; } } else { if (yych <= 'a') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'b') goto yy382; if (yych <= 'z') goto yy144; goto yy4; } } yy382: YYDEBUG(382, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy145; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'e') goto yy383; if (yych <= 'z') goto yy145; goto yy4; } } yy383: YYDEBUG(383, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Q') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'R') goto yy206; if (yych == 'r') goto yy206; goto yy4; } yy384: YYDEBUG(384, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'T') goto yy380; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 't') goto yy385; if (yych <= 'z') goto yy147; goto yy4; } } } yy385: YYDEBUG(385, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= '-') { if (yych <= ')') goto yy140; if (yych <= ',') goto yy194; goto yy372; } else { if (yych == '/') goto yy148; goto yy196; } } } else { if (yych <= '^') { if (yych <= 'N') { if (yych <= '@') goto yy194; goto yy143; } else { if (yych <= 'O') goto yy381; if (yych <= 'Z') goto yy143; goto yy194; } } else { if (yych <= 'n') { if (yych <= '_') goto yy148; if (yych <= '`') goto yy194; goto yy151; } else { if (yych <= 'o') goto yy386; if (yych <= 'z') goto yy151; goto yy194; } } } yy386: YYDEBUG(386, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'A') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'B') goto yy382; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'a') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'b') goto yy387; if (yych <= 'z') goto yy152; goto yy4; } } } yy387: YYDEBUG(387, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'E') goto yy383; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'd') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'e') goto yy388; if (yych <= 'z') goto yy153; goto yy4; } } } yy388: YYDEBUG(388, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'Q') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'R') goto yy206; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'r') goto yy377; if (yych <= 'z') goto yy154; goto yy4; } } yy389: YYDEBUG(389, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'G') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'F') goto yy142; goto yy397; } } else { if (yych <= 'f') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'g') goto yy397; if (yych <= 'z') goto yy142; goto yy4; } } yy390: YYDEBUG(390, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'Q') goto yy142; goto yy394; } } else { if (yych <= 'q') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'r') goto yy394; if (yych <= 'z') goto yy142; goto yy4; } } yy391: YYDEBUG(391, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'N') goto yy142; } } else { if (yych <= 'n') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'o') goto yy392; if (yych <= 'z') goto yy142; goto yy4; } } yy392: YYDEBUG(392, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '@') { if (yych == ')') goto yy140; } else { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy393; if (yych <= 'z') goto yy143; } yy393: YYDEBUG(393, *YYCURSOR); #line 1586 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("ago"); TIMELIB_INIT; s->time->relative.y = 0 - s->time->relative.y; s->time->relative.m = 0 - s->time->relative.m; s->time->relative.d = 0 - s->time->relative.d; s->time->relative.h = 0 - s->time->relative.h; s->time->relative.i = 0 - s->time->relative.i; s->time->relative.s = 0 - s->time->relative.s; s->time->relative.weekday = 0 - s->time->relative.weekday; if (s->time->relative.weekday == 0) { s->time->relative.weekday = -7; } if (s->time->relative.have_special_relative && s->time->relative.special.type == TIMELIB_SPECIAL_WEEKDAY) { s->time->relative.special.amount = 0 - s->time->relative.special.amount; } TIMELIB_DEINIT; return TIMELIB_AGO; } #line 7317 "ext/date/lib/parse_date.c" yy394: YYDEBUG(394, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; goto yy194; } else { if (yych <= '-') goto yy197; if (yych <= '.') goto yy196; goto yy194; } } } else { if (yych <= 'Z') { if (yych <= '@') { if (yych <= '9') goto yy196; goto yy194; } else { if (yych != 'I') goto yy143; } } else { if (yych <= 'h') { if (yych <= '`') goto yy194; goto yy143; } else { if (yych <= 'i') goto yy395; if (yych <= 'z') goto yy143; goto yy194; } } } yy395: YYDEBUG(395, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'K') goto yy144; } } else { if (yych <= 'k') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'l') goto yy396; if (yych <= 'z') goto yy144; goto yy4; } } yy396: YYDEBUG(396, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= 0x1F) { if (yych == '\t') goto yy196; goto yy194; } else { if (yych <= ' ') goto yy196; if (yych == ')') goto yy140; goto yy194; } } else { if (yych <= '@') { if (yych == '/') goto yy194; if (yych <= '9') goto yy196; goto yy194; } else { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy194; if (yych <= 'z') goto yy145; goto yy194; } } yy397: YYDEBUG(397, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; goto yy194; } else { if (yych <= '-') goto yy197; if (yych <= '.') goto yy196; goto yy194; } } } else { if (yych <= 'Z') { if (yych <= '@') { if (yych <= '9') goto yy196; goto yy194; } else { if (yych != 'U') goto yy143; } } else { if (yych <= 't') { if (yych <= '`') goto yy194; goto yy143; } else { if (yych <= 'u') goto yy398; if (yych <= 'z') goto yy143; goto yy194; } } } yy398: YYDEBUG(398, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'R') goto yy144; } } else { if (yych <= 'r') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 's') goto yy399; if (yych <= 'z') goto yy144; goto yy4; } } yy399: YYDEBUG(399, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy145; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 't') goto yy400; if (yych <= 'z') goto yy145; goto yy4; } } yy400: YYDEBUG(400, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= '.') { if (yych <= ')') goto yy140; if (yych <= ',') goto yy194; goto yy196; } else { if (yych <= '/') goto yy194; if (yych <= '9') goto yy196; goto yy194; } } yy401: YYDEBUG(401, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'F') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'G') goto yy397; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'f') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'g') goto yy408; if (yych <= 'z') goto yy147; goto yy4; } } } yy402: YYDEBUG(402, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'Q') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'R') goto yy394; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'q') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'r') goto yy405; if (yych <= 'z') goto yy147; goto yy4; } } } yy403: YYDEBUG(403, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'N') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'O') goto yy392; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'n') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'o') goto yy404; if (yych <= 'z') goto yy147; goto yy4; } } } yy404: YYDEBUG(404, *YYCURSOR); yyaccept = 9; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy393; } else { if (yych == '.') goto yy393; goto yy148; } } else { if (yych <= '^') { if (yych <= '@') goto yy393; if (yych <= 'Z') goto yy143; goto yy393; } else { if (yych <= '_') goto yy148; if (yych <= '`') goto yy393; if (yych <= 'z') goto yy151; goto yy393; } } yy405: YYDEBUG(405, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= '-') { if (yych <= ')') goto yy140; if (yych <= ',') goto yy194; goto yy372; } else { if (yych == '/') goto yy148; goto yy196; } } } else { if (yych <= '^') { if (yych <= 'H') { if (yych <= '@') goto yy194; goto yy143; } else { if (yych <= 'I') goto yy395; if (yych <= 'Z') goto yy143; goto yy194; } } else { if (yych <= 'h') { if (yych <= '_') goto yy148; if (yych <= '`') goto yy194; goto yy151; } else { if (yych <= 'i') goto yy406; if (yych <= 'z') goto yy151; goto yy194; } } } yy406: YYDEBUG(406, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'K') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'L') goto yy396; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'k') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'l') goto yy407; if (yych <= 'z') goto yy152; goto yy4; } } } yy407: YYDEBUG(407, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ' ') { if (yych == '\t') goto yy196; if (yych <= 0x1F) goto yy194; goto yy196; } else { if (yych <= ')') { if (yych <= '(') goto yy194; goto yy140; } else { if (yych <= ',') goto yy194; if (yych <= '-') goto yy378; goto yy196; } } } else { if (yych <= 'Z') { if (yych <= '/') goto yy148; if (yych <= '9') goto yy196; if (yych <= '@') goto yy194; goto yy145; } else { if (yych <= '_') { if (yych <= '^') goto yy194; goto yy148; } else { if (yych <= '`') goto yy194; if (yych <= 'z') goto yy153; goto yy194; } } } yy408: YYDEBUG(408, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= '-') { if (yych <= ')') goto yy140; if (yych <= ',') goto yy194; goto yy372; } else { if (yych == '/') goto yy148; goto yy196; } } } else { if (yych <= '^') { if (yych <= 'T') { if (yych <= '@') goto yy194; goto yy143; } else { if (yych <= 'U') goto yy398; if (yych <= 'Z') goto yy143; goto yy194; } } else { if (yych <= 't') { if (yych <= '_') goto yy148; if (yych <= '`') goto yy194; goto yy151; } else { if (yych <= 'u') goto yy409; if (yych <= 'z') goto yy151; goto yy194; } } } yy409: YYDEBUG(409, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'R') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'S') goto yy399; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'r') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 's') goto yy410; if (yych <= 'z') goto yy152; goto yy4; } } } yy410: YYDEBUG(410, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'T') goto yy400; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 't') goto yy411; if (yych <= 'z') goto yy153; goto yy4; } } } yy411: YYDEBUG(411, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 16) { goto yy154; } if (yych <= ',') { if (yych <= 0x1F) { if (yych == '\t') goto yy196; goto yy194; } else { if (yych <= ' ') goto yy196; if (yych == ')') goto yy140; goto yy194; } } else { if (yych <= '/') { if (yych <= '-') goto yy378; if (yych <= '.') goto yy196; goto yy148; } else { if (yych <= '9') goto yy196; if (yych == '_') goto yy148; goto yy194; } } yy412: YYDEBUG(412, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == 'L') goto yy419; if (yych <= 'M') goto yy142; goto yy418; } } else { if (yych <= 'l') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; if (yych <= 'k') goto yy142; goto yy419; } else { if (yych == 'n') goto yy418; if (yych <= 'z') goto yy142; goto yy4; } } yy413: YYDEBUG(413, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'M') goto yy142; } } else { if (yych <= 'm') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'n') goto yy414; if (yych <= 'z') goto yy142; goto yy4; } } yy414: YYDEBUG(414, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; goto yy194; } else { if (yych <= '-') goto yy197; if (yych <= '.') goto yy196; goto yy194; } } } else { if (yych <= 'Z') { if (yych <= '@') { if (yych <= '9') goto yy196; goto yy194; } else { if (yych != 'U') goto yy143; } } else { if (yych <= 't') { if (yych <= '`') goto yy194; goto yy143; } else { if (yych <= 'u') goto yy415; if (yych <= 'z') goto yy143; goto yy194; } } } yy415: YYDEBUG(415, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; } else { if (yych <= '`') { if (yych <= 'Z') goto yy144; goto yy4; } else { if (yych <= 'a') goto yy416; if (yych <= 'z') goto yy144; goto yy4; } } yy416: YYDEBUG(416, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'Q') goto yy145; } } else { if (yych <= 'q') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'r') goto yy417; if (yych <= 'z') goto yy145; goto yy4; } } yy417: YYDEBUG(417, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'X') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'Y') goto yy206; if (yych == 'y') goto yy206; goto yy4; } yy418: YYDEBUG(418, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; goto yy194; } else { if (yych <= '-') goto yy197; if (yych <= '.') goto yy196; goto yy194; } } } else { if (yych <= 'Z') { if (yych <= '@') { if (yych <= '9') goto yy196; goto yy194; } else { if (yych == 'E') goto yy420; goto yy143; } } else { if (yych <= 'd') { if (yych <= '`') goto yy194; goto yy143; } else { if (yych <= 'e') goto yy420; if (yych <= 'z') goto yy143; goto yy194; } } } yy419: YYDEBUG(419, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; goto yy194; } else { if (yych <= '-') goto yy197; if (yych <= '.') goto yy196; goto yy194; } } } else { if (yych <= 'Z') { if (yych <= '@') { if (yych <= '9') goto yy196; goto yy194; } else { if (yych != 'Y') goto yy143; } } else { if (yych <= 'x') { if (yych <= '`') goto yy194; goto yy143; } else { if (yych <= 'y') goto yy420; if (yych <= 'z') goto yy143; goto yy194; } } } yy420: YYDEBUG(420, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= 0x1F) { if (yych == '\t') goto yy196; goto yy194; } else { if (yych <= ' ') goto yy196; if (yych == ')') goto yy140; goto yy194; } } else { if (yych <= '@') { if (yych == '/') goto yy194; if (yych <= '9') goto yy196; goto yy194; } else { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy194; if (yych <= 'z') goto yy144; goto yy194; } } yy421: YYDEBUG(421, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'M') { if (yych <= '.') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych == '-') goto yy148; goto yy4; } } else { if (yych <= '@') { if (yych <= '/') goto yy148; goto yy4; } else { if (yych == 'L') goto yy419; goto yy142; } } } else { if (yych <= '`') { if (yych <= 'Z') { if (yych <= 'N') goto yy418; goto yy142; } else { if (yych == '_') goto yy148; goto yy4; } } else { if (yych <= 'm') { if (yych == 'l') goto yy428; goto yy147; } else { if (yych <= 'n') goto yy427; if (yych <= 'z') goto yy147; goto yy4; } } } yy422: YYDEBUG(422, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'M') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'N') goto yy414; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'm') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'n') goto yy423; if (yych <= 'z') goto yy147; goto yy4; } } } yy423: YYDEBUG(423, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= '-') { if (yych <= ')') goto yy140; if (yych <= ',') goto yy194; goto yy372; } else { if (yych == '/') goto yy148; goto yy196; } } } else { if (yych <= '^') { if (yych <= 'T') { if (yych <= '@') goto yy194; goto yy143; } else { if (yych <= 'U') goto yy415; if (yych <= 'Z') goto yy143; goto yy194; } } else { if (yych <= 't') { if (yych <= '_') goto yy148; if (yych <= '`') goto yy194; goto yy151; } else { if (yych <= 'u') goto yy424; if (yych <= 'z') goto yy151; goto yy194; } } } yy424: YYDEBUG(424, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '_') { if (yych <= 'A') goto yy416; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'a') goto yy425; if (yych <= 'z') goto yy152; goto yy4; } } yy425: YYDEBUG(425, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'Q') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'R') goto yy417; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'q') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'r') goto yy426; if (yych <= 'z') goto yy153; goto yy4; } } } yy426: YYDEBUG(426, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'X') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'Y') goto yy206; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'y') goto yy377; if (yych <= 'z') goto yy154; goto yy4; } } yy427: YYDEBUG(427, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= '-') { if (yych <= ')') goto yy140; if (yych <= ',') goto yy194; goto yy372; } else { if (yych == '/') goto yy148; goto yy196; } } } else { if (yych <= '^') { if (yych <= 'D') { if (yych <= '@') goto yy194; goto yy143; } else { if (yych <= 'E') goto yy420; if (yych <= 'Z') goto yy143; goto yy194; } } else { if (yych <= 'd') { if (yych <= '_') goto yy148; if (yych <= '`') goto yy194; goto yy151; } else { if (yych <= 'e') goto yy429; if (yych <= 'z') goto yy151; goto yy194; } } } yy428: YYDEBUG(428, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= '-') { if (yych <= ')') goto yy140; if (yych <= ',') goto yy194; goto yy372; } else { if (yych == '/') goto yy148; goto yy196; } } } else { if (yych <= '^') { if (yych <= 'X') { if (yych <= '@') goto yy194; goto yy143; } else { if (yych <= 'Y') goto yy420; if (yych <= 'Z') goto yy143; goto yy194; } } else { if (yych <= 'x') { if (yych <= '_') goto yy148; if (yych <= '`') goto yy194; goto yy151; } else { if (yych <= 'y') goto yy429; if (yych <= 'z') goto yy151; goto yy194; } } } yy429: YYDEBUG(429, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ' ') { if (yych == '\t') goto yy196; if (yych <= 0x1F) goto yy194; goto yy196; } else { if (yych <= ')') { if (yych <= '(') goto yy194; goto yy140; } else { if (yych <= ',') goto yy194; if (yych <= '-') goto yy378; goto yy196; } } } else { if (yych <= 'Z') { if (yych <= '/') goto yy148; if (yych <= '9') goto yy196; if (yych <= '@') goto yy194; goto yy144; } else { if (yych <= '_') { if (yych <= '^') goto yy194; goto yy148; } else { if (yych <= '`') goto yy194; if (yych <= 'z') goto yy152; goto yy194; } } } yy430: YYDEBUG(430, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ' ') { if (yych == '\t') goto yy196; if (yych <= 0x1F) goto yy4; goto yy196; } else { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy196; } } else { if (yych <= 'H') { if (yych <= '/') goto yy4; if (yych <= '9') goto yy196; if (yych <= '@') goto yy4; goto yy142; } else { if (yych <= 'Z') { if (yych >= 'J') goto yy142; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy142; goto yy4; } } } yy431: YYDEBUG(431, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= 0x1F) { if (yych == '\t') goto yy196; goto yy4; } else { if (yych <= ' ') goto yy196; if (yych == ')') goto yy140; goto yy4; } } else { if (yych <= '@') { if (yych == '/') goto yy4; if (yych <= '9') goto yy196; goto yy4; } else { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; if (yych <= 'z') goto yy143; goto yy4; } } yy432: YYDEBUG(432, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ' ') { if (yych == '\t') goto yy196; if (yych <= 0x1F) goto yy4; goto yy196; } else { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy196; } } else { if (yych <= 'H') { if (yych <= '/') goto yy4; if (yych <= '9') goto yy196; if (yych <= '@') goto yy4; goto yy142; } else { if (yych <= 'Z') { if (yych >= 'J') goto yy142; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy142; goto yy4; } } } YYDEBUG(433, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ' ') { if (yych == '\t') goto yy196; if (yych <= 0x1F) goto yy4; goto yy196; } else { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy196; } } else { if (yych <= 'H') { if (yych <= '/') goto yy4; if (yych <= '9') goto yy196; if (yych <= '@') goto yy4; goto yy143; } else { if (yych <= 'Z') { if (yych >= 'J') goto yy143; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy143; goto yy4; } } } YYDEBUG(434, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= 0x1F) { if (yych == '\t') goto yy196; goto yy4; } else { if (yych <= ' ') goto yy196; if (yych == ')') goto yy140; goto yy4; } } else { if (yych <= '@') { if (yych == '/') goto yy4; if (yych <= '9') goto yy196; goto yy4; } else { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; if (yych <= 'z') goto yy144; goto yy4; } } yy435: YYDEBUG(435, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= 0x1F) { if (yych == '\t') goto yy196; goto yy4; } else { if (yych <= ' ') goto yy196; if (yych == ')') goto yy140; goto yy4; } } else { if (yych <= '@') { if (yych == '/') goto yy4; if (yych <= '9') goto yy196; goto yy4; } else { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; if (yych <= 'z') goto yy142; goto yy4; } } yy436: YYDEBUG(436, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ' ') { if (yych == '\t') goto yy196; if (yych <= 0x1F) goto yy4; goto yy196; } else { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy196; } } else { if (yych <= 'H') { if (yych <= '/') goto yy4; if (yych <= '9') goto yy196; if (yych <= '@') goto yy4; goto yy142; } else { if (yych <= 'Z') { if (yych <= 'I') goto yy431; goto yy142; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy142; goto yy4; } } } yy437: YYDEBUG(437, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'V') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy4; goto yy61; } else { if (yych <= '9') { if (yych <= '/') goto yy4; goto yy457; } else { if (yych <= ':') goto yy163; if (yych <= 'C') goto yy4; goto yy61; } } } else { if (yych <= 'H') { if (yych == 'F') goto yy61; if (yych <= 'G') goto yy4; goto yy61; } else { if (yych <= 'M') { if (yych <= 'L') goto yy4; goto yy61; } else { if (yych <= 'R') goto yy4; if (yych <= 'T') goto yy61; goto yy4; } } } } else { if (yych <= 'h') { if (yych <= 'c') { if (yych == 'X') goto yy4; if (yych <= 'Y') goto yy61; goto yy4; } else { if (yych <= 'e') { if (yych <= 'd') goto yy61; goto yy4; } else { if (yych == 'g') goto yy4; goto yy61; } } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych <= 'r') goto yy4; goto yy61; } else { if (yych <= 'w') { if (yych <= 'v') goto yy4; goto yy61; } else { if (yych == 'y') goto yy61; goto yy4; } } } } yy438: YYDEBUG(438, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych <= ':') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy4; goto yy61; } else { if (yych <= '4') { if (yych <= '/') goto yy4; goto yy457; } else { if (yych <= '5') goto yy442; if (yych <= '9') goto yy443; goto yy163; } } } else { if (yych <= 'G') { if (yych <= 'D') { if (yych <= 'C') goto yy4; goto yy61; } else { if (yych == 'F') goto yy61; goto yy4; } } else { if (yych <= 'L') { if (yych <= 'H') goto yy61; goto yy4; } else { if (yych <= 'M') goto yy61; if (yych <= 'R') goto yy4; goto yy61; } } } } else { if (yych <= 'g') { if (yych <= 'Y') { if (yych == 'W') goto yy61; if (yych <= 'X') goto yy4; goto yy61; } else { if (yych <= 'd') { if (yych <= 'c') goto yy4; goto yy61; } else { if (yych == 'f') goto yy61; goto yy4; } } } else { if (yych <= 't') { if (yych <= 'l') { if (yych <= 'h') goto yy61; goto yy4; } else { if (yych <= 'm') goto yy61; if (yych <= 'r') goto yy4; goto yy61; } } else { if (yych <= 'w') { if (yych <= 'v') goto yy4; goto yy61; } else { if (yych == 'y') goto yy61; goto yy4; } } } } yy439: YYDEBUG(439, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych <= 'C') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy4; goto yy61; } else { if (yych <= '5') { if (yych <= '/') goto yy4; goto yy442; } else { if (yych <= '9') goto yy443; if (yych <= ':') goto yy163; goto yy4; } } } else { if (yych <= 'G') { if (yych == 'E') goto yy4; if (yych <= 'F') goto yy61; goto yy4; } else { if (yych <= 'L') { if (yych <= 'H') goto yy61; goto yy4; } else { if (yych <= 'M') goto yy61; if (yych <= 'R') goto yy4; goto yy61; } } } } else { if (yych <= 'g') { if (yych <= 'Y') { if (yych == 'W') goto yy61; if (yych <= 'X') goto yy4; goto yy61; } else { if (yych <= 'd') { if (yych <= 'c') goto yy4; goto yy61; } else { if (yych == 'f') goto yy61; goto yy4; } } } else { if (yych <= 't') { if (yych <= 'l') { if (yych <= 'h') goto yy61; goto yy4; } else { if (yych <= 'm') goto yy61; if (yych <= 'r') goto yy4; goto yy61; } } else { if (yych <= 'w') { if (yych <= 'v') goto yy4; goto yy61; } else { if (yych == 'y') goto yy61; goto yy4; } } } } yy440: YYDEBUG(440, *YYCURSOR); ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; YYDEBUG(441, *YYCURSOR); if (yybm[0+yych] & 4) { goto yy58; } if (yych <= ',') { if (yych == '+') goto yy440; goto yy57; } else { if (yych <= '-') goto yy440; if (yych <= '/') goto yy57; if (yych <= '9') goto yy55; goto yy57; } yy442: YYDEBUG(442, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'V') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy4; goto yy61; } else { if (yych <= '/') goto yy4; if (yych <= '9') goto yy456; if (yych <= 'C') goto yy4; goto yy61; } } else { if (yych <= 'H') { if (yych == 'F') goto yy61; if (yych <= 'G') goto yy4; goto yy61; } else { if (yych <= 'M') { if (yych <= 'L') goto yy4; goto yy61; } else { if (yych <= 'R') goto yy4; if (yych <= 'T') goto yy61; goto yy4; } } } } else { if (yych <= 'h') { if (yych <= 'c') { if (yych == 'X') goto yy4; if (yych <= 'Y') goto yy61; goto yy4; } else { if (yych <= 'e') { if (yych <= 'd') goto yy61; goto yy4; } else { if (yych == 'g') goto yy4; goto yy61; } } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych <= 'r') goto yy4; goto yy61; } else { if (yych <= 'w') { if (yych <= 'v') goto yy4; goto yy61; } else { if (yych == 'y') goto yy61; goto yy4; } } } } yy443: YYDEBUG(443, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'V') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy4; goto yy61; } else { if (yych <= '/') goto yy4; if (yych <= '9') goto yy444; if (yych <= 'C') goto yy4; goto yy61; } } else { if (yych <= 'H') { if (yych == 'F') goto yy61; if (yych <= 'G') goto yy4; goto yy61; } else { if (yych <= 'M') { if (yych <= 'L') goto yy4; goto yy61; } else { if (yych <= 'R') goto yy4; if (yych <= 'T') goto yy61; goto yy4; } } } } else { if (yych <= 'h') { if (yych <= 'c') { if (yych == 'X') goto yy4; if (yych <= 'Y') goto yy61; goto yy4; } else { if (yych <= 'e') { if (yych <= 'd') goto yy61; goto yy4; } else { if (yych == 'g') goto yy4; goto yy61; } } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych <= 'r') goto yy4; goto yy61; } else { if (yych <= 'w') { if (yych <= 'v') goto yy4; goto yy61; } else { if (yych == 'y') goto yy61; goto yy4; } } } } yy444: YYDEBUG(444, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych >= ':') goto yy61; yy445: YYDEBUG(445, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 2) { goto yy55; } if (yych != '-') goto yy61; yy446: YYDEBUG(446, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '0') goto yy447; if (yych <= '1') goto yy448; goto yy57; yy447: YYDEBUG(447, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy449; goto yy57; yy448: YYDEBUG(448, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= '3') goto yy57; yy449: YYDEBUG(449, *YYCURSOR); yych = *++YYCURSOR; if (yych != '-') goto yy57; YYDEBUG(450, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '0') goto yy451; if (yych <= '2') goto yy452; if (yych <= '3') goto yy453; goto yy57; yy451: YYDEBUG(451, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy454; goto yy57; yy452: YYDEBUG(452, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy454; goto yy57; yy453: YYDEBUG(453, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= '2') goto yy57; yy454: YYDEBUG(454, *YYCURSOR); ++YYCURSOR; yy455: YYDEBUG(455, *YYCURSOR); #line 1289 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("iso8601date4 | iso8601date2 | iso8601dateslash | dateslash"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->y = timelib_get_unsigned_nr((char **) &ptr, 4); s->time->m = timelib_get_nr((char **) &ptr, 2); s->time->d = timelib_get_nr((char **) &ptr, 2); TIMELIB_DEINIT; return TIMELIB_ISO_DATE; } #line 9078 "ext/date/lib/parse_date.c" yy456: YYDEBUG(456, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'V') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy4; goto yy61; } else { if (yych <= '/') goto yy4; if (yych <= '9') goto yy445; if (yych <= 'C') goto yy4; goto yy61; } } else { if (yych <= 'H') { if (yych == 'F') goto yy61; if (yych <= 'G') goto yy4; goto yy61; } else { if (yych <= 'M') { if (yych <= 'L') goto yy4; goto yy61; } else { if (yych <= 'R') goto yy4; if (yych <= 'T') goto yy61; goto yy4; } } } } else { if (yych <= 'h') { if (yych <= 'c') { if (yych == 'X') goto yy4; if (yych <= 'Y') goto yy61; goto yy4; } else { if (yych <= 'e') { if (yych <= 'd') goto yy61; goto yy4; } else { if (yych == 'g') goto yy4; goto yy61; } } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych <= 'r') goto yy4; goto yy61; } else { if (yych <= 'w') { if (yych <= 'v') goto yy4; goto yy61; } else { if (yych == 'y') goto yy61; goto yy4; } } } } yy457: YYDEBUG(457, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych <= 'C') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy4; goto yy61; } else { if (yych <= '5') { if (yych <= '/') goto yy4; } else { if (yych <= '9') goto yy456; if (yych <= ':') goto yy163; goto yy4; } } } else { if (yych <= 'G') { if (yych == 'E') goto yy4; if (yych <= 'F') goto yy61; goto yy4; } else { if (yych <= 'L') { if (yych <= 'H') goto yy61; goto yy4; } else { if (yych <= 'M') goto yy61; if (yych <= 'R') goto yy4; goto yy61; } } } } else { if (yych <= 'g') { if (yych <= 'Y') { if (yych == 'W') goto yy61; if (yych <= 'X') goto yy4; goto yy61; } else { if (yych <= 'd') { if (yych <= 'c') goto yy4; goto yy61; } else { if (yych == 'f') goto yy61; goto yy4; } } } else { if (yych <= 't') { if (yych <= 'l') { if (yych <= 'h') goto yy61; goto yy4; } else { if (yych <= 'm') goto yy61; if (yych <= 'r') goto yy4; goto yy61; } } else { if (yych <= 'w') { if (yych <= 'v') goto yy4; goto yy61; } else { if (yych == 'y') goto yy61; goto yy4; } } } } YYDEBUG(458, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'V') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy4; goto yy61; } else { if (yych <= '/') goto yy4; if (yych <= '9') goto yy459; if (yych <= 'C') goto yy4; goto yy61; } } else { if (yych <= 'H') { if (yych == 'F') goto yy61; if (yych <= 'G') goto yy4; goto yy61; } else { if (yych <= 'M') { if (yych <= 'L') goto yy4; goto yy61; } else { if (yych <= 'R') goto yy4; if (yych <= 'T') goto yy61; goto yy4; } } } } else { if (yych <= 'h') { if (yych <= 'c') { if (yych == 'X') goto yy4; if (yych <= 'Y') goto yy61; goto yy4; } else { if (yych <= 'e') { if (yych <= 'd') goto yy61; goto yy4; } else { if (yych == 'g') goto yy4; goto yy61; } } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych <= 'r') goto yy4; goto yy61; } else { if (yych <= 'w') { if (yych <= 'v') goto yy4; goto yy61; } else { if (yych == 'y') goto yy61; goto yy4; } } } } yy459: YYDEBUG(459, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 2) { goto yy55; } if (yych <= 'V') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy4; goto yy61; } else { if (yych == '-') goto yy446; if (yych <= 'C') goto yy4; goto yy61; } } else { if (yych <= 'H') { if (yych == 'F') goto yy61; if (yych <= 'G') goto yy4; goto yy61; } else { if (yych <= 'M') { if (yych <= 'L') goto yy4; goto yy61; } else { if (yych <= 'R') goto yy4; if (yych <= 'T') goto yy61; goto yy4; } } } } else { if (yych <= 'h') { if (yych <= 'c') { if (yych == 'X') goto yy4; if (yych <= 'Y') goto yy61; goto yy4; } else { if (yych <= 'e') { if (yych <= 'd') goto yy61; goto yy4; } else { if (yych == 'g') goto yy4; goto yy61; } } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych <= 'r') goto yy4; goto yy61; } else { if (yych <= 'w') { if (yych <= 'v') goto yy4; goto yy61; } else { if (yych == 'y') goto yy61; goto yy4; } } } } yy460: YYDEBUG(460, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy462; if (yych <= '0') goto yy736; if (yych <= '1') goto yy737; if (yych <= '9') goto yy738; goto yy462; yy461: YYDEBUG(461, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 13) YYFILL(13); yych = *YYCURSOR; yy462: YYDEBUG(462, *YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case '\t': case ' ': goto yy461; case '-': case '.': goto yy577; case 'A': case 'a': goto yy480; case 'D': case 'd': goto yy466; case 'F': case 'f': goto yy467; case 'H': case 'h': goto yy64; case 'I': goto yy475; case 'J': case 'j': goto yy479; case 'M': case 'm': goto yy465; case 'N': case 'n': goto yy482; case 'O': case 'o': goto yy481; case 'P': case 'p': goto yy484; case 'S': case 's': goto yy463; case 'T': case 't': goto yy69; case 'V': goto yy477; case 'W': case 'w': goto yy68; case 'X': goto yy478; case 'Y': case 'y': goto yy67; default: goto yy57; } yy463: YYDEBUG(463, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= 'D') { if (yych == 'A') goto yy127; goto yy57; } else { if (yych <= 'E') goto yy1049; if (yych <= 'T') goto yy57; goto yy126; } } else { if (yych <= 'd') { if (yych == 'a') goto yy127; goto yy57; } else { if (yych <= 'e') goto yy1049; if (yych == 'u') goto yy126; goto yy57; } } yy464: YYDEBUG(464, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '`') { if (yych <= 'D') { if (yych == 'A') goto yy127; goto yy57; } else { if (yych <= 'E') goto yy1049; if (yych == 'U') goto yy126; goto yy57; } } else { if (yych <= 'e') { if (yych <= 'a') goto yy127; if (yych <= 'd') goto yy57; goto yy1049; } else { if (yych <= 's') goto yy57; if (yych <= 't') goto yy729; if (yych <= 'u') goto yy126; goto yy57; } } yy465: YYDEBUG(465, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= 'H') { if (yych == 'A') goto yy592; goto yy57; } else { if (yych <= 'I') goto yy118; if (yych <= 'N') goto yy57; goto yy117; } } else { if (yych <= 'h') { if (yych == 'a') goto yy592; goto yy57; } else { if (yych <= 'i') goto yy118; if (yych == 'o') goto yy117; goto yy57; } } yy466: YYDEBUG(466, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych == 'A') goto yy114; if (yych <= 'D') goto yy57; goto yy579; } else { if (yych <= 'a') { if (yych <= '`') goto yy57; goto yy114; } else { if (yych == 'e') goto yy579; goto yy57; } } yy467: YYDEBUG(467, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= 'N') { if (yych == 'E') goto yy595; goto yy57; } else { if (yych <= 'O') goto yy99; if (yych <= 'Q') goto yy57; goto yy98; } } else { if (yych <= 'n') { if (yych == 'e') goto yy595; goto yy57; } else { if (yych <= 'o') goto yy99; if (yych == 'r') goto yy98; goto yy57; } } yy468: YYDEBUG(468, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'H') goto yy70; if (yych <= 'T') goto yy57; goto yy71; } else { if (yych <= 'h') { if (yych <= 'g') goto yy57; goto yy1048; } else { if (yych == 'u') goto yy71; goto yy57; } } yy469: YYDEBUG(469, *YYCURSOR); yych = *++YYCURSOR; if (yych == '-') goto yy742; if (yych <= '/') goto yy61; if (yych <= '9') goto yy741; goto yy61; yy470: YYDEBUG(470, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'c') { if (yych == 'O') goto yy530; goto yy57; } else { if (yych <= 'd') goto yy729; if (yych == 'o') goto yy530; goto yy57; } yy471: YYDEBUG(471, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'd') goto yy729; goto yy57; yy472: YYDEBUG(472, *YYCURSOR); yych = *++YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case '0': case '1': case '2': goto yy666; case '3': goto yy668; case '4': case '5': case '6': case '7': case '8': case '9': goto yy669; case 'A': case 'a': goto yy673; case 'D': case 'd': goto yy677; case 'F': case 'f': goto yy671; case 'J': case 'j': goto yy670; case 'M': case 'm': goto yy672; case 'N': case 'n': goto yy676; case 'O': case 'o': goto yy675; case 'S': case 's': goto yy674; default: goto yy57; } yy473: YYDEBUG(473, *YYCURSOR); yych = *++YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case '0': goto yy616; case '1': goto yy617; case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy618; case 'A': case 'a': goto yy622; case 'D': case 'd': goto yy626; case 'F': case 'f': goto yy620; case 'J': case 'j': goto yy619; case 'M': case 'm': goto yy621; case 'N': case 'n': goto yy625; case 'O': case 'o': goto yy624; case 'S': case 's': goto yy623; default: goto yy578; } yy474: YYDEBUG(474, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '1') { if (yych <= '/') goto yy578; if (yych <= '0') goto yy568; goto yy569; } else { if (yych <= '5') goto yy570; if (yych <= '9') goto yy571; goto yy578; } yy475: YYDEBUG(475, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; if (yych <= '.') goto yy532; } } else { if (yych <= 'U') { if (yych <= '9') goto yy534; if (yych == 'I') goto yy567; } else { if (yych == 'W') goto yy476; if (yych <= 'X') goto yy540; } } yy476: YYDEBUG(476, *YYCURSOR); #line 1426 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("datenoyearrev"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->d = timelib_get_nr((char **) &ptr, 2); timelib_skip_day_suffix((char **) &ptr); s->time->m = timelib_get_month((char **) &ptr); TIMELIB_DEINIT; return TIMELIB_DATE_TEXT; } #line 9649 "ext/date/lib/parse_date.c" yy477: YYDEBUG(477, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= '\t') { if (yych <= 0x08) goto yy476; goto yy532; } else { if (yych == ' ') goto yy532; goto yy476; } } else { if (yych <= '9') { if (yych <= '.') goto yy532; if (yych <= '/') goto yy476; goto yy534; } else { if (yych == 'I') goto yy565; goto yy476; } } yy478: YYDEBUG(478, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= '\t') { if (yych <= 0x08) goto yy476; goto yy532; } else { if (yych == ' ') goto yy532; goto yy476; } } else { if (yych <= '9') { if (yych <= '.') goto yy532; if (yych <= '/') goto yy476; goto yy534; } else { if (yych == 'I') goto yy564; goto yy476; } } yy479: YYDEBUG(479, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'A') goto yy557; if (yych <= 'T') goto yy57; goto yy556; } else { if (yych <= 'a') { if (yych <= '`') goto yy57; goto yy557; } else { if (yych == 'u') goto yy556; goto yy57; } } yy480: YYDEBUG(480, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= 'L') { if (yych == '.') goto yy485; goto yy57; } else { if (yych <= 'M') goto yy486; if (yych == 'P') goto yy550; goto yy57; } } else { if (yych <= 'o') { if (yych <= 'U') goto yy549; if (yych == 'm') goto yy486; goto yy57; } else { if (yych <= 'p') goto yy550; if (yych == 'u') goto yy549; goto yy57; } } yy481: YYDEBUG(481, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy544; if (yych == 'c') goto yy544; goto yy57; yy482: YYDEBUG(482, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy530; if (yych == 'o') goto yy530; goto yy57; yy483: YYDEBUG(483, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy490; if (yych <= '9') goto yy492; goto yy57; yy484: YYDEBUG(484, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych != '.') goto yy57; } else { if (yych <= 'M') goto yy486; if (yych == 'm') goto yy486; goto yy57; } yy485: YYDEBUG(485, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy486; if (yych != 'm') goto yy57; yy486: YYDEBUG(486, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 0x1F) { if (yych <= 0x00) goto yy488; if (yych == '\t') goto yy488; goto yy57; } else { if (yych <= ' ') goto yy488; if (yych != '.') goto yy57; } YYDEBUG(487, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '\t') { if (yych <= 0x00) goto yy488; if (yych <= 0x08) goto yy57; } else { if (yych != ' ') goto yy57; } yy488: YYDEBUG(488, *YYCURSOR); ++YYCURSOR; YYDEBUG(489, *YYCURSOR); #line 1144 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("timetiny12 | timeshort12 | timelong12"); TIMELIB_INIT; TIMELIB_HAVE_TIME(); s->time->h = timelib_get_nr((char **) &ptr, 2); if (*ptr == ':' || *ptr == '.') { s->time->i = timelib_get_nr((char **) &ptr, 2); if (*ptr == ':' || *ptr == '.') { s->time->s = timelib_get_nr((char **) &ptr, 2); } } s->time->h += timelib_meridian((char **) &ptr, s->time->h); TIMELIB_DEINIT; return TIMELIB_TIME12; } #line 9806 "ext/date/lib/parse_date.c" yy490: YYDEBUG(490, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy493; } else { if (yych <= '9') goto yy507; if (yych <= ':') goto yy493; } yy491: YYDEBUG(491, *YYCURSOR); #line 1181 "ext/date/lib/parse_date.re" { int tz_not_found; DEBUG_OUTPUT("timeshort24 | timelong24 | iso8601long"); TIMELIB_INIT; TIMELIB_HAVE_TIME(); s->time->h = timelib_get_nr((char **) &ptr, 2); s->time->i = timelib_get_nr((char **) &ptr, 2); if (*ptr == ':' || *ptr == '.') { s->time->s = timelib_get_nr((char **) &ptr, 2); if (*ptr == '.') { s->time->f = timelib_get_frac_nr((char **) &ptr, 8); } } if (*ptr != '\0') { s->time->z = timelib_get_zone((char **) &ptr, &s->time->dst, s->time, &tz_not_found, s->tzdb); if (tz_not_found) { add_error(s, "The timezone could not be found in the database"); } } TIMELIB_DEINIT; return TIMELIB_TIME24_WITH_ZONE; } #line 9844 "ext/date/lib/parse_date.c" yy492: YYDEBUG(492, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy493; if (yych != ':') goto yy491; yy493: YYDEBUG(493, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy494; if (yych <= '6') goto yy495; if (yych <= '9') goto yy496; goto yy57; yy494: YYDEBUG(494, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy497; if (yych <= '/') goto yy491; if (yych <= '9') goto yy500; goto yy491; yy495: YYDEBUG(495, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy497; if (yych == '0') goto yy500; goto yy491; yy496: YYDEBUG(496, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych != '.') goto yy491; yy497: YYDEBUG(497, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; yy498: YYDEBUG(498, *YYCURSOR); ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; YYDEBUG(499, *YYCURSOR); if (yych <= '/') goto yy491; if (yych <= '9') goto yy498; goto yy491; yy500: YYDEBUG(500, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych <= 0x1F) { if (yych != '\t') goto yy491; } else { if (yych <= ' ') goto yy501; if (yych == '.') goto yy497; goto yy491; } } else { if (yych <= '`') { if (yych <= 'A') goto yy503; if (yych == 'P') goto yy503; goto yy491; } else { if (yych <= 'a') goto yy503; if (yych == 'p') goto yy503; goto yy491; } } yy501: YYDEBUG(501, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 5) YYFILL(5); yych = *YYCURSOR; YYDEBUG(502, *YYCURSOR); if (yych <= 'A') { if (yych <= 0x1F) { if (yych == '\t') goto yy501; goto yy57; } else { if (yych <= ' ') goto yy501; if (yych <= '@') goto yy57; } } else { if (yych <= '`') { if (yych != 'P') goto yy57; } else { if (yych <= 'a') goto yy503; if (yych != 'p') goto yy57; } } yy503: YYDEBUG(503, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych != '.') goto yy57; } else { if (yych <= 'M') goto yy505; if (yych == 'm') goto yy505; goto yy57; } YYDEBUG(504, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy505; if (yych != 'm') goto yy57; yy505: YYDEBUG(505, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 0x1F) { if (yych <= 0x00) goto yy488; if (yych == '\t') goto yy488; goto yy57; } else { if (yych <= ' ') goto yy488; if (yych != '.') goto yy57; } YYDEBUG(506, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '\t') { if (yych <= 0x00) goto yy488; if (yych <= 0x08) goto yy57; goto yy488; } else { if (yych == ' ') goto yy488; goto yy57; } yy507: YYDEBUG(507, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ':') { if (yych <= ' ') { if (yych == '\t') goto yy508; if (yych <= 0x1F) goto yy491; } else { if (yych == '.') goto yy493; if (yych <= '9') goto yy491; goto yy511; } } else { if (yych <= 'P') { if (yych == 'A') goto yy510; if (yych <= 'O') goto yy491; goto yy510; } else { if (yych <= 'a') { if (yych <= '`') goto yy491; goto yy510; } else { if (yych == 'p') goto yy510; goto yy491; } } } yy508: YYDEBUG(508, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 5) YYFILL(5); yych = *YYCURSOR; YYDEBUG(509, *YYCURSOR); if (yych <= 'A') { if (yych <= 0x1F) { if (yych == '\t') goto yy508; goto yy57; } else { if (yych <= ' ') goto yy508; if (yych <= '@') goto yy57; } } else { if (yych <= '`') { if (yych != 'P') goto yy57; } else { if (yych <= 'a') goto yy510; if (yych != 'p') goto yy57; } } yy510: YYDEBUG(510, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych == '.') goto yy527; goto yy57; } else { if (yych <= 'M') goto yy528; if (yych == 'm') goto yy528; goto yy57; } yy511: YYDEBUG(511, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy512; if (yych <= '6') goto yy513; if (yych <= '9') goto yy496; goto yy57; yy512: YYDEBUG(512, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy497; if (yych <= '/') goto yy491; if (yych <= '9') goto yy514; goto yy491; yy513: YYDEBUG(513, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy497; if (yych != '0') goto yy491; yy514: YYDEBUG(514, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ':') { if (yych <= ' ') { if (yych == '\t') goto yy501; if (yych <= 0x1F) goto yy491; goto yy501; } else { if (yych == '.') goto yy515; if (yych <= '9') goto yy491; goto yy516; } } else { if (yych <= 'P') { if (yych == 'A') goto yy503; if (yych <= 'O') goto yy491; goto yy503; } else { if (yych <= 'a') { if (yych <= '`') goto yy491; goto yy503; } else { if (yych == 'p') goto yy503; goto yy491; } } } yy515: YYDEBUG(515, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy525; goto yy57; yy516: YYDEBUG(516, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; yy517: YYDEBUG(517, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 5) YYFILL(5); yych = *YYCURSOR; YYDEBUG(518, *YYCURSOR); if (yych <= 'O') { if (yych <= '9') { if (yych <= '/') goto yy57; goto yy517; } else { if (yych != 'A') goto yy57; } } else { if (yych <= 'a') { if (yych <= 'P') goto yy519; if (yych <= '`') goto yy57; } else { if (yych != 'p') goto yy57; } } yy519: YYDEBUG(519, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych != '.') goto yy57; } else { if (yych <= 'M') goto yy521; if (yych == 'm') goto yy521; goto yy57; } YYDEBUG(520, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy521; if (yych != 'm') goto yy57; yy521: YYDEBUG(521, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 0x1F) { if (yych <= 0x00) goto yy523; if (yych == '\t') goto yy523; goto yy57; } else { if (yych <= ' ') goto yy523; if (yych != '.') goto yy57; } YYDEBUG(522, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '\t') { if (yych <= 0x00) goto yy523; if (yych <= 0x08) goto yy57; } else { if (yych != ' ') goto yy57; } yy523: YYDEBUG(523, *YYCURSOR); ++YYCURSOR; YYDEBUG(524, *YYCURSOR); #line 1161 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("mssqltime"); TIMELIB_INIT; TIMELIB_HAVE_TIME(); s->time->h = timelib_get_nr((char **) &ptr, 2); s->time->i = timelib_get_nr((char **) &ptr, 2); if (*ptr == ':' || *ptr == '.') { s->time->s = timelib_get_nr((char **) &ptr, 2); if (*ptr == ':' || *ptr == '.') { s->time->f = timelib_get_frac_nr((char **) &ptr, 8); } } timelib_eat_spaces((char **) &ptr); s->time->h += timelib_meridian((char **) &ptr, s->time->h); TIMELIB_DEINIT; return TIMELIB_TIME24_WITH_ZONE; } #line 10173 "ext/date/lib/parse_date.c" yy525: YYDEBUG(525, *YYCURSOR); yyaccept = 11; YYMARKER = ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 5) YYFILL(5); yych = *YYCURSOR; YYDEBUG(526, *YYCURSOR); if (yych <= 'O') { if (yych <= '9') { if (yych <= '/') goto yy491; goto yy525; } else { if (yych == 'A') goto yy519; goto yy491; } } else { if (yych <= 'a') { if (yych <= 'P') goto yy519; if (yych <= '`') goto yy491; goto yy519; } else { if (yych == 'p') goto yy519; goto yy491; } } yy527: YYDEBUG(527, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy528; if (yych != 'm') goto yy57; yy528: YYDEBUG(528, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 0x1F) { if (yych <= 0x00) goto yy488; if (yych == '\t') goto yy488; goto yy57; } else { if (yych <= ' ') goto yy488; if (yych != '.') goto yy57; } YYDEBUG(529, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '\t') { if (yych <= 0x00) goto yy488; if (yych <= 0x08) goto yy57; goto yy488; } else { if (yych == ' ') goto yy488; goto yy57; } yy530: YYDEBUG(530, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'V') goto yy531; if (yych != 'v') goto yy57; yy531: YYDEBUG(531, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych != '\t') goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; } } else { if (yych <= 'D') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'E') goto yy536; if (yych == 'e') goto yy536; goto yy476; } } yy532: YYDEBUG(532, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4); yych = *YYCURSOR; yy533: YYDEBUG(533, *YYCURSOR); if (yych <= ' ') { if (yych == '\t') goto yy532; if (yych <= 0x1F) goto yy57; goto yy532; } else { if (yych <= '.') { if (yych <= ',') goto yy57; goto yy532; } else { if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; } } yy534: YYDEBUG(534, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '/') goto yy535; if (yych <= '9') goto yy541; yy535: YYDEBUG(535, *YYCURSOR); #line 1343 "ext/date/lib/parse_date.re" { int length = 0; DEBUG_OUTPUT("datefull"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->d = timelib_get_nr((char **) &ptr, 2); timelib_skip_day_suffix((char **) &ptr); s->time->m = timelib_get_month((char **) &ptr); s->time->y = timelib_get_nr_ex((char **) &ptr, 4, &length); TIMELIB_PROCESS_YEAR(s->time->y, length); TIMELIB_DEINIT; return TIMELIB_DATE_FULL; } #line 10293 "ext/date/lib/parse_date.c" yy536: YYDEBUG(536, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy537; if (yych != 'm') goto yy57; yy537: YYDEBUG(537, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy538; if (yych != 'b') goto yy57; yy538: YYDEBUG(538, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy539; if (yych != 'e') goto yy57; yy539: YYDEBUG(539, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy540; if (yych != 'r') goto yy57; yy540: YYDEBUG(540, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ' ') { if (yych == '\t') goto yy532; if (yych <= 0x1F) goto yy476; goto yy532; } else { if (yych <= '.') { if (yych <= ',') goto yy476; goto yy532; } else { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } } yy541: YYDEBUG(541, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy535; if (yych >= ':') goto yy535; yy542: YYDEBUG(542, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy535; if (yych >= ':') goto yy535; YYDEBUG(543, *YYCURSOR); yych = *++YYCURSOR; goto yy535; yy544: YYDEBUG(544, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy545; if (yych != 't') goto yy57; yy545: YYDEBUG(545, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; goto yy532; } } else { if (yych <= 'N') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'O') goto yy546; if (yych != 'o') goto yy476; } } yy546: YYDEBUG(546, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy547; if (yych != 'b') goto yy57; yy547: YYDEBUG(547, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy548; if (yych != 'e') goto yy57; yy548: YYDEBUG(548, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy540; if (yych == 'r') goto yy540; goto yy57; yy549: YYDEBUG(549, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy553; if (yych == 'g') goto yy553; goto yy57; yy550: YYDEBUG(550, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy551; if (yych != 'r') goto yy57; yy551: YYDEBUG(551, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; goto yy532; } } else { if (yych <= 'H') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'I') goto yy552; if (yych != 'i') goto yy476; } } yy552: YYDEBUG(552, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy540; if (yych == 'l') goto yy540; goto yy57; yy553: YYDEBUG(553, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; goto yy532; } } else { if (yych <= 'T') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'U') goto yy554; if (yych != 'u') goto yy476; } } yy554: YYDEBUG(554, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy555; if (yych != 's') goto yy57; yy555: YYDEBUG(555, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy540; if (yych == 't') goto yy540; goto yy57; yy556: YYDEBUG(556, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych == 'L') goto yy563; if (yych <= 'M') goto yy57; goto yy562; } else { if (yych <= 'l') { if (yych <= 'k') goto yy57; goto yy563; } else { if (yych == 'n') goto yy562; goto yy57; } } yy557: YYDEBUG(557, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy558; if (yych != 'n') goto yy57; yy558: YYDEBUG(558, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; goto yy532; } } else { if (yych <= 'T') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'U') goto yy559; if (yych != 'u') goto yy476; } } yy559: YYDEBUG(559, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy560; if (yych != 'a') goto yy57; yy560: YYDEBUG(560, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy561; if (yych != 'r') goto yy57; yy561: YYDEBUG(561, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy540; if (yych == 'y') goto yy540; goto yy57; yy562: YYDEBUG(562, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; goto yy532; } } else { if (yych <= 'D') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'E') goto yy540; if (yych == 'e') goto yy540; goto yy476; } } yy563: YYDEBUG(563, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; goto yy532; } } else { if (yych <= 'X') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'Y') goto yy540; if (yych == 'y') goto yy540; goto yy476; } } yy564: YYDEBUG(564, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= '\t') { if (yych <= 0x08) goto yy476; goto yy532; } else { if (yych == ' ') goto yy532; goto yy476; } } else { if (yych <= '9') { if (yych <= '.') goto yy532; if (yych <= '/') goto yy476; goto yy534; } else { if (yych == 'I') goto yy540; goto yy476; } } yy565: YYDEBUG(565, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= '\t') { if (yych <= 0x08) goto yy476; goto yy532; } else { if (yych == ' ') goto yy532; goto yy476; } } else { if (yych <= '9') { if (yych <= '.') goto yy532; if (yych <= '/') goto yy476; goto yy534; } else { if (yych != 'I') goto yy476; } } YYDEBUG(566, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= '\t') { if (yych <= 0x08) goto yy476; goto yy532; } else { if (yych == ' ') goto yy532; goto yy476; } } else { if (yych <= '9') { if (yych <= '.') goto yy532; if (yych <= '/') goto yy476; goto yy534; } else { if (yych == 'I') goto yy540; goto yy476; } } yy567: YYDEBUG(567, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= '\t') { if (yych <= 0x08) goto yy476; goto yy532; } else { if (yych == ' ') goto yy532; goto yy476; } } else { if (yych <= '9') { if (yych <= '.') goto yy532; if (yych <= '/') goto yy476; goto yy534; } else { if (yych == 'I') goto yy540; goto yy476; } } yy568: YYDEBUG(568, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ',') goto yy491; if (yych <= '-') goto yy602; goto yy601; } else { if (yych <= '/') goto yy491; if (yych <= '9') goto yy615; if (yych <= ':') goto yy493; goto yy491; } yy569: YYDEBUG(569, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') goto yy491; if (yych <= '-') goto yy602; if (yych <= '.') goto yy601; goto yy491; } else { if (yych <= '2') goto yy615; if (yych <= '9') goto yy614; if (yych <= ':') goto yy493; goto yy491; } yy570: YYDEBUG(570, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ',') goto yy491; if (yych <= '-') goto yy602; goto yy601; } else { if (yych <= '/') goto yy491; if (yych <= '9') goto yy614; if (yych <= ':') goto yy493; goto yy491; } yy571: YYDEBUG(571, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ',') goto yy491; if (yych <= '-') goto yy602; goto yy601; } else { if (yych == ':') goto yy493; goto yy491; } yy572: YYDEBUG(572, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy595; if (yych == 'e') goto yy595; goto yy57; yy573: YYDEBUG(573, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy592; if (yych == 'a') goto yy592; goto yy57; yy574: YYDEBUG(574, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'P') goto yy550; if (yych <= 'T') goto yy57; goto yy549; } else { if (yych <= 'p') { if (yych <= 'o') goto yy57; goto yy550; } else { if (yych == 'u') goto yy549; goto yy57; } } yy575: YYDEBUG(575, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy585; if (yych == 'e') goto yy585; goto yy57; yy576: YYDEBUG(576, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy579; if (yych == 'e') goto yy579; goto yy57; yy577: YYDEBUG(577, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 13) YYFILL(13); yych = *YYCURSOR; yy578: YYDEBUG(578, *YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case '\t': case ' ': case '-': case '.': goto yy577; case 'A': case 'a': goto yy574; case 'D': case 'd': goto yy576; case 'F': case 'f': goto yy572; case 'I': goto yy475; case 'J': case 'j': goto yy479; case 'M': case 'm': goto yy573; case 'N': case 'n': goto yy482; case 'O': case 'o': goto yy481; case 'S': case 's': goto yy575; case 'V': goto yy477; case 'X': goto yy478; default: goto yy57; } yy579: YYDEBUG(579, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy580; if (yych != 'c') goto yy57; yy580: YYDEBUG(580, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; goto yy532; } } else { if (yych <= 'D') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'E') goto yy581; if (yych != 'e') goto yy476; } } yy581: YYDEBUG(581, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy582; if (yych != 'm') goto yy57; yy582: YYDEBUG(582, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy583; if (yych != 'b') goto yy57; yy583: YYDEBUG(583, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy584; if (yych != 'e') goto yy57; yy584: YYDEBUG(584, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy540; if (yych == 'r') goto yy540; goto yy57; yy585: YYDEBUG(585, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy586; if (yych != 'p') goto yy57; yy586: YYDEBUG(586, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; goto yy532; } } else { if (yych <= 'S') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'T') goto yy587; if (yych != 't') goto yy476; } } yy587: YYDEBUG(587, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; goto yy532; } } else { if (yych <= 'D') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'E') goto yy588; if (yych != 'e') goto yy476; } } yy588: YYDEBUG(588, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy589; if (yych != 'm') goto yy57; yy589: YYDEBUG(589, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy590; if (yych != 'b') goto yy57; yy590: YYDEBUG(590, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy591; if (yych != 'e') goto yy57; yy591: YYDEBUG(591, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy540; if (yych == 'r') goto yy540; goto yy57; yy592: YYDEBUG(592, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych == 'R') goto yy593; if (yych <= 'X') goto yy57; goto yy540; } else { if (yych <= 'r') { if (yych <= 'q') goto yy57; } else { if (yych == 'y') goto yy540; goto yy57; } } yy593: YYDEBUG(593, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; goto yy532; } } else { if (yych <= 'B') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'C') goto yy594; if (yych != 'c') goto yy476; } } yy594: YYDEBUG(594, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy540; if (yych == 'h') goto yy540; goto yy57; yy595: YYDEBUG(595, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy596; if (yych != 'b') goto yy57; yy596: YYDEBUG(596, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; goto yy532; } } else { if (yych <= 'Q') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'R') goto yy597; if (yych != 'r') goto yy476; } } yy597: YYDEBUG(597, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy598; if (yych != 'u') goto yy57; yy598: YYDEBUG(598, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy599; if (yych != 'a') goto yy57; yy599: YYDEBUG(599, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy600; if (yych != 'r') goto yy57; yy600: YYDEBUG(600, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy540; if (yych == 'y') goto yy540; goto yy57; yy601: YYDEBUG(601, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy608; if (yych <= '6') goto yy609; if (yych <= '9') goto yy610; goto yy57; yy602: YYDEBUG(602, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; YYDEBUG(603, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; yy604: YYDEBUG(604, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; yy605: YYDEBUG(605, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; YYDEBUG(606, *YYCURSOR); ++YYCURSOR; YYDEBUG(607, *YYCURSOR); #line 1358 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("pointed date YYYY"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->d = timelib_get_nr((char **) &ptr, 2); s->time->m = timelib_get_nr((char **) &ptr, 2); s->time->y = timelib_get_nr((char **) &ptr, 4); TIMELIB_DEINIT; return TIMELIB_DATE_FULL_POINTED; } #line 11041 "ext/date/lib/parse_date.c" yy608: YYDEBUG(608, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy497; if (yych <= '/') goto yy491; if (yych <= '9') goto yy613; goto yy491; yy609: YYDEBUG(609, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy497; goto yy491; } else { if (yych <= '0') goto yy613; if (yych <= '9') goto yy611; goto yy491; } yy610: YYDEBUG(610, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy497; if (yych <= '/') goto yy491; if (yych >= ':') goto yy491; yy611: YYDEBUG(611, *YYCURSOR); yyaccept = 12; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') goto yy612; if (yych <= '9') goto yy605; yy612: YYDEBUG(612, *YYCURSOR); #line 1370 "ext/date/lib/parse_date.re" { int length = 0; DEBUG_OUTPUT("pointed date YY"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->d = timelib_get_nr((char **) &ptr, 2); s->time->m = timelib_get_nr((char **) &ptr, 2); s->time->y = timelib_get_nr_ex((char **) &ptr, 2, &length); TIMELIB_PROCESS_YEAR(s->time->y, length); TIMELIB_DEINIT; return TIMELIB_DATE_FULL_POINTED; } #line 11090 "ext/date/lib/parse_date.c" yy613: YYDEBUG(613, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= ' ') { if (yych == '\t') goto yy501; if (yych <= 0x1F) goto yy491; goto yy501; } else { if (yych == '.') goto yy497; if (yych <= '/') goto yy491; goto yy605; } } else { if (yych <= 'P') { if (yych == 'A') goto yy503; if (yych <= 'O') goto yy491; goto yy503; } else { if (yych <= 'a') { if (yych <= '`') goto yy491; goto yy503; } else { if (yych == 'p') goto yy503; goto yy491; } } } yy614: YYDEBUG(614, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ':') { if (yych <= ' ') { if (yych == '\t') goto yy508; if (yych <= 0x1F) goto yy491; goto yy508; } else { if (yych == '.') goto yy493; if (yych <= '9') goto yy491; goto yy493; } } else { if (yych <= 'P') { if (yych == 'A') goto yy510; if (yych <= 'O') goto yy491; goto yy510; } else { if (yych <= 'a') { if (yych <= '`') goto yy491; goto yy510; } else { if (yych == 'p') goto yy510; goto yy491; } } } yy615: YYDEBUG(615, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ':') { if (yych <= ' ') { if (yych == '\t') goto yy508; if (yych <= 0x1F) goto yy491; goto yy508; } else { if (yych <= '-') { if (yych <= ',') goto yy491; goto yy602; } else { if (yych <= '.') goto yy601; if (yych <= '9') goto yy491; goto yy493; } } } else { if (yych <= 'P') { if (yych == 'A') goto yy510; if (yych <= 'O') goto yy491; goto yy510; } else { if (yych <= 'a') { if (yych <= '`') goto yy491; goto yy510; } else { if (yych == 'p') goto yy510; goto yy491; } } } yy616: YYDEBUG(616, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '.') { if (yych <= ',') goto yy57; if (yych <= '-') goto yy655; goto yy602; } else { if (yych <= '/') goto yy57; if (yych <= '9') goto yy618; goto yy57; } yy617: YYDEBUG(617, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '.') { if (yych <= ',') goto yy57; if (yych <= '-') goto yy655; goto yy602; } else { if (yych <= '/') goto yy57; if (yych >= '3') goto yy57; } yy618: YYDEBUG(618, *YYCURSOR); yych = *++YYCURSOR; if (yych <= ',') goto yy57; if (yych <= '-') goto yy655; if (yych <= '.') goto yy602; goto yy57; yy619: YYDEBUG(619, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'A') goto yy651; if (yych <= 'T') goto yy57; goto yy650; } else { if (yych <= 'a') { if (yych <= '`') goto yy57; goto yy651; } else { if (yych == 'u') goto yy650; goto yy57; } } yy620: YYDEBUG(620, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy648; if (yych == 'e') goto yy648; goto yy57; yy621: YYDEBUG(621, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy645; if (yych == 'a') goto yy645; goto yy57; yy622: YYDEBUG(622, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'P') goto yy642; if (yych <= 'T') goto yy57; goto yy641; } else { if (yych <= 'p') { if (yych <= 'o') goto yy57; goto yy642; } else { if (yych == 'u') goto yy641; goto yy57; } } yy623: YYDEBUG(623, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy638; if (yych == 'e') goto yy638; goto yy57; yy624: YYDEBUG(624, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy636; if (yych == 'c') goto yy636; goto yy57; yy625: YYDEBUG(625, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy634; if (yych == 'o') goto yy634; goto yy57; yy626: YYDEBUG(626, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy627; if (yych != 'e') goto yy57; yy627: YYDEBUG(627, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy628; if (yych != 'c') goto yy57; yy628: YYDEBUG(628, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; if (yych >= '.') goto yy532; } } else { if (yych <= 'D') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'E') goto yy581; if (yych == 'e') goto yy581; goto yy476; } } yy629: YYDEBUG(629, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy533; if (yych <= '0') goto yy630; if (yych <= '2') goto yy631; if (yych <= '3') goto yy632; goto yy533; yy630: YYDEBUG(630, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy535; if (yych <= '9') goto yy633; goto yy535; yy631: YYDEBUG(631, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy535; if (yych <= '9') goto yy633; goto yy535; yy632: YYDEBUG(632, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy535; if (yych <= '1') goto yy633; if (yych <= '9') goto yy541; goto yy535; yy633: YYDEBUG(633, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy535; if (yych <= '9') goto yy542; goto yy535; yy634: YYDEBUG(634, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'V') goto yy635; if (yych != 'v') goto yy57; yy635: YYDEBUG(635, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; if (yych <= '-') goto yy629; goto yy532; } } else { if (yych <= 'D') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'E') goto yy536; if (yych == 'e') goto yy536; goto yy476; } } yy636: YYDEBUG(636, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy637; if (yych != 't') goto yy57; yy637: YYDEBUG(637, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; if (yych <= '-') goto yy629; goto yy532; } } else { if (yych <= 'N') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'O') goto yy546; if (yych == 'o') goto yy546; goto yy476; } } yy638: YYDEBUG(638, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy639; if (yych != 'p') goto yy57; yy639: YYDEBUG(639, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; if (yych <= '-') goto yy629; goto yy532; } } else { if (yych <= 'S') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'T') goto yy640; if (yych != 't') goto yy476; } } yy640: YYDEBUG(640, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; if (yych <= '-') goto yy629; goto yy532; } } else { if (yych <= 'D') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'E') goto yy588; if (yych == 'e') goto yy588; goto yy476; } } yy641: YYDEBUG(641, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy644; if (yych == 'g') goto yy644; goto yy57; yy642: YYDEBUG(642, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy643; if (yych != 'r') goto yy57; yy643: YYDEBUG(643, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; if (yych <= '-') goto yy629; goto yy532; } } else { if (yych <= 'H') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'I') goto yy552; if (yych == 'i') goto yy552; goto yy476; } } yy644: YYDEBUG(644, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; if (yych <= '-') goto yy629; goto yy532; } } else { if (yych <= 'T') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'U') goto yy554; if (yych == 'u') goto yy554; goto yy476; } } yy645: YYDEBUG(645, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych == 'R') goto yy646; if (yych <= 'X') goto yy57; goto yy647; } else { if (yych <= 'r') { if (yych <= 'q') goto yy57; } else { if (yych == 'y') goto yy647; goto yy57; } } yy646: YYDEBUG(646, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; if (yych <= '-') goto yy629; goto yy532; } } else { if (yych <= 'B') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'C') goto yy594; if (yych == 'c') goto yy594; goto yy476; } } yy647: YYDEBUG(647, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ',') { if (yych <= '\t') { if (yych <= 0x08) goto yy476; goto yy532; } else { if (yych == ' ') goto yy532; goto yy476; } } else { if (yych <= '.') { if (yych <= '-') goto yy629; goto yy532; } else { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } } yy648: YYDEBUG(648, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy649; if (yych != 'b') goto yy57; yy649: YYDEBUG(649, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; if (yych <= '-') goto yy629; goto yy532; } } else { if (yych <= 'Q') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'R') goto yy597; if (yych == 'r') goto yy597; goto yy476; } } yy650: YYDEBUG(650, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych == 'L') goto yy654; if (yych <= 'M') goto yy57; goto yy653; } else { if (yych <= 'l') { if (yych <= 'k') goto yy57; goto yy654; } else { if (yych == 'n') goto yy653; goto yy57; } } yy651: YYDEBUG(651, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy652; if (yych != 'n') goto yy57; yy652: YYDEBUG(652, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; if (yych <= '-') goto yy629; goto yy532; } } else { if (yych <= 'T') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'U') goto yy559; if (yych == 'u') goto yy559; goto yy476; } } yy653: YYDEBUG(653, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; if (yych <= '-') goto yy629; goto yy532; } } else { if (yych <= 'D') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'E') goto yy540; if (yych == 'e') goto yy540; goto yy476; } } yy654: YYDEBUG(654, *YYCURSOR); yyaccept = 10; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= 0x1F) { if (yych == '\t') goto yy532; goto yy476; } else { if (yych <= ' ') goto yy532; if (yych <= ',') goto yy476; if (yych <= '-') goto yy629; goto yy532; } } else { if (yych <= 'X') { if (yych <= '/') goto yy476; if (yych <= '9') goto yy534; goto yy476; } else { if (yych <= 'Y') goto yy540; if (yych == 'y') goto yy540; goto yy476; } } yy655: YYDEBUG(655, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '2') goto yy656; if (yych <= '3') goto yy658; if (yych <= '9') goto yy659; goto yy57; yy656: YYDEBUG(656, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy657; if (yych <= '9') goto yy665; if (yych >= 'n') goto yy661; } else { if (yych <= 'r') { if (yych >= 'r') goto yy662; } else { if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; } } yy657: YYDEBUG(657, *YYCURSOR); #line 1329 "ext/date/lib/parse_date.re" { int length = 0; DEBUG_OUTPUT("gnudateshort"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->y = timelib_get_nr_ex((char **) &ptr, 4, &length); s->time->m = timelib_get_nr((char **) &ptr, 2); s->time->d = timelib_get_nr((char **) &ptr, 2); TIMELIB_PROCESS_YEAR(s->time->y, length); TIMELIB_DEINIT; return TIMELIB_ISO_DATE; } #line 11744 "ext/date/lib/parse_date.c" yy658: YYDEBUG(658, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '1') { if (yych <= '/') goto yy657; goto yy665; } else { if (yych <= '9') goto yy604; if (yych <= 'm') goto yy657; goto yy661; } } else { if (yych <= 'r') { if (yych <= 'q') goto yy657; goto yy662; } else { if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; goto yy657; } } yy659: YYDEBUG(659, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy657; if (yych <= '9') goto yy604; if (yych <= 'm') goto yy657; goto yy661; } else { if (yych <= 'r') { if (yych <= 'q') goto yy657; goto yy662; } else { if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; goto yy657; } } yy660: YYDEBUG(660, *YYCURSOR); yych = *++YYCURSOR; if (yych == 't') goto yy664; goto yy57; yy661: YYDEBUG(661, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'd') goto yy664; goto yy57; yy662: YYDEBUG(662, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'd') goto yy664; goto yy57; yy663: YYDEBUG(663, *YYCURSOR); yych = *++YYCURSOR; if (yych != 'h') goto yy57; yy664: YYDEBUG(664, *YYCURSOR); yych = *++YYCURSOR; goto yy657; yy665: YYDEBUG(665, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy657; if (yych <= '9') goto yy605; if (yych <= 'm') goto yy657; goto yy661; } else { if (yych <= 'r') { if (yych <= 'q') goto yy657; goto yy662; } else { if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; goto yy657; } } yy666: YYDEBUG(666, *YYCURSOR); yyaccept = 14; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') { if (yych >= '/') goto yy723; } else { if (yych <= '9') goto yy669; if (yych >= 'n') goto yy720; } } else { if (yych <= 'r') { if (yych >= 'r') goto yy721; } else { if (yych <= 's') goto yy719; if (yych <= 't') goto yy722; } } yy667: YYDEBUG(667, *YYCURSOR); #line 1273 "ext/date/lib/parse_date.re" { int length = 0; DEBUG_OUTPUT("americanshort | american"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->m = timelib_get_nr((char **) &ptr, 2); s->time->d = timelib_get_nr((char **) &ptr, 2); if (*ptr == '/') { s->time->y = timelib_get_nr_ex((char **) &ptr, 4, &length); TIMELIB_PROCESS_YEAR(s->time->y, length); } TIMELIB_DEINIT; return TIMELIB_AMERICAN; } #line 11865 "ext/date/lib/parse_date.c" yy668: YYDEBUG(668, *YYCURSOR); yyaccept = 14; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') { if (yych <= '.') goto yy667; goto yy723; } else { if (yych <= '1') goto yy669; if (yych <= 'm') goto yy667; goto yy720; } } else { if (yych <= 'r') { if (yych <= 'q') goto yy667; goto yy721; } else { if (yych <= 's') goto yy719; if (yych <= 't') goto yy722; goto yy667; } } yy669: YYDEBUG(669, *YYCURSOR); yyaccept = 14; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych == '/') goto yy723; if (yych <= 'm') goto yy667; goto yy720; } else { if (yych <= 'r') { if (yych <= 'q') goto yy667; goto yy721; } else { if (yych <= 's') goto yy719; if (yych <= 't') goto yy722; goto yy667; } } yy670: YYDEBUG(670, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'A') goto yy718; if (yych <= 'T') goto yy57; goto yy717; } else { if (yych <= 'a') { if (yych <= '`') goto yy57; goto yy718; } else { if (yych == 'u') goto yy717; goto yy57; } } yy671: YYDEBUG(671, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy716; if (yych == 'e') goto yy716; goto yy57; yy672: YYDEBUG(672, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy715; if (yych == 'a') goto yy715; goto yy57; yy673: YYDEBUG(673, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'P') goto yy714; if (yych <= 'T') goto yy57; goto yy713; } else { if (yych <= 'p') { if (yych <= 'o') goto yy57; goto yy714; } else { if (yych == 'u') goto yy713; goto yy57; } } yy674: YYDEBUG(674, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy711; if (yych == 'e') goto yy711; goto yy57; yy675: YYDEBUG(675, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy710; if (yych == 'c') goto yy710; goto yy57; yy676: YYDEBUG(676, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy709; if (yych == 'o') goto yy709; goto yy57; yy677: YYDEBUG(677, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy678; if (yych != 'e') goto yy57; yy678: YYDEBUG(678, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy679; if (yych != 'c') goto yy57; yy679: YYDEBUG(679, *YYCURSOR); yych = *++YYCURSOR; if (yych != '/') goto yy57; yy680: YYDEBUG(680, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; YYDEBUG(681, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; YYDEBUG(682, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; YYDEBUG(683, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; YYDEBUG(684, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy57; YYDEBUG(685, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '1') goto yy686; if (yych <= '2') goto yy687; goto yy57; yy686: YYDEBUG(686, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy688; goto yy57; yy687: YYDEBUG(687, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= '5') goto yy57; yy688: YYDEBUG(688, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy57; YYDEBUG(689, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= '6') goto yy57; YYDEBUG(690, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; YYDEBUG(691, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy57; YYDEBUG(692, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy693; if (yych <= '6') goto yy694; goto yy57; yy693: YYDEBUG(693, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy695; goto yy57; yy694: YYDEBUG(694, *YYCURSOR); yych = *++YYCURSOR; if (yych != '0') goto yy57; yy695: YYDEBUG(695, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\t') goto yy696; if (yych != ' ') goto yy57; yy696: YYDEBUG(696, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 9) YYFILL(9); yych = *YYCURSOR; YYDEBUG(697, *YYCURSOR); if (yych <= '*') { if (yych <= '\t') { if (yych <= 0x08) goto yy57; goto yy696; } else { if (yych == ' ') goto yy696; goto yy57; } } else { if (yych <= '-') { if (yych == ',') goto yy57; goto yy699; } else { if (yych != 'G') goto yy57; } } YYDEBUG(698, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy707; goto yy57; yy699: YYDEBUG(699, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '1') goto yy700; if (yych <= '2') goto yy702; if (yych <= '9') goto yy703; goto yy57; yy700: YYDEBUG(700, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '/') goto yy701; if (yych <= '9') goto yy703; if (yych <= ':') goto yy704; yy701: YYDEBUG(701, *YYCURSOR); #line 1556 "ext/date/lib/parse_date.re" { int tz_not_found; DEBUG_OUTPUT("clf"); TIMELIB_INIT; TIMELIB_HAVE_TIME(); TIMELIB_HAVE_DATE(); s->time->d = timelib_get_nr((char **) &ptr, 2); s->time->m = timelib_get_month((char **) &ptr); s->time->y = timelib_get_nr((char **) &ptr, 4); s->time->h = timelib_get_nr((char **) &ptr, 2); s->time->i = timelib_get_nr((char **) &ptr, 2); s->time->s = timelib_get_nr((char **) &ptr, 2); s->time->z = timelib_get_zone((char **) &ptr, &s->time->dst, s->time, &tz_not_found, s->tzdb); if (tz_not_found) { add_error(s, "The timezone could not be found in the database"); } TIMELIB_DEINIT; return TIMELIB_CLF; } #line 12118 "ext/date/lib/parse_date.c" yy702: YYDEBUG(702, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '5') { if (yych <= '/') goto yy701; if (yych >= '5') goto yy705; } else { if (yych <= '9') goto yy706; if (yych <= ':') goto yy704; goto yy701; } yy703: YYDEBUG(703, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy701; if (yych <= '5') goto yy705; if (yych <= '9') goto yy706; if (yych >= ';') goto yy701; yy704: YYDEBUG(704, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy701; if (yych <= '5') goto yy705; if (yych <= '9') goto yy706; goto yy701; yy705: YYDEBUG(705, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy701; if (yych >= ':') goto yy701; yy706: YYDEBUG(706, *YYCURSOR); yych = *++YYCURSOR; goto yy701; yy707: YYDEBUG(707, *YYCURSOR); yych = *++YYCURSOR; if (yych != 'T') goto yy57; YYDEBUG(708, *YYCURSOR); yych = *++YYCURSOR; if (yych == '+') goto yy699; if (yych == '-') goto yy699; goto yy57; yy709: YYDEBUG(709, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'V') goto yy679; if (yych == 'v') goto yy679; goto yy57; yy710: YYDEBUG(710, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy679; if (yych == 't') goto yy679; goto yy57; yy711: YYDEBUG(711, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy712; if (yych != 'p') goto yy57; yy712: YYDEBUG(712, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych == '/') goto yy680; goto yy57; } else { if (yych <= 'T') goto yy679; if (yych == 't') goto yy679; goto yy57; } yy713: YYDEBUG(713, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy679; if (yych == 'g') goto yy679; goto yy57; yy714: YYDEBUG(714, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy679; if (yych == 'r') goto yy679; goto yy57; yy715: YYDEBUG(715, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych == 'R') goto yy679; if (yych <= 'X') goto yy57; goto yy679; } else { if (yych <= 'r') { if (yych <= 'q') goto yy57; goto yy679; } else { if (yych == 'y') goto yy679; goto yy57; } } yy716: YYDEBUG(716, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy679; if (yych == 'b') goto yy679; goto yy57; yy717: YYDEBUG(717, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych == 'L') goto yy679; if (yych <= 'M') goto yy57; goto yy679; } else { if (yych <= 'l') { if (yych <= 'k') goto yy57; goto yy679; } else { if (yych == 'n') goto yy679; goto yy57; } } yy718: YYDEBUG(718, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy679; if (yych == 'n') goto yy679; goto yy57; yy719: YYDEBUG(719, *YYCURSOR); yych = *++YYCURSOR; if (yych == 't') goto yy728; goto yy57; yy720: YYDEBUG(720, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'd') goto yy728; goto yy57; yy721: YYDEBUG(721, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'd') goto yy728; goto yy57; yy722: YYDEBUG(722, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'h') goto yy728; goto yy57; yy723: YYDEBUG(723, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; YYDEBUG(724, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy667; if (yych >= ':') goto yy667; YYDEBUG(725, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy667; if (yych >= ':') goto yy667; YYDEBUG(726, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy667; if (yych >= ':') goto yy667; YYDEBUG(727, *YYCURSOR); yych = *++YYCURSOR; goto yy667; yy728: YYDEBUG(728, *YYCURSOR); yyaccept = 14; yych = *(YYMARKER = ++YYCURSOR); if (yych == '/') goto yy723; goto yy667; yy729: YYDEBUG(729, *YYCURSOR); yych = *++YYCURSOR; if (yych <= ',') { if (yych == '\t') goto yy731; goto yy578; } else { if (yych <= '-') goto yy732; if (yych <= '.') goto yy731; if (yych >= '0') goto yy578; } yy730: YYDEBUG(730, *YYCURSOR); yych = *++YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case 'A': case 'a': goto yy673; case 'D': case 'd': goto yy677; case 'F': case 'f': goto yy671; case 'J': case 'j': goto yy670; case 'M': case 'm': goto yy672; case 'N': case 'n': goto yy676; case 'O': case 'o': goto yy675; case 'S': case 's': goto yy674; default: goto yy57; } yy731: YYDEBUG(731, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy578; if (yych <= '0') goto yy736; if (yych <= '1') goto yy737; if (yych <= '9') goto yy738; goto yy578; yy732: YYDEBUG(732, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy578; if (yych <= '0') goto yy733; if (yych <= '1') goto yy734; if (yych <= '9') goto yy735; goto yy578; yy733: YYDEBUG(733, *YYCURSOR); yych = *++YYCURSOR; if (yych <= ',') goto yy57; if (yych <= '.') goto yy602; if (yych <= '/') goto yy57; if (yych <= '9') goto yy735; goto yy57; yy734: YYDEBUG(734, *YYCURSOR); yych = *++YYCURSOR; if (yych <= ',') goto yy57; if (yych <= '.') goto yy602; if (yych <= '/') goto yy57; if (yych >= '3') goto yy57; yy735: YYDEBUG(735, *YYCURSOR); yych = *++YYCURSOR; if (yych <= ',') goto yy57; if (yych <= '.') goto yy602; goto yy57; yy736: YYDEBUG(736, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '.') { if (yych <= ',') goto yy57; if (yych <= '-') goto yy602; goto yy739; } else { if (yych <= '/') goto yy57; if (yych <= '9') goto yy738; goto yy57; } yy737: YYDEBUG(737, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '.') { if (yych <= ',') goto yy57; if (yych <= '-') goto yy602; goto yy739; } else { if (yych <= '/') goto yy57; if (yych >= '3') goto yy57; } yy738: YYDEBUG(738, *YYCURSOR); yych = *++YYCURSOR; if (yych <= ',') goto yy57; if (yych <= '-') goto yy602; if (yych >= '/') goto yy57; yy739: YYDEBUG(739, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; YYDEBUG(740, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy611; goto yy57; yy741: YYDEBUG(741, *YYCURSOR); yych = *++YYCURSOR; if (yych == '-') goto yy785; if (yych <= '/') goto yy61; if (yych <= '9') goto yy783; goto yy61; yy742: YYDEBUG(742, *YYCURSOR); yych = *++YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case '0': goto yy751; case '1': goto yy752; case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy753; case 'A': case 'a': goto yy746; case 'D': case 'd': goto yy750; case 'F': case 'f': goto yy744; case 'J': case 'j': goto yy743; case 'M': case 'm': goto yy745; case 'N': case 'n': goto yy749; case 'O': case 'o': goto yy748; case 'S': case 's': goto yy747; default: goto yy57; } yy743: YYDEBUG(743, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'A') goto yy782; if (yych <= 'T') goto yy57; goto yy781; } else { if (yych <= 'a') { if (yych <= '`') goto yy57; goto yy782; } else { if (yych == 'u') goto yy781; goto yy57; } } yy744: YYDEBUG(744, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy780; if (yych == 'e') goto yy780; goto yy57; yy745: YYDEBUG(745, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy779; if (yych == 'a') goto yy779; goto yy57; yy746: YYDEBUG(746, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'P') goto yy778; if (yych <= 'T') goto yy57; goto yy777; } else { if (yych <= 'p') { if (yych <= 'o') goto yy57; goto yy778; } else { if (yych == 'u') goto yy777; goto yy57; } } yy747: YYDEBUG(747, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy775; if (yych == 'e') goto yy775; goto yy57; yy748: YYDEBUG(748, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy774; if (yych == 'c') goto yy774; goto yy57; yy749: YYDEBUG(749, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy773; if (yych == 'o') goto yy773; goto yy57; yy750: YYDEBUG(750, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy765; if (yych == 'e') goto yy765; goto yy57; yy751: YYDEBUG(751, *YYCURSOR); yych = *++YYCURSOR; if (yych == '-') goto yy754; if (yych <= '/') goto yy57; if (yych <= '9') goto yy758; goto yy57; yy752: YYDEBUG(752, *YYCURSOR); yych = *++YYCURSOR; if (yych == '-') goto yy754; if (yych <= '/') goto yy57; if (yych <= '2') goto yy758; goto yy57; yy753: YYDEBUG(753, *YYCURSOR); yych = *++YYCURSOR; if (yych != '-') goto yy57; yy754: YYDEBUG(754, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '2') goto yy755; if (yych <= '3') goto yy756; if (yych <= '9') goto yy757; goto yy57; yy755: YYDEBUG(755, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy657; if (yych <= '9') goto yy757; if (yych <= 'm') goto yy657; goto yy661; } else { if (yych <= 'r') { if (yych <= 'q') goto yy657; goto yy662; } else { if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; goto yy657; } } yy756: YYDEBUG(756, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy657; if (yych <= '1') goto yy757; if (yych <= 'm') goto yy657; goto yy661; } else { if (yych <= 'r') { if (yych <= 'q') goto yy657; goto yy662; } else { if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; goto yy657; } } yy757: YYDEBUG(757, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'q') { if (yych == 'n') goto yy661; goto yy657; } else { if (yych <= 'r') goto yy662; if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; goto yy657; } yy758: YYDEBUG(758, *YYCURSOR); yych = *++YYCURSOR; if (yych != '-') goto yy57; YYDEBUG(759, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '2') { if (yych <= '/') goto yy57; if (yych >= '1') goto yy761; } else { if (yych <= '3') goto yy762; if (yych <= '9') goto yy757; goto yy57; } YYDEBUG(760, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy657; if (yych <= '9') goto yy763; if (yych <= 'm') goto yy657; goto yy661; } else { if (yych <= 'r') { if (yych <= 'q') goto yy657; goto yy662; } else { if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; goto yy657; } } yy761: YYDEBUG(761, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy657; if (yych <= '9') goto yy763; if (yych <= 'm') goto yy657; goto yy661; } else { if (yych <= 'r') { if (yych <= 'q') goto yy657; goto yy662; } else { if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; goto yy657; } } yy762: YYDEBUG(762, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy657; if (yych <= '1') goto yy763; if (yych <= 'm') goto yy657; goto yy661; } else { if (yych <= 'r') { if (yych <= 'q') goto yy657; goto yy662; } else { if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; goto yy657; } } yy763: YYDEBUG(763, *YYCURSOR); yyaccept = 15; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'q') { if (yych == 'n') goto yy661; } else { if (yych <= 'r') goto yy662; if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; } yy764: YYDEBUG(764, *YYCURSOR); #line 1301 "ext/date/lib/parse_date.re" { int length = 0; DEBUG_OUTPUT("iso8601date2"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->y = timelib_get_nr_ex((char **) &ptr, 4, &length); s->time->m = timelib_get_nr((char **) &ptr, 2); s->time->d = timelib_get_nr((char **) &ptr, 2); TIMELIB_PROCESS_YEAR(s->time->y, length); TIMELIB_DEINIT; return TIMELIB_ISO_DATE; } #line 12683 "ext/date/lib/parse_date.c" yy765: YYDEBUG(765, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy766; if (yych != 'c') goto yy57; yy766: YYDEBUG(766, *YYCURSOR); yych = *++YYCURSOR; if (yych != '-') goto yy57; yy767: YYDEBUG(767, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '0') goto yy768; if (yych <= '2') goto yy769; if (yych <= '3') goto yy770; goto yy57; yy768: YYDEBUG(768, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy771; goto yy57; yy769: YYDEBUG(769, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy771; goto yy57; yy770: YYDEBUG(770, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= '2') goto yy57; yy771: YYDEBUG(771, *YYCURSOR); ++YYCURSOR; YYDEBUG(772, *YYCURSOR); #line 1542 "ext/date/lib/parse_date.re" { int length = 0; DEBUG_OUTPUT("pgtextreverse"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->y = timelib_get_nr_ex((char **) &ptr, 4, &length); s->time->m = timelib_get_month((char **) &ptr); s->time->d = timelib_get_nr((char **) &ptr, 2); TIMELIB_PROCESS_YEAR(s->time->y, length); TIMELIB_DEINIT; return TIMELIB_PG_TEXT; } #line 12735 "ext/date/lib/parse_date.c" yy773: YYDEBUG(773, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'V') goto yy766; if (yych == 'v') goto yy766; goto yy57; yy774: YYDEBUG(774, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy766; if (yych == 't') goto yy766; goto yy57; yy775: YYDEBUG(775, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy776; if (yych != 'p') goto yy57; yy776: YYDEBUG(776, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych == '-') goto yy767; goto yy57; } else { if (yych <= 'T') goto yy766; if (yych == 't') goto yy766; goto yy57; } yy777: YYDEBUG(777, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy766; if (yych == 'g') goto yy766; goto yy57; yy778: YYDEBUG(778, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy766; if (yych == 'r') goto yy766; goto yy57; yy779: YYDEBUG(779, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych == 'R') goto yy766; if (yych <= 'X') goto yy57; goto yy766; } else { if (yych <= 'r') { if (yych <= 'q') goto yy57; goto yy766; } else { if (yych == 'y') goto yy766; goto yy57; } } yy780: YYDEBUG(780, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy766; if (yych == 'b') goto yy766; goto yy57; yy781: YYDEBUG(781, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych == 'L') goto yy766; if (yych <= 'M') goto yy57; goto yy766; } else { if (yych <= 'l') { if (yych <= 'k') goto yy57; goto yy766; } else { if (yych == 'n') goto yy766; goto yy57; } } yy782: YYDEBUG(782, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy766; if (yych == 'n') goto yy766; goto yy57; yy783: YYDEBUG(783, *YYCURSOR); yyaccept = 16; yych = *(YYMARKER = ++YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case '\t': case ' ': case 'A': case 'D': case 'F': case 'H': case 'I': case 'J': case 'M': case 'N': case 'O': case 'S': case 'T': case 'V': case 'X': case 'Y': case 'a': case 'd': case 'f': case 'h': case 'j': case 'm': case 'n': case 'o': case 's': case 't': case 'w': case 'y': goto yy791; case '-': goto yy788; case '.': goto yy792; case '/': goto yy789; case '0': goto yy805; case '1': goto yy806; case '2': goto yy808; case '3': goto yy809; case '4': case '5': case '6': case '7': case '8': case '9': goto yy55; case ':': goto yy807; case 'W': goto yy810; default: goto yy784; } yy784: YYDEBUG(784, *YYCURSOR); #line 1577 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("year4"); TIMELIB_INIT; s->time->y = timelib_get_nr((char **) &ptr, 4); TIMELIB_DEINIT; return TIMELIB_CLF; } #line 12881 "ext/date/lib/parse_date.c" yy785: YYDEBUG(785, *YYCURSOR); yych = *++YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case '0': goto yy786; case '1': goto yy787; case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy753; case 'A': case 'a': goto yy746; case 'D': case 'd': goto yy750; case 'F': case 'f': goto yy744; case 'J': case 'j': goto yy743; case 'M': case 'm': goto yy745; case 'N': case 'n': goto yy749; case 'O': case 'o': goto yy748; case 'S': case 's': goto yy747; default: goto yy57; } yy786: YYDEBUG(786, *YYCURSOR); yych = *++YYCURSOR; if (yych == '-') goto yy754; if (yych <= '/') goto yy57; if (yych <= '9') goto yy753; goto yy57; yy787: YYDEBUG(787, *YYCURSOR); yych = *++YYCURSOR; if (yych == '-') goto yy754; if (yych <= '/') goto yy57; if (yych <= '2') goto yy753; goto yy57; yy788: YYDEBUG(788, *YYCURSOR); yych = *++YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case '0': goto yy973; case '1': goto yy975; case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy976; case 'A': case 'a': goto yy967; case 'D': case 'd': goto yy971; case 'F': case 'f': goto yy965; case 'J': case 'j': goto yy964; case 'M': case 'm': goto yy966; case 'N': case 'n': goto yy970; case 'O': case 'o': goto yy969; case 'S': case 's': goto yy968; case 'W': goto yy972; default: goto yy939; } yy789: YYDEBUG(789, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '0') goto yy947; if (yych <= '1') goto yy948; if (yych <= '9') goto yy949; goto yy57; yy790: YYDEBUG(790, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 11) YYFILL(11); yych = *YYCURSOR; yy791: YYDEBUG(791, *YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case '\t': case ' ': goto yy790; case '-': case '.': goto yy938; case 'A': case 'a': goto yy800; case 'D': case 'd': goto yy804; case 'F': case 'f': goto yy798; case 'H': case 'h': goto yy64; case 'I': goto yy793; case 'J': case 'j': goto yy797; case 'M': case 'm': goto yy799; case 'N': case 'n': goto yy803; case 'O': case 'o': goto yy802; case 'S': case 's': goto yy801; case 'T': case 't': goto yy69; case 'V': goto yy795; case 'W': case 'w': goto yy68; case 'X': goto yy796; case 'Y': case 'y': goto yy67; default: goto yy57; } yy792: YYDEBUG(792, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy939; if (yych <= '0') goto yy931; if (yych <= '2') goto yy932; if (yych <= '3') goto yy933; goto yy939; yy793: YYDEBUG(793, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= 'U') { if (yych == 'I') goto yy930; } else { if (yych == 'W') goto yy794; if (yych <= 'X') goto yy884; } yy794: YYDEBUG(794, *YYCURSOR); #line 1398 "ext/date/lib/parse_date.re" { int length = 0; DEBUG_OUTPUT("datenodayrev"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->y = timelib_get_nr_ex((char **) &ptr, 4, &length); s->time->m = timelib_get_month((char **) &ptr); s->time->d = 1; TIMELIB_PROCESS_YEAR(s->time->y, length); TIMELIB_DEINIT; return TIMELIB_DATE_NO_DAY; } #line 13045 "ext/date/lib/parse_date.c" yy795: YYDEBUG(795, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy928; goto yy794; yy796: YYDEBUG(796, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy927; goto yy794; yy797: YYDEBUG(797, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'A') goto yy920; if (yych <= 'T') goto yy57; goto yy919; } else { if (yych <= 'a') { if (yych <= '`') goto yy57; goto yy920; } else { if (yych == 'u') goto yy919; goto yy57; } } yy798: YYDEBUG(798, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= 'N') { if (yych == 'E') goto yy913; goto yy57; } else { if (yych <= 'O') goto yy99; if (yych <= 'Q') goto yy57; goto yy98; } } else { if (yych <= 'n') { if (yych == 'e') goto yy913; goto yy57; } else { if (yych <= 'o') goto yy99; if (yych == 'r') goto yy98; goto yy57; } } yy799: YYDEBUG(799, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= 'H') { if (yych == 'A') goto yy910; goto yy57; } else { if (yych <= 'I') goto yy118; if (yych <= 'N') goto yy57; goto yy117; } } else { if (yych <= 'h') { if (yych == 'a') goto yy910; goto yy57; } else { if (yych <= 'i') goto yy118; if (yych == 'o') goto yy117; goto yy57; } } yy800: YYDEBUG(800, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'P') goto yy904; if (yych <= 'T') goto yy57; goto yy903; } else { if (yych <= 'p') { if (yych <= 'o') goto yy57; goto yy904; } else { if (yych == 'u') goto yy903; goto yy57; } } yy801: YYDEBUG(801, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= 'D') { if (yych == 'A') goto yy127; goto yy57; } else { if (yych <= 'E') goto yy896; if (yych <= 'T') goto yy57; goto yy126; } } else { if (yych <= 'd') { if (yych == 'a') goto yy127; goto yy57; } else { if (yych <= 'e') goto yy896; if (yych == 'u') goto yy126; goto yy57; } } yy802: YYDEBUG(802, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy891; if (yych == 'c') goto yy891; goto yy57; yy803: YYDEBUG(803, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy885; if (yych == 'o') goto yy885; goto yy57; yy804: YYDEBUG(804, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych == 'A') goto yy114; if (yych <= 'D') goto yy57; goto yy878; } else { if (yych <= 'a') { if (yych <= '`') goto yy57; goto yy114; } else { if (yych == 'e') goto yy878; goto yy57; } } yy805: YYDEBUG(805, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '0') goto yy875; if (yych <= '9') goto yy876; goto yy61; yy806: YYDEBUG(806, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '2') goto yy844; if (yych <= '9') goto yy823; goto yy61; yy807: YYDEBUG(807, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '0') goto yy824; if (yych <= '1') goto yy825; goto yy57; yy808: YYDEBUG(808, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '9') goto yy823; goto yy61; yy809: YYDEBUG(809, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '5') goto yy819; if (yych <= '6') goto yy820; if (yych <= '9') goto yy55; goto yy61; yy810: YYDEBUG(810, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '5') { if (yych <= '/') goto yy57; if (yych <= '0') goto yy811; if (yych <= '4') goto yy812; goto yy813; } else { if (yych <= 'E') { if (yych <= 'D') goto yy57; goto yy83; } else { if (yych == 'e') goto yy83; goto yy57; } } yy811: YYDEBUG(811, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '0') goto yy57; if (yych <= '9') goto yy814; goto yy57; yy812: YYDEBUG(812, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy814; goto yy57; yy813: YYDEBUG(813, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= '4') goto yy57; yy814: YYDEBUG(814, *YYCURSOR); yyaccept = 17; yych = *(YYMARKER = ++YYCURSOR); if (yych == '-') goto yy816; if (yych <= '/') goto yy815; if (yych <= '7') goto yy817; yy815: YYDEBUG(815, *YYCURSOR); #line 1509 "ext/date/lib/parse_date.re" { timelib_sll w, d; DEBUG_OUTPUT("isoweek"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); TIMELIB_HAVE_RELATIVE(); s->time->y = timelib_get_nr((char **) &ptr, 4); w = timelib_get_nr((char **) &ptr, 2); d = 1; s->time->m = 1; s->time->d = 1; s->time->relative.d = timelib_daynr_from_weeknr(s->time->y, w, d); TIMELIB_DEINIT; return TIMELIB_ISO_WEEK; } #line 13278 "ext/date/lib/parse_date.c" yy816: YYDEBUG(816, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= '8') goto yy57; yy817: YYDEBUG(817, *YYCURSOR); ++YYCURSOR; YYDEBUG(818, *YYCURSOR); #line 1490 "ext/date/lib/parse_date.re" { timelib_sll w, d; DEBUG_OUTPUT("isoweekday"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); TIMELIB_HAVE_RELATIVE(); s->time->y = timelib_get_nr((char **) &ptr, 4); w = timelib_get_nr((char **) &ptr, 2); d = timelib_get_nr((char **) &ptr, 1); s->time->m = 1; s->time->d = 1; s->time->relative.d = timelib_daynr_from_weeknr(s->time->y, w, d); TIMELIB_DEINIT; return TIMELIB_ISO_WEEK; } #line 13306 "ext/date/lib/parse_date.c" yy819: YYDEBUG(819, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '9') goto yy821; goto yy61; yy820: YYDEBUG(820, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '6') goto yy821; if (yych <= '9') goto yy55; goto yy61; yy821: YYDEBUG(821, *YYCURSOR); yyaccept = 18; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 2) { goto yy55; } if (yych <= 'W') { if (yych <= 'F') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych >= ' ') goto yy61; } else { if (yych == 'D') goto yy61; if (yych >= 'F') goto yy61; } } else { if (yych <= 'M') { if (yych == 'H') goto yy61; if (yych >= 'M') goto yy61; } else { if (yych <= 'R') goto yy822; if (yych <= 'T') goto yy61; if (yych >= 'W') goto yy61; } } } else { if (yych <= 'h') { if (yych <= 'd') { if (yych == 'Y') goto yy61; if (yych >= 'd') goto yy61; } else { if (yych == 'f') goto yy61; if (yych >= 'h') goto yy61; } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych >= 's') goto yy61; } else { if (yych <= 'w') { if (yych >= 'w') goto yy61; } else { if (yych == 'y') goto yy61; } } } } yy822: YYDEBUG(822, *YYCURSOR); #line 1476 "ext/date/lib/parse_date.re" { int length = 0; DEBUG_OUTPUT("pgydotd"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->y = timelib_get_nr_ex((char **) &ptr, 4, &length); s->time->d = timelib_get_nr((char **) &ptr, 3); s->time->m = 1; TIMELIB_PROCESS_YEAR(s->time->y, length); TIMELIB_DEINIT; return TIMELIB_PG_YEARDAY; } #line 13383 "ext/date/lib/parse_date.c" yy823: YYDEBUG(823, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '9') goto yy821; goto yy61; yy824: YYDEBUG(824, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy826; goto yy57; yy825: YYDEBUG(825, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= '3') goto yy57; yy826: YYDEBUG(826, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy57; YYDEBUG(827, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '0') goto yy828; if (yych <= '2') goto yy829; if (yych <= '3') goto yy830; goto yy57; yy828: YYDEBUG(828, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy831; goto yy57; yy829: YYDEBUG(829, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy831; goto yy57; yy830: YYDEBUG(830, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= '2') goto yy57; yy831: YYDEBUG(831, *YYCURSOR); yych = *++YYCURSOR; if (yych != ' ') goto yy57; YYDEBUG(832, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '1') goto yy833; if (yych <= '2') goto yy834; goto yy57; yy833: YYDEBUG(833, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy835; goto yy57; yy834: YYDEBUG(834, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= '5') goto yy57; yy835: YYDEBUG(835, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy57; YYDEBUG(836, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= '6') goto yy57; YYDEBUG(837, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; YYDEBUG(838, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy57; YYDEBUG(839, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy840; if (yych <= '6') goto yy841; goto yy57; yy840: YYDEBUG(840, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy842; goto yy57; yy841: YYDEBUG(841, *YYCURSOR); yych = *++YYCURSOR; if (yych != '0') goto yy57; yy842: YYDEBUG(842, *YYCURSOR); ++YYCURSOR; yy843: YYDEBUG(843, *YYCURSOR); #line 1450 "ext/date/lib/parse_date.re" { int tz_not_found; DEBUG_OUTPUT("xmlrpc | xmlrpcnocolon | soap | wddx | exif"); TIMELIB_INIT; TIMELIB_HAVE_TIME(); TIMELIB_HAVE_DATE(); s->time->y = timelib_get_nr((char **) &ptr, 4); s->time->m = timelib_get_nr((char **) &ptr, 2); s->time->d = timelib_get_nr((char **) &ptr, 2); s->time->h = timelib_get_nr((char **) &ptr, 2); s->time->i = timelib_get_nr((char **) &ptr, 2); s->time->s = timelib_get_nr((char **) &ptr, 2); if (*ptr == '.') { s->time->f = timelib_get_frac_nr((char **) &ptr, 9); if (*ptr) { /* timezone is optional */ s->time->z = timelib_get_zone((char **) &ptr, &s->time->dst, s->time, &tz_not_found, s->tzdb); if (tz_not_found) { add_error(s, "The timezone could not be found in the database"); } } } TIMELIB_DEINIT; return TIMELIB_XMLRPC_SOAP; } #line 13511 "ext/date/lib/parse_date.c" yy844: YYDEBUG(844, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '2') { if (yych <= '/') goto yy61; if (yych >= '1') goto yy846; } else { if (yych <= '3') goto yy847; if (yych <= '9') goto yy821; goto yy61; } yy845: YYDEBUG(845, *YYCURSOR); yyaccept = 18; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'V') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy822; goto yy61; } else { if (yych <= '/') goto yy822; if (yych <= '9') goto yy848; if (yych <= 'C') goto yy822; goto yy61; } } else { if (yych <= 'H') { if (yych == 'F') goto yy61; if (yych <= 'G') goto yy822; goto yy61; } else { if (yych <= 'M') { if (yych <= 'L') goto yy822; goto yy61; } else { if (yych <= 'R') goto yy822; if (yych <= 'T') goto yy61; goto yy822; } } } } else { if (yych <= 'h') { if (yych <= 'c') { if (yych == 'X') goto yy822; if (yych <= 'Y') goto yy61; goto yy822; } else { if (yych <= 'e') { if (yych <= 'd') goto yy61; goto yy822; } else { if (yych == 'g') goto yy822; goto yy61; } } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych <= 'r') goto yy822; goto yy61; } else { if (yych <= 'w') { if (yych <= 'v') goto yy822; goto yy61; } else { if (yych == 'y') goto yy61; goto yy822; } } } } yy846: YYDEBUG(846, *YYCURSOR); yyaccept = 18; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'V') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy822; goto yy61; } else { if (yych <= '/') goto yy822; if (yych <= '9') goto yy848; if (yych <= 'C') goto yy822; goto yy61; } } else { if (yych <= 'H') { if (yych == 'F') goto yy61; if (yych <= 'G') goto yy822; goto yy61; } else { if (yych <= 'M') { if (yych <= 'L') goto yy822; goto yy61; } else { if (yych <= 'R') goto yy822; if (yych <= 'T') goto yy61; goto yy822; } } } } else { if (yych <= 'h') { if (yych <= 'c') { if (yych == 'X') goto yy822; if (yych <= 'Y') goto yy61; goto yy822; } else { if (yych <= 'e') { if (yych <= 'd') goto yy61; goto yy822; } else { if (yych == 'g') goto yy822; goto yy61; } } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych <= 'r') goto yy822; goto yy61; } else { if (yych <= 'w') { if (yych <= 'v') goto yy822; goto yy61; } else { if (yych == 'y') goto yy61; goto yy822; } } } } yy847: YYDEBUG(847, *YYCURSOR); yyaccept = 18; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'V') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy822; goto yy61; } else { if (yych <= '1') { if (yych <= '/') goto yy822; } else { if (yych <= '9') goto yy55; if (yych <= 'C') goto yy822; goto yy61; } } } else { if (yych <= 'H') { if (yych == 'F') goto yy61; if (yych <= 'G') goto yy822; goto yy61; } else { if (yych <= 'M') { if (yych <= 'L') goto yy822; goto yy61; } else { if (yych <= 'R') goto yy822; if (yych <= 'T') goto yy61; goto yy822; } } } } else { if (yych <= 'h') { if (yych <= 'c') { if (yych == 'X') goto yy822; if (yych <= 'Y') goto yy61; goto yy822; } else { if (yych <= 'e') { if (yych <= 'd') goto yy61; goto yy822; } else { if (yych == 'g') goto yy822; goto yy61; } } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych <= 'r') goto yy822; goto yy61; } else { if (yych <= 'w') { if (yych <= 'v') goto yy822; goto yy61; } else { if (yych == 'y') goto yy61; goto yy822; } } } } yy848: YYDEBUG(848, *YYCURSOR); yyaccept = 19; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 2) { goto yy55; } if (yych <= 'W') { if (yych <= 'F') { if (yych <= ' ') { if (yych == '\t') goto yy60; if (yych >= ' ') goto yy60; } else { if (yych == 'D') goto yy65; if (yych >= 'F') goto yy66; } } else { if (yych <= 'M') { if (yych == 'H') goto yy64; if (yych >= 'M') goto yy63; } else { if (yych <= 'S') { if (yych >= 'S') goto yy62; } else { if (yych <= 'T') goto yy850; if (yych >= 'W') goto yy68; } } } } else { if (yych <= 'l') { if (yych <= 'd') { if (yych == 'Y') goto yy67; if (yych >= 'd') goto yy65; } else { if (yych <= 'f') { if (yych >= 'f') goto yy66; } else { if (yych == 'h') goto yy64; } } } else { if (yych <= 't') { if (yych <= 'm') goto yy63; if (yych <= 'r') goto yy849; if (yych <= 's') goto yy62; goto yy851; } else { if (yych <= 'w') { if (yych >= 'w') goto yy68; } else { if (yych == 'y') goto yy67; } } } } yy849: YYDEBUG(849, *YYCURSOR); #line 1438 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("datenocolon"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->y = timelib_get_nr((char **) &ptr, 4); s->time->m = timelib_get_nr((char **) &ptr, 2); s->time->d = timelib_get_nr((char **) &ptr, 2); TIMELIB_DEINIT; return TIMELIB_DATE_NOCOLON; } #line 13784 "ext/date/lib/parse_date.c" yy850: YYDEBUG(850, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'H') { if (yych <= '2') { if (yych <= '/') goto yy57; if (yych <= '1') goto yy865; goto yy866; } else { if (yych <= '9') goto yy867; if (yych <= 'G') goto yy57; goto yy70; } } else { if (yych <= 'g') { if (yych == 'U') goto yy71; goto yy57; } else { if (yych <= 'h') goto yy70; if (yych == 'u') goto yy71; goto yy57; } } yy851: YYDEBUG(851, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'H') { if (yych <= '2') { if (yych <= '/') goto yy57; if (yych >= '2') goto yy853; } else { if (yych <= '9') goto yy854; if (yych <= 'G') goto yy57; goto yy70; } } else { if (yych <= 'g') { if (yych == 'U') goto yy71; goto yy57; } else { if (yych <= 'h') goto yy70; if (yych == 'u') goto yy71; goto yy57; } } YYDEBUG(852, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy859; if (yych <= '9') goto yy854; goto yy57; yy853: YYDEBUG(853, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '4') goto yy859; if (yych <= '5') goto yy855; goto yy57; yy854: YYDEBUG(854, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= '6') goto yy57; yy855: YYDEBUG(855, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; yy856: YYDEBUG(856, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy857; if (yych <= '6') goto yy858; goto yy57; yy857: YYDEBUG(857, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy842; goto yy57; yy858: YYDEBUG(858, *YYCURSOR); yych = *++YYCURSOR; if (yych == '0') goto yy842; goto yy57; yy859: YYDEBUG(859, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy860; if (yych <= '9') goto yy856; goto yy57; yy860: YYDEBUG(860, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy861; if (yych <= '6') goto yy862; if (yych <= '9') goto yy856; goto yy57; yy861: YYDEBUG(861, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy863; if (yych <= '6') goto yy864; if (yych <= '9') goto yy842; goto yy57; yy862: YYDEBUG(862, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '0') goto yy863; if (yych <= '5') goto yy857; if (yych <= '6') goto yy858; goto yy57; yy863: YYDEBUG(863, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy843; if (yych <= '9') goto yy842; goto yy843; yy864: YYDEBUG(864, *YYCURSOR); yych = *++YYCURSOR; if (yych == '0') goto yy842; goto yy843; yy865: YYDEBUG(865, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy874; if (yych <= '9') goto yy867; if (yych <= ':') goto yy868; goto yy57; yy866: YYDEBUG(866, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '5') { if (yych <= '/') goto yy57; if (yych <= '4') goto yy874; goto yy855; } else { if (yych == ':') goto yy868; goto yy57; } yy867: YYDEBUG(867, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy855; if (yych != ':') goto yy57; yy868: YYDEBUG(868, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= '6') goto yy57; YYDEBUG(869, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; YYDEBUG(870, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy57; YYDEBUG(871, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy872; if (yych <= '6') goto yy873; goto yy57; yy872: YYDEBUG(872, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy842; goto yy57; yy873: YYDEBUG(873, *YYCURSOR); yych = *++YYCURSOR; if (yych == '0') goto yy842; goto yy57; yy874: YYDEBUG(874, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy860; if (yych <= '9') goto yy856; if (yych <= ':') goto yy868; goto yy57; yy875: YYDEBUG(875, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '2') { if (yych <= '/') goto yy61; if (yych <= '0') goto yy877; goto yy846; } else { if (yych <= '3') goto yy847; if (yych <= '9') goto yy821; goto yy61; } yy876: YYDEBUG(876, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '2') { if (yych <= '/') goto yy61; if (yych <= '0') goto yy845; goto yy846; } else { if (yych <= '3') goto yy847; if (yych <= '9') goto yy821; goto yy61; } yy877: YYDEBUG(877, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '9') goto yy848; goto yy61; yy878: YYDEBUG(878, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy879; if (yych != 'c') goto yy57; yy879: YYDEBUG(879, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'E') goto yy880; if (yych != 'e') goto yy794; yy880: YYDEBUG(880, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy881; if (yych != 'm') goto yy57; yy881: YYDEBUG(881, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy882; if (yych != 'b') goto yy57; yy882: YYDEBUG(882, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy883; if (yych != 'e') goto yy57; yy883: YYDEBUG(883, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy884; if (yych != 'r') goto yy57; yy884: YYDEBUG(884, *YYCURSOR); yych = *++YYCURSOR; goto yy794; yy885: YYDEBUG(885, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'V') goto yy886; if (yych != 'v') goto yy57; yy886: YYDEBUG(886, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'E') goto yy887; if (yych != 'e') goto yy794; yy887: YYDEBUG(887, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy888; if (yych != 'm') goto yy57; yy888: YYDEBUG(888, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy889; if (yych != 'b') goto yy57; yy889: YYDEBUG(889, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy890; if (yych != 'e') goto yy57; yy890: YYDEBUG(890, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy884; if (yych == 'r') goto yy884; goto yy57; yy891: YYDEBUG(891, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy892; if (yych != 't') goto yy57; yy892: YYDEBUG(892, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'O') goto yy893; if (yych != 'o') goto yy794; yy893: YYDEBUG(893, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy894; if (yych != 'b') goto yy57; yy894: YYDEBUG(894, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy895; if (yych != 'e') goto yy57; yy895: YYDEBUG(895, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy884; if (yych == 'r') goto yy884; goto yy57; yy896: YYDEBUG(896, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'P') { if (yych == 'C') goto yy129; if (yych <= 'O') goto yy57; } else { if (yych <= 'c') { if (yych <= 'b') goto yy57; goto yy129; } else { if (yych != 'p') goto yy57; } } yy897: YYDEBUG(897, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy898; if (yych != 't') goto yy794; yy898: YYDEBUG(898, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'E') goto yy899; if (yych != 'e') goto yy794; yy899: YYDEBUG(899, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy900; if (yych != 'm') goto yy57; yy900: YYDEBUG(900, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy901; if (yych != 'b') goto yy57; yy901: YYDEBUG(901, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy902; if (yych != 'e') goto yy57; yy902: YYDEBUG(902, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy884; if (yych == 'r') goto yy884; goto yy57; yy903: YYDEBUG(903, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy907; if (yych == 'g') goto yy907; goto yy57; yy904: YYDEBUG(904, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy905; if (yych != 'r') goto yy57; yy905: YYDEBUG(905, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'I') goto yy906; if (yych != 'i') goto yy794; yy906: YYDEBUG(906, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy884; if (yych == 'l') goto yy884; goto yy57; yy907: YYDEBUG(907, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'U') goto yy908; if (yych != 'u') goto yy794; yy908: YYDEBUG(908, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy909; if (yych != 's') goto yy57; yy909: YYDEBUG(909, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy884; if (yych == 't') goto yy884; goto yy57; yy910: YYDEBUG(910, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych == 'R') goto yy911; if (yych <= 'X') goto yy57; goto yy884; } else { if (yych <= 'r') { if (yych <= 'q') goto yy57; } else { if (yych == 'y') goto yy884; goto yy57; } } yy911: YYDEBUG(911, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'C') goto yy912; if (yych != 'c') goto yy794; yy912: YYDEBUG(912, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy884; if (yych == 'h') goto yy884; goto yy57; yy913: YYDEBUG(913, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy914; if (yych != 'b') goto yy57; yy914: YYDEBUG(914, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'R') goto yy915; if (yych != 'r') goto yy794; yy915: YYDEBUG(915, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy916; if (yych != 'u') goto yy57; yy916: YYDEBUG(916, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy917; if (yych != 'a') goto yy57; yy917: YYDEBUG(917, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy918; if (yych != 'r') goto yy57; yy918: YYDEBUG(918, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy884; if (yych == 'y') goto yy884; goto yy57; yy919: YYDEBUG(919, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych == 'L') goto yy926; if (yych <= 'M') goto yy57; goto yy925; } else { if (yych <= 'l') { if (yych <= 'k') goto yy57; goto yy926; } else { if (yych == 'n') goto yy925; goto yy57; } } yy920: YYDEBUG(920, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy921; if (yych != 'n') goto yy57; yy921: YYDEBUG(921, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'U') goto yy922; if (yych != 'u') goto yy794; yy922: YYDEBUG(922, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy923; if (yych != 'a') goto yy57; yy923: YYDEBUG(923, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy924; if (yych != 'r') goto yy57; yy924: YYDEBUG(924, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy884; if (yych == 'y') goto yy884; goto yy57; yy925: YYDEBUG(925, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy884; if (yych == 'e') goto yy884; goto yy794; yy926: YYDEBUG(926, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy884; if (yych == 'y') goto yy884; goto yy794; yy927: YYDEBUG(927, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy884; goto yy794; yy928: YYDEBUG(928, *YYCURSOR); yych = *++YYCURSOR; if (yych != 'I') goto yy794; YYDEBUG(929, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy884; goto yy794; yy930: YYDEBUG(930, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy884; goto yy794; yy931: YYDEBUG(931, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '0') goto yy946; if (yych <= '9') goto yy945; goto yy57; yy932: YYDEBUG(932, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy944; goto yy57; yy933: YYDEBUG(933, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy942; if (yych <= '6') goto yy941; goto yy57; yy934: YYDEBUG(934, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy913; if (yych == 'e') goto yy913; goto yy57; yy935: YYDEBUG(935, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy910; if (yych == 'a') goto yy910; goto yy57; yy936: YYDEBUG(936, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy940; if (yych == 'e') goto yy940; goto yy57; yy937: YYDEBUG(937, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy878; if (yych == 'e') goto yy878; goto yy57; yy938: YYDEBUG(938, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 9) YYFILL(9); yych = *YYCURSOR; yy939: YYDEBUG(939, *YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case '\t': case ' ': case '-': case '.': goto yy938; case 'A': case 'a': goto yy800; case 'D': case 'd': goto yy937; case 'F': case 'f': goto yy934; case 'I': goto yy793; case 'J': case 'j': goto yy797; case 'M': case 'm': goto yy935; case 'N': case 'n': goto yy803; case 'O': case 'o': goto yy802; case 'S': case 's': goto yy936; case 'V': goto yy795; case 'X': goto yy796; default: goto yy57; } yy940: YYDEBUG(940, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy897; if (yych == 'p') goto yy897; goto yy57; yy941: YYDEBUG(941, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '6') goto yy943; goto yy57; yy942: YYDEBUG(942, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; yy943: YYDEBUG(943, *YYCURSOR); yych = *++YYCURSOR; goto yy822; yy944: YYDEBUG(944, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy943; goto yy57; yy945: YYDEBUG(945, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy943; goto yy57; yy946: YYDEBUG(946, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '0') goto yy57; if (yych <= '9') goto yy943; goto yy57; yy947: YYDEBUG(947, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '.') goto yy57; if (yych <= '/') goto yy950; if (yych <= '9') goto yy958; goto yy57; yy948: YYDEBUG(948, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '.') goto yy57; if (yych <= '/') goto yy950; if (yych <= '2') goto yy958; goto yy57; yy949: YYDEBUG(949, *YYCURSOR); yych = *++YYCURSOR; if (yych != '/') goto yy57; yy950: YYDEBUG(950, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '2') goto yy951; if (yych <= '3') goto yy952; if (yych <= '9') goto yy953; goto yy57; yy951: YYDEBUG(951, *YYCURSOR); yyaccept = 21; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy455; if (yych <= '9') goto yy953; if (yych <= 'm') goto yy455; goto yy955; } else { if (yych <= 'r') { if (yych <= 'q') goto yy455; goto yy956; } else { if (yych <= 's') goto yy954; if (yych <= 't') goto yy957; goto yy455; } } yy952: YYDEBUG(952, *YYCURSOR); yyaccept = 21; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy455; if (yych <= '1') goto yy953; if (yych <= 'm') goto yy455; goto yy955; } else { if (yych <= 'r') { if (yych <= 'q') goto yy455; goto yy956; } else { if (yych <= 's') goto yy954; if (yych <= 't') goto yy957; goto yy455; } } yy953: YYDEBUG(953, *YYCURSOR); yyaccept = 21; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'q') { if (yych == 'n') goto yy955; goto yy455; } else { if (yych <= 'r') goto yy956; if (yych <= 's') goto yy954; if (yych <= 't') goto yy957; goto yy455; } yy954: YYDEBUG(954, *YYCURSOR); yych = *++YYCURSOR; if (yych == 't') goto yy454; goto yy57; yy955: YYDEBUG(955, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'd') goto yy454; goto yy57; yy956: YYDEBUG(956, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'd') goto yy454; goto yy57; yy957: YYDEBUG(957, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'h') goto yy454; goto yy57; yy958: YYDEBUG(958, *YYCURSOR); yych = *++YYCURSOR; if (yych != '/') goto yy57; YYDEBUG(959, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '2') { if (yych <= '/') goto yy57; if (yych >= '1') goto yy961; } else { if (yych <= '3') goto yy962; if (yych <= '9') goto yy953; goto yy57; } YYDEBUG(960, *YYCURSOR); yyaccept = 21; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy455; if (yych <= '9') goto yy963; if (yych <= 'm') goto yy455; goto yy955; } else { if (yych <= 'r') { if (yych <= 'q') goto yy455; goto yy956; } else { if (yych <= 's') goto yy954; if (yych <= 't') goto yy957; goto yy455; } } yy961: YYDEBUG(961, *YYCURSOR); yyaccept = 21; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy455; if (yych <= '9') goto yy963; if (yych <= 'm') goto yy455; goto yy955; } else { if (yych <= 'r') { if (yych <= 'q') goto yy455; goto yy956; } else { if (yych <= 's') goto yy954; if (yych <= 't') goto yy957; goto yy455; } } yy962: YYDEBUG(962, *YYCURSOR); yyaccept = 21; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy455; if (yych <= '1') goto yy963; if (yych <= 'm') goto yy455; goto yy955; } else { if (yych <= 'r') { if (yych <= 'q') goto yy455; goto yy956; } else { if (yych <= 's') goto yy954; if (yych <= 't') goto yy957; goto yy455; } } yy963: YYDEBUG(963, *YYCURSOR); yyaccept = 21; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych == '/') goto yy454; if (yych <= 'm') goto yy455; goto yy955; } else { if (yych <= 'r') { if (yych <= 'q') goto yy455; goto yy956; } else { if (yych <= 's') goto yy954; if (yych <= 't') goto yy957; goto yy455; } } yy964: YYDEBUG(964, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'A') goto yy1044; if (yych <= 'T') goto yy57; goto yy1043; } else { if (yych <= 'a') { if (yych <= '`') goto yy57; goto yy1044; } else { if (yych == 'u') goto yy1043; goto yy57; } } yy965: YYDEBUG(965, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy1041; if (yych == 'e') goto yy1041; goto yy57; yy966: YYDEBUG(966, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1038; if (yych == 'a') goto yy1038; goto yy57; yy967: YYDEBUG(967, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'P') goto yy1035; if (yych <= 'T') goto yy57; goto yy1034; } else { if (yych <= 'p') { if (yych <= 'o') goto yy57; goto yy1035; } else { if (yych == 'u') goto yy1034; goto yy57; } } yy968: YYDEBUG(968, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy1031; if (yych == 'e') goto yy1031; goto yy57; yy969: YYDEBUG(969, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy1029; if (yych == 'c') goto yy1029; goto yy57; yy970: YYDEBUG(970, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy1027; if (yych == 'o') goto yy1027; goto yy57; yy971: YYDEBUG(971, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy1025; if (yych == 'e') goto yy1025; goto yy57; yy972: YYDEBUG(972, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '0') goto yy811; if (yych <= '4') goto yy812; if (yych <= '5') goto yy813; goto yy57; yy973: YYDEBUG(973, *YYCURSOR); yyaccept = 22; yych = *(YYMARKER = ++YYCURSOR); if (yych == '-') goto yy977; if (yych <= '/') goto yy974; if (yych <= '9') goto yy996; yy974: YYDEBUG(974, *YYCURSOR); #line 1315 "ext/date/lib/parse_date.re" { int length = 0; DEBUG_OUTPUT("gnudateshorter"); TIMELIB_INIT; TIMELIB_HAVE_DATE(); s->time->y = timelib_get_nr_ex((char **) &ptr, 4, &length); s->time->m = timelib_get_nr((char **) &ptr, 2); s->time->d = 1; TIMELIB_PROCESS_YEAR(s->time->y, length); TIMELIB_DEINIT; return TIMELIB_ISO_DATE; } #line 14717 "ext/date/lib/parse_date.c" yy975: YYDEBUG(975, *YYCURSOR); yyaccept = 22; yych = *(YYMARKER = ++YYCURSOR); if (yych == '-') goto yy977; if (yych <= '/') goto yy974; if (yych <= '2') goto yy996; goto yy974; yy976: YYDEBUG(976, *YYCURSOR); yyaccept = 22; yych = *(YYMARKER = ++YYCURSOR); if (yych != '-') goto yy974; yy977: YYDEBUG(977, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '2') goto yy978; if (yych <= '3') goto yy979; if (yych <= '9') goto yy980; goto yy57; yy978: YYDEBUG(978, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'm') { if (yych <= '9') { if (yych <= '/') goto yy657; goto yy980; } else { if (yych == 'T') goto yy985; goto yy657; } } else { if (yych <= 'r') { if (yych <= 'n') goto yy982; if (yych <= 'q') goto yy657; goto yy983; } else { if (yych <= 's') goto yy981; if (yych <= 't') goto yy984; goto yy657; } } yy979: YYDEBUG(979, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'm') { if (yych <= '1') { if (yych <= '/') goto yy657; } else { if (yych == 'T') goto yy985; goto yy657; } } else { if (yych <= 'r') { if (yych <= 'n') goto yy982; if (yych <= 'q') goto yy657; goto yy983; } else { if (yych <= 's') goto yy981; if (yych <= 't') goto yy984; goto yy657; } } yy980: YYDEBUG(980, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych == 'T') goto yy985; if (yych <= 'm') goto yy657; goto yy982; } else { if (yych <= 'r') { if (yych <= 'q') goto yy657; goto yy983; } else { if (yych <= 's') goto yy981; if (yych <= 't') goto yy984; goto yy657; } } yy981: YYDEBUG(981, *YYCURSOR); yych = *++YYCURSOR; if (yych == 't') goto yy995; goto yy57; yy982: YYDEBUG(982, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'd') goto yy995; goto yy57; yy983: YYDEBUG(983, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'd') goto yy995; goto yy57; yy984: YYDEBUG(984, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'h') goto yy995; goto yy57; yy985: YYDEBUG(985, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '1') goto yy986; if (yych <= '2') goto yy987; if (yych <= '9') goto yy988; goto yy57; yy986: YYDEBUG(986, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy988; if (yych <= ':') goto yy989; goto yy57; yy987: YYDEBUG(987, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '4') goto yy988; if (yych == ':') goto yy989; goto yy57; yy988: YYDEBUG(988, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy57; yy989: YYDEBUG(989, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy990; if (yych <= '9') goto yy991; goto yy57; yy990: YYDEBUG(990, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy991; if (yych <= ':') goto yy992; goto yy57; yy991: YYDEBUG(991, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy57; yy992: YYDEBUG(992, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy993; if (yych <= '6') goto yy994; if (yych <= '9') goto yy842; goto yy57; yy993: YYDEBUG(993, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy843; if (yych <= '9') goto yy842; goto yy843; yy994: YYDEBUG(994, *YYCURSOR); yych = *++YYCURSOR; if (yych == '0') goto yy842; goto yy843; yy995: YYDEBUG(995, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych == 'T') goto yy985; goto yy657; yy996: YYDEBUG(996, *YYCURSOR); yyaccept = 22; yych = *(YYMARKER = ++YYCURSOR); if (yych != '-') goto yy974; YYDEBUG(997, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '2') { if (yych <= '/') goto yy57; if (yych >= '1') goto yy999; } else { if (yych <= '3') goto yy1000; if (yych <= '9') goto yy980; goto yy57; } YYDEBUG(998, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'm') { if (yych <= '9') { if (yych <= '/') goto yy657; goto yy1001; } else { if (yych == 'T') goto yy985; goto yy657; } } else { if (yych <= 'r') { if (yych <= 'n') goto yy982; if (yych <= 'q') goto yy657; goto yy983; } else { if (yych <= 's') goto yy981; if (yych <= 't') goto yy984; goto yy657; } } yy999: YYDEBUG(999, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'm') { if (yych <= '9') { if (yych <= '/') goto yy657; goto yy1001; } else { if (yych == 'T') goto yy985; goto yy657; } } else { if (yych <= 'r') { if (yych <= 'n') goto yy982; if (yych <= 'q') goto yy657; goto yy983; } else { if (yych <= 's') goto yy981; if (yych <= 't') goto yy984; goto yy657; } } yy1000: YYDEBUG(1000, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'm') { if (yych <= '1') { if (yych <= '/') goto yy657; } else { if (yych == 'T') goto yy985; goto yy657; } } else { if (yych <= 'r') { if (yych <= 'n') goto yy982; if (yych <= 'q') goto yy657; goto yy983; } else { if (yych <= 's') goto yy981; if (yych <= 't') goto yy984; goto yy657; } } yy1001: YYDEBUG(1001, *YYCURSOR); yyaccept = 21; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych == 'T') goto yy1002; if (yych <= 'm') goto yy455; goto yy982; } else { if (yych <= 'r') { if (yych <= 'q') goto yy455; goto yy983; } else { if (yych <= 's') goto yy981; if (yych <= 't') goto yy984; goto yy455; } } yy1002: YYDEBUG(1002, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '1') goto yy1003; if (yych <= '2') goto yy1004; if (yych <= '9') goto yy988; goto yy57; yy1003: YYDEBUG(1003, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy1005; if (yych <= ':') goto yy989; goto yy57; yy1004: YYDEBUG(1004, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '4') goto yy1005; if (yych == ':') goto yy989; goto yy57; yy1005: YYDEBUG(1005, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy57; YYDEBUG(1006, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy1007; if (yych <= '9') goto yy991; goto yy57; yy1007: YYDEBUG(1007, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy1008; if (yych <= ':') goto yy992; goto yy57; yy1008: YYDEBUG(1008, *YYCURSOR); yych = *++YYCURSOR; if (yych != ':') goto yy57; YYDEBUG(1009, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy1010; if (yych <= '6') goto yy1011; if (yych <= '9') goto yy842; goto yy57; yy1010: YYDEBUG(1010, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy843; if (yych <= '9') goto yy1012; goto yy843; yy1011: YYDEBUG(1011, *YYCURSOR); yych = *++YYCURSOR; if (yych != '0') goto yy843; yy1012: YYDEBUG(1012, *YYCURSOR); yyaccept = 23; yych = *(YYMARKER = ++YYCURSOR); if (yych != '.') goto yy843; YYDEBUG(1013, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; yy1014: YYDEBUG(1014, *YYCURSOR); yyaccept = 23; YYMARKER = ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 9) YYFILL(9); yych = *YYCURSOR; YYDEBUG(1015, *YYCURSOR); if (yych <= '-') { if (yych == '+') goto yy1017; if (yych <= ',') goto yy843; goto yy1017; } else { if (yych <= '9') { if (yych <= '/') goto yy843; goto yy1014; } else { if (yych != 'G') goto yy843; } } YYDEBUG(1016, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy1023; goto yy57; yy1017: YYDEBUG(1017, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '1') goto yy1018; if (yych <= '2') goto yy1019; if (yych <= '9') goto yy1020; goto yy57; yy1018: YYDEBUG(1018, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy843; if (yych <= '9') goto yy1020; if (yych <= ':') goto yy1021; goto yy843; yy1019: YYDEBUG(1019, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '5') { if (yych <= '/') goto yy843; if (yych >= '5') goto yy1022; } else { if (yych <= '9') goto yy842; if (yych <= ':') goto yy1021; goto yy843; } yy1020: YYDEBUG(1020, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy843; if (yych <= '5') goto yy1022; if (yych <= '9') goto yy842; if (yych >= ';') goto yy843; yy1021: YYDEBUG(1021, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy843; if (yych <= '5') goto yy1022; if (yych <= '9') goto yy842; goto yy843; yy1022: YYDEBUG(1022, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy843; if (yych <= '9') goto yy842; goto yy843; yy1023: YYDEBUG(1023, *YYCURSOR); yych = *++YYCURSOR; if (yych != 'T') goto yy57; YYDEBUG(1024, *YYCURSOR); yych = *++YYCURSOR; if (yych == '+') goto yy1017; if (yych == '-') goto yy1017; goto yy57; yy1025: YYDEBUG(1025, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy1026; if (yych != 'c') goto yy57; yy1026: YYDEBUG(1026, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych == '-') goto yy767; goto yy794; } else { if (yych <= 'E') goto yy880; if (yych == 'e') goto yy880; goto yy794; } yy1027: YYDEBUG(1027, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'V') goto yy1028; if (yych != 'v') goto yy57; yy1028: YYDEBUG(1028, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych == '-') goto yy767; goto yy794; } else { if (yych <= 'E') goto yy887; if (yych == 'e') goto yy887; goto yy794; } yy1029: YYDEBUG(1029, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy1030; if (yych != 't') goto yy57; yy1030: YYDEBUG(1030, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'N') { if (yych == '-') goto yy767; goto yy794; } else { if (yych <= 'O') goto yy893; if (yych == 'o') goto yy893; goto yy794; } yy1031: YYDEBUG(1031, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy1032; if (yych != 'p') goto yy57; yy1032: YYDEBUG(1032, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych == '-') goto yy767; goto yy794; } else { if (yych <= 'T') goto yy1033; if (yych != 't') goto yy794; } yy1033: YYDEBUG(1033, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych == '-') goto yy767; goto yy794; } else { if (yych <= 'E') goto yy899; if (yych == 'e') goto yy899; goto yy794; } yy1034: YYDEBUG(1034, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy1037; if (yych == 'g') goto yy1037; goto yy57; yy1035: YYDEBUG(1035, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy1036; if (yych != 'r') goto yy57; yy1036: YYDEBUG(1036, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'H') { if (yych == '-') goto yy767; goto yy794; } else { if (yych <= 'I') goto yy906; if (yych == 'i') goto yy906; goto yy794; } yy1037: YYDEBUG(1037, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych == '-') goto yy767; goto yy794; } else { if (yych <= 'U') goto yy908; if (yych == 'u') goto yy908; goto yy794; } yy1038: YYDEBUG(1038, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych == 'R') goto yy1039; if (yych <= 'X') goto yy57; goto yy1040; } else { if (yych <= 'r') { if (yych <= 'q') goto yy57; } else { if (yych == 'y') goto yy1040; goto yy57; } } yy1039: YYDEBUG(1039, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'B') { if (yych == '-') goto yy767; goto yy794; } else { if (yych <= 'C') goto yy912; if (yych == 'c') goto yy912; goto yy794; } yy1040: YYDEBUG(1040, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych == '-') goto yy767; goto yy794; yy1041: YYDEBUG(1041, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy1042; if (yych != 'b') goto yy57; yy1042: YYDEBUG(1042, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'Q') { if (yych == '-') goto yy767; goto yy794; } else { if (yych <= 'R') goto yy915; if (yych == 'r') goto yy915; goto yy794; } yy1043: YYDEBUG(1043, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych == 'L') goto yy1047; if (yych <= 'M') goto yy57; goto yy1046; } else { if (yych <= 'l') { if (yych <= 'k') goto yy57; goto yy1047; } else { if (yych == 'n') goto yy1046; goto yy57; } } yy1044: YYDEBUG(1044, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy1045; if (yych != 'n') goto yy57; yy1045: YYDEBUG(1045, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych == '-') goto yy767; goto yy794; } else { if (yych <= 'U') goto yy922; if (yych == 'u') goto yy922; goto yy794; } yy1046: YYDEBUG(1046, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych == '-') goto yy767; goto yy794; } else { if (yych <= 'E') goto yy884; if (yych == 'e') goto yy884; goto yy794; } yy1047: YYDEBUG(1047, *YYCURSOR); yyaccept = 20; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'X') { if (yych == '-') goto yy767; goto yy794; } else { if (yych <= 'Y') goto yy884; if (yych == 'y') goto yy884; goto yy794; } yy1048: YYDEBUG(1048, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '.') { if (yych <= '\t') { if (yych <= 0x08) goto yy578; goto yy731; } else { if (yych <= ',') goto yy578; if (yych <= '-') goto yy732; goto yy731; } } else { if (yych <= 'U') { if (yych <= '/') goto yy730; if (yych <= 'T') goto yy578; goto yy78; } else { if (yych == 'u') goto yy78; goto yy578; } } yy1049: YYDEBUG(1049, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'P') { if (yych == 'C') goto yy129; if (yych <= 'O') goto yy57; goto yy586; } else { if (yych <= 'c') { if (yych <= 'b') goto yy57; goto yy129; } else { if (yych == 'p') goto yy586; goto yy57; } } yy1050: YYDEBUG(1050, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '9') { if (yych <= ',') { if (yych == '\t') goto yy1052; goto yy1054; } else { if (yych <= '-') goto yy1051; if (yych <= '.') goto yy731; if (yych <= '/') goto yy730; goto yy741; } } else { if (yych <= 'q') { if (yych == 'n') goto yy470; goto yy1054; } else { if (yych <= 'r') goto yy471; if (yych <= 's') goto yy464; if (yych <= 't') goto yy468; goto yy1054; } } yy1051: YYDEBUG(1051, *YYCURSOR); yych = *++YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case '0': goto yy1055; case '1': goto yy1056; case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy618; case 'A': case 'a': goto yy622; case 'D': case 'd': goto yy626; case 'F': case 'f': goto yy620; case 'J': case 'j': goto yy619; case 'M': case 'm': goto yy621; case 'N': case 'n': goto yy625; case 'O': case 'o': goto yy624; case 'S': case 's': goto yy623; default: goto yy578; } yy1052: YYDEBUG(1052, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy1054; if (yych <= '0') goto yy736; if (yych <= '1') goto yy737; if (yych <= '9') goto yy738; goto yy1054; yy1053: YYDEBUG(1053, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 13) YYFILL(13); yych = *YYCURSOR; yy1054: YYDEBUG(1054, *YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case '\t': case ' ': goto yy1053; case '-': case '.': goto yy577; case 'A': case 'a': goto yy574; case 'D': case 'd': goto yy466; case 'F': case 'f': goto yy467; case 'H': case 'h': goto yy64; case 'I': goto yy475; case 'J': case 'j': goto yy479; case 'M': case 'm': goto yy465; case 'N': case 'n': goto yy482; case 'O': case 'o': goto yy481; case 'S': case 's': goto yy463; case 'T': case 't': goto yy69; case 'V': goto yy477; case 'W': case 'w': goto yy68; case 'X': goto yy478; case 'Y': case 'y': goto yy67; default: goto yy57; } yy1055: YYDEBUG(1055, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '.') { if (yych <= ',') goto yy57; if (yych <= '-') goto yy655; goto yy602; } else { if (yych <= '/') goto yy57; if (yych <= '9') goto yy1057; goto yy57; } yy1056: YYDEBUG(1056, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '.') { if (yych <= ',') goto yy57; if (yych <= '-') goto yy655; goto yy602; } else { if (yych <= '/') goto yy57; if (yych >= '3') goto yy57; } yy1057: YYDEBUG(1057, *YYCURSOR); yych = *++YYCURSOR; if (yych <= ',') goto yy57; if (yych <= '-') goto yy1058; if (yych <= '.') goto yy602; goto yy57; yy1058: YYDEBUG(1058, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '2') { if (yych <= '/') goto yy57; if (yych >= '1') goto yy1060; } else { if (yych <= '3') goto yy1061; if (yych <= '9') goto yy659; goto yy57; } YYDEBUG(1059, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy657; if (yych <= '9') goto yy1062; if (yych <= 'm') goto yy657; goto yy661; } else { if (yych <= 'r') { if (yych <= 'q') goto yy657; goto yy662; } else { if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; goto yy657; } } yy1060: YYDEBUG(1060, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy657; if (yych <= '9') goto yy1062; if (yych <= 'm') goto yy657; goto yy661; } else { if (yych <= 'r') { if (yych <= 'q') goto yy657; goto yy662; } else { if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; goto yy657; } } yy1061: YYDEBUG(1061, *YYCURSOR); yyaccept = 13; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '1') { if (yych <= '/') goto yy657; } else { if (yych <= '9') goto yy604; if (yych <= 'm') goto yy657; goto yy661; } } else { if (yych <= 'r') { if (yych <= 'q') goto yy657; goto yy662; } else { if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; goto yy657; } } yy1062: YYDEBUG(1062, *YYCURSOR); yyaccept = 15; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'n') { if (yych <= '/') goto yy764; if (yych <= '9') goto yy605; if (yych <= 'm') goto yy764; goto yy661; } else { if (yych <= 'r') { if (yych <= 'q') goto yy764; goto yy662; } else { if (yych <= 's') goto yy660; if (yych <= 't') goto yy663; goto yy764; } } yy1063: YYDEBUG(1063, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '9') { if (yych <= '-') { if (yych == '\t') goto yy1052; if (yych <= ',') goto yy1054; goto yy1051; } else { if (yych <= '.') goto yy1064; if (yych <= '/') goto yy730; if (yych <= '5') goto yy1066; goto yy741; } } else { if (yych <= 'q') { if (yych <= ':') goto yy1065; if (yych == 'n') goto yy470; goto yy1054; } else { if (yych <= 'r') goto yy471; if (yych <= 's') goto yy464; if (yych <= 't') goto yy468; goto yy1054; } } yy1064: YYDEBUG(1064, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '1') { if (yych <= '/') goto yy578; if (yych <= '0') goto yy1088; goto yy1089; } else { if (yych <= '5') goto yy1090; if (yych <= '9') goto yy1091; goto yy578; } yy1065: YYDEBUG(1065, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy1083; if (yych <= '9') goto yy1084; goto yy57; yy1066: YYDEBUG(1066, *YYCURSOR); yych = *++YYCURSOR; if (yych == '-') goto yy785; if (yych <= '/') goto yy61; if (yych >= ':') goto yy61; YYDEBUG(1067, *YYCURSOR); yyaccept = 24; yych = *(YYMARKER = ++YYCURSOR); YYDEBUG(-1, yych); switch (yych) { case '\t': case ' ': case 'A': case 'D': case 'F': case 'H': case 'I': case 'J': case 'M': case 'N': case 'O': case 'S': case 'T': case 'V': case 'X': case 'Y': case 'a': case 'd': case 'f': case 'h': case 'j': case 'm': case 'n': case 'o': case 's': case 't': case 'w': case 'y': goto yy791; case '-': goto yy788; case '.': goto yy792; case '/': goto yy789; case '0': goto yy1069; case '1': goto yy1070; case '2': goto yy1071; case '3': goto yy1072; case '4': case '5': goto yy1073; case '6': goto yy1074; case '7': case '8': case '9': goto yy55; case ':': goto yy807; case 'W': goto yy810; default: goto yy1068; } yy1068: YYDEBUG(1068, *YYCURSOR); #line 1207 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("gnunocolon"); TIMELIB_INIT; switch (s->time->have_time) { case 0: s->time->h = timelib_get_nr((char **) &ptr, 2); s->time->i = timelib_get_nr((char **) &ptr, 2); s->time->s = 0; break; case 1: s->time->y = timelib_get_nr((char **) &ptr, 4); break; default: TIMELIB_DEINIT; add_error(s, "Double time specification"); return TIMELIB_ERROR; } s->time->have_time++; TIMELIB_DEINIT; return TIMELIB_GNU_NOCOLON; } #line 15748 "ext/date/lib/parse_date.c" yy1069: YYDEBUG(1069, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '0') goto yy1081; if (yych <= '9') goto yy1082; goto yy61; yy1070: YYDEBUG(1070, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '2') goto yy1080; if (yych <= '9') goto yy1079; goto yy61; yy1071: YYDEBUG(1071, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '9') goto yy1079; goto yy61; yy1072: YYDEBUG(1072, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '5') goto yy1077; if (yych <= '6') goto yy1078; if (yych <= '9') goto yy1075; goto yy61; yy1073: YYDEBUG(1073, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '9') goto yy1075; goto yy61; yy1074: YYDEBUG(1074, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy61; if (yych <= '0') goto yy1075; if (yych <= '9') goto yy55; goto yy61; yy1075: YYDEBUG(1075, *YYCURSOR); yyaccept = 25; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 2) { goto yy55; } if (yych <= 'W') { if (yych <= 'F') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych >= ' ') goto yy61; } else { if (yych == 'D') goto yy61; if (yych >= 'F') goto yy61; } } else { if (yych <= 'M') { if (yych == 'H') goto yy61; if (yych >= 'M') goto yy61; } else { if (yych <= 'R') goto yy1076; if (yych <= 'T') goto yy61; if (yych >= 'W') goto yy61; } } } else { if (yych <= 'h') { if (yych <= 'd') { if (yych == 'Y') goto yy61; if (yych >= 'd') goto yy61; } else { if (yych == 'f') goto yy61; if (yych >= 'h') goto yy61; } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych >= 's') goto yy61; } else { if (yych <= 'w') { if (yych >= 'w') goto yy61; } else { if (yych == 'y') goto yy61; } } } } yy1076: YYDEBUG(1076, *YYCURSOR); #line 1253 "ext/date/lib/parse_date.re" { int tz_not_found; DEBUG_OUTPUT("iso8601nocolon"); TIMELIB_INIT; TIMELIB_HAVE_TIME(); s->time->h = timelib_get_nr((char **) &ptr, 2); s->time->i = timelib_get_nr((char **) &ptr, 2); s->time->s = timelib_get_nr((char **) &ptr, 2); if (*ptr != '\0') { s->time->z = timelib_get_zone((char **) &ptr, &s->time->dst, s->time, &tz_not_found, s->tzdb); if (tz_not_found) { add_error(s, "The timezone could not be found in the database"); } } TIMELIB_DEINIT; return TIMELIB_ISO_NOCOLON; } #line 15859 "ext/date/lib/parse_date.c" yy1077: YYDEBUG(1077, *YYCURSOR); yyaccept = 25; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'V') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy1076; goto yy61; } else { if (yych <= '/') goto yy1076; if (yych <= '9') goto yy821; if (yych <= 'C') goto yy1076; goto yy61; } } else { if (yych <= 'H') { if (yych == 'F') goto yy61; if (yych <= 'G') goto yy1076; goto yy61; } else { if (yych <= 'M') { if (yych <= 'L') goto yy1076; goto yy61; } else { if (yych <= 'R') goto yy1076; if (yych <= 'T') goto yy61; goto yy1076; } } } } else { if (yych <= 'h') { if (yych <= 'c') { if (yych == 'X') goto yy1076; if (yych <= 'Y') goto yy61; goto yy1076; } else { if (yych <= 'e') { if (yych <= 'd') goto yy61; goto yy1076; } else { if (yych == 'g') goto yy1076; goto yy61; } } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych <= 'r') goto yy1076; goto yy61; } else { if (yych <= 'w') { if (yych <= 'v') goto yy1076; goto yy61; } else { if (yych == 'y') goto yy61; goto yy1076; } } } } yy1078: YYDEBUG(1078, *YYCURSOR); yyaccept = 25; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'V') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy1076; goto yy61; } else { if (yych <= '6') { if (yych <= '/') goto yy1076; goto yy821; } else { if (yych <= '9') goto yy55; if (yych <= 'C') goto yy1076; goto yy61; } } } else { if (yych <= 'H') { if (yych == 'F') goto yy61; if (yych <= 'G') goto yy1076; goto yy61; } else { if (yych <= 'M') { if (yych <= 'L') goto yy1076; goto yy61; } else { if (yych <= 'R') goto yy1076; if (yych <= 'T') goto yy61; goto yy1076; } } } } else { if (yych <= 'h') { if (yych <= 'c') { if (yych == 'X') goto yy1076; if (yych <= 'Y') goto yy61; goto yy1076; } else { if (yych <= 'e') { if (yych <= 'd') goto yy61; goto yy1076; } else { if (yych == 'g') goto yy1076; goto yy61; } } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych <= 'r') goto yy1076; goto yy61; } else { if (yych <= 'w') { if (yych <= 'v') goto yy1076; goto yy61; } else { if (yych == 'y') goto yy61; goto yy1076; } } } } yy1079: YYDEBUG(1079, *YYCURSOR); yyaccept = 25; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'V') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy1076; goto yy61; } else { if (yych <= '/') goto yy1076; if (yych <= '9') goto yy821; if (yych <= 'C') goto yy1076; goto yy61; } } else { if (yych <= 'H') { if (yych == 'F') goto yy61; if (yych <= 'G') goto yy1076; goto yy61; } else { if (yych <= 'M') { if (yych <= 'L') goto yy1076; goto yy61; } else { if (yych <= 'R') goto yy1076; if (yych <= 'T') goto yy61; goto yy1076; } } } } else { if (yych <= 'h') { if (yych <= 'c') { if (yych == 'X') goto yy1076; if (yych <= 'Y') goto yy61; goto yy1076; } else { if (yych <= 'e') { if (yych <= 'd') goto yy61; goto yy1076; } else { if (yych == 'g') goto yy1076; goto yy61; } } } else { if (yych <= 't') { if (yych == 'm') goto yy61; if (yych <= 'r') goto yy1076; goto yy61; } else { if (yych <= 'w') { if (yych <= 'v') goto yy1076; goto yy61; } else { if (yych == 'y') goto yy61; goto yy1076; } } } } yy1080: YYDEBUG(1080, *YYCURSOR); yyaccept = 25; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych <= '9') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy1076; goto yy61; } else { if (yych <= '0') { if (yych <= '/') goto yy1076; goto yy845; } else { if (yych <= '2') goto yy846; if (yych <= '3') goto yy847; goto yy821; } } } else { if (yych <= 'G') { if (yych <= 'D') { if (yych <= 'C') goto yy1076; goto yy61; } else { if (yych == 'F') goto yy61; goto yy1076; } } else { if (yych <= 'L') { if (yych <= 'H') goto yy61; goto yy1076; } else { if (yych <= 'M') goto yy61; if (yych <= 'R') goto yy1076; goto yy61; } } } } else { if (yych <= 'g') { if (yych <= 'Y') { if (yych == 'W') goto yy61; if (yych <= 'X') goto yy1076; goto yy61; } else { if (yych <= 'd') { if (yych <= 'c') goto yy1076; goto yy61; } else { if (yych == 'f') goto yy61; goto yy1076; } } } else { if (yych <= 't') { if (yych <= 'l') { if (yych <= 'h') goto yy61; goto yy1076; } else { if (yych <= 'm') goto yy61; if (yych <= 'r') goto yy1076; goto yy61; } } else { if (yych <= 'w') { if (yych <= 'v') goto yy1076; goto yy61; } else { if (yych == 'y') goto yy61; goto yy1076; } } } } yy1081: YYDEBUG(1081, *YYCURSOR); yyaccept = 25; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych <= '9') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy1076; goto yy61; } else { if (yych <= '0') { if (yych <= '/') goto yy1076; goto yy877; } else { if (yych <= '2') goto yy846; if (yych <= '3') goto yy847; goto yy821; } } } else { if (yych <= 'G') { if (yych <= 'D') { if (yych <= 'C') goto yy1076; goto yy61; } else { if (yych == 'F') goto yy61; goto yy1076; } } else { if (yych <= 'L') { if (yych <= 'H') goto yy61; goto yy1076; } else { if (yych <= 'M') goto yy61; if (yych <= 'R') goto yy1076; goto yy61; } } } } else { if (yych <= 'g') { if (yych <= 'Y') { if (yych == 'W') goto yy61; if (yych <= 'X') goto yy1076; goto yy61; } else { if (yych <= 'd') { if (yych <= 'c') goto yy1076; goto yy61; } else { if (yych == 'f') goto yy61; goto yy1076; } } } else { if (yych <= 't') { if (yych <= 'l') { if (yych <= 'h') goto yy61; goto yy1076; } else { if (yych <= 'm') goto yy61; if (yych <= 'r') goto yy1076; goto yy61; } } else { if (yych <= 'w') { if (yych <= 'v') goto yy1076; goto yy61; } else { if (yych == 'y') goto yy61; goto yy1076; } } } } yy1082: YYDEBUG(1082, *YYCURSOR); yyaccept = 25; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych <= '9') { if (yych <= ' ') { if (yych == '\t') goto yy61; if (yych <= 0x1F) goto yy1076; goto yy61; } else { if (yych <= '0') { if (yych <= '/') goto yy1076; goto yy845; } else { if (yych <= '2') goto yy846; if (yych <= '3') goto yy847; goto yy821; } } } else { if (yych <= 'G') { if (yych <= 'D') { if (yych <= 'C') goto yy1076; goto yy61; } else { if (yych == 'F') goto yy61; goto yy1076; } } else { if (yych <= 'L') { if (yych <= 'H') goto yy61; goto yy1076; } else { if (yych <= 'M') goto yy61; if (yych <= 'R') goto yy1076; goto yy61; } } } } else { if (yych <= 'g') { if (yych <= 'Y') { if (yych == 'W') goto yy61; if (yych <= 'X') goto yy1076; goto yy61; } else { if (yych <= 'd') { if (yych <= 'c') goto yy1076; goto yy61; } else { if (yych == 'f') goto yy61; goto yy1076; } } } else { if (yych <= 't') { if (yych <= 'l') { if (yych <= 'h') goto yy61; goto yy1076; } else { if (yych <= 'm') goto yy61; if (yych <= 'r') goto yy1076; goto yy61; } } else { if (yych <= 'w') { if (yych <= 'v') goto yy1076; goto yy61; } else { if (yych == 'y') goto yy61; goto yy1076; } } } } yy1083: YYDEBUG(1083, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy1085; goto yy491; } else { if (yych <= '9') goto yy1084; if (yych <= ':') goto yy1085; goto yy491; } yy1084: YYDEBUG(1084, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy1085; if (yych != ':') goto yy491; yy1085: YYDEBUG(1085, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy1086; if (yych <= '6') goto yy1087; if (yych <= '9') goto yy496; goto yy57; yy1086: YYDEBUG(1086, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy497; if (yych <= '/') goto yy491; if (yych <= '9') goto yy496; goto yy491; yy1087: YYDEBUG(1087, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy497; if (yych == '0') goto yy496; goto yy491; yy1088: YYDEBUG(1088, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ',') goto yy491; if (yych <= '-') goto yy602; goto yy1092; } else { if (yych <= '/') goto yy491; if (yych <= '9') goto yy1091; if (yych <= ':') goto yy1085; goto yy491; } yy1089: YYDEBUG(1089, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') goto yy491; if (yych <= '-') goto yy602; if (yych <= '.') goto yy1092; goto yy491; } else { if (yych <= '2') goto yy1091; if (yych <= '9') goto yy1084; if (yych <= ':') goto yy1085; goto yy491; } yy1090: YYDEBUG(1090, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ',') goto yy491; if (yych <= '-') goto yy602; goto yy1092; } else { if (yych <= '/') goto yy491; if (yych <= '9') goto yy1084; if (yych <= ':') goto yy1085; goto yy491; } yy1091: YYDEBUG(1091, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ',') goto yy491; if (yych <= '-') goto yy602; } else { if (yych == ':') goto yy1085; goto yy491; } yy1092: YYDEBUG(1092, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '5') goto yy1093; if (yych <= '6') goto yy1094; if (yych <= '9') goto yy610; goto yy57; yy1093: YYDEBUG(1093, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy497; if (yych <= '/') goto yy491; if (yych <= '9') goto yy1095; goto yy491; yy1094: YYDEBUG(1094, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych == '.') goto yy497; goto yy491; } else { if (yych <= '0') goto yy1095; if (yych <= '9') goto yy611; goto yy491; } yy1095: YYDEBUG(1095, *YYCURSOR); yyaccept = 11; yych = *(YYMARKER = ++YYCURSOR); if (yych == '.') goto yy497; if (yych <= '/') goto yy491; if (yych <= '9') goto yy605; goto yy491; yy1096: YYDEBUG(1096, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '9') { if (yych <= '-') { if (yych == '\t') goto yy460; if (yych <= ',') goto yy462; goto yy1051; } else { if (yych <= '.') goto yy474; if (yych <= '/') goto yy472; if (yych <= '5') goto yy1066; goto yy741; } } else { if (yych <= 'q') { if (yych <= ':') goto yy483; if (yych == 'n') goto yy470; goto yy462; } else { if (yych <= 'r') goto yy471; if (yych <= 's') goto yy464; if (yych <= 't') goto yy468; goto yy462; } } yy1097: YYDEBUG(1097, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '9') { if (yych <= '-') { if (yych == '\t') goto yy1052; if (yych <= ',') goto yy1054; goto yy1051; } else { if (yych <= '.') goto yy1064; if (yych <= '/') goto yy472; if (yych <= '5') goto yy1066; goto yy741; } } else { if (yych <= 'q') { if (yych <= ':') goto yy1065; if (yych == 'n') goto yy470; goto yy1054; } else { if (yych <= 'r') goto yy471; if (yych <= 's') goto yy464; if (yych <= 't') goto yy468; goto yy1054; } } yy1098: YYDEBUG(1098, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy142; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'e') goto yy1099; if (yych <= 'z') goto yy142; goto yy4; } } yy1099: YYDEBUG(1099, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'V') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'U') goto yy143; } } else { if (yych <= 'u') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'v') goto yy1100; if (yych <= 'z') goto yy143; goto yy4; } } yy1100: YYDEBUG(1100, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'I') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'H') goto yy144; } } else { if (yych <= 'h') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'i') goto yy1101; if (yych <= 'z') goto yy144; goto yy4; } } yy1101: YYDEBUG(1101, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'N') goto yy145; } } else { if (yych <= 'n') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'o') goto yy1102; if (yych <= 'z') goto yy145; goto yy4; } } yy1102: YYDEBUG(1102, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'U') goto yy1103; if (yych != 'u') goto yy4; } yy1103: YYDEBUG(1103, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy1104; if (yych != 's') goto yy57; yy1104: YYDEBUG(1104, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\t') goto yy1105; if (yych != ' ') goto yy57; yy1105: YYDEBUG(1105, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 11) YYFILL(11); yych = *YYCURSOR; yy1106: YYDEBUG(1106, *YYCURSOR); if (yych <= 'W') { if (yych <= 'F') { if (yych <= ' ') { if (yych == '\t') goto yy1105; if (yych <= 0x1F) goto yy57; goto yy1105; } else { if (yych == 'D') goto yy1110; if (yych <= 'E') goto yy57; goto yy1111; } } else { if (yych <= 'M') { if (yych == 'H') goto yy1109; if (yych <= 'L') goto yy57; goto yy1108; } else { if (yych <= 'S') { if (yych <= 'R') goto yy57; } else { if (yych <= 'T') goto yy1114; if (yych <= 'V') goto yy57; goto yy1113; } } } } else { if (yych <= 'l') { if (yych <= 'd') { if (yych == 'Y') goto yy1112; if (yych <= 'c') goto yy57; goto yy1110; } else { if (yych <= 'f') { if (yych <= 'e') goto yy57; goto yy1111; } else { if (yych == 'h') goto yy1109; goto yy57; } } } else { if (yych <= 't') { if (yych <= 'm') goto yy1108; if (yych <= 'r') goto yy57; if (yych >= 't') goto yy1114; } else { if (yych <= 'w') { if (yych <= 'v') goto yy57; goto yy1113; } else { if (yych == 'y') goto yy1112; goto yy57; } } } } yy1107: YYDEBUG(1107, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= 'D') { if (yych == 'A') goto yy1179; goto yy57; } else { if (yych <= 'E') goto yy1180; if (yych <= 'T') goto yy57; goto yy1178; } } else { if (yych <= 'd') { if (yych == 'a') goto yy1179; goto yy57; } else { if (yych <= 'e') goto yy1180; if (yych == 'u') goto yy1178; goto yy57; } } yy1108: YYDEBUG(1108, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'I') goto yy1170; if (yych <= 'N') goto yy57; goto yy1169; } else { if (yych <= 'i') { if (yych <= 'h') goto yy57; goto yy1170; } else { if (yych == 'o') goto yy1169; goto yy57; } } yy1109: YYDEBUG(1109, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy1167; if (yych == 'o') goto yy1167; goto yy57; yy1110: YYDEBUG(1110, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1166; if (yych == 'a') goto yy1166; goto yy57; yy1111: YYDEBUG(1111, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych == 'O') goto yy1151; if (yych <= 'Q') goto yy57; goto yy1150; } else { if (yych <= 'o') { if (yych <= 'n') goto yy57; goto yy1151; } else { if (yych == 'r') goto yy1150; goto yy57; } } yy1112: YYDEBUG(1112, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy1147; if (yych == 'e') goto yy1147; goto yy57; yy1113: YYDEBUG(1113, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy1133; if (yych == 'e') goto yy1133; goto yy57; yy1114: YYDEBUG(1114, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'H') goto yy1115; if (yych <= 'T') goto yy57; goto yy1116; } else { if (yych <= 'h') { if (yych <= 'g') goto yy57; } else { if (yych == 'u') goto yy1116; goto yy57; } } yy1115: YYDEBUG(1115, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy1128; if (yych == 'u') goto yy1128; goto yy57; yy1116: YYDEBUG(1116, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy1117; if (yych != 'e') goto yy57; yy1117: YYDEBUG(1117, *YYCURSOR); yyaccept = 26; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ' ') { if (yych == '\t') goto yy1119; if (yych >= ' ') goto yy1119; } else { if (yych <= 'S') { if (yych >= 'S') goto yy1121; } else { if (yych == 's') goto yy1121; } } yy1118: YYDEBUG(1118, *YYCURSOR); #line 1649 "ext/date/lib/parse_date.re" { timelib_sll i; int behavior = 0; DEBUG_OUTPUT("relativetext"); TIMELIB_INIT; TIMELIB_HAVE_RELATIVE(); while(*ptr) { i = timelib_get_relative_text((char **) &ptr, &behavior); timelib_eat_spaces((char **) &ptr); timelib_set_relative((char **) &ptr, i, behavior, s); } TIMELIB_DEINIT; return TIMELIB_RELATIVE; } #line 16773 "ext/date/lib/parse_date.c" yy1119: YYDEBUG(1119, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; YYDEBUG(1120, *YYCURSOR); if (yych <= ' ') { if (yych == '\t') goto yy1119; if (yych <= 0x1F) goto yy57; goto yy1119; } else { if (yych <= 'O') { if (yych <= 'N') goto yy57; goto yy1125; } else { if (yych == 'o') goto yy1125; goto yy57; } } yy1121: YYDEBUG(1121, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy1122; if (yych != 'd') goto yy57; yy1122: YYDEBUG(1122, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1123; if (yych != 'a') goto yy57; yy1123: YYDEBUG(1123, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy1124; if (yych != 'y') goto yy57; yy1124: YYDEBUG(1124, *YYCURSOR); yyaccept = 26; yych = *(YYMARKER = ++YYCURSOR); if (yych == '\t') goto yy1119; if (yych == ' ') goto yy1119; goto yy1118; yy1125: YYDEBUG(1125, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy1126; if (yych != 'f') goto yy57; yy1126: YYDEBUG(1126, *YYCURSOR); ++YYCURSOR; YYDEBUG(1127, *YYCURSOR); #line 1122 "ext/date/lib/parse_date.re" { timelib_sll i; int behavior = 0; DEBUG_OUTPUT("weekdayof"); TIMELIB_INIT; TIMELIB_HAVE_RELATIVE(); TIMELIB_HAVE_SPECIAL_RELATIVE(); i = timelib_get_relative_text((char **) &ptr, &behavior); timelib_eat_spaces((char **) &ptr); if (i > 0) { /* first, second... etc */ s->time->relative.special.type = TIMELIB_SPECIAL_DAY_OF_WEEK_IN_MONTH; timelib_set_relative((char **) &ptr, i, 1, s); } else { /* last */ s->time->relative.special.type = TIMELIB_SPECIAL_LAST_DAY_OF_WEEK_IN_MONTH; timelib_set_relative((char **) &ptr, i, behavior, s); } TIMELIB_DEINIT; return TIMELIB_WEEK_DAY_OF_MONTH; } #line 16845 "ext/date/lib/parse_date.c" yy1128: YYDEBUG(1128, *YYCURSOR); yyaccept = 26; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ' ') { if (yych == '\t') goto yy1119; if (yych <= 0x1F) goto yy1118; goto yy1119; } else { if (yych <= 'R') { if (yych <= 'Q') goto yy1118; } else { if (yych != 'r') goto yy1118; } } YYDEBUG(1129, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy1130; if (yych != 's') goto yy57; yy1130: YYDEBUG(1130, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy1131; if (yych != 'd') goto yy57; yy1131: YYDEBUG(1131, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1132; if (yych != 'a') goto yy57; yy1132: YYDEBUG(1132, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy1124; if (yych == 'y') goto yy1124; goto yy57; yy1133: YYDEBUG(1133, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= 'C') goto yy57; if (yych <= 'D') goto yy1135; } else { if (yych <= 'c') goto yy57; if (yych <= 'd') goto yy1135; if (yych >= 'f') goto yy57; } YYDEBUG(1134, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'K') goto yy1141; if (yych == 'k') goto yy1141; goto yy57; yy1135: YYDEBUG(1135, *YYCURSOR); yyaccept = 26; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ' ') { if (yych == '\t') goto yy1119; if (yych <= 0x1F) goto yy1118; goto yy1119; } else { if (yych <= 'N') { if (yych <= 'M') goto yy1118; } else { if (yych != 'n') goto yy1118; } } YYDEBUG(1136, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy1137; if (yych != 'e') goto yy57; yy1137: YYDEBUG(1137, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy1138; if (yych != 's') goto yy57; yy1138: YYDEBUG(1138, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy1139; if (yych != 'd') goto yy57; yy1139: YYDEBUG(1139, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1140; if (yych != 'a') goto yy57; yy1140: YYDEBUG(1140, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy1124; if (yych == 'y') goto yy1124; goto yy57; yy1141: YYDEBUG(1141, *YYCURSOR); yyaccept = 27; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych == 'D') goto yy1144; if (yych >= 'S') goto yy1143; } else { if (yych <= 'd') { if (yych >= 'd') goto yy1144; } else { if (yych == 's') goto yy1143; } } yy1142: YYDEBUG(1142, *YYCURSOR); #line 1625 "ext/date/lib/parse_date.re" { timelib_sll i; int behavior = 0; DEBUG_OUTPUT("relativetextweek"); TIMELIB_INIT; TIMELIB_HAVE_RELATIVE(); while(*ptr) { i = timelib_get_relative_text((char **) &ptr, &behavior); timelib_eat_spaces((char **) &ptr); timelib_set_relative((char **) &ptr, i, behavior, s); s->time->relative.weekday_behavior = 2; /* to handle the format weekday + last/this/next week */ if (s->time->relative.have_weekday_relative == 0) { TIMELIB_HAVE_WEEKDAY_RELATIVE(); s->time->relative.weekday = 1; } } TIMELIB_DEINIT; return TIMELIB_RELATIVE; } #line 16976 "ext/date/lib/parse_date.c" yy1143: YYDEBUG(1143, *YYCURSOR); yych = *++YYCURSOR; goto yy1118; yy1144: YYDEBUG(1144, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1145; if (yych != 'a') goto yy57; yy1145: YYDEBUG(1145, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy1146; if (yych != 'y') goto yy57; yy1146: YYDEBUG(1146, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy1143; if (yych == 's') goto yy1143; goto yy1118; yy1147: YYDEBUG(1147, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1148; if (yych != 'a') goto yy57; yy1148: YYDEBUG(1148, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy1149; if (yych != 'r') goto yy57; yy1149: YYDEBUG(1149, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy1143; if (yych == 's') goto yy1143; goto yy1118; yy1150: YYDEBUG(1150, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy1163; if (yych == 'i') goto yy1163; goto yy57; yy1151: YYDEBUG(1151, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy1152; if (yych != 'r') goto yy57; yy1152: YYDEBUG(1152, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy1153; if (yych != 't') goto yy57; yy1153: YYDEBUG(1153, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych == 'H') goto yy1155; if (yych <= 'M') goto yy57; } else { if (yych <= 'h') { if (yych <= 'g') goto yy57; goto yy1155; } else { if (yych != 'n') goto yy57; } } YYDEBUG(1154, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy1160; if (yych == 'i') goto yy1160; goto yy57; yy1155: YYDEBUG(1155, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy1156; if (yych != 'n') goto yy57; yy1156: YYDEBUG(1156, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy1157; if (yych != 'i') goto yy57; yy1157: YYDEBUG(1157, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy1158; if (yych != 'g') goto yy57; yy1158: YYDEBUG(1158, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy1159; if (yych != 'h') goto yy57; yy1159: YYDEBUG(1159, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy1149; if (yych == 't') goto yy1149; goto yy57; yy1160: YYDEBUG(1160, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy1161; if (yych != 'g') goto yy57; yy1161: YYDEBUG(1161, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy1162; if (yych != 'h') goto yy57; yy1162: YYDEBUG(1162, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy1149; if (yych == 't') goto yy1149; goto yy57; yy1163: YYDEBUG(1163, *YYCURSOR); yyaccept = 26; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ' ') { if (yych == '\t') goto yy1119; if (yych <= 0x1F) goto yy1118; goto yy1119; } else { if (yych <= 'D') { if (yych <= 'C') goto yy1118; } else { if (yych != 'd') goto yy1118; } } YYDEBUG(1164, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1165; if (yych != 'a') goto yy57; yy1165: YYDEBUG(1165, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy1124; if (yych == 'y') goto yy1124; goto yy57; yy1166: YYDEBUG(1166, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy1149; if (yych == 'y') goto yy1149; goto yy57; yy1167: YYDEBUG(1167, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy1168; if (yych != 'u') goto yy57; yy1168: YYDEBUG(1168, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy1149; if (yych == 'r') goto yy1149; goto yy57; yy1169: YYDEBUG(1169, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy1174; if (yych == 'n') goto yy1174; goto yy57; yy1170: YYDEBUG(1170, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy1171; if (yych != 'n') goto yy57; yy1171: YYDEBUG(1171, *YYCURSOR); yyaccept = 26; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'U') { if (yych == 'S') goto yy1143; if (yych <= 'T') goto yy1118; } else { if (yych <= 's') { if (yych <= 'r') goto yy1118; goto yy1143; } else { if (yych != 'u') goto yy1118; } } YYDEBUG(1172, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy1173; if (yych != 't') goto yy57; yy1173: YYDEBUG(1173, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy1149; if (yych == 'e') goto yy1149; goto yy57; yy1174: YYDEBUG(1174, *YYCURSOR); yyaccept = 26; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych <= 0x1F) { if (yych == '\t') goto yy1119; goto yy1118; } else { if (yych <= ' ') goto yy1119; if (yych <= 'C') goto yy1118; } } else { if (yych <= 'c') { if (yych == 'T') goto yy1176; goto yy1118; } else { if (yych <= 'd') goto yy1175; if (yych == 't') goto yy1176; goto yy1118; } } yy1175: YYDEBUG(1175, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1177; if (yych == 'a') goto yy1177; goto yy57; yy1176: YYDEBUG(1176, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy1149; if (yych == 'h') goto yy1149; goto yy57; yy1177: YYDEBUG(1177, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy1124; if (yych == 'y') goto yy1124; goto yy57; yy1178: YYDEBUG(1178, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy1189; if (yych == 'n') goto yy1189; goto yy57; yy1179: YYDEBUG(1179, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy1184; if (yych == 't') goto yy1184; goto yy57; yy1180: YYDEBUG(1180, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy1181; if (yych != 'c') goto yy57; yy1181: YYDEBUG(1181, *YYCURSOR); yyaccept = 26; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych == 'O') goto yy1182; if (yych <= 'R') goto yy1118; goto yy1143; } else { if (yych <= 'o') { if (yych <= 'n') goto yy1118; } else { if (yych == 's') goto yy1143; goto yy1118; } } yy1182: YYDEBUG(1182, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy1183; if (yych != 'n') goto yy57; yy1183: YYDEBUG(1183, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy1149; if (yych == 'd') goto yy1149; goto yy57; yy1184: YYDEBUG(1184, *YYCURSOR); yyaccept = 26; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ' ') { if (yych == '\t') goto yy1119; if (yych <= 0x1F) goto yy1118; goto yy1119; } else { if (yych <= 'U') { if (yych <= 'T') goto yy1118; } else { if (yych != 'u') goto yy1118; } } YYDEBUG(1185, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy1186; if (yych != 'r') goto yy57; yy1186: YYDEBUG(1186, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy1187; if (yych != 'd') goto yy57; yy1187: YYDEBUG(1187, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1188; if (yych != 'a') goto yy57; yy1188: YYDEBUG(1188, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy1124; if (yych == 'y') goto yy1124; goto yy57; yy1189: YYDEBUG(1189, *YYCURSOR); yyaccept = 26; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ' ') { if (yych == '\t') goto yy1119; if (yych <= 0x1F) goto yy1118; goto yy1119; } else { if (yych <= 'D') { if (yych <= 'C') goto yy1118; } else { if (yych != 'd') goto yy1118; } } YYDEBUG(1190, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1191; if (yych != 'a') goto yy57; yy1191: YYDEBUG(1191, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy1124; if (yych == 'y') goto yy1124; goto yy57; yy1192: YYDEBUG(1192, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'E') goto yy1099; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'd') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'e') goto yy1193; if (yych <= 'z') goto yy147; goto yy4; } } } yy1193: YYDEBUG(1193, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'U') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'V') goto yy1100; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'u') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 'v') goto yy1194; if (yych <= 'z') goto yy151; goto yy4; } } } yy1194: YYDEBUG(1194, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'H') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'I') goto yy1101; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'h') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'i') goto yy1195; if (yych <= 'z') goto yy152; goto yy4; } } } yy1195: YYDEBUG(1195, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'N') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'O') goto yy1102; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'n') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'o') goto yy1196; if (yych <= 'z') goto yy153; goto yy4; } } } yy1196: YYDEBUG(1196, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'U') goto yy1103; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'u') goto yy1197; if (yych <= 'z') goto yy154; goto yy4; } } yy1197: YYDEBUG(1197, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy1104; if (yych != 's') goto yy155; YYDEBUG(1198, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 16) { goto yy154; } if (yych <= ',') { if (yych <= '\t') { if (yych <= 0x08) goto yy57; goto yy1105; } else { if (yych == ' ') goto yy1105; goto yy57; } } else { if (yych <= '/') { if (yych == '.') goto yy57; goto yy148; } else { if (yych == '_') goto yy148; goto yy57; } } yy1199: YYDEBUG(1199, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'G') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'F') goto yy142; goto yy1213; } } else { if (yych <= 'f') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'g') goto yy1213; if (yych <= 'z') goto yy142; goto yy4; } } yy1200: YYDEBUG(1200, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy142; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'e') goto yy1201; if (yych <= 'z') goto yy142; goto yy4; } } yy1201: YYDEBUG(1201, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'V') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'U') goto yy143; } } else { if (yych <= 'u') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'v') goto yy1202; if (yych <= 'z') goto yy143; goto yy4; } } yy1202: YYDEBUG(1202, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy144; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'e') goto yy1203; if (yych <= 'z') goto yy144; goto yy4; } } yy1203: YYDEBUG(1203, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'M') goto yy145; } } else { if (yych <= 'm') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'n') goto yy1204; if (yych <= 'z') goto yy145; goto yy4; } } yy1204: YYDEBUG(1204, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'T') goto yy1205; if (yych != 't') goto yy4; } yy1205: YYDEBUG(1205, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy1206; if (yych != 'h') goto yy57; yy1206: YYDEBUG(1206, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\t') goto yy1207; if (yych != ' ') goto yy57; yy1207: YYDEBUG(1207, *YYCURSOR); ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 11) YYFILL(11); yych = *YYCURSOR; yy1208: YYDEBUG(1208, *YYCURSOR); if (yych <= 'W') { if (yych <= 'F') { if (yych <= ' ') { if (yych == '\t') goto yy1207; if (yych <= 0x1F) goto yy57; goto yy1207; } else { if (yych == 'D') goto yy1110; if (yych <= 'E') goto yy57; goto yy1111; } } else { if (yych <= 'M') { if (yych == 'H') goto yy1109; if (yych <= 'L') goto yy57; goto yy1108; } else { if (yych <= 'S') { if (yych <= 'R') goto yy57; goto yy1107; } else { if (yych <= 'T') goto yy1114; if (yych <= 'V') goto yy57; } } } } else { if (yych <= 'l') { if (yych <= 'd') { if (yych == 'Y') goto yy1112; if (yych <= 'c') goto yy57; goto yy1110; } else { if (yych <= 'f') { if (yych <= 'e') goto yy57; goto yy1111; } else { if (yych == 'h') goto yy1109; goto yy57; } } } else { if (yych <= 't') { if (yych <= 'm') goto yy1108; if (yych <= 'r') goto yy57; if (yych <= 's') goto yy1107; goto yy1114; } else { if (yych <= 'w') { if (yych <= 'v') goto yy57; } else { if (yych == 'y') goto yy1112; goto yy57; } } } } YYDEBUG(1209, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy1210; if (yych != 'e') goto yy57; yy1210: YYDEBUG(1210, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= 'C') goto yy57; if (yych <= 'D') goto yy1135; } else { if (yych <= 'c') goto yy57; if (yych <= 'd') goto yy1135; if (yych >= 'f') goto yy57; } YYDEBUG(1211, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'K') goto yy1212; if (yych != 'k') goto yy57; yy1212: YYDEBUG(1212, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych == 'D') goto yy1144; if (yych <= 'R') goto yy57; goto yy1143; } else { if (yych <= 'd') { if (yych <= 'c') goto yy57; goto yy1144; } else { if (yych == 's') goto yy1143; goto yy57; } } yy1213: YYDEBUG(1213, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'H') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'G') goto yy143; } } else { if (yych <= 'g') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'h') goto yy1214; if (yych <= 'z') goto yy143; goto yy4; } } yy1214: YYDEBUG(1214, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy144; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 't') goto yy1215; if (yych <= 'z') goto yy144; goto yy4; } } yy1215: YYDEBUG(1215, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych <= 0x1F) { if (yych == '\t') goto yy1207; goto yy4; } else { if (yych <= ' ') goto yy1207; if (yych == ')') goto yy140; goto yy4; } } else { if (yych <= '`') { if (yych == 'H') goto yy1216; if (yych <= 'Z') goto yy145; goto yy4; } else { if (yych == 'h') goto yy1216; if (yych <= 'z') goto yy145; goto yy4; } } yy1216: YYDEBUG(1216, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy1207; goto yy4; } else { if (yych <= ' ') goto yy1207; if (yych == ')') goto yy140; goto yy4; } yy1217: YYDEBUG(1217, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'F') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'G') goto yy1213; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'f') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'g') goto yy1225; if (yych <= 'z') goto yy147; goto yy4; } } } yy1218: YYDEBUG(1218, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'E') goto yy1201; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'd') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'e') goto yy1219; if (yych <= 'z') goto yy147; goto yy4; } } } yy1219: YYDEBUG(1219, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'U') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'V') goto yy1202; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'u') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 'v') goto yy1220; if (yych <= 'z') goto yy151; goto yy4; } } } yy1220: YYDEBUG(1220, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'E') goto yy1203; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'd') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'e') goto yy1221; if (yych <= 'z') goto yy152; goto yy4; } } } yy1221: YYDEBUG(1221, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'M') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'N') goto yy1204; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'm') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'n') goto yy1222; if (yych <= 'z') goto yy153; goto yy4; } } } yy1222: YYDEBUG(1222, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'T') goto yy1205; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 't') goto yy1223; if (yych <= 'z') goto yy154; goto yy4; } } yy1223: YYDEBUG(1223, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy1206; if (yych != 'h') goto yy155; yy1224: YYDEBUG(1224, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 16) { goto yy154; } if (yych <= ',') { if (yych <= '\t') { if (yych <= 0x08) goto yy57; goto yy1207; } else { if (yych == ' ') goto yy1207; goto yy57; } } else { if (yych <= '/') { if (yych == '.') goto yy57; goto yy148; } else { if (yych == '_') goto yy148; goto yy57; } } yy1225: YYDEBUG(1225, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'G') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'H') goto yy1214; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'g') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 'h') goto yy1226; if (yych <= 'z') goto yy151; goto yy4; } } } yy1226: YYDEBUG(1226, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1215; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 't') goto yy1227; if (yych <= 'z') goto yy152; goto yy4; } } } yy1227: YYDEBUG(1227, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy4; goto yy1207; } else { if (yych == ' ') goto yy1207; goto yy4; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; goto yy148; } } } else { if (yych <= '^') { if (yych <= 'G') { if (yych <= '@') goto yy4; goto yy145; } else { if (yych <= 'H') goto yy1216; if (yych <= 'Z') goto yy145; goto yy4; } } else { if (yych <= 'g') { if (yych <= '_') goto yy148; if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'h') goto yy1228; if (yych <= 'z') goto yy153; goto yy4; } } } yy1228: YYDEBUG(1228, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 16) { goto yy154; } if (yych <= ')') { if (yych <= 0x1F) { if (yych == '\t') goto yy1207; goto yy4; } else { if (yych <= ' ') goto yy1207; if (yych <= '(') goto yy4; goto yy140; } } else { if (yych <= '.') { if (yych == '-') goto yy148; goto yy4; } else { if (yych <= '/') goto yy148; if (yych == '_') goto yy148; goto yy4; } } yy1229: YYDEBUG(1229, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'V') { if (yych <= 'B') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy142; } else { if (yych <= 'O') { if (yych <= 'C') goto yy1245; goto yy142; } else { if (yych <= 'P') goto yy1247; if (yych <= 'U') goto yy142; goto yy1246; } } } else { if (yych <= 'o') { if (yych <= '`') { if (yych <= 'Z') goto yy142; goto yy4; } else { if (yych == 'c') goto yy1245; goto yy142; } } else { if (yych <= 'u') { if (yych <= 'p') goto yy1247; goto yy142; } else { if (yych <= 'v') goto yy1246; if (yych <= 'z') goto yy142; goto yy4; } } } yy1230: YYDEBUG(1230, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy142; goto yy1240; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 't') goto yy1240; if (yych <= 'z') goto yy142; goto yy4; } } yy1231: YYDEBUG(1231, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'X') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'W') goto yy142; goto yy1237; } } else { if (yych <= 'w') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'x') goto yy1237; if (yych <= 'z') goto yy142; goto yy4; } } yy1232: YYDEBUG(1232, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'M') goto yy142; } } else { if (yych <= 'm') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'n') goto yy1233; if (yych <= 'z') goto yy142; goto yy4; } } yy1233: YYDEBUG(1233, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'D') { if (yych <= ')') { if (yych <= '(') goto yy167; goto yy140; } else { if (yych <= '@') goto yy167; if (yych <= 'C') goto yy143; } } else { if (yych <= 'c') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy167; goto yy143; } else { if (yych <= 'd') goto yy1234; if (yych <= 'z') goto yy143; goto yy167; } } yy1234: YYDEBUG(1234, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; } else { if (yych <= '`') { if (yych <= 'Z') goto yy144; goto yy4; } else { if (yych <= 'a') goto yy1235; if (yych <= 'z') goto yy144; goto yy4; } } yy1235: YYDEBUG(1235, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'X') goto yy145; } } else { if (yych <= 'x') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'y') goto yy1236; if (yych <= 'z') goto yy145; goto yy4; } } yy1236: YYDEBUG(1236, *YYCURSOR); yych = *++YYCURSOR; if (yych == ')') goto yy140; goto yy167; yy1237: YYDEBUG(1237, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy143; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 't') goto yy1238; if (yych <= 'z') goto yy143; goto yy4; } } yy1238: YYDEBUG(1238, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'H') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'G') goto yy144; } } else { if (yych <= 'g') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'h') goto yy1239; if (yych <= 'z') goto yy144; goto yy4; } } yy1239: YYDEBUG(1239, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy4; goto yy1207; } else { if (yych == ' ') goto yy1207; goto yy4; } } else { if (yych <= 'Z') { if (yych <= ')') goto yy140; if (yych <= '@') goto yy4; goto yy145; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy145; goto yy4; } } yy1240: YYDEBUG(1240, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= ')') { if (yych <= '(') goto yy167; goto yy140; } else { if (yych <= '@') goto yy167; if (yych <= 'T') goto yy143; } } else { if (yych <= 't') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy167; goto yy143; } else { if (yych <= 'u') goto yy1241; if (yych <= 'z') goto yy143; goto yy167; } } yy1241: YYDEBUG(1241, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'Q') goto yy144; } } else { if (yych <= 'q') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'r') goto yy1242; if (yych <= 'z') goto yy144; goto yy4; } } yy1242: YYDEBUG(1242, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'D') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'C') goto yy145; } } else { if (yych <= 'c') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'd') goto yy1243; if (yych <= 'z') goto yy145; goto yy4; } } yy1243: YYDEBUG(1243, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'A') goto yy1244; if (yych != 'a') goto yy4; } yy1244: YYDEBUG(1244, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy173; if (yych == 'y') goto yy173; goto yy57; yy1245: YYDEBUG(1245, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'N') goto yy143; goto yy1256; } } else { if (yych <= 'n') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'o') goto yy1256; if (yych <= 'z') goto yy143; goto yy4; } } yy1246: YYDEBUG(1246, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy143; goto yy1253; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'e') goto yy1253; if (yych <= 'z') goto yy143; goto yy4; } } yy1247: YYDEBUG(1247, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; goto yy194; } else { if (yych <= '-') goto yy197; if (yych <= '.') goto yy196; goto yy194; } } } else { if (yych <= 'Z') { if (yych <= '@') { if (yych <= '9') goto yy196; goto yy194; } else { if (yych != 'T') goto yy143; } } else { if (yych <= 's') { if (yych <= '`') goto yy194; goto yy143; } else { if (yych <= 't') goto yy1248; if (yych <= 'z') goto yy143; goto yy194; } } } yy1248: YYDEBUG(1248, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; goto yy194; } else { if (yych <= '-') goto yy197; if (yych <= '.') goto yy196; goto yy194; } } } else { if (yych <= 'Z') { if (yych <= '@') { if (yych <= '9') goto yy196; goto yy194; } else { if (yych != 'E') goto yy144; } } else { if (yych <= 'd') { if (yych <= '`') goto yy194; goto yy144; } else { if (yych <= 'e') goto yy1249; if (yych <= 'z') goto yy144; goto yy194; } } } yy1249: YYDEBUG(1249, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'M') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'L') goto yy145; } } else { if (yych <= 'l') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'm') goto yy1250; if (yych <= 'z') goto yy145; goto yy4; } } yy1250: YYDEBUG(1250, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'A') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'B') goto yy1251; if (yych != 'b') goto yy4; } yy1251: YYDEBUG(1251, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy1252; if (yych != 'e') goto yy57; yy1252: YYDEBUG(1252, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy206; if (yych == 'r') goto yy206; goto yy57; yy1253: YYDEBUG(1253, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'M') goto yy144; } } else { if (yych <= 'm') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'n') goto yy1254; if (yych <= 'z') goto yy144; goto yy4; } } yy1254: YYDEBUG(1254, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy145; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 't') goto yy1255; if (yych <= 'z') goto yy145; goto yy4; } } yy1255: YYDEBUG(1255, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'G') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'H') goto yy1206; if (yych == 'h') goto yy1206; goto yy4; } yy1256: YYDEBUG(1256, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'M') goto yy144; } } else { if (yych <= 'm') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'n') goto yy1257; if (yych <= 'z') goto yy144; goto yy4; } } yy1257: YYDEBUG(1257, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'D') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'C') goto yy145; goto yy1216; } } else { if (yych <= 'c') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'd') goto yy1216; if (yych <= 'z') goto yy145; goto yy4; } } yy1258: YYDEBUG(1258, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'U') { if (yych <= '/') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; goto yy148; } } else { if (yych <= 'C') { if (yych <= '@') goto yy4; if (yych <= 'B') goto yy142; goto yy1245; } else { if (yych == 'P') goto yy1247; goto yy142; } } } else { if (yych <= 'b') { if (yych <= '^') { if (yych <= 'V') goto yy1246; if (yych <= 'Z') goto yy142; goto yy4; } else { if (yych <= '_') goto yy148; if (yych <= '`') goto yy4; goto yy147; } } else { if (yych <= 'p') { if (yych <= 'c') goto yy1274; if (yych <= 'o') goto yy147; goto yy1276; } else { if (yych == 'v') goto yy1275; if (yych <= 'z') goto yy147; goto yy4; } } } yy1259: YYDEBUG(1259, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1240; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 't') goto yy1269; if (yych <= 'z') goto yy147; goto yy4; } } } yy1260: YYDEBUG(1260, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'W') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'X') goto yy1237; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'w') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'x') goto yy1266; if (yych <= 'z') goto yy147; goto yy4; } } } yy1261: YYDEBUG(1261, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'M') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'N') goto yy1233; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'm') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'n') goto yy1262; if (yych <= 'z') goto yy147; goto yy4; } } } yy1262: YYDEBUG(1262, *YYCURSOR); yyaccept = 4; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy167; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy167; goto yy143; } } else { if (yych <= '_') { if (yych <= 'D') goto yy1234; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy167; goto yy148; } else { if (yych <= 'c') { if (yych <= '`') goto yy167; goto yy151; } else { if (yych <= 'd') goto yy1263; if (yych <= 'z') goto yy151; goto yy167; } } } yy1263: YYDEBUG(1263, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '_') { if (yych <= 'A') goto yy1235; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'a') goto yy1264; if (yych <= 'z') goto yy152; goto yy4; } } yy1264: YYDEBUG(1264, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'X') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'Y') goto yy1236; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'x') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'y') goto yy1265; if (yych <= 'z') goto yy153; goto yy4; } } } yy1265: YYDEBUG(1265, *YYCURSOR); yyaccept = 4; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 16) { goto yy154; } if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy167; goto yy148; } else { if (yych <= '/') { if (yych <= '.') goto yy167; goto yy148; } else { if (yych == '_') goto yy148; goto yy167; } } yy1266: YYDEBUG(1266, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1238; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 't') goto yy1267; if (yych <= 'z') goto yy151; goto yy4; } } } yy1267: YYDEBUG(1267, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'G') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'H') goto yy1239; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'g') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'h') goto yy1268; if (yych <= 'z') goto yy152; goto yy4; } } } yy1268: YYDEBUG(1268, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '-') { if (yych <= ' ') { if (yych == '\t') goto yy1207; if (yych <= 0x1F) goto yy4; goto yy1207; } else { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } } else { if (yych <= 'Z') { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } else { if (yych <= '_') { if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy153; goto yy4; } } } yy1269: YYDEBUG(1269, *YYCURSOR); yyaccept = 4; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy167; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy167; goto yy143; } } else { if (yych <= '_') { if (yych <= 'U') goto yy1241; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy167; goto yy148; } else { if (yych <= 't') { if (yych <= '`') goto yy167; goto yy151; } else { if (yych <= 'u') goto yy1270; if (yych <= 'z') goto yy151; goto yy167; } } } yy1270: YYDEBUG(1270, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'Q') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'R') goto yy1242; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'q') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'r') goto yy1271; if (yych <= 'z') goto yy152; goto yy4; } } } yy1271: YYDEBUG(1271, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'D') goto yy1243; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'c') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'd') goto yy1272; if (yych <= 'z') goto yy153; goto yy4; } } } yy1272: YYDEBUG(1272, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '_') { if (yych <= 'A') goto yy1244; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'a') goto yy1273; if (yych <= 'z') goto yy154; goto yy4; } } yy1273: YYDEBUG(1273, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy173; if (yych == 'y') goto yy186; goto yy155; yy1274: YYDEBUG(1274, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'N') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'O') goto yy1256; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'n') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 'o') goto yy1285; if (yych <= 'z') goto yy151; goto yy4; } } } yy1275: YYDEBUG(1275, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'E') goto yy1253; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'd') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 'e') goto yy1282; if (yych <= 'z') goto yy151; goto yy4; } } } yy1276: YYDEBUG(1276, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= '-') { if (yych <= ')') goto yy140; if (yych <= ',') goto yy194; goto yy372; } else { if (yych == '/') goto yy148; goto yy196; } } } else { if (yych <= '^') { if (yych <= 'S') { if (yych <= '@') goto yy194; goto yy143; } else { if (yych <= 'T') goto yy1248; if (yych <= 'Z') goto yy143; goto yy194; } } else { if (yych <= 's') { if (yych <= '_') goto yy148; if (yych <= '`') goto yy194; goto yy151; } else { if (yych <= 't') goto yy1277; if (yych <= 'z') goto yy151; goto yy194; } } } yy1277: YYDEBUG(1277, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= '-') { if (yych <= ')') goto yy140; if (yych <= ',') goto yy194; goto yy372; } else { if (yych == '/') goto yy148; goto yy196; } } } else { if (yych <= '^') { if (yych <= 'D') { if (yych <= '@') goto yy194; goto yy144; } else { if (yych <= 'E') goto yy1249; if (yych <= 'Z') goto yy144; goto yy194; } } else { if (yych <= 'd') { if (yych <= '_') goto yy148; if (yych <= '`') goto yy194; goto yy152; } else { if (yych <= 'e') goto yy1278; if (yych <= 'z') goto yy152; goto yy194; } } } yy1278: YYDEBUG(1278, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'L') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'M') goto yy1250; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'l') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'm') goto yy1279; if (yych <= 'z') goto yy153; goto yy4; } } } yy1279: YYDEBUG(1279, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'A') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'B') goto yy1251; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'b') goto yy1280; if (yych <= 'z') goto yy154; goto yy4; } } yy1280: YYDEBUG(1280, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy1252; if (yych != 'e') goto yy155; YYDEBUG(1281, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy206; if (yych == 'r') goto yy377; goto yy155; yy1282: YYDEBUG(1282, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'M') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'N') goto yy1254; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'm') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'n') goto yy1283; if (yych <= 'z') goto yy152; goto yy4; } } } yy1283: YYDEBUG(1283, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1255; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 't') goto yy1284; if (yych <= 'z') goto yy153; goto yy4; } } } yy1284: YYDEBUG(1284, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'G') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'H') goto yy1206; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'h') goto yy1224; if (yych <= 'z') goto yy154; goto yy4; } } yy1285: YYDEBUG(1285, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'M') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'N') goto yy1257; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'm') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'n') goto yy1286; if (yych <= 'z') goto yy152; goto yy4; } } } yy1286: YYDEBUG(1286, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'D') goto yy1216; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'c') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'd') goto yy1228; if (yych <= 'z') goto yy153; goto yy4; } } } yy1287: YYDEBUG(1287, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'C') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'B') goto yy142; } } else { if (yych <= 'b') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'c') goto yy1288; if (yych <= 'z') goto yy142; goto yy4; } } yy1288: YYDEBUG(1288, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'K') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'J') goto yy143; } } else { if (yych <= 'j') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'k') goto yy1289; if (yych <= 'z') goto yy143; goto yy4; } } yy1289: YYDEBUG(1289, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ')') { if (yych == ' ') goto yy1290; if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= 'Z') { if (yych <= '@') goto yy4; goto yy144; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy144; goto yy4; } } yy1290: YYDEBUG(1290, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy1291; if (yych != 'o') goto yy57; yy1291: YYDEBUG(1291, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy1292; if (yych != 'f') goto yy57; yy1292: YYDEBUG(1292, *YYCURSOR); yych = *++YYCURSOR; if (yych != ' ') goto yy57; YYDEBUG(1293, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '1') goto yy1294; if (yych <= '2') goto yy1296; if (yych <= '9') goto yy1297; goto yy57; yy1294: YYDEBUG(1294, *YYCURSOR); yyaccept = 28; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') goto yy1298; if (yych <= '9') goto yy1297; goto yy1298; yy1295: YYDEBUG(1295, *YYCURSOR); #line 1099 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("backof | frontof"); TIMELIB_INIT; TIMELIB_UNHAVE_TIME(); TIMELIB_HAVE_TIME(); if (*ptr == 'b') { s->time->h = timelib_get_nr((char **) &ptr, 2); s->time->i = 15; } else { s->time->h = timelib_get_nr((char **) &ptr, 2) - 1; s->time->i = 45; } if (*ptr != '\0' ) { timelib_eat_spaces((char **) &ptr); s->time->h += timelib_meridian((char **) &ptr, s->time->h); } TIMELIB_DEINIT; return TIMELIB_LF_DAY_OF_MONTH; } #line 19675 "ext/date/lib/parse_date.c" yy1296: YYDEBUG(1296, *YYCURSOR); yyaccept = 28; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') goto yy1298; if (yych >= '5') goto yy1298; yy1297: YYDEBUG(1297, *YYCURSOR); yyaccept = 28; YYMARKER = ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 5) YYFILL(5); yych = *YYCURSOR; yy1298: YYDEBUG(1298, *YYCURSOR); if (yych <= 'A') { if (yych <= 0x1F) { if (yych == '\t') goto yy1297; goto yy1295; } else { if (yych <= ' ') goto yy1297; if (yych <= '@') goto yy1295; } } else { if (yych <= '`') { if (yych != 'P') goto yy1295; } else { if (yych <= 'a') goto yy1299; if (yych != 'p') goto yy1295; } } yy1299: YYDEBUG(1299, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych != '.') goto yy57; } else { if (yych <= 'M') goto yy1301; if (yych == 'm') goto yy1301; goto yy57; } YYDEBUG(1300, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy1301; if (yych != 'm') goto yy57; yy1301: YYDEBUG(1301, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 0x1F) { if (yych <= 0x00) goto yy1303; if (yych == '\t') goto yy1303; goto yy57; } else { if (yych <= ' ') goto yy1303; if (yych != '.') goto yy57; } YYDEBUG(1302, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '\t') { if (yych <= 0x00) goto yy1303; if (yych <= 0x08) goto yy57; } else { if (yych != ' ') goto yy57; } yy1303: YYDEBUG(1303, *YYCURSOR); yych = *++YYCURSOR; goto yy1295; yy1304: YYDEBUG(1304, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'B') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'C') goto yy1288; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'b') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'c') goto yy1305; if (yych <= 'z') goto yy147; goto yy4; } } } yy1305: YYDEBUG(1305, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'J') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'K') goto yy1289; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'j') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 'k') goto yy1306; if (yych <= 'z') goto yy151; goto yy4; } } } yy1306: YYDEBUG(1306, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= '(') { if (yych == ' ') goto yy1290; goto yy4; } else { if (yych <= ')') goto yy140; if (yych == '-') goto yy148; goto yy4; } } else { if (yych <= '^') { if (yych <= '/') goto yy148; if (yych <= '@') goto yy4; if (yych <= 'Z') goto yy144; goto yy4; } else { if (yych <= '_') goto yy148; if (yych <= '`') goto yy4; if (yych <= 'z') goto yy152; goto yy4; } } yy1307: YYDEBUG(1307, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'R') goto yy142; } } else { if (yych <= 'r') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 's') goto yy1308; if (yych <= 'z') goto yy142; goto yy4; } } yy1308: YYDEBUG(1308, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy143; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 't') goto yy1309; if (yych <= 'z') goto yy143; goto yy4; } } yy1309: YYDEBUG(1309, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy4; goto yy1105; } else { if (yych != ' ') goto yy4; } } else { if (yych <= 'Z') { if (yych <= ')') goto yy140; if (yych <= '@') goto yy4; goto yy144; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy144; goto yy4; } } yy1310: YYDEBUG(1310, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy1311; if (yych != 'd') goto yy1106; yy1311: YYDEBUG(1311, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1312; if (yych != 'a') goto yy57; yy1312: YYDEBUG(1312, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy1313; if (yych != 'y') goto yy57; yy1313: YYDEBUG(1313, *YYCURSOR); yyaccept = 26; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'R') { if (yych != ' ') goto yy1118; } else { if (yych <= 'S') goto yy1143; if (yych == 's') goto yy1143; goto yy1118; } YYDEBUG(1314, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy1315; if (yych != 'o') goto yy57; yy1315: YYDEBUG(1315, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy1316; if (yych != 'f') goto yy57; yy1316: YYDEBUG(1316, *YYCURSOR); yych = *++YYCURSOR; goto yy2; yy1317: YYDEBUG(1317, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'R') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'S') goto yy1308; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'r') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 's') goto yy1318; if (yych <= 'z') goto yy147; goto yy4; } } } yy1318: YYDEBUG(1318, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1309; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 't') goto yy1319; if (yych <= 'z') goto yy151; goto yy4; } } } yy1319: YYDEBUG(1319, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '-') { if (yych <= ' ') { if (yych == '\t') goto yy1105; if (yych <= 0x1F) goto yy4; goto yy1310; } else { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } } else { if (yych <= 'Z') { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } else { if (yych <= '_') { if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy152; goto yy4; } } } yy1320: YYDEBUG(1320, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'B') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'A') goto yy142; goto yy1356; } } else { if (yych <= 'a') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'b') goto yy1356; if (yych <= 'z') goto yy142; goto yy4; } } yy1321: YYDEBUG(1321, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == 'F') goto yy1346; if (yych <= 'Q') goto yy142; goto yy1345; } } else { if (yych <= 'f') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; if (yych <= 'e') goto yy142; goto yy1346; } else { if (yych == 'r') goto yy1345; if (yych <= 'z') goto yy142; goto yy4; } } yy1322: YYDEBUG(1322, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'T') goto yy142; goto yy1342; } } else { if (yych <= 't') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'u') goto yy1342; if (yych <= 'z') goto yy142; goto yy4; } } yy1323: YYDEBUG(1323, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == 'I') goto yy1325; if (yych <= 'N') goto yy142; } } else { if (yych <= 'i') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; if (yych <= 'h') goto yy142; goto yy1325; } else { if (yych == 'o') goto yy1324; if (yych <= 'z') goto yy142; goto yy4; } } yy1324: YYDEBUG(1324, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'M') goto yy143; goto yy1328; } } else { if (yych <= 'm') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'n') goto yy1328; if (yych <= 'z') goto yy143; goto yy4; } } yy1325: YYDEBUG(1325, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'D') { if (yych <= ')') { if (yych <= '(') goto yy167; goto yy140; } else { if (yych <= '@') goto yy167; if (yych <= 'C') goto yy143; } } else { if (yych <= 'c') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy167; goto yy143; } else { if (yych <= 'd') goto yy1326; if (yych <= 'z') goto yy143; goto yy167; } } yy1326: YYDEBUG(1326, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; } else { if (yych <= '`') { if (yych <= 'Z') goto yy144; goto yy4; } else { if (yych <= 'a') goto yy1327; if (yych <= 'z') goto yy144; goto yy4; } } yy1327: YYDEBUG(1327, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'X') goto yy145; goto yy1236; } } else { if (yych <= 'x') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'y') goto yy1236; if (yych <= 'z') goto yy145; goto yy4; } } yy1328: YYDEBUG(1328, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy144; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 't') goto yy1329; if (yych <= 'z') goto yy144; goto yy4; } } yy1329: YYDEBUG(1329, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ')') { if (yych == ' ') goto yy1330; if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= 'Z') { if (yych <= '@') goto yy4; goto yy145; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy145; goto yy4; } } yy1330: YYDEBUG(1330, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy1331; if (yych != 'o') goto yy57; yy1331: YYDEBUG(1331, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy1332; if (yych != 'f') goto yy57; yy1332: YYDEBUG(1332, *YYCURSOR); yych = *++YYCURSOR; if (yych != ' ') goto yy57; YYDEBUG(1333, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '1') goto yy1334; if (yych <= '2') goto yy1335; if (yych <= '9') goto yy1336; goto yy57; yy1334: YYDEBUG(1334, *YYCURSOR); yyaccept = 28; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') goto yy1337; if (yych <= '9') goto yy1336; goto yy1337; yy1335: YYDEBUG(1335, *YYCURSOR); yyaccept = 28; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') goto yy1337; if (yych >= '5') goto yy1337; yy1336: YYDEBUG(1336, *YYCURSOR); yyaccept = 28; YYMARKER = ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 5) YYFILL(5); yych = *YYCURSOR; yy1337: YYDEBUG(1337, *YYCURSOR); if (yych <= 'A') { if (yych <= 0x1F) { if (yych == '\t') goto yy1336; goto yy1295; } else { if (yych <= ' ') goto yy1336; if (yych <= '@') goto yy1295; } } else { if (yych <= '`') { if (yych != 'P') goto yy1295; } else { if (yych <= 'a') goto yy1338; if (yych != 'p') goto yy1295; } } yy1338: YYDEBUG(1338, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych != '.') goto yy57; } else { if (yych <= 'M') goto yy1340; if (yych == 'm') goto yy1340; goto yy57; } YYDEBUG(1339, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy1340; if (yych != 'm') goto yy57; yy1340: YYDEBUG(1340, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 0x1F) { if (yych <= 0x00) goto yy1303; if (yych == '\t') goto yy1303; goto yy57; } else { if (yych <= ' ') goto yy1303; if (yych != '.') goto yy57; } YYDEBUG(1341, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '\t') { if (yych <= 0x00) goto yy1303; if (yych <= 0x08) goto yy57; goto yy1303; } else { if (yych == ' ') goto yy1303; goto yy57; } yy1342: YYDEBUG(1342, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'Q') goto yy143; } } else { if (yych <= 'q') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'r') goto yy1343; if (yych <= 'z') goto yy143; goto yy4; } } yy1343: YYDEBUG(1343, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy144; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 't') goto yy1344; if (yych <= 'z') goto yy144; goto yy4; } } yy1344: YYDEBUG(1344, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'H') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'G') goto yy145; goto yy1216; } } else { if (yych <= 'g') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'h') goto yy1216; if (yych <= 'z') goto yy145; goto yy4; } } yy1345: YYDEBUG(1345, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'R') goto yy143; goto yy1348; } } else { if (yych <= 'r') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 's') goto yy1348; if (yych <= 'z') goto yy143; goto yy4; } } yy1346: YYDEBUG(1346, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy143; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 't') goto yy1347; if (yych <= 'z') goto yy143; goto yy4; } } yy1347: YYDEBUG(1347, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'H') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'G') goto yy144; goto yy1239; } } else { if (yych <= 'g') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'h') goto yy1239; if (yych <= 'z') goto yy144; goto yy4; } } yy1348: YYDEBUG(1348, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy144; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 't') goto yy1349; if (yych <= 'z') goto yy144; goto yy4; } } yy1349: YYDEBUG(1349, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy4; goto yy1207; } else { if (yych != ' ') goto yy4; } } else { if (yych <= 'Z') { if (yych <= ')') goto yy140; if (yych <= '@') goto yy4; goto yy145; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy145; goto yy4; } } yy1350: YYDEBUG(1350, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy1351; if (yych != 'd') goto yy1208; yy1351: YYDEBUG(1351, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1352; if (yych != 'a') goto yy57; yy1352: YYDEBUG(1352, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy1353; if (yych != 'y') goto yy57; yy1353: YYDEBUG(1353, *YYCURSOR); yyaccept = 26; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'R') { if (yych != ' ') goto yy1118; } else { if (yych <= 'S') goto yy1143; if (yych == 's') goto yy1143; goto yy1118; } YYDEBUG(1354, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy1355; if (yych != 'o') goto yy57; yy1355: YYDEBUG(1355, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy1316; if (yych == 'f') goto yy1316; goto yy57; yy1356: YYDEBUG(1356, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; goto yy194; } else { if (yych <= '-') goto yy197; if (yych <= '.') goto yy196; goto yy194; } } } else { if (yych <= 'Z') { if (yych <= '@') { if (yych <= '9') goto yy196; goto yy194; } else { if (yych != 'R') goto yy143; } } else { if (yych <= 'q') { if (yych <= '`') goto yy194; goto yy143; } else { if (yych <= 'r') goto yy1357; if (yych <= 'z') goto yy143; goto yy194; } } } yy1357: YYDEBUG(1357, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'T') goto yy144; } } else { if (yych <= 't') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'u') goto yy1358; if (yych <= 'z') goto yy144; goto yy4; } } yy1358: YYDEBUG(1358, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; } else { if (yych <= '`') { if (yych <= 'Z') goto yy145; goto yy4; } else { if (yych <= 'a') goto yy1359; if (yych <= 'z') goto yy145; goto yy4; } } yy1359: YYDEBUG(1359, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'Q') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'R') goto yy1360; if (yych != 'r') goto yy4; } yy1360: YYDEBUG(1360, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy206; if (yych == 'y') goto yy206; goto yy57; yy1361: YYDEBUG(1361, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'A') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'B') goto yy1356; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'a') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'b') goto yy1379; if (yych <= 'z') goto yy147; goto yy4; } } } yy1362: YYDEBUG(1362, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'Q') { if (yych <= '.') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych == '-') goto yy148; goto yy4; } } else { if (yych <= '@') { if (yych <= '/') goto yy148; goto yy4; } else { if (yych == 'F') goto yy1346; goto yy142; } } } else { if (yych <= '`') { if (yych <= 'Z') { if (yych <= 'R') goto yy1345; goto yy142; } else { if (yych == '_') goto yy148; goto yy4; } } else { if (yych <= 'q') { if (yych == 'f') goto yy1375; goto yy147; } else { if (yych <= 'r') goto yy1374; if (yych <= 'z') goto yy147; goto yy4; } } } yy1363: YYDEBUG(1363, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'U') goto yy1342; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 't') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'u') goto yy1371; if (yych <= 'z') goto yy147; goto yy4; } } } yy1364: YYDEBUG(1364, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'N') { if (yych <= '.') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych == '-') goto yy148; goto yy4; } } else { if (yych <= '@') { if (yych <= '/') goto yy148; goto yy4; } else { if (yych == 'I') goto yy1325; goto yy142; } } } else { if (yych <= '`') { if (yych <= 'Z') { if (yych <= 'O') goto yy1324; goto yy142; } else { if (yych == '_') goto yy148; goto yy4; } } else { if (yych <= 'n') { if (yych == 'i') goto yy1366; goto yy147; } else { if (yych <= 'o') goto yy1365; if (yych <= 'z') goto yy147; goto yy4; } } } yy1365: YYDEBUG(1365, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'M') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'N') goto yy1328; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'm') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 'n') goto yy1369; if (yych <= 'z') goto yy151; goto yy4; } } } yy1366: YYDEBUG(1366, *YYCURSOR); yyaccept = 4; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy167; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy167; goto yy143; } } else { if (yych <= '_') { if (yych <= 'D') goto yy1326; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy167; goto yy148; } else { if (yych <= 'c') { if (yych <= '`') goto yy167; goto yy151; } else { if (yych <= 'd') goto yy1367; if (yych <= 'z') goto yy151; goto yy167; } } } yy1367: YYDEBUG(1367, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '_') { if (yych <= 'A') goto yy1327; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'a') goto yy1368; if (yych <= 'z') goto yy152; goto yy4; } } yy1368: YYDEBUG(1368, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'X') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'Y') goto yy1236; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'x') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'y') goto yy1265; if (yych <= 'z') goto yy153; goto yy4; } } } yy1369: YYDEBUG(1369, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1329; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 't') goto yy1370; if (yych <= 'z') goto yy152; goto yy4; } } } yy1370: YYDEBUG(1370, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= '(') { if (yych == ' ') goto yy1330; goto yy4; } else { if (yych <= ')') goto yy140; if (yych == '-') goto yy148; goto yy4; } } else { if (yych <= '^') { if (yych <= '/') goto yy148; if (yych <= '@') goto yy4; if (yych <= 'Z') goto yy145; goto yy4; } else { if (yych <= '_') goto yy148; if (yych <= '`') goto yy4; if (yych <= 'z') goto yy153; goto yy4; } } yy1371: YYDEBUG(1371, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'Q') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'R') goto yy1343; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'q') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 'r') goto yy1372; if (yych <= 'z') goto yy151; goto yy4; } } } yy1372: YYDEBUG(1372, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1344; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 't') goto yy1373; if (yych <= 'z') goto yy152; goto yy4; } } } yy1373: YYDEBUG(1373, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'G') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'H') goto yy1216; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'g') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'h') goto yy1228; if (yych <= 'z') goto yy153; goto yy4; } } } yy1374: YYDEBUG(1374, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'R') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'S') goto yy1348; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'r') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 's') goto yy1377; if (yych <= 'z') goto yy151; goto yy4; } } } yy1375: YYDEBUG(1375, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1347; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 't') goto yy1376; if (yych <= 'z') goto yy151; goto yy4; } } } yy1376: YYDEBUG(1376, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'G') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'H') goto yy1239; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'g') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'h') goto yy1268; if (yych <= 'z') goto yy152; goto yy4; } } } yy1377: YYDEBUG(1377, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1349; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 't') goto yy1378; if (yych <= 'z') goto yy152; goto yy4; } } } yy1378: YYDEBUG(1378, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '-') { if (yych <= ' ') { if (yych == '\t') goto yy1207; if (yych <= 0x1F) goto yy4; goto yy1350; } else { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } } else { if (yych <= 'Z') { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } else { if (yych <= '_') { if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy153; goto yy4; } } } yy1379: YYDEBUG(1379, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= '-') { if (yych <= ')') goto yy140; if (yych <= ',') goto yy194; goto yy372; } else { if (yych == '/') goto yy148; goto yy196; } } } else { if (yych <= '^') { if (yych <= 'Q') { if (yych <= '@') goto yy194; goto yy143; } else { if (yych <= 'R') goto yy1357; if (yych <= 'Z') goto yy143; goto yy194; } } else { if (yych <= 'q') { if (yych <= '_') goto yy148; if (yych <= '`') goto yy194; goto yy151; } else { if (yych <= 'r') goto yy1380; if (yych <= 'z') goto yy151; goto yy194; } } } yy1380: YYDEBUG(1380, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'U') goto yy1358; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 't') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'u') goto yy1381; if (yych <= 'z') goto yy152; goto yy4; } } } yy1381: YYDEBUG(1381, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '_') { if (yych <= 'A') goto yy1359; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'a') goto yy1382; if (yych <= 'z') goto yy153; goto yy4; } } yy1382: YYDEBUG(1382, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'Q') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'R') goto yy1360; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'r') goto yy1383; if (yych <= 'z') goto yy154; goto yy4; } } yy1383: YYDEBUG(1383, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy206; if (yych == 'y') goto yy377; goto yy155; yy1384: YYDEBUG(1384, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; yy1385: YYDEBUG(1385, *YYCURSOR); ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; YYDEBUG(1386, *YYCURSOR); if (yych <= '/') goto yy1387; if (yych <= '9') goto yy1385; yy1387: YYDEBUG(1387, *YYCURSOR); #line 1057 "ext/date/lib/parse_date.re" { timelib_ull i; TIMELIB_INIT; TIMELIB_HAVE_RELATIVE(); TIMELIB_UNHAVE_DATE(); TIMELIB_UNHAVE_TIME(); TIMELIB_HAVE_TZ(); i = timelib_get_unsigned_nr((char **) &ptr, 24); s->time->y = 1970; s->time->m = 1; s->time->d = 1; s->time->h = s->time->i = s->time->s = 0; s->time->f = 0.0; s->time->relative.s += i; s->time->is_localtime = 1; s->time->zone_type = TIMELIB_ZONETYPE_OFFSET; s->time->z = 0; TIMELIB_DEINIT; return TIMELIB_RELATIVE; } #line 21390 "ext/date/lib/parse_date.c" yy1388: YYDEBUG(1388, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'M') goto yy142; goto yy1429; } } else { if (yych <= 'm') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'n') goto yy1429; if (yych <= 'z') goto yy142; goto yy4; } } yy1389: YYDEBUG(1389, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == 'I') goto yy1421; if (yych <= 'T') goto yy142; goto yy1422; } } else { if (yych <= 'i') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; if (yych <= 'h') goto yy142; goto yy1421; } else { if (yych == 'u') goto yy1422; if (yych <= 'z') goto yy142; goto yy4; } } yy1390: YYDEBUG(1390, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'M') { if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == 'D') goto yy1410; if (yych <= 'L') goto yy142; goto yy1411; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; if (yych <= 'c') goto yy142; goto yy1410; } else { if (yych == 'm') goto yy1411; if (yych <= 'z') goto yy142; goto yy4; } } yy1391: YYDEBUG(1391, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy142; goto yy1406; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'e') goto yy1406; if (yych <= 'z') goto yy142; goto yy4; } } yy1392: YYDEBUG(1392, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy142; goto yy1402; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'e') goto yy1402; if (yych <= 'z') goto yy142; goto yy4; } } yy1393: YYDEBUG(1393, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy1065; goto yy57; } else { if (yych <= '9') goto yy1396; if (yych <= ':') goto yy1065; goto yy57; } yy1394: YYDEBUG(1394, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy1065; goto yy57; } else { if (yych <= '4') goto yy1396; if (yych == ':') goto yy1065; goto yy57; } yy1395: YYDEBUG(1395, *YYCURSOR); yych = *++YYCURSOR; if (yych == '.') goto yy1065; if (yych == ':') goto yy1065; goto yy57; yy1396: YYDEBUG(1396, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy1065; goto yy57; } else { if (yych <= '5') goto yy1397; if (yych == ':') goto yy1065; goto yy57; } yy1397: YYDEBUG(1397, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych >= ':') goto yy57; YYDEBUG(1398, *YYCURSOR); yyaccept = 24; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') goto yy1068; if (yych <= '5') goto yy1399; if (yych <= '6') goto yy1400; goto yy1068; yy1399: YYDEBUG(1399, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy57; if (yych <= '9') goto yy1401; goto yy57; yy1400: YYDEBUG(1400, *YYCURSOR); yych = *++YYCURSOR; if (yych != '0') goto yy57; yy1401: YYDEBUG(1401, *YYCURSOR); yych = *++YYCURSOR; goto yy1076; yy1402: YYDEBUG(1402, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'L') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'K') goto yy143; } } else { if (yych <= 'k') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'l') goto yy1403; if (yych <= 'z') goto yy143; goto yy4; } } yy1403: YYDEBUG(1403, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'F') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'E') goto yy144; } } else { if (yych <= 'e') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'f') goto yy1404; if (yych <= 'z') goto yy144; goto yy4; } } yy1404: YYDEBUG(1404, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy145; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 't') goto yy1405; if (yych <= 'z') goto yy145; goto yy4; } } yy1405: YYDEBUG(1405, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'G') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'H') goto yy1206; if (yych == 'h') goto yy1206; goto yy4; } yy1406: YYDEBUG(1406, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= ')') { if (yych <= '(') goto yy167; goto yy140; } else { if (yych <= '@') goto yy167; if (yych <= 'R') goto yy143; } } else { if (yych <= 'r') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy167; goto yy143; } else { if (yych <= 's') goto yy1407; if (yych <= 'z') goto yy143; goto yy167; } } yy1407: YYDEBUG(1407, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'D') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'C') goto yy144; } } else { if (yych <= 'c') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'd') goto yy1408; if (yych <= 'z') goto yy144; goto yy4; } } yy1408: YYDEBUG(1408, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; } else { if (yych <= '`') { if (yych <= 'Z') goto yy145; goto yy4; } else { if (yych <= 'a') goto yy1409; if (yych <= 'z') goto yy145; goto yy4; } } yy1409: YYDEBUG(1409, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'X') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'Y') goto yy173; if (yych == 'y') goto yy173; goto yy4; } yy1410: YYDEBUG(1410, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy1418; } else { if (yych <= '`') { if (yych <= 'Z') goto yy143; goto yy4; } else { if (yych <= 'a') goto yy1418; if (yych <= 'z') goto yy143; goto yy4; } } yy1411: YYDEBUG(1411, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'N') goto yy143; } } else { if (yych <= 'n') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'o') goto yy1412; if (yych <= 'z') goto yy143; goto yy4; } } yy1412: YYDEBUG(1412, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'Q') goto yy144; } } else { if (yych <= 'q') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'r') goto yy1413; if (yych <= 'z') goto yy144; goto yy4; } } yy1413: YYDEBUG(1413, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'Q') goto yy145; } } else { if (yych <= 'q') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'r') goto yy1414; if (yych <= 'z') goto yy145; goto yy4; } } yy1414: YYDEBUG(1414, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'N') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'O') goto yy1415; if (yych != 'o') goto yy4; } yy1415: YYDEBUG(1415, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'W') goto yy1416; if (yych != 'w') goto yy57; yy1416: YYDEBUG(1416, *YYCURSOR); ++YYCURSOR; yy1417: YYDEBUG(1417, *YYCURSOR); #line 1045 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("tomorrow"); TIMELIB_INIT; TIMELIB_HAVE_RELATIVE(); TIMELIB_UNHAVE_TIME(); s->time->relative.d = 1; TIMELIB_DEINIT; return TIMELIB_RELATIVE; } #line 21837 "ext/date/lib/parse_date.c" yy1418: YYDEBUG(1418, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'X') goto yy144; } } else { if (yych <= 'x') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'y') goto yy1419; if (yych <= 'z') goto yy144; goto yy4; } } yy1419: YYDEBUG(1419, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '@') { if (yych == ')') goto yy140; } else { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy1420; if (yych <= 'z') goto yy145; } yy1420: YYDEBUG(1420, *YYCURSOR); #line 1035 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("midnight | today"); TIMELIB_INIT; TIMELIB_UNHAVE_TIME(); TIMELIB_DEINIT; return TIMELIB_RELATIVE; } #line 21881 "ext/date/lib/parse_date.c" yy1421: YYDEBUG(1421, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'Q') goto yy143; if (yych <= 'R') goto yy1427; goto yy1428; } } else { if (yych <= 'q') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'r') goto yy1427; if (yych <= 's') goto yy1428; if (yych <= 'z') goto yy143; goto yy4; } } yy1422: YYDEBUG(1422, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= ')') { if (yych <= '(') goto yy167; goto yy140; } else { if (yych <= '@') goto yy167; if (yych <= 'Q') goto yy143; } } else { if (yych <= 'q') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy167; goto yy143; } else { if (yych <= 'r') goto yy1423; if (yych <= 'z') goto yy143; goto yy167; } } yy1423: YYDEBUG(1423, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'R') goto yy144; } } else { if (yych <= 'r') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 's') goto yy1424; if (yych <= 'z') goto yy144; goto yy4; } } yy1424: YYDEBUG(1424, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'D') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'C') goto yy145; } } else { if (yych <= 'c') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'd') goto yy1425; if (yych <= 'z') goto yy145; goto yy4; } } yy1425: YYDEBUG(1425, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'A') goto yy1426; if (yych != 'a') goto yy4; } yy1426: YYDEBUG(1426, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy173; if (yych == 'y') goto yy173; goto yy57; yy1427: YYDEBUG(1427, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'D') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'C') goto yy144; goto yy1239; } } else { if (yych <= 'c') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'd') goto yy1239; if (yych <= 'z') goto yy144; goto yy4; } } yy1428: YYDEBUG(1428, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy4; goto yy1105; } else { if (yych == ' ') goto yy1105; goto yy4; } } else { if (yych <= 'Z') { if (yych <= ')') goto yy140; if (yych <= '@') goto yy4; goto yy144; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy144; goto yy4; } } yy1429: YYDEBUG(1429, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy143; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 't') goto yy1430; if (yych <= 'z') goto yy143; goto yy4; } } yy1430: YYDEBUG(1430, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'H') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'G') goto yy144; goto yy1239; } } else { if (yych <= 'g') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'h') goto yy1239; if (yych <= 'z') goto yy144; goto yy4; } } yy1431: YYDEBUG(1431, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'M') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'N') goto yy1429; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'm') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'n') goto yy1461; if (yych <= 'z') goto yy147; goto yy4; } } } yy1432: YYDEBUG(1432, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'T') { if (yych <= '.') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych == '-') goto yy148; goto yy4; } } else { if (yych <= '@') { if (yych <= '/') goto yy148; goto yy4; } else { if (yych == 'I') goto yy1421; goto yy142; } } } else { if (yych <= '`') { if (yych <= 'Z') { if (yych <= 'U') goto yy1422; goto yy142; } else { if (yych == '_') goto yy148; goto yy4; } } else { if (yych <= 't') { if (yych == 'i') goto yy1453; goto yy147; } else { if (yych <= 'u') goto yy1454; if (yych <= 'z') goto yy147; goto yy4; } } } yy1433: YYDEBUG(1433, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'L') { if (yych <= '.') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych == '-') goto yy148; goto yy4; } } else { if (yych <= '@') { if (yych <= '/') goto yy148; goto yy4; } else { if (yych == 'D') goto yy1410; goto yy142; } } } else { if (yych <= '`') { if (yych <= 'Z') { if (yych <= 'M') goto yy1411; goto yy142; } else { if (yych == '_') goto yy148; goto yy4; } } else { if (yych <= 'l') { if (yych == 'd') goto yy1444; goto yy147; } else { if (yych <= 'm') goto yy1445; if (yych <= 'z') goto yy147; goto yy4; } } } yy1434: YYDEBUG(1434, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'E') goto yy1406; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'd') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'e') goto yy1440; if (yych <= 'z') goto yy147; goto yy4; } } } yy1435: YYDEBUG(1435, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'E') goto yy1402; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'd') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'e') goto yy1436; if (yych <= 'z') goto yy147; goto yy4; } } } yy1436: YYDEBUG(1436, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'K') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'L') goto yy1403; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'k') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 'l') goto yy1437; if (yych <= 'z') goto yy151; goto yy4; } } } yy1437: YYDEBUG(1437, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'E') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'F') goto yy1404; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'e') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'f') goto yy1438; if (yych <= 'z') goto yy152; goto yy4; } } } yy1438: YYDEBUG(1438, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1405; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 't') goto yy1439; if (yych <= 'z') goto yy153; goto yy4; } } } yy1439: YYDEBUG(1439, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'G') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'H') goto yy1206; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'h') goto yy1224; if (yych <= 'z') goto yy154; goto yy4; } } yy1440: YYDEBUG(1440, *YYCURSOR); yyaccept = 4; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'R') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy167; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy167; goto yy143; } } else { if (yych <= '_') { if (yych <= 'S') goto yy1407; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy167; goto yy148; } else { if (yych <= 'r') { if (yych <= '`') goto yy167; goto yy151; } else { if (yych <= 's') goto yy1441; if (yych <= 'z') goto yy151; goto yy167; } } } yy1441: YYDEBUG(1441, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'D') goto yy1408; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'c') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'd') goto yy1442; if (yych <= 'z') goto yy152; goto yy4; } } } yy1442: YYDEBUG(1442, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '_') { if (yych <= 'A') goto yy1409; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'a') goto yy1443; if (yych <= 'z') goto yy153; goto yy4; } } yy1443: YYDEBUG(1443, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'X') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'Y') goto yy173; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'y') goto yy186; if (yych <= 'z') goto yy154; goto yy4; } } yy1444: YYDEBUG(1444, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '_') { if (yych <= 'A') goto yy1418; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'a') goto yy1451; if (yych <= 'z') goto yy151; goto yy4; } } yy1445: YYDEBUG(1445, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'N') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'O') goto yy1412; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'n') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 'o') goto yy1446; if (yych <= 'z') goto yy151; goto yy4; } } } yy1446: YYDEBUG(1446, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'Q') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'R') goto yy1413; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'q') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'r') goto yy1447; if (yych <= 'z') goto yy152; goto yy4; } } } yy1447: YYDEBUG(1447, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'Q') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'R') goto yy1414; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'q') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'r') goto yy1448; if (yych <= 'z') goto yy153; goto yy4; } } } yy1448: YYDEBUG(1448, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'N') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'O') goto yy1415; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'o') goto yy1449; if (yych <= 'z') goto yy154; goto yy4; } } yy1449: YYDEBUG(1449, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'W') goto yy1416; if (yych != 'w') goto yy155; YYDEBUG(1450, *YYCURSOR); yyaccept = 29; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 16) { goto yy154; } if (yych <= '.') { if (yych == '-') goto yy148; goto yy1417; } else { if (yych <= '/') goto yy148; if (yych == '_') goto yy148; goto yy1417; } yy1451: YYDEBUG(1451, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'X') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'Y') goto yy1419; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'x') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'y') goto yy1452; if (yych <= 'z') goto yy152; goto yy4; } } } yy1452: YYDEBUG(1452, *YYCURSOR); yyaccept = 30; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy1420; } else { if (yych == '.') goto yy1420; goto yy148; } } else { if (yych <= '^') { if (yych <= '@') goto yy1420; if (yych <= 'Z') goto yy145; goto yy1420; } else { if (yych <= '_') goto yy148; if (yych <= '`') goto yy1420; if (yych <= 'z') goto yy153; goto yy1420; } } yy1453: YYDEBUG(1453, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'R') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych <= '/') { if (yych <= '.') goto yy4; goto yy148; } else { if (yych <= '@') goto yy4; if (yych <= 'Q') goto yy143; goto yy1427; } } } else { if (yych <= '`') { if (yych <= 'Z') { if (yych <= 'S') goto yy1428; goto yy143; } else { if (yych == '_') goto yy148; goto yy4; } } else { if (yych <= 'r') { if (yych <= 'q') goto yy151; goto yy1459; } else { if (yych <= 's') goto yy1460; if (yych <= 'z') goto yy151; goto yy4; } } } yy1454: YYDEBUG(1454, *YYCURSOR); yyaccept = 4; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'Q') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy167; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy167; goto yy143; } } else { if (yych <= '_') { if (yych <= 'R') goto yy1423; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy167; goto yy148; } else { if (yych <= 'q') { if (yych <= '`') goto yy167; goto yy151; } else { if (yych <= 'r') goto yy1455; if (yych <= 'z') goto yy151; goto yy167; } } } yy1455: YYDEBUG(1455, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'R') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'S') goto yy1424; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'r') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 's') goto yy1456; if (yych <= 'z') goto yy152; goto yy4; } } } yy1456: YYDEBUG(1456, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'D') goto yy1425; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'c') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'd') goto yy1457; if (yych <= 'z') goto yy153; goto yy4; } } } yy1457: YYDEBUG(1457, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '_') { if (yych <= 'A') goto yy1426; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'a') goto yy1458; if (yych <= 'z') goto yy154; goto yy4; } } yy1458: YYDEBUG(1458, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy173; if (yych == 'y') goto yy186; goto yy155; yy1459: YYDEBUG(1459, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'D') goto yy1239; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'c') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'd') goto yy1268; if (yych <= 'z') goto yy152; goto yy4; } } } yy1460: YYDEBUG(1460, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '-') { if (yych <= ' ') { if (yych == '\t') goto yy1105; if (yych <= 0x1F) goto yy4; goto yy1105; } else { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } } else { if (yych <= 'Z') { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } else { if (yych <= '_') { if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'z') goto yy152; goto yy4; } } } yy1461: YYDEBUG(1461, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1430; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 't') goto yy1462; if (yych <= 'z') goto yy151; goto yy4; } } } yy1462: YYDEBUG(1462, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'G') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'H') goto yy1239; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'g') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'h') goto yy1268; if (yych <= 'z') goto yy152; goto yy4; } } } yy1463: YYDEBUG(1463, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych <= '@') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == 'R') goto yy1475; if (yych <= 'X') goto yy142; goto yy1476; } } else { if (yych <= 'r') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; if (yych <= 'q') goto yy142; goto yy1475; } else { if (yych == 'y') goto yy1476; if (yych <= 'z') goto yy142; goto yy4; } } yy1464: YYDEBUG(1464, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'D') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'C') goto yy142; goto yy1469; } } else { if (yych <= 'c') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'd') goto yy1469; if (yych <= 'z') goto yy142; goto yy4; } } yy1465: YYDEBUG(1465, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'M') goto yy142; } } else { if (yych <= 'm') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'n') goto yy1466; if (yych <= 'z') goto yy142; goto yy4; } } yy1466: YYDEBUG(1466, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'D') { if (yych <= ')') { if (yych <= '(') goto yy167; goto yy140; } else { if (yych <= '@') goto yy167; if (yych <= 'C') goto yy143; } } else { if (yych <= 'c') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy167; goto yy143; } else { if (yych <= 'd') goto yy1467; if (yych <= 'z') goto yy143; goto yy167; } } yy1467: YYDEBUG(1467, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'A') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; } else { if (yych <= '`') { if (yych <= 'Z') goto yy144; goto yy4; } else { if (yych <= 'a') goto yy1468; if (yych <= 'z') goto yy144; goto yy4; } } yy1468: YYDEBUG(1468, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'X') goto yy145; goto yy1236; } } else { if (yych <= 'x') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'y') goto yy1236; if (yych <= 'z') goto yy145; goto yy4; } } yy1469: YYDEBUG(1469, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'M') goto yy143; } } else { if (yych <= 'm') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'n') goto yy1470; if (yych <= 'z') goto yy143; goto yy4; } } yy1470: YYDEBUG(1470, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'I') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'H') goto yy144; } } else { if (yych <= 'h') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'i') goto yy1471; if (yych <= 'z') goto yy144; goto yy4; } } yy1471: YYDEBUG(1471, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'G') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'F') goto yy145; } } else { if (yych <= 'f') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'g') goto yy1472; if (yych <= 'z') goto yy145; goto yy4; } } yy1472: YYDEBUG(1472, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'G') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'H') goto yy1473; if (yych != 'h') goto yy4; } yy1473: YYDEBUG(1473, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy1474; if (yych != 't') goto yy57; yy1474: YYDEBUG(1474, *YYCURSOR); yych = *++YYCURSOR; goto yy1420; yy1475: YYDEBUG(1475, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; goto yy194; } else { if (yych <= '-') goto yy197; if (yych <= '.') goto yy196; goto yy194; } } } else { if (yych <= 'Z') { if (yych <= '@') { if (yych <= '9') goto yy196; goto yy194; } else { if (yych == 'C') goto yy1477; goto yy143; } } else { if (yych <= 'b') { if (yych <= '`') goto yy194; goto yy143; } else { if (yych <= 'c') goto yy1477; if (yych <= 'z') goto yy143; goto yy194; } } } yy1476: YYDEBUG(1476, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '-') { if (yych <= ' ') { if (yych == '\t') goto yy196; if (yych <= 0x1F) goto yy194; goto yy196; } else { if (yych == ')') goto yy140; if (yych <= ',') goto yy194; goto yy197; } } else { if (yych <= '@') { if (yych == '/') goto yy194; if (yych <= '9') goto yy196; goto yy194; } else { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy194; if (yych <= 'z') goto yy143; goto yy194; } } yy1477: YYDEBUG(1477, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'H') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'G') goto yy144; goto yy396; } } else { if (yych <= 'g') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'h') goto yy396; if (yych <= 'z') goto yy144; goto yy4; } } yy1478: YYDEBUG(1478, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'X') { if (yych <= '.') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych == '-') goto yy148; goto yy4; } } else { if (yych <= '@') { if (yych <= '/') goto yy148; goto yy4; } else { if (yych == 'R') goto yy1475; goto yy142; } } } else { if (yych <= '`') { if (yych <= 'Z') { if (yych <= 'Y') goto yy1476; goto yy142; } else { if (yych == '_') goto yy148; goto yy4; } } else { if (yych <= 'x') { if (yych == 'r') goto yy1490; goto yy147; } else { if (yych <= 'y') goto yy1491; if (yych <= 'z') goto yy147; goto yy4; } } } yy1479: YYDEBUG(1479, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'D') goto yy1469; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'c') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'd') goto yy1484; if (yych <= 'z') goto yy147; goto yy4; } } } yy1480: YYDEBUG(1480, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'M') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'N') goto yy1466; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'm') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'n') goto yy1481; if (yych <= 'z') goto yy147; goto yy4; } } } yy1481: YYDEBUG(1481, *YYCURSOR); yyaccept = 4; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy167; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy167; goto yy143; } } else { if (yych <= '_') { if (yych <= 'D') goto yy1467; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy167; goto yy148; } else { if (yych <= 'c') { if (yych <= '`') goto yy167; goto yy151; } else { if (yych <= 'd') goto yy1482; if (yych <= 'z') goto yy151; goto yy167; } } } yy1482: YYDEBUG(1482, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '@') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '_') { if (yych <= 'A') goto yy1468; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= '`') goto yy4; if (yych <= 'a') goto yy1483; if (yych <= 'z') goto yy152; goto yy4; } } yy1483: YYDEBUG(1483, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'X') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'Y') goto yy1236; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'x') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'y') goto yy1265; if (yych <= 'z') goto yy153; goto yy4; } } } yy1484: YYDEBUG(1484, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'M') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'N') goto yy1470; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'm') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 'n') goto yy1485; if (yych <= 'z') goto yy151; goto yy4; } } } yy1485: YYDEBUG(1485, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'H') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'I') goto yy1471; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'h') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'i') goto yy1486; if (yych <= 'z') goto yy152; goto yy4; } } } yy1486: YYDEBUG(1486, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'F') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'G') goto yy1472; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'f') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'g') goto yy1487; if (yych <= 'z') goto yy153; goto yy4; } } } yy1487: YYDEBUG(1487, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'G') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'H') goto yy1473; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'h') goto yy1488; if (yych <= 'z') goto yy154; goto yy4; } } yy1488: YYDEBUG(1488, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy1474; if (yych != 't') goto yy155; YYDEBUG(1489, *YYCURSOR); yyaccept = 30; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 16) { goto yy154; } if (yych <= '.') { if (yych == '-') goto yy148; goto yy1420; } else { if (yych <= '/') goto yy148; if (yych == '_') goto yy148; goto yy1420; } yy1490: YYDEBUG(1490, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= '-') { if (yych <= ')') goto yy140; if (yych <= ',') goto yy194; goto yy372; } else { if (yych == '/') goto yy148; goto yy196; } } } else { if (yych <= '^') { if (yych <= 'B') { if (yych <= '@') goto yy194; goto yy143; } else { if (yych <= 'C') goto yy1477; if (yych <= 'Z') goto yy143; goto yy194; } } else { if (yych <= 'b') { if (yych <= '_') goto yy148; if (yych <= '`') goto yy194; goto yy151; } else { if (yych <= 'c') goto yy1492; if (yych <= 'z') goto yy151; goto yy194; } } } yy1491: YYDEBUG(1491, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '.') { if (yych <= ' ') { if (yych == '\t') goto yy196; if (yych <= 0x1F) goto yy194; goto yy196; } else { if (yych <= ')') { if (yych <= '(') goto yy194; goto yy140; } else { if (yych <= ',') goto yy194; if (yych <= '-') goto yy372; goto yy196; } } } else { if (yych <= 'Z') { if (yych <= '/') goto yy148; if (yych <= '9') goto yy196; if (yych <= '@') goto yy194; goto yy143; } else { if (yych <= '_') { if (yych <= '^') goto yy194; goto yy148; } else { if (yych <= '`') goto yy194; if (yych <= 'z') goto yy151; goto yy194; } } } yy1492: YYDEBUG(1492, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'G') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'H') goto yy396; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'g') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'h') goto yy407; if (yych <= 'z') goto yy152; goto yy4; } } } yy1493: YYDEBUG(1493, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'W') { if (yych <= 'N') { if (yych == ')') goto yy140; if (yych <= '@') goto yy4; goto yy142; } else { if (yych <= 'O') goto yy1501; if (yych <= 'U') goto yy142; if (yych <= 'V') goto yy1502; goto yy1499; } } else { if (yych <= 'o') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; if (yych <= 'n') goto yy142; goto yy1501; } else { if (yych <= 'v') { if (yych <= 'u') goto yy142; goto yy1502; } else { if (yych <= 'w') goto yy1499; if (yych <= 'z') goto yy142; goto yy4; } } } yy1494: YYDEBUG(1494, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'X') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'W') goto yy142; goto yy1498; } } else { if (yych <= 'w') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'x') goto yy1498; if (yych <= 'z') goto yy142; goto yy4; } } yy1495: YYDEBUG(1495, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'M') goto yy142; } } else { if (yych <= 'm') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 'n') goto yy1496; if (yych <= 'z') goto yy142; goto yy4; } } yy1496: YYDEBUG(1496, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy143; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 't') goto yy1497; if (yych <= 'z') goto yy143; goto yy4; } } yy1497: YYDEBUG(1497, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'H') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'G') goto yy144; goto yy1239; } } else { if (yych <= 'g') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'h') goto yy1239; if (yych <= 'z') goto yy144; goto yy4; } } yy1498: YYDEBUG(1498, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy143; goto yy1428; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 't') goto yy1428; if (yych <= 'z') goto yy143; goto yy4; } } yy1499: YYDEBUG(1499, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '@') { if (yych == ')') goto yy140; } else { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy1500; if (yych <= 'z') goto yy143; } yy1500: YYDEBUG(1500, *YYCURSOR); #line 1014 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("now"); TIMELIB_INIT; TIMELIB_DEINIT; return TIMELIB_RELATIVE; } #line 23901 "ext/date/lib/parse_date.c" yy1501: YYDEBUG(1501, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'N') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'M') goto yy143; goto yy1507; } } else { if (yych <= 'm') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 'n') goto yy1507; if (yych <= 'z') goto yy143; goto yy4; } } yy1502: YYDEBUG(1502, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= ',') { if (yych <= ')') goto yy140; goto yy194; } else { if (yych <= '-') goto yy197; if (yych <= '.') goto yy196; goto yy194; } } } else { if (yych <= 'Z') { if (yych <= '@') { if (yych <= '9') goto yy196; goto yy194; } else { if (yych != 'E') goto yy143; } } else { if (yych <= 'd') { if (yych <= '`') goto yy194; goto yy143; } else { if (yych <= 'e') goto yy1503; if (yych <= 'z') goto yy143; goto yy194; } } } yy1503: YYDEBUG(1503, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'M') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'L') goto yy144; } } else { if (yych <= 'l') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'm') goto yy1504; if (yych <= 'z') goto yy144; goto yy4; } } yy1504: YYDEBUG(1504, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'B') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'A') goto yy145; } } else { if (yych <= 'a') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'b') goto yy1505; if (yych <= 'z') goto yy145; goto yy4; } } yy1505: YYDEBUG(1505, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'E') goto yy1506; if (yych != 'e') goto yy4; } yy1506: YYDEBUG(1506, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy206; if (yych == 'r') goto yy206; goto yy57; yy1507: YYDEBUG(1507, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '@') { if (yych == ')') goto yy140; } else { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy1508; if (yych <= 'z') goto yy144; } yy1508: YYDEBUG(1508, *YYCURSOR); #line 1023 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("noon"); TIMELIB_INIT; TIMELIB_UNHAVE_TIME(); TIMELIB_HAVE_TIME(); s->time->h = 12; TIMELIB_DEINIT; return TIMELIB_RELATIVE; } #line 24051 "ext/date/lib/parse_date.c" yy1509: YYDEBUG(1509, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'V') { if (yych <= '.') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych == '-') goto yy148; goto yy4; } } else { if (yych <= 'N') { if (yych <= '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } else { if (yych <= 'O') goto yy1501; if (yych <= 'U') goto yy142; goto yy1502; } } } else { if (yych <= 'n') { if (yych <= '^') { if (yych <= 'W') goto yy1499; if (yych <= 'Z') goto yy142; goto yy4; } else { if (yych <= '_') goto yy148; if (yych <= '`') goto yy4; goto yy147; } } else { if (yych <= 'v') { if (yych <= 'o') goto yy1516; if (yych <= 'u') goto yy147; goto yy1517; } else { if (yych <= 'w') goto yy1515; if (yych <= 'z') goto yy147; goto yy4; } } } yy1510: YYDEBUG(1510, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'W') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'X') goto yy1498; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'w') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'x') goto yy1514; if (yych <= 'z') goto yy147; goto yy4; } } } yy1511: YYDEBUG(1511, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'M') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'N') goto yy1496; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'm') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 'n') goto yy1512; if (yych <= 'z') goto yy147; goto yy4; } } } yy1512: YYDEBUG(1512, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1497; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 't') goto yy1513; if (yych <= 'z') goto yy151; goto yy4; } } } yy1513: YYDEBUG(1513, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'G') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'H') goto yy1239; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'g') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'h') goto yy1268; if (yych <= 'z') goto yy152; goto yy4; } } } yy1514: YYDEBUG(1514, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1428; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 't') goto yy1460; if (yych <= 'z') goto yy151; goto yy4; } } } yy1515: YYDEBUG(1515, *YYCURSOR); yyaccept = 31; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy1500; } else { if (yych == '.') goto yy1500; goto yy148; } } else { if (yych <= '^') { if (yych <= '@') goto yy1500; if (yych <= 'Z') goto yy143; goto yy1500; } else { if (yych <= '_') goto yy148; if (yych <= '`') goto yy1500; if (yych <= 'z') goto yy151; goto yy1500; } } yy1516: YYDEBUG(1516, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'M') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'N') goto yy1507; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'm') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 'n') goto yy1522; if (yych <= 'z') goto yy151; goto yy4; } } } yy1517: YYDEBUG(1517, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych <= '(') { if (yych <= '\t') { if (yych <= 0x08) goto yy194; goto yy196; } else { if (yych == ' ') goto yy196; goto yy194; } } else { if (yych <= '-') { if (yych <= ')') goto yy140; if (yych <= ',') goto yy194; goto yy372; } else { if (yych == '/') goto yy148; goto yy196; } } } else { if (yych <= '^') { if (yych <= 'D') { if (yych <= '@') goto yy194; goto yy143; } else { if (yych <= 'E') goto yy1503; if (yych <= 'Z') goto yy143; goto yy194; } } else { if (yych <= 'd') { if (yych <= '_') goto yy148; if (yych <= '`') goto yy194; goto yy151; } else { if (yych <= 'e') goto yy1518; if (yych <= 'z') goto yy151; goto yy194; } } } yy1518: YYDEBUG(1518, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'L') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'M') goto yy1504; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'l') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'm') goto yy1519; if (yych <= 'z') goto yy152; goto yy4; } } } yy1519: YYDEBUG(1519, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'A') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'B') goto yy1505; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'a') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'b') goto yy1520; if (yych <= 'z') goto yy153; goto yy4; } } } yy1520: YYDEBUG(1520, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'E') goto yy1506; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'e') goto yy1521; if (yych <= 'z') goto yy154; goto yy4; } } yy1521: YYDEBUG(1521, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy206; if (yych == 'r') goto yy377; goto yy155; yy1522: YYDEBUG(1522, *YYCURSOR); yyaccept = 32; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '/') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy1508; } else { if (yych == '.') goto yy1508; goto yy148; } } else { if (yych <= '^') { if (yych <= '@') goto yy1508; if (yych <= 'Z') goto yy144; goto yy1508; } else { if (yych <= '_') goto yy148; if (yych <= '`') goto yy1508; if (yych <= 'z') goto yy152; goto yy1508; } } yy1523: YYDEBUG(1523, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'R') goto yy142; } } else { if (yych <= 'r') { if (yych <= 'Z') goto yy142; if (yych <= '`') goto yy4; goto yy142; } else { if (yych <= 's') goto yy1524; if (yych <= 'z') goto yy142; goto yy4; } } yy1524: YYDEBUG(1524, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'S') goto yy143; } } else { if (yych <= 's') { if (yych <= 'Z') goto yy143; if (yych <= '`') goto yy4; goto yy143; } else { if (yych <= 't') goto yy1525; if (yych <= 'z') goto yy143; goto yy4; } } yy1525: YYDEBUG(1525, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'D') goto yy144; } } else { if (yych <= 'd') { if (yych <= 'Z') goto yy144; if (yych <= '`') goto yy4; goto yy144; } else { if (yych <= 'e') goto yy1526; if (yych <= 'z') goto yy144; goto yy4; } } yy1526: YYDEBUG(1526, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych <= ')') { if (yych <= '(') goto yy4; goto yy140; } else { if (yych <= '@') goto yy4; if (yych <= 'Q') goto yy145; } } else { if (yych <= 'q') { if (yych <= 'Z') goto yy145; if (yych <= '`') goto yy4; goto yy145; } else { if (yych <= 'r') goto yy1527; if (yych <= 'z') goto yy145; goto yy4; } } yy1527: YYDEBUG(1527, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych == ')') goto yy140; goto yy4; } else { if (yych <= 'D') goto yy1528; if (yych != 'd') goto yy4; } yy1528: YYDEBUG(1528, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1529; if (yych != 'a') goto yy57; yy1529: YYDEBUG(1529, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy1530; if (yych != 'y') goto yy57; yy1530: YYDEBUG(1530, *YYCURSOR); ++YYCURSOR; yy1531: YYDEBUG(1531, *YYCURSOR); #line 1002 "ext/date/lib/parse_date.re" { DEBUG_OUTPUT("yesterday"); TIMELIB_INIT; TIMELIB_HAVE_RELATIVE(); TIMELIB_UNHAVE_TIME(); s->time->relative.d = -1; TIMELIB_DEINIT; return TIMELIB_RELATIVE; } #line 24595 "ext/date/lib/parse_date.c" yy1532: YYDEBUG(1532, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'R') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy142; } } else { if (yych <= '_') { if (yych <= 'S') goto yy1524; if (yych <= 'Z') goto yy142; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'r') { if (yych <= '`') goto yy4; goto yy147; } else { if (yych <= 's') goto yy1533; if (yych <= 'z') goto yy147; goto yy4; } } } yy1533: YYDEBUG(1533, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy143; } } else { if (yych <= '_') { if (yych <= 'T') goto yy1525; if (yych <= 'Z') goto yy143; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 's') { if (yych <= '`') goto yy4; goto yy151; } else { if (yych <= 't') goto yy1534; if (yych <= 'z') goto yy151; goto yy4; } } } yy1534: YYDEBUG(1534, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'D') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy144; } } else { if (yych <= '_') { if (yych <= 'E') goto yy1526; if (yych <= 'Z') goto yy144; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'd') { if (yych <= '`') goto yy4; goto yy152; } else { if (yych <= 'e') goto yy1535; if (yych <= 'z') goto yy152; goto yy4; } } } yy1535: YYDEBUG(1535, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'Q') { if (yych <= '-') { if (yych == ')') goto yy140; if (yych <= ',') goto yy4; goto yy148; } else { if (yych == '/') goto yy148; if (yych <= '@') goto yy4; goto yy145; } } else { if (yych <= '_') { if (yych <= 'R') goto yy1527; if (yych <= 'Z') goto yy145; if (yych <= '^') goto yy4; goto yy148; } else { if (yych <= 'q') { if (yych <= '`') goto yy4; goto yy153; } else { if (yych <= 'r') goto yy1536; if (yych <= 'z') goto yy153; goto yy4; } } } yy1536: YYDEBUG(1536, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'C') { if (yych <= ',') { if (yych == ')') goto yy140; goto yy4; } else { if (yych == '.') goto yy4; if (yych <= '/') goto yy148; goto yy4; } } else { if (yych <= '`') { if (yych <= 'D') goto yy1528; if (yych == '_') goto yy148; goto yy4; } else { if (yych == 'd') goto yy1537; if (yych <= 'z') goto yy154; goto yy4; } } yy1537: YYDEBUG(1537, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy1529; if (yych != 'a') goto yy155; YYDEBUG(1538, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy1530; if (yych != 'y') goto yy155; YYDEBUG(1539, *YYCURSOR); yyaccept = 33; yych = *(YYMARKER = ++YYCURSOR); if (yybm[0+yych] & 16) { goto yy154; } if (yych <= '.') { if (yych == '-') goto yy148; goto yy1531; } else { if (yych <= '/') goto yy148; if (yych == '_') goto yy148; goto yy1531; } } #line 1775 "ext/date/lib/parse_date.re" } #define YYMAXFILL 31 timelib_time* timelib_strtotime(char *s, int len, struct timelib_error_container **errors, const timelib_tzdb *tzdb) { Scanner in; int t; char *e = s + len - 1; memset(&in, 0, sizeof(in)); in.errors = malloc(sizeof(struct timelib_error_container)); in.errors->warning_count = 0; in.errors->warning_messages = NULL; in.errors->error_count = 0; in.errors->error_messages = NULL; if (len > 0) { while (isspace(*s) && s < e) { s++; } while (isspace(*e) && e > s) { e--; } } if (e - s < 0) { in.time = timelib_time_ctor(); add_error(&in, "Empty string"); if (errors) { *errors = in.errors; } else { timelib_error_container_dtor(in.errors); } in.time->y = in.time->d = in.time->m = in.time->h = in.time->i = in.time->s = in.time->f = in.time->dst = in.time->z = TIMELIB_UNSET; in.time->is_localtime = in.time->zone_type = 0; return in.time; } e++; in.str = malloc((e - s) + YYMAXFILL); memset(in.str, 0, (e - s) + YYMAXFILL); memcpy(in.str, s, (e - s)); in.lim = in.str + (e - s) + YYMAXFILL; in.cur = in.str; in.time = timelib_time_ctor(); in.time->y = TIMELIB_UNSET; in.time->d = TIMELIB_UNSET; in.time->m = TIMELIB_UNSET; in.time->h = TIMELIB_UNSET; in.time->i = TIMELIB_UNSET; in.time->s = TIMELIB_UNSET; in.time->f = TIMELIB_UNSET; in.time->z = TIMELIB_UNSET; in.time->dst = TIMELIB_UNSET; in.tzdb = tzdb; in.time->is_localtime = 0; in.time->zone_type = 0; do { t = scan(&in); #ifdef DEBUG_PARSER printf("%d\n", t); #endif } while(t != EOI); /* do funky checking whether the parsed time was valid time */ if (in.time->have_time && !timelib_valid_time( in.time->h, in.time->i, in.time->s)) { add_warning(&in, "The parsed time was invalid"); } /* do funky checking whether the parsed date was valid date */ if (in.time->have_date && !timelib_valid_date( in.time->y, in.time->m, in.time->d)) { add_warning(&in, "The parsed date was invalid"); } free(in.str); if (errors) { *errors = in.errors; } else { timelib_error_container_dtor(in.errors); } return in.time; } #define TIMELIB_CHECK_NUMBER \ if (strchr("0123456789", *ptr) == NULL) \ { \ add_pbf_error(s, "Unexpected data found.", string, begin); \ } static void timelib_time_reset_fields(timelib_time *time) { assert(time != NULL); time->y = 1970; time->m = 1; time->d = 1; time->h = time->i = time->s = 0; time->f = 0.0; time->tz_info = NULL; } static void timelib_time_reset_unset_fields(timelib_time *time) { assert(time != NULL); if (time->y == TIMELIB_UNSET ) time->y = 1970; if (time->m == TIMELIB_UNSET ) time->m = 1; if (time->d == TIMELIB_UNSET ) time->d = 1; if (time->h == TIMELIB_UNSET ) time->h = 0; if (time->i == TIMELIB_UNSET ) time->i = 0; if (time->s == TIMELIB_UNSET ) time->s = 0; if (time->f == TIMELIB_UNSET ) time->f = 0.0; } timelib_time *timelib_parse_from_format(char *format, char *string, int len, timelib_error_container **errors, const timelib_tzdb *tzdb) { char *fptr = format; char *ptr = string; char *begin; timelib_sll tmp; Scanner in; Scanner *s = &in; int allow_extra = 0; memset(&in, 0, sizeof(in)); in.errors = malloc(sizeof(struct timelib_error_container)); in.errors->warning_count = 0; in.errors->warning_messages = NULL; in.errors->error_count = 0; in.errors->error_messages = NULL; in.time = timelib_time_ctor(); in.time->y = TIMELIB_UNSET; in.time->d = TIMELIB_UNSET; in.time->m = TIMELIB_UNSET; in.time->h = TIMELIB_UNSET; in.time->i = TIMELIB_UNSET; in.time->s = TIMELIB_UNSET; in.time->f = TIMELIB_UNSET; in.time->z = TIMELIB_UNSET; in.time->dst = TIMELIB_UNSET; in.tzdb = tzdb; in.time->is_localtime = 0; in.time->zone_type = 0; /* Loop over the format string */ while (*fptr && *ptr) { begin = ptr; switch (*fptr) { case 'D': /* three letter day */ case 'l': /* full day */ { const timelib_relunit* tmprel = 0; tmprel = timelib_lookup_relunit((char **) &ptr); if (!tmprel) { add_pbf_error(s, "A textual day could not be found", string, begin); break; } else { in.time->have_relative = 1; in.time->relative.have_weekday_relative = 1; in.time->relative.weekday = tmprel->multiplier; in.time->relative.weekday_behavior = 1; } } break; case 'd': /* two digit day, with leading zero */ case 'j': /* two digit day, without leading zero */ TIMELIB_CHECK_NUMBER; if ((s->time->d = timelib_get_nr((char **) &ptr, 2)) == TIMELIB_UNSET) { add_pbf_error(s, "A two digit day could not be found", string, begin); } break; case 'S': /* day suffix, ignored, nor checked */ timelib_skip_day_suffix((char **) &ptr); break; case 'z': /* day of year - resets month (0 based) */ TIMELIB_CHECK_NUMBER; if ((tmp = timelib_get_nr((char **) &ptr, 3)) == TIMELIB_UNSET) { add_pbf_error(s, "A three digit day-of-year could not be found", string, begin); } else { s->time->m = 1; s->time->d = tmp + 1; } break; case 'm': /* two digit month, with leading zero */ case 'n': /* two digit month, without leading zero */ TIMELIB_CHECK_NUMBER; if ((s->time->m = timelib_get_nr((char **) &ptr, 2)) == TIMELIB_UNSET) { add_pbf_error(s, "A two digit month could not be found", string, begin); } break; case 'M': /* three letter month */ case 'F': /* full month */ tmp = timelib_lookup_month((char **) &ptr); if (!tmp) { add_pbf_error(s, "A textual month could not be found", string, begin); } else { s->time->m = tmp; } break; case 'y': /* two digit year */ { int length = 0; TIMELIB_CHECK_NUMBER; if ((s->time->y = timelib_get_nr_ex((char **) &ptr, 2, &length)) == TIMELIB_UNSET) { add_pbf_error(s, "A two digit year could not be found", string, begin); } TIMELIB_PROCESS_YEAR(s->time->y, length); } break; case 'Y': /* four digit year */ TIMELIB_CHECK_NUMBER; if ((s->time->y = timelib_get_nr((char **) &ptr, 4)) == TIMELIB_UNSET) { add_pbf_error(s, "A four digit year could not be found", string, begin); } break; case 'g': /* two digit hour, with leading zero */ case 'h': /* two digit hour, without leading zero */ TIMELIB_CHECK_NUMBER; if ((s->time->h = timelib_get_nr((char **) &ptr, 2)) == TIMELIB_UNSET) { add_pbf_error(s, "A two digit hour could not be found", string, begin); } if (s->time->h > 12) { add_pbf_error(s, "Hour can not be higher than 12", string, begin); } break; case 'G': /* two digit hour, with leading zero */ case 'H': /* two digit hour, without leading zero */ TIMELIB_CHECK_NUMBER; if ((s->time->h = timelib_get_nr((char **) &ptr, 2)) == TIMELIB_UNSET) { add_pbf_error(s, "A two digit hour could not be found", string, begin); } break; case 'a': /* am/pm/a.m./p.m. */ case 'A': /* AM/PM/A.M./P.M. */ if (s->time->h == TIMELIB_UNSET) { add_pbf_error(s, "Meridian can only come after an hour has been found", string, begin); } else if ((tmp = timelib_meridian_with_check((char **) &ptr, s->time->h)) == TIMELIB_UNSET) { add_pbf_error(s, "A meridian could not be found", string, begin); } else { s->time->h += tmp; } break; case 'i': /* two digit minute, with leading zero */ { int length; timelib_sll min; TIMELIB_CHECK_NUMBER; min = timelib_get_nr_ex((char **) &ptr, 2, &length); if (min == TIMELIB_UNSET || length != 2) { add_pbf_error(s, "A two digit minute could not be found", string, begin); } else { s->time->i = min; } } break; case 's': /* two digit second, with leading zero */ { int length; timelib_sll sec; TIMELIB_CHECK_NUMBER; sec = timelib_get_nr_ex((char **) &ptr, 2, &length); if (sec == TIMELIB_UNSET || length != 2) { add_pbf_error(s, "A two second minute could not be found", string, begin); } else { s->time->s = sec; } } break; case 'u': /* up to six digit millisecond */ { double f; char *tptr; TIMELIB_CHECK_NUMBER; tptr = ptr; if ((f = timelib_get_nr((char **) &ptr, 6)) == TIMELIB_UNSET || (ptr - tptr < 1)) { add_pbf_error(s, "A six digit millisecond could not be found", string, begin); } else { s->time->f = (f / pow(10, (ptr - tptr))); } } break; case ' ': /* any sort of whitespace (' ' and \t) */ timelib_eat_spaces((char **) &ptr); break; case 'U': /* epoch seconds */ TIMELIB_CHECK_NUMBER; TIMELIB_HAVE_RELATIVE(); tmp = timelib_get_unsigned_nr((char **) &ptr, 24); s->time->y = 1970; s->time->m = 1; s->time->d = 1; s->time->h = s->time->i = s->time->s = 0; s->time->f = 0.0; s->time->relative.s += tmp; s->time->is_localtime = 1; s->time->zone_type = TIMELIB_ZONETYPE_OFFSET; s->time->z = 0; break; case 'e': /* timezone */ case 'P': /* timezone */ case 'T': /* timezone */ case 'O': /* timezone */ { int tz_not_found; s->time->z = timelib_get_zone((char **) &ptr, &s->time->dst, s->time, &tz_not_found, s->tzdb); if (tz_not_found) { add_pbf_error(s, "The timezone could not be found in the database", string, begin); } } break; case '#': /* separation symbol */ if (*ptr == ';' || *ptr == ':' || *ptr == '/' || *ptr == '.' || *ptr == ',' || *ptr == '-' || *ptr == '(' || *ptr == ')') { ++ptr; } else { add_pbf_error(s, "The separation symbol ([;:/.,-]) could not be found", string, begin); } break; case ';': case ':': case '/': case '.': case ',': case '-': case '(': case ')': if (*ptr == *fptr) { ++ptr; } else { add_pbf_error(s, "The separation symbol could not be found", string, begin); } break; case '!': /* reset all fields to default */ timelib_time_reset_fields(s->time); break; /* break intentionally not missing */ case '|': /* reset all fields to default when not set */ timelib_time_reset_unset_fields(s->time); break; /* break intentionally not missing */ case '?': /* random char */ ++ptr; break; case '\\': /* escaped char */ *fptr++; if (*ptr == *fptr) { ++ptr; } else { add_pbf_error(s, "The escaped character could not be found", string, begin); } break; case '*': /* random chars until a separator or number ([ \t.,:;/-0123456789]) */ timelib_eat_until_separator((char **) &ptr); break; case '+': /* allow extra chars in the format */ allow_extra = 1; break; default: if (*fptr != *ptr) { add_pbf_error(s, "The format separator does not match", string, begin); } ptr++; } fptr++; } if (*ptr) { if (allow_extra) { add_pbf_warning(s, "Trailing data", string, ptr); } else { add_pbf_error(s, "Trailing data", string, ptr); } } /* ignore trailing +'s */ while (*fptr == '+') { fptr++; } if (*fptr) { /* Trailing | and ! specifiers are valid. */ int done = 0; while (*fptr && !done) { switch (*fptr++) { case '!': /* reset all fields to default */ timelib_time_reset_fields(s->time); break; case '|': /* reset all fields to default when not set */ timelib_time_reset_unset_fields(s->time); break; default: add_pbf_error(s, "Data missing", string, ptr); done = 1; } } } /* clean up a bit */ if (s->time->h != TIMELIB_UNSET || s->time->i != TIMELIB_UNSET || s->time->s != TIMELIB_UNSET) { if (s->time->h == TIMELIB_UNSET ) { s->time->h = 0; } if (s->time->i == TIMELIB_UNSET ) { s->time->i = 0; } if (s->time->s == TIMELIB_UNSET ) { s->time->s = 0; } } /* do funky checking whether the parsed time was valid time */ if (s->time->h != TIMELIB_UNSET && s->time->i != TIMELIB_UNSET && s->time->s != TIMELIB_UNSET && !timelib_valid_time( s->time->h, s->time->i, s->time->s)) { add_pbf_warning(s, "The parsed time was invalid", string, ptr); } /* do funky checking whether the parsed date was valid date */ if (s->time->y != TIMELIB_UNSET && s->time->m != TIMELIB_UNSET && s->time->d != TIMELIB_UNSET && !timelib_valid_date( s->time->y, s->time->m, s->time->d)) { add_pbf_warning(s, "The parsed date was invalid", string, ptr); } if (errors) { *errors = in.errors; } else { timelib_error_container_dtor(in.errors); } return in.time; } void timelib_fill_holes(timelib_time *parsed, timelib_time *now, int options) { if (!(options & TIMELIB_OVERRIDE_TIME) && parsed->have_date && !parsed->have_time) { parsed->h = 0; parsed->i = 0; parsed->s = 0; parsed->f = 0; } if (parsed->y == TIMELIB_UNSET) parsed->y = now->y != TIMELIB_UNSET ? now->y : 0; if (parsed->d == TIMELIB_UNSET) parsed->d = now->d != TIMELIB_UNSET ? now->d : 0; if (parsed->m == TIMELIB_UNSET) parsed->m = now->m != TIMELIB_UNSET ? now->m : 0; if (parsed->h == TIMELIB_UNSET) parsed->h = now->h != TIMELIB_UNSET ? now->h : 0; if (parsed->i == TIMELIB_UNSET) parsed->i = now->i != TIMELIB_UNSET ? now->i : 0; if (parsed->s == TIMELIB_UNSET) parsed->s = now->s != TIMELIB_UNSET ? now->s : 0; if (parsed->f == TIMELIB_UNSET) parsed->f = now->f != TIMELIB_UNSET ? now->f : 0; if (parsed->z == TIMELIB_UNSET) parsed->z = now->z != TIMELIB_UNSET ? now->z : 0; if (parsed->dst == TIMELIB_UNSET) parsed->dst = now->dst != TIMELIB_UNSET ? now->dst : 0; if (!parsed->tz_abbr) { parsed->tz_abbr = now->tz_abbr ? strdup(now->tz_abbr) : NULL; } if (!parsed->tz_info) { parsed->tz_info = now->tz_info ? (!(options & TIMELIB_NO_CLONE) ? timelib_tzinfo_clone(now->tz_info) : now->tz_info) : NULL; } if (parsed->zone_type == 0 && now->zone_type != 0) { parsed->zone_type = now->zone_type; /* parsed->tz_abbr = now->tz_abbr ? strdup(now->tz_abbr) : NULL; parsed->tz_info = now->tz_info ? timelib_tzinfo_clone(now->tz_info) : NULL; */ parsed->is_localtime = 1; } /* timelib_dump_date(parsed, 2); timelib_dump_date(now, 2); */ } char *timelib_timezone_id_from_abbr(const char *abbr, long gmtoffset, int isdst) { const timelib_tz_lookup_table *tp; tp = zone_search(abbr, gmtoffset, isdst); if (tp) { return (tp->full_tz_name); } else { return NULL; } } const timelib_tz_lookup_table *timelib_timezone_abbreviations_list(void) { return timelib_timezone_lookup; } #ifdef DEBUG_PARSER_STUB int main(void) { timelib_time time = timelib_strtotime("May 12"); printf ("%04d-%02d-%02d %02d:%02d:%02d.%-5d %+04d %1d", time.y, time.m, time.d, time.h, time.i, time.s, time.f, time.z, time.dst); if (time.have_relative) { printf ("%3dY %3dM %3dD / %3dH %3dM %3dS", time.relative.y, time.relative.m, time.relative.d, time.relative.h, time.relative.i, time.relative.s); } if (time.have_weekday_relative) { printf (" / %d", time.relative.weekday); } if (time.have_weeknr_day) { printf(" / %dW%d", time.relative.weeknr_day.weeknr, time.relative.weeknr_day.dayofweek); } return 0; } #endif /* * vim: syntax=c */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-11-26-7c2946f80e-dc6ecd21ee.c
manybugs_data_17
#include <sys/types.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <ctype.h> #include <assert.h> #include <stdio.h> #include <fcntl.h> #include "server.h" #include "keyvalue.h" #include "log.h" #include "connections.h" #include "joblist.h" #include "fdevent.h" #include "plugin.h" #include "http_resp.h" #include "sys-files.h" #include "sys-mmap.h" #include "sys-socket.h" #include "sys-strings.h" #include "sys-process.h" #include "network_backends.h" #ifdef HAVE_SYS_FILIO_H # include <sys/filio.h> #endif enum {EOL_UNSET, EOL_N, EOL_RN}; typedef struct { char **ptr; size_t size; size_t used; } char_array; #define pid_t int typedef struct { pid_t *ptr; size_t used; size_t size; } buffer_pid_t; typedef struct { array *cgi; unsigned short execute_all; } plugin_config; typedef struct { PLUGIN_DATA; buffer_pid_t cgi_pid; buffer *tmp_buf; http_resp *resp; plugin_config **config_storage; plugin_config conf; } plugin_data; typedef enum { CGI_STATE_UNSET, CGI_STATE_CONNECTING, CGI_STATE_READ_RESPONSE_HEADER, CGI_STATE_READ_RESPONSE_CONTENT } cgi_state_t; typedef struct { pid_t pid; iosocket *sock; iosocket *wb_sock; chunkqueue *rb; chunkqueue *wb; cgi_state_t state; connection *remote_con; /* dumb pointer */ } cgi_session; static cgi_session * cgi_session_init() { cgi_session *sess = calloc(1, sizeof(*sess)); assert(sess); sess->sock = iosocket_init(); sess->wb_sock = iosocket_init(); sess->wb = chunkqueue_init(); sess->rb = chunkqueue_init(); return sess; } static void cgi_session_free(cgi_session *sess) { if (!sess) return; iosocket_free(sess->sock); iosocket_free(sess->wb_sock); chunkqueue_free(sess->wb); chunkqueue_free(sess->rb); free(sess); } INIT_FUNC(mod_cgi_init) { plugin_data *p; UNUSED(srv); p = calloc(1, sizeof(*p)); assert(p); p->tmp_buf = buffer_init(); p->resp = http_response_init(); return p; } FREE_FUNC(mod_cgi_free) { plugin_data *p = p_d; buffer_pid_t *r = &(p->cgi_pid); UNUSED(srv); if (p->config_storage) { size_t i; for (i = 0; i < srv->config_context->used; i++) { plugin_config *s = p->config_storage[i]; array_free(s->cgi); free(s); } free(p->config_storage); } if (r->ptr) free(r->ptr); buffer_free(p->tmp_buf); http_response_free(p->resp); free(p); return HANDLER_GO_ON; } #define PLUGIN_NAME "cgi" #define CONFIG_ASSIGN PLUGIN_NAME ".assign" #define CONFIG_EXECUTE_ALL PLUGIN_NAME ".execute-all" SETDEFAULTS_FUNC(mod_cgi_set_defaults) { plugin_data *p = p_d; size_t i = 0; config_values_t cv[] = { { CONFIG_ASSIGN, NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 0 */ { CONFIG_EXECUTE_ALL, NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 1 */ { NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET} }; if (!p) return HANDLER_ERROR; p->config_storage = calloc(1, srv->config_context->used * sizeof(specific_config *)); for (i = 0; i < srv->config_context->used; i++) { plugin_config *s; s = calloc(1, sizeof(plugin_config)); assert(s); s->cgi = array_init(); s->execute_all = 0; cv[0].destination = s->cgi; cv[1].destination = &(s->execute_all); p->config_storage[i] = s; if (0 != config_insert_values_global(srv, ((data_config *)srv->config_context->data[i])->value, cv)) { return HANDLER_ERROR; } } return HANDLER_GO_ON; } static int cgi_pid_add(server *srv, plugin_data *p, pid_t pid) { int m = -1; size_t i; buffer_pid_t *r = &(p->cgi_pid); UNUSED(srv); for (i = 0; i < r->used; i++) { if (r->ptr[i] > m) m = r->ptr[i]; } if (r->size == 0) { r->size = 16; r->ptr = malloc(sizeof(*r->ptr) * r->size); } else if (r->used == r->size) { r->size += 16; r->ptr = realloc(r->ptr, sizeof(*r->ptr) * r->size); } r->ptr[r->used++] = pid; return m; } static int cgi_pid_del(server *srv, plugin_data *p, pid_t pid) { size_t i; buffer_pid_t *r = &(p->cgi_pid); UNUSED(srv); for (i = 0; i < r->used; i++) { if (r->ptr[i] == pid) break; } if (i != r->used) { /* found */ if (i != r->used - 1) { r->ptr[i] = r->ptr[r->used - 1]; } r->used--; } return 0; } /** * Copy decoded response content to client connection. */ static int cgi_copy_response(server *srv, connection *con, cgi_session *sess) { chunk *c; int we_have = 0; UNUSED(srv); chunkqueue_remove_finished_chunks(sess->rb); /* copy the content to the next cq */ for (c = sess->rb->first; c; c = c->next) { if (c->mem->used == 0) continue; we_have = c->mem->used - c->offset - 1; sess->rb->bytes_out += we_have; con->send->bytes_in += we_have; if (c->offset == 0) { /* steal the buffer from the previous queue */ chunkqueue_steal_chunk(con->send, c); } else { chunkqueue_append_mem(con->send, c->mem->ptr + c->offset, c->mem->used - c->offset); c->offset = c->mem->used - 1; /* mark the incoming side as read */ } } chunkqueue_remove_finished_chunks(sess->rb); if(sess->rb->is_closed) { con->send->is_closed = 1; } return 0; } static int cgi_demux_response(server *srv, connection *con, plugin_data *p) { cgi_session *sess = con->plugin_ctx[p->id]; switch(srv->network_backend_read(srv, con, sess->sock, sess->rb)) { case NETWORK_STATUS_CONNECTION_CLOSE: fdevent_event_del(srv->ev, sess->sock); /* connection closed. close the read chunkqueue. */ sess->rb->is_closed = 1; case NETWORK_STATUS_SUCCESS: /* we got content */ break; case NETWORK_STATUS_WAIT_FOR_EVENT: return 0; default: /* oops */ ERROR("%s", "oops, read-pipe-read failed and I don't know why"); return -1; } /* looks like we got some content * * split off the header from the incoming stream */ if (con->file_started == 0) { size_t i; int have_content_length = 0; http_response_reset(p->resp); /* the response header is not fully received yet, * * extract the http-response header from the rb-cq */ switch (http_response_parse_cq(sess->rb, p->resp)) { case PARSE_UNSET: case PARSE_ERROR: /* parsing failed */ TRACE("%s", "response parser failed"); con->http_status = 502; /* Bad Gateway */ return -1; case PARSE_NEED_MORE: return 0; case PARSE_SUCCESS: con->http_status = p->resp->status; chunkqueue_remove_finished_chunks(sess->rb); /* copy the http-headers */ for (i = 0; i < p->resp->headers->used; i++) { const char *ign[] = { "Status", "Connection", NULL }; size_t j; data_string *ds; data_string *header = (data_string *)p->resp->headers->data[i]; /* some headers are ignored by default */ for (j = 0; ign[j]; j++) { if (0 == strcasecmp(ign[j], header->key->ptr)) break; } if (ign[j]) continue; if (0 == buffer_caseless_compare(CONST_BUF_LEN(header->key), CONST_STR_LEN("Location"))) { /* CGI/1.1 rev 03 - 7.2.1.2 */ if (con->http_status == 0) con->http_status = 302; } else if (0 == buffer_caseless_compare(CONST_BUF_LEN(header->key), CONST_STR_LEN("Content-Length"))) { have_content_length = 1; } if (NULL == (ds = (data_string *)array_get_unused_element(con->response.headers, TYPE_STRING))) { ds = data_response_init(); } buffer_copy_string_buffer(ds->key, header->key); buffer_copy_string_buffer(ds->value, header->value); array_insert_unique(con->response.headers, (data_unset *)ds); } con->file_started = 1; /* if Status: ... is not set, 200 is our default status-code */ if (con->http_status == 0) con->http_status = 200; sess->state = CGI_STATE_READ_RESPONSE_CONTENT; if (con->request.http_version == HTTP_VERSION_1_1 && !have_content_length) { con->response.transfer_encoding = HTTP_TRANSFER_ENCODING_CHUNKED; } break; } } /* FIXME: pass the response-header to the other plugins to * setup the filter-queue * * - use next-queue instead of con->write_queue */ /* copy the resopnse content */ cgi_copy_response(srv, con, sess); joblist_append(srv, con); return 0; } static handler_t cgi_connection_close(server *srv, connection *con, plugin_data *p) { cgi_session *sess = con->plugin_ctx[p->id]; int status; pid_t pid; if (NULL == sess) return HANDLER_GO_ON; if (con->mode != p->id) return HANDLER_GO_ON; #ifndef _WIN32 /* the connection to the browser went away, but we still have a connection * to the CGI script * * close cgi-connection */ if (sess->sock->fd != -1) { /* close connection to the cgi-script */ fdevent_event_del(srv->ev, sess->sock); fdevent_unregister(srv->ev, sess->sock); } if (sess->wb_sock->fd != -1) { close(sess->wb_sock->fd); sess->wb_sock->fd = -1; } pid = sess->pid; con->plugin_ctx[p->id] = NULL; /* is this a good idea ? */ cgi_session_free(sess); sess = NULL; /* if waitpid hasn't been called by response.c yet, do it here */ if (pid) { /* check if the CGI-script is already gone */ #ifndef _WIN32 switch(waitpid(pid, &status, WNOHANG)) { case 0: /* not finished yet */ #if 0 log_error_write(srv, __FILE__, __LINE__, "sd", "(debug) child isn't done yet, pid:", pid); #endif break; case -1: /* */ if (errno == EINTR) break; /* * errno == ECHILD happens if _subrequest catches the process-status before * we have read the response of the cgi process * * -> catch status * -> WAIT_FOR_EVENT * -> read response * -> we get here with waitpid == ECHILD * */ if (errno == ECHILD) return HANDLER_GO_ON; log_error_write(srv, __FILE__, __LINE__, "ss", "waitpid failed: ", strerror(errno)); return HANDLER_ERROR; default: /* Send an error if we haven't sent any data yet */ if (0 == con->file_started) { if (con->http_status == 0) con->http_status = 500; con->mode = DIRECT; } if (WIFEXITED(status)) { #if 0 log_error_write(srv, __FILE__, __LINE__, "sd", "(debug) cgi exited fine, pid:", pid); #endif pid = 0; return HANDLER_GO_ON; } else { log_error_write(srv, __FILE__, __LINE__, "sd", "cgi died, pid:", pid); pid = 0; return HANDLER_GO_ON; } } kill(pid, SIGTERM); #endif /* cgi-script is still alive, queue the PID for removal */ cgi_pid_add(srv, p, pid); } #endif return HANDLER_GO_ON; } static handler_t cgi_connection_close_callback(server *srv, connection *con, void *p_d) { plugin_data *p = p_d; return cgi_connection_close(srv, con, p); } static handler_t cgi_handle_fdevent(void *s, void *ctx, int revents) { server *srv = (server *)s; cgi_session *sess = ctx; connection *con = sess->remote_con; if (revents & FDEVENT_IN) { switch (sess->state) { case CGI_STATE_READ_RESPONSE_HEADER: /* parse the header and set file-started, the demuxer will care about it */ joblist_append(srv, con); break; case CGI_STATE_READ_RESPONSE_CONTENT: /* just forward the content to the out-going queue */ chunkqueue_remove_finished_chunks(sess->rb); switch (srv->network_backend_read(srv, con, sess->sock, sess->rb)) { case NETWORK_STATUS_CONNECTION_CLOSE: fdevent_event_del(srv->ev, sess->sock); /* connection closed. close the read chunkqueue. */ sess->rb->is_closed = 1; case NETWORK_STATUS_SUCCESS: /* read even more, do we have all the content */ /* how much do we want to read ? */ /* copy the resopnse content */ cgi_copy_response(srv, con, sess); break; default: ERROR("%s", "oops, we failed to read"); break; } joblist_append(srv, con); break; default: TRACE("unexpected state for a FDEVENT_IN: %d", sess->state); break; } } if (revents & FDEVENT_OUT) { /* nothing to do */ } /* perhaps this issue is already handled */ if (revents & FDEVENT_HUP) { con->send->is_closed = 1; fdevent_event_del(srv->ev, sess->sock); joblist_append(srv, con); } else if (revents & FDEVENT_ERR) { con->send->is_closed = 1; /* kill all connections to the cgi process */ fdevent_event_del(srv->ev, sess->sock); } return HANDLER_FINISHED; } static int cgi_env_add(char_array *env, const char *key, size_t key_len, const char *val, size_t val_len) { char *dst; if (!key || !val) return -1; dst = malloc(key_len + val_len + 3); memcpy(dst, key, key_len); dst[key_len] = '='; /* add the \0 from the value */ memcpy(dst + key_len + 1, val, val_len + 1); if (env->size == 0) { env->size = 16; env->ptr = malloc(env->size * sizeof(*env->ptr)); } else if (env->size == env->used) { env->size += 16; env->ptr = realloc(env->ptr, env->size * sizeof(*env->ptr)); } env->ptr[env->used++] = dst; return 0; } static int cgi_create_env(server *srv, connection *con, plugin_data *p, buffer *cgi_handler) { pid_t pid; #ifdef HAVE_IPV6 char b2[INET6_ADDRSTRLEN + 1]; #endif int to_cgi_fds[2]; int from_cgi_fds[2]; struct stat st; #ifndef _WIN32 if (cgi_handler && cgi_handler->used > 1) { /* stat the exec file */ if (-1 == (stat(cgi_handler->ptr, &st))) { log_error_write(srv, __FILE__, __LINE__, "sbss", "stat for cgi-handler", cgi_handler, "failed:", strerror(errno)); return -1; } } if (pipe(to_cgi_fds)) { log_error_write(srv, __FILE__, __LINE__, "ss", "pipe failed:", strerror(errno)); return -1; } if (pipe(from_cgi_fds)) { log_error_write(srv, __FILE__, __LINE__, "ss", "pipe failed:", strerror(errno)); return -1; } /* fork, execve */ switch (pid = fork()) { case 0: { /* child */ char **args; int argc; int i = 0; char buf[32]; size_t n; char_array env; char *c; const char *s; server_socket *srv_sock = con->srv_socket; /* move stdout to from_cgi_fd[1] */ close(STDOUT_FILENO); dup2(from_cgi_fds[1], STDOUT_FILENO); close(from_cgi_fds[1]); /* not needed */ close(from_cgi_fds[0]); /* move the stdin to to_cgi_fd[0] */ close(STDIN_FILENO); dup2(to_cgi_fds[0], STDIN_FILENO); close(to_cgi_fds[0]); /* not needed */ close(to_cgi_fds[1]); /** * FIXME: add a event-handler for STDERR_FILENO and let it LOG() */ close(STDERR_FILENO); /* create environment */ env.ptr = NULL; env.size = 0; env.used = 0; cgi_env_add(&env, CONST_STR_LEN("SERVER_SOFTWARE"), CONST_STR_LEN(PACKAGE_NAME"/"PACKAGE_VERSION)); if (!buffer_is_empty(con->server_name)) { cgi_env_add(&env, CONST_STR_LEN("SERVER_NAME"), CONST_BUF_LEN(con->server_name)); } else { #ifdef HAVE_IPV6 s = inet_ntop(srv_sock->addr.plain.sa_family, srv_sock->addr.plain.sa_family == AF_INET6 ? (const void *) &(srv_sock->addr.ipv6.sin6_addr) : (const void *) &(srv_sock->addr.ipv4.sin_addr), b2, sizeof(b2)-1); #else s = inet_ntoa(srv_sock->addr.ipv4.sin_addr); #endif cgi_env_add(&env, CONST_STR_LEN("SERVER_NAME"), s, strlen(s)); } cgi_env_add(&env, CONST_STR_LEN("GATEWAY_INTERFACE"), CONST_STR_LEN("CGI/1.1")); s = get_http_version_name(con->request.http_version); cgi_env_add(&env, CONST_STR_LEN("SERVER_PROTOCOL"), s, strlen(s)); ltostr(buf, #ifdef HAVE_IPV6 ntohs(srv_sock->addr.plain.sa_family == AF_INET6 ? srv_sock->addr.ipv6.sin6_port : srv_sock->addr.ipv4.sin_port) #else ntohs(srv_sock->addr.ipv4.sin_port) #endif ); cgi_env_add(&env, CONST_STR_LEN("SERVER_PORT"), buf, strlen(buf)); #ifdef HAVE_IPV6 s = inet_ntop(srv_sock->addr.plain.sa_family, srv_sock->addr.plain.sa_family == AF_INET6 ? (const void *) &(srv_sock->addr.ipv6.sin6_addr) : (const void *) &(srv_sock->addr.ipv4.sin_addr), b2, sizeof(b2)-1); #else s = inet_ntoa(srv_sock->addr.ipv4.sin_addr); #endif cgi_env_add(&env, CONST_STR_LEN("SERVER_ADDR"), s, strlen(s)); s = get_http_method_name(con->request.http_method); cgi_env_add(&env, CONST_STR_LEN("REQUEST_METHOD"), s, strlen(s)); if (!buffer_is_empty(con->request.pathinfo)) { cgi_env_add(&env, CONST_STR_LEN("PATH_INFO"), CONST_BUF_LEN(con->request.pathinfo)); } cgi_env_add(&env, CONST_STR_LEN("REDIRECT_STATUS"), CONST_STR_LEN("200")); if (!buffer_is_empty(con->uri.query)) { cgi_env_add(&env, CONST_STR_LEN("QUERY_STRING"), CONST_BUF_LEN(con->uri.query)); } else { /* set a empty QUERY_STRING */ cgi_env_add(&env, CONST_STR_LEN("QUERY_STRING"), CONST_STR_LEN("")); } if (!buffer_is_empty(con->request.orig_uri)) { cgi_env_add(&env, CONST_STR_LEN("REQUEST_URI"), CONST_BUF_LEN(con->request.orig_uri)); } #ifdef HAVE_IPV6 s = inet_ntop(con->dst_addr.plain.sa_family, con->dst_addr.plain.sa_family == AF_INET6 ? (const void *) &(con->dst_addr.ipv6.sin6_addr) : (const void *) &(con->dst_addr.ipv4.sin_addr), b2, sizeof(b2)-1); #else s = inet_ntoa(con->dst_addr.ipv4.sin_addr); #endif cgi_env_add(&env, CONST_STR_LEN("REMOTE_ADDR"), s, strlen(s)); ltostr(buf, #ifdef HAVE_IPV6 ntohs(con->dst_addr.plain.sa_family == AF_INET6 ? con->dst_addr.ipv6.sin6_port : con->dst_addr.ipv4.sin_port) #else ntohs(con->dst_addr.ipv4.sin_port) #endif ); cgi_env_add(&env, CONST_STR_LEN("REMOTE_PORT"), buf, strlen(buf)); if (!buffer_is_empty(con->authed_user)) { cgi_env_add(&env, CONST_STR_LEN("REMOTE_USER"), CONST_BUF_LEN(con->authed_user)); } #ifdef USE_OPENSSL if (srv_sock->is_ssl) { cgi_env_add(&env, CONST_STR_LEN("HTTPS"), CONST_STR_LEN("on")); } #endif /* request.content_length < SSIZE_MAX, see request.c */ ltostr(buf, con->request.content_length); cgi_env_add(&env, CONST_STR_LEN("CONTENT_LENGTH"), buf, strlen(buf)); cgi_env_add(&env, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(con->physical.path)); cgi_env_add(&env, CONST_STR_LEN("SCRIPT_NAME"), CONST_BUF_LEN(con->uri.path)); cgi_env_add(&env, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(con->physical.doc_root)); /* for valgrind */ if (NULL != (s = getenv("LD_PRELOAD"))) { cgi_env_add(&env, CONST_STR_LEN("LD_PRELOAD"), s, strlen(s)); } if (NULL != (s = getenv("LD_LIBRARY_PATH"))) { cgi_env_add(&env, CONST_STR_LEN("LD_LIBRARY_PATH"), s, strlen(s)); } #ifdef __CYGWIN__ /* CYGWIN needs SYSTEMROOT */ if (NULL != (s = getenv("SYSTEMROOT"))) { cgi_env_add(&env, CONST_STR_LEN("SYSTEMROOT"), s, strlen(s)); } #endif for (n = 0; n < con->request.headers->used; n++) { data_string *ds; ds = (data_string *)con->request.headers->data[n]; if (ds->value->used && ds->key->used) { size_t j; buffer_reset(p->tmp_buf); if (0 != strcasecmp(ds->key->ptr, "CONTENT-TYPE")) { buffer_copy_string(p->tmp_buf, "HTTP_"); p->tmp_buf->used--; /* strip \0 after HTTP_ */ } buffer_prepare_append(p->tmp_buf, ds->key->used + 2); for (j = 0; j < ds->key->used - 1; j++) { char cr = '_'; if (light_isalpha(ds->key->ptr[j])) { /* upper-case */ cr = ds->key->ptr[j] & ~32; } else if (light_isdigit(ds->key->ptr[j])) { /* copy */ cr = ds->key->ptr[j]; } p->tmp_buf->ptr[p->tmp_buf->used++] = cr; } p->tmp_buf->ptr[p->tmp_buf->used++] = '\0'; cgi_env_add(&env, CONST_BUF_LEN(p->tmp_buf), CONST_BUF_LEN(ds->value)); } } for (n = 0; n < con->environment->used; n++) { data_string *ds; ds = (data_string *)con->environment->data[n]; if (ds->value->used && ds->key->used) { size_t j; buffer_reset(p->tmp_buf); buffer_prepare_append(p->tmp_buf, ds->key->used + 2); for (j = 0; j < ds->key->used - 1; j++) { p->tmp_buf->ptr[p->tmp_buf->used++] = isalpha((unsigned char)ds->key->ptr[j]) ? toupper((unsigned char)ds->key->ptr[j]) : '_'; } p->tmp_buf->ptr[p->tmp_buf->used++] = '\0'; cgi_env_add(&env, CONST_BUF_LEN(p->tmp_buf), CONST_BUF_LEN(ds->value)); } } if (env.size == env.used) { env.size += 16; env.ptr = realloc(env.ptr, env.size * sizeof(*env.ptr)); } env.ptr[env.used] = NULL; /* set up args */ argc = 3; args = malloc(sizeof(*args) * argc); i = 0; if (cgi_handler && cgi_handler->used > 1) { args[i++] = cgi_handler->ptr; } args[i++] = con->physical.path->ptr; args[i++] = NULL; /* search for the last / */ if (NULL != (c = strrchr(con->physical.path->ptr, '/'))) { *c = '\0'; /* change to the physical directory */ if (-1 == chdir(con->physical.path->ptr)) { log_error_write(srv, __FILE__, __LINE__, "ssb", "chdir failed:", strerror(errno), con->physical.path); } *c = '/'; } /* we don't need the client socket */ for (i = 3; i < 256; i++) { close(i); } /* exec the cgi */ execve(args[0], args, env.ptr); /* */ SEGFAULT("execve(%s) failed: %s", args[0], strerror(errno)); break; } case -1: /* error */ ERROR("fork() failed: %s", strerror(errno)); break; default: { cgi_session *sess; /* father */ close(from_cgi_fds[1]); close(to_cgi_fds[0]); /* register PID and wait for them asyncronously */ con->mode = p->id; buffer_reset(con->physical.path); sess = cgi_session_init(); sess->remote_con = con; sess->pid = pid; assert(sess->sock); sess->sock->fd = from_cgi_fds[0]; sess->sock->type = IOSOCKET_TYPE_PIPE; sess->wb_sock->fd = to_cgi_fds[1]; sess->wb_sock->type = IOSOCKET_TYPE_PIPE; if (-1 == fdevent_fcntl_set(srv->ev, sess->sock)) { log_error_write(srv, __FILE__, __LINE__, "ss", "fcntl failed: ", strerror(errno)); cgi_session_free(sess); return -1; } con->plugin_ctx[p->id] = sess; fdevent_register(srv->ev, sess->sock, cgi_handle_fdevent, sess); fdevent_event_add(srv->ev, sess->sock, FDEVENT_IN); sess->state = CGI_STATE_READ_RESPONSE_HEADER; break; } } return 0; #else return -1; #endif } static int mod_cgi_patch_connection(server *srv, connection *con, plugin_data *p) { size_t i, j; plugin_config *s = p->config_storage[0]; PATCH_OPTION(cgi); PATCH_OPTION(execute_all); /* skip the first, the global context */ for (i = 1; i < srv->config_context->used; i++) { data_config *dc = (data_config *)srv->config_context->data[i]; s = p->config_storage[i]; /* condition didn't match */ if (!config_check_cond(srv, con, dc)) continue; /* merge config */ for (j = 0; j < dc->value->used; j++) { data_unset *du = dc->value->data[j]; if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_ASSIGN))) { PATCH_OPTION(cgi); } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_EXECUTE_ALL))) { PATCH_OPTION(execute_all); } } } return 0; } URIHANDLER_FUNC(mod_cgi_start_backend) { size_t k, s_len; plugin_data *p = p_d; buffer *fn = con->physical.path; if (fn->used == 0) return HANDLER_GO_ON; mod_cgi_patch_connection(srv, con, p); if (p->conf.cgi->used == 0 && p->conf.execute_all == 0) { return HANDLER_GO_ON; } if (con->conf.log_request_handling) { TRACE("-- checking request in mod_%s", "cgi"); } s_len = fn->used - 1; for (k = 0; k < p->conf.cgi->used; k++) { data_string *ds = (data_string *)p->conf.cgi->data[k]; size_t ct_len = ds->key->used - 1; if (ds->key->used == 0) continue; if (s_len < ct_len) continue; if (0 == strncmp(fn->ptr + s_len - ct_len, ds->key->ptr, ct_len)) { if (cgi_create_env(srv, con, p, ds->value)) { con->http_status = 500; buffer_reset(con->physical.path); return HANDLER_FINISHED; } /* one handler is enough for the request */ break; } } if (p->conf.execute_all) { if (cgi_create_env(srv, con, p, NULL)) { con->http_status = 500; buffer_reset(con->physical.path); return HANDLER_FINISHED; } } return HANDLER_GO_ON; } TRIGGER_FUNC(cgi_trigger) { plugin_data *p = p_d; size_t ndx; /* the trigger handle only cares about lonely PID which we have to wait for */ #ifndef _WIN32 for (ndx = 0; ndx < p->cgi_pid.used; ndx++) { int status; switch(waitpid(p->cgi_pid.ptr[ndx], &status, WNOHANG)) { case 0: /* not finished yet */ #if 0 log_error_write(srv, __FILE__, __LINE__, "sd", "(debug) child isn't done yet, pid:", p->cgi_pid.ptr[ndx]); #endif break; case -1: log_error_write(srv, __FILE__, __LINE__, "ss", "waitpid failed: ", strerror(errno)); return HANDLER_ERROR; default: if (WIFEXITED(status)) { #if 0 log_error_write(srv, __FILE__, __LINE__, "sd", "(debug) cgi exited fine, pid:", p->cgi_pid.ptr[ndx]); #endif } else { log_error_write(srv, __FILE__, __LINE__, "s", "cgi died ?"); } cgi_pid_del(srv, p, p->cgi_pid.ptr[ndx]); /* del modified the buffer structure * and copies the last entry to the current one * -> recheck the current index */ ndx--; } } #endif return HANDLER_GO_ON; } SUBREQUEST_FUNC(mod_cgi_read_response_content) { int status; plugin_data *p = p_d; cgi_session *sess = con->plugin_ctx[p->id]; if (con->mode != p->id) return HANDLER_GO_ON; if (NULL == sess) return HANDLER_GO_ON; switch (cgi_demux_response(srv, con, p)) { case 0: break; case 1: cgi_connection_close(srv, con, p); /* if we get a IN|HUP and have read everything don't exec the close twice */ return HANDLER_FINISHED; case -1: cgi_connection_close(srv, con, p); if (0 == con->http_status) con->http_status = 500; con->mode = DIRECT; return HANDLER_FINISHED; } #if 0 log_error_write(srv, __FILE__, __LINE__, "sdd", "subrequest, pid =", sess, sess->pid); #endif if (sess->pid == 0) return HANDLER_FINISHED; #ifndef _WIN32 switch(waitpid(sess->pid, &status, WNOHANG)) { case 0: /* we only have for events here if we don't have the header yet, * otherwise the event-handler will send us the incoming data */ if (!con->file_started) return HANDLER_WAIT_FOR_EVENT; if (con->send->is_closed) return HANDLER_FINISHED; return HANDLER_GO_ON; case -1: if (errno == EINTR) return HANDLER_WAIT_FOR_EVENT; if (errno == ECHILD && con->file_started == 0) { /* * second round but still not response */ return HANDLER_WAIT_FOR_EVENT; } log_error_write(srv, __FILE__, __LINE__, "ss", "waitpid failed: ", strerror(errno)); con->mode = DIRECT; con->http_status = 500; sess->pid = 0; fdevent_event_del(srv->ev, sess->sock); fdevent_unregister(srv->ev, sess->sock); cgi_session_free(sess); sess = NULL; con->plugin_ctx[p->id] = NULL; return HANDLER_FINISHED; default: con->send->is_closed = 1; if (WIFEXITED(status)) { /* nothing */ } else { log_error_write(srv, __FILE__, __LINE__, "s", "cgi died ?"); con->mode = DIRECT; con->http_status = 500; } sess->pid = 0; fdevent_event_del(srv->ev, sess->sock); fdevent_unregister(srv->ev, sess->sock); cgi_session_free(sess); sess = NULL; con->plugin_ctx[p->id] = NULL; return HANDLER_FINISHED; } #else return HANDLER_ERROR; #endif } URIHANDLER_FUNC(mod_cgi_send_request_content) { plugin_data *p = p_d; cgi_session *sess = con->plugin_ctx[p->id]; if (p->id != con->mode) return HANDLER_GO_ON; if (con->request.content_length > 0 && con->recv->bytes_in > con->recv->bytes_out) { /* write request content. */ switch (network_write_chunkqueue_write(srv, con, sess->wb_sock, con->recv)) { case NETWORK_STATUS_SUCCESS: /** fall through, still have data to write. */ case NETWORK_STATUS_WAIT_FOR_EVENT: /** fall through */ case NETWORK_STATUS_WAIT_FOR_AIO_EVENT: break; case NETWORK_STATUS_CONNECTION_CLOSE: /* the script might have written a response already. */ break; default: TRACE("%s", "(error)"); return HANDLER_ERROR; } chunkqueue_remove_finished_chunks(con->recv); } /* we have to close the pipe to finish the request. */ if ((con->recv->is_closed && con->recv->bytes_in == con->recv->bytes_out) || con->request.content_length <= 0) { close(sess->wb_sock->fd); sess->wb_sock->fd = -1; } else { /* there is more data to write. */ return HANDLER_GO_ON; } return mod_cgi_read_response_content(srv, con, p_d); } int mod_cgi_plugin_init(plugin *p) { p->version = LIGHTTPD_VERSION_ID; p->name = buffer_init_string("cgi"); p->connection_reset = cgi_connection_close_callback; p->handle_start_backend = mod_cgi_start_backend; p->handle_send_request_content = mod_cgi_send_request_content; p->handle_read_response_content = mod_cgi_read_response_content; p->handle_trigger = cgi_trigger; p->init = mod_cgi_init; p->cleanup = mod_cgi_free; p->set_defaults = mod_cgi_set_defaults; p->data = NULL; return 0; } #include <sys/types.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <ctype.h> #include <assert.h> #include <stdio.h> #include <fcntl.h> #include "server.h" #include "keyvalue.h" #include "log.h" #include "connections.h" #include "joblist.h" #include "fdevent.h" #include "plugin.h" #include "http_resp.h" #include "sys-files.h" #include "sys-mmap.h" #include "sys-socket.h" #include "sys-strings.h" #include "sys-process.h" #include "network_backends.h" #ifdef HAVE_SYS_FILIO_H # include <sys/filio.h> #endif enum {EOL_UNSET, EOL_N, EOL_RN}; typedef struct { char **ptr; size_t size; size_t used; } char_array; #define pid_t int typedef struct { pid_t *ptr; size_t used; size_t size; } buffer_pid_t; typedef struct { array *cgi; unsigned short execute_all; } plugin_config; typedef struct { PLUGIN_DATA; buffer_pid_t cgi_pid; buffer *tmp_buf; http_resp *resp; plugin_config **config_storage; plugin_config conf; } plugin_data; typedef enum { CGI_STATE_UNSET, CGI_STATE_CONNECTING, CGI_STATE_READ_RESPONSE_HEADER, CGI_STATE_READ_RESPONSE_CONTENT } cgi_state_t; typedef struct { pid_t pid; iosocket *sock; iosocket *wb_sock; chunkqueue *rb; chunkqueue *wb; cgi_state_t state; connection *remote_con; /* dumb pointer */ } cgi_session; static cgi_session * cgi_session_init() { cgi_session *sess = calloc(1, sizeof(*sess)); assert(sess); sess->sock = iosocket_init(); sess->wb_sock = iosocket_init(); sess->wb = chunkqueue_init(); sess->rb = chunkqueue_init(); return sess; } static void cgi_session_free(cgi_session *sess) { if (!sess) return; iosocket_free(sess->sock); iosocket_free(sess->wb_sock); chunkqueue_free(sess->wb); chunkqueue_free(sess->rb); free(sess); } INIT_FUNC(mod_cgi_init) { plugin_data *p; UNUSED(srv); p = calloc(1, sizeof(*p)); assert(p); p->tmp_buf = buffer_init(); p->resp = http_response_init(); return p; } FREE_FUNC(mod_cgi_free) { plugin_data *p = p_d; buffer_pid_t *r = &(p->cgi_pid); UNUSED(srv); if (p->config_storage) { size_t i; for (i = 0; i < srv->config_context->used; i++) { plugin_config *s = p->config_storage[i]; array_free(s->cgi); free(s); } free(p->config_storage); } if (r->ptr) free(r->ptr); buffer_free(p->tmp_buf); http_response_free(p->resp); free(p); return HANDLER_GO_ON; } #define PLUGIN_NAME "cgi" #define CONFIG_ASSIGN PLUGIN_NAME ".assign" #define CONFIG_EXECUTE_ALL PLUGIN_NAME ".execute-all" SETDEFAULTS_FUNC(mod_cgi_set_defaults) { plugin_data *p = p_d; size_t i = 0; config_values_t cv[] = { { CONFIG_ASSIGN, NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 0 */ { CONFIG_EXECUTE_ALL, NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 1 */ { NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET} }; if (!p) return HANDLER_ERROR; p->config_storage = calloc(1, srv->config_context->used * sizeof(specific_config *)); for (i = 0; i < srv->config_context->used; i++) { plugin_config *s; s = calloc(1, sizeof(plugin_config)); assert(s); s->cgi = array_init(); s->execute_all = 0; cv[0].destination = s->cgi; cv[1].destination = &(s->execute_all); p->config_storage[i] = s; if (0 != config_insert_values_global(srv, ((data_config *)srv->config_context->data[i])->value, cv)) { return HANDLER_ERROR; } } return HANDLER_GO_ON; } static int cgi_pid_add(server *srv, plugin_data *p, pid_t pid) { int m = -1; size_t i; buffer_pid_t *r = &(p->cgi_pid); UNUSED(srv); for (i = 0; i < r->used; i++) { if (r->ptr[i] > m) m = r->ptr[i]; } if (r->size == 0) { r->size = 16; r->ptr = malloc(sizeof(*r->ptr) * r->size); } else if (r->used == r->size) { r->size += 16; r->ptr = realloc(r->ptr, sizeof(*r->ptr) * r->size); } r->ptr[r->used++] = pid; return m; } static int cgi_pid_del(server *srv, plugin_data *p, pid_t pid) { size_t i; buffer_pid_t *r = &(p->cgi_pid); UNUSED(srv); for (i = 0; i < r->used; i++) { if (r->ptr[i] == pid) break; } if (i != r->used) { /* found */ if (i != r->used - 1) { r->ptr[i] = r->ptr[r->used - 1]; } r->used--; } return 0; } /** * Copy decoded response content to client connection. */ static int cgi_copy_response(server *srv, connection *con, cgi_session *sess) { chunk *c; int we_have = 0; UNUSED(srv); chunkqueue_remove_finished_chunks(sess->rb); /* copy the content to the next cq */ for (c = sess->rb->first; c; c = c->next) { if (c->mem->used == 0) continue; we_have = c->mem->used - c->offset - 1; sess->rb->bytes_out += we_have; con->send->bytes_in += we_have; if (c->offset == 0) { /* steal the buffer from the previous queue */ chunkqueue_steal_chunk(con->send, c); } else { chunkqueue_append_mem(con->send, c->mem->ptr + c->offset, c->mem->used - c->offset); c->offset = c->mem->used - 1; /* mark the incoming side as read */ } } chunkqueue_remove_finished_chunks(sess->rb); if(sess->rb->is_closed) { con->send->is_closed = 1; } return 0; } static int cgi_demux_response(server *srv, connection *con, plugin_data *p) { cgi_session *sess = con->plugin_ctx[p->id]; switch(srv->network_backend_read(srv, con, sess->sock, sess->rb)) { case NETWORK_STATUS_CONNECTION_CLOSE: fdevent_event_del(srv->ev, sess->sock); /* connection closed. close the read chunkqueue. */ sess->rb->is_closed = 1; case NETWORK_STATUS_SUCCESS: /* we got content */ break; case NETWORK_STATUS_WAIT_FOR_EVENT: return 0; default: /* oops */ ERROR("%s", "oops, read-pipe-read failed and I don't know why"); return -1; } /* looks like we got some content * * split off the header from the incoming stream */ if (con->file_started == 0) { size_t i; int have_content_length = 0; http_response_reset(p->resp); /* the response header is not fully received yet, * * extract the http-response header from the rb-cq */ switch (http_response_parse_cq(sess->rb, p->resp)) { case PARSE_UNSET: case PARSE_ERROR: /* parsing failed */ TRACE("%s", "response parser failed"); con->http_status = 502; /* Bad Gateway */ return -1; case PARSE_NEED_MORE: return 0; case PARSE_SUCCESS: con->http_status = p->resp->status; chunkqueue_remove_finished_chunks(sess->rb); /* copy the http-headers */ for (i = 0; i < p->resp->headers->used; i++) { const char *ign[] = { "Status", "Connection", NULL }; size_t j; data_string *ds; data_string *header = (data_string *)p->resp->headers->data[i]; /* some headers are ignored by default */ for (j = 0; ign[j]; j++) { if (0 == strcasecmp(ign[j], header->key->ptr)) break; } if (ign[j]) continue; if (0 == buffer_caseless_compare(CONST_BUF_LEN(header->key), CONST_STR_LEN("Location"))) { /* CGI/1.1 rev 03 - 7.2.1.2 */ if (con->http_status == 0) con->http_status = 302; } else if (0 == buffer_caseless_compare(CONST_BUF_LEN(header->key), CONST_STR_LEN("Content-Length"))) { have_content_length = 1; } if (NULL == (ds = (data_string *)array_get_unused_element(con->response.headers, TYPE_STRING))) { ds = data_response_init(); } buffer_copy_string_buffer(ds->key, header->key); buffer_copy_string_buffer(ds->value, header->value); array_insert_unique(con->response.headers, (data_unset *)ds); } con->file_started = 1; /* if Status: ... is not set, 200 is our default status-code */ if (con->http_status == 0) con->http_status = 200; sess->state = CGI_STATE_READ_RESPONSE_CONTENT; if (con->request.http_version == HTTP_VERSION_1_1 && !have_content_length) { con->response.transfer_encoding = HTTP_TRANSFER_ENCODING_CHUNKED; } break; } } /* FIXME: pass the response-header to the other plugins to * setup the filter-queue * * - use next-queue instead of con->write_queue */ /* copy the resopnse content */ cgi_copy_response(srv, con, sess); joblist_append(srv, con); return 0; } static handler_t cgi_connection_close(server *srv, connection *con, plugin_data *p) { cgi_session *sess = con->plugin_ctx[p->id]; int status; pid_t pid; if (NULL == sess) return HANDLER_GO_ON; if (con->mode != p->id) return HANDLER_GO_ON; #ifndef _WIN32 /* the connection to the browser went away, but we still have a connection * to the CGI script * * close cgi-connection */ if (sess->sock->fd != -1) { /* close connection to the cgi-script */ fdevent_event_del(srv->ev, sess->sock); fdevent_unregister(srv->ev, sess->sock); } if (sess->wb_sock->fd != -1) { close(sess->wb_sock->fd); sess->wb_sock->fd = -1; } pid = sess->pid; con->plugin_ctx[p->id] = NULL; /* is this a good idea ? */ cgi_session_free(sess); sess = NULL; /* if waitpid hasn't been called by response.c yet, do it here */ if (pid) { /* check if the CGI-script is already gone */ #ifndef _WIN32 switch(waitpid(pid, &status, WNOHANG)) { case 0: /* not finished yet */ #if 0 log_error_write(srv, __FILE__, __LINE__, "sd", "(debug) child isn't done yet, pid:", pid); #endif break; case -1: /* */ if (errno == EINTR) break; /* * errno == ECHILD happens if _subrequest catches the process-status before * we have read the response of the cgi process * * -> catch status * -> WAIT_FOR_EVENT * -> read response * -> we get here with waitpid == ECHILD * */ if (errno == ECHILD) return HANDLER_GO_ON; log_error_write(srv, __FILE__, __LINE__, "ss", "waitpid failed: ", strerror(errno)); return HANDLER_ERROR; default: /* Send an error if we haven't sent any data yet */ if (0 == con->file_started) { if (con->http_status == 0) con->http_status = 500; con->mode = DIRECT; } if (WIFEXITED(status)) { #if 0 log_error_write(srv, __FILE__, __LINE__, "sd", "(debug) cgi exited fine, pid:", pid); #endif pid = 0; return HANDLER_GO_ON; } else { log_error_write(srv, __FILE__, __LINE__, "sd", "cgi died, pid:", pid); pid = 0; return HANDLER_GO_ON; } } kill(pid, SIGTERM); #endif /* cgi-script is still alive, queue the PID for removal */ cgi_pid_add(srv, p, pid); } #endif return HANDLER_GO_ON; } static handler_t cgi_connection_close_callback(server *srv, connection *con, void *p_d) { plugin_data *p = p_d; return cgi_connection_close(srv, con, p); } static handler_t cgi_handle_fdevent(void *s, void *ctx, int revents) { server *srv = (server *)s; cgi_session *sess = ctx; connection *con = sess->remote_con; if (revents & FDEVENT_IN) { switch (sess->state) { case CGI_STATE_READ_RESPONSE_HEADER: /* parse the header and set file-started, the demuxer will care about it */ joblist_append(srv, con); break; case CGI_STATE_READ_RESPONSE_CONTENT: /* just forward the content to the out-going queue */ chunkqueue_remove_finished_chunks(sess->rb); switch (srv->network_backend_read(srv, con, sess->sock, sess->rb)) { case NETWORK_STATUS_CONNECTION_CLOSE: fdevent_event_del(srv->ev, sess->sock); /* connection closed. close the read chunkqueue. */ sess->rb->is_closed = 1; case NETWORK_STATUS_SUCCESS: /* read even more, do we have all the content */ /* how much do we want to read ? */ /* copy the resopnse content */ cgi_copy_response(srv, con, sess); break; default: ERROR("%s", "oops, we failed to read"); break; } joblist_append(srv, con); break; default: TRACE("unexpected state for a FDEVENT_IN: %d", sess->state); break; } } if (revents & FDEVENT_OUT) { /* nothing to do */ } /* perhaps this issue is already handled */ if (revents & FDEVENT_HUP) { con->send->is_closed = 1; fdevent_event_del(srv->ev, sess->sock); joblist_append(srv, con); } else if (revents & FDEVENT_ERR) { con->send->is_closed = 1; /* kill all connections to the cgi process */ fdevent_event_del(srv->ev, sess->sock); } return HANDLER_FINISHED; } static int cgi_env_add(char_array *env, const char *key, size_t key_len, const char *val, size_t val_len) { char *dst; if (!key || !val) return -1; dst = malloc(key_len + val_len + 3); memcpy(dst, key, key_len); dst[key_len] = '='; /* add the \0 from the value */ memcpy(dst + key_len + 1, val, val_len + 1); if (env->size == 0) { env->size = 16; env->ptr = malloc(env->size * sizeof(*env->ptr)); } else if (env->size == env->used) { env->size += 16; env->ptr = realloc(env->ptr, env->size * sizeof(*env->ptr)); } env->ptr[env->used++] = dst; return 0; } static int cgi_create_env(server *srv, connection *con, plugin_data *p, buffer *cgi_handler) { pid_t pid; #ifdef HAVE_IPV6 char b2[INET6_ADDRSTRLEN + 1]; #endif int to_cgi_fds[2]; int from_cgi_fds[2]; struct stat st; #ifndef _WIN32 if (cgi_handler && cgi_handler->used > 1) { /* stat the exec file */ if (-1 == (stat(cgi_handler->ptr, &st))) { log_error_write(srv, __FILE__, __LINE__, "sbss", "stat for cgi-handler", cgi_handler, "failed:", strerror(errno)); return -1; } } if (pipe(to_cgi_fds)) { log_error_write(srv, __FILE__, __LINE__, "ss", "pipe failed:", strerror(errno)); return -1; } if (pipe(from_cgi_fds)) { log_error_write(srv, __FILE__, __LINE__, "ss", "pipe failed:", strerror(errno)); return -1; } /* fork, execve */ switch (pid = fork()) { case 0: { /* child */ char **args; int argc; int i = 0; char buf[32]; size_t n; char_array env; char *c; const char *s; server_socket *srv_sock = con->srv_socket; /* move stdout to from_cgi_fd[1] */ close(STDOUT_FILENO); dup2(from_cgi_fds[1], STDOUT_FILENO); close(from_cgi_fds[1]); /* not needed */ close(from_cgi_fds[0]); /* move the stdin to to_cgi_fd[0] */ close(STDIN_FILENO); dup2(to_cgi_fds[0], STDIN_FILENO); close(to_cgi_fds[0]); /* not needed */ close(to_cgi_fds[1]); /** * FIXME: add a event-handler for STDERR_FILENO and let it LOG() */ close(STDERR_FILENO); /* create environment */ env.ptr = NULL; env.size = 0; env.used = 0; cgi_env_add(&env, CONST_STR_LEN("SERVER_SOFTWARE"), CONST_STR_LEN(PACKAGE_NAME"/"PACKAGE_VERSION)); if (!buffer_is_empty(con->server_name)) { cgi_env_add(&env, CONST_STR_LEN("SERVER_NAME"), CONST_BUF_LEN(con->server_name)); } else { #ifdef HAVE_IPV6 s = inet_ntop(srv_sock->addr.plain.sa_family, srv_sock->addr.plain.sa_family == AF_INET6 ? (const void *) &(srv_sock->addr.ipv6.sin6_addr) : (const void *) &(srv_sock->addr.ipv4.sin_addr), b2, sizeof(b2)-1); #else s = inet_ntoa(srv_sock->addr.ipv4.sin_addr); #endif cgi_env_add(&env, CONST_STR_LEN("SERVER_NAME"), s, strlen(s)); } cgi_env_add(&env, CONST_STR_LEN("GATEWAY_INTERFACE"), CONST_STR_LEN("CGI/1.1")); s = get_http_version_name(con->request.http_version); cgi_env_add(&env, CONST_STR_LEN("SERVER_PROTOCOL"), s, strlen(s)); ltostr(buf, #ifdef HAVE_IPV6 ntohs(srv_sock->addr.plain.sa_family == AF_INET6 ? srv_sock->addr.ipv6.sin6_port : srv_sock->addr.ipv4.sin_port) #else ntohs(srv_sock->addr.ipv4.sin_port) #endif ); cgi_env_add(&env, CONST_STR_LEN("SERVER_PORT"), buf, strlen(buf)); #ifdef HAVE_IPV6 s = inet_ntop(srv_sock->addr.plain.sa_family, srv_sock->addr.plain.sa_family == AF_INET6 ? (const void *) &(srv_sock->addr.ipv6.sin6_addr) : (const void *) &(srv_sock->addr.ipv4.sin_addr), b2, sizeof(b2)-1); #else s = inet_ntoa(srv_sock->addr.ipv4.sin_addr); #endif cgi_env_add(&env, CONST_STR_LEN("SERVER_ADDR"), s, strlen(s)); s = get_http_method_name(con->request.http_method); cgi_env_add(&env, CONST_STR_LEN("REQUEST_METHOD"), s, strlen(s)); if (!buffer_is_empty(con->request.pathinfo)) { cgi_env_add(&env, CONST_STR_LEN("PATH_INFO"), CONST_BUF_LEN(con->request.pathinfo)); } cgi_env_add(&env, CONST_STR_LEN("REDIRECT_STATUS"), CONST_STR_LEN("200")); if (!buffer_is_empty(con->uri.query)) { cgi_env_add(&env, CONST_STR_LEN("QUERY_STRING"), CONST_BUF_LEN(con->uri.query)); } else { /* set a empty QUERY_STRING */ cgi_env_add(&env, CONST_STR_LEN("QUERY_STRING"), CONST_STR_LEN("")); } if (!buffer_is_empty(con->request.orig_uri)) { cgi_env_add(&env, CONST_STR_LEN("REQUEST_URI"), CONST_BUF_LEN(con->request.orig_uri)); } #ifdef HAVE_IPV6 s = inet_ntop(con->dst_addr.plain.sa_family, con->dst_addr.plain.sa_family == AF_INET6 ? (const void *) &(con->dst_addr.ipv6.sin6_addr) : (const void *) &(con->dst_addr.ipv4.sin_addr), b2, sizeof(b2)-1); #else s = inet_ntoa(con->dst_addr.ipv4.sin_addr); #endif cgi_env_add(&env, CONST_STR_LEN("REMOTE_ADDR"), s, strlen(s)); ltostr(buf, #ifdef HAVE_IPV6 ntohs(con->dst_addr.plain.sa_family == AF_INET6 ? con->dst_addr.ipv6.sin6_port : con->dst_addr.ipv4.sin_port) #else ntohs(con->dst_addr.ipv4.sin_port) #endif ); cgi_env_add(&env, CONST_STR_LEN("REMOTE_PORT"), buf, strlen(buf)); if (!buffer_is_empty(con->authed_user)) { cgi_env_add(&env, CONST_STR_LEN("REMOTE_USER"), CONST_BUF_LEN(con->authed_user)); } #ifdef USE_OPENSSL if (srv_sock->is_ssl) { cgi_env_add(&env, CONST_STR_LEN("HTTPS"), CONST_STR_LEN("on")); } #endif /* request.content_length < SSIZE_MAX, see request.c */ if (con->request.content_length > 0) { ltostr(buf, con->request.content_length); cgi_env_add(&env, CONST_STR_LEN("CONTENT_LENGTH"), buf, strlen(buf)); } cgi_env_add(&env, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(con->physical.path)); cgi_env_add(&env, CONST_STR_LEN("SCRIPT_NAME"), CONST_BUF_LEN(con->uri.path)); cgi_env_add(&env, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(con->physical.doc_root)); /* for valgrind */ if (NULL != (s = getenv("LD_PRELOAD"))) { cgi_env_add(&env, CONST_STR_LEN("LD_PRELOAD"), s, strlen(s)); } if (NULL != (s = getenv("LD_LIBRARY_PATH"))) { cgi_env_add(&env, CONST_STR_LEN("LD_LIBRARY_PATH"), s, strlen(s)); } #ifdef __CYGWIN__ /* CYGWIN needs SYSTEMROOT */ if (NULL != (s = getenv("SYSTEMROOT"))) { cgi_env_add(&env, CONST_STR_LEN("SYSTEMROOT"), s, strlen(s)); } #endif for (n = 0; n < con->request.headers->used; n++) { data_string *ds; ds = (data_string *)con->request.headers->data[n]; if (ds->value->used && ds->key->used) { size_t j; buffer_reset(p->tmp_buf); if (0 != strcasecmp(ds->key->ptr, "CONTENT-TYPE")) { buffer_copy_string(p->tmp_buf, "HTTP_"); p->tmp_buf->used--; /* strip \0 after HTTP_ */ } buffer_prepare_append(p->tmp_buf, ds->key->used + 2); for (j = 0; j < ds->key->used - 1; j++) { char cr = '_'; if (light_isalpha(ds->key->ptr[j])) { /* upper-case */ cr = ds->key->ptr[j] & ~32; } else if (light_isdigit(ds->key->ptr[j])) { /* copy */ cr = ds->key->ptr[j]; } p->tmp_buf->ptr[p->tmp_buf->used++] = cr; } p->tmp_buf->ptr[p->tmp_buf->used++] = '\0'; cgi_env_add(&env, CONST_BUF_LEN(p->tmp_buf), CONST_BUF_LEN(ds->value)); } } for (n = 0; n < con->environment->used; n++) { data_string *ds; ds = (data_string *)con->environment->data[n]; if (ds->value->used && ds->key->used) { size_t j; buffer_reset(p->tmp_buf); buffer_prepare_append(p->tmp_buf, ds->key->used + 2); for (j = 0; j < ds->key->used - 1; j++) { p->tmp_buf->ptr[p->tmp_buf->used++] = isalpha((unsigned char)ds->key->ptr[j]) ? toupper((unsigned char)ds->key->ptr[j]) : '_'; } p->tmp_buf->ptr[p->tmp_buf->used++] = '\0'; cgi_env_add(&env, CONST_BUF_LEN(p->tmp_buf), CONST_BUF_LEN(ds->value)); } } if (env.size == env.used) { env.size += 16; env.ptr = realloc(env.ptr, env.size * sizeof(*env.ptr)); } env.ptr[env.used] = NULL; /* set up args */ argc = 3; args = malloc(sizeof(*args) * argc); i = 0; if (cgi_handler && cgi_handler->used > 1) { args[i++] = cgi_handler->ptr; } args[i++] = con->physical.path->ptr; args[i++] = NULL; /* search for the last / */ if (NULL != (c = strrchr(con->physical.path->ptr, '/'))) { *c = '\0'; /* change to the physical directory */ if (-1 == chdir(con->physical.path->ptr)) { log_error_write(srv, __FILE__, __LINE__, "ssb", "chdir failed:", strerror(errno), con->physical.path); } *c = '/'; } /* we don't need the client socket */ for (i = 3; i < 256; i++) { close(i); } /* exec the cgi */ execve(args[0], args, env.ptr); /* */ SEGFAULT("execve(%s) failed: %s", args[0], strerror(errno)); break; } case -1: /* error */ ERROR("fork() failed: %s", strerror(errno)); break; default: { cgi_session *sess; /* father */ close(from_cgi_fds[1]); close(to_cgi_fds[0]); /* register PID and wait for them asyncronously */ con->mode = p->id; buffer_reset(con->physical.path); sess = cgi_session_init(); sess->remote_con = con; sess->pid = pid; assert(sess->sock); sess->sock->fd = from_cgi_fds[0]; sess->sock->type = IOSOCKET_TYPE_PIPE; sess->wb_sock->fd = to_cgi_fds[1]; sess->wb_sock->type = IOSOCKET_TYPE_PIPE; if (-1 == fdevent_fcntl_set(srv->ev, sess->sock)) { log_error_write(srv, __FILE__, __LINE__, "ss", "fcntl failed: ", strerror(errno)); cgi_session_free(sess); return -1; } con->plugin_ctx[p->id] = sess; fdevent_register(srv->ev, sess->sock, cgi_handle_fdevent, sess); fdevent_event_add(srv->ev, sess->sock, FDEVENT_IN); sess->state = CGI_STATE_READ_RESPONSE_HEADER; break; } } return 0; #else return -1; #endif } static int mod_cgi_patch_connection(server *srv, connection *con, plugin_data *p) { size_t i, j; plugin_config *s = p->config_storage[0]; PATCH_OPTION(cgi); PATCH_OPTION(execute_all); /* skip the first, the global context */ for (i = 1; i < srv->config_context->used; i++) { data_config *dc = (data_config *)srv->config_context->data[i]; s = p->config_storage[i]; /* condition didn't match */ if (!config_check_cond(srv, con, dc)) continue; /* merge config */ for (j = 0; j < dc->value->used; j++) { data_unset *du = dc->value->data[j]; if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_ASSIGN))) { PATCH_OPTION(cgi); } else if (buffer_is_equal_string(du->key, CONST_STR_LEN(CONFIG_EXECUTE_ALL))) { PATCH_OPTION(execute_all); } } } return 0; } URIHANDLER_FUNC(mod_cgi_start_backend) { size_t k, s_len; plugin_data *p = p_d; buffer *fn = con->physical.path; if (fn->used == 0) return HANDLER_GO_ON; mod_cgi_patch_connection(srv, con, p); if (p->conf.cgi->used == 0 && p->conf.execute_all == 0) { return HANDLER_GO_ON; } if (con->conf.log_request_handling) { TRACE("-- checking request in mod_%s", "cgi"); } s_len = fn->used - 1; for (k = 0; k < p->conf.cgi->used; k++) { data_string *ds = (data_string *)p->conf.cgi->data[k]; size_t ct_len = ds->key->used - 1; if (ds->key->used == 0) continue; if (s_len < ct_len) continue; if (0 == strncmp(fn->ptr + s_len - ct_len, ds->key->ptr, ct_len)) { if (cgi_create_env(srv, con, p, ds->value)) { con->http_status = 500; buffer_reset(con->physical.path); return HANDLER_FINISHED; } /* one handler is enough for the request */ break; } } if (p->conf.execute_all) { if (cgi_create_env(srv, con, p, NULL)) { con->http_status = 500; buffer_reset(con->physical.path); return HANDLER_FINISHED; } } return HANDLER_GO_ON; } TRIGGER_FUNC(cgi_trigger) { plugin_data *p = p_d; size_t ndx; /* the trigger handle only cares about lonely PID which we have to wait for */ #ifndef _WIN32 for (ndx = 0; ndx < p->cgi_pid.used; ndx++) { int status; switch(waitpid(p->cgi_pid.ptr[ndx], &status, WNOHANG)) { case 0: /* not finished yet */ #if 0 log_error_write(srv, __FILE__, __LINE__, "sd", "(debug) child isn't done yet, pid:", p->cgi_pid.ptr[ndx]); #endif break; case -1: log_error_write(srv, __FILE__, __LINE__, "ss", "waitpid failed: ", strerror(errno)); return HANDLER_ERROR; default: if (WIFEXITED(status)) { #if 0 log_error_write(srv, __FILE__, __LINE__, "sd", "(debug) cgi exited fine, pid:", p->cgi_pid.ptr[ndx]); #endif } else { log_error_write(srv, __FILE__, __LINE__, "s", "cgi died ?"); } cgi_pid_del(srv, p, p->cgi_pid.ptr[ndx]); /* del modified the buffer structure * and copies the last entry to the current one * -> recheck the current index */ ndx--; } } #endif return HANDLER_GO_ON; } SUBREQUEST_FUNC(mod_cgi_read_response_content) { int status; plugin_data *p = p_d; cgi_session *sess = con->plugin_ctx[p->id]; if (con->mode != p->id) return HANDLER_GO_ON; if (NULL == sess) return HANDLER_GO_ON; switch (cgi_demux_response(srv, con, p)) { case 0: break; case 1: cgi_connection_close(srv, con, p); /* if we get a IN|HUP and have read everything don't exec the close twice */ return HANDLER_FINISHED; case -1: cgi_connection_close(srv, con, p); if (0 == con->http_status) con->http_status = 500; con->mode = DIRECT; return HANDLER_FINISHED; } #if 0 log_error_write(srv, __FILE__, __LINE__, "sdd", "subrequest, pid =", sess, sess->pid); #endif if (sess->pid == 0) return HANDLER_FINISHED; #ifndef _WIN32 switch(waitpid(sess->pid, &status, WNOHANG)) { case 0: /* we only have for events here if we don't have the header yet, * otherwise the event-handler will send us the incoming data */ if (!con->file_started) return HANDLER_WAIT_FOR_EVENT; if (con->send->is_closed) return HANDLER_FINISHED; return HANDLER_GO_ON; case -1: if (errno == EINTR) return HANDLER_WAIT_FOR_EVENT; if (errno == ECHILD && con->file_started == 0) { /* * second round but still not response */ return HANDLER_WAIT_FOR_EVENT; } log_error_write(srv, __FILE__, __LINE__, "ss", "waitpid failed: ", strerror(errno)); con->mode = DIRECT; con->http_status = 500; sess->pid = 0; fdevent_event_del(srv->ev, sess->sock); fdevent_unregister(srv->ev, sess->sock); cgi_session_free(sess); sess = NULL; con->plugin_ctx[p->id] = NULL; return HANDLER_FINISHED; default: con->send->is_closed = 1; if (WIFEXITED(status)) { /* nothing */ } else { log_error_write(srv, __FILE__, __LINE__, "s", "cgi died ?"); con->mode = DIRECT; con->http_status = 500; } sess->pid = 0; fdevent_event_del(srv->ev, sess->sock); fdevent_unregister(srv->ev, sess->sock); cgi_session_free(sess); sess = NULL; con->plugin_ctx[p->id] = NULL; return HANDLER_FINISHED; } #else return HANDLER_ERROR; #endif } URIHANDLER_FUNC(mod_cgi_send_request_content) { plugin_data *p = p_d; cgi_session *sess = con->plugin_ctx[p->id]; if (p->id != con->mode) return HANDLER_GO_ON; if (con->request.content_length > 0 && con->recv->bytes_in > con->recv->bytes_out) { /* write request content. */ switch (network_write_chunkqueue_write(srv, con, sess->wb_sock, con->recv)) { case NETWORK_STATUS_SUCCESS: /** fall through, still have data to write. */ case NETWORK_STATUS_WAIT_FOR_EVENT: /** fall through */ case NETWORK_STATUS_WAIT_FOR_AIO_EVENT: break; case NETWORK_STATUS_CONNECTION_CLOSE: /* the script might have written a response already. */ break; default: TRACE("%s", "(error)"); return HANDLER_ERROR; } chunkqueue_remove_finished_chunks(con->recv); } /* we have to close the pipe to finish the request. */ if ((con->recv->is_closed && con->recv->bytes_in == con->recv->bytes_out) || con->request.content_length <= 0) { close(sess->wb_sock->fd); sess->wb_sock->fd = -1; } else { /* there is more data to write. */ return HANDLER_GO_ON; } return mod_cgi_read_response_content(srv, con, p_d); } int mod_cgi_plugin_init(plugin *p) { p->version = LIGHTTPD_VERSION_ID; p->name = buffer_init_string("cgi"); p->connection_reset = cgi_connection_close_callback; p->handle_start_backend = mod_cgi_start_backend; p->handle_send_request_content = mod_cgi_send_request_content; p->handle_read_response_content = mod_cgi_read_response_content; p->handle_trigger = cgi_trigger; p->init = mod_cgi_init; p->cleanup = mod_cgi_free; p->set_defaults = mod_cgi_set_defaults; p->data = NULL; return 0; }
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/lighttpd_1913-1914.c
manybugs_data_18
/* +----------------------------------------------------------------------+ | phar php single-file executable PHP extension | +----------------------------------------------------------------------+ | Copyright (c) 2005-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Gregory Beaver <[email protected]> | | Marcus Boerger <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #define PHAR_MAIN 1 #include "phar_internal.h" #include "SAPI.h" #include "func_interceptors.h" static void destroy_phar_data(void *pDest); ZEND_DECLARE_MODULE_GLOBALS(phar) #if PHP_VERSION_ID >= 50300 char *(*phar_save_resolve_path)(const char *filename, int filename_len TSRMLS_DC); #endif /** * set's phar->is_writeable based on the current INI value */ static int phar_set_writeable_bit(void *pDest, void *argument TSRMLS_DC) /* {{{ */ { zend_bool keep = *(zend_bool *)argument; phar_archive_data *phar = *(phar_archive_data **)pDest; if (!phar->is_data) { phar->is_writeable = !keep; } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* if the original value is 0 (disabled), then allow setting/unsetting at will. Otherwise only allow 1 (enabled), and error on disabling */ ZEND_INI_MH(phar_ini_modify_handler) /* {{{ */ { zend_bool old, ini; if (entry->name_length == 14) { old = PHAR_G(readonly_orig); } else { old = PHAR_G(require_hash_orig); } if (new_value_length == 2 && !strcasecmp("on", new_value)) { ini = (zend_bool) 1; } else if (new_value_length == 3 && !strcasecmp("yes", new_value)) { ini = (zend_bool) 1; } else if (new_value_length == 4 && !strcasecmp("true", new_value)) { ini = (zend_bool) 1; } else { ini = (zend_bool) atoi(new_value); } /* do not allow unsetting in runtime */ if (stage == ZEND_INI_STAGE_STARTUP) { if (entry->name_length == 14) { PHAR_G(readonly_orig) = ini; } else { PHAR_G(require_hash_orig) = ini; } } else if (old && !ini) { return FAILURE; } if (entry->name_length == 14) { PHAR_G(readonly) = ini; if (PHAR_GLOBALS->request_init && PHAR_GLOBALS->phar_fname_map.arBuckets) { zend_hash_apply_with_argument(&(PHAR_GLOBALS->phar_fname_map), phar_set_writeable_bit, (void *)&ini TSRMLS_CC); } } else { PHAR_G(require_hash) = ini; } return SUCCESS; } /* }}}*/ /* this global stores the global cached pre-parsed manifests */ HashTable cached_phars; HashTable cached_alias; static void phar_split_cache_list(TSRMLS_D) /* {{{ */ { char *tmp; char *key, *lasts, *end; char ds[2]; phar_archive_data *phar; uint i = 0; if (!PHAR_GLOBALS->cache_list || !(PHAR_GLOBALS->cache_list[0])) { return; } ds[0] = DEFAULT_DIR_SEPARATOR; ds[1] = '\0'; tmp = estrdup(PHAR_GLOBALS->cache_list); /* fake request startup */ PHAR_GLOBALS->request_init = 1; if (zend_hash_init(&EG(regular_list), 0, NULL, NULL, 0) == SUCCESS) { EG(regular_list).nNextFreeElement=1; /* we don't want resource id 0 */ } PHAR_G(has_bz2) = zend_hash_exists(&module_registry, "bz2", sizeof("bz2")); PHAR_G(has_zlib) = zend_hash_exists(&module_registry, "zlib", sizeof("zlib")); /* these two are dummies and will be destroyed later */ zend_hash_init(&cached_phars, sizeof(phar_archive_data*), zend_get_hash_value, destroy_phar_data, 1); zend_hash_init(&cached_alias, sizeof(phar_archive_data*), zend_get_hash_value, NULL, 1); /* these two are real and will be copied over cached_phars/cached_alias later */ zend_hash_init(&(PHAR_GLOBALS->phar_fname_map), sizeof(phar_archive_data*), zend_get_hash_value, destroy_phar_data, 1); zend_hash_init(&(PHAR_GLOBALS->phar_alias_map), sizeof(phar_archive_data*), zend_get_hash_value, NULL, 1); PHAR_GLOBALS->manifest_cached = 1; PHAR_GLOBALS->persist = 1; for (key = php_strtok_r(tmp, ds, &lasts); key; key = php_strtok_r(NULL, ds, &lasts)) { end = strchr(key, DEFAULT_DIR_SEPARATOR); if (end) { if (SUCCESS == phar_open_from_filename(key, end - key, NULL, 0, 0, &phar, NULL TSRMLS_CC)) { finish_up: phar->phar_pos = i++; php_stream_close(phar->fp); phar->fp = NULL; } else { finish_error: PHAR_GLOBALS->persist = 0; PHAR_GLOBALS->manifest_cached = 0; efree(tmp); zend_hash_destroy(&(PHAR_G(phar_fname_map))); PHAR_GLOBALS->phar_fname_map.arBuckets = 0; zend_hash_destroy(&(PHAR_G(phar_alias_map))); PHAR_GLOBALS->phar_alias_map.arBuckets = 0; zend_hash_destroy(&cached_phars); zend_hash_destroy(&cached_alias); zend_hash_graceful_reverse_destroy(&EG(regular_list)); memset(&EG(regular_list), 0, sizeof(HashTable)); /* free cached manifests */ PHAR_GLOBALS->request_init = 0; return; } } else { if (SUCCESS == phar_open_from_filename(key, strlen(key), NULL, 0, 0, &phar, NULL TSRMLS_CC)) { goto finish_up; } else { goto finish_error; } } } PHAR_GLOBALS->persist = 0; PHAR_GLOBALS->request_init = 0; /* destroy dummy values from before */ zend_hash_destroy(&cached_phars); zend_hash_destroy(&cached_alias); cached_phars = PHAR_GLOBALS->phar_fname_map; cached_alias = PHAR_GLOBALS->phar_alias_map; PHAR_GLOBALS->phar_fname_map.arBuckets = 0; PHAR_GLOBALS->phar_alias_map.arBuckets = 0; zend_hash_graceful_reverse_destroy(&EG(regular_list)); memset(&EG(regular_list), 0, sizeof(HashTable)); efree(tmp); } /* }}} */ ZEND_INI_MH(phar_ini_cache_list) /* {{{ */ { PHAR_G(cache_list) = new_value; if (stage == ZEND_INI_STAGE_STARTUP) { phar_split_cache_list(TSRMLS_C); } return SUCCESS; } /* }}} */ PHP_INI_BEGIN() STD_PHP_INI_BOOLEAN( "phar.readonly", "1", PHP_INI_ALL, phar_ini_modify_handler, readonly, zend_phar_globals, phar_globals) STD_PHP_INI_BOOLEAN( "phar.require_hash", "1", PHP_INI_ALL, phar_ini_modify_handler, require_hash, zend_phar_globals, phar_globals) STD_PHP_INI_ENTRY("phar.cache_list", "", PHP_INI_SYSTEM, phar_ini_cache_list, cache_list, zend_phar_globals, phar_globals) PHP_INI_END() /** * When all uses of a phar have been concluded, this frees the manifest * and the phar slot */ void phar_destroy_phar_data(phar_archive_data *phar TSRMLS_DC) /* {{{ */ { if (phar->alias && phar->alias != phar->fname) { pefree(phar->alias, phar->is_persistent); phar->alias = NULL; } if (phar->fname) { pefree(phar->fname, phar->is_persistent); phar->fname = NULL; } if (phar->signature) { pefree(phar->signature, phar->is_persistent); phar->signature = NULL; } if (phar->manifest.arBuckets) { zend_hash_destroy(&phar->manifest); phar->manifest.arBuckets = NULL; } if (phar->mounted_dirs.arBuckets) { zend_hash_destroy(&phar->mounted_dirs); phar->mounted_dirs.arBuckets = NULL; } if (phar->virtual_dirs.arBuckets) { zend_hash_destroy(&phar->virtual_dirs); phar->virtual_dirs.arBuckets = NULL; } if (phar->metadata) { if (phar->is_persistent) { if (phar->metadata_len) { /* for zip comments that are strings */ free(phar->metadata); } else { zval_internal_ptr_dtor(&phar->metadata); } } else { zval_ptr_dtor(&phar->metadata); } phar->metadata_len = 0; phar->metadata = 0; } if (phar->fp) { php_stream_close(phar->fp); phar->fp = 0; } if (phar->ufp) { php_stream_close(phar->ufp); phar->ufp = 0; } pefree(phar, phar->is_persistent); } /* }}}*/ /** * Delete refcount and destruct if needed. On destruct return 1 else 0. */ int phar_archive_delref(phar_archive_data *phar TSRMLS_DC) /* {{{ */ { if (phar->is_persistent) { return 0; } if (--phar->refcount < 0) { if (PHAR_GLOBALS->request_done || zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), phar->fname, phar->fname_len) != SUCCESS) { phar_destroy_phar_data(phar TSRMLS_CC); } return 1; } else if (!phar->refcount) { /* invalidate phar cache */ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; if (phar->fp && !(phar->flags & PHAR_FILE_COMPRESSION_MASK)) { /* close open file handle - allows removal or rename of the file on windows, which has greedy locking only close if the archive was not already compressed. If it was compressed, then the fp does not refer to the original file */ php_stream_close(phar->fp); phar->fp = NULL; } if (!zend_hash_num_elements(&phar->manifest)) { /* this is a new phar that has perhaps had an alias/metadata set, but has never been flushed */ if (zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), phar->fname, phar->fname_len) != SUCCESS) { phar_destroy_phar_data(phar TSRMLS_CC); } return 1; } } return 0; } /* }}}*/ /** * Destroy phar's in shutdown, here we don't care about aliases */ static void destroy_phar_data_only(void *pDest) /* {{{ */ { phar_archive_data *phar_data = *(phar_archive_data **) pDest; TSRMLS_FETCH(); if (EG(exception) || --phar_data->refcount < 0) { phar_destroy_phar_data(phar_data TSRMLS_CC); } } /* }}}*/ /** * Delete aliases to phar's that got kicked out of the global table */ static int phar_unalias_apply(void *pDest, void *argument TSRMLS_DC) /* {{{ */ { return *(void**)pDest == argument ? ZEND_HASH_APPLY_REMOVE : ZEND_HASH_APPLY_KEEP; } /* }}} */ /** * Delete aliases to phar's that got kicked out of the global table */ static int phar_tmpclose_apply(void *pDest TSRMLS_DC) /* {{{ */ { phar_entry_info *entry = (phar_entry_info *) pDest; if (entry->fp_type != PHAR_TMP) { return ZEND_HASH_APPLY_KEEP; } if (entry->fp && !entry->fp_refcount) { php_stream_close(entry->fp); entry->fp = NULL; } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /** * Filename map destructor */ static void destroy_phar_data(void *pDest) /* {{{ */ { phar_archive_data *phar_data = *(phar_archive_data **) pDest; TSRMLS_FETCH(); if (PHAR_GLOBALS->request_ends) { /* first, iterate over the manifest and close all PHAR_TMP entry fp handles, this prevents unnecessary unfreed stream resources */ zend_hash_apply(&(phar_data->manifest), phar_tmpclose_apply TSRMLS_CC); destroy_phar_data_only(pDest); return; } zend_hash_apply_with_argument(&(PHAR_GLOBALS->phar_alias_map), phar_unalias_apply, phar_data TSRMLS_CC); if (--phar_data->refcount < 0) { phar_destroy_phar_data(phar_data TSRMLS_CC); } } /* }}}*/ /** * destructor for the manifest hash, frees each file's entry */ void destroy_phar_manifest_entry(void *pDest) /* {{{ */ { phar_entry_info *entry = (phar_entry_info *)pDest; TSRMLS_FETCH(); if (entry->cfp) { php_stream_close(entry->cfp); entry->cfp = 0; } if (entry->fp) { php_stream_close(entry->fp); entry->fp = 0; } if (entry->metadata) { if (entry->is_persistent) { if (entry->metadata_len) { /* for zip comments that are strings */ free(entry->metadata); } else { zval_internal_ptr_dtor(&entry->metadata); } } else { zval_ptr_dtor(&entry->metadata); } entry->metadata_len = 0; entry->metadata = 0; } if (entry->metadata_str.c) { smart_str_free(&entry->metadata_str); entry->metadata_str.c = 0; } pefree(entry->filename, entry->is_persistent); if (entry->link) { pefree(entry->link, entry->is_persistent); entry->link = 0; } if (entry->tmp) { pefree(entry->tmp, entry->is_persistent); entry->tmp = 0; } } /* }}} */ int phar_entry_delref(phar_entry_data *idata TSRMLS_DC) /* {{{ */ { int ret = 0; if (idata->internal_file && !idata->internal_file->is_persistent) { if (--idata->internal_file->fp_refcount < 0) { idata->internal_file->fp_refcount = 0; } if (idata->fp && idata->fp != idata->phar->fp && idata->fp != idata->phar->ufp && idata->fp != idata->internal_file->fp) { php_stream_close(idata->fp); } /* if phar_get_or_create_entry_data returns a sub-directory, we have to free it */ if (idata->internal_file->is_temp_dir) { destroy_phar_manifest_entry((void *)idata->internal_file); efree(idata->internal_file); } } phar_archive_delref(idata->phar TSRMLS_CC); efree(idata); return ret; } /* }}} */ /** * Removes an entry, either by actually removing it or by marking it. */ void phar_entry_remove(phar_entry_data *idata, char **error TSRMLS_DC) /* {{{ */ { phar_archive_data *phar; phar = idata->phar; if (idata->internal_file->fp_refcount < 2) { if (idata->fp && idata->fp != idata->phar->fp && idata->fp != idata->phar->ufp && idata->fp != idata->internal_file->fp) { php_stream_close(idata->fp); } zend_hash_del(&idata->phar->manifest, idata->internal_file->filename, idata->internal_file->filename_len); idata->phar->refcount--; efree(idata); } else { idata->internal_file->is_deleted = 1; phar_entry_delref(idata TSRMLS_CC); } if (!phar->donotflush) { phar_flush(phar, 0, 0, 0, error TSRMLS_CC); } } /* }}} */ #define MAPPHAR_ALLOC_FAIL(msg) \ if (fp) {\ php_stream_close(fp);\ }\ if (error) {\ spprintf(error, 0, msg, fname);\ }\ return FAILURE; #define MAPPHAR_FAIL(msg) \ efree(savebuf);\ if (mydata) {\ phar_destroy_phar_data(mydata TSRMLS_CC);\ }\ if (signature) {\ pefree(signature, PHAR_G(persist));\ }\ MAPPHAR_ALLOC_FAIL(msg) #ifdef WORDS_BIGENDIAN # define PHAR_GET_32(buffer, var) \ var = ((((unsigned char*)(buffer))[3]) << 24) \ | ((((unsigned char*)(buffer))[2]) << 16) \ | ((((unsigned char*)(buffer))[1]) << 8) \ | (((unsigned char*)(buffer))[0]); \ (buffer) += 4 # define PHAR_GET_16(buffer, var) \ var = ((((unsigned char*)(buffer))[1]) << 8) \ | (((unsigned char*)(buffer))[0]); \ (buffer) += 2 #else # define PHAR_GET_32(buffer, var) \ memcpy(&var, buffer, sizeof(var)); \ buffer += 4 # define PHAR_GET_16(buffer, var) \ var = *(php_uint16*)(buffer); \ buffer += 2 #endif #define PHAR_ZIP_16(var) ((php_uint16)((((php_uint16)var[0]) & 0xff) | \ (((php_uint16)var[1]) & 0xff) << 8)) #define PHAR_ZIP_32(var) ((php_uint32)((((php_uint32)var[0]) & 0xff) | \ (((php_uint32)var[1]) & 0xff) << 8 | \ (((php_uint32)var[2]) & 0xff) << 16 | \ (((php_uint32)var[3]) & 0xff) << 24)) /** * Open an already loaded phar */ int phar_open_parsed_phar(char *fname, int fname_len, char *alias, int alias_len, int is_data, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { phar_archive_data *phar; #ifdef PHP_WIN32 char *unixfname; #endif if (error) { *error = NULL; } #ifdef PHP_WIN32 unixfname = estrndup(fname, fname_len); phar_unixify_path_separators(unixfname, fname_len); if (SUCCESS == phar_get_archive(&phar, unixfname, fname_len, alias, alias_len, error TSRMLS_CC) && ((alias && fname_len == phar->fname_len && !strncmp(unixfname, phar->fname, fname_len)) || !alias) ) { phar_entry_info *stub; efree(unixfname); #else if (SUCCESS == phar_get_archive(&phar, fname, fname_len, alias, alias_len, error TSRMLS_CC) && ((alias && fname_len == phar->fname_len && !strncmp(fname, phar->fname, fname_len)) || !alias) ) { phar_entry_info *stub; #endif /* logic above is as follows: If an explicit alias was requested, ensure the filename passed in matches the phar's filename. If no alias was passed in, then it can match either and be valid */ if (!is_data) { /* prevent any ".phar" without a stub getting through */ if (!phar->halt_offset && !phar->is_brandnew && (phar->is_tar || phar->is_zip)) { if (PHAR_G(readonly) && FAILURE == zend_hash_find(&(phar->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1, (void **)&stub)) { if (error) { spprintf(error, 0, "'%s' is not a phar archive. Use PharData::__construct() for a standard zip or tar archive", fname); } return FAILURE; } } } if (pphar) { *pphar = phar; } return SUCCESS; } else { #ifdef PHP_WIN32 efree(unixfname); #endif if (pphar) { *pphar = NULL; } if (phar && error && !(options & REPORT_ERRORS)) { efree(error); } return FAILURE; } } /* }}}*/ /** * Parse out metadata from the manifest for a single file * * Meta-data is in this format: * [len32][data...] * * data is the serialized zval */ int phar_parse_metadata(char **buffer, zval **metadata, int zip_metadata_len TSRMLS_DC) /* {{{ */ { const unsigned char *p; php_uint32 buf_len; php_unserialize_data_t var_hash; if (!zip_metadata_len) { PHAR_GET_32(*buffer, buf_len); } else { buf_len = zip_metadata_len; } if (buf_len) { ALLOC_ZVAL(*metadata); INIT_ZVAL(**metadata); p = (const unsigned char*) *buffer; PHP_VAR_UNSERIALIZE_INIT(var_hash); if (!php_var_unserialize(metadata, &p, p + buf_len, &var_hash TSRMLS_CC)) { PHP_VAR_UNSERIALIZE_DESTROY(var_hash); zval_ptr_dtor(metadata); *metadata = NULL; return FAILURE; } PHP_VAR_UNSERIALIZE_DESTROY(var_hash); if (PHAR_G(persist)) { /* lazy init metadata */ zval_ptr_dtor(metadata); *metadata = (zval *) pemalloc(buf_len, 1); memcpy(*metadata, *buffer, buf_len); *buffer += buf_len; return SUCCESS; } } else { *metadata = NULL; } if (!zip_metadata_len) { *buffer += buf_len; } return SUCCESS; } /* }}}*/ /** * Does not check for a previously opened phar in the cache. * * Parse a new one and add it to the cache, returning either SUCCESS or * FAILURE, and setting pphar to the pointer to the manifest entry * * This is used by phar_open_from_filename to process the manifest, but can be called * directly. */ static int phar_parse_pharfile(php_stream *fp, char *fname, int fname_len, char *alias, int alias_len, long halt_offset, phar_archive_data** pphar, php_uint32 compression, char **error TSRMLS_DC) /* {{{ */ { char b32[4], *buffer, *endbuffer, *savebuf; phar_archive_data *mydata = NULL; phar_entry_info entry; php_uint32 manifest_len, manifest_count, manifest_flags, manifest_index, tmp_len, sig_flags; php_uint16 manifest_ver; long offset; int sig_len, register_alias = 0, temp_alias = 0; char *signature = NULL; if (pphar) { *pphar = NULL; } if (error) { *error = NULL; } /* check for ?>\n and increment accordingly */ if (-1 == php_stream_seek(fp, halt_offset, SEEK_SET)) { MAPPHAR_ALLOC_FAIL("cannot seek to __HALT_COMPILER(); location in phar \"%s\"") } buffer = b32; if (3 != php_stream_read(fp, buffer, 3)) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at stub end)") } if ((*buffer == ' ' || *buffer == '\n') && *(buffer + 1) == '?' && *(buffer + 2) == '>') { int nextchar; halt_offset += 3; if (EOF == (nextchar = php_stream_getc(fp))) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at stub end)") } if ((char) nextchar == '\r') { /* if we have an \r we require an \n as well */ if (EOF == (nextchar = php_stream_getc(fp)) || (char)nextchar != '\n') { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at stub end)") } ++halt_offset; } if ((char) nextchar == '\n') { ++halt_offset; } } /* make sure we are at the right location to read the manifest */ if (-1 == php_stream_seek(fp, halt_offset, SEEK_SET)) { MAPPHAR_ALLOC_FAIL("cannot seek to __HALT_COMPILER(); location in phar \"%s\"") } /* read in manifest */ buffer = b32; if (4 != php_stream_read(fp, buffer, 4)) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at manifest length)") } PHAR_GET_32(buffer, manifest_len); if (manifest_len > 1048576 * 100) { /* prevent serious memory issues by limiting manifest to at most 100 MB in length */ MAPPHAR_ALLOC_FAIL("manifest cannot be larger than 100 MB in phar \"%s\"") } buffer = (char *)emalloc(manifest_len); savebuf = buffer; endbuffer = buffer + manifest_len; if (manifest_len < 10 || manifest_len != php_stream_read(fp, buffer, manifest_len)) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest header)") } /* extract the number of entries */ PHAR_GET_32(buffer, manifest_count); if (manifest_count == 0) { MAPPHAR_FAIL("in phar \"%s\", manifest claims to have zero entries. Phars must have at least 1 entry"); } /* extract API version, lowest nibble currently unused */ manifest_ver = (((unsigned char)buffer[0]) << 8) + ((unsigned char)buffer[1]); buffer += 2; if ((manifest_ver & PHAR_API_VER_MASK) < PHAR_API_MIN_READ) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" is API version %1.u.%1.u.%1.u, and cannot be processed", fname, manifest_ver >> 12, (manifest_ver >> 8) & 0xF, (manifest_ver >> 4) & 0x0F); } return FAILURE; } PHAR_GET_32(buffer, manifest_flags); manifest_flags &= ~PHAR_HDR_COMPRESSION_MASK; manifest_flags &= ~PHAR_FILE_COMPRESSION_MASK; /* remember whether this entire phar was compressed with gz/bzip2 */ manifest_flags |= compression; /* The lowest nibble contains the phar wide flags. The compression flags can */ /* be ignored on reading because it is being generated anyways. */ if (manifest_flags & PHAR_HDR_SIGNATURE) { char sig_buf[8], *sig_ptr = sig_buf; off_t read_len; size_t end_of_phar; if (-1 == php_stream_seek(fp, -8, SEEK_END) || (read_len = php_stream_tell(fp)) < 20 || 8 != php_stream_read(fp, sig_buf, 8) || memcmp(sig_buf+4, "GBMB", 4)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } PHAR_GET_32(sig_ptr, sig_flags); switch(sig_flags) { case PHAR_SIG_OPENSSL: { php_uint32 signature_len; char *sig; off_t whence; /* we store the signature followed by the signature length */ if (-1 == php_stream_seek(fp, -12, SEEK_CUR) || 4 != php_stream_read(fp, sig_buf, 4)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" openssl signature length could not be read", fname); } return FAILURE; } sig_ptr = sig_buf; PHAR_GET_32(sig_ptr, signature_len); sig = (char *) emalloc(signature_len); whence = signature_len + 4; whence = -whence; if (-1 == php_stream_seek(fp, whence, SEEK_CUR) || !(end_of_phar = php_stream_tell(fp)) || signature_len != php_stream_read(fp, sig, signature_len)) { efree(savebuf); efree(sig); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" openssl signature could not be read", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, end_of_phar, PHAR_SIG_OPENSSL, sig, signature_len, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); efree(sig); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" openssl signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } efree(sig); } break; #if PHAR_HASH_OK case PHAR_SIG_SHA512: { unsigned char digest[64]; php_stream_seek(fp, -(8 + 64), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_SHA512, (char *)digest, 64, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" SHA512 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } case PHAR_SIG_SHA256: { unsigned char digest[32]; php_stream_seek(fp, -(8 + 32), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_SHA256, (char *)digest, 32, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" SHA256 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } #else case PHAR_SIG_SHA512: case PHAR_SIG_SHA256: efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a unsupported signature", fname); } return FAILURE; #endif case PHAR_SIG_SHA1: { unsigned char digest[20]; php_stream_seek(fp, -(8 + 20), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_SHA1, (char *)digest, 20, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" SHA1 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } case PHAR_SIG_MD5: { unsigned char digest[16]; php_stream_seek(fp, -(8 + 16), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_MD5, (char *)digest, 16, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" MD5 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } default: efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken or unsupported signature", fname); } return FAILURE; } } else if (PHAR_G(require_hash)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" does not have a signature", fname); } return FAILURE; } else { sig_flags = 0; sig_len = 0; } /* extract alias */ PHAR_GET_32(buffer, tmp_len); if (buffer + tmp_len > endbuffer) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (buffer overrun)"); } if (manifest_len < 10 + tmp_len) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest header)") } /* tmp_len = 0 says alias length is 0, which means the alias is not stored in the phar */ if (tmp_len) { /* if the alias is stored we enforce it (implicit overrides explicit) */ if (alias && alias_len && (alias_len != (int)tmp_len || strncmp(alias, buffer, tmp_len))) { buffer[tmp_len] = '\0'; php_stream_close(fp); if (signature) { efree(signature); } if (error) { spprintf(error, 0, "cannot load phar \"%s\" with implicit alias \"%s\" under different alias \"%s\"", fname, buffer, alias); } efree(savebuf); return FAILURE; } alias_len = tmp_len; alias = buffer; buffer += tmp_len; register_alias = 1; } else if (!alias_len || !alias) { /* if we neither have an explicit nor an implicit alias, we use the filename */ alias = NULL; alias_len = 0; register_alias = 0; } else if (alias_len) { register_alias = 1; temp_alias = 1; } /* we have 5 32-bit items plus 1 byte at least */ if (manifest_count > ((manifest_len - 10 - tmp_len) / (5 * 4 + 1))) { /* prevent serious memory issues */ MAPPHAR_FAIL("internal corruption of phar \"%s\" (too many manifest entries for size of manifest)") } mydata = pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist)); mydata->is_persistent = PHAR_G(persist); /* check whether we have meta data, zero check works regardless of byte order */ if (mydata->is_persistent) { PHAR_GET_32(buffer, mydata->metadata_len); if (phar_parse_metadata(&buffer, &mydata->metadata, mydata->metadata_len TSRMLS_CC) == FAILURE) { MAPPHAR_FAIL("unable to read phar metadata in .phar file \"%s\""); } } else { if (phar_parse_metadata(&buffer, &mydata->metadata, 0 TSRMLS_CC) == FAILURE) { MAPPHAR_FAIL("unable to read phar metadata in .phar file \"%s\""); } } /* set up our manifest */ zend_hash_init(&mydata->manifest, manifest_count, zend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)mydata->is_persistent); zend_hash_init(&mydata->mounted_dirs, 5, zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); zend_hash_init(&mydata->virtual_dirs, manifest_count * 2, zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); mydata->fname = pestrndup(fname, fname_len, mydata->is_persistent); #ifdef PHP_WIN32 phar_unixify_path_separators(mydata->fname, fname_len); #endif mydata->fname_len = fname_len; offset = halt_offset + manifest_len + 4; memset(&entry, 0, sizeof(phar_entry_info)); entry.phar = mydata; entry.fp_type = PHAR_FP; entry.is_persistent = mydata->is_persistent; for (manifest_index = 0; manifest_index < manifest_count; ++manifest_index) { if (buffer + 4 > endbuffer) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest entry)") } PHAR_GET_32(buffer, entry.filename_len); if (entry.filename_len == 0) { MAPPHAR_FAIL("zero-length filename encountered in phar \"%s\""); } if (entry.is_persistent) { entry.manifest_pos = manifest_index; } if (buffer + entry.filename_len + 20 > endbuffer) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest entry)"); } if ((manifest_ver & PHAR_API_VER_MASK) >= PHAR_API_MIN_DIR && buffer[entry.filename_len - 1] == '/') { entry.is_dir = 1; } else { entry.is_dir = 0; } phar_add_virtual_dirs(mydata, buffer, entry.filename_len TSRMLS_CC); entry.filename = pestrndup(buffer, entry.filename_len, entry.is_persistent); buffer += entry.filename_len; PHAR_GET_32(buffer, entry.uncompressed_filesize); PHAR_GET_32(buffer, entry.timestamp); if (offset == halt_offset + (int)manifest_len + 4) { mydata->min_timestamp = entry.timestamp; mydata->max_timestamp = entry.timestamp; } else { if (mydata->min_timestamp > entry.timestamp) { mydata->min_timestamp = entry.timestamp; } else if (mydata->max_timestamp < entry.timestamp) { mydata->max_timestamp = entry.timestamp; } } PHAR_GET_32(buffer, entry.compressed_filesize); PHAR_GET_32(buffer, entry.crc32); PHAR_GET_32(buffer, entry.flags); if (entry.is_dir) { entry.filename_len--; entry.flags |= PHAR_ENT_PERM_DEF_DIR; } if (entry.is_persistent) { PHAR_GET_32(buffer, entry.metadata_len); if (!entry.metadata_len) buffer -= 4; if (phar_parse_metadata(&buffer, &entry.metadata, entry.metadata_len TSRMLS_CC) == FAILURE) { pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("unable to read file metadata in .phar file \"%s\""); } } else { if (phar_parse_metadata(&buffer, &entry.metadata, 0 TSRMLS_CC) == FAILURE) { pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("unable to read file metadata in .phar file \"%s\""); } } entry.offset = entry.offset_abs = offset; offset += entry.compressed_filesize; switch (entry.flags & PHAR_ENT_COMPRESSION_MASK) { case PHAR_ENT_COMPRESSED_GZ: if (!PHAR_G(has_zlib)) { if (entry.metadata) { if (entry.is_persistent) { free(entry.metadata); } else { zval_ptr_dtor(&entry.metadata); } } pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("zlib extension is required for gz compressed .phar file \"%s\""); } break; case PHAR_ENT_COMPRESSED_BZ2: if (!PHAR_G(has_bz2)) { if (entry.metadata) { if (entry.is_persistent) { free(entry.metadata); } else { zval_ptr_dtor(&entry.metadata); } } pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("bz2 extension is required for bzip2 compressed .phar file \"%s\""); } break; default: if (entry.uncompressed_filesize != entry.compressed_filesize) { if (entry.metadata) { if (entry.is_persistent) { free(entry.metadata); } else { zval_ptr_dtor(&entry.metadata); } } pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("internal corruption of phar \"%s\" (compressed and uncompressed size does not match for uncompressed entry)"); } break; } manifest_flags |= (entry.flags & PHAR_ENT_COMPRESSION_MASK); /* if signature matched, no need to check CRC32 for each file */ entry.is_crc_checked = (manifest_flags & PHAR_HDR_SIGNATURE ? 1 : 0); phar_set_inode(&entry TSRMLS_CC); zend_hash_add(&mydata->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info), NULL); } snprintf(mydata->version, sizeof(mydata->version), "%u.%u.%u", manifest_ver >> 12, (manifest_ver >> 8) & 0xF, (manifest_ver >> 4) & 0xF); mydata->internal_file_start = halt_offset + manifest_len + 4; mydata->halt_offset = halt_offset; mydata->flags = manifest_flags; endbuffer = strrchr(mydata->fname, '/'); if (endbuffer) { mydata->ext = memchr(endbuffer, '.', (mydata->fname + fname_len) - endbuffer); if (mydata->ext == endbuffer) { mydata->ext = memchr(endbuffer + 1, '.', (mydata->fname + fname_len) - endbuffer - 1); } if (mydata->ext) { mydata->ext_len = (mydata->fname + mydata->fname_len) - mydata->ext; } } mydata->alias = alias ? pestrndup(alias, alias_len, mydata->is_persistent) : pestrndup(mydata->fname, fname_len, mydata->is_persistent); mydata->alias_len = alias ? alias_len : fname_len; mydata->sig_flags = sig_flags; mydata->fp = fp; mydata->sig_len = sig_len; mydata->signature = signature; phar_request_initialize(TSRMLS_C); if (register_alias) { phar_archive_data **fd_ptr; mydata->is_temporary_alias = temp_alias; if (!phar_validate_alias(mydata->alias, mydata->alias_len)) { signature = NULL; fp = NULL; MAPPHAR_FAIL("Cannot open archive \"%s\", invalid alias"); } if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) { if (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) { signature = NULL; fp = NULL; MAPPHAR_FAIL("Cannot open archive \"%s\", alias is already in use by existing archive"); } } zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&mydata, sizeof(phar_archive_data*), NULL); } else { mydata->is_temporary_alias = 1; } zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len, (void*)&mydata, sizeof(phar_archive_data*), NULL); efree(savebuf); if (pphar) { *pphar = mydata; } return SUCCESS; } /* }}} */ /** * Create or open a phar for writing */ int phar_open_or_create_filename(char *fname, int fname_len, char *alias, int alias_len, int is_data, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { const char *ext_str, *z; char *my_error; int ext_len; phar_archive_data **test, *unused = NULL; test = &unused; if (error) { *error = NULL; } /* first try to open an existing file */ if (phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, !is_data, 0, 1 TSRMLS_CC) == SUCCESS) { goto check_file; } /* next try to create a new file */ if (FAILURE == phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, !is_data, 1, 1 TSRMLS_CC)) { if (error) { if (ext_len == -2) { spprintf(error, 0, "Cannot create a phar archive from a URL like \"%s\". Phar objects can only be created from local files", fname); } else { spprintf(error, 0, "Cannot create phar '%s', file extension (or combination) not recognised or the directory does not exist", fname); } } return FAILURE; } check_file: if (phar_open_parsed_phar(fname, fname_len, alias, alias_len, is_data, options, test, &my_error TSRMLS_CC) == SUCCESS) { if (pphar) { *pphar = *test; } if ((*test)->is_data && !(*test)->is_tar && !(*test)->is_zip) { if (error) { spprintf(error, 0, "Cannot open '%s' as a PharData object. Use Phar::__construct() for executable archives", fname); } return FAILURE; } if (PHAR_G(readonly) && !(*test)->is_data && ((*test)->is_tar || (*test)->is_zip)) { phar_entry_info *stub; if (FAILURE == zend_hash_find(&((*test)->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1, (void **)&stub)) { spprintf(error, 0, "'%s' is not a phar archive. Use PharData::__construct() for a standard zip or tar archive", fname); return FAILURE; } } if (!PHAR_G(readonly) || (*test)->is_data) { (*test)->is_writeable = 1; } return SUCCESS; } else if (my_error) { if (error) { *error = my_error; } else { efree(my_error); } return FAILURE; } if (ext_len > 3 && (z = memchr(ext_str, 'z', ext_len)) && ((ext_str + ext_len) - z >= 2) && !memcmp(z + 1, "ip", 2)) { /* assume zip-based phar */ return phar_open_or_create_zip(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC); } if (ext_len > 3 && (z = memchr(ext_str, 't', ext_len)) && ((ext_str + ext_len) - z >= 2) && !memcmp(z + 1, "ar", 2)) { /* assume tar-based phar */ return phar_open_or_create_tar(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC); } return phar_create_or_parse_filename(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC); } /* }}} */ int phar_create_or_parse_filename(char *fname, int fname_len, char *alias, int alias_len, int is_data, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { phar_archive_data *mydata; php_stream *fp; char *actual = NULL, *p; if (!pphar) { pphar = &mydata; } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { return FAILURE; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { return FAILURE; } /* first open readonly so it won't be created if not present */ fp = php_stream_open_wrapper(fname, "rb", IGNORE_URL|STREAM_MUST_SEEK|0, &actual); if (actual) { fname = actual; fname_len = strlen(actual); } if (fp) { if (phar_open_from_fp(fp, fname, fname_len, alias, alias_len, options, pphar, is_data, error TSRMLS_CC) == SUCCESS) { if ((*pphar)->is_data || !PHAR_G(readonly)) { (*pphar)->is_writeable = 1; } if (actual) { efree(actual); } return SUCCESS; } else { /* file exists, but is either corrupt or not a phar archive */ if (actual) { efree(actual); } return FAILURE; } } if (actual) { efree(actual); } if (PHAR_G(readonly) && !is_data) { if (options & REPORT_ERRORS) { if (error) { spprintf(error, 0, "creating archive \"%s\" disabled by the php.ini setting phar.readonly", fname); } } return FAILURE; } /* set up our manifest */ mydata = ecalloc(1, sizeof(phar_archive_data)); mydata->fname = expand_filepath(fname, NULL TSRMLS_CC); fname_len = strlen(mydata->fname); #ifdef PHP_WIN32 phar_unixify_path_separators(mydata->fname, fname_len); #endif p = strrchr(mydata->fname, '/'); if (p) { mydata->ext = memchr(p, '.', (mydata->fname + fname_len) - p); if (mydata->ext == p) { mydata->ext = memchr(p + 1, '.', (mydata->fname + fname_len) - p - 1); } if (mydata->ext) { mydata->ext_len = (mydata->fname + fname_len) - mydata->ext; } } if (pphar) { *pphar = mydata; } zend_hash_init(&mydata->manifest, sizeof(phar_entry_info), zend_get_hash_value, destroy_phar_manifest_entry, 0); zend_hash_init(&mydata->mounted_dirs, sizeof(char *), zend_get_hash_value, NULL, 0); zend_hash_init(&mydata->virtual_dirs, sizeof(char *), zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); mydata->fname_len = fname_len; snprintf(mydata->version, sizeof(mydata->version), "%s", PHP_PHAR_API_VERSION); mydata->is_temporary_alias = alias ? 0 : 1; mydata->internal_file_start = -1; mydata->fp = NULL; mydata->is_writeable = 1; mydata->is_brandnew = 1; phar_request_initialize(TSRMLS_C); zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len, (void*)&mydata, sizeof(phar_archive_data*), NULL); if (is_data) { alias = NULL; alias_len = 0; mydata->is_data = 1; /* assume tar format, PharData can specify other */ mydata->is_tar = 1; } else { phar_archive_data **fd_ptr; if (alias && SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) { if (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) { if (error) { spprintf(error, 4096, "phar error: phar \"%s\" cannot set alias \"%s\", already in use by another phar archive", mydata->fname, alias); } zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len); if (pphar) { *pphar = NULL; } return FAILURE; } } mydata->alias = alias ? estrndup(alias, alias_len) : estrndup(mydata->fname, fname_len); mydata->alias_len = alias ? alias_len : fname_len; } if (alias_len && alias) { if (FAILURE == zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&mydata, sizeof(phar_archive_data*), NULL)) { if (options & REPORT_ERRORS) { if (error) { spprintf(error, 0, "archive \"%s\" cannot be associated with alias \"%s\", already in use", fname, alias); } } zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len); if (pphar) { *pphar = NULL; } return FAILURE; } } return SUCCESS; } /* }}}*/ /** * Return an already opened filename. * * Or scan a phar file for the required __HALT_COMPILER(); ?> token and verify * that the manifest is proper, then pass it to phar_parse_pharfile(). SUCCESS * or FAILURE is returned and pphar is set to a pointer to the phar's manifest */ int phar_open_from_filename(char *fname, int fname_len, char *alias, int alias_len, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { php_stream *fp; char *actual; int ret, is_data = 0; if (error) { *error = NULL; } if (!strstr(fname, ".phar")) { is_data = 1; } if (phar_open_parsed_phar(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC) == SUCCESS) { return SUCCESS; } else if (error && *error) { return FAILURE; } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { return FAILURE; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { return FAILURE; } fp = php_stream_open_wrapper(fname, "rb", IGNORE_URL|STREAM_MUST_SEEK, &actual); if (!fp) { if (options & REPORT_ERRORS) { if (error) { spprintf(error, 0, "unable to open phar for reading \"%s\"", fname); } } if (actual) { efree(actual); } return FAILURE; } if (actual) { fname = actual; fname_len = strlen(actual); } ret = phar_open_from_fp(fp, fname, fname_len, alias, alias_len, options, pphar, is_data, error TSRMLS_CC); if (actual) { efree(actual); } return ret; } /* }}}*/ static inline char *phar_strnstr(const char *buf, int buf_len, const char *search, int search_len) /* {{{ */ { const char *c; int so_far = 0; if (buf_len < search_len) { return NULL; } c = buf - 1; do { if (!(c = memchr(c + 1, search[0], buf_len - search_len - so_far))) { return (char *) NULL; } so_far = c - buf; if (so_far >= (buf_len - search_len)) { return (char *) NULL; } if (!memcmp(c, search, search_len)) { return (char *) c; } } while (1); } /* }}} */ /** * Scan an open fp for the required __HALT_COMPILER(); ?> token and verify * that the manifest is proper, then pass it to phar_parse_pharfile(). SUCCESS * or FAILURE is returned and pphar is set to a pointer to the phar's manifest */ static int phar_open_from_fp(php_stream* fp, char *fname, int fname_len, char *alias, int alias_len, int options, phar_archive_data** pphar, int is_data, char **error TSRMLS_DC) /* {{{ */ { const char token[] = "__HALT_COMPILER();"; const char zip_magic[] = "PK\x03\x04"; const char gz_magic[] = "\x1f\x8b\x08"; const char bz_magic[] = "BZh"; char *pos, test = '\0'; const int window_size = 1024 + sizeof(token); char buffer[1024 + sizeof(token)]; /* a 1024 byte window + the size of the halt_compiler token (moving window) */ const long readsize = sizeof(buffer) - sizeof(token); const long tokenlen = sizeof(token) - 1; long halt_offset; size_t got; php_uint32 compression = PHAR_FILE_COMPRESSED_NONE; if (error) { *error = NULL; } if (-1 == php_stream_rewind(fp)) { MAPPHAR_ALLOC_FAIL("cannot rewind phar \"%s\"") } buffer[sizeof(buffer)-1] = '\0'; memset(buffer, 32, sizeof(token)); halt_offset = 0; /* Maybe it's better to compile the file instead of just searching, */ /* but we only want the offset. So we want a .re scanner to find it. */ while(!php_stream_eof(fp)) { if ((got = php_stream_read(fp, buffer+tokenlen, readsize)) < (size_t) tokenlen) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated entry)") } if (!test) { test = '\1'; pos = buffer+tokenlen; if (!memcmp(pos, gz_magic, 3)) { char err = 0; php_stream_filter *filter; php_stream *temp; /* to properly decompress, we have to tell zlib to look for a zlib or gzip header */ zval filterparams; if (!PHAR_G(has_zlib)) { MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\" to temporary file, enable zlib extension in php.ini") } array_init(&filterparams); /* this is defined in zlib's zconf.h */ #ifndef MAX_WBITS #define MAX_WBITS 15 #endif add_assoc_long(&filterparams, "window", MAX_WBITS + 32); /* entire file is gzip-compressed, uncompress to temporary file */ if (!(temp = php_stream_fopen_tmpfile())) { MAPPHAR_ALLOC_FAIL("unable to create temporary file for decompression of gzipped phar archive \"%s\"") } php_stream_rewind(fp); filter = php_stream_filter_create("zlib.inflate", &filterparams, php_stream_is_persistent(fp) TSRMLS_CC); if (!filter) { err = 1; add_assoc_long(&filterparams, "window", MAX_WBITS); filter = php_stream_filter_create("zlib.inflate", &filterparams, php_stream_is_persistent(fp) TSRMLS_CC); zval_dtor(&filterparams); if (!filter) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\", ext/zlib is buggy in PHP versions older than 5.2.6") } } else { zval_dtor(&filterparams); } php_stream_filter_append(&temp->writefilters, filter); if (SUCCESS != phar_stream_copy_to_stream(fp, temp, PHP_STREAM_COPY_ALL, NULL)) { if (err) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\", ext/zlib is buggy in PHP versions older than 5.2.6") } php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\" to temporary file") } php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(fp); fp = temp; php_stream_rewind(fp); compression = PHAR_FILE_COMPRESSED_GZ; /* now, start over */ test = '\0'; continue; } else if (!memcmp(pos, bz_magic, 3)) { php_stream_filter *filter; php_stream *temp; if (!PHAR_G(has_bz2)) { MAPPHAR_ALLOC_FAIL("unable to decompress bzipped phar archive \"%s\" to temporary file, enable bz2 extension in php.ini") } /* entire file is bzip-compressed, uncompress to temporary file */ if (!(temp = php_stream_fopen_tmpfile())) { MAPPHAR_ALLOC_FAIL("unable to create temporary file for decompression of bzipped phar archive \"%s\"") } php_stream_rewind(fp); filter = php_stream_filter_create("bzip2.decompress", NULL, php_stream_is_persistent(fp) TSRMLS_CC); if (!filter) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress bzipped phar archive \"%s\", filter creation failed") } php_stream_filter_append(&temp->writefilters, filter); if (SUCCESS != phar_stream_copy_to_stream(fp, temp, PHP_STREAM_COPY_ALL, NULL)) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress bzipped phar archive \"%s\" to temporary file") } php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(fp); fp = temp; php_stream_rewind(fp); compression = PHAR_FILE_COMPRESSED_BZ2; /* now, start over */ test = '\0'; continue; } if (!memcmp(pos, zip_magic, 4)) { php_stream_seek(fp, 0, SEEK_END); return phar_parse_zipfile(fp, fname, fname_len, alias, alias_len, pphar, error TSRMLS_CC); } if (got > 512) { if (phar_is_tar(pos, fname)) { php_stream_rewind(fp); return phar_parse_tarfile(fp, fname, fname_len, alias, alias_len, pphar, is_data, compression, error TSRMLS_CC); } } } if (got > 0 && (pos = phar_strnstr(buffer, got + sizeof(token), token, sizeof(token)-1)) != NULL) { halt_offset += (pos - buffer); /* no -tokenlen+tokenlen here */ return phar_parse_pharfile(fp, fname, fname_len, alias, alias_len, halt_offset, pphar, compression, error TSRMLS_CC); } halt_offset += got; memmove(buffer, buffer + window_size, tokenlen); /* move the memory buffer by the size of the window */ } MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (__HALT_COMPILER(); not found)") } /* }}} */ /* * given the location of the file extension and the start of the file path, * determine the end of the portion of the path (i.e. /path/to/file.ext/blah * grabs "/path/to/file.ext" as does the straight /path/to/file.ext), * stat it to determine if it exists. * if so, check to see if it is a directory and fail if so * if not, check to see if its dirname() exists (i.e. "/path/to") and is a directory * succeed if we are creating the file, otherwise fail. */ static int phar_analyze_path(const char *fname, const char *ext, int ext_len, int for_create TSRMLS_DC) /* {{{ */ { php_stream_statbuf ssb; char *realpath; char *filename = estrndup(fname, (ext - fname) + ext_len); if ((realpath = expand_filepath(filename, NULL TSRMLS_CC))) { #ifdef PHP_WIN32 phar_unixify_path_separators(realpath, strlen(realpath)); #endif if (zend_hash_exists(&(PHAR_GLOBALS->phar_fname_map), realpath, strlen(realpath))) { efree(realpath); efree(filename); return SUCCESS; } if (PHAR_G(manifest_cached) && zend_hash_exists(&cached_phars, realpath, strlen(realpath))) { efree(realpath); efree(filename); return SUCCESS; } efree(realpath); } if (SUCCESS == php_stream_stat_path((char *) filename, &ssb)) { efree(filename); if (ssb.sb.st_mode & S_IFDIR) { return FAILURE; } if (for_create == 1) { return FAILURE; } return SUCCESS; } else { char *slash; if (!for_create) { efree(filename); return FAILURE; } slash = (char *) strrchr(filename, '/'); if (slash) { *slash = '\0'; } if (SUCCESS != php_stream_stat_path((char *) filename, &ssb)) { if (!slash) { if (!(realpath = expand_filepath(filename, NULL TSRMLS_CC))) { efree(filename); return FAILURE; } #ifdef PHP_WIN32 phar_unixify_path_separators(realpath, strlen(realpath)); #endif slash = strstr(realpath, filename) + ((ext - fname) + ext_len); *slash = '\0'; slash = strrchr(realpath, '/'); if (slash) { *slash = '\0'; } else { efree(realpath); efree(filename); return FAILURE; } if (SUCCESS != php_stream_stat_path(realpath, &ssb)) { efree(realpath); efree(filename); return FAILURE; } efree(realpath); if (ssb.sb.st_mode & S_IFDIR) { efree(filename); return SUCCESS; } } efree(filename); return FAILURE; } efree(filename); if (ssb.sb.st_mode & S_IFDIR) { return SUCCESS; } return FAILURE; } } /* }}} */ /* check for ".phar" in extension */ static int phar_check_str(const char *fname, const char *ext_str, int ext_len, int executable, int for_create TSRMLS_DC) /* {{{ */ { char test[51]; const char *pos; if (ext_len >= 50) { return FAILURE; } if (executable == 1) { /* copy "." as well */ memcpy(test, ext_str - 1, ext_len + 1); test[ext_len + 1] = '\0'; /* executable phars must contain ".phar" as a valid extension (phar://.pharmy/oops is invalid) */ /* (phar://hi/there/.phar/oops is also invalid) */ pos = strstr(test, ".phar"); if (pos && (*(pos - 1) != '/') && (pos += 5) && (*pos == '\0' || *pos == '/' || *pos == '.')) { return phar_analyze_path(fname, ext_str, ext_len, for_create TSRMLS_CC); } else { return FAILURE; } } /* data phars need only contain a single non-"." to be valid */ if (!executable) { pos = strstr(ext_str, ".phar"); if (!(pos && (*(pos - 1) != '/') && (pos += 5) && (*pos == '\0' || *pos == '/' || *pos == '.')) && *(ext_str + 1) != '.' && *(ext_str + 1) != '/' && *(ext_str + 1) != '\0') { return phar_analyze_path(fname, ext_str, ext_len, for_create TSRMLS_CC); } } else { if (*(ext_str + 1) != '.' && *(ext_str + 1) != '/' && *(ext_str + 1) != '\0') { return phar_analyze_path(fname, ext_str, ext_len, for_create TSRMLS_CC); } } return FAILURE; } /* }}} */ /* * if executable is 1, only returns SUCCESS if the extension is one of the tar/zip .phar extensions * if executable is 0, it returns SUCCESS only if the filename does *not* contain ".phar" anywhere, and treats * the first extension as the filename extension * * if an extension is found, it sets ext_str to the location of the file extension in filename, * and ext_len to the length of the extension. * for urls like "phar://alias/oops" it instead sets ext_len to -1 and returns FAILURE, which tells * the calling function to use "alias" as the phar alias * * the last parameter should be set to tell the thing to assume that filename is the full path, and only to check the * extension rules, not to iterate. */ int phar_detect_phar_fname_ext(const char *filename, int filename_len, const char **ext_str, int *ext_len, int executable, int for_create, int is_complete TSRMLS_DC) /* {{{ */ { const char *pos, *slash; *ext_str = NULL; *ext_len = 0; if (!filename_len || filename_len == 1) { return FAILURE; } phar_request_initialize(TSRMLS_C); /* first check for alias in first segment */ pos = memchr(filename, '/', filename_len); if (pos && pos != filename) { /* check for url like http:// or phar:// */ if (*(pos - 1) == ':' && (pos - filename) < filename_len - 1 && *(pos + 1) == '/') { *ext_len = -2; *ext_str = NULL; return FAILURE; } if (zend_hash_exists(&(PHAR_GLOBALS->phar_alias_map), (char *) filename, pos - filename)) { *ext_str = pos; *ext_len = -1; return FAILURE; } if (PHAR_G(manifest_cached) && zend_hash_exists(&cached_alias, (char *) filename, pos - filename)) { *ext_str = pos; *ext_len = -1; return FAILURE; } } if (zend_hash_num_elements(&(PHAR_GLOBALS->phar_fname_map)) || PHAR_G(manifest_cached)) { phar_archive_data **pphar; if (is_complete) { if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), (char *) filename, filename_len, (void **)&pphar)) { *ext_str = filename + (filename_len - (*pphar)->ext_len); woohoo: *ext_len = (*pphar)->ext_len; if (executable == 2) { return SUCCESS; } if (executable == 1 && !(*pphar)->is_data) { return SUCCESS; } if (!executable && (*pphar)->is_data) { return SUCCESS; } return FAILURE; } if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, (char *) filename, filename_len, (void **)&pphar)) { *ext_str = filename + (filename_len - (*pphar)->ext_len); goto woohoo; } } else { phar_zstr key; char *str_key; uint keylen; ulong unused; zend_hash_internal_pointer_reset(&(PHAR_GLOBALS->phar_fname_map)); while (FAILURE != zend_hash_has_more_elements(&(PHAR_GLOBALS->phar_fname_map))) { if (HASH_KEY_NON_EXISTANT == zend_hash_get_current_key_ex(&(PHAR_GLOBALS->phar_fname_map), &key, &keylen, &unused, 0, NULL)) { break; } PHAR_STR(key, str_key); if (keylen > (uint) filename_len) { zend_hash_move_forward(&(PHAR_GLOBALS->phar_fname_map)); PHAR_STR_FREE(str_key); continue; } if (!memcmp(filename, str_key, keylen) && ((uint)filename_len == keylen || filename[keylen] == '/' || filename[keylen] == '\0')) { PHAR_STR_FREE(str_key); if (FAILURE == zend_hash_get_current_data(&(PHAR_GLOBALS->phar_fname_map), (void **) &pphar)) { break; } *ext_str = filename + (keylen - (*pphar)->ext_len); goto woohoo; } PHAR_STR_FREE(str_key); zend_hash_move_forward(&(PHAR_GLOBALS->phar_fname_map)); } if (PHAR_G(manifest_cached)) { zend_hash_internal_pointer_reset(&cached_phars); while (FAILURE != zend_hash_has_more_elements(&cached_phars)) { if (HASH_KEY_NON_EXISTANT == zend_hash_get_current_key_ex(&cached_phars, &key, &keylen, &unused, 0, NULL)) { break; } PHAR_STR(key, str_key); if (keylen > (uint) filename_len) { zend_hash_move_forward(&cached_phars); PHAR_STR_FREE(str_key); continue; } if (!memcmp(filename, str_key, keylen) && ((uint)filename_len == keylen || filename[keylen] == '/' || filename[keylen] == '\0')) { PHAR_STR_FREE(str_key); if (FAILURE == zend_hash_get_current_data(&cached_phars, (void **) &pphar)) { break; } *ext_str = filename + (keylen - (*pphar)->ext_len); goto woohoo; } PHAR_STR_FREE(str_key); zend_hash_move_forward(&cached_phars); } } } } pos = memchr(filename + 1, '.', filename_len); next_extension: if (!pos) { return FAILURE; } while (pos != filename && (*(pos - 1) == '/' || *(pos - 1) == '\0')) { pos = memchr(pos + 1, '.', filename_len - (pos - filename) + 1); if (!pos) { return FAILURE; } } slash = memchr(pos, '/', filename_len - (pos - filename)); if (!slash) { /* this is a url like "phar://blah.phar" with no directory */ *ext_str = pos; *ext_len = strlen(pos); /* file extension must contain "phar" */ switch (phar_check_str(filename, *ext_str, *ext_len, executable, for_create TSRMLS_CC)) { case SUCCESS: return SUCCESS; case FAILURE: /* we are at the end of the string, so we fail */ return FAILURE; } } /* we've found an extension that ends at a directory separator */ *ext_str = pos; *ext_len = slash - pos; switch (phar_check_str(filename, *ext_str, *ext_len, executable, for_create TSRMLS_CC)) { case SUCCESS: return SUCCESS; case FAILURE: /* look for more extensions */ pos = strchr(pos + 1, '.'); if (pos) { *ext_str = NULL; *ext_len = 0; } goto next_extension; } return FAILURE; } /* }}} */ static int php_check_dots(const char *element, int n) /* {{{ */ { for(n--; n >= 0; --n) { if (element[n] != '.') { return 1; } } return 0; } /* }}} */ #define IS_DIRECTORY_UP(element, len) \ (len >= 2 && !php_check_dots(element, len)) #define IS_DIRECTORY_CURRENT(element, len) \ (len == 1 && element[0] == '.') #define IS_BACKSLASH(c) ((c) == '/') #ifdef COMPILE_DL_PHAR /* stupid-ass non-extern declaration in tsrm_strtok.h breaks dumbass MS compiler */ static inline int in_character_class(char ch, const char *delim) /* {{{ */ { while (*delim) { if (*delim == ch) { return 1; } ++delim; } return 0; } /* }}} */ char *tsrm_strtok_r(char *s, const char *delim, char **last) /* {{{ */ { char *token; if (s == NULL) { s = *last; } while (*s && in_character_class(*s, delim)) { ++s; } if (!*s) { return NULL; } token = s; while (*s && !in_character_class(*s, delim)) { ++s; } if (!*s) { *last = s; } else { *s = '\0'; *last = s + 1; } return token; } /* }}} */ #endif /** * Remove .. and . references within a phar filename */ char *phar_fix_filepath(char *path, int *new_len, int use_cwd TSRMLS_DC) /* {{{ */ { char newpath[MAXPATHLEN]; int newpath_len; char *ptr; char *tok; int ptr_length, path_length = *new_len; if (PHAR_G(cwd_len) && use_cwd && path_length > 2 && path[0] == '.' && path[1] == '/') { newpath_len = PHAR_G(cwd_len); memcpy(newpath, PHAR_G(cwd), newpath_len); } else { newpath[0] = '/'; newpath_len = 1; } ptr = path; if (*ptr == '/') { ++ptr; } tok = ptr; do { ptr = memchr(ptr, '/', path_length - (ptr - path)); } while (ptr && ptr - tok == 0 && *ptr == '/' && ++ptr && ++tok); if (!ptr && (path_length - (tok - path))) { switch (path_length - (tok - path)) { case 1: if (*tok == '.') { efree(path); *new_len = 1; return estrndup("/", 1); } break; case 2: if (tok[0] == '.' && tok[1] == '.') { efree(path); *new_len = 1; return estrndup("/", 1); } } return path; } while (ptr) { ptr_length = ptr - tok; last_time: if (IS_DIRECTORY_UP(tok, ptr_length)) { #define PREVIOUS newpath[newpath_len - 1] while (newpath_len > 1 && !IS_BACKSLASH(PREVIOUS)) { newpath_len--; } if (newpath[0] != '/') { newpath[newpath_len] = '\0'; } else if (newpath_len > 1) { --newpath_len; } } else if (!IS_DIRECTORY_CURRENT(tok, ptr_length)) { if (newpath_len > 1) { newpath[newpath_len++] = '/'; memcpy(newpath + newpath_len, tok, ptr_length+1); } else { memcpy(newpath + newpath_len, tok, ptr_length+1); } newpath_len += ptr_length; } if (ptr == path + path_length) { break; } tok = ++ptr; do { ptr = memchr(ptr, '/', path_length - (ptr - path)); } while (ptr && ptr - tok == 0 && *ptr == '/' && ++ptr && ++tok); if (!ptr && (path_length - (tok - path))) { ptr_length = path_length - (tok - path); ptr = path + path_length; goto last_time; } } efree(path); *new_len = newpath_len; return estrndup(newpath, newpath_len); } /* }}} */ /** * Process a phar stream name, ensuring we can handle any of: * * - whatever.phar * - whatever.phar.gz * - whatever.phar.bz2 * - whatever.phar.php * * Optionally the name might start with 'phar://' * * This is used by phar_parse_url() */ int phar_split_fname(char *filename, int filename_len, char **arch, int *arch_len, char **entry, int *entry_len, int executable, int for_create TSRMLS_DC) /* {{{ */ { const char *ext_str; #ifdef PHP_WIN32 char *save; #endif int ext_len, free_filename = 0; if (!strncasecmp(filename, "phar://", 7)) { filename += 7; filename_len -= 7; } ext_len = 0; #ifdef PHP_WIN32 free_filename = 1; save = filename; filename = estrndup(filename, filename_len); phar_unixify_path_separators(filename, filename_len); #endif if (phar_detect_phar_fname_ext(filename, filename_len, &ext_str, &ext_len, executable, for_create, 0 TSRMLS_CC) == FAILURE) { if (ext_len != -1) { if (!ext_str) { /* no / detected, restore arch for error message */ #ifdef PHP_WIN32 *arch = save; #else *arch = filename; #endif } if (free_filename) { efree(filename); } return FAILURE; } ext_len = 0; /* no extension detected - instead we are dealing with an alias */ } *arch_len = ext_str - filename + ext_len; *arch = estrndup(filename, *arch_len); if (ext_str[ext_len]) { *entry_len = filename_len - *arch_len; *entry = estrndup(ext_str+ext_len, *entry_len); #ifdef PHP_WIN32 phar_unixify_path_separators(*entry, *entry_len); #endif *entry = phar_fix_filepath(*entry, entry_len, 0 TSRMLS_CC); } else { *entry_len = 1; *entry = estrndup("/", 1); } if (free_filename) { efree(filename); } return SUCCESS; } /* }}} */ /** * Invoked when a user calls Phar::mapPhar() from within an executing .phar * to set up its manifest directly */ int phar_open_executed_filename(char *alias, int alias_len, char **error TSRMLS_DC) /* {{{ */ { char *fname; zval *halt_constant; php_stream *fp; int fname_len; char *actual = NULL; int ret; if (error) { *error = NULL; } fname = (char*)zend_get_executed_filename(TSRMLS_C); fname_len = strlen(fname); if (phar_open_parsed_phar(fname, fname_len, alias, alias_len, 0, REPORT_ERRORS, NULL, 0 TSRMLS_CC) == SUCCESS) { return SUCCESS; } if (!strcmp(fname, "[no active file]")) { if (error) { spprintf(error, 0, "cannot initialize a phar outside of PHP execution"); } return FAILURE; } MAKE_STD_ZVAL(halt_constant); if (0 == zend_get_constant("__COMPILER_HALT_OFFSET__", 24, halt_constant TSRMLS_CC)) { FREE_ZVAL(halt_constant); if (error) { spprintf(error, 0, "__HALT_COMPILER(); must be declared in a phar"); } return FAILURE; } FREE_ZVAL(halt_constant); #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { return FAILURE; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { return FAILURE; } fp = php_stream_open_wrapper(fname, "rb", IGNORE_URL|STREAM_MUST_SEEK|REPORT_ERRORS, &actual); if (!fp) { if (error) { spprintf(error, 0, "unable to open phar for reading \"%s\"", fname); } if (actual) { efree(actual); } return FAILURE; } if (actual) { fname = actual; fname_len = strlen(actual); } ret = phar_open_from_fp(fp, fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, 0, error TSRMLS_CC); if (actual) { efree(actual); } return ret; } /* }}} */ /** * Validate the CRC32 of a file opened from within the phar */ int phar_postprocess_file(phar_entry_data *idata, php_uint32 crc32, char **error, int process_zip TSRMLS_DC) /* {{{ */ { php_uint32 crc = ~0; int len = idata->internal_file->uncompressed_filesize; php_stream *fp = idata->fp; phar_entry_info *entry = idata->internal_file; if (error) { *error = NULL; } if (entry->is_zip && process_zip > 0) { /* verify local file header */ phar_zip_file_header local; phar_zip_data_desc desc; if (SUCCESS != phar_open_archive_fp(idata->phar TSRMLS_CC)) { spprintf(error, 0, "phar error: unable to open zip-based phar archive \"%s\" to verify local file header for file \"%s\"", idata->phar->fname, entry->filename); return FAILURE; } php_stream_seek(phar_get_entrypfp(idata->internal_file TSRMLS_CC), entry->header_offset, SEEK_SET); if (sizeof(local) != php_stream_read(phar_get_entrypfp(idata->internal_file TSRMLS_CC), (char *) &local, sizeof(local))) { spprintf(error, 0, "phar error: internal corruption of zip-based phar \"%s\" (cannot read local file header for file \"%s\")", idata->phar->fname, entry->filename); return FAILURE; } /* check for data descriptor */ if (((PHAR_ZIP_16(local.flags)) & 0x8) == 0x8) { php_stream_seek(phar_get_entrypfp(idata->internal_file TSRMLS_CC), entry->header_offset + sizeof(local) + PHAR_ZIP_16(local.filename_len) + PHAR_ZIP_16(local.extra_len) + entry->compressed_filesize, SEEK_SET); if (sizeof(desc) != php_stream_read(phar_get_entrypfp(idata->internal_file TSRMLS_CC), (char *) &desc, sizeof(desc))) { spprintf(error, 0, "phar error: internal corruption of zip-based phar \"%s\" (cannot read local data descriptor for file \"%s\")", idata->phar->fname, entry->filename); return FAILURE; } if (desc.signature[0] == 'P' && desc.signature[1] == 'K') { memcpy(&(local.crc32), &(desc.crc32), 12); } else { /* old data descriptors have no signature */ memcpy(&(local.crc32), &desc, 12); } } /* verify local header */ if (entry->filename_len != PHAR_ZIP_16(local.filename_len) || entry->crc32 != PHAR_ZIP_32(local.crc32) || entry->uncompressed_filesize != PHAR_ZIP_32(local.uncompsize) || entry->compressed_filesize != PHAR_ZIP_32(local.compsize)) { spprintf(error, 0, "phar error: internal corruption of zip-based phar \"%s\" (local header of file \"%s\" does not match central directory)", idata->phar->fname, entry->filename); return FAILURE; } /* construct actual offset to file start - local extra_len can be different from central extra_len */ entry->offset = entry->offset_abs = sizeof(local) + entry->header_offset + PHAR_ZIP_16(local.filename_len) + PHAR_ZIP_16(local.extra_len); if (idata->zero && idata->zero != entry->offset_abs) { idata->zero = entry->offset_abs; } } if (process_zip == 1) { return SUCCESS; } php_stream_seek(fp, idata->zero, SEEK_SET); while (len--) { CRC32(crc, php_stream_getc(fp)); } php_stream_seek(fp, idata->zero, SEEK_SET); if (~crc == crc32) { entry->is_crc_checked = 1; return SUCCESS; } else { spprintf(error, 0, "phar error: internal corruption of phar \"%s\" (crc32 mismatch on file \"%s\")", idata->phar->fname, entry->filename); return FAILURE; } } /* }}} */ static inline void phar_set_32(char *buffer, int var) /* {{{ */ { #ifdef WORDS_BIGENDIAN *((buffer) + 3) = (unsigned char) (((var) >> 24) & 0xFF); *((buffer) + 2) = (unsigned char) (((var) >> 16) & 0xFF); *((buffer) + 1) = (unsigned char) (((var) >> 8) & 0xFF); *((buffer) + 0) = (unsigned char) ((var) & 0xFF); #else memcpy(buffer, &var, sizeof(var)); #endif } /* }}} */ static int phar_flush_clean_deleted_apply(void *data TSRMLS_DC) /* {{{ */ { phar_entry_info *entry = (phar_entry_info *)data; if (entry->fp_refcount <= 0 && entry->is_deleted) { return ZEND_HASH_APPLY_REMOVE; } else { return ZEND_HASH_APPLY_KEEP; } } /* }}} */ #include "stub.h" char *phar_create_default_stub(const char *index_php, const char *web_index, size_t *len, char **error TSRMLS_DC) /* {{{ */ { char *stub = NULL; int index_len, web_len; size_t dummy; if (!len) { len = &dummy; } if (error) { *error = NULL; } if (!index_php) { index_php = "index.php"; } if (!web_index) { web_index = "index.php"; } index_len = strlen(index_php); web_len = strlen(web_index); if (index_len > 400) { /* ridiculous size not allowed for index.php startup filename */ if (error) { spprintf(error, 0, "Illegal filename passed in for stub creation, was %d characters long, and only 400 or less is allowed", index_len); return NULL; } } if (web_len > 400) { /* ridiculous size not allowed for index.php startup filename */ if (error) { spprintf(error, 0, "Illegal web filename passed in for stub creation, was %d characters long, and only 400 or less is allowed", web_len); return NULL; } } phar_get_stub(index_php, web_index, len, &stub, index_len+1, web_len+1 TSRMLS_CC); return stub; } /* }}} */ /** * Save phar contents to disk * * user_stub contains either a string, or a resource pointer, if len is a negative length. * user_stub and len should be both 0 if the default or existing stub should be used */ int phar_flush(phar_archive_data *phar, char *user_stub, long len, int convert, char **error TSRMLS_DC) /* {{{ */ { char halt_stub[] = "__HALT_COMPILER();"; char *newstub, *tmp; phar_entry_info *entry, *newentry; int halt_offset, restore_alias_len, global_flags = 0, closeoldfile; char *pos, has_dirs = 0; char manifest[18], entry_buffer[24]; off_t manifest_ftell; long offset; size_t wrote; php_uint32 manifest_len, mytime, loc, new_manifest_count; php_uint32 newcrc32; php_stream *file, *oldfile, *newfile, *stubfile; php_stream_filter *filter; php_serialize_data_t metadata_hash; smart_str main_metadata_str = {0}; int free_user_stub, free_fp = 1, free_ufp = 1; if (phar->is_persistent) { if (error) { spprintf(error, 0, "internal error: attempt to flush cached zip-based phar \"%s\"", phar->fname); } return EOF; } if (error) { *error = NULL; } if (!zend_hash_num_elements(&phar->manifest) && !user_stub) { return EOF; } zend_hash_clean(&phar->virtual_dirs); if (phar->is_zip) { return phar_zip_flush(phar, user_stub, len, convert, error TSRMLS_CC); } if (phar->is_tar) { return phar_tar_flush(phar, user_stub, len, convert, error TSRMLS_CC); } if (PHAR_G(readonly)) { return EOF; } if (phar->fp && !phar->is_brandnew) { oldfile = phar->fp; closeoldfile = 0; php_stream_rewind(oldfile); } else { oldfile = php_stream_open_wrapper(phar->fname, "rb", 0, NULL); closeoldfile = oldfile != NULL; } newfile = php_stream_fopen_tmpfile(); if (!newfile) { if (error) { spprintf(error, 0, "unable to create temporary file"); } if (closeoldfile) { php_stream_close(oldfile); } return EOF; } if (user_stub) { if (len < 0) { /* resource passed in */ if (!(php_stream_from_zval_no_verify(stubfile, (zval **)user_stub))) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to access resource to copy stub to new phar \"%s\"", phar->fname); } return EOF; } if (len == -1) { len = PHP_STREAM_COPY_ALL; } else { len = -len; } user_stub = 0; #if PHP_MAJOR_VERSION >= 6 if (!(len = php_stream_copy_to_mem(stubfile, (void **) &user_stub, len, 0)) || !user_stub) { #else if (!(len = php_stream_copy_to_mem(stubfile, &user_stub, len, 0)) || !user_stub) { #endif if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to read resource to copy stub to new phar \"%s\"", phar->fname); } return EOF; } free_user_stub = 1; } else { free_user_stub = 0; } tmp = estrndup(user_stub, len); if ((pos = php_stristr(tmp, halt_stub, len, sizeof(halt_stub) - 1)) == NULL) { efree(tmp); if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "illegal stub for phar \"%s\"", phar->fname); } if (free_user_stub) { efree(user_stub); } return EOF; } pos = user_stub + (pos - tmp); efree(tmp); len = pos - user_stub + 18; if ((size_t)len != php_stream_write(newfile, user_stub, len) || 5 != php_stream_write(newfile, " ?>\r\n", 5)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to create stub from string in new phar \"%s\"", phar->fname); } if (free_user_stub) { efree(user_stub); } return EOF; } phar->halt_offset = len + 5; if (free_user_stub) { efree(user_stub); } } else { size_t written; if (!user_stub && phar->halt_offset && oldfile && !phar->is_brandnew) { phar_stream_copy_to_stream(oldfile, newfile, phar->halt_offset, &written); newstub = NULL; } else { /* this is either a brand new phar or a default stub overwrite */ newstub = phar_create_default_stub(NULL, NULL, &(phar->halt_offset), NULL TSRMLS_CC); written = php_stream_write(newfile, newstub, phar->halt_offset); } if (phar->halt_offset != written) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { if (newstub) { spprintf(error, 0, "unable to create stub in new phar \"%s\"", phar->fname); } else { spprintf(error, 0, "unable to copy stub of old phar to new phar \"%s\"", phar->fname); } } if (newstub) { efree(newstub); } return EOF; } if (newstub) { efree(newstub); } } manifest_ftell = php_stream_tell(newfile); halt_offset = manifest_ftell; /* Check whether we can get rid of some of the deleted entries which are * unused. However some might still be in use so even after this clean-up * we need to skip entries marked is_deleted. */ zend_hash_apply(&phar->manifest, phar_flush_clean_deleted_apply TSRMLS_CC); /* compress as necessary, calculate crcs, serialize meta-data, manifest size, and file sizes */ main_metadata_str.c = 0; if (phar->metadata) { PHP_VAR_SERIALIZE_INIT(metadata_hash); php_var_serialize(&main_metadata_str, &phar->metadata, &metadata_hash TSRMLS_CC); PHP_VAR_SERIALIZE_DESTROY(metadata_hash); } else { main_metadata_str.len = 0; } new_manifest_count = 0; offset = 0; for (zend_hash_internal_pointer_reset(&phar->manifest); zend_hash_has_more_elements(&phar->manifest) == SUCCESS; zend_hash_move_forward(&phar->manifest)) { if (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) { continue; } if (entry->cfp) { /* did we forget to get rid of cfp last time? */ php_stream_close(entry->cfp); entry->cfp = 0; } if (entry->is_deleted || entry->is_mounted) { /* remove this from the new phar */ continue; } if (!entry->is_modified && entry->fp_refcount) { /* open file pointers refer to this fp, do not free the stream */ switch (entry->fp_type) { case PHAR_FP: free_fp = 0; break; case PHAR_UFP: free_ufp = 0; default: break; } } /* after excluding deleted files, calculate manifest size in bytes and number of entries */ ++new_manifest_count; phar_add_virtual_dirs(phar, entry->filename, entry->filename_len TSRMLS_CC); if (entry->is_dir) { /* we use this to calculate API version, 1.1.1 is used for phars with directories */ has_dirs = 1; } if (entry->metadata) { if (entry->metadata_str.c) { smart_str_free(&entry->metadata_str); } entry->metadata_str.c = 0; entry->metadata_str.len = 0; PHP_VAR_SERIALIZE_INIT(metadata_hash); php_var_serialize(&entry->metadata_str, &entry->metadata, &metadata_hash TSRMLS_CC); PHP_VAR_SERIALIZE_DESTROY(metadata_hash); } else { if (entry->metadata_str.c) { smart_str_free(&entry->metadata_str); } entry->metadata_str.c = 0; entry->metadata_str.len = 0; } /* 32 bits for filename length, length of filename, manifest + metadata, and add 1 for trailing / if a directory */ offset += 4 + entry->filename_len + sizeof(entry_buffer) + entry->metadata_str.len + (entry->is_dir ? 1 : 0); /* compress and rehash as necessary */ if ((oldfile && !entry->is_modified) || entry->is_dir) { if (entry->fp_type == PHAR_UFP) { /* reset so we can copy the compressed data over */ entry->fp_type = PHAR_FP; } continue; } if (!phar_get_efp(entry, 0 TSRMLS_CC)) { /* re-open internal file pointer just-in-time */ newentry = phar_open_jit(phar, entry, error TSRMLS_CC); if (!newentry) { /* major problem re-opening, so we ignore this file and the error */ efree(*error); *error = NULL; continue; } entry = newentry; } file = phar_get_efp(entry, 0 TSRMLS_CC); if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 1 TSRMLS_CC)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } newcrc32 = ~0; mytime = entry->uncompressed_filesize; for (loc = 0;loc < mytime; ++loc) { CRC32(newcrc32, php_stream_getc(file)); } entry->crc32 = ~newcrc32; entry->is_crc_checked = 1; if (!(entry->flags & PHAR_ENT_COMPRESSION_MASK)) { /* not compressed */ entry->compressed_filesize = entry->uncompressed_filesize; continue; } filter = php_stream_filter_create(phar_compress_filter(entry, 0), NULL, 0 TSRMLS_CC); if (!filter) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (entry->flags & PHAR_ENT_COMPRESSED_GZ) { if (error) { spprintf(error, 0, "unable to gzip compress file \"%s\" to new phar \"%s\"", entry->filename, phar->fname); } } else { if (error) { spprintf(error, 0, "unable to bzip2 compress file \"%s\" to new phar \"%s\"", entry->filename, phar->fname); } } return EOF; } /* create new file that holds the compressed version */ /* work around inability to specify freedom in write and strictness in read count */ entry->cfp = php_stream_fopen_tmpfile(); if (!entry->cfp) { if (error) { spprintf(error, 0, "unable to create temporary file"); } if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); return EOF; } php_stream_flush(file); if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 0 TSRMLS_CC)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } php_stream_filter_append((&entry->cfp->writefilters), filter); if (SUCCESS != phar_stream_copy_to_stream(file, entry->cfp, entry->uncompressed_filesize, NULL)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to copy compressed file contents of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } php_stream_filter_flush(filter, 1); php_stream_flush(entry->cfp); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_seek(entry->cfp, 0, SEEK_END); entry->compressed_filesize = (php_uint32) php_stream_tell(entry->cfp); /* generate crc on compressed file */ php_stream_rewind(entry->cfp); entry->old_flags = entry->flags; entry->is_modified = 1; global_flags |= (entry->flags & PHAR_ENT_COMPRESSION_MASK); } global_flags |= PHAR_HDR_SIGNATURE; /* write out manifest pre-header */ /* 4: manifest length * 4: manifest entry count * 2: phar version * 4: phar global flags * 4: alias length * ?: the alias itself * 4: phar metadata length * ?: phar metadata */ restore_alias_len = phar->alias_len; if (phar->is_temporary_alias) { phar->alias_len = 0; } manifest_len = offset + phar->alias_len + sizeof(manifest) + main_metadata_str.len; phar_set_32(manifest, manifest_len); phar_set_32(manifest+4, new_manifest_count); if (has_dirs) { *(manifest + 8) = (unsigned char) (((PHAR_API_VERSION) >> 8) & 0xFF); *(manifest + 9) = (unsigned char) (((PHAR_API_VERSION) & 0xF0)); } else { *(manifest + 8) = (unsigned char) (((PHAR_API_VERSION_NODIR) >> 8) & 0xFF); *(manifest + 9) = (unsigned char) (((PHAR_API_VERSION_NODIR) & 0xF0)); } phar_set_32(manifest+10, global_flags); phar_set_32(manifest+14, phar->alias_len); /* write the manifest header */ if (sizeof(manifest) != php_stream_write(newfile, manifest, sizeof(manifest)) || (size_t)phar->alias_len != php_stream_write(newfile, phar->alias, phar->alias_len)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); phar->alias_len = restore_alias_len; if (error) { spprintf(error, 0, "unable to write manifest header of new phar \"%s\"", phar->fname); } return EOF; } phar->alias_len = restore_alias_len; phar_set_32(manifest, main_metadata_str.len); if (4 != php_stream_write(newfile, manifest, 4) || (main_metadata_str.len && main_metadata_str.len != php_stream_write(newfile, main_metadata_str.c, main_metadata_str.len))) { smart_str_free(&main_metadata_str); if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); phar->alias_len = restore_alias_len; if (error) { spprintf(error, 0, "unable to write manifest meta-data of new phar \"%s\"", phar->fname); } return EOF; } smart_str_free(&main_metadata_str); /* re-calculate the manifest location to simplify later code */ manifest_ftell = php_stream_tell(newfile); /* now write the manifest */ for (zend_hash_internal_pointer_reset(&phar->manifest); zend_hash_has_more_elements(&phar->manifest) == SUCCESS; zend_hash_move_forward(&phar->manifest)) { if (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) { continue; } if (entry->is_deleted || entry->is_mounted) { /* remove this from the new phar if deleted, ignore if mounted */ continue; } if (entry->is_dir) { /* add 1 for trailing slash */ phar_set_32(entry_buffer, entry->filename_len + 1); } else { phar_set_32(entry_buffer, entry->filename_len); } if (4 != php_stream_write(newfile, entry_buffer, 4) || entry->filename_len != php_stream_write(newfile, entry->filename, entry->filename_len) || (entry->is_dir && 1 != php_stream_write(newfile, "/", 1))) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { if (entry->is_dir) { spprintf(error, 0, "unable to write filename of directory \"%s\" to manifest of new phar \"%s\"", entry->filename, phar->fname); } else { spprintf(error, 0, "unable to write filename of file \"%s\" to manifest of new phar \"%s\"", entry->filename, phar->fname); } } return EOF; } /* set the manifest meta-data: 4: uncompressed filesize 4: creation timestamp 4: compressed filesize 4: crc32 4: flags 4: metadata-len +: metadata */ mytime = time(NULL); phar_set_32(entry_buffer, entry->uncompressed_filesize); phar_set_32(entry_buffer+4, mytime); phar_set_32(entry_buffer+8, entry->compressed_filesize); phar_set_32(entry_buffer+12, entry->crc32); phar_set_32(entry_buffer+16, entry->flags); phar_set_32(entry_buffer+20, entry->metadata_str.len); if (sizeof(entry_buffer) != php_stream_write(newfile, entry_buffer, sizeof(entry_buffer)) || entry->metadata_str.len != php_stream_write(newfile, entry->metadata_str.c, entry->metadata_str.len)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to write temporary manifest of file \"%s\" to manifest of new phar \"%s\"", entry->filename, phar->fname); } return EOF; } } /* now copy the actual file data to the new phar */ offset = php_stream_tell(newfile); for (zend_hash_internal_pointer_reset(&phar->manifest); zend_hash_has_more_elements(&phar->manifest) == SUCCESS; zend_hash_move_forward(&phar->manifest)) { if (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) { continue; } if (entry->is_deleted || entry->is_dir || entry->is_mounted) { continue; } if (entry->cfp) { file = entry->cfp; php_stream_rewind(file); } else { file = phar_get_efp(entry, 0 TSRMLS_CC); if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 0 TSRMLS_CC)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } } if (!file) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } /* this will have changed for all files that have either changed compression or been modified */ entry->offset = entry->offset_abs = offset; offset += entry->compressed_filesize; if (phar_stream_copy_to_stream(file, newfile, entry->compressed_filesize, &wrote) == FAILURE) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to write contents of file \"%s\" to new phar \"%s\"", entry->filename, phar->fname); } return EOF; } entry->is_modified = 0; if (entry->cfp) { php_stream_close(entry->cfp); entry->cfp = NULL; } if (entry->fp_type == PHAR_MOD) { /* this fp is in use by a phar_entry_data returned by phar_get_entry_data, it will be closed when the phar_entry_data is phar_entry_delref'ed */ if (entry->fp_refcount == 0 && entry->fp != phar->fp && entry->fp != phar->ufp) { php_stream_close(entry->fp); } entry->fp = NULL; entry->fp_type = PHAR_FP; } else if (entry->fp_type == PHAR_UFP) { entry->fp_type = PHAR_FP; } } /* append signature */ if (global_flags & PHAR_HDR_SIGNATURE) { char sig_buf[4]; php_stream_rewind(newfile); if (phar->signature) { efree(phar->signature); phar->signature = NULL; } switch(phar->sig_flags) { #ifndef PHAR_HASH_OK case PHAR_SIG_SHA512: case PHAR_SIG_SHA256: if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to write contents of file \"%s\" to new phar \"%s\" with requested hash type", entry->filename, phar->fname); } return EOF; #endif default: { char *digest = NULL; int digest_len; if (FAILURE == phar_create_signature(phar, newfile, &digest, &digest_len, error TSRMLS_CC)) { if (error) { char *save = *error; spprintf(error, 0, "phar error: unable to write signature: %s", save); efree(save); } if (digest) { efree(digest); } if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); return EOF; } php_stream_write(newfile, digest, digest_len); efree(digest); if (phar->sig_flags == PHAR_SIG_OPENSSL) { phar_set_32(sig_buf, digest_len); php_stream_write(newfile, sig_buf, 4); } break; } } phar_set_32(sig_buf, phar->sig_flags); php_stream_write(newfile, sig_buf, 4); php_stream_write(newfile, "GBMB", 4); } /* finally, close the temp file, rename the original phar, move the temp to the old phar, unlink the old phar, and reload it into memory */ if (phar->fp && free_fp) { php_stream_close(phar->fp); } if (phar->ufp) { if (free_ufp) { php_stream_close(phar->ufp); } phar->ufp = NULL; } if (closeoldfile) { php_stream_close(oldfile); } phar->internal_file_start = halt_offset + manifest_len + 4; phar->halt_offset = halt_offset; phar->is_brandnew = 0; php_stream_rewind(newfile); if (phar->donotflush) { /* deferred flush */ phar->fp = newfile; } else { phar->fp = php_stream_open_wrapper(phar->fname, "w+b", IGNORE_URL|STREAM_MUST_SEEK|REPORT_ERRORS, NULL); if (!phar->fp) { phar->fp = newfile; if (error) { spprintf(error, 4096, "unable to open new phar \"%s\" for writing", phar->fname); } return EOF; } if (phar->flags & PHAR_FILE_COMPRESSED_GZ) { /* to properly compress, we have to tell zlib to add a zlib header */ zval filterparams; array_init(&filterparams); add_assoc_long(&filterparams, "window", MAX_WBITS+16); filter = php_stream_filter_create("zlib.deflate", &filterparams, php_stream_is_persistent(phar->fp) TSRMLS_CC); zval_dtor(&filterparams); if (!filter) { if (error) { spprintf(error, 4096, "unable to compress all contents of phar \"%s\" using zlib, PHP versions older than 5.2.6 have a buggy zlib", phar->fname); } return EOF; } php_stream_filter_append(&phar->fp->writefilters, filter); phar_stream_copy_to_stream(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL); php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(phar->fp); /* use the temp stream as our base */ phar->fp = newfile; } else if (phar->flags & PHAR_FILE_COMPRESSED_BZ2) { filter = php_stream_filter_create("bzip2.compress", NULL, php_stream_is_persistent(phar->fp) TSRMLS_CC); php_stream_filter_append(&phar->fp->writefilters, filter); phar_stream_copy_to_stream(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL); php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(phar->fp); /* use the temp stream as our base */ phar->fp = newfile; } else { phar_stream_copy_to_stream(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL); /* we could also reopen the file in "rb" mode but there is no need for that */ php_stream_close(newfile); } } if (-1 == php_stream_seek(phar->fp, phar->halt_offset, SEEK_SET)) { if (error) { spprintf(error, 0, "unable to seek to __HALT_COMPILER(); in new phar \"%s\"", phar->fname); } return EOF; } return EOF; } /* }}} */ #ifdef COMPILE_DL_PHAR ZEND_GET_MODULE(phar) #endif /* {{{ phar_functions[] * * Every user visible function must have an entry in phar_functions[]. */ zend_function_entry phar_functions[] = { PHP_FE_END }; /* }}}*/ static size_t phar_zend_stream_reader(void *handle, char *buf, size_t len TSRMLS_DC) /* {{{ */ { return php_stream_read(phar_get_pharfp((phar_archive_data*)handle TSRMLS_CC), buf, len); } /* }}} */ #if PHP_VERSION_ID >= 50300 static size_t phar_zend_stream_fsizer(void *handle TSRMLS_DC) /* {{{ */ { return ((phar_archive_data*)handle)->halt_offset + 32; } /* }}} */ #else /* PHP_VERSION_ID */ static long phar_stream_fteller_for_zend(void *handle TSRMLS_DC) /* {{{ */ { return (long)php_stream_tell(phar_get_pharfp((phar_archive_data*)handle TSRMLS_CC)); } /* }}} */ #endif zend_op_array *(*phar_orig_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); #if PHP_VERSION_ID >= 50300 #define phar_orig_zend_open zend_stream_open_function static char *phar_resolve_path(const char *filename, int filename_len TSRMLS_DC) { return phar_find_in_include_path((char *) filename, filename_len, NULL TSRMLS_CC); } #else int (*phar_orig_zend_open)(const char *filename, zend_file_handle *handle TSRMLS_DC); #endif static zend_op_array *phar_compile_file(zend_file_handle *file_handle, int type TSRMLS_DC) /* {{{ */ { zend_op_array *res; char *name = NULL; int failed; phar_archive_data *phar; if (!file_handle || !file_handle->filename) { return phar_orig_compile_file(file_handle, type TSRMLS_CC); } if (strstr(file_handle->filename, ".phar") && !strstr(file_handle->filename, "://")) { if (SUCCESS == phar_open_from_filename((char*)file_handle->filename, strlen(file_handle->filename), NULL, 0, 0, &phar, NULL TSRMLS_CC)) { if (phar->is_zip || phar->is_tar) { zend_file_handle f = *file_handle; /* zip or tar-based phar */ spprintf(&name, 4096, "phar://%s/%s", file_handle->filename, ".phar/stub.php"); if (SUCCESS == phar_orig_zend_open((const char *)name, file_handle TSRMLS_CC)) { efree(name); name = NULL; file_handle->filename = f.filename; if (file_handle->opened_path) { efree(file_handle->opened_path); } file_handle->opened_path = f.opened_path; file_handle->free_filename = f.free_filename; } else { *file_handle = f; } } else if (phar->flags & PHAR_FILE_COMPRESSION_MASK) { /* compressed phar */ #if PHP_VERSION_ID >= 50300 file_handle->type = ZEND_HANDLE_STREAM; /* we do our own reading directly from the phar, don't change the next line */ file_handle->handle.stream.handle = phar; file_handle->handle.stream.reader = phar_zend_stream_reader; file_handle->handle.stream.closer = NULL; file_handle->handle.stream.fsizer = phar_zend_stream_fsizer; file_handle->handle.stream.isatty = 0; phar->is_persistent ? php_stream_rewind(PHAR_GLOBALS->cached_fp[phar->phar_pos].fp) : php_stream_rewind(phar->fp); memset(&file_handle->handle.stream.mmap, 0, sizeof(file_handle->handle.stream.mmap)); #else /* PHP_VERSION_ID */ file_handle->type = ZEND_HANDLE_STREAM; /* we do our own reading directly from the phar, don't change the next line */ file_handle->handle.stream.handle = phar; file_handle->handle.stream.reader = phar_zend_stream_reader; file_handle->handle.stream.closer = NULL; /* don't close - let phar handle this one */ file_handle->handle.stream.fteller = phar_stream_fteller_for_zend; file_handle->handle.stream.interactive = 0; phar->is_persistent ? php_stream_rewind(PHAR_GLOBALS->cached_fp[phar->phar_pos].fp) : php_stream_rewind(phar->fp); #endif } } } zend_try { failed = 0; res = phar_orig_compile_file(file_handle, type TSRMLS_CC); } zend_catch { failed = 1; res = NULL; } zend_end_try(); if (name) { efree(name); } if (failed) { zend_bailout(); } return res; } /* }}} */ #if PHP_VERSION_ID < 50300 int phar_zend_open(const char *filename, zend_file_handle *handle TSRMLS_DC) /* {{{ */ { char *arch, *entry; int arch_len, entry_len; /* this code is obsoleted in php 5.3 */ entry = (char *) filename; if (!IS_ABSOLUTE_PATH(entry, strlen(entry)) && !strstr(entry, "://")) { phar_archive_data **pphar = NULL; char *fname; int fname_len; fname = (char*)zend_get_executed_filename(TSRMLS_C); fname_len = strlen(fname); if (fname_len > 7 && !strncasecmp(fname, "phar://", 7)) { if (SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 1, 0 TSRMLS_CC)) { zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), arch, arch_len, (void **) &pphar); if (!pphar && PHAR_G(manifest_cached)) { zend_hash_find(&cached_phars, arch, arch_len, (void **) &pphar); } efree(arch); efree(entry); } } /* retrieving an include within the current directory, so use this if possible */ if (!(entry = phar_find_in_include_path((char *) filename, strlen(filename), NULL TSRMLS_CC))) { /* this file is not in the phar, use the original path */ goto skip_phar; } if (SUCCESS == phar_orig_zend_open(entry, handle TSRMLS_CC)) { if (!handle->opened_path) { handle->opened_path = entry; } if (entry != filename) { handle->free_filename = 1; } return SUCCESS; } if (entry != filename) { efree(entry); } return FAILURE; } skip_phar: return phar_orig_zend_open(filename, handle TSRMLS_CC); } /* }}} */ #endif typedef zend_op_array* (zend_compile_t)(zend_file_handle*, int TSRMLS_DC); typedef zend_compile_t* (compile_hook)(zend_compile_t *ptr); PHP_GINIT_FUNCTION(phar) /* {{{ */ { phar_mime_type mime; memset(phar_globals, 0, sizeof(zend_phar_globals)); phar_globals->readonly = 1; zend_hash_init(&phar_globals->mime_types, 0, NULL, NULL, 1); #define PHAR_SET_MIME(mimetype, ret, fileext) \ mime.mime = mimetype; \ mime.len = sizeof((mimetype))+1; \ mime.type = ret; \ zend_hash_add(&phar_globals->mime_types, fileext, sizeof(fileext)-1, (void *)&mime, sizeof(phar_mime_type), NULL); \ PHAR_SET_MIME("text/html", PHAR_MIME_PHPS, "phps") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "c") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "cc") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "cpp") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "c++") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "dtd") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "h") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "log") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "rng") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "txt") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "xsd") PHAR_SET_MIME("", PHAR_MIME_PHP, "php") PHAR_SET_MIME("", PHAR_MIME_PHP, "inc") PHAR_SET_MIME("video/avi", PHAR_MIME_OTHER, "avi") PHAR_SET_MIME("image/bmp", PHAR_MIME_OTHER, "bmp") PHAR_SET_MIME("text/css", PHAR_MIME_OTHER, "css") PHAR_SET_MIME("image/gif", PHAR_MIME_OTHER, "gif") PHAR_SET_MIME("text/html", PHAR_MIME_OTHER, "htm") PHAR_SET_MIME("text/html", PHAR_MIME_OTHER, "html") PHAR_SET_MIME("text/html", PHAR_MIME_OTHER, "htmls") PHAR_SET_MIME("image/x-ico", PHAR_MIME_OTHER, "ico") PHAR_SET_MIME("image/jpeg", PHAR_MIME_OTHER, "jpe") PHAR_SET_MIME("image/jpeg", PHAR_MIME_OTHER, "jpg") PHAR_SET_MIME("image/jpeg", PHAR_MIME_OTHER, "jpeg") PHAR_SET_MIME("application/x-javascript", PHAR_MIME_OTHER, "js") PHAR_SET_MIME("audio/midi", PHAR_MIME_OTHER, "midi") PHAR_SET_MIME("audio/midi", PHAR_MIME_OTHER, "mid") PHAR_SET_MIME("audio/mod", PHAR_MIME_OTHER, "mod") PHAR_SET_MIME("movie/quicktime", PHAR_MIME_OTHER, "mov") PHAR_SET_MIME("audio/mp3", PHAR_MIME_OTHER, "mp3") PHAR_SET_MIME("video/mpeg", PHAR_MIME_OTHER, "mpg") PHAR_SET_MIME("video/mpeg", PHAR_MIME_OTHER, "mpeg") PHAR_SET_MIME("application/pdf", PHAR_MIME_OTHER, "pdf") PHAR_SET_MIME("image/png", PHAR_MIME_OTHER, "png") PHAR_SET_MIME("application/shockwave-flash", PHAR_MIME_OTHER, "swf") PHAR_SET_MIME("image/tiff", PHAR_MIME_OTHER, "tif") PHAR_SET_MIME("image/tiff", PHAR_MIME_OTHER, "tiff") PHAR_SET_MIME("audio/wav", PHAR_MIME_OTHER, "wav") PHAR_SET_MIME("image/xbm", PHAR_MIME_OTHER, "xbm") PHAR_SET_MIME("text/xml", PHAR_MIME_OTHER, "xml") phar_restore_orig_functions(TSRMLS_C); } /* }}} */ PHP_GSHUTDOWN_FUNCTION(phar) /* {{{ */ { zend_hash_destroy(&phar_globals->mime_types); } /* }}} */ PHP_MINIT_FUNCTION(phar) /* {{{ */ { REGISTER_INI_ENTRIES(); phar_orig_compile_file = zend_compile_file; zend_compile_file = phar_compile_file; #if PHP_VERSION_ID >= 50300 phar_save_resolve_path = zend_resolve_path; zend_resolve_path = phar_resolve_path; #else phar_orig_zend_open = zend_stream_open_function; zend_stream_open_function = phar_zend_open; #endif phar_object_init(TSRMLS_C); phar_intercept_functions_init(TSRMLS_C); phar_save_orig_functions(TSRMLS_C); return php_register_url_stream_wrapper("phar", &php_stream_phar_wrapper TSRMLS_CC); } /* }}} */ PHP_MSHUTDOWN_FUNCTION(phar) /* {{{ */ { php_unregister_url_stream_wrapper("phar" TSRMLS_CC); phar_intercept_functions_shutdown(TSRMLS_C); if (zend_compile_file == phar_compile_file) { zend_compile_file = phar_orig_compile_file; } #if PHP_VERSION_ID < 50300 if (zend_stream_open_function == phar_zend_open) { zend_stream_open_function = phar_orig_zend_open; } #endif if (PHAR_G(manifest_cached)) { zend_hash_destroy(&(cached_phars)); zend_hash_destroy(&(cached_alias)); } return SUCCESS; } /* }}} */ void phar_request_initialize(TSRMLS_D) /* {{{ */ { if (!PHAR_GLOBALS->request_init) { PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; PHAR_G(has_bz2) = zend_hash_exists(&module_registry, "bz2", sizeof("bz2")); PHAR_G(has_zlib) = zend_hash_exists(&module_registry, "zlib", sizeof("zlib")); PHAR_GLOBALS->request_init = 1; PHAR_GLOBALS->request_ends = 0; PHAR_GLOBALS->request_done = 0; zend_hash_init(&(PHAR_GLOBALS->phar_fname_map), 5, zend_get_hash_value, destroy_phar_data, 0); zend_hash_init(&(PHAR_GLOBALS->phar_persist_map), 5, zend_get_hash_value, NULL, 0); zend_hash_init(&(PHAR_GLOBALS->phar_alias_map), 5, zend_get_hash_value, NULL, 0); if (PHAR_G(manifest_cached)) { phar_archive_data **pphar; phar_entry_fp *stuff = (phar_entry_fp *) ecalloc(zend_hash_num_elements(&cached_phars), sizeof(phar_entry_fp)); for (zend_hash_internal_pointer_reset(&cached_phars); zend_hash_get_current_data(&cached_phars, (void **)&pphar) == SUCCESS; zend_hash_move_forward(&cached_phars)) { stuff[pphar[0]->phar_pos].manifest = (phar_entry_fp_info *) ecalloc( zend_hash_num_elements(&(pphar[0]->manifest)), sizeof(phar_entry_fp_info)); } PHAR_GLOBALS->cached_fp = stuff; } PHAR_GLOBALS->phar_SERVER_mung_list = 0; PHAR_G(cwd) = NULL; PHAR_G(cwd_len) = 0; PHAR_G(cwd_init) = 0; } } /* }}} */ PHP_RSHUTDOWN_FUNCTION(phar) /* {{{ */ { int i; PHAR_GLOBALS->request_ends = 1; if (PHAR_GLOBALS->request_init) { phar_release_functions(TSRMLS_C); zend_hash_destroy(&(PHAR_GLOBALS->phar_alias_map)); PHAR_GLOBALS->phar_alias_map.arBuckets = NULL; zend_hash_destroy(&(PHAR_GLOBALS->phar_fname_map)); PHAR_GLOBALS->phar_fname_map.arBuckets = NULL; zend_hash_destroy(&(PHAR_GLOBALS->phar_persist_map)); PHAR_GLOBALS->phar_persist_map.arBuckets = NULL; PHAR_GLOBALS->phar_SERVER_mung_list = 0; if (PHAR_GLOBALS->cached_fp) { for (i = 0; i < zend_hash_num_elements(&cached_phars); ++i) { if (PHAR_GLOBALS->cached_fp[i].fp) { php_stream_close(PHAR_GLOBALS->cached_fp[i].fp); } if (PHAR_GLOBALS->cached_fp[i].ufp) { php_stream_close(PHAR_GLOBALS->cached_fp[i].ufp); } efree(PHAR_GLOBALS->cached_fp[i].manifest); } efree(PHAR_GLOBALS->cached_fp); PHAR_GLOBALS->cached_fp = 0; } PHAR_GLOBALS->request_init = 0; if (PHAR_G(cwd)) { efree(PHAR_G(cwd)); } PHAR_G(cwd) = NULL; PHAR_G(cwd_len) = 0; PHAR_G(cwd_init) = 0; } PHAR_GLOBALS->request_done = 1; return SUCCESS; } /* }}} */ PHP_MINFO_FUNCTION(phar) /* {{{ */ { phar_request_initialize(TSRMLS_C); php_info_print_table_start(); php_info_print_table_header(2, "Phar: PHP Archive support", "enabled"); php_info_print_table_row(2, "Phar EXT version", PHP_PHAR_VERSION); php_info_print_table_row(2, "Phar API version", PHP_PHAR_API_VERSION); php_info_print_table_row(2, "SVN revision", "$Revision$"); php_info_print_table_row(2, "Phar-based phar archives", "enabled"); php_info_print_table_row(2, "Tar-based phar archives", "enabled"); php_info_print_table_row(2, "ZIP-based phar archives", "enabled"); if (PHAR_G(has_zlib)) { php_info_print_table_row(2, "gzip compression", "enabled"); } else { php_info_print_table_row(2, "gzip compression", "disabled (install ext/zlib)"); } if (PHAR_G(has_bz2)) { php_info_print_table_row(2, "bzip2 compression", "enabled"); } else { php_info_print_table_row(2, "bzip2 compression", "disabled (install pecl/bz2)"); } #ifdef PHAR_HAVE_OPENSSL php_info_print_table_row(2, "Native OpenSSL support", "enabled"); #else if (zend_hash_exists(&module_registry, "openssl", sizeof("openssl"))) { php_info_print_table_row(2, "OpenSSL support", "enabled"); } else { php_info_print_table_row(2, "OpenSSL support", "disabled (install ext/openssl)"); } #endif php_info_print_table_end(); php_info_print_box_start(0); PUTS("Phar based on pear/PHP_Archive, original concept by Davey Shafik."); PUTS(!sapi_module.phpinfo_as_text?"<br />":"\n"); PUTS("Phar fully realized by Gregory Beaver and Marcus Boerger."); PUTS(!sapi_module.phpinfo_as_text?"<br />":"\n"); PUTS("Portions of tar implementation Copyright (c) 2003-2009 Tim Kientzle."); php_info_print_box_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ /* {{{ phar_module_entry */ static const zend_module_dep phar_deps[] = { ZEND_MOD_OPTIONAL("apc") ZEND_MOD_OPTIONAL("bz2") ZEND_MOD_OPTIONAL("openssl") ZEND_MOD_OPTIONAL("zlib") ZEND_MOD_OPTIONAL("standard") #if defined(HAVE_HASH) && !defined(COMPILE_DL_HASH) ZEND_MOD_REQUIRED("hash") #endif #if HAVE_SPL ZEND_MOD_REQUIRED("spl") #endif ZEND_MOD_END }; zend_module_entry phar_module_entry = { STANDARD_MODULE_HEADER_EX, NULL, phar_deps, "Phar", phar_functions, PHP_MINIT(phar), PHP_MSHUTDOWN(phar), NULL, PHP_RSHUTDOWN(phar), PHP_MINFO(phar), PHP_PHAR_VERSION, PHP_MODULE_GLOBALS(phar), /* globals descriptor */ PHP_GINIT(phar), /* globals ctor */ PHP_GSHUTDOWN(phar), /* globals dtor */ NULL, /* post deactivate */ STANDARD_MODULE_PROPERTIES_EX }; /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | phar php single-file executable PHP extension | +----------------------------------------------------------------------+ | Copyright (c) 2005-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Gregory Beaver <[email protected]> | | Marcus Boerger <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #define PHAR_MAIN 1 #include "phar_internal.h" #include "SAPI.h" #include "func_interceptors.h" static void destroy_phar_data(void *pDest); ZEND_DECLARE_MODULE_GLOBALS(phar) #if PHP_VERSION_ID >= 50300 char *(*phar_save_resolve_path)(const char *filename, int filename_len TSRMLS_DC); #endif /** * set's phar->is_writeable based on the current INI value */ static int phar_set_writeable_bit(void *pDest, void *argument TSRMLS_DC) /* {{{ */ { zend_bool keep = *(zend_bool *)argument; phar_archive_data *phar = *(phar_archive_data **)pDest; if (!phar->is_data) { phar->is_writeable = !keep; } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* if the original value is 0 (disabled), then allow setting/unsetting at will. Otherwise only allow 1 (enabled), and error on disabling */ ZEND_INI_MH(phar_ini_modify_handler) /* {{{ */ { zend_bool old, ini; if (entry->name_length == 14) { old = PHAR_G(readonly_orig); } else { old = PHAR_G(require_hash_orig); } if (new_value_length == 2 && !strcasecmp("on", new_value)) { ini = (zend_bool) 1; } else if (new_value_length == 3 && !strcasecmp("yes", new_value)) { ini = (zend_bool) 1; } else if (new_value_length == 4 && !strcasecmp("true", new_value)) { ini = (zend_bool) 1; } else { ini = (zend_bool) atoi(new_value); } /* do not allow unsetting in runtime */ if (stage == ZEND_INI_STAGE_STARTUP) { if (entry->name_length == 14) { PHAR_G(readonly_orig) = ini; } else { PHAR_G(require_hash_orig) = ini; } } else if (old && !ini) { return FAILURE; } if (entry->name_length == 14) { PHAR_G(readonly) = ini; if (PHAR_GLOBALS->request_init && PHAR_GLOBALS->phar_fname_map.arBuckets) { zend_hash_apply_with_argument(&(PHAR_GLOBALS->phar_fname_map), phar_set_writeable_bit, (void *)&ini TSRMLS_CC); } } else { PHAR_G(require_hash) = ini; } return SUCCESS; } /* }}}*/ /* this global stores the global cached pre-parsed manifests */ HashTable cached_phars; HashTable cached_alias; static void phar_split_cache_list(TSRMLS_D) /* {{{ */ { char *tmp; char *key, *lasts, *end; char ds[2]; phar_archive_data *phar; uint i = 0; if (!PHAR_GLOBALS->cache_list || !(PHAR_GLOBALS->cache_list[0])) { return; } ds[0] = DEFAULT_DIR_SEPARATOR; ds[1] = '\0'; tmp = estrdup(PHAR_GLOBALS->cache_list); /* fake request startup */ PHAR_GLOBALS->request_init = 1; if (zend_hash_init(&EG(regular_list), 0, NULL, NULL, 0) == SUCCESS) { EG(regular_list).nNextFreeElement=1; /* we don't want resource id 0 */ } PHAR_G(has_bz2) = zend_hash_exists(&module_registry, "bz2", sizeof("bz2")); PHAR_G(has_zlib) = zend_hash_exists(&module_registry, "zlib", sizeof("zlib")); /* these two are dummies and will be destroyed later */ zend_hash_init(&cached_phars, sizeof(phar_archive_data*), zend_get_hash_value, destroy_phar_data, 1); zend_hash_init(&cached_alias, sizeof(phar_archive_data*), zend_get_hash_value, NULL, 1); /* these two are real and will be copied over cached_phars/cached_alias later */ zend_hash_init(&(PHAR_GLOBALS->phar_fname_map), sizeof(phar_archive_data*), zend_get_hash_value, destroy_phar_data, 1); zend_hash_init(&(PHAR_GLOBALS->phar_alias_map), sizeof(phar_archive_data*), zend_get_hash_value, NULL, 1); PHAR_GLOBALS->manifest_cached = 1; PHAR_GLOBALS->persist = 1; for (key = php_strtok_r(tmp, ds, &lasts); key; key = php_strtok_r(NULL, ds, &lasts)) { end = strchr(key, DEFAULT_DIR_SEPARATOR); if (end) { if (SUCCESS == phar_open_from_filename(key, end - key, NULL, 0, 0, &phar, NULL TSRMLS_CC)) { finish_up: phar->phar_pos = i++; php_stream_close(phar->fp); phar->fp = NULL; } else { finish_error: PHAR_GLOBALS->persist = 0; PHAR_GLOBALS->manifest_cached = 0; efree(tmp); zend_hash_destroy(&(PHAR_G(phar_fname_map))); PHAR_GLOBALS->phar_fname_map.arBuckets = 0; zend_hash_destroy(&(PHAR_G(phar_alias_map))); PHAR_GLOBALS->phar_alias_map.arBuckets = 0; zend_hash_destroy(&cached_phars); zend_hash_destroy(&cached_alias); zend_hash_graceful_reverse_destroy(&EG(regular_list)); memset(&EG(regular_list), 0, sizeof(HashTable)); /* free cached manifests */ PHAR_GLOBALS->request_init = 0; return; } } else { if (SUCCESS == phar_open_from_filename(key, strlen(key), NULL, 0, 0, &phar, NULL TSRMLS_CC)) { goto finish_up; } else { goto finish_error; } } } PHAR_GLOBALS->persist = 0; PHAR_GLOBALS->request_init = 0; /* destroy dummy values from before */ zend_hash_destroy(&cached_phars); zend_hash_destroy(&cached_alias); cached_phars = PHAR_GLOBALS->phar_fname_map; cached_alias = PHAR_GLOBALS->phar_alias_map; PHAR_GLOBALS->phar_fname_map.arBuckets = 0; PHAR_GLOBALS->phar_alias_map.arBuckets = 0; zend_hash_graceful_reverse_destroy(&EG(regular_list)); memset(&EG(regular_list), 0, sizeof(HashTable)); efree(tmp); } /* }}} */ ZEND_INI_MH(phar_ini_cache_list) /* {{{ */ { PHAR_G(cache_list) = new_value; if (stage == ZEND_INI_STAGE_STARTUP) { phar_split_cache_list(TSRMLS_C); } return SUCCESS; } /* }}} */ PHP_INI_BEGIN() STD_PHP_INI_BOOLEAN( "phar.readonly", "1", PHP_INI_ALL, phar_ini_modify_handler, readonly, zend_phar_globals, phar_globals) STD_PHP_INI_BOOLEAN( "phar.require_hash", "1", PHP_INI_ALL, phar_ini_modify_handler, require_hash, zend_phar_globals, phar_globals) STD_PHP_INI_ENTRY("phar.cache_list", "", PHP_INI_SYSTEM, phar_ini_cache_list, cache_list, zend_phar_globals, phar_globals) PHP_INI_END() /** * When all uses of a phar have been concluded, this frees the manifest * and the phar slot */ void phar_destroy_phar_data(phar_archive_data *phar TSRMLS_DC) /* {{{ */ { if (phar->alias && phar->alias != phar->fname) { pefree(phar->alias, phar->is_persistent); phar->alias = NULL; } if (phar->fname) { pefree(phar->fname, phar->is_persistent); phar->fname = NULL; } if (phar->signature) { pefree(phar->signature, phar->is_persistent); phar->signature = NULL; } if (phar->manifest.arBuckets) { zend_hash_destroy(&phar->manifest); phar->manifest.arBuckets = NULL; } if (phar->mounted_dirs.arBuckets) { zend_hash_destroy(&phar->mounted_dirs); phar->mounted_dirs.arBuckets = NULL; } if (phar->virtual_dirs.arBuckets) { zend_hash_destroy(&phar->virtual_dirs); phar->virtual_dirs.arBuckets = NULL; } if (phar->metadata) { if (phar->is_persistent) { if (phar->metadata_len) { /* for zip comments that are strings */ free(phar->metadata); } else { zval_internal_ptr_dtor(&phar->metadata); } } else { zval_ptr_dtor(&phar->metadata); } phar->metadata_len = 0; phar->metadata = 0; } if (phar->fp) { php_stream_close(phar->fp); phar->fp = 0; } if (phar->ufp) { php_stream_close(phar->ufp); phar->ufp = 0; } pefree(phar, phar->is_persistent); } /* }}}*/ /** * Delete refcount and destruct if needed. On destruct return 1 else 0. */ int phar_archive_delref(phar_archive_data *phar TSRMLS_DC) /* {{{ */ { if (phar->is_persistent) { return 0; } if (--phar->refcount < 0) { if (PHAR_GLOBALS->request_done || zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), phar->fname, phar->fname_len) != SUCCESS) { phar_destroy_phar_data(phar TSRMLS_CC); } return 1; } else if (!phar->refcount) { /* invalidate phar cache */ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; if (phar->fp && !(phar->flags & PHAR_FILE_COMPRESSION_MASK)) { /* close open file handle - allows removal or rename of the file on windows, which has greedy locking only close if the archive was not already compressed. If it was compressed, then the fp does not refer to the original file */ php_stream_close(phar->fp); phar->fp = NULL; } if (!zend_hash_num_elements(&phar->manifest)) { /* this is a new phar that has perhaps had an alias/metadata set, but has never been flushed */ if (zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), phar->fname, phar->fname_len) != SUCCESS) { phar_destroy_phar_data(phar TSRMLS_CC); } return 1; } } return 0; } /* }}}*/ /** * Destroy phar's in shutdown, here we don't care about aliases */ static void destroy_phar_data_only(void *pDest) /* {{{ */ { phar_archive_data *phar_data = *(phar_archive_data **) pDest; TSRMLS_FETCH(); if (EG(exception) || --phar_data->refcount < 0) { phar_destroy_phar_data(phar_data TSRMLS_CC); } } /* }}}*/ /** * Delete aliases to phar's that got kicked out of the global table */ static int phar_unalias_apply(void *pDest, void *argument TSRMLS_DC) /* {{{ */ { return *(void**)pDest == argument ? ZEND_HASH_APPLY_REMOVE : ZEND_HASH_APPLY_KEEP; } /* }}} */ /** * Delete aliases to phar's that got kicked out of the global table */ static int phar_tmpclose_apply(void *pDest TSRMLS_DC) /* {{{ */ { phar_entry_info *entry = (phar_entry_info *) pDest; if (entry->fp_type != PHAR_TMP) { return ZEND_HASH_APPLY_KEEP; } if (entry->fp && !entry->fp_refcount) { php_stream_close(entry->fp); entry->fp = NULL; } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /** * Filename map destructor */ static void destroy_phar_data(void *pDest) /* {{{ */ { phar_archive_data *phar_data = *(phar_archive_data **) pDest; TSRMLS_FETCH(); if (PHAR_GLOBALS->request_ends) { /* first, iterate over the manifest and close all PHAR_TMP entry fp handles, this prevents unnecessary unfreed stream resources */ zend_hash_apply(&(phar_data->manifest), phar_tmpclose_apply TSRMLS_CC); destroy_phar_data_only(pDest); return; } zend_hash_apply_with_argument(&(PHAR_GLOBALS->phar_alias_map), phar_unalias_apply, phar_data TSRMLS_CC); if (--phar_data->refcount < 0) { phar_destroy_phar_data(phar_data TSRMLS_CC); } } /* }}}*/ /** * destructor for the manifest hash, frees each file's entry */ void destroy_phar_manifest_entry(void *pDest) /* {{{ */ { phar_entry_info *entry = (phar_entry_info *)pDest; TSRMLS_FETCH(); if (entry->cfp) { php_stream_close(entry->cfp); entry->cfp = 0; } if (entry->fp) { php_stream_close(entry->fp); entry->fp = 0; } if (entry->metadata) { if (entry->is_persistent) { if (entry->metadata_len) { /* for zip comments that are strings */ free(entry->metadata); } else { zval_internal_ptr_dtor(&entry->metadata); } } else { zval_ptr_dtor(&entry->metadata); } entry->metadata_len = 0; entry->metadata = 0; } if (entry->metadata_str.c) { smart_str_free(&entry->metadata_str); entry->metadata_str.c = 0; } pefree(entry->filename, entry->is_persistent); if (entry->link) { pefree(entry->link, entry->is_persistent); entry->link = 0; } if (entry->tmp) { pefree(entry->tmp, entry->is_persistent); entry->tmp = 0; } } /* }}} */ int phar_entry_delref(phar_entry_data *idata TSRMLS_DC) /* {{{ */ { int ret = 0; if (idata->internal_file && !idata->internal_file->is_persistent) { if (--idata->internal_file->fp_refcount < 0) { idata->internal_file->fp_refcount = 0; } if (idata->fp && idata->fp != idata->phar->fp && idata->fp != idata->phar->ufp && idata->fp != idata->internal_file->fp) { php_stream_close(idata->fp); } /* if phar_get_or_create_entry_data returns a sub-directory, we have to free it */ if (idata->internal_file->is_temp_dir) { destroy_phar_manifest_entry((void *)idata->internal_file); efree(idata->internal_file); } } phar_archive_delref(idata->phar TSRMLS_CC); efree(idata); return ret; } /* }}} */ /** * Removes an entry, either by actually removing it or by marking it. */ void phar_entry_remove(phar_entry_data *idata, char **error TSRMLS_DC) /* {{{ */ { phar_archive_data *phar; phar = idata->phar; if (idata->internal_file->fp_refcount < 2) { if (idata->fp && idata->fp != idata->phar->fp && idata->fp != idata->phar->ufp && idata->fp != idata->internal_file->fp) { php_stream_close(idata->fp); } zend_hash_del(&idata->phar->manifest, idata->internal_file->filename, idata->internal_file->filename_len); idata->phar->refcount--; efree(idata); } else { idata->internal_file->is_deleted = 1; phar_entry_delref(idata TSRMLS_CC); } if (!phar->donotflush) { phar_flush(phar, 0, 0, 0, error TSRMLS_CC); } } /* }}} */ #define MAPPHAR_ALLOC_FAIL(msg) \ if (fp) {\ php_stream_close(fp);\ }\ if (error) {\ spprintf(error, 0, msg, fname);\ }\ return FAILURE; #define MAPPHAR_FAIL(msg) \ efree(savebuf);\ if (mydata) {\ phar_destroy_phar_data(mydata TSRMLS_CC);\ }\ if (signature) {\ pefree(signature, PHAR_G(persist));\ }\ MAPPHAR_ALLOC_FAIL(msg) #ifdef WORDS_BIGENDIAN # define PHAR_GET_32(buffer, var) \ var = ((((unsigned char*)(buffer))[3]) << 24) \ | ((((unsigned char*)(buffer))[2]) << 16) \ | ((((unsigned char*)(buffer))[1]) << 8) \ | (((unsigned char*)(buffer))[0]); \ (buffer) += 4 # define PHAR_GET_16(buffer, var) \ var = ((((unsigned char*)(buffer))[1]) << 8) \ | (((unsigned char*)(buffer))[0]); \ (buffer) += 2 #else # define PHAR_GET_32(buffer, var) \ memcpy(&var, buffer, sizeof(var)); \ buffer += 4 # define PHAR_GET_16(buffer, var) \ var = *(php_uint16*)(buffer); \ buffer += 2 #endif #define PHAR_ZIP_16(var) ((php_uint16)((((php_uint16)var[0]) & 0xff) | \ (((php_uint16)var[1]) & 0xff) << 8)) #define PHAR_ZIP_32(var) ((php_uint32)((((php_uint32)var[0]) & 0xff) | \ (((php_uint32)var[1]) & 0xff) << 8 | \ (((php_uint32)var[2]) & 0xff) << 16 | \ (((php_uint32)var[3]) & 0xff) << 24)) /** * Open an already loaded phar */ int phar_open_parsed_phar(char *fname, int fname_len, char *alias, int alias_len, int is_data, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { phar_archive_data *phar; #ifdef PHP_WIN32 char *unixfname; #endif if (error) { *error = NULL; } #ifdef PHP_WIN32 unixfname = estrndup(fname, fname_len); phar_unixify_path_separators(unixfname, fname_len); if (SUCCESS == phar_get_archive(&phar, unixfname, fname_len, alias, alias_len, error TSRMLS_CC) && ((alias && fname_len == phar->fname_len && !strncmp(unixfname, phar->fname, fname_len)) || !alias) ) { phar_entry_info *stub; efree(unixfname); #else if (SUCCESS == phar_get_archive(&phar, fname, fname_len, alias, alias_len, error TSRMLS_CC) && ((alias && fname_len == phar->fname_len && !strncmp(fname, phar->fname, fname_len)) || !alias) ) { phar_entry_info *stub; #endif /* logic above is as follows: If an explicit alias was requested, ensure the filename passed in matches the phar's filename. If no alias was passed in, then it can match either and be valid */ if (!is_data) { /* prevent any ".phar" without a stub getting through */ if (!phar->halt_offset && !phar->is_brandnew && (phar->is_tar || phar->is_zip)) { if (PHAR_G(readonly) && FAILURE == zend_hash_find(&(phar->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1, (void **)&stub)) { if (error) { spprintf(error, 0, "'%s' is not a phar archive. Use PharData::__construct() for a standard zip or tar archive", fname); } return FAILURE; } } } if (pphar) { *pphar = phar; } return SUCCESS; } else { #ifdef PHP_WIN32 efree(unixfname); #endif if (pphar) { *pphar = NULL; } if (phar && error && !(options & REPORT_ERRORS)) { efree(error); } return FAILURE; } } /* }}}*/ /** * Parse out metadata from the manifest for a single file * * Meta-data is in this format: * [len32][data...] * * data is the serialized zval */ int phar_parse_metadata(char **buffer, zval **metadata, int zip_metadata_len TSRMLS_DC) /* {{{ */ { const unsigned char *p; php_uint32 buf_len; php_unserialize_data_t var_hash; if (!zip_metadata_len) { PHAR_GET_32(*buffer, buf_len); } else { buf_len = zip_metadata_len; } if (buf_len) { ALLOC_ZVAL(*metadata); INIT_ZVAL(**metadata); p = (const unsigned char*) *buffer; PHP_VAR_UNSERIALIZE_INIT(var_hash); if (!php_var_unserialize(metadata, &p, p + buf_len, &var_hash TSRMLS_CC)) { PHP_VAR_UNSERIALIZE_DESTROY(var_hash); zval_ptr_dtor(metadata); *metadata = NULL; return FAILURE; } PHP_VAR_UNSERIALIZE_DESTROY(var_hash); if (PHAR_G(persist)) { /* lazy init metadata */ zval_ptr_dtor(metadata); *metadata = (zval *) pemalloc(buf_len, 1); memcpy(*metadata, *buffer, buf_len); *buffer += buf_len; return SUCCESS; } } else { *metadata = NULL; } if (!zip_metadata_len) { *buffer += buf_len; } return SUCCESS; } /* }}}*/ /** * Does not check for a previously opened phar in the cache. * * Parse a new one and add it to the cache, returning either SUCCESS or * FAILURE, and setting pphar to the pointer to the manifest entry * * This is used by phar_open_from_filename to process the manifest, but can be called * directly. */ static int phar_parse_pharfile(php_stream *fp, char *fname, int fname_len, char *alias, int alias_len, long halt_offset, phar_archive_data** pphar, php_uint32 compression, char **error TSRMLS_DC) /* {{{ */ { char b32[4], *buffer, *endbuffer, *savebuf; phar_archive_data *mydata = NULL; phar_entry_info entry; php_uint32 manifest_len, manifest_count, manifest_flags, manifest_index, tmp_len, sig_flags; php_uint16 manifest_ver; long offset; int sig_len, register_alias = 0, temp_alias = 0; char *signature = NULL; if (pphar) { *pphar = NULL; } if (error) { *error = NULL; } /* check for ?>\n and increment accordingly */ if (-1 == php_stream_seek(fp, halt_offset, SEEK_SET)) { MAPPHAR_ALLOC_FAIL("cannot seek to __HALT_COMPILER(); location in phar \"%s\"") } buffer = b32; if (3 != php_stream_read(fp, buffer, 3)) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at stub end)") } if ((*buffer == ' ' || *buffer == '\n') && *(buffer + 1) == '?' && *(buffer + 2) == '>') { int nextchar; halt_offset += 3; if (EOF == (nextchar = php_stream_getc(fp))) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at stub end)") } if ((char) nextchar == '\r') { /* if we have an \r we require an \n as well */ if (EOF == (nextchar = php_stream_getc(fp)) || (char)nextchar != '\n') { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at stub end)") } ++halt_offset; } if ((char) nextchar == '\n') { ++halt_offset; } } /* make sure we are at the right location to read the manifest */ if (-1 == php_stream_seek(fp, halt_offset, SEEK_SET)) { MAPPHAR_ALLOC_FAIL("cannot seek to __HALT_COMPILER(); location in phar \"%s\"") } /* read in manifest */ buffer = b32; if (4 != php_stream_read(fp, buffer, 4)) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at manifest length)") } PHAR_GET_32(buffer, manifest_len); if (manifest_len > 1048576 * 100) { /* prevent serious memory issues by limiting manifest to at most 100 MB in length */ MAPPHAR_ALLOC_FAIL("manifest cannot be larger than 100 MB in phar \"%s\"") } buffer = (char *)emalloc(manifest_len); savebuf = buffer; endbuffer = buffer + manifest_len; if (manifest_len < 10 || manifest_len != php_stream_read(fp, buffer, manifest_len)) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest header)") } /* extract the number of entries */ PHAR_GET_32(buffer, manifest_count); if (manifest_count == 0) { MAPPHAR_FAIL("in phar \"%s\", manifest claims to have zero entries. Phars must have at least 1 entry"); } /* extract API version, lowest nibble currently unused */ manifest_ver = (((unsigned char)buffer[0]) << 8) + ((unsigned char)buffer[1]); buffer += 2; if ((manifest_ver & PHAR_API_VER_MASK) < PHAR_API_MIN_READ) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" is API version %1.u.%1.u.%1.u, and cannot be processed", fname, manifest_ver >> 12, (manifest_ver >> 8) & 0xF, (manifest_ver >> 4) & 0x0F); } return FAILURE; } PHAR_GET_32(buffer, manifest_flags); manifest_flags &= ~PHAR_HDR_COMPRESSION_MASK; manifest_flags &= ~PHAR_FILE_COMPRESSION_MASK; /* remember whether this entire phar was compressed with gz/bzip2 */ manifest_flags |= compression; /* The lowest nibble contains the phar wide flags. The compression flags can */ /* be ignored on reading because it is being generated anyways. */ if (manifest_flags & PHAR_HDR_SIGNATURE) { char sig_buf[8], *sig_ptr = sig_buf; off_t read_len; size_t end_of_phar; if (-1 == php_stream_seek(fp, -8, SEEK_END) || (read_len = php_stream_tell(fp)) < 20 || 8 != php_stream_read(fp, sig_buf, 8) || memcmp(sig_buf+4, "GBMB", 4)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } PHAR_GET_32(sig_ptr, sig_flags); switch(sig_flags) { case PHAR_SIG_OPENSSL: { php_uint32 signature_len; char *sig; off_t whence; /* we store the signature followed by the signature length */ if (-1 == php_stream_seek(fp, -12, SEEK_CUR) || 4 != php_stream_read(fp, sig_buf, 4)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" openssl signature length could not be read", fname); } return FAILURE; } sig_ptr = sig_buf; PHAR_GET_32(sig_ptr, signature_len); sig = (char *) emalloc(signature_len); whence = signature_len + 4; whence = -whence; if (-1 == php_stream_seek(fp, whence, SEEK_CUR) || !(end_of_phar = php_stream_tell(fp)) || signature_len != php_stream_read(fp, sig, signature_len)) { efree(savebuf); efree(sig); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" openssl signature could not be read", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, end_of_phar, PHAR_SIG_OPENSSL, sig, signature_len, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); efree(sig); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" openssl signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } efree(sig); } break; #if PHAR_HASH_OK case PHAR_SIG_SHA512: { unsigned char digest[64]; php_stream_seek(fp, -(8 + 64), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_SHA512, (char *)digest, 64, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" SHA512 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } case PHAR_SIG_SHA256: { unsigned char digest[32]; php_stream_seek(fp, -(8 + 32), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_SHA256, (char *)digest, 32, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" SHA256 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } #else case PHAR_SIG_SHA512: case PHAR_SIG_SHA256: efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a unsupported signature", fname); } return FAILURE; #endif case PHAR_SIG_SHA1: { unsigned char digest[20]; php_stream_seek(fp, -(8 + 20), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_SHA1, (char *)digest, 20, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" SHA1 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } case PHAR_SIG_MD5: { unsigned char digest[16]; php_stream_seek(fp, -(8 + 16), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_MD5, (char *)digest, 16, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" MD5 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } default: efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken or unsupported signature", fname); } return FAILURE; } } else if (PHAR_G(require_hash)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" does not have a signature", fname); } return FAILURE; } else { sig_flags = 0; sig_len = 0; } /* extract alias */ PHAR_GET_32(buffer, tmp_len); if (buffer + tmp_len > endbuffer) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (buffer overrun)"); } if (manifest_len < 10 + tmp_len) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest header)") } /* tmp_len = 0 says alias length is 0, which means the alias is not stored in the phar */ if (tmp_len) { /* if the alias is stored we enforce it (implicit overrides explicit) */ if (alias && alias_len && (alias_len != (int)tmp_len || strncmp(alias, buffer, tmp_len))) { buffer[tmp_len] = '\0'; php_stream_close(fp); if (signature) { efree(signature); } if (error) { spprintf(error, 0, "cannot load phar \"%s\" with implicit alias \"%s\" under different alias \"%s\"", fname, buffer, alias); } efree(savebuf); return FAILURE; } alias_len = tmp_len; alias = buffer; buffer += tmp_len; register_alias = 1; } else if (!alias_len || !alias) { /* if we neither have an explicit nor an implicit alias, we use the filename */ alias = NULL; alias_len = 0; register_alias = 0; } else if (alias_len) { register_alias = 1; temp_alias = 1; } /* we have 5 32-bit items plus 1 byte at least */ if (manifest_count > ((manifest_len - 10 - tmp_len) / (5 * 4 + 1))) { /* prevent serious memory issues */ MAPPHAR_FAIL("internal corruption of phar \"%s\" (too many manifest entries for size of manifest)") } mydata = pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist)); mydata->is_persistent = PHAR_G(persist); /* check whether we have meta data, zero check works regardless of byte order */ if (mydata->is_persistent) { PHAR_GET_32(buffer, mydata->metadata_len); if (phar_parse_metadata(&buffer, &mydata->metadata, mydata->metadata_len TSRMLS_CC) == FAILURE) { MAPPHAR_FAIL("unable to read phar metadata in .phar file \"%s\""); } } else { if (phar_parse_metadata(&buffer, &mydata->metadata, 0 TSRMLS_CC) == FAILURE) { MAPPHAR_FAIL("unable to read phar metadata in .phar file \"%s\""); } } /* set up our manifest */ zend_hash_init(&mydata->manifest, manifest_count, zend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)mydata->is_persistent); zend_hash_init(&mydata->mounted_dirs, 5, zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); zend_hash_init(&mydata->virtual_dirs, manifest_count * 2, zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); mydata->fname = pestrndup(fname, fname_len, mydata->is_persistent); #ifdef PHP_WIN32 phar_unixify_path_separators(mydata->fname, fname_len); #endif mydata->fname_len = fname_len; offset = halt_offset + manifest_len + 4; memset(&entry, 0, sizeof(phar_entry_info)); entry.phar = mydata; entry.fp_type = PHAR_FP; entry.is_persistent = mydata->is_persistent; for (manifest_index = 0; manifest_index < manifest_count; ++manifest_index) { if (buffer + 4 > endbuffer) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest entry)") } PHAR_GET_32(buffer, entry.filename_len); if (entry.filename_len == 0) { MAPPHAR_FAIL("zero-length filename encountered in phar \"%s\""); } if (entry.is_persistent) { entry.manifest_pos = manifest_index; } if (buffer + entry.filename_len + 20 > endbuffer) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest entry)"); } if ((manifest_ver & PHAR_API_VER_MASK) >= PHAR_API_MIN_DIR && buffer[entry.filename_len - 1] == '/') { entry.is_dir = 1; } else { entry.is_dir = 0; } phar_add_virtual_dirs(mydata, buffer, entry.filename_len TSRMLS_CC); entry.filename = pestrndup(buffer, entry.filename_len, entry.is_persistent); buffer += entry.filename_len; PHAR_GET_32(buffer, entry.uncompressed_filesize); PHAR_GET_32(buffer, entry.timestamp); if (offset == halt_offset + (int)manifest_len + 4) { mydata->min_timestamp = entry.timestamp; mydata->max_timestamp = entry.timestamp; } else { if (mydata->min_timestamp > entry.timestamp) { mydata->min_timestamp = entry.timestamp; } else if (mydata->max_timestamp < entry.timestamp) { mydata->max_timestamp = entry.timestamp; } } PHAR_GET_32(buffer, entry.compressed_filesize); PHAR_GET_32(buffer, entry.crc32); PHAR_GET_32(buffer, entry.flags); if (entry.is_dir) { entry.filename_len--; entry.flags |= PHAR_ENT_PERM_DEF_DIR; } if (entry.is_persistent) { PHAR_GET_32(buffer, entry.metadata_len); if (!entry.metadata_len) buffer -= 4; if (phar_parse_metadata(&buffer, &entry.metadata, entry.metadata_len TSRMLS_CC) == FAILURE) { pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("unable to read file metadata in .phar file \"%s\""); } } else { if (phar_parse_metadata(&buffer, &entry.metadata, 0 TSRMLS_CC) == FAILURE) { pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("unable to read file metadata in .phar file \"%s\""); } } entry.offset = entry.offset_abs = offset; offset += entry.compressed_filesize; switch (entry.flags & PHAR_ENT_COMPRESSION_MASK) { case PHAR_ENT_COMPRESSED_GZ: if (!PHAR_G(has_zlib)) { if (entry.metadata) { if (entry.is_persistent) { free(entry.metadata); } else { zval_ptr_dtor(&entry.metadata); } } pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("zlib extension is required for gz compressed .phar file \"%s\""); } break; case PHAR_ENT_COMPRESSED_BZ2: if (!PHAR_G(has_bz2)) { if (entry.metadata) { if (entry.is_persistent) { free(entry.metadata); } else { zval_ptr_dtor(&entry.metadata); } } pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("bz2 extension is required for bzip2 compressed .phar file \"%s\""); } break; default: if (entry.uncompressed_filesize != entry.compressed_filesize) { if (entry.metadata) { if (entry.is_persistent) { free(entry.metadata); } else { zval_ptr_dtor(&entry.metadata); } } pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("internal corruption of phar \"%s\" (compressed and uncompressed size does not match for uncompressed entry)"); } break; } manifest_flags |= (entry.flags & PHAR_ENT_COMPRESSION_MASK); /* if signature matched, no need to check CRC32 for each file */ entry.is_crc_checked = (manifest_flags & PHAR_HDR_SIGNATURE ? 1 : 0); phar_set_inode(&entry TSRMLS_CC); zend_hash_add(&mydata->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info), NULL); } snprintf(mydata->version, sizeof(mydata->version), "%u.%u.%u", manifest_ver >> 12, (manifest_ver >> 8) & 0xF, (manifest_ver >> 4) & 0xF); mydata->internal_file_start = halt_offset + manifest_len + 4; mydata->halt_offset = halt_offset; mydata->flags = manifest_flags; endbuffer = strrchr(mydata->fname, '/'); if (endbuffer) { mydata->ext = memchr(endbuffer, '.', (mydata->fname + fname_len) - endbuffer); if (mydata->ext == endbuffer) { mydata->ext = memchr(endbuffer + 1, '.', (mydata->fname + fname_len) - endbuffer - 1); } if (mydata->ext) { mydata->ext_len = (mydata->fname + mydata->fname_len) - mydata->ext; } } mydata->alias = alias ? pestrndup(alias, alias_len, mydata->is_persistent) : pestrndup(mydata->fname, fname_len, mydata->is_persistent); mydata->alias_len = alias ? alias_len : fname_len; mydata->sig_flags = sig_flags; mydata->fp = fp; mydata->sig_len = sig_len; mydata->signature = signature; phar_request_initialize(TSRMLS_C); if (register_alias) { phar_archive_data **fd_ptr; mydata->is_temporary_alias = temp_alias; if (!phar_validate_alias(mydata->alias, mydata->alias_len)) { signature = NULL; fp = NULL; MAPPHAR_FAIL("Cannot open archive \"%s\", invalid alias"); } if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) { if (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) { signature = NULL; fp = NULL; MAPPHAR_FAIL("Cannot open archive \"%s\", alias is already in use by existing archive"); } } zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&mydata, sizeof(phar_archive_data*), NULL); } else { mydata->is_temporary_alias = 1; } zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len, (void*)&mydata, sizeof(phar_archive_data*), NULL); efree(savebuf); if (pphar) { *pphar = mydata; } return SUCCESS; } /* }}} */ /** * Create or open a phar for writing */ int phar_open_or_create_filename(char *fname, int fname_len, char *alias, int alias_len, int is_data, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { const char *ext_str, *z; char *my_error; int ext_len; phar_archive_data **test, *unused = NULL; test = &unused; if (error) { *error = NULL; } /* first try to open an existing file */ if (phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, !is_data, 0, 1 TSRMLS_CC) == SUCCESS) { goto check_file; } /* next try to create a new file */ if (FAILURE == phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, !is_data, 1, 1 TSRMLS_CC)) { if (error) { if (ext_len == -2) { spprintf(error, 0, "Cannot create a phar archive from a URL like \"%s\". Phar objects can only be created from local files", fname); } else { spprintf(error, 0, "Cannot create phar '%s', file extension (or combination) not recognised or the directory does not exist", fname); } } return FAILURE; } check_file: if (phar_open_parsed_phar(fname, fname_len, alias, alias_len, is_data, options, test, &my_error TSRMLS_CC) == SUCCESS) { if (pphar) { *pphar = *test; } if ((*test)->is_data && !(*test)->is_tar && !(*test)->is_zip) { if (error) { spprintf(error, 0, "Cannot open '%s' as a PharData object. Use Phar::__construct() for executable archives", fname); } return FAILURE; } if (PHAR_G(readonly) && !(*test)->is_data && ((*test)->is_tar || (*test)->is_zip)) { phar_entry_info *stub; if (FAILURE == zend_hash_find(&((*test)->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1, (void **)&stub)) { spprintf(error, 0, "'%s' is not a phar archive. Use PharData::__construct() for a standard zip or tar archive", fname); return FAILURE; } } if (!PHAR_G(readonly) || (*test)->is_data) { (*test)->is_writeable = 1; } return SUCCESS; } else if (my_error) { if (error) { *error = my_error; } else { efree(my_error); } return FAILURE; } if (ext_len > 3 && (z = memchr(ext_str, 'z', ext_len)) && ((ext_str + ext_len) - z >= 2) && !memcmp(z + 1, "ip", 2)) { /* assume zip-based phar */ return phar_open_or_create_zip(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC); } if (ext_len > 3 && (z = memchr(ext_str, 't', ext_len)) && ((ext_str + ext_len) - z >= 2) && !memcmp(z + 1, "ar", 2)) { /* assume tar-based phar */ return phar_open_or_create_tar(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC); } return phar_create_or_parse_filename(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC); } /* }}} */ int phar_create_or_parse_filename(char *fname, int fname_len, char *alias, int alias_len, int is_data, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { phar_archive_data *mydata; php_stream *fp; char *actual = NULL, *p; if (!pphar) { pphar = &mydata; } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { return FAILURE; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { return FAILURE; } /* first open readonly so it won't be created if not present */ fp = php_stream_open_wrapper(fname, "rb", IGNORE_URL|STREAM_MUST_SEEK|0, &actual); if (actual) { fname = actual; fname_len = strlen(actual); } if (fp) { if (phar_open_from_fp(fp, fname, fname_len, alias, alias_len, options, pphar, is_data, error TSRMLS_CC) == SUCCESS) { if ((*pphar)->is_data || !PHAR_G(readonly)) { (*pphar)->is_writeable = 1; } if (actual) { efree(actual); } return SUCCESS; } else { /* file exists, but is either corrupt or not a phar archive */ if (actual) { efree(actual); } return FAILURE; } } if (actual) { efree(actual); } if (PHAR_G(readonly) && !is_data) { if (options & REPORT_ERRORS) { if (error) { spprintf(error, 0, "creating archive \"%s\" disabled by the php.ini setting phar.readonly", fname); } } return FAILURE; } /* set up our manifest */ mydata = ecalloc(1, sizeof(phar_archive_data)); mydata->fname = expand_filepath(fname, NULL TSRMLS_CC); fname_len = strlen(mydata->fname); #ifdef PHP_WIN32 phar_unixify_path_separators(mydata->fname, fname_len); #endif p = strrchr(mydata->fname, '/'); if (p) { mydata->ext = memchr(p, '.', (mydata->fname + fname_len) - p); if (mydata->ext == p) { mydata->ext = memchr(p + 1, '.', (mydata->fname + fname_len) - p - 1); } if (mydata->ext) { mydata->ext_len = (mydata->fname + fname_len) - mydata->ext; } } if (pphar) { *pphar = mydata; } zend_hash_init(&mydata->manifest, sizeof(phar_entry_info), zend_get_hash_value, destroy_phar_manifest_entry, 0); zend_hash_init(&mydata->mounted_dirs, sizeof(char *), zend_get_hash_value, NULL, 0); zend_hash_init(&mydata->virtual_dirs, sizeof(char *), zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); mydata->fname_len = fname_len; snprintf(mydata->version, sizeof(mydata->version), "%s", PHP_PHAR_API_VERSION); mydata->is_temporary_alias = alias ? 0 : 1; mydata->internal_file_start = -1; mydata->fp = NULL; mydata->is_writeable = 1; mydata->is_brandnew = 1; phar_request_initialize(TSRMLS_C); zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len, (void*)&mydata, sizeof(phar_archive_data*), NULL); if (is_data) { alias = NULL; alias_len = 0; mydata->is_data = 1; /* assume tar format, PharData can specify other */ mydata->is_tar = 1; } else { phar_archive_data **fd_ptr; if (alias && SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) { if (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) { if (error) { spprintf(error, 4096, "phar error: phar \"%s\" cannot set alias \"%s\", already in use by another phar archive", mydata->fname, alias); } zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len); if (pphar) { *pphar = NULL; } return FAILURE; } } mydata->alias = alias ? estrndup(alias, alias_len) : estrndup(mydata->fname, fname_len); mydata->alias_len = alias ? alias_len : fname_len; } if (alias_len && alias) { if (FAILURE == zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&mydata, sizeof(phar_archive_data*), NULL)) { if (options & REPORT_ERRORS) { if (error) { spprintf(error, 0, "archive \"%s\" cannot be associated with alias \"%s\", already in use", fname, alias); } } zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len); if (pphar) { *pphar = NULL; } return FAILURE; } } return SUCCESS; } /* }}}*/ /** * Return an already opened filename. * * Or scan a phar file for the required __HALT_COMPILER(); ?> token and verify * that the manifest is proper, then pass it to phar_parse_pharfile(). SUCCESS * or FAILURE is returned and pphar is set to a pointer to the phar's manifest */ int phar_open_from_filename(char *fname, int fname_len, char *alias, int alias_len, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { php_stream *fp; char *actual; int ret, is_data = 0; if (error) { *error = NULL; } if (!strstr(fname, ".phar")) { is_data = 1; } if (phar_open_parsed_phar(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC) == SUCCESS) { return SUCCESS; } else if (error && *error) { return FAILURE; } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { return FAILURE; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { return FAILURE; } fp = php_stream_open_wrapper(fname, "rb", IGNORE_URL|STREAM_MUST_SEEK, &actual); if (!fp) { if (options & REPORT_ERRORS) { if (error) { spprintf(error, 0, "unable to open phar for reading \"%s\"", fname); } } if (actual) { efree(actual); } return FAILURE; } if (actual) { fname = actual; fname_len = strlen(actual); } ret = phar_open_from_fp(fp, fname, fname_len, alias, alias_len, options, pphar, is_data, error TSRMLS_CC); if (actual) { efree(actual); } return ret; } /* }}}*/ static inline char *phar_strnstr(const char *buf, int buf_len, const char *search, int search_len) /* {{{ */ { const char *c; int so_far = 0; if (buf_len < search_len) { return NULL; } c = buf - 1; do { if (!(c = memchr(c + 1, search[0], buf_len - search_len - so_far))) { return (char *) NULL; } so_far = c - buf; if (so_far >= (buf_len - search_len)) { return (char *) NULL; } if (!memcmp(c, search, search_len)) { return (char *) c; } } while (1); } /* }}} */ /** * Scan an open fp for the required __HALT_COMPILER(); ?> token and verify * that the manifest is proper, then pass it to phar_parse_pharfile(). SUCCESS * or FAILURE is returned and pphar is set to a pointer to the phar's manifest */ static int phar_open_from_fp(php_stream* fp, char *fname, int fname_len, char *alias, int alias_len, int options, phar_archive_data** pphar, int is_data, char **error TSRMLS_DC) /* {{{ */ { const char token[] = "__HALT_COMPILER();"; const char zip_magic[] = "PK\x03\x04"; const char gz_magic[] = "\x1f\x8b\x08"; const char bz_magic[] = "BZh"; char *pos, test = '\0'; const int window_size = 1024; char buffer[1024 + sizeof(token)]; /* a 1024 byte window + the size of the halt_compiler token (moving window) */ const long readsize = sizeof(buffer) - sizeof(token); const long tokenlen = sizeof(token) - 1; long halt_offset; size_t got; php_uint32 compression = PHAR_FILE_COMPRESSED_NONE; if (error) { *error = NULL; } if (-1 == php_stream_rewind(fp)) { MAPPHAR_ALLOC_FAIL("cannot rewind phar \"%s\"") } buffer[sizeof(buffer)-1] = '\0'; memset(buffer, 32, sizeof(token)); halt_offset = 0; /* Maybe it's better to compile the file instead of just searching, */ /* but we only want the offset. So we want a .re scanner to find it. */ while(!php_stream_eof(fp)) { if ((got = php_stream_read(fp, buffer+tokenlen, readsize)) < (size_t) tokenlen) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated entry)") } if (!test) { test = '\1'; pos = buffer+tokenlen; if (!memcmp(pos, gz_magic, 3)) { char err = 0; php_stream_filter *filter; php_stream *temp; /* to properly decompress, we have to tell zlib to look for a zlib or gzip header */ zval filterparams; if (!PHAR_G(has_zlib)) { MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\" to temporary file, enable zlib extension in php.ini") } array_init(&filterparams); /* this is defined in zlib's zconf.h */ #ifndef MAX_WBITS #define MAX_WBITS 15 #endif add_assoc_long(&filterparams, "window", MAX_WBITS + 32); /* entire file is gzip-compressed, uncompress to temporary file */ if (!(temp = php_stream_fopen_tmpfile())) { MAPPHAR_ALLOC_FAIL("unable to create temporary file for decompression of gzipped phar archive \"%s\"") } php_stream_rewind(fp); filter = php_stream_filter_create("zlib.inflate", &filterparams, php_stream_is_persistent(fp) TSRMLS_CC); if (!filter) { err = 1; add_assoc_long(&filterparams, "window", MAX_WBITS); filter = php_stream_filter_create("zlib.inflate", &filterparams, php_stream_is_persistent(fp) TSRMLS_CC); zval_dtor(&filterparams); if (!filter) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\", ext/zlib is buggy in PHP versions older than 5.2.6") } } else { zval_dtor(&filterparams); } php_stream_filter_append(&temp->writefilters, filter); if (SUCCESS != phar_stream_copy_to_stream(fp, temp, PHP_STREAM_COPY_ALL, NULL)) { if (err) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\", ext/zlib is buggy in PHP versions older than 5.2.6") } php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\" to temporary file") } php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(fp); fp = temp; php_stream_rewind(fp); compression = PHAR_FILE_COMPRESSED_GZ; /* now, start over */ test = '\0'; continue; } else if (!memcmp(pos, bz_magic, 3)) { php_stream_filter *filter; php_stream *temp; if (!PHAR_G(has_bz2)) { MAPPHAR_ALLOC_FAIL("unable to decompress bzipped phar archive \"%s\" to temporary file, enable bz2 extension in php.ini") } /* entire file is bzip-compressed, uncompress to temporary file */ if (!(temp = php_stream_fopen_tmpfile())) { MAPPHAR_ALLOC_FAIL("unable to create temporary file for decompression of bzipped phar archive \"%s\"") } php_stream_rewind(fp); filter = php_stream_filter_create("bzip2.decompress", NULL, php_stream_is_persistent(fp) TSRMLS_CC); if (!filter) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress bzipped phar archive \"%s\", filter creation failed") } php_stream_filter_append(&temp->writefilters, filter); if (SUCCESS != phar_stream_copy_to_stream(fp, temp, PHP_STREAM_COPY_ALL, NULL)) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress bzipped phar archive \"%s\" to temporary file") } php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(fp); fp = temp; php_stream_rewind(fp); compression = PHAR_FILE_COMPRESSED_BZ2; /* now, start over */ test = '\0'; continue; } if (!memcmp(pos, zip_magic, 4)) { php_stream_seek(fp, 0, SEEK_END); return phar_parse_zipfile(fp, fname, fname_len, alias, alias_len, pphar, error TSRMLS_CC); } if (got > 512) { if (phar_is_tar(pos, fname)) { php_stream_rewind(fp); return phar_parse_tarfile(fp, fname, fname_len, alias, alias_len, pphar, is_data, compression, error TSRMLS_CC); } } } if (got > 0 && (pos = phar_strnstr(buffer, got + sizeof(token), token, sizeof(token)-1)) != NULL) { halt_offset += (pos - buffer); /* no -tokenlen+tokenlen here */ return phar_parse_pharfile(fp, fname, fname_len, alias, alias_len, halt_offset, pphar, compression, error TSRMLS_CC); } halt_offset += got; memmove(buffer, buffer + window_size, tokenlen); /* move the memory buffer by the size of the window */ } MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (__HALT_COMPILER(); not found)") } /* }}} */ /* * given the location of the file extension and the start of the file path, * determine the end of the portion of the path (i.e. /path/to/file.ext/blah * grabs "/path/to/file.ext" as does the straight /path/to/file.ext), * stat it to determine if it exists. * if so, check to see if it is a directory and fail if so * if not, check to see if its dirname() exists (i.e. "/path/to") and is a directory * succeed if we are creating the file, otherwise fail. */ static int phar_analyze_path(const char *fname, const char *ext, int ext_len, int for_create TSRMLS_DC) /* {{{ */ { php_stream_statbuf ssb; char *realpath; char *filename = estrndup(fname, (ext - fname) + ext_len); if ((realpath = expand_filepath(filename, NULL TSRMLS_CC))) { #ifdef PHP_WIN32 phar_unixify_path_separators(realpath, strlen(realpath)); #endif if (zend_hash_exists(&(PHAR_GLOBALS->phar_fname_map), realpath, strlen(realpath))) { efree(realpath); efree(filename); return SUCCESS; } if (PHAR_G(manifest_cached) && zend_hash_exists(&cached_phars, realpath, strlen(realpath))) { efree(realpath); efree(filename); return SUCCESS; } efree(realpath); } if (SUCCESS == php_stream_stat_path((char *) filename, &ssb)) { efree(filename); if (ssb.sb.st_mode & S_IFDIR) { return FAILURE; } if (for_create == 1) { return FAILURE; } return SUCCESS; } else { char *slash; if (!for_create) { efree(filename); return FAILURE; } slash = (char *) strrchr(filename, '/'); if (slash) { *slash = '\0'; } if (SUCCESS != php_stream_stat_path((char *) filename, &ssb)) { if (!slash) { if (!(realpath = expand_filepath(filename, NULL TSRMLS_CC))) { efree(filename); return FAILURE; } #ifdef PHP_WIN32 phar_unixify_path_separators(realpath, strlen(realpath)); #endif slash = strstr(realpath, filename) + ((ext - fname) + ext_len); *slash = '\0'; slash = strrchr(realpath, '/'); if (slash) { *slash = '\0'; } else { efree(realpath); efree(filename); return FAILURE; } if (SUCCESS != php_stream_stat_path(realpath, &ssb)) { efree(realpath); efree(filename); return FAILURE; } efree(realpath); if (ssb.sb.st_mode & S_IFDIR) { efree(filename); return SUCCESS; } } efree(filename); return FAILURE; } efree(filename); if (ssb.sb.st_mode & S_IFDIR) { return SUCCESS; } return FAILURE; } } /* }}} */ /* check for ".phar" in extension */ static int phar_check_str(const char *fname, const char *ext_str, int ext_len, int executable, int for_create TSRMLS_DC) /* {{{ */ { char test[51]; const char *pos; if (ext_len >= 50) { return FAILURE; } if (executable == 1) { /* copy "." as well */ memcpy(test, ext_str - 1, ext_len + 1); test[ext_len + 1] = '\0'; /* executable phars must contain ".phar" as a valid extension (phar://.pharmy/oops is invalid) */ /* (phar://hi/there/.phar/oops is also invalid) */ pos = strstr(test, ".phar"); if (pos && (*(pos - 1) != '/') && (pos += 5) && (*pos == '\0' || *pos == '/' || *pos == '.')) { return phar_analyze_path(fname, ext_str, ext_len, for_create TSRMLS_CC); } else { return FAILURE; } } /* data phars need only contain a single non-"." to be valid */ if (!executable) { pos = strstr(ext_str, ".phar"); if (!(pos && (*(pos - 1) != '/') && (pos += 5) && (*pos == '\0' || *pos == '/' || *pos == '.')) && *(ext_str + 1) != '.' && *(ext_str + 1) != '/' && *(ext_str + 1) != '\0') { return phar_analyze_path(fname, ext_str, ext_len, for_create TSRMLS_CC); } } else { if (*(ext_str + 1) != '.' && *(ext_str + 1) != '/' && *(ext_str + 1) != '\0') { return phar_analyze_path(fname, ext_str, ext_len, for_create TSRMLS_CC); } } return FAILURE; } /* }}} */ /* * if executable is 1, only returns SUCCESS if the extension is one of the tar/zip .phar extensions * if executable is 0, it returns SUCCESS only if the filename does *not* contain ".phar" anywhere, and treats * the first extension as the filename extension * * if an extension is found, it sets ext_str to the location of the file extension in filename, * and ext_len to the length of the extension. * for urls like "phar://alias/oops" it instead sets ext_len to -1 and returns FAILURE, which tells * the calling function to use "alias" as the phar alias * * the last parameter should be set to tell the thing to assume that filename is the full path, and only to check the * extension rules, not to iterate. */ int phar_detect_phar_fname_ext(const char *filename, int filename_len, const char **ext_str, int *ext_len, int executable, int for_create, int is_complete TSRMLS_DC) /* {{{ */ { const char *pos, *slash; *ext_str = NULL; *ext_len = 0; if (!filename_len || filename_len == 1) { return FAILURE; } phar_request_initialize(TSRMLS_C); /* first check for alias in first segment */ pos = memchr(filename, '/', filename_len); if (pos && pos != filename) { /* check for url like http:// or phar:// */ if (*(pos - 1) == ':' && (pos - filename) < filename_len - 1 && *(pos + 1) == '/') { *ext_len = -2; *ext_str = NULL; return FAILURE; } if (zend_hash_exists(&(PHAR_GLOBALS->phar_alias_map), (char *) filename, pos - filename)) { *ext_str = pos; *ext_len = -1; return FAILURE; } if (PHAR_G(manifest_cached) && zend_hash_exists(&cached_alias, (char *) filename, pos - filename)) { *ext_str = pos; *ext_len = -1; return FAILURE; } } if (zend_hash_num_elements(&(PHAR_GLOBALS->phar_fname_map)) || PHAR_G(manifest_cached)) { phar_archive_data **pphar; if (is_complete) { if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), (char *) filename, filename_len, (void **)&pphar)) { *ext_str = filename + (filename_len - (*pphar)->ext_len); woohoo: *ext_len = (*pphar)->ext_len; if (executable == 2) { return SUCCESS; } if (executable == 1 && !(*pphar)->is_data) { return SUCCESS; } if (!executable && (*pphar)->is_data) { return SUCCESS; } return FAILURE; } if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, (char *) filename, filename_len, (void **)&pphar)) { *ext_str = filename + (filename_len - (*pphar)->ext_len); goto woohoo; } } else { phar_zstr key; char *str_key; uint keylen; ulong unused; zend_hash_internal_pointer_reset(&(PHAR_GLOBALS->phar_fname_map)); while (FAILURE != zend_hash_has_more_elements(&(PHAR_GLOBALS->phar_fname_map))) { if (HASH_KEY_NON_EXISTANT == zend_hash_get_current_key_ex(&(PHAR_GLOBALS->phar_fname_map), &key, &keylen, &unused, 0, NULL)) { break; } PHAR_STR(key, str_key); if (keylen > (uint) filename_len) { zend_hash_move_forward(&(PHAR_GLOBALS->phar_fname_map)); PHAR_STR_FREE(str_key); continue; } if (!memcmp(filename, str_key, keylen) && ((uint)filename_len == keylen || filename[keylen] == '/' || filename[keylen] == '\0')) { PHAR_STR_FREE(str_key); if (FAILURE == zend_hash_get_current_data(&(PHAR_GLOBALS->phar_fname_map), (void **) &pphar)) { break; } *ext_str = filename + (keylen - (*pphar)->ext_len); goto woohoo; } PHAR_STR_FREE(str_key); zend_hash_move_forward(&(PHAR_GLOBALS->phar_fname_map)); } if (PHAR_G(manifest_cached)) { zend_hash_internal_pointer_reset(&cached_phars); while (FAILURE != zend_hash_has_more_elements(&cached_phars)) { if (HASH_KEY_NON_EXISTANT == zend_hash_get_current_key_ex(&cached_phars, &key, &keylen, &unused, 0, NULL)) { break; } PHAR_STR(key, str_key); if (keylen > (uint) filename_len) { zend_hash_move_forward(&cached_phars); PHAR_STR_FREE(str_key); continue; } if (!memcmp(filename, str_key, keylen) && ((uint)filename_len == keylen || filename[keylen] == '/' || filename[keylen] == '\0')) { PHAR_STR_FREE(str_key); if (FAILURE == zend_hash_get_current_data(&cached_phars, (void **) &pphar)) { break; } *ext_str = filename + (keylen - (*pphar)->ext_len); goto woohoo; } PHAR_STR_FREE(str_key); zend_hash_move_forward(&cached_phars); } } } } pos = memchr(filename + 1, '.', filename_len); next_extension: if (!pos) { return FAILURE; } while (pos != filename && (*(pos - 1) == '/' || *(pos - 1) == '\0')) { pos = memchr(pos + 1, '.', filename_len - (pos - filename) + 1); if (!pos) { return FAILURE; } } slash = memchr(pos, '/', filename_len - (pos - filename)); if (!slash) { /* this is a url like "phar://blah.phar" with no directory */ *ext_str = pos; *ext_len = strlen(pos); /* file extension must contain "phar" */ switch (phar_check_str(filename, *ext_str, *ext_len, executable, for_create TSRMLS_CC)) { case SUCCESS: return SUCCESS; case FAILURE: /* we are at the end of the string, so we fail */ return FAILURE; } } /* we've found an extension that ends at a directory separator */ *ext_str = pos; *ext_len = slash - pos; switch (phar_check_str(filename, *ext_str, *ext_len, executable, for_create TSRMLS_CC)) { case SUCCESS: return SUCCESS; case FAILURE: /* look for more extensions */ pos = strchr(pos + 1, '.'); if (pos) { *ext_str = NULL; *ext_len = 0; } goto next_extension; } return FAILURE; } /* }}} */ static int php_check_dots(const char *element, int n) /* {{{ */ { for(n--; n >= 0; --n) { if (element[n] != '.') { return 1; } } return 0; } /* }}} */ #define IS_DIRECTORY_UP(element, len) \ (len >= 2 && !php_check_dots(element, len)) #define IS_DIRECTORY_CURRENT(element, len) \ (len == 1 && element[0] == '.') #define IS_BACKSLASH(c) ((c) == '/') #ifdef COMPILE_DL_PHAR /* stupid-ass non-extern declaration in tsrm_strtok.h breaks dumbass MS compiler */ static inline int in_character_class(char ch, const char *delim) /* {{{ */ { while (*delim) { if (*delim == ch) { return 1; } ++delim; } return 0; } /* }}} */ char *tsrm_strtok_r(char *s, const char *delim, char **last) /* {{{ */ { char *token; if (s == NULL) { s = *last; } while (*s && in_character_class(*s, delim)) { ++s; } if (!*s) { return NULL; } token = s; while (*s && !in_character_class(*s, delim)) { ++s; } if (!*s) { *last = s; } else { *s = '\0'; *last = s + 1; } return token; } /* }}} */ #endif /** * Remove .. and . references within a phar filename */ char *phar_fix_filepath(char *path, int *new_len, int use_cwd TSRMLS_DC) /* {{{ */ { char newpath[MAXPATHLEN]; int newpath_len; char *ptr; char *tok; int ptr_length, path_length = *new_len; if (PHAR_G(cwd_len) && use_cwd && path_length > 2 && path[0] == '.' && path[1] == '/') { newpath_len = PHAR_G(cwd_len); memcpy(newpath, PHAR_G(cwd), newpath_len); } else { newpath[0] = '/'; newpath_len = 1; } ptr = path; if (*ptr == '/') { ++ptr; } tok = ptr; do { ptr = memchr(ptr, '/', path_length - (ptr - path)); } while (ptr && ptr - tok == 0 && *ptr == '/' && ++ptr && ++tok); if (!ptr && (path_length - (tok - path))) { switch (path_length - (tok - path)) { case 1: if (*tok == '.') { efree(path); *new_len = 1; return estrndup("/", 1); } break; case 2: if (tok[0] == '.' && tok[1] == '.') { efree(path); *new_len = 1; return estrndup("/", 1); } } return path; } while (ptr) { ptr_length = ptr - tok; last_time: if (IS_DIRECTORY_UP(tok, ptr_length)) { #define PREVIOUS newpath[newpath_len - 1] while (newpath_len > 1 && !IS_BACKSLASH(PREVIOUS)) { newpath_len--; } if (newpath[0] != '/') { newpath[newpath_len] = '\0'; } else if (newpath_len > 1) { --newpath_len; } } else if (!IS_DIRECTORY_CURRENT(tok, ptr_length)) { if (newpath_len > 1) { newpath[newpath_len++] = '/'; memcpy(newpath + newpath_len, tok, ptr_length+1); } else { memcpy(newpath + newpath_len, tok, ptr_length+1); } newpath_len += ptr_length; } if (ptr == path + path_length) { break; } tok = ++ptr; do { ptr = memchr(ptr, '/', path_length - (ptr - path)); } while (ptr && ptr - tok == 0 && *ptr == '/' && ++ptr && ++tok); if (!ptr && (path_length - (tok - path))) { ptr_length = path_length - (tok - path); ptr = path + path_length; goto last_time; } } efree(path); *new_len = newpath_len; return estrndup(newpath, newpath_len); } /* }}} */ /** * Process a phar stream name, ensuring we can handle any of: * * - whatever.phar * - whatever.phar.gz * - whatever.phar.bz2 * - whatever.phar.php * * Optionally the name might start with 'phar://' * * This is used by phar_parse_url() */ int phar_split_fname(char *filename, int filename_len, char **arch, int *arch_len, char **entry, int *entry_len, int executable, int for_create TSRMLS_DC) /* {{{ */ { const char *ext_str; #ifdef PHP_WIN32 char *save; #endif int ext_len, free_filename = 0; if (!strncasecmp(filename, "phar://", 7)) { filename += 7; filename_len -= 7; } ext_len = 0; #ifdef PHP_WIN32 free_filename = 1; save = filename; filename = estrndup(filename, filename_len); phar_unixify_path_separators(filename, filename_len); #endif if (phar_detect_phar_fname_ext(filename, filename_len, &ext_str, &ext_len, executable, for_create, 0 TSRMLS_CC) == FAILURE) { if (ext_len != -1) { if (!ext_str) { /* no / detected, restore arch for error message */ #ifdef PHP_WIN32 *arch = save; #else *arch = filename; #endif } if (free_filename) { efree(filename); } return FAILURE; } ext_len = 0; /* no extension detected - instead we are dealing with an alias */ } *arch_len = ext_str - filename + ext_len; *arch = estrndup(filename, *arch_len); if (ext_str[ext_len]) { *entry_len = filename_len - *arch_len; *entry = estrndup(ext_str+ext_len, *entry_len); #ifdef PHP_WIN32 phar_unixify_path_separators(*entry, *entry_len); #endif *entry = phar_fix_filepath(*entry, entry_len, 0 TSRMLS_CC); } else { *entry_len = 1; *entry = estrndup("/", 1); } if (free_filename) { efree(filename); } return SUCCESS; } /* }}} */ /** * Invoked when a user calls Phar::mapPhar() from within an executing .phar * to set up its manifest directly */ int phar_open_executed_filename(char *alias, int alias_len, char **error TSRMLS_DC) /* {{{ */ { char *fname; zval *halt_constant; php_stream *fp; int fname_len; char *actual = NULL; int ret; if (error) { *error = NULL; } fname = (char*)zend_get_executed_filename(TSRMLS_C); fname_len = strlen(fname); if (phar_open_parsed_phar(fname, fname_len, alias, alias_len, 0, REPORT_ERRORS, NULL, 0 TSRMLS_CC) == SUCCESS) { return SUCCESS; } if (!strcmp(fname, "[no active file]")) { if (error) { spprintf(error, 0, "cannot initialize a phar outside of PHP execution"); } return FAILURE; } MAKE_STD_ZVAL(halt_constant); if (0 == zend_get_constant("__COMPILER_HALT_OFFSET__", 24, halt_constant TSRMLS_CC)) { FREE_ZVAL(halt_constant); if (error) { spprintf(error, 0, "__HALT_COMPILER(); must be declared in a phar"); } return FAILURE; } FREE_ZVAL(halt_constant); #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { return FAILURE; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { return FAILURE; } fp = php_stream_open_wrapper(fname, "rb", IGNORE_URL|STREAM_MUST_SEEK|REPORT_ERRORS, &actual); if (!fp) { if (error) { spprintf(error, 0, "unable to open phar for reading \"%s\"", fname); } if (actual) { efree(actual); } return FAILURE; } if (actual) { fname = actual; fname_len = strlen(actual); } ret = phar_open_from_fp(fp, fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, 0, error TSRMLS_CC); if (actual) { efree(actual); } return ret; } /* }}} */ /** * Validate the CRC32 of a file opened from within the phar */ int phar_postprocess_file(phar_entry_data *idata, php_uint32 crc32, char **error, int process_zip TSRMLS_DC) /* {{{ */ { php_uint32 crc = ~0; int len = idata->internal_file->uncompressed_filesize; php_stream *fp = idata->fp; phar_entry_info *entry = idata->internal_file; if (error) { *error = NULL; } if (entry->is_zip && process_zip > 0) { /* verify local file header */ phar_zip_file_header local; phar_zip_data_desc desc; if (SUCCESS != phar_open_archive_fp(idata->phar TSRMLS_CC)) { spprintf(error, 0, "phar error: unable to open zip-based phar archive \"%s\" to verify local file header for file \"%s\"", idata->phar->fname, entry->filename); return FAILURE; } php_stream_seek(phar_get_entrypfp(idata->internal_file TSRMLS_CC), entry->header_offset, SEEK_SET); if (sizeof(local) != php_stream_read(phar_get_entrypfp(idata->internal_file TSRMLS_CC), (char *) &local, sizeof(local))) { spprintf(error, 0, "phar error: internal corruption of zip-based phar \"%s\" (cannot read local file header for file \"%s\")", idata->phar->fname, entry->filename); return FAILURE; } /* check for data descriptor */ if (((PHAR_ZIP_16(local.flags)) & 0x8) == 0x8) { php_stream_seek(phar_get_entrypfp(idata->internal_file TSRMLS_CC), entry->header_offset + sizeof(local) + PHAR_ZIP_16(local.filename_len) + PHAR_ZIP_16(local.extra_len) + entry->compressed_filesize, SEEK_SET); if (sizeof(desc) != php_stream_read(phar_get_entrypfp(idata->internal_file TSRMLS_CC), (char *) &desc, sizeof(desc))) { spprintf(error, 0, "phar error: internal corruption of zip-based phar \"%s\" (cannot read local data descriptor for file \"%s\")", idata->phar->fname, entry->filename); return FAILURE; } if (desc.signature[0] == 'P' && desc.signature[1] == 'K') { memcpy(&(local.crc32), &(desc.crc32), 12); } else { /* old data descriptors have no signature */ memcpy(&(local.crc32), &desc, 12); } } /* verify local header */ if (entry->filename_len != PHAR_ZIP_16(local.filename_len) || entry->crc32 != PHAR_ZIP_32(local.crc32) || entry->uncompressed_filesize != PHAR_ZIP_32(local.uncompsize) || entry->compressed_filesize != PHAR_ZIP_32(local.compsize)) { spprintf(error, 0, "phar error: internal corruption of zip-based phar \"%s\" (local header of file \"%s\" does not match central directory)", idata->phar->fname, entry->filename); return FAILURE; } /* construct actual offset to file start - local extra_len can be different from central extra_len */ entry->offset = entry->offset_abs = sizeof(local) + entry->header_offset + PHAR_ZIP_16(local.filename_len) + PHAR_ZIP_16(local.extra_len); if (idata->zero && idata->zero != entry->offset_abs) { idata->zero = entry->offset_abs; } } if (process_zip == 1) { return SUCCESS; } php_stream_seek(fp, idata->zero, SEEK_SET); while (len--) { CRC32(crc, php_stream_getc(fp)); } php_stream_seek(fp, idata->zero, SEEK_SET); if (~crc == crc32) { entry->is_crc_checked = 1; return SUCCESS; } else { spprintf(error, 0, "phar error: internal corruption of phar \"%s\" (crc32 mismatch on file \"%s\")", idata->phar->fname, entry->filename); return FAILURE; } } /* }}} */ static inline void phar_set_32(char *buffer, int var) /* {{{ */ { #ifdef WORDS_BIGENDIAN *((buffer) + 3) = (unsigned char) (((var) >> 24) & 0xFF); *((buffer) + 2) = (unsigned char) (((var) >> 16) & 0xFF); *((buffer) + 1) = (unsigned char) (((var) >> 8) & 0xFF); *((buffer) + 0) = (unsigned char) ((var) & 0xFF); #else memcpy(buffer, &var, sizeof(var)); #endif } /* }}} */ static int phar_flush_clean_deleted_apply(void *data TSRMLS_DC) /* {{{ */ { phar_entry_info *entry = (phar_entry_info *)data; if (entry->fp_refcount <= 0 && entry->is_deleted) { return ZEND_HASH_APPLY_REMOVE; } else { return ZEND_HASH_APPLY_KEEP; } } /* }}} */ #include "stub.h" char *phar_create_default_stub(const char *index_php, const char *web_index, size_t *len, char **error TSRMLS_DC) /* {{{ */ { char *stub = NULL; int index_len, web_len; size_t dummy; if (!len) { len = &dummy; } if (error) { *error = NULL; } if (!index_php) { index_php = "index.php"; } if (!web_index) { web_index = "index.php"; } index_len = strlen(index_php); web_len = strlen(web_index); if (index_len > 400) { /* ridiculous size not allowed for index.php startup filename */ if (error) { spprintf(error, 0, "Illegal filename passed in for stub creation, was %d characters long, and only 400 or less is allowed", index_len); return NULL; } } if (web_len > 400) { /* ridiculous size not allowed for index.php startup filename */ if (error) { spprintf(error, 0, "Illegal web filename passed in for stub creation, was %d characters long, and only 400 or less is allowed", web_len); return NULL; } } phar_get_stub(index_php, web_index, len, &stub, index_len+1, web_len+1 TSRMLS_CC); return stub; } /* }}} */ /** * Save phar contents to disk * * user_stub contains either a string, or a resource pointer, if len is a negative length. * user_stub and len should be both 0 if the default or existing stub should be used */ int phar_flush(phar_archive_data *phar, char *user_stub, long len, int convert, char **error TSRMLS_DC) /* {{{ */ { char halt_stub[] = "__HALT_COMPILER();"; char *newstub, *tmp; phar_entry_info *entry, *newentry; int halt_offset, restore_alias_len, global_flags = 0, closeoldfile; char *pos, has_dirs = 0; char manifest[18], entry_buffer[24]; off_t manifest_ftell; long offset; size_t wrote; php_uint32 manifest_len, mytime, loc, new_manifest_count; php_uint32 newcrc32; php_stream *file, *oldfile, *newfile, *stubfile; php_stream_filter *filter; php_serialize_data_t metadata_hash; smart_str main_metadata_str = {0}; int free_user_stub, free_fp = 1, free_ufp = 1; if (phar->is_persistent) { if (error) { spprintf(error, 0, "internal error: attempt to flush cached zip-based phar \"%s\"", phar->fname); } return EOF; } if (error) { *error = NULL; } if (!zend_hash_num_elements(&phar->manifest) && !user_stub) { return EOF; } zend_hash_clean(&phar->virtual_dirs); if (phar->is_zip) { return phar_zip_flush(phar, user_stub, len, convert, error TSRMLS_CC); } if (phar->is_tar) { return phar_tar_flush(phar, user_stub, len, convert, error TSRMLS_CC); } if (PHAR_G(readonly)) { return EOF; } if (phar->fp && !phar->is_brandnew) { oldfile = phar->fp; closeoldfile = 0; php_stream_rewind(oldfile); } else { oldfile = php_stream_open_wrapper(phar->fname, "rb", 0, NULL); closeoldfile = oldfile != NULL; } newfile = php_stream_fopen_tmpfile(); if (!newfile) { if (error) { spprintf(error, 0, "unable to create temporary file"); } if (closeoldfile) { php_stream_close(oldfile); } return EOF; } if (user_stub) { if (len < 0) { /* resource passed in */ if (!(php_stream_from_zval_no_verify(stubfile, (zval **)user_stub))) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to access resource to copy stub to new phar \"%s\"", phar->fname); } return EOF; } if (len == -1) { len = PHP_STREAM_COPY_ALL; } else { len = -len; } user_stub = 0; #if PHP_MAJOR_VERSION >= 6 if (!(len = php_stream_copy_to_mem(stubfile, (void **) &user_stub, len, 0)) || !user_stub) { #else if (!(len = php_stream_copy_to_mem(stubfile, &user_stub, len, 0)) || !user_stub) { #endif if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to read resource to copy stub to new phar \"%s\"", phar->fname); } return EOF; } free_user_stub = 1; } else { free_user_stub = 0; } tmp = estrndup(user_stub, len); if ((pos = php_stristr(tmp, halt_stub, len, sizeof(halt_stub) - 1)) == NULL) { efree(tmp); if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "illegal stub for phar \"%s\"", phar->fname); } if (free_user_stub) { efree(user_stub); } return EOF; } pos = user_stub + (pos - tmp); efree(tmp); len = pos - user_stub + 18; if ((size_t)len != php_stream_write(newfile, user_stub, len) || 5 != php_stream_write(newfile, " ?>\r\n", 5)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to create stub from string in new phar \"%s\"", phar->fname); } if (free_user_stub) { efree(user_stub); } return EOF; } phar->halt_offset = len + 5; if (free_user_stub) { efree(user_stub); } } else { size_t written; if (!user_stub && phar->halt_offset && oldfile && !phar->is_brandnew) { phar_stream_copy_to_stream(oldfile, newfile, phar->halt_offset, &written); newstub = NULL; } else { /* this is either a brand new phar or a default stub overwrite */ newstub = phar_create_default_stub(NULL, NULL, &(phar->halt_offset), NULL TSRMLS_CC); written = php_stream_write(newfile, newstub, phar->halt_offset); } if (phar->halt_offset != written) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { if (newstub) { spprintf(error, 0, "unable to create stub in new phar \"%s\"", phar->fname); } else { spprintf(error, 0, "unable to copy stub of old phar to new phar \"%s\"", phar->fname); } } if (newstub) { efree(newstub); } return EOF; } if (newstub) { efree(newstub); } } manifest_ftell = php_stream_tell(newfile); halt_offset = manifest_ftell; /* Check whether we can get rid of some of the deleted entries which are * unused. However some might still be in use so even after this clean-up * we need to skip entries marked is_deleted. */ zend_hash_apply(&phar->manifest, phar_flush_clean_deleted_apply TSRMLS_CC); /* compress as necessary, calculate crcs, serialize meta-data, manifest size, and file sizes */ main_metadata_str.c = 0; if (phar->metadata) { PHP_VAR_SERIALIZE_INIT(metadata_hash); php_var_serialize(&main_metadata_str, &phar->metadata, &metadata_hash TSRMLS_CC); PHP_VAR_SERIALIZE_DESTROY(metadata_hash); } else { main_metadata_str.len = 0; } new_manifest_count = 0; offset = 0; for (zend_hash_internal_pointer_reset(&phar->manifest); zend_hash_has_more_elements(&phar->manifest) == SUCCESS; zend_hash_move_forward(&phar->manifest)) { if (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) { continue; } if (entry->cfp) { /* did we forget to get rid of cfp last time? */ php_stream_close(entry->cfp); entry->cfp = 0; } if (entry->is_deleted || entry->is_mounted) { /* remove this from the new phar */ continue; } if (!entry->is_modified && entry->fp_refcount) { /* open file pointers refer to this fp, do not free the stream */ switch (entry->fp_type) { case PHAR_FP: free_fp = 0; break; case PHAR_UFP: free_ufp = 0; default: break; } } /* after excluding deleted files, calculate manifest size in bytes and number of entries */ ++new_manifest_count; phar_add_virtual_dirs(phar, entry->filename, entry->filename_len TSRMLS_CC); if (entry->is_dir) { /* we use this to calculate API version, 1.1.1 is used for phars with directories */ has_dirs = 1; } if (entry->metadata) { if (entry->metadata_str.c) { smart_str_free(&entry->metadata_str); } entry->metadata_str.c = 0; entry->metadata_str.len = 0; PHP_VAR_SERIALIZE_INIT(metadata_hash); php_var_serialize(&entry->metadata_str, &entry->metadata, &metadata_hash TSRMLS_CC); PHP_VAR_SERIALIZE_DESTROY(metadata_hash); } else { if (entry->metadata_str.c) { smart_str_free(&entry->metadata_str); } entry->metadata_str.c = 0; entry->metadata_str.len = 0; } /* 32 bits for filename length, length of filename, manifest + metadata, and add 1 for trailing / if a directory */ offset += 4 + entry->filename_len + sizeof(entry_buffer) + entry->metadata_str.len + (entry->is_dir ? 1 : 0); /* compress and rehash as necessary */ if ((oldfile && !entry->is_modified) || entry->is_dir) { if (entry->fp_type == PHAR_UFP) { /* reset so we can copy the compressed data over */ entry->fp_type = PHAR_FP; } continue; } if (!phar_get_efp(entry, 0 TSRMLS_CC)) { /* re-open internal file pointer just-in-time */ newentry = phar_open_jit(phar, entry, error TSRMLS_CC); if (!newentry) { /* major problem re-opening, so we ignore this file and the error */ efree(*error); *error = NULL; continue; } entry = newentry; } file = phar_get_efp(entry, 0 TSRMLS_CC); if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 1 TSRMLS_CC)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } newcrc32 = ~0; mytime = entry->uncompressed_filesize; for (loc = 0;loc < mytime; ++loc) { CRC32(newcrc32, php_stream_getc(file)); } entry->crc32 = ~newcrc32; entry->is_crc_checked = 1; if (!(entry->flags & PHAR_ENT_COMPRESSION_MASK)) { /* not compressed */ entry->compressed_filesize = entry->uncompressed_filesize; continue; } filter = php_stream_filter_create(phar_compress_filter(entry, 0), NULL, 0 TSRMLS_CC); if (!filter) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (entry->flags & PHAR_ENT_COMPRESSED_GZ) { if (error) { spprintf(error, 0, "unable to gzip compress file \"%s\" to new phar \"%s\"", entry->filename, phar->fname); } } else { if (error) { spprintf(error, 0, "unable to bzip2 compress file \"%s\" to new phar \"%s\"", entry->filename, phar->fname); } } return EOF; } /* create new file that holds the compressed version */ /* work around inability to specify freedom in write and strictness in read count */ entry->cfp = php_stream_fopen_tmpfile(); if (!entry->cfp) { if (error) { spprintf(error, 0, "unable to create temporary file"); } if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); return EOF; } php_stream_flush(file); if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 0 TSRMLS_CC)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } php_stream_filter_append((&entry->cfp->writefilters), filter); if (SUCCESS != phar_stream_copy_to_stream(file, entry->cfp, entry->uncompressed_filesize, NULL)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to copy compressed file contents of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } php_stream_filter_flush(filter, 1); php_stream_flush(entry->cfp); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_seek(entry->cfp, 0, SEEK_END); entry->compressed_filesize = (php_uint32) php_stream_tell(entry->cfp); /* generate crc on compressed file */ php_stream_rewind(entry->cfp); entry->old_flags = entry->flags; entry->is_modified = 1; global_flags |= (entry->flags & PHAR_ENT_COMPRESSION_MASK); } global_flags |= PHAR_HDR_SIGNATURE; /* write out manifest pre-header */ /* 4: manifest length * 4: manifest entry count * 2: phar version * 4: phar global flags * 4: alias length * ?: the alias itself * 4: phar metadata length * ?: phar metadata */ restore_alias_len = phar->alias_len; if (phar->is_temporary_alias) { phar->alias_len = 0; } manifest_len = offset + phar->alias_len + sizeof(manifest) + main_metadata_str.len; phar_set_32(manifest, manifest_len); phar_set_32(manifest+4, new_manifest_count); if (has_dirs) { *(manifest + 8) = (unsigned char) (((PHAR_API_VERSION) >> 8) & 0xFF); *(manifest + 9) = (unsigned char) (((PHAR_API_VERSION) & 0xF0)); } else { *(manifest + 8) = (unsigned char) (((PHAR_API_VERSION_NODIR) >> 8) & 0xFF); *(manifest + 9) = (unsigned char) (((PHAR_API_VERSION_NODIR) & 0xF0)); } phar_set_32(manifest+10, global_flags); phar_set_32(manifest+14, phar->alias_len); /* write the manifest header */ if (sizeof(manifest) != php_stream_write(newfile, manifest, sizeof(manifest)) || (size_t)phar->alias_len != php_stream_write(newfile, phar->alias, phar->alias_len)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); phar->alias_len = restore_alias_len; if (error) { spprintf(error, 0, "unable to write manifest header of new phar \"%s\"", phar->fname); } return EOF; } phar->alias_len = restore_alias_len; phar_set_32(manifest, main_metadata_str.len); if (4 != php_stream_write(newfile, manifest, 4) || (main_metadata_str.len && main_metadata_str.len != php_stream_write(newfile, main_metadata_str.c, main_metadata_str.len))) { smart_str_free(&main_metadata_str); if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); phar->alias_len = restore_alias_len; if (error) { spprintf(error, 0, "unable to write manifest meta-data of new phar \"%s\"", phar->fname); } return EOF; } smart_str_free(&main_metadata_str); /* re-calculate the manifest location to simplify later code */ manifest_ftell = php_stream_tell(newfile); /* now write the manifest */ for (zend_hash_internal_pointer_reset(&phar->manifest); zend_hash_has_more_elements(&phar->manifest) == SUCCESS; zend_hash_move_forward(&phar->manifest)) { if (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) { continue; } if (entry->is_deleted || entry->is_mounted) { /* remove this from the new phar if deleted, ignore if mounted */ continue; } if (entry->is_dir) { /* add 1 for trailing slash */ phar_set_32(entry_buffer, entry->filename_len + 1); } else { phar_set_32(entry_buffer, entry->filename_len); } if (4 != php_stream_write(newfile, entry_buffer, 4) || entry->filename_len != php_stream_write(newfile, entry->filename, entry->filename_len) || (entry->is_dir && 1 != php_stream_write(newfile, "/", 1))) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { if (entry->is_dir) { spprintf(error, 0, "unable to write filename of directory \"%s\" to manifest of new phar \"%s\"", entry->filename, phar->fname); } else { spprintf(error, 0, "unable to write filename of file \"%s\" to manifest of new phar \"%s\"", entry->filename, phar->fname); } } return EOF; } /* set the manifest meta-data: 4: uncompressed filesize 4: creation timestamp 4: compressed filesize 4: crc32 4: flags 4: metadata-len +: metadata */ mytime = time(NULL); phar_set_32(entry_buffer, entry->uncompressed_filesize); phar_set_32(entry_buffer+4, mytime); phar_set_32(entry_buffer+8, entry->compressed_filesize); phar_set_32(entry_buffer+12, entry->crc32); phar_set_32(entry_buffer+16, entry->flags); phar_set_32(entry_buffer+20, entry->metadata_str.len); if (sizeof(entry_buffer) != php_stream_write(newfile, entry_buffer, sizeof(entry_buffer)) || entry->metadata_str.len != php_stream_write(newfile, entry->metadata_str.c, entry->metadata_str.len)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to write temporary manifest of file \"%s\" to manifest of new phar \"%s\"", entry->filename, phar->fname); } return EOF; } } /* now copy the actual file data to the new phar */ offset = php_stream_tell(newfile); for (zend_hash_internal_pointer_reset(&phar->manifest); zend_hash_has_more_elements(&phar->manifest) == SUCCESS; zend_hash_move_forward(&phar->manifest)) { if (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) { continue; } if (entry->is_deleted || entry->is_dir || entry->is_mounted) { continue; } if (entry->cfp) { file = entry->cfp; php_stream_rewind(file); } else { file = phar_get_efp(entry, 0 TSRMLS_CC); if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 0 TSRMLS_CC)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } } if (!file) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } /* this will have changed for all files that have either changed compression or been modified */ entry->offset = entry->offset_abs = offset; offset += entry->compressed_filesize; if (phar_stream_copy_to_stream(file, newfile, entry->compressed_filesize, &wrote) == FAILURE) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to write contents of file \"%s\" to new phar \"%s\"", entry->filename, phar->fname); } return EOF; } entry->is_modified = 0; if (entry->cfp) { php_stream_close(entry->cfp); entry->cfp = NULL; } if (entry->fp_type == PHAR_MOD) { /* this fp is in use by a phar_entry_data returned by phar_get_entry_data, it will be closed when the phar_entry_data is phar_entry_delref'ed */ if (entry->fp_refcount == 0 && entry->fp != phar->fp && entry->fp != phar->ufp) { php_stream_close(entry->fp); } entry->fp = NULL; entry->fp_type = PHAR_FP; } else if (entry->fp_type == PHAR_UFP) { entry->fp_type = PHAR_FP; } } /* append signature */ if (global_flags & PHAR_HDR_SIGNATURE) { char sig_buf[4]; php_stream_rewind(newfile); if (phar->signature) { efree(phar->signature); phar->signature = NULL; } switch(phar->sig_flags) { #ifndef PHAR_HASH_OK case PHAR_SIG_SHA512: case PHAR_SIG_SHA256: if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to write contents of file \"%s\" to new phar \"%s\" with requested hash type", entry->filename, phar->fname); } return EOF; #endif default: { char *digest = NULL; int digest_len; if (FAILURE == phar_create_signature(phar, newfile, &digest, &digest_len, error TSRMLS_CC)) { if (error) { char *save = *error; spprintf(error, 0, "phar error: unable to write signature: %s", save); efree(save); } if (digest) { efree(digest); } if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); return EOF; } php_stream_write(newfile, digest, digest_len); efree(digest); if (phar->sig_flags == PHAR_SIG_OPENSSL) { phar_set_32(sig_buf, digest_len); php_stream_write(newfile, sig_buf, 4); } break; } } phar_set_32(sig_buf, phar->sig_flags); php_stream_write(newfile, sig_buf, 4); php_stream_write(newfile, "GBMB", 4); } /* finally, close the temp file, rename the original phar, move the temp to the old phar, unlink the old phar, and reload it into memory */ if (phar->fp && free_fp) { php_stream_close(phar->fp); } if (phar->ufp) { if (free_ufp) { php_stream_close(phar->ufp); } phar->ufp = NULL; } if (closeoldfile) { php_stream_close(oldfile); } phar->internal_file_start = halt_offset + manifest_len + 4; phar->halt_offset = halt_offset; phar->is_brandnew = 0; php_stream_rewind(newfile); if (phar->donotflush) { /* deferred flush */ phar->fp = newfile; } else { phar->fp = php_stream_open_wrapper(phar->fname, "w+b", IGNORE_URL|STREAM_MUST_SEEK|REPORT_ERRORS, NULL); if (!phar->fp) { phar->fp = newfile; if (error) { spprintf(error, 4096, "unable to open new phar \"%s\" for writing", phar->fname); } return EOF; } if (phar->flags & PHAR_FILE_COMPRESSED_GZ) { /* to properly compress, we have to tell zlib to add a zlib header */ zval filterparams; array_init(&filterparams); add_assoc_long(&filterparams, "window", MAX_WBITS+16); filter = php_stream_filter_create("zlib.deflate", &filterparams, php_stream_is_persistent(phar->fp) TSRMLS_CC); zval_dtor(&filterparams); if (!filter) { if (error) { spprintf(error, 4096, "unable to compress all contents of phar \"%s\" using zlib, PHP versions older than 5.2.6 have a buggy zlib", phar->fname); } return EOF; } php_stream_filter_append(&phar->fp->writefilters, filter); phar_stream_copy_to_stream(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL); php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(phar->fp); /* use the temp stream as our base */ phar->fp = newfile; } else if (phar->flags & PHAR_FILE_COMPRESSED_BZ2) { filter = php_stream_filter_create("bzip2.compress", NULL, php_stream_is_persistent(phar->fp) TSRMLS_CC); php_stream_filter_append(&phar->fp->writefilters, filter); phar_stream_copy_to_stream(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL); php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(phar->fp); /* use the temp stream as our base */ phar->fp = newfile; } else { phar_stream_copy_to_stream(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL); /* we could also reopen the file in "rb" mode but there is no need for that */ php_stream_close(newfile); } } if (-1 == php_stream_seek(phar->fp, phar->halt_offset, SEEK_SET)) { if (error) { spprintf(error, 0, "unable to seek to __HALT_COMPILER(); in new phar \"%s\"", phar->fname); } return EOF; } return EOF; } /* }}} */ #ifdef COMPILE_DL_PHAR ZEND_GET_MODULE(phar) #endif /* {{{ phar_functions[] * * Every user visible function must have an entry in phar_functions[]. */ zend_function_entry phar_functions[] = { PHP_FE_END }; /* }}}*/ static size_t phar_zend_stream_reader(void *handle, char *buf, size_t len TSRMLS_DC) /* {{{ */ { return php_stream_read(phar_get_pharfp((phar_archive_data*)handle TSRMLS_CC), buf, len); } /* }}} */ #if PHP_VERSION_ID >= 50300 static size_t phar_zend_stream_fsizer(void *handle TSRMLS_DC) /* {{{ */ { return ((phar_archive_data*)handle)->halt_offset + 32; } /* }}} */ #else /* PHP_VERSION_ID */ static long phar_stream_fteller_for_zend(void *handle TSRMLS_DC) /* {{{ */ { return (long)php_stream_tell(phar_get_pharfp((phar_archive_data*)handle TSRMLS_CC)); } /* }}} */ #endif zend_op_array *(*phar_orig_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); #if PHP_VERSION_ID >= 50300 #define phar_orig_zend_open zend_stream_open_function static char *phar_resolve_path(const char *filename, int filename_len TSRMLS_DC) { return phar_find_in_include_path((char *) filename, filename_len, NULL TSRMLS_CC); } #else int (*phar_orig_zend_open)(const char *filename, zend_file_handle *handle TSRMLS_DC); #endif static zend_op_array *phar_compile_file(zend_file_handle *file_handle, int type TSRMLS_DC) /* {{{ */ { zend_op_array *res; char *name = NULL; int failed; phar_archive_data *phar; if (!file_handle || !file_handle->filename) { return phar_orig_compile_file(file_handle, type TSRMLS_CC); } if (strstr(file_handle->filename, ".phar") && !strstr(file_handle->filename, "://")) { if (SUCCESS == phar_open_from_filename((char*)file_handle->filename, strlen(file_handle->filename), NULL, 0, 0, &phar, NULL TSRMLS_CC)) { if (phar->is_zip || phar->is_tar) { zend_file_handle f = *file_handle; /* zip or tar-based phar */ spprintf(&name, 4096, "phar://%s/%s", file_handle->filename, ".phar/stub.php"); if (SUCCESS == phar_orig_zend_open((const char *)name, file_handle TSRMLS_CC)) { efree(name); name = NULL; file_handle->filename = f.filename; if (file_handle->opened_path) { efree(file_handle->opened_path); } file_handle->opened_path = f.opened_path; file_handle->free_filename = f.free_filename; } else { *file_handle = f; } } else if (phar->flags & PHAR_FILE_COMPRESSION_MASK) { /* compressed phar */ #if PHP_VERSION_ID >= 50300 file_handle->type = ZEND_HANDLE_STREAM; /* we do our own reading directly from the phar, don't change the next line */ file_handle->handle.stream.handle = phar; file_handle->handle.stream.reader = phar_zend_stream_reader; file_handle->handle.stream.closer = NULL; file_handle->handle.stream.fsizer = phar_zend_stream_fsizer; file_handle->handle.stream.isatty = 0; phar->is_persistent ? php_stream_rewind(PHAR_GLOBALS->cached_fp[phar->phar_pos].fp) : php_stream_rewind(phar->fp); memset(&file_handle->handle.stream.mmap, 0, sizeof(file_handle->handle.stream.mmap)); #else /* PHP_VERSION_ID */ file_handle->type = ZEND_HANDLE_STREAM; /* we do our own reading directly from the phar, don't change the next line */ file_handle->handle.stream.handle = phar; file_handle->handle.stream.reader = phar_zend_stream_reader; file_handle->handle.stream.closer = NULL; /* don't close - let phar handle this one */ file_handle->handle.stream.fteller = phar_stream_fteller_for_zend; file_handle->handle.stream.interactive = 0; phar->is_persistent ? php_stream_rewind(PHAR_GLOBALS->cached_fp[phar->phar_pos].fp) : php_stream_rewind(phar->fp); #endif } } } zend_try { failed = 0; res = phar_orig_compile_file(file_handle, type TSRMLS_CC); } zend_catch { failed = 1; res = NULL; } zend_end_try(); if (name) { efree(name); } if (failed) { zend_bailout(); } return res; } /* }}} */ #if PHP_VERSION_ID < 50300 int phar_zend_open(const char *filename, zend_file_handle *handle TSRMLS_DC) /* {{{ */ { char *arch, *entry; int arch_len, entry_len; /* this code is obsoleted in php 5.3 */ entry = (char *) filename; if (!IS_ABSOLUTE_PATH(entry, strlen(entry)) && !strstr(entry, "://")) { phar_archive_data **pphar = NULL; char *fname; int fname_len; fname = (char*)zend_get_executed_filename(TSRMLS_C); fname_len = strlen(fname); if (fname_len > 7 && !strncasecmp(fname, "phar://", 7)) { if (SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 1, 0 TSRMLS_CC)) { zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), arch, arch_len, (void **) &pphar); if (!pphar && PHAR_G(manifest_cached)) { zend_hash_find(&cached_phars, arch, arch_len, (void **) &pphar); } efree(arch); efree(entry); } } /* retrieving an include within the current directory, so use this if possible */ if (!(entry = phar_find_in_include_path((char *) filename, strlen(filename), NULL TSRMLS_CC))) { /* this file is not in the phar, use the original path */ goto skip_phar; } if (SUCCESS == phar_orig_zend_open(entry, handle TSRMLS_CC)) { if (!handle->opened_path) { handle->opened_path = entry; } if (entry != filename) { handle->free_filename = 1; } return SUCCESS; } if (entry != filename) { efree(entry); } return FAILURE; } skip_phar: return phar_orig_zend_open(filename, handle TSRMLS_CC); } /* }}} */ #endif typedef zend_op_array* (zend_compile_t)(zend_file_handle*, int TSRMLS_DC); typedef zend_compile_t* (compile_hook)(zend_compile_t *ptr); PHP_GINIT_FUNCTION(phar) /* {{{ */ { phar_mime_type mime; memset(phar_globals, 0, sizeof(zend_phar_globals)); phar_globals->readonly = 1; zend_hash_init(&phar_globals->mime_types, 0, NULL, NULL, 1); #define PHAR_SET_MIME(mimetype, ret, fileext) \ mime.mime = mimetype; \ mime.len = sizeof((mimetype))+1; \ mime.type = ret; \ zend_hash_add(&phar_globals->mime_types, fileext, sizeof(fileext)-1, (void *)&mime, sizeof(phar_mime_type), NULL); \ PHAR_SET_MIME("text/html", PHAR_MIME_PHPS, "phps") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "c") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "cc") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "cpp") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "c++") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "dtd") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "h") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "log") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "rng") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "txt") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "xsd") PHAR_SET_MIME("", PHAR_MIME_PHP, "php") PHAR_SET_MIME("", PHAR_MIME_PHP, "inc") PHAR_SET_MIME("video/avi", PHAR_MIME_OTHER, "avi") PHAR_SET_MIME("image/bmp", PHAR_MIME_OTHER, "bmp") PHAR_SET_MIME("text/css", PHAR_MIME_OTHER, "css") PHAR_SET_MIME("image/gif", PHAR_MIME_OTHER, "gif") PHAR_SET_MIME("text/html", PHAR_MIME_OTHER, "htm") PHAR_SET_MIME("text/html", PHAR_MIME_OTHER, "html") PHAR_SET_MIME("text/html", PHAR_MIME_OTHER, "htmls") PHAR_SET_MIME("image/x-ico", PHAR_MIME_OTHER, "ico") PHAR_SET_MIME("image/jpeg", PHAR_MIME_OTHER, "jpe") PHAR_SET_MIME("image/jpeg", PHAR_MIME_OTHER, "jpg") PHAR_SET_MIME("image/jpeg", PHAR_MIME_OTHER, "jpeg") PHAR_SET_MIME("application/x-javascript", PHAR_MIME_OTHER, "js") PHAR_SET_MIME("audio/midi", PHAR_MIME_OTHER, "midi") PHAR_SET_MIME("audio/midi", PHAR_MIME_OTHER, "mid") PHAR_SET_MIME("audio/mod", PHAR_MIME_OTHER, "mod") PHAR_SET_MIME("movie/quicktime", PHAR_MIME_OTHER, "mov") PHAR_SET_MIME("audio/mp3", PHAR_MIME_OTHER, "mp3") PHAR_SET_MIME("video/mpeg", PHAR_MIME_OTHER, "mpg") PHAR_SET_MIME("video/mpeg", PHAR_MIME_OTHER, "mpeg") PHAR_SET_MIME("application/pdf", PHAR_MIME_OTHER, "pdf") PHAR_SET_MIME("image/png", PHAR_MIME_OTHER, "png") PHAR_SET_MIME("application/shockwave-flash", PHAR_MIME_OTHER, "swf") PHAR_SET_MIME("image/tiff", PHAR_MIME_OTHER, "tif") PHAR_SET_MIME("image/tiff", PHAR_MIME_OTHER, "tiff") PHAR_SET_MIME("audio/wav", PHAR_MIME_OTHER, "wav") PHAR_SET_MIME("image/xbm", PHAR_MIME_OTHER, "xbm") PHAR_SET_MIME("text/xml", PHAR_MIME_OTHER, "xml") phar_restore_orig_functions(TSRMLS_C); } /* }}} */ PHP_GSHUTDOWN_FUNCTION(phar) /* {{{ */ { zend_hash_destroy(&phar_globals->mime_types); } /* }}} */ PHP_MINIT_FUNCTION(phar) /* {{{ */ { REGISTER_INI_ENTRIES(); phar_orig_compile_file = zend_compile_file; zend_compile_file = phar_compile_file; #if PHP_VERSION_ID >= 50300 phar_save_resolve_path = zend_resolve_path; zend_resolve_path = phar_resolve_path; #else phar_orig_zend_open = zend_stream_open_function; zend_stream_open_function = phar_zend_open; #endif phar_object_init(TSRMLS_C); phar_intercept_functions_init(TSRMLS_C); phar_save_orig_functions(TSRMLS_C); return php_register_url_stream_wrapper("phar", &php_stream_phar_wrapper TSRMLS_CC); } /* }}} */ PHP_MSHUTDOWN_FUNCTION(phar) /* {{{ */ { php_unregister_url_stream_wrapper("phar" TSRMLS_CC); phar_intercept_functions_shutdown(TSRMLS_C); if (zend_compile_file == phar_compile_file) { zend_compile_file = phar_orig_compile_file; } #if PHP_VERSION_ID < 50300 if (zend_stream_open_function == phar_zend_open) { zend_stream_open_function = phar_orig_zend_open; } #endif if (PHAR_G(manifest_cached)) { zend_hash_destroy(&(cached_phars)); zend_hash_destroy(&(cached_alias)); } return SUCCESS; } /* }}} */ void phar_request_initialize(TSRMLS_D) /* {{{ */ { if (!PHAR_GLOBALS->request_init) { PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; PHAR_G(has_bz2) = zend_hash_exists(&module_registry, "bz2", sizeof("bz2")); PHAR_G(has_zlib) = zend_hash_exists(&module_registry, "zlib", sizeof("zlib")); PHAR_GLOBALS->request_init = 1; PHAR_GLOBALS->request_ends = 0; PHAR_GLOBALS->request_done = 0; zend_hash_init(&(PHAR_GLOBALS->phar_fname_map), 5, zend_get_hash_value, destroy_phar_data, 0); zend_hash_init(&(PHAR_GLOBALS->phar_persist_map), 5, zend_get_hash_value, NULL, 0); zend_hash_init(&(PHAR_GLOBALS->phar_alias_map), 5, zend_get_hash_value, NULL, 0); if (PHAR_G(manifest_cached)) { phar_archive_data **pphar; phar_entry_fp *stuff = (phar_entry_fp *) ecalloc(zend_hash_num_elements(&cached_phars), sizeof(phar_entry_fp)); for (zend_hash_internal_pointer_reset(&cached_phars); zend_hash_get_current_data(&cached_phars, (void **)&pphar) == SUCCESS; zend_hash_move_forward(&cached_phars)) { stuff[pphar[0]->phar_pos].manifest = (phar_entry_fp_info *) ecalloc( zend_hash_num_elements(&(pphar[0]->manifest)), sizeof(phar_entry_fp_info)); } PHAR_GLOBALS->cached_fp = stuff; } PHAR_GLOBALS->phar_SERVER_mung_list = 0; PHAR_G(cwd) = NULL; PHAR_G(cwd_len) = 0; PHAR_G(cwd_init) = 0; } } /* }}} */ PHP_RSHUTDOWN_FUNCTION(phar) /* {{{ */ { int i; PHAR_GLOBALS->request_ends = 1; if (PHAR_GLOBALS->request_init) { phar_release_functions(TSRMLS_C); zend_hash_destroy(&(PHAR_GLOBALS->phar_alias_map)); PHAR_GLOBALS->phar_alias_map.arBuckets = NULL; zend_hash_destroy(&(PHAR_GLOBALS->phar_fname_map)); PHAR_GLOBALS->phar_fname_map.arBuckets = NULL; zend_hash_destroy(&(PHAR_GLOBALS->phar_persist_map)); PHAR_GLOBALS->phar_persist_map.arBuckets = NULL; PHAR_GLOBALS->phar_SERVER_mung_list = 0; if (PHAR_GLOBALS->cached_fp) { for (i = 0; i < zend_hash_num_elements(&cached_phars); ++i) { if (PHAR_GLOBALS->cached_fp[i].fp) { php_stream_close(PHAR_GLOBALS->cached_fp[i].fp); } if (PHAR_GLOBALS->cached_fp[i].ufp) { php_stream_close(PHAR_GLOBALS->cached_fp[i].ufp); } efree(PHAR_GLOBALS->cached_fp[i].manifest); } efree(PHAR_GLOBALS->cached_fp); PHAR_GLOBALS->cached_fp = 0; } PHAR_GLOBALS->request_init = 0; if (PHAR_G(cwd)) { efree(PHAR_G(cwd)); } PHAR_G(cwd) = NULL; PHAR_G(cwd_len) = 0; PHAR_G(cwd_init) = 0; } PHAR_GLOBALS->request_done = 1; return SUCCESS; } /* }}} */ PHP_MINFO_FUNCTION(phar) /* {{{ */ { phar_request_initialize(TSRMLS_C); php_info_print_table_start(); php_info_print_table_header(2, "Phar: PHP Archive support", "enabled"); php_info_print_table_row(2, "Phar EXT version", PHP_PHAR_VERSION); php_info_print_table_row(2, "Phar API version", PHP_PHAR_API_VERSION); php_info_print_table_row(2, "SVN revision", "$Revision$"); php_info_print_table_row(2, "Phar-based phar archives", "enabled"); php_info_print_table_row(2, "Tar-based phar archives", "enabled"); php_info_print_table_row(2, "ZIP-based phar archives", "enabled"); if (PHAR_G(has_zlib)) { php_info_print_table_row(2, "gzip compression", "enabled"); } else { php_info_print_table_row(2, "gzip compression", "disabled (install ext/zlib)"); } if (PHAR_G(has_bz2)) { php_info_print_table_row(2, "bzip2 compression", "enabled"); } else { php_info_print_table_row(2, "bzip2 compression", "disabled (install pecl/bz2)"); } #ifdef PHAR_HAVE_OPENSSL php_info_print_table_row(2, "Native OpenSSL support", "enabled"); #else if (zend_hash_exists(&module_registry, "openssl", sizeof("openssl"))) { php_info_print_table_row(2, "OpenSSL support", "enabled"); } else { php_info_print_table_row(2, "OpenSSL support", "disabled (install ext/openssl)"); } #endif php_info_print_table_end(); php_info_print_box_start(0); PUTS("Phar based on pear/PHP_Archive, original concept by Davey Shafik."); PUTS(!sapi_module.phpinfo_as_text?"<br />":"\n"); PUTS("Phar fully realized by Gregory Beaver and Marcus Boerger."); PUTS(!sapi_module.phpinfo_as_text?"<br />":"\n"); PUTS("Portions of tar implementation Copyright (c) 2003-2009 Tim Kientzle."); php_info_print_box_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ /* {{{ phar_module_entry */ static const zend_module_dep phar_deps[] = { ZEND_MOD_OPTIONAL("apc") ZEND_MOD_OPTIONAL("bz2") ZEND_MOD_OPTIONAL("openssl") ZEND_MOD_OPTIONAL("zlib") ZEND_MOD_OPTIONAL("standard") #if defined(HAVE_HASH) && !defined(COMPILE_DL_HASH) ZEND_MOD_REQUIRED("hash") #endif #if HAVE_SPL ZEND_MOD_REQUIRED("spl") #endif ZEND_MOD_END }; zend_module_entry phar_module_entry = { STANDARD_MODULE_HEADER_EX, NULL, phar_deps, "Phar", phar_functions, PHP_MINIT(phar), PHP_MSHUTDOWN(phar), NULL, PHP_RSHUTDOWN(phar), PHP_MINFO(phar), PHP_PHAR_VERSION, PHP_MODULE_GLOBALS(phar), /* globals descriptor */ PHP_GINIT(phar), /* globals ctor */ PHP_GSHUTDOWN(phar), /* globals dtor */ NULL, /* post deactivate */ STANDARD_MODULE_PROPERTIES_EX }; /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-11-19-eeba0b5681-f330c8ab4e.c
manybugs_data_19
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Derick Rethans <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "php.h" #include "php_streams.h" #include "php_main.h" #include "php_globals.h" #include "php_ini.h" #include "ext/standard/info.h" #include "ext/standard/php_versioning.h" #include "ext/standard/php_math.h" #include "php_date.h" #include "zend_interfaces.h" #include "lib/timelib.h" #include <time.h> #ifdef PHP_WIN32 static __inline __int64 php_date_llabs( __int64 i ) { return i >= 0? i: -i; } #elif defined(__GNUC__) && __GNUC__ < 3 static __inline __int64_t php_date_llabs( __int64_t i ) { return i >= 0 ? i : -i; } #else static inline long long php_date_llabs( long long i ) { return i >= 0 ? i : -i; } #endif /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_date, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_gmdate, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_idate, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strtotime, 0, 0, 1) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, now) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mktime, 0, 0, 0) ZEND_ARG_INFO(0, hour) ZEND_ARG_INFO(0, min) ZEND_ARG_INFO(0, sec) ZEND_ARG_INFO(0, mon) ZEND_ARG_INFO(0, day) ZEND_ARG_INFO(0, year) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_gmmktime, 0, 0, 0) ZEND_ARG_INFO(0, hour) ZEND_ARG_INFO(0, min) ZEND_ARG_INFO(0, sec) ZEND_ARG_INFO(0, mon) ZEND_ARG_INFO(0, day) ZEND_ARG_INFO(0, year) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_checkdate, 0) ZEND_ARG_INFO(0, month) ZEND_ARG_INFO(0, day) ZEND_ARG_INFO(0, year) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strftime, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_gmstrftime, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_time, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_localtime, 0, 0, 0) ZEND_ARG_INFO(0, timestamp) ZEND_ARG_INFO(0, associative_array) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_getdate, 0, 0, 0) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_default_timezone_set, 0) ZEND_ARG_INFO(0, timezone_identifier) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_default_timezone_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_sunrise, 0, 0, 1) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, latitude) ZEND_ARG_INFO(0, longitude) ZEND_ARG_INFO(0, zenith) ZEND_ARG_INFO(0, gmt_offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_sunset, 0, 0, 1) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, latitude) ZEND_ARG_INFO(0, longitude) ZEND_ARG_INFO(0, zenith) ZEND_ARG_INFO(0, gmt_offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_sun_info, 0) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, latitude) ZEND_ARG_INFO(0, longitude) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_create, 0, 0, 0) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_create_from_format, 0, 0, 2) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_parse, 0, 0, 1) ZEND_ARG_INFO(0, date) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_parse_from_format, 0, 0, 2) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, date) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_get_last_errors, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_format, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_format, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_modify, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, modify) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_modify, 0, 0, 1) ZEND_ARG_INFO(0, modify) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_add, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, interval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_add, 0, 0, 1) ZEND_ARG_INFO(0, interval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_sub, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, interval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_sub, 0, 0, 1) ZEND_ARG_INFO(0, interval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_timezone_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_method_timezone_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_timezone_set, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, timezone) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_timezone_set, 0, 0, 1) ZEND_ARG_INFO(0, timezone) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_offset_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_method_offset_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_diff, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, object2) ZEND_ARG_INFO(0, absolute) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_diff, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, absolute) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_time_set, 0, 0, 3) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, hour) ZEND_ARG_INFO(0, minute) ZEND_ARG_INFO(0, second) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_time_set, 0, 0, 2) ZEND_ARG_INFO(0, hour) ZEND_ARG_INFO(0, minute) ZEND_ARG_INFO(0, second) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_date_set, 0, 0, 4) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, year) ZEND_ARG_INFO(0, month) ZEND_ARG_INFO(0, day) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_date_set, 0, 0, 3) ZEND_ARG_INFO(0, year) ZEND_ARG_INFO(0, month) ZEND_ARG_INFO(0, day) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_isodate_set, 0, 0, 3) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, year) ZEND_ARG_INFO(0, week) ZEND_ARG_INFO(0, day) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_isodate_set, 0, 0, 2) ZEND_ARG_INFO(0, year) ZEND_ARG_INFO(0, week) ZEND_ARG_INFO(0, day) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_timestamp_set, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, unixtimestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_timestamp_set, 0, 0, 1) ZEND_ARG_INFO(0, unixtimestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_timestamp_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_method_timestamp_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_open, 0, 0, 1) ZEND_ARG_INFO(0, timezone) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_name_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_method_name_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_name_from_abbr, 0, 0, 1) ZEND_ARG_INFO(0, abbr) ZEND_ARG_INFO(0, gmtoffset) ZEND_ARG_INFO(0, isdst) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_offset_get, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, datetime) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_method_offset_get, 0, 0, 1) ZEND_ARG_INFO(0, datetime) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_transitions_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, timestamp_begin) ZEND_ARG_INFO(0, timestamp_end) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_method_transitions_get, 0) ZEND_ARG_INFO(0, timestamp_begin) ZEND_ARG_INFO(0, timestamp_end) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_location_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_method_location_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_identifiers_list, 0, 0, 0) ZEND_ARG_INFO(0, what) ZEND_ARG_INFO(0, country) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_abbreviations_list, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_version_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_interval_create_from_date_string, 0, 0, 1) ZEND_ARG_INFO(0, time) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_interval_format, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_method_interval_format, 0) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_period_construct, 0, 0, 3) ZEND_ARG_INFO(0, start) ZEND_ARG_INFO(0, interval) ZEND_ARG_INFO(0, end) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_interval_construct, 0, 0, 0) ZEND_ARG_INFO(0, interval_spec) ZEND_END_ARG_INFO() /* }}} */ /* {{{ Function table */ const zend_function_entry date_functions[] = { PHP_FE(strtotime, arginfo_strtotime) PHP_FE(date, arginfo_date) PHP_FE(idate, arginfo_idate) PHP_FE(gmdate, arginfo_gmdate) PHP_FE(mktime, arginfo_mktime) PHP_FE(gmmktime, arginfo_gmmktime) PHP_FE(checkdate, arginfo_checkdate) #ifdef HAVE_STRFTIME PHP_FE(strftime, arginfo_strftime) PHP_FE(gmstrftime, arginfo_gmstrftime) #endif PHP_FE(time, arginfo_time) PHP_FE(localtime, arginfo_localtime) PHP_FE(getdate, arginfo_getdate) /* Advanced Interface */ PHP_FE(date_create, arginfo_date_create) PHP_FE(date_create_from_format, arginfo_date_create_from_format) PHP_FE(date_parse, arginfo_date_parse) PHP_FE(date_parse_from_format, arginfo_date_parse_from_format) PHP_FE(date_get_last_errors, arginfo_date_get_last_errors) PHP_FE(date_format, arginfo_date_format) PHP_FE(date_modify, arginfo_date_modify) PHP_FE(date_add, arginfo_date_add) PHP_FE(date_sub, arginfo_date_sub) PHP_FE(date_timezone_get, arginfo_date_timezone_get) PHP_FE(date_timezone_set, arginfo_date_timezone_set) PHP_FE(date_offset_get, arginfo_date_offset_get) PHP_FE(date_diff, arginfo_date_diff) PHP_FE(date_time_set, arginfo_date_time_set) PHP_FE(date_date_set, arginfo_date_date_set) PHP_FE(date_isodate_set, arginfo_date_isodate_set) PHP_FE(date_timestamp_set, arginfo_date_timestamp_set) PHP_FE(date_timestamp_get, arginfo_date_timestamp_get) PHP_FE(timezone_open, arginfo_timezone_open) PHP_FE(timezone_name_get, arginfo_timezone_name_get) PHP_FE(timezone_name_from_abbr, arginfo_timezone_name_from_abbr) PHP_FE(timezone_offset_get, arginfo_timezone_offset_get) PHP_FE(timezone_transitions_get, arginfo_timezone_transitions_get) PHP_FE(timezone_location_get, arginfo_timezone_location_get) PHP_FE(timezone_identifiers_list, arginfo_timezone_identifiers_list) PHP_FE(timezone_abbreviations_list, arginfo_timezone_abbreviations_list) PHP_FE(timezone_version_get, arginfo_timezone_version_get) PHP_FE(date_interval_create_from_date_string, arginfo_date_interval_create_from_date_string) PHP_FE(date_interval_format, arginfo_date_interval_format) /* Options and Configuration */ PHP_FE(date_default_timezone_set, arginfo_date_default_timezone_set) PHP_FE(date_default_timezone_get, arginfo_date_default_timezone_get) /* Astronomical functions */ PHP_FE(date_sunrise, arginfo_date_sunrise) PHP_FE(date_sunset, arginfo_date_sunset) PHP_FE(date_sun_info, arginfo_date_sun_info) {NULL, NULL, NULL} }; const zend_function_entry date_funcs_date[] = { PHP_ME(DateTime, __construct, arginfo_date_create, ZEND_ACC_CTOR|ZEND_ACC_PUBLIC) PHP_ME(DateTime, __wakeup, NULL, ZEND_ACC_PUBLIC) PHP_ME(DateTime, __set_state, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_ME_MAPPING(createFromFormat, date_create_from_format, arginfo_date_create_from_format, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_ME_MAPPING(getLastErrors, date_get_last_errors, arginfo_date_get_last_errors, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_ME_MAPPING(format, date_format, arginfo_date_method_format, 0) PHP_ME_MAPPING(modify, date_modify, arginfo_date_method_modify, 0) PHP_ME_MAPPING(add, date_add, arginfo_date_method_add, 0) PHP_ME_MAPPING(sub, date_sub, arginfo_date_method_sub, 0) PHP_ME_MAPPING(getTimezone, date_timezone_get, arginfo_date_method_timezone_get, 0) PHP_ME_MAPPING(setTimezone, date_timezone_set, arginfo_date_method_timezone_set, 0) PHP_ME_MAPPING(getOffset, date_offset_get, arginfo_date_method_offset_get, 0) PHP_ME_MAPPING(setTime, date_time_set, arginfo_date_method_time_set, 0) PHP_ME_MAPPING(setDate, date_date_set, arginfo_date_method_date_set, 0) PHP_ME_MAPPING(setISODate, date_isodate_set, arginfo_date_method_isodate_set, 0) PHP_ME_MAPPING(setTimestamp, date_timestamp_set, arginfo_date_method_timestamp_set, 0) PHP_ME_MAPPING(getTimestamp, date_timestamp_get, arginfo_date_method_timestamp_get, 0) PHP_ME_MAPPING(diff, date_diff, arginfo_date_method_diff, 0) {NULL, NULL, NULL} }; const zend_function_entry date_funcs_timezone[] = { PHP_ME(DateTimeZone, __construct, arginfo_timezone_open, ZEND_ACC_CTOR|ZEND_ACC_PUBLIC) PHP_ME_MAPPING(getName, timezone_name_get, arginfo_timezone_method_name_get, 0) PHP_ME_MAPPING(getOffset, timezone_offset_get, arginfo_timezone_method_offset_get, 0) PHP_ME_MAPPING(getTransitions, timezone_transitions_get, arginfo_timezone_method_transitions_get, 0) PHP_ME_MAPPING(getLocation, timezone_location_get, arginfo_timezone_method_location_get, 0) PHP_ME_MAPPING(listAbbreviations, timezone_abbreviations_list, arginfo_timezone_abbreviations_list, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_ME_MAPPING(listIdentifiers, timezone_identifiers_list, arginfo_timezone_identifiers_list, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) {NULL, NULL, NULL} }; const zend_function_entry date_funcs_interval[] = { PHP_ME(DateInterval, __construct, arginfo_date_interval_construct, ZEND_ACC_CTOR|ZEND_ACC_PUBLIC) PHP_ME_MAPPING(format, date_interval_format, arginfo_date_method_interval_format, 0) PHP_ME_MAPPING(createFromDateString, date_interval_create_from_date_string, arginfo_date_interval_create_from_date_string, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) {NULL, NULL, NULL} }; const zend_function_entry date_funcs_period[] = { PHP_ME(DatePeriod, __construct, arginfo_date_period_construct, ZEND_ACC_CTOR|ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; static char* guess_timezone(const timelib_tzdb *tzdb TSRMLS_DC); static void date_register_classes(TSRMLS_D); /* }}} */ ZEND_DECLARE_MODULE_GLOBALS(date) static PHP_GINIT_FUNCTION(date); /* True global */ timelib_tzdb *php_date_global_timezone_db; int php_date_global_timezone_db_enabled; #define DATE_DEFAULT_LATITUDE "31.7667" #define DATE_DEFAULT_LONGITUDE "35.2333" /* on 90'35; common sunset declaration (start of sun body appear) */ #define DATE_SUNSET_ZENITH "90.583333" /* on 90'35; common sunrise declaration (sun body disappeared) */ #define DATE_SUNRISE_ZENITH "90.583333" /* {{{ INI Settings */ PHP_INI_BEGIN() STD_PHP_INI_ENTRY("date.timezone", "", PHP_INI_ALL, OnUpdateString, default_timezone, zend_date_globals, date_globals) PHP_INI_ENTRY("date.default_latitude", DATE_DEFAULT_LATITUDE, PHP_INI_ALL, NULL) PHP_INI_ENTRY("date.default_longitude", DATE_DEFAULT_LONGITUDE, PHP_INI_ALL, NULL) PHP_INI_ENTRY("date.sunset_zenith", DATE_SUNSET_ZENITH, PHP_INI_ALL, NULL) PHP_INI_ENTRY("date.sunrise_zenith", DATE_SUNRISE_ZENITH, PHP_INI_ALL, NULL) PHP_INI_END() /* }}} */ zend_class_entry *date_ce_date, *date_ce_timezone, *date_ce_interval, *date_ce_period; PHPAPI zend_class_entry *php_date_get_date_ce(void) { return date_ce_date; } PHPAPI zend_class_entry *php_date_get_timezone_ce(void) { return date_ce_timezone; } static zend_object_handlers date_object_handlers_date; static zend_object_handlers date_object_handlers_timezone; static zend_object_handlers date_object_handlers_interval; static zend_object_handlers date_object_handlers_period; #define DATE_SET_CONTEXT \ zval *object; \ object = getThis(); \ #define DATE_FETCH_OBJECT \ php_date_obj *obj; \ DATE_SET_CONTEXT; \ if (object) { \ if (zend_parse_parameters_none() == FAILURE) { \ return; \ } \ } else { \ if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, NULL, "O", &object, date_ce_date) == FAILURE) { \ RETURN_FALSE; \ } \ } \ obj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); \ #define DATE_CHECK_INITIALIZED(member, class_name) \ if (!(member)) { \ php_error_docref(NULL TSRMLS_CC, E_WARNING, "The " #class_name " object has not been correctly initialized by its constructor"); \ RETURN_FALSE; \ } static void date_object_free_storage_date(void *object TSRMLS_DC); static void date_object_free_storage_timezone(void *object TSRMLS_DC); static void date_object_free_storage_interval(void *object TSRMLS_DC); static void date_object_free_storage_period(void *object TSRMLS_DC); static zend_object_value date_object_new_date(zend_class_entry *class_type TSRMLS_DC); static zend_object_value date_object_new_timezone(zend_class_entry *class_type TSRMLS_DC); static zend_object_value date_object_new_interval(zend_class_entry *class_type TSRMLS_DC); static zend_object_value date_object_new_period(zend_class_entry *class_type TSRMLS_DC); static zend_object_value date_object_clone_date(zval *this_ptr TSRMLS_DC); static zend_object_value date_object_clone_timezone(zval *this_ptr TSRMLS_DC); static zend_object_value date_object_clone_interval(zval *this_ptr TSRMLS_DC); static zend_object_value date_object_clone_period(zval *this_ptr TSRMLS_DC); static int date_object_compare_date(zval *d1, zval *d2 TSRMLS_DC); static HashTable *date_object_get_properties(zval *object TSRMLS_DC); static HashTable *date_object_get_properties_interval(zval *object TSRMLS_DC); zval *date_interval_read_property(zval *object, zval *member, int type, const zend_literal *key TSRMLS_DC); void date_interval_write_property(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC); /* {{{ Module struct */ zend_module_entry date_module_entry = { STANDARD_MODULE_HEADER_EX, NULL, NULL, "date", /* extension name */ date_functions, /* function list */ PHP_MINIT(date), /* process startup */ PHP_MSHUTDOWN(date), /* process shutdown */ PHP_RINIT(date), /* request startup */ PHP_RSHUTDOWN(date), /* request shutdown */ PHP_MINFO(date), /* extension info */ PHP_VERSION, /* extension version */ PHP_MODULE_GLOBALS(date), /* globals descriptor */ PHP_GINIT(date), /* globals ctor */ NULL, /* globals dtor */ NULL, /* post deactivate */ STANDARD_MODULE_PROPERTIES_EX }; /* }}} */ /* {{{ PHP_GINIT_FUNCTION */ static PHP_GINIT_FUNCTION(date) { date_globals->default_timezone = NULL; date_globals->timezone = NULL; date_globals->tzcache = NULL; } /* }}} */ static void _php_date_tzinfo_dtor(void *tzinfo) { timelib_tzinfo **tzi = (timelib_tzinfo **)tzinfo; timelib_tzinfo_dtor(*tzi); } /* {{{ PHP_RINIT_FUNCTION */ PHP_RINIT_FUNCTION(date) { if (DATEG(timezone)) { efree(DATEG(timezone)); } DATEG(timezone) = NULL; DATEG(tzcache) = NULL; DATEG(last_errors) = NULL; return SUCCESS; } /* }}} */ /* {{{ PHP_RSHUTDOWN_FUNCTION */ PHP_RSHUTDOWN_FUNCTION(date) { if (DATEG(timezone)) { efree(DATEG(timezone)); } DATEG(timezone) = NULL; if(DATEG(tzcache)) { zend_hash_destroy(DATEG(tzcache)); FREE_HASHTABLE(DATEG(tzcache)); DATEG(tzcache) = NULL; } if (DATEG(last_errors)) { timelib_error_container_dtor(DATEG(last_errors)); DATEG(last_errors) = NULL; } return SUCCESS; } /* }}} */ #define DATE_TIMEZONEDB php_date_global_timezone_db ? php_date_global_timezone_db : timelib_builtin_db() /* * RFC822, Section 5.1: http://www.ietf.org/rfc/rfc822.txt * date-time = [ day "," ] date time ; dd mm yy hh:mm:ss zzz * day = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" * date = 1*2DIGIT month 2DIGIT ; day month year e.g. 20 Jun 82 * month = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec" * time = hour zone ; ANSI and Military * hour = 2DIGIT ":" 2DIGIT [":" 2DIGIT] ; 00:00:00 - 23:59:59 * zone = "UT" / "GMT" / "EST" / "EDT" / "CST" / "CDT" / "MST" / "MDT" / "PST" / "PDT" / 1ALPHA / ( ("+" / "-") 4DIGIT ) */ #define DATE_FORMAT_RFC822 "D, d M y H:i:s O" /* * RFC850, Section 2.1.4: http://www.ietf.org/rfc/rfc850.txt * Format must be acceptable both to the ARPANET and to the getdate routine. * One format that is acceptable to both is Weekday, DD-Mon-YY HH:MM:SS TIMEZONE * TIMEZONE can be any timezone name (3 or more letters) */ #define DATE_FORMAT_RFC850 "l, d-M-y H:i:s T" /* * RFC1036, Section 2.1.2: http://www.ietf.org/rfc/rfc1036.txt * Its format must be acceptable both in RFC-822 and to the getdate(3) * Wdy, DD Mon YY HH:MM:SS TIMEZONE * There is no hope of having a complete list of timezones. Universal * Time (GMT), the North American timezones (PST, PDT, MST, MDT, CST, * CDT, EST, EDT) and the +/-hhmm offset specifed in RFC-822 should be supported. */ #define DATE_FORMAT_RFC1036 "D, d M y H:i:s O" /* * RFC1123, Section 5.2.14: http://www.ietf.org/rfc/rfc1123.txt * RFC-822 Date and Time Specification: RFC-822 Section 5 * The syntax for the date is hereby changed to: date = 1*2DIGIT month 2*4DIGIT */ #define DATE_FORMAT_RFC1123 "D, d M Y H:i:s O" /* * RFC2822, Section 3.3: http://www.ietf.org/rfc/rfc2822.txt * FWS = ([*WSP CRLF] 1*WSP) / ; Folding white space * CFWS = *([FWS] comment) (([FWS] comment) / FWS) * * date-time = [ day-of-week "," ] date FWS time [CFWS] * day-of-week = ([FWS] day-name) * day-name = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" * date = day month year * year = 4*DIGIT * month = (FWS month-name FWS) * month-name = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec" * day = ([FWS] 1*2DIGIT) * time = time-of-day FWS zone * time-of-day = hour ":" minute [ ":" second ] * hour = 2DIGIT * minute = 2DIGIT * second = 2DIGIT * zone = (( "+" / "-" ) 4DIGIT) */ #define DATE_FORMAT_RFC2822 "D, d M Y H:i:s O" /* * RFC3339, Section 5.6: http://www.ietf.org/rfc/rfc3339.txt * date-fullyear = 4DIGIT * date-month = 2DIGIT ; 01-12 * date-mday = 2DIGIT ; 01-28, 01-29, 01-30, 01-31 based on month/year * * time-hour = 2DIGIT ; 00-23 * time-minute = 2DIGIT ; 00-59 * time-second = 2DIGIT ; 00-58, 00-59, 00-60 based on leap second rules * * time-secfrac = "." 1*DIGIT * time-numoffset = ("+" / "-") time-hour ":" time-minute * time-offset = "Z" / time-numoffset * * partial-time = time-hour ":" time-minute ":" time-second [time-secfrac] * full-date = date-fullyear "-" date-month "-" date-mday * full-time = partial-time time-offset * * date-time = full-date "T" full-time */ #define DATE_FORMAT_RFC3339 "Y-m-d\\TH:i:sP" #define DATE_FORMAT_ISO8601 "Y-m-d\\TH:i:sO" #define DATE_TZ_ERRMSG \ "It is not safe to rely on the system's timezone settings. You are " \ "*required* to use the date.timezone setting or the " \ "date_default_timezone_set() function. In case you used any of those " \ "methods and you are still getting this warning, you most likely " \ "misspelled the timezone identifier. " #define SUNFUNCS_RET_TIMESTAMP 0 #define SUNFUNCS_RET_STRING 1 #define SUNFUNCS_RET_DOUBLE 2 /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(date) { REGISTER_INI_ENTRIES(); date_register_classes(TSRMLS_C); /* * RFC4287, Section 3.3: http://www.ietf.org/rfc/rfc4287.txt * A Date construct is an element whose content MUST conform to the * "date-time" production in [RFC3339]. In addition, an uppercase "T" * character MUST be used to separate date and time, and an uppercase * "Z" character MUST be present in the absence of a numeric time zone offset. */ REGISTER_STRING_CONSTANT("DATE_ATOM", DATE_FORMAT_RFC3339, CONST_CS | CONST_PERSISTENT); /* * Preliminary specification: http://wp.netscape.com/newsref/std/cookie_spec.html * "This is based on RFC 822, RFC 850, RFC 1036, and RFC 1123, * with the variations that the only legal time zone is GMT * and the separators between the elements of the date must be dashes." */ REGISTER_STRING_CONSTANT("DATE_COOKIE", DATE_FORMAT_RFC850, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_ISO8601", DATE_FORMAT_ISO8601, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC822", DATE_FORMAT_RFC822, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC850", DATE_FORMAT_RFC850, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC1036", DATE_FORMAT_RFC1036, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC1123", DATE_FORMAT_RFC1123, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC2822", DATE_FORMAT_RFC2822, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC3339", DATE_FORMAT_RFC3339, CONST_CS | CONST_PERSISTENT); /* * RSS 2.0 Specification: http://blogs.law.harvard.edu/tech/rss * "All date-times in RSS conform to the Date and Time Specification of RFC 822, * with the exception that the year may be expressed with two characters or four characters (four preferred)" */ REGISTER_STRING_CONSTANT("DATE_RSS", DATE_FORMAT_RFC1123, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_W3C", DATE_FORMAT_RFC3339, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SUNFUNCS_RET_TIMESTAMP", SUNFUNCS_RET_TIMESTAMP, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SUNFUNCS_RET_STRING", SUNFUNCS_RET_STRING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SUNFUNCS_RET_DOUBLE", SUNFUNCS_RET_DOUBLE, CONST_CS | CONST_PERSISTENT); php_date_global_timezone_db = NULL; php_date_global_timezone_db_enabled = 0; DATEG(last_errors) = NULL; return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ PHP_MSHUTDOWN_FUNCTION(date) { UNREGISTER_INI_ENTRIES(); if (DATEG(last_errors)) { timelib_error_container_dtor(DATEG(last_errors)); } return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(date) { const timelib_tzdb *tzdb = DATE_TIMEZONEDB; php_info_print_table_start(); php_info_print_table_row(2, "date/time support", "enabled"); php_info_print_table_row(2, "\"Olson\" Timezone Database Version", tzdb->version); php_info_print_table_row(2, "Timezone Database", php_date_global_timezone_db_enabled ? "external" : "internal"); php_info_print_table_row(2, "Default timezone", guess_timezone(tzdb TSRMLS_CC)); php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ /* {{{ Timezone Cache functions */ static timelib_tzinfo *php_date_parse_tzfile(char *formal_tzname, const timelib_tzdb *tzdb TSRMLS_DC) { timelib_tzinfo *tzi, **ptzi; if(!DATEG(tzcache)) { ALLOC_HASHTABLE(DATEG(tzcache)); zend_hash_init(DATEG(tzcache), 4, NULL, _php_date_tzinfo_dtor, 0); } if (zend_hash_find(DATEG(tzcache), formal_tzname, strlen(formal_tzname) + 1, (void **) &ptzi) == SUCCESS) { return *ptzi; } tzi = timelib_parse_tzfile(formal_tzname, tzdb); if (tzi) { zend_hash_add(DATEG(tzcache), formal_tzname, strlen(formal_tzname) + 1, (void *) &tzi, sizeof(timelib_tzinfo*), NULL); } return tzi; } /* }}} */ /* {{{ Helper functions */ static char* guess_timezone(const timelib_tzdb *tzdb TSRMLS_DC) { char *env; /* Checking configure timezone */ if (DATEG(timezone) && (strlen(DATEG(timezone)) > 0)) { return DATEG(timezone); } /* Check environment variable */ env = getenv("TZ"); if (env && *env && timelib_timezone_id_is_valid(env, tzdb)) { return env; } /* Check config setting for default timezone */ if (!DATEG(default_timezone)) { /* Special case: ext/date wasn't initialized yet */ zval ztz; if (SUCCESS == zend_get_configuration_directive("date.timezone", sizeof("date.timezone"), &ztz) && Z_TYPE(ztz) == IS_STRING && Z_STRLEN(ztz) > 0 && timelib_timezone_id_is_valid(Z_STRVAL(ztz), tzdb)) { return Z_STRVAL(ztz); } } else if (*DATEG(default_timezone) && timelib_timezone_id_is_valid(DATEG(default_timezone), tzdb)) { return DATEG(default_timezone); } #if HAVE_TM_ZONE /* Try to guess timezone from system information */ { struct tm *ta, tmbuf; time_t the_time; char *tzid = NULL; the_time = time(NULL); ta = php_localtime_r(&the_time, &tmbuf); if (ta) { tzid = timelib_timezone_id_from_abbr(ta->tm_zone, ta->tm_gmtoff, ta->tm_isdst); } if (! tzid) { tzid = "UTC"; } php_error_docref(NULL TSRMLS_CC, E_WARNING, DATE_TZ_ERRMSG "We selected '%s' for '%s/%.1f/%s' instead", tzid, ta ? ta->tm_zone : "Unknown", ta ? (float) (ta->tm_gmtoff / 3600) : 0, ta ? (ta->tm_isdst ? "DST" : "no DST") : "Unknown"); return tzid; } #endif #ifdef PHP_WIN32 { char *tzid; TIME_ZONE_INFORMATION tzi; switch (GetTimeZoneInformation(&tzi)) { /* DST in effect */ case TIME_ZONE_ID_DAYLIGHT: /* If user has disabled DST in the control panel, Windows returns 0 here */ if (tzi.DaylightBias == 0) { goto php_win_std_time; } tzid = timelib_timezone_id_from_abbr("", (tzi.Bias + tzi.DaylightBias) * -60, 1); if (! tzid) { tzid = "UTC"; } php_error_docref(NULL TSRMLS_CC, E_WARNING, DATE_TZ_ERRMSG "We selected '%s' for '%.1f/DST' instead", tzid, ((tzi.Bias + tzi.DaylightBias) / -60.0)); break; /* no DST or not in effect */ case TIME_ZONE_ID_UNKNOWN: case TIME_ZONE_ID_STANDARD: default: php_win_std_time: tzid = timelib_timezone_id_from_abbr("", (tzi.Bias + tzi.StandardBias) * -60, 0); if (! tzid) { tzid = "UTC"; } php_error_docref(NULL TSRMLS_CC, E_WARNING, DATE_TZ_ERRMSG "We selected '%s' for '%.1f/no DST' instead", tzid, ((tzi.Bias + tzi.StandardBias) / -60.0)); break; } return tzid; } #elif defined(NETWARE) /* Try to guess timezone from system information */ { char *tzid = timelib_timezone_id_from_abbr("", ((_timezone * -1) + (daylightOffset * daylightOnOff)), daylightOnOff); if (tzid) { return tzid; } } #endif /* Fallback to UTC */ php_error_docref(NULL TSRMLS_CC, E_WARNING, DATE_TZ_ERRMSG "We had to select 'UTC' because your platform doesn't provide functionality for the guessing algorithm"); return "UTC"; } PHPAPI timelib_tzinfo *get_timezone_info(TSRMLS_D) { char *tz; timelib_tzinfo *tzi; tz = guess_timezone(DATE_TIMEZONEDB TSRMLS_CC); tzi = php_date_parse_tzfile(tz, DATE_TIMEZONEDB TSRMLS_CC); if (! tzi) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Timezone database is corrupt - this should *never* happen!"); } return tzi; } /* }}} */ /* {{{ date() and gmdate() data */ #include "ext/standard/php_smart_str.h" static char *mon_full_names[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; static char *mon_short_names[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; static char *day_full_names[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; static char *day_short_names[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; static char *english_suffix(timelib_sll number) { if (number >= 10 && number <= 19) { return "th"; } else { switch (number % 10) { case 1: return "st"; case 2: return "nd"; case 3: return "rd"; } } return "th"; } /* }}} */ /* {{{ day of week helpers */ char *php_date_full_day_name(timelib_sll y, timelib_sll m, timelib_sll d) { timelib_sll day_of_week = timelib_day_of_week(y, m, d); if (day_of_week < 0) { return "Unknown"; } return day_full_names[day_of_week]; } char *php_date_short_day_name(timelib_sll y, timelib_sll m, timelib_sll d) { timelib_sll day_of_week = timelib_day_of_week(y, m, d); if (day_of_week < 0) { return "Unknown"; } return day_short_names[day_of_week]; } /* }}} */ /* {{{ date_format - (gm)date helper */ static char *date_format(char *format, int format_len, timelib_time *t, int localtime) { smart_str string = {0}; int i, length; char buffer[97]; timelib_time_offset *offset = NULL; timelib_sll isoweek, isoyear; int rfc_colon; if (!format_len) { return estrdup(""); } if (localtime) { if (t->zone_type == TIMELIB_ZONETYPE_ABBR) { offset = timelib_time_offset_ctor(); offset->offset = (t->z - (t->dst * 60)) * -60; offset->leap_secs = 0; offset->is_dst = t->dst; offset->abbr = strdup(t->tz_abbr); } else if (t->zone_type == TIMELIB_ZONETYPE_OFFSET) { offset = timelib_time_offset_ctor(); offset->offset = (t->z) * -60; offset->leap_secs = 0; offset->is_dst = 0; offset->abbr = malloc(9); /* GMT�xxxx\0 */ snprintf(offset->abbr, 9, "GMT%c%02d%02d", localtime ? ((offset->offset < 0) ? '-' : '+') : '+', localtime ? abs(offset->offset / 3600) : 0, localtime ? abs((offset->offset % 3600) / 60) : 0 ); } else { offset = timelib_get_time_zone_info(t->sse, t->tz_info); } } timelib_isoweek_from_date(t->y, t->m, t->d, &isoweek, &isoyear); for (i = 0; i < format_len; i++) { rfc_colon = 0; switch (format[i]) { /* day */ case 'd': length = slprintf(buffer, 32, "%02d", (int) t->d); break; case 'D': length = slprintf(buffer, 32, "%s", php_date_short_day_name(t->y, t->m, t->d)); break; case 'j': length = slprintf(buffer, 32, "%d", (int) t->d); break; case 'l': length = slprintf(buffer, 32, "%s", php_date_full_day_name(t->y, t->m, t->d)); break; case 'S': length = slprintf(buffer, 32, "%s", english_suffix(t->d)); break; case 'w': length = slprintf(buffer, 32, "%d", (int) timelib_day_of_week(t->y, t->m, t->d)); break; case 'N': length = slprintf(buffer, 32, "%d", (int) timelib_iso_day_of_week(t->y, t->m, t->d)); break; case 'z': length = slprintf(buffer, 32, "%d", (int) timelib_day_of_year(t->y, t->m, t->d)); break; /* week */ case 'W': length = slprintf(buffer, 32, "%02d", (int) isoweek); break; /* iso weeknr */ case 'o': length = slprintf(buffer, 32, "%d", (int) isoyear); break; /* iso year */ /* month */ case 'F': length = slprintf(buffer, 32, "%s", mon_full_names[t->m - 1]); break; case 'm': length = slprintf(buffer, 32, "%02d", (int) t->m); break; case 'M': length = slprintf(buffer, 32, "%s", mon_short_names[t->m - 1]); break; case 'n': length = slprintf(buffer, 32, "%d", (int) t->m); break; case 't': length = slprintf(buffer, 32, "%d", (int) timelib_days_in_month(t->y, t->m)); break; /* year */ case 'L': length = slprintf(buffer, 32, "%d", timelib_is_leap((int) t->y)); break; case 'y': length = slprintf(buffer, 32, "%02d", (int) t->y % 100); break; case 'Y': length = slprintf(buffer, 32, "%s%04lld", t->y < 0 ? "-" : "", php_date_llabs((timelib_sll) t->y)); break; /* time */ case 'a': length = slprintf(buffer, 32, "%s", t->h >= 12 ? "pm" : "am"); break; case 'A': length = slprintf(buffer, 32, "%s", t->h >= 12 ? "PM" : "AM"); break; case 'B': { int retval = (((((long)t->sse)-(((long)t->sse) - ((((long)t->sse) % 86400) + 3600))) * 10) / 864); while (retval < 0) { retval += 1000; } retval = retval % 1000; length = slprintf(buffer, 32, "%03d", retval); break; } case 'g': length = slprintf(buffer, 32, "%d", (t->h % 12) ? (int) t->h % 12 : 12); break; case 'G': length = slprintf(buffer, 32, "%d", (int) t->h); break; case 'h': length = slprintf(buffer, 32, "%02d", (t->h % 12) ? (int) t->h % 12 : 12); break; case 'H': length = slprintf(buffer, 32, "%02d", (int) t->h); break; case 'i': length = slprintf(buffer, 32, "%02d", (int) t->i); break; case 's': length = slprintf(buffer, 32, "%02d", (int) t->s); break; case 'u': length = slprintf(buffer, 32, "%06d", (int) floor(t->f * 1000000)); break; /* timezone */ case 'I': length = slprintf(buffer, 32, "%d", localtime ? offset->is_dst : 0); break; case 'P': rfc_colon = 1; /* break intentionally missing */ case 'O': length = slprintf(buffer, 32, "%c%02d%s%02d", localtime ? ((offset->offset < 0) ? '-' : '+') : '+', localtime ? abs(offset->offset / 3600) : 0, rfc_colon ? ":" : "", localtime ? abs((offset->offset % 3600) / 60) : 0 ); break; case 'T': length = slprintf(buffer, 32, "%s", localtime ? offset->abbr : "GMT"); break; case 'e': if (!localtime) { length = slprintf(buffer, 32, "%s", "UTC"); } else { switch (t->zone_type) { case TIMELIB_ZONETYPE_ID: length = slprintf(buffer, 32, "%s", t->tz_info->name); break; case TIMELIB_ZONETYPE_ABBR: length = slprintf(buffer, 32, "%s", offset->abbr); break; case TIMELIB_ZONETYPE_OFFSET: length = slprintf(buffer, 32, "%c%02d:%02d", ((offset->offset < 0) ? '-' : '+'), abs(offset->offset / 3600), abs((offset->offset % 3600) / 60) ); break; } } break; case 'Z': length = slprintf(buffer, 32, "%d", localtime ? offset->offset : 0); break; /* full date/time */ case 'c': length = slprintf(buffer, 96, "%04d-%02d-%02dT%02d:%02d:%02d%c%02d:%02d", (int) t->y, (int) t->m, (int) t->d, (int) t->h, (int) t->i, (int) t->s, localtime ? ((offset->offset < 0) ? '-' : '+') : '+', localtime ? abs(offset->offset / 3600) : 0, localtime ? abs((offset->offset % 3600) / 60) : 0 ); break; case 'r': length = slprintf(buffer, 96, "%3s, %02d %3s %04d %02d:%02d:%02d %c%02d%02d", php_date_short_day_name(t->y, t->m, t->d), (int) t->d, mon_short_names[t->m - 1], (int) t->y, (int) t->h, (int) t->i, (int) t->s, localtime ? ((offset->offset < 0) ? '-' : '+') : '+', localtime ? abs(offset->offset / 3600) : 0, localtime ? abs((offset->offset % 3600) / 60) : 0 ); break; case 'U': length = slprintf(buffer, 32, "%lld", (timelib_sll) t->sse); break; case '\\': if (i < format_len) i++; /* break intentionally missing */ default: buffer[0] = format[i]; buffer[1] = '\0'; length = 1; break; } smart_str_appendl(&string, buffer, length); } smart_str_0(&string); if (localtime) { timelib_time_offset_dtor(offset); } return string.c; } static void php_date(INTERNAL_FUNCTION_PARAMETERS, int localtime) { char *format; int format_len; long ts; char *string; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &format, &format_len, &ts) == FAILURE) { RETURN_FALSE; } if (ZEND_NUM_ARGS() == 1) { ts = time(NULL); } string = php_format_date(format, format_len, ts, localtime TSRMLS_CC); RETVAL_STRING(string, 0); } /* }}} */ PHPAPI char *php_format_date(char *format, int format_len, time_t ts, int localtime TSRMLS_DC) /* {{{ */ { timelib_time *t; timelib_tzinfo *tzi; char *string; t = timelib_time_ctor(); if (localtime) { tzi = get_timezone_info(TSRMLS_C); t->tz_info = tzi; t->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(t, ts); } else { tzi = NULL; timelib_unixtime2gmt(t, ts); } string = date_format(format, format_len, t, localtime); timelib_time_dtor(t); return string; } /* }}} */ /* {{{ php_idate */ PHPAPI int php_idate(char format, time_t ts, int localtime TSRMLS_DC) { timelib_time *t; timelib_tzinfo *tzi; int retval = -1; timelib_time_offset *offset = NULL; timelib_sll isoweek, isoyear; t = timelib_time_ctor(); if (!localtime) { tzi = get_timezone_info(TSRMLS_C); t->tz_info = tzi; t->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(t, ts); } else { tzi = NULL; timelib_unixtime2gmt(t, ts); } if (!localtime) { if (t->zone_type == TIMELIB_ZONETYPE_ABBR) { offset = timelib_time_offset_ctor(); offset->offset = (t->z - (t->dst * 60)) * -60; offset->leap_secs = 0; offset->is_dst = t->dst; offset->abbr = strdup(t->tz_abbr); } else if (t->zone_type == TIMELIB_ZONETYPE_OFFSET) { offset = timelib_time_offset_ctor(); offset->offset = (t->z - (t->dst * 60)) * -60; offset->leap_secs = 0; offset->is_dst = t->dst; offset->abbr = malloc(9); /* GMT�xxxx\0 */ snprintf(offset->abbr, 9, "GMT%c%02d%02d", !localtime ? ((offset->offset < 0) ? '-' : '+') : '+', !localtime ? abs(offset->offset / 3600) : 0, !localtime ? abs((offset->offset % 3600) / 60) : 0 ); } else { offset = timelib_get_time_zone_info(t->sse, t->tz_info); } } timelib_isoweek_from_date(t->y, t->m, t->d, &isoweek, &isoyear); switch (format) { /* day */ case 'd': case 'j': retval = (int) t->d; break; case 'w': retval = (int) timelib_day_of_week(t->y, t->m, t->d); break; case 'z': retval = (int) timelib_day_of_year(t->y, t->m, t->d); break; /* week */ case 'W': retval = (int) isoweek; break; /* iso weeknr */ /* month */ case 'm': case 'n': retval = (int) t->m; break; case 't': retval = (int) timelib_days_in_month(t->y, t->m); break; /* year */ case 'L': retval = (int) timelib_is_leap((int) t->y); break; case 'y': retval = (int) (t->y % 100); break; case 'Y': retval = (int) t->y; break; /* Swatch Beat a.k.a. Internet Time */ case 'B': retval = (((((long)t->sse)-(((long)t->sse) - ((((long)t->sse) % 86400) + 3600))) * 10) / 864); while (retval < 0) { retval += 1000; } retval = retval % 1000; break; /* time */ case 'g': case 'h': retval = (int) ((t->h % 12) ? (int) t->h % 12 : 12); break; case 'H': case 'G': retval = (int) t->h; break; case 'i': retval = (int) t->i; break; case 's': retval = (int) t->s; break; /* timezone */ case 'I': retval = (int) (!localtime ? offset->is_dst : 0); break; case 'Z': retval = (int) (!localtime ? offset->offset : 0); break; case 'U': retval = (int) t->sse; break; } if (!localtime) { timelib_time_offset_dtor(offset); } timelib_time_dtor(t); return retval; } /* }}} */ /* {{{ proto string date(string format [, long timestamp]) Format a local date/time */ PHP_FUNCTION(date) { php_date(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto string gmdate(string format [, long timestamp]) Format a GMT date/time */ PHP_FUNCTION(gmdate) { php_date(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto int idate(string format [, int timestamp]) Format a local time/date as integer */ PHP_FUNCTION(idate) { char *format; int format_len; long ts = 0; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &format, &format_len, &ts) == FAILURE) { RETURN_FALSE; } if (format_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "idate format is one char"); RETURN_FALSE; } if (ZEND_NUM_ARGS() == 1) { ts = time(NULL); } ret = php_idate(format[0], ts, 0 TSRMLS_CC); if (ret == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unrecognized date format token."); RETURN_FALSE; } RETURN_LONG(ret); } /* }}} */ /* {{{ php_date_set_tzdb - NOT THREADSAFE */ PHPAPI void php_date_set_tzdb(timelib_tzdb *tzdb) { const timelib_tzdb *builtin = timelib_builtin_db(); if (php_version_compare(tzdb->version, builtin->version) > 0) { php_date_global_timezone_db = tzdb; php_date_global_timezone_db_enabled = 1; } } /* }}} */ /* {{{ php_parse_date: Backwards compability function */ PHPAPI signed long php_parse_date(char *string, signed long *now) { timelib_time *parsed_time; timelib_error_container *error = NULL; int error2; signed long retval; parsed_time = timelib_strtotime(string, strlen(string), &error, DATE_TIMEZONEDB); if (error->error_count) { timelib_error_container_dtor(error); return -1; } timelib_error_container_dtor(error); timelib_update_ts(parsed_time, NULL); retval = timelib_date_to_int(parsed_time, &error2); timelib_time_dtor(parsed_time); if (error2) { return -1; } return retval; } /* }}} */ /* {{{ proto int strtotime(string time [, int now ]) Convert string representation of date and time to a timestamp */ PHP_FUNCTION(strtotime) { char *times, *initial_ts; int time_len, error1, error2; struct timelib_error_container *error; long preset_ts = 0, ts; timelib_time *t, *now; timelib_tzinfo *tzi; tzi = get_timezone_info(TSRMLS_C); if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "sl", &times, &time_len, &preset_ts) != FAILURE) { /* We have an initial timestamp */ now = timelib_time_ctor(); initial_ts = emalloc(25); snprintf(initial_ts, 24, "@%ld UTC", preset_ts); t = timelib_strtotime(initial_ts, strlen(initial_ts), NULL, DATE_TIMEZONEDB); /* we ignore the error here, as this should never fail */ timelib_update_ts(t, tzi); now->tz_info = tzi; now->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(now, t->sse); timelib_time_dtor(t); efree(initial_ts); } else if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &times, &time_len, &preset_ts) != FAILURE) { /* We have no initial timestamp */ now = timelib_time_ctor(); now->tz_info = tzi; now->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(now, (timelib_sll) time(NULL)); } else { RETURN_FALSE; } if (!time_len) { timelib_time_dtor(now); RETURN_FALSE; } t = timelib_strtotime(times, time_len, &error, DATE_TIMEZONEDB); error1 = error->error_count; timelib_error_container_dtor(error); timelib_fill_holes(t, now, TIMELIB_NO_CLONE); timelib_update_ts(t, tzi); ts = timelib_date_to_int(t, &error2); timelib_time_dtor(now); timelib_time_dtor(t); if (error1 || error2) { RETURN_FALSE; } else { RETURN_LONG(ts); } } /* }}} */ /* {{{ php_mktime - (gm)mktime helper */ PHPAPI void php_mktime(INTERNAL_FUNCTION_PARAMETERS, int gmt) { long hou = 0, min = 0, sec = 0, mon = 0, day = 0, yea = 0, dst = -1; timelib_time *now; timelib_tzinfo *tzi = NULL; long ts, adjust_seconds = 0; int error; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lllllll", &hou, &min, &sec, &mon, &day, &yea, &dst) == FAILURE) { RETURN_FALSE; } /* Initialize structure with current time */ now = timelib_time_ctor(); if (gmt) { timelib_unixtime2gmt(now, (timelib_sll) time(NULL)); } else { tzi = get_timezone_info(TSRMLS_C); now->tz_info = tzi; now->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(now, (timelib_sll) time(NULL)); } /* Fill in the new data */ switch (ZEND_NUM_ARGS()) { case 7: /* break intentionally missing */ case 6: if (yea >= 0 && yea < 70) { yea += 2000; } else if (yea >= 70 && yea <= 100) { yea += 1900; } now->y = yea; /* break intentionally missing again */ case 5: now->d = day; /* break missing intentionally here too */ case 4: now->m = mon; /* and here */ case 3: now->s = sec; /* yup, this break isn't here on purpose too */ case 2: now->i = min; /* last intentionally missing break */ case 1: now->h = hou; break; default: php_error_docref(NULL TSRMLS_CC, E_STRICT, "You should be using the time() function instead"); } /* Update the timestamp */ if (gmt) { timelib_update_ts(now, NULL); } else { timelib_update_ts(now, tzi); } /* Support for the deprecated is_dst parameter */ if (dst != -1) { php_error_docref(NULL TSRMLS_CC, E_DEPRECATED, "The is_dst parameter is deprecated"); if (gmt) { /* GMT never uses DST */ if (dst == 1) { adjust_seconds = -3600; } } else { /* Figure out is_dst for current TS */ timelib_time_offset *tmp_offset; tmp_offset = timelib_get_time_zone_info(now->sse, tzi); if (dst == 1 && tmp_offset->is_dst == 0) { adjust_seconds = -3600; } if (dst == 0 && tmp_offset->is_dst == 1) { adjust_seconds = +3600; } timelib_time_offset_dtor(tmp_offset); } } /* Clean up and return */ ts = timelib_date_to_int(now, &error); ts += adjust_seconds; timelib_time_dtor(now); if (error) { RETURN_FALSE; } else { RETURN_LONG(ts); } } /* }}} */ /* {{{ proto int mktime([int hour [, int min [, int sec [, int mon [, int day [, int year]]]]]]) Get UNIX timestamp for a date */ PHP_FUNCTION(mktime) { php_mktime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto int gmmktime([int hour [, int min [, int sec [, int mon [, int day [, int year]]]]]]) Get UNIX timestamp for a GMT date */ PHP_FUNCTION(gmmktime) { php_mktime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto bool checkdate(int month, int day, int year) Returns true(1) if it is a valid date in gregorian calendar */ PHP_FUNCTION(checkdate) { long m, d, y; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lll", &m, &d, &y) == FAILURE) { RETURN_FALSE; } if (y < 1 || y > 32767 || !timelib_valid_date(y, m, d)) { RETURN_FALSE; } RETURN_TRUE; /* True : This month, day, year arguments are valid */ } /* }}} */ #ifdef HAVE_STRFTIME /* {{{ php_strftime - (gm)strftime helper */ PHPAPI void php_strftime(INTERNAL_FUNCTION_PARAMETERS, int gmt) { char *format, *buf; int format_len; long timestamp = 0; struct tm ta; int max_reallocs = 5; size_t buf_len = 64, real_len; timelib_time *ts; timelib_tzinfo *tzi; timelib_time_offset *offset = NULL; timestamp = (long) time(NULL); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &format, &format_len, &timestamp) == FAILURE) { RETURN_FALSE; } if (format_len == 0) { RETURN_FALSE; } ts = timelib_time_ctor(); if (gmt) { tzi = NULL; timelib_unixtime2gmt(ts, (timelib_sll) timestamp); } else { tzi = get_timezone_info(TSRMLS_C); ts->tz_info = tzi; ts->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(ts, (timelib_sll) timestamp); } ta.tm_sec = ts->s; ta.tm_min = ts->i; ta.tm_hour = ts->h; ta.tm_mday = ts->d; ta.tm_mon = ts->m - 1; ta.tm_year = ts->y - 1900; ta.tm_wday = timelib_day_of_week(ts->y, ts->m, ts->d); ta.tm_yday = timelib_day_of_year(ts->y, ts->m, ts->d); if (gmt) { ta.tm_isdst = 0; #if HAVE_TM_GMTOFF ta.tm_gmtoff = 0; #endif #if HAVE_TM_ZONE ta.tm_zone = "GMT"; #endif } else { offset = timelib_get_time_zone_info(timestamp, tzi); ta.tm_isdst = offset->is_dst; #if HAVE_TM_GMTOFF ta.tm_gmtoff = offset->offset; #endif #if HAVE_TM_ZONE ta.tm_zone = offset->abbr; #endif } buf = (char *) emalloc(buf_len); while ((real_len=strftime(buf, buf_len, format, &ta))==buf_len || real_len==0) { buf_len *= 2; buf = (char *) erealloc(buf, buf_len); if (!--max_reallocs) { break; } } timelib_time_dtor(ts); if (!gmt) { timelib_time_offset_dtor(offset); } if (real_len && real_len != buf_len) { buf = (char *) erealloc(buf, real_len + 1); RETURN_STRINGL(buf, real_len, 0); } efree(buf); RETURN_FALSE; } /* }}} */ /* {{{ proto string strftime(string format [, int timestamp]) Format a local time/date according to locale settings */ PHP_FUNCTION(strftime) { php_strftime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto string gmstrftime(string format [, int timestamp]) Format a GMT/UCT time/date according to locale settings */ PHP_FUNCTION(gmstrftime) { php_strftime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ #endif /* {{{ proto int time(void) Return current UNIX timestamp */ PHP_FUNCTION(time) { RETURN_LONG((long)time(NULL)); } /* }}} */ /* {{{ proto array localtime([int timestamp [, bool associative_array]]) Returns the results of the C system call localtime as an associative array if the associative_array argument is set to 1 other wise it is a regular array */ PHP_FUNCTION(localtime) { long timestamp = (long)time(NULL); zend_bool associative = 0; timelib_tzinfo *tzi; timelib_time *ts; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lb", &timestamp, &associative) == FAILURE) { RETURN_FALSE; } tzi = get_timezone_info(TSRMLS_C); ts = timelib_time_ctor(); ts->tz_info = tzi; ts->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(ts, (timelib_sll) timestamp); array_init(return_value); if (associative) { add_assoc_long(return_value, "tm_sec", ts->s); add_assoc_long(return_value, "tm_min", ts->i); add_assoc_long(return_value, "tm_hour", ts->h); add_assoc_long(return_value, "tm_mday", ts->d); add_assoc_long(return_value, "tm_mon", ts->m - 1); add_assoc_long(return_value, "tm_year", ts->y - 1900); add_assoc_long(return_value, "tm_wday", timelib_day_of_week(ts->y, ts->m, ts->d)); add_assoc_long(return_value, "tm_yday", timelib_day_of_year(ts->y, ts->m, ts->d)); add_assoc_long(return_value, "tm_isdst", ts->dst); } else { add_next_index_long(return_value, ts->s); add_next_index_long(return_value, ts->i); add_next_index_long(return_value, ts->h); add_next_index_long(return_value, ts->d); add_next_index_long(return_value, ts->m - 1); add_next_index_long(return_value, ts->y- 1900); add_next_index_long(return_value, timelib_day_of_week(ts->y, ts->m, ts->d)); add_next_index_long(return_value, timelib_day_of_year(ts->y, ts->m, ts->d)); add_next_index_long(return_value, ts->dst); } timelib_time_dtor(ts); } /* }}} */ /* {{{ proto array getdate([int timestamp]) Get date/time information */ PHP_FUNCTION(getdate) { long timestamp = (long)time(NULL); timelib_tzinfo *tzi; timelib_time *ts; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &timestamp) == FAILURE) { RETURN_FALSE; } tzi = get_timezone_info(TSRMLS_C); ts = timelib_time_ctor(); ts->tz_info = tzi; ts->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(ts, (timelib_sll) timestamp); array_init(return_value); add_assoc_long(return_value, "seconds", ts->s); add_assoc_long(return_value, "minutes", ts->i); add_assoc_long(return_value, "hours", ts->h); add_assoc_long(return_value, "mday", ts->d); add_assoc_long(return_value, "wday", timelib_day_of_week(ts->y, ts->m, ts->d)); add_assoc_long(return_value, "mon", ts->m); add_assoc_long(return_value, "year", ts->y); add_assoc_long(return_value, "yday", timelib_day_of_year(ts->y, ts->m, ts->d)); add_assoc_string(return_value, "weekday", php_date_full_day_name(ts->y, ts->m, ts->d), 1); add_assoc_string(return_value, "month", mon_full_names[ts->m - 1], 1); add_index_long(return_value, 0, timestamp); timelib_time_dtor(ts); } /* }}} */ #define PHP_DATE_TIMEZONE_GROUP_AFRICA 0x0001 #define PHP_DATE_TIMEZONE_GROUP_AMERICA 0x0002 #define PHP_DATE_TIMEZONE_GROUP_ANTARCTICA 0x0004 #define PHP_DATE_TIMEZONE_GROUP_ARCTIC 0x0008 #define PHP_DATE_TIMEZONE_GROUP_ASIA 0x0010 #define PHP_DATE_TIMEZONE_GROUP_ATLANTIC 0x0020 #define PHP_DATE_TIMEZONE_GROUP_AUSTRALIA 0x0040 #define PHP_DATE_TIMEZONE_GROUP_EUROPE 0x0080 #define PHP_DATE_TIMEZONE_GROUP_INDIAN 0x0100 #define PHP_DATE_TIMEZONE_GROUP_PACIFIC 0x0200 #define PHP_DATE_TIMEZONE_GROUP_UTC 0x0400 #define PHP_DATE_TIMEZONE_GROUP_ALL 0x07FF #define PHP_DATE_TIMEZONE_GROUP_ALL_W_BC 0x0FFF #define PHP_DATE_TIMEZONE_PER_COUNTRY 0x1000 #define PHP_DATE_PERIOD_EXCLUDE_START_DATE 0x0001 /* define an overloaded iterator structure */ typedef struct { zend_object_iterator intern; zval *date_period_zval; zval *current; php_period_obj *object; int current_index; } date_period_it; /* {{{ date_period_it_invalidate_current */ static void date_period_it_invalidate_current(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; if (iterator->current) { zval_ptr_dtor(&iterator->current); iterator->current = NULL; } } /* }}} */ /* {{{ date_period_it_dtor */ static void date_period_it_dtor(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; date_period_it_invalidate_current(iter TSRMLS_CC); zval_ptr_dtor(&iterator->date_period_zval); efree(iterator); } /* }}} */ /* {{{ date_period_it_has_more */ static int date_period_it_has_more(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; php_period_obj *object = iterator->object; timelib_time *it_time = object->current; /* apply modification if it's not the first iteration */ if (!object->include_start_date || iterator->current_index > 0) { it_time->have_relative = 1; it_time->relative = *object->interval; it_time->sse_uptodate = 0; timelib_update_ts(it_time, NULL); timelib_update_from_sse(it_time); } if (object->end) { return object->current->sse < object->end->sse ? SUCCESS : FAILURE; } else { return (iterator->current_index < object->recurrences) ? SUCCESS : FAILURE; } } /* }}} */ /* {{{ date_period_it_current_data */ static void date_period_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; php_period_obj *object = iterator->object; timelib_time *it_time = object->current; php_date_obj *newdateobj; /* Create new object */ MAKE_STD_ZVAL(iterator->current); php_date_instantiate(date_ce_date, iterator->current TSRMLS_CC); newdateobj = (php_date_obj *) zend_object_store_get_object(iterator->current TSRMLS_CC); newdateobj->time = timelib_time_ctor(); *newdateobj->time = *it_time; if (it_time->tz_abbr) { newdateobj->time->tz_abbr = strdup(it_time->tz_abbr); } if (it_time->tz_info) { newdateobj->time->tz_info = it_time->tz_info; } *data = &iterator->current; } /* }}} */ /* {{{ date_period_it_current_key */ static int date_period_it_current_key(zend_object_iterator *iter, char **str_key, uint *str_key_len, ulong *int_key TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; *int_key = iterator->current_index; return HASH_KEY_IS_LONG; } /* }}} */ /* {{{ date_period_it_move_forward */ static void date_period_it_move_forward(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; iterator->current_index++; date_period_it_invalidate_current(iter TSRMLS_CC); } /* }}} */ /* {{{ date_period_it_rewind */ static void date_period_it_rewind(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; iterator->current_index = 0; if (iterator->object->current) { timelib_time_dtor(iterator->object->current); } iterator->object->current = timelib_time_clone(iterator->object->start); date_period_it_invalidate_current(iter TSRMLS_CC); } /* }}} */ /* iterator handler table */ zend_object_iterator_funcs date_period_it_funcs = { date_period_it_dtor, date_period_it_has_more, date_period_it_current_data, date_period_it_current_key, date_period_it_move_forward, date_period_it_rewind, date_period_it_invalidate_current }; zend_object_iterator *date_object_period_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) { date_period_it *iterator = emalloc(sizeof(date_period_it)); php_period_obj *dpobj = (php_period_obj *)zend_object_store_get_object(object TSRMLS_CC); if (by_ref) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } Z_ADDREF_P(object); iterator->intern.data = (void*) dpobj; iterator->intern.funcs = &date_period_it_funcs; iterator->date_period_zval = object; iterator->object = dpobj; iterator->current = NULL; return (zend_object_iterator*)iterator; } static void date_register_classes(TSRMLS_D) { zend_class_entry ce_date, ce_timezone, ce_interval, ce_period; INIT_CLASS_ENTRY(ce_date, "DateTime", date_funcs_date); ce_date.create_object = date_object_new_date; date_ce_date = zend_register_internal_class_ex(&ce_date, NULL, NULL TSRMLS_CC); memcpy(&date_object_handlers_date, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); date_object_handlers_date.clone_obj = date_object_clone_date; date_object_handlers_date.compare_objects = date_object_compare_date; date_object_handlers_date.get_properties = date_object_get_properties; #define REGISTER_DATE_CLASS_CONST_STRING(const_name, value) \ zend_declare_class_constant_stringl(date_ce_date, const_name, sizeof(const_name)-1, value, sizeof(value)-1 TSRMLS_CC); REGISTER_DATE_CLASS_CONST_STRING("ATOM", DATE_FORMAT_RFC3339); REGISTER_DATE_CLASS_CONST_STRING("COOKIE", DATE_FORMAT_RFC850); REGISTER_DATE_CLASS_CONST_STRING("ISO8601", DATE_FORMAT_ISO8601); REGISTER_DATE_CLASS_CONST_STRING("RFC822", DATE_FORMAT_RFC822); REGISTER_DATE_CLASS_CONST_STRING("RFC850", DATE_FORMAT_RFC850); REGISTER_DATE_CLASS_CONST_STRING("RFC1036", DATE_FORMAT_RFC1036); REGISTER_DATE_CLASS_CONST_STRING("RFC1123", DATE_FORMAT_RFC1123); REGISTER_DATE_CLASS_CONST_STRING("RFC2822", DATE_FORMAT_RFC2822); REGISTER_DATE_CLASS_CONST_STRING("RFC3339", DATE_FORMAT_RFC3339); REGISTER_DATE_CLASS_CONST_STRING("RSS", DATE_FORMAT_RFC1123); REGISTER_DATE_CLASS_CONST_STRING("W3C", DATE_FORMAT_RFC3339); INIT_CLASS_ENTRY(ce_timezone, "DateTimeZone", date_funcs_timezone); ce_timezone.create_object = date_object_new_timezone; date_ce_timezone = zend_register_internal_class_ex(&ce_timezone, NULL, NULL TSRMLS_CC); memcpy(&date_object_handlers_timezone, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); date_object_handlers_timezone.clone_obj = date_object_clone_timezone; #define REGISTER_TIMEZONE_CLASS_CONST_STRING(const_name, value) \ zend_declare_class_constant_long(date_ce_timezone, const_name, sizeof(const_name)-1, value TSRMLS_CC); REGISTER_TIMEZONE_CLASS_CONST_STRING("AFRICA", PHP_DATE_TIMEZONE_GROUP_AFRICA); REGISTER_TIMEZONE_CLASS_CONST_STRING("AMERICA", PHP_DATE_TIMEZONE_GROUP_AMERICA); REGISTER_TIMEZONE_CLASS_CONST_STRING("ANTARCTICA", PHP_DATE_TIMEZONE_GROUP_ANTARCTICA); REGISTER_TIMEZONE_CLASS_CONST_STRING("ARCTIC", PHP_DATE_TIMEZONE_GROUP_ARCTIC); REGISTER_TIMEZONE_CLASS_CONST_STRING("ASIA", PHP_DATE_TIMEZONE_GROUP_ASIA); REGISTER_TIMEZONE_CLASS_CONST_STRING("ATLANTIC", PHP_DATE_TIMEZONE_GROUP_ATLANTIC); REGISTER_TIMEZONE_CLASS_CONST_STRING("AUSTRALIA", PHP_DATE_TIMEZONE_GROUP_AUSTRALIA); REGISTER_TIMEZONE_CLASS_CONST_STRING("EUROPE", PHP_DATE_TIMEZONE_GROUP_EUROPE); REGISTER_TIMEZONE_CLASS_CONST_STRING("INDIAN", PHP_DATE_TIMEZONE_GROUP_INDIAN); REGISTER_TIMEZONE_CLASS_CONST_STRING("PACIFIC", PHP_DATE_TIMEZONE_GROUP_PACIFIC); REGISTER_TIMEZONE_CLASS_CONST_STRING("UTC", PHP_DATE_TIMEZONE_GROUP_UTC); REGISTER_TIMEZONE_CLASS_CONST_STRING("ALL", PHP_DATE_TIMEZONE_GROUP_ALL); REGISTER_TIMEZONE_CLASS_CONST_STRING("ALL_WITH_BC", PHP_DATE_TIMEZONE_GROUP_ALL_W_BC); REGISTER_TIMEZONE_CLASS_CONST_STRING("PER_COUNTRY", PHP_DATE_TIMEZONE_PER_COUNTRY); INIT_CLASS_ENTRY(ce_interval, "DateInterval", date_funcs_interval); ce_interval.create_object = date_object_new_interval; date_ce_interval = zend_register_internal_class_ex(&ce_interval, NULL, NULL TSRMLS_CC); memcpy(&date_object_handlers_interval, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); date_object_handlers_interval.clone_obj = date_object_clone_interval; date_object_handlers_interval.read_property = date_interval_read_property; date_object_handlers_interval.write_property = date_interval_write_property; date_object_handlers_interval.get_properties = date_object_get_properties_interval; date_object_handlers_interval.get_property_ptr_ptr = NULL; INIT_CLASS_ENTRY(ce_period, "DatePeriod", date_funcs_period); ce_period.create_object = date_object_new_period; date_ce_period = zend_register_internal_class_ex(&ce_period, NULL, NULL TSRMLS_CC); date_ce_period->get_iterator = date_object_period_get_iterator; date_ce_period->iterator_funcs.funcs = &date_period_it_funcs; zend_class_implements(date_ce_period TSRMLS_CC, 1, zend_ce_traversable); memcpy(&date_object_handlers_period, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); date_object_handlers_period.clone_obj = date_object_clone_period; #define REGISTER_PERIOD_CLASS_CONST_STRING(const_name, value) \ zend_declare_class_constant_long(date_ce_period, const_name, sizeof(const_name)-1, value TSRMLS_CC); REGISTER_PERIOD_CLASS_CONST_STRING("EXCLUDE_START_DATE", PHP_DATE_PERIOD_EXCLUDE_START_DATE); } static inline zend_object_value date_object_new_date_ex(zend_class_entry *class_type, php_date_obj **ptr TSRMLS_DC) { php_date_obj *intern; zend_object_value retval; intern = emalloc(sizeof(php_date_obj)); memset(intern, 0, sizeof(php_date_obj)); if (ptr) { *ptr = intern; } zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) date_object_free_storage_date, NULL TSRMLS_CC); retval.handlers = &date_object_handlers_date; return retval; } static zend_object_value date_object_new_date(zend_class_entry *class_type TSRMLS_DC) { return date_object_new_date_ex(class_type, NULL TSRMLS_CC); } static zend_object_value date_object_clone_date(zval *this_ptr TSRMLS_DC) { php_date_obj *new_obj = NULL; php_date_obj *old_obj = (php_date_obj *) zend_object_store_get_object(this_ptr TSRMLS_CC); zend_object_value new_ov = date_object_new_date_ex(old_obj->std.ce, &new_obj TSRMLS_CC); zend_objects_clone_members(&new_obj->std, new_ov, &old_obj->std, Z_OBJ_HANDLE_P(this_ptr) TSRMLS_CC); /* this should probably moved to a new `timelib_time *timelime_time_clone(timelib_time *)` */ new_obj->time = timelib_time_ctor(); *new_obj->time = *old_obj->time; if (old_obj->time->tz_abbr) { new_obj->time->tz_abbr = strdup(old_obj->time->tz_abbr); } if (old_obj->time->tz_info) { new_obj->time->tz_info = old_obj->time->tz_info; } return new_ov; } static int date_object_compare_date(zval *d1, zval *d2 TSRMLS_DC) { if (Z_TYPE_P(d1) == IS_OBJECT && Z_TYPE_P(d2) == IS_OBJECT && instanceof_function(Z_OBJCE_P(d1), date_ce_date TSRMLS_CC) && instanceof_function(Z_OBJCE_P(d2), date_ce_date TSRMLS_CC)) { php_date_obj *o1 = zend_object_store_get_object(d1 TSRMLS_CC); php_date_obj *o2 = zend_object_store_get_object(d2 TSRMLS_CC); if (!o1->time->sse_uptodate) { timelib_update_ts(o1->time, o1->time->tz_info); } if (!o2->time->sse_uptodate) { timelib_update_ts(o2->time, o2->time->tz_info); } return (o1->time->sse == o2->time->sse) ? 0 : ((o1->time->sse < o2->time->sse) ? -1 : 1); } return 1; } static HashTable *date_object_get_properties(zval *object TSRMLS_DC) { HashTable *props; zval *zv; php_date_obj *dateobj; dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); props = zend_std_get_properties(object TSRMLS_CC); if (!dateobj->time || GC_G(gc_active)) { return props; } /* first we add the date and time in ISO format */ MAKE_STD_ZVAL(zv); ZVAL_STRING(zv, date_format("Y-m-d H:i:s", 12, dateobj->time, 1), 0); zend_hash_update(props, "date", 5, &zv, sizeof(zval), NULL); /* then we add the timezone name (or similar) */ if (dateobj->time->is_localtime) { MAKE_STD_ZVAL(zv); ZVAL_LONG(zv, dateobj->time->zone_type); zend_hash_update(props, "timezone_type", 14, &zv, sizeof(zval), NULL); MAKE_STD_ZVAL(zv); switch (dateobj->time->zone_type) { case TIMELIB_ZONETYPE_ID: ZVAL_STRING(zv, dateobj->time->tz_info->name, 1); break; case TIMELIB_ZONETYPE_OFFSET: { char *tmpstr = emalloc(sizeof("UTC+05:00")); timelib_sll utc_offset = dateobj->time->z; snprintf(tmpstr, sizeof("+05:00"), "%c%02d:%02d", utc_offset > 0 ? '-' : '+', abs(utc_offset / 60), abs((utc_offset % 60))); ZVAL_STRING(zv, tmpstr, 0); } break; case TIMELIB_ZONETYPE_ABBR: ZVAL_STRING(zv, dateobj->time->tz_abbr, 1); break; } zend_hash_update(props, "timezone", 9, &zv, sizeof(zval), NULL); } return props; } static inline zend_object_value date_object_new_timezone_ex(zend_class_entry *class_type, php_timezone_obj **ptr TSRMLS_DC) { php_timezone_obj *intern; zend_object_value retval; intern = emalloc(sizeof(php_timezone_obj)); memset(intern, 0, sizeof(php_timezone_obj)); if (ptr) { *ptr = intern; } zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) date_object_free_storage_timezone, NULL TSRMLS_CC); retval.handlers = &date_object_handlers_timezone; return retval; } static zend_object_value date_object_new_timezone(zend_class_entry *class_type TSRMLS_DC) { return date_object_new_timezone_ex(class_type, NULL TSRMLS_CC); } static zend_object_value date_object_clone_timezone(zval *this_ptr TSRMLS_DC) { php_timezone_obj *new_obj = NULL; php_timezone_obj *old_obj = (php_timezone_obj *) zend_object_store_get_object(this_ptr TSRMLS_CC); zend_object_value new_ov = date_object_new_timezone_ex(old_obj->std.ce, &new_obj TSRMLS_CC); zend_objects_clone_members(&new_obj->std, new_ov, &old_obj->std, Z_OBJ_HANDLE_P(this_ptr) TSRMLS_CC); new_obj->type = old_obj->type; new_obj->initialized = 1; switch (new_obj->type) { case TIMELIB_ZONETYPE_ID: new_obj->tzi.tz = old_obj->tzi.tz; break; case TIMELIB_ZONETYPE_OFFSET: new_obj->tzi.utc_offset = old_obj->tzi.utc_offset; break; case TIMELIB_ZONETYPE_ABBR: new_obj->tzi.z.utc_offset = old_obj->tzi.z.utc_offset; new_obj->tzi.z.dst = old_obj->tzi.z.dst; new_obj->tzi.z.abbr = old_obj->tzi.z.abbr; break; } return new_ov; } static inline zend_object_value date_object_new_interval_ex(zend_class_entry *class_type, php_interval_obj **ptr TSRMLS_DC) { php_interval_obj *intern; zend_object_value retval; intern = emalloc(sizeof(php_interval_obj)); memset(intern, 0, sizeof(php_interval_obj)); if (ptr) { *ptr = intern; } zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) date_object_free_storage_interval, NULL TSRMLS_CC); retval.handlers = &date_object_handlers_interval; return retval; } static zend_object_value date_object_new_interval(zend_class_entry *class_type TSRMLS_DC) { return date_object_new_interval_ex(class_type, NULL TSRMLS_CC); } static zend_object_value date_object_clone_interval(zval *this_ptr TSRMLS_DC) { php_interval_obj *new_obj = NULL; php_interval_obj *old_obj = (php_interval_obj *) zend_object_store_get_object(this_ptr TSRMLS_CC); zend_object_value new_ov = date_object_new_interval_ex(old_obj->std.ce, &new_obj TSRMLS_CC); zend_objects_clone_members(&new_obj->std, new_ov, &old_obj->std, Z_OBJ_HANDLE_P(this_ptr) TSRMLS_CC); /** FIX ME ADD CLONE STUFF **/ return new_ov; } static HashTable *date_object_get_properties_interval(zval *object TSRMLS_DC) { HashTable *props; zval *zv; php_interval_obj *intervalobj; intervalobj = (php_interval_obj *) zend_object_store_get_object(object TSRMLS_CC); props = zend_std_get_properties(object TSRMLS_CC); if (!intervalobj->initialized || GC_G(gc_active)) { return props; } #define PHP_DATE_INTERVAL_ADD_PROPERTY(n,f) \ MAKE_STD_ZVAL(zv); \ ZVAL_LONG(zv, intervalobj->diff->f); \ zend_hash_update(props, n, strlen(n) + 1, &zv, sizeof(zval), NULL); PHP_DATE_INTERVAL_ADD_PROPERTY("y", y); PHP_DATE_INTERVAL_ADD_PROPERTY("m", m); PHP_DATE_INTERVAL_ADD_PROPERTY("d", d); PHP_DATE_INTERVAL_ADD_PROPERTY("h", h); PHP_DATE_INTERVAL_ADD_PROPERTY("i", i); PHP_DATE_INTERVAL_ADD_PROPERTY("s", s); PHP_DATE_INTERVAL_ADD_PROPERTY("invert", invert); if (intervalobj->diff->days != -99999) { PHP_DATE_INTERVAL_ADD_PROPERTY("days", days); } else { MAKE_STD_ZVAL(zv); ZVAL_FALSE(zv); zend_hash_update(props, "days", 5, &zv, sizeof(zval), NULL); } return props; } static inline zend_object_value date_object_new_period_ex(zend_class_entry *class_type, php_period_obj **ptr TSRMLS_DC) { php_period_obj *intern; zend_object_value retval; intern = emalloc(sizeof(php_period_obj)); memset(intern, 0, sizeof(php_period_obj)); if (ptr) { *ptr = intern; } zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) date_object_free_storage_period, NULL TSRMLS_CC); retval.handlers = &date_object_handlers_period; return retval; } static zend_object_value date_object_new_period(zend_class_entry *class_type TSRMLS_DC) { return date_object_new_period_ex(class_type, NULL TSRMLS_CC); } static zend_object_value date_object_clone_period(zval *this_ptr TSRMLS_DC) { php_period_obj *new_obj = NULL; php_period_obj *old_obj = (php_period_obj *) zend_object_store_get_object(this_ptr TSRMLS_CC); zend_object_value new_ov = date_object_new_period_ex(old_obj->std.ce, &new_obj TSRMLS_CC); zend_objects_clone_members(&new_obj->std, new_ov, &old_obj->std, Z_OBJ_HANDLE_P(this_ptr) TSRMLS_CC); /** FIX ME ADD CLONE STUFF **/ return new_ov; } static void date_object_free_storage_date(void *object TSRMLS_DC) { php_date_obj *intern = (php_date_obj *)object; if (intern->time) { timelib_time_dtor(intern->time); } zend_object_std_dtor(&intern->std TSRMLS_CC); efree(object); } static void date_object_free_storage_timezone(void *object TSRMLS_DC) { php_timezone_obj *intern = (php_timezone_obj *)object; if (intern->type == TIMELIB_ZONETYPE_ABBR) { free(intern->tzi.z.abbr); } zend_object_std_dtor(&intern->std TSRMLS_CC); efree(object); } static void date_object_free_storage_interval(void *object TSRMLS_DC) { php_interval_obj *intern = (php_interval_obj *)object; timelib_rel_time_dtor(intern->diff); zend_object_std_dtor(&intern->std TSRMLS_CC); efree(object); } static void date_object_free_storage_period(void *object TSRMLS_DC) { php_period_obj *intern = (php_period_obj *)object; if (intern->start) { timelib_time_dtor(intern->start); } if (intern->current) { timelib_time_dtor(intern->current); } if (intern->end) { timelib_time_dtor(intern->end); } timelib_rel_time_dtor(intern->interval); zend_object_std_dtor(&intern->std TSRMLS_CC); efree(object); } /* Advanced Interface */ PHPAPI zval *php_date_instantiate(zend_class_entry *pce, zval *object TSRMLS_DC) { Z_TYPE_P(object) = IS_OBJECT; object_init_ex(object, pce); Z_SET_REFCOUNT_P(object, 1); Z_UNSET_ISREF_P(object); return object; } /* Helper function used to store the latest found warnings and errors while * parsing, from either strtotime or parse_from_format. */ static void update_errors_warnings(timelib_error_container *last_errors TSRMLS_DC) { if (DATEG(last_errors)) { timelib_error_container_dtor(DATEG(last_errors)); DATEG(last_errors) = NULL; } DATEG(last_errors) = last_errors; } PHPAPI int php_date_initialize(php_date_obj *dateobj, /*const*/ char *time_str, int time_str_len, char *format, zval *timezone_object, int ctor TSRMLS_DC) { timelib_time *now; timelib_tzinfo *tzi; timelib_error_container *err = NULL; int type = TIMELIB_ZONETYPE_ID, new_dst; char *new_abbr; timelib_sll new_offset; if (dateobj->time) { timelib_time_dtor(dateobj->time); } if (format) { dateobj->time = timelib_parse_from_format(format, time_str_len ? time_str : "", time_str_len ? time_str_len : 0, &err, DATE_TIMEZONEDB); } else { dateobj->time = timelib_strtotime(time_str_len ? time_str : "now", time_str_len ? time_str_len : sizeof("now") -1, &err, DATE_TIMEZONEDB); } /* update last errors and warnings */ update_errors_warnings(err TSRMLS_CC); if (ctor && err && err->error_count) { /* spit out the first library error message, at least */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse time string (%s) at position %d (%c): %s", time_str, err->error_messages[0].position, err->error_messages[0].character, err->error_messages[0].message); } if (err && err->error_count) { return 0; } if (timezone_object) { php_timezone_obj *tzobj; tzobj = (php_timezone_obj *) zend_object_store_get_object(timezone_object TSRMLS_CC); switch (tzobj->type) { case TIMELIB_ZONETYPE_ID: tzi = tzobj->tzi.tz; break; case TIMELIB_ZONETYPE_OFFSET: new_offset = tzobj->tzi.utc_offset; break; case TIMELIB_ZONETYPE_ABBR: new_offset = tzobj->tzi.z.utc_offset; new_dst = tzobj->tzi.z.dst; new_abbr = strdup(tzobj->tzi.z.abbr); break; } type = tzobj->type; } else if (dateobj->time->tz_info) { tzi = dateobj->time->tz_info; } else { tzi = get_timezone_info(TSRMLS_C); } now = timelib_time_ctor(); now->zone_type = type; switch (type) { case TIMELIB_ZONETYPE_ID: now->tz_info = tzi; break; case TIMELIB_ZONETYPE_OFFSET: now->z = new_offset; break; case TIMELIB_ZONETYPE_ABBR: now->z = new_offset; now->dst = new_dst; now->tz_abbr = new_abbr; break; } timelib_unixtime2local(now, (timelib_sll) time(NULL)); timelib_fill_holes(dateobj->time, now, TIMELIB_NO_CLONE); timelib_update_ts(dateobj->time, tzi); dateobj->time->have_relative = 0; timelib_time_dtor(now); return 1; } /* {{{ proto DateTime date_create([string time[, DateTimeZone object]]) Returns new DateTime object */ PHP_FUNCTION(date_create) { zval *timezone_object = NULL; char *time_str = NULL; int time_str_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sO!", &time_str, &time_str_len, &timezone_object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } php_date_instantiate(date_ce_date, return_value TSRMLS_CC); if (!php_date_initialize(zend_object_store_get_object(return_value TSRMLS_CC), time_str, time_str_len, NULL, timezone_object, 0 TSRMLS_CC)) { RETURN_FALSE; } } /* }}} */ /* {{{ proto DateTime date_create_from_format(string format, string time[, DateTimeZone object]) Returns new DateTime object formatted according to the specified format */ PHP_FUNCTION(date_create_from_format) { zval *timezone_object = NULL; char *time_str = NULL, *format_str = NULL; int time_str_len = 0, format_str_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|O", &format_str, &format_str_len, &time_str, &time_str_len, &timezone_object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } php_date_instantiate(date_ce_date, return_value TSRMLS_CC); if (!php_date_initialize(zend_object_store_get_object(return_value TSRMLS_CC), time_str, time_str_len, format_str, timezone_object, 0 TSRMLS_CC)) { RETURN_FALSE; } } /* }}} */ /* {{{ proto DateTime::__construct([string time[, DateTimeZone object]]) Creates new DateTime object */ PHP_METHOD(DateTime, __construct) { zval *timezone_object = NULL; char *time_str = NULL; int time_str_len = 0; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sO!", &time_str, &time_str_len, &timezone_object, date_ce_timezone)) { php_date_initialize(zend_object_store_get_object(getThis() TSRMLS_CC), time_str, time_str_len, NULL, timezone_object, 1 TSRMLS_CC); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ static int php_date_initialize_from_hash(zval **return_value, php_date_obj **dateobj, HashTable *myht TSRMLS_DC) { zval **z_date = NULL; zval **z_timezone = NULL; zval **z_timezone_type = NULL; zval *tmp_obj = NULL; timelib_tzinfo *tzi; php_timezone_obj *tzobj; if (zend_hash_find(myht, "date", 5, (void**) &z_date) == SUCCESS) { convert_to_string(*z_date); if (zend_hash_find(myht, "timezone_type", 14, (void**) &z_timezone_type) == SUCCESS) { convert_to_long(*z_timezone_type); if (zend_hash_find(myht, "timezone", 9, (void**) &z_timezone) == SUCCESS) { convert_to_string(*z_timezone); switch (Z_LVAL_PP(z_timezone_type)) { case TIMELIB_ZONETYPE_OFFSET: case TIMELIB_ZONETYPE_ABBR: { char *tmp = emalloc(Z_STRLEN_PP(z_date) + Z_STRLEN_PP(z_timezone) + 2); snprintf(tmp, Z_STRLEN_PP(z_date) + Z_STRLEN_PP(z_timezone) + 2, "%s %s", Z_STRVAL_PP(z_date), Z_STRVAL_PP(z_timezone)); php_date_initialize(*dateobj, tmp, Z_STRLEN_PP(z_date) + Z_STRLEN_PP(z_timezone) + 1, NULL, NULL, 0 TSRMLS_CC); efree(tmp); return 1; } case TIMELIB_ZONETYPE_ID: convert_to_string(*z_timezone); tzi = php_date_parse_tzfile(Z_STRVAL_PP(z_timezone), DATE_TIMEZONEDB TSRMLS_CC); ALLOC_INIT_ZVAL(tmp_obj); tzobj = zend_object_store_get_object(php_date_instantiate(date_ce_timezone, tmp_obj TSRMLS_CC) TSRMLS_CC); tzobj->type = TIMELIB_ZONETYPE_ID; tzobj->tzi.tz = tzi; tzobj->initialized = 1; php_date_initialize(*dateobj, Z_STRVAL_PP(z_date), Z_STRLEN_PP(z_date), NULL, tmp_obj, 0 TSRMLS_CC); zval_ptr_dtor(&tmp_obj); return 1; } } } } return 0; } /* {{{ proto DateTime::__set_state() */ PHP_METHOD(DateTime, __set_state) { php_date_obj *dateobj; zval *array; HashTable *myht; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) { RETURN_FALSE; } myht = HASH_OF(array); php_date_instantiate(date_ce_date, return_value TSRMLS_CC); dateobj = (php_date_obj *) zend_object_store_get_object(return_value TSRMLS_CC); php_date_initialize_from_hash(&return_value, &dateobj, myht TSRMLS_CC); } /* }}} */ /* {{{ proto DateTime::__wakeup() */ PHP_METHOD(DateTime, __wakeup) { zval *object = getThis(); php_date_obj *dateobj; HashTable *myht; dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); myht = Z_OBJPROP_P(object); php_date_initialize_from_hash(&return_value, &dateobj, myht TSRMLS_CC); } /* }}} */ /* Helper function used to add an associative array of warnings and errors to a zval */ static void zval_from_error_container(zval *z, timelib_error_container *error) { int i; zval *element; add_assoc_long(z, "warning_count", error->warning_count); MAKE_STD_ZVAL(element); array_init(element); for (i = 0; i < error->warning_count; i++) { add_index_string(element, error->warning_messages[i].position, error->warning_messages[i].message, 1); } add_assoc_zval(z, "warnings", element); add_assoc_long(z, "error_count", error->error_count); MAKE_STD_ZVAL(element); array_init(element); for (i = 0; i < error->error_count; i++) { add_index_string(element, error->error_messages[i].position, error->error_messages[i].message, 1); } add_assoc_zval(z, "errors", element); } /* {{{ proto array date_get_last_errors() Returns the warnings and errors found while parsing a date/time string. */ PHP_FUNCTION(date_get_last_errors) { if (DATEG(last_errors)) { array_init(return_value); zval_from_error_container(return_value, DATEG(last_errors)); } else { RETURN_FALSE; } } /* }}} */ void php_date_do_return_parsed_time(INTERNAL_FUNCTION_PARAMETERS, timelib_time *parsed_time, struct timelib_error_container *error) { zval *element; array_init(return_value); #define PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(name, elem) \ if (parsed_time->elem == -99999) { \ add_assoc_bool(return_value, #name, 0); \ } else { \ add_assoc_long(return_value, #name, parsed_time->elem); \ } PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(year, y); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(month, m); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(day, d); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(hour, h); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(minute, i); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(second, s); if (parsed_time->f == -99999) { add_assoc_bool(return_value, "fraction", 0); } else { add_assoc_double(return_value, "fraction", parsed_time->f); } zval_from_error_container(return_value, error); timelib_error_container_dtor(error); add_assoc_bool(return_value, "is_localtime", parsed_time->is_localtime); if (parsed_time->is_localtime) { PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(zone_type, zone_type); switch (parsed_time->zone_type) { case TIMELIB_ZONETYPE_OFFSET: PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(zone, z); add_assoc_bool(return_value, "is_dst", parsed_time->dst); break; case TIMELIB_ZONETYPE_ID: if (parsed_time->tz_abbr) { add_assoc_string(return_value, "tz_abbr", parsed_time->tz_abbr, 1); } if (parsed_time->tz_info) { add_assoc_string(return_value, "tz_id", parsed_time->tz_info->name, 1); } break; case TIMELIB_ZONETYPE_ABBR: PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(zone, z); add_assoc_bool(return_value, "is_dst", parsed_time->dst); add_assoc_string(return_value, "tz_abbr", parsed_time->tz_abbr, 1); break; } } if (parsed_time->have_relative) { MAKE_STD_ZVAL(element); array_init(element); add_assoc_long(element, "year", parsed_time->relative.y); add_assoc_long(element, "month", parsed_time->relative.m); add_assoc_long(element, "day", parsed_time->relative.d); add_assoc_long(element, "hour", parsed_time->relative.h); add_assoc_long(element, "minute", parsed_time->relative.i); add_assoc_long(element, "second", parsed_time->relative.s); if (parsed_time->relative.have_weekday_relative) { add_assoc_long(element, "weekday", parsed_time->relative.weekday); } if (parsed_time->relative.have_special_relative && (parsed_time->relative.special.type == TIMELIB_SPECIAL_WEEKDAY)) { add_assoc_long(element, "weekdays", parsed_time->relative.special.amount); } if (parsed_time->relative.first_last_day_of) { add_assoc_bool(element, parsed_time->relative.first_last_day_of == 1 ? "first_day_of_month" : "last_day_of_month", 1); } add_assoc_zval(return_value, "relative", element); } timelib_time_dtor(parsed_time); } /* {{{ proto array date_parse(string date) Returns associative array with detailed info about given date */ PHP_FUNCTION(date_parse) { char *date; int date_len; struct timelib_error_container *error; timelib_time *parsed_time; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &date, &date_len) == FAILURE) { RETURN_FALSE; } parsed_time = timelib_strtotime(date, date_len, &error, DATE_TIMEZONEDB); php_date_do_return_parsed_time(INTERNAL_FUNCTION_PARAM_PASSTHRU, parsed_time, error); } /* }}} */ /* {{{ proto array date_parse_from_format(string format, string date) Returns associative array with detailed info about given date */ PHP_FUNCTION(date_parse_from_format) { char *date, *format; int date_len, format_len; struct timelib_error_container *error; timelib_time *parsed_time; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &format, &format_len, &date, &date_len) == FAILURE) { RETURN_FALSE; } parsed_time = timelib_parse_from_format(format, date, date_len, &error, DATE_TIMEZONEDB); php_date_do_return_parsed_time(INTERNAL_FUNCTION_PARAM_PASSTHRU, parsed_time, error); } /* }}} */ /* {{{ proto string date_format(DateTime object, string format) Returns date formatted according to given format */ PHP_FUNCTION(date_format) { zval *object; php_date_obj *dateobj; char *format; int format_len; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, date_ce_date, &format, &format_len) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); RETURN_STRING(date_format(format, format_len, dateobj->time, dateobj->time->is_localtime), 0); } /* }}} */ /* {{{ proto DateTime date_modify(DateTime object, string modify) Alters the timestamp. */ PHP_FUNCTION(date_modify) { zval *object; php_date_obj *dateobj; char *modify; int modify_len; timelib_time *tmp_time; timelib_error_container *err = NULL; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, date_ce_date, &modify, &modify_len) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); tmp_time = timelib_strtotime(modify, modify_len, &err, DATE_TIMEZONEDB); /* update last errors and warnings */ update_errors_warnings(err TSRMLS_CC); if (err && err->error_count) { /* spit out the first library error message, at least */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse time string (%s) at position %d (%c): %s", modify, err->error_messages[0].position, err->error_messages[0].character, err->error_messages[0].message); timelib_time_dtor(tmp_time); RETURN_FALSE; } memcpy(&dateobj->time->relative, &tmp_time->relative, sizeof(struct timelib_rel_time)); dateobj->time->have_relative = tmp_time->have_relative; dateobj->time->sse_uptodate = 0; if (tmp_time->y != -99999) { dateobj->time->y = tmp_time->y; } if (tmp_time->m != -99999) { dateobj->time->m = tmp_time->m; } if (tmp_time->d != -99999) { dateobj->time->d = tmp_time->d; } if (tmp_time->h != -99999) { dateobj->time->h = tmp_time->h; if (tmp_time->i != -99999) { dateobj->time->i = tmp_time->i; if (tmp_time->s != -99999) { dateobj->time->s = tmp_time->s; } else { dateobj->time->s = 0; } } else { dateobj->time->i = 0; dateobj->time->s = 0; } } timelib_time_dtor(tmp_time); timelib_update_ts(dateobj->time, NULL); timelib_update_from_sse(dateobj->time); dateobj->time->have_relative = 0; RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_add(DateTime object, DateInterval interval) Adds an interval to the current date in object. */ PHP_FUNCTION(date_add) { zval *object, *interval; php_date_obj *dateobj; php_interval_obj *intobj; int bias = 1; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &object, date_ce_date, &interval, date_ce_interval) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); intobj = (php_interval_obj *) zend_object_store_get_object(interval TSRMLS_CC); DATE_CHECK_INITIALIZED(intobj->initialized, DateInterval); if (intobj->diff->have_weekday_relative || intobj->diff->have_special_relative) { memcpy(&dateobj->time->relative, intobj->diff, sizeof(struct timelib_rel_time)); } else { if (intobj->diff->invert) { bias = -1; } dateobj->time->relative.y = intobj->diff->y * bias; dateobj->time->relative.m = intobj->diff->m * bias; dateobj->time->relative.d = intobj->diff->d * bias; dateobj->time->relative.h = intobj->diff->h * bias; dateobj->time->relative.i = intobj->diff->i * bias; dateobj->time->relative.s = intobj->diff->s * bias; dateobj->time->relative.weekday = 0; dateobj->time->relative.have_weekday_relative = 0; } dateobj->time->have_relative = 1; dateobj->time->sse_uptodate = 0; timelib_update_ts(dateobj->time, NULL); timelib_update_from_sse(dateobj->time); dateobj->time->have_relative = 0; RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_sub(DateTime object, DateInterval interval) Subtracts an interval to the current date in object. */ PHP_FUNCTION(date_sub) { zval *object, *interval; php_date_obj *dateobj; php_interval_obj *intobj; int bias = 1; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &object, date_ce_date, &interval, date_ce_interval) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); intobj = (php_interval_obj *) zend_object_store_get_object(interval TSRMLS_CC); DATE_CHECK_INITIALIZED(intobj->initialized, DateInterval); if (intobj->diff->have_special_relative) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Only non-special relative time specifications are supported for subtraction"); return; } if (intobj->diff->invert) { bias = -1; } dateobj->time->relative.y = 0 - (intobj->diff->y * bias); dateobj->time->relative.m = 0 - (intobj->diff->m * bias); dateobj->time->relative.d = 0 - (intobj->diff->d * bias); dateobj->time->relative.h = 0 - (intobj->diff->h * bias); dateobj->time->relative.i = 0 - (intobj->diff->i * bias); dateobj->time->relative.s = 0 - (intobj->diff->s * bias); dateobj->time->have_relative = 1; dateobj->time->relative.weekday = 0; dateobj->time->relative.have_weekday_relative = 0; dateobj->time->sse_uptodate = 0; timelib_update_ts(dateobj->time, NULL); timelib_update_from_sse(dateobj->time); dateobj->time->have_relative = 0; RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTimeZone date_timezone_get(DateTime object) Return new DateTimeZone object relative to give DateTime */ PHP_FUNCTION(date_timezone_get) { zval *object; php_date_obj *dateobj; php_timezone_obj *tzobj; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_date) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); if (dateobj->time->is_localtime/* && dateobj->time->tz_info*/) { php_date_instantiate(date_ce_timezone, return_value TSRMLS_CC); tzobj = (php_timezone_obj *) zend_object_store_get_object(return_value TSRMLS_CC); tzobj->initialized = 1; tzobj->type = dateobj->time->zone_type; switch (dateobj->time->zone_type) { case TIMELIB_ZONETYPE_ID: tzobj->tzi.tz = dateobj->time->tz_info; break; case TIMELIB_ZONETYPE_OFFSET: tzobj->tzi.utc_offset = dateobj->time->z; break; case TIMELIB_ZONETYPE_ABBR: tzobj->tzi.z.utc_offset = dateobj->time->z; tzobj->tzi.z.dst = dateobj->time->dst; tzobj->tzi.z.abbr = strdup(dateobj->time->tz_abbr); break; } } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto DateTime date_timezone_set(DateTime object, DateTimeZone object) Sets the timezone for the DateTime object. */ PHP_FUNCTION(date_timezone_set) { zval *object; zval *timezone_object; php_date_obj *dateobj; php_timezone_obj *tzobj; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &object, date_ce_date, &timezone_object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); tzobj = (php_timezone_obj *) zend_object_store_get_object(timezone_object TSRMLS_CC); if (tzobj->type != TIMELIB_ZONETYPE_ID) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can only do this for zones with ID for now"); return; } timelib_set_timezone(dateobj->time, tzobj->tzi.tz); timelib_unixtime2local(dateobj->time, dateobj->time->sse); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto long date_offset_get(DateTime object) Returns the DST offset. */ PHP_FUNCTION(date_offset_get) { zval *object; php_date_obj *dateobj; timelib_time_offset *offset; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_date) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); if (dateobj->time->is_localtime/* && dateobj->time->tz_info*/) { switch (dateobj->time->zone_type) { case TIMELIB_ZONETYPE_ID: offset = timelib_get_time_zone_info(dateobj->time->sse, dateobj->time->tz_info); RETVAL_LONG(offset->offset); timelib_time_offset_dtor(offset); break; case TIMELIB_ZONETYPE_OFFSET: RETVAL_LONG(dateobj->time->z * -60); break; case TIMELIB_ZONETYPE_ABBR: RETVAL_LONG((dateobj->time->z - (60 * dateobj->time->dst)) * -60); break; } return; } else { RETURN_LONG(0); } } /* }}} */ /* {{{ proto DateTime date_time_set(DateTime object, long hour, long minute[, long second]) Sets the time. */ PHP_FUNCTION(date_time_set) { zval *object; php_date_obj *dateobj; long h, i, s = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oll|l", &object, date_ce_date, &h, &i, &s) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); dateobj->time->h = h; dateobj->time->i = i; dateobj->time->s = s; timelib_update_ts(dateobj->time, NULL); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_date_set(DateTime object, long year, long month, long day) Sets the date. */ PHP_FUNCTION(date_date_set) { zval *object; php_date_obj *dateobj; long y, m, d; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Olll", &object, date_ce_date, &y, &m, &d) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); dateobj->time->y = y; dateobj->time->m = m; dateobj->time->d = d; timelib_update_ts(dateobj->time, NULL); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_isodate_set(DateTime object, long year, long week[, long day]) Sets the ISO date. */ PHP_FUNCTION(date_isodate_set) { zval *object; php_date_obj *dateobj; long y, w, d = 1; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oll|l", &object, date_ce_date, &y, &w, &d) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); dateobj->time->y = y; dateobj->time->m = 1; dateobj->time->d = 1; dateobj->time->relative.d = timelib_daynr_from_weeknr(y, w, d); dateobj->time->have_relative = 1; timelib_update_ts(dateobj->time, NULL); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_timestamp_set(DateTime object, long unixTimestamp) Sets the date and time based on an Unix timestamp. */ PHP_FUNCTION(date_timestamp_set) { zval *object; php_date_obj *dateobj; long timestamp; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Ol", &object, date_ce_date, &timestamp) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); timelib_unixtime2local(dateobj->time, (timelib_sll)timestamp); timelib_update_ts(dateobj->time, NULL); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto long date_timestamp_get(DateTime object) Gets the Unix timestamp. */ PHP_FUNCTION(date_timestamp_get) { zval *object; php_date_obj *dateobj; long timestamp; int error; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_date) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); timelib_update_ts(dateobj->time, NULL); timestamp = timelib_date_to_int(dateobj->time, &error); if (error) { RETURN_FALSE; } else { RETVAL_LONG(timestamp); } } /* }}} */ /* {{{ proto DateInterval date_diff(DateTime object [, bool absolute]) Returns the difference between two DateTime objects. */ PHP_FUNCTION(date_diff) { zval *object1, *object2; php_date_obj *dateobj1, *dateobj2; php_interval_obj *interval; long absolute = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO|l", &object1, date_ce_date, &object2, date_ce_date, &absolute) == FAILURE) { RETURN_FALSE; } dateobj1 = (php_date_obj *) zend_object_store_get_object(object1 TSRMLS_CC); dateobj2 = (php_date_obj *) zend_object_store_get_object(object2 TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj1->time, DateTime); DATE_CHECK_INITIALIZED(dateobj2->time, DateTime); timelib_update_ts(dateobj1->time, NULL); timelib_update_ts(dateobj2->time, NULL); php_date_instantiate(date_ce_interval, return_value TSRMLS_CC); interval = zend_object_store_get_object(return_value TSRMLS_CC); interval->diff = timelib_diff(dateobj1->time, dateobj2->time); if (absolute) { interval->diff->invert = 0; } interval->initialized = 1; } /* }}} */ static int timezone_initialize(timelib_tzinfo **tzi, /*const*/ char *tz TSRMLS_DC) { char *tzid; *tzi = NULL; if ((tzid = timelib_timezone_id_from_abbr(tz, -1, 0))) { *tzi = php_date_parse_tzfile(tzid, DATE_TIMEZONEDB TSRMLS_CC); } else { *tzi = php_date_parse_tzfile(tz, DATE_TIMEZONEDB TSRMLS_CC); } if (*tzi) { return SUCCESS; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown or bad timezone (%s)", tz); return FAILURE; } } /* {{{ proto DateTimeZone timezone_open(string timezone) Returns new DateTimeZone object */ PHP_FUNCTION(timezone_open) { char *tz; int tz_len; timelib_tzinfo *tzi = NULL; php_timezone_obj *tzobj; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &tz, &tz_len) == FAILURE) { RETURN_FALSE; } if (SUCCESS != timezone_initialize(&tzi, tz TSRMLS_CC)) { RETURN_FALSE; } tzobj = zend_object_store_get_object(php_date_instantiate(date_ce_timezone, return_value TSRMLS_CC) TSRMLS_CC); tzobj->type = TIMELIB_ZONETYPE_ID; tzobj->tzi.tz = tzi; tzobj->initialized = 1; } /* }}} */ /* {{{ proto DateTimeZone::__construct(string timezone) Creates new DateTimeZone object. */ PHP_METHOD(DateTimeZone, __construct) { char *tz; int tz_len; timelib_tzinfo *tzi = NULL; php_timezone_obj *tzobj; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &tz, &tz_len)) { if (SUCCESS == timezone_initialize(&tzi, tz TSRMLS_CC)) { tzobj = zend_object_store_get_object(getThis() TSRMLS_CC); tzobj->type = TIMELIB_ZONETYPE_ID; tzobj->tzi.tz = tzi; tzobj->initialized = 1; } else { ZVAL_NULL(getThis()); } } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto string timezone_name_get(DateTimeZone object) Returns the name of the timezone. */ PHP_FUNCTION(timezone_name_get) { zval *object; php_timezone_obj *tzobj; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } tzobj = (php_timezone_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(tzobj->initialized, DateTimeZone); switch (tzobj->type) { case TIMELIB_ZONETYPE_ID: RETURN_STRING(tzobj->tzi.tz->name, 1); break; case TIMELIB_ZONETYPE_OFFSET: { char *tmpstr = emalloc(sizeof("UTC+05:00")); timelib_sll utc_offset = tzobj->tzi.utc_offset; snprintf(tmpstr, sizeof("+05:00"), "%c%02d:%02d", utc_offset > 0 ? '-' : '+', abs(utc_offset / 60), abs((utc_offset % 60))); RETURN_STRING(tmpstr, 0); } break; case TIMELIB_ZONETYPE_ABBR: RETURN_STRING(tzobj->tzi.z.abbr, 1); break; } } /* }}} */ /* {{{ proto string timezone_name_from_abbr(string abbr[, long gmtOffset[, long isdst]]) Returns the timezone name from abbrevation */ PHP_FUNCTION(timezone_name_from_abbr) { char *abbr; char *tzid; int abbr_len; long gmtoffset = -1; long isdst = -1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ll", &abbr, &abbr_len, &gmtoffset, &isdst) == FAILURE) { RETURN_FALSE; } tzid = timelib_timezone_id_from_abbr(abbr, gmtoffset, isdst); if (tzid) { RETURN_STRING(tzid, 1); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto long timezone_offset_get(DateTimeZone object, DateTime object) Returns the timezone offset. */ PHP_FUNCTION(timezone_offset_get) { zval *object, *dateobject; php_timezone_obj *tzobj; php_date_obj *dateobj; timelib_time_offset *offset; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &object, date_ce_timezone, &dateobject, date_ce_date) == FAILURE) { RETURN_FALSE; } tzobj = (php_timezone_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(tzobj->initialized, DateTimeZone); dateobj = (php_date_obj *) zend_object_store_get_object(dateobject TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); switch (tzobj->type) { case TIMELIB_ZONETYPE_ID: offset = timelib_get_time_zone_info(dateobj->time->sse, tzobj->tzi.tz); RETVAL_LONG(offset->offset); timelib_time_offset_dtor(offset); break; case TIMELIB_ZONETYPE_OFFSET: RETURN_LONG(tzobj->tzi.utc_offset * -60); break; case TIMELIB_ZONETYPE_ABBR: RETURN_LONG((tzobj->tzi.z.utc_offset - (tzobj->tzi.z.dst*60)) * -60); break; } } /* }}} */ /* {{{ proto array timezone_transitions_get(DateTimeZone object [, long timestamp_begin [, long timestamp_end ]]) Returns numerically indexed array containing associative array for all transitions in the specified range for the timezone. */ PHP_FUNCTION(timezone_transitions_get) { zval *object, *element; php_timezone_obj *tzobj; unsigned int i, begin = 0, found; long timestamp_begin = LONG_MIN, timestamp_end = LONG_MAX; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|ll", &object, date_ce_timezone, &timestamp_begin, &timestamp_end) == FAILURE) { RETURN_FALSE; } tzobj = (php_timezone_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(tzobj->initialized, DateTimeZone); if (tzobj->type != TIMELIB_ZONETYPE_ID) { RETURN_FALSE; } #define add_nominal() \ MAKE_STD_ZVAL(element); \ array_init(element); \ add_assoc_long(element, "ts", timestamp_begin); \ add_assoc_string(element, "time", php_format_date(DATE_FORMAT_ISO8601, 13, timestamp_begin, 0 TSRMLS_CC), 0); \ add_assoc_long(element, "offset", tzobj->tzi.tz->type[0].offset); \ add_assoc_bool(element, "isdst", tzobj->tzi.tz->type[0].isdst); \ add_assoc_string(element, "abbr", &tzobj->tzi.tz->timezone_abbr[tzobj->tzi.tz->type[0].abbr_idx], 1); \ add_next_index_zval(return_value, element); #define add(i,ts) \ MAKE_STD_ZVAL(element); \ array_init(element); \ add_assoc_long(element, "ts", ts); \ add_assoc_string(element, "time", php_format_date(DATE_FORMAT_ISO8601, 13, ts, 0 TSRMLS_CC), 0); \ add_assoc_long(element, "offset", tzobj->tzi.tz->type[tzobj->tzi.tz->trans_idx[i]].offset); \ add_assoc_bool(element, "isdst", tzobj->tzi.tz->type[tzobj->tzi.tz->trans_idx[i]].isdst); \ add_assoc_string(element, "abbr", &tzobj->tzi.tz->timezone_abbr[tzobj->tzi.tz->type[tzobj->tzi.tz->trans_idx[i]].abbr_idx], 1); \ add_next_index_zval(return_value, element); #define add_last() add(tzobj->tzi.tz->timecnt - 1, timestamp_begin) array_init(return_value); if (timestamp_begin == LONG_MIN) { add_nominal(); begin = 0; found = 1; } else { begin = 0; found = 0; if (tzobj->tzi.tz->timecnt > 0) { do { if (tzobj->tzi.tz->trans[begin] > timestamp_begin) { if (begin > 0) { add(begin - 1, timestamp_begin); } else { add_nominal(); } found = 1; break; } begin++; } while (begin < tzobj->tzi.tz->timecnt); } } if (!found) { if (tzobj->tzi.tz->timecnt > 0) { add_last(); } else { add_nominal(); } } else { for (i = begin; i < tzobj->tzi.tz->timecnt; ++i) { if (tzobj->tzi.tz->trans[i] < timestamp_end) { add(i, tzobj->tzi.tz->trans[i]); } } } } /* }}} */ /* {{{ proto array timezone_location_get() Returns location information for a timezone, including country code, latitude/longitude and comments */ PHP_FUNCTION(timezone_location_get) { zval *object; php_timezone_obj *tzobj; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } tzobj = (php_timezone_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(tzobj->initialized, DateTimeZone); if (tzobj->type != TIMELIB_ZONETYPE_ID) { RETURN_FALSE; } array_init(return_value); add_assoc_string(return_value, "country_code", tzobj->tzi.tz->location.country_code, 1); add_assoc_double(return_value, "latitude", tzobj->tzi.tz->location.latitude); add_assoc_double(return_value, "longitude", tzobj->tzi.tz->location.longitude); add_assoc_string(return_value, "comments", tzobj->tzi.tz->location.comments, 1); } /* }}} */ static int date_interval_initialize(timelib_rel_time **rt, /*const*/ char *format, int format_length TSRMLS_DC) { timelib_time *b = NULL, *e = NULL; timelib_rel_time *p = NULL; int r = 0; int retval = 0; struct timelib_error_container *errors; timelib_strtointerval(format, format_length, &b, &e, &p, &r, &errors); if (errors->error_count > 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown or bad format (%s)", format); retval = FAILURE; } else { if(p) { *rt = p; retval = SUCCESS; } else { if(b && e) { timelib_update_ts(b, NULL); timelib_update_ts(e, NULL); *rt = timelib_diff(b, e); retval = SUCCESS; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse interval (%s)", format); retval = FAILURE; } } } timelib_error_container_dtor(errors); return retval; } /* {{{ date_interval_read_property */ zval *date_interval_read_property(zval *object, zval *member, int type, const zend_literal *key TSRMLS_DC) { php_interval_obj *obj; zval *retval; zval tmp_member; timelib_sll value = -1; if (member->type != IS_STRING) { tmp_member = *member; zval_copy_ctor(&tmp_member); convert_to_string(&tmp_member); member = &tmp_member; } obj = (php_interval_obj *)zend_objects_get_address(object TSRMLS_CC); #define GET_VALUE_FROM_STRUCT(n,m) \ if (strcmp(Z_STRVAL_P(member), m) == 0) { \ value = obj->diff->n; \ break; \ } do { GET_VALUE_FROM_STRUCT(y, "y"); GET_VALUE_FROM_STRUCT(m, "m"); GET_VALUE_FROM_STRUCT(d, "d"); GET_VALUE_FROM_STRUCT(h, "h"); GET_VALUE_FROM_STRUCT(i, "i"); GET_VALUE_FROM_STRUCT(s, "s"); GET_VALUE_FROM_STRUCT(invert, "invert"); GET_VALUE_FROM_STRUCT(days, "days"); /* didn't find any */ retval = (zend_get_std_object_handlers())->read_property(object, member, type, key TSRMLS_CC); if (member == &tmp_member) { zval_dtor(member); } return retval; } while(0); ALLOC_INIT_ZVAL(retval); Z_SET_REFCOUNT_P(retval, 0); ZVAL_LONG(retval, value); if (member == &tmp_member) { zval_dtor(member); } return retval; } /* }}} */ /* {{{ date_interval_write_property */ void date_interval_write_property(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC) { php_interval_obj *obj; zval tmp_member, tmp_value; if (member->type != IS_STRING) { tmp_member = *member; zval_copy_ctor(&tmp_member); convert_to_string(&tmp_member); member = &tmp_member; } obj = (php_interval_obj *)zend_objects_get_address(object TSRMLS_CC); #define SET_VALUE_FROM_STRUCT(n,m) \ if (strcmp(Z_STRVAL_P(member), m) == 0) { \ if (value->type != IS_LONG) { \ tmp_value = *value; \ zval_copy_ctor(&tmp_value); \ convert_to_long(&tmp_value); \ value = &tmp_value; \ } \ obj->diff->n = Z_LVAL_P(value); \ if (value == &tmp_value) { \ zval_dtor(value); \ } \ break; \ } do { SET_VALUE_FROM_STRUCT(y, "y"); SET_VALUE_FROM_STRUCT(m, "m"); SET_VALUE_FROM_STRUCT(d, "d"); SET_VALUE_FROM_STRUCT(h, "h"); SET_VALUE_FROM_STRUCT(i, "i"); SET_VALUE_FROM_STRUCT(s, "s"); SET_VALUE_FROM_STRUCT(invert, "invert"); /* didn't find any */ (zend_get_std_object_handlers())->write_property(object, member, value, key TSRMLS_CC); } while(0); if (member == &tmp_member) { zval_dtor(member); } } /* }}} */ /* {{{ proto DateInterval::__construct([string interval_spec]) Creates new DateInterval object. */ PHP_METHOD(DateInterval, __construct) { char *interval_string = NULL; int interval_string_length; php_interval_obj *diobj; timelib_rel_time *reltime; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &interval_string, &interval_string_length) == SUCCESS) { if (date_interval_initialize(&reltime, interval_string, interval_string_length TSRMLS_CC) == SUCCESS) { diobj = zend_object_store_get_object(getThis() TSRMLS_CC); diobj->diff = reltime; diobj->initialized = 1; } else { ZVAL_NULL(getThis()); } } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto DateInterval date_interval_create_from_date_string(string time) Uses the normal date parsers and sets up a DateInterval from the relative parts of the parsed string */ PHP_FUNCTION(date_interval_create_from_date_string) { char *time_str = NULL; int time_str_len = 0; timelib_time *time; timelib_error_container *err = NULL; php_interval_obj *diobj; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &time_str, &time_str_len) == FAILURE) { RETURN_FALSE; } php_date_instantiate(date_ce_interval, return_value TSRMLS_CC); time = timelib_strtotime(time_str, time_str_len, &err, DATE_TIMEZONEDB); diobj = (php_interval_obj *) zend_object_store_get_object(return_value TSRMLS_CC); diobj->diff = timelib_rel_time_clone(&time->relative); diobj->initialized = 1; timelib_time_dtor(time); timelib_error_container_dtor(err); } /* }}} */ /* {{{ date_interval_format - */ static char *date_interval_format(char *format, int format_len, timelib_rel_time *t) { smart_str string = {0}; int i, length, have_format_spec = 0; char buffer[33]; if (!format_len) { return estrdup(""); } for (i = 0; i < format_len; i++) { if (have_format_spec) { switch (format[i]) { case 'Y': length = slprintf(buffer, 32, "%02d", (int) t->y); break; case 'y': length = slprintf(buffer, 32, "%d", (int) t->y); break; case 'M': length = slprintf(buffer, 32, "%02d", (int) t->m); break; case 'm': length = slprintf(buffer, 32, "%d", (int) t->m); break; case 'D': length = slprintf(buffer, 32, "%02d", (int) t->d); break; case 'd': length = slprintf(buffer, 32, "%d", (int) t->d); break; case 'H': length = slprintf(buffer, 32, "%02d", (int) t->h); break; case 'h': length = slprintf(buffer, 32, "%d", (int) t->h); break; case 'I': length = slprintf(buffer, 32, "%02d", (int) t->i); break; case 'i': length = slprintf(buffer, 32, "%d", (int) t->i); break; case 'S': length = slprintf(buffer, 32, "%02d", (int) t->s); break; case 's': length = slprintf(buffer, 32, "%d", (int) t->s); break; case 'a': { if ((int) t->days != -99999) { length = slprintf(buffer, 32, "%d", (int) t->days); } else { length = slprintf(buffer, 32, "(unknown)"); } } break; case 'r': length = slprintf(buffer, 32, "%s", t->invert ? "-" : ""); break; case 'R': length = slprintf(buffer, 32, "%c", t->invert ? '-' : '+'); break; case '%': length = slprintf(buffer, 32, "%%"); break; default: buffer[0] = '%'; buffer[1] = format[i]; buffer[2] = '\0'; length = 2; break; } smart_str_appendl(&string, buffer, length); have_format_spec = 0; } else { if (format[i] == '%') { have_format_spec = 1; } else { smart_str_appendc(&string, format[i]); } } } smart_str_0(&string); return string.c; } /* }}} */ /* {{{ proto string date_interval_format(DateInterval object, string format) Formats the interval. */ PHP_FUNCTION(date_interval_format) { zval *object; php_interval_obj *diobj; char *format; int format_len; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, date_ce_interval, &format, &format_len) == FAILURE) { RETURN_FALSE; } diobj = (php_interval_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(diobj->initialized, DateInterval); RETURN_STRING(date_interval_format(format, format_len, diobj->diff), 0); } /* }}} */ static int date_period_initialize(timelib_time **st, timelib_time **et, timelib_rel_time **d, long *recurrences, /*const*/ char *format, int format_length TSRMLS_DC) { timelib_time *b = NULL, *e = NULL; timelib_rel_time *p = NULL; int r = 0; int retval = 0; struct timelib_error_container *errors; timelib_strtointerval(format, format_length, &b, &e, &p, &r, &errors); if (errors->error_count > 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown or bad format (%s)", format); retval = FAILURE; } else { *st = b; *et = e; *d = p; *recurrences = r; retval = SUCCESS; } timelib_error_container_dtor(errors); return retval; } /* {{{ proto DatePeriod::__construct(DateTime $start, DateInterval $interval, int recurrences|DateTime $end) Creates new DatePeriod object. */ PHP_METHOD(DatePeriod, __construct) { php_period_obj *dpobj; php_date_obj *dateobj; php_interval_obj *intobj; zval *start, *end = NULL, *interval; long recurrences = 0, options = 0; char *isostr = NULL; int isostr_len = 0; timelib_time *clone; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "OOl|l", &start, date_ce_date, &interval, date_ce_interval, &recurrences, &options) == FAILURE) { if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "OOO|l", &start, date_ce_date, &interval, date_ce_interval, &end, date_ce_date, &options) == FAILURE) { if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &isostr, &isostr_len, &options) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "This constructor accepts either (DateTime, DateInterval, int) OR (DateTime, DateInterval, DateTime) OR (string) as arguments."); zend_restore_error_handling(&error_handling TSRMLS_CC); return; } } } dpobj = zend_object_store_get_object(getThis() TSRMLS_CC); dpobj->current = NULL; if (isostr_len) { date_period_initialize(&(dpobj->start), &(dpobj->end), &(dpobj->interval), &recurrences, isostr, isostr_len TSRMLS_CC); if (dpobj->start == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The ISO interval '%s' did not contain a start date.", isostr); } if (dpobj->interval == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The ISO interval '%s' did not contain an interval.", isostr); } if (dpobj->end == NULL && recurrences == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The ISO interval '%s' did not contain an end date or a recurrence count.", isostr); } if (dpobj->start) { timelib_update_ts(dpobj->start, NULL); } if (dpobj->end) { timelib_update_ts(dpobj->end, NULL); } } else { /* init */ intobj = (php_interval_obj *) zend_object_store_get_object(interval TSRMLS_CC); /* start date */ dateobj = (php_date_obj *) zend_object_store_get_object(start TSRMLS_CC); clone = timelib_time_ctor(); memcpy(clone, dateobj->time, sizeof(timelib_time)); if (dateobj->time->tz_abbr) { clone->tz_abbr = strdup(dateobj->time->tz_abbr); } if (dateobj->time->tz_info) { clone->tz_info = dateobj->time->tz_info; } dpobj->start = clone; /* interval */ dpobj->interval = timelib_rel_time_clone(intobj->diff); /* end date */ if (end) { dateobj = (php_date_obj *) zend_object_store_get_object(end TSRMLS_CC); clone = timelib_time_clone(dateobj->time); dpobj->end = clone; } } /* options */ dpobj->include_start_date = !(options & PHP_DATE_PERIOD_EXCLUDE_START_DATE); /* recurrrences */ dpobj->recurrences = recurrences + dpobj->include_start_date; dpobj->initialized = 1; zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ static int check_id_allowed(char *id, long what) { if (what & PHP_DATE_TIMEZONE_GROUP_AFRICA && strncasecmp(id, "Africa/", 7) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_AMERICA && strncasecmp(id, "America/", 8) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_ANTARCTICA && strncasecmp(id, "Antarctica/", 11) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_ARCTIC && strncasecmp(id, "Arctic/", 7) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_ASIA && strncasecmp(id, "Asia/", 5) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_ATLANTIC && strncasecmp(id, "Atlantic/", 9) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_AUSTRALIA && strncasecmp(id, "Australia/", 10) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_EUROPE && strncasecmp(id, "Europe/", 7) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_INDIAN && strncasecmp(id, "Indian/", 7) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_PACIFIC && strncasecmp(id, "Pacific/", 8) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_UTC && strncasecmp(id, "UTC", 3) == 0) return 1; return 0; } /* {{{ proto array timezone_identifiers_list([long what[, string country]]) Returns numerically index array with all timezone identifiers. */ PHP_FUNCTION(timezone_identifiers_list) { const timelib_tzdb *tzdb; const timelib_tzdb_index_entry *table; int i, item_count; long what = PHP_DATE_TIMEZONE_GROUP_ALL; char *option = NULL; int option_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|ls", &what, &option, &option_len) == FAILURE) { RETURN_FALSE; } /* Extra validation */ if (what == PHP_DATE_TIMEZONE_PER_COUNTRY && option_len != 2) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "A two-letter ISO 3166-1 compatible country code is expected"); RETURN_FALSE; } tzdb = DATE_TIMEZONEDB; item_count = tzdb->index_size; table = tzdb->index; array_init(return_value); for (i = 0; i < item_count; ++i) { if (what == PHP_DATE_TIMEZONE_PER_COUNTRY) { if (tzdb->data[table[i].pos + 5] == option[0] && tzdb->data[table[i].pos + 6] == option[1]) { add_next_index_string(return_value, table[i].id, 1); } } else if (what == PHP_DATE_TIMEZONE_GROUP_ALL_W_BC || (check_id_allowed(table[i].id, what) && (tzdb->data[table[i].pos + 4] == '\1'))) { add_next_index_string(return_value, table[i].id, 1); } }; } /* }}} */ /* {{{ proto array timezone_version_get() Returns the Olson database version number. */ PHP_FUNCTION(timezone_version_get) { const timelib_tzdb *tzdb; tzdb = DATE_TIMEZONEDB; RETURN_STRING(tzdb->version, 1); } /* }}} */ /* {{{ proto array timezone_abbreviations_list() Returns associative array containing dst, offset and the timezone name */ PHP_FUNCTION(timezone_abbreviations_list) { const timelib_tz_lookup_table *table, *entry; zval *element, **abbr_array_pp, *abbr_array; table = timelib_timezone_abbreviations_list(); array_init(return_value); entry = table; do { MAKE_STD_ZVAL(element); array_init(element); add_assoc_bool(element, "dst", entry->type); add_assoc_long(element, "offset", entry->gmtoffset); if (entry->full_tz_name) { add_assoc_string(element, "timezone_id", entry->full_tz_name, 1); } else { add_assoc_null(element, "timezone_id"); } if (zend_hash_find(HASH_OF(return_value), entry->name, strlen(entry->name) + 1, (void **) &abbr_array_pp) == FAILURE) { MAKE_STD_ZVAL(abbr_array); array_init(abbr_array); add_assoc_zval(return_value, entry->name, abbr_array); } else { abbr_array = *abbr_array_pp; } add_next_index_zval(abbr_array, element); entry++; } while (entry->name); } /* }}} */ /* {{{ proto bool date_default_timezone_set(string timezone_identifier) Sets the default timezone used by all date/time functions in a script */ PHP_FUNCTION(date_default_timezone_set) { char *zone; int zone_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &zone, &zone_len) == FAILURE) { RETURN_FALSE; } if (!timelib_timezone_id_is_valid(zone, DATE_TIMEZONEDB)) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Timezone ID '%s' is invalid", zone); RETURN_FALSE; } if (DATEG(timezone)) { efree(DATEG(timezone)); DATEG(timezone) = NULL; } DATEG(timezone) = estrndup(zone, zone_len); RETURN_TRUE; } /* }}} */ /* {{{ proto string date_default_timezone_get() Gets the default timezone used by all date/time functions in a script */ PHP_FUNCTION(date_default_timezone_get) { timelib_tzinfo *default_tz; default_tz = get_timezone_info(TSRMLS_C); RETVAL_STRING(default_tz->name, 1); } /* }}} */ /* {{{ php_do_date_sunrise_sunset * Common for date_sunrise() and date_sunset() functions */ static void php_do_date_sunrise_sunset(INTERNAL_FUNCTION_PARAMETERS, int calc_sunset) { double latitude = 0.0, longitude = 0.0, zenith = 0.0, gmt_offset = 0, altitude; double h_rise, h_set, N; timelib_sll rise, set, transit; long time, retformat = 0; int rs; timelib_time *t; timelib_tzinfo *tzi; char *retstr; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|ldddd", &time, &retformat, &latitude, &longitude, &zenith, &gmt_offset) == FAILURE) { RETURN_FALSE; } switch (ZEND_NUM_ARGS()) { case 1: retformat = SUNFUNCS_RET_STRING; case 2: latitude = INI_FLT("date.default_latitude"); case 3: longitude = INI_FLT("date.default_longitude"); case 4: if (calc_sunset) { zenith = INI_FLT("date.sunset_zenith"); } else { zenith = INI_FLT("date.sunrise_zenith"); } case 5: case 6: break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "invalid format"); RETURN_FALSE; break; } if (retformat != SUNFUNCS_RET_TIMESTAMP && retformat != SUNFUNCS_RET_STRING && retformat != SUNFUNCS_RET_DOUBLE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Wrong return format given, pick one of SUNFUNCS_RET_TIMESTAMP, SUNFUNCS_RET_STRING or SUNFUNCS_RET_DOUBLE"); RETURN_FALSE; } altitude = 90 - zenith; /* Initialize time struct */ t = timelib_time_ctor(); tzi = get_timezone_info(TSRMLS_C); t->tz_info = tzi; t->zone_type = TIMELIB_ZONETYPE_ID; if (ZEND_NUM_ARGS() <= 5) { gmt_offset = timelib_get_current_offset(t) / 3600; } timelib_unixtime2local(t, time); rs = timelib_astro_rise_set_altitude(t, longitude, latitude, altitude, 1, &h_rise, &h_set, &rise, &set, &transit); timelib_time_dtor(t); if (rs != 0) { RETURN_FALSE; } if (retformat == SUNFUNCS_RET_TIMESTAMP) { RETURN_LONG(calc_sunset ? set : rise); } N = (calc_sunset ? h_set : h_rise) + gmt_offset; if (N > 24 || N < 0) { N -= floor(N / 24) * 24; } switch (retformat) { case SUNFUNCS_RET_STRING: spprintf(&retstr, 0, "%02d:%02d", (int) N, (int) (60 * (N - (int) N))); RETURN_STRINGL(retstr, 5, 0); break; case SUNFUNCS_RET_DOUBLE: RETURN_DOUBLE(N); break; } } /* }}} */ /* {{{ proto mixed date_sunrise(mixed time [, int format [, float latitude [, float longitude [, float zenith [, float gmt_offset]]]]]) Returns time of sunrise for a given day and location */ PHP_FUNCTION(date_sunrise) { php_do_date_sunrise_sunset(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto mixed date_sunset(mixed time [, int format [, float latitude [, float longitude [, float zenith [, float gmt_offset]]]]]) Returns time of sunset for a given day and location */ PHP_FUNCTION(date_sunset) { php_do_date_sunrise_sunset(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto array date_sun_info(long time, float latitude, float longitude) Returns an array with information about sun set/rise and twilight begin/end */ PHP_FUNCTION(date_sun_info) { long time; double latitude, longitude; timelib_time *t, *t2; timelib_tzinfo *tzi; int rs; timelib_sll rise, set, transit; int dummy; double ddummy; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ldd", &time, &latitude, &longitude) == FAILURE) { RETURN_FALSE; } /* Initialize time struct */ t = timelib_time_ctor(); tzi = get_timezone_info(TSRMLS_C); t->tz_info = tzi; t->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(t, time); /* Setup */ t2 = timelib_time_ctor(); array_init(return_value); /* Get sun up/down and transit */ rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -35.0/60, 1, &ddummy, &ddummy, &rise, &set, &transit); switch (rs) { case -1: /* always below */ add_assoc_bool(return_value, "sunrise", 0); add_assoc_bool(return_value, "sunset", 0); break; case 1: /* always above */ add_assoc_bool(return_value, "sunrise", 1); add_assoc_bool(return_value, "sunset", 1); break; default: t2->sse = rise; add_assoc_long(return_value, "sunrise", timelib_date_to_int(t2, &dummy)); t2->sse = set; add_assoc_long(return_value, "sunset", timelib_date_to_int(t2, &dummy)); } t2->sse = transit; add_assoc_long(return_value, "transit", timelib_date_to_int(t2, &dummy)); /* Get civil twilight */ rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -6.0, 0, &ddummy, &ddummy, &rise, &set, &transit); switch (rs) { case -1: /* always below */ add_assoc_bool(return_value, "civil_twilight_begin", 0); add_assoc_bool(return_value, "civil_twilight_end", 0); break; case 1: /* always above */ add_assoc_bool(return_value, "civil_twilight_begin", 1); add_assoc_bool(return_value, "civil_twilight_end", 1); break; default: t2->sse = rise; add_assoc_long(return_value, "civil_twilight_begin", timelib_date_to_int(t2, &dummy)); t2->sse = set; add_assoc_long(return_value, "civil_twilight_end", timelib_date_to_int(t2, &dummy)); } /* Get nautical twilight */ rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -12.0, 0, &ddummy, &ddummy, &rise, &set, &transit); switch (rs) { case -1: /* always below */ add_assoc_bool(return_value, "nautical_twilight_begin", 0); add_assoc_bool(return_value, "nautical_twilight_end", 0); break; case 1: /* always above */ add_assoc_bool(return_value, "nautical_twilight_begin", 1); add_assoc_bool(return_value, "nautical_twilight_end", 1); break; default: t2->sse = rise; add_assoc_long(return_value, "nautical_twilight_begin", timelib_date_to_int(t2, &dummy)); t2->sse = set; add_assoc_long(return_value, "nautical_twilight_end", timelib_date_to_int(t2, &dummy)); } /* Get astronomical twilight */ rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -18.0, 0, &ddummy, &ddummy, &rise, &set, &transit); switch (rs) { case -1: /* always below */ add_assoc_bool(return_value, "astronomical_twilight_begin", 0); add_assoc_bool(return_value, "astronomical_twilight_end", 0); break; case 1: /* always above */ add_assoc_bool(return_value, "astronomical_twilight_begin", 1); add_assoc_bool(return_value, "astronomical_twilight_end", 1); break; default: t2->sse = rise; add_assoc_long(return_value, "astronomical_twilight_begin", timelib_date_to_int(t2, &dummy)); t2->sse = set; add_assoc_long(return_value, "astronomical_twilight_end", timelib_date_to_int(t2, &dummy)); } timelib_time_dtor(t); timelib_time_dtor(t2); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: fdm=marker * vim: noet sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Derick Rethans <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "php.h" #include "php_streams.h" #include "php_main.h" #include "php_globals.h" #include "php_ini.h" #include "ext/standard/info.h" #include "ext/standard/php_versioning.h" #include "ext/standard/php_math.h" #include "php_date.h" #include "zend_interfaces.h" #include "lib/timelib.h" #include <time.h> #ifdef PHP_WIN32 static __inline __int64 php_date_llabs( __int64 i ) { return i >= 0? i: -i; } #elif defined(__GNUC__) && __GNUC__ < 3 static __inline __int64_t php_date_llabs( __int64_t i ) { return i >= 0 ? i : -i; } #else static inline long long php_date_llabs( long long i ) { return i >= 0 ? i : -i; } #endif /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_date, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_gmdate, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_idate, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strtotime, 0, 0, 1) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, now) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mktime, 0, 0, 0) ZEND_ARG_INFO(0, hour) ZEND_ARG_INFO(0, min) ZEND_ARG_INFO(0, sec) ZEND_ARG_INFO(0, mon) ZEND_ARG_INFO(0, day) ZEND_ARG_INFO(0, year) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_gmmktime, 0, 0, 0) ZEND_ARG_INFO(0, hour) ZEND_ARG_INFO(0, min) ZEND_ARG_INFO(0, sec) ZEND_ARG_INFO(0, mon) ZEND_ARG_INFO(0, day) ZEND_ARG_INFO(0, year) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_checkdate, 0) ZEND_ARG_INFO(0, month) ZEND_ARG_INFO(0, day) ZEND_ARG_INFO(0, year) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strftime, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_gmstrftime, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_time, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_localtime, 0, 0, 0) ZEND_ARG_INFO(0, timestamp) ZEND_ARG_INFO(0, associative_array) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_getdate, 0, 0, 0) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_default_timezone_set, 0) ZEND_ARG_INFO(0, timezone_identifier) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_default_timezone_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_sunrise, 0, 0, 1) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, latitude) ZEND_ARG_INFO(0, longitude) ZEND_ARG_INFO(0, zenith) ZEND_ARG_INFO(0, gmt_offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_sunset, 0, 0, 1) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, latitude) ZEND_ARG_INFO(0, longitude) ZEND_ARG_INFO(0, zenith) ZEND_ARG_INFO(0, gmt_offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_sun_info, 0) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, latitude) ZEND_ARG_INFO(0, longitude) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_create, 0, 0, 0) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_create_from_format, 0, 0, 2) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_parse, 0, 0, 1) ZEND_ARG_INFO(0, date) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_parse_from_format, 0, 0, 2) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, date) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_get_last_errors, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_format, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_format, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_modify, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, modify) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_modify, 0, 0, 1) ZEND_ARG_INFO(0, modify) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_add, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, interval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_add, 0, 0, 1) ZEND_ARG_INFO(0, interval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_sub, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, interval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_sub, 0, 0, 1) ZEND_ARG_INFO(0, interval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_timezone_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_method_timezone_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_timezone_set, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, timezone) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_timezone_set, 0, 0, 1) ZEND_ARG_INFO(0, timezone) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_offset_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_method_offset_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_diff, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, object2) ZEND_ARG_INFO(0, absolute) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_diff, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, absolute) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_time_set, 0, 0, 3) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, hour) ZEND_ARG_INFO(0, minute) ZEND_ARG_INFO(0, second) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_time_set, 0, 0, 2) ZEND_ARG_INFO(0, hour) ZEND_ARG_INFO(0, minute) ZEND_ARG_INFO(0, second) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_date_set, 0, 0, 4) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, year) ZEND_ARG_INFO(0, month) ZEND_ARG_INFO(0, day) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_date_set, 0, 0, 3) ZEND_ARG_INFO(0, year) ZEND_ARG_INFO(0, month) ZEND_ARG_INFO(0, day) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_isodate_set, 0, 0, 3) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, year) ZEND_ARG_INFO(0, week) ZEND_ARG_INFO(0, day) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_isodate_set, 0, 0, 2) ZEND_ARG_INFO(0, year) ZEND_ARG_INFO(0, week) ZEND_ARG_INFO(0, day) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_timestamp_set, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, unixtimestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_timestamp_set, 0, 0, 1) ZEND_ARG_INFO(0, unixtimestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_timestamp_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_method_timestamp_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_open, 0, 0, 1) ZEND_ARG_INFO(0, timezone) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_name_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_method_name_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_name_from_abbr, 0, 0, 1) ZEND_ARG_INFO(0, abbr) ZEND_ARG_INFO(0, gmtoffset) ZEND_ARG_INFO(0, isdst) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_offset_get, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, datetime) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_method_offset_get, 0, 0, 1) ZEND_ARG_INFO(0, datetime) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_transitions_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, timestamp_begin) ZEND_ARG_INFO(0, timestamp_end) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_method_transitions_get, 0) ZEND_ARG_INFO(0, timestamp_begin) ZEND_ARG_INFO(0, timestamp_end) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_location_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_method_location_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_identifiers_list, 0, 0, 0) ZEND_ARG_INFO(0, what) ZEND_ARG_INFO(0, country) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_abbreviations_list, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_version_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_interval_create_from_date_string, 0, 0, 1) ZEND_ARG_INFO(0, time) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_interval_format, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_method_interval_format, 0) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_period_construct, 0, 0, 3) ZEND_ARG_INFO(0, start) ZEND_ARG_INFO(0, interval) ZEND_ARG_INFO(0, end) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_interval_construct, 0, 0, 0) ZEND_ARG_INFO(0, interval_spec) ZEND_END_ARG_INFO() /* }}} */ /* {{{ Function table */ const zend_function_entry date_functions[] = { PHP_FE(strtotime, arginfo_strtotime) PHP_FE(date, arginfo_date) PHP_FE(idate, arginfo_idate) PHP_FE(gmdate, arginfo_gmdate) PHP_FE(mktime, arginfo_mktime) PHP_FE(gmmktime, arginfo_gmmktime) PHP_FE(checkdate, arginfo_checkdate) #ifdef HAVE_STRFTIME PHP_FE(strftime, arginfo_strftime) PHP_FE(gmstrftime, arginfo_gmstrftime) #endif PHP_FE(time, arginfo_time) PHP_FE(localtime, arginfo_localtime) PHP_FE(getdate, arginfo_getdate) /* Advanced Interface */ PHP_FE(date_create, arginfo_date_create) PHP_FE(date_create_from_format, arginfo_date_create_from_format) PHP_FE(date_parse, arginfo_date_parse) PHP_FE(date_parse_from_format, arginfo_date_parse_from_format) PHP_FE(date_get_last_errors, arginfo_date_get_last_errors) PHP_FE(date_format, arginfo_date_format) PHP_FE(date_modify, arginfo_date_modify) PHP_FE(date_add, arginfo_date_add) PHP_FE(date_sub, arginfo_date_sub) PHP_FE(date_timezone_get, arginfo_date_timezone_get) PHP_FE(date_timezone_set, arginfo_date_timezone_set) PHP_FE(date_offset_get, arginfo_date_offset_get) PHP_FE(date_diff, arginfo_date_diff) PHP_FE(date_time_set, arginfo_date_time_set) PHP_FE(date_date_set, arginfo_date_date_set) PHP_FE(date_isodate_set, arginfo_date_isodate_set) PHP_FE(date_timestamp_set, arginfo_date_timestamp_set) PHP_FE(date_timestamp_get, arginfo_date_timestamp_get) PHP_FE(timezone_open, arginfo_timezone_open) PHP_FE(timezone_name_get, arginfo_timezone_name_get) PHP_FE(timezone_name_from_abbr, arginfo_timezone_name_from_abbr) PHP_FE(timezone_offset_get, arginfo_timezone_offset_get) PHP_FE(timezone_transitions_get, arginfo_timezone_transitions_get) PHP_FE(timezone_location_get, arginfo_timezone_location_get) PHP_FE(timezone_identifiers_list, arginfo_timezone_identifiers_list) PHP_FE(timezone_abbreviations_list, arginfo_timezone_abbreviations_list) PHP_FE(timezone_version_get, arginfo_timezone_version_get) PHP_FE(date_interval_create_from_date_string, arginfo_date_interval_create_from_date_string) PHP_FE(date_interval_format, arginfo_date_interval_format) /* Options and Configuration */ PHP_FE(date_default_timezone_set, arginfo_date_default_timezone_set) PHP_FE(date_default_timezone_get, arginfo_date_default_timezone_get) /* Astronomical functions */ PHP_FE(date_sunrise, arginfo_date_sunrise) PHP_FE(date_sunset, arginfo_date_sunset) PHP_FE(date_sun_info, arginfo_date_sun_info) {NULL, NULL, NULL} }; const zend_function_entry date_funcs_date[] = { PHP_ME(DateTime, __construct, arginfo_date_create, ZEND_ACC_CTOR|ZEND_ACC_PUBLIC) PHP_ME(DateTime, __wakeup, NULL, ZEND_ACC_PUBLIC) PHP_ME(DateTime, __set_state, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_ME_MAPPING(createFromFormat, date_create_from_format, arginfo_date_create_from_format, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_ME_MAPPING(getLastErrors, date_get_last_errors, arginfo_date_get_last_errors, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_ME_MAPPING(format, date_format, arginfo_date_method_format, 0) PHP_ME_MAPPING(modify, date_modify, arginfo_date_method_modify, 0) PHP_ME_MAPPING(add, date_add, arginfo_date_method_add, 0) PHP_ME_MAPPING(sub, date_sub, arginfo_date_method_sub, 0) PHP_ME_MAPPING(getTimezone, date_timezone_get, arginfo_date_method_timezone_get, 0) PHP_ME_MAPPING(setTimezone, date_timezone_set, arginfo_date_method_timezone_set, 0) PHP_ME_MAPPING(getOffset, date_offset_get, arginfo_date_method_offset_get, 0) PHP_ME_MAPPING(setTime, date_time_set, arginfo_date_method_time_set, 0) PHP_ME_MAPPING(setDate, date_date_set, arginfo_date_method_date_set, 0) PHP_ME_MAPPING(setISODate, date_isodate_set, arginfo_date_method_isodate_set, 0) PHP_ME_MAPPING(setTimestamp, date_timestamp_set, arginfo_date_method_timestamp_set, 0) PHP_ME_MAPPING(getTimestamp, date_timestamp_get, arginfo_date_method_timestamp_get, 0) PHP_ME_MAPPING(diff, date_diff, arginfo_date_method_diff, 0) {NULL, NULL, NULL} }; const zend_function_entry date_funcs_timezone[] = { PHP_ME(DateTimeZone, __construct, arginfo_timezone_open, ZEND_ACC_CTOR|ZEND_ACC_PUBLIC) PHP_ME_MAPPING(getName, timezone_name_get, arginfo_timezone_method_name_get, 0) PHP_ME_MAPPING(getOffset, timezone_offset_get, arginfo_timezone_method_offset_get, 0) PHP_ME_MAPPING(getTransitions, timezone_transitions_get, arginfo_timezone_method_transitions_get, 0) PHP_ME_MAPPING(getLocation, timezone_location_get, arginfo_timezone_method_location_get, 0) PHP_ME_MAPPING(listAbbreviations, timezone_abbreviations_list, arginfo_timezone_abbreviations_list, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_ME_MAPPING(listIdentifiers, timezone_identifiers_list, arginfo_timezone_identifiers_list, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) {NULL, NULL, NULL} }; const zend_function_entry date_funcs_interval[] = { PHP_ME(DateInterval, __construct, arginfo_date_interval_construct, ZEND_ACC_CTOR|ZEND_ACC_PUBLIC) PHP_ME_MAPPING(format, date_interval_format, arginfo_date_method_interval_format, 0) PHP_ME_MAPPING(createFromDateString, date_interval_create_from_date_string, arginfo_date_interval_create_from_date_string, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) {NULL, NULL, NULL} }; const zend_function_entry date_funcs_period[] = { PHP_ME(DatePeriod, __construct, arginfo_date_period_construct, ZEND_ACC_CTOR|ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; static char* guess_timezone(const timelib_tzdb *tzdb TSRMLS_DC); static void date_register_classes(TSRMLS_D); /* }}} */ ZEND_DECLARE_MODULE_GLOBALS(date) static PHP_GINIT_FUNCTION(date); /* True global */ timelib_tzdb *php_date_global_timezone_db; int php_date_global_timezone_db_enabled; #define DATE_DEFAULT_LATITUDE "31.7667" #define DATE_DEFAULT_LONGITUDE "35.2333" /* on 90'35; common sunset declaration (start of sun body appear) */ #define DATE_SUNSET_ZENITH "90.583333" /* on 90'35; common sunrise declaration (sun body disappeared) */ #define DATE_SUNRISE_ZENITH "90.583333" /* {{{ INI Settings */ PHP_INI_BEGIN() STD_PHP_INI_ENTRY("date.timezone", "", PHP_INI_ALL, OnUpdateString, default_timezone, zend_date_globals, date_globals) PHP_INI_ENTRY("date.default_latitude", DATE_DEFAULT_LATITUDE, PHP_INI_ALL, NULL) PHP_INI_ENTRY("date.default_longitude", DATE_DEFAULT_LONGITUDE, PHP_INI_ALL, NULL) PHP_INI_ENTRY("date.sunset_zenith", DATE_SUNSET_ZENITH, PHP_INI_ALL, NULL) PHP_INI_ENTRY("date.sunrise_zenith", DATE_SUNRISE_ZENITH, PHP_INI_ALL, NULL) PHP_INI_END() /* }}} */ zend_class_entry *date_ce_date, *date_ce_timezone, *date_ce_interval, *date_ce_period; PHPAPI zend_class_entry *php_date_get_date_ce(void) { return date_ce_date; } PHPAPI zend_class_entry *php_date_get_timezone_ce(void) { return date_ce_timezone; } static zend_object_handlers date_object_handlers_date; static zend_object_handlers date_object_handlers_timezone; static zend_object_handlers date_object_handlers_interval; static zend_object_handlers date_object_handlers_period; #define DATE_SET_CONTEXT \ zval *object; \ object = getThis(); \ #define DATE_FETCH_OBJECT \ php_date_obj *obj; \ DATE_SET_CONTEXT; \ if (object) { \ if (zend_parse_parameters_none() == FAILURE) { \ return; \ } \ } else { \ if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, NULL, "O", &object, date_ce_date) == FAILURE) { \ RETURN_FALSE; \ } \ } \ obj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); \ #define DATE_CHECK_INITIALIZED(member, class_name) \ if (!(member)) { \ php_error_docref(NULL TSRMLS_CC, E_WARNING, "The " #class_name " object has not been correctly initialized by its constructor"); \ RETURN_FALSE; \ } static void date_object_free_storage_date(void *object TSRMLS_DC); static void date_object_free_storage_timezone(void *object TSRMLS_DC); static void date_object_free_storage_interval(void *object TSRMLS_DC); static void date_object_free_storage_period(void *object TSRMLS_DC); static zend_object_value date_object_new_date(zend_class_entry *class_type TSRMLS_DC); static zend_object_value date_object_new_timezone(zend_class_entry *class_type TSRMLS_DC); static zend_object_value date_object_new_interval(zend_class_entry *class_type TSRMLS_DC); static zend_object_value date_object_new_period(zend_class_entry *class_type TSRMLS_DC); static zend_object_value date_object_clone_date(zval *this_ptr TSRMLS_DC); static zend_object_value date_object_clone_timezone(zval *this_ptr TSRMLS_DC); static zend_object_value date_object_clone_interval(zval *this_ptr TSRMLS_DC); static zend_object_value date_object_clone_period(zval *this_ptr TSRMLS_DC); static int date_object_compare_date(zval *d1, zval *d2 TSRMLS_DC); static HashTable *date_object_get_properties(zval *object TSRMLS_DC); static HashTable *date_object_get_properties_interval(zval *object TSRMLS_DC); zval *date_interval_read_property(zval *object, zval *member, int type, const zend_literal *key TSRMLS_DC); void date_interval_write_property(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC); /* {{{ Module struct */ zend_module_entry date_module_entry = { STANDARD_MODULE_HEADER_EX, NULL, NULL, "date", /* extension name */ date_functions, /* function list */ PHP_MINIT(date), /* process startup */ PHP_MSHUTDOWN(date), /* process shutdown */ PHP_RINIT(date), /* request startup */ PHP_RSHUTDOWN(date), /* request shutdown */ PHP_MINFO(date), /* extension info */ PHP_VERSION, /* extension version */ PHP_MODULE_GLOBALS(date), /* globals descriptor */ PHP_GINIT(date), /* globals ctor */ NULL, /* globals dtor */ NULL, /* post deactivate */ STANDARD_MODULE_PROPERTIES_EX }; /* }}} */ /* {{{ PHP_GINIT_FUNCTION */ static PHP_GINIT_FUNCTION(date) { date_globals->default_timezone = NULL; date_globals->timezone = NULL; date_globals->tzcache = NULL; } /* }}} */ static void _php_date_tzinfo_dtor(void *tzinfo) { timelib_tzinfo **tzi = (timelib_tzinfo **)tzinfo; timelib_tzinfo_dtor(*tzi); } /* {{{ PHP_RINIT_FUNCTION */ PHP_RINIT_FUNCTION(date) { if (DATEG(timezone)) { efree(DATEG(timezone)); } DATEG(timezone) = NULL; DATEG(tzcache) = NULL; DATEG(last_errors) = NULL; return SUCCESS; } /* }}} */ /* {{{ PHP_RSHUTDOWN_FUNCTION */ PHP_RSHUTDOWN_FUNCTION(date) { if (DATEG(timezone)) { efree(DATEG(timezone)); } DATEG(timezone) = NULL; if(DATEG(tzcache)) { zend_hash_destroy(DATEG(tzcache)); FREE_HASHTABLE(DATEG(tzcache)); DATEG(tzcache) = NULL; } if (DATEG(last_errors)) { timelib_error_container_dtor(DATEG(last_errors)); DATEG(last_errors) = NULL; } return SUCCESS; } /* }}} */ #define DATE_TIMEZONEDB php_date_global_timezone_db ? php_date_global_timezone_db : timelib_builtin_db() /* * RFC822, Section 5.1: http://www.ietf.org/rfc/rfc822.txt * date-time = [ day "," ] date time ; dd mm yy hh:mm:ss zzz * day = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" * date = 1*2DIGIT month 2DIGIT ; day month year e.g. 20 Jun 82 * month = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec" * time = hour zone ; ANSI and Military * hour = 2DIGIT ":" 2DIGIT [":" 2DIGIT] ; 00:00:00 - 23:59:59 * zone = "UT" / "GMT" / "EST" / "EDT" / "CST" / "CDT" / "MST" / "MDT" / "PST" / "PDT" / 1ALPHA / ( ("+" / "-") 4DIGIT ) */ #define DATE_FORMAT_RFC822 "D, d M y H:i:s O" /* * RFC850, Section 2.1.4: http://www.ietf.org/rfc/rfc850.txt * Format must be acceptable both to the ARPANET and to the getdate routine. * One format that is acceptable to both is Weekday, DD-Mon-YY HH:MM:SS TIMEZONE * TIMEZONE can be any timezone name (3 or more letters) */ #define DATE_FORMAT_RFC850 "l, d-M-y H:i:s T" /* * RFC1036, Section 2.1.2: http://www.ietf.org/rfc/rfc1036.txt * Its format must be acceptable both in RFC-822 and to the getdate(3) * Wdy, DD Mon YY HH:MM:SS TIMEZONE * There is no hope of having a complete list of timezones. Universal * Time (GMT), the North American timezones (PST, PDT, MST, MDT, CST, * CDT, EST, EDT) and the +/-hhmm offset specifed in RFC-822 should be supported. */ #define DATE_FORMAT_RFC1036 "D, d M y H:i:s O" /* * RFC1123, Section 5.2.14: http://www.ietf.org/rfc/rfc1123.txt * RFC-822 Date and Time Specification: RFC-822 Section 5 * The syntax for the date is hereby changed to: date = 1*2DIGIT month 2*4DIGIT */ #define DATE_FORMAT_RFC1123 "D, d M Y H:i:s O" /* * RFC2822, Section 3.3: http://www.ietf.org/rfc/rfc2822.txt * FWS = ([*WSP CRLF] 1*WSP) / ; Folding white space * CFWS = *([FWS] comment) (([FWS] comment) / FWS) * * date-time = [ day-of-week "," ] date FWS time [CFWS] * day-of-week = ([FWS] day-name) * day-name = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" * date = day month year * year = 4*DIGIT * month = (FWS month-name FWS) * month-name = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec" * day = ([FWS] 1*2DIGIT) * time = time-of-day FWS zone * time-of-day = hour ":" minute [ ":" second ] * hour = 2DIGIT * minute = 2DIGIT * second = 2DIGIT * zone = (( "+" / "-" ) 4DIGIT) */ #define DATE_FORMAT_RFC2822 "D, d M Y H:i:s O" /* * RFC3339, Section 5.6: http://www.ietf.org/rfc/rfc3339.txt * date-fullyear = 4DIGIT * date-month = 2DIGIT ; 01-12 * date-mday = 2DIGIT ; 01-28, 01-29, 01-30, 01-31 based on month/year * * time-hour = 2DIGIT ; 00-23 * time-minute = 2DIGIT ; 00-59 * time-second = 2DIGIT ; 00-58, 00-59, 00-60 based on leap second rules * * time-secfrac = "." 1*DIGIT * time-numoffset = ("+" / "-") time-hour ":" time-minute * time-offset = "Z" / time-numoffset * * partial-time = time-hour ":" time-minute ":" time-second [time-secfrac] * full-date = date-fullyear "-" date-month "-" date-mday * full-time = partial-time time-offset * * date-time = full-date "T" full-time */ #define DATE_FORMAT_RFC3339 "Y-m-d\\TH:i:sP" #define DATE_FORMAT_ISO8601 "Y-m-d\\TH:i:sO" #define DATE_TZ_ERRMSG \ "It is not safe to rely on the system's timezone settings. You are " \ "*required* to use the date.timezone setting or the " \ "date_default_timezone_set() function. In case you used any of those " \ "methods and you are still getting this warning, you most likely " \ "misspelled the timezone identifier. " #define SUNFUNCS_RET_TIMESTAMP 0 #define SUNFUNCS_RET_STRING 1 #define SUNFUNCS_RET_DOUBLE 2 /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(date) { REGISTER_INI_ENTRIES(); date_register_classes(TSRMLS_C); /* * RFC4287, Section 3.3: http://www.ietf.org/rfc/rfc4287.txt * A Date construct is an element whose content MUST conform to the * "date-time" production in [RFC3339]. In addition, an uppercase "T" * character MUST be used to separate date and time, and an uppercase * "Z" character MUST be present in the absence of a numeric time zone offset. */ REGISTER_STRING_CONSTANT("DATE_ATOM", DATE_FORMAT_RFC3339, CONST_CS | CONST_PERSISTENT); /* * Preliminary specification: http://wp.netscape.com/newsref/std/cookie_spec.html * "This is based on RFC 822, RFC 850, RFC 1036, and RFC 1123, * with the variations that the only legal time zone is GMT * and the separators between the elements of the date must be dashes." */ REGISTER_STRING_CONSTANT("DATE_COOKIE", DATE_FORMAT_RFC850, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_ISO8601", DATE_FORMAT_ISO8601, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC822", DATE_FORMAT_RFC822, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC850", DATE_FORMAT_RFC850, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC1036", DATE_FORMAT_RFC1036, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC1123", DATE_FORMAT_RFC1123, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC2822", DATE_FORMAT_RFC2822, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC3339", DATE_FORMAT_RFC3339, CONST_CS | CONST_PERSISTENT); /* * RSS 2.0 Specification: http://blogs.law.harvard.edu/tech/rss * "All date-times in RSS conform to the Date and Time Specification of RFC 822, * with the exception that the year may be expressed with two characters or four characters (four preferred)" */ REGISTER_STRING_CONSTANT("DATE_RSS", DATE_FORMAT_RFC1123, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_W3C", DATE_FORMAT_RFC3339, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SUNFUNCS_RET_TIMESTAMP", SUNFUNCS_RET_TIMESTAMP, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SUNFUNCS_RET_STRING", SUNFUNCS_RET_STRING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SUNFUNCS_RET_DOUBLE", SUNFUNCS_RET_DOUBLE, CONST_CS | CONST_PERSISTENT); php_date_global_timezone_db = NULL; php_date_global_timezone_db_enabled = 0; DATEG(last_errors) = NULL; return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ PHP_MSHUTDOWN_FUNCTION(date) { UNREGISTER_INI_ENTRIES(); if (DATEG(last_errors)) { timelib_error_container_dtor(DATEG(last_errors)); } return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(date) { const timelib_tzdb *tzdb = DATE_TIMEZONEDB; php_info_print_table_start(); php_info_print_table_row(2, "date/time support", "enabled"); php_info_print_table_row(2, "\"Olson\" Timezone Database Version", tzdb->version); php_info_print_table_row(2, "Timezone Database", php_date_global_timezone_db_enabled ? "external" : "internal"); php_info_print_table_row(2, "Default timezone", guess_timezone(tzdb TSRMLS_CC)); php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ /* {{{ Timezone Cache functions */ static timelib_tzinfo *php_date_parse_tzfile(char *formal_tzname, const timelib_tzdb *tzdb TSRMLS_DC) { timelib_tzinfo *tzi, **ptzi; if(!DATEG(tzcache)) { ALLOC_HASHTABLE(DATEG(tzcache)); zend_hash_init(DATEG(tzcache), 4, NULL, _php_date_tzinfo_dtor, 0); } if (zend_hash_find(DATEG(tzcache), formal_tzname, strlen(formal_tzname) + 1, (void **) &ptzi) == SUCCESS) { return *ptzi; } tzi = timelib_parse_tzfile(formal_tzname, tzdb); if (tzi) { zend_hash_add(DATEG(tzcache), formal_tzname, strlen(formal_tzname) + 1, (void *) &tzi, sizeof(timelib_tzinfo*), NULL); } return tzi; } /* }}} */ /* {{{ Helper functions */ static char* guess_timezone(const timelib_tzdb *tzdb TSRMLS_DC) { char *env; /* Checking configure timezone */ if (DATEG(timezone) && (strlen(DATEG(timezone)) > 0)) { return DATEG(timezone); } /* Check environment variable */ env = getenv("TZ"); if (env && *env && timelib_timezone_id_is_valid(env, tzdb)) { return env; } /* Check config setting for default timezone */ if (!DATEG(default_timezone)) { /* Special case: ext/date wasn't initialized yet */ zval ztz; if (SUCCESS == zend_get_configuration_directive("date.timezone", sizeof("date.timezone"), &ztz) && Z_TYPE(ztz) == IS_STRING && Z_STRLEN(ztz) > 0 && timelib_timezone_id_is_valid(Z_STRVAL(ztz), tzdb)) { return Z_STRVAL(ztz); } } else if (*DATEG(default_timezone) && timelib_timezone_id_is_valid(DATEG(default_timezone), tzdb)) { return DATEG(default_timezone); } #if HAVE_TM_ZONE /* Try to guess timezone from system information */ { struct tm *ta, tmbuf; time_t the_time; char *tzid = NULL; the_time = time(NULL); ta = php_localtime_r(&the_time, &tmbuf); if (ta) { tzid = timelib_timezone_id_from_abbr(ta->tm_zone, ta->tm_gmtoff, ta->tm_isdst); } if (! tzid) { tzid = "UTC"; } php_error_docref(NULL TSRMLS_CC, E_WARNING, DATE_TZ_ERRMSG "We selected '%s' for '%s/%.1f/%s' instead", tzid, ta ? ta->tm_zone : "Unknown", ta ? (float) (ta->tm_gmtoff / 3600) : 0, ta ? (ta->tm_isdst ? "DST" : "no DST") : "Unknown"); return tzid; } #endif #ifdef PHP_WIN32 { char *tzid; TIME_ZONE_INFORMATION tzi; switch (GetTimeZoneInformation(&tzi)) { /* DST in effect */ case TIME_ZONE_ID_DAYLIGHT: /* If user has disabled DST in the control panel, Windows returns 0 here */ if (tzi.DaylightBias == 0) { goto php_win_std_time; } tzid = timelib_timezone_id_from_abbr("", (tzi.Bias + tzi.DaylightBias) * -60, 1); if (! tzid) { tzid = "UTC"; } php_error_docref(NULL TSRMLS_CC, E_WARNING, DATE_TZ_ERRMSG "We selected '%s' for '%.1f/DST' instead", tzid, ((tzi.Bias + tzi.DaylightBias) / -60.0)); break; /* no DST or not in effect */ case TIME_ZONE_ID_UNKNOWN: case TIME_ZONE_ID_STANDARD: default: php_win_std_time: tzid = timelib_timezone_id_from_abbr("", (tzi.Bias + tzi.StandardBias) * -60, 0); if (! tzid) { tzid = "UTC"; } php_error_docref(NULL TSRMLS_CC, E_WARNING, DATE_TZ_ERRMSG "We selected '%s' for '%.1f/no DST' instead", tzid, ((tzi.Bias + tzi.StandardBias) / -60.0)); break; } return tzid; } #elif defined(NETWARE) /* Try to guess timezone from system information */ { char *tzid = timelib_timezone_id_from_abbr("", ((_timezone * -1) + (daylightOffset * daylightOnOff)), daylightOnOff); if (tzid) { return tzid; } } #endif /* Fallback to UTC */ php_error_docref(NULL TSRMLS_CC, E_WARNING, DATE_TZ_ERRMSG "We had to select 'UTC' because your platform doesn't provide functionality for the guessing algorithm"); return "UTC"; } PHPAPI timelib_tzinfo *get_timezone_info(TSRMLS_D) { char *tz; timelib_tzinfo *tzi; tz = guess_timezone(DATE_TIMEZONEDB TSRMLS_CC); tzi = php_date_parse_tzfile(tz, DATE_TIMEZONEDB TSRMLS_CC); if (! tzi) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Timezone database is corrupt - this should *never* happen!"); } return tzi; } /* }}} */ /* {{{ date() and gmdate() data */ #include "ext/standard/php_smart_str.h" static char *mon_full_names[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; static char *mon_short_names[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; static char *day_full_names[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; static char *day_short_names[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; static char *english_suffix(timelib_sll number) { if (number >= 10 && number <= 19) { return "th"; } else { switch (number % 10) { case 1: return "st"; case 2: return "nd"; case 3: return "rd"; } } return "th"; } /* }}} */ /* {{{ day of week helpers */ char *php_date_full_day_name(timelib_sll y, timelib_sll m, timelib_sll d) { timelib_sll day_of_week = timelib_day_of_week(y, m, d); if (day_of_week < 0) { return "Unknown"; } return day_full_names[day_of_week]; } char *php_date_short_day_name(timelib_sll y, timelib_sll m, timelib_sll d) { timelib_sll day_of_week = timelib_day_of_week(y, m, d); if (day_of_week < 0) { return "Unknown"; } return day_short_names[day_of_week]; } /* }}} */ /* {{{ date_format - (gm)date helper */ static char *date_format(char *format, int format_len, timelib_time *t, int localtime) { smart_str string = {0}; int i, length; char buffer[97]; timelib_time_offset *offset = NULL; timelib_sll isoweek, isoyear; int rfc_colon; if (!format_len) { return estrdup(""); } if (localtime) { if (t->zone_type == TIMELIB_ZONETYPE_ABBR) { offset = timelib_time_offset_ctor(); offset->offset = (t->z - (t->dst * 60)) * -60; offset->leap_secs = 0; offset->is_dst = t->dst; offset->abbr = strdup(t->tz_abbr); } else if (t->zone_type == TIMELIB_ZONETYPE_OFFSET) { offset = timelib_time_offset_ctor(); offset->offset = (t->z) * -60; offset->leap_secs = 0; offset->is_dst = 0; offset->abbr = malloc(9); /* GMT�xxxx\0 */ snprintf(offset->abbr, 9, "GMT%c%02d%02d", localtime ? ((offset->offset < 0) ? '-' : '+') : '+', localtime ? abs(offset->offset / 3600) : 0, localtime ? abs((offset->offset % 3600) / 60) : 0 ); } else { offset = timelib_get_time_zone_info(t->sse, t->tz_info); } } timelib_isoweek_from_date(t->y, t->m, t->d, &isoweek, &isoyear); for (i = 0; i < format_len; i++) { rfc_colon = 0; switch (format[i]) { /* day */ case 'd': length = slprintf(buffer, 32, "%02d", (int) t->d); break; case 'D': length = slprintf(buffer, 32, "%s", php_date_short_day_name(t->y, t->m, t->d)); break; case 'j': length = slprintf(buffer, 32, "%d", (int) t->d); break; case 'l': length = slprintf(buffer, 32, "%s", php_date_full_day_name(t->y, t->m, t->d)); break; case 'S': length = slprintf(buffer, 32, "%s", english_suffix(t->d)); break; case 'w': length = slprintf(buffer, 32, "%d", (int) timelib_day_of_week(t->y, t->m, t->d)); break; case 'N': length = slprintf(buffer, 32, "%d", (int) timelib_iso_day_of_week(t->y, t->m, t->d)); break; case 'z': length = slprintf(buffer, 32, "%d", (int) timelib_day_of_year(t->y, t->m, t->d)); break; /* week */ case 'W': length = slprintf(buffer, 32, "%02d", (int) isoweek); break; /* iso weeknr */ case 'o': length = slprintf(buffer, 32, "%d", (int) isoyear); break; /* iso year */ /* month */ case 'F': length = slprintf(buffer, 32, "%s", mon_full_names[t->m - 1]); break; case 'm': length = slprintf(buffer, 32, "%02d", (int) t->m); break; case 'M': length = slprintf(buffer, 32, "%s", mon_short_names[t->m - 1]); break; case 'n': length = slprintf(buffer, 32, "%d", (int) t->m); break; case 't': length = slprintf(buffer, 32, "%d", (int) timelib_days_in_month(t->y, t->m)); break; /* year */ case 'L': length = slprintf(buffer, 32, "%d", timelib_is_leap((int) t->y)); break; case 'y': length = slprintf(buffer, 32, "%02d", (int) t->y % 100); break; case 'Y': length = slprintf(buffer, 32, "%s%04lld", t->y < 0 ? "-" : "", php_date_llabs((timelib_sll) t->y)); break; /* time */ case 'a': length = slprintf(buffer, 32, "%s", t->h >= 12 ? "pm" : "am"); break; case 'A': length = slprintf(buffer, 32, "%s", t->h >= 12 ? "PM" : "AM"); break; case 'B': { int retval = (((((long)t->sse)-(((long)t->sse) - ((((long)t->sse) % 86400) + 3600))) * 10) / 864); while (retval < 0) { retval += 1000; } retval = retval % 1000; length = slprintf(buffer, 32, "%03d", retval); break; } case 'g': length = slprintf(buffer, 32, "%d", (t->h % 12) ? (int) t->h % 12 : 12); break; case 'G': length = slprintf(buffer, 32, "%d", (int) t->h); break; case 'h': length = slprintf(buffer, 32, "%02d", (t->h % 12) ? (int) t->h % 12 : 12); break; case 'H': length = slprintf(buffer, 32, "%02d", (int) t->h); break; case 'i': length = slprintf(buffer, 32, "%02d", (int) t->i); break; case 's': length = slprintf(buffer, 32, "%02d", (int) t->s); break; case 'u': length = slprintf(buffer, 32, "%06d", (int) floor(t->f * 1000000)); break; /* timezone */ case 'I': length = slprintf(buffer, 32, "%d", localtime ? offset->is_dst : 0); break; case 'P': rfc_colon = 1; /* break intentionally missing */ case 'O': length = slprintf(buffer, 32, "%c%02d%s%02d", localtime ? ((offset->offset < 0) ? '-' : '+') : '+', localtime ? abs(offset->offset / 3600) : 0, rfc_colon ? ":" : "", localtime ? abs((offset->offset % 3600) / 60) : 0 ); break; case 'T': length = slprintf(buffer, 32, "%s", localtime ? offset->abbr : "GMT"); break; case 'e': if (!localtime) { length = slprintf(buffer, 32, "%s", "UTC"); } else { switch (t->zone_type) { case TIMELIB_ZONETYPE_ID: length = slprintf(buffer, 32, "%s", t->tz_info->name); break; case TIMELIB_ZONETYPE_ABBR: length = slprintf(buffer, 32, "%s", offset->abbr); break; case TIMELIB_ZONETYPE_OFFSET: length = slprintf(buffer, 32, "%c%02d:%02d", ((offset->offset < 0) ? '-' : '+'), abs(offset->offset / 3600), abs((offset->offset % 3600) / 60) ); break; } } break; case 'Z': length = slprintf(buffer, 32, "%d", localtime ? offset->offset : 0); break; /* full date/time */ case 'c': length = slprintf(buffer, 96, "%04d-%02d-%02dT%02d:%02d:%02d%c%02d:%02d", (int) t->y, (int) t->m, (int) t->d, (int) t->h, (int) t->i, (int) t->s, localtime ? ((offset->offset < 0) ? '-' : '+') : '+', localtime ? abs(offset->offset / 3600) : 0, localtime ? abs((offset->offset % 3600) / 60) : 0 ); break; case 'r': length = slprintf(buffer, 96, "%3s, %02d %3s %04d %02d:%02d:%02d %c%02d%02d", php_date_short_day_name(t->y, t->m, t->d), (int) t->d, mon_short_names[t->m - 1], (int) t->y, (int) t->h, (int) t->i, (int) t->s, localtime ? ((offset->offset < 0) ? '-' : '+') : '+', localtime ? abs(offset->offset / 3600) : 0, localtime ? abs((offset->offset % 3600) / 60) : 0 ); break; case 'U': length = slprintf(buffer, 32, "%lld", (timelib_sll) t->sse); break; case '\\': if (i < format_len) i++; /* break intentionally missing */ default: buffer[0] = format[i]; buffer[1] = '\0'; length = 1; break; } smart_str_appendl(&string, buffer, length); } smart_str_0(&string); if (localtime) { timelib_time_offset_dtor(offset); } return string.c; } static void php_date(INTERNAL_FUNCTION_PARAMETERS, int localtime) { char *format; int format_len; long ts; char *string; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &format, &format_len, &ts) == FAILURE) { RETURN_FALSE; } if (ZEND_NUM_ARGS() == 1) { ts = time(NULL); } string = php_format_date(format, format_len, ts, localtime TSRMLS_CC); RETVAL_STRING(string, 0); } /* }}} */ PHPAPI char *php_format_date(char *format, int format_len, time_t ts, int localtime TSRMLS_DC) /* {{{ */ { timelib_time *t; timelib_tzinfo *tzi; char *string; t = timelib_time_ctor(); if (localtime) { tzi = get_timezone_info(TSRMLS_C); t->tz_info = tzi; t->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(t, ts); } else { tzi = NULL; timelib_unixtime2gmt(t, ts); } string = date_format(format, format_len, t, localtime); timelib_time_dtor(t); return string; } /* }}} */ /* {{{ php_idate */ PHPAPI int php_idate(char format, time_t ts, int localtime TSRMLS_DC) { timelib_time *t; timelib_tzinfo *tzi; int retval = -1; timelib_time_offset *offset = NULL; timelib_sll isoweek, isoyear; t = timelib_time_ctor(); if (!localtime) { tzi = get_timezone_info(TSRMLS_C); t->tz_info = tzi; t->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(t, ts); } else { tzi = NULL; timelib_unixtime2gmt(t, ts); } if (!localtime) { if (t->zone_type == TIMELIB_ZONETYPE_ABBR) { offset = timelib_time_offset_ctor(); offset->offset = (t->z - (t->dst * 60)) * -60; offset->leap_secs = 0; offset->is_dst = t->dst; offset->abbr = strdup(t->tz_abbr); } else if (t->zone_type == TIMELIB_ZONETYPE_OFFSET) { offset = timelib_time_offset_ctor(); offset->offset = (t->z - (t->dst * 60)) * -60; offset->leap_secs = 0; offset->is_dst = t->dst; offset->abbr = malloc(9); /* GMT�xxxx\0 */ snprintf(offset->abbr, 9, "GMT%c%02d%02d", !localtime ? ((offset->offset < 0) ? '-' : '+') : '+', !localtime ? abs(offset->offset / 3600) : 0, !localtime ? abs((offset->offset % 3600) / 60) : 0 ); } else { offset = timelib_get_time_zone_info(t->sse, t->tz_info); } } timelib_isoweek_from_date(t->y, t->m, t->d, &isoweek, &isoyear); switch (format) { /* day */ case 'd': case 'j': retval = (int) t->d; break; case 'w': retval = (int) timelib_day_of_week(t->y, t->m, t->d); break; case 'z': retval = (int) timelib_day_of_year(t->y, t->m, t->d); break; /* week */ case 'W': retval = (int) isoweek; break; /* iso weeknr */ /* month */ case 'm': case 'n': retval = (int) t->m; break; case 't': retval = (int) timelib_days_in_month(t->y, t->m); break; /* year */ case 'L': retval = (int) timelib_is_leap((int) t->y); break; case 'y': retval = (int) (t->y % 100); break; case 'Y': retval = (int) t->y; break; /* Swatch Beat a.k.a. Internet Time */ case 'B': retval = (((((long)t->sse)-(((long)t->sse) - ((((long)t->sse) % 86400) + 3600))) * 10) / 864); while (retval < 0) { retval += 1000; } retval = retval % 1000; break; /* time */ case 'g': case 'h': retval = (int) ((t->h % 12) ? (int) t->h % 12 : 12); break; case 'H': case 'G': retval = (int) t->h; break; case 'i': retval = (int) t->i; break; case 's': retval = (int) t->s; break; /* timezone */ case 'I': retval = (int) (!localtime ? offset->is_dst : 0); break; case 'Z': retval = (int) (!localtime ? offset->offset : 0); break; case 'U': retval = (int) t->sse; break; } if (!localtime) { timelib_time_offset_dtor(offset); } timelib_time_dtor(t); return retval; } /* }}} */ /* {{{ proto string date(string format [, long timestamp]) Format a local date/time */ PHP_FUNCTION(date) { php_date(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto string gmdate(string format [, long timestamp]) Format a GMT date/time */ PHP_FUNCTION(gmdate) { php_date(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto int idate(string format [, int timestamp]) Format a local time/date as integer */ PHP_FUNCTION(idate) { char *format; int format_len; long ts = 0; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &format, &format_len, &ts) == FAILURE) { RETURN_FALSE; } if (format_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "idate format is one char"); RETURN_FALSE; } if (ZEND_NUM_ARGS() == 1) { ts = time(NULL); } ret = php_idate(format[0], ts, 0 TSRMLS_CC); if (ret == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unrecognized date format token."); RETURN_FALSE; } RETURN_LONG(ret); } /* }}} */ /* {{{ php_date_set_tzdb - NOT THREADSAFE */ PHPAPI void php_date_set_tzdb(timelib_tzdb *tzdb) { const timelib_tzdb *builtin = timelib_builtin_db(); if (php_version_compare(tzdb->version, builtin->version) > 0) { php_date_global_timezone_db = tzdb; php_date_global_timezone_db_enabled = 1; } } /* }}} */ /* {{{ php_parse_date: Backwards compability function */ PHPAPI signed long php_parse_date(char *string, signed long *now) { timelib_time *parsed_time; timelib_error_container *error = NULL; int error2; signed long retval; parsed_time = timelib_strtotime(string, strlen(string), &error, DATE_TIMEZONEDB); if (error->error_count) { timelib_error_container_dtor(error); return -1; } timelib_error_container_dtor(error); timelib_update_ts(parsed_time, NULL); retval = timelib_date_to_int(parsed_time, &error2); timelib_time_dtor(parsed_time); if (error2) { return -1; } return retval; } /* }}} */ /* {{{ proto int strtotime(string time [, int now ]) Convert string representation of date and time to a timestamp */ PHP_FUNCTION(strtotime) { char *times, *initial_ts; int time_len, error1, error2; struct timelib_error_container *error; long preset_ts = 0, ts; timelib_time *t, *now; timelib_tzinfo *tzi; tzi = get_timezone_info(TSRMLS_C); if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "sl", &times, &time_len, &preset_ts) != FAILURE) { /* We have an initial timestamp */ now = timelib_time_ctor(); initial_ts = emalloc(25); snprintf(initial_ts, 24, "@%ld UTC", preset_ts); t = timelib_strtotime(initial_ts, strlen(initial_ts), NULL, DATE_TIMEZONEDB); /* we ignore the error here, as this should never fail */ timelib_update_ts(t, tzi); now->tz_info = tzi; now->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(now, t->sse); timelib_time_dtor(t); efree(initial_ts); } else if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &times, &time_len, &preset_ts) != FAILURE) { /* We have no initial timestamp */ now = timelib_time_ctor(); now->tz_info = tzi; now->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(now, (timelib_sll) time(NULL)); } else { RETURN_FALSE; } if (!time_len) { timelib_time_dtor(now); RETURN_FALSE; } t = timelib_strtotime(times, time_len, &error, DATE_TIMEZONEDB); error1 = error->error_count; timelib_error_container_dtor(error); timelib_fill_holes(t, now, TIMELIB_NO_CLONE); timelib_update_ts(t, tzi); ts = timelib_date_to_int(t, &error2); timelib_time_dtor(now); timelib_time_dtor(t); if (error1 || error2) { RETURN_FALSE; } else { RETURN_LONG(ts); } } /* }}} */ /* {{{ php_mktime - (gm)mktime helper */ PHPAPI void php_mktime(INTERNAL_FUNCTION_PARAMETERS, int gmt) { long hou = 0, min = 0, sec = 0, mon = 0, day = 0, yea = 0, dst = -1; timelib_time *now; timelib_tzinfo *tzi = NULL; long ts, adjust_seconds = 0; int error; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lllllll", &hou, &min, &sec, &mon, &day, &yea, &dst) == FAILURE) { RETURN_FALSE; } /* Initialize structure with current time */ now = timelib_time_ctor(); if (gmt) { timelib_unixtime2gmt(now, (timelib_sll) time(NULL)); } else { tzi = get_timezone_info(TSRMLS_C); now->tz_info = tzi; now->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(now, (timelib_sll) time(NULL)); } /* Fill in the new data */ switch (ZEND_NUM_ARGS()) { case 7: /* break intentionally missing */ case 6: if (yea >= 0 && yea < 70) { yea += 2000; } else if (yea >= 70 && yea <= 100) { yea += 1900; } now->y = yea; /* break intentionally missing again */ case 5: now->d = day; /* break missing intentionally here too */ case 4: now->m = mon; /* and here */ case 3: now->s = sec; /* yup, this break isn't here on purpose too */ case 2: now->i = min; /* last intentionally missing break */ case 1: now->h = hou; break; default: php_error_docref(NULL TSRMLS_CC, E_STRICT, "You should be using the time() function instead"); } /* Update the timestamp */ if (gmt) { timelib_update_ts(now, NULL); } else { timelib_update_ts(now, tzi); } /* Support for the deprecated is_dst parameter */ if (dst != -1) { php_error_docref(NULL TSRMLS_CC, E_DEPRECATED, "The is_dst parameter is deprecated"); if (gmt) { /* GMT never uses DST */ if (dst == 1) { adjust_seconds = -3600; } } else { /* Figure out is_dst for current TS */ timelib_time_offset *tmp_offset; tmp_offset = timelib_get_time_zone_info(now->sse, tzi); if (dst == 1 && tmp_offset->is_dst == 0) { adjust_seconds = -3600; } if (dst == 0 && tmp_offset->is_dst == 1) { adjust_seconds = +3600; } timelib_time_offset_dtor(tmp_offset); } } /* Clean up and return */ ts = timelib_date_to_int(now, &error); ts += adjust_seconds; timelib_time_dtor(now); if (error) { RETURN_FALSE; } else { RETURN_LONG(ts); } } /* }}} */ /* {{{ proto int mktime([int hour [, int min [, int sec [, int mon [, int day [, int year]]]]]]) Get UNIX timestamp for a date */ PHP_FUNCTION(mktime) { php_mktime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto int gmmktime([int hour [, int min [, int sec [, int mon [, int day [, int year]]]]]]) Get UNIX timestamp for a GMT date */ PHP_FUNCTION(gmmktime) { php_mktime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto bool checkdate(int month, int day, int year) Returns true(1) if it is a valid date in gregorian calendar */ PHP_FUNCTION(checkdate) { long m, d, y; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lll", &m, &d, &y) == FAILURE) { RETURN_FALSE; } if (y < 1 || y > 32767 || !timelib_valid_date(y, m, d)) { RETURN_FALSE; } RETURN_TRUE; /* True : This month, day, year arguments are valid */ } /* }}} */ #ifdef HAVE_STRFTIME /* {{{ php_strftime - (gm)strftime helper */ PHPAPI void php_strftime(INTERNAL_FUNCTION_PARAMETERS, int gmt) { char *format, *buf; int format_len; long timestamp = 0; struct tm ta; int max_reallocs = 5; size_t buf_len = 64, real_len; timelib_time *ts; timelib_tzinfo *tzi; timelib_time_offset *offset = NULL; timestamp = (long) time(NULL); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &format, &format_len, &timestamp) == FAILURE) { RETURN_FALSE; } if (format_len == 0) { RETURN_FALSE; } ts = timelib_time_ctor(); if (gmt) { tzi = NULL; timelib_unixtime2gmt(ts, (timelib_sll) timestamp); } else { tzi = get_timezone_info(TSRMLS_C); ts->tz_info = tzi; ts->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(ts, (timelib_sll) timestamp); } ta.tm_sec = ts->s; ta.tm_min = ts->i; ta.tm_hour = ts->h; ta.tm_mday = ts->d; ta.tm_mon = ts->m - 1; ta.tm_year = ts->y - 1900; ta.tm_wday = timelib_day_of_week(ts->y, ts->m, ts->d); ta.tm_yday = timelib_day_of_year(ts->y, ts->m, ts->d); if (gmt) { ta.tm_isdst = 0; #if HAVE_TM_GMTOFF ta.tm_gmtoff = 0; #endif #if HAVE_TM_ZONE ta.tm_zone = "GMT"; #endif } else { offset = timelib_get_time_zone_info(timestamp, tzi); ta.tm_isdst = offset->is_dst; #if HAVE_TM_GMTOFF ta.tm_gmtoff = offset->offset; #endif #if HAVE_TM_ZONE ta.tm_zone = offset->abbr; #endif } buf = (char *) emalloc(buf_len); while ((real_len=strftime(buf, buf_len, format, &ta))==buf_len || real_len==0) { buf_len *= 2; buf = (char *) erealloc(buf, buf_len); if (!--max_reallocs) { break; } } timelib_time_dtor(ts); if (!gmt) { timelib_time_offset_dtor(offset); } if (real_len && real_len != buf_len) { buf = (char *) erealloc(buf, real_len + 1); RETURN_STRINGL(buf, real_len, 0); } efree(buf); RETURN_FALSE; } /* }}} */ /* {{{ proto string strftime(string format [, int timestamp]) Format a local time/date according to locale settings */ PHP_FUNCTION(strftime) { php_strftime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto string gmstrftime(string format [, int timestamp]) Format a GMT/UCT time/date according to locale settings */ PHP_FUNCTION(gmstrftime) { php_strftime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ #endif /* {{{ proto int time(void) Return current UNIX timestamp */ PHP_FUNCTION(time) { RETURN_LONG((long)time(NULL)); } /* }}} */ /* {{{ proto array localtime([int timestamp [, bool associative_array]]) Returns the results of the C system call localtime as an associative array if the associative_array argument is set to 1 other wise it is a regular array */ PHP_FUNCTION(localtime) { long timestamp = (long)time(NULL); zend_bool associative = 0; timelib_tzinfo *tzi; timelib_time *ts; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lb", &timestamp, &associative) == FAILURE) { RETURN_FALSE; } tzi = get_timezone_info(TSRMLS_C); ts = timelib_time_ctor(); ts->tz_info = tzi; ts->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(ts, (timelib_sll) timestamp); array_init(return_value); if (associative) { add_assoc_long(return_value, "tm_sec", ts->s); add_assoc_long(return_value, "tm_min", ts->i); add_assoc_long(return_value, "tm_hour", ts->h); add_assoc_long(return_value, "tm_mday", ts->d); add_assoc_long(return_value, "tm_mon", ts->m - 1); add_assoc_long(return_value, "tm_year", ts->y - 1900); add_assoc_long(return_value, "tm_wday", timelib_day_of_week(ts->y, ts->m, ts->d)); add_assoc_long(return_value, "tm_yday", timelib_day_of_year(ts->y, ts->m, ts->d)); add_assoc_long(return_value, "tm_isdst", ts->dst); } else { add_next_index_long(return_value, ts->s); add_next_index_long(return_value, ts->i); add_next_index_long(return_value, ts->h); add_next_index_long(return_value, ts->d); add_next_index_long(return_value, ts->m - 1); add_next_index_long(return_value, ts->y- 1900); add_next_index_long(return_value, timelib_day_of_week(ts->y, ts->m, ts->d)); add_next_index_long(return_value, timelib_day_of_year(ts->y, ts->m, ts->d)); add_next_index_long(return_value, ts->dst); } timelib_time_dtor(ts); } /* }}} */ /* {{{ proto array getdate([int timestamp]) Get date/time information */ PHP_FUNCTION(getdate) { long timestamp = (long)time(NULL); timelib_tzinfo *tzi; timelib_time *ts; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &timestamp) == FAILURE) { RETURN_FALSE; } tzi = get_timezone_info(TSRMLS_C); ts = timelib_time_ctor(); ts->tz_info = tzi; ts->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(ts, (timelib_sll) timestamp); array_init(return_value); add_assoc_long(return_value, "seconds", ts->s); add_assoc_long(return_value, "minutes", ts->i); add_assoc_long(return_value, "hours", ts->h); add_assoc_long(return_value, "mday", ts->d); add_assoc_long(return_value, "wday", timelib_day_of_week(ts->y, ts->m, ts->d)); add_assoc_long(return_value, "mon", ts->m); add_assoc_long(return_value, "year", ts->y); add_assoc_long(return_value, "yday", timelib_day_of_year(ts->y, ts->m, ts->d)); add_assoc_string(return_value, "weekday", php_date_full_day_name(ts->y, ts->m, ts->d), 1); add_assoc_string(return_value, "month", mon_full_names[ts->m - 1], 1); add_index_long(return_value, 0, timestamp); timelib_time_dtor(ts); } /* }}} */ #define PHP_DATE_TIMEZONE_GROUP_AFRICA 0x0001 #define PHP_DATE_TIMEZONE_GROUP_AMERICA 0x0002 #define PHP_DATE_TIMEZONE_GROUP_ANTARCTICA 0x0004 #define PHP_DATE_TIMEZONE_GROUP_ARCTIC 0x0008 #define PHP_DATE_TIMEZONE_GROUP_ASIA 0x0010 #define PHP_DATE_TIMEZONE_GROUP_ATLANTIC 0x0020 #define PHP_DATE_TIMEZONE_GROUP_AUSTRALIA 0x0040 #define PHP_DATE_TIMEZONE_GROUP_EUROPE 0x0080 #define PHP_DATE_TIMEZONE_GROUP_INDIAN 0x0100 #define PHP_DATE_TIMEZONE_GROUP_PACIFIC 0x0200 #define PHP_DATE_TIMEZONE_GROUP_UTC 0x0400 #define PHP_DATE_TIMEZONE_GROUP_ALL 0x07FF #define PHP_DATE_TIMEZONE_GROUP_ALL_W_BC 0x0FFF #define PHP_DATE_TIMEZONE_PER_COUNTRY 0x1000 #define PHP_DATE_PERIOD_EXCLUDE_START_DATE 0x0001 /* define an overloaded iterator structure */ typedef struct { zend_object_iterator intern; zval *date_period_zval; zval *current; php_period_obj *object; int current_index; } date_period_it; /* {{{ date_period_it_invalidate_current */ static void date_period_it_invalidate_current(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; if (iterator->current) { zval_ptr_dtor(&iterator->current); iterator->current = NULL; } } /* }}} */ /* {{{ date_period_it_dtor */ static void date_period_it_dtor(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; date_period_it_invalidate_current(iter TSRMLS_CC); zval_ptr_dtor(&iterator->date_period_zval); efree(iterator); } /* }}} */ /* {{{ date_period_it_has_more */ static int date_period_it_has_more(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; php_period_obj *object = iterator->object; timelib_time *it_time = object->current; /* apply modification if it's not the first iteration */ if (!object->include_start_date || iterator->current_index > 0) { it_time->have_relative = 1; it_time->relative = *object->interval; it_time->sse_uptodate = 0; timelib_update_ts(it_time, NULL); timelib_update_from_sse(it_time); } if (object->end) { return object->current->sse < object->end->sse ? SUCCESS : FAILURE; } else { return (iterator->current_index < object->recurrences) ? SUCCESS : FAILURE; } } /* }}} */ /* {{{ date_period_it_current_data */ static void date_period_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; php_period_obj *object = iterator->object; timelib_time *it_time = object->current; php_date_obj *newdateobj; /* Create new object */ MAKE_STD_ZVAL(iterator->current); php_date_instantiate(date_ce_date, iterator->current TSRMLS_CC); newdateobj = (php_date_obj *) zend_object_store_get_object(iterator->current TSRMLS_CC); newdateobj->time = timelib_time_ctor(); *newdateobj->time = *it_time; if (it_time->tz_abbr) { newdateobj->time->tz_abbr = strdup(it_time->tz_abbr); } if (it_time->tz_info) { newdateobj->time->tz_info = it_time->tz_info; } *data = &iterator->current; } /* }}} */ /* {{{ date_period_it_current_key */ static int date_period_it_current_key(zend_object_iterator *iter, char **str_key, uint *str_key_len, ulong *int_key TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; *int_key = iterator->current_index; return HASH_KEY_IS_LONG; } /* }}} */ /* {{{ date_period_it_move_forward */ static void date_period_it_move_forward(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; iterator->current_index++; date_period_it_invalidate_current(iter TSRMLS_CC); } /* }}} */ /* {{{ date_period_it_rewind */ static void date_period_it_rewind(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; iterator->current_index = 0; if (iterator->object->current) { timelib_time_dtor(iterator->object->current); } iterator->object->current = timelib_time_clone(iterator->object->start); date_period_it_invalidate_current(iter TSRMLS_CC); } /* }}} */ /* iterator handler table */ zend_object_iterator_funcs date_period_it_funcs = { date_period_it_dtor, date_period_it_has_more, date_period_it_current_data, date_period_it_current_key, date_period_it_move_forward, date_period_it_rewind, date_period_it_invalidate_current }; zend_object_iterator *date_object_period_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) { date_period_it *iterator = emalloc(sizeof(date_period_it)); php_period_obj *dpobj = (php_period_obj *)zend_object_store_get_object(object TSRMLS_CC); if (by_ref) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } Z_ADDREF_P(object); iterator->intern.data = (void*) dpobj; iterator->intern.funcs = &date_period_it_funcs; iterator->date_period_zval = object; iterator->object = dpobj; iterator->current = NULL; return (zend_object_iterator*)iterator; } static void date_register_classes(TSRMLS_D) { zend_class_entry ce_date, ce_timezone, ce_interval, ce_period; INIT_CLASS_ENTRY(ce_date, "DateTime", date_funcs_date); ce_date.create_object = date_object_new_date; date_ce_date = zend_register_internal_class_ex(&ce_date, NULL, NULL TSRMLS_CC); memcpy(&date_object_handlers_date, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); date_object_handlers_date.clone_obj = date_object_clone_date; date_object_handlers_date.compare_objects = date_object_compare_date; date_object_handlers_date.get_properties = date_object_get_properties; #define REGISTER_DATE_CLASS_CONST_STRING(const_name, value) \ zend_declare_class_constant_stringl(date_ce_date, const_name, sizeof(const_name)-1, value, sizeof(value)-1 TSRMLS_CC); REGISTER_DATE_CLASS_CONST_STRING("ATOM", DATE_FORMAT_RFC3339); REGISTER_DATE_CLASS_CONST_STRING("COOKIE", DATE_FORMAT_RFC850); REGISTER_DATE_CLASS_CONST_STRING("ISO8601", DATE_FORMAT_ISO8601); REGISTER_DATE_CLASS_CONST_STRING("RFC822", DATE_FORMAT_RFC822); REGISTER_DATE_CLASS_CONST_STRING("RFC850", DATE_FORMAT_RFC850); REGISTER_DATE_CLASS_CONST_STRING("RFC1036", DATE_FORMAT_RFC1036); REGISTER_DATE_CLASS_CONST_STRING("RFC1123", DATE_FORMAT_RFC1123); REGISTER_DATE_CLASS_CONST_STRING("RFC2822", DATE_FORMAT_RFC2822); REGISTER_DATE_CLASS_CONST_STRING("RFC3339", DATE_FORMAT_RFC3339); REGISTER_DATE_CLASS_CONST_STRING("RSS", DATE_FORMAT_RFC1123); REGISTER_DATE_CLASS_CONST_STRING("W3C", DATE_FORMAT_RFC3339); INIT_CLASS_ENTRY(ce_timezone, "DateTimeZone", date_funcs_timezone); ce_timezone.create_object = date_object_new_timezone; date_ce_timezone = zend_register_internal_class_ex(&ce_timezone, NULL, NULL TSRMLS_CC); memcpy(&date_object_handlers_timezone, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); date_object_handlers_timezone.clone_obj = date_object_clone_timezone; #define REGISTER_TIMEZONE_CLASS_CONST_STRING(const_name, value) \ zend_declare_class_constant_long(date_ce_timezone, const_name, sizeof(const_name)-1, value TSRMLS_CC); REGISTER_TIMEZONE_CLASS_CONST_STRING("AFRICA", PHP_DATE_TIMEZONE_GROUP_AFRICA); REGISTER_TIMEZONE_CLASS_CONST_STRING("AMERICA", PHP_DATE_TIMEZONE_GROUP_AMERICA); REGISTER_TIMEZONE_CLASS_CONST_STRING("ANTARCTICA", PHP_DATE_TIMEZONE_GROUP_ANTARCTICA); REGISTER_TIMEZONE_CLASS_CONST_STRING("ARCTIC", PHP_DATE_TIMEZONE_GROUP_ARCTIC); REGISTER_TIMEZONE_CLASS_CONST_STRING("ASIA", PHP_DATE_TIMEZONE_GROUP_ASIA); REGISTER_TIMEZONE_CLASS_CONST_STRING("ATLANTIC", PHP_DATE_TIMEZONE_GROUP_ATLANTIC); REGISTER_TIMEZONE_CLASS_CONST_STRING("AUSTRALIA", PHP_DATE_TIMEZONE_GROUP_AUSTRALIA); REGISTER_TIMEZONE_CLASS_CONST_STRING("EUROPE", PHP_DATE_TIMEZONE_GROUP_EUROPE); REGISTER_TIMEZONE_CLASS_CONST_STRING("INDIAN", PHP_DATE_TIMEZONE_GROUP_INDIAN); REGISTER_TIMEZONE_CLASS_CONST_STRING("PACIFIC", PHP_DATE_TIMEZONE_GROUP_PACIFIC); REGISTER_TIMEZONE_CLASS_CONST_STRING("UTC", PHP_DATE_TIMEZONE_GROUP_UTC); REGISTER_TIMEZONE_CLASS_CONST_STRING("ALL", PHP_DATE_TIMEZONE_GROUP_ALL); REGISTER_TIMEZONE_CLASS_CONST_STRING("ALL_WITH_BC", PHP_DATE_TIMEZONE_GROUP_ALL_W_BC); REGISTER_TIMEZONE_CLASS_CONST_STRING("PER_COUNTRY", PHP_DATE_TIMEZONE_PER_COUNTRY); INIT_CLASS_ENTRY(ce_interval, "DateInterval", date_funcs_interval); ce_interval.create_object = date_object_new_interval; date_ce_interval = zend_register_internal_class_ex(&ce_interval, NULL, NULL TSRMLS_CC); memcpy(&date_object_handlers_interval, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); date_object_handlers_interval.clone_obj = date_object_clone_interval; date_object_handlers_interval.read_property = date_interval_read_property; date_object_handlers_interval.write_property = date_interval_write_property; date_object_handlers_interval.get_properties = date_object_get_properties_interval; date_object_handlers_interval.get_property_ptr_ptr = NULL; INIT_CLASS_ENTRY(ce_period, "DatePeriod", date_funcs_period); ce_period.create_object = date_object_new_period; date_ce_period = zend_register_internal_class_ex(&ce_period, NULL, NULL TSRMLS_CC); date_ce_period->get_iterator = date_object_period_get_iterator; date_ce_period->iterator_funcs.funcs = &date_period_it_funcs; zend_class_implements(date_ce_period TSRMLS_CC, 1, zend_ce_traversable); memcpy(&date_object_handlers_period, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); date_object_handlers_period.clone_obj = date_object_clone_period; #define REGISTER_PERIOD_CLASS_CONST_STRING(const_name, value) \ zend_declare_class_constant_long(date_ce_period, const_name, sizeof(const_name)-1, value TSRMLS_CC); REGISTER_PERIOD_CLASS_CONST_STRING("EXCLUDE_START_DATE", PHP_DATE_PERIOD_EXCLUDE_START_DATE); } static inline zend_object_value date_object_new_date_ex(zend_class_entry *class_type, php_date_obj **ptr TSRMLS_DC) { php_date_obj *intern; zend_object_value retval; intern = emalloc(sizeof(php_date_obj)); memset(intern, 0, sizeof(php_date_obj)); if (ptr) { *ptr = intern; } zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) date_object_free_storage_date, NULL TSRMLS_CC); retval.handlers = &date_object_handlers_date; return retval; } static zend_object_value date_object_new_date(zend_class_entry *class_type TSRMLS_DC) { return date_object_new_date_ex(class_type, NULL TSRMLS_CC); } static zend_object_value date_object_clone_date(zval *this_ptr TSRMLS_DC) { php_date_obj *new_obj = NULL; php_date_obj *old_obj = (php_date_obj *) zend_object_store_get_object(this_ptr TSRMLS_CC); zend_object_value new_ov = date_object_new_date_ex(old_obj->std.ce, &new_obj TSRMLS_CC); zend_objects_clone_members(&new_obj->std, new_ov, &old_obj->std, Z_OBJ_HANDLE_P(this_ptr) TSRMLS_CC); /* this should probably moved to a new `timelib_time *timelime_time_clone(timelib_time *)` */ new_obj->time = timelib_time_ctor(); *new_obj->time = *old_obj->time; if (old_obj->time->tz_abbr) { new_obj->time->tz_abbr = strdup(old_obj->time->tz_abbr); } if (old_obj->time->tz_info) { new_obj->time->tz_info = old_obj->time->tz_info; } return new_ov; } static int date_object_compare_date(zval *d1, zval *d2 TSRMLS_DC) { if (Z_TYPE_P(d1) == IS_OBJECT && Z_TYPE_P(d2) == IS_OBJECT && instanceof_function(Z_OBJCE_P(d1), date_ce_date TSRMLS_CC) && instanceof_function(Z_OBJCE_P(d2), date_ce_date TSRMLS_CC)) { php_date_obj *o1 = zend_object_store_get_object(d1 TSRMLS_CC); php_date_obj *o2 = zend_object_store_get_object(d2 TSRMLS_CC); if (!o1->time->sse_uptodate) { timelib_update_ts(o1->time, o1->time->tz_info); } if (!o2->time->sse_uptodate) { timelib_update_ts(o2->time, o2->time->tz_info); } return (o1->time->sse == o2->time->sse) ? 0 : ((o1->time->sse < o2->time->sse) ? -1 : 1); } return 1; } static HashTable *date_object_get_properties(zval *object TSRMLS_DC) { HashTable *props; zval *zv; php_date_obj *dateobj; dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); props = zend_std_get_properties(object TSRMLS_CC); if (!dateobj->time || GC_G(gc_active)) { return props; } /* first we add the date and time in ISO format */ MAKE_STD_ZVAL(zv); ZVAL_STRING(zv, date_format("Y-m-d H:i:s", 12, dateobj->time, 1), 0); zend_hash_update(props, "date", 5, &zv, sizeof(zval), NULL); /* then we add the timezone name (or similar) */ if (dateobj->time->is_localtime) { MAKE_STD_ZVAL(zv); ZVAL_LONG(zv, dateobj->time->zone_type); zend_hash_update(props, "timezone_type", 14, &zv, sizeof(zval), NULL); MAKE_STD_ZVAL(zv); switch (dateobj->time->zone_type) { case TIMELIB_ZONETYPE_ID: ZVAL_STRING(zv, dateobj->time->tz_info->name, 1); break; case TIMELIB_ZONETYPE_OFFSET: { char *tmpstr = emalloc(sizeof("UTC+05:00")); timelib_sll utc_offset = dateobj->time->z; snprintf(tmpstr, sizeof("+05:00"), "%c%02d:%02d", utc_offset > 0 ? '-' : '+', abs(utc_offset / 60), abs((utc_offset % 60))); ZVAL_STRING(zv, tmpstr, 0); } break; case TIMELIB_ZONETYPE_ABBR: ZVAL_STRING(zv, dateobj->time->tz_abbr, 1); break; } zend_hash_update(props, "timezone", 9, &zv, sizeof(zval), NULL); } return props; } static inline zend_object_value date_object_new_timezone_ex(zend_class_entry *class_type, php_timezone_obj **ptr TSRMLS_DC) { php_timezone_obj *intern; zend_object_value retval; intern = emalloc(sizeof(php_timezone_obj)); memset(intern, 0, sizeof(php_timezone_obj)); if (ptr) { *ptr = intern; } zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) date_object_free_storage_timezone, NULL TSRMLS_CC); retval.handlers = &date_object_handlers_timezone; return retval; } static zend_object_value date_object_new_timezone(zend_class_entry *class_type TSRMLS_DC) { return date_object_new_timezone_ex(class_type, NULL TSRMLS_CC); } static zend_object_value date_object_clone_timezone(zval *this_ptr TSRMLS_DC) { php_timezone_obj *new_obj = NULL; php_timezone_obj *old_obj = (php_timezone_obj *) zend_object_store_get_object(this_ptr TSRMLS_CC); zend_object_value new_ov = date_object_new_timezone_ex(old_obj->std.ce, &new_obj TSRMLS_CC); zend_objects_clone_members(&new_obj->std, new_ov, &old_obj->std, Z_OBJ_HANDLE_P(this_ptr) TSRMLS_CC); new_obj->type = old_obj->type; new_obj->initialized = 1; switch (new_obj->type) { case TIMELIB_ZONETYPE_ID: new_obj->tzi.tz = old_obj->tzi.tz; break; case TIMELIB_ZONETYPE_OFFSET: new_obj->tzi.utc_offset = old_obj->tzi.utc_offset; break; case TIMELIB_ZONETYPE_ABBR: new_obj->tzi.z.utc_offset = old_obj->tzi.z.utc_offset; new_obj->tzi.z.dst = old_obj->tzi.z.dst; new_obj->tzi.z.abbr = old_obj->tzi.z.abbr; break; } return new_ov; } static inline zend_object_value date_object_new_interval_ex(zend_class_entry *class_type, php_interval_obj **ptr TSRMLS_DC) { php_interval_obj *intern; zend_object_value retval; intern = emalloc(sizeof(php_interval_obj)); memset(intern, 0, sizeof(php_interval_obj)); if (ptr) { *ptr = intern; } zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) date_object_free_storage_interval, NULL TSRMLS_CC); retval.handlers = &date_object_handlers_interval; return retval; } static zend_object_value date_object_new_interval(zend_class_entry *class_type TSRMLS_DC) { return date_object_new_interval_ex(class_type, NULL TSRMLS_CC); } static zend_object_value date_object_clone_interval(zval *this_ptr TSRMLS_DC) { php_interval_obj *new_obj = NULL; php_interval_obj *old_obj = (php_interval_obj *) zend_object_store_get_object(this_ptr TSRMLS_CC); zend_object_value new_ov = date_object_new_interval_ex(old_obj->std.ce, &new_obj TSRMLS_CC); zend_objects_clone_members(&new_obj->std, new_ov, &old_obj->std, Z_OBJ_HANDLE_P(this_ptr) TSRMLS_CC); /** FIX ME ADD CLONE STUFF **/ return new_ov; } static HashTable *date_object_get_properties_interval(zval *object TSRMLS_DC) { HashTable *props; zval *zv; php_interval_obj *intervalobj; intervalobj = (php_interval_obj *) zend_object_store_get_object(object TSRMLS_CC); props = zend_std_get_properties(object TSRMLS_CC); if (!intervalobj->initialized || GC_G(gc_active)) { return props; } #define PHP_DATE_INTERVAL_ADD_PROPERTY(n,f) \ MAKE_STD_ZVAL(zv); \ ZVAL_LONG(zv, intervalobj->diff->f); \ zend_hash_update(props, n, strlen(n) + 1, &zv, sizeof(zval), NULL); PHP_DATE_INTERVAL_ADD_PROPERTY("y", y); PHP_DATE_INTERVAL_ADD_PROPERTY("m", m); PHP_DATE_INTERVAL_ADD_PROPERTY("d", d); PHP_DATE_INTERVAL_ADD_PROPERTY("h", h); PHP_DATE_INTERVAL_ADD_PROPERTY("i", i); PHP_DATE_INTERVAL_ADD_PROPERTY("s", s); PHP_DATE_INTERVAL_ADD_PROPERTY("invert", invert); if (intervalobj->diff->days != -99999) { PHP_DATE_INTERVAL_ADD_PROPERTY("days", days); } else { MAKE_STD_ZVAL(zv); ZVAL_FALSE(zv); zend_hash_update(props, "days", 5, &zv, sizeof(zval), NULL); } return props; } static inline zend_object_value date_object_new_period_ex(zend_class_entry *class_type, php_period_obj **ptr TSRMLS_DC) { php_period_obj *intern; zend_object_value retval; intern = emalloc(sizeof(php_period_obj)); memset(intern, 0, sizeof(php_period_obj)); if (ptr) { *ptr = intern; } zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) date_object_free_storage_period, NULL TSRMLS_CC); retval.handlers = &date_object_handlers_period; return retval; } static zend_object_value date_object_new_period(zend_class_entry *class_type TSRMLS_DC) { return date_object_new_period_ex(class_type, NULL TSRMLS_CC); } static zend_object_value date_object_clone_period(zval *this_ptr TSRMLS_DC) { php_period_obj *new_obj = NULL; php_period_obj *old_obj = (php_period_obj *) zend_object_store_get_object(this_ptr TSRMLS_CC); zend_object_value new_ov = date_object_new_period_ex(old_obj->std.ce, &new_obj TSRMLS_CC); zend_objects_clone_members(&new_obj->std, new_ov, &old_obj->std, Z_OBJ_HANDLE_P(this_ptr) TSRMLS_CC); /** FIX ME ADD CLONE STUFF **/ return new_ov; } static void date_object_free_storage_date(void *object TSRMLS_DC) { php_date_obj *intern = (php_date_obj *)object; if (intern->time) { timelib_time_dtor(intern->time); } zend_object_std_dtor(&intern->std TSRMLS_CC); efree(object); } static void date_object_free_storage_timezone(void *object TSRMLS_DC) { php_timezone_obj *intern = (php_timezone_obj *)object; if (intern->type == TIMELIB_ZONETYPE_ABBR) { free(intern->tzi.z.abbr); } zend_object_std_dtor(&intern->std TSRMLS_CC); efree(object); } static void date_object_free_storage_interval(void *object TSRMLS_DC) { php_interval_obj *intern = (php_interval_obj *)object; timelib_rel_time_dtor(intern->diff); zend_object_std_dtor(&intern->std TSRMLS_CC); efree(object); } static void date_object_free_storage_period(void *object TSRMLS_DC) { php_period_obj *intern = (php_period_obj *)object; if (intern->start) { timelib_time_dtor(intern->start); } if (intern->current) { timelib_time_dtor(intern->current); } if (intern->end) { timelib_time_dtor(intern->end); } timelib_rel_time_dtor(intern->interval); zend_object_std_dtor(&intern->std TSRMLS_CC); efree(object); } /* Advanced Interface */ PHPAPI zval *php_date_instantiate(zend_class_entry *pce, zval *object TSRMLS_DC) { Z_TYPE_P(object) = IS_OBJECT; object_init_ex(object, pce); Z_SET_REFCOUNT_P(object, 1); Z_UNSET_ISREF_P(object); return object; } /* Helper function used to store the latest found warnings and errors while * parsing, from either strtotime or parse_from_format. */ static void update_errors_warnings(timelib_error_container *last_errors TSRMLS_DC) { if (DATEG(last_errors)) { timelib_error_container_dtor(DATEG(last_errors)); DATEG(last_errors) = NULL; } DATEG(last_errors) = last_errors; } PHPAPI int php_date_initialize(php_date_obj *dateobj, /*const*/ char *time_str, int time_str_len, char *format, zval *timezone_object, int ctor TSRMLS_DC) { timelib_time *now; timelib_tzinfo *tzi; timelib_error_container *err = NULL; int type = TIMELIB_ZONETYPE_ID, new_dst; char *new_abbr; timelib_sll new_offset; if (dateobj->time) { timelib_time_dtor(dateobj->time); } if (format) { dateobj->time = timelib_parse_from_format(format, time_str_len ? time_str : "", time_str_len ? time_str_len : 0, &err, DATE_TIMEZONEDB); } else { dateobj->time = timelib_strtotime(time_str_len ? time_str : "now", time_str_len ? time_str_len : sizeof("now") -1, &err, DATE_TIMEZONEDB); } /* update last errors and warnings */ update_errors_warnings(err TSRMLS_CC); if (ctor && err && err->error_count) { /* spit out the first library error message, at least */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse time string (%s) at position %d (%c): %s", time_str, err->error_messages[0].position, err->error_messages[0].character, err->error_messages[0].message); } if (err && err->error_count) { return 0; } if (timezone_object) { php_timezone_obj *tzobj; tzobj = (php_timezone_obj *) zend_object_store_get_object(timezone_object TSRMLS_CC); switch (tzobj->type) { case TIMELIB_ZONETYPE_ID: tzi = tzobj->tzi.tz; break; case TIMELIB_ZONETYPE_OFFSET: new_offset = tzobj->tzi.utc_offset; break; case TIMELIB_ZONETYPE_ABBR: new_offset = tzobj->tzi.z.utc_offset; new_dst = tzobj->tzi.z.dst; new_abbr = strdup(tzobj->tzi.z.abbr); break; } type = tzobj->type; } else if (dateobj->time->tz_info) { tzi = dateobj->time->tz_info; } else { tzi = get_timezone_info(TSRMLS_C); } now = timelib_time_ctor(); now->zone_type = type; switch (type) { case TIMELIB_ZONETYPE_ID: now->tz_info = tzi; break; case TIMELIB_ZONETYPE_OFFSET: now->z = new_offset; break; case TIMELIB_ZONETYPE_ABBR: now->z = new_offset; now->dst = new_dst; now->tz_abbr = new_abbr; break; } timelib_unixtime2local(now, (timelib_sll) time(NULL)); timelib_fill_holes(dateobj->time, now, TIMELIB_NO_CLONE); timelib_update_ts(dateobj->time, tzi); dateobj->time->have_relative = 0; timelib_time_dtor(now); return 1; } /* {{{ proto DateTime date_create([string time[, DateTimeZone object]]) Returns new DateTime object */ PHP_FUNCTION(date_create) { zval *timezone_object = NULL; char *time_str = NULL; int time_str_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sO!", &time_str, &time_str_len, &timezone_object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } php_date_instantiate(date_ce_date, return_value TSRMLS_CC); if (!php_date_initialize(zend_object_store_get_object(return_value TSRMLS_CC), time_str, time_str_len, NULL, timezone_object, 0 TSRMLS_CC)) { RETURN_FALSE; } } /* }}} */ /* {{{ proto DateTime date_create_from_format(string format, string time[, DateTimeZone object]) Returns new DateTime object formatted according to the specified format */ PHP_FUNCTION(date_create_from_format) { zval *timezone_object = NULL; char *time_str = NULL, *format_str = NULL; int time_str_len = 0, format_str_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|O", &format_str, &format_str_len, &time_str, &time_str_len, &timezone_object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } php_date_instantiate(date_ce_date, return_value TSRMLS_CC); if (!php_date_initialize(zend_object_store_get_object(return_value TSRMLS_CC), time_str, time_str_len, format_str, timezone_object, 0 TSRMLS_CC)) { RETURN_FALSE; } } /* }}} */ /* {{{ proto DateTime::__construct([string time[, DateTimeZone object]]) Creates new DateTime object */ PHP_METHOD(DateTime, __construct) { zval *timezone_object = NULL; char *time_str = NULL; int time_str_len = 0; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sO!", &time_str, &time_str_len, &timezone_object, date_ce_timezone)) { php_date_initialize(zend_object_store_get_object(getThis() TSRMLS_CC), time_str, time_str_len, NULL, timezone_object, 1 TSRMLS_CC); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ static int php_date_initialize_from_hash(zval **return_value, php_date_obj **dateobj, HashTable *myht TSRMLS_DC) { zval **z_date = NULL; zval **z_timezone = NULL; zval **z_timezone_type = NULL; zval *tmp_obj = NULL; timelib_tzinfo *tzi; php_timezone_obj *tzobj; if (zend_hash_find(myht, "date", 5, (void**) &z_date) == SUCCESS) { convert_to_string(*z_date); if (zend_hash_find(myht, "timezone_type", 14, (void**) &z_timezone_type) == SUCCESS) { convert_to_long(*z_timezone_type); if (zend_hash_find(myht, "timezone", 9, (void**) &z_timezone) == SUCCESS) { convert_to_string(*z_timezone); switch (Z_LVAL_PP(z_timezone_type)) { case TIMELIB_ZONETYPE_OFFSET: case TIMELIB_ZONETYPE_ABBR: { char *tmp = emalloc(Z_STRLEN_PP(z_date) + Z_STRLEN_PP(z_timezone) + 2); snprintf(tmp, Z_STRLEN_PP(z_date) + Z_STRLEN_PP(z_timezone) + 2, "%s %s", Z_STRVAL_PP(z_date), Z_STRVAL_PP(z_timezone)); php_date_initialize(*dateobj, tmp, Z_STRLEN_PP(z_date) + Z_STRLEN_PP(z_timezone) + 1, NULL, NULL, 0 TSRMLS_CC); efree(tmp); return 1; } case TIMELIB_ZONETYPE_ID: convert_to_string(*z_timezone); tzi = php_date_parse_tzfile(Z_STRVAL_PP(z_timezone), DATE_TIMEZONEDB TSRMLS_CC); ALLOC_INIT_ZVAL(tmp_obj); tzobj = zend_object_store_get_object(php_date_instantiate(date_ce_timezone, tmp_obj TSRMLS_CC) TSRMLS_CC); tzobj->type = TIMELIB_ZONETYPE_ID; tzobj->tzi.tz = tzi; tzobj->initialized = 1; php_date_initialize(*dateobj, Z_STRVAL_PP(z_date), Z_STRLEN_PP(z_date), NULL, tmp_obj, 0 TSRMLS_CC); zval_ptr_dtor(&tmp_obj); return 1; } } } } return 0; } /* {{{ proto DateTime::__set_state() */ PHP_METHOD(DateTime, __set_state) { php_date_obj *dateobj; zval *array; HashTable *myht; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) { RETURN_FALSE; } myht = HASH_OF(array); php_date_instantiate(date_ce_date, return_value TSRMLS_CC); dateobj = (php_date_obj *) zend_object_store_get_object(return_value TSRMLS_CC); php_date_initialize_from_hash(&return_value, &dateobj, myht TSRMLS_CC); } /* }}} */ /* {{{ proto DateTime::__wakeup() */ PHP_METHOD(DateTime, __wakeup) { zval *object = getThis(); php_date_obj *dateobj; HashTable *myht; dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); myht = Z_OBJPROP_P(object); php_date_initialize_from_hash(&return_value, &dateobj, myht TSRMLS_CC); } /* }}} */ /* Helper function used to add an associative array of warnings and errors to a zval */ static void zval_from_error_container(zval *z, timelib_error_container *error) { int i; zval *element; add_assoc_long(z, "warning_count", error->warning_count); MAKE_STD_ZVAL(element); array_init(element); for (i = 0; i < error->warning_count; i++) { add_index_string(element, error->warning_messages[i].position, error->warning_messages[i].message, 1); } add_assoc_zval(z, "warnings", element); add_assoc_long(z, "error_count", error->error_count); MAKE_STD_ZVAL(element); array_init(element); for (i = 0; i < error->error_count; i++) { add_index_string(element, error->error_messages[i].position, error->error_messages[i].message, 1); } add_assoc_zval(z, "errors", element); } /* {{{ proto array date_get_last_errors() Returns the warnings and errors found while parsing a date/time string. */ PHP_FUNCTION(date_get_last_errors) { if (DATEG(last_errors)) { array_init(return_value); zval_from_error_container(return_value, DATEG(last_errors)); } else { RETURN_FALSE; } } /* }}} */ void php_date_do_return_parsed_time(INTERNAL_FUNCTION_PARAMETERS, timelib_time *parsed_time, struct timelib_error_container *error) { zval *element; array_init(return_value); #define PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(name, elem) \ if (parsed_time->elem == -99999) { \ add_assoc_bool(return_value, #name, 0); \ } else { \ add_assoc_long(return_value, #name, parsed_time->elem); \ } PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(year, y); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(month, m); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(day, d); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(hour, h); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(minute, i); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(second, s); if (parsed_time->f == -99999) { add_assoc_bool(return_value, "fraction", 0); } else { add_assoc_double(return_value, "fraction", parsed_time->f); } zval_from_error_container(return_value, error); timelib_error_container_dtor(error); add_assoc_bool(return_value, "is_localtime", parsed_time->is_localtime); if (parsed_time->is_localtime) { PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(zone_type, zone_type); switch (parsed_time->zone_type) { case TIMELIB_ZONETYPE_OFFSET: PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(zone, z); add_assoc_bool(return_value, "is_dst", parsed_time->dst); break; case TIMELIB_ZONETYPE_ID: if (parsed_time->tz_abbr) { add_assoc_string(return_value, "tz_abbr", parsed_time->tz_abbr, 1); } if (parsed_time->tz_info) { add_assoc_string(return_value, "tz_id", parsed_time->tz_info->name, 1); } break; case TIMELIB_ZONETYPE_ABBR: PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(zone, z); add_assoc_bool(return_value, "is_dst", parsed_time->dst); add_assoc_string(return_value, "tz_abbr", parsed_time->tz_abbr, 1); break; } } if (parsed_time->have_relative) { MAKE_STD_ZVAL(element); array_init(element); add_assoc_long(element, "year", parsed_time->relative.y); add_assoc_long(element, "month", parsed_time->relative.m); add_assoc_long(element, "day", parsed_time->relative.d); add_assoc_long(element, "hour", parsed_time->relative.h); add_assoc_long(element, "minute", parsed_time->relative.i); add_assoc_long(element, "second", parsed_time->relative.s); if (parsed_time->relative.have_weekday_relative) { add_assoc_long(element, "weekday", parsed_time->relative.weekday); } if (parsed_time->relative.have_special_relative && (parsed_time->relative.special.type == TIMELIB_SPECIAL_WEEKDAY)) { add_assoc_long(element, "weekdays", parsed_time->relative.special.amount); } if (parsed_time->relative.first_last_day_of) { add_assoc_bool(element, parsed_time->relative.first_last_day_of == 1 ? "first_day_of_month" : "last_day_of_month", 1); } add_assoc_zval(return_value, "relative", element); } timelib_time_dtor(parsed_time); } /* {{{ proto array date_parse(string date) Returns associative array with detailed info about given date */ PHP_FUNCTION(date_parse) { char *date; int date_len; struct timelib_error_container *error; timelib_time *parsed_time; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &date, &date_len) == FAILURE) { RETURN_FALSE; } parsed_time = timelib_strtotime(date, date_len, &error, DATE_TIMEZONEDB); php_date_do_return_parsed_time(INTERNAL_FUNCTION_PARAM_PASSTHRU, parsed_time, error); } /* }}} */ /* {{{ proto array date_parse_from_format(string format, string date) Returns associative array with detailed info about given date */ PHP_FUNCTION(date_parse_from_format) { char *date, *format; int date_len, format_len; struct timelib_error_container *error; timelib_time *parsed_time; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &format, &format_len, &date, &date_len) == FAILURE) { RETURN_FALSE; } parsed_time = timelib_parse_from_format(format, date, date_len, &error, DATE_TIMEZONEDB); php_date_do_return_parsed_time(INTERNAL_FUNCTION_PARAM_PASSTHRU, parsed_time, error); } /* }}} */ /* {{{ proto string date_format(DateTime object, string format) Returns date formatted according to given format */ PHP_FUNCTION(date_format) { zval *object; php_date_obj *dateobj; char *format; int format_len; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, date_ce_date, &format, &format_len) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); RETURN_STRING(date_format(format, format_len, dateobj->time, dateobj->time->is_localtime), 0); } /* }}} */ /* {{{ proto DateTime date_modify(DateTime object, string modify) Alters the timestamp. */ PHP_FUNCTION(date_modify) { zval *object; php_date_obj *dateobj; char *modify; int modify_len; timelib_time *tmp_time; timelib_error_container *err = NULL; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, date_ce_date, &modify, &modify_len) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); tmp_time = timelib_strtotime(modify, modify_len, &err, DATE_TIMEZONEDB); /* update last errors and warnings */ update_errors_warnings(err TSRMLS_CC); if (err && err->error_count) { /* spit out the first library error message, at least */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse time string (%s) at position %d (%c): %s", modify, err->error_messages[0].position, err->error_messages[0].character, err->error_messages[0].message); timelib_time_dtor(tmp_time); RETURN_FALSE; } memcpy(&dateobj->time->relative, &tmp_time->relative, sizeof(struct timelib_rel_time)); dateobj->time->have_relative = tmp_time->have_relative; dateobj->time->sse_uptodate = 0; if (tmp_time->y != -99999) { dateobj->time->y = tmp_time->y; } if (tmp_time->m != -99999) { dateobj->time->m = tmp_time->m; } if (tmp_time->d != -99999) { dateobj->time->d = tmp_time->d; } if (tmp_time->h != -99999) { dateobj->time->h = tmp_time->h; if (tmp_time->i != -99999) { dateobj->time->i = tmp_time->i; if (tmp_time->s != -99999) { dateobj->time->s = tmp_time->s; } else { dateobj->time->s = 0; } } else { dateobj->time->i = 0; dateobj->time->s = 0; } } timelib_time_dtor(tmp_time); timelib_update_ts(dateobj->time, NULL); timelib_update_from_sse(dateobj->time); dateobj->time->have_relative = 0; RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_add(DateTime object, DateInterval interval) Adds an interval to the current date in object. */ PHP_FUNCTION(date_add) { zval *object, *interval; php_date_obj *dateobj; php_interval_obj *intobj; int bias = 1; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &object, date_ce_date, &interval, date_ce_interval) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); intobj = (php_interval_obj *) zend_object_store_get_object(interval TSRMLS_CC); DATE_CHECK_INITIALIZED(intobj->initialized, DateInterval); if (intobj->diff->have_weekday_relative || intobj->diff->have_special_relative) { memcpy(&dateobj->time->relative, intobj->diff, sizeof(struct timelib_rel_time)); } else { if (intobj->diff->invert) { bias = -1; } dateobj->time->relative.y = intobj->diff->y * bias; dateobj->time->relative.m = intobj->diff->m * bias; dateobj->time->relative.d = intobj->diff->d * bias; dateobj->time->relative.h = intobj->diff->h * bias; dateobj->time->relative.i = intobj->diff->i * bias; dateobj->time->relative.s = intobj->diff->s * bias; dateobj->time->relative.weekday = 0; dateobj->time->relative.have_weekday_relative = 0; } dateobj->time->have_relative = 1; dateobj->time->sse_uptodate = 0; timelib_update_ts(dateobj->time, NULL); timelib_update_from_sse(dateobj->time); dateobj->time->have_relative = 0; RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_sub(DateTime object, DateInterval interval) Subtracts an interval to the current date in object. */ PHP_FUNCTION(date_sub) { zval *object, *interval; php_date_obj *dateobj; php_interval_obj *intobj; int bias = 1; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &object, date_ce_date, &interval, date_ce_interval) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); intobj = (php_interval_obj *) zend_object_store_get_object(interval TSRMLS_CC); DATE_CHECK_INITIALIZED(intobj->initialized, DateInterval); if (intobj->diff->have_special_relative) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Only non-special relative time specifications are supported for subtraction"); return; } if (intobj->diff->invert) { bias = -1; } dateobj->time->relative.y = 0 - (intobj->diff->y * bias); dateobj->time->relative.m = 0 - (intobj->diff->m * bias); dateobj->time->relative.d = 0 - (intobj->diff->d * bias); dateobj->time->relative.h = 0 - (intobj->diff->h * bias); dateobj->time->relative.i = 0 - (intobj->diff->i * bias); dateobj->time->relative.s = 0 - (intobj->diff->s * bias); dateobj->time->have_relative = 1; dateobj->time->relative.weekday = 0; dateobj->time->relative.have_weekday_relative = 0; dateobj->time->sse_uptodate = 0; timelib_update_ts(dateobj->time, NULL); timelib_update_from_sse(dateobj->time); dateobj->time->have_relative = 0; RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTimeZone date_timezone_get(DateTime object) Return new DateTimeZone object relative to give DateTime */ PHP_FUNCTION(date_timezone_get) { zval *object; php_date_obj *dateobj; php_timezone_obj *tzobj; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_date) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); if (dateobj->time->is_localtime/* && dateobj->time->tz_info*/) { php_date_instantiate(date_ce_timezone, return_value TSRMLS_CC); tzobj = (php_timezone_obj *) zend_object_store_get_object(return_value TSRMLS_CC); tzobj->initialized = 1; tzobj->type = dateobj->time->zone_type; switch (dateobj->time->zone_type) { case TIMELIB_ZONETYPE_ID: tzobj->tzi.tz = dateobj->time->tz_info; break; case TIMELIB_ZONETYPE_OFFSET: tzobj->tzi.utc_offset = dateobj->time->z; break; case TIMELIB_ZONETYPE_ABBR: tzobj->tzi.z.utc_offset = dateobj->time->z; tzobj->tzi.z.dst = dateobj->time->dst; tzobj->tzi.z.abbr = strdup(dateobj->time->tz_abbr); break; } } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto DateTime date_timezone_set(DateTime object, DateTimeZone object) Sets the timezone for the DateTime object. */ PHP_FUNCTION(date_timezone_set) { zval *object; zval *timezone_object; php_date_obj *dateobj; php_timezone_obj *tzobj; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &object, date_ce_date, &timezone_object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); tzobj = (php_timezone_obj *) zend_object_store_get_object(timezone_object TSRMLS_CC); if (tzobj->type != TIMELIB_ZONETYPE_ID) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can only do this for zones with ID for now"); return; } timelib_set_timezone(dateobj->time, tzobj->tzi.tz); timelib_unixtime2local(dateobj->time, dateobj->time->sse); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto long date_offset_get(DateTime object) Returns the DST offset. */ PHP_FUNCTION(date_offset_get) { zval *object; php_date_obj *dateobj; timelib_time_offset *offset; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_date) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); if (dateobj->time->is_localtime/* && dateobj->time->tz_info*/) { switch (dateobj->time->zone_type) { case TIMELIB_ZONETYPE_ID: offset = timelib_get_time_zone_info(dateobj->time->sse, dateobj->time->tz_info); RETVAL_LONG(offset->offset); timelib_time_offset_dtor(offset); break; case TIMELIB_ZONETYPE_OFFSET: RETVAL_LONG(dateobj->time->z * -60); break; case TIMELIB_ZONETYPE_ABBR: RETVAL_LONG((dateobj->time->z - (60 * dateobj->time->dst)) * -60); break; } return; } else { RETURN_LONG(0); } } /* }}} */ /* {{{ proto DateTime date_time_set(DateTime object, long hour, long minute[, long second]) Sets the time. */ PHP_FUNCTION(date_time_set) { zval *object; php_date_obj *dateobj; long h, i, s = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oll|l", &object, date_ce_date, &h, &i, &s) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); dateobj->time->h = h; dateobj->time->i = i; dateobj->time->s = s; timelib_update_ts(dateobj->time, NULL); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_date_set(DateTime object, long year, long month, long day) Sets the date. */ PHP_FUNCTION(date_date_set) { zval *object; php_date_obj *dateobj; long y, m, d; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Olll", &object, date_ce_date, &y, &m, &d) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); dateobj->time->y = y; dateobj->time->m = m; dateobj->time->d = d; timelib_update_ts(dateobj->time, NULL); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_isodate_set(DateTime object, long year, long week[, long day]) Sets the ISO date. */ PHP_FUNCTION(date_isodate_set) { zval *object; php_date_obj *dateobj; long y, w, d = 1; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oll|l", &object, date_ce_date, &y, &w, &d) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); dateobj->time->y = y; dateobj->time->m = 1; dateobj->time->d = 1; memset(&dateobj->time->relative, 0, sizeof(dateobj->time->relative)); dateobj->time->relative.d = timelib_daynr_from_weeknr(y, w, d); dateobj->time->have_relative = 1; timelib_update_ts(dateobj->time, NULL); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_timestamp_set(DateTime object, long unixTimestamp) Sets the date and time based on an Unix timestamp. */ PHP_FUNCTION(date_timestamp_set) { zval *object; php_date_obj *dateobj; long timestamp; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Ol", &object, date_ce_date, &timestamp) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); timelib_unixtime2local(dateobj->time, (timelib_sll)timestamp); timelib_update_ts(dateobj->time, NULL); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto long date_timestamp_get(DateTime object) Gets the Unix timestamp. */ PHP_FUNCTION(date_timestamp_get) { zval *object; php_date_obj *dateobj; long timestamp; int error; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_date) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); timelib_update_ts(dateobj->time, NULL); timestamp = timelib_date_to_int(dateobj->time, &error); if (error) { RETURN_FALSE; } else { RETVAL_LONG(timestamp); } } /* }}} */ /* {{{ proto DateInterval date_diff(DateTime object [, bool absolute]) Returns the difference between two DateTime objects. */ PHP_FUNCTION(date_diff) { zval *object1, *object2; php_date_obj *dateobj1, *dateobj2; php_interval_obj *interval; long absolute = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO|l", &object1, date_ce_date, &object2, date_ce_date, &absolute) == FAILURE) { RETURN_FALSE; } dateobj1 = (php_date_obj *) zend_object_store_get_object(object1 TSRMLS_CC); dateobj2 = (php_date_obj *) zend_object_store_get_object(object2 TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj1->time, DateTime); DATE_CHECK_INITIALIZED(dateobj2->time, DateTime); timelib_update_ts(dateobj1->time, NULL); timelib_update_ts(dateobj2->time, NULL); php_date_instantiate(date_ce_interval, return_value TSRMLS_CC); interval = zend_object_store_get_object(return_value TSRMLS_CC); interval->diff = timelib_diff(dateobj1->time, dateobj2->time); if (absolute) { interval->diff->invert = 0; } interval->initialized = 1; } /* }}} */ static int timezone_initialize(timelib_tzinfo **tzi, /*const*/ char *tz TSRMLS_DC) { char *tzid; *tzi = NULL; if ((tzid = timelib_timezone_id_from_abbr(tz, -1, 0))) { *tzi = php_date_parse_tzfile(tzid, DATE_TIMEZONEDB TSRMLS_CC); } else { *tzi = php_date_parse_tzfile(tz, DATE_TIMEZONEDB TSRMLS_CC); } if (*tzi) { return SUCCESS; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown or bad timezone (%s)", tz); return FAILURE; } } /* {{{ proto DateTimeZone timezone_open(string timezone) Returns new DateTimeZone object */ PHP_FUNCTION(timezone_open) { char *tz; int tz_len; timelib_tzinfo *tzi = NULL; php_timezone_obj *tzobj; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &tz, &tz_len) == FAILURE) { RETURN_FALSE; } if (SUCCESS != timezone_initialize(&tzi, tz TSRMLS_CC)) { RETURN_FALSE; } tzobj = zend_object_store_get_object(php_date_instantiate(date_ce_timezone, return_value TSRMLS_CC) TSRMLS_CC); tzobj->type = TIMELIB_ZONETYPE_ID; tzobj->tzi.tz = tzi; tzobj->initialized = 1; } /* }}} */ /* {{{ proto DateTimeZone::__construct(string timezone) Creates new DateTimeZone object. */ PHP_METHOD(DateTimeZone, __construct) { char *tz; int tz_len; timelib_tzinfo *tzi = NULL; php_timezone_obj *tzobj; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &tz, &tz_len)) { if (SUCCESS == timezone_initialize(&tzi, tz TSRMLS_CC)) { tzobj = zend_object_store_get_object(getThis() TSRMLS_CC); tzobj->type = TIMELIB_ZONETYPE_ID; tzobj->tzi.tz = tzi; tzobj->initialized = 1; } else { ZVAL_NULL(getThis()); } } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto string timezone_name_get(DateTimeZone object) Returns the name of the timezone. */ PHP_FUNCTION(timezone_name_get) { zval *object; php_timezone_obj *tzobj; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } tzobj = (php_timezone_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(tzobj->initialized, DateTimeZone); switch (tzobj->type) { case TIMELIB_ZONETYPE_ID: RETURN_STRING(tzobj->tzi.tz->name, 1); break; case TIMELIB_ZONETYPE_OFFSET: { char *tmpstr = emalloc(sizeof("UTC+05:00")); timelib_sll utc_offset = tzobj->tzi.utc_offset; snprintf(tmpstr, sizeof("+05:00"), "%c%02d:%02d", utc_offset > 0 ? '-' : '+', abs(utc_offset / 60), abs((utc_offset % 60))); RETURN_STRING(tmpstr, 0); } break; case TIMELIB_ZONETYPE_ABBR: RETURN_STRING(tzobj->tzi.z.abbr, 1); break; } } /* }}} */ /* {{{ proto string timezone_name_from_abbr(string abbr[, long gmtOffset[, long isdst]]) Returns the timezone name from abbrevation */ PHP_FUNCTION(timezone_name_from_abbr) { char *abbr; char *tzid; int abbr_len; long gmtoffset = -1; long isdst = -1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ll", &abbr, &abbr_len, &gmtoffset, &isdst) == FAILURE) { RETURN_FALSE; } tzid = timelib_timezone_id_from_abbr(abbr, gmtoffset, isdst); if (tzid) { RETURN_STRING(tzid, 1); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto long timezone_offset_get(DateTimeZone object, DateTime object) Returns the timezone offset. */ PHP_FUNCTION(timezone_offset_get) { zval *object, *dateobject; php_timezone_obj *tzobj; php_date_obj *dateobj; timelib_time_offset *offset; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &object, date_ce_timezone, &dateobject, date_ce_date) == FAILURE) { RETURN_FALSE; } tzobj = (php_timezone_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(tzobj->initialized, DateTimeZone); dateobj = (php_date_obj *) zend_object_store_get_object(dateobject TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); switch (tzobj->type) { case TIMELIB_ZONETYPE_ID: offset = timelib_get_time_zone_info(dateobj->time->sse, tzobj->tzi.tz); RETVAL_LONG(offset->offset); timelib_time_offset_dtor(offset); break; case TIMELIB_ZONETYPE_OFFSET: RETURN_LONG(tzobj->tzi.utc_offset * -60); break; case TIMELIB_ZONETYPE_ABBR: RETURN_LONG((tzobj->tzi.z.utc_offset - (tzobj->tzi.z.dst*60)) * -60); break; } } /* }}} */ /* {{{ proto array timezone_transitions_get(DateTimeZone object [, long timestamp_begin [, long timestamp_end ]]) Returns numerically indexed array containing associative array for all transitions in the specified range for the timezone. */ PHP_FUNCTION(timezone_transitions_get) { zval *object, *element; php_timezone_obj *tzobj; unsigned int i, begin = 0, found; long timestamp_begin = LONG_MIN, timestamp_end = LONG_MAX; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|ll", &object, date_ce_timezone, &timestamp_begin, &timestamp_end) == FAILURE) { RETURN_FALSE; } tzobj = (php_timezone_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(tzobj->initialized, DateTimeZone); if (tzobj->type != TIMELIB_ZONETYPE_ID) { RETURN_FALSE; } #define add_nominal() \ MAKE_STD_ZVAL(element); \ array_init(element); \ add_assoc_long(element, "ts", timestamp_begin); \ add_assoc_string(element, "time", php_format_date(DATE_FORMAT_ISO8601, 13, timestamp_begin, 0 TSRMLS_CC), 0); \ add_assoc_long(element, "offset", tzobj->tzi.tz->type[0].offset); \ add_assoc_bool(element, "isdst", tzobj->tzi.tz->type[0].isdst); \ add_assoc_string(element, "abbr", &tzobj->tzi.tz->timezone_abbr[tzobj->tzi.tz->type[0].abbr_idx], 1); \ add_next_index_zval(return_value, element); #define add(i,ts) \ MAKE_STD_ZVAL(element); \ array_init(element); \ add_assoc_long(element, "ts", ts); \ add_assoc_string(element, "time", php_format_date(DATE_FORMAT_ISO8601, 13, ts, 0 TSRMLS_CC), 0); \ add_assoc_long(element, "offset", tzobj->tzi.tz->type[tzobj->tzi.tz->trans_idx[i]].offset); \ add_assoc_bool(element, "isdst", tzobj->tzi.tz->type[tzobj->tzi.tz->trans_idx[i]].isdst); \ add_assoc_string(element, "abbr", &tzobj->tzi.tz->timezone_abbr[tzobj->tzi.tz->type[tzobj->tzi.tz->trans_idx[i]].abbr_idx], 1); \ add_next_index_zval(return_value, element); #define add_last() add(tzobj->tzi.tz->timecnt - 1, timestamp_begin) array_init(return_value); if (timestamp_begin == LONG_MIN) { add_nominal(); begin = 0; found = 1; } else { begin = 0; found = 0; if (tzobj->tzi.tz->timecnt > 0) { do { if (tzobj->tzi.tz->trans[begin] > timestamp_begin) { if (begin > 0) { add(begin - 1, timestamp_begin); } else { add_nominal(); } found = 1; break; } begin++; } while (begin < tzobj->tzi.tz->timecnt); } } if (!found) { if (tzobj->tzi.tz->timecnt > 0) { add_last(); } else { add_nominal(); } } else { for (i = begin; i < tzobj->tzi.tz->timecnt; ++i) { if (tzobj->tzi.tz->trans[i] < timestamp_end) { add(i, tzobj->tzi.tz->trans[i]); } } } } /* }}} */ /* {{{ proto array timezone_location_get() Returns location information for a timezone, including country code, latitude/longitude and comments */ PHP_FUNCTION(timezone_location_get) { zval *object; php_timezone_obj *tzobj; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } tzobj = (php_timezone_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(tzobj->initialized, DateTimeZone); if (tzobj->type != TIMELIB_ZONETYPE_ID) { RETURN_FALSE; } array_init(return_value); add_assoc_string(return_value, "country_code", tzobj->tzi.tz->location.country_code, 1); add_assoc_double(return_value, "latitude", tzobj->tzi.tz->location.latitude); add_assoc_double(return_value, "longitude", tzobj->tzi.tz->location.longitude); add_assoc_string(return_value, "comments", tzobj->tzi.tz->location.comments, 1); } /* }}} */ static int date_interval_initialize(timelib_rel_time **rt, /*const*/ char *format, int format_length TSRMLS_DC) { timelib_time *b = NULL, *e = NULL; timelib_rel_time *p = NULL; int r = 0; int retval = 0; struct timelib_error_container *errors; timelib_strtointerval(format, format_length, &b, &e, &p, &r, &errors); if (errors->error_count > 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown or bad format (%s)", format); retval = FAILURE; } else { if(p) { *rt = p; retval = SUCCESS; } else { if(b && e) { timelib_update_ts(b, NULL); timelib_update_ts(e, NULL); *rt = timelib_diff(b, e); retval = SUCCESS; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse interval (%s)", format); retval = FAILURE; } } } timelib_error_container_dtor(errors); return retval; } /* {{{ date_interval_read_property */ zval *date_interval_read_property(zval *object, zval *member, int type, const zend_literal *key TSRMLS_DC) { php_interval_obj *obj; zval *retval; zval tmp_member; timelib_sll value = -1; if (member->type != IS_STRING) { tmp_member = *member; zval_copy_ctor(&tmp_member); convert_to_string(&tmp_member); member = &tmp_member; } obj = (php_interval_obj *)zend_objects_get_address(object TSRMLS_CC); #define GET_VALUE_FROM_STRUCT(n,m) \ if (strcmp(Z_STRVAL_P(member), m) == 0) { \ value = obj->diff->n; \ break; \ } do { GET_VALUE_FROM_STRUCT(y, "y"); GET_VALUE_FROM_STRUCT(m, "m"); GET_VALUE_FROM_STRUCT(d, "d"); GET_VALUE_FROM_STRUCT(h, "h"); GET_VALUE_FROM_STRUCT(i, "i"); GET_VALUE_FROM_STRUCT(s, "s"); GET_VALUE_FROM_STRUCT(invert, "invert"); GET_VALUE_FROM_STRUCT(days, "days"); /* didn't find any */ retval = (zend_get_std_object_handlers())->read_property(object, member, type, key TSRMLS_CC); if (member == &tmp_member) { zval_dtor(member); } return retval; } while(0); ALLOC_INIT_ZVAL(retval); Z_SET_REFCOUNT_P(retval, 0); ZVAL_LONG(retval, value); if (member == &tmp_member) { zval_dtor(member); } return retval; } /* }}} */ /* {{{ date_interval_write_property */ void date_interval_write_property(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC) { php_interval_obj *obj; zval tmp_member, tmp_value; if (member->type != IS_STRING) { tmp_member = *member; zval_copy_ctor(&tmp_member); convert_to_string(&tmp_member); member = &tmp_member; } obj = (php_interval_obj *)zend_objects_get_address(object TSRMLS_CC); #define SET_VALUE_FROM_STRUCT(n,m) \ if (strcmp(Z_STRVAL_P(member), m) == 0) { \ if (value->type != IS_LONG) { \ tmp_value = *value; \ zval_copy_ctor(&tmp_value); \ convert_to_long(&tmp_value); \ value = &tmp_value; \ } \ obj->diff->n = Z_LVAL_P(value); \ if (value == &tmp_value) { \ zval_dtor(value); \ } \ break; \ } do { SET_VALUE_FROM_STRUCT(y, "y"); SET_VALUE_FROM_STRUCT(m, "m"); SET_VALUE_FROM_STRUCT(d, "d"); SET_VALUE_FROM_STRUCT(h, "h"); SET_VALUE_FROM_STRUCT(i, "i"); SET_VALUE_FROM_STRUCT(s, "s"); SET_VALUE_FROM_STRUCT(invert, "invert"); /* didn't find any */ (zend_get_std_object_handlers())->write_property(object, member, value, key TSRMLS_CC); } while(0); if (member == &tmp_member) { zval_dtor(member); } } /* }}} */ /* {{{ proto DateInterval::__construct([string interval_spec]) Creates new DateInterval object. */ PHP_METHOD(DateInterval, __construct) { char *interval_string = NULL; int interval_string_length; php_interval_obj *diobj; timelib_rel_time *reltime; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &interval_string, &interval_string_length) == SUCCESS) { if (date_interval_initialize(&reltime, interval_string, interval_string_length TSRMLS_CC) == SUCCESS) { diobj = zend_object_store_get_object(getThis() TSRMLS_CC); diobj->diff = reltime; diobj->initialized = 1; } else { ZVAL_NULL(getThis()); } } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto DateInterval date_interval_create_from_date_string(string time) Uses the normal date parsers and sets up a DateInterval from the relative parts of the parsed string */ PHP_FUNCTION(date_interval_create_from_date_string) { char *time_str = NULL; int time_str_len = 0; timelib_time *time; timelib_error_container *err = NULL; php_interval_obj *diobj; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &time_str, &time_str_len) == FAILURE) { RETURN_FALSE; } php_date_instantiate(date_ce_interval, return_value TSRMLS_CC); time = timelib_strtotime(time_str, time_str_len, &err, DATE_TIMEZONEDB); diobj = (php_interval_obj *) zend_object_store_get_object(return_value TSRMLS_CC); diobj->diff = timelib_rel_time_clone(&time->relative); diobj->initialized = 1; timelib_time_dtor(time); timelib_error_container_dtor(err); } /* }}} */ /* {{{ date_interval_format - */ static char *date_interval_format(char *format, int format_len, timelib_rel_time *t) { smart_str string = {0}; int i, length, have_format_spec = 0; char buffer[33]; if (!format_len) { return estrdup(""); } for (i = 0; i < format_len; i++) { if (have_format_spec) { switch (format[i]) { case 'Y': length = slprintf(buffer, 32, "%02d", (int) t->y); break; case 'y': length = slprintf(buffer, 32, "%d", (int) t->y); break; case 'M': length = slprintf(buffer, 32, "%02d", (int) t->m); break; case 'm': length = slprintf(buffer, 32, "%d", (int) t->m); break; case 'D': length = slprintf(buffer, 32, "%02d", (int) t->d); break; case 'd': length = slprintf(buffer, 32, "%d", (int) t->d); break; case 'H': length = slprintf(buffer, 32, "%02d", (int) t->h); break; case 'h': length = slprintf(buffer, 32, "%d", (int) t->h); break; case 'I': length = slprintf(buffer, 32, "%02d", (int) t->i); break; case 'i': length = slprintf(buffer, 32, "%d", (int) t->i); break; case 'S': length = slprintf(buffer, 32, "%02d", (int) t->s); break; case 's': length = slprintf(buffer, 32, "%d", (int) t->s); break; case 'a': { if ((int) t->days != -99999) { length = slprintf(buffer, 32, "%d", (int) t->days); } else { length = slprintf(buffer, 32, "(unknown)"); } } break; case 'r': length = slprintf(buffer, 32, "%s", t->invert ? "-" : ""); break; case 'R': length = slprintf(buffer, 32, "%c", t->invert ? '-' : '+'); break; case '%': length = slprintf(buffer, 32, "%%"); break; default: buffer[0] = '%'; buffer[1] = format[i]; buffer[2] = '\0'; length = 2; break; } smart_str_appendl(&string, buffer, length); have_format_spec = 0; } else { if (format[i] == '%') { have_format_spec = 1; } else { smart_str_appendc(&string, format[i]); } } } smart_str_0(&string); return string.c; } /* }}} */ /* {{{ proto string date_interval_format(DateInterval object, string format) Formats the interval. */ PHP_FUNCTION(date_interval_format) { zval *object; php_interval_obj *diobj; char *format; int format_len; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, date_ce_interval, &format, &format_len) == FAILURE) { RETURN_FALSE; } diobj = (php_interval_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(diobj->initialized, DateInterval); RETURN_STRING(date_interval_format(format, format_len, diobj->diff), 0); } /* }}} */ static int date_period_initialize(timelib_time **st, timelib_time **et, timelib_rel_time **d, long *recurrences, /*const*/ char *format, int format_length TSRMLS_DC) { timelib_time *b = NULL, *e = NULL; timelib_rel_time *p = NULL; int r = 0; int retval = 0; struct timelib_error_container *errors; timelib_strtointerval(format, format_length, &b, &e, &p, &r, &errors); if (errors->error_count > 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown or bad format (%s)", format); retval = FAILURE; } else { *st = b; *et = e; *d = p; *recurrences = r; retval = SUCCESS; } timelib_error_container_dtor(errors); return retval; } /* {{{ proto DatePeriod::__construct(DateTime $start, DateInterval $interval, int recurrences|DateTime $end) Creates new DatePeriod object. */ PHP_METHOD(DatePeriod, __construct) { php_period_obj *dpobj; php_date_obj *dateobj; php_interval_obj *intobj; zval *start, *end = NULL, *interval; long recurrences = 0, options = 0; char *isostr = NULL; int isostr_len = 0; timelib_time *clone; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "OOl|l", &start, date_ce_date, &interval, date_ce_interval, &recurrences, &options) == FAILURE) { if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "OOO|l", &start, date_ce_date, &interval, date_ce_interval, &end, date_ce_date, &options) == FAILURE) { if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &isostr, &isostr_len, &options) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "This constructor accepts either (DateTime, DateInterval, int) OR (DateTime, DateInterval, DateTime) OR (string) as arguments."); zend_restore_error_handling(&error_handling TSRMLS_CC); return; } } } dpobj = zend_object_store_get_object(getThis() TSRMLS_CC); dpobj->current = NULL; if (isostr_len) { date_period_initialize(&(dpobj->start), &(dpobj->end), &(dpobj->interval), &recurrences, isostr, isostr_len TSRMLS_CC); if (dpobj->start == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The ISO interval '%s' did not contain a start date.", isostr); } if (dpobj->interval == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The ISO interval '%s' did not contain an interval.", isostr); } if (dpobj->end == NULL && recurrences == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The ISO interval '%s' did not contain an end date or a recurrence count.", isostr); } if (dpobj->start) { timelib_update_ts(dpobj->start, NULL); } if (dpobj->end) { timelib_update_ts(dpobj->end, NULL); } } else { /* init */ intobj = (php_interval_obj *) zend_object_store_get_object(interval TSRMLS_CC); /* start date */ dateobj = (php_date_obj *) zend_object_store_get_object(start TSRMLS_CC); clone = timelib_time_ctor(); memcpy(clone, dateobj->time, sizeof(timelib_time)); if (dateobj->time->tz_abbr) { clone->tz_abbr = strdup(dateobj->time->tz_abbr); } if (dateobj->time->tz_info) { clone->tz_info = dateobj->time->tz_info; } dpobj->start = clone; /* interval */ dpobj->interval = timelib_rel_time_clone(intobj->diff); /* end date */ if (end) { dateobj = (php_date_obj *) zend_object_store_get_object(end TSRMLS_CC); clone = timelib_time_clone(dateobj->time); dpobj->end = clone; } } /* options */ dpobj->include_start_date = !(options & PHP_DATE_PERIOD_EXCLUDE_START_DATE); /* recurrrences */ dpobj->recurrences = recurrences + dpobj->include_start_date; dpobj->initialized = 1; zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ static int check_id_allowed(char *id, long what) { if (what & PHP_DATE_TIMEZONE_GROUP_AFRICA && strncasecmp(id, "Africa/", 7) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_AMERICA && strncasecmp(id, "America/", 8) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_ANTARCTICA && strncasecmp(id, "Antarctica/", 11) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_ARCTIC && strncasecmp(id, "Arctic/", 7) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_ASIA && strncasecmp(id, "Asia/", 5) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_ATLANTIC && strncasecmp(id, "Atlantic/", 9) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_AUSTRALIA && strncasecmp(id, "Australia/", 10) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_EUROPE && strncasecmp(id, "Europe/", 7) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_INDIAN && strncasecmp(id, "Indian/", 7) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_PACIFIC && strncasecmp(id, "Pacific/", 8) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_UTC && strncasecmp(id, "UTC", 3) == 0) return 1; return 0; } /* {{{ proto array timezone_identifiers_list([long what[, string country]]) Returns numerically index array with all timezone identifiers. */ PHP_FUNCTION(timezone_identifiers_list) { const timelib_tzdb *tzdb; const timelib_tzdb_index_entry *table; int i, item_count; long what = PHP_DATE_TIMEZONE_GROUP_ALL; char *option = NULL; int option_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|ls", &what, &option, &option_len) == FAILURE) { RETURN_FALSE; } /* Extra validation */ if (what == PHP_DATE_TIMEZONE_PER_COUNTRY && option_len != 2) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "A two-letter ISO 3166-1 compatible country code is expected"); RETURN_FALSE; } tzdb = DATE_TIMEZONEDB; item_count = tzdb->index_size; table = tzdb->index; array_init(return_value); for (i = 0; i < item_count; ++i) { if (what == PHP_DATE_TIMEZONE_PER_COUNTRY) { if (tzdb->data[table[i].pos + 5] == option[0] && tzdb->data[table[i].pos + 6] == option[1]) { add_next_index_string(return_value, table[i].id, 1); } } else if (what == PHP_DATE_TIMEZONE_GROUP_ALL_W_BC || (check_id_allowed(table[i].id, what) && (tzdb->data[table[i].pos + 4] == '\1'))) { add_next_index_string(return_value, table[i].id, 1); } }; } /* }}} */ /* {{{ proto array timezone_version_get() Returns the Olson database version number. */ PHP_FUNCTION(timezone_version_get) { const timelib_tzdb *tzdb; tzdb = DATE_TIMEZONEDB; RETURN_STRING(tzdb->version, 1); } /* }}} */ /* {{{ proto array timezone_abbreviations_list() Returns associative array containing dst, offset and the timezone name */ PHP_FUNCTION(timezone_abbreviations_list) { const timelib_tz_lookup_table *table, *entry; zval *element, **abbr_array_pp, *abbr_array; table = timelib_timezone_abbreviations_list(); array_init(return_value); entry = table; do { MAKE_STD_ZVAL(element); array_init(element); add_assoc_bool(element, "dst", entry->type); add_assoc_long(element, "offset", entry->gmtoffset); if (entry->full_tz_name) { add_assoc_string(element, "timezone_id", entry->full_tz_name, 1); } else { add_assoc_null(element, "timezone_id"); } if (zend_hash_find(HASH_OF(return_value), entry->name, strlen(entry->name) + 1, (void **) &abbr_array_pp) == FAILURE) { MAKE_STD_ZVAL(abbr_array); array_init(abbr_array); add_assoc_zval(return_value, entry->name, abbr_array); } else { abbr_array = *abbr_array_pp; } add_next_index_zval(abbr_array, element); entry++; } while (entry->name); } /* }}} */ /* {{{ proto bool date_default_timezone_set(string timezone_identifier) Sets the default timezone used by all date/time functions in a script */ PHP_FUNCTION(date_default_timezone_set) { char *zone; int zone_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &zone, &zone_len) == FAILURE) { RETURN_FALSE; } if (!timelib_timezone_id_is_valid(zone, DATE_TIMEZONEDB)) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Timezone ID '%s' is invalid", zone); RETURN_FALSE; } if (DATEG(timezone)) { efree(DATEG(timezone)); DATEG(timezone) = NULL; } DATEG(timezone) = estrndup(zone, zone_len); RETURN_TRUE; } /* }}} */ /* {{{ proto string date_default_timezone_get() Gets the default timezone used by all date/time functions in a script */ PHP_FUNCTION(date_default_timezone_get) { timelib_tzinfo *default_tz; default_tz = get_timezone_info(TSRMLS_C); RETVAL_STRING(default_tz->name, 1); } /* }}} */ /* {{{ php_do_date_sunrise_sunset * Common for date_sunrise() and date_sunset() functions */ static void php_do_date_sunrise_sunset(INTERNAL_FUNCTION_PARAMETERS, int calc_sunset) { double latitude = 0.0, longitude = 0.0, zenith = 0.0, gmt_offset = 0, altitude; double h_rise, h_set, N; timelib_sll rise, set, transit; long time, retformat = 0; int rs; timelib_time *t; timelib_tzinfo *tzi; char *retstr; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|ldddd", &time, &retformat, &latitude, &longitude, &zenith, &gmt_offset) == FAILURE) { RETURN_FALSE; } switch (ZEND_NUM_ARGS()) { case 1: retformat = SUNFUNCS_RET_STRING; case 2: latitude = INI_FLT("date.default_latitude"); case 3: longitude = INI_FLT("date.default_longitude"); case 4: if (calc_sunset) { zenith = INI_FLT("date.sunset_zenith"); } else { zenith = INI_FLT("date.sunrise_zenith"); } case 5: case 6: break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "invalid format"); RETURN_FALSE; break; } if (retformat != SUNFUNCS_RET_TIMESTAMP && retformat != SUNFUNCS_RET_STRING && retformat != SUNFUNCS_RET_DOUBLE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Wrong return format given, pick one of SUNFUNCS_RET_TIMESTAMP, SUNFUNCS_RET_STRING or SUNFUNCS_RET_DOUBLE"); RETURN_FALSE; } altitude = 90 - zenith; /* Initialize time struct */ t = timelib_time_ctor(); tzi = get_timezone_info(TSRMLS_C); t->tz_info = tzi; t->zone_type = TIMELIB_ZONETYPE_ID; if (ZEND_NUM_ARGS() <= 5) { gmt_offset = timelib_get_current_offset(t) / 3600; } timelib_unixtime2local(t, time); rs = timelib_astro_rise_set_altitude(t, longitude, latitude, altitude, 1, &h_rise, &h_set, &rise, &set, &transit); timelib_time_dtor(t); if (rs != 0) { RETURN_FALSE; } if (retformat == SUNFUNCS_RET_TIMESTAMP) { RETURN_LONG(calc_sunset ? set : rise); } N = (calc_sunset ? h_set : h_rise) + gmt_offset; if (N > 24 || N < 0) { N -= floor(N / 24) * 24; } switch (retformat) { case SUNFUNCS_RET_STRING: spprintf(&retstr, 0, "%02d:%02d", (int) N, (int) (60 * (N - (int) N))); RETURN_STRINGL(retstr, 5, 0); break; case SUNFUNCS_RET_DOUBLE: RETURN_DOUBLE(N); break; } } /* }}} */ /* {{{ proto mixed date_sunrise(mixed time [, int format [, float latitude [, float longitude [, float zenith [, float gmt_offset]]]]]) Returns time of sunrise for a given day and location */ PHP_FUNCTION(date_sunrise) { php_do_date_sunrise_sunset(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto mixed date_sunset(mixed time [, int format [, float latitude [, float longitude [, float zenith [, float gmt_offset]]]]]) Returns time of sunset for a given day and location */ PHP_FUNCTION(date_sunset) { php_do_date_sunrise_sunset(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto array date_sun_info(long time, float latitude, float longitude) Returns an array with information about sun set/rise and twilight begin/end */ PHP_FUNCTION(date_sun_info) { long time; double latitude, longitude; timelib_time *t, *t2; timelib_tzinfo *tzi; int rs; timelib_sll rise, set, transit; int dummy; double ddummy; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ldd", &time, &latitude, &longitude) == FAILURE) { RETURN_FALSE; } /* Initialize time struct */ t = timelib_time_ctor(); tzi = get_timezone_info(TSRMLS_C); t->tz_info = tzi; t->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(t, time); /* Setup */ t2 = timelib_time_ctor(); array_init(return_value); /* Get sun up/down and transit */ rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -35.0/60, 1, &ddummy, &ddummy, &rise, &set, &transit); switch (rs) { case -1: /* always below */ add_assoc_bool(return_value, "sunrise", 0); add_assoc_bool(return_value, "sunset", 0); break; case 1: /* always above */ add_assoc_bool(return_value, "sunrise", 1); add_assoc_bool(return_value, "sunset", 1); break; default: t2->sse = rise; add_assoc_long(return_value, "sunrise", timelib_date_to_int(t2, &dummy)); t2->sse = set; add_assoc_long(return_value, "sunset", timelib_date_to_int(t2, &dummy)); } t2->sse = transit; add_assoc_long(return_value, "transit", timelib_date_to_int(t2, &dummy)); /* Get civil twilight */ rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -6.0, 0, &ddummy, &ddummy, &rise, &set, &transit); switch (rs) { case -1: /* always below */ add_assoc_bool(return_value, "civil_twilight_begin", 0); add_assoc_bool(return_value, "civil_twilight_end", 0); break; case 1: /* always above */ add_assoc_bool(return_value, "civil_twilight_begin", 1); add_assoc_bool(return_value, "civil_twilight_end", 1); break; default: t2->sse = rise; add_assoc_long(return_value, "civil_twilight_begin", timelib_date_to_int(t2, &dummy)); t2->sse = set; add_assoc_long(return_value, "civil_twilight_end", timelib_date_to_int(t2, &dummy)); } /* Get nautical twilight */ rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -12.0, 0, &ddummy, &ddummy, &rise, &set, &transit); switch (rs) { case -1: /* always below */ add_assoc_bool(return_value, "nautical_twilight_begin", 0); add_assoc_bool(return_value, "nautical_twilight_end", 0); break; case 1: /* always above */ add_assoc_bool(return_value, "nautical_twilight_begin", 1); add_assoc_bool(return_value, "nautical_twilight_end", 1); break; default: t2->sse = rise; add_assoc_long(return_value, "nautical_twilight_begin", timelib_date_to_int(t2, &dummy)); t2->sse = set; add_assoc_long(return_value, "nautical_twilight_end", timelib_date_to_int(t2, &dummy)); } /* Get astronomical twilight */ rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -18.0, 0, &ddummy, &ddummy, &rise, &set, &transit); switch (rs) { case -1: /* always below */ add_assoc_bool(return_value, "astronomical_twilight_begin", 0); add_assoc_bool(return_value, "astronomical_twilight_end", 0); break; case 1: /* always above */ add_assoc_bool(return_value, "astronomical_twilight_begin", 1); add_assoc_bool(return_value, "astronomical_twilight_end", 1); break; default: t2->sse = rise; add_assoc_long(return_value, "astronomical_twilight_begin", timelib_date_to_int(t2, &dummy)); t2->sse = set; add_assoc_long(return_value, "astronomical_twilight_end", timelib_date_to_int(t2, &dummy)); } timelib_time_dtor(t); timelib_time_dtor(t2); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: fdm=marker * vim: noet sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-01-30-5bb0a44e06-1e91069eb4.c
manybugs_data_20
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2012 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | Rasmus Lerdorf <[email protected]> | | Andrei Zmievski <[email protected]> | | Stig Venaas <[email protected]> | | Jason Greene <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "php.h" #include "php_ini.h" #include <stdarg.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <stdio.h> #if HAVE_STRING_H #include <string.h> #else #include <strings.h> #endif #ifdef PHP_WIN32 #include "win32/unistd.h" #endif #include "zend_globals.h" #include "zend_interfaces.h" #include "php_globals.h" #include "php_array.h" #include "basic_functions.h" #include "php_string.h" #include "php_rand.h" #include "php_smart_str.h" #ifdef HAVE_SPL #include "ext/spl/spl_array.h" #endif /* {{{ defines */ #define EXTR_OVERWRITE 0 #define EXTR_SKIP 1 #define EXTR_PREFIX_SAME 2 #define EXTR_PREFIX_ALL 3 #define EXTR_PREFIX_INVALID 4 #define EXTR_PREFIX_IF_EXISTS 5 #define EXTR_IF_EXISTS 6 #define EXTR_REFS 0x100 #define CASE_LOWER 0 #define CASE_UPPER 1 #define COUNT_NORMAL 0 #define COUNT_RECURSIVE 1 #define DIFF_NORMAL 1 #define DIFF_KEY 2 #define DIFF_ASSOC 6 #define DIFF_COMP_DATA_NONE -1 #define DIFF_COMP_DATA_INTERNAL 0 #define DIFF_COMP_DATA_USER 1 #define DIFF_COMP_KEY_INTERNAL 0 #define DIFF_COMP_KEY_USER 1 #define INTERSECT_NORMAL 1 #define INTERSECT_KEY 2 #define INTERSECT_ASSOC 6 #define INTERSECT_COMP_DATA_NONE -1 #define INTERSECT_COMP_DATA_INTERNAL 0 #define INTERSECT_COMP_DATA_USER 1 #define INTERSECT_COMP_KEY_INTERNAL 0 #define INTERSECT_COMP_KEY_USER 1 #define DOUBLE_DRIFT_FIX 0.000000000000001 /* }}} */ ZEND_DECLARE_MODULE_GLOBALS(array) /* {{{ php_array_init_globals */ static void php_array_init_globals(zend_array_globals *array_globals) { memset(array_globals, 0, sizeof(zend_array_globals)); } /* }}} */ PHP_MINIT_FUNCTION(array) /* {{{ */ { ZEND_INIT_MODULE_GLOBALS(array, php_array_init_globals, NULL); REGISTER_LONG_CONSTANT("EXTR_OVERWRITE", EXTR_OVERWRITE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_SKIP", EXTR_SKIP, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_PREFIX_SAME", EXTR_PREFIX_SAME, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_PREFIX_ALL", EXTR_PREFIX_ALL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_PREFIX_INVALID", EXTR_PREFIX_INVALID, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_PREFIX_IF_EXISTS", EXTR_PREFIX_IF_EXISTS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_IF_EXISTS", EXTR_IF_EXISTS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_REFS", EXTR_REFS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_ASC", PHP_SORT_ASC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_DESC", PHP_SORT_DESC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_REGULAR", PHP_SORT_REGULAR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_NUMERIC", PHP_SORT_NUMERIC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_STRING", PHP_SORT_STRING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_LOCALE_STRING", PHP_SORT_LOCALE_STRING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_NATURAL", PHP_SORT_NATURAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_FLAG_CASE", PHP_SORT_FLAG_CASE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("CASE_LOWER", CASE_LOWER, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("CASE_UPPER", CASE_UPPER, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("COUNT_NORMAL", COUNT_NORMAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("COUNT_RECURSIVE", COUNT_RECURSIVE, CONST_CS | CONST_PERSISTENT); return SUCCESS; } /* }}} */ PHP_MSHUTDOWN_FUNCTION(array) /* {{{ */ { #ifdef ZTS ts_free_id(array_globals_id); #endif return SUCCESS; } /* }}} */ static void php_set_compare_func(int sort_type TSRMLS_DC) /* {{{ */ { switch (sort_type & ~PHP_SORT_FLAG_CASE) { case PHP_SORT_NUMERIC: ARRAYG(compare_func) = numeric_compare_function; break; case PHP_SORT_STRING: ARRAYG(compare_func) = sort_type & PHP_SORT_FLAG_CASE ? string_case_compare_function : string_compare_function; break; case PHP_SORT_NATURAL: ARRAYG(compare_func) = sort_type & PHP_SORT_FLAG_CASE ? string_natural_case_compare_function : string_natural_compare_function; break; #if HAVE_STRCOLL case PHP_SORT_LOCALE_STRING: ARRAYG(compare_func) = string_locale_compare_function; break; #endif case PHP_SORT_REGULAR: default: ARRAYG(compare_func) = compare_function; break; } } /* }}} */ static int php_array_key_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { Bucket *f; Bucket *s; zval result; zval first; zval second; f = *((Bucket **) a); s = *((Bucket **) b); if (f->nKeyLength == 0) { Z_TYPE(first) = IS_LONG; Z_LVAL(first) = f->h; } else { Z_TYPE(first) = IS_STRING; Z_STRVAL(first) = (char*)f->arKey; Z_STRLEN(first) = f->nKeyLength - 1; } if (s->nKeyLength == 0) { Z_TYPE(second) = IS_LONG; Z_LVAL(second) = s->h; } else { Z_TYPE(second) = IS_STRING; Z_STRVAL(second) = (char*)s->arKey; Z_STRLEN(second) = s->nKeyLength - 1; } if (ARRAYG(compare_func)(&result, &first, &second TSRMLS_CC) == FAILURE) { return 0; } if (Z_TYPE(result) == IS_DOUBLE) { if (Z_DVAL(result) < 0) { return -1; } else if (Z_DVAL(result) > 0) { return 1; } else { return 0; } } convert_to_long(&result); if (Z_LVAL(result) < 0) { return -1; } else if (Z_LVAL(result) > 0) { return 1; } return 0; } /* }}} */ static int php_array_reverse_key_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { return php_array_key_compare(a, b TSRMLS_CC) * -1; } /* }}} */ /* {{{ proto bool krsort(array &array_arg [, int sort_flags]) Sort an array by key value in reverse order */ PHP_FUNCTION(krsort) { zval *array; long sort_type = PHP_SORT_REGULAR; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { RETURN_FALSE; } php_set_compare_func(sort_type TSRMLS_CC); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_reverse_key_compare, 0 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool ksort(array &array_arg [, int sort_flags]) Sort an array by key */ PHP_FUNCTION(ksort) { zval *array; long sort_type = PHP_SORT_REGULAR; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { RETURN_FALSE; } php_set_compare_func(sort_type TSRMLS_CC); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_key_compare, 0 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ static int php_count_recursive(zval *array, long mode TSRMLS_DC) /* {{{ */ { long cnt = 0; zval **element; if (Z_TYPE_P(array) == IS_ARRAY) { if (Z_ARRVAL_P(array)->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); return 0; } cnt = zend_hash_num_elements(Z_ARRVAL_P(array)); if (mode == COUNT_RECURSIVE) { HashPosition pos; for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(array), &pos); zend_hash_get_current_data_ex(Z_ARRVAL_P(array), (void **) &element, &pos) == SUCCESS; zend_hash_move_forward_ex(Z_ARRVAL_P(array), &pos) ) { Z_ARRVAL_P(array)->nApplyCount++; cnt += php_count_recursive(*element, COUNT_RECURSIVE TSRMLS_CC); Z_ARRVAL_P(array)->nApplyCount--; } } } return cnt; } /* }}} */ /* {{{ proto int count(mixed var [, int mode]) Count the number of elements in a variable (usually an array) */ PHP_FUNCTION(count) { zval *array; long mode = COUNT_NORMAL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|l", &array, &mode) == FAILURE) { return; } switch (Z_TYPE_P(array)) { case IS_NULL: RETURN_LONG(0); break; case IS_ARRAY: RETURN_LONG (php_count_recursive (array, mode TSRMLS_CC)); break; case IS_OBJECT: { #ifdef HAVE_SPL zval *retval; #endif /* first, we check if the handler is defined */ if (Z_OBJ_HT_P(array)->count_elements) { RETVAL_LONG(1); if (SUCCESS == Z_OBJ_HT(*array)->count_elements(array, &Z_LVAL_P(return_value) TSRMLS_CC)) { return; } } #ifdef HAVE_SPL /* if not and the object implements Countable we call its count() method */ if (Z_OBJ_HT_P(array)->get_class_entry && instanceof_function(Z_OBJCE_P(array), spl_ce_Countable TSRMLS_CC)) { zend_call_method_with_0_params(&array, NULL, NULL, "count", &retval); if (retval) { convert_to_long_ex(&retval); RETVAL_LONG(Z_LVAL_P(retval)); zval_ptr_dtor(&retval); } return; } #endif } default: RETURN_LONG(1); break; } } /* }}} */ /* Numbers are always smaller than strings int this function as it * anyway doesn't make much sense to compare two different data types. * This keeps it consistant and simple. * * This is not correct any more, depends on what compare_func is set to. */ static int php_array_data_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { Bucket *f; Bucket *s; zval result; zval *first; zval *second; f = *((Bucket **) a); s = *((Bucket **) b); first = *((zval **) f->pData); second = *((zval **) s->pData); if (ARRAYG(compare_func)(&result, first, second TSRMLS_CC) == FAILURE) { return 0; } if (Z_TYPE(result) == IS_DOUBLE) { if (Z_DVAL(result) < 0) { return -1; } else if (Z_DVAL(result) > 0) { return 1; } else { return 0; } } convert_to_long(&result); if (Z_LVAL(result) < 0) { return -1; } else if (Z_LVAL(result) > 0) { return 1; } return 0; } /* }}} */ static int php_array_reverse_data_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { return php_array_data_compare(a, b TSRMLS_CC) * -1; } /* }}} */ static int php_array_natural_general_compare(const void *a, const void *b, int fold_case) /* {{{ */ { Bucket *f, *s; zval *fval, *sval; zval first, second; int result; f = *((Bucket **) a); s = *((Bucket **) b); fval = *((zval **) f->pData); sval = *((zval **) s->pData); first = *fval; second = *sval; if (Z_TYPE_P(fval) != IS_STRING) { zval_copy_ctor(&first); convert_to_string(&first); } if (Z_TYPE_P(sval) != IS_STRING) { zval_copy_ctor(&second); convert_to_string(&second); } result = strnatcmp_ex(Z_STRVAL(first), Z_STRLEN(first), Z_STRVAL(second), Z_STRLEN(second), fold_case); if (Z_TYPE_P(fval) != IS_STRING) { zval_dtor(&first); } if (Z_TYPE_P(sval) != IS_STRING) { zval_dtor(&second); } return result; } /* }}} */ static int php_array_natural_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { return php_array_natural_general_compare(a, b, 0); } /* }}} */ static int php_array_natural_case_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { return php_array_natural_general_compare(a, b, 1); } /* }}} */ static void php_natsort(INTERNAL_FUNCTION_PARAMETERS, int fold_case) /* {{{ */ { zval *array; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) { return; } if (fold_case) { if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_natural_case_compare, 0 TSRMLS_CC) == FAILURE) { return; } } else { if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_natural_compare, 0 TSRMLS_CC) == FAILURE) { return; } } RETURN_TRUE; } /* }}} */ /* {{{ proto void natsort(array &array_arg) Sort an array using natural sort */ PHP_FUNCTION(natsort) { php_natsort(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto void natcasesort(array &array_arg) Sort an array using case-insensitive natural sort */ PHP_FUNCTION(natcasesort) { php_natsort(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto bool asort(array &array_arg [, int sort_flags]) Sort an array and maintain index association */ PHP_FUNCTION(asort) { zval *array; long sort_type = PHP_SORT_REGULAR; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { RETURN_FALSE; } php_set_compare_func(sort_type TSRMLS_CC); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_data_compare, 0 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool arsort(array &array_arg [, int sort_flags]) Sort an array in reverse order and maintain index association */ PHP_FUNCTION(arsort) { zval *array; long sort_type = PHP_SORT_REGULAR; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { RETURN_FALSE; } php_set_compare_func(sort_type TSRMLS_CC); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_reverse_data_compare, 0 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool sort(array &array_arg [, int sort_flags]) Sort an array */ PHP_FUNCTION(sort) { zval *array; long sort_type = PHP_SORT_REGULAR; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { RETURN_FALSE; } php_set_compare_func(sort_type TSRMLS_CC); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_data_compare, 1 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool rsort(array &array_arg [, int sort_flags]) Sort an array in reverse order */ PHP_FUNCTION(rsort) { zval *array; long sort_type = PHP_SORT_REGULAR; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { RETURN_FALSE; } php_set_compare_func(sort_type TSRMLS_CC); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_reverse_data_compare, 1 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ static int php_array_user_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { Bucket *f; Bucket *s; zval **args[2]; zval *retval_ptr = NULL; f = *((Bucket **) a); s = *((Bucket **) b); args[0] = (zval **) f->pData; args[1] = (zval **) s->pData; BG(user_compare_fci).param_count = 2; BG(user_compare_fci).params = args; BG(user_compare_fci).retval_ptr_ptr = &retval_ptr; BG(user_compare_fci).no_separation = 0; if (zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache) TSRMLS_CC) == SUCCESS && retval_ptr) { long retval; convert_to_long_ex(&retval_ptr); retval = Z_LVAL_P(retval_ptr); zval_ptr_dtor(&retval_ptr); return retval < 0 ? -1 : retval > 0 ? 1 : 0; } else { return 0; } } /* }}} */ /* check if comparison function is valid */ #define PHP_ARRAY_CMP_FUNC_CHECK(func_name) \ if (!zend_is_callable(*func_name, 0, NULL TSRMLS_CC)) { \ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid comparison function"); \ BG(user_compare_fci) = old_user_compare_fci; \ BG(user_compare_fci_cache) = old_user_compare_fci_cache; \ RETURN_FALSE; \ } \ /* Clear FCI cache otherwise : for example the same or other array with * (partly) the same key values has been sorted with uasort() or * other sorting function the comparison is cached, however the name * of the function for comparison is not respected. see bug #28739 AND #33295 * * Following defines will assist in backup / restore values. */ #define PHP_ARRAY_CMP_FUNC_VARS \ zend_fcall_info old_user_compare_fci; \ zend_fcall_info_cache old_user_compare_fci_cache \ #define PHP_ARRAY_CMP_FUNC_BACKUP() \ old_user_compare_fci = BG(user_compare_fci); \ old_user_compare_fci_cache = BG(user_compare_fci_cache); \ BG(user_compare_fci_cache) = empty_fcall_info_cache; \ #define PHP_ARRAY_CMP_FUNC_RESTORE() \ BG(user_compare_fci) = old_user_compare_fci; \ BG(user_compare_fci_cache) = old_user_compare_fci_cache; \ /* {{{ proto bool usort(array array_arg, string cmp_function) Sort an array by values using a user-defined comparison function */ PHP_FUNCTION(usort) { zval *array; unsigned int refcount; PHP_ARRAY_CMP_FUNC_VARS; PHP_ARRAY_CMP_FUNC_BACKUP(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "af", &array, &BG(user_compare_fci), &BG(user_compare_fci_cache)) == FAILURE) { PHP_ARRAY_CMP_FUNC_RESTORE(); return; } /* Clear the is_ref flag, so the attemts to modify the array in user * comparison function will create a copy of array and won't affect the * original array. The fact of modification is detected using refcount * comparison. The result of sorting in such case is undefined and the * function returns FALSE. */ Z_UNSET_ISREF_P(array); refcount = Z_REFCOUNT_P(array); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_user_compare, 1 TSRMLS_CC) == FAILURE) { RETVAL_FALSE; } else { if (refcount > Z_REFCOUNT_P(array)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array was modified by the user comparison function"); RETVAL_FALSE; } else { RETVAL_TRUE; } } if (Z_REFCOUNT_P(array) > 1) { Z_SET_ISREF_P(array); } PHP_ARRAY_CMP_FUNC_RESTORE(); } /* }}} */ /* {{{ proto bool uasort(array array_arg, string cmp_function) Sort an array with a user-defined comparison function and maintain index association */ PHP_FUNCTION(uasort) { zval *array; unsigned int refcount; PHP_ARRAY_CMP_FUNC_VARS; PHP_ARRAY_CMP_FUNC_BACKUP(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "af", &array, &BG(user_compare_fci), &BG(user_compare_fci_cache)) == FAILURE) { PHP_ARRAY_CMP_FUNC_RESTORE(); return; } /* Clear the is_ref flag, so the attemts to modify the array in user * comaprison function will create a copy of array and won't affect the * original array. The fact of modification is detected using refcount * comparison. The result of sorting in such case is undefined and the * function returns FALSE. */ Z_UNSET_ISREF_P(array); refcount = Z_REFCOUNT_P(array); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_user_compare, 0 TSRMLS_CC) == FAILURE) { RETVAL_FALSE; } else { if (refcount > Z_REFCOUNT_P(array)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array was modified by the user comparison function"); RETVAL_FALSE; } else { RETVAL_TRUE; } } if (Z_REFCOUNT_P(array) > 1) { Z_SET_ISREF_P(array); } PHP_ARRAY_CMP_FUNC_RESTORE(); } /* }}} */ static int php_array_user_key_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { Bucket *f; Bucket *s; zval *key1, *key2; zval **args[2]; zval *retval_ptr = NULL; long result; ALLOC_INIT_ZVAL(key1); ALLOC_INIT_ZVAL(key2); args[0] = &key1; args[1] = &key2; f = *((Bucket **) a); s = *((Bucket **) b); if (f->nKeyLength == 0) { Z_LVAL_P(key1) = f->h; Z_TYPE_P(key1) = IS_LONG; } else { Z_STRVAL_P(key1) = estrndup(f->arKey, f->nKeyLength - 1); Z_STRLEN_P(key1) = f->nKeyLength - 1; Z_TYPE_P(key1) = IS_STRING; } if (s->nKeyLength == 0) { Z_LVAL_P(key2) = s->h; Z_TYPE_P(key2) = IS_LONG; } else { Z_STRVAL_P(key2) = estrndup(s->arKey, s->nKeyLength - 1); Z_STRLEN_P(key2) = s->nKeyLength - 1; Z_TYPE_P(key2) = IS_STRING; } BG(user_compare_fci).param_count = 2; BG(user_compare_fci).params = args; BG(user_compare_fci).retval_ptr_ptr = &retval_ptr; BG(user_compare_fci).no_separation = 0; if (zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache) TSRMLS_CC) == SUCCESS && retval_ptr) { convert_to_long_ex(&retval_ptr); result = Z_LVAL_P(retval_ptr); zval_ptr_dtor(&retval_ptr); } else { result = 0; } zval_ptr_dtor(&key1); zval_ptr_dtor(&key2); return result; } /* }}} */ /* {{{ proto bool uksort(array array_arg, string cmp_function) Sort an array by keys using a user-defined comparison function */ PHP_FUNCTION(uksort) { zval *array; unsigned int refcount; PHP_ARRAY_CMP_FUNC_VARS; PHP_ARRAY_CMP_FUNC_BACKUP(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "af", &array, &BG(user_compare_fci), &BG(user_compare_fci_cache)) == FAILURE) { PHP_ARRAY_CMP_FUNC_RESTORE(); return; } /* Clear the is_ref flag, so the attemts to modify the array in user * comaprison function will create a copy of array and won't affect the * original array. The fact of modification is detected using refcount * comparison. The result of sorting in such case is undefined and the * function returns FALSE. */ Z_UNSET_ISREF_P(array); refcount = Z_REFCOUNT_P(array); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_user_key_compare, 0 TSRMLS_CC) == FAILURE) { RETVAL_FALSE; } else { if (refcount > Z_REFCOUNT_P(array)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array was modified by the user comparison function"); RETVAL_FALSE; } else { RETVAL_TRUE; } } if (Z_REFCOUNT_P(array) > 1) { Z_SET_ISREF_P(array); } PHP_ARRAY_CMP_FUNC_RESTORE(); } /* }}} */ /* {{{ proto mixed end(array array_arg) Advances array argument's internal pointer to the last element and return it */ PHP_FUNCTION(end) { HashTable *array; zval **entry; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "H", &array) == FAILURE) { return; } zend_hash_internal_pointer_end(array); if (return_value_used) { if (zend_hash_get_current_data(array, (void **) &entry) == FAILURE) { RETURN_FALSE; } RETURN_ZVAL(*entry, 1, 0); } } /* }}} */ /* {{{ proto mixed prev(array array_arg) Move array argument's internal pointer to the previous element and return it */ PHP_FUNCTION(prev) { HashTable *array; zval **entry; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "H", &array) == FAILURE) { return; } zend_hash_move_backwards(array); if (return_value_used) { if (zend_hash_get_current_data(array, (void **) &entry) == FAILURE) { RETURN_FALSE; } RETURN_ZVAL(*entry, 1, 0); } } /* }}} */ /* {{{ proto mixed next(array array_arg) Move array argument's internal pointer to the next element and return it */ PHP_FUNCTION(next) { HashTable *array; zval **entry; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "H", &array) == FAILURE) { return; } zend_hash_move_forward(array); if (return_value_used) { if (zend_hash_get_current_data(array, (void **) &entry) == FAILURE) { RETURN_FALSE; } RETURN_ZVAL(*entry, 1, 0); } } /* }}} */ /* {{{ proto mixed reset(array array_arg) Set array argument's internal pointer to the first element and return it */ PHP_FUNCTION(reset) { HashTable *array; zval **entry; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "H", &array) == FAILURE) { return; } zend_hash_internal_pointer_reset(array); if (return_value_used) { if (zend_hash_get_current_data(array, (void **) &entry) == FAILURE) { RETURN_FALSE; } RETURN_ZVAL(*entry, 1, 0); } } /* }}} */ /* {{{ proto mixed current(array array_arg) Return the element currently pointed to by the internal array pointer */ PHP_FUNCTION(current) { HashTable *array; zval **entry; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "H", &array) == FAILURE) { return; } if (zend_hash_get_current_data(array, (void **) &entry) == FAILURE) { RETURN_FALSE; } RETURN_ZVAL(*entry, 1, 0); } /* }}} */ /* {{{ proto mixed key(array array_arg) Return the key of the element currently pointed to by the internal array pointer */ PHP_FUNCTION(key) { HashTable *array; char *string_key; uint string_length; ulong num_key; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "H", &array) == FAILURE) { return; } switch (zend_hash_get_current_key_ex(array, &string_key, &string_length, &num_key, 0, NULL)) { case HASH_KEY_IS_STRING: RETVAL_STRINGL(string_key, string_length - 1, 1); break; case HASH_KEY_IS_LONG: RETVAL_LONG(num_key); break; case HASH_KEY_NON_EXISTANT: return; } } /* }}} */ /* {{{ proto mixed min(mixed arg1 [, mixed arg2 [, mixed ...]]) Return the lowest value in an array or a series of arguments */ PHP_FUNCTION(min) { int argc; zval ***args = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &argc) == FAILURE) { return; } php_set_compare_func(PHP_SORT_REGULAR TSRMLS_CC); /* mixed min ( array $values ) */ if (argc == 1) { zval **result; if (Z_TYPE_PP(args[0]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "When only one parameter is given, it must be an array"); RETVAL_NULL(); } else { if (zend_hash_minmax(Z_ARRVAL_PP(args[0]), php_array_data_compare, 0, (void **) &result TSRMLS_CC) == SUCCESS) { RETVAL_ZVAL(*result, 1, 0); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array must contain at least one element"); RETVAL_FALSE; } } } else { /* mixed min ( mixed $value1 , mixed $value2 [, mixed $value3... ] ) */ zval **min, result; int i; min = args[0]; for (i = 1; i < argc; i++) { is_smaller_function(&result, *args[i], *min TSRMLS_CC); if (Z_LVAL(result) == 1) { min = args[i]; } } RETVAL_ZVAL(*min, 1, 0); } if (args) { efree(args); } } /* }}} */ /* {{{ proto mixed max(mixed arg1 [, mixed arg2 [, mixed ...]]) Return the highest value in an array or a series of arguments */ PHP_FUNCTION(max) { zval ***args = NULL; int argc; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &argc) == FAILURE) { return; } php_set_compare_func(PHP_SORT_REGULAR TSRMLS_CC); /* mixed max ( array $values ) */ if (argc == 1) { zval **result; if (Z_TYPE_PP(args[0]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "When only one parameter is given, it must be an array"); RETVAL_NULL(); } else { if (zend_hash_minmax(Z_ARRVAL_PP(args[0]), php_array_data_compare, 1, (void **) &result TSRMLS_CC) == SUCCESS) { RETVAL_ZVAL(*result, 1, 0); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array must contain at least one element"); RETVAL_FALSE; } } } else { /* mixed max ( mixed $value1 , mixed $value2 [, mixed $value3... ] ) */ zval **max, result; int i; max = args[0]; for (i = 1; i < argc; i++) { is_smaller_or_equal_function(&result, *args[i], *max TSRMLS_CC); if (Z_LVAL(result) == 0) { max = args[i]; } } RETVAL_ZVAL(*max, 1, 0); } if (args) { efree(args); } } /* }}} */ static int php_array_walk(HashTable *target_hash, zval **userdata, int recursive TSRMLS_DC) /* {{{ */ { zval **args[3], /* Arguments to userland function */ *retval_ptr, /* Return value - unused */ *key=NULL; /* Entry key */ char *string_key; uint string_key_len; ulong num_key; HashPosition pos; /* Set up known arguments */ args[1] = &key; args[2] = userdata; if (userdata) { Z_ADDREF_PP(userdata); } zend_hash_internal_pointer_reset_ex(target_hash, &pos); BG(array_walk_fci).retval_ptr_ptr = &retval_ptr; BG(array_walk_fci).param_count = userdata ? 3 : 2; BG(array_walk_fci).params = args; BG(array_walk_fci).no_separation = 0; /* Iterate through hash */ while (!EG(exception) && zend_hash_get_current_data_ex(target_hash, (void **)&args[0], &pos) == SUCCESS) { if (recursive && Z_TYPE_PP(args[0]) == IS_ARRAY) { HashTable *thash; zend_fcall_info orig_array_walk_fci; zend_fcall_info_cache orig_array_walk_fci_cache; SEPARATE_ZVAL_IF_NOT_REF(args[0]); thash = Z_ARRVAL_PP(args[0]); if (thash->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); if (userdata) { zval_ptr_dtor(userdata); } return 0; } /* backup the fcall info and cache */ orig_array_walk_fci = BG(array_walk_fci); orig_array_walk_fci_cache = BG(array_walk_fci_cache); thash->nApplyCount++; php_array_walk(thash, userdata, recursive TSRMLS_CC); thash->nApplyCount--; /* restore the fcall info and cache */ BG(array_walk_fci) = orig_array_walk_fci; BG(array_walk_fci_cache) = orig_array_walk_fci_cache; } else { /* Allocate space for key */ MAKE_STD_ZVAL(key); /* Set up the key */ switch (zend_hash_get_current_key_ex(target_hash, &string_key, &string_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_LONG: Z_TYPE_P(key) = IS_LONG; Z_LVAL_P(key) = num_key; break; case HASH_KEY_IS_STRING: ZVAL_STRINGL(key, string_key, string_key_len - 1, 1); break; } /* Call the userland function */ if (zend_call_function(&BG(array_walk_fci), &BG(array_walk_fci_cache) TSRMLS_CC) == SUCCESS) { if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } } else { if (key) { zval_ptr_dtor(&key); key = NULL; } break; } } if (key) { zval_ptr_dtor(&key); key = NULL; } zend_hash_move_forward_ex(target_hash, &pos); } if (userdata) { zval_ptr_dtor(userdata); } return 0; } /* }}} */ /* {{{ proto bool array_walk(array input, string funcname [, mixed userdata]) Apply a user function to every member of an array */ PHP_FUNCTION(array_walk) { HashTable *array; zval *userdata = NULL; zend_fcall_info orig_array_walk_fci; zend_fcall_info_cache orig_array_walk_fci_cache; orig_array_walk_fci = BG(array_walk_fci); orig_array_walk_fci_cache = BG(array_walk_fci_cache); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Hf|z/", &array, &BG(array_walk_fci), &BG(array_walk_fci_cache), &userdata) == FAILURE) { BG(array_walk_fci) = orig_array_walk_fci; BG(array_walk_fci_cache) = orig_array_walk_fci_cache; return; } php_array_walk(array, userdata ? &userdata : NULL, 0 TSRMLS_CC); BG(array_walk_fci) = orig_array_walk_fci; BG(array_walk_fci_cache) = orig_array_walk_fci_cache; RETURN_TRUE; } /* }}} */ /* {{{ proto bool array_walk_recursive(array input, string funcname [, mixed userdata]) Apply a user function recursively to every member of an array */ PHP_FUNCTION(array_walk_recursive) { HashTable *array; zval *userdata = NULL; zend_fcall_info orig_array_walk_fci; zend_fcall_info_cache orig_array_walk_fci_cache; orig_array_walk_fci = BG(array_walk_fci); orig_array_walk_fci_cache = BG(array_walk_fci_cache); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Hf|z/", &array, &BG(array_walk_fci), &BG(array_walk_fci_cache), &userdata) == FAILURE) { BG(array_walk_fci) = orig_array_walk_fci; BG(array_walk_fci_cache) = orig_array_walk_fci_cache; return; } php_array_walk(array, userdata ? &userdata : NULL, 1 TSRMLS_CC); BG(array_walk_fci) = orig_array_walk_fci; BG(array_walk_fci_cache) = orig_array_walk_fci_cache; RETURN_TRUE; } /* }}} */ /* void php_search_array(INTERNAL_FUNCTION_PARAMETERS, int behavior) * 0 = return boolean * 1 = return key */ static void php_search_array(INTERNAL_FUNCTION_PARAMETERS, int behavior) /* {{{ */ { zval *value, /* value to check for */ *array, /* array to check in */ **entry, /* pointer to array entry */ res; /* comparison result */ HashPosition pos; /* hash iterator */ zend_bool strict = 0; /* strict comparison or not */ ulong num_key; uint str_key_len; char *string_key; int (*is_equal_func)(zval *, zval *, zval * TSRMLS_DC) = is_equal_function; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "za|b", &value, &array, &strict) == FAILURE) { return; } if (strict) { is_equal_func = is_identical_function; } zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(array), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(array), (void **)&entry, &pos) == SUCCESS) { is_equal_func(&res, value, *entry TSRMLS_CC); if (Z_LVAL(res)) { if (behavior == 0) { RETURN_TRUE; } else { /* Return current key */ switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(array), &string_key, &str_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_STRING: RETURN_STRINGL(string_key, str_key_len - 1, 1); break; case HASH_KEY_IS_LONG: RETURN_LONG(num_key); break; } } } zend_hash_move_forward_ex(Z_ARRVAL_P(array), &pos); } RETURN_FALSE; } /* }}} */ /* {{{ proto bool in_array(mixed needle, array haystack [, bool strict]) Checks if the given value exists in the array */ PHP_FUNCTION(in_array) { php_search_array(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto mixed array_search(mixed needle, array haystack [, bool strict]) Searches the array for a given value and returns the corresponding key if successful */ PHP_FUNCTION(array_search) { php_search_array(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ static int php_valid_var_name(char *var_name, int var_name_len) /* {{{ */ { int i, ch; if (!var_name || !var_name_len) { return 0; } /* These are allowed as first char: [a-zA-Z_\x7f-\xff] */ ch = (int)((unsigned char *)var_name)[0]; if (var_name[0] != '_' && (ch < 65 /* A */ || /* Z */ ch > 90) && (ch < 97 /* a */ || /* z */ ch > 122) && (ch < 127 /* 0x7f */ || /* 0xff */ ch > 255) ) { return 0; } /* And these as the rest: [a-zA-Z0-9_\x7f-\xff] */ if (var_name_len > 1) { for (i = 1; i < var_name_len; i++) { ch = (int)((unsigned char *)var_name)[i]; if (var_name[i] != '_' && (ch < 48 /* 0 */ || /* 9 */ ch > 57) && (ch < 65 /* A */ || /* Z */ ch > 90) && (ch < 97 /* a */ || /* z */ ch > 122) && (ch < 127 /* 0x7f */ || /* 0xff */ ch > 255) ) { return 0; } } } return 1; } /* }}} */ PHPAPI int php_prefix_varname(zval *result, zval *prefix, char *var_name, int var_name_len, zend_bool add_underscore TSRMLS_DC) /* {{{ */ { Z_STRLEN_P(result) = Z_STRLEN_P(prefix) + (add_underscore ? 1 : 0) + var_name_len; Z_TYPE_P(result) = IS_STRING; Z_STRVAL_P(result) = emalloc(Z_STRLEN_P(result) + 1); memcpy(Z_STRVAL_P(result), Z_STRVAL_P(prefix), Z_STRLEN_P(prefix)); if (add_underscore) { Z_STRVAL_P(result)[Z_STRLEN_P(prefix)] = '_'; } memcpy(Z_STRVAL_P(result) + Z_STRLEN_P(prefix) + (add_underscore ? 1 : 0), var_name, var_name_len + 1); return SUCCESS; } /* }}} */ /* {{{ proto int extract(array var_array [, int extract_type [, string prefix]]) Imports variables into symbol table from an array */ PHP_FUNCTION(extract) { zval *var_array, *prefix = NULL; long extract_type = EXTR_OVERWRITE; zval **entry, *data; char *var_name; ulong num_key; uint var_name_len; int var_exists, key_type, count = 0; int extract_refs = 0; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|lz/", &var_array, &extract_type, &prefix) == FAILURE) { return; } extract_refs = (extract_type & EXTR_REFS); extract_type &= 0xff; if (extract_type < EXTR_OVERWRITE || extract_type > EXTR_IF_EXISTS) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid extract type"); return; } if (extract_type > EXTR_SKIP && extract_type <= EXTR_PREFIX_IF_EXISTS && ZEND_NUM_ARGS() < 3) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "specified extract type requires the prefix parameter"); return; } if (prefix) { convert_to_string(prefix); if (Z_STRLEN_P(prefix) && !php_valid_var_name(Z_STRVAL_P(prefix), Z_STRLEN_P(prefix))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "prefix is not a valid identifier"); return; } } if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } /* var_array is passed by ref for the needs of EXTR_REFS (needs to * work on the original array to create refs to its members) * simulate pass_by_value if EXTR_REFS is not used */ if (!extract_refs) { SEPARATE_ARG_IF_REF(var_array); } zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(var_array), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(var_array), (void **)&entry, &pos) == SUCCESS) { zval final_name; ZVAL_NULL(&final_name); key_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(var_array), &var_name, &var_name_len, &num_key, 0, &pos); var_exists = 0; if (key_type == HASH_KEY_IS_STRING) { var_name_len--; var_exists = zend_hash_exists(EG(active_symbol_table), var_name, var_name_len + 1); } else if (key_type == HASH_KEY_IS_LONG && (extract_type == EXTR_PREFIX_ALL || extract_type == EXTR_PREFIX_INVALID)) { zval num; ZVAL_LONG(&num, num_key); convert_to_string(&num); php_prefix_varname(&final_name, prefix, Z_STRVAL(num), Z_STRLEN(num), 1 TSRMLS_CC); zval_dtor(&num); } else { zend_hash_move_forward_ex(Z_ARRVAL_P(var_array), &pos); continue; } switch (extract_type) { case EXTR_IF_EXISTS: if (!var_exists) break; /* break omitted intentionally */ case EXTR_OVERWRITE: /* GLOBALS protection */ if (var_exists && var_name_len == sizeof("GLOBALS")-1 && !strcmp(var_name, "GLOBALS")) { break; } if (var_exists && var_name_len == sizeof("this")-1 && !strcmp(var_name, "this") && EG(scope) && EG(scope)->name_length != 0) { break; } ZVAL_STRINGL(&final_name, var_name, var_name_len, 1); break; case EXTR_PREFIX_IF_EXISTS: if (var_exists) { php_prefix_varname(&final_name, prefix, var_name, var_name_len, 1 TSRMLS_CC); } break; case EXTR_PREFIX_SAME: if (!var_exists && var_name_len != 0) { ZVAL_STRINGL(&final_name, var_name, var_name_len, 1); } /* break omitted intentionally */ case EXTR_PREFIX_ALL: if (Z_TYPE(final_name) == IS_NULL && var_name_len != 0) { php_prefix_varname(&final_name, prefix, var_name, var_name_len, 1 TSRMLS_CC); } break; case EXTR_PREFIX_INVALID: if (Z_TYPE(final_name) == IS_NULL) { if (!php_valid_var_name(var_name, var_name_len)) { php_prefix_varname(&final_name, prefix, var_name, var_name_len, 1 TSRMLS_CC); } else { ZVAL_STRINGL(&final_name, var_name, var_name_len, 1); } } break; default: if (!var_exists) { ZVAL_STRINGL(&final_name, var_name, var_name_len, 1); } break; } if (Z_TYPE(final_name) != IS_NULL && php_valid_var_name(Z_STRVAL(final_name), Z_STRLEN(final_name))) { if (extract_refs) { zval **orig_var; SEPARATE_ZVAL_TO_MAKE_IS_REF(entry); zval_add_ref(entry); if (zend_hash_find(EG(active_symbol_table), Z_STRVAL(final_name), Z_STRLEN(final_name) + 1, (void **) &orig_var) == SUCCESS) { zval_ptr_dtor(orig_var); *orig_var = *entry; } else { zend_hash_update(EG(active_symbol_table), Z_STRVAL(final_name), Z_STRLEN(final_name) + 1, (void **) entry, sizeof(zval *), NULL); } } else { MAKE_STD_ZVAL(data); *data = **entry; zval_copy_ctor(data); ZEND_SET_SYMBOL_WITH_LENGTH(EG(active_symbol_table), Z_STRVAL(final_name), Z_STRLEN(final_name) + 1, data, 1, 0); } count++; } zval_dtor(&final_name); zend_hash_move_forward_ex(Z_ARRVAL_P(var_array), &pos); } if (!extract_refs) { zval_ptr_dtor(&var_array); } RETURN_LONG(count); } /* }}} */ static void php_compact_var(HashTable *eg_active_symbol_table, zval *return_value, zval *entry TSRMLS_DC) /* {{{ */ { zval **value_ptr, *value, *data; if (Z_TYPE_P(entry) == IS_STRING) { if (zend_hash_find(eg_active_symbol_table, Z_STRVAL_P(entry), Z_STRLEN_P(entry) + 1, (void **)&value_ptr) != FAILURE) { value = *value_ptr; ALLOC_ZVAL(data); MAKE_COPY_ZVAL(&value, data); zend_hash_update(Z_ARRVAL_P(return_value), Z_STRVAL_P(entry), Z_STRLEN_P(entry) + 1, &data, sizeof(zval *), NULL); } } else if (Z_TYPE_P(entry) == IS_ARRAY) { HashPosition pos; if ((Z_ARRVAL_P(entry)->nApplyCount > 1)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); return; } Z_ARRVAL_P(entry)->nApplyCount++; zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(entry), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(entry), (void**)&value_ptr, &pos) == SUCCESS) { value = *value_ptr; php_compact_var(eg_active_symbol_table, return_value, value TSRMLS_CC); zend_hash_move_forward_ex(Z_ARRVAL_P(entry), &pos); } Z_ARRVAL_P(entry)->nApplyCount--; } } /* }}} */ /* {{{ proto array compact(mixed var_names [, mixed ...]) Creates a hash containing variables and their values */ PHP_FUNCTION(compact) { zval ***args = NULL; /* function arguments array */ int num_args, i; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &num_args) == FAILURE) { return; } if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } /* compact() is probably most used with a single array of var_names or multiple string names, rather than a combination of both. So quickly guess a minimum result size based on that */ if (ZEND_NUM_ARGS() == 1 && Z_TYPE_PP(args[0]) == IS_ARRAY) { array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_PP(args[0]))); } else { array_init_size(return_value, ZEND_NUM_ARGS()); } for (i=0; i<ZEND_NUM_ARGS(); i++) { php_compact_var(EG(active_symbol_table), return_value, *args[i] TSRMLS_CC); } if (args) { efree(args); } } /* }}} */ /* {{{ proto array array_fill(int start_key, int num, mixed val) Create an array containing num elements starting with index start_key each initialized to val */ PHP_FUNCTION(array_fill) { zval *val; long start_key, num; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "llz", &start_key, &num, &val) == FAILURE) { return; } if (num < 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number of elements must be positive"); RETURN_FALSE; } /* allocate an array for return */ array_init_size(return_value, num); num--; zval_add_ref(&val); if (zend_hash_index_update(Z_ARRVAL_P(return_value), start_key, &val, sizeof(zval *), NULL) == FAILURE) { zval_ptr_dtor(&val); } while (num--) { zval_add_ref(&val); if (zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &val, sizeof(zval *), NULL) == FAILURE) { zval_ptr_dtor(&val); } } } /* }}} */ /* {{{ proto array array_fill_keys(array keys, mixed val) Create an array using the elements of the first parameter as keys each initialized to val */ PHP_FUNCTION(array_fill_keys) { zval *keys, *val, **entry; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "az", &keys, &val) == FAILURE) { return; } /* Initialize return array */ array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(keys))); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(keys), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(keys), (void **)&entry, &pos) == SUCCESS) { if (Z_TYPE_PP(entry) == IS_LONG) { zval_add_ref(&val); zend_hash_index_update(Z_ARRVAL_P(return_value), Z_LVAL_PP(entry), &val, sizeof(zval *), NULL); } else { zval key, *key_ptr = *entry; if (Z_TYPE_PP(entry) != IS_STRING) { key = **entry; zval_copy_ctor(&key); convert_to_string(&key); key_ptr = &key; } zval_add_ref(&val); zend_symtable_update(Z_ARRVAL_P(return_value), Z_STRVAL_P(key_ptr), Z_STRLEN_P(key_ptr) + 1, &val, sizeof(zval *), NULL); if (key_ptr != *entry) { zval_dtor(&key); } } zend_hash_move_forward_ex(Z_ARRVAL_P(keys), &pos); } } /* }}} */ /* {{{ proto array range(mixed low, mixed high[, int step]) Create an array containing the range of integers or characters from low to high (inclusive) */ PHP_FUNCTION(range) { zval *zlow, *zhigh, *zstep = NULL; int err = 0, is_step_double = 0; double step = 1.0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z/z/|z/", &zlow, &zhigh, &zstep) == FAILURE) { RETURN_FALSE; } if (zstep) { if (Z_TYPE_P(zstep) == IS_DOUBLE || (Z_TYPE_P(zstep) == IS_STRING && is_numeric_string(Z_STRVAL_P(zstep), Z_STRLEN_P(zstep), NULL, NULL, 0) == IS_DOUBLE) ) { is_step_double = 1; } convert_to_double_ex(&zstep); step = Z_DVAL_P(zstep); /* We only want positive step values. */ if (step < 0.0) { step *= -1; } } /* Initialize the return_value as an array. */ array_init(return_value); /* If the range is given as strings, generate an array of characters. */ if (Z_TYPE_P(zlow) == IS_STRING && Z_TYPE_P(zhigh) == IS_STRING && Z_STRLEN_P(zlow) >= 1 && Z_STRLEN_P(zhigh) >= 1) { int type1, type2; unsigned char *low, *high; long lstep = (long) step; type1 = is_numeric_string(Z_STRVAL_P(zlow), Z_STRLEN_P(zlow), NULL, NULL, 0); type2 = is_numeric_string(Z_STRVAL_P(zhigh), Z_STRLEN_P(zhigh), NULL, NULL, 0); if (type1 == IS_DOUBLE || type2 == IS_DOUBLE || is_step_double) { goto double_str; } else if (type1 == IS_LONG || type2 == IS_LONG) { goto long_str; } convert_to_string(zlow); convert_to_string(zhigh); low = (unsigned char *)Z_STRVAL_P(zlow); high = (unsigned char *)Z_STRVAL_P(zhigh); if (*low > *high) { /* Negative Steps */ unsigned char ch = *low; if (lstep <= 0) { err = 1; goto err; } for (; ch >= *high; ch -= (unsigned int)lstep) { add_next_index_stringl(return_value, (const char *)&ch, 1, 1); if (((signed int)ch - lstep) < 0) { break; } } } else if (*high > *low) { /* Positive Steps */ unsigned char ch = *low; if (lstep <= 0) { err = 1; goto err; } for (; ch <= *high; ch += (unsigned int)lstep) { add_next_index_stringl(return_value, (const char *)&ch, 1, 1); if (((signed int)ch + lstep) > 255) { break; } } } else { add_next_index_stringl(return_value, (const char *)low, 1, 1); } } else if (Z_TYPE_P(zlow) == IS_DOUBLE || Z_TYPE_P(zhigh) == IS_DOUBLE || is_step_double) { double low, high, value; long i; double_str: convert_to_double(zlow); convert_to_double(zhigh); low = Z_DVAL_P(zlow); high = Z_DVAL_P(zhigh); i = 0; if (low > high) { /* Negative steps */ if (low - high < step || step <= 0) { err = 1; goto err; } for (value = low; value >= (high - DOUBLE_DRIFT_FIX); value = low - (++i * step)) { add_next_index_double(return_value, value); } } else if (high > low) { /* Positive steps */ if (high - low < step || step <= 0) { err = 1; goto err; } for (value = low; value <= (high + DOUBLE_DRIFT_FIX); value = low + (++i * step)) { add_next_index_double(return_value, value); } } else { add_next_index_double(return_value, low); } } else { double low, high; long lstep; long_str: convert_to_double(zlow); convert_to_double(zhigh); low = Z_DVAL_P(zlow); high = Z_DVAL_P(zhigh); lstep = (long) step; if (low > high) { /* Negative steps */ if (low - high < lstep || lstep <= 0) { err = 1; goto err; } for (; low >= high; low -= lstep) { add_next_index_long(return_value, (long)low); } } else if (high > low) { /* Positive steps */ if (high - low < lstep || lstep <= 0) { err = 1; goto err; } for (; low <= high; low += lstep) { add_next_index_long(return_value, (long)low); } } else { add_next_index_long(return_value, (long)low); } } err: if (err) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "step exceeds the specified range"); zval_dtor(return_value); RETURN_FALSE; } } /* }}} */ static void php_array_data_shuffle(zval *array TSRMLS_DC) /* {{{ */ { Bucket **elems, *temp; HashTable *hash; int j, n_elems, rnd_idx, n_left; n_elems = zend_hash_num_elements(Z_ARRVAL_P(array)); if (n_elems < 1) { return; } elems = (Bucket **)safe_emalloc(n_elems, sizeof(Bucket *), 0); hash = Z_ARRVAL_P(array); n_left = n_elems; for (j = 0, temp = hash->pListHead; temp; temp = temp->pListNext) elems[j++] = temp; while (--n_left) { rnd_idx = php_rand(TSRMLS_C); RAND_RANGE(rnd_idx, 0, n_left, PHP_RAND_MAX); if (rnd_idx != n_left) { temp = elems[n_left]; elems[n_left] = elems[rnd_idx]; elems[rnd_idx] = temp; } } HANDLE_BLOCK_INTERRUPTIONS(); hash->pListHead = elems[0]; hash->pListTail = NULL; hash->pInternalPointer = hash->pListHead; for (j = 0; j < n_elems; j++) { if (hash->pListTail) { hash->pListTail->pListNext = elems[j]; } elems[j]->pListLast = hash->pListTail; elems[j]->pListNext = NULL; hash->pListTail = elems[j]; } temp = hash->pListHead; j = 0; while (temp != NULL) { temp->nKeyLength = 0; temp->h = j++; temp = temp->pListNext; } hash->nNextFreeElement = n_elems; zend_hash_rehash(hash); HANDLE_UNBLOCK_INTERRUPTIONS(); efree(elems); } /* }}} */ /* {{{ proto bool shuffle(array array_arg) Randomly shuffle the contents of an array */ PHP_FUNCTION(shuffle) { zval *array; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) { RETURN_FALSE; } php_array_data_shuffle(array TSRMLS_CC); RETURN_TRUE; } /* }}} */ PHPAPI HashTable* php_splice(HashTable *in_hash, int offset, int length, zval ***list, int list_count, HashTable **removed) /* {{{ */ { HashTable *out_hash = NULL; /* Output hashtable */ int num_in, /* Number of entries in the input hashtable */ pos, /* Current position in the hashtable */ i; /* Loop counter */ Bucket *p; /* Pointer to hash bucket */ zval *entry; /* Hash entry */ /* If input hash doesn't exist, we have nothing to do */ if (!in_hash) { return NULL; } /* Get number of entries in the input hash */ num_in = zend_hash_num_elements(in_hash); /* Clamp the offset.. */ if (offset > num_in) { offset = num_in; } else if (offset < 0 && (offset = (num_in + offset)) < 0) { offset = 0; } /* ..and the length */ if (length < 0) { length = num_in - offset + length; } else if (((unsigned)offset + (unsigned)length) > (unsigned)num_in) { length = num_in - offset; } /* Create and initialize output hash */ ALLOC_HASHTABLE(out_hash); zend_hash_init(out_hash, (length > 0 ? num_in - length : 0) + list_count, NULL, ZVAL_PTR_DTOR, 0); /* Start at the beginning of the input hash and copy entries to output hash until offset is reached */ for (pos = 0, p = in_hash->pListHead; pos < offset && p ; pos++, p = p->pListNext) { /* Get entry and increase reference count */ entry = *((zval **)p->pData); Z_ADDREF_P(entry); /* Update output hash depending on key type */ if (p->nKeyLength == 0) { zend_hash_next_index_insert(out_hash, &entry, sizeof(zval *), NULL); } else { zend_hash_quick_update(out_hash, p->arKey, p->nKeyLength, p->h, &entry, sizeof(zval *), NULL); } } /* If hash for removed entries exists, go until offset+length and copy the entries to it */ if (removed != NULL) { for ( ; pos < offset + length && p; pos++, p = p->pListNext) { entry = *((zval **)p->pData); Z_ADDREF_P(entry); if (p->nKeyLength == 0) { zend_hash_next_index_insert(*removed, &entry, sizeof(zval *), NULL); } else { zend_hash_quick_update(*removed, p->arKey, p->nKeyLength, p->h, &entry, sizeof(zval *), NULL); } } } else { /* otherwise just skip those entries */ for ( ; pos < offset + length && p; pos++, p = p->pListNext); } /* If there are entries to insert.. */ if (list != NULL) { /* ..for each one, create a new zval, copy entry into it and copy it into the output hash */ for (i = 0; i < list_count; i++) { entry = *list[i]; Z_ADDREF_P(entry); zend_hash_next_index_insert(out_hash, &entry, sizeof(zval *), NULL); } } /* Copy the remaining input hash entries to the output hash */ for ( ; p ; p = p->pListNext) { entry = *((zval **)p->pData); Z_ADDREF_P(entry); if (p->nKeyLength == 0) { zend_hash_next_index_insert(out_hash, &entry, sizeof(zval *), NULL); } else { zend_hash_quick_update(out_hash, p->arKey, p->nKeyLength, p->h, &entry, sizeof(zval *), NULL); } } zend_hash_internal_pointer_reset(out_hash); return out_hash; } /* }}} */ /* {{{ proto int array_push(array stack, mixed var [, mixed ...]) Pushes elements onto the end of the array */ PHP_FUNCTION(array_push) { zval ***args, /* Function arguments array */ *stack, /* Input array */ *new_var; /* Variable to be pushed */ int i, /* Loop counter */ argc; /* Number of function arguments */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a+", &stack, &args, &argc) == FAILURE) { return; } /* For each subsequent argument, make it a reference, increase refcount, and add it to the end of the array */ for (i = 0; i < argc; i++) { new_var = *args[i]; Z_ADDREF_P(new_var); if (zend_hash_next_index_insert(Z_ARRVAL_P(stack), &new_var, sizeof(zval *), NULL) == FAILURE) { Z_DELREF_P(new_var); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot add element to the array as the next element is already occupied"); efree(args); RETURN_FALSE; } } /* Clean up and return the number of values in the stack */ efree(args); RETVAL_LONG(zend_hash_num_elements(Z_ARRVAL_P(stack))); } /* }}} */ /* {{{ void _phpi_pop(INTERNAL_FUNCTION_PARAMETERS, int off_the_end) */ static void _phpi_pop(INTERNAL_FUNCTION_PARAMETERS, int off_the_end) { zval *stack, /* Input stack */ **val; /* Value to be popped */ char *key = NULL; uint key_len = 0; ulong index; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &stack) == FAILURE) { return; } if (zend_hash_num_elements(Z_ARRVAL_P(stack)) == 0) { return; } /* Get the first or last value and copy it into the return value */ if (off_the_end) { zend_hash_internal_pointer_end(Z_ARRVAL_P(stack)); } else { zend_hash_internal_pointer_reset(Z_ARRVAL_P(stack)); } zend_hash_get_current_data(Z_ARRVAL_P(stack), (void **)&val); RETVAL_ZVAL(*val, 1, 0); /* Delete the first or last value */ zend_hash_get_current_key_ex(Z_ARRVAL_P(stack), &key, &key_len, &index, 0, NULL); if (key && Z_ARRVAL_P(stack) == &EG(symbol_table)) { zend_delete_global_variable(key, key_len - 1 TSRMLS_CC); } else { zend_hash_del_key_or_index(Z_ARRVAL_P(stack), key, key_len, index, (key) ? HASH_DEL_KEY : HASH_DEL_INDEX); } /* If we did a shift... re-index like it did before */ if (!off_the_end) { unsigned int k = 0; int should_rehash = 0; Bucket *p = Z_ARRVAL_P(stack)->pListHead; while (p != NULL) { if (p->nKeyLength == 0) { if (p->h != k) { p->h = k++; should_rehash = 1; } else { k++; } } p = p->pListNext; } Z_ARRVAL_P(stack)->nNextFreeElement = k; if (should_rehash) { zend_hash_rehash(Z_ARRVAL_P(stack)); } } else if (!key_len && index >= Z_ARRVAL_P(stack)->nNextFreeElement - 1) { Z_ARRVAL_P(stack)->nNextFreeElement = Z_ARRVAL_P(stack)->nNextFreeElement - 1; } zend_hash_internal_pointer_reset(Z_ARRVAL_P(stack)); } /* }}} */ /* {{{ proto mixed array_pop(array stack) Pops an element off the end of the array */ PHP_FUNCTION(array_pop) { _phpi_pop(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto mixed array_shift(array stack) Pops an element off the beginning of the array */ PHP_FUNCTION(array_shift) { _phpi_pop(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto int array_unshift(array stack, mixed var [, mixed ...]) Pushes elements onto the beginning of the array */ PHP_FUNCTION(array_unshift) { zval ***args, /* Function arguments array */ *stack; /* Input stack */ HashTable *new_hash; /* New hashtable for the stack */ HashTable old_hash; int argc; /* Number of function arguments */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a+", &stack, &args, &argc) == FAILURE) { return; } /* Use splice to insert the elements at the beginning. Destroy old * hashtable and replace it with new one */ new_hash = php_splice(Z_ARRVAL_P(stack), 0, 0, &args[0], argc, NULL); old_hash = *Z_ARRVAL_P(stack); if (Z_ARRVAL_P(stack) == &EG(symbol_table)) { zend_reset_all_cv(&EG(symbol_table) TSRMLS_CC); } *Z_ARRVAL_P(stack) = *new_hash; FREE_HASHTABLE(new_hash); zend_hash_destroy(&old_hash); /* Clean up and return the number of elements in the stack */ efree(args); RETVAL_LONG(zend_hash_num_elements(Z_ARRVAL_P(stack))); } /* }}} */ /* {{{ proto array array_splice(array input, int offset [, int length [, array replacement]]) Removes the elements designated by offset and length and replace them with supplied array */ PHP_FUNCTION(array_splice) { zval *array, /* Input array */ *repl_array = NULL, /* Replacement array */ ***repl = NULL; /* Replacement elements */ HashTable *new_hash = NULL, /* Output array's hash */ **rem_hash = NULL; /* Removed elements' hash */ HashTable old_hash; Bucket *p; /* Bucket used for traversing hash */ long i, offset, length = 0, repl_num = 0; /* Number of replacement elements */ int num_in; /* Number of elements in the input array */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "al|lz/", &array, &offset, &length, &repl_array) == FAILURE) { return; } num_in = zend_hash_num_elements(Z_ARRVAL_P(array)); if (ZEND_NUM_ARGS() < 3) { length = num_in; } if (ZEND_NUM_ARGS() == 4) { /* Make sure the last argument, if passed, is an array */ convert_to_array(repl_array); /* Create the array of replacement elements */ repl_num = zend_hash_num_elements(Z_ARRVAL_P(repl_array)); repl = (zval ***)safe_emalloc(repl_num, sizeof(zval **), 0); for (p = Z_ARRVAL_P(repl_array)->pListHead, i = 0; p; p = p->pListNext, i++) { repl[i] = ((zval **)p->pData); } } /* Don't create the array of removed elements if it's not going * to be used; e.g. only removing and/or replacing elements */ if (return_value_used) { int size = length; /* Clamp the offset.. */ if (offset > num_in) { offset = num_in; } else if (offset < 0 && (offset = (num_in + offset)) < 0) { offset = 0; } /* ..and the length */ if (length < 0) { size = num_in - offset + length; } else if (((unsigned long) offset + (unsigned long) length) > (unsigned) num_in) { size = num_in - offset; } /* Initialize return value */ array_init_size(return_value, size > 0 ? size : 0); rem_hash = &Z_ARRVAL_P(return_value); } /* Perform splice */ new_hash = php_splice(Z_ARRVAL_P(array), offset, length, repl, repl_num, rem_hash); /* Replace input array's hashtable with the new one */ old_hash = *Z_ARRVAL_P(array); if (Z_ARRVAL_P(array) == &EG(symbol_table)) { zend_reset_all_cv(&EG(symbol_table) TSRMLS_CC); } *Z_ARRVAL_P(array) = *new_hash; FREE_HASHTABLE(new_hash); zend_hash_destroy(&old_hash); /* Clean up */ if (ZEND_NUM_ARGS() == 4) { efree(repl); } } /* }}} */ /* {{{ proto array array_slice(array input, int offset [, int length [, bool preserve_keys]]) Returns elements specified by offset and length */ PHP_FUNCTION(array_slice) { zval *input, /* Input array */ **z_length = NULL, /* How many elements to get */ **entry; /* An array entry */ long offset, /* Offset to get elements from */ length = 0; zend_bool preserve_keys = 0; /* Whether to preserve keys while copying to the new array or not */ int num_in, /* Number of elements in the input array */ pos; /* Current position in the array */ char *string_key; uint string_key_len; ulong num_key; HashPosition hpos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "al|Zb", &input, &offset, &z_length, &preserve_keys) == FAILURE) { return; } /* Get number of entries in the input hash */ num_in = zend_hash_num_elements(Z_ARRVAL_P(input)); /* We want all entries from offset to the end if length is not passed or is null */ if (ZEND_NUM_ARGS() < 3 || Z_TYPE_PP(z_length) == IS_NULL) { length = num_in; } else { convert_to_long_ex(z_length); length = Z_LVAL_PP(z_length); } /* Clamp the offset.. */ if (offset > num_in) { array_init(return_value); return; } else if (offset < 0 && (offset = (num_in + offset)) < 0) { offset = 0; } /* ..and the length */ if (length < 0) { length = num_in - offset + length; } else if (((unsigned long) offset + (unsigned long) length) > (unsigned) num_in) { length = num_in - offset; } /* Initialize returned array */ array_init_size(return_value, length > 0 ? length : 0); if (length <= 0) { return; } /* Start at the beginning and go until we hit offset */ pos = 0; zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &hpos); while (pos < offset && zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &hpos) == SUCCESS) { pos++; zend_hash_move_forward_ex(Z_ARRVAL_P(input), &hpos); } /* Copy elements from input array to the one that's returned */ while (pos < offset + length && zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &hpos) == SUCCESS) { zval_add_ref(entry); switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(input), &string_key, &string_key_len, &num_key, 0, &hpos)) { case HASH_KEY_IS_STRING: zend_hash_update(Z_ARRVAL_P(return_value), string_key, string_key_len, entry, sizeof(zval *), NULL); break; case HASH_KEY_IS_LONG: if (preserve_keys) { zend_hash_index_update(Z_ARRVAL_P(return_value), num_key, entry, sizeof(zval *), NULL); } else { zend_hash_next_index_insert(Z_ARRVAL_P(return_value), entry, sizeof(zval *), NULL); } break; } pos++; zend_hash_move_forward_ex(Z_ARRVAL_P(input), &hpos); } } /* }}} */ PHPAPI int php_array_merge(HashTable *dest, HashTable *src, int recursive TSRMLS_DC) /* {{{ */ { zval **src_entry, **dest_entry; char *string_key; uint string_key_len; ulong num_key; HashPosition pos; zend_hash_internal_pointer_reset_ex(src, &pos); while (zend_hash_get_current_data_ex(src, (void **)&src_entry, &pos) == SUCCESS) { switch (zend_hash_get_current_key_ex(src, &string_key, &string_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_STRING: if (recursive && zend_hash_find(dest, string_key, string_key_len, (void **)&dest_entry) == SUCCESS) { HashTable *thash = Z_TYPE_PP(dest_entry) == IS_ARRAY ? Z_ARRVAL_PP(dest_entry) : NULL; if ((thash && thash->nApplyCount > 1) || (*src_entry == *dest_entry && Z_ISREF_PP(dest_entry) && (Z_REFCOUNT_PP(dest_entry) % 2))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); return 0; } SEPARATE_ZVAL(dest_entry); SEPARATE_ZVAL(src_entry); if (Z_TYPE_PP(dest_entry) == IS_NULL) { convert_to_array_ex(dest_entry); add_next_index_null(*dest_entry); } else { convert_to_array_ex(dest_entry); } if (Z_TYPE_PP(src_entry) == IS_NULL) { convert_to_array_ex(src_entry); add_next_index_null(*src_entry); } else { convert_to_array_ex(src_entry); } if (thash) { thash->nApplyCount++; } if (!php_array_merge(Z_ARRVAL_PP(dest_entry), Z_ARRVAL_PP(src_entry), recursive TSRMLS_CC)) { if (thash) { thash->nApplyCount--; } return 0; } if (thash) { thash->nApplyCount--; } } else { Z_ADDREF_PP(src_entry); zend_hash_update(dest, string_key, string_key_len, src_entry, sizeof(zval *), NULL); } break; case HASH_KEY_IS_LONG: Z_ADDREF_PP(src_entry); zend_hash_next_index_insert(dest, src_entry, sizeof(zval *), NULL); break; } zend_hash_move_forward_ex(src, &pos); } return 1; } /* }}} */ PHPAPI int php_array_replace_recursive(HashTable *dest, HashTable *src TSRMLS_DC) /* {{{ */ { zval **src_entry, **dest_entry; char *string_key; uint string_key_len; ulong num_key; HashPosition pos; for (zend_hash_internal_pointer_reset_ex(src, &pos); zend_hash_get_current_data_ex(src, (void **)&src_entry, &pos) == SUCCESS; zend_hash_move_forward_ex(src, &pos)) { switch (zend_hash_get_current_key_ex(src, &string_key, &string_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_STRING: if (Z_TYPE_PP(src_entry) != IS_ARRAY || zend_hash_find(dest, string_key, string_key_len, (void **)&dest_entry) == FAILURE || Z_TYPE_PP(dest_entry) != IS_ARRAY) { Z_ADDREF_PP(src_entry); zend_hash_update(dest, string_key, string_key_len, src_entry, sizeof(zval *), NULL); continue; } break; case HASH_KEY_IS_LONG: if (Z_TYPE_PP(src_entry) != IS_ARRAY || zend_hash_index_find(dest, num_key, (void **)&dest_entry) == FAILURE || Z_TYPE_PP(dest_entry) != IS_ARRAY) { Z_ADDREF_PP(src_entry); zend_hash_index_update(dest, num_key, src_entry, sizeof(zval *), NULL); continue; } break; } if (Z_ARRVAL_PP(dest_entry)->nApplyCount > 1 || Z_ARRVAL_PP(src_entry)->nApplyCount > 1 || (*src_entry == *dest_entry && Z_ISREF_PP(dest_entry) && (Z_REFCOUNT_PP(dest_entry) % 2))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); return 0; } SEPARATE_ZVAL(dest_entry); Z_ARRVAL_PP(dest_entry)->nApplyCount++; Z_ARRVAL_PP(src_entry)->nApplyCount++; if (!php_array_replace_recursive(Z_ARRVAL_PP(dest_entry), Z_ARRVAL_PP(src_entry) TSRMLS_CC)) { Z_ARRVAL_PP(dest_entry)->nApplyCount--; Z_ARRVAL_PP(src_entry)->nApplyCount--; return 0; } Z_ARRVAL_PP(dest_entry)->nApplyCount--; Z_ARRVAL_PP(src_entry)->nApplyCount--; } return 1; } /* }}} */ static void php_array_merge_or_replace_wrapper(INTERNAL_FUNCTION_PARAMETERS, int recursive, int replace) /* {{{ */ { zval ***args = NULL; int argc, i, init_size = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &argc) == FAILURE) { return; } for (i = 0; i < argc; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is not an array", i + 1); efree(args); RETURN_NULL(); } else { int num = zend_hash_num_elements(Z_ARRVAL_PP(args[i])); if (num > init_size) { init_size = num; } } } array_init_size(return_value, init_size); for (i = 0; i < argc; i++) { SEPARATE_ZVAL(args[i]); if (!replace) { php_array_merge(Z_ARRVAL_P(return_value), Z_ARRVAL_PP(args[i]), recursive TSRMLS_CC); } else if (recursive && i > 0) { /* First array will be copied directly instead */ php_array_replace_recursive(Z_ARRVAL_P(return_value), Z_ARRVAL_PP(args[i]) TSRMLS_CC); } else { zend_hash_merge(Z_ARRVAL_P(return_value), Z_ARRVAL_PP(args[i]), (copy_ctor_func_t) zval_add_ref, NULL, sizeof(zval *), 1); } } efree(args); } /* }}} */ /* {{{ proto array array_merge(array arr1, array arr2 [, array ...]) Merges elements from passed arrays into one array */ PHP_FUNCTION(array_merge) { php_array_merge_or_replace_wrapper(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0, 0); } /* }}} */ /* {{{ proto array array_merge_recursive(array arr1, array arr2 [, array ...]) Recursively merges elements from passed arrays into one array */ PHP_FUNCTION(array_merge_recursive) { php_array_merge_or_replace_wrapper(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1, 0); } /* }}} */ /* {{{ proto array array_replace(array arr1, array arr2 [, array ...]) Replaces elements from passed arrays into one array */ PHP_FUNCTION(array_replace) { php_array_merge_or_replace_wrapper(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0, 1); } /* }}} */ /* {{{ proto array array_replace_recursive(array arr1, array arr2 [, array ...]) Recursively replaces elements from passed arrays into one array */ PHP_FUNCTION(array_replace_recursive) { php_array_merge_or_replace_wrapper(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1, 1); } /* }}} */ /* {{{ proto array array_keys(array input [, mixed search_value[, bool strict]]) Return just the keys from the input array, optionally only for the specified search_value */ PHP_FUNCTION(array_keys) { zval *input, /* Input array */ *search_value = NULL, /* Value to search for */ **entry, /* An entry in the input array */ res, /* Result of comparison */ *new_val; /* New value */ int add_key; /* Flag to indicate whether a key should be added */ char *string_key; /* String key */ uint string_key_len; ulong num_key; /* Numeric key */ zend_bool strict = 0; /* do strict comparison */ HashPosition pos; int (*is_equal_func)(zval *, zval *, zval * TSRMLS_DC) = is_equal_function; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|zb", &input, &search_value, &strict) == FAILURE) { return; } if (strict) { is_equal_func = is_identical_function; } /* Initialize return array */ if (search_value != NULL) { array_init(return_value); } else { array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(input))); } add_key = 1; /* Go through input array and add keys to the return array */ zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &pos) == SUCCESS) { if (search_value != NULL) { is_equal_func(&res, search_value, *entry TSRMLS_CC); add_key = zval_is_true(&res); } if (add_key) { MAKE_STD_ZVAL(new_val); switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(input), &string_key, &string_key_len, &num_key, 1, &pos)) { case HASH_KEY_IS_STRING: ZVAL_STRINGL(new_val, string_key, string_key_len - 1, 0); zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &new_val, sizeof(zval *), NULL); break; case HASH_KEY_IS_LONG: Z_TYPE_P(new_val) = IS_LONG; Z_LVAL_P(new_val) = num_key; zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &new_val, sizeof(zval *), NULL); break; } } zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos); } } /* }}} */ /* {{{ proto array array_values(array input) Return just the values from the input array */ PHP_FUNCTION(array_values) { zval *input, /* Input array */ **entry; /* An entry in the input array */ HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &input) == FAILURE) { return; } /* Initialize return array */ array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(input))); /* Go through input array and add values to the return array */ zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &pos) == SUCCESS) { zval_add_ref(entry); zend_hash_next_index_insert(Z_ARRVAL_P(return_value), entry, sizeof(zval *), NULL); zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos); } } /* }}} */ /* {{{ proto array array_count_values(array input) Return the value as key and the frequency of that value in input as value */ PHP_FUNCTION(array_count_values) { zval *input, /* Input array */ **entry, /* An entry in the input array */ **tmp; HashTable *myht; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &input) == FAILURE) { return; } /* Initialize return array */ array_init(return_value); /* Go through input array and add values to the return array */ myht = Z_ARRVAL_P(input); zend_hash_internal_pointer_reset_ex(myht, &pos); while (zend_hash_get_current_data_ex(myht, (void **)&entry, &pos) == SUCCESS) { if (Z_TYPE_PP(entry) == IS_LONG) { if (zend_hash_index_find(Z_ARRVAL_P(return_value), Z_LVAL_PP(entry), (void **)&tmp) == FAILURE) { zval *data; MAKE_STD_ZVAL(data); ZVAL_LONG(data, 1); zend_hash_index_update(Z_ARRVAL_P(return_value), Z_LVAL_PP(entry), &data, sizeof(data), NULL); } else { Z_LVAL_PP(tmp)++; } } else if (Z_TYPE_PP(entry) == IS_STRING) { if (zend_symtable_find(Z_ARRVAL_P(return_value), Z_STRVAL_PP(entry), Z_STRLEN_PP(entry) + 1, (void**)&tmp) == FAILURE) { zval *data; MAKE_STD_ZVAL(data); ZVAL_LONG(data, 1); zend_symtable_update(Z_ARRVAL_P(return_value), Z_STRVAL_PP(entry), Z_STRLEN_PP(entry) + 1, &data, sizeof(data), NULL); } else { Z_LVAL_PP(tmp)++; } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can only count STRING and INTEGER values!"); } zend_hash_move_forward_ex(myht, &pos); } } /* }}} */ /* {{{ proto array array_reverse(array input [, bool preserve keys]) Return input as a new array with the order of the entries reversed */ PHP_FUNCTION(array_reverse) { zval *input, /* Input array */ **entry; /* An entry in the input array */ char *string_key; uint string_key_len; ulong num_key; zend_bool preserve_keys = 0; /* whether to preserve keys */ HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|b", &input, &preserve_keys) == FAILURE) { return; } /* Initialize return array */ array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(input))); zend_hash_internal_pointer_end_ex(Z_ARRVAL_P(input), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &pos) == SUCCESS) { zval_add_ref(entry); switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(input), &string_key, &string_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_STRING: zend_hash_update(Z_ARRVAL_P(return_value), string_key, string_key_len, entry, sizeof(zval *), NULL); break; case HASH_KEY_IS_LONG: if (preserve_keys) { zend_hash_index_update(Z_ARRVAL_P(return_value), num_key, entry, sizeof(zval *), NULL); } else { zend_hash_next_index_insert(Z_ARRVAL_P(return_value), entry, sizeof(zval *), NULL); } break; } zend_hash_move_backwards_ex(Z_ARRVAL_P(input), &pos); } } /* }}} */ /* {{{ proto array array_pad(array input, int pad_size, mixed pad_value) Returns a copy of input array padded with pad_value to size pad_size */ PHP_FUNCTION(array_pad) { zval *input; /* Input array */ zval *pad_value; /* Padding value obviously */ zval ***pads; /* Array to pass to splice */ HashTable *new_hash;/* Return value from splice */ HashTable old_hash; long pad_size; /* Size to pad to */ long pad_size_abs; /* Absolute value of pad_size */ int input_size; /* Size of the input array */ int num_pads; /* How many pads do we need */ int do_pad; /* Whether we should do padding at all */ int i; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "alz", &input, &pad_size, &pad_value) == FAILURE) { return; } /* Do some initial calculations */ input_size = zend_hash_num_elements(Z_ARRVAL_P(input)); pad_size_abs = abs(pad_size); if (pad_size_abs < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You may only pad up to 1048576 elements at a time"); zval_dtor(return_value); RETURN_FALSE; } do_pad = (input_size >= pad_size_abs) ? 0 : 1; /* Copy the original array */ RETVAL_ZVAL(input, 1, 0); /* If no need to pad, no need to continue */ if (!do_pad) { return; } /* Populate the pads array */ num_pads = pad_size_abs - input_size; if (num_pads > 1048576) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You may only pad up to 1048576 elements at a time"); zval_dtor(return_value); RETURN_FALSE; } pads = (zval ***)safe_emalloc(num_pads, sizeof(zval **), 0); for (i = 0; i < num_pads; i++) { pads[i] = &pad_value; } /* Pad on the right or on the left */ if (pad_size > 0) { new_hash = php_splice(Z_ARRVAL_P(return_value), input_size, 0, pads, num_pads, NULL); } else { new_hash = php_splice(Z_ARRVAL_P(return_value), 0, 0, pads, num_pads, NULL); } /* Copy the result hash into return value */ old_hash = *Z_ARRVAL_P(return_value); if (Z_ARRVAL_P(return_value) == &EG(symbol_table)) { zend_reset_all_cv(&EG(symbol_table) TSRMLS_CC); } *Z_ARRVAL_P(return_value) = *new_hash; FREE_HASHTABLE(new_hash); zend_hash_destroy(&old_hash); /* Clean up */ efree(pads); } /* }}} */ /* {{{ proto array array_flip(array input) Return array with key <-> value flipped */ PHP_FUNCTION(array_flip) { zval *array, **entry, *data; char *string_key; uint str_key_len; ulong num_key; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) { return; } array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(array))); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(array), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(array), (void **)&entry, &pos) == SUCCESS) { MAKE_STD_ZVAL(data); switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(array), &string_key, &str_key_len, &num_key, 1, &pos)) { case HASH_KEY_IS_STRING: ZVAL_STRINGL(data, string_key, str_key_len - 1, 0); break; case HASH_KEY_IS_LONG: Z_TYPE_P(data) = IS_LONG; Z_LVAL_P(data) = num_key; break; } if (Z_TYPE_PP(entry) == IS_LONG) { zend_hash_index_update(Z_ARRVAL_P(return_value), Z_LVAL_PP(entry), &data, sizeof(data), NULL); } else if (Z_TYPE_PP(entry) == IS_STRING) { zend_symtable_update(Z_ARRVAL_P(return_value), Z_STRVAL_PP(entry), Z_STRLEN_PP(entry) + 1, &data, sizeof(data), NULL); } else { zval_ptr_dtor(&data); /* will free also zval structure */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can only flip STRING and INTEGER values!"); } zend_hash_move_forward_ex(Z_ARRVAL_P(array), &pos); } } /* }}} */ /* {{{ proto array array_change_key_case(array input [, int case=CASE_LOWER]) Retuns an array with all string keys lowercased [or uppercased] */ PHP_FUNCTION(array_change_key_case) { zval *array, **entry; char *string_key; char *new_key; uint str_key_len; ulong num_key; long change_to_upper=0; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &change_to_upper) == FAILURE) { return; } array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(array))); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(array), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(array), (void **)&entry, &pos) == SUCCESS) { zval_add_ref(entry); switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(array), &string_key, &str_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_LONG: zend_hash_index_update(Z_ARRVAL_P(return_value), num_key, entry, sizeof(entry), NULL); break; case HASH_KEY_IS_STRING: new_key = estrndup(string_key, str_key_len - 1); if (change_to_upper) { php_strtoupper(new_key, str_key_len - 1); } else { php_strtolower(new_key, str_key_len - 1); } zend_hash_update(Z_ARRVAL_P(return_value), new_key, str_key_len, entry, sizeof(entry), NULL); efree(new_key); break; } zend_hash_move_forward_ex(Z_ARRVAL_P(array), &pos); } } /* }}} */ /* {{{ proto array array_unique(array input [, int sort_flags]) Removes duplicate values from array */ PHP_FUNCTION(array_unique) { zval *array, *tmp; Bucket *p; struct bucketindex { Bucket *b; unsigned int i; }; struct bucketindex *arTmp, *cmpdata, *lastkept; unsigned int i; long sort_type = PHP_SORT_STRING; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { return; } php_set_compare_func(sort_type TSRMLS_CC); array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(array))); zend_hash_copy(Z_ARRVAL_P(return_value), Z_ARRVAL_P(array), (copy_ctor_func_t) zval_add_ref, (void *)&tmp, sizeof(zval*)); if (Z_ARRVAL_P(array)->nNumOfElements <= 1) { /* nothing to do */ return; } /* create and sort array with pointers to the target_hash buckets */ arTmp = (struct bucketindex *) pemalloc((Z_ARRVAL_P(array)->nNumOfElements + 1) * sizeof(struct bucketindex), Z_ARRVAL_P(array)->persistent); if (!arTmp) { zval_dtor(return_value); RETURN_FALSE; } for (i = 0, p = Z_ARRVAL_P(array)->pListHead; p; i++, p = p->pListNext) { arTmp[i].b = p; arTmp[i].i = i; } arTmp[i].b = NULL; zend_qsort((void *) arTmp, i, sizeof(struct bucketindex), php_array_data_compare TSRMLS_CC); /* go through the sorted array and delete duplicates from the copy */ lastkept = arTmp; for (cmpdata = arTmp + 1; cmpdata->b; cmpdata++) { if (php_array_data_compare(lastkept, cmpdata TSRMLS_CC)) { lastkept = cmpdata; } else { if (lastkept->i > cmpdata->i) { p = lastkept->b; lastkept = cmpdata; } else { p = cmpdata->b; } if (p->nKeyLength == 0) { zend_hash_index_del(Z_ARRVAL_P(return_value), p->h); } else { if (Z_ARRVAL_P(return_value) == &EG(symbol_table)) { zend_delete_global_variable(p->arKey, p->nKeyLength - 1 TSRMLS_CC); } else { zend_hash_quick_del(Z_ARRVAL_P(return_value), p->arKey, p->nKeyLength, p->h); } } } } pefree(arTmp, Z_ARRVAL_P(array)->persistent); } /* }}} */ static int zval_compare(zval **a, zval **b TSRMLS_DC) /* {{{ */ { zval result; zval *first; zval *second; first = *((zval **) a); second = *((zval **) b); if (string_compare_function(&result, first, second TSRMLS_CC) == FAILURE) { return 0; } if (Z_TYPE(result) == IS_DOUBLE) { if (Z_DVAL(result) < 0) { return -1; } else if (Z_DVAL(result) > 0) { return 1; } else { return 0; } } convert_to_long(&result); if (Z_LVAL(result) < 0) { return -1; } else if (Z_LVAL(result) > 0) { return 1; } return 0; } /* }}} */ static int zval_user_compare(zval **a, zval **b TSRMLS_DC) /* {{{ */ { zval **args[2]; zval *retval_ptr; args[0] = (zval **) a; args[1] = (zval **) b; BG(user_compare_fci).param_count = 2; BG(user_compare_fci).params = args; BG(user_compare_fci).retval_ptr_ptr = &retval_ptr; BG(user_compare_fci).no_separation = 0; if (zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache) TSRMLS_CC) == SUCCESS && retval_ptr) { long retval; convert_to_long_ex(&retval_ptr); retval = Z_LVAL_P(retval_ptr); zval_ptr_dtor(&retval_ptr); return retval < 0 ? -1 : retval > 0 ? 1 : 0;; } else { return 0; } } /* }}} */ static void php_array_intersect_key(INTERNAL_FUNCTION_PARAMETERS, int data_compare_type) /* {{{ */ { Bucket *p; int argc, i; zval ***args; int (*intersect_data_compare_func)(zval **, zval ** TSRMLS_DC) = NULL; zend_bool ok; zval **data; int req_args; char *param_spec; /* Get the argument count */ argc = ZEND_NUM_ARGS(); if (data_compare_type == INTERSECT_COMP_DATA_USER) { /* INTERSECT_COMP_DATA_USER - array_uintersect_assoc() */ req_args = 3; param_spec = "+f"; intersect_data_compare_func = zval_user_compare; } else { /* INTERSECT_COMP_DATA_NONE - array_intersect_key() INTERSECT_COMP_DATA_INTERNAL - array_intersect_assoc() */ req_args = 2; param_spec = "+"; if (data_compare_type == INTERSECT_COMP_DATA_INTERNAL) { intersect_data_compare_func = zval_compare; } } if (argc < req_args) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least %d parameters are required, %d given", req_args, argc); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, param_spec, &args, &argc, &BG(user_compare_fci), &BG(user_compare_fci_cache)) == FAILURE) { return; } for (i = 0; i < argc; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is not an array", i + 1); RETVAL_NULL(); goto out; } } array_init(return_value); for (p = Z_ARRVAL_PP(args[0])->pListHead; p != NULL; p = p->pListNext) { if (p->nKeyLength == 0) { ok = 1; for (i = 1; i < argc; i++) { if (zend_hash_index_find(Z_ARRVAL_PP(args[i]), p->h, (void**)&data) == FAILURE || (intersect_data_compare_func && intersect_data_compare_func((zval**)p->pData, data TSRMLS_CC) != 0) ) { ok = 0; break; } } if (ok) { Z_ADDREF_PP((zval**)p->pData); zend_hash_index_update(Z_ARRVAL_P(return_value), p->h, p->pData, sizeof(zval*), NULL); } } else { ok = 1; for (i = 1; i < argc; i++) { if (zend_hash_quick_find(Z_ARRVAL_PP(args[i]), p->arKey, p->nKeyLength, p->h, (void**)&data) == FAILURE || (intersect_data_compare_func && intersect_data_compare_func((zval**)p->pData, data TSRMLS_CC) != 0) ) { ok = 0; break; } } if (ok) { Z_ADDREF_PP((zval**)p->pData); zend_hash_quick_update(Z_ARRVAL_P(return_value), p->arKey, p->nKeyLength, p->h, p->pData, sizeof(zval*), NULL); } } } out: efree(args); } /* }}} */ static void php_array_intersect(INTERNAL_FUNCTION_PARAMETERS, int behavior, int data_compare_type, int key_compare_type) /* {{{ */ { zval ***args = NULL; HashTable *hash; int arr_argc, i, c = 0; Bucket ***lists, **list, ***ptrs, *p; int req_args; char *param_spec; zend_fcall_info fci1, fci2; zend_fcall_info_cache fci1_cache = empty_fcall_info_cache, fci2_cache = empty_fcall_info_cache; zend_fcall_info *fci_key, *fci_data; zend_fcall_info_cache *fci_key_cache, *fci_data_cache; PHP_ARRAY_CMP_FUNC_VARS; int (*intersect_key_compare_func)(const void *, const void * TSRMLS_DC); int (*intersect_data_compare_func)(const void *, const void * TSRMLS_DC); if (behavior == INTERSECT_NORMAL) { intersect_key_compare_func = php_array_key_compare; if (data_compare_type == INTERSECT_COMP_DATA_INTERNAL) { /* array_intersect() */ req_args = 2; param_spec = "+"; intersect_data_compare_func = php_array_data_compare; } else if (data_compare_type == INTERSECT_COMP_DATA_USER) { /* array_uintersect() */ req_args = 3; param_spec = "+f"; intersect_data_compare_func = php_array_user_compare; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "data_compare_type is %d. This should never happen. Please report as a bug", data_compare_type); return; } if (ZEND_NUM_ARGS() < req_args) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least %d parameters are required, %d given", req_args, ZEND_NUM_ARGS()); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, param_spec, &args, &arr_argc, &fci1, &fci1_cache) == FAILURE) { return; } fci_data = &fci1; fci_data_cache = &fci1_cache; } else if (behavior & INTERSECT_ASSOC) { /* triggered also when INTERSECT_KEY */ /* INTERSECT_KEY is subset of INTERSECT_ASSOC. When having the former * no comparison of the data is done (part of INTERSECT_ASSOC) */ intersect_key_compare_func = php_array_key_compare; if (data_compare_type == INTERSECT_COMP_DATA_INTERNAL && key_compare_type == INTERSECT_COMP_KEY_INTERNAL) { /* array_intersect_assoc() or array_intersect_key() */ req_args = 2; param_spec = "+"; intersect_key_compare_func = php_array_key_compare; intersect_data_compare_func = php_array_data_compare; } else if (data_compare_type == INTERSECT_COMP_DATA_USER && key_compare_type == INTERSECT_COMP_KEY_INTERNAL) { /* array_uintersect_assoc() */ req_args = 3; param_spec = "+f"; intersect_key_compare_func = php_array_key_compare; intersect_data_compare_func = php_array_user_compare; fci_data = &fci1; fci_data_cache = &fci1_cache; } else if (data_compare_type == INTERSECT_COMP_DATA_INTERNAL && key_compare_type == INTERSECT_COMP_KEY_USER) { /* array_intersect_uassoc() or array_intersect_ukey() */ req_args = 3; param_spec = "+f"; intersect_key_compare_func = php_array_user_key_compare; intersect_data_compare_func = php_array_data_compare; fci_key = &fci1; fci_key_cache = &fci1_cache; } else if (data_compare_type == INTERSECT_COMP_DATA_USER && key_compare_type == INTERSECT_COMP_KEY_USER) { /* array_uintersect_uassoc() */ req_args = 4; param_spec = "+ff"; intersect_key_compare_func = php_array_user_key_compare; intersect_data_compare_func = php_array_user_compare; fci_data = &fci1; fci_data_cache = &fci1_cache; fci_key = &fci2; fci_key_cache = &fci2_cache; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "data_compare_type is %d. key_compare_type is %d. This should never happen. Please report as a bug", data_compare_type, key_compare_type); return; } if (ZEND_NUM_ARGS() < req_args) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least %d parameters are required, %d given", req_args, ZEND_NUM_ARGS()); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, param_spec, &args, &arr_argc, &fci1, &fci1_cache, &fci2, &fci2_cache) == FAILURE) { return; } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "behavior is %d. This should never happen. Please report as a bug", behavior); return; } PHP_ARRAY_CMP_FUNC_BACKUP(); /* for each argument, create and sort list with pointers to the hash buckets */ lists = (Bucket ***)safe_emalloc(arr_argc, sizeof(Bucket **), 0); ptrs = (Bucket ***)safe_emalloc(arr_argc, sizeof(Bucket **), 0); php_set_compare_func(PHP_SORT_STRING TSRMLS_CC); if (behavior == INTERSECT_NORMAL && data_compare_type == INTERSECT_COMP_DATA_USER) { BG(user_compare_fci) = *fci_data; BG(user_compare_fci_cache) = *fci_data_cache; } else if (behavior & INTERSECT_ASSOC && key_compare_type == INTERSECT_COMP_KEY_USER) { BG(user_compare_fci) = *fci_key; BG(user_compare_fci_cache) = *fci_key_cache; } for (i = 0; i < arr_argc; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is not an array", i + 1); arr_argc = i; /* only free up to i - 1 */ goto out; } hash = Z_ARRVAL_PP(args[i]); list = (Bucket **) pemalloc((hash->nNumOfElements + 1) * sizeof(Bucket *), hash->persistent); if (!list) { PHP_ARRAY_CMP_FUNC_RESTORE(); efree(ptrs); efree(lists); efree(args); RETURN_FALSE; } lists[i] = list; ptrs[i] = list; for (p = hash->pListHead; p; p = p->pListNext) { *list++ = p; } *list = NULL; if (behavior == INTERSECT_NORMAL) { zend_qsort((void *) lists[i], hash->nNumOfElements, sizeof(Bucket *), intersect_data_compare_func TSRMLS_CC); } else if (behavior & INTERSECT_ASSOC) { /* triggered also when INTERSECT_KEY */ zend_qsort((void *) lists[i], hash->nNumOfElements, sizeof(Bucket *), intersect_key_compare_func TSRMLS_CC); } } /* copy the argument array */ RETVAL_ZVAL(*args[0], 1, 0); if (return_value->value.ht == &EG(symbol_table)) { HashTable *ht; zval *tmp; ALLOC_HASHTABLE(ht); zend_hash_init(ht, zend_hash_num_elements(return_value->value.ht), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(ht, return_value->value.ht, (copy_ctor_func_t) zval_add_ref, (void *) &tmp, sizeof(zval *)); return_value->value.ht = ht; } /* go through the lists and look for common values */ while (*ptrs[0]) { if ((behavior & INTERSECT_ASSOC) /* triggered also when INTERSECT_KEY */ && key_compare_type == INTERSECT_COMP_KEY_USER) { BG(user_compare_fci) = *fci_key; BG(user_compare_fci_cache) = *fci_key_cache; } for (i = 1; i < arr_argc; i++) { if (behavior & INTERSECT_NORMAL) { while (*ptrs[i] && (0 < (c = intersect_data_compare_func(ptrs[0], ptrs[i] TSRMLS_CC)))) { ptrs[i]++; } } else if (behavior & INTERSECT_ASSOC) { /* triggered also when INTERSECT_KEY */ while (*ptrs[i] && (0 < (c = intersect_key_compare_func(ptrs[0], ptrs[i] TSRMLS_CC)))) { ptrs[i]++; } if ((!c && *ptrs[i]) && (behavior == INTERSECT_ASSOC)) { /* only when INTERSECT_ASSOC */ /* this means that ptrs[i] is not NULL so we can compare * and "c==0" is from last operation * in this branch of code we enter only when INTERSECT_ASSOC * since when we have INTERSECT_KEY compare of data is not wanted. */ if (data_compare_type == INTERSECT_COMP_DATA_USER) { BG(user_compare_fci) = *fci_data; BG(user_compare_fci_cache) = *fci_data_cache; } if (intersect_data_compare_func(ptrs[0], ptrs[i] TSRMLS_CC) != 0) { c = 1; if (key_compare_type == INTERSECT_COMP_KEY_USER) { BG(user_compare_fci) = *fci_key; BG(user_compare_fci_cache) = *fci_key_cache; /* When KEY_USER, the last parameter is always the callback */ } /* we are going to the break */ } else { /* continue looping */ } } } if (!*ptrs[i]) { /* delete any values corresponding to remains of ptrs[0] */ /* and exit because they do not present in at least one of */ /* the other arguments */ for (;;) { p = *ptrs[0]++; if (!p) { goto out; } if (p->nKeyLength == 0) { zend_hash_index_del(Z_ARRVAL_P(return_value), p->h); } else { zend_hash_quick_del(Z_ARRVAL_P(return_value), p->arKey, p->nKeyLength, p->h); } } } if (c) /* here we get if not all are equal */ break; ptrs[i]++; } if (c) { /* Value of ptrs[0] not in all arguments, delete all entries */ /* with value < value of ptrs[i] */ for (;;) { p = *ptrs[0]; if (p->nKeyLength == 0) { zend_hash_index_del(Z_ARRVAL_P(return_value), p->h); } else { zend_hash_quick_del(Z_ARRVAL_P(return_value), p->arKey, p->nKeyLength, p->h); } if (!*++ptrs[0]) { goto out; } if (behavior == INTERSECT_NORMAL) { if (0 <= intersect_data_compare_func(ptrs[0], ptrs[i] TSRMLS_CC)) { break; } } else if (behavior & INTERSECT_ASSOC) { /* triggered also when INTERSECT_KEY */ /* no need of looping because indexes are unique */ break; } } } else { /* ptrs[0] is present in all the arguments */ /* Skip all entries with same value as ptrs[0] */ for (;;) { if (!*++ptrs[0]) { goto out; } if (behavior == INTERSECT_NORMAL) { if (intersect_data_compare_func(ptrs[0] - 1, ptrs[0] TSRMLS_CC)) { break; } } else if (behavior & INTERSECT_ASSOC) { /* triggered also when INTERSECT_KEY */ /* no need of looping because indexes are unique */ break; } } } } out: for (i = 0; i < arr_argc; i++) { hash = Z_ARRVAL_PP(args[i]); pefree(lists[i], hash->persistent); } PHP_ARRAY_CMP_FUNC_RESTORE(); efree(ptrs); efree(lists); efree(args); } /* }}} */ /* {{{ proto array array_intersect_key(array arr1, array arr2 [, array ...]) Returns the entries of arr1 that have keys which are present in all the other arguments. Kind of equivalent to array_diff(array_keys($arr1), array_keys($arr2)[,array_keys(...)]). Equivalent of array_intersect_assoc() but does not do compare of the data. */ PHP_FUNCTION(array_intersect_key) { php_array_intersect_key(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_COMP_DATA_NONE); } /* }}} */ /* {{{ proto array array_intersect_ukey(array arr1, array arr2 [, array ...], callback key_compare_func) Returns the entries of arr1 that have keys which are present in all the other arguments. Kind of equivalent to array_diff(array_keys($arr1), array_keys($arr2)[,array_keys(...)]). The comparison of the keys is performed by a user supplied function. Equivalent of array_intersect_uassoc() but does not do compare of the data. */ PHP_FUNCTION(array_intersect_ukey) { php_array_intersect(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_KEY, INTERSECT_COMP_DATA_INTERNAL, INTERSECT_COMP_KEY_USER); } /* }}} */ /* {{{ proto array array_intersect(array arr1, array arr2 [, array ...]) Returns the entries of arr1 that have values which are present in all the other arguments */ PHP_FUNCTION(array_intersect) { php_array_intersect(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_NORMAL, INTERSECT_COMP_DATA_INTERNAL, INTERSECT_COMP_KEY_INTERNAL); } /* }}} */ /* {{{ proto array array_uintersect(array arr1, array arr2 [, array ...], callback data_compare_func) Returns the entries of arr1 that have values which are present in all the other arguments. Data is compared by using an user-supplied callback. */ PHP_FUNCTION(array_uintersect) { php_array_intersect(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_NORMAL, INTERSECT_COMP_DATA_USER, INTERSECT_COMP_KEY_INTERNAL); } /* }}} */ /* {{{ proto array array_intersect_assoc(array arr1, array arr2 [, array ...]) Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check */ PHP_FUNCTION(array_intersect_assoc) { php_array_intersect_key(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_COMP_DATA_INTERNAL); } /* }}} */ /* {{{ proto array array_intersect_uassoc(array arr1, array arr2 [, array ...], callback key_compare_func) U Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check and they are compared by using an user-supplied callback. */ PHP_FUNCTION(array_intersect_uassoc) { php_array_intersect(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_ASSOC, INTERSECT_COMP_DATA_INTERNAL, INTERSECT_COMP_KEY_USER); } /* }}} */ /* {{{ proto array array_uintersect_assoc(array arr1, array arr2 [, array ...], callback data_compare_func) U Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check. Data is compared by using an user-supplied callback. */ PHP_FUNCTION(array_uintersect_assoc) { php_array_intersect_key(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_COMP_DATA_USER); } /* }}} */ /* {{{ proto array array_uintersect_uassoc(array arr1, array arr2 [, array ...], callback data_compare_func, callback key_compare_func) Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check. Both data and keys are compared by using user-supplied callbacks. */ PHP_FUNCTION(array_uintersect_uassoc) { php_array_intersect(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_ASSOC, INTERSECT_COMP_DATA_USER, INTERSECT_COMP_KEY_USER); } /* }}} */ static void php_array_diff_key(INTERNAL_FUNCTION_PARAMETERS, int data_compare_type) /* {{{ */ { Bucket *p; int argc, i; zval ***args; int (*diff_data_compare_func)(zval **, zval ** TSRMLS_DC) = NULL; zend_bool ok; zval **data; /* Get the argument count */ argc = ZEND_NUM_ARGS(); if (data_compare_type == DIFF_COMP_DATA_USER) { if (argc < 3) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least 3 parameters are required, %d given", ZEND_NUM_ARGS()); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+f", &args, &argc, &BG(user_compare_fci), &BG(user_compare_fci_cache)) == FAILURE) { return; } diff_data_compare_func = zval_user_compare; } else { if (argc < 2) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least 2 parameters are required, %d given", ZEND_NUM_ARGS()); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &argc) == FAILURE) { return; } if (data_compare_type == DIFF_COMP_DATA_INTERNAL) { diff_data_compare_func = zval_compare; } } for (i = 0; i < argc; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is not an array", i + 1); RETVAL_NULL(); goto out; } } array_init(return_value); for (p = Z_ARRVAL_PP(args[0])->pListHead; p != NULL; p = p->pListNext) { if (p->nKeyLength == 0) { ok = 1; for (i = 1; i < argc; i++) { if (zend_hash_index_find(Z_ARRVAL_PP(args[i]), p->h, (void**)&data) == SUCCESS && (!diff_data_compare_func || diff_data_compare_func((zval**)p->pData, data TSRMLS_CC) == 0) ) { ok = 0; break; } } if (ok) { Z_ADDREF_PP((zval**)p->pData); zend_hash_index_update(Z_ARRVAL_P(return_value), p->h, p->pData, sizeof(zval*), NULL); } } else { ok = 1; for (i = 1; i < argc; i++) { if (zend_hash_quick_find(Z_ARRVAL_PP(args[i]), p->arKey, p->nKeyLength, p->h, (void**)&data) == SUCCESS && (!diff_data_compare_func || diff_data_compare_func((zval**)p->pData, data TSRMLS_CC) == 0) ) { ok = 0; break; } } if (ok) { Z_ADDREF_PP((zval**)p->pData); zend_hash_quick_update(Z_ARRVAL_P(return_value), p->arKey, p->nKeyLength, p->h, p->pData, sizeof(zval*), NULL); } } } out: efree(args); } /* }}} */ static void php_array_diff(INTERNAL_FUNCTION_PARAMETERS, int behavior, int data_compare_type, int key_compare_type) /* {{{ */ { zval ***args = NULL; HashTable *hash; int arr_argc, i, c; Bucket ***lists, **list, ***ptrs, *p; int req_args; char *param_spec; zend_fcall_info fci1, fci2; zend_fcall_info_cache fci1_cache = empty_fcall_info_cache, fci2_cache = empty_fcall_info_cache; zend_fcall_info *fci_key, *fci_data; zend_fcall_info_cache *fci_key_cache, *fci_data_cache; PHP_ARRAY_CMP_FUNC_VARS; int (*diff_key_compare_func)(const void *, const void * TSRMLS_DC); int (*diff_data_compare_func)(const void *, const void * TSRMLS_DC); if (behavior == DIFF_NORMAL) { diff_key_compare_func = php_array_key_compare; if (data_compare_type == DIFF_COMP_DATA_INTERNAL) { /* array_diff */ req_args = 2; param_spec = "+"; diff_data_compare_func = php_array_data_compare; } else if (data_compare_type == DIFF_COMP_DATA_USER) { /* array_udiff */ req_args = 3; param_spec = "+f"; diff_data_compare_func = php_array_user_compare; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "data_compare_type is %d. This should never happen. Please report as a bug", data_compare_type); return; } if (ZEND_NUM_ARGS() < req_args) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least %d parameters are required, %d given", req_args, ZEND_NUM_ARGS()); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, param_spec, &args, &arr_argc, &fci1, &fci1_cache) == FAILURE) { return; } fci_data = &fci1; fci_data_cache = &fci1_cache; } else if (behavior & DIFF_ASSOC) { /* triggered also if DIFF_KEY */ /* DIFF_KEY is subset of DIFF_ASSOC. When having the former * no comparison of the data is done (part of DIFF_ASSOC) */ if (data_compare_type == DIFF_COMP_DATA_INTERNAL && key_compare_type == DIFF_COMP_KEY_INTERNAL) { /* array_diff_assoc() or array_diff_key() */ req_args = 2; param_spec = "+"; diff_key_compare_func = php_array_key_compare; diff_data_compare_func = php_array_data_compare; } else if (data_compare_type == DIFF_COMP_DATA_USER && key_compare_type == DIFF_COMP_KEY_INTERNAL) { /* array_udiff_assoc() */ req_args = 3; param_spec = "+f"; diff_key_compare_func = php_array_key_compare; diff_data_compare_func = php_array_user_compare; fci_data = &fci1; fci_data_cache = &fci1_cache; } else if (data_compare_type == DIFF_COMP_DATA_INTERNAL && key_compare_type == DIFF_COMP_KEY_USER) { /* array_diff_uassoc() or array_diff_ukey() */ req_args = 3; param_spec = "+f"; diff_key_compare_func = php_array_user_key_compare; diff_data_compare_func = php_array_data_compare; fci_key = &fci1; fci_key_cache = &fci1_cache; } else if (data_compare_type == DIFF_COMP_DATA_USER && key_compare_type == DIFF_COMP_KEY_USER) { /* array_udiff_uassoc() */ req_args = 4; param_spec = "+ff"; diff_key_compare_func = php_array_user_key_compare; diff_data_compare_func = php_array_user_compare; fci_data = &fci1; fci_data_cache = &fci1_cache; fci_key = &fci2; fci_key_cache = &fci2_cache; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "data_compare_type is %d. key_compare_type is %d. This should never happen. Please report as a bug", data_compare_type, key_compare_type); return; } if (ZEND_NUM_ARGS() < req_args) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least %d parameters are required, %d given", req_args, ZEND_NUM_ARGS()); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, param_spec, &args, &arr_argc, &fci1, &fci1_cache, &fci2, &fci2_cache) == FAILURE) { return; } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "behavior is %d. This should never happen. Please report as a bug", behavior); return; } PHP_ARRAY_CMP_FUNC_BACKUP(); /* for each argument, create and sort list with pointers to the hash buckets */ lists = (Bucket ***)safe_emalloc(arr_argc, sizeof(Bucket **), 0); ptrs = (Bucket ***)safe_emalloc(arr_argc, sizeof(Bucket **), 0); php_set_compare_func(PHP_SORT_STRING TSRMLS_CC); if (behavior == DIFF_NORMAL && data_compare_type == DIFF_COMP_DATA_USER) { BG(user_compare_fci) = *fci_data; BG(user_compare_fci_cache) = *fci_data_cache; } else if (behavior & DIFF_ASSOC && key_compare_type == DIFF_COMP_KEY_USER) { BG(user_compare_fci) = *fci_key; BG(user_compare_fci_cache) = *fci_key_cache; } for (i = 0; i < arr_argc; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is not an array", i + 1); arr_argc = i; /* only free up to i - 1 */ goto out; } hash = Z_ARRVAL_PP(args[i]); list = (Bucket **) pemalloc((hash->nNumOfElements + 1) * sizeof(Bucket *), hash->persistent); if (!list) { PHP_ARRAY_CMP_FUNC_RESTORE(); efree(ptrs); efree(lists); efree(args); RETURN_FALSE; } lists[i] = list; ptrs[i] = list; for (p = hash->pListHead; p; p = p->pListNext) { *list++ = p; } *list = NULL; if (behavior == DIFF_NORMAL) { zend_qsort((void *) lists[i], hash->nNumOfElements, sizeof(Bucket *), diff_data_compare_func TSRMLS_CC); } else if (behavior & DIFF_ASSOC) { /* triggered also when DIFF_KEY */ zend_qsort((void *) lists[i], hash->nNumOfElements, sizeof(Bucket *), diff_key_compare_func TSRMLS_CC); } } /* copy the argument array */ RETVAL_ZVAL(*args[0], 1, 0); if (return_value->value.ht == &EG(symbol_table)) { HashTable *ht; zval *tmp; ALLOC_HASHTABLE(ht); zend_hash_init(ht, zend_hash_num_elements(return_value->value.ht), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(ht, return_value->value.ht, (copy_ctor_func_t) zval_add_ref, (void *) &tmp, sizeof(zval *)); return_value->value.ht = ht; } /* go through the lists and look for values of ptr[0] that are not in the others */ while (*ptrs[0]) { if ((behavior & DIFF_ASSOC) /* triggered also when DIFF_KEY */ && key_compare_type == DIFF_COMP_KEY_USER ) { BG(user_compare_fci) = *fci_key; BG(user_compare_fci_cache) = *fci_key_cache; } c = 1; for (i = 1; i < arr_argc; i++) { Bucket **ptr = ptrs[i]; if (behavior == DIFF_NORMAL) { while (*ptrs[i] && (0 < (c = diff_data_compare_func(ptrs[0], ptrs[i] TSRMLS_CC)))) { ptrs[i]++; } } else if (behavior & DIFF_ASSOC) { /* triggered also when DIFF_KEY */ while (*ptr && (0 != (c = diff_key_compare_func(ptrs[0], ptr TSRMLS_CC)))) { ptr++; } } if (!c) { if (behavior == DIFF_NORMAL) { if (*ptrs[i]) { ptrs[i]++; } break; } else if (behavior == DIFF_ASSOC) { /* only when DIFF_ASSOC */ /* In this branch is execute only when DIFF_ASSOC. If behavior == DIFF_KEY * data comparison is not needed - skipped. */ if (*ptr) { if (data_compare_type == DIFF_COMP_DATA_USER) { BG(user_compare_fci) = *fci_data; BG(user_compare_fci_cache) = *fci_data_cache; } if (diff_data_compare_func(ptrs[0], ptr TSRMLS_CC) != 0) { /* the data is not the same */ c = -1; if (key_compare_type == DIFF_COMP_KEY_USER) { BG(user_compare_fci) = *fci_key; BG(user_compare_fci_cache) = *fci_key_cache; } } else { break; /* we have found the element in other arrays thus we don't want it * in the return_value -> delete from there */ } } } else if (behavior == DIFF_KEY) { /* only when DIFF_KEY */ /* the behavior here differs from INTERSECT_KEY in php_intersect * since in the "diff" case we have to remove the entry from * return_value while when doing intersection the entry must not * be deleted. */ break; /* remove the key */ } } } if (!c) { /* ptrs[0] in one of the other arguments */ /* delete all entries with value as ptrs[0] */ for (;;) { p = *ptrs[0]; if (p->nKeyLength == 0) { zend_hash_index_del(Z_ARRVAL_P(return_value), p->h); } else { zend_hash_quick_del(Z_ARRVAL_P(return_value), p->arKey, p->nKeyLength, p->h); } if (!*++ptrs[0]) { goto out; } if (behavior == DIFF_NORMAL) { if (diff_data_compare_func(ptrs[0] - 1, ptrs[0] TSRMLS_CC)) { break; } } else if (behavior & DIFF_ASSOC) { /* triggered also when DIFF_KEY */ /* in this case no array_key_compare is needed */ break; } } } else { /* ptrs[0] in none of the other arguments */ /* skip all entries with value as ptrs[0] */ for (;;) { if (!*++ptrs[0]) { goto out; } if (behavior == DIFF_NORMAL) { if (diff_data_compare_func(ptrs[0] - 1, ptrs[0] TSRMLS_CC)) { break; } } else if (behavior & DIFF_ASSOC) { /* triggered also when DIFF_KEY */ /* in this case no array_key_compare is needed */ break; } } } } out: for (i = 0; i < arr_argc; i++) { hash = Z_ARRVAL_PP(args[i]); pefree(lists[i], hash->persistent); } PHP_ARRAY_CMP_FUNC_RESTORE(); efree(ptrs); efree(lists); efree(args); } /* }}} */ /* {{{ proto array array_diff_key(array arr1, array arr2 [, array ...]) Returns the entries of arr1 that have keys which are not present in any of the others arguments. This function is like array_diff() but works on the keys instead of the values. The associativity is preserved. */ PHP_FUNCTION(array_diff_key) { php_array_diff_key(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_COMP_DATA_NONE); } /* }}} */ /* {{{ proto array array_diff_ukey(array arr1, array arr2 [, array ...], callback key_comp_func) Returns the entries of arr1 that have keys which are not present in any of the others arguments. User supplied function is used for comparing the keys. This function is like array_udiff() but works on the keys instead of the values. The associativity is preserved. */ PHP_FUNCTION(array_diff_ukey) { php_array_diff(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_KEY, DIFF_COMP_DATA_INTERNAL, DIFF_COMP_KEY_USER); } /* }}} */ /* {{{ proto array array_diff(array arr1, array arr2 [, array ...]) Returns the entries of arr1 that have values which are not present in any of the others arguments. */ PHP_FUNCTION(array_diff) { php_array_diff(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_NORMAL, DIFF_COMP_DATA_INTERNAL, DIFF_COMP_KEY_INTERNAL); } /* }}} */ /* {{{ proto array array_udiff(array arr1, array arr2 [, array ...], callback data_comp_func) Returns the entries of arr1 that have values which are not present in any of the others arguments. Elements are compared by user supplied function. */ PHP_FUNCTION(array_udiff) { php_array_diff(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_NORMAL, DIFF_COMP_DATA_USER, DIFF_COMP_KEY_INTERNAL); } /* }}} */ /* {{{ proto array array_diff_assoc(array arr1, array arr2 [, array ...]) Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal */ PHP_FUNCTION(array_diff_assoc) { php_array_diff_key(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_COMP_DATA_INTERNAL); } /* }}} */ /* {{{ proto array array_diff_uassoc(array arr1, array arr2 [, array ...], callback data_comp_func) Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal. Elements are compared by user supplied function. */ PHP_FUNCTION(array_diff_uassoc) { php_array_diff(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_ASSOC, DIFF_COMP_DATA_INTERNAL, DIFF_COMP_KEY_USER); } /* }}} */ /* {{{ proto array array_udiff_assoc(array arr1, array arr2 [, array ...], callback key_comp_func) Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal. Keys are compared by user supplied function. */ PHP_FUNCTION(array_udiff_assoc) { php_array_diff_key(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_COMP_DATA_USER); } /* }}} */ /* {{{ proto array array_udiff_uassoc(array arr1, array arr2 [, array ...], callback data_comp_func, callback key_comp_func) Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal. Keys and elements are compared by user supplied functions. */ PHP_FUNCTION(array_udiff_uassoc) { php_array_diff(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_ASSOC, DIFF_COMP_DATA_USER, DIFF_COMP_KEY_USER); } /* }}} */ #define MULTISORT_ORDER 0 #define MULTISORT_TYPE 1 #define MULTISORT_LAST 2 PHPAPI int php_multisort_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { Bucket **ab = *(Bucket ***)a; Bucket **bb = *(Bucket ***)b; int r; int result = 0; zval temp; r = 0; do { php_set_compare_func(ARRAYG(multisort_flags)[MULTISORT_TYPE][r] TSRMLS_CC); ARRAYG(compare_func)(&temp, *((zval **)ab[r]->pData), *((zval **)bb[r]->pData) TSRMLS_CC); result = ARRAYG(multisort_flags)[MULTISORT_ORDER][r] * Z_LVAL(temp); if (result != 0) { return result; } r++; } while (ab[r] != NULL); return result; } /* }}} */ #define MULTISORT_ABORT \ for (k = 0; k < MULTISORT_LAST; k++) \ efree(ARRAYG(multisort_flags)[k]); \ efree(arrays); \ efree(args); \ RETURN_FALSE; /* {{{ proto bool array_multisort(array ar1 [, SORT_ASC|SORT_DESC [, SORT_REGULAR|SORT_NUMERIC|SORT_STRING|SORT_NATURAL|SORT_FLAG_CASE]] [, array ar2 [, SORT_ASC|SORT_DESC [, SORT_REGULAR|SORT_NUMERIC|SORT_STRING|SORT_NATURAL|SORT_FLAG_CASE]], ...]) Sort multiple arrays at once similar to how ORDER BY clause works in SQL */ PHP_FUNCTION(array_multisort) { zval*** args; zval*** arrays; Bucket*** indirect; Bucket* p; HashTable* hash; int argc; int array_size; int num_arrays = 0; int parse_state[MULTISORT_LAST]; /* 0 - flag not allowed 1 - flag allowed */ int sort_order = PHP_SORT_ASC; int sort_type = PHP_SORT_REGULAR; int i, k; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &argc) == FAILURE) { return; } /* Allocate space for storing pointers to input arrays and sort flags. */ arrays = (zval ***)ecalloc(argc, sizeof(zval **)); for (i = 0; i < MULTISORT_LAST; i++) { parse_state[i] = 0; ARRAYG(multisort_flags)[i] = (int *)ecalloc(argc, sizeof(int)); } /* Here we go through the input arguments and parse them. Each one can * be either an array or a sort flag which follows an array. If not * specified, the sort flags defaults to PHP_SORT_ASC and PHP_SORT_REGULAR * accordingly. There can't be two sort flags of the same type after an * array, and the very first argument has to be an array. */ for (i = 0; i < argc; i++) { if (Z_TYPE_PP(args[i]) == IS_ARRAY) { /* We see the next array, so we update the sort flags of * the previous array and reset the sort flags. */ if (i > 0) { ARRAYG(multisort_flags)[MULTISORT_ORDER][num_arrays - 1] = sort_order; ARRAYG(multisort_flags)[MULTISORT_TYPE][num_arrays - 1] = sort_type; sort_order = PHP_SORT_ASC; sort_type = PHP_SORT_REGULAR; } arrays[num_arrays++] = args[i]; /* Next one may be an array or a list of sort flags. */ for (k = 0; k < MULTISORT_LAST; k++) { parse_state[k] = 1; } } else if (Z_TYPE_PP(args[i]) == IS_LONG) { switch (Z_LVAL_PP(args[i]) & ~PHP_SORT_FLAG_CASE) { case PHP_SORT_ASC: case PHP_SORT_DESC: /* flag allowed here */ if (parse_state[MULTISORT_ORDER] == 1) { /* Save the flag and make sure then next arg is not the current flag. */ sort_order = Z_LVAL_PP(args[i]) == PHP_SORT_DESC ? -1 : 1; parse_state[MULTISORT_ORDER] = 0; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is expected to be an array or sorting flag that has not already been specified", i + 1); MULTISORT_ABORT; } break; case PHP_SORT_REGULAR: case PHP_SORT_NUMERIC: case PHP_SORT_STRING: case PHP_SORT_NATURAL: #if HAVE_STRCOLL case PHP_SORT_LOCALE_STRING: #endif /* flag allowed here */ if (parse_state[MULTISORT_TYPE] == 1) { /* Save the flag and make sure then next arg is not the current flag. */ sort_type = Z_LVAL_PP(args[i]); parse_state[MULTISORT_TYPE] = 0; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is expected to be an array or sorting flag that has not already been specified", i + 1); MULTISORT_ABORT; } break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is an unknown sort flag", i + 1); MULTISORT_ABORT; break; } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is expected to be an array or a sort flag", i + 1); MULTISORT_ABORT; } } /* Take care of the last array sort flags. */ ARRAYG(multisort_flags)[MULTISORT_ORDER][num_arrays - 1] = sort_order; ARRAYG(multisort_flags)[MULTISORT_TYPE][num_arrays - 1] = sort_type; /* Make sure the arrays are of the same size. */ array_size = zend_hash_num_elements(Z_ARRVAL_PP(arrays[0])); for (i = 0; i < num_arrays; i++) { if (zend_hash_num_elements(Z_ARRVAL_PP(arrays[i])) != array_size) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array sizes are inconsistent"); MULTISORT_ABORT; } } /* If all arrays are empty we don't need to do anything. */ if (array_size < 1) { for (k = 0; k < MULTISORT_LAST; k++) { efree(ARRAYG(multisort_flags)[k]); } efree(arrays); efree(args); RETURN_TRUE; } /* Create the indirection array. This array is of size MxN, where * M is the number of entries in each input array and N is the number * of the input arrays + 1. The last column is NULL to indicate the end * of the row. */ indirect = (Bucket ***)safe_emalloc(array_size, sizeof(Bucket **), 0); for (i = 0; i < array_size; i++) { indirect[i] = (Bucket **)safe_emalloc((num_arrays + 1), sizeof(Bucket *), 0); } for (i = 0; i < num_arrays; i++) { k = 0; for (p = Z_ARRVAL_PP(arrays[i])->pListHead; p; p = p->pListNext, k++) { indirect[k][i] = p; } } for (k = 0; k < array_size; k++) { indirect[k][num_arrays] = NULL; } /* Do the actual sort magic - bada-bim, bada-boom. */ zend_qsort(indirect, array_size, sizeof(Bucket **), php_multisort_compare TSRMLS_CC); /* Restructure the arrays based on sorted indirect - this is mostly taken from zend_hash_sort() function. */ HANDLE_BLOCK_INTERRUPTIONS(); for (i = 0; i < num_arrays; i++) { hash = Z_ARRVAL_PP(arrays[i]); hash->pListHead = indirect[0][i];; hash->pListTail = NULL; hash->pInternalPointer = hash->pListHead; for (k = 0; k < array_size; k++) { if (hash->pListTail) { hash->pListTail->pListNext = indirect[k][i]; } indirect[k][i]->pListLast = hash->pListTail; indirect[k][i]->pListNext = NULL; hash->pListTail = indirect[k][i]; } p = hash->pListHead; k = 0; while (p != NULL) { if (p->nKeyLength == 0) p->h = k++; p = p->pListNext; } hash->nNextFreeElement = array_size; zend_hash_rehash(hash); } HANDLE_UNBLOCK_INTERRUPTIONS(); /* Clean up. */ for (i = 0; i < array_size; i++) { efree(indirect[i]); } efree(indirect); for (k = 0; k < MULTISORT_LAST; k++) { efree(ARRAYG(multisort_flags)[k]); } efree(arrays); efree(args); RETURN_TRUE; } /* }}} */ /* {{{ proto mixed array_rand(array input [, int num_req]) Return key/keys for random entry/entries in the array */ PHP_FUNCTION(array_rand) { zval *input; long randval, num_req = 1; int num_avail, key_type; char *string_key; uint string_key_len; ulong num_key; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &input, &num_req) == FAILURE) { return; } num_avail = zend_hash_num_elements(Z_ARRVAL_P(input)); if (ZEND_NUM_ARGS() > 1) { if (num_req <= 0 || num_req > num_avail) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Second argument has to be between 1 and the number of elements in the array"); return; } } /* Make the return value an array only if we need to pass back more than one result. */ if (num_req > 1) { array_init_size(return_value, num_req); } /* We can't use zend_hash_index_find() because the array may have string keys or gaps. */ zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos); while (num_req && (key_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(input), &string_key, &string_key_len, &num_key, 0, &pos)) != HASH_KEY_NON_EXISTANT) { randval = php_rand(TSRMLS_C); if ((double) (randval / (PHP_RAND_MAX + 1.0)) < (double) num_req / (double) num_avail) { /* If we are returning a single result, just do it. */ if (Z_TYPE_P(return_value) != IS_ARRAY) { if (key_type == HASH_KEY_IS_STRING) { RETURN_STRINGL(string_key, string_key_len - 1, 1); } else { RETURN_LONG(num_key); } } else { /* Append the result to the return value. */ if (key_type == HASH_KEY_IS_STRING) { add_next_index_stringl(return_value, string_key, string_key_len - 1, 1); } else { add_next_index_long(return_value, num_key); } } num_req--; } num_avail--; zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos); } } /* }}} */ /* {{{ proto mixed array_sum(array input) Returns the sum of the array entries */ PHP_FUNCTION(array_sum) { zval *input, **entry, entry_n; HashPosition pos; double dval; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &input) == FAILURE) { return; } ZVAL_LONG(return_value, 0); for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos); zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &pos) == SUCCESS; zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos) ) { if (Z_TYPE_PP(entry) == IS_ARRAY || Z_TYPE_PP(entry) == IS_OBJECT) { continue; } entry_n = **entry; zval_copy_ctor(&entry_n); convert_scalar_to_number(&entry_n TSRMLS_CC); if (Z_TYPE(entry_n) == IS_LONG && Z_TYPE_P(return_value) == IS_LONG) { dval = (double)Z_LVAL_P(return_value) + (double)Z_LVAL(entry_n); if ( (double)LONG_MIN <= dval && dval <= (double)LONG_MAX ) { Z_LVAL_P(return_value) += Z_LVAL(entry_n); continue; } } convert_to_double(return_value); convert_to_double(&entry_n); Z_DVAL_P(return_value) += Z_DVAL(entry_n); } } /* }}} */ /* {{{ proto mixed array_product(array input) Returns the product of the array entries */ PHP_FUNCTION(array_product) { zval *input, **entry, entry_n; HashPosition pos; double dval; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &input) == FAILURE) { return; } ZVAL_LONG(return_value, 1); if (!zend_hash_num_elements(Z_ARRVAL_P(input))) { return; } for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos); zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &pos) == SUCCESS; zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos) ) { if (Z_TYPE_PP(entry) == IS_ARRAY || Z_TYPE_PP(entry) == IS_OBJECT) { continue; } entry_n = **entry; zval_copy_ctor(&entry_n); convert_scalar_to_number(&entry_n TSRMLS_CC); if (Z_TYPE(entry_n) == IS_LONG && Z_TYPE_P(return_value) == IS_LONG) { dval = (double)Z_LVAL_P(return_value) * (double)Z_LVAL(entry_n); if ( (double)LONG_MIN <= dval && dval <= (double)LONG_MAX ) { Z_LVAL_P(return_value) *= Z_LVAL(entry_n); continue; } } convert_to_double(return_value); convert_to_double(&entry_n); Z_DVAL_P(return_value) *= Z_DVAL(entry_n); } } /* }}} */ /* {{{ proto mixed array_reduce(array input, mixed callback [, mixed initial]) Iteratively reduce the array to a single value via the callback. */ PHP_FUNCTION(array_reduce) { zval *input; zval **args[2]; zval **operand; zval *result = NULL; zval *retval; zend_fcall_info fci; zend_fcall_info_cache fci_cache = empty_fcall_info_cache; zval *initial = NULL; HashPosition pos; HashTable *htbl; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "af|z", &input, &fci, &fci_cache, &initial) == FAILURE) { return; } if (ZEND_NUM_ARGS() > 2) { ALLOC_ZVAL(result); MAKE_COPY_ZVAL(&initial, result); } else { MAKE_STD_ZVAL(result); ZVAL_NULL(result); } /* (zval **)input points to an element of argument stack * the base pointer of which is subject to change. * thus we need to keep the pointer to the hashtable for safety */ htbl = Z_ARRVAL_P(input); if (zend_hash_num_elements(htbl) == 0) { if (result) { RETVAL_ZVAL(result, 1, 1); } return; } fci.retval_ptr_ptr = &retval; fci.param_count = 2; fci.no_separation = 0; zend_hash_internal_pointer_reset_ex(htbl, &pos); while (zend_hash_get_current_data_ex(htbl, (void **)&operand, &pos) == SUCCESS) { if (result) { args[0] = &result; args[1] = operand; fci.params = args; if (zend_call_function(&fci, &fci_cache TSRMLS_CC) == SUCCESS && retval) { zval_ptr_dtor(&result); result = retval; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "An error occurred while invoking the reduction callback"); return; } } else { result = *operand; zval_add_ref(&result); } zend_hash_move_forward_ex(htbl, &pos); } RETVAL_ZVAL(result, 1, 1); } /* }}} */ /* {{{ proto array array_filter(array input [, mixed callback]) Filters elements from the array via the callback. */ PHP_FUNCTION(array_filter) { zval *array; zval **operand; zval **args[1]; zval *retval = NULL; zend_bool have_callback = 0; char *string_key; zend_fcall_info fci = empty_fcall_info; zend_fcall_info_cache fci_cache = empty_fcall_info_cache; uint string_key_len; ulong num_key; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|f", &array, &fci, &fci_cache) == FAILURE) { return; } array_init(return_value); if (zend_hash_num_elements(Z_ARRVAL_P(array)) == 0) { return; } if (ZEND_NUM_ARGS() > 1) { have_callback = 1; fci.no_separation = 0; fci.retval_ptr_ptr = &retval; fci.param_count = 1; } for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(array), &pos); zend_hash_get_current_data_ex(Z_ARRVAL_P(array), (void **)&operand, &pos) == SUCCESS; zend_hash_move_forward_ex(Z_ARRVAL_P(array), &pos) ) { if (have_callback) { args[0] = operand; fci.params = args; if (zend_call_function(&fci, &fci_cache TSRMLS_CC) == SUCCESS && retval) { if (!zend_is_true(retval)) { zval_ptr_dtor(&retval); continue; } else { zval_ptr_dtor(&retval); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "An error occurred while invoking the filter callback"); return; } } else if (!zend_is_true(*operand)) { continue; } zval_add_ref(operand); switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(array), &string_key, &string_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_STRING: zend_hash_update(Z_ARRVAL_P(return_value), string_key, string_key_len, operand, sizeof(zval *), NULL); break; case HASH_KEY_IS_LONG: zend_hash_index_update(Z_ARRVAL_P(return_value), num_key, operand, sizeof(zval *), NULL); break; } } } /* }}} */ /* {{{ proto array array_map(mixed callback, array input1 [, array input2 ,...]) Applies the callback to the elements in given arrays. */ PHP_FUNCTION(array_map) { zval ***arrays = NULL; int n_arrays = 0; zval ***params; zval *result, *null; HashPosition *array_pos; zval **args; zend_fcall_info fci = empty_fcall_info; zend_fcall_info_cache fci_cache = empty_fcall_info_cache; int i, k, maxlen = 0; int *array_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "f!+", &fci, &fci_cache, &arrays, &n_arrays) == FAILURE) { return; } RETVAL_NULL(); args = (zval **)safe_emalloc(n_arrays, sizeof(zval *), 0); array_len = (int *)safe_emalloc(n_arrays, sizeof(int), 0); array_pos = (HashPosition *)safe_emalloc(n_arrays, sizeof(HashPosition), 0); for (i = 0; i < n_arrays; i++) { if (Z_TYPE_PP(arrays[i]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d should be an array", i + 2); efree(arrays); efree(args); efree(array_len); efree(array_pos); return; } SEPARATE_ZVAL_IF_NOT_REF(arrays[i]); args[i] = *arrays[i]; array_len[i] = zend_hash_num_elements(Z_ARRVAL_PP(arrays[i])); if (array_len[i] > maxlen) { maxlen = array_len[i]; } zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(arrays[i]), &array_pos[i]); } efree(arrays); /* Short-circuit: if no callback and only one array, just return it. */ if (!ZEND_FCI_INITIALIZED(fci) && n_arrays == 1) { RETVAL_ZVAL(args[0], 1, 0); efree(array_len); efree(array_pos); efree(args); return; } array_init_size(return_value, maxlen); params = (zval ***)safe_emalloc(n_arrays, sizeof(zval **), 0); MAKE_STD_ZVAL(null); ZVAL_NULL(null); /* We iterate through all the arrays at once. */ for (k = 0; k < maxlen; k++) { uint str_key_len; ulong num_key; char *str_key; int key_type = 0; /* If no callback, the result will be an array, consisting of current * entries from all arrays. */ if (!ZEND_FCI_INITIALIZED(fci)) { MAKE_STD_ZVAL(result); array_init_size(result, n_arrays); } for (i = 0; i < n_arrays; i++) { /* If this array still has elements, add the current one to the * parameter list, otherwise use null value. */ if (k < array_len[i]) { zend_hash_get_current_data_ex(Z_ARRVAL_P(args[i]), (void **)&params[i], &array_pos[i]); /* It is safe to store only last value of key type, because * this loop will run just once if there is only 1 array. */ if (n_arrays == 1) { key_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(args[0]), &str_key, &str_key_len, &num_key, 0, &array_pos[i]); } zend_hash_move_forward_ex(Z_ARRVAL_P(args[i]), &array_pos[i]); } else { params[i] = &null; } if (!ZEND_FCI_INITIALIZED(fci)) { zval_add_ref(params[i]); add_next_index_zval(result, *params[i]); } } if (ZEND_FCI_INITIALIZED(fci)) { fci.retval_ptr_ptr = &result; fci.param_count = n_arrays; fci.params = params; fci.no_separation = 0; if (zend_call_function(&fci, &fci_cache TSRMLS_CC) != SUCCESS || !result) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "An error occurred while invoking the map callback"); efree(array_len); efree(args); efree(array_pos); zval_dtor(return_value); zval_ptr_dtor(&null); efree(params); RETURN_NULL(); } } if (n_arrays > 1) { add_next_index_zval(return_value, result); } else { if (key_type == HASH_KEY_IS_STRING) { add_assoc_zval_ex(return_value, str_key, str_key_len, result); } else { add_index_zval(return_value, num_key, result); } } } zval_ptr_dtor(&null); efree(params); efree(array_len); efree(array_pos); efree(args); } /* }}} */ /* {{{ proto bool array_key_exists(mixed key, array search) Checks if the given key or index exists in the array */ PHP_FUNCTION(array_key_exists) { zval *key; /* key to check for */ HashTable *array; /* array to check in */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zH", &key, &array) == FAILURE) { return; } switch (Z_TYPE_P(key)) { case IS_STRING: if (zend_symtable_exists(array, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1)) { RETURN_TRUE; } RETURN_FALSE; case IS_LONG: if (zend_hash_index_exists(array, Z_LVAL_P(key))) { RETURN_TRUE; } RETURN_FALSE; case IS_NULL: if (zend_hash_exists(array, "", 1)) { RETURN_TRUE; } RETURN_FALSE; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "The first argument should be either a string or an integer"); RETURN_FALSE; } } /* }}} */ /* {{{ proto array array_chunk(array input, int size [, bool preserve_keys]) Split array into chunks */ PHP_FUNCTION(array_chunk) { int argc = ZEND_NUM_ARGS(), key_type, num_in; long size, current = 0; char *str_key; uint str_key_len; ulong num_key; zend_bool preserve_keys = 0; zval *input = NULL; zval *chunk = NULL; zval **entry; HashPosition pos; if (zend_parse_parameters(argc TSRMLS_CC, "al|b", &input, &size, &preserve_keys) == FAILURE) { return; } /* Do bounds checking for size parameter. */ if (size < 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Size parameter expected to be greater than 0"); return; } num_in = zend_hash_num_elements(Z_ARRVAL_P(input)); if (size > num_in) { size = num_in > 0 ? num_in : 1; } array_init_size(return_value, ((num_in - 1) / size) + 1); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void**)&entry, &pos) == SUCCESS) { /* If new chunk, create and initialize it. */ if (!chunk) { MAKE_STD_ZVAL(chunk); array_init_size(chunk, size); } /* Add entry to the chunk, preserving keys if necessary. */ zval_add_ref(entry); if (preserve_keys) { key_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(input), &str_key, &str_key_len, &num_key, 0, &pos); switch (key_type) { case HASH_KEY_IS_STRING: add_assoc_zval_ex(chunk, str_key, str_key_len, *entry); break; default: add_index_zval(chunk, num_key, *entry); break; } } else { add_next_index_zval(chunk, *entry); } /* If reached the chunk size, add it to the result array, and reset the * pointer. */ if (!(++current % size)) { add_next_index_zval(return_value, chunk); chunk = NULL; } zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos); } /* Add the final chunk if there is one. */ if (chunk) { add_next_index_zval(return_value, chunk); } } /* }}} */ /* {{{ proto array array_combine(array keys, array values) Creates an array by using the elements of the first parameter as keys and the elements of the second as the corresponding values */ PHP_FUNCTION(array_combine) { zval *values, *keys; HashPosition pos_values, pos_keys; zval **entry_keys, **entry_values; int num_keys, num_values; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "aa", &keys, &values) == FAILURE) { return; } num_keys = zend_hash_num_elements(Z_ARRVAL_P(keys)); num_values = zend_hash_num_elements(Z_ARRVAL_P(values)); if (num_keys != num_values) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Both parameters should have an equal number of elements"); RETURN_FALSE; } array_init_size(return_value, num_keys); if (!num_keys) { return; } zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(keys), &pos_keys); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(values), &pos_values); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(keys), (void **)&entry_keys, &pos_keys) == SUCCESS && zend_hash_get_current_data_ex(Z_ARRVAL_P(values), (void **)&entry_values, &pos_values) == SUCCESS ) { if (Z_TYPE_PP(entry_keys) == IS_LONG) { zval_add_ref(entry_values); add_index_zval(return_value, Z_LVAL_PP(entry_keys), *entry_values); } else { zval key, *key_ptr = *entry_keys; if (Z_TYPE_PP(entry_keys) != IS_STRING) { key = **entry_keys; zval_copy_ctor(&key); convert_to_string(&key); key_ptr = &key; } zval_add_ref(entry_values); add_assoc_zval_ex(return_value, Z_STRVAL_P(key_ptr), Z_STRLEN_P(key_ptr) + 1, *entry_values); if (key_ptr != *entry_keys) { zval_dtor(&key); } } zend_hash_move_forward_ex(Z_ARRVAL_P(keys), &pos_keys); zend_hash_move_forward_ex(Z_ARRVAL_P(values), &pos_values); } } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2012 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | Rasmus Lerdorf <[email protected]> | | Andrei Zmievski <[email protected]> | | Stig Venaas <[email protected]> | | Jason Greene <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "php.h" #include "php_ini.h" #include <stdarg.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <stdio.h> #if HAVE_STRING_H #include <string.h> #else #include <strings.h> #endif #ifdef PHP_WIN32 #include "win32/unistd.h" #endif #include "zend_globals.h" #include "zend_interfaces.h" #include "php_globals.h" #include "php_array.h" #include "basic_functions.h" #include "php_string.h" #include "php_rand.h" #include "php_smart_str.h" #ifdef HAVE_SPL #include "ext/spl/spl_array.h" #endif /* {{{ defines */ #define EXTR_OVERWRITE 0 #define EXTR_SKIP 1 #define EXTR_PREFIX_SAME 2 #define EXTR_PREFIX_ALL 3 #define EXTR_PREFIX_INVALID 4 #define EXTR_PREFIX_IF_EXISTS 5 #define EXTR_IF_EXISTS 6 #define EXTR_REFS 0x100 #define CASE_LOWER 0 #define CASE_UPPER 1 #define COUNT_NORMAL 0 #define COUNT_RECURSIVE 1 #define DIFF_NORMAL 1 #define DIFF_KEY 2 #define DIFF_ASSOC 6 #define DIFF_COMP_DATA_NONE -1 #define DIFF_COMP_DATA_INTERNAL 0 #define DIFF_COMP_DATA_USER 1 #define DIFF_COMP_KEY_INTERNAL 0 #define DIFF_COMP_KEY_USER 1 #define INTERSECT_NORMAL 1 #define INTERSECT_KEY 2 #define INTERSECT_ASSOC 6 #define INTERSECT_COMP_DATA_NONE -1 #define INTERSECT_COMP_DATA_INTERNAL 0 #define INTERSECT_COMP_DATA_USER 1 #define INTERSECT_COMP_KEY_INTERNAL 0 #define INTERSECT_COMP_KEY_USER 1 #define DOUBLE_DRIFT_FIX 0.000000000000001 /* }}} */ ZEND_DECLARE_MODULE_GLOBALS(array) /* {{{ php_array_init_globals */ static void php_array_init_globals(zend_array_globals *array_globals) { memset(array_globals, 0, sizeof(zend_array_globals)); } /* }}} */ PHP_MINIT_FUNCTION(array) /* {{{ */ { ZEND_INIT_MODULE_GLOBALS(array, php_array_init_globals, NULL); REGISTER_LONG_CONSTANT("EXTR_OVERWRITE", EXTR_OVERWRITE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_SKIP", EXTR_SKIP, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_PREFIX_SAME", EXTR_PREFIX_SAME, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_PREFIX_ALL", EXTR_PREFIX_ALL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_PREFIX_INVALID", EXTR_PREFIX_INVALID, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_PREFIX_IF_EXISTS", EXTR_PREFIX_IF_EXISTS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_IF_EXISTS", EXTR_IF_EXISTS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_REFS", EXTR_REFS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_ASC", PHP_SORT_ASC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_DESC", PHP_SORT_DESC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_REGULAR", PHP_SORT_REGULAR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_NUMERIC", PHP_SORT_NUMERIC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_STRING", PHP_SORT_STRING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_LOCALE_STRING", PHP_SORT_LOCALE_STRING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_NATURAL", PHP_SORT_NATURAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_FLAG_CASE", PHP_SORT_FLAG_CASE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("CASE_LOWER", CASE_LOWER, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("CASE_UPPER", CASE_UPPER, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("COUNT_NORMAL", COUNT_NORMAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("COUNT_RECURSIVE", COUNT_RECURSIVE, CONST_CS | CONST_PERSISTENT); return SUCCESS; } /* }}} */ PHP_MSHUTDOWN_FUNCTION(array) /* {{{ */ { #ifdef ZTS ts_free_id(array_globals_id); #endif return SUCCESS; } /* }}} */ static void php_set_compare_func(int sort_type TSRMLS_DC) /* {{{ */ { switch (sort_type & ~PHP_SORT_FLAG_CASE) { case PHP_SORT_NUMERIC: ARRAYG(compare_func) = numeric_compare_function; break; case PHP_SORT_STRING: ARRAYG(compare_func) = sort_type & PHP_SORT_FLAG_CASE ? string_case_compare_function : string_compare_function; break; case PHP_SORT_NATURAL: ARRAYG(compare_func) = sort_type & PHP_SORT_FLAG_CASE ? string_natural_case_compare_function : string_natural_compare_function; break; #if HAVE_STRCOLL case PHP_SORT_LOCALE_STRING: ARRAYG(compare_func) = string_locale_compare_function; break; #endif case PHP_SORT_REGULAR: default: ARRAYG(compare_func) = compare_function; break; } } /* }}} */ static int php_array_key_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { Bucket *f; Bucket *s; zval result; zval first; zval second; f = *((Bucket **) a); s = *((Bucket **) b); if (f->nKeyLength == 0) { Z_TYPE(first) = IS_LONG; Z_LVAL(first) = f->h; } else { Z_TYPE(first) = IS_STRING; Z_STRVAL(first) = (char*)f->arKey; Z_STRLEN(first) = f->nKeyLength - 1; } if (s->nKeyLength == 0) { Z_TYPE(second) = IS_LONG; Z_LVAL(second) = s->h; } else { Z_TYPE(second) = IS_STRING; Z_STRVAL(second) = (char*)s->arKey; Z_STRLEN(second) = s->nKeyLength - 1; } if (ARRAYG(compare_func)(&result, &first, &second TSRMLS_CC) == FAILURE) { return 0; } if (Z_TYPE(result) == IS_DOUBLE) { if (Z_DVAL(result) < 0) { return -1; } else if (Z_DVAL(result) > 0) { return 1; } else { return 0; } } convert_to_long(&result); if (Z_LVAL(result) < 0) { return -1; } else if (Z_LVAL(result) > 0) { return 1; } return 0; } /* }}} */ static int php_array_reverse_key_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { return php_array_key_compare(a, b TSRMLS_CC) * -1; } /* }}} */ /* {{{ proto bool krsort(array &array_arg [, int sort_flags]) Sort an array by key value in reverse order */ PHP_FUNCTION(krsort) { zval *array; long sort_type = PHP_SORT_REGULAR; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { RETURN_FALSE; } php_set_compare_func(sort_type TSRMLS_CC); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_reverse_key_compare, 0 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool ksort(array &array_arg [, int sort_flags]) Sort an array by key */ PHP_FUNCTION(ksort) { zval *array; long sort_type = PHP_SORT_REGULAR; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { RETURN_FALSE; } php_set_compare_func(sort_type TSRMLS_CC); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_key_compare, 0 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ static int php_count_recursive(zval *array, long mode TSRMLS_DC) /* {{{ */ { long cnt = 0; zval **element; if (Z_TYPE_P(array) == IS_ARRAY) { if (Z_ARRVAL_P(array)->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); return 0; } cnt = zend_hash_num_elements(Z_ARRVAL_P(array)); if (mode == COUNT_RECURSIVE) { HashPosition pos; for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(array), &pos); zend_hash_get_current_data_ex(Z_ARRVAL_P(array), (void **) &element, &pos) == SUCCESS; zend_hash_move_forward_ex(Z_ARRVAL_P(array), &pos) ) { Z_ARRVAL_P(array)->nApplyCount++; cnt += php_count_recursive(*element, COUNT_RECURSIVE TSRMLS_CC); Z_ARRVAL_P(array)->nApplyCount--; } } } return cnt; } /* }}} */ /* {{{ proto int count(mixed var [, int mode]) Count the number of elements in a variable (usually an array) */ PHP_FUNCTION(count) { zval *array; long mode = COUNT_NORMAL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|l", &array, &mode) == FAILURE) { return; } switch (Z_TYPE_P(array)) { case IS_NULL: RETURN_LONG(0); break; case IS_ARRAY: RETURN_LONG (php_count_recursive (array, mode TSRMLS_CC)); break; case IS_OBJECT: { #ifdef HAVE_SPL zval *retval; #endif /* first, we check if the handler is defined */ if (Z_OBJ_HT_P(array)->count_elements) { RETVAL_LONG(1); if (SUCCESS == Z_OBJ_HT(*array)->count_elements(array, &Z_LVAL_P(return_value) TSRMLS_CC)) { return; } } #ifdef HAVE_SPL /* if not and the object implements Countable we call its count() method */ if (Z_OBJ_HT_P(array)->get_class_entry && instanceof_function(Z_OBJCE_P(array), spl_ce_Countable TSRMLS_CC)) { zend_call_method_with_0_params(&array, NULL, NULL, "count", &retval); if (retval) { convert_to_long_ex(&retval); RETVAL_LONG(Z_LVAL_P(retval)); zval_ptr_dtor(&retval); } return; } #endif } default: RETURN_LONG(1); break; } } /* }}} */ /* Numbers are always smaller than strings int this function as it * anyway doesn't make much sense to compare two different data types. * This keeps it consistant and simple. * * This is not correct any more, depends on what compare_func is set to. */ static int php_array_data_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { Bucket *f; Bucket *s; zval result; zval *first; zval *second; f = *((Bucket **) a); s = *((Bucket **) b); first = *((zval **) f->pData); second = *((zval **) s->pData); if (ARRAYG(compare_func)(&result, first, second TSRMLS_CC) == FAILURE) { return 0; } if (Z_TYPE(result) == IS_DOUBLE) { if (Z_DVAL(result) < 0) { return -1; } else if (Z_DVAL(result) > 0) { return 1; } else { return 0; } } convert_to_long(&result); if (Z_LVAL(result) < 0) { return -1; } else if (Z_LVAL(result) > 0) { return 1; } return 0; } /* }}} */ static int php_array_reverse_data_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { return php_array_data_compare(a, b TSRMLS_CC) * -1; } /* }}} */ static int php_array_natural_general_compare(const void *a, const void *b, int fold_case) /* {{{ */ { Bucket *f, *s; zval *fval, *sval; zval first, second; int result; f = *((Bucket **) a); s = *((Bucket **) b); fval = *((zval **) f->pData); sval = *((zval **) s->pData); first = *fval; second = *sval; if (Z_TYPE_P(fval) != IS_STRING) { zval_copy_ctor(&first); convert_to_string(&first); } if (Z_TYPE_P(sval) != IS_STRING) { zval_copy_ctor(&second); convert_to_string(&second); } result = strnatcmp_ex(Z_STRVAL(first), Z_STRLEN(first), Z_STRVAL(second), Z_STRLEN(second), fold_case); if (Z_TYPE_P(fval) != IS_STRING) { zval_dtor(&first); } if (Z_TYPE_P(sval) != IS_STRING) { zval_dtor(&second); } return result; } /* }}} */ static int php_array_natural_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { return php_array_natural_general_compare(a, b, 0); } /* }}} */ static int php_array_natural_case_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { return php_array_natural_general_compare(a, b, 1); } /* }}} */ static void php_natsort(INTERNAL_FUNCTION_PARAMETERS, int fold_case) /* {{{ */ { zval *array; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) { return; } if (fold_case) { if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_natural_case_compare, 0 TSRMLS_CC) == FAILURE) { return; } } else { if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_natural_compare, 0 TSRMLS_CC) == FAILURE) { return; } } RETURN_TRUE; } /* }}} */ /* {{{ proto void natsort(array &array_arg) Sort an array using natural sort */ PHP_FUNCTION(natsort) { php_natsort(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto void natcasesort(array &array_arg) Sort an array using case-insensitive natural sort */ PHP_FUNCTION(natcasesort) { php_natsort(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto bool asort(array &array_arg [, int sort_flags]) Sort an array and maintain index association */ PHP_FUNCTION(asort) { zval *array; long sort_type = PHP_SORT_REGULAR; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { RETURN_FALSE; } php_set_compare_func(sort_type TSRMLS_CC); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_data_compare, 0 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool arsort(array &array_arg [, int sort_flags]) Sort an array in reverse order and maintain index association */ PHP_FUNCTION(arsort) { zval *array; long sort_type = PHP_SORT_REGULAR; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { RETURN_FALSE; } php_set_compare_func(sort_type TSRMLS_CC); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_reverse_data_compare, 0 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool sort(array &array_arg [, int sort_flags]) Sort an array */ PHP_FUNCTION(sort) { zval *array; long sort_type = PHP_SORT_REGULAR; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { RETURN_FALSE; } php_set_compare_func(sort_type TSRMLS_CC); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_data_compare, 1 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool rsort(array &array_arg [, int sort_flags]) Sort an array in reverse order */ PHP_FUNCTION(rsort) { zval *array; long sort_type = PHP_SORT_REGULAR; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { RETURN_FALSE; } php_set_compare_func(sort_type TSRMLS_CC); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_reverse_data_compare, 1 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ static int php_array_user_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { Bucket *f; Bucket *s; zval **args[2]; zval *retval_ptr = NULL; f = *((Bucket **) a); s = *((Bucket **) b); args[0] = (zval **) f->pData; args[1] = (zval **) s->pData; BG(user_compare_fci).param_count = 2; BG(user_compare_fci).params = args; BG(user_compare_fci).retval_ptr_ptr = &retval_ptr; BG(user_compare_fci).no_separation = 0; if (zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache) TSRMLS_CC) == SUCCESS && retval_ptr) { long retval; convert_to_long_ex(&retval_ptr); retval = Z_LVAL_P(retval_ptr); zval_ptr_dtor(&retval_ptr); return retval < 0 ? -1 : retval > 0 ? 1 : 0; } else { return 0; } } /* }}} */ /* check if comparison function is valid */ #define PHP_ARRAY_CMP_FUNC_CHECK(func_name) \ if (!zend_is_callable(*func_name, 0, NULL TSRMLS_CC)) { \ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid comparison function"); \ BG(user_compare_fci) = old_user_compare_fci; \ BG(user_compare_fci_cache) = old_user_compare_fci_cache; \ RETURN_FALSE; \ } \ /* Clear FCI cache otherwise : for example the same or other array with * (partly) the same key values has been sorted with uasort() or * other sorting function the comparison is cached, however the name * of the function for comparison is not respected. see bug #28739 AND #33295 * * Following defines will assist in backup / restore values. */ #define PHP_ARRAY_CMP_FUNC_VARS \ zend_fcall_info old_user_compare_fci; \ zend_fcall_info_cache old_user_compare_fci_cache \ #define PHP_ARRAY_CMP_FUNC_BACKUP() \ old_user_compare_fci = BG(user_compare_fci); \ old_user_compare_fci_cache = BG(user_compare_fci_cache); \ BG(user_compare_fci_cache) = empty_fcall_info_cache; \ #define PHP_ARRAY_CMP_FUNC_RESTORE() \ BG(user_compare_fci) = old_user_compare_fci; \ BG(user_compare_fci_cache) = old_user_compare_fci_cache; \ /* {{{ proto bool usort(array array_arg, string cmp_function) Sort an array by values using a user-defined comparison function */ PHP_FUNCTION(usort) { zval *array; unsigned int refcount; PHP_ARRAY_CMP_FUNC_VARS; PHP_ARRAY_CMP_FUNC_BACKUP(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "af", &array, &BG(user_compare_fci), &BG(user_compare_fci_cache)) == FAILURE) { PHP_ARRAY_CMP_FUNC_RESTORE(); return; } /* Clear the is_ref flag, so the attemts to modify the array in user * comparison function will create a copy of array and won't affect the * original array. The fact of modification is detected using refcount * comparison. The result of sorting in such case is undefined and the * function returns FALSE. */ Z_UNSET_ISREF_P(array); refcount = Z_REFCOUNT_P(array); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_user_compare, 1 TSRMLS_CC) == FAILURE) { RETVAL_FALSE; } else { if (refcount > Z_REFCOUNT_P(array)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array was modified by the user comparison function"); RETVAL_FALSE; } else { RETVAL_TRUE; } } if (Z_REFCOUNT_P(array) > 1) { Z_SET_ISREF_P(array); } PHP_ARRAY_CMP_FUNC_RESTORE(); } /* }}} */ /* {{{ proto bool uasort(array array_arg, string cmp_function) Sort an array with a user-defined comparison function and maintain index association */ PHP_FUNCTION(uasort) { zval *array; unsigned int refcount; PHP_ARRAY_CMP_FUNC_VARS; PHP_ARRAY_CMP_FUNC_BACKUP(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "af", &array, &BG(user_compare_fci), &BG(user_compare_fci_cache)) == FAILURE) { PHP_ARRAY_CMP_FUNC_RESTORE(); return; } /* Clear the is_ref flag, so the attemts to modify the array in user * comaprison function will create a copy of array and won't affect the * original array. The fact of modification is detected using refcount * comparison. The result of sorting in such case is undefined and the * function returns FALSE. */ Z_UNSET_ISREF_P(array); refcount = Z_REFCOUNT_P(array); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_user_compare, 0 TSRMLS_CC) == FAILURE) { RETVAL_FALSE; } else { if (refcount > Z_REFCOUNT_P(array)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array was modified by the user comparison function"); RETVAL_FALSE; } else { RETVAL_TRUE; } } if (Z_REFCOUNT_P(array) > 1) { Z_SET_ISREF_P(array); } PHP_ARRAY_CMP_FUNC_RESTORE(); } /* }}} */ static int php_array_user_key_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { Bucket *f; Bucket *s; zval *key1, *key2; zval **args[2]; zval *retval_ptr = NULL; long result; ALLOC_INIT_ZVAL(key1); ALLOC_INIT_ZVAL(key2); args[0] = &key1; args[1] = &key2; f = *((Bucket **) a); s = *((Bucket **) b); if (f->nKeyLength == 0) { Z_LVAL_P(key1) = f->h; Z_TYPE_P(key1) = IS_LONG; } else { Z_STRVAL_P(key1) = estrndup(f->arKey, f->nKeyLength - 1); Z_STRLEN_P(key1) = f->nKeyLength - 1; Z_TYPE_P(key1) = IS_STRING; } if (s->nKeyLength == 0) { Z_LVAL_P(key2) = s->h; Z_TYPE_P(key2) = IS_LONG; } else { Z_STRVAL_P(key2) = estrndup(s->arKey, s->nKeyLength - 1); Z_STRLEN_P(key2) = s->nKeyLength - 1; Z_TYPE_P(key2) = IS_STRING; } BG(user_compare_fci).param_count = 2; BG(user_compare_fci).params = args; BG(user_compare_fci).retval_ptr_ptr = &retval_ptr; BG(user_compare_fci).no_separation = 0; if (zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache) TSRMLS_CC) == SUCCESS && retval_ptr) { convert_to_long_ex(&retval_ptr); result = Z_LVAL_P(retval_ptr); zval_ptr_dtor(&retval_ptr); } else { result = 0; } zval_ptr_dtor(&key1); zval_ptr_dtor(&key2); return result; } /* }}} */ /* {{{ proto bool uksort(array array_arg, string cmp_function) Sort an array by keys using a user-defined comparison function */ PHP_FUNCTION(uksort) { zval *array; unsigned int refcount; PHP_ARRAY_CMP_FUNC_VARS; PHP_ARRAY_CMP_FUNC_BACKUP(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "af", &array, &BG(user_compare_fci), &BG(user_compare_fci_cache)) == FAILURE) { PHP_ARRAY_CMP_FUNC_RESTORE(); return; } /* Clear the is_ref flag, so the attemts to modify the array in user * comaprison function will create a copy of array and won't affect the * original array. The fact of modification is detected using refcount * comparison. The result of sorting in such case is undefined and the * function returns FALSE. */ Z_UNSET_ISREF_P(array); refcount = Z_REFCOUNT_P(array); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_user_key_compare, 0 TSRMLS_CC) == FAILURE) { RETVAL_FALSE; } else { if (refcount > Z_REFCOUNT_P(array)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array was modified by the user comparison function"); RETVAL_FALSE; } else { RETVAL_TRUE; } } if (Z_REFCOUNT_P(array) > 1) { Z_SET_ISREF_P(array); } PHP_ARRAY_CMP_FUNC_RESTORE(); } /* }}} */ /* {{{ proto mixed end(array array_arg) Advances array argument's internal pointer to the last element and return it */ PHP_FUNCTION(end) { HashTable *array; zval **entry; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "H", &array) == FAILURE) { return; } zend_hash_internal_pointer_end(array); if (return_value_used) { if (zend_hash_get_current_data(array, (void **) &entry) == FAILURE) { RETURN_FALSE; } RETURN_ZVAL(*entry, 1, 0); } } /* }}} */ /* {{{ proto mixed prev(array array_arg) Move array argument's internal pointer to the previous element and return it */ PHP_FUNCTION(prev) { HashTable *array; zval **entry; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "H", &array) == FAILURE) { return; } zend_hash_move_backwards(array); if (return_value_used) { if (zend_hash_get_current_data(array, (void **) &entry) == FAILURE) { RETURN_FALSE; } RETURN_ZVAL(*entry, 1, 0); } } /* }}} */ /* {{{ proto mixed next(array array_arg) Move array argument's internal pointer to the next element and return it */ PHP_FUNCTION(next) { HashTable *array; zval **entry; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "H", &array) == FAILURE) { return; } zend_hash_move_forward(array); if (return_value_used) { if (zend_hash_get_current_data(array, (void **) &entry) == FAILURE) { RETURN_FALSE; } RETURN_ZVAL(*entry, 1, 0); } } /* }}} */ /* {{{ proto mixed reset(array array_arg) Set array argument's internal pointer to the first element and return it */ PHP_FUNCTION(reset) { HashTable *array; zval **entry; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "H", &array) == FAILURE) { return; } zend_hash_internal_pointer_reset(array); if (return_value_used) { if (zend_hash_get_current_data(array, (void **) &entry) == FAILURE) { RETURN_FALSE; } RETURN_ZVAL(*entry, 1, 0); } } /* }}} */ /* {{{ proto mixed current(array array_arg) Return the element currently pointed to by the internal array pointer */ PHP_FUNCTION(current) { HashTable *array; zval **entry; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "H", &array) == FAILURE) { return; } if (zend_hash_get_current_data(array, (void **) &entry) == FAILURE) { RETURN_FALSE; } RETURN_ZVAL(*entry, 1, 0); } /* }}} */ /* {{{ proto mixed key(array array_arg) Return the key of the element currently pointed to by the internal array pointer */ PHP_FUNCTION(key) { HashTable *array; char *string_key; uint string_length; ulong num_key; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "H", &array) == FAILURE) { return; } switch (zend_hash_get_current_key_ex(array, &string_key, &string_length, &num_key, 0, NULL)) { case HASH_KEY_IS_STRING: RETVAL_STRINGL(string_key, string_length - 1, 1); break; case HASH_KEY_IS_LONG: RETVAL_LONG(num_key); break; case HASH_KEY_NON_EXISTANT: return; } } /* }}} */ /* {{{ proto mixed min(mixed arg1 [, mixed arg2 [, mixed ...]]) Return the lowest value in an array or a series of arguments */ PHP_FUNCTION(min) { int argc; zval ***args = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &argc) == FAILURE) { return; } php_set_compare_func(PHP_SORT_REGULAR TSRMLS_CC); /* mixed min ( array $values ) */ if (argc == 1) { zval **result; if (Z_TYPE_PP(args[0]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "When only one parameter is given, it must be an array"); RETVAL_NULL(); } else { if (zend_hash_minmax(Z_ARRVAL_PP(args[0]), php_array_data_compare, 0, (void **) &result TSRMLS_CC) == SUCCESS) { RETVAL_ZVAL(*result, 1, 0); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array must contain at least one element"); RETVAL_FALSE; } } } else { /* mixed min ( mixed $value1 , mixed $value2 [, mixed $value3... ] ) */ zval **min, result; int i; min = args[0]; for (i = 1; i < argc; i++) { is_smaller_function(&result, *args[i], *min TSRMLS_CC); if (Z_LVAL(result) == 1) { min = args[i]; } } RETVAL_ZVAL(*min, 1, 0); } if (args) { efree(args); } } /* }}} */ /* {{{ proto mixed max(mixed arg1 [, mixed arg2 [, mixed ...]]) Return the highest value in an array or a series of arguments */ PHP_FUNCTION(max) { zval ***args = NULL; int argc; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &argc) == FAILURE) { return; } php_set_compare_func(PHP_SORT_REGULAR TSRMLS_CC); /* mixed max ( array $values ) */ if (argc == 1) { zval **result; if (Z_TYPE_PP(args[0]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "When only one parameter is given, it must be an array"); RETVAL_NULL(); } else { if (zend_hash_minmax(Z_ARRVAL_PP(args[0]), php_array_data_compare, 1, (void **) &result TSRMLS_CC) == SUCCESS) { RETVAL_ZVAL(*result, 1, 0); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array must contain at least one element"); RETVAL_FALSE; } } } else { /* mixed max ( mixed $value1 , mixed $value2 [, mixed $value3... ] ) */ zval **max, result; int i; max = args[0]; for (i = 1; i < argc; i++) { is_smaller_or_equal_function(&result, *args[i], *max TSRMLS_CC); if (Z_LVAL(result) == 0) { max = args[i]; } } RETVAL_ZVAL(*max, 1, 0); } if (args) { efree(args); } } /* }}} */ static int php_array_walk(HashTable *target_hash, zval **userdata, int recursive TSRMLS_DC) /* {{{ */ { zval **args[3], /* Arguments to userland function */ *retval_ptr, /* Return value - unused */ *key=NULL; /* Entry key */ char *string_key; uint string_key_len; ulong num_key; HashPosition pos; /* Set up known arguments */ args[1] = &key; args[2] = userdata; if (userdata) { Z_ADDREF_PP(userdata); } zend_hash_internal_pointer_reset_ex(target_hash, &pos); BG(array_walk_fci).retval_ptr_ptr = &retval_ptr; BG(array_walk_fci).param_count = userdata ? 3 : 2; BG(array_walk_fci).params = args; BG(array_walk_fci).no_separation = 0; /* Iterate through hash */ while (!EG(exception) && zend_hash_get_current_data_ex(target_hash, (void **)&args[0], &pos) == SUCCESS) { if (recursive && Z_TYPE_PP(args[0]) == IS_ARRAY) { HashTable *thash; zend_fcall_info orig_array_walk_fci; zend_fcall_info_cache orig_array_walk_fci_cache; SEPARATE_ZVAL_IF_NOT_REF(args[0]); thash = Z_ARRVAL_PP(args[0]); if (thash->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); if (userdata) { zval_ptr_dtor(userdata); } return 0; } /* backup the fcall info and cache */ orig_array_walk_fci = BG(array_walk_fci); orig_array_walk_fci_cache = BG(array_walk_fci_cache); thash->nApplyCount++; php_array_walk(thash, userdata, recursive TSRMLS_CC); thash->nApplyCount--; /* restore the fcall info and cache */ BG(array_walk_fci) = orig_array_walk_fci; BG(array_walk_fci_cache) = orig_array_walk_fci_cache; } else { /* Allocate space for key */ MAKE_STD_ZVAL(key); /* Set up the key */ switch (zend_hash_get_current_key_ex(target_hash, &string_key, &string_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_LONG: Z_TYPE_P(key) = IS_LONG; Z_LVAL_P(key) = num_key; break; case HASH_KEY_IS_STRING: ZVAL_STRINGL(key, string_key, string_key_len - 1, 1); break; } /* Call the userland function */ if (zend_call_function(&BG(array_walk_fci), &BG(array_walk_fci_cache) TSRMLS_CC) == SUCCESS) { if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } } else { if (key) { zval_ptr_dtor(&key); key = NULL; } break; } } if (key) { zval_ptr_dtor(&key); key = NULL; } zend_hash_move_forward_ex(target_hash, &pos); } if (userdata) { zval_ptr_dtor(userdata); } return 0; } /* }}} */ /* {{{ proto bool array_walk(array input, string funcname [, mixed userdata]) Apply a user function to every member of an array */ PHP_FUNCTION(array_walk) { HashTable *array; zval *userdata = NULL; zend_fcall_info orig_array_walk_fci; zend_fcall_info_cache orig_array_walk_fci_cache; orig_array_walk_fci = BG(array_walk_fci); orig_array_walk_fci_cache = BG(array_walk_fci_cache); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Hf|z/", &array, &BG(array_walk_fci), &BG(array_walk_fci_cache), &userdata) == FAILURE) { BG(array_walk_fci) = orig_array_walk_fci; BG(array_walk_fci_cache) = orig_array_walk_fci_cache; return; } php_array_walk(array, userdata ? &userdata : NULL, 0 TSRMLS_CC); BG(array_walk_fci) = orig_array_walk_fci; BG(array_walk_fci_cache) = orig_array_walk_fci_cache; RETURN_TRUE; } /* }}} */ /* {{{ proto bool array_walk_recursive(array input, string funcname [, mixed userdata]) Apply a user function recursively to every member of an array */ PHP_FUNCTION(array_walk_recursive) { HashTable *array; zval *userdata = NULL; zend_fcall_info orig_array_walk_fci; zend_fcall_info_cache orig_array_walk_fci_cache; orig_array_walk_fci = BG(array_walk_fci); orig_array_walk_fci_cache = BG(array_walk_fci_cache); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Hf|z/", &array, &BG(array_walk_fci), &BG(array_walk_fci_cache), &userdata) == FAILURE) { BG(array_walk_fci) = orig_array_walk_fci; BG(array_walk_fci_cache) = orig_array_walk_fci_cache; return; } php_array_walk(array, userdata ? &userdata : NULL, 1 TSRMLS_CC); BG(array_walk_fci) = orig_array_walk_fci; BG(array_walk_fci_cache) = orig_array_walk_fci_cache; RETURN_TRUE; } /* }}} */ /* void php_search_array(INTERNAL_FUNCTION_PARAMETERS, int behavior) * 0 = return boolean * 1 = return key */ static void php_search_array(INTERNAL_FUNCTION_PARAMETERS, int behavior) /* {{{ */ { zval *value, /* value to check for */ *array, /* array to check in */ **entry, /* pointer to array entry */ res; /* comparison result */ HashPosition pos; /* hash iterator */ zend_bool strict = 0; /* strict comparison or not */ ulong num_key; uint str_key_len; char *string_key; int (*is_equal_func)(zval *, zval *, zval * TSRMLS_DC) = is_equal_function; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "za|b", &value, &array, &strict) == FAILURE) { return; } if (strict) { is_equal_func = is_identical_function; } zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(array), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(array), (void **)&entry, &pos) == SUCCESS) { is_equal_func(&res, value, *entry TSRMLS_CC); if (Z_LVAL(res)) { if (behavior == 0) { RETURN_TRUE; } else { /* Return current key */ switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(array), &string_key, &str_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_STRING: RETURN_STRINGL(string_key, str_key_len - 1, 1); break; case HASH_KEY_IS_LONG: RETURN_LONG(num_key); break; } } } zend_hash_move_forward_ex(Z_ARRVAL_P(array), &pos); } RETURN_FALSE; } /* }}} */ /* {{{ proto bool in_array(mixed needle, array haystack [, bool strict]) Checks if the given value exists in the array */ PHP_FUNCTION(in_array) { php_search_array(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto mixed array_search(mixed needle, array haystack [, bool strict]) Searches the array for a given value and returns the corresponding key if successful */ PHP_FUNCTION(array_search) { php_search_array(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ static int php_valid_var_name(char *var_name, int var_name_len) /* {{{ */ { int i, ch; if (!var_name || !var_name_len) { return 0; } /* These are allowed as first char: [a-zA-Z_\x7f-\xff] */ ch = (int)((unsigned char *)var_name)[0]; if (var_name[0] != '_' && (ch < 65 /* A */ || /* Z */ ch > 90) && (ch < 97 /* a */ || /* z */ ch > 122) && (ch < 127 /* 0x7f */ || /* 0xff */ ch > 255) ) { return 0; } /* And these as the rest: [a-zA-Z0-9_\x7f-\xff] */ if (var_name_len > 1) { for (i = 1; i < var_name_len; i++) { ch = (int)((unsigned char *)var_name)[i]; if (var_name[i] != '_' && (ch < 48 /* 0 */ || /* 9 */ ch > 57) && (ch < 65 /* A */ || /* Z */ ch > 90) && (ch < 97 /* a */ || /* z */ ch > 122) && (ch < 127 /* 0x7f */ || /* 0xff */ ch > 255) ) { return 0; } } } return 1; } /* }}} */ PHPAPI int php_prefix_varname(zval *result, zval *prefix, char *var_name, int var_name_len, zend_bool add_underscore TSRMLS_DC) /* {{{ */ { Z_STRLEN_P(result) = Z_STRLEN_P(prefix) + (add_underscore ? 1 : 0) + var_name_len; Z_TYPE_P(result) = IS_STRING; Z_STRVAL_P(result) = emalloc(Z_STRLEN_P(result) + 1); memcpy(Z_STRVAL_P(result), Z_STRVAL_P(prefix), Z_STRLEN_P(prefix)); if (add_underscore) { Z_STRVAL_P(result)[Z_STRLEN_P(prefix)] = '_'; } memcpy(Z_STRVAL_P(result) + Z_STRLEN_P(prefix) + (add_underscore ? 1 : 0), var_name, var_name_len + 1); return SUCCESS; } /* }}} */ /* {{{ proto int extract(array var_array [, int extract_type [, string prefix]]) Imports variables into symbol table from an array */ PHP_FUNCTION(extract) { zval *var_array, *prefix = NULL; long extract_type = EXTR_OVERWRITE; zval **entry, *data; char *var_name; ulong num_key; uint var_name_len; int var_exists, key_type, count = 0; int extract_refs = 0; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|lz/", &var_array, &extract_type, &prefix) == FAILURE) { return; } extract_refs = (extract_type & EXTR_REFS); extract_type &= 0xff; if (extract_type < EXTR_OVERWRITE || extract_type > EXTR_IF_EXISTS) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid extract type"); return; } if (extract_type > EXTR_SKIP && extract_type <= EXTR_PREFIX_IF_EXISTS && ZEND_NUM_ARGS() < 3) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "specified extract type requires the prefix parameter"); return; } if (prefix) { convert_to_string(prefix); if (Z_STRLEN_P(prefix) && !php_valid_var_name(Z_STRVAL_P(prefix), Z_STRLEN_P(prefix))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "prefix is not a valid identifier"); return; } } if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } /* var_array is passed by ref for the needs of EXTR_REFS (needs to * work on the original array to create refs to its members) * simulate pass_by_value if EXTR_REFS is not used */ if (!extract_refs) { SEPARATE_ARG_IF_REF(var_array); } zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(var_array), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(var_array), (void **)&entry, &pos) == SUCCESS) { zval final_name; ZVAL_NULL(&final_name); key_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(var_array), &var_name, &var_name_len, &num_key, 0, &pos); var_exists = 0; if (key_type == HASH_KEY_IS_STRING) { var_name_len--; var_exists = zend_hash_exists(EG(active_symbol_table), var_name, var_name_len + 1); } else if (key_type == HASH_KEY_IS_LONG && (extract_type == EXTR_PREFIX_ALL || extract_type == EXTR_PREFIX_INVALID)) { zval num; ZVAL_LONG(&num, num_key); convert_to_string(&num); php_prefix_varname(&final_name, prefix, Z_STRVAL(num), Z_STRLEN(num), 1 TSRMLS_CC); zval_dtor(&num); } else { zend_hash_move_forward_ex(Z_ARRVAL_P(var_array), &pos); continue; } switch (extract_type) { case EXTR_IF_EXISTS: if (!var_exists) break; /* break omitted intentionally */ case EXTR_OVERWRITE: /* GLOBALS protection */ if (var_exists && var_name_len == sizeof("GLOBALS")-1 && !strcmp(var_name, "GLOBALS")) { break; } if (var_exists && var_name_len == sizeof("this")-1 && !strcmp(var_name, "this") && EG(scope) && EG(scope)->name_length != 0) { break; } ZVAL_STRINGL(&final_name, var_name, var_name_len, 1); break; case EXTR_PREFIX_IF_EXISTS: if (var_exists) { php_prefix_varname(&final_name, prefix, var_name, var_name_len, 1 TSRMLS_CC); } break; case EXTR_PREFIX_SAME: if (!var_exists && var_name_len != 0) { ZVAL_STRINGL(&final_name, var_name, var_name_len, 1); } /* break omitted intentionally */ case EXTR_PREFIX_ALL: if (Z_TYPE(final_name) == IS_NULL && var_name_len != 0) { php_prefix_varname(&final_name, prefix, var_name, var_name_len, 1 TSRMLS_CC); } break; case EXTR_PREFIX_INVALID: if (Z_TYPE(final_name) == IS_NULL) { if (!php_valid_var_name(var_name, var_name_len)) { php_prefix_varname(&final_name, prefix, var_name, var_name_len, 1 TSRMLS_CC); } else { ZVAL_STRINGL(&final_name, var_name, var_name_len, 1); } } break; default: if (!var_exists) { ZVAL_STRINGL(&final_name, var_name, var_name_len, 1); } break; } if (Z_TYPE(final_name) != IS_NULL && php_valid_var_name(Z_STRVAL(final_name), Z_STRLEN(final_name))) { if (extract_refs) { zval **orig_var; SEPARATE_ZVAL_TO_MAKE_IS_REF(entry); zval_add_ref(entry); if (zend_hash_find(EG(active_symbol_table), Z_STRVAL(final_name), Z_STRLEN(final_name) + 1, (void **) &orig_var) == SUCCESS) { zval_ptr_dtor(orig_var); *orig_var = *entry; } else { zend_hash_update(EG(active_symbol_table), Z_STRVAL(final_name), Z_STRLEN(final_name) + 1, (void **) entry, sizeof(zval *), NULL); } } else { MAKE_STD_ZVAL(data); *data = **entry; zval_copy_ctor(data); ZEND_SET_SYMBOL_WITH_LENGTH(EG(active_symbol_table), Z_STRVAL(final_name), Z_STRLEN(final_name) + 1, data, 1, 0); } count++; } zval_dtor(&final_name); zend_hash_move_forward_ex(Z_ARRVAL_P(var_array), &pos); } if (!extract_refs) { zval_ptr_dtor(&var_array); } RETURN_LONG(count); } /* }}} */ static void php_compact_var(HashTable *eg_active_symbol_table, zval *return_value, zval *entry TSRMLS_DC) /* {{{ */ { zval **value_ptr, *value, *data; if (Z_TYPE_P(entry) == IS_STRING) { if (zend_hash_find(eg_active_symbol_table, Z_STRVAL_P(entry), Z_STRLEN_P(entry) + 1, (void **)&value_ptr) != FAILURE) { value = *value_ptr; ALLOC_ZVAL(data); MAKE_COPY_ZVAL(&value, data); zend_hash_update(Z_ARRVAL_P(return_value), Z_STRVAL_P(entry), Z_STRLEN_P(entry) + 1, &data, sizeof(zval *), NULL); } } else if (Z_TYPE_P(entry) == IS_ARRAY) { HashPosition pos; if ((Z_ARRVAL_P(entry)->nApplyCount > 1)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); return; } Z_ARRVAL_P(entry)->nApplyCount++; zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(entry), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(entry), (void**)&value_ptr, &pos) == SUCCESS) { value = *value_ptr; php_compact_var(eg_active_symbol_table, return_value, value TSRMLS_CC); zend_hash_move_forward_ex(Z_ARRVAL_P(entry), &pos); } Z_ARRVAL_P(entry)->nApplyCount--; } } /* }}} */ /* {{{ proto array compact(mixed var_names [, mixed ...]) Creates a hash containing variables and their values */ PHP_FUNCTION(compact) { zval ***args = NULL; /* function arguments array */ int num_args, i; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &num_args) == FAILURE) { return; } if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } /* compact() is probably most used with a single array of var_names or multiple string names, rather than a combination of both. So quickly guess a minimum result size based on that */ if (ZEND_NUM_ARGS() == 1 && Z_TYPE_PP(args[0]) == IS_ARRAY) { array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_PP(args[0]))); } else { array_init_size(return_value, ZEND_NUM_ARGS()); } for (i=0; i<ZEND_NUM_ARGS(); i++) { php_compact_var(EG(active_symbol_table), return_value, *args[i] TSRMLS_CC); } if (args) { efree(args); } } /* }}} */ /* {{{ proto array array_fill(int start_key, int num, mixed val) Create an array containing num elements starting with index start_key each initialized to val */ PHP_FUNCTION(array_fill) { zval *val; long start_key, num; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "llz", &start_key, &num, &val) == FAILURE) { return; } if (num < 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number of elements must be positive"); RETURN_FALSE; } /* allocate an array for return */ array_init_size(return_value, num); num--; zend_hash_index_update(Z_ARRVAL_P(return_value), start_key, &val, sizeof(zval *), NULL); zval_add_ref(&val); while (num--) { if (zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &val, sizeof(zval *), NULL) == SUCCESS) { zval_add_ref(&val); } else { zval_dtor(return_value); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot add element to the array as the next element is already occupied"); RETURN_FALSE; } } } /* }}} */ /* {{{ proto array array_fill_keys(array keys, mixed val) Create an array using the elements of the first parameter as keys each initialized to val */ PHP_FUNCTION(array_fill_keys) { zval *keys, *val, **entry; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "az", &keys, &val) == FAILURE) { return; } /* Initialize return array */ array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(keys))); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(keys), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(keys), (void **)&entry, &pos) == SUCCESS) { if (Z_TYPE_PP(entry) == IS_LONG) { zval_add_ref(&val); zend_hash_index_update(Z_ARRVAL_P(return_value), Z_LVAL_PP(entry), &val, sizeof(zval *), NULL); } else { zval key, *key_ptr = *entry; if (Z_TYPE_PP(entry) != IS_STRING) { key = **entry; zval_copy_ctor(&key); convert_to_string(&key); key_ptr = &key; } zval_add_ref(&val); zend_symtable_update(Z_ARRVAL_P(return_value), Z_STRVAL_P(key_ptr), Z_STRLEN_P(key_ptr) + 1, &val, sizeof(zval *), NULL); if (key_ptr != *entry) { zval_dtor(&key); } } zend_hash_move_forward_ex(Z_ARRVAL_P(keys), &pos); } } /* }}} */ /* {{{ proto array range(mixed low, mixed high[, int step]) Create an array containing the range of integers or characters from low to high (inclusive) */ PHP_FUNCTION(range) { zval *zlow, *zhigh, *zstep = NULL; int err = 0, is_step_double = 0; double step = 1.0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z/z/|z/", &zlow, &zhigh, &zstep) == FAILURE) { RETURN_FALSE; } if (zstep) { if (Z_TYPE_P(zstep) == IS_DOUBLE || (Z_TYPE_P(zstep) == IS_STRING && is_numeric_string(Z_STRVAL_P(zstep), Z_STRLEN_P(zstep), NULL, NULL, 0) == IS_DOUBLE) ) { is_step_double = 1; } convert_to_double_ex(&zstep); step = Z_DVAL_P(zstep); /* We only want positive step values. */ if (step < 0.0) { step *= -1; } } /* Initialize the return_value as an array. */ array_init(return_value); /* If the range is given as strings, generate an array of characters. */ if (Z_TYPE_P(zlow) == IS_STRING && Z_TYPE_P(zhigh) == IS_STRING && Z_STRLEN_P(zlow) >= 1 && Z_STRLEN_P(zhigh) >= 1) { int type1, type2; unsigned char *low, *high; long lstep = (long) step; type1 = is_numeric_string(Z_STRVAL_P(zlow), Z_STRLEN_P(zlow), NULL, NULL, 0); type2 = is_numeric_string(Z_STRVAL_P(zhigh), Z_STRLEN_P(zhigh), NULL, NULL, 0); if (type1 == IS_DOUBLE || type2 == IS_DOUBLE || is_step_double) { goto double_str; } else if (type1 == IS_LONG || type2 == IS_LONG) { goto long_str; } convert_to_string(zlow); convert_to_string(zhigh); low = (unsigned char *)Z_STRVAL_P(zlow); high = (unsigned char *)Z_STRVAL_P(zhigh); if (*low > *high) { /* Negative Steps */ unsigned char ch = *low; if (lstep <= 0) { err = 1; goto err; } for (; ch >= *high; ch -= (unsigned int)lstep) { add_next_index_stringl(return_value, (const char *)&ch, 1, 1); if (((signed int)ch - lstep) < 0) { break; } } } else if (*high > *low) { /* Positive Steps */ unsigned char ch = *low; if (lstep <= 0) { err = 1; goto err; } for (; ch <= *high; ch += (unsigned int)lstep) { add_next_index_stringl(return_value, (const char *)&ch, 1, 1); if (((signed int)ch + lstep) > 255) { break; } } } else { add_next_index_stringl(return_value, (const char *)low, 1, 1); } } else if (Z_TYPE_P(zlow) == IS_DOUBLE || Z_TYPE_P(zhigh) == IS_DOUBLE || is_step_double) { double low, high, value; long i; double_str: convert_to_double(zlow); convert_to_double(zhigh); low = Z_DVAL_P(zlow); high = Z_DVAL_P(zhigh); i = 0; if (low > high) { /* Negative steps */ if (low - high < step || step <= 0) { err = 1; goto err; } for (value = low; value >= (high - DOUBLE_DRIFT_FIX); value = low - (++i * step)) { add_next_index_double(return_value, value); } } else if (high > low) { /* Positive steps */ if (high - low < step || step <= 0) { err = 1; goto err; } for (value = low; value <= (high + DOUBLE_DRIFT_FIX); value = low + (++i * step)) { add_next_index_double(return_value, value); } } else { add_next_index_double(return_value, low); } } else { double low, high; long lstep; long_str: convert_to_double(zlow); convert_to_double(zhigh); low = Z_DVAL_P(zlow); high = Z_DVAL_P(zhigh); lstep = (long) step; if (low > high) { /* Negative steps */ if (low - high < lstep || lstep <= 0) { err = 1; goto err; } for (; low >= high; low -= lstep) { add_next_index_long(return_value, (long)low); } } else if (high > low) { /* Positive steps */ if (high - low < lstep || lstep <= 0) { err = 1; goto err; } for (; low <= high; low += lstep) { add_next_index_long(return_value, (long)low); } } else { add_next_index_long(return_value, (long)low); } } err: if (err) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "step exceeds the specified range"); zval_dtor(return_value); RETURN_FALSE; } } /* }}} */ static void php_array_data_shuffle(zval *array TSRMLS_DC) /* {{{ */ { Bucket **elems, *temp; HashTable *hash; int j, n_elems, rnd_idx, n_left; n_elems = zend_hash_num_elements(Z_ARRVAL_P(array)); if (n_elems < 1) { return; } elems = (Bucket **)safe_emalloc(n_elems, sizeof(Bucket *), 0); hash = Z_ARRVAL_P(array); n_left = n_elems; for (j = 0, temp = hash->pListHead; temp; temp = temp->pListNext) elems[j++] = temp; while (--n_left) { rnd_idx = php_rand(TSRMLS_C); RAND_RANGE(rnd_idx, 0, n_left, PHP_RAND_MAX); if (rnd_idx != n_left) { temp = elems[n_left]; elems[n_left] = elems[rnd_idx]; elems[rnd_idx] = temp; } } HANDLE_BLOCK_INTERRUPTIONS(); hash->pListHead = elems[0]; hash->pListTail = NULL; hash->pInternalPointer = hash->pListHead; for (j = 0; j < n_elems; j++) { if (hash->pListTail) { hash->pListTail->pListNext = elems[j]; } elems[j]->pListLast = hash->pListTail; elems[j]->pListNext = NULL; hash->pListTail = elems[j]; } temp = hash->pListHead; j = 0; while (temp != NULL) { temp->nKeyLength = 0; temp->h = j++; temp = temp->pListNext; } hash->nNextFreeElement = n_elems; zend_hash_rehash(hash); HANDLE_UNBLOCK_INTERRUPTIONS(); efree(elems); } /* }}} */ /* {{{ proto bool shuffle(array array_arg) Randomly shuffle the contents of an array */ PHP_FUNCTION(shuffle) { zval *array; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) { RETURN_FALSE; } php_array_data_shuffle(array TSRMLS_CC); RETURN_TRUE; } /* }}} */ PHPAPI HashTable* php_splice(HashTable *in_hash, int offset, int length, zval ***list, int list_count, HashTable **removed) /* {{{ */ { HashTable *out_hash = NULL; /* Output hashtable */ int num_in, /* Number of entries in the input hashtable */ pos, /* Current position in the hashtable */ i; /* Loop counter */ Bucket *p; /* Pointer to hash bucket */ zval *entry; /* Hash entry */ /* If input hash doesn't exist, we have nothing to do */ if (!in_hash) { return NULL; } /* Get number of entries in the input hash */ num_in = zend_hash_num_elements(in_hash); /* Clamp the offset.. */ if (offset > num_in) { offset = num_in; } else if (offset < 0 && (offset = (num_in + offset)) < 0) { offset = 0; } /* ..and the length */ if (length < 0) { length = num_in - offset + length; } else if (((unsigned)offset + (unsigned)length) > (unsigned)num_in) { length = num_in - offset; } /* Create and initialize output hash */ ALLOC_HASHTABLE(out_hash); zend_hash_init(out_hash, (length > 0 ? num_in - length : 0) + list_count, NULL, ZVAL_PTR_DTOR, 0); /* Start at the beginning of the input hash and copy entries to output hash until offset is reached */ for (pos = 0, p = in_hash->pListHead; pos < offset && p ; pos++, p = p->pListNext) { /* Get entry and increase reference count */ entry = *((zval **)p->pData); Z_ADDREF_P(entry); /* Update output hash depending on key type */ if (p->nKeyLength == 0) { zend_hash_next_index_insert(out_hash, &entry, sizeof(zval *), NULL); } else { zend_hash_quick_update(out_hash, p->arKey, p->nKeyLength, p->h, &entry, sizeof(zval *), NULL); } } /* If hash for removed entries exists, go until offset+length and copy the entries to it */ if (removed != NULL) { for ( ; pos < offset + length && p; pos++, p = p->pListNext) { entry = *((zval **)p->pData); Z_ADDREF_P(entry); if (p->nKeyLength == 0) { zend_hash_next_index_insert(*removed, &entry, sizeof(zval *), NULL); } else { zend_hash_quick_update(*removed, p->arKey, p->nKeyLength, p->h, &entry, sizeof(zval *), NULL); } } } else { /* otherwise just skip those entries */ for ( ; pos < offset + length && p; pos++, p = p->pListNext); } /* If there are entries to insert.. */ if (list != NULL) { /* ..for each one, create a new zval, copy entry into it and copy it into the output hash */ for (i = 0; i < list_count; i++) { entry = *list[i]; Z_ADDREF_P(entry); zend_hash_next_index_insert(out_hash, &entry, sizeof(zval *), NULL); } } /* Copy the remaining input hash entries to the output hash */ for ( ; p ; p = p->pListNext) { entry = *((zval **)p->pData); Z_ADDREF_P(entry); if (p->nKeyLength == 0) { zend_hash_next_index_insert(out_hash, &entry, sizeof(zval *), NULL); } else { zend_hash_quick_update(out_hash, p->arKey, p->nKeyLength, p->h, &entry, sizeof(zval *), NULL); } } zend_hash_internal_pointer_reset(out_hash); return out_hash; } /* }}} */ /* {{{ proto int array_push(array stack, mixed var [, mixed ...]) Pushes elements onto the end of the array */ PHP_FUNCTION(array_push) { zval ***args, /* Function arguments array */ *stack, /* Input array */ *new_var; /* Variable to be pushed */ int i, /* Loop counter */ argc; /* Number of function arguments */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a+", &stack, &args, &argc) == FAILURE) { return; } /* For each subsequent argument, make it a reference, increase refcount, and add it to the end of the array */ for (i = 0; i < argc; i++) { new_var = *args[i]; Z_ADDREF_P(new_var); if (zend_hash_next_index_insert(Z_ARRVAL_P(stack), &new_var, sizeof(zval *), NULL) == FAILURE) { Z_DELREF_P(new_var); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot add element to the array as the next element is already occupied"); efree(args); RETURN_FALSE; } } /* Clean up and return the number of values in the stack */ efree(args); RETVAL_LONG(zend_hash_num_elements(Z_ARRVAL_P(stack))); } /* }}} */ /* {{{ void _phpi_pop(INTERNAL_FUNCTION_PARAMETERS, int off_the_end) */ static void _phpi_pop(INTERNAL_FUNCTION_PARAMETERS, int off_the_end) { zval *stack, /* Input stack */ **val; /* Value to be popped */ char *key = NULL; uint key_len = 0; ulong index; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &stack) == FAILURE) { return; } if (zend_hash_num_elements(Z_ARRVAL_P(stack)) == 0) { return; } /* Get the first or last value and copy it into the return value */ if (off_the_end) { zend_hash_internal_pointer_end(Z_ARRVAL_P(stack)); } else { zend_hash_internal_pointer_reset(Z_ARRVAL_P(stack)); } zend_hash_get_current_data(Z_ARRVAL_P(stack), (void **)&val); RETVAL_ZVAL(*val, 1, 0); /* Delete the first or last value */ zend_hash_get_current_key_ex(Z_ARRVAL_P(stack), &key, &key_len, &index, 0, NULL); if (key && Z_ARRVAL_P(stack) == &EG(symbol_table)) { zend_delete_global_variable(key, key_len - 1 TSRMLS_CC); } else { zend_hash_del_key_or_index(Z_ARRVAL_P(stack), key, key_len, index, (key) ? HASH_DEL_KEY : HASH_DEL_INDEX); } /* If we did a shift... re-index like it did before */ if (!off_the_end) { unsigned int k = 0; int should_rehash = 0; Bucket *p = Z_ARRVAL_P(stack)->pListHead; while (p != NULL) { if (p->nKeyLength == 0) { if (p->h != k) { p->h = k++; should_rehash = 1; } else { k++; } } p = p->pListNext; } Z_ARRVAL_P(stack)->nNextFreeElement = k; if (should_rehash) { zend_hash_rehash(Z_ARRVAL_P(stack)); } } else if (!key_len && index >= Z_ARRVAL_P(stack)->nNextFreeElement - 1) { Z_ARRVAL_P(stack)->nNextFreeElement = Z_ARRVAL_P(stack)->nNextFreeElement - 1; } zend_hash_internal_pointer_reset(Z_ARRVAL_P(stack)); } /* }}} */ /* {{{ proto mixed array_pop(array stack) Pops an element off the end of the array */ PHP_FUNCTION(array_pop) { _phpi_pop(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto mixed array_shift(array stack) Pops an element off the beginning of the array */ PHP_FUNCTION(array_shift) { _phpi_pop(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto int array_unshift(array stack, mixed var [, mixed ...]) Pushes elements onto the beginning of the array */ PHP_FUNCTION(array_unshift) { zval ***args, /* Function arguments array */ *stack; /* Input stack */ HashTable *new_hash; /* New hashtable for the stack */ HashTable old_hash; int argc; /* Number of function arguments */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a+", &stack, &args, &argc) == FAILURE) { return; } /* Use splice to insert the elements at the beginning. Destroy old * hashtable and replace it with new one */ new_hash = php_splice(Z_ARRVAL_P(stack), 0, 0, &args[0], argc, NULL); old_hash = *Z_ARRVAL_P(stack); if (Z_ARRVAL_P(stack) == &EG(symbol_table)) { zend_reset_all_cv(&EG(symbol_table) TSRMLS_CC); } *Z_ARRVAL_P(stack) = *new_hash; FREE_HASHTABLE(new_hash); zend_hash_destroy(&old_hash); /* Clean up and return the number of elements in the stack */ efree(args); RETVAL_LONG(zend_hash_num_elements(Z_ARRVAL_P(stack))); } /* }}} */ /* {{{ proto array array_splice(array input, int offset [, int length [, array replacement]]) Removes the elements designated by offset and length and replace them with supplied array */ PHP_FUNCTION(array_splice) { zval *array, /* Input array */ *repl_array = NULL, /* Replacement array */ ***repl = NULL; /* Replacement elements */ HashTable *new_hash = NULL, /* Output array's hash */ **rem_hash = NULL; /* Removed elements' hash */ HashTable old_hash; Bucket *p; /* Bucket used for traversing hash */ long i, offset, length = 0, repl_num = 0; /* Number of replacement elements */ int num_in; /* Number of elements in the input array */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "al|lz/", &array, &offset, &length, &repl_array) == FAILURE) { return; } num_in = zend_hash_num_elements(Z_ARRVAL_P(array)); if (ZEND_NUM_ARGS() < 3) { length = num_in; } if (ZEND_NUM_ARGS() == 4) { /* Make sure the last argument, if passed, is an array */ convert_to_array(repl_array); /* Create the array of replacement elements */ repl_num = zend_hash_num_elements(Z_ARRVAL_P(repl_array)); repl = (zval ***)safe_emalloc(repl_num, sizeof(zval **), 0); for (p = Z_ARRVAL_P(repl_array)->pListHead, i = 0; p; p = p->pListNext, i++) { repl[i] = ((zval **)p->pData); } } /* Don't create the array of removed elements if it's not going * to be used; e.g. only removing and/or replacing elements */ if (return_value_used) { int size = length; /* Clamp the offset.. */ if (offset > num_in) { offset = num_in; } else if (offset < 0 && (offset = (num_in + offset)) < 0) { offset = 0; } /* ..and the length */ if (length < 0) { size = num_in - offset + length; } else if (((unsigned long) offset + (unsigned long) length) > (unsigned) num_in) { size = num_in - offset; } /* Initialize return value */ array_init_size(return_value, size > 0 ? size : 0); rem_hash = &Z_ARRVAL_P(return_value); } /* Perform splice */ new_hash = php_splice(Z_ARRVAL_P(array), offset, length, repl, repl_num, rem_hash); /* Replace input array's hashtable with the new one */ old_hash = *Z_ARRVAL_P(array); if (Z_ARRVAL_P(array) == &EG(symbol_table)) { zend_reset_all_cv(&EG(symbol_table) TSRMLS_CC); } *Z_ARRVAL_P(array) = *new_hash; FREE_HASHTABLE(new_hash); zend_hash_destroy(&old_hash); /* Clean up */ if (ZEND_NUM_ARGS() == 4) { efree(repl); } } /* }}} */ /* {{{ proto array array_slice(array input, int offset [, int length [, bool preserve_keys]]) Returns elements specified by offset and length */ PHP_FUNCTION(array_slice) { zval *input, /* Input array */ **z_length = NULL, /* How many elements to get */ **entry; /* An array entry */ long offset, /* Offset to get elements from */ length = 0; zend_bool preserve_keys = 0; /* Whether to preserve keys while copying to the new array or not */ int num_in, /* Number of elements in the input array */ pos; /* Current position in the array */ char *string_key; uint string_key_len; ulong num_key; HashPosition hpos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "al|Zb", &input, &offset, &z_length, &preserve_keys) == FAILURE) { return; } /* Get number of entries in the input hash */ num_in = zend_hash_num_elements(Z_ARRVAL_P(input)); /* We want all entries from offset to the end if length is not passed or is null */ if (ZEND_NUM_ARGS() < 3 || Z_TYPE_PP(z_length) == IS_NULL) { length = num_in; } else { convert_to_long_ex(z_length); length = Z_LVAL_PP(z_length); } /* Clamp the offset.. */ if (offset > num_in) { array_init(return_value); return; } else if (offset < 0 && (offset = (num_in + offset)) < 0) { offset = 0; } /* ..and the length */ if (length < 0) { length = num_in - offset + length; } else if (((unsigned long) offset + (unsigned long) length) > (unsigned) num_in) { length = num_in - offset; } /* Initialize returned array */ array_init_size(return_value, length > 0 ? length : 0); if (length <= 0) { return; } /* Start at the beginning and go until we hit offset */ pos = 0; zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &hpos); while (pos < offset && zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &hpos) == SUCCESS) { pos++; zend_hash_move_forward_ex(Z_ARRVAL_P(input), &hpos); } /* Copy elements from input array to the one that's returned */ while (pos < offset + length && zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &hpos) == SUCCESS) { zval_add_ref(entry); switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(input), &string_key, &string_key_len, &num_key, 0, &hpos)) { case HASH_KEY_IS_STRING: zend_hash_update(Z_ARRVAL_P(return_value), string_key, string_key_len, entry, sizeof(zval *), NULL); break; case HASH_KEY_IS_LONG: if (preserve_keys) { zend_hash_index_update(Z_ARRVAL_P(return_value), num_key, entry, sizeof(zval *), NULL); } else { zend_hash_next_index_insert(Z_ARRVAL_P(return_value), entry, sizeof(zval *), NULL); } break; } pos++; zend_hash_move_forward_ex(Z_ARRVAL_P(input), &hpos); } } /* }}} */ PHPAPI int php_array_merge(HashTable *dest, HashTable *src, int recursive TSRMLS_DC) /* {{{ */ { zval **src_entry, **dest_entry; char *string_key; uint string_key_len; ulong num_key; HashPosition pos; zend_hash_internal_pointer_reset_ex(src, &pos); while (zend_hash_get_current_data_ex(src, (void **)&src_entry, &pos) == SUCCESS) { switch (zend_hash_get_current_key_ex(src, &string_key, &string_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_STRING: if (recursive && zend_hash_find(dest, string_key, string_key_len, (void **)&dest_entry) == SUCCESS) { HashTable *thash = Z_TYPE_PP(dest_entry) == IS_ARRAY ? Z_ARRVAL_PP(dest_entry) : NULL; if ((thash && thash->nApplyCount > 1) || (*src_entry == *dest_entry && Z_ISREF_PP(dest_entry) && (Z_REFCOUNT_PP(dest_entry) % 2))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); return 0; } SEPARATE_ZVAL(dest_entry); SEPARATE_ZVAL(src_entry); if (Z_TYPE_PP(dest_entry) == IS_NULL) { convert_to_array_ex(dest_entry); add_next_index_null(*dest_entry); } else { convert_to_array_ex(dest_entry); } if (Z_TYPE_PP(src_entry) == IS_NULL) { convert_to_array_ex(src_entry); add_next_index_null(*src_entry); } else { convert_to_array_ex(src_entry); } if (thash) { thash->nApplyCount++; } if (!php_array_merge(Z_ARRVAL_PP(dest_entry), Z_ARRVAL_PP(src_entry), recursive TSRMLS_CC)) { if (thash) { thash->nApplyCount--; } return 0; } if (thash) { thash->nApplyCount--; } } else { Z_ADDREF_PP(src_entry); zend_hash_update(dest, string_key, string_key_len, src_entry, sizeof(zval *), NULL); } break; case HASH_KEY_IS_LONG: Z_ADDREF_PP(src_entry); zend_hash_next_index_insert(dest, src_entry, sizeof(zval *), NULL); break; } zend_hash_move_forward_ex(src, &pos); } return 1; } /* }}} */ PHPAPI int php_array_replace_recursive(HashTable *dest, HashTable *src TSRMLS_DC) /* {{{ */ { zval **src_entry, **dest_entry; char *string_key; uint string_key_len; ulong num_key; HashPosition pos; for (zend_hash_internal_pointer_reset_ex(src, &pos); zend_hash_get_current_data_ex(src, (void **)&src_entry, &pos) == SUCCESS; zend_hash_move_forward_ex(src, &pos)) { switch (zend_hash_get_current_key_ex(src, &string_key, &string_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_STRING: if (Z_TYPE_PP(src_entry) != IS_ARRAY || zend_hash_find(dest, string_key, string_key_len, (void **)&dest_entry) == FAILURE || Z_TYPE_PP(dest_entry) != IS_ARRAY) { Z_ADDREF_PP(src_entry); zend_hash_update(dest, string_key, string_key_len, src_entry, sizeof(zval *), NULL); continue; } break; case HASH_KEY_IS_LONG: if (Z_TYPE_PP(src_entry) != IS_ARRAY || zend_hash_index_find(dest, num_key, (void **)&dest_entry) == FAILURE || Z_TYPE_PP(dest_entry) != IS_ARRAY) { Z_ADDREF_PP(src_entry); zend_hash_index_update(dest, num_key, src_entry, sizeof(zval *), NULL); continue; } break; } if (Z_ARRVAL_PP(dest_entry)->nApplyCount > 1 || Z_ARRVAL_PP(src_entry)->nApplyCount > 1 || (*src_entry == *dest_entry && Z_ISREF_PP(dest_entry) && (Z_REFCOUNT_PP(dest_entry) % 2))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); return 0; } SEPARATE_ZVAL(dest_entry); Z_ARRVAL_PP(dest_entry)->nApplyCount++; Z_ARRVAL_PP(src_entry)->nApplyCount++; if (!php_array_replace_recursive(Z_ARRVAL_PP(dest_entry), Z_ARRVAL_PP(src_entry) TSRMLS_CC)) { Z_ARRVAL_PP(dest_entry)->nApplyCount--; Z_ARRVAL_PP(src_entry)->nApplyCount--; return 0; } Z_ARRVAL_PP(dest_entry)->nApplyCount--; Z_ARRVAL_PP(src_entry)->nApplyCount--; } return 1; } /* }}} */ static void php_array_merge_or_replace_wrapper(INTERNAL_FUNCTION_PARAMETERS, int recursive, int replace) /* {{{ */ { zval ***args = NULL; int argc, i, init_size = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &argc) == FAILURE) { return; } for (i = 0; i < argc; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is not an array", i + 1); efree(args); RETURN_NULL(); } else { int num = zend_hash_num_elements(Z_ARRVAL_PP(args[i])); if (num > init_size) { init_size = num; } } } array_init_size(return_value, init_size); for (i = 0; i < argc; i++) { SEPARATE_ZVAL(args[i]); if (!replace) { php_array_merge(Z_ARRVAL_P(return_value), Z_ARRVAL_PP(args[i]), recursive TSRMLS_CC); } else if (recursive && i > 0) { /* First array will be copied directly instead */ php_array_replace_recursive(Z_ARRVAL_P(return_value), Z_ARRVAL_PP(args[i]) TSRMLS_CC); } else { zend_hash_merge(Z_ARRVAL_P(return_value), Z_ARRVAL_PP(args[i]), (copy_ctor_func_t) zval_add_ref, NULL, sizeof(zval *), 1); } } efree(args); } /* }}} */ /* {{{ proto array array_merge(array arr1, array arr2 [, array ...]) Merges elements from passed arrays into one array */ PHP_FUNCTION(array_merge) { php_array_merge_or_replace_wrapper(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0, 0); } /* }}} */ /* {{{ proto array array_merge_recursive(array arr1, array arr2 [, array ...]) Recursively merges elements from passed arrays into one array */ PHP_FUNCTION(array_merge_recursive) { php_array_merge_or_replace_wrapper(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1, 0); } /* }}} */ /* {{{ proto array array_replace(array arr1, array arr2 [, array ...]) Replaces elements from passed arrays into one array */ PHP_FUNCTION(array_replace) { php_array_merge_or_replace_wrapper(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0, 1); } /* }}} */ /* {{{ proto array array_replace_recursive(array arr1, array arr2 [, array ...]) Recursively replaces elements from passed arrays into one array */ PHP_FUNCTION(array_replace_recursive) { php_array_merge_or_replace_wrapper(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1, 1); } /* }}} */ /* {{{ proto array array_keys(array input [, mixed search_value[, bool strict]]) Return just the keys from the input array, optionally only for the specified search_value */ PHP_FUNCTION(array_keys) { zval *input, /* Input array */ *search_value = NULL, /* Value to search for */ **entry, /* An entry in the input array */ res, /* Result of comparison */ *new_val; /* New value */ int add_key; /* Flag to indicate whether a key should be added */ char *string_key; /* String key */ uint string_key_len; ulong num_key; /* Numeric key */ zend_bool strict = 0; /* do strict comparison */ HashPosition pos; int (*is_equal_func)(zval *, zval *, zval * TSRMLS_DC) = is_equal_function; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|zb", &input, &search_value, &strict) == FAILURE) { return; } if (strict) { is_equal_func = is_identical_function; } /* Initialize return array */ if (search_value != NULL) { array_init(return_value); } else { array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(input))); } add_key = 1; /* Go through input array and add keys to the return array */ zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &pos) == SUCCESS) { if (search_value != NULL) { is_equal_func(&res, search_value, *entry TSRMLS_CC); add_key = zval_is_true(&res); } if (add_key) { MAKE_STD_ZVAL(new_val); switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(input), &string_key, &string_key_len, &num_key, 1, &pos)) { case HASH_KEY_IS_STRING: ZVAL_STRINGL(new_val, string_key, string_key_len - 1, 0); zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &new_val, sizeof(zval *), NULL); break; case HASH_KEY_IS_LONG: Z_TYPE_P(new_val) = IS_LONG; Z_LVAL_P(new_val) = num_key; zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &new_val, sizeof(zval *), NULL); break; } } zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos); } } /* }}} */ /* {{{ proto array array_values(array input) Return just the values from the input array */ PHP_FUNCTION(array_values) { zval *input, /* Input array */ **entry; /* An entry in the input array */ HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &input) == FAILURE) { return; } /* Initialize return array */ array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(input))); /* Go through input array and add values to the return array */ zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &pos) == SUCCESS) { zval_add_ref(entry); zend_hash_next_index_insert(Z_ARRVAL_P(return_value), entry, sizeof(zval *), NULL); zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos); } } /* }}} */ /* {{{ proto array array_count_values(array input) Return the value as key and the frequency of that value in input as value */ PHP_FUNCTION(array_count_values) { zval *input, /* Input array */ **entry, /* An entry in the input array */ **tmp; HashTable *myht; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &input) == FAILURE) { return; } /* Initialize return array */ array_init(return_value); /* Go through input array and add values to the return array */ myht = Z_ARRVAL_P(input); zend_hash_internal_pointer_reset_ex(myht, &pos); while (zend_hash_get_current_data_ex(myht, (void **)&entry, &pos) == SUCCESS) { if (Z_TYPE_PP(entry) == IS_LONG) { if (zend_hash_index_find(Z_ARRVAL_P(return_value), Z_LVAL_PP(entry), (void **)&tmp) == FAILURE) { zval *data; MAKE_STD_ZVAL(data); ZVAL_LONG(data, 1); zend_hash_index_update(Z_ARRVAL_P(return_value), Z_LVAL_PP(entry), &data, sizeof(data), NULL); } else { Z_LVAL_PP(tmp)++; } } else if (Z_TYPE_PP(entry) == IS_STRING) { if (zend_symtable_find(Z_ARRVAL_P(return_value), Z_STRVAL_PP(entry), Z_STRLEN_PP(entry) + 1, (void**)&tmp) == FAILURE) { zval *data; MAKE_STD_ZVAL(data); ZVAL_LONG(data, 1); zend_symtable_update(Z_ARRVAL_P(return_value), Z_STRVAL_PP(entry), Z_STRLEN_PP(entry) + 1, &data, sizeof(data), NULL); } else { Z_LVAL_PP(tmp)++; } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can only count STRING and INTEGER values!"); } zend_hash_move_forward_ex(myht, &pos); } } /* }}} */ /* {{{ proto array array_reverse(array input [, bool preserve keys]) Return input as a new array with the order of the entries reversed */ PHP_FUNCTION(array_reverse) { zval *input, /* Input array */ **entry; /* An entry in the input array */ char *string_key; uint string_key_len; ulong num_key; zend_bool preserve_keys = 0; /* whether to preserve keys */ HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|b", &input, &preserve_keys) == FAILURE) { return; } /* Initialize return array */ array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(input))); zend_hash_internal_pointer_end_ex(Z_ARRVAL_P(input), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &pos) == SUCCESS) { zval_add_ref(entry); switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(input), &string_key, &string_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_STRING: zend_hash_update(Z_ARRVAL_P(return_value), string_key, string_key_len, entry, sizeof(zval *), NULL); break; case HASH_KEY_IS_LONG: if (preserve_keys) { zend_hash_index_update(Z_ARRVAL_P(return_value), num_key, entry, sizeof(zval *), NULL); } else { zend_hash_next_index_insert(Z_ARRVAL_P(return_value), entry, sizeof(zval *), NULL); } break; } zend_hash_move_backwards_ex(Z_ARRVAL_P(input), &pos); } } /* }}} */ /* {{{ proto array array_pad(array input, int pad_size, mixed pad_value) Returns a copy of input array padded with pad_value to size pad_size */ PHP_FUNCTION(array_pad) { zval *input; /* Input array */ zval *pad_value; /* Padding value obviously */ zval ***pads; /* Array to pass to splice */ HashTable *new_hash;/* Return value from splice */ HashTable old_hash; long pad_size; /* Size to pad to */ long pad_size_abs; /* Absolute value of pad_size */ int input_size; /* Size of the input array */ int num_pads; /* How many pads do we need */ int do_pad; /* Whether we should do padding at all */ int i; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "alz", &input, &pad_size, &pad_value) == FAILURE) { return; } /* Do some initial calculations */ input_size = zend_hash_num_elements(Z_ARRVAL_P(input)); pad_size_abs = abs(pad_size); if (pad_size_abs < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You may only pad up to 1048576 elements at a time"); zval_dtor(return_value); RETURN_FALSE; } do_pad = (input_size >= pad_size_abs) ? 0 : 1; /* Copy the original array */ RETVAL_ZVAL(input, 1, 0); /* If no need to pad, no need to continue */ if (!do_pad) { return; } /* Populate the pads array */ num_pads = pad_size_abs - input_size; if (num_pads > 1048576) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You may only pad up to 1048576 elements at a time"); zval_dtor(return_value); RETURN_FALSE; } pads = (zval ***)safe_emalloc(num_pads, sizeof(zval **), 0); for (i = 0; i < num_pads; i++) { pads[i] = &pad_value; } /* Pad on the right or on the left */ if (pad_size > 0) { new_hash = php_splice(Z_ARRVAL_P(return_value), input_size, 0, pads, num_pads, NULL); } else { new_hash = php_splice(Z_ARRVAL_P(return_value), 0, 0, pads, num_pads, NULL); } /* Copy the result hash into return value */ old_hash = *Z_ARRVAL_P(return_value); if (Z_ARRVAL_P(return_value) == &EG(symbol_table)) { zend_reset_all_cv(&EG(symbol_table) TSRMLS_CC); } *Z_ARRVAL_P(return_value) = *new_hash; FREE_HASHTABLE(new_hash); zend_hash_destroy(&old_hash); /* Clean up */ efree(pads); } /* }}} */ /* {{{ proto array array_flip(array input) Return array with key <-> value flipped */ PHP_FUNCTION(array_flip) { zval *array, **entry, *data; char *string_key; uint str_key_len; ulong num_key; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) { return; } array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(array))); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(array), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(array), (void **)&entry, &pos) == SUCCESS) { MAKE_STD_ZVAL(data); switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(array), &string_key, &str_key_len, &num_key, 1, &pos)) { case HASH_KEY_IS_STRING: ZVAL_STRINGL(data, string_key, str_key_len - 1, 0); break; case HASH_KEY_IS_LONG: Z_TYPE_P(data) = IS_LONG; Z_LVAL_P(data) = num_key; break; } if (Z_TYPE_PP(entry) == IS_LONG) { zend_hash_index_update(Z_ARRVAL_P(return_value), Z_LVAL_PP(entry), &data, sizeof(data), NULL); } else if (Z_TYPE_PP(entry) == IS_STRING) { zend_symtable_update(Z_ARRVAL_P(return_value), Z_STRVAL_PP(entry), Z_STRLEN_PP(entry) + 1, &data, sizeof(data), NULL); } else { zval_ptr_dtor(&data); /* will free also zval structure */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can only flip STRING and INTEGER values!"); } zend_hash_move_forward_ex(Z_ARRVAL_P(array), &pos); } } /* }}} */ /* {{{ proto array array_change_key_case(array input [, int case=CASE_LOWER]) Retuns an array with all string keys lowercased [or uppercased] */ PHP_FUNCTION(array_change_key_case) { zval *array, **entry; char *string_key; char *new_key; uint str_key_len; ulong num_key; long change_to_upper=0; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &change_to_upper) == FAILURE) { return; } array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(array))); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(array), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(array), (void **)&entry, &pos) == SUCCESS) { zval_add_ref(entry); switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(array), &string_key, &str_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_LONG: zend_hash_index_update(Z_ARRVAL_P(return_value), num_key, entry, sizeof(entry), NULL); break; case HASH_KEY_IS_STRING: new_key = estrndup(string_key, str_key_len - 1); if (change_to_upper) { php_strtoupper(new_key, str_key_len - 1); } else { php_strtolower(new_key, str_key_len - 1); } zend_hash_update(Z_ARRVAL_P(return_value), new_key, str_key_len, entry, sizeof(entry), NULL); efree(new_key); break; } zend_hash_move_forward_ex(Z_ARRVAL_P(array), &pos); } } /* }}} */ /* {{{ proto array array_unique(array input [, int sort_flags]) Removes duplicate values from array */ PHP_FUNCTION(array_unique) { zval *array, *tmp; Bucket *p; struct bucketindex { Bucket *b; unsigned int i; }; struct bucketindex *arTmp, *cmpdata, *lastkept; unsigned int i; long sort_type = PHP_SORT_STRING; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { return; } php_set_compare_func(sort_type TSRMLS_CC); array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(array))); zend_hash_copy(Z_ARRVAL_P(return_value), Z_ARRVAL_P(array), (copy_ctor_func_t) zval_add_ref, (void *)&tmp, sizeof(zval*)); if (Z_ARRVAL_P(array)->nNumOfElements <= 1) { /* nothing to do */ return; } /* create and sort array with pointers to the target_hash buckets */ arTmp = (struct bucketindex *) pemalloc((Z_ARRVAL_P(array)->nNumOfElements + 1) * sizeof(struct bucketindex), Z_ARRVAL_P(array)->persistent); if (!arTmp) { zval_dtor(return_value); RETURN_FALSE; } for (i = 0, p = Z_ARRVAL_P(array)->pListHead; p; i++, p = p->pListNext) { arTmp[i].b = p; arTmp[i].i = i; } arTmp[i].b = NULL; zend_qsort((void *) arTmp, i, sizeof(struct bucketindex), php_array_data_compare TSRMLS_CC); /* go through the sorted array and delete duplicates from the copy */ lastkept = arTmp; for (cmpdata = arTmp + 1; cmpdata->b; cmpdata++) { if (php_array_data_compare(lastkept, cmpdata TSRMLS_CC)) { lastkept = cmpdata; } else { if (lastkept->i > cmpdata->i) { p = lastkept->b; lastkept = cmpdata; } else { p = cmpdata->b; } if (p->nKeyLength == 0) { zend_hash_index_del(Z_ARRVAL_P(return_value), p->h); } else { if (Z_ARRVAL_P(return_value) == &EG(symbol_table)) { zend_delete_global_variable(p->arKey, p->nKeyLength - 1 TSRMLS_CC); } else { zend_hash_quick_del(Z_ARRVAL_P(return_value), p->arKey, p->nKeyLength, p->h); } } } } pefree(arTmp, Z_ARRVAL_P(array)->persistent); } /* }}} */ static int zval_compare(zval **a, zval **b TSRMLS_DC) /* {{{ */ { zval result; zval *first; zval *second; first = *((zval **) a); second = *((zval **) b); if (string_compare_function(&result, first, second TSRMLS_CC) == FAILURE) { return 0; } if (Z_TYPE(result) == IS_DOUBLE) { if (Z_DVAL(result) < 0) { return -1; } else if (Z_DVAL(result) > 0) { return 1; } else { return 0; } } convert_to_long(&result); if (Z_LVAL(result) < 0) { return -1; } else if (Z_LVAL(result) > 0) { return 1; } return 0; } /* }}} */ static int zval_user_compare(zval **a, zval **b TSRMLS_DC) /* {{{ */ { zval **args[2]; zval *retval_ptr; args[0] = (zval **) a; args[1] = (zval **) b; BG(user_compare_fci).param_count = 2; BG(user_compare_fci).params = args; BG(user_compare_fci).retval_ptr_ptr = &retval_ptr; BG(user_compare_fci).no_separation = 0; if (zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache) TSRMLS_CC) == SUCCESS && retval_ptr) { long retval; convert_to_long_ex(&retval_ptr); retval = Z_LVAL_P(retval_ptr); zval_ptr_dtor(&retval_ptr); return retval < 0 ? -1 : retval > 0 ? 1 : 0;; } else { return 0; } } /* }}} */ static void php_array_intersect_key(INTERNAL_FUNCTION_PARAMETERS, int data_compare_type) /* {{{ */ { Bucket *p; int argc, i; zval ***args; int (*intersect_data_compare_func)(zval **, zval ** TSRMLS_DC) = NULL; zend_bool ok; zval **data; int req_args; char *param_spec; /* Get the argument count */ argc = ZEND_NUM_ARGS(); if (data_compare_type == INTERSECT_COMP_DATA_USER) { /* INTERSECT_COMP_DATA_USER - array_uintersect_assoc() */ req_args = 3; param_spec = "+f"; intersect_data_compare_func = zval_user_compare; } else { /* INTERSECT_COMP_DATA_NONE - array_intersect_key() INTERSECT_COMP_DATA_INTERNAL - array_intersect_assoc() */ req_args = 2; param_spec = "+"; if (data_compare_type == INTERSECT_COMP_DATA_INTERNAL) { intersect_data_compare_func = zval_compare; } } if (argc < req_args) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least %d parameters are required, %d given", req_args, argc); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, param_spec, &args, &argc, &BG(user_compare_fci), &BG(user_compare_fci_cache)) == FAILURE) { return; } for (i = 0; i < argc; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is not an array", i + 1); RETVAL_NULL(); goto out; } } array_init(return_value); for (p = Z_ARRVAL_PP(args[0])->pListHead; p != NULL; p = p->pListNext) { if (p->nKeyLength == 0) { ok = 1; for (i = 1; i < argc; i++) { if (zend_hash_index_find(Z_ARRVAL_PP(args[i]), p->h, (void**)&data) == FAILURE || (intersect_data_compare_func && intersect_data_compare_func((zval**)p->pData, data TSRMLS_CC) != 0) ) { ok = 0; break; } } if (ok) { Z_ADDREF_PP((zval**)p->pData); zend_hash_index_update(Z_ARRVAL_P(return_value), p->h, p->pData, sizeof(zval*), NULL); } } else { ok = 1; for (i = 1; i < argc; i++) { if (zend_hash_quick_find(Z_ARRVAL_PP(args[i]), p->arKey, p->nKeyLength, p->h, (void**)&data) == FAILURE || (intersect_data_compare_func && intersect_data_compare_func((zval**)p->pData, data TSRMLS_CC) != 0) ) { ok = 0; break; } } if (ok) { Z_ADDREF_PP((zval**)p->pData); zend_hash_quick_update(Z_ARRVAL_P(return_value), p->arKey, p->nKeyLength, p->h, p->pData, sizeof(zval*), NULL); } } } out: efree(args); } /* }}} */ static void php_array_intersect(INTERNAL_FUNCTION_PARAMETERS, int behavior, int data_compare_type, int key_compare_type) /* {{{ */ { zval ***args = NULL; HashTable *hash; int arr_argc, i, c = 0; Bucket ***lists, **list, ***ptrs, *p; int req_args; char *param_spec; zend_fcall_info fci1, fci2; zend_fcall_info_cache fci1_cache = empty_fcall_info_cache, fci2_cache = empty_fcall_info_cache; zend_fcall_info *fci_key, *fci_data; zend_fcall_info_cache *fci_key_cache, *fci_data_cache; PHP_ARRAY_CMP_FUNC_VARS; int (*intersect_key_compare_func)(const void *, const void * TSRMLS_DC); int (*intersect_data_compare_func)(const void *, const void * TSRMLS_DC); if (behavior == INTERSECT_NORMAL) { intersect_key_compare_func = php_array_key_compare; if (data_compare_type == INTERSECT_COMP_DATA_INTERNAL) { /* array_intersect() */ req_args = 2; param_spec = "+"; intersect_data_compare_func = php_array_data_compare; } else if (data_compare_type == INTERSECT_COMP_DATA_USER) { /* array_uintersect() */ req_args = 3; param_spec = "+f"; intersect_data_compare_func = php_array_user_compare; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "data_compare_type is %d. This should never happen. Please report as a bug", data_compare_type); return; } if (ZEND_NUM_ARGS() < req_args) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least %d parameters are required, %d given", req_args, ZEND_NUM_ARGS()); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, param_spec, &args, &arr_argc, &fci1, &fci1_cache) == FAILURE) { return; } fci_data = &fci1; fci_data_cache = &fci1_cache; } else if (behavior & INTERSECT_ASSOC) { /* triggered also when INTERSECT_KEY */ /* INTERSECT_KEY is subset of INTERSECT_ASSOC. When having the former * no comparison of the data is done (part of INTERSECT_ASSOC) */ intersect_key_compare_func = php_array_key_compare; if (data_compare_type == INTERSECT_COMP_DATA_INTERNAL && key_compare_type == INTERSECT_COMP_KEY_INTERNAL) { /* array_intersect_assoc() or array_intersect_key() */ req_args = 2; param_spec = "+"; intersect_key_compare_func = php_array_key_compare; intersect_data_compare_func = php_array_data_compare; } else if (data_compare_type == INTERSECT_COMP_DATA_USER && key_compare_type == INTERSECT_COMP_KEY_INTERNAL) { /* array_uintersect_assoc() */ req_args = 3; param_spec = "+f"; intersect_key_compare_func = php_array_key_compare; intersect_data_compare_func = php_array_user_compare; fci_data = &fci1; fci_data_cache = &fci1_cache; } else if (data_compare_type == INTERSECT_COMP_DATA_INTERNAL && key_compare_type == INTERSECT_COMP_KEY_USER) { /* array_intersect_uassoc() or array_intersect_ukey() */ req_args = 3; param_spec = "+f"; intersect_key_compare_func = php_array_user_key_compare; intersect_data_compare_func = php_array_data_compare; fci_key = &fci1; fci_key_cache = &fci1_cache; } else if (data_compare_type == INTERSECT_COMP_DATA_USER && key_compare_type == INTERSECT_COMP_KEY_USER) { /* array_uintersect_uassoc() */ req_args = 4; param_spec = "+ff"; intersect_key_compare_func = php_array_user_key_compare; intersect_data_compare_func = php_array_user_compare; fci_data = &fci1; fci_data_cache = &fci1_cache; fci_key = &fci2; fci_key_cache = &fci2_cache; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "data_compare_type is %d. key_compare_type is %d. This should never happen. Please report as a bug", data_compare_type, key_compare_type); return; } if (ZEND_NUM_ARGS() < req_args) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least %d parameters are required, %d given", req_args, ZEND_NUM_ARGS()); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, param_spec, &args, &arr_argc, &fci1, &fci1_cache, &fci2, &fci2_cache) == FAILURE) { return; } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "behavior is %d. This should never happen. Please report as a bug", behavior); return; } PHP_ARRAY_CMP_FUNC_BACKUP(); /* for each argument, create and sort list with pointers to the hash buckets */ lists = (Bucket ***)safe_emalloc(arr_argc, sizeof(Bucket **), 0); ptrs = (Bucket ***)safe_emalloc(arr_argc, sizeof(Bucket **), 0); php_set_compare_func(PHP_SORT_STRING TSRMLS_CC); if (behavior == INTERSECT_NORMAL && data_compare_type == INTERSECT_COMP_DATA_USER) { BG(user_compare_fci) = *fci_data; BG(user_compare_fci_cache) = *fci_data_cache; } else if (behavior & INTERSECT_ASSOC && key_compare_type == INTERSECT_COMP_KEY_USER) { BG(user_compare_fci) = *fci_key; BG(user_compare_fci_cache) = *fci_key_cache; } for (i = 0; i < arr_argc; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is not an array", i + 1); arr_argc = i; /* only free up to i - 1 */ goto out; } hash = Z_ARRVAL_PP(args[i]); list = (Bucket **) pemalloc((hash->nNumOfElements + 1) * sizeof(Bucket *), hash->persistent); if (!list) { PHP_ARRAY_CMP_FUNC_RESTORE(); efree(ptrs); efree(lists); efree(args); RETURN_FALSE; } lists[i] = list; ptrs[i] = list; for (p = hash->pListHead; p; p = p->pListNext) { *list++ = p; } *list = NULL; if (behavior == INTERSECT_NORMAL) { zend_qsort((void *) lists[i], hash->nNumOfElements, sizeof(Bucket *), intersect_data_compare_func TSRMLS_CC); } else if (behavior & INTERSECT_ASSOC) { /* triggered also when INTERSECT_KEY */ zend_qsort((void *) lists[i], hash->nNumOfElements, sizeof(Bucket *), intersect_key_compare_func TSRMLS_CC); } } /* copy the argument array */ RETVAL_ZVAL(*args[0], 1, 0); if (return_value->value.ht == &EG(symbol_table)) { HashTable *ht; zval *tmp; ALLOC_HASHTABLE(ht); zend_hash_init(ht, zend_hash_num_elements(return_value->value.ht), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(ht, return_value->value.ht, (copy_ctor_func_t) zval_add_ref, (void *) &tmp, sizeof(zval *)); return_value->value.ht = ht; } /* go through the lists and look for common values */ while (*ptrs[0]) { if ((behavior & INTERSECT_ASSOC) /* triggered also when INTERSECT_KEY */ && key_compare_type == INTERSECT_COMP_KEY_USER) { BG(user_compare_fci) = *fci_key; BG(user_compare_fci_cache) = *fci_key_cache; } for (i = 1; i < arr_argc; i++) { if (behavior & INTERSECT_NORMAL) { while (*ptrs[i] && (0 < (c = intersect_data_compare_func(ptrs[0], ptrs[i] TSRMLS_CC)))) { ptrs[i]++; } } else if (behavior & INTERSECT_ASSOC) { /* triggered also when INTERSECT_KEY */ while (*ptrs[i] && (0 < (c = intersect_key_compare_func(ptrs[0], ptrs[i] TSRMLS_CC)))) { ptrs[i]++; } if ((!c && *ptrs[i]) && (behavior == INTERSECT_ASSOC)) { /* only when INTERSECT_ASSOC */ /* this means that ptrs[i] is not NULL so we can compare * and "c==0" is from last operation * in this branch of code we enter only when INTERSECT_ASSOC * since when we have INTERSECT_KEY compare of data is not wanted. */ if (data_compare_type == INTERSECT_COMP_DATA_USER) { BG(user_compare_fci) = *fci_data; BG(user_compare_fci_cache) = *fci_data_cache; } if (intersect_data_compare_func(ptrs[0], ptrs[i] TSRMLS_CC) != 0) { c = 1; if (key_compare_type == INTERSECT_COMP_KEY_USER) { BG(user_compare_fci) = *fci_key; BG(user_compare_fci_cache) = *fci_key_cache; /* When KEY_USER, the last parameter is always the callback */ } /* we are going to the break */ } else { /* continue looping */ } } } if (!*ptrs[i]) { /* delete any values corresponding to remains of ptrs[0] */ /* and exit because they do not present in at least one of */ /* the other arguments */ for (;;) { p = *ptrs[0]++; if (!p) { goto out; } if (p->nKeyLength == 0) { zend_hash_index_del(Z_ARRVAL_P(return_value), p->h); } else { zend_hash_quick_del(Z_ARRVAL_P(return_value), p->arKey, p->nKeyLength, p->h); } } } if (c) /* here we get if not all are equal */ break; ptrs[i]++; } if (c) { /* Value of ptrs[0] not in all arguments, delete all entries */ /* with value < value of ptrs[i] */ for (;;) { p = *ptrs[0]; if (p->nKeyLength == 0) { zend_hash_index_del(Z_ARRVAL_P(return_value), p->h); } else { zend_hash_quick_del(Z_ARRVAL_P(return_value), p->arKey, p->nKeyLength, p->h); } if (!*++ptrs[0]) { goto out; } if (behavior == INTERSECT_NORMAL) { if (0 <= intersect_data_compare_func(ptrs[0], ptrs[i] TSRMLS_CC)) { break; } } else if (behavior & INTERSECT_ASSOC) { /* triggered also when INTERSECT_KEY */ /* no need of looping because indexes are unique */ break; } } } else { /* ptrs[0] is present in all the arguments */ /* Skip all entries with same value as ptrs[0] */ for (;;) { if (!*++ptrs[0]) { goto out; } if (behavior == INTERSECT_NORMAL) { if (intersect_data_compare_func(ptrs[0] - 1, ptrs[0] TSRMLS_CC)) { break; } } else if (behavior & INTERSECT_ASSOC) { /* triggered also when INTERSECT_KEY */ /* no need of looping because indexes are unique */ break; } } } } out: for (i = 0; i < arr_argc; i++) { hash = Z_ARRVAL_PP(args[i]); pefree(lists[i], hash->persistent); } PHP_ARRAY_CMP_FUNC_RESTORE(); efree(ptrs); efree(lists); efree(args); } /* }}} */ /* {{{ proto array array_intersect_key(array arr1, array arr2 [, array ...]) Returns the entries of arr1 that have keys which are present in all the other arguments. Kind of equivalent to array_diff(array_keys($arr1), array_keys($arr2)[,array_keys(...)]). Equivalent of array_intersect_assoc() but does not do compare of the data. */ PHP_FUNCTION(array_intersect_key) { php_array_intersect_key(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_COMP_DATA_NONE); } /* }}} */ /* {{{ proto array array_intersect_ukey(array arr1, array arr2 [, array ...], callback key_compare_func) Returns the entries of arr1 that have keys which are present in all the other arguments. Kind of equivalent to array_diff(array_keys($arr1), array_keys($arr2)[,array_keys(...)]). The comparison of the keys is performed by a user supplied function. Equivalent of array_intersect_uassoc() but does not do compare of the data. */ PHP_FUNCTION(array_intersect_ukey) { php_array_intersect(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_KEY, INTERSECT_COMP_DATA_INTERNAL, INTERSECT_COMP_KEY_USER); } /* }}} */ /* {{{ proto array array_intersect(array arr1, array arr2 [, array ...]) Returns the entries of arr1 that have values which are present in all the other arguments */ PHP_FUNCTION(array_intersect) { php_array_intersect(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_NORMAL, INTERSECT_COMP_DATA_INTERNAL, INTERSECT_COMP_KEY_INTERNAL); } /* }}} */ /* {{{ proto array array_uintersect(array arr1, array arr2 [, array ...], callback data_compare_func) Returns the entries of arr1 that have values which are present in all the other arguments. Data is compared by using an user-supplied callback. */ PHP_FUNCTION(array_uintersect) { php_array_intersect(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_NORMAL, INTERSECT_COMP_DATA_USER, INTERSECT_COMP_KEY_INTERNAL); } /* }}} */ /* {{{ proto array array_intersect_assoc(array arr1, array arr2 [, array ...]) Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check */ PHP_FUNCTION(array_intersect_assoc) { php_array_intersect_key(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_COMP_DATA_INTERNAL); } /* }}} */ /* {{{ proto array array_intersect_uassoc(array arr1, array arr2 [, array ...], callback key_compare_func) U Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check and they are compared by using an user-supplied callback. */ PHP_FUNCTION(array_intersect_uassoc) { php_array_intersect(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_ASSOC, INTERSECT_COMP_DATA_INTERNAL, INTERSECT_COMP_KEY_USER); } /* }}} */ /* {{{ proto array array_uintersect_assoc(array arr1, array arr2 [, array ...], callback data_compare_func) U Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check. Data is compared by using an user-supplied callback. */ PHP_FUNCTION(array_uintersect_assoc) { php_array_intersect_key(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_COMP_DATA_USER); } /* }}} */ /* {{{ proto array array_uintersect_uassoc(array arr1, array arr2 [, array ...], callback data_compare_func, callback key_compare_func) Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check. Both data and keys are compared by using user-supplied callbacks. */ PHP_FUNCTION(array_uintersect_uassoc) { php_array_intersect(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_ASSOC, INTERSECT_COMP_DATA_USER, INTERSECT_COMP_KEY_USER); } /* }}} */ static void php_array_diff_key(INTERNAL_FUNCTION_PARAMETERS, int data_compare_type) /* {{{ */ { Bucket *p; int argc, i; zval ***args; int (*diff_data_compare_func)(zval **, zval ** TSRMLS_DC) = NULL; zend_bool ok; zval **data; /* Get the argument count */ argc = ZEND_NUM_ARGS(); if (data_compare_type == DIFF_COMP_DATA_USER) { if (argc < 3) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least 3 parameters are required, %d given", ZEND_NUM_ARGS()); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+f", &args, &argc, &BG(user_compare_fci), &BG(user_compare_fci_cache)) == FAILURE) { return; } diff_data_compare_func = zval_user_compare; } else { if (argc < 2) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least 2 parameters are required, %d given", ZEND_NUM_ARGS()); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &argc) == FAILURE) { return; } if (data_compare_type == DIFF_COMP_DATA_INTERNAL) { diff_data_compare_func = zval_compare; } } for (i = 0; i < argc; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is not an array", i + 1); RETVAL_NULL(); goto out; } } array_init(return_value); for (p = Z_ARRVAL_PP(args[0])->pListHead; p != NULL; p = p->pListNext) { if (p->nKeyLength == 0) { ok = 1; for (i = 1; i < argc; i++) { if (zend_hash_index_find(Z_ARRVAL_PP(args[i]), p->h, (void**)&data) == SUCCESS && (!diff_data_compare_func || diff_data_compare_func((zval**)p->pData, data TSRMLS_CC) == 0) ) { ok = 0; break; } } if (ok) { Z_ADDREF_PP((zval**)p->pData); zend_hash_index_update(Z_ARRVAL_P(return_value), p->h, p->pData, sizeof(zval*), NULL); } } else { ok = 1; for (i = 1; i < argc; i++) { if (zend_hash_quick_find(Z_ARRVAL_PP(args[i]), p->arKey, p->nKeyLength, p->h, (void**)&data) == SUCCESS && (!diff_data_compare_func || diff_data_compare_func((zval**)p->pData, data TSRMLS_CC) == 0) ) { ok = 0; break; } } if (ok) { Z_ADDREF_PP((zval**)p->pData); zend_hash_quick_update(Z_ARRVAL_P(return_value), p->arKey, p->nKeyLength, p->h, p->pData, sizeof(zval*), NULL); } } } out: efree(args); } /* }}} */ static void php_array_diff(INTERNAL_FUNCTION_PARAMETERS, int behavior, int data_compare_type, int key_compare_type) /* {{{ */ { zval ***args = NULL; HashTable *hash; int arr_argc, i, c; Bucket ***lists, **list, ***ptrs, *p; int req_args; char *param_spec; zend_fcall_info fci1, fci2; zend_fcall_info_cache fci1_cache = empty_fcall_info_cache, fci2_cache = empty_fcall_info_cache; zend_fcall_info *fci_key, *fci_data; zend_fcall_info_cache *fci_key_cache, *fci_data_cache; PHP_ARRAY_CMP_FUNC_VARS; int (*diff_key_compare_func)(const void *, const void * TSRMLS_DC); int (*diff_data_compare_func)(const void *, const void * TSRMLS_DC); if (behavior == DIFF_NORMAL) { diff_key_compare_func = php_array_key_compare; if (data_compare_type == DIFF_COMP_DATA_INTERNAL) { /* array_diff */ req_args = 2; param_spec = "+"; diff_data_compare_func = php_array_data_compare; } else if (data_compare_type == DIFF_COMP_DATA_USER) { /* array_udiff */ req_args = 3; param_spec = "+f"; diff_data_compare_func = php_array_user_compare; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "data_compare_type is %d. This should never happen. Please report as a bug", data_compare_type); return; } if (ZEND_NUM_ARGS() < req_args) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least %d parameters are required, %d given", req_args, ZEND_NUM_ARGS()); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, param_spec, &args, &arr_argc, &fci1, &fci1_cache) == FAILURE) { return; } fci_data = &fci1; fci_data_cache = &fci1_cache; } else if (behavior & DIFF_ASSOC) { /* triggered also if DIFF_KEY */ /* DIFF_KEY is subset of DIFF_ASSOC. When having the former * no comparison of the data is done (part of DIFF_ASSOC) */ if (data_compare_type == DIFF_COMP_DATA_INTERNAL && key_compare_type == DIFF_COMP_KEY_INTERNAL) { /* array_diff_assoc() or array_diff_key() */ req_args = 2; param_spec = "+"; diff_key_compare_func = php_array_key_compare; diff_data_compare_func = php_array_data_compare; } else if (data_compare_type == DIFF_COMP_DATA_USER && key_compare_type == DIFF_COMP_KEY_INTERNAL) { /* array_udiff_assoc() */ req_args = 3; param_spec = "+f"; diff_key_compare_func = php_array_key_compare; diff_data_compare_func = php_array_user_compare; fci_data = &fci1; fci_data_cache = &fci1_cache; } else if (data_compare_type == DIFF_COMP_DATA_INTERNAL && key_compare_type == DIFF_COMP_KEY_USER) { /* array_diff_uassoc() or array_diff_ukey() */ req_args = 3; param_spec = "+f"; diff_key_compare_func = php_array_user_key_compare; diff_data_compare_func = php_array_data_compare; fci_key = &fci1; fci_key_cache = &fci1_cache; } else if (data_compare_type == DIFF_COMP_DATA_USER && key_compare_type == DIFF_COMP_KEY_USER) { /* array_udiff_uassoc() */ req_args = 4; param_spec = "+ff"; diff_key_compare_func = php_array_user_key_compare; diff_data_compare_func = php_array_user_compare; fci_data = &fci1; fci_data_cache = &fci1_cache; fci_key = &fci2; fci_key_cache = &fci2_cache; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "data_compare_type is %d. key_compare_type is %d. This should never happen. Please report as a bug", data_compare_type, key_compare_type); return; } if (ZEND_NUM_ARGS() < req_args) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least %d parameters are required, %d given", req_args, ZEND_NUM_ARGS()); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, param_spec, &args, &arr_argc, &fci1, &fci1_cache, &fci2, &fci2_cache) == FAILURE) { return; } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "behavior is %d. This should never happen. Please report as a bug", behavior); return; } PHP_ARRAY_CMP_FUNC_BACKUP(); /* for each argument, create and sort list with pointers to the hash buckets */ lists = (Bucket ***)safe_emalloc(arr_argc, sizeof(Bucket **), 0); ptrs = (Bucket ***)safe_emalloc(arr_argc, sizeof(Bucket **), 0); php_set_compare_func(PHP_SORT_STRING TSRMLS_CC); if (behavior == DIFF_NORMAL && data_compare_type == DIFF_COMP_DATA_USER) { BG(user_compare_fci) = *fci_data; BG(user_compare_fci_cache) = *fci_data_cache; } else if (behavior & DIFF_ASSOC && key_compare_type == DIFF_COMP_KEY_USER) { BG(user_compare_fci) = *fci_key; BG(user_compare_fci_cache) = *fci_key_cache; } for (i = 0; i < arr_argc; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is not an array", i + 1); arr_argc = i; /* only free up to i - 1 */ goto out; } hash = Z_ARRVAL_PP(args[i]); list = (Bucket **) pemalloc((hash->nNumOfElements + 1) * sizeof(Bucket *), hash->persistent); if (!list) { PHP_ARRAY_CMP_FUNC_RESTORE(); efree(ptrs); efree(lists); efree(args); RETURN_FALSE; } lists[i] = list; ptrs[i] = list; for (p = hash->pListHead; p; p = p->pListNext) { *list++ = p; } *list = NULL; if (behavior == DIFF_NORMAL) { zend_qsort((void *) lists[i], hash->nNumOfElements, sizeof(Bucket *), diff_data_compare_func TSRMLS_CC); } else if (behavior & DIFF_ASSOC) { /* triggered also when DIFF_KEY */ zend_qsort((void *) lists[i], hash->nNumOfElements, sizeof(Bucket *), diff_key_compare_func TSRMLS_CC); } } /* copy the argument array */ RETVAL_ZVAL(*args[0], 1, 0); if (return_value->value.ht == &EG(symbol_table)) { HashTable *ht; zval *tmp; ALLOC_HASHTABLE(ht); zend_hash_init(ht, zend_hash_num_elements(return_value->value.ht), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(ht, return_value->value.ht, (copy_ctor_func_t) zval_add_ref, (void *) &tmp, sizeof(zval *)); return_value->value.ht = ht; } /* go through the lists and look for values of ptr[0] that are not in the others */ while (*ptrs[0]) { if ((behavior & DIFF_ASSOC) /* triggered also when DIFF_KEY */ && key_compare_type == DIFF_COMP_KEY_USER ) { BG(user_compare_fci) = *fci_key; BG(user_compare_fci_cache) = *fci_key_cache; } c = 1; for (i = 1; i < arr_argc; i++) { Bucket **ptr = ptrs[i]; if (behavior == DIFF_NORMAL) { while (*ptrs[i] && (0 < (c = diff_data_compare_func(ptrs[0], ptrs[i] TSRMLS_CC)))) { ptrs[i]++; } } else if (behavior & DIFF_ASSOC) { /* triggered also when DIFF_KEY */ while (*ptr && (0 != (c = diff_key_compare_func(ptrs[0], ptr TSRMLS_CC)))) { ptr++; } } if (!c) { if (behavior == DIFF_NORMAL) { if (*ptrs[i]) { ptrs[i]++; } break; } else if (behavior == DIFF_ASSOC) { /* only when DIFF_ASSOC */ /* In this branch is execute only when DIFF_ASSOC. If behavior == DIFF_KEY * data comparison is not needed - skipped. */ if (*ptr) { if (data_compare_type == DIFF_COMP_DATA_USER) { BG(user_compare_fci) = *fci_data; BG(user_compare_fci_cache) = *fci_data_cache; } if (diff_data_compare_func(ptrs[0], ptr TSRMLS_CC) != 0) { /* the data is not the same */ c = -1; if (key_compare_type == DIFF_COMP_KEY_USER) { BG(user_compare_fci) = *fci_key; BG(user_compare_fci_cache) = *fci_key_cache; } } else { break; /* we have found the element in other arrays thus we don't want it * in the return_value -> delete from there */ } } } else if (behavior == DIFF_KEY) { /* only when DIFF_KEY */ /* the behavior here differs from INTERSECT_KEY in php_intersect * since in the "diff" case we have to remove the entry from * return_value while when doing intersection the entry must not * be deleted. */ break; /* remove the key */ } } } if (!c) { /* ptrs[0] in one of the other arguments */ /* delete all entries with value as ptrs[0] */ for (;;) { p = *ptrs[0]; if (p->nKeyLength == 0) { zend_hash_index_del(Z_ARRVAL_P(return_value), p->h); } else { zend_hash_quick_del(Z_ARRVAL_P(return_value), p->arKey, p->nKeyLength, p->h); } if (!*++ptrs[0]) { goto out; } if (behavior == DIFF_NORMAL) { if (diff_data_compare_func(ptrs[0] - 1, ptrs[0] TSRMLS_CC)) { break; } } else if (behavior & DIFF_ASSOC) { /* triggered also when DIFF_KEY */ /* in this case no array_key_compare is needed */ break; } } } else { /* ptrs[0] in none of the other arguments */ /* skip all entries with value as ptrs[0] */ for (;;) { if (!*++ptrs[0]) { goto out; } if (behavior == DIFF_NORMAL) { if (diff_data_compare_func(ptrs[0] - 1, ptrs[0] TSRMLS_CC)) { break; } } else if (behavior & DIFF_ASSOC) { /* triggered also when DIFF_KEY */ /* in this case no array_key_compare is needed */ break; } } } } out: for (i = 0; i < arr_argc; i++) { hash = Z_ARRVAL_PP(args[i]); pefree(lists[i], hash->persistent); } PHP_ARRAY_CMP_FUNC_RESTORE(); efree(ptrs); efree(lists); efree(args); } /* }}} */ /* {{{ proto array array_diff_key(array arr1, array arr2 [, array ...]) Returns the entries of arr1 that have keys which are not present in any of the others arguments. This function is like array_diff() but works on the keys instead of the values. The associativity is preserved. */ PHP_FUNCTION(array_diff_key) { php_array_diff_key(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_COMP_DATA_NONE); } /* }}} */ /* {{{ proto array array_diff_ukey(array arr1, array arr2 [, array ...], callback key_comp_func) Returns the entries of arr1 that have keys which are not present in any of the others arguments. User supplied function is used for comparing the keys. This function is like array_udiff() but works on the keys instead of the values. The associativity is preserved. */ PHP_FUNCTION(array_diff_ukey) { php_array_diff(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_KEY, DIFF_COMP_DATA_INTERNAL, DIFF_COMP_KEY_USER); } /* }}} */ /* {{{ proto array array_diff(array arr1, array arr2 [, array ...]) Returns the entries of arr1 that have values which are not present in any of the others arguments. */ PHP_FUNCTION(array_diff) { php_array_diff(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_NORMAL, DIFF_COMP_DATA_INTERNAL, DIFF_COMP_KEY_INTERNAL); } /* }}} */ /* {{{ proto array array_udiff(array arr1, array arr2 [, array ...], callback data_comp_func) Returns the entries of arr1 that have values which are not present in any of the others arguments. Elements are compared by user supplied function. */ PHP_FUNCTION(array_udiff) { php_array_diff(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_NORMAL, DIFF_COMP_DATA_USER, DIFF_COMP_KEY_INTERNAL); } /* }}} */ /* {{{ proto array array_diff_assoc(array arr1, array arr2 [, array ...]) Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal */ PHP_FUNCTION(array_diff_assoc) { php_array_diff_key(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_COMP_DATA_INTERNAL); } /* }}} */ /* {{{ proto array array_diff_uassoc(array arr1, array arr2 [, array ...], callback data_comp_func) Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal. Elements are compared by user supplied function. */ PHP_FUNCTION(array_diff_uassoc) { php_array_diff(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_ASSOC, DIFF_COMP_DATA_INTERNAL, DIFF_COMP_KEY_USER); } /* }}} */ /* {{{ proto array array_udiff_assoc(array arr1, array arr2 [, array ...], callback key_comp_func) Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal. Keys are compared by user supplied function. */ PHP_FUNCTION(array_udiff_assoc) { php_array_diff_key(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_COMP_DATA_USER); } /* }}} */ /* {{{ proto array array_udiff_uassoc(array arr1, array arr2 [, array ...], callback data_comp_func, callback key_comp_func) Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal. Keys and elements are compared by user supplied functions. */ PHP_FUNCTION(array_udiff_uassoc) { php_array_diff(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_ASSOC, DIFF_COMP_DATA_USER, DIFF_COMP_KEY_USER); } /* }}} */ #define MULTISORT_ORDER 0 #define MULTISORT_TYPE 1 #define MULTISORT_LAST 2 PHPAPI int php_multisort_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { Bucket **ab = *(Bucket ***)a; Bucket **bb = *(Bucket ***)b; int r; int result = 0; zval temp; r = 0; do { php_set_compare_func(ARRAYG(multisort_flags)[MULTISORT_TYPE][r] TSRMLS_CC); ARRAYG(compare_func)(&temp, *((zval **)ab[r]->pData), *((zval **)bb[r]->pData) TSRMLS_CC); result = ARRAYG(multisort_flags)[MULTISORT_ORDER][r] * Z_LVAL(temp); if (result != 0) { return result; } r++; } while (ab[r] != NULL); return result; } /* }}} */ #define MULTISORT_ABORT \ for (k = 0; k < MULTISORT_LAST; k++) \ efree(ARRAYG(multisort_flags)[k]); \ efree(arrays); \ efree(args); \ RETURN_FALSE; /* {{{ proto bool array_multisort(array ar1 [, SORT_ASC|SORT_DESC [, SORT_REGULAR|SORT_NUMERIC|SORT_STRING|SORT_NATURAL|SORT_FLAG_CASE]] [, array ar2 [, SORT_ASC|SORT_DESC [, SORT_REGULAR|SORT_NUMERIC|SORT_STRING|SORT_NATURAL|SORT_FLAG_CASE]], ...]) Sort multiple arrays at once similar to how ORDER BY clause works in SQL */ PHP_FUNCTION(array_multisort) { zval*** args; zval*** arrays; Bucket*** indirect; Bucket* p; HashTable* hash; int argc; int array_size; int num_arrays = 0; int parse_state[MULTISORT_LAST]; /* 0 - flag not allowed 1 - flag allowed */ int sort_order = PHP_SORT_ASC; int sort_type = PHP_SORT_REGULAR; int i, k; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &argc) == FAILURE) { return; } /* Allocate space for storing pointers to input arrays and sort flags. */ arrays = (zval ***)ecalloc(argc, sizeof(zval **)); for (i = 0; i < MULTISORT_LAST; i++) { parse_state[i] = 0; ARRAYG(multisort_flags)[i] = (int *)ecalloc(argc, sizeof(int)); } /* Here we go through the input arguments and parse them. Each one can * be either an array or a sort flag which follows an array. If not * specified, the sort flags defaults to PHP_SORT_ASC and PHP_SORT_REGULAR * accordingly. There can't be two sort flags of the same type after an * array, and the very first argument has to be an array. */ for (i = 0; i < argc; i++) { if (Z_TYPE_PP(args[i]) == IS_ARRAY) { /* We see the next array, so we update the sort flags of * the previous array and reset the sort flags. */ if (i > 0) { ARRAYG(multisort_flags)[MULTISORT_ORDER][num_arrays - 1] = sort_order; ARRAYG(multisort_flags)[MULTISORT_TYPE][num_arrays - 1] = sort_type; sort_order = PHP_SORT_ASC; sort_type = PHP_SORT_REGULAR; } arrays[num_arrays++] = args[i]; /* Next one may be an array or a list of sort flags. */ for (k = 0; k < MULTISORT_LAST; k++) { parse_state[k] = 1; } } else if (Z_TYPE_PP(args[i]) == IS_LONG) { switch (Z_LVAL_PP(args[i]) & ~PHP_SORT_FLAG_CASE) { case PHP_SORT_ASC: case PHP_SORT_DESC: /* flag allowed here */ if (parse_state[MULTISORT_ORDER] == 1) { /* Save the flag and make sure then next arg is not the current flag. */ sort_order = Z_LVAL_PP(args[i]) == PHP_SORT_DESC ? -1 : 1; parse_state[MULTISORT_ORDER] = 0; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is expected to be an array or sorting flag that has not already been specified", i + 1); MULTISORT_ABORT; } break; case PHP_SORT_REGULAR: case PHP_SORT_NUMERIC: case PHP_SORT_STRING: case PHP_SORT_NATURAL: #if HAVE_STRCOLL case PHP_SORT_LOCALE_STRING: #endif /* flag allowed here */ if (parse_state[MULTISORT_TYPE] == 1) { /* Save the flag and make sure then next arg is not the current flag. */ sort_type = Z_LVAL_PP(args[i]); parse_state[MULTISORT_TYPE] = 0; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is expected to be an array or sorting flag that has not already been specified", i + 1); MULTISORT_ABORT; } break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is an unknown sort flag", i + 1); MULTISORT_ABORT; break; } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is expected to be an array or a sort flag", i + 1); MULTISORT_ABORT; } } /* Take care of the last array sort flags. */ ARRAYG(multisort_flags)[MULTISORT_ORDER][num_arrays - 1] = sort_order; ARRAYG(multisort_flags)[MULTISORT_TYPE][num_arrays - 1] = sort_type; /* Make sure the arrays are of the same size. */ array_size = zend_hash_num_elements(Z_ARRVAL_PP(arrays[0])); for (i = 0; i < num_arrays; i++) { if (zend_hash_num_elements(Z_ARRVAL_PP(arrays[i])) != array_size) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array sizes are inconsistent"); MULTISORT_ABORT; } } /* If all arrays are empty we don't need to do anything. */ if (array_size < 1) { for (k = 0; k < MULTISORT_LAST; k++) { efree(ARRAYG(multisort_flags)[k]); } efree(arrays); efree(args); RETURN_TRUE; } /* Create the indirection array. This array is of size MxN, where * M is the number of entries in each input array and N is the number * of the input arrays + 1. The last column is NULL to indicate the end * of the row. */ indirect = (Bucket ***)safe_emalloc(array_size, sizeof(Bucket **), 0); for (i = 0; i < array_size; i++) { indirect[i] = (Bucket **)safe_emalloc((num_arrays + 1), sizeof(Bucket *), 0); } for (i = 0; i < num_arrays; i++) { k = 0; for (p = Z_ARRVAL_PP(arrays[i])->pListHead; p; p = p->pListNext, k++) { indirect[k][i] = p; } } for (k = 0; k < array_size; k++) { indirect[k][num_arrays] = NULL; } /* Do the actual sort magic - bada-bim, bada-boom. */ zend_qsort(indirect, array_size, sizeof(Bucket **), php_multisort_compare TSRMLS_CC); /* Restructure the arrays based on sorted indirect - this is mostly taken from zend_hash_sort() function. */ HANDLE_BLOCK_INTERRUPTIONS(); for (i = 0; i < num_arrays; i++) { hash = Z_ARRVAL_PP(arrays[i]); hash->pListHead = indirect[0][i];; hash->pListTail = NULL; hash->pInternalPointer = hash->pListHead; for (k = 0; k < array_size; k++) { if (hash->pListTail) { hash->pListTail->pListNext = indirect[k][i]; } indirect[k][i]->pListLast = hash->pListTail; indirect[k][i]->pListNext = NULL; hash->pListTail = indirect[k][i]; } p = hash->pListHead; k = 0; while (p != NULL) { if (p->nKeyLength == 0) p->h = k++; p = p->pListNext; } hash->nNextFreeElement = array_size; zend_hash_rehash(hash); } HANDLE_UNBLOCK_INTERRUPTIONS(); /* Clean up. */ for (i = 0; i < array_size; i++) { efree(indirect[i]); } efree(indirect); for (k = 0; k < MULTISORT_LAST; k++) { efree(ARRAYG(multisort_flags)[k]); } efree(arrays); efree(args); RETURN_TRUE; } /* }}} */ /* {{{ proto mixed array_rand(array input [, int num_req]) Return key/keys for random entry/entries in the array */ PHP_FUNCTION(array_rand) { zval *input; long randval, num_req = 1; int num_avail, key_type; char *string_key; uint string_key_len; ulong num_key; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &input, &num_req) == FAILURE) { return; } num_avail = zend_hash_num_elements(Z_ARRVAL_P(input)); if (ZEND_NUM_ARGS() > 1) { if (num_req <= 0 || num_req > num_avail) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Second argument has to be between 1 and the number of elements in the array"); return; } } /* Make the return value an array only if we need to pass back more than one result. */ if (num_req > 1) { array_init_size(return_value, num_req); } /* We can't use zend_hash_index_find() because the array may have string keys or gaps. */ zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos); while (num_req && (key_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(input), &string_key, &string_key_len, &num_key, 0, &pos)) != HASH_KEY_NON_EXISTANT) { randval = php_rand(TSRMLS_C); if ((double) (randval / (PHP_RAND_MAX + 1.0)) < (double) num_req / (double) num_avail) { /* If we are returning a single result, just do it. */ if (Z_TYPE_P(return_value) != IS_ARRAY) { if (key_type == HASH_KEY_IS_STRING) { RETURN_STRINGL(string_key, string_key_len - 1, 1); } else { RETURN_LONG(num_key); } } else { /* Append the result to the return value. */ if (key_type == HASH_KEY_IS_STRING) { add_next_index_stringl(return_value, string_key, string_key_len - 1, 1); } else { add_next_index_long(return_value, num_key); } } num_req--; } num_avail--; zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos); } } /* }}} */ /* {{{ proto mixed array_sum(array input) Returns the sum of the array entries */ PHP_FUNCTION(array_sum) { zval *input, **entry, entry_n; HashPosition pos; double dval; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &input) == FAILURE) { return; } ZVAL_LONG(return_value, 0); for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos); zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &pos) == SUCCESS; zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos) ) { if (Z_TYPE_PP(entry) == IS_ARRAY || Z_TYPE_PP(entry) == IS_OBJECT) { continue; } entry_n = **entry; zval_copy_ctor(&entry_n); convert_scalar_to_number(&entry_n TSRMLS_CC); if (Z_TYPE(entry_n) == IS_LONG && Z_TYPE_P(return_value) == IS_LONG) { dval = (double)Z_LVAL_P(return_value) + (double)Z_LVAL(entry_n); if ( (double)LONG_MIN <= dval && dval <= (double)LONG_MAX ) { Z_LVAL_P(return_value) += Z_LVAL(entry_n); continue; } } convert_to_double(return_value); convert_to_double(&entry_n); Z_DVAL_P(return_value) += Z_DVAL(entry_n); } } /* }}} */ /* {{{ proto mixed array_product(array input) Returns the product of the array entries */ PHP_FUNCTION(array_product) { zval *input, **entry, entry_n; HashPosition pos; double dval; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &input) == FAILURE) { return; } ZVAL_LONG(return_value, 1); if (!zend_hash_num_elements(Z_ARRVAL_P(input))) { return; } for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos); zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &pos) == SUCCESS; zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos) ) { if (Z_TYPE_PP(entry) == IS_ARRAY || Z_TYPE_PP(entry) == IS_OBJECT) { continue; } entry_n = **entry; zval_copy_ctor(&entry_n); convert_scalar_to_number(&entry_n TSRMLS_CC); if (Z_TYPE(entry_n) == IS_LONG && Z_TYPE_P(return_value) == IS_LONG) { dval = (double)Z_LVAL_P(return_value) * (double)Z_LVAL(entry_n); if ( (double)LONG_MIN <= dval && dval <= (double)LONG_MAX ) { Z_LVAL_P(return_value) *= Z_LVAL(entry_n); continue; } } convert_to_double(return_value); convert_to_double(&entry_n); Z_DVAL_P(return_value) *= Z_DVAL(entry_n); } } /* }}} */ /* {{{ proto mixed array_reduce(array input, mixed callback [, mixed initial]) Iteratively reduce the array to a single value via the callback. */ PHP_FUNCTION(array_reduce) { zval *input; zval **args[2]; zval **operand; zval *result = NULL; zval *retval; zend_fcall_info fci; zend_fcall_info_cache fci_cache = empty_fcall_info_cache; zval *initial = NULL; HashPosition pos; HashTable *htbl; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "af|z", &input, &fci, &fci_cache, &initial) == FAILURE) { return; } if (ZEND_NUM_ARGS() > 2) { ALLOC_ZVAL(result); MAKE_COPY_ZVAL(&initial, result); } else { MAKE_STD_ZVAL(result); ZVAL_NULL(result); } /* (zval **)input points to an element of argument stack * the base pointer of which is subject to change. * thus we need to keep the pointer to the hashtable for safety */ htbl = Z_ARRVAL_P(input); if (zend_hash_num_elements(htbl) == 0) { if (result) { RETVAL_ZVAL(result, 1, 1); } return; } fci.retval_ptr_ptr = &retval; fci.param_count = 2; fci.no_separation = 0; zend_hash_internal_pointer_reset_ex(htbl, &pos); while (zend_hash_get_current_data_ex(htbl, (void **)&operand, &pos) == SUCCESS) { if (result) { args[0] = &result; args[1] = operand; fci.params = args; if (zend_call_function(&fci, &fci_cache TSRMLS_CC) == SUCCESS && retval) { zval_ptr_dtor(&result); result = retval; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "An error occurred while invoking the reduction callback"); return; } } else { result = *operand; zval_add_ref(&result); } zend_hash_move_forward_ex(htbl, &pos); } RETVAL_ZVAL(result, 1, 1); } /* }}} */ /* {{{ proto array array_filter(array input [, mixed callback]) Filters elements from the array via the callback. */ PHP_FUNCTION(array_filter) { zval *array; zval **operand; zval **args[1]; zval *retval = NULL; zend_bool have_callback = 0; char *string_key; zend_fcall_info fci = empty_fcall_info; zend_fcall_info_cache fci_cache = empty_fcall_info_cache; uint string_key_len; ulong num_key; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|f", &array, &fci, &fci_cache) == FAILURE) { return; } array_init(return_value); if (zend_hash_num_elements(Z_ARRVAL_P(array)) == 0) { return; } if (ZEND_NUM_ARGS() > 1) { have_callback = 1; fci.no_separation = 0; fci.retval_ptr_ptr = &retval; fci.param_count = 1; } for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(array), &pos); zend_hash_get_current_data_ex(Z_ARRVAL_P(array), (void **)&operand, &pos) == SUCCESS; zend_hash_move_forward_ex(Z_ARRVAL_P(array), &pos) ) { if (have_callback) { args[0] = operand; fci.params = args; if (zend_call_function(&fci, &fci_cache TSRMLS_CC) == SUCCESS && retval) { if (!zend_is_true(retval)) { zval_ptr_dtor(&retval); continue; } else { zval_ptr_dtor(&retval); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "An error occurred while invoking the filter callback"); return; } } else if (!zend_is_true(*operand)) { continue; } zval_add_ref(operand); switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(array), &string_key, &string_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_STRING: zend_hash_update(Z_ARRVAL_P(return_value), string_key, string_key_len, operand, sizeof(zval *), NULL); break; case HASH_KEY_IS_LONG: zend_hash_index_update(Z_ARRVAL_P(return_value), num_key, operand, sizeof(zval *), NULL); break; } } } /* }}} */ /* {{{ proto array array_map(mixed callback, array input1 [, array input2 ,...]) Applies the callback to the elements in given arrays. */ PHP_FUNCTION(array_map) { zval ***arrays = NULL; int n_arrays = 0; zval ***params; zval *result, *null; HashPosition *array_pos; zval **args; zend_fcall_info fci = empty_fcall_info; zend_fcall_info_cache fci_cache = empty_fcall_info_cache; int i, k, maxlen = 0; int *array_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "f!+", &fci, &fci_cache, &arrays, &n_arrays) == FAILURE) { return; } RETVAL_NULL(); args = (zval **)safe_emalloc(n_arrays, sizeof(zval *), 0); array_len = (int *)safe_emalloc(n_arrays, sizeof(int), 0); array_pos = (HashPosition *)safe_emalloc(n_arrays, sizeof(HashPosition), 0); for (i = 0; i < n_arrays; i++) { if (Z_TYPE_PP(arrays[i]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d should be an array", i + 2); efree(arrays); efree(args); efree(array_len); efree(array_pos); return; } SEPARATE_ZVAL_IF_NOT_REF(arrays[i]); args[i] = *arrays[i]; array_len[i] = zend_hash_num_elements(Z_ARRVAL_PP(arrays[i])); if (array_len[i] > maxlen) { maxlen = array_len[i]; } zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(arrays[i]), &array_pos[i]); } efree(arrays); /* Short-circuit: if no callback and only one array, just return it. */ if (!ZEND_FCI_INITIALIZED(fci) && n_arrays == 1) { RETVAL_ZVAL(args[0], 1, 0); efree(array_len); efree(array_pos); efree(args); return; } array_init_size(return_value, maxlen); params = (zval ***)safe_emalloc(n_arrays, sizeof(zval **), 0); MAKE_STD_ZVAL(null); ZVAL_NULL(null); /* We iterate through all the arrays at once. */ for (k = 0; k < maxlen; k++) { uint str_key_len; ulong num_key; char *str_key; int key_type = 0; /* If no callback, the result will be an array, consisting of current * entries from all arrays. */ if (!ZEND_FCI_INITIALIZED(fci)) { MAKE_STD_ZVAL(result); array_init_size(result, n_arrays); } for (i = 0; i < n_arrays; i++) { /* If this array still has elements, add the current one to the * parameter list, otherwise use null value. */ if (k < array_len[i]) { zend_hash_get_current_data_ex(Z_ARRVAL_P(args[i]), (void **)&params[i], &array_pos[i]); /* It is safe to store only last value of key type, because * this loop will run just once if there is only 1 array. */ if (n_arrays == 1) { key_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(args[0]), &str_key, &str_key_len, &num_key, 0, &array_pos[i]); } zend_hash_move_forward_ex(Z_ARRVAL_P(args[i]), &array_pos[i]); } else { params[i] = &null; } if (!ZEND_FCI_INITIALIZED(fci)) { zval_add_ref(params[i]); add_next_index_zval(result, *params[i]); } } if (ZEND_FCI_INITIALIZED(fci)) { fci.retval_ptr_ptr = &result; fci.param_count = n_arrays; fci.params = params; fci.no_separation = 0; if (zend_call_function(&fci, &fci_cache TSRMLS_CC) != SUCCESS || !result) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "An error occurred while invoking the map callback"); efree(array_len); efree(args); efree(array_pos); zval_dtor(return_value); zval_ptr_dtor(&null); efree(params); RETURN_NULL(); } } if (n_arrays > 1) { add_next_index_zval(return_value, result); } else { if (key_type == HASH_KEY_IS_STRING) { add_assoc_zval_ex(return_value, str_key, str_key_len, result); } else { add_index_zval(return_value, num_key, result); } } } zval_ptr_dtor(&null); efree(params); efree(array_len); efree(array_pos); efree(args); } /* }}} */ /* {{{ proto bool array_key_exists(mixed key, array search) Checks if the given key or index exists in the array */ PHP_FUNCTION(array_key_exists) { zval *key; /* key to check for */ HashTable *array; /* array to check in */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zH", &key, &array) == FAILURE) { return; } switch (Z_TYPE_P(key)) { case IS_STRING: if (zend_symtable_exists(array, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1)) { RETURN_TRUE; } RETURN_FALSE; case IS_LONG: if (zend_hash_index_exists(array, Z_LVAL_P(key))) { RETURN_TRUE; } RETURN_FALSE; case IS_NULL: if (zend_hash_exists(array, "", 1)) { RETURN_TRUE; } RETURN_FALSE; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "The first argument should be either a string or an integer"); RETURN_FALSE; } } /* }}} */ /* {{{ proto array array_chunk(array input, int size [, bool preserve_keys]) Split array into chunks */ PHP_FUNCTION(array_chunk) { int argc = ZEND_NUM_ARGS(), key_type, num_in; long size, current = 0; char *str_key; uint str_key_len; ulong num_key; zend_bool preserve_keys = 0; zval *input = NULL; zval *chunk = NULL; zval **entry; HashPosition pos; if (zend_parse_parameters(argc TSRMLS_CC, "al|b", &input, &size, &preserve_keys) == FAILURE) { return; } /* Do bounds checking for size parameter. */ if (size < 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Size parameter expected to be greater than 0"); return; } num_in = zend_hash_num_elements(Z_ARRVAL_P(input)); if (size > num_in) { size = num_in > 0 ? num_in : 1; } array_init_size(return_value, ((num_in - 1) / size) + 1); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void**)&entry, &pos) == SUCCESS) { /* If new chunk, create and initialize it. */ if (!chunk) { MAKE_STD_ZVAL(chunk); array_init_size(chunk, size); } /* Add entry to the chunk, preserving keys if necessary. */ zval_add_ref(entry); if (preserve_keys) { key_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(input), &str_key, &str_key_len, &num_key, 0, &pos); switch (key_type) { case HASH_KEY_IS_STRING: add_assoc_zval_ex(chunk, str_key, str_key_len, *entry); break; default: add_index_zval(chunk, num_key, *entry); break; } } else { add_next_index_zval(chunk, *entry); } /* If reached the chunk size, add it to the result array, and reset the * pointer. */ if (!(++current % size)) { add_next_index_zval(return_value, chunk); chunk = NULL; } zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos); } /* Add the final chunk if there is one. */ if (chunk) { add_next_index_zval(return_value, chunk); } } /* }}} */ /* {{{ proto array array_combine(array keys, array values) Creates an array by using the elements of the first parameter as keys and the elements of the second as the corresponding values */ PHP_FUNCTION(array_combine) { zval *values, *keys; HashPosition pos_values, pos_keys; zval **entry_keys, **entry_values; int num_keys, num_values; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "aa", &keys, &values) == FAILURE) { return; } num_keys = zend_hash_num_elements(Z_ARRVAL_P(keys)); num_values = zend_hash_num_elements(Z_ARRVAL_P(values)); if (num_keys != num_values) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Both parameters should have an equal number of elements"); RETURN_FALSE; } array_init_size(return_value, num_keys); if (!num_keys) { return; } zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(keys), &pos_keys); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(values), &pos_values); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(keys), (void **)&entry_keys, &pos_keys) == SUCCESS && zend_hash_get_current_data_ex(Z_ARRVAL_P(values), (void **)&entry_values, &pos_values) == SUCCESS ) { if (Z_TYPE_PP(entry_keys) == IS_LONG) { zval_add_ref(entry_values); add_index_zval(return_value, Z_LVAL_PP(entry_keys), *entry_values); } else { zval key, *key_ptr = *entry_keys; if (Z_TYPE_PP(entry_keys) != IS_STRING) { key = **entry_keys; zval_copy_ctor(&key); convert_to_string(&key); key_ptr = &key; } zval_add_ref(entry_values); add_assoc_zval_ex(return_value, Z_STRVAL_P(key_ptr), Z_STRLEN_P(key_ptr) + 1, *entry_values); if (key_ptr != *entry_keys) { zval_dtor(&key); } } zend_hash_move_forward_ex(Z_ARRVAL_P(keys), &pos_keys); zend_hash_move_forward_ex(Z_ARRVAL_P(values), &pos_values); } } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2012-02-12-3d898cfa3f-af92365239.c
manybugs_data_21
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Christian Stocker <[email protected]> | | Rob Richards <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #if HAVE_LIBXML && HAVE_DOM #include "php_dom.h" #include <libxml/SAX.h> #ifdef LIBXML_SCHEMAS_ENABLED #include <libxml/relaxng.h> #include <libxml/xmlschemas.h> #endif typedef struct _idsIterator idsIterator; struct _idsIterator { xmlChar *elementId; xmlNode *element; }; #define DOM_LOAD_STRING 0 #define DOM_LOAD_FILE 1 /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_element, 0, 0, 1) ZEND_ARG_INFO(0, tagName) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_document_fragment, 0, 0, 0) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_text_node, 0, 0, 1) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_comment, 0, 0, 1) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_cdatasection, 0, 0, 1) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_processing_instruction, 0, 0, 2) ZEND_ARG_INFO(0, target) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_attribute, 0, 0, 1) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_entity_reference, 0, 0, 1) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_get_elements_by_tag_name, 0, 0, 1) ZEND_ARG_INFO(0, tagName) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_import_node, 0, 0, 2) ZEND_ARG_OBJ_INFO(0, importedNode, DOMNode, 0) ZEND_ARG_INFO(0, deep) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_element_ns, 0, 0, 2) ZEND_ARG_INFO(0, namespaceURI) ZEND_ARG_INFO(0, qualifiedName) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_attribute_ns, 0, 0, 2) ZEND_ARG_INFO(0, namespaceURI) ZEND_ARG_INFO(0, qualifiedName) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_get_elements_by_tag_name_ns, 0, 0, 2) ZEND_ARG_INFO(0, namespaceURI) ZEND_ARG_INFO(0, localName) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_get_element_by_id, 0, 0, 1) ZEND_ARG_INFO(0, elementId) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_adopt_node, 0, 0, 1) ZEND_ARG_OBJ_INFO(0, source, DOMNode, 0) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_normalize_document, 0, 0, 0) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_rename_node, 0, 0, 3) ZEND_ARG_OBJ_INFO(0, node, DOMNode, 0) ZEND_ARG_INFO(0, namespaceURI) ZEND_ARG_INFO(0, qualifiedName) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_load, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_save, 0, 0, 1) ZEND_ARG_INFO(0, file) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_loadxml, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_savexml, 0, 0, 0) ZEND_ARG_OBJ_INFO(0, node, DOMNode, 1) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_construct, 0, 0, 0) ZEND_ARG_INFO(0, version) ZEND_ARG_INFO(0, encoding) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_validate, 0, 0, 0) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_xinclude, 0, 0, 0) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_loadhtml, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_loadhtmlfile, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_savehtml, 0, 0, 0) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_savehtmlfile, 0, 0, 1) ZEND_ARG_INFO(0, file) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_schema_validate_file, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_schema_validate_xml, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_relaxNG_validate_file, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_relaxNG_validate_xml, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_registernodeclass, 0, 0, 2) ZEND_ARG_INFO(0, baseClass) ZEND_ARG_INFO(0, extendedClass) ZEND_END_ARG_INFO(); /* }}} */ /* * class DOMDocument extends DOMNode * * URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-i-Document * Since: */ const zend_function_entry php_dom_document_class_functions[] = { /* {{{ */ PHP_FALIAS(createElement, dom_document_create_element, arginfo_dom_document_create_element) PHP_FALIAS(createDocumentFragment, dom_document_create_document_fragment, arginfo_dom_document_create_document_fragment) PHP_FALIAS(createTextNode, dom_document_create_text_node, arginfo_dom_document_create_text_node) PHP_FALIAS(createComment, dom_document_create_comment, arginfo_dom_document_create_comment) PHP_FALIAS(createCDATASection, dom_document_create_cdatasection, arginfo_dom_document_create_cdatasection) PHP_FALIAS(createProcessingInstruction, dom_document_create_processing_instruction, arginfo_dom_document_create_processing_instruction) PHP_FALIAS(createAttribute, dom_document_create_attribute, arginfo_dom_document_create_attribute) PHP_FALIAS(createEntityReference, dom_document_create_entity_reference, arginfo_dom_document_create_entity_reference) PHP_FALIAS(getElementsByTagName, dom_document_get_elements_by_tag_name, arginfo_dom_document_get_elements_by_tag_name) PHP_FALIAS(importNode, dom_document_import_node, arginfo_dom_document_import_node) PHP_FALIAS(createElementNS, dom_document_create_element_ns, arginfo_dom_document_create_element_ns) PHP_FALIAS(createAttributeNS, dom_document_create_attribute_ns, arginfo_dom_document_create_attribute_ns) PHP_FALIAS(getElementsByTagNameNS, dom_document_get_elements_by_tag_name_ns, arginfo_dom_document_get_elements_by_tag_name_ns) PHP_FALIAS(getElementById, dom_document_get_element_by_id, arginfo_dom_document_get_element_by_id) PHP_FALIAS(adoptNode, dom_document_adopt_node, arginfo_dom_document_adopt_node) PHP_FALIAS(normalizeDocument, dom_document_normalize_document, arginfo_dom_document_normalize_document) PHP_FALIAS(renameNode, dom_document_rename_node, arginfo_dom_document_rename_node) PHP_ME(domdocument, load, arginfo_dom_document_load, ZEND_ACC_PUBLIC|ZEND_ACC_ALLOW_STATIC) PHP_FALIAS(save, dom_document_save, arginfo_dom_document_save) PHP_ME(domdocument, loadXML, arginfo_dom_document_loadxml, ZEND_ACC_PUBLIC|ZEND_ACC_ALLOW_STATIC) PHP_FALIAS(saveXML, dom_document_savexml, arginfo_dom_document_savexml) PHP_ME(domdocument, __construct, arginfo_dom_document_construct, ZEND_ACC_PUBLIC) PHP_FALIAS(validate, dom_document_validate, arginfo_dom_document_validate) PHP_FALIAS(xinclude, dom_document_xinclude, arginfo_dom_document_xinclude) #if defined(LIBXML_HTML_ENABLED) PHP_ME(domdocument, loadHTML, arginfo_dom_document_loadhtml, ZEND_ACC_PUBLIC|ZEND_ACC_ALLOW_STATIC) PHP_ME(domdocument, loadHTMLFile, arginfo_dom_document_loadhtmlfile, ZEND_ACC_PUBLIC|ZEND_ACC_ALLOW_STATIC) PHP_FALIAS(saveHTML, dom_document_save_html, arginfo_dom_document_savehtml) PHP_FALIAS(saveHTMLFile, dom_document_save_html_file, arginfo_dom_document_savehtmlfile) #endif /* defined(LIBXML_HTML_ENABLED) */ #if defined(LIBXML_SCHEMAS_ENABLED) PHP_FALIAS(schemaValidate, dom_document_schema_validate_file, arginfo_dom_document_schema_validate_file) PHP_FALIAS(schemaValidateSource, dom_document_schema_validate_xml, arginfo_dom_document_schema_validate_xml) PHP_FALIAS(relaxNGValidate, dom_document_relaxNG_validate_file, arginfo_dom_document_relaxNG_validate_file) PHP_FALIAS(relaxNGValidateSource, dom_document_relaxNG_validate_xml, arginfo_dom_document_relaxNG_validate_xml) #endif PHP_ME(domdocument, registerNodeClass, arginfo_dom_document_registernodeclass, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; /* }}} */ /* {{{ docType DOMDocumentType readonly=yes URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-B63ED1A31 Since: */ int dom_document_doctype_read(dom_object *obj, zval **retval TSRMLS_DC) { xmlDoc *docp; xmlDtdPtr dtdptr; int ret; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } ALLOC_ZVAL(*retval); dtdptr = xmlGetIntSubset(docp); if (!dtdptr) { ZVAL_NULL(*retval); return SUCCESS; } if (NULL == (*retval = php_dom_create_object((xmlNodePtr) dtdptr, &ret, NULL, *retval, obj TSRMLS_CC))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot create required DOM object"); return FAILURE; } return SUCCESS; } /* }}} */ /* {{{ implementation DOMImplementation readonly=yes URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1B793EBA Since: */ int dom_document_implementation_read(dom_object *obj, zval **retval TSRMLS_DC) { ALLOC_ZVAL(*retval); php_dom_create_implementation(retval TSRMLS_CC); return SUCCESS; } /* }}} */ /* {{{ documentElement DOMElement readonly=yes URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-87CD092 Since: */ int dom_document_document_element_read(dom_object *obj, zval **retval TSRMLS_DC) { xmlDoc *docp; xmlNode *root; int ret; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } ALLOC_ZVAL(*retval); root = xmlDocGetRootElement(docp); if (!root) { ZVAL_NULL(*retval); return SUCCESS; } if (NULL == (*retval = php_dom_create_object(root, &ret, NULL, *retval, obj TSRMLS_CC))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot create required DOM object"); return FAILURE; } return SUCCESS; } /* }}} */ /* {{{ encoding string URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-encoding Since: DOM Level 3 */ int dom_document_encoding_read(dom_object *obj, zval **retval TSRMLS_DC) { xmlDoc *docp; char *encoding; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } encoding = (char *) docp->encoding; ALLOC_ZVAL(*retval); if (encoding != NULL) { ZVAL_STRING(*retval, encoding, 1); } else { ZVAL_NULL(*retval); } return SUCCESS; } int dom_document_encoding_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; xmlDoc *docp; xmlCharEncodingHandlerPtr handler; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } if (newval->type != IS_STRING) { if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_string(newval); } handler = xmlFindCharEncodingHandler(Z_STRVAL_P(newval)); if (handler != NULL) { xmlCharEncCloseFunc(handler); if (docp->encoding != NULL) { xmlFree((xmlChar *)docp->encoding); } docp->encoding = xmlStrdup((const xmlChar *) Z_STRVAL_P(newval)); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Document Encoding"); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ standalone boolean readonly=no URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-standalone Since: DOM Level 3 */ int dom_document_standalone_read(dom_object *obj, zval **retval TSRMLS_DC) { xmlDoc *docp; int standalone; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } ALLOC_ZVAL(*retval); standalone = docp->standalone; ZVAL_BOOL(*retval, standalone); return SUCCESS; } int dom_document_standalone_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; xmlDoc *docp; int standalone; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_long(newval); standalone = Z_LVAL_P(newval); if (standalone > 0) { docp->standalone = 1; } else if (standalone < 0) { docp->standalone = -1; } else { docp->standalone = 0; } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ version string readonly=no URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-version Since: DOM Level 3 */ int dom_document_version_read(dom_object *obj, zval **retval TSRMLS_DC) { xmlDoc *docp; char *version; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } version = (char *) docp->version; ALLOC_ZVAL(*retval); if (version != NULL) { ZVAL_STRING(*retval, version, 1); } else { ZVAL_NULL(*retval); } return SUCCESS; } int dom_document_version_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; xmlDoc *docp; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } if (docp->version != NULL) { xmlFree((xmlChar *) docp->version ); } if (newval->type != IS_STRING) { if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_string(newval); } docp->version = xmlStrdup((const xmlChar *) Z_STRVAL_P(newval)); if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ strictErrorChecking boolean readonly=no URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-strictErrorChecking Since: DOM Level 3 */ int dom_document_strict_error_checking_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->stricterror); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_strict_error_checking_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->stricterror = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ formatOutput boolean readonly=no */ int dom_document_format_output_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->formatoutput); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_format_output_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->formatoutput = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ validateOnParse boolean readonly=no */ int dom_document_validate_on_parse_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->validateonparse); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_validate_on_parse_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->validateonparse = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ resolveExternals boolean readonly=no */ int dom_document_resolve_externals_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->resolveexternals); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_resolve_externals_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->resolveexternals = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ preserveWhiteSpace boolean readonly=no */ int dom_document_preserve_whitespace_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->preservewhitespace); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_preserve_whitespace_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->preservewhitespace = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ recover boolean readonly=no */ int dom_document_recover_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->recover); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_recover_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->recover = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ substituteEntities boolean readonly=no */ int dom_document_substitue_entities_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->substituteentities); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_substitue_entities_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->substituteentities = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ documentURI string readonly=no URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-documentURI Since: DOM Level 3 */ int dom_document_document_uri_read(dom_object *obj, zval **retval TSRMLS_DC) { xmlDoc *docp; char *url; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } ALLOC_ZVAL(*retval); url = (char *) docp->URL; if (url != NULL) { ZVAL_STRING(*retval, url, 1); } else { ZVAL_NULL(*retval); } return SUCCESS; } int dom_document_document_uri_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; xmlDoc *docp; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } if (docp->URL != NULL) { xmlFree((xmlChar *) docp->URL); } if (newval->type != IS_STRING) { if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_string(newval); } docp->URL = xmlStrdup((const xmlChar *) Z_STRVAL_P(newval)); if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ config DOMConfiguration readonly=yes URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-config Since: DOM Level 3 */ int dom_document_config_read(dom_object *obj, zval **retval TSRMLS_DC) { ALLOC_ZVAL(*retval); ZVAL_NULL(*retval); return SUCCESS; } /* }}} */ /* {{{ proto DOMElement dom_document_create_element(string tagName [, string value]); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-2141741547 Since: */ PHP_FUNCTION(dom_document_create_element) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp; dom_object *intern; int ret, name_len, value_len; char *name, *value = NULL; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|s", &id, dom_document_class_entry, &name, &name_len, &value, &value_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); if (xmlValidateName((xmlChar *) name, 0) != 0) { php_dom_throw_error(INVALID_CHARACTER_ERR, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } node = xmlNewDocNode(docp, NULL, name, value); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, node, &ret, intern); } /* }}} end dom_document_create_element */ /* {{{ proto DOMDocumentFragment dom_document_create_document_fragment(); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-35CB04B5 Since: */ PHP_FUNCTION(dom_document_create_document_fragment) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp; dom_object *intern; int ret; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &id, dom_document_class_entry) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); node = xmlNewDocFragment(docp); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, node, &ret, intern); } /* }}} end dom_document_create_document_fragment */ /* {{{ proto DOMText dom_document_create_text_node(string data); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1975348127 Since: */ PHP_FUNCTION(dom_document_create_text_node) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp; int ret, value_len; dom_object *intern; char *value; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &value, &value_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); node = xmlNewDocText(docp, (xmlChar *) value); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, node, &ret, intern); } /* }}} end dom_document_create_text_node */ /* {{{ proto DOMComment dom_document_create_comment(string data); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1334481328 Since: */ PHP_FUNCTION(dom_document_create_comment) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp; int ret, value_len; dom_object *intern; char *value; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &value, &value_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); node = xmlNewDocComment(docp, (xmlChar *) value); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, node, &ret, intern); } /* }}} end dom_document_create_comment */ /* {{{ proto DOMCdataSection dom_document_create_cdatasection(string data); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-D26C0AF8 Since: */ PHP_FUNCTION(dom_document_create_cdatasection) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp; int ret, value_len; dom_object *intern; char *value; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &value, &value_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); node = xmlNewCDataBlock(docp, (xmlChar *) value, value_len); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, node, &ret, intern); } /* }}} end dom_document_create_cdatasection */ /* {{{ proto DOMProcessingInstruction dom_document_create_processing_instruction(string target, string data); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-135944439 Since: */ PHP_FUNCTION(dom_document_create_processing_instruction) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp; int ret, value_len, name_len = 0; dom_object *intern; char *name, *value = NULL; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|s", &id, dom_document_class_entry, &name, &name_len, &value, &value_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); if (xmlValidateName((xmlChar *) name, 0) != 0) { php_dom_throw_error(INVALID_CHARACTER_ERR, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } node = xmlNewPI((xmlChar *) name, (xmlChar *) value); if (!node) { RETURN_FALSE; } node->doc = docp; DOM_RET_OBJ(rv, node, &ret, intern); } /* }}} end dom_document_create_processing_instruction */ /* {{{ proto DOMAttr dom_document_create_attribute(string name); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1084891198 Since: */ PHP_FUNCTION(dom_document_create_attribute) { zval *id, *rv = NULL; xmlAttrPtr node; xmlDocPtr docp; int ret, name_len; dom_object *intern; char *name; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &name, &name_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); if (xmlValidateName((xmlChar *) name, 0) != 0) { php_dom_throw_error(INVALID_CHARACTER_ERR, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } node = xmlNewDocProp(docp, (xmlChar *) name, NULL); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, (xmlNodePtr) node, &ret, intern); } /* }}} end dom_document_create_attribute */ /* {{{ proto DOMEntityReference dom_document_create_entity_reference(string name); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-392B75AE Since: */ PHP_FUNCTION(dom_document_create_entity_reference) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp = NULL; dom_object *intern; int ret, name_len; char *name; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &name, &name_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); if (xmlValidateName((xmlChar *) name, 0) != 0) { php_dom_throw_error(INVALID_CHARACTER_ERR, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } node = xmlNewReference(docp, name); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, (xmlNodePtr) node, &ret, intern); } /* }}} end dom_document_create_entity_reference */ /* {{{ proto DOMNodeList dom_document_get_elements_by_tag_name(string tagname); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-A6C9094 Since: */ PHP_FUNCTION(dom_document_get_elements_by_tag_name) { zval *id; xmlDocPtr docp; int name_len; dom_object *intern, *namednode; char *name; xmlChar *local; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &name, &name_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); php_dom_create_interator(return_value, DOM_NODELIST TSRMLS_CC); namednode = (dom_object *)zend_objects_get_address(return_value TSRMLS_CC); local = xmlCharStrndup(name, name_len); dom_namednode_iter(intern, 0, namednode, NULL, local, NULL TSRMLS_CC); } /* }}} end dom_document_get_elements_by_tag_name */ /* {{{ proto DOMNode dom_document_import_node(DOMNode importedNode, boolean deep); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Core-Document-importNode Since: DOM Level 2 */ PHP_FUNCTION(dom_document_import_node) { zval *rv = NULL; zval *id, *node; xmlDocPtr docp; xmlNodePtr nodep, retnodep; dom_object *intern, *nodeobj; int ret; long recursive = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO|l", &id, dom_document_class_entry, &node, dom_node_class_entry, &recursive) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); DOM_GET_OBJ(nodep, node, xmlNodePtr, nodeobj); if (nodep->type == XML_HTML_DOCUMENT_NODE || nodep->type == XML_DOCUMENT_NODE || nodep->type == XML_DOCUMENT_TYPE_NODE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot import: Node Type Not Supported"); RETURN_FALSE; } if (nodep->doc == docp) { retnodep = nodep; } else { if ((recursive == 0) && (nodep->type == XML_ELEMENT_NODE)) { recursive = 2; } retnodep = xmlDocCopyNode(nodep, docp, recursive); if (!retnodep) { RETURN_FALSE; } if ((retnodep->type == XML_ATTRIBUTE_NODE) && (nodep->ns != NULL)) { xmlNsPtr nsptr = NULL; xmlNodePtr root = xmlDocGetRootElement(docp); nsptr = xmlSearchNsByHref (nodep->doc, root, nodep->ns->href); if (nsptr == NULL) { int errorcode; nsptr = dom_get_ns(root, (char *) nodep->ns->href, &errorcode, (char *) nodep->ns->prefix); } xmlSetNs(retnodep, nsptr); } } DOM_RET_OBJ(rv, (xmlNodePtr) retnodep, &ret, intern); } /* }}} end dom_document_import_node */ /* {{{ proto DOMElement dom_document_create_element_ns(string namespaceURI, string qualifiedName [,string value]); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-DocCrElNS Since: DOM Level 2 */ PHP_FUNCTION(dom_document_create_element_ns) { zval *id, *rv = NULL; xmlDocPtr docp; xmlNodePtr nodep = NULL; xmlNsPtr nsptr = NULL; int ret, uri_len = 0, name_len = 0, value_len = 0; char *uri, *name, *value = NULL; char *localname = NULL, *prefix = NULL; int errorcode; dom_object *intern; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os!s|s", &id, dom_document_class_entry, &uri, &uri_len, &name, &name_len, &value, &value_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); errorcode = dom_check_qname(name, &localname, &prefix, uri_len, name_len); if (errorcode == 0) { if (xmlValidateName((xmlChar *) localname, 0) == 0) { nodep = xmlNewDocNode (docp, NULL, localname, value); if (nodep != NULL && uri != NULL) { nsptr = xmlSearchNsByHref (nodep->doc, nodep, uri); if (nsptr == NULL) { nsptr = dom_get_ns(nodep, uri, &errorcode, prefix); } xmlSetNs(nodep, nsptr); } } else { errorcode = INVALID_CHARACTER_ERR; } } xmlFree(localname); if (prefix != NULL) { xmlFree(prefix); } if (errorcode != 0) { if (nodep != NULL) { xmlFreeNode(nodep); } php_dom_throw_error(errorcode, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } if (nodep == NULL) { RETURN_FALSE; } nodep->ns = nsptr; DOM_RET_OBJ(rv, nodep, &ret, intern); } /* }}} end dom_document_create_element_ns */ /* {{{ proto DOMAttr dom_document_create_attribute_ns(string namespaceURI, string qualifiedName); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-DocCrAttrNS Since: DOM Level 2 */ PHP_FUNCTION(dom_document_create_attribute_ns) { zval *id, *rv = NULL; xmlDocPtr docp; xmlNodePtr nodep = NULL, root; xmlNsPtr nsptr; int ret, uri_len = 0, name_len = 0; char *uri, *name; char *localname = NULL, *prefix = NULL; dom_object *intern; int errorcode; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os!s", &id, dom_document_class_entry, &uri, &uri_len, &name, &name_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); root = xmlDocGetRootElement(docp); if (root != NULL) { errorcode = dom_check_qname(name, &localname, &prefix, uri_len, name_len); if (errorcode == 0) { if (xmlValidateName((xmlChar *) localname, 0) == 0) { nodep = (xmlNodePtr) xmlNewDocProp(docp, localname, NULL); if (nodep != NULL && uri_len > 0) { nsptr = xmlSearchNsByHref (nodep->doc, root, uri); if (nsptr == NULL) { nsptr = dom_get_ns(root, uri, &errorcode, prefix); } xmlSetNs(nodep, nsptr); } } else { errorcode = INVALID_CHARACTER_ERR; } } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Document Missing Root Element"); RETURN_FALSE; } xmlFree(localname); if (prefix != NULL) { xmlFree(prefix); } if (errorcode != 0) { if (nodep != NULL) { xmlFreeProp((xmlAttrPtr) nodep); } php_dom_throw_error(errorcode, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } if (nodep == NULL) { RETURN_FALSE; } DOM_RET_OBJ(rv, nodep, &ret, intern); } /* }}} end dom_document_create_attribute_ns */ /* {{{ proto DOMNodeList dom_document_get_elements_by_tag_name_ns(string namespaceURI, string localName); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-getElBTNNS Since: DOM Level 2 */ PHP_FUNCTION(dom_document_get_elements_by_tag_name_ns) { zval *id; xmlDocPtr docp; int uri_len, name_len; dom_object *intern, *namednode; char *uri, *name; xmlChar *local, *nsuri; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oss", &id, dom_document_class_entry, &uri, &uri_len, &name, &name_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); php_dom_create_interator(return_value, DOM_NODELIST TSRMLS_CC); namednode = (dom_object *)zend_objects_get_address(return_value TSRMLS_CC); local = xmlCharStrndup(name, name_len); nsuri = xmlCharStrndup(uri, uri_len); dom_namednode_iter(intern, 0, namednode, NULL, local, nsuri TSRMLS_CC); } /* }}} end dom_document_get_elements_by_tag_name_ns */ /* {{{ proto DOMElement dom_document_get_element_by_id(string elementId); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-getElBId Since: DOM Level 2 */ PHP_FUNCTION(dom_document_get_element_by_id) { zval *id, *rv = NULL; xmlDocPtr docp; xmlAttrPtr attrp; int ret, idname_len; dom_object *intern; char *idname; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &idname, &idname_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); attrp = xmlGetID(docp, (xmlChar *) idname); if (attrp && attrp->parent) { DOM_RET_OBJ(rv, (xmlNodePtr) attrp->parent, &ret, intern); } else { RETVAL_NULL(); } } /* }}} end dom_document_get_element_by_id */ /* {{{ proto DOMNode dom_document_adopt_node(DOMNode source); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-adoptNode Since: DOM Level 3 */ PHP_FUNCTION(dom_document_adopt_node) { DOM_NOT_IMPLEMENTED(); } /* }}} end dom_document_adopt_node */ /* {{{ proto void dom_document_normalize_document(); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-normalizeDocument Since: DOM Level 3 */ PHP_FUNCTION(dom_document_normalize_document) { zval *id; xmlDocPtr docp; dom_object *intern; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &id, dom_document_class_entry) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); dom_normalize((xmlNodePtr) docp TSRMLS_CC); } /* }}} end dom_document_normalize_document */ /* {{{ proto DOMNode dom_document_rename_node(node n, string namespaceURI, string qualifiedName); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-renameNode Since: DOM Level 3 */ PHP_FUNCTION(dom_document_rename_node) { DOM_NOT_IMPLEMENTED(); } /* }}} end dom_document_rename_node */ /* {{{ proto void DOMDocument::__construct([string version], [string encoding]); */ PHP_METHOD(domdocument, __construct) { zval *id; xmlDoc *docp = NULL, *olddoc; dom_object *intern; char *encoding, *version = NULL; int encoding_len = 0, version_len = 0, refcount; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, dom_domexception_class_entry, &error_handling TSRMLS_CC); if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|ss", &id, dom_document_class_entry, &version, &version_len, &encoding, &encoding_len) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } zend_restore_error_handling(&error_handling TSRMLS_CC); docp = xmlNewDoc(version); if (!docp) { php_dom_throw_error(INVALID_STATE_ERR, 1 TSRMLS_CC); RETURN_FALSE; } if (encoding_len > 0) { docp->encoding = (const xmlChar*)xmlStrdup(encoding); } intern = (dom_object *)zend_object_store_get_object(id TSRMLS_CC); if (intern != NULL) { olddoc = (xmlDocPtr) dom_object_get_node(intern); if (olddoc != NULL) { php_libxml_decrement_node_ptr((php_libxml_node_object *) intern TSRMLS_CC); refcount = php_libxml_decrement_doc_ref((php_libxml_node_object *)intern TSRMLS_CC); if (refcount != 0) { olddoc->_private = NULL; } } intern->document = NULL; if (php_libxml_increment_doc_ref((php_libxml_node_object *)intern, docp TSRMLS_CC) == -1) { RETURN_FALSE; } php_libxml_increment_node_ptr((php_libxml_node_object *)intern, (xmlNodePtr)docp, (void *)intern TSRMLS_CC); } } /* }}} end DOMDocument::__construct */ char *_dom_get_valid_file_path(char *source, char *resolved_path, int resolved_path_len TSRMLS_DC) /* {{{ */ { xmlURI *uri; xmlChar *escsource; char *file_dest; int isFileUri = 0; uri = xmlCreateURI(); escsource = xmlURIEscapeStr(source, ":"); xmlParseURIReference(uri, escsource); xmlFree(escsource); if (uri->scheme != NULL) { /* absolute file uris - libxml only supports localhost or empty host */ if (strncasecmp(source, "file:///",8) == 0) { isFileUri = 1; #ifdef PHP_WIN32 source += 8; #else source += 7; #endif } else if (strncasecmp(source, "file://localhost/",17) == 0) { isFileUri = 1; #ifdef PHP_WIN32 source += 17; #else source += 16; #endif } } file_dest = source; if ((uri->scheme == NULL || isFileUri)) { /* XXX possible buffer overflow if VCWD_REALPATH does not know size of resolved_path */ if (!VCWD_REALPATH(source, resolved_path) && !expand_filepath(source, resolved_path TSRMLS_CC)) { xmlFreeURI(uri); return NULL; } file_dest = resolved_path; } xmlFreeURI(uri); return file_dest; } /* }}} */ static xmlDocPtr dom_document_parser(zval *id, int mode, char *source, int source_len, int options TSRMLS_DC) /* {{{ */ { xmlDocPtr ret; xmlParserCtxtPtr ctxt = NULL; dom_doc_propsptr doc_props; dom_object *intern; php_libxml_ref_obj *document = NULL; int validate, recover, resolve_externals, keep_blanks, substitute_ent; int resolved_path_len; int old_error_reporting = 0; char *directory=NULL, resolved_path[MAXPATHLEN]; if (id != NULL) { intern = (dom_object *)zend_object_store_get_object(id TSRMLS_CC); document = intern->document; } doc_props = dom_get_doc_props(document); validate = doc_props->validateonparse; resolve_externals = doc_props->resolveexternals; keep_blanks = doc_props->preservewhitespace; substitute_ent = doc_props->substituteentities; recover = doc_props->recover; if (document == NULL) { efree(doc_props); } xmlInitParser(); if (mode == DOM_LOAD_FILE) { char *file_dest = _dom_get_valid_file_path(source, resolved_path, MAXPATHLEN TSRMLS_CC); if (file_dest) { ctxt = xmlCreateFileParserCtxt(file_dest); } } else { ctxt = xmlCreateMemoryParserCtxt(source, source_len); } if (ctxt == NULL) { return(NULL); } /* If loading from memory, we need to set the base directory for the document */ if (mode != DOM_LOAD_FILE) { #if HAVE_GETCWD directory = VCWD_GETCWD(resolved_path, MAXPATHLEN); #elif HAVE_GETWD directory = VCWD_GETWD(resolved_path); #endif if (directory) { if(ctxt->directory != NULL) { xmlFree((char *) ctxt->directory); } resolved_path_len = strlen(resolved_path); if (resolved_path[resolved_path_len - 1] != DEFAULT_SLASH) { resolved_path[resolved_path_len] = DEFAULT_SLASH; resolved_path[++resolved_path_len] = '\0'; } ctxt->directory = (char *) xmlCanonicPath((const xmlChar *) resolved_path); } } ctxt->vctxt.error = php_libxml_ctx_error; ctxt->vctxt.warning = php_libxml_ctx_warning; if (ctxt->sax != NULL) { ctxt->sax->error = php_libxml_ctx_error; ctxt->sax->warning = php_libxml_ctx_warning; } if (validate && ! (options & XML_PARSE_DTDVALID)) { options |= XML_PARSE_DTDVALID; } if (resolve_externals && ! (options & XML_PARSE_DTDATTR)) { options |= XML_PARSE_DTDATTR; } if (substitute_ent && ! (options & XML_PARSE_NOENT)) { options |= XML_PARSE_NOENT; } if (keep_blanks == 0 && ! (options & XML_PARSE_NOBLANKS)) { options |= XML_PARSE_NOBLANKS; } xmlCtxtUseOptions(ctxt, options); ctxt->recovery = recover; if (recover) { old_error_reporting = EG(error_reporting); EG(error_reporting) = old_error_reporting | E_WARNING; } xmlParseDocument(ctxt); if (ctxt->wellFormed || recover) { ret = ctxt->myDoc; if (ctxt->recovery) { EG(error_reporting) = old_error_reporting; } /* If loading from memory, set the base reference uri for the document */ if (ret && ret->URL == NULL && ctxt->directory != NULL) { ret->URL = xmlStrdup(ctxt->directory); } } else { ret = NULL; xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } xmlFreeParserCtxt(ctxt); return(ret); } /* }}} */ /* {{{ static void dom_parse_document(INTERNAL_FUNCTION_PARAMETERS, int mode) */ static void dom_parse_document(INTERNAL_FUNCTION_PARAMETERS, int mode) { zval *id, *rv = NULL; xmlDoc *docp = NULL, *newdoc; dom_doc_propsptr doc_prop; dom_object *intern; char *source; int source_len, refcount, ret; long options = 0; id = getThis(); if (id != NULL && ! instanceof_function(Z_OBJCE_P(id), dom_document_class_entry TSRMLS_CC)) { id = NULL; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &source, &source_len, &options) == FAILURE) { return; } if (!source_len) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty string supplied as input"); RETURN_FALSE; } newdoc = dom_document_parser(id, mode, source, source_len, options TSRMLS_CC); if (!newdoc) RETURN_FALSE; if (id != NULL) { intern = (dom_object *)zend_object_store_get_object(id TSRMLS_CC); if (intern != NULL) { docp = (xmlDocPtr) dom_object_get_node(intern); doc_prop = NULL; if (docp != NULL) { php_libxml_decrement_node_ptr((php_libxml_node_object *) intern TSRMLS_CC); doc_prop = intern->document->doc_props; intern->document->doc_props = NULL; refcount = php_libxml_decrement_doc_ref((php_libxml_node_object *)intern TSRMLS_CC); if (refcount != 0) { docp->_private = NULL; } } intern->document = NULL; if (php_libxml_increment_doc_ref((php_libxml_node_object *)intern, newdoc TSRMLS_CC) == -1) { RETURN_FALSE; } intern->document->doc_props = doc_prop; } php_libxml_increment_node_ptr((php_libxml_node_object *)intern, (xmlNodePtr)newdoc, (void *)intern TSRMLS_CC); RETURN_TRUE; } else { DOM_RET_OBJ(rv, (xmlNodePtr) newdoc, &ret, NULL); } } /* }}} end dom_parser_document */ /* {{{ proto DOMNode dom_document_load(string source [, int options]); URL: http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-DocumentLS-load Since: DOM Level 3 */ PHP_METHOD(domdocument, load) { dom_parse_document(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_FILE); } /* }}} end dom_document_load */ /* {{{ proto DOMNode dom_document_loadxml(string source [, int options]); URL: http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-DocumentLS-loadXML Since: DOM Level 3 */ PHP_METHOD(domdocument, loadXML) { dom_parse_document(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_STRING); } /* }}} end dom_document_loadxml */ /* {{{ proto int dom_document_save(string file); Convenience method to save to file */ PHP_FUNCTION(dom_document_save) { zval *id; xmlDoc *docp; int file_len = 0, bytes, format, saveempty = 0; dom_object *intern; dom_doc_propsptr doc_props; char *file; long options = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|l", &id, dom_document_class_entry, &file, &file_len, &options) == FAILURE) { return; } if (file_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Filename"); RETURN_FALSE; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); /* encoding handled by property on doc */ doc_props = dom_get_doc_props(intern->document); format = doc_props->formatoutput; if (options & LIBXML_SAVE_NOEMPTYTAG) { saveempty = xmlSaveNoEmptyTags; xmlSaveNoEmptyTags = 1; } bytes = xmlSaveFormatFileEnc(file, docp, NULL, format); if (options & LIBXML_SAVE_NOEMPTYTAG) { xmlSaveNoEmptyTags = saveempty; } if (bytes == -1) { RETURN_FALSE; } RETURN_LONG(bytes); } /* }}} end dom_document_save */ /* {{{ proto string dom_document_savexml([node n]); URL: http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-DocumentLS-saveXML Since: DOM Level 3 */ PHP_FUNCTION(dom_document_savexml) { zval *id, *nodep = NULL; xmlDoc *docp; xmlNode *node; xmlBufferPtr buf; xmlChar *mem; dom_object *intern, *nodeobj; dom_doc_propsptr doc_props; int size, format, saveempty = 0; long options = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|O!l", &id, dom_document_class_entry, &nodep, dom_node_class_entry, &options) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); doc_props = dom_get_doc_props(intern->document); format = doc_props->formatoutput; if (nodep != NULL) { /* Dump contents of Node */ DOM_GET_OBJ(node, nodep, xmlNodePtr, nodeobj); if (node->doc != docp) { php_dom_throw_error(WRONG_DOCUMENT_ERR, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } buf = xmlBufferCreate(); if (!buf) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not fetch buffer"); RETURN_FALSE; } if (options & LIBXML_SAVE_NOEMPTYTAG) { saveempty = xmlSaveNoEmptyTags; xmlSaveNoEmptyTags = 1; } xmlNodeDump(buf, docp, node, 0, format); if (options & LIBXML_SAVE_NOEMPTYTAG) { xmlSaveNoEmptyTags = saveempty; } mem = (xmlChar*) xmlBufferContent(buf); if (!mem) { xmlBufferFree(buf); RETURN_FALSE; } RETVAL_STRING(mem, 1); xmlBufferFree(buf); } else { if (options & LIBXML_SAVE_NOEMPTYTAG) { saveempty = xmlSaveNoEmptyTags; xmlSaveNoEmptyTags = 1; } /* Encoding is handled from the encoding property set on the document */ xmlDocDumpFormatMemory(docp, &mem, &size, format); if (options & LIBXML_SAVE_NOEMPTYTAG) { xmlSaveNoEmptyTags = saveempty; } if (!size) { RETURN_FALSE; } RETVAL_STRINGL(mem, size, 1); xmlFree(mem); } } /* }}} end dom_document_savexml */ static xmlNodePtr php_dom_free_xinclude_node(xmlNodePtr cur TSRMLS_DC) /* {{{ */ { xmlNodePtr xincnode; xincnode = cur; cur = cur->next; xmlUnlinkNode(xincnode); php_libxml_node_free_resource(xincnode TSRMLS_CC); return cur; } /* }}} */ static void php_dom_remove_xinclude_nodes(xmlNodePtr cur TSRMLS_DC) /* {{{ */ { while(cur) { if (cur->type == XML_XINCLUDE_START) { cur = php_dom_free_xinclude_node(cur TSRMLS_CC); /* XML_XINCLUDE_END node will be a sibling of XML_XINCLUDE_START */ while(cur && cur->type != XML_XINCLUDE_END) { /* remove xinclude processing nodes from recursive xincludes */ if (cur->type == XML_ELEMENT_NODE) { php_dom_remove_xinclude_nodes(cur->children TSRMLS_CC); } cur = cur->next; } if (cur && cur->type == XML_XINCLUDE_END) { cur = php_dom_free_xinclude_node(cur TSRMLS_CC); } } else { if (cur->type == XML_ELEMENT_NODE) { php_dom_remove_xinclude_nodes(cur->children TSRMLS_CC); } cur = cur->next; } } } /* }}} */ /* {{{ proto int dom_document_xinclude([int options]) Substitutues xincludes in a DomDocument */ PHP_FUNCTION(dom_document_xinclude) { zval *id; xmlDoc *docp; xmlNodePtr root; long flags = 0; int err; dom_object *intern; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|l", &id, dom_document_class_entry, &flags) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); err = xmlXIncludeProcessFlags(docp, flags); /* XML_XINCLUDE_START and XML_XINCLUDE_END nodes need to be removed as these are added via xmlXIncludeProcess to mark beginning and ending of xincluded document but are not wanted in resulting document - must be done even if err as it could fail after having processed some xincludes */ root = (xmlNodePtr) docp->children; while(root && root->type != XML_ELEMENT_NODE && root->type != XML_XINCLUDE_START) { root = root->next; } if (root) { php_dom_remove_xinclude_nodes(root TSRMLS_CC); } if (err) { RETVAL_LONG(err); } else { RETVAL_FALSE; } } /* }}} */ /* {{{ proto boolean dom_document_validate(); Since: DOM extended */ PHP_FUNCTION(dom_document_validate) { zval *id; xmlDoc *docp; dom_object *intern; xmlValidCtxt *cvp; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &id, dom_document_class_entry) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); cvp = xmlNewValidCtxt(); cvp->userData = NULL; cvp->error = (xmlValidityErrorFunc) php_libxml_error_handler; cvp->warning = (xmlValidityErrorFunc) php_libxml_error_handler; if (xmlValidateDocument(cvp, docp)) { RETVAL_TRUE; } else { RETVAL_FALSE; } xmlFreeValidCtxt(cvp); } /* }}} */ #if defined(LIBXML_SCHEMAS_ENABLED) static void _dom_document_schema_validate(INTERNAL_FUNCTION_PARAMETERS, int type) /* {{{ */ { zval *id; xmlDoc *docp; dom_object *intern; char *source = NULL, *valid_file = NULL; int source_len = 0; xmlSchemaParserCtxtPtr parser; xmlSchemaPtr sptr; xmlSchemaValidCtxtPtr vptr; int is_valid; char resolved_path[MAXPATHLEN + 1]; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &source, &source_len) == FAILURE) { return; } if (source_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Schema source"); RETURN_FALSE; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); switch (type) { case DOM_LOAD_FILE: valid_file = _dom_get_valid_file_path(source, resolved_path, MAXPATHLEN TSRMLS_CC); if (!valid_file) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Schema file source"); RETURN_FALSE; } parser = xmlSchemaNewParserCtxt(valid_file); break; case DOM_LOAD_STRING: parser = xmlSchemaNewMemParserCtxt(source, source_len); /* If loading from memory, we need to set the base directory for the document but it is not apparent how to do that for schema's */ break; default: return; } xmlSchemaSetParserErrors(parser, (xmlSchemaValidityErrorFunc) php_libxml_error_handler, (xmlSchemaValidityWarningFunc) php_libxml_error_handler, parser); sptr = xmlSchemaParse(parser); xmlSchemaFreeParserCtxt(parser); if (!sptr) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Schema"); RETURN_FALSE; } docp = (xmlDocPtr) dom_object_get_node(intern); vptr = xmlSchemaNewValidCtxt(sptr); if (!vptr) { xmlSchemaFree(sptr); php_error(E_ERROR, "Invalid Schema Validation Context"); RETURN_FALSE; } xmlSchemaSetValidErrors(vptr, php_libxml_error_handler, php_libxml_error_handler, vptr); is_valid = xmlSchemaValidateDoc(vptr, docp); xmlSchemaFree(sptr); xmlSchemaFreeValidCtxt(vptr); if (is_valid == 0) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto boolean dom_document_schema_validate_file(string filename); */ PHP_FUNCTION(dom_document_schema_validate_file) { _dom_document_schema_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_FILE); } /* }}} end dom_document_schema_validate_file */ /* {{{ proto boolean dom_document_schema_validate(string source); */ PHP_FUNCTION(dom_document_schema_validate_xml) { _dom_document_schema_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_STRING); } /* }}} end dom_document_schema_validate */ static void _dom_document_relaxNG_validate(INTERNAL_FUNCTION_PARAMETERS, int type) /* {{{ */ { zval *id; xmlDoc *docp; dom_object *intern; char *source = NULL, *valid_file = NULL; int source_len = 0; xmlRelaxNGParserCtxtPtr parser; xmlRelaxNGPtr sptr; xmlRelaxNGValidCtxtPtr vptr; int is_valid; char resolved_path[MAXPATHLEN + 1]; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &source, &source_len) == FAILURE) { return; } if (source_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Schema source"); RETURN_FALSE; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); switch (type) { case DOM_LOAD_FILE: valid_file = _dom_get_valid_file_path(source, resolved_path, MAXPATHLEN TSRMLS_CC); if (!valid_file) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid RelaxNG file source"); RETURN_FALSE; } parser = xmlRelaxNGNewParserCtxt(valid_file); break; case DOM_LOAD_STRING: parser = xmlRelaxNGNewMemParserCtxt(source, source_len); /* If loading from memory, we need to set the base directory for the document but it is not apparent how to do that for schema's */ break; default: return; } xmlRelaxNGSetParserErrors(parser, (xmlRelaxNGValidityErrorFunc) php_libxml_error_handler, (xmlRelaxNGValidityWarningFunc) php_libxml_error_handler, parser); sptr = xmlRelaxNGParse(parser); xmlRelaxNGFreeParserCtxt(parser); if (!sptr) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid RelaxNG"); RETURN_FALSE; } docp = (xmlDocPtr) dom_object_get_node(intern); vptr = xmlRelaxNGNewValidCtxt(sptr); if (!vptr) { xmlRelaxNGFree(sptr); php_error(E_ERROR, "Invalid RelaxNG Validation Context"); RETURN_FALSE; } xmlRelaxNGSetValidErrors(vptr, php_libxml_error_handler, php_libxml_error_handler, vptr); is_valid = xmlRelaxNGValidateDoc(vptr, docp); xmlRelaxNGFree(sptr); xmlRelaxNGFreeValidCtxt(vptr); if (is_valid == 0) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto boolean dom_document_relaxNG_validate_file(string filename); */ PHP_FUNCTION(dom_document_relaxNG_validate_file) { _dom_document_relaxNG_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_FILE); } /* }}} end dom_document_relaxNG_validate_file */ /* {{{ proto boolean dom_document_relaxNG_validate_xml(string source); */ PHP_FUNCTION(dom_document_relaxNG_validate_xml) { _dom_document_relaxNG_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_STRING); } /* }}} end dom_document_relaxNG_validate_xml */ #endif #if defined(LIBXML_HTML_ENABLED) static void dom_load_html(INTERNAL_FUNCTION_PARAMETERS, int mode) /* {{{ */ { zval *id, *rv = NULL; xmlDoc *docp = NULL, *newdoc; dom_object *intern; dom_doc_propsptr doc_prop; char *source; int source_len, refcount, ret; htmlParserCtxtPtr ctxt; id = getThis(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &source, &source_len) == FAILURE) { return; } if (!source_len) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty string supplied as input"); RETURN_FALSE; } if (mode == DOM_LOAD_FILE) { ctxt = htmlCreateFileParserCtxt(source, NULL); } else { source_len = xmlStrlen(source); ctxt = htmlCreateMemoryParserCtxt(source, source_len); } if (!ctxt) { RETURN_FALSE; } ctxt->vctxt.error = php_libxml_ctx_error; ctxt->vctxt.warning = php_libxml_ctx_warning; if (ctxt->sax != NULL) { ctxt->sax->error = php_libxml_ctx_error; ctxt->sax->warning = php_libxml_ctx_warning; } htmlParseDocument(ctxt); newdoc = ctxt->myDoc; htmlFreeParserCtxt(ctxt); if (!newdoc) RETURN_FALSE; if (id != NULL && instanceof_function(Z_OBJCE_P(id), dom_document_class_entry TSRMLS_CC)) { intern = (dom_object *)zend_object_store_get_object(id TSRMLS_CC); if (intern != NULL) { docp = (xmlDocPtr) dom_object_get_node(intern); doc_prop = NULL; if (docp != NULL) { php_libxml_decrement_node_ptr((php_libxml_node_object *) intern TSRMLS_CC); doc_prop = intern->document->doc_props; intern->document->doc_props = NULL; refcount = php_libxml_decrement_doc_ref((php_libxml_node_object *)intern TSRMLS_CC); if (refcount != 0) { docp->_private = NULL; } } intern->document = NULL; if (php_libxml_increment_doc_ref((php_libxml_node_object *)intern, newdoc TSRMLS_CC) == -1) { RETURN_FALSE; } intern->document->doc_props = doc_prop; } php_libxml_increment_node_ptr((php_libxml_node_object *)intern, (xmlNodePtr)newdoc, (void *)intern TSRMLS_CC); RETURN_TRUE; } else { DOM_RET_OBJ(rv, (xmlNodePtr) newdoc, &ret, NULL); } } /* }}} */ /* {{{ proto DOMNode dom_document_load_html_file(string source); Since: DOM extended */ PHP_METHOD(domdocument, loadHTMLFile) { dom_load_html(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_FILE); } /* }}} end dom_document_load_html_file */ /* {{{ proto DOMNode dom_document_load_html(string source); Since: DOM extended */ PHP_METHOD(domdocument, loadHTML) { dom_load_html(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_STRING); } /* }}} end dom_document_load_html */ /* {{{ proto int dom_document_save_html_file(string file); Convenience method to save to file as html */ PHP_FUNCTION(dom_document_save_html_file) { zval *id; xmlDoc *docp; int file_len, bytes, format; dom_object *intern; dom_doc_propsptr doc_props; char *file; const char *encoding; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &file, &file_len) == FAILURE) { return; } if (file_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Filename"); RETURN_FALSE; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); encoding = (const char *) htmlGetMetaEncoding(docp); doc_props = dom_get_doc_props(intern->document); format = doc_props->formatoutput; bytes = htmlSaveFileFormat(file, docp, encoding, format); if (bytes == -1) { RETURN_FALSE; } RETURN_LONG(bytes); } /* }}} end dom_document_save_html_file */ /* {{{ proto string dom_document_save_html(); Convenience method to output as html */ PHP_FUNCTION(dom_document_save_html) { zval *id; xmlDoc *docp; dom_object *intern; xmlChar *mem; int size, format; dom_doc_propsptr doc_props; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &id, dom_document_class_entry) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); #if LIBXML_VERSION >= 20623 doc_props = dom_get_doc_props(intern->document); format = doc_props->formatoutput; htmlDocDumpMemoryFormat(docp, &mem, &size, format); #else htmlDocDumpMemory(docp, &mem, &size); #endif if (!size) { if (mem) xmlFree(mem); RETURN_FALSE; } RETVAL_STRINGL(mem, size, 1); xmlFree(mem); } /* }}} end dom_document_save_html */ #endif /* defined(LIBXML_HTML_ENABLED) */ /* {{{ proto boolean DOMDocument::registerNodeClass(string baseclass, string extendedclass); Register extended class used to create base node type */ PHP_METHOD(domdocument, registerNodeClass) { zval *id; xmlDoc *docp; char *baseclass = NULL, *extendedclass = NULL; int baseclass_len = 0, extendedclass_len = 0; zend_class_entry *basece = NULL, *ce = NULL; dom_object *intern; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oss!", &id, dom_document_class_entry, &baseclass, &baseclass_len, &extendedclass, &extendedclass_len) == FAILURE) { return; } if (baseclass_len) { zend_class_entry **pce; if (zend_lookup_class(baseclass, baseclass_len, &pce TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Class %s does not exist", baseclass); return; } basece = *pce; } if (basece == NULL || ! instanceof_function(basece, dom_node_class_entry TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Class %s is not derived from DOMNode.", baseclass); return; } if (extendedclass_len) { zend_class_entry **pce; if (zend_lookup_class(extendedclass, extendedclass_len, &pce TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Class %s does not exist", extendedclass); } ce = *pce; } if (ce == NULL || instanceof_function(ce, basece TSRMLS_CC)) { DOM_GET_OBJ(docp, id, xmlDocPtr, intern); if (dom_set_doc_classmap(intern->document, basece, ce TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Class %s could not be registered.", extendedclass); } RETURN_TRUE; } else { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Class %s is not derived from %s.", extendedclass, baseclass); } RETURN_FALSE; } /* }}} */ #endif /* HAVE_LIBXML && HAVE_DOM */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Christian Stocker <[email protected]> | | Rob Richards <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #if HAVE_LIBXML && HAVE_DOM #include "php_dom.h" #include <libxml/SAX.h> #ifdef LIBXML_SCHEMAS_ENABLED #include <libxml/relaxng.h> #include <libxml/xmlschemas.h> #endif typedef struct _idsIterator idsIterator; struct _idsIterator { xmlChar *elementId; xmlNode *element; }; #define DOM_LOAD_STRING 0 #define DOM_LOAD_FILE 1 /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_element, 0, 0, 1) ZEND_ARG_INFO(0, tagName) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_document_fragment, 0, 0, 0) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_text_node, 0, 0, 1) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_comment, 0, 0, 1) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_cdatasection, 0, 0, 1) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_processing_instruction, 0, 0, 2) ZEND_ARG_INFO(0, target) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_attribute, 0, 0, 1) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_entity_reference, 0, 0, 1) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_get_elements_by_tag_name, 0, 0, 1) ZEND_ARG_INFO(0, tagName) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_import_node, 0, 0, 2) ZEND_ARG_OBJ_INFO(0, importedNode, DOMNode, 0) ZEND_ARG_INFO(0, deep) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_element_ns, 0, 0, 2) ZEND_ARG_INFO(0, namespaceURI) ZEND_ARG_INFO(0, qualifiedName) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_attribute_ns, 0, 0, 2) ZEND_ARG_INFO(0, namespaceURI) ZEND_ARG_INFO(0, qualifiedName) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_get_elements_by_tag_name_ns, 0, 0, 2) ZEND_ARG_INFO(0, namespaceURI) ZEND_ARG_INFO(0, localName) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_get_element_by_id, 0, 0, 1) ZEND_ARG_INFO(0, elementId) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_adopt_node, 0, 0, 1) ZEND_ARG_OBJ_INFO(0, source, DOMNode, 0) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_normalize_document, 0, 0, 0) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_rename_node, 0, 0, 3) ZEND_ARG_OBJ_INFO(0, node, DOMNode, 0) ZEND_ARG_INFO(0, namespaceURI) ZEND_ARG_INFO(0, qualifiedName) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_load, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_save, 0, 0, 1) ZEND_ARG_INFO(0, file) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_loadxml, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_savexml, 0, 0, 0) ZEND_ARG_OBJ_INFO(0, node, DOMNode, 1) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_construct, 0, 0, 0) ZEND_ARG_INFO(0, version) ZEND_ARG_INFO(0, encoding) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_validate, 0, 0, 0) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_xinclude, 0, 0, 0) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_loadhtml, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_loadhtmlfile, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_savehtml, 0, 0, 0) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_savehtmlfile, 0, 0, 1) ZEND_ARG_INFO(0, file) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_schema_validate_file, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_schema_validate_xml, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_relaxNG_validate_file, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_relaxNG_validate_xml, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_registernodeclass, 0, 0, 2) ZEND_ARG_INFO(0, baseClass) ZEND_ARG_INFO(0, extendedClass) ZEND_END_ARG_INFO(); /* }}} */ /* * class DOMDocument extends DOMNode * * URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-i-Document * Since: */ const zend_function_entry php_dom_document_class_functions[] = { /* {{{ */ PHP_FALIAS(createElement, dom_document_create_element, arginfo_dom_document_create_element) PHP_FALIAS(createDocumentFragment, dom_document_create_document_fragment, arginfo_dom_document_create_document_fragment) PHP_FALIAS(createTextNode, dom_document_create_text_node, arginfo_dom_document_create_text_node) PHP_FALIAS(createComment, dom_document_create_comment, arginfo_dom_document_create_comment) PHP_FALIAS(createCDATASection, dom_document_create_cdatasection, arginfo_dom_document_create_cdatasection) PHP_FALIAS(createProcessingInstruction, dom_document_create_processing_instruction, arginfo_dom_document_create_processing_instruction) PHP_FALIAS(createAttribute, dom_document_create_attribute, arginfo_dom_document_create_attribute) PHP_FALIAS(createEntityReference, dom_document_create_entity_reference, arginfo_dom_document_create_entity_reference) PHP_FALIAS(getElementsByTagName, dom_document_get_elements_by_tag_name, arginfo_dom_document_get_elements_by_tag_name) PHP_FALIAS(importNode, dom_document_import_node, arginfo_dom_document_import_node) PHP_FALIAS(createElementNS, dom_document_create_element_ns, arginfo_dom_document_create_element_ns) PHP_FALIAS(createAttributeNS, dom_document_create_attribute_ns, arginfo_dom_document_create_attribute_ns) PHP_FALIAS(getElementsByTagNameNS, dom_document_get_elements_by_tag_name_ns, arginfo_dom_document_get_elements_by_tag_name_ns) PHP_FALIAS(getElementById, dom_document_get_element_by_id, arginfo_dom_document_get_element_by_id) PHP_FALIAS(adoptNode, dom_document_adopt_node, arginfo_dom_document_adopt_node) PHP_FALIAS(normalizeDocument, dom_document_normalize_document, arginfo_dom_document_normalize_document) PHP_FALIAS(renameNode, dom_document_rename_node, arginfo_dom_document_rename_node) PHP_ME(domdocument, load, arginfo_dom_document_load, ZEND_ACC_PUBLIC|ZEND_ACC_ALLOW_STATIC) PHP_FALIAS(save, dom_document_save, arginfo_dom_document_save) PHP_ME(domdocument, loadXML, arginfo_dom_document_loadxml, ZEND_ACC_PUBLIC|ZEND_ACC_ALLOW_STATIC) PHP_FALIAS(saveXML, dom_document_savexml, arginfo_dom_document_savexml) PHP_ME(domdocument, __construct, arginfo_dom_document_construct, ZEND_ACC_PUBLIC) PHP_FALIAS(validate, dom_document_validate, arginfo_dom_document_validate) PHP_FALIAS(xinclude, dom_document_xinclude, arginfo_dom_document_xinclude) #if defined(LIBXML_HTML_ENABLED) PHP_ME(domdocument, loadHTML, arginfo_dom_document_loadhtml, ZEND_ACC_PUBLIC|ZEND_ACC_ALLOW_STATIC) PHP_ME(domdocument, loadHTMLFile, arginfo_dom_document_loadhtmlfile, ZEND_ACC_PUBLIC|ZEND_ACC_ALLOW_STATIC) PHP_FALIAS(saveHTML, dom_document_save_html, arginfo_dom_document_savehtml) PHP_FALIAS(saveHTMLFile, dom_document_save_html_file, arginfo_dom_document_savehtmlfile) #endif /* defined(LIBXML_HTML_ENABLED) */ #if defined(LIBXML_SCHEMAS_ENABLED) PHP_FALIAS(schemaValidate, dom_document_schema_validate_file, arginfo_dom_document_schema_validate_file) PHP_FALIAS(schemaValidateSource, dom_document_schema_validate_xml, arginfo_dom_document_schema_validate_xml) PHP_FALIAS(relaxNGValidate, dom_document_relaxNG_validate_file, arginfo_dom_document_relaxNG_validate_file) PHP_FALIAS(relaxNGValidateSource, dom_document_relaxNG_validate_xml, arginfo_dom_document_relaxNG_validate_xml) #endif PHP_ME(domdocument, registerNodeClass, arginfo_dom_document_registernodeclass, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; /* }}} */ /* {{{ docType DOMDocumentType readonly=yes URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-B63ED1A31 Since: */ int dom_document_doctype_read(dom_object *obj, zval **retval TSRMLS_DC) { xmlDoc *docp; xmlDtdPtr dtdptr; int ret; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } ALLOC_ZVAL(*retval); dtdptr = xmlGetIntSubset(docp); if (!dtdptr) { ZVAL_NULL(*retval); return SUCCESS; } if (NULL == (*retval = php_dom_create_object((xmlNodePtr) dtdptr, &ret, NULL, *retval, obj TSRMLS_CC))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot create required DOM object"); return FAILURE; } return SUCCESS; } /* }}} */ /* {{{ implementation DOMImplementation readonly=yes URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1B793EBA Since: */ int dom_document_implementation_read(dom_object *obj, zval **retval TSRMLS_DC) { ALLOC_ZVAL(*retval); php_dom_create_implementation(retval TSRMLS_CC); return SUCCESS; } /* }}} */ /* {{{ documentElement DOMElement readonly=yes URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-87CD092 Since: */ int dom_document_document_element_read(dom_object *obj, zval **retval TSRMLS_DC) { xmlDoc *docp; xmlNode *root; int ret; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } ALLOC_ZVAL(*retval); root = xmlDocGetRootElement(docp); if (!root) { ZVAL_NULL(*retval); return SUCCESS; } if (NULL == (*retval = php_dom_create_object(root, &ret, NULL, *retval, obj TSRMLS_CC))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot create required DOM object"); return FAILURE; } return SUCCESS; } /* }}} */ /* {{{ encoding string URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-encoding Since: DOM Level 3 */ int dom_document_encoding_read(dom_object *obj, zval **retval TSRMLS_DC) { xmlDoc *docp; char *encoding; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } encoding = (char *) docp->encoding; ALLOC_ZVAL(*retval); if (encoding != NULL) { ZVAL_STRING(*retval, encoding, 1); } else { ZVAL_NULL(*retval); } return SUCCESS; } int dom_document_encoding_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; xmlDoc *docp; xmlCharEncodingHandlerPtr handler; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } if (newval->type != IS_STRING) { if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_string(newval); } handler = xmlFindCharEncodingHandler(Z_STRVAL_P(newval)); if (handler != NULL) { xmlCharEncCloseFunc(handler); if (docp->encoding != NULL) { xmlFree((xmlChar *)docp->encoding); } docp->encoding = xmlStrdup((const xmlChar *) Z_STRVAL_P(newval)); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Document Encoding"); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ standalone boolean readonly=no URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-standalone Since: DOM Level 3 */ int dom_document_standalone_read(dom_object *obj, zval **retval TSRMLS_DC) { xmlDoc *docp; int standalone; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } ALLOC_ZVAL(*retval); standalone = docp->standalone; ZVAL_BOOL(*retval, standalone); return SUCCESS; } int dom_document_standalone_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; xmlDoc *docp; int standalone; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_long(newval); standalone = Z_LVAL_P(newval); if (standalone > 0) { docp->standalone = 1; } else if (standalone < 0) { docp->standalone = -1; } else { docp->standalone = 0; } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ version string readonly=no URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-version Since: DOM Level 3 */ int dom_document_version_read(dom_object *obj, zval **retval TSRMLS_DC) { xmlDoc *docp; char *version; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } version = (char *) docp->version; ALLOC_ZVAL(*retval); if (version != NULL) { ZVAL_STRING(*retval, version, 1); } else { ZVAL_NULL(*retval); } return SUCCESS; } int dom_document_version_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; xmlDoc *docp; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } if (docp->version != NULL) { xmlFree((xmlChar *) docp->version ); } if (newval->type != IS_STRING) { if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_string(newval); } docp->version = xmlStrdup((const xmlChar *) Z_STRVAL_P(newval)); if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ strictErrorChecking boolean readonly=no URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-strictErrorChecking Since: DOM Level 3 */ int dom_document_strict_error_checking_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->stricterror); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_strict_error_checking_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->stricterror = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ formatOutput boolean readonly=no */ int dom_document_format_output_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->formatoutput); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_format_output_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->formatoutput = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ validateOnParse boolean readonly=no */ int dom_document_validate_on_parse_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->validateonparse); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_validate_on_parse_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->validateonparse = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ resolveExternals boolean readonly=no */ int dom_document_resolve_externals_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->resolveexternals); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_resolve_externals_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->resolveexternals = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ preserveWhiteSpace boolean readonly=no */ int dom_document_preserve_whitespace_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->preservewhitespace); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_preserve_whitespace_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->preservewhitespace = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ recover boolean readonly=no */ int dom_document_recover_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->recover); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_recover_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->recover = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ substituteEntities boolean readonly=no */ int dom_document_substitue_entities_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->substituteentities); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_substitue_entities_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->substituteentities = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ documentURI string readonly=no URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-documentURI Since: DOM Level 3 */ int dom_document_document_uri_read(dom_object *obj, zval **retval TSRMLS_DC) { xmlDoc *docp; char *url; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } ALLOC_ZVAL(*retval); url = (char *) docp->URL; if (url != NULL) { ZVAL_STRING(*retval, url, 1); } else { ZVAL_NULL(*retval); } return SUCCESS; } int dom_document_document_uri_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; xmlDoc *docp; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } if (docp->URL != NULL) { xmlFree((xmlChar *) docp->URL); } if (newval->type != IS_STRING) { if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_string(newval); } docp->URL = xmlStrdup((const xmlChar *) Z_STRVAL_P(newval)); if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ config DOMConfiguration readonly=yes URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-config Since: DOM Level 3 */ int dom_document_config_read(dom_object *obj, zval **retval TSRMLS_DC) { ALLOC_ZVAL(*retval); ZVAL_NULL(*retval); return SUCCESS; } /* }}} */ /* {{{ proto DOMElement dom_document_create_element(string tagName [, string value]); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-2141741547 Since: */ PHP_FUNCTION(dom_document_create_element) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp; dom_object *intern; int ret, name_len, value_len; char *name, *value = NULL; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|s", &id, dom_document_class_entry, &name, &name_len, &value, &value_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); if (xmlValidateName((xmlChar *) name, 0) != 0) { php_dom_throw_error(INVALID_CHARACTER_ERR, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } node = xmlNewDocNode(docp, NULL, name, value); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, node, &ret, intern); } /* }}} end dom_document_create_element */ /* {{{ proto DOMDocumentFragment dom_document_create_document_fragment(); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-35CB04B5 Since: */ PHP_FUNCTION(dom_document_create_document_fragment) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp; dom_object *intern; int ret; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &id, dom_document_class_entry) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); node = xmlNewDocFragment(docp); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, node, &ret, intern); } /* }}} end dom_document_create_document_fragment */ /* {{{ proto DOMText dom_document_create_text_node(string data); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1975348127 Since: */ PHP_FUNCTION(dom_document_create_text_node) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp; int ret, value_len; dom_object *intern; char *value; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &value, &value_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); node = xmlNewDocText(docp, (xmlChar *) value); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, node, &ret, intern); } /* }}} end dom_document_create_text_node */ /* {{{ proto DOMComment dom_document_create_comment(string data); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1334481328 Since: */ PHP_FUNCTION(dom_document_create_comment) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp; int ret, value_len; dom_object *intern; char *value; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &value, &value_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); node = xmlNewDocComment(docp, (xmlChar *) value); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, node, &ret, intern); } /* }}} end dom_document_create_comment */ /* {{{ proto DOMCdataSection dom_document_create_cdatasection(string data); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-D26C0AF8 Since: */ PHP_FUNCTION(dom_document_create_cdatasection) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp; int ret, value_len; dom_object *intern; char *value; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &value, &value_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); node = xmlNewCDataBlock(docp, (xmlChar *) value, value_len); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, node, &ret, intern); } /* }}} end dom_document_create_cdatasection */ /* {{{ proto DOMProcessingInstruction dom_document_create_processing_instruction(string target, string data); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-135944439 Since: */ PHP_FUNCTION(dom_document_create_processing_instruction) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp; int ret, value_len, name_len = 0; dom_object *intern; char *name, *value = NULL; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|s", &id, dom_document_class_entry, &name, &name_len, &value, &value_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); if (xmlValidateName((xmlChar *) name, 0) != 0) { php_dom_throw_error(INVALID_CHARACTER_ERR, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } node = xmlNewPI((xmlChar *) name, (xmlChar *) value); if (!node) { RETURN_FALSE; } node->doc = docp; DOM_RET_OBJ(rv, node, &ret, intern); } /* }}} end dom_document_create_processing_instruction */ /* {{{ proto DOMAttr dom_document_create_attribute(string name); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1084891198 Since: */ PHP_FUNCTION(dom_document_create_attribute) { zval *id, *rv = NULL; xmlAttrPtr node; xmlDocPtr docp; int ret, name_len; dom_object *intern; char *name; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &name, &name_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); if (xmlValidateName((xmlChar *) name, 0) != 0) { php_dom_throw_error(INVALID_CHARACTER_ERR, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } node = xmlNewDocProp(docp, (xmlChar *) name, NULL); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, (xmlNodePtr) node, &ret, intern); } /* }}} end dom_document_create_attribute */ /* {{{ proto DOMEntityReference dom_document_create_entity_reference(string name); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-392B75AE Since: */ PHP_FUNCTION(dom_document_create_entity_reference) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp = NULL; dom_object *intern; int ret, name_len; char *name; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &name, &name_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); if (xmlValidateName((xmlChar *) name, 0) != 0) { php_dom_throw_error(INVALID_CHARACTER_ERR, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } node = xmlNewReference(docp, name); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, (xmlNodePtr) node, &ret, intern); } /* }}} end dom_document_create_entity_reference */ /* {{{ proto DOMNodeList dom_document_get_elements_by_tag_name(string tagname); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-A6C9094 Since: */ PHP_FUNCTION(dom_document_get_elements_by_tag_name) { zval *id; xmlDocPtr docp; int name_len; dom_object *intern, *namednode; char *name; xmlChar *local; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &name, &name_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); php_dom_create_interator(return_value, DOM_NODELIST TSRMLS_CC); namednode = (dom_object *)zend_objects_get_address(return_value TSRMLS_CC); local = xmlCharStrndup(name, name_len); dom_namednode_iter(intern, 0, namednode, NULL, local, NULL TSRMLS_CC); } /* }}} end dom_document_get_elements_by_tag_name */ /* {{{ proto DOMNode dom_document_import_node(DOMNode importedNode, boolean deep); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Core-Document-importNode Since: DOM Level 2 */ PHP_FUNCTION(dom_document_import_node) { zval *rv = NULL; zval *id, *node; xmlDocPtr docp; xmlNodePtr nodep, retnodep; dom_object *intern, *nodeobj; int ret; long recursive = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO|l", &id, dom_document_class_entry, &node, dom_node_class_entry, &recursive) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); DOM_GET_OBJ(nodep, node, xmlNodePtr, nodeobj); if (nodep->type == XML_HTML_DOCUMENT_NODE || nodep->type == XML_DOCUMENT_NODE || nodep->type == XML_DOCUMENT_TYPE_NODE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot import: Node Type Not Supported"); RETURN_FALSE; } if (nodep->doc == docp) { retnodep = nodep; } else { if ((recursive == 0) && (nodep->type == XML_ELEMENT_NODE)) { recursive = 2; } retnodep = xmlDocCopyNode(nodep, docp, recursive); if (!retnodep) { RETURN_FALSE; } if ((retnodep->type == XML_ATTRIBUTE_NODE) && (nodep->ns != NULL)) { xmlNsPtr nsptr = NULL; xmlNodePtr root = xmlDocGetRootElement(docp); nsptr = xmlSearchNsByHref (nodep->doc, root, nodep->ns->href); if (nsptr == NULL) { int errorcode; nsptr = dom_get_ns(root, (char *) nodep->ns->href, &errorcode, (char *) nodep->ns->prefix); } xmlSetNs(retnodep, nsptr); } } DOM_RET_OBJ(rv, (xmlNodePtr) retnodep, &ret, intern); } /* }}} end dom_document_import_node */ /* {{{ proto DOMElement dom_document_create_element_ns(string namespaceURI, string qualifiedName [,string value]); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-DocCrElNS Since: DOM Level 2 */ PHP_FUNCTION(dom_document_create_element_ns) { zval *id, *rv = NULL; xmlDocPtr docp; xmlNodePtr nodep = NULL; xmlNsPtr nsptr = NULL; int ret, uri_len = 0, name_len = 0, value_len = 0; char *uri, *name, *value = NULL; char *localname = NULL, *prefix = NULL; int errorcode; dom_object *intern; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os!s|s", &id, dom_document_class_entry, &uri, &uri_len, &name, &name_len, &value, &value_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); errorcode = dom_check_qname(name, &localname, &prefix, uri_len, name_len); if (errorcode == 0) { if (xmlValidateName((xmlChar *) localname, 0) == 0) { nodep = xmlNewDocNode (docp, NULL, localname, value); if (nodep != NULL && uri != NULL) { nsptr = xmlSearchNsByHref (nodep->doc, nodep, uri); if (nsptr == NULL) { nsptr = dom_get_ns(nodep, uri, &errorcode, prefix); } xmlSetNs(nodep, nsptr); } } else { errorcode = INVALID_CHARACTER_ERR; } } xmlFree(localname); if (prefix != NULL) { xmlFree(prefix); } if (errorcode != 0) { if (nodep != NULL) { xmlFreeNode(nodep); } php_dom_throw_error(errorcode, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } if (nodep == NULL) { RETURN_FALSE; } nodep->ns = nsptr; DOM_RET_OBJ(rv, nodep, &ret, intern); } /* }}} end dom_document_create_element_ns */ /* {{{ proto DOMAttr dom_document_create_attribute_ns(string namespaceURI, string qualifiedName); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-DocCrAttrNS Since: DOM Level 2 */ PHP_FUNCTION(dom_document_create_attribute_ns) { zval *id, *rv = NULL; xmlDocPtr docp; xmlNodePtr nodep = NULL, root; xmlNsPtr nsptr; int ret, uri_len = 0, name_len = 0; char *uri, *name; char *localname = NULL, *prefix = NULL; dom_object *intern; int errorcode; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os!s", &id, dom_document_class_entry, &uri, &uri_len, &name, &name_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); root = xmlDocGetRootElement(docp); if (root != NULL) { errorcode = dom_check_qname(name, &localname, &prefix, uri_len, name_len); if (errorcode == 0) { if (xmlValidateName((xmlChar *) localname, 0) == 0) { nodep = (xmlNodePtr) xmlNewDocProp(docp, localname, NULL); if (nodep != NULL && uri_len > 0) { nsptr = xmlSearchNsByHref (nodep->doc, root, uri); if (nsptr == NULL) { nsptr = dom_get_ns(root, uri, &errorcode, prefix); } xmlSetNs(nodep, nsptr); } } else { errorcode = INVALID_CHARACTER_ERR; } } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Document Missing Root Element"); RETURN_FALSE; } xmlFree(localname); if (prefix != NULL) { xmlFree(prefix); } if (errorcode != 0) { if (nodep != NULL) { xmlFreeProp((xmlAttrPtr) nodep); } php_dom_throw_error(errorcode, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } if (nodep == NULL) { RETURN_FALSE; } DOM_RET_OBJ(rv, nodep, &ret, intern); } /* }}} end dom_document_create_attribute_ns */ /* {{{ proto DOMNodeList dom_document_get_elements_by_tag_name_ns(string namespaceURI, string localName); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-getElBTNNS Since: DOM Level 2 */ PHP_FUNCTION(dom_document_get_elements_by_tag_name_ns) { zval *id; xmlDocPtr docp; int uri_len, name_len; dom_object *intern, *namednode; char *uri, *name; xmlChar *local, *nsuri; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oss", &id, dom_document_class_entry, &uri, &uri_len, &name, &name_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); php_dom_create_interator(return_value, DOM_NODELIST TSRMLS_CC); namednode = (dom_object *)zend_objects_get_address(return_value TSRMLS_CC); local = xmlCharStrndup(name, name_len); nsuri = xmlCharStrndup(uri, uri_len); dom_namednode_iter(intern, 0, namednode, NULL, local, nsuri TSRMLS_CC); } /* }}} end dom_document_get_elements_by_tag_name_ns */ /* {{{ proto DOMElement dom_document_get_element_by_id(string elementId); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-getElBId Since: DOM Level 2 */ PHP_FUNCTION(dom_document_get_element_by_id) { zval *id, *rv = NULL; xmlDocPtr docp; xmlAttrPtr attrp; int ret, idname_len; dom_object *intern; char *idname; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &idname, &idname_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); attrp = xmlGetID(docp, (xmlChar *) idname); if (attrp && attrp->parent) { DOM_RET_OBJ(rv, (xmlNodePtr) attrp->parent, &ret, intern); } else { RETVAL_NULL(); } } /* }}} end dom_document_get_element_by_id */ /* {{{ proto DOMNode dom_document_adopt_node(DOMNode source); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-adoptNode Since: DOM Level 3 */ PHP_FUNCTION(dom_document_adopt_node) { DOM_NOT_IMPLEMENTED(); } /* }}} end dom_document_adopt_node */ /* {{{ proto void dom_document_normalize_document(); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-normalizeDocument Since: DOM Level 3 */ PHP_FUNCTION(dom_document_normalize_document) { zval *id; xmlDocPtr docp; dom_object *intern; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &id, dom_document_class_entry) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); dom_normalize((xmlNodePtr) docp TSRMLS_CC); } /* }}} end dom_document_normalize_document */ /* {{{ proto DOMNode dom_document_rename_node(node n, string namespaceURI, string qualifiedName); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-renameNode Since: DOM Level 3 */ PHP_FUNCTION(dom_document_rename_node) { DOM_NOT_IMPLEMENTED(); } /* }}} end dom_document_rename_node */ /* {{{ proto void DOMDocument::__construct([string version], [string encoding]); */ PHP_METHOD(domdocument, __construct) { zval *id; xmlDoc *docp = NULL, *olddoc; dom_object *intern; char *encoding, *version = NULL; int encoding_len = 0, version_len = 0, refcount; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, dom_domexception_class_entry, &error_handling TSRMLS_CC); if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|ss", &id, dom_document_class_entry, &version, &version_len, &encoding, &encoding_len) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } zend_restore_error_handling(&error_handling TSRMLS_CC); docp = xmlNewDoc(version); if (!docp) { php_dom_throw_error(INVALID_STATE_ERR, 1 TSRMLS_CC); RETURN_FALSE; } if (encoding_len > 0) { docp->encoding = (const xmlChar*)xmlStrdup(encoding); } intern = (dom_object *)zend_object_store_get_object(id TSRMLS_CC); if (intern != NULL) { olddoc = (xmlDocPtr) dom_object_get_node(intern); if (olddoc != NULL) { php_libxml_decrement_node_ptr((php_libxml_node_object *) intern TSRMLS_CC); refcount = php_libxml_decrement_doc_ref((php_libxml_node_object *)intern TSRMLS_CC); if (refcount != 0) { olddoc->_private = NULL; } } intern->document = NULL; if (php_libxml_increment_doc_ref((php_libxml_node_object *)intern, docp TSRMLS_CC) == -1) { RETURN_FALSE; } php_libxml_increment_node_ptr((php_libxml_node_object *)intern, (xmlNodePtr)docp, (void *)intern TSRMLS_CC); } } /* }}} end DOMDocument::__construct */ char *_dom_get_valid_file_path(char *source, char *resolved_path, int resolved_path_len TSRMLS_DC) /* {{{ */ { xmlURI *uri; xmlChar *escsource; char *file_dest; int isFileUri = 0; uri = xmlCreateURI(); escsource = xmlURIEscapeStr(source, ":"); xmlParseURIReference(uri, escsource); xmlFree(escsource); if (uri->scheme != NULL) { /* absolute file uris - libxml only supports localhost or empty host */ if (strncasecmp(source, "file:///",8) == 0) { isFileUri = 1; #ifdef PHP_WIN32 source += 8; #else source += 7; #endif } else if (strncasecmp(source, "file://localhost/",17) == 0) { isFileUri = 1; #ifdef PHP_WIN32 source += 17; #else source += 16; #endif } } file_dest = source; if ((uri->scheme == NULL || isFileUri)) { /* XXX possible buffer overflow if VCWD_REALPATH does not know size of resolved_path */ if (!VCWD_REALPATH(source, resolved_path) && !expand_filepath(source, resolved_path TSRMLS_CC)) { xmlFreeURI(uri); return NULL; } file_dest = resolved_path; } xmlFreeURI(uri); return file_dest; } /* }}} */ static xmlDocPtr dom_document_parser(zval *id, int mode, char *source, int source_len, int options TSRMLS_DC) /* {{{ */ { xmlDocPtr ret; xmlParserCtxtPtr ctxt = NULL; dom_doc_propsptr doc_props; dom_object *intern; php_libxml_ref_obj *document = NULL; int validate, recover, resolve_externals, keep_blanks, substitute_ent; int resolved_path_len; int old_error_reporting = 0; char *directory=NULL, resolved_path[MAXPATHLEN]; if (id != NULL) { intern = (dom_object *)zend_object_store_get_object(id TSRMLS_CC); document = intern->document; } doc_props = dom_get_doc_props(document); validate = doc_props->validateonparse; resolve_externals = doc_props->resolveexternals; keep_blanks = doc_props->preservewhitespace; substitute_ent = doc_props->substituteentities; recover = doc_props->recover; if (document == NULL) { efree(doc_props); } xmlInitParser(); if (mode == DOM_LOAD_FILE) { char *file_dest = _dom_get_valid_file_path(source, resolved_path, MAXPATHLEN TSRMLS_CC); if (file_dest) { ctxt = xmlCreateFileParserCtxt(file_dest); } } else { ctxt = xmlCreateMemoryParserCtxt(source, source_len); } if (ctxt == NULL) { return(NULL); } /* If loading from memory, we need to set the base directory for the document */ if (mode != DOM_LOAD_FILE) { #if HAVE_GETCWD directory = VCWD_GETCWD(resolved_path, MAXPATHLEN); #elif HAVE_GETWD directory = VCWD_GETWD(resolved_path); #endif if (directory) { if(ctxt->directory != NULL) { xmlFree((char *) ctxt->directory); } resolved_path_len = strlen(resolved_path); if (resolved_path[resolved_path_len - 1] != DEFAULT_SLASH) { resolved_path[resolved_path_len] = DEFAULT_SLASH; resolved_path[++resolved_path_len] = '\0'; } ctxt->directory = (char *) xmlCanonicPath((const xmlChar *) resolved_path); } } ctxt->vctxt.error = php_libxml_ctx_error; ctxt->vctxt.warning = php_libxml_ctx_warning; if (ctxt->sax != NULL) { ctxt->sax->error = php_libxml_ctx_error; ctxt->sax->warning = php_libxml_ctx_warning; } if (validate && ! (options & XML_PARSE_DTDVALID)) { options |= XML_PARSE_DTDVALID; } if (resolve_externals && ! (options & XML_PARSE_DTDATTR)) { options |= XML_PARSE_DTDATTR; } if (substitute_ent && ! (options & XML_PARSE_NOENT)) { options |= XML_PARSE_NOENT; } if (keep_blanks == 0 && ! (options & XML_PARSE_NOBLANKS)) { options |= XML_PARSE_NOBLANKS; } xmlCtxtUseOptions(ctxt, options); ctxt->recovery = recover; if (recover) { old_error_reporting = EG(error_reporting); EG(error_reporting) = old_error_reporting | E_WARNING; } xmlParseDocument(ctxt); if (ctxt->wellFormed || recover) { ret = ctxt->myDoc; if (ctxt->recovery) { EG(error_reporting) = old_error_reporting; } /* If loading from memory, set the base reference uri for the document */ if (ret && ret->URL == NULL && ctxt->directory != NULL) { ret->URL = xmlStrdup(ctxt->directory); } } else { ret = NULL; xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } xmlFreeParserCtxt(ctxt); return(ret); } /* }}} */ /* {{{ static void dom_parse_document(INTERNAL_FUNCTION_PARAMETERS, int mode) */ static void dom_parse_document(INTERNAL_FUNCTION_PARAMETERS, int mode) { zval *id, *rv = NULL; xmlDoc *docp = NULL, *newdoc; dom_doc_propsptr doc_prop; dom_object *intern; char *source; int source_len, refcount, ret; long options = 0; id = getThis(); if (id != NULL && ! instanceof_function(Z_OBJCE_P(id), dom_document_class_entry TSRMLS_CC)) { id = NULL; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &source, &source_len, &options) == FAILURE) { return; } if (!source_len) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty string supplied as input"); RETURN_FALSE; } newdoc = dom_document_parser(id, mode, source, source_len, options TSRMLS_CC); if (!newdoc) RETURN_FALSE; if (id != NULL) { intern = (dom_object *)zend_object_store_get_object(id TSRMLS_CC); if (intern != NULL) { docp = (xmlDocPtr) dom_object_get_node(intern); doc_prop = NULL; if (docp != NULL) { php_libxml_decrement_node_ptr((php_libxml_node_object *) intern TSRMLS_CC); doc_prop = intern->document->doc_props; intern->document->doc_props = NULL; refcount = php_libxml_decrement_doc_ref((php_libxml_node_object *)intern TSRMLS_CC); if (refcount != 0) { docp->_private = NULL; } } intern->document = NULL; if (php_libxml_increment_doc_ref((php_libxml_node_object *)intern, newdoc TSRMLS_CC) == -1) { RETURN_FALSE; } intern->document->doc_props = doc_prop; } php_libxml_increment_node_ptr((php_libxml_node_object *)intern, (xmlNodePtr)newdoc, (void *)intern TSRMLS_CC); RETURN_TRUE; } else { DOM_RET_OBJ(rv, (xmlNodePtr) newdoc, &ret, NULL); } } /* }}} end dom_parser_document */ /* {{{ proto DOMNode dom_document_load(string source [, int options]); URL: http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-DocumentLS-load Since: DOM Level 3 */ PHP_METHOD(domdocument, load) { dom_parse_document(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_FILE); } /* }}} end dom_document_load */ /* {{{ proto DOMNode dom_document_loadxml(string source [, int options]); URL: http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-DocumentLS-loadXML Since: DOM Level 3 */ PHP_METHOD(domdocument, loadXML) { dom_parse_document(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_STRING); } /* }}} end dom_document_loadxml */ /* {{{ proto int dom_document_save(string file); Convenience method to save to file */ PHP_FUNCTION(dom_document_save) { zval *id; xmlDoc *docp; int file_len = 0, bytes, format, saveempty = 0; dom_object *intern; dom_doc_propsptr doc_props; char *file; long options = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|l", &id, dom_document_class_entry, &file, &file_len, &options) == FAILURE) { return; } if (file_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Filename"); RETURN_FALSE; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); /* encoding handled by property on doc */ doc_props = dom_get_doc_props(intern->document); format = doc_props->formatoutput; if (options & LIBXML_SAVE_NOEMPTYTAG) { saveempty = xmlSaveNoEmptyTags; xmlSaveNoEmptyTags = 1; } bytes = xmlSaveFormatFileEnc(file, docp, NULL, format); if (options & LIBXML_SAVE_NOEMPTYTAG) { xmlSaveNoEmptyTags = saveempty; } if (bytes == -1) { RETURN_FALSE; } RETURN_LONG(bytes); } /* }}} end dom_document_save */ /* {{{ proto string dom_document_savexml([node n]); URL: http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-DocumentLS-saveXML Since: DOM Level 3 */ PHP_FUNCTION(dom_document_savexml) { zval *id, *nodep = NULL; xmlDoc *docp; xmlNode *node; xmlBufferPtr buf; xmlChar *mem; dom_object *intern, *nodeobj; dom_doc_propsptr doc_props; int size, format, saveempty = 0; long options = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|O!l", &id, dom_document_class_entry, &nodep, dom_node_class_entry, &options) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); doc_props = dom_get_doc_props(intern->document); format = doc_props->formatoutput; if (nodep != NULL) { /* Dump contents of Node */ DOM_GET_OBJ(node, nodep, xmlNodePtr, nodeobj); if (node->doc != docp) { php_dom_throw_error(WRONG_DOCUMENT_ERR, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } buf = xmlBufferCreate(); if (!buf) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not fetch buffer"); RETURN_FALSE; } if (options & LIBXML_SAVE_NOEMPTYTAG) { saveempty = xmlSaveNoEmptyTags; xmlSaveNoEmptyTags = 1; } xmlNodeDump(buf, docp, node, 0, format); if (options & LIBXML_SAVE_NOEMPTYTAG) { xmlSaveNoEmptyTags = saveempty; } mem = (xmlChar*) xmlBufferContent(buf); if (!mem) { xmlBufferFree(buf); RETURN_FALSE; } RETVAL_STRING(mem, 1); xmlBufferFree(buf); } else { if (options & LIBXML_SAVE_NOEMPTYTAG) { saveempty = xmlSaveNoEmptyTags; xmlSaveNoEmptyTags = 1; } /* Encoding is handled from the encoding property set on the document */ xmlDocDumpFormatMemory(docp, &mem, &size, format); if (options & LIBXML_SAVE_NOEMPTYTAG) { xmlSaveNoEmptyTags = saveempty; } if (!size) { RETURN_FALSE; } RETVAL_STRINGL(mem, size, 1); xmlFree(mem); } } /* }}} end dom_document_savexml */ static xmlNodePtr php_dom_free_xinclude_node(xmlNodePtr cur TSRMLS_DC) /* {{{ */ { xmlNodePtr xincnode; xincnode = cur; cur = cur->next; xmlUnlinkNode(xincnode); php_libxml_node_free_resource(xincnode TSRMLS_CC); return cur; } /* }}} */ static void php_dom_remove_xinclude_nodes(xmlNodePtr cur TSRMLS_DC) /* {{{ */ { while(cur) { if (cur->type == XML_XINCLUDE_START) { cur = php_dom_free_xinclude_node(cur TSRMLS_CC); /* XML_XINCLUDE_END node will be a sibling of XML_XINCLUDE_START */ while(cur && cur->type != XML_XINCLUDE_END) { /* remove xinclude processing nodes from recursive xincludes */ if (cur->type == XML_ELEMENT_NODE) { php_dom_remove_xinclude_nodes(cur->children TSRMLS_CC); } cur = cur->next; } if (cur && cur->type == XML_XINCLUDE_END) { cur = php_dom_free_xinclude_node(cur TSRMLS_CC); } } else { if (cur->type == XML_ELEMENT_NODE) { php_dom_remove_xinclude_nodes(cur->children TSRMLS_CC); } cur = cur->next; } } } /* }}} */ /* {{{ proto int dom_document_xinclude([int options]) Substitutues xincludes in a DomDocument */ PHP_FUNCTION(dom_document_xinclude) { zval *id; xmlDoc *docp; xmlNodePtr root; long flags = 0; int err; dom_object *intern; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|l", &id, dom_document_class_entry, &flags) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); err = xmlXIncludeProcessFlags(docp, flags); /* XML_XINCLUDE_START and XML_XINCLUDE_END nodes need to be removed as these are added via xmlXIncludeProcess to mark beginning and ending of xincluded document but are not wanted in resulting document - must be done even if err as it could fail after having processed some xincludes */ root = (xmlNodePtr) docp->children; while(root && root->type != XML_ELEMENT_NODE && root->type != XML_XINCLUDE_START) { root = root->next; } if (root) { php_dom_remove_xinclude_nodes(root TSRMLS_CC); } if (err) { RETVAL_LONG(err); } else { RETVAL_FALSE; } } /* }}} */ /* {{{ proto boolean dom_document_validate(); Since: DOM extended */ PHP_FUNCTION(dom_document_validate) { zval *id; xmlDoc *docp; dom_object *intern; xmlValidCtxt *cvp; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &id, dom_document_class_entry) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); cvp = xmlNewValidCtxt(); cvp->userData = NULL; cvp->error = (xmlValidityErrorFunc) php_libxml_error_handler; cvp->warning = (xmlValidityErrorFunc) php_libxml_error_handler; if (xmlValidateDocument(cvp, docp)) { RETVAL_TRUE; } else { RETVAL_FALSE; } xmlFreeValidCtxt(cvp); } /* }}} */ #if defined(LIBXML_SCHEMAS_ENABLED) static void _dom_document_schema_validate(INTERNAL_FUNCTION_PARAMETERS, int type) /* {{{ */ { zval *id; xmlDoc *docp; dom_object *intern; char *source = NULL, *valid_file = NULL; int source_len = 0; xmlSchemaParserCtxtPtr parser; xmlSchemaPtr sptr; xmlSchemaValidCtxtPtr vptr; int is_valid; char resolved_path[MAXPATHLEN + 1]; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &source, &source_len) == FAILURE) { return; } if (source_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Schema source"); RETURN_FALSE; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); switch (type) { case DOM_LOAD_FILE: valid_file = _dom_get_valid_file_path(source, resolved_path, MAXPATHLEN TSRMLS_CC); if (!valid_file) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Schema file source"); RETURN_FALSE; } parser = xmlSchemaNewParserCtxt(valid_file); break; case DOM_LOAD_STRING: parser = xmlSchemaNewMemParserCtxt(source, source_len); /* If loading from memory, we need to set the base directory for the document but it is not apparent how to do that for schema's */ break; default: return; } xmlSchemaSetParserErrors(parser, (xmlSchemaValidityErrorFunc) php_libxml_error_handler, (xmlSchemaValidityWarningFunc) php_libxml_error_handler, parser); sptr = xmlSchemaParse(parser); xmlSchemaFreeParserCtxt(parser); if (!sptr) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Schema"); RETURN_FALSE; } docp = (xmlDocPtr) dom_object_get_node(intern); vptr = xmlSchemaNewValidCtxt(sptr); if (!vptr) { xmlSchemaFree(sptr); php_error(E_ERROR, "Invalid Schema Validation Context"); RETURN_FALSE; } xmlSchemaSetValidErrors(vptr, php_libxml_error_handler, php_libxml_error_handler, vptr); is_valid = xmlSchemaValidateDoc(vptr, docp); xmlSchemaFree(sptr); xmlSchemaFreeValidCtxt(vptr); if (is_valid == 0) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto boolean dom_document_schema_validate_file(string filename); */ PHP_FUNCTION(dom_document_schema_validate_file) { _dom_document_schema_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_FILE); } /* }}} end dom_document_schema_validate_file */ /* {{{ proto boolean dom_document_schema_validate(string source); */ PHP_FUNCTION(dom_document_schema_validate_xml) { _dom_document_schema_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_STRING); } /* }}} end dom_document_schema_validate */ static void _dom_document_relaxNG_validate(INTERNAL_FUNCTION_PARAMETERS, int type) /* {{{ */ { zval *id; xmlDoc *docp; dom_object *intern; char *source = NULL, *valid_file = NULL; int source_len = 0; xmlRelaxNGParserCtxtPtr parser; xmlRelaxNGPtr sptr; xmlRelaxNGValidCtxtPtr vptr; int is_valid; char resolved_path[MAXPATHLEN + 1]; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &source, &source_len) == FAILURE) { return; } if (source_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Schema source"); RETURN_FALSE; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); switch (type) { case DOM_LOAD_FILE: valid_file = _dom_get_valid_file_path(source, resolved_path, MAXPATHLEN TSRMLS_CC); if (!valid_file) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid RelaxNG file source"); RETURN_FALSE; } parser = xmlRelaxNGNewParserCtxt(valid_file); break; case DOM_LOAD_STRING: parser = xmlRelaxNGNewMemParserCtxt(source, source_len); /* If loading from memory, we need to set the base directory for the document but it is not apparent how to do that for schema's */ break; default: return; } xmlRelaxNGSetParserErrors(parser, (xmlRelaxNGValidityErrorFunc) php_libxml_error_handler, (xmlRelaxNGValidityWarningFunc) php_libxml_error_handler, parser); sptr = xmlRelaxNGParse(parser); xmlRelaxNGFreeParserCtxt(parser); if (!sptr) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid RelaxNG"); RETURN_FALSE; } docp = (xmlDocPtr) dom_object_get_node(intern); vptr = xmlRelaxNGNewValidCtxt(sptr); if (!vptr) { xmlRelaxNGFree(sptr); php_error(E_ERROR, "Invalid RelaxNG Validation Context"); RETURN_FALSE; } xmlRelaxNGSetValidErrors(vptr, php_libxml_error_handler, php_libxml_error_handler, vptr); is_valid = xmlRelaxNGValidateDoc(vptr, docp); xmlRelaxNGFree(sptr); xmlRelaxNGFreeValidCtxt(vptr); if (is_valid == 0) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto boolean dom_document_relaxNG_validate_file(string filename); */ PHP_FUNCTION(dom_document_relaxNG_validate_file) { _dom_document_relaxNG_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_FILE); } /* }}} end dom_document_relaxNG_validate_file */ /* {{{ proto boolean dom_document_relaxNG_validate_xml(string source); */ PHP_FUNCTION(dom_document_relaxNG_validate_xml) { _dom_document_relaxNG_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_STRING); } /* }}} end dom_document_relaxNG_validate_xml */ #endif #if defined(LIBXML_HTML_ENABLED) static void dom_load_html(INTERNAL_FUNCTION_PARAMETERS, int mode) /* {{{ */ { zval *id, *rv = NULL; xmlDoc *docp = NULL, *newdoc; dom_object *intern; dom_doc_propsptr doc_prop; char *source; int source_len, refcount, ret; htmlParserCtxtPtr ctxt; id = getThis(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &source, &source_len) == FAILURE) { return; } if (!source_len) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty string supplied as input"); RETURN_FALSE; } if (mode == DOM_LOAD_FILE) { ctxt = htmlCreateFileParserCtxt(source, NULL); } else { source_len = xmlStrlen(source); ctxt = htmlCreateMemoryParserCtxt(source, source_len); } if (!ctxt) { RETURN_FALSE; } ctxt->vctxt.error = php_libxml_ctx_error; ctxt->vctxt.warning = php_libxml_ctx_warning; if (ctxt->sax != NULL) { ctxt->sax->error = php_libxml_ctx_error; ctxt->sax->warning = php_libxml_ctx_warning; } htmlParseDocument(ctxt); newdoc = ctxt->myDoc; htmlFreeParserCtxt(ctxt); if (!newdoc) RETURN_FALSE; if (id != NULL && instanceof_function(Z_OBJCE_P(id), dom_document_class_entry TSRMLS_CC)) { intern = (dom_object *)zend_object_store_get_object(id TSRMLS_CC); if (intern != NULL) { docp = (xmlDocPtr) dom_object_get_node(intern); doc_prop = NULL; if (docp != NULL) { php_libxml_decrement_node_ptr((php_libxml_node_object *) intern TSRMLS_CC); doc_prop = intern->document->doc_props; intern->document->doc_props = NULL; refcount = php_libxml_decrement_doc_ref((php_libxml_node_object *)intern TSRMLS_CC); if (refcount != 0) { docp->_private = NULL; } } intern->document = NULL; if (php_libxml_increment_doc_ref((php_libxml_node_object *)intern, newdoc TSRMLS_CC) == -1) { RETURN_FALSE; } intern->document->doc_props = doc_prop; } php_libxml_increment_node_ptr((php_libxml_node_object *)intern, (xmlNodePtr)newdoc, (void *)intern TSRMLS_CC); RETURN_TRUE; } else { DOM_RET_OBJ(rv, (xmlNodePtr) newdoc, &ret, NULL); } } /* }}} */ /* {{{ proto DOMNode dom_document_load_html_file(string source); Since: DOM extended */ PHP_METHOD(domdocument, loadHTMLFile) { dom_load_html(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_FILE); } /* }}} end dom_document_load_html_file */ /* {{{ proto DOMNode dom_document_load_html(string source); Since: DOM extended */ PHP_METHOD(domdocument, loadHTML) { dom_load_html(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_STRING); } /* }}} end dom_document_load_html */ /* {{{ proto int dom_document_save_html_file(string file); Convenience method to save to file as html */ PHP_FUNCTION(dom_document_save_html_file) { zval *id; xmlDoc *docp; int file_len, bytes, format; dom_object *intern; dom_doc_propsptr doc_props; char *file; const char *encoding; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &file, &file_len) == FAILURE) { return; } if (file_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Filename"); RETURN_FALSE; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); encoding = (const char *) htmlGetMetaEncoding(docp); doc_props = dom_get_doc_props(intern->document); format = doc_props->formatoutput; bytes = htmlSaveFileFormat(file, docp, encoding, format); if (bytes == -1) { RETURN_FALSE; } RETURN_LONG(bytes); } /* }}} end dom_document_save_html_file */ /* {{{ proto string dom_document_save_html(); Convenience method to output as html */ PHP_FUNCTION(dom_document_save_html) { zval *id, *nodep = NULL; xmlDoc *docp; xmlNode *node; xmlBufferPtr buf; dom_object *intern, *nodeobj; xmlChar *mem = NULL; int size, format; dom_doc_propsptr doc_props; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|O!", &id, dom_document_class_entry, &nodep, dom_node_class_entry) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); doc_props = dom_get_doc_props(intern->document); format = doc_props->formatoutput; if (nodep != NULL) { /* Dump contents of Node */ DOM_GET_OBJ(node, nodep, xmlNodePtr, nodeobj); if (node->doc != docp) { php_dom_throw_error(WRONG_DOCUMENT_ERR, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } buf = xmlBufferCreate(); if (!buf) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not fetch buffer"); RETURN_FALSE; } xmlNodeDump(buf, docp, node, 0, format); mem = (xmlChar*) xmlBufferContent(buf); if (!mem) { RETVAL_FALSE; } else { RETVAL_STRING(mem, 1); } xmlBufferFree(buf); } else { #if LIBXML_VERSION >= 20623 htmlDocDumpMemoryFormat(docp, &mem, &size, format); #else htmlDocDumpMemory(docp, &mem, &size); #endif if (!size) { RETVAL_FALSE; } else { RETVAL_STRINGL(mem, size, 1); } if (mem) xmlFree(mem); } } /* }}} end dom_document_save_html */ #endif /* defined(LIBXML_HTML_ENABLED) */ /* {{{ proto boolean DOMDocument::registerNodeClass(string baseclass, string extendedclass); Register extended class used to create base node type */ PHP_METHOD(domdocument, registerNodeClass) { zval *id; xmlDoc *docp; char *baseclass = NULL, *extendedclass = NULL; int baseclass_len = 0, extendedclass_len = 0; zend_class_entry *basece = NULL, *ce = NULL; dom_object *intern; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oss!", &id, dom_document_class_entry, &baseclass, &baseclass_len, &extendedclass, &extendedclass_len) == FAILURE) { return; } if (baseclass_len) { zend_class_entry **pce; if (zend_lookup_class(baseclass, baseclass_len, &pce TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Class %s does not exist", baseclass); return; } basece = *pce; } if (basece == NULL || ! instanceof_function(basece, dom_node_class_entry TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Class %s is not derived from DOMNode.", baseclass); return; } if (extendedclass_len) { zend_class_entry **pce; if (zend_lookup_class(extendedclass, extendedclass_len, &pce TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Class %s does not exist", extendedclass); } ce = *pce; } if (ce == NULL || instanceof_function(ce, basece TSRMLS_CC)) { DOM_GET_OBJ(docp, id, xmlDocPtr, intern); if (dom_set_doc_classmap(intern->document, basece, ce TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Class %s could not be registered.", extendedclass); } RETURN_TRUE; } else { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Class %s is not derived from %s.", extendedclass, baseclass); } RETURN_FALSE; } /* }}} */ #endif /* HAVE_LIBXML && HAVE_DOM */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-01-18-b5e12bd4da-163b3bcec9.c
manybugs_data_22
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Derick Rethans <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "php.h" #include "php_streams.h" #include "php_main.h" #include "php_globals.h" #include "php_ini.h" #include "ext/standard/info.h" #include "ext/standard/php_versioning.h" #include "ext/standard/php_math.h" #include "php_date.h" #include "zend_interfaces.h" #include "lib/timelib.h" #include <time.h> #ifdef PHP_WIN32 static __inline __int64 php_date_llabs( __int64 i ) { return i >= 0? i: -i; } #elif defined(__GNUC__) && __GNUC__ < 3 static __inline __int64_t php_date_llabs( __int64_t i ) { return i >= 0 ? i : -i; } #else static inline long long php_date_llabs( long long i ) { return i >= 0 ? i : -i; } #endif /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_date, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_gmdate, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_idate, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strtotime, 0, 0, 1) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, now) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mktime, 0, 0, 0) ZEND_ARG_INFO(0, hour) ZEND_ARG_INFO(0, min) ZEND_ARG_INFO(0, sec) ZEND_ARG_INFO(0, mon) ZEND_ARG_INFO(0, day) ZEND_ARG_INFO(0, year) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_gmmktime, 0, 0, 0) ZEND_ARG_INFO(0, hour) ZEND_ARG_INFO(0, min) ZEND_ARG_INFO(0, sec) ZEND_ARG_INFO(0, mon) ZEND_ARG_INFO(0, day) ZEND_ARG_INFO(0, year) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_checkdate, 0) ZEND_ARG_INFO(0, month) ZEND_ARG_INFO(0, day) ZEND_ARG_INFO(0, year) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strftime, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_gmstrftime, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_time, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_localtime, 0, 0, 0) ZEND_ARG_INFO(0, timestamp) ZEND_ARG_INFO(0, associative_array) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_getdate, 0, 0, 0) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_default_timezone_set, 0) ZEND_ARG_INFO(0, timezone_identifier) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_default_timezone_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_sunrise, 0, 0, 1) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, latitude) ZEND_ARG_INFO(0, longitude) ZEND_ARG_INFO(0, zenith) ZEND_ARG_INFO(0, gmt_offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_sunset, 0, 0, 1) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, latitude) ZEND_ARG_INFO(0, longitude) ZEND_ARG_INFO(0, zenith) ZEND_ARG_INFO(0, gmt_offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_sun_info, 0) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, latitude) ZEND_ARG_INFO(0, longitude) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_create, 0, 0, 0) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_create_from_format, 0, 0, 2) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_parse, 0, 0, 1) ZEND_ARG_INFO(0, date) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_parse_from_format, 0, 0, 2) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, date) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_get_last_errors, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_format, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_format, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_modify, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, modify) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_modify, 0, 0, 1) ZEND_ARG_INFO(0, modify) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_add, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, interval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_add, 0, 0, 1) ZEND_ARG_INFO(0, interval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_sub, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, interval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_sub, 0, 0, 1) ZEND_ARG_INFO(0, interval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_timezone_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_method_timezone_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_timezone_set, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, timezone) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_timezone_set, 0, 0, 1) ZEND_ARG_INFO(0, timezone) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_offset_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_method_offset_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_diff, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, object2) ZEND_ARG_INFO(0, absolute) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_diff, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, absolute) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_time_set, 0, 0, 3) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, hour) ZEND_ARG_INFO(0, minute) ZEND_ARG_INFO(0, second) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_time_set, 0, 0, 2) ZEND_ARG_INFO(0, hour) ZEND_ARG_INFO(0, minute) ZEND_ARG_INFO(0, second) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_date_set, 0, 0, 4) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, year) ZEND_ARG_INFO(0, month) ZEND_ARG_INFO(0, day) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_date_set, 0, 0, 3) ZEND_ARG_INFO(0, year) ZEND_ARG_INFO(0, month) ZEND_ARG_INFO(0, day) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_isodate_set, 0, 0, 3) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, year) ZEND_ARG_INFO(0, week) ZEND_ARG_INFO(0, day) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_isodate_set, 0, 0, 2) ZEND_ARG_INFO(0, year) ZEND_ARG_INFO(0, week) ZEND_ARG_INFO(0, day) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_timestamp_set, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, unixtimestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_timestamp_set, 0, 0, 1) ZEND_ARG_INFO(0, unixtimestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_timestamp_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_method_timestamp_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_open, 0, 0, 1) ZEND_ARG_INFO(0, timezone) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_name_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_method_name_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_name_from_abbr, 0, 0, 1) ZEND_ARG_INFO(0, abbr) ZEND_ARG_INFO(0, gmtoffset) ZEND_ARG_INFO(0, isdst) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_offset_get, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, datetime) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_method_offset_get, 0, 0, 1) ZEND_ARG_INFO(0, datetime) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_transitions_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, timestamp_begin) ZEND_ARG_INFO(0, timestamp_end) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_method_transitions_get, 0) ZEND_ARG_INFO(0, timestamp_begin) ZEND_ARG_INFO(0, timestamp_end) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_location_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_method_location_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_identifiers_list, 0, 0, 0) ZEND_ARG_INFO(0, what) ZEND_ARG_INFO(0, country) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_abbreviations_list, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_version_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_interval_create_from_date_string, 0, 0, 1) ZEND_ARG_INFO(0, time) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_interval_format, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_method_interval_format, 0) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_period_construct, 0, 0, 3) ZEND_ARG_INFO(0, start) ZEND_ARG_INFO(0, interval) ZEND_ARG_INFO(0, end) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_interval_construct, 0, 0, 0) ZEND_ARG_INFO(0, interval_spec) ZEND_END_ARG_INFO() /* }}} */ /* {{{ Function table */ const zend_function_entry date_functions[] = { PHP_FE(strtotime, arginfo_strtotime) PHP_FE(date, arginfo_date) PHP_FE(idate, arginfo_idate) PHP_FE(gmdate, arginfo_gmdate) PHP_FE(mktime, arginfo_mktime) PHP_FE(gmmktime, arginfo_gmmktime) PHP_FE(checkdate, arginfo_checkdate) #ifdef HAVE_STRFTIME PHP_FE(strftime, arginfo_strftime) PHP_FE(gmstrftime, arginfo_gmstrftime) #endif PHP_FE(time, arginfo_time) PHP_FE(localtime, arginfo_localtime) PHP_FE(getdate, arginfo_getdate) /* Advanced Interface */ PHP_FE(date_create, arginfo_date_create) PHP_FE(date_create_from_format, arginfo_date_create_from_format) PHP_FE(date_parse, arginfo_date_parse) PHP_FE(date_parse_from_format, arginfo_date_parse_from_format) PHP_FE(date_get_last_errors, arginfo_date_get_last_errors) PHP_FE(date_format, arginfo_date_format) PHP_FE(date_modify, arginfo_date_modify) PHP_FE(date_add, arginfo_date_add) PHP_FE(date_sub, arginfo_date_sub) PHP_FE(date_timezone_get, arginfo_date_timezone_get) PHP_FE(date_timezone_set, arginfo_date_timezone_set) PHP_FE(date_offset_get, arginfo_date_offset_get) PHP_FE(date_diff, arginfo_date_diff) PHP_FE(date_time_set, arginfo_date_time_set) PHP_FE(date_date_set, arginfo_date_date_set) PHP_FE(date_isodate_set, arginfo_date_isodate_set) PHP_FE(date_timestamp_set, arginfo_date_timestamp_set) PHP_FE(date_timestamp_get, arginfo_date_timestamp_get) PHP_FE(timezone_open, arginfo_timezone_open) PHP_FE(timezone_name_get, arginfo_timezone_name_get) PHP_FE(timezone_name_from_abbr, arginfo_timezone_name_from_abbr) PHP_FE(timezone_offset_get, arginfo_timezone_offset_get) PHP_FE(timezone_transitions_get, arginfo_timezone_transitions_get) PHP_FE(timezone_location_get, arginfo_timezone_location_get) PHP_FE(timezone_identifiers_list, arginfo_timezone_identifiers_list) PHP_FE(timezone_abbreviations_list, arginfo_timezone_abbreviations_list) PHP_FE(timezone_version_get, arginfo_timezone_version_get) PHP_FE(date_interval_create_from_date_string, arginfo_date_interval_create_from_date_string) PHP_FE(date_interval_format, arginfo_date_interval_format) /* Options and Configuration */ PHP_FE(date_default_timezone_set, arginfo_date_default_timezone_set) PHP_FE(date_default_timezone_get, arginfo_date_default_timezone_get) /* Astronomical functions */ PHP_FE(date_sunrise, arginfo_date_sunrise) PHP_FE(date_sunset, arginfo_date_sunset) PHP_FE(date_sun_info, arginfo_date_sun_info) {NULL, NULL, NULL} }; const zend_function_entry date_funcs_date[] = { PHP_ME(DateTime, __construct, arginfo_date_create, ZEND_ACC_CTOR|ZEND_ACC_PUBLIC) PHP_ME(DateTime, __wakeup, NULL, ZEND_ACC_PUBLIC) PHP_ME(DateTime, __set_state, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_ME_MAPPING(createFromFormat, date_create_from_format, arginfo_date_create_from_format, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_ME_MAPPING(getLastErrors, date_get_last_errors, arginfo_date_get_last_errors, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_ME_MAPPING(format, date_format, arginfo_date_method_format, 0) PHP_ME_MAPPING(modify, date_modify, arginfo_date_method_modify, 0) PHP_ME_MAPPING(add, date_add, arginfo_date_method_add, 0) PHP_ME_MAPPING(sub, date_sub, arginfo_date_method_sub, 0) PHP_ME_MAPPING(getTimezone, date_timezone_get, arginfo_date_method_timezone_get, 0) PHP_ME_MAPPING(setTimezone, date_timezone_set, arginfo_date_method_timezone_set, 0) PHP_ME_MAPPING(getOffset, date_offset_get, arginfo_date_method_offset_get, 0) PHP_ME_MAPPING(setTime, date_time_set, arginfo_date_method_time_set, 0) PHP_ME_MAPPING(setDate, date_date_set, arginfo_date_method_date_set, 0) PHP_ME_MAPPING(setISODate, date_isodate_set, arginfo_date_method_isodate_set, 0) PHP_ME_MAPPING(setTimestamp, date_timestamp_set, arginfo_date_method_timestamp_set, 0) PHP_ME_MAPPING(getTimestamp, date_timestamp_get, arginfo_date_method_timestamp_get, 0) PHP_ME_MAPPING(diff, date_diff, arginfo_date_method_diff, 0) {NULL, NULL, NULL} }; const zend_function_entry date_funcs_timezone[] = { PHP_ME(DateTimeZone, __construct, arginfo_timezone_open, ZEND_ACC_CTOR|ZEND_ACC_PUBLIC) PHP_ME_MAPPING(getName, timezone_name_get, arginfo_timezone_method_name_get, 0) PHP_ME_MAPPING(getOffset, timezone_offset_get, arginfo_timezone_method_offset_get, 0) PHP_ME_MAPPING(getTransitions, timezone_transitions_get, arginfo_timezone_method_transitions_get, 0) PHP_ME_MAPPING(getLocation, timezone_location_get, arginfo_timezone_method_location_get, 0) PHP_ME_MAPPING(listAbbreviations, timezone_abbreviations_list, arginfo_timezone_abbreviations_list, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_ME_MAPPING(listIdentifiers, timezone_identifiers_list, arginfo_timezone_identifiers_list, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) {NULL, NULL, NULL} }; const zend_function_entry date_funcs_interval[] = { PHP_ME(DateInterval, __construct, arginfo_date_interval_construct, ZEND_ACC_CTOR|ZEND_ACC_PUBLIC) PHP_ME_MAPPING(format, date_interval_format, arginfo_date_method_interval_format, 0) PHP_ME_MAPPING(createFromDateString, date_interval_create_from_date_string, arginfo_date_interval_create_from_date_string, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) {NULL, NULL, NULL} }; const zend_function_entry date_funcs_period[] = { PHP_ME(DatePeriod, __construct, arginfo_date_period_construct, ZEND_ACC_CTOR|ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; static char* guess_timezone(const timelib_tzdb *tzdb TSRMLS_DC); static void date_register_classes(TSRMLS_D); /* }}} */ ZEND_DECLARE_MODULE_GLOBALS(date) static PHP_GINIT_FUNCTION(date); /* True global */ timelib_tzdb *php_date_global_timezone_db; int php_date_global_timezone_db_enabled; #define DATE_DEFAULT_LATITUDE "31.7667" #define DATE_DEFAULT_LONGITUDE "35.2333" /* on 90'35; common sunset declaration (start of sun body appear) */ #define DATE_SUNSET_ZENITH "90.583333" /* on 90'35; common sunrise declaration (sun body disappeared) */ #define DATE_SUNRISE_ZENITH "90.583333" /* {{{ INI Settings */ PHP_INI_BEGIN() STD_PHP_INI_ENTRY("date.timezone", "", PHP_INI_ALL, OnUpdateString, default_timezone, zend_date_globals, date_globals) PHP_INI_ENTRY("date.default_latitude", DATE_DEFAULT_LATITUDE, PHP_INI_ALL, NULL) PHP_INI_ENTRY("date.default_longitude", DATE_DEFAULT_LONGITUDE, PHP_INI_ALL, NULL) PHP_INI_ENTRY("date.sunset_zenith", DATE_SUNSET_ZENITH, PHP_INI_ALL, NULL) PHP_INI_ENTRY("date.sunrise_zenith", DATE_SUNRISE_ZENITH, PHP_INI_ALL, NULL) PHP_INI_END() /* }}} */ zend_class_entry *date_ce_date, *date_ce_timezone, *date_ce_interval, *date_ce_period; PHPAPI zend_class_entry *php_date_get_date_ce(void) { return date_ce_date; } PHPAPI zend_class_entry *php_date_get_timezone_ce(void) { return date_ce_timezone; } static zend_object_handlers date_object_handlers_date; static zend_object_handlers date_object_handlers_timezone; static zend_object_handlers date_object_handlers_interval; static zend_object_handlers date_object_handlers_period; #define DATE_SET_CONTEXT \ zval *object; \ object = getThis(); \ #define DATE_FETCH_OBJECT \ php_date_obj *obj; \ DATE_SET_CONTEXT; \ if (object) { \ if (zend_parse_parameters_none() == FAILURE) { \ return; \ } \ } else { \ if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, NULL, "O", &object, date_ce_date) == FAILURE) { \ RETURN_FALSE; \ } \ } \ obj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); \ #define DATE_CHECK_INITIALIZED(member, class_name) \ if (!(member)) { \ php_error_docref(NULL TSRMLS_CC, E_WARNING, "The " #class_name " object has not been correctly initialized by its constructor"); \ RETURN_FALSE; \ } static void date_object_free_storage_date(void *object TSRMLS_DC); static void date_object_free_storage_timezone(void *object TSRMLS_DC); static void date_object_free_storage_interval(void *object TSRMLS_DC); static void date_object_free_storage_period(void *object TSRMLS_DC); static zend_object_value date_object_new_date(zend_class_entry *class_type TSRMLS_DC); static zend_object_value date_object_new_timezone(zend_class_entry *class_type TSRMLS_DC); static zend_object_value date_object_new_interval(zend_class_entry *class_type TSRMLS_DC); static zend_object_value date_object_new_period(zend_class_entry *class_type TSRMLS_DC); static zend_object_value date_object_clone_date(zval *this_ptr TSRMLS_DC); static zend_object_value date_object_clone_timezone(zval *this_ptr TSRMLS_DC); static zend_object_value date_object_clone_interval(zval *this_ptr TSRMLS_DC); static zend_object_value date_object_clone_period(zval *this_ptr TSRMLS_DC); static int date_object_compare_date(zval *d1, zval *d2 TSRMLS_DC); static HashTable *date_object_get_properties(zval *object TSRMLS_DC); static HashTable *date_object_get_properties_interval(zval *object TSRMLS_DC); zval *date_interval_read_property(zval *object, zval *member, int type, const zend_literal *key TSRMLS_DC); void date_interval_write_property(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC); /* {{{ Module struct */ zend_module_entry date_module_entry = { STANDARD_MODULE_HEADER_EX, NULL, NULL, "date", /* extension name */ date_functions, /* function list */ PHP_MINIT(date), /* process startup */ PHP_MSHUTDOWN(date), /* process shutdown */ PHP_RINIT(date), /* request startup */ PHP_RSHUTDOWN(date), /* request shutdown */ PHP_MINFO(date), /* extension info */ PHP_VERSION, /* extension version */ PHP_MODULE_GLOBALS(date), /* globals descriptor */ PHP_GINIT(date), /* globals ctor */ NULL, /* globals dtor */ NULL, /* post deactivate */ STANDARD_MODULE_PROPERTIES_EX }; /* }}} */ /* {{{ PHP_GINIT_FUNCTION */ static PHP_GINIT_FUNCTION(date) { date_globals->default_timezone = NULL; date_globals->timezone = NULL; date_globals->tzcache = NULL; } /* }}} */ static void _php_date_tzinfo_dtor(void *tzinfo) { timelib_tzinfo **tzi = (timelib_tzinfo **)tzinfo; timelib_tzinfo_dtor(*tzi); } /* {{{ PHP_RINIT_FUNCTION */ PHP_RINIT_FUNCTION(date) { if (DATEG(timezone)) { efree(DATEG(timezone)); } DATEG(timezone) = NULL; DATEG(tzcache) = NULL; DATEG(last_errors) = NULL; return SUCCESS; } /* }}} */ /* {{{ PHP_RSHUTDOWN_FUNCTION */ PHP_RSHUTDOWN_FUNCTION(date) { if (DATEG(timezone)) { efree(DATEG(timezone)); } DATEG(timezone) = NULL; if(DATEG(tzcache)) { zend_hash_destroy(DATEG(tzcache)); FREE_HASHTABLE(DATEG(tzcache)); DATEG(tzcache) = NULL; } if (DATEG(last_errors)) { timelib_error_container_dtor(DATEG(last_errors)); DATEG(last_errors) = NULL; } return SUCCESS; } /* }}} */ #define DATE_TIMEZONEDB php_date_global_timezone_db ? php_date_global_timezone_db : timelib_builtin_db() /* * RFC822, Section 5.1: http://www.ietf.org/rfc/rfc822.txt * date-time = [ day "," ] date time ; dd mm yy hh:mm:ss zzz * day = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" * date = 1*2DIGIT month 2DIGIT ; day month year e.g. 20 Jun 82 * month = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec" * time = hour zone ; ANSI and Military * hour = 2DIGIT ":" 2DIGIT [":" 2DIGIT] ; 00:00:00 - 23:59:59 * zone = "UT" / "GMT" / "EST" / "EDT" / "CST" / "CDT" / "MST" / "MDT" / "PST" / "PDT" / 1ALPHA / ( ("+" / "-") 4DIGIT ) */ #define DATE_FORMAT_RFC822 "D, d M y H:i:s O" /* * RFC850, Section 2.1.4: http://www.ietf.org/rfc/rfc850.txt * Format must be acceptable both to the ARPANET and to the getdate routine. * One format that is acceptable to both is Weekday, DD-Mon-YY HH:MM:SS TIMEZONE * TIMEZONE can be any timezone name (3 or more letters) */ #define DATE_FORMAT_RFC850 "l, d-M-y H:i:s T" /* * RFC1036, Section 2.1.2: http://www.ietf.org/rfc/rfc1036.txt * Its format must be acceptable both in RFC-822 and to the getdate(3) * Wdy, DD Mon YY HH:MM:SS TIMEZONE * There is no hope of having a complete list of timezones. Universal * Time (GMT), the North American timezones (PST, PDT, MST, MDT, CST, * CDT, EST, EDT) and the +/-hhmm offset specifed in RFC-822 should be supported. */ #define DATE_FORMAT_RFC1036 "D, d M y H:i:s O" /* * RFC1123, Section 5.2.14: http://www.ietf.org/rfc/rfc1123.txt * RFC-822 Date and Time Specification: RFC-822 Section 5 * The syntax for the date is hereby changed to: date = 1*2DIGIT month 2*4DIGIT */ #define DATE_FORMAT_RFC1123 "D, d M Y H:i:s O" /* * RFC2822, Section 3.3: http://www.ietf.org/rfc/rfc2822.txt * FWS = ([*WSP CRLF] 1*WSP) / ; Folding white space * CFWS = *([FWS] comment) (([FWS] comment) / FWS) * * date-time = [ day-of-week "," ] date FWS time [CFWS] * day-of-week = ([FWS] day-name) * day-name = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" * date = day month year * year = 4*DIGIT * month = (FWS month-name FWS) * month-name = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec" * day = ([FWS] 1*2DIGIT) * time = time-of-day FWS zone * time-of-day = hour ":" minute [ ":" second ] * hour = 2DIGIT * minute = 2DIGIT * second = 2DIGIT * zone = (( "+" / "-" ) 4DIGIT) */ #define DATE_FORMAT_RFC2822 "D, d M Y H:i:s O" /* * RFC3339, Section 5.6: http://www.ietf.org/rfc/rfc3339.txt * date-fullyear = 4DIGIT * date-month = 2DIGIT ; 01-12 * date-mday = 2DIGIT ; 01-28, 01-29, 01-30, 01-31 based on month/year * * time-hour = 2DIGIT ; 00-23 * time-minute = 2DIGIT ; 00-59 * time-second = 2DIGIT ; 00-58, 00-59, 00-60 based on leap second rules * * time-secfrac = "." 1*DIGIT * time-numoffset = ("+" / "-") time-hour ":" time-minute * time-offset = "Z" / time-numoffset * * partial-time = time-hour ":" time-minute ":" time-second [time-secfrac] * full-date = date-fullyear "-" date-month "-" date-mday * full-time = partial-time time-offset * * date-time = full-date "T" full-time */ #define DATE_FORMAT_RFC3339 "Y-m-d\\TH:i:sP" #define DATE_FORMAT_ISO8601 "Y-m-d\\TH:i:sO" #define DATE_TZ_ERRMSG \ "It is not safe to rely on the system's timezone settings. You are " \ "*required* to use the date.timezone setting or the " \ "date_default_timezone_set() function. In case you used any of those " \ "methods and you are still getting this warning, you most likely " \ "misspelled the timezone identifier. " #define SUNFUNCS_RET_TIMESTAMP 0 #define SUNFUNCS_RET_STRING 1 #define SUNFUNCS_RET_DOUBLE 2 /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(date) { REGISTER_INI_ENTRIES(); date_register_classes(TSRMLS_C); /* * RFC4287, Section 3.3: http://www.ietf.org/rfc/rfc4287.txt * A Date construct is an element whose content MUST conform to the * "date-time" production in [RFC3339]. In addition, an uppercase "T" * character MUST be used to separate date and time, and an uppercase * "Z" character MUST be present in the absence of a numeric time zone offset. */ REGISTER_STRING_CONSTANT("DATE_ATOM", DATE_FORMAT_RFC3339, CONST_CS | CONST_PERSISTENT); /* * Preliminary specification: http://wp.netscape.com/newsref/std/cookie_spec.html * "This is based on RFC 822, RFC 850, RFC 1036, and RFC 1123, * with the variations that the only legal time zone is GMT * and the separators between the elements of the date must be dashes." */ REGISTER_STRING_CONSTANT("DATE_COOKIE", DATE_FORMAT_RFC850, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_ISO8601", DATE_FORMAT_ISO8601, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC822", DATE_FORMAT_RFC822, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC850", DATE_FORMAT_RFC850, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC1036", DATE_FORMAT_RFC1036, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC1123", DATE_FORMAT_RFC1123, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC2822", DATE_FORMAT_RFC2822, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC3339", DATE_FORMAT_RFC3339, CONST_CS | CONST_PERSISTENT); /* * RSS 2.0 Specification: http://blogs.law.harvard.edu/tech/rss * "All date-times in RSS conform to the Date and Time Specification of RFC 822, * with the exception that the year may be expressed with two characters or four characters (four preferred)" */ REGISTER_STRING_CONSTANT("DATE_RSS", DATE_FORMAT_RFC1123, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_W3C", DATE_FORMAT_RFC3339, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SUNFUNCS_RET_TIMESTAMP", SUNFUNCS_RET_TIMESTAMP, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SUNFUNCS_RET_STRING", SUNFUNCS_RET_STRING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SUNFUNCS_RET_DOUBLE", SUNFUNCS_RET_DOUBLE, CONST_CS | CONST_PERSISTENT); php_date_global_timezone_db = NULL; php_date_global_timezone_db_enabled = 0; DATEG(last_errors) = NULL; return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ PHP_MSHUTDOWN_FUNCTION(date) { UNREGISTER_INI_ENTRIES(); if (DATEG(last_errors)) { timelib_error_container_dtor(DATEG(last_errors)); } return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(date) { const timelib_tzdb *tzdb = DATE_TIMEZONEDB; php_info_print_table_start(); php_info_print_table_row(2, "date/time support", "enabled"); php_info_print_table_row(2, "\"Olson\" Timezone Database Version", tzdb->version); php_info_print_table_row(2, "Timezone Database", php_date_global_timezone_db_enabled ? "external" : "internal"); php_info_print_table_row(2, "Default timezone", guess_timezone(tzdb TSRMLS_CC)); php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ /* {{{ Timezone Cache functions */ static timelib_tzinfo *php_date_parse_tzfile(char *formal_tzname, const timelib_tzdb *tzdb TSRMLS_DC) { timelib_tzinfo *tzi, **ptzi; if(!DATEG(tzcache)) { ALLOC_HASHTABLE(DATEG(tzcache)); zend_hash_init(DATEG(tzcache), 4, NULL, _php_date_tzinfo_dtor, 0); } if (zend_hash_find(DATEG(tzcache), formal_tzname, strlen(formal_tzname) + 1, (void **) &ptzi) == SUCCESS) { return *ptzi; } tzi = timelib_parse_tzfile(formal_tzname, tzdb); if (tzi) { zend_hash_add(DATEG(tzcache), formal_tzname, strlen(formal_tzname) + 1, (void *) &tzi, sizeof(timelib_tzinfo*), NULL); } return tzi; } /* }}} */ /* {{{ Helper functions */ static char* guess_timezone(const timelib_tzdb *tzdb TSRMLS_DC) { char *env; /* Checking configure timezone */ if (DATEG(timezone) && (strlen(DATEG(timezone)) > 0)) { return DATEG(timezone); } /* Check environment variable */ env = getenv("TZ"); if (env && *env && timelib_timezone_id_is_valid(env, tzdb)) { return env; } /* Check config setting for default timezone */ if (!DATEG(default_timezone)) { /* Special case: ext/date wasn't initialized yet */ zval ztz; if (SUCCESS == zend_get_configuration_directive("date.timezone", sizeof("date.timezone"), &ztz) && Z_TYPE(ztz) == IS_STRING && Z_STRLEN(ztz) > 0 && timelib_timezone_id_is_valid(Z_STRVAL(ztz), tzdb)) { return Z_STRVAL(ztz); } } else if (*DATEG(default_timezone) && timelib_timezone_id_is_valid(DATEG(default_timezone), tzdb)) { return DATEG(default_timezone); } #if HAVE_TM_ZONE /* Try to guess timezone from system information */ { struct tm *ta, tmbuf; time_t the_time; char *tzid = NULL; the_time = time(NULL); ta = php_localtime_r(&the_time, &tmbuf); if (ta) { tzid = timelib_timezone_id_from_abbr(ta->tm_zone, ta->tm_gmtoff, ta->tm_isdst); } if (! tzid) { tzid = "UTC"; } php_error_docref(NULL TSRMLS_CC, E_WARNING, DATE_TZ_ERRMSG "We selected '%s' for '%s/%.1f/%s' instead", tzid, ta ? ta->tm_zone : "Unknown", ta ? (float) (ta->tm_gmtoff / 3600) : 0, ta ? (ta->tm_isdst ? "DST" : "no DST") : "Unknown"); return tzid; } #endif #ifdef PHP_WIN32 { char *tzid; TIME_ZONE_INFORMATION tzi; switch (GetTimeZoneInformation(&tzi)) { /* DST in effect */ case TIME_ZONE_ID_DAYLIGHT: /* If user has disabled DST in the control panel, Windows returns 0 here */ if (tzi.DaylightBias == 0) { goto php_win_std_time; } tzid = timelib_timezone_id_from_abbr("", (tzi.Bias + tzi.DaylightBias) * -60, 1); if (! tzid) { tzid = "UTC"; } php_error_docref(NULL TSRMLS_CC, E_WARNING, DATE_TZ_ERRMSG "We selected '%s' for '%.1f/DST' instead", tzid, ((tzi.Bias + tzi.DaylightBias) / -60.0)); break; /* no DST or not in effect */ case TIME_ZONE_ID_UNKNOWN: case TIME_ZONE_ID_STANDARD: default: php_win_std_time: tzid = timelib_timezone_id_from_abbr("", (tzi.Bias + tzi.StandardBias) * -60, 0); if (! tzid) { tzid = "UTC"; } php_error_docref(NULL TSRMLS_CC, E_WARNING, DATE_TZ_ERRMSG "We selected '%s' for '%.1f/no DST' instead", tzid, ((tzi.Bias + tzi.StandardBias) / -60.0)); break; } return tzid; } #elif defined(NETWARE) /* Try to guess timezone from system information */ { char *tzid = timelib_timezone_id_from_abbr("", ((_timezone * -1) + (daylightOffset * daylightOnOff)), daylightOnOff); if (tzid) { return tzid; } } #endif /* Fallback to UTC */ php_error_docref(NULL TSRMLS_CC, E_WARNING, DATE_TZ_ERRMSG "We had to select 'UTC' because your platform doesn't provide functionality for the guessing algorithm"); return "UTC"; } PHPAPI timelib_tzinfo *get_timezone_info(TSRMLS_D) { char *tz; timelib_tzinfo *tzi; tz = guess_timezone(DATE_TIMEZONEDB TSRMLS_CC); tzi = php_date_parse_tzfile(tz, DATE_TIMEZONEDB TSRMLS_CC); if (! tzi) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Timezone database is corrupt - this should *never* happen!"); } return tzi; } /* }}} */ /* {{{ date() and gmdate() data */ #include "ext/standard/php_smart_str.h" static char *mon_full_names[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; static char *mon_short_names[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; static char *day_full_names[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; static char *day_short_names[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; static char *english_suffix(timelib_sll number) { if (number >= 10 && number <= 19) { return "th"; } else { switch (number % 10) { case 1: return "st"; case 2: return "nd"; case 3: return "rd"; } } return "th"; } /* }}} */ /* {{{ day of week helpers */ char *php_date_full_day_name(timelib_sll y, timelib_sll m, timelib_sll d) { timelib_sll day_of_week = timelib_day_of_week(y, m, d); if (day_of_week < 0) { return "Unknown"; } return day_full_names[day_of_week]; } char *php_date_short_day_name(timelib_sll y, timelib_sll m, timelib_sll d) { timelib_sll day_of_week = timelib_day_of_week(y, m, d); if (day_of_week < 0) { return "Unknown"; } return day_short_names[day_of_week]; } /* }}} */ /* {{{ date_format - (gm)date helper */ static char *date_format(char *format, int format_len, timelib_time *t, int localtime) { smart_str string = {0}; int i, length; char buffer[97]; timelib_time_offset *offset = NULL; timelib_sll isoweek, isoyear; int rfc_colon; if (!format_len) { return estrdup(""); } if (localtime) { if (t->zone_type == TIMELIB_ZONETYPE_ABBR) { offset = timelib_time_offset_ctor(); offset->offset = (t->z - (t->dst * 60)) * -60; offset->leap_secs = 0; offset->is_dst = t->dst; offset->abbr = strdup(t->tz_abbr); } else if (t->zone_type == TIMELIB_ZONETYPE_OFFSET) { offset = timelib_time_offset_ctor(); offset->offset = (t->z) * -60; offset->leap_secs = 0; offset->is_dst = 0; offset->abbr = malloc(9); /* GMT�xxxx\0 */ snprintf(offset->abbr, 9, "GMT%c%02d%02d", localtime ? ((offset->offset < 0) ? '-' : '+') : '+', localtime ? abs(offset->offset / 3600) : 0, localtime ? abs((offset->offset % 3600) / 60) : 0 ); } else { offset = timelib_get_time_zone_info(t->sse, t->tz_info); } } timelib_isoweek_from_date(t->y, t->m, t->d, &isoweek, &isoyear); for (i = 0; i < format_len; i++) { rfc_colon = 0; switch (format[i]) { /* day */ case 'd': length = slprintf(buffer, 32, "%02d", (int) t->d); break; case 'D': length = slprintf(buffer, 32, "%s", php_date_short_day_name(t->y, t->m, t->d)); break; case 'j': length = slprintf(buffer, 32, "%d", (int) t->d); break; case 'l': length = slprintf(buffer, 32, "%s", php_date_full_day_name(t->y, t->m, t->d)); break; case 'S': length = slprintf(buffer, 32, "%s", english_suffix(t->d)); break; case 'w': length = slprintf(buffer, 32, "%d", (int) timelib_day_of_week(t->y, t->m, t->d)); break; case 'N': length = slprintf(buffer, 32, "%d", (int) timelib_iso_day_of_week(t->y, t->m, t->d)); break; case 'z': length = slprintf(buffer, 32, "%d", (int) timelib_day_of_year(t->y, t->m, t->d)); break; /* week */ case 'W': length = slprintf(buffer, 32, "%02d", (int) isoweek); break; /* iso weeknr */ case 'o': length = slprintf(buffer, 32, "%d", (int) isoyear); break; /* iso year */ /* month */ case 'F': length = slprintf(buffer, 32, "%s", mon_full_names[t->m - 1]); break; case 'm': length = slprintf(buffer, 32, "%02d", (int) t->m); break; case 'M': length = slprintf(buffer, 32, "%s", mon_short_names[t->m - 1]); break; case 'n': length = slprintf(buffer, 32, "%d", (int) t->m); break; case 't': length = slprintf(buffer, 32, "%d", (int) timelib_days_in_month(t->y, t->m)); break; /* year */ case 'L': length = slprintf(buffer, 32, "%d", timelib_is_leap((int) t->y)); break; case 'y': length = slprintf(buffer, 32, "%02d", (int) t->y % 100); break; case 'Y': length = slprintf(buffer, 32, "%s%04lld", t->y < 0 ? "-" : "", php_date_llabs((timelib_sll) t->y)); break; /* time */ case 'a': length = slprintf(buffer, 32, "%s", t->h >= 12 ? "pm" : "am"); break; case 'A': length = slprintf(buffer, 32, "%s", t->h >= 12 ? "PM" : "AM"); break; case 'B': { int retval = (((((long)t->sse)-(((long)t->sse) - ((((long)t->sse) % 86400) + 3600))) * 10) / 864); while (retval < 0) { retval += 1000; } retval = retval % 1000; length = slprintf(buffer, 32, "%03d", retval); break; } case 'g': length = slprintf(buffer, 32, "%d", (t->h % 12) ? (int) t->h % 12 : 12); break; case 'G': length = slprintf(buffer, 32, "%d", (int) t->h); break; case 'h': length = slprintf(buffer, 32, "%02d", (t->h % 12) ? (int) t->h % 12 : 12); break; case 'H': length = slprintf(buffer, 32, "%02d", (int) t->h); break; case 'i': length = slprintf(buffer, 32, "%02d", (int) t->i); break; case 's': length = slprintf(buffer, 32, "%02d", (int) t->s); break; case 'u': length = slprintf(buffer, 32, "%06d", (int) floor(t->f * 1000000)); break; /* timezone */ case 'I': length = slprintf(buffer, 32, "%d", localtime ? offset->is_dst : 0); break; case 'P': rfc_colon = 1; /* break intentionally missing */ case 'O': length = slprintf(buffer, 32, "%c%02d%s%02d", localtime ? ((offset->offset < 0) ? '-' : '+') : '+', localtime ? abs(offset->offset / 3600) : 0, rfc_colon ? ":" : "", localtime ? abs((offset->offset % 3600) / 60) : 0 ); break; case 'T': length = slprintf(buffer, 32, "%s", localtime ? offset->abbr : "GMT"); break; case 'e': if (!localtime) { length = slprintf(buffer, 32, "%s", "UTC"); } else { switch (t->zone_type) { case TIMELIB_ZONETYPE_ID: length = slprintf(buffer, 32, "%s", t->tz_info->name); break; case TIMELIB_ZONETYPE_ABBR: length = slprintf(buffer, 32, "%s", offset->abbr); break; case TIMELIB_ZONETYPE_OFFSET: length = slprintf(buffer, 32, "%c%02d:%02d", ((offset->offset < 0) ? '-' : '+'), abs(offset->offset / 3600), abs((offset->offset % 3600) / 60) ); break; } } break; case 'Z': length = slprintf(buffer, 32, "%d", localtime ? offset->offset : 0); break; /* full date/time */ case 'c': length = slprintf(buffer, 96, "%04d-%02d-%02dT%02d:%02d:%02d%c%02d:%02d", (int) t->y, (int) t->m, (int) t->d, (int) t->h, (int) t->i, (int) t->s, localtime ? ((offset->offset < 0) ? '-' : '+') : '+', localtime ? abs(offset->offset / 3600) : 0, localtime ? abs((offset->offset % 3600) / 60) : 0 ); break; case 'r': length = slprintf(buffer, 96, "%3s, %02d %3s %04d %02d:%02d:%02d %c%02d%02d", php_date_short_day_name(t->y, t->m, t->d), (int) t->d, mon_short_names[t->m - 1], (int) t->y, (int) t->h, (int) t->i, (int) t->s, localtime ? ((offset->offset < 0) ? '-' : '+') : '+', localtime ? abs(offset->offset / 3600) : 0, localtime ? abs((offset->offset % 3600) / 60) : 0 ); break; case 'U': length = slprintf(buffer, 32, "%lld", (timelib_sll) t->sse); break; case '\\': if (i < format_len) i++; /* break intentionally missing */ default: buffer[0] = format[i]; buffer[1] = '\0'; length = 1; break; } smart_str_appendl(&string, buffer, length); } smart_str_0(&string); if (localtime) { timelib_time_offset_dtor(offset); } return string.c; } static void php_date(INTERNAL_FUNCTION_PARAMETERS, int localtime) { char *format; int format_len; long ts; char *string; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &format, &format_len, &ts) == FAILURE) { RETURN_FALSE; } if (ZEND_NUM_ARGS() == 1) { ts = time(NULL); } string = php_format_date(format, format_len, ts, localtime TSRMLS_CC); RETVAL_STRING(string, 0); } /* }}} */ PHPAPI char *php_format_date(char *format, int format_len, time_t ts, int localtime TSRMLS_DC) /* {{{ */ { timelib_time *t; timelib_tzinfo *tzi; char *string; t = timelib_time_ctor(); if (localtime) { tzi = get_timezone_info(TSRMLS_C); t->tz_info = tzi; t->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(t, ts); } else { tzi = NULL; timelib_unixtime2gmt(t, ts); } string = date_format(format, format_len, t, localtime); timelib_time_dtor(t); return string; } /* }}} */ /* {{{ php_idate */ PHPAPI int php_idate(char format, time_t ts, int localtime TSRMLS_DC) { timelib_time *t; timelib_tzinfo *tzi; int retval = -1; timelib_time_offset *offset = NULL; timelib_sll isoweek, isoyear; t = timelib_time_ctor(); if (!localtime) { tzi = get_timezone_info(TSRMLS_C); t->tz_info = tzi; t->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(t, ts); } else { tzi = NULL; timelib_unixtime2gmt(t, ts); } if (!localtime) { if (t->zone_type == TIMELIB_ZONETYPE_ABBR) { offset = timelib_time_offset_ctor(); offset->offset = (t->z - (t->dst * 60)) * -60; offset->leap_secs = 0; offset->is_dst = t->dst; offset->abbr = strdup(t->tz_abbr); } else if (t->zone_type == TIMELIB_ZONETYPE_OFFSET) { offset = timelib_time_offset_ctor(); offset->offset = (t->z - (t->dst * 60)) * -60; offset->leap_secs = 0; offset->is_dst = t->dst; offset->abbr = malloc(9); /* GMT�xxxx\0 */ snprintf(offset->abbr, 9, "GMT%c%02d%02d", !localtime ? ((offset->offset < 0) ? '-' : '+') : '+', !localtime ? abs(offset->offset / 3600) : 0, !localtime ? abs((offset->offset % 3600) / 60) : 0 ); } else { offset = timelib_get_time_zone_info(t->sse, t->tz_info); } } timelib_isoweek_from_date(t->y, t->m, t->d, &isoweek, &isoyear); switch (format) { /* day */ case 'd': case 'j': retval = (int) t->d; break; case 'w': retval = (int) timelib_day_of_week(t->y, t->m, t->d); break; case 'z': retval = (int) timelib_day_of_year(t->y, t->m, t->d); break; /* week */ case 'W': retval = (int) isoweek; break; /* iso weeknr */ /* month */ case 'm': case 'n': retval = (int) t->m; break; case 't': retval = (int) timelib_days_in_month(t->y, t->m); break; /* year */ case 'L': retval = (int) timelib_is_leap((int) t->y); break; case 'y': retval = (int) (t->y % 100); break; case 'Y': retval = (int) t->y; break; /* Swatch Beat a.k.a. Internet Time */ case 'B': retval = (((((long)t->sse)-(((long)t->sse) - ((((long)t->sse) % 86400) + 3600))) * 10) / 864); while (retval < 0) { retval += 1000; } retval = retval % 1000; break; /* time */ case 'g': case 'h': retval = (int) ((t->h % 12) ? (int) t->h % 12 : 12); break; case 'H': case 'G': retval = (int) t->h; break; case 'i': retval = (int) t->i; break; case 's': retval = (int) t->s; break; /* timezone */ case 'I': retval = (int) (!localtime ? offset->is_dst : 0); break; case 'Z': retval = (int) (!localtime ? offset->offset : 0); break; case 'U': retval = (int) t->sse; break; } if (!localtime) { timelib_time_offset_dtor(offset); } timelib_time_dtor(t); return retval; } /* }}} */ /* {{{ proto string date(string format [, long timestamp]) Format a local date/time */ PHP_FUNCTION(date) { php_date(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto string gmdate(string format [, long timestamp]) Format a GMT date/time */ PHP_FUNCTION(gmdate) { php_date(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto int idate(string format [, int timestamp]) Format a local time/date as integer */ PHP_FUNCTION(idate) { char *format; int format_len; long ts = 0; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &format, &format_len, &ts) == FAILURE) { RETURN_FALSE; } if (format_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "idate format is one char"); RETURN_FALSE; } if (ZEND_NUM_ARGS() == 1) { ts = time(NULL); } ret = php_idate(format[0], ts, 0 TSRMLS_CC); if (ret == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unrecognized date format token."); RETURN_FALSE; } RETURN_LONG(ret); } /* }}} */ /* {{{ php_date_set_tzdb - NOT THREADSAFE */ PHPAPI void php_date_set_tzdb(timelib_tzdb *tzdb) { const timelib_tzdb *builtin = timelib_builtin_db(); if (php_version_compare(tzdb->version, builtin->version) > 0) { php_date_global_timezone_db = tzdb; php_date_global_timezone_db_enabled = 1; } } /* }}} */ /* {{{ php_parse_date: Backwards compability function */ PHPAPI signed long php_parse_date(char *string, signed long *now) { timelib_time *parsed_time; timelib_error_container *error = NULL; int error2; signed long retval; parsed_time = timelib_strtotime(string, strlen(string), &error, DATE_TIMEZONEDB); if (error->error_count) { timelib_error_container_dtor(error); return -1; } timelib_error_container_dtor(error); timelib_update_ts(parsed_time, NULL); retval = timelib_date_to_int(parsed_time, &error2); timelib_time_dtor(parsed_time); if (error2) { return -1; } return retval; } /* }}} */ /* {{{ proto int strtotime(string time [, int now ]) Convert string representation of date and time to a timestamp */ PHP_FUNCTION(strtotime) { char *times, *initial_ts; int time_len, error1, error2; struct timelib_error_container *error; long preset_ts = 0, ts; timelib_time *t, *now; timelib_tzinfo *tzi; tzi = get_timezone_info(TSRMLS_C); if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "sl", &times, &time_len, &preset_ts) != FAILURE) { /* We have an initial timestamp */ now = timelib_time_ctor(); initial_ts = emalloc(25); snprintf(initial_ts, 24, "@%ld UTC", preset_ts); t = timelib_strtotime(initial_ts, strlen(initial_ts), NULL, DATE_TIMEZONEDB); /* we ignore the error here, as this should never fail */ timelib_update_ts(t, tzi); now->tz_info = tzi; now->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(now, t->sse); timelib_time_dtor(t); efree(initial_ts); } else if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &times, &time_len, &preset_ts) != FAILURE) { /* We have no initial timestamp */ now = timelib_time_ctor(); now->tz_info = tzi; now->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(now, (timelib_sll) time(NULL)); } else { RETURN_FALSE; } if (!time_len) { timelib_time_dtor(now); RETURN_FALSE; } t = timelib_strtotime(times, time_len, &error, DATE_TIMEZONEDB); error1 = error->error_count; timelib_error_container_dtor(error); timelib_fill_holes(t, now, TIMELIB_NO_CLONE); timelib_update_ts(t, tzi); ts = timelib_date_to_int(t, &error2); timelib_time_dtor(now); timelib_time_dtor(t); if (error1 || error2) { RETURN_FALSE; } else { RETURN_LONG(ts); } } /* }}} */ /* {{{ php_mktime - (gm)mktime helper */ PHPAPI void php_mktime(INTERNAL_FUNCTION_PARAMETERS, int gmt) { long hou = 0, min = 0, sec = 0, mon = 0, day = 0, yea = 0, dst = -1; timelib_time *now; timelib_tzinfo *tzi = NULL; long ts, adjust_seconds = 0; int error; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lllllll", &hou, &min, &sec, &mon, &day, &yea, &dst) == FAILURE) { RETURN_FALSE; } /* Initialize structure with current time */ now = timelib_time_ctor(); if (gmt) { timelib_unixtime2gmt(now, (timelib_sll) time(NULL)); } else { tzi = get_timezone_info(TSRMLS_C); now->tz_info = tzi; now->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(now, (timelib_sll) time(NULL)); } /* Fill in the new data */ switch (ZEND_NUM_ARGS()) { case 7: /* break intentionally missing */ case 6: if (yea >= 0 && yea < 70) { yea += 2000; } else if (yea >= 70 && yea <= 100) { yea += 1900; } now->y = yea; /* break intentionally missing again */ case 5: now->d = day; /* break missing intentionally here too */ case 4: now->m = mon; /* and here */ case 3: now->s = sec; /* yup, this break isn't here on purpose too */ case 2: now->i = min; /* last intentionally missing break */ case 1: now->h = hou; break; default: php_error_docref(NULL TSRMLS_CC, E_STRICT, "You should be using the time() function instead"); } /* Update the timestamp */ if (gmt) { timelib_update_ts(now, NULL); } else { timelib_update_ts(now, tzi); } /* Support for the deprecated is_dst parameter */ if (dst != -1) { php_error_docref(NULL TSRMLS_CC, E_DEPRECATED, "The is_dst parameter is deprecated"); if (gmt) { /* GMT never uses DST */ if (dst == 1) { adjust_seconds = -3600; } } else { /* Figure out is_dst for current TS */ timelib_time_offset *tmp_offset; tmp_offset = timelib_get_time_zone_info(now->sse, tzi); if (dst == 1 && tmp_offset->is_dst == 0) { adjust_seconds = -3600; } if (dst == 0 && tmp_offset->is_dst == 1) { adjust_seconds = +3600; } timelib_time_offset_dtor(tmp_offset); } } /* Clean up and return */ ts = timelib_date_to_int(now, &error); ts += adjust_seconds; timelib_time_dtor(now); if (error) { RETURN_FALSE; } else { RETURN_LONG(ts); } } /* }}} */ /* {{{ proto int mktime([int hour [, int min [, int sec [, int mon [, int day [, int year]]]]]]) Get UNIX timestamp for a date */ PHP_FUNCTION(mktime) { php_mktime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto int gmmktime([int hour [, int min [, int sec [, int mon [, int day [, int year]]]]]]) Get UNIX timestamp for a GMT date */ PHP_FUNCTION(gmmktime) { php_mktime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto bool checkdate(int month, int day, int year) Returns true(1) if it is a valid date in gregorian calendar */ PHP_FUNCTION(checkdate) { long m, d, y; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lll", &m, &d, &y) == FAILURE) { RETURN_FALSE; } if (y < 1 || y > 32767 || !timelib_valid_date(y, m, d)) { RETURN_FALSE; } RETURN_TRUE; /* True : This month, day, year arguments are valid */ } /* }}} */ #ifdef HAVE_STRFTIME /* {{{ php_strftime - (gm)strftime helper */ PHPAPI void php_strftime(INTERNAL_FUNCTION_PARAMETERS, int gmt) { char *format, *buf; int format_len; long timestamp = 0; struct tm ta; int max_reallocs = 5; size_t buf_len = 64, real_len; timelib_time *ts; timelib_tzinfo *tzi; timelib_time_offset *offset = NULL; timestamp = (long) time(NULL); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &format, &format_len, &timestamp) == FAILURE) { RETURN_FALSE; } if (format_len == 0) { RETURN_FALSE; } ts = timelib_time_ctor(); if (gmt) { tzi = NULL; timelib_unixtime2gmt(ts, (timelib_sll) timestamp); } else { tzi = get_timezone_info(TSRMLS_C); ts->tz_info = tzi; ts->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(ts, (timelib_sll) timestamp); } ta.tm_sec = ts->s; ta.tm_min = ts->i; ta.tm_hour = ts->h; ta.tm_mday = ts->d; ta.tm_mon = ts->m - 1; ta.tm_year = ts->y - 1900; ta.tm_wday = timelib_day_of_week(ts->y, ts->m, ts->d); ta.tm_yday = timelib_day_of_year(ts->y, ts->m, ts->d); if (gmt) { ta.tm_isdst = 0; #if HAVE_TM_GMTOFF ta.tm_gmtoff = 0; #endif #if HAVE_TM_ZONE ta.tm_zone = "GMT"; #endif } else { offset = timelib_get_time_zone_info(timestamp, tzi); ta.tm_isdst = offset->is_dst; #if HAVE_TM_GMTOFF ta.tm_gmtoff = offset->offset; #endif #if HAVE_TM_ZONE ta.tm_zone = offset->abbr; #endif } buf = (char *) emalloc(buf_len); while ((real_len=strftime(buf, buf_len, format, &ta))==buf_len || real_len==0) { buf_len *= 2; buf = (char *) erealloc(buf, buf_len); if (!--max_reallocs) { break; } } timelib_time_dtor(ts); if (!gmt) { timelib_time_offset_dtor(offset); } if (real_len && real_len != buf_len) { buf = (char *) erealloc(buf, real_len + 1); RETURN_STRINGL(buf, real_len, 0); } efree(buf); RETURN_FALSE; } /* }}} */ /* {{{ proto string strftime(string format [, int timestamp]) Format a local time/date according to locale settings */ PHP_FUNCTION(strftime) { php_strftime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto string gmstrftime(string format [, int timestamp]) Format a GMT/UCT time/date according to locale settings */ PHP_FUNCTION(gmstrftime) { php_strftime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ #endif /* {{{ proto int time(void) Return current UNIX timestamp */ PHP_FUNCTION(time) { RETURN_LONG((long)time(NULL)); } /* }}} */ /* {{{ proto array localtime([int timestamp [, bool associative_array]]) Returns the results of the C system call localtime as an associative array if the associative_array argument is set to 1 other wise it is a regular array */ PHP_FUNCTION(localtime) { long timestamp = (long)time(NULL); zend_bool associative = 0; timelib_tzinfo *tzi; timelib_time *ts; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lb", &timestamp, &associative) == FAILURE) { RETURN_FALSE; } tzi = get_timezone_info(TSRMLS_C); ts = timelib_time_ctor(); ts->tz_info = tzi; ts->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(ts, (timelib_sll) timestamp); array_init(return_value); if (associative) { add_assoc_long(return_value, "tm_sec", ts->s); add_assoc_long(return_value, "tm_min", ts->i); add_assoc_long(return_value, "tm_hour", ts->h); add_assoc_long(return_value, "tm_mday", ts->d); add_assoc_long(return_value, "tm_mon", ts->m - 1); add_assoc_long(return_value, "tm_year", ts->y - 1900); add_assoc_long(return_value, "tm_wday", timelib_day_of_week(ts->y, ts->m, ts->d)); add_assoc_long(return_value, "tm_yday", timelib_day_of_year(ts->y, ts->m, ts->d)); add_assoc_long(return_value, "tm_isdst", ts->dst); } else { add_next_index_long(return_value, ts->s); add_next_index_long(return_value, ts->i); add_next_index_long(return_value, ts->h); add_next_index_long(return_value, ts->d); add_next_index_long(return_value, ts->m - 1); add_next_index_long(return_value, ts->y- 1900); add_next_index_long(return_value, timelib_day_of_week(ts->y, ts->m, ts->d)); add_next_index_long(return_value, timelib_day_of_year(ts->y, ts->m, ts->d)); add_next_index_long(return_value, ts->dst); } timelib_time_dtor(ts); } /* }}} */ /* {{{ proto array getdate([int timestamp]) Get date/time information */ PHP_FUNCTION(getdate) { long timestamp = (long)time(NULL); timelib_tzinfo *tzi; timelib_time *ts; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &timestamp) == FAILURE) { RETURN_FALSE; } tzi = get_timezone_info(TSRMLS_C); ts = timelib_time_ctor(); ts->tz_info = tzi; ts->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(ts, (timelib_sll) timestamp); array_init(return_value); add_assoc_long(return_value, "seconds", ts->s); add_assoc_long(return_value, "minutes", ts->i); add_assoc_long(return_value, "hours", ts->h); add_assoc_long(return_value, "mday", ts->d); add_assoc_long(return_value, "wday", timelib_day_of_week(ts->y, ts->m, ts->d)); add_assoc_long(return_value, "mon", ts->m); add_assoc_long(return_value, "year", ts->y); add_assoc_long(return_value, "yday", timelib_day_of_year(ts->y, ts->m, ts->d)); add_assoc_string(return_value, "weekday", php_date_full_day_name(ts->y, ts->m, ts->d), 1); add_assoc_string(return_value, "month", mon_full_names[ts->m - 1], 1); add_index_long(return_value, 0, timestamp); timelib_time_dtor(ts); } /* }}} */ #define PHP_DATE_TIMEZONE_GROUP_AFRICA 0x0001 #define PHP_DATE_TIMEZONE_GROUP_AMERICA 0x0002 #define PHP_DATE_TIMEZONE_GROUP_ANTARCTICA 0x0004 #define PHP_DATE_TIMEZONE_GROUP_ARCTIC 0x0008 #define PHP_DATE_TIMEZONE_GROUP_ASIA 0x0010 #define PHP_DATE_TIMEZONE_GROUP_ATLANTIC 0x0020 #define PHP_DATE_TIMEZONE_GROUP_AUSTRALIA 0x0040 #define PHP_DATE_TIMEZONE_GROUP_EUROPE 0x0080 #define PHP_DATE_TIMEZONE_GROUP_INDIAN 0x0100 #define PHP_DATE_TIMEZONE_GROUP_PACIFIC 0x0200 #define PHP_DATE_TIMEZONE_GROUP_UTC 0x0400 #define PHP_DATE_TIMEZONE_GROUP_ALL 0x07FF #define PHP_DATE_TIMEZONE_GROUP_ALL_W_BC 0x0FFF #define PHP_DATE_TIMEZONE_PER_COUNTRY 0x1000 #define PHP_DATE_PERIOD_EXCLUDE_START_DATE 0x0001 /* define an overloaded iterator structure */ typedef struct { zend_object_iterator intern; zval *date_period_zval; zval *current; php_period_obj *object; int current_index; } date_period_it; /* {{{ date_period_it_invalidate_current */ static void date_period_it_invalidate_current(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; if (iterator->current) { zval_ptr_dtor(&iterator->current); iterator->current = NULL; } } /* }}} */ /* {{{ date_period_it_dtor */ static void date_period_it_dtor(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; date_period_it_invalidate_current(iter TSRMLS_CC); zval_ptr_dtor(&iterator->date_period_zval); efree(iterator); } /* }}} */ /* {{{ date_period_it_has_more */ static int date_period_it_has_more(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; php_period_obj *object = iterator->object; timelib_time *it_time = object->current; /* apply modification if it's not the first iteration */ if (!object->include_start_date || iterator->current_index > 0) { it_time->have_relative = 1; it_time->relative = *object->interval; it_time->sse_uptodate = 0; timelib_update_ts(it_time, NULL); timelib_update_from_sse(it_time); } if (object->end) { return object->current->sse < object->end->sse ? SUCCESS : FAILURE; } else { return (iterator->current_index < object->recurrences) ? SUCCESS : FAILURE; } } /* }}} */ /* {{{ date_period_it_current_data */ static void date_period_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; php_period_obj *object = iterator->object; timelib_time *it_time = object->current; php_date_obj *newdateobj; /* Create new object */ MAKE_STD_ZVAL(iterator->current); php_date_instantiate(date_ce_date, iterator->current TSRMLS_CC); newdateobj = (php_date_obj *) zend_object_store_get_object(iterator->current TSRMLS_CC); newdateobj->time = timelib_time_ctor(); *newdateobj->time = *it_time; if (it_time->tz_abbr) { newdateobj->time->tz_abbr = strdup(it_time->tz_abbr); } if (it_time->tz_info) { newdateobj->time->tz_info = it_time->tz_info; } *data = &iterator->current; } /* }}} */ /* {{{ date_period_it_current_key */ static int date_period_it_current_key(zend_object_iterator *iter, char **str_key, uint *str_key_len, ulong *int_key TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; *int_key = iterator->current_index; return HASH_KEY_IS_LONG; } /* }}} */ /* {{{ date_period_it_move_forward */ static void date_period_it_move_forward(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; iterator->current_index++; date_period_it_invalidate_current(iter TSRMLS_CC); } /* }}} */ /* {{{ date_period_it_rewind */ static void date_period_it_rewind(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; iterator->current_index = 0; if (iterator->object->current) { timelib_time_dtor(iterator->object->current); } iterator->object->current = timelib_time_clone(iterator->object->start); date_period_it_invalidate_current(iter TSRMLS_CC); } /* }}} */ /* iterator handler table */ zend_object_iterator_funcs date_period_it_funcs = { date_period_it_dtor, date_period_it_has_more, date_period_it_current_data, date_period_it_current_key, date_period_it_move_forward, date_period_it_rewind, date_period_it_invalidate_current }; zend_object_iterator *date_object_period_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) { date_period_it *iterator = emalloc(sizeof(date_period_it)); php_period_obj *dpobj = (php_period_obj *)zend_object_store_get_object(object TSRMLS_CC); if (by_ref) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } Z_ADDREF_P(object); iterator->intern.data = (void*) dpobj; iterator->intern.funcs = &date_period_it_funcs; iterator->date_period_zval = object; iterator->object = dpobj; iterator->current = NULL; return (zend_object_iterator*)iterator; } static void date_register_classes(TSRMLS_D) { zend_class_entry ce_date, ce_timezone, ce_interval, ce_period; INIT_CLASS_ENTRY(ce_date, "DateTime", date_funcs_date); ce_date.create_object = date_object_new_date; date_ce_date = zend_register_internal_class_ex(&ce_date, NULL, NULL TSRMLS_CC); memcpy(&date_object_handlers_date, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); date_object_handlers_date.clone_obj = date_object_clone_date; date_object_handlers_date.compare_objects = date_object_compare_date; date_object_handlers_date.get_properties = date_object_get_properties; #define REGISTER_DATE_CLASS_CONST_STRING(const_name, value) \ zend_declare_class_constant_stringl(date_ce_date, const_name, sizeof(const_name)-1, value, sizeof(value)-1 TSRMLS_CC); REGISTER_DATE_CLASS_CONST_STRING("ATOM", DATE_FORMAT_RFC3339); REGISTER_DATE_CLASS_CONST_STRING("COOKIE", DATE_FORMAT_RFC850); REGISTER_DATE_CLASS_CONST_STRING("ISO8601", DATE_FORMAT_ISO8601); REGISTER_DATE_CLASS_CONST_STRING("RFC822", DATE_FORMAT_RFC822); REGISTER_DATE_CLASS_CONST_STRING("RFC850", DATE_FORMAT_RFC850); REGISTER_DATE_CLASS_CONST_STRING("RFC1036", DATE_FORMAT_RFC1036); REGISTER_DATE_CLASS_CONST_STRING("RFC1123", DATE_FORMAT_RFC1123); REGISTER_DATE_CLASS_CONST_STRING("RFC2822", DATE_FORMAT_RFC2822); REGISTER_DATE_CLASS_CONST_STRING("RFC3339", DATE_FORMAT_RFC3339); REGISTER_DATE_CLASS_CONST_STRING("RSS", DATE_FORMAT_RFC1123); REGISTER_DATE_CLASS_CONST_STRING("W3C", DATE_FORMAT_RFC3339); INIT_CLASS_ENTRY(ce_timezone, "DateTimeZone", date_funcs_timezone); ce_timezone.create_object = date_object_new_timezone; date_ce_timezone = zend_register_internal_class_ex(&ce_timezone, NULL, NULL TSRMLS_CC); memcpy(&date_object_handlers_timezone, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); date_object_handlers_timezone.clone_obj = date_object_clone_timezone; #define REGISTER_TIMEZONE_CLASS_CONST_STRING(const_name, value) \ zend_declare_class_constant_long(date_ce_timezone, const_name, sizeof(const_name)-1, value TSRMLS_CC); REGISTER_TIMEZONE_CLASS_CONST_STRING("AFRICA", PHP_DATE_TIMEZONE_GROUP_AFRICA); REGISTER_TIMEZONE_CLASS_CONST_STRING("AMERICA", PHP_DATE_TIMEZONE_GROUP_AMERICA); REGISTER_TIMEZONE_CLASS_CONST_STRING("ANTARCTICA", PHP_DATE_TIMEZONE_GROUP_ANTARCTICA); REGISTER_TIMEZONE_CLASS_CONST_STRING("ARCTIC", PHP_DATE_TIMEZONE_GROUP_ARCTIC); REGISTER_TIMEZONE_CLASS_CONST_STRING("ASIA", PHP_DATE_TIMEZONE_GROUP_ASIA); REGISTER_TIMEZONE_CLASS_CONST_STRING("ATLANTIC", PHP_DATE_TIMEZONE_GROUP_ATLANTIC); REGISTER_TIMEZONE_CLASS_CONST_STRING("AUSTRALIA", PHP_DATE_TIMEZONE_GROUP_AUSTRALIA); REGISTER_TIMEZONE_CLASS_CONST_STRING("EUROPE", PHP_DATE_TIMEZONE_GROUP_EUROPE); REGISTER_TIMEZONE_CLASS_CONST_STRING("INDIAN", PHP_DATE_TIMEZONE_GROUP_INDIAN); REGISTER_TIMEZONE_CLASS_CONST_STRING("PACIFIC", PHP_DATE_TIMEZONE_GROUP_PACIFIC); REGISTER_TIMEZONE_CLASS_CONST_STRING("UTC", PHP_DATE_TIMEZONE_GROUP_UTC); REGISTER_TIMEZONE_CLASS_CONST_STRING("ALL", PHP_DATE_TIMEZONE_GROUP_ALL); REGISTER_TIMEZONE_CLASS_CONST_STRING("ALL_WITH_BC", PHP_DATE_TIMEZONE_GROUP_ALL_W_BC); REGISTER_TIMEZONE_CLASS_CONST_STRING("PER_COUNTRY", PHP_DATE_TIMEZONE_PER_COUNTRY); INIT_CLASS_ENTRY(ce_interval, "DateInterval", date_funcs_interval); ce_interval.create_object = date_object_new_interval; date_ce_interval = zend_register_internal_class_ex(&ce_interval, NULL, NULL TSRMLS_CC); memcpy(&date_object_handlers_interval, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); date_object_handlers_interval.clone_obj = date_object_clone_interval; date_object_handlers_interval.read_property = date_interval_read_property; date_object_handlers_interval.write_property = date_interval_write_property; date_object_handlers_interval.get_properties = date_object_get_properties_interval; date_object_handlers_interval.get_property_ptr_ptr = NULL; INIT_CLASS_ENTRY(ce_period, "DatePeriod", date_funcs_period); ce_period.create_object = date_object_new_period; date_ce_period = zend_register_internal_class_ex(&ce_period, NULL, NULL TSRMLS_CC); date_ce_period->get_iterator = date_object_period_get_iterator; date_ce_period->iterator_funcs.funcs = &date_period_it_funcs; zend_class_implements(date_ce_period TSRMLS_CC, 1, zend_ce_traversable); memcpy(&date_object_handlers_period, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); date_object_handlers_period.clone_obj = date_object_clone_period; #define REGISTER_PERIOD_CLASS_CONST_STRING(const_name, value) \ zend_declare_class_constant_long(date_ce_period, const_name, sizeof(const_name)-1, value TSRMLS_CC); REGISTER_PERIOD_CLASS_CONST_STRING("EXCLUDE_START_DATE", PHP_DATE_PERIOD_EXCLUDE_START_DATE); } static inline zend_object_value date_object_new_date_ex(zend_class_entry *class_type, php_date_obj **ptr TSRMLS_DC) { php_date_obj *intern; zend_object_value retval; intern = emalloc(sizeof(php_date_obj)); memset(intern, 0, sizeof(php_date_obj)); if (ptr) { *ptr = intern; } zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) date_object_free_storage_date, NULL TSRMLS_CC); retval.handlers = &date_object_handlers_date; return retval; } static zend_object_value date_object_new_date(zend_class_entry *class_type TSRMLS_DC) { return date_object_new_date_ex(class_type, NULL TSRMLS_CC); } static zend_object_value date_object_clone_date(zval *this_ptr TSRMLS_DC) { php_date_obj *new_obj = NULL; php_date_obj *old_obj = (php_date_obj *) zend_object_store_get_object(this_ptr TSRMLS_CC); zend_object_value new_ov = date_object_new_date_ex(old_obj->std.ce, &new_obj TSRMLS_CC); zend_objects_clone_members(&new_obj->std, new_ov, &old_obj->std, Z_OBJ_HANDLE_P(this_ptr) TSRMLS_CC); /* this should probably moved to a new `timelib_time *timelime_time_clone(timelib_time *)` */ new_obj->time = timelib_time_ctor(); *new_obj->time = *old_obj->time; if (old_obj->time->tz_abbr) { new_obj->time->tz_abbr = strdup(old_obj->time->tz_abbr); } if (old_obj->time->tz_info) { new_obj->time->tz_info = old_obj->time->tz_info; } return new_ov; } static int date_object_compare_date(zval *d1, zval *d2 TSRMLS_DC) { if (Z_TYPE_P(d1) == IS_OBJECT && Z_TYPE_P(d2) == IS_OBJECT && instanceof_function(Z_OBJCE_P(d1), date_ce_date TSRMLS_CC) && instanceof_function(Z_OBJCE_P(d2), date_ce_date TSRMLS_CC)) { php_date_obj *o1 = zend_object_store_get_object(d1 TSRMLS_CC); php_date_obj *o2 = zend_object_store_get_object(d2 TSRMLS_CC); if (!o1->time->sse_uptodate) { timelib_update_ts(o1->time, o1->time->tz_info); } if (!o2->time->sse_uptodate) { timelib_update_ts(o2->time, o2->time->tz_info); } return (o1->time->sse == o2->time->sse) ? 0 : ((o1->time->sse < o2->time->sse) ? -1 : 1); } return 1; } static HashTable *date_object_get_properties(zval *object TSRMLS_DC) { HashTable *props; zval *zv; php_date_obj *dateobj; dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); props = zend_std_get_properties(object TSRMLS_CC); if (!dateobj->time || GC_G(gc_active)) { return props; } /* first we add the date and time in ISO format */ MAKE_STD_ZVAL(zv); ZVAL_STRING(zv, date_format("Y-m-d H:i:s", 12, dateobj->time, 1), 0); zend_hash_update(props, "date", 5, &zv, sizeof(zval), NULL); /* then we add the timezone name (or similar) */ if (dateobj->time->is_localtime) { MAKE_STD_ZVAL(zv); ZVAL_LONG(zv, dateobj->time->zone_type); zend_hash_update(props, "timezone_type", 14, &zv, sizeof(zval), NULL); MAKE_STD_ZVAL(zv); switch (dateobj->time->zone_type) { case TIMELIB_ZONETYPE_ID: ZVAL_STRING(zv, dateobj->time->tz_info->name, 1); break; case TIMELIB_ZONETYPE_OFFSET: { char *tmpstr = emalloc(sizeof("UTC+05:00")); timelib_sll utc_offset = dateobj->time->z; snprintf(tmpstr, sizeof("+05:00"), "%c%02d:%02d", utc_offset > 0 ? '-' : '+', abs(utc_offset / 60), abs((utc_offset % 60))); ZVAL_STRING(zv, tmpstr, 0); } break; case TIMELIB_ZONETYPE_ABBR: ZVAL_STRING(zv, dateobj->time->tz_abbr, 1); break; } zend_hash_update(props, "timezone", 9, &zv, sizeof(zval), NULL); } return props; } static inline zend_object_value date_object_new_timezone_ex(zend_class_entry *class_type, php_timezone_obj **ptr TSRMLS_DC) { php_timezone_obj *intern; zend_object_value retval; intern = emalloc(sizeof(php_timezone_obj)); memset(intern, 0, sizeof(php_timezone_obj)); if (ptr) { *ptr = intern; } zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) date_object_free_storage_timezone, NULL TSRMLS_CC); retval.handlers = &date_object_handlers_timezone; return retval; } static zend_object_value date_object_new_timezone(zend_class_entry *class_type TSRMLS_DC) { return date_object_new_timezone_ex(class_type, NULL TSRMLS_CC); } static zend_object_value date_object_clone_timezone(zval *this_ptr TSRMLS_DC) { php_timezone_obj *new_obj = NULL; php_timezone_obj *old_obj = (php_timezone_obj *) zend_object_store_get_object(this_ptr TSRMLS_CC); zend_object_value new_ov = date_object_new_timezone_ex(old_obj->std.ce, &new_obj TSRMLS_CC); zend_objects_clone_members(&new_obj->std, new_ov, &old_obj->std, Z_OBJ_HANDLE_P(this_ptr) TSRMLS_CC); new_obj->type = old_obj->type; new_obj->initialized = 1; switch (new_obj->type) { case TIMELIB_ZONETYPE_ID: new_obj->tzi.tz = old_obj->tzi.tz; break; case TIMELIB_ZONETYPE_OFFSET: new_obj->tzi.utc_offset = old_obj->tzi.utc_offset; break; case TIMELIB_ZONETYPE_ABBR: new_obj->tzi.z.utc_offset = old_obj->tzi.z.utc_offset; new_obj->tzi.z.dst = old_obj->tzi.z.dst; new_obj->tzi.z.abbr = old_obj->tzi.z.abbr; break; } return new_ov; } static inline zend_object_value date_object_new_interval_ex(zend_class_entry *class_type, php_interval_obj **ptr TSRMLS_DC) { php_interval_obj *intern; zend_object_value retval; intern = emalloc(sizeof(php_interval_obj)); memset(intern, 0, sizeof(php_interval_obj)); if (ptr) { *ptr = intern; } zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) date_object_free_storage_interval, NULL TSRMLS_CC); retval.handlers = &date_object_handlers_interval; return retval; } static zend_object_value date_object_new_interval(zend_class_entry *class_type TSRMLS_DC) { return date_object_new_interval_ex(class_type, NULL TSRMLS_CC); } static zend_object_value date_object_clone_interval(zval *this_ptr TSRMLS_DC) { php_interval_obj *new_obj = NULL; php_interval_obj *old_obj = (php_interval_obj *) zend_object_store_get_object(this_ptr TSRMLS_CC); zend_object_value new_ov = date_object_new_interval_ex(old_obj->std.ce, &new_obj TSRMLS_CC); zend_objects_clone_members(&new_obj->std, new_ov, &old_obj->std, Z_OBJ_HANDLE_P(this_ptr) TSRMLS_CC); /** FIX ME ADD CLONE STUFF **/ return new_ov; } static HashTable *date_object_get_properties_interval(zval *object TSRMLS_DC) { HashTable *props; zval *zv; php_interval_obj *intervalobj; intervalobj = (php_interval_obj *) zend_object_store_get_object(object TSRMLS_CC); props = zend_std_get_properties(object TSRMLS_CC); if (!intervalobj->initialized || GC_G(gc_active)) { return props; } #define PHP_DATE_INTERVAL_ADD_PROPERTY(n,f) \ MAKE_STD_ZVAL(zv); \ ZVAL_LONG(zv, intervalobj->diff->f); \ zend_hash_update(props, n, strlen(n) + 1, &zv, sizeof(zval), NULL); PHP_DATE_INTERVAL_ADD_PROPERTY("y", y); PHP_DATE_INTERVAL_ADD_PROPERTY("m", m); PHP_DATE_INTERVAL_ADD_PROPERTY("d", d); PHP_DATE_INTERVAL_ADD_PROPERTY("h", h); PHP_DATE_INTERVAL_ADD_PROPERTY("i", i); PHP_DATE_INTERVAL_ADD_PROPERTY("s", s); PHP_DATE_INTERVAL_ADD_PROPERTY("invert", invert); if (intervalobj->diff->days != -99999) { PHP_DATE_INTERVAL_ADD_PROPERTY("days", days); } else { MAKE_STD_ZVAL(zv); ZVAL_FALSE(zv); zend_hash_update(props, "days", 5, &zv, sizeof(zval), NULL); } return props; } static inline zend_object_value date_object_new_period_ex(zend_class_entry *class_type, php_period_obj **ptr TSRMLS_DC) { php_period_obj *intern; zend_object_value retval; intern = emalloc(sizeof(php_period_obj)); memset(intern, 0, sizeof(php_period_obj)); if (ptr) { *ptr = intern; } zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) date_object_free_storage_period, NULL TSRMLS_CC); retval.handlers = &date_object_handlers_period; return retval; } static zend_object_value date_object_new_period(zend_class_entry *class_type TSRMLS_DC) { return date_object_new_period_ex(class_type, NULL TSRMLS_CC); } static zend_object_value date_object_clone_period(zval *this_ptr TSRMLS_DC) { php_period_obj *new_obj = NULL; php_period_obj *old_obj = (php_period_obj *) zend_object_store_get_object(this_ptr TSRMLS_CC); zend_object_value new_ov = date_object_new_period_ex(old_obj->std.ce, &new_obj TSRMLS_CC); zend_objects_clone_members(&new_obj->std, new_ov, &old_obj->std, Z_OBJ_HANDLE_P(this_ptr) TSRMLS_CC); /** FIX ME ADD CLONE STUFF **/ return new_ov; } static void date_object_free_storage_date(void *object TSRMLS_DC) { php_date_obj *intern = (php_date_obj *)object; if (intern->time) { timelib_time_dtor(intern->time); } zend_object_std_dtor(&intern->std TSRMLS_CC); efree(object); } static void date_object_free_storage_timezone(void *object TSRMLS_DC) { php_timezone_obj *intern = (php_timezone_obj *)object; if (intern->type == TIMELIB_ZONETYPE_ABBR) { free(intern->tzi.z.abbr); } zend_object_std_dtor(&intern->std TSRMLS_CC); efree(object); } static void date_object_free_storage_interval(void *object TSRMLS_DC) { php_interval_obj *intern = (php_interval_obj *)object; timelib_rel_time_dtor(intern->diff); zend_object_std_dtor(&intern->std TSRMLS_CC); efree(object); } static void date_object_free_storage_period(void *object TSRMLS_DC) { php_period_obj *intern = (php_period_obj *)object; if (intern->start) { timelib_time_dtor(intern->start); } if (intern->current) { timelib_time_dtor(intern->current); } if (intern->end) { timelib_time_dtor(intern->end); } timelib_rel_time_dtor(intern->interval); zend_object_std_dtor(&intern->std TSRMLS_CC); efree(object); } /* Advanced Interface */ PHPAPI zval *php_date_instantiate(zend_class_entry *pce, zval *object TSRMLS_DC) { Z_TYPE_P(object) = IS_OBJECT; object_init_ex(object, pce); Z_SET_REFCOUNT_P(object, 1); Z_UNSET_ISREF_P(object); return object; } /* Helper function used to store the latest found warnings and errors while * parsing, from either strtotime or parse_from_format. */ static void update_errors_warnings(timelib_error_container *last_errors TSRMLS_DC) { if (DATEG(last_errors)) { timelib_error_container_dtor(DATEG(last_errors)); DATEG(last_errors) = NULL; } DATEG(last_errors) = last_errors; } PHPAPI int php_date_initialize(php_date_obj *dateobj, /*const*/ char *time_str, int time_str_len, char *format, zval *timezone_object, int ctor TSRMLS_DC) { timelib_time *now; timelib_tzinfo *tzi; timelib_error_container *err = NULL; int type = TIMELIB_ZONETYPE_ID, new_dst; char *new_abbr; timelib_sll new_offset; if (dateobj->time) { timelib_time_dtor(dateobj->time); } if (format) { dateobj->time = timelib_parse_from_format(format, time_str_len ? time_str : "", time_str_len ? time_str_len : 0, &err, DATE_TIMEZONEDB); } else { dateobj->time = timelib_strtotime(time_str_len ? time_str : "now", time_str_len ? time_str_len : sizeof("now") -1, &err, DATE_TIMEZONEDB); } /* update last errors and warnings */ update_errors_warnings(err TSRMLS_CC); if (ctor && err && err->error_count) { /* spit out the first library error message, at least */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse time string (%s) at position %d (%c): %s", time_str, err->error_messages[0].position, err->error_messages[0].character, err->error_messages[0].message); } if (err && err->error_count) { return 0; } if (timezone_object) { php_timezone_obj *tzobj; tzobj = (php_timezone_obj *) zend_object_store_get_object(timezone_object TSRMLS_CC); switch (tzobj->type) { case TIMELIB_ZONETYPE_ID: tzi = tzobj->tzi.tz; break; case TIMELIB_ZONETYPE_OFFSET: new_offset = tzobj->tzi.utc_offset; break; case TIMELIB_ZONETYPE_ABBR: new_offset = tzobj->tzi.z.utc_offset; new_dst = tzobj->tzi.z.dst; new_abbr = strdup(tzobj->tzi.z.abbr); break; } type = tzobj->type; } else if (dateobj->time->tz_info) { tzi = dateobj->time->tz_info; } else { tzi = get_timezone_info(TSRMLS_C); } now = timelib_time_ctor(); now->zone_type = type; switch (type) { case TIMELIB_ZONETYPE_ID: now->tz_info = tzi; break; case TIMELIB_ZONETYPE_OFFSET: now->z = new_offset; break; case TIMELIB_ZONETYPE_ABBR: now->z = new_offset; now->dst = new_dst; now->tz_abbr = new_abbr; break; } timelib_unixtime2local(now, (timelib_sll) time(NULL)); timelib_fill_holes(dateobj->time, now, TIMELIB_NO_CLONE); timelib_update_ts(dateobj->time, tzi); dateobj->time->have_relative = 0; timelib_time_dtor(now); return 1; } /* {{{ proto DateTime date_create([string time[, DateTimeZone object]]) Returns new DateTime object */ PHP_FUNCTION(date_create) { zval *timezone_object = NULL; char *time_str = NULL; int time_str_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sO!", &time_str, &time_str_len, &timezone_object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } php_date_instantiate(date_ce_date, return_value TSRMLS_CC); if (!php_date_initialize(zend_object_store_get_object(return_value TSRMLS_CC), time_str, time_str_len, NULL, timezone_object, 0 TSRMLS_CC)) { RETURN_FALSE; } } /* }}} */ /* {{{ proto DateTime date_create_from_format(string format, string time[, DateTimeZone object]) Returns new DateTime object formatted according to the specified format */ PHP_FUNCTION(date_create_from_format) { zval *timezone_object = NULL; char *time_str = NULL, *format_str = NULL; int time_str_len = 0, format_str_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|O", &format_str, &format_str_len, &time_str, &time_str_len, &timezone_object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } php_date_instantiate(date_ce_date, return_value TSRMLS_CC); if (!php_date_initialize(zend_object_store_get_object(return_value TSRMLS_CC), time_str, time_str_len, format_str, timezone_object, 0 TSRMLS_CC)) { RETURN_FALSE; } } /* }}} */ /* {{{ proto DateTime::__construct([string time[, DateTimeZone object]]) Creates new DateTime object */ PHP_METHOD(DateTime, __construct) { zval *timezone_object = NULL; char *time_str = NULL; int time_str_len = 0; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sO!", &time_str, &time_str_len, &timezone_object, date_ce_timezone)) { php_date_initialize(zend_object_store_get_object(getThis() TSRMLS_CC), time_str, time_str_len, NULL, timezone_object, 1 TSRMLS_CC); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ static int php_date_initialize_from_hash(zval **return_value, php_date_obj **dateobj, HashTable *myht TSRMLS_DC) { zval **z_date = NULL; zval **z_timezone = NULL; zval **z_timezone_type = NULL; zval *tmp_obj = NULL; timelib_tzinfo *tzi; php_timezone_obj *tzobj; if (zend_hash_find(myht, "date", 5, (void**) &z_date) == SUCCESS) { convert_to_string(*z_date); if (zend_hash_find(myht, "timezone_type", 14, (void**) &z_timezone_type) == SUCCESS) { convert_to_long(*z_timezone_type); if (zend_hash_find(myht, "timezone", 9, (void**) &z_timezone) == SUCCESS) { convert_to_string(*z_timezone); switch (Z_LVAL_PP(z_timezone_type)) { case TIMELIB_ZONETYPE_OFFSET: case TIMELIB_ZONETYPE_ABBR: { char *tmp = emalloc(Z_STRLEN_PP(z_date) + Z_STRLEN_PP(z_timezone) + 2); snprintf(tmp, Z_STRLEN_PP(z_date) + Z_STRLEN_PP(z_timezone) + 2, "%s %s", Z_STRVAL_PP(z_date), Z_STRVAL_PP(z_timezone)); php_date_initialize(*dateobj, tmp, Z_STRLEN_PP(z_date) + Z_STRLEN_PP(z_timezone) + 1, NULL, NULL, 0 TSRMLS_CC); efree(tmp); return 1; } case TIMELIB_ZONETYPE_ID: convert_to_string(*z_timezone); tzi = php_date_parse_tzfile(Z_STRVAL_PP(z_timezone), DATE_TIMEZONEDB TSRMLS_CC); ALLOC_INIT_ZVAL(tmp_obj); tzobj = zend_object_store_get_object(php_date_instantiate(date_ce_timezone, tmp_obj TSRMLS_CC) TSRMLS_CC); tzobj->type = TIMELIB_ZONETYPE_ID; tzobj->tzi.tz = tzi; tzobj->initialized = 1; php_date_initialize(*dateobj, Z_STRVAL_PP(z_date), Z_STRLEN_PP(z_date), NULL, tmp_obj, 0 TSRMLS_CC); zval_ptr_dtor(&tmp_obj); return 1; } } } } return 0; } /* {{{ proto DateTime::__set_state() */ PHP_METHOD(DateTime, __set_state) { php_date_obj *dateobj; zval *array; HashTable *myht; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) { RETURN_FALSE; } myht = HASH_OF(array); php_date_instantiate(date_ce_date, return_value TSRMLS_CC); dateobj = (php_date_obj *) zend_object_store_get_object(return_value TSRMLS_CC); php_date_initialize_from_hash(&return_value, &dateobj, myht TSRMLS_CC); } /* }}} */ /* {{{ proto DateTime::__wakeup() */ PHP_METHOD(DateTime, __wakeup) { zval *object = getThis(); php_date_obj *dateobj; HashTable *myht; dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); myht = Z_OBJPROP_P(object); php_date_initialize_from_hash(&return_value, &dateobj, myht TSRMLS_CC); } /* }}} */ /* Helper function used to add an associative array of warnings and errors to a zval */ static void zval_from_error_container(zval *z, timelib_error_container *error) { int i; zval *element; add_assoc_long(z, "warning_count", error->warning_count); MAKE_STD_ZVAL(element); array_init(element); for (i = 0; i < error->warning_count; i++) { add_index_string(element, error->warning_messages[i].position, error->warning_messages[i].message, 1); } add_assoc_zval(z, "warnings", element); add_assoc_long(z, "error_count", error->error_count); MAKE_STD_ZVAL(element); array_init(element); for (i = 0; i < error->error_count; i++) { add_index_string(element, error->error_messages[i].position, error->error_messages[i].message, 1); } add_assoc_zval(z, "errors", element); } /* {{{ proto array date_get_last_errors() Returns the warnings and errors found while parsing a date/time string. */ PHP_FUNCTION(date_get_last_errors) { if (DATEG(last_errors)) { array_init(return_value); zval_from_error_container(return_value, DATEG(last_errors)); } else { RETURN_FALSE; } } /* }}} */ void php_date_do_return_parsed_time(INTERNAL_FUNCTION_PARAMETERS, timelib_time *parsed_time, struct timelib_error_container *error) { zval *element; array_init(return_value); #define PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(name, elem) \ if (parsed_time->elem == -99999) { \ add_assoc_bool(return_value, #name, 0); \ } else { \ add_assoc_long(return_value, #name, parsed_time->elem); \ } PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(year, y); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(month, m); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(day, d); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(hour, h); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(minute, i); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(second, s); if (parsed_time->f == -99999) { add_assoc_bool(return_value, "fraction", 0); } else { add_assoc_double(return_value, "fraction", parsed_time->f); } zval_from_error_container(return_value, error); timelib_error_container_dtor(error); add_assoc_bool(return_value, "is_localtime", parsed_time->is_localtime); if (parsed_time->is_localtime) { PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(zone_type, zone_type); switch (parsed_time->zone_type) { case TIMELIB_ZONETYPE_OFFSET: PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(zone, z); add_assoc_bool(return_value, "is_dst", parsed_time->dst); break; case TIMELIB_ZONETYPE_ID: if (parsed_time->tz_abbr) { add_assoc_string(return_value, "tz_abbr", parsed_time->tz_abbr, 1); } if (parsed_time->tz_info) { add_assoc_string(return_value, "tz_id", parsed_time->tz_info->name, 1); } break; case TIMELIB_ZONETYPE_ABBR: PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(zone, z); add_assoc_bool(return_value, "is_dst", parsed_time->dst); add_assoc_string(return_value, "tz_abbr", parsed_time->tz_abbr, 1); break; } } if (parsed_time->have_relative) { MAKE_STD_ZVAL(element); array_init(element); add_assoc_long(element, "year", parsed_time->relative.y); add_assoc_long(element, "month", parsed_time->relative.m); add_assoc_long(element, "day", parsed_time->relative.d); add_assoc_long(element, "hour", parsed_time->relative.h); add_assoc_long(element, "minute", parsed_time->relative.i); add_assoc_long(element, "second", parsed_time->relative.s); if (parsed_time->relative.have_weekday_relative) { add_assoc_long(element, "weekday", parsed_time->relative.weekday); } if (parsed_time->relative.have_special_relative && (parsed_time->relative.special.type == TIMELIB_SPECIAL_WEEKDAY)) { add_assoc_long(element, "weekdays", parsed_time->relative.special.amount); } if (parsed_time->relative.first_last_day_of) { add_assoc_bool(element, parsed_time->relative.first_last_day_of == 1 ? "first_day_of_month" : "last_day_of_month", 1); } add_assoc_zval(return_value, "relative", element); } timelib_time_dtor(parsed_time); } /* {{{ proto array date_parse(string date) Returns associative array with detailed info about given date */ PHP_FUNCTION(date_parse) { char *date; int date_len; struct timelib_error_container *error; timelib_time *parsed_time; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &date, &date_len) == FAILURE) { RETURN_FALSE; } parsed_time = timelib_strtotime(date, date_len, &error, DATE_TIMEZONEDB); php_date_do_return_parsed_time(INTERNAL_FUNCTION_PARAM_PASSTHRU, parsed_time, error); } /* }}} */ /* {{{ proto array date_parse_from_format(string format, string date) Returns associative array with detailed info about given date */ PHP_FUNCTION(date_parse_from_format) { char *date, *format; int date_len, format_len; struct timelib_error_container *error; timelib_time *parsed_time; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &format, &format_len, &date, &date_len) == FAILURE) { RETURN_FALSE; } parsed_time = timelib_parse_from_format(format, date, date_len, &error, DATE_TIMEZONEDB); php_date_do_return_parsed_time(INTERNAL_FUNCTION_PARAM_PASSTHRU, parsed_time, error); } /* }}} */ /* {{{ proto string date_format(DateTime object, string format) Returns date formatted according to given format */ PHP_FUNCTION(date_format) { zval *object; php_date_obj *dateobj; char *format; int format_len; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, date_ce_date, &format, &format_len) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); RETURN_STRING(date_format(format, format_len, dateobj->time, dateobj->time->is_localtime), 0); } /* }}} */ /* {{{ proto DateTime date_modify(DateTime object, string modify) Alters the timestamp. */ PHP_FUNCTION(date_modify) { zval *object; php_date_obj *dateobj; char *modify; int modify_len; timelib_time *tmp_time; timelib_error_container *err = NULL; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, date_ce_date, &modify, &modify_len) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); tmp_time = timelib_strtotime(modify, modify_len, &err, DATE_TIMEZONEDB); /* update last errors and warnings */ update_errors_warnings(err TSRMLS_CC); if (err && err->error_count) { /* spit out the first library error message, at least */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse time string (%s) at position %d (%c): %s", modify, err->error_messages[0].position, err->error_messages[0].character, err->error_messages[0].message); timelib_time_dtor(tmp_time); RETURN_FALSE; } memcpy(&dateobj->time->relative, &tmp_time->relative, sizeof(struct timelib_rel_time)); dateobj->time->have_relative = tmp_time->have_relative; dateobj->time->sse_uptodate = 0; if (tmp_time->y != -99999) { dateobj->time->y = tmp_time->y; } if (tmp_time->m != -99999) { dateobj->time->m = tmp_time->m; } if (tmp_time->d != -99999) { dateobj->time->d = tmp_time->d; } if (tmp_time->h != -99999) { dateobj->time->h = tmp_time->h; if (tmp_time->i != -99999) { dateobj->time->i = tmp_time->i; if (tmp_time->s != -99999) { dateobj->time->s = tmp_time->s; } else { dateobj->time->s = 0; } } else { dateobj->time->i = 0; dateobj->time->s = 0; } } timelib_time_dtor(tmp_time); timelib_update_ts(dateobj->time, NULL); timelib_update_from_sse(dateobj->time); dateobj->time->have_relative = 0; RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_add(DateTime object, DateInterval interval) Adds an interval to the current date in object. */ PHP_FUNCTION(date_add) { zval *object, *interval; php_date_obj *dateobj; php_interval_obj *intobj; int bias = 1; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &object, date_ce_date, &interval, date_ce_interval) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); intobj = (php_interval_obj *) zend_object_store_get_object(interval TSRMLS_CC); DATE_CHECK_INITIALIZED(intobj->initialized, DateInterval); if (intobj->diff->have_weekday_relative || intobj->diff->have_special_relative) { memcpy(&dateobj->time->relative, intobj->diff, sizeof(struct timelib_rel_time)); } else { if (intobj->diff->invert) { bias = -1; } memset(&dateobj->time->relative, 0, sizeof(struct timelib_rel_time)); dateobj->time->relative.y = intobj->diff->y * bias; dateobj->time->relative.m = intobj->diff->m * bias; dateobj->time->relative.d = intobj->diff->d * bias; dateobj->time->relative.h = intobj->diff->h * bias; dateobj->time->relative.i = intobj->diff->i * bias; dateobj->time->relative.s = intobj->diff->s * bias; } dateobj->time->have_relative = 1; dateobj->time->sse_uptodate = 0; timelib_update_ts(dateobj->time, NULL); timelib_update_from_sse(dateobj->time); dateobj->time->have_relative = 0; RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_sub(DateTime object, DateInterval interval) Subtracts an interval to the current date in object. */ PHP_FUNCTION(date_sub) { zval *object, *interval; php_date_obj *dateobj; php_interval_obj *intobj; int bias = 1; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &object, date_ce_date, &interval, date_ce_interval) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); intobj = (php_interval_obj *) zend_object_store_get_object(interval TSRMLS_CC); DATE_CHECK_INITIALIZED(intobj->initialized, DateInterval); if (intobj->diff->have_special_relative) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Only non-special relative time specifications are supported for subtraction"); return; } if (intobj->diff->invert) { bias = -1; } memset(&dateobj->time->relative, 0, sizeof(struct timelib_rel_time)); dateobj->time->relative.y = 0 - (intobj->diff->y * bias); dateobj->time->relative.m = 0 - (intobj->diff->m * bias); dateobj->time->relative.d = 0 - (intobj->diff->d * bias); dateobj->time->relative.h = 0 - (intobj->diff->h * bias); dateobj->time->relative.i = 0 - (intobj->diff->i * bias); dateobj->time->relative.s = 0 - (intobj->diff->s * bias); dateobj->time->have_relative = 1; dateobj->time->sse_uptodate = 0; timelib_update_ts(dateobj->time, NULL); timelib_update_from_sse(dateobj->time); dateobj->time->have_relative = 0; RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTimeZone date_timezone_get(DateTime object) Return new DateTimeZone object relative to give DateTime */ PHP_FUNCTION(date_timezone_get) { zval *object; php_date_obj *dateobj; php_timezone_obj *tzobj; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_date) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); if (dateobj->time->is_localtime/* && dateobj->time->tz_info*/) { php_date_instantiate(date_ce_timezone, return_value TSRMLS_CC); tzobj = (php_timezone_obj *) zend_object_store_get_object(return_value TSRMLS_CC); tzobj->initialized = 1; tzobj->type = dateobj->time->zone_type; switch (dateobj->time->zone_type) { case TIMELIB_ZONETYPE_ID: tzobj->tzi.tz = dateobj->time->tz_info; break; case TIMELIB_ZONETYPE_OFFSET: tzobj->tzi.utc_offset = dateobj->time->z; break; case TIMELIB_ZONETYPE_ABBR: tzobj->tzi.z.utc_offset = dateobj->time->z; tzobj->tzi.z.dst = dateobj->time->dst; tzobj->tzi.z.abbr = strdup(dateobj->time->tz_abbr); break; } } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto DateTime date_timezone_set(DateTime object, DateTimeZone object) Sets the timezone for the DateTime object. */ PHP_FUNCTION(date_timezone_set) { zval *object; zval *timezone_object; php_date_obj *dateobj; php_timezone_obj *tzobj; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &object, date_ce_date, &timezone_object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); tzobj = (php_timezone_obj *) zend_object_store_get_object(timezone_object TSRMLS_CC); if (tzobj->type != TIMELIB_ZONETYPE_ID) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can only do this for zones with ID for now"); return; } timelib_set_timezone(dateobj->time, tzobj->tzi.tz); timelib_unixtime2local(dateobj->time, dateobj->time->sse); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto long date_offset_get(DateTime object) Returns the DST offset. */ PHP_FUNCTION(date_offset_get) { zval *object; php_date_obj *dateobj; timelib_time_offset *offset; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_date) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); if (dateobj->time->is_localtime/* && dateobj->time->tz_info*/) { switch (dateobj->time->zone_type) { case TIMELIB_ZONETYPE_ID: offset = timelib_get_time_zone_info(dateobj->time->sse, dateobj->time->tz_info); RETVAL_LONG(offset->offset); timelib_time_offset_dtor(offset); break; case TIMELIB_ZONETYPE_OFFSET: RETVAL_LONG(dateobj->time->z * -60); break; case TIMELIB_ZONETYPE_ABBR: RETVAL_LONG((dateobj->time->z - (60 * dateobj->time->dst)) * -60); break; } return; } else { RETURN_LONG(0); } } /* }}} */ /* {{{ proto DateTime date_time_set(DateTime object, long hour, long minute[, long second]) Sets the time. */ PHP_FUNCTION(date_time_set) { zval *object; php_date_obj *dateobj; long h, i, s = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oll|l", &object, date_ce_date, &h, &i, &s) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); dateobj->time->h = h; dateobj->time->i = i; dateobj->time->s = s; timelib_update_ts(dateobj->time, NULL); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_date_set(DateTime object, long year, long month, long day) Sets the date. */ PHP_FUNCTION(date_date_set) { zval *object; php_date_obj *dateobj; long y, m, d; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Olll", &object, date_ce_date, &y, &m, &d) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); dateobj->time->y = y; dateobj->time->m = m; dateobj->time->d = d; timelib_update_ts(dateobj->time, NULL); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_isodate_set(DateTime object, long year, long week[, long day]) Sets the ISO date. */ PHP_FUNCTION(date_isodate_set) { zval *object; php_date_obj *dateobj; long y, w, d = 1; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oll|l", &object, date_ce_date, &y, &w, &d) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); dateobj->time->y = y; dateobj->time->m = 1; dateobj->time->d = 1; memset(&dateobj->time->relative, 0, sizeof(dateobj->time->relative)); dateobj->time->relative.d = timelib_daynr_from_weeknr(y, w, d); dateobj->time->have_relative = 1; timelib_update_ts(dateobj->time, NULL); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_timestamp_set(DateTime object, long unixTimestamp) Sets the date and time based on an Unix timestamp. */ PHP_FUNCTION(date_timestamp_set) { zval *object; php_date_obj *dateobj; long timestamp; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Ol", &object, date_ce_date, &timestamp) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); timelib_unixtime2local(dateobj->time, (timelib_sll)timestamp); timelib_update_ts(dateobj->time, NULL); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto long date_timestamp_get(DateTime object) Gets the Unix timestamp. */ PHP_FUNCTION(date_timestamp_get) { zval *object; php_date_obj *dateobj; long timestamp; int error; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_date) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); timelib_update_ts(dateobj->time, NULL); timestamp = timelib_date_to_int(dateobj->time, &error); if (error) { RETURN_FALSE; } else { RETVAL_LONG(timestamp); } } /* }}} */ /* {{{ proto DateInterval date_diff(DateTime object [, bool absolute]) Returns the difference between two DateTime objects. */ PHP_FUNCTION(date_diff) { zval *object1, *object2; php_date_obj *dateobj1, *dateobj2; php_interval_obj *interval; long absolute = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO|l", &object1, date_ce_date, &object2, date_ce_date, &absolute) == FAILURE) { RETURN_FALSE; } dateobj1 = (php_date_obj *) zend_object_store_get_object(object1 TSRMLS_CC); dateobj2 = (php_date_obj *) zend_object_store_get_object(object2 TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj1->time, DateTime); DATE_CHECK_INITIALIZED(dateobj2->time, DateTime); timelib_update_ts(dateobj1->time, NULL); timelib_update_ts(dateobj2->time, NULL); php_date_instantiate(date_ce_interval, return_value TSRMLS_CC); interval = zend_object_store_get_object(return_value TSRMLS_CC); interval->diff = timelib_diff(dateobj1->time, dateobj2->time); if (absolute) { interval->diff->invert = 0; } interval->initialized = 1; } /* }}} */ static int timezone_initialize(timelib_tzinfo **tzi, /*const*/ char *tz TSRMLS_DC) { char *tzid; *tzi = NULL; if ((tzid = timelib_timezone_id_from_abbr(tz, -1, 0))) { *tzi = php_date_parse_tzfile(tzid, DATE_TIMEZONEDB TSRMLS_CC); } else { *tzi = php_date_parse_tzfile(tz, DATE_TIMEZONEDB TSRMLS_CC); } if (*tzi) { return SUCCESS; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown or bad timezone (%s)", tz); return FAILURE; } } /* {{{ proto DateTimeZone timezone_open(string timezone) Returns new DateTimeZone object */ PHP_FUNCTION(timezone_open) { char *tz; int tz_len; timelib_tzinfo *tzi = NULL; php_timezone_obj *tzobj; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &tz, &tz_len) == FAILURE) { RETURN_FALSE; } if (SUCCESS != timezone_initialize(&tzi, tz TSRMLS_CC)) { RETURN_FALSE; } tzobj = zend_object_store_get_object(php_date_instantiate(date_ce_timezone, return_value TSRMLS_CC) TSRMLS_CC); tzobj->type = TIMELIB_ZONETYPE_ID; tzobj->tzi.tz = tzi; tzobj->initialized = 1; } /* }}} */ /* {{{ proto DateTimeZone::__construct(string timezone) Creates new DateTimeZone object. */ PHP_METHOD(DateTimeZone, __construct) { char *tz; int tz_len; timelib_tzinfo *tzi = NULL; php_timezone_obj *tzobj; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &tz, &tz_len)) { if (SUCCESS == timezone_initialize(&tzi, tz TSRMLS_CC)) { tzobj = zend_object_store_get_object(getThis() TSRMLS_CC); tzobj->type = TIMELIB_ZONETYPE_ID; tzobj->tzi.tz = tzi; tzobj->initialized = 1; } else { ZVAL_NULL(getThis()); } } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto string timezone_name_get(DateTimeZone object) Returns the name of the timezone. */ PHP_FUNCTION(timezone_name_get) { zval *object; php_timezone_obj *tzobj; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } tzobj = (php_timezone_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(tzobj->initialized, DateTimeZone); switch (tzobj->type) { case TIMELIB_ZONETYPE_ID: RETURN_STRING(tzobj->tzi.tz->name, 1); break; case TIMELIB_ZONETYPE_OFFSET: { char *tmpstr = emalloc(sizeof("UTC+05:00")); timelib_sll utc_offset = tzobj->tzi.utc_offset; snprintf(tmpstr, sizeof("+05:00"), "%c%02d:%02d", utc_offset > 0 ? '-' : '+', abs(utc_offset / 60), abs((utc_offset % 60))); RETURN_STRING(tmpstr, 0); } break; case TIMELIB_ZONETYPE_ABBR: RETURN_STRING(tzobj->tzi.z.abbr, 1); break; } } /* }}} */ /* {{{ proto string timezone_name_from_abbr(string abbr[, long gmtOffset[, long isdst]]) Returns the timezone name from abbrevation */ PHP_FUNCTION(timezone_name_from_abbr) { char *abbr; char *tzid; int abbr_len; long gmtoffset = -1; long isdst = -1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ll", &abbr, &abbr_len, &gmtoffset, &isdst) == FAILURE) { RETURN_FALSE; } tzid = timelib_timezone_id_from_abbr(abbr, gmtoffset, isdst); if (tzid) { RETURN_STRING(tzid, 1); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto long timezone_offset_get(DateTimeZone object, DateTime object) Returns the timezone offset. */ PHP_FUNCTION(timezone_offset_get) { zval *object, *dateobject; php_timezone_obj *tzobj; php_date_obj *dateobj; timelib_time_offset *offset; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &object, date_ce_timezone, &dateobject, date_ce_date) == FAILURE) { RETURN_FALSE; } tzobj = (php_timezone_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(tzobj->initialized, DateTimeZone); dateobj = (php_date_obj *) zend_object_store_get_object(dateobject TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); switch (tzobj->type) { case TIMELIB_ZONETYPE_ID: offset = timelib_get_time_zone_info(dateobj->time->sse, tzobj->tzi.tz); RETVAL_LONG(offset->offset); timelib_time_offset_dtor(offset); break; case TIMELIB_ZONETYPE_OFFSET: RETURN_LONG(tzobj->tzi.utc_offset * -60); break; case TIMELIB_ZONETYPE_ABBR: RETURN_LONG((tzobj->tzi.z.utc_offset - (tzobj->tzi.z.dst*60)) * -60); break; } } /* }}} */ /* {{{ proto array timezone_transitions_get(DateTimeZone object [, long timestamp_begin [, long timestamp_end ]]) Returns numerically indexed array containing associative array for all transitions in the specified range for the timezone. */ PHP_FUNCTION(timezone_transitions_get) { zval *object, *element; php_timezone_obj *tzobj; unsigned int i, begin = 0, found; long timestamp_begin = LONG_MIN, timestamp_end = LONG_MAX; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|ll", &object, date_ce_timezone, &timestamp_begin, &timestamp_end) == FAILURE) { RETURN_FALSE; } tzobj = (php_timezone_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(tzobj->initialized, DateTimeZone); if (tzobj->type != TIMELIB_ZONETYPE_ID) { RETURN_FALSE; } #define add_nominal() \ MAKE_STD_ZVAL(element); \ array_init(element); \ add_assoc_long(element, "ts", timestamp_begin); \ add_assoc_string(element, "time", php_format_date(DATE_FORMAT_ISO8601, 13, timestamp_begin, 0 TSRMLS_CC), 0); \ add_assoc_long(element, "offset", tzobj->tzi.tz->type[0].offset); \ add_assoc_bool(element, "isdst", tzobj->tzi.tz->type[0].isdst); \ add_assoc_string(element, "abbr", &tzobj->tzi.tz->timezone_abbr[tzobj->tzi.tz->type[0].abbr_idx], 1); \ add_next_index_zval(return_value, element); #define add(i,ts) \ MAKE_STD_ZVAL(element); \ array_init(element); \ add_assoc_long(element, "ts", ts); \ add_assoc_string(element, "time", php_format_date(DATE_FORMAT_ISO8601, 13, ts, 0 TSRMLS_CC), 0); \ add_assoc_long(element, "offset", tzobj->tzi.tz->type[tzobj->tzi.tz->trans_idx[i]].offset); \ add_assoc_bool(element, "isdst", tzobj->tzi.tz->type[tzobj->tzi.tz->trans_idx[i]].isdst); \ add_assoc_string(element, "abbr", &tzobj->tzi.tz->timezone_abbr[tzobj->tzi.tz->type[tzobj->tzi.tz->trans_idx[i]].abbr_idx], 1); \ add_next_index_zval(return_value, element); #define add_last() add(tzobj->tzi.tz->timecnt - 1, timestamp_begin) array_init(return_value); if (timestamp_begin == LONG_MIN) { add_nominal(); begin = 0; found = 1; } else { begin = 0; found = 0; if (tzobj->tzi.tz->timecnt > 0) { do { if (tzobj->tzi.tz->trans[begin] > timestamp_begin) { if (begin > 0) { add(begin - 1, timestamp_begin); } else { add_nominal(); } found = 1; break; } begin++; } while (begin < tzobj->tzi.tz->timecnt); } } if (!found) { if (tzobj->tzi.tz->timecnt > 0) { add_last(); } else { add_nominal(); } } else { for (i = begin; i < tzobj->tzi.tz->timecnt; ++i) { if (tzobj->tzi.tz->trans[i] < timestamp_end) { add(i, tzobj->tzi.tz->trans[i]); } } } } /* }}} */ /* {{{ proto array timezone_location_get() Returns location information for a timezone, including country code, latitude/longitude and comments */ PHP_FUNCTION(timezone_location_get) { zval *object; php_timezone_obj *tzobj; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } tzobj = (php_timezone_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(tzobj->initialized, DateTimeZone); if (tzobj->type != TIMELIB_ZONETYPE_ID) { RETURN_FALSE; } array_init(return_value); add_assoc_string(return_value, "country_code", tzobj->tzi.tz->location.country_code, 1); add_assoc_double(return_value, "latitude", tzobj->tzi.tz->location.latitude); add_assoc_double(return_value, "longitude", tzobj->tzi.tz->location.longitude); add_assoc_string(return_value, "comments", tzobj->tzi.tz->location.comments, 1); } /* }}} */ static int date_interval_initialize(timelib_rel_time **rt, /*const*/ char *format, int format_length TSRMLS_DC) { timelib_time *b = NULL, *e = NULL; timelib_rel_time *p = NULL; int r = 0; int retval = 0; struct timelib_error_container *errors; timelib_strtointerval(format, format_length, &b, &e, &p, &r, &errors); if (errors->error_count > 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown or bad format (%s)", format); retval = FAILURE; } else { if(p) { *rt = p; retval = SUCCESS; } else { if(b && e) { timelib_update_ts(b, NULL); timelib_update_ts(e, NULL); *rt = timelib_diff(b, e); retval = SUCCESS; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse interval (%s)", format); retval = FAILURE; } } } timelib_error_container_dtor(errors); return retval; } /* {{{ date_interval_read_property */ zval *date_interval_read_property(zval *object, zval *member, int type, const zend_literal *key TSRMLS_DC) { php_interval_obj *obj; zval *retval; zval tmp_member; timelib_sll value = -1; if (member->type != IS_STRING) { tmp_member = *member; zval_copy_ctor(&tmp_member); convert_to_string(&tmp_member); member = &tmp_member; } obj = (php_interval_obj *)zend_objects_get_address(object TSRMLS_CC); #define GET_VALUE_FROM_STRUCT(n,m) \ if (strcmp(Z_STRVAL_P(member), m) == 0) { \ value = obj->diff->n; \ break; \ } do { GET_VALUE_FROM_STRUCT(y, "y"); GET_VALUE_FROM_STRUCT(m, "m"); GET_VALUE_FROM_STRUCT(d, "d"); GET_VALUE_FROM_STRUCT(h, "h"); GET_VALUE_FROM_STRUCT(i, "i"); GET_VALUE_FROM_STRUCT(s, "s"); GET_VALUE_FROM_STRUCT(invert, "invert"); GET_VALUE_FROM_STRUCT(days, "days"); /* didn't find any */ retval = (zend_get_std_object_handlers())->read_property(object, member, type, key TSRMLS_CC); if (member == &tmp_member) { zval_dtor(member); } return retval; } while(0); ALLOC_INIT_ZVAL(retval); Z_SET_REFCOUNT_P(retval, 0); ZVAL_LONG(retval, value); if (member == &tmp_member) { zval_dtor(member); } return retval; } /* }}} */ /* {{{ date_interval_write_property */ void date_interval_write_property(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC) { php_interval_obj *obj; zval tmp_member, tmp_value; if (member->type != IS_STRING) { tmp_member = *member; zval_copy_ctor(&tmp_member); convert_to_string(&tmp_member); member = &tmp_member; } obj = (php_interval_obj *)zend_objects_get_address(object TSRMLS_CC); #define SET_VALUE_FROM_STRUCT(n,m) \ if (strcmp(Z_STRVAL_P(member), m) == 0) { \ if (value->type != IS_LONG) { \ tmp_value = *value; \ zval_copy_ctor(&tmp_value); \ convert_to_long(&tmp_value); \ value = &tmp_value; \ } \ obj->diff->n = Z_LVAL_P(value); \ if (value == &tmp_value) { \ zval_dtor(value); \ } \ break; \ } do { SET_VALUE_FROM_STRUCT(y, "y"); SET_VALUE_FROM_STRUCT(m, "m"); SET_VALUE_FROM_STRUCT(d, "d"); SET_VALUE_FROM_STRUCT(h, "h"); SET_VALUE_FROM_STRUCT(i, "i"); SET_VALUE_FROM_STRUCT(s, "s"); SET_VALUE_FROM_STRUCT(invert, "invert"); /* didn't find any */ (zend_get_std_object_handlers())->write_property(object, member, value, key TSRMLS_CC); } while(0); if (member == &tmp_member) { zval_dtor(member); } } /* }}} */ /* {{{ proto DateInterval::__construct([string interval_spec]) Creates new DateInterval object. */ PHP_METHOD(DateInterval, __construct) { char *interval_string = NULL; int interval_string_length; php_interval_obj *diobj; timelib_rel_time *reltime; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &interval_string, &interval_string_length) == SUCCESS) { if (date_interval_initialize(&reltime, interval_string, interval_string_length TSRMLS_CC) == SUCCESS) { diobj = zend_object_store_get_object(getThis() TSRMLS_CC); diobj->diff = reltime; diobj->initialized = 1; } else { ZVAL_NULL(getThis()); } } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto DateInterval date_interval_create_from_date_string(string time) Uses the normal date parsers and sets up a DateInterval from the relative parts of the parsed string */ PHP_FUNCTION(date_interval_create_from_date_string) { char *time_str = NULL; int time_str_len = 0; timelib_time *time; timelib_error_container *err = NULL; php_interval_obj *diobj; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &time_str, &time_str_len) == FAILURE) { RETURN_FALSE; } php_date_instantiate(date_ce_interval, return_value TSRMLS_CC); time = timelib_strtotime(time_str, time_str_len, &err, DATE_TIMEZONEDB); diobj = (php_interval_obj *) zend_object_store_get_object(return_value TSRMLS_CC); diobj->diff = timelib_rel_time_clone(&time->relative); diobj->initialized = 1; timelib_time_dtor(time); timelib_error_container_dtor(err); } /* }}} */ /* {{{ date_interval_format - */ static char *date_interval_format(char *format, int format_len, timelib_rel_time *t) { smart_str string = {0}; int i, length, have_format_spec = 0; char buffer[33]; if (!format_len) { return estrdup(""); } for (i = 0; i < format_len; i++) { if (have_format_spec) { switch (format[i]) { case 'Y': length = slprintf(buffer, 32, "%02d", (int) t->y); break; case 'y': length = slprintf(buffer, 32, "%d", (int) t->y); break; case 'M': length = slprintf(buffer, 32, "%02d", (int) t->m); break; case 'm': length = slprintf(buffer, 32, "%d", (int) t->m); break; case 'D': length = slprintf(buffer, 32, "%02d", (int) t->d); break; case 'd': length = slprintf(buffer, 32, "%d", (int) t->d); break; case 'H': length = slprintf(buffer, 32, "%02d", (int) t->h); break; case 'h': length = slprintf(buffer, 32, "%d", (int) t->h); break; case 'I': length = slprintf(buffer, 32, "%02d", (int) t->i); break; case 'i': length = slprintf(buffer, 32, "%d", (int) t->i); break; case 'S': length = slprintf(buffer, 32, "%02d", (int) t->s); break; case 's': length = slprintf(buffer, 32, "%d", (int) t->s); break; case 'a': { if ((int) t->days != -99999) { length = slprintf(buffer, 32, "%d", (int) t->days); } else { length = slprintf(buffer, 32, "(unknown)"); } } break; case 'r': length = slprintf(buffer, 32, "%s", t->invert ? "-" : ""); break; case 'R': length = slprintf(buffer, 32, "%c", t->invert ? '-' : '+'); break; case '%': length = slprintf(buffer, 32, "%%"); break; default: buffer[0] = '%'; buffer[1] = format[i]; buffer[2] = '\0'; length = 2; break; } smart_str_appendl(&string, buffer, length); have_format_spec = 0; } else { if (format[i] == '%') { have_format_spec = 1; } else { smart_str_appendc(&string, format[i]); } } } smart_str_0(&string); return string.c; } /* }}} */ /* {{{ proto string date_interval_format(DateInterval object, string format) Formats the interval. */ PHP_FUNCTION(date_interval_format) { zval *object; php_interval_obj *diobj; char *format; int format_len; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, date_ce_interval, &format, &format_len) == FAILURE) { RETURN_FALSE; } diobj = (php_interval_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(diobj->initialized, DateInterval); RETURN_STRING(date_interval_format(format, format_len, diobj->diff), 0); } /* }}} */ static int date_period_initialize(timelib_time **st, timelib_time **et, timelib_rel_time **d, long *recurrences, /*const*/ char *format, int format_length TSRMLS_DC) { timelib_time *b = NULL, *e = NULL; timelib_rel_time *p = NULL; int r = 0; int retval = 0; struct timelib_error_container *errors; timelib_strtointerval(format, format_length, &b, &e, &p, &r, &errors); if (errors->error_count > 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown or bad format (%s)", format); retval = FAILURE; } else { *st = b; *et = e; *d = p; *recurrences = r; retval = SUCCESS; } timelib_error_container_dtor(errors); return retval; } /* {{{ proto DatePeriod::__construct(DateTime $start, DateInterval $interval, int recurrences|DateTime $end) Creates new DatePeriod object. */ PHP_METHOD(DatePeriod, __construct) { php_period_obj *dpobj; php_date_obj *dateobj; php_interval_obj *intobj; zval *start, *end = NULL, *interval; long recurrences = 0, options = 0; char *isostr = NULL; int isostr_len = 0; timelib_time *clone; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "OOl|l", &start, date_ce_date, &interval, date_ce_interval, &recurrences, &options) == FAILURE) { if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "OOO|l", &start, date_ce_date, &interval, date_ce_interval, &end, date_ce_date, &options) == FAILURE) { if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &isostr, &isostr_len, &options) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "This constructor accepts either (DateTime, DateInterval, int) OR (DateTime, DateInterval, DateTime) OR (string) as arguments."); zend_restore_error_handling(&error_handling TSRMLS_CC); return; } } } dpobj = zend_object_store_get_object(getThis() TSRMLS_CC); dpobj->current = NULL; if (isostr_len) { date_period_initialize(&(dpobj->start), &(dpobj->end), &(dpobj->interval), &recurrences, isostr, isostr_len TSRMLS_CC); if (dpobj->start == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The ISO interval '%s' did not contain a start date.", isostr); } if (dpobj->interval == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The ISO interval '%s' did not contain an interval.", isostr); } if (dpobj->end == NULL && recurrences == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The ISO interval '%s' did not contain an end date or a recurrence count.", isostr); } if (dpobj->start) { timelib_update_ts(dpobj->start, NULL); } if (dpobj->end) { timelib_update_ts(dpobj->end, NULL); } } else { /* init */ intobj = (php_interval_obj *) zend_object_store_get_object(interval TSRMLS_CC); /* start date */ dateobj = (php_date_obj *) zend_object_store_get_object(start TSRMLS_CC); clone = timelib_time_ctor(); memcpy(clone, dateobj->time, sizeof(timelib_time)); if (dateobj->time->tz_abbr) { clone->tz_abbr = strdup(dateobj->time->tz_abbr); } if (dateobj->time->tz_info) { clone->tz_info = dateobj->time->tz_info; } dpobj->start = clone; /* interval */ dpobj->interval = timelib_rel_time_clone(intobj->diff); /* end date */ if (end) { dateobj = (php_date_obj *) zend_object_store_get_object(end TSRMLS_CC); clone = timelib_time_clone(dateobj->time); dpobj->end = clone; } } /* options */ dpobj->include_start_date = !(options & PHP_DATE_PERIOD_EXCLUDE_START_DATE); /* recurrrences */ dpobj->recurrences = recurrences + dpobj->include_start_date; dpobj->initialized = 1; zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ static int check_id_allowed(char *id, long what) { if (what & PHP_DATE_TIMEZONE_GROUP_AFRICA && strncasecmp(id, "Africa/", 7) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_AMERICA && strncasecmp(id, "America/", 8) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_ANTARCTICA && strncasecmp(id, "Antarctica/", 11) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_ARCTIC && strncasecmp(id, "Arctic/", 7) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_ASIA && strncasecmp(id, "Asia/", 5) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_ATLANTIC && strncasecmp(id, "Atlantic/", 9) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_AUSTRALIA && strncasecmp(id, "Australia/", 10) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_EUROPE && strncasecmp(id, "Europe/", 7) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_INDIAN && strncasecmp(id, "Indian/", 7) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_PACIFIC && strncasecmp(id, "Pacific/", 8) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_UTC && strncasecmp(id, "UTC", 3) == 0) return 1; return 0; } /* {{{ proto array timezone_identifiers_list([long what[, string country]]) Returns numerically index array with all timezone identifiers. */ PHP_FUNCTION(timezone_identifiers_list) { const timelib_tzdb *tzdb; const timelib_tzdb_index_entry *table; int i, item_count; long what = PHP_DATE_TIMEZONE_GROUP_ALL; char *option = NULL; int option_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|ls", &what, &option, &option_len) == FAILURE) { RETURN_FALSE; } /* Extra validation */ if (what == PHP_DATE_TIMEZONE_PER_COUNTRY && option_len != 2) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "A two-letter ISO 3166-1 compatible country code is expected"); RETURN_FALSE; } tzdb = DATE_TIMEZONEDB; item_count = tzdb->index_size; table = tzdb->index; array_init(return_value); for (i = 0; i < item_count; ++i) { if (what == PHP_DATE_TIMEZONE_PER_COUNTRY) { if (tzdb->data[table[i].pos + 5] == option[0] && tzdb->data[table[i].pos + 6] == option[1]) { add_next_index_string(return_value, table[i].id, 1); } } else if (what == PHP_DATE_TIMEZONE_GROUP_ALL_W_BC || (check_id_allowed(table[i].id, what) && (tzdb->data[table[i].pos + 4] == '\1'))) { add_next_index_string(return_value, table[i].id, 1); } }; } /* }}} */ /* {{{ proto array timezone_version_get() Returns the Olson database version number. */ PHP_FUNCTION(timezone_version_get) { const timelib_tzdb *tzdb; tzdb = DATE_TIMEZONEDB; RETURN_STRING(tzdb->version, 1); } /* }}} */ /* {{{ proto array timezone_abbreviations_list() Returns associative array containing dst, offset and the timezone name */ PHP_FUNCTION(timezone_abbreviations_list) { const timelib_tz_lookup_table *table, *entry; zval *element, **abbr_array_pp, *abbr_array; table = timelib_timezone_abbreviations_list(); array_init(return_value); entry = table; do { MAKE_STD_ZVAL(element); array_init(element); add_assoc_bool(element, "dst", entry->type); add_assoc_long(element, "offset", entry->gmtoffset); if (entry->full_tz_name) { add_assoc_string(element, "timezone_id", entry->full_tz_name, 1); } else { add_assoc_null(element, "timezone_id"); } if (zend_hash_find(HASH_OF(return_value), entry->name, strlen(entry->name) + 1, (void **) &abbr_array_pp) == FAILURE) { MAKE_STD_ZVAL(abbr_array); array_init(abbr_array); add_assoc_zval(return_value, entry->name, abbr_array); } else { abbr_array = *abbr_array_pp; } add_next_index_zval(abbr_array, element); entry++; } while (entry->name); } /* }}} */ /* {{{ proto bool date_default_timezone_set(string timezone_identifier) Sets the default timezone used by all date/time functions in a script */ PHP_FUNCTION(date_default_timezone_set) { char *zone; int zone_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &zone, &zone_len) == FAILURE) { RETURN_FALSE; } if (!timelib_timezone_id_is_valid(zone, DATE_TIMEZONEDB)) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Timezone ID '%s' is invalid", zone); RETURN_FALSE; } if (DATEG(timezone)) { efree(DATEG(timezone)); DATEG(timezone) = NULL; } DATEG(timezone) = estrndup(zone, zone_len); RETURN_TRUE; } /* }}} */ /* {{{ proto string date_default_timezone_get() Gets the default timezone used by all date/time functions in a script */ PHP_FUNCTION(date_default_timezone_get) { timelib_tzinfo *default_tz; default_tz = get_timezone_info(TSRMLS_C); RETVAL_STRING(default_tz->name, 1); } /* }}} */ /* {{{ php_do_date_sunrise_sunset * Common for date_sunrise() and date_sunset() functions */ static void php_do_date_sunrise_sunset(INTERNAL_FUNCTION_PARAMETERS, int calc_sunset) { double latitude = 0.0, longitude = 0.0, zenith = 0.0, gmt_offset = 0, altitude; double h_rise, h_set, N; timelib_sll rise, set, transit; long time, retformat = 0; int rs; timelib_time *t; timelib_tzinfo *tzi; char *retstr; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|ldddd", &time, &retformat, &latitude, &longitude, &zenith, &gmt_offset) == FAILURE) { RETURN_FALSE; } switch (ZEND_NUM_ARGS()) { case 1: retformat = SUNFUNCS_RET_STRING; case 2: latitude = INI_FLT("date.default_latitude"); case 3: longitude = INI_FLT("date.default_longitude"); case 4: if (calc_sunset) { zenith = INI_FLT("date.sunset_zenith"); } else { zenith = INI_FLT("date.sunrise_zenith"); } case 5: case 6: break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "invalid format"); RETURN_FALSE; break; } if (retformat != SUNFUNCS_RET_TIMESTAMP && retformat != SUNFUNCS_RET_STRING && retformat != SUNFUNCS_RET_DOUBLE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Wrong return format given, pick one of SUNFUNCS_RET_TIMESTAMP, SUNFUNCS_RET_STRING or SUNFUNCS_RET_DOUBLE"); RETURN_FALSE; } altitude = 90 - zenith; /* Initialize time struct */ t = timelib_time_ctor(); tzi = get_timezone_info(TSRMLS_C); t->tz_info = tzi; t->zone_type = TIMELIB_ZONETYPE_ID; if (ZEND_NUM_ARGS() <= 5) { gmt_offset = timelib_get_current_offset(t) / 3600; } timelib_unixtime2local(t, time); rs = timelib_astro_rise_set_altitude(t, longitude, latitude, altitude, 1, &h_rise, &h_set, &rise, &set, &transit); timelib_time_dtor(t); if (rs != 0) { RETURN_FALSE; } if (retformat == SUNFUNCS_RET_TIMESTAMP) { RETURN_LONG(calc_sunset ? set : rise); } N = (calc_sunset ? h_set : h_rise) + gmt_offset; if (N > 24 || N < 0) { N -= floor(N / 24) * 24; } switch (retformat) { case SUNFUNCS_RET_STRING: spprintf(&retstr, 0, "%02d:%02d", (int) N, (int) (60 * (N - (int) N))); RETURN_STRINGL(retstr, 5, 0); break; case SUNFUNCS_RET_DOUBLE: RETURN_DOUBLE(N); break; } } /* }}} */ /* {{{ proto mixed date_sunrise(mixed time [, int format [, float latitude [, float longitude [, float zenith [, float gmt_offset]]]]]) Returns time of sunrise for a given day and location */ PHP_FUNCTION(date_sunrise) { php_do_date_sunrise_sunset(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto mixed date_sunset(mixed time [, int format [, float latitude [, float longitude [, float zenith [, float gmt_offset]]]]]) Returns time of sunset for a given day and location */ PHP_FUNCTION(date_sunset) { php_do_date_sunrise_sunset(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto array date_sun_info(long time, float latitude, float longitude) Returns an array with information about sun set/rise and twilight begin/end */ PHP_FUNCTION(date_sun_info) { long time; double latitude, longitude; timelib_time *t, *t2; timelib_tzinfo *tzi; int rs; timelib_sll rise, set, transit; int dummy; double ddummy; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ldd", &time, &latitude, &longitude) == FAILURE) { RETURN_FALSE; } /* Initialize time struct */ t = timelib_time_ctor(); tzi = get_timezone_info(TSRMLS_C); t->tz_info = tzi; t->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(t, time); /* Setup */ t2 = timelib_time_ctor(); array_init(return_value); /* Get sun up/down and transit */ rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -35.0/60, 1, &ddummy, &ddummy, &rise, &set, &transit); switch (rs) { case -1: /* always below */ add_assoc_bool(return_value, "sunrise", 0); add_assoc_bool(return_value, "sunset", 0); break; case 1: /* always above */ add_assoc_bool(return_value, "sunrise", 1); add_assoc_bool(return_value, "sunset", 1); break; default: t2->sse = rise; add_assoc_long(return_value, "sunrise", timelib_date_to_int(t2, &dummy)); t2->sse = set; add_assoc_long(return_value, "sunset", timelib_date_to_int(t2, &dummy)); } t2->sse = transit; add_assoc_long(return_value, "transit", timelib_date_to_int(t2, &dummy)); /* Get civil twilight */ rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -6.0, 0, &ddummy, &ddummy, &rise, &set, &transit); switch (rs) { case -1: /* always below */ add_assoc_bool(return_value, "civil_twilight_begin", 0); add_assoc_bool(return_value, "civil_twilight_end", 0); break; case 1: /* always above */ add_assoc_bool(return_value, "civil_twilight_begin", 1); add_assoc_bool(return_value, "civil_twilight_end", 1); break; default: t2->sse = rise; add_assoc_long(return_value, "civil_twilight_begin", timelib_date_to_int(t2, &dummy)); t2->sse = set; add_assoc_long(return_value, "civil_twilight_end", timelib_date_to_int(t2, &dummy)); } /* Get nautical twilight */ rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -12.0, 0, &ddummy, &ddummy, &rise, &set, &transit); switch (rs) { case -1: /* always below */ add_assoc_bool(return_value, "nautical_twilight_begin", 0); add_assoc_bool(return_value, "nautical_twilight_end", 0); break; case 1: /* always above */ add_assoc_bool(return_value, "nautical_twilight_begin", 1); add_assoc_bool(return_value, "nautical_twilight_end", 1); break; default: t2->sse = rise; add_assoc_long(return_value, "nautical_twilight_begin", timelib_date_to_int(t2, &dummy)); t2->sse = set; add_assoc_long(return_value, "nautical_twilight_end", timelib_date_to_int(t2, &dummy)); } /* Get astronomical twilight */ rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -18.0, 0, &ddummy, &ddummy, &rise, &set, &transit); switch (rs) { case -1: /* always below */ add_assoc_bool(return_value, "astronomical_twilight_begin", 0); add_assoc_bool(return_value, "astronomical_twilight_end", 0); break; case 1: /* always above */ add_assoc_bool(return_value, "astronomical_twilight_begin", 1); add_assoc_bool(return_value, "astronomical_twilight_end", 1); break; default: t2->sse = rise; add_assoc_long(return_value, "astronomical_twilight_begin", timelib_date_to_int(t2, &dummy)); t2->sse = set; add_assoc_long(return_value, "astronomical_twilight_end", timelib_date_to_int(t2, &dummy)); } timelib_time_dtor(t); timelib_time_dtor(t2); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: fdm=marker * vim: noet sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Derick Rethans <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "php.h" #include "php_streams.h" #include "php_main.h" #include "php_globals.h" #include "php_ini.h" #include "ext/standard/info.h" #include "ext/standard/php_versioning.h" #include "ext/standard/php_math.h" #include "php_date.h" #include "zend_interfaces.h" #include "lib/timelib.h" #include <time.h> #ifdef PHP_WIN32 static __inline __int64 php_date_llabs( __int64 i ) { return i >= 0? i: -i; } #elif defined(__GNUC__) && __GNUC__ < 3 static __inline __int64_t php_date_llabs( __int64_t i ) { return i >= 0 ? i : -i; } #else static inline long long php_date_llabs( long long i ) { return i >= 0 ? i : -i; } #endif /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_date, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_gmdate, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_idate, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strtotime, 0, 0, 1) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, now) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mktime, 0, 0, 0) ZEND_ARG_INFO(0, hour) ZEND_ARG_INFO(0, min) ZEND_ARG_INFO(0, sec) ZEND_ARG_INFO(0, mon) ZEND_ARG_INFO(0, day) ZEND_ARG_INFO(0, year) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_gmmktime, 0, 0, 0) ZEND_ARG_INFO(0, hour) ZEND_ARG_INFO(0, min) ZEND_ARG_INFO(0, sec) ZEND_ARG_INFO(0, mon) ZEND_ARG_INFO(0, day) ZEND_ARG_INFO(0, year) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_checkdate, 0) ZEND_ARG_INFO(0, month) ZEND_ARG_INFO(0, day) ZEND_ARG_INFO(0, year) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strftime, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_gmstrftime, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_time, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_localtime, 0, 0, 0) ZEND_ARG_INFO(0, timestamp) ZEND_ARG_INFO(0, associative_array) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_getdate, 0, 0, 0) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_default_timezone_set, 0) ZEND_ARG_INFO(0, timezone_identifier) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_default_timezone_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_sunrise, 0, 0, 1) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, latitude) ZEND_ARG_INFO(0, longitude) ZEND_ARG_INFO(0, zenith) ZEND_ARG_INFO(0, gmt_offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_sunset, 0, 0, 1) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, latitude) ZEND_ARG_INFO(0, longitude) ZEND_ARG_INFO(0, zenith) ZEND_ARG_INFO(0, gmt_offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_sun_info, 0) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, latitude) ZEND_ARG_INFO(0, longitude) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_create, 0, 0, 0) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_create_from_format, 0, 0, 2) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_parse, 0, 0, 1) ZEND_ARG_INFO(0, date) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_parse_from_format, 0, 0, 2) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, date) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_get_last_errors, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_format, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_format, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_modify, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, modify) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_modify, 0, 0, 1) ZEND_ARG_INFO(0, modify) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_add, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, interval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_add, 0, 0, 1) ZEND_ARG_INFO(0, interval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_sub, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, interval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_sub, 0, 0, 1) ZEND_ARG_INFO(0, interval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_timezone_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_method_timezone_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_timezone_set, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, timezone) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_timezone_set, 0, 0, 1) ZEND_ARG_INFO(0, timezone) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_offset_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_method_offset_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_diff, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, object2) ZEND_ARG_INFO(0, absolute) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_diff, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, absolute) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_time_set, 0, 0, 3) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, hour) ZEND_ARG_INFO(0, minute) ZEND_ARG_INFO(0, second) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_time_set, 0, 0, 2) ZEND_ARG_INFO(0, hour) ZEND_ARG_INFO(0, minute) ZEND_ARG_INFO(0, second) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_date_set, 0, 0, 4) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, year) ZEND_ARG_INFO(0, month) ZEND_ARG_INFO(0, day) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_date_set, 0, 0, 3) ZEND_ARG_INFO(0, year) ZEND_ARG_INFO(0, month) ZEND_ARG_INFO(0, day) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_isodate_set, 0, 0, 3) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, year) ZEND_ARG_INFO(0, week) ZEND_ARG_INFO(0, day) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_isodate_set, 0, 0, 2) ZEND_ARG_INFO(0, year) ZEND_ARG_INFO(0, week) ZEND_ARG_INFO(0, day) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_timestamp_set, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, unixtimestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_timestamp_set, 0, 0, 1) ZEND_ARG_INFO(0, unixtimestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_timestamp_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_method_timestamp_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_open, 0, 0, 1) ZEND_ARG_INFO(0, timezone) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_name_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_method_name_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_name_from_abbr, 0, 0, 1) ZEND_ARG_INFO(0, abbr) ZEND_ARG_INFO(0, gmtoffset) ZEND_ARG_INFO(0, isdst) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_offset_get, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, datetime) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_method_offset_get, 0, 0, 1) ZEND_ARG_INFO(0, datetime) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_transitions_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, timestamp_begin) ZEND_ARG_INFO(0, timestamp_end) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_method_transitions_get, 0) ZEND_ARG_INFO(0, timestamp_begin) ZEND_ARG_INFO(0, timestamp_end) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_location_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_method_location_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_identifiers_list, 0, 0, 0) ZEND_ARG_INFO(0, what) ZEND_ARG_INFO(0, country) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_abbreviations_list, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_version_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_interval_create_from_date_string, 0, 0, 1) ZEND_ARG_INFO(0, time) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_interval_format, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_method_interval_format, 0) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_period_construct, 0, 0, 3) ZEND_ARG_INFO(0, start) ZEND_ARG_INFO(0, interval) ZEND_ARG_INFO(0, end) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_interval_construct, 0, 0, 0) ZEND_ARG_INFO(0, interval_spec) ZEND_END_ARG_INFO() /* }}} */ /* {{{ Function table */ const zend_function_entry date_functions[] = { PHP_FE(strtotime, arginfo_strtotime) PHP_FE(date, arginfo_date) PHP_FE(idate, arginfo_idate) PHP_FE(gmdate, arginfo_gmdate) PHP_FE(mktime, arginfo_mktime) PHP_FE(gmmktime, arginfo_gmmktime) PHP_FE(checkdate, arginfo_checkdate) #ifdef HAVE_STRFTIME PHP_FE(strftime, arginfo_strftime) PHP_FE(gmstrftime, arginfo_gmstrftime) #endif PHP_FE(time, arginfo_time) PHP_FE(localtime, arginfo_localtime) PHP_FE(getdate, arginfo_getdate) /* Advanced Interface */ PHP_FE(date_create, arginfo_date_create) PHP_FE(date_create_from_format, arginfo_date_create_from_format) PHP_FE(date_parse, arginfo_date_parse) PHP_FE(date_parse_from_format, arginfo_date_parse_from_format) PHP_FE(date_get_last_errors, arginfo_date_get_last_errors) PHP_FE(date_format, arginfo_date_format) PHP_FE(date_modify, arginfo_date_modify) PHP_FE(date_add, arginfo_date_add) PHP_FE(date_sub, arginfo_date_sub) PHP_FE(date_timezone_get, arginfo_date_timezone_get) PHP_FE(date_timezone_set, arginfo_date_timezone_set) PHP_FE(date_offset_get, arginfo_date_offset_get) PHP_FE(date_diff, arginfo_date_diff) PHP_FE(date_time_set, arginfo_date_time_set) PHP_FE(date_date_set, arginfo_date_date_set) PHP_FE(date_isodate_set, arginfo_date_isodate_set) PHP_FE(date_timestamp_set, arginfo_date_timestamp_set) PHP_FE(date_timestamp_get, arginfo_date_timestamp_get) PHP_FE(timezone_open, arginfo_timezone_open) PHP_FE(timezone_name_get, arginfo_timezone_name_get) PHP_FE(timezone_name_from_abbr, arginfo_timezone_name_from_abbr) PHP_FE(timezone_offset_get, arginfo_timezone_offset_get) PHP_FE(timezone_transitions_get, arginfo_timezone_transitions_get) PHP_FE(timezone_location_get, arginfo_timezone_location_get) PHP_FE(timezone_identifiers_list, arginfo_timezone_identifiers_list) PHP_FE(timezone_abbreviations_list, arginfo_timezone_abbreviations_list) PHP_FE(timezone_version_get, arginfo_timezone_version_get) PHP_FE(date_interval_create_from_date_string, arginfo_date_interval_create_from_date_string) PHP_FE(date_interval_format, arginfo_date_interval_format) /* Options and Configuration */ PHP_FE(date_default_timezone_set, arginfo_date_default_timezone_set) PHP_FE(date_default_timezone_get, arginfo_date_default_timezone_get) /* Astronomical functions */ PHP_FE(date_sunrise, arginfo_date_sunrise) PHP_FE(date_sunset, arginfo_date_sunset) PHP_FE(date_sun_info, arginfo_date_sun_info) {NULL, NULL, NULL} }; const zend_function_entry date_funcs_date[] = { PHP_ME(DateTime, __construct, arginfo_date_create, ZEND_ACC_CTOR|ZEND_ACC_PUBLIC) PHP_ME(DateTime, __wakeup, NULL, ZEND_ACC_PUBLIC) PHP_ME(DateTime, __set_state, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_ME_MAPPING(createFromFormat, date_create_from_format, arginfo_date_create_from_format, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_ME_MAPPING(getLastErrors, date_get_last_errors, arginfo_date_get_last_errors, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_ME_MAPPING(format, date_format, arginfo_date_method_format, 0) PHP_ME_MAPPING(modify, date_modify, arginfo_date_method_modify, 0) PHP_ME_MAPPING(add, date_add, arginfo_date_method_add, 0) PHP_ME_MAPPING(sub, date_sub, arginfo_date_method_sub, 0) PHP_ME_MAPPING(getTimezone, date_timezone_get, arginfo_date_method_timezone_get, 0) PHP_ME_MAPPING(setTimezone, date_timezone_set, arginfo_date_method_timezone_set, 0) PHP_ME_MAPPING(getOffset, date_offset_get, arginfo_date_method_offset_get, 0) PHP_ME_MAPPING(setTime, date_time_set, arginfo_date_method_time_set, 0) PHP_ME_MAPPING(setDate, date_date_set, arginfo_date_method_date_set, 0) PHP_ME_MAPPING(setISODate, date_isodate_set, arginfo_date_method_isodate_set, 0) PHP_ME_MAPPING(setTimestamp, date_timestamp_set, arginfo_date_method_timestamp_set, 0) PHP_ME_MAPPING(getTimestamp, date_timestamp_get, arginfo_date_method_timestamp_get, 0) PHP_ME_MAPPING(diff, date_diff, arginfo_date_method_diff, 0) {NULL, NULL, NULL} }; const zend_function_entry date_funcs_timezone[] = { PHP_ME(DateTimeZone, __construct, arginfo_timezone_open, ZEND_ACC_CTOR|ZEND_ACC_PUBLIC) PHP_ME_MAPPING(getName, timezone_name_get, arginfo_timezone_method_name_get, 0) PHP_ME_MAPPING(getOffset, timezone_offset_get, arginfo_timezone_method_offset_get, 0) PHP_ME_MAPPING(getTransitions, timezone_transitions_get, arginfo_timezone_method_transitions_get, 0) PHP_ME_MAPPING(getLocation, timezone_location_get, arginfo_timezone_method_location_get, 0) PHP_ME_MAPPING(listAbbreviations, timezone_abbreviations_list, arginfo_timezone_abbreviations_list, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_ME_MAPPING(listIdentifiers, timezone_identifiers_list, arginfo_timezone_identifiers_list, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) {NULL, NULL, NULL} }; const zend_function_entry date_funcs_interval[] = { PHP_ME(DateInterval, __construct, arginfo_date_interval_construct, ZEND_ACC_CTOR|ZEND_ACC_PUBLIC) PHP_ME_MAPPING(format, date_interval_format, arginfo_date_method_interval_format, 0) PHP_ME_MAPPING(createFromDateString, date_interval_create_from_date_string, arginfo_date_interval_create_from_date_string, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) {NULL, NULL, NULL} }; const zend_function_entry date_funcs_period[] = { PHP_ME(DatePeriod, __construct, arginfo_date_period_construct, ZEND_ACC_CTOR|ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; static char* guess_timezone(const timelib_tzdb *tzdb TSRMLS_DC); static void date_register_classes(TSRMLS_D); /* }}} */ ZEND_DECLARE_MODULE_GLOBALS(date) static PHP_GINIT_FUNCTION(date); /* True global */ timelib_tzdb *php_date_global_timezone_db; int php_date_global_timezone_db_enabled; #define DATE_DEFAULT_LATITUDE "31.7667" #define DATE_DEFAULT_LONGITUDE "35.2333" /* on 90'35; common sunset declaration (start of sun body appear) */ #define DATE_SUNSET_ZENITH "90.583333" /* on 90'35; common sunrise declaration (sun body disappeared) */ #define DATE_SUNRISE_ZENITH "90.583333" /* {{{ INI Settings */ PHP_INI_BEGIN() STD_PHP_INI_ENTRY("date.timezone", "", PHP_INI_ALL, OnUpdateString, default_timezone, zend_date_globals, date_globals) PHP_INI_ENTRY("date.default_latitude", DATE_DEFAULT_LATITUDE, PHP_INI_ALL, NULL) PHP_INI_ENTRY("date.default_longitude", DATE_DEFAULT_LONGITUDE, PHP_INI_ALL, NULL) PHP_INI_ENTRY("date.sunset_zenith", DATE_SUNSET_ZENITH, PHP_INI_ALL, NULL) PHP_INI_ENTRY("date.sunrise_zenith", DATE_SUNRISE_ZENITH, PHP_INI_ALL, NULL) PHP_INI_END() /* }}} */ zend_class_entry *date_ce_date, *date_ce_timezone, *date_ce_interval, *date_ce_period; PHPAPI zend_class_entry *php_date_get_date_ce(void) { return date_ce_date; } PHPAPI zend_class_entry *php_date_get_timezone_ce(void) { return date_ce_timezone; } static zend_object_handlers date_object_handlers_date; static zend_object_handlers date_object_handlers_timezone; static zend_object_handlers date_object_handlers_interval; static zend_object_handlers date_object_handlers_period; #define DATE_SET_CONTEXT \ zval *object; \ object = getThis(); \ #define DATE_FETCH_OBJECT \ php_date_obj *obj; \ DATE_SET_CONTEXT; \ if (object) { \ if (zend_parse_parameters_none() == FAILURE) { \ return; \ } \ } else { \ if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, NULL, "O", &object, date_ce_date) == FAILURE) { \ RETURN_FALSE; \ } \ } \ obj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); \ #define DATE_CHECK_INITIALIZED(member, class_name) \ if (!(member)) { \ php_error_docref(NULL TSRMLS_CC, E_WARNING, "The " #class_name " object has not been correctly initialized by its constructor"); \ RETURN_FALSE; \ } static void date_object_free_storage_date(void *object TSRMLS_DC); static void date_object_free_storage_timezone(void *object TSRMLS_DC); static void date_object_free_storage_interval(void *object TSRMLS_DC); static void date_object_free_storage_period(void *object TSRMLS_DC); static zend_object_value date_object_new_date(zend_class_entry *class_type TSRMLS_DC); static zend_object_value date_object_new_timezone(zend_class_entry *class_type TSRMLS_DC); static zend_object_value date_object_new_interval(zend_class_entry *class_type TSRMLS_DC); static zend_object_value date_object_new_period(zend_class_entry *class_type TSRMLS_DC); static zend_object_value date_object_clone_date(zval *this_ptr TSRMLS_DC); static zend_object_value date_object_clone_timezone(zval *this_ptr TSRMLS_DC); static zend_object_value date_object_clone_interval(zval *this_ptr TSRMLS_DC); static zend_object_value date_object_clone_period(zval *this_ptr TSRMLS_DC); static int date_object_compare_date(zval *d1, zval *d2 TSRMLS_DC); static HashTable *date_object_get_properties(zval *object TSRMLS_DC); static HashTable *date_object_get_properties_interval(zval *object TSRMLS_DC); zval *date_interval_read_property(zval *object, zval *member, int type, const zend_literal *key TSRMLS_DC); void date_interval_write_property(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC); /* {{{ Module struct */ zend_module_entry date_module_entry = { STANDARD_MODULE_HEADER_EX, NULL, NULL, "date", /* extension name */ date_functions, /* function list */ PHP_MINIT(date), /* process startup */ PHP_MSHUTDOWN(date), /* process shutdown */ PHP_RINIT(date), /* request startup */ PHP_RSHUTDOWN(date), /* request shutdown */ PHP_MINFO(date), /* extension info */ PHP_VERSION, /* extension version */ PHP_MODULE_GLOBALS(date), /* globals descriptor */ PHP_GINIT(date), /* globals ctor */ NULL, /* globals dtor */ NULL, /* post deactivate */ STANDARD_MODULE_PROPERTIES_EX }; /* }}} */ /* {{{ PHP_GINIT_FUNCTION */ static PHP_GINIT_FUNCTION(date) { date_globals->default_timezone = NULL; date_globals->timezone = NULL; date_globals->tzcache = NULL; } /* }}} */ static void _php_date_tzinfo_dtor(void *tzinfo) { timelib_tzinfo **tzi = (timelib_tzinfo **)tzinfo; timelib_tzinfo_dtor(*tzi); } /* {{{ PHP_RINIT_FUNCTION */ PHP_RINIT_FUNCTION(date) { if (DATEG(timezone)) { efree(DATEG(timezone)); } DATEG(timezone) = NULL; DATEG(tzcache) = NULL; DATEG(last_errors) = NULL; return SUCCESS; } /* }}} */ /* {{{ PHP_RSHUTDOWN_FUNCTION */ PHP_RSHUTDOWN_FUNCTION(date) { if (DATEG(timezone)) { efree(DATEG(timezone)); } DATEG(timezone) = NULL; if(DATEG(tzcache)) { zend_hash_destroy(DATEG(tzcache)); FREE_HASHTABLE(DATEG(tzcache)); DATEG(tzcache) = NULL; } if (DATEG(last_errors)) { timelib_error_container_dtor(DATEG(last_errors)); DATEG(last_errors) = NULL; } return SUCCESS; } /* }}} */ #define DATE_TIMEZONEDB php_date_global_timezone_db ? php_date_global_timezone_db : timelib_builtin_db() /* * RFC822, Section 5.1: http://www.ietf.org/rfc/rfc822.txt * date-time = [ day "," ] date time ; dd mm yy hh:mm:ss zzz * day = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" * date = 1*2DIGIT month 2DIGIT ; day month year e.g. 20 Jun 82 * month = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec" * time = hour zone ; ANSI and Military * hour = 2DIGIT ":" 2DIGIT [":" 2DIGIT] ; 00:00:00 - 23:59:59 * zone = "UT" / "GMT" / "EST" / "EDT" / "CST" / "CDT" / "MST" / "MDT" / "PST" / "PDT" / 1ALPHA / ( ("+" / "-") 4DIGIT ) */ #define DATE_FORMAT_RFC822 "D, d M y H:i:s O" /* * RFC850, Section 2.1.4: http://www.ietf.org/rfc/rfc850.txt * Format must be acceptable both to the ARPANET and to the getdate routine. * One format that is acceptable to both is Weekday, DD-Mon-YY HH:MM:SS TIMEZONE * TIMEZONE can be any timezone name (3 or more letters) */ #define DATE_FORMAT_RFC850 "l, d-M-y H:i:s T" /* * RFC1036, Section 2.1.2: http://www.ietf.org/rfc/rfc1036.txt * Its format must be acceptable both in RFC-822 and to the getdate(3) * Wdy, DD Mon YY HH:MM:SS TIMEZONE * There is no hope of having a complete list of timezones. Universal * Time (GMT), the North American timezones (PST, PDT, MST, MDT, CST, * CDT, EST, EDT) and the +/-hhmm offset specifed in RFC-822 should be supported. */ #define DATE_FORMAT_RFC1036 "D, d M y H:i:s O" /* * RFC1123, Section 5.2.14: http://www.ietf.org/rfc/rfc1123.txt * RFC-822 Date and Time Specification: RFC-822 Section 5 * The syntax for the date is hereby changed to: date = 1*2DIGIT month 2*4DIGIT */ #define DATE_FORMAT_RFC1123 "D, d M Y H:i:s O" /* * RFC2822, Section 3.3: http://www.ietf.org/rfc/rfc2822.txt * FWS = ([*WSP CRLF] 1*WSP) / ; Folding white space * CFWS = *([FWS] comment) (([FWS] comment) / FWS) * * date-time = [ day-of-week "," ] date FWS time [CFWS] * day-of-week = ([FWS] day-name) * day-name = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" * date = day month year * year = 4*DIGIT * month = (FWS month-name FWS) * month-name = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec" * day = ([FWS] 1*2DIGIT) * time = time-of-day FWS zone * time-of-day = hour ":" minute [ ":" second ] * hour = 2DIGIT * minute = 2DIGIT * second = 2DIGIT * zone = (( "+" / "-" ) 4DIGIT) */ #define DATE_FORMAT_RFC2822 "D, d M Y H:i:s O" /* * RFC3339, Section 5.6: http://www.ietf.org/rfc/rfc3339.txt * date-fullyear = 4DIGIT * date-month = 2DIGIT ; 01-12 * date-mday = 2DIGIT ; 01-28, 01-29, 01-30, 01-31 based on month/year * * time-hour = 2DIGIT ; 00-23 * time-minute = 2DIGIT ; 00-59 * time-second = 2DIGIT ; 00-58, 00-59, 00-60 based on leap second rules * * time-secfrac = "." 1*DIGIT * time-numoffset = ("+" / "-") time-hour ":" time-minute * time-offset = "Z" / time-numoffset * * partial-time = time-hour ":" time-minute ":" time-second [time-secfrac] * full-date = date-fullyear "-" date-month "-" date-mday * full-time = partial-time time-offset * * date-time = full-date "T" full-time */ #define DATE_FORMAT_RFC3339 "Y-m-d\\TH:i:sP" #define DATE_FORMAT_ISO8601 "Y-m-d\\TH:i:sO" #define DATE_TZ_ERRMSG \ "It is not safe to rely on the system's timezone settings. You are " \ "*required* to use the date.timezone setting or the " \ "date_default_timezone_set() function. In case you used any of those " \ "methods and you are still getting this warning, you most likely " \ "misspelled the timezone identifier. " #define SUNFUNCS_RET_TIMESTAMP 0 #define SUNFUNCS_RET_STRING 1 #define SUNFUNCS_RET_DOUBLE 2 /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(date) { REGISTER_INI_ENTRIES(); date_register_classes(TSRMLS_C); /* * RFC4287, Section 3.3: http://www.ietf.org/rfc/rfc4287.txt * A Date construct is an element whose content MUST conform to the * "date-time" production in [RFC3339]. In addition, an uppercase "T" * character MUST be used to separate date and time, and an uppercase * "Z" character MUST be present in the absence of a numeric time zone offset. */ REGISTER_STRING_CONSTANT("DATE_ATOM", DATE_FORMAT_RFC3339, CONST_CS | CONST_PERSISTENT); /* * Preliminary specification: http://wp.netscape.com/newsref/std/cookie_spec.html * "This is based on RFC 822, RFC 850, RFC 1036, and RFC 1123, * with the variations that the only legal time zone is GMT * and the separators between the elements of the date must be dashes." */ REGISTER_STRING_CONSTANT("DATE_COOKIE", DATE_FORMAT_RFC850, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_ISO8601", DATE_FORMAT_ISO8601, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC822", DATE_FORMAT_RFC822, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC850", DATE_FORMAT_RFC850, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC1036", DATE_FORMAT_RFC1036, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC1123", DATE_FORMAT_RFC1123, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC2822", DATE_FORMAT_RFC2822, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC3339", DATE_FORMAT_RFC3339, CONST_CS | CONST_PERSISTENT); /* * RSS 2.0 Specification: http://blogs.law.harvard.edu/tech/rss * "All date-times in RSS conform to the Date and Time Specification of RFC 822, * with the exception that the year may be expressed with two characters or four characters (four preferred)" */ REGISTER_STRING_CONSTANT("DATE_RSS", DATE_FORMAT_RFC1123, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_W3C", DATE_FORMAT_RFC3339, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SUNFUNCS_RET_TIMESTAMP", SUNFUNCS_RET_TIMESTAMP, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SUNFUNCS_RET_STRING", SUNFUNCS_RET_STRING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SUNFUNCS_RET_DOUBLE", SUNFUNCS_RET_DOUBLE, CONST_CS | CONST_PERSISTENT); php_date_global_timezone_db = NULL; php_date_global_timezone_db_enabled = 0; DATEG(last_errors) = NULL; return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ PHP_MSHUTDOWN_FUNCTION(date) { UNREGISTER_INI_ENTRIES(); if (DATEG(last_errors)) { timelib_error_container_dtor(DATEG(last_errors)); } return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(date) { const timelib_tzdb *tzdb = DATE_TIMEZONEDB; php_info_print_table_start(); php_info_print_table_row(2, "date/time support", "enabled"); php_info_print_table_row(2, "\"Olson\" Timezone Database Version", tzdb->version); php_info_print_table_row(2, "Timezone Database", php_date_global_timezone_db_enabled ? "external" : "internal"); php_info_print_table_row(2, "Default timezone", guess_timezone(tzdb TSRMLS_CC)); php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ /* {{{ Timezone Cache functions */ static timelib_tzinfo *php_date_parse_tzfile(char *formal_tzname, const timelib_tzdb *tzdb TSRMLS_DC) { timelib_tzinfo *tzi, **ptzi; if(!DATEG(tzcache)) { ALLOC_HASHTABLE(DATEG(tzcache)); zend_hash_init(DATEG(tzcache), 4, NULL, _php_date_tzinfo_dtor, 0); } if (zend_hash_find(DATEG(tzcache), formal_tzname, strlen(formal_tzname) + 1, (void **) &ptzi) == SUCCESS) { return *ptzi; } tzi = timelib_parse_tzfile(formal_tzname, tzdb); if (tzi) { zend_hash_add(DATEG(tzcache), formal_tzname, strlen(formal_tzname) + 1, (void *) &tzi, sizeof(timelib_tzinfo*), NULL); } return tzi; } /* }}} */ /* {{{ Helper functions */ static char* guess_timezone(const timelib_tzdb *tzdb TSRMLS_DC) { char *env; /* Checking configure timezone */ if (DATEG(timezone) && (strlen(DATEG(timezone)) > 0)) { return DATEG(timezone); } /* Check environment variable */ env = getenv("TZ"); if (env && *env && timelib_timezone_id_is_valid(env, tzdb)) { return env; } /* Check config setting for default timezone */ if (!DATEG(default_timezone)) { /* Special case: ext/date wasn't initialized yet */ zval ztz; if (SUCCESS == zend_get_configuration_directive("date.timezone", sizeof("date.timezone"), &ztz) && Z_TYPE(ztz) == IS_STRING && Z_STRLEN(ztz) > 0 && timelib_timezone_id_is_valid(Z_STRVAL(ztz), tzdb)) { return Z_STRVAL(ztz); } } else if (*DATEG(default_timezone) && timelib_timezone_id_is_valid(DATEG(default_timezone), tzdb)) { return DATEG(default_timezone); } #if HAVE_TM_ZONE /* Try to guess timezone from system information */ { struct tm *ta, tmbuf; time_t the_time; char *tzid = NULL; the_time = time(NULL); ta = php_localtime_r(&the_time, &tmbuf); if (ta) { tzid = timelib_timezone_id_from_abbr(ta->tm_zone, ta->tm_gmtoff, ta->tm_isdst); } if (! tzid) { tzid = "UTC"; } php_error_docref(NULL TSRMLS_CC, E_WARNING, DATE_TZ_ERRMSG "We selected '%s' for '%s/%.1f/%s' instead", tzid, ta ? ta->tm_zone : "Unknown", ta ? (float) (ta->tm_gmtoff / 3600) : 0, ta ? (ta->tm_isdst ? "DST" : "no DST") : "Unknown"); return tzid; } #endif #ifdef PHP_WIN32 { char *tzid; TIME_ZONE_INFORMATION tzi; switch (GetTimeZoneInformation(&tzi)) { /* DST in effect */ case TIME_ZONE_ID_DAYLIGHT: /* If user has disabled DST in the control panel, Windows returns 0 here */ if (tzi.DaylightBias == 0) { goto php_win_std_time; } tzid = timelib_timezone_id_from_abbr("", (tzi.Bias + tzi.DaylightBias) * -60, 1); if (! tzid) { tzid = "UTC"; } php_error_docref(NULL TSRMLS_CC, E_WARNING, DATE_TZ_ERRMSG "We selected '%s' for '%.1f/DST' instead", tzid, ((tzi.Bias + tzi.DaylightBias) / -60.0)); break; /* no DST or not in effect */ case TIME_ZONE_ID_UNKNOWN: case TIME_ZONE_ID_STANDARD: default: php_win_std_time: tzid = timelib_timezone_id_from_abbr("", (tzi.Bias + tzi.StandardBias) * -60, 0); if (! tzid) { tzid = "UTC"; } php_error_docref(NULL TSRMLS_CC, E_WARNING, DATE_TZ_ERRMSG "We selected '%s' for '%.1f/no DST' instead", tzid, ((tzi.Bias + tzi.StandardBias) / -60.0)); break; } return tzid; } #elif defined(NETWARE) /* Try to guess timezone from system information */ { char *tzid = timelib_timezone_id_from_abbr("", ((_timezone * -1) + (daylightOffset * daylightOnOff)), daylightOnOff); if (tzid) { return tzid; } } #endif /* Fallback to UTC */ php_error_docref(NULL TSRMLS_CC, E_WARNING, DATE_TZ_ERRMSG "We had to select 'UTC' because your platform doesn't provide functionality for the guessing algorithm"); return "UTC"; } PHPAPI timelib_tzinfo *get_timezone_info(TSRMLS_D) { char *tz; timelib_tzinfo *tzi; tz = guess_timezone(DATE_TIMEZONEDB TSRMLS_CC); tzi = php_date_parse_tzfile(tz, DATE_TIMEZONEDB TSRMLS_CC); if (! tzi) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Timezone database is corrupt - this should *never* happen!"); } return tzi; } /* }}} */ /* {{{ date() and gmdate() data */ #include "ext/standard/php_smart_str.h" static char *mon_full_names[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; static char *mon_short_names[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; static char *day_full_names[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; static char *day_short_names[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; static char *english_suffix(timelib_sll number) { if (number >= 10 && number <= 19) { return "th"; } else { switch (number % 10) { case 1: return "st"; case 2: return "nd"; case 3: return "rd"; } } return "th"; } /* }}} */ /* {{{ day of week helpers */ char *php_date_full_day_name(timelib_sll y, timelib_sll m, timelib_sll d) { timelib_sll day_of_week = timelib_day_of_week(y, m, d); if (day_of_week < 0) { return "Unknown"; } return day_full_names[day_of_week]; } char *php_date_short_day_name(timelib_sll y, timelib_sll m, timelib_sll d) { timelib_sll day_of_week = timelib_day_of_week(y, m, d); if (day_of_week < 0) { return "Unknown"; } return day_short_names[day_of_week]; } /* }}} */ /* {{{ date_format - (gm)date helper */ static char *date_format(char *format, int format_len, timelib_time *t, int localtime) { smart_str string = {0}; int i, length; char buffer[97]; timelib_time_offset *offset = NULL; timelib_sll isoweek, isoyear; int rfc_colon; if (!format_len) { return estrdup(""); } if (localtime) { if (t->zone_type == TIMELIB_ZONETYPE_ABBR) { offset = timelib_time_offset_ctor(); offset->offset = (t->z - (t->dst * 60)) * -60; offset->leap_secs = 0; offset->is_dst = t->dst; offset->abbr = strdup(t->tz_abbr); } else if (t->zone_type == TIMELIB_ZONETYPE_OFFSET) { offset = timelib_time_offset_ctor(); offset->offset = (t->z) * -60; offset->leap_secs = 0; offset->is_dst = 0; offset->abbr = malloc(9); /* GMT�xxxx\0 */ snprintf(offset->abbr, 9, "GMT%c%02d%02d", localtime ? ((offset->offset < 0) ? '-' : '+') : '+', localtime ? abs(offset->offset / 3600) : 0, localtime ? abs((offset->offset % 3600) / 60) : 0 ); } else { offset = timelib_get_time_zone_info(t->sse, t->tz_info); } } timelib_isoweek_from_date(t->y, t->m, t->d, &isoweek, &isoyear); for (i = 0; i < format_len; i++) { rfc_colon = 0; switch (format[i]) { /* day */ case 'd': length = slprintf(buffer, 32, "%02d", (int) t->d); break; case 'D': length = slprintf(buffer, 32, "%s", php_date_short_day_name(t->y, t->m, t->d)); break; case 'j': length = slprintf(buffer, 32, "%d", (int) t->d); break; case 'l': length = slprintf(buffer, 32, "%s", php_date_full_day_name(t->y, t->m, t->d)); break; case 'S': length = slprintf(buffer, 32, "%s", english_suffix(t->d)); break; case 'w': length = slprintf(buffer, 32, "%d", (int) timelib_day_of_week(t->y, t->m, t->d)); break; case 'N': length = slprintf(buffer, 32, "%d", (int) timelib_iso_day_of_week(t->y, t->m, t->d)); break; case 'z': length = slprintf(buffer, 32, "%d", (int) timelib_day_of_year(t->y, t->m, t->d)); break; /* week */ case 'W': length = slprintf(buffer, 32, "%02d", (int) isoweek); break; /* iso weeknr */ case 'o': length = slprintf(buffer, 32, "%d", (int) isoyear); break; /* iso year */ /* month */ case 'F': length = slprintf(buffer, 32, "%s", mon_full_names[t->m - 1]); break; case 'm': length = slprintf(buffer, 32, "%02d", (int) t->m); break; case 'M': length = slprintf(buffer, 32, "%s", mon_short_names[t->m - 1]); break; case 'n': length = slprintf(buffer, 32, "%d", (int) t->m); break; case 't': length = slprintf(buffer, 32, "%d", (int) timelib_days_in_month(t->y, t->m)); break; /* year */ case 'L': length = slprintf(buffer, 32, "%d", timelib_is_leap((int) t->y)); break; case 'y': length = slprintf(buffer, 32, "%02d", (int) t->y % 100); break; case 'Y': length = slprintf(buffer, 32, "%s%04lld", t->y < 0 ? "-" : "", php_date_llabs((timelib_sll) t->y)); break; /* time */ case 'a': length = slprintf(buffer, 32, "%s", t->h >= 12 ? "pm" : "am"); break; case 'A': length = slprintf(buffer, 32, "%s", t->h >= 12 ? "PM" : "AM"); break; case 'B': { int retval = (((((long)t->sse)-(((long)t->sse) - ((((long)t->sse) % 86400) + 3600))) * 10) / 864); while (retval < 0) { retval += 1000; } retval = retval % 1000; length = slprintf(buffer, 32, "%03d", retval); break; } case 'g': length = slprintf(buffer, 32, "%d", (t->h % 12) ? (int) t->h % 12 : 12); break; case 'G': length = slprintf(buffer, 32, "%d", (int) t->h); break; case 'h': length = slprintf(buffer, 32, "%02d", (t->h % 12) ? (int) t->h % 12 : 12); break; case 'H': length = slprintf(buffer, 32, "%02d", (int) t->h); break; case 'i': length = slprintf(buffer, 32, "%02d", (int) t->i); break; case 's': length = slprintf(buffer, 32, "%02d", (int) t->s); break; case 'u': length = slprintf(buffer, 32, "%06d", (int) floor(t->f * 1000000)); break; /* timezone */ case 'I': length = slprintf(buffer, 32, "%d", localtime ? offset->is_dst : 0); break; case 'P': rfc_colon = 1; /* break intentionally missing */ case 'O': length = slprintf(buffer, 32, "%c%02d%s%02d", localtime ? ((offset->offset < 0) ? '-' : '+') : '+', localtime ? abs(offset->offset / 3600) : 0, rfc_colon ? ":" : "", localtime ? abs((offset->offset % 3600) / 60) : 0 ); break; case 'T': length = slprintf(buffer, 32, "%s", localtime ? offset->abbr : "GMT"); break; case 'e': if (!localtime) { length = slprintf(buffer, 32, "%s", "UTC"); } else { switch (t->zone_type) { case TIMELIB_ZONETYPE_ID: length = slprintf(buffer, 32, "%s", t->tz_info->name); break; case TIMELIB_ZONETYPE_ABBR: length = slprintf(buffer, 32, "%s", offset->abbr); break; case TIMELIB_ZONETYPE_OFFSET: length = slprintf(buffer, 32, "%c%02d:%02d", ((offset->offset < 0) ? '-' : '+'), abs(offset->offset / 3600), abs((offset->offset % 3600) / 60) ); break; } } break; case 'Z': length = slprintf(buffer, 32, "%d", localtime ? offset->offset : 0); break; /* full date/time */ case 'c': length = slprintf(buffer, 96, "%04d-%02d-%02dT%02d:%02d:%02d%c%02d:%02d", (int) t->y, (int) t->m, (int) t->d, (int) t->h, (int) t->i, (int) t->s, localtime ? ((offset->offset < 0) ? '-' : '+') : '+', localtime ? abs(offset->offset / 3600) : 0, localtime ? abs((offset->offset % 3600) / 60) : 0 ); break; case 'r': length = slprintf(buffer, 96, "%3s, %02d %3s %04d %02d:%02d:%02d %c%02d%02d", php_date_short_day_name(t->y, t->m, t->d), (int) t->d, mon_short_names[t->m - 1], (int) t->y, (int) t->h, (int) t->i, (int) t->s, localtime ? ((offset->offset < 0) ? '-' : '+') : '+', localtime ? abs(offset->offset / 3600) : 0, localtime ? abs((offset->offset % 3600) / 60) : 0 ); break; case 'U': length = slprintf(buffer, 32, "%lld", (timelib_sll) t->sse); break; case '\\': if (i < format_len) i++; /* break intentionally missing */ default: buffer[0] = format[i]; buffer[1] = '\0'; length = 1; break; } smart_str_appendl(&string, buffer, length); } smart_str_0(&string); if (localtime) { timelib_time_offset_dtor(offset); } return string.c; } static void php_date(INTERNAL_FUNCTION_PARAMETERS, int localtime) { char *format; int format_len; long ts; char *string; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &format, &format_len, &ts) == FAILURE) { RETURN_FALSE; } if (ZEND_NUM_ARGS() == 1) { ts = time(NULL); } string = php_format_date(format, format_len, ts, localtime TSRMLS_CC); RETVAL_STRING(string, 0); } /* }}} */ PHPAPI char *php_format_date(char *format, int format_len, time_t ts, int localtime TSRMLS_DC) /* {{{ */ { timelib_time *t; timelib_tzinfo *tzi; char *string; t = timelib_time_ctor(); if (localtime) { tzi = get_timezone_info(TSRMLS_C); t->tz_info = tzi; t->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(t, ts); } else { tzi = NULL; timelib_unixtime2gmt(t, ts); } string = date_format(format, format_len, t, localtime); timelib_time_dtor(t); return string; } /* }}} */ /* {{{ php_idate */ PHPAPI int php_idate(char format, time_t ts, int localtime TSRMLS_DC) { timelib_time *t; timelib_tzinfo *tzi; int retval = -1; timelib_time_offset *offset = NULL; timelib_sll isoweek, isoyear; t = timelib_time_ctor(); if (!localtime) { tzi = get_timezone_info(TSRMLS_C); t->tz_info = tzi; t->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(t, ts); } else { tzi = NULL; timelib_unixtime2gmt(t, ts); } if (!localtime) { if (t->zone_type == TIMELIB_ZONETYPE_ABBR) { offset = timelib_time_offset_ctor(); offset->offset = (t->z - (t->dst * 60)) * -60; offset->leap_secs = 0; offset->is_dst = t->dst; offset->abbr = strdup(t->tz_abbr); } else if (t->zone_type == TIMELIB_ZONETYPE_OFFSET) { offset = timelib_time_offset_ctor(); offset->offset = (t->z - (t->dst * 60)) * -60; offset->leap_secs = 0; offset->is_dst = t->dst; offset->abbr = malloc(9); /* GMT�xxxx\0 */ snprintf(offset->abbr, 9, "GMT%c%02d%02d", !localtime ? ((offset->offset < 0) ? '-' : '+') : '+', !localtime ? abs(offset->offset / 3600) : 0, !localtime ? abs((offset->offset % 3600) / 60) : 0 ); } else { offset = timelib_get_time_zone_info(t->sse, t->tz_info); } } timelib_isoweek_from_date(t->y, t->m, t->d, &isoweek, &isoyear); switch (format) { /* day */ case 'd': case 'j': retval = (int) t->d; break; case 'w': retval = (int) timelib_day_of_week(t->y, t->m, t->d); break; case 'z': retval = (int) timelib_day_of_year(t->y, t->m, t->d); break; /* week */ case 'W': retval = (int) isoweek; break; /* iso weeknr */ /* month */ case 'm': case 'n': retval = (int) t->m; break; case 't': retval = (int) timelib_days_in_month(t->y, t->m); break; /* year */ case 'L': retval = (int) timelib_is_leap((int) t->y); break; case 'y': retval = (int) (t->y % 100); break; case 'Y': retval = (int) t->y; break; /* Swatch Beat a.k.a. Internet Time */ case 'B': retval = (((((long)t->sse)-(((long)t->sse) - ((((long)t->sse) % 86400) + 3600))) * 10) / 864); while (retval < 0) { retval += 1000; } retval = retval % 1000; break; /* time */ case 'g': case 'h': retval = (int) ((t->h % 12) ? (int) t->h % 12 : 12); break; case 'H': case 'G': retval = (int) t->h; break; case 'i': retval = (int) t->i; break; case 's': retval = (int) t->s; break; /* timezone */ case 'I': retval = (int) (!localtime ? offset->is_dst : 0); break; case 'Z': retval = (int) (!localtime ? offset->offset : 0); break; case 'U': retval = (int) t->sse; break; } if (!localtime) { timelib_time_offset_dtor(offset); } timelib_time_dtor(t); return retval; } /* }}} */ /* {{{ proto string date(string format [, long timestamp]) Format a local date/time */ PHP_FUNCTION(date) { php_date(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto string gmdate(string format [, long timestamp]) Format a GMT date/time */ PHP_FUNCTION(gmdate) { php_date(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto int idate(string format [, int timestamp]) Format a local time/date as integer */ PHP_FUNCTION(idate) { char *format; int format_len; long ts = 0; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &format, &format_len, &ts) == FAILURE) { RETURN_FALSE; } if (format_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "idate format is one char"); RETURN_FALSE; } if (ZEND_NUM_ARGS() == 1) { ts = time(NULL); } ret = php_idate(format[0], ts, 0 TSRMLS_CC); if (ret == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unrecognized date format token."); RETURN_FALSE; } RETURN_LONG(ret); } /* }}} */ /* {{{ php_date_set_tzdb - NOT THREADSAFE */ PHPAPI void php_date_set_tzdb(timelib_tzdb *tzdb) { const timelib_tzdb *builtin = timelib_builtin_db(); if (php_version_compare(tzdb->version, builtin->version) > 0) { php_date_global_timezone_db = tzdb; php_date_global_timezone_db_enabled = 1; } } /* }}} */ /* {{{ php_parse_date: Backwards compability function */ PHPAPI signed long php_parse_date(char *string, signed long *now) { timelib_time *parsed_time; timelib_error_container *error = NULL; int error2; signed long retval; parsed_time = timelib_strtotime(string, strlen(string), &error, DATE_TIMEZONEDB); if (error->error_count) { timelib_error_container_dtor(error); return -1; } timelib_error_container_dtor(error); timelib_update_ts(parsed_time, NULL); retval = timelib_date_to_int(parsed_time, &error2); timelib_time_dtor(parsed_time); if (error2) { return -1; } return retval; } /* }}} */ /* {{{ proto int strtotime(string time [, int now ]) Convert string representation of date and time to a timestamp */ PHP_FUNCTION(strtotime) { char *times, *initial_ts; int time_len, error1, error2; struct timelib_error_container *error; long preset_ts = 0, ts; timelib_time *t, *now; timelib_tzinfo *tzi; tzi = get_timezone_info(TSRMLS_C); if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "sl", &times, &time_len, &preset_ts) != FAILURE) { /* We have an initial timestamp */ now = timelib_time_ctor(); initial_ts = emalloc(25); snprintf(initial_ts, 24, "@%ld UTC", preset_ts); t = timelib_strtotime(initial_ts, strlen(initial_ts), NULL, DATE_TIMEZONEDB); /* we ignore the error here, as this should never fail */ timelib_update_ts(t, tzi); now->tz_info = tzi; now->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(now, t->sse); timelib_time_dtor(t); efree(initial_ts); } else if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &times, &time_len, &preset_ts) != FAILURE) { /* We have no initial timestamp */ now = timelib_time_ctor(); now->tz_info = tzi; now->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(now, (timelib_sll) time(NULL)); } else { RETURN_FALSE; } if (!time_len) { timelib_time_dtor(now); RETURN_FALSE; } t = timelib_strtotime(times, time_len, &error, DATE_TIMEZONEDB); error1 = error->error_count; timelib_error_container_dtor(error); timelib_fill_holes(t, now, TIMELIB_NO_CLONE); timelib_update_ts(t, tzi); ts = timelib_date_to_int(t, &error2); timelib_time_dtor(now); timelib_time_dtor(t); if (error1 || error2) { RETURN_FALSE; } else { RETURN_LONG(ts); } } /* }}} */ /* {{{ php_mktime - (gm)mktime helper */ PHPAPI void php_mktime(INTERNAL_FUNCTION_PARAMETERS, int gmt) { long hou = 0, min = 0, sec = 0, mon = 0, day = 0, yea = 0, dst = -1; timelib_time *now; timelib_tzinfo *tzi = NULL; long ts, adjust_seconds = 0; int error; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lllllll", &hou, &min, &sec, &mon, &day, &yea, &dst) == FAILURE) { RETURN_FALSE; } /* Initialize structure with current time */ now = timelib_time_ctor(); if (gmt) { timelib_unixtime2gmt(now, (timelib_sll) time(NULL)); } else { tzi = get_timezone_info(TSRMLS_C); now->tz_info = tzi; now->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(now, (timelib_sll) time(NULL)); } /* Fill in the new data */ switch (ZEND_NUM_ARGS()) { case 7: /* break intentionally missing */ case 6: if (yea >= 0 && yea < 70) { yea += 2000; } else if (yea >= 70 && yea <= 100) { yea += 1900; } now->y = yea; /* break intentionally missing again */ case 5: now->d = day; /* break missing intentionally here too */ case 4: now->m = mon; /* and here */ case 3: now->s = sec; /* yup, this break isn't here on purpose too */ case 2: now->i = min; /* last intentionally missing break */ case 1: now->h = hou; break; default: php_error_docref(NULL TSRMLS_CC, E_STRICT, "You should be using the time() function instead"); } /* Update the timestamp */ if (gmt) { timelib_update_ts(now, NULL); } else { timelib_update_ts(now, tzi); } /* Support for the deprecated is_dst parameter */ if (dst != -1) { php_error_docref(NULL TSRMLS_CC, E_DEPRECATED, "The is_dst parameter is deprecated"); if (gmt) { /* GMT never uses DST */ if (dst == 1) { adjust_seconds = -3600; } } else { /* Figure out is_dst for current TS */ timelib_time_offset *tmp_offset; tmp_offset = timelib_get_time_zone_info(now->sse, tzi); if (dst == 1 && tmp_offset->is_dst == 0) { adjust_seconds = -3600; } if (dst == 0 && tmp_offset->is_dst == 1) { adjust_seconds = +3600; } timelib_time_offset_dtor(tmp_offset); } } /* Clean up and return */ ts = timelib_date_to_int(now, &error); ts += adjust_seconds; timelib_time_dtor(now); if (error) { RETURN_FALSE; } else { RETURN_LONG(ts); } } /* }}} */ /* {{{ proto int mktime([int hour [, int min [, int sec [, int mon [, int day [, int year]]]]]]) Get UNIX timestamp for a date */ PHP_FUNCTION(mktime) { php_mktime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto int gmmktime([int hour [, int min [, int sec [, int mon [, int day [, int year]]]]]]) Get UNIX timestamp for a GMT date */ PHP_FUNCTION(gmmktime) { php_mktime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto bool checkdate(int month, int day, int year) Returns true(1) if it is a valid date in gregorian calendar */ PHP_FUNCTION(checkdate) { long m, d, y; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lll", &m, &d, &y) == FAILURE) { RETURN_FALSE; } if (y < 1 || y > 32767 || !timelib_valid_date(y, m, d)) { RETURN_FALSE; } RETURN_TRUE; /* True : This month, day, year arguments are valid */ } /* }}} */ #ifdef HAVE_STRFTIME /* {{{ php_strftime - (gm)strftime helper */ PHPAPI void php_strftime(INTERNAL_FUNCTION_PARAMETERS, int gmt) { char *format, *buf; int format_len; long timestamp = 0; struct tm ta; int max_reallocs = 5; size_t buf_len = 64, real_len; timelib_time *ts; timelib_tzinfo *tzi; timelib_time_offset *offset = NULL; timestamp = (long) time(NULL); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &format, &format_len, &timestamp) == FAILURE) { RETURN_FALSE; } if (format_len == 0) { RETURN_FALSE; } ts = timelib_time_ctor(); if (gmt) { tzi = NULL; timelib_unixtime2gmt(ts, (timelib_sll) timestamp); } else { tzi = get_timezone_info(TSRMLS_C); ts->tz_info = tzi; ts->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(ts, (timelib_sll) timestamp); } ta.tm_sec = ts->s; ta.tm_min = ts->i; ta.tm_hour = ts->h; ta.tm_mday = ts->d; ta.tm_mon = ts->m - 1; ta.tm_year = ts->y - 1900; ta.tm_wday = timelib_day_of_week(ts->y, ts->m, ts->d); ta.tm_yday = timelib_day_of_year(ts->y, ts->m, ts->d); if (gmt) { ta.tm_isdst = 0; #if HAVE_TM_GMTOFF ta.tm_gmtoff = 0; #endif #if HAVE_TM_ZONE ta.tm_zone = "GMT"; #endif } else { offset = timelib_get_time_zone_info(timestamp, tzi); ta.tm_isdst = offset->is_dst; #if HAVE_TM_GMTOFF ta.tm_gmtoff = offset->offset; #endif #if HAVE_TM_ZONE ta.tm_zone = offset->abbr; #endif } buf = (char *) emalloc(buf_len); while ((real_len=strftime(buf, buf_len, format, &ta))==buf_len || real_len==0) { buf_len *= 2; buf = (char *) erealloc(buf, buf_len); if (!--max_reallocs) { break; } } timelib_time_dtor(ts); if (!gmt) { timelib_time_offset_dtor(offset); } if (real_len && real_len != buf_len) { buf = (char *) erealloc(buf, real_len + 1); RETURN_STRINGL(buf, real_len, 0); } efree(buf); RETURN_FALSE; } /* }}} */ /* {{{ proto string strftime(string format [, int timestamp]) Format a local time/date according to locale settings */ PHP_FUNCTION(strftime) { php_strftime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto string gmstrftime(string format [, int timestamp]) Format a GMT/UCT time/date according to locale settings */ PHP_FUNCTION(gmstrftime) { php_strftime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ #endif /* {{{ proto int time(void) Return current UNIX timestamp */ PHP_FUNCTION(time) { RETURN_LONG((long)time(NULL)); } /* }}} */ /* {{{ proto array localtime([int timestamp [, bool associative_array]]) Returns the results of the C system call localtime as an associative array if the associative_array argument is set to 1 other wise it is a regular array */ PHP_FUNCTION(localtime) { long timestamp = (long)time(NULL); zend_bool associative = 0; timelib_tzinfo *tzi; timelib_time *ts; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lb", &timestamp, &associative) == FAILURE) { RETURN_FALSE; } tzi = get_timezone_info(TSRMLS_C); ts = timelib_time_ctor(); ts->tz_info = tzi; ts->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(ts, (timelib_sll) timestamp); array_init(return_value); if (associative) { add_assoc_long(return_value, "tm_sec", ts->s); add_assoc_long(return_value, "tm_min", ts->i); add_assoc_long(return_value, "tm_hour", ts->h); add_assoc_long(return_value, "tm_mday", ts->d); add_assoc_long(return_value, "tm_mon", ts->m - 1); add_assoc_long(return_value, "tm_year", ts->y - 1900); add_assoc_long(return_value, "tm_wday", timelib_day_of_week(ts->y, ts->m, ts->d)); add_assoc_long(return_value, "tm_yday", timelib_day_of_year(ts->y, ts->m, ts->d)); add_assoc_long(return_value, "tm_isdst", ts->dst); } else { add_next_index_long(return_value, ts->s); add_next_index_long(return_value, ts->i); add_next_index_long(return_value, ts->h); add_next_index_long(return_value, ts->d); add_next_index_long(return_value, ts->m - 1); add_next_index_long(return_value, ts->y- 1900); add_next_index_long(return_value, timelib_day_of_week(ts->y, ts->m, ts->d)); add_next_index_long(return_value, timelib_day_of_year(ts->y, ts->m, ts->d)); add_next_index_long(return_value, ts->dst); } timelib_time_dtor(ts); } /* }}} */ /* {{{ proto array getdate([int timestamp]) Get date/time information */ PHP_FUNCTION(getdate) { long timestamp = (long)time(NULL); timelib_tzinfo *tzi; timelib_time *ts; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &timestamp) == FAILURE) { RETURN_FALSE; } tzi = get_timezone_info(TSRMLS_C); ts = timelib_time_ctor(); ts->tz_info = tzi; ts->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(ts, (timelib_sll) timestamp); array_init(return_value); add_assoc_long(return_value, "seconds", ts->s); add_assoc_long(return_value, "minutes", ts->i); add_assoc_long(return_value, "hours", ts->h); add_assoc_long(return_value, "mday", ts->d); add_assoc_long(return_value, "wday", timelib_day_of_week(ts->y, ts->m, ts->d)); add_assoc_long(return_value, "mon", ts->m); add_assoc_long(return_value, "year", ts->y); add_assoc_long(return_value, "yday", timelib_day_of_year(ts->y, ts->m, ts->d)); add_assoc_string(return_value, "weekday", php_date_full_day_name(ts->y, ts->m, ts->d), 1); add_assoc_string(return_value, "month", mon_full_names[ts->m - 1], 1); add_index_long(return_value, 0, timestamp); timelib_time_dtor(ts); } /* }}} */ #define PHP_DATE_TIMEZONE_GROUP_AFRICA 0x0001 #define PHP_DATE_TIMEZONE_GROUP_AMERICA 0x0002 #define PHP_DATE_TIMEZONE_GROUP_ANTARCTICA 0x0004 #define PHP_DATE_TIMEZONE_GROUP_ARCTIC 0x0008 #define PHP_DATE_TIMEZONE_GROUP_ASIA 0x0010 #define PHP_DATE_TIMEZONE_GROUP_ATLANTIC 0x0020 #define PHP_DATE_TIMEZONE_GROUP_AUSTRALIA 0x0040 #define PHP_DATE_TIMEZONE_GROUP_EUROPE 0x0080 #define PHP_DATE_TIMEZONE_GROUP_INDIAN 0x0100 #define PHP_DATE_TIMEZONE_GROUP_PACIFIC 0x0200 #define PHP_DATE_TIMEZONE_GROUP_UTC 0x0400 #define PHP_DATE_TIMEZONE_GROUP_ALL 0x07FF #define PHP_DATE_TIMEZONE_GROUP_ALL_W_BC 0x0FFF #define PHP_DATE_TIMEZONE_PER_COUNTRY 0x1000 #define PHP_DATE_PERIOD_EXCLUDE_START_DATE 0x0001 /* define an overloaded iterator structure */ typedef struct { zend_object_iterator intern; zval *date_period_zval; zval *current; php_period_obj *object; int current_index; } date_period_it; /* {{{ date_period_it_invalidate_current */ static void date_period_it_invalidate_current(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; if (iterator->current) { zval_ptr_dtor(&iterator->current); iterator->current = NULL; } } /* }}} */ /* {{{ date_period_it_dtor */ static void date_period_it_dtor(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; date_period_it_invalidate_current(iter TSRMLS_CC); zval_ptr_dtor(&iterator->date_period_zval); efree(iterator); } /* }}} */ /* {{{ date_period_it_has_more */ static int date_period_it_has_more(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; php_period_obj *object = iterator->object; timelib_time *it_time = object->current; /* apply modification if it's not the first iteration */ if (!object->include_start_date || iterator->current_index > 0) { it_time->have_relative = 1; it_time->relative = *object->interval; it_time->sse_uptodate = 0; timelib_update_ts(it_time, NULL); timelib_update_from_sse(it_time); } if (object->end) { return object->current->sse < object->end->sse ? SUCCESS : FAILURE; } else { return (iterator->current_index < object->recurrences) ? SUCCESS : FAILURE; } } /* }}} */ /* {{{ date_period_it_current_data */ static void date_period_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; php_period_obj *object = iterator->object; timelib_time *it_time = object->current; php_date_obj *newdateobj; /* Create new object */ MAKE_STD_ZVAL(iterator->current); php_date_instantiate(date_ce_date, iterator->current TSRMLS_CC); newdateobj = (php_date_obj *) zend_object_store_get_object(iterator->current TSRMLS_CC); newdateobj->time = timelib_time_ctor(); *newdateobj->time = *it_time; if (it_time->tz_abbr) { newdateobj->time->tz_abbr = strdup(it_time->tz_abbr); } if (it_time->tz_info) { newdateobj->time->tz_info = it_time->tz_info; } *data = &iterator->current; } /* }}} */ /* {{{ date_period_it_current_key */ static int date_period_it_current_key(zend_object_iterator *iter, char **str_key, uint *str_key_len, ulong *int_key TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; *int_key = iterator->current_index; return HASH_KEY_IS_LONG; } /* }}} */ /* {{{ date_period_it_move_forward */ static void date_period_it_move_forward(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; iterator->current_index++; date_period_it_invalidate_current(iter TSRMLS_CC); } /* }}} */ /* {{{ date_period_it_rewind */ static void date_period_it_rewind(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; iterator->current_index = 0; if (iterator->object->current) { timelib_time_dtor(iterator->object->current); } iterator->object->current = timelib_time_clone(iterator->object->start); date_period_it_invalidate_current(iter TSRMLS_CC); } /* }}} */ /* iterator handler table */ zend_object_iterator_funcs date_period_it_funcs = { date_period_it_dtor, date_period_it_has_more, date_period_it_current_data, date_period_it_current_key, date_period_it_move_forward, date_period_it_rewind, date_period_it_invalidate_current }; zend_object_iterator *date_object_period_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) { date_period_it *iterator = emalloc(sizeof(date_period_it)); php_period_obj *dpobj = (php_period_obj *)zend_object_store_get_object(object TSRMLS_CC); if (by_ref) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } Z_ADDREF_P(object); iterator->intern.data = (void*) dpobj; iterator->intern.funcs = &date_period_it_funcs; iterator->date_period_zval = object; iterator->object = dpobj; iterator->current = NULL; return (zend_object_iterator*)iterator; } static void date_register_classes(TSRMLS_D) { zend_class_entry ce_date, ce_timezone, ce_interval, ce_period; INIT_CLASS_ENTRY(ce_date, "DateTime", date_funcs_date); ce_date.create_object = date_object_new_date; date_ce_date = zend_register_internal_class_ex(&ce_date, NULL, NULL TSRMLS_CC); memcpy(&date_object_handlers_date, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); date_object_handlers_date.clone_obj = date_object_clone_date; date_object_handlers_date.compare_objects = date_object_compare_date; date_object_handlers_date.get_properties = date_object_get_properties; #define REGISTER_DATE_CLASS_CONST_STRING(const_name, value) \ zend_declare_class_constant_stringl(date_ce_date, const_name, sizeof(const_name)-1, value, sizeof(value)-1 TSRMLS_CC); REGISTER_DATE_CLASS_CONST_STRING("ATOM", DATE_FORMAT_RFC3339); REGISTER_DATE_CLASS_CONST_STRING("COOKIE", DATE_FORMAT_RFC850); REGISTER_DATE_CLASS_CONST_STRING("ISO8601", DATE_FORMAT_ISO8601); REGISTER_DATE_CLASS_CONST_STRING("RFC822", DATE_FORMAT_RFC822); REGISTER_DATE_CLASS_CONST_STRING("RFC850", DATE_FORMAT_RFC850); REGISTER_DATE_CLASS_CONST_STRING("RFC1036", DATE_FORMAT_RFC1036); REGISTER_DATE_CLASS_CONST_STRING("RFC1123", DATE_FORMAT_RFC1123); REGISTER_DATE_CLASS_CONST_STRING("RFC2822", DATE_FORMAT_RFC2822); REGISTER_DATE_CLASS_CONST_STRING("RFC3339", DATE_FORMAT_RFC3339); REGISTER_DATE_CLASS_CONST_STRING("RSS", DATE_FORMAT_RFC1123); REGISTER_DATE_CLASS_CONST_STRING("W3C", DATE_FORMAT_RFC3339); INIT_CLASS_ENTRY(ce_timezone, "DateTimeZone", date_funcs_timezone); ce_timezone.create_object = date_object_new_timezone; date_ce_timezone = zend_register_internal_class_ex(&ce_timezone, NULL, NULL TSRMLS_CC); memcpy(&date_object_handlers_timezone, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); date_object_handlers_timezone.clone_obj = date_object_clone_timezone; #define REGISTER_TIMEZONE_CLASS_CONST_STRING(const_name, value) \ zend_declare_class_constant_long(date_ce_timezone, const_name, sizeof(const_name)-1, value TSRMLS_CC); REGISTER_TIMEZONE_CLASS_CONST_STRING("AFRICA", PHP_DATE_TIMEZONE_GROUP_AFRICA); REGISTER_TIMEZONE_CLASS_CONST_STRING("AMERICA", PHP_DATE_TIMEZONE_GROUP_AMERICA); REGISTER_TIMEZONE_CLASS_CONST_STRING("ANTARCTICA", PHP_DATE_TIMEZONE_GROUP_ANTARCTICA); REGISTER_TIMEZONE_CLASS_CONST_STRING("ARCTIC", PHP_DATE_TIMEZONE_GROUP_ARCTIC); REGISTER_TIMEZONE_CLASS_CONST_STRING("ASIA", PHP_DATE_TIMEZONE_GROUP_ASIA); REGISTER_TIMEZONE_CLASS_CONST_STRING("ATLANTIC", PHP_DATE_TIMEZONE_GROUP_ATLANTIC); REGISTER_TIMEZONE_CLASS_CONST_STRING("AUSTRALIA", PHP_DATE_TIMEZONE_GROUP_AUSTRALIA); REGISTER_TIMEZONE_CLASS_CONST_STRING("EUROPE", PHP_DATE_TIMEZONE_GROUP_EUROPE); REGISTER_TIMEZONE_CLASS_CONST_STRING("INDIAN", PHP_DATE_TIMEZONE_GROUP_INDIAN); REGISTER_TIMEZONE_CLASS_CONST_STRING("PACIFIC", PHP_DATE_TIMEZONE_GROUP_PACIFIC); REGISTER_TIMEZONE_CLASS_CONST_STRING("UTC", PHP_DATE_TIMEZONE_GROUP_UTC); REGISTER_TIMEZONE_CLASS_CONST_STRING("ALL", PHP_DATE_TIMEZONE_GROUP_ALL); REGISTER_TIMEZONE_CLASS_CONST_STRING("ALL_WITH_BC", PHP_DATE_TIMEZONE_GROUP_ALL_W_BC); REGISTER_TIMEZONE_CLASS_CONST_STRING("PER_COUNTRY", PHP_DATE_TIMEZONE_PER_COUNTRY); INIT_CLASS_ENTRY(ce_interval, "DateInterval", date_funcs_interval); ce_interval.create_object = date_object_new_interval; date_ce_interval = zend_register_internal_class_ex(&ce_interval, NULL, NULL TSRMLS_CC); memcpy(&date_object_handlers_interval, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); date_object_handlers_interval.clone_obj = date_object_clone_interval; date_object_handlers_interval.read_property = date_interval_read_property; date_object_handlers_interval.write_property = date_interval_write_property; date_object_handlers_interval.get_properties = date_object_get_properties_interval; date_object_handlers_interval.get_property_ptr_ptr = NULL; INIT_CLASS_ENTRY(ce_period, "DatePeriod", date_funcs_period); ce_period.create_object = date_object_new_period; date_ce_period = zend_register_internal_class_ex(&ce_period, NULL, NULL TSRMLS_CC); date_ce_period->get_iterator = date_object_period_get_iterator; date_ce_period->iterator_funcs.funcs = &date_period_it_funcs; zend_class_implements(date_ce_period TSRMLS_CC, 1, zend_ce_traversable); memcpy(&date_object_handlers_period, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); date_object_handlers_period.clone_obj = date_object_clone_period; #define REGISTER_PERIOD_CLASS_CONST_STRING(const_name, value) \ zend_declare_class_constant_long(date_ce_period, const_name, sizeof(const_name)-1, value TSRMLS_CC); REGISTER_PERIOD_CLASS_CONST_STRING("EXCLUDE_START_DATE", PHP_DATE_PERIOD_EXCLUDE_START_DATE); } static inline zend_object_value date_object_new_date_ex(zend_class_entry *class_type, php_date_obj **ptr TSRMLS_DC) { php_date_obj *intern; zend_object_value retval; intern = emalloc(sizeof(php_date_obj)); memset(intern, 0, sizeof(php_date_obj)); if (ptr) { *ptr = intern; } zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) date_object_free_storage_date, NULL TSRMLS_CC); retval.handlers = &date_object_handlers_date; return retval; } static zend_object_value date_object_new_date(zend_class_entry *class_type TSRMLS_DC) { return date_object_new_date_ex(class_type, NULL TSRMLS_CC); } static zend_object_value date_object_clone_date(zval *this_ptr TSRMLS_DC) { php_date_obj *new_obj = NULL; php_date_obj *old_obj = (php_date_obj *) zend_object_store_get_object(this_ptr TSRMLS_CC); zend_object_value new_ov = date_object_new_date_ex(old_obj->std.ce, &new_obj TSRMLS_CC); zend_objects_clone_members(&new_obj->std, new_ov, &old_obj->std, Z_OBJ_HANDLE_P(this_ptr) TSRMLS_CC); /* this should probably moved to a new `timelib_time *timelime_time_clone(timelib_time *)` */ new_obj->time = timelib_time_ctor(); *new_obj->time = *old_obj->time; if (old_obj->time->tz_abbr) { new_obj->time->tz_abbr = strdup(old_obj->time->tz_abbr); } if (old_obj->time->tz_info) { new_obj->time->tz_info = old_obj->time->tz_info; } return new_ov; } static int date_object_compare_date(zval *d1, zval *d2 TSRMLS_DC) { if (Z_TYPE_P(d1) == IS_OBJECT && Z_TYPE_P(d2) == IS_OBJECT && instanceof_function(Z_OBJCE_P(d1), date_ce_date TSRMLS_CC) && instanceof_function(Z_OBJCE_P(d2), date_ce_date TSRMLS_CC)) { php_date_obj *o1 = zend_object_store_get_object(d1 TSRMLS_CC); php_date_obj *o2 = zend_object_store_get_object(d2 TSRMLS_CC); if (!o1->time->sse_uptodate) { timelib_update_ts(o1->time, o1->time->tz_info); } if (!o2->time->sse_uptodate) { timelib_update_ts(o2->time, o2->time->tz_info); } return (o1->time->sse == o2->time->sse) ? 0 : ((o1->time->sse < o2->time->sse) ? -1 : 1); } return 1; } static HashTable *date_object_get_properties(zval *object TSRMLS_DC) { HashTable *props; zval *zv; php_date_obj *dateobj; dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); props = zend_std_get_properties(object TSRMLS_CC); if (!dateobj->time || GC_G(gc_active)) { return props; } /* first we add the date and time in ISO format */ MAKE_STD_ZVAL(zv); ZVAL_STRING(zv, date_format("Y-m-d H:i:s", 12, dateobj->time, 1), 0); zend_hash_update(props, "date", 5, &zv, sizeof(zval), NULL); /* then we add the timezone name (or similar) */ if (dateobj->time->is_localtime) { MAKE_STD_ZVAL(zv); ZVAL_LONG(zv, dateobj->time->zone_type); zend_hash_update(props, "timezone_type", 14, &zv, sizeof(zval), NULL); MAKE_STD_ZVAL(zv); switch (dateobj->time->zone_type) { case TIMELIB_ZONETYPE_ID: ZVAL_STRING(zv, dateobj->time->tz_info->name, 1); break; case TIMELIB_ZONETYPE_OFFSET: { char *tmpstr = emalloc(sizeof("UTC+05:00")); timelib_sll utc_offset = dateobj->time->z; snprintf(tmpstr, sizeof("+05:00"), "%c%02d:%02d", utc_offset > 0 ? '-' : '+', abs(utc_offset / 60), abs((utc_offset % 60))); ZVAL_STRING(zv, tmpstr, 0); } break; case TIMELIB_ZONETYPE_ABBR: ZVAL_STRING(zv, dateobj->time->tz_abbr, 1); break; } zend_hash_update(props, "timezone", 9, &zv, sizeof(zval), NULL); } return props; } static inline zend_object_value date_object_new_timezone_ex(zend_class_entry *class_type, php_timezone_obj **ptr TSRMLS_DC) { php_timezone_obj *intern; zend_object_value retval; intern = emalloc(sizeof(php_timezone_obj)); memset(intern, 0, sizeof(php_timezone_obj)); if (ptr) { *ptr = intern; } zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) date_object_free_storage_timezone, NULL TSRMLS_CC); retval.handlers = &date_object_handlers_timezone; return retval; } static zend_object_value date_object_new_timezone(zend_class_entry *class_type TSRMLS_DC) { return date_object_new_timezone_ex(class_type, NULL TSRMLS_CC); } static zend_object_value date_object_clone_timezone(zval *this_ptr TSRMLS_DC) { php_timezone_obj *new_obj = NULL; php_timezone_obj *old_obj = (php_timezone_obj *) zend_object_store_get_object(this_ptr TSRMLS_CC); zend_object_value new_ov = date_object_new_timezone_ex(old_obj->std.ce, &new_obj TSRMLS_CC); zend_objects_clone_members(&new_obj->std, new_ov, &old_obj->std, Z_OBJ_HANDLE_P(this_ptr) TSRMLS_CC); new_obj->type = old_obj->type; new_obj->initialized = 1; switch (new_obj->type) { case TIMELIB_ZONETYPE_ID: new_obj->tzi.tz = old_obj->tzi.tz; break; case TIMELIB_ZONETYPE_OFFSET: new_obj->tzi.utc_offset = old_obj->tzi.utc_offset; break; case TIMELIB_ZONETYPE_ABBR: new_obj->tzi.z.utc_offset = old_obj->tzi.z.utc_offset; new_obj->tzi.z.dst = old_obj->tzi.z.dst; new_obj->tzi.z.abbr = old_obj->tzi.z.abbr; break; } return new_ov; } static inline zend_object_value date_object_new_interval_ex(zend_class_entry *class_type, php_interval_obj **ptr TSRMLS_DC) { php_interval_obj *intern; zend_object_value retval; intern = emalloc(sizeof(php_interval_obj)); memset(intern, 0, sizeof(php_interval_obj)); if (ptr) { *ptr = intern; } zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) date_object_free_storage_interval, NULL TSRMLS_CC); retval.handlers = &date_object_handlers_interval; return retval; } static zend_object_value date_object_new_interval(zend_class_entry *class_type TSRMLS_DC) { return date_object_new_interval_ex(class_type, NULL TSRMLS_CC); } static zend_object_value date_object_clone_interval(zval *this_ptr TSRMLS_DC) { php_interval_obj *new_obj = NULL; php_interval_obj *old_obj = (php_interval_obj *) zend_object_store_get_object(this_ptr TSRMLS_CC); zend_object_value new_ov = date_object_new_interval_ex(old_obj->std.ce, &new_obj TSRMLS_CC); zend_objects_clone_members(&new_obj->std, new_ov, &old_obj->std, Z_OBJ_HANDLE_P(this_ptr) TSRMLS_CC); /** FIX ME ADD CLONE STUFF **/ return new_ov; } static HashTable *date_object_get_properties_interval(zval *object TSRMLS_DC) { HashTable *props; zval *zv; php_interval_obj *intervalobj; intervalobj = (php_interval_obj *) zend_object_store_get_object(object TSRMLS_CC); props = zend_std_get_properties(object TSRMLS_CC); if (!intervalobj->initialized || GC_G(gc_active)) { return props; } #define PHP_DATE_INTERVAL_ADD_PROPERTY(n,f) \ MAKE_STD_ZVAL(zv); \ ZVAL_LONG(zv, intervalobj->diff->f); \ zend_hash_update(props, n, strlen(n) + 1, &zv, sizeof(zval), NULL); PHP_DATE_INTERVAL_ADD_PROPERTY("y", y); PHP_DATE_INTERVAL_ADD_PROPERTY("m", m); PHP_DATE_INTERVAL_ADD_PROPERTY("d", d); PHP_DATE_INTERVAL_ADD_PROPERTY("h", h); PHP_DATE_INTERVAL_ADD_PROPERTY("i", i); PHP_DATE_INTERVAL_ADD_PROPERTY("s", s); PHP_DATE_INTERVAL_ADD_PROPERTY("invert", invert); if (intervalobj->diff->days != -99999) { PHP_DATE_INTERVAL_ADD_PROPERTY("days", days); } else { MAKE_STD_ZVAL(zv); ZVAL_FALSE(zv); zend_hash_update(props, "days", 5, &zv, sizeof(zval), NULL); } return props; } static inline zend_object_value date_object_new_period_ex(zend_class_entry *class_type, php_period_obj **ptr TSRMLS_DC) { php_period_obj *intern; zend_object_value retval; intern = emalloc(sizeof(php_period_obj)); memset(intern, 0, sizeof(php_period_obj)); if (ptr) { *ptr = intern; } zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) date_object_free_storage_period, NULL TSRMLS_CC); retval.handlers = &date_object_handlers_period; return retval; } static zend_object_value date_object_new_period(zend_class_entry *class_type TSRMLS_DC) { return date_object_new_period_ex(class_type, NULL TSRMLS_CC); } static zend_object_value date_object_clone_period(zval *this_ptr TSRMLS_DC) { php_period_obj *new_obj = NULL; php_period_obj *old_obj = (php_period_obj *) zend_object_store_get_object(this_ptr TSRMLS_CC); zend_object_value new_ov = date_object_new_period_ex(old_obj->std.ce, &new_obj TSRMLS_CC); zend_objects_clone_members(&new_obj->std, new_ov, &old_obj->std, Z_OBJ_HANDLE_P(this_ptr) TSRMLS_CC); /** FIX ME ADD CLONE STUFF **/ return new_ov; } static void date_object_free_storage_date(void *object TSRMLS_DC) { php_date_obj *intern = (php_date_obj *)object; if (intern->time) { timelib_time_dtor(intern->time); } zend_object_std_dtor(&intern->std TSRMLS_CC); efree(object); } static void date_object_free_storage_timezone(void *object TSRMLS_DC) { php_timezone_obj *intern = (php_timezone_obj *)object; if (intern->type == TIMELIB_ZONETYPE_ABBR) { free(intern->tzi.z.abbr); } zend_object_std_dtor(&intern->std TSRMLS_CC); efree(object); } static void date_object_free_storage_interval(void *object TSRMLS_DC) { php_interval_obj *intern = (php_interval_obj *)object; timelib_rel_time_dtor(intern->diff); zend_object_std_dtor(&intern->std TSRMLS_CC); efree(object); } static void date_object_free_storage_period(void *object TSRMLS_DC) { php_period_obj *intern = (php_period_obj *)object; if (intern->start) { timelib_time_dtor(intern->start); } if (intern->current) { timelib_time_dtor(intern->current); } if (intern->end) { timelib_time_dtor(intern->end); } timelib_rel_time_dtor(intern->interval); zend_object_std_dtor(&intern->std TSRMLS_CC); efree(object); } /* Advanced Interface */ PHPAPI zval *php_date_instantiate(zend_class_entry *pce, zval *object TSRMLS_DC) { Z_TYPE_P(object) = IS_OBJECT; object_init_ex(object, pce); Z_SET_REFCOUNT_P(object, 1); Z_UNSET_ISREF_P(object); return object; } /* Helper function used to store the latest found warnings and errors while * parsing, from either strtotime or parse_from_format. */ static void update_errors_warnings(timelib_error_container *last_errors TSRMLS_DC) { if (DATEG(last_errors)) { timelib_error_container_dtor(DATEG(last_errors)); DATEG(last_errors) = NULL; } DATEG(last_errors) = last_errors; } PHPAPI int php_date_initialize(php_date_obj *dateobj, /*const*/ char *time_str, int time_str_len, char *format, zval *timezone_object, int ctor TSRMLS_DC) { timelib_time *now; timelib_tzinfo *tzi; timelib_error_container *err = NULL; int type = TIMELIB_ZONETYPE_ID, new_dst; char *new_abbr; timelib_sll new_offset; if (dateobj->time) { timelib_time_dtor(dateobj->time); } if (format) { dateobj->time = timelib_parse_from_format(format, time_str_len ? time_str : "", time_str_len ? time_str_len : 0, &err, DATE_TIMEZONEDB); } else { dateobj->time = timelib_strtotime(time_str_len ? time_str : "now", time_str_len ? time_str_len : sizeof("now") -1, &err, DATE_TIMEZONEDB); } /* update last errors and warnings */ update_errors_warnings(err TSRMLS_CC); if (ctor && err && err->error_count) { /* spit out the first library error message, at least */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse time string (%s) at position %d (%c): %s", time_str, err->error_messages[0].position, err->error_messages[0].character, err->error_messages[0].message); } if (err && err->error_count) { return 0; } if (timezone_object) { php_timezone_obj *tzobj; tzobj = (php_timezone_obj *) zend_object_store_get_object(timezone_object TSRMLS_CC); switch (tzobj->type) { case TIMELIB_ZONETYPE_ID: tzi = tzobj->tzi.tz; break; case TIMELIB_ZONETYPE_OFFSET: new_offset = tzobj->tzi.utc_offset; break; case TIMELIB_ZONETYPE_ABBR: new_offset = tzobj->tzi.z.utc_offset; new_dst = tzobj->tzi.z.dst; new_abbr = strdup(tzobj->tzi.z.abbr); break; } type = tzobj->type; } else if (dateobj->time->tz_info) { tzi = dateobj->time->tz_info; } else { tzi = get_timezone_info(TSRMLS_C); } now = timelib_time_ctor(); now->zone_type = type; switch (type) { case TIMELIB_ZONETYPE_ID: now->tz_info = tzi; break; case TIMELIB_ZONETYPE_OFFSET: now->z = new_offset; break; case TIMELIB_ZONETYPE_ABBR: now->z = new_offset; now->dst = new_dst; now->tz_abbr = new_abbr; break; } timelib_unixtime2local(now, (timelib_sll) time(NULL)); timelib_fill_holes(dateobj->time, now, TIMELIB_NO_CLONE); timelib_update_ts(dateobj->time, tzi); dateobj->time->have_relative = 0; timelib_time_dtor(now); return 1; } /* {{{ proto DateTime date_create([string time[, DateTimeZone object]]) Returns new DateTime object */ PHP_FUNCTION(date_create) { zval *timezone_object = NULL; char *time_str = NULL; int time_str_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sO!", &time_str, &time_str_len, &timezone_object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } php_date_instantiate(date_ce_date, return_value TSRMLS_CC); if (!php_date_initialize(zend_object_store_get_object(return_value TSRMLS_CC), time_str, time_str_len, NULL, timezone_object, 0 TSRMLS_CC)) { RETURN_FALSE; } } /* }}} */ /* {{{ proto DateTime date_create_from_format(string format, string time[, DateTimeZone object]) Returns new DateTime object formatted according to the specified format */ PHP_FUNCTION(date_create_from_format) { zval *timezone_object = NULL; char *time_str = NULL, *format_str = NULL; int time_str_len = 0, format_str_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|O", &format_str, &format_str_len, &time_str, &time_str_len, &timezone_object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } php_date_instantiate(date_ce_date, return_value TSRMLS_CC); if (!php_date_initialize(zend_object_store_get_object(return_value TSRMLS_CC), time_str, time_str_len, format_str, timezone_object, 0 TSRMLS_CC)) { RETURN_FALSE; } } /* }}} */ /* {{{ proto DateTime::__construct([string time[, DateTimeZone object]]) Creates new DateTime object */ PHP_METHOD(DateTime, __construct) { zval *timezone_object = NULL; char *time_str = NULL; int time_str_len = 0; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sO!", &time_str, &time_str_len, &timezone_object, date_ce_timezone)) { php_date_initialize(zend_object_store_get_object(getThis() TSRMLS_CC), time_str, time_str_len, NULL, timezone_object, 1 TSRMLS_CC); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ static int php_date_initialize_from_hash(zval **return_value, php_date_obj **dateobj, HashTable *myht TSRMLS_DC) { zval **z_date = NULL; zval **z_timezone = NULL; zval **z_timezone_type = NULL; zval *tmp_obj = NULL; timelib_tzinfo *tzi; php_timezone_obj *tzobj; if (zend_hash_find(myht, "date", 5, (void**) &z_date) == SUCCESS) { convert_to_string(*z_date); if (zend_hash_find(myht, "timezone_type", 14, (void**) &z_timezone_type) == SUCCESS) { convert_to_long(*z_timezone_type); if (zend_hash_find(myht, "timezone", 9, (void**) &z_timezone) == SUCCESS) { convert_to_string(*z_timezone); switch (Z_LVAL_PP(z_timezone_type)) { case TIMELIB_ZONETYPE_OFFSET: case TIMELIB_ZONETYPE_ABBR: { char *tmp = emalloc(Z_STRLEN_PP(z_date) + Z_STRLEN_PP(z_timezone) + 2); snprintf(tmp, Z_STRLEN_PP(z_date) + Z_STRLEN_PP(z_timezone) + 2, "%s %s", Z_STRVAL_PP(z_date), Z_STRVAL_PP(z_timezone)); php_date_initialize(*dateobj, tmp, Z_STRLEN_PP(z_date) + Z_STRLEN_PP(z_timezone) + 1, NULL, NULL, 0 TSRMLS_CC); efree(tmp); return 1; } case TIMELIB_ZONETYPE_ID: convert_to_string(*z_timezone); tzi = php_date_parse_tzfile(Z_STRVAL_PP(z_timezone), DATE_TIMEZONEDB TSRMLS_CC); ALLOC_INIT_ZVAL(tmp_obj); tzobj = zend_object_store_get_object(php_date_instantiate(date_ce_timezone, tmp_obj TSRMLS_CC) TSRMLS_CC); tzobj->type = TIMELIB_ZONETYPE_ID; tzobj->tzi.tz = tzi; tzobj->initialized = 1; php_date_initialize(*dateobj, Z_STRVAL_PP(z_date), Z_STRLEN_PP(z_date), NULL, tmp_obj, 0 TSRMLS_CC); zval_ptr_dtor(&tmp_obj); return 1; } } } } return 0; } /* {{{ proto DateTime::__set_state() */ PHP_METHOD(DateTime, __set_state) { php_date_obj *dateobj; zval *array; HashTable *myht; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) { RETURN_FALSE; } myht = HASH_OF(array); php_date_instantiate(date_ce_date, return_value TSRMLS_CC); dateobj = (php_date_obj *) zend_object_store_get_object(return_value TSRMLS_CC); php_date_initialize_from_hash(&return_value, &dateobj, myht TSRMLS_CC); } /* }}} */ /* {{{ proto DateTime::__wakeup() */ PHP_METHOD(DateTime, __wakeup) { zval *object = getThis(); php_date_obj *dateobj; HashTable *myht; dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); myht = Z_OBJPROP_P(object); php_date_initialize_from_hash(&return_value, &dateobj, myht TSRMLS_CC); } /* }}} */ /* Helper function used to add an associative array of warnings and errors to a zval */ static void zval_from_error_container(zval *z, timelib_error_container *error) { int i; zval *element; add_assoc_long(z, "warning_count", error->warning_count); MAKE_STD_ZVAL(element); array_init(element); for (i = 0; i < error->warning_count; i++) { add_index_string(element, error->warning_messages[i].position, error->warning_messages[i].message, 1); } add_assoc_zval(z, "warnings", element); add_assoc_long(z, "error_count", error->error_count); MAKE_STD_ZVAL(element); array_init(element); for (i = 0; i < error->error_count; i++) { add_index_string(element, error->error_messages[i].position, error->error_messages[i].message, 1); } add_assoc_zval(z, "errors", element); } /* {{{ proto array date_get_last_errors() Returns the warnings and errors found while parsing a date/time string. */ PHP_FUNCTION(date_get_last_errors) { if (DATEG(last_errors)) { array_init(return_value); zval_from_error_container(return_value, DATEG(last_errors)); } else { RETURN_FALSE; } } /* }}} */ void php_date_do_return_parsed_time(INTERNAL_FUNCTION_PARAMETERS, timelib_time *parsed_time, struct timelib_error_container *error) { zval *element; array_init(return_value); #define PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(name, elem) \ if (parsed_time->elem == -99999) { \ add_assoc_bool(return_value, #name, 0); \ } else { \ add_assoc_long(return_value, #name, parsed_time->elem); \ } PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(year, y); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(month, m); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(day, d); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(hour, h); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(minute, i); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(second, s); if (parsed_time->f == -99999) { add_assoc_bool(return_value, "fraction", 0); } else { add_assoc_double(return_value, "fraction", parsed_time->f); } zval_from_error_container(return_value, error); timelib_error_container_dtor(error); add_assoc_bool(return_value, "is_localtime", parsed_time->is_localtime); if (parsed_time->is_localtime) { PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(zone_type, zone_type); switch (parsed_time->zone_type) { case TIMELIB_ZONETYPE_OFFSET: PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(zone, z); add_assoc_bool(return_value, "is_dst", parsed_time->dst); break; case TIMELIB_ZONETYPE_ID: if (parsed_time->tz_abbr) { add_assoc_string(return_value, "tz_abbr", parsed_time->tz_abbr, 1); } if (parsed_time->tz_info) { add_assoc_string(return_value, "tz_id", parsed_time->tz_info->name, 1); } break; case TIMELIB_ZONETYPE_ABBR: PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(zone, z); add_assoc_bool(return_value, "is_dst", parsed_time->dst); add_assoc_string(return_value, "tz_abbr", parsed_time->tz_abbr, 1); break; } } if (parsed_time->have_relative) { MAKE_STD_ZVAL(element); array_init(element); add_assoc_long(element, "year", parsed_time->relative.y); add_assoc_long(element, "month", parsed_time->relative.m); add_assoc_long(element, "day", parsed_time->relative.d); add_assoc_long(element, "hour", parsed_time->relative.h); add_assoc_long(element, "minute", parsed_time->relative.i); add_assoc_long(element, "second", parsed_time->relative.s); if (parsed_time->relative.have_weekday_relative) { add_assoc_long(element, "weekday", parsed_time->relative.weekday); } if (parsed_time->relative.have_special_relative && (parsed_time->relative.special.type == TIMELIB_SPECIAL_WEEKDAY)) { add_assoc_long(element, "weekdays", parsed_time->relative.special.amount); } if (parsed_time->relative.first_last_day_of) { add_assoc_bool(element, parsed_time->relative.first_last_day_of == 1 ? "first_day_of_month" : "last_day_of_month", 1); } add_assoc_zval(return_value, "relative", element); } timelib_time_dtor(parsed_time); } /* {{{ proto array date_parse(string date) Returns associative array with detailed info about given date */ PHP_FUNCTION(date_parse) { char *date; int date_len; struct timelib_error_container *error; timelib_time *parsed_time; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &date, &date_len) == FAILURE) { RETURN_FALSE; } parsed_time = timelib_strtotime(date, date_len, &error, DATE_TIMEZONEDB); php_date_do_return_parsed_time(INTERNAL_FUNCTION_PARAM_PASSTHRU, parsed_time, error); } /* }}} */ /* {{{ proto array date_parse_from_format(string format, string date) Returns associative array with detailed info about given date */ PHP_FUNCTION(date_parse_from_format) { char *date, *format; int date_len, format_len; struct timelib_error_container *error; timelib_time *parsed_time; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &format, &format_len, &date, &date_len) == FAILURE) { RETURN_FALSE; } parsed_time = timelib_parse_from_format(format, date, date_len, &error, DATE_TIMEZONEDB); php_date_do_return_parsed_time(INTERNAL_FUNCTION_PARAM_PASSTHRU, parsed_time, error); } /* }}} */ /* {{{ proto string date_format(DateTime object, string format) Returns date formatted according to given format */ PHP_FUNCTION(date_format) { zval *object; php_date_obj *dateobj; char *format; int format_len; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, date_ce_date, &format, &format_len) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); RETURN_STRING(date_format(format, format_len, dateobj->time, dateobj->time->is_localtime), 0); } /* }}} */ /* {{{ proto DateTime date_modify(DateTime object, string modify) Alters the timestamp. */ PHP_FUNCTION(date_modify) { zval *object; php_date_obj *dateobj; char *modify; int modify_len; timelib_time *tmp_time; timelib_error_container *err = NULL; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, date_ce_date, &modify, &modify_len) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); tmp_time = timelib_strtotime(modify, modify_len, &err, DATE_TIMEZONEDB); /* update last errors and warnings */ update_errors_warnings(err TSRMLS_CC); if (err && err->error_count) { /* spit out the first library error message, at least */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse time string (%s) at position %d (%c): %s", modify, err->error_messages[0].position, err->error_messages[0].character, err->error_messages[0].message); timelib_time_dtor(tmp_time); RETURN_FALSE; } memcpy(&dateobj->time->relative, &tmp_time->relative, sizeof(struct timelib_rel_time)); dateobj->time->have_relative = tmp_time->have_relative; dateobj->time->sse_uptodate = 0; if (tmp_time->y != -99999) { dateobj->time->y = tmp_time->y; } if (tmp_time->m != -99999) { dateobj->time->m = tmp_time->m; } if (tmp_time->d != -99999) { dateobj->time->d = tmp_time->d; } if (tmp_time->h != -99999) { dateobj->time->h = tmp_time->h; if (tmp_time->i != -99999) { dateobj->time->i = tmp_time->i; if (tmp_time->s != -99999) { dateobj->time->s = tmp_time->s; } else { dateobj->time->s = 0; } } else { dateobj->time->i = 0; dateobj->time->s = 0; } } timelib_time_dtor(tmp_time); timelib_update_ts(dateobj->time, NULL); timelib_update_from_sse(dateobj->time); dateobj->time->have_relative = 0; RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_add(DateTime object, DateInterval interval) Adds an interval to the current date in object. */ PHP_FUNCTION(date_add) { zval *object, *interval; php_date_obj *dateobj; php_interval_obj *intobj; int bias = 1; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &object, date_ce_date, &interval, date_ce_interval) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); intobj = (php_interval_obj *) zend_object_store_get_object(interval TSRMLS_CC); DATE_CHECK_INITIALIZED(intobj->initialized, DateInterval); if (intobj->diff->have_weekday_relative || intobj->diff->have_special_relative) { memcpy(&dateobj->time->relative, intobj->diff, sizeof(struct timelib_rel_time)); } else { if (intobj->diff->invert) { bias = -1; } memset(&dateobj->time->relative, 0, sizeof(struct timelib_rel_time)); dateobj->time->relative.y = intobj->diff->y * bias; dateobj->time->relative.m = intobj->diff->m * bias; dateobj->time->relative.d = intobj->diff->d * bias; dateobj->time->relative.h = intobj->diff->h * bias; dateobj->time->relative.i = intobj->diff->i * bias; dateobj->time->relative.s = intobj->diff->s * bias; } dateobj->time->have_relative = 1; dateobj->time->sse_uptodate = 0; timelib_update_ts(dateobj->time, NULL); timelib_update_from_sse(dateobj->time); dateobj->time->have_relative = 0; RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_sub(DateTime object, DateInterval interval) Subtracts an interval to the current date in object. */ PHP_FUNCTION(date_sub) { zval *object, *interval; php_date_obj *dateobj; php_interval_obj *intobj; int bias = 1; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &object, date_ce_date, &interval, date_ce_interval) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); intobj = (php_interval_obj *) zend_object_store_get_object(interval TSRMLS_CC); DATE_CHECK_INITIALIZED(intobj->initialized, DateInterval); if (intobj->diff->have_special_relative) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Only non-special relative time specifications are supported for subtraction"); return; } if (intobj->diff->invert) { bias = -1; } memset(&dateobj->time->relative, 0, sizeof(struct timelib_rel_time)); dateobj->time->relative.y = 0 - (intobj->diff->y * bias); dateobj->time->relative.m = 0 - (intobj->diff->m * bias); dateobj->time->relative.d = 0 - (intobj->diff->d * bias); dateobj->time->relative.h = 0 - (intobj->diff->h * bias); dateobj->time->relative.i = 0 - (intobj->diff->i * bias); dateobj->time->relative.s = 0 - (intobj->diff->s * bias); dateobj->time->have_relative = 1; dateobj->time->sse_uptodate = 0; timelib_update_ts(dateobj->time, NULL); timelib_update_from_sse(dateobj->time); dateobj->time->have_relative = 0; RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTimeZone date_timezone_get(DateTime object) Return new DateTimeZone object relative to give DateTime */ PHP_FUNCTION(date_timezone_get) { zval *object; php_date_obj *dateobj; php_timezone_obj *tzobj; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_date) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); if (dateobj->time->is_localtime/* && dateobj->time->tz_info*/) { php_date_instantiate(date_ce_timezone, return_value TSRMLS_CC); tzobj = (php_timezone_obj *) zend_object_store_get_object(return_value TSRMLS_CC); tzobj->initialized = 1; tzobj->type = dateobj->time->zone_type; switch (dateobj->time->zone_type) { case TIMELIB_ZONETYPE_ID: tzobj->tzi.tz = dateobj->time->tz_info; break; case TIMELIB_ZONETYPE_OFFSET: tzobj->tzi.utc_offset = dateobj->time->z; break; case TIMELIB_ZONETYPE_ABBR: tzobj->tzi.z.utc_offset = dateobj->time->z; tzobj->tzi.z.dst = dateobj->time->dst; tzobj->tzi.z.abbr = strdup(dateobj->time->tz_abbr); break; } } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto DateTime date_timezone_set(DateTime object, DateTimeZone object) Sets the timezone for the DateTime object. */ PHP_FUNCTION(date_timezone_set) { zval *object; zval *timezone_object; php_date_obj *dateobj; php_timezone_obj *tzobj; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &object, date_ce_date, &timezone_object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); tzobj = (php_timezone_obj *) zend_object_store_get_object(timezone_object TSRMLS_CC); if (tzobj->type != TIMELIB_ZONETYPE_ID) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can only do this for zones with ID for now"); return; } timelib_set_timezone(dateobj->time, tzobj->tzi.tz); timelib_unixtime2local(dateobj->time, dateobj->time->sse); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto long date_offset_get(DateTime object) Returns the DST offset. */ PHP_FUNCTION(date_offset_get) { zval *object; php_date_obj *dateobj; timelib_time_offset *offset; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_date) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); if (dateobj->time->is_localtime/* && dateobj->time->tz_info*/) { switch (dateobj->time->zone_type) { case TIMELIB_ZONETYPE_ID: offset = timelib_get_time_zone_info(dateobj->time->sse, dateobj->time->tz_info); RETVAL_LONG(offset->offset); timelib_time_offset_dtor(offset); break; case TIMELIB_ZONETYPE_OFFSET: RETVAL_LONG(dateobj->time->z * -60); break; case TIMELIB_ZONETYPE_ABBR: RETVAL_LONG((dateobj->time->z - (60 * dateobj->time->dst)) * -60); break; } return; } else { RETURN_LONG(0); } } /* }}} */ /* {{{ proto DateTime date_time_set(DateTime object, long hour, long minute[, long second]) Sets the time. */ PHP_FUNCTION(date_time_set) { zval *object; php_date_obj *dateobj; long h, i, s = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oll|l", &object, date_ce_date, &h, &i, &s) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); dateobj->time->h = h; dateobj->time->i = i; dateobj->time->s = s; timelib_update_ts(dateobj->time, NULL); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_date_set(DateTime object, long year, long month, long day) Sets the date. */ PHP_FUNCTION(date_date_set) { zval *object; php_date_obj *dateobj; long y, m, d; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Olll", &object, date_ce_date, &y, &m, &d) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); dateobj->time->y = y; dateobj->time->m = m; dateobj->time->d = d; timelib_update_ts(dateobj->time, NULL); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_isodate_set(DateTime object, long year, long week[, long day]) Sets the ISO date. */ PHP_FUNCTION(date_isodate_set) { zval *object; php_date_obj *dateobj; long y, w, d = 1; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oll|l", &object, date_ce_date, &y, &w, &d) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); dateobj->time->y = y; dateobj->time->m = 1; dateobj->time->d = 1; memset(&dateobj->time->relative, 0, sizeof(dateobj->time->relative)); dateobj->time->relative.d = timelib_daynr_from_weeknr(y, w, d); dateobj->time->have_relative = 1; timelib_update_ts(dateobj->time, NULL); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_timestamp_set(DateTime object, long unixTimestamp) Sets the date and time based on an Unix timestamp. */ PHP_FUNCTION(date_timestamp_set) { zval *object; php_date_obj *dateobj; long timestamp; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Ol", &object, date_ce_date, &timestamp) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); timelib_unixtime2local(dateobj->time, (timelib_sll)timestamp); timelib_update_ts(dateobj->time, NULL); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto long date_timestamp_get(DateTime object) Gets the Unix timestamp. */ PHP_FUNCTION(date_timestamp_get) { zval *object; php_date_obj *dateobj; long timestamp; int error; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_date) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); timelib_update_ts(dateobj->time, NULL); timestamp = timelib_date_to_int(dateobj->time, &error); if (error) { RETURN_FALSE; } else { RETVAL_LONG(timestamp); } } /* }}} */ /* {{{ proto DateInterval date_diff(DateTime object [, bool absolute]) Returns the difference between two DateTime objects. */ PHP_FUNCTION(date_diff) { zval *object1, *object2; php_date_obj *dateobj1, *dateobj2; php_interval_obj *interval; long absolute = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO|l", &object1, date_ce_date, &object2, date_ce_date, &absolute) == FAILURE) { RETURN_FALSE; } dateobj1 = (php_date_obj *) zend_object_store_get_object(object1 TSRMLS_CC); dateobj2 = (php_date_obj *) zend_object_store_get_object(object2 TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj1->time, DateTime); DATE_CHECK_INITIALIZED(dateobj2->time, DateTime); timelib_update_ts(dateobj1->time, NULL); timelib_update_ts(dateobj2->time, NULL); php_date_instantiate(date_ce_interval, return_value TSRMLS_CC); interval = zend_object_store_get_object(return_value TSRMLS_CC); interval->diff = timelib_diff(dateobj1->time, dateobj2->time); if (absolute) { interval->diff->invert = 0; } interval->initialized = 1; } /* }}} */ static int timezone_initialize(timelib_tzinfo **tzi, /*const*/ char *tz TSRMLS_DC) { char *tzid; *tzi = NULL; if ((tzid = timelib_timezone_id_from_abbr(tz, -1, 0))) { *tzi = php_date_parse_tzfile(tzid, DATE_TIMEZONEDB TSRMLS_CC); } else { *tzi = php_date_parse_tzfile(tz, DATE_TIMEZONEDB TSRMLS_CC); } if (*tzi) { return SUCCESS; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown or bad timezone (%s)", tz); return FAILURE; } } /* {{{ proto DateTimeZone timezone_open(string timezone) Returns new DateTimeZone object */ PHP_FUNCTION(timezone_open) { char *tz; int tz_len; timelib_tzinfo *tzi = NULL; php_timezone_obj *tzobj; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &tz, &tz_len) == FAILURE) { RETURN_FALSE; } if (SUCCESS != timezone_initialize(&tzi, tz TSRMLS_CC)) { RETURN_FALSE; } tzobj = zend_object_store_get_object(php_date_instantiate(date_ce_timezone, return_value TSRMLS_CC) TSRMLS_CC); tzobj->type = TIMELIB_ZONETYPE_ID; tzobj->tzi.tz = tzi; tzobj->initialized = 1; } /* }}} */ /* {{{ proto DateTimeZone::__construct(string timezone) Creates new DateTimeZone object. */ PHP_METHOD(DateTimeZone, __construct) { char *tz; int tz_len; timelib_tzinfo *tzi = NULL; php_timezone_obj *tzobj; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &tz, &tz_len)) { if (SUCCESS == timezone_initialize(&tzi, tz TSRMLS_CC)) { tzobj = zend_object_store_get_object(getThis() TSRMLS_CC); tzobj->type = TIMELIB_ZONETYPE_ID; tzobj->tzi.tz = tzi; tzobj->initialized = 1; } else { ZVAL_NULL(getThis()); } } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto string timezone_name_get(DateTimeZone object) Returns the name of the timezone. */ PHP_FUNCTION(timezone_name_get) { zval *object; php_timezone_obj *tzobj; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } tzobj = (php_timezone_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(tzobj->initialized, DateTimeZone); switch (tzobj->type) { case TIMELIB_ZONETYPE_ID: RETURN_STRING(tzobj->tzi.tz->name, 1); break; case TIMELIB_ZONETYPE_OFFSET: { char *tmpstr = emalloc(sizeof("UTC+05:00")); timelib_sll utc_offset = tzobj->tzi.utc_offset; snprintf(tmpstr, sizeof("+05:00"), "%c%02d:%02d", utc_offset > 0 ? '-' : '+', abs(utc_offset / 60), abs((utc_offset % 60))); RETURN_STRING(tmpstr, 0); } break; case TIMELIB_ZONETYPE_ABBR: RETURN_STRING(tzobj->tzi.z.abbr, 1); break; } } /* }}} */ /* {{{ proto string timezone_name_from_abbr(string abbr[, long gmtOffset[, long isdst]]) Returns the timezone name from abbrevation */ PHP_FUNCTION(timezone_name_from_abbr) { char *abbr; char *tzid; int abbr_len; long gmtoffset = -1; long isdst = -1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ll", &abbr, &abbr_len, &gmtoffset, &isdst) == FAILURE) { RETURN_FALSE; } tzid = timelib_timezone_id_from_abbr(abbr, gmtoffset, isdst); if (tzid) { RETURN_STRING(tzid, 1); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto long timezone_offset_get(DateTimeZone object, DateTime object) Returns the timezone offset. */ PHP_FUNCTION(timezone_offset_get) { zval *object, *dateobject; php_timezone_obj *tzobj; php_date_obj *dateobj; timelib_time_offset *offset; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &object, date_ce_timezone, &dateobject, date_ce_date) == FAILURE) { RETURN_FALSE; } tzobj = (php_timezone_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(tzobj->initialized, DateTimeZone); dateobj = (php_date_obj *) zend_object_store_get_object(dateobject TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); switch (tzobj->type) { case TIMELIB_ZONETYPE_ID: offset = timelib_get_time_zone_info(dateobj->time->sse, tzobj->tzi.tz); RETVAL_LONG(offset->offset); timelib_time_offset_dtor(offset); break; case TIMELIB_ZONETYPE_OFFSET: RETURN_LONG(tzobj->tzi.utc_offset * -60); break; case TIMELIB_ZONETYPE_ABBR: RETURN_LONG((tzobj->tzi.z.utc_offset - (tzobj->tzi.z.dst*60)) * -60); break; } } /* }}} */ /* {{{ proto array timezone_transitions_get(DateTimeZone object [, long timestamp_begin [, long timestamp_end ]]) Returns numerically indexed array containing associative array for all transitions in the specified range for the timezone. */ PHP_FUNCTION(timezone_transitions_get) { zval *object, *element; php_timezone_obj *tzobj; unsigned int i, begin = 0, found; long timestamp_begin = LONG_MIN, timestamp_end = LONG_MAX; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|ll", &object, date_ce_timezone, &timestamp_begin, &timestamp_end) == FAILURE) { RETURN_FALSE; } tzobj = (php_timezone_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(tzobj->initialized, DateTimeZone); if (tzobj->type != TIMELIB_ZONETYPE_ID) { RETURN_FALSE; } #define add_nominal() \ MAKE_STD_ZVAL(element); \ array_init(element); \ add_assoc_long(element, "ts", timestamp_begin); \ add_assoc_string(element, "time", php_format_date(DATE_FORMAT_ISO8601, 13, timestamp_begin, 0 TSRMLS_CC), 0); \ add_assoc_long(element, "offset", tzobj->tzi.tz->type[0].offset); \ add_assoc_bool(element, "isdst", tzobj->tzi.tz->type[0].isdst); \ add_assoc_string(element, "abbr", &tzobj->tzi.tz->timezone_abbr[tzobj->tzi.tz->type[0].abbr_idx], 1); \ add_next_index_zval(return_value, element); #define add(i,ts) \ MAKE_STD_ZVAL(element); \ array_init(element); \ add_assoc_long(element, "ts", ts); \ add_assoc_string(element, "time", php_format_date(DATE_FORMAT_ISO8601, 13, ts, 0 TSRMLS_CC), 0); \ add_assoc_long(element, "offset", tzobj->tzi.tz->type[tzobj->tzi.tz->trans_idx[i]].offset); \ add_assoc_bool(element, "isdst", tzobj->tzi.tz->type[tzobj->tzi.tz->trans_idx[i]].isdst); \ add_assoc_string(element, "abbr", &tzobj->tzi.tz->timezone_abbr[tzobj->tzi.tz->type[tzobj->tzi.tz->trans_idx[i]].abbr_idx], 1); \ add_next_index_zval(return_value, element); #define add_last() add(tzobj->tzi.tz->timecnt - 1, timestamp_begin) array_init(return_value); if (timestamp_begin == LONG_MIN) { add_nominal(); begin = 0; found = 1; } else { begin = 0; found = 0; if (tzobj->tzi.tz->timecnt > 0) { do { if (tzobj->tzi.tz->trans[begin] > timestamp_begin) { if (begin > 0) { add(begin - 1, timestamp_begin); } else { add_nominal(); } found = 1; break; } begin++; } while (begin < tzobj->tzi.tz->timecnt); } } if (!found) { if (tzobj->tzi.tz->timecnt > 0) { add_last(); } else { add_nominal(); } } else { for (i = begin; i < tzobj->tzi.tz->timecnt; ++i) { if (tzobj->tzi.tz->trans[i] < timestamp_end) { add(i, tzobj->tzi.tz->trans[i]); } } } } /* }}} */ /* {{{ proto array timezone_location_get() Returns location information for a timezone, including country code, latitude/longitude and comments */ PHP_FUNCTION(timezone_location_get) { zval *object; php_timezone_obj *tzobj; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } tzobj = (php_timezone_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(tzobj->initialized, DateTimeZone); if (tzobj->type != TIMELIB_ZONETYPE_ID) { RETURN_FALSE; } array_init(return_value); add_assoc_string(return_value, "country_code", tzobj->tzi.tz->location.country_code, 1); add_assoc_double(return_value, "latitude", tzobj->tzi.tz->location.latitude); add_assoc_double(return_value, "longitude", tzobj->tzi.tz->location.longitude); add_assoc_string(return_value, "comments", tzobj->tzi.tz->location.comments, 1); } /* }}} */ static int date_interval_initialize(timelib_rel_time **rt, /*const*/ char *format, int format_length TSRMLS_DC) { timelib_time *b = NULL, *e = NULL; timelib_rel_time *p = NULL; int r = 0; int retval = 0; struct timelib_error_container *errors; timelib_strtointerval(format, format_length, &b, &e, &p, &r, &errors); if (errors->error_count > 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown or bad format (%s)", format); retval = FAILURE; } else { if(p) { *rt = p; retval = SUCCESS; } else { if(b && e) { timelib_update_ts(b, NULL); timelib_update_ts(e, NULL); *rt = timelib_diff(b, e); retval = SUCCESS; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse interval (%s)", format); retval = FAILURE; } } } timelib_error_container_dtor(errors); return retval; } /* {{{ date_interval_read_property */ zval *date_interval_read_property(zval *object, zval *member, int type, const zend_literal *key TSRMLS_DC) { php_interval_obj *obj; zval *retval; zval tmp_member; timelib_sll value = -1; if (member->type != IS_STRING) { tmp_member = *member; zval_copy_ctor(&tmp_member); convert_to_string(&tmp_member); member = &tmp_member; } obj = (php_interval_obj *)zend_objects_get_address(object TSRMLS_CC); #define GET_VALUE_FROM_STRUCT(n,m) \ if (strcmp(Z_STRVAL_P(member), m) == 0) { \ value = obj->diff->n; \ break; \ } do { GET_VALUE_FROM_STRUCT(y, "y"); GET_VALUE_FROM_STRUCT(m, "m"); GET_VALUE_FROM_STRUCT(d, "d"); GET_VALUE_FROM_STRUCT(h, "h"); GET_VALUE_FROM_STRUCT(i, "i"); GET_VALUE_FROM_STRUCT(s, "s"); GET_VALUE_FROM_STRUCT(invert, "invert"); GET_VALUE_FROM_STRUCT(days, "days"); /* didn't find any */ retval = (zend_get_std_object_handlers())->read_property(object, member, type, key TSRMLS_CC); if (member == &tmp_member) { zval_dtor(member); } return retval; } while(0); ALLOC_INIT_ZVAL(retval); Z_SET_REFCOUNT_P(retval, 0); ZVAL_LONG(retval, value); if (member == &tmp_member) { zval_dtor(member); } return retval; } /* }}} */ /* {{{ date_interval_write_property */ void date_interval_write_property(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC) { php_interval_obj *obj; zval tmp_member, tmp_value; if (member->type != IS_STRING) { tmp_member = *member; zval_copy_ctor(&tmp_member); convert_to_string(&tmp_member); member = &tmp_member; } obj = (php_interval_obj *)zend_objects_get_address(object TSRMLS_CC); #define SET_VALUE_FROM_STRUCT(n,m) \ if (strcmp(Z_STRVAL_P(member), m) == 0) { \ if (value->type != IS_LONG) { \ tmp_value = *value; \ zval_copy_ctor(&tmp_value); \ convert_to_long(&tmp_value); \ value = &tmp_value; \ } \ obj->diff->n = Z_LVAL_P(value); \ if (value == &tmp_value) { \ zval_dtor(value); \ } \ break; \ } do { SET_VALUE_FROM_STRUCT(y, "y"); SET_VALUE_FROM_STRUCT(m, "m"); SET_VALUE_FROM_STRUCT(d, "d"); SET_VALUE_FROM_STRUCT(h, "h"); SET_VALUE_FROM_STRUCT(i, "i"); SET_VALUE_FROM_STRUCT(s, "s"); SET_VALUE_FROM_STRUCT(invert, "invert"); /* didn't find any */ (zend_get_std_object_handlers())->write_property(object, member, value, key TSRMLS_CC); } while(0); if (member == &tmp_member) { zval_dtor(member); } } /* }}} */ /* {{{ proto DateInterval::__construct([string interval_spec]) Creates new DateInterval object. */ PHP_METHOD(DateInterval, __construct) { char *interval_string = NULL; int interval_string_length; php_interval_obj *diobj; timelib_rel_time *reltime; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &interval_string, &interval_string_length) == SUCCESS) { if (date_interval_initialize(&reltime, interval_string, interval_string_length TSRMLS_CC) == SUCCESS) { diobj = zend_object_store_get_object(getThis() TSRMLS_CC); diobj->diff = reltime; diobj->initialized = 1; } else { ZVAL_NULL(getThis()); } } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto DateInterval date_interval_create_from_date_string(string time) Uses the normal date parsers and sets up a DateInterval from the relative parts of the parsed string */ PHP_FUNCTION(date_interval_create_from_date_string) { char *time_str = NULL; int time_str_len = 0; timelib_time *time; timelib_error_container *err = NULL; php_interval_obj *diobj; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &time_str, &time_str_len) == FAILURE) { RETURN_FALSE; } php_date_instantiate(date_ce_interval, return_value TSRMLS_CC); time = timelib_strtotime(time_str, time_str_len, &err, DATE_TIMEZONEDB); diobj = (php_interval_obj *) zend_object_store_get_object(return_value TSRMLS_CC); diobj->diff = timelib_rel_time_clone(&time->relative); diobj->initialized = 1; timelib_time_dtor(time); timelib_error_container_dtor(err); } /* }}} */ /* {{{ date_interval_format - */ static char *date_interval_format(char *format, int format_len, timelib_rel_time *t) { smart_str string = {0}; int i, length, have_format_spec = 0; char buffer[33]; if (!format_len) { return estrdup(""); } for (i = 0; i < format_len; i++) { if (have_format_spec) { switch (format[i]) { case 'Y': length = slprintf(buffer, 32, "%02d", (int) t->y); break; case 'y': length = slprintf(buffer, 32, "%d", (int) t->y); break; case 'M': length = slprintf(buffer, 32, "%02d", (int) t->m); break; case 'm': length = slprintf(buffer, 32, "%d", (int) t->m); break; case 'D': length = slprintf(buffer, 32, "%02d", (int) t->d); break; case 'd': length = slprintf(buffer, 32, "%d", (int) t->d); break; case 'H': length = slprintf(buffer, 32, "%02d", (int) t->h); break; case 'h': length = slprintf(buffer, 32, "%d", (int) t->h); break; case 'I': length = slprintf(buffer, 32, "%02d", (int) t->i); break; case 'i': length = slprintf(buffer, 32, "%d", (int) t->i); break; case 'S': length = slprintf(buffer, 32, "%02d", (int) t->s); break; case 's': length = slprintf(buffer, 32, "%d", (int) t->s); break; case 'a': { if ((int) t->days != -99999) { length = slprintf(buffer, 32, "%d", (int) t->days); } else { length = slprintf(buffer, 32, "(unknown)"); } } break; case 'r': length = slprintf(buffer, 32, "%s", t->invert ? "-" : ""); break; case 'R': length = slprintf(buffer, 32, "%c", t->invert ? '-' : '+'); break; case '%': length = slprintf(buffer, 32, "%%"); break; default: buffer[0] = '%'; buffer[1] = format[i]; buffer[2] = '\0'; length = 2; break; } smart_str_appendl(&string, buffer, length); have_format_spec = 0; } else { if (format[i] == '%') { have_format_spec = 1; } else { smart_str_appendc(&string, format[i]); } } } smart_str_0(&string); return string.c; } /* }}} */ /* {{{ proto string date_interval_format(DateInterval object, string format) Formats the interval. */ PHP_FUNCTION(date_interval_format) { zval *object; php_interval_obj *diobj; char *format; int format_len; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, date_ce_interval, &format, &format_len) == FAILURE) { RETURN_FALSE; } diobj = (php_interval_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(diobj->initialized, DateInterval); RETURN_STRING(date_interval_format(format, format_len, diobj->diff), 0); } /* }}} */ static int date_period_initialize(timelib_time **st, timelib_time **et, timelib_rel_time **d, long *recurrences, /*const*/ char *format, int format_length TSRMLS_DC) { timelib_time *b = NULL, *e = NULL; timelib_rel_time *p = NULL; int r = 0; int retval = 0; struct timelib_error_container *errors; timelib_strtointerval(format, format_length, &b, &e, &p, &r, &errors); if (errors->error_count > 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown or bad format (%s)", format); retval = FAILURE; } else { *st = b; *et = e; *d = p; *recurrences = r; retval = SUCCESS; } timelib_error_container_dtor(errors); return retval; } /* {{{ proto DatePeriod::__construct(DateTime $start, DateInterval $interval, int recurrences|DateTime $end) Creates new DatePeriod object. */ PHP_METHOD(DatePeriod, __construct) { php_period_obj *dpobj; php_date_obj *dateobj; php_interval_obj *intobj; zval *start, *end = NULL, *interval; long recurrences = 0, options = 0; char *isostr = NULL; int isostr_len = 0; timelib_time *clone; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "OOl|l", &start, date_ce_date, &interval, date_ce_interval, &recurrences, &options) == FAILURE) { if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "OOO|l", &start, date_ce_date, &interval, date_ce_interval, &end, date_ce_date, &options) == FAILURE) { if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &isostr, &isostr_len, &options) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "This constructor accepts either (DateTime, DateInterval, int) OR (DateTime, DateInterval, DateTime) OR (string) as arguments."); zend_restore_error_handling(&error_handling TSRMLS_CC); return; } } } dpobj = zend_object_store_get_object(getThis() TSRMLS_CC); dpobj->current = NULL; if (isostr) { date_period_initialize(&(dpobj->start), &(dpobj->end), &(dpobj->interval), &recurrences, isostr, isostr_len TSRMLS_CC); if (dpobj->start == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The ISO interval '%s' did not contain a start date.", isostr); } if (dpobj->interval == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The ISO interval '%s' did not contain an interval.", isostr); } if (dpobj->end == NULL && recurrences == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The ISO interval '%s' did not contain an end date or a recurrence count.", isostr); } if (dpobj->start) { timelib_update_ts(dpobj->start, NULL); } if (dpobj->end) { timelib_update_ts(dpobj->end, NULL); } } else { /* init */ intobj = (php_interval_obj *) zend_object_store_get_object(interval TSRMLS_CC); /* start date */ dateobj = (php_date_obj *) zend_object_store_get_object(start TSRMLS_CC); clone = timelib_time_ctor(); memcpy(clone, dateobj->time, sizeof(timelib_time)); if (dateobj->time->tz_abbr) { clone->tz_abbr = strdup(dateobj->time->tz_abbr); } if (dateobj->time->tz_info) { clone->tz_info = dateobj->time->tz_info; } dpobj->start = clone; /* interval */ dpobj->interval = timelib_rel_time_clone(intobj->diff); /* end date */ if (end) { dateobj = (php_date_obj *) zend_object_store_get_object(end TSRMLS_CC); clone = timelib_time_clone(dateobj->time); dpobj->end = clone; } } /* options */ dpobj->include_start_date = !(options & PHP_DATE_PERIOD_EXCLUDE_START_DATE); /* recurrrences */ dpobj->recurrences = recurrences + dpobj->include_start_date; dpobj->initialized = 1; zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ static int check_id_allowed(char *id, long what) { if (what & PHP_DATE_TIMEZONE_GROUP_AFRICA && strncasecmp(id, "Africa/", 7) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_AMERICA && strncasecmp(id, "America/", 8) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_ANTARCTICA && strncasecmp(id, "Antarctica/", 11) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_ARCTIC && strncasecmp(id, "Arctic/", 7) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_ASIA && strncasecmp(id, "Asia/", 5) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_ATLANTIC && strncasecmp(id, "Atlantic/", 9) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_AUSTRALIA && strncasecmp(id, "Australia/", 10) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_EUROPE && strncasecmp(id, "Europe/", 7) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_INDIAN && strncasecmp(id, "Indian/", 7) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_PACIFIC && strncasecmp(id, "Pacific/", 8) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_UTC && strncasecmp(id, "UTC", 3) == 0) return 1; return 0; } /* {{{ proto array timezone_identifiers_list([long what[, string country]]) Returns numerically index array with all timezone identifiers. */ PHP_FUNCTION(timezone_identifiers_list) { const timelib_tzdb *tzdb; const timelib_tzdb_index_entry *table; int i, item_count; long what = PHP_DATE_TIMEZONE_GROUP_ALL; char *option = NULL; int option_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|ls", &what, &option, &option_len) == FAILURE) { RETURN_FALSE; } /* Extra validation */ if (what == PHP_DATE_TIMEZONE_PER_COUNTRY && option_len != 2) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "A two-letter ISO 3166-1 compatible country code is expected"); RETURN_FALSE; } tzdb = DATE_TIMEZONEDB; item_count = tzdb->index_size; table = tzdb->index; array_init(return_value); for (i = 0; i < item_count; ++i) { if (what == PHP_DATE_TIMEZONE_PER_COUNTRY) { if (tzdb->data[table[i].pos + 5] == option[0] && tzdb->data[table[i].pos + 6] == option[1]) { add_next_index_string(return_value, table[i].id, 1); } } else if (what == PHP_DATE_TIMEZONE_GROUP_ALL_W_BC || (check_id_allowed(table[i].id, what) && (tzdb->data[table[i].pos + 4] == '\1'))) { add_next_index_string(return_value, table[i].id, 1); } }; } /* }}} */ /* {{{ proto array timezone_version_get() Returns the Olson database version number. */ PHP_FUNCTION(timezone_version_get) { const timelib_tzdb *tzdb; tzdb = DATE_TIMEZONEDB; RETURN_STRING(tzdb->version, 1); } /* }}} */ /* {{{ proto array timezone_abbreviations_list() Returns associative array containing dst, offset and the timezone name */ PHP_FUNCTION(timezone_abbreviations_list) { const timelib_tz_lookup_table *table, *entry; zval *element, **abbr_array_pp, *abbr_array; table = timelib_timezone_abbreviations_list(); array_init(return_value); entry = table; do { MAKE_STD_ZVAL(element); array_init(element); add_assoc_bool(element, "dst", entry->type); add_assoc_long(element, "offset", entry->gmtoffset); if (entry->full_tz_name) { add_assoc_string(element, "timezone_id", entry->full_tz_name, 1); } else { add_assoc_null(element, "timezone_id"); } if (zend_hash_find(HASH_OF(return_value), entry->name, strlen(entry->name) + 1, (void **) &abbr_array_pp) == FAILURE) { MAKE_STD_ZVAL(abbr_array); array_init(abbr_array); add_assoc_zval(return_value, entry->name, abbr_array); } else { abbr_array = *abbr_array_pp; } add_next_index_zval(abbr_array, element); entry++; } while (entry->name); } /* }}} */ /* {{{ proto bool date_default_timezone_set(string timezone_identifier) Sets the default timezone used by all date/time functions in a script */ PHP_FUNCTION(date_default_timezone_set) { char *zone; int zone_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &zone, &zone_len) == FAILURE) { RETURN_FALSE; } if (!timelib_timezone_id_is_valid(zone, DATE_TIMEZONEDB)) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Timezone ID '%s' is invalid", zone); RETURN_FALSE; } if (DATEG(timezone)) { efree(DATEG(timezone)); DATEG(timezone) = NULL; } DATEG(timezone) = estrndup(zone, zone_len); RETURN_TRUE; } /* }}} */ /* {{{ proto string date_default_timezone_get() Gets the default timezone used by all date/time functions in a script */ PHP_FUNCTION(date_default_timezone_get) { timelib_tzinfo *default_tz; default_tz = get_timezone_info(TSRMLS_C); RETVAL_STRING(default_tz->name, 1); } /* }}} */ /* {{{ php_do_date_sunrise_sunset * Common for date_sunrise() and date_sunset() functions */ static void php_do_date_sunrise_sunset(INTERNAL_FUNCTION_PARAMETERS, int calc_sunset) { double latitude = 0.0, longitude = 0.0, zenith = 0.0, gmt_offset = 0, altitude; double h_rise, h_set, N; timelib_sll rise, set, transit; long time, retformat = 0; int rs; timelib_time *t; timelib_tzinfo *tzi; char *retstr; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|ldddd", &time, &retformat, &latitude, &longitude, &zenith, &gmt_offset) == FAILURE) { RETURN_FALSE; } switch (ZEND_NUM_ARGS()) { case 1: retformat = SUNFUNCS_RET_STRING; case 2: latitude = INI_FLT("date.default_latitude"); case 3: longitude = INI_FLT("date.default_longitude"); case 4: if (calc_sunset) { zenith = INI_FLT("date.sunset_zenith"); } else { zenith = INI_FLT("date.sunrise_zenith"); } case 5: case 6: break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "invalid format"); RETURN_FALSE; break; } if (retformat != SUNFUNCS_RET_TIMESTAMP && retformat != SUNFUNCS_RET_STRING && retformat != SUNFUNCS_RET_DOUBLE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Wrong return format given, pick one of SUNFUNCS_RET_TIMESTAMP, SUNFUNCS_RET_STRING or SUNFUNCS_RET_DOUBLE"); RETURN_FALSE; } altitude = 90 - zenith; /* Initialize time struct */ t = timelib_time_ctor(); tzi = get_timezone_info(TSRMLS_C); t->tz_info = tzi; t->zone_type = TIMELIB_ZONETYPE_ID; if (ZEND_NUM_ARGS() <= 5) { gmt_offset = timelib_get_current_offset(t) / 3600; } timelib_unixtime2local(t, time); rs = timelib_astro_rise_set_altitude(t, longitude, latitude, altitude, 1, &h_rise, &h_set, &rise, &set, &transit); timelib_time_dtor(t); if (rs != 0) { RETURN_FALSE; } if (retformat == SUNFUNCS_RET_TIMESTAMP) { RETURN_LONG(calc_sunset ? set : rise); } N = (calc_sunset ? h_set : h_rise) + gmt_offset; if (N > 24 || N < 0) { N -= floor(N / 24) * 24; } switch (retformat) { case SUNFUNCS_RET_STRING: spprintf(&retstr, 0, "%02d:%02d", (int) N, (int) (60 * (N - (int) N))); RETURN_STRINGL(retstr, 5, 0); break; case SUNFUNCS_RET_DOUBLE: RETURN_DOUBLE(N); break; } } /* }}} */ /* {{{ proto mixed date_sunrise(mixed time [, int format [, float latitude [, float longitude [, float zenith [, float gmt_offset]]]]]) Returns time of sunrise for a given day and location */ PHP_FUNCTION(date_sunrise) { php_do_date_sunrise_sunset(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto mixed date_sunset(mixed time [, int format [, float latitude [, float longitude [, float zenith [, float gmt_offset]]]]]) Returns time of sunset for a given day and location */ PHP_FUNCTION(date_sunset) { php_do_date_sunrise_sunset(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto array date_sun_info(long time, float latitude, float longitude) Returns an array with information about sun set/rise and twilight begin/end */ PHP_FUNCTION(date_sun_info) { long time; double latitude, longitude; timelib_time *t, *t2; timelib_tzinfo *tzi; int rs; timelib_sll rise, set, transit; int dummy; double ddummy; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ldd", &time, &latitude, &longitude) == FAILURE) { RETURN_FALSE; } /* Initialize time struct */ t = timelib_time_ctor(); tzi = get_timezone_info(TSRMLS_C); t->tz_info = tzi; t->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(t, time); /* Setup */ t2 = timelib_time_ctor(); array_init(return_value); /* Get sun up/down and transit */ rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -35.0/60, 1, &ddummy, &ddummy, &rise, &set, &transit); switch (rs) { case -1: /* always below */ add_assoc_bool(return_value, "sunrise", 0); add_assoc_bool(return_value, "sunset", 0); break; case 1: /* always above */ add_assoc_bool(return_value, "sunrise", 1); add_assoc_bool(return_value, "sunset", 1); break; default: t2->sse = rise; add_assoc_long(return_value, "sunrise", timelib_date_to_int(t2, &dummy)); t2->sse = set; add_assoc_long(return_value, "sunset", timelib_date_to_int(t2, &dummy)); } t2->sse = transit; add_assoc_long(return_value, "transit", timelib_date_to_int(t2, &dummy)); /* Get civil twilight */ rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -6.0, 0, &ddummy, &ddummy, &rise, &set, &transit); switch (rs) { case -1: /* always below */ add_assoc_bool(return_value, "civil_twilight_begin", 0); add_assoc_bool(return_value, "civil_twilight_end", 0); break; case 1: /* always above */ add_assoc_bool(return_value, "civil_twilight_begin", 1); add_assoc_bool(return_value, "civil_twilight_end", 1); break; default: t2->sse = rise; add_assoc_long(return_value, "civil_twilight_begin", timelib_date_to_int(t2, &dummy)); t2->sse = set; add_assoc_long(return_value, "civil_twilight_end", timelib_date_to_int(t2, &dummy)); } /* Get nautical twilight */ rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -12.0, 0, &ddummy, &ddummy, &rise, &set, &transit); switch (rs) { case -1: /* always below */ add_assoc_bool(return_value, "nautical_twilight_begin", 0); add_assoc_bool(return_value, "nautical_twilight_end", 0); break; case 1: /* always above */ add_assoc_bool(return_value, "nautical_twilight_begin", 1); add_assoc_bool(return_value, "nautical_twilight_end", 1); break; default: t2->sse = rise; add_assoc_long(return_value, "nautical_twilight_begin", timelib_date_to_int(t2, &dummy)); t2->sse = set; add_assoc_long(return_value, "nautical_twilight_end", timelib_date_to_int(t2, &dummy)); } /* Get astronomical twilight */ rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -18.0, 0, &ddummy, &ddummy, &rise, &set, &transit); switch (rs) { case -1: /* always below */ add_assoc_bool(return_value, "astronomical_twilight_begin", 0); add_assoc_bool(return_value, "astronomical_twilight_end", 0); break; case 1: /* always above */ add_assoc_bool(return_value, "astronomical_twilight_begin", 1); add_assoc_bool(return_value, "astronomical_twilight_end", 1); break; default: t2->sse = rise; add_assoc_long(return_value, "astronomical_twilight_begin", timelib_date_to_int(t2, &dummy)); t2->sse = set; add_assoc_long(return_value, "astronomical_twilight_end", timelib_date_to_int(t2, &dummy)); } timelib_time_dtor(t); timelib_time_dtor(t2); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: fdm=marker * vim: noet sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-03-23-63673a533f-2adf58cfcf.c
manybugs_data_23
/* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ #include "tif_config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef HAVE_STRINGS_H # include <strings.h> #endif #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #ifdef NEED_LIBPORT # include "libport.h" #endif #include "tiffiop.h" static TIFFErrorHandler old_error_handler = 0; static int status = 0; /* exit status */ static int showdata = 0; /* show data */ static int rawdata = 0; /* show raw/decoded data */ static int showwords = 0; /* show data as bytes/words */ static int readdata = 0; /* read data in file */ static int stoponerr = 1; /* stop on first read error */ static void usage(void); static void tiffinfo(TIFF*, uint16, long); static void PrivateErrorHandler(const char* module, const char* fmt, va_list ap) { if (old_error_handler) (*old_error_handler)(module,fmt,ap); status = 1; } int main(int argc, char* argv[]) { int dirnum = -1, multiplefiles, c; uint16 order = 0; TIFF* tif; extern int optind; extern char* optarg; long flags = 0; uint64 diroff = 0; int chopstrips = 0; /* disable strip chopping */ while ((c = getopt(argc, argv, "f:o:cdDSjilmrsvwz0123456789")) != -1) switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': dirnum = atoi(&argv[optind-1][1]); break; case 'd': showdata++; /* fall thru... */ case 'D': readdata++; break; case 'c': flags |= TIFFPRINT_COLORMAP | TIFFPRINT_CURVES; break; case 'f': /* fill order */ if (streq(optarg, "lsb2msb")) order = FILLORDER_LSB2MSB; else if (streq(optarg, "msb2lsb")) order = FILLORDER_MSB2LSB; else usage(); break; case 'i': stoponerr = 0; break; case 'o': diroff = strtoul(optarg, NULL, 0); break; case 'j': flags |= TIFFPRINT_JPEGQTABLES | TIFFPRINT_JPEGACTABLES | TIFFPRINT_JPEGDCTABLES; break; case 'r': rawdata = 1; break; case 's': flags |= TIFFPRINT_STRIPS; break; case 'w': showwords = 1; break; case 'z': chopstrips = 1; break; case '?': usage(); /*NOTREACHED*/ } if (optind >= argc) usage(); old_error_handler = _TIFFerrorHandler; (void) TIFFSetErrorHandler(PrivateErrorHandler); multiplefiles = (argc - optind > 1); for (; optind < argc; optind++) { if (multiplefiles) printf("%s:\n", argv[optind]); tif = TIFFOpen(argv[optind], chopstrips ? "rC" : "rc"); if (tif != NULL) { if (dirnum != -1) { if (TIFFSetDirectory(tif, (tdir_t) dirnum)) tiffinfo(tif, order, flags); } else if (diroff != 0) { if (TIFFSetSubDirectory(tif, diroff)) tiffinfo(tif, order, flags); } else { do { toff_t offset; tiffinfo(tif, order, flags); if (TIFFGetField(tif, TIFFTAG_EXIFIFD, &offset)) { if (TIFFReadEXIFDirectory(tif, offset)) tiffinfo(tif, order, flags); } } while (TIFFReadDirectory(tif)); } TIFFClose(tif); } } return (status); } char* stuff[] = { "usage: tiffinfo [options] input...", "where options are:", " -D read data", " -i ignore read errors", " -c display data for grey/color response curve or colormap", " -d display raw/decoded image data", " -f lsb2msb force lsb-to-msb FillOrder for input", " -f msb2lsb force msb-to-lsb FillOrder for input", " -j show JPEG tables", " -o offset set initial directory offset", " -r read/display raw image data instead of decoded data", " -s display strip offsets and byte counts", " -w display raw data in words rather than bytes", " -z enable strip chopping", " -# set initial directory (first directory is # 0)", NULL }; static void usage(void) { char buf[BUFSIZ]; int i; setbuf(stderr, buf); fprintf(stderr, "%s\n\n", TIFFGetVersion()); for (i = 0; stuff[i] != NULL; i++) fprintf(stderr, "%s\n", stuff[i]); exit(-1); } static void ShowStrip(tstrip_t strip, unsigned char* pp, uint32 nrow, tsize_t scanline) { register tsize_t cc; printf("Strip %lu:\n", (unsigned long) strip); while (nrow-- > 0) { for (cc = 0; cc < scanline; cc++) { printf(" %02x", *pp++); if (((cc+1) % 24) == 0) putchar('\n'); } putchar('\n'); } } void TIFFReadContigStripData(TIFF* tif) { unsigned char *buf; tsize_t scanline = TIFFScanlineSize(tif); buf = (unsigned char *)_TIFFmalloc(TIFFStripSize(tif)); if (buf) { uint32 row, h; uint32 rowsperstrip = (uint32)-1; TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h); TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); for (row = 0; row < h; row += rowsperstrip) { uint32 nrow = (row+rowsperstrip > h ? h-row : rowsperstrip); tstrip_t strip = TIFFComputeStrip(tif, row, 0); if (TIFFReadEncodedStrip(tif, strip, buf, nrow*scanline) < 0) { if (stoponerr) break; } else if (showdata) ShowStrip(strip, buf, nrow, scanline); } _TIFFfree(buf); } } void TIFFReadSeparateStripData(TIFF* tif) { unsigned char *buf; tsize_t scanline = TIFFScanlineSize(tif); buf = (unsigned char *)_TIFFmalloc(TIFFStripSize(tif)); if (buf) { uint32 row, h; uint32 rowsperstrip = (uint32)-1; tsample_t s, samplesperpixel; TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h); TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel); for (row = 0; row < h; row += rowsperstrip) { for (s = 0; s < samplesperpixel; s++) { uint32 nrow = (row+rowsperstrip > h ? h-row : rowsperstrip); tstrip_t strip = TIFFComputeStrip(tif, row, s); if (TIFFReadEncodedStrip(tif, strip, buf, nrow*scanline) < 0) { if (stoponerr) break; } else if (showdata) ShowStrip(strip, buf, nrow, scanline); } } _TIFFfree(buf); } } static void ShowTile(uint32 row, uint32 col, tsample_t sample, unsigned char* pp, uint32 nrow, tsize_t rowsize) { uint32 cc; printf("Tile (%lu,%lu", (unsigned long) row, (unsigned long) col); if (sample != (tsample_t) -1) printf(",%u", sample); printf("):\n"); while (nrow-- > 0) { for (cc = 0; cc < (uint32) rowsize; cc++) { printf(" %02x", *pp++); if (((cc+1) % 24) == 0) putchar('\n'); } putchar('\n'); } } void TIFFReadContigTileData(TIFF* tif) { unsigned char *buf; tsize_t rowsize = TIFFTileRowSize(tif); buf = (unsigned char *)_TIFFmalloc(TIFFTileSize(tif)); if (buf) { uint32 tw, th, w, h; uint32 row, col; TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w); TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h); TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(tif, TIFFTAG_TILELENGTH, &th); for (row = 0; row < h; row += th) { for (col = 0; col < w; col += tw) { if (TIFFReadTile(tif, buf, col, row, 0, 0) < 0) { if (stoponerr) break; } else if (showdata) ShowTile(row, col, (tsample_t) -1, buf, th, rowsize); } } _TIFFfree(buf); } } void TIFFReadSeparateTileData(TIFF* tif) { unsigned char *buf; tsize_t rowsize = TIFFTileRowSize(tif); buf = (unsigned char *)_TIFFmalloc(TIFFTileSize(tif)); if (buf) { uint32 tw, th, w, h; uint32 row, col; tsample_t s, samplesperpixel; TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w); TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h); TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(tif, TIFFTAG_TILELENGTH, &th); TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel); for (row = 0; row < h; row += th) { for (col = 0; col < w; col += tw) { for (s = 0; s < samplesperpixel; s++) { if (TIFFReadTile(tif, buf, col, row, 0, s) < 0) { if (stoponerr) break; } else if (showdata) ShowTile(row, col, s, buf, th, rowsize); } } } _TIFFfree(buf); } } void TIFFReadData(TIFF* tif) { uint16 config; TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &config); if (TIFFIsTiled(tif)) { if (config == PLANARCONFIG_CONTIG) TIFFReadContigTileData(tif); else TIFFReadSeparateTileData(tif); } else { if (config == PLANARCONFIG_CONTIG) TIFFReadContigStripData(tif); else TIFFReadSeparateStripData(tif); } } static void ShowRawBytes(unsigned char* pp, uint32 n) { uint32 i; for (i = 0; i < n; i++) { printf(" %02x", *pp++); if (((i+1) % 24) == 0) printf("\n "); } putchar('\n'); } static void ShowRawWords(uint16* pp, uint32 n) { uint32 i; for (i = 0; i < n; i++) { printf(" %04x", *pp++); if (((i+1) % 15) == 0) printf("\n "); } putchar('\n'); } void TIFFReadRawData(TIFF* tif, int bitrev) { tstrip_t nstrips = TIFFNumberOfStrips(tif); const char* what = TIFFIsTiled(tif) ? "Tile" : "Strip"; uint64* stripbc; TIFFGetField(tif, TIFFTAG_STRIPBYTECOUNTS, &stripbc); if (nstrips > 0) { uint32 bufsize = (uint32) stripbc[0]; tdata_t buf = _TIFFmalloc(bufsize); tstrip_t s; for (s = 0; s < nstrips; s++) { if (stripbc[s] > bufsize) { buf = _TIFFrealloc(buf, (tmsize_t)stripbc[s]); bufsize = (uint32) stripbc[s]; } if (buf == NULL) { fprintf(stderr, "Cannot allocate buffer to read strip %lu\n", (unsigned long) s); break; } if (TIFFReadRawStrip(tif, s, buf, (tmsize_t) stripbc[s]) < 0) { fprintf(stderr, "Error reading strip %lu\n", (unsigned long) s); if (stoponerr) break; } else if (showdata) { if (bitrev) { TIFFReverseBits(buf, (tmsize_t)stripbc[s]); printf("%s %lu: (bit reversed)\n ", what, (unsigned long) s); } else printf("%s %lu:\n ", what, (unsigned long) s); if (showwords) ShowRawWords((uint16*) buf, (uint32) stripbc[s]>>1); else ShowRawBytes((unsigned char*) buf, (uint32) stripbc[s]); } } if (buf != NULL) _TIFFfree(buf); } } static void tiffinfo(TIFF* tif, uint16 order, long flags) { TIFFPrintDirectory(tif, stdout, flags); if (!readdata) return; if (rawdata) { if (order) { uint16 o; TIFFGetFieldDefaulted(tif, TIFFTAG_FILLORDER, &o); TIFFReadRawData(tif, o != order); } else TIFFReadRawData(tif, 0); } else { if (order) TIFFSetField(tif, TIFFTAG_FILLORDER, order); TIFFReadData(tif); } } /* vim: set ts=8 sts=8 sw=8 noet: */ /* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ #include "tif_config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef HAVE_STRINGS_H # include <strings.h> #endif #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #ifdef NEED_LIBPORT # include "libport.h" #endif #include "tiffio.h" #define streq(a,b) (strcasecmp(a,b) == 0) int showdata = 0; /* show data */ int rawdata = 0; /* show raw/decoded data */ int showwords = 0; /* show data as bytes/words */ int readdata = 0; /* read data in file */ int stoponerr = 1; /* stop on first read error */ static void usage(void); static void tiffinfo(TIFF*, uint16, long); int main(int argc, char* argv[]) { int dirnum = -1, multiplefiles, c; uint16 order = 0; TIFF* tif; extern int optind; extern char* optarg; long flags = 0; uint64 diroff = 0; int chopstrips = 0; /* disable strip chopping */ while ((c = getopt(argc, argv, "f:o:cdDSjilmrsvwz0123456789")) != -1) switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': dirnum = atoi(&argv[optind-1][1]); break; case 'd': showdata++; /* fall thru... */ case 'D': readdata++; break; case 'c': flags |= TIFFPRINT_COLORMAP | TIFFPRINT_CURVES; break; case 'f': /* fill order */ if (streq(optarg, "lsb2msb")) order = FILLORDER_LSB2MSB; else if (streq(optarg, "msb2lsb")) order = FILLORDER_MSB2LSB; else usage(); break; case 'i': stoponerr = 0; break; case 'o': diroff = strtoul(optarg, NULL, 0); break; case 'j': flags |= TIFFPRINT_JPEGQTABLES | TIFFPRINT_JPEGACTABLES | TIFFPRINT_JPEGDCTABLES; break; case 'r': rawdata = 1; break; case 's': flags |= TIFFPRINT_STRIPS; break; case 'w': showwords = 1; break; case 'z': chopstrips = 1; break; case '?': usage(); /*NOTREACHED*/ } if (optind >= argc) usage(); multiplefiles = (argc - optind > 1); for (; optind < argc; optind++) { if (multiplefiles) printf("%s:\n", argv[optind]); tif = TIFFOpen(argv[optind], chopstrips ? "rC" : "rc"); if (tif != NULL) { if (dirnum != -1) { if (TIFFSetDirectory(tif, (tdir_t) dirnum)) tiffinfo(tif, order, flags); } else if (diroff != 0) { if (TIFFSetSubDirectory(tif, diroff)) tiffinfo(tif, order, flags); } else { do { toff_t offset; tiffinfo(tif, order, flags); if (TIFFGetField(tif, TIFFTAG_EXIFIFD, &offset)) { if (TIFFReadEXIFDirectory(tif, offset)) tiffinfo(tif, order, flags); } } while (TIFFReadDirectory(tif)); } TIFFClose(tif); } } return (0); } char* stuff[] = { "usage: tiffinfo [options] input...", "where options are:", " -D read data", " -i ignore read errors", " -c display data for grey/color response curve or colormap", " -d display raw/decoded image data", " -f lsb2msb force lsb-to-msb FillOrder for input", " -f msb2lsb force msb-to-lsb FillOrder for input", " -j show JPEG tables", " -o offset set initial directory offset", " -r read/display raw image data instead of decoded data", " -s display strip offsets and byte counts", " -w display raw data in words rather than bytes", " -z enable strip chopping", " -# set initial directory (first directory is # 0)", NULL }; static void usage(void) { char buf[BUFSIZ]; int i; setbuf(stderr, buf); fprintf(stderr, "%s\n\n", TIFFGetVersion()); for (i = 0; stuff[i] != NULL; i++) fprintf(stderr, "%s\n", stuff[i]); exit(-1); } static void ShowStrip(tstrip_t strip, unsigned char* pp, uint32 nrow, tsize_t scanline) { register tsize_t cc; printf("Strip %lu:\n", (unsigned long) strip); while (nrow-- > 0) { for (cc = 0; cc < scanline; cc++) { printf(" %02x", *pp++); if (((cc+1) % 24) == 0) putchar('\n'); } putchar('\n'); } } void TIFFReadContigStripData(TIFF* tif) { unsigned char *buf; tsize_t scanline = TIFFScanlineSize(tif); buf = (unsigned char *)_TIFFmalloc(TIFFStripSize(tif)); if (buf) { uint32 row, h; uint32 rowsperstrip = (uint32)-1; TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h); TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); for (row = 0; row < h; row += rowsperstrip) { uint32 nrow = (row+rowsperstrip > h ? h-row : rowsperstrip); tstrip_t strip = TIFFComputeStrip(tif, row, 0); if (TIFFReadEncodedStrip(tif, strip, buf, nrow*scanline) < 0) { if (stoponerr) break; } else if (showdata) ShowStrip(strip, buf, nrow, scanline); } _TIFFfree(buf); } } void TIFFReadSeparateStripData(TIFF* tif) { unsigned char *buf; tsize_t scanline = TIFFScanlineSize(tif); buf = (unsigned char *)_TIFFmalloc(TIFFStripSize(tif)); if (buf) { uint32 row, h; uint32 rowsperstrip = (uint32)-1; tsample_t s, samplesperpixel; TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h); TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel); for (row = 0; row < h; row += rowsperstrip) { for (s = 0; s < samplesperpixel; s++) { uint32 nrow = (row+rowsperstrip > h ? h-row : rowsperstrip); tstrip_t strip = TIFFComputeStrip(tif, row, s); if (TIFFReadEncodedStrip(tif, strip, buf, nrow*scanline) < 0) { if (stoponerr) break; } else if (showdata) ShowStrip(strip, buf, nrow, scanline); } } _TIFFfree(buf); } } static void ShowTile(uint32 row, uint32 col, tsample_t sample, unsigned char* pp, uint32 nrow, tsize_t rowsize) { uint32 cc; printf("Tile (%lu,%lu", (unsigned long) row, (unsigned long) col); if (sample != (tsample_t) -1) printf(",%u", sample); printf("):\n"); while (nrow-- > 0) { for (cc = 0; cc < (uint32) rowsize; cc++) { printf(" %02x", *pp++); if (((cc+1) % 24) == 0) putchar('\n'); } putchar('\n'); } } void TIFFReadContigTileData(TIFF* tif) { unsigned char *buf; tsize_t rowsize = TIFFTileRowSize(tif); buf = (unsigned char *)_TIFFmalloc(TIFFTileSize(tif)); if (buf) { uint32 tw, th, w, h; uint32 row, col; TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w); TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h); TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(tif, TIFFTAG_TILELENGTH, &th); for (row = 0; row < h; row += th) { for (col = 0; col < w; col += tw) { if (TIFFReadTile(tif, buf, col, row, 0, 0) < 0) { if (stoponerr) break; } else if (showdata) ShowTile(row, col, (tsample_t) -1, buf, th, rowsize); } } _TIFFfree(buf); } } void TIFFReadSeparateTileData(TIFF* tif) { unsigned char *buf; tsize_t rowsize = TIFFTileRowSize(tif); buf = (unsigned char *)_TIFFmalloc(TIFFTileSize(tif)); if (buf) { uint32 tw, th, w, h; uint32 row, col; tsample_t s, samplesperpixel; TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w); TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h); TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(tif, TIFFTAG_TILELENGTH, &th); TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel); for (row = 0; row < h; row += th) { for (col = 0; col < w; col += tw) { for (s = 0; s < samplesperpixel; s++) { if (TIFFReadTile(tif, buf, col, row, 0, s) < 0) { if (stoponerr) break; } else if (showdata) ShowTile(row, col, s, buf, th, rowsize); } } } _TIFFfree(buf); } } void TIFFReadData(TIFF* tif) { uint16 config; TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &config); if (TIFFIsTiled(tif)) { if (config == PLANARCONFIG_CONTIG) TIFFReadContigTileData(tif); else TIFFReadSeparateTileData(tif); } else { if (config == PLANARCONFIG_CONTIG) TIFFReadContigStripData(tif); else TIFFReadSeparateStripData(tif); } } static void ShowRawBytes(unsigned char* pp, uint32 n) { uint32 i; for (i = 0; i < n; i++) { printf(" %02x", *pp++); if (((i+1) % 24) == 0) printf("\n "); } putchar('\n'); } static void ShowRawWords(uint16* pp, uint32 n) { uint32 i; for (i = 0; i < n; i++) { printf(" %04x", *pp++); if (((i+1) % 15) == 0) printf("\n "); } putchar('\n'); } void TIFFReadRawData(TIFF* tif, int bitrev) { tstrip_t nstrips = TIFFNumberOfStrips(tif); const char* what = TIFFIsTiled(tif) ? "Tile" : "Strip"; uint64* stripbc; TIFFGetField(tif, TIFFTAG_STRIPBYTECOUNTS, &stripbc); if (nstrips > 0) { uint32 bufsize = (uint32) stripbc[0]; tdata_t buf = _TIFFmalloc(bufsize); tstrip_t s; for (s = 0; s < nstrips; s++) { if (stripbc[s] > bufsize) { buf = _TIFFrealloc(buf, (tmsize_t)stripbc[s]); bufsize = (uint32) stripbc[s]; } if (buf == NULL) { fprintf(stderr, "Cannot allocate buffer to read strip %lu\n", (unsigned long) s); break; } if (TIFFReadRawStrip(tif, s, buf, (tmsize_t) stripbc[s]) < 0) { fprintf(stderr, "Error reading strip %lu\n", (unsigned long) s); if (stoponerr) break; } else if (showdata) { if (bitrev) { TIFFReverseBits(buf, (tmsize_t)stripbc[s]); printf("%s %lu: (bit reversed)\n ", what, (unsigned long) s); } else printf("%s %lu:\n ", what, (unsigned long) s); if (showwords) ShowRawWords((uint16*) buf, (uint32) stripbc[s]>>1); else ShowRawBytes((unsigned char*) buf, (uint32) stripbc[s]); } } if (buf != NULL) _TIFFfree(buf); } } static void tiffinfo(TIFF* tif, uint16 order, long flags) { TIFFPrintDirectory(tif, stdout, flags); if (!readdata) return; if (rawdata) { if (order) { uint16 o; TIFFGetFieldDefaulted(tif, TIFFTAG_FILLORDER, &o); TIFFReadRawData(tif, o != order); } else TIFFReadRawData(tif, 0); } else { if (order) TIFFSetField(tif, TIFFTAG_FILLORDER, order); TIFFReadData(tif); } } /* vim: set ts=8 sts=8 sw=8 noet: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/libtiff_2009-08-28-e8a47d4-023b6df.c
manybugs_data_24
/* gzip (GNU zip) -- compress files with zip algorithm and 'compress' interface Copyright (C) 1999, 2001-2002, 2006-2007, 2009 Free Software Foundation, Inc. Copyright (C) 1992-1993 Jean-loup Gailly This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * The unzip code was written and put in the public domain by Mark Adler. * Portions of the lzw code are derived from the public domain 'compress' * written by Spencer Thomas, Joe Orost, James Woods, Jim McKie, Steve Davies, * Ken Turkowski, Dave Mack and Peter Jannesen. * * See the license_msg below and the file COPYING for the software license. * See the file algorithm.doc for the compression algorithms and file formats. */ static char *license_msg[] = { "Copyright (C) 2007 Free Software Foundation, Inc.", "Copyright (C) 1993 Jean-loup Gailly.", "This is free software. You may redistribute copies of it under the terms of", "the GNU General Public License <http://www.gnu.org/licenses/gpl.html>.", "There is NO WARRANTY, to the extent permitted by law.", 0}; /* Compress files with zip algorithm and 'compress' interface. * See help() function below for all options. * Outputs: * file.gz: compressed file with same mode, owner, and utimes * or stdout with -c option or if stdin used as input. * If the output file name had to be truncated, the original name is kept * in the compressed file. * On MSDOS, file.tmp -> file.tmz. On VMS, file.tmp -> file.tmp-gz. * * Using gz on MSDOS would create too many file name conflicts. For * example, foo.txt -> foo.tgz (.tgz must be reserved as shorthand for * tar.gz). Similarly, foo.dir and foo.doc would both be mapped to foo.dgz. * I also considered 12345678.txt -> 12345txt.gz but this truncates the name * too heavily. There is no ideal solution given the MSDOS 8+3 limitation. * * For the meaning of all compilation flags, see comments in Makefile.in. */ #include <config.h> #include <ctype.h> #include <sys/types.h> #include <signal.h> #include <sys/stat.h> #include <errno.h> #include "closein.h" #include "tailor.h" #include "gzip.h" #include "lzw.h" #include "revision.h" #include "fcntl-safer.h" #include "getopt.h" #include "stat-time.h" /* configuration */ #ifdef HAVE_FCNTL_H # include <fcntl.h> #endif #ifdef HAVE_LIMITS_H # include <limits.h> #endif #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #if defined STDC_HEADERS || defined HAVE_STDLIB_H # include <stdlib.h> #else extern int errno; #endif #ifndef NO_DIR # define NO_DIR 0 #endif #if !NO_DIR # include <dirent.h> # ifndef _D_EXACT_NAMLEN # define _D_EXACT_NAMLEN(dp) strlen ((dp)->d_name) # endif #endif #ifdef CLOSEDIR_VOID # define CLOSEDIR(d) (closedir(d), 0) #else # define CLOSEDIR(d) closedir(d) #endif #ifndef NO_UTIME # include <utimens.h> #endif #define RW_USER (S_IRUSR | S_IWUSR) /* creation mode for open() */ #ifndef MAX_PATH_LEN # define MAX_PATH_LEN 1024 /* max pathname length */ #endif #ifndef SEEK_END # define SEEK_END 2 #endif #ifndef CHAR_BIT # define CHAR_BIT 8 #endif #ifdef off_t off_t lseek OF((int fd, off_t offset, int whence)); #endif #ifndef OFF_T_MIN #define OFF_T_MIN (~ (off_t) 0 << (sizeof (off_t) * CHAR_BIT - 1)) #endif #ifndef OFF_T_MAX #define OFF_T_MAX (~ (off_t) 0 - OFF_T_MIN) #endif /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is present. */ #ifndef SA_NOCLDSTOP # define SA_NOCLDSTOP 0 # define sigprocmask(how, set, oset) /* empty */ # define sigset_t int # if ! HAVE_SIGINTERRUPT # define siginterrupt(sig, flag) /* empty */ # endif #endif #ifndef HAVE_WORKING_O_NOFOLLOW # define HAVE_WORKING_O_NOFOLLOW 0 #endif #ifndef ELOOP # define ELOOP EINVAL #endif /* Separator for file name parts (see shorten_name()) */ #ifdef NO_MULTIPLE_DOTS # define PART_SEP "-" #else # define PART_SEP "." #endif /* global buffers */ DECLARE(uch, inbuf, INBUFSIZ +INBUF_EXTRA); DECLARE(uch, outbuf, OUTBUFSIZ+OUTBUF_EXTRA); DECLARE(ush, d_buf, DIST_BUFSIZE); DECLARE(uch, window, 2L*WSIZE); #ifndef MAXSEG_64K DECLARE(ush, tab_prefix, 1L<<BITS); #else DECLARE(ush, tab_prefix0, 1L<<(BITS-1)); DECLARE(ush, tab_prefix1, 1L<<(BITS-1)); #endif /* local variables */ int ascii = 0; /* convert end-of-lines to local OS conventions */ int to_stdout = 0; /* output to stdout (-c) */ int decompress = 0; /* decompress (-d) */ int force = 0; /* don't ask questions, compress links (-f) */ int no_name = -1; /* don't save or restore the original file name */ int no_time = -1; /* don't save or restore the original file time */ int recursive = 0; /* recurse through directories (-r) */ int list = 0; /* list the file contents (-l) */ int verbose = 0; /* be verbose (-v) */ int quiet = 0; /* be very quiet (-q) */ int do_lzw = 0; /* generate output compatible with old compress (-Z) */ int test = 0; /* test .gz file integrity */ int foreground = 0; /* set if program run in foreground */ char *program_name; /* program name */ int maxbits = BITS; /* max bits per code for LZW */ int method = DEFLATED;/* compression method */ int level = 6; /* compression level */ int exit_code = OK; /* program exit code */ int save_orig_name; /* set if original name must be saved */ int last_member; /* set for .zip and .Z files */ int part_nb; /* number of parts in .gz file */ struct timespec time_stamp; /* original time stamp (modification time) */ off_t ifile_size; /* input file size, -1 for devices (debug only) */ char *env; /* contents of GZIP env variable */ char **args = NULL; /* argv pointer if GZIP env variable defined */ char *z_suffix; /* default suffix (can be set with --suffix) */ size_t z_len; /* strlen(z_suffix) */ /* The set of signals that are caught. */ static sigset_t caught_signals; /* If nonzero then exit with status WARNING, rather than with the usual signal status, on receipt of a signal with this value. This suppresses a "Broken Pipe" message with some shells. */ static int volatile exiting_signal; /* If nonnegative, close this file descriptor and unlink ofname on error. */ static int volatile remove_ofname_fd = -1; off_t bytes_in; /* number of input bytes */ off_t bytes_out; /* number of output bytes */ off_t total_in; /* input bytes for all files */ off_t total_out; /* output bytes for all files */ char ifname[MAX_PATH_LEN]; /* input file name */ char ofname[MAX_PATH_LEN]; /* output file name */ struct stat istat; /* status for input file */ int ifd; /* input file descriptor */ int ofd; /* output file descriptor */ unsigned insize; /* valid bytes in inbuf */ unsigned inptr; /* index of next byte to be processed in inbuf */ unsigned outcnt; /* bytes in output buffer */ static int handled_sig[] = { /* SIGINT must be first, as 'foreground' depends on it. */ SIGINT #ifdef SIGHUP , SIGHUP #endif #ifdef SIGPIPE , SIGPIPE #else # define SIGPIPE 0 #endif #ifdef SIGTERM , SIGTERM #endif #ifdef SIGXCPU , SIGXCPU #endif #ifdef SIGXFSZ , SIGXFSZ #endif }; struct option longopts[] = { /* { name has_arg *flag val } */ {"ascii", 0, 0, 'a'}, /* ascii text mode */ {"to-stdout", 0, 0, 'c'}, /* write output on standard output */ {"stdout", 0, 0, 'c'}, /* write output on standard output */ {"decompress", 0, 0, 'd'}, /* decompress */ {"uncompress", 0, 0, 'd'}, /* decompress */ /* {"encrypt", 0, 0, 'e'}, encrypt */ {"force", 0, 0, 'f'}, /* force overwrite of output file */ {"help", 0, 0, 'h'}, /* give help */ /* {"pkzip", 0, 0, 'k'}, force output in pkzip format */ {"list", 0, 0, 'l'}, /* list .gz file contents */ {"license", 0, 0, 'L'}, /* display software license */ {"no-name", 0, 0, 'n'}, /* don't save or restore original name & time */ {"name", 0, 0, 'N'}, /* save or restore original name & time */ {"quiet", 0, 0, 'q'}, /* quiet mode */ {"silent", 0, 0, 'q'}, /* quiet mode */ {"recursive", 0, 0, 'r'}, /* recurse through directories */ {"suffix", 1, 0, 'S'}, /* use given suffix instead of .gz */ {"test", 0, 0, 't'}, /* test compressed file integrity */ {"no-time", 0, 0, 'T'}, /* don't save or restore the time stamp */ {"verbose", 0, 0, 'v'}, /* verbose mode */ {"version", 0, 0, 'V'}, /* display version number */ {"fast", 0, 0, '1'}, /* compress faster */ {"best", 0, 0, '9'}, /* compress better */ {"lzw", 0, 0, 'Z'}, /* make output compatible with old compress */ {"bits", 1, 0, 'b'}, /* max number of bits per code (implies -Z) */ { 0, 0, 0, 0 } }; /* local functions */ local void try_help OF((void)) ATTRIBUTE_NORETURN; local void help OF((void)); local void license OF((void)); local void version OF((void)); local int input_eof OF((void)); local void treat_stdin OF((void)); local void treat_file OF((char *iname)); local int create_outfile OF((void)); local char *get_suffix OF((char *name)); local int open_input_file OF((char *iname, struct stat *sbuf)); local int make_ofname OF((void)); local void shorten_name OF((char *name)); local int get_method OF((int in)); local void do_list OF((int ifd, int method)); local int check_ofname OF((void)); local void copy_stat OF((struct stat *ifstat)); local void install_signal_handlers OF((void)); local void remove_output_file OF((void)); local RETSIGTYPE abort_gzip_signal OF((int)); local void do_exit OF((int exitcode)) ATTRIBUTE_NORETURN; int main OF((int argc, char **argv)); int (*work) OF((int infile, int outfile)) = zip; /* function to call */ #if ! NO_DIR local void treat_dir OF((int fd, char *dir)); #endif #define strequ(s1, s2) (strcmp((s1),(s2)) == 0) static void try_help () { fprintf (stderr, "Try `%s --help' for more information.\n", program_name); do_exit (ERROR); } /* ======================================================================== */ local void help() { static char *help_msg[] = { "Compress or uncompress FILEs (by default, compress FILES in-place).", "", "Mandatory arguments to long options are mandatory for short options too.", "", #if O_BINARY " -a, --ascii ascii text; convert end-of-line using local conventions", #endif " -c, --stdout write on standard output, keep original files unchanged", " -d, --decompress decompress", /* -e, --encrypt encrypt */ " -f, --force force overwrite of output file and compress links", " -h, --help give this help", /* -k, --pkzip force output in pkzip format */ " -l, --list list compressed file contents", " -L, --license display software license", #ifdef UNDOCUMENTED " -m, --no-time do not save or restore the original modification time", " -M, --time save or restore the original modification time", #endif " -n, --no-name do not save or restore the original name and time stamp", " -N, --name save or restore the original name and time stamp", " -q, --quiet suppress all warnings", #if ! NO_DIR " -r, --recursive operate recursively on directories", #endif " -S, --suffix=SUF use suffix SUF on compressed files", " -t, --test test compressed file integrity", " -v, --verbose verbose mode", " -V, --version display version number", " -1, --fast compress faster", " -9, --best compress better", #ifdef LZW " -Z, --lzw produce output compatible with old compress", " -b, --bits=BITS max number of bits per code (implies -Z)", #endif "", "With no FILE, or when FILE is -, read standard input.", "", "Report bugs to <[email protected]>.", 0}; char **p = help_msg; printf ("Usage: %s [OPTION]... [FILE]...\n", program_name); while (*p) printf ("%s\n", *p++); } /* ======================================================================== */ local void license() { char **p = license_msg; printf ("%s %s\n", program_name, VERSION); while (*p) printf ("%s\n", *p++); } /* ======================================================================== */ local void version() { license (); printf ("\n"); printf ("Written by Jean-loup Gailly.\n"); } local void progerror (string) char *string; { int e = errno; fprintf (stderr, "%s: ", program_name); errno = e; perror(string); exit_code = ERROR; } /* ======================================================================== */ int main (argc, argv) int argc; char **argv; { int file_count; /* number of files to process */ size_t proglen; /* length of program_name */ int optc; /* current option */ EXPAND(argc, argv); /* wild card expansion if necessary */ program_name = gzip_base_name (argv[0]); proglen = strlen (program_name); atexit (close_stdin); /* Suppress .exe for MSDOS, OS/2 and VMS: */ if (4 < proglen && strequ (program_name + proglen - 4, ".exe")) program_name[proglen - 4] = '\0'; /* Add options in GZIP environment variable if there is one */ env = add_envopt(&argc, &argv, OPTIONS_VAR); if (env != NULL) args = argv; #ifndef GNU_STANDARD # define GNU_STANDARD 1 #endif #if !GNU_STANDARD /* For compatibility with old compress, use program name as an option. * Unless you compile with -DGNU_STANDARD=0, this program will behave as * gzip even if it is invoked under the name gunzip or zcat. * * Systems which do not support links can still use -d or -dc. * Ignore an .exe extension for MSDOS, OS/2 and VMS. */ if (strncmp (program_name, "un", 2) == 0 /* ungzip, uncompress */ || strncmp (program_name, "gun", 3) == 0) /* gunzip */ decompress = 1; else if (strequ (program_name + 1, "cat") /* zcat, pcat, gcat */ || strequ (program_name, "gzcat")) /* gzcat */ decompress = to_stdout = 1; #endif z_suffix = Z_SUFFIX; z_len = strlen(z_suffix); while ((optc = getopt_long (argc, argv, "ab:cdfhH?lLmMnNqrS:tvVZ123456789", longopts, (int *)0)) != -1) { switch (optc) { case 'a': ascii = 1; break; case 'b': maxbits = atoi(optarg); for (; *optarg; optarg++) if (! ('0' <= *optarg && *optarg <= '9')) { fprintf (stderr, "%s: -b operand is not an integer\n", program_name); try_help (); } break; case 'c': to_stdout = 1; break; case 'd': decompress = 1; break; case 'f': force++; break; case 'h': case 'H': help(); do_exit(OK); break; case 'l': list = decompress = to_stdout = 1; break; case 'L': license(); do_exit(OK); break; case 'm': /* undocumented, may change later */ no_time = 1; break; case 'M': /* undocumented, may change later */ no_time = 0; break; case 'n': no_name = no_time = 1; break; case 'N': no_name = no_time = 0; break; case 'q': quiet = 1; verbose = 0; break; case 'r': #if NO_DIR fprintf (stderr, "%s: -r not supported on this system\n", program_name); try_help (); #else recursive = 1; #endif break; case 'S': #ifdef NO_MULTIPLE_DOTS if (*optarg == '.') optarg++; #endif z_len = strlen(optarg); z_suffix = optarg; break; case 't': test = decompress = to_stdout = 1; break; case 'v': verbose++; quiet = 0; break; case 'V': version(); do_exit(OK); break; case 'Z': #ifdef LZW do_lzw = 1; break; #else fprintf(stderr, "%s: -Z not supported in this version\n", program_name); try_help (); break; #endif case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': level = optc - '0'; break; default: /* Error message already emitted by getopt_long. */ try_help (); } } /* loop on all arguments */ /* By default, save name and timestamp on compression but do not * restore them on decompression. */ if (no_time < 0) no_time = decompress; if (no_name < 0) no_name = decompress; file_count = argc - optind; #if O_BINARY #else if (ascii && !quiet) { fprintf(stderr, "%s: option --ascii ignored on this system\n", program_name); } #endif if ((z_len == 0 && !decompress) || z_len > MAX_SUFFIX) { fprintf(stderr, "%s: incorrect suffix '%s'\n", program_name, z_suffix); do_exit(ERROR); } if (do_lzw && !decompress) work = lzw; /* Allocate all global buffers (for DYN_ALLOC option) */ ALLOC(uch, inbuf, INBUFSIZ +INBUF_EXTRA); ALLOC(uch, outbuf, OUTBUFSIZ+OUTBUF_EXTRA); ALLOC(ush, d_buf, DIST_BUFSIZE); ALLOC(uch, window, 2L*WSIZE); #ifndef MAXSEG_64K ALLOC(ush, tab_prefix, 1L<<BITS); #else ALLOC(ush, tab_prefix0, 1L<<(BITS-1)); ALLOC(ush, tab_prefix1, 1L<<(BITS-1)); #endif exiting_signal = quiet ? SIGPIPE : 0; install_signal_handlers (); /* And get to work */ if (file_count != 0) { if (to_stdout && !test && !list && (!decompress || !ascii)) { SET_BINARY_MODE(fileno(stdout)); } while (optind < argc) { treat_file(argv[optind++]); } } else { /* Standard input */ treat_stdin(); } if (list && !quiet && file_count > 1) { do_list(-1, -1); /* print totals */ } do_exit(exit_code); return exit_code; /* just to avoid lint warning */ } /* Return nonzero when at end of file on input. */ local int input_eof () { if (!decompress || last_member) return 1; if (inptr == insize) { if (insize != INBUFSIZ || fill_inbuf (1) == EOF) return 1; /* Unget the char that fill_inbuf got. */ inptr = 0; } return 0; } /* ======================================================================== * Compress or decompress stdin */ local void treat_stdin() { if (!force && !list && isatty(fileno((FILE *)(decompress ? stdin : stdout)))) { /* Do not send compressed data to the terminal or read it from * the terminal. We get here when user invoked the program * without parameters, so be helpful. According to the GNU standards: * * If there is one behavior you think is most useful when the output * is to a terminal, and another that you think is most useful when * the output is a file or a pipe, then it is usually best to make * the default behavior the one that is useful with output to a * terminal, and have an option for the other behavior. * * Here we use the --force option to get the other behavior. */ fprintf(stderr, "%s: compressed data not %s a terminal. Use -f to force %scompression.\n", program_name, decompress ? "read from" : "written to", decompress ? "de" : ""); fprintf (stderr, "For help, type: %s -h\n", program_name); do_exit(ERROR); } if (decompress || !ascii) { SET_BINARY_MODE(fileno(stdin)); } if (!test && !list && (!decompress || !ascii)) { SET_BINARY_MODE(fileno(stdout)); } strcpy(ifname, "stdin"); strcpy(ofname, "stdout"); /* Get the file's time stamp and size. */ if (fstat (fileno (stdin), &istat) != 0) { progerror ("standard input"); do_exit (ERROR); } ifile_size = S_ISREG (istat.st_mode) ? istat.st_size : -1; time_stamp.tv_nsec = -1; if (!no_time || list) time_stamp = get_stat_mtime (&istat); clear_bufs(); /* clear input and output buffers */ to_stdout = 1; part_nb = 0; ifd = fileno(stdin); if (decompress) { method = get_method(ifd); if (method < 0) { do_exit(exit_code); /* error message already emitted */ } } if (list) { do_list(ifd, method); return; } /* Actually do the compression/decompression. Loop over zipped members. */ for (;;) { if ((*work)(fileno(stdin), fileno(stdout)) != OK) return; if (input_eof ()) break; method = get_method(ifd); if (method < 0) return; /* error message already emitted */ bytes_out = 0; /* required for length check */ } if (verbose) { if (test) { fprintf(stderr, " OK\n"); } else if (!decompress) { display_ratio(bytes_in-(bytes_out-header_bytes), bytes_in, stderr); fprintf(stderr, "\n"); #ifdef DISPLAY_STDIN_RATIO } else { display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out,stderr); fprintf(stderr, "\n"); #endif } } } /* ======================================================================== * Compress or decompress the given file */ local void treat_file(iname) char *iname; { /* Accept "-" as synonym for stdin */ if (strequ(iname, "-")) { int cflag = to_stdout; treat_stdin(); to_stdout = cflag; return; } /* Check if the input file is present, set ifname and istat: */ ifd = open_input_file (iname, &istat); if (ifd < 0) return; /* If the input name is that of a directory, recurse or ignore: */ if (S_ISDIR(istat.st_mode)) { #if ! NO_DIR if (recursive) { treat_dir (ifd, iname); /* Warning: ifname is now garbage */ return; } #endif close (ifd); WARN ((stderr, "%s: %s is a directory -- ignored\n", program_name, ifname)); return; } if (! to_stdout) { if (! S_ISREG (istat.st_mode)) { WARN ((stderr, "%s: %s is not a directory or a regular file - ignored\n", program_name, ifname)); close (ifd); return; } if (istat.st_mode & S_ISUID) { WARN ((stderr, "%s: %s is set-user-ID on execution - ignored\n", program_name, ifname)); close (ifd); return; } if (istat.st_mode & S_ISGID) { WARN ((stderr, "%s: %s is set-group-ID on execution - ignored\n", program_name, ifname)); close (ifd); return; } if (! force) { if (istat.st_mode & S_ISVTX) { WARN ((stderr, "%s: %s has the sticky bit set - file ignored\n", program_name, ifname)); close (ifd); return; } if (2 <= istat.st_nlink) { WARN ((stderr, "%s: %s has %lu other link%c -- unchanged\n", program_name, ifname, (unsigned long int) istat.st_nlink - 1, istat.st_nlink == 2 ? ' ' : 's')); close (ifd); return; } } } ifile_size = S_ISREG (istat.st_mode) ? istat.st_size : -1; time_stamp.tv_nsec = -1; if (!no_time || list) time_stamp = get_stat_mtime (&istat); /* Generate output file name. For -r and (-t or -l), skip files * without a valid gzip suffix (check done in make_ofname). */ if (to_stdout && !list && !test) { strcpy(ofname, "stdout"); } else if (make_ofname() != OK) { close (ifd); return; } clear_bufs(); /* clear input and output buffers */ part_nb = 0; if (decompress) { method = get_method(ifd); /* updates ofname if original given */ if (method < 0) { close(ifd); return; /* error message already emitted */ } } if (list) { do_list(ifd, method); if (close (ifd) != 0) read_error (); return; } /* If compressing to a file, check if ofname is not ambiguous * because the operating system truncates names. Otherwise, generate * a new ofname and save the original name in the compressed file. */ if (to_stdout) { ofd = fileno(stdout); /* Keep remove_ofname_fd negative. */ } else { if (create_outfile() != OK) return; if (!decompress && save_orig_name && !verbose && !quiet) { fprintf(stderr, "%s: %s compressed to %s\n", program_name, ifname, ofname); } } /* Keep the name even if not truncated except with --no-name: */ if (!save_orig_name) save_orig_name = !no_name; if (verbose) { fprintf(stderr, "%s:\t", ifname); } /* Actually do the compression/decompression. Loop over zipped members. */ for (;;) { if ((*work)(ifd, ofd) != OK) { method = -1; /* force cleanup */ break; } if (input_eof ()) break; method = get_method(ifd); if (method < 0) break; /* error message already emitted */ bytes_out = 0; /* required for length check */ } if (close (ifd) != 0) read_error (); if (!to_stdout) { sigset_t oldset; int unlink_errno; copy_stat (&istat); if (close (ofd) != 0) write_error (); sigprocmask (SIG_BLOCK, &caught_signals, &oldset); remove_ofname_fd = -1; unlink_errno = xunlink (ifname) == 0 ? 0 : errno; sigprocmask (SIG_SETMASK, &oldset, NULL); if (unlink_errno) { WARN ((stderr, "%s: ", program_name)); if (!quiet) { errno = unlink_errno; perror (ifname); } } } if (method == -1) { if (!to_stdout) remove_output_file (); return; } /* Display statistics */ if(verbose) { if (test) { fprintf(stderr, " OK"); } else if (decompress) { display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out,stderr); } else { display_ratio(bytes_in-(bytes_out-header_bytes), bytes_in, stderr); } if (!test && !to_stdout) { fprintf(stderr, " -- replaced with %s", ofname); } fprintf(stderr, "\n"); } } /* ======================================================================== * Create the output file. Return OK or ERROR. * Try several times if necessary to avoid truncating the z_suffix. For * example, do not create a compressed file of name "1234567890123." * Sets save_orig_name to true if the file name has been truncated. * IN assertions: the input file has already been open (ifd is set) and * ofname has already been updated if there was an original name. * OUT assertions: ifd and ofd are closed in case of error. */ local int create_outfile() { int name_shortened = 0; int flags = (O_WRONLY | O_CREAT | O_EXCL | (ascii && decompress ? 0 : O_BINARY)); for (;;) { int open_errno; sigset_t oldset; sigprocmask (SIG_BLOCK, &caught_signals, &oldset); remove_ofname_fd = ofd = OPEN (ofname, flags, RW_USER); open_errno = errno; sigprocmask (SIG_SETMASK, &oldset, NULL); if (0 <= ofd) break; switch (open_errno) { #ifdef ENAMETOOLONG case ENAMETOOLONG: shorten_name (ofname); name_shortened = 1; break; #endif case EEXIST: if (check_ofname () != OK) { close (ifd); return ERROR; } break; default: progerror (ofname); close (ifd); return ERROR; } } if (name_shortened && decompress) { /* name might be too long if an original name was saved */ WARN ((stderr, "%s: %s: warning, name truncated\n", program_name, ofname)); } return OK; } /* ======================================================================== * Return a pointer to the 'z' suffix of a file name, or NULL. For all * systems, ".gz", ".z", ".Z", ".taz", ".tgz", "-gz", "-z" and "_z" are * accepted suffixes, in addition to the value of the --suffix option. * ".tgz" is a useful convention for tar.z files on systems limited * to 3 characters extensions. On such systems, ".?z" and ".??z" are * also accepted suffixes. For Unix, we do not want to accept any * .??z suffix as indicating a compressed file; some people use .xyz * to denote volume data. * On systems allowing multiple versions of the same file (such as VMS), * this function removes any version suffix in the given name. */ local char *get_suffix(name) char *name; { int nlen, slen; char suffix[MAX_SUFFIX+3]; /* last chars of name, forced to lower case */ static char *known_suffixes[] = {NULL, ".gz", ".z", ".taz", ".tgz", "-gz", "-z", "_z", #ifdef MAX_EXT_CHARS "z", #endif NULL}; char **suf = known_suffixes; *suf = z_suffix; if (strequ(z_suffix, "z")) suf++; /* check long suffixes first */ #ifdef SUFFIX_SEP /* strip a version number from the file name */ { char *v = strrchr(name, SUFFIX_SEP); if (v != NULL) *v = '\0'; } #endif nlen = strlen(name); if (nlen <= MAX_SUFFIX+2) { strcpy(suffix, name); } else { strcpy(suffix, name+nlen-MAX_SUFFIX-2); } strlwr(suffix); slen = strlen(suffix); do { int s = strlen(*suf); if (slen > s && suffix[slen-s-1] != PATH_SEP && strequ(suffix + slen - s, *suf)) { return name+nlen-s; } } while (*++suf != NULL); return NULL; } /* Open file NAME with the given flags and mode and store its status into *ST. Return a file descriptor to the newly opened file, or -1 (setting errno) on failure. */ static int open_and_stat (char *name, int flags, mode_t mode, struct stat *st) { int fd; /* Refuse to follow symbolic links unless -c or -f. */ if (!to_stdout && !force) { if (HAVE_WORKING_O_NOFOLLOW) flags |= O_NOFOLLOW; else { #if HAVE_LSTAT || defined lstat if (lstat (name, st) != 0) return -1; else if (S_ISLNK (st->st_mode)) { errno = ELOOP; return -1; } #endif } } fd = OPEN (name, flags, mode); if (0 <= fd && fstat (fd, st) != 0) { int e = errno; close (fd); errno = e; return -1; } return fd; } /* ======================================================================== * Set ifname to the input file name (with a suffix appended if necessary) * and istat to its stats. For decompression, if no file exists with the * original name, try adding successively z_suffix, .gz, .z, -z and .Z. * For MSDOS, we try only z_suffix and z. * Return an open file descriptor or -1. */ static int open_input_file (iname, sbuf) char *iname; struct stat *sbuf; { int ilen; /* strlen(ifname) */ int z_suffix_errno = 0; static char *suffixes[] = {NULL, ".gz", ".z", "-z", ".Z", NULL}; char **suf = suffixes; char *s; #ifdef NO_MULTIPLE_DOTS char *dot; /* pointer to ifname extension, or NULL */ #endif int fd; int open_flags = (O_RDONLY | O_NONBLOCK | O_NOCTTY | (ascii && !decompress ? 0 : O_BINARY)); *suf = z_suffix; if (sizeof ifname - 1 <= strlen (iname)) goto name_too_long; strcpy(ifname, iname); /* If input file exists, return OK. */ fd = open_and_stat (ifname, open_flags, RW_USER, sbuf); if (0 <= fd) return fd; if (!decompress || errno != ENOENT) { progerror(ifname); return -1; } /* file.ext doesn't exist, try adding a suffix (after removing any * version number for VMS). */ s = get_suffix(ifname); if (s != NULL) { progerror(ifname); /* ifname already has z suffix and does not exist */ return -1; } #ifdef NO_MULTIPLE_DOTS dot = strrchr(ifname, '.'); if (dot == NULL) { strcat(ifname, "."); dot = strrchr(ifname, '.'); } #endif ilen = strlen(ifname); if (strequ(z_suffix, ".gz")) suf++; /* Search for all suffixes */ do { char *s0 = s = *suf; strcpy (ifname, iname); #ifdef NO_MULTIPLE_DOTS if (*s == '.') s++; if (*dot == '\0') strcpy (dot, "."); #endif #ifdef MAX_EXT_CHARS if (MAX_EXT_CHARS < strlen (s) + strlen (dot + 1)) dot[MAX_EXT_CHARS + 1 - strlen (s)] = '\0'; #endif if (sizeof ifname <= ilen + strlen (s)) goto name_too_long; strcat(ifname, s); fd = open_and_stat (ifname, open_flags, RW_USER, sbuf); if (0 <= fd) return fd; if (errno != ENOENT) { progerror (ifname); return -1; } if (strequ (s0, z_suffix)) z_suffix_errno = errno; } while (*++suf != NULL); /* No suffix found, complain using z_suffix: */ strcpy(ifname, iname); #ifdef NO_MULTIPLE_DOTS if (*dot == '\0') strcpy(dot, "."); #endif #ifdef MAX_EXT_CHARS if (MAX_EXT_CHARS < z_len + strlen (dot + 1)) dot[MAX_EXT_CHARS + 1 - z_len] = '\0'; #endif strcat(ifname, z_suffix); errno = z_suffix_errno; progerror(ifname); return -1; name_too_long: fprintf (stderr, "%s: %s: file name too long\n", program_name, iname); exit_code = ERROR; return -1; } /* ======================================================================== * Generate ofname given ifname. Return OK, or WARNING if file must be skipped. * Sets save_orig_name to true if the file name has been truncated. */ local int make_ofname() { char *suff; /* ofname z suffix */ strcpy(ofname, ifname); /* strip a version number if any and get the gzip suffix if present: */ suff = get_suffix(ofname); if (decompress) { if (suff == NULL) { /* With -t or -l, try all files (even without .gz suffix) * except with -r (behave as with just -dr). */ if (!recursive && (list || test)) return OK; /* Avoid annoying messages with -r */ if (verbose || (!recursive && !quiet)) { WARN((stderr,"%s: %s: unknown suffix -- ignored\n", program_name, ifname)); } return WARNING; } /* Make a special case for .tgz and .taz: */ strlwr(suff); if (strequ(suff, ".tgz") || strequ(suff, ".taz")) { strcpy(suff, ".tar"); } else { *suff = '\0'; /* strip the z suffix */ } /* ofname might be changed later if infile contains an original name */ } else if (suff && ! force) { /* Avoid annoying messages with -r (see treat_dir()) */ if (verbose || (!recursive && !quiet)) { /* Don't use WARN, as it affects exit status. */ fprintf (stderr, "%s: %s already has %s suffix -- unchanged\n", program_name, ifname, suff); } return WARNING; } else { save_orig_name = 0; #ifdef NO_MULTIPLE_DOTS suff = strrchr(ofname, '.'); if (suff == NULL) { if (sizeof ofname <= strlen (ofname) + 1) goto name_too_long; strcat(ofname, "."); # ifdef MAX_EXT_CHARS if (strequ(z_suffix, "z")) { if (sizeof ofname <= strlen (ofname) + 2) goto name_too_long; strcat(ofname, "gz"); /* enough room */ return OK; } /* On the Atari and some versions of MSDOS, * ENAMETOOLONG does not work correctly. So we * must truncate here. */ } else if (strlen(suff)-1 + z_len > MAX_SUFFIX) { suff[MAX_SUFFIX+1-z_len] = '\0'; save_orig_name = 1; # endif } #endif /* NO_MULTIPLE_DOTS */ if (sizeof ofname <= strlen (ofname) + z_len) goto name_too_long; strcat(ofname, z_suffix); } /* decompress ? */ return OK; name_too_long: WARN ((stderr, "%s: %s: file name too long\n", program_name, ifname)); return WARNING; } /* ======================================================================== * Check the magic number of the input file and update ofname if an * original name was given and to_stdout is not set. * Return the compression method, -1 for error, -2 for warning. * Set inptr to the offset of the next byte to be processed. * Updates time_stamp if there is one and --no-time is not used. * This function may be called repeatedly for an input file consisting * of several contiguous gzip'ed members. * IN assertions: there is at least one remaining compressed member. * If the member is a zip file, it must be the only one. */ local int get_method(in) int in; /* input file descriptor */ { uch flags; /* compression flags */ char magic[2]; /* magic header */ int imagic1; /* like magic[1], but can represent EOF */ ulg stamp; /* time stamp */ /* If --force and --stdout, zcat == cat, so do not complain about * premature end of file: use try_byte instead of get_byte. */ if (force && to_stdout) { magic[0] = (char)try_byte(); imagic1 = try_byte (); magic[1] = (char) imagic1; /* If try_byte returned EOF, magic[1] == (char) EOF. */ } else { magic[0] = (char)get_byte(); magic[1] = (char)get_byte(); imagic1 = 0; /* avoid lint warning */ } method = -1; /* unknown yet */ part_nb++; /* number of parts in gzip file */ header_bytes = 0; last_member = RECORD_IO; /* assume multiple members in gzip file except for record oriented I/O */ if (memcmp(magic, GZIP_MAGIC, 2) == 0 || memcmp(magic, OLD_GZIP_MAGIC, 2) == 0) { method = (int)get_byte(); if (method != DEFLATED) { fprintf(stderr, "%s: %s: unknown method %d -- not supported\n", program_name, ifname, method); exit_code = ERROR; return -1; } work = unzip; flags = (uch)get_byte(); if ((flags & ENCRYPTED) != 0) { fprintf(stderr, "%s: %s is encrypted -- not supported\n", program_name, ifname); exit_code = ERROR; return -1; } if ((flags & CONTINUATION) != 0) { fprintf(stderr, "%s: %s is a multi-part gzip file -- not supported\n", program_name, ifname); exit_code = ERROR; if (force <= 1) return -1; } if ((flags & RESERVED) != 0) { fprintf(stderr, "%s: %s has flags 0x%x -- not supported\n", program_name, ifname, flags); exit_code = ERROR; if (force <= 1) return -1; } stamp = (ulg)get_byte(); stamp |= ((ulg)get_byte()) << 8; stamp |= ((ulg)get_byte()) << 16; stamp |= ((ulg)get_byte()) << 24; if (stamp != 0 && !no_time) { time_stamp.tv_sec = stamp; time_stamp.tv_nsec = 0; } (void)get_byte(); /* Ignore extra flags for the moment */ (void)get_byte(); /* Ignore OS type for the moment */ if ((flags & CONTINUATION) != 0) { unsigned part = (unsigned)get_byte(); part |= ((unsigned)get_byte())<<8; if (verbose) { fprintf(stderr,"%s: %s: part number %u\n", program_name, ifname, part); } } if ((flags & EXTRA_FIELD) != 0) { unsigned len = (unsigned)get_byte(); len |= ((unsigned)get_byte())<<8; if (verbose) { fprintf(stderr,"%s: %s: extra field of %u bytes ignored\n", program_name, ifname, len); } while (len--) (void)get_byte(); } /* Get original file name if it was truncated */ if ((flags & ORIG_NAME) != 0) { if (no_name || (to_stdout && !list) || part_nb > 1) { /* Discard the old name */ char c; /* dummy used for NeXTstep 3.0 cc optimizer bug */ do {c=get_byte();} while (c != 0); } else { /* Copy the base name. Keep a directory prefix intact. */ char *p = gzip_base_name (ofname); char *base = p; for (;;) { *p = (char)get_char(); if (*p++ == '\0') break; if (p >= ofname+sizeof(ofname)) { gzip_error ("corrupted input -- file name too large"); } } p = gzip_base_name (base); memmove (base, p, strlen (p) + 1); /* If necessary, adapt the name to local OS conventions: */ if (!list) { MAKE_LEGAL_NAME(base); if (base) list=0; /* avoid warning about unused variable */ } } /* no_name || to_stdout */ } /* ORIG_NAME */ /* Discard file comment if any */ if ((flags & COMMENT) != 0) { while (get_char() != 0) /* null */ ; } if (part_nb == 1) { header_bytes = inptr + 2*sizeof(long); /* include crc and size */ } } else if (memcmp(magic, PKZIP_MAGIC, 2) == 0 && inptr == 2 && memcmp((char*)inbuf, PKZIP_MAGIC, 4) == 0) { /* To simplify the code, we support a zip file when alone only. * We are thus guaranteed that the entire local header fits in inbuf. */ inptr = 0; work = unzip; if (check_zipfile(in) != OK) return -1; /* check_zipfile may get ofname from the local header */ last_member = 1; } else if (memcmp(magic, PACK_MAGIC, 2) == 0) { work = unpack; method = PACKED; } else if (memcmp(magic, LZW_MAGIC, 2) == 0) { work = unlzw; method = COMPRESSED; last_member = 1; } else if (memcmp(magic, LZH_MAGIC, 2) == 0) { work = unlzh; method = LZHED; last_member = 1; } else if (force && to_stdout && !list) { /* pass input unchanged */ method = STORED; work = copy; inptr = 0; last_member = 1; } if (method >= 0) return method; if (part_nb == 1) { fprintf (stderr, "\n%s: %s: not in gzip format\n", program_name, ifname); exit_code = ERROR; return -1; } else { if (magic[0] == 0) { int inbyte; for (inbyte = imagic1; inbyte == 0; inbyte = try_byte ()) continue; if (inbyte == EOF) { if (verbose) WARN ((stderr, "\n%s: %s: decompression OK, trailing zero bytes ignored\n", program_name, ifname)); return -3; } } WARN((stderr, "\n%s: %s: decompression OK, trailing garbage ignored\n", program_name, ifname)); return -2; } } /* ======================================================================== * Display the characteristics of the compressed file. * If the given method is < 0, display the accumulated totals. * IN assertions: time_stamp, header_bytes and ifile_size are initialized. */ local void do_list(ifd, method) int ifd; /* input file descriptor */ int method; /* compression method */ { ulg crc; /* original crc */ static int first_time = 1; static char* methods[MAX_METHODS] = { "store", /* 0 */ "compr", /* 1 */ "pack ", /* 2 */ "lzh ", /* 3 */ "", "", "", "", /* 4 to 7 reserved */ "defla"}; /* 8 */ int positive_off_t_width = 1; off_t o; for (o = OFF_T_MAX; 9 < o; o /= 10) { positive_off_t_width++; } if (first_time && method >= 0) { first_time = 0; if (verbose) { printf("method crc date time "); } if (!quiet) { printf("%*.*s %*.*s ratio uncompressed_name\n", positive_off_t_width, positive_off_t_width, "compressed", positive_off_t_width, positive_off_t_width, "uncompressed"); } } else if (method < 0) { if (total_in <= 0 || total_out <= 0) return; if (verbose) { printf(" "); } if (verbose || !quiet) { fprint_off(stdout, total_in, positive_off_t_width); printf(" "); fprint_off(stdout, total_out, positive_off_t_width); printf(" "); } display_ratio(total_out-(total_in-header_bytes), total_out, stdout); /* header_bytes is not meaningful but used to ensure the same * ratio if there is a single file. */ printf(" (totals)\n"); return; } crc = (ulg)~0; /* unknown */ bytes_out = -1L; bytes_in = ifile_size; #if RECORD_IO == 0 if (method == DEFLATED && !last_member) { /* Get the crc and uncompressed size for gzip'ed (not zip'ed) files. * If the lseek fails, we could use read() to get to the end, but * --list is used to get quick results. * Use "gunzip < foo.gz | wc -c" to get the uncompressed size if * you are not concerned about speed. */ bytes_in = lseek(ifd, (off_t)(-8), SEEK_END); if (bytes_in != -1L) { uch buf[8]; bytes_in += 8L; if (read(ifd, (char*)buf, sizeof(buf)) != sizeof(buf)) { read_error(); } crc = LG(buf); bytes_out = LG(buf+4); } } #endif /* RECORD_IO */ if (verbose) { struct tm *tm = localtime (&time_stamp.tv_sec); printf ("%5s %08lx ", methods[method], crc); if (tm) printf ("%s%3d %02d:%02d ", ("Jan\0Feb\0Mar\0Apr\0May\0Jun\0Jul\0Aug\0Sep\0Oct\0Nov\0Dec" + 4 * tm->tm_mon), tm->tm_mday, tm->tm_hour, tm->tm_min); else printf ("??? ?? ??:?? "); } fprint_off(stdout, bytes_in, positive_off_t_width); printf(" "); fprint_off(stdout, bytes_out, positive_off_t_width); printf(" "); if (bytes_in == -1L) { total_in = -1L; bytes_in = bytes_out = header_bytes = 0; } else if (total_in >= 0) { total_in += bytes_in; } if (bytes_out == -1L) { total_out = -1L; bytes_in = bytes_out = header_bytes = 0; } else if (total_out >= 0) { total_out += bytes_out; } display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out, stdout); printf(" %s\n", ofname); } /* ======================================================================== * Shorten the given name by one character, or replace a .tar extension * with .tgz. Truncate the last part of the name which is longer than * MIN_PART characters: 1234.678.012.gz -> 123.678.012.gz. If the name * has only parts shorter than MIN_PART truncate the longest part. * For decompression, just remove the last character of the name. * * IN assertion: for compression, the suffix of the given name is z_suffix. */ local void shorten_name(name) char *name; { int len; /* length of name without z_suffix */ char *trunc = NULL; /* character to be truncated */ int plen; /* current part length */ int min_part = MIN_PART; /* current minimum part length */ char *p; len = strlen(name); if (decompress) { if (len <= 1) gzip_error ("name too short"); name[len-1] = '\0'; return; } p = get_suffix(name); if (! p) gzip_error ("can't recover suffix\n"); *p = '\0'; save_orig_name = 1; /* compress 1234567890.tar to 1234567890.tgz */ if (len > 4 && strequ(p-4, ".tar")) { strcpy(p-4, ".tgz"); return; } /* Try keeping short extensions intact: * 1234.678.012.gz -> 123.678.012.gz */ do { p = strrchr(name, PATH_SEP); p = p ? p+1 : name; while (*p) { plen = strcspn(p, PART_SEP); p += plen; if (plen > min_part) trunc = p-1; if (*p) p++; } } while (trunc == NULL && --min_part != 0); if (trunc != NULL) { do { trunc[0] = trunc[1]; } while (*trunc++); trunc--; } else { trunc = strrchr(name, PART_SEP[0]); if (!trunc) gzip_error ("internal error in shorten_name"); if (trunc[1] == '\0') trunc--; /* force truncation */ } strcpy(trunc, z_suffix); } /* ======================================================================== * The compressed file already exists, so ask for confirmation. * Return ERROR if the file must be skipped. */ local int check_ofname() { /* Ask permission to overwrite the existing file */ if (!force) { int ok = 0; fprintf (stderr, "%s: %s already exists;", program_name, ofname); if (foreground && isatty(fileno(stdin))) { fprintf(stderr, " do you wish to overwrite (y or n)? "); fflush(stderr); ok = yesno(); } if (!ok) { fprintf(stderr, "\tnot overwritten\n"); if (exit_code == OK) exit_code = WARNING; return ERROR; } } if (xunlink (ofname)) { progerror(ofname); return ERROR; } return OK; } /* ======================================================================== * Copy modes, times, ownership from input file to output file. * IN assertion: to_stdout is false. */ local void copy_stat(ifstat) struct stat *ifstat; { mode_t mode = ifstat->st_mode & S_IRWXUGO; int r; #ifndef NO_UTIME struct timespec timespec[2]; timespec[0] = get_stat_atime (ifstat); timespec[1] = get_stat_mtime (ifstat); if (decompress && 0 <= time_stamp.tv_nsec && ! (timespec[1].tv_sec == time_stamp.tv_sec && timespec[1].tv_nsec == time_stamp.tv_nsec)) { timespec[1] = time_stamp; if (verbose > 1) { fprintf(stderr, "%s: time stamp restored\n", ofname); } } if (gl_futimens (ofd, ofname, timespec) != 0) { int e = errno; WARN ((stderr, "%s: ", program_name)); if (!quiet) { errno = e; perror (ofname); } } #endif #ifndef NO_CHOWN # if HAVE_FCHOWN fchown (ofd, ifstat->st_uid, ifstat->st_gid); /* Copy ownership */ # elif HAVE_CHOWN chown(ofname, ifstat->st_uid, ifstat->st_gid); /* Copy ownership */ # endif #endif /* Copy the protection modes */ #if HAVE_FCHMOD r = fchmod (ofd, mode); #else r = chmod (ofname, mode); #endif if (r != 0) { int e = errno; WARN ((stderr, "%s: ", program_name)); if (!quiet) { errno = e; perror(ofname); } } } #if ! NO_DIR /* ======================================================================== * Recurse through the given directory. This code is taken from ncompress. */ local void treat_dir (fd, dir) int fd; char *dir; { struct dirent *dp; DIR *dirp; char nbuf[MAX_PATH_LEN]; int len; #if HAVE_FDOPENDIR dirp = fdopendir (fd); #else close (fd); dirp = opendir(dir); #endif if (dirp == NULL) { progerror(dir); #if HAVE_FDOPENDIR close (fd); #endif return ; } /* ** WARNING: the following algorithm could occasionally cause ** compress to produce error warnings of the form "<filename>.gz ** already has .gz suffix - ignored". This occurs when the ** .gz output file is inserted into the directory below ** readdir's current pointer. ** These warnings are harmless but annoying, so they are suppressed ** with option -r (except when -v is on). An alternative ** to allowing this would be to store the entire directory ** list in memory, then compress the entries in the stored ** list. Given the depth-first recursive algorithm used here, ** this could use up a tremendous amount of memory. I don't ** think it's worth it. -- Dave Mack ** (An other alternative might be two passes to avoid depth-first.) */ while ((errno = 0, dp = readdir(dirp)) != NULL) { if (strequ(dp->d_name,".") || strequ(dp->d_name,"..")) { continue; } len = strlen(dir); if (len + _D_EXACT_NAMLEN (dp) + 1 < MAX_PATH_LEN - 1) { strcpy(nbuf,dir); if (len != 0 /* dir = "" means current dir on Amiga */ #ifdef PATH_SEP2 && dir[len-1] != PATH_SEP2 #endif #ifdef PATH_SEP3 && dir[len-1] != PATH_SEP3 #endif ) { nbuf[len++] = PATH_SEP; } strcpy(nbuf+len, dp->d_name); treat_file(nbuf); } else { fprintf(stderr,"%s: %s/%s: pathname too long\n", program_name, dir, dp->d_name); exit_code = ERROR; } } if (errno != 0) progerror(dir); if (CLOSEDIR(dirp) != 0) progerror(dir); } #endif /* ! NO_DIR */ /* Make sure signals get handled properly. */ static void install_signal_handlers () { int nsigs = sizeof handled_sig / sizeof handled_sig[0]; int i; #if SA_NOCLDSTOP struct sigaction act; sigemptyset (&caught_signals); for (i = 0; i < nsigs; i++) { sigaction (handled_sig[i], NULL, &act); if (act.sa_handler != SIG_IGN) sigaddset (&caught_signals, handled_sig[i]); } act.sa_handler = abort_gzip_signal; act.sa_mask = caught_signals; act.sa_flags = 0; for (i = 0; i < nsigs; i++) if (sigismember (&caught_signals, handled_sig[i])) { if (i == 0) foreground = 1; sigaction (handled_sig[i], &act, NULL); } #else for (i = 0; i < nsigs; i++) if (signal (handled_sig[i], SIG_IGN) != SIG_IGN) { if (i == 0) foreground = 1; signal (handled_sig[i], abort_gzip_signal); siginterrupt (handled_sig[i], 1); } #endif } /* ======================================================================== * Free all dynamically allocated variables and exit with the given code. */ local void do_exit(exitcode) int exitcode; { static int in_exit = 0; if (in_exit) exit(exitcode); in_exit = 1; free(env); env = NULL; free(args); args = NULL; FREE(inbuf); FREE(outbuf); FREE(d_buf); FREE(window); #ifndef MAXSEG_64K FREE(tab_prefix); #else FREE(tab_prefix0); FREE(tab_prefix1); #endif exit(exitcode); } /* ======================================================================== * Close and unlink the output file. */ static void remove_output_file () { int fd; sigset_t oldset; sigprocmask (SIG_BLOCK, &caught_signals, &oldset); fd = remove_ofname_fd; if (0 <= fd) { remove_ofname_fd = -1; close (fd); xunlink (ofname); } sigprocmask (SIG_SETMASK, &oldset, NULL); } /* ======================================================================== * Error handler. */ void abort_gzip () { remove_output_file (); do_exit(ERROR); } /* ======================================================================== * Signal handler. */ static RETSIGTYPE abort_gzip_signal (sig) int sig; { if (! SA_NOCLDSTOP) signal (sig, SIG_IGN); remove_output_file (); if (sig == exiting_signal) _exit (WARNING); signal (sig, SIG_DFL); raise (sig); } /* gzip (GNU zip) -- compress files with zip algorithm and 'compress' interface Copyright (C) 1999, 2001-2002, 2006-2007, 2009 Free Software Foundation, Inc. Copyright (C) 1992-1993 Jean-loup Gailly This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * The unzip code was written and put in the public domain by Mark Adler. * Portions of the lzw code are derived from the public domain 'compress' * written by Spencer Thomas, Joe Orost, James Woods, Jim McKie, Steve Davies, * Ken Turkowski, Dave Mack and Peter Jannesen. * * See the license_msg below and the file COPYING for the software license. * See the file algorithm.doc for the compression algorithms and file formats. */ static char *license_msg[] = { "Copyright (C) 2007 Free Software Foundation, Inc.", "Copyright (C) 1993 Jean-loup Gailly.", "This is free software. You may redistribute copies of it under the terms of", "the GNU General Public License <http://www.gnu.org/licenses/gpl.html>.", "There is NO WARRANTY, to the extent permitted by law.", 0}; /* Compress files with zip algorithm and 'compress' interface. * See help() function below for all options. * Outputs: * file.gz: compressed file with same mode, owner, and utimes * or stdout with -c option or if stdin used as input. * If the output file name had to be truncated, the original name is kept * in the compressed file. * On MSDOS, file.tmp -> file.tmz. On VMS, file.tmp -> file.tmp-gz. * * Using gz on MSDOS would create too many file name conflicts. For * example, foo.txt -> foo.tgz (.tgz must be reserved as shorthand for * tar.gz). Similarly, foo.dir and foo.doc would both be mapped to foo.dgz. * I also considered 12345678.txt -> 12345txt.gz but this truncates the name * too heavily. There is no ideal solution given the MSDOS 8+3 limitation. * * For the meaning of all compilation flags, see comments in Makefile.in. */ #include <config.h> #include <ctype.h> #include <sys/types.h> #include <signal.h> #include <sys/stat.h> #include <errno.h> #include "closein.h" #include "tailor.h" #include "gzip.h" #include "lzw.h" #include "revision.h" #include "fcntl-safer.h" #include "getopt.h" #include "stat-time.h" /* configuration */ #ifdef HAVE_FCNTL_H # include <fcntl.h> #endif #ifdef HAVE_LIMITS_H # include <limits.h> #endif #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #if defined STDC_HEADERS || defined HAVE_STDLIB_H # include <stdlib.h> #else extern int errno; #endif #ifndef NO_DIR # define NO_DIR 0 #endif #if !NO_DIR # include <dirent.h> # ifndef _D_EXACT_NAMLEN # define _D_EXACT_NAMLEN(dp) strlen ((dp)->d_name) # endif #endif #ifdef CLOSEDIR_VOID # define CLOSEDIR(d) (closedir(d), 0) #else # define CLOSEDIR(d) closedir(d) #endif #ifndef NO_UTIME # include <utimens.h> #endif #define RW_USER (S_IRUSR | S_IWUSR) /* creation mode for open() */ #ifndef MAX_PATH_LEN # define MAX_PATH_LEN 1024 /* max pathname length */ #endif #ifndef SEEK_END # define SEEK_END 2 #endif #ifndef CHAR_BIT # define CHAR_BIT 8 #endif #ifdef off_t off_t lseek OF((int fd, off_t offset, int whence)); #endif #ifndef OFF_T_MIN #define OFF_T_MIN (~ (off_t) 0 << (sizeof (off_t) * CHAR_BIT - 1)) #endif #ifndef OFF_T_MAX #define OFF_T_MAX (~ (off_t) 0 - OFF_T_MIN) #endif /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is present. */ #ifndef SA_NOCLDSTOP # define SA_NOCLDSTOP 0 # define sigprocmask(how, set, oset) /* empty */ # define sigset_t int # if ! HAVE_SIGINTERRUPT # define siginterrupt(sig, flag) /* empty */ # endif #endif #ifndef HAVE_WORKING_O_NOFOLLOW # define HAVE_WORKING_O_NOFOLLOW 0 #endif #ifndef ELOOP # define ELOOP EINVAL #endif /* Separator for file name parts (see shorten_name()) */ #ifdef NO_MULTIPLE_DOTS # define PART_SEP "-" #else # define PART_SEP "." #endif /* global buffers */ DECLARE(uch, inbuf, INBUFSIZ +INBUF_EXTRA); DECLARE(uch, outbuf, OUTBUFSIZ+OUTBUF_EXTRA); DECLARE(ush, d_buf, DIST_BUFSIZE); DECLARE(uch, window, 2L*WSIZE); #ifndef MAXSEG_64K DECLARE(ush, tab_prefix, 1L<<BITS); #else DECLARE(ush, tab_prefix0, 1L<<(BITS-1)); DECLARE(ush, tab_prefix1, 1L<<(BITS-1)); #endif /* local variables */ int ascii = 0; /* convert end-of-lines to local OS conventions */ int to_stdout = 0; /* output to stdout (-c) */ int decompress = 0; /* decompress (-d) */ int force = 0; /* don't ask questions, compress links (-f) */ int no_name = -1; /* don't save or restore the original file name */ int no_time = -1; /* don't save or restore the original file time */ int recursive = 0; /* recurse through directories (-r) */ int list = 0; /* list the file contents (-l) */ int verbose = 0; /* be verbose (-v) */ int quiet = 0; /* be very quiet (-q) */ int do_lzw = 0; /* generate output compatible with old compress (-Z) */ int test = 0; /* test .gz file integrity */ int foreground = 0; /* set if program run in foreground */ char *program_name; /* program name */ int maxbits = BITS; /* max bits per code for LZW */ int method = DEFLATED;/* compression method */ int level = 6; /* compression level */ int exit_code = OK; /* program exit code */ int save_orig_name; /* set if original name must be saved */ int last_member; /* set for .zip and .Z files */ int part_nb; /* number of parts in .gz file */ struct timespec time_stamp; /* original time stamp (modification time) */ off_t ifile_size; /* input file size, -1 for devices (debug only) */ char *env; /* contents of GZIP env variable */ char **args = NULL; /* argv pointer if GZIP env variable defined */ char *z_suffix; /* default suffix (can be set with --suffix) */ size_t z_len; /* strlen(z_suffix) */ /* The set of signals that are caught. */ static sigset_t caught_signals; /* If nonzero then exit with status WARNING, rather than with the usual signal status, on receipt of a signal with this value. This suppresses a "Broken Pipe" message with some shells. */ static int volatile exiting_signal; /* If nonnegative, close this file descriptor and unlink ofname on error. */ static int volatile remove_ofname_fd = -1; off_t bytes_in; /* number of input bytes */ off_t bytes_out; /* number of output bytes */ off_t total_in; /* input bytes for all files */ off_t total_out; /* output bytes for all files */ char ifname[MAX_PATH_LEN]; /* input file name */ char ofname[MAX_PATH_LEN]; /* output file name */ struct stat istat; /* status for input file */ int ifd; /* input file descriptor */ int ofd; /* output file descriptor */ unsigned insize; /* valid bytes in inbuf */ unsigned inptr; /* index of next byte to be processed in inbuf */ unsigned outcnt; /* bytes in output buffer */ static int handled_sig[] = { /* SIGINT must be first, as 'foreground' depends on it. */ SIGINT #ifdef SIGHUP , SIGHUP #endif #ifdef SIGPIPE , SIGPIPE #else # define SIGPIPE 0 #endif #ifdef SIGTERM , SIGTERM #endif #ifdef SIGXCPU , SIGXCPU #endif #ifdef SIGXFSZ , SIGXFSZ #endif }; struct option longopts[] = { /* { name has_arg *flag val } */ {"ascii", 0, 0, 'a'}, /* ascii text mode */ {"to-stdout", 0, 0, 'c'}, /* write output on standard output */ {"stdout", 0, 0, 'c'}, /* write output on standard output */ {"decompress", 0, 0, 'd'}, /* decompress */ {"uncompress", 0, 0, 'd'}, /* decompress */ /* {"encrypt", 0, 0, 'e'}, encrypt */ {"force", 0, 0, 'f'}, /* force overwrite of output file */ {"help", 0, 0, 'h'}, /* give help */ /* {"pkzip", 0, 0, 'k'}, force output in pkzip format */ {"list", 0, 0, 'l'}, /* list .gz file contents */ {"license", 0, 0, 'L'}, /* display software license */ {"no-name", 0, 0, 'n'}, /* don't save or restore original name & time */ {"name", 0, 0, 'N'}, /* save or restore original name & time */ {"quiet", 0, 0, 'q'}, /* quiet mode */ {"silent", 0, 0, 'q'}, /* quiet mode */ {"recursive", 0, 0, 'r'}, /* recurse through directories */ {"suffix", 1, 0, 'S'}, /* use given suffix instead of .gz */ {"test", 0, 0, 't'}, /* test compressed file integrity */ {"no-time", 0, 0, 'T'}, /* don't save or restore the time stamp */ {"verbose", 0, 0, 'v'}, /* verbose mode */ {"version", 0, 0, 'V'}, /* display version number */ {"fast", 0, 0, '1'}, /* compress faster */ {"best", 0, 0, '9'}, /* compress better */ {"lzw", 0, 0, 'Z'}, /* make output compatible with old compress */ {"bits", 1, 0, 'b'}, /* max number of bits per code (implies -Z) */ { 0, 0, 0, 0 } }; /* local functions */ local void try_help OF((void)) ATTRIBUTE_NORETURN; local void help OF((void)); local void license OF((void)); local void version OF((void)); local int input_eof OF((void)); local void treat_stdin OF((void)); local void treat_file OF((char *iname)); local int create_outfile OF((void)); local char *get_suffix OF((char *name)); local int open_input_file OF((char *iname, struct stat *sbuf)); local int make_ofname OF((void)); local void shorten_name OF((char *name)); local int get_method OF((int in)); local void do_list OF((int ifd, int method)); local int check_ofname OF((void)); local void copy_stat OF((struct stat *ifstat)); local void install_signal_handlers OF((void)); local void remove_output_file OF((void)); local RETSIGTYPE abort_gzip_signal OF((int)); local void do_exit OF((int exitcode)) ATTRIBUTE_NORETURN; int main OF((int argc, char **argv)); int (*work) OF((int infile, int outfile)) = zip; /* function to call */ #if ! NO_DIR local void treat_dir OF((int fd, char *dir)); #endif #define strequ(s1, s2) (strcmp((s1),(s2)) == 0) static void try_help () { fprintf (stderr, "Try `%s --help' for more information.\n", program_name); do_exit (ERROR); } /* ======================================================================== */ local void help() { static char *help_msg[] = { "Compress or uncompress FILEs (by default, compress FILES in-place).", "", "Mandatory arguments to long options are mandatory for short options too.", "", #if O_BINARY " -a, --ascii ascii text; convert end-of-line using local conventions", #endif " -c, --stdout write on standard output, keep original files unchanged", " -d, --decompress decompress", /* -e, --encrypt encrypt */ " -f, --force force overwrite of output file and compress links", " -h, --help give this help", /* -k, --pkzip force output in pkzip format */ " -l, --list list compressed file contents", " -L, --license display software license", #ifdef UNDOCUMENTED " -m, --no-time do not save or restore the original modification time", " -M, --time save or restore the original modification time", #endif " -n, --no-name do not save or restore the original name and time stamp", " -N, --name save or restore the original name and time stamp", " -q, --quiet suppress all warnings", #if ! NO_DIR " -r, --recursive operate recursively on directories", #endif " -S, --suffix=SUF use suffix SUF on compressed files", " -t, --test test compressed file integrity", " -v, --verbose verbose mode", " -V, --version display version number", " -1, --fast compress faster", " -9, --best compress better", #ifdef LZW " -Z, --lzw produce output compatible with old compress", " -b, --bits=BITS max number of bits per code (implies -Z)", #endif "", "With no FILE, or when FILE is -, read standard input.", "", "Report bugs to <[email protected]>.", 0}; char **p = help_msg; printf ("Usage: %s [OPTION]... [FILE]...\n", program_name); while (*p) printf ("%s\n", *p++); } /* ======================================================================== */ local void license() { char **p = license_msg; printf ("%s %s\n", program_name, VERSION); while (*p) printf ("%s\n", *p++); } /* ======================================================================== */ local void version() { license (); printf ("\n"); printf ("Written by Jean-loup Gailly.\n"); } local void progerror (string) char *string; { int e = errno; fprintf (stderr, "%s: ", program_name); errno = e; perror(string); exit_code = ERROR; } /* ======================================================================== */ int main (argc, argv) int argc; char **argv; { int file_count; /* number of files to process */ size_t proglen; /* length of program_name */ int optc; /* current option */ EXPAND(argc, argv); /* wild card expansion if necessary */ program_name = gzip_base_name (argv[0]); proglen = strlen (program_name); atexit (close_stdin); /* Suppress .exe for MSDOS, OS/2 and VMS: */ if (4 < proglen && strequ (program_name + proglen - 4, ".exe")) program_name[proglen - 4] = '\0'; /* Add options in GZIP environment variable if there is one */ env = add_envopt(&argc, &argv, OPTIONS_VAR); if (env != NULL) args = argv; #ifndef GNU_STANDARD # define GNU_STANDARD 1 #endif #if !GNU_STANDARD /* For compatibility with old compress, use program name as an option. * Unless you compile with -DGNU_STANDARD=0, this program will behave as * gzip even if it is invoked under the name gunzip or zcat. * * Systems which do not support links can still use -d or -dc. * Ignore an .exe extension for MSDOS, OS/2 and VMS. */ if (strncmp (program_name, "un", 2) == 0 /* ungzip, uncompress */ || strncmp (program_name, "gun", 3) == 0) /* gunzip */ decompress = 1; else if (strequ (program_name + 1, "cat") /* zcat, pcat, gcat */ || strequ (program_name, "gzcat")) /* gzcat */ decompress = to_stdout = 1; #endif z_suffix = Z_SUFFIX; z_len = strlen(z_suffix); while ((optc = getopt_long (argc, argv, "ab:cdfhH?lLmMnNqrS:tvVZ123456789", longopts, (int *)0)) != -1) { switch (optc) { case 'a': ascii = 1; break; case 'b': maxbits = atoi(optarg); for (; *optarg; optarg++) if (! ('0' <= *optarg && *optarg <= '9')) { fprintf (stderr, "%s: -b operand is not an integer\n", program_name); try_help (); } break; case 'c': to_stdout = 1; break; case 'd': decompress = 1; break; case 'f': force++; break; case 'h': case 'H': help(); do_exit(OK); break; case 'l': list = decompress = to_stdout = 1; break; case 'L': license(); do_exit(OK); break; case 'm': /* undocumented, may change later */ no_time = 1; break; case 'M': /* undocumented, may change later */ no_time = 0; break; case 'n': no_name = no_time = 1; break; case 'N': no_name = no_time = 0; break; case 'q': quiet = 1; verbose = 0; break; case 'r': #if NO_DIR fprintf (stderr, "%s: -r not supported on this system\n", program_name); try_help (); #else recursive = 1; #endif break; case 'S': #ifdef NO_MULTIPLE_DOTS if (*optarg == '.') optarg++; #endif z_len = strlen(optarg); z_suffix = optarg; break; case 't': test = decompress = to_stdout = 1; break; case 'v': verbose++; quiet = 0; break; case 'V': version(); do_exit(OK); break; case 'Z': #ifdef LZW do_lzw = 1; break; #else fprintf(stderr, "%s: -Z not supported in this version\n", program_name); try_help (); break; #endif case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': level = optc - '0'; break; default: /* Error message already emitted by getopt_long. */ try_help (); } } /* loop on all arguments */ /* By default, save name and timestamp on compression but do not * restore them on decompression. */ if (no_time < 0) no_time = decompress; if (no_name < 0) no_name = decompress; file_count = argc - optind; #if O_BINARY #else if (ascii && !quiet) { fprintf(stderr, "%s: option --ascii ignored on this system\n", program_name); } #endif if ((z_len == 0 && !decompress) || z_len > MAX_SUFFIX) { fprintf(stderr, "%s: incorrect suffix '%s'\n", program_name, z_suffix); do_exit(ERROR); } if (do_lzw && !decompress) work = lzw; /* Allocate all global buffers (for DYN_ALLOC option) */ ALLOC(uch, inbuf, INBUFSIZ +INBUF_EXTRA); ALLOC(uch, outbuf, OUTBUFSIZ+OUTBUF_EXTRA); ALLOC(ush, d_buf, DIST_BUFSIZE); ALLOC(uch, window, 2L*WSIZE); #ifndef MAXSEG_64K ALLOC(ush, tab_prefix, 1L<<BITS); #else ALLOC(ush, tab_prefix0, 1L<<(BITS-1)); ALLOC(ush, tab_prefix1, 1L<<(BITS-1)); #endif exiting_signal = quiet ? SIGPIPE : 0; install_signal_handlers (); /* And get to work */ if (file_count != 0) { if (to_stdout && !test && !list && (!decompress || !ascii)) { SET_BINARY_MODE(fileno(stdout)); } while (optind < argc) { treat_file(argv[optind++]); } } else { /* Standard input */ treat_stdin(); } if (list && !quiet && file_count > 1) { do_list(-1, -1); /* print totals */ } do_exit(exit_code); return exit_code; /* just to avoid lint warning */ } /* Return nonzero when at end of file on input. */ local int input_eof () { if (!decompress || last_member) return 1; if (inptr == insize) { if (insize != INBUFSIZ || fill_inbuf (1) == EOF) return 1; /* Unget the char that fill_inbuf got. */ inptr = 0; } return 0; } /* ======================================================================== * Compress or decompress stdin */ local void treat_stdin() { if (!force && !list && isatty(fileno((FILE *)(decompress ? stdin : stdout)))) { /* Do not send compressed data to the terminal or read it from * the terminal. We get here when user invoked the program * without parameters, so be helpful. According to the GNU standards: * * If there is one behavior you think is most useful when the output * is to a terminal, and another that you think is most useful when * the output is a file or a pipe, then it is usually best to make * the default behavior the one that is useful with output to a * terminal, and have an option for the other behavior. * * Here we use the --force option to get the other behavior. */ fprintf(stderr, "%s: compressed data not %s a terminal. Use -f to force %scompression.\n", program_name, decompress ? "read from" : "written to", decompress ? "de" : ""); fprintf (stderr, "For help, type: %s -h\n", program_name); do_exit(ERROR); } if (decompress || !ascii) { SET_BINARY_MODE(fileno(stdin)); } if (!test && !list && (!decompress || !ascii)) { SET_BINARY_MODE(fileno(stdout)); } strcpy(ifname, "stdin"); strcpy(ofname, "stdout"); /* Get the file's time stamp and size. */ if (fstat (fileno (stdin), &istat) != 0) { progerror ("standard input"); do_exit (ERROR); } ifile_size = S_ISREG (istat.st_mode) ? istat.st_size : -1; time_stamp.tv_nsec = -1; if (!no_time || list) time_stamp = get_stat_mtime (&istat); clear_bufs(); /* clear input and output buffers */ to_stdout = 1; part_nb = 0; ifd = fileno(stdin); if (decompress) { method = get_method(ifd); if (method < 0) { do_exit(exit_code); /* error message already emitted */ } } if (list) { do_list(ifd, method); return; } /* Actually do the compression/decompression. Loop over zipped members. */ for (;;) { if ((*work)(fileno(stdin), fileno(stdout)) != OK) return; if (input_eof ()) break; method = get_method(ifd); if (method < 0) return; /* error message already emitted */ bytes_out = 0; /* required for length check */ } if (verbose) { if (test) { fprintf(stderr, " OK\n"); } else if (!decompress) { display_ratio(bytes_in-(bytes_out-header_bytes), bytes_in, stderr); fprintf(stderr, "\n"); #ifdef DISPLAY_STDIN_RATIO } else { display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out,stderr); fprintf(stderr, "\n"); #endif } } } /* ======================================================================== * Compress or decompress the given file */ local void treat_file(iname) char *iname; { /* Accept "-" as synonym for stdin */ if (strequ(iname, "-")) { int cflag = to_stdout; treat_stdin(); to_stdout = cflag; return; } /* Check if the input file is present, set ifname and istat: */ ifd = open_input_file (iname, &istat); if (ifd < 0) return; /* If the input name is that of a directory, recurse or ignore: */ if (S_ISDIR(istat.st_mode)) { #if ! NO_DIR if (recursive) { treat_dir (ifd, iname); /* Warning: ifname is now garbage */ return; } #endif close (ifd); WARN ((stderr, "%s: %s is a directory -- ignored\n", program_name, ifname)); return; } if (! to_stdout) { if (! S_ISREG (istat.st_mode)) { WARN ((stderr, "%s: %s is not a directory or a regular file - ignored\n", program_name, ifname)); close (ifd); return; } if (istat.st_mode & S_ISUID) { WARN ((stderr, "%s: %s is set-user-ID on execution - ignored\n", program_name, ifname)); close (ifd); return; } if (istat.st_mode & S_ISGID) { WARN ((stderr, "%s: %s is set-group-ID on execution - ignored\n", program_name, ifname)); close (ifd); return; } if (! force) { if (istat.st_mode & S_ISVTX) { WARN ((stderr, "%s: %s has the sticky bit set - file ignored\n", program_name, ifname)); close (ifd); return; } if (2 <= istat.st_nlink) { WARN ((stderr, "%s: %s has %lu other link%c -- unchanged\n", program_name, ifname, (unsigned long int) istat.st_nlink - 1, istat.st_nlink == 2 ? ' ' : 's')); close (ifd); return; } } } ifile_size = S_ISREG (istat.st_mode) ? istat.st_size : -1; time_stamp.tv_nsec = -1; if (!no_time || list) time_stamp = get_stat_mtime (&istat); /* Generate output file name. For -r and (-t or -l), skip files * without a valid gzip suffix (check done in make_ofname). */ if (to_stdout && !list && !test) { strcpy(ofname, "stdout"); } else if (make_ofname() != OK) { close (ifd); return; } clear_bufs(); /* clear input and output buffers */ part_nb = 0; if (decompress) { method = get_method(ifd); /* updates ofname if original given */ if (method < 0) { close(ifd); return; /* error message already emitted */ } } if (list) { do_list(ifd, method); if (close (ifd) != 0) read_error (); return; } /* If compressing to a file, check if ofname is not ambiguous * because the operating system truncates names. Otherwise, generate * a new ofname and save the original name in the compressed file. */ if (to_stdout) { ofd = fileno(stdout); /* Keep remove_ofname_fd negative. */ } else { if (create_outfile() != OK) return; if (!decompress && save_orig_name && !verbose && !quiet) { fprintf(stderr, "%s: %s compressed to %s\n", program_name, ifname, ofname); } } /* Keep the name even if not truncated except with --no-name: */ if (!save_orig_name) save_orig_name = !no_name; if (verbose) { fprintf(stderr, "%s:\t", ifname); } /* Actually do the compression/decompression. Loop over zipped members. */ for (;;) { if ((*work)(ifd, ofd) != OK) { method = -1; /* force cleanup */ break; } if (input_eof ()) break; method = get_method(ifd); if (method < 0) break; /* error message already emitted */ bytes_out = 0; /* required for length check */ } if (close (ifd) != 0) read_error (); if (!to_stdout) { sigset_t oldset; int unlink_errno; copy_stat (&istat); if (close (ofd) != 0) write_error (); sigprocmask (SIG_BLOCK, &caught_signals, &oldset); remove_ofname_fd = -1; unlink_errno = xunlink (ifname) == 0 ? 0 : errno; sigprocmask (SIG_SETMASK, &oldset, NULL); if (unlink_errno) { WARN ((stderr, "%s: ", program_name)); if (!quiet) { errno = unlink_errno; perror (ifname); } } } if (method == -1) { if (!to_stdout) remove_output_file (); return; } /* Display statistics */ if(verbose) { if (test) { fprintf(stderr, " OK"); } else if (decompress) { display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out,stderr); } else { display_ratio(bytes_in-(bytes_out-header_bytes), bytes_in, stderr); } if (!test && !to_stdout) { fprintf(stderr, " -- replaced with %s", ofname); } fprintf(stderr, "\n"); } } /* ======================================================================== * Create the output file. Return OK or ERROR. * Try several times if necessary to avoid truncating the z_suffix. For * example, do not create a compressed file of name "1234567890123." * Sets save_orig_name to true if the file name has been truncated. * IN assertions: the input file has already been open (ifd is set) and * ofname has already been updated if there was an original name. * OUT assertions: ifd and ofd are closed in case of error. */ local int create_outfile() { int name_shortened = 0; int flags = (O_WRONLY | O_CREAT | O_EXCL | (ascii && decompress ? 0 : O_BINARY)); for (;;) { int open_errno; sigset_t oldset; sigprocmask (SIG_BLOCK, &caught_signals, &oldset); remove_ofname_fd = ofd = OPEN (ofname, flags, RW_USER); open_errno = errno; sigprocmask (SIG_SETMASK, &oldset, NULL); if (0 <= ofd) break; switch (open_errno) { #ifdef ENAMETOOLONG case ENAMETOOLONG: shorten_name (ofname); name_shortened = 1; break; #endif case EEXIST: if (check_ofname () != OK) { close (ifd); return ERROR; } break; default: progerror (ofname); close (ifd); return ERROR; } } if (name_shortened && decompress) { /* name might be too long if an original name was saved */ WARN ((stderr, "%s: %s: warning, name truncated\n", program_name, ofname)); } return OK; } /* ======================================================================== * Return a pointer to the 'z' suffix of a file name, or NULL. For all * systems, ".gz", ".z", ".Z", ".taz", ".tgz", "-gz", "-z" and "_z" are * accepted suffixes, in addition to the value of the --suffix option. * ".tgz" is a useful convention for tar.z files on systems limited * to 3 characters extensions. On such systems, ".?z" and ".??z" are * also accepted suffixes. For Unix, we do not want to accept any * .??z suffix as indicating a compressed file; some people use .xyz * to denote volume data. * On systems allowing multiple versions of the same file (such as VMS), * this function removes any version suffix in the given name. */ local char *get_suffix(name) char *name; { int nlen, slen; char suffix[MAX_SUFFIX+3]; /* last chars of name, forced to lower case */ static char *known_suffixes[] = {NULL, ".gz", ".z", ".taz", ".tgz", "-gz", "-z", "_z", #ifdef MAX_EXT_CHARS "z", #endif NULL}; char **suf = known_suffixes; *suf = z_suffix; if (strequ(z_suffix, "z")) suf++; /* check long suffixes first */ #ifdef SUFFIX_SEP /* strip a version number from the file name */ { char *v = strrchr(name, SUFFIX_SEP); if (v != NULL) *v = '\0'; } #endif nlen = strlen(name); if (nlen <= MAX_SUFFIX+2) { strcpy(suffix, name); } else { strcpy(suffix, name+nlen-MAX_SUFFIX-2); } strlwr(suffix); slen = strlen(suffix); do { int s = strlen(*suf); if (slen > s && suffix[slen-s-1] != PATH_SEP && strequ(suffix + slen - s, *suf)) { return name+nlen-s; } } while (*++suf != NULL); return NULL; } /* Open file NAME with the given flags and mode and store its status into *ST. Return a file descriptor to the newly opened file, or -1 (setting errno) on failure. */ static int open_and_stat (char *name, int flags, mode_t mode, struct stat *st) { int fd; /* Refuse to follow symbolic links unless -c or -f. */ if (!to_stdout && !force) { if (HAVE_WORKING_O_NOFOLLOW) flags |= O_NOFOLLOW; else { #if HAVE_LSTAT || defined lstat if (lstat (name, st) != 0) return -1; else if (S_ISLNK (st->st_mode)) { errno = ELOOP; return -1; } #endif } } fd = OPEN (name, flags, mode); if (0 <= fd && fstat (fd, st) != 0) { int e = errno; close (fd); errno = e; return -1; } return fd; } /* ======================================================================== * Set ifname to the input file name (with a suffix appended if necessary) * and istat to its stats. For decompression, if no file exists with the * original name, try adding successively z_suffix, .gz, .z, -z and .Z. * For MSDOS, we try only z_suffix and z. * Return an open file descriptor or -1. */ static int open_input_file (iname, sbuf) char *iname; struct stat *sbuf; { int ilen; /* strlen(ifname) */ int z_suffix_errno = 0; static char *suffixes[] = {NULL, ".gz", ".z", "-z", ".Z", NULL}; char **suf = suffixes; char *s; #ifdef NO_MULTIPLE_DOTS char *dot; /* pointer to ifname extension, or NULL */ #endif int fd; int open_flags = (O_RDONLY | O_NONBLOCK | O_NOCTTY | (ascii && !decompress ? 0 : O_BINARY)); *suf = z_suffix; if (sizeof ifname - 1 <= strlen (iname)) goto name_too_long; strcpy(ifname, iname); /* If input file exists, return OK. */ fd = open_and_stat (ifname, open_flags, RW_USER, sbuf); if (0 <= fd) return fd; if (!decompress || errno != ENOENT) { progerror(ifname); return -1; } /* file.ext doesn't exist, try adding a suffix (after removing any * version number for VMS). */ s = get_suffix(ifname); if (s != NULL) { progerror(ifname); /* ifname already has z suffix and does not exist */ return -1; } #ifdef NO_MULTIPLE_DOTS dot = strrchr(ifname, '.'); if (dot == NULL) { strcat(ifname, "."); dot = strrchr(ifname, '.'); } #endif ilen = strlen(ifname); if (strequ(z_suffix, ".gz")) suf++; /* Search for all suffixes */ do { char *s0 = s = *suf; strcpy (ifname, iname); #ifdef NO_MULTIPLE_DOTS if (*s == '.') s++; if (*dot == '\0') strcpy (dot, "."); #endif #ifdef MAX_EXT_CHARS if (MAX_EXT_CHARS < strlen (s) + strlen (dot + 1)) dot[MAX_EXT_CHARS + 1 - strlen (s)] = '\0'; #endif if (sizeof ifname <= ilen + strlen (s)) goto name_too_long; strcat(ifname, s); fd = open_and_stat (ifname, open_flags, RW_USER, sbuf); if (0 <= fd) return fd; if (errno != ENOENT) { progerror (ifname); return -1; } if (strequ (s0, z_suffix)) z_suffix_errno = errno; } while (*++suf != NULL); /* No suffix found, complain using z_suffix: */ strcpy(ifname, iname); #ifdef NO_MULTIPLE_DOTS if (*dot == '\0') strcpy(dot, "."); #endif #ifdef MAX_EXT_CHARS if (MAX_EXT_CHARS < z_len + strlen (dot + 1)) dot[MAX_EXT_CHARS + 1 - z_len] = '\0'; #endif strcat(ifname, z_suffix); errno = z_suffix_errno; progerror(ifname); return -1; name_too_long: fprintf (stderr, "%s: %s: file name too long\n", program_name, iname); exit_code = ERROR; return -1; } /* ======================================================================== * Generate ofname given ifname. Return OK, or WARNING if file must be skipped. * Sets save_orig_name to true if the file name has been truncated. */ local int make_ofname() { char *suff; /* ofname z suffix */ strcpy(ofname, ifname); /* strip a version number if any and get the gzip suffix if present: */ suff = get_suffix(ofname); if (decompress) { if (suff == NULL) { /* With -t or -l, try all files (even without .gz suffix) * except with -r (behave as with just -dr). */ if (!recursive && (list || test)) return OK; /* Avoid annoying messages with -r */ if (verbose || (!recursive && !quiet)) { WARN((stderr,"%s: %s: unknown suffix -- ignored\n", program_name, ifname)); } return WARNING; } /* Make a special case for .tgz and .taz: */ strlwr(suff); if (strequ(suff, ".tgz") || strequ(suff, ".taz")) { strcpy(suff, ".tar"); } else { *suff = '\0'; /* strip the z suffix */ } /* ofname might be changed later if infile contains an original name */ } else if (suff && ! force) { /* Avoid annoying messages with -r (see treat_dir()) */ if (verbose || (!recursive && !quiet)) { /* Don't use WARN, as it affects exit status. */ fprintf (stderr, "%s: %s already has %s suffix -- unchanged\n", program_name, ifname, suff); } return WARNING; } else { save_orig_name = 0; #ifdef NO_MULTIPLE_DOTS suff = strrchr(ofname, '.'); if (suff == NULL) { if (sizeof ofname <= strlen (ofname) + 1) goto name_too_long; strcat(ofname, "."); # ifdef MAX_EXT_CHARS if (strequ(z_suffix, "z")) { if (sizeof ofname <= strlen (ofname) + 2) goto name_too_long; strcat(ofname, "gz"); /* enough room */ return OK; } /* On the Atari and some versions of MSDOS, * ENAMETOOLONG does not work correctly. So we * must truncate here. */ } else if (strlen(suff)-1 + z_len > MAX_SUFFIX) { suff[MAX_SUFFIX+1-z_len] = '\0'; save_orig_name = 1; # endif } #endif /* NO_MULTIPLE_DOTS */ if (sizeof ofname <= strlen (ofname) + z_len) goto name_too_long; strcat(ofname, z_suffix); } /* decompress ? */ return OK; name_too_long: WARN ((stderr, "%s: %s: file name too long\n", program_name, ifname)); return WARNING; } /* ======================================================================== * Check the magic number of the input file and update ofname if an * original name was given and to_stdout is not set. * Return the compression method, -1 for error, -2 for warning. * Set inptr to the offset of the next byte to be processed. * Updates time_stamp if there is one and --no-time is not used. * This function may be called repeatedly for an input file consisting * of several contiguous gzip'ed members. * IN assertions: there is at least one remaining compressed member. * If the member is a zip file, it must be the only one. */ local int get_method(in) int in; /* input file descriptor */ { uch flags; /* compression flags */ char magic[2]; /* magic header */ int imagic1; /* like magic[1], but can represent EOF */ ulg stamp; /* time stamp */ /* If --force and --stdout, zcat == cat, so do not complain about * premature end of file: use try_byte instead of get_byte. */ if (force && to_stdout) { magic[0] = (char)try_byte(); imagic1 = try_byte (); magic[1] = (char) imagic1; /* If try_byte returned EOF, magic[1] == (char) EOF. */ } else { magic[0] = (char)get_byte(); if (magic[0]) { magic[1] = (char)get_byte(); imagic1 = 0; /* avoid lint warning */ } else { imagic1 = try_byte (); magic[1] = (char) imagic1; } } method = -1; /* unknown yet */ part_nb++; /* number of parts in gzip file */ header_bytes = 0; last_member = RECORD_IO; /* assume multiple members in gzip file except for record oriented I/O */ if (memcmp(magic, GZIP_MAGIC, 2) == 0 || memcmp(magic, OLD_GZIP_MAGIC, 2) == 0) { method = (int)get_byte(); if (method != DEFLATED) { fprintf(stderr, "%s: %s: unknown method %d -- not supported\n", program_name, ifname, method); exit_code = ERROR; return -1; } work = unzip; flags = (uch)get_byte(); if ((flags & ENCRYPTED) != 0) { fprintf(stderr, "%s: %s is encrypted -- not supported\n", program_name, ifname); exit_code = ERROR; return -1; } if ((flags & CONTINUATION) != 0) { fprintf(stderr, "%s: %s is a multi-part gzip file -- not supported\n", program_name, ifname); exit_code = ERROR; if (force <= 1) return -1; } if ((flags & RESERVED) != 0) { fprintf(stderr, "%s: %s has flags 0x%x -- not supported\n", program_name, ifname, flags); exit_code = ERROR; if (force <= 1) return -1; } stamp = (ulg)get_byte(); stamp |= ((ulg)get_byte()) << 8; stamp |= ((ulg)get_byte()) << 16; stamp |= ((ulg)get_byte()) << 24; if (stamp != 0 && !no_time) { time_stamp.tv_sec = stamp; time_stamp.tv_nsec = 0; } (void)get_byte(); /* Ignore extra flags for the moment */ (void)get_byte(); /* Ignore OS type for the moment */ if ((flags & CONTINUATION) != 0) { unsigned part = (unsigned)get_byte(); part |= ((unsigned)get_byte())<<8; if (verbose) { fprintf(stderr,"%s: %s: part number %u\n", program_name, ifname, part); } } if ((flags & EXTRA_FIELD) != 0) { unsigned len = (unsigned)get_byte(); len |= ((unsigned)get_byte())<<8; if (verbose) { fprintf(stderr,"%s: %s: extra field of %u bytes ignored\n", program_name, ifname, len); } while (len--) (void)get_byte(); } /* Get original file name if it was truncated */ if ((flags & ORIG_NAME) != 0) { if (no_name || (to_stdout && !list) || part_nb > 1) { /* Discard the old name */ char c; /* dummy used for NeXTstep 3.0 cc optimizer bug */ do {c=get_byte();} while (c != 0); } else { /* Copy the base name. Keep a directory prefix intact. */ char *p = gzip_base_name (ofname); char *base = p; for (;;) { *p = (char)get_char(); if (*p++ == '\0') break; if (p >= ofname+sizeof(ofname)) { gzip_error ("corrupted input -- file name too large"); } } p = gzip_base_name (base); memmove (base, p, strlen (p) + 1); /* If necessary, adapt the name to local OS conventions: */ if (!list) { MAKE_LEGAL_NAME(base); if (base) list=0; /* avoid warning about unused variable */ } } /* no_name || to_stdout */ } /* ORIG_NAME */ /* Discard file comment if any */ if ((flags & COMMENT) != 0) { while (get_char() != 0) /* null */ ; } if (part_nb == 1) { header_bytes = inptr + 2*sizeof(long); /* include crc and size */ } } else if (memcmp(magic, PKZIP_MAGIC, 2) == 0 && inptr == 2 && memcmp((char*)inbuf, PKZIP_MAGIC, 4) == 0) { /* To simplify the code, we support a zip file when alone only. * We are thus guaranteed that the entire local header fits in inbuf. */ inptr = 0; work = unzip; if (check_zipfile(in) != OK) return -1; /* check_zipfile may get ofname from the local header */ last_member = 1; } else if (memcmp(magic, PACK_MAGIC, 2) == 0) { work = unpack; method = PACKED; } else if (memcmp(magic, LZW_MAGIC, 2) == 0) { work = unlzw; method = COMPRESSED; last_member = 1; } else if (memcmp(magic, LZH_MAGIC, 2) == 0) { work = unlzh; method = LZHED; last_member = 1; } else if (force && to_stdout && !list) { /* pass input unchanged */ method = STORED; work = copy; inptr = 0; last_member = 1; } if (method >= 0) return method; if (part_nb == 1) { fprintf (stderr, "\n%s: %s: not in gzip format\n", program_name, ifname); exit_code = ERROR; return -1; } else { if (magic[0] == 0) { int inbyte; for (inbyte = imagic1; inbyte == 0; inbyte = try_byte ()) continue; if (inbyte == EOF) { if (verbose) WARN ((stderr, "\n%s: %s: decompression OK, trailing zero bytes ignored\n", program_name, ifname)); return -3; } } WARN((stderr, "\n%s: %s: decompression OK, trailing garbage ignored\n", program_name, ifname)); return -2; } } /* ======================================================================== * Display the characteristics of the compressed file. * If the given method is < 0, display the accumulated totals. * IN assertions: time_stamp, header_bytes and ifile_size are initialized. */ local void do_list(ifd, method) int ifd; /* input file descriptor */ int method; /* compression method */ { ulg crc; /* original crc */ static int first_time = 1; static char* methods[MAX_METHODS] = { "store", /* 0 */ "compr", /* 1 */ "pack ", /* 2 */ "lzh ", /* 3 */ "", "", "", "", /* 4 to 7 reserved */ "defla"}; /* 8 */ int positive_off_t_width = 1; off_t o; for (o = OFF_T_MAX; 9 < o; o /= 10) { positive_off_t_width++; } if (first_time && method >= 0) { first_time = 0; if (verbose) { printf("method crc date time "); } if (!quiet) { printf("%*.*s %*.*s ratio uncompressed_name\n", positive_off_t_width, positive_off_t_width, "compressed", positive_off_t_width, positive_off_t_width, "uncompressed"); } } else if (method < 0) { if (total_in <= 0 || total_out <= 0) return; if (verbose) { printf(" "); } if (verbose || !quiet) { fprint_off(stdout, total_in, positive_off_t_width); printf(" "); fprint_off(stdout, total_out, positive_off_t_width); printf(" "); } display_ratio(total_out-(total_in-header_bytes), total_out, stdout); /* header_bytes is not meaningful but used to ensure the same * ratio if there is a single file. */ printf(" (totals)\n"); return; } crc = (ulg)~0; /* unknown */ bytes_out = -1L; bytes_in = ifile_size; #if RECORD_IO == 0 if (method == DEFLATED && !last_member) { /* Get the crc and uncompressed size for gzip'ed (not zip'ed) files. * If the lseek fails, we could use read() to get to the end, but * --list is used to get quick results. * Use "gunzip < foo.gz | wc -c" to get the uncompressed size if * you are not concerned about speed. */ bytes_in = lseek(ifd, (off_t)(-8), SEEK_END); if (bytes_in != -1L) { uch buf[8]; bytes_in += 8L; if (read(ifd, (char*)buf, sizeof(buf)) != sizeof(buf)) { read_error(); } crc = LG(buf); bytes_out = LG(buf+4); } } #endif /* RECORD_IO */ if (verbose) { struct tm *tm = localtime (&time_stamp.tv_sec); printf ("%5s %08lx ", methods[method], crc); if (tm) printf ("%s%3d %02d:%02d ", ("Jan\0Feb\0Mar\0Apr\0May\0Jun\0Jul\0Aug\0Sep\0Oct\0Nov\0Dec" + 4 * tm->tm_mon), tm->tm_mday, tm->tm_hour, tm->tm_min); else printf ("??? ?? ??:?? "); } fprint_off(stdout, bytes_in, positive_off_t_width); printf(" "); fprint_off(stdout, bytes_out, positive_off_t_width); printf(" "); if (bytes_in == -1L) { total_in = -1L; bytes_in = bytes_out = header_bytes = 0; } else if (total_in >= 0) { total_in += bytes_in; } if (bytes_out == -1L) { total_out = -1L; bytes_in = bytes_out = header_bytes = 0; } else if (total_out >= 0) { total_out += bytes_out; } display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out, stdout); printf(" %s\n", ofname); } /* ======================================================================== * Shorten the given name by one character, or replace a .tar extension * with .tgz. Truncate the last part of the name which is longer than * MIN_PART characters: 1234.678.012.gz -> 123.678.012.gz. If the name * has only parts shorter than MIN_PART truncate the longest part. * For decompression, just remove the last character of the name. * * IN assertion: for compression, the suffix of the given name is z_suffix. */ local void shorten_name(name) char *name; { int len; /* length of name without z_suffix */ char *trunc = NULL; /* character to be truncated */ int plen; /* current part length */ int min_part = MIN_PART; /* current minimum part length */ char *p; len = strlen(name); if (decompress) { if (len <= 1) gzip_error ("name too short"); name[len-1] = '\0'; return; } p = get_suffix(name); if (! p) gzip_error ("can't recover suffix\n"); *p = '\0'; save_orig_name = 1; /* compress 1234567890.tar to 1234567890.tgz */ if (len > 4 && strequ(p-4, ".tar")) { strcpy(p-4, ".tgz"); return; } /* Try keeping short extensions intact: * 1234.678.012.gz -> 123.678.012.gz */ do { p = strrchr(name, PATH_SEP); p = p ? p+1 : name; while (*p) { plen = strcspn(p, PART_SEP); p += plen; if (plen > min_part) trunc = p-1; if (*p) p++; } } while (trunc == NULL && --min_part != 0); if (trunc != NULL) { do { trunc[0] = trunc[1]; } while (*trunc++); trunc--; } else { trunc = strrchr(name, PART_SEP[0]); if (!trunc) gzip_error ("internal error in shorten_name"); if (trunc[1] == '\0') trunc--; /* force truncation */ } strcpy(trunc, z_suffix); } /* ======================================================================== * The compressed file already exists, so ask for confirmation. * Return ERROR if the file must be skipped. */ local int check_ofname() { /* Ask permission to overwrite the existing file */ if (!force) { int ok = 0; fprintf (stderr, "%s: %s already exists;", program_name, ofname); if (foreground && isatty(fileno(stdin))) { fprintf(stderr, " do you wish to overwrite (y or n)? "); fflush(stderr); ok = yesno(); } if (!ok) { fprintf(stderr, "\tnot overwritten\n"); if (exit_code == OK) exit_code = WARNING; return ERROR; } } if (xunlink (ofname)) { progerror(ofname); return ERROR; } return OK; } /* ======================================================================== * Copy modes, times, ownership from input file to output file. * IN assertion: to_stdout is false. */ local void copy_stat(ifstat) struct stat *ifstat; { mode_t mode = ifstat->st_mode & S_IRWXUGO; int r; #ifndef NO_UTIME struct timespec timespec[2]; timespec[0] = get_stat_atime (ifstat); timespec[1] = get_stat_mtime (ifstat); if (decompress && 0 <= time_stamp.tv_nsec && ! (timespec[1].tv_sec == time_stamp.tv_sec && timespec[1].tv_nsec == time_stamp.tv_nsec)) { timespec[1] = time_stamp; if (verbose > 1) { fprintf(stderr, "%s: time stamp restored\n", ofname); } } if (gl_futimens (ofd, ofname, timespec) != 0) { int e = errno; WARN ((stderr, "%s: ", program_name)); if (!quiet) { errno = e; perror (ofname); } } #endif #ifndef NO_CHOWN # if HAVE_FCHOWN fchown (ofd, ifstat->st_uid, ifstat->st_gid); /* Copy ownership */ # elif HAVE_CHOWN chown(ofname, ifstat->st_uid, ifstat->st_gid); /* Copy ownership */ # endif #endif /* Copy the protection modes */ #if HAVE_FCHMOD r = fchmod (ofd, mode); #else r = chmod (ofname, mode); #endif if (r != 0) { int e = errno; WARN ((stderr, "%s: ", program_name)); if (!quiet) { errno = e; perror(ofname); } } } #if ! NO_DIR /* ======================================================================== * Recurse through the given directory. This code is taken from ncompress. */ local void treat_dir (fd, dir) int fd; char *dir; { struct dirent *dp; DIR *dirp; char nbuf[MAX_PATH_LEN]; int len; #if HAVE_FDOPENDIR dirp = fdopendir (fd); #else close (fd); dirp = opendir(dir); #endif if (dirp == NULL) { progerror(dir); #if HAVE_FDOPENDIR close (fd); #endif return ; } /* ** WARNING: the following algorithm could occasionally cause ** compress to produce error warnings of the form "<filename>.gz ** already has .gz suffix - ignored". This occurs when the ** .gz output file is inserted into the directory below ** readdir's current pointer. ** These warnings are harmless but annoying, so they are suppressed ** with option -r (except when -v is on). An alternative ** to allowing this would be to store the entire directory ** list in memory, then compress the entries in the stored ** list. Given the depth-first recursive algorithm used here, ** this could use up a tremendous amount of memory. I don't ** think it's worth it. -- Dave Mack ** (An other alternative might be two passes to avoid depth-first.) */ while ((errno = 0, dp = readdir(dirp)) != NULL) { if (strequ(dp->d_name,".") || strequ(dp->d_name,"..")) { continue; } len = strlen(dir); if (len + _D_EXACT_NAMLEN (dp) + 1 < MAX_PATH_LEN - 1) { strcpy(nbuf,dir); if (len != 0 /* dir = "" means current dir on Amiga */ #ifdef PATH_SEP2 && dir[len-1] != PATH_SEP2 #endif #ifdef PATH_SEP3 && dir[len-1] != PATH_SEP3 #endif ) { nbuf[len++] = PATH_SEP; } strcpy(nbuf+len, dp->d_name); treat_file(nbuf); } else { fprintf(stderr,"%s: %s/%s: pathname too long\n", program_name, dir, dp->d_name); exit_code = ERROR; } } if (errno != 0) progerror(dir); if (CLOSEDIR(dirp) != 0) progerror(dir); } #endif /* ! NO_DIR */ /* Make sure signals get handled properly. */ static void install_signal_handlers () { int nsigs = sizeof handled_sig / sizeof handled_sig[0]; int i; #if SA_NOCLDSTOP struct sigaction act; sigemptyset (&caught_signals); for (i = 0; i < nsigs; i++) { sigaction (handled_sig[i], NULL, &act); if (act.sa_handler != SIG_IGN) sigaddset (&caught_signals, handled_sig[i]); } act.sa_handler = abort_gzip_signal; act.sa_mask = caught_signals; act.sa_flags = 0; for (i = 0; i < nsigs; i++) if (sigismember (&caught_signals, handled_sig[i])) { if (i == 0) foreground = 1; sigaction (handled_sig[i], &act, NULL); } #else for (i = 0; i < nsigs; i++) if (signal (handled_sig[i], SIG_IGN) != SIG_IGN) { if (i == 0) foreground = 1; signal (handled_sig[i], abort_gzip_signal); siginterrupt (handled_sig[i], 1); } #endif } /* ======================================================================== * Free all dynamically allocated variables and exit with the given code. */ local void do_exit(exitcode) int exitcode; { static int in_exit = 0; if (in_exit) exit(exitcode); in_exit = 1; free(env); env = NULL; free(args); args = NULL; FREE(inbuf); FREE(outbuf); FREE(d_buf); FREE(window); #ifndef MAXSEG_64K FREE(tab_prefix); #else FREE(tab_prefix0); FREE(tab_prefix1); #endif exit(exitcode); } /* ======================================================================== * Close and unlink the output file. */ static void remove_output_file () { int fd; sigset_t oldset; sigprocmask (SIG_BLOCK, &caught_signals, &oldset); fd = remove_ofname_fd; if (0 <= fd) { remove_ofname_fd = -1; close (fd); xunlink (ofname); } sigprocmask (SIG_SETMASK, &oldset, NULL); } /* ======================================================================== * Error handler. */ void abort_gzip () { remove_output_file (); do_exit(ERROR); } /* ======================================================================== * Signal handler. */ static RETSIGTYPE abort_gzip_signal (sig) int sig; { if (! SA_NOCLDSTOP) signal (sig, SIG_IGN); remove_output_file (); if (sig == exiting_signal) _exit (WARNING); signal (sig, SIG_DFL); raise (sig); }
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/gzip_2009-10-09-1a085b1446-118a107f2d.c
manybugs_data_25
/* mpn_powm -- Compute R = U^E mod M. Contributed to the GNU project by Torbjorn Granlund. THE FUNCTIONS IN THIS FILE ARE INTERNAL WITH MUTABLE INTERFACES. IT IS ONLY SAFE TO REACH THEM THROUGH DOCUMENTED INTERFACES. IN FACT, IT IS ALMOST GUARANTEED THAT THEY WILL CHANGE OR DISAPPEAR IN A FUTURE GNU MP RELEASE. Copyright 2007, 2008, 2009 Free Software Foundation, Inc. This file is part of the GNU MP Library. The GNU MP Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. The GNU MP Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU MP Library. If not, see http://www.gnu.org/licenses/. */ /* BASIC ALGORITHM, Compute U^E mod M, where M < B^n is odd. 1. W <- U 2. T <- (B^n * U) mod M Convert to REDC form 3. Compute table U^1, U^3, U^5... of E-dependent size 4. While there are more bits in E W <- power left-to-right base-k TODO: * Make getbits a macro, thereby allowing it to update the index operand. That will simplify the code using getbits. (Perhaps make getbits' sibling getbit then have similar form, for symmetry.) * Write an itch function. Or perhaps get rid of tp parameter since the huge pp area is allocated locally anyway? * Choose window size without looping. (Superoptimize or think(tm).) * Handle small bases with initial, reduction-free exponentiation. * Call new division functions, not mpn_tdiv_qr. * Consider special code for one-limb M. * How should we handle the redc1/redc2/redc_n choice? - redc1: T(binvert_1limb) + e * (n) * (T(mullo-1x1) + n*T(addmul_1)) - redc2: T(binvert_2limbs) + e * (n/2) * (T(mullo-2x2) + n*T(addmul_2)) - redc_n: T(binvert_nlimbs) + e * (T(mullo-nxn) + T(M(n))) This disregards the addmul_N constant term, but we could think of that as part of the respective mullo. * When U (the base) is small, we should start the exponentiation with plain operations, then convert that partial result to REDC form. * When U is just one limb, should it be handled without the k-ary tricks? We could keep a factor of B^n in W, but use U' = BU as base. After multiplying by this (pseudo two-limb) number, we need to multiply by 1/B mod M. */ #include "gmp.h" #include "gmp-impl.h" #include "longlong.h" #if HAVE_NATIVE_mpn_addmul_2 || HAVE_NATIVE_mpn_redc_2 #define WANT_REDC_2 1 #endif #define getbit(p,bi) \ ((p[(bi - 1) / GMP_LIMB_BITS] >> (bi - 1) % GMP_LIMB_BITS) & 1) static inline mp_limb_t getbits (const mp_limb_t *p, mp_bitcnt_t bi, int nbits) { int nbits_in_r; mp_limb_t r; mp_size_t i; if (bi < nbits) { return p[0] & (((mp_limb_t) 1 << bi) - 1); } else { bi -= nbits; /* bit index of low bit to extract */ i = bi / GMP_NUMB_BITS; /* word index of low bit to extract */ bi %= GMP_NUMB_BITS; /* bit index in low word */ r = p[i] >> bi; /* extract (low) bits */ nbits_in_r = GMP_NUMB_BITS - bi; /* number of bits now in r */ if (nbits_in_r < nbits) /* did we get enough bits? */ r += p[i + 1] << nbits_in_r; /* prepend bits from higher word */ return r & (((mp_limb_t ) 1 << nbits) - 1); } } static inline int win_size (mp_bitcnt_t eb) { int k; static mp_bitcnt_t x[] = {0,7,25,81,241,673,1793,4609,11521,28161,~(mp_bitcnt_t)0}; for (k = 1; eb > x[k]; k++) ; return k; } /* Convert U to REDC form, U_r = B^n * U mod M */ static void redcify (mp_ptr rp, mp_srcptr up, mp_size_t un, mp_srcptr mp, mp_size_t n) { mp_ptr tp, qp; TMP_DECL; TMP_MARK; tp = TMP_ALLOC_LIMBS (un + n); qp = TMP_ALLOC_LIMBS (un + 1); /* FIXME: Put at tp+? */ MPN_ZERO (tp, n); MPN_COPY (tp + n, up, un); mpn_tdiv_qr (qp, rp, 0L, tp, un + n, mp, n); TMP_FREE; } /* rp[n-1..0] = bp[bn-1..0] ^ ep[en-1..0] mod mp[n-1..0] Requires that mp[n-1..0] is odd. Requires that ep[en-1..0] is > 1. Uses scratch space at tp of MAX(mpn_binvert_itch(n),3n+1) limbs. */ void mpn_powm (mp_ptr rp, mp_srcptr bp, mp_size_t bn, mp_srcptr ep, mp_size_t en, mp_srcptr mp, mp_size_t n, mp_ptr tp) { mp_limb_t ip[2], *mip; int cnt; mp_bitcnt_t ebi; int windowsize, this_windowsize; mp_limb_t expbits; mp_ptr pp, this_pp; mp_ptr b2p; long i; TMP_DECL; ASSERT (en > 1 || (en == 1 && ep[0] > 1)); ASSERT (n >= 1 && ((mp[0] & 1) != 0)); TMP_MARK; count_leading_zeros (cnt, ep[en - 1]); ebi = (mp_bitcnt_t) en * GMP_LIMB_BITS - cnt; #if 0 if (bn < n) { /* Do the first few exponent bits without mod reductions, until the result is greater than the mod argument. */ for (;;) { mpn_sqr (tp, this_pp, tn); tn = tn * 2 - 1, tn += tp[tn] != 0; if (getbit (ep, ebi) != 0) mpn_mul (..., tp, tn, bp, bn); ebi--; } } #endif windowsize = win_size (ebi); #if WANT_REDC_2 if (BELOW_THRESHOLD (n, REDC_1_TO_REDC_2_THRESHOLD)) { mip = ip; binvert_limb (mip[0], mp[0]); mip[0] = -mip[0]; } else if (BELOW_THRESHOLD (n, REDC_2_TO_REDC_N_THRESHOLD)) { mip = ip; mpn_binvert (mip, mp, 2, tp); mip[0] = -mip[0]; mip[1] = ~mip[1]; } #else if (BELOW_THRESHOLD (n, REDC_1_TO_REDC_N_THRESHOLD)) { mip = ip; binvert_limb (mip[0], mp[0]); mip[0] = -mip[0]; } #endif else { mip = TMP_ALLOC_LIMBS (n); mpn_binvert (mip, mp, n, tp); } pp = TMP_ALLOC_LIMBS (n << (windowsize - 1)); this_pp = pp; redcify (this_pp, bp, bn, mp, n); b2p = tp + 2*n; /* Store b^2 in b2. */ mpn_sqr (tp, this_pp, n); #if WANT_REDC_2 if (BELOW_THRESHOLD (n, REDC_1_TO_REDC_2_THRESHOLD)) mpn_redc_1 (b2p, tp, mp, n, mip[0]); else if (BELOW_THRESHOLD (n, REDC_2_TO_REDC_N_THRESHOLD)) mpn_redc_2 (b2p, tp, mp, n, mip); #else if (BELOW_THRESHOLD (n, REDC_1_TO_REDC_N_THRESHOLD)) mpn_redc_1 (b2p, tp, mp, n, mip[0]); #endif else mpn_redc_n (b2p, tp, mp, n, mip); /* Precompute odd powers of b and put them in the temporary area at pp. */ for (i = (1 << (windowsize - 1)) - 1; i > 0; i--) { mpn_mul_n (tp, this_pp, b2p, n); this_pp += n; #if WANT_REDC_2 if (BELOW_THRESHOLD (n, REDC_1_TO_REDC_2_THRESHOLD)) mpn_redc_1 (this_pp, tp, mp, n, mip[0]); else if (BELOW_THRESHOLD (n, REDC_2_TO_REDC_N_THRESHOLD)) mpn_redc_2 (this_pp, tp, mp, n, mip); #else if (BELOW_THRESHOLD (n, REDC_1_TO_REDC_N_THRESHOLD)) mpn_redc_1 (this_pp, tp, mp, n, mip[0]); #endif else mpn_redc_n (this_pp, tp, mp, n, mip); } expbits = getbits (ep, ebi, windowsize); if (ebi < windowsize) ebi = 0; else ebi -= windowsize; count_trailing_zeros (cnt, expbits); ebi += cnt; expbits >>= cnt; MPN_COPY (rp, pp + n * (expbits >> 1), n); #define INNERLOOP \ while (ebi != 0) \ { \ while (getbit (ep, ebi) == 0) \ { \ MPN_SQR (tp, rp, n); \ MPN_REDUCE (rp, tp, mp, n, mip); \ ebi--; \ if (ebi == 0) \ goto done; \ } \ \ /* The next bit of the exponent is 1. Now extract the largest \ block of bits <= windowsize, and such that the least \ significant bit is 1. */ \ \ expbits = getbits (ep, ebi, windowsize); \ this_windowsize = windowsize; \ if (ebi < windowsize) \ { \ this_windowsize -= windowsize - ebi; \ ebi = 0; \ } \ else \ ebi -= windowsize; \ \ count_trailing_zeros (cnt, expbits); \ this_windowsize -= cnt; \ ebi += cnt; \ expbits >>= cnt; \ \ do \ { \ MPN_SQR (tp, rp, n); \ MPN_REDUCE (rp, tp, mp, n, mip); \ this_windowsize--; \ } \ while (this_windowsize != 0); \ \ MPN_MUL_N (tp, rp, pp + n * (expbits >> 1), n); \ MPN_REDUCE (rp, tp, mp, n, mip); \ } #if WANT_REDC_2 if (REDC_1_TO_REDC_2_THRESHOLD < MUL_TOOM22_THRESHOLD) { if (BELOW_THRESHOLD (n, REDC_1_TO_REDC_2_THRESHOLD)) { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_basecase (r,a,n,b,n) #define MPN_SQR(r,a,n) mpn_sqr_basecase (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_1 (rp, tp, mp, n, mip[0]) INNERLOOP; } else if (BELOW_THRESHOLD (n, MUL_TOOM22_THRESHOLD)) { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_basecase (r,a,n,b,n) #define MPN_SQR(r,a,n) mpn_sqr_basecase (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_2 (rp, tp, mp, n, mip) INNERLOOP; } else if (BELOW_THRESHOLD (n, REDC_2_TO_REDC_N_THRESHOLD)) { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_n (r,a,b,n) #define MPN_SQR(r,a,n) mpn_sqr (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_2 (rp, tp, mp, n, mip) INNERLOOP; } else { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_n (r,a,b,n) #define MPN_SQR(r,a,n) mpn_sqr (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_n (rp, tp, mp, n, mip) INNERLOOP; } } else { if (BELOW_THRESHOLD (n, MUL_TOOM22_THRESHOLD)) { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_basecase (r,a,n,b,n) #define MPN_SQR(r,a,n) mpn_sqr_basecase (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_1 (rp, tp, mp, n, mip[0]) INNERLOOP; } else if (BELOW_THRESHOLD (n, REDC_1_TO_REDC_2_THRESHOLD)) { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_n (r,a,b,n) #define MPN_SQR(r,a,n) mpn_sqr (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_1 (rp, tp, mp, n, mip[0]) INNERLOOP; } else if (BELOW_THRESHOLD (n, REDC_2_TO_REDC_N_THRESHOLD)) { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_n (r,a,b,n) #define MPN_SQR(r,a,n) mpn_sqr (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_2 (rp, tp, mp, n, mip) INNERLOOP; } else { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_n (r,a,b,n) #define MPN_SQR(r,a,n) mpn_sqr (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_n (rp, tp, mp, n, mip) INNERLOOP; } } #else /* WANT_REDC_2 */ if (REDC_1_TO_REDC_N_THRESHOLD < MUL_TOOM22_THRESHOLD) { if (BELOW_THRESHOLD (n, REDC_1_TO_REDC_N_THRESHOLD)) { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_basecase (r,a,n,b,n) #define MPN_SQR(r,a,n) mpn_sqr_basecase (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_1 (rp, tp, mp, n, mip[0]) INNERLOOP; } else if (BELOW_THRESHOLD (n, MUL_TOOM22_THRESHOLD)) { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_basecase (r,a,n,b,n) #define MPN_SQR(r,a,n) mpn_sqr_basecase (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_n (rp, tp, mp, n, mip) INNERLOOP; } else { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_n (r,a,b,n) #define MPN_SQR(r,a,n) mpn_sqr (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_n (rp, tp, mp, n, mip) INNERLOOP; } } else { if (BELOW_THRESHOLD (n, MUL_TOOM22_THRESHOLD)) { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_basecase (r,a,n,b,n) #define MPN_SQR(r,a,n) mpn_sqr_basecase (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_1 (rp, tp, mp, n, mip[0]) INNERLOOP; } else if (BELOW_THRESHOLD (n, REDC_1_TO_REDC_N_THRESHOLD)) { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_n (r,a,b,n) #define MPN_SQR(r,a,n) mpn_sqr (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_1 (rp, tp, mp, n, mip[0]) INNERLOOP; } else { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_n (r,a,b,n) #define MPN_SQR(r,a,n) mpn_sqr (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_n (rp, tp, mp, n, mip) INNERLOOP; } } #endif /* WANT_REDC_2 */ done: MPN_COPY (tp, rp, n); MPN_ZERO (tp + n, n); #if WANT_REDC_2 if (BELOW_THRESHOLD (n, REDC_1_TO_REDC_2_THRESHOLD)) mpn_redc_1 (rp, tp, mp, n, mip[0]); else if (BELOW_THRESHOLD (n, REDC_2_TO_REDC_N_THRESHOLD)) mpn_redc_2 (rp, tp, mp, n, mip); #else if (BELOW_THRESHOLD (n, REDC_1_TO_REDC_N_THRESHOLD)) mpn_redc_1 (rp, tp, mp, n, mip[0]); #endif else mpn_redc_n (rp, tp, mp, n, mip); if (mpn_cmp (rp, mp, n) >= 0) mpn_sub_n (rp, rp, mp, n); TMP_FREE; } /* mpn_powm -- Compute R = U^E mod M. Contributed to the GNU project by Torbjorn Granlund. THE FUNCTIONS IN THIS FILE ARE INTERNAL WITH MUTABLE INTERFACES. IT IS ONLY SAFE TO REACH THEM THROUGH DOCUMENTED INTERFACES. IN FACT, IT IS ALMOST GUARANTEED THAT THEY WILL CHANGE OR DISAPPEAR IN A FUTURE GNU MP RELEASE. Copyright 2007, 2008, 2009 Free Software Foundation, Inc. This file is part of the GNU MP Library. The GNU MP Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. The GNU MP Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU MP Library. If not, see http://www.gnu.org/licenses/. */ /* BASIC ALGORITHM, Compute U^E mod M, where M < B^n is odd. 1. W <- U 2. T <- (B^n * U) mod M Convert to REDC form 3. Compute table U^1, U^3, U^5... of E-dependent size 4. While there are more bits in E W <- power left-to-right base-k TODO: * Make getbits a macro, thereby allowing it to update the index operand. That will simplify the code using getbits. (Perhaps make getbits' sibling getbit then have similar form, for symmetry.) * Write an itch function. Or perhaps get rid of tp parameter since the huge pp area is allocated locally anyway? * Choose window size without looping. (Superoptimize or think(tm).) * Handle small bases with initial, reduction-free exponentiation. * Call new division functions, not mpn_tdiv_qr. * Consider special code for one-limb M. * How should we handle the redc1/redc2/redc_n choice? - redc1: T(binvert_1limb) + e * (n) * (T(mullo-1x1) + n*T(addmul_1)) - redc2: T(binvert_2limbs) + e * (n/2) * (T(mullo-2x2) + n*T(addmul_2)) - redc_n: T(binvert_nlimbs) + e * (T(mullo-nxn) + T(M(n))) This disregards the addmul_N constant term, but we could think of that as part of the respective mullo. * When U (the base) is small, we should start the exponentiation with plain operations, then convert that partial result to REDC form. * When U is just one limb, should it be handled without the k-ary tricks? We could keep a factor of B^n in W, but use U' = BU as base. After multiplying by this (pseudo two-limb) number, we need to multiply by 1/B mod M. */ #include "gmp.h" #include "gmp-impl.h" #include "longlong.h" #if HAVE_NATIVE_mpn_addmul_2 || HAVE_NATIVE_mpn_redc_2 #define WANT_REDC_2 1 #endif #define getbit(p,bi) \ ((p[(bi - 1) / GMP_LIMB_BITS] >> (bi - 1) % GMP_LIMB_BITS) & 1) static inline mp_limb_t getbits (const mp_limb_t *p, mp_bitcnt_t bi, int nbits) { int nbits_in_r; mp_limb_t r; mp_size_t i; if (bi < nbits) { return p[0] & (((mp_limb_t) 1 << bi) - 1); } else { bi -= nbits; /* bit index of low bit to extract */ i = bi / GMP_NUMB_BITS; /* word index of low bit to extract */ bi %= GMP_NUMB_BITS; /* bit index in low word */ r = p[i] >> bi; /* extract (low) bits */ nbits_in_r = GMP_NUMB_BITS - bi; /* number of bits now in r */ if (nbits_in_r < nbits) /* did we get enough bits? */ r += p[i + 1] << nbits_in_r; /* prepend bits from higher word */ return r & (((mp_limb_t ) 1 << nbits) - 1); } } static inline int win_size (mp_bitcnt_t eb) { int k; static mp_bitcnt_t x[] = {0,7,25,81,241,673,1793,4609,11521,28161,~(mp_bitcnt_t)0}; for (k = 1; eb > x[k]; k++) ; return k; } /* Convert U to REDC form, U_r = B^n * U mod M */ static void redcify (mp_ptr rp, mp_srcptr up, mp_size_t un, mp_srcptr mp, mp_size_t n) { mp_ptr tp, qp; TMP_DECL; TMP_MARK; tp = TMP_ALLOC_LIMBS (un + n); qp = TMP_ALLOC_LIMBS (un + 1); /* FIXME: Put at tp+? */ MPN_ZERO (tp, n); MPN_COPY (tp + n, up, un); mpn_tdiv_qr (qp, rp, 0L, tp, un + n, mp, n); TMP_FREE; } /* rp[n-1..0] = bp[bn-1..0] ^ ep[en-1..0] mod mp[n-1..0] Requires that mp[n-1..0] is odd. Requires that ep[en-1..0] is > 1. Uses scratch space at tp of MAX(mpn_binvert_itch(n),2n) limbs. */ void mpn_powm (mp_ptr rp, mp_srcptr bp, mp_size_t bn, mp_srcptr ep, mp_size_t en, mp_srcptr mp, mp_size_t n, mp_ptr tp) { mp_limb_t ip[2], *mip; int cnt; mp_bitcnt_t ebi; int windowsize, this_windowsize; mp_limb_t expbits; mp_ptr pp, this_pp; long i; TMP_DECL; ASSERT (en > 1 || (en == 1 && ep[0] > 1)); ASSERT (n >= 1 && ((mp[0] & 1) != 0)); TMP_MARK; count_leading_zeros (cnt, ep[en - 1]); ebi = (mp_bitcnt_t) en * GMP_LIMB_BITS - cnt; #if 0 if (bn < n) { /* Do the first few exponent bits without mod reductions, until the result is greater than the mod argument. */ for (;;) { mpn_sqr (tp, this_pp, tn); tn = tn * 2 - 1, tn += tp[tn] != 0; if (getbit (ep, ebi) != 0) mpn_mul (..., tp, tn, bp, bn); ebi--; } } #endif windowsize = win_size (ebi); #if WANT_REDC_2 if (BELOW_THRESHOLD (n, REDC_1_TO_REDC_2_THRESHOLD)) { mip = ip; binvert_limb (mip[0], mp[0]); mip[0] = -mip[0]; } else if (BELOW_THRESHOLD (n, REDC_2_TO_REDC_N_THRESHOLD)) { mip = ip; mpn_binvert (mip, mp, 2, tp); mip[0] = -mip[0]; mip[1] = ~mip[1]; } #else if (BELOW_THRESHOLD (n, REDC_1_TO_REDC_N_THRESHOLD)) { mip = ip; binvert_limb (mip[0], mp[0]); mip[0] = -mip[0]; } #endif else { mip = TMP_ALLOC_LIMBS (n); mpn_binvert (mip, mp, n, tp); } pp = TMP_ALLOC_LIMBS (n << (windowsize - 1)); this_pp = pp; redcify (this_pp, bp, bn, mp, n); /* Store b^2 at rp. */ mpn_sqr (tp, this_pp, n); #if WANT_REDC_2 if (BELOW_THRESHOLD (n, REDC_1_TO_REDC_2_THRESHOLD)) mpn_redc_1 (rp, tp, mp, n, mip[0]); else if (BELOW_THRESHOLD (n, REDC_2_TO_REDC_N_THRESHOLD)) mpn_redc_2 (rp, tp, mp, n, mip); #else if (BELOW_THRESHOLD (n, REDC_1_TO_REDC_N_THRESHOLD)) mpn_redc_1 (rp, tp, mp, n, mip[0]); #endif else mpn_redc_n (rp, tp, mp, n, mip); /* Precompute odd powers of b and put them in the temporary area at pp. */ for (i = (1 << (windowsize - 1)) - 1; i > 0; i--) { mpn_mul_n (tp, this_pp, rp, n); this_pp += n; #if WANT_REDC_2 if (BELOW_THRESHOLD (n, REDC_1_TO_REDC_2_THRESHOLD)) mpn_redc_1 (this_pp, tp, mp, n, mip[0]); else if (BELOW_THRESHOLD (n, REDC_2_TO_REDC_N_THRESHOLD)) mpn_redc_2 (this_pp, tp, mp, n, mip); #else if (BELOW_THRESHOLD (n, REDC_1_TO_REDC_N_THRESHOLD)) mpn_redc_1 (this_pp, tp, mp, n, mip[0]); #endif else mpn_redc_n (this_pp, tp, mp, n, mip); } expbits = getbits (ep, ebi, windowsize); if (ebi < windowsize) ebi = 0; else ebi -= windowsize; count_trailing_zeros (cnt, expbits); ebi += cnt; expbits >>= cnt; MPN_COPY (rp, pp + n * (expbits >> 1), n); #define INNERLOOP \ while (ebi != 0) \ { \ while (getbit (ep, ebi) == 0) \ { \ MPN_SQR (tp, rp, n); \ MPN_REDUCE (rp, tp, mp, n, mip); \ ebi--; \ if (ebi == 0) \ goto done; \ } \ \ /* The next bit of the exponent is 1. Now extract the largest \ block of bits <= windowsize, and such that the least \ significant bit is 1. */ \ \ expbits = getbits (ep, ebi, windowsize); \ this_windowsize = windowsize; \ if (ebi < windowsize) \ { \ this_windowsize -= windowsize - ebi; \ ebi = 0; \ } \ else \ ebi -= windowsize; \ \ count_trailing_zeros (cnt, expbits); \ this_windowsize -= cnt; \ ebi += cnt; \ expbits >>= cnt; \ \ do \ { \ MPN_SQR (tp, rp, n); \ MPN_REDUCE (rp, tp, mp, n, mip); \ this_windowsize--; \ } \ while (this_windowsize != 0); \ \ MPN_MUL_N (tp, rp, pp + n * (expbits >> 1), n); \ MPN_REDUCE (rp, tp, mp, n, mip); \ } #if WANT_REDC_2 if (REDC_1_TO_REDC_2_THRESHOLD < MUL_TOOM22_THRESHOLD) { if (BELOW_THRESHOLD (n, REDC_1_TO_REDC_2_THRESHOLD)) { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_basecase (r,a,n,b,n) #define MPN_SQR(r,a,n) mpn_sqr_basecase (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_1 (rp, tp, mp, n, mip[0]) INNERLOOP; } else if (BELOW_THRESHOLD (n, MUL_TOOM22_THRESHOLD)) { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_basecase (r,a,n,b,n) #define MPN_SQR(r,a,n) mpn_sqr_basecase (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_2 (rp, tp, mp, n, mip) INNERLOOP; } else if (BELOW_THRESHOLD (n, REDC_2_TO_REDC_N_THRESHOLD)) { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_n (r,a,b,n) #define MPN_SQR(r,a,n) mpn_sqr (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_2 (rp, tp, mp, n, mip) INNERLOOP; } else { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_n (r,a,b,n) #define MPN_SQR(r,a,n) mpn_sqr (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_n (rp, tp, mp, n, mip) INNERLOOP; } } else { if (BELOW_THRESHOLD (n, MUL_TOOM22_THRESHOLD)) { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_basecase (r,a,n,b,n) #define MPN_SQR(r,a,n) mpn_sqr_basecase (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_1 (rp, tp, mp, n, mip[0]) INNERLOOP; } else if (BELOW_THRESHOLD (n, REDC_1_TO_REDC_2_THRESHOLD)) { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_n (r,a,b,n) #define MPN_SQR(r,a,n) mpn_sqr (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_1 (rp, tp, mp, n, mip[0]) INNERLOOP; } else if (BELOW_THRESHOLD (n, REDC_2_TO_REDC_N_THRESHOLD)) { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_n (r,a,b,n) #define MPN_SQR(r,a,n) mpn_sqr (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_2 (rp, tp, mp, n, mip) INNERLOOP; } else { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_n (r,a,b,n) #define MPN_SQR(r,a,n) mpn_sqr (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_n (rp, tp, mp, n, mip) INNERLOOP; } } #else /* WANT_REDC_2 */ if (REDC_1_TO_REDC_N_THRESHOLD < MUL_TOOM22_THRESHOLD) { if (BELOW_THRESHOLD (n, REDC_1_TO_REDC_N_THRESHOLD)) { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_basecase (r,a,n,b,n) #define MPN_SQR(r,a,n) mpn_sqr_basecase (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_1 (rp, tp, mp, n, mip[0]) INNERLOOP; } else if (BELOW_THRESHOLD (n, MUL_TOOM22_THRESHOLD)) { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_basecase (r,a,n,b,n) #define MPN_SQR(r,a,n) mpn_sqr_basecase (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_n (rp, tp, mp, n, mip) INNERLOOP; } else { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_n (r,a,b,n) #define MPN_SQR(r,a,n) mpn_sqr (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_n (rp, tp, mp, n, mip) INNERLOOP; } } else { if (BELOW_THRESHOLD (n, MUL_TOOM22_THRESHOLD)) { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_basecase (r,a,n,b,n) #define MPN_SQR(r,a,n) mpn_sqr_basecase (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_1 (rp, tp, mp, n, mip[0]) INNERLOOP; } else if (BELOW_THRESHOLD (n, REDC_1_TO_REDC_N_THRESHOLD)) { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_n (r,a,b,n) #define MPN_SQR(r,a,n) mpn_sqr (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_1 (rp, tp, mp, n, mip[0]) INNERLOOP; } else { #undef MPN_MUL_N #undef MPN_SQR #undef MPN_REDUCE #define MPN_MUL_N(r,a,b,n) mpn_mul_n (r,a,b,n) #define MPN_SQR(r,a,n) mpn_sqr (r,a,n) #define MPN_REDUCE(rp,tp,mp,n,mip) mpn_redc_n (rp, tp, mp, n, mip) INNERLOOP; } } #endif /* WANT_REDC_2 */ done: MPN_COPY (tp, rp, n); MPN_ZERO (tp + n, n); #if WANT_REDC_2 if (BELOW_THRESHOLD (n, REDC_1_TO_REDC_2_THRESHOLD)) mpn_redc_1 (rp, tp, mp, n, mip[0]); else if (BELOW_THRESHOLD (n, REDC_2_TO_REDC_N_THRESHOLD)) mpn_redc_2 (rp, tp, mp, n, mip); #else if (BELOW_THRESHOLD (n, REDC_1_TO_REDC_N_THRESHOLD)) mpn_redc_1 (rp, tp, mp, n, mip[0]); #endif else mpn_redc_n (rp, tp, mp, n, mip); if (mpn_cmp (rp, mp, n) >= 0) mpn_sub_n (rp, rp, mp, n); TMP_FREE; }
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/gmp_13420-13421.c
manybugs_data_26
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <zend_language_parser.h> #include "zend.h" #include "zend_compile.h" #include "zend_constants.h" #include "zend_llist.h" #include "zend_API.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "zend_multibyte.h" #include "zend_language_scanner.h" #define CONSTANT_EX(op_array, op) \ (op_array)->literals[op].constant #define CONSTANT(op) \ CONSTANT_EX(CG(active_op_array), op) #define SET_NODE(target, src) do { \ target ## _type = (src)->op_type; \ if ((src)->op_type == IS_CONST) { \ target.constant = zend_add_literal(CG(active_op_array), &(src)->u.constant TSRMLS_CC); \ } else { \ target = (src)->u.op; \ } \ } while (0) #define GET_NODE(target, src) do { \ (target)->op_type = src ## _type; \ if ((target)->op_type == IS_CONST) { \ (target)->u.constant = CONSTANT(src.constant); \ } else { \ (target)->u.op = src; \ (target)->EA = 0; \ } \ } while (0) #define COPY_NODE(target, src) do { \ target ## _type = src ## _type; \ target = src; \ } while (0) #define CALCULATE_LITERAL_HASH(num) do { \ if (IS_INTERNED(Z_STRVAL(CONSTANT(num)))) { \ Z_HASH_P(&CONSTANT(num)) = INTERNED_HASH(Z_STRVAL(CONSTANT(num))); \ } else { \ Z_HASH_P(&CONSTANT(num)) = zend_hash_func(Z_STRVAL(CONSTANT(num)), Z_STRLEN(CONSTANT(num))+1); \ } \ } while (0) #define GET_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot++; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ } \ } while (0) #define POLYMORPHIC_CACHE_SLOT_SIZE 2 #define GET_POLYMORPHIC_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot; \ CG(active_op_array)->last_cache_slot += POLYMORPHIC_CACHE_SLOT_SIZE; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 2] = NULL; \ } \ } while (0) #define FREE_POLYMORPHIC_CACHE_SLOT(literal) do { \ if (CG(active_op_array)->literals[literal].cache_slot == \ CG(active_op_array)->last_cache_slot - POLYMORPHIC_CACHE_SLOT_SIZE) { \ CG(active_op_array)->literals[literal].cache_slot = -1; \ CG(active_op_array)->last_cache_slot -= POLYMORPHIC_CACHE_SLOT_SIZE; \ } \ } while (0) ZEND_API zend_op_array *(*zend_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); ZEND_API zend_op_array *(*zend_compile_string)(zval *source_string, char *filename TSRMLS_DC); #ifndef ZTS ZEND_API zend_compiler_globals compiler_globals; ZEND_API zend_executor_globals executor_globals; #endif static void zend_duplicate_property_info(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = estrndup(property_info->name, property_info->name_length); } if (property_info->doc_comment) { property_info->doc_comment = estrndup(property_info->doc_comment, property_info->doc_comment_len); } } /* }}} */ static void zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = zend_strndup(property_info->name, property_info->name_length); } } /* }}} */ static void zend_destroy_property_info(zend_property_info *property_info) /* {{{ */ { str_efree(property_info->name); if (property_info->doc_comment) { efree((char*)property_info->doc_comment); } } /* }}} */ static void zend_destroy_property_info_internal(zend_property_info *property_info) /* {{{ */ { str_free((char*)property_info->name); } /* }}} */ static void build_runtime_defined_function_key(zval *result, const char *name, int name_length TSRMLS_DC) /* {{{ */ { char char_pos_buf[32]; uint char_pos_len; const char *filename; char_pos_len = zend_sprintf(char_pos_buf, "%p", LANG_SCNG(yy_text)); if (CG(active_op_array)->filename) { filename = CG(active_op_array)->filename; } else { filename = "-"; } /* NULL, name length, filename length, last accepting char position length */ result->value.str.len = 1+name_length+strlen(filename)+char_pos_len; /* must be binary safe */ result->value.str.val = (char *) safe_emalloc(result->value.str.len, 1, 1); result->value.str.val[0] = '\0'; sprintf(result->value.str.val+1, "%s%s%s", name, filename, char_pos_buf); result->type = IS_STRING; Z_SET_REFCOUNT_P(result, 1); } /* }}} */ static void init_compiler_declarables(TSRMLS_D) /* {{{ */ { Z_TYPE(CG(declarables).ticks) = IS_LONG; Z_LVAL(CG(declarables).ticks) = 0; } /* }}} */ void zend_init_compiler_context(TSRMLS_D) /* {{{ */ { CG(context).opcodes_size = (CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) ? INITIAL_INTERACTIVE_OP_ARRAY_SIZE : INITIAL_OP_ARRAY_SIZE; CG(context).vars_size = 0; CG(context).literals_size = 0; CG(context).current_brk_cont = -1; CG(context).backpatch_count = 0; CG(context).labels = NULL; } /* }}} */ void zend_init_compiler_data_structures(TSRMLS_D) /* {{{ */ { zend_stack_init(&CG(bp_stack)); zend_stack_init(&CG(function_call_stack)); zend_stack_init(&CG(switch_cond_stack)); zend_stack_init(&CG(foreach_copy_stack)); zend_stack_init(&CG(object_stack)); zend_stack_init(&CG(declare_stack)); CG(active_class_entry) = NULL; zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_stack_init(&CG(list_stack)); CG(in_compilation) = 0; CG(start_lineno) = 0; CG(current_namespace) = NULL; CG(in_namespace) = 0; CG(has_bracketed_namespaces) = 0; CG(current_import) = NULL; init_compiler_declarables(TSRMLS_C); zend_stack_init(&CG(context_stack)); CG(encoding_declared) = 0; } /* }}} */ ZEND_API void file_handle_dtor(zend_file_handle *fh) /* {{{ */ { TSRMLS_FETCH(); zend_file_handle_dtor(fh TSRMLS_CC); } /* }}} */ void init_compiler(TSRMLS_D) /* {{{ */ { CG(active_op_array) = NULL; zend_init_compiler_data_structures(TSRMLS_C); zend_init_rsrc_list(TSRMLS_C); zend_hash_init(&CG(filenames_table), 5, NULL, (dtor_func_t) free_estring, 0); zend_llist_init(&CG(open_files), sizeof(zend_file_handle), (void (*)(void *)) file_handle_dtor, 0); CG(unclean_shutdown) = 0; } /* }}} */ void shutdown_compiler(TSRMLS_D) /* {{{ */ { zend_stack_destroy(&CG(bp_stack)); zend_stack_destroy(&CG(function_call_stack)); zend_stack_destroy(&CG(switch_cond_stack)); zend_stack_destroy(&CG(foreach_copy_stack)); zend_stack_destroy(&CG(object_stack)); zend_stack_destroy(&CG(declare_stack)); zend_stack_destroy(&CG(list_stack)); zend_hash_destroy(&CG(filenames_table)); zend_llist_destroy(&CG(open_files)); zend_stack_destroy(&CG(context_stack)); } /* }}} */ ZEND_API char *zend_set_compiled_filename(const char *new_compiled_filename TSRMLS_DC) /* {{{ */ { char **pp, *p; int length = strlen(new_compiled_filename); if (zend_hash_find(&CG(filenames_table), new_compiled_filename, length+1, (void **) &pp) == SUCCESS) { CG(compiled_filename) = *pp; return *pp; } p = estrndup(new_compiled_filename, length); zend_hash_update(&CG(filenames_table), new_compiled_filename, length+1, &p, sizeof(char *), (void **) &pp); CG(compiled_filename) = p; return p; } /* }}} */ ZEND_API void zend_restore_compiled_filename(char *original_compiled_filename TSRMLS_DC) /* {{{ */ { CG(compiled_filename) = original_compiled_filename; } /* }}} */ ZEND_API char *zend_get_compiled_filename(TSRMLS_D) /* {{{ */ { return CG(compiled_filename); } /* }}} */ ZEND_API int zend_get_compiled_lineno(TSRMLS_D) /* {{{ */ { return CG(zend_lineno); } /* }}} */ ZEND_API zend_bool zend_is_compiling(TSRMLS_D) /* {{{ */ { return CG(in_compilation); } /* }}} */ static zend_uint get_temporary_variable(zend_op_array *op_array) /* {{{ */ { return (op_array->T)++ * ZEND_MM_ALIGNED_SIZE(sizeof(temp_variable)); } /* }}} */ static int lookup_cv(zend_op_array *op_array, char* name, int name_len, ulong hash TSRMLS_DC) /* {{{ */ { int i = 0; ulong hash_value = hash ? hash : zend_inline_hash_func(name, name_len+1); while (i < op_array->last_var) { if (op_array->vars[i].name == name || (op_array->vars[i].hash_value == hash_value && op_array->vars[i].name_len == name_len && memcmp(op_array->vars[i].name, name, name_len) == 0)) { str_efree(name); return i; } i++; } i = op_array->last_var; op_array->last_var++; if (op_array->last_var > CG(context).vars_size) { CG(context).vars_size += 16; /* FIXME */ op_array->vars = erealloc(op_array->vars, CG(context).vars_size * sizeof(zend_compiled_variable)); } op_array->vars[i].name = zend_new_interned_string(name, name_len + 1, 1 TSRMLS_CC); op_array->vars[i].name_len = name_len; op_array->vars[i].hash_value = hash_value; return i; } /* }}} */ void zend_del_literal(zend_op_array *op_array, int n) /* {{{ */ { zval_dtor(&CONSTANT_EX(op_array, n)); if (n + 1 == op_array->last_literal) { op_array->last_literal--; } else { Z_TYPE(CONSTANT_EX(op_array, n)) = IS_NULL; } } /* }}} */ /* Common part of zend_add_literal and zend_append_individual_literal */ static inline void zend_insert_literal(zend_op_array *op_array, const zval *zv, int literal_position TSRMLS_DC) /* {{{ */ { if (Z_TYPE_P(zv) == IS_STRING || Z_TYPE_P(zv) == IS_CONSTANT) { zval *z = (zval*)zv; Z_STRVAL_P(z) = (char*)zend_new_interned_string(Z_STRVAL_P(zv), Z_STRLEN_P(zv) + 1, 1 TSRMLS_CC); } CONSTANT_EX(op_array, literal_position) = *zv; Z_SET_REFCOUNT(CONSTANT_EX(op_array, literal_position), 2); Z_SET_ISREF(CONSTANT_EX(op_array, literal_position)); op_array->literals[literal_position].hash_value = 0; op_array->literals[literal_position].cache_slot = -1; } /* }}} */ /* Is used while compiling a function, using the context to keep track of an approximate size to avoid to relocate to often. Literals are truncated to actual size in the second compiler pass (pass_two()). */ int zend_add_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; if (i >= CG(context).literals_size) { while (i >= CG(context).literals_size) { CG(context).literals_size += 16; /* FIXME */ } op_array->literals = (zend_literal*)erealloc(op_array->literals, CG(context).literals_size * sizeof(zend_literal)); } zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ /* Is used after normal compilation to append an additional literal. Allocation is done precisely here. */ int zend_append_individual_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; op_array->literals = (zend_literal*)erealloc(op_array->literals, (i + 1) * sizeof(zend_literal)); zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ int zend_add_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_ns_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; const char *ns_separator; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); ns_separator = (const char*)zend_memrchr(Z_STRVAL_P(zv), '\\', Z_STRLEN_P(zv)) + 1; lc_len = Z_STRLEN_P(zv) - (ns_separator - Z_STRVAL_P(zv)); lc_name = zend_str_tolower_dup(ns_separator, lc_len); ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_class_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } if (Z_STRVAL_P(zv)[0] == '\\') { lc_len = Z_STRLEN_P(zv) - 1; lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv) + 1, lc_len); } else { lc_len = Z_STRLEN_P(zv); lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), lc_len); } ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); GET_CACHE_SLOT(ret); return ret; } /* }}} */ int zend_add_const_name_literal(zend_op_array *op_array, const zval *zv, int unqualified TSRMLS_DC) /* {{{ */ { int ret, tmp_literal; char *name, *tmp_name; const char *ns_separator; int name_len, ns_len; zval c; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } /* skip leading '\\' */ if (Z_STRVAL_P(zv)[0] == '\\') { name_len = Z_STRLEN_P(zv) - 1; name = Z_STRVAL_P(zv) + 1; } else { name_len = Z_STRLEN_P(zv); name = Z_STRVAL_P(zv); } ns_separator = zend_memrchr(name, '\\', name_len); if (ns_separator) { ns_len = ns_separator - name; } else { ns_len = 0; } if (ns_len) { /* lowercased namespace name & original constant name */ tmp_name = estrndup(name, name_len); zend_str_tolower(tmp_name, ns_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased namespace name & lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); } if (ns_len) { if (!unqualified) { return ret; } ns_len++; name += ns_len; name_len -= ns_len; } /* original constant name */ tmp_name = estrndup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); return ret; } /* }}} */ #define LITERAL_STRINGL(op, str, len, copy) do { \ zval _c; \ ZVAL_STRINGL(&_c, str, len, copy); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG(op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG_EX(op_array, op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(op_array, &_c TSRMLS_CC); \ } while (0) #define LITERAL_NULL(op) do { \ zval _c; \ INIT_ZVAL( _c); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) static inline zend_bool zend_is_function_or_method_call(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; return ((type & ZEND_PARSED_METHOD_CALL) || (type == ZEND_PARSED_FUNCTION_CALL)); } /* }}} */ void zend_do_binary_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_unary_op(zend_uchar op, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); GET_NODE(result, opline->result); SET_UNUSED(opline->op2); } /* }}} */ #define MAKE_NOP(opline) { opline->opcode = ZEND_NOP; memset(&opline->result,0,sizeof(opline->result)); memset(&opline->op1,0,sizeof(opline->op1)); memset(&opline->op2,0,sizeof(opline->op2)); opline->result_type=opline->op1_type=opline->op2_type=IS_UNUSED; } static void zend_do_op_data(zend_op *data_op, const znode *value TSRMLS_DC) /* {{{ */ { data_op->opcode = ZEND_OP_DATA; SET_NODE(data_op->op1, value); SET_UNUSED(data_op->op2); } /* }}} */ void zend_do_binary_assign_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; switch (last_op->opcode) { case ZEND_FETCH_OBJ_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, op2 TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; case ZEND_FETCH_DIM_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_DIM; zend_do_op_data(opline, op2 TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result,last_op->result); return; default: break; } } opline->opcode = op; SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void fetch_simple_variable_ex(znode *result, znode *varname, int bp, zend_uchar op TSRMLS_DC) /* {{{ */ { zend_op opline; zend_op *opline_ptr; zend_llist *fetch_list_ptr; if (varname->op_type == IS_CONST) { ulong hash = 0; if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } else if (IS_INTERNED(Z_STRVAL(varname->u.constant))) { hash = INTERNED_HASH(Z_STRVAL(varname->u.constant)); } if (!zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC) && !(varname->u.constant.value.str.len == (sizeof("this")-1) && !memcmp(varname->u.constant.value.str.val, "this", sizeof("this"))) && (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE)) { result->op_type = IS_CV; result->u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC); varname->u.constant.value.str.val = (char*)CG(active_op_array)->vars[result->u.op.var].name; result->EA = 0; return; } } if (bp) { opline_ptr = &opline; init_op(opline_ptr TSRMLS_CC); } else { opline_ptr = get_next_op(CG(active_op_array) TSRMLS_CC); } opline_ptr->opcode = op; opline_ptr->result_type = IS_VAR; opline_ptr->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline_ptr->op1, varname); GET_NODE(result, opline_ptr->result); SET_UNUSED(opline_ptr->op2); opline_ptr->extended_value = ZEND_FETCH_LOCAL; if (varname->op_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline_ptr->op1.constant); if (zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC)) { opline_ptr->extended_value = ZEND_FETCH_GLOBAL; } } if (bp) { zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); zend_llist_add_element(fetch_list_ptr, opline_ptr); } } /* }}} */ void fetch_simple_variable(znode *result, znode *varname, int bp TSRMLS_DC) /* {{{ */ { /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ fetch_simple_variable_ex(result, varname, bp, ZEND_FETCH_W TSRMLS_CC); } /* }}} */ void zend_do_fetch_static_member(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { znode class_node; zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline_ptr; zend_op opline; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); } zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (result->op_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[result->u.op.var].name), CG(active_op_array)->vars[result->u.op.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } GET_NODE(result,opline.result); opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; opline_ptr = &opline; zend_llist_add_element(fetch_list_ptr, &opline); } else { le = fetch_list_ptr->head; opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode != ZEND_FETCH_W && opline_ptr->op1_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[opline_ptr->op1.var].name), CG(active_op_array)->vars[opline_ptr->op1.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; COPY_NODE(opline_ptr->op1, opline.result); zend_llist_prepend_element(fetch_list_ptr, &opline); } else { if (opline_ptr->op1_type == IS_CONST) { GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op1.constant); } if (class_node.op_type == IS_CONST) { opline_ptr->op2_type = IS_CONST; opline_ptr->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline_ptr->op2, &class_node); } opline_ptr->extended_value |= ZEND_FETCH_STATIC_MEMBER; } } } /* }}} */ void fetch_array_begin(znode *result, znode *varname, znode *first_dim TSRMLS_DC) /* {{{ */ { fetch_simple_variable(result, varname, 1 TSRMLS_CC); fetch_array_dim(result, result, first_dim TSRMLS_CC); } /* }}} */ void fetch_array_dim(znode *result, const znode *parent, const znode *dim TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (zend_is_function_or_method_call(parent)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, parent); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_DIM_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, parent); SET_NODE(opline.op2, dim); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline.op2.constant)), Z_STRLEN(CONSTANT(opline.op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline.op2.constant)); ZVAL_LONG(&CONSTANT(opline.op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline.op2.constant); } } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void fetch_string_offset(znode *result, const znode *parent, const znode *offset TSRMLS_DC) /* {{{ */ { fetch_array_dim(result, parent, offset TSRMLS_CC); } /* }}} */ void zend_do_print(znode *result, const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->opcode = ZEND_PRINT; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_echo(const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ECHO; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_abstract_method(const znode *function_name, znode *modifiers, const znode *body TSRMLS_DC) /* {{{ */ { char *method_type; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { Z_LVAL(modifiers->u.constant) |= ZEND_ACC_ABSTRACT; method_type = "Interface"; } else { method_type = "Abstract"; } if (modifiers->u.constant.value.lval & ZEND_ACC_ABSTRACT) { if(modifiers->u.constant.value.lval & ZEND_ACC_PRIVATE) { zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot be declared private", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } if (Z_LVAL(body->u.constant) == ZEND_ACC_ABSTRACT) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_RAISE_ABSTRACT_ERROR; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } else { /* we had code in the function body */ zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot contain body", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } else { if (body->u.constant.value.lval == ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Non-abstract method %s::%s() must contain body", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } } /* }}} */ static zend_bool opline_is_fetch_this(const zend_op *opline TSRMLS_DC) /* {{{ */ { if ((opline->opcode == ZEND_FETCH_W) && (opline->op1_type == IS_CONST) && (Z_TYPE(CONSTANT(opline->op1.constant)) == IS_STRING) && (Z_HASH_P(&CONSTANT(opline->op1.constant)) == THIS_HASHVAL) && (Z_STRLEN(CONSTANT(opline->op1.constant)) == (sizeof("this")-1)) && !memcmp(Z_STRVAL(CONSTANT(opline->op1.constant)), "this", sizeof("this"))) { return 1; } else { return 0; } } /* }}} */ void zend_do_assign(znode *result, znode *variable, znode *value TSRMLS_DC) /* {{{ */ { int last_op_number; zend_op *opline; if (value->op_type == IS_CV) { zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (fetch_list_ptr && fetch_list_ptr->head) { opline = (zend_op *)fetch_list_ptr->head->data; if (opline->opcode == ZEND_FETCH_DIM_W && opline->op1_type == IS_CV && opline->op1.var == value->u.op.var) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_R; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->op1_type = IS_CONST; LITERAL_STRINGL(opline->op1, CG(active_op_array)->vars[value->u.op.var].name, CG(active_op_array)->vars[value->u.op.var].name_len, 1); CALCULATE_LITERAL_HASH(opline->op1.constant); SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_LOCAL; GET_NODE(value, opline->result); } } } zend_do_end_variable_parse(variable, BP_VAR_W, 0 TSRMLS_CC); last_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (variable->op_type == IS_CV) { if (variable->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (variable->op_type == IS_VAR) { int n = 0; while (last_op_number - n > 0) { zend_op *last_op; last_op = &CG(active_op_array)->opcodes[last_op_number-n-1]; if (last_op->result_type == IS_VAR && last_op->result.var == variable->u.op.var) { if (last_op->opcode == ZEND_FETCH_OBJ_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, value TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (last_op->opcode == ZEND_FETCH_DIM_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ /* TBFixed: this can realloc opcodes, leaving last_op pointing wrong */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_DIM; zend_do_op_data(opline, value TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (opline_is_fetch_this(last_op TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } else { break; } } n++; } } opline->opcode = ZEND_ASSIGN; SET_NODE(opline->op1, variable); SET_NODE(opline->op2, value); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_assign_ref(znode *result, const znode *lvar, const znode *rvar TSRMLS_DC) /* {{{ */ { zend_op *opline; if (lvar->op_type == IS_CV) { if (lvar->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (lvar->op_type == IS_VAR) { int last_op_number = get_next_op_number(CG(active_op_array)); if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline_is_fetch_this(opline TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ASSIGN_REF; if (zend_is_function_or_method_call(rvar)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } else if (rvar->EA & ZEND_PARSED_NEW) { opline->extended_value = ZEND_RETURNS_NEW; } else { opline->extended_value = 0; } if (result) { opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } else { opline->result_type = IS_UNUSED | EXT_TYPE_UNUSED; } SET_NODE(opline->op1, lvar); SET_NODE(opline->op2, rvar); } /* }}} */ static inline void do_begin_loop(TSRMLS_D) /* {{{ */ { zend_brk_cont_element *brk_cont_element; int parent; parent = CG(context).current_brk_cont; CG(context).current_brk_cont = CG(active_op_array)->last_brk_cont; brk_cont_element = get_next_brk_cont_element(CG(active_op_array)); brk_cont_element->start = get_next_op_number(CG(active_op_array)); brk_cont_element->parent = parent; } /* }}} */ static inline void do_end_loop(int cont_addr, int has_loop_var TSRMLS_DC) /* {{{ */ { if (!has_loop_var) { /* The start fileld is used to free temporary variables in case of exceptions. * We won't try to free something of we don't have loop variable. */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].start = -1; } CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = cont_addr; CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; } /* }}} */ void zend_do_while_cond(const znode *expr, znode *close_bracket_token TSRMLS_DC) /* {{{ */ { int while_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, expr); close_bracket_token->u.op.opline_num = while_cond_op_number; SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_while_end(const znode *while_token, const znode *close_bracket_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* add unconditional jump */ opline->opcode = ZEND_JMP; opline->op1.opline_num = while_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* update while's conditional jmp */ CG(active_op_array)->opcodes[close_bracket_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); do_end_loop(while_token->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_cond(const znode *expr, znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { int for_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZNZ; SET_NODE(opline->op1, expr); /* the conditional expression */ second_semicolon_token->u.op.opline_num = for_cond_op_number; SET_UNUSED(opline->op2); } /* }}} */ void zend_do_for_before_statement(const znode *cond_start, const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = cond_start->u.op.opline_num; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_end(const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = second_semicolon_token->u.op.opline_num+1; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_end_loop(second_semicolon_token->u.op.opline_num+1, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_pre_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_PRE_INC)?ZEND_PRE_INC_OBJ:ZEND_PRE_DEC_OBJ; last_op->result_type = IS_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_post_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_POST_INC)?ZEND_POST_INC_OBJ:ZEND_POST_DEC_OBJ; last_op->result_type = IS_TMP_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_if_cond(const znode *cond, znode *closing_bracket_token TSRMLS_DC) /* {{{ */ { int if_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); closing_bracket_token->u.op.opline_num = if_cond_op_number; SET_UNUSED(opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_if_after_statement(const znode *closing_bracket_token, unsigned char initialize TSRMLS_DC) /* {{{ */ { int if_end_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; /* save for backpatching */ if (initialize) { zend_llist jmp_list; zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); } zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &if_end_op_number); CG(active_op_array)->opcodes[closing_bracket_token->u.op.opline_num].op2.opline_num = if_end_op_number+1; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_if_end(TSRMLS_D) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_llist *jmp_list_ptr; zend_llist_element *le; zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); for (le=jmp_list_ptr->head; le; le = le->next) { CG(active_op_array)->opcodes[*((int *) le->data)].op1.opline_num = next_op_number; } zend_llist_destroy(jmp_list_ptr); zend_stack_del_top(&CG(bp_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_check_writable_variable(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; if (type & ZEND_PARSED_METHOD_CALL) { zend_error(E_COMPILE_ERROR, "Can't use method return value in write context"); } if (type == ZEND_PARSED_FUNCTION_CALL) { zend_error(E_COMPILE_ERROR, "Can't use function return value in write context"); } } /* }}} */ void zend_do_begin_variable_parse(TSRMLS_D) /* {{{ */ { zend_llist fetch_list; zend_llist_init(&fetch_list, sizeof(zend_op), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &fetch_list, sizeof(zend_llist)); } /* }}} */ void zend_do_end_variable_parse(znode *variable, int type, int arg_offset TSRMLS_DC) /* {{{ */ { zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline = NULL; zend_op *opline_ptr; zend_uint this_var = -1; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); le = fetch_list_ptr->head; /* TODO: $foo->x->y->z = 1 should fetch "x" and "y" for R or RW, not just W */ if (le) { opline_ptr = (zend_op *)le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { /* convert to FETCH_?(this) into IS_CV */ if (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE) { this_var = opline_ptr->result.var; if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), Z_STRVAL(CONSTANT(opline_ptr->op1.constant)), Z_STRLEN(CONSTANT(opline_ptr->op1.constant)), Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC); Z_TYPE(CONSTANT(opline_ptr->op1.constant)) = IS_NULL; } else { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); } le = le->next; if (variable->op_type == IS_VAR && variable->u.op.var == this_var) { variable->op_type = IS_CV; variable->u.op.var = CG(active_op_array)->this_var; } } else if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } while (le) { opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode == ZEND_SEPARATE) { if (type != BP_VAR_R && type != BP_VAR_IS) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); } le = le->next; continue; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); if (opline->op1_type == IS_VAR && opline->op1.var == this_var) { opline->op1_type = IS_CV; opline->op1.var = CG(active_op_array)->this_var; } switch (type) { case BP_VAR_R: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode -= 3; break; case BP_VAR_W: break; case BP_VAR_RW: opline->opcode += 3; break; case BP_VAR_IS: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode += 6; /* 3+3 */ break; case BP_VAR_FUNC_ARG: opline->opcode += 9; /* 3+3+3 */ opline->extended_value |= arg_offset; break; case BP_VAR_UNSET: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for unsetting"); } opline->opcode += 12; /* 3+3+3+3 */ break; } le = le->next; } if (opline && type == BP_VAR_W && arg_offset) { opline->extended_value |= ZEND_FETCH_MAKE_REF; } } zend_llist_destroy(fetch_list_ptr); zend_stack_del_top(&CG(bp_stack)); } /* }}} */ void zend_do_add_string(znode *result, const znode *op1, znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline; if (Z_STRLEN(op2->u.constant) > 1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_STRING; } else if (Z_STRLEN(op2->u.constant) == 1) { int ch = *Z_STRVAL(op2->u.constant); /* Free memory and use ZEND_ADD_CHAR in case of 1 character strings */ efree(Z_STRVAL(op2->u.constant)); ZVAL_LONG(&op2->u.constant, ch); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_CHAR; } else { /* String can be empty after a variable at the end of a heredoc */ efree(Z_STRVAL(op2->u.constant)); return; } if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_add_variable(znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_VAR; if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_free(znode *op1 TSRMLS_DC) /* {{{ */ { if (op1->op_type==IS_TMP_VAR) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else if (op1->op_type==IS_VAR) { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; while (opline->opcode == ZEND_END_SILENCE || opline->opcode == ZEND_EXT_FCALL_END || opline->opcode == ZEND_OP_DATA) { opline--; } if (opline->result_type == IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_FETCH_R || opline->opcode == ZEND_FETCH_DIM_R || opline->opcode == ZEND_FETCH_OBJ_R || opline->opcode == ZEND_QM_ASSIGN_VAR) { /* It's very rare and useless case. It's better to use additional FREE opcode and simplify the FETCH handlers their selves */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else { opline->result_type |= EXT_TYPE_UNUSED; } } else { while (opline>CG(active_op_array)->opcodes) { if (opline->opcode == ZEND_FETCH_DIM_R && opline->op1_type == IS_VAR && opline->op1.var == op1->u.op.var) { /* This should the end of a list() construct * Mark its result as unused */ opline->extended_value = ZEND_FETCH_STANDARD; break; } else if (opline->result_type==IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_NEW) { opline->result_type |= EXT_TYPE_UNUSED; } break; } opline--; } } } else if (op1->op_type == IS_CONST) { zval_dtor(&op1->u.constant); } } /* }}} */ int zend_do_verify_access_types(const znode *current_access_type, const znode *new_modifier) /* {{{ */ { if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_PPP_MASK) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Multiple access type modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_ABSTRACT) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Multiple abstract modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_STATIC) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Multiple static modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_FINAL) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Multiple final modifiers are not allowed"); } if (((Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)) & (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) == (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Cannot use the final modifier on an abstract class member"); } return (Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)); } /* }}} */ void zend_do_begin_function_declaration(znode *function_token, znode *function_name, int is_method, int return_reference, znode *fn_flags_znode TSRMLS_DC) /* {{{ */ { zend_op_array op_array; char *name = function_name->u.constant.value.str.val; int name_len = function_name->u.constant.value.str.len; int function_begin_line = function_token->u.op.opline_num; zend_uint fn_flags; const char *lcname; zend_bool orig_interactive; ALLOCA_FLAG(use_heap) if (is_method) { if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((Z_LVAL(fn_flags_znode->u.constant) & ~(ZEND_ACC_STATIC|ZEND_ACC_PUBLIC))) { zend_error(E_COMPILE_ERROR, "Access type for interface method %s::%s() must be omitted", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } Z_LVAL(fn_flags_znode->u.constant) |= ZEND_ACC_ABSTRACT; /* propagates to the rest of the parser */ } fn_flags = Z_LVAL(fn_flags_znode->u.constant); /* must be done *after* the above check */ } else { fn_flags = 0; } if ((fn_flags & ZEND_ACC_STATIC) && (fn_flags & ZEND_ACC_ABSTRACT) && !(CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_STRICT, "Static function %s%s%s() should not be abstract", is_method ? CG(active_class_entry)->name : "", is_method ? "::" : "", Z_STRVAL(function_name->u.constant)); } function_token->u.op_array = CG(active_op_array); orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(&op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; op_array.function_name = name; if (return_reference) { op_array.fn_flags |= ZEND_ACC_RETURN_REFERENCE; } op_array.fn_flags |= fn_flags; op_array.scope = is_method?CG(active_class_entry):NULL; op_array.prototype = NULL; op_array.line_start = zend_get_compiled_lineno(TSRMLS_C); if (is_method) { int result; lcname = zend_new_interned_string(zend_str_tolower_dup(name, name_len), name_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lcname)) { result = zend_hash_quick_add(&CG(active_class_entry)->function_table, lcname, name_len+1, INTERNED_HASH(lcname), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } else { result = zend_hash_add(&CG(active_class_entry)->function_table, lcname, name_len+1, &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } if (result == FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::%s()", CG(active_class_entry)->name, name); } zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); if (fn_flags & ZEND_ACC_ABSTRACT) { CG(active_class_entry)->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (!(fn_flags & ZEND_ACC_PPP_MASK)) { fn_flags |= ZEND_ACC_PUBLIC; } if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } } } else { char *class_lcname; class_lcname = do_alloca(CG(active_class_entry)->name_length + 1, use_heap); zend_str_tolower_copy(class_lcname, CG(active_class_entry)->name, CG(active_class_entry)->name_length); /* Improve after RC: cache the lowercase class name */ if ((CG(active_class_entry)->name_length == name_len) && ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT) && (!memcmp(class_lcname, lcname, name_len))) { if (!CG(active_class_entry)->constructor) { CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } } else if ((name_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)))) { if (CG(active_class_entry)->constructor) { zend_error(E_STRICT, "Redefining already defined constructor for class %s", CG(active_class_entry)->name); } CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1))) { CG(active_class_entry)->destructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1))) { CG(active_class_entry)->clone = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } CG(active_class_entry)->__call = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } CG(active_class_entry)->__callstatic = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } CG(active_class_entry)->__get = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } CG(active_class_entry)->__set = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } CG(active_class_entry)->__unset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } CG(active_class_entry)->__isset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } CG(active_class_entry)->__tostring = (zend_function *) CG(active_op_array); } else if (!(fn_flags & ZEND_ACC_STATIC)) { CG(active_op_array)->fn_flags |= ZEND_ACC_ALLOW_STATIC; } free_alloca(class_lcname, use_heap); } str_efree(lcname); } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zval key; if (CG(current_namespace)) { /* Prefix function name with current namespcae name */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, function_name TSRMLS_CC); op_array.function_name = Z_STRVAL(tmp.u.constant); name_len = Z_STRLEN(tmp.u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), name_len); } else { lcname = zend_str_tolower_dup(name, name_len); } opline->opcode = ZEND_DECLARE_FUNCTION; opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, name_len TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; LITERAL_STRINGL(opline->op2, lcname, name_len, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); opline->extended_value = ZEND_DECLARE_FUNCTION; zend_hash_quick_update(CG(function_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); } if (CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_NOP; opline->lineno = function_begin_line; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } { /* Push a seperator to the switch and foreach stacks */ zend_switch_entry switch_entry; switch_entry.cond.op_type = IS_UNUSED; switch_entry.default_case = 0; switch_entry.control_var = 0; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); { /* Foreach stack separator */ zend_op dummy_opline; dummy_opline.result_type = IS_UNUSED; dummy_opline.op1_type = IS_UNUSED; zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); } } if (CG(doc_comment)) { CG(active_op_array)->doc_comment = CG(doc_comment); CG(active_op_array)->doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_begin_lambda_function_declaration(znode *result, znode *function_token, int return_reference, int is_static TSRMLS_DC) /* {{{ */ { znode function_name; zend_op_array *current_op_array = CG(active_op_array); int current_op_number = get_next_op_number(CG(active_op_array)); zend_op *current_op; function_name.op_type = IS_CONST; ZVAL_STRINGL(&function_name.u.constant, "{closure}", sizeof("{closure}")-1, 1); zend_do_begin_function_declaration(function_token, &function_name, 0, return_reference, NULL TSRMLS_CC); result->op_type = IS_TMP_VAR; result->u.op.var = get_temporary_variable(current_op_array); current_op = &current_op_array->opcodes[current_op_number]; current_op->opcode = ZEND_DECLARE_LAMBDA_FUNCTION; zend_del_literal(current_op_array, current_op->op2.constant); SET_UNUSED(current_op->op2); SET_NODE(current_op->result, result); if (is_static) { CG(active_op_array)->fn_flags |= ZEND_ACC_STATIC; } CG(active_op_array)->fn_flags |= ZEND_ACC_CLOSURE; } /* }}} */ void zend_do_handle_exception(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_HANDLE_EXCEPTION; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_function_declaration(const znode *function_token TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; zend_do_extended_info(TSRMLS_C); zend_do_return(NULL, 0 TSRMLS_CC); pass_two(CG(active_op_array) TSRMLS_CC); zend_release_labels(TSRMLS_C); if (CG(active_class_entry)) { zend_check_magic_method_implementation(CG(active_class_entry), (zend_function*)CG(active_op_array), E_COMPILE_ERROR TSRMLS_CC); } else { /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(CG(active_op_array)->function_name); zend_str_tolower_copy(lcname, CG(active_op_array)->function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME)) && CG(active_op_array)->num_args != 1) { zend_error(E_COMPILE_ERROR, "%s() must take exactly 1 argument", ZEND_AUTOLOAD_FUNC_NAME); } } CG(active_op_array)->line_end = zend_get_compiled_lineno(TSRMLS_C); CG(active_op_array) = function_token->u.op_array; /* Pop the switch and foreach seperators */ zend_stack_del_top(&CG(switch_cond_stack)); zend_stack_del_top(&CG(foreach_copy_stack)); } /* }}} */ void zend_do_receive_arg(zend_uchar op, znode *varname, const znode *offset, const znode *initialization, znode *class_type, zend_uchar pass_by_reference TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_arg_info *cur_arg_info; znode var; if (class_type->op_type == IS_CONST && Z_TYPE(class_type->u.constant) == IS_STRING && Z_STRLEN(class_type->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_type->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } if (zend_is_auto_global_quick(Z_STRVAL(varname->u.constant), Z_STRLEN(varname->u.constant), 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign auto-global variable %s", Z_STRVAL(varname->u.constant)); } else { var.op_type = IS_CV; var.u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(varname->u.constant) = (char*)CG(active_op_array)->vars[var.u.op.var].name; var.EA = 0; if (CG(active_op_array)->vars[var.u.op.var].hash_value == THIS_HASHVAL && Z_STRLEN(varname->u.constant) == sizeof("this")-1 && !memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this")-1)) { if (CG(active_op_array)->scope && (CG(active_op_array)->fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } CG(active_op_array)->this_var = var.u.op.var; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->num_args++; opline->opcode = op; SET_NODE(opline->result, &var); SET_NODE(opline->op1, offset); if (op == ZEND_RECV_INIT) { SET_NODE(opline->op2, initialization); } else { CG(active_op_array)->required_num_args = CG(active_op_array)->num_args; SET_UNUSED(opline->op2); } CG(active_op_array)->arg_info = erealloc(CG(active_op_array)->arg_info, sizeof(zend_arg_info)*(CG(active_op_array)->num_args)); cur_arg_info = &CG(active_op_array)->arg_info[CG(active_op_array)->num_args-1]; cur_arg_info->name = zend_new_interned_string(estrndup(varname->u.constant.value.str.val, varname->u.constant.value.str.len), varname->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->name_len = varname->u.constant.value.str.len; cur_arg_info->type_hint = 0; cur_arg_info->allow_null = 1; cur_arg_info->pass_by_reference = pass_by_reference; cur_arg_info->class_name = NULL; cur_arg_info->class_name_len = 0; if (class_type->op_type != IS_UNUSED) { cur_arg_info->allow_null = 0; if (class_type->u.constant.type != IS_NULL) { if (class_type->u.constant.type == IS_ARRAY) { cur_arg_info->type_hint = IS_ARRAY; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else if (Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Default value for parameters with array type hint can only be an array or NULL"); } } } else if (class_type->u.constant.type == IS_CALLABLE) { cur_arg_info->type_hint = IS_CALLABLE; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with callable type hint can only be NULL"); } } } else { cur_arg_info->type_hint = IS_OBJECT; if (ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_type->u.constant), Z_STRLEN(class_type->u.constant))) { zend_resolve_class_name(class_type, opline->extended_value, 1 TSRMLS_CC); } Z_STRVAL(class_type->u.constant) = (char*)zend_new_interned_string(class_type->u.constant.value.str.val, class_type->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->class_name = class_type->u.constant.value.str.val; cur_arg_info->class_name_len = class_type->u.constant.value.str.len; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with a class type hint can only be NULL"); } } } } } } /* }}} */ int zend_do_begin_function_call(znode *function_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { zend_function *function; char *lcname; char *is_compound = memchr(Z_STRVAL(function_name->u.constant), '\\', Z_STRLEN(function_name->u.constant)); zend_resolve_non_class_name(function_name, check_namespace TSRMLS_CC); if (check_namespace && CG(current_namespace) && !is_compound) { /* We assume we call function from the current namespace if it is not prefixed. */ /* In run-time PHP will check for function with full name and internal function with short name */ zend_do_begin_dynamic_function_call(function_name, 1 TSRMLS_CC); return 1; } lcname = zend_str_tolower_dup(function_name->u.constant.value.str.val, function_name->u.constant.value.str.len); if ((zend_hash_find(CG(function_table), lcname, function_name->u.constant.value.str.len+1, (void **) &function)==FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_FUNCTIONS) && (function->type == ZEND_INTERNAL_FUNCTION))) { zend_do_begin_dynamic_function_call(function_name, 0 TSRMLS_CC); efree(lcname); return 1; /* Dynamic */ } efree(function_name->u.constant.value.str.val); function_name->u.constant.value.str.val = lcname; zend_stack_push(&CG(function_call_stack), (void *) &function, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 0; } /* }}} */ void zend_do_begin_method_call(znode *left_bracket TSRMLS_DC) /* {{{ */ { zend_op *last_op; int last_op_number; unsigned char *ptr = NULL; zend_do_end_variable_parse(left_bracket, BP_VAR_R, 0 TSRMLS_CC); zend_do_begin_variable_parse(TSRMLS_C); last_op_number = get_next_op_number(CG(active_op_array))-1; last_op = &CG(active_op_array)->opcodes[last_op_number]; if ((last_op->op2_type == IS_CONST) && (Z_TYPE(CONSTANT(last_op->op2.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(last_op->op2.constant)) == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !zend_binary_strcasecmp(Z_STRVAL(CONSTANT(last_op->op2.constant)), Z_STRLEN(CONSTANT(last_op->op2.constant)), ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1)) { zend_error(E_COMPILE_ERROR, "Cannot call __clone() method on objects - use 'clone $obj' instead"); } if (last_op->opcode == ZEND_FETCH_OBJ_R) { if (last_op->op2_type == IS_CONST) { zval name; name = CONSTANT(last_op->op2.constant); if (!IS_INTERNED(Z_STRVAL(name))) { Z_STRVAL(name) = estrndup(Z_STRVAL(name), Z_STRLEN(name)); } FREE_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); last_op->op2.constant = zend_add_func_name_literal(CG(active_op_array), &name TSRMLS_CC); GET_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); } last_op->opcode = ZEND_INIT_METHOD_CALL; SET_UNUSED(last_op->result); Z_LVAL(left_bracket->u.constant) = ZEND_INIT_FCALL_BY_NAME; } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (left_bracket->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &left_bracket->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, left_bracket); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_do_clone(znode *result, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CLONE; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_begin_dynamic_function_call(znode *function_name, int ns_call TSRMLS_DC) /* {{{ */ { unsigned char *ptr = NULL; zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (ns_call) { /* In run-time PHP will check for function with full name and internal function with short name */ opline->opcode = ZEND_INIT_NS_FCALL_BY_NAME; SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_ns_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (function_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, function_name); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_resolve_non_class_name(znode *element_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; int len; zval **ns; char *lcname, *compound = memchr(Z_STRVAL(element_name->u.constant), '\\', Z_STRLEN(element_name->u.constant)); if (Z_STRVAL(element_name->u.constant)[0] == '\\') { /* name starts with \ so it is known and unambiguos, nothing to do here but shorten it */ memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+1, Z_STRLEN(element_name->u.constant)); --Z_STRLEN(element_name->u.constant); return; } if(!check_namespace) { return; } if (compound && CG(current_import)) { len = compound - Z_STRVAL(element_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(element_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(element_name->u.constant) -= len; memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+len, Z_STRLEN(element_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, element_name TSRMLS_CC); *element_name = tmp; efree(lcname); return; } efree(lcname); } if (CG(current_namespace)) { tmp = *element_name; Z_STRLEN(tmp.u.constant) = sizeof("\\")-1 + Z_STRLEN(element_name->u.constant) + Z_STRLEN_P(CG(current_namespace)); Z_STRVAL(tmp.u.constant) = (char *) emalloc(Z_STRLEN(tmp.u.constant)+1); memcpy(Z_STRVAL(tmp.u.constant), Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace))]), "\\", sizeof("\\")-1); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace)) + sizeof("\\")-1]), Z_STRVAL(element_name->u.constant), Z_STRLEN(element_name->u.constant)+1); STR_FREE(Z_STRVAL(element_name->u.constant)); *element_name = tmp; } } /* }}} */ void zend_resolve_class_name(znode *class_name, ulong fetch_type, int check_ns_name TSRMLS_DC) /* {{{ */ { char *compound; char *lcname; zval **ns; znode tmp; int len; compound = memchr(Z_STRVAL(class_name->u.constant), '\\', Z_STRLEN(class_name->u.constant)); if (compound) { /* This is a compound class name that contains namespace prefix */ if (Z_STRVAL(class_name->u.constant)[0] == '\\') { /* The STRING name has "\" prefix */ Z_STRLEN(class_name->u.constant) -= 1; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+1, Z_STRLEN(class_name->u.constant)+1); Z_STRVAL(class_name->u.constant) = erealloc( Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1); if (ZEND_FETCH_CLASS_DEFAULT != zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "'\\%s' is an invalid class name", Z_STRVAL(class_name->u.constant)); } } else { if (CG(current_import)) { len = compound - Z_STRVAL(class_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(class_name->u.constant) -= len; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+len, Z_STRLEN(class_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; efree(lcname); return; } efree(lcname); } /* Here name is not prefixed with \ and not imported */ if (CG(current_namespace)) { tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } } } else if (CG(current_import) || CG(current_namespace)) { /* this is a plain name (without \) */ lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns) == SUCCESS) { /* The given name is an import name. Substitute it. */ zval_dtor(&class_name->u.constant); class_name->u.constant = **ns; zval_copy_ctor(&class_name->u.constant); } else if (CG(current_namespace)) { /* plain name, no import - prepend current namespace to it */ tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } efree(lcname); } } /* }}} */ void zend_do_fetch_class(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { long fetch_class_op_number; zend_op *opline; if (class_name->op_type == IS_CONST && Z_TYPE(class_name->u.constant) == IS_STRING && Z_STRLEN(class_name->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_name->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } fetch_class_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CLASS; SET_UNUSED(opline->op1); opline->extended_value = ZEND_FETCH_CLASS_GLOBAL; CG(catch_begin) = fetch_class_op_number; if (class_name->op_type == IS_CONST) { int fetch_type; fetch_type = zend_get_class_fetch_type(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); switch (fetch_type) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: SET_UNUSED(opline->op2); opline->extended_value = fetch_type; zval_dtor(&class_name->u.constant); break; default: zend_resolve_class_name(class_name, opline->extended_value, 0 TSRMLS_CC); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_name->u.constant TSRMLS_CC); break; } } else { SET_NODE(opline->op2, class_name); } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; /* FIXME: Hack so that INIT_FCALL_BY_NAME still knows this is a class */ GET_NODE(result, opline->result); result->EA = opline->extended_value; } /* }}} */ void zend_do_label(znode *label TSRMLS_DC) /* {{{ */ { zend_label dest; if (!CG(context).labels) { ALLOC_HASHTABLE(CG(context).labels); zend_hash_init(CG(context).labels, 4, NULL, NULL, 0); } dest.brk_cont = CG(context).current_brk_cont; dest.opline_num = get_next_op_number(CG(active_op_array)); if (zend_hash_add(CG(context).labels, Z_STRVAL(label->u.constant), Z_STRLEN(label->u.constant) + 1, (void**)&dest, sizeof(zend_label), NULL) == FAILURE) { zend_error(E_COMPILE_ERROR, "Label '%s' already defined", Z_STRVAL(label->u.constant)); } /* Done with label now */ zval_dtor(&label->u.constant); } /* }}} */ void zend_resolve_goto_label(zend_op_array *op_array, zend_op *opline, int pass2 TSRMLS_DC) /* {{{ */ { zend_label *dest; long current, distance; zval *label; if (pass2) { label = opline->op2.zv; } else { label = &CONSTANT_EX(op_array, opline->op2.constant); } if (CG(context).labels == NULL || zend_hash_find(CG(context).labels, Z_STRVAL_P(label), Z_STRLEN_P(label)+1, (void**)&dest) == FAILURE) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; zend_error(E_COMPILE_ERROR, "'goto' to undefined label '%s'", Z_STRVAL_P(label)); } else { /* Label is not defined. Delay to pass 2. */ INC_BPC(op_array); return; } } opline->op1.opline_num = dest->opline_num; zval_dtor(label); Z_TYPE_P(label) = IS_NULL; /* Check that we are not moving into loop or switch */ current = opline->extended_value; for (distance = 0; current != dest->brk_cont; distance++) { if (current == -1) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; } zend_error(E_COMPILE_ERROR, "'goto' into loop or switch statement is disallowed"); } current = op_array->brk_cont_array[current].parent; } if (distance == 0) { /* Nothing to break out of, optimize to ZEND_JMP */ opline->opcode = ZEND_JMP; opline->extended_value = 0; SET_UNUSED(opline->op2); } else { /* Set real break distance */ ZVAL_LONG(label, distance); } if (pass2) { DEC_BPC(op_array); } } /* }}} */ void zend_do_goto(const znode *label TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_GOTO; opline->extended_value = CG(context).current_brk_cont; SET_UNUSED(opline->op1); SET_NODE(opline->op2, label); zend_resolve_goto_label(CG(active_op_array), opline, 0 TSRMLS_CC); } /* }}} */ void zend_release_labels(TSRMLS_D) /* {{{ */ { if (CG(context).labels) { zend_hash_destroy(CG(context).labels); FREE_HASHTABLE(CG(context).labels); } if (!zend_stack_is_empty(&CG(context_stack))) { zend_compiler_context *ctx; zend_stack_top(&CG(context_stack), (void**)&ctx); CG(context) = *ctx; zend_stack_del_top(&CG(context_stack)); } } /* }}} */ void zend_do_build_full_name(znode *result, znode *prefix, znode *name, int is_class_member TSRMLS_DC) /* {{{ */ { zend_uint length; if (!result) { result = prefix; } else { *result = *prefix; } if (is_class_member) { length = sizeof("::")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "::", sizeof("::")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("::")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } else { length = sizeof("\\")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "\\", sizeof("\\")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("\\")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } } /* }}} */ int zend_do_begin_class_member_function_call(znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { znode class_node; unsigned char *ptr = NULL; zend_op *opline; if (method_name->op_type == IS_CONST) { char *lcname = zend_str_tolower_dup(Z_STRVAL(method_name->u.constant), Z_STRLEN(method_name->u.constant)); if ((sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == Z_STRLEN(method_name->u.constant) && memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == 0) { zval_dtor(&method_name->u.constant); method_name->op_type = IS_UNUSED; } efree(lcname); } if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; opline = get_next_op(CG(active_op_array) TSRMLS_CC); } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->extended_value = class_node.EA ; } opline->opcode = ZEND_INIT_STATIC_METHOD_CALL; if (class_node.op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, &class_node); } if (method_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &method_name->u.constant TSRMLS_CC); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } } else { SET_NODE(opline->op2, method_name); } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 1; /* Dynamic */ } /* }}} */ void zend_do_end_function_call(znode *function_name, znode *result, const znode *argument_list, int is_method, int is_dynamic_fcall TSRMLS_DC) /* {{{ */ { zend_op *opline; if (is_method && function_name && function_name->op_type == IS_UNUSED) { /* clone */ if (Z_LVAL(argument_list->u.constant) != 0) { zend_error(E_WARNING, "Clone method does not require arguments"); } opline = &CG(active_op_array)->opcodes[Z_LVAL(function_name->u.constant)]; } else { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (!is_method && !is_dynamic_fcall && function_name->op_type==IS_CONST) { opline->opcode = ZEND_DO_FCALL; SET_NODE(opline->op1, function_name); CALCULATE_LITERAL_HASH(opline->op1.constant); GET_CACHE_SLOT(opline->op1.constant); } else { opline->opcode = ZEND_DO_FCALL_BY_NAME; SET_UNUSED(opline->op1); } } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(result, opline->result) ; SET_UNUSED(opline->op2); zend_stack_del_top(&CG(function_call_stack)); opline->extended_value = Z_LVAL(argument_list->u.constant); } /* }}} */ void zend_do_pass_param(znode *param, zend_uchar op, int offset TSRMLS_DC) /* {{{ */ { zend_op *opline; int original_op=op; zend_function **function_ptr_ptr, *function_ptr; int send_by_reference; int send_function = 0; zend_stack_top(&CG(function_call_stack), (void **) &function_ptr_ptr); function_ptr = *function_ptr_ptr; if (original_op == ZEND_SEND_REF) { if (function_ptr && function_ptr->common.function_name && function_ptr->common.type == ZEND_USER_FUNCTION && !ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed; " "If you would like to pass argument by reference, modify the declaration of %s().", function_ptr->common.function_name); } else { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed"); } return; } if (function_ptr) { if (ARG_MAY_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { if (param->op_type & (IS_VAR|IS_CV) && original_op != ZEND_SEND_VAL) { send_by_reference = 1; if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION | ZEND_ARG_SEND_SILENT; } } else { op = ZEND_SEND_VAL; send_by_reference = 0; } } else { send_by_reference = ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset) ? ZEND_ARG_SEND_BY_REF : 0; } } else { send_by_reference = 0; } if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION; } else if (op == ZEND_SEND_VAL && (param->op_type & (IS_VAR|IS_CV))) { op = ZEND_SEND_VAR_NO_REF; } if (op!=ZEND_SEND_VAR_NO_REF && send_by_reference==ZEND_ARG_SEND_BY_REF) { /* change to passing by reference */ switch (param->op_type) { case IS_VAR: case IS_CV: op = ZEND_SEND_REF; break; default: zend_error(E_COMPILE_ERROR, "Only variables can be passed by reference"); break; } } if (original_op == ZEND_SEND_VAR) { switch (op) { case ZEND_SEND_VAR_NO_REF: zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); break; case ZEND_SEND_VAR: if (function_ptr) { zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(param, BP_VAR_FUNC_ARG, offset TSRMLS_CC); } break; case ZEND_SEND_REF: zend_do_end_variable_parse(param, BP_VAR_W, 0 TSRMLS_CC); break; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (op == ZEND_SEND_VAR_NO_REF) { if (function_ptr) { opline->extended_value = ZEND_ARG_COMPILE_TIME_BOUND | send_by_reference | send_function; } else { opline->extended_value = send_function; } } else { if (function_ptr) { opline->extended_value = ZEND_DO_FCALL; } else { opline->extended_value = ZEND_DO_FCALL_BY_NAME; } } opline->opcode = op; SET_NODE(opline->op1, param); opline->op2.opline_num = offset; SET_UNUSED(opline->op2); } /* }}} */ static int generate_free_switch_expr(const zend_switch_entry *switch_entry TSRMLS_DC) /* {{{ */ { zend_op *opline; if (switch_entry->cond.op_type != IS_VAR && switch_entry->cond.op_type != IS_TMP_VAR) { return (switch_entry->cond.op_type == IS_UNUSED); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry->cond); SET_UNUSED(opline->op2); opline->extended_value = 0; return 0; } /* }}} */ static int generate_free_foreach_copy(const zend_op *foreach_copy TSRMLS_DC) /* {{{ */ { zend_op *opline; /* If we reach the seperator then stop applying the stack */ if (foreach_copy->result_type == IS_UNUSED && foreach_copy->op1_type == IS_UNUSED) { return 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->result_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->result); SET_UNUSED(opline->op2); opline->extended_value = 1; if (foreach_copy->op1_type != IS_UNUSED) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->op1_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->op1); SET_UNUSED(opline->op2); opline->extended_value = 0; } return 0; } /* }}} */ void zend_do_return(znode *expr, int do_end_vparse TSRMLS_DC) /* {{{ */ { zend_op *opline; int start_op_number, end_op_number; if (do_end_vparse) { if ((CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) && !zend_is_function_or_method_call(expr)) { zend_do_end_variable_parse(expr, BP_VAR_W, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(expr, BP_VAR_R, 0 TSRMLS_CC); } } start_op_number = get_next_op_number(CG(active_op_array)); #ifdef ZTS zend_stack_apply_with_argument(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_switch_expr TSRMLS_CC); zend_stack_apply_with_argument(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_foreach_copy TSRMLS_CC); #else zend_stack_apply(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_switch_expr); zend_stack_apply(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_foreach_copy); #endif end_op_number = get_next_op_number(CG(active_op_array)); while (start_op_number < end_op_number) { CG(active_op_array)->opcodes[start_op_number].extended_value |= EXT_TYPE_FREE_ON_RETURN; start_op_number++; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) ? ZEND_RETURN_BY_REF : ZEND_RETURN; if (expr) { SET_NODE(opline->op1, expr); if (do_end_vparse && zend_is_function_or_method_call(expr)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } } else { opline->op1_type = IS_CONST; LITERAL_NULL(opline->op1); } SET_UNUSED(opline->op2); } /* }}} */ static int zend_add_try_element(zend_uint try_op TSRMLS_DC) /* {{{ */ { int try_catch_offset = CG(active_op_array)->last_try_catch++; CG(active_op_array)->try_catch_array = erealloc(CG(active_op_array)->try_catch_array, sizeof(zend_try_catch_element)*CG(active_op_array)->last_try_catch); CG(active_op_array)->try_catch_array[try_catch_offset].try_op = try_op; return try_catch_offset; } /* }}} */ static void zend_add_catch_element(int offset, zend_uint catch_op TSRMLS_DC) /* {{{ */ { CG(active_op_array)->try_catch_array[offset].catch_op = catch_op; } /* }}} */ void zend_do_first_catch(znode *open_parentheses TSRMLS_DC) /* {{{ */ { open_parentheses->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_initialize_try_catch_element(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist jmp_list; zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); zend_add_catch_element(try_token->u.op.opline_num, get_next_op_number(CG(active_op_array)) TSRMLS_CC); } /* }}} */ void zend_do_mark_last_catch(const znode *first_catch, const znode *last_additional_catch TSRMLS_DC) /* {{{ */ { CG(active_op_array)->last--; zend_do_if_end(TSRMLS_C); if (last_additional_catch->u.op.opline_num == -1) { CG(active_op_array)->opcodes[first_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[first_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } else { CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_try(znode *try_token TSRMLS_DC) /* {{{ */ { try_token->u.op.opline_num = zend_add_try_element(get_next_op_number(CG(active_op_array)) TSRMLS_CC); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_catch(znode *try_token, znode *class_name, znode *catch_var, znode *first_catch TSRMLS_DC) /* {{{ */ { long catch_op_number; zend_op *opline; znode catch_class; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); catch_class = *class_name; } else { zend_error(E_COMPILE_ERROR, "Bad class name in the catch statement"); } catch_op_number = get_next_op_number(CG(active_op_array)); if (first_catch) { first_catch->u.op.opline_num = catch_op_number; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CATCH; opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &catch_class.u.constant TSRMLS_CC); opline->op2_type = IS_CV; opline->op2.var = lookup_cv(CG(active_op_array), catch_var->u.constant.value.str.val, catch_var->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(catch_var->u.constant) = (char*)CG(active_op_array)->vars[opline->op2.var].name; opline->result.num = 0; /* 1 means it's the last catch in the block */ try_token->u.op.opline_num = catch_op_number; } /* }}} */ void zend_do_end_catch(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); CG(active_op_array)->opcodes[try_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_throw(const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_THROW; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); } /* }}} */ ZEND_API void function_add_ref(zend_function *function) /* {{{ */ { if (function->type == ZEND_USER_FUNCTION) { zend_op_array *op_array = &function->op_array; (*op_array->refcount)++; if (op_array->static_variables) { HashTable *static_variables = op_array->static_variables; zval *tmp_zval; ALLOC_HASHTABLE(op_array->static_variables); zend_hash_init(op_array->static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(op_array->static_variables, static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_zval, sizeof(zval *)); } op_array->run_time_cache = NULL; } } /* }}} */ static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */ { zend_function *function; if (!ce->parent) { return; } /* You cannot change create_object */ ce->create_object = ce->parent->create_object; /* Inherit special functions if needed */ if (!ce->get_iterator) { ce->get_iterator = ce->parent->get_iterator; } if (!ce->iterator_funcs.funcs) { ce->iterator_funcs.funcs = ce->parent->iterator_funcs.funcs; } if (!ce->__get) { ce->__get = ce->parent->__get; } if (!ce->__set) { ce->__set = ce->parent->__set; } if (!ce->__unset) { ce->__unset = ce->parent->__unset; } if (!ce->__isset) { ce->__isset = ce->parent->__isset; } if (!ce->__call) { ce->__call = ce->parent->__call; } if (!ce->__callstatic) { ce->__callstatic = ce->parent->__callstatic; } if (!ce->__tostring) { ce->__tostring = ce->parent->__tostring; } if (!ce->clone) { ce->clone = ce->parent->clone; } if(!ce->serialize) { ce->serialize = ce->parent->serialize; } if(!ce->unserialize) { ce->unserialize = ce->parent->unserialize; } if (!ce->destructor) { ce->destructor = ce->parent->destructor; } if (ce->constructor) { if (ce->parent->constructor && ce->parent->constructor->common.fn_flags & ZEND_ACC_FINAL) { zend_error(E_ERROR, "Cannot override final %s::%s() with %s::%s()", ce->parent->name, ce->parent->constructor->common.function_name, ce->name, ce->constructor->common.function_name ); } return; } if (zend_hash_find(&ce->parent->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), (void **)&function)==SUCCESS) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), function, sizeof(zend_function), NULL); function_add_ref(function); } else { /* Don't inherit the old style constructor if we already have the new style constructor */ char *lc_class_name; char *lc_parent_class_name; lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); if (!zend_hash_exists(&ce->function_table, lc_class_name, ce->name_length+1)) { lc_parent_class_name = zend_str_tolower_dup(ce->parent->name, ce->parent->name_length); if (!zend_hash_exists(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1) && zend_hash_find(&ce->parent->function_table, lc_parent_class_name, ce->parent->name_length+1, (void **)&function)==SUCCESS) { if (function->common.fn_flags & ZEND_ACC_CTOR) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1, function, sizeof(zend_function), NULL); function_add_ref(function); } } efree(lc_parent_class_name); } efree(lc_class_name); } ce->constructor = ce->parent->constructor; } /* }}} */ char *zend_visibility_string(zend_uint fn_flags) /* {{{ */ { if (fn_flags & ZEND_ACC_PRIVATE) { return "private"; } if (fn_flags & ZEND_ACC_PROTECTED) { return "protected"; } if (fn_flags & ZEND_ACC_PUBLIC) { return "public"; } return ""; } /* }}} */ static void do_inherit_method(zend_function *function) /* {{{ */ { /* The class entry of the derived function intentionally remains the same * as that of the parent class. That allows us to know in which context * we're running, and handle private method calls properly. */ function_add_ref(function); } /* }}} */ static zend_bool zend_do_perform_implementation_check(const zend_function *fe, const zend_function *proto TSRMLS_DC) /* {{{ */ { zend_uint i; /* If it's a user function then arg_info == NULL means we don't have any parameters but * we still need to do the arg number checks. We are only willing to ignore this for internal * functions because extensions don't always define arg_info. */ if (!proto || (!proto->common.arg_info && proto->common.type != ZEND_USER_FUNCTION)) { return 1; } /* Checks for constructors only if they are declared in an interface, * or explicitly marked as abstract */ if ((fe->common.fn_flags & ZEND_ACC_CTOR) && ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)) { return 1; } /* check number of arguments */ if (proto->common.required_num_args < fe->common.required_num_args || proto->common.num_args > fe->common.num_args) { return 0; } if (fe->common.type != ZEND_USER_FUNCTION && (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) != 0 && (fe->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) == 0) { return 0; } /* by-ref constraints on return values are covariant */ if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) { return 0; } for (i=0; i < proto->common.num_args; i++) { if (ZEND_LOG_XOR(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)) { /* Only one has a type hint and the other one doesn't */ return 0; } if (fe->common.arg_info[i].class_name && strcasecmp(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)!=0) { const char *colon; if (fe->common.type != ZEND_USER_FUNCTION) { return 0; } else if (strchr(proto->common.arg_info[i].class_name, '\\') != NULL || (colon = zend_memrchr(fe->common.arg_info[i].class_name, '\\', fe->common.arg_info[i].class_name_len)) == NULL || strcasecmp(colon+1, proto->common.arg_info[i].class_name) != 0) { zend_class_entry **fe_ce, **proto_ce; int found, found2; found = zend_lookup_class(fe->common.arg_info[i].class_name, fe->common.arg_info[i].class_name_len, &fe_ce TSRMLS_CC); found2 = zend_lookup_class(proto->common.arg_info[i].class_name, proto->common.arg_info[i].class_name_len, &proto_ce TSRMLS_CC); /* Check for class alias */ if (found != SUCCESS || found2 != SUCCESS || (*fe_ce)->type == ZEND_INTERNAL_CLASS || (*proto_ce)->type == ZEND_INTERNAL_CLASS || *fe_ce != *proto_ce) { return 0; } } } if (fe->common.arg_info[i].type_hint != proto->common.arg_info[i].type_hint) { /* Incompatible type hint */ return 0; } /* by-ref constraints on arguments are invariant */ if (fe->common.arg_info[i].pass_by_reference != proto->common.arg_info[i].pass_by_reference) { return 0; } } if (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) { for (i=proto->common.num_args; i < fe->common.num_args; i++) { if (!fe->common.arg_info[i].pass_by_reference) { return 0; } } } return 1; } /* }}} */ #define REALLOC_BUF_IF_EXCEED(buf, offset, length, size) \ if (UNEXPECTED(offset - buf + size >= length)) { \ length += size + 1; \ buf = erealloc(buf, length); \ } static char * zend_get_function_declaration(zend_function *fptr TSRMLS_DC) /* {{{ */ { char *offset, *buf; zend_uint length = 1024; offset = buf = (char *)emalloc(length * sizeof(char)); if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { *(offset++) = '&'; *(offset++) = ' '; } if (fptr->common.scope) { memcpy(offset, fptr->common.scope->name, fptr->common.scope->name_length); offset += fptr->common.scope->name_length; *(offset++) = ':'; *(offset++) = ':'; } { size_t name_len = strlen(fptr->common.function_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, name_len); memcpy(offset, fptr->common.function_name, name_len); offset += name_len; } *(offset++) = '('; if (fptr->common.arg_info) { zend_uint i, required; zend_arg_info *arg_info = fptr->common.arg_info; required = fptr->common.required_num_args; for (i = 0; i < fptr->common.num_args;) { if (arg_info->class_name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->class_name_len); memcpy(offset, arg_info->class_name, arg_info->class_name_len); offset += arg_info->class_name_len; *(offset++) = ' '; } else if (arg_info->type_hint) { zend_uint type_name_len; char *type_name = zend_get_type_by_const(arg_info->type_hint); type_name_len = strlen(type_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, type_name_len); memcpy(offset, type_name, type_name_len); offset += type_name_len; *(offset++) = ' '; } if (arg_info->pass_by_reference) { *(offset++) = '&'; } *(offset++) = '$'; if (arg_info->name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->name_len); memcpy(offset, arg_info->name, arg_info->name_len); offset += arg_info->name_len; } else { zend_uint idx = i; memcpy(offset, "param", 5); offset += 5; do { *(offset++) = (char) (idx % 10) + '0'; idx /= 10; } while (idx > 0); } if (i >= required) { *(offset++) = ' '; *(offset++) = '='; *(offset++) = ' '; if (fptr->type == ZEND_USER_FUNCTION) { zend_op *precv = NULL; { zend_uint idx = i; zend_op *op = ((zend_op_array *)fptr)->opcodes; zend_op *end = op + ((zend_op_array *)fptr)->last; ++idx; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT) && op->op1.num == (long)idx) { precv = op; } ++op; } } if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) { zval *zv, zv_copy; int use_copy; ALLOC_ZVAL(zv); *zv = *precv->op2.zv; zval_copy_ctor(zv); INIT_PZVAL(zv); zval_update_constant_ex(&zv, (void*)1, fptr->common.scope TSRMLS_CC); if (Z_TYPE_P(zv) == IS_BOOL) { if (Z_LVAL_P(zv)) { memcpy(offset, "true", 4); offset += 4; } else { memcpy(offset, "false", 5); offset += 5; } } else if (Z_TYPE_P(zv) == IS_NULL) { memcpy(offset, "NULL", 4); offset += 4; } else if (Z_TYPE_P(zv) == IS_STRING) { *(offset++) = '\''; REALLOC_BUF_IF_EXCEED(buf, offset, length, MIN(Z_STRLEN_P(zv), 10)); memcpy(offset, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 10)); offset += MIN(Z_STRLEN_P(zv), 10); if (Z_STRLEN_P(zv) > 10) { *(offset++) = '.'; *(offset++) = '.'; *(offset++) = '.'; } *(offset++) = '\''; } else if (Z_TYPE_P(zv) == IS_ARRAY) { memcpy(offset, "Array", 5); offset += 5; } else { zend_make_printable_zval(zv, &zv_copy, &use_copy); REALLOC_BUF_IF_EXCEED(buf, offset, length, Z_STRLEN(zv_copy)); memcpy(offset, Z_STRVAL(zv_copy), Z_STRLEN(zv_copy)); offset += Z_STRLEN(zv_copy); if (use_copy) { zval_dtor(&zv_copy); } } zval_ptr_dtor(&zv); } } else { memcpy(offset, "NULL", 4); offset += 4; } } if (++i < fptr->common.num_args) { *(offset++) = ','; *(offset++) = ' '; } arg_info++; REALLOC_BUF_IF_EXCEED(buf, offset, length, 32); } } *(offset++) = ')'; *offset = '\0'; return buf; } /* }}} */ static void do_inheritance_check_on_method(zend_function *child, zend_function *parent TSRMLS_DC) /* {{{ */ { zend_uint child_flags; zend_uint parent_flags = parent->common.fn_flags; if (parent->common.fn_flags & ZEND_ACC_ABSTRACT && parent->common.scope != (child->common.prototype ? child->common.prototype->common.scope : child->common.scope) && child->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_IMPLEMENTED_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Can't inherit abstract function %s::%s() (previously declared abstract in %s)", parent->common.scope->name, child->common.function_name, child->common.prototype ? child->common.prototype->common.scope->name : child->common.scope->name); } if (parent_flags & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot override final method %s::%s()", ZEND_FN_SCOPE_NAME(parent), child->common.function_name); } child_flags = child->common.fn_flags; /* You cannot change from static to non static and vice versa. */ if ((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC)) { if (child->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot make non static method %s::%s() static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } else { zend_error(E_COMPILE_ERROR, "Cannot make static method %s::%s() non static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } } /* Disallow making an inherited method abstract. */ if ((child_flags & ZEND_ACC_ABSTRACT) && !(parent_flags & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Cannot make non abstract method %s::%s() abstract in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } if (parent_flags & ZEND_ACC_CHANGED) { child->common.fn_flags |= ZEND_ACC_CHANGED; } else { /* Prevent derived classes from restricting access that was available in parent classes */ if ((child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::%s() must be %s (as in class %s)%s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if (((child_flags & ZEND_ACC_PPP_MASK) < (parent_flags & ZEND_ACC_PPP_MASK)) && ((parent_flags & ZEND_ACC_PPP_MASK) & ZEND_ACC_PRIVATE)) { child->common.fn_flags |= ZEND_ACC_CHANGED; } } if (parent_flags & ZEND_ACC_PRIVATE) { child->common.prototype = NULL; } else if (parent_flags & ZEND_ACC_ABSTRACT) { child->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; child->common.prototype = parent; } else if (!(parent->common.fn_flags & ZEND_ACC_CTOR) || (parent->common.prototype && (parent->common.prototype->common.scope->ce_flags & ZEND_ACC_INTERFACE))) { /* ctors only have a prototype if it comes from an interface */ child->common.prototype = parent->common.prototype ? parent->common.prototype : parent; } if (child->common.prototype && (child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { if (!zend_do_perform_implementation_check(child, child->common.prototype TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s::%s() must be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_get_function_declaration(child->common.prototype TSRMLS_CC)); } } else if (EG(error_reporting) & E_STRICT || EG(user_error_handler)) { /* Check E_STRICT (or custom error handler) before the check so that we save some time */ if (!zend_do_perform_implementation_check(child, parent TSRMLS_CC)) { char *method_prototype = zend_get_function_declaration(child->common.prototype TSRMLS_CC); zend_error(E_STRICT, "Declaration of %s::%s() should be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, method_prototype); efree(method_prototype); } } } /* }}} */ static zend_bool do_inherit_method_check(HashTable *child_function_table, zend_function *parent, const zend_hash_key *hash_key, zend_class_entry *child_ce) /* {{{ */ { zend_uint parent_flags = parent->common.fn_flags; zend_function *child; TSRMLS_FETCH(); if (zend_hash_quick_find(child_function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child)==FAILURE) { if (parent_flags & (ZEND_ACC_ABSTRACT)) { child_ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } return 1; /* method doesn't exist in child, copy from parent */ } do_inheritance_check_on_method(child, parent TSRMLS_CC); return 0; } /* }}} */ static zend_bool do_inherit_property_access_check(HashTable *target_ht, zend_property_info *parent_info, const zend_hash_key *hash_key, zend_class_entry *ce) /* {{{ */ { zend_property_info *child_info; zend_class_entry *parent_ce = ce->parent; if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW)) { if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { child_info->flags |= ZEND_ACC_CHANGED; } else { zend_hash_quick_update(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, parent_info, sizeof(zend_property_info), (void **) &child_info); if(ce->type & ZEND_INTERNAL_CLASS) { zend_duplicate_property_info_internal(child_info); } else { zend_duplicate_property_info(child_info); } child_info->flags &= ~ZEND_ACC_PRIVATE; /* it's not private anymore */ child_info->flags |= ZEND_ACC_SHADOW; /* but it's a shadow of private */ } return 0; /* don't copy access information to child */ } if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { if ((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s", (parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", parent_ce->name, hash_key->arKey, (child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ce->name, hash_key->arKey); } if(parent_info->flags & ZEND_ACC_CHANGED) { child_info->flags |= ZEND_ACC_CHANGED; } if ((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ce->name, hash_key->arKey, zend_visibility_string(parent_info->flags), parent_ce->name, (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if ((child_info->flags & ZEND_ACC_STATIC) == 0) { Z_DELREF_P(ce->default_properties_table[parent_info->offset]); ce->default_properties_table[parent_info->offset] = ce->default_properties_table[child_info->offset]; ce->default_properties_table[child_info->offset] = NULL; child_info->offset = parent_info->offset; } return 0; /* Don't copy from parent */ } else { return 1; /* Copy from parent */ } } /* }}} */ static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce TSRMLS_CC) == FAILURE) { zend_error(E_CORE_ERROR, "Class %s could not implement interface %s", ce->name, iface->name); } if (ce == iface) { zend_error(E_ERROR, "Interface %s cannot implement itself", ce->name); } } /* }}} */ ZEND_API void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface TSRMLS_DC) /* {{{ */ { /* expects interface to be contained in ce's interface list already */ zend_uint i, ce_num, if_num = iface->num_interfaces; zend_class_entry *entry; if (if_num==0) { return; } ce_num = ce->num_interfaces; if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } /* Inherit the interfaces, only if they're not already inherited by the class */ while (if_num--) { entry = iface->interfaces[if_num]; for (i = 0; i < ce_num; i++) { if (ce->interfaces[i] == entry) { break; } } if (i == ce_num) { ce->interfaces[ce->num_interfaces++] = entry; } } /* and now call the implementing handlers */ while (ce_num < ce->num_interfaces) { do_implement_interface(ce, ce->interfaces[ce_num++] TSRMLS_CC); } } /* }}} */ #ifdef ZTS static void zval_internal_ctor(zval **p) /* {{{ */ { zval *orig_ptr = *p; ALLOC_ZVAL(*p); MAKE_COPY_ZVAL(&orig_ptr, *p); } /* }}} */ # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) (((parent_ce)->type != (ce)->type) ? zval_internal_ctor : zval_add_ref)) #else # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) zval_add_ref) #endif ZEND_API void zend_do_inheritance(zend_class_entry *ce, zend_class_entry *parent_ce TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; if ((ce->ce_flags & ZEND_ACC_INTERFACE) && !(parent_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ce->name, parent_ce->name); } if (parent_ce->ce_flags & ZEND_ACC_FINAL_CLASS) { zend_error(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ce->name, parent_ce->name); } ce->parent = parent_ce; /* Copy serialize/unserialize callbacks */ if (!ce->serialize) { ce->serialize = parent_ce->serialize; } if (!ce->unserialize) { ce->unserialize = parent_ce->unserialize; } /* Inherit interfaces */ zend_do_inherit_interfaces(ce, parent_ce TSRMLS_CC); /* Inherit properties */ if (parent_ce->default_properties_count) { int i = ce->default_properties_count + parent_ce->default_properties_count; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_properties_count) { while (i-- > parent_ce->default_properties_count) { ce->default_properties_table[i] = ce->default_properties_table[i - parent_ce->default_properties_count]; } } for (i = 0; i < parent_ce->default_properties_count; i++) { ce->default_properties_table[i] = parent_ce->default_properties_table[i]; if (ce->default_properties_table[i]) { #ifdef ZTS if (parent_ce->type != ce->type) { zval *p; ALLOC_ZVAL(p); MAKE_COPY_ZVAL(&ce->default_properties_table[i], p); ce->default_properties_table[i] = p; } else { Z_ADDREF_P(ce->default_properties_table[i]); } #else Z_ADDREF_P(ce->default_properties_table[i]); #endif } } ce->default_properties_count += parent_ce->default_properties_count; } if (parent_ce->type != ce->type) { /* User class extends internal class */ zend_update_class_constants(parent_ce TSRMLS_CC); if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = erealloc(ce->default_static_members_table, sizeof(void*) * i); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&CE_STATIC_MEMBERS(parent_ce)[i]); ce->default_static_members_table[i] = CE_STATIC_MEMBERS(parent_ce)[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; ce->static_members_table = ce->default_static_members_table; } } else { if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&parent_ce->default_static_members_table[i]); ce->default_static_members_table[i] = parent_ce->default_static_members_table[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } } for (zend_hash_internal_pointer_reset(&ce->properties_info); zend_hash_get_current_data(&ce->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->properties_info)) { if (property_info->ce == ce) { if (property_info->flags & ZEND_ACC_STATIC) { property_info->offset += parent_ce->default_static_members_count; } else { property_info->offset += parent_ce->default_properties_count; } } } zend_hash_merge_ex(&ce->properties_info, &parent_ce->properties_info, (copy_ctor_func_t) (ce->type & ZEND_INTERNAL_CLASS ? zend_duplicate_property_info_internal : zend_duplicate_property_info), sizeof(zend_property_info), (merge_checker_func_t) do_inherit_property_access_check, ce); zend_hash_merge(&ce->constants_table, &parent_ce->constants_table, zval_property_ctor(parent_ce, ce), NULL, sizeof(zval *), 0); zend_hash_merge_ex(&ce->function_table, &parent_ce->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_inherit_parent_constructor(ce); if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS && ce->type == ZEND_INTERNAL_CLASS) { ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } else if (!(ce->ce_flags & ZEND_ACC_IMPLEMENT_INTERFACES) && !(ce->ce_flags & ZEND_ACC_IMPLEMENT_TRAITS)) { /* The verification will be done in runtime by ZEND_VERIFY_ABSTRACT_CLASS */ zend_verify_abstract_class(ce TSRMLS_CC); } ce->ce_flags |= parent_ce->ce_flags & ZEND_HAS_STATIC_IN_METHODS; } /* }}} */ static zend_bool do_inherit_constant_check(HashTable *child_constants_table, const zval **parent_constant, const zend_hash_key *hash_key, const zend_class_entry *iface) /* {{{ */ { zval **old_constant; if (zend_hash_quick_find(child_constants_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**)&old_constant) == SUCCESS) { if (*old_constant != *parent_constant) { zend_error(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", hash_key->arKey, iface->name); } return 0; } return 1; } /* }}} */ static int do_interface_constant_check(zval **val TSRMLS_DC, int num_args, va_list args, const zend_hash_key *key) /* {{{ */ { zend_class_entry **iface = va_arg(args, zend_class_entry**); do_inherit_constant_check(&(*iface)->constants_table, (const zval **) val, key, *iface); return ZEND_HASH_APPLY_KEEP; } /* }}} */ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_iface_num = ce->num_interfaces; zend_uint parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0; for (i = 0; i < ce->num_interfaces; i++) { if (ce->interfaces[i] == NULL) { memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i)); i--; } else if (ce->interfaces[i] == iface) { if (i < parent_iface_num) { ignore = 1; } else { zend_error(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ce->name, iface->name); } } } if (ignore) { /* Check for attempt to redeclare interface constants */ zend_hash_apply_with_arguments(&ce->constants_table TSRMLS_CC, (apply_func_args_t) do_interface_constant_check, 1, &iface); } else { if (ce->num_interfaces >= current_iface_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } } ce->interfaces[ce->num_interfaces++] = iface; zend_hash_merge_ex(&ce->constants_table, &iface->constants_table, (copy_ctor_func_t) zval_add_ref, sizeof(zval *), (merge_checker_func_t) do_inherit_constant_check, iface); zend_hash_merge_ex(&ce->function_table, &iface->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_implement_interface(ce, iface TSRMLS_CC); zend_do_inherit_interfaces(ce, iface TSRMLS_CC); } } /* }}} */ ZEND_API void zend_do_implement_trait(zend_class_entry *ce, zend_class_entry *trait TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_trait_num = ce->num_traits; zend_uint parent_trait_num = ce->parent ? ce->parent->num_traits : 0; for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == NULL) { memmove(ce->traits + i, ce->traits + i + 1, sizeof(zend_class_entry*) * (--ce->num_traits - i)); i--; } else if (ce->traits[i] == trait) { if (i < parent_trait_num) { ignore = 1; } } } if (!ignore) { if (ce->num_traits >= current_trait_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->traits = (zend_class_entry **) realloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } else { ce->traits = (zend_class_entry **) erealloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } } ce->traits[ce->num_traits++] = trait; } } /* }}} */ static int zend_traits_merge_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { size_t current; size_t i; size_t count; HashTable* resulting_table; HashTable** function_tables; zend_class_entry *ce; size_t collision = 0; size_t abstract_solved = 0; zend_function* other_trait_fn; current = va_arg(args, size_t); /* index of current trait */ count = va_arg(args, size_t); resulting_table = va_arg(args, HashTable*); function_tables = va_arg(args, HashTable**); ce = va_arg(args, zend_class_entry*); for (i = 0; i < count; i++) { if (i == current) { continue; /* just skip this, cause its the table this function is applied on */ } if (zend_hash_quick_find(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&other_trait_fn) == SUCCESS) { /* if it is an abstract method, there is no collision */ if (other_trait_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible */ do_inheritance_check_on_method(fn, other_trait_fn TSRMLS_CC); /* we can savely free and remove it from other table */ zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } else { /* if it is not an abstract method, there is still no collision */ /* if fn is an abstract method */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible */ do_inheritance_check_on_method(other_trait_fn, fn TSRMLS_CC); /* just mark as solved, will be added if its own trait is processed */ abstract_solved = 1; } else { /* but else, we have a collision of non-abstract methods */ collision++; zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } } } if (collision) { zend_function* class_fn; /* make sure method is not already overridden in class */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&class_fn) == FAILURE || class_fn->common.scope != ce) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because there are collisions with other trait methods on %s", fn->common.function_name, ce->name); } zend_function_dtor(fn); } else if (abstract_solved) { zend_function_dtor(fn); } else { /* Add it to result function table */ if (zend_hash_quick_add(resulting_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, fn, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating resulting trait method table", fn->common.function_name); } } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ /* {{{ Originates from php_runkit_function_copy_ctor Duplicate structures in an op_array where necessary to make an outright duplicate */ static void zend_traits_duplicate_function(zend_function *fe, zend_class_entry *target_ce, char *newname TSRMLS_DC) { zend_literal *literals_copy; zend_compiled_variable *dupvars; zend_op *opcode_copy; zval class_name_zv; int class_name_literal; int i; int number_of_literals; if (fe->op_array.static_variables) { HashTable *tmpHash; ALLOC_HASHTABLE(tmpHash); zend_hash_init(tmpHash, zend_hash_num_elements(fe->op_array.static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_apply_with_arguments(fe->op_array.static_variables TSRMLS_CC, (apply_func_args_t)zval_copy_static_var, 1, tmpHash); fe->op_array.static_variables = tmpHash; } number_of_literals = fe->op_array.last_literal; literals_copy = (zend_literal*)emalloc(number_of_literals * sizeof(zend_literal)); for (i = 0; i < number_of_literals; i++) { literals_copy[i] = fe->op_array.literals[i]; zval_copy_ctor(&literals_copy[i].constant); } fe->op_array.literals = literals_copy; fe->op_array.refcount = emalloc(sizeof(zend_uint)); *(fe->op_array.refcount) = 1; if (fe->op_array.vars) { i = fe->op_array.last_var; dupvars = safe_emalloc(fe->op_array.last_var, sizeof(zend_compiled_variable), 0); while (i > 0) { i--; dupvars[i].name = estrndup(fe->op_array.vars[i].name, fe->op_array.vars[i].name_len); dupvars[i].name_len = fe->op_array.vars[i].name_len; dupvars[i].hash_value = fe->op_array.vars[i].hash_value; } fe->op_array.vars = dupvars; } else { fe->op_array.vars = NULL; } opcode_copy = safe_emalloc(sizeof(zend_op), fe->op_array.last, 0); for(i = 0; i < fe->op_array.last; i++) { opcode_copy[i] = fe->op_array.opcodes[i]; if (opcode_copy[i].op1_type != IS_CONST) { if (opcode_copy[i].op1.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op1.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op1.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op1.jmp_addr - fe->op_array.opcodes); } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op1.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op1.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op1.zv = &fe->op_array.literals[class_name_literal].constant; } } if (opcode_copy[i].op2_type != IS_CONST) { if (opcode_copy[i].op2.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op2.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op2.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op2.jmp_addr - fe->op_array.opcodes); } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op2.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op2.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op2.zv = &fe->op_array.literals[class_name_literal].constant; } } } fe->op_array.opcodes = opcode_copy; fe->op_array.function_name = newname; /* was setting it to fe which does not work since fe is stack allocated and not a stable address */ /* fe->op_array.prototype = fe->op_array.prototype; */ if (fe->op_array.arg_info) { zend_arg_info *tmpArginfo; tmpArginfo = safe_emalloc(sizeof(zend_arg_info), fe->op_array.num_args, 0); for(i = 0; i < fe->op_array.num_args; i++) { tmpArginfo[i] = fe->op_array.arg_info[i]; tmpArginfo[i].name = estrndup(tmpArginfo[i].name, tmpArginfo[i].name_len); if (tmpArginfo[i].class_name) { tmpArginfo[i].class_name = estrndup(tmpArginfo[i].class_name, tmpArginfo[i].class_name_len); } } fe->op_array.arg_info = tmpArginfo; } fe->op_array.doc_comment = estrndup(fe->op_array.doc_comment, fe->op_array.doc_comment_len); fe->op_array.try_catch_array = (zend_try_catch_element*)estrndup((char*)fe->op_array.try_catch_array, sizeof(zend_try_catch_element) * fe->op_array.last_try_catch); fe->op_array.brk_cont_array = (zend_brk_cont_element*)estrndup((char*)fe->op_array.brk_cont_array, sizeof(zend_brk_cont_element) * fe->op_array.last_brk_cont); } /* }}} */ static void zend_add_magic_methods(zend_class_entry* ce, const char* mname, uint mname_len, zend_function* fe TSRMLS_DC) { if ( !strncmp(mname, ZEND_CLONE_FUNC_NAME, mname_len)) { ce->clone = fe; fe->common.fn_flags |= ZEND_ACC_CLONE; } else if (!strncmp(mname, ZEND_CONSTRUCTOR_FUNC_NAME, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } else if (!strncmp(mname, ZEND_DESTRUCTOR_FUNC_NAME, mname_len)) { ce->destructor = fe; fe->common.fn_flags |= ZEND_ACC_DTOR; } else if (!strncmp(mname, ZEND_GET_FUNC_NAME, mname_len)) ce->__get = fe; else if (!strncmp(mname, ZEND_SET_FUNC_NAME, mname_len)) ce->__set = fe; else if (!strncmp(mname, ZEND_CALL_FUNC_NAME, mname_len)) ce->__call = fe; else if (!strncmp(mname, ZEND_UNSET_FUNC_NAME, mname_len)) ce->__unset = fe; else if (!strncmp(mname, ZEND_ISSET_FUNC_NAME, mname_len)) ce->__isset = fe; else if (!strncmp(mname, ZEND_CALLSTATIC_FUNC_NAME, mname_len)) ce->__callstatic= fe; else if (!strncmp(mname, ZEND_TOSTRING_FUNC_NAME, mname_len)) ce->__tostring = fe; else if (ce->name_length + 1 == mname_len) { char *lowercase_name = emalloc(ce->name_length + 1); zend_str_tolower_copy(lowercase_name, ce->name, ce->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, ce->name_length + 1, 1 TSRMLS_CC); if (!memcmp(mname, lowercase_name, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } str_efree(lowercase_name); } } static int zend_traits_merge_functions_to_class(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zend_class_entry *ce = va_arg(args, zend_class_entry*); int add = 0; zend_function* existing_fn; zend_function fn_copy, *fn_copy_p; zend_function* prototype = NULL; /* is used to determine the prototype according to the inheritance chain */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &existing_fn) == FAILURE) { add = 1; /* not found */ } else if (existing_fn->common.scope != ce) { add = 1; /* or inherited from other class or interface */ /* it is just a reference which was added to the subclass while doing the inheritance */ /* so we can deleted now, and will add the overriding method afterwards */ /* except, if we try to add an abstract function, then we should not delete the inherited one */ /* delete inherited fn if the function to be added is not abstract */ if ((fn->common.fn_flags & ZEND_ACC_ABSTRACT) == 0) { zend_hash_quick_del(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } if (add) { zend_function* parent_function; if (ce->parent && zend_hash_quick_find(&ce->parent->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &parent_function) != FAILURE) { prototype = parent_function; /* ->common.fn_flags |= ZEND_ACC_ABSTRACT; */ /* we got that method in the parent class, and are going to override it, except, if the trait is just asking to have an abstract method implemented. */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* then we clean up an skip this method */ zend_function_dtor(fn); return ZEND_HASH_APPLY_REMOVE; } } fn->common.scope = ce; fn->common.prototype = prototype; if (prototype && (prototype->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT || prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { fn->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; } else if (fn->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT) { /* remove ZEND_ACC_IMPLEMENTED_ABSTRACT flag, think it shouldn't be copied to class */ fn->common.fn_flags = fn->common.fn_flags - ZEND_ACC_IMPLEMENTED_ABSTRACT; } /* check whether the trait method fullfills the inheritance requirements */ if (prototype) { do_inheritance_check_on_method(fn, prototype TSRMLS_CC); } if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (fn->op_array.static_variables) { ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, ce, estrdup(fn->common.function_name) TSRMLS_CC); if (zend_hash_quick_update(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, &fn_copy, sizeof(zend_function), (void**)&fn_copy_p)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating class method table", hash_key->arKey); } zend_add_magic_methods(ce, hash_key->arKey, hash_key->nKeyLength, fn_copy_p TSRMLS_CC); zend_function_dtor(fn); } else { zend_function_dtor(fn); } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ static int zend_traits_copy_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { HashTable* target; zend_class_entry *target_ce; zend_trait_alias** aliases; HashTable* exclude_table; char* lcname; unsigned int fnname_len; zend_function fn_copy; void* dummy; size_t i = 0; target = va_arg(args, HashTable*); target_ce = va_arg(args, zend_class_entry*); aliases = va_arg(args, zend_trait_alias**); exclude_table = va_arg(args, HashTable*); fnname_len = strlen(fn->common.function_name); /* apply aliases which are qualified with a class name, there should not be any ambiguity */ if (aliases) { while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias != NULL && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && aliases[i]->trait_method->mname_len == fnname_len && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(aliases[i]->alias, aliases[i]->alias_len) TSRMLS_CC); /* if it is 0, no modifieres has been changed */ if (aliases[i]->modifiers) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } lcname = zend_str_tolower_dup(aliases[i]->alias, aliases[i]->alias_len); if (zend_hash_add(target, lcname, aliases[i]->alias_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add aliased trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } efree(lcname); } i++; } } lcname = zend_str_tolower_dup(fn->common.function_name, fnname_len); if (exclude_table == NULL || zend_hash_find(exclude_table, lcname, fnname_len, &dummy) == FAILURE) { /* is not in hashtable, thus, function is not to be excluded */ fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(fn->common.function_name, fnname_len) TSRMLS_CC); /* apply aliases which are not qualified by a class name, or which have not * alias name, just setting visibility */ if (aliases) { i = 0; while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias == NULL && aliases[i]->modifiers != 0 && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && (aliases[i]->trait_method->mname_len == fnname_len) && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } i++; } } if (zend_hash_add(target, lcname, fnname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } } efree(lcname); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* Copies function table entries to target function table with applied aliasing */ static void zend_traits_copy_trait_function_table(HashTable *target, zend_class_entry *target_ce, HashTable *source, zend_trait_alias** aliases, HashTable* exclude_table TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_arguments(source TSRMLS_CC, (apply_func_args_t)zend_traits_copy_functions, 4, target, target_ce, aliases, exclude_table); } /* }}} */ static void zend_traits_init_trait_structures(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i, j = 0; zend_trait_precedence *cur_precedence; zend_trait_method_reference *cur_method_ref; /* resolve class references */ if (ce->trait_precedences) { i = 0; while ((cur_precedence = ce->trait_precedences[i])) { if (cur_precedence->exclude_from_classes) { cur_precedence->trait_method->ce = zend_fetch_class(cur_precedence->trait_method->class_name, cur_precedence->trait_method->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); j = 0; while (cur_precedence->exclude_from_classes[j]) { char* class_name = (char*)cur_precedence->exclude_from_classes[j]; zend_uint name_length = strlen(class_name); cur_precedence->exclude_from_classes[j] = zend_fetch_class(class_name, name_length, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); efree(class_name); j++; } } i++; } } if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { if (ce->trait_aliases[i]->trait_method->class_name) { cur_method_ref = ce->trait_aliases[i]->trait_method; cur_method_ref->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); } i++; } } } /* }}} */ static void zend_traits_compile_exclude_table(HashTable* exclude_table, zend_trait_precedence **precedences, zend_class_entry *trait) /* {{{ */ { size_t i = 0, j; if (!precedences) { return; } while (precedences[i]) { if (precedences[i]->exclude_from_classes) { j = 0; while (precedences[i]->exclude_from_classes[j]) { if (precedences[i]->exclude_from_classes[j] == trait) { zend_uint lcname_len = precedences[i]->trait_method->mname_len; char *lcname = zend_str_tolower_dup(precedences[i]->trait_method->method_name, lcname_len); if (zend_hash_add(exclude_table, lcname, lcname_len, NULL, 0, NULL) == FAILURE) { efree(lcname); zend_error(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", precedences[i]->trait_method->method_name, trait->name); } efree(lcname); } ++j; } } ++i; } } /* }}} */ static void zend_do_traits_method_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { HashTable** function_tables; HashTable* resulting_table; HashTable exclude_table; size_t i; /* prepare copies of trait function tables for combination */ function_tables = malloc(sizeof(HashTable*) * ce->num_traits); resulting_table = (HashTable *) malloc(sizeof(HashTable)); /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(resulting_table, 10, NULL, NULL, 1, 0); for (i = 0; i < ce->num_traits; i++) { function_tables[i] = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(function_tables[i], ce->traits[i]->function_table.nNumOfElements, NULL, NULL, 1, 0); if (ce->trait_precedences) { /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(&exclude_table, 2, NULL, NULL, 0, 0); zend_traits_compile_exclude_table(&exclude_table, ce->trait_precedences, ce->traits[i]); /* copies functions, applies defined aliasing, and excludes unused trait methods */ zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, &exclude_table TSRMLS_CC); zend_hash_graceful_destroy(&exclude_table); } else { zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, NULL TSRMLS_CC); } } /* now merge trait methods */ for (i = 0; i < ce->num_traits; i++) { zend_hash_apply_with_arguments(function_tables[i] TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions, 5, i, ce->num_traits, resulting_table, function_tables, ce); } /* Now the resulting_table contains all trait methods we would have to * add to the class in the following step the methods are inserted into the method table * if there is already a method with the same name it is replaced iff ce != fn.scope * --> all inherited methods are overridden, methods defined in the class are left untouched */ zend_hash_apply_with_arguments(resulting_table TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions_to_class, 1, ce); /* free temporary function tables */ for (i = 0; i < ce->num_traits; i++) { /* zend_hash_destroy(function_tables[i]); */ zend_hash_graceful_destroy(function_tables[i]); free(function_tables[i]); } free(function_tables); /* free temporary resulting table */ /* zend_hash_destroy(resulting_table); */ zend_hash_graceful_destroy(resulting_table); free(resulting_table); } /* }}} */ static zend_class_entry* find_first_definition(zend_class_entry *ce, size_t current_trait, const char* prop_name, int prop_name_length, ulong prop_hash, zend_class_entry *coliding_ce) /* {{{ */ { size_t i; zend_property_info *coliding_prop; for (i = 0; (i < current_trait) && (i < ce->num_traits); i++) { if (zend_hash_quick_find(&ce->traits[i]->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS) { return ce->traits[i]; } } return coliding_ce; } /* }}} */ static void zend_do_traits_property_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i; zend_property_info *property_info; zend_property_info *coliding_prop; zval compare_result; const char* prop_name; int prop_name_length; ulong prop_hash; const char* class_name_unused; zend_bool prop_found; zend_bool not_compatible; zval* prop_value; /* In the following steps the properties are inserted into the property table * for that, a very strict approach is applied: * - check for compatibility, if not compatible with any property in class -> fatal * - if compatible, then strict notice */ for (i = 0; i < ce->num_traits; i++) { for (zend_hash_internal_pointer_reset(&ce->traits[i]->properties_info); zend_hash_get_current_data(&ce->traits[i]->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->traits[i]->properties_info)) { /* first get the unmangeld name if necessary, * then check whether the property is already there */ if ((property_info->flags & ZEND_ACC_PPP_MASK) == ZEND_ACC_PUBLIC) { prop_hash = property_info->h; prop_name = property_info->name; prop_name_length = property_info->name_length; prop_found = zend_hash_quick_find(&ce->properties_info, property_info->name, property_info->name_length+1, property_info->h, (void **) &coliding_prop) == SUCCESS; } else { /* for private and protected we need to unmangle the names */ zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name_unused, &prop_name); prop_name_length = strlen(prop_name); prop_hash = zend_get_hash_value(prop_name, prop_name_length + 1); prop_found = zend_hash_quick_find(&ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS; } /* next: check for conflicts with current class */ if (prop_found) { if (coliding_prop->flags & ZEND_ACC_SHADOW) { /* this one is inherited, lets look it up in its own class */ zend_hash_quick_find(&coliding_prop->ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop); } if ((coliding_prop->flags & ZEND_ACC_PPP_MASK) == (property_info->flags & ZEND_ACC_PPP_MASK)) { /* flags are identical, now the value needs to be checked */ if (property_info->flags & ZEND_ACC_STATIC) { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_static_members_table[coliding_prop->offset], ce->traits[i]->default_static_members_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } else { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_properties_table[coliding_prop->offset], ce->traits[i]->default_properties_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } } else { /* the flags are not identical, thus, we assume properties are not compatible */ not_compatible = 1; } if (not_compatible) { zend_error(E_COMPILE_ERROR, "%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } else { zend_error(E_STRICT, "%s and %s define the same property ($%s) in the composition of %s. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } } /* property not found, so lets add it */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); zend_declare_property_ex(ce, prop_name, prop_name_length, prop_value, property_info->flags, property_info->doc_comment, property_info->doc_comment_len TSRMLS_CC); } } } /* }}} */ ZEND_API void zend_do_bind_traits(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { if (ce->num_traits <= 0) { return; } /* complete initialization of trait strutures in ce */ zend_traits_init_trait_structures(ce TSRMLS_CC); /* first care about all methods to be flattened into the class */ zend_do_traits_method_binding(ce TSRMLS_CC); /* then flatten the properties into it, to, mostly to notfiy developer about problems */ zend_do_traits_property_binding(ce TSRMLS_CC); /* verify that all abstract methods from traits have been implemented */ zend_verify_abstract_class(ce TSRMLS_CC); /* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */ if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { ce->ce_flags -= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } } /* }}} */ ZEND_API int do_bind_function(const zend_op_array *op_array, zend_op *opline, HashTable *function_table, zend_bool compile_time) /* {{{ */ { zend_function *function; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } zend_hash_quick_find(function_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void *) &function); if (zend_hash_quick_add(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), function, sizeof(zend_function), NULL)==FAILURE) { int error_level = compile_time ? E_COMPILE_ERROR : E_ERROR; zend_function *old_function; if (zend_hash_quick_find(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), (void *) &old_function)==SUCCESS && old_function->type == ZEND_USER_FUNCTION && old_function->op_array.last > 0) { zend_error(error_level, "Cannot redeclare %s() (previously declared in %s:%d)", function->common.function_name, old_function->op_array.filename, old_function->op_array.opcodes[0].lineno); } else { zend_error(error_level, "Cannot redeclare %s()", function->common.function_name); } return FAILURE; } else { (*function->op_array.refcount)++; function->op_array.static_variables = NULL; /* NULL out the unbound function */ return SUCCESS; } } /* }}} */ void zend_add_trait_precedence(znode *precedence_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_precedences, precedence_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_add_trait_alias(znode *alias_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_aliases, alias_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_prepare_reference(znode *result, znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { zend_trait_method_reference *method_ref = emalloc(sizeof(zend_trait_method_reference)); method_ref->ce = NULL; /* REM: There should not be a need for copying, zend_do_begin_class_declaration is also just using that string */ if (class_name) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); method_ref->class_name = Z_STRVAL(class_name->u.constant); method_ref->cname_len = Z_STRLEN(class_name->u.constant); } else { method_ref->class_name = NULL; method_ref->cname_len = 0; } method_ref->method_name = Z_STRVAL(method_name->u.constant); method_ref->mname_len = Z_STRLEN(method_name->u.constant); result->u.op.ptr = method_ref; result->op_type = IS_TMP_VAR; } /* }}} */ void zend_prepare_trait_alias(znode *result, znode *method_reference, znode *modifiers, znode *alias TSRMLS_DC) /* {{{ */ { zend_trait_alias *trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_alias->modifiers = Z_LVAL(modifiers->u.constant); if (Z_LVAL(modifiers->u.constant) == ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot use 'static' as method modifier"); return; } if (alias) { trait_alias->alias = Z_STRVAL(alias->u.constant); trait_alias->alias_len = Z_STRLEN(alias->u.constant); } else { trait_alias->alias = NULL; } trait_alias->function = NULL; result->u.op.ptr = trait_alias; } /* }}} */ void zend_prepare_trait_precedence(znode *result, znode *method_reference, znode *trait_list TSRMLS_DC) /* {{{ */ { zend_trait_precedence *trait_precedence = emalloc(sizeof(zend_trait_precedence)); trait_precedence->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_precedence->exclude_from_classes = (zend_class_entry**) trait_list->u.op.ptr; trait_precedence->function = NULL; result->u.op.ptr = trait_precedence; } /* }}} */ ZEND_API zend_class_entry *do_bind_class(const zend_op_array* op_array, const zend_op *opline, HashTable *class_table, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } if (zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce)==FAILURE) { zend_error(E_COMPILE_ERROR, "Internal Zend error - Missing class information for %s", Z_STRVAL_P(op1)); return NULL; } else { ce = *pce; } ce->refcount++; if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), &ce, sizeof(zend_class_entry *), NULL)==FAILURE) { ce->refcount--; if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return NULL; } else { if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLEMENT_INTERFACES))) { zend_verify_abstract_class(ce TSRMLS_CC); } return ce; } } /* }}} */ ZEND_API zend_class_entry *do_bind_inherited_class(const zend_op_array *op_array, const zend_op *opline, HashTable *class_table, zend_class_entry *parent_ce, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; int found_ce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } found_ce = zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce); if (found_ce == FAILURE) { if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", Z_STRVAL_P(op2)); } return NULL; } else { ce = *pce; } if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ce->name, parent_ce->name); } else if ((parent_ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ce->name, parent_ce->name); } zend_do_inheritance(ce, parent_ce TSRMLS_CC); ce->refcount++; /* Register the derived class */ if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), pce, sizeof(zend_class_entry *), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return ce; } /* }}} */ void zend_do_early_binding(TSRMLS_D) /* {{{ */ { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; HashTable *table; while (opline->opcode == ZEND_TICKS && opline > CG(active_op_array)->opcodes) { opline--; } switch (opline->opcode) { case ZEND_DECLARE_FUNCTION: if (do_bind_function(CG(active_op_array), opline, CG(function_table), 1) == FAILURE) { return; } table = CG(function_table); break; case ZEND_DECLARE_CLASS: if (do_bind_class(CG(active_op_array), opline, CG(class_table), 1 TSRMLS_CC) == NULL) { return; } table = CG(class_table); break; case ZEND_DECLARE_INHERITED_CLASS: { zend_op *fetch_class_opline = opline-1; zval *parent_name; zend_class_entry **pce; parent_name = &CONSTANT(fetch_class_opline->op2.constant); if ((zend_lookup_class(Z_STRVAL_P(parent_name), Z_STRLEN_P(parent_name), &pce TSRMLS_CC) == FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_CLASSES) && ((*pce)->type == ZEND_INTERNAL_CLASS))) { if (CG(compiler_options) & ZEND_COMPILE_DELAYED_BINDING) { zend_uint *opline_num = &CG(active_op_array)->early_binding; while (*opline_num != -1) { opline_num = &CG(active_op_array)->opcodes[*opline_num].result.opline_num; } *opline_num = opline - CG(active_op_array)->opcodes; opline->opcode = ZEND_DECLARE_INHERITED_CLASS_DELAYED; opline->result_type = IS_UNUSED; opline->result.opline_num = -1; } return; } if (do_bind_inherited_class(CG(active_op_array), opline, CG(class_table), *pce, 1 TSRMLS_CC) == NULL) { return; } /* clear unnecessary ZEND_FETCH_CLASS opcode */ zend_del_literal(CG(active_op_array), fetch_class_opline->op2.constant); MAKE_NOP(fetch_class_opline); table = CG(class_table); break; } case ZEND_VERIFY_ABSTRACT_CLASS: case ZEND_ADD_INTERFACE: case ZEND_ADD_TRAIT: case ZEND_BIND_TRAITS: /* We currently don't early-bind classes that implement interfaces */ /* Classes with traits are handled exactly the same, no early-bind here */ return; default: zend_error(E_COMPILE_ERROR, "Invalid binding type"); return; } zend_hash_quick_del(table, Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant)), Z_HASH_P(&CONSTANT(opline->op1.constant))); zend_del_literal(CG(active_op_array), opline->op1.constant); zend_del_literal(CG(active_op_array), opline->op2.constant); MAKE_NOP(opline); } /* }}} */ ZEND_API void zend_do_delayed_early_binding(const zend_op_array *op_array TSRMLS_DC) /* {{{ */ { if (op_array->early_binding != -1) { zend_bool orig_in_compilation = CG(in_compilation); zend_uint opline_num = op_array->early_binding; zend_class_entry **pce; CG(in_compilation) = 1; while (opline_num != -1) { if (zend_lookup_class(Z_STRVAL_P(op_array->opcodes[opline_num-1].op2.zv), Z_STRLEN_P(op_array->opcodes[opline_num-1].op2.zv), &pce TSRMLS_CC) == SUCCESS) { do_bind_inherited_class(op_array, &op_array->opcodes[opline_num], EG(class_table), *pce, 0 TSRMLS_CC); } opline_num = op_array->opcodes[opline_num].result.opline_num; } CG(in_compilation) = orig_in_compilation; } } /* }}} */ void zend_do_boolean_or_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_or_end(znode *result, const znode *expr1, const znode *expr2, znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_boolean_and_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_and_end(znode *result, const znode *expr1, const znode *expr2, const znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_do_while_begin(TSRMLS_D) /* {{{ */ { do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_do_while_end(const znode *do_token, const znode *expr_open_bracket, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ; SET_NODE(opline->op1, expr); opline->op2.opline_num = do_token->u.op.opline_num; SET_UNUSED(opline->op2); do_end_loop(expr_open_bracket->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_brk_cont(zend_uchar op, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->op1.opline_num = CG(context).current_brk_cont; SET_UNUSED(opline->op1); if (expr) { if (expr->op_type != IS_CONST) { zend_error(E_COMPILE_ERROR, "'%s' operator with non-constant operand is no longer supported", op == ZEND_BRK ? "break" : "continue"); } else if (Z_TYPE(expr->u.constant) != IS_LONG || Z_LVAL(expr->u.constant) < 1) { zend_error(E_COMPILE_ERROR, "'%s' operator accepts only positive numbers", op == ZEND_BRK ? "break" : "continue"); } SET_NODE(opline->op2, expr); } else { LITERAL_LONG(opline->op2, 1); opline->op2_type = IS_CONST; } } /* }}} */ void zend_do_switch_cond(const znode *cond TSRMLS_DC) /* {{{ */ { zend_switch_entry switch_entry; switch_entry.cond = *cond; switch_entry.default_case = -1; switch_entry.control_var = -1; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_switch_end(const znode *case_list TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); /* add code to jmp to default case */ if (switch_entry_ptr->default_case != -1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->op1.opline_num = switch_entry_ptr->default_case; } if (case_list->op_type != IS_UNUSED) { /* non-empty switch */ int next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* remember break/continue loop information */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; if (switch_entry_ptr->cond.op_type==IS_VAR || switch_entry_ptr->cond.op_type==IS_TMP_VAR) { /* emit free for the switch condition*/ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry_ptr->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_UNUSED(opline->op2); } if (switch_entry_ptr->cond.op_type == IS_CONST) { zval_dtor(&switch_entry_ptr->cond.u.constant); } zend_stack_del_top(&CG(switch_cond_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_case_before_statement(const znode *case_list, znode *case_token, const znode *case_expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); int next_op_number; zend_switch_entry *switch_entry_ptr; znode result; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); if (switch_entry_ptr->control_var == -1) { switch_entry_ptr->control_var = get_temporary_variable(CG(active_op_array)); } opline->opcode = ZEND_CASE; opline->result.var = switch_entry_ptr->control_var; opline->result_type = IS_TMP_VAR; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_NODE(opline->op2, case_expr); if (opline->op1_type == IS_CONST) { zval_copy_ctor(&CONSTANT(opline->op1.constant)); } GET_NODE(&result, opline->result); next_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, &result); SET_UNUSED(opline->op2); case_token->u.op.opline_num = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_case_after_statement(znode *result, const znode *case_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); result->u.op.opline_num = next_op_number; switch (CG(active_op_array)->opcodes[case_token->u.op.opline_num].opcode) { case ZEND_JMP: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); break; case ZEND_JMPZ: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); break; } } /* }}} */ void zend_do_default_before_statement(const znode *case_list, znode *default_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); default_token->u.op.opline_num = next_op_number; next_op_number = get_next_op_number(CG(active_op_array)); switch_entry_ptr->default_case = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_begin_class_declaration(const znode *class_token, znode *class_name, const znode *parent_class_name TSRMLS_DC) /* {{{ */ { zend_op *opline; int doing_inheritance = 0; zend_class_entry *new_class_entry; char *lcname; int error = 0; zval **ns_name, key; if (CG(active_class_entry)) { zend_error(E_COMPILE_ERROR, "Class declarations may not be nested"); return; } lcname = zend_str_tolower_dup(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); if (!(strcmp(lcname, "self") && strcmp(lcname, "parent"))) { efree(lcname); zend_error(E_COMPILE_ERROR, "Cannot use '%s' as class name as it is reserved", Z_STRVAL(class_name->u.constant)); } /* Class name must not conflict with import names */ if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns_name) == SUCCESS) { error = 1; } if (CG(current_namespace)) { /* Prefix class name with name of current namespace */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); class_name = &tmp; efree(lcname); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); } if (error) { char *tmp = zend_str_tolower_dup(Z_STRVAL_PP(ns_name), Z_STRLEN_PP(ns_name)); if (Z_STRLEN_PP(ns_name) != Z_STRLEN(class_name->u.constant) || memcmp(tmp, lcname, Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "Cannot declare class %s because the name is already in use", Z_STRVAL(class_name->u.constant)); } efree(tmp); } new_class_entry = emalloc(sizeof(zend_class_entry)); new_class_entry->type = ZEND_USER_CLASS; new_class_entry->name = zend_new_interned_string(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1, 1 TSRMLS_CC); new_class_entry->name_length = Z_STRLEN(class_name->u.constant); zend_initialize_class_data(new_class_entry, 1 TSRMLS_CC); new_class_entry->info.user.filename = zend_get_compiled_filename(TSRMLS_C); new_class_entry->info.user.line_start = class_token->u.op.opline_num; new_class_entry->ce_flags |= class_token->EA; if (parent_class_name && parent_class_name->op_type != IS_UNUSED) { switch (parent_class_name->EA) { case ZEND_FETCH_CLASS_SELF: zend_error(E_COMPILE_ERROR, "Cannot use 'self' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_PARENT: zend_error(E_COMPILE_ERROR, "Cannot use 'parent' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use 'static' as class name as it is reserved"); break; default: break; } doing_inheritance = 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, new_class_entry->name_length TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; if (doing_inheritance) { /* Make sure a trait does not try to extend a class */ if ((new_class_entry->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "A trait (%s) cannot extend a class", new_class_entry->name); } opline->extended_value = parent_class_name->u.op.var; opline->opcode = ZEND_DECLARE_INHERITED_CLASS; } else { opline->opcode = ZEND_DECLARE_CLASS; } LITERAL_STRINGL(opline->op2, lcname, new_class_entry->name_length, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); zend_hash_quick_update(CG(class_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &new_class_entry, sizeof(zend_class_entry *), NULL); CG(active_class_entry) = new_class_entry; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(&CG(implementing_class), opline->result); if (CG(doc_comment)) { CG(active_class_entry)->info.user.doc_comment = CG(doc_comment); CG(active_class_entry)->info.user.doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ static void do_verify_abstract_class(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_VERIFY_ABSTRACT_CLASS; SET_NODE(opline->op1, &CG(implementing_class)); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_class_declaration(const znode *class_token, const znode *parent_token TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); if (ce->constructor) { ce->constructor->common.fn_flags |= ZEND_ACC_CTOR; if (ce->constructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Constructor %s::%s() cannot be static", ce->name, ce->constructor->common.function_name); } } if (ce->destructor) { ce->destructor->common.fn_flags |= ZEND_ACC_DTOR; if (ce->destructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Destructor %s::%s() cannot be static", ce->name, ce->destructor->common.function_name); } } if (ce->clone) { ce->clone->common.fn_flags |= ZEND_ACC_CLONE; if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static", ce->name, ce->clone->common.function_name); } } ce->info.user.line_end = zend_get_compiled_lineno(TSRMLS_C); /* Check for traits and proceed like with interfaces. * The only difference will be a combined handling of them in the end. * Thus, we need another opcode here. */ if (ce->num_traits > 0) { zend_op *opline; ce->traits = NULL; ce->num_traits = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_TRAITS; /* opcode generation: */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BIND_TRAITS; SET_NODE(opline->op1, &CG(implementing_class)); } if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) && ((parent_token->op_type != IS_UNUSED) || (ce->num_interfaces > 0))) { zend_verify_abstract_class(ce TSRMLS_CC); if (ce->num_interfaces) { do_verify_abstract_class(TSRMLS_C); } } /* Inherit interfaces; reset number to zero, we need it for above check and * will restore it during actual implementation. * The ZEND_ACC_IMPLEMENT_INTERFACES flag disables double call to * zend_verify_abstract_class() */ if (ce->num_interfaces > 0) { ce->interfaces = NULL; ce->num_interfaces = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_INTERFACES; } CG(active_class_entry) = NULL; } /* }}} */ void zend_do_implements_interface(znode *interface_name TSRMLS_DC) /* {{{ */ { zend_op *opline; /* Traits can not implement interfaces */ if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface on '%s' since it is a Trait", Z_STRVAL(interface_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(interface_name->u.constant), Z_STRLEN(interface_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface name as it is reserved", Z_STRVAL(interface_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_INTERFACE; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(interface_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = (opline->extended_value & ~ZEND_FETCH_CLASS_MASK) | ZEND_FETCH_CLASS_INTERFACE; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &interface_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_interfaces++; } /* }}} */ void zend_do_implements_trait(znode *trait_name TSRMLS_DC) /* {{{ */ { zend_op *opline; if ((CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Cannot use traits inside of interfaces. %s is used in %s", Z_STRVAL(trait_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(trait_name->u.constant), Z_STRLEN(trait_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as trait name as it is reserved", Z_STRVAL(trait_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_TRAIT; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(trait_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = ZEND_FETCH_CLASS_TRAIT; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &trait_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_traits++; } /* }}} */ ZEND_API void zend_mangle_property_name(char **dest, int *dest_length, const char *src1, int src1_length, const char *src2, int src2_length, int internal) /* {{{ */ { char *prop_name; int prop_name_length; prop_name_length = 1 + src1_length + 1 + src2_length; prop_name = pemalloc(prop_name_length + 1, internal); prop_name[0] = '\0'; memcpy(prop_name + 1, src1, src1_length+1); memcpy(prop_name + 1 + src1_length + 1, src2, src2_length+1); *dest = prop_name; *dest_length = prop_name_length; } /* }}} */ static int zend_strnlen(const char* s, int maxlen) /* {{{ */ { int len = 0; while (*s++ && maxlen--) len++; return len; } /* }}} */ ZEND_API int zend_unmangle_property_name(const char *mangled_property, int len, const char **class_name, const char **prop_name) /* {{{ */ { int class_name_len; *class_name = NULL; if (mangled_property[0]!=0) { *prop_name = mangled_property; return SUCCESS; } if (len < 3 || mangled_property[1]==0) { zend_error(E_NOTICE, "Illegal member variable name"); *prop_name = mangled_property; return FAILURE; } class_name_len = zend_strnlen(mangled_property+1, --len - 1) + 1; if (class_name_len >= len || mangled_property[class_name_len]!=0) { zend_error(E_NOTICE, "Corrupt member variable name"); *prop_name = mangled_property; return FAILURE; } *class_name = mangled_property+1; *prop_name = (*class_name)+class_name_len; return SUCCESS; } /* }}} */ void zend_do_declare_property(const znode *var_name, const znode *value, zend_uint access_type TSRMLS_DC) /* {{{ */ { zval *property; zend_property_info *existing_property_info; char *comment = NULL; int comment_len = 0; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Interfaces may not include member variables"); } if (access_type & ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Properties cannot be declared abstract"); } if (access_type & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot declare property %s::$%s final, the final modifier is allowed only for methods and classes", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } if (zend_hash_find(&CG(active_class_entry)->properties_info, var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, (void **) &existing_property_info)==SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::$%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } ALLOC_ZVAL(property); if (value) { *property = value->u.constant; } else { INIT_PZVAL(property); Z_TYPE_P(property) = IS_NULL; } if (CG(doc_comment)) { comment = CG(doc_comment); comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } zend_declare_property_ex(CG(active_class_entry), zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len + 1, 0 TSRMLS_CC), var_name->u.constant.value.str.len, property, access_type, comment, comment_len TSRMLS_CC); efree(var_name->u.constant.value.str.val); } /* }}} */ void zend_do_declare_class_constant(znode *var_name, const znode *value TSRMLS_DC) /* {{{ */ { zval *property; const char *cname = NULL; int result; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed in class constants"); return; } if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Traits cannot have constants"); return; } ALLOC_ZVAL(property); *property = value->u.constant; cname = zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, 0 TSRMLS_CC); if (IS_INTERNED(cname)) { result = zend_hash_quick_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, INTERNED_HASH(cname), &property, sizeof(zval *), NULL); } else { result = zend_hash_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, &property, sizeof(zval *), NULL); } if (result == FAILURE) { FREE_ZVAL(property); zend_error(E_COMPILE_ERROR, "Cannot redefine class constant %s::%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } FREE_PNODE(var_name); if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_fetch_property(znode *result, znode *object, const znode *property TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (object->op_type == IS_CV) { if (object->u.op.var == CG(active_op_array)->this_var) { object->op_type = IS_UNUSED; /* this means $this for objects */ } } else if (fetch_list_ptr->count == 1) { zend_llist_element *le = fetch_list_ptr->head; zend_op *opline_ptr = (zend_op *) le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); SET_UNUSED(opline_ptr->op1); /* this means $this for objects */ SET_NODE(opline_ptr->op2, property); /* if it was usual fetch, we change it to object fetch */ switch (opline_ptr->opcode) { case ZEND_FETCH_W: opline_ptr->opcode = ZEND_FETCH_OBJ_W; break; case ZEND_FETCH_R: opline_ptr->opcode = ZEND_FETCH_OBJ_R; break; case ZEND_FETCH_RW: opline_ptr->opcode = ZEND_FETCH_OBJ_RW; break; case ZEND_FETCH_IS: opline_ptr->opcode = ZEND_FETCH_OBJ_IS; break; case ZEND_FETCH_UNSET: opline_ptr->opcode = ZEND_FETCH_OBJ_UNSET; break; case ZEND_FETCH_FUNC_ARG: opline_ptr->opcode = ZEND_FETCH_OBJ_FUNC_ARG; break; } if (opline_ptr->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline_ptr->op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline_ptr->op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op2.constant); } GET_NODE(result, opline_ptr->result); return; } } if (zend_is_function_or_method_call(object)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, object); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_OBJ_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, object); SET_NODE(opline.op2, property); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline.op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op2.constant); } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void zend_do_halt_compiler_register(TSRMLS_D) /* {{{ */ { char *name, *cfilename; char haltoff[] = "__COMPILER_HALT_OFFSET__"; int len, clen; cfilename = zend_get_compiled_filename(TSRMLS_C); clen = strlen(cfilename); zend_mangle_property_name(&name, &len, haltoff, sizeof(haltoff) - 1, cfilename, clen, 0); zend_register_long_constant(name, len+1, zend_get_scanned_file_offset(TSRMLS_C), CONST_CS, 0 TSRMLS_CC); pefree(name, 0); if (CG(in_namespace)) { zend_do_end_namespace(TSRMLS_C); } } /* }}} */ void zend_do_push_object(const znode *object TSRMLS_DC) /* {{{ */ { zend_stack_push(&CG(object_stack), object, sizeof(znode)); } /* }}} */ void zend_do_pop_object(znode *object TSRMLS_DC) /* {{{ */ { if (object) { znode *tmp; zend_stack_top(&CG(object_stack), (void **) &tmp); *object = *tmp; } zend_stack_del_top(&CG(object_stack)); } /* }}} */ void zend_do_begin_new_object(znode *new_token, znode *class_type TSRMLS_DC) /* {{{ */ { zend_op *opline; unsigned char *ptr = NULL; new_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_NEW; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, class_type); SET_UNUSED(opline->op2); zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(unsigned char *)); } /* }}} */ void zend_do_end_new_object(znode *result, const znode *new_token, const znode *argument_list TSRMLS_DC) /* {{{ */ { znode ctor_result; zend_do_end_function_call(NULL, &ctor_result, argument_list, 1, 0 TSRMLS_CC); zend_do_free(&ctor_result TSRMLS_CC); CG(active_op_array)->opcodes[new_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, CG(active_op_array)->opcodes[new_token->u.op.opline_num].result); } /* }}} */ static zend_constant* zend_get_ct_const(const zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = NULL; if (Z_STRVAL_P(const_name)[0] == '\\') { if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name), (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name)-1); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name), (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } } else if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)+1, (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name)+1, (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } if (c->flags & CONST_CT_SUBST) { return c; } if (all_internal_constants_substitution && (c->flags & CONST_PERSISTENT) && !(CG(compiler_options) & ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION) && Z_TYPE(c->value) != IS_CONSTANT && Z_TYPE(c->value) != IS_CONSTANT_ARRAY) { return c; } return NULL; } /* }}} */ static int zend_constant_ct_subst(znode *result, zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = zend_get_ct_const(const_name, all_internal_constants_substitution TSRMLS_CC); if (c) { zval_dtor(const_name); result->op_type = IS_CONST; result->u.constant = c->value; zval_copy_ctor(&result->u.constant); INIT_PZVAL(&result->u.constant); return 1; } return 0; } /* }}} */ void zend_do_fetch_constant(znode *result, znode *constant_container, znode *constant_name, int mode, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; zend_op *opline; int type; char *compound; ulong fetch_type = 0; if (constant_container) { switch (mode) { case ZEND_CT: /* this is a class constant */ type = zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant)); if (ZEND_FETCH_CLASS_STATIC == type) { zend_error(E_ERROR, "\"static::\" is not allowed in compile-time constants"); } else if (ZEND_FETCH_CLASS_DEFAULT == type) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } zend_do_build_full_name(NULL, constant_container, constant_name, 1 TSRMLS_CC); *result = *constant_container; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: if (constant_container->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant))) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } else { zend_do_fetch_class(&tmp, constant_container TSRMLS_CC); constant_container = &tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); if (constant_container->op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &constant_container->u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, constant_container); } SET_NODE(opline->op2, constant_name); CALCULATE_LITERAL_HASH(opline->op2.constant); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } GET_NODE(result, opline->result); break; } return; } /* namespace constant */ /* only one that did not contain \ from the start can be converted to string if unknown */ switch (mode) { case ZEND_CT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); /* this is a namespace constant, or an unprefixed constant */ if (zend_constant_ct_subst(result, &constant_name->u.constant, 0 TSRMLS_CC)) { break; } zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(!compound) { fetch_type |= IS_CONSTANT_UNQUALIFIED; } *result = *constant_name; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(zend_constant_ct_subst(result, &constant_name->u.constant, 1 TSRMLS_CC)) { break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; if (compound) { /* the name is unambiguous */ opline->extended_value = 0; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } else { opline->extended_value = IS_CONSTANT_UNQUALIFIED; if (CG(current_namespace)) { opline->extended_value |= IS_CONSTANT_IN_NAMESPACE; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 1 TSRMLS_CC); } else { opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } } GET_CACHE_SLOT(opline->op2.constant); break; } } /* }}} */ void zend_do_shell_exec(znode *result, const znode *cmd TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); switch (cmd->op_type) { case IS_CONST: case IS_TMP_VAR: opline->opcode = ZEND_SEND_VAL; break; default: opline->opcode = ZEND_SEND_VAR; break; } SET_NODE(opline->op1, cmd); opline->op2.opline_num = 0; opline->extended_value = ZEND_DO_FCALL; SET_UNUSED(opline->op2); /* FIXME: exception support not added to this op2 */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DO_FCALL; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; LITERAL_STRINGL(opline->op1, estrndup("shell_exec", sizeof("shell_exec")-1), sizeof("shell_exec")-1, 0); CALCULATE_LITERAL_HASH(opline->op1.constant); opline->op1_type = IS_CONST; GET_CACHE_SLOT(opline->op1.constant); opline->extended_value = 1; SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_init_array(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_ARRAY; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; GET_NODE(result, opline->result); if (expr) { SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } } else { SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_array_element(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_ARRAY_ELEMENT; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_static_array_element(znode *result, znode *offset, const znode *expr) /* {{{ */ { zval *element; ALLOC_ZVAL(element); *element = expr->u.constant; if (offset) { switch (offset->u.constant.type & IS_CONSTANT_TYPE_MASK) { case IS_CONSTANT: /* Ugly hack to denote that this value has a constant index */ Z_TYPE_P(element) |= IS_CONSTANT_INDEX; Z_STRVAL(offset->u.constant) = erealloc(Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+1] = Z_TYPE(offset->u.constant); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+2] = 0; zend_symtable_update(result->u.constant.value.ht, Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_STRING: zend_symtable_update(result->u.constant.value.ht, offset->u.constant.value.str.val, offset->u.constant.value.str.len+1, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_NULL: zend_symtable_update(Z_ARRVAL(result->u.constant), "", 1, &element, sizeof(zval *), NULL); break; case IS_LONG: case IS_BOOL: zend_hash_index_update(Z_ARRVAL(result->u.constant), Z_LVAL(offset->u.constant), &element, sizeof(zval *), NULL); break; case IS_DOUBLE: zend_hash_index_update(Z_ARRVAL(result->u.constant), zend_dval_to_lval(Z_DVAL(offset->u.constant)), &element, sizeof(zval *), NULL); break; case IS_CONSTANT_ARRAY: zend_error(E_ERROR, "Illegal offset type"); break; } } else { zend_hash_next_index_insert(Z_ARRVAL(result->u.constant), &element, sizeof(zval *), NULL); } } /* }}} */ void zend_do_add_list_element(const znode *element TSRMLS_DC) /* {{{ */ { list_llist_element lle; if (element) { zend_check_writable_variable(element); lle.var = *element; zend_llist_copy(&lle.dimensions, &CG(dimension_llist)); zend_llist_prepend_element(&CG(list_llist), &lle); } (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_new_list_begin(TSRMLS_D) /* {{{ */ { int current_dimension = 0; zend_llist_add_element(&CG(dimension_llist), &current_dimension); } /* }}} */ void zend_do_new_list_end(TSRMLS_D) /* {{{ */ { zend_llist_remove_tail(&CG(dimension_llist)); (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_list_init(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(list_stack), &CG(list_llist), sizeof(zend_llist)); zend_stack_push(&CG(list_stack), &CG(dimension_llist), sizeof(zend_llist)); zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_do_new_list_begin(TSRMLS_C); } /* }}} */ void zend_do_list_end(znode *result, znode *expr TSRMLS_DC) /* {{{ */ { zend_llist_element *le; zend_llist_element *dimension; zend_op *opline; znode last_container; le = CG(list_llist).head; while (le) { zend_llist *tmp_dimension_llist = &((list_llist_element *)le->data)->dimensions; dimension = tmp_dimension_llist->head; while (dimension) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (dimension == tmp_dimension_llist->head) { /* first */ last_container = *expr; switch (expr->op_type) { case IS_VAR: case IS_CV: opline->opcode = ZEND_FETCH_DIM_R; break; case IS_TMP_VAR: opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; case IS_CONST: /* fetch_dim_tmp_var will handle this bogus fetch */ zval_copy_ctor(&expr->u.constant); opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; } opline->extended_value |= ZEND_FETCH_ADD_LOCK; } else { opline->opcode = ZEND_FETCH_DIM_R; } opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, &last_container); opline->op2_type = IS_CONST; LITERAL_LONG(opline->op2, *((int *) dimension->data)); GET_NODE(&last_container, opline->result); dimension = dimension->next; } ((list_llist_element *) le->data)->value = last_container; zend_llist_destroy(&((list_llist_element *) le->data)->dimensions); zend_do_assign(result, &((list_llist_element *) le->data)->var, &((list_llist_element *) le->data)->value TSRMLS_CC); zend_do_free(result TSRMLS_CC); le = le->next; } zend_llist_destroy(&CG(dimension_llist)); zend_llist_destroy(&CG(list_llist)); *result = *expr; { zend_llist *p; /* restore previous lists */ zend_stack_top(&CG(list_stack), (void **) &p); CG(dimension_llist) = *p; zend_stack_del_top(&CG(list_stack)); zend_stack_top(&CG(list_stack), (void **) &p); CG(list_llist) = *p; zend_stack_del_top(&CG(list_stack)); } } /* }}} */ void zend_init_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = emalloc(sizeof(void*) * 2); list[0] = item; list[1] = NULL; *(void**)result = list; } /* }}} */ void zend_add_to_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = *(void**)result; size_t n = 0; while (list && list[n]) { n++; } list = erealloc(list, sizeof(void*) * (n+2)); list[n] = item; list[n+1] = NULL; *(void**)result = list; } /* }}} */ void zend_do_fetch_static_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zval *tmp; zend_op *opline; znode lval; znode result; ALLOC_ZVAL(tmp); if (static_assignment) { *tmp = static_assignment->u.constant; } else { INIT_ZVAL(*tmp); } if (!CG(active_op_array)->static_variables) { if (CG(active_op_array)->scope) { CG(active_op_array)->scope->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } ALLOC_HASHTABLE(CG(active_op_array)->static_variables); zend_hash_init(CG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } zend_hash_update(CG(active_op_array)->static_variables, varname->u.constant.value.str.val, varname->u.constant.value.str.len+1, &tmp, sizeof(zval *), NULL); if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (fetch_type == ZEND_FETCH_LEXICAL) ? ZEND_FETCH_R : ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_STATIC; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ if (fetch_type == ZEND_FETCH_LEXICAL) { znode dummy; zend_do_begin_variable_parse(TSRMLS_C); zend_do_assign(&dummy, &lval, &result TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } else { zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); } CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_fetch_lexical_variable(znode *varname, zend_bool is_ref TSRMLS_DC) /* {{{ */ { znode value; if (Z_STRLEN(varname->u.constant) == sizeof("this") - 1 && memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this") - 1) == 0) { zend_error(E_COMPILE_ERROR, "Cannot use $this as lexical variable"); return; } value.op_type = IS_CONST; ZVAL_NULL(&value.u.constant); Z_TYPE(value.u.constant) |= is_ref ? IS_LEXICAL_REF : IS_LEXICAL_VAR; Z_SET_REFCOUNT_P(&value.u.constant, 1); Z_UNSET_ISREF_P(&value.u.constant); zend_do_fetch_static_variable(varname, &value, is_ref ? ZEND_FETCH_STATIC : ZEND_FETCH_LEXICAL TSRMLS_CC); } /* }}} */ void zend_do_fetch_global_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zend_op *opline; znode lval; znode result; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = fetch_type; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_cast(znode *result, const znode *expr, int type TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CAST; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } /* }}} */ void zend_do_include_or_eval(int type, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_do_extended_fcall_begin(TSRMLS_C); { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INCLUDE_OR_EVAL; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } zend_do_extended_fcall_end(TSRMLS_C); } /* }}} */ void zend_do_indirect_references(znode *result, const znode *num_references, znode *variable TSRMLS_DC) /* {{{ */ { int i; zend_do_end_variable_parse(variable, BP_VAR_R, 0 TSRMLS_CC); for (i=1; i<num_references->u.constant.value.lval; i++) { fetch_simple_variable_ex(result, variable, 0, ZEND_FETCH_R TSRMLS_CC); *variable = *result; } zend_do_begin_variable_parse(TSRMLS_C); fetch_simple_variable(result, variable, 1 TSRMLS_CC); /* there is a chance someone is accessing $this */ if (CG(active_op_array)->scope && CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } /* }}} */ void zend_do_unset(const znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_UNSET_VAR; SET_NODE(opline->op1, variable); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); opline->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_UNSET: last_op->opcode = ZEND_UNSET_VAR; SET_UNUSED(last_op->result); break; case ZEND_FETCH_DIM_UNSET: last_op->opcode = ZEND_UNSET_DIM; SET_UNUSED(last_op->result); break; case ZEND_FETCH_OBJ_UNSET: last_op->opcode = ZEND_UNSET_OBJ; SET_UNUSED(last_op->result); break; } } } /* }}} */ void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_do_end_variable_parse(variable, BP_VAR_IS, 0 TSRMLS_CC); zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { last_op = get_next_op(CG(active_op_array) TSRMLS_CC); last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; SET_NODE(last_op->op1, variable); SET_UNUSED(last_op->op2); last_op->result.var = get_temporary_variable(CG(active_op_array)); last_op->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; break; case ZEND_FETCH_DIM_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_DIM_OBJ; break; case ZEND_FETCH_OBJ_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_PROP_OBJ; break; } } last_op->result_type = IS_TMP_VAR; last_op->extended_value |= type; GET_NODE(result, last_op->result); } /* }}} */ void zend_do_instanceof(znode *result, const znode *expr, const znode *class_znode, int type TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline->opcode == ZEND_FETCH_CLASS) { opline->extended_value |= ZEND_FETCH_CLASS_NO_AUTOLOAD; } } if (expr->op_type == IS_CONST) { zend_error(E_COMPILE_ERROR, "instanceof expects an object instance, constant given"); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INSTANCEOF; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_NODE(opline->op2, class_znode); GET_NODE(result, opline->result); } /* }}} */ void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_bool is_variable; zend_bool push_container = 0; zend_op dummy_opline; if (variable) { if (zend_is_function_or_method_call(array)) { is_variable = 0; } else { is_variable = 1; } /* save the location of FETCH_W instruction(s) */ open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); zend_do_end_variable_parse(array, BP_VAR_W, 0 TSRMLS_CC); if (CG(active_op_array)->last > 0 && CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) { /* Only lock the container if we are fetching from a real container and not $this */ if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1_type == IS_VAR) { CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK; push_container = 1; } } } else { is_variable = 0; open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* save the location of FE_RESET */ foreach_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* Preform array reset */ opline->opcode = ZEND_FE_RESET; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, array); SET_UNUSED(opline->op2); opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0; COPY_NODE(dummy_opline.result, opline->result); if (push_container) { COPY_NODE(dummy_opline.op1, CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1); } else { dummy_opline.op1_type = IS_UNUSED; } zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); /* save the location of FE_FETCH */ as_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FE_FETCH; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); COPY_NODE(opline->op1, dummy_opline.result); opline->extended_value = 0; SET_UNUSED(opline->op2); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_OP_DATA; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); } /* }}} */ void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC) /* {{{ */ { zend_op *opline; znode dummy, value_node; zend_bool assign_by_ref=0; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num]; if (key->op_type != IS_UNUSED) { znode *tmp; /* switch between the key and value... */ tmp = key; key = value; value = tmp; /* Mark extended_value in case both key and value are being used */ opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; } if ((key->op_type != IS_UNUSED) && (key->EA & ZEND_PARSED_REFERENCE_VARIABLE)) { zend_error(E_COMPILE_ERROR, "Key element cannot be a reference"); } if (value->EA & ZEND_PARSED_REFERENCE_VARIABLE) { assign_by_ref = 1; if (!(opline-1)->extended_value) { zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression"); } /* Mark extended_value for assign-by-reference */ opline->extended_value |= ZEND_FE_FETCH_BYREF; CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; } else { zend_op *foreach_copy; zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.op.opline_num]; zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.op.opline_num]; /* Change "write context" into "read context" */ fetch->extended_value = 0; /* reset ZEND_FE_RESET_VARIABLE */ while (fetch != end) { --fetch; if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } if (fetch->opcode == ZEND_SEPARATE) { MAKE_NOP(fetch); } else { fetch->opcode -= 3; /* FETCH_W -> FETCH_R */ } } /* prevent double SWITCH_FREE */ zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy); foreach_copy->op1_type = IS_UNUSED; } GET_NODE(&value_node, opline->result); if (assign_by_ref) { zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); /* Mark FE_FETCH as IS_VAR as it holds the data directly as a value */ zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC); } else { zend_do_assign(&dummy, value, &value_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } if (key->op_type != IS_UNUSED) { znode key_node; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num+1]; opline->result_type = IS_TMP_VAR; opline->result.opline_num = get_temporary_variable(CG(active_op_array)); GET_NODE(&key_node, opline->result); zend_do_assign(&dummy, key, &key_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_foreach_end(const znode *foreach_token, const znode *as_token TSRMLS_DC) /* {{{ */ { zend_op *container_ptr; zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = as_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_RESET */ CG(active_op_array)->opcodes[as_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_FETCH */ do_end_loop(as_token->u.op.opline_num, 1 TSRMLS_CC); zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr); generate_free_foreach_copy(container_ptr TSRMLS_CC); zend_stack_del_top(&CG(foreach_copy_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_declare_begin(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(declare_stack), &CG(declarables), sizeof(zend_declarables)); } /* }}} */ void zend_do_declare_stmt(znode *var, znode *val TSRMLS_DC) /* {{{ */ { if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "ticks", sizeof("ticks")-1)) { convert_to_long(&val->u.constant); CG(declarables).ticks = val->u.constant; } else if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "encoding", sizeof("encoding")-1)) { if ((Z_TYPE(val->u.constant) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Cannot use constants as encoding"); } /* * Check that the pragma comes before any opcodes. If the compilation * got as far as this, the previous portion of the script must have been * parseable according to the .ini script_encoding setting. We still * want to tell them to put declare() at the top. */ { int num = CG(active_op_array)->last; /* ignore ZEND_EXT_STMT and ZEND_TICKS */ while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Encoding declaration pragma must be the very first statement in the script"); } } if (CG(multibyte)) { const zend_encoding *new_encoding, *old_encoding; zend_encoding_filter old_input_filter; CG(encoding_declared) = 1; convert_to_string(&val->u.constant); new_encoding = zend_multibyte_fetch_encoding(val->u.constant.value.str.val TSRMLS_CC); if (!new_encoding) { zend_error(E_COMPILE_WARNING, "Unsupported encoding [%s]", val->u.constant.value.str.val); } else { old_input_filter = LANG_SCNG(input_filter); old_encoding = LANG_SCNG(script_encoding); zend_multibyte_set_filter(new_encoding TSRMLS_CC); /* need to re-scan if input filter changed */ if (old_input_filter != LANG_SCNG(input_filter) || (old_input_filter && new_encoding != old_encoding)) { zend_multibyte_yyinput_again(old_input_filter, old_encoding TSRMLS_CC); } } } else { zend_error(E_COMPILE_WARNING, "declare(encoding=...) ignored because Zend multibyte feature is turned off by settings"); } zval_dtor(&val->u.constant); } else { zend_error(E_COMPILE_WARNING, "Unsupported declare '%s'", var->u.constant.value.str.val); zval_dtor(&val->u.constant); } zval_dtor(&var->u.constant); } /* }}} */ void zend_do_declare_end(const znode *declare_token TSRMLS_DC) /* {{{ */ { zend_declarables *declarables; zend_stack_top(&CG(declare_stack), (void **) &declarables); /* We should restore if there was more than (current - start) - (ticks?1:0) opcodes */ if ((get_next_op_number(CG(active_op_array)) - declare_token->u.op.opline_num) - ((Z_LVAL(CG(declarables).ticks))?1:0)) { CG(declarables) = *declarables; } } /* }}} */ void zend_do_exit(znode *result, const znode *message TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXIT; SET_NODE(opline->op1, message); SET_UNUSED(opline->op2); result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_BOOL; Z_LVAL(result->u.constant) = 1; } /* }}} */ void zend_do_begin_silence(znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BEGIN_SILENCE; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); GET_NODE(strudel_token, opline->result); } /* }}} */ void zend_do_end_silence(const znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_END_SILENCE; SET_NODE(opline->op1, strudel_token); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_jmp_set(const znode *value, znode *jmp_token, znode *colon_token TSRMLS_DC) /* {{{ */ { int op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (value->op_type == IS_VAR || value->op_type == IS_CV) { opline->opcode = ZEND_JMP_SET_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_JMP_SET; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, value); SET_UNUSED(opline->op2); GET_NODE(colon_token, opline->result); jmp_token->u.op .opline_num = op_number; INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_jmp_set_else(znode *result, const znode *false_value, const znode *jmp_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, colon_token); if (colon_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].opcode = ZEND_JMP_SET_VAR; CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } opline->extended_value = 0; SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_qm_op(const znode *cond, znode *qm_token TSRMLS_DC) /* {{{ */ { int jmpz_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); SET_UNUSED(opline->op2); opline->op2.opline_num = jmpz_op_number; GET_NODE(qm_token, opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_qm_true(const znode *true_value, znode *qm_token, znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->opcodes[qm_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array))+1; /* jmp over the ZEND_JMP */ if (true_value->op_type == IS_VAR || true_value->op_type == IS_CV) { opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, true_value); SET_UNUSED(opline->op2); GET_NODE(qm_token, opline->result); colon_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_qm_false(znode *result, const znode *false_value, const znode *qm_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, qm_token); if (qm_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].opcode = ZEND_QM_ASSIGN_VAR; CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[colon_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, opline->result); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_extended_info(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_STMT; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_begin(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_BEGIN; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_end(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_END; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_ticks(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_TICKS; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->extended_value = Z_LVAL(CG(declarables).ticks); } /* }}} */ zend_bool zend_is_auto_global_quick(const char *name, uint name_len, ulong hashval TSRMLS_DC) /* {{{ */ { zend_auto_global *auto_global; ulong hash = hashval ? hashval : zend_hash_func(name, name_len+1); if (zend_hash_quick_find(CG(auto_globals), name, name_len+1, hash, (void **) &auto_global)==SUCCESS) { if (auto_global->armed) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } return 1; } return 0; } /* }}} */ zend_bool zend_is_auto_global(const char *name, uint name_len TSRMLS_DC) /* {{{ */ { return zend_is_auto_global_quick(name, name_len, 0 TSRMLS_CC); } /* }}} */ int zend_register_auto_global(const char *name, uint name_len, zend_bool jit, zend_auto_global_callback auto_global_callback TSRMLS_DC) /* {{{ */ { zend_auto_global auto_global; auto_global.name = zend_new_interned_string((char*)name, name_len + 1, 0 TSRMLS_CC); auto_global.name_len = name_len; auto_global.auto_global_callback = auto_global_callback; auto_global.jit = jit; return zend_hash_add(CG(auto_globals), name, name_len+1, &auto_global, sizeof(zend_auto_global), NULL); } /* }}} */ static int zend_auto_global_init(zend_auto_global *auto_global TSRMLS_DC) /* {{{ */ { if (auto_global->jit) { auto_global->armed = 1; } else if (auto_global->auto_global_callback) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } else { auto_global->armed = 0; } return 0; } /* }}} */ ZEND_API void zend_activate_auto_globals(TSRMLS_D) /* {{{ */ { zend_hash_apply(CG(auto_globals), (apply_func_t) zend_auto_global_init TSRMLS_CC); } /* }}} */ int zendlex(znode *zendlval TSRMLS_DC) /* {{{ */ { int retval; if (CG(increment_lineno)) { CG(zend_lineno)++; CG(increment_lineno) = 0; } again: Z_TYPE(zendlval->u.constant) = IS_LONG; retval = lex_scan(&zendlval->u.constant TSRMLS_CC); switch (retval) { case T_COMMENT: case T_DOC_COMMENT: case T_OPEN_TAG: case T_WHITESPACE: goto again; case T_CLOSE_TAG: if (LANG_SCNG(yy_text)[LANG_SCNG(yy_leng)-1] != '>') { CG(increment_lineno) = 1; } if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { goto again; } retval = ';'; /* implicit ; */ break; case T_OPEN_TAG_WITH_ECHO: retval = T_ECHO; break; case T_END_HEREDOC: efree(Z_STRVAL(zendlval->u.constant)); break; } INIT_PZVAL(&zendlval->u.constant); zendlval->op_type = IS_CONST; return retval; } /* }}} */ ZEND_API void zend_initialize_class_data(zend_class_entry *ce, zend_bool nullify_handlers TSRMLS_DC) /* {{{ */ { zend_bool persistent_hashes = (ce->type == ZEND_INTERNAL_CLASS) ? 1 : 0; dtor_func_t zval_ptr_dtor_func = ((persistent_hashes) ? ZVAL_INTERNAL_PTR_DTOR : ZVAL_PTR_DTOR); ce->refcount = 1; ce->ce_flags = 0; ce->default_properties_table = NULL; ce->default_static_members_table = NULL; zend_hash_init_ex(&ce->properties_info, 0, NULL, (dtor_func_t) (persistent_hashes ? zend_destroy_property_info_internal : zend_destroy_property_info), persistent_hashes, 0); zend_hash_init_ex(&ce->constants_table, 0, NULL, zval_ptr_dtor_func, persistent_hashes, 0); zend_hash_init_ex(&ce->function_table, 0, NULL, ZEND_FUNCTION_DTOR, persistent_hashes, 0); if (ce->type == ZEND_INTERNAL_CLASS) { #ifdef ZTS int n = zend_hash_num_elements(CG(class_table)); if (CG(static_members_table) && n >= CG(last_static_member)) { /* Support for run-time declaration: dl() */ CG(last_static_member) = n+1; CG(static_members_table) = realloc(CG(static_members_table), (n+1)*sizeof(zval**)); CG(static_members_table)[n] = NULL; } ce->static_members_table = (zval**)(zend_intptr_t)n; #else ce->static_members_table = NULL; #endif } else { ce->static_members_table = ce->default_static_members_table; ce->info.user.doc_comment = NULL; ce->info.user.doc_comment_len = 0; } ce->default_properties_count = 0; ce->default_static_members_count = 0; if (nullify_handlers) { ce->constructor = NULL; ce->destructor = NULL; ce->clone = NULL; ce->__get = NULL; ce->__set = NULL; ce->__unset = NULL; ce->__isset = NULL; ce->__call = NULL; ce->__callstatic = NULL; ce->__tostring = NULL; ce->create_object = NULL; ce->get_iterator = NULL; ce->iterator_funcs.funcs = NULL; ce->interface_gets_implemented = NULL; ce->get_static_method = NULL; ce->parent = NULL; ce->num_interfaces = 0; ce->interfaces = NULL; ce->num_traits = 0; ce->traits = NULL; ce->trait_aliases = NULL; ce->trait_precedences = NULL; ce->serialize = NULL; ce->unserialize = NULL; ce->serialize_func = NULL; ce->unserialize_func = NULL; if (ce->type == ZEND_INTERNAL_CLASS) { ce->info.internal.module = NULL; ce->info.internal.builtin_functions = NULL; } } } /* }}} */ int zend_get_class_fetch_type(const char *class_name, uint class_name_len) /* {{{ */ { if ((class_name_len == sizeof("self")-1) && !memcmp(class_name, "self", sizeof("self")-1)) { return ZEND_FETCH_CLASS_SELF; } else if ((class_name_len == sizeof("parent")-1) && !memcmp(class_name, "parent", sizeof("parent")-1)) { return ZEND_FETCH_CLASS_PARENT; } else if ((class_name_len == sizeof("static")-1) && !memcmp(class_name, "static", sizeof("static")-1)) { return ZEND_FETCH_CLASS_STATIC; } else { return ZEND_FETCH_CLASS_DEFAULT; } } /* }}} */ ZEND_API const char* zend_get_compiled_variable_name(const zend_op_array *op_array, zend_uint var, int* name_len) /* {{{ */ { if (name_len) { *name_len = op_array->vars[var].name_len; } return op_array->vars[var].name; } /* }}} */ void zend_do_build_namespace_name(znode *result, znode *prefix, znode *name TSRMLS_DC) /* {{{ */ { if (prefix) { *result = *prefix; if (Z_TYPE(result->u.constant) == IS_STRING && Z_STRLEN(result->u.constant) == 0) { /* namespace\ */ if (CG(current_namespace)) { znode tmp; zval_dtor(&result->u.constant); tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(result, NULL, &tmp TSRMLS_CC); } } } else { result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_STRING; Z_STRVAL(result->u.constant) = NULL; Z_STRLEN(result->u.constant) = 0; } /* prefix = result */ zend_do_build_full_name(NULL, result, name, 0 TSRMLS_CC); } /* }}} */ void zend_do_begin_namespace(const znode *name, zend_bool with_bracket TSRMLS_DC) /* {{{ */ { char *lcname; /* handle mixed syntax declaration or nested namespaces */ if (!CG(has_bracketed_namespaces)) { if (CG(current_namespace)) { /* previous namespace declarations were unbracketed */ if (with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } } } else { /* previous namespace declarations were bracketed */ if (!with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } else if (CG(current_namespace) || CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "Namespace declarations cannot be nested"); } } if (((!with_bracket && !CG(current_namespace)) || (with_bracket && !CG(has_bracketed_namespaces))) && CG(active_op_array)->last > 0) { /* ignore ZEND_EXT_STMT and ZEND_TICKS */ int num = CG(active_op_array)->last; while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Namespace declaration statement has to be the very first statement in the script"); } } CG(in_namespace) = 1; if (with_bracket) { CG(has_bracketed_namespaces) = 1; } if (name) { lcname = zend_str_tolower_dup(Z_STRVAL(name->u.constant), Z_STRLEN(name->u.constant)); if (((Z_STRLEN(name->u.constant) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN(name->u.constant) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as namespace name", Z_STRVAL(name->u.constant)); } efree(lcname); if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); } else { ALLOC_ZVAL(CG(current_namespace)); } *CG(current_namespace) = name->u.constant; } else { if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_use(znode *ns_name, znode *new_name, int is_global TSRMLS_DC) /* {{{ */ { char *lcname; zval *name, *ns, tmp; zend_bool warn = 0; zend_class_entry **pce; if (!CG(current_import)) { CG(current_import) = emalloc(sizeof(HashTable)); zend_hash_init(CG(current_import), 0, NULL, ZVAL_PTR_DTOR, 0); } ALLOC_ZVAL(ns); *ns = ns_name->u.constant; if (new_name) { name = &new_name->u.constant; } else { const char *p; /* The form "use A\B" is eqivalent to "use A\B as B". So we extract the last part of compound name to use as a new_name */ name = &tmp; p = zend_memrchr(Z_STRVAL_P(ns), '\\', Z_STRLEN_P(ns)); if (p) { ZVAL_STRING(name, p+1, 1); } else { *name = *ns; zval_copy_ctor(name); warn = !is_global && !CG(current_namespace); } } lcname = zend_str_tolower_dup(Z_STRVAL_P(name), Z_STRLEN_P(name)); if (((Z_STRLEN_P(name) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN_P(name) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because '%s' is a special class name", Z_STRVAL_P(ns), Z_STRVAL_P(name), Z_STRVAL_P(name)); } if (CG(current_namespace)) { /* Prefix import name with current namespace name to avoid conflicts with classes */ char *c_ns_name = emalloc(Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) + 1); zend_str_tolower_copy(c_ns_name, Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); c_ns_name[Z_STRLEN_P(CG(current_namespace))] = '\\'; memcpy(c_ns_name+Z_STRLEN_P(CG(current_namespace))+1, lcname, Z_STRLEN_P(name)+1); if (zend_hash_exists(CG(class_table), c_ns_name, Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name)+1)) { char *tmp2 = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) || memcmp(tmp2, c_ns_name, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(tmp2); } efree(c_ns_name); } else if (zend_hash_find(CG(class_table), lcname, Z_STRLEN_P(name)+1, (void**)&pce) == SUCCESS && (*pce)->type == ZEND_USER_CLASS && (*pce)->info.user.filename == CG(compiled_filename)) { char *c_tmp = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(name) || memcmp(c_tmp, lcname, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(c_tmp); } if (zend_hash_add(CG(current_import), lcname, Z_STRLEN_P(name)+1, &ns, sizeof(zval*), NULL) != SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } if (warn) { if (!strcmp(Z_STRVAL_P(name), "strict")) { zend_error(E_COMPILE_ERROR, "You seem to be trying to use a different language..."); } zend_error(E_WARNING, "The use statement with non-compound name '%s' has no effect", Z_STRVAL_P(name)); } efree(lcname); zval_dtor(name); } /* }}} */ void zend_do_declare_constant(znode *name, znode *value TSRMLS_DC) /* {{{ */ { zend_op *opline; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed as constants"); } if (zend_get_ct_const(&name->u.constant, 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare constant '%s'", Z_STRVAL(name->u.constant)); } if (CG(current_namespace)) { /* Prefix constant name with name of current namespace, lowercased */ znode tmp; tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); Z_STRVAL(tmp.u.constant) = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), Z_STRLEN(tmp.u.constant)); zend_do_build_namespace_name(&tmp, &tmp, name TSRMLS_CC); *name = tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DECLARE_CONST; SET_UNUSED(opline->result); SET_NODE(opline->op1, name); SET_NODE(opline->op2, value); } /* }}} */ void zend_verify_namespace(TSRMLS_D) /* {{{ */ { if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "No code may exist outside of namespace {}"); } } /* }}} */ void zend_do_end_namespace(TSRMLS_D) /* {{{ */ { CG(in_namespace) = 0; if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_end_compilation(TSRMLS_D) /* {{{ */ { CG(has_bracketed_namespaces) = 0; zend_do_end_namespace(TSRMLS_C); } /* }}} */ /* {{{ zend_dirname Returns directory name component of path */ ZEND_API size_t zend_dirname(char *path, size_t len) { register char *end = path + len - 1; unsigned int len_adjust = 0; #ifdef PHP_WIN32 /* Note that on Win32 CWD is per drive (heritage from CP/M). * This means dirname("c:foo") maps to "c:." or "c:" - which means CWD on C: drive. */ if ((2 <= len) && isalpha((int)((unsigned char *)path)[0]) && (':' == path[1])) { /* Skip over the drive spec (if any) so as not to change */ path += 2; len_adjust += 2; if (2 == len) { /* Return "c:" on Win32 for dirname("c:"). * It would be more consistent to return "c:." * but that would require making the string *longer*. */ return len; } } #elif defined(NETWARE) /* * Find the first occurence of : from the left * move the path pointer to the position just after : * increment the len_adjust to the length of path till colon character(inclusive) * If there is no character beyond : simple return len */ char *colonpos = NULL; colonpos = strchr(path, ':'); if (colonpos != NULL) { len_adjust = ((colonpos - path) + 1); path += len_adjust; if (len_adjust == len) { return len; } } #endif if (len == 0) { /* Illegal use of this function */ return 0; } /* Strip trailing slashes */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { /* The path only contained slashes */ path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } /* Strip filename */ while (end >= path && !IS_SLASH_P(end)) { end--; } if (end < path) { /* No slash found, therefore return '.' */ #ifdef NETWARE if (len_adjust == 0) { path[0] = '.'; path[1] = '\0'; return 1; /* only one character */ } else { path[0] = '\0'; return len_adjust; } #else path[0] = '.'; path[1] = '\0'; return 1 + len_adjust; #endif } /* Strip slashes which came before the file name */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } *(end+1) = '\0'; return (size_t)(end + 1 - path) + len_adjust; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */ /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <zend_language_parser.h> #include "zend.h" #include "zend_compile.h" #include "zend_constants.h" #include "zend_llist.h" #include "zend_API.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "zend_multibyte.h" #include "zend_language_scanner.h" #define CONSTANT_EX(op_array, op) \ (op_array)->literals[op].constant #define CONSTANT(op) \ CONSTANT_EX(CG(active_op_array), op) #define SET_NODE(target, src) do { \ target ## _type = (src)->op_type; \ if ((src)->op_type == IS_CONST) { \ target.constant = zend_add_literal(CG(active_op_array), &(src)->u.constant TSRMLS_CC); \ } else { \ target = (src)->u.op; \ } \ } while (0) #define GET_NODE(target, src) do { \ (target)->op_type = src ## _type; \ if ((target)->op_type == IS_CONST) { \ (target)->u.constant = CONSTANT(src.constant); \ } else { \ (target)->u.op = src; \ (target)->EA = 0; \ } \ } while (0) #define COPY_NODE(target, src) do { \ target ## _type = src ## _type; \ target = src; \ } while (0) #define CALCULATE_LITERAL_HASH(num) do { \ if (IS_INTERNED(Z_STRVAL(CONSTANT(num)))) { \ Z_HASH_P(&CONSTANT(num)) = INTERNED_HASH(Z_STRVAL(CONSTANT(num))); \ } else { \ Z_HASH_P(&CONSTANT(num)) = zend_hash_func(Z_STRVAL(CONSTANT(num)), Z_STRLEN(CONSTANT(num))+1); \ } \ } while (0) #define GET_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot++; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ } \ } while (0) #define POLYMORPHIC_CACHE_SLOT_SIZE 2 #define GET_POLYMORPHIC_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot; \ CG(active_op_array)->last_cache_slot += POLYMORPHIC_CACHE_SLOT_SIZE; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 2] = NULL; \ } \ } while (0) #define FREE_POLYMORPHIC_CACHE_SLOT(literal) do { \ if (CG(active_op_array)->literals[literal].cache_slot == \ CG(active_op_array)->last_cache_slot - POLYMORPHIC_CACHE_SLOT_SIZE) { \ CG(active_op_array)->literals[literal].cache_slot = -1; \ CG(active_op_array)->last_cache_slot -= POLYMORPHIC_CACHE_SLOT_SIZE; \ } \ } while (0) ZEND_API zend_op_array *(*zend_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); ZEND_API zend_op_array *(*zend_compile_string)(zval *source_string, char *filename TSRMLS_DC); #ifndef ZTS ZEND_API zend_compiler_globals compiler_globals; ZEND_API zend_executor_globals executor_globals; #endif static void zend_duplicate_property_info(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = estrndup(property_info->name, property_info->name_length); } if (property_info->doc_comment) { property_info->doc_comment = estrndup(property_info->doc_comment, property_info->doc_comment_len); } } /* }}} */ static void zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = zend_strndup(property_info->name, property_info->name_length); } } /* }}} */ static void zend_destroy_property_info(zend_property_info *property_info) /* {{{ */ { str_efree(property_info->name); if (property_info->doc_comment) { efree((char*)property_info->doc_comment); } } /* }}} */ static void zend_destroy_property_info_internal(zend_property_info *property_info) /* {{{ */ { str_free((char*)property_info->name); } /* }}} */ static void build_runtime_defined_function_key(zval *result, const char *name, int name_length TSRMLS_DC) /* {{{ */ { char char_pos_buf[32]; uint char_pos_len; const char *filename; char_pos_len = zend_sprintf(char_pos_buf, "%p", LANG_SCNG(yy_text)); if (CG(active_op_array)->filename) { filename = CG(active_op_array)->filename; } else { filename = "-"; } /* NULL, name length, filename length, last accepting char position length */ result->value.str.len = 1+name_length+strlen(filename)+char_pos_len; /* must be binary safe */ result->value.str.val = (char *) safe_emalloc(result->value.str.len, 1, 1); result->value.str.val[0] = '\0'; sprintf(result->value.str.val+1, "%s%s%s", name, filename, char_pos_buf); result->type = IS_STRING; Z_SET_REFCOUNT_P(result, 1); } /* }}} */ static void init_compiler_declarables(TSRMLS_D) /* {{{ */ { Z_TYPE(CG(declarables).ticks) = IS_LONG; Z_LVAL(CG(declarables).ticks) = 0; } /* }}} */ void zend_init_compiler_context(TSRMLS_D) /* {{{ */ { CG(context).opcodes_size = (CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) ? INITIAL_INTERACTIVE_OP_ARRAY_SIZE : INITIAL_OP_ARRAY_SIZE; CG(context).vars_size = 0; CG(context).literals_size = 0; CG(context).current_brk_cont = -1; CG(context).backpatch_count = 0; CG(context).labels = NULL; } /* }}} */ void zend_init_compiler_data_structures(TSRMLS_D) /* {{{ */ { zend_stack_init(&CG(bp_stack)); zend_stack_init(&CG(function_call_stack)); zend_stack_init(&CG(switch_cond_stack)); zend_stack_init(&CG(foreach_copy_stack)); zend_stack_init(&CG(object_stack)); zend_stack_init(&CG(declare_stack)); CG(active_class_entry) = NULL; zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_stack_init(&CG(list_stack)); CG(in_compilation) = 0; CG(start_lineno) = 0; CG(current_namespace) = NULL; CG(in_namespace) = 0; CG(has_bracketed_namespaces) = 0; CG(current_import) = NULL; init_compiler_declarables(TSRMLS_C); zend_stack_init(&CG(context_stack)); CG(encoding_declared) = 0; } /* }}} */ ZEND_API void file_handle_dtor(zend_file_handle *fh) /* {{{ */ { TSRMLS_FETCH(); zend_file_handle_dtor(fh TSRMLS_CC); } /* }}} */ void init_compiler(TSRMLS_D) /* {{{ */ { CG(active_op_array) = NULL; zend_init_compiler_data_structures(TSRMLS_C); zend_init_rsrc_list(TSRMLS_C); zend_hash_init(&CG(filenames_table), 5, NULL, (dtor_func_t) free_estring, 0); zend_llist_init(&CG(open_files), sizeof(zend_file_handle), (void (*)(void *)) file_handle_dtor, 0); CG(unclean_shutdown) = 0; } /* }}} */ void shutdown_compiler(TSRMLS_D) /* {{{ */ { zend_stack_destroy(&CG(bp_stack)); zend_stack_destroy(&CG(function_call_stack)); zend_stack_destroy(&CG(switch_cond_stack)); zend_stack_destroy(&CG(foreach_copy_stack)); zend_stack_destroy(&CG(object_stack)); zend_stack_destroy(&CG(declare_stack)); zend_stack_destroy(&CG(list_stack)); zend_hash_destroy(&CG(filenames_table)); zend_llist_destroy(&CG(open_files)); zend_stack_destroy(&CG(context_stack)); } /* }}} */ ZEND_API char *zend_set_compiled_filename(const char *new_compiled_filename TSRMLS_DC) /* {{{ */ { char **pp, *p; int length = strlen(new_compiled_filename); if (zend_hash_find(&CG(filenames_table), new_compiled_filename, length+1, (void **) &pp) == SUCCESS) { CG(compiled_filename) = *pp; return *pp; } p = estrndup(new_compiled_filename, length); zend_hash_update(&CG(filenames_table), new_compiled_filename, length+1, &p, sizeof(char *), (void **) &pp); CG(compiled_filename) = p; return p; } /* }}} */ ZEND_API void zend_restore_compiled_filename(char *original_compiled_filename TSRMLS_DC) /* {{{ */ { CG(compiled_filename) = original_compiled_filename; } /* }}} */ ZEND_API char *zend_get_compiled_filename(TSRMLS_D) /* {{{ */ { return CG(compiled_filename); } /* }}} */ ZEND_API int zend_get_compiled_lineno(TSRMLS_D) /* {{{ */ { return CG(zend_lineno); } /* }}} */ ZEND_API zend_bool zend_is_compiling(TSRMLS_D) /* {{{ */ { return CG(in_compilation); } /* }}} */ static zend_uint get_temporary_variable(zend_op_array *op_array) /* {{{ */ { return (op_array->T)++ * ZEND_MM_ALIGNED_SIZE(sizeof(temp_variable)); } /* }}} */ static int lookup_cv(zend_op_array *op_array, char* name, int name_len, ulong hash TSRMLS_DC) /* {{{ */ { int i = 0; ulong hash_value = hash ? hash : zend_inline_hash_func(name, name_len+1); while (i < op_array->last_var) { if (op_array->vars[i].name == name || (op_array->vars[i].hash_value == hash_value && op_array->vars[i].name_len == name_len && memcmp(op_array->vars[i].name, name, name_len) == 0)) { str_efree(name); return i; } i++; } i = op_array->last_var; op_array->last_var++; if (op_array->last_var > CG(context).vars_size) { CG(context).vars_size += 16; /* FIXME */ op_array->vars = erealloc(op_array->vars, CG(context).vars_size * sizeof(zend_compiled_variable)); } op_array->vars[i].name = zend_new_interned_string(name, name_len + 1, 1 TSRMLS_CC); op_array->vars[i].name_len = name_len; op_array->vars[i].hash_value = hash_value; return i; } /* }}} */ void zend_del_literal(zend_op_array *op_array, int n) /* {{{ */ { zval_dtor(&CONSTANT_EX(op_array, n)); if (n + 1 == op_array->last_literal) { op_array->last_literal--; } else { Z_TYPE(CONSTANT_EX(op_array, n)) = IS_NULL; } } /* }}} */ /* Common part of zend_add_literal and zend_append_individual_literal */ static inline void zend_insert_literal(zend_op_array *op_array, const zval *zv, int literal_position TSRMLS_DC) /* {{{ */ { if (Z_TYPE_P(zv) == IS_STRING || Z_TYPE_P(zv) == IS_CONSTANT) { zval *z = (zval*)zv; Z_STRVAL_P(z) = (char*)zend_new_interned_string(Z_STRVAL_P(zv), Z_STRLEN_P(zv) + 1, 1 TSRMLS_CC); } CONSTANT_EX(op_array, literal_position) = *zv; Z_SET_REFCOUNT(CONSTANT_EX(op_array, literal_position), 2); Z_SET_ISREF(CONSTANT_EX(op_array, literal_position)); op_array->literals[literal_position].hash_value = 0; op_array->literals[literal_position].cache_slot = -1; } /* }}} */ /* Is used while compiling a function, using the context to keep track of an approximate size to avoid to relocate to often. Literals are truncated to actual size in the second compiler pass (pass_two()). */ int zend_add_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; if (i >= CG(context).literals_size) { while (i >= CG(context).literals_size) { CG(context).literals_size += 16; /* FIXME */ } op_array->literals = (zend_literal*)erealloc(op_array->literals, CG(context).literals_size * sizeof(zend_literal)); } zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ /* Is used after normal compilation to append an additional literal. Allocation is done precisely here. */ int zend_append_individual_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; op_array->literals = (zend_literal*)erealloc(op_array->literals, (i + 1) * sizeof(zend_literal)); zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ int zend_add_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_ns_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; const char *ns_separator; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); ns_separator = (const char*)zend_memrchr(Z_STRVAL_P(zv), '\\', Z_STRLEN_P(zv)) + 1; lc_len = Z_STRLEN_P(zv) - (ns_separator - Z_STRVAL_P(zv)); lc_name = zend_str_tolower_dup(ns_separator, lc_len); ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_class_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } if (Z_STRVAL_P(zv)[0] == '\\') { lc_len = Z_STRLEN_P(zv) - 1; lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv) + 1, lc_len); } else { lc_len = Z_STRLEN_P(zv); lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), lc_len); } ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); GET_CACHE_SLOT(ret); return ret; } /* }}} */ int zend_add_const_name_literal(zend_op_array *op_array, const zval *zv, int unqualified TSRMLS_DC) /* {{{ */ { int ret, tmp_literal; char *name, *tmp_name; const char *ns_separator; int name_len, ns_len; zval c; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } /* skip leading '\\' */ if (Z_STRVAL_P(zv)[0] == '\\') { name_len = Z_STRLEN_P(zv) - 1; name = Z_STRVAL_P(zv) + 1; } else { name_len = Z_STRLEN_P(zv); name = Z_STRVAL_P(zv); } ns_separator = zend_memrchr(name, '\\', name_len); if (ns_separator) { ns_len = ns_separator - name; } else { ns_len = 0; } if (ns_len) { /* lowercased namespace name & original constant name */ tmp_name = estrndup(name, name_len); zend_str_tolower(tmp_name, ns_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased namespace name & lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); } if (ns_len) { if (!unqualified) { return ret; } ns_len++; name += ns_len; name_len -= ns_len; } /* original constant name */ tmp_name = estrndup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); return ret; } /* }}} */ #define LITERAL_STRINGL(op, str, len, copy) do { \ zval _c; \ ZVAL_STRINGL(&_c, str, len, copy); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG(op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG_EX(op_array, op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(op_array, &_c TSRMLS_CC); \ } while (0) #define LITERAL_NULL(op) do { \ zval _c; \ INIT_ZVAL( _c); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) static inline zend_bool zend_is_function_or_method_call(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; return ((type & ZEND_PARSED_METHOD_CALL) || (type == ZEND_PARSED_FUNCTION_CALL)); } /* }}} */ void zend_do_binary_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_unary_op(zend_uchar op, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); GET_NODE(result, opline->result); SET_UNUSED(opline->op2); } /* }}} */ #define MAKE_NOP(opline) { opline->opcode = ZEND_NOP; memset(&opline->result,0,sizeof(opline->result)); memset(&opline->op1,0,sizeof(opline->op1)); memset(&opline->op2,0,sizeof(opline->op2)); opline->result_type=opline->op1_type=opline->op2_type=IS_UNUSED; } static void zend_do_op_data(zend_op *data_op, const znode *value TSRMLS_DC) /* {{{ */ { data_op->opcode = ZEND_OP_DATA; SET_NODE(data_op->op1, value); SET_UNUSED(data_op->op2); } /* }}} */ void zend_do_binary_assign_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; switch (last_op->opcode) { case ZEND_FETCH_OBJ_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, op2 TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; case ZEND_FETCH_DIM_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_DIM; zend_do_op_data(opline, op2 TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result,last_op->result); return; default: break; } } opline->opcode = op; SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void fetch_simple_variable_ex(znode *result, znode *varname, int bp, zend_uchar op TSRMLS_DC) /* {{{ */ { zend_op opline; zend_op *opline_ptr; zend_llist *fetch_list_ptr; if (varname->op_type == IS_CONST) { ulong hash = 0; if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } else if (IS_INTERNED(Z_STRVAL(varname->u.constant))) { hash = INTERNED_HASH(Z_STRVAL(varname->u.constant)); } if (!zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC) && !(varname->u.constant.value.str.len == (sizeof("this")-1) && !memcmp(varname->u.constant.value.str.val, "this", sizeof("this"))) && (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE)) { result->op_type = IS_CV; result->u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC); varname->u.constant.value.str.val = (char*)CG(active_op_array)->vars[result->u.op.var].name; result->EA = 0; return; } } if (bp) { opline_ptr = &opline; init_op(opline_ptr TSRMLS_CC); } else { opline_ptr = get_next_op(CG(active_op_array) TSRMLS_CC); } opline_ptr->opcode = op; opline_ptr->result_type = IS_VAR; opline_ptr->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline_ptr->op1, varname); GET_NODE(result, opline_ptr->result); SET_UNUSED(opline_ptr->op2); opline_ptr->extended_value = ZEND_FETCH_LOCAL; if (varname->op_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline_ptr->op1.constant); if (zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC)) { opline_ptr->extended_value = ZEND_FETCH_GLOBAL; } } if (bp) { zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); zend_llist_add_element(fetch_list_ptr, opline_ptr); } } /* }}} */ void fetch_simple_variable(znode *result, znode *varname, int bp TSRMLS_DC) /* {{{ */ { /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ fetch_simple_variable_ex(result, varname, bp, ZEND_FETCH_W TSRMLS_CC); } /* }}} */ void zend_do_fetch_static_member(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { znode class_node; zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline_ptr; zend_op opline; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); } zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (result->op_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[result->u.op.var].name), CG(active_op_array)->vars[result->u.op.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } GET_NODE(result,opline.result); opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; opline_ptr = &opline; zend_llist_add_element(fetch_list_ptr, &opline); } else { le = fetch_list_ptr->head; opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode != ZEND_FETCH_W && opline_ptr->op1_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[opline_ptr->op1.var].name), CG(active_op_array)->vars[opline_ptr->op1.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; COPY_NODE(opline_ptr->op1, opline.result); zend_llist_prepend_element(fetch_list_ptr, &opline); } else { if (opline_ptr->op1_type == IS_CONST) { GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op1.constant); } if (class_node.op_type == IS_CONST) { opline_ptr->op2_type = IS_CONST; opline_ptr->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline_ptr->op2, &class_node); } opline_ptr->extended_value |= ZEND_FETCH_STATIC_MEMBER; } } } /* }}} */ void fetch_array_begin(znode *result, znode *varname, znode *first_dim TSRMLS_DC) /* {{{ */ { fetch_simple_variable(result, varname, 1 TSRMLS_CC); fetch_array_dim(result, result, first_dim TSRMLS_CC); } /* }}} */ void fetch_array_dim(znode *result, const znode *parent, const znode *dim TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (zend_is_function_or_method_call(parent)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, parent); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_DIM_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, parent); SET_NODE(opline.op2, dim); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline.op2.constant)), Z_STRLEN(CONSTANT(opline.op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline.op2.constant)); ZVAL_LONG(&CONSTANT(opline.op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline.op2.constant); } } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void fetch_string_offset(znode *result, const znode *parent, const znode *offset TSRMLS_DC) /* {{{ */ { fetch_array_dim(result, parent, offset TSRMLS_CC); } /* }}} */ void zend_do_print(znode *result, const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->opcode = ZEND_PRINT; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_echo(const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ECHO; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_abstract_method(const znode *function_name, znode *modifiers, const znode *body TSRMLS_DC) /* {{{ */ { char *method_type; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { Z_LVAL(modifiers->u.constant) |= ZEND_ACC_ABSTRACT; method_type = "Interface"; } else { method_type = "Abstract"; } if (modifiers->u.constant.value.lval & ZEND_ACC_ABSTRACT) { if(modifiers->u.constant.value.lval & ZEND_ACC_PRIVATE) { zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot be declared private", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } if (Z_LVAL(body->u.constant) == ZEND_ACC_ABSTRACT) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_RAISE_ABSTRACT_ERROR; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } else { /* we had code in the function body */ zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot contain body", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } else { if (body->u.constant.value.lval == ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Non-abstract method %s::%s() must contain body", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } } /* }}} */ static zend_bool opline_is_fetch_this(const zend_op *opline TSRMLS_DC) /* {{{ */ { if ((opline->opcode == ZEND_FETCH_W) && (opline->op1_type == IS_CONST) && (Z_TYPE(CONSTANT(opline->op1.constant)) == IS_STRING) && (Z_HASH_P(&CONSTANT(opline->op1.constant)) == THIS_HASHVAL) && (Z_STRLEN(CONSTANT(opline->op1.constant)) == (sizeof("this")-1)) && !memcmp(Z_STRVAL(CONSTANT(opline->op1.constant)), "this", sizeof("this"))) { return 1; } else { return 0; } } /* }}} */ void zend_do_assign(znode *result, znode *variable, znode *value TSRMLS_DC) /* {{{ */ { int last_op_number; zend_op *opline; if (value->op_type == IS_CV) { zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (fetch_list_ptr && fetch_list_ptr->head) { opline = (zend_op *)fetch_list_ptr->head->data; if (opline->opcode == ZEND_FETCH_DIM_W && opline->op1_type == IS_CV && opline->op1.var == value->u.op.var) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_R; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->op1_type = IS_CONST; LITERAL_STRINGL(opline->op1, CG(active_op_array)->vars[value->u.op.var].name, CG(active_op_array)->vars[value->u.op.var].name_len, 1); CALCULATE_LITERAL_HASH(opline->op1.constant); SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_LOCAL; GET_NODE(value, opline->result); } } } zend_do_end_variable_parse(variable, BP_VAR_W, 0 TSRMLS_CC); last_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (variable->op_type == IS_CV) { if (variable->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (variable->op_type == IS_VAR) { int n = 0; while (last_op_number - n > 0) { zend_op *last_op; last_op = &CG(active_op_array)->opcodes[last_op_number-n-1]; if (last_op->result_type == IS_VAR && last_op->result.var == variable->u.op.var) { if (last_op->opcode == ZEND_FETCH_OBJ_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, value TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (last_op->opcode == ZEND_FETCH_DIM_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ /* TBFixed: this can realloc opcodes, leaving last_op pointing wrong */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_DIM; zend_do_op_data(opline, value TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (opline_is_fetch_this(last_op TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } else { break; } } n++; } } opline->opcode = ZEND_ASSIGN; SET_NODE(opline->op1, variable); SET_NODE(opline->op2, value); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_assign_ref(znode *result, const znode *lvar, const znode *rvar TSRMLS_DC) /* {{{ */ { zend_op *opline; if (lvar->op_type == IS_CV) { if (lvar->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (lvar->op_type == IS_VAR) { int last_op_number = get_next_op_number(CG(active_op_array)); if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline_is_fetch_this(opline TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ASSIGN_REF; if (zend_is_function_or_method_call(rvar)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } else if (rvar->EA & ZEND_PARSED_NEW) { opline->extended_value = ZEND_RETURNS_NEW; } else { opline->extended_value = 0; } if (result) { opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } else { opline->result_type = IS_UNUSED | EXT_TYPE_UNUSED; } SET_NODE(opline->op1, lvar); SET_NODE(opline->op2, rvar); } /* }}} */ static inline void do_begin_loop(TSRMLS_D) /* {{{ */ { zend_brk_cont_element *brk_cont_element; int parent; parent = CG(context).current_brk_cont; CG(context).current_brk_cont = CG(active_op_array)->last_brk_cont; brk_cont_element = get_next_brk_cont_element(CG(active_op_array)); brk_cont_element->start = get_next_op_number(CG(active_op_array)); brk_cont_element->parent = parent; } /* }}} */ static inline void do_end_loop(int cont_addr, int has_loop_var TSRMLS_DC) /* {{{ */ { if (!has_loop_var) { /* The start fileld is used to free temporary variables in case of exceptions. * We won't try to free something of we don't have loop variable. */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].start = -1; } CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = cont_addr; CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; } /* }}} */ void zend_do_while_cond(const znode *expr, znode *close_bracket_token TSRMLS_DC) /* {{{ */ { int while_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, expr); close_bracket_token->u.op.opline_num = while_cond_op_number; SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_while_end(const znode *while_token, const znode *close_bracket_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* add unconditional jump */ opline->opcode = ZEND_JMP; opline->op1.opline_num = while_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* update while's conditional jmp */ CG(active_op_array)->opcodes[close_bracket_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); do_end_loop(while_token->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_cond(const znode *expr, znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { int for_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZNZ; SET_NODE(opline->op1, expr); /* the conditional expression */ second_semicolon_token->u.op.opline_num = for_cond_op_number; SET_UNUSED(opline->op2); } /* }}} */ void zend_do_for_before_statement(const znode *cond_start, const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = cond_start->u.op.opline_num; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_end(const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = second_semicolon_token->u.op.opline_num+1; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_end_loop(second_semicolon_token->u.op.opline_num+1, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_pre_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_PRE_INC)?ZEND_PRE_INC_OBJ:ZEND_PRE_DEC_OBJ; last_op->result_type = IS_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_post_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_POST_INC)?ZEND_POST_INC_OBJ:ZEND_POST_DEC_OBJ; last_op->result_type = IS_TMP_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_if_cond(const znode *cond, znode *closing_bracket_token TSRMLS_DC) /* {{{ */ { int if_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); closing_bracket_token->u.op.opline_num = if_cond_op_number; SET_UNUSED(opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_if_after_statement(const znode *closing_bracket_token, unsigned char initialize TSRMLS_DC) /* {{{ */ { int if_end_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; /* save for backpatching */ if (initialize) { zend_llist jmp_list; zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); } zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &if_end_op_number); CG(active_op_array)->opcodes[closing_bracket_token->u.op.opline_num].op2.opline_num = if_end_op_number+1; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_if_end(TSRMLS_D) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_llist *jmp_list_ptr; zend_llist_element *le; zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); for (le=jmp_list_ptr->head; le; le = le->next) { CG(active_op_array)->opcodes[*((int *) le->data)].op1.opline_num = next_op_number; } zend_llist_destroy(jmp_list_ptr); zend_stack_del_top(&CG(bp_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_check_writable_variable(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; if (type & ZEND_PARSED_METHOD_CALL) { zend_error(E_COMPILE_ERROR, "Can't use method return value in write context"); } if (type == ZEND_PARSED_FUNCTION_CALL) { zend_error(E_COMPILE_ERROR, "Can't use function return value in write context"); } } /* }}} */ void zend_do_begin_variable_parse(TSRMLS_D) /* {{{ */ { zend_llist fetch_list; zend_llist_init(&fetch_list, sizeof(zend_op), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &fetch_list, sizeof(zend_llist)); } /* }}} */ void zend_do_end_variable_parse(znode *variable, int type, int arg_offset TSRMLS_DC) /* {{{ */ { zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline = NULL; zend_op *opline_ptr; zend_uint this_var = -1; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); le = fetch_list_ptr->head; /* TODO: $foo->x->y->z = 1 should fetch "x" and "y" for R or RW, not just W */ if (le) { opline_ptr = (zend_op *)le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { /* convert to FETCH_?(this) into IS_CV */ if (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE) { this_var = opline_ptr->result.var; if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), Z_STRVAL(CONSTANT(opline_ptr->op1.constant)), Z_STRLEN(CONSTANT(opline_ptr->op1.constant)), Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC); Z_TYPE(CONSTANT(opline_ptr->op1.constant)) = IS_NULL; } else { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); } le = le->next; if (variable->op_type == IS_VAR && variable->u.op.var == this_var) { variable->op_type = IS_CV; variable->u.op.var = CG(active_op_array)->this_var; } } else if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } while (le) { opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode == ZEND_SEPARATE) { if (type != BP_VAR_R && type != BP_VAR_IS) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); } le = le->next; continue; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); if (opline->op1_type == IS_VAR && opline->op1.var == this_var) { opline->op1_type = IS_CV; opline->op1.var = CG(active_op_array)->this_var; } switch (type) { case BP_VAR_R: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode -= 3; break; case BP_VAR_W: break; case BP_VAR_RW: opline->opcode += 3; break; case BP_VAR_IS: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode += 6; /* 3+3 */ break; case BP_VAR_FUNC_ARG: opline->opcode += 9; /* 3+3+3 */ opline->extended_value |= arg_offset; break; case BP_VAR_UNSET: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for unsetting"); } opline->opcode += 12; /* 3+3+3+3 */ break; } le = le->next; } if (opline && type == BP_VAR_W && arg_offset) { opline->extended_value |= ZEND_FETCH_MAKE_REF; } } zend_llist_destroy(fetch_list_ptr); zend_stack_del_top(&CG(bp_stack)); } /* }}} */ void zend_do_add_string(znode *result, const znode *op1, znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline; if (Z_STRLEN(op2->u.constant) > 1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_STRING; } else if (Z_STRLEN(op2->u.constant) == 1) { int ch = *Z_STRVAL(op2->u.constant); /* Free memory and use ZEND_ADD_CHAR in case of 1 character strings */ efree(Z_STRVAL(op2->u.constant)); ZVAL_LONG(&op2->u.constant, ch); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_CHAR; } else { /* String can be empty after a variable at the end of a heredoc */ efree(Z_STRVAL(op2->u.constant)); return; } if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_add_variable(znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_VAR; if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_free(znode *op1 TSRMLS_DC) /* {{{ */ { if (op1->op_type==IS_TMP_VAR) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else if (op1->op_type==IS_VAR) { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; while (opline->opcode == ZEND_END_SILENCE || opline->opcode == ZEND_EXT_FCALL_END || opline->opcode == ZEND_OP_DATA) { opline--; } if (opline->result_type == IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_FETCH_R || opline->opcode == ZEND_FETCH_DIM_R || opline->opcode == ZEND_FETCH_OBJ_R || opline->opcode == ZEND_QM_ASSIGN_VAR) { /* It's very rare and useless case. It's better to use additional FREE opcode and simplify the FETCH handlers their selves */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else { opline->result_type |= EXT_TYPE_UNUSED; } } else { while (opline>CG(active_op_array)->opcodes) { if (opline->opcode == ZEND_FETCH_DIM_R && opline->op1_type == IS_VAR && opline->op1.var == op1->u.op.var) { /* This should the end of a list() construct * Mark its result as unused */ opline->extended_value = ZEND_FETCH_STANDARD; break; } else if (opline->result_type==IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_NEW) { opline->result_type |= EXT_TYPE_UNUSED; } break; } opline--; } } } else if (op1->op_type == IS_CONST) { zval_dtor(&op1->u.constant); } } /* }}} */ int zend_do_verify_access_types(const znode *current_access_type, const znode *new_modifier) /* {{{ */ { if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_PPP_MASK) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Multiple access type modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_ABSTRACT) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Multiple abstract modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_STATIC) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Multiple static modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_FINAL) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Multiple final modifiers are not allowed"); } if (((Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)) & (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) == (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Cannot use the final modifier on an abstract class member"); } return (Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)); } /* }}} */ void zend_do_begin_function_declaration(znode *function_token, znode *function_name, int is_method, int return_reference, znode *fn_flags_znode TSRMLS_DC) /* {{{ */ { zend_op_array op_array; char *name = function_name->u.constant.value.str.val; int name_len = function_name->u.constant.value.str.len; int function_begin_line = function_token->u.op.opline_num; zend_uint fn_flags; const char *lcname; zend_bool orig_interactive; ALLOCA_FLAG(use_heap) if (is_method) { if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((Z_LVAL(fn_flags_znode->u.constant) & ~(ZEND_ACC_STATIC|ZEND_ACC_PUBLIC))) { zend_error(E_COMPILE_ERROR, "Access type for interface method %s::%s() must be omitted", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } Z_LVAL(fn_flags_znode->u.constant) |= ZEND_ACC_ABSTRACT; /* propagates to the rest of the parser */ } fn_flags = Z_LVAL(fn_flags_znode->u.constant); /* must be done *after* the above check */ } else { fn_flags = 0; } if ((fn_flags & ZEND_ACC_STATIC) && (fn_flags & ZEND_ACC_ABSTRACT) && !(CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_STRICT, "Static function %s%s%s() should not be abstract", is_method ? CG(active_class_entry)->name : "", is_method ? "::" : "", Z_STRVAL(function_name->u.constant)); } function_token->u.op_array = CG(active_op_array); orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(&op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; op_array.function_name = name; if (return_reference) { op_array.fn_flags |= ZEND_ACC_RETURN_REFERENCE; } op_array.fn_flags |= fn_flags; op_array.scope = is_method?CG(active_class_entry):NULL; op_array.prototype = NULL; op_array.line_start = zend_get_compiled_lineno(TSRMLS_C); if (is_method) { int result; lcname = zend_new_interned_string(zend_str_tolower_dup(name, name_len), name_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lcname)) { result = zend_hash_quick_add(&CG(active_class_entry)->function_table, lcname, name_len+1, INTERNED_HASH(lcname), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } else { result = zend_hash_add(&CG(active_class_entry)->function_table, lcname, name_len+1, &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } if (result == FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::%s()", CG(active_class_entry)->name, name); } zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); if (fn_flags & ZEND_ACC_ABSTRACT) { CG(active_class_entry)->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (!(fn_flags & ZEND_ACC_PPP_MASK)) { fn_flags |= ZEND_ACC_PUBLIC; } if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } } } else { char *class_lcname; class_lcname = do_alloca(CG(active_class_entry)->name_length + 1, use_heap); zend_str_tolower_copy(class_lcname, CG(active_class_entry)->name, CG(active_class_entry)->name_length); /* Improve after RC: cache the lowercase class name */ if ((CG(active_class_entry)->name_length == name_len) && ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT) && (!memcmp(class_lcname, lcname, name_len))) { if (!CG(active_class_entry)->constructor) { CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } } else if ((name_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)))) { if (CG(active_class_entry)->constructor) { zend_error(E_STRICT, "Redefining already defined constructor for class %s", CG(active_class_entry)->name); } CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1))) { CG(active_class_entry)->destructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1))) { CG(active_class_entry)->clone = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } CG(active_class_entry)->__call = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } CG(active_class_entry)->__callstatic = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } CG(active_class_entry)->__get = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } CG(active_class_entry)->__set = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } CG(active_class_entry)->__unset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } CG(active_class_entry)->__isset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } CG(active_class_entry)->__tostring = (zend_function *) CG(active_op_array); } else if (!(fn_flags & ZEND_ACC_STATIC)) { CG(active_op_array)->fn_flags |= ZEND_ACC_ALLOW_STATIC; } free_alloca(class_lcname, use_heap); } str_efree(lcname); } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zval key; if (CG(current_namespace)) { /* Prefix function name with current namespcae name */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, function_name TSRMLS_CC); op_array.function_name = Z_STRVAL(tmp.u.constant); name_len = Z_STRLEN(tmp.u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), name_len); } else { lcname = zend_str_tolower_dup(name, name_len); } opline->opcode = ZEND_DECLARE_FUNCTION; opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, name_len TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; LITERAL_STRINGL(opline->op2, lcname, name_len, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); opline->extended_value = ZEND_DECLARE_FUNCTION; zend_hash_quick_update(CG(function_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); } if (CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_NOP; opline->lineno = function_begin_line; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } { /* Push a seperator to the switch and foreach stacks */ zend_switch_entry switch_entry; switch_entry.cond.op_type = IS_UNUSED; switch_entry.default_case = 0; switch_entry.control_var = 0; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); { /* Foreach stack separator */ zend_op dummy_opline; dummy_opline.result_type = IS_UNUSED; dummy_opline.op1_type = IS_UNUSED; zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); } } if (CG(doc_comment)) { CG(active_op_array)->doc_comment = CG(doc_comment); CG(active_op_array)->doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_begin_lambda_function_declaration(znode *result, znode *function_token, int return_reference, int is_static TSRMLS_DC) /* {{{ */ { znode function_name; zend_op_array *current_op_array = CG(active_op_array); int current_op_number = get_next_op_number(CG(active_op_array)); zend_op *current_op; function_name.op_type = IS_CONST; ZVAL_STRINGL(&function_name.u.constant, "{closure}", sizeof("{closure}")-1, 1); zend_do_begin_function_declaration(function_token, &function_name, 0, return_reference, NULL TSRMLS_CC); result->op_type = IS_TMP_VAR; result->u.op.var = get_temporary_variable(current_op_array); current_op = &current_op_array->opcodes[current_op_number]; current_op->opcode = ZEND_DECLARE_LAMBDA_FUNCTION; zend_del_literal(current_op_array, current_op->op2.constant); SET_UNUSED(current_op->op2); SET_NODE(current_op->result, result); if (is_static) { CG(active_op_array)->fn_flags |= ZEND_ACC_STATIC; } CG(active_op_array)->fn_flags |= ZEND_ACC_CLOSURE; } /* }}} */ void zend_do_handle_exception(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_HANDLE_EXCEPTION; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_function_declaration(const znode *function_token TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; zend_do_extended_info(TSRMLS_C); zend_do_return(NULL, 0 TSRMLS_CC); pass_two(CG(active_op_array) TSRMLS_CC); zend_release_labels(TSRMLS_C); if (CG(active_class_entry)) { zend_check_magic_method_implementation(CG(active_class_entry), (zend_function*)CG(active_op_array), E_COMPILE_ERROR TSRMLS_CC); } else { /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(CG(active_op_array)->function_name); zend_str_tolower_copy(lcname, CG(active_op_array)->function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME)) && CG(active_op_array)->num_args != 1) { zend_error(E_COMPILE_ERROR, "%s() must take exactly 1 argument", ZEND_AUTOLOAD_FUNC_NAME); } } CG(active_op_array)->line_end = zend_get_compiled_lineno(TSRMLS_C); CG(active_op_array) = function_token->u.op_array; /* Pop the switch and foreach seperators */ zend_stack_del_top(&CG(switch_cond_stack)); zend_stack_del_top(&CG(foreach_copy_stack)); } /* }}} */ void zend_do_receive_arg(zend_uchar op, znode *varname, const znode *offset, const znode *initialization, znode *class_type, zend_uchar pass_by_reference TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_arg_info *cur_arg_info; znode var; if (class_type->op_type == IS_CONST && Z_TYPE(class_type->u.constant) == IS_STRING && Z_STRLEN(class_type->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_type->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } if (zend_is_auto_global_quick(Z_STRVAL(varname->u.constant), Z_STRLEN(varname->u.constant), 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign auto-global variable %s", Z_STRVAL(varname->u.constant)); } else { var.op_type = IS_CV; var.u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(varname->u.constant) = (char*)CG(active_op_array)->vars[var.u.op.var].name; var.EA = 0; if (CG(active_op_array)->vars[var.u.op.var].hash_value == THIS_HASHVAL && Z_STRLEN(varname->u.constant) == sizeof("this")-1 && !memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this")-1)) { if (CG(active_op_array)->scope && (CG(active_op_array)->fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } CG(active_op_array)->this_var = var.u.op.var; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->num_args++; opline->opcode = op; SET_NODE(opline->result, &var); SET_NODE(opline->op1, offset); if (op == ZEND_RECV_INIT) { SET_NODE(opline->op2, initialization); } else { CG(active_op_array)->required_num_args = CG(active_op_array)->num_args; SET_UNUSED(opline->op2); } CG(active_op_array)->arg_info = erealloc(CG(active_op_array)->arg_info, sizeof(zend_arg_info)*(CG(active_op_array)->num_args)); cur_arg_info = &CG(active_op_array)->arg_info[CG(active_op_array)->num_args-1]; cur_arg_info->name = zend_new_interned_string(estrndup(varname->u.constant.value.str.val, varname->u.constant.value.str.len), varname->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->name_len = varname->u.constant.value.str.len; cur_arg_info->type_hint = 0; cur_arg_info->allow_null = 1; cur_arg_info->pass_by_reference = pass_by_reference; cur_arg_info->class_name = NULL; cur_arg_info->class_name_len = 0; if (class_type->op_type != IS_UNUSED) { cur_arg_info->allow_null = 0; if (class_type->u.constant.type != IS_NULL) { if (class_type->u.constant.type == IS_ARRAY) { cur_arg_info->type_hint = IS_ARRAY; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else if (Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Default value for parameters with array type hint can only be an array or NULL"); } } } else if (class_type->u.constant.type == IS_CALLABLE) { cur_arg_info->type_hint = IS_CALLABLE; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with callable type hint can only be NULL"); } } } else { cur_arg_info->type_hint = IS_OBJECT; if (ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_type->u.constant), Z_STRLEN(class_type->u.constant))) { zend_resolve_class_name(class_type, opline->extended_value, 1 TSRMLS_CC); } Z_STRVAL(class_type->u.constant) = (char*)zend_new_interned_string(class_type->u.constant.value.str.val, class_type->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->class_name = class_type->u.constant.value.str.val; cur_arg_info->class_name_len = class_type->u.constant.value.str.len; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with a class type hint can only be NULL"); } } } } } } /* }}} */ int zend_do_begin_function_call(znode *function_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { zend_function *function; char *lcname; char *is_compound = memchr(Z_STRVAL(function_name->u.constant), '\\', Z_STRLEN(function_name->u.constant)); zend_resolve_non_class_name(function_name, check_namespace TSRMLS_CC); if (check_namespace && CG(current_namespace) && !is_compound) { /* We assume we call function from the current namespace if it is not prefixed. */ /* In run-time PHP will check for function with full name and internal function with short name */ zend_do_begin_dynamic_function_call(function_name, 1 TSRMLS_CC); return 1; } lcname = zend_str_tolower_dup(function_name->u.constant.value.str.val, function_name->u.constant.value.str.len); if ((zend_hash_find(CG(function_table), lcname, function_name->u.constant.value.str.len+1, (void **) &function)==FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_FUNCTIONS) && (function->type == ZEND_INTERNAL_FUNCTION))) { zend_do_begin_dynamic_function_call(function_name, 0 TSRMLS_CC); efree(lcname); return 1; /* Dynamic */ } efree(function_name->u.constant.value.str.val); function_name->u.constant.value.str.val = lcname; zend_stack_push(&CG(function_call_stack), (void *) &function, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 0; } /* }}} */ void zend_do_begin_method_call(znode *left_bracket TSRMLS_DC) /* {{{ */ { zend_op *last_op; int last_op_number; unsigned char *ptr = NULL; zend_do_end_variable_parse(left_bracket, BP_VAR_R, 0 TSRMLS_CC); zend_do_begin_variable_parse(TSRMLS_C); last_op_number = get_next_op_number(CG(active_op_array))-1; last_op = &CG(active_op_array)->opcodes[last_op_number]; if ((last_op->op2_type == IS_CONST) && (Z_TYPE(CONSTANT(last_op->op2.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(last_op->op2.constant)) == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !zend_binary_strcasecmp(Z_STRVAL(CONSTANT(last_op->op2.constant)), Z_STRLEN(CONSTANT(last_op->op2.constant)), ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1)) { zend_error(E_COMPILE_ERROR, "Cannot call __clone() method on objects - use 'clone $obj' instead"); } if (last_op->opcode == ZEND_FETCH_OBJ_R) { if (last_op->op2_type == IS_CONST) { zval name; name = CONSTANT(last_op->op2.constant); if (!IS_INTERNED(Z_STRVAL(name))) { Z_STRVAL(name) = estrndup(Z_STRVAL(name), Z_STRLEN(name)); } FREE_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); last_op->op2.constant = zend_add_func_name_literal(CG(active_op_array), &name TSRMLS_CC); GET_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); } last_op->opcode = ZEND_INIT_METHOD_CALL; SET_UNUSED(last_op->result); Z_LVAL(left_bracket->u.constant) = ZEND_INIT_FCALL_BY_NAME; } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (left_bracket->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &left_bracket->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, left_bracket); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_do_clone(znode *result, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CLONE; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_begin_dynamic_function_call(znode *function_name, int ns_call TSRMLS_DC) /* {{{ */ { unsigned char *ptr = NULL; zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (ns_call) { /* In run-time PHP will check for function with full name and internal function with short name */ opline->opcode = ZEND_INIT_NS_FCALL_BY_NAME; SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_ns_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (function_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, function_name); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_resolve_non_class_name(znode *element_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; int len; zval **ns; char *lcname, *compound = memchr(Z_STRVAL(element_name->u.constant), '\\', Z_STRLEN(element_name->u.constant)); if (Z_STRVAL(element_name->u.constant)[0] == '\\') { /* name starts with \ so it is known and unambiguos, nothing to do here but shorten it */ memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+1, Z_STRLEN(element_name->u.constant)); --Z_STRLEN(element_name->u.constant); return; } if(!check_namespace) { return; } if (compound && CG(current_import)) { len = compound - Z_STRVAL(element_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(element_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(element_name->u.constant) -= len; memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+len, Z_STRLEN(element_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, element_name TSRMLS_CC); *element_name = tmp; efree(lcname); return; } efree(lcname); } if (CG(current_namespace)) { tmp = *element_name; Z_STRLEN(tmp.u.constant) = sizeof("\\")-1 + Z_STRLEN(element_name->u.constant) + Z_STRLEN_P(CG(current_namespace)); Z_STRVAL(tmp.u.constant) = (char *) emalloc(Z_STRLEN(tmp.u.constant)+1); memcpy(Z_STRVAL(tmp.u.constant), Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace))]), "\\", sizeof("\\")-1); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace)) + sizeof("\\")-1]), Z_STRVAL(element_name->u.constant), Z_STRLEN(element_name->u.constant)+1); STR_FREE(Z_STRVAL(element_name->u.constant)); *element_name = tmp; } } /* }}} */ void zend_resolve_class_name(znode *class_name, ulong fetch_type, int check_ns_name TSRMLS_DC) /* {{{ */ { char *compound; char *lcname; zval **ns; znode tmp; int len; compound = memchr(Z_STRVAL(class_name->u.constant), '\\', Z_STRLEN(class_name->u.constant)); if (compound) { /* This is a compound class name that contains namespace prefix */ if (Z_STRVAL(class_name->u.constant)[0] == '\\') { /* The STRING name has "\" prefix */ Z_STRLEN(class_name->u.constant) -= 1; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+1, Z_STRLEN(class_name->u.constant)+1); Z_STRVAL(class_name->u.constant) = erealloc( Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1); if (ZEND_FETCH_CLASS_DEFAULT != zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "'\\%s' is an invalid class name", Z_STRVAL(class_name->u.constant)); } } else { if (CG(current_import)) { len = compound - Z_STRVAL(class_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(class_name->u.constant) -= len; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+len, Z_STRLEN(class_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; efree(lcname); return; } efree(lcname); } /* Here name is not prefixed with \ and not imported */ if (CG(current_namespace)) { tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } } } else if (CG(current_import) || CG(current_namespace)) { /* this is a plain name (without \) */ lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns) == SUCCESS) { /* The given name is an import name. Substitute it. */ zval_dtor(&class_name->u.constant); class_name->u.constant = **ns; zval_copy_ctor(&class_name->u.constant); } else if (CG(current_namespace)) { /* plain name, no import - prepend current namespace to it */ tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } efree(lcname); } } /* }}} */ void zend_do_fetch_class(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { long fetch_class_op_number; zend_op *opline; if (class_name->op_type == IS_CONST && Z_TYPE(class_name->u.constant) == IS_STRING && Z_STRLEN(class_name->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_name->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } fetch_class_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CLASS; SET_UNUSED(opline->op1); opline->extended_value = ZEND_FETCH_CLASS_GLOBAL; CG(catch_begin) = fetch_class_op_number; if (class_name->op_type == IS_CONST) { int fetch_type; fetch_type = zend_get_class_fetch_type(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); switch (fetch_type) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: SET_UNUSED(opline->op2); opline->extended_value = fetch_type; zval_dtor(&class_name->u.constant); break; default: zend_resolve_class_name(class_name, opline->extended_value, 0 TSRMLS_CC); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_name->u.constant TSRMLS_CC); break; } } else { SET_NODE(opline->op2, class_name); } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; /* FIXME: Hack so that INIT_FCALL_BY_NAME still knows this is a class */ GET_NODE(result, opline->result); result->EA = opline->extended_value; } /* }}} */ void zend_do_label(znode *label TSRMLS_DC) /* {{{ */ { zend_label dest; if (!CG(context).labels) { ALLOC_HASHTABLE(CG(context).labels); zend_hash_init(CG(context).labels, 4, NULL, NULL, 0); } dest.brk_cont = CG(context).current_brk_cont; dest.opline_num = get_next_op_number(CG(active_op_array)); if (zend_hash_add(CG(context).labels, Z_STRVAL(label->u.constant), Z_STRLEN(label->u.constant) + 1, (void**)&dest, sizeof(zend_label), NULL) == FAILURE) { zend_error(E_COMPILE_ERROR, "Label '%s' already defined", Z_STRVAL(label->u.constant)); } /* Done with label now */ zval_dtor(&label->u.constant); } /* }}} */ void zend_resolve_goto_label(zend_op_array *op_array, zend_op *opline, int pass2 TSRMLS_DC) /* {{{ */ { zend_label *dest; long current, distance; zval *label; if (pass2) { label = opline->op2.zv; } else { label = &CONSTANT_EX(op_array, opline->op2.constant); } if (CG(context).labels == NULL || zend_hash_find(CG(context).labels, Z_STRVAL_P(label), Z_STRLEN_P(label)+1, (void**)&dest) == FAILURE) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; zend_error(E_COMPILE_ERROR, "'goto' to undefined label '%s'", Z_STRVAL_P(label)); } else { /* Label is not defined. Delay to pass 2. */ INC_BPC(op_array); return; } } opline->op1.opline_num = dest->opline_num; zval_dtor(label); Z_TYPE_P(label) = IS_NULL; /* Check that we are not moving into loop or switch */ current = opline->extended_value; for (distance = 0; current != dest->brk_cont; distance++) { if (current == -1) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; } zend_error(E_COMPILE_ERROR, "'goto' into loop or switch statement is disallowed"); } current = op_array->brk_cont_array[current].parent; } if (distance == 0) { /* Nothing to break out of, optimize to ZEND_JMP */ opline->opcode = ZEND_JMP; opline->extended_value = 0; SET_UNUSED(opline->op2); } else { /* Set real break distance */ ZVAL_LONG(label, distance); } if (pass2) { DEC_BPC(op_array); } } /* }}} */ void zend_do_goto(const znode *label TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_GOTO; opline->extended_value = CG(context).current_brk_cont; SET_UNUSED(opline->op1); SET_NODE(opline->op2, label); zend_resolve_goto_label(CG(active_op_array), opline, 0 TSRMLS_CC); } /* }}} */ void zend_release_labels(TSRMLS_D) /* {{{ */ { if (CG(context).labels) { zend_hash_destroy(CG(context).labels); FREE_HASHTABLE(CG(context).labels); } if (!zend_stack_is_empty(&CG(context_stack))) { zend_compiler_context *ctx; zend_stack_top(&CG(context_stack), (void**)&ctx); CG(context) = *ctx; zend_stack_del_top(&CG(context_stack)); } } /* }}} */ void zend_do_build_full_name(znode *result, znode *prefix, znode *name, int is_class_member TSRMLS_DC) /* {{{ */ { zend_uint length; if (!result) { result = prefix; } else { *result = *prefix; } if (is_class_member) { length = sizeof("::")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "::", sizeof("::")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("::")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } else { length = sizeof("\\")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "\\", sizeof("\\")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("\\")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } } /* }}} */ int zend_do_begin_class_member_function_call(znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { znode class_node; unsigned char *ptr = NULL; zend_op *opline; if (method_name->op_type == IS_CONST) { char *lcname = zend_str_tolower_dup(Z_STRVAL(method_name->u.constant), Z_STRLEN(method_name->u.constant)); if ((sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == Z_STRLEN(method_name->u.constant) && memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == 0) { zval_dtor(&method_name->u.constant); method_name->op_type = IS_UNUSED; } efree(lcname); } if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; opline = get_next_op(CG(active_op_array) TSRMLS_CC); } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->extended_value = class_node.EA ; } opline->opcode = ZEND_INIT_STATIC_METHOD_CALL; if (class_node.op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, &class_node); } if (method_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &method_name->u.constant TSRMLS_CC); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } } else { SET_NODE(opline->op2, method_name); } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 1; /* Dynamic */ } /* }}} */ void zend_do_end_function_call(znode *function_name, znode *result, const znode *argument_list, int is_method, int is_dynamic_fcall TSRMLS_DC) /* {{{ */ { zend_op *opline; if (is_method && function_name && function_name->op_type == IS_UNUSED) { /* clone */ if (Z_LVAL(argument_list->u.constant) != 0) { zend_error(E_WARNING, "Clone method does not require arguments"); } opline = &CG(active_op_array)->opcodes[Z_LVAL(function_name->u.constant)]; } else { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (!is_method && !is_dynamic_fcall && function_name->op_type==IS_CONST) { opline->opcode = ZEND_DO_FCALL; SET_NODE(opline->op1, function_name); CALCULATE_LITERAL_HASH(opline->op1.constant); GET_CACHE_SLOT(opline->op1.constant); } else { opline->opcode = ZEND_DO_FCALL_BY_NAME; SET_UNUSED(opline->op1); } } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(result, opline->result) ; SET_UNUSED(opline->op2); zend_stack_del_top(&CG(function_call_stack)); opline->extended_value = Z_LVAL(argument_list->u.constant); } /* }}} */ void zend_do_pass_param(znode *param, zend_uchar op, int offset TSRMLS_DC) /* {{{ */ { zend_op *opline; int original_op=op; zend_function **function_ptr_ptr, *function_ptr; int send_by_reference; int send_function = 0; zend_stack_top(&CG(function_call_stack), (void **) &function_ptr_ptr); function_ptr = *function_ptr_ptr; if (original_op == ZEND_SEND_REF) { if (function_ptr && function_ptr->common.function_name && function_ptr->common.type == ZEND_USER_FUNCTION && !ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed; " "If you would like to pass argument by reference, modify the declaration of %s().", function_ptr->common.function_name); } else { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed"); } return; } if (function_ptr) { if (ARG_MAY_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { if (param->op_type & (IS_VAR|IS_CV) && original_op != ZEND_SEND_VAL) { send_by_reference = 1; if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION | ZEND_ARG_SEND_SILENT; } } else { op = ZEND_SEND_VAL; send_by_reference = 0; } } else { send_by_reference = ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset) ? ZEND_ARG_SEND_BY_REF : 0; } } else { send_by_reference = 0; } if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION; } else if (op == ZEND_SEND_VAL && (param->op_type & (IS_VAR|IS_CV))) { op = ZEND_SEND_VAR_NO_REF; } if (op!=ZEND_SEND_VAR_NO_REF && send_by_reference==ZEND_ARG_SEND_BY_REF) { /* change to passing by reference */ switch (param->op_type) { case IS_VAR: case IS_CV: op = ZEND_SEND_REF; break; default: zend_error(E_COMPILE_ERROR, "Only variables can be passed by reference"); break; } } if (original_op == ZEND_SEND_VAR) { switch (op) { case ZEND_SEND_VAR_NO_REF: zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); break; case ZEND_SEND_VAR: if (function_ptr) { zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(param, BP_VAR_FUNC_ARG, offset TSRMLS_CC); } break; case ZEND_SEND_REF: zend_do_end_variable_parse(param, BP_VAR_W, 0 TSRMLS_CC); break; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (op == ZEND_SEND_VAR_NO_REF) { if (function_ptr) { opline->extended_value = ZEND_ARG_COMPILE_TIME_BOUND | send_by_reference | send_function; } else { opline->extended_value = send_function; } } else { if (function_ptr) { opline->extended_value = ZEND_DO_FCALL; } else { opline->extended_value = ZEND_DO_FCALL_BY_NAME; } } opline->opcode = op; SET_NODE(opline->op1, param); opline->op2.opline_num = offset; SET_UNUSED(opline->op2); } /* }}} */ static int generate_free_switch_expr(const zend_switch_entry *switch_entry TSRMLS_DC) /* {{{ */ { zend_op *opline; if (switch_entry->cond.op_type != IS_VAR && switch_entry->cond.op_type != IS_TMP_VAR) { return (switch_entry->cond.op_type == IS_UNUSED); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry->cond); SET_UNUSED(opline->op2); opline->extended_value = 0; return 0; } /* }}} */ static int generate_free_foreach_copy(const zend_op *foreach_copy TSRMLS_DC) /* {{{ */ { zend_op *opline; /* If we reach the seperator then stop applying the stack */ if (foreach_copy->result_type == IS_UNUSED && foreach_copy->op1_type == IS_UNUSED) { return 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->result_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->result); SET_UNUSED(opline->op2); opline->extended_value = 1; if (foreach_copy->op1_type != IS_UNUSED) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->op1_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->op1); SET_UNUSED(opline->op2); opline->extended_value = 0; } return 0; } /* }}} */ void zend_do_return(znode *expr, int do_end_vparse TSRMLS_DC) /* {{{ */ { zend_op *opline; int start_op_number, end_op_number; if (do_end_vparse) { if ((CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) && !zend_is_function_or_method_call(expr)) { zend_do_end_variable_parse(expr, BP_VAR_W, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(expr, BP_VAR_R, 0 TSRMLS_CC); } } start_op_number = get_next_op_number(CG(active_op_array)); #ifdef ZTS zend_stack_apply_with_argument(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_switch_expr TSRMLS_CC); zend_stack_apply_with_argument(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_foreach_copy TSRMLS_CC); #else zend_stack_apply(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_switch_expr); zend_stack_apply(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_foreach_copy); #endif end_op_number = get_next_op_number(CG(active_op_array)); while (start_op_number < end_op_number) { CG(active_op_array)->opcodes[start_op_number].extended_value |= EXT_TYPE_FREE_ON_RETURN; start_op_number++; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) ? ZEND_RETURN_BY_REF : ZEND_RETURN; if (expr) { SET_NODE(opline->op1, expr); if (do_end_vparse && zend_is_function_or_method_call(expr)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } } else { opline->op1_type = IS_CONST; LITERAL_NULL(opline->op1); } SET_UNUSED(opline->op2); } /* }}} */ static int zend_add_try_element(zend_uint try_op TSRMLS_DC) /* {{{ */ { int try_catch_offset = CG(active_op_array)->last_try_catch++; CG(active_op_array)->try_catch_array = erealloc(CG(active_op_array)->try_catch_array, sizeof(zend_try_catch_element)*CG(active_op_array)->last_try_catch); CG(active_op_array)->try_catch_array[try_catch_offset].try_op = try_op; return try_catch_offset; } /* }}} */ static void zend_add_catch_element(int offset, zend_uint catch_op TSRMLS_DC) /* {{{ */ { CG(active_op_array)->try_catch_array[offset].catch_op = catch_op; } /* }}} */ void zend_do_first_catch(znode *open_parentheses TSRMLS_DC) /* {{{ */ { open_parentheses->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_initialize_try_catch_element(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist jmp_list; zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); zend_add_catch_element(try_token->u.op.opline_num, get_next_op_number(CG(active_op_array)) TSRMLS_CC); } /* }}} */ void zend_do_mark_last_catch(const znode *first_catch, const znode *last_additional_catch TSRMLS_DC) /* {{{ */ { CG(active_op_array)->last--; zend_do_if_end(TSRMLS_C); if (last_additional_catch->u.op.opline_num == -1) { CG(active_op_array)->opcodes[first_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[first_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } else { CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_try(znode *try_token TSRMLS_DC) /* {{{ */ { try_token->u.op.opline_num = zend_add_try_element(get_next_op_number(CG(active_op_array)) TSRMLS_CC); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_catch(znode *try_token, znode *class_name, znode *catch_var, znode *first_catch TSRMLS_DC) /* {{{ */ { long catch_op_number; zend_op *opline; znode catch_class; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); catch_class = *class_name; } else { zend_error(E_COMPILE_ERROR, "Bad class name in the catch statement"); } catch_op_number = get_next_op_number(CG(active_op_array)); if (first_catch) { first_catch->u.op.opline_num = catch_op_number; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CATCH; opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &catch_class.u.constant TSRMLS_CC); opline->op2_type = IS_CV; opline->op2.var = lookup_cv(CG(active_op_array), catch_var->u.constant.value.str.val, catch_var->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(catch_var->u.constant) = (char*)CG(active_op_array)->vars[opline->op2.var].name; opline->result.num = 0; /* 1 means it's the last catch in the block */ try_token->u.op.opline_num = catch_op_number; } /* }}} */ void zend_do_end_catch(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); CG(active_op_array)->opcodes[try_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_throw(const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_THROW; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); } /* }}} */ ZEND_API void function_add_ref(zend_function *function) /* {{{ */ { if (function->type == ZEND_USER_FUNCTION) { zend_op_array *op_array = &function->op_array; (*op_array->refcount)++; if (op_array->static_variables) { HashTable *static_variables = op_array->static_variables; zval *tmp_zval; ALLOC_HASHTABLE(op_array->static_variables); zend_hash_init(op_array->static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(op_array->static_variables, static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_zval, sizeof(zval *)); } op_array->run_time_cache = NULL; } } /* }}} */ static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */ { zend_function *function; if (!ce->parent) { return; } /* You cannot change create_object */ ce->create_object = ce->parent->create_object; /* Inherit special functions if needed */ if (!ce->get_iterator) { ce->get_iterator = ce->parent->get_iterator; } if (!ce->iterator_funcs.funcs) { ce->iterator_funcs.funcs = ce->parent->iterator_funcs.funcs; } if (!ce->__get) { ce->__get = ce->parent->__get; } if (!ce->__set) { ce->__set = ce->parent->__set; } if (!ce->__unset) { ce->__unset = ce->parent->__unset; } if (!ce->__isset) { ce->__isset = ce->parent->__isset; } if (!ce->__call) { ce->__call = ce->parent->__call; } if (!ce->__callstatic) { ce->__callstatic = ce->parent->__callstatic; } if (!ce->__tostring) { ce->__tostring = ce->parent->__tostring; } if (!ce->clone) { ce->clone = ce->parent->clone; } if(!ce->serialize) { ce->serialize = ce->parent->serialize; } if(!ce->unserialize) { ce->unserialize = ce->parent->unserialize; } if (!ce->destructor) { ce->destructor = ce->parent->destructor; } if (ce->constructor) { if (ce->parent->constructor && ce->parent->constructor->common.fn_flags & ZEND_ACC_FINAL) { zend_error(E_ERROR, "Cannot override final %s::%s() with %s::%s()", ce->parent->name, ce->parent->constructor->common.function_name, ce->name, ce->constructor->common.function_name ); } return; } if (zend_hash_find(&ce->parent->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), (void **)&function)==SUCCESS) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), function, sizeof(zend_function), NULL); function_add_ref(function); } else { /* Don't inherit the old style constructor if we already have the new style constructor */ char *lc_class_name; char *lc_parent_class_name; lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); if (!zend_hash_exists(&ce->function_table, lc_class_name, ce->name_length+1)) { lc_parent_class_name = zend_str_tolower_dup(ce->parent->name, ce->parent->name_length); if (!zend_hash_exists(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1) && zend_hash_find(&ce->parent->function_table, lc_parent_class_name, ce->parent->name_length+1, (void **)&function)==SUCCESS) { if (function->common.fn_flags & ZEND_ACC_CTOR) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1, function, sizeof(zend_function), NULL); function_add_ref(function); } } efree(lc_parent_class_name); } efree(lc_class_name); } ce->constructor = ce->parent->constructor; } /* }}} */ char *zend_visibility_string(zend_uint fn_flags) /* {{{ */ { if (fn_flags & ZEND_ACC_PRIVATE) { return "private"; } if (fn_flags & ZEND_ACC_PROTECTED) { return "protected"; } if (fn_flags & ZEND_ACC_PUBLIC) { return "public"; } return ""; } /* }}} */ static void do_inherit_method(zend_function *function) /* {{{ */ { /* The class entry of the derived function intentionally remains the same * as that of the parent class. That allows us to know in which context * we're running, and handle private method calls properly. */ function_add_ref(function); } /* }}} */ static zend_bool zend_do_perform_implementation_check(const zend_function *fe, const zend_function *proto TSRMLS_DC) /* {{{ */ { zend_uint i; /* If it's a user function then arg_info == NULL means we don't have any parameters but * we still need to do the arg number checks. We are only willing to ignore this for internal * functions because extensions don't always define arg_info. */ if (!proto || (!proto->common.arg_info && proto->common.type != ZEND_USER_FUNCTION)) { return 1; } /* Checks for constructors only if they are declared in an interface, * or explicitly marked as abstract */ if ((fe->common.fn_flags & ZEND_ACC_CTOR) && ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)) { return 1; } /* check number of arguments */ if (proto->common.required_num_args < fe->common.required_num_args || proto->common.num_args > fe->common.num_args) { return 0; } if (fe->common.type != ZEND_USER_FUNCTION && (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) != 0 && (fe->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) == 0) { return 0; } /* by-ref constraints on return values are covariant */ if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) { return 0; } for (i=0; i < proto->common.num_args; i++) { if (ZEND_LOG_XOR(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)) { /* Only one has a type hint and the other one doesn't */ return 0; } if (fe->common.arg_info[i].class_name && strcasecmp(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)!=0) { const char *colon; if (fe->common.type != ZEND_USER_FUNCTION) { return 0; } else if (strchr(proto->common.arg_info[i].class_name, '\\') != NULL || (colon = zend_memrchr(fe->common.arg_info[i].class_name, '\\', fe->common.arg_info[i].class_name_len)) == NULL || strcasecmp(colon+1, proto->common.arg_info[i].class_name) != 0) { zend_class_entry **fe_ce, **proto_ce; int found, found2; found = zend_lookup_class(fe->common.arg_info[i].class_name, fe->common.arg_info[i].class_name_len, &fe_ce TSRMLS_CC); found2 = zend_lookup_class(proto->common.arg_info[i].class_name, proto->common.arg_info[i].class_name_len, &proto_ce TSRMLS_CC); /* Check for class alias */ if (found != SUCCESS || found2 != SUCCESS || (*fe_ce)->type == ZEND_INTERNAL_CLASS || (*proto_ce)->type == ZEND_INTERNAL_CLASS || *fe_ce != *proto_ce) { return 0; } } } if (fe->common.arg_info[i].type_hint != proto->common.arg_info[i].type_hint) { /* Incompatible type hint */ return 0; } /* by-ref constraints on arguments are invariant */ if (fe->common.arg_info[i].pass_by_reference != proto->common.arg_info[i].pass_by_reference) { return 0; } } if (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) { for (i=proto->common.num_args; i < fe->common.num_args; i++) { if (!fe->common.arg_info[i].pass_by_reference) { return 0; } } } return 1; } /* }}} */ #define REALLOC_BUF_IF_EXCEED(buf, offset, length, size) \ if (UNEXPECTED(offset - buf + size >= length)) { \ length += size + 1; \ buf = erealloc(buf, length); \ } static char * zend_get_function_declaration(zend_function *fptr TSRMLS_DC) /* {{{ */ { char *offset, *buf; zend_uint length = 1024; offset = buf = (char *)emalloc(length * sizeof(char)); if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { *(offset++) = '&'; *(offset++) = ' '; } if (fptr->common.scope) { memcpy(offset, fptr->common.scope->name, fptr->common.scope->name_length); offset += fptr->common.scope->name_length; *(offset++) = ':'; *(offset++) = ':'; } { size_t name_len = strlen(fptr->common.function_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, name_len); memcpy(offset, fptr->common.function_name, name_len); offset += name_len; } *(offset++) = '('; if (fptr->common.arg_info) { zend_uint i, required; zend_arg_info *arg_info = fptr->common.arg_info; required = fptr->common.required_num_args; for (i = 0; i < fptr->common.num_args;) { if (arg_info->class_name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->class_name_len); memcpy(offset, arg_info->class_name, arg_info->class_name_len); offset += arg_info->class_name_len; *(offset++) = ' '; } else if (arg_info->type_hint) { zend_uint type_name_len; char *type_name = zend_get_type_by_const(arg_info->type_hint); type_name_len = strlen(type_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, type_name_len); memcpy(offset, type_name, type_name_len); offset += type_name_len; *(offset++) = ' '; } if (arg_info->pass_by_reference) { *(offset++) = '&'; } *(offset++) = '$'; if (arg_info->name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->name_len); memcpy(offset, arg_info->name, arg_info->name_len); offset += arg_info->name_len; } else { zend_uint idx = i; memcpy(offset, "param", 5); offset += 5; do { *(offset++) = (char) (idx % 10) + '0'; idx /= 10; } while (idx > 0); } if (i >= required) { *(offset++) = ' '; *(offset++) = '='; *(offset++) = ' '; if (fptr->type == ZEND_USER_FUNCTION) { zend_op *precv = NULL; { zend_uint idx = i; zend_op *op = ((zend_op_array *)fptr)->opcodes; zend_op *end = op + ((zend_op_array *)fptr)->last; ++idx; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT) && op->op1.num == (long)idx) { precv = op; } ++op; } } if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) { zval *zv, zv_copy; int use_copy; ALLOC_ZVAL(zv); *zv = *precv->op2.zv; zval_copy_ctor(zv); INIT_PZVAL(zv); zval_update_constant_ex(&zv, (void*)1, fptr->common.scope TSRMLS_CC); if (Z_TYPE_P(zv) == IS_BOOL) { if (Z_LVAL_P(zv)) { memcpy(offset, "true", 4); offset += 4; } else { memcpy(offset, "false", 5); offset += 5; } } else if (Z_TYPE_P(zv) == IS_NULL) { memcpy(offset, "NULL", 4); offset += 4; } else if (Z_TYPE_P(zv) == IS_STRING) { *(offset++) = '\''; REALLOC_BUF_IF_EXCEED(buf, offset, length, MIN(Z_STRLEN_P(zv), 10)); memcpy(offset, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 10)); offset += MIN(Z_STRLEN_P(zv), 10); if (Z_STRLEN_P(zv) > 10) { *(offset++) = '.'; *(offset++) = '.'; *(offset++) = '.'; } *(offset++) = '\''; } else if (Z_TYPE_P(zv) == IS_ARRAY) { memcpy(offset, "Array", 5); offset += 5; } else { zend_make_printable_zval(zv, &zv_copy, &use_copy); REALLOC_BUF_IF_EXCEED(buf, offset, length, Z_STRLEN(zv_copy)); memcpy(offset, Z_STRVAL(zv_copy), Z_STRLEN(zv_copy)); offset += Z_STRLEN(zv_copy); if (use_copy) { zval_dtor(&zv_copy); } } zval_ptr_dtor(&zv); } } else { memcpy(offset, "NULL", 4); offset += 4; } } if (++i < fptr->common.num_args) { *(offset++) = ','; *(offset++) = ' '; } arg_info++; REALLOC_BUF_IF_EXCEED(buf, offset, length, 32); } } *(offset++) = ')'; *offset = '\0'; return buf; } /* }}} */ static void do_inheritance_check_on_method(zend_function *child, zend_function *parent TSRMLS_DC) /* {{{ */ { zend_uint child_flags; zend_uint parent_flags = parent->common.fn_flags; if (parent->common.fn_flags & ZEND_ACC_ABSTRACT && parent->common.scope != (child->common.prototype ? child->common.prototype->common.scope : child->common.scope) && child->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_IMPLEMENTED_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Can't inherit abstract function %s::%s() (previously declared abstract in %s)", parent->common.scope->name, child->common.function_name, child->common.prototype ? child->common.prototype->common.scope->name : child->common.scope->name); } if (parent_flags & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot override final method %s::%s()", ZEND_FN_SCOPE_NAME(parent), child->common.function_name); } child_flags = child->common.fn_flags; /* You cannot change from static to non static and vice versa. */ if ((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC)) { if (child->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot make non static method %s::%s() static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } else { zend_error(E_COMPILE_ERROR, "Cannot make static method %s::%s() non static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } } /* Disallow making an inherited method abstract. */ if ((child_flags & ZEND_ACC_ABSTRACT) && !(parent_flags & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Cannot make non abstract method %s::%s() abstract in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } if (parent_flags & ZEND_ACC_CHANGED) { child->common.fn_flags |= ZEND_ACC_CHANGED; } else { /* Prevent derived classes from restricting access that was available in parent classes */ if ((child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::%s() must be %s (as in class %s)%s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if (((child_flags & ZEND_ACC_PPP_MASK) < (parent_flags & ZEND_ACC_PPP_MASK)) && ((parent_flags & ZEND_ACC_PPP_MASK) & ZEND_ACC_PRIVATE)) { child->common.fn_flags |= ZEND_ACC_CHANGED; } } if (parent_flags & ZEND_ACC_PRIVATE) { child->common.prototype = NULL; } else if (parent_flags & ZEND_ACC_ABSTRACT) { child->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; child->common.prototype = parent; } else if (!(parent->common.fn_flags & ZEND_ACC_CTOR) || (parent->common.prototype && (parent->common.prototype->common.scope->ce_flags & ZEND_ACC_INTERFACE))) { /* ctors only have a prototype if it comes from an interface */ child->common.prototype = parent->common.prototype ? parent->common.prototype : parent; } if (child->common.prototype && (child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { if (!zend_do_perform_implementation_check(child, child->common.prototype TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s::%s() must be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_get_function_declaration(child->common.prototype TSRMLS_CC)); } } else if (EG(error_reporting) & E_STRICT || EG(user_error_handler)) { /* Check E_STRICT (or custom error handler) before the check so that we save some time */ if (!zend_do_perform_implementation_check(child, parent TSRMLS_CC)) { char *method_prototype = zend_get_function_declaration(child->common.prototype TSRMLS_CC); zend_error(E_STRICT, "Declaration of %s::%s() should be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, method_prototype); efree(method_prototype); } } } /* }}} */ static zend_bool do_inherit_method_check(HashTable *child_function_table, zend_function *parent, const zend_hash_key *hash_key, zend_class_entry *child_ce) /* {{{ */ { zend_uint parent_flags = parent->common.fn_flags; zend_function *child; TSRMLS_FETCH(); if (zend_hash_quick_find(child_function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child)==FAILURE) { if (parent_flags & (ZEND_ACC_ABSTRACT)) { child_ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } return 1; /* method doesn't exist in child, copy from parent */ } do_inheritance_check_on_method(child, parent TSRMLS_CC); return 0; } /* }}} */ static zend_bool do_inherit_property_access_check(HashTable *target_ht, zend_property_info *parent_info, const zend_hash_key *hash_key, zend_class_entry *ce) /* {{{ */ { zend_property_info *child_info; zend_class_entry *parent_ce = ce->parent; if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW)) { if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { child_info->flags |= ZEND_ACC_CHANGED; } else { zend_hash_quick_update(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, parent_info, sizeof(zend_property_info), (void **) &child_info); if(ce->type & ZEND_INTERNAL_CLASS) { zend_duplicate_property_info_internal(child_info); } else { zend_duplicate_property_info(child_info); } child_info->flags &= ~ZEND_ACC_PRIVATE; /* it's not private anymore */ child_info->flags |= ZEND_ACC_SHADOW; /* but it's a shadow of private */ } return 0; /* don't copy access information to child */ } if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { if ((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s", (parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", parent_ce->name, hash_key->arKey, (child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ce->name, hash_key->arKey); } if(parent_info->flags & ZEND_ACC_CHANGED) { child_info->flags |= ZEND_ACC_CHANGED; } if ((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ce->name, hash_key->arKey, zend_visibility_string(parent_info->flags), parent_ce->name, (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if ((child_info->flags & ZEND_ACC_STATIC) == 0) { Z_DELREF_P(ce->default_properties_table[parent_info->offset]); ce->default_properties_table[parent_info->offset] = ce->default_properties_table[child_info->offset]; ce->default_properties_table[child_info->offset] = NULL; child_info->offset = parent_info->offset; } return 0; /* Don't copy from parent */ } else { return 1; /* Copy from parent */ } } /* }}} */ static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce TSRMLS_CC) == FAILURE) { zend_error(E_CORE_ERROR, "Class %s could not implement interface %s", ce->name, iface->name); } if (ce == iface) { zend_error(E_ERROR, "Interface %s cannot implement itself", ce->name); } } /* }}} */ ZEND_API void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface TSRMLS_DC) /* {{{ */ { /* expects interface to be contained in ce's interface list already */ zend_uint i, ce_num, if_num = iface->num_interfaces; zend_class_entry *entry; if (if_num==0) { return; } ce_num = ce->num_interfaces; if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } /* Inherit the interfaces, only if they're not already inherited by the class */ while (if_num--) { entry = iface->interfaces[if_num]; for (i = 0; i < ce_num; i++) { if (ce->interfaces[i] == entry) { break; } } if (i == ce_num) { ce->interfaces[ce->num_interfaces++] = entry; } } /* and now call the implementing handlers */ while (ce_num < ce->num_interfaces) { do_implement_interface(ce, ce->interfaces[ce_num++] TSRMLS_CC); } } /* }}} */ #ifdef ZTS static void zval_internal_ctor(zval **p) /* {{{ */ { zval *orig_ptr = *p; ALLOC_ZVAL(*p); MAKE_COPY_ZVAL(&orig_ptr, *p); } /* }}} */ # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) (((parent_ce)->type != (ce)->type) ? zval_internal_ctor : zval_add_ref)) #else # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) zval_add_ref) #endif ZEND_API void zend_do_inheritance(zend_class_entry *ce, zend_class_entry *parent_ce TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; if ((ce->ce_flags & ZEND_ACC_INTERFACE) && !(parent_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ce->name, parent_ce->name); } if (parent_ce->ce_flags & ZEND_ACC_FINAL_CLASS) { zend_error(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ce->name, parent_ce->name); } ce->parent = parent_ce; /* Copy serialize/unserialize callbacks */ if (!ce->serialize) { ce->serialize = parent_ce->serialize; } if (!ce->unserialize) { ce->unserialize = parent_ce->unserialize; } /* Inherit interfaces */ zend_do_inherit_interfaces(ce, parent_ce TSRMLS_CC); /* Inherit properties */ if (parent_ce->default_properties_count) { int i = ce->default_properties_count + parent_ce->default_properties_count; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_properties_count) { while (i-- > parent_ce->default_properties_count) { ce->default_properties_table[i] = ce->default_properties_table[i - parent_ce->default_properties_count]; } } for (i = 0; i < parent_ce->default_properties_count; i++) { ce->default_properties_table[i] = parent_ce->default_properties_table[i]; if (ce->default_properties_table[i]) { #ifdef ZTS if (parent_ce->type != ce->type) { zval *p; ALLOC_ZVAL(p); MAKE_COPY_ZVAL(&ce->default_properties_table[i], p); ce->default_properties_table[i] = p; } else { Z_ADDREF_P(ce->default_properties_table[i]); } #else Z_ADDREF_P(ce->default_properties_table[i]); #endif } } ce->default_properties_count += parent_ce->default_properties_count; } if (parent_ce->type != ce->type) { /* User class extends internal class */ zend_update_class_constants(parent_ce TSRMLS_CC); if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = erealloc(ce->default_static_members_table, sizeof(void*) * i); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&CE_STATIC_MEMBERS(parent_ce)[i]); ce->default_static_members_table[i] = CE_STATIC_MEMBERS(parent_ce)[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; ce->static_members_table = ce->default_static_members_table; } } else { if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&parent_ce->default_static_members_table[i]); ce->default_static_members_table[i] = parent_ce->default_static_members_table[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } } for (zend_hash_internal_pointer_reset(&ce->properties_info); zend_hash_get_current_data(&ce->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->properties_info)) { if (property_info->ce == ce) { if (property_info->flags & ZEND_ACC_STATIC) { property_info->offset += parent_ce->default_static_members_count; } else { property_info->offset += parent_ce->default_properties_count; } } } zend_hash_merge_ex(&ce->properties_info, &parent_ce->properties_info, (copy_ctor_func_t) (ce->type & ZEND_INTERNAL_CLASS ? zend_duplicate_property_info_internal : zend_duplicate_property_info), sizeof(zend_property_info), (merge_checker_func_t) do_inherit_property_access_check, ce); zend_hash_merge(&ce->constants_table, &parent_ce->constants_table, zval_property_ctor(parent_ce, ce), NULL, sizeof(zval *), 0); zend_hash_merge_ex(&ce->function_table, &parent_ce->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_inherit_parent_constructor(ce); if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS && ce->type == ZEND_INTERNAL_CLASS) { ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } else if (!(ce->ce_flags & ZEND_ACC_IMPLEMENT_INTERFACES) && !(ce->ce_flags & ZEND_ACC_IMPLEMENT_TRAITS)) { /* The verification will be done in runtime by ZEND_VERIFY_ABSTRACT_CLASS */ zend_verify_abstract_class(ce TSRMLS_CC); } ce->ce_flags |= parent_ce->ce_flags & ZEND_HAS_STATIC_IN_METHODS; } /* }}} */ static zend_bool do_inherit_constant_check(HashTable *child_constants_table, const zval **parent_constant, const zend_hash_key *hash_key, const zend_class_entry *iface) /* {{{ */ { zval **old_constant; if (zend_hash_quick_find(child_constants_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**)&old_constant) == SUCCESS) { if (*old_constant != *parent_constant) { zend_error(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", hash_key->arKey, iface->name); } return 0; } return 1; } /* }}} */ static int do_interface_constant_check(zval **val TSRMLS_DC, int num_args, va_list args, const zend_hash_key *key) /* {{{ */ { zend_class_entry **iface = va_arg(args, zend_class_entry**); do_inherit_constant_check(&(*iface)->constants_table, (const zval **) val, key, *iface); return ZEND_HASH_APPLY_KEEP; } /* }}} */ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_iface_num = ce->num_interfaces; zend_uint parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0; for (i = 0; i < ce->num_interfaces; i++) { if (ce->interfaces[i] == NULL) { memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i)); i--; } else if (ce->interfaces[i] == iface) { if (i < parent_iface_num) { ignore = 1; } else { zend_error(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ce->name, iface->name); } } } if (ignore) { /* Check for attempt to redeclare interface constants */ zend_hash_apply_with_arguments(&ce->constants_table TSRMLS_CC, (apply_func_args_t) do_interface_constant_check, 1, &iface); } else { if (ce->num_interfaces >= current_iface_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } } ce->interfaces[ce->num_interfaces++] = iface; zend_hash_merge_ex(&ce->constants_table, &iface->constants_table, (copy_ctor_func_t) zval_add_ref, sizeof(zval *), (merge_checker_func_t) do_inherit_constant_check, iface); zend_hash_merge_ex(&ce->function_table, &iface->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_implement_interface(ce, iface TSRMLS_CC); zend_do_inherit_interfaces(ce, iface TSRMLS_CC); } } /* }}} */ ZEND_API void zend_do_implement_trait(zend_class_entry *ce, zend_class_entry *trait TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_trait_num = ce->num_traits; zend_uint parent_trait_num = ce->parent ? ce->parent->num_traits : 0; for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == NULL) { memmove(ce->traits + i, ce->traits + i + 1, sizeof(zend_class_entry*) * (--ce->num_traits - i)); i--; } else if (ce->traits[i] == trait) { if (i < parent_trait_num) { ignore = 1; } } } if (!ignore) { if (ce->num_traits >= current_trait_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->traits = (zend_class_entry **) realloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } else { ce->traits = (zend_class_entry **) erealloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } } ce->traits[ce->num_traits++] = trait; } } /* }}} */ static int zend_traits_merge_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { size_t current; size_t i; size_t count; HashTable* resulting_table; HashTable** function_tables; zend_class_entry *ce; size_t collision = 0; size_t abstract_solved = 0; zend_function* other_trait_fn; current = va_arg(args, size_t); /* index of current trait */ count = va_arg(args, size_t); resulting_table = va_arg(args, HashTable*); function_tables = va_arg(args, HashTable**); ce = va_arg(args, zend_class_entry*); for (i = 0; i < count; i++) { if (i == current) { continue; /* just skip this, cause its the table this function is applied on */ } if (zend_hash_quick_find(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&other_trait_fn) == SUCCESS) { /* if it is an abstract method, there is no collision */ if (other_trait_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible */ do_inheritance_check_on_method(fn, other_trait_fn TSRMLS_CC); /* we can savely free and remove it from other table */ zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } else { /* if it is not an abstract method, there is still no collision */ /* if fn is an abstract method */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible */ do_inheritance_check_on_method(other_trait_fn, fn TSRMLS_CC); /* just mark as solved, will be added if its own trait is processed */ abstract_solved = 1; } else { /* but else, we have a collision of non-abstract methods */ collision++; zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } } } if (collision) { zend_function* class_fn; /* make sure method is not already overridden in class */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&class_fn) == FAILURE || class_fn->common.scope != ce) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because there are collisions with other trait methods on %s", fn->common.function_name, ce->name); } zend_function_dtor(fn); } else if (abstract_solved) { zend_function_dtor(fn); } else { /* Add it to result function table */ if (zend_hash_quick_add(resulting_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, fn, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating resulting trait method table", fn->common.function_name); } } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ /* {{{ Originates from php_runkit_function_copy_ctor Duplicate structures in an op_array where necessary to make an outright duplicate */ static void zend_traits_duplicate_function(zend_function *fe, zend_class_entry *target_ce, char *newname TSRMLS_DC) { zend_literal *literals_copy; zend_compiled_variable *dupvars; zend_op *opcode_copy; zval class_name_zv; int class_name_literal; int i; int number_of_literals; if (fe->op_array.static_variables) { HashTable *tmpHash; ALLOC_HASHTABLE(tmpHash); zend_hash_init(tmpHash, zend_hash_num_elements(fe->op_array.static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_apply_with_arguments(fe->op_array.static_variables TSRMLS_CC, (apply_func_args_t)zval_copy_static_var, 1, tmpHash); fe->op_array.static_variables = tmpHash; } number_of_literals = fe->op_array.last_literal; literals_copy = (zend_literal*)emalloc(number_of_literals * sizeof(zend_literal)); for (i = 0; i < number_of_literals; i++) { literals_copy[i] = fe->op_array.literals[i]; zval_copy_ctor(&literals_copy[i].constant); } fe->op_array.literals = literals_copy; fe->op_array.refcount = emalloc(sizeof(zend_uint)); *(fe->op_array.refcount) = 1; if (fe->op_array.vars) { i = fe->op_array.last_var; dupvars = safe_emalloc(fe->op_array.last_var, sizeof(zend_compiled_variable), 0); while (i > 0) { i--; dupvars[i].name = estrndup(fe->op_array.vars[i].name, fe->op_array.vars[i].name_len); dupvars[i].name_len = fe->op_array.vars[i].name_len; dupvars[i].hash_value = fe->op_array.vars[i].hash_value; } fe->op_array.vars = dupvars; } else { fe->op_array.vars = NULL; } opcode_copy = safe_emalloc(sizeof(zend_op), fe->op_array.last, 0); for(i = 0; i < fe->op_array.last; i++) { opcode_copy[i] = fe->op_array.opcodes[i]; if (opcode_copy[i].op1_type != IS_CONST) { if (opcode_copy[i].op1.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op1.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op1.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op1.jmp_addr - fe->op_array.opcodes); } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op1.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op1.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op1.zv = &fe->op_array.literals[class_name_literal].constant; } } if (opcode_copy[i].op2_type != IS_CONST) { if (opcode_copy[i].op2.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op2.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op2.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op2.jmp_addr - fe->op_array.opcodes); } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op2.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op2.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op2.zv = &fe->op_array.literals[class_name_literal].constant; } } } fe->op_array.opcodes = opcode_copy; fe->op_array.function_name = newname; /* was setting it to fe which does not work since fe is stack allocated and not a stable address */ /* fe->op_array.prototype = fe->op_array.prototype; */ if (fe->op_array.arg_info) { zend_arg_info *tmpArginfo; tmpArginfo = safe_emalloc(sizeof(zend_arg_info), fe->op_array.num_args, 0); for(i = 0; i < fe->op_array.num_args; i++) { tmpArginfo[i] = fe->op_array.arg_info[i]; tmpArginfo[i].name = estrndup(tmpArginfo[i].name, tmpArginfo[i].name_len); if (tmpArginfo[i].class_name) { tmpArginfo[i].class_name = estrndup(tmpArginfo[i].class_name, tmpArginfo[i].class_name_len); } } fe->op_array.arg_info = tmpArginfo; } fe->op_array.doc_comment = estrndup(fe->op_array.doc_comment, fe->op_array.doc_comment_len); fe->op_array.try_catch_array = (zend_try_catch_element*)estrndup((char*)fe->op_array.try_catch_array, sizeof(zend_try_catch_element) * fe->op_array.last_try_catch); fe->op_array.brk_cont_array = (zend_brk_cont_element*)estrndup((char*)fe->op_array.brk_cont_array, sizeof(zend_brk_cont_element) * fe->op_array.last_brk_cont); } /* }}} */ static void zend_add_magic_methods(zend_class_entry* ce, const char* mname, uint mname_len, zend_function* fe TSRMLS_DC) { if ( !strncmp(mname, ZEND_CLONE_FUNC_NAME, mname_len)) { ce->clone = fe; fe->common.fn_flags |= ZEND_ACC_CLONE; } else if (!strncmp(mname, ZEND_CONSTRUCTOR_FUNC_NAME, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } else if (!strncmp(mname, ZEND_DESTRUCTOR_FUNC_NAME, mname_len)) { ce->destructor = fe; fe->common.fn_flags |= ZEND_ACC_DTOR; } else if (!strncmp(mname, ZEND_GET_FUNC_NAME, mname_len)) ce->__get = fe; else if (!strncmp(mname, ZEND_SET_FUNC_NAME, mname_len)) ce->__set = fe; else if (!strncmp(mname, ZEND_CALL_FUNC_NAME, mname_len)) ce->__call = fe; else if (!strncmp(mname, ZEND_UNSET_FUNC_NAME, mname_len)) ce->__unset = fe; else if (!strncmp(mname, ZEND_ISSET_FUNC_NAME, mname_len)) ce->__isset = fe; else if (!strncmp(mname, ZEND_CALLSTATIC_FUNC_NAME, mname_len)) ce->__callstatic= fe; else if (!strncmp(mname, ZEND_TOSTRING_FUNC_NAME, mname_len)) ce->__tostring = fe; else if (ce->name_length + 1 == mname_len) { char *lowercase_name = emalloc(ce->name_length + 1); zend_str_tolower_copy(lowercase_name, ce->name, ce->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, ce->name_length + 1, 1 TSRMLS_CC); if (!memcmp(mname, lowercase_name, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } str_efree(lowercase_name); } } static int zend_traits_merge_functions_to_class(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zend_class_entry *ce = va_arg(args, zend_class_entry*); int add = 0; zend_function* existing_fn; zend_function fn_copy, *fn_copy_p; zend_function* prototype = NULL; /* is used to determine the prototype according to the inheritance chain */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &existing_fn) == FAILURE) { add = 1; /* not found */ } else if (existing_fn->common.scope != ce) { add = 1; /* or inherited from other class or interface */ } if (add) { zend_function* parent_function; if (ce->parent && zend_hash_quick_find(&ce->parent->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &parent_function) != FAILURE) { prototype = parent_function; /* ->common.fn_flags |= ZEND_ACC_ABSTRACT; */ /* we got that method in the parent class, and are going to override it, except, if the trait is just asking to have an abstract method implemented. */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* then we clean up an skip this method */ zend_function_dtor(fn); return ZEND_HASH_APPLY_REMOVE; } } fn->common.scope = ce; fn->common.prototype = prototype; if (prototype && (prototype->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT || prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { fn->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; } else if (fn->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT) { /* remove ZEND_ACC_IMPLEMENTED_ABSTRACT flag, think it shouldn't be copied to class */ fn->common.fn_flags = fn->common.fn_flags - ZEND_ACC_IMPLEMENTED_ABSTRACT; } /* check whether the trait method fullfills the inheritance requirements */ if (prototype) { do_inheritance_check_on_method(fn, prototype TSRMLS_CC); } /* one more thing: make sure we properly implement an abstract method */ if (existing_fn && existing_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { do_inheritance_check_on_method(fn, existing_fn TSRMLS_CC); } /* delete inherited fn if the function to be added is not abstract */ if (existing_fn && existing_fn->common.scope != ce && (fn->common.fn_flags & ZEND_ACC_ABSTRACT) == 0) { /* it is just a reference which was added to the subclass while doing the inheritance, so we can deleted now, and will add the overriding method afterwards. Except, if we try to add an abstract function, then we should not delete the inherited one */ zend_hash_quick_del(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h); } if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (fn->op_array.static_variables) { ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, ce, estrdup(fn->common.function_name) TSRMLS_CC); if (zend_hash_quick_update(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, &fn_copy, sizeof(zend_function), (void**)&fn_copy_p)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating class method table", hash_key->arKey); } zend_add_magic_methods(ce, hash_key->arKey, hash_key->nKeyLength, fn_copy_p TSRMLS_CC); zend_function_dtor(fn); } else { zend_function_dtor(fn); } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ static int zend_traits_copy_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { HashTable* target; zend_class_entry *target_ce; zend_trait_alias** aliases; HashTable* exclude_table; char* lcname; unsigned int fnname_len; zend_function fn_copy; void* dummy; size_t i = 0; target = va_arg(args, HashTable*); target_ce = va_arg(args, zend_class_entry*); aliases = va_arg(args, zend_trait_alias**); exclude_table = va_arg(args, HashTable*); fnname_len = strlen(fn->common.function_name); /* apply aliases which are qualified with a class name, there should not be any ambiguity */ if (aliases) { while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias != NULL && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && aliases[i]->trait_method->mname_len == fnname_len && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(aliases[i]->alias, aliases[i]->alias_len) TSRMLS_CC); /* if it is 0, no modifieres has been changed */ if (aliases[i]->modifiers) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } lcname = zend_str_tolower_dup(aliases[i]->alias, aliases[i]->alias_len); if (zend_hash_add(target, lcname, aliases[i]->alias_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add aliased trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } efree(lcname); } i++; } } lcname = zend_str_tolower_dup(fn->common.function_name, fnname_len); if (exclude_table == NULL || zend_hash_find(exclude_table, lcname, fnname_len, &dummy) == FAILURE) { /* is not in hashtable, thus, function is not to be excluded */ fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(fn->common.function_name, fnname_len) TSRMLS_CC); /* apply aliases which are not qualified by a class name, or which have not * alias name, just setting visibility */ if (aliases) { i = 0; while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias == NULL && aliases[i]->modifiers != 0 && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && (aliases[i]->trait_method->mname_len == fnname_len) && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } i++; } } if (zend_hash_add(target, lcname, fnname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } } efree(lcname); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* Copies function table entries to target function table with applied aliasing */ static void zend_traits_copy_trait_function_table(HashTable *target, zend_class_entry *target_ce, HashTable *source, zend_trait_alias** aliases, HashTable* exclude_table TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_arguments(source TSRMLS_CC, (apply_func_args_t)zend_traits_copy_functions, 4, target, target_ce, aliases, exclude_table); } /* }}} */ static void zend_traits_init_trait_structures(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i, j = 0; zend_trait_precedence *cur_precedence; zend_trait_method_reference *cur_method_ref; /* resolve class references */ if (ce->trait_precedences) { i = 0; while ((cur_precedence = ce->trait_precedences[i])) { if (cur_precedence->exclude_from_classes) { cur_precedence->trait_method->ce = zend_fetch_class(cur_precedence->trait_method->class_name, cur_precedence->trait_method->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); j = 0; while (cur_precedence->exclude_from_classes[j]) { char* class_name = (char*)cur_precedence->exclude_from_classes[j]; zend_uint name_length = strlen(class_name); cur_precedence->exclude_from_classes[j] = zend_fetch_class(class_name, name_length, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); efree(class_name); j++; } } i++; } } if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { if (ce->trait_aliases[i]->trait_method->class_name) { cur_method_ref = ce->trait_aliases[i]->trait_method; cur_method_ref->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); } i++; } } } /* }}} */ static void zend_traits_compile_exclude_table(HashTable* exclude_table, zend_trait_precedence **precedences, zend_class_entry *trait) /* {{{ */ { size_t i = 0, j; if (!precedences) { return; } while (precedences[i]) { if (precedences[i]->exclude_from_classes) { j = 0; while (precedences[i]->exclude_from_classes[j]) { if (precedences[i]->exclude_from_classes[j] == trait) { zend_uint lcname_len = precedences[i]->trait_method->mname_len; char *lcname = zend_str_tolower_dup(precedences[i]->trait_method->method_name, lcname_len); if (zend_hash_add(exclude_table, lcname, lcname_len, NULL, 0, NULL) == FAILURE) { efree(lcname); zend_error(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", precedences[i]->trait_method->method_name, trait->name); } efree(lcname); } ++j; } } ++i; } } /* }}} */ static void zend_do_traits_method_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { HashTable** function_tables; HashTable* resulting_table; HashTable exclude_table; size_t i; /* prepare copies of trait function tables for combination */ function_tables = malloc(sizeof(HashTable*) * ce->num_traits); resulting_table = (HashTable *) malloc(sizeof(HashTable)); /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(resulting_table, 10, NULL, NULL, 1, 0); for (i = 0; i < ce->num_traits; i++) { function_tables[i] = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(function_tables[i], ce->traits[i]->function_table.nNumOfElements, NULL, NULL, 1, 0); if (ce->trait_precedences) { /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(&exclude_table, 2, NULL, NULL, 0, 0); zend_traits_compile_exclude_table(&exclude_table, ce->trait_precedences, ce->traits[i]); /* copies functions, applies defined aliasing, and excludes unused trait methods */ zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, &exclude_table TSRMLS_CC); zend_hash_graceful_destroy(&exclude_table); } else { zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, NULL TSRMLS_CC); } } /* now merge trait methods */ for (i = 0; i < ce->num_traits; i++) { zend_hash_apply_with_arguments(function_tables[i] TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions, 5, i, ce->num_traits, resulting_table, function_tables, ce); } /* Now the resulting_table contains all trait methods we would have to * add to the class in the following step the methods are inserted into the method table * if there is already a method with the same name it is replaced iff ce != fn.scope * --> all inherited methods are overridden, methods defined in the class are left untouched */ zend_hash_apply_with_arguments(resulting_table TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions_to_class, 1, ce); /* free temporary function tables */ for (i = 0; i < ce->num_traits; i++) { /* zend_hash_destroy(function_tables[i]); */ zend_hash_graceful_destroy(function_tables[i]); free(function_tables[i]); } free(function_tables); /* free temporary resulting table */ /* zend_hash_destroy(resulting_table); */ zend_hash_graceful_destroy(resulting_table); free(resulting_table); } /* }}} */ static zend_class_entry* find_first_definition(zend_class_entry *ce, size_t current_trait, const char* prop_name, int prop_name_length, ulong prop_hash, zend_class_entry *coliding_ce) /* {{{ */ { size_t i; zend_property_info *coliding_prop; for (i = 0; (i < current_trait) && (i < ce->num_traits); i++) { if (zend_hash_quick_find(&ce->traits[i]->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS) { return ce->traits[i]; } } return coliding_ce; } /* }}} */ static void zend_do_traits_property_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i; zend_property_info *property_info; zend_property_info *coliding_prop; zval compare_result; const char* prop_name; int prop_name_length; ulong prop_hash; const char* class_name_unused; zend_bool prop_found; zend_bool not_compatible; zval* prop_value; /* In the following steps the properties are inserted into the property table * for that, a very strict approach is applied: * - check for compatibility, if not compatible with any property in class -> fatal * - if compatible, then strict notice */ for (i = 0; i < ce->num_traits; i++) { for (zend_hash_internal_pointer_reset(&ce->traits[i]->properties_info); zend_hash_get_current_data(&ce->traits[i]->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->traits[i]->properties_info)) { /* first get the unmangeld name if necessary, * then check whether the property is already there */ if ((property_info->flags & ZEND_ACC_PPP_MASK) == ZEND_ACC_PUBLIC) { prop_hash = property_info->h; prop_name = property_info->name; prop_name_length = property_info->name_length; prop_found = zend_hash_quick_find(&ce->properties_info, property_info->name, property_info->name_length+1, property_info->h, (void **) &coliding_prop) == SUCCESS; } else { /* for private and protected we need to unmangle the names */ zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name_unused, &prop_name); prop_name_length = strlen(prop_name); prop_hash = zend_get_hash_value(prop_name, prop_name_length + 1); prop_found = zend_hash_quick_find(&ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS; } /* next: check for conflicts with current class */ if (prop_found) { if (coliding_prop->flags & ZEND_ACC_SHADOW) { /* this one is inherited, lets look it up in its own class */ zend_hash_quick_find(&coliding_prop->ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop); } if ((coliding_prop->flags & ZEND_ACC_PPP_MASK) == (property_info->flags & ZEND_ACC_PPP_MASK)) { /* flags are identical, now the value needs to be checked */ if (property_info->flags & ZEND_ACC_STATIC) { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_static_members_table[coliding_prop->offset], ce->traits[i]->default_static_members_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } else { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_properties_table[coliding_prop->offset], ce->traits[i]->default_properties_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } } else { /* the flags are not identical, thus, we assume properties are not compatible */ not_compatible = 1; } if (not_compatible) { zend_error(E_COMPILE_ERROR, "%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } else { zend_error(E_STRICT, "%s and %s define the same property ($%s) in the composition of %s. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } } /* property not found, so lets add it */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); zend_declare_property_ex(ce, prop_name, prop_name_length, prop_value, property_info->flags, property_info->doc_comment, property_info->doc_comment_len TSRMLS_CC); } } } /* }}} */ ZEND_API void zend_do_bind_traits(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { if (ce->num_traits <= 0) { return; } /* complete initialization of trait strutures in ce */ zend_traits_init_trait_structures(ce TSRMLS_CC); /* first care about all methods to be flattened into the class */ zend_do_traits_method_binding(ce TSRMLS_CC); /* then flatten the properties into it, to, mostly to notfiy developer about problems */ zend_do_traits_property_binding(ce TSRMLS_CC); /* verify that all abstract methods from traits have been implemented */ zend_verify_abstract_class(ce TSRMLS_CC); /* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */ if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { ce->ce_flags -= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } } /* }}} */ ZEND_API int do_bind_function(const zend_op_array *op_array, zend_op *opline, HashTable *function_table, zend_bool compile_time) /* {{{ */ { zend_function *function; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } zend_hash_quick_find(function_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void *) &function); if (zend_hash_quick_add(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), function, sizeof(zend_function), NULL)==FAILURE) { int error_level = compile_time ? E_COMPILE_ERROR : E_ERROR; zend_function *old_function; if (zend_hash_quick_find(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), (void *) &old_function)==SUCCESS && old_function->type == ZEND_USER_FUNCTION && old_function->op_array.last > 0) { zend_error(error_level, "Cannot redeclare %s() (previously declared in %s:%d)", function->common.function_name, old_function->op_array.filename, old_function->op_array.opcodes[0].lineno); } else { zend_error(error_level, "Cannot redeclare %s()", function->common.function_name); } return FAILURE; } else { (*function->op_array.refcount)++; function->op_array.static_variables = NULL; /* NULL out the unbound function */ return SUCCESS; } } /* }}} */ void zend_add_trait_precedence(znode *precedence_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_precedences, precedence_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_add_trait_alias(znode *alias_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_aliases, alias_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_prepare_reference(znode *result, znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { zend_trait_method_reference *method_ref = emalloc(sizeof(zend_trait_method_reference)); method_ref->ce = NULL; /* REM: There should not be a need for copying, zend_do_begin_class_declaration is also just using that string */ if (class_name) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); method_ref->class_name = Z_STRVAL(class_name->u.constant); method_ref->cname_len = Z_STRLEN(class_name->u.constant); } else { method_ref->class_name = NULL; method_ref->cname_len = 0; } method_ref->method_name = Z_STRVAL(method_name->u.constant); method_ref->mname_len = Z_STRLEN(method_name->u.constant); result->u.op.ptr = method_ref; result->op_type = IS_TMP_VAR; } /* }}} */ void zend_prepare_trait_alias(znode *result, znode *method_reference, znode *modifiers, znode *alias TSRMLS_DC) /* {{{ */ { zend_trait_alias *trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_alias->modifiers = Z_LVAL(modifiers->u.constant); if (Z_LVAL(modifiers->u.constant) == ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot use 'static' as method modifier"); return; } if (alias) { trait_alias->alias = Z_STRVAL(alias->u.constant); trait_alias->alias_len = Z_STRLEN(alias->u.constant); } else { trait_alias->alias = NULL; } trait_alias->function = NULL; result->u.op.ptr = trait_alias; } /* }}} */ void zend_prepare_trait_precedence(znode *result, znode *method_reference, znode *trait_list TSRMLS_DC) /* {{{ */ { zend_trait_precedence *trait_precedence = emalloc(sizeof(zend_trait_precedence)); trait_precedence->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_precedence->exclude_from_classes = (zend_class_entry**) trait_list->u.op.ptr; trait_precedence->function = NULL; result->u.op.ptr = trait_precedence; } /* }}} */ ZEND_API zend_class_entry *do_bind_class(const zend_op_array* op_array, const zend_op *opline, HashTable *class_table, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } if (zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce)==FAILURE) { zend_error(E_COMPILE_ERROR, "Internal Zend error - Missing class information for %s", Z_STRVAL_P(op1)); return NULL; } else { ce = *pce; } ce->refcount++; if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), &ce, sizeof(zend_class_entry *), NULL)==FAILURE) { ce->refcount--; if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return NULL; } else { if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLEMENT_INTERFACES))) { zend_verify_abstract_class(ce TSRMLS_CC); } return ce; } } /* }}} */ ZEND_API zend_class_entry *do_bind_inherited_class(const zend_op_array *op_array, const zend_op *opline, HashTable *class_table, zend_class_entry *parent_ce, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; int found_ce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } found_ce = zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce); if (found_ce == FAILURE) { if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", Z_STRVAL_P(op2)); } return NULL; } else { ce = *pce; } if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ce->name, parent_ce->name); } else if ((parent_ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ce->name, parent_ce->name); } zend_do_inheritance(ce, parent_ce TSRMLS_CC); ce->refcount++; /* Register the derived class */ if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), pce, sizeof(zend_class_entry *), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return ce; } /* }}} */ void zend_do_early_binding(TSRMLS_D) /* {{{ */ { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; HashTable *table; while (opline->opcode == ZEND_TICKS && opline > CG(active_op_array)->opcodes) { opline--; } switch (opline->opcode) { case ZEND_DECLARE_FUNCTION: if (do_bind_function(CG(active_op_array), opline, CG(function_table), 1) == FAILURE) { return; } table = CG(function_table); break; case ZEND_DECLARE_CLASS: if (do_bind_class(CG(active_op_array), opline, CG(class_table), 1 TSRMLS_CC) == NULL) { return; } table = CG(class_table); break; case ZEND_DECLARE_INHERITED_CLASS: { zend_op *fetch_class_opline = opline-1; zval *parent_name; zend_class_entry **pce; parent_name = &CONSTANT(fetch_class_opline->op2.constant); if ((zend_lookup_class(Z_STRVAL_P(parent_name), Z_STRLEN_P(parent_name), &pce TSRMLS_CC) == FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_CLASSES) && ((*pce)->type == ZEND_INTERNAL_CLASS))) { if (CG(compiler_options) & ZEND_COMPILE_DELAYED_BINDING) { zend_uint *opline_num = &CG(active_op_array)->early_binding; while (*opline_num != -1) { opline_num = &CG(active_op_array)->opcodes[*opline_num].result.opline_num; } *opline_num = opline - CG(active_op_array)->opcodes; opline->opcode = ZEND_DECLARE_INHERITED_CLASS_DELAYED; opline->result_type = IS_UNUSED; opline->result.opline_num = -1; } return; } if (do_bind_inherited_class(CG(active_op_array), opline, CG(class_table), *pce, 1 TSRMLS_CC) == NULL) { return; } /* clear unnecessary ZEND_FETCH_CLASS opcode */ zend_del_literal(CG(active_op_array), fetch_class_opline->op2.constant); MAKE_NOP(fetch_class_opline); table = CG(class_table); break; } case ZEND_VERIFY_ABSTRACT_CLASS: case ZEND_ADD_INTERFACE: case ZEND_ADD_TRAIT: case ZEND_BIND_TRAITS: /* We currently don't early-bind classes that implement interfaces */ /* Classes with traits are handled exactly the same, no early-bind here */ return; default: zend_error(E_COMPILE_ERROR, "Invalid binding type"); return; } zend_hash_quick_del(table, Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant)), Z_HASH_P(&CONSTANT(opline->op1.constant))); zend_del_literal(CG(active_op_array), opline->op1.constant); zend_del_literal(CG(active_op_array), opline->op2.constant); MAKE_NOP(opline); } /* }}} */ ZEND_API void zend_do_delayed_early_binding(const zend_op_array *op_array TSRMLS_DC) /* {{{ */ { if (op_array->early_binding != -1) { zend_bool orig_in_compilation = CG(in_compilation); zend_uint opline_num = op_array->early_binding; zend_class_entry **pce; CG(in_compilation) = 1; while (opline_num != -1) { if (zend_lookup_class(Z_STRVAL_P(op_array->opcodes[opline_num-1].op2.zv), Z_STRLEN_P(op_array->opcodes[opline_num-1].op2.zv), &pce TSRMLS_CC) == SUCCESS) { do_bind_inherited_class(op_array, &op_array->opcodes[opline_num], EG(class_table), *pce, 0 TSRMLS_CC); } opline_num = op_array->opcodes[opline_num].result.opline_num; } CG(in_compilation) = orig_in_compilation; } } /* }}} */ void zend_do_boolean_or_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_or_end(znode *result, const znode *expr1, const znode *expr2, znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_boolean_and_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_and_end(znode *result, const znode *expr1, const znode *expr2, const znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_do_while_begin(TSRMLS_D) /* {{{ */ { do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_do_while_end(const znode *do_token, const znode *expr_open_bracket, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ; SET_NODE(opline->op1, expr); opline->op2.opline_num = do_token->u.op.opline_num; SET_UNUSED(opline->op2); do_end_loop(expr_open_bracket->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_brk_cont(zend_uchar op, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->op1.opline_num = CG(context).current_brk_cont; SET_UNUSED(opline->op1); if (expr) { if (expr->op_type != IS_CONST) { zend_error(E_COMPILE_ERROR, "'%s' operator with non-constant operand is no longer supported", op == ZEND_BRK ? "break" : "continue"); } else if (Z_TYPE(expr->u.constant) != IS_LONG || Z_LVAL(expr->u.constant) < 1) { zend_error(E_COMPILE_ERROR, "'%s' operator accepts only positive numbers", op == ZEND_BRK ? "break" : "continue"); } SET_NODE(opline->op2, expr); } else { LITERAL_LONG(opline->op2, 1); opline->op2_type = IS_CONST; } } /* }}} */ void zend_do_switch_cond(const znode *cond TSRMLS_DC) /* {{{ */ { zend_switch_entry switch_entry; switch_entry.cond = *cond; switch_entry.default_case = -1; switch_entry.control_var = -1; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_switch_end(const znode *case_list TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); /* add code to jmp to default case */ if (switch_entry_ptr->default_case != -1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->op1.opline_num = switch_entry_ptr->default_case; } if (case_list->op_type != IS_UNUSED) { /* non-empty switch */ int next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* remember break/continue loop information */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; if (switch_entry_ptr->cond.op_type==IS_VAR || switch_entry_ptr->cond.op_type==IS_TMP_VAR) { /* emit free for the switch condition*/ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry_ptr->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_UNUSED(opline->op2); } if (switch_entry_ptr->cond.op_type == IS_CONST) { zval_dtor(&switch_entry_ptr->cond.u.constant); } zend_stack_del_top(&CG(switch_cond_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_case_before_statement(const znode *case_list, znode *case_token, const znode *case_expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); int next_op_number; zend_switch_entry *switch_entry_ptr; znode result; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); if (switch_entry_ptr->control_var == -1) { switch_entry_ptr->control_var = get_temporary_variable(CG(active_op_array)); } opline->opcode = ZEND_CASE; opline->result.var = switch_entry_ptr->control_var; opline->result_type = IS_TMP_VAR; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_NODE(opline->op2, case_expr); if (opline->op1_type == IS_CONST) { zval_copy_ctor(&CONSTANT(opline->op1.constant)); } GET_NODE(&result, opline->result); next_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, &result); SET_UNUSED(opline->op2); case_token->u.op.opline_num = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_case_after_statement(znode *result, const znode *case_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); result->u.op.opline_num = next_op_number; switch (CG(active_op_array)->opcodes[case_token->u.op.opline_num].opcode) { case ZEND_JMP: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); break; case ZEND_JMPZ: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); break; } } /* }}} */ void zend_do_default_before_statement(const znode *case_list, znode *default_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); default_token->u.op.opline_num = next_op_number; next_op_number = get_next_op_number(CG(active_op_array)); switch_entry_ptr->default_case = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_begin_class_declaration(const znode *class_token, znode *class_name, const znode *parent_class_name TSRMLS_DC) /* {{{ */ { zend_op *opline; int doing_inheritance = 0; zend_class_entry *new_class_entry; char *lcname; int error = 0; zval **ns_name, key; if (CG(active_class_entry)) { zend_error(E_COMPILE_ERROR, "Class declarations may not be nested"); return; } lcname = zend_str_tolower_dup(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); if (!(strcmp(lcname, "self") && strcmp(lcname, "parent"))) { efree(lcname); zend_error(E_COMPILE_ERROR, "Cannot use '%s' as class name as it is reserved", Z_STRVAL(class_name->u.constant)); } /* Class name must not conflict with import names */ if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns_name) == SUCCESS) { error = 1; } if (CG(current_namespace)) { /* Prefix class name with name of current namespace */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); class_name = &tmp; efree(lcname); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); } if (error) { char *tmp = zend_str_tolower_dup(Z_STRVAL_PP(ns_name), Z_STRLEN_PP(ns_name)); if (Z_STRLEN_PP(ns_name) != Z_STRLEN(class_name->u.constant) || memcmp(tmp, lcname, Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "Cannot declare class %s because the name is already in use", Z_STRVAL(class_name->u.constant)); } efree(tmp); } new_class_entry = emalloc(sizeof(zend_class_entry)); new_class_entry->type = ZEND_USER_CLASS; new_class_entry->name = zend_new_interned_string(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1, 1 TSRMLS_CC); new_class_entry->name_length = Z_STRLEN(class_name->u.constant); zend_initialize_class_data(new_class_entry, 1 TSRMLS_CC); new_class_entry->info.user.filename = zend_get_compiled_filename(TSRMLS_C); new_class_entry->info.user.line_start = class_token->u.op.opline_num; new_class_entry->ce_flags |= class_token->EA; if (parent_class_name && parent_class_name->op_type != IS_UNUSED) { switch (parent_class_name->EA) { case ZEND_FETCH_CLASS_SELF: zend_error(E_COMPILE_ERROR, "Cannot use 'self' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_PARENT: zend_error(E_COMPILE_ERROR, "Cannot use 'parent' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use 'static' as class name as it is reserved"); break; default: break; } doing_inheritance = 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, new_class_entry->name_length TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; if (doing_inheritance) { /* Make sure a trait does not try to extend a class */ if ((new_class_entry->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "A trait (%s) cannot extend a class", new_class_entry->name); } opline->extended_value = parent_class_name->u.op.var; opline->opcode = ZEND_DECLARE_INHERITED_CLASS; } else { opline->opcode = ZEND_DECLARE_CLASS; } LITERAL_STRINGL(opline->op2, lcname, new_class_entry->name_length, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); zend_hash_quick_update(CG(class_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &new_class_entry, sizeof(zend_class_entry *), NULL); CG(active_class_entry) = new_class_entry; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(&CG(implementing_class), opline->result); if (CG(doc_comment)) { CG(active_class_entry)->info.user.doc_comment = CG(doc_comment); CG(active_class_entry)->info.user.doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ static void do_verify_abstract_class(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_VERIFY_ABSTRACT_CLASS; SET_NODE(opline->op1, &CG(implementing_class)); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_class_declaration(const znode *class_token, const znode *parent_token TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); if (ce->constructor) { ce->constructor->common.fn_flags |= ZEND_ACC_CTOR; if (ce->constructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Constructor %s::%s() cannot be static", ce->name, ce->constructor->common.function_name); } } if (ce->destructor) { ce->destructor->common.fn_flags |= ZEND_ACC_DTOR; if (ce->destructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Destructor %s::%s() cannot be static", ce->name, ce->destructor->common.function_name); } } if (ce->clone) { ce->clone->common.fn_flags |= ZEND_ACC_CLONE; if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static", ce->name, ce->clone->common.function_name); } } ce->info.user.line_end = zend_get_compiled_lineno(TSRMLS_C); /* Check for traits and proceed like with interfaces. * The only difference will be a combined handling of them in the end. * Thus, we need another opcode here. */ if (ce->num_traits > 0) { zend_op *opline; ce->traits = NULL; ce->num_traits = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_TRAITS; /* opcode generation: */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BIND_TRAITS; SET_NODE(opline->op1, &CG(implementing_class)); } if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) && ((parent_token->op_type != IS_UNUSED) || (ce->num_interfaces > 0))) { zend_verify_abstract_class(ce TSRMLS_CC); if (ce->num_interfaces) { do_verify_abstract_class(TSRMLS_C); } } /* Inherit interfaces; reset number to zero, we need it for above check and * will restore it during actual implementation. * The ZEND_ACC_IMPLEMENT_INTERFACES flag disables double call to * zend_verify_abstract_class() */ if (ce->num_interfaces > 0) { ce->interfaces = NULL; ce->num_interfaces = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_INTERFACES; } CG(active_class_entry) = NULL; } /* }}} */ void zend_do_implements_interface(znode *interface_name TSRMLS_DC) /* {{{ */ { zend_op *opline; /* Traits can not implement interfaces */ if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface on '%s' since it is a Trait", Z_STRVAL(interface_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(interface_name->u.constant), Z_STRLEN(interface_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface name as it is reserved", Z_STRVAL(interface_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_INTERFACE; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(interface_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = (opline->extended_value & ~ZEND_FETCH_CLASS_MASK) | ZEND_FETCH_CLASS_INTERFACE; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &interface_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_interfaces++; } /* }}} */ void zend_do_implements_trait(znode *trait_name TSRMLS_DC) /* {{{ */ { zend_op *opline; if ((CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Cannot use traits inside of interfaces. %s is used in %s", Z_STRVAL(trait_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(trait_name->u.constant), Z_STRLEN(trait_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as trait name as it is reserved", Z_STRVAL(trait_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_TRAIT; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(trait_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = ZEND_FETCH_CLASS_TRAIT; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &trait_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_traits++; } /* }}} */ ZEND_API void zend_mangle_property_name(char **dest, int *dest_length, const char *src1, int src1_length, const char *src2, int src2_length, int internal) /* {{{ */ { char *prop_name; int prop_name_length; prop_name_length = 1 + src1_length + 1 + src2_length; prop_name = pemalloc(prop_name_length + 1, internal); prop_name[0] = '\0'; memcpy(prop_name + 1, src1, src1_length+1); memcpy(prop_name + 1 + src1_length + 1, src2, src2_length+1); *dest = prop_name; *dest_length = prop_name_length; } /* }}} */ static int zend_strnlen(const char* s, int maxlen) /* {{{ */ { int len = 0; while (*s++ && maxlen--) len++; return len; } /* }}} */ ZEND_API int zend_unmangle_property_name(const char *mangled_property, int len, const char **class_name, const char **prop_name) /* {{{ */ { int class_name_len; *class_name = NULL; if (mangled_property[0]!=0) { *prop_name = mangled_property; return SUCCESS; } if (len < 3 || mangled_property[1]==0) { zend_error(E_NOTICE, "Illegal member variable name"); *prop_name = mangled_property; return FAILURE; } class_name_len = zend_strnlen(mangled_property+1, --len - 1) + 1; if (class_name_len >= len || mangled_property[class_name_len]!=0) { zend_error(E_NOTICE, "Corrupt member variable name"); *prop_name = mangled_property; return FAILURE; } *class_name = mangled_property+1; *prop_name = (*class_name)+class_name_len; return SUCCESS; } /* }}} */ void zend_do_declare_property(const znode *var_name, const znode *value, zend_uint access_type TSRMLS_DC) /* {{{ */ { zval *property; zend_property_info *existing_property_info; char *comment = NULL; int comment_len = 0; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Interfaces may not include member variables"); } if (access_type & ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Properties cannot be declared abstract"); } if (access_type & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot declare property %s::$%s final, the final modifier is allowed only for methods and classes", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } if (zend_hash_find(&CG(active_class_entry)->properties_info, var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, (void **) &existing_property_info)==SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::$%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } ALLOC_ZVAL(property); if (value) { *property = value->u.constant; } else { INIT_PZVAL(property); Z_TYPE_P(property) = IS_NULL; } if (CG(doc_comment)) { comment = CG(doc_comment); comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } zend_declare_property_ex(CG(active_class_entry), zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len + 1, 0 TSRMLS_CC), var_name->u.constant.value.str.len, property, access_type, comment, comment_len TSRMLS_CC); efree(var_name->u.constant.value.str.val); } /* }}} */ void zend_do_declare_class_constant(znode *var_name, const znode *value TSRMLS_DC) /* {{{ */ { zval *property; const char *cname = NULL; int result; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed in class constants"); return; } if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Traits cannot have constants"); return; } ALLOC_ZVAL(property); *property = value->u.constant; cname = zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, 0 TSRMLS_CC); if (IS_INTERNED(cname)) { result = zend_hash_quick_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, INTERNED_HASH(cname), &property, sizeof(zval *), NULL); } else { result = zend_hash_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, &property, sizeof(zval *), NULL); } if (result == FAILURE) { FREE_ZVAL(property); zend_error(E_COMPILE_ERROR, "Cannot redefine class constant %s::%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } FREE_PNODE(var_name); if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_fetch_property(znode *result, znode *object, const znode *property TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (object->op_type == IS_CV) { if (object->u.op.var == CG(active_op_array)->this_var) { object->op_type = IS_UNUSED; /* this means $this for objects */ } } else if (fetch_list_ptr->count == 1) { zend_llist_element *le = fetch_list_ptr->head; zend_op *opline_ptr = (zend_op *) le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); SET_UNUSED(opline_ptr->op1); /* this means $this for objects */ SET_NODE(opline_ptr->op2, property); /* if it was usual fetch, we change it to object fetch */ switch (opline_ptr->opcode) { case ZEND_FETCH_W: opline_ptr->opcode = ZEND_FETCH_OBJ_W; break; case ZEND_FETCH_R: opline_ptr->opcode = ZEND_FETCH_OBJ_R; break; case ZEND_FETCH_RW: opline_ptr->opcode = ZEND_FETCH_OBJ_RW; break; case ZEND_FETCH_IS: opline_ptr->opcode = ZEND_FETCH_OBJ_IS; break; case ZEND_FETCH_UNSET: opline_ptr->opcode = ZEND_FETCH_OBJ_UNSET; break; case ZEND_FETCH_FUNC_ARG: opline_ptr->opcode = ZEND_FETCH_OBJ_FUNC_ARG; break; } if (opline_ptr->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline_ptr->op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline_ptr->op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op2.constant); } GET_NODE(result, opline_ptr->result); return; } } if (zend_is_function_or_method_call(object)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, object); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_OBJ_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, object); SET_NODE(opline.op2, property); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline.op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op2.constant); } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void zend_do_halt_compiler_register(TSRMLS_D) /* {{{ */ { char *name, *cfilename; char haltoff[] = "__COMPILER_HALT_OFFSET__"; int len, clen; cfilename = zend_get_compiled_filename(TSRMLS_C); clen = strlen(cfilename); zend_mangle_property_name(&name, &len, haltoff, sizeof(haltoff) - 1, cfilename, clen, 0); zend_register_long_constant(name, len+1, zend_get_scanned_file_offset(TSRMLS_C), CONST_CS, 0 TSRMLS_CC); pefree(name, 0); if (CG(in_namespace)) { zend_do_end_namespace(TSRMLS_C); } } /* }}} */ void zend_do_push_object(const znode *object TSRMLS_DC) /* {{{ */ { zend_stack_push(&CG(object_stack), object, sizeof(znode)); } /* }}} */ void zend_do_pop_object(znode *object TSRMLS_DC) /* {{{ */ { if (object) { znode *tmp; zend_stack_top(&CG(object_stack), (void **) &tmp); *object = *tmp; } zend_stack_del_top(&CG(object_stack)); } /* }}} */ void zend_do_begin_new_object(znode *new_token, znode *class_type TSRMLS_DC) /* {{{ */ { zend_op *opline; unsigned char *ptr = NULL; new_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_NEW; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, class_type); SET_UNUSED(opline->op2); zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(unsigned char *)); } /* }}} */ void zend_do_end_new_object(znode *result, const znode *new_token, const znode *argument_list TSRMLS_DC) /* {{{ */ { znode ctor_result; zend_do_end_function_call(NULL, &ctor_result, argument_list, 1, 0 TSRMLS_CC); zend_do_free(&ctor_result TSRMLS_CC); CG(active_op_array)->opcodes[new_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, CG(active_op_array)->opcodes[new_token->u.op.opline_num].result); } /* }}} */ static zend_constant* zend_get_ct_const(const zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = NULL; if (Z_STRVAL_P(const_name)[0] == '\\') { if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name), (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name)-1); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name), (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } } else if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)+1, (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name)+1, (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } if (c->flags & CONST_CT_SUBST) { return c; } if (all_internal_constants_substitution && (c->flags & CONST_PERSISTENT) && !(CG(compiler_options) & ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION) && Z_TYPE(c->value) != IS_CONSTANT && Z_TYPE(c->value) != IS_CONSTANT_ARRAY) { return c; } return NULL; } /* }}} */ static int zend_constant_ct_subst(znode *result, zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = zend_get_ct_const(const_name, all_internal_constants_substitution TSRMLS_CC); if (c) { zval_dtor(const_name); result->op_type = IS_CONST; result->u.constant = c->value; zval_copy_ctor(&result->u.constant); INIT_PZVAL(&result->u.constant); return 1; } return 0; } /* }}} */ void zend_do_fetch_constant(znode *result, znode *constant_container, znode *constant_name, int mode, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; zend_op *opline; int type; char *compound; ulong fetch_type = 0; if (constant_container) { switch (mode) { case ZEND_CT: /* this is a class constant */ type = zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant)); if (ZEND_FETCH_CLASS_STATIC == type) { zend_error(E_ERROR, "\"static::\" is not allowed in compile-time constants"); } else if (ZEND_FETCH_CLASS_DEFAULT == type) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } zend_do_build_full_name(NULL, constant_container, constant_name, 1 TSRMLS_CC); *result = *constant_container; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: if (constant_container->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant))) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } else { zend_do_fetch_class(&tmp, constant_container TSRMLS_CC); constant_container = &tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); if (constant_container->op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &constant_container->u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, constant_container); } SET_NODE(opline->op2, constant_name); CALCULATE_LITERAL_HASH(opline->op2.constant); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } GET_NODE(result, opline->result); break; } return; } /* namespace constant */ /* only one that did not contain \ from the start can be converted to string if unknown */ switch (mode) { case ZEND_CT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); /* this is a namespace constant, or an unprefixed constant */ if (zend_constant_ct_subst(result, &constant_name->u.constant, 0 TSRMLS_CC)) { break; } zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(!compound) { fetch_type |= IS_CONSTANT_UNQUALIFIED; } *result = *constant_name; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(zend_constant_ct_subst(result, &constant_name->u.constant, 1 TSRMLS_CC)) { break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; if (compound) { /* the name is unambiguous */ opline->extended_value = 0; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } else { opline->extended_value = IS_CONSTANT_UNQUALIFIED; if (CG(current_namespace)) { opline->extended_value |= IS_CONSTANT_IN_NAMESPACE; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 1 TSRMLS_CC); } else { opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } } GET_CACHE_SLOT(opline->op2.constant); break; } } /* }}} */ void zend_do_shell_exec(znode *result, const znode *cmd TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); switch (cmd->op_type) { case IS_CONST: case IS_TMP_VAR: opline->opcode = ZEND_SEND_VAL; break; default: opline->opcode = ZEND_SEND_VAR; break; } SET_NODE(opline->op1, cmd); opline->op2.opline_num = 0; opline->extended_value = ZEND_DO_FCALL; SET_UNUSED(opline->op2); /* FIXME: exception support not added to this op2 */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DO_FCALL; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; LITERAL_STRINGL(opline->op1, estrndup("shell_exec", sizeof("shell_exec")-1), sizeof("shell_exec")-1, 0); CALCULATE_LITERAL_HASH(opline->op1.constant); opline->op1_type = IS_CONST; GET_CACHE_SLOT(opline->op1.constant); opline->extended_value = 1; SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_init_array(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_ARRAY; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; GET_NODE(result, opline->result); if (expr) { SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } } else { SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_array_element(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_ARRAY_ELEMENT; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_static_array_element(znode *result, znode *offset, const znode *expr) /* {{{ */ { zval *element; ALLOC_ZVAL(element); *element = expr->u.constant; if (offset) { switch (offset->u.constant.type & IS_CONSTANT_TYPE_MASK) { case IS_CONSTANT: /* Ugly hack to denote that this value has a constant index */ Z_TYPE_P(element) |= IS_CONSTANT_INDEX; Z_STRVAL(offset->u.constant) = erealloc(Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+1] = Z_TYPE(offset->u.constant); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+2] = 0; zend_symtable_update(result->u.constant.value.ht, Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_STRING: zend_symtable_update(result->u.constant.value.ht, offset->u.constant.value.str.val, offset->u.constant.value.str.len+1, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_NULL: zend_symtable_update(Z_ARRVAL(result->u.constant), "", 1, &element, sizeof(zval *), NULL); break; case IS_LONG: case IS_BOOL: zend_hash_index_update(Z_ARRVAL(result->u.constant), Z_LVAL(offset->u.constant), &element, sizeof(zval *), NULL); break; case IS_DOUBLE: zend_hash_index_update(Z_ARRVAL(result->u.constant), zend_dval_to_lval(Z_DVAL(offset->u.constant)), &element, sizeof(zval *), NULL); break; case IS_CONSTANT_ARRAY: zend_error(E_ERROR, "Illegal offset type"); break; } } else { zend_hash_next_index_insert(Z_ARRVAL(result->u.constant), &element, sizeof(zval *), NULL); } } /* }}} */ void zend_do_add_list_element(const znode *element TSRMLS_DC) /* {{{ */ { list_llist_element lle; if (element) { zend_check_writable_variable(element); lle.var = *element; zend_llist_copy(&lle.dimensions, &CG(dimension_llist)); zend_llist_prepend_element(&CG(list_llist), &lle); } (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_new_list_begin(TSRMLS_D) /* {{{ */ { int current_dimension = 0; zend_llist_add_element(&CG(dimension_llist), &current_dimension); } /* }}} */ void zend_do_new_list_end(TSRMLS_D) /* {{{ */ { zend_llist_remove_tail(&CG(dimension_llist)); (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_list_init(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(list_stack), &CG(list_llist), sizeof(zend_llist)); zend_stack_push(&CG(list_stack), &CG(dimension_llist), sizeof(zend_llist)); zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_do_new_list_begin(TSRMLS_C); } /* }}} */ void zend_do_list_end(znode *result, znode *expr TSRMLS_DC) /* {{{ */ { zend_llist_element *le; zend_llist_element *dimension; zend_op *opline; znode last_container; le = CG(list_llist).head; while (le) { zend_llist *tmp_dimension_llist = &((list_llist_element *)le->data)->dimensions; dimension = tmp_dimension_llist->head; while (dimension) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (dimension == tmp_dimension_llist->head) { /* first */ last_container = *expr; switch (expr->op_type) { case IS_VAR: case IS_CV: opline->opcode = ZEND_FETCH_DIM_R; break; case IS_TMP_VAR: opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; case IS_CONST: /* fetch_dim_tmp_var will handle this bogus fetch */ zval_copy_ctor(&expr->u.constant); opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; } opline->extended_value |= ZEND_FETCH_ADD_LOCK; } else { opline->opcode = ZEND_FETCH_DIM_R; } opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, &last_container); opline->op2_type = IS_CONST; LITERAL_LONG(opline->op2, *((int *) dimension->data)); GET_NODE(&last_container, opline->result); dimension = dimension->next; } ((list_llist_element *) le->data)->value = last_container; zend_llist_destroy(&((list_llist_element *) le->data)->dimensions); zend_do_assign(result, &((list_llist_element *) le->data)->var, &((list_llist_element *) le->data)->value TSRMLS_CC); zend_do_free(result TSRMLS_CC); le = le->next; } zend_llist_destroy(&CG(dimension_llist)); zend_llist_destroy(&CG(list_llist)); *result = *expr; { zend_llist *p; /* restore previous lists */ zend_stack_top(&CG(list_stack), (void **) &p); CG(dimension_llist) = *p; zend_stack_del_top(&CG(list_stack)); zend_stack_top(&CG(list_stack), (void **) &p); CG(list_llist) = *p; zend_stack_del_top(&CG(list_stack)); } } /* }}} */ void zend_init_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = emalloc(sizeof(void*) * 2); list[0] = item; list[1] = NULL; *(void**)result = list; } /* }}} */ void zend_add_to_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = *(void**)result; size_t n = 0; while (list && list[n]) { n++; } list = erealloc(list, sizeof(void*) * (n+2)); list[n] = item; list[n+1] = NULL; *(void**)result = list; } /* }}} */ void zend_do_fetch_static_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zval *tmp; zend_op *opline; znode lval; znode result; ALLOC_ZVAL(tmp); if (static_assignment) { *tmp = static_assignment->u.constant; } else { INIT_ZVAL(*tmp); } if (!CG(active_op_array)->static_variables) { if (CG(active_op_array)->scope) { CG(active_op_array)->scope->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } ALLOC_HASHTABLE(CG(active_op_array)->static_variables); zend_hash_init(CG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } zend_hash_update(CG(active_op_array)->static_variables, varname->u.constant.value.str.val, varname->u.constant.value.str.len+1, &tmp, sizeof(zval *), NULL); if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (fetch_type == ZEND_FETCH_LEXICAL) ? ZEND_FETCH_R : ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_STATIC; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ if (fetch_type == ZEND_FETCH_LEXICAL) { znode dummy; zend_do_begin_variable_parse(TSRMLS_C); zend_do_assign(&dummy, &lval, &result TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } else { zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); } CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_fetch_lexical_variable(znode *varname, zend_bool is_ref TSRMLS_DC) /* {{{ */ { znode value; if (Z_STRLEN(varname->u.constant) == sizeof("this") - 1 && memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this") - 1) == 0) { zend_error(E_COMPILE_ERROR, "Cannot use $this as lexical variable"); return; } value.op_type = IS_CONST; ZVAL_NULL(&value.u.constant); Z_TYPE(value.u.constant) |= is_ref ? IS_LEXICAL_REF : IS_LEXICAL_VAR; Z_SET_REFCOUNT_P(&value.u.constant, 1); Z_UNSET_ISREF_P(&value.u.constant); zend_do_fetch_static_variable(varname, &value, is_ref ? ZEND_FETCH_STATIC : ZEND_FETCH_LEXICAL TSRMLS_CC); } /* }}} */ void zend_do_fetch_global_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zend_op *opline; znode lval; znode result; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = fetch_type; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_cast(znode *result, const znode *expr, int type TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CAST; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } /* }}} */ void zend_do_include_or_eval(int type, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_do_extended_fcall_begin(TSRMLS_C); { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INCLUDE_OR_EVAL; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } zend_do_extended_fcall_end(TSRMLS_C); } /* }}} */ void zend_do_indirect_references(znode *result, const znode *num_references, znode *variable TSRMLS_DC) /* {{{ */ { int i; zend_do_end_variable_parse(variable, BP_VAR_R, 0 TSRMLS_CC); for (i=1; i<num_references->u.constant.value.lval; i++) { fetch_simple_variable_ex(result, variable, 0, ZEND_FETCH_R TSRMLS_CC); *variable = *result; } zend_do_begin_variable_parse(TSRMLS_C); fetch_simple_variable(result, variable, 1 TSRMLS_CC); /* there is a chance someone is accessing $this */ if (CG(active_op_array)->scope && CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } /* }}} */ void zend_do_unset(const znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_UNSET_VAR; SET_NODE(opline->op1, variable); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); opline->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_UNSET: last_op->opcode = ZEND_UNSET_VAR; SET_UNUSED(last_op->result); break; case ZEND_FETCH_DIM_UNSET: last_op->opcode = ZEND_UNSET_DIM; SET_UNUSED(last_op->result); break; case ZEND_FETCH_OBJ_UNSET: last_op->opcode = ZEND_UNSET_OBJ; SET_UNUSED(last_op->result); break; } } } /* }}} */ void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_do_end_variable_parse(variable, BP_VAR_IS, 0 TSRMLS_CC); zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { last_op = get_next_op(CG(active_op_array) TSRMLS_CC); last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; SET_NODE(last_op->op1, variable); SET_UNUSED(last_op->op2); last_op->result.var = get_temporary_variable(CG(active_op_array)); last_op->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; break; case ZEND_FETCH_DIM_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_DIM_OBJ; break; case ZEND_FETCH_OBJ_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_PROP_OBJ; break; } } last_op->result_type = IS_TMP_VAR; last_op->extended_value |= type; GET_NODE(result, last_op->result); } /* }}} */ void zend_do_instanceof(znode *result, const znode *expr, const znode *class_znode, int type TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline->opcode == ZEND_FETCH_CLASS) { opline->extended_value |= ZEND_FETCH_CLASS_NO_AUTOLOAD; } } if (expr->op_type == IS_CONST) { zend_error(E_COMPILE_ERROR, "instanceof expects an object instance, constant given"); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INSTANCEOF; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_NODE(opline->op2, class_znode); GET_NODE(result, opline->result); } /* }}} */ void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_bool is_variable; zend_bool push_container = 0; zend_op dummy_opline; if (variable) { if (zend_is_function_or_method_call(array)) { is_variable = 0; } else { is_variable = 1; } /* save the location of FETCH_W instruction(s) */ open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); zend_do_end_variable_parse(array, BP_VAR_W, 0 TSRMLS_CC); if (CG(active_op_array)->last > 0 && CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) { /* Only lock the container if we are fetching from a real container and not $this */ if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1_type == IS_VAR) { CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK; push_container = 1; } } } else { is_variable = 0; open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* save the location of FE_RESET */ foreach_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* Preform array reset */ opline->opcode = ZEND_FE_RESET; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, array); SET_UNUSED(opline->op2); opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0; COPY_NODE(dummy_opline.result, opline->result); if (push_container) { COPY_NODE(dummy_opline.op1, CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1); } else { dummy_opline.op1_type = IS_UNUSED; } zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); /* save the location of FE_FETCH */ as_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FE_FETCH; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); COPY_NODE(opline->op1, dummy_opline.result); opline->extended_value = 0; SET_UNUSED(opline->op2); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_OP_DATA; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); } /* }}} */ void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC) /* {{{ */ { zend_op *opline; znode dummy, value_node; zend_bool assign_by_ref=0; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num]; if (key->op_type != IS_UNUSED) { znode *tmp; /* switch between the key and value... */ tmp = key; key = value; value = tmp; /* Mark extended_value in case both key and value are being used */ opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; } if ((key->op_type != IS_UNUSED) && (key->EA & ZEND_PARSED_REFERENCE_VARIABLE)) { zend_error(E_COMPILE_ERROR, "Key element cannot be a reference"); } if (value->EA & ZEND_PARSED_REFERENCE_VARIABLE) { assign_by_ref = 1; if (!(opline-1)->extended_value) { zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression"); } /* Mark extended_value for assign-by-reference */ opline->extended_value |= ZEND_FE_FETCH_BYREF; CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; } else { zend_op *foreach_copy; zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.op.opline_num]; zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.op.opline_num]; /* Change "write context" into "read context" */ fetch->extended_value = 0; /* reset ZEND_FE_RESET_VARIABLE */ while (fetch != end) { --fetch; if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } if (fetch->opcode == ZEND_SEPARATE) { MAKE_NOP(fetch); } else { fetch->opcode -= 3; /* FETCH_W -> FETCH_R */ } } /* prevent double SWITCH_FREE */ zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy); foreach_copy->op1_type = IS_UNUSED; } GET_NODE(&value_node, opline->result); if (assign_by_ref) { zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); /* Mark FE_FETCH as IS_VAR as it holds the data directly as a value */ zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC); } else { zend_do_assign(&dummy, value, &value_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } if (key->op_type != IS_UNUSED) { znode key_node; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num+1]; opline->result_type = IS_TMP_VAR; opline->result.opline_num = get_temporary_variable(CG(active_op_array)); GET_NODE(&key_node, opline->result); zend_do_assign(&dummy, key, &key_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_foreach_end(const znode *foreach_token, const znode *as_token TSRMLS_DC) /* {{{ */ { zend_op *container_ptr; zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = as_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_RESET */ CG(active_op_array)->opcodes[as_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_FETCH */ do_end_loop(as_token->u.op.opline_num, 1 TSRMLS_CC); zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr); generate_free_foreach_copy(container_ptr TSRMLS_CC); zend_stack_del_top(&CG(foreach_copy_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_declare_begin(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(declare_stack), &CG(declarables), sizeof(zend_declarables)); } /* }}} */ void zend_do_declare_stmt(znode *var, znode *val TSRMLS_DC) /* {{{ */ { if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "ticks", sizeof("ticks")-1)) { convert_to_long(&val->u.constant); CG(declarables).ticks = val->u.constant; } else if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "encoding", sizeof("encoding")-1)) { if ((Z_TYPE(val->u.constant) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Cannot use constants as encoding"); } /* * Check that the pragma comes before any opcodes. If the compilation * got as far as this, the previous portion of the script must have been * parseable according to the .ini script_encoding setting. We still * want to tell them to put declare() at the top. */ { int num = CG(active_op_array)->last; /* ignore ZEND_EXT_STMT and ZEND_TICKS */ while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Encoding declaration pragma must be the very first statement in the script"); } } if (CG(multibyte)) { const zend_encoding *new_encoding, *old_encoding; zend_encoding_filter old_input_filter; CG(encoding_declared) = 1; convert_to_string(&val->u.constant); new_encoding = zend_multibyte_fetch_encoding(val->u.constant.value.str.val TSRMLS_CC); if (!new_encoding) { zend_error(E_COMPILE_WARNING, "Unsupported encoding [%s]", val->u.constant.value.str.val); } else { old_input_filter = LANG_SCNG(input_filter); old_encoding = LANG_SCNG(script_encoding); zend_multibyte_set_filter(new_encoding TSRMLS_CC); /* need to re-scan if input filter changed */ if (old_input_filter != LANG_SCNG(input_filter) || (old_input_filter && new_encoding != old_encoding)) { zend_multibyte_yyinput_again(old_input_filter, old_encoding TSRMLS_CC); } } } else { zend_error(E_COMPILE_WARNING, "declare(encoding=...) ignored because Zend multibyte feature is turned off by settings"); } zval_dtor(&val->u.constant); } else { zend_error(E_COMPILE_WARNING, "Unsupported declare '%s'", var->u.constant.value.str.val); zval_dtor(&val->u.constant); } zval_dtor(&var->u.constant); } /* }}} */ void zend_do_declare_end(const znode *declare_token TSRMLS_DC) /* {{{ */ { zend_declarables *declarables; zend_stack_top(&CG(declare_stack), (void **) &declarables); /* We should restore if there was more than (current - start) - (ticks?1:0) opcodes */ if ((get_next_op_number(CG(active_op_array)) - declare_token->u.op.opline_num) - ((Z_LVAL(CG(declarables).ticks))?1:0)) { CG(declarables) = *declarables; } } /* }}} */ void zend_do_exit(znode *result, const znode *message TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXIT; SET_NODE(opline->op1, message); SET_UNUSED(opline->op2); result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_BOOL; Z_LVAL(result->u.constant) = 1; } /* }}} */ void zend_do_begin_silence(znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BEGIN_SILENCE; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); GET_NODE(strudel_token, opline->result); } /* }}} */ void zend_do_end_silence(const znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_END_SILENCE; SET_NODE(opline->op1, strudel_token); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_jmp_set(const znode *value, znode *jmp_token, znode *colon_token TSRMLS_DC) /* {{{ */ { int op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (value->op_type == IS_VAR || value->op_type == IS_CV) { opline->opcode = ZEND_JMP_SET_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_JMP_SET; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, value); SET_UNUSED(opline->op2); GET_NODE(colon_token, opline->result); jmp_token->u.op .opline_num = op_number; INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_jmp_set_else(znode *result, const znode *false_value, const znode *jmp_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, colon_token); if (colon_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].opcode = ZEND_JMP_SET_VAR; CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } opline->extended_value = 0; SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_qm_op(const znode *cond, znode *qm_token TSRMLS_DC) /* {{{ */ { int jmpz_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); SET_UNUSED(opline->op2); opline->op2.opline_num = jmpz_op_number; GET_NODE(qm_token, opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_qm_true(const znode *true_value, znode *qm_token, znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->opcodes[qm_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array))+1; /* jmp over the ZEND_JMP */ if (true_value->op_type == IS_VAR || true_value->op_type == IS_CV) { opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, true_value); SET_UNUSED(opline->op2); GET_NODE(qm_token, opline->result); colon_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_qm_false(znode *result, const znode *false_value, const znode *qm_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, qm_token); if (qm_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].opcode = ZEND_QM_ASSIGN_VAR; CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[colon_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, opline->result); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_extended_info(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_STMT; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_begin(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_BEGIN; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_end(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_END; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_ticks(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_TICKS; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->extended_value = Z_LVAL(CG(declarables).ticks); } /* }}} */ zend_bool zend_is_auto_global_quick(const char *name, uint name_len, ulong hashval TSRMLS_DC) /* {{{ */ { zend_auto_global *auto_global; ulong hash = hashval ? hashval : zend_hash_func(name, name_len+1); if (zend_hash_quick_find(CG(auto_globals), name, name_len+1, hash, (void **) &auto_global)==SUCCESS) { if (auto_global->armed) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } return 1; } return 0; } /* }}} */ zend_bool zend_is_auto_global(const char *name, uint name_len TSRMLS_DC) /* {{{ */ { return zend_is_auto_global_quick(name, name_len, 0 TSRMLS_CC); } /* }}} */ int zend_register_auto_global(const char *name, uint name_len, zend_bool jit, zend_auto_global_callback auto_global_callback TSRMLS_DC) /* {{{ */ { zend_auto_global auto_global; auto_global.name = zend_new_interned_string((char*)name, name_len + 1, 0 TSRMLS_CC); auto_global.name_len = name_len; auto_global.auto_global_callback = auto_global_callback; auto_global.jit = jit; return zend_hash_add(CG(auto_globals), name, name_len+1, &auto_global, sizeof(zend_auto_global), NULL); } /* }}} */ static int zend_auto_global_init(zend_auto_global *auto_global TSRMLS_DC) /* {{{ */ { if (auto_global->jit) { auto_global->armed = 1; } else if (auto_global->auto_global_callback) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } else { auto_global->armed = 0; } return 0; } /* }}} */ ZEND_API void zend_activate_auto_globals(TSRMLS_D) /* {{{ */ { zend_hash_apply(CG(auto_globals), (apply_func_t) zend_auto_global_init TSRMLS_CC); } /* }}} */ int zendlex(znode *zendlval TSRMLS_DC) /* {{{ */ { int retval; if (CG(increment_lineno)) { CG(zend_lineno)++; CG(increment_lineno) = 0; } again: Z_TYPE(zendlval->u.constant) = IS_LONG; retval = lex_scan(&zendlval->u.constant TSRMLS_CC); switch (retval) { case T_COMMENT: case T_DOC_COMMENT: case T_OPEN_TAG: case T_WHITESPACE: goto again; case T_CLOSE_TAG: if (LANG_SCNG(yy_text)[LANG_SCNG(yy_leng)-1] != '>') { CG(increment_lineno) = 1; } if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { goto again; } retval = ';'; /* implicit ; */ break; case T_OPEN_TAG_WITH_ECHO: retval = T_ECHO; break; case T_END_HEREDOC: efree(Z_STRVAL(zendlval->u.constant)); break; } INIT_PZVAL(&zendlval->u.constant); zendlval->op_type = IS_CONST; return retval; } /* }}} */ ZEND_API void zend_initialize_class_data(zend_class_entry *ce, zend_bool nullify_handlers TSRMLS_DC) /* {{{ */ { zend_bool persistent_hashes = (ce->type == ZEND_INTERNAL_CLASS) ? 1 : 0; dtor_func_t zval_ptr_dtor_func = ((persistent_hashes) ? ZVAL_INTERNAL_PTR_DTOR : ZVAL_PTR_DTOR); ce->refcount = 1; ce->ce_flags = 0; ce->default_properties_table = NULL; ce->default_static_members_table = NULL; zend_hash_init_ex(&ce->properties_info, 0, NULL, (dtor_func_t) (persistent_hashes ? zend_destroy_property_info_internal : zend_destroy_property_info), persistent_hashes, 0); zend_hash_init_ex(&ce->constants_table, 0, NULL, zval_ptr_dtor_func, persistent_hashes, 0); zend_hash_init_ex(&ce->function_table, 0, NULL, ZEND_FUNCTION_DTOR, persistent_hashes, 0); if (ce->type == ZEND_INTERNAL_CLASS) { #ifdef ZTS int n = zend_hash_num_elements(CG(class_table)); if (CG(static_members_table) && n >= CG(last_static_member)) { /* Support for run-time declaration: dl() */ CG(last_static_member) = n+1; CG(static_members_table) = realloc(CG(static_members_table), (n+1)*sizeof(zval**)); CG(static_members_table)[n] = NULL; } ce->static_members_table = (zval**)(zend_intptr_t)n; #else ce->static_members_table = NULL; #endif } else { ce->static_members_table = ce->default_static_members_table; ce->info.user.doc_comment = NULL; ce->info.user.doc_comment_len = 0; } ce->default_properties_count = 0; ce->default_static_members_count = 0; if (nullify_handlers) { ce->constructor = NULL; ce->destructor = NULL; ce->clone = NULL; ce->__get = NULL; ce->__set = NULL; ce->__unset = NULL; ce->__isset = NULL; ce->__call = NULL; ce->__callstatic = NULL; ce->__tostring = NULL; ce->create_object = NULL; ce->get_iterator = NULL; ce->iterator_funcs.funcs = NULL; ce->interface_gets_implemented = NULL; ce->get_static_method = NULL; ce->parent = NULL; ce->num_interfaces = 0; ce->interfaces = NULL; ce->num_traits = 0; ce->traits = NULL; ce->trait_aliases = NULL; ce->trait_precedences = NULL; ce->serialize = NULL; ce->unserialize = NULL; ce->serialize_func = NULL; ce->unserialize_func = NULL; if (ce->type == ZEND_INTERNAL_CLASS) { ce->info.internal.module = NULL; ce->info.internal.builtin_functions = NULL; } } } /* }}} */ int zend_get_class_fetch_type(const char *class_name, uint class_name_len) /* {{{ */ { if ((class_name_len == sizeof("self")-1) && !memcmp(class_name, "self", sizeof("self")-1)) { return ZEND_FETCH_CLASS_SELF; } else if ((class_name_len == sizeof("parent")-1) && !memcmp(class_name, "parent", sizeof("parent")-1)) { return ZEND_FETCH_CLASS_PARENT; } else if ((class_name_len == sizeof("static")-1) && !memcmp(class_name, "static", sizeof("static")-1)) { return ZEND_FETCH_CLASS_STATIC; } else { return ZEND_FETCH_CLASS_DEFAULT; } } /* }}} */ ZEND_API const char* zend_get_compiled_variable_name(const zend_op_array *op_array, zend_uint var, int* name_len) /* {{{ */ { if (name_len) { *name_len = op_array->vars[var].name_len; } return op_array->vars[var].name; } /* }}} */ void zend_do_build_namespace_name(znode *result, znode *prefix, znode *name TSRMLS_DC) /* {{{ */ { if (prefix) { *result = *prefix; if (Z_TYPE(result->u.constant) == IS_STRING && Z_STRLEN(result->u.constant) == 0) { /* namespace\ */ if (CG(current_namespace)) { znode tmp; zval_dtor(&result->u.constant); tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(result, NULL, &tmp TSRMLS_CC); } } } else { result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_STRING; Z_STRVAL(result->u.constant) = NULL; Z_STRLEN(result->u.constant) = 0; } /* prefix = result */ zend_do_build_full_name(NULL, result, name, 0 TSRMLS_CC); } /* }}} */ void zend_do_begin_namespace(const znode *name, zend_bool with_bracket TSRMLS_DC) /* {{{ */ { char *lcname; /* handle mixed syntax declaration or nested namespaces */ if (!CG(has_bracketed_namespaces)) { if (CG(current_namespace)) { /* previous namespace declarations were unbracketed */ if (with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } } } else { /* previous namespace declarations were bracketed */ if (!with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } else if (CG(current_namespace) || CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "Namespace declarations cannot be nested"); } } if (((!with_bracket && !CG(current_namespace)) || (with_bracket && !CG(has_bracketed_namespaces))) && CG(active_op_array)->last > 0) { /* ignore ZEND_EXT_STMT and ZEND_TICKS */ int num = CG(active_op_array)->last; while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Namespace declaration statement has to be the very first statement in the script"); } } CG(in_namespace) = 1; if (with_bracket) { CG(has_bracketed_namespaces) = 1; } if (name) { lcname = zend_str_tolower_dup(Z_STRVAL(name->u.constant), Z_STRLEN(name->u.constant)); if (((Z_STRLEN(name->u.constant) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN(name->u.constant) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as namespace name", Z_STRVAL(name->u.constant)); } efree(lcname); if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); } else { ALLOC_ZVAL(CG(current_namespace)); } *CG(current_namespace) = name->u.constant; } else { if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_use(znode *ns_name, znode *new_name, int is_global TSRMLS_DC) /* {{{ */ { char *lcname; zval *name, *ns, tmp; zend_bool warn = 0; zend_class_entry **pce; if (!CG(current_import)) { CG(current_import) = emalloc(sizeof(HashTable)); zend_hash_init(CG(current_import), 0, NULL, ZVAL_PTR_DTOR, 0); } ALLOC_ZVAL(ns); *ns = ns_name->u.constant; if (new_name) { name = &new_name->u.constant; } else { const char *p; /* The form "use A\B" is eqivalent to "use A\B as B". So we extract the last part of compound name to use as a new_name */ name = &tmp; p = zend_memrchr(Z_STRVAL_P(ns), '\\', Z_STRLEN_P(ns)); if (p) { ZVAL_STRING(name, p+1, 1); } else { *name = *ns; zval_copy_ctor(name); warn = !is_global && !CG(current_namespace); } } lcname = zend_str_tolower_dup(Z_STRVAL_P(name), Z_STRLEN_P(name)); if (((Z_STRLEN_P(name) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN_P(name) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because '%s' is a special class name", Z_STRVAL_P(ns), Z_STRVAL_P(name), Z_STRVAL_P(name)); } if (CG(current_namespace)) { /* Prefix import name with current namespace name to avoid conflicts with classes */ char *c_ns_name = emalloc(Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) + 1); zend_str_tolower_copy(c_ns_name, Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); c_ns_name[Z_STRLEN_P(CG(current_namespace))] = '\\'; memcpy(c_ns_name+Z_STRLEN_P(CG(current_namespace))+1, lcname, Z_STRLEN_P(name)+1); if (zend_hash_exists(CG(class_table), c_ns_name, Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name)+1)) { char *tmp2 = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) || memcmp(tmp2, c_ns_name, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(tmp2); } efree(c_ns_name); } else if (zend_hash_find(CG(class_table), lcname, Z_STRLEN_P(name)+1, (void**)&pce) == SUCCESS && (*pce)->type == ZEND_USER_CLASS && (*pce)->info.user.filename == CG(compiled_filename)) { char *c_tmp = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(name) || memcmp(c_tmp, lcname, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(c_tmp); } if (zend_hash_add(CG(current_import), lcname, Z_STRLEN_P(name)+1, &ns, sizeof(zval*), NULL) != SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } if (warn) { if (!strcmp(Z_STRVAL_P(name), "strict")) { zend_error(E_COMPILE_ERROR, "You seem to be trying to use a different language..."); } zend_error(E_WARNING, "The use statement with non-compound name '%s' has no effect", Z_STRVAL_P(name)); } efree(lcname); zval_dtor(name); } /* }}} */ void zend_do_declare_constant(znode *name, znode *value TSRMLS_DC) /* {{{ */ { zend_op *opline; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed as constants"); } if (zend_get_ct_const(&name->u.constant, 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare constant '%s'", Z_STRVAL(name->u.constant)); } if (CG(current_namespace)) { /* Prefix constant name with name of current namespace, lowercased */ znode tmp; tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); Z_STRVAL(tmp.u.constant) = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), Z_STRLEN(tmp.u.constant)); zend_do_build_namespace_name(&tmp, &tmp, name TSRMLS_CC); *name = tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DECLARE_CONST; SET_UNUSED(opline->result); SET_NODE(opline->op1, name); SET_NODE(opline->op2, value); } /* }}} */ void zend_verify_namespace(TSRMLS_D) /* {{{ */ { if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "No code may exist outside of namespace {}"); } } /* }}} */ void zend_do_end_namespace(TSRMLS_D) /* {{{ */ { CG(in_namespace) = 0; if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_end_compilation(TSRMLS_D) /* {{{ */ { CG(has_bracketed_namespaces) = 0; zend_do_end_namespace(TSRMLS_C); } /* }}} */ /* {{{ zend_dirname Returns directory name component of path */ ZEND_API size_t zend_dirname(char *path, size_t len) { register char *end = path + len - 1; unsigned int len_adjust = 0; #ifdef PHP_WIN32 /* Note that on Win32 CWD is per drive (heritage from CP/M). * This means dirname("c:foo") maps to "c:." or "c:" - which means CWD on C: drive. */ if ((2 <= len) && isalpha((int)((unsigned char *)path)[0]) && (':' == path[1])) { /* Skip over the drive spec (if any) so as not to change */ path += 2; len_adjust += 2; if (2 == len) { /* Return "c:" on Win32 for dirname("c:"). * It would be more consistent to return "c:." * but that would require making the string *longer*. */ return len; } } #elif defined(NETWARE) /* * Find the first occurence of : from the left * move the path pointer to the position just after : * increment the len_adjust to the length of path till colon character(inclusive) * If there is no character beyond : simple return len */ char *colonpos = NULL; colonpos = strchr(path, ':'); if (colonpos != NULL) { len_adjust = ((colonpos - path) + 1); path += len_adjust; if (len_adjust == len) { return len; } } #endif if (len == 0) { /* Illegal use of this function */ return 0; } /* Strip trailing slashes */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { /* The path only contained slashes */ path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } /* Strip filename */ while (end >= path && !IS_SLASH_P(end)) { end--; } if (end < path) { /* No slash found, therefore return '.' */ #ifdef NETWARE if (len_adjust == 0) { path[0] = '.'; path[1] = '\0'; return 1; /* only one character */ } else { path[0] = '\0'; return len_adjust; } #else path[0] = '.'; path[1] = '\0'; return 1 + len_adjust; #endif } /* Strip slashes which came before the file name */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } *(end+1) = '\0'; return (size_t)(end + 1 - path) + len_adjust; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-11-01-d2881adcbc-4591498df7.c
manybugs_data_27
/* gzip (GNU zip) -- compress files with zip algorithm and 'compress' interface Copyright (C) 1999, 2001-2002, 2006-2007, 2009-2010 Free Software Foundation, Inc. Copyright (C) 1992-1993 Jean-loup Gailly This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * The unzip code was written and put in the public domain by Mark Adler. * Portions of the lzw code are derived from the public domain 'compress' * written by Spencer Thomas, Joe Orost, James Woods, Jim McKie, Steve Davies, * Ken Turkowski, Dave Mack and Peter Jannesen. * * See the license_msg below and the file COPYING for the software license. * See the file algorithm.doc for the compression algorithms and file formats. */ static char const *const license_msg[] = { "Copyright (C) 2007, 2010 Free Software Foundation, Inc.", "Copyright (C) 1993 Jean-loup Gailly.", "This is free software. You may redistribute copies of it under the terms of", "the GNU General Public License <http://www.gnu.org/licenses/gpl.html>.", "There is NO WARRANTY, to the extent permitted by law.", 0}; /* Compress files with zip algorithm and 'compress' interface. * See help() function below for all options. * Outputs: * file.gz: compressed file with same mode, owner, and utimes * or stdout with -c option or if stdin used as input. * If the output file name had to be truncated, the original name is kept * in the compressed file. * On MSDOS, file.tmp -> file.tmz. On VMS, file.tmp -> file.tmp-gz. * * Using gz on MSDOS would create too many file name conflicts. For * example, foo.txt -> foo.tgz (.tgz must be reserved as shorthand for * tar.gz). Similarly, foo.dir and foo.doc would both be mapped to foo.dgz. * I also considered 12345678.txt -> 12345txt.gz but this truncates the name * too heavily. There is no ideal solution given the MSDOS 8+3 limitation. * * For the meaning of all compilation flags, see comments in Makefile.in. */ #include <config.h> #include <ctype.h> #include <sys/types.h> #include <signal.h> #include <stdbool.h> #include <sys/stat.h> #include <errno.h> #include "closein.h" #include "tailor.h" #include "gzip.h" #include "lzw.h" #include "revision.h" #include "fcntl-safer.h" #include "getopt.h" #include "ignore-value.h" #include "stat-time.h" /* configuration */ #include <fcntl.h> #include <limits.h> #include <unistd.h> #include <stdlib.h> #include <errno.h> #ifndef NO_DIR # define NO_DIR 0 #endif #if !NO_DIR # include <dirent.h> # ifndef _D_EXACT_NAMLEN # define _D_EXACT_NAMLEN(dp) strlen ((dp)->d_name) # endif #endif #ifdef CLOSEDIR_VOID # define CLOSEDIR(d) (closedir(d), 0) #else # define CLOSEDIR(d) closedir(d) #endif #ifndef NO_UTIME # include <utimens.h> #endif #define RW_USER (S_IRUSR | S_IWUSR) /* creation mode for open() */ #ifndef MAX_PATH_LEN # define MAX_PATH_LEN 1024 /* max pathname length */ #endif #ifndef SEEK_END # define SEEK_END 2 #endif #ifndef CHAR_BIT # define CHAR_BIT 8 #endif #ifdef off_t off_t lseek OF((int fd, off_t offset, int whence)); #endif #ifndef OFF_T_MIN #define OFF_T_MIN (~ (off_t) 0 << (sizeof (off_t) * CHAR_BIT - 1)) #endif #ifndef OFF_T_MAX #define OFF_T_MAX (~ (off_t) 0 - OFF_T_MIN) #endif /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is present. */ #ifndef SA_NOCLDSTOP # define SA_NOCLDSTOP 0 # define sigprocmask(how, set, oset) /* empty */ # define sigset_t int # if ! HAVE_SIGINTERRUPT # define siginterrupt(sig, flag) /* empty */ # endif #endif #ifndef HAVE_WORKING_O_NOFOLLOW # define HAVE_WORKING_O_NOFOLLOW 0 #endif #ifndef ELOOP # define ELOOP EINVAL #endif /* Separator for file name parts (see shorten_name()) */ #ifdef NO_MULTIPLE_DOTS # define PART_SEP "-" #else # define PART_SEP "." #endif /* global buffers */ DECLARE(uch, inbuf, INBUFSIZ +INBUF_EXTRA); DECLARE(uch, outbuf, OUTBUFSIZ+OUTBUF_EXTRA); DECLARE(ush, d_buf, DIST_BUFSIZE); DECLARE(uch, window, 2L*WSIZE); #ifndef MAXSEG_64K DECLARE(ush, tab_prefix, 1L<<BITS); #else DECLARE(ush, tab_prefix0, 1L<<(BITS-1)); DECLARE(ush, tab_prefix1, 1L<<(BITS-1)); #endif /* local variables */ /* If true, pretend that standard input is a tty. This option is deliberately not documented, and only for testing. */ static bool presume_input_tty; int ascii = 0; /* convert end-of-lines to local OS conventions */ int to_stdout = 0; /* output to stdout (-c) */ int decompress = 0; /* decompress (-d) */ int force = 0; /* don't ask questions, compress links (-f) */ int no_name = -1; /* don't save or restore the original file name */ int no_time = -1; /* don't save or restore the original file time */ int recursive = 0; /* recurse through directories (-r) */ int list = 0; /* list the file contents (-l) */ int verbose = 0; /* be verbose (-v) */ int quiet = 0; /* be very quiet (-q) */ int do_lzw = 0; /* generate output compatible with old compress (-Z) */ int test = 0; /* test .gz file integrity */ int foreground = 0; /* set if program run in foreground */ char *program_name; /* program name */ int maxbits = BITS; /* max bits per code for LZW */ int method = DEFLATED;/* compression method */ int level = 6; /* compression level */ int exit_code = OK; /* program exit code */ int save_orig_name; /* set if original name must be saved */ int last_member; /* set for .zip and .Z files */ int part_nb; /* number of parts in .gz file */ struct timespec time_stamp; /* original time stamp (modification time) */ off_t ifile_size; /* input file size, -1 for devices (debug only) */ char *env; /* contents of GZIP env variable */ char **args = NULL; /* argv pointer if GZIP env variable defined */ char const *z_suffix; /* default suffix (can be set with --suffix) */ size_t z_len; /* strlen(z_suffix) */ /* The set of signals that are caught. */ static sigset_t caught_signals; /* If nonzero then exit with status WARNING, rather than with the usual signal status, on receipt of a signal with this value. This suppresses a "Broken Pipe" message with some shells. */ static int volatile exiting_signal; /* If nonnegative, close this file descriptor and unlink ofname on error. */ static int volatile remove_ofname_fd = -1; off_t bytes_in; /* number of input bytes */ off_t bytes_out; /* number of output bytes */ off_t total_in; /* input bytes for all files */ off_t total_out; /* output bytes for all files */ char ifname[MAX_PATH_LEN]; /* input file name */ char ofname[MAX_PATH_LEN]; /* output file name */ struct stat istat; /* status for input file */ int ifd; /* input file descriptor */ int ofd; /* output file descriptor */ unsigned insize; /* valid bytes in inbuf */ unsigned inptr; /* index of next byte to be processed in inbuf */ unsigned outcnt; /* bytes in output buffer */ static int handled_sig[] = { /* SIGINT must be first, as 'foreground' depends on it. */ SIGINT #ifdef SIGHUP , SIGHUP #endif #ifdef SIGPIPE , SIGPIPE #else # define SIGPIPE 0 #endif #ifdef SIGTERM , SIGTERM #endif #ifdef SIGXCPU , SIGXCPU #endif #ifdef SIGXFSZ , SIGXFSZ #endif }; /* For long options that have no equivalent short option, use a non-character as a pseudo short option, starting with CHAR_MAX + 1. */ enum { PRESUME_INPUT_TTY_OPTION = CHAR_MAX + 1 }; struct option longopts[] = { /* { name has_arg *flag val } */ {"ascii", 0, 0, 'a'}, /* ascii text mode */ {"to-stdout", 0, 0, 'c'}, /* write output on standard output */ {"stdout", 0, 0, 'c'}, /* write output on standard output */ {"decompress", 0, 0, 'd'}, /* decompress */ {"uncompress", 0, 0, 'd'}, /* decompress */ /* {"encrypt", 0, 0, 'e'}, encrypt */ {"force", 0, 0, 'f'}, /* force overwrite of output file */ {"help", 0, 0, 'h'}, /* give help */ /* {"pkzip", 0, 0, 'k'}, force output in pkzip format */ {"list", 0, 0, 'l'}, /* list .gz file contents */ {"license", 0, 0, 'L'}, /* display software license */ {"no-name", 0, 0, 'n'}, /* don't save or restore original name & time */ {"name", 0, 0, 'N'}, /* save or restore original name & time */ {"-presume-input-tty", no_argument, NULL, PRESUME_INPUT_TTY_OPTION}, {"quiet", 0, 0, 'q'}, /* quiet mode */ {"silent", 0, 0, 'q'}, /* quiet mode */ {"recursive", 0, 0, 'r'}, /* recurse through directories */ {"suffix", 1, 0, 'S'}, /* use given suffix instead of .gz */ {"test", 0, 0, 't'}, /* test compressed file integrity */ {"no-time", 0, 0, 'T'}, /* don't save or restore the time stamp */ {"verbose", 0, 0, 'v'}, /* verbose mode */ {"version", 0, 0, 'V'}, /* display version number */ {"fast", 0, 0, '1'}, /* compress faster */ {"best", 0, 0, '9'}, /* compress better */ {"lzw", 0, 0, 'Z'}, /* make output compatible with old compress */ {"bits", 1, 0, 'b'}, /* max number of bits per code (implies -Z) */ { 0, 0, 0, 0 } }; /* local functions */ local void try_help OF((void)) ATTRIBUTE_NORETURN; local void help OF((void)); local void license OF((void)); local void version OF((void)); local int input_eof OF((void)); local void treat_stdin OF((void)); local void treat_file OF((char *iname)); local int create_outfile OF((void)); local char *get_suffix OF((char *name)); local int open_input_file OF((char *iname, struct stat *sbuf)); local int make_ofname OF((void)); local void shorten_name OF((char *name)); local int get_method OF((int in)); local void do_list OF((int ifd, int method)); local int check_ofname OF((void)); local void copy_stat OF((struct stat *ifstat)); local void install_signal_handlers OF((void)); local void remove_output_file OF((void)); local RETSIGTYPE abort_gzip_signal OF((int)); local void do_exit OF((int exitcode)) ATTRIBUTE_NORETURN; int main OF((int argc, char **argv)); int (*work) OF((int infile, int outfile)) = zip; /* function to call */ #if ! NO_DIR local void treat_dir OF((int fd, char *dir)); #endif #define strequ(s1, s2) (strcmp((s1),(s2)) == 0) static void try_help () { fprintf (stderr, "Try `%s --help' for more information.\n", program_name); do_exit (ERROR); } /* ======================================================================== */ local void help() { static char const* const help_msg[] = { "Compress or uncompress FILEs (by default, compress FILES in-place).", "", "Mandatory arguments to long options are mandatory for short options too.", "", #if O_BINARY " -a, --ascii ascii text; convert end-of-line using local conventions", #endif " -c, --stdout write on standard output, keep original files unchanged", " -d, --decompress decompress", /* -e, --encrypt encrypt */ " -f, --force force overwrite of output file and compress links", " -h, --help give this help", /* -k, --pkzip force output in pkzip format */ " -l, --list list compressed file contents", " -L, --license display software license", #ifdef UNDOCUMENTED " -m, --no-time do not save or restore the original modification time", " -M, --time save or restore the original modification time", #endif " -n, --no-name do not save or restore the original name and time stamp", " -N, --name save or restore the original name and time stamp", " -q, --quiet suppress all warnings", #if ! NO_DIR " -r, --recursive operate recursively on directories", #endif " -S, --suffix=SUF use suffix SUF on compressed files", " -t, --test test compressed file integrity", " -v, --verbose verbose mode", " -V, --version display version number", " -1, --fast compress faster", " -9, --best compress better", #ifdef LZW " -Z, --lzw produce output compatible with old compress", " -b, --bits=BITS max number of bits per code (implies -Z)", #endif "", "With no FILE, or when FILE is -, read standard input.", "", "Report bugs to <[email protected]>.", 0}; char const *const *p = help_msg; printf ("Usage: %s [OPTION]... [FILE]...\n", program_name); while (*p) printf ("%s\n", *p++); } /* ======================================================================== */ local void license() { char const *const *p = license_msg; printf ("%s %s\n", program_name, VERSION); while (*p) printf ("%s\n", *p++); } /* ======================================================================== */ local void version() { license (); printf ("\n"); printf ("Written by Jean-loup Gailly.\n"); } local void progerror (char const *string) { int e = errno; fprintf (stderr, "%s: ", program_name); errno = e; perror(string); exit_code = ERROR; } /* ======================================================================== */ int main (int argc, char **argv) { int file_count; /* number of files to process */ size_t proglen; /* length of program_name */ int optc; /* current option */ EXPAND(argc, argv); /* wild card expansion if necessary */ program_name = gzip_base_name (argv[0]); proglen = strlen (program_name); atexit (close_stdin); /* Suppress .exe for MSDOS, OS/2 and VMS: */ if (4 < proglen && strequ (program_name + proglen - 4, ".exe")) program_name[proglen - 4] = '\0'; /* Add options in GZIP environment variable if there is one */ env = add_envopt(&argc, &argv, OPTIONS_VAR); if (env != NULL) args = argv; #ifndef GNU_STANDARD # define GNU_STANDARD 1 #endif #if !GNU_STANDARD /* For compatibility with old compress, use program name as an option. * Unless you compile with -DGNU_STANDARD=0, this program will behave as * gzip even if it is invoked under the name gunzip or zcat. * * Systems which do not support links can still use -d or -dc. * Ignore an .exe extension for MSDOS, OS/2 and VMS. */ if (strncmp (program_name, "un", 2) == 0 /* ungzip, uncompress */ || strncmp (program_name, "gun", 3) == 0) /* gunzip */ decompress = 1; else if (strequ (program_name + 1, "cat") /* zcat, pcat, gcat */ || strequ (program_name, "gzcat")) /* gzcat */ decompress = to_stdout = 1; #endif z_suffix = Z_SUFFIX; z_len = strlen(z_suffix); while ((optc = getopt_long (argc, argv, "ab:cdfhH?lLmMnNqrS:tvVZ123456789", longopts, (int *)0)) != -1) { switch (optc) { case 'a': ascii = 1; break; case 'b': maxbits = atoi(optarg); for (; *optarg; optarg++) if (! ('0' <= *optarg && *optarg <= '9')) { fprintf (stderr, "%s: -b operand is not an integer\n", program_name); try_help (); } break; case 'c': to_stdout = 1; break; case 'd': decompress = 1; break; case 'f': force++; break; case 'h': case 'H': help(); do_exit(OK); break; case 'l': list = decompress = to_stdout = 1; break; case 'L': license(); do_exit(OK); break; case 'm': /* undocumented, may change later */ no_time = 1; break; case 'M': /* undocumented, may change later */ no_time = 0; break; case 'n': no_name = no_time = 1; break; case 'N': no_name = no_time = 0; break; case PRESUME_INPUT_TTY_OPTION: presume_input_tty = true; break; case 'q': quiet = 1; verbose = 0; break; case 'r': #if NO_DIR fprintf (stderr, "%s: -r not supported on this system\n", program_name); try_help (); #else recursive = 1; #endif break; case 'S': #ifdef NO_MULTIPLE_DOTS if (*optarg == '.') optarg++; #endif z_len = strlen(optarg); z_suffix = optarg; break; case 't': test = decompress = to_stdout = 1; break; case 'v': verbose++; quiet = 0; break; case 'V': version(); do_exit(OK); break; case 'Z': #ifdef LZW do_lzw = 1; break; #else fprintf(stderr, "%s: -Z not supported in this version\n", program_name); try_help (); break; #endif case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': level = optc - '0'; break; default: /* Error message already emitted by getopt_long. */ try_help (); } } /* loop on all arguments */ /* By default, save name and timestamp on compression but do not * restore them on decompression. */ if (no_time < 0) no_time = decompress; if (no_name < 0) no_name = decompress; file_count = argc - optind; #if O_BINARY #else if (ascii && !quiet) { fprintf(stderr, "%s: option --ascii ignored on this system\n", program_name); } #endif if ((z_len == 0 && !decompress) || z_len > MAX_SUFFIX) { fprintf(stderr, "%s: incorrect suffix '%s'\n", program_name, z_suffix); do_exit(ERROR); } if (do_lzw && !decompress) work = lzw; /* Allocate all global buffers (for DYN_ALLOC option) */ ALLOC(uch, inbuf, INBUFSIZ +INBUF_EXTRA); ALLOC(uch, outbuf, OUTBUFSIZ+OUTBUF_EXTRA); ALLOC(ush, d_buf, DIST_BUFSIZE); ALLOC(uch, window, 2L*WSIZE); #ifndef MAXSEG_64K ALLOC(ush, tab_prefix, 1L<<BITS); #else ALLOC(ush, tab_prefix0, 1L<<(BITS-1)); ALLOC(ush, tab_prefix1, 1L<<(BITS-1)); #endif exiting_signal = quiet ? SIGPIPE : 0; install_signal_handlers (); /* And get to work */ if (file_count != 0) { if (to_stdout && !test && !list && (!decompress || !ascii)) { SET_BINARY_MODE(fileno(stdout)); } while (optind < argc) { treat_file(argv[optind++]); } } else { /* Standard input */ treat_stdin(); } if (list && !quiet && file_count > 1) { do_list(-1, -1); /* print totals */ } do_exit(exit_code); return exit_code; /* just to avoid lint warning */ } /* Return nonzero when at end of file on input. */ local int input_eof () { if (!decompress || last_member) return 1; if (inptr == insize) { if (insize != INBUFSIZ || fill_inbuf (1) == EOF) return 1; /* Unget the char that fill_inbuf got. */ inptr = 0; } return 0; } /* ======================================================================== * Compress or decompress stdin */ local void treat_stdin() { if (!force && !list && (presume_input_tty || isatty(fileno((FILE *)(decompress ? stdin : stdout))))) { /* Do not send compressed data to the terminal or read it from * the terminal. We get here when user invoked the program * without parameters, so be helpful. According to the GNU standards: * * If there is one behavior you think is most useful when the output * is to a terminal, and another that you think is most useful when * the output is a file or a pipe, then it is usually best to make * the default behavior the one that is useful with output to a * terminal, and have an option for the other behavior. * * Here we use the --force option to get the other behavior. */ fprintf(stderr, "%s: compressed data not %s a terminal. Use -f to force %scompression.\n", program_name, decompress ? "read from" : "written to", decompress ? "de" : ""); fprintf (stderr, "For help, type: %s -h\n", program_name); do_exit(ERROR); } if (decompress || !ascii) { SET_BINARY_MODE(fileno(stdin)); } if (!test && !list && (!decompress || !ascii)) { SET_BINARY_MODE(fileno(stdout)); } strcpy(ifname, "stdin"); strcpy(ofname, "stdout"); /* Get the file's time stamp and size. */ if (fstat (fileno (stdin), &istat) != 0) { progerror ("standard input"); do_exit (ERROR); } ifile_size = S_ISREG (istat.st_mode) ? istat.st_size : -1; time_stamp.tv_nsec = -1; if (!no_time || list) time_stamp = get_stat_mtime (&istat); clear_bufs(); /* clear input and output buffers */ to_stdout = 1; part_nb = 0; ifd = fileno(stdin); if (decompress) { method = get_method(ifd); if (method < 0) { do_exit(exit_code); /* error message already emitted */ } } if (list) { do_list(ifd, method); return; } /* Actually do the compression/decompression. Loop over zipped members. */ for (;;) { if ((*work)(fileno(stdin), fileno(stdout)) != OK) return; if (input_eof ()) break; method = get_method(ifd); if (method < 0) return; /* error message already emitted */ bytes_out = 0; /* required for length check */ } if (verbose) { if (test) { fprintf(stderr, " OK\n"); } else if (!decompress) { display_ratio(bytes_in-(bytes_out-header_bytes), bytes_in, stderr); fprintf(stderr, "\n"); #ifdef DISPLAY_STDIN_RATIO } else { display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out,stderr); fprintf(stderr, "\n"); #endif } } } /* ======================================================================== * Compress or decompress the given file */ local void treat_file(iname) char *iname; { /* Accept "-" as synonym for stdin */ if (strequ(iname, "-")) { int cflag = to_stdout; treat_stdin(); to_stdout = cflag; return; } /* Check if the input file is present, set ifname and istat: */ ifd = open_input_file (iname, &istat); if (ifd < 0) return; /* If the input name is that of a directory, recurse or ignore: */ if (S_ISDIR(istat.st_mode)) { #if ! NO_DIR if (recursive) { treat_dir (ifd, iname); /* Warning: ifname is now garbage */ return; } #endif close (ifd); WARN ((stderr, "%s: %s is a directory -- ignored\n", program_name, ifname)); return; } if (! to_stdout) { if (! S_ISREG (istat.st_mode)) { WARN ((stderr, "%s: %s is not a directory or a regular file - ignored\n", program_name, ifname)); close (ifd); return; } if (istat.st_mode & S_ISUID) { WARN ((stderr, "%s: %s is set-user-ID on execution - ignored\n", program_name, ifname)); close (ifd); return; } if (istat.st_mode & S_ISGID) { WARN ((stderr, "%s: %s is set-group-ID on execution - ignored\n", program_name, ifname)); close (ifd); return; } if (! force) { if (istat.st_mode & S_ISVTX) { WARN ((stderr, "%s: %s has the sticky bit set - file ignored\n", program_name, ifname)); close (ifd); return; } if (2 <= istat.st_nlink) { WARN ((stderr, "%s: %s has %lu other link%c -- unchanged\n", program_name, ifname, (unsigned long int) istat.st_nlink - 1, istat.st_nlink == 2 ? ' ' : 's')); close (ifd); return; } } } ifile_size = S_ISREG (istat.st_mode) ? istat.st_size : -1; time_stamp.tv_nsec = -1; if (!no_time || list) time_stamp = get_stat_mtime (&istat); /* Generate output file name. For -r and (-t or -l), skip files * without a valid gzip suffix (check done in make_ofname). */ if (to_stdout && !list && !test) { strcpy(ofname, "stdout"); } else if (make_ofname() != OK) { close (ifd); return; } clear_bufs(); /* clear input and output buffers */ part_nb = 0; if (decompress) { method = get_method(ifd); /* updates ofname if original given */ if (method < 0) { close(ifd); return; /* error message already emitted */ } } if (list) { do_list(ifd, method); if (close (ifd) != 0) read_error (); return; } /* If compressing to a file, check if ofname is not ambiguous * because the operating system truncates names. Otherwise, generate * a new ofname and save the original name in the compressed file. */ if (to_stdout) { ofd = fileno(stdout); /* Keep remove_ofname_fd negative. */ } else { if (create_outfile() != OK) return; if (!decompress && save_orig_name && !verbose && !quiet) { fprintf(stderr, "%s: %s compressed to %s\n", program_name, ifname, ofname); } } /* Keep the name even if not truncated except with --no-name: */ if (!save_orig_name) save_orig_name = !no_name; if (verbose) { fprintf(stderr, "%s:\t", ifname); } /* Actually do the compression/decompression. Loop over zipped members. */ for (;;) { if ((*work)(ifd, ofd) != OK) { method = -1; /* force cleanup */ break; } if (input_eof ()) break; method = get_method(ifd); if (method < 0) break; /* error message already emitted */ bytes_out = 0; /* required for length check */ } if (close (ifd) != 0) read_error (); if (!to_stdout) { sigset_t oldset; int unlink_errno; copy_stat (&istat); if (close (ofd) != 0) write_error (); sigprocmask (SIG_BLOCK, &caught_signals, &oldset); remove_ofname_fd = -1; unlink_errno = xunlink (ifname) == 0 ? 0 : errno; sigprocmask (SIG_SETMASK, &oldset, NULL); if (unlink_errno) { WARN ((stderr, "%s: ", program_name)); if (!quiet) { errno = unlink_errno; perror (ifname); } } } if (method == -1) { if (!to_stdout) remove_output_file (); return; } /* Display statistics */ if(verbose) { if (test) { fprintf(stderr, " OK"); } else if (decompress) { display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out,stderr); } else { display_ratio(bytes_in-(bytes_out-header_bytes), bytes_in, stderr); } if (!test && !to_stdout) { fprintf(stderr, " -- replaced with %s", ofname); } fprintf(stderr, "\n"); } } /* ======================================================================== * Create the output file. Return OK or ERROR. * Try several times if necessary to avoid truncating the z_suffix. For * example, do not create a compressed file of name "1234567890123." * Sets save_orig_name to true if the file name has been truncated. * IN assertions: the input file has already been open (ifd is set) and * ofname has already been updated if there was an original name. * OUT assertions: ifd and ofd are closed in case of error. */ local int create_outfile() { int name_shortened = 0; int flags = (O_WRONLY | O_CREAT | O_EXCL | (ascii && decompress ? 0 : O_BINARY)); for (;;) { int open_errno; sigset_t oldset; sigprocmask (SIG_BLOCK, &caught_signals, &oldset); remove_ofname_fd = ofd = OPEN (ofname, flags, RW_USER); open_errno = errno; sigprocmask (SIG_SETMASK, &oldset, NULL); if (0 <= ofd) break; switch (open_errno) { #ifdef ENAMETOOLONG case ENAMETOOLONG: shorten_name (ofname); name_shortened = 1; break; #endif case EEXIST: if (check_ofname () != OK) { close (ifd); return ERROR; } break; default: progerror (ofname); close (ifd); return ERROR; } } if (name_shortened && decompress) { /* name might be too long if an original name was saved */ WARN ((stderr, "%s: %s: warning, name truncated\n", program_name, ofname)); } return OK; } /* ======================================================================== * Return a pointer to the 'z' suffix of a file name, or NULL. For all * systems, ".gz", ".z", ".Z", ".taz", ".tgz", "-gz", "-z" and "_z" are * accepted suffixes, in addition to the value of the --suffix option. * ".tgz" is a useful convention for tar.z files on systems limited * to 3 characters extensions. On such systems, ".?z" and ".??z" are * also accepted suffixes. For Unix, we do not want to accept any * .??z suffix as indicating a compressed file; some people use .xyz * to denote volume data. * On systems allowing multiple versions of the same file (such as VMS), * this function removes any version suffix in the given name. */ local char *get_suffix(name) char *name; { int nlen, slen; char suffix[MAX_SUFFIX+3]; /* last chars of name, forced to lower case */ static char const *known_suffixes[] = {NULL, ".gz", ".z", ".taz", ".tgz", "-gz", "-z", "_z", #ifdef MAX_EXT_CHARS "z", #endif NULL}; char const **suf = known_suffixes; *suf = z_suffix; if (strequ(z_suffix, "z")) suf++; /* check long suffixes first */ #ifdef SUFFIX_SEP /* strip a version number from the file name */ { char *v = strrchr(name, SUFFIX_SEP); if (v != NULL) *v = '\0'; } #endif nlen = strlen(name); if (nlen <= MAX_SUFFIX+2) { strcpy(suffix, name); } else { strcpy(suffix, name+nlen-MAX_SUFFIX-2); } strlwr(suffix); slen = strlen(suffix); do { int s = strlen(*suf); if (slen > s && suffix[slen-s-1] != PATH_SEP && strequ(suffix + slen - s, *suf)) { return name+nlen-s; } } while (*++suf != NULL); return NULL; } /* Open file NAME with the given flags and mode and store its status into *ST. Return a file descriptor to the newly opened file, or -1 (setting errno) on failure. */ static int open_and_stat (char *name, int flags, mode_t mode, struct stat *st) { int fd; /* Refuse to follow symbolic links unless -c or -f. */ if (!to_stdout && !force) { if (HAVE_WORKING_O_NOFOLLOW) flags |= O_NOFOLLOW; else { #if HAVE_LSTAT || defined lstat if (lstat (name, st) != 0) return -1; else if (S_ISLNK (st->st_mode)) { errno = ELOOP; return -1; } #endif } } fd = OPEN (name, flags, mode); if (0 <= fd && fstat (fd, st) != 0) { int e = errno; close (fd); errno = e; return -1; } return fd; } /* ======================================================================== * Set ifname to the input file name (with a suffix appended if necessary) * and istat to its stats. For decompression, if no file exists with the * original name, try adding successively z_suffix, .gz, .z, -z and .Z. * For MSDOS, we try only z_suffix and z. * Return an open file descriptor or -1. */ static int open_input_file (iname, sbuf) char *iname; struct stat *sbuf; { int ilen; /* strlen(ifname) */ int z_suffix_errno = 0; static char const *suffixes[] = {NULL, ".gz", ".z", "-z", ".Z", NULL}; char const **suf = suffixes; char const *s; #ifdef NO_MULTIPLE_DOTS char *dot; /* pointer to ifname extension, or NULL */ #endif int fd; int open_flags = (O_RDONLY | O_NONBLOCK | O_NOCTTY | (ascii && !decompress ? 0 : O_BINARY)); *suf = z_suffix; if (sizeof ifname - 1 <= strlen (iname)) goto name_too_long; strcpy(ifname, iname); /* If input file exists, return OK. */ fd = open_and_stat (ifname, open_flags, RW_USER, sbuf); if (0 <= fd) return fd; if (!decompress || errno != ENOENT) { progerror(ifname); return -1; } /* file.ext doesn't exist, try adding a suffix (after removing any * version number for VMS). */ s = get_suffix(ifname); if (s != NULL) { progerror(ifname); /* ifname already has z suffix and does not exist */ return -1; } #ifdef NO_MULTIPLE_DOTS dot = strrchr(ifname, '.'); if (dot == NULL) { strcat(ifname, "."); dot = strrchr(ifname, '.'); } #endif ilen = strlen(ifname); if (strequ(z_suffix, ".gz")) suf++; /* Search for all suffixes */ do { char const *s0 = s = *suf; strcpy (ifname, iname); #ifdef NO_MULTIPLE_DOTS if (*s == '.') s++; if (*dot == '\0') strcpy (dot, "."); #endif #ifdef MAX_EXT_CHARS if (MAX_EXT_CHARS < strlen (s) + strlen (dot + 1)) dot[MAX_EXT_CHARS + 1 - strlen (s)] = '\0'; #endif if (sizeof ifname <= ilen + strlen (s)) goto name_too_long; strcat(ifname, s); fd = open_and_stat (ifname, open_flags, RW_USER, sbuf); if (0 <= fd) return fd; if (errno != ENOENT) { progerror (ifname); return -1; } if (strequ (s0, z_suffix)) z_suffix_errno = errno; } while (*++suf != NULL); /* No suffix found, complain using z_suffix: */ strcpy(ifname, iname); #ifdef NO_MULTIPLE_DOTS if (*dot == '\0') strcpy(dot, "."); #endif #ifdef MAX_EXT_CHARS if (MAX_EXT_CHARS < z_len + strlen (dot + 1)) dot[MAX_EXT_CHARS + 1 - z_len] = '\0'; #endif strcat(ifname, z_suffix); errno = z_suffix_errno; progerror(ifname); return -1; name_too_long: fprintf (stderr, "%s: %s: file name too long\n", program_name, iname); exit_code = ERROR; return -1; } /* ======================================================================== * Generate ofname given ifname. Return OK, or WARNING if file must be skipped. * Sets save_orig_name to true if the file name has been truncated. */ local int make_ofname() { char *suff; /* ofname z suffix */ strcpy(ofname, ifname); /* strip a version number if any and get the gzip suffix if present: */ suff = get_suffix(ofname); if (decompress) { if (suff == NULL) { /* With -t or -l, try all files (even without .gz suffix) * except with -r (behave as with just -dr). */ if (!recursive && (list || test)) return OK; /* Avoid annoying messages with -r */ if (verbose || (!recursive && !quiet)) { WARN((stderr,"%s: %s: unknown suffix -- ignored\n", program_name, ifname)); } return WARNING; } /* Make a special case for .tgz and .taz: */ strlwr(suff); if (strequ(suff, ".tgz") || strequ(suff, ".taz")) { strcpy(suff, ".tar"); } else { *suff = '\0'; /* strip the z suffix */ } /* ofname might be changed later if infile contains an original name */ } else if (suff && ! force) { /* Avoid annoying messages with -r (see treat_dir()) */ if (verbose || (!recursive && !quiet)) { /* Don't use WARN, as it affects exit status. */ fprintf (stderr, "%s: %s already has %s suffix -- unchanged\n", program_name, ifname, suff); } return WARNING; } else { save_orig_name = 0; #ifdef NO_MULTIPLE_DOTS suff = strrchr(ofname, '.'); if (suff == NULL) { if (sizeof ofname <= strlen (ofname) + 1) goto name_too_long; strcat(ofname, "."); # ifdef MAX_EXT_CHARS if (strequ(z_suffix, "z")) { if (sizeof ofname <= strlen (ofname) + 2) goto name_too_long; strcat(ofname, "gz"); /* enough room */ return OK; } /* On the Atari and some versions of MSDOS, * ENAMETOOLONG does not work correctly. So we * must truncate here. */ } else if (strlen(suff)-1 + z_len > MAX_SUFFIX) { suff[MAX_SUFFIX+1-z_len] = '\0'; save_orig_name = 1; # endif } #endif /* NO_MULTIPLE_DOTS */ if (sizeof ofname <= strlen (ofname) + z_len) goto name_too_long; strcat(ofname, z_suffix); } /* decompress ? */ return OK; name_too_long: WARN ((stderr, "%s: %s: file name too long\n", program_name, ifname)); return WARNING; } /* ======================================================================== * Check the magic number of the input file and update ofname if an * original name was given and to_stdout is not set. * Return the compression method, -1 for error, -2 for warning. * Set inptr to the offset of the next byte to be processed. * Updates time_stamp if there is one and --no-time is not used. * This function may be called repeatedly for an input file consisting * of several contiguous gzip'ed members. * IN assertions: there is at least one remaining compressed member. * If the member is a zip file, it must be the only one. */ local int get_method(in) int in; /* input file descriptor */ { uch flags; /* compression flags */ char magic[2]; /* magic header */ int imagic0; /* first magic byte or EOF */ int imagic1; /* like magic[1], but can represent EOF */ ulg stamp; /* time stamp */ /* If --force and --stdout, zcat == cat, so do not complain about * premature end of file: use try_byte instead of get_byte. */ if (force && to_stdout) { imagic0 = try_byte(); magic[0] = (char) imagic0; imagic1 = try_byte (); magic[1] = (char) imagic1; /* If try_byte returned EOF, magic[1] == (char) EOF. */ } else { magic[0] = (char)get_byte(); imagic0 = 0; if (magic[0]) { magic[1] = (char)get_byte(); imagic1 = 0; /* avoid lint warning */ } else { imagic1 = try_byte (); magic[1] = (char) imagic1; } } method = -1; /* unknown yet */ part_nb++; /* number of parts in gzip file */ header_bytes = 0; last_member = RECORD_IO; /* assume multiple members in gzip file except for record oriented I/O */ if (memcmp(magic, GZIP_MAGIC, 2) == 0 || memcmp(magic, OLD_GZIP_MAGIC, 2) == 0) { method = (int)get_byte(); if (method != DEFLATED) { fprintf(stderr, "%s: %s: unknown method %d -- not supported\n", program_name, ifname, method); exit_code = ERROR; return -1; } work = unzip; flags = (uch)get_byte(); if ((flags & ENCRYPTED) != 0) { fprintf(stderr, "%s: %s is encrypted -- not supported\n", program_name, ifname); exit_code = ERROR; return -1; } if ((flags & CONTINUATION) != 0) { fprintf(stderr, "%s: %s is a multi-part gzip file -- not supported\n", program_name, ifname); exit_code = ERROR; if (force <= 1) return -1; } if ((flags & RESERVED) != 0) { fprintf(stderr, "%s: %s has flags 0x%x -- not supported\n", program_name, ifname, flags); exit_code = ERROR; if (force <= 1) return -1; } stamp = (ulg)get_byte(); stamp |= ((ulg)get_byte()) << 8; stamp |= ((ulg)get_byte()) << 16; stamp |= ((ulg)get_byte()) << 24; if (stamp != 0 && !no_time) { time_stamp.tv_sec = stamp; time_stamp.tv_nsec = 0; } (void)get_byte(); /* Ignore extra flags for the moment */ (void)get_byte(); /* Ignore OS type for the moment */ if ((flags & CONTINUATION) != 0) { unsigned part = (unsigned)get_byte(); part |= ((unsigned)get_byte())<<8; if (verbose) { fprintf(stderr,"%s: %s: part number %u\n", program_name, ifname, part); } } if ((flags & EXTRA_FIELD) != 0) { unsigned len = (unsigned)get_byte(); len |= ((unsigned)get_byte())<<8; if (verbose) { fprintf(stderr,"%s: %s: extra field of %u bytes ignored\n", program_name, ifname, len); } while (len--) (void)get_byte(); } /* Get original file name if it was truncated */ if ((flags & ORIG_NAME) != 0) { if (no_name || (to_stdout && !list) || part_nb > 1) { /* Discard the old name */ char c; /* dummy used for NeXTstep 3.0 cc optimizer bug */ do {c=get_byte();} while (c != 0); } else { /* Copy the base name. Keep a directory prefix intact. */ char *p = gzip_base_name (ofname); char *base = p; for (;;) { *p = (char)get_char(); if (*p++ == '\0') break; if (p >= ofname+sizeof(ofname)) { gzip_error ("corrupted input -- file name too large"); } } p = gzip_base_name (base); memmove (base, p, strlen (p) + 1); /* If necessary, adapt the name to local OS conventions: */ if (!list) { MAKE_LEGAL_NAME(base); if (base) list=0; /* avoid warning about unused variable */ } } /* no_name || to_stdout */ } /* ORIG_NAME */ /* Discard file comment if any */ if ((flags & COMMENT) != 0) { while (get_char() != 0) /* null */ ; } if (part_nb == 1) { header_bytes = inptr + 2*sizeof(long); /* include crc and size */ } } else if (memcmp(magic, PKZIP_MAGIC, 2) == 0 && inptr == 2 && memcmp((char*)inbuf, PKZIP_MAGIC, 4) == 0) { /* To simplify the code, we support a zip file when alone only. * We are thus guaranteed that the entire local header fits in inbuf. */ inptr = 0; work = unzip; if (check_zipfile(in) != OK) return -1; /* check_zipfile may get ofname from the local header */ last_member = 1; } else if (memcmp(magic, PACK_MAGIC, 2) == 0) { work = unpack; method = PACKED; } else if (memcmp(magic, LZW_MAGIC, 2) == 0) { work = unlzw; method = COMPRESSED; last_member = 1; } else if (memcmp(magic, LZH_MAGIC, 2) == 0) { work = unlzh; method = LZHED; last_member = 1; } else if (force && to_stdout && !list) { /* pass input unchanged */ method = STORED; work = copy; if (imagic1 != EOF) inptr--; last_member = 1; if (imagic0 != EOF) { write_buf(fileno(stdout), magic, 1); bytes_out++; } } if (method >= 0) return method; if (part_nb == 1) { fprintf (stderr, "\n%s: %s: not in gzip format\n", program_name, ifname); exit_code = ERROR; return -1; } else { if (magic[0] == 0) { int inbyte; for (inbyte = imagic1; inbyte == 0; inbyte = try_byte ()) continue; if (inbyte == EOF) { if (verbose) WARN ((stderr, "\n%s: %s: decompression OK, trailing zero bytes ignored\n", program_name, ifname)); return -3; } } WARN((stderr, "\n%s: %s: decompression OK, trailing garbage ignored\n", program_name, ifname)); return -2; } } /* ======================================================================== * Display the characteristics of the compressed file. * If the given method is < 0, display the accumulated totals. * IN assertions: time_stamp, header_bytes and ifile_size are initialized. */ local void do_list(ifd, method) int ifd; /* input file descriptor */ int method; /* compression method */ { ulg crc; /* original crc */ static int first_time = 1; static char const *const methods[MAX_METHODS] = { "store", /* 0 */ "compr", /* 1 */ "pack ", /* 2 */ "lzh ", /* 3 */ "", "", "", "", /* 4 to 7 reserved */ "defla"}; /* 8 */ int positive_off_t_width = 1; off_t o; for (o = OFF_T_MAX; 9 < o; o /= 10) { positive_off_t_width++; } if (first_time && method >= 0) { first_time = 0; if (verbose) { printf("method crc date time "); } if (!quiet) { printf("%*.*s %*.*s ratio uncompressed_name\n", positive_off_t_width, positive_off_t_width, "compressed", positive_off_t_width, positive_off_t_width, "uncompressed"); } } else if (method < 0) { if (total_in <= 0 || total_out <= 0) return; if (verbose) { printf(" "); } if (verbose || !quiet) { fprint_off(stdout, total_in, positive_off_t_width); printf(" "); fprint_off(stdout, total_out, positive_off_t_width); printf(" "); } display_ratio(total_out-(total_in-header_bytes), total_out, stdout); /* header_bytes is not meaningful but used to ensure the same * ratio if there is a single file. */ printf(" (totals)\n"); return; } crc = (ulg)~0; /* unknown */ bytes_out = -1L; bytes_in = ifile_size; #if RECORD_IO == 0 if (method == DEFLATED && !last_member) { /* Get the crc and uncompressed size for gzip'ed (not zip'ed) files. * If the lseek fails, we could use read() to get to the end, but * --list is used to get quick results. * Use "gunzip < foo.gz | wc -c" to get the uncompressed size if * you are not concerned about speed. */ bytes_in = lseek(ifd, (off_t)(-8), SEEK_END); if (bytes_in != -1L) { uch buf[8]; bytes_in += 8L; if (read(ifd, (char*)buf, sizeof(buf)) != sizeof(buf)) { read_error(); } crc = LG(buf); bytes_out = LG(buf+4); } } #endif /* RECORD_IO */ if (verbose) { struct tm *tm = localtime (&time_stamp.tv_sec); printf ("%5s %08lx ", methods[method], crc); if (tm) printf ("%s%3d %02d:%02d ", ("Jan\0Feb\0Mar\0Apr\0May\0Jun\0Jul\0Aug\0Sep\0Oct\0Nov\0Dec" + 4 * tm->tm_mon), tm->tm_mday, tm->tm_hour, tm->tm_min); else printf ("??? ?? ??:?? "); } fprint_off(stdout, bytes_in, positive_off_t_width); printf(" "); fprint_off(stdout, bytes_out, positive_off_t_width); printf(" "); if (bytes_in == -1L) { total_in = -1L; bytes_in = bytes_out = header_bytes = 0; } else if (total_in >= 0) { total_in += bytes_in; } if (bytes_out == -1L) { total_out = -1L; bytes_in = bytes_out = header_bytes = 0; } else if (total_out >= 0) { total_out += bytes_out; } display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out, stdout); printf(" %s\n", ofname); } /* ======================================================================== * Shorten the given name by one character, or replace a .tar extension * with .tgz. Truncate the last part of the name which is longer than * MIN_PART characters: 1234.678.012.gz -> 123.678.012.gz. If the name * has only parts shorter than MIN_PART truncate the longest part. * For decompression, just remove the last character of the name. * * IN assertion: for compression, the suffix of the given name is z_suffix. */ local void shorten_name(name) char *name; { int len; /* length of name without z_suffix */ char *trunc = NULL; /* character to be truncated */ int plen; /* current part length */ int min_part = MIN_PART; /* current minimum part length */ char *p; len = strlen(name); if (decompress) { if (len <= 1) gzip_error ("name too short"); name[len-1] = '\0'; return; } p = get_suffix(name); if (! p) gzip_error ("can't recover suffix\n"); *p = '\0'; save_orig_name = 1; /* compress 1234567890.tar to 1234567890.tgz */ if (len > 4 && strequ(p-4, ".tar")) { strcpy(p-4, ".tgz"); return; } /* Try keeping short extensions intact: * 1234.678.012.gz -> 123.678.012.gz */ do { p = strrchr(name, PATH_SEP); p = p ? p+1 : name; while (*p) { plen = strcspn(p, PART_SEP); p += plen; if (plen > min_part) trunc = p-1; if (*p) p++; } } while (trunc == NULL && --min_part != 0); if (trunc != NULL) { do { trunc[0] = trunc[1]; } while (*trunc++); trunc--; } else { trunc = strrchr(name, PART_SEP[0]); if (!trunc) gzip_error ("internal error in shorten_name"); if (trunc[1] == '\0') trunc--; /* force truncation */ } strcpy(trunc, z_suffix); } /* ======================================================================== * The compressed file already exists, so ask for confirmation. * Return ERROR if the file must be skipped. */ local int check_ofname() { /* Ask permission to overwrite the existing file */ if (!force) { int ok = 0; fprintf (stderr, "%s: %s already exists;", program_name, ofname); if (foreground && (presume_input_tty || isatty(fileno(stdin)))) { fprintf(stderr, " do you wish to overwrite (y or n)? "); fflush(stderr); ok = yesno(); } if (!ok) { fprintf(stderr, "\tnot overwritten\n"); if (exit_code == OK) exit_code = WARNING; return ERROR; } } if (xunlink (ofname)) { progerror(ofname); return ERROR; } return OK; } /* ======================================================================== * Copy modes, times, ownership from input file to output file. * IN assertion: to_stdout is false. */ local void copy_stat(ifstat) struct stat *ifstat; { mode_t mode = ifstat->st_mode & S_IRWXUGO; int r; #ifndef NO_UTIME struct timespec timespec[2]; timespec[0] = get_stat_atime (ifstat); timespec[1] = get_stat_mtime (ifstat); if (decompress && 0 <= time_stamp.tv_nsec && ! (timespec[1].tv_sec == time_stamp.tv_sec && timespec[1].tv_nsec == time_stamp.tv_nsec)) { timespec[1] = time_stamp; if (verbose > 1) { fprintf(stderr, "%s: time stamp restored\n", ofname); } } if (gl_futimens (ofd, ofname, timespec) != 0) { int e = errno; WARN ((stderr, "%s: ", program_name)); if (!quiet) { errno = e; perror (ofname); } } #endif #ifndef NO_CHOWN /* Copy ownership */ # if HAVE_FCHOWN ignore_value (fchown (ofd, ifstat->st_uid, ifstat->st_gid)); # elif HAVE_CHOWN ignore_value (chown (ofname, ifstat->st_uid, ifstat->st_gid)); # endif #endif /* Copy the protection modes */ #if HAVE_FCHMOD r = fchmod (ofd, mode); #else r = chmod (ofname, mode); #endif if (r != 0) { int e = errno; WARN ((stderr, "%s: ", program_name)); if (!quiet) { errno = e; perror(ofname); } } } #if ! NO_DIR /* ======================================================================== * Recurse through the given directory. This code is taken from ncompress. */ local void treat_dir (fd, dir) int fd; char *dir; { struct dirent *dp; DIR *dirp; char nbuf[MAX_PATH_LEN]; int len; dirp = fdopendir (fd); if (dirp == NULL) { progerror(dir); close (fd); return ; } /* ** WARNING: the following algorithm could occasionally cause ** compress to produce error warnings of the form "<filename>.gz ** already has .gz suffix - ignored". This occurs when the ** .gz output file is inserted into the directory below ** readdir's current pointer. ** These warnings are harmless but annoying, so they are suppressed ** with option -r (except when -v is on). An alternative ** to allowing this would be to store the entire directory ** list in memory, then compress the entries in the stored ** list. Given the depth-first recursive algorithm used here, ** this could use up a tremendous amount of memory. I don't ** think it's worth it. -- Dave Mack ** (An other alternative might be two passes to avoid depth-first.) */ while ((errno = 0, dp = readdir(dirp)) != NULL) { if (strequ(dp->d_name,".") || strequ(dp->d_name,"..")) { continue; } len = strlen(dir); if (len + _D_EXACT_NAMLEN (dp) + 1 < MAX_PATH_LEN - 1) { strcpy(nbuf,dir); if (len != 0 /* dir = "" means current dir on Amiga */ #ifdef PATH_SEP2 && dir[len-1] != PATH_SEP2 #endif #ifdef PATH_SEP3 && dir[len-1] != PATH_SEP3 #endif ) { nbuf[len++] = PATH_SEP; } strcpy(nbuf+len, dp->d_name); treat_file(nbuf); } else { fprintf(stderr,"%s: %s/%s: pathname too long\n", program_name, dir, dp->d_name); exit_code = ERROR; } } if (errno != 0) progerror(dir); if (CLOSEDIR(dirp) != 0) progerror(dir); } #endif /* ! NO_DIR */ /* Make sure signals get handled properly. */ static void install_signal_handlers () { int nsigs = sizeof handled_sig / sizeof handled_sig[0]; int i; #if SA_NOCLDSTOP struct sigaction act; sigemptyset (&caught_signals); for (i = 0; i < nsigs; i++) { sigaction (handled_sig[i], NULL, &act); if (act.sa_handler != SIG_IGN) sigaddset (&caught_signals, handled_sig[i]); } act.sa_handler = abort_gzip_signal; act.sa_mask = caught_signals; act.sa_flags = 0; for (i = 0; i < nsigs; i++) if (sigismember (&caught_signals, handled_sig[i])) { if (i == 0) foreground = 1; sigaction (handled_sig[i], &act, NULL); } #else for (i = 0; i < nsigs; i++) if (signal (handled_sig[i], SIG_IGN) != SIG_IGN) { if (i == 0) foreground = 1; signal (handled_sig[i], abort_gzip_signal); siginterrupt (handled_sig[i], 1); } #endif } /* ======================================================================== * Free all dynamically allocated variables and exit with the given code. */ local void do_exit(exitcode) int exitcode; { static int in_exit = 0; if (in_exit) exit(exitcode); in_exit = 1; free(env); env = NULL; free(args); args = NULL; FREE(inbuf); FREE(outbuf); FREE(d_buf); FREE(window); #ifndef MAXSEG_64K FREE(tab_prefix); #else FREE(tab_prefix0); FREE(tab_prefix1); #endif exit(exitcode); } /* ======================================================================== * Close and unlink the output file. */ static void remove_output_file () { int fd; sigset_t oldset; sigprocmask (SIG_BLOCK, &caught_signals, &oldset); fd = remove_ofname_fd; if (0 <= fd) { remove_ofname_fd = -1; close (fd); xunlink (ofname); } sigprocmask (SIG_SETMASK, &oldset, NULL); } /* ======================================================================== * Error handler. */ void abort_gzip () { remove_output_file (); do_exit(ERROR); } /* ======================================================================== * Signal handler. */ static RETSIGTYPE abort_gzip_signal (sig) int sig; { if (! SA_NOCLDSTOP) signal (sig, SIG_IGN); remove_output_file (); if (sig == exiting_signal) _exit (WARNING); signal (sig, SIG_DFL); raise (sig); } /* gzip (GNU zip) -- compress files with zip algorithm and 'compress' interface Copyright (C) 1999, 2001-2002, 2006-2007, 2009-2010 Free Software Foundation, Inc. Copyright (C) 1992-1993 Jean-loup Gailly This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * The unzip code was written and put in the public domain by Mark Adler. * Portions of the lzw code are derived from the public domain 'compress' * written by Spencer Thomas, Joe Orost, James Woods, Jim McKie, Steve Davies, * Ken Turkowski, Dave Mack and Peter Jannesen. * * See the license_msg below and the file COPYING for the software license. * See the file algorithm.doc for the compression algorithms and file formats. */ static char const *const license_msg[] = { "Copyright (C) 2007, 2010 Free Software Foundation, Inc.", "Copyright (C) 1993 Jean-loup Gailly.", "This is free software. You may redistribute copies of it under the terms of", "the GNU General Public License <http://www.gnu.org/licenses/gpl.html>.", "There is NO WARRANTY, to the extent permitted by law.", 0}; /* Compress files with zip algorithm and 'compress' interface. * See help() function below for all options. * Outputs: * file.gz: compressed file with same mode, owner, and utimes * or stdout with -c option or if stdin used as input. * If the output file name had to be truncated, the original name is kept * in the compressed file. * On MSDOS, file.tmp -> file.tmz. On VMS, file.tmp -> file.tmp-gz. * * Using gz on MSDOS would create too many file name conflicts. For * example, foo.txt -> foo.tgz (.tgz must be reserved as shorthand for * tar.gz). Similarly, foo.dir and foo.doc would both be mapped to foo.dgz. * I also considered 12345678.txt -> 12345txt.gz but this truncates the name * too heavily. There is no ideal solution given the MSDOS 8+3 limitation. * * For the meaning of all compilation flags, see comments in Makefile.in. */ #include <config.h> #include <ctype.h> #include <sys/types.h> #include <signal.h> #include <stdbool.h> #include <sys/stat.h> #include <errno.h> #include "closein.h" #include "tailor.h" #include "gzip.h" #include "lzw.h" #include "revision.h" #include "fcntl-safer.h" #include "getopt.h" #include "ignore-value.h" #include "stat-time.h" /* configuration */ #include <fcntl.h> #include <limits.h> #include <unistd.h> #include <stdlib.h> #include <errno.h> #ifndef NO_DIR # define NO_DIR 0 #endif #if !NO_DIR # include <dirent.h> # ifndef _D_EXACT_NAMLEN # define _D_EXACT_NAMLEN(dp) strlen ((dp)->d_name) # endif #endif #ifdef CLOSEDIR_VOID # define CLOSEDIR(d) (closedir(d), 0) #else # define CLOSEDIR(d) closedir(d) #endif #ifndef NO_UTIME # include <utimens.h> #endif #define RW_USER (S_IRUSR | S_IWUSR) /* creation mode for open() */ #ifndef MAX_PATH_LEN # define MAX_PATH_LEN 1024 /* max pathname length */ #endif #ifndef SEEK_END # define SEEK_END 2 #endif #ifndef CHAR_BIT # define CHAR_BIT 8 #endif #ifdef off_t off_t lseek OF((int fd, off_t offset, int whence)); #endif #ifndef OFF_T_MIN #define OFF_T_MIN (~ (off_t) 0 << (sizeof (off_t) * CHAR_BIT - 1)) #endif #ifndef OFF_T_MAX #define OFF_T_MAX (~ (off_t) 0 - OFF_T_MIN) #endif /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is present. */ #ifndef SA_NOCLDSTOP # define SA_NOCLDSTOP 0 # define sigprocmask(how, set, oset) /* empty */ # define sigset_t int # if ! HAVE_SIGINTERRUPT # define siginterrupt(sig, flag) /* empty */ # endif #endif #ifndef HAVE_WORKING_O_NOFOLLOW # define HAVE_WORKING_O_NOFOLLOW 0 #endif #ifndef ELOOP # define ELOOP EINVAL #endif /* Separator for file name parts (see shorten_name()) */ #ifdef NO_MULTIPLE_DOTS # define PART_SEP "-" #else # define PART_SEP "." #endif /* global buffers */ DECLARE(uch, inbuf, INBUFSIZ +INBUF_EXTRA); DECLARE(uch, outbuf, OUTBUFSIZ+OUTBUF_EXTRA); DECLARE(ush, d_buf, DIST_BUFSIZE); DECLARE(uch, window, 2L*WSIZE); #ifndef MAXSEG_64K DECLARE(ush, tab_prefix, 1L<<BITS); #else DECLARE(ush, tab_prefix0, 1L<<(BITS-1)); DECLARE(ush, tab_prefix1, 1L<<(BITS-1)); #endif /* local variables */ /* If true, pretend that standard input is a tty. This option is deliberately not documented, and only for testing. */ static bool presume_input_tty; int ascii = 0; /* convert end-of-lines to local OS conventions */ int to_stdout = 0; /* output to stdout (-c) */ int decompress = 0; /* decompress (-d) */ int force = 0; /* don't ask questions, compress links (-f) */ int no_name = -1; /* don't save or restore the original file name */ int no_time = -1; /* don't save or restore the original file time */ int recursive = 0; /* recurse through directories (-r) */ int list = 0; /* list the file contents (-l) */ int verbose = 0; /* be verbose (-v) */ int quiet = 0; /* be very quiet (-q) */ int do_lzw = 0; /* generate output compatible with old compress (-Z) */ int test = 0; /* test .gz file integrity */ int foreground = 0; /* set if program run in foreground */ char *program_name; /* program name */ int maxbits = BITS; /* max bits per code for LZW */ int method = DEFLATED;/* compression method */ int level = 6; /* compression level */ int exit_code = OK; /* program exit code */ int save_orig_name; /* set if original name must be saved */ int last_member; /* set for .zip and .Z files */ int part_nb; /* number of parts in .gz file */ struct timespec time_stamp; /* original time stamp (modification time) */ off_t ifile_size; /* input file size, -1 for devices (debug only) */ char *env; /* contents of GZIP env variable */ char **args = NULL; /* argv pointer if GZIP env variable defined */ char const *z_suffix; /* default suffix (can be set with --suffix) */ size_t z_len; /* strlen(z_suffix) */ /* The set of signals that are caught. */ static sigset_t caught_signals; /* If nonzero then exit with status WARNING, rather than with the usual signal status, on receipt of a signal with this value. This suppresses a "Broken Pipe" message with some shells. */ static int volatile exiting_signal; /* If nonnegative, close this file descriptor and unlink ofname on error. */ static int volatile remove_ofname_fd = -1; off_t bytes_in; /* number of input bytes */ off_t bytes_out; /* number of output bytes */ off_t total_in; /* input bytes for all files */ off_t total_out; /* output bytes for all files */ char ifname[MAX_PATH_LEN]; /* input file name */ char ofname[MAX_PATH_LEN]; /* output file name */ struct stat istat; /* status for input file */ int ifd; /* input file descriptor */ int ofd; /* output file descriptor */ unsigned insize; /* valid bytes in inbuf */ unsigned inptr; /* index of next byte to be processed in inbuf */ unsigned outcnt; /* bytes in output buffer */ static int handled_sig[] = { /* SIGINT must be first, as 'foreground' depends on it. */ SIGINT #ifdef SIGHUP , SIGHUP #endif #ifdef SIGPIPE , SIGPIPE #else # define SIGPIPE 0 #endif #ifdef SIGTERM , SIGTERM #endif #ifdef SIGXCPU , SIGXCPU #endif #ifdef SIGXFSZ , SIGXFSZ #endif }; /* For long options that have no equivalent short option, use a non-character as a pseudo short option, starting with CHAR_MAX + 1. */ enum { PRESUME_INPUT_TTY_OPTION = CHAR_MAX + 1 }; struct option longopts[] = { /* { name has_arg *flag val } */ {"ascii", 0, 0, 'a'}, /* ascii text mode */ {"to-stdout", 0, 0, 'c'}, /* write output on standard output */ {"stdout", 0, 0, 'c'}, /* write output on standard output */ {"decompress", 0, 0, 'd'}, /* decompress */ {"uncompress", 0, 0, 'd'}, /* decompress */ /* {"encrypt", 0, 0, 'e'}, encrypt */ {"force", 0, 0, 'f'}, /* force overwrite of output file */ {"help", 0, 0, 'h'}, /* give help */ /* {"pkzip", 0, 0, 'k'}, force output in pkzip format */ {"list", 0, 0, 'l'}, /* list .gz file contents */ {"license", 0, 0, 'L'}, /* display software license */ {"no-name", 0, 0, 'n'}, /* don't save or restore original name & time */ {"name", 0, 0, 'N'}, /* save or restore original name & time */ {"-presume-input-tty", no_argument, NULL, PRESUME_INPUT_TTY_OPTION}, {"quiet", 0, 0, 'q'}, /* quiet mode */ {"silent", 0, 0, 'q'}, /* quiet mode */ {"recursive", 0, 0, 'r'}, /* recurse through directories */ {"suffix", 1, 0, 'S'}, /* use given suffix instead of .gz */ {"test", 0, 0, 't'}, /* test compressed file integrity */ {"no-time", 0, 0, 'T'}, /* don't save or restore the time stamp */ {"verbose", 0, 0, 'v'}, /* verbose mode */ {"version", 0, 0, 'V'}, /* display version number */ {"fast", 0, 0, '1'}, /* compress faster */ {"best", 0, 0, '9'}, /* compress better */ {"lzw", 0, 0, 'Z'}, /* make output compatible with old compress */ {"bits", 1, 0, 'b'}, /* max number of bits per code (implies -Z) */ { 0, 0, 0, 0 } }; /* local functions */ local void try_help OF((void)) ATTRIBUTE_NORETURN; local void help OF((void)); local void license OF((void)); local void version OF((void)); local int input_eof OF((void)); local void treat_stdin OF((void)); local void treat_file OF((char *iname)); local int create_outfile OF((void)); local char *get_suffix OF((char *name)); local int open_input_file OF((char *iname, struct stat *sbuf)); local int make_ofname OF((void)); local void shorten_name OF((char *name)); local int get_method OF((int in)); local void do_list OF((int ifd, int method)); local int check_ofname OF((void)); local void copy_stat OF((struct stat *ifstat)); local void install_signal_handlers OF((void)); local void remove_output_file OF((void)); local RETSIGTYPE abort_gzip_signal OF((int)); local void do_exit OF((int exitcode)) ATTRIBUTE_NORETURN; int main OF((int argc, char **argv)); int (*work) OF((int infile, int outfile)) = zip; /* function to call */ #if ! NO_DIR local void treat_dir OF((int fd, char *dir)); #endif #define strequ(s1, s2) (strcmp((s1),(s2)) == 0) static void try_help () { fprintf (stderr, "Try `%s --help' for more information.\n", program_name); do_exit (ERROR); } /* ======================================================================== */ local void help() { static char const* const help_msg[] = { "Compress or uncompress FILEs (by default, compress FILES in-place).", "", "Mandatory arguments to long options are mandatory for short options too.", "", #if O_BINARY " -a, --ascii ascii text; convert end-of-line using local conventions", #endif " -c, --stdout write on standard output, keep original files unchanged", " -d, --decompress decompress", /* -e, --encrypt encrypt */ " -f, --force force overwrite of output file and compress links", " -h, --help give this help", /* -k, --pkzip force output in pkzip format */ " -l, --list list compressed file contents", " -L, --license display software license", #ifdef UNDOCUMENTED " -m, --no-time do not save or restore the original modification time", " -M, --time save or restore the original modification time", #endif " -n, --no-name do not save or restore the original name and time stamp", " -N, --name save or restore the original name and time stamp", " -q, --quiet suppress all warnings", #if ! NO_DIR " -r, --recursive operate recursively on directories", #endif " -S, --suffix=SUF use suffix SUF on compressed files", " -t, --test test compressed file integrity", " -v, --verbose verbose mode", " -V, --version display version number", " -1, --fast compress faster", " -9, --best compress better", #ifdef LZW " -Z, --lzw produce output compatible with old compress", " -b, --bits=BITS max number of bits per code (implies -Z)", #endif "", "With no FILE, or when FILE is -, read standard input.", "", "Report bugs to <[email protected]>.", 0}; char const *const *p = help_msg; printf ("Usage: %s [OPTION]... [FILE]...\n", program_name); while (*p) printf ("%s\n", *p++); } /* ======================================================================== */ local void license() { char const *const *p = license_msg; printf ("%s %s\n", program_name, VERSION); while (*p) printf ("%s\n", *p++); } /* ======================================================================== */ local void version() { license (); printf ("\n"); printf ("Written by Jean-loup Gailly.\n"); } local void progerror (char const *string) { int e = errno; fprintf (stderr, "%s: ", program_name); errno = e; perror(string); exit_code = ERROR; } /* ======================================================================== */ int main (int argc, char **argv) { int file_count; /* number of files to process */ size_t proglen; /* length of program_name */ int optc; /* current option */ EXPAND(argc, argv); /* wild card expansion if necessary */ program_name = gzip_base_name (argv[0]); proglen = strlen (program_name); atexit (close_stdin); /* Suppress .exe for MSDOS, OS/2 and VMS: */ if (4 < proglen && strequ (program_name + proglen - 4, ".exe")) program_name[proglen - 4] = '\0'; /* Add options in GZIP environment variable if there is one */ env = add_envopt(&argc, &argv, OPTIONS_VAR); if (env != NULL) args = argv; #ifndef GNU_STANDARD # define GNU_STANDARD 1 #endif #if !GNU_STANDARD /* For compatibility with old compress, use program name as an option. * Unless you compile with -DGNU_STANDARD=0, this program will behave as * gzip even if it is invoked under the name gunzip or zcat. * * Systems which do not support links can still use -d or -dc. * Ignore an .exe extension for MSDOS, OS/2 and VMS. */ if (strncmp (program_name, "un", 2) == 0 /* ungzip, uncompress */ || strncmp (program_name, "gun", 3) == 0) /* gunzip */ decompress = 1; else if (strequ (program_name + 1, "cat") /* zcat, pcat, gcat */ || strequ (program_name, "gzcat")) /* gzcat */ decompress = to_stdout = 1; #endif z_suffix = Z_SUFFIX; z_len = strlen(z_suffix); while ((optc = getopt_long (argc, argv, "ab:cdfhH?lLmMnNqrS:tvVZ123456789", longopts, (int *)0)) != -1) { switch (optc) { case 'a': ascii = 1; break; case 'b': maxbits = atoi(optarg); for (; *optarg; optarg++) if (! ('0' <= *optarg && *optarg <= '9')) { fprintf (stderr, "%s: -b operand is not an integer\n", program_name); try_help (); } break; case 'c': to_stdout = 1; break; case 'd': decompress = 1; break; case 'f': force++; break; case 'h': case 'H': help(); do_exit(OK); break; case 'l': list = decompress = to_stdout = 1; break; case 'L': license(); do_exit(OK); break; case 'm': /* undocumented, may change later */ no_time = 1; break; case 'M': /* undocumented, may change later */ no_time = 0; break; case 'n': no_name = no_time = 1; break; case 'N': no_name = no_time = 0; break; case PRESUME_INPUT_TTY_OPTION: presume_input_tty = true; break; case 'q': quiet = 1; verbose = 0; break; case 'r': #if NO_DIR fprintf (stderr, "%s: -r not supported on this system\n", program_name); try_help (); #else recursive = 1; #endif break; case 'S': #ifdef NO_MULTIPLE_DOTS if (*optarg == '.') optarg++; #endif z_len = strlen(optarg); z_suffix = optarg; break; case 't': test = decompress = to_stdout = 1; break; case 'v': verbose++; quiet = 0; break; case 'V': version(); do_exit(OK); break; case 'Z': #ifdef LZW do_lzw = 1; break; #else fprintf(stderr, "%s: -Z not supported in this version\n", program_name); try_help (); break; #endif case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': level = optc - '0'; break; default: /* Error message already emitted by getopt_long. */ try_help (); } } /* loop on all arguments */ /* By default, save name and timestamp on compression but do not * restore them on decompression. */ if (no_time < 0) no_time = decompress; if (no_name < 0) no_name = decompress; file_count = argc - optind; #if O_BINARY #else if (ascii && !quiet) { fprintf(stderr, "%s: option --ascii ignored on this system\n", program_name); } #endif if (z_len == 0 || z_len > MAX_SUFFIX) { fprintf(stderr, "%s: invalid suffix '%s'\n", program_name, z_suffix); do_exit(ERROR); } if (do_lzw && !decompress) work = lzw; /* Allocate all global buffers (for DYN_ALLOC option) */ ALLOC(uch, inbuf, INBUFSIZ +INBUF_EXTRA); ALLOC(uch, outbuf, OUTBUFSIZ+OUTBUF_EXTRA); ALLOC(ush, d_buf, DIST_BUFSIZE); ALLOC(uch, window, 2L*WSIZE); #ifndef MAXSEG_64K ALLOC(ush, tab_prefix, 1L<<BITS); #else ALLOC(ush, tab_prefix0, 1L<<(BITS-1)); ALLOC(ush, tab_prefix1, 1L<<(BITS-1)); #endif exiting_signal = quiet ? SIGPIPE : 0; install_signal_handlers (); /* And get to work */ if (file_count != 0) { if (to_stdout && !test && !list && (!decompress || !ascii)) { SET_BINARY_MODE(fileno(stdout)); } while (optind < argc) { treat_file(argv[optind++]); } } else { /* Standard input */ treat_stdin(); } if (list && !quiet && file_count > 1) { do_list(-1, -1); /* print totals */ } do_exit(exit_code); return exit_code; /* just to avoid lint warning */ } /* Return nonzero when at end of file on input. */ local int input_eof () { if (!decompress || last_member) return 1; if (inptr == insize) { if (insize != INBUFSIZ || fill_inbuf (1) == EOF) return 1; /* Unget the char that fill_inbuf got. */ inptr = 0; } return 0; } /* ======================================================================== * Compress or decompress stdin */ local void treat_stdin() { if (!force && !list && (presume_input_tty || isatty(fileno((FILE *)(decompress ? stdin : stdout))))) { /* Do not send compressed data to the terminal or read it from * the terminal. We get here when user invoked the program * without parameters, so be helpful. According to the GNU standards: * * If there is one behavior you think is most useful when the output * is to a terminal, and another that you think is most useful when * the output is a file or a pipe, then it is usually best to make * the default behavior the one that is useful with output to a * terminal, and have an option for the other behavior. * * Here we use the --force option to get the other behavior. */ fprintf(stderr, "%s: compressed data not %s a terminal. Use -f to force %scompression.\n", program_name, decompress ? "read from" : "written to", decompress ? "de" : ""); fprintf (stderr, "For help, type: %s -h\n", program_name); do_exit(ERROR); } if (decompress || !ascii) { SET_BINARY_MODE(fileno(stdin)); } if (!test && !list && (!decompress || !ascii)) { SET_BINARY_MODE(fileno(stdout)); } strcpy(ifname, "stdin"); strcpy(ofname, "stdout"); /* Get the file's time stamp and size. */ if (fstat (fileno (stdin), &istat) != 0) { progerror ("standard input"); do_exit (ERROR); } ifile_size = S_ISREG (istat.st_mode) ? istat.st_size : -1; time_stamp.tv_nsec = -1; if (!no_time || list) time_stamp = get_stat_mtime (&istat); clear_bufs(); /* clear input and output buffers */ to_stdout = 1; part_nb = 0; ifd = fileno(stdin); if (decompress) { method = get_method(ifd); if (method < 0) { do_exit(exit_code); /* error message already emitted */ } } if (list) { do_list(ifd, method); return; } /* Actually do the compression/decompression. Loop over zipped members. */ for (;;) { if ((*work)(fileno(stdin), fileno(stdout)) != OK) return; if (input_eof ()) break; method = get_method(ifd); if (method < 0) return; /* error message already emitted */ bytes_out = 0; /* required for length check */ } if (verbose) { if (test) { fprintf(stderr, " OK\n"); } else if (!decompress) { display_ratio(bytes_in-(bytes_out-header_bytes), bytes_in, stderr); fprintf(stderr, "\n"); #ifdef DISPLAY_STDIN_RATIO } else { display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out,stderr); fprintf(stderr, "\n"); #endif } } } /* ======================================================================== * Compress or decompress the given file */ local void treat_file(iname) char *iname; { /* Accept "-" as synonym for stdin */ if (strequ(iname, "-")) { int cflag = to_stdout; treat_stdin(); to_stdout = cflag; return; } /* Check if the input file is present, set ifname and istat: */ ifd = open_input_file (iname, &istat); if (ifd < 0) return; /* If the input name is that of a directory, recurse or ignore: */ if (S_ISDIR(istat.st_mode)) { #if ! NO_DIR if (recursive) { treat_dir (ifd, iname); /* Warning: ifname is now garbage */ return; } #endif close (ifd); WARN ((stderr, "%s: %s is a directory -- ignored\n", program_name, ifname)); return; } if (! to_stdout) { if (! S_ISREG (istat.st_mode)) { WARN ((stderr, "%s: %s is not a directory or a regular file - ignored\n", program_name, ifname)); close (ifd); return; } if (istat.st_mode & S_ISUID) { WARN ((stderr, "%s: %s is set-user-ID on execution - ignored\n", program_name, ifname)); close (ifd); return; } if (istat.st_mode & S_ISGID) { WARN ((stderr, "%s: %s is set-group-ID on execution - ignored\n", program_name, ifname)); close (ifd); return; } if (! force) { if (istat.st_mode & S_ISVTX) { WARN ((stderr, "%s: %s has the sticky bit set - file ignored\n", program_name, ifname)); close (ifd); return; } if (2 <= istat.st_nlink) { WARN ((stderr, "%s: %s has %lu other link%c -- unchanged\n", program_name, ifname, (unsigned long int) istat.st_nlink - 1, istat.st_nlink == 2 ? ' ' : 's')); close (ifd); return; } } } ifile_size = S_ISREG (istat.st_mode) ? istat.st_size : -1; time_stamp.tv_nsec = -1; if (!no_time || list) time_stamp = get_stat_mtime (&istat); /* Generate output file name. For -r and (-t or -l), skip files * without a valid gzip suffix (check done in make_ofname). */ if (to_stdout && !list && !test) { strcpy(ofname, "stdout"); } else if (make_ofname() != OK) { close (ifd); return; } clear_bufs(); /* clear input and output buffers */ part_nb = 0; if (decompress) { method = get_method(ifd); /* updates ofname if original given */ if (method < 0) { close(ifd); return; /* error message already emitted */ } } if (list) { do_list(ifd, method); if (close (ifd) != 0) read_error (); return; } /* If compressing to a file, check if ofname is not ambiguous * because the operating system truncates names. Otherwise, generate * a new ofname and save the original name in the compressed file. */ if (to_stdout) { ofd = fileno(stdout); /* Keep remove_ofname_fd negative. */ } else { if (create_outfile() != OK) return; if (!decompress && save_orig_name && !verbose && !quiet) { fprintf(stderr, "%s: %s compressed to %s\n", program_name, ifname, ofname); } } /* Keep the name even if not truncated except with --no-name: */ if (!save_orig_name) save_orig_name = !no_name; if (verbose) { fprintf(stderr, "%s:\t", ifname); } /* Actually do the compression/decompression. Loop over zipped members. */ for (;;) { if ((*work)(ifd, ofd) != OK) { method = -1; /* force cleanup */ break; } if (input_eof ()) break; method = get_method(ifd); if (method < 0) break; /* error message already emitted */ bytes_out = 0; /* required for length check */ } if (close (ifd) != 0) read_error (); if (!to_stdout) { sigset_t oldset; int unlink_errno; copy_stat (&istat); if (close (ofd) != 0) write_error (); sigprocmask (SIG_BLOCK, &caught_signals, &oldset); remove_ofname_fd = -1; unlink_errno = xunlink (ifname) == 0 ? 0 : errno; sigprocmask (SIG_SETMASK, &oldset, NULL); if (unlink_errno) { WARN ((stderr, "%s: ", program_name)); if (!quiet) { errno = unlink_errno; perror (ifname); } } } if (method == -1) { if (!to_stdout) remove_output_file (); return; } /* Display statistics */ if(verbose) { if (test) { fprintf(stderr, " OK"); } else if (decompress) { display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out,stderr); } else { display_ratio(bytes_in-(bytes_out-header_bytes), bytes_in, stderr); } if (!test && !to_stdout) { fprintf(stderr, " -- replaced with %s", ofname); } fprintf(stderr, "\n"); } } /* ======================================================================== * Create the output file. Return OK or ERROR. * Try several times if necessary to avoid truncating the z_suffix. For * example, do not create a compressed file of name "1234567890123." * Sets save_orig_name to true if the file name has been truncated. * IN assertions: the input file has already been open (ifd is set) and * ofname has already been updated if there was an original name. * OUT assertions: ifd and ofd are closed in case of error. */ local int create_outfile() { int name_shortened = 0; int flags = (O_WRONLY | O_CREAT | O_EXCL | (ascii && decompress ? 0 : O_BINARY)); for (;;) { int open_errno; sigset_t oldset; sigprocmask (SIG_BLOCK, &caught_signals, &oldset); remove_ofname_fd = ofd = OPEN (ofname, flags, RW_USER); open_errno = errno; sigprocmask (SIG_SETMASK, &oldset, NULL); if (0 <= ofd) break; switch (open_errno) { #ifdef ENAMETOOLONG case ENAMETOOLONG: shorten_name (ofname); name_shortened = 1; break; #endif case EEXIST: if (check_ofname () != OK) { close (ifd); return ERROR; } break; default: progerror (ofname); close (ifd); return ERROR; } } if (name_shortened && decompress) { /* name might be too long if an original name was saved */ WARN ((stderr, "%s: %s: warning, name truncated\n", program_name, ofname)); } return OK; } /* ======================================================================== * Return a pointer to the 'z' suffix of a file name, or NULL. For all * systems, ".gz", ".z", ".Z", ".taz", ".tgz", "-gz", "-z" and "_z" are * accepted suffixes, in addition to the value of the --suffix option. * ".tgz" is a useful convention for tar.z files on systems limited * to 3 characters extensions. On such systems, ".?z" and ".??z" are * also accepted suffixes. For Unix, we do not want to accept any * .??z suffix as indicating a compressed file; some people use .xyz * to denote volume data. * On systems allowing multiple versions of the same file (such as VMS), * this function removes any version suffix in the given name. */ local char *get_suffix(name) char *name; { int nlen, slen; char suffix[MAX_SUFFIX+3]; /* last chars of name, forced to lower case */ static char const *known_suffixes[] = {NULL, ".gz", ".z", ".taz", ".tgz", "-gz", "-z", "_z", #ifdef MAX_EXT_CHARS "z", #endif NULL}; char const **suf = known_suffixes; *suf = z_suffix; if (strequ(z_suffix, "z")) suf++; /* check long suffixes first */ #ifdef SUFFIX_SEP /* strip a version number from the file name */ { char *v = strrchr(name, SUFFIX_SEP); if (v != NULL) *v = '\0'; } #endif nlen = strlen(name); if (nlen <= MAX_SUFFIX+2) { strcpy(suffix, name); } else { strcpy(suffix, name+nlen-MAX_SUFFIX-2); } strlwr(suffix); slen = strlen(suffix); do { int s = strlen(*suf); if (slen > s && suffix[slen-s-1] != PATH_SEP && strequ(suffix + slen - s, *suf)) { return name+nlen-s; } } while (*++suf != NULL); return NULL; } /* Open file NAME with the given flags and mode and store its status into *ST. Return a file descriptor to the newly opened file, or -1 (setting errno) on failure. */ static int open_and_stat (char *name, int flags, mode_t mode, struct stat *st) { int fd; /* Refuse to follow symbolic links unless -c or -f. */ if (!to_stdout && !force) { if (HAVE_WORKING_O_NOFOLLOW) flags |= O_NOFOLLOW; else { #if HAVE_LSTAT || defined lstat if (lstat (name, st) != 0) return -1; else if (S_ISLNK (st->st_mode)) { errno = ELOOP; return -1; } #endif } } fd = OPEN (name, flags, mode); if (0 <= fd && fstat (fd, st) != 0) { int e = errno; close (fd); errno = e; return -1; } return fd; } /* ======================================================================== * Set ifname to the input file name (with a suffix appended if necessary) * and istat to its stats. For decompression, if no file exists with the * original name, try adding successively z_suffix, .gz, .z, -z and .Z. * For MSDOS, we try only z_suffix and z. * Return an open file descriptor or -1. */ static int open_input_file (iname, sbuf) char *iname; struct stat *sbuf; { int ilen; /* strlen(ifname) */ int z_suffix_errno = 0; static char const *suffixes[] = {NULL, ".gz", ".z", "-z", ".Z", NULL}; char const **suf = suffixes; char const *s; #ifdef NO_MULTIPLE_DOTS char *dot; /* pointer to ifname extension, or NULL */ #endif int fd; int open_flags = (O_RDONLY | O_NONBLOCK | O_NOCTTY | (ascii && !decompress ? 0 : O_BINARY)); *suf = z_suffix; if (sizeof ifname - 1 <= strlen (iname)) goto name_too_long; strcpy(ifname, iname); /* If input file exists, return OK. */ fd = open_and_stat (ifname, open_flags, RW_USER, sbuf); if (0 <= fd) return fd; if (!decompress || errno != ENOENT) { progerror(ifname); return -1; } /* file.ext doesn't exist, try adding a suffix (after removing any * version number for VMS). */ s = get_suffix(ifname); if (s != NULL) { progerror(ifname); /* ifname already has z suffix and does not exist */ return -1; } #ifdef NO_MULTIPLE_DOTS dot = strrchr(ifname, '.'); if (dot == NULL) { strcat(ifname, "."); dot = strrchr(ifname, '.'); } #endif ilen = strlen(ifname); if (strequ(z_suffix, ".gz")) suf++; /* Search for all suffixes */ do { char const *s0 = s = *suf; strcpy (ifname, iname); #ifdef NO_MULTIPLE_DOTS if (*s == '.') s++; if (*dot == '\0') strcpy (dot, "."); #endif #ifdef MAX_EXT_CHARS if (MAX_EXT_CHARS < strlen (s) + strlen (dot + 1)) dot[MAX_EXT_CHARS + 1 - strlen (s)] = '\0'; #endif if (sizeof ifname <= ilen + strlen (s)) goto name_too_long; strcat(ifname, s); fd = open_and_stat (ifname, open_flags, RW_USER, sbuf); if (0 <= fd) return fd; if (errno != ENOENT) { progerror (ifname); return -1; } if (strequ (s0, z_suffix)) z_suffix_errno = errno; } while (*++suf != NULL); /* No suffix found, complain using z_suffix: */ strcpy(ifname, iname); #ifdef NO_MULTIPLE_DOTS if (*dot == '\0') strcpy(dot, "."); #endif #ifdef MAX_EXT_CHARS if (MAX_EXT_CHARS < z_len + strlen (dot + 1)) dot[MAX_EXT_CHARS + 1 - z_len] = '\0'; #endif strcat(ifname, z_suffix); errno = z_suffix_errno; progerror(ifname); return -1; name_too_long: fprintf (stderr, "%s: %s: file name too long\n", program_name, iname); exit_code = ERROR; return -1; } /* ======================================================================== * Generate ofname given ifname. Return OK, or WARNING if file must be skipped. * Sets save_orig_name to true if the file name has been truncated. */ local int make_ofname() { char *suff; /* ofname z suffix */ strcpy(ofname, ifname); /* strip a version number if any and get the gzip suffix if present: */ suff = get_suffix(ofname); if (decompress) { if (suff == NULL) { /* With -t or -l, try all files (even without .gz suffix) * except with -r (behave as with just -dr). */ if (!recursive && (list || test)) return OK; /* Avoid annoying messages with -r */ if (verbose || (!recursive && !quiet)) { WARN((stderr,"%s: %s: unknown suffix -- ignored\n", program_name, ifname)); } return WARNING; } /* Make a special case for .tgz and .taz: */ strlwr(suff); if (strequ(suff, ".tgz") || strequ(suff, ".taz")) { strcpy(suff, ".tar"); } else { *suff = '\0'; /* strip the z suffix */ } /* ofname might be changed later if infile contains an original name */ } else if (suff && ! force) { /* Avoid annoying messages with -r (see treat_dir()) */ if (verbose || (!recursive && !quiet)) { /* Don't use WARN, as it affects exit status. */ fprintf (stderr, "%s: %s already has %s suffix -- unchanged\n", program_name, ifname, suff); } return WARNING; } else { save_orig_name = 0; #ifdef NO_MULTIPLE_DOTS suff = strrchr(ofname, '.'); if (suff == NULL) { if (sizeof ofname <= strlen (ofname) + 1) goto name_too_long; strcat(ofname, "."); # ifdef MAX_EXT_CHARS if (strequ(z_suffix, "z")) { if (sizeof ofname <= strlen (ofname) + 2) goto name_too_long; strcat(ofname, "gz"); /* enough room */ return OK; } /* On the Atari and some versions of MSDOS, * ENAMETOOLONG does not work correctly. So we * must truncate here. */ } else if (strlen(suff)-1 + z_len > MAX_SUFFIX) { suff[MAX_SUFFIX+1-z_len] = '\0'; save_orig_name = 1; # endif } #endif /* NO_MULTIPLE_DOTS */ if (sizeof ofname <= strlen (ofname) + z_len) goto name_too_long; strcat(ofname, z_suffix); } /* decompress ? */ return OK; name_too_long: WARN ((stderr, "%s: %s: file name too long\n", program_name, ifname)); return WARNING; } /* ======================================================================== * Check the magic number of the input file and update ofname if an * original name was given and to_stdout is not set. * Return the compression method, -1 for error, -2 for warning. * Set inptr to the offset of the next byte to be processed. * Updates time_stamp if there is one and --no-time is not used. * This function may be called repeatedly for an input file consisting * of several contiguous gzip'ed members. * IN assertions: there is at least one remaining compressed member. * If the member is a zip file, it must be the only one. */ local int get_method(in) int in; /* input file descriptor */ { uch flags; /* compression flags */ char magic[2]; /* magic header */ int imagic0; /* first magic byte or EOF */ int imagic1; /* like magic[1], but can represent EOF */ ulg stamp; /* time stamp */ /* If --force and --stdout, zcat == cat, so do not complain about * premature end of file: use try_byte instead of get_byte. */ if (force && to_stdout) { imagic0 = try_byte(); magic[0] = (char) imagic0; imagic1 = try_byte (); magic[1] = (char) imagic1; /* If try_byte returned EOF, magic[1] == (char) EOF. */ } else { magic[0] = (char)get_byte(); imagic0 = 0; if (magic[0]) { magic[1] = (char)get_byte(); imagic1 = 0; /* avoid lint warning */ } else { imagic1 = try_byte (); magic[1] = (char) imagic1; } } method = -1; /* unknown yet */ part_nb++; /* number of parts in gzip file */ header_bytes = 0; last_member = RECORD_IO; /* assume multiple members in gzip file except for record oriented I/O */ if (memcmp(magic, GZIP_MAGIC, 2) == 0 || memcmp(magic, OLD_GZIP_MAGIC, 2) == 0) { method = (int)get_byte(); if (method != DEFLATED) { fprintf(stderr, "%s: %s: unknown method %d -- not supported\n", program_name, ifname, method); exit_code = ERROR; return -1; } work = unzip; flags = (uch)get_byte(); if ((flags & ENCRYPTED) != 0) { fprintf(stderr, "%s: %s is encrypted -- not supported\n", program_name, ifname); exit_code = ERROR; return -1; } if ((flags & CONTINUATION) != 0) { fprintf(stderr, "%s: %s is a multi-part gzip file -- not supported\n", program_name, ifname); exit_code = ERROR; if (force <= 1) return -1; } if ((flags & RESERVED) != 0) { fprintf(stderr, "%s: %s has flags 0x%x -- not supported\n", program_name, ifname, flags); exit_code = ERROR; if (force <= 1) return -1; } stamp = (ulg)get_byte(); stamp |= ((ulg)get_byte()) << 8; stamp |= ((ulg)get_byte()) << 16; stamp |= ((ulg)get_byte()) << 24; if (stamp != 0 && !no_time) { time_stamp.tv_sec = stamp; time_stamp.tv_nsec = 0; } (void)get_byte(); /* Ignore extra flags for the moment */ (void)get_byte(); /* Ignore OS type for the moment */ if ((flags & CONTINUATION) != 0) { unsigned part = (unsigned)get_byte(); part |= ((unsigned)get_byte())<<8; if (verbose) { fprintf(stderr,"%s: %s: part number %u\n", program_name, ifname, part); } } if ((flags & EXTRA_FIELD) != 0) { unsigned len = (unsigned)get_byte(); len |= ((unsigned)get_byte())<<8; if (verbose) { fprintf(stderr,"%s: %s: extra field of %u bytes ignored\n", program_name, ifname, len); } while (len--) (void)get_byte(); } /* Get original file name if it was truncated */ if ((flags & ORIG_NAME) != 0) { if (no_name || (to_stdout && !list) || part_nb > 1) { /* Discard the old name */ char c; /* dummy used for NeXTstep 3.0 cc optimizer bug */ do {c=get_byte();} while (c != 0); } else { /* Copy the base name. Keep a directory prefix intact. */ char *p = gzip_base_name (ofname); char *base = p; for (;;) { *p = (char)get_char(); if (*p++ == '\0') break; if (p >= ofname+sizeof(ofname)) { gzip_error ("corrupted input -- file name too large"); } } p = gzip_base_name (base); memmove (base, p, strlen (p) + 1); /* If necessary, adapt the name to local OS conventions: */ if (!list) { MAKE_LEGAL_NAME(base); if (base) list=0; /* avoid warning about unused variable */ } } /* no_name || to_stdout */ } /* ORIG_NAME */ /* Discard file comment if any */ if ((flags & COMMENT) != 0) { while (get_char() != 0) /* null */ ; } if (part_nb == 1) { header_bytes = inptr + 2*sizeof(long); /* include crc and size */ } } else if (memcmp(magic, PKZIP_MAGIC, 2) == 0 && inptr == 2 && memcmp((char*)inbuf, PKZIP_MAGIC, 4) == 0) { /* To simplify the code, we support a zip file when alone only. * We are thus guaranteed that the entire local header fits in inbuf. */ inptr = 0; work = unzip; if (check_zipfile(in) != OK) return -1; /* check_zipfile may get ofname from the local header */ last_member = 1; } else if (memcmp(magic, PACK_MAGIC, 2) == 0) { work = unpack; method = PACKED; } else if (memcmp(magic, LZW_MAGIC, 2) == 0) { work = unlzw; method = COMPRESSED; last_member = 1; } else if (memcmp(magic, LZH_MAGIC, 2) == 0) { work = unlzh; method = LZHED; last_member = 1; } else if (force && to_stdout && !list) { /* pass input unchanged */ method = STORED; work = copy; if (imagic1 != EOF) inptr--; last_member = 1; if (imagic0 != EOF) { write_buf(fileno(stdout), magic, 1); bytes_out++; } } if (method >= 0) return method; if (part_nb == 1) { fprintf (stderr, "\n%s: %s: not in gzip format\n", program_name, ifname); exit_code = ERROR; return -1; } else { if (magic[0] == 0) { int inbyte; for (inbyte = imagic1; inbyte == 0; inbyte = try_byte ()) continue; if (inbyte == EOF) { if (verbose) WARN ((stderr, "\n%s: %s: decompression OK, trailing zero bytes ignored\n", program_name, ifname)); return -3; } } WARN((stderr, "\n%s: %s: decompression OK, trailing garbage ignored\n", program_name, ifname)); return -2; } } /* ======================================================================== * Display the characteristics of the compressed file. * If the given method is < 0, display the accumulated totals. * IN assertions: time_stamp, header_bytes and ifile_size are initialized. */ local void do_list(ifd, method) int ifd; /* input file descriptor */ int method; /* compression method */ { ulg crc; /* original crc */ static int first_time = 1; static char const *const methods[MAX_METHODS] = { "store", /* 0 */ "compr", /* 1 */ "pack ", /* 2 */ "lzh ", /* 3 */ "", "", "", "", /* 4 to 7 reserved */ "defla"}; /* 8 */ int positive_off_t_width = 1; off_t o; for (o = OFF_T_MAX; 9 < o; o /= 10) { positive_off_t_width++; } if (first_time && method >= 0) { first_time = 0; if (verbose) { printf("method crc date time "); } if (!quiet) { printf("%*.*s %*.*s ratio uncompressed_name\n", positive_off_t_width, positive_off_t_width, "compressed", positive_off_t_width, positive_off_t_width, "uncompressed"); } } else if (method < 0) { if (total_in <= 0 || total_out <= 0) return; if (verbose) { printf(" "); } if (verbose || !quiet) { fprint_off(stdout, total_in, positive_off_t_width); printf(" "); fprint_off(stdout, total_out, positive_off_t_width); printf(" "); } display_ratio(total_out-(total_in-header_bytes), total_out, stdout); /* header_bytes is not meaningful but used to ensure the same * ratio if there is a single file. */ printf(" (totals)\n"); return; } crc = (ulg)~0; /* unknown */ bytes_out = -1L; bytes_in = ifile_size; #if RECORD_IO == 0 if (method == DEFLATED && !last_member) { /* Get the crc and uncompressed size for gzip'ed (not zip'ed) files. * If the lseek fails, we could use read() to get to the end, but * --list is used to get quick results. * Use "gunzip < foo.gz | wc -c" to get the uncompressed size if * you are not concerned about speed. */ bytes_in = lseek(ifd, (off_t)(-8), SEEK_END); if (bytes_in != -1L) { uch buf[8]; bytes_in += 8L; if (read(ifd, (char*)buf, sizeof(buf)) != sizeof(buf)) { read_error(); } crc = LG(buf); bytes_out = LG(buf+4); } } #endif /* RECORD_IO */ if (verbose) { struct tm *tm = localtime (&time_stamp.tv_sec); printf ("%5s %08lx ", methods[method], crc); if (tm) printf ("%s%3d %02d:%02d ", ("Jan\0Feb\0Mar\0Apr\0May\0Jun\0Jul\0Aug\0Sep\0Oct\0Nov\0Dec" + 4 * tm->tm_mon), tm->tm_mday, tm->tm_hour, tm->tm_min); else printf ("??? ?? ??:?? "); } fprint_off(stdout, bytes_in, positive_off_t_width); printf(" "); fprint_off(stdout, bytes_out, positive_off_t_width); printf(" "); if (bytes_in == -1L) { total_in = -1L; bytes_in = bytes_out = header_bytes = 0; } else if (total_in >= 0) { total_in += bytes_in; } if (bytes_out == -1L) { total_out = -1L; bytes_in = bytes_out = header_bytes = 0; } else if (total_out >= 0) { total_out += bytes_out; } display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out, stdout); printf(" %s\n", ofname); } /* ======================================================================== * Shorten the given name by one character, or replace a .tar extension * with .tgz. Truncate the last part of the name which is longer than * MIN_PART characters: 1234.678.012.gz -> 123.678.012.gz. If the name * has only parts shorter than MIN_PART truncate the longest part. * For decompression, just remove the last character of the name. * * IN assertion: for compression, the suffix of the given name is z_suffix. */ local void shorten_name(name) char *name; { int len; /* length of name without z_suffix */ char *trunc = NULL; /* character to be truncated */ int plen; /* current part length */ int min_part = MIN_PART; /* current minimum part length */ char *p; len = strlen(name); if (decompress) { if (len <= 1) gzip_error ("name too short"); name[len-1] = '\0'; return; } p = get_suffix(name); if (! p) gzip_error ("can't recover suffix\n"); *p = '\0'; save_orig_name = 1; /* compress 1234567890.tar to 1234567890.tgz */ if (len > 4 && strequ(p-4, ".tar")) { strcpy(p-4, ".tgz"); return; } /* Try keeping short extensions intact: * 1234.678.012.gz -> 123.678.012.gz */ do { p = strrchr(name, PATH_SEP); p = p ? p+1 : name; while (*p) { plen = strcspn(p, PART_SEP); p += plen; if (plen > min_part) trunc = p-1; if (*p) p++; } } while (trunc == NULL && --min_part != 0); if (trunc != NULL) { do { trunc[0] = trunc[1]; } while (*trunc++); trunc--; } else { trunc = strrchr(name, PART_SEP[0]); if (!trunc) gzip_error ("internal error in shorten_name"); if (trunc[1] == '\0') trunc--; /* force truncation */ } strcpy(trunc, z_suffix); } /* ======================================================================== * The compressed file already exists, so ask for confirmation. * Return ERROR if the file must be skipped. */ local int check_ofname() { /* Ask permission to overwrite the existing file */ if (!force) { int ok = 0; fprintf (stderr, "%s: %s already exists;", program_name, ofname); if (foreground && (presume_input_tty || isatty(fileno(stdin)))) { fprintf(stderr, " do you wish to overwrite (y or n)? "); fflush(stderr); ok = yesno(); } if (!ok) { fprintf(stderr, "\tnot overwritten\n"); if (exit_code == OK) exit_code = WARNING; return ERROR; } } if (xunlink (ofname)) { progerror(ofname); return ERROR; } return OK; } /* ======================================================================== * Copy modes, times, ownership from input file to output file. * IN assertion: to_stdout is false. */ local void copy_stat(ifstat) struct stat *ifstat; { mode_t mode = ifstat->st_mode & S_IRWXUGO; int r; #ifndef NO_UTIME struct timespec timespec[2]; timespec[0] = get_stat_atime (ifstat); timespec[1] = get_stat_mtime (ifstat); if (decompress && 0 <= time_stamp.tv_nsec && ! (timespec[1].tv_sec == time_stamp.tv_sec && timespec[1].tv_nsec == time_stamp.tv_nsec)) { timespec[1] = time_stamp; if (verbose > 1) { fprintf(stderr, "%s: time stamp restored\n", ofname); } } if (gl_futimens (ofd, ofname, timespec) != 0) { int e = errno; WARN ((stderr, "%s: ", program_name)); if (!quiet) { errno = e; perror (ofname); } } #endif #ifndef NO_CHOWN /* Copy ownership */ # if HAVE_FCHOWN ignore_value (fchown (ofd, ifstat->st_uid, ifstat->st_gid)); # elif HAVE_CHOWN ignore_value (chown (ofname, ifstat->st_uid, ifstat->st_gid)); # endif #endif /* Copy the protection modes */ #if HAVE_FCHMOD r = fchmod (ofd, mode); #else r = chmod (ofname, mode); #endif if (r != 0) { int e = errno; WARN ((stderr, "%s: ", program_name)); if (!quiet) { errno = e; perror(ofname); } } } #if ! NO_DIR /* ======================================================================== * Recurse through the given directory. This code is taken from ncompress. */ local void treat_dir (fd, dir) int fd; char *dir; { struct dirent *dp; DIR *dirp; char nbuf[MAX_PATH_LEN]; int len; dirp = fdopendir (fd); if (dirp == NULL) { progerror(dir); close (fd); return ; } /* ** WARNING: the following algorithm could occasionally cause ** compress to produce error warnings of the form "<filename>.gz ** already has .gz suffix - ignored". This occurs when the ** .gz output file is inserted into the directory below ** readdir's current pointer. ** These warnings are harmless but annoying, so they are suppressed ** with option -r (except when -v is on). An alternative ** to allowing this would be to store the entire directory ** list in memory, then compress the entries in the stored ** list. Given the depth-first recursive algorithm used here, ** this could use up a tremendous amount of memory. I don't ** think it's worth it. -- Dave Mack ** (An other alternative might be two passes to avoid depth-first.) */ while ((errno = 0, dp = readdir(dirp)) != NULL) { if (strequ(dp->d_name,".") || strequ(dp->d_name,"..")) { continue; } len = strlen(dir); if (len + _D_EXACT_NAMLEN (dp) + 1 < MAX_PATH_LEN - 1) { strcpy(nbuf,dir); if (len != 0 /* dir = "" means current dir on Amiga */ #ifdef PATH_SEP2 && dir[len-1] != PATH_SEP2 #endif #ifdef PATH_SEP3 && dir[len-1] != PATH_SEP3 #endif ) { nbuf[len++] = PATH_SEP; } strcpy(nbuf+len, dp->d_name); treat_file(nbuf); } else { fprintf(stderr,"%s: %s/%s: pathname too long\n", program_name, dir, dp->d_name); exit_code = ERROR; } } if (errno != 0) progerror(dir); if (CLOSEDIR(dirp) != 0) progerror(dir); } #endif /* ! NO_DIR */ /* Make sure signals get handled properly. */ static void install_signal_handlers () { int nsigs = sizeof handled_sig / sizeof handled_sig[0]; int i; #if SA_NOCLDSTOP struct sigaction act; sigemptyset (&caught_signals); for (i = 0; i < nsigs; i++) { sigaction (handled_sig[i], NULL, &act); if (act.sa_handler != SIG_IGN) sigaddset (&caught_signals, handled_sig[i]); } act.sa_handler = abort_gzip_signal; act.sa_mask = caught_signals; act.sa_flags = 0; for (i = 0; i < nsigs; i++) if (sigismember (&caught_signals, handled_sig[i])) { if (i == 0) foreground = 1; sigaction (handled_sig[i], &act, NULL); } #else for (i = 0; i < nsigs; i++) if (signal (handled_sig[i], SIG_IGN) != SIG_IGN) { if (i == 0) foreground = 1; signal (handled_sig[i], abort_gzip_signal); siginterrupt (handled_sig[i], 1); } #endif } /* ======================================================================== * Free all dynamically allocated variables and exit with the given code. */ local void do_exit(exitcode) int exitcode; { static int in_exit = 0; if (in_exit) exit(exitcode); in_exit = 1; free(env); env = NULL; free(args); args = NULL; FREE(inbuf); FREE(outbuf); FREE(d_buf); FREE(window); #ifndef MAXSEG_64K FREE(tab_prefix); #else FREE(tab_prefix0); FREE(tab_prefix1); #endif exit(exitcode); } /* ======================================================================== * Close and unlink the output file. */ static void remove_output_file () { int fd; sigset_t oldset; sigprocmask (SIG_BLOCK, &caught_signals, &oldset); fd = remove_ofname_fd; if (0 <= fd) { remove_ofname_fd = -1; close (fd); xunlink (ofname); } sigprocmask (SIG_SETMASK, &oldset, NULL); } /* ======================================================================== * Error handler. */ void abort_gzip () { remove_output_file (); do_exit(ERROR); } /* ======================================================================== * Signal handler. */ static RETSIGTYPE abort_gzip_signal (sig) int sig; { if (! SA_NOCLDSTOP) signal (sig, SIG_IGN); remove_output_file (); if (sig == exiting_signal) _exit (WARNING); signal (sig, SIG_DFL); raise (sig); }
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/gzip_2010-02-19-3eb6091d69-884ef6d16c.c
manybugs_data_28
#include <ctype.h> #include <stdlib.h> #include <string.h> #include "base.h" #include "log.h" #include "buffer.h" #include "plugin.h" #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef USE_OPENSSL # include <openssl/md5.h> #else # include "md5.h" #endif #define HASHLEN 16 typedef unsigned char HASH[HASHLEN]; #define HASHHEXLEN 32 typedef char HASHHEX[HASHHEXLEN+1]; #ifdef USE_OPENSSL #define IN const #else #define IN #endif #define OUT /* plugin config for all request/connections */ typedef struct { buffer *doc_root; buffer *secret; buffer *uri_prefix; unsigned short timeout; } plugin_config; typedef struct { PLUGIN_DATA; buffer *md5; plugin_config **config_storage; plugin_config conf; } plugin_data; /* init the plugin data */ INIT_FUNC(mod_secdownload_init) { plugin_data *p; UNUSED(srv); p = calloc(1, sizeof(*p)); p->md5 = buffer_init(); return p; } /* detroy the plugin data */ FREE_FUNC(mod_secdownload_free) { plugin_data *p = p_d; UNUSED(srv); if (!p) return HANDLER_GO_ON; if (p->config_storage) { size_t i; for (i = 0; i < srv->config_context->used; i++) { plugin_config *s = p->config_storage[i]; buffer_free(s->secret); buffer_free(s->doc_root); buffer_free(s->uri_prefix); free(s); } free(p->config_storage); } buffer_free(p->md5); free(p); return HANDLER_GO_ON; } /* handle plugin config and check values */ SETDEFAULTS_FUNC(mod_secdownload_set_defaults) { plugin_data *p = p_d; size_t i = 0; config_values_t cv[] = { { "secdownload.secret", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 0 */ { "secdownload.document-root", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 1 */ { "secdownload.uri-prefix", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 2 */ { "secdownload.timeout", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 3 */ { NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET } }; if (!p) return HANDLER_ERROR; p->config_storage = calloc(1, srv->config_context->used * sizeof(specific_config *)); for (i = 0; i < srv->config_context->used; i++) { plugin_config *s; s = calloc(1, sizeof(plugin_config)); s->secret = buffer_init(); s->doc_root = buffer_init(); s->uri_prefix = buffer_init(); s->timeout = 60; cv[0].destination = s->secret; cv[1].destination = s->doc_root; cv[2].destination = s->uri_prefix; cv[3].destination = &(s->timeout); p->config_storage[i] = s; if (0 != config_insert_values_global(srv, ((data_config *)srv->config_context->data[i])->value, cv)) { return HANDLER_ERROR; } } return HANDLER_GO_ON; } /** * checks if the supplied string is a MD5 string * * @param str a possible MD5 string * @return if the supplied string is a valid MD5 string 1 is returned otherwise 0 */ int is_hex_len(const char *str, size_t len) { size_t i; if (NULL == str) return 0; for (i = 0; i < len && *str; i++, str++) { /* illegal characters */ if (!((*str >= '0' && *str <= '9') || (*str >= 'a' && *str <= 'f') || (*str >= 'A' && *str <= 'F')) ) { return 0; } } return i == len; } static int mod_secdownload_patch_connection(server *srv, connection *con, plugin_data *p) { size_t i, j; plugin_config *s = p->config_storage[0]; PATCH_OPTION(secret); PATCH_OPTION(doc_root); PATCH_OPTION(uri_prefix); PATCH_OPTION(timeout); /* skip the first, the global context */ for (i = 1; i < srv->config_context->used; i++) { data_config *dc = (data_config *)srv->config_context->data[i]; s = p->config_storage[i]; /* condition didn't match */ if (!config_check_cond(srv, con, dc)) continue; /* merge config */ for (j = 0; j < dc->value->used; j++) { data_unset *du = dc->value->data[j]; if (buffer_is_equal_string(du->key, CONST_STR_LEN("secdownload.secret"))) { PATCH_OPTION(secret); } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("secdownload.document-root"))) { PATCH_OPTION(doc_root); } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("secdownload.uri-prefix"))) { PATCH_OPTION(uri_prefix); } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("secdownload.timeout"))) { PATCH_OPTION(timeout); } } } return 0; } URIHANDLER_FUNC(mod_secdownload_uri_handler) { plugin_data *p = p_d; MD5_CTX Md5Ctx; HASH HA1; const char *rel_uri, *ts_str, *md5_str; time_t ts = 0; size_t i; if (con->uri.path->used == 0) return HANDLER_GO_ON; mod_secdownload_patch_connection(srv, con, p); if (buffer_is_empty(p->conf.uri_prefix)) return HANDLER_GO_ON; if (buffer_is_empty(p->conf.secret)) { ERROR("secdownload.secret has to be set: %s", ""); return HANDLER_ERROR; } if (buffer_is_empty(p->conf.doc_root)) { ERROR("secdownload.document-root has to be set: %s", ""); return HANDLER_ERROR; } if (con->conf.log_request_handling) { TRACE("-- handling %s in mod_secdownload", SAFE_BUF_STR(con->uri.path)); } /* * /<uri-prefix>[a-f0-9]{32}/[a-f0-9]{8}/<rel-path> */ if (0 != strncmp(con->uri.path->ptr, p->conf.uri_prefix->ptr, p->conf.uri_prefix->used - 1)) { if (con->conf.log_request_handling) { TRACE("prefix '%s' didn't matched the url: %s", SAFE_BUF_STR(p->conf.uri_prefix), SAFE_BUF_STR(con->uri.path)); } return HANDLER_GO_ON; } md5_str = con->uri.path->ptr + p->conf.uri_prefix->used - 1; if (!is_hex_len(md5_str, 32)) { if (con->conf.log_request_handling) { TRACE("expected a 32-char hex-val as md5-hash: %s", SAFE_BUF_STR(con->uri.path)); } return HANDLER_GO_ON; } if (*(md5_str + 32) != '/') { if (con->conf.log_request_handling) { TRACE("missing a / after the md5-hash: %s", SAFE_BUF_STR(con->uri.path)); } return HANDLER_GO_ON; } ts_str = md5_str + 32 + 1; if (!is_hex_len(ts_str, 8)) { if (con->conf.log_request_handling) { TRACE("expected a 8-char hex-val after md5-hash: %s", SAFE_BUF_STR(con->uri.path)); } return HANDLER_GO_ON; } if (*(ts_str + 8) != '/') { if (con->conf.log_request_handling) { TRACE("missing a / after the timestamp: %s", SAFE_BUF_STR(con->uri.path)); } return HANDLER_GO_ON; } for (i = 0; i < 8; i++) { ts = (ts << 4) + hex2int(*(ts_str + i)); } /* timed-out */ if (srv->cur_ts - ts > p->conf.timeout || srv->cur_ts - ts < -p->conf.timeout) { if (con->conf.log_request_handling) { TRACE("timestamp is too old: %ld, timeout: %d", ts, p->conf.timeout); } con->http_status = 408; return HANDLER_FINISHED; } rel_uri = ts_str + 8; /* checking MD5 * * <secret><rel-path><timestamp-hex> */ buffer_copy_string_buffer(p->md5, p->conf.secret); buffer_append_string(p->md5, rel_uri); buffer_append_string_len(p->md5, ts_str, 8); MD5_Init(&Md5Ctx); MD5_Update(&Md5Ctx, (unsigned char *)p->md5->ptr, p->md5->used - 1); MD5_Final(HA1, &Md5Ctx); buffer_copy_string_hex(p->md5, (char *)HA1, 16); if (0 != strncasecmp(md5_str, p->md5->ptr, 32)) { con->http_status = 403; TRACE("MD5 didn't matched: %s == %s", md5_str, SAFE_BUF_STR(p->md5)); return HANDLER_FINISHED; } /* starting with the last / we should have relative-path to the docroot */ buffer_copy_string_buffer(con->physical.doc_root, p->conf.doc_root); buffer_copy_string(con->physical.rel_path, rel_uri); buffer_copy_string_buffer(con->physical.path, con->physical.doc_root); buffer_append_string_buffer(con->physical.path, con->physical.rel_path); if (con->conf.log_request_handling) { TRACE("MD5 matched, timestamp is ok, sending %s", SAFE_BUF_STR(con->physical.path)); } return HANDLER_GO_ON; } /* this function is called at dlopen() time and inits the callbacks */ LI_EXPORT int mod_secdownload_plugin_init(plugin *p) { p->version = LIGHTTPD_VERSION_ID; p->name = buffer_init_string("secdownload"); p->init = mod_secdownload_init; p->handle_physical = mod_secdownload_uri_handler; p->set_defaults = mod_secdownload_set_defaults; p->cleanup = mod_secdownload_free; p->data = NULL; return 0; } #include <ctype.h> #include <stdlib.h> #include <string.h> #include "base.h" #include "log.h" #include "buffer.h" #include "plugin.h" #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef USE_OPENSSL # include <openssl/md5.h> #else # include "md5.h" #endif #define HASHLEN 16 typedef unsigned char HASH[HASHLEN]; #define HASHHEXLEN 32 typedef char HASHHEX[HASHHEXLEN+1]; #ifdef USE_OPENSSL #define IN const #else #define IN #endif #define OUT /* plugin config for all request/connections */ typedef struct { buffer *doc_root; buffer *secret; buffer *uri_prefix; unsigned short timeout; } plugin_config; typedef struct { PLUGIN_DATA; buffer *md5; plugin_config **config_storage; plugin_config conf; } plugin_data; /* init the plugin data */ INIT_FUNC(mod_secdownload_init) { plugin_data *p; UNUSED(srv); p = calloc(1, sizeof(*p)); p->md5 = buffer_init(); return p; } /* detroy the plugin data */ FREE_FUNC(mod_secdownload_free) { plugin_data *p = p_d; UNUSED(srv); if (!p) return HANDLER_GO_ON; if (p->config_storage) { size_t i; for (i = 0; i < srv->config_context->used; i++) { plugin_config *s = p->config_storage[i]; buffer_free(s->secret); buffer_free(s->doc_root); buffer_free(s->uri_prefix); free(s); } free(p->config_storage); } buffer_free(p->md5); free(p); return HANDLER_GO_ON; } /* handle plugin config and check values */ SETDEFAULTS_FUNC(mod_secdownload_set_defaults) { plugin_data *p = p_d; size_t i = 0; config_values_t cv[] = { { "secdownload.secret", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 0 */ { "secdownload.document-root", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 1 */ { "secdownload.uri-prefix", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 2 */ { "secdownload.timeout", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 3 */ { NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET } }; if (!p) return HANDLER_ERROR; p->config_storage = calloc(1, srv->config_context->used * sizeof(specific_config *)); for (i = 0; i < srv->config_context->used; i++) { plugin_config *s; s = calloc(1, sizeof(plugin_config)); s->secret = buffer_init(); s->doc_root = buffer_init(); s->uri_prefix = buffer_init(); s->timeout = 60; cv[0].destination = s->secret; cv[1].destination = s->doc_root; cv[2].destination = s->uri_prefix; cv[3].destination = &(s->timeout); p->config_storage[i] = s; if (0 != config_insert_values_global(srv, ((data_config *)srv->config_context->data[i])->value, cv)) { return HANDLER_ERROR; } } return HANDLER_GO_ON; } /** * checks if the supplied string is a MD5 string * * @param str a possible MD5 string * @return if the supplied string is a valid MD5 string 1 is returned otherwise 0 */ int is_hex_len(const char *str, size_t len) { size_t i; if (NULL == str) return 0; for (i = 0; i < len && *str; i++, str++) { /* illegal characters */ if (!((*str >= '0' && *str <= '9') || (*str >= 'a' && *str <= 'f') || (*str >= 'A' && *str <= 'F')) ) { return 0; } } return i == len; } static int mod_secdownload_patch_connection(server *srv, connection *con, plugin_data *p) { size_t i, j; plugin_config *s = p->config_storage[0]; PATCH_OPTION(secret); PATCH_OPTION(doc_root); PATCH_OPTION(uri_prefix); PATCH_OPTION(timeout); /* skip the first, the global context */ for (i = 1; i < srv->config_context->used; i++) { data_config *dc = (data_config *)srv->config_context->data[i]; s = p->config_storage[i]; /* condition didn't match */ if (!config_check_cond(srv, con, dc)) continue; /* merge config */ for (j = 0; j < dc->value->used; j++) { data_unset *du = dc->value->data[j]; if (buffer_is_equal_string(du->key, CONST_STR_LEN("secdownload.secret"))) { PATCH_OPTION(secret); } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("secdownload.document-root"))) { PATCH_OPTION(doc_root); } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("secdownload.uri-prefix"))) { PATCH_OPTION(uri_prefix); } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("secdownload.timeout"))) { PATCH_OPTION(timeout); } } } return 0; } URIHANDLER_FUNC(mod_secdownload_uri_handler) { plugin_data *p = p_d; MD5_CTX Md5Ctx; HASH HA1; const char *rel_uri, *ts_str, *md5_str; time_t ts = 0; size_t i; if (con->uri.path->used == 0) return HANDLER_GO_ON; mod_secdownload_patch_connection(srv, con, p); if (buffer_is_empty(p->conf.uri_prefix)) return HANDLER_GO_ON; if (buffer_is_empty(p->conf.secret)) { ERROR("secdownload.secret has to be set: %s", ""); return HANDLER_ERROR; } if (buffer_is_empty(p->conf.doc_root)) { ERROR("secdownload.document-root has to be set: %s", ""); return HANDLER_ERROR; } if (con->conf.log_request_handling) { TRACE("-- handling %s in mod_secdownload", SAFE_BUF_STR(con->uri.path)); } /* * /<uri-prefix>[a-f0-9]{32}/[a-f0-9]{8}/<rel-path> */ if (0 != strncmp(con->uri.path->ptr, p->conf.uri_prefix->ptr, p->conf.uri_prefix->used - 1)) { if (con->conf.log_request_handling) { TRACE("prefix '%s' didn't matched the url: %s", SAFE_BUF_STR(p->conf.uri_prefix), SAFE_BUF_STR(con->uri.path)); } return HANDLER_GO_ON; } md5_str = con->uri.path->ptr + p->conf.uri_prefix->used - 1; if (!is_hex_len(md5_str, 32)) { if (con->conf.log_request_handling) { TRACE("expected a 32-char hex-val as md5-hash: %s", SAFE_BUF_STR(con->uri.path)); } return HANDLER_GO_ON; } if (*(md5_str + 32) != '/') { if (con->conf.log_request_handling) { TRACE("missing a / after the md5-hash: %s", SAFE_BUF_STR(con->uri.path)); } return HANDLER_GO_ON; } ts_str = md5_str + 32 + 1; if (!is_hex_len(ts_str, 8)) { if (con->conf.log_request_handling) { TRACE("expected a 8-char hex-val after md5-hash: %s", SAFE_BUF_STR(con->uri.path)); } return HANDLER_GO_ON; } if (*(ts_str + 8) != '/') { if (con->conf.log_request_handling) { TRACE("missing a / after the timestamp: %s", SAFE_BUF_STR(con->uri.path)); } return HANDLER_GO_ON; } for (i = 0; i < 8; i++) { ts = (ts << 4) + hex2int(*(ts_str + i)); } /* timed-out */ if ( (srv->cur_ts > ts && srv->cur_ts - ts > p->conf.timeout) || (srv->cur_ts < ts && ts - srv->cur_ts > p->conf.timeout) ) { if (con->conf.log_request_handling) { TRACE("timestamp is too old: %ld, timeout: %d", ts, p->conf.timeout); } /* "Gone" as the url will never be valid again instead of "408 - Timeout" where the request may be repeated */ con->http_status = 410; return HANDLER_FINISHED; } rel_uri = ts_str + 8; /* checking MD5 * * <secret><rel-path><timestamp-hex> */ buffer_copy_string_buffer(p->md5, p->conf.secret); buffer_append_string(p->md5, rel_uri); buffer_append_string_len(p->md5, ts_str, 8); MD5_Init(&Md5Ctx); MD5_Update(&Md5Ctx, (unsigned char *)p->md5->ptr, p->md5->used - 1); MD5_Final(HA1, &Md5Ctx); buffer_copy_string_hex(p->md5, (char *)HA1, 16); if (0 != strncasecmp(md5_str, p->md5->ptr, 32)) { con->http_status = 403; TRACE("MD5 didn't matched: %s == %s", md5_str, SAFE_BUF_STR(p->md5)); return HANDLER_FINISHED; } /* starting with the last / we should have relative-path to the docroot */ buffer_copy_string_buffer(con->physical.doc_root, p->conf.doc_root); buffer_copy_string(con->physical.rel_path, rel_uri); buffer_copy_string_buffer(con->physical.path, con->physical.doc_root); buffer_append_string_buffer(con->physical.path, con->physical.rel_path); if (con->conf.log_request_handling) { TRACE("MD5 matched, timestamp is ok, sending %s", SAFE_BUF_STR(con->physical.path)); } return HANDLER_GO_ON; } /* this function is called at dlopen() time and inits the callbacks */ LI_EXPORT int mod_secdownload_plugin_init(plugin *p) { p->version = LIGHTTPD_VERSION_ID; p->name = buffer_init_string("secdownload"); p->init = mod_secdownload_init; p->handle_physical = mod_secdownload_uri_handler; p->set_defaults = mod_secdownload_set_defaults; p->cleanup = mod_secdownload_free; p->data = NULL; return 0; }
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/lighttpd_2254-2259.c
manybugs_data_29
/* Inflate deflated data Copyright (C) 1997, 1998, 1999, 2002, 2006 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Not copyrighted 1992 by Mark Adler version c10p1, 10 January 1993 */ /* You can do whatever you like with this source file, though I would prefer that if you modify it and redistribute it that you include comments to that effect with your name and the date. Thank you. [The history has been moved to the file ChangeLog.] */ /* Inflate deflated (PKZIP's method 8 compressed) data. The compression method searches for as much of the current string of bytes (up to a length of 258) in the previous 32K bytes. If it doesn't find any matches (of at least length 3), it codes the next byte. Otherwise, it codes the length of the matched string and its distance backwards from the current position. There is a single Huffman code that codes both single bytes (called "literals") and match lengths. A second Huffman code codes the distance information, which follows a length code. Each length or distance code actually represents a base value and a number of "extra" (sometimes zero) bits to get to add to the base value. At the end of each deflated block is a special end-of-block (EOB) literal/ length code. The decoding process is basically: get a literal/length code; if EOB then done; if a literal, emit the decoded byte; if a length then get the distance and emit the referred-to bytes from the sliding window of previously emitted data. There are (currently) three kinds of inflate blocks: stored, fixed, and dynamic. The compressor deals with some chunk of data at a time, and decides which method to use on a chunk-by-chunk basis. A chunk might typically be 32K or 64K. If the chunk is uncompressible, then the "stored" method is used. In this case, the bytes are simply stored as is, eight bits per byte, with none of the above coding. The bytes are preceded by a count, since there is no longer an EOB code. If the data is compressible, then either the fixed or dynamic methods are used. In the dynamic method, the compressed data is preceded by an encoding of the literal/length and distance Huffman codes that are to be used to decode this block. The representation is itself Huffman coded, and so is preceded by a description of that code. These code descriptions take up a little space, and so for small blocks, there is a predefined set of codes, called the fixed codes. The fixed method is used if the block codes up smaller that way (usually for quite small chunks), otherwise the dynamic method is used. In the latter case, the codes are customized to the probabilities in the current block, and so can code it much better than the pre-determined fixed codes. The Huffman codes themselves are decoded using a multi-level table lookup, in order to maximize the speed of decoding plus the speed of building the decoding tables. See the comments below that precede the lbits and dbits tuning parameters. */ /* Notes beyond the 1.93a appnote.txt: 1. Distance pointers never point before the beginning of the output stream. 2. Distance pointers can point back across blocks, up to 32k away. 3. There is an implied maximum of 7 bits for the bit length table and 15 bits for the actual data. 4. If only one code exists, then it is encoded using one bit. (Zero would be more efficient, but perhaps a little confusing.) If two codes exist, they are coded using one bit each (0 and 1). 5. There is no way of sending zero distance codes--a dummy must be sent if there are none. (History: a pre 2.0 version of PKZIP would store blocks with no distance codes, but this was discovered to be too harsh a criterion.) Valid only for 1.93a. 2.04c does allow zero distance codes, which is sent as one code of zero bits in length. 6. There are up to 286 literal/length codes. Code 256 represents the end-of-block. Note however that the static length tree defines 288 codes just to fill out the Huffman codes. Codes 286 and 287 cannot be used though, since there is no length base or extra bits defined for them. Similarly, there are up to 30 distance codes. However, static trees define 32 codes (all 5 bits) to fill out the Huffman codes, but the last two had better not show up in the data. 7. Unzip can check dynamic Huffman blocks for complete code sets. The exception is that a single code would not be complete (see #4). 8. The five bits following the block type is really the number of literal codes sent minus 257. 9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits (1+6+6). Therefore, to output three times the length, you output three codes (1+1+1), whereas to output four times the same length, you only need two codes (1+3). Hmm. 10. In the tree reconstruction algorithm, Code = Code + Increment only if BitLength(i) is not zero. (Pretty obvious.) 11. Correction: 4 Bits: # of Bit Length codes - 4 (4 - 19) 12. Note: length code 284 can represent 227-258, but length code 285 really is 258. The last length deserves its own, short code since it gets used a lot in very redundant files. The length 258 is special since 258 - 3 (the min match length) is 255. 13. The literal/length and distance code bit lengths are read as a single stream of lengths. It is possible (and advantageous) for a repeat code (16, 17, or 18) to go across the boundary between the two sets of lengths. */ #ifdef RCSID static char rcsid[] = "$Id$"; #endif #include <config.h> #include "tailor.h" #if defined STDC_HEADERS || defined HAVE_STDLIB_H # include <stdlib.h> #endif #include "gzip.h" #define slide window /* Huffman code lookup table entry--this entry is four bytes for machines that have 16-bit pointers (e.g. PC's in the small or medium model). Valid extra bits are 0..13. e == 15 is EOB (end of block), e == 16 means that v is a literal, 16 < e < 32 means that v is a pointer to the next table, which codes e - 16 bits, and lastly e == 99 indicates an unused code. If a code with e == 99 is looked up, this implies an error in the data. */ struct huft { uch e; /* number of extra bits or operation */ uch b; /* number of bits in this code or subcode */ union { ush n; /* literal, length base, or distance base */ struct huft *t; /* pointer to next level of table */ } v; }; /* Function prototypes */ int huft_build OF((unsigned *, unsigned, unsigned, ush *, ush *, struct huft **, int *)); int huft_free OF((struct huft *)); int inflate_codes OF((struct huft *, struct huft *, int, int)); int inflate_stored OF((void)); int inflate_fixed OF((void)); int inflate_dynamic OF((void)); int inflate_block OF((int *)); int inflate OF((void)); /* The inflate algorithm uses a sliding 32K byte window on the uncompressed stream to find repeated byte strings. This is implemented here as a circular buffer. The index is updated simply by incrementing and then and'ing with 0x7fff (32K-1). */ /* It is left to other modules to supply the 32K area. It is assumed to be usable as if it were declared "uch slide[32768];" or as just "uch *slide;" and then malloc'ed in the latter case. The definition must be in unzip.h, included above. */ /* unsigned wp; current position in slide */ #define wp outcnt #define flush_output(w) (wp=(w),flush_window()) /* Tables for deflate from PKZIP's appnote.txt. */ static unsigned border[] = { /* Order of the bit length code lengths */ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; static ush cplens[] = { /* Copy lengths for literal codes 257..285 */ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; /* note: see note #13 above about the 258 in this list. */ static ush cplext[] = { /* Extra bits for literal codes 257..285 */ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99}; /* 99==invalid */ static ush cpdist[] = { /* Copy offsets for distance codes 0..29 */ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; static ush cpdext[] = { /* Extra bits for distance codes */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; /* Macros for inflate() bit peeking and grabbing. The usage is: NEEDBITS(j) x = b & mask_bits[j]; DUMPBITS(j) where NEEDBITS makes sure that b has at least j bits in it, and DUMPBITS removes the bits from b. The macros use the variable k for the number of bits in b. Normally, b and k are register variables for speed, and are initialized at the beginning of a routine that uses these macros from a global bit buffer and count. The macros also use the variable w, which is a cached copy of wp. If we assume that EOB will be the longest code, then we will never ask for bits with NEEDBITS that are beyond the end of the stream. So, NEEDBITS should not read any more bytes than are needed to meet the request. Then no bytes need to be "returned" to the buffer at the end of the last block. However, this assumption is not true for fixed blocks--the EOB code is 7 bits, but the other literal/length codes can be 8 or 9 bits. (The EOB code is shorter than other codes because fixed blocks are generally short. So, while a block always has an EOB, many other literal/length codes have a significantly lower probability of showing up at all.) However, by making the first table have a lookup of seven bits, the EOB code will be found in that first lookup, and so will not require that too many bits be pulled from the stream. */ ulg bb; /* bit buffer */ unsigned bk; /* bits in bit buffer */ ush mask_bits[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff, 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff }; #define GETBYTE() (inptr < insize ? inbuf[inptr++] : (wp = w, fill_inbuf(0))) #ifdef CRYPT uch cc; # define NEXTBYTE() \ (decrypt ? (cc = GETBYTE(), zdecode(cc), cc) : GETBYTE()) #else # define NEXTBYTE() (uch)GETBYTE() #endif #define NEEDBITS(n) {while(k<(n)){b|=((ulg)NEXTBYTE())<<k;k+=8;}} #define DUMPBITS(n) {b>>=(n);k-=(n);} /* Huffman code decoding is performed using a multi-level table lookup. The fastest way to decode is to simply build a lookup table whose size is determined by the longest code. However, the time it takes to build this table can also be a factor if the data being decoded is not very long. The most common codes are necessarily the shortest codes, so those codes dominate the decoding time, and hence the speed. The idea is you can have a shorter table that decodes the shorter, more probable codes, and then point to subsidiary tables for the longer codes. The time it costs to decode the longer codes is then traded against the time it takes to make longer tables. This results of this trade are in the variables lbits and dbits below. lbits is the number of bits the first level table for literal/ length codes can decode in one step, and dbits is the same thing for the distance codes. Subsequent tables are also less than or equal to those sizes. These values may be adjusted either when all of the codes are shorter than that, in which case the longest code length in bits is used, or when the shortest code is *longer* than the requested table size, in which case the length of the shortest code in bits is used. There are two different values for the two tables, since they code a different number of possibilities each. The literal/length table codes 286 possible values, or in a flat code, a little over eight bits. The distance table codes 30 possible values, or a little less than five bits, flat. The optimum values for speed end up being about one bit more than those, so lbits is 8+1 and dbits is 5+1. The optimum values may differ though from machine to machine, and possibly even between compilers. Your mileage may vary. */ int lbits = 9; /* bits in base literal/length lookup table */ int dbits = 6; /* bits in base distance lookup table */ /* If BMAX needs to be larger than 16, then h and x[] should be ulg. */ #define BMAX 16 /* maximum bit length of any code (16 for explode) */ #define N_MAX 288 /* maximum number of codes in any set */ unsigned hufts; /* track memory usage */ int huft_build(b, n, s, d, e, t, m) unsigned *b; /* code lengths in bits (all assumed <= BMAX) */ unsigned n; /* number of codes (assumed <= N_MAX) */ unsigned s; /* number of simple-valued codes (0..s-1) */ ush *d; /* list of base values for non-simple codes */ ush *e; /* list of extra bits for non-simple codes */ struct huft **t; /* result: starting table */ int *m; /* maximum lookup bits, returns actual */ /* Given a list of code lengths and a maximum table size, make a set of tables to decode that set of codes. Return zero on success, one if the given code set is incomplete (the tables are still built in this case), two if the input is invalid (all zero length codes or an oversubscribed set of lengths), and three if not enough memory. */ { unsigned a; /* counter for codes of length k */ unsigned c[BMAX+1]; /* bit length count table */ unsigned f; /* i repeats in table every f entries */ int g; /* maximum code length */ int h; /* table level */ register unsigned i; /* counter, current code */ register unsigned j; /* counter */ register int k; /* number of bits in current code */ int l; /* bits per table (returned in m) */ register unsigned *p; /* pointer into c[], b[], or v[] */ register struct huft *q; /* points to current table */ struct huft r; /* table entry for structure assignment */ struct huft *u[BMAX]; /* table stack */ unsigned v[N_MAX]; /* values in order of bit length */ register int w; /* bits before this table == (l * h) */ unsigned x[BMAX+1]; /* bit offsets, then code stack */ unsigned *xp; /* pointer into x */ int y; /* number of dummy codes added */ unsigned z; /* number of entries in current table */ /* Generate counts for each bit length */ memzero(c, sizeof(c)); p = b; i = n; do { Tracecv(*p, (stderr, (n-i >= ' ' && n-i <= '~' ? "%c %d\n" : "0x%x %d\n"), n-i, *p)); c[*p]++; /* assume all entries <= BMAX */ p++; /* Can't combine with above line (Solaris bug) */ } while (--i); if (c[0] == n) /* null input--all zero length codes */ { q = (struct huft *) malloc (2 * sizeof *q); if (!q) return 3; hufts += 2; q[0].v.t = (struct huft *) NULL; q[1].e = 99; /* invalid code marker */ q[1].b = 1; *t = q + 1; *m = 1; return 0; } /* Find minimum and maximum length, bound *m by those */ l = *m; for (j = 1; j <= BMAX; j++) if (c[j]) break; k = j; /* minimum code length */ if ((unsigned)l < j) l = j; for (i = BMAX; i; i--) if (c[i]) break; g = i; /* maximum code length */ if ((unsigned)l > i) l = i; *m = l; /* Adjust last length count to fill out codes, if needed */ for (y = 1 << j; j < i; j++, y <<= 1) if ((y -= c[j]) < 0) return 2; /* bad input: more codes than bits */ if ((y -= c[i]) < 0) return 2; c[i] += y; /* Generate starting offsets into the value table for each length */ x[1] = j = 0; p = c + 1; xp = x + 2; while (--i) { /* note that i == g from above */ *xp++ = (j += *p++); } /* Make a table of values in order of bit lengths */ p = b; i = 0; do { if ((j = *p++) != 0) v[x[j]++] = i; } while (++i < n); n = x[g]; /* set n to length of v */ /* Generate the Huffman codes and for each, make the table entries */ x[0] = i = 0; /* first Huffman code is zero */ p = v; /* grab values in bit order */ h = -1; /* no tables yet--level -1 */ w = -l; /* bits decoded == (l * h) */ u[0] = (struct huft *)NULL; /* just to keep compilers happy */ q = (struct huft *)NULL; /* ditto */ z = 0; /* ditto */ /* go through the bit lengths (k already is bits in shortest code) */ for (; k <= g; k++) { a = c[k]; while (a--) { /* here i is the Huffman code of length k bits for value *p */ /* make tables up to required level */ while (k > w + l) { h++; w += l; /* previous table always l bits */ /* compute minimum size table less than or equal to l bits */ z = (z = g - w) > (unsigned)l ? l : z; /* upper limit on table size */ if ((f = 1 << (j = k - w)) > a + 1) /* try a k-w bit table */ { /* too few codes for k-w bit table */ f -= a + 1; /* deduct codes from patterns left */ xp = c + k; if (j < z) while (++j < z) /* try smaller tables up to z bits */ { if ((f <<= 1) <= *++xp) break; /* enough codes to use up j bits */ f -= *xp; /* else deduct codes from patterns */ } } z = 1 << j; /* table entries for j-bit table */ /* allocate and link in new table */ if ((q = (struct huft *)malloc((z + 1)*sizeof(struct huft))) == (struct huft *)NULL) { if (h) huft_free(u[0]); return 3; /* not enough memory */ } hufts += z + 1; /* track memory usage */ *t = q + 1; /* link to list for huft_free() */ *(t = &(q->v.t)) = (struct huft *)NULL; u[h] = ++q; /* table starts after link */ /* connect to last table, if there is one */ if (h) { x[h] = i; /* save pattern for backing up */ r.b = (uch)l; /* bits to dump before this table */ r.e = (uch)(16 + j); /* bits in this table */ r.v.t = q; /* pointer to this table */ j = i >> (w - l); /* (get around Turbo C bug) */ u[h-1][j] = r; /* connect to last table */ } } /* set up table entry in r */ r.b = (uch)(k - w); if (p >= v + n) r.e = 99; /* out of values--invalid code */ else if (*p < s) { r.e = (uch)(*p < 256 ? 16 : 15); /* 256 is end-of-block code */ r.v.n = (ush)(*p); /* simple code is just the value */ p++; /* one compiler does not like *p++ */ } else { r.e = (uch)e[*p - s]; /* non-simple--look up in lists */ r.v.n = d[*p++ - s]; } /* fill code-like entries with r */ f = 1 << (k - w); for (j = i >> w; j < z; j += f) q[j] = r; /* backwards increment the k-bit code i */ for (j = 1 << (k - 1); i & j; j >>= 1) i ^= j; i ^= j; /* backup over finished tables */ while ((i & ((1 << w) - 1)) != x[h]) { h--; /* don't need to update q */ w -= l; } } } /* Return true (1) if we were given an incomplete table */ return y != 0 && g != 1; } int huft_free(t) struct huft *t; /* table to free */ /* Free the malloc'ed tables built by huft_build(), which makes a linked list of the tables it made, with the links in a dummy first entry of each table. */ { register struct huft *p, *q; /* Go through linked list, freeing from the malloced (t[-1]) address. */ p = t; while (p != (struct huft *)NULL) { q = (--p)->v.t; free((char*)p); p = q; } return 0; } int inflate_codes(tl, td, bl, bd) struct huft *tl, *td; /* literal/length and distance decoder tables */ int bl, bd; /* number of bits decoded by tl[] and td[] */ /* inflate (decompress) the codes in a deflated (compressed) block. Return an error code or zero if it all goes ok. */ { register unsigned e; /* table entry flag/number of extra bits */ unsigned n, d; /* length and index for copy */ unsigned w; /* current window position */ struct huft *t; /* pointer to table entry */ unsigned ml, md; /* masks for bl and bd bits */ register ulg b; /* bit buffer */ register unsigned k; /* number of bits in bit buffer */ /* make local copies of globals */ b = bb; /* initialize bit buffer */ k = bk; w = wp; /* initialize window position */ /* inflate the coded data */ ml = mask_bits[bl]; /* precompute masks for speed */ md = mask_bits[bd]; for (;;) /* do until end of block */ { NEEDBITS((unsigned)bl) if ((e = (t = tl + ((unsigned)b & ml))->e) > 16) do { if (e == 99) return 1; DUMPBITS(t->b) e -= 16; NEEDBITS(e) } while ((e = (t = t->v.t + ((unsigned)b & mask_bits[e]))->e) > 16); DUMPBITS(t->b) if (e == 16) /* then it's a literal */ { slide[w++] = (uch)t->v.n; Tracevv((stderr, "%c", slide[w-1])); if (w == WSIZE) { flush_output(w); w = 0; } } else /* it's an EOB or a length */ { /* exit if end of block */ if (e == 15) break; /* get length of block to copy */ NEEDBITS(e) n = t->v.n + ((unsigned)b & mask_bits[e]); DUMPBITS(e); /* decode distance of block to copy */ NEEDBITS((unsigned)bd) if ((e = (t = td + ((unsigned)b & md))->e) > 16) do { if (e == 99) return 1; DUMPBITS(t->b) e -= 16; NEEDBITS(e) } while ((e = (t = t->v.t + ((unsigned)b & mask_bits[e]))->e) > 16); DUMPBITS(t->b) NEEDBITS(e) d = w - t->v.n - ((unsigned)b & mask_bits[e]); DUMPBITS(e) Tracevv((stderr,"\\[%d,%d]", w-d, n)); /* do the copy */ do { n -= (e = (e = WSIZE - ((d &= WSIZE-1) > w ? d : w)) > n ? n : e); #if !defined(NOMEMCPY) && !defined(DEBUG) if (w - d >= e) /* (this test assumes unsigned comparison) */ { memcpy(slide + w, slide + d, e); w += e; d += e; } else /* do it slow to avoid memcpy() overlap */ #endif /* !NOMEMCPY */ do { slide[w++] = slide[d++]; Tracevv((stderr, "%c", slide[w-1])); } while (--e); if (w == WSIZE) { flush_output(w); w = 0; } } while (n); } } /* restore the globals from the locals */ wp = w; /* restore global window pointer */ bb = b; /* restore global bit buffer */ bk = k; /* done */ return 0; } int inflate_stored() /* "decompress" an inflated type 0 (stored) block. */ { unsigned n; /* number of bytes in block */ unsigned w; /* current window position */ register ulg b; /* bit buffer */ register unsigned k; /* number of bits in bit buffer */ /* make local copies of globals */ b = bb; /* initialize bit buffer */ k = bk; w = wp; /* initialize window position */ /* go to byte boundary */ n = k & 7; DUMPBITS(n); /* get the length and its complement */ NEEDBITS(16) n = ((unsigned)b & 0xffff); DUMPBITS(16) NEEDBITS(16) if (n != (unsigned)((~b) & 0xffff)) return 1; /* error in compressed data */ DUMPBITS(16) /* read and output the compressed data */ while (n--) { NEEDBITS(8) slide[w++] = (uch)b; if (w == WSIZE) { flush_output(w); w = 0; } DUMPBITS(8) } /* restore the globals from the locals */ wp = w; /* restore global window pointer */ bb = b; /* restore global bit buffer */ bk = k; return 0; } int inflate_fixed() /* decompress an inflated type 1 (fixed Huffman codes) block. We should either replace this with a custom decoder, or at least precompute the Huffman tables. */ { int i; /* temporary variable */ struct huft *tl; /* literal/length code table */ struct huft *td; /* distance code table */ int bl; /* lookup bits for tl */ int bd; /* lookup bits for td */ unsigned l[288]; /* length list for huft_build */ /* set up literal table */ for (i = 0; i < 144; i++) l[i] = 8; for (; i < 256; i++) l[i] = 9; for (; i < 280; i++) l[i] = 7; for (; i < 288; i++) /* make a complete, but wrong code set */ l[i] = 8; bl = 7; if ((i = huft_build(l, 288, 257, cplens, cplext, &tl, &bl)) != 0) return i; /* set up distance table */ for (i = 0; i < 30; i++) /* make an incomplete code set */ l[i] = 5; bd = 5; if ((i = huft_build(l, 30, 0, cpdist, cpdext, &td, &bd)) > 1) { huft_free(tl); return i; } /* decompress until an end-of-block code */ if (inflate_codes(tl, td, bl, bd)) return 1; /* free the decoding tables, return */ huft_free(tl); huft_free(td); return 0; } int inflate_dynamic() /* decompress an inflated type 2 (dynamic Huffman codes) block. */ { int i; /* temporary variables */ unsigned j; unsigned l; /* last length */ unsigned m; /* mask for bit lengths table */ unsigned n; /* number of lengths to get */ unsigned w; /* current window position */ struct huft *tl; /* literal/length code table */ struct huft *td; /* distance code table */ int bl; /* lookup bits for tl */ int bd; /* lookup bits for td */ unsigned nb; /* number of bit length codes */ unsigned nl; /* number of literal/length codes */ unsigned nd; /* number of distance codes */ #ifdef PKZIP_BUG_WORKAROUND unsigned ll[288+32]; /* literal/length and distance code lengths */ #else unsigned ll[286+30]; /* literal/length and distance code lengths */ #endif register ulg b; /* bit buffer */ register unsigned k; /* number of bits in bit buffer */ /* make local bit buffer */ b = bb; k = bk; w = wp; /* read in table lengths */ NEEDBITS(5) nl = 257 + ((unsigned)b & 0x1f); /* number of literal/length codes */ DUMPBITS(5) NEEDBITS(5) nd = 1 + ((unsigned)b & 0x1f); /* number of distance codes */ DUMPBITS(5) NEEDBITS(4) nb = 4 + ((unsigned)b & 0xf); /* number of bit length codes */ DUMPBITS(4) #ifdef PKZIP_BUG_WORKAROUND if (nl > 288 || nd > 32) #else if (nl > 286 || nd > 30) #endif return 1; /* bad lengths */ /* read in bit-length-code lengths */ for (j = 0; j < nb; j++) { NEEDBITS(3) ll[border[j]] = (unsigned)b & 7; DUMPBITS(3) } for (; j < 19; j++) ll[border[j]] = 0; /* build decoding table for trees--single level, 7 bit lookup */ bl = 7; if ((i = huft_build(ll, 19, 19, NULL, NULL, &tl, &bl)) != 0) { if (i == 1) huft_free(tl); return i; /* incomplete code set */ } if (tl == NULL) /* Grrrhhh */ return 2; /* read in literal and distance code lengths */ n = nl + nd; m = mask_bits[bl]; i = l = 0; while ((unsigned)i < n) { NEEDBITS((unsigned)bl) j = (td = tl + ((unsigned)b & m))->b; DUMPBITS(j) j = td->v.n; if (j < 16) /* length of code in bits (0..15) */ ll[i++] = l = j; /* save last length in l */ else if (j == 16) /* repeat last length 3 to 6 times */ { NEEDBITS(2) j = 3 + ((unsigned)b & 3); DUMPBITS(2) if ((unsigned)i + j > n) return 1; while (j--) ll[i++] = l; } else if (j == 17) /* 3 to 10 zero length codes */ { NEEDBITS(3) j = 3 + ((unsigned)b & 7); DUMPBITS(3) if ((unsigned)i + j > n) return 1; while (j--) ll[i++] = 0; l = 0; } else /* j == 18: 11 to 138 zero length codes */ { NEEDBITS(7) j = 11 + ((unsigned)b & 0x7f); DUMPBITS(7) if ((unsigned)i + j > n) return 1; while (j--) ll[i++] = 0; l = 0; } } /* free decoding table for trees */ huft_free(tl); /* restore the global bit buffer */ bb = b; bk = k; /* build the decoding tables for literal/length and distance codes */ bl = lbits; if ((i = huft_build(ll, nl, 257, cplens, cplext, &tl, &bl)) != 0) { if (i == 1) { Trace ((stderr, " incomplete literal tree\n")); huft_free(tl); } return i; /* incomplete code set */ } bd = dbits; if ((i = huft_build(ll + nl, nd, 0, cpdist, cpdext, &td, &bd)) != 0) { if (i == 1) { Trace ((stderr, " incomplete distance tree\n")); #ifdef PKZIP_BUG_WORKAROUND i = 0; } #else huft_free(td); } huft_free(tl); return i; /* incomplete code set */ #endif } /* decompress until an end-of-block code */ if (inflate_codes(tl, td, bl, bd)) return 1; /* free the decoding tables, return */ huft_free(tl); huft_free(td); return 0; } int inflate_block(e) int *e; /* last block flag */ /* decompress an inflated block */ { unsigned t; /* block type */ unsigned w; /* current window position */ register ulg b; /* bit buffer */ register unsigned k; /* number of bits in bit buffer */ /* make local bit buffer */ b = bb; k = bk; w = wp; /* read in last block bit */ NEEDBITS(1) *e = (int)b & 1; DUMPBITS(1) /* read in block type */ NEEDBITS(2) t = (unsigned)b & 3; DUMPBITS(2) /* restore the global bit buffer */ bb = b; bk = k; /* inflate that block type */ if (t == 2) return inflate_dynamic(); if (t == 0) return inflate_stored(); if (t == 1) return inflate_fixed(); /* bad block type */ return 2; } int inflate() /* decompress an inflated entry */ { int e; /* last block flag */ int r; /* result code */ unsigned h; /* maximum struct huft's malloc'ed */ /* initialize window, bit buffer */ wp = 0; bk = 0; bb = 0; /* decompress until the last block */ h = 0; do { hufts = 0; if ((r = inflate_block(&e)) != 0) return r; if (hufts > h) h = hufts; } while (!e); /* Undo too much lookahead. The next read will be byte aligned so we * can discard unused bits in the last meaningful byte. */ while (bk >= 8) { bk -= 8; inptr--; } /* flush out slide */ flush_output(wp); /* return success */ Trace ((stderr, "<%u> ", h)); return 0; } /* Inflate deflated data Copyright (C) 1997, 1998, 1999, 2002, 2006 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Not copyrighted 1992 by Mark Adler version c10p1, 10 January 1993 */ /* You can do whatever you like with this source file, though I would prefer that if you modify it and redistribute it that you include comments to that effect with your name and the date. Thank you. [The history has been moved to the file ChangeLog.] */ /* Inflate deflated (PKZIP's method 8 compressed) data. The compression method searches for as much of the current string of bytes (up to a length of 258) in the previous 32K bytes. If it doesn't find any matches (of at least length 3), it codes the next byte. Otherwise, it codes the length of the matched string and its distance backwards from the current position. There is a single Huffman code that codes both single bytes (called "literals") and match lengths. A second Huffman code codes the distance information, which follows a length code. Each length or distance code actually represents a base value and a number of "extra" (sometimes zero) bits to get to add to the base value. At the end of each deflated block is a special end-of-block (EOB) literal/ length code. The decoding process is basically: get a literal/length code; if EOB then done; if a literal, emit the decoded byte; if a length then get the distance and emit the referred-to bytes from the sliding window of previously emitted data. There are (currently) three kinds of inflate blocks: stored, fixed, and dynamic. The compressor deals with some chunk of data at a time, and decides which method to use on a chunk-by-chunk basis. A chunk might typically be 32K or 64K. If the chunk is uncompressible, then the "stored" method is used. In this case, the bytes are simply stored as is, eight bits per byte, with none of the above coding. The bytes are preceded by a count, since there is no longer an EOB code. If the data is compressible, then either the fixed or dynamic methods are used. In the dynamic method, the compressed data is preceded by an encoding of the literal/length and distance Huffman codes that are to be used to decode this block. The representation is itself Huffman coded, and so is preceded by a description of that code. These code descriptions take up a little space, and so for small blocks, there is a predefined set of codes, called the fixed codes. The fixed method is used if the block codes up smaller that way (usually for quite small chunks), otherwise the dynamic method is used. In the latter case, the codes are customized to the probabilities in the current block, and so can code it much better than the pre-determined fixed codes. The Huffman codes themselves are decoded using a multi-level table lookup, in order to maximize the speed of decoding plus the speed of building the decoding tables. See the comments below that precede the lbits and dbits tuning parameters. */ /* Notes beyond the 1.93a appnote.txt: 1. Distance pointers never point before the beginning of the output stream. 2. Distance pointers can point back across blocks, up to 32k away. 3. There is an implied maximum of 7 bits for the bit length table and 15 bits for the actual data. 4. If only one code exists, then it is encoded using one bit. (Zero would be more efficient, but perhaps a little confusing.) If two codes exist, they are coded using one bit each (0 and 1). 5. There is no way of sending zero distance codes--a dummy must be sent if there are none. (History: a pre 2.0 version of PKZIP would store blocks with no distance codes, but this was discovered to be too harsh a criterion.) Valid only for 1.93a. 2.04c does allow zero distance codes, which is sent as one code of zero bits in length. 6. There are up to 286 literal/length codes. Code 256 represents the end-of-block. Note however that the static length tree defines 288 codes just to fill out the Huffman codes. Codes 286 and 287 cannot be used though, since there is no length base or extra bits defined for them. Similarly, there are up to 30 distance codes. However, static trees define 32 codes (all 5 bits) to fill out the Huffman codes, but the last two had better not show up in the data. 7. Unzip can check dynamic Huffman blocks for complete code sets. The exception is that a single code would not be complete (see #4). 8. The five bits following the block type is really the number of literal codes sent minus 257. 9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits (1+6+6). Therefore, to output three times the length, you output three codes (1+1+1), whereas to output four times the same length, you only need two codes (1+3). Hmm. 10. In the tree reconstruction algorithm, Code = Code + Increment only if BitLength(i) is not zero. (Pretty obvious.) 11. Correction: 4 Bits: # of Bit Length codes - 4 (4 - 19) 12. Note: length code 284 can represent 227-258, but length code 285 really is 258. The last length deserves its own, short code since it gets used a lot in very redundant files. The length 258 is special since 258 - 3 (the min match length) is 255. 13. The literal/length and distance code bit lengths are read as a single stream of lengths. It is possible (and advantageous) for a repeat code (16, 17, or 18) to go across the boundary between the two sets of lengths. */ #ifdef RCSID static char rcsid[] = "$Id$"; #endif #include <config.h> #include "tailor.h" #if defined STDC_HEADERS || defined HAVE_STDLIB_H # include <stdlib.h> #endif #include "gzip.h" #define slide window /* Huffman code lookup table entry--this entry is four bytes for machines that have 16-bit pointers (e.g. PC's in the small or medium model). Valid extra bits are 0..13. e == 15 is EOB (end of block), e == 16 means that v is a literal, 16 < e < 32 means that v is a pointer to the next table, which codes e - 16 bits, and lastly e == 99 indicates an unused code. If a code with e == 99 is looked up, this implies an error in the data. */ struct huft { uch e; /* number of extra bits or operation */ uch b; /* number of bits in this code or subcode */ union { ush n; /* literal, length base, or distance base */ struct huft *t; /* pointer to next level of table */ } v; }; /* Function prototypes */ int huft_build OF((unsigned *, unsigned, unsigned, ush *, ush *, struct huft **, int *)); int huft_free OF((struct huft *)); int inflate_codes OF((struct huft *, struct huft *, int, int)); int inflate_stored OF((void)); int inflate_fixed OF((void)); int inflate_dynamic OF((void)); int inflate_block OF((int *)); int inflate OF((void)); /* The inflate algorithm uses a sliding 32K byte window on the uncompressed stream to find repeated byte strings. This is implemented here as a circular buffer. The index is updated simply by incrementing and then and'ing with 0x7fff (32K-1). */ /* It is left to other modules to supply the 32K area. It is assumed to be usable as if it were declared "uch slide[32768];" or as just "uch *slide;" and then malloc'ed in the latter case. The definition must be in unzip.h, included above. */ /* unsigned wp; current position in slide */ #define wp outcnt #define flush_output(w) (wp=(w),flush_window()) /* Tables for deflate from PKZIP's appnote.txt. */ static unsigned border[] = { /* Order of the bit length code lengths */ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; static ush cplens[] = { /* Copy lengths for literal codes 257..285 */ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; /* note: see note #13 above about the 258 in this list. */ static ush cplext[] = { /* Extra bits for literal codes 257..285 */ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99}; /* 99==invalid */ static ush cpdist[] = { /* Copy offsets for distance codes 0..29 */ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; static ush cpdext[] = { /* Extra bits for distance codes */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; /* Macros for inflate() bit peeking and grabbing. The usage is: NEEDBITS(j) x = b & mask_bits[j]; DUMPBITS(j) where NEEDBITS makes sure that b has at least j bits in it, and DUMPBITS removes the bits from b. The macros use the variable k for the number of bits in b. Normally, b and k are register variables for speed, and are initialized at the beginning of a routine that uses these macros from a global bit buffer and count. The macros also use the variable w, which is a cached copy of wp. If we assume that EOB will be the longest code, then we will never ask for bits with NEEDBITS that are beyond the end of the stream. So, NEEDBITS should not read any more bytes than are needed to meet the request. Then no bytes need to be "returned" to the buffer at the end of the last block. However, this assumption is not true for fixed blocks--the EOB code is 7 bits, but the other literal/length codes can be 8 or 9 bits. (The EOB code is shorter than other codes because fixed blocks are generally short. So, while a block always has an EOB, many other literal/length codes have a significantly lower probability of showing up at all.) However, by making the first table have a lookup of seven bits, the EOB code will be found in that first lookup, and so will not require that too many bits be pulled from the stream. */ ulg bb; /* bit buffer */ unsigned bk; /* bits in bit buffer */ ush mask_bits[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff, 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff }; #define GETBYTE() (inptr < insize ? inbuf[inptr++] : (wp = w, fill_inbuf(0))) #ifdef CRYPT uch cc; # define NEXTBYTE() \ (decrypt ? (cc = GETBYTE(), zdecode(cc), cc) : GETBYTE()) #else # define NEXTBYTE() (uch)GETBYTE() #endif #define NEEDBITS(n) {while(k<(n)){b|=((ulg)NEXTBYTE())<<k;k+=8;}} #define DUMPBITS(n) {b>>=(n);k-=(n);} /* Huffman code decoding is performed using a multi-level table lookup. The fastest way to decode is to simply build a lookup table whose size is determined by the longest code. However, the time it takes to build this table can also be a factor if the data being decoded is not very long. The most common codes are necessarily the shortest codes, so those codes dominate the decoding time, and hence the speed. The idea is you can have a shorter table that decodes the shorter, more probable codes, and then point to subsidiary tables for the longer codes. The time it costs to decode the longer codes is then traded against the time it takes to make longer tables. This results of this trade are in the variables lbits and dbits below. lbits is the number of bits the first level table for literal/ length codes can decode in one step, and dbits is the same thing for the distance codes. Subsequent tables are also less than or equal to those sizes. These values may be adjusted either when all of the codes are shorter than that, in which case the longest code length in bits is used, or when the shortest code is *longer* than the requested table size, in which case the length of the shortest code in bits is used. There are two different values for the two tables, since they code a different number of possibilities each. The literal/length table codes 286 possible values, or in a flat code, a little over eight bits. The distance table codes 30 possible values, or a little less than five bits, flat. The optimum values for speed end up being about one bit more than those, so lbits is 8+1 and dbits is 5+1. The optimum values may differ though from machine to machine, and possibly even between compilers. Your mileage may vary. */ int lbits = 9; /* bits in base literal/length lookup table */ int dbits = 6; /* bits in base distance lookup table */ /* If BMAX needs to be larger than 16, then h and x[] should be ulg. */ #define BMAX 16 /* maximum bit length of any code (16 for explode) */ #define N_MAX 288 /* maximum number of codes in any set */ unsigned hufts; /* track memory usage */ int huft_build(b, n, s, d, e, t, m) unsigned *b; /* code lengths in bits (all assumed <= BMAX) */ unsigned n; /* number of codes (assumed <= N_MAX) */ unsigned s; /* number of simple-valued codes (0..s-1) */ ush *d; /* list of base values for non-simple codes */ ush *e; /* list of extra bits for non-simple codes */ struct huft **t; /* result: starting table */ int *m; /* maximum lookup bits, returns actual */ /* Given a list of code lengths and a maximum table size, make a set of tables to decode that set of codes. Return zero on success, one if the given code set is incomplete (the tables are still built in this case), two if the input is invalid (all zero length codes or an oversubscribed set of lengths), and three if not enough memory. */ { unsigned a; /* counter for codes of length k */ unsigned c[BMAX+1]; /* bit length count table */ unsigned f; /* i repeats in table every f entries */ int g; /* maximum code length */ int h; /* table level */ register unsigned i; /* counter, current code */ register unsigned j; /* counter */ register int k; /* number of bits in current code */ int l; /* bits per table (returned in m) */ register unsigned *p; /* pointer into c[], b[], or v[] */ register struct huft *q; /* points to current table */ struct huft r; /* table entry for structure assignment */ struct huft *u[BMAX]; /* table stack */ unsigned v[N_MAX]; /* values in order of bit length */ register int w; /* bits before this table == (l * h) */ unsigned x[BMAX+1]; /* bit offsets, then code stack */ unsigned *xp; /* pointer into x */ int y; /* number of dummy codes added */ unsigned z; /* number of entries in current table */ /* Generate counts for each bit length */ memzero(c, sizeof(c)); p = b; i = n; do { Tracecv(*p, (stderr, (n-i >= ' ' && n-i <= '~' ? "%c %d\n" : "0x%x %d\n"), n-i, *p)); c[*p]++; /* assume all entries <= BMAX */ p++; /* Can't combine with above line (Solaris bug) */ } while (--i); if (c[0] == n) /* null input--all zero length codes */ { q = (struct huft *) malloc (3 * sizeof *q); if (!q) return 3; hufts += 3; q[0].v.t = (struct huft *) NULL; q[1].e = 99; /* invalid code marker */ q[1].b = 1; q[2].e = 99; /* invalid code marker */ q[2].b = 1; *t = q + 1; *m = 1; return 0; } /* Find minimum and maximum length, bound *m by those */ l = *m; for (j = 1; j <= BMAX; j++) if (c[j]) break; k = j; /* minimum code length */ if ((unsigned)l < j) l = j; for (i = BMAX; i; i--) if (c[i]) break; g = i; /* maximum code length */ if ((unsigned)l > i) l = i; *m = l; /* Adjust last length count to fill out codes, if needed */ for (y = 1 << j; j < i; j++, y <<= 1) if ((y -= c[j]) < 0) return 2; /* bad input: more codes than bits */ if ((y -= c[i]) < 0) return 2; c[i] += y; /* Generate starting offsets into the value table for each length */ x[1] = j = 0; p = c + 1; xp = x + 2; while (--i) { /* note that i == g from above */ *xp++ = (j += *p++); } /* Make a table of values in order of bit lengths */ p = b; i = 0; do { if ((j = *p++) != 0) v[x[j]++] = i; } while (++i < n); n = x[g]; /* set n to length of v */ /* Generate the Huffman codes and for each, make the table entries */ x[0] = i = 0; /* first Huffman code is zero */ p = v; /* grab values in bit order */ h = -1; /* no tables yet--level -1 */ w = -l; /* bits decoded == (l * h) */ u[0] = (struct huft *)NULL; /* just to keep compilers happy */ q = (struct huft *)NULL; /* ditto */ z = 0; /* ditto */ /* go through the bit lengths (k already is bits in shortest code) */ for (; k <= g; k++) { a = c[k]; while (a--) { /* here i is the Huffman code of length k bits for value *p */ /* make tables up to required level */ while (k > w + l) { h++; w += l; /* previous table always l bits */ /* compute minimum size table less than or equal to l bits */ z = (z = g - w) > (unsigned)l ? l : z; /* upper limit on table size */ if ((f = 1 << (j = k - w)) > a + 1) /* try a k-w bit table */ { /* too few codes for k-w bit table */ f -= a + 1; /* deduct codes from patterns left */ xp = c + k; if (j < z) while (++j < z) /* try smaller tables up to z bits */ { if ((f <<= 1) <= *++xp) break; /* enough codes to use up j bits */ f -= *xp; /* else deduct codes from patterns */ } } z = 1 << j; /* table entries for j-bit table */ /* allocate and link in new table */ if ((q = (struct huft *)malloc((z + 1)*sizeof(struct huft))) == (struct huft *)NULL) { if (h) huft_free(u[0]); return 3; /* not enough memory */ } hufts += z + 1; /* track memory usage */ *t = q + 1; /* link to list for huft_free() */ *(t = &(q->v.t)) = (struct huft *)NULL; u[h] = ++q; /* table starts after link */ /* connect to last table, if there is one */ if (h) { x[h] = i; /* save pattern for backing up */ r.b = (uch)l; /* bits to dump before this table */ r.e = (uch)(16 + j); /* bits in this table */ r.v.t = q; /* pointer to this table */ j = i >> (w - l); /* (get around Turbo C bug) */ u[h-1][j] = r; /* connect to last table */ } } /* set up table entry in r */ r.b = (uch)(k - w); if (p >= v + n) r.e = 99; /* out of values--invalid code */ else if (*p < s) { r.e = (uch)(*p < 256 ? 16 : 15); /* 256 is end-of-block code */ r.v.n = (ush)(*p); /* simple code is just the value */ p++; /* one compiler does not like *p++ */ } else { r.e = (uch)e[*p - s]; /* non-simple--look up in lists */ r.v.n = d[*p++ - s]; } /* fill code-like entries with r */ f = 1 << (k - w); for (j = i >> w; j < z; j += f) q[j] = r; /* backwards increment the k-bit code i */ for (j = 1 << (k - 1); i & j; j >>= 1) i ^= j; i ^= j; /* backup over finished tables */ while ((i & ((1 << w) - 1)) != x[h]) { h--; /* don't need to update q */ w -= l; } } } /* Return true (1) if we were given an incomplete table */ return y != 0 && g != 1; } int huft_free(t) struct huft *t; /* table to free */ /* Free the malloc'ed tables built by huft_build(), which makes a linked list of the tables it made, with the links in a dummy first entry of each table. */ { register struct huft *p, *q; /* Go through linked list, freeing from the malloced (t[-1]) address. */ p = t; while (p != (struct huft *)NULL) { q = (--p)->v.t; free((char*)p); p = q; } return 0; } int inflate_codes(tl, td, bl, bd) struct huft *tl, *td; /* literal/length and distance decoder tables */ int bl, bd; /* number of bits decoded by tl[] and td[] */ /* inflate (decompress) the codes in a deflated (compressed) block. Return an error code or zero if it all goes ok. */ { register unsigned e; /* table entry flag/number of extra bits */ unsigned n, d; /* length and index for copy */ unsigned w; /* current window position */ struct huft *t; /* pointer to table entry */ unsigned ml, md; /* masks for bl and bd bits */ register ulg b; /* bit buffer */ register unsigned k; /* number of bits in bit buffer */ /* make local copies of globals */ b = bb; /* initialize bit buffer */ k = bk; w = wp; /* initialize window position */ /* inflate the coded data */ ml = mask_bits[bl]; /* precompute masks for speed */ md = mask_bits[bd]; for (;;) /* do until end of block */ { NEEDBITS((unsigned)bl) if ((e = (t = tl + ((unsigned)b & ml))->e) > 16) do { if (e == 99) return 1; DUMPBITS(t->b) e -= 16; NEEDBITS(e) } while ((e = (t = t->v.t + ((unsigned)b & mask_bits[e]))->e) > 16); DUMPBITS(t->b) if (e == 16) /* then it's a literal */ { slide[w++] = (uch)t->v.n; Tracevv((stderr, "%c", slide[w-1])); if (w == WSIZE) { flush_output(w); w = 0; } } else /* it's an EOB or a length */ { /* exit if end of block */ if (e == 15) break; /* get length of block to copy */ NEEDBITS(e) n = t->v.n + ((unsigned)b & mask_bits[e]); DUMPBITS(e); /* decode distance of block to copy */ NEEDBITS((unsigned)bd) if ((e = (t = td + ((unsigned)b & md))->e) > 16) do { if (e == 99) return 1; DUMPBITS(t->b) e -= 16; NEEDBITS(e) } while ((e = (t = t->v.t + ((unsigned)b & mask_bits[e]))->e) > 16); DUMPBITS(t->b) NEEDBITS(e) d = w - t->v.n - ((unsigned)b & mask_bits[e]); DUMPBITS(e) Tracevv((stderr,"\\[%d,%d]", w-d, n)); /* do the copy */ do { n -= (e = (e = WSIZE - ((d &= WSIZE-1) > w ? d : w)) > n ? n : e); #if !defined(NOMEMCPY) && !defined(DEBUG) if (w - d >= e) /* (this test assumes unsigned comparison) */ { memcpy(slide + w, slide + d, e); w += e; d += e; } else /* do it slow to avoid memcpy() overlap */ #endif /* !NOMEMCPY */ do { slide[w++] = slide[d++]; Tracevv((stderr, "%c", slide[w-1])); } while (--e); if (w == WSIZE) { flush_output(w); w = 0; } } while (n); } } /* restore the globals from the locals */ wp = w; /* restore global window pointer */ bb = b; /* restore global bit buffer */ bk = k; /* done */ return 0; } int inflate_stored() /* "decompress" an inflated type 0 (stored) block. */ { unsigned n; /* number of bytes in block */ unsigned w; /* current window position */ register ulg b; /* bit buffer */ register unsigned k; /* number of bits in bit buffer */ /* make local copies of globals */ b = bb; /* initialize bit buffer */ k = bk; w = wp; /* initialize window position */ /* go to byte boundary */ n = k & 7; DUMPBITS(n); /* get the length and its complement */ NEEDBITS(16) n = ((unsigned)b & 0xffff); DUMPBITS(16) NEEDBITS(16) if (n != (unsigned)((~b) & 0xffff)) return 1; /* error in compressed data */ DUMPBITS(16) /* read and output the compressed data */ while (n--) { NEEDBITS(8) slide[w++] = (uch)b; if (w == WSIZE) { flush_output(w); w = 0; } DUMPBITS(8) } /* restore the globals from the locals */ wp = w; /* restore global window pointer */ bb = b; /* restore global bit buffer */ bk = k; return 0; } int inflate_fixed() /* decompress an inflated type 1 (fixed Huffman codes) block. We should either replace this with a custom decoder, or at least precompute the Huffman tables. */ { int i; /* temporary variable */ struct huft *tl; /* literal/length code table */ struct huft *td; /* distance code table */ int bl; /* lookup bits for tl */ int bd; /* lookup bits for td */ unsigned l[288]; /* length list for huft_build */ /* set up literal table */ for (i = 0; i < 144; i++) l[i] = 8; for (; i < 256; i++) l[i] = 9; for (; i < 280; i++) l[i] = 7; for (; i < 288; i++) /* make a complete, but wrong code set */ l[i] = 8; bl = 7; if ((i = huft_build(l, 288, 257, cplens, cplext, &tl, &bl)) != 0) return i; /* set up distance table */ for (i = 0; i < 30; i++) /* make an incomplete code set */ l[i] = 5; bd = 5; if ((i = huft_build(l, 30, 0, cpdist, cpdext, &td, &bd)) > 1) { huft_free(tl); return i; } /* decompress until an end-of-block code */ if (inflate_codes(tl, td, bl, bd)) return 1; /* free the decoding tables, return */ huft_free(tl); huft_free(td); return 0; } int inflate_dynamic() /* decompress an inflated type 2 (dynamic Huffman codes) block. */ { int i; /* temporary variables */ unsigned j; unsigned l; /* last length */ unsigned m; /* mask for bit lengths table */ unsigned n; /* number of lengths to get */ unsigned w; /* current window position */ struct huft *tl; /* literal/length code table */ struct huft *td; /* distance code table */ int bl; /* lookup bits for tl */ int bd; /* lookup bits for td */ unsigned nb; /* number of bit length codes */ unsigned nl; /* number of literal/length codes */ unsigned nd; /* number of distance codes */ #ifdef PKZIP_BUG_WORKAROUND unsigned ll[288+32]; /* literal/length and distance code lengths */ #else unsigned ll[286+30]; /* literal/length and distance code lengths */ #endif register ulg b; /* bit buffer */ register unsigned k; /* number of bits in bit buffer */ /* make local bit buffer */ b = bb; k = bk; w = wp; /* read in table lengths */ NEEDBITS(5) nl = 257 + ((unsigned)b & 0x1f); /* number of literal/length codes */ DUMPBITS(5) NEEDBITS(5) nd = 1 + ((unsigned)b & 0x1f); /* number of distance codes */ DUMPBITS(5) NEEDBITS(4) nb = 4 + ((unsigned)b & 0xf); /* number of bit length codes */ DUMPBITS(4) #ifdef PKZIP_BUG_WORKAROUND if (nl > 288 || nd > 32) #else if (nl > 286 || nd > 30) #endif return 1; /* bad lengths */ /* read in bit-length-code lengths */ for (j = 0; j < nb; j++) { NEEDBITS(3) ll[border[j]] = (unsigned)b & 7; DUMPBITS(3) } for (; j < 19; j++) ll[border[j]] = 0; /* build decoding table for trees--single level, 7 bit lookup */ bl = 7; if ((i = huft_build(ll, 19, 19, NULL, NULL, &tl, &bl)) != 0) { if (i == 1) huft_free(tl); return i; /* incomplete code set */ } if (tl == NULL) /* Grrrhhh */ return 2; /* read in literal and distance code lengths */ n = nl + nd; m = mask_bits[bl]; i = l = 0; while ((unsigned)i < n) { NEEDBITS((unsigned)bl) j = (td = tl + ((unsigned)b & m))->b; DUMPBITS(j) j = td->v.n; if (j < 16) /* length of code in bits (0..15) */ ll[i++] = l = j; /* save last length in l */ else if (j == 16) /* repeat last length 3 to 6 times */ { NEEDBITS(2) j = 3 + ((unsigned)b & 3); DUMPBITS(2) if ((unsigned)i + j > n) return 1; while (j--) ll[i++] = l; } else if (j == 17) /* 3 to 10 zero length codes */ { NEEDBITS(3) j = 3 + ((unsigned)b & 7); DUMPBITS(3) if ((unsigned)i + j > n) return 1; while (j--) ll[i++] = 0; l = 0; } else /* j == 18: 11 to 138 zero length codes */ { NEEDBITS(7) j = 11 + ((unsigned)b & 0x7f); DUMPBITS(7) if ((unsigned)i + j > n) return 1; while (j--) ll[i++] = 0; l = 0; } } /* free decoding table for trees */ huft_free(tl); /* restore the global bit buffer */ bb = b; bk = k; /* build the decoding tables for literal/length and distance codes */ bl = lbits; if ((i = huft_build(ll, nl, 257, cplens, cplext, &tl, &bl)) != 0) { if (i == 1) { Trace ((stderr, " incomplete literal tree\n")); huft_free(tl); } return i; /* incomplete code set */ } bd = dbits; if ((i = huft_build(ll + nl, nd, 0, cpdist, cpdext, &td, &bd)) != 0) { if (i == 1) { Trace ((stderr, " incomplete distance tree\n")); #ifdef PKZIP_BUG_WORKAROUND i = 0; } #else huft_free(td); } huft_free(tl); return i; /* incomplete code set */ #endif } /* decompress until an end-of-block code */ if (inflate_codes(tl, td, bl, bd)) return 1; /* free the decoding tables, return */ huft_free(tl); huft_free(td); return 0; } int inflate_block(e) int *e; /* last block flag */ /* decompress an inflated block */ { unsigned t; /* block type */ unsigned w; /* current window position */ register ulg b; /* bit buffer */ register unsigned k; /* number of bits in bit buffer */ /* make local bit buffer */ b = bb; k = bk; w = wp; /* read in last block bit */ NEEDBITS(1) *e = (int)b & 1; DUMPBITS(1) /* read in block type */ NEEDBITS(2) t = (unsigned)b & 3; DUMPBITS(2) /* restore the global bit buffer */ bb = b; bk = k; /* inflate that block type */ if (t == 2) return inflate_dynamic(); if (t == 0) return inflate_stored(); if (t == 1) return inflate_fixed(); /* bad block type */ return 2; } int inflate() /* decompress an inflated entry */ { int e; /* last block flag */ int r; /* result code */ unsigned h; /* maximum struct huft's malloc'ed */ /* initialize window, bit buffer */ wp = 0; bk = 0; bb = 0; /* decompress until the last block */ h = 0; do { hufts = 0; if ((r = inflate_block(&e)) != 0) return r; if (hufts > h) h = hufts; } while (!e); /* Undo too much lookahead. The next read will be byte aligned so we * can discard unused bits in the last meaningful byte. */ while (bk >= 8) { bk -= 8; inptr--; } /* flush out slide */ flush_output(wp); /* return success */ Trace ((stderr, "<%u> ", h)); return 0; }
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/gzip_2009-08-16-3fe0caeada-39a362ae9d.c
manybugs_data_30
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | Rasmus Lerdorf <[email protected]> | | Andrei Zmievski <[email protected]> | | Stig Venaas <[email protected]> | | Jason Greene <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "php.h" #include "php_ini.h" #include <stdarg.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <stdio.h> #if HAVE_STRING_H #include <string.h> #else #include <strings.h> #endif #ifdef PHP_WIN32 #include "win32/unistd.h" #endif #include "zend_globals.h" #include "zend_interfaces.h" #include "php_globals.h" #include "php_array.h" #include "basic_functions.h" #include "php_string.h" #include "php_rand.h" #include "php_smart_str.h" #ifdef HAVE_SPL #include "ext/spl/spl_array.h" #endif /* {{{ defines */ #define EXTR_OVERWRITE 0 #define EXTR_SKIP 1 #define EXTR_PREFIX_SAME 2 #define EXTR_PREFIX_ALL 3 #define EXTR_PREFIX_INVALID 4 #define EXTR_PREFIX_IF_EXISTS 5 #define EXTR_IF_EXISTS 6 #define EXTR_REFS 0x100 #define CASE_LOWER 0 #define CASE_UPPER 1 #define COUNT_NORMAL 0 #define COUNT_RECURSIVE 1 #define DIFF_NORMAL 1 #define DIFF_KEY 2 #define DIFF_ASSOC 6 #define DIFF_COMP_DATA_NONE -1 #define DIFF_COMP_DATA_INTERNAL 0 #define DIFF_COMP_DATA_USER 1 #define DIFF_COMP_KEY_INTERNAL 0 #define DIFF_COMP_KEY_USER 1 #define INTERSECT_NORMAL 1 #define INTERSECT_KEY 2 #define INTERSECT_ASSOC 6 #define INTERSECT_COMP_DATA_NONE -1 #define INTERSECT_COMP_DATA_INTERNAL 0 #define INTERSECT_COMP_DATA_USER 1 #define INTERSECT_COMP_KEY_INTERNAL 0 #define INTERSECT_COMP_KEY_USER 1 #define DOUBLE_DRIFT_FIX 0.000000000000001 /* }}} */ ZEND_DECLARE_MODULE_GLOBALS(array) /* {{{ php_array_init_globals */ static void php_array_init_globals(zend_array_globals *array_globals) { memset(array_globals, 0, sizeof(zend_array_globals)); } /* }}} */ PHP_MINIT_FUNCTION(array) /* {{{ */ { ZEND_INIT_MODULE_GLOBALS(array, php_array_init_globals, NULL); REGISTER_LONG_CONSTANT("EXTR_OVERWRITE", EXTR_OVERWRITE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_SKIP", EXTR_SKIP, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_PREFIX_SAME", EXTR_PREFIX_SAME, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_PREFIX_ALL", EXTR_PREFIX_ALL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_PREFIX_INVALID", EXTR_PREFIX_INVALID, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_PREFIX_IF_EXISTS", EXTR_PREFIX_IF_EXISTS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_IF_EXISTS", EXTR_IF_EXISTS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_REFS", EXTR_REFS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_ASC", PHP_SORT_ASC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_DESC", PHP_SORT_DESC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_REGULAR", PHP_SORT_REGULAR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_NUMERIC", PHP_SORT_NUMERIC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_STRING", PHP_SORT_STRING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_LOCALE_STRING", PHP_SORT_LOCALE_STRING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("CASE_LOWER", CASE_LOWER, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("CASE_UPPER", CASE_UPPER, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("COUNT_NORMAL", COUNT_NORMAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("COUNT_RECURSIVE", COUNT_RECURSIVE, CONST_CS | CONST_PERSISTENT); return SUCCESS; } /* }}} */ PHP_MSHUTDOWN_FUNCTION(array) /* {{{ */ { #ifdef ZTS ts_free_id(array_globals_id); #endif return SUCCESS; } /* }}} */ static void php_set_compare_func(int sort_type TSRMLS_DC) /* {{{ */ { switch (sort_type) { case PHP_SORT_NUMERIC: ARRAYG(compare_func) = numeric_compare_function; break; case PHP_SORT_STRING: ARRAYG(compare_func) = string_compare_function; break; #if HAVE_STRCOLL case PHP_SORT_LOCALE_STRING: ARRAYG(compare_func) = string_locale_compare_function; break; #endif case PHP_SORT_REGULAR: default: ARRAYG(compare_func) = compare_function; break; } } /* }}} */ static int php_array_key_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { Bucket *f; Bucket *s; zval result; zval first; zval second; f = *((Bucket **) a); s = *((Bucket **) b); if (f->nKeyLength == 0) { Z_TYPE(first) = IS_LONG; Z_LVAL(first) = f->h; } else { Z_TYPE(first) = IS_STRING; Z_STRVAL(first) = f->arKey; Z_STRLEN(first) = f->nKeyLength - 1; } if (s->nKeyLength == 0) { Z_TYPE(second) = IS_LONG; Z_LVAL(second) = s->h; } else { Z_TYPE(second) = IS_STRING; Z_STRVAL(second) = s->arKey; Z_STRLEN(second) = s->nKeyLength - 1; } if (ARRAYG(compare_func)(&result, &first, &second TSRMLS_CC) == FAILURE) { return 0; } if (Z_TYPE(result) == IS_DOUBLE) { if (Z_DVAL(result) < 0) { return -1; } else if (Z_DVAL(result) > 0) { return 1; } else { return 0; } } convert_to_long(&result); if (Z_LVAL(result) < 0) { return -1; } else if (Z_LVAL(result) > 0) { return 1; } return 0; } /* }}} */ static int php_array_reverse_key_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { return php_array_key_compare(a, b TSRMLS_CC) * -1; } /* }}} */ /* {{{ proto bool krsort(array &array_arg [, int sort_flags]) Sort an array by key value in reverse order */ PHP_FUNCTION(krsort) { zval *array; long sort_type = PHP_SORT_REGULAR; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { RETURN_FALSE; } php_set_compare_func(sort_type TSRMLS_CC); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_reverse_key_compare, 0 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool ksort(array &array_arg [, int sort_flags]) Sort an array by key */ PHP_FUNCTION(ksort) { zval *array; long sort_type = PHP_SORT_REGULAR; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { RETURN_FALSE; } php_set_compare_func(sort_type TSRMLS_CC); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_key_compare, 0 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ static int php_count_recursive(zval *array, long mode TSRMLS_DC) /* {{{ */ { long cnt = 0; zval **element; if (Z_TYPE_P(array) == IS_ARRAY) { if (Z_ARRVAL_P(array)->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); return 0; } cnt = zend_hash_num_elements(Z_ARRVAL_P(array)); if (mode == COUNT_RECURSIVE) { HashPosition pos; for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(array), &pos); zend_hash_get_current_data_ex(Z_ARRVAL_P(array), (void **) &element, &pos) == SUCCESS; zend_hash_move_forward_ex(Z_ARRVAL_P(array), &pos) ) { Z_ARRVAL_P(array)->nApplyCount++; cnt += php_count_recursive(*element, COUNT_RECURSIVE TSRMLS_CC); Z_ARRVAL_P(array)->nApplyCount--; } } } return cnt; } /* }}} */ /* {{{ proto int count(mixed var [, int mode]) Count the number of elements in a variable (usually an array) */ PHP_FUNCTION(count) { zval *array; long mode = COUNT_NORMAL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|l", &array, &mode) == FAILURE) { return; } switch (Z_TYPE_P(array)) { case IS_NULL: RETURN_LONG(0); break; case IS_ARRAY: RETURN_LONG (php_count_recursive (array, mode TSRMLS_CC)); break; case IS_OBJECT: { #ifdef HAVE_SPL zval *retval; #endif /* first, we check if the handler is defined */ if (Z_OBJ_HT_P(array)->count_elements) { RETVAL_LONG(1); if (SUCCESS == Z_OBJ_HT(*array)->count_elements(array, &Z_LVAL_P(return_value) TSRMLS_CC)) { return; } } #ifdef HAVE_SPL /* if not and the object implements Countable we call its count() method */ if (Z_OBJ_HT_P(array)->get_class_entry && instanceof_function(Z_OBJCE_P(array), spl_ce_Countable TSRMLS_CC)) { zend_call_method_with_0_params(&array, NULL, NULL, "count", &retval); if (retval) { convert_to_long_ex(&retval); RETVAL_LONG(Z_LVAL_P(retval)); zval_ptr_dtor(&retval); } return; } #endif } default: RETURN_LONG(1); break; } } /* }}} */ /* Numbers are always smaller than strings int this function as it * anyway doesn't make much sense to compare two different data types. * This keeps it consistant and simple. * * This is not correct any more, depends on what compare_func is set to. */ static int php_array_data_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { Bucket *f; Bucket *s; zval result; zval *first; zval *second; f = *((Bucket **) a); s = *((Bucket **) b); first = *((zval **) f->pData); second = *((zval **) s->pData); if (ARRAYG(compare_func)(&result, first, second TSRMLS_CC) == FAILURE) { return 0; } if (Z_TYPE(result) == IS_DOUBLE) { if (Z_DVAL(result) < 0) { return -1; } else if (Z_DVAL(result) > 0) { return 1; } else { return 0; } } convert_to_long(&result); if (Z_LVAL(result) < 0) { return -1; } else if (Z_LVAL(result) > 0) { return 1; } return 0; } /* }}} */ static int php_array_reverse_data_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { return php_array_data_compare(a, b TSRMLS_CC) * -1; } /* }}} */ static int php_array_natural_general_compare(const void *a, const void *b, int fold_case) /* {{{ */ { Bucket *f, *s; zval *fval, *sval; zval first, second; int result; f = *((Bucket **) a); s = *((Bucket **) b); fval = *((zval **) f->pData); sval = *((zval **) s->pData); first = *fval; second = *sval; if (Z_TYPE_P(fval) != IS_STRING) { zval_copy_ctor(&first); convert_to_string(&first); } if (Z_TYPE_P(sval) != IS_STRING) { zval_copy_ctor(&second); convert_to_string(&second); } result = strnatcmp_ex(Z_STRVAL(first), Z_STRLEN(first), Z_STRVAL(second), Z_STRLEN(second), fold_case); if (Z_TYPE_P(fval) != IS_STRING) { zval_dtor(&first); } if (Z_TYPE_P(sval) != IS_STRING) { zval_dtor(&second); } return result; } /* }}} */ static int php_array_natural_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { return php_array_natural_general_compare(a, b, 0); } /* }}} */ static int php_array_natural_case_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { return php_array_natural_general_compare(a, b, 1); } /* }}} */ static void php_natsort(INTERNAL_FUNCTION_PARAMETERS, int fold_case) /* {{{ */ { zval *array; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) { return; } if (fold_case) { if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_natural_case_compare, 0 TSRMLS_CC) == FAILURE) { return; } } else { if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_natural_compare, 0 TSRMLS_CC) == FAILURE) { return; } } RETURN_TRUE; } /* }}} */ /* {{{ proto void natsort(array &array_arg) Sort an array using natural sort */ PHP_FUNCTION(natsort) { php_natsort(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto void natcasesort(array &array_arg) Sort an array using case-insensitive natural sort */ PHP_FUNCTION(natcasesort) { php_natsort(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto bool asort(array &array_arg [, int sort_flags]) Sort an array and maintain index association */ PHP_FUNCTION(asort) { zval *array; long sort_type = PHP_SORT_REGULAR; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { RETURN_FALSE; } php_set_compare_func(sort_type TSRMLS_CC); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_data_compare, 0 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool arsort(array &array_arg [, int sort_flags]) Sort an array in reverse order and maintain index association */ PHP_FUNCTION(arsort) { zval *array; long sort_type = PHP_SORT_REGULAR; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { RETURN_FALSE; } php_set_compare_func(sort_type TSRMLS_CC); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_reverse_data_compare, 0 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool sort(array &array_arg [, int sort_flags]) Sort an array */ PHP_FUNCTION(sort) { zval *array; long sort_type = PHP_SORT_REGULAR; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { RETURN_FALSE; } php_set_compare_func(sort_type TSRMLS_CC); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_data_compare, 1 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool rsort(array &array_arg [, int sort_flags]) Sort an array in reverse order */ PHP_FUNCTION(rsort) { zval *array; long sort_type = PHP_SORT_REGULAR; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { RETURN_FALSE; } php_set_compare_func(sort_type TSRMLS_CC); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_reverse_data_compare, 1 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ static int php_array_user_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { Bucket *f; Bucket *s; zval **args[2]; zval *retval_ptr = NULL; f = *((Bucket **) a); s = *((Bucket **) b); args[0] = (zval **) f->pData; args[1] = (zval **) s->pData; BG(user_compare_fci).param_count = 2; BG(user_compare_fci).params = args; BG(user_compare_fci).retval_ptr_ptr = &retval_ptr; BG(user_compare_fci).no_separation = 0; if (zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache) TSRMLS_CC) == SUCCESS && retval_ptr) { long retval; convert_to_long_ex(&retval_ptr); retval = Z_LVAL_P(retval_ptr); zval_ptr_dtor(&retval_ptr); return retval < 0 ? -1 : retval > 0 ? 1 : 0; } else { return 0; } } /* }}} */ /* check if comparison function is valid */ #define PHP_ARRAY_CMP_FUNC_CHECK(func_name) \ if (!zend_is_callable(*func_name, 0, NULL TSRMLS_CC)) { \ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid comparison function"); \ BG(user_compare_fci) = old_user_compare_fci; \ BG(user_compare_fci_cache) = old_user_compare_fci_cache; \ RETURN_FALSE; \ } \ /* Clear FCI cache otherwise : for example the same or other array with * (partly) the same key values has been sorted with uasort() or * other sorting function the comparison is cached, however the name * of the function for comparison is not respected. see bug #28739 AND #33295 * * Following defines will assist in backup / restore values. */ #define PHP_ARRAY_CMP_FUNC_VARS \ zend_fcall_info old_user_compare_fci; \ zend_fcall_info_cache old_user_compare_fci_cache \ #define PHP_ARRAY_CMP_FUNC_BACKUP() \ old_user_compare_fci = BG(user_compare_fci); \ old_user_compare_fci_cache = BG(user_compare_fci_cache); \ BG(user_compare_fci_cache) = empty_fcall_info_cache; \ #define PHP_ARRAY_CMP_FUNC_RESTORE() \ BG(user_compare_fci) = old_user_compare_fci; \ BG(user_compare_fci_cache) = old_user_compare_fci_cache; \ /* {{{ proto bool usort(array array_arg, string cmp_function) Sort an array by values using a user-defined comparison function */ PHP_FUNCTION(usort) { zval *array; unsigned int refcount; PHP_ARRAY_CMP_FUNC_VARS; PHP_ARRAY_CMP_FUNC_BACKUP(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "af", &array, &BG(user_compare_fci), &BG(user_compare_fci_cache)) == FAILURE) { PHP_ARRAY_CMP_FUNC_RESTORE(); return; } /* Clear the is_ref flag, so the attemts to modify the array in user * comparison function will create a copy of array and won't affect the * original array. The fact of modification is detected using refcount * comparison. The result of sorting in such case is undefined and the * function returns FALSE. */ Z_UNSET_ISREF_P(array); refcount = Z_REFCOUNT_P(array); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_user_compare, 1 TSRMLS_CC) == FAILURE) { RETVAL_FALSE; } else { if (refcount > Z_REFCOUNT_P(array)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array was modified by the user comparison function"); RETVAL_FALSE; } else { RETVAL_TRUE; } } if (Z_REFCOUNT_P(array) > 1) { Z_SET_ISREF_P(array); } PHP_ARRAY_CMP_FUNC_RESTORE(); } /* }}} */ /* {{{ proto bool uasort(array array_arg, string cmp_function) Sort an array with a user-defined comparison function and maintain index association */ PHP_FUNCTION(uasort) { zval *array; unsigned int refcount; PHP_ARRAY_CMP_FUNC_VARS; PHP_ARRAY_CMP_FUNC_BACKUP(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "af", &array, &BG(user_compare_fci), &BG(user_compare_fci_cache)) == FAILURE) { PHP_ARRAY_CMP_FUNC_RESTORE(); return; } /* Clear the is_ref flag, so the attemts to modify the array in user * comaprison function will create a copy of array and won't affect the * original array. The fact of modification is detected using refcount * comparison. The result of sorting in such case is undefined and the * function returns FALSE. */ Z_UNSET_ISREF_P(array); refcount = Z_REFCOUNT_P(array); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_user_compare, 0 TSRMLS_CC) == FAILURE) { RETVAL_FALSE; } else { if (refcount > Z_REFCOUNT_P(array)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array was modified by the user comparison function"); RETVAL_FALSE; } else { RETVAL_TRUE; } } if (Z_REFCOUNT_P(array) > 1) { Z_SET_ISREF_P(array); } PHP_ARRAY_CMP_FUNC_RESTORE(); } /* }}} */ static int php_array_user_key_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { Bucket *f; Bucket *s; zval *key1, *key2; zval **args[2]; zval *retval_ptr = NULL; long result; ALLOC_INIT_ZVAL(key1); ALLOC_INIT_ZVAL(key2); args[0] = &key1; args[1] = &key2; f = *((Bucket **) a); s = *((Bucket **) b); if (f->nKeyLength == 0) { Z_LVAL_P(key1) = f->h; Z_TYPE_P(key1) = IS_LONG; } else { Z_STRVAL_P(key1) = estrndup(f->arKey, f->nKeyLength - 1); Z_STRLEN_P(key1) = f->nKeyLength - 1; Z_TYPE_P(key1) = IS_STRING; } if (s->nKeyLength == 0) { Z_LVAL_P(key2) = s->h; Z_TYPE_P(key2) = IS_LONG; } else { Z_STRVAL_P(key2) = estrndup(s->arKey, s->nKeyLength - 1); Z_STRLEN_P(key2) = s->nKeyLength - 1; Z_TYPE_P(key2) = IS_STRING; } BG(user_compare_fci).param_count = 2; BG(user_compare_fci).params = args; BG(user_compare_fci).retval_ptr_ptr = &retval_ptr; BG(user_compare_fci).no_separation = 0; if (zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache) TSRMLS_CC) == SUCCESS && retval_ptr) { convert_to_long_ex(&retval_ptr); result = Z_LVAL_P(retval_ptr); zval_ptr_dtor(&retval_ptr); } else { result = 0; } zval_ptr_dtor(&key1); zval_ptr_dtor(&key2); return result; } /* }}} */ /* {{{ proto bool uksort(array array_arg, string cmp_function) Sort an array by keys using a user-defined comparison function */ PHP_FUNCTION(uksort) { zval *array; unsigned int refcount; PHP_ARRAY_CMP_FUNC_VARS; PHP_ARRAY_CMP_FUNC_BACKUP(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "af", &array, &BG(user_compare_fci), &BG(user_compare_fci_cache)) == FAILURE) { PHP_ARRAY_CMP_FUNC_RESTORE(); return; } /* Clear the is_ref flag, so the attemts to modify the array in user * comaprison function will create a copy of array and won't affect the * original array. The fact of modification is detected using refcount * comparison. The result of sorting in such case is undefined and the * function returns FALSE. */ Z_UNSET_ISREF_P(array); refcount = Z_REFCOUNT_P(array); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_user_key_compare, 0 TSRMLS_CC) == FAILURE) { RETVAL_FALSE; } else { if (refcount > Z_REFCOUNT_P(array)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array was modified by the user comparison function"); RETVAL_FALSE; } else { RETVAL_TRUE; } } if (Z_REFCOUNT_P(array) > 1) { Z_SET_ISREF_P(array); } PHP_ARRAY_CMP_FUNC_RESTORE(); } /* }}} */ /* {{{ proto mixed end(array array_arg) Advances array argument's internal pointer to the last element and return it */ PHP_FUNCTION(end) { HashTable *array; zval **entry; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "H", &array) == FAILURE) { return; } zend_hash_internal_pointer_end(array); if (return_value_used) { if (zend_hash_get_current_data(array, (void **) &entry) == FAILURE) { RETURN_FALSE; } RETURN_ZVAL(*entry, 1, 0); } } /* }}} */ /* {{{ proto mixed prev(array array_arg) Move array argument's internal pointer to the previous element and return it */ PHP_FUNCTION(prev) { HashTable *array; zval **entry; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "H", &array) == FAILURE) { return; } zend_hash_move_backwards(array); if (return_value_used) { if (zend_hash_get_current_data(array, (void **) &entry) == FAILURE) { RETURN_FALSE; } RETURN_ZVAL(*entry, 1, 0); } } /* }}} */ /* {{{ proto mixed next(array array_arg) Move array argument's internal pointer to the next element and return it */ PHP_FUNCTION(next) { HashTable *array; zval **entry; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "H", &array) == FAILURE) { return; } zend_hash_move_forward(array); if (return_value_used) { if (zend_hash_get_current_data(array, (void **) &entry) == FAILURE) { RETURN_FALSE; } RETURN_ZVAL(*entry, 1, 0); } } /* }}} */ /* {{{ proto mixed reset(array array_arg) Set array argument's internal pointer to the first element and return it */ PHP_FUNCTION(reset) { HashTable *array; zval **entry; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "H", &array) == FAILURE) { return; } zend_hash_internal_pointer_reset(array); if (return_value_used) { if (zend_hash_get_current_data(array, (void **) &entry) == FAILURE) { RETURN_FALSE; } RETURN_ZVAL(*entry, 1, 0); } } /* }}} */ /* {{{ proto mixed current(array array_arg) Return the element currently pointed to by the internal array pointer */ PHP_FUNCTION(current) { HashTable *array; zval **entry; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "H", &array) == FAILURE) { return; } if (zend_hash_get_current_data(array, (void **) &entry) == FAILURE) { RETURN_FALSE; } RETURN_ZVAL(*entry, 1, 0); } /* }}} */ /* {{{ proto mixed key(array array_arg) Return the key of the element currently pointed to by the internal array pointer */ PHP_FUNCTION(key) { HashTable *array; char *string_key; uint string_length; ulong num_key; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "H", &array) == FAILURE) { return; } switch (zend_hash_get_current_key_ex(array, &string_key, &string_length, &num_key, 0, NULL)) { case HASH_KEY_IS_STRING: RETVAL_STRINGL(string_key, string_length - 1, 1); break; case HASH_KEY_IS_LONG: RETVAL_LONG(num_key); break; case HASH_KEY_NON_EXISTANT: return; } } /* }}} */ /* {{{ proto mixed min(mixed arg1 [, mixed arg2 [, mixed ...]]) Return the lowest value in an array or a series of arguments */ PHP_FUNCTION(min) { int argc; zval ***args = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &argc) == FAILURE) { return; } php_set_compare_func(PHP_SORT_REGULAR TSRMLS_CC); /* mixed min ( array $values ) */ if (argc == 1) { zval **result; if (Z_TYPE_PP(args[0]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "When only one parameter is given, it must be an array"); RETVAL_NULL(); } else { if (zend_hash_minmax(Z_ARRVAL_PP(args[0]), php_array_data_compare, 0, (void **) &result TSRMLS_CC) == SUCCESS) { RETVAL_ZVAL(*result, 1, 0); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array must contain at least one element"); RETVAL_FALSE; } } } else { /* mixed min ( mixed $value1 , mixed $value2 [, mixed $value3... ] ) */ zval **min, result; int i; min = args[0]; for (i = 1; i < argc; i++) { is_smaller_function(&result, *args[i], *min TSRMLS_CC); if (Z_LVAL(result) == 1) { min = args[i]; } } RETVAL_ZVAL(*min, 1, 0); } if (args) { efree(args); } } /* }}} */ /* {{{ proto mixed max(mixed arg1 [, mixed arg2 [, mixed ...]]) Return the highest value in an array or a series of arguments */ PHP_FUNCTION(max) { zval ***args = NULL; int argc; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &argc) == FAILURE) { return; } php_set_compare_func(PHP_SORT_REGULAR TSRMLS_CC); /* mixed max ( array $values ) */ if (argc == 1) { zval **result; if (Z_TYPE_PP(args[0]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "When only one parameter is given, it must be an array"); RETVAL_NULL(); } else { if (zend_hash_minmax(Z_ARRVAL_PP(args[0]), php_array_data_compare, 1, (void **) &result TSRMLS_CC) == SUCCESS) { RETVAL_ZVAL(*result, 1, 0); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array must contain at least one element"); RETVAL_FALSE; } } } else { /* mixed max ( mixed $value1 , mixed $value2 [, mixed $value3... ] ) */ zval **max, result; int i; max = args[0]; for (i = 1; i < argc; i++) { is_smaller_or_equal_function(&result, *args[i], *max TSRMLS_CC); if (Z_LVAL(result) == 0) { max = args[i]; } } RETVAL_ZVAL(*max, 1, 0); } if (args) { efree(args); } } /* }}} */ static int php_array_walk(HashTable *target_hash, zval **userdata, int recursive TSRMLS_DC) /* {{{ */ { zval **args[3], /* Arguments to userland function */ *retval_ptr, /* Return value - unused */ *key=NULL; /* Entry key */ char *string_key; uint string_key_len; ulong num_key; HashPosition pos; /* Set up known arguments */ args[1] = &key; args[2] = userdata; if (userdata) { Z_ADDREF_PP(userdata); } zend_hash_internal_pointer_reset_ex(target_hash, &pos); BG(array_walk_fci).retval_ptr_ptr = &retval_ptr; BG(array_walk_fci).param_count = userdata ? 3 : 2; BG(array_walk_fci).params = args; BG(array_walk_fci).no_separation = 0; /* Iterate through hash */ while (!EG(exception) && zend_hash_get_current_data_ex(target_hash, (void **)&args[0], &pos) == SUCCESS) { if (recursive && Z_TYPE_PP(args[0]) == IS_ARRAY) { HashTable *thash; zend_fcall_info orig_array_walk_fci; zend_fcall_info_cache orig_array_walk_fci_cache; SEPARATE_ZVAL_IF_NOT_REF(args[0]); thash = Z_ARRVAL_PP(args[0]); if (thash->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); if (userdata) { zval_ptr_dtor(userdata); } return 0; } /* backup the fcall info and cache */ orig_array_walk_fci = BG(array_walk_fci); orig_array_walk_fci_cache = BG(array_walk_fci_cache); thash->nApplyCount++; php_array_walk(thash, userdata, recursive TSRMLS_CC); thash->nApplyCount--; /* restore the fcall info and cache */ BG(array_walk_fci) = orig_array_walk_fci; BG(array_walk_fci_cache) = orig_array_walk_fci_cache; } else { /* Allocate space for key */ MAKE_STD_ZVAL(key); /* Set up the key */ switch (zend_hash_get_current_key_ex(target_hash, &string_key, &string_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_LONG: Z_TYPE_P(key) = IS_LONG; Z_LVAL_P(key) = num_key; break; case HASH_KEY_IS_STRING: ZVAL_STRINGL(key, string_key, string_key_len - 1, 1); break; } /* Call the userland function */ if (zend_call_function(&BG(array_walk_fci), &BG(array_walk_fci_cache) TSRMLS_CC) == SUCCESS) { if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } } else { if (key) { zval_ptr_dtor(&key); key = NULL; } break; } } if (key) { zval_ptr_dtor(&key); key = NULL; } zend_hash_move_forward_ex(target_hash, &pos); } if (userdata) { zval_ptr_dtor(userdata); } return 0; } /* }}} */ /* {{{ proto bool array_walk(array input, string funcname [, mixed userdata]) Apply a user function to every member of an array */ PHP_FUNCTION(array_walk) { HashTable *array; zval *userdata = NULL; zend_fcall_info orig_array_walk_fci; zend_fcall_info_cache orig_array_walk_fci_cache; orig_array_walk_fci = BG(array_walk_fci); orig_array_walk_fci_cache = BG(array_walk_fci_cache); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Hf|z/", &array, &BG(array_walk_fci), &BG(array_walk_fci_cache), &userdata) == FAILURE) { BG(array_walk_fci) = orig_array_walk_fci; BG(array_walk_fci_cache) = orig_array_walk_fci_cache; return; } php_array_walk(array, userdata ? &userdata : NULL, 0 TSRMLS_CC); BG(array_walk_fci) = orig_array_walk_fci; BG(array_walk_fci_cache) = orig_array_walk_fci_cache; RETURN_TRUE; } /* }}} */ /* {{{ proto bool array_walk_recursive(array input, string funcname [, mixed userdata]) Apply a user function recursively to every member of an array */ PHP_FUNCTION(array_walk_recursive) { HashTable *array; zval *userdata = NULL; zend_fcall_info orig_array_walk_fci; zend_fcall_info_cache orig_array_walk_fci_cache; orig_array_walk_fci = BG(array_walk_fci); orig_array_walk_fci_cache = BG(array_walk_fci_cache); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Hf|z/", &array, &BG(array_walk_fci), &BG(array_walk_fci_cache), &userdata) == FAILURE) { BG(array_walk_fci) = orig_array_walk_fci; BG(array_walk_fci_cache) = orig_array_walk_fci_cache; return; } php_array_walk(array, userdata ? &userdata : NULL, 1 TSRMLS_CC); BG(array_walk_fci) = orig_array_walk_fci; BG(array_walk_fci_cache) = orig_array_walk_fci_cache; RETURN_TRUE; } /* }}} */ /* void php_search_array(INTERNAL_FUNCTION_PARAMETERS, int behavior) * 0 = return boolean * 1 = return key */ static void php_search_array(INTERNAL_FUNCTION_PARAMETERS, int behavior) /* {{{ */ { zval *value, /* value to check for */ *array, /* array to check in */ **entry, /* pointer to array entry */ res; /* comparison result */ HashPosition pos; /* hash iterator */ zend_bool strict = 0; /* strict comparison or not */ ulong num_key; uint str_key_len; char *string_key; int (*is_equal_func)(zval *, zval *, zval * TSRMLS_DC) = is_equal_function; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "za|b", &value, &array, &strict) == FAILURE) { return; } if (strict) { is_equal_func = is_identical_function; } zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(array), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(array), (void **)&entry, &pos) == SUCCESS) { is_equal_func(&res, value, *entry TSRMLS_CC); if (Z_LVAL(res)) { if (behavior == 0) { RETURN_TRUE; } else { /* Return current key */ switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(array), &string_key, &str_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_STRING: RETURN_STRINGL(string_key, str_key_len - 1, 1); break; case HASH_KEY_IS_LONG: RETURN_LONG(num_key); break; } } } zend_hash_move_forward_ex(Z_ARRVAL_P(array), &pos); } RETURN_FALSE; } /* }}} */ /* {{{ proto bool in_array(mixed needle, array haystack [, bool strict]) Checks if the given value exists in the array */ PHP_FUNCTION(in_array) { php_search_array(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto mixed array_search(mixed needle, array haystack [, bool strict]) Searches the array for a given value and returns the corresponding key if successful */ PHP_FUNCTION(array_search) { php_search_array(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ static int php_valid_var_name(char *var_name, int var_name_len) /* {{{ */ { int i, ch; if (!var_name || !var_name_len) { return 0; } /* These are allowed as first char: [a-zA-Z_\x7f-\xff] */ ch = (int)((unsigned char *)var_name)[0]; if (var_name[0] != '_' && (ch < 65 /* A */ || /* Z */ ch > 90) && (ch < 97 /* a */ || /* z */ ch > 122) && (ch < 127 /* 0x7f */ || /* 0xff */ ch > 255) ) { return 0; } /* And these as the rest: [a-zA-Z0-9_\x7f-\xff] */ if (var_name_len > 1) { for (i = 1; i < var_name_len; i++) { ch = (int)((unsigned char *)var_name)[i]; if (var_name[i] != '_' && (ch < 48 /* 0 */ || /* 9 */ ch > 57) && (ch < 65 /* A */ || /* Z */ ch > 90) && (ch < 97 /* a */ || /* z */ ch > 122) && (ch < 127 /* 0x7f */ || /* 0xff */ ch > 255) ) { return 0; } } } return 1; } /* }}} */ PHPAPI int php_prefix_varname(zval *result, zval *prefix, char *var_name, int var_name_len, zend_bool add_underscore TSRMLS_DC) /* {{{ */ { Z_STRLEN_P(result) = Z_STRLEN_P(prefix) + (add_underscore ? 1 : 0) + var_name_len; Z_TYPE_P(result) = IS_STRING; Z_STRVAL_P(result) = emalloc(Z_STRLEN_P(result) + 1); memcpy(Z_STRVAL_P(result), Z_STRVAL_P(prefix), Z_STRLEN_P(prefix)); if (add_underscore) { Z_STRVAL_P(result)[Z_STRLEN_P(prefix)] = '_'; } memcpy(Z_STRVAL_P(result) + Z_STRLEN_P(prefix) + (add_underscore ? 1 : 0), var_name, var_name_len + 1); return SUCCESS; } /* }}} */ /* {{{ proto int extract(array var_array [, int extract_type [, string prefix]]) Imports variables into symbol table from an array */ PHP_FUNCTION(extract) { zval *var_array, *prefix = NULL; long extract_type = EXTR_OVERWRITE; zval **entry, *data; char *var_name; ulong num_key; uint var_name_len; int var_exists, key_type, count = 0; int extract_refs = 0; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|lz/", &var_array, &extract_type, &prefix) == FAILURE) { return; } extract_refs = (extract_type & EXTR_REFS); extract_type &= 0xff; if (extract_type < EXTR_OVERWRITE || extract_type > EXTR_IF_EXISTS) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid extract type"); return; } if (extract_type > EXTR_SKIP && extract_type <= EXTR_PREFIX_IF_EXISTS && ZEND_NUM_ARGS() < 3) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "specified extract type requires the prefix parameter"); return; } if (prefix) { convert_to_string(prefix); if (Z_STRLEN_P(prefix) && !php_valid_var_name(Z_STRVAL_P(prefix), Z_STRLEN_P(prefix))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "prefix is not a valid identifier"); return; } } if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } /* var_array is passed by ref for the needs of EXTR_REFS (needs to * work on the original array to create refs to its members) * simulate pass_by_value if EXTR_REFS is not used */ if (!extract_refs) { SEPARATE_ARG_IF_REF(var_array); } zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(var_array), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(var_array), (void **)&entry, &pos) == SUCCESS) { zval final_name; ZVAL_NULL(&final_name); key_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(var_array), &var_name, &var_name_len, &num_key, 0, &pos); var_exists = 0; if (key_type == HASH_KEY_IS_STRING) { var_name_len--; var_exists = zend_hash_exists(EG(active_symbol_table), var_name, var_name_len + 1); } else if (key_type == HASH_KEY_IS_LONG && (extract_type == EXTR_PREFIX_ALL || extract_type == EXTR_PREFIX_INVALID)) { zval num; ZVAL_LONG(&num, num_key); convert_to_string(&num); php_prefix_varname(&final_name, prefix, Z_STRVAL(num), Z_STRLEN(num), 1 TSRMLS_CC); zval_dtor(&num); } else { zend_hash_move_forward_ex(Z_ARRVAL_P(var_array), &pos); continue; } switch (extract_type) { case EXTR_IF_EXISTS: if (!var_exists) break; /* break omitted intentionally */ case EXTR_OVERWRITE: /* GLOBALS protection */ if (var_exists && var_name_len == sizeof("GLOBALS")-1 && !strcmp(var_name, "GLOBALS")) { break; } if (var_exists && var_name_len == sizeof("this")-1 && !strcmp(var_name, "this") && EG(scope) && EG(scope)->name_length != 0) { break; } ZVAL_STRINGL(&final_name, var_name, var_name_len, 1); break; case EXTR_PREFIX_IF_EXISTS: if (var_exists) { php_prefix_varname(&final_name, prefix, var_name, var_name_len, 1 TSRMLS_CC); } break; case EXTR_PREFIX_SAME: if (!var_exists && var_name_len != 0) { ZVAL_STRINGL(&final_name, var_name, var_name_len, 1); } /* break omitted intentionally */ case EXTR_PREFIX_ALL: if (Z_TYPE(final_name) == IS_NULL && var_name_len != 0) { php_prefix_varname(&final_name, prefix, var_name, var_name_len, 1 TSRMLS_CC); } break; case EXTR_PREFIX_INVALID: if (Z_TYPE(final_name) == IS_NULL) { if (!php_valid_var_name(var_name, var_name_len)) { php_prefix_varname(&final_name, prefix, var_name, var_name_len, 1 TSRMLS_CC); } else { ZVAL_STRINGL(&final_name, var_name, var_name_len, 1); } } break; default: if (!var_exists) { ZVAL_STRINGL(&final_name, var_name, var_name_len, 1); } break; } if (Z_TYPE(final_name) != IS_NULL && php_valid_var_name(Z_STRVAL(final_name), Z_STRLEN(final_name))) { if (extract_refs) { zval **orig_var; SEPARATE_ZVAL_TO_MAKE_IS_REF(entry); zval_add_ref(entry); if (zend_hash_find(EG(active_symbol_table), Z_STRVAL(final_name), Z_STRLEN(final_name) + 1, (void **) &orig_var) == SUCCESS) { zval_ptr_dtor(orig_var); *orig_var = *entry; } else { zend_hash_update(EG(active_symbol_table), Z_STRVAL(final_name), Z_STRLEN(final_name) + 1, (void **) entry, sizeof(zval *), NULL); } } else { MAKE_STD_ZVAL(data); *data = **entry; zval_copy_ctor(data); ZEND_SET_SYMBOL_WITH_LENGTH(EG(active_symbol_table), Z_STRVAL(final_name), Z_STRLEN(final_name) + 1, data, 1, 0); } count++; } zval_dtor(&final_name); zend_hash_move_forward_ex(Z_ARRVAL_P(var_array), &pos); } if (!extract_refs) { zval_ptr_dtor(&var_array); } RETURN_LONG(count); } /* }}} */ static void php_compact_var(HashTable *eg_active_symbol_table, zval *return_value, zval *entry TSRMLS_DC) /* {{{ */ { zval **value_ptr, *value, *data; if (Z_TYPE_P(entry) == IS_STRING) { if (zend_hash_find(eg_active_symbol_table, Z_STRVAL_P(entry), Z_STRLEN_P(entry) + 1, (void **)&value_ptr) != FAILURE) { value = *value_ptr; ALLOC_ZVAL(data); MAKE_COPY_ZVAL(&value, data); zend_hash_update(Z_ARRVAL_P(return_value), Z_STRVAL_P(entry), Z_STRLEN_P(entry) + 1, &data, sizeof(zval *), NULL); } } else if (Z_TYPE_P(entry) == IS_ARRAY) { HashPosition pos; if ((Z_ARRVAL_P(entry)->nApplyCount > 1)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); return; } Z_ARRVAL_P(entry)->nApplyCount++; zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(entry), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(entry), (void**)&value_ptr, &pos) == SUCCESS) { value = *value_ptr; php_compact_var(eg_active_symbol_table, return_value, value TSRMLS_CC); zend_hash_move_forward_ex(Z_ARRVAL_P(entry), &pos); } Z_ARRVAL_P(entry)->nApplyCount--; } } /* }}} */ /* {{{ proto array compact(mixed var_names [, mixed ...]) Creates a hash containing variables and their values */ PHP_FUNCTION(compact) { zval ***args = NULL; /* function arguments array */ int num_args, i; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &num_args) == FAILURE) { return; } if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } /* compact() is probably most used with a single array of var_names or multiple string names, rather than a combination of both. So quickly guess a minimum result size based on that */ if (ZEND_NUM_ARGS() == 1 && Z_TYPE_PP(args[0]) == IS_ARRAY) { array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_PP(args[0]))); } else { array_init_size(return_value, ZEND_NUM_ARGS()); } for (i=0; i<ZEND_NUM_ARGS(); i++) { php_compact_var(EG(active_symbol_table), return_value, *args[i] TSRMLS_CC); } if (args) { efree(args); } } /* }}} */ /* {{{ proto array array_fill(int start_key, int num, mixed val) Create an array containing num elements starting with index start_key each initialized to val */ PHP_FUNCTION(array_fill) { zval *val; long start_key, num; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "llz", &start_key, &num, &val) == FAILURE) { return; } if (num < 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number of elements must be positive"); RETURN_FALSE; } /* allocate an array for return */ array_init_size(return_value, num); num--; zval_add_ref(&val); zend_hash_index_update(Z_ARRVAL_P(return_value), start_key, &val, sizeof(zval *), NULL); while (num--) { zval_add_ref(&val); zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &val, sizeof(zval *), NULL); } } /* }}} */ /* {{{ proto array array_fill_keys(array keys, mixed val) Create an array using the elements of the first parameter as keys each initialized to val */ PHP_FUNCTION(array_fill_keys) { zval *keys, *val, **entry; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "az", &keys, &val) == FAILURE) { return; } /* Initialize return array */ array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(keys))); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(keys), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(keys), (void **)&entry, &pos) == SUCCESS) { if (Z_TYPE_PP(entry) == IS_LONG) { zval_add_ref(&val); zend_hash_index_update(Z_ARRVAL_P(return_value), Z_LVAL_PP(entry), &val, sizeof(zval *), NULL); } else { zval key, *key_ptr = *entry; if (Z_TYPE_PP(entry) != IS_STRING) { key = **entry; zval_copy_ctor(&key); convert_to_string(&key); key_ptr = &key; } zval_add_ref(&val); zend_symtable_update(Z_ARRVAL_P(return_value), Z_STRVAL_P(key_ptr), Z_STRLEN_P(key_ptr) + 1, &val, sizeof(zval *), NULL); if (key_ptr != *entry) { zval_dtor(&key); } } zend_hash_move_forward_ex(Z_ARRVAL_P(keys), &pos); } } /* }}} */ /* {{{ proto array range(mixed low, mixed high[, int step]) Create an array containing the range of integers or characters from low to high (inclusive) */ PHP_FUNCTION(range) { zval *zlow, *zhigh, *zstep = NULL; int err = 0, is_step_double = 0; double step = 1.0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z/z/|z/", &zlow, &zhigh, &zstep) == FAILURE) { RETURN_FALSE; } if (zstep) { if (Z_TYPE_P(zstep) == IS_DOUBLE || (Z_TYPE_P(zstep) == IS_STRING && is_numeric_string(Z_STRVAL_P(zstep), Z_STRLEN_P(zstep), NULL, NULL, 0) == IS_DOUBLE) ) { is_step_double = 1; } convert_to_double_ex(&zstep); step = Z_DVAL_P(zstep); /* We only want positive step values. */ if (step < 0.0) { step *= -1; } } /* Initialize the return_value as an array. */ array_init(return_value); /* If the range is given as strings, generate an array of characters. */ if (Z_TYPE_P(zlow) == IS_STRING && Z_TYPE_P(zhigh) == IS_STRING && Z_STRLEN_P(zlow) >= 1 && Z_STRLEN_P(zhigh) >= 1) { int type1, type2; unsigned char *low, *high; long lstep = (long) step; type1 = is_numeric_string(Z_STRVAL_P(zlow), Z_STRLEN_P(zlow), NULL, NULL, 0); type2 = is_numeric_string(Z_STRVAL_P(zhigh), Z_STRLEN_P(zhigh), NULL, NULL, 0); if (type1 == IS_DOUBLE || type2 == IS_DOUBLE || is_step_double) { goto double_str; } else if (type1 == IS_LONG || type2 == IS_LONG) { goto long_str; } convert_to_string(zlow); convert_to_string(zhigh); low = (unsigned char *)Z_STRVAL_P(zlow); high = (unsigned char *)Z_STRVAL_P(zhigh); if (*low > *high) { /* Negative Steps */ unsigned char ch = *low; if (lstep <= 0) { err = 1; goto err; } for (; ch >= *high; ch -= (unsigned int)lstep) { add_next_index_stringl(return_value, (const char *)&ch, 1, 1); if (((signed int)ch - lstep) < 0) { break; } } } else if (*high > *low) { /* Positive Steps */ unsigned char ch = *low; if (lstep <= 0) { err = 1; goto err; } for (; ch <= *high; ch += (unsigned int)lstep) { add_next_index_stringl(return_value, (const char *)&ch, 1, 1); if (((signed int)ch + lstep) > 255) { break; } } } else { add_next_index_stringl(return_value, (const char *)low, 1, 1); } } else if (Z_TYPE_P(zlow) == IS_DOUBLE || Z_TYPE_P(zhigh) == IS_DOUBLE || is_step_double) { double low, high; double_str: convert_to_double(zlow); convert_to_double(zhigh); low = Z_DVAL_P(zlow); high = Z_DVAL_P(zhigh); if (low > high) { /* Negative steps */ if (low - high < step || step <= 0) { err = 1; goto err; } for (; low >= (high - DOUBLE_DRIFT_FIX); low -= step) { add_next_index_double(return_value, low); } } else if (high > low) { /* Positive steps */ if (high - low < step || step <= 0) { err = 1; goto err; } for (; low <= (high + DOUBLE_DRIFT_FIX); low += step) { add_next_index_double(return_value, low); } } else { add_next_index_double(return_value, low); } } else { double low, high; long lstep; long_str: convert_to_double(zlow); convert_to_double(zhigh); low = Z_DVAL_P(zlow); high = Z_DVAL_P(zhigh); lstep = (long) step; if (low > high) { /* Negative steps */ if (low - high < lstep || lstep <= 0) { err = 1; goto err; } for (; low >= high; low -= lstep) { add_next_index_long(return_value, (long)low); } } else if (high > low) { /* Positive steps */ if (high - low < lstep || lstep <= 0) { err = 1; goto err; } for (; low <= high; low += lstep) { add_next_index_long(return_value, (long)low); } } else { add_next_index_long(return_value, (long)low); } } err: if (err) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "step exceeds the specified range"); zval_dtor(return_value); RETURN_FALSE; } } /* }}} */ static void php_array_data_shuffle(zval *array TSRMLS_DC) /* {{{ */ { Bucket **elems, *temp; HashTable *hash; int j, n_elems, rnd_idx, n_left; n_elems = zend_hash_num_elements(Z_ARRVAL_P(array)); if (n_elems < 1) { return; } elems = (Bucket **)safe_emalloc(n_elems, sizeof(Bucket *), 0); hash = Z_ARRVAL_P(array); n_left = n_elems; for (j = 0, temp = hash->pListHead; temp; temp = temp->pListNext) elems[j++] = temp; while (--n_left) { rnd_idx = php_rand(TSRMLS_C); RAND_RANGE(rnd_idx, 0, n_left, PHP_RAND_MAX); if (rnd_idx != n_left) { temp = elems[n_left]; elems[n_left] = elems[rnd_idx]; elems[rnd_idx] = temp; } } HANDLE_BLOCK_INTERRUPTIONS(); hash->pListHead = elems[0]; hash->pListTail = NULL; hash->pInternalPointer = hash->pListHead; for (j = 0; j < n_elems; j++) { if (hash->pListTail) { hash->pListTail->pListNext = elems[j]; } elems[j]->pListLast = hash->pListTail; elems[j]->pListNext = NULL; hash->pListTail = elems[j]; } temp = hash->pListHead; j = 0; while (temp != NULL) { temp->nKeyLength = 0; temp->h = j++; temp = temp->pListNext; } hash->nNextFreeElement = n_elems; zend_hash_rehash(hash); HANDLE_UNBLOCK_INTERRUPTIONS(); efree(elems); } /* }}} */ /* {{{ proto bool shuffle(array array_arg) Randomly shuffle the contents of an array */ PHP_FUNCTION(shuffle) { zval *array; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) { RETURN_FALSE; } php_array_data_shuffle(array TSRMLS_CC); RETURN_TRUE; } /* }}} */ PHPAPI HashTable* php_splice(HashTable *in_hash, int offset, int length, zval ***list, int list_count, HashTable **removed) /* {{{ */ { HashTable *out_hash = NULL; /* Output hashtable */ int num_in, /* Number of entries in the input hashtable */ pos, /* Current position in the hashtable */ i; /* Loop counter */ Bucket *p; /* Pointer to hash bucket */ zval *entry; /* Hash entry */ /* If input hash doesn't exist, we have nothing to do */ if (!in_hash) { return NULL; } /* Get number of entries in the input hash */ num_in = zend_hash_num_elements(in_hash); /* Clamp the offset.. */ if (offset > num_in) { offset = num_in; } else if (offset < 0 && (offset = (num_in + offset)) < 0) { offset = 0; } /* ..and the length */ if (length < 0) { length = num_in - offset + length; } else if (((unsigned)offset + (unsigned)length) > (unsigned)num_in) { length = num_in - offset; } /* Create and initialize output hash */ ALLOC_HASHTABLE(out_hash); zend_hash_init(out_hash, (length > 0 ? num_in - length : 0) + list_count, NULL, ZVAL_PTR_DTOR, 0); /* Start at the beginning of the input hash and copy entries to output hash until offset is reached */ for (pos = 0, p = in_hash->pListHead; pos < offset && p ; pos++, p = p->pListNext) { /* Get entry and increase reference count */ entry = *((zval **)p->pData); Z_ADDREF_P(entry); /* Update output hash depending on key type */ if (p->nKeyLength == 0) { zend_hash_next_index_insert(out_hash, &entry, sizeof(zval *), NULL); } else { zend_hash_quick_update(out_hash, p->arKey, p->nKeyLength, p->h, &entry, sizeof(zval *), NULL); } } /* If hash for removed entries exists, go until offset+length and copy the entries to it */ if (removed != NULL) { for ( ; pos < offset + length && p; pos++, p = p->pListNext) { entry = *((zval **)p->pData); Z_ADDREF_P(entry); if (p->nKeyLength == 0) { zend_hash_next_index_insert(*removed, &entry, sizeof(zval *), NULL); } else { zend_hash_quick_update(*removed, p->arKey, p->nKeyLength, p->h, &entry, sizeof(zval *), NULL); } } } else { /* otherwise just skip those entries */ for ( ; pos < offset + length && p; pos++, p = p->pListNext); } /* If there are entries to insert.. */ if (list != NULL) { /* ..for each one, create a new zval, copy entry into it and copy it into the output hash */ for (i = 0; i < list_count; i++) { entry = *list[i]; Z_ADDREF_P(entry); zend_hash_next_index_insert(out_hash, &entry, sizeof(zval *), NULL); } } /* Copy the remaining input hash entries to the output hash */ for ( ; p ; p = p->pListNext) { entry = *((zval **)p->pData); Z_ADDREF_P(entry); if (p->nKeyLength == 0) { zend_hash_next_index_insert(out_hash, &entry, sizeof(zval *), NULL); } else { zend_hash_quick_update(out_hash, p->arKey, p->nKeyLength, p->h, &entry, sizeof(zval *), NULL); } } zend_hash_internal_pointer_reset(out_hash); return out_hash; } /* }}} */ /* {{{ proto int array_push(array stack, mixed var [, mixed ...]) Pushes elements onto the end of the array */ PHP_FUNCTION(array_push) { zval ***args, /* Function arguments array */ *stack, /* Input array */ *new_var; /* Variable to be pushed */ int i, /* Loop counter */ argc; /* Number of function arguments */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a+", &stack, &args, &argc) == FAILURE) { return; } /* For each subsequent argument, make it a reference, increase refcount, and add it to the end of the array */ for (i = 0; i < argc; i++) { new_var = *args[i]; Z_ADDREF_P(new_var); if (zend_hash_next_index_insert(Z_ARRVAL_P(stack), &new_var, sizeof(zval *), NULL) == FAILURE) { Z_DELREF_P(new_var); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot add element to the array as the next element is already occupied"); efree(args); RETURN_FALSE; } } /* Clean up and return the number of values in the stack */ efree(args); RETVAL_LONG(zend_hash_num_elements(Z_ARRVAL_P(stack))); } /* }}} */ /* {{{ void _phpi_pop(INTERNAL_FUNCTION_PARAMETERS, int off_the_end) */ static void _phpi_pop(INTERNAL_FUNCTION_PARAMETERS, int off_the_end) { zval *stack, /* Input stack */ **val; /* Value to be popped */ char *key = NULL; uint key_len = 0; ulong index; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &stack) == FAILURE) { return; } if (zend_hash_num_elements(Z_ARRVAL_P(stack)) == 0) { return; } /* Get the first or last value and copy it into the return value */ if (off_the_end) { zend_hash_internal_pointer_end(Z_ARRVAL_P(stack)); } else { zend_hash_internal_pointer_reset(Z_ARRVAL_P(stack)); } zend_hash_get_current_data(Z_ARRVAL_P(stack), (void **)&val); RETVAL_ZVAL(*val, 1, 0); /* Delete the first or last value */ zend_hash_get_current_key_ex(Z_ARRVAL_P(stack), &key, &key_len, &index, 0, NULL); if (key && Z_ARRVAL_P(stack) == &EG(symbol_table)) { zend_delete_global_variable(key, key_len - 1 TSRMLS_CC); } else { zend_hash_del_key_or_index(Z_ARRVAL_P(stack), key, key_len, index, (key) ? HASH_DEL_KEY : HASH_DEL_INDEX); } /* If we did a shift... re-index like it did before */ if (!off_the_end) { unsigned int k = 0; int should_rehash = 0; Bucket *p = Z_ARRVAL_P(stack)->pListHead; while (p != NULL) { if (p->nKeyLength == 0) { if (p->h != k) { p->h = k++; should_rehash = 1; } else { k++; } } p = p->pListNext; } Z_ARRVAL_P(stack)->nNextFreeElement = k; if (should_rehash) { zend_hash_rehash(Z_ARRVAL_P(stack)); } } else if (!key_len && index >= Z_ARRVAL_P(stack)->nNextFreeElement - 1) { Z_ARRVAL_P(stack)->nNextFreeElement = Z_ARRVAL_P(stack)->nNextFreeElement - 1; } zend_hash_internal_pointer_reset(Z_ARRVAL_P(stack)); } /* }}} */ /* {{{ proto mixed array_pop(array stack) Pops an element off the end of the array */ PHP_FUNCTION(array_pop) { _phpi_pop(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto mixed array_shift(array stack) Pops an element off the beginning of the array */ PHP_FUNCTION(array_shift) { _phpi_pop(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto int array_unshift(array stack, mixed var [, mixed ...]) Pushes elements onto the beginning of the array */ PHP_FUNCTION(array_unshift) { zval ***args, /* Function arguments array */ *stack; /* Input stack */ HashTable *new_hash; /* New hashtable for the stack */ HashTable old_hash; int argc; /* Number of function arguments */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a+", &stack, &args, &argc) == FAILURE) { return; } /* Use splice to insert the elements at the beginning. Destroy old * hashtable and replace it with new one */ new_hash = php_splice(Z_ARRVAL_P(stack), 0, 0, &args[0], argc, NULL); old_hash = *Z_ARRVAL_P(stack); if (Z_ARRVAL_P(stack) == &EG(symbol_table)) { zend_reset_all_cv(&EG(symbol_table) TSRMLS_CC); } *Z_ARRVAL_P(stack) = *new_hash; FREE_HASHTABLE(new_hash); zend_hash_destroy(&old_hash); /* Clean up and return the number of elements in the stack */ efree(args); RETVAL_LONG(zend_hash_num_elements(Z_ARRVAL_P(stack))); } /* }}} */ /* {{{ proto array array_splice(array input, int offset [, int length [, array replacement]]) Removes the elements designated by offset and length and replace them with supplied array */ PHP_FUNCTION(array_splice) { zval *array, /* Input array */ *repl_array = NULL, /* Replacement array */ ***repl = NULL; /* Replacement elements */ HashTable *new_hash = NULL, /* Output array's hash */ **rem_hash = NULL; /* Removed elements' hash */ HashTable old_hash; Bucket *p; /* Bucket used for traversing hash */ long i, offset, length = 0, repl_num = 0; /* Number of replacement elements */ int num_in; /* Number of elements in the input array */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "al|lz/", &array, &offset, &length, &repl_array) == FAILURE) { return; } num_in = zend_hash_num_elements(Z_ARRVAL_P(array)); if (ZEND_NUM_ARGS() < 3) { length = num_in; } if (ZEND_NUM_ARGS() == 4) { /* Make sure the last argument, if passed, is an array */ convert_to_array(repl_array); /* Create the array of replacement elements */ repl_num = zend_hash_num_elements(Z_ARRVAL_P(repl_array)); repl = (zval ***)safe_emalloc(repl_num, sizeof(zval **), 0); for (p = Z_ARRVAL_P(repl_array)->pListHead, i = 0; p; p = p->pListNext, i++) { repl[i] = ((zval **)p->pData); } } /* Don't create the array of removed elements if it's not going * to be used; e.g. only removing and/or replacing elements */ if (return_value_used) { int size = length; /* Clamp the offset.. */ if (offset > num_in) { offset = num_in; } else if (offset < 0 && (offset = (num_in + offset)) < 0) { offset = 0; } /* ..and the length */ if (length < 0) { size = num_in - offset + length; } else if (((unsigned long) offset + (unsigned long) length) > (unsigned) num_in) { size = num_in - offset; } /* Initialize return value */ array_init_size(return_value, size > 0 ? size : 0); rem_hash = &Z_ARRVAL_P(return_value); } /* Perform splice */ new_hash = php_splice(Z_ARRVAL_P(array), offset, length, repl, repl_num, rem_hash); /* Replace input array's hashtable with the new one */ old_hash = *Z_ARRVAL_P(array); if (Z_ARRVAL_P(array) == &EG(symbol_table)) { zend_reset_all_cv(&EG(symbol_table) TSRMLS_CC); } *Z_ARRVAL_P(array) = *new_hash; FREE_HASHTABLE(new_hash); zend_hash_destroy(&old_hash); /* Clean up */ if (ZEND_NUM_ARGS() == 4) { efree(repl); } } /* }}} */ /* {{{ proto array array_slice(array input, int offset [, int length [, bool preserve_keys]]) Returns elements specified by offset and length */ PHP_FUNCTION(array_slice) { zval *input, /* Input array */ **z_length = NULL, /* How many elements to get */ **entry; /* An array entry */ long offset, /* Offset to get elements from */ length = 0; zend_bool preserve_keys = 0; /* Whether to preserve keys while copying to the new array or not */ int num_in, /* Number of elements in the input array */ pos; /* Current position in the array */ char *string_key; uint string_key_len; ulong num_key; HashPosition hpos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "al|Zb", &input, &offset, &z_length, &preserve_keys) == FAILURE) { return; } /* Get number of entries in the input hash */ num_in = zend_hash_num_elements(Z_ARRVAL_P(input)); /* We want all entries from offset to the end if length is not passed or is null */ if (ZEND_NUM_ARGS() < 3 || Z_TYPE_PP(z_length) == IS_NULL) { length = num_in; } else { convert_to_long_ex(z_length); length = Z_LVAL_PP(z_length); } /* Clamp the offset.. */ if (offset > num_in) { array_init(return_value); return; } else if (offset < 0 && (offset = (num_in + offset)) < 0) { offset = 0; } /* ..and the length */ if (length < 0) { length = num_in - offset + length; } else if (((unsigned long) offset + (unsigned long) length) > (unsigned) num_in) { length = num_in - offset; } /* Initialize returned array */ array_init_size(return_value, length > 0 ? length : 0); if (length <= 0) { return; } /* Start at the beginning and go until we hit offset */ pos = 0; zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &hpos); while (pos < offset && zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &hpos) == SUCCESS) { pos++; zend_hash_move_forward_ex(Z_ARRVAL_P(input), &hpos); } /* Copy elements from input array to the one that's returned */ while (pos < offset + length && zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &hpos) == SUCCESS) { zval_add_ref(entry); switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(input), &string_key, &string_key_len, &num_key, 0, &hpos)) { case HASH_KEY_IS_STRING: zend_hash_update(Z_ARRVAL_P(return_value), string_key, string_key_len, entry, sizeof(zval *), NULL); break; case HASH_KEY_IS_LONG: if (preserve_keys) { zend_hash_index_update(Z_ARRVAL_P(return_value), num_key, entry, sizeof(zval *), NULL); } else { zend_hash_next_index_insert(Z_ARRVAL_P(return_value), entry, sizeof(zval *), NULL); } break; } pos++; zend_hash_move_forward_ex(Z_ARRVAL_P(input), &hpos); } } /* }}} */ PHPAPI int php_array_merge(HashTable *dest, HashTable *src, int recursive TSRMLS_DC) /* {{{ */ { zval **src_entry, **dest_entry; char *string_key; uint string_key_len; ulong num_key; HashPosition pos; zend_hash_internal_pointer_reset_ex(src, &pos); while (zend_hash_get_current_data_ex(src, (void **)&src_entry, &pos) == SUCCESS) { switch (zend_hash_get_current_key_ex(src, &string_key, &string_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_STRING: if (recursive && zend_hash_find(dest, string_key, string_key_len, (void **)&dest_entry) == SUCCESS) { HashTable *thash = Z_TYPE_PP(dest_entry) == IS_ARRAY ? Z_ARRVAL_PP(dest_entry) : NULL; if ((thash && thash->nApplyCount > 1) || (*src_entry == *dest_entry && Z_ISREF_PP(dest_entry) && (Z_REFCOUNT_PP(dest_entry) % 2))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); return 0; } SEPARATE_ZVAL(dest_entry); SEPARATE_ZVAL(src_entry); if (Z_TYPE_PP(dest_entry) == IS_NULL) { convert_to_array_ex(dest_entry); add_next_index_null(*dest_entry); } else { convert_to_array_ex(dest_entry); } if (Z_TYPE_PP(src_entry) == IS_NULL) { convert_to_array_ex(src_entry); add_next_index_null(*src_entry); } else { convert_to_array_ex(src_entry); } if (thash) { thash->nApplyCount++; } if (!php_array_merge(Z_ARRVAL_PP(dest_entry), Z_ARRVAL_PP(src_entry), recursive TSRMLS_CC)) { if (thash) { thash->nApplyCount--; } return 0; } if (thash) { thash->nApplyCount--; } } else { Z_ADDREF_PP(src_entry); zend_hash_update(dest, string_key, string_key_len, src_entry, sizeof(zval *), NULL); } break; case HASH_KEY_IS_LONG: Z_ADDREF_PP(src_entry); zend_hash_next_index_insert(dest, src_entry, sizeof(zval *), NULL); break; } zend_hash_move_forward_ex(src, &pos); } return 1; } /* }}} */ PHPAPI int php_array_replace_recursive(HashTable *dest, HashTable *src TSRMLS_DC) /* {{{ */ { zval **src_entry, **dest_entry; char *string_key; uint string_key_len; ulong num_key; HashPosition pos; for (zend_hash_internal_pointer_reset_ex(src, &pos); zend_hash_get_current_data_ex(src, (void **)&src_entry, &pos) == SUCCESS; zend_hash_move_forward_ex(src, &pos)) { switch (zend_hash_get_current_key_ex(src, &string_key, &string_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_STRING: if (Z_TYPE_PP(src_entry) != IS_ARRAY || zend_hash_find(dest, string_key, string_key_len, (void **)&dest_entry) == FAILURE || Z_TYPE_PP(dest_entry) != IS_ARRAY) { Z_ADDREF_PP(src_entry); zend_hash_update(dest, string_key, string_key_len, src_entry, sizeof(zval *), NULL); continue; } break; case HASH_KEY_IS_LONG: if (Z_TYPE_PP(src_entry) != IS_ARRAY || zend_hash_index_find(dest, num_key, (void **)&dest_entry) == FAILURE || Z_TYPE_PP(dest_entry) != IS_ARRAY) { Z_ADDREF_PP(src_entry); zend_hash_index_update(dest, num_key, src_entry, sizeof(zval *), NULL); continue; } break; } if (Z_ARRVAL_PP(dest_entry)->nApplyCount > 1 || Z_ARRVAL_PP(src_entry)->nApplyCount > 1 || (*src_entry == *dest_entry && Z_ISREF_PP(dest_entry) && (Z_REFCOUNT_PP(dest_entry) % 2))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); return 0; } SEPARATE_ZVAL(dest_entry); Z_ARRVAL_PP(dest_entry)->nApplyCount++; Z_ARRVAL_PP(src_entry)->nApplyCount++; if (!php_array_replace_recursive(Z_ARRVAL_PP(dest_entry), Z_ARRVAL_PP(src_entry) TSRMLS_CC)) { Z_ARRVAL_PP(dest_entry)->nApplyCount--; Z_ARRVAL_PP(src_entry)->nApplyCount--; return 0; } Z_ARRVAL_PP(dest_entry)->nApplyCount--; Z_ARRVAL_PP(src_entry)->nApplyCount--; } return 1; } /* }}} */ static void php_array_merge_or_replace_wrapper(INTERNAL_FUNCTION_PARAMETERS, int recursive, int replace) /* {{{ */ { zval ***args = NULL; int argc, i, init_size = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &argc) == FAILURE) { return; } for (i = 0; i < argc; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is not an array", i + 1); efree(args); RETURN_NULL(); } else { int num = zend_hash_num_elements(Z_ARRVAL_PP(args[i])); if (num > init_size) { init_size = num; } } } array_init_size(return_value, init_size); for (i = 0; i < argc; i++) { SEPARATE_ZVAL(args[i]); if (!replace) { php_array_merge(Z_ARRVAL_P(return_value), Z_ARRVAL_PP(args[i]), recursive TSRMLS_CC); } else if (recursive && i > 0) { /* First array will be copied directly instead */ php_array_replace_recursive(Z_ARRVAL_P(return_value), Z_ARRVAL_PP(args[i]) TSRMLS_CC); } else { zend_hash_merge(Z_ARRVAL_P(return_value), Z_ARRVAL_PP(args[i]), (copy_ctor_func_t) zval_add_ref, NULL, sizeof(zval *), 1); } } efree(args); } /* }}} */ /* {{{ proto array array_merge(array arr1, array arr2 [, array ...]) Merges elements from passed arrays into one array */ PHP_FUNCTION(array_merge) { php_array_merge_or_replace_wrapper(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0, 0); } /* }}} */ /* {{{ proto array array_merge_recursive(array arr1, array arr2 [, array ...]) Recursively merges elements from passed arrays into one array */ PHP_FUNCTION(array_merge_recursive) { php_array_merge_or_replace_wrapper(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1, 0); } /* }}} */ /* {{{ proto array array_replace(array arr1, array arr2 [, array ...]) Replaces elements from passed arrays into one array */ PHP_FUNCTION(array_replace) { php_array_merge_or_replace_wrapper(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0, 1); } /* }}} */ /* {{{ proto array array_replace_recursive(array arr1, array arr2 [, array ...]) Recursively replaces elements from passed arrays into one array */ PHP_FUNCTION(array_replace_recursive) { php_array_merge_or_replace_wrapper(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1, 1); } /* }}} */ /* {{{ proto array array_keys(array input [, mixed search_value[, bool strict]]) Return just the keys from the input array, optionally only for the specified search_value */ PHP_FUNCTION(array_keys) { zval *input, /* Input array */ *search_value = NULL, /* Value to search for */ **entry, /* An entry in the input array */ res, /* Result of comparison */ *new_val; /* New value */ int add_key; /* Flag to indicate whether a key should be added */ char *string_key; /* String key */ uint string_key_len; ulong num_key; /* Numeric key */ zend_bool strict = 0; /* do strict comparison */ HashPosition pos; int (*is_equal_func)(zval *, zval *, zval * TSRMLS_DC) = is_equal_function; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|zb", &input, &search_value, &strict) == FAILURE) { return; } if (strict) { is_equal_func = is_identical_function; } /* Initialize return array */ if (search_value != NULL) { array_init(return_value); } else { array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(input))); } add_key = 1; /* Go through input array and add keys to the return array */ zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &pos) == SUCCESS) { if (search_value != NULL) { is_equal_func(&res, search_value, *entry TSRMLS_CC); add_key = zval_is_true(&res); } if (add_key) { MAKE_STD_ZVAL(new_val); switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(input), &string_key, &string_key_len, &num_key, 1, &pos)) { case HASH_KEY_IS_STRING: ZVAL_STRINGL(new_val, string_key, string_key_len - 1, 0); zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &new_val, sizeof(zval *), NULL); break; case HASH_KEY_IS_LONG: Z_TYPE_P(new_val) = IS_LONG; Z_LVAL_P(new_val) = num_key; zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &new_val, sizeof(zval *), NULL); break; } } zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos); } } /* }}} */ /* {{{ proto array array_values(array input) Return just the values from the input array */ PHP_FUNCTION(array_values) { zval *input, /* Input array */ **entry; /* An entry in the input array */ HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &input) == FAILURE) { return; } /* Initialize return array */ array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(input))); /* Go through input array and add values to the return array */ zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &pos) == SUCCESS) { zval_add_ref(entry); zend_hash_next_index_insert(Z_ARRVAL_P(return_value), entry, sizeof(zval *), NULL); zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos); } } /* }}} */ /* {{{ proto array array_count_values(array input) Return the value as key and the frequency of that value in input as value */ PHP_FUNCTION(array_count_values) { zval *input, /* Input array */ **entry, /* An entry in the input array */ **tmp; HashTable *myht; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &input) == FAILURE) { return; } /* Initialize return array */ array_init(return_value); /* Go through input array and add values to the return array */ myht = Z_ARRVAL_P(input); zend_hash_internal_pointer_reset_ex(myht, &pos); while (zend_hash_get_current_data_ex(myht, (void **)&entry, &pos) == SUCCESS) { if (Z_TYPE_PP(entry) == IS_LONG) { if (zend_hash_index_find(Z_ARRVAL_P(return_value), Z_LVAL_PP(entry), (void **)&tmp) == FAILURE) { zval *data; MAKE_STD_ZVAL(data); ZVAL_LONG(data, 1); zend_hash_index_update(Z_ARRVAL_P(return_value), Z_LVAL_PP(entry), &data, sizeof(data), NULL); } else { Z_LVAL_PP(tmp)++; } } else if (Z_TYPE_PP(entry) == IS_STRING) { if (zend_symtable_find(Z_ARRVAL_P(return_value), Z_STRVAL_PP(entry), Z_STRLEN_PP(entry) + 1, (void**)&tmp) == FAILURE) { zval *data; MAKE_STD_ZVAL(data); ZVAL_LONG(data, 1); zend_symtable_update(Z_ARRVAL_P(return_value), Z_STRVAL_PP(entry), Z_STRLEN_PP(entry) + 1, &data, sizeof(data), NULL); } else { Z_LVAL_PP(tmp)++; } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can only count STRING and INTEGER values!"); } zend_hash_move_forward_ex(myht, &pos); } } /* }}} */ /* {{{ proto array array_reverse(array input [, bool preserve keys]) Return input as a new array with the order of the entries reversed */ PHP_FUNCTION(array_reverse) { zval *input, /* Input array */ **entry; /* An entry in the input array */ char *string_key; uint string_key_len; ulong num_key; zend_bool preserve_keys = 0; /* whether to preserve keys */ HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|b", &input, &preserve_keys) == FAILURE) { return; } /* Initialize return array */ array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(input))); zend_hash_internal_pointer_end_ex(Z_ARRVAL_P(input), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &pos) == SUCCESS) { zval_add_ref(entry); switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(input), &string_key, &string_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_STRING: zend_hash_update(Z_ARRVAL_P(return_value), string_key, string_key_len, entry, sizeof(zval *), NULL); break; case HASH_KEY_IS_LONG: if (preserve_keys) { zend_hash_index_update(Z_ARRVAL_P(return_value), num_key, entry, sizeof(zval *), NULL); } else { zend_hash_next_index_insert(Z_ARRVAL_P(return_value), entry, sizeof(zval *), NULL); } break; } zend_hash_move_backwards_ex(Z_ARRVAL_P(input), &pos); } } /* }}} */ /* {{{ proto array array_pad(array input, int pad_size, mixed pad_value) Returns a copy of input array padded with pad_value to size pad_size */ PHP_FUNCTION(array_pad) { zval *input; /* Input array */ zval *pad_value; /* Padding value obviously */ zval ***pads; /* Array to pass to splice */ HashTable *new_hash;/* Return value from splice */ HashTable old_hash; long pad_size; /* Size to pad to */ long pad_size_abs; /* Absolute value of pad_size */ int input_size; /* Size of the input array */ int num_pads; /* How many pads do we need */ int do_pad; /* Whether we should do padding at all */ int i; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "alz", &input, &pad_size, &pad_value) == FAILURE) { return; } /* Do some initial calculations */ input_size = zend_hash_num_elements(Z_ARRVAL_P(input)); pad_size_abs = abs(pad_size); if (pad_size_abs < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You may only pad up to 1048576 elements at a time"); zval_dtor(return_value); RETURN_FALSE; } do_pad = (input_size >= pad_size_abs) ? 0 : 1; /* Copy the original array */ RETVAL_ZVAL(input, 1, 0); /* If no need to pad, no need to continue */ if (!do_pad) { return; } /* Populate the pads array */ num_pads = pad_size_abs - input_size; if (num_pads > 1048576) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You may only pad up to 1048576 elements at a time"); zval_dtor(return_value); RETURN_FALSE; } pads = (zval ***)safe_emalloc(num_pads, sizeof(zval **), 0); for (i = 0; i < num_pads; i++) { pads[i] = &pad_value; } /* Pad on the right or on the left */ if (pad_size > 0) { new_hash = php_splice(Z_ARRVAL_P(return_value), input_size, 0, pads, num_pads, NULL); } else { new_hash = php_splice(Z_ARRVAL_P(return_value), 0, 0, pads, num_pads, NULL); } /* Copy the result hash into return value */ old_hash = *Z_ARRVAL_P(return_value); if (Z_ARRVAL_P(return_value) == &EG(symbol_table)) { zend_reset_all_cv(&EG(symbol_table) TSRMLS_CC); } *Z_ARRVAL_P(return_value) = *new_hash; FREE_HASHTABLE(new_hash); zend_hash_destroy(&old_hash); /* Clean up */ efree(pads); } /* }}} */ /* {{{ proto array array_flip(array input) Return array with key <-> value flipped */ PHP_FUNCTION(array_flip) { zval *array, **entry, *data; char *string_key; uint str_key_len; ulong num_key; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) { return; } array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(array))); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(array), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(array), (void **)&entry, &pos) == SUCCESS) { MAKE_STD_ZVAL(data); switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(array), &string_key, &str_key_len, &num_key, 1, &pos)) { case HASH_KEY_IS_STRING: ZVAL_STRINGL(data, string_key, str_key_len - 1, 0); break; case HASH_KEY_IS_LONG: Z_TYPE_P(data) = IS_LONG; Z_LVAL_P(data) = num_key; break; } if (Z_TYPE_PP(entry) == IS_LONG) { zend_hash_index_update(Z_ARRVAL_P(return_value), Z_LVAL_PP(entry), &data, sizeof(data), NULL); } else if (Z_TYPE_PP(entry) == IS_STRING) { zend_symtable_update(Z_ARRVAL_P(return_value), Z_STRVAL_PP(entry), Z_STRLEN_PP(entry) + 1, &data, sizeof(data), NULL); } else { zval_ptr_dtor(&data); /* will free also zval structure */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can only flip STRING and INTEGER values!"); } zend_hash_move_forward_ex(Z_ARRVAL_P(array), &pos); } } /* }}} */ /* {{{ proto array array_change_key_case(array input [, int case=CASE_LOWER]) Retuns an array with all string keys lowercased [or uppercased] */ PHP_FUNCTION(array_change_key_case) { zval *array, **entry; char *string_key; char *new_key; uint str_key_len; ulong num_key; long change_to_upper=0; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &change_to_upper) == FAILURE) { return; } array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(array))); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(array), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(array), (void **)&entry, &pos) == SUCCESS) { zval_add_ref(entry); switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(array), &string_key, &str_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_LONG: zend_hash_index_update(Z_ARRVAL_P(return_value), num_key, entry, sizeof(entry), NULL); break; case HASH_KEY_IS_STRING: new_key = estrndup(string_key, str_key_len - 1); if (change_to_upper) { php_strtoupper(new_key, str_key_len - 1); } else { php_strtolower(new_key, str_key_len - 1); } zend_hash_update(Z_ARRVAL_P(return_value), new_key, str_key_len, entry, sizeof(entry), NULL); efree(new_key); break; } zend_hash_move_forward_ex(Z_ARRVAL_P(array), &pos); } } /* }}} */ /* {{{ proto array array_unique(array input [, int sort_flags]) Removes duplicate values from array */ PHP_FUNCTION(array_unique) { zval *array, *tmp; Bucket *p; struct bucketindex { Bucket *b; unsigned int i; }; struct bucketindex *arTmp, *cmpdata, *lastkept; unsigned int i; long sort_type = PHP_SORT_STRING; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { return; } php_set_compare_func(sort_type TSRMLS_CC); array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(array))); zend_hash_copy(Z_ARRVAL_P(return_value), Z_ARRVAL_P(array), (copy_ctor_func_t) zval_add_ref, (void *)&tmp, sizeof(zval*)); if (Z_ARRVAL_P(array)->nNumOfElements <= 1) { /* nothing to do */ return; } /* create and sort array with pointers to the target_hash buckets */ arTmp = (struct bucketindex *) pemalloc((Z_ARRVAL_P(array)->nNumOfElements + 1) * sizeof(struct bucketindex), Z_ARRVAL_P(array)->persistent); if (!arTmp) { zval_dtor(return_value); RETURN_FALSE; } for (i = 0, p = Z_ARRVAL_P(array)->pListHead; p; i++, p = p->pListNext) { arTmp[i].b = p; arTmp[i].i = i; } arTmp[i].b = NULL; zend_qsort((void *) arTmp, i, sizeof(struct bucketindex), php_array_data_compare TSRMLS_CC); /* go through the sorted array and delete duplicates from the copy */ lastkept = arTmp; for (cmpdata = arTmp + 1; cmpdata->b; cmpdata++) { if (php_array_data_compare(lastkept, cmpdata TSRMLS_CC)) { lastkept = cmpdata; } else { if (lastkept->i > cmpdata->i) { p = lastkept->b; lastkept = cmpdata; } else { p = cmpdata->b; } if (p->nKeyLength == 0) { zend_hash_index_del(Z_ARRVAL_P(return_value), p->h); } else { if (Z_ARRVAL_P(return_value) == &EG(symbol_table)) { zend_delete_global_variable(p->arKey, p->nKeyLength - 1 TSRMLS_CC); } else { zend_hash_quick_del(Z_ARRVAL_P(return_value), p->arKey, p->nKeyLength, p->h); } } } } pefree(arTmp, Z_ARRVAL_P(array)->persistent); } /* }}} */ static int zval_compare(zval **a, zval **b TSRMLS_DC) /* {{{ */ { zval result; zval *first; zval *second; first = *((zval **) a); second = *((zval **) b); if (string_compare_function(&result, first, second TSRMLS_CC) == FAILURE) { return 0; } if (Z_TYPE(result) == IS_DOUBLE) { if (Z_DVAL(result) < 0) { return -1; } else if (Z_DVAL(result) > 0) { return 1; } else { return 0; } } convert_to_long(&result); if (Z_LVAL(result) < 0) { return -1; } else if (Z_LVAL(result) > 0) { return 1; } return 0; } /* }}} */ static int zval_user_compare(zval **a, zval **b TSRMLS_DC) /* {{{ */ { zval **args[2]; zval *retval_ptr; args[0] = (zval **) a; args[1] = (zval **) b; BG(user_compare_fci).param_count = 2; BG(user_compare_fci).params = args; BG(user_compare_fci).retval_ptr_ptr = &retval_ptr; BG(user_compare_fci).no_separation = 0; if (zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache) TSRMLS_CC) == SUCCESS && retval_ptr) { long retval; convert_to_long_ex(&retval_ptr); retval = Z_LVAL_P(retval_ptr); zval_ptr_dtor(&retval_ptr); return retval < 0 ? -1 : retval > 0 ? 1 : 0;; } else { return 0; } } /* }}} */ static void php_array_intersect_key(INTERNAL_FUNCTION_PARAMETERS, int data_compare_type) /* {{{ */ { Bucket *p; int argc, i; zval ***args; int (*intersect_data_compare_func)(zval **, zval ** TSRMLS_DC) = NULL; zend_bool ok; zval **data; int req_args; char *param_spec; /* Get the argument count */ argc = ZEND_NUM_ARGS(); if (data_compare_type == INTERSECT_COMP_DATA_USER) { /* INTERSECT_COMP_DATA_USER - array_uintersect_assoc() */ req_args = 3; param_spec = "+f"; intersect_data_compare_func = zval_user_compare; } else { /* INTERSECT_COMP_DATA_NONE - array_intersect_key() INTERSECT_COMP_DATA_INTERNAL - array_intersect_assoc() */ req_args = 2; param_spec = "+"; if (data_compare_type == INTERSECT_COMP_DATA_INTERNAL) { intersect_data_compare_func = zval_compare; } } if (argc < req_args) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least %d parameters are required, %d given", req_args, argc); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, param_spec, &args, &argc, &BG(user_compare_fci), &BG(user_compare_fci_cache)) == FAILURE) { return; } for (i = 0; i < argc; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is not an array", i + 1); RETVAL_NULL(); goto out; } } array_init(return_value); for (p = Z_ARRVAL_PP(args[0])->pListHead; p != NULL; p = p->pListNext) { if (p->nKeyLength == 0) { ok = 1; for (i = 1; i < argc; i++) { if (zend_hash_index_find(Z_ARRVAL_PP(args[i]), p->h, (void**)&data) == FAILURE || (intersect_data_compare_func && intersect_data_compare_func((zval**)p->pData, data TSRMLS_CC) != 0) ) { ok = 0; break; } } if (ok) { Z_ADDREF_PP((zval**)p->pData); zend_hash_index_update(Z_ARRVAL_P(return_value), p->h, p->pData, sizeof(zval*), NULL); } } else { ok = 1; for (i = 1; i < argc; i++) { if (zend_hash_quick_find(Z_ARRVAL_PP(args[i]), p->arKey, p->nKeyLength, p->h, (void**)&data) == FAILURE || (intersect_data_compare_func && intersect_data_compare_func((zval**)p->pData, data TSRMLS_CC) != 0) ) { ok = 0; break; } } if (ok) { Z_ADDREF_PP((zval**)p->pData); zend_hash_quick_update(Z_ARRVAL_P(return_value), p->arKey, p->nKeyLength, p->h, p->pData, sizeof(zval*), NULL); } } } out: efree(args); } /* }}} */ static void php_array_intersect(INTERNAL_FUNCTION_PARAMETERS, int behavior, int data_compare_type, int key_compare_type) /* {{{ */ { zval ***args = NULL; HashTable *hash; int arr_argc, i, c = 0; Bucket ***lists, **list, ***ptrs, *p; int req_args; char *param_spec; zend_fcall_info fci1, fci2; zend_fcall_info_cache fci1_cache = empty_fcall_info_cache, fci2_cache = empty_fcall_info_cache; zend_fcall_info *fci_key, *fci_data; zend_fcall_info_cache *fci_key_cache, *fci_data_cache; PHP_ARRAY_CMP_FUNC_VARS; int (*intersect_key_compare_func)(const void *, const void * TSRMLS_DC); int (*intersect_data_compare_func)(const void *, const void * TSRMLS_DC); if (behavior == INTERSECT_NORMAL) { intersect_key_compare_func = php_array_key_compare; if (data_compare_type == INTERSECT_COMP_DATA_INTERNAL) { /* array_intersect() */ req_args = 2; param_spec = "+"; intersect_data_compare_func = php_array_data_compare; } else if (data_compare_type == INTERSECT_COMP_DATA_USER) { /* array_uintersect() */ req_args = 3; param_spec = "+f"; intersect_data_compare_func = php_array_user_compare; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "data_compare_type is %d. This should never happen. Please report as a bug", data_compare_type); return; } if (ZEND_NUM_ARGS() < req_args) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least %d parameters are required, %d given", req_args, ZEND_NUM_ARGS()); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, param_spec, &args, &arr_argc, &fci1, &fci1_cache) == FAILURE) { return; } fci_data = &fci1; fci_data_cache = &fci1_cache; } else if (behavior & INTERSECT_ASSOC) { /* triggered also when INTERSECT_KEY */ /* INTERSECT_KEY is subset of INTERSECT_ASSOC. When having the former * no comparison of the data is done (part of INTERSECT_ASSOC) */ intersect_key_compare_func = php_array_key_compare; if (data_compare_type == INTERSECT_COMP_DATA_INTERNAL && key_compare_type == INTERSECT_COMP_KEY_INTERNAL) { /* array_intersect_assoc() or array_intersect_key() */ req_args = 2; param_spec = "+"; intersect_key_compare_func = php_array_key_compare; intersect_data_compare_func = php_array_data_compare; } else if (data_compare_type == INTERSECT_COMP_DATA_USER && key_compare_type == INTERSECT_COMP_KEY_INTERNAL) { /* array_uintersect_assoc() */ req_args = 3; param_spec = "+f"; intersect_key_compare_func = php_array_key_compare; intersect_data_compare_func = php_array_user_compare; fci_data = &fci1; fci_data_cache = &fci1_cache; } else if (data_compare_type == INTERSECT_COMP_DATA_INTERNAL && key_compare_type == INTERSECT_COMP_KEY_USER) { /* array_intersect_uassoc() or array_intersect_ukey() */ req_args = 3; param_spec = "+f"; intersect_key_compare_func = php_array_user_key_compare; intersect_data_compare_func = php_array_data_compare; fci_key = &fci1; fci_key_cache = &fci1_cache; } else if (data_compare_type == INTERSECT_COMP_DATA_USER && key_compare_type == INTERSECT_COMP_KEY_USER) { /* array_uintersect_uassoc() */ req_args = 4; param_spec = "+ff"; intersect_key_compare_func = php_array_user_key_compare; intersect_data_compare_func = php_array_user_compare; fci_data = &fci1; fci_data_cache = &fci1_cache; fci_key = &fci2; fci_key_cache = &fci2_cache; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "data_compare_type is %d. key_compare_type is %d. This should never happen. Please report as a bug", data_compare_type, key_compare_type); return; } if (ZEND_NUM_ARGS() < req_args) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least %d parameters are required, %d given", req_args, ZEND_NUM_ARGS()); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, param_spec, &args, &arr_argc, &fci1, &fci1_cache, &fci2, &fci2_cache) == FAILURE) { return; } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "behavior is %d. This should never happen. Please report as a bug", behavior); return; } PHP_ARRAY_CMP_FUNC_BACKUP(); /* for each argument, create and sort list with pointers to the hash buckets */ lists = (Bucket ***)safe_emalloc(arr_argc, sizeof(Bucket **), 0); ptrs = (Bucket ***)safe_emalloc(arr_argc, sizeof(Bucket **), 0); php_set_compare_func(PHP_SORT_STRING TSRMLS_CC); if (behavior == INTERSECT_NORMAL && data_compare_type == INTERSECT_COMP_DATA_USER) { BG(user_compare_fci) = *fci_data; BG(user_compare_fci_cache) = *fci_data_cache; } else if (behavior & INTERSECT_ASSOC && key_compare_type == INTERSECT_COMP_KEY_USER) { BG(user_compare_fci) = *fci_key; BG(user_compare_fci_cache) = *fci_key_cache; } for (i = 0; i < arr_argc; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is not an array", i + 1); arr_argc = i; /* only free up to i - 1 */ goto out; } hash = Z_ARRVAL_PP(args[i]); list = (Bucket **) pemalloc((hash->nNumOfElements + 1) * sizeof(Bucket *), hash->persistent); if (!list) { PHP_ARRAY_CMP_FUNC_RESTORE(); efree(ptrs); efree(lists); efree(args); RETURN_FALSE; } lists[i] = list; ptrs[i] = list; for (p = hash->pListHead; p; p = p->pListNext) { *list++ = p; } *list = NULL; if (behavior == INTERSECT_NORMAL) { zend_qsort((void *) lists[i], hash->nNumOfElements, sizeof(Bucket *), intersect_data_compare_func TSRMLS_CC); } else if (behavior & INTERSECT_ASSOC) { /* triggered also when INTERSECT_KEY */ zend_qsort((void *) lists[i], hash->nNumOfElements, sizeof(Bucket *), intersect_key_compare_func TSRMLS_CC); } } /* copy the argument array */ RETVAL_ZVAL(*args[0], 1, 0); if (return_value->value.ht == &EG(symbol_table)) { HashTable *ht; zval *tmp; ALLOC_HASHTABLE(ht); zend_hash_init(ht, zend_hash_num_elements(return_value->value.ht), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(ht, return_value->value.ht, (copy_ctor_func_t) zval_add_ref, (void *) &tmp, sizeof(zval *)); return_value->value.ht = ht; } /* go through the lists and look for common values */ while (*ptrs[0]) { if ((behavior & INTERSECT_ASSOC) /* triggered also when INTERSECT_KEY */ && key_compare_type == INTERSECT_COMP_KEY_USER) { BG(user_compare_fci) = *fci_key; BG(user_compare_fci_cache) = *fci_key_cache; } for (i = 1; i < arr_argc; i++) { if (behavior & INTERSECT_NORMAL) { while (*ptrs[i] && (0 < (c = intersect_data_compare_func(ptrs[0], ptrs[i] TSRMLS_CC)))) { ptrs[i]++; } } else if (behavior & INTERSECT_ASSOC) { /* triggered also when INTERSECT_KEY */ while (*ptrs[i] && (0 < (c = intersect_key_compare_func(ptrs[0], ptrs[i] TSRMLS_CC)))) { ptrs[i]++; } if ((!c && *ptrs[i]) && (behavior == INTERSECT_ASSOC)) { /* only when INTERSECT_ASSOC */ /* this means that ptrs[i] is not NULL so we can compare * and "c==0" is from last operation * in this branch of code we enter only when INTERSECT_ASSOC * since when we have INTERSECT_KEY compare of data is not wanted. */ if (data_compare_type == INTERSECT_COMP_DATA_USER) { BG(user_compare_fci) = *fci_data; BG(user_compare_fci_cache) = *fci_data_cache; } if (intersect_data_compare_func(ptrs[0], ptrs[i] TSRMLS_CC) != 0) { c = 1; if (key_compare_type == INTERSECT_COMP_KEY_USER) { BG(user_compare_fci) = *fci_key; BG(user_compare_fci_cache) = *fci_key_cache; /* When KEY_USER, the last parameter is always the callback */ } /* we are going to the break */ } else { /* continue looping */ } } } if (!*ptrs[i]) { /* delete any values corresponding to remains of ptrs[0] */ /* and exit because they do not present in at least one of */ /* the other arguments */ for (;;) { p = *ptrs[0]++; if (!p) { goto out; } if (p->nKeyLength == 0) { zend_hash_index_del(Z_ARRVAL_P(return_value), p->h); } else { zend_hash_quick_del(Z_ARRVAL_P(return_value), p->arKey, p->nKeyLength, p->h); } } } if (c) /* here we get if not all are equal */ break; ptrs[i]++; } if (c) { /* Value of ptrs[0] not in all arguments, delete all entries */ /* with value < value of ptrs[i] */ for (;;) { p = *ptrs[0]; if (p->nKeyLength == 0) { zend_hash_index_del(Z_ARRVAL_P(return_value), p->h); } else { zend_hash_quick_del(Z_ARRVAL_P(return_value), p->arKey, p->nKeyLength, p->h); } if (!*++ptrs[0]) { goto out; } if (behavior == INTERSECT_NORMAL) { if (0 <= intersect_data_compare_func(ptrs[0], ptrs[i] TSRMLS_CC)) { break; } } else if (behavior & INTERSECT_ASSOC) { /* triggered also when INTERSECT_KEY */ /* no need of looping because indexes are unique */ break; } } } else { /* ptrs[0] is present in all the arguments */ /* Skip all entries with same value as ptrs[0] */ for (;;) { if (!*++ptrs[0]) { goto out; } if (behavior == INTERSECT_NORMAL) { if (intersect_data_compare_func(ptrs[0] - 1, ptrs[0] TSRMLS_CC)) { break; } } else if (behavior & INTERSECT_ASSOC) { /* triggered also when INTERSECT_KEY */ /* no need of looping because indexes are unique */ break; } } } } out: for (i = 0; i < arr_argc; i++) { hash = Z_ARRVAL_PP(args[i]); pefree(lists[i], hash->persistent); } PHP_ARRAY_CMP_FUNC_RESTORE(); efree(ptrs); efree(lists); efree(args); } /* }}} */ /* {{{ proto array array_intersect_key(array arr1, array arr2 [, array ...]) Returns the entries of arr1 that have keys which are present in all the other arguments. Kind of equivalent to array_diff(array_keys($arr1), array_keys($arr2)[,array_keys(...)]). Equivalent of array_intersect_assoc() but does not do compare of the data. */ PHP_FUNCTION(array_intersect_key) { php_array_intersect_key(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_COMP_DATA_NONE); } /* }}} */ /* {{{ proto array array_intersect_ukey(array arr1, array arr2 [, array ...], callback key_compare_func) Returns the entries of arr1 that have keys which are present in all the other arguments. Kind of equivalent to array_diff(array_keys($arr1), array_keys($arr2)[,array_keys(...)]). The comparison of the keys is performed by a user supplied function. Equivalent of array_intersect_uassoc() but does not do compare of the data. */ PHP_FUNCTION(array_intersect_ukey) { php_array_intersect(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_KEY, INTERSECT_COMP_DATA_INTERNAL, INTERSECT_COMP_KEY_USER); } /* }}} */ /* {{{ proto array array_intersect(array arr1, array arr2 [, array ...]) Returns the entries of arr1 that have values which are present in all the other arguments */ PHP_FUNCTION(array_intersect) { php_array_intersect(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_NORMAL, INTERSECT_COMP_DATA_INTERNAL, INTERSECT_COMP_KEY_INTERNAL); } /* }}} */ /* {{{ proto array array_uintersect(array arr1, array arr2 [, array ...], callback data_compare_func) Returns the entries of arr1 that have values which are present in all the other arguments. Data is compared by using an user-supplied callback. */ PHP_FUNCTION(array_uintersect) { php_array_intersect(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_NORMAL, INTERSECT_COMP_DATA_USER, INTERSECT_COMP_KEY_INTERNAL); } /* }}} */ /* {{{ proto array array_intersect_assoc(array arr1, array arr2 [, array ...]) Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check */ PHP_FUNCTION(array_intersect_assoc) { php_array_intersect_key(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_COMP_DATA_INTERNAL); } /* }}} */ /* {{{ proto array array_intersect_uassoc(array arr1, array arr2 [, array ...], callback key_compare_func) U Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check and they are compared by using an user-supplied callback. */ PHP_FUNCTION(array_intersect_uassoc) { php_array_intersect(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_ASSOC, INTERSECT_COMP_DATA_INTERNAL, INTERSECT_COMP_KEY_USER); } /* }}} */ /* {{{ proto array array_uintersect_assoc(array arr1, array arr2 [, array ...], callback data_compare_func) U Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check. Data is compared by using an user-supplied callback. */ PHP_FUNCTION(array_uintersect_assoc) { php_array_intersect_key(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_COMP_DATA_USER); } /* }}} */ /* {{{ proto array array_uintersect_uassoc(array arr1, array arr2 [, array ...], callback data_compare_func, callback key_compare_func) Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check. Both data and keys are compared by using user-supplied callbacks. */ PHP_FUNCTION(array_uintersect_uassoc) { php_array_intersect(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_ASSOC, INTERSECT_COMP_DATA_USER, INTERSECT_COMP_KEY_USER); } /* }}} */ static void php_array_diff_key(INTERNAL_FUNCTION_PARAMETERS, int data_compare_type) /* {{{ */ { Bucket *p; int argc, i; zval ***args; int (*diff_data_compare_func)(zval **, zval ** TSRMLS_DC) = NULL; zend_bool ok; zval **data; /* Get the argument count */ argc = ZEND_NUM_ARGS(); if (data_compare_type == DIFF_COMP_DATA_USER) { if (argc < 3) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least 3 parameters are required, %d given", ZEND_NUM_ARGS()); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+f", &args, &argc, &BG(user_compare_fci), &BG(user_compare_fci_cache)) == FAILURE) { return; } diff_data_compare_func = zval_user_compare; } else { if (argc < 2) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least 2 parameters are required, %d given", ZEND_NUM_ARGS()); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &argc) == FAILURE) { return; } if (data_compare_type == DIFF_COMP_DATA_INTERNAL) { diff_data_compare_func = zval_compare; } } for (i = 0; i < argc; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is not an array", i + 1); RETVAL_NULL(); goto out; } } array_init(return_value); for (p = Z_ARRVAL_PP(args[0])->pListHead; p != NULL; p = p->pListNext) { if (p->nKeyLength == 0) { ok = 1; for (i = 1; i < argc; i++) { if (zend_hash_index_find(Z_ARRVAL_PP(args[i]), p->h, (void**)&data) == SUCCESS && (!diff_data_compare_func || diff_data_compare_func((zval**)p->pData, data TSRMLS_CC) == 0) ) { ok = 0; break; } } if (ok) { Z_ADDREF_PP((zval**)p->pData); zend_hash_index_update(Z_ARRVAL_P(return_value), p->h, p->pData, sizeof(zval*), NULL); } } else { ok = 1; for (i = 1; i < argc; i++) { if (zend_hash_quick_find(Z_ARRVAL_PP(args[i]), p->arKey, p->nKeyLength, p->h, (void**)&data) == SUCCESS && (!diff_data_compare_func || diff_data_compare_func((zval**)p->pData, data TSRMLS_CC) == 0) ) { ok = 0; break; } } if (ok) { Z_ADDREF_PP((zval**)p->pData); zend_hash_quick_update(Z_ARRVAL_P(return_value), p->arKey, p->nKeyLength, p->h, p->pData, sizeof(zval*), NULL); } } } out: efree(args); } /* }}} */ static void php_array_diff(INTERNAL_FUNCTION_PARAMETERS, int behavior, int data_compare_type, int key_compare_type) /* {{{ */ { zval ***args = NULL; HashTable *hash; int arr_argc, i, c; Bucket ***lists, **list, ***ptrs, *p; int req_args; char *param_spec; zend_fcall_info fci1, fci2; zend_fcall_info_cache fci1_cache = empty_fcall_info_cache, fci2_cache = empty_fcall_info_cache; zend_fcall_info *fci_key, *fci_data; zend_fcall_info_cache *fci_key_cache, *fci_data_cache; PHP_ARRAY_CMP_FUNC_VARS; int (*diff_key_compare_func)(const void *, const void * TSRMLS_DC); int (*diff_data_compare_func)(const void *, const void * TSRMLS_DC); if (behavior == DIFF_NORMAL) { diff_key_compare_func = php_array_key_compare; if (data_compare_type == DIFF_COMP_DATA_INTERNAL) { /* array_diff */ req_args = 2; param_spec = "+"; diff_data_compare_func = php_array_data_compare; } else if (data_compare_type == DIFF_COMP_DATA_USER) { /* array_udiff */ req_args = 3; param_spec = "+f"; diff_data_compare_func = php_array_user_compare; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "data_compare_type is %d. This should never happen. Please report as a bug", data_compare_type); return; } if (ZEND_NUM_ARGS() < req_args) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least %d parameters are required, %d given", req_args, ZEND_NUM_ARGS()); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, param_spec, &args, &arr_argc, &fci1, &fci1_cache) == FAILURE) { return; } fci_data = &fci1; fci_data_cache = &fci1_cache; } else if (behavior & DIFF_ASSOC) { /* triggered also if DIFF_KEY */ /* DIFF_KEY is subset of DIFF_ASSOC. When having the former * no comparison of the data is done (part of DIFF_ASSOC) */ if (data_compare_type == DIFF_COMP_DATA_INTERNAL && key_compare_type == DIFF_COMP_KEY_INTERNAL) { /* array_diff_assoc() or array_diff_key() */ req_args = 2; param_spec = "+"; diff_key_compare_func = php_array_key_compare; diff_data_compare_func = php_array_data_compare; } else if (data_compare_type == DIFF_COMP_DATA_USER && key_compare_type == DIFF_COMP_KEY_INTERNAL) { /* array_udiff_assoc() */ req_args = 3; param_spec = "+f"; diff_key_compare_func = php_array_key_compare; diff_data_compare_func = php_array_user_compare; fci_data = &fci1; fci_data_cache = &fci1_cache; } else if (data_compare_type == DIFF_COMP_DATA_INTERNAL && key_compare_type == DIFF_COMP_KEY_USER) { /* array_diff_uassoc() or array_diff_ukey() */ req_args = 3; param_spec = "+f"; diff_key_compare_func = php_array_user_key_compare; diff_data_compare_func = php_array_data_compare; fci_key = &fci1; fci_key_cache = &fci1_cache; } else if (data_compare_type == DIFF_COMP_DATA_USER && key_compare_type == DIFF_COMP_KEY_USER) { /* array_udiff_uassoc() */ req_args = 4; param_spec = "+ff"; diff_key_compare_func = php_array_user_key_compare; diff_data_compare_func = php_array_user_compare; fci_data = &fci1; fci_data_cache = &fci1_cache; fci_key = &fci2; fci_key_cache = &fci2_cache; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "data_compare_type is %d. key_compare_type is %d. This should never happen. Please report as a bug", data_compare_type, key_compare_type); return; } if (ZEND_NUM_ARGS() < req_args) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least %d parameters are required, %d given", req_args, ZEND_NUM_ARGS()); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, param_spec, &args, &arr_argc, &fci1, &fci1_cache, &fci2, &fci2_cache) == FAILURE) { return; } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "behavior is %d. This should never happen. Please report as a bug", behavior); return; } PHP_ARRAY_CMP_FUNC_BACKUP(); /* for each argument, create and sort list with pointers to the hash buckets */ lists = (Bucket ***)safe_emalloc(arr_argc, sizeof(Bucket **), 0); ptrs = (Bucket ***)safe_emalloc(arr_argc, sizeof(Bucket **), 0); php_set_compare_func(PHP_SORT_STRING TSRMLS_CC); if (behavior == DIFF_NORMAL && data_compare_type == DIFF_COMP_DATA_USER) { BG(user_compare_fci) = *fci_data; BG(user_compare_fci_cache) = *fci_data_cache; } else if (behavior & DIFF_ASSOC && key_compare_type == DIFF_COMP_KEY_USER) { BG(user_compare_fci) = *fci_key; BG(user_compare_fci_cache) = *fci_key_cache; } for (i = 0; i < arr_argc; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is not an array", i + 1); arr_argc = i; /* only free up to i - 1 */ goto out; } hash = Z_ARRVAL_PP(args[i]); list = (Bucket **) pemalloc((hash->nNumOfElements + 1) * sizeof(Bucket *), hash->persistent); if (!list) { PHP_ARRAY_CMP_FUNC_RESTORE(); efree(ptrs); efree(lists); efree(args); RETURN_FALSE; } lists[i] = list; ptrs[i] = list; for (p = hash->pListHead; p; p = p->pListNext) { *list++ = p; } *list = NULL; if (behavior == DIFF_NORMAL) { zend_qsort((void *) lists[i], hash->nNumOfElements, sizeof(Bucket *), diff_data_compare_func TSRMLS_CC); } else if (behavior & DIFF_ASSOC) { /* triggered also when DIFF_KEY */ zend_qsort((void *) lists[i], hash->nNumOfElements, sizeof(Bucket *), diff_key_compare_func TSRMLS_CC); } } /* copy the argument array */ RETVAL_ZVAL(*args[0], 1, 0); if (return_value->value.ht == &EG(symbol_table)) { HashTable *ht; zval *tmp; ALLOC_HASHTABLE(ht); zend_hash_init(ht, zend_hash_num_elements(return_value->value.ht), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(ht, return_value->value.ht, (copy_ctor_func_t) zval_add_ref, (void *) &tmp, sizeof(zval *)); return_value->value.ht = ht; } /* go through the lists and look for values of ptr[0] that are not in the others */ while (*ptrs[0]) { if ((behavior & DIFF_ASSOC) /* triggered also when DIFF_KEY */ && key_compare_type == DIFF_COMP_KEY_USER ) { BG(user_compare_fci) = *fci_key; BG(user_compare_fci_cache) = *fci_key_cache; } c = 1; for (i = 1; i < arr_argc; i++) { Bucket **ptr = ptrs[i]; if (behavior == DIFF_NORMAL) { while (*ptrs[i] && (0 < (c = diff_data_compare_func(ptrs[0], ptrs[i] TSRMLS_CC)))) { ptrs[i]++; } } else if (behavior & DIFF_ASSOC) { /* triggered also when DIFF_KEY */ while (*ptr && (0 != (c = diff_key_compare_func(ptrs[0], ptr TSRMLS_CC)))) { ptr++; } } if (!c) { if (behavior == DIFF_NORMAL) { if (*ptrs[i]) { ptrs[i]++; } break; } else if (behavior == DIFF_ASSOC) { /* only when DIFF_ASSOC */ /* In this branch is execute only when DIFF_ASSOC. If behavior == DIFF_KEY * data comparison is not needed - skipped. */ if (*ptr) { if (data_compare_type == DIFF_COMP_DATA_USER) { BG(user_compare_fci) = *fci_data; BG(user_compare_fci_cache) = *fci_data_cache; } if (diff_data_compare_func(ptrs[0], ptr TSRMLS_CC) != 0) { /* the data is not the same */ c = -1; if (key_compare_type == DIFF_COMP_KEY_USER) { BG(user_compare_fci) = *fci_key; BG(user_compare_fci_cache) = *fci_key_cache; } } else { break; /* we have found the element in other arrays thus we don't want it * in the return_value -> delete from there */ } } } else if (behavior == DIFF_KEY) { /* only when DIFF_KEY */ /* the behavior here differs from INTERSECT_KEY in php_intersect * since in the "diff" case we have to remove the entry from * return_value while when doing intersection the entry must not * be deleted. */ break; /* remove the key */ } } } if (!c) { /* ptrs[0] in one of the other arguments */ /* delete all entries with value as ptrs[0] */ for (;;) { p = *ptrs[0]; if (p->nKeyLength == 0) { zend_hash_index_del(Z_ARRVAL_P(return_value), p->h); } else { zend_hash_quick_del(Z_ARRVAL_P(return_value), p->arKey, p->nKeyLength, p->h); } if (!*++ptrs[0]) { goto out; } if (behavior == DIFF_NORMAL) { if (diff_data_compare_func(ptrs[0] - 1, ptrs[0] TSRMLS_CC)) { break; } } else if (behavior & DIFF_ASSOC) { /* triggered also when DIFF_KEY */ /* in this case no array_key_compare is needed */ break; } } } else { /* ptrs[0] in none of the other arguments */ /* skip all entries with value as ptrs[0] */ for (;;) { if (!*++ptrs[0]) { goto out; } if (behavior == DIFF_NORMAL) { if (diff_data_compare_func(ptrs[0] - 1, ptrs[0] TSRMLS_CC)) { break; } } else if (behavior & DIFF_ASSOC) { /* triggered also when DIFF_KEY */ /* in this case no array_key_compare is needed */ break; } } } } out: for (i = 0; i < arr_argc; i++) { hash = Z_ARRVAL_PP(args[i]); pefree(lists[i], hash->persistent); } PHP_ARRAY_CMP_FUNC_RESTORE(); efree(ptrs); efree(lists); efree(args); } /* }}} */ /* {{{ proto array array_diff_key(array arr1, array arr2 [, array ...]) Returns the entries of arr1 that have keys which are not present in any of the others arguments. This function is like array_diff() but works on the keys instead of the values. The associativity is preserved. */ PHP_FUNCTION(array_diff_key) { php_array_diff_key(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_COMP_DATA_NONE); } /* }}} */ /* {{{ proto array array_diff_ukey(array arr1, array arr2 [, array ...], callback key_comp_func) Returns the entries of arr1 that have keys which are not present in any of the others arguments. User supplied function is used for comparing the keys. This function is like array_udiff() but works on the keys instead of the values. The associativity is preserved. */ PHP_FUNCTION(array_diff_ukey) { php_array_diff(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_KEY, DIFF_COMP_DATA_INTERNAL, DIFF_COMP_KEY_USER); } /* }}} */ /* {{{ proto array array_diff(array arr1, array arr2 [, array ...]) Returns the entries of arr1 that have values which are not present in any of the others arguments. */ PHP_FUNCTION(array_diff) { php_array_diff(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_NORMAL, DIFF_COMP_DATA_INTERNAL, DIFF_COMP_KEY_INTERNAL); } /* }}} */ /* {{{ proto array array_udiff(array arr1, array arr2 [, array ...], callback data_comp_func) Returns the entries of arr1 that have values which are not present in any of the others arguments. Elements are compared by user supplied function. */ PHP_FUNCTION(array_udiff) { php_array_diff(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_NORMAL, DIFF_COMP_DATA_USER, DIFF_COMP_KEY_INTERNAL); } /* }}} */ /* {{{ proto array array_diff_assoc(array arr1, array arr2 [, array ...]) Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal */ PHP_FUNCTION(array_diff_assoc) { php_array_diff_key(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_COMP_DATA_INTERNAL); } /* }}} */ /* {{{ proto array array_diff_uassoc(array arr1, array arr2 [, array ...], callback data_comp_func) Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal. Elements are compared by user supplied function. */ PHP_FUNCTION(array_diff_uassoc) { php_array_diff(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_ASSOC, DIFF_COMP_DATA_INTERNAL, DIFF_COMP_KEY_USER); } /* }}} */ /* {{{ proto array array_udiff_assoc(array arr1, array arr2 [, array ...], callback key_comp_func) Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal. Keys are compared by user supplied function. */ PHP_FUNCTION(array_udiff_assoc) { php_array_diff_key(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_COMP_DATA_USER); } /* }}} */ /* {{{ proto array array_udiff_uassoc(array arr1, array arr2 [, array ...], callback data_comp_func, callback key_comp_func) Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal. Keys and elements are compared by user supplied functions. */ PHP_FUNCTION(array_udiff_uassoc) { php_array_diff(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_ASSOC, DIFF_COMP_DATA_USER, DIFF_COMP_KEY_USER); } /* }}} */ #define MULTISORT_ORDER 0 #define MULTISORT_TYPE 1 #define MULTISORT_LAST 2 PHPAPI int php_multisort_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { Bucket **ab = *(Bucket ***)a; Bucket **bb = *(Bucket ***)b; int r; int result = 0; zval temp; r = 0; do { php_set_compare_func(ARRAYG(multisort_flags)[MULTISORT_TYPE][r] TSRMLS_CC); ARRAYG(compare_func)(&temp, *((zval **)ab[r]->pData), *((zval **)bb[r]->pData) TSRMLS_CC); result = ARRAYG(multisort_flags)[MULTISORT_ORDER][r] * Z_LVAL(temp); if (result != 0) { return result; } r++; } while (ab[r] != NULL); return result; } /* }}} */ #define MULTISORT_ABORT \ for (k = 0; k < MULTISORT_LAST; k++) \ efree(ARRAYG(multisort_flags)[k]); \ efree(arrays); \ efree(args); \ RETURN_FALSE; /* {{{ proto bool array_multisort(array ar1 [, SORT_ASC|SORT_DESC [, SORT_REGULAR|SORT_NUMERIC|SORT_STRING]] [, array ar2 [, SORT_ASC|SORT_DESC [, SORT_REGULAR|SORT_NUMERIC|SORT_STRING]], ...]) Sort multiple arrays at once similar to how ORDER BY clause works in SQL */ PHP_FUNCTION(array_multisort) { zval*** args; zval*** arrays; Bucket*** indirect; Bucket* p; HashTable* hash; int argc; int array_size; int num_arrays = 0; int parse_state[MULTISORT_LAST]; /* 0 - flag not allowed 1 - flag allowed */ int sort_order = PHP_SORT_ASC; int sort_type = PHP_SORT_REGULAR; int i, k; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &argc) == FAILURE) { return; } /* Allocate space for storing pointers to input arrays and sort flags. */ arrays = (zval ***)ecalloc(argc, sizeof(zval **)); for (i = 0; i < MULTISORT_LAST; i++) { parse_state[i] = 0; ARRAYG(multisort_flags)[i] = (int *)ecalloc(argc, sizeof(int)); } /* Here we go through the input arguments and parse them. Each one can * be either an array or a sort flag which follows an array. If not * specified, the sort flags defaults to PHP_SORT_ASC and PHP_SORT_REGULAR * accordingly. There can't be two sort flags of the same type after an * array, and the very first argument has to be an array. */ for (i = 0; i < argc; i++) { if (Z_TYPE_PP(args[i]) == IS_ARRAY) { /* We see the next array, so we update the sort flags of * the previous array and reset the sort flags. */ if (i > 0) { ARRAYG(multisort_flags)[MULTISORT_ORDER][num_arrays - 1] = sort_order; ARRAYG(multisort_flags)[MULTISORT_TYPE][num_arrays - 1] = sort_type; sort_order = PHP_SORT_ASC; sort_type = PHP_SORT_REGULAR; } arrays[num_arrays++] = args[i]; /* Next one may be an array or a list of sort flags. */ for (k = 0; k < MULTISORT_LAST; k++) { parse_state[k] = 1; } } else if (Z_TYPE_PP(args[i]) == IS_LONG) { switch (Z_LVAL_PP(args[i])) { case PHP_SORT_ASC: case PHP_SORT_DESC: /* flag allowed here */ if (parse_state[MULTISORT_ORDER] == 1) { /* Save the flag and make sure then next arg is not the current flag. */ sort_order = Z_LVAL_PP(args[i]) == PHP_SORT_DESC ? -1 : 1; parse_state[MULTISORT_ORDER] = 0; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is expected to be an array or sorting flag that has not already been specified", i + 1); MULTISORT_ABORT; } break; case PHP_SORT_REGULAR: case PHP_SORT_NUMERIC: case PHP_SORT_STRING: #if HAVE_STRCOLL case PHP_SORT_LOCALE_STRING: #endif /* flag allowed here */ if (parse_state[MULTISORT_TYPE] == 1) { /* Save the flag and make sure then next arg is not the current flag. */ sort_type = Z_LVAL_PP(args[i]); parse_state[MULTISORT_TYPE] = 0; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is expected to be an array or sorting flag that has not already been specified", i + 1); MULTISORT_ABORT; } break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is an unknown sort flag", i + 1); MULTISORT_ABORT; break; } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is expected to be an array or a sort flag", i + 1); MULTISORT_ABORT; } } /* Take care of the last array sort flags. */ ARRAYG(multisort_flags)[MULTISORT_ORDER][num_arrays - 1] = sort_order; ARRAYG(multisort_flags)[MULTISORT_TYPE][num_arrays - 1] = sort_type; /* Make sure the arrays are of the same size. */ array_size = zend_hash_num_elements(Z_ARRVAL_PP(arrays[0])); for (i = 0; i < num_arrays; i++) { if (zend_hash_num_elements(Z_ARRVAL_PP(arrays[i])) != array_size) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array sizes are inconsistent"); MULTISORT_ABORT; } } /* If all arrays are empty we don't need to do anything. */ if (array_size < 1) { for (k = 0; k < MULTISORT_LAST; k++) { efree(ARRAYG(multisort_flags)[k]); } efree(arrays); efree(args); RETURN_TRUE; } /* Create the indirection array. This array is of size MxN, where * M is the number of entries in each input array and N is the number * of the input arrays + 1. The last column is NULL to indicate the end * of the row. */ indirect = (Bucket ***)safe_emalloc(array_size, sizeof(Bucket **), 0); for (i = 0; i < array_size; i++) { indirect[i] = (Bucket **)safe_emalloc((num_arrays + 1), sizeof(Bucket *), 0); } for (i = 0; i < num_arrays; i++) { k = 0; for (p = Z_ARRVAL_PP(arrays[i])->pListHead; p; p = p->pListNext, k++) { indirect[k][i] = p; } } for (k = 0; k < array_size; k++) { indirect[k][num_arrays] = NULL; } /* Do the actual sort magic - bada-bim, bada-boom. */ zend_qsort(indirect, array_size, sizeof(Bucket **), php_multisort_compare TSRMLS_CC); /* Restructure the arrays based on sorted indirect - this is mostly taken from zend_hash_sort() function. */ HANDLE_BLOCK_INTERRUPTIONS(); for (i = 0; i < num_arrays; i++) { hash = Z_ARRVAL_PP(arrays[i]); hash->pListHead = indirect[0][i];; hash->pListTail = NULL; hash->pInternalPointer = hash->pListHead; for (k = 0; k < array_size; k++) { if (hash->pListTail) { hash->pListTail->pListNext = indirect[k][i]; } indirect[k][i]->pListLast = hash->pListTail; indirect[k][i]->pListNext = NULL; hash->pListTail = indirect[k][i]; } p = hash->pListHead; k = 0; while (p != NULL) { if (p->nKeyLength == 0) p->h = k++; p = p->pListNext; } hash->nNextFreeElement = array_size; zend_hash_rehash(hash); } HANDLE_UNBLOCK_INTERRUPTIONS(); /* Clean up. */ for (i = 0; i < array_size; i++) { efree(indirect[i]); } efree(indirect); for (k = 0; k < MULTISORT_LAST; k++) { efree(ARRAYG(multisort_flags)[k]); } efree(arrays); efree(args); RETURN_TRUE; } /* }}} */ /* {{{ proto mixed array_rand(array input [, int num_req]) Return key/keys for random entry/entries in the array */ PHP_FUNCTION(array_rand) { zval *input; long randval, num_req = 1; int num_avail, key_type; char *string_key; uint string_key_len; ulong num_key; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &input, &num_req) == FAILURE) { return; } num_avail = zend_hash_num_elements(Z_ARRVAL_P(input)); if (ZEND_NUM_ARGS() > 1) { if (num_req <= 0 || num_req > num_avail) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Second argument has to be between 1 and the number of elements in the array"); return; } } /* Make the return value an array only if we need to pass back more than one result. */ if (num_req > 1) { array_init_size(return_value, num_req); } /* We can't use zend_hash_index_find() because the array may have string keys or gaps. */ zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos); while (num_req && (key_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(input), &string_key, &string_key_len, &num_key, 0, &pos)) != HASH_KEY_NON_EXISTANT) { randval = php_rand(TSRMLS_C); if ((double) (randval / (PHP_RAND_MAX + 1.0)) < (double) num_req / (double) num_avail) { /* If we are returning a single result, just do it. */ if (Z_TYPE_P(return_value) != IS_ARRAY) { if (key_type == HASH_KEY_IS_STRING) { RETURN_STRINGL(string_key, string_key_len - 1, 1); } else { RETURN_LONG(num_key); } } else { /* Append the result to the return value. */ if (key_type == HASH_KEY_IS_STRING) { add_next_index_stringl(return_value, string_key, string_key_len - 1, 1); } else { add_next_index_long(return_value, num_key); } } num_req--; } num_avail--; zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos); } } /* }}} */ /* {{{ proto mixed array_sum(array input) Returns the sum of the array entries */ PHP_FUNCTION(array_sum) { zval *input, **entry, entry_n; HashPosition pos; double dval; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &input) == FAILURE) { return; } ZVAL_LONG(return_value, 0); for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos); zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &pos) == SUCCESS; zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos) ) { if (Z_TYPE_PP(entry) == IS_ARRAY || Z_TYPE_PP(entry) == IS_OBJECT) { continue; } entry_n = **entry; zval_copy_ctor(&entry_n); convert_scalar_to_number(&entry_n TSRMLS_CC); if (Z_TYPE(entry_n) == IS_LONG && Z_TYPE_P(return_value) == IS_LONG) { dval = (double)Z_LVAL_P(return_value) + (double)Z_LVAL(entry_n); if ( (double)LONG_MIN <= dval && dval <= (double)LONG_MAX ) { Z_LVAL_P(return_value) += Z_LVAL(entry_n); continue; } } convert_to_double(return_value); convert_to_double(&entry_n); Z_DVAL_P(return_value) += Z_DVAL(entry_n); } } /* }}} */ /* {{{ proto mixed array_product(array input) Returns the product of the array entries */ PHP_FUNCTION(array_product) { zval *input, **entry, entry_n; HashPosition pos; double dval; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &input) == FAILURE) { return; } ZVAL_LONG(return_value, 1); if (!zend_hash_num_elements(Z_ARRVAL_P(input))) { return; } for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos); zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &pos) == SUCCESS; zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos) ) { if (Z_TYPE_PP(entry) == IS_ARRAY || Z_TYPE_PP(entry) == IS_OBJECT) { continue; } entry_n = **entry; zval_copy_ctor(&entry_n); convert_scalar_to_number(&entry_n TSRMLS_CC); if (Z_TYPE(entry_n) == IS_LONG && Z_TYPE_P(return_value) == IS_LONG) { dval = (double)Z_LVAL_P(return_value) * (double)Z_LVAL(entry_n); if ( (double)LONG_MIN <= dval && dval <= (double)LONG_MAX ) { Z_LVAL_P(return_value) *= Z_LVAL(entry_n); continue; } } convert_to_double(return_value); convert_to_double(&entry_n); Z_DVAL_P(return_value) *= Z_DVAL(entry_n); } } /* }}} */ /* {{{ proto mixed array_reduce(array input, mixed callback [, mixed initial]) Iteratively reduce the array to a single value via the callback. */ PHP_FUNCTION(array_reduce) { zval *input; zval **args[2]; zval **operand; zval *result = NULL; zval *retval; zend_fcall_info fci; zend_fcall_info_cache fci_cache = empty_fcall_info_cache; zval *initial = NULL; HashPosition pos; HashTable *htbl; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "af|z", &input, &fci, &fci_cache, &initial) == FAILURE) { return; } if (ZEND_NUM_ARGS() > 2) { ALLOC_ZVAL(result); MAKE_COPY_ZVAL(&initial, result); } else { MAKE_STD_ZVAL(result); ZVAL_NULL(result); } /* (zval **)input points to an element of argument stack * the base pointer of which is subject to change. * thus we need to keep the pointer to the hashtable for safety */ htbl = Z_ARRVAL_P(input); if (zend_hash_num_elements(htbl) == 0) { if (result) { RETVAL_ZVAL(result, 1, 1); } return; } fci.retval_ptr_ptr = &retval; fci.param_count = 2; fci.no_separation = 0; zend_hash_internal_pointer_reset_ex(htbl, &pos); while (zend_hash_get_current_data_ex(htbl, (void **)&operand, &pos) == SUCCESS) { if (result) { args[0] = &result; args[1] = operand; fci.params = args; if (zend_call_function(&fci, &fci_cache TSRMLS_CC) == SUCCESS && retval) { zval_ptr_dtor(&result); result = retval; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "An error occurred while invoking the reduction callback"); return; } } else { result = *operand; zval_add_ref(&result); } zend_hash_move_forward_ex(htbl, &pos); } RETVAL_ZVAL(result, 1, 1); } /* }}} */ /* {{{ proto array array_filter(array input [, mixed callback]) Filters elements from the array via the callback. */ PHP_FUNCTION(array_filter) { zval *array; zval **operand; zval **args[1]; zval *retval = NULL; zend_bool have_callback = 0; char *string_key; zend_fcall_info fci = empty_fcall_info; zend_fcall_info_cache fci_cache = empty_fcall_info_cache; uint string_key_len; ulong num_key; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|f", &array, &fci, &fci_cache) == FAILURE) { return; } array_init(return_value); if (zend_hash_num_elements(Z_ARRVAL_P(array)) == 0) { return; } if (ZEND_NUM_ARGS() > 1) { have_callback = 1; fci.no_separation = 0; fci.retval_ptr_ptr = &retval; fci.param_count = 1; } for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(array), &pos); zend_hash_get_current_data_ex(Z_ARRVAL_P(array), (void **)&operand, &pos) == SUCCESS; zend_hash_move_forward_ex(Z_ARRVAL_P(array), &pos) ) { if (have_callback) { args[0] = operand; fci.params = args; if (zend_call_function(&fci, &fci_cache TSRMLS_CC) == SUCCESS && retval) { if (!zend_is_true(retval)) { zval_ptr_dtor(&retval); continue; } else { zval_ptr_dtor(&retval); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "An error occurred while invoking the filter callback"); return; } } else if (!zend_is_true(*operand)) { continue; } zval_add_ref(operand); switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(array), &string_key, &string_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_STRING: zend_hash_update(Z_ARRVAL_P(return_value), string_key, string_key_len, operand, sizeof(zval *), NULL); break; case HASH_KEY_IS_LONG: zend_hash_index_update(Z_ARRVAL_P(return_value), num_key, operand, sizeof(zval *), NULL); break; } } } /* }}} */ /* {{{ proto array array_map(mixed callback, array input1 [, array input2 ,...]) Applies the callback to the elements in given arrays. */ PHP_FUNCTION(array_map) { zval ***arrays = NULL; int n_arrays = 0; zval ***params; zval *result, *null; HashPosition *array_pos; zval **args; zend_fcall_info fci = empty_fcall_info; zend_fcall_info_cache fci_cache = empty_fcall_info_cache; int i, k, maxlen = 0; int *array_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "f!+", &fci, &fci_cache, &arrays, &n_arrays) == FAILURE) { return; } RETVAL_NULL(); args = (zval **)safe_emalloc(n_arrays, sizeof(zval *), 0); array_len = (int *)safe_emalloc(n_arrays, sizeof(int), 0); array_pos = (HashPosition *)safe_emalloc(n_arrays, sizeof(HashPosition), 0); for (i = 0; i < n_arrays; i++) { if (Z_TYPE_PP(arrays[i]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d should be an array", i + 2); efree(arrays); efree(args); efree(array_len); efree(array_pos); return; } SEPARATE_ZVAL_IF_NOT_REF(arrays[i]); args[i] = *arrays[i]; array_len[i] = zend_hash_num_elements(Z_ARRVAL_PP(arrays[i])); if (array_len[i] > maxlen) { maxlen = array_len[i]; } zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(arrays[i]), &array_pos[i]); } efree(arrays); /* Short-circuit: if no callback and only one array, just return it. */ if (!ZEND_FCI_INITIALIZED(fci) && n_arrays == 1) { RETVAL_ZVAL(args[0], 1, 0); efree(array_len); efree(array_pos); efree(args); return; } array_init_size(return_value, maxlen); params = (zval ***)safe_emalloc(n_arrays, sizeof(zval **), 0); MAKE_STD_ZVAL(null); ZVAL_NULL(null); /* We iterate through all the arrays at once. */ for (k = 0; k < maxlen; k++) { uint str_key_len; ulong num_key; char *str_key; int key_type = 0; /* If no callback, the result will be an array, consisting of current * entries from all arrays. */ if (!ZEND_FCI_INITIALIZED(fci)) { MAKE_STD_ZVAL(result); array_init_size(result, n_arrays); } for (i = 0; i < n_arrays; i++) { /* If this array still has elements, add the current one to the * parameter list, otherwise use null value. */ if (k < array_len[i]) { zend_hash_get_current_data_ex(Z_ARRVAL_P(args[i]), (void **)&params[i], &array_pos[i]); /* It is safe to store only last value of key type, because * this loop will run just once if there is only 1 array. */ if (n_arrays == 1) { key_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(args[0]), &str_key, &str_key_len, &num_key, 0, &array_pos[i]); } zend_hash_move_forward_ex(Z_ARRVAL_P(args[i]), &array_pos[i]); } else { params[i] = &null; } if (!ZEND_FCI_INITIALIZED(fci)) { zval_add_ref(params[i]); add_next_index_zval(result, *params[i]); } } if (ZEND_FCI_INITIALIZED(fci)) { fci.retval_ptr_ptr = &result; fci.param_count = n_arrays; fci.params = params; fci.no_separation = 0; if (zend_call_function(&fci, &fci_cache TSRMLS_CC) != SUCCESS || !result) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "An error occurred while invoking the map callback"); efree(array_len); efree(args); efree(array_pos); zval_dtor(return_value); zval_ptr_dtor(&null); efree(params); RETURN_NULL(); } } if (n_arrays > 1) { add_next_index_zval(return_value, result); } else { if (key_type == HASH_KEY_IS_STRING) { add_assoc_zval_ex(return_value, str_key, str_key_len, result); } else { add_index_zval(return_value, num_key, result); } } } zval_ptr_dtor(&null); efree(params); efree(array_len); efree(array_pos); efree(args); } /* }}} */ /* {{{ proto bool array_key_exists(mixed key, array search) Checks if the given key or index exists in the array */ PHP_FUNCTION(array_key_exists) { zval *key; /* key to check for */ HashTable *array; /* array to check in */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zH", &key, &array) == FAILURE) { return; } switch (Z_TYPE_P(key)) { case IS_STRING: if (zend_symtable_exists(array, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1)) { RETURN_TRUE; } RETURN_FALSE; case IS_LONG: if (zend_hash_index_exists(array, Z_LVAL_P(key))) { RETURN_TRUE; } RETURN_FALSE; case IS_NULL: if (zend_hash_exists(array, "", 1)) { RETURN_TRUE; } RETURN_FALSE; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "The first argument should be either a string or an integer"); RETURN_FALSE; } } /* }}} */ /* {{{ proto array array_chunk(array input, int size [, bool preserve_keys]) Split array into chunks */ PHP_FUNCTION(array_chunk) { int argc = ZEND_NUM_ARGS(), key_type, num_in; long size, current = 0; char *str_key; uint str_key_len; ulong num_key; zend_bool preserve_keys = 0; zval *input = NULL; zval *chunk = NULL; zval **entry; HashPosition pos; if (zend_parse_parameters(argc TSRMLS_CC, "al|b", &input, &size, &preserve_keys) == FAILURE) { return; } /* Do bounds checking for size parameter. */ if (size < 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Size parameter expected to be greater than 0"); return; } num_in = zend_hash_num_elements(Z_ARRVAL_P(input)); if (size > num_in) { size = num_in > 0 ? num_in : 1; } array_init_size(return_value, ((num_in - 1) / size) + 1); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void**)&entry, &pos) == SUCCESS) { /* If new chunk, create and initialize it. */ if (!chunk) { MAKE_STD_ZVAL(chunk); array_init_size(chunk, size); } /* Add entry to the chunk, preserving keys if necessary. */ zval_add_ref(entry); if (preserve_keys) { key_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(input), &str_key, &str_key_len, &num_key, 0, &pos); switch (key_type) { case HASH_KEY_IS_STRING: add_assoc_zval_ex(chunk, str_key, str_key_len, *entry); break; default: add_index_zval(chunk, num_key, *entry); break; } } else { add_next_index_zval(chunk, *entry); } /* If reached the chunk size, add it to the result array, and reset the * pointer. */ if (!(++current % size)) { add_next_index_zval(return_value, chunk); chunk = NULL; } zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos); } /* Add the final chunk if there is one. */ if (chunk) { add_next_index_zval(return_value, chunk); } } /* }}} */ /* {{{ proto array array_combine(array keys, array values) Creates an array by using the elements of the first parameter as keys and the elements of the second as the corresponding values */ PHP_FUNCTION(array_combine) { zval *values, *keys; HashPosition pos_values, pos_keys; zval **entry_keys, **entry_values; int num_keys, num_values; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "aa", &keys, &values) == FAILURE) { return; } num_keys = zend_hash_num_elements(Z_ARRVAL_P(keys)); num_values = zend_hash_num_elements(Z_ARRVAL_P(values)); if (num_keys != num_values) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Both parameters should have an equal number of elements"); RETURN_FALSE; } array_init_size(return_value, num_keys); if (!num_keys) { return; } zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(keys), &pos_keys); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(values), &pos_values); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(keys), (void **)&entry_keys, &pos_keys) == SUCCESS && zend_hash_get_current_data_ex(Z_ARRVAL_P(values), (void **)&entry_values, &pos_values) == SUCCESS ) { if (Z_TYPE_PP(entry_keys) == IS_LONG) { zval_add_ref(entry_values); add_index_zval(return_value, Z_LVAL_PP(entry_keys), *entry_values); } else { zval key, *key_ptr = *entry_keys; if (Z_TYPE_PP(entry_keys) != IS_STRING) { key = **entry_keys; zval_copy_ctor(&key); convert_to_string(&key); key_ptr = &key; } zval_add_ref(entry_values); add_assoc_zval_ex(return_value, Z_STRVAL_P(key_ptr), Z_STRLEN_P(key_ptr) + 1, *entry_values); if (key_ptr != *entry_keys) { zval_dtor(&key); } } zend_hash_move_forward_ex(Z_ARRVAL_P(keys), &pos_keys); zend_hash_move_forward_ex(Z_ARRVAL_P(values), &pos_values); } } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | Rasmus Lerdorf <[email protected]> | | Andrei Zmievski <[email protected]> | | Stig Venaas <[email protected]> | | Jason Greene <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "php.h" #include "php_ini.h" #include <stdarg.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <stdio.h> #if HAVE_STRING_H #include <string.h> #else #include <strings.h> #endif #ifdef PHP_WIN32 #include "win32/unistd.h" #endif #include "zend_globals.h" #include "zend_interfaces.h" #include "php_globals.h" #include "php_array.h" #include "basic_functions.h" #include "php_string.h" #include "php_rand.h" #include "php_smart_str.h" #ifdef HAVE_SPL #include "ext/spl/spl_array.h" #endif /* {{{ defines */ #define EXTR_OVERWRITE 0 #define EXTR_SKIP 1 #define EXTR_PREFIX_SAME 2 #define EXTR_PREFIX_ALL 3 #define EXTR_PREFIX_INVALID 4 #define EXTR_PREFIX_IF_EXISTS 5 #define EXTR_IF_EXISTS 6 #define EXTR_REFS 0x100 #define CASE_LOWER 0 #define CASE_UPPER 1 #define COUNT_NORMAL 0 #define COUNT_RECURSIVE 1 #define DIFF_NORMAL 1 #define DIFF_KEY 2 #define DIFF_ASSOC 6 #define DIFF_COMP_DATA_NONE -1 #define DIFF_COMP_DATA_INTERNAL 0 #define DIFF_COMP_DATA_USER 1 #define DIFF_COMP_KEY_INTERNAL 0 #define DIFF_COMP_KEY_USER 1 #define INTERSECT_NORMAL 1 #define INTERSECT_KEY 2 #define INTERSECT_ASSOC 6 #define INTERSECT_COMP_DATA_NONE -1 #define INTERSECT_COMP_DATA_INTERNAL 0 #define INTERSECT_COMP_DATA_USER 1 #define INTERSECT_COMP_KEY_INTERNAL 0 #define INTERSECT_COMP_KEY_USER 1 #define DOUBLE_DRIFT_FIX 0.000000000000001 /* }}} */ ZEND_DECLARE_MODULE_GLOBALS(array) /* {{{ php_array_init_globals */ static void php_array_init_globals(zend_array_globals *array_globals) { memset(array_globals, 0, sizeof(zend_array_globals)); } /* }}} */ PHP_MINIT_FUNCTION(array) /* {{{ */ { ZEND_INIT_MODULE_GLOBALS(array, php_array_init_globals, NULL); REGISTER_LONG_CONSTANT("EXTR_OVERWRITE", EXTR_OVERWRITE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_SKIP", EXTR_SKIP, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_PREFIX_SAME", EXTR_PREFIX_SAME, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_PREFIX_ALL", EXTR_PREFIX_ALL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_PREFIX_INVALID", EXTR_PREFIX_INVALID, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_PREFIX_IF_EXISTS", EXTR_PREFIX_IF_EXISTS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_IF_EXISTS", EXTR_IF_EXISTS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("EXTR_REFS", EXTR_REFS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_ASC", PHP_SORT_ASC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_DESC", PHP_SORT_DESC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_REGULAR", PHP_SORT_REGULAR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_NUMERIC", PHP_SORT_NUMERIC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_STRING", PHP_SORT_STRING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SORT_LOCALE_STRING", PHP_SORT_LOCALE_STRING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("CASE_LOWER", CASE_LOWER, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("CASE_UPPER", CASE_UPPER, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("COUNT_NORMAL", COUNT_NORMAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("COUNT_RECURSIVE", COUNT_RECURSIVE, CONST_CS | CONST_PERSISTENT); return SUCCESS; } /* }}} */ PHP_MSHUTDOWN_FUNCTION(array) /* {{{ */ { #ifdef ZTS ts_free_id(array_globals_id); #endif return SUCCESS; } /* }}} */ static void php_set_compare_func(int sort_type TSRMLS_DC) /* {{{ */ { switch (sort_type) { case PHP_SORT_NUMERIC: ARRAYG(compare_func) = numeric_compare_function; break; case PHP_SORT_STRING: ARRAYG(compare_func) = string_compare_function; break; #if HAVE_STRCOLL case PHP_SORT_LOCALE_STRING: ARRAYG(compare_func) = string_locale_compare_function; break; #endif case PHP_SORT_REGULAR: default: ARRAYG(compare_func) = compare_function; break; } } /* }}} */ static int php_array_key_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { Bucket *f; Bucket *s; zval result; zval first; zval second; f = *((Bucket **) a); s = *((Bucket **) b); if (f->nKeyLength == 0) { Z_TYPE(first) = IS_LONG; Z_LVAL(first) = f->h; } else { Z_TYPE(first) = IS_STRING; Z_STRVAL(first) = f->arKey; Z_STRLEN(first) = f->nKeyLength - 1; } if (s->nKeyLength == 0) { Z_TYPE(second) = IS_LONG; Z_LVAL(second) = s->h; } else { Z_TYPE(second) = IS_STRING; Z_STRVAL(second) = s->arKey; Z_STRLEN(second) = s->nKeyLength - 1; } if (ARRAYG(compare_func)(&result, &first, &second TSRMLS_CC) == FAILURE) { return 0; } if (Z_TYPE(result) == IS_DOUBLE) { if (Z_DVAL(result) < 0) { return -1; } else if (Z_DVAL(result) > 0) { return 1; } else { return 0; } } convert_to_long(&result); if (Z_LVAL(result) < 0) { return -1; } else if (Z_LVAL(result) > 0) { return 1; } return 0; } /* }}} */ static int php_array_reverse_key_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { return php_array_key_compare(a, b TSRMLS_CC) * -1; } /* }}} */ /* {{{ proto bool krsort(array &array_arg [, int sort_flags]) Sort an array by key value in reverse order */ PHP_FUNCTION(krsort) { zval *array; long sort_type = PHP_SORT_REGULAR; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { RETURN_FALSE; } php_set_compare_func(sort_type TSRMLS_CC); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_reverse_key_compare, 0 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool ksort(array &array_arg [, int sort_flags]) Sort an array by key */ PHP_FUNCTION(ksort) { zval *array; long sort_type = PHP_SORT_REGULAR; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { RETURN_FALSE; } php_set_compare_func(sort_type TSRMLS_CC); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_key_compare, 0 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ static int php_count_recursive(zval *array, long mode TSRMLS_DC) /* {{{ */ { long cnt = 0; zval **element; if (Z_TYPE_P(array) == IS_ARRAY) { if (Z_ARRVAL_P(array)->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); return 0; } cnt = zend_hash_num_elements(Z_ARRVAL_P(array)); if (mode == COUNT_RECURSIVE) { HashPosition pos; for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(array), &pos); zend_hash_get_current_data_ex(Z_ARRVAL_P(array), (void **) &element, &pos) == SUCCESS; zend_hash_move_forward_ex(Z_ARRVAL_P(array), &pos) ) { Z_ARRVAL_P(array)->nApplyCount++; cnt += php_count_recursive(*element, COUNT_RECURSIVE TSRMLS_CC); Z_ARRVAL_P(array)->nApplyCount--; } } } return cnt; } /* }}} */ /* {{{ proto int count(mixed var [, int mode]) Count the number of elements in a variable (usually an array) */ PHP_FUNCTION(count) { zval *array; long mode = COUNT_NORMAL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|l", &array, &mode) == FAILURE) { return; } switch (Z_TYPE_P(array)) { case IS_NULL: RETURN_LONG(0); break; case IS_ARRAY: RETURN_LONG (php_count_recursive (array, mode TSRMLS_CC)); break; case IS_OBJECT: { #ifdef HAVE_SPL zval *retval; #endif /* first, we check if the handler is defined */ if (Z_OBJ_HT_P(array)->count_elements) { RETVAL_LONG(1); if (SUCCESS == Z_OBJ_HT(*array)->count_elements(array, &Z_LVAL_P(return_value) TSRMLS_CC)) { return; } } #ifdef HAVE_SPL /* if not and the object implements Countable we call its count() method */ if (Z_OBJ_HT_P(array)->get_class_entry && instanceof_function(Z_OBJCE_P(array), spl_ce_Countable TSRMLS_CC)) { zend_call_method_with_0_params(&array, NULL, NULL, "count", &retval); if (retval) { convert_to_long_ex(&retval); RETVAL_LONG(Z_LVAL_P(retval)); zval_ptr_dtor(&retval); } return; } #endif } default: RETURN_LONG(1); break; } } /* }}} */ /* Numbers are always smaller than strings int this function as it * anyway doesn't make much sense to compare two different data types. * This keeps it consistant and simple. * * This is not correct any more, depends on what compare_func is set to. */ static int php_array_data_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { Bucket *f; Bucket *s; zval result; zval *first; zval *second; f = *((Bucket **) a); s = *((Bucket **) b); first = *((zval **) f->pData); second = *((zval **) s->pData); if (ARRAYG(compare_func)(&result, first, second TSRMLS_CC) == FAILURE) { return 0; } if (Z_TYPE(result) == IS_DOUBLE) { if (Z_DVAL(result) < 0) { return -1; } else if (Z_DVAL(result) > 0) { return 1; } else { return 0; } } convert_to_long(&result); if (Z_LVAL(result) < 0) { return -1; } else if (Z_LVAL(result) > 0) { return 1; } return 0; } /* }}} */ static int php_array_reverse_data_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { return php_array_data_compare(a, b TSRMLS_CC) * -1; } /* }}} */ static int php_array_natural_general_compare(const void *a, const void *b, int fold_case) /* {{{ */ { Bucket *f, *s; zval *fval, *sval; zval first, second; int result; f = *((Bucket **) a); s = *((Bucket **) b); fval = *((zval **) f->pData); sval = *((zval **) s->pData); first = *fval; second = *sval; if (Z_TYPE_P(fval) != IS_STRING) { zval_copy_ctor(&first); convert_to_string(&first); } if (Z_TYPE_P(sval) != IS_STRING) { zval_copy_ctor(&second); convert_to_string(&second); } result = strnatcmp_ex(Z_STRVAL(first), Z_STRLEN(first), Z_STRVAL(second), Z_STRLEN(second), fold_case); if (Z_TYPE_P(fval) != IS_STRING) { zval_dtor(&first); } if (Z_TYPE_P(sval) != IS_STRING) { zval_dtor(&second); } return result; } /* }}} */ static int php_array_natural_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { return php_array_natural_general_compare(a, b, 0); } /* }}} */ static int php_array_natural_case_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { return php_array_natural_general_compare(a, b, 1); } /* }}} */ static void php_natsort(INTERNAL_FUNCTION_PARAMETERS, int fold_case) /* {{{ */ { zval *array; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) { return; } if (fold_case) { if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_natural_case_compare, 0 TSRMLS_CC) == FAILURE) { return; } } else { if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_natural_compare, 0 TSRMLS_CC) == FAILURE) { return; } } RETURN_TRUE; } /* }}} */ /* {{{ proto void natsort(array &array_arg) Sort an array using natural sort */ PHP_FUNCTION(natsort) { php_natsort(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto void natcasesort(array &array_arg) Sort an array using case-insensitive natural sort */ PHP_FUNCTION(natcasesort) { php_natsort(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto bool asort(array &array_arg [, int sort_flags]) Sort an array and maintain index association */ PHP_FUNCTION(asort) { zval *array; long sort_type = PHP_SORT_REGULAR; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { RETURN_FALSE; } php_set_compare_func(sort_type TSRMLS_CC); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_data_compare, 0 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool arsort(array &array_arg [, int sort_flags]) Sort an array in reverse order and maintain index association */ PHP_FUNCTION(arsort) { zval *array; long sort_type = PHP_SORT_REGULAR; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { RETURN_FALSE; } php_set_compare_func(sort_type TSRMLS_CC); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_reverse_data_compare, 0 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool sort(array &array_arg [, int sort_flags]) Sort an array */ PHP_FUNCTION(sort) { zval *array; long sort_type = PHP_SORT_REGULAR; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { RETURN_FALSE; } php_set_compare_func(sort_type TSRMLS_CC); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_data_compare, 1 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool rsort(array &array_arg [, int sort_flags]) Sort an array in reverse order */ PHP_FUNCTION(rsort) { zval *array; long sort_type = PHP_SORT_REGULAR; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { RETURN_FALSE; } php_set_compare_func(sort_type TSRMLS_CC); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_reverse_data_compare, 1 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ static int php_array_user_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { Bucket *f; Bucket *s; zval **args[2]; zval *retval_ptr = NULL; f = *((Bucket **) a); s = *((Bucket **) b); args[0] = (zval **) f->pData; args[1] = (zval **) s->pData; BG(user_compare_fci).param_count = 2; BG(user_compare_fci).params = args; BG(user_compare_fci).retval_ptr_ptr = &retval_ptr; BG(user_compare_fci).no_separation = 0; if (zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache) TSRMLS_CC) == SUCCESS && retval_ptr) { long retval; convert_to_long_ex(&retval_ptr); retval = Z_LVAL_P(retval_ptr); zval_ptr_dtor(&retval_ptr); return retval < 0 ? -1 : retval > 0 ? 1 : 0; } else { return 0; } } /* }}} */ /* check if comparison function is valid */ #define PHP_ARRAY_CMP_FUNC_CHECK(func_name) \ if (!zend_is_callable(*func_name, 0, NULL TSRMLS_CC)) { \ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid comparison function"); \ BG(user_compare_fci) = old_user_compare_fci; \ BG(user_compare_fci_cache) = old_user_compare_fci_cache; \ RETURN_FALSE; \ } \ /* Clear FCI cache otherwise : for example the same or other array with * (partly) the same key values has been sorted with uasort() or * other sorting function the comparison is cached, however the name * of the function for comparison is not respected. see bug #28739 AND #33295 * * Following defines will assist in backup / restore values. */ #define PHP_ARRAY_CMP_FUNC_VARS \ zend_fcall_info old_user_compare_fci; \ zend_fcall_info_cache old_user_compare_fci_cache \ #define PHP_ARRAY_CMP_FUNC_BACKUP() \ old_user_compare_fci = BG(user_compare_fci); \ old_user_compare_fci_cache = BG(user_compare_fci_cache); \ BG(user_compare_fci_cache) = empty_fcall_info_cache; \ #define PHP_ARRAY_CMP_FUNC_RESTORE() \ BG(user_compare_fci) = old_user_compare_fci; \ BG(user_compare_fci_cache) = old_user_compare_fci_cache; \ /* {{{ proto bool usort(array array_arg, string cmp_function) Sort an array by values using a user-defined comparison function */ PHP_FUNCTION(usort) { zval *array; unsigned int refcount; PHP_ARRAY_CMP_FUNC_VARS; PHP_ARRAY_CMP_FUNC_BACKUP(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "af", &array, &BG(user_compare_fci), &BG(user_compare_fci_cache)) == FAILURE) { PHP_ARRAY_CMP_FUNC_RESTORE(); return; } /* Clear the is_ref flag, so the attemts to modify the array in user * comparison function will create a copy of array and won't affect the * original array. The fact of modification is detected using refcount * comparison. The result of sorting in such case is undefined and the * function returns FALSE. */ Z_UNSET_ISREF_P(array); refcount = Z_REFCOUNT_P(array); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_user_compare, 1 TSRMLS_CC) == FAILURE) { RETVAL_FALSE; } else { if (refcount > Z_REFCOUNT_P(array)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array was modified by the user comparison function"); RETVAL_FALSE; } else { RETVAL_TRUE; } } if (Z_REFCOUNT_P(array) > 1) { Z_SET_ISREF_P(array); } PHP_ARRAY_CMP_FUNC_RESTORE(); } /* }}} */ /* {{{ proto bool uasort(array array_arg, string cmp_function) Sort an array with a user-defined comparison function and maintain index association */ PHP_FUNCTION(uasort) { zval *array; unsigned int refcount; PHP_ARRAY_CMP_FUNC_VARS; PHP_ARRAY_CMP_FUNC_BACKUP(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "af", &array, &BG(user_compare_fci), &BG(user_compare_fci_cache)) == FAILURE) { PHP_ARRAY_CMP_FUNC_RESTORE(); return; } /* Clear the is_ref flag, so the attemts to modify the array in user * comaprison function will create a copy of array and won't affect the * original array. The fact of modification is detected using refcount * comparison. The result of sorting in such case is undefined and the * function returns FALSE. */ Z_UNSET_ISREF_P(array); refcount = Z_REFCOUNT_P(array); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_user_compare, 0 TSRMLS_CC) == FAILURE) { RETVAL_FALSE; } else { if (refcount > Z_REFCOUNT_P(array)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array was modified by the user comparison function"); RETVAL_FALSE; } else { RETVAL_TRUE; } } if (Z_REFCOUNT_P(array) > 1) { Z_SET_ISREF_P(array); } PHP_ARRAY_CMP_FUNC_RESTORE(); } /* }}} */ static int php_array_user_key_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { Bucket *f; Bucket *s; zval *key1, *key2; zval **args[2]; zval *retval_ptr = NULL; long result; ALLOC_INIT_ZVAL(key1); ALLOC_INIT_ZVAL(key2); args[0] = &key1; args[1] = &key2; f = *((Bucket **) a); s = *((Bucket **) b); if (f->nKeyLength == 0) { Z_LVAL_P(key1) = f->h; Z_TYPE_P(key1) = IS_LONG; } else { Z_STRVAL_P(key1) = estrndup(f->arKey, f->nKeyLength - 1); Z_STRLEN_P(key1) = f->nKeyLength - 1; Z_TYPE_P(key1) = IS_STRING; } if (s->nKeyLength == 0) { Z_LVAL_P(key2) = s->h; Z_TYPE_P(key2) = IS_LONG; } else { Z_STRVAL_P(key2) = estrndup(s->arKey, s->nKeyLength - 1); Z_STRLEN_P(key2) = s->nKeyLength - 1; Z_TYPE_P(key2) = IS_STRING; } BG(user_compare_fci).param_count = 2; BG(user_compare_fci).params = args; BG(user_compare_fci).retval_ptr_ptr = &retval_ptr; BG(user_compare_fci).no_separation = 0; if (zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache) TSRMLS_CC) == SUCCESS && retval_ptr) { convert_to_long_ex(&retval_ptr); result = Z_LVAL_P(retval_ptr); zval_ptr_dtor(&retval_ptr); } else { result = 0; } zval_ptr_dtor(&key1); zval_ptr_dtor(&key2); return result; } /* }}} */ /* {{{ proto bool uksort(array array_arg, string cmp_function) Sort an array by keys using a user-defined comparison function */ PHP_FUNCTION(uksort) { zval *array; unsigned int refcount; PHP_ARRAY_CMP_FUNC_VARS; PHP_ARRAY_CMP_FUNC_BACKUP(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "af", &array, &BG(user_compare_fci), &BG(user_compare_fci_cache)) == FAILURE) { PHP_ARRAY_CMP_FUNC_RESTORE(); return; } /* Clear the is_ref flag, so the attemts to modify the array in user * comaprison function will create a copy of array and won't affect the * original array. The fact of modification is detected using refcount * comparison. The result of sorting in such case is undefined and the * function returns FALSE. */ Z_UNSET_ISREF_P(array); refcount = Z_REFCOUNT_P(array); if (zend_hash_sort(Z_ARRVAL_P(array), zend_qsort, php_array_user_key_compare, 0 TSRMLS_CC) == FAILURE) { RETVAL_FALSE; } else { if (refcount > Z_REFCOUNT_P(array)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array was modified by the user comparison function"); RETVAL_FALSE; } else { RETVAL_TRUE; } } if (Z_REFCOUNT_P(array) > 1) { Z_SET_ISREF_P(array); } PHP_ARRAY_CMP_FUNC_RESTORE(); } /* }}} */ /* {{{ proto mixed end(array array_arg) Advances array argument's internal pointer to the last element and return it */ PHP_FUNCTION(end) { HashTable *array; zval **entry; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "H", &array) == FAILURE) { return; } zend_hash_internal_pointer_end(array); if (return_value_used) { if (zend_hash_get_current_data(array, (void **) &entry) == FAILURE) { RETURN_FALSE; } RETURN_ZVAL(*entry, 1, 0); } } /* }}} */ /* {{{ proto mixed prev(array array_arg) Move array argument's internal pointer to the previous element and return it */ PHP_FUNCTION(prev) { HashTable *array; zval **entry; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "H", &array) == FAILURE) { return; } zend_hash_move_backwards(array); if (return_value_used) { if (zend_hash_get_current_data(array, (void **) &entry) == FAILURE) { RETURN_FALSE; } RETURN_ZVAL(*entry, 1, 0); } } /* }}} */ /* {{{ proto mixed next(array array_arg) Move array argument's internal pointer to the next element and return it */ PHP_FUNCTION(next) { HashTable *array; zval **entry; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "H", &array) == FAILURE) { return; } zend_hash_move_forward(array); if (return_value_used) { if (zend_hash_get_current_data(array, (void **) &entry) == FAILURE) { RETURN_FALSE; } RETURN_ZVAL(*entry, 1, 0); } } /* }}} */ /* {{{ proto mixed reset(array array_arg) Set array argument's internal pointer to the first element and return it */ PHP_FUNCTION(reset) { HashTable *array; zval **entry; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "H", &array) == FAILURE) { return; } zend_hash_internal_pointer_reset(array); if (return_value_used) { if (zend_hash_get_current_data(array, (void **) &entry) == FAILURE) { RETURN_FALSE; } RETURN_ZVAL(*entry, 1, 0); } } /* }}} */ /* {{{ proto mixed current(array array_arg) Return the element currently pointed to by the internal array pointer */ PHP_FUNCTION(current) { HashTable *array; zval **entry; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "H", &array) == FAILURE) { return; } if (zend_hash_get_current_data(array, (void **) &entry) == FAILURE) { RETURN_FALSE; } RETURN_ZVAL(*entry, 1, 0); } /* }}} */ /* {{{ proto mixed key(array array_arg) Return the key of the element currently pointed to by the internal array pointer */ PHP_FUNCTION(key) { HashTable *array; char *string_key; uint string_length; ulong num_key; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "H", &array) == FAILURE) { return; } switch (zend_hash_get_current_key_ex(array, &string_key, &string_length, &num_key, 0, NULL)) { case HASH_KEY_IS_STRING: RETVAL_STRINGL(string_key, string_length - 1, 1); break; case HASH_KEY_IS_LONG: RETVAL_LONG(num_key); break; case HASH_KEY_NON_EXISTANT: return; } } /* }}} */ /* {{{ proto mixed min(mixed arg1 [, mixed arg2 [, mixed ...]]) Return the lowest value in an array or a series of arguments */ PHP_FUNCTION(min) { int argc; zval ***args = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &argc) == FAILURE) { return; } php_set_compare_func(PHP_SORT_REGULAR TSRMLS_CC); /* mixed min ( array $values ) */ if (argc == 1) { zval **result; if (Z_TYPE_PP(args[0]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "When only one parameter is given, it must be an array"); RETVAL_NULL(); } else { if (zend_hash_minmax(Z_ARRVAL_PP(args[0]), php_array_data_compare, 0, (void **) &result TSRMLS_CC) == SUCCESS) { RETVAL_ZVAL(*result, 1, 0); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array must contain at least one element"); RETVAL_FALSE; } } } else { /* mixed min ( mixed $value1 , mixed $value2 [, mixed $value3... ] ) */ zval **min, result; int i; min = args[0]; for (i = 1; i < argc; i++) { is_smaller_function(&result, *args[i], *min TSRMLS_CC); if (Z_LVAL(result) == 1) { min = args[i]; } } RETVAL_ZVAL(*min, 1, 0); } if (args) { efree(args); } } /* }}} */ /* {{{ proto mixed max(mixed arg1 [, mixed arg2 [, mixed ...]]) Return the highest value in an array or a series of arguments */ PHP_FUNCTION(max) { zval ***args = NULL; int argc; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &argc) == FAILURE) { return; } php_set_compare_func(PHP_SORT_REGULAR TSRMLS_CC); /* mixed max ( array $values ) */ if (argc == 1) { zval **result; if (Z_TYPE_PP(args[0]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "When only one parameter is given, it must be an array"); RETVAL_NULL(); } else { if (zend_hash_minmax(Z_ARRVAL_PP(args[0]), php_array_data_compare, 1, (void **) &result TSRMLS_CC) == SUCCESS) { RETVAL_ZVAL(*result, 1, 0); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array must contain at least one element"); RETVAL_FALSE; } } } else { /* mixed max ( mixed $value1 , mixed $value2 [, mixed $value3... ] ) */ zval **max, result; int i; max = args[0]; for (i = 1; i < argc; i++) { is_smaller_or_equal_function(&result, *args[i], *max TSRMLS_CC); if (Z_LVAL(result) == 0) { max = args[i]; } } RETVAL_ZVAL(*max, 1, 0); } if (args) { efree(args); } } /* }}} */ static int php_array_walk(HashTable *target_hash, zval **userdata, int recursive TSRMLS_DC) /* {{{ */ { zval **args[3], /* Arguments to userland function */ *retval_ptr, /* Return value - unused */ *key=NULL; /* Entry key */ char *string_key; uint string_key_len; ulong num_key; HashPosition pos; /* Set up known arguments */ args[1] = &key; args[2] = userdata; if (userdata) { Z_ADDREF_PP(userdata); } zend_hash_internal_pointer_reset_ex(target_hash, &pos); BG(array_walk_fci).retval_ptr_ptr = &retval_ptr; BG(array_walk_fci).param_count = userdata ? 3 : 2; BG(array_walk_fci).params = args; BG(array_walk_fci).no_separation = 0; /* Iterate through hash */ while (!EG(exception) && zend_hash_get_current_data_ex(target_hash, (void **)&args[0], &pos) == SUCCESS) { if (recursive && Z_TYPE_PP(args[0]) == IS_ARRAY) { HashTable *thash; zend_fcall_info orig_array_walk_fci; zend_fcall_info_cache orig_array_walk_fci_cache; SEPARATE_ZVAL_IF_NOT_REF(args[0]); thash = Z_ARRVAL_PP(args[0]); if (thash->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); if (userdata) { zval_ptr_dtor(userdata); } return 0; } /* backup the fcall info and cache */ orig_array_walk_fci = BG(array_walk_fci); orig_array_walk_fci_cache = BG(array_walk_fci_cache); thash->nApplyCount++; php_array_walk(thash, userdata, recursive TSRMLS_CC); thash->nApplyCount--; /* restore the fcall info and cache */ BG(array_walk_fci) = orig_array_walk_fci; BG(array_walk_fci_cache) = orig_array_walk_fci_cache; } else { /* Allocate space for key */ MAKE_STD_ZVAL(key); /* Set up the key */ switch (zend_hash_get_current_key_ex(target_hash, &string_key, &string_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_LONG: Z_TYPE_P(key) = IS_LONG; Z_LVAL_P(key) = num_key; break; case HASH_KEY_IS_STRING: ZVAL_STRINGL(key, string_key, string_key_len - 1, 1); break; } /* Call the userland function */ if (zend_call_function(&BG(array_walk_fci), &BG(array_walk_fci_cache) TSRMLS_CC) == SUCCESS) { if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } } else { if (key) { zval_ptr_dtor(&key); key = NULL; } break; } } if (key) { zval_ptr_dtor(&key); key = NULL; } zend_hash_move_forward_ex(target_hash, &pos); } if (userdata) { zval_ptr_dtor(userdata); } return 0; } /* }}} */ /* {{{ proto bool array_walk(array input, string funcname [, mixed userdata]) Apply a user function to every member of an array */ PHP_FUNCTION(array_walk) { HashTable *array; zval *userdata = NULL; zend_fcall_info orig_array_walk_fci; zend_fcall_info_cache orig_array_walk_fci_cache; orig_array_walk_fci = BG(array_walk_fci); orig_array_walk_fci_cache = BG(array_walk_fci_cache); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Hf|z/", &array, &BG(array_walk_fci), &BG(array_walk_fci_cache), &userdata) == FAILURE) { BG(array_walk_fci) = orig_array_walk_fci; BG(array_walk_fci_cache) = orig_array_walk_fci_cache; return; } php_array_walk(array, userdata ? &userdata : NULL, 0 TSRMLS_CC); BG(array_walk_fci) = orig_array_walk_fci; BG(array_walk_fci_cache) = orig_array_walk_fci_cache; RETURN_TRUE; } /* }}} */ /* {{{ proto bool array_walk_recursive(array input, string funcname [, mixed userdata]) Apply a user function recursively to every member of an array */ PHP_FUNCTION(array_walk_recursive) { HashTable *array; zval *userdata = NULL; zend_fcall_info orig_array_walk_fci; zend_fcall_info_cache orig_array_walk_fci_cache; orig_array_walk_fci = BG(array_walk_fci); orig_array_walk_fci_cache = BG(array_walk_fci_cache); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Hf|z/", &array, &BG(array_walk_fci), &BG(array_walk_fci_cache), &userdata) == FAILURE) { BG(array_walk_fci) = orig_array_walk_fci; BG(array_walk_fci_cache) = orig_array_walk_fci_cache; return; } php_array_walk(array, userdata ? &userdata : NULL, 1 TSRMLS_CC); BG(array_walk_fci) = orig_array_walk_fci; BG(array_walk_fci_cache) = orig_array_walk_fci_cache; RETURN_TRUE; } /* }}} */ /* void php_search_array(INTERNAL_FUNCTION_PARAMETERS, int behavior) * 0 = return boolean * 1 = return key */ static void php_search_array(INTERNAL_FUNCTION_PARAMETERS, int behavior) /* {{{ */ { zval *value, /* value to check for */ *array, /* array to check in */ **entry, /* pointer to array entry */ res; /* comparison result */ HashPosition pos; /* hash iterator */ zend_bool strict = 0; /* strict comparison or not */ ulong num_key; uint str_key_len; char *string_key; int (*is_equal_func)(zval *, zval *, zval * TSRMLS_DC) = is_equal_function; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "za|b", &value, &array, &strict) == FAILURE) { return; } if (strict) { is_equal_func = is_identical_function; } zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(array), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(array), (void **)&entry, &pos) == SUCCESS) { is_equal_func(&res, value, *entry TSRMLS_CC); if (Z_LVAL(res)) { if (behavior == 0) { RETURN_TRUE; } else { /* Return current key */ switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(array), &string_key, &str_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_STRING: RETURN_STRINGL(string_key, str_key_len - 1, 1); break; case HASH_KEY_IS_LONG: RETURN_LONG(num_key); break; } } } zend_hash_move_forward_ex(Z_ARRVAL_P(array), &pos); } RETURN_FALSE; } /* }}} */ /* {{{ proto bool in_array(mixed needle, array haystack [, bool strict]) Checks if the given value exists in the array */ PHP_FUNCTION(in_array) { php_search_array(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto mixed array_search(mixed needle, array haystack [, bool strict]) Searches the array for a given value and returns the corresponding key if successful */ PHP_FUNCTION(array_search) { php_search_array(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ static int php_valid_var_name(char *var_name, int var_name_len) /* {{{ */ { int i, ch; if (!var_name || !var_name_len) { return 0; } /* These are allowed as first char: [a-zA-Z_\x7f-\xff] */ ch = (int)((unsigned char *)var_name)[0]; if (var_name[0] != '_' && (ch < 65 /* A */ || /* Z */ ch > 90) && (ch < 97 /* a */ || /* z */ ch > 122) && (ch < 127 /* 0x7f */ || /* 0xff */ ch > 255) ) { return 0; } /* And these as the rest: [a-zA-Z0-9_\x7f-\xff] */ if (var_name_len > 1) { for (i = 1; i < var_name_len; i++) { ch = (int)((unsigned char *)var_name)[i]; if (var_name[i] != '_' && (ch < 48 /* 0 */ || /* 9 */ ch > 57) && (ch < 65 /* A */ || /* Z */ ch > 90) && (ch < 97 /* a */ || /* z */ ch > 122) && (ch < 127 /* 0x7f */ || /* 0xff */ ch > 255) ) { return 0; } } } return 1; } /* }}} */ PHPAPI int php_prefix_varname(zval *result, zval *prefix, char *var_name, int var_name_len, zend_bool add_underscore TSRMLS_DC) /* {{{ */ { Z_STRLEN_P(result) = Z_STRLEN_P(prefix) + (add_underscore ? 1 : 0) + var_name_len; Z_TYPE_P(result) = IS_STRING; Z_STRVAL_P(result) = emalloc(Z_STRLEN_P(result) + 1); memcpy(Z_STRVAL_P(result), Z_STRVAL_P(prefix), Z_STRLEN_P(prefix)); if (add_underscore) { Z_STRVAL_P(result)[Z_STRLEN_P(prefix)] = '_'; } memcpy(Z_STRVAL_P(result) + Z_STRLEN_P(prefix) + (add_underscore ? 1 : 0), var_name, var_name_len + 1); return SUCCESS; } /* }}} */ /* {{{ proto int extract(array var_array [, int extract_type [, string prefix]]) Imports variables into symbol table from an array */ PHP_FUNCTION(extract) { zval *var_array, *prefix = NULL; long extract_type = EXTR_OVERWRITE; zval **entry, *data; char *var_name; ulong num_key; uint var_name_len; int var_exists, key_type, count = 0; int extract_refs = 0; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|lz/", &var_array, &extract_type, &prefix) == FAILURE) { return; } extract_refs = (extract_type & EXTR_REFS); extract_type &= 0xff; if (extract_type < EXTR_OVERWRITE || extract_type > EXTR_IF_EXISTS) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid extract type"); return; } if (extract_type > EXTR_SKIP && extract_type <= EXTR_PREFIX_IF_EXISTS && ZEND_NUM_ARGS() < 3) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "specified extract type requires the prefix parameter"); return; } if (prefix) { convert_to_string(prefix); if (Z_STRLEN_P(prefix) && !php_valid_var_name(Z_STRVAL_P(prefix), Z_STRLEN_P(prefix))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "prefix is not a valid identifier"); return; } } if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } /* var_array is passed by ref for the needs of EXTR_REFS (needs to * work on the original array to create refs to its members) * simulate pass_by_value if EXTR_REFS is not used */ if (!extract_refs) { SEPARATE_ARG_IF_REF(var_array); } zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(var_array), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(var_array), (void **)&entry, &pos) == SUCCESS) { zval final_name; ZVAL_NULL(&final_name); key_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(var_array), &var_name, &var_name_len, &num_key, 0, &pos); var_exists = 0; if (key_type == HASH_KEY_IS_STRING) { var_name_len--; var_exists = zend_hash_exists(EG(active_symbol_table), var_name, var_name_len + 1); } else if (key_type == HASH_KEY_IS_LONG && (extract_type == EXTR_PREFIX_ALL || extract_type == EXTR_PREFIX_INVALID)) { zval num; ZVAL_LONG(&num, num_key); convert_to_string(&num); php_prefix_varname(&final_name, prefix, Z_STRVAL(num), Z_STRLEN(num), 1 TSRMLS_CC); zval_dtor(&num); } else { zend_hash_move_forward_ex(Z_ARRVAL_P(var_array), &pos); continue; } switch (extract_type) { case EXTR_IF_EXISTS: if (!var_exists) break; /* break omitted intentionally */ case EXTR_OVERWRITE: /* GLOBALS protection */ if (var_exists && var_name_len == sizeof("GLOBALS")-1 && !strcmp(var_name, "GLOBALS")) { break; } if (var_exists && var_name_len == sizeof("this")-1 && !strcmp(var_name, "this") && EG(scope) && EG(scope)->name_length != 0) { break; } ZVAL_STRINGL(&final_name, var_name, var_name_len, 1); break; case EXTR_PREFIX_IF_EXISTS: if (var_exists) { php_prefix_varname(&final_name, prefix, var_name, var_name_len, 1 TSRMLS_CC); } break; case EXTR_PREFIX_SAME: if (!var_exists && var_name_len != 0) { ZVAL_STRINGL(&final_name, var_name, var_name_len, 1); } /* break omitted intentionally */ case EXTR_PREFIX_ALL: if (Z_TYPE(final_name) == IS_NULL && var_name_len != 0) { php_prefix_varname(&final_name, prefix, var_name, var_name_len, 1 TSRMLS_CC); } break; case EXTR_PREFIX_INVALID: if (Z_TYPE(final_name) == IS_NULL) { if (!php_valid_var_name(var_name, var_name_len)) { php_prefix_varname(&final_name, prefix, var_name, var_name_len, 1 TSRMLS_CC); } else { ZVAL_STRINGL(&final_name, var_name, var_name_len, 1); } } break; default: if (!var_exists) { ZVAL_STRINGL(&final_name, var_name, var_name_len, 1); } break; } if (Z_TYPE(final_name) != IS_NULL && php_valid_var_name(Z_STRVAL(final_name), Z_STRLEN(final_name))) { if (extract_refs) { zval **orig_var; SEPARATE_ZVAL_TO_MAKE_IS_REF(entry); zval_add_ref(entry); if (zend_hash_find(EG(active_symbol_table), Z_STRVAL(final_name), Z_STRLEN(final_name) + 1, (void **) &orig_var) == SUCCESS) { zval_ptr_dtor(orig_var); *orig_var = *entry; } else { zend_hash_update(EG(active_symbol_table), Z_STRVAL(final_name), Z_STRLEN(final_name) + 1, (void **) entry, sizeof(zval *), NULL); } } else { MAKE_STD_ZVAL(data); *data = **entry; zval_copy_ctor(data); ZEND_SET_SYMBOL_WITH_LENGTH(EG(active_symbol_table), Z_STRVAL(final_name), Z_STRLEN(final_name) + 1, data, 1, 0); } count++; } zval_dtor(&final_name); zend_hash_move_forward_ex(Z_ARRVAL_P(var_array), &pos); } if (!extract_refs) { zval_ptr_dtor(&var_array); } RETURN_LONG(count); } /* }}} */ static void php_compact_var(HashTable *eg_active_symbol_table, zval *return_value, zval *entry TSRMLS_DC) /* {{{ */ { zval **value_ptr, *value, *data; if (Z_TYPE_P(entry) == IS_STRING) { if (zend_hash_find(eg_active_symbol_table, Z_STRVAL_P(entry), Z_STRLEN_P(entry) + 1, (void **)&value_ptr) != FAILURE) { value = *value_ptr; ALLOC_ZVAL(data); MAKE_COPY_ZVAL(&value, data); zend_hash_update(Z_ARRVAL_P(return_value), Z_STRVAL_P(entry), Z_STRLEN_P(entry) + 1, &data, sizeof(zval *), NULL); } } else if (Z_TYPE_P(entry) == IS_ARRAY) { HashPosition pos; if ((Z_ARRVAL_P(entry)->nApplyCount > 1)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); return; } Z_ARRVAL_P(entry)->nApplyCount++; zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(entry), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(entry), (void**)&value_ptr, &pos) == SUCCESS) { value = *value_ptr; php_compact_var(eg_active_symbol_table, return_value, value TSRMLS_CC); zend_hash_move_forward_ex(Z_ARRVAL_P(entry), &pos); } Z_ARRVAL_P(entry)->nApplyCount--; } } /* }}} */ /* {{{ proto array compact(mixed var_names [, mixed ...]) Creates a hash containing variables and their values */ PHP_FUNCTION(compact) { zval ***args = NULL; /* function arguments array */ int num_args, i; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &num_args) == FAILURE) { return; } if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } /* compact() is probably most used with a single array of var_names or multiple string names, rather than a combination of both. So quickly guess a minimum result size based on that */ if (ZEND_NUM_ARGS() == 1 && Z_TYPE_PP(args[0]) == IS_ARRAY) { array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_PP(args[0]))); } else { array_init_size(return_value, ZEND_NUM_ARGS()); } for (i=0; i<ZEND_NUM_ARGS(); i++) { php_compact_var(EG(active_symbol_table), return_value, *args[i] TSRMLS_CC); } if (args) { efree(args); } } /* }}} */ /* {{{ proto array array_fill(int start_key, int num, mixed val) Create an array containing num elements starting with index start_key each initialized to val */ PHP_FUNCTION(array_fill) { zval *val; long start_key, num; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "llz", &start_key, &num, &val) == FAILURE) { return; } if (num < 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number of elements must be positive"); RETURN_FALSE; } /* allocate an array for return */ array_init_size(return_value, num); num--; zval_add_ref(&val); zend_hash_index_update(Z_ARRVAL_P(return_value), start_key, &val, sizeof(zval *), NULL); while (num--) { zval_add_ref(&val); zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &val, sizeof(zval *), NULL); } } /* }}} */ /* {{{ proto array array_fill_keys(array keys, mixed val) Create an array using the elements of the first parameter as keys each initialized to val */ PHP_FUNCTION(array_fill_keys) { zval *keys, *val, **entry; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "az", &keys, &val) == FAILURE) { return; } /* Initialize return array */ array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(keys))); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(keys), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(keys), (void **)&entry, &pos) == SUCCESS) { if (Z_TYPE_PP(entry) == IS_LONG) { zval_add_ref(&val); zend_hash_index_update(Z_ARRVAL_P(return_value), Z_LVAL_PP(entry), &val, sizeof(zval *), NULL); } else { zval key, *key_ptr = *entry; if (Z_TYPE_PP(entry) != IS_STRING) { key = **entry; zval_copy_ctor(&key); convert_to_string(&key); key_ptr = &key; } zval_add_ref(&val); zend_symtable_update(Z_ARRVAL_P(return_value), Z_STRVAL_P(key_ptr), Z_STRLEN_P(key_ptr) + 1, &val, sizeof(zval *), NULL); if (key_ptr != *entry) { zval_dtor(&key); } } zend_hash_move_forward_ex(Z_ARRVAL_P(keys), &pos); } } /* }}} */ /* {{{ proto array range(mixed low, mixed high[, int step]) Create an array containing the range of integers or characters from low to high (inclusive) */ PHP_FUNCTION(range) { zval *zlow, *zhigh, *zstep = NULL; int err = 0, is_step_double = 0; double step = 1.0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z/z/|z/", &zlow, &zhigh, &zstep) == FAILURE) { RETURN_FALSE; } if (zstep) { if (Z_TYPE_P(zstep) == IS_DOUBLE || (Z_TYPE_P(zstep) == IS_STRING && is_numeric_string(Z_STRVAL_P(zstep), Z_STRLEN_P(zstep), NULL, NULL, 0) == IS_DOUBLE) ) { is_step_double = 1; } convert_to_double_ex(&zstep); step = Z_DVAL_P(zstep); /* We only want positive step values. */ if (step < 0.0) { step *= -1; } } /* Initialize the return_value as an array. */ array_init(return_value); /* If the range is given as strings, generate an array of characters. */ if (Z_TYPE_P(zlow) == IS_STRING && Z_TYPE_P(zhigh) == IS_STRING && Z_STRLEN_P(zlow) >= 1 && Z_STRLEN_P(zhigh) >= 1) { int type1, type2; unsigned char *low, *high; long lstep = (long) step; type1 = is_numeric_string(Z_STRVAL_P(zlow), Z_STRLEN_P(zlow), NULL, NULL, 0); type2 = is_numeric_string(Z_STRVAL_P(zhigh), Z_STRLEN_P(zhigh), NULL, NULL, 0); if (type1 == IS_DOUBLE || type2 == IS_DOUBLE || is_step_double) { goto double_str; } else if (type1 == IS_LONG || type2 == IS_LONG) { goto long_str; } convert_to_string(zlow); convert_to_string(zhigh); low = (unsigned char *)Z_STRVAL_P(zlow); high = (unsigned char *)Z_STRVAL_P(zhigh); if (*low > *high) { /* Negative Steps */ unsigned char ch = *low; if (lstep <= 0) { err = 1; goto err; } for (; ch >= *high; ch -= (unsigned int)lstep) { add_next_index_stringl(return_value, (const char *)&ch, 1, 1); if (((signed int)ch - lstep) < 0) { break; } } } else if (*high > *low) { /* Positive Steps */ unsigned char ch = *low; if (lstep <= 0) { err = 1; goto err; } for (; ch <= *high; ch += (unsigned int)lstep) { add_next_index_stringl(return_value, (const char *)&ch, 1, 1); if (((signed int)ch + lstep) > 255) { break; } } } else { add_next_index_stringl(return_value, (const char *)low, 1, 1); } } else if (Z_TYPE_P(zlow) == IS_DOUBLE || Z_TYPE_P(zhigh) == IS_DOUBLE || is_step_double) { double low, high, value; long i; double_str: convert_to_double(zlow); convert_to_double(zhigh); low = Z_DVAL_P(zlow); high = Z_DVAL_P(zhigh); i = 0; if (low > high) { /* Negative steps */ if (low - high < step || step <= 0) { err = 1; goto err; } for (value = low; value >= (high - DOUBLE_DRIFT_FIX); value = low - (++i * step)) { add_next_index_double(return_value, value); } } else if (high > low) { /* Positive steps */ if (high - low < step || step <= 0) { err = 1; goto err; } for (value = low; value <= (high + DOUBLE_DRIFT_FIX); value = low + (++i * step)) { add_next_index_double(return_value, value); } } else { add_next_index_double(return_value, low); } } else { double low, high; long lstep; long_str: convert_to_double(zlow); convert_to_double(zhigh); low = Z_DVAL_P(zlow); high = Z_DVAL_P(zhigh); lstep = (long) step; if (low > high) { /* Negative steps */ if (low - high < lstep || lstep <= 0) { err = 1; goto err; } for (; low >= high; low -= lstep) { add_next_index_long(return_value, (long)low); } } else if (high > low) { /* Positive steps */ if (high - low < lstep || lstep <= 0) { err = 1; goto err; } for (; low <= high; low += lstep) { add_next_index_long(return_value, (long)low); } } else { add_next_index_long(return_value, (long)low); } } err: if (err) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "step exceeds the specified range"); zval_dtor(return_value); RETURN_FALSE; } } /* }}} */ static void php_array_data_shuffle(zval *array TSRMLS_DC) /* {{{ */ { Bucket **elems, *temp; HashTable *hash; int j, n_elems, rnd_idx, n_left; n_elems = zend_hash_num_elements(Z_ARRVAL_P(array)); if (n_elems < 1) { return; } elems = (Bucket **)safe_emalloc(n_elems, sizeof(Bucket *), 0); hash = Z_ARRVAL_P(array); n_left = n_elems; for (j = 0, temp = hash->pListHead; temp; temp = temp->pListNext) elems[j++] = temp; while (--n_left) { rnd_idx = php_rand(TSRMLS_C); RAND_RANGE(rnd_idx, 0, n_left, PHP_RAND_MAX); if (rnd_idx != n_left) { temp = elems[n_left]; elems[n_left] = elems[rnd_idx]; elems[rnd_idx] = temp; } } HANDLE_BLOCK_INTERRUPTIONS(); hash->pListHead = elems[0]; hash->pListTail = NULL; hash->pInternalPointer = hash->pListHead; for (j = 0; j < n_elems; j++) { if (hash->pListTail) { hash->pListTail->pListNext = elems[j]; } elems[j]->pListLast = hash->pListTail; elems[j]->pListNext = NULL; hash->pListTail = elems[j]; } temp = hash->pListHead; j = 0; while (temp != NULL) { temp->nKeyLength = 0; temp->h = j++; temp = temp->pListNext; } hash->nNextFreeElement = n_elems; zend_hash_rehash(hash); HANDLE_UNBLOCK_INTERRUPTIONS(); efree(elems); } /* }}} */ /* {{{ proto bool shuffle(array array_arg) Randomly shuffle the contents of an array */ PHP_FUNCTION(shuffle) { zval *array; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) { RETURN_FALSE; } php_array_data_shuffle(array TSRMLS_CC); RETURN_TRUE; } /* }}} */ PHPAPI HashTable* php_splice(HashTable *in_hash, int offset, int length, zval ***list, int list_count, HashTable **removed) /* {{{ */ { HashTable *out_hash = NULL; /* Output hashtable */ int num_in, /* Number of entries in the input hashtable */ pos, /* Current position in the hashtable */ i; /* Loop counter */ Bucket *p; /* Pointer to hash bucket */ zval *entry; /* Hash entry */ /* If input hash doesn't exist, we have nothing to do */ if (!in_hash) { return NULL; } /* Get number of entries in the input hash */ num_in = zend_hash_num_elements(in_hash); /* Clamp the offset.. */ if (offset > num_in) { offset = num_in; } else if (offset < 0 && (offset = (num_in + offset)) < 0) { offset = 0; } /* ..and the length */ if (length < 0) { length = num_in - offset + length; } else if (((unsigned)offset + (unsigned)length) > (unsigned)num_in) { length = num_in - offset; } /* Create and initialize output hash */ ALLOC_HASHTABLE(out_hash); zend_hash_init(out_hash, (length > 0 ? num_in - length : 0) + list_count, NULL, ZVAL_PTR_DTOR, 0); /* Start at the beginning of the input hash and copy entries to output hash until offset is reached */ for (pos = 0, p = in_hash->pListHead; pos < offset && p ; pos++, p = p->pListNext) { /* Get entry and increase reference count */ entry = *((zval **)p->pData); Z_ADDREF_P(entry); /* Update output hash depending on key type */ if (p->nKeyLength == 0) { zend_hash_next_index_insert(out_hash, &entry, sizeof(zval *), NULL); } else { zend_hash_quick_update(out_hash, p->arKey, p->nKeyLength, p->h, &entry, sizeof(zval *), NULL); } } /* If hash for removed entries exists, go until offset+length and copy the entries to it */ if (removed != NULL) { for ( ; pos < offset + length && p; pos++, p = p->pListNext) { entry = *((zval **)p->pData); Z_ADDREF_P(entry); if (p->nKeyLength == 0) { zend_hash_next_index_insert(*removed, &entry, sizeof(zval *), NULL); } else { zend_hash_quick_update(*removed, p->arKey, p->nKeyLength, p->h, &entry, sizeof(zval *), NULL); } } } else { /* otherwise just skip those entries */ for ( ; pos < offset + length && p; pos++, p = p->pListNext); } /* If there are entries to insert.. */ if (list != NULL) { /* ..for each one, create a new zval, copy entry into it and copy it into the output hash */ for (i = 0; i < list_count; i++) { entry = *list[i]; Z_ADDREF_P(entry); zend_hash_next_index_insert(out_hash, &entry, sizeof(zval *), NULL); } } /* Copy the remaining input hash entries to the output hash */ for ( ; p ; p = p->pListNext) { entry = *((zval **)p->pData); Z_ADDREF_P(entry); if (p->nKeyLength == 0) { zend_hash_next_index_insert(out_hash, &entry, sizeof(zval *), NULL); } else { zend_hash_quick_update(out_hash, p->arKey, p->nKeyLength, p->h, &entry, sizeof(zval *), NULL); } } zend_hash_internal_pointer_reset(out_hash); return out_hash; } /* }}} */ /* {{{ proto int array_push(array stack, mixed var [, mixed ...]) Pushes elements onto the end of the array */ PHP_FUNCTION(array_push) { zval ***args, /* Function arguments array */ *stack, /* Input array */ *new_var; /* Variable to be pushed */ int i, /* Loop counter */ argc; /* Number of function arguments */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a+", &stack, &args, &argc) == FAILURE) { return; } /* For each subsequent argument, make it a reference, increase refcount, and add it to the end of the array */ for (i = 0; i < argc; i++) { new_var = *args[i]; Z_ADDREF_P(new_var); if (zend_hash_next_index_insert(Z_ARRVAL_P(stack), &new_var, sizeof(zval *), NULL) == FAILURE) { Z_DELREF_P(new_var); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot add element to the array as the next element is already occupied"); efree(args); RETURN_FALSE; } } /* Clean up and return the number of values in the stack */ efree(args); RETVAL_LONG(zend_hash_num_elements(Z_ARRVAL_P(stack))); } /* }}} */ /* {{{ void _phpi_pop(INTERNAL_FUNCTION_PARAMETERS, int off_the_end) */ static void _phpi_pop(INTERNAL_FUNCTION_PARAMETERS, int off_the_end) { zval *stack, /* Input stack */ **val; /* Value to be popped */ char *key = NULL; uint key_len = 0; ulong index; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &stack) == FAILURE) { return; } if (zend_hash_num_elements(Z_ARRVAL_P(stack)) == 0) { return; } /* Get the first or last value and copy it into the return value */ if (off_the_end) { zend_hash_internal_pointer_end(Z_ARRVAL_P(stack)); } else { zend_hash_internal_pointer_reset(Z_ARRVAL_P(stack)); } zend_hash_get_current_data(Z_ARRVAL_P(stack), (void **)&val); RETVAL_ZVAL(*val, 1, 0); /* Delete the first or last value */ zend_hash_get_current_key_ex(Z_ARRVAL_P(stack), &key, &key_len, &index, 0, NULL); if (key && Z_ARRVAL_P(stack) == &EG(symbol_table)) { zend_delete_global_variable(key, key_len - 1 TSRMLS_CC); } else { zend_hash_del_key_or_index(Z_ARRVAL_P(stack), key, key_len, index, (key) ? HASH_DEL_KEY : HASH_DEL_INDEX); } /* If we did a shift... re-index like it did before */ if (!off_the_end) { unsigned int k = 0; int should_rehash = 0; Bucket *p = Z_ARRVAL_P(stack)->pListHead; while (p != NULL) { if (p->nKeyLength == 0) { if (p->h != k) { p->h = k++; should_rehash = 1; } else { k++; } } p = p->pListNext; } Z_ARRVAL_P(stack)->nNextFreeElement = k; if (should_rehash) { zend_hash_rehash(Z_ARRVAL_P(stack)); } } else if (!key_len && index >= Z_ARRVAL_P(stack)->nNextFreeElement - 1) { Z_ARRVAL_P(stack)->nNextFreeElement = Z_ARRVAL_P(stack)->nNextFreeElement - 1; } zend_hash_internal_pointer_reset(Z_ARRVAL_P(stack)); } /* }}} */ /* {{{ proto mixed array_pop(array stack) Pops an element off the end of the array */ PHP_FUNCTION(array_pop) { _phpi_pop(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto mixed array_shift(array stack) Pops an element off the beginning of the array */ PHP_FUNCTION(array_shift) { _phpi_pop(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto int array_unshift(array stack, mixed var [, mixed ...]) Pushes elements onto the beginning of the array */ PHP_FUNCTION(array_unshift) { zval ***args, /* Function arguments array */ *stack; /* Input stack */ HashTable *new_hash; /* New hashtable for the stack */ HashTable old_hash; int argc; /* Number of function arguments */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a+", &stack, &args, &argc) == FAILURE) { return; } /* Use splice to insert the elements at the beginning. Destroy old * hashtable and replace it with new one */ new_hash = php_splice(Z_ARRVAL_P(stack), 0, 0, &args[0], argc, NULL); old_hash = *Z_ARRVAL_P(stack); if (Z_ARRVAL_P(stack) == &EG(symbol_table)) { zend_reset_all_cv(&EG(symbol_table) TSRMLS_CC); } *Z_ARRVAL_P(stack) = *new_hash; FREE_HASHTABLE(new_hash); zend_hash_destroy(&old_hash); /* Clean up and return the number of elements in the stack */ efree(args); RETVAL_LONG(zend_hash_num_elements(Z_ARRVAL_P(stack))); } /* }}} */ /* {{{ proto array array_splice(array input, int offset [, int length [, array replacement]]) Removes the elements designated by offset and length and replace them with supplied array */ PHP_FUNCTION(array_splice) { zval *array, /* Input array */ *repl_array = NULL, /* Replacement array */ ***repl = NULL; /* Replacement elements */ HashTable *new_hash = NULL, /* Output array's hash */ **rem_hash = NULL; /* Removed elements' hash */ HashTable old_hash; Bucket *p; /* Bucket used for traversing hash */ long i, offset, length = 0, repl_num = 0; /* Number of replacement elements */ int num_in; /* Number of elements in the input array */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "al|lz/", &array, &offset, &length, &repl_array) == FAILURE) { return; } num_in = zend_hash_num_elements(Z_ARRVAL_P(array)); if (ZEND_NUM_ARGS() < 3) { length = num_in; } if (ZEND_NUM_ARGS() == 4) { /* Make sure the last argument, if passed, is an array */ convert_to_array(repl_array); /* Create the array of replacement elements */ repl_num = zend_hash_num_elements(Z_ARRVAL_P(repl_array)); repl = (zval ***)safe_emalloc(repl_num, sizeof(zval **), 0); for (p = Z_ARRVAL_P(repl_array)->pListHead, i = 0; p; p = p->pListNext, i++) { repl[i] = ((zval **)p->pData); } } /* Don't create the array of removed elements if it's not going * to be used; e.g. only removing and/or replacing elements */ if (return_value_used) { int size = length; /* Clamp the offset.. */ if (offset > num_in) { offset = num_in; } else if (offset < 0 && (offset = (num_in + offset)) < 0) { offset = 0; } /* ..and the length */ if (length < 0) { size = num_in - offset + length; } else if (((unsigned long) offset + (unsigned long) length) > (unsigned) num_in) { size = num_in - offset; } /* Initialize return value */ array_init_size(return_value, size > 0 ? size : 0); rem_hash = &Z_ARRVAL_P(return_value); } /* Perform splice */ new_hash = php_splice(Z_ARRVAL_P(array), offset, length, repl, repl_num, rem_hash); /* Replace input array's hashtable with the new one */ old_hash = *Z_ARRVAL_P(array); if (Z_ARRVAL_P(array) == &EG(symbol_table)) { zend_reset_all_cv(&EG(symbol_table) TSRMLS_CC); } *Z_ARRVAL_P(array) = *new_hash; FREE_HASHTABLE(new_hash); zend_hash_destroy(&old_hash); /* Clean up */ if (ZEND_NUM_ARGS() == 4) { efree(repl); } } /* }}} */ /* {{{ proto array array_slice(array input, int offset [, int length [, bool preserve_keys]]) Returns elements specified by offset and length */ PHP_FUNCTION(array_slice) { zval *input, /* Input array */ **z_length = NULL, /* How many elements to get */ **entry; /* An array entry */ long offset, /* Offset to get elements from */ length = 0; zend_bool preserve_keys = 0; /* Whether to preserve keys while copying to the new array or not */ int num_in, /* Number of elements in the input array */ pos; /* Current position in the array */ char *string_key; uint string_key_len; ulong num_key; HashPosition hpos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "al|Zb", &input, &offset, &z_length, &preserve_keys) == FAILURE) { return; } /* Get number of entries in the input hash */ num_in = zend_hash_num_elements(Z_ARRVAL_P(input)); /* We want all entries from offset to the end if length is not passed or is null */ if (ZEND_NUM_ARGS() < 3 || Z_TYPE_PP(z_length) == IS_NULL) { length = num_in; } else { convert_to_long_ex(z_length); length = Z_LVAL_PP(z_length); } /* Clamp the offset.. */ if (offset > num_in) { array_init(return_value); return; } else if (offset < 0 && (offset = (num_in + offset)) < 0) { offset = 0; } /* ..and the length */ if (length < 0) { length = num_in - offset + length; } else if (((unsigned long) offset + (unsigned long) length) > (unsigned) num_in) { length = num_in - offset; } /* Initialize returned array */ array_init_size(return_value, length > 0 ? length : 0); if (length <= 0) { return; } /* Start at the beginning and go until we hit offset */ pos = 0; zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &hpos); while (pos < offset && zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &hpos) == SUCCESS) { pos++; zend_hash_move_forward_ex(Z_ARRVAL_P(input), &hpos); } /* Copy elements from input array to the one that's returned */ while (pos < offset + length && zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &hpos) == SUCCESS) { zval_add_ref(entry); switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(input), &string_key, &string_key_len, &num_key, 0, &hpos)) { case HASH_KEY_IS_STRING: zend_hash_update(Z_ARRVAL_P(return_value), string_key, string_key_len, entry, sizeof(zval *), NULL); break; case HASH_KEY_IS_LONG: if (preserve_keys) { zend_hash_index_update(Z_ARRVAL_P(return_value), num_key, entry, sizeof(zval *), NULL); } else { zend_hash_next_index_insert(Z_ARRVAL_P(return_value), entry, sizeof(zval *), NULL); } break; } pos++; zend_hash_move_forward_ex(Z_ARRVAL_P(input), &hpos); } } /* }}} */ PHPAPI int php_array_merge(HashTable *dest, HashTable *src, int recursive TSRMLS_DC) /* {{{ */ { zval **src_entry, **dest_entry; char *string_key; uint string_key_len; ulong num_key; HashPosition pos; zend_hash_internal_pointer_reset_ex(src, &pos); while (zend_hash_get_current_data_ex(src, (void **)&src_entry, &pos) == SUCCESS) { switch (zend_hash_get_current_key_ex(src, &string_key, &string_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_STRING: if (recursive && zend_hash_find(dest, string_key, string_key_len, (void **)&dest_entry) == SUCCESS) { HashTable *thash = Z_TYPE_PP(dest_entry) == IS_ARRAY ? Z_ARRVAL_PP(dest_entry) : NULL; if ((thash && thash->nApplyCount > 1) || (*src_entry == *dest_entry && Z_ISREF_PP(dest_entry) && (Z_REFCOUNT_PP(dest_entry) % 2))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); return 0; } SEPARATE_ZVAL(dest_entry); SEPARATE_ZVAL(src_entry); if (Z_TYPE_PP(dest_entry) == IS_NULL) { convert_to_array_ex(dest_entry); add_next_index_null(*dest_entry); } else { convert_to_array_ex(dest_entry); } if (Z_TYPE_PP(src_entry) == IS_NULL) { convert_to_array_ex(src_entry); add_next_index_null(*src_entry); } else { convert_to_array_ex(src_entry); } if (thash) { thash->nApplyCount++; } if (!php_array_merge(Z_ARRVAL_PP(dest_entry), Z_ARRVAL_PP(src_entry), recursive TSRMLS_CC)) { if (thash) { thash->nApplyCount--; } return 0; } if (thash) { thash->nApplyCount--; } } else { Z_ADDREF_PP(src_entry); zend_hash_update(dest, string_key, string_key_len, src_entry, sizeof(zval *), NULL); } break; case HASH_KEY_IS_LONG: Z_ADDREF_PP(src_entry); zend_hash_next_index_insert(dest, src_entry, sizeof(zval *), NULL); break; } zend_hash_move_forward_ex(src, &pos); } return 1; } /* }}} */ PHPAPI int php_array_replace_recursive(HashTable *dest, HashTable *src TSRMLS_DC) /* {{{ */ { zval **src_entry, **dest_entry; char *string_key; uint string_key_len; ulong num_key; HashPosition pos; for (zend_hash_internal_pointer_reset_ex(src, &pos); zend_hash_get_current_data_ex(src, (void **)&src_entry, &pos) == SUCCESS; zend_hash_move_forward_ex(src, &pos)) { switch (zend_hash_get_current_key_ex(src, &string_key, &string_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_STRING: if (Z_TYPE_PP(src_entry) != IS_ARRAY || zend_hash_find(dest, string_key, string_key_len, (void **)&dest_entry) == FAILURE || Z_TYPE_PP(dest_entry) != IS_ARRAY) { Z_ADDREF_PP(src_entry); zend_hash_update(dest, string_key, string_key_len, src_entry, sizeof(zval *), NULL); continue; } break; case HASH_KEY_IS_LONG: if (Z_TYPE_PP(src_entry) != IS_ARRAY || zend_hash_index_find(dest, num_key, (void **)&dest_entry) == FAILURE || Z_TYPE_PP(dest_entry) != IS_ARRAY) { Z_ADDREF_PP(src_entry); zend_hash_index_update(dest, num_key, src_entry, sizeof(zval *), NULL); continue; } break; } if (Z_ARRVAL_PP(dest_entry)->nApplyCount > 1 || Z_ARRVAL_PP(src_entry)->nApplyCount > 1 || (*src_entry == *dest_entry && Z_ISREF_PP(dest_entry) && (Z_REFCOUNT_PP(dest_entry) % 2))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); return 0; } SEPARATE_ZVAL(dest_entry); Z_ARRVAL_PP(dest_entry)->nApplyCount++; Z_ARRVAL_PP(src_entry)->nApplyCount++; if (!php_array_replace_recursive(Z_ARRVAL_PP(dest_entry), Z_ARRVAL_PP(src_entry) TSRMLS_CC)) { Z_ARRVAL_PP(dest_entry)->nApplyCount--; Z_ARRVAL_PP(src_entry)->nApplyCount--; return 0; } Z_ARRVAL_PP(dest_entry)->nApplyCount--; Z_ARRVAL_PP(src_entry)->nApplyCount--; } return 1; } /* }}} */ static void php_array_merge_or_replace_wrapper(INTERNAL_FUNCTION_PARAMETERS, int recursive, int replace) /* {{{ */ { zval ***args = NULL; int argc, i, init_size = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &argc) == FAILURE) { return; } for (i = 0; i < argc; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is not an array", i + 1); efree(args); RETURN_NULL(); } else { int num = zend_hash_num_elements(Z_ARRVAL_PP(args[i])); if (num > init_size) { init_size = num; } } } array_init_size(return_value, init_size); for (i = 0; i < argc; i++) { SEPARATE_ZVAL(args[i]); if (!replace) { php_array_merge(Z_ARRVAL_P(return_value), Z_ARRVAL_PP(args[i]), recursive TSRMLS_CC); } else if (recursive && i > 0) { /* First array will be copied directly instead */ php_array_replace_recursive(Z_ARRVAL_P(return_value), Z_ARRVAL_PP(args[i]) TSRMLS_CC); } else { zend_hash_merge(Z_ARRVAL_P(return_value), Z_ARRVAL_PP(args[i]), (copy_ctor_func_t) zval_add_ref, NULL, sizeof(zval *), 1); } } efree(args); } /* }}} */ /* {{{ proto array array_merge(array arr1, array arr2 [, array ...]) Merges elements from passed arrays into one array */ PHP_FUNCTION(array_merge) { php_array_merge_or_replace_wrapper(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0, 0); } /* }}} */ /* {{{ proto array array_merge_recursive(array arr1, array arr2 [, array ...]) Recursively merges elements from passed arrays into one array */ PHP_FUNCTION(array_merge_recursive) { php_array_merge_or_replace_wrapper(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1, 0); } /* }}} */ /* {{{ proto array array_replace(array arr1, array arr2 [, array ...]) Replaces elements from passed arrays into one array */ PHP_FUNCTION(array_replace) { php_array_merge_or_replace_wrapper(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0, 1); } /* }}} */ /* {{{ proto array array_replace_recursive(array arr1, array arr2 [, array ...]) Recursively replaces elements from passed arrays into one array */ PHP_FUNCTION(array_replace_recursive) { php_array_merge_or_replace_wrapper(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1, 1); } /* }}} */ /* {{{ proto array array_keys(array input [, mixed search_value[, bool strict]]) Return just the keys from the input array, optionally only for the specified search_value */ PHP_FUNCTION(array_keys) { zval *input, /* Input array */ *search_value = NULL, /* Value to search for */ **entry, /* An entry in the input array */ res, /* Result of comparison */ *new_val; /* New value */ int add_key; /* Flag to indicate whether a key should be added */ char *string_key; /* String key */ uint string_key_len; ulong num_key; /* Numeric key */ zend_bool strict = 0; /* do strict comparison */ HashPosition pos; int (*is_equal_func)(zval *, zval *, zval * TSRMLS_DC) = is_equal_function; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|zb", &input, &search_value, &strict) == FAILURE) { return; } if (strict) { is_equal_func = is_identical_function; } /* Initialize return array */ if (search_value != NULL) { array_init(return_value); } else { array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(input))); } add_key = 1; /* Go through input array and add keys to the return array */ zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &pos) == SUCCESS) { if (search_value != NULL) { is_equal_func(&res, search_value, *entry TSRMLS_CC); add_key = zval_is_true(&res); } if (add_key) { MAKE_STD_ZVAL(new_val); switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(input), &string_key, &string_key_len, &num_key, 1, &pos)) { case HASH_KEY_IS_STRING: ZVAL_STRINGL(new_val, string_key, string_key_len - 1, 0); zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &new_val, sizeof(zval *), NULL); break; case HASH_KEY_IS_LONG: Z_TYPE_P(new_val) = IS_LONG; Z_LVAL_P(new_val) = num_key; zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &new_val, sizeof(zval *), NULL); break; } } zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos); } } /* }}} */ /* {{{ proto array array_values(array input) Return just the values from the input array */ PHP_FUNCTION(array_values) { zval *input, /* Input array */ **entry; /* An entry in the input array */ HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &input) == FAILURE) { return; } /* Initialize return array */ array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(input))); /* Go through input array and add values to the return array */ zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &pos) == SUCCESS) { zval_add_ref(entry); zend_hash_next_index_insert(Z_ARRVAL_P(return_value), entry, sizeof(zval *), NULL); zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos); } } /* }}} */ /* {{{ proto array array_count_values(array input) Return the value as key and the frequency of that value in input as value */ PHP_FUNCTION(array_count_values) { zval *input, /* Input array */ **entry, /* An entry in the input array */ **tmp; HashTable *myht; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &input) == FAILURE) { return; } /* Initialize return array */ array_init(return_value); /* Go through input array and add values to the return array */ myht = Z_ARRVAL_P(input); zend_hash_internal_pointer_reset_ex(myht, &pos); while (zend_hash_get_current_data_ex(myht, (void **)&entry, &pos) == SUCCESS) { if (Z_TYPE_PP(entry) == IS_LONG) { if (zend_hash_index_find(Z_ARRVAL_P(return_value), Z_LVAL_PP(entry), (void **)&tmp) == FAILURE) { zval *data; MAKE_STD_ZVAL(data); ZVAL_LONG(data, 1); zend_hash_index_update(Z_ARRVAL_P(return_value), Z_LVAL_PP(entry), &data, sizeof(data), NULL); } else { Z_LVAL_PP(tmp)++; } } else if (Z_TYPE_PP(entry) == IS_STRING) { if (zend_symtable_find(Z_ARRVAL_P(return_value), Z_STRVAL_PP(entry), Z_STRLEN_PP(entry) + 1, (void**)&tmp) == FAILURE) { zval *data; MAKE_STD_ZVAL(data); ZVAL_LONG(data, 1); zend_symtable_update(Z_ARRVAL_P(return_value), Z_STRVAL_PP(entry), Z_STRLEN_PP(entry) + 1, &data, sizeof(data), NULL); } else { Z_LVAL_PP(tmp)++; } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can only count STRING and INTEGER values!"); } zend_hash_move_forward_ex(myht, &pos); } } /* }}} */ /* {{{ proto array array_reverse(array input [, bool preserve keys]) Return input as a new array with the order of the entries reversed */ PHP_FUNCTION(array_reverse) { zval *input, /* Input array */ **entry; /* An entry in the input array */ char *string_key; uint string_key_len; ulong num_key; zend_bool preserve_keys = 0; /* whether to preserve keys */ HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|b", &input, &preserve_keys) == FAILURE) { return; } /* Initialize return array */ array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(input))); zend_hash_internal_pointer_end_ex(Z_ARRVAL_P(input), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &pos) == SUCCESS) { zval_add_ref(entry); switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(input), &string_key, &string_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_STRING: zend_hash_update(Z_ARRVAL_P(return_value), string_key, string_key_len, entry, sizeof(zval *), NULL); break; case HASH_KEY_IS_LONG: if (preserve_keys) { zend_hash_index_update(Z_ARRVAL_P(return_value), num_key, entry, sizeof(zval *), NULL); } else { zend_hash_next_index_insert(Z_ARRVAL_P(return_value), entry, sizeof(zval *), NULL); } break; } zend_hash_move_backwards_ex(Z_ARRVAL_P(input), &pos); } } /* }}} */ /* {{{ proto array array_pad(array input, int pad_size, mixed pad_value) Returns a copy of input array padded with pad_value to size pad_size */ PHP_FUNCTION(array_pad) { zval *input; /* Input array */ zval *pad_value; /* Padding value obviously */ zval ***pads; /* Array to pass to splice */ HashTable *new_hash;/* Return value from splice */ HashTable old_hash; long pad_size; /* Size to pad to */ long pad_size_abs; /* Absolute value of pad_size */ int input_size; /* Size of the input array */ int num_pads; /* How many pads do we need */ int do_pad; /* Whether we should do padding at all */ int i; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "alz", &input, &pad_size, &pad_value) == FAILURE) { return; } /* Do some initial calculations */ input_size = zend_hash_num_elements(Z_ARRVAL_P(input)); pad_size_abs = abs(pad_size); if (pad_size_abs < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You may only pad up to 1048576 elements at a time"); zval_dtor(return_value); RETURN_FALSE; } do_pad = (input_size >= pad_size_abs) ? 0 : 1; /* Copy the original array */ RETVAL_ZVAL(input, 1, 0); /* If no need to pad, no need to continue */ if (!do_pad) { return; } /* Populate the pads array */ num_pads = pad_size_abs - input_size; if (num_pads > 1048576) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You may only pad up to 1048576 elements at a time"); zval_dtor(return_value); RETURN_FALSE; } pads = (zval ***)safe_emalloc(num_pads, sizeof(zval **), 0); for (i = 0; i < num_pads; i++) { pads[i] = &pad_value; } /* Pad on the right or on the left */ if (pad_size > 0) { new_hash = php_splice(Z_ARRVAL_P(return_value), input_size, 0, pads, num_pads, NULL); } else { new_hash = php_splice(Z_ARRVAL_P(return_value), 0, 0, pads, num_pads, NULL); } /* Copy the result hash into return value */ old_hash = *Z_ARRVAL_P(return_value); if (Z_ARRVAL_P(return_value) == &EG(symbol_table)) { zend_reset_all_cv(&EG(symbol_table) TSRMLS_CC); } *Z_ARRVAL_P(return_value) = *new_hash; FREE_HASHTABLE(new_hash); zend_hash_destroy(&old_hash); /* Clean up */ efree(pads); } /* }}} */ /* {{{ proto array array_flip(array input) Return array with key <-> value flipped */ PHP_FUNCTION(array_flip) { zval *array, **entry, *data; char *string_key; uint str_key_len; ulong num_key; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) { return; } array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(array))); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(array), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(array), (void **)&entry, &pos) == SUCCESS) { MAKE_STD_ZVAL(data); switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(array), &string_key, &str_key_len, &num_key, 1, &pos)) { case HASH_KEY_IS_STRING: ZVAL_STRINGL(data, string_key, str_key_len - 1, 0); break; case HASH_KEY_IS_LONG: Z_TYPE_P(data) = IS_LONG; Z_LVAL_P(data) = num_key; break; } if (Z_TYPE_PP(entry) == IS_LONG) { zend_hash_index_update(Z_ARRVAL_P(return_value), Z_LVAL_PP(entry), &data, sizeof(data), NULL); } else if (Z_TYPE_PP(entry) == IS_STRING) { zend_symtable_update(Z_ARRVAL_P(return_value), Z_STRVAL_PP(entry), Z_STRLEN_PP(entry) + 1, &data, sizeof(data), NULL); } else { zval_ptr_dtor(&data); /* will free also zval structure */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can only flip STRING and INTEGER values!"); } zend_hash_move_forward_ex(Z_ARRVAL_P(array), &pos); } } /* }}} */ /* {{{ proto array array_change_key_case(array input [, int case=CASE_LOWER]) Retuns an array with all string keys lowercased [or uppercased] */ PHP_FUNCTION(array_change_key_case) { zval *array, **entry; char *string_key; char *new_key; uint str_key_len; ulong num_key; long change_to_upper=0; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &change_to_upper) == FAILURE) { return; } array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(array))); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(array), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(array), (void **)&entry, &pos) == SUCCESS) { zval_add_ref(entry); switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(array), &string_key, &str_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_LONG: zend_hash_index_update(Z_ARRVAL_P(return_value), num_key, entry, sizeof(entry), NULL); break; case HASH_KEY_IS_STRING: new_key = estrndup(string_key, str_key_len - 1); if (change_to_upper) { php_strtoupper(new_key, str_key_len - 1); } else { php_strtolower(new_key, str_key_len - 1); } zend_hash_update(Z_ARRVAL_P(return_value), new_key, str_key_len, entry, sizeof(entry), NULL); efree(new_key); break; } zend_hash_move_forward_ex(Z_ARRVAL_P(array), &pos); } } /* }}} */ /* {{{ proto array array_unique(array input [, int sort_flags]) Removes duplicate values from array */ PHP_FUNCTION(array_unique) { zval *array, *tmp; Bucket *p; struct bucketindex { Bucket *b; unsigned int i; }; struct bucketindex *arTmp, *cmpdata, *lastkept; unsigned int i; long sort_type = PHP_SORT_STRING; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { return; } php_set_compare_func(sort_type TSRMLS_CC); array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(array))); zend_hash_copy(Z_ARRVAL_P(return_value), Z_ARRVAL_P(array), (copy_ctor_func_t) zval_add_ref, (void *)&tmp, sizeof(zval*)); if (Z_ARRVAL_P(array)->nNumOfElements <= 1) { /* nothing to do */ return; } /* create and sort array with pointers to the target_hash buckets */ arTmp = (struct bucketindex *) pemalloc((Z_ARRVAL_P(array)->nNumOfElements + 1) * sizeof(struct bucketindex), Z_ARRVAL_P(array)->persistent); if (!arTmp) { zval_dtor(return_value); RETURN_FALSE; } for (i = 0, p = Z_ARRVAL_P(array)->pListHead; p; i++, p = p->pListNext) { arTmp[i].b = p; arTmp[i].i = i; } arTmp[i].b = NULL; zend_qsort((void *) arTmp, i, sizeof(struct bucketindex), php_array_data_compare TSRMLS_CC); /* go through the sorted array and delete duplicates from the copy */ lastkept = arTmp; for (cmpdata = arTmp + 1; cmpdata->b; cmpdata++) { if (php_array_data_compare(lastkept, cmpdata TSRMLS_CC)) { lastkept = cmpdata; } else { if (lastkept->i > cmpdata->i) { p = lastkept->b; lastkept = cmpdata; } else { p = cmpdata->b; } if (p->nKeyLength == 0) { zend_hash_index_del(Z_ARRVAL_P(return_value), p->h); } else { if (Z_ARRVAL_P(return_value) == &EG(symbol_table)) { zend_delete_global_variable(p->arKey, p->nKeyLength - 1 TSRMLS_CC); } else { zend_hash_quick_del(Z_ARRVAL_P(return_value), p->arKey, p->nKeyLength, p->h); } } } } pefree(arTmp, Z_ARRVAL_P(array)->persistent); } /* }}} */ static int zval_compare(zval **a, zval **b TSRMLS_DC) /* {{{ */ { zval result; zval *first; zval *second; first = *((zval **) a); second = *((zval **) b); if (string_compare_function(&result, first, second TSRMLS_CC) == FAILURE) { return 0; } if (Z_TYPE(result) == IS_DOUBLE) { if (Z_DVAL(result) < 0) { return -1; } else if (Z_DVAL(result) > 0) { return 1; } else { return 0; } } convert_to_long(&result); if (Z_LVAL(result) < 0) { return -1; } else if (Z_LVAL(result) > 0) { return 1; } return 0; } /* }}} */ static int zval_user_compare(zval **a, zval **b TSRMLS_DC) /* {{{ */ { zval **args[2]; zval *retval_ptr; args[0] = (zval **) a; args[1] = (zval **) b; BG(user_compare_fci).param_count = 2; BG(user_compare_fci).params = args; BG(user_compare_fci).retval_ptr_ptr = &retval_ptr; BG(user_compare_fci).no_separation = 0; if (zend_call_function(&BG(user_compare_fci), &BG(user_compare_fci_cache) TSRMLS_CC) == SUCCESS && retval_ptr) { long retval; convert_to_long_ex(&retval_ptr); retval = Z_LVAL_P(retval_ptr); zval_ptr_dtor(&retval_ptr); return retval < 0 ? -1 : retval > 0 ? 1 : 0;; } else { return 0; } } /* }}} */ static void php_array_intersect_key(INTERNAL_FUNCTION_PARAMETERS, int data_compare_type) /* {{{ */ { Bucket *p; int argc, i; zval ***args; int (*intersect_data_compare_func)(zval **, zval ** TSRMLS_DC) = NULL; zend_bool ok; zval **data; int req_args; char *param_spec; /* Get the argument count */ argc = ZEND_NUM_ARGS(); if (data_compare_type == INTERSECT_COMP_DATA_USER) { /* INTERSECT_COMP_DATA_USER - array_uintersect_assoc() */ req_args = 3; param_spec = "+f"; intersect_data_compare_func = zval_user_compare; } else { /* INTERSECT_COMP_DATA_NONE - array_intersect_key() INTERSECT_COMP_DATA_INTERNAL - array_intersect_assoc() */ req_args = 2; param_spec = "+"; if (data_compare_type == INTERSECT_COMP_DATA_INTERNAL) { intersect_data_compare_func = zval_compare; } } if (argc < req_args) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least %d parameters are required, %d given", req_args, argc); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, param_spec, &args, &argc, &BG(user_compare_fci), &BG(user_compare_fci_cache)) == FAILURE) { return; } for (i = 0; i < argc; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is not an array", i + 1); RETVAL_NULL(); goto out; } } array_init(return_value); for (p = Z_ARRVAL_PP(args[0])->pListHead; p != NULL; p = p->pListNext) { if (p->nKeyLength == 0) { ok = 1; for (i = 1; i < argc; i++) { if (zend_hash_index_find(Z_ARRVAL_PP(args[i]), p->h, (void**)&data) == FAILURE || (intersect_data_compare_func && intersect_data_compare_func((zval**)p->pData, data TSRMLS_CC) != 0) ) { ok = 0; break; } } if (ok) { Z_ADDREF_PP((zval**)p->pData); zend_hash_index_update(Z_ARRVAL_P(return_value), p->h, p->pData, sizeof(zval*), NULL); } } else { ok = 1; for (i = 1; i < argc; i++) { if (zend_hash_quick_find(Z_ARRVAL_PP(args[i]), p->arKey, p->nKeyLength, p->h, (void**)&data) == FAILURE || (intersect_data_compare_func && intersect_data_compare_func((zval**)p->pData, data TSRMLS_CC) != 0) ) { ok = 0; break; } } if (ok) { Z_ADDREF_PP((zval**)p->pData); zend_hash_quick_update(Z_ARRVAL_P(return_value), p->arKey, p->nKeyLength, p->h, p->pData, sizeof(zval*), NULL); } } } out: efree(args); } /* }}} */ static void php_array_intersect(INTERNAL_FUNCTION_PARAMETERS, int behavior, int data_compare_type, int key_compare_type) /* {{{ */ { zval ***args = NULL; HashTable *hash; int arr_argc, i, c = 0; Bucket ***lists, **list, ***ptrs, *p; int req_args; char *param_spec; zend_fcall_info fci1, fci2; zend_fcall_info_cache fci1_cache = empty_fcall_info_cache, fci2_cache = empty_fcall_info_cache; zend_fcall_info *fci_key, *fci_data; zend_fcall_info_cache *fci_key_cache, *fci_data_cache; PHP_ARRAY_CMP_FUNC_VARS; int (*intersect_key_compare_func)(const void *, const void * TSRMLS_DC); int (*intersect_data_compare_func)(const void *, const void * TSRMLS_DC); if (behavior == INTERSECT_NORMAL) { intersect_key_compare_func = php_array_key_compare; if (data_compare_type == INTERSECT_COMP_DATA_INTERNAL) { /* array_intersect() */ req_args = 2; param_spec = "+"; intersect_data_compare_func = php_array_data_compare; } else if (data_compare_type == INTERSECT_COMP_DATA_USER) { /* array_uintersect() */ req_args = 3; param_spec = "+f"; intersect_data_compare_func = php_array_user_compare; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "data_compare_type is %d. This should never happen. Please report as a bug", data_compare_type); return; } if (ZEND_NUM_ARGS() < req_args) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least %d parameters are required, %d given", req_args, ZEND_NUM_ARGS()); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, param_spec, &args, &arr_argc, &fci1, &fci1_cache) == FAILURE) { return; } fci_data = &fci1; fci_data_cache = &fci1_cache; } else if (behavior & INTERSECT_ASSOC) { /* triggered also when INTERSECT_KEY */ /* INTERSECT_KEY is subset of INTERSECT_ASSOC. When having the former * no comparison of the data is done (part of INTERSECT_ASSOC) */ intersect_key_compare_func = php_array_key_compare; if (data_compare_type == INTERSECT_COMP_DATA_INTERNAL && key_compare_type == INTERSECT_COMP_KEY_INTERNAL) { /* array_intersect_assoc() or array_intersect_key() */ req_args = 2; param_spec = "+"; intersect_key_compare_func = php_array_key_compare; intersect_data_compare_func = php_array_data_compare; } else if (data_compare_type == INTERSECT_COMP_DATA_USER && key_compare_type == INTERSECT_COMP_KEY_INTERNAL) { /* array_uintersect_assoc() */ req_args = 3; param_spec = "+f"; intersect_key_compare_func = php_array_key_compare; intersect_data_compare_func = php_array_user_compare; fci_data = &fci1; fci_data_cache = &fci1_cache; } else if (data_compare_type == INTERSECT_COMP_DATA_INTERNAL && key_compare_type == INTERSECT_COMP_KEY_USER) { /* array_intersect_uassoc() or array_intersect_ukey() */ req_args = 3; param_spec = "+f"; intersect_key_compare_func = php_array_user_key_compare; intersect_data_compare_func = php_array_data_compare; fci_key = &fci1; fci_key_cache = &fci1_cache; } else if (data_compare_type == INTERSECT_COMP_DATA_USER && key_compare_type == INTERSECT_COMP_KEY_USER) { /* array_uintersect_uassoc() */ req_args = 4; param_spec = "+ff"; intersect_key_compare_func = php_array_user_key_compare; intersect_data_compare_func = php_array_user_compare; fci_data = &fci1; fci_data_cache = &fci1_cache; fci_key = &fci2; fci_key_cache = &fci2_cache; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "data_compare_type is %d. key_compare_type is %d. This should never happen. Please report as a bug", data_compare_type, key_compare_type); return; } if (ZEND_NUM_ARGS() < req_args) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least %d parameters are required, %d given", req_args, ZEND_NUM_ARGS()); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, param_spec, &args, &arr_argc, &fci1, &fci1_cache, &fci2, &fci2_cache) == FAILURE) { return; } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "behavior is %d. This should never happen. Please report as a bug", behavior); return; } PHP_ARRAY_CMP_FUNC_BACKUP(); /* for each argument, create and sort list with pointers to the hash buckets */ lists = (Bucket ***)safe_emalloc(arr_argc, sizeof(Bucket **), 0); ptrs = (Bucket ***)safe_emalloc(arr_argc, sizeof(Bucket **), 0); php_set_compare_func(PHP_SORT_STRING TSRMLS_CC); if (behavior == INTERSECT_NORMAL && data_compare_type == INTERSECT_COMP_DATA_USER) { BG(user_compare_fci) = *fci_data; BG(user_compare_fci_cache) = *fci_data_cache; } else if (behavior & INTERSECT_ASSOC && key_compare_type == INTERSECT_COMP_KEY_USER) { BG(user_compare_fci) = *fci_key; BG(user_compare_fci_cache) = *fci_key_cache; } for (i = 0; i < arr_argc; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is not an array", i + 1); arr_argc = i; /* only free up to i - 1 */ goto out; } hash = Z_ARRVAL_PP(args[i]); list = (Bucket **) pemalloc((hash->nNumOfElements + 1) * sizeof(Bucket *), hash->persistent); if (!list) { PHP_ARRAY_CMP_FUNC_RESTORE(); efree(ptrs); efree(lists); efree(args); RETURN_FALSE; } lists[i] = list; ptrs[i] = list; for (p = hash->pListHead; p; p = p->pListNext) { *list++ = p; } *list = NULL; if (behavior == INTERSECT_NORMAL) { zend_qsort((void *) lists[i], hash->nNumOfElements, sizeof(Bucket *), intersect_data_compare_func TSRMLS_CC); } else if (behavior & INTERSECT_ASSOC) { /* triggered also when INTERSECT_KEY */ zend_qsort((void *) lists[i], hash->nNumOfElements, sizeof(Bucket *), intersect_key_compare_func TSRMLS_CC); } } /* copy the argument array */ RETVAL_ZVAL(*args[0], 1, 0); if (return_value->value.ht == &EG(symbol_table)) { HashTable *ht; zval *tmp; ALLOC_HASHTABLE(ht); zend_hash_init(ht, zend_hash_num_elements(return_value->value.ht), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(ht, return_value->value.ht, (copy_ctor_func_t) zval_add_ref, (void *) &tmp, sizeof(zval *)); return_value->value.ht = ht; } /* go through the lists and look for common values */ while (*ptrs[0]) { if ((behavior & INTERSECT_ASSOC) /* triggered also when INTERSECT_KEY */ && key_compare_type == INTERSECT_COMP_KEY_USER) { BG(user_compare_fci) = *fci_key; BG(user_compare_fci_cache) = *fci_key_cache; } for (i = 1; i < arr_argc; i++) { if (behavior & INTERSECT_NORMAL) { while (*ptrs[i] && (0 < (c = intersect_data_compare_func(ptrs[0], ptrs[i] TSRMLS_CC)))) { ptrs[i]++; } } else if (behavior & INTERSECT_ASSOC) { /* triggered also when INTERSECT_KEY */ while (*ptrs[i] && (0 < (c = intersect_key_compare_func(ptrs[0], ptrs[i] TSRMLS_CC)))) { ptrs[i]++; } if ((!c && *ptrs[i]) && (behavior == INTERSECT_ASSOC)) { /* only when INTERSECT_ASSOC */ /* this means that ptrs[i] is not NULL so we can compare * and "c==0" is from last operation * in this branch of code we enter only when INTERSECT_ASSOC * since when we have INTERSECT_KEY compare of data is not wanted. */ if (data_compare_type == INTERSECT_COMP_DATA_USER) { BG(user_compare_fci) = *fci_data; BG(user_compare_fci_cache) = *fci_data_cache; } if (intersect_data_compare_func(ptrs[0], ptrs[i] TSRMLS_CC) != 0) { c = 1; if (key_compare_type == INTERSECT_COMP_KEY_USER) { BG(user_compare_fci) = *fci_key; BG(user_compare_fci_cache) = *fci_key_cache; /* When KEY_USER, the last parameter is always the callback */ } /* we are going to the break */ } else { /* continue looping */ } } } if (!*ptrs[i]) { /* delete any values corresponding to remains of ptrs[0] */ /* and exit because they do not present in at least one of */ /* the other arguments */ for (;;) { p = *ptrs[0]++; if (!p) { goto out; } if (p->nKeyLength == 0) { zend_hash_index_del(Z_ARRVAL_P(return_value), p->h); } else { zend_hash_quick_del(Z_ARRVAL_P(return_value), p->arKey, p->nKeyLength, p->h); } } } if (c) /* here we get if not all are equal */ break; ptrs[i]++; } if (c) { /* Value of ptrs[0] not in all arguments, delete all entries */ /* with value < value of ptrs[i] */ for (;;) { p = *ptrs[0]; if (p->nKeyLength == 0) { zend_hash_index_del(Z_ARRVAL_P(return_value), p->h); } else { zend_hash_quick_del(Z_ARRVAL_P(return_value), p->arKey, p->nKeyLength, p->h); } if (!*++ptrs[0]) { goto out; } if (behavior == INTERSECT_NORMAL) { if (0 <= intersect_data_compare_func(ptrs[0], ptrs[i] TSRMLS_CC)) { break; } } else if (behavior & INTERSECT_ASSOC) { /* triggered also when INTERSECT_KEY */ /* no need of looping because indexes are unique */ break; } } } else { /* ptrs[0] is present in all the arguments */ /* Skip all entries with same value as ptrs[0] */ for (;;) { if (!*++ptrs[0]) { goto out; } if (behavior == INTERSECT_NORMAL) { if (intersect_data_compare_func(ptrs[0] - 1, ptrs[0] TSRMLS_CC)) { break; } } else if (behavior & INTERSECT_ASSOC) { /* triggered also when INTERSECT_KEY */ /* no need of looping because indexes are unique */ break; } } } } out: for (i = 0; i < arr_argc; i++) { hash = Z_ARRVAL_PP(args[i]); pefree(lists[i], hash->persistent); } PHP_ARRAY_CMP_FUNC_RESTORE(); efree(ptrs); efree(lists); efree(args); } /* }}} */ /* {{{ proto array array_intersect_key(array arr1, array arr2 [, array ...]) Returns the entries of arr1 that have keys which are present in all the other arguments. Kind of equivalent to array_diff(array_keys($arr1), array_keys($arr2)[,array_keys(...)]). Equivalent of array_intersect_assoc() but does not do compare of the data. */ PHP_FUNCTION(array_intersect_key) { php_array_intersect_key(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_COMP_DATA_NONE); } /* }}} */ /* {{{ proto array array_intersect_ukey(array arr1, array arr2 [, array ...], callback key_compare_func) Returns the entries of arr1 that have keys which are present in all the other arguments. Kind of equivalent to array_diff(array_keys($arr1), array_keys($arr2)[,array_keys(...)]). The comparison of the keys is performed by a user supplied function. Equivalent of array_intersect_uassoc() but does not do compare of the data. */ PHP_FUNCTION(array_intersect_ukey) { php_array_intersect(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_KEY, INTERSECT_COMP_DATA_INTERNAL, INTERSECT_COMP_KEY_USER); } /* }}} */ /* {{{ proto array array_intersect(array arr1, array arr2 [, array ...]) Returns the entries of arr1 that have values which are present in all the other arguments */ PHP_FUNCTION(array_intersect) { php_array_intersect(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_NORMAL, INTERSECT_COMP_DATA_INTERNAL, INTERSECT_COMP_KEY_INTERNAL); } /* }}} */ /* {{{ proto array array_uintersect(array arr1, array arr2 [, array ...], callback data_compare_func) Returns the entries of arr1 that have values which are present in all the other arguments. Data is compared by using an user-supplied callback. */ PHP_FUNCTION(array_uintersect) { php_array_intersect(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_NORMAL, INTERSECT_COMP_DATA_USER, INTERSECT_COMP_KEY_INTERNAL); } /* }}} */ /* {{{ proto array array_intersect_assoc(array arr1, array arr2 [, array ...]) Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check */ PHP_FUNCTION(array_intersect_assoc) { php_array_intersect_key(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_COMP_DATA_INTERNAL); } /* }}} */ /* {{{ proto array array_intersect_uassoc(array arr1, array arr2 [, array ...], callback key_compare_func) U Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check and they are compared by using an user-supplied callback. */ PHP_FUNCTION(array_intersect_uassoc) { php_array_intersect(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_ASSOC, INTERSECT_COMP_DATA_INTERNAL, INTERSECT_COMP_KEY_USER); } /* }}} */ /* {{{ proto array array_uintersect_assoc(array arr1, array arr2 [, array ...], callback data_compare_func) U Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check. Data is compared by using an user-supplied callback. */ PHP_FUNCTION(array_uintersect_assoc) { php_array_intersect_key(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_COMP_DATA_USER); } /* }}} */ /* {{{ proto array array_uintersect_uassoc(array arr1, array arr2 [, array ...], callback data_compare_func, callback key_compare_func) Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check. Both data and keys are compared by using user-supplied callbacks. */ PHP_FUNCTION(array_uintersect_uassoc) { php_array_intersect(INTERNAL_FUNCTION_PARAM_PASSTHRU, INTERSECT_ASSOC, INTERSECT_COMP_DATA_USER, INTERSECT_COMP_KEY_USER); } /* }}} */ static void php_array_diff_key(INTERNAL_FUNCTION_PARAMETERS, int data_compare_type) /* {{{ */ { Bucket *p; int argc, i; zval ***args; int (*diff_data_compare_func)(zval **, zval ** TSRMLS_DC) = NULL; zend_bool ok; zval **data; /* Get the argument count */ argc = ZEND_NUM_ARGS(); if (data_compare_type == DIFF_COMP_DATA_USER) { if (argc < 3) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least 3 parameters are required, %d given", ZEND_NUM_ARGS()); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+f", &args, &argc, &BG(user_compare_fci), &BG(user_compare_fci_cache)) == FAILURE) { return; } diff_data_compare_func = zval_user_compare; } else { if (argc < 2) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least 2 parameters are required, %d given", ZEND_NUM_ARGS()); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &argc) == FAILURE) { return; } if (data_compare_type == DIFF_COMP_DATA_INTERNAL) { diff_data_compare_func = zval_compare; } } for (i = 0; i < argc; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is not an array", i + 1); RETVAL_NULL(); goto out; } } array_init(return_value); for (p = Z_ARRVAL_PP(args[0])->pListHead; p != NULL; p = p->pListNext) { if (p->nKeyLength == 0) { ok = 1; for (i = 1; i < argc; i++) { if (zend_hash_index_find(Z_ARRVAL_PP(args[i]), p->h, (void**)&data) == SUCCESS && (!diff_data_compare_func || diff_data_compare_func((zval**)p->pData, data TSRMLS_CC) == 0) ) { ok = 0; break; } } if (ok) { Z_ADDREF_PP((zval**)p->pData); zend_hash_index_update(Z_ARRVAL_P(return_value), p->h, p->pData, sizeof(zval*), NULL); } } else { ok = 1; for (i = 1; i < argc; i++) { if (zend_hash_quick_find(Z_ARRVAL_PP(args[i]), p->arKey, p->nKeyLength, p->h, (void**)&data) == SUCCESS && (!diff_data_compare_func || diff_data_compare_func((zval**)p->pData, data TSRMLS_CC) == 0) ) { ok = 0; break; } } if (ok) { Z_ADDREF_PP((zval**)p->pData); zend_hash_quick_update(Z_ARRVAL_P(return_value), p->arKey, p->nKeyLength, p->h, p->pData, sizeof(zval*), NULL); } } } out: efree(args); } /* }}} */ static void php_array_diff(INTERNAL_FUNCTION_PARAMETERS, int behavior, int data_compare_type, int key_compare_type) /* {{{ */ { zval ***args = NULL; HashTable *hash; int arr_argc, i, c; Bucket ***lists, **list, ***ptrs, *p; int req_args; char *param_spec; zend_fcall_info fci1, fci2; zend_fcall_info_cache fci1_cache = empty_fcall_info_cache, fci2_cache = empty_fcall_info_cache; zend_fcall_info *fci_key, *fci_data; zend_fcall_info_cache *fci_key_cache, *fci_data_cache; PHP_ARRAY_CMP_FUNC_VARS; int (*diff_key_compare_func)(const void *, const void * TSRMLS_DC); int (*diff_data_compare_func)(const void *, const void * TSRMLS_DC); if (behavior == DIFF_NORMAL) { diff_key_compare_func = php_array_key_compare; if (data_compare_type == DIFF_COMP_DATA_INTERNAL) { /* array_diff */ req_args = 2; param_spec = "+"; diff_data_compare_func = php_array_data_compare; } else if (data_compare_type == DIFF_COMP_DATA_USER) { /* array_udiff */ req_args = 3; param_spec = "+f"; diff_data_compare_func = php_array_user_compare; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "data_compare_type is %d. This should never happen. Please report as a bug", data_compare_type); return; } if (ZEND_NUM_ARGS() < req_args) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least %d parameters are required, %d given", req_args, ZEND_NUM_ARGS()); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, param_spec, &args, &arr_argc, &fci1, &fci1_cache) == FAILURE) { return; } fci_data = &fci1; fci_data_cache = &fci1_cache; } else if (behavior & DIFF_ASSOC) { /* triggered also if DIFF_KEY */ /* DIFF_KEY is subset of DIFF_ASSOC. When having the former * no comparison of the data is done (part of DIFF_ASSOC) */ if (data_compare_type == DIFF_COMP_DATA_INTERNAL && key_compare_type == DIFF_COMP_KEY_INTERNAL) { /* array_diff_assoc() or array_diff_key() */ req_args = 2; param_spec = "+"; diff_key_compare_func = php_array_key_compare; diff_data_compare_func = php_array_data_compare; } else if (data_compare_type == DIFF_COMP_DATA_USER && key_compare_type == DIFF_COMP_KEY_INTERNAL) { /* array_udiff_assoc() */ req_args = 3; param_spec = "+f"; diff_key_compare_func = php_array_key_compare; diff_data_compare_func = php_array_user_compare; fci_data = &fci1; fci_data_cache = &fci1_cache; } else if (data_compare_type == DIFF_COMP_DATA_INTERNAL && key_compare_type == DIFF_COMP_KEY_USER) { /* array_diff_uassoc() or array_diff_ukey() */ req_args = 3; param_spec = "+f"; diff_key_compare_func = php_array_user_key_compare; diff_data_compare_func = php_array_data_compare; fci_key = &fci1; fci_key_cache = &fci1_cache; } else if (data_compare_type == DIFF_COMP_DATA_USER && key_compare_type == DIFF_COMP_KEY_USER) { /* array_udiff_uassoc() */ req_args = 4; param_spec = "+ff"; diff_key_compare_func = php_array_user_key_compare; diff_data_compare_func = php_array_user_compare; fci_data = &fci1; fci_data_cache = &fci1_cache; fci_key = &fci2; fci_key_cache = &fci2_cache; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "data_compare_type is %d. key_compare_type is %d. This should never happen. Please report as a bug", data_compare_type, key_compare_type); return; } if (ZEND_NUM_ARGS() < req_args) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "at least %d parameters are required, %d given", req_args, ZEND_NUM_ARGS()); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, param_spec, &args, &arr_argc, &fci1, &fci1_cache, &fci2, &fci2_cache) == FAILURE) { return; } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "behavior is %d. This should never happen. Please report as a bug", behavior); return; } PHP_ARRAY_CMP_FUNC_BACKUP(); /* for each argument, create and sort list with pointers to the hash buckets */ lists = (Bucket ***)safe_emalloc(arr_argc, sizeof(Bucket **), 0); ptrs = (Bucket ***)safe_emalloc(arr_argc, sizeof(Bucket **), 0); php_set_compare_func(PHP_SORT_STRING TSRMLS_CC); if (behavior == DIFF_NORMAL && data_compare_type == DIFF_COMP_DATA_USER) { BG(user_compare_fci) = *fci_data; BG(user_compare_fci_cache) = *fci_data_cache; } else if (behavior & DIFF_ASSOC && key_compare_type == DIFF_COMP_KEY_USER) { BG(user_compare_fci) = *fci_key; BG(user_compare_fci_cache) = *fci_key_cache; } for (i = 0; i < arr_argc; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is not an array", i + 1); arr_argc = i; /* only free up to i - 1 */ goto out; } hash = Z_ARRVAL_PP(args[i]); list = (Bucket **) pemalloc((hash->nNumOfElements + 1) * sizeof(Bucket *), hash->persistent); if (!list) { PHP_ARRAY_CMP_FUNC_RESTORE(); efree(ptrs); efree(lists); efree(args); RETURN_FALSE; } lists[i] = list; ptrs[i] = list; for (p = hash->pListHead; p; p = p->pListNext) { *list++ = p; } *list = NULL; if (behavior == DIFF_NORMAL) { zend_qsort((void *) lists[i], hash->nNumOfElements, sizeof(Bucket *), diff_data_compare_func TSRMLS_CC); } else if (behavior & DIFF_ASSOC) { /* triggered also when DIFF_KEY */ zend_qsort((void *) lists[i], hash->nNumOfElements, sizeof(Bucket *), diff_key_compare_func TSRMLS_CC); } } /* copy the argument array */ RETVAL_ZVAL(*args[0], 1, 0); if (return_value->value.ht == &EG(symbol_table)) { HashTable *ht; zval *tmp; ALLOC_HASHTABLE(ht); zend_hash_init(ht, zend_hash_num_elements(return_value->value.ht), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(ht, return_value->value.ht, (copy_ctor_func_t) zval_add_ref, (void *) &tmp, sizeof(zval *)); return_value->value.ht = ht; } /* go through the lists and look for values of ptr[0] that are not in the others */ while (*ptrs[0]) { if ((behavior & DIFF_ASSOC) /* triggered also when DIFF_KEY */ && key_compare_type == DIFF_COMP_KEY_USER ) { BG(user_compare_fci) = *fci_key; BG(user_compare_fci_cache) = *fci_key_cache; } c = 1; for (i = 1; i < arr_argc; i++) { Bucket **ptr = ptrs[i]; if (behavior == DIFF_NORMAL) { while (*ptrs[i] && (0 < (c = diff_data_compare_func(ptrs[0], ptrs[i] TSRMLS_CC)))) { ptrs[i]++; } } else if (behavior & DIFF_ASSOC) { /* triggered also when DIFF_KEY */ while (*ptr && (0 != (c = diff_key_compare_func(ptrs[0], ptr TSRMLS_CC)))) { ptr++; } } if (!c) { if (behavior == DIFF_NORMAL) { if (*ptrs[i]) { ptrs[i]++; } break; } else if (behavior == DIFF_ASSOC) { /* only when DIFF_ASSOC */ /* In this branch is execute only when DIFF_ASSOC. If behavior == DIFF_KEY * data comparison is not needed - skipped. */ if (*ptr) { if (data_compare_type == DIFF_COMP_DATA_USER) { BG(user_compare_fci) = *fci_data; BG(user_compare_fci_cache) = *fci_data_cache; } if (diff_data_compare_func(ptrs[0], ptr TSRMLS_CC) != 0) { /* the data is not the same */ c = -1; if (key_compare_type == DIFF_COMP_KEY_USER) { BG(user_compare_fci) = *fci_key; BG(user_compare_fci_cache) = *fci_key_cache; } } else { break; /* we have found the element in other arrays thus we don't want it * in the return_value -> delete from there */ } } } else if (behavior == DIFF_KEY) { /* only when DIFF_KEY */ /* the behavior here differs from INTERSECT_KEY in php_intersect * since in the "diff" case we have to remove the entry from * return_value while when doing intersection the entry must not * be deleted. */ break; /* remove the key */ } } } if (!c) { /* ptrs[0] in one of the other arguments */ /* delete all entries with value as ptrs[0] */ for (;;) { p = *ptrs[0]; if (p->nKeyLength == 0) { zend_hash_index_del(Z_ARRVAL_P(return_value), p->h); } else { zend_hash_quick_del(Z_ARRVAL_P(return_value), p->arKey, p->nKeyLength, p->h); } if (!*++ptrs[0]) { goto out; } if (behavior == DIFF_NORMAL) { if (diff_data_compare_func(ptrs[0] - 1, ptrs[0] TSRMLS_CC)) { break; } } else if (behavior & DIFF_ASSOC) { /* triggered also when DIFF_KEY */ /* in this case no array_key_compare is needed */ break; } } } else { /* ptrs[0] in none of the other arguments */ /* skip all entries with value as ptrs[0] */ for (;;) { if (!*++ptrs[0]) { goto out; } if (behavior == DIFF_NORMAL) { if (diff_data_compare_func(ptrs[0] - 1, ptrs[0] TSRMLS_CC)) { break; } } else if (behavior & DIFF_ASSOC) { /* triggered also when DIFF_KEY */ /* in this case no array_key_compare is needed */ break; } } } } out: for (i = 0; i < arr_argc; i++) { hash = Z_ARRVAL_PP(args[i]); pefree(lists[i], hash->persistent); } PHP_ARRAY_CMP_FUNC_RESTORE(); efree(ptrs); efree(lists); efree(args); } /* }}} */ /* {{{ proto array array_diff_key(array arr1, array arr2 [, array ...]) Returns the entries of arr1 that have keys which are not present in any of the others arguments. This function is like array_diff() but works on the keys instead of the values. The associativity is preserved. */ PHP_FUNCTION(array_diff_key) { php_array_diff_key(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_COMP_DATA_NONE); } /* }}} */ /* {{{ proto array array_diff_ukey(array arr1, array arr2 [, array ...], callback key_comp_func) Returns the entries of arr1 that have keys which are not present in any of the others arguments. User supplied function is used for comparing the keys. This function is like array_udiff() but works on the keys instead of the values. The associativity is preserved. */ PHP_FUNCTION(array_diff_ukey) { php_array_diff(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_KEY, DIFF_COMP_DATA_INTERNAL, DIFF_COMP_KEY_USER); } /* }}} */ /* {{{ proto array array_diff(array arr1, array arr2 [, array ...]) Returns the entries of arr1 that have values which are not present in any of the others arguments. */ PHP_FUNCTION(array_diff) { php_array_diff(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_NORMAL, DIFF_COMP_DATA_INTERNAL, DIFF_COMP_KEY_INTERNAL); } /* }}} */ /* {{{ proto array array_udiff(array arr1, array arr2 [, array ...], callback data_comp_func) Returns the entries of arr1 that have values which are not present in any of the others arguments. Elements are compared by user supplied function. */ PHP_FUNCTION(array_udiff) { php_array_diff(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_NORMAL, DIFF_COMP_DATA_USER, DIFF_COMP_KEY_INTERNAL); } /* }}} */ /* {{{ proto array array_diff_assoc(array arr1, array arr2 [, array ...]) Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal */ PHP_FUNCTION(array_diff_assoc) { php_array_diff_key(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_COMP_DATA_INTERNAL); } /* }}} */ /* {{{ proto array array_diff_uassoc(array arr1, array arr2 [, array ...], callback data_comp_func) Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal. Elements are compared by user supplied function. */ PHP_FUNCTION(array_diff_uassoc) { php_array_diff(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_ASSOC, DIFF_COMP_DATA_INTERNAL, DIFF_COMP_KEY_USER); } /* }}} */ /* {{{ proto array array_udiff_assoc(array arr1, array arr2 [, array ...], callback key_comp_func) Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal. Keys are compared by user supplied function. */ PHP_FUNCTION(array_udiff_assoc) { php_array_diff_key(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_COMP_DATA_USER); } /* }}} */ /* {{{ proto array array_udiff_uassoc(array arr1, array arr2 [, array ...], callback data_comp_func, callback key_comp_func) Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal. Keys and elements are compared by user supplied functions. */ PHP_FUNCTION(array_udiff_uassoc) { php_array_diff(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_ASSOC, DIFF_COMP_DATA_USER, DIFF_COMP_KEY_USER); } /* }}} */ #define MULTISORT_ORDER 0 #define MULTISORT_TYPE 1 #define MULTISORT_LAST 2 PHPAPI int php_multisort_compare(const void *a, const void *b TSRMLS_DC) /* {{{ */ { Bucket **ab = *(Bucket ***)a; Bucket **bb = *(Bucket ***)b; int r; int result = 0; zval temp; r = 0; do { php_set_compare_func(ARRAYG(multisort_flags)[MULTISORT_TYPE][r] TSRMLS_CC); ARRAYG(compare_func)(&temp, *((zval **)ab[r]->pData), *((zval **)bb[r]->pData) TSRMLS_CC); result = ARRAYG(multisort_flags)[MULTISORT_ORDER][r] * Z_LVAL(temp); if (result != 0) { return result; } r++; } while (ab[r] != NULL); return result; } /* }}} */ #define MULTISORT_ABORT \ for (k = 0; k < MULTISORT_LAST; k++) \ efree(ARRAYG(multisort_flags)[k]); \ efree(arrays); \ efree(args); \ RETURN_FALSE; /* {{{ proto bool array_multisort(array ar1 [, SORT_ASC|SORT_DESC [, SORT_REGULAR|SORT_NUMERIC|SORT_STRING]] [, array ar2 [, SORT_ASC|SORT_DESC [, SORT_REGULAR|SORT_NUMERIC|SORT_STRING]], ...]) Sort multiple arrays at once similar to how ORDER BY clause works in SQL */ PHP_FUNCTION(array_multisort) { zval*** args; zval*** arrays; Bucket*** indirect; Bucket* p; HashTable* hash; int argc; int array_size; int num_arrays = 0; int parse_state[MULTISORT_LAST]; /* 0 - flag not allowed 1 - flag allowed */ int sort_order = PHP_SORT_ASC; int sort_type = PHP_SORT_REGULAR; int i, k; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &argc) == FAILURE) { return; } /* Allocate space for storing pointers to input arrays and sort flags. */ arrays = (zval ***)ecalloc(argc, sizeof(zval **)); for (i = 0; i < MULTISORT_LAST; i++) { parse_state[i] = 0; ARRAYG(multisort_flags)[i] = (int *)ecalloc(argc, sizeof(int)); } /* Here we go through the input arguments and parse them. Each one can * be either an array or a sort flag which follows an array. If not * specified, the sort flags defaults to PHP_SORT_ASC and PHP_SORT_REGULAR * accordingly. There can't be two sort flags of the same type after an * array, and the very first argument has to be an array. */ for (i = 0; i < argc; i++) { if (Z_TYPE_PP(args[i]) == IS_ARRAY) { /* We see the next array, so we update the sort flags of * the previous array and reset the sort flags. */ if (i > 0) { ARRAYG(multisort_flags)[MULTISORT_ORDER][num_arrays - 1] = sort_order; ARRAYG(multisort_flags)[MULTISORT_TYPE][num_arrays - 1] = sort_type; sort_order = PHP_SORT_ASC; sort_type = PHP_SORT_REGULAR; } arrays[num_arrays++] = args[i]; /* Next one may be an array or a list of sort flags. */ for (k = 0; k < MULTISORT_LAST; k++) { parse_state[k] = 1; } } else if (Z_TYPE_PP(args[i]) == IS_LONG) { switch (Z_LVAL_PP(args[i])) { case PHP_SORT_ASC: case PHP_SORT_DESC: /* flag allowed here */ if (parse_state[MULTISORT_ORDER] == 1) { /* Save the flag and make sure then next arg is not the current flag. */ sort_order = Z_LVAL_PP(args[i]) == PHP_SORT_DESC ? -1 : 1; parse_state[MULTISORT_ORDER] = 0; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is expected to be an array or sorting flag that has not already been specified", i + 1); MULTISORT_ABORT; } break; case PHP_SORT_REGULAR: case PHP_SORT_NUMERIC: case PHP_SORT_STRING: #if HAVE_STRCOLL case PHP_SORT_LOCALE_STRING: #endif /* flag allowed here */ if (parse_state[MULTISORT_TYPE] == 1) { /* Save the flag and make sure then next arg is not the current flag. */ sort_type = Z_LVAL_PP(args[i]); parse_state[MULTISORT_TYPE] = 0; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is expected to be an array or sorting flag that has not already been specified", i + 1); MULTISORT_ABORT; } break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is an unknown sort flag", i + 1); MULTISORT_ABORT; break; } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d is expected to be an array or a sort flag", i + 1); MULTISORT_ABORT; } } /* Take care of the last array sort flags. */ ARRAYG(multisort_flags)[MULTISORT_ORDER][num_arrays - 1] = sort_order; ARRAYG(multisort_flags)[MULTISORT_TYPE][num_arrays - 1] = sort_type; /* Make sure the arrays are of the same size. */ array_size = zend_hash_num_elements(Z_ARRVAL_PP(arrays[0])); for (i = 0; i < num_arrays; i++) { if (zend_hash_num_elements(Z_ARRVAL_PP(arrays[i])) != array_size) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array sizes are inconsistent"); MULTISORT_ABORT; } } /* If all arrays are empty we don't need to do anything. */ if (array_size < 1) { for (k = 0; k < MULTISORT_LAST; k++) { efree(ARRAYG(multisort_flags)[k]); } efree(arrays); efree(args); RETURN_TRUE; } /* Create the indirection array. This array is of size MxN, where * M is the number of entries in each input array and N is the number * of the input arrays + 1. The last column is NULL to indicate the end * of the row. */ indirect = (Bucket ***)safe_emalloc(array_size, sizeof(Bucket **), 0); for (i = 0; i < array_size; i++) { indirect[i] = (Bucket **)safe_emalloc((num_arrays + 1), sizeof(Bucket *), 0); } for (i = 0; i < num_arrays; i++) { k = 0; for (p = Z_ARRVAL_PP(arrays[i])->pListHead; p; p = p->pListNext, k++) { indirect[k][i] = p; } } for (k = 0; k < array_size; k++) { indirect[k][num_arrays] = NULL; } /* Do the actual sort magic - bada-bim, bada-boom. */ zend_qsort(indirect, array_size, sizeof(Bucket **), php_multisort_compare TSRMLS_CC); /* Restructure the arrays based on sorted indirect - this is mostly taken from zend_hash_sort() function. */ HANDLE_BLOCK_INTERRUPTIONS(); for (i = 0; i < num_arrays; i++) { hash = Z_ARRVAL_PP(arrays[i]); hash->pListHead = indirect[0][i];; hash->pListTail = NULL; hash->pInternalPointer = hash->pListHead; for (k = 0; k < array_size; k++) { if (hash->pListTail) { hash->pListTail->pListNext = indirect[k][i]; } indirect[k][i]->pListLast = hash->pListTail; indirect[k][i]->pListNext = NULL; hash->pListTail = indirect[k][i]; } p = hash->pListHead; k = 0; while (p != NULL) { if (p->nKeyLength == 0) p->h = k++; p = p->pListNext; } hash->nNextFreeElement = array_size; zend_hash_rehash(hash); } HANDLE_UNBLOCK_INTERRUPTIONS(); /* Clean up. */ for (i = 0; i < array_size; i++) { efree(indirect[i]); } efree(indirect); for (k = 0; k < MULTISORT_LAST; k++) { efree(ARRAYG(multisort_flags)[k]); } efree(arrays); efree(args); RETURN_TRUE; } /* }}} */ /* {{{ proto mixed array_rand(array input [, int num_req]) Return key/keys for random entry/entries in the array */ PHP_FUNCTION(array_rand) { zval *input; long randval, num_req = 1; int num_avail, key_type; char *string_key; uint string_key_len; ulong num_key; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &input, &num_req) == FAILURE) { return; } num_avail = zend_hash_num_elements(Z_ARRVAL_P(input)); if (ZEND_NUM_ARGS() > 1) { if (num_req <= 0 || num_req > num_avail) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Second argument has to be between 1 and the number of elements in the array"); return; } } /* Make the return value an array only if we need to pass back more than one result. */ if (num_req > 1) { array_init_size(return_value, num_req); } /* We can't use zend_hash_index_find() because the array may have string keys or gaps. */ zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos); while (num_req && (key_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(input), &string_key, &string_key_len, &num_key, 0, &pos)) != HASH_KEY_NON_EXISTANT) { randval = php_rand(TSRMLS_C); if ((double) (randval / (PHP_RAND_MAX + 1.0)) < (double) num_req / (double) num_avail) { /* If we are returning a single result, just do it. */ if (Z_TYPE_P(return_value) != IS_ARRAY) { if (key_type == HASH_KEY_IS_STRING) { RETURN_STRINGL(string_key, string_key_len - 1, 1); } else { RETURN_LONG(num_key); } } else { /* Append the result to the return value. */ if (key_type == HASH_KEY_IS_STRING) { add_next_index_stringl(return_value, string_key, string_key_len - 1, 1); } else { add_next_index_long(return_value, num_key); } } num_req--; } num_avail--; zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos); } } /* }}} */ /* {{{ proto mixed array_sum(array input) Returns the sum of the array entries */ PHP_FUNCTION(array_sum) { zval *input, **entry, entry_n; HashPosition pos; double dval; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &input) == FAILURE) { return; } ZVAL_LONG(return_value, 0); for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos); zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &pos) == SUCCESS; zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos) ) { if (Z_TYPE_PP(entry) == IS_ARRAY || Z_TYPE_PP(entry) == IS_OBJECT) { continue; } entry_n = **entry; zval_copy_ctor(&entry_n); convert_scalar_to_number(&entry_n TSRMLS_CC); if (Z_TYPE(entry_n) == IS_LONG && Z_TYPE_P(return_value) == IS_LONG) { dval = (double)Z_LVAL_P(return_value) + (double)Z_LVAL(entry_n); if ( (double)LONG_MIN <= dval && dval <= (double)LONG_MAX ) { Z_LVAL_P(return_value) += Z_LVAL(entry_n); continue; } } convert_to_double(return_value); convert_to_double(&entry_n); Z_DVAL_P(return_value) += Z_DVAL(entry_n); } } /* }}} */ /* {{{ proto mixed array_product(array input) Returns the product of the array entries */ PHP_FUNCTION(array_product) { zval *input, **entry, entry_n; HashPosition pos; double dval; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &input) == FAILURE) { return; } ZVAL_LONG(return_value, 1); if (!zend_hash_num_elements(Z_ARRVAL_P(input))) { return; } for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos); zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &pos) == SUCCESS; zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos) ) { if (Z_TYPE_PP(entry) == IS_ARRAY || Z_TYPE_PP(entry) == IS_OBJECT) { continue; } entry_n = **entry; zval_copy_ctor(&entry_n); convert_scalar_to_number(&entry_n TSRMLS_CC); if (Z_TYPE(entry_n) == IS_LONG && Z_TYPE_P(return_value) == IS_LONG) { dval = (double)Z_LVAL_P(return_value) * (double)Z_LVAL(entry_n); if ( (double)LONG_MIN <= dval && dval <= (double)LONG_MAX ) { Z_LVAL_P(return_value) *= Z_LVAL(entry_n); continue; } } convert_to_double(return_value); convert_to_double(&entry_n); Z_DVAL_P(return_value) *= Z_DVAL(entry_n); } } /* }}} */ /* {{{ proto mixed array_reduce(array input, mixed callback [, mixed initial]) Iteratively reduce the array to a single value via the callback. */ PHP_FUNCTION(array_reduce) { zval *input; zval **args[2]; zval **operand; zval *result = NULL; zval *retval; zend_fcall_info fci; zend_fcall_info_cache fci_cache = empty_fcall_info_cache; zval *initial = NULL; HashPosition pos; HashTable *htbl; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "af|z", &input, &fci, &fci_cache, &initial) == FAILURE) { return; } if (ZEND_NUM_ARGS() > 2) { ALLOC_ZVAL(result); MAKE_COPY_ZVAL(&initial, result); } else { MAKE_STD_ZVAL(result); ZVAL_NULL(result); } /* (zval **)input points to an element of argument stack * the base pointer of which is subject to change. * thus we need to keep the pointer to the hashtable for safety */ htbl = Z_ARRVAL_P(input); if (zend_hash_num_elements(htbl) == 0) { if (result) { RETVAL_ZVAL(result, 1, 1); } return; } fci.retval_ptr_ptr = &retval; fci.param_count = 2; fci.no_separation = 0; zend_hash_internal_pointer_reset_ex(htbl, &pos); while (zend_hash_get_current_data_ex(htbl, (void **)&operand, &pos) == SUCCESS) { if (result) { args[0] = &result; args[1] = operand; fci.params = args; if (zend_call_function(&fci, &fci_cache TSRMLS_CC) == SUCCESS && retval) { zval_ptr_dtor(&result); result = retval; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "An error occurred while invoking the reduction callback"); return; } } else { result = *operand; zval_add_ref(&result); } zend_hash_move_forward_ex(htbl, &pos); } RETVAL_ZVAL(result, 1, 1); } /* }}} */ /* {{{ proto array array_filter(array input [, mixed callback]) Filters elements from the array via the callback. */ PHP_FUNCTION(array_filter) { zval *array; zval **operand; zval **args[1]; zval *retval = NULL; zend_bool have_callback = 0; char *string_key; zend_fcall_info fci = empty_fcall_info; zend_fcall_info_cache fci_cache = empty_fcall_info_cache; uint string_key_len; ulong num_key; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|f", &array, &fci, &fci_cache) == FAILURE) { return; } array_init(return_value); if (zend_hash_num_elements(Z_ARRVAL_P(array)) == 0) { return; } if (ZEND_NUM_ARGS() > 1) { have_callback = 1; fci.no_separation = 0; fci.retval_ptr_ptr = &retval; fci.param_count = 1; } for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(array), &pos); zend_hash_get_current_data_ex(Z_ARRVAL_P(array), (void **)&operand, &pos) == SUCCESS; zend_hash_move_forward_ex(Z_ARRVAL_P(array), &pos) ) { if (have_callback) { args[0] = operand; fci.params = args; if (zend_call_function(&fci, &fci_cache TSRMLS_CC) == SUCCESS && retval) { if (!zend_is_true(retval)) { zval_ptr_dtor(&retval); continue; } else { zval_ptr_dtor(&retval); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "An error occurred while invoking the filter callback"); return; } } else if (!zend_is_true(*operand)) { continue; } zval_add_ref(operand); switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(array), &string_key, &string_key_len, &num_key, 0, &pos)) { case HASH_KEY_IS_STRING: zend_hash_update(Z_ARRVAL_P(return_value), string_key, string_key_len, operand, sizeof(zval *), NULL); break; case HASH_KEY_IS_LONG: zend_hash_index_update(Z_ARRVAL_P(return_value), num_key, operand, sizeof(zval *), NULL); break; } } } /* }}} */ /* {{{ proto array array_map(mixed callback, array input1 [, array input2 ,...]) Applies the callback to the elements in given arrays. */ PHP_FUNCTION(array_map) { zval ***arrays = NULL; int n_arrays = 0; zval ***params; zval *result, *null; HashPosition *array_pos; zval **args; zend_fcall_info fci = empty_fcall_info; zend_fcall_info_cache fci_cache = empty_fcall_info_cache; int i, k, maxlen = 0; int *array_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "f!+", &fci, &fci_cache, &arrays, &n_arrays) == FAILURE) { return; } RETVAL_NULL(); args = (zval **)safe_emalloc(n_arrays, sizeof(zval *), 0); array_len = (int *)safe_emalloc(n_arrays, sizeof(int), 0); array_pos = (HashPosition *)safe_emalloc(n_arrays, sizeof(HashPosition), 0); for (i = 0; i < n_arrays; i++) { if (Z_TYPE_PP(arrays[i]) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument #%d should be an array", i + 2); efree(arrays); efree(args); efree(array_len); efree(array_pos); return; } SEPARATE_ZVAL_IF_NOT_REF(arrays[i]); args[i] = *arrays[i]; array_len[i] = zend_hash_num_elements(Z_ARRVAL_PP(arrays[i])); if (array_len[i] > maxlen) { maxlen = array_len[i]; } zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(arrays[i]), &array_pos[i]); } efree(arrays); /* Short-circuit: if no callback and only one array, just return it. */ if (!ZEND_FCI_INITIALIZED(fci) && n_arrays == 1) { RETVAL_ZVAL(args[0], 1, 0); efree(array_len); efree(array_pos); efree(args); return; } array_init_size(return_value, maxlen); params = (zval ***)safe_emalloc(n_arrays, sizeof(zval **), 0); MAKE_STD_ZVAL(null); ZVAL_NULL(null); /* We iterate through all the arrays at once. */ for (k = 0; k < maxlen; k++) { uint str_key_len; ulong num_key; char *str_key; int key_type = 0; /* If no callback, the result will be an array, consisting of current * entries from all arrays. */ if (!ZEND_FCI_INITIALIZED(fci)) { MAKE_STD_ZVAL(result); array_init_size(result, n_arrays); } for (i = 0; i < n_arrays; i++) { /* If this array still has elements, add the current one to the * parameter list, otherwise use null value. */ if (k < array_len[i]) { zend_hash_get_current_data_ex(Z_ARRVAL_P(args[i]), (void **)&params[i], &array_pos[i]); /* It is safe to store only last value of key type, because * this loop will run just once if there is only 1 array. */ if (n_arrays == 1) { key_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(args[0]), &str_key, &str_key_len, &num_key, 0, &array_pos[i]); } zend_hash_move_forward_ex(Z_ARRVAL_P(args[i]), &array_pos[i]); } else { params[i] = &null; } if (!ZEND_FCI_INITIALIZED(fci)) { zval_add_ref(params[i]); add_next_index_zval(result, *params[i]); } } if (ZEND_FCI_INITIALIZED(fci)) { fci.retval_ptr_ptr = &result; fci.param_count = n_arrays; fci.params = params; fci.no_separation = 0; if (zend_call_function(&fci, &fci_cache TSRMLS_CC) != SUCCESS || !result) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "An error occurred while invoking the map callback"); efree(array_len); efree(args); efree(array_pos); zval_dtor(return_value); zval_ptr_dtor(&null); efree(params); RETURN_NULL(); } } if (n_arrays > 1) { add_next_index_zval(return_value, result); } else { if (key_type == HASH_KEY_IS_STRING) { add_assoc_zval_ex(return_value, str_key, str_key_len, result); } else { add_index_zval(return_value, num_key, result); } } } zval_ptr_dtor(&null); efree(params); efree(array_len); efree(array_pos); efree(args); } /* }}} */ /* {{{ proto bool array_key_exists(mixed key, array search) Checks if the given key or index exists in the array */ PHP_FUNCTION(array_key_exists) { zval *key; /* key to check for */ HashTable *array; /* array to check in */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zH", &key, &array) == FAILURE) { return; } switch (Z_TYPE_P(key)) { case IS_STRING: if (zend_symtable_exists(array, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1)) { RETURN_TRUE; } RETURN_FALSE; case IS_LONG: if (zend_hash_index_exists(array, Z_LVAL_P(key))) { RETURN_TRUE; } RETURN_FALSE; case IS_NULL: if (zend_hash_exists(array, "", 1)) { RETURN_TRUE; } RETURN_FALSE; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "The first argument should be either a string or an integer"); RETURN_FALSE; } } /* }}} */ /* {{{ proto array array_chunk(array input, int size [, bool preserve_keys]) Split array into chunks */ PHP_FUNCTION(array_chunk) { int argc = ZEND_NUM_ARGS(), key_type, num_in; long size, current = 0; char *str_key; uint str_key_len; ulong num_key; zend_bool preserve_keys = 0; zval *input = NULL; zval *chunk = NULL; zval **entry; HashPosition pos; if (zend_parse_parameters(argc TSRMLS_CC, "al|b", &input, &size, &preserve_keys) == FAILURE) { return; } /* Do bounds checking for size parameter. */ if (size < 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Size parameter expected to be greater than 0"); return; } num_in = zend_hash_num_elements(Z_ARRVAL_P(input)); if (size > num_in) { size = num_in > 0 ? num_in : 1; } array_init_size(return_value, ((num_in - 1) / size) + 1); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void**)&entry, &pos) == SUCCESS) { /* If new chunk, create and initialize it. */ if (!chunk) { MAKE_STD_ZVAL(chunk); array_init_size(chunk, size); } /* Add entry to the chunk, preserving keys if necessary. */ zval_add_ref(entry); if (preserve_keys) { key_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(input), &str_key, &str_key_len, &num_key, 0, &pos); switch (key_type) { case HASH_KEY_IS_STRING: add_assoc_zval_ex(chunk, str_key, str_key_len, *entry); break; default: add_index_zval(chunk, num_key, *entry); break; } } else { add_next_index_zval(chunk, *entry); } /* If reached the chunk size, add it to the result array, and reset the * pointer. */ if (!(++current % size)) { add_next_index_zval(return_value, chunk); chunk = NULL; } zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos); } /* Add the final chunk if there is one. */ if (chunk) { add_next_index_zval(return_value, chunk); } } /* }}} */ /* {{{ proto array array_combine(array keys, array values) Creates an array by using the elements of the first parameter as keys and the elements of the second as the corresponding values */ PHP_FUNCTION(array_combine) { zval *values, *keys; HashPosition pos_values, pos_keys; zval **entry_keys, **entry_values; int num_keys, num_values; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "aa", &keys, &values) == FAILURE) { return; } num_keys = zend_hash_num_elements(Z_ARRVAL_P(keys)); num_values = zend_hash_num_elements(Z_ARRVAL_P(values)); if (num_keys != num_values) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Both parameters should have an equal number of elements"); RETURN_FALSE; } array_init_size(return_value, num_keys); if (!num_keys) { return; } zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(keys), &pos_keys); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(values), &pos_values); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(keys), (void **)&entry_keys, &pos_keys) == SUCCESS && zend_hash_get_current_data_ex(Z_ARRVAL_P(values), (void **)&entry_values, &pos_values) == SUCCESS ) { if (Z_TYPE_PP(entry_keys) == IS_LONG) { zval_add_ref(entry_values); add_index_zval(return_value, Z_LVAL_PP(entry_keys), *entry_values); } else { zval key, *key_ptr = *entry_keys; if (Z_TYPE_PP(entry_keys) != IS_STRING) { key = **entry_keys; zval_copy_ctor(&key); convert_to_string(&key); key_ptr = &key; } zval_add_ref(entry_values); add_assoc_zval_ex(return_value, Z_STRVAL_P(key_ptr), Z_STRLEN_P(key_ptr) + 1, *entry_values); if (key_ptr != *entry_keys) { zval_dtor(&key); } } zend_hash_move_forward_ex(Z_ARRVAL_P(keys), &pos_keys); zend_hash_move_forward_ex(Z_ARRVAL_P(values), &pos_values); } } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-04-06-18d71a6f59-187eb235fe.c
manybugs_data_31
/* Remote utility routines for the remote server for GDB. Copyright (C) 1986, 1989, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2011 Free Software Foundation, Inc. This file is part of GDB. It has been modified to integrate it in valgrind This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "pub_core_basics.h" #include "pub_core_vki.h" #include "pub_core_vkiscnums.h" #include "pub_core_libcsignal.h" #include "pub_core_options.h" #include "server.h" # if defined(VGO_linux) #include <sys/prctl.h> # endif Bool noack_mode; static int readchar (int single); void remote_utils_output_status(void); static int remote_desc; static VgdbShared *shared; static int last_looked_cntr = -1; static struct vki_pollfd remote_desc_pollfdread_activity; #define INVALID_DESCRIPTOR -1 /* for a gdbserver embedded in valgrind, we read from a FIFO and write to another FIFO So, we need two descriptors */ static int write_remote_desc = INVALID_DESCRIPTOR; static int pid_from_to_creator; /* only this pid will remove the FIFOs: if an exec fails, we must avoid that the exiting child believes it has to remove the FIFOs of its parent */ static int mknod_done = 0; static char *from_gdb = NULL; static char *to_gdb = NULL; static char *shared_mem = NULL; static int open_fifo (char *side, char *path, int flags) { SysRes o; int fd; dlog(1, "Opening %s side %s\n", side, path); o = VG_(open) (path, flags, 0); if (sr_isError (o)) { sr_perror(o, "open fifo %s\n", path); fatal ("valgrind: fatal error: vgdb FIFO cannot be opened.\n"); } else { fd = sr_Res(o); dlog(1, "result fd %d\n", fd); } fd = VG_(safe_fd)(fd); dlog(1, "result safe_fd %d\n", fd); if (fd == -1) fatal("safe_fd for vgdb FIFO failed\n"); return fd; } void remote_utils_output_status(void) { if (shared == NULL) VG_(umsg)("remote communication not initialized\n"); else VG_(umsg)("shared->written_by_vgdb %d shared->seen_by_valgrind %d\n", shared->written_by_vgdb, shared->seen_by_valgrind); } /* Returns 0 if vgdb and connection state looks good, otherwise returns an int value telling which check failed. */ static int vgdb_state_looks_bad(char* where) { if (VG_(kill)(shared->vgdb_pid, 0) != 0) return 1; // vgdb process does not exist anymore. if (remote_desc_activity(where) == 2) return 2; // check for error on remote desc shows a problem if (remote_desc == INVALID_DESCRIPTOR) return 3; // after check, remote_desc not ok anymore return 0; // all is ok. } /* On systems that defines PR_SET_PTRACER, verify if ptrace_scope is is permissive enough for vgdb. Otherwise, call set_ptracer. This is especially aimed at Ubuntu >= 10.10 which has added the ptrace_scope context. */ static void set_ptracer(void) { #ifdef PR_SET_PTRACER SysRes o; char *ptrace_scope_setting_file = "/proc/sys/kernel/yama/ptrace_scope"; int fd; char ptrace_scope; int ret; o = VG_(open) (ptrace_scope_setting_file, VKI_O_RDONLY, 0); if (sr_isError(o)) { if (VG_(debugLog_getLevel)() >= 1) { sr_perror(o, "error VG_(open) %s\n", ptrace_scope_setting_file); } /* can't read setting. Assuming ptrace can be called by vgdb. */ return; } fd = sr_Res(o); if (VG_(read) (fd, &ptrace_scope, 1) == 1) { dlog(1, "ptrace_scope %c\n", ptrace_scope); if (ptrace_scope != '0') { /* insufficient default ptrace_scope. Indicate to the kernel that we accept to be ptraced by our vgdb. */ ret = VG_(prctl) (PR_SET_PTRACER, shared->vgdb_pid, 0, 0, 0); dlog(1, "set_ptracer to vgdb_pid %d result %d\n", shared->vgdb_pid, ret); } } else { dlog(0, "Could not read the ptrace_scope setting from %s\n", ptrace_scope_setting_file); } VG_(close) (fd); #endif } /* returns 1 if one or more poll "errors" is set. Errors are: VKI_POLLERR or VKI_POLLHUP or VKI_POLLNAL */ static int poll_cond (short revents) { return (revents & (VKI_POLLERR | VKI_POLLHUP | VKI_POLLNVAL)); } /* Ensures we have a valid write file descriptor. Returns 1 if we have a valid write file descriptor, 0 if the write fd could not be opened. */ static int ensure_write_remote_desc(void) { struct vki_pollfd write_remote_desc_ok; int ret; if (write_remote_desc != INVALID_DESCRIPTOR) { write_remote_desc_ok.fd = write_remote_desc; write_remote_desc_ok.events = VKI_POLLOUT; write_remote_desc_ok.revents = 0; ret = VG_(poll)(&write_remote_desc_ok, 1, 0); if (ret && poll_cond(write_remote_desc_ok.revents)) { dlog(1, "POLLcond %d closing write_remote_desc %d\n", write_remote_desc_ok.revents, write_remote_desc); VG_(close) (write_remote_desc); write_remote_desc = INVALID_DESCRIPTOR; } } if (write_remote_desc == INVALID_DESCRIPTOR) { /* open_fifo write will block if the receiving vgdb process is dead. So, let's check for vgdb state to be reasonably sure someone is reading on the other side of the fifo. */ if (!vgdb_state_looks_bad("bad?@ensure_write_remote_desc")) { set_ptracer(); write_remote_desc = open_fifo ("write", to_gdb, VKI_O_WRONLY); } } return (write_remote_desc != INVALID_DESCRIPTOR); } #if defined(VGO_darwin) #define VKI_S_IFIFO 0010000 #endif static void safe_mknod (char *nod) { SysRes m; m = VG_(mknod) (nod, VKI_S_IFIFO|0666, 0); if (sr_isError (m)) { if (sr_Err (m) == VKI_EEXIST) { if (VG_(clo_verbosity) > 1) { VG_(umsg)("%s already created\n", nod); } } else { sr_perror(m, "mknod %s\n", nod); VG_(umsg) ("valgrind: fatal error: vgdb FIFOs cannot be created.\n"); VG_(exit)(1); } } } /* Open a connection to a remote debugger. NAME is the filename used for communication. For Valgrind, name is the prefix for the two read and write FIFOs The two FIFOs names will be build by appending -from-vgdb-to-pid and -to-vgdb-from-pid with pid being the pidnr of the valgrind process These two FIFOs will be created if not existing yet. They will be removed when the gdbserver connection is closed or the process exits */ void remote_open (char *name) { int save_fcntl_flags; VgdbShared vgdbinit = {0, 0, 0, (Addr) VG_(invoke_gdbserver), (Addr) VG_(threads), sizeof(ThreadState), offsetof(ThreadState, status), offsetof(ThreadState, os_state) + offsetof(ThreadOSstate, lwpid)}; const int pid = VG_(getpid)(); const int name_default = strcmp(name, VG_CLO_VGDB_PREFIX_DEFAULT) == 0; Addr addr_shared; SysRes o; int shared_mem_fd = INVALID_DESCRIPTOR; if (from_gdb != NULL) free (from_gdb); from_gdb = malloc (strlen(name) + 30); if (to_gdb != NULL) free (to_gdb); to_gdb = malloc (strlen(name) + 30); if (shared_mem != NULL) free (shared_mem); shared_mem = malloc (strlen(name) + 30); /* below 3 lines must match the equivalent in vgdb.c */ VG_(sprintf) (from_gdb, "%s-from-vgdb-to-%d", name, pid); VG_(sprintf) (to_gdb, "%s-to-vgdb-from-%d", name, pid); VG_(sprintf) (shared_mem, "%s-shared-mem-vgdb-%d", name, pid); if (VG_(clo_verbosity) > 1) { VG_(umsg)("embedded gdbserver: reading from %s\n", from_gdb); VG_(umsg)("embedded gdbserver: writing to %s\n", to_gdb); VG_(umsg)("embedded gdbserver: shared mem %s\n", shared_mem); VG_(umsg)("CONTROL ME using: vgdb --pid=%d%s%s ...command...\n", pid, (name_default ? "" : " --vgdb="), (name_default ? "" : name)); VG_(umsg)("DEBUG ME using: (gdb) target remote | vgdb --pid=%d%s%s\n", pid, (name_default ? "" : " --vgdb="), (name_default ? "" : name)); VG_(umsg)(" --pid optional if only one valgrind process is running\n"); } if (!mknod_done) { mknod_done++; safe_mknod(from_gdb); safe_mknod(to_gdb); pid_from_to_creator = pid; o = VG_(open) (shared_mem, VKI_O_CREAT|VKI_O_RDWR, 0666); if (sr_isError (o)) { sr_perror(o, "cannot create shared_mem file %s\n", shared_mem); fatal(""); } else { shared_mem_fd = sr_Res(o); } if (VG_(write)(shared_mem_fd, &vgdbinit, sizeof(VgdbShared)) != sizeof(VgdbShared)) { fatal("error writing %d bytes to shared mem %s\n", (int) sizeof(VgdbShared), shared_mem); } shared_mem_fd = VG_(safe_fd)(shared_mem_fd); if (shared_mem_fd == -1) { fatal("safe_fd for vgdb shared_mem %s failed\n", shared_mem); } { SysRes res = VG_(am_shared_mmap_file_float_valgrind) (sizeof(VgdbShared), VKI_PROT_READ|VKI_PROT_WRITE, shared_mem_fd, (Off64T)0); if (sr_isError(res)) { sr_perror(res, "error VG_(am_shared_mmap_file_float_valgrind) %s\n", shared_mem); fatal(""); } addr_shared = sr_Res (res); } shared = (VgdbShared*) addr_shared; } /* we open the read side FIFO in non blocking mode We then set the fd in blocking mode. Opening in non-blocking read mode always succeeds while opening in non-blocking write mode succeeds only if the fifo is already opened in read mode. So, we wait till we have read the first character from the read side before opening the write side. */ remote_desc = open_fifo ("read", from_gdb, VKI_O_RDONLY|VKI_O_NONBLOCK); save_fcntl_flags = VG_(fcntl) (remote_desc, VKI_F_GETFL, 0); VG_(fcntl) (remote_desc, VKI_F_SETFL, save_fcntl_flags & ~VKI_O_NONBLOCK); remote_desc_pollfdread_activity.fd = remote_desc; remote_desc_pollfdread_activity.events = VKI_POLLIN; remote_desc_pollfdread_activity.revents = 0; } /* sync_gdb_connection wait a time long enough to let the connection be properly closed if needed when closing the connection (in case of detach or error), if we reopen it too quickly, it seems there are some events queued in the kernel concerning the "old" connection/remote_desc which are discovered with poll or select on the "new" connection/remote_desc. We bypass this by waiting some time to let a proper cleanup to be donex */ void sync_gdb_connection(void) { VG_(poll)(0, 0, 100); } static char * ppFinishReason (FinishReason reason) { switch (reason) { case orderly_finish: return "orderly_finish"; case reset_after_error: return "reset_after_error"; case reset_after_fork: return "reset_after_fork"; default: vg_assert (0); } } void remote_finish (FinishReason reason) { dlog(1, "remote_finish (reason %s) %d %d\n", ppFinishReason(reason), remote_desc, write_remote_desc); reset_valgrind_sink(ppFinishReason(reason)); if (write_remote_desc != INVALID_DESCRIPTOR) VG_(close) (write_remote_desc); write_remote_desc = INVALID_DESCRIPTOR; if (remote_desc != INVALID_DESCRIPTOR) { remote_desc_pollfdread_activity.fd = INVALID_DESCRIPTOR; remote_desc_pollfdread_activity.events = 0; remote_desc_pollfdread_activity.revents = 0; VG_(close) (remote_desc); } remote_desc = INVALID_DESCRIPTOR; noack_mode = False; /* ensure the child will create its own FIFOs */ if (reason == reset_after_fork) mknod_done = 0; if (reason == reset_after_error) sync_gdb_connection(); } /* orderly close, cleans up everything */ void remote_close (void) { const int pid = VG_(getpid)(); remote_finish(orderly_finish); if (pid == pid_from_to_creator) { dlog(1, "unlinking\n %s\n %s\n %s\n", from_gdb, to_gdb, shared_mem); if (VG_(unlink) (from_gdb) == -1) warning ("could not unlink %s\n", from_gdb); if (VG_(unlink) (to_gdb) == -1) warning ("could not unlink %s\n", to_gdb); if (VG_(unlink) (shared_mem) == -1) warning ("could not unlink %s\n", shared_mem); } else { dlog(1, "not creator => not unlinking %s and %s\n", from_gdb, to_gdb); } free (from_gdb); free (to_gdb); } Bool remote_connected(void) { return write_remote_desc != INVALID_DESCRIPTOR; } /* cleanup after an error detected by poll_cond */ static void error_poll_cond(void) { /* if we will close the connection, we assume either that all characters have been seen or that they will be dropped. */ shared->seen_by_valgrind = shared->written_by_vgdb; remote_finish(reset_after_error); } /* remote_desc_activity might be used at high frequency if the user gives a small value to --vgdb-poll. So, the function avoids doing repetitively system calls by rather looking at the counter values maintained in shared memory by vgdb. */ int remote_desc_activity(char *msg) { int ret; const int looking_at = shared->written_by_vgdb; if (shared->seen_by_valgrind == looking_at) // if (last_looked_cntr == looking_at) return 0; if (remote_desc == INVALID_DESCRIPTOR) return 0; /* poll the remote desc */ remote_desc_pollfdread_activity.revents = 0; ret = VG_(poll) (&remote_desc_pollfdread_activity, 1, 0); if (ret && poll_cond(remote_desc_pollfdread_activity.revents)) { dlog(1, "POLLcond %d remote_desc_pollfdread %d\n", remote_desc_pollfdread_activity.revents, remote_desc); error_poll_cond(); ret = 2; } dlog(1, "remote_desc_activity %s %d last_looked_cntr %d looking_at %d" " shared->written_by_vgdb %d shared->seen_by_valgrind %d" " ret %d\n", msg, remote_desc, last_looked_cntr, looking_at, shared->written_by_vgdb, shared->seen_by_valgrind, ret); /* if no error from poll, indicate we have "seen" up to looking_at */ if (ret != 2) last_looked_cntr = looking_at; return ret; } /* Convert hex digit A to a number. */ static int fromhex (int a) { if (a >= '0' && a <= '9') return a - '0'; else if (a >= 'a' && a <= 'f') return a - 'a' + 10; else error ("Reply contains invalid hex digit 0x%x\n", a); return 0; } int unhexify (char *bin, const char *hex, int count) { int i; for (i = 0; i < count; i++) { if (hex[0] == 0 || hex[1] == 0) { /* Hex string is short, or of uneven length. Return the count that has been converted so far. */ return i; } *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]); hex += 2; } return i; } void decode_address (CORE_ADDR *addrp, const char *start, int len) { CORE_ADDR addr; char ch; int i; addr = 0; for (i = 0; i < len; i++) { ch = start[i]; addr = addr << 4; addr = addr | (fromhex (ch) & 0x0f); } *addrp = addr; } /* Convert number NIB to a hex digit. */ static int tohex (int nib) { if (nib < 10) return '0' + nib; else return 'a' + nib - 10; } int hexify (char *hex, const char *bin, int count) { int i; /* May use a length, or a nul-terminated string as input. */ if (count == 0) count = strlen (bin); for (i = 0; i < count; i++) { *hex++ = tohex ((*bin >> 4) & 0xf); *hex++ = tohex (*bin++ & 0xf); } *hex = 0; return i; } /* Convert BUFFER, binary data at least LEN bytes long, into escaped binary data in OUT_BUF. Set *OUT_LEN to the length of the data encoded in OUT_BUF, and return the number of bytes in OUT_BUF (which may be more than *OUT_LEN due to escape characters). The total number of bytes in the output buffer will be at most OUT_MAXLEN. */ int remote_escape_output (const gdb_byte *buffer, int len, gdb_byte *out_buf, int *out_len, int out_maxlen) { int input_index, output_index; output_index = 0; for (input_index = 0; input_index < len; input_index++) { gdb_byte b = buffer[input_index]; if (b == '$' || b == '#' || b == '}' || b == '*') { /* These must be escaped. */ if (output_index + 2 > out_maxlen) break; out_buf[output_index++] = '}'; out_buf[output_index++] = b ^ 0x20; } else { if (output_index + 1 > out_maxlen) break; out_buf[output_index++] = b; } } *out_len = input_index; return output_index; } /* Convert BUFFER, escaped data LEN bytes long, into binary data in OUT_BUF. Return the number of bytes written to OUT_BUF. Raise an error if the total number of bytes exceeds OUT_MAXLEN. This function reverses remote_escape_output. It allows more escaped characters than that function does, in particular because '*' must be escaped to avoid the run-length encoding processing in reading packets. */ static int remote_unescape_input (const gdb_byte *buffer, int len, gdb_byte *out_buf, int out_maxlen) { int input_index, output_index; int escaped; output_index = 0; escaped = 0; for (input_index = 0; input_index < len; input_index++) { gdb_byte b = buffer[input_index]; if (output_index + 1 > out_maxlen) error ("Received too much data (len %d) from the target.\n", len); if (escaped) { out_buf[output_index++] = b ^ 0x20; escaped = 0; } else if (b == '}') { escaped = 1; } else { out_buf[output_index++] = b; } } if (escaped) error ("Unmatched escape character in target response.\n"); return output_index; } /* Look for a sequence of characters which can be run-length encoded. If there are any, update *CSUM and *P. Otherwise, output the single character. Return the number of characters consumed. */ static int try_rle (char *buf, int remaining, unsigned char *csum, char **p) { int n; /* Always output the character. */ *csum += buf[0]; *(*p)++ = buf[0]; /* Don't go past '~'. */ if (remaining > 97) remaining = 97; for (n = 1; n < remaining; n++) if (buf[n] != buf[0]) break; /* N is the index of the first character not the same as buf[0]. buf[0] is counted twice, so by decrementing N, we get the number of characters the RLE sequence will replace. */ n--; if (n < 3) return 1; /* Skip the frame characters. The manual says to skip '+' and '-' also, but there's no reason to. Unfortunately these two unusable characters double the encoded length of a four byte zero value. */ while (n + 29 == '$' || n + 29 == '#') n--; *csum += '*'; *(*p)++ = '*'; *csum += n + 29; *(*p)++ = n + 29; return n + 1; } /* Send a packet to the remote machine, with error checking. The data of the packet is in BUF, and the length of the packet is in CNT. Returns >= 0 on success, -1 otherwise. */ int putpkt_binary (char *buf, int cnt) { int i; unsigned char csum = 0; char *buf2; char *p; int cc; buf2 = malloc (PBUFSIZ); /* Copy the packet into buffer BUF2, encapsulating it and giving it a checksum. */ p = buf2; *p++ = '$'; for (i = 0; i < cnt;) i += try_rle (buf + i, cnt - i, &csum, &p); *p++ = '#'; *p++ = tohex ((csum >> 4) & 0xf); *p++ = tohex (csum & 0xf); *p = '\0'; /* we might have to write a pkt when out FIFO not yet/anymore opened */ if (!ensure_write_remote_desc()) { warning ("putpkt(write) error: no write_remote_desc\n"); return -1; } /* Send it once (noack_mode) or send it over and over until we get a positive ack. */ do { if (VG_(write) (write_remote_desc, buf2, p - buf2) != p - buf2) { warning ("putpkt(write) error\n"); return -1; } if (noack_mode) dlog(1, "putpkt (\"%s\"); [no ack]\n", buf2); else dlog(1,"putpkt (\"%s\"); [looking for ack]\n", buf2); if (noack_mode) break; cc = readchar (1); if (cc > 0) dlog(1, "[received '%c' (0x%x)]\n", cc, cc); if (cc <= 0) { if (cc == 0) dlog(1, "putpkt(read): Got EOF\n"); else warning ("putpkt(read) error\n"); free (buf2); return -1; } /* Check for an input interrupt while we're here. */ if (cc == '\003') (*the_target->send_signal) (VKI_SIGINT); } while (cc != '+'); free (buf2); return 1; /* Success! */ } /* Send a packet to the remote machine, with error checking. The data of the packet is in BUF, and the packet should be a NUL-terminated string. Returns >= 0 on success, -1 otherwise. */ int putpkt (char *buf) { return putpkt_binary (buf, strlen (buf)); } void monitor_output (char *s) { const int len = strlen(s); char *buf = malloc(1 + 2*len + 1); buf[0] = 'O'; hexify(buf+1, s, len); if (putpkt (buf) < 0) { /* We probably have lost the connection with vgdb. */ reset_valgrind_sink("Error writing monitor output"); /* write again after reset */ VG_(printf) ("%s", s); } free (buf); } /* Returns next char from remote GDB. -1 if error. */ /* if single, only one character maximum can be read with read system call. Otherwise, when reading an ack character we might pile up the next gdb command in the static buf. The read loop is then blocked in poll till gdb times out. */ static int readchar (int single) { static unsigned char buf[PBUFSIZ]; static int bufcnt = 0; static unsigned char *bufp; int ret; if (bufcnt-- > 0) return *bufp++; if (remote_desc == INVALID_DESCRIPTOR) return -1; /* No characters available in buf => wait for some characters to arrive */ remote_desc_pollfdread_activity.revents = 0; ret = VG_(poll)(&remote_desc_pollfdread_activity, 1, -1); if (ret != 1) { dlog(0, "readchar: poll got %d\n", ret); return -1; } if (single) bufcnt = VG_(read) (remote_desc, buf, 1); else bufcnt = VG_(read) (remote_desc, buf, sizeof (buf)); if (bufcnt <= 0) { if (bufcnt == 0) dlog (1, "readchar: Got EOF\n"); else warning ("readchar read error\n"); return -1; } shared->seen_by_valgrind += bufcnt; /* If we have received a character and we do not yet have a connection, we better open our "write" fifo to let vgdb open its read fifo side */ if (write_remote_desc == INVALID_DESCRIPTOR && !ensure_write_remote_desc()) { dlog(1, "reachar: write_remote_desc could not be created"); } bufp = buf; bufcnt--; if (poll_cond(remote_desc_pollfdread_activity.revents)) { dlog(1, "readchar: POLLcond got %d\n", remote_desc_pollfdread_activity.revents); error_poll_cond(); } return *bufp++; } /* Read a packet from the remote machine, with error checking, and store it in BUF. Returns length of packet, or negative if error. */ int getpkt (char *buf) { char *bp; unsigned char csum, c1, c2; int c; while (1) { csum = 0; while (1) { c = readchar (0); if (c == '$') break; dlog(1, "[getpkt: discarding char '%c']\n", c); if (c < 0) return -1; } bp = buf; while (1) { c = readchar (0); if (c < 0) return -1; if (c == '#') break; *bp++ = c; csum += c; } *bp = 0; c1 = fromhex (readchar (0)); c2 = fromhex (readchar (0)); if (csum == (c1 << 4) + c2) break; dlog (0, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n", (c1 << 4) + c2, csum, buf); if (!ensure_write_remote_desc()) { dlog(1, "getpkt(write nack) no write_remote_desc"); } VG_(write) (write_remote_desc, "-", 1); } if (noack_mode) dlog(1, "getpkt (\"%s\"); [no ack] \n", buf); else dlog(1, "getpkt (\"%s\"); [sending ack] \n", buf); if (!noack_mode) { if (!ensure_write_remote_desc()) { dlog(1, "getpkt(write ack) no write_remote_desc"); } VG_(write) (write_remote_desc, "+", 1); dlog(1, "[sent ack]\n"); } return bp - buf; } void write_ok (char *buf) { buf[0] = 'O'; buf[1] = 'K'; buf[2] = '\0'; } void write_enn (char *buf) { /* Some day, we should define the meanings of the error codes... */ buf[0] = 'E'; buf[1] = '0'; buf[2] = '1'; buf[3] = '\0'; } void convert_int_to_ascii (unsigned char *from, char *to, int n) { int nib; int ch; while (n--) { ch = *from++; nib = ((ch & 0xf0) >> 4) & 0x0f; *to++ = tohex (nib); nib = ch & 0x0f; *to++ = tohex (nib); } *to++ = 0; } void convert_ascii_to_int (char *from, unsigned char *to, int n) { int nib1, nib2; while (n--) { nib1 = fromhex (*from++); nib2 = fromhex (*from++); *to++ = (((nib1 & 0x0f) << 4) & 0xf0) | (nib2 & 0x0f); } } static char * outreg (int regno, char *buf) { if ((regno >> 12) != 0) *buf++ = tohex ((regno >> 12) & 0xf); if ((regno >> 8) != 0) *buf++ = tohex ((regno >> 8) & 0xf); *buf++ = tohex ((regno >> 4) & 0xf); *buf++ = tohex (regno & 0xf); *buf++ = ':'; collect_register_as_string (regno, buf); buf += 2 * register_size (regno); *buf++ = ';'; return buf; } void prepare_resume_reply (char *buf, char status, unsigned char sig) { int nib; *buf++ = status; nib = ((sig & 0xf0) >> 4); *buf++ = tohex (nib); nib = sig & 0x0f; *buf++ = tohex (nib); if (status == 'T') { const char **regp = gdbserver_expedite_regs; if (the_target->stopped_by_watchpoint != NULL && (*the_target->stopped_by_watchpoint) ()) { CORE_ADDR addr; int i; strncpy (buf, "watch:", 6); buf += 6; addr = (*the_target->stopped_data_address) (); /* Convert each byte of the address into two hexadecimal chars. Note that we take sizeof (void *) instead of sizeof (addr); this is to avoid sending a 64-bit address to a 32-bit GDB. */ for (i = sizeof (void *) * 2; i > 0; i--) { *buf++ = tohex ((addr >> (i - 1) * 4) & 0xf); } *buf++ = ';'; } while (*regp) { buf = outreg (find_regno (*regp), buf); regp ++; } { unsigned int gdb_id_from_wait; /* FIXME right place to set this? */ thread_from_wait = ((struct inferior_list_entry *)current_inferior)->id; gdb_id_from_wait = thread_to_gdb_id (current_inferior); dlog(1, "Writing resume reply for %ld\n", thread_from_wait); /* This if (1) ought to be unnecessary. But remote_wait in GDB will claim this event belongs to inferior_ptid if we do not specify a thread, and there's no way for gdbserver to know what inferior_ptid is. */ if (1 || old_thread_from_wait != thread_from_wait) { general_thread = thread_from_wait; VG_(sprintf) (buf, "thread:%x;", gdb_id_from_wait); buf += strlen (buf); old_thread_from_wait = thread_from_wait; } } } /* For W and X, we're done. */ *buf++ = 0; } void decode_m_packet (char *from, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr) { int i = 0, j = 0; char ch; *mem_addr_ptr = *len_ptr = 0; while ((ch = from[i++]) != ',') { *mem_addr_ptr = *mem_addr_ptr << 4; *mem_addr_ptr |= fromhex (ch) & 0x0f; } for (j = 0; j < 4; j++) { if ((ch = from[i++]) == 0) break; *len_ptr = *len_ptr << 4; *len_ptr |= fromhex (ch) & 0x0f; } } void decode_M_packet (char *from, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr, unsigned char *to) { int i = 0; char ch; *mem_addr_ptr = *len_ptr = 0; while ((ch = from[i++]) != ',') { *mem_addr_ptr = *mem_addr_ptr << 4; *mem_addr_ptr |= fromhex (ch) & 0x0f; } while ((ch = from[i++]) != ':') { *len_ptr = *len_ptr << 4; *len_ptr |= fromhex (ch) & 0x0f; } convert_ascii_to_int (&from[i++], to, *len_ptr); } int decode_X_packet (char *from, int packet_len, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr, unsigned char *to) { int i = 0; char ch; *mem_addr_ptr = *len_ptr = 0; while ((ch = from[i++]) != ',') { *mem_addr_ptr = *mem_addr_ptr << 4; *mem_addr_ptr |= fromhex (ch) & 0x0f; } while ((ch = from[i++]) != ':') { *len_ptr = *len_ptr << 4; *len_ptr |= fromhex (ch) & 0x0f; } if (remote_unescape_input ((const gdb_byte *) &from[i], packet_len - i, to, *len_ptr) != *len_ptr) return -1; return 0; } /* Remote utility routines for the remote server for GDB. Copyright (C) 1986, 1989, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2011 Free Software Foundation, Inc. This file is part of GDB. It has been modified to integrate it in valgrind This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "pub_core_basics.h" #include "pub_core_vki.h" #include "pub_core_vkiscnums.h" #include "pub_core_libcsignal.h" #include "pub_core_options.h" #include "server.h" # if defined(VGO_linux) #include <sys/prctl.h> # endif Bool noack_mode; static int readchar (int single); void remote_utils_output_status(void); static int remote_desc; static VgdbShared *shared; static int last_looked_cntr = -1; static struct vki_pollfd remote_desc_pollfdread_activity; #define INVALID_DESCRIPTOR -1 /* for a gdbserver embedded in valgrind, we read from a FIFO and write to another FIFO So, we need two descriptors */ static int write_remote_desc = INVALID_DESCRIPTOR; static int pid_from_to_creator; /* only this pid will remove the FIFOs: if an exec fails, we must avoid that the exiting child believes it has to remove the FIFOs of its parent */ static int mknod_done = 0; static char *from_gdb = NULL; static char *to_gdb = NULL; static char *shared_mem = NULL; static int open_fifo (char *side, char *path, int flags) { SysRes o; int fd; dlog(1, "Opening %s side %s\n", side, path); o = VG_(open) (path, flags, 0); if (sr_isError (o)) { sr_perror(o, "open fifo %s\n", path); fatal ("valgrind: fatal error: vgdb FIFO cannot be opened.\n"); } else { fd = sr_Res(o); dlog(1, "result fd %d\n", fd); } fd = VG_(safe_fd)(fd); dlog(1, "result safe_fd %d\n", fd); if (fd == -1) fatal("safe_fd for vgdb FIFO failed\n"); return fd; } void remote_utils_output_status(void) { if (shared == NULL) VG_(umsg)("remote communication not initialized\n"); else VG_(umsg)("shared->written_by_vgdb %d shared->seen_by_valgrind %d\n", shared->written_by_vgdb, shared->seen_by_valgrind); } /* Returns 0 if vgdb and connection state looks good, otherwise returns an int value telling which check failed. */ static int vgdb_state_looks_bad(char* where) { if (VG_(kill)(shared->vgdb_pid, 0) != 0) return 1; // vgdb process does not exist anymore. if (remote_desc_activity(where) == 2) return 2; // check for error on remote desc shows a problem if (remote_desc == INVALID_DESCRIPTOR) return 3; // after check, remote_desc not ok anymore return 0; // all is ok. } /* On systems that defines PR_SET_PTRACER, verify if ptrace_scope is is permissive enough for vgdb. Otherwise, call set_ptracer. This is especially aimed at Ubuntu >= 10.10 which has added the ptrace_scope context. */ static void set_ptracer(void) { #ifdef PR_SET_PTRACER SysRes o; char *ptrace_scope_setting_file = "/proc/sys/kernel/yama/ptrace_scope"; int fd; char ptrace_scope; int ret; o = VG_(open) (ptrace_scope_setting_file, VKI_O_RDONLY, 0); if (sr_isError(o)) { if (VG_(debugLog_getLevel)() >= 1) { sr_perror(o, "error VG_(open) %s\n", ptrace_scope_setting_file); } /* can't read setting. Assuming ptrace can be called by vgdb. */ return; } fd = sr_Res(o); if (VG_(read) (fd, &ptrace_scope, 1) == 1) { dlog(1, "ptrace_scope %c\n", ptrace_scope); if (ptrace_scope != '0') { /* insufficient default ptrace_scope. Indicate to the kernel that we accept to be ptraced by our vgdb. */ ret = VG_(prctl) (PR_SET_PTRACER, shared->vgdb_pid, 0, 0, 0); dlog(1, "set_ptracer to vgdb_pid %d result %d\n", shared->vgdb_pid, ret); } } else { dlog(0, "Could not read the ptrace_scope setting from %s\n", ptrace_scope_setting_file); } VG_(close) (fd); #endif } /* returns 1 if one or more poll "errors" is set. Errors are: VKI_POLLERR or VKI_POLLHUP or VKI_POLLNAL */ static int poll_cond (short revents) { return (revents & (VKI_POLLERR | VKI_POLLHUP | VKI_POLLNVAL)); } /* Ensures we have a valid write file descriptor. Returns 1 if we have a valid write file descriptor, 0 if the write fd could not be opened. */ static int ensure_write_remote_desc(void) { struct vki_pollfd write_remote_desc_ok; int ret; if (write_remote_desc != INVALID_DESCRIPTOR) { write_remote_desc_ok.fd = write_remote_desc; write_remote_desc_ok.events = VKI_POLLOUT; write_remote_desc_ok.revents = 0; ret = VG_(poll)(&write_remote_desc_ok, 1, 0); if (ret && poll_cond(write_remote_desc_ok.revents)) { dlog(1, "POLLcond %d closing write_remote_desc %d\n", write_remote_desc_ok.revents, write_remote_desc); VG_(close) (write_remote_desc); write_remote_desc = INVALID_DESCRIPTOR; } } if (write_remote_desc == INVALID_DESCRIPTOR) { /* open_fifo write will block if the receiving vgdb process is dead. So, let's check for vgdb state to be reasonably sure someone is reading on the other side of the fifo. */ if (!vgdb_state_looks_bad("bad?@ensure_write_remote_desc")) { set_ptracer(); write_remote_desc = open_fifo ("write", to_gdb, VKI_O_WRONLY); } } return (write_remote_desc != INVALID_DESCRIPTOR); } #if defined(VGO_darwin) #define VKI_S_IFIFO 0010000 #endif static void safe_mknod (char *nod) { SysRes m; m = VG_(mknod) (nod, VKI_S_IFIFO|0666, 0); if (sr_isError (m)) { if (sr_Err (m) == VKI_EEXIST) { if (VG_(clo_verbosity) > 1) { VG_(umsg)("%s already created\n", nod); } } else { sr_perror(m, "mknod %s\n", nod); VG_(umsg) ("valgrind: fatal error: vgdb FIFOs cannot be created.\n"); VG_(exit)(1); } } } /* Open a connection to a remote debugger. NAME is the filename used for communication. For Valgrind, name is the prefix for the two read and write FIFOs The two FIFOs names will be build by appending -from-vgdb-to-pid and -to-vgdb-from-pid with pid being the pidnr of the valgrind process These two FIFOs will be created if not existing yet. They will be removed when the gdbserver connection is closed or the process exits */ void remote_open (char *name) { int save_fcntl_flags; VgdbShared vgdbinit = {0, 0, 0, (Addr) VG_(invoke_gdbserver), (Addr) VG_(threads), sizeof(ThreadState), offsetof(ThreadState, status), offsetof(ThreadState, os_state) + offsetof(ThreadOSstate, lwpid)}; const int pid = VG_(getpid)(); const int name_default = strcmp(name, VG_CLO_VGDB_PREFIX_DEFAULT) == 0; Addr addr_shared; SysRes o; int shared_mem_fd = INVALID_DESCRIPTOR; if (from_gdb != NULL) free (from_gdb); from_gdb = malloc (strlen(name) + 30); if (to_gdb != NULL) free (to_gdb); to_gdb = malloc (strlen(name) + 30); if (shared_mem != NULL) free (shared_mem); shared_mem = malloc (strlen(name) + 30); /* below 3 lines must match the equivalent in vgdb.c */ VG_(sprintf) (from_gdb, "%s-from-vgdb-to-%d", name, pid); VG_(sprintf) (to_gdb, "%s-to-vgdb-from-%d", name, pid); VG_(sprintf) (shared_mem, "%s-shared-mem-vgdb-%d", name, pid); if (VG_(clo_verbosity) > 1) { VG_(umsg)("embedded gdbserver: reading from %s\n", from_gdb); VG_(umsg)("embedded gdbserver: writing to %s\n", to_gdb); VG_(umsg)("embedded gdbserver: shared mem %s\n", shared_mem); VG_(umsg)("CONTROL ME using: vgdb --pid=%d%s%s ...command...\n", pid, (name_default ? "" : " --vgdb="), (name_default ? "" : name)); VG_(umsg)("DEBUG ME using: (gdb) target remote | vgdb --pid=%d%s%s\n", pid, (name_default ? "" : " --vgdb="), (name_default ? "" : name)); VG_(umsg)(" --pid optional if only one valgrind process is running\n"); } if (!mknod_done) { mknod_done++; safe_mknod(from_gdb); safe_mknod(to_gdb); pid_from_to_creator = pid; o = VG_(open) (shared_mem, VKI_O_CREAT|VKI_O_RDWR, 0666); if (sr_isError (o)) { sr_perror(o, "cannot create shared_mem file %s\n", shared_mem); fatal(""); } else { shared_mem_fd = sr_Res(o); } if (VG_(write)(shared_mem_fd, &vgdbinit, sizeof(VgdbShared)) != sizeof(VgdbShared)) { fatal("error writing %d bytes to shared mem %s\n", (int) sizeof(VgdbShared), shared_mem); } { SysRes res = VG_(am_shared_mmap_file_float_valgrind) (sizeof(VgdbShared), VKI_PROT_READ|VKI_PROT_WRITE, shared_mem_fd, (Off64T)0); if (sr_isError(res)) { sr_perror(res, "error VG_(am_shared_mmap_file_float_valgrind) %s\n", shared_mem); fatal(""); } addr_shared = sr_Res (res); } shared = (VgdbShared*) addr_shared; VG_(close) (shared_mem_fd); } /* we open the read side FIFO in non blocking mode We then set the fd in blocking mode. Opening in non-blocking read mode always succeeds while opening in non-blocking write mode succeeds only if the fifo is already opened in read mode. So, we wait till we have read the first character from the read side before opening the write side. */ remote_desc = open_fifo ("read", from_gdb, VKI_O_RDONLY|VKI_O_NONBLOCK); save_fcntl_flags = VG_(fcntl) (remote_desc, VKI_F_GETFL, 0); VG_(fcntl) (remote_desc, VKI_F_SETFL, save_fcntl_flags & ~VKI_O_NONBLOCK); remote_desc_pollfdread_activity.fd = remote_desc; remote_desc_pollfdread_activity.events = VKI_POLLIN; remote_desc_pollfdread_activity.revents = 0; } /* sync_gdb_connection wait a time long enough to let the connection be properly closed if needed when closing the connection (in case of detach or error), if we reopen it too quickly, it seems there are some events queued in the kernel concerning the "old" connection/remote_desc which are discovered with poll or select on the "new" connection/remote_desc. We bypass this by waiting some time to let a proper cleanup to be donex */ void sync_gdb_connection(void) { VG_(poll)(0, 0, 100); } static char * ppFinishReason (FinishReason reason) { switch (reason) { case orderly_finish: return "orderly_finish"; case reset_after_error: return "reset_after_error"; case reset_after_fork: return "reset_after_fork"; default: vg_assert (0); } } void remote_finish (FinishReason reason) { dlog(1, "remote_finish (reason %s) %d %d\n", ppFinishReason(reason), remote_desc, write_remote_desc); reset_valgrind_sink(ppFinishReason(reason)); if (write_remote_desc != INVALID_DESCRIPTOR) VG_(close) (write_remote_desc); write_remote_desc = INVALID_DESCRIPTOR; if (remote_desc != INVALID_DESCRIPTOR) { remote_desc_pollfdread_activity.fd = INVALID_DESCRIPTOR; remote_desc_pollfdread_activity.events = 0; remote_desc_pollfdread_activity.revents = 0; VG_(close) (remote_desc); } remote_desc = INVALID_DESCRIPTOR; noack_mode = False; /* ensure the child will create its own FIFOs */ if (reason == reset_after_fork) mknod_done = 0; if (reason == reset_after_error) sync_gdb_connection(); } /* orderly close, cleans up everything */ void remote_close (void) { const int pid = VG_(getpid)(); remote_finish(orderly_finish); if (pid == pid_from_to_creator) { dlog(1, "unlinking\n %s\n %s\n %s\n", from_gdb, to_gdb, shared_mem); if (VG_(unlink) (from_gdb) == -1) warning ("could not unlink %s\n", from_gdb); if (VG_(unlink) (to_gdb) == -1) warning ("could not unlink %s\n", to_gdb); if (VG_(unlink) (shared_mem) == -1) warning ("could not unlink %s\n", shared_mem); } else { dlog(1, "not creator => not unlinking %s and %s\n", from_gdb, to_gdb); } free (from_gdb); free (to_gdb); } Bool remote_connected(void) { return write_remote_desc != INVALID_DESCRIPTOR; } /* cleanup after an error detected by poll_cond */ static void error_poll_cond(void) { /* if we will close the connection, we assume either that all characters have been seen or that they will be dropped. */ shared->seen_by_valgrind = shared->written_by_vgdb; remote_finish(reset_after_error); } /* remote_desc_activity might be used at high frequency if the user gives a small value to --vgdb-poll. So, the function avoids doing repetitively system calls by rather looking at the counter values maintained in shared memory by vgdb. */ int remote_desc_activity(char *msg) { int ret; const int looking_at = shared->written_by_vgdb; if (shared->seen_by_valgrind == looking_at) // if (last_looked_cntr == looking_at) return 0; if (remote_desc == INVALID_DESCRIPTOR) return 0; /* poll the remote desc */ remote_desc_pollfdread_activity.revents = 0; ret = VG_(poll) (&remote_desc_pollfdread_activity, 1, 0); if (ret && poll_cond(remote_desc_pollfdread_activity.revents)) { dlog(1, "POLLcond %d remote_desc_pollfdread %d\n", remote_desc_pollfdread_activity.revents, remote_desc); error_poll_cond(); ret = 2; } dlog(1, "remote_desc_activity %s %d last_looked_cntr %d looking_at %d" " shared->written_by_vgdb %d shared->seen_by_valgrind %d" " ret %d\n", msg, remote_desc, last_looked_cntr, looking_at, shared->written_by_vgdb, shared->seen_by_valgrind, ret); /* if no error from poll, indicate we have "seen" up to looking_at */ if (ret != 2) last_looked_cntr = looking_at; return ret; } /* Convert hex digit A to a number. */ static int fromhex (int a) { if (a >= '0' && a <= '9') return a - '0'; else if (a >= 'a' && a <= 'f') return a - 'a' + 10; else error ("Reply contains invalid hex digit 0x%x\n", a); return 0; } int unhexify (char *bin, const char *hex, int count) { int i; for (i = 0; i < count; i++) { if (hex[0] == 0 || hex[1] == 0) { /* Hex string is short, or of uneven length. Return the count that has been converted so far. */ return i; } *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]); hex += 2; } return i; } void decode_address (CORE_ADDR *addrp, const char *start, int len) { CORE_ADDR addr; char ch; int i; addr = 0; for (i = 0; i < len; i++) { ch = start[i]; addr = addr << 4; addr = addr | (fromhex (ch) & 0x0f); } *addrp = addr; } /* Convert number NIB to a hex digit. */ static int tohex (int nib) { if (nib < 10) return '0' + nib; else return 'a' + nib - 10; } int hexify (char *hex, const char *bin, int count) { int i; /* May use a length, or a nul-terminated string as input. */ if (count == 0) count = strlen (bin); for (i = 0; i < count; i++) { *hex++ = tohex ((*bin >> 4) & 0xf); *hex++ = tohex (*bin++ & 0xf); } *hex = 0; return i; } /* Convert BUFFER, binary data at least LEN bytes long, into escaped binary data in OUT_BUF. Set *OUT_LEN to the length of the data encoded in OUT_BUF, and return the number of bytes in OUT_BUF (which may be more than *OUT_LEN due to escape characters). The total number of bytes in the output buffer will be at most OUT_MAXLEN. */ int remote_escape_output (const gdb_byte *buffer, int len, gdb_byte *out_buf, int *out_len, int out_maxlen) { int input_index, output_index; output_index = 0; for (input_index = 0; input_index < len; input_index++) { gdb_byte b = buffer[input_index]; if (b == '$' || b == '#' || b == '}' || b == '*') { /* These must be escaped. */ if (output_index + 2 > out_maxlen) break; out_buf[output_index++] = '}'; out_buf[output_index++] = b ^ 0x20; } else { if (output_index + 1 > out_maxlen) break; out_buf[output_index++] = b; } } *out_len = input_index; return output_index; } /* Convert BUFFER, escaped data LEN bytes long, into binary data in OUT_BUF. Return the number of bytes written to OUT_BUF. Raise an error if the total number of bytes exceeds OUT_MAXLEN. This function reverses remote_escape_output. It allows more escaped characters than that function does, in particular because '*' must be escaped to avoid the run-length encoding processing in reading packets. */ static int remote_unescape_input (const gdb_byte *buffer, int len, gdb_byte *out_buf, int out_maxlen) { int input_index, output_index; int escaped; output_index = 0; escaped = 0; for (input_index = 0; input_index < len; input_index++) { gdb_byte b = buffer[input_index]; if (output_index + 1 > out_maxlen) error ("Received too much data (len %d) from the target.\n", len); if (escaped) { out_buf[output_index++] = b ^ 0x20; escaped = 0; } else if (b == '}') { escaped = 1; } else { out_buf[output_index++] = b; } } if (escaped) error ("Unmatched escape character in target response.\n"); return output_index; } /* Look for a sequence of characters which can be run-length encoded. If there are any, update *CSUM and *P. Otherwise, output the single character. Return the number of characters consumed. */ static int try_rle (char *buf, int remaining, unsigned char *csum, char **p) { int n; /* Always output the character. */ *csum += buf[0]; *(*p)++ = buf[0]; /* Don't go past '~'. */ if (remaining > 97) remaining = 97; for (n = 1; n < remaining; n++) if (buf[n] != buf[0]) break; /* N is the index of the first character not the same as buf[0]. buf[0] is counted twice, so by decrementing N, we get the number of characters the RLE sequence will replace. */ n--; if (n < 3) return 1; /* Skip the frame characters. The manual says to skip '+' and '-' also, but there's no reason to. Unfortunately these two unusable characters double the encoded length of a four byte zero value. */ while (n + 29 == '$' || n + 29 == '#') n--; *csum += '*'; *(*p)++ = '*'; *csum += n + 29; *(*p)++ = n + 29; return n + 1; } /* Send a packet to the remote machine, with error checking. The data of the packet is in BUF, and the length of the packet is in CNT. Returns >= 0 on success, -1 otherwise. */ int putpkt_binary (char *buf, int cnt) { int i; unsigned char csum = 0; char *buf2; char *p; int cc; buf2 = malloc (PBUFSIZ); /* Copy the packet into buffer BUF2, encapsulating it and giving it a checksum. */ p = buf2; *p++ = '$'; for (i = 0; i < cnt;) i += try_rle (buf + i, cnt - i, &csum, &p); *p++ = '#'; *p++ = tohex ((csum >> 4) & 0xf); *p++ = tohex (csum & 0xf); *p = '\0'; /* we might have to write a pkt when out FIFO not yet/anymore opened */ if (!ensure_write_remote_desc()) { warning ("putpkt(write) error: no write_remote_desc\n"); return -1; } /* Send it once (noack_mode) or send it over and over until we get a positive ack. */ do { if (VG_(write) (write_remote_desc, buf2, p - buf2) != p - buf2) { warning ("putpkt(write) error\n"); return -1; } if (noack_mode) dlog(1, "putpkt (\"%s\"); [no ack]\n", buf2); else dlog(1,"putpkt (\"%s\"); [looking for ack]\n", buf2); if (noack_mode) break; cc = readchar (1); if (cc > 0) dlog(1, "[received '%c' (0x%x)]\n", cc, cc); if (cc <= 0) { if (cc == 0) dlog(1, "putpkt(read): Got EOF\n"); else warning ("putpkt(read) error\n"); free (buf2); return -1; } /* Check for an input interrupt while we're here. */ if (cc == '\003') (*the_target->send_signal) (VKI_SIGINT); } while (cc != '+'); free (buf2); return 1; /* Success! */ } /* Send a packet to the remote machine, with error checking. The data of the packet is in BUF, and the packet should be a NUL-terminated string. Returns >= 0 on success, -1 otherwise. */ int putpkt (char *buf) { return putpkt_binary (buf, strlen (buf)); } void monitor_output (char *s) { const int len = strlen(s); char *buf = malloc(1 + 2*len + 1); buf[0] = 'O'; hexify(buf+1, s, len); if (putpkt (buf) < 0) { /* We probably have lost the connection with vgdb. */ reset_valgrind_sink("Error writing monitor output"); /* write again after reset */ VG_(printf) ("%s", s); } free (buf); } /* Returns next char from remote GDB. -1 if error. */ /* if single, only one character maximum can be read with read system call. Otherwise, when reading an ack character we might pile up the next gdb command in the static buf. The read loop is then blocked in poll till gdb times out. */ static int readchar (int single) { static unsigned char buf[PBUFSIZ]; static int bufcnt = 0; static unsigned char *bufp; int ret; if (bufcnt-- > 0) return *bufp++; if (remote_desc == INVALID_DESCRIPTOR) return -1; /* No characters available in buf => wait for some characters to arrive */ remote_desc_pollfdread_activity.revents = 0; ret = VG_(poll)(&remote_desc_pollfdread_activity, 1, -1); if (ret != 1) { dlog(0, "readchar: poll got %d\n", ret); return -1; } if (single) bufcnt = VG_(read) (remote_desc, buf, 1); else bufcnt = VG_(read) (remote_desc, buf, sizeof (buf)); if (bufcnt <= 0) { if (bufcnt == 0) dlog (1, "readchar: Got EOF\n"); else warning ("readchar read error\n"); return -1; } shared->seen_by_valgrind += bufcnt; /* If we have received a character and we do not yet have a connection, we better open our "write" fifo to let vgdb open its read fifo side */ if (write_remote_desc == INVALID_DESCRIPTOR && !ensure_write_remote_desc()) { dlog(1, "reachar: write_remote_desc could not be created"); } bufp = buf; bufcnt--; if (poll_cond(remote_desc_pollfdread_activity.revents)) { dlog(1, "readchar: POLLcond got %d\n", remote_desc_pollfdread_activity.revents); error_poll_cond(); } return *bufp++; } /* Read a packet from the remote machine, with error checking, and store it in BUF. Returns length of packet, or negative if error. */ int getpkt (char *buf) { char *bp; unsigned char csum, c1, c2; int c; while (1) { csum = 0; while (1) { c = readchar (0); if (c == '$') break; dlog(1, "[getpkt: discarding char '%c']\n", c); if (c < 0) return -1; } bp = buf; while (1) { c = readchar (0); if (c < 0) return -1; if (c == '#') break; *bp++ = c; csum += c; } *bp = 0; c1 = fromhex (readchar (0)); c2 = fromhex (readchar (0)); if (csum == (c1 << 4) + c2) break; dlog (0, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n", (c1 << 4) + c2, csum, buf); if (!ensure_write_remote_desc()) { dlog(1, "getpkt(write nack) no write_remote_desc"); } VG_(write) (write_remote_desc, "-", 1); } if (noack_mode) dlog(1, "getpkt (\"%s\"); [no ack] \n", buf); else dlog(1, "getpkt (\"%s\"); [sending ack] \n", buf); if (!noack_mode) { if (!ensure_write_remote_desc()) { dlog(1, "getpkt(write ack) no write_remote_desc"); } VG_(write) (write_remote_desc, "+", 1); dlog(1, "[sent ack]\n"); } return bp - buf; } void write_ok (char *buf) { buf[0] = 'O'; buf[1] = 'K'; buf[2] = '\0'; } void write_enn (char *buf) { /* Some day, we should define the meanings of the error codes... */ buf[0] = 'E'; buf[1] = '0'; buf[2] = '1'; buf[3] = '\0'; } void convert_int_to_ascii (unsigned char *from, char *to, int n) { int nib; int ch; while (n--) { ch = *from++; nib = ((ch & 0xf0) >> 4) & 0x0f; *to++ = tohex (nib); nib = ch & 0x0f; *to++ = tohex (nib); } *to++ = 0; } void convert_ascii_to_int (char *from, unsigned char *to, int n) { int nib1, nib2; while (n--) { nib1 = fromhex (*from++); nib2 = fromhex (*from++); *to++ = (((nib1 & 0x0f) << 4) & 0xf0) | (nib2 & 0x0f); } } static char * outreg (int regno, char *buf) { if ((regno >> 12) != 0) *buf++ = tohex ((regno >> 12) & 0xf); if ((regno >> 8) != 0) *buf++ = tohex ((regno >> 8) & 0xf); *buf++ = tohex ((regno >> 4) & 0xf); *buf++ = tohex (regno & 0xf); *buf++ = ':'; collect_register_as_string (regno, buf); buf += 2 * register_size (regno); *buf++ = ';'; return buf; } void prepare_resume_reply (char *buf, char status, unsigned char sig) { int nib; *buf++ = status; nib = ((sig & 0xf0) >> 4); *buf++ = tohex (nib); nib = sig & 0x0f; *buf++ = tohex (nib); if (status == 'T') { const char **regp = gdbserver_expedite_regs; if (the_target->stopped_by_watchpoint != NULL && (*the_target->stopped_by_watchpoint) ()) { CORE_ADDR addr; int i; strncpy (buf, "watch:", 6); buf += 6; addr = (*the_target->stopped_data_address) (); /* Convert each byte of the address into two hexadecimal chars. Note that we take sizeof (void *) instead of sizeof (addr); this is to avoid sending a 64-bit address to a 32-bit GDB. */ for (i = sizeof (void *) * 2; i > 0; i--) { *buf++ = tohex ((addr >> (i - 1) * 4) & 0xf); } *buf++ = ';'; } while (*regp) { buf = outreg (find_regno (*regp), buf); regp ++; } { unsigned int gdb_id_from_wait; /* FIXME right place to set this? */ thread_from_wait = ((struct inferior_list_entry *)current_inferior)->id; gdb_id_from_wait = thread_to_gdb_id (current_inferior); dlog(1, "Writing resume reply for %ld\n", thread_from_wait); /* This if (1) ought to be unnecessary. But remote_wait in GDB will claim this event belongs to inferior_ptid if we do not specify a thread, and there's no way for gdbserver to know what inferior_ptid is. */ if (1 || old_thread_from_wait != thread_from_wait) { general_thread = thread_from_wait; VG_(sprintf) (buf, "thread:%x;", gdb_id_from_wait); buf += strlen (buf); old_thread_from_wait = thread_from_wait; } } } /* For W and X, we're done. */ *buf++ = 0; } void decode_m_packet (char *from, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr) { int i = 0, j = 0; char ch; *mem_addr_ptr = *len_ptr = 0; while ((ch = from[i++]) != ',') { *mem_addr_ptr = *mem_addr_ptr << 4; *mem_addr_ptr |= fromhex (ch) & 0x0f; } for (j = 0; j < 4; j++) { if ((ch = from[i++]) == 0) break; *len_ptr = *len_ptr << 4; *len_ptr |= fromhex (ch) & 0x0f; } } void decode_M_packet (char *from, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr, unsigned char *to) { int i = 0; char ch; *mem_addr_ptr = *len_ptr = 0; while ((ch = from[i++]) != ',') { *mem_addr_ptr = *mem_addr_ptr << 4; *mem_addr_ptr |= fromhex (ch) & 0x0f; } while ((ch = from[i++]) != ':') { *len_ptr = *len_ptr << 4; *len_ptr |= fromhex (ch) & 0x0f; } convert_ascii_to_int (&from[i++], to, *len_ptr); } int decode_X_packet (char *from, int packet_len, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr, unsigned char *to) { int i = 0; char ch; *mem_addr_ptr = *len_ptr = 0; while ((ch = from[i++]) != ',') { *mem_addr_ptr = *mem_addr_ptr << 4; *mem_addr_ptr |= fromhex (ch) & 0x0f; } while ((ch = from[i++]) != ':') { *len_ptr = *len_ptr << 4; *len_ptr |= fromhex (ch) & 0x0f; } if (remote_unescape_input ((const gdb_byte *) &from[i], packet_len - i, to, *len_ptr) != *len_ptr) return -1; return 0; }
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/valgrind_11817-11818.c
manybugs_data_32
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Andrei Zmievski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" #include "php_tokenizer.h" #include "zend.h" #include "zend_language_scanner.h" #include "zend_language_scanner_defs.h" #include <zend_language_parser.h> #define zendtext LANG_SCNG(yy_text) #define zendleng LANG_SCNG(yy_leng) /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_token_get_all, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_token_name, 0, 0, 1) ZEND_ARG_INFO(0, token) ZEND_END_ARG_INFO() /* }}} */ /* {{{ tokenizer_functions[] * * Every user visible function must have an entry in tokenizer_functions[]. */ const zend_function_entry tokenizer_functions[] = { PHP_FE(token_get_all, arginfo_token_get_all) PHP_FE(token_name, arginfo_token_name) {NULL, NULL, NULL} /* Must be the last line in tokenizer_functions[] */ }; /* }}} */ /* {{{ tokenizer_module_entry */ zend_module_entry tokenizer_module_entry = { #if ZEND_MODULE_API_NO >= 20010901 STANDARD_MODULE_HEADER, #endif "tokenizer", tokenizer_functions, PHP_MINIT(tokenizer), NULL, NULL, NULL, PHP_MINFO(tokenizer), #if ZEND_MODULE_API_NO >= 20010901 "0.1", /* Replace with version number for your extension */ #endif STANDARD_MODULE_PROPERTIES }; /* }}} */ #ifdef COMPILE_DL_TOKENIZER ZEND_GET_MODULE(tokenizer) #endif /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(tokenizer) { tokenizer_register_constants(INIT_FUNC_ARGS_PASSTHRU); return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(tokenizer) { php_info_print_table_start(); php_info_print_table_row(2, "Tokenizer Support", "enabled"); php_info_print_table_end(); } /* }}} */ static void tokenize(zval *return_value TSRMLS_DC) { zval token; zval *keyword; int token_type; zend_bool destroy; int token_line = 1; array_init(return_value); ZVAL_NULL(&token); while ((token_type = lex_scan(&token TSRMLS_CC))) { destroy = 1; switch (token_type) { case T_CLOSE_TAG: if (zendtext[zendleng - 1] != '>') { CG(zend_lineno)++; } case T_OPEN_TAG: case T_OPEN_TAG_WITH_ECHO: case T_WHITESPACE: case T_COMMENT: case T_DOC_COMMENT: destroy = 0; break; } if (token_type >= 256) { MAKE_STD_ZVAL(keyword); array_init(keyword); add_next_index_long(keyword, token_type); if (token_type == T_END_HEREDOC) { if (CG(increment_lineno)) { token_line = ++CG(zend_lineno); CG(increment_lineno) = 0; } add_next_index_stringl(keyword, Z_STRVAL(token), Z_STRLEN(token), 1); efree(Z_STRVAL(token)); } else { add_next_index_stringl(keyword, (char *)zendtext, zendleng, 1); } add_next_index_long(keyword, token_line); add_next_index_zval(return_value, keyword); } else { add_next_index_stringl(return_value, (char *)zendtext, zendleng, 1); } if (destroy && Z_TYPE(token) != IS_NULL) { zval_dtor(&token); } ZVAL_NULL(&token); token_line = CG(zend_lineno); } } /* {{{ proto array token_get_all(string source) */ PHP_FUNCTION(token_get_all) { char *source = NULL; int argc = ZEND_NUM_ARGS(); int source_len; zval source_z; zend_lex_state original_lex_state; if (zend_parse_parameters(argc TSRMLS_CC, "s", &source, &source_len) == FAILURE) { return; } ZVAL_STRINGL(&source_z, source, source_len, 1); zend_save_lexical_state(&original_lex_state TSRMLS_CC); if (zend_prepare_string_for_scanning(&source_z, "" TSRMLS_CC) == FAILURE) { zend_restore_lexical_state(&original_lex_state TSRMLS_CC); RETURN_FALSE; } LANG_SCNG(yy_state) = yycINITIAL; tokenize(return_value TSRMLS_CC); zend_restore_lexical_state(&original_lex_state TSRMLS_CC); zval_dtor(&source_z); } /* }}} */ /* {{{ proto string token_name(int type) */ PHP_FUNCTION(token_name) { int argc = ZEND_NUM_ARGS(); long type; if (zend_parse_parameters(argc TSRMLS_CC, "l", &type) == FAILURE) { return; } RETVAL_STRING(get_token_type_name(type), 1); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Andrei Zmievski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" #include "php_tokenizer.h" #include "zend.h" #include "zend_language_scanner.h" #include "zend_language_scanner_defs.h" #include <zend_language_parser.h> #define zendtext LANG_SCNG(yy_text) #define zendleng LANG_SCNG(yy_leng) /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_token_get_all, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_token_name, 0, 0, 1) ZEND_ARG_INFO(0, token) ZEND_END_ARG_INFO() /* }}} */ /* {{{ tokenizer_functions[] * * Every user visible function must have an entry in tokenizer_functions[]. */ const zend_function_entry tokenizer_functions[] = { PHP_FE(token_get_all, arginfo_token_get_all) PHP_FE(token_name, arginfo_token_name) {NULL, NULL, NULL} /* Must be the last line in tokenizer_functions[] */ }; /* }}} */ /* {{{ tokenizer_module_entry */ zend_module_entry tokenizer_module_entry = { #if ZEND_MODULE_API_NO >= 20010901 STANDARD_MODULE_HEADER, #endif "tokenizer", tokenizer_functions, PHP_MINIT(tokenizer), NULL, NULL, NULL, PHP_MINFO(tokenizer), #if ZEND_MODULE_API_NO >= 20010901 "0.1", /* Replace with version number for your extension */ #endif STANDARD_MODULE_PROPERTIES }; /* }}} */ #ifdef COMPILE_DL_TOKENIZER ZEND_GET_MODULE(tokenizer) #endif /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(tokenizer) { tokenizer_register_constants(INIT_FUNC_ARGS_PASSTHRU); return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(tokenizer) { php_info_print_table_start(); php_info_print_table_row(2, "Tokenizer Support", "enabled"); php_info_print_table_end(); } /* }}} */ static void tokenize(zval *return_value TSRMLS_DC) { zval token; zval *keyword; int token_type; zend_bool destroy; int token_line = 1; array_init(return_value); ZVAL_NULL(&token); while ((token_type = lex_scan(&token TSRMLS_CC))) { destroy = 1; switch (token_type) { case T_CLOSE_TAG: if (zendtext[zendleng - 1] != '>') { CG(zend_lineno)++; } case T_OPEN_TAG: case T_OPEN_TAG_WITH_ECHO: case T_WHITESPACE: case T_COMMENT: case T_DOC_COMMENT: destroy = 0; break; } if (token_type >= 256) { MAKE_STD_ZVAL(keyword); array_init(keyword); add_next_index_long(keyword, token_type); if (token_type == T_END_HEREDOC) { if (CG(increment_lineno)) { token_line = ++CG(zend_lineno); CG(increment_lineno) = 0; } add_next_index_stringl(keyword, Z_STRVAL(token), Z_STRLEN(token), 1); efree(Z_STRVAL(token)); } else { add_next_index_stringl(keyword, (char *)zendtext, zendleng, 1); } add_next_index_long(keyword, token_line); add_next_index_zval(return_value, keyword); } else { add_next_index_stringl(return_value, (char *)zendtext, zendleng, 1); } if (destroy && Z_TYPE(token) != IS_NULL) { zval_dtor(&token); } ZVAL_NULL(&token); token_line = CG(zend_lineno); if (token_type == T_HALT_COMPILER) { break; } } } /* {{{ proto array token_get_all(string source) */ PHP_FUNCTION(token_get_all) { char *source = NULL; int argc = ZEND_NUM_ARGS(); int source_len; zval source_z; zend_lex_state original_lex_state; if (zend_parse_parameters(argc TSRMLS_CC, "s", &source, &source_len) == FAILURE) { return; } ZVAL_STRINGL(&source_z, source, source_len, 1); zend_save_lexical_state(&original_lex_state TSRMLS_CC); if (zend_prepare_string_for_scanning(&source_z, "" TSRMLS_CC) == FAILURE) { zend_restore_lexical_state(&original_lex_state TSRMLS_CC); RETURN_FALSE; } LANG_SCNG(yy_state) = yycINITIAL; tokenize(return_value TSRMLS_CC); zend_restore_lexical_state(&original_lex_state TSRMLS_CC); zval_dtor(&source_z); } /* }}} */ /* {{{ proto string token_name(int type) */ PHP_FUNCTION(token_name) { int argc = ZEND_NUM_ARGS(); long type; if (zend_parse_parameters(argc TSRMLS_CC, "l", &type) == FAILURE) { return; } RETVAL_STRING(get_token_type_name(type), 1); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-02-27-e65d361fde-1d984a7ffd.c
manybugs_data_33
/* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library. * * Directory Write Support Routines. */ #include "tiffiop.h" #ifdef HAVE_IEEEFP # define TIFFCvtNativeToIEEEFloat(tif, n, fp) # define TIFFCvtNativeToIEEEDouble(tif, n, dp) #else extern void TIFFCvtNativeToIEEEFloat(TIFF*, uint32, float*); extern void TIFFCvtNativeToIEEEDouble(TIFF*, uint32, double*); #endif static int TIFFWriteNormalTag(TIFF*, TIFFDirEntry*, const TIFFFieldInfo*); static void TIFFSetupShortLong(TIFF*, ttag_t, TIFFDirEntry*, uint32); static void TIFFSetupShort(TIFF*, ttag_t, TIFFDirEntry*, uint16); static int TIFFSetupShortPair(TIFF*, ttag_t, TIFFDirEntry*); static int TIFFWritePerSampleShorts(TIFF*, ttag_t, TIFFDirEntry*); static int TIFFWritePerSampleAnys(TIFF*, TIFFDataType, ttag_t, TIFFDirEntry*); static int TIFFWriteShortTable(TIFF*, ttag_t, TIFFDirEntry*, uint32, uint16**); static int TIFFWriteShortArray(TIFF*, TIFFDirEntry*, uint16*); static int TIFFWriteLongArray(TIFF *, TIFFDirEntry*, uint32*); static int TIFFWriteRationalArray(TIFF *, TIFFDirEntry*, float*); static int TIFFWriteFloatArray(TIFF *, TIFFDirEntry*, float*); static int TIFFWriteDoubleArray(TIFF *, TIFFDirEntry*, double*); static int TIFFWriteByteArray(TIFF*, TIFFDirEntry*, char*); static int TIFFWriteAnyArray(TIFF*, TIFFDataType, ttag_t, TIFFDirEntry*, uint32, double*); static int TIFFWriteTransferFunction(TIFF*, TIFFDirEntry*); static int TIFFWriteInkNames(TIFF*, TIFFDirEntry*); static int TIFFWriteData(TIFF*, TIFFDirEntry*, char*); static int TIFFLinkDirectory(TIFF*); #define WriteRationalPair(type, tag1, v1, tag2, v2) { \ TIFFWriteRational((tif), (type), (tag1), (dir), (v1)) \ TIFFWriteRational((tif), (type), (tag2), (dir)+1, (v2)) \ (dir)++; \ } #define TIFFWriteRational(tif, type, tag, dir, v) \ (dir)->tdir_tag = (tag); \ (dir)->tdir_type = (type); \ (dir)->tdir_count = 1; \ if (!TIFFWriteRationalArray((tif), (dir), &(v))) \ goto bad; /* * Write the contents of the current directory * to the specified file. This routine doesn't * handle overwriting a directory with auxiliary * storage that's been changed. */ static int _TIFFWriteDirectory(TIFF* tif, int done) { uint16 dircount; toff_t diroff; ttag_t tag; uint32 nfields; tsize_t dirsize; char* data; TIFFDirEntry* dir; TIFFDirectory* td; unsigned long b, fields[FIELD_SETLONGS]; int fi, nfi; if (tif->tif_mode == O_RDONLY) return (1); /* * Clear write state so that subsequent images with * different characteristics get the right buffers * setup for them. */ if (done) { if (tif->tif_flags & TIFF_POSTENCODE) { tif->tif_flags &= ~TIFF_POSTENCODE; if (!(*tif->tif_postencode)(tif)) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error post-encoding before directory write"); return (0); } } (*tif->tif_close)(tif); /* shutdown encoder */ /* * Flush any data that might have been written * by the compression close+cleanup routines. */ if (tif->tif_rawcc > 0 && !TIFFFlushData1(tif)) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error flushing data before directory write"); return (0); } if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata) { _TIFFfree(tif->tif_rawdata); tif->tif_rawdata = NULL; tif->tif_rawcc = 0; tif->tif_rawdatasize = 0; } tif->tif_flags &= ~(TIFF_BEENWRITING|TIFF_BUFFERSETUP); } td = &tif->tif_dir; /* * Size the directory so that we can calculate * offsets for the data items that aren't kept * in-place in each field. */ nfields = 0; for (b = 0; b <= FIELD_LAST; b++) if (TIFFFieldSet(tif, b) && b != FIELD_CUSTOM) nfields += (b < FIELD_SUBFILETYPE ? 2 : 1); nfields += td->td_customValueCount; dirsize = nfields * sizeof (TIFFDirEntry); data = (char*) _TIFFmalloc(dirsize); if (data == NULL) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Cannot write directory, out of space"); return (0); } /* * Directory hasn't been placed yet, put * it at the end of the file and link it * into the existing directory structure. */ if (tif->tif_diroff == 0 && !TIFFLinkDirectory(tif)) goto bad; tif->tif_dataoff = (toff_t)( tif->tif_diroff + sizeof (uint16) + dirsize + sizeof (toff_t)); if (tif->tif_dataoff & 1) tif->tif_dataoff++; (void) TIFFSeekFile(tif, tif->tif_dataoff, SEEK_SET); tif->tif_curdir++; dir = (TIFFDirEntry*) data; /* * Setup external form of directory * entries and write data items. */ _TIFFmemcpy(fields, td->td_fieldsset, sizeof (fields)); /* * Write out ExtraSamples tag only if * extra samples are present in the data. */ if (FieldSet(fields, FIELD_EXTRASAMPLES) && !td->td_extrasamples) { ResetFieldBit(fields, FIELD_EXTRASAMPLES); nfields--; dirsize -= sizeof (TIFFDirEntry); } /*XXX*/ for (fi = 0, nfi = tif->tif_nfields; nfi > 0; nfi--, fi++) { const TIFFFieldInfo* fip = tif->tif_fieldinfo[fi]; /* ** For custom fields, we test to see if the custom field ** is set or not. For normal fields, we just use the ** FieldSet test. */ if( fip->field_bit == FIELD_CUSTOM ) { int ci, is_set = FALSE; for( ci = 0; ci < td->td_customValueCount; ci++ ) is_set |= (td->td_customValues[ci].info == fip); if( !is_set ) continue; } else if (!FieldSet(fields, fip->field_bit)) continue; /* ** Handle other fields. */ switch (fip->field_bit) { case FIELD_STRIPOFFSETS: /* * We use one field bit for both strip and tile * offsets, and so must be careful in selecting * the appropriate field descriptor (so that tags * are written in sorted order). */ tag = isTiled(tif) ? TIFFTAG_TILEOFFSETS : TIFFTAG_STRIPOFFSETS; if (tag != fip->field_tag) continue; dir->tdir_tag = (uint16) tag; dir->tdir_type = (uint16) TIFF_LONG; dir->tdir_count = (uint32) td->td_nstrips; if (!TIFFWriteLongArray(tif, dir, td->td_stripoffset)) goto bad; break; case FIELD_STRIPBYTECOUNTS: /* * We use one field bit for both strip and tile * byte counts, and so must be careful in selecting * the appropriate field descriptor (so that tags * are written in sorted order). */ tag = isTiled(tif) ? TIFFTAG_TILEBYTECOUNTS : TIFFTAG_STRIPBYTECOUNTS; if (tag != fip->field_tag) continue; dir->tdir_tag = (uint16) tag; dir->tdir_type = (uint16) TIFF_LONG; dir->tdir_count = (uint32) td->td_nstrips; if (!TIFFWriteLongArray(tif, dir, td->td_stripbytecount)) goto bad; break; case FIELD_ROWSPERSTRIP: TIFFSetupShortLong(tif, TIFFTAG_ROWSPERSTRIP, dir, td->td_rowsperstrip); break; case FIELD_COLORMAP: if (!TIFFWriteShortTable(tif, TIFFTAG_COLORMAP, dir, 3, td->td_colormap)) goto bad; break; case FIELD_IMAGEDIMENSIONS: TIFFSetupShortLong(tif, TIFFTAG_IMAGEWIDTH, dir++, td->td_imagewidth); TIFFSetupShortLong(tif, TIFFTAG_IMAGELENGTH, dir, td->td_imagelength); break; case FIELD_TILEDIMENSIONS: TIFFSetupShortLong(tif, TIFFTAG_TILEWIDTH, dir++, td->td_tilewidth); TIFFSetupShortLong(tif, TIFFTAG_TILELENGTH, dir, td->td_tilelength); break; case FIELD_COMPRESSION: TIFFSetupShort(tif, TIFFTAG_COMPRESSION, dir, td->td_compression); break; case FIELD_PHOTOMETRIC: TIFFSetupShort(tif, TIFFTAG_PHOTOMETRIC, dir, td->td_photometric); break; case FIELD_POSITION: WriteRationalPair(TIFF_RATIONAL, TIFFTAG_XPOSITION, td->td_xposition, TIFFTAG_YPOSITION, td->td_yposition); break; case FIELD_RESOLUTION: WriteRationalPair(TIFF_RATIONAL, TIFFTAG_XRESOLUTION, td->td_xresolution, TIFFTAG_YRESOLUTION, td->td_yresolution); break; case FIELD_BITSPERSAMPLE: case FIELD_MINSAMPLEVALUE: case FIELD_MAXSAMPLEVALUE: case FIELD_SAMPLEFORMAT: if (!TIFFWritePerSampleShorts(tif, fip->field_tag, dir)) goto bad; break; case FIELD_SMINSAMPLEVALUE: case FIELD_SMAXSAMPLEVALUE: if (!TIFFWritePerSampleAnys(tif, _TIFFSampleToTagType(tif), fip->field_tag, dir)) goto bad; break; case FIELD_PAGENUMBER: case FIELD_HALFTONEHINTS: case FIELD_YCBCRSUBSAMPLING: if (!TIFFSetupShortPair(tif, fip->field_tag, dir)) goto bad; break; case FIELD_INKNAMES: if (!TIFFWriteInkNames(tif, dir)) goto bad; break; case FIELD_TRANSFERFUNCTION: if (!TIFFWriteTransferFunction(tif, dir)) goto bad; break; case FIELD_SUBIFD: /* * XXX: Always write this field using LONG type * for backward compatibility. */ dir->tdir_tag = (uint16) fip->field_tag; dir->tdir_type = (uint16) TIFF_LONG; dir->tdir_count = (uint32) td->td_nsubifd; if (!TIFFWriteLongArray(tif, dir, td->td_subifd)) goto bad; /* * Total hack: if this directory includes a SubIFD * tag then force the next <n> directories to be * written as ``sub directories'' of this one. This * is used to write things like thumbnails and * image masks that one wants to keep out of the * normal directory linkage access mechanism. */ if (dir->tdir_count > 0) { tif->tif_flags |= TIFF_INSUBIFD; tif->tif_nsubifd = (uint16) dir->tdir_count; if (dir->tdir_count > 1) tif->tif_subifdoff = dir->tdir_offset; else tif->tif_subifdoff = (uint32)( tif->tif_diroff + sizeof (uint16) + ((char*)&dir->tdir_offset-data)); } break; default: if (!TIFFWriteNormalTag(tif, dir, fip)) goto bad; break; } dir++; if( fip->field_bit != FIELD_CUSTOM ) ResetFieldBit(fields, fip->field_bit); } /* * Write directory. */ dircount = (uint16) nfields; diroff = (uint32) tif->tif_nextdiroff; if (tif->tif_flags & TIFF_SWAB) { /* * The file's byte order is opposite to the * native machine architecture. We overwrite * the directory information with impunity * because it'll be released below after we * write it to the file. Note that all the * other tag construction routines assume that * we do this byte-swapping; i.e. they only * byte-swap indirect data. */ for (dir = (TIFFDirEntry*) data; dircount; dir++, dircount--) { TIFFSwabArrayOfShort(&dir->tdir_tag, 2); TIFFSwabArrayOfLong(&dir->tdir_count, 2); } dircount = (uint16) nfields; TIFFSwabShort(&dircount); TIFFSwabLong(&diroff); } (void) TIFFSeekFile(tif, tif->tif_diroff, SEEK_SET); if (!WriteOK(tif, &dircount, sizeof (dircount))) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error writing directory count"); goto bad; } if (!WriteOK(tif, data, dirsize)) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error writing directory contents"); goto bad; } if (!WriteOK(tif, &diroff, sizeof (diroff))) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error writing directory link"); goto bad; } if (done) { TIFFFreeDirectory(tif); tif->tif_flags &= ~TIFF_DIRTYDIRECT; (*tif->tif_cleanup)(tif); /* * Reset directory-related state for subsequent * directories. */ TIFFCreateDirectory(tif); } _TIFFfree(data); return (1); bad: _TIFFfree(data); return (0); } #undef WriteRationalPair int TIFFWriteDirectory(TIFF* tif) { return _TIFFWriteDirectory(tif, TRUE); } /* * Similar to TIFFWriteDirectory(), writes the directory out * but leaves all data structures in memory so that it can be * written again. This will make a partially written TIFF file * readable before it is successfully completed/closed. */ int TIFFCheckpointDirectory(TIFF* tif) { int rc; /* Setup the strips arrays, if they haven't already been. */ if (tif->tif_dir.td_stripoffset == NULL) (void) TIFFSetupStrips(tif); rc = _TIFFWriteDirectory(tif, FALSE); (void) TIFFSetWriteOffset(tif, TIFFSeekFile(tif, 0, SEEK_END)); return rc; } /* * Process tags that are not special cased. */ static int TIFFWriteNormalTag(TIFF* tif, TIFFDirEntry* dir, const TIFFFieldInfo* fip) { uint16 wc = (uint16) fip->field_writecount; uint32 wc2; dir->tdir_tag = (uint16) fip->field_tag; dir->tdir_type = (uint16) fip->field_type; dir->tdir_count = wc; switch (fip->field_type) { case TIFF_SHORT: case TIFF_SSHORT: if (fip->field_passcount) { uint16* wp; if (wc == (uint16) TIFF_VARIABLE2) { TIFFGetField(tif, fip->field_tag, &wc2, &wp); dir->tdir_count = wc2; } else { /* Assume TIFF_VARIABLE */ TIFFGetField(tif, fip->field_tag, &wc, &wp); dir->tdir_count = wc; } if (!TIFFWriteShortArray(tif, dir, wp)) return 0; } else { if (wc == 1) { uint16 sv; TIFFGetField(tif, fip->field_tag, &sv); dir->tdir_offset = TIFFInsertData(tif, dir->tdir_type, sv); } else { uint16* wp; TIFFGetField(tif, fip->field_tag, &wp); if (!TIFFWriteShortArray(tif, dir, wp)) return 0; } } break; case TIFF_LONG: case TIFF_SLONG: case TIFF_IFD: if (fip->field_passcount) { uint32* lp; if (wc == (uint16) TIFF_VARIABLE2) { TIFFGetField(tif, fip->field_tag, &wc2, &lp); dir->tdir_count = wc2; } else { /* Assume TIFF_VARIABLE */ TIFFGetField(tif, fip->field_tag, &wc, &lp); dir->tdir_count = wc; } if (!TIFFWriteLongArray(tif, dir, lp)) return 0; } else { if (wc == 1) { /* XXX handle LONG->SHORT conversion */ TIFFGetField(tif, fip->field_tag, &dir->tdir_offset); } else { uint32* lp; TIFFGetField(tif, fip->field_tag, &lp); if (!TIFFWriteLongArray(tif, dir, lp)) return 0; } } break; case TIFF_RATIONAL: case TIFF_SRATIONAL: if (fip->field_passcount) { float* fp; if (wc == (uint16) TIFF_VARIABLE2) { TIFFGetField(tif, fip->field_tag, &wc2, &fp); dir->tdir_count = wc2; } else { /* Assume TIFF_VARIABLE */ TIFFGetField(tif, fip->field_tag, &wc, &fp); dir->tdir_count = wc; } if (!TIFFWriteRationalArray(tif, dir, fp)) return 0; } else { if (wc == 1) { float fv; TIFFGetField(tif, fip->field_tag, &fv); if (!TIFFWriteRationalArray(tif, dir, &fv)) return 0; } else { float* fp; TIFFGetField(tif, fip->field_tag, &fp); if (!TIFFWriteRationalArray(tif, dir, fp)) return 0; } } break; case TIFF_FLOAT: if (fip->field_passcount) { float* fp; if (wc == (uint16) TIFF_VARIABLE2) { TIFFGetField(tif, fip->field_tag, &wc2, &fp); dir->tdir_count = wc2; } else { /* Assume TIFF_VARIABLE */ TIFFGetField(tif, fip->field_tag, &wc, &fp); dir->tdir_count = wc; } if (!TIFFWriteFloatArray(tif, dir, fp)) return 0; } else { if (wc == 1) { float fv; TIFFGetField(tif, fip->field_tag, &fv); if (!TIFFWriteFloatArray(tif, dir, &fv)) return 0; } else { float* fp; TIFFGetField(tif, fip->field_tag, &fp); if (!TIFFWriteFloatArray(tif, dir, fp)) return 0; } } break; case TIFF_DOUBLE: if (fip->field_passcount) { double* dp; if (wc == (uint16) TIFF_VARIABLE2) { TIFFGetField(tif, fip->field_tag, &wc2, &dp); dir->tdir_count = wc2; } else { /* Assume TIFF_VARIABLE */ TIFFGetField(tif, fip->field_tag, &wc, &dp); dir->tdir_count = wc; } if (!TIFFWriteDoubleArray(tif, dir, dp)) return 0; } else { if (wc == 1) { double dv; TIFFGetField(tif, fip->field_tag, &dv); if (!TIFFWriteDoubleArray(tif, dir, &dv)) return 0; } else { double* dp; TIFFGetField(tif, fip->field_tag, &dp); if (!TIFFWriteDoubleArray(tif, dir, dp)) return 0; } } break; case TIFF_ASCII: { char* cp; if (fip->field_passcount) TIFFGetField(tif, fip->field_tag, &wc, &cp); else TIFFGetField(tif, fip->field_tag, &cp); dir->tdir_count = (uint32) (strlen(cp) + 1); if (!TIFFWriteByteArray(tif, dir, cp)) return (0); } break; case TIFF_BYTE: case TIFF_SBYTE: if (fip->field_passcount) { char* cp; if (wc == (uint16) TIFF_VARIABLE2) { TIFFGetField(tif, fip->field_tag, &wc2, &cp); dir->tdir_count = wc2; } else { /* Assume TIFF_VARIABLE */ TIFFGetField(tif, fip->field_tag, &wc, &cp); dir->tdir_count = wc; } if (!TIFFWriteByteArray(tif, dir, cp)) return 0; } else { if (wc == 1) { char cv; TIFFGetField(tif, fip->field_tag, &cv); if (!TIFFWriteByteArray(tif, dir, &cv)) return 0; } else { char* cp; TIFFGetField(tif, fip->field_tag, &cp); if (!TIFFWriteByteArray(tif, dir, cp)) return 0; } } break; case TIFF_UNDEFINED: { char* cp; if (wc == (unsigned short) TIFF_VARIABLE) { TIFFGetField(tif, fip->field_tag, &wc, &cp); dir->tdir_count = wc; } else if (wc == (unsigned short) TIFF_VARIABLE2) { TIFFGetField(tif, fip->field_tag, &wc2, &cp); dir->tdir_count = wc2; } else TIFFGetField(tif, fip->field_tag, &cp); if (!TIFFWriteByteArray(tif, dir, cp)) return (0); } break; case TIFF_NOTYPE: break; } return (1); } /* * Setup a directory entry with either a SHORT * or LONG type according to the value. */ static void TIFFSetupShortLong(TIFF* tif, ttag_t tag, TIFFDirEntry* dir, uint32 v) { dir->tdir_tag = (uint16) tag; dir->tdir_count = 1; if (v > 0xffffL) { dir->tdir_type = (short) TIFF_LONG; dir->tdir_offset = v; } else { dir->tdir_type = (short) TIFF_SHORT; dir->tdir_offset = TIFFInsertData(tif, (int) TIFF_SHORT, v); } } /* * Setup a SHORT directory entry */ static void TIFFSetupShort(TIFF* tif, ttag_t tag, TIFFDirEntry* dir, uint16 v) { dir->tdir_tag = (uint16) tag; dir->tdir_count = 1; dir->tdir_type = (short) TIFF_SHORT; dir->tdir_offset = TIFFInsertData(tif, (int) TIFF_SHORT, v); } #undef MakeShortDirent #define NITEMS(x) (sizeof (x) / sizeof (x[0])) /* * Setup a directory entry that references a * samples/pixel array of SHORT values and * (potentially) write the associated indirect * values. */ static int TIFFWritePerSampleShorts(TIFF* tif, ttag_t tag, TIFFDirEntry* dir) { uint16 buf[10], v; uint16* w = buf; uint16 i, samples = tif->tif_dir.td_samplesperpixel; int status; if (samples > NITEMS(buf)) { w = (uint16*) _TIFFmalloc(samples * sizeof (uint16)); if (w == NULL) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "No space to write per-sample shorts"); return (0); } } TIFFGetField(tif, tag, &v); for (i = 0; i < samples; i++) w[i] = v; dir->tdir_tag = (uint16) tag; dir->tdir_type = (uint16) TIFF_SHORT; dir->tdir_count = samples; status = TIFFWriteShortArray(tif, dir, w); if (w != buf) _TIFFfree((char*) w); return (status); } /* * Setup a directory entry that references a samples/pixel array of ``type'' * values and (potentially) write the associated indirect values. The source * data from TIFFGetField() for the specified tag must be returned as double. */ static int TIFFWritePerSampleAnys(TIFF* tif, TIFFDataType type, ttag_t tag, TIFFDirEntry* dir) { double buf[10], v; double* w = buf; uint16 i, samples = tif->tif_dir.td_samplesperpixel; int status; if (samples > NITEMS(buf)) { w = (double*) _TIFFmalloc(samples * sizeof (double)); if (w == NULL) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "No space to write per-sample values"); return (0); } } TIFFGetField(tif, tag, &v); for (i = 0; i < samples; i++) w[i] = v; status = TIFFWriteAnyArray(tif, type, tag, dir, samples, w); if (w != buf) _TIFFfree(w); return (status); } #undef NITEMS /* * Setup a pair of shorts that are returned by * value, rather than as a reference to an array. */ static int TIFFSetupShortPair(TIFF* tif, ttag_t tag, TIFFDirEntry* dir) { uint16 v[2]; TIFFGetField(tif, tag, &v[0], &v[1]); dir->tdir_tag = (uint16) tag; dir->tdir_type = (uint16) TIFF_SHORT; dir->tdir_count = 2; return (TIFFWriteShortArray(tif, dir, v)); } /* * Setup a directory entry for an NxM table of shorts, * where M is known to be 2**bitspersample, and write * the associated indirect data. */ static int TIFFWriteShortTable(TIFF* tif, ttag_t tag, TIFFDirEntry* dir, uint32 n, uint16** table) { uint32 i, off; dir->tdir_tag = (uint16) tag; dir->tdir_type = (short) TIFF_SHORT; /* XXX -- yech, fool TIFFWriteData */ dir->tdir_count = (uint32) (1L<<tif->tif_dir.td_bitspersample); off = tif->tif_dataoff; for (i = 0; i < n; i++) if (!TIFFWriteData(tif, dir, (char *)table[i])) return (0); dir->tdir_count *= n; dir->tdir_offset = off; return (1); } /* * Write/copy data associated with an ASCII or opaque tag value. */ static int TIFFWriteByteArray(TIFF* tif, TIFFDirEntry* dir, char* cp) { if (dir->tdir_count > 4) { if (!TIFFWriteData(tif, dir, cp)) return (0); } else _TIFFmemcpy(&dir->tdir_offset, cp, dir->tdir_count); return (1); } /* * Setup a directory entry of an array of SHORT * or SSHORT and write the associated indirect values. */ static int TIFFWriteShortArray(TIFF* tif, TIFFDirEntry* dir, uint16* v) { if (dir->tdir_count <= 2) { if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) { dir->tdir_offset = (uint32) ((long) v[0] << 16); if (dir->tdir_count == 2) dir->tdir_offset |= v[1] & 0xffff; } else { dir->tdir_offset = v[0] & 0xffff; if (dir->tdir_count == 2) dir->tdir_offset |= (long) v[1] << 16; } return (1); } else return (TIFFWriteData(tif, dir, (char*) v)); } /* * Setup a directory entry of an array of LONG * or SLONG and write the associated indirect values. */ static int TIFFWriteLongArray(TIFF* tif, TIFFDirEntry* dir, uint32* v) { if (dir->tdir_count == 1) { dir->tdir_offset = v[0]; return (1); } else return (TIFFWriteData(tif, dir, (char*) v)); } /* * Setup a directory entry of an array of RATIONAL * or SRATIONAL and write the associated indirect values. */ static int TIFFWriteRationalArray(TIFF* tif, TIFFDirEntry* dir, float* v) { uint32 i; uint32* t; int status; t = (uint32*) _TIFFmalloc(2 * dir->tdir_count * sizeof (uint32)); if (t == NULL) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "No space to write RATIONAL array"); return (0); } for (i = 0; i < dir->tdir_count; i++) { float fv = v[i]; int sign = 1; uint32 den; if (fv < 0) { if (dir->tdir_type == TIFF_RATIONAL) { TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "\"%s\": Information lost writing value (%g) as (unsigned) RATIONAL", _TIFFFieldWithTag(tif,dir->tdir_tag)->field_name, fv); fv = 0; } else fv = -fv, sign = -1; } den = 1L; if (fv > 0) { while (fv < 1L<<(31-3) && den < 1L<<(31-3)) fv *= 1<<3, den *= 1L<<3; } t[2*i+0] = (uint32) (sign * (fv + 0.5)); t[2*i+1] = den; } status = TIFFWriteData(tif, dir, (char *)t); _TIFFfree((char*) t); return (status); } static int TIFFWriteFloatArray(TIFF* tif, TIFFDirEntry* dir, float* v) { TIFFCvtNativeToIEEEFloat(tif, dir->tdir_count, v); if (dir->tdir_count == 1) { dir->tdir_offset = *(uint32*) &v[0]; return (1); } else return (TIFFWriteData(tif, dir, (char*) v)); } static int TIFFWriteDoubleArray(TIFF* tif, TIFFDirEntry* dir, double* v) { TIFFCvtNativeToIEEEDouble(tif, dir->tdir_count, v); return (TIFFWriteData(tif, dir, (char*) v)); } /* * Write an array of ``type'' values for a specified tag (i.e. this is a tag * which is allowed to have different types, e.g. SMaxSampleType). * Internally the data values are represented as double since a double can * hold any of the TIFF tag types (yes, this should really be an abstract * type tany_t for portability). The data is converted into the specified * type in a temporary buffer and then handed off to the appropriate array * writer. */ static int TIFFWriteAnyArray(TIFF* tif, TIFFDataType type, ttag_t tag, TIFFDirEntry* dir, uint32 n, double* v) { char buf[10 * sizeof(double)]; char* w = buf; int i, status = 0; if (n * TIFFDataWidth(type) > sizeof buf) { w = (char*) _TIFFmalloc(n * TIFFDataWidth(type)); if (w == NULL) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "No space to write array"); return (0); } } dir->tdir_tag = (uint16) tag; dir->tdir_type = (uint16) type; dir->tdir_count = n; switch (type) { case TIFF_BYTE: { uint8* bp = (uint8*) w; for (i = 0; i < (int) n; i++) bp[i] = (uint8) v[i]; if (!TIFFWriteByteArray(tif, dir, (char*) bp)) goto out; } break; case TIFF_SBYTE: { int8* bp = (int8*) w; for (i = 0; i < (int) n; i++) bp[i] = (int8) v[i]; if (!TIFFWriteByteArray(tif, dir, (char*) bp)) goto out; } break; case TIFF_SHORT: { uint16* bp = (uint16*) w; for (i = 0; i < (int) n; i++) bp[i] = (uint16) v[i]; if (!TIFFWriteShortArray(tif, dir, (uint16*)bp)) goto out; } break; case TIFF_SSHORT: { int16* bp = (int16*) w; for (i = 0; i < (int) n; i++) bp[i] = (int16) v[i]; if (!TIFFWriteShortArray(tif, dir, (uint16*)bp)) goto out; } break; case TIFF_LONG: { uint32* bp = (uint32*) w; for (i = 0; i < (int) n; i++) bp[i] = (uint32) v[i]; if (!TIFFWriteLongArray(tif, dir, bp)) goto out; } break; case TIFF_SLONG: { int32* bp = (int32*) w; for (i = 0; i < (int) n; i++) bp[i] = (int32) v[i]; if (!TIFFWriteLongArray(tif, dir, (uint32*) bp)) goto out; } break; case TIFF_FLOAT: { float* bp = (float*) w; for (i = 0; i < (int) n; i++) bp[i] = (float) v[i]; if (!TIFFWriteFloatArray(tif, dir, bp)) goto out; } break; case TIFF_DOUBLE: return (TIFFWriteDoubleArray(tif, dir, v)); default: /* TIFF_NOTYPE */ /* TIFF_ASCII */ /* TIFF_UNDEFINED */ /* TIFF_RATIONAL */ /* TIFF_SRATIONAL */ goto out; } status = 1; out: if (w != buf) _TIFFfree(w); return (status); } static int TIFFWriteTransferFunction(TIFF* tif, TIFFDirEntry* dir) { TIFFDirectory* td = &tif->tif_dir; tsize_t n = (1L<<td->td_bitspersample) * sizeof (uint16); uint16** tf = td->td_transferfunction; int ncols; /* * Check if the table can be written as a single column, * or if it must be written as 3 columns. Note that we * write a 3-column tag if there are 2 samples/pixel and * a single column of data won't suffice--hmm. */ switch (td->td_samplesperpixel - td->td_extrasamples) { default: if (_TIFFmemcmp(tf[0], tf[2], n)) { ncols = 3; break; } case 2: if (_TIFFmemcmp(tf[0], tf[1], n)) { ncols = 3; break; } case 1: case 0: ncols = 1; } return (TIFFWriteShortTable(tif, TIFFTAG_TRANSFERFUNCTION, dir, ncols, tf)); } static int TIFFWriteInkNames(TIFF* tif, TIFFDirEntry* dir) { TIFFDirectory* td = &tif->tif_dir; dir->tdir_tag = TIFFTAG_INKNAMES; dir->tdir_type = (short) TIFF_ASCII; dir->tdir_count = td->td_inknameslen; return (TIFFWriteByteArray(tif, dir, td->td_inknames)); } /* * Write a contiguous directory item. */ static int TIFFWriteData(TIFF* tif, TIFFDirEntry* dir, char* cp) { tsize_t cc; if (tif->tif_flags & TIFF_SWAB) { switch (dir->tdir_type) { case TIFF_SHORT: case TIFF_SSHORT: TIFFSwabArrayOfShort((uint16*) cp, dir->tdir_count); break; case TIFF_LONG: case TIFF_SLONG: case TIFF_FLOAT: TIFFSwabArrayOfLong((uint32*) cp, dir->tdir_count); break; case TIFF_RATIONAL: case TIFF_SRATIONAL: TIFFSwabArrayOfLong((uint32*) cp, 2*dir->tdir_count); break; case TIFF_DOUBLE: TIFFSwabArrayOfDouble((double*) cp, dir->tdir_count); break; } } dir->tdir_offset = tif->tif_dataoff; cc = dir->tdir_count * TIFFDataWidth((TIFFDataType) dir->tdir_type); if (SeekOK(tif, dir->tdir_offset) && WriteOK(tif, cp, cc)) { tif->tif_dataoff += (cc + 1) & ~1; return (1); } TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error writing data for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); return (0); } /* * Similar to TIFFWriteDirectory(), but if the directory has already * been written once, it is relocated to the end of the file, in case it * has changed in size. Note that this will result in the loss of the * previously used directory space. */ int TIFFRewriteDirectory( TIFF *tif ) { static const char module[] = "TIFFRewriteDirectory"; /* We don't need to do anything special if it hasn't been written. */ if( tif->tif_diroff == 0 ) return TIFFWriteDirectory( tif ); /* ** Find and zero the pointer to this directory, so that TIFFLinkDirectory ** will cause it to be added after this directories current pre-link. */ /* Is it the first directory in the file? */ if (tif->tif_header.tiff_diroff == tif->tif_diroff) { tif->tif_header.tiff_diroff = 0; tif->tif_diroff = 0; TIFFSeekFile(tif, (toff_t)(TIFF_MAGIC_SIZE+TIFF_VERSION_SIZE), SEEK_SET); if (!WriteOK(tif, &(tif->tif_header.tiff_diroff), sizeof (tif->tif_diroff))) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error updating TIFF header"); return (0); } } else { toff_t nextdir, off; nextdir = tif->tif_header.tiff_diroff; do { uint16 dircount; if (!SeekOK(tif, nextdir) || !ReadOK(tif, &dircount, sizeof (dircount))) { TIFFErrorExt(tif->tif_clientdata, module, "Error fetching directory count"); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); (void) TIFFSeekFile(tif, dircount * sizeof (TIFFDirEntry), SEEK_CUR); if (!ReadOK(tif, &nextdir, sizeof (nextdir))) { TIFFErrorExt(tif->tif_clientdata, module, "Error fetching directory link"); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong(&nextdir); } while (nextdir != tif->tif_diroff && nextdir != 0); off = TIFFSeekFile(tif, 0, SEEK_CUR); /* get current offset */ (void) TIFFSeekFile(tif, off - (toff_t)sizeof(nextdir), SEEK_SET); tif->tif_diroff = 0; if (!WriteOK(tif, &(tif->tif_diroff), sizeof (nextdir))) { TIFFErrorExt(tif->tif_clientdata, module, "Error writing directory link"); return (0); } } /* ** Now use TIFFWriteDirectory() normally. */ return TIFFWriteDirectory( tif ); } /* * Link the current directory into the * directory chain for the file. */ static int TIFFLinkDirectory(TIFF* tif) { static const char module[] = "TIFFLinkDirectory"; toff_t nextdir; toff_t diroff, off; tif->tif_diroff = (TIFFSeekFile(tif, (toff_t) 0, SEEK_END)+1) &~ 1; diroff = tif->tif_diroff; if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong(&diroff); /* * Handle SubIFDs */ if (tif->tif_flags & TIFF_INSUBIFD) { (void) TIFFSeekFile(tif, tif->tif_subifdoff, SEEK_SET); if (!WriteOK(tif, &diroff, sizeof (diroff))) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Error writing SubIFD directory link", tif->tif_name); return (0); } /* * Advance to the next SubIFD or, if this is * the last one configured, revert back to the * normal directory linkage. */ if (--tif->tif_nsubifd) tif->tif_subifdoff += sizeof (diroff); else tif->tif_flags &= ~TIFF_INSUBIFD; return (1); } if (tif->tif_header.tiff_diroff == 0) { /* * First directory, overwrite offset in header. */ tif->tif_header.tiff_diroff = tif->tif_diroff; (void) TIFFSeekFile(tif, (toff_t)(TIFF_MAGIC_SIZE+TIFF_VERSION_SIZE), SEEK_SET); if (!WriteOK(tif, &diroff, sizeof (diroff))) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error writing TIFF header"); return (0); } return (1); } /* * Not the first directory, search to the last and append. */ nextdir = tif->tif_header.tiff_diroff; do { uint16 dircount; if (!SeekOK(tif, nextdir) || !ReadOK(tif, &dircount, sizeof (dircount))) { TIFFErrorExt(tif->tif_clientdata, module, "Error fetching directory count"); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); (void) TIFFSeekFile(tif, dircount * sizeof (TIFFDirEntry), SEEK_CUR); if (!ReadOK(tif, &nextdir, sizeof (nextdir))) { TIFFErrorExt(tif->tif_clientdata, module, "Error fetching directory link"); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong(&nextdir); } while (nextdir != 0); off = TIFFSeekFile(tif, 0, SEEK_CUR); /* get current offset */ (void) TIFFSeekFile(tif, off - (toff_t)sizeof(nextdir), SEEK_SET); if (!WriteOK(tif, &diroff, sizeof (diroff))) { TIFFErrorExt(tif->tif_clientdata, module, "Error writing directory link"); return (0); } return (1); } /* vim: set ts=8 sts=8 sw=8 noet: */ /* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library. * * Directory Write Support Routines. */ #include "tiffiop.h" #ifdef HAVE_IEEEFP # define TIFFCvtNativeToIEEEFloat(tif, n, fp) # define TIFFCvtNativeToIEEEDouble(tif, n, dp) #else extern void TIFFCvtNativeToIEEEFloat(TIFF*, uint32, float*); extern void TIFFCvtNativeToIEEEDouble(TIFF*, uint32, double*); #endif static int TIFFWriteNormalTag(TIFF*, TIFFDirEntry*, const TIFFFieldInfo*); static void TIFFSetupShortLong(TIFF*, ttag_t, TIFFDirEntry*, uint32); static void TIFFSetupShort(TIFF*, ttag_t, TIFFDirEntry*, uint16); static int TIFFSetupShortPair(TIFF*, ttag_t, TIFFDirEntry*); static int TIFFWritePerSampleShorts(TIFF*, ttag_t, TIFFDirEntry*); static int TIFFWritePerSampleAnys(TIFF*, TIFFDataType, ttag_t, TIFFDirEntry*); static int TIFFWriteShortTable(TIFF*, ttag_t, TIFFDirEntry*, uint32, uint16**); static int TIFFWriteShortArray(TIFF*, TIFFDirEntry*, uint16*); static int TIFFWriteLongArray(TIFF *, TIFFDirEntry*, uint32*); static int TIFFWriteRationalArray(TIFF *, TIFFDirEntry*, float*); static int TIFFWriteFloatArray(TIFF *, TIFFDirEntry*, float*); static int TIFFWriteDoubleArray(TIFF *, TIFFDirEntry*, double*); static int TIFFWriteByteArray(TIFF*, TIFFDirEntry*, char*); static int TIFFWriteAnyArray(TIFF*, TIFFDataType, ttag_t, TIFFDirEntry*, uint32, double*); static int TIFFWriteTransferFunction(TIFF*, TIFFDirEntry*); static int TIFFWriteInkNames(TIFF*, TIFFDirEntry*); static int TIFFWriteData(TIFF*, TIFFDirEntry*, char*); static int TIFFLinkDirectory(TIFF*); #define WriteRationalPair(type, tag1, v1, tag2, v2) { \ TIFFWriteRational((tif), (type), (tag1), (dir), (v1)) \ TIFFWriteRational((tif), (type), (tag2), (dir)+1, (v2)) \ (dir)++; \ } #define TIFFWriteRational(tif, type, tag, dir, v) \ (dir)->tdir_tag = (tag); \ (dir)->tdir_type = (type); \ (dir)->tdir_count = 1; \ if (!TIFFWriteRationalArray((tif), (dir), &(v))) \ goto bad; /* * Write the contents of the current directory * to the specified file. This routine doesn't * handle overwriting a directory with auxiliary * storage that's been changed. */ static int _TIFFWriteDirectory(TIFF* tif, int done) { uint16 dircount; toff_t diroff; ttag_t tag; uint32 nfields; tsize_t dirsize; char* data; TIFFDirEntry* dir; TIFFDirectory* td; unsigned long b, fields[FIELD_SETLONGS]; int fi, nfi; if (tif->tif_mode == O_RDONLY) return (1); /* * Clear write state so that subsequent images with * different characteristics get the right buffers * setup for them. */ if (done) { if (tif->tif_flags & TIFF_POSTENCODE) { tif->tif_flags &= ~TIFF_POSTENCODE; if (!(*tif->tif_postencode)(tif)) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error post-encoding before directory write"); return (0); } } (*tif->tif_close)(tif); /* shutdown encoder */ /* * Flush any data that might have been written * by the compression close+cleanup routines. */ if (tif->tif_rawcc > 0 && !TIFFFlushData1(tif)) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error flushing data before directory write"); return (0); } if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata) { _TIFFfree(tif->tif_rawdata); tif->tif_rawdata = NULL; tif->tif_rawcc = 0; tif->tif_rawdatasize = 0; } tif->tif_flags &= ~(TIFF_BEENWRITING|TIFF_BUFFERSETUP); } td = &tif->tif_dir; /* * Size the directory so that we can calculate * offsets for the data items that aren't kept * in-place in each field. */ nfields = 0; for (b = 0; b <= FIELD_LAST; b++) if (TIFFFieldSet(tif, b) && b != FIELD_CUSTOM) nfields += (b < FIELD_SUBFILETYPE ? 2 : 1); nfields += td->td_customValueCount; dirsize = nfields * sizeof (TIFFDirEntry); data = (char*) _TIFFmalloc(dirsize); if (data == NULL) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Cannot write directory, out of space"); return (0); } /* * Directory hasn't been placed yet, put * it at the end of the file and link it * into the existing directory structure. */ if (tif->tif_diroff == 0 && !TIFFLinkDirectory(tif)) goto bad; tif->tif_dataoff = (toff_t)( tif->tif_diroff + sizeof (uint16) + dirsize + sizeof (toff_t)); if (tif->tif_dataoff & 1) tif->tif_dataoff++; (void) TIFFSeekFile(tif, tif->tif_dataoff, SEEK_SET); tif->tif_curdir++; dir = (TIFFDirEntry*) data; /* * Setup external form of directory * entries and write data items. */ _TIFFmemcpy(fields, td->td_fieldsset, sizeof (fields)); /* * Write out ExtraSamples tag only if * extra samples are present in the data. */ if (FieldSet(fields, FIELD_EXTRASAMPLES) && !td->td_extrasamples) { ResetFieldBit(fields, FIELD_EXTRASAMPLES); nfields--; dirsize -= sizeof (TIFFDirEntry); } /*XXX*/ for (fi = 0, nfi = tif->tif_nfields; nfi > 0; nfi--, fi++) { const TIFFFieldInfo* fip = tif->tif_fieldinfo[fi]; /* ** For custom fields, we test to see if the custom field ** is set or not. For normal fields, we just use the ** FieldSet test. */ if( fip->field_bit == FIELD_CUSTOM ) { int ci, is_set = FALSE; for( ci = 0; ci < td->td_customValueCount; ci++ ) is_set |= (td->td_customValues[ci].info == fip); if( !is_set ) continue; } else if (!FieldSet(fields, fip->field_bit)) continue; /* ** Handle other fields. */ switch (fip->field_bit) { case FIELD_STRIPOFFSETS: /* * We use one field bit for both strip and tile * offsets, and so must be careful in selecting * the appropriate field descriptor (so that tags * are written in sorted order). */ tag = isTiled(tif) ? TIFFTAG_TILEOFFSETS : TIFFTAG_STRIPOFFSETS; if (tag != fip->field_tag) continue; dir->tdir_tag = (uint16) tag; dir->tdir_type = (uint16) TIFF_LONG; dir->tdir_count = (uint32) td->td_nstrips; if (!TIFFWriteLongArray(tif, dir, td->td_stripoffset)) goto bad; break; case FIELD_STRIPBYTECOUNTS: /* * We use one field bit for both strip and tile * byte counts, and so must be careful in selecting * the appropriate field descriptor (so that tags * are written in sorted order). */ tag = isTiled(tif) ? TIFFTAG_TILEBYTECOUNTS : TIFFTAG_STRIPBYTECOUNTS; if (tag != fip->field_tag) continue; dir->tdir_tag = (uint16) tag; dir->tdir_type = (uint16) TIFF_LONG; dir->tdir_count = (uint32) td->td_nstrips; if (!TIFFWriteLongArray(tif, dir, td->td_stripbytecount)) goto bad; break; case FIELD_ROWSPERSTRIP: TIFFSetupShortLong(tif, TIFFTAG_ROWSPERSTRIP, dir, td->td_rowsperstrip); break; case FIELD_COLORMAP: if (!TIFFWriteShortTable(tif, TIFFTAG_COLORMAP, dir, 3, td->td_colormap)) goto bad; break; case FIELD_IMAGEDIMENSIONS: TIFFSetupShortLong(tif, TIFFTAG_IMAGEWIDTH, dir++, td->td_imagewidth); TIFFSetupShortLong(tif, TIFFTAG_IMAGELENGTH, dir, td->td_imagelength); break; case FIELD_TILEDIMENSIONS: TIFFSetupShortLong(tif, TIFFTAG_TILEWIDTH, dir++, td->td_tilewidth); TIFFSetupShortLong(tif, TIFFTAG_TILELENGTH, dir, td->td_tilelength); break; case FIELD_COMPRESSION: TIFFSetupShort(tif, TIFFTAG_COMPRESSION, dir, td->td_compression); break; case FIELD_PHOTOMETRIC: TIFFSetupShort(tif, TIFFTAG_PHOTOMETRIC, dir, td->td_photometric); break; case FIELD_POSITION: WriteRationalPair(TIFF_RATIONAL, TIFFTAG_XPOSITION, td->td_xposition, TIFFTAG_YPOSITION, td->td_yposition); break; case FIELD_RESOLUTION: WriteRationalPair(TIFF_RATIONAL, TIFFTAG_XRESOLUTION, td->td_xresolution, TIFFTAG_YRESOLUTION, td->td_yresolution); break; case FIELD_BITSPERSAMPLE: case FIELD_MINSAMPLEVALUE: case FIELD_MAXSAMPLEVALUE: case FIELD_SAMPLEFORMAT: if (!TIFFWritePerSampleShorts(tif, fip->field_tag, dir)) goto bad; break; case FIELD_SMINSAMPLEVALUE: case FIELD_SMAXSAMPLEVALUE: if (!TIFFWritePerSampleAnys(tif, _TIFFSampleToTagType(tif), fip->field_tag, dir)) goto bad; break; case FIELD_PAGENUMBER: case FIELD_HALFTONEHINTS: case FIELD_YCBCRSUBSAMPLING: if (!TIFFSetupShortPair(tif, fip->field_tag, dir)) goto bad; break; case FIELD_INKNAMES: if (!TIFFWriteInkNames(tif, dir)) goto bad; break; case FIELD_TRANSFERFUNCTION: if (!TIFFWriteTransferFunction(tif, dir)) goto bad; break; case FIELD_SUBIFD: /* * XXX: Always write this field using LONG type * for backward compatibility. */ dir->tdir_tag = (uint16) fip->field_tag; dir->tdir_type = (uint16) TIFF_LONG; dir->tdir_count = (uint32) td->td_nsubifd; if (!TIFFWriteLongArray(tif, dir, td->td_subifd)) goto bad; /* * Total hack: if this directory includes a SubIFD * tag then force the next <n> directories to be * written as ``sub directories'' of this one. This * is used to write things like thumbnails and * image masks that one wants to keep out of the * normal directory linkage access mechanism. */ if (dir->tdir_count > 0) { tif->tif_flags |= TIFF_INSUBIFD; tif->tif_nsubifd = (uint16) dir->tdir_count; if (dir->tdir_count > 1) tif->tif_subifdoff = dir->tdir_offset; else tif->tif_subifdoff = (uint32)( tif->tif_diroff + sizeof (uint16) + ((char*)&dir->tdir_offset-data)); } break; default: /* XXX: Should be fixed and removed. */ if (fip->field_tag == TIFFTAG_DOTRANGE) { if (!TIFFSetupShortPair(tif, fip->field_tag, dir)) goto bad; } else if (!TIFFWriteNormalTag(tif, dir, fip)) goto bad; break; } dir++; if( fip->field_bit != FIELD_CUSTOM ) ResetFieldBit(fields, fip->field_bit); } /* * Write directory. */ dircount = (uint16) nfields; diroff = (uint32) tif->tif_nextdiroff; if (tif->tif_flags & TIFF_SWAB) { /* * The file's byte order is opposite to the * native machine architecture. We overwrite * the directory information with impunity * because it'll be released below after we * write it to the file. Note that all the * other tag construction routines assume that * we do this byte-swapping; i.e. they only * byte-swap indirect data. */ for (dir = (TIFFDirEntry*) data; dircount; dir++, dircount--) { TIFFSwabArrayOfShort(&dir->tdir_tag, 2); TIFFSwabArrayOfLong(&dir->tdir_count, 2); } dircount = (uint16) nfields; TIFFSwabShort(&dircount); TIFFSwabLong(&diroff); } (void) TIFFSeekFile(tif, tif->tif_diroff, SEEK_SET); if (!WriteOK(tif, &dircount, sizeof (dircount))) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error writing directory count"); goto bad; } if (!WriteOK(tif, data, dirsize)) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error writing directory contents"); goto bad; } if (!WriteOK(tif, &diroff, sizeof (diroff))) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error writing directory link"); goto bad; } if (done) { TIFFFreeDirectory(tif); tif->tif_flags &= ~TIFF_DIRTYDIRECT; (*tif->tif_cleanup)(tif); /* * Reset directory-related state for subsequent * directories. */ TIFFCreateDirectory(tif); } _TIFFfree(data); return (1); bad: _TIFFfree(data); return (0); } #undef WriteRationalPair int TIFFWriteDirectory(TIFF* tif) { return _TIFFWriteDirectory(tif, TRUE); } /* * Similar to TIFFWriteDirectory(), writes the directory out * but leaves all data structures in memory so that it can be * written again. This will make a partially written TIFF file * readable before it is successfully completed/closed. */ int TIFFCheckpointDirectory(TIFF* tif) { int rc; /* Setup the strips arrays, if they haven't already been. */ if (tif->tif_dir.td_stripoffset == NULL) (void) TIFFSetupStrips(tif); rc = _TIFFWriteDirectory(tif, FALSE); (void) TIFFSetWriteOffset(tif, TIFFSeekFile(tif, 0, SEEK_END)); return rc; } /* * Process tags that are not special cased. */ static int TIFFWriteNormalTag(TIFF* tif, TIFFDirEntry* dir, const TIFFFieldInfo* fip) { uint16 wc = (uint16) fip->field_writecount; uint32 wc2; dir->tdir_tag = (uint16) fip->field_tag; dir->tdir_type = (uint16) fip->field_type; dir->tdir_count = wc; switch (fip->field_type) { case TIFF_SHORT: case TIFF_SSHORT: if (fip->field_passcount) { uint16* wp; if (wc == (uint16) TIFF_VARIABLE2) { TIFFGetField(tif, fip->field_tag, &wc2, &wp); dir->tdir_count = wc2; } else { /* Assume TIFF_VARIABLE */ TIFFGetField(tif, fip->field_tag, &wc, &wp); dir->tdir_count = wc; } if (!TIFFWriteShortArray(tif, dir, wp)) return 0; } else { if (wc == 1) { uint16 sv; TIFFGetField(tif, fip->field_tag, &sv); dir->tdir_offset = TIFFInsertData(tif, dir->tdir_type, sv); } else { uint16* wp; TIFFGetField(tif, fip->field_tag, &wp); if (!TIFFWriteShortArray(tif, dir, wp)) return 0; } } break; case TIFF_LONG: case TIFF_SLONG: case TIFF_IFD: if (fip->field_passcount) { uint32* lp; if (wc == (uint16) TIFF_VARIABLE2) { TIFFGetField(tif, fip->field_tag, &wc2, &lp); dir->tdir_count = wc2; } else { /* Assume TIFF_VARIABLE */ TIFFGetField(tif, fip->field_tag, &wc, &lp); dir->tdir_count = wc; } if (!TIFFWriteLongArray(tif, dir, lp)) return 0; } else { if (wc == 1) { /* XXX handle LONG->SHORT conversion */ TIFFGetField(tif, fip->field_tag, &dir->tdir_offset); } else { uint32* lp; TIFFGetField(tif, fip->field_tag, &lp); if (!TIFFWriteLongArray(tif, dir, lp)) return 0; } } break; case TIFF_RATIONAL: case TIFF_SRATIONAL: if (fip->field_passcount) { float* fp; if (wc == (uint16) TIFF_VARIABLE2) { TIFFGetField(tif, fip->field_tag, &wc2, &fp); dir->tdir_count = wc2; } else { /* Assume TIFF_VARIABLE */ TIFFGetField(tif, fip->field_tag, &wc, &fp); dir->tdir_count = wc; } if (!TIFFWriteRationalArray(tif, dir, fp)) return 0; } else { if (wc == 1) { float fv; TIFFGetField(tif, fip->field_tag, &fv); if (!TIFFWriteRationalArray(tif, dir, &fv)) return 0; } else { float* fp; TIFFGetField(tif, fip->field_tag, &fp); if (!TIFFWriteRationalArray(tif, dir, fp)) return 0; } } break; case TIFF_FLOAT: if (fip->field_passcount) { float* fp; if (wc == (uint16) TIFF_VARIABLE2) { TIFFGetField(tif, fip->field_tag, &wc2, &fp); dir->tdir_count = wc2; } else { /* Assume TIFF_VARIABLE */ TIFFGetField(tif, fip->field_tag, &wc, &fp); dir->tdir_count = wc; } if (!TIFFWriteFloatArray(tif, dir, fp)) return 0; } else { if (wc == 1) { float fv; TIFFGetField(tif, fip->field_tag, &fv); if (!TIFFWriteFloatArray(tif, dir, &fv)) return 0; } else { float* fp; TIFFGetField(tif, fip->field_tag, &fp); if (!TIFFWriteFloatArray(tif, dir, fp)) return 0; } } break; case TIFF_DOUBLE: if (fip->field_passcount) { double* dp; if (wc == (uint16) TIFF_VARIABLE2) { TIFFGetField(tif, fip->field_tag, &wc2, &dp); dir->tdir_count = wc2; } else { /* Assume TIFF_VARIABLE */ TIFFGetField(tif, fip->field_tag, &wc, &dp); dir->tdir_count = wc; } if (!TIFFWriteDoubleArray(tif, dir, dp)) return 0; } else { if (wc == 1) { double dv; TIFFGetField(tif, fip->field_tag, &dv); if (!TIFFWriteDoubleArray(tif, dir, &dv)) return 0; } else { double* dp; TIFFGetField(tif, fip->field_tag, &dp); if (!TIFFWriteDoubleArray(tif, dir, dp)) return 0; } } break; case TIFF_ASCII: { char* cp; if (fip->field_passcount) TIFFGetField(tif, fip->field_tag, &wc, &cp); else TIFFGetField(tif, fip->field_tag, &cp); dir->tdir_count = (uint32) (strlen(cp) + 1); if (!TIFFWriteByteArray(tif, dir, cp)) return (0); } break; case TIFF_BYTE: case TIFF_SBYTE: if (fip->field_passcount) { char* cp; if (wc == (uint16) TIFF_VARIABLE2) { TIFFGetField(tif, fip->field_tag, &wc2, &cp); dir->tdir_count = wc2; } else { /* Assume TIFF_VARIABLE */ TIFFGetField(tif, fip->field_tag, &wc, &cp); dir->tdir_count = wc; } if (!TIFFWriteByteArray(tif, dir, cp)) return 0; } else { if (wc == 1) { char cv; TIFFGetField(tif, fip->field_tag, &cv); if (!TIFFWriteByteArray(tif, dir, &cv)) return 0; } else { char* cp; TIFFGetField(tif, fip->field_tag, &cp); if (!TIFFWriteByteArray(tif, dir, cp)) return 0; } } break; case TIFF_UNDEFINED: { char* cp; if (wc == (unsigned short) TIFF_VARIABLE) { TIFFGetField(tif, fip->field_tag, &wc, &cp); dir->tdir_count = wc; } else if (wc == (unsigned short) TIFF_VARIABLE2) { TIFFGetField(tif, fip->field_tag, &wc2, &cp); dir->tdir_count = wc2; } else TIFFGetField(tif, fip->field_tag, &cp); if (!TIFFWriteByteArray(tif, dir, cp)) return (0); } break; case TIFF_NOTYPE: break; } return (1); } /* * Setup a directory entry with either a SHORT * or LONG type according to the value. */ static void TIFFSetupShortLong(TIFF* tif, ttag_t tag, TIFFDirEntry* dir, uint32 v) { dir->tdir_tag = (uint16) tag; dir->tdir_count = 1; if (v > 0xffffL) { dir->tdir_type = (short) TIFF_LONG; dir->tdir_offset = v; } else { dir->tdir_type = (short) TIFF_SHORT; dir->tdir_offset = TIFFInsertData(tif, (int) TIFF_SHORT, v); } } /* * Setup a SHORT directory entry */ static void TIFFSetupShort(TIFF* tif, ttag_t tag, TIFFDirEntry* dir, uint16 v) { dir->tdir_tag = (uint16) tag; dir->tdir_count = 1; dir->tdir_type = (short) TIFF_SHORT; dir->tdir_offset = TIFFInsertData(tif, (int) TIFF_SHORT, v); } #undef MakeShortDirent #define NITEMS(x) (sizeof (x) / sizeof (x[0])) /* * Setup a directory entry that references a * samples/pixel array of SHORT values and * (potentially) write the associated indirect * values. */ static int TIFFWritePerSampleShorts(TIFF* tif, ttag_t tag, TIFFDirEntry* dir) { uint16 buf[10], v; uint16* w = buf; uint16 i, samples = tif->tif_dir.td_samplesperpixel; int status; if (samples > NITEMS(buf)) { w = (uint16*) _TIFFmalloc(samples * sizeof (uint16)); if (w == NULL) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "No space to write per-sample shorts"); return (0); } } TIFFGetField(tif, tag, &v); for (i = 0; i < samples; i++) w[i] = v; dir->tdir_tag = (uint16) tag; dir->tdir_type = (uint16) TIFF_SHORT; dir->tdir_count = samples; status = TIFFWriteShortArray(tif, dir, w); if (w != buf) _TIFFfree((char*) w); return (status); } /* * Setup a directory entry that references a samples/pixel array of ``type'' * values and (potentially) write the associated indirect values. The source * data from TIFFGetField() for the specified tag must be returned as double. */ static int TIFFWritePerSampleAnys(TIFF* tif, TIFFDataType type, ttag_t tag, TIFFDirEntry* dir) { double buf[10], v; double* w = buf; uint16 i, samples = tif->tif_dir.td_samplesperpixel; int status; if (samples > NITEMS(buf)) { w = (double*) _TIFFmalloc(samples * sizeof (double)); if (w == NULL) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "No space to write per-sample values"); return (0); } } TIFFGetField(tif, tag, &v); for (i = 0; i < samples; i++) w[i] = v; status = TIFFWriteAnyArray(tif, type, tag, dir, samples, w); if (w != buf) _TIFFfree(w); return (status); } #undef NITEMS /* * Setup a pair of shorts that are returned by * value, rather than as a reference to an array. */ static int TIFFSetupShortPair(TIFF* tif, ttag_t tag, TIFFDirEntry* dir) { uint16 v[2]; TIFFGetField(tif, tag, &v[0], &v[1]); dir->tdir_tag = (uint16) tag; dir->tdir_type = (uint16) TIFF_SHORT; dir->tdir_count = 2; return (TIFFWriteShortArray(tif, dir, v)); } /* * Setup a directory entry for an NxM table of shorts, * where M is known to be 2**bitspersample, and write * the associated indirect data. */ static int TIFFWriteShortTable(TIFF* tif, ttag_t tag, TIFFDirEntry* dir, uint32 n, uint16** table) { uint32 i, off; dir->tdir_tag = (uint16) tag; dir->tdir_type = (short) TIFF_SHORT; /* XXX -- yech, fool TIFFWriteData */ dir->tdir_count = (uint32) (1L<<tif->tif_dir.td_bitspersample); off = tif->tif_dataoff; for (i = 0; i < n; i++) if (!TIFFWriteData(tif, dir, (char *)table[i])) return (0); dir->tdir_count *= n; dir->tdir_offset = off; return (1); } /* * Write/copy data associated with an ASCII or opaque tag value. */ static int TIFFWriteByteArray(TIFF* tif, TIFFDirEntry* dir, char* cp) { if (dir->tdir_count > 4) { if (!TIFFWriteData(tif, dir, cp)) return (0); } else _TIFFmemcpy(&dir->tdir_offset, cp, dir->tdir_count); return (1); } /* * Setup a directory entry of an array of SHORT * or SSHORT and write the associated indirect values. */ static int TIFFWriteShortArray(TIFF* tif, TIFFDirEntry* dir, uint16* v) { if (dir->tdir_count <= 2) { if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) { dir->tdir_offset = (uint32) ((long) v[0] << 16); if (dir->tdir_count == 2) dir->tdir_offset |= v[1] & 0xffff; } else { dir->tdir_offset = v[0] & 0xffff; if (dir->tdir_count == 2) dir->tdir_offset |= (long) v[1] << 16; } return (1); } else return (TIFFWriteData(tif, dir, (char*) v)); } /* * Setup a directory entry of an array of LONG * or SLONG and write the associated indirect values. */ static int TIFFWriteLongArray(TIFF* tif, TIFFDirEntry* dir, uint32* v) { if (dir->tdir_count == 1) { dir->tdir_offset = v[0]; return (1); } else return (TIFFWriteData(tif, dir, (char*) v)); } /* * Setup a directory entry of an array of RATIONAL * or SRATIONAL and write the associated indirect values. */ static int TIFFWriteRationalArray(TIFF* tif, TIFFDirEntry* dir, float* v) { uint32 i; uint32* t; int status; t = (uint32*) _TIFFmalloc(2 * dir->tdir_count * sizeof (uint32)); if (t == NULL) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "No space to write RATIONAL array"); return (0); } for (i = 0; i < dir->tdir_count; i++) { float fv = v[i]; int sign = 1; uint32 den; if (fv < 0) { if (dir->tdir_type == TIFF_RATIONAL) { TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "\"%s\": Information lost writing value (%g) as (unsigned) RATIONAL", _TIFFFieldWithTag(tif,dir->tdir_tag)->field_name, fv); fv = 0; } else fv = -fv, sign = -1; } den = 1L; if (fv > 0) { while (fv < 1L<<(31-3) && den < 1L<<(31-3)) fv *= 1<<3, den *= 1L<<3; } t[2*i+0] = (uint32) (sign * (fv + 0.5)); t[2*i+1] = den; } status = TIFFWriteData(tif, dir, (char *)t); _TIFFfree((char*) t); return (status); } static int TIFFWriteFloatArray(TIFF* tif, TIFFDirEntry* dir, float* v) { TIFFCvtNativeToIEEEFloat(tif, dir->tdir_count, v); if (dir->tdir_count == 1) { dir->tdir_offset = *(uint32*) &v[0]; return (1); } else return (TIFFWriteData(tif, dir, (char*) v)); } static int TIFFWriteDoubleArray(TIFF* tif, TIFFDirEntry* dir, double* v) { TIFFCvtNativeToIEEEDouble(tif, dir->tdir_count, v); return (TIFFWriteData(tif, dir, (char*) v)); } /* * Write an array of ``type'' values for a specified tag (i.e. this is a tag * which is allowed to have different types, e.g. SMaxSampleType). * Internally the data values are represented as double since a double can * hold any of the TIFF tag types (yes, this should really be an abstract * type tany_t for portability). The data is converted into the specified * type in a temporary buffer and then handed off to the appropriate array * writer. */ static int TIFFWriteAnyArray(TIFF* tif, TIFFDataType type, ttag_t tag, TIFFDirEntry* dir, uint32 n, double* v) { char buf[10 * sizeof(double)]; char* w = buf; int i, status = 0; if (n * TIFFDataWidth(type) > sizeof buf) { w = (char*) _TIFFmalloc(n * TIFFDataWidth(type)); if (w == NULL) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "No space to write array"); return (0); } } dir->tdir_tag = (uint16) tag; dir->tdir_type = (uint16) type; dir->tdir_count = n; switch (type) { case TIFF_BYTE: { uint8* bp = (uint8*) w; for (i = 0; i < (int) n; i++) bp[i] = (uint8) v[i]; if (!TIFFWriteByteArray(tif, dir, (char*) bp)) goto out; } break; case TIFF_SBYTE: { int8* bp = (int8*) w; for (i = 0; i < (int) n; i++) bp[i] = (int8) v[i]; if (!TIFFWriteByteArray(tif, dir, (char*) bp)) goto out; } break; case TIFF_SHORT: { uint16* bp = (uint16*) w; for (i = 0; i < (int) n; i++) bp[i] = (uint16) v[i]; if (!TIFFWriteShortArray(tif, dir, (uint16*)bp)) goto out; } break; case TIFF_SSHORT: { int16* bp = (int16*) w; for (i = 0; i < (int) n; i++) bp[i] = (int16) v[i]; if (!TIFFWriteShortArray(tif, dir, (uint16*)bp)) goto out; } break; case TIFF_LONG: { uint32* bp = (uint32*) w; for (i = 0; i < (int) n; i++) bp[i] = (uint32) v[i]; if (!TIFFWriteLongArray(tif, dir, bp)) goto out; } break; case TIFF_SLONG: { int32* bp = (int32*) w; for (i = 0; i < (int) n; i++) bp[i] = (int32) v[i]; if (!TIFFWriteLongArray(tif, dir, (uint32*) bp)) goto out; } break; case TIFF_FLOAT: { float* bp = (float*) w; for (i = 0; i < (int) n; i++) bp[i] = (float) v[i]; if (!TIFFWriteFloatArray(tif, dir, bp)) goto out; } break; case TIFF_DOUBLE: return (TIFFWriteDoubleArray(tif, dir, v)); default: /* TIFF_NOTYPE */ /* TIFF_ASCII */ /* TIFF_UNDEFINED */ /* TIFF_RATIONAL */ /* TIFF_SRATIONAL */ goto out; } status = 1; out: if (w != buf) _TIFFfree(w); return (status); } static int TIFFWriteTransferFunction(TIFF* tif, TIFFDirEntry* dir) { TIFFDirectory* td = &tif->tif_dir; tsize_t n = (1L<<td->td_bitspersample) * sizeof (uint16); uint16** tf = td->td_transferfunction; int ncols; /* * Check if the table can be written as a single column, * or if it must be written as 3 columns. Note that we * write a 3-column tag if there are 2 samples/pixel and * a single column of data won't suffice--hmm. */ switch (td->td_samplesperpixel - td->td_extrasamples) { default: if (_TIFFmemcmp(tf[0], tf[2], n)) { ncols = 3; break; } case 2: if (_TIFFmemcmp(tf[0], tf[1], n)) { ncols = 3; break; } case 1: case 0: ncols = 1; } return (TIFFWriteShortTable(tif, TIFFTAG_TRANSFERFUNCTION, dir, ncols, tf)); } static int TIFFWriteInkNames(TIFF* tif, TIFFDirEntry* dir) { TIFFDirectory* td = &tif->tif_dir; dir->tdir_tag = TIFFTAG_INKNAMES; dir->tdir_type = (short) TIFF_ASCII; dir->tdir_count = td->td_inknameslen; return (TIFFWriteByteArray(tif, dir, td->td_inknames)); } /* * Write a contiguous directory item. */ static int TIFFWriteData(TIFF* tif, TIFFDirEntry* dir, char* cp) { tsize_t cc; if (tif->tif_flags & TIFF_SWAB) { switch (dir->tdir_type) { case TIFF_SHORT: case TIFF_SSHORT: TIFFSwabArrayOfShort((uint16*) cp, dir->tdir_count); break; case TIFF_LONG: case TIFF_SLONG: case TIFF_FLOAT: TIFFSwabArrayOfLong((uint32*) cp, dir->tdir_count); break; case TIFF_RATIONAL: case TIFF_SRATIONAL: TIFFSwabArrayOfLong((uint32*) cp, 2*dir->tdir_count); break; case TIFF_DOUBLE: TIFFSwabArrayOfDouble((double*) cp, dir->tdir_count); break; } } dir->tdir_offset = tif->tif_dataoff; cc = dir->tdir_count * TIFFDataWidth((TIFFDataType) dir->tdir_type); if (SeekOK(tif, dir->tdir_offset) && WriteOK(tif, cp, cc)) { tif->tif_dataoff += (cc + 1) & ~1; return (1); } TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error writing data for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); return (0); } /* * Similar to TIFFWriteDirectory(), but if the directory has already * been written once, it is relocated to the end of the file, in case it * has changed in size. Note that this will result in the loss of the * previously used directory space. */ int TIFFRewriteDirectory( TIFF *tif ) { static const char module[] = "TIFFRewriteDirectory"; /* We don't need to do anything special if it hasn't been written. */ if( tif->tif_diroff == 0 ) return TIFFWriteDirectory( tif ); /* ** Find and zero the pointer to this directory, so that TIFFLinkDirectory ** will cause it to be added after this directories current pre-link. */ /* Is it the first directory in the file? */ if (tif->tif_header.tiff_diroff == tif->tif_diroff) { tif->tif_header.tiff_diroff = 0; tif->tif_diroff = 0; TIFFSeekFile(tif, (toff_t)(TIFF_MAGIC_SIZE+TIFF_VERSION_SIZE), SEEK_SET); if (!WriteOK(tif, &(tif->tif_header.tiff_diroff), sizeof (tif->tif_diroff))) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error updating TIFF header"); return (0); } } else { toff_t nextdir, off; nextdir = tif->tif_header.tiff_diroff; do { uint16 dircount; if (!SeekOK(tif, nextdir) || !ReadOK(tif, &dircount, sizeof (dircount))) { TIFFErrorExt(tif->tif_clientdata, module, "Error fetching directory count"); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); (void) TIFFSeekFile(tif, dircount * sizeof (TIFFDirEntry), SEEK_CUR); if (!ReadOK(tif, &nextdir, sizeof (nextdir))) { TIFFErrorExt(tif->tif_clientdata, module, "Error fetching directory link"); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong(&nextdir); } while (nextdir != tif->tif_diroff && nextdir != 0); off = TIFFSeekFile(tif, 0, SEEK_CUR); /* get current offset */ (void) TIFFSeekFile(tif, off - (toff_t)sizeof(nextdir), SEEK_SET); tif->tif_diroff = 0; if (!WriteOK(tif, &(tif->tif_diroff), sizeof (nextdir))) { TIFFErrorExt(tif->tif_clientdata, module, "Error writing directory link"); return (0); } } /* ** Now use TIFFWriteDirectory() normally. */ return TIFFWriteDirectory( tif ); } /* * Link the current directory into the * directory chain for the file. */ static int TIFFLinkDirectory(TIFF* tif) { static const char module[] = "TIFFLinkDirectory"; toff_t nextdir; toff_t diroff, off; tif->tif_diroff = (TIFFSeekFile(tif, (toff_t) 0, SEEK_END)+1) &~ 1; diroff = tif->tif_diroff; if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong(&diroff); /* * Handle SubIFDs */ if (tif->tif_flags & TIFF_INSUBIFD) { (void) TIFFSeekFile(tif, tif->tif_subifdoff, SEEK_SET); if (!WriteOK(tif, &diroff, sizeof (diroff))) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Error writing SubIFD directory link", tif->tif_name); return (0); } /* * Advance to the next SubIFD or, if this is * the last one configured, revert back to the * normal directory linkage. */ if (--tif->tif_nsubifd) tif->tif_subifdoff += sizeof (diroff); else tif->tif_flags &= ~TIFF_INSUBIFD; return (1); } if (tif->tif_header.tiff_diroff == 0) { /* * First directory, overwrite offset in header. */ tif->tif_header.tiff_diroff = tif->tif_diroff; (void) TIFFSeekFile(tif, (toff_t)(TIFF_MAGIC_SIZE+TIFF_VERSION_SIZE), SEEK_SET); if (!WriteOK(tif, &diroff, sizeof (diroff))) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error writing TIFF header"); return (0); } return (1); } /* * Not the first directory, search to the last and append. */ nextdir = tif->tif_header.tiff_diroff; do { uint16 dircount; if (!SeekOK(tif, nextdir) || !ReadOK(tif, &dircount, sizeof (dircount))) { TIFFErrorExt(tif->tif_clientdata, module, "Error fetching directory count"); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); (void) TIFFSeekFile(tif, dircount * sizeof (TIFFDirEntry), SEEK_CUR); if (!ReadOK(tif, &nextdir, sizeof (nextdir))) { TIFFErrorExt(tif->tif_clientdata, module, "Error fetching directory link"); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong(&nextdir); } while (nextdir != 0); off = TIFFSeekFile(tif, 0, SEEK_CUR); /* get current offset */ (void) TIFFSeekFile(tif, off - (toff_t)sizeof(nextdir), SEEK_SET); if (!WriteOK(tif, &diroff, sizeof (diroff))) { TIFFErrorExt(tif->tif_clientdata, module, "Error writing directory link"); return (0); } return (1); } /* vim: set ts=8 sts=8 sw=8 noet: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/libtiff_2006-02-23-b2ce5d8-207c78a.c
manybugs_data_34
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "zend.h" #include "zend_globals.h" #include "zend_variables.h" #include "zend_API.h" #include "zend_objects.h" #include "zend_objects_API.h" #include "zend_object_handlers.h" #include "zend_interfaces.h" #include "zend_closures.h" #include "zend_compile.h" #define DEBUG_OBJECT_HANDLERS 0 #define Z_OBJ_P(zval_p) \ ((zend_object*)(EG(objects_store).object_buckets[Z_OBJ_HANDLE_P(zval_p)].bucket.obj.object)) /* __X accessors explanation: if we have __get and property that is not part of the properties array is requested, we call __get handler. If it fails, we return uninitialized. if we have __set and property that is not part of the properties array is set, we call __set handler. If it fails, we do not change the array. for both handlers above, when we are inside __get/__set, no further calls for __get/__set for this property of this object will be made, to prevent endless recursion and enable accessors to change properties array. if we have __call and method which is not part of the class function table is called, we cal __call handler. */ ZEND_API void rebuild_object_properties(zend_object *zobj) /* {{{ */ { if (!zobj->properties) { HashPosition pos; zend_property_info *prop_info; zend_class_entry *ce = zobj->ce; ALLOC_HASHTABLE(zobj->properties); zend_hash_init(zobj->properties, 0, NULL, ZVAL_PTR_DTOR, 0); if (ce->default_properties_count) { for (zend_hash_internal_pointer_reset_ex(&ce->properties_info, &pos); zend_hash_get_current_data_ex(&ce->properties_info, (void**)&prop_info, &pos) == SUCCESS; zend_hash_move_forward_ex(&ce->properties_info, &pos)) { if (/*prop_info->ce == ce &&*/ (prop_info->flags & ZEND_ACC_STATIC) == 0 && prop_info->offset >= 0 && zobj->properties_table[prop_info->offset]) { zend_hash_quick_add(zobj->properties, prop_info->name, prop_info->name_length+1, prop_info->h, (void**)&zobj->properties_table[prop_info->offset], sizeof(zval*), (void**)&zobj->properties_table[prop_info->offset]); } } while (ce->parent && ce->parent->default_properties_count) { ce = ce->parent; for (zend_hash_internal_pointer_reset_ex(&ce->properties_info, &pos); zend_hash_get_current_data_ex(&ce->properties_info, (void**)&prop_info, &pos) == SUCCESS; zend_hash_move_forward_ex(&ce->properties_info, &pos)) { if (prop_info->ce == ce && (prop_info->flags & ZEND_ACC_STATIC) == 0 && (prop_info->flags & ZEND_ACC_PRIVATE) != 0 && prop_info->offset >= 0 && zobj->properties_table[prop_info->offset]) { zend_hash_quick_add(zobj->properties, prop_info->name, prop_info->name_length+1, prop_info->h, (void**)&zobj->properties_table[prop_info->offset], sizeof(zval*), (void**)&zobj->properties_table[prop_info->offset]); } } } } } } ZEND_API HashTable *zend_std_get_properties(zval *object TSRMLS_DC) /* {{{ */ { zend_object *zobj; zobj = Z_OBJ_P(object); if (!zobj->properties) { rebuild_object_properties(zobj); } return zobj->properties; } /* }}} */ ZEND_API HashTable *zend_std_get_debug_info(zval *object, int *is_temp TSRMLS_DC) /* {{{ */ { *is_temp = 0; return zend_std_get_properties(object TSRMLS_CC); } /* }}} */ static zval *zend_std_call_getter(zval *object, zval *member TSRMLS_DC) /* {{{ */ { zval *retval = NULL; zend_class_entry *ce = Z_OBJCE_P(object); /* __get handler is called with one argument: property name it should return whether the call was successfull or not */ SEPARATE_ARG_IF_REF(member); zend_call_method_with_1_params(&object, ce, &ce->__get, ZEND_GET_FUNC_NAME, &retval, member); zval_ptr_dtor(&member); if (retval) { Z_DELREF_P(retval); } return retval; } /* }}} */ static int zend_std_call_setter(zval *object, zval *member, zval *value TSRMLS_DC) /* {{{ */ { zval *retval = NULL; int result; zend_class_entry *ce = Z_OBJCE_P(object); SEPARATE_ARG_IF_REF(member); Z_ADDREF_P(value); /* __set handler is called with two arguments: property name value to be set it should return whether the call was successfull or not */ zend_call_method_with_2_params(&object, ce, &ce->__set, ZEND_SET_FUNC_NAME, &retval, member, value); zval_ptr_dtor(&member); zval_ptr_dtor(&value); if (retval) { result = i_zend_is_true(retval) ? SUCCESS : FAILURE; zval_ptr_dtor(&retval); return result; } else { return FAILURE; } } /* }}} */ static void zend_std_call_unsetter(zval *object, zval *member TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = Z_OBJCE_P(object); /* __unset handler is called with one argument: property name */ SEPARATE_ARG_IF_REF(member); zend_call_method_with_1_params(&object, ce, &ce->__unset, ZEND_UNSET_FUNC_NAME, NULL, member); zval_ptr_dtor(&member); } /* }}} */ static zval *zend_std_call_issetter(zval *object, zval *member TSRMLS_DC) /* {{{ */ { zval *retval = NULL; zend_class_entry *ce = Z_OBJCE_P(object); /* __isset handler is called with one argument: property name it should return whether the property is set or not */ SEPARATE_ARG_IF_REF(member); zend_call_method_with_1_params(&object, ce, &ce->__isset, ZEND_ISSET_FUNC_NAME, &retval, member); zval_ptr_dtor(&member); return retval; } /* }}} */ static zend_always_inline int zend_verify_property_access(zend_property_info *property_info, zend_class_entry *ce TSRMLS_DC) /* {{{ */ { switch (property_info->flags & ZEND_ACC_PPP_MASK) { case ZEND_ACC_PUBLIC: return 1; case ZEND_ACC_PROTECTED: return zend_check_protected(property_info->ce, EG(scope)); case ZEND_ACC_PRIVATE: if ((ce==EG(scope) || property_info->ce == EG(scope)) && EG(scope)) { return 1; } else { return 0; } break; } return 0; } /* }}} */ static zend_always_inline zend_bool is_derived_class(zend_class_entry *child_class, zend_class_entry *parent_class) /* {{{ */ { child_class = child_class->parent; while (child_class) { if (child_class == parent_class) { return 1; } child_class = child_class->parent; } return 0; } /* }}} */ static zend_always_inline struct _zend_property_info *zend_get_property_info_quick(zend_class_entry *ce, zval *member, int silent, const zend_literal *key TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; zend_property_info *scope_property_info; zend_bool denied_access = 0; ulong h; if (key && (property_info = CACHED_POLYMORPHIC_PTR(key->cache_slot, ce)) != NULL) { return property_info; } if (UNEXPECTED(Z_STRVAL_P(member)[0] == '\0')) { if (!silent) { if (Z_STRLEN_P(member) == 0) { zend_error_noreturn(E_ERROR, "Cannot access empty property"); } else { zend_error_noreturn(E_ERROR, "Cannot access property started with '\\0'"); } } return NULL; } property_info = NULL; h = key ? key->hash_value : zend_get_hash_value(Z_STRVAL_P(member), Z_STRLEN_P(member) + 1); if (zend_hash_quick_find(&ce->properties_info, Z_STRVAL_P(member), Z_STRLEN_P(member)+1, h, (void **) &property_info)==SUCCESS) { if (UNEXPECTED((property_info->flags & ZEND_ACC_SHADOW) != 0)) { /* if it's a shadow - go to access it's private */ property_info = NULL; } else { if (EXPECTED(zend_verify_property_access(property_info, ce TSRMLS_CC) != 0)) { if (EXPECTED((property_info->flags & ZEND_ACC_CHANGED) != 0) && EXPECTED(!(property_info->flags & ZEND_ACC_PRIVATE))) { /* We still need to make sure that we're not in a context * where the right property is a different 'statically linked' private * continue checking below... */ } else { if (UNEXPECTED((property_info->flags & ZEND_ACC_STATIC) != 0) && !silent) { zend_error(E_STRICT, "Accessing static property %s::$%s as non static", ce->name, Z_STRVAL_P(member)); } if (key) { CACHE_POLYMORPHIC_PTR(key->cache_slot, ce, property_info); } return property_info; } } else { /* Try to look in the scope instead */ denied_access = 1; } } } if (EG(scope) != ce && EG(scope) && is_derived_class(ce, EG(scope)) && zend_hash_quick_find(&EG(scope)->properties_info, Z_STRVAL_P(member), Z_STRLEN_P(member)+1, h, (void **) &scope_property_info)==SUCCESS && scope_property_info->flags & ZEND_ACC_PRIVATE) { if (key) { CACHE_POLYMORPHIC_PTR(key->cache_slot, ce, scope_property_info); } return scope_property_info; } else if (property_info) { if (UNEXPECTED(denied_access != 0)) { /* Information was available, but we were denied access. Error out. */ if (!silent) { zend_error_noreturn(E_ERROR, "Cannot access %s property %s::$%s", zend_visibility_string(property_info->flags), ce->name, Z_STRVAL_P(member)); } return NULL; } else { /* fall through, return property_info... */ if (key) { CACHE_POLYMORPHIC_PTR(key->cache_slot, ce, property_info); } } } else { EG(std_property_info).flags = ZEND_ACC_PUBLIC; EG(std_property_info).name = Z_STRVAL_P(member); EG(std_property_info).name_length = Z_STRLEN_P(member); EG(std_property_info).h = h; EG(std_property_info).ce = ce; EG(std_property_info).offset = -1; property_info = &EG(std_property_info); } return property_info; } /* }}} */ ZEND_API struct _zend_property_info *zend_get_property_info(zend_class_entry *ce, zval *member, int silent TSRMLS_DC) /* {{{ */ { return zend_get_property_info_quick(ce, member, silent, NULL TSRMLS_CC); } /* }}} */ ZEND_API int zend_check_property_access(zend_object *zobj, char *prop_info_name, int prop_info_name_len TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; char *class_name, *prop_name; zval member; zend_unmangle_property_name(prop_info_name, prop_info_name_len, &class_name, &prop_name); ZVAL_STRING(&member, prop_name, 0); property_info = zend_get_property_info_quick(zobj->ce, &member, 1, NULL TSRMLS_CC); if (!property_info) { return FAILURE; } if (class_name && class_name[0] != '*') { if (!(property_info->flags & ZEND_ACC_PRIVATE)) { /* we we're looking for a private prop but found a non private one of the same name */ return FAILURE; } else if (strcmp(prop_info_name+1, property_info->name+1)) { /* we we're looking for a private prop but found a private one of the same name but another class */ return FAILURE; } } return zend_verify_property_access(property_info, zobj->ce TSRMLS_CC) ? SUCCESS : FAILURE; } /* }}} */ static int zend_get_property_guard(zend_object *zobj, zend_property_info *property_info, zval *member, zend_guard **pguard) /* {{{ */ { zend_property_info info; zend_guard stub; if (!property_info) { property_info = &info; info.name = Z_STRVAL_P(member); info.name_length = Z_STRLEN_P(member); info.h = zend_get_hash_value(Z_STRVAL_P(member), Z_STRLEN_P(member) + 1); } if (!zobj->guards) { ALLOC_HASHTABLE(zobj->guards); zend_hash_init(zobj->guards, 0, NULL, NULL, 0); } else if (zend_hash_quick_find(zobj->guards, property_info->name, property_info->name_length+1, property_info->h, (void **) pguard) == SUCCESS) { return SUCCESS; } stub.in_get = 0; stub.in_set = 0; stub.in_unset = 0; stub.in_isset = 0; return zend_hash_quick_add(zobj->guards, property_info->name, property_info->name_length+1, property_info->h, (void**)&stub, sizeof(stub), (void**) pguard); } /* }}} */ zval *zend_std_read_property(zval *object, zval *member, int type, const zend_literal *key TSRMLS_DC) /* {{{ */ { zend_object *zobj; zval *tmp_member = NULL; zval **retval; zval *rv = NULL; zend_property_info *property_info; int silent; silent = (type == BP_VAR_IS); zobj = Z_OBJ_P(object); if (UNEXPECTED(Z_TYPE_P(member) != IS_STRING)) { ALLOC_ZVAL(tmp_member); *tmp_member = *member; INIT_PZVAL(tmp_member); zval_copy_ctor(tmp_member); convert_to_string(tmp_member); member = tmp_member; key = NULL; } #if DEBUG_OBJECT_HANDLERS fprintf(stderr, "Read object #%d property: %s\n", Z_OBJ_HANDLE_P(object), Z_STRVAL_P(member)); #endif /* make zend_get_property_info silent if we have getter - we may want to use it */ property_info = zend_get_property_info_quick(zobj->ce, member, (zobj->ce->__get != NULL), key TSRMLS_CC); if (UNEXPECTED(!property_info) || ((EXPECTED((property_info->flags & ZEND_ACC_STATIC) == 0) && property_info->offset >= 0) ? (zobj->properties ? ((retval = (zval**)zobj->properties_table[property_info->offset]) == NULL) : (*(retval = &zobj->properties_table[property_info->offset]) == NULL)) : (UNEXPECTED(!zobj->properties) || UNEXPECTED(zend_hash_quick_find(zobj->properties, property_info->name, property_info->name_length+1, property_info->h, (void **) &retval) == FAILURE)))) { zend_guard *guard = NULL; if (zobj->ce->__get && zend_get_property_guard(zobj, property_info, member, &guard) == SUCCESS && !guard->in_get) { /* have getter - try with it! */ Z_ADDREF_P(object); if (PZVAL_IS_REF(object)) { SEPARATE_ZVAL(&object); } guard->in_get = 1; /* prevent circular getting */ rv = zend_std_call_getter(object, member TSRMLS_CC); guard->in_get = 0; if (rv) { retval = &rv; if (!Z_ISREF_P(rv) && (type == BP_VAR_W || type == BP_VAR_RW || type == BP_VAR_UNSET)) { if (Z_REFCOUNT_P(rv) > 0) { zval *tmp = rv; ALLOC_ZVAL(rv); *rv = *tmp; zval_copy_ctor(rv); Z_UNSET_ISREF_P(rv); Z_SET_REFCOUNT_P(rv, 0); } if (UNEXPECTED(Z_TYPE_P(rv) != IS_OBJECT)) { zend_error(E_NOTICE, "Indirect modification of overloaded property %s::$%s has no effect", zobj->ce->name, Z_STRVAL_P(member)); } } } else { retval = &EG(uninitialized_zval_ptr); } zval_ptr_dtor(&object); } else { if (zobj->ce->__get && guard && guard->in_get == 1) { if (Z_STRVAL_P(member)[0] == '\0') { if (Z_STRLEN_P(member) == 0) { zend_error(E_ERROR, "Cannot access empty property"); } else { zend_error(E_ERROR, "Cannot access property started with '\\0'"); } } } if (!silent) { zend_error(E_NOTICE,"Undefined property: %s::$%s", zobj->ce->name, Z_STRVAL_P(member)); } retval = &EG(uninitialized_zval_ptr); } } if (UNEXPECTED(tmp_member != NULL)) { Z_ADDREF_PP(retval); zval_ptr_dtor(&tmp_member); Z_DELREF_PP(retval); } return *retval; } /* }}} */ ZEND_API void zend_std_write_property(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC) /* {{{ */ { zend_object *zobj; zval *tmp_member = NULL; zval **variable_ptr; zend_property_info *property_info; zobj = Z_OBJ_P(object); if (UNEXPECTED(Z_TYPE_P(member) != IS_STRING)) { ALLOC_ZVAL(tmp_member); *tmp_member = *member; INIT_PZVAL(tmp_member); zval_copy_ctor(tmp_member); convert_to_string(tmp_member); member = tmp_member; key = NULL; } property_info = zend_get_property_info_quick(zobj->ce, member, (zobj->ce->__set != NULL), key TSRMLS_CC); if (EXPECTED(property_info != NULL) && ((EXPECTED((property_info->flags & ZEND_ACC_STATIC) == 0) && property_info->offset >= 0) ? (zobj->properties ? ((variable_ptr = (zval**)zobj->properties_table[property_info->offset]) != NULL) : (*(variable_ptr = &zobj->properties_table[property_info->offset]) != NULL)) : (EXPECTED(zobj->properties != NULL) && EXPECTED(zend_hash_quick_find(zobj->properties, property_info->name, property_info->name_length+1, property_info->h, (void **) &variable_ptr) == SUCCESS)))) { /* if we already have this value there, we don't actually need to do anything */ if (EXPECTED(*variable_ptr != value)) { /* if we are assigning reference, we shouldn't move it, but instead assign variable to the same pointer */ if (PZVAL_IS_REF(*variable_ptr)) { zval garbage = **variable_ptr; /* old value should be destroyed */ /* To check: can't *variable_ptr be some system variable like error_zval here? */ Z_TYPE_PP(variable_ptr) = Z_TYPE_P(value); (*variable_ptr)->value = value->value; if (Z_REFCOUNT_P(value) > 0) { zval_copy_ctor(*variable_ptr); } zval_dtor(&garbage); } else { zval *garbage = *variable_ptr; /* if we assign referenced variable, we should separate it */ Z_ADDREF_P(value); if (PZVAL_IS_REF(value)) { SEPARATE_ZVAL(&value); } *variable_ptr = value; zval_ptr_dtor(&garbage); } } } else { zend_guard *guard = NULL; if (zobj->ce->__set && zend_get_property_guard(zobj, property_info, member, &guard) == SUCCESS && !guard->in_set) { Z_ADDREF_P(object); if (PZVAL_IS_REF(object)) { SEPARATE_ZVAL(&object); } guard->in_set = 1; /* prevent circular setting */ if (zend_std_call_setter(object, member, value TSRMLS_CC) != SUCCESS) { /* for now, just ignore it - __set should take care of warnings, etc. */ } guard->in_set = 0; zval_ptr_dtor(&object); } else if (EXPECTED(property_info != NULL)) { /* if we assign referenced variable, we should separate it */ Z_ADDREF_P(value); if (PZVAL_IS_REF(value)) { SEPARATE_ZVAL(&value); } if (EXPECTED((property_info->flags & ZEND_ACC_STATIC) == 0) && property_info->offset >= 0) { if (!zobj->properties) { zobj->properties_table[property_info->offset] = value; } else if (zobj->properties_table[property_info->offset]) { *(zval**)zobj->properties_table[property_info->offset] = value; } else { zend_hash_quick_update(zobj->properties, property_info->name, property_info->name_length+1, property_info->h, &value, sizeof(zval *), (void**)&zobj->properties_table[property_info->offset]); } } else { if (!zobj->properties) { rebuild_object_properties(zobj); } zend_hash_quick_update(zobj->properties, property_info->name, property_info->name_length+1, property_info->h, &value, sizeof(zval *), NULL); } } else if (zobj->ce->__set && guard && guard->in_set == 1) { if (Z_STRVAL_P(member)[0] == '\0') { if (Z_STRLEN_P(member) == 0) { zend_error(E_ERROR, "Cannot access empty property"); } else { zend_error(E_ERROR, "Cannot access property started with '\\0'"); } } } } if (UNEXPECTED(tmp_member != NULL)) { zval_ptr_dtor(&tmp_member); } } /* }}} */ zval *zend_std_read_dimension(zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = Z_OBJCE_P(object); zval *retval; if (EXPECTED(instanceof_function_ex(ce, zend_ce_arrayaccess, 1 TSRMLS_CC) != 0)) { if(offset == NULL) { /* [] construct */ ALLOC_INIT_ZVAL(offset); } else { SEPARATE_ARG_IF_REF(offset); } zend_call_method_with_1_params(&object, ce, NULL, "offsetget", &retval, offset); zval_ptr_dtor(&offset); if (UNEXPECTED(!retval)) { if (UNEXPECTED(!EG(exception))) { zend_error_noreturn(E_ERROR, "Undefined offset for object of type %s used as array", ce->name); } return 0; } /* Undo PZVAL_LOCK() */ Z_DELREF_P(retval); return retval; } else { zend_error_noreturn(E_ERROR, "Cannot use object of type %s as array", ce->name); return 0; } } /* }}} */ static void zend_std_write_dimension(zval *object, zval *offset, zval *value TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = Z_OBJCE_P(object); if (EXPECTED(instanceof_function_ex(ce, zend_ce_arrayaccess, 1 TSRMLS_CC) != 0)) { if (!offset) { ALLOC_INIT_ZVAL(offset); } else { SEPARATE_ARG_IF_REF(offset); } zend_call_method_with_2_params(&object, ce, NULL, "offsetset", NULL, offset, value); zval_ptr_dtor(&offset); } else { zend_error_noreturn(E_ERROR, "Cannot use object of type %s as array", ce->name); } } /* }}} */ static int zend_std_has_dimension(zval *object, zval *offset, int check_empty TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = Z_OBJCE_P(object); zval *retval; int result; if (EXPECTED(instanceof_function_ex(ce, zend_ce_arrayaccess, 1 TSRMLS_CC) != 0)) { SEPARATE_ARG_IF_REF(offset); zend_call_method_with_1_params(&object, ce, NULL, "offsetexists", &retval, offset); if (EXPECTED(retval != NULL)) { result = i_zend_is_true(retval); zval_ptr_dtor(&retval); if (check_empty && result && EXPECTED(!EG(exception))) { zend_call_method_with_1_params(&object, ce, NULL, "offsetget", &retval, offset); if (retval) { result = i_zend_is_true(retval); zval_ptr_dtor(&retval); } } } else { result = 0; } zval_ptr_dtor(&offset); } else { zend_error_noreturn(E_ERROR, "Cannot use object of type %s as array", ce->name); return 0; } return result; } /* }}} */ static zval **zend_std_get_property_ptr_ptr(zval *object, zval *member, const zend_literal *key TSRMLS_DC) /* {{{ */ { zend_object *zobj; zval tmp_member; zval **retval; zend_property_info *property_info; zobj = Z_OBJ_P(object); if (UNEXPECTED(Z_TYPE_P(member) != IS_STRING)) { tmp_member = *member; zval_copy_ctor(&tmp_member); convert_to_string(&tmp_member); member = &tmp_member; key = NULL; } #if DEBUG_OBJECT_HANDLERS fprintf(stderr, "Ptr object #%d property: %s\n", Z_OBJ_HANDLE_P(object), Z_STRVAL_P(member)); #endif property_info = zend_get_property_info_quick(zobj->ce, member, (zobj->ce->__get != NULL), key TSRMLS_CC); if (UNEXPECTED(!property_info) || ((EXPECTED((property_info->flags & ZEND_ACC_STATIC) == 0) && property_info->offset >= 0) ? (zobj->properties ? ((retval = (zval**)zobj->properties_table[property_info->offset]) == NULL) : (*(retval = &zobj->properties_table[property_info->offset]) == NULL)) : (UNEXPECTED(!zobj->properties) || UNEXPECTED(zend_hash_quick_find(zobj->properties, property_info->name, property_info->name_length+1, property_info->h, (void **) &retval) == FAILURE)))) { zval *new_zval; zend_guard *guard; if (!zobj->ce->__get || zend_get_property_guard(zobj, property_info, member, &guard) != SUCCESS || (property_info && guard->in_get)) { /* we don't have access controls - will just add it */ new_zval = &EG(uninitialized_zval); /* zend_error(E_NOTICE, "Undefined property: %s", Z_STRVAL_P(member)); */ Z_ADDREF_P(new_zval); if (EXPECTED((property_info->flags & ZEND_ACC_STATIC) == 0) && property_info->offset >= 0) { if (!zobj->properties) { zobj->properties_table[property_info->offset] = new_zval; retval = &zobj->properties_table[property_info->offset]; } else if (zobj->properties_table[property_info->offset]) { *(zval**)zobj->properties_table[property_info->offset] = new_zval; retval = (zval**)zobj->properties_table[property_info->offset]; } else { zend_hash_quick_update(zobj->properties, property_info->name, property_info->name_length+1, property_info->h, &new_zval, sizeof(zval *), (void**)&zobj->properties_table[property_info->offset]); retval = (zval**)zobj->properties_table[property_info->offset]; } } else { if (!zobj->properties) { rebuild_object_properties(zobj); } zend_hash_quick_update(zobj->properties, property_info->name, property_info->name_length+1, property_info->h, &new_zval, sizeof(zval *), (void **) &retval); } } else { /* we do have getter - fail and let it try again with usual get/set */ retval = NULL; } } if (UNEXPECTED(member == &tmp_member)) { zval_dtor(member); } return retval; } /* }}} */ static void zend_std_unset_property(zval *object, zval *member, const zend_literal *key TSRMLS_DC) /* {{{ */ { zend_object *zobj; zval *tmp_member = NULL; zend_property_info *property_info; zobj = Z_OBJ_P(object); if (UNEXPECTED(Z_TYPE_P(member) != IS_STRING)) { ALLOC_ZVAL(tmp_member); *tmp_member = *member; INIT_PZVAL(tmp_member); zval_copy_ctor(tmp_member); convert_to_string(tmp_member); member = tmp_member; key = NULL; } property_info = zend_get_property_info_quick(zobj->ce, member, (zobj->ce->__unset != NULL), key TSRMLS_CC); if (EXPECTED(property_info != NULL) && EXPECTED((property_info->flags & ZEND_ACC_STATIC) == 0) && !zobj->properties && property_info->offset >= 0 && EXPECTED(zobj->properties_table[property_info->offset] != NULL)) { zval_ptr_dtor(&zobj->properties_table[property_info->offset]); zobj->properties_table[property_info->offset] = NULL; } else if (UNEXPECTED(!property_info) || !zobj->properties || UNEXPECTED(zend_hash_quick_del(zobj->properties, property_info->name, property_info->name_length+1, property_info->h) == FAILURE)) { zend_guard *guard = NULL; if (zobj->ce->__unset && zend_get_property_guard(zobj, property_info, member, &guard) == SUCCESS && !guard->in_unset) { /* have unseter - try with it! */ Z_ADDREF_P(object); if (PZVAL_IS_REF(object)) { SEPARATE_ZVAL(&object); } guard->in_unset = 1; /* prevent circular unsetting */ zend_std_call_unsetter(object, member TSRMLS_CC); guard->in_unset = 0; zval_ptr_dtor(&object); } else if (zobj->ce->__unset && guard && guard->in_unset == 1) { if (Z_STRVAL_P(member)[0] == '\0') { if (Z_STRLEN_P(member) == 0) { zend_error(E_ERROR, "Cannot access empty property"); } else { zend_error(E_ERROR, "Cannot access property started with '\\0'"); } } } } else if (EXPECTED(property_info != NULL) && EXPECTED((property_info->flags & ZEND_ACC_STATIC) == 0) && property_info->offset >= 0) { zobj->properties_table[property_info->offset] = NULL; } if (UNEXPECTED(tmp_member != NULL)) { zval_ptr_dtor(&tmp_member); } } /* }}} */ static void zend_std_unset_dimension(zval *object, zval *offset TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = Z_OBJCE_P(object); if (instanceof_function_ex(ce, zend_ce_arrayaccess, 1 TSRMLS_CC)) { SEPARATE_ARG_IF_REF(offset); zend_call_method_with_1_params(&object, ce, NULL, "offsetunset", NULL, offset); zval_ptr_dtor(&offset); } else { zend_error_noreturn(E_ERROR, "Cannot use object of type %s as array", ce->name); } } /* }}} */ ZEND_API void zend_std_call_user_call(INTERNAL_FUNCTION_PARAMETERS) /* {{{ */ { zend_internal_function *func = (zend_internal_function *)EG(current_execute_data)->function_state.function; zval *method_name_ptr, *method_args_ptr; zval *method_result_ptr = NULL; zend_class_entry *ce = Z_OBJCE_P(this_ptr); ALLOC_ZVAL(method_args_ptr); INIT_PZVAL(method_args_ptr); array_init_size(method_args_ptr, ZEND_NUM_ARGS()); if (UNEXPECTED(zend_copy_parameters_array(ZEND_NUM_ARGS(), method_args_ptr TSRMLS_CC) == FAILURE)) { zval_dtor(method_args_ptr); zend_error_noreturn(E_ERROR, "Cannot get arguments for __call"); RETURN_FALSE; } ALLOC_ZVAL(method_name_ptr); INIT_PZVAL(method_name_ptr); ZVAL_STRING(method_name_ptr, func->function_name, 0); /* no dup - it's a copy */ /* __call handler is called with two arguments: method name array of method parameters */ zend_call_method_with_2_params(&this_ptr, ce, &ce->__call, ZEND_CALL_FUNC_NAME, &method_result_ptr, method_name_ptr, method_args_ptr); if (method_result_ptr) { if (Z_ISREF_P(method_result_ptr) || Z_REFCOUNT_P(method_result_ptr) > 1) { RETVAL_ZVAL(method_result_ptr, 1, 1); } else { RETVAL_ZVAL(method_result_ptr, 0, 1); } } /* now destruct all auxiliaries */ zval_ptr_dtor(&method_args_ptr); zval_ptr_dtor(&method_name_ptr); /* destruct the function also, then - we have allocated it in get_method */ efree(func); } /* }}} */ /* Ensures that we're allowed to call a private method. * Returns the function address that should be called, or NULL * if no such function exists. */ static inline zend_function *zend_check_private_int(zend_function *fbc, zend_class_entry *ce, char *function_name_strval, int function_name_strlen, ulong hash_value TSRMLS_DC) /* {{{ */ { if (!ce) { return 0; } /* We may call a private function if: * 1. The class of our object is the same as the scope, and the private * function (EX(fbc)) has the same scope. * 2. One of our parent classes are the same as the scope, and it contains * a private function with the same name that has the same scope. */ if (fbc->common.scope == ce && EG(scope) == ce) { /* rule #1 checks out ok, allow the function call */ return fbc; } /* Check rule #2 */ ce = ce->parent; while (ce) { if (ce == EG(scope)) { if (zend_hash_quick_find(&ce->function_table, function_name_strval, function_name_strlen+1, hash_value, (void **) &fbc)==SUCCESS && fbc->op_array.fn_flags & ZEND_ACC_PRIVATE && fbc->common.scope == EG(scope)) { return fbc; } break; } ce = ce->parent; } return NULL; } /* }}} */ ZEND_API int zend_check_private(zend_function *fbc, zend_class_entry *ce, char *function_name_strval, int function_name_strlen TSRMLS_DC) /* {{{ */ { return zend_check_private_int(fbc, ce, function_name_strval, function_name_strlen, zend_hash_func(function_name_strval, function_name_strlen+1) TSRMLS_CC) != NULL; } /* }}} */ /* Ensures that we're allowed to call a protected method. */ ZEND_API int zend_check_protected(zend_class_entry *ce, zend_class_entry *scope) /* {{{ */ { zend_class_entry *fbc_scope = ce; /* Is the context that's calling the function, the same as one of * the function's parents? */ while (fbc_scope) { if (fbc_scope==scope) { return 1; } fbc_scope = fbc_scope->parent; } /* Is the function's scope the same as our current object context, * or any of the parents of our context? */ while (scope) { if (scope==ce) { return 1; } scope = scope->parent; } return 0; } /* }}} */ static inline zend_class_entry * zend_get_function_root_class(zend_function *fbc) /* {{{ */ { return fbc->common.prototype ? fbc->common.prototype->common.scope : fbc->common.scope; } /* }}} */ static inline union _zend_function *zend_get_user_call_function(zend_class_entry *ce, const char *method_name, int method_len) /* {{{ */ { zend_internal_function *call_user_call = emalloc(sizeof(zend_internal_function)); call_user_call->type = ZEND_INTERNAL_FUNCTION; call_user_call->module = (ce->type == ZEND_INTERNAL_CLASS) ? ce->info.internal.module : NULL; call_user_call->handler = zend_std_call_user_call; call_user_call->arg_info = NULL; call_user_call->num_args = 0; call_user_call->scope = ce; call_user_call->fn_flags = ZEND_ACC_CALL_VIA_HANDLER; call_user_call->function_name = estrndup(method_name, method_len); return (union _zend_function *)call_user_call; } /* }}} */ static union _zend_function *zend_std_get_method(zval **object_ptr, char *method_name, int method_len, const zend_literal *key TSRMLS_DC) /* {{{ */ { zend_function *fbc; zval *object = *object_ptr; zend_object *zobj = Z_OBJ_P(object); ulong hash_value; char *lc_method_name; ALLOCA_FLAG(use_heap) if (EXPECTED(key != NULL)) { lc_method_name = Z_STRVAL(key->constant); hash_value = key->hash_value; } else { lc_method_name = do_alloca(method_len+1, use_heap); /* Create a zend_copy_str_tolower(dest, src, src_length); */ zend_str_tolower_copy(lc_method_name, method_name, method_len); hash_value = zend_hash_func(lc_method_name, method_len+1); } if (UNEXPECTED(zend_hash_quick_find(&zobj->ce->function_table, lc_method_name, method_len+1, hash_value, (void **)&fbc) == FAILURE)) { if (UNEXPECTED(!key)) { free_alloca(lc_method_name, use_heap); } if (zobj->ce->__call) { return zend_get_user_call_function(zobj->ce, method_name, method_len); } else { return NULL; } } /* Check access level */ if (fbc->op_array.fn_flags & ZEND_ACC_PRIVATE) { zend_function *updated_fbc; /* Ensure that if we're calling a private function, we're allowed to do so. * If we're not and __call() handler exists, invoke it, otherwise error out. */ updated_fbc = zend_check_private_int(fbc, Z_OBJ_HANDLER_P(object, get_class_entry)(object TSRMLS_CC), lc_method_name, method_len, hash_value TSRMLS_CC); if (EXPECTED(updated_fbc != NULL)) { fbc = updated_fbc; } else { if (zobj->ce->__call) { fbc = zend_get_user_call_function(zobj->ce, method_name, method_len); } else { zend_error_noreturn(E_ERROR, "Call to %s method %s::%s() from context '%s'", zend_visibility_string(fbc->common.fn_flags), ZEND_FN_SCOPE_NAME(fbc), method_name, EG(scope) ? EG(scope)->name : ""); } } } else { /* Ensure that we haven't overridden a private function and end up calling * the overriding public function... */ if (EG(scope) && is_derived_class(fbc->common.scope, EG(scope)) && fbc->op_array.fn_flags & ZEND_ACC_CHANGED) { zend_function *priv_fbc; if (zend_hash_quick_find(&EG(scope)->function_table, lc_method_name, method_len+1, hash_value, (void **) &priv_fbc)==SUCCESS && priv_fbc->common.fn_flags & ZEND_ACC_PRIVATE && priv_fbc->common.scope == EG(scope)) { fbc = priv_fbc; } } if ((fbc->common.fn_flags & ZEND_ACC_PROTECTED)) { /* Ensure that if we're calling a protected function, we're allowed to do so. * If we're not and __call() handler exists, invoke it, otherwise error out. */ if (UNEXPECTED(!zend_check_protected(zend_get_function_root_class(fbc), EG(scope)))) { if (zobj->ce->__call) { fbc = zend_get_user_call_function(zobj->ce, method_name, method_len); } else { zend_error_noreturn(E_ERROR, "Call to %s method %s::%s() from context '%s'", zend_visibility_string(fbc->common.fn_flags), ZEND_FN_SCOPE_NAME(fbc), method_name, EG(scope) ? EG(scope)->name : ""); } } } } if (UNEXPECTED(!key)) { free_alloca(lc_method_name, use_heap); } return fbc; } /* }}} */ ZEND_API void zend_std_callstatic_user_call(INTERNAL_FUNCTION_PARAMETERS) /* {{{ */ { zend_internal_function *func = (zend_internal_function *)EG(current_execute_data)->function_state.function; zval *method_name_ptr, *method_args_ptr; zval *method_result_ptr = NULL; zend_class_entry *ce = EG(scope); ALLOC_ZVAL(method_args_ptr); INIT_PZVAL(method_args_ptr); array_init_size(method_args_ptr, ZEND_NUM_ARGS()); if (UNEXPECTED(zend_copy_parameters_array(ZEND_NUM_ARGS(), method_args_ptr TSRMLS_CC) == FAILURE)) { zval_dtor(method_args_ptr); zend_error_noreturn(E_ERROR, "Cannot get arguments for " ZEND_CALLSTATIC_FUNC_NAME); RETURN_FALSE; } ALLOC_ZVAL(method_name_ptr); INIT_PZVAL(method_name_ptr); ZVAL_STRING(method_name_ptr, func->function_name, 0); /* no dup - it's a copy */ /* __callStatic handler is called with two arguments: method name array of method parameters */ zend_call_method_with_2_params(NULL, ce, &ce->__callstatic, ZEND_CALLSTATIC_FUNC_NAME, &method_result_ptr, method_name_ptr, method_args_ptr); if (method_result_ptr) { if (Z_ISREF_P(method_result_ptr) || Z_REFCOUNT_P(method_result_ptr) > 1) { RETVAL_ZVAL(method_result_ptr, 1, 1); } else { RETVAL_ZVAL(method_result_ptr, 0, 1); } } /* now destruct all auxiliaries */ zval_ptr_dtor(&method_args_ptr); zval_ptr_dtor(&method_name_ptr); /* destruct the function also, then - we have allocated it in get_method */ efree(func); } /* }}} */ static inline union _zend_function *zend_get_user_callstatic_function(zend_class_entry *ce, const char *method_name, int method_len) /* {{{ */ { zend_internal_function *callstatic_user_call = emalloc(sizeof(zend_internal_function)); callstatic_user_call->type = ZEND_INTERNAL_FUNCTION; callstatic_user_call->module = (ce->type == ZEND_INTERNAL_CLASS) ? ce->info.internal.module : NULL; callstatic_user_call->handler = zend_std_callstatic_user_call; callstatic_user_call->arg_info = NULL; callstatic_user_call->num_args = 0; callstatic_user_call->scope = ce; callstatic_user_call->fn_flags = ZEND_ACC_STATIC | ZEND_ACC_PUBLIC | ZEND_ACC_CALL_VIA_HANDLER; callstatic_user_call->function_name = estrndup(method_name, method_len); return (zend_function *)callstatic_user_call; } /* }}} */ /* This is not (yet?) in the API, but it belongs in the built-in objects callbacks */ ZEND_API zend_function *zend_std_get_static_method(zend_class_entry *ce, char *function_name_strval, int function_name_strlen, const zend_literal *key TSRMLS_DC) /* {{{ */ { zend_function *fbc = NULL; char *lc_class_name, *lc_function_name = NULL; ulong hash_value; ALLOCA_FLAG(use_heap) if (EXPECTED(key != NULL)) { lc_function_name = Z_STRVAL(key->constant); hash_value = key->hash_value; } else { lc_function_name = do_alloca(function_name_strlen+1, use_heap); /* Create a zend_copy_str_tolower(dest, src, src_length); */ zend_str_tolower_copy(lc_function_name, function_name_strval, function_name_strlen); hash_value = zend_hash_func(lc_function_name, function_name_strlen+1); } if (function_name_strlen == ce->name_length && ce->constructor) { lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); /* Only change the method to the constructor if the constructor isn't called __construct * we check for __ so we can be binary safe for lowering, we should use ZEND_CONSTRUCTOR_FUNC_NAME */ if (!memcmp(lc_class_name, lc_function_name, function_name_strlen) && memcmp(ce->constructor->common.function_name, "__", sizeof("__") - 1)) { fbc = ce->constructor; } efree(lc_class_name); } if (EXPECTED(!fbc) && UNEXPECTED(zend_hash_quick_find(&ce->function_table, lc_function_name, function_name_strlen+1, hash_value, (void **) &fbc)==FAILURE)) { if (UNEXPECTED(!key)) { free_alloca(lc_function_name, use_heap); } if (ce->__call && EG(This) && Z_OBJ_HT_P(EG(This))->get_class_entry && instanceof_function(Z_OBJCE_P(EG(This)), ce TSRMLS_CC)) { return zend_get_user_call_function(ce, function_name_strval, function_name_strlen); } else if (ce->__callstatic) { return zend_get_user_callstatic_function(ce, function_name_strval, function_name_strlen); } else { return NULL; } } #if MBO_0 /* right now this function is used for non static method lookup too */ /* Is the function static */ if (UNEXPECTED(!(fbc->common.fn_flags & ZEND_ACC_STATIC))) { zend_error_noreturn(E_ERROR, "Cannot call non static method %s::%s() without object", ZEND_FN_SCOPE_NAME(fbc), fbc->common.function_name); } #endif if (fbc->op_array.fn_flags & ZEND_ACC_PUBLIC) { /* No further checks necessary, most common case */ } else if (fbc->op_array.fn_flags & ZEND_ACC_PRIVATE) { zend_function *updated_fbc; /* Ensure that if we're calling a private function, we're allowed to do so. */ updated_fbc = zend_check_private_int(fbc, EG(scope), lc_function_name, function_name_strlen, hash_value TSRMLS_CC); if (EXPECTED(updated_fbc != NULL)) { fbc = updated_fbc; } else { if (ce->__callstatic) { fbc = zend_get_user_callstatic_function(ce, function_name_strval, function_name_strlen); } else { zend_error_noreturn(E_ERROR, "Call to %s method %s::%s() from context '%s'", zend_visibility_string(fbc->common.fn_flags), ZEND_FN_SCOPE_NAME(fbc), function_name_strval, EG(scope) ? EG(scope)->name : ""); } } } else if ((fbc->common.fn_flags & ZEND_ACC_PROTECTED)) { /* Ensure that if we're calling a protected function, we're allowed to do so. */ if (UNEXPECTED(!zend_check_protected(zend_get_function_root_class(fbc), EG(scope)))) { if (ce->__callstatic) { fbc = zend_get_user_callstatic_function(ce, function_name_strval, function_name_strlen); } else { zend_error_noreturn(E_ERROR, "Call to %s method %s::%s() from context '%s'", zend_visibility_string(fbc->common.fn_flags), ZEND_FN_SCOPE_NAME(fbc), function_name_strval, EG(scope) ? EG(scope)->name : ""); } } } if (UNEXPECTED(!key)) { free_alloca(lc_function_name, use_heap); } return fbc; } /* }}} */ ZEND_API zval **zend_std_get_static_property(zend_class_entry *ce, char *property_name, int property_name_len, zend_bool silent, const zend_literal *key TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; ulong hash_value; if (UNEXPECTED(!key) || (property_info = CACHED_POLYMORPHIC_PTR(key->cache_slot, ce)) == NULL) { if (EXPECTED(key != NULL)) { hash_value = key->hash_value; } else { hash_value = zend_hash_func(property_name, property_name_len+1); } if (UNEXPECTED(zend_hash_quick_find(&ce->properties_info, property_name, property_name_len+1, hash_value, (void **) &property_info)==FAILURE)) { if (!silent) { zend_error_noreturn(E_ERROR, "Access to undeclared static property: %s::$%s", ce->name, property_name); } return NULL; } #if DEBUG_OBJECT_HANDLERS zend_printf("Access type for %s::%s is %s\n", ce->name, property_name, zend_visibility_string(property_info->flags)); #endif if (UNEXPECTED(!zend_verify_property_access(property_info, ce TSRMLS_CC))) { if (!silent) { zend_error_noreturn(E_ERROR, "Cannot access %s property %s::$%s", zend_visibility_string(property_info->flags), ce->name, property_name); } return NULL; } if (UNEXPECTED((property_info->flags & ZEND_ACC_STATIC) == 0)) { if (!silent) { zend_error_noreturn(E_ERROR, "Access to undeclared static property: %s::$%s", ce->name, property_name); } return NULL; } zend_update_class_constants(ce TSRMLS_CC); if (EXPECTED(key != NULL)) { CACHE_POLYMORPHIC_PTR(key->cache_slot, ce, property_info); } } return &CE_STATIC_MEMBERS(ce)[property_info->offset]; } /* }}} */ ZEND_API zend_bool zend_std_unset_static_property(zend_class_entry *ce, char *property_name, int property_name_len, const zend_literal *key TSRMLS_DC) /* {{{ */ { zend_error_noreturn(E_ERROR, "Attempt to unset static property %s::$%s", ce->name, property_name); return 0; } /* }}} */ ZEND_API union _zend_function *zend_std_get_constructor(zval *object TSRMLS_DC) /* {{{ */ { zend_object *zobj = Z_OBJ_P(object); zend_function *constructor = zobj->ce->constructor; if (constructor) { if (constructor->op_array.fn_flags & ZEND_ACC_PUBLIC) { /* No further checks necessary */ } else if (constructor->op_array.fn_flags & ZEND_ACC_PRIVATE) { /* Ensure that if we're calling a private function, we're allowed to do so. */ if (UNEXPECTED(constructor->common.scope != EG(scope))) { if (EG(scope)) { zend_error_noreturn(E_ERROR, "Call to private %s::%s() from context '%s'", constructor->common.scope->name, constructor->common.function_name, EG(scope)->name); } else { zend_error_noreturn(E_ERROR, "Call to private %s::%s() from invalid context", constructor->common.scope->name, constructor->common.function_name); } } } else if ((constructor->common.fn_flags & ZEND_ACC_PROTECTED)) { /* Ensure that if we're calling a protected function, we're allowed to do so. * Constructors only have prototype if they are defined by an interface but * it is the compilers responsibility to take care of the prototype. */ if (UNEXPECTED(!zend_check_protected(zend_get_function_root_class(constructor), EG(scope)))) { if (EG(scope)) { zend_error_noreturn(E_ERROR, "Call to protected %s::%s() from context '%s'", constructor->common.scope->name, constructor->common.function_name, EG(scope)->name); } else { zend_error_noreturn(E_ERROR, "Call to protected %s::%s() from invalid context", constructor->common.scope->name, constructor->common.function_name); } } } } return constructor; } /* }}} */ int zend_compare_symbol_tables_i(HashTable *ht1, HashTable *ht2 TSRMLS_DC); static int zend_std_compare_objects(zval *o1, zval *o2 TSRMLS_DC) /* {{{ */ { zend_object *zobj1, *zobj2; zobj1 = Z_OBJ_P(o1); zobj2 = Z_OBJ_P(o2); if (zobj1->ce != zobj2->ce) { return 1; /* different classes */ } if (!zobj1->properties && !zobj2->properties) { int i; for (i = 0; i < zobj1->ce->default_properties_count; i++) { if (zobj1->properties_table[i]) { if (zobj2->properties_table[i]) { zval result; if (compare_function(&result, zobj1->properties_table[i], zobj2->properties_table[i] TSRMLS_CC)==FAILURE) { return 1; } if (Z_LVAL(result) != 0) { return Z_LVAL(result); } } else { return 1; } } else { if (zobj2->properties_table[i]) { return 1; } else { return 0; } } } return 0; } else { if (!zobj1->properties) { rebuild_object_properties(zobj1); } if (!zobj2->properties) { rebuild_object_properties(zobj2); } return zend_compare_symbol_tables_i(zobj1->properties, zobj2->properties TSRMLS_CC); } } /* }}} */ static int zend_std_has_property(zval *object, zval *member, int has_set_exists, const zend_literal *key TSRMLS_DC) /* {{{ */ { zend_object *zobj; int result; zval **value = NULL; zval *tmp_member = NULL; zend_property_info *property_info; zobj = Z_OBJ_P(object); if (UNEXPECTED(Z_TYPE_P(member) != IS_STRING)) { ALLOC_ZVAL(tmp_member); *tmp_member = *member; INIT_PZVAL(tmp_member); zval_copy_ctor(tmp_member); convert_to_string(tmp_member); member = tmp_member; key = NULL; } #if DEBUG_OBJECT_HANDLERS fprintf(stderr, "Read object #%d property: %s\n", Z_OBJ_HANDLE_P(object), Z_STRVAL_P(member)); #endif property_info = zend_get_property_info_quick(zobj->ce, member, 1, key TSRMLS_CC); if (UNEXPECTED(!property_info) || ((EXPECTED((property_info->flags & ZEND_ACC_STATIC) == 0) && property_info->offset >= 0) ? (zobj->properties ? ((value = (zval**)zobj->properties_table[property_info->offset]) == NULL) : (*(value = &zobj->properties_table[property_info->offset]) == NULL)) : (UNEXPECTED(!zobj->properties) || UNEXPECTED(zend_hash_quick_find(zobj->properties, property_info->name, property_info->name_length+1, property_info->h, (void **) &value) == FAILURE)))) { zend_guard *guard; result = 0; if ((has_set_exists != 2) && zobj->ce->__isset && zend_get_property_guard(zobj, property_info, member, &guard) == SUCCESS && !guard->in_isset) { zval *rv; /* have issetter - try with it! */ Z_ADDREF_P(object); if (PZVAL_IS_REF(object)) { SEPARATE_ZVAL(&object); } guard->in_isset = 1; /* prevent circular getting */ rv = zend_std_call_issetter(object, member TSRMLS_CC); if (rv) { result = zend_is_true(rv); zval_ptr_dtor(&rv); if (has_set_exists && result) { if (EXPECTED(!EG(exception)) && zobj->ce->__get && !guard->in_get) { guard->in_get = 1; rv = zend_std_call_getter(object, member TSRMLS_CC); guard->in_get = 0; if (rv) { Z_ADDREF_P(rv); result = i_zend_is_true(rv); zval_ptr_dtor(&rv); } else { result = 0; } } else { result = 0; } } } guard->in_isset = 0; zval_ptr_dtor(&object); } } else { switch (has_set_exists) { case 0: result = (Z_TYPE_PP(value) != IS_NULL); break; default: result = zend_is_true(*value); break; case 2: result = 1; break; } } if (UNEXPECTED(tmp_member != NULL)) { zval_ptr_dtor(&tmp_member); } return result; } /* }}} */ zend_class_entry *zend_std_object_get_class(const zval *object TSRMLS_DC) /* {{{ */ { zend_object *zobj; zobj = Z_OBJ_P(object); return zobj->ce; } /* }}} */ int zend_std_object_get_class_name(const zval *object, char **class_name, zend_uint *class_name_len, int parent TSRMLS_DC) /* {{{ */ { zend_object *zobj; zend_class_entry *ce; zobj = Z_OBJ_P(object); if (parent) { if (!zobj->ce->parent) { return FAILURE; } ce = zobj->ce->parent; } else { ce = zobj->ce; } *class_name_len = ce->name_length; *class_name = estrndup(ce->name, ce->name_length); return SUCCESS; } /* }}} */ ZEND_API int zend_std_cast_object_tostring(zval *readobj, zval *writeobj, int type TSRMLS_DC) /* {{{ */ { zval *retval; zend_class_entry *ce; switch (type) { case IS_STRING: ce = Z_OBJCE_P(readobj); if (ce->__tostring && (zend_call_method_with_0_params(&readobj, ce, &ce->__tostring, "__tostring", &retval) || EG(exception))) { if (UNEXPECTED(EG(exception) != NULL)) { if (retval) { zval_ptr_dtor(&retval); } zend_error_noreturn(E_ERROR, "Method %s::__toString() must not throw an exception", ce->name); return FAILURE; } if (EXPECTED(Z_TYPE_P(retval) == IS_STRING)) { INIT_PZVAL(writeobj); if (readobj == writeobj) { zval_dtor(readobj); } ZVAL_ZVAL(writeobj, retval, 1, 1); if (Z_TYPE_P(writeobj) != type) { convert_to_explicit_type(writeobj, type); } return SUCCESS; } else { zval_ptr_dtor(&retval); INIT_PZVAL(writeobj); if (readobj == writeobj) { zval_dtor(readobj); } ZVAL_EMPTY_STRING(writeobj); zend_error(E_RECOVERABLE_ERROR, "Method %s::__toString() must return a string value", ce->name); return SUCCESS; } } return FAILURE; case IS_BOOL: INIT_PZVAL(writeobj); ZVAL_BOOL(writeobj, 1); return SUCCESS; case IS_LONG: ce = Z_OBJCE_P(readobj); zend_error(E_NOTICE, "Object of class %s could not be converted to int", ce->name); INIT_PZVAL(writeobj); if (readobj == writeobj) { zval_dtor(readobj); } ZVAL_LONG(writeobj, 1); return SUCCESS; case IS_DOUBLE: ce = Z_OBJCE_P(readobj); zend_error(E_NOTICE, "Object of class %s could not be converted to double", ce->name); INIT_PZVAL(writeobj); if (readobj == writeobj) { zval_dtor(readobj); } ZVAL_DOUBLE(writeobj, 1); return SUCCESS; default: INIT_PZVAL(writeobj); Z_TYPE_P(writeobj) = IS_NULL; break; } return FAILURE; } /* }}} */ int zend_std_get_closure(zval *obj, zend_class_entry **ce_ptr, zend_function **fptr_ptr, zval **zobj_ptr TSRMLS_DC) /* {{{ */ { zend_class_entry *ce; if (Z_TYPE_P(obj) != IS_OBJECT) { return FAILURE; } ce = Z_OBJCE_P(obj); if (zend_hash_find(&ce->function_table, ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME), (void**)fptr_ptr) == FAILURE) { return FAILURE; } *ce_ptr = ce; if ((*fptr_ptr)->common.fn_flags & ZEND_ACC_STATIC) { if (zobj_ptr) { *zobj_ptr = NULL; } } else { if (zobj_ptr) { *zobj_ptr = obj; } } return SUCCESS; } /* }}} */ ZEND_API zend_object_handlers std_object_handlers = { zend_objects_store_add_ref, /* add_ref */ zend_objects_store_del_ref, /* del_ref */ zend_objects_clone_obj, /* clone_obj */ zend_std_read_property, /* read_property */ zend_std_write_property, /* write_property */ zend_std_read_dimension, /* read_dimension */ zend_std_write_dimension, /* write_dimension */ zend_std_get_property_ptr_ptr, /* get_property_ptr_ptr */ NULL, /* get */ NULL, /* set */ zend_std_has_property, /* has_property */ zend_std_unset_property, /* unset_property */ zend_std_has_dimension, /* has_dimension */ zend_std_unset_dimension, /* unset_dimension */ zend_std_get_properties, /* get_properties */ zend_std_get_method, /* get_method */ NULL, /* call_method */ zend_std_get_constructor, /* get_constructor */ zend_std_object_get_class, /* get_class_entry */ zend_std_object_get_class_name, /* get_class_name */ zend_std_compare_objects, /* compare_objects */ zend_std_cast_object_tostring, /* cast_object */ NULL, /* count_elements */ NULL, /* get_debug_info */ zend_std_get_closure, /* get_closure */ }; /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */ /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "zend.h" #include "zend_globals.h" #include "zend_variables.h" #include "zend_API.h" #include "zend_objects.h" #include "zend_objects_API.h" #include "zend_object_handlers.h" #include "zend_interfaces.h" #include "zend_closures.h" #include "zend_compile.h" #define DEBUG_OBJECT_HANDLERS 0 #define Z_OBJ_P(zval_p) \ ((zend_object*)(EG(objects_store).object_buckets[Z_OBJ_HANDLE_P(zval_p)].bucket.obj.object)) /* __X accessors explanation: if we have __get and property that is not part of the properties array is requested, we call __get handler. If it fails, we return uninitialized. if we have __set and property that is not part of the properties array is set, we call __set handler. If it fails, we do not change the array. for both handlers above, when we are inside __get/__set, no further calls for __get/__set for this property of this object will be made, to prevent endless recursion and enable accessors to change properties array. if we have __call and method which is not part of the class function table is called, we cal __call handler. */ ZEND_API void rebuild_object_properties(zend_object *zobj) /* {{{ */ { if (!zobj->properties) { HashPosition pos; zend_property_info *prop_info; zend_class_entry *ce = zobj->ce; ALLOC_HASHTABLE(zobj->properties); zend_hash_init(zobj->properties, 0, NULL, ZVAL_PTR_DTOR, 0); if (ce->default_properties_count) { for (zend_hash_internal_pointer_reset_ex(&ce->properties_info, &pos); zend_hash_get_current_data_ex(&ce->properties_info, (void**)&prop_info, &pos) == SUCCESS; zend_hash_move_forward_ex(&ce->properties_info, &pos)) { if (/*prop_info->ce == ce &&*/ (prop_info->flags & ZEND_ACC_STATIC) == 0 && prop_info->offset >= 0 && zobj->properties_table[prop_info->offset]) { zend_hash_quick_add(zobj->properties, prop_info->name, prop_info->name_length+1, prop_info->h, (void**)&zobj->properties_table[prop_info->offset], sizeof(zval*), (void**)&zobj->properties_table[prop_info->offset]); } } while (ce->parent && ce->parent->default_properties_count) { ce = ce->parent; for (zend_hash_internal_pointer_reset_ex(&ce->properties_info, &pos); zend_hash_get_current_data_ex(&ce->properties_info, (void**)&prop_info, &pos) == SUCCESS; zend_hash_move_forward_ex(&ce->properties_info, &pos)) { if (prop_info->ce == ce && (prop_info->flags & ZEND_ACC_STATIC) == 0 && (prop_info->flags & ZEND_ACC_PRIVATE) != 0 && prop_info->offset >= 0 && zobj->properties_table[prop_info->offset]) { zend_hash_quick_add(zobj->properties, prop_info->name, prop_info->name_length+1, prop_info->h, (void**)&zobj->properties_table[prop_info->offset], sizeof(zval*), (void**)&zobj->properties_table[prop_info->offset]); } } } } } } ZEND_API HashTable *zend_std_get_properties(zval *object TSRMLS_DC) /* {{{ */ { zend_object *zobj; zobj = Z_OBJ_P(object); if (!zobj->properties) { rebuild_object_properties(zobj); } return zobj->properties; } /* }}} */ ZEND_API HashTable *zend_std_get_debug_info(zval *object, int *is_temp TSRMLS_DC) /* {{{ */ { *is_temp = 0; return zend_std_get_properties(object TSRMLS_CC); } /* }}} */ static zval *zend_std_call_getter(zval *object, zval *member TSRMLS_DC) /* {{{ */ { zval *retval = NULL; zend_class_entry *ce = Z_OBJCE_P(object); /* __get handler is called with one argument: property name it should return whether the call was successfull or not */ SEPARATE_ARG_IF_REF(member); zend_call_method_with_1_params(&object, ce, &ce->__get, ZEND_GET_FUNC_NAME, &retval, member); zval_ptr_dtor(&member); if (retval) { Z_DELREF_P(retval); } return retval; } /* }}} */ static int zend_std_call_setter(zval *object, zval *member, zval *value TSRMLS_DC) /* {{{ */ { zval *retval = NULL; int result; zend_class_entry *ce = Z_OBJCE_P(object); SEPARATE_ARG_IF_REF(member); Z_ADDREF_P(value); /* __set handler is called with two arguments: property name value to be set it should return whether the call was successfull or not */ zend_call_method_with_2_params(&object, ce, &ce->__set, ZEND_SET_FUNC_NAME, &retval, member, value); zval_ptr_dtor(&member); zval_ptr_dtor(&value); if (retval) { result = i_zend_is_true(retval) ? SUCCESS : FAILURE; zval_ptr_dtor(&retval); return result; } else { return FAILURE; } } /* }}} */ static void zend_std_call_unsetter(zval *object, zval *member TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = Z_OBJCE_P(object); /* __unset handler is called with one argument: property name */ SEPARATE_ARG_IF_REF(member); zend_call_method_with_1_params(&object, ce, &ce->__unset, ZEND_UNSET_FUNC_NAME, NULL, member); zval_ptr_dtor(&member); } /* }}} */ static zval *zend_std_call_issetter(zval *object, zval *member TSRMLS_DC) /* {{{ */ { zval *retval = NULL; zend_class_entry *ce = Z_OBJCE_P(object); /* __isset handler is called with one argument: property name it should return whether the property is set or not */ SEPARATE_ARG_IF_REF(member); zend_call_method_with_1_params(&object, ce, &ce->__isset, ZEND_ISSET_FUNC_NAME, &retval, member); zval_ptr_dtor(&member); return retval; } /* }}} */ static zend_always_inline int zend_verify_property_access(zend_property_info *property_info, zend_class_entry *ce TSRMLS_DC) /* {{{ */ { switch (property_info->flags & ZEND_ACC_PPP_MASK) { case ZEND_ACC_PUBLIC: return 1; case ZEND_ACC_PROTECTED: return zend_check_protected(property_info->ce, EG(scope)); case ZEND_ACC_PRIVATE: if ((ce==EG(scope) || property_info->ce == EG(scope)) && EG(scope)) { return 1; } else { return 0; } break; } return 0; } /* }}} */ static zend_always_inline zend_bool is_derived_class(zend_class_entry *child_class, zend_class_entry *parent_class) /* {{{ */ { child_class = child_class->parent; while (child_class) { if (child_class == parent_class) { return 1; } child_class = child_class->parent; } return 0; } /* }}} */ static zend_always_inline struct _zend_property_info *zend_get_property_info_quick(zend_class_entry *ce, zval *member, int silent, const zend_literal *key TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; zend_property_info *scope_property_info; zend_bool denied_access = 0; ulong h; if (key && (property_info = CACHED_POLYMORPHIC_PTR(key->cache_slot, ce)) != NULL) { return property_info; } if (UNEXPECTED(Z_STRVAL_P(member)[0] == '\0')) { if (!silent) { if (Z_STRLEN_P(member) == 0) { zend_error_noreturn(E_ERROR, "Cannot access empty property"); } else { zend_error_noreturn(E_ERROR, "Cannot access property started with '\\0'"); } } return NULL; } property_info = NULL; h = key ? key->hash_value : zend_get_hash_value(Z_STRVAL_P(member), Z_STRLEN_P(member) + 1); if (zend_hash_quick_find(&ce->properties_info, Z_STRVAL_P(member), Z_STRLEN_P(member)+1, h, (void **) &property_info)==SUCCESS) { if (UNEXPECTED((property_info->flags & ZEND_ACC_SHADOW) != 0)) { /* if it's a shadow - go to access it's private */ property_info = NULL; } else { if (EXPECTED(zend_verify_property_access(property_info, ce TSRMLS_CC) != 0)) { if (EXPECTED((property_info->flags & ZEND_ACC_CHANGED) != 0) && EXPECTED(!(property_info->flags & ZEND_ACC_PRIVATE))) { /* We still need to make sure that we're not in a context * where the right property is a different 'statically linked' private * continue checking below... */ } else { if (UNEXPECTED((property_info->flags & ZEND_ACC_STATIC) != 0) && !silent) { zend_error(E_STRICT, "Accessing static property %s::$%s as non static", ce->name, Z_STRVAL_P(member)); } if (key) { CACHE_POLYMORPHIC_PTR(key->cache_slot, ce, property_info); } return property_info; } } else { /* Try to look in the scope instead */ denied_access = 1; } } } if (EG(scope) != ce && EG(scope) && is_derived_class(ce, EG(scope)) && zend_hash_quick_find(&EG(scope)->properties_info, Z_STRVAL_P(member), Z_STRLEN_P(member)+1, h, (void **) &scope_property_info)==SUCCESS && scope_property_info->flags & ZEND_ACC_PRIVATE) { if (key) { CACHE_POLYMORPHIC_PTR(key->cache_slot, ce, scope_property_info); } return scope_property_info; } else if (property_info) { if (UNEXPECTED(denied_access != 0)) { /* Information was available, but we were denied access. Error out. */ if (!silent) { zend_error_noreturn(E_ERROR, "Cannot access %s property %s::$%s", zend_visibility_string(property_info->flags), ce->name, Z_STRVAL_P(member)); } return NULL; } else { /* fall through, return property_info... */ if (key) { CACHE_POLYMORPHIC_PTR(key->cache_slot, ce, property_info); } } } else { EG(std_property_info).flags = ZEND_ACC_PUBLIC; EG(std_property_info).name = Z_STRVAL_P(member); EG(std_property_info).name_length = Z_STRLEN_P(member); EG(std_property_info).h = h; EG(std_property_info).ce = ce; EG(std_property_info).offset = -1; property_info = &EG(std_property_info); } return property_info; } /* }}} */ ZEND_API struct _zend_property_info *zend_get_property_info(zend_class_entry *ce, zval *member, int silent TSRMLS_DC) /* {{{ */ { return zend_get_property_info_quick(ce, member, silent, NULL TSRMLS_CC); } /* }}} */ ZEND_API int zend_check_property_access(zend_object *zobj, char *prop_info_name, int prop_info_name_len TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; char *class_name, *prop_name; zval member; zend_unmangle_property_name(prop_info_name, prop_info_name_len, &class_name, &prop_name); ZVAL_STRING(&member, prop_name, 0); property_info = zend_get_property_info_quick(zobj->ce, &member, 1, NULL TSRMLS_CC); if (!property_info) { return FAILURE; } if (class_name && class_name[0] != '*') { if (!(property_info->flags & ZEND_ACC_PRIVATE)) { /* we we're looking for a private prop but found a non private one of the same name */ return FAILURE; } else if (strcmp(prop_info_name+1, property_info->name+1)) { /* we we're looking for a private prop but found a private one of the same name but another class */ return FAILURE; } } return zend_verify_property_access(property_info, zobj->ce TSRMLS_CC) ? SUCCESS : FAILURE; } /* }}} */ static int zend_get_property_guard(zend_object *zobj, zend_property_info *property_info, zval *member, zend_guard **pguard) /* {{{ */ { zend_property_info info; zend_guard stub; if (!property_info) { property_info = &info; info.name = Z_STRVAL_P(member); info.name_length = Z_STRLEN_P(member); info.h = zend_get_hash_value(Z_STRVAL_P(member), Z_STRLEN_P(member) + 1); } if (!zobj->guards) { ALLOC_HASHTABLE(zobj->guards); zend_hash_init(zobj->guards, 0, NULL, NULL, 0); } else if (zend_hash_quick_find(zobj->guards, property_info->name, property_info->name_length+1, property_info->h, (void **) pguard) == SUCCESS) { return SUCCESS; } stub.in_get = 0; stub.in_set = 0; stub.in_unset = 0; stub.in_isset = 0; return zend_hash_quick_add(zobj->guards, property_info->name, property_info->name_length+1, property_info->h, (void**)&stub, sizeof(stub), (void**) pguard); } /* }}} */ zval *zend_std_read_property(zval *object, zval *member, int type, const zend_literal *key TSRMLS_DC) /* {{{ */ { zend_object *zobj; zval *tmp_member = NULL; zval **retval; zval *rv = NULL; zend_property_info *property_info; int silent; silent = (type == BP_VAR_IS); zobj = Z_OBJ_P(object); if (UNEXPECTED(Z_TYPE_P(member) != IS_STRING)) { ALLOC_ZVAL(tmp_member); *tmp_member = *member; INIT_PZVAL(tmp_member); zval_copy_ctor(tmp_member); convert_to_string(tmp_member); member = tmp_member; key = NULL; } #if DEBUG_OBJECT_HANDLERS fprintf(stderr, "Read object #%d property: %s\n", Z_OBJ_HANDLE_P(object), Z_STRVAL_P(member)); #endif /* make zend_get_property_info silent if we have getter - we may want to use it */ property_info = zend_get_property_info_quick(zobj->ce, member, (zobj->ce->__get != NULL), key TSRMLS_CC); if (UNEXPECTED(!property_info) || ((EXPECTED((property_info->flags & ZEND_ACC_STATIC) == 0) && property_info->offset >= 0) ? (zobj->properties ? ((retval = (zval**)zobj->properties_table[property_info->offset]) == NULL) : (*(retval = &zobj->properties_table[property_info->offset]) == NULL)) : (UNEXPECTED(!zobj->properties) || UNEXPECTED(zend_hash_quick_find(zobj->properties, property_info->name, property_info->name_length+1, property_info->h, (void **) &retval) == FAILURE)))) { zend_guard *guard = NULL; if (zobj->ce->__get && zend_get_property_guard(zobj, property_info, member, &guard) == SUCCESS && !guard->in_get) { /* have getter - try with it! */ Z_ADDREF_P(object); if (PZVAL_IS_REF(object)) { SEPARATE_ZVAL(&object); } guard->in_get = 1; /* prevent circular getting */ rv = zend_std_call_getter(object, member TSRMLS_CC); guard->in_get = 0; if (rv) { retval = &rv; if (!Z_ISREF_P(rv) && (type == BP_VAR_W || type == BP_VAR_RW || type == BP_VAR_UNSET)) { if (Z_REFCOUNT_P(rv) > 0) { zval *tmp = rv; ALLOC_ZVAL(rv); *rv = *tmp; zval_copy_ctor(rv); Z_UNSET_ISREF_P(rv); Z_SET_REFCOUNT_P(rv, 0); } if (UNEXPECTED(Z_TYPE_P(rv) != IS_OBJECT)) { zend_error(E_NOTICE, "Indirect modification of overloaded property %s::$%s has no effect", zobj->ce->name, Z_STRVAL_P(member)); } } } else { retval = &EG(uninitialized_zval_ptr); } if (EXPECTED(*retval != object)) { zval_ptr_dtor(&object); } else { Z_DELREF_P(object); } } else { if (zobj->ce->__get && guard && guard->in_get == 1) { if (Z_STRVAL_P(member)[0] == '\0') { if (Z_STRLEN_P(member) == 0) { zend_error(E_ERROR, "Cannot access empty property"); } else { zend_error(E_ERROR, "Cannot access property started with '\\0'"); } } } if (!silent) { zend_error(E_NOTICE,"Undefined property: %s::$%s", zobj->ce->name, Z_STRVAL_P(member)); } retval = &EG(uninitialized_zval_ptr); } } if (UNEXPECTED(tmp_member != NULL)) { Z_ADDREF_PP(retval); zval_ptr_dtor(&tmp_member); Z_DELREF_PP(retval); } return *retval; } /* }}} */ ZEND_API void zend_std_write_property(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC) /* {{{ */ { zend_object *zobj; zval *tmp_member = NULL; zval **variable_ptr; zend_property_info *property_info; zobj = Z_OBJ_P(object); if (UNEXPECTED(Z_TYPE_P(member) != IS_STRING)) { ALLOC_ZVAL(tmp_member); *tmp_member = *member; INIT_PZVAL(tmp_member); zval_copy_ctor(tmp_member); convert_to_string(tmp_member); member = tmp_member; key = NULL; } property_info = zend_get_property_info_quick(zobj->ce, member, (zobj->ce->__set != NULL), key TSRMLS_CC); if (EXPECTED(property_info != NULL) && ((EXPECTED((property_info->flags & ZEND_ACC_STATIC) == 0) && property_info->offset >= 0) ? (zobj->properties ? ((variable_ptr = (zval**)zobj->properties_table[property_info->offset]) != NULL) : (*(variable_ptr = &zobj->properties_table[property_info->offset]) != NULL)) : (EXPECTED(zobj->properties != NULL) && EXPECTED(zend_hash_quick_find(zobj->properties, property_info->name, property_info->name_length+1, property_info->h, (void **) &variable_ptr) == SUCCESS)))) { /* if we already have this value there, we don't actually need to do anything */ if (EXPECTED(*variable_ptr != value)) { /* if we are assigning reference, we shouldn't move it, but instead assign variable to the same pointer */ if (PZVAL_IS_REF(*variable_ptr)) { zval garbage = **variable_ptr; /* old value should be destroyed */ /* To check: can't *variable_ptr be some system variable like error_zval here? */ Z_TYPE_PP(variable_ptr) = Z_TYPE_P(value); (*variable_ptr)->value = value->value; if (Z_REFCOUNT_P(value) > 0) { zval_copy_ctor(*variable_ptr); } zval_dtor(&garbage); } else { zval *garbage = *variable_ptr; /* if we assign referenced variable, we should separate it */ Z_ADDREF_P(value); if (PZVAL_IS_REF(value)) { SEPARATE_ZVAL(&value); } *variable_ptr = value; zval_ptr_dtor(&garbage); } } } else { zend_guard *guard = NULL; if (zobj->ce->__set && zend_get_property_guard(zobj, property_info, member, &guard) == SUCCESS && !guard->in_set) { Z_ADDREF_P(object); if (PZVAL_IS_REF(object)) { SEPARATE_ZVAL(&object); } guard->in_set = 1; /* prevent circular setting */ if (zend_std_call_setter(object, member, value TSRMLS_CC) != SUCCESS) { /* for now, just ignore it - __set should take care of warnings, etc. */ } guard->in_set = 0; zval_ptr_dtor(&object); } else if (EXPECTED(property_info != NULL)) { /* if we assign referenced variable, we should separate it */ Z_ADDREF_P(value); if (PZVAL_IS_REF(value)) { SEPARATE_ZVAL(&value); } if (EXPECTED((property_info->flags & ZEND_ACC_STATIC) == 0) && property_info->offset >= 0) { if (!zobj->properties) { zobj->properties_table[property_info->offset] = value; } else if (zobj->properties_table[property_info->offset]) { *(zval**)zobj->properties_table[property_info->offset] = value; } else { zend_hash_quick_update(zobj->properties, property_info->name, property_info->name_length+1, property_info->h, &value, sizeof(zval *), (void**)&zobj->properties_table[property_info->offset]); } } else { if (!zobj->properties) { rebuild_object_properties(zobj); } zend_hash_quick_update(zobj->properties, property_info->name, property_info->name_length+1, property_info->h, &value, sizeof(zval *), NULL); } } else if (zobj->ce->__set && guard && guard->in_set == 1) { if (Z_STRVAL_P(member)[0] == '\0') { if (Z_STRLEN_P(member) == 0) { zend_error(E_ERROR, "Cannot access empty property"); } else { zend_error(E_ERROR, "Cannot access property started with '\\0'"); } } } } if (UNEXPECTED(tmp_member != NULL)) { zval_ptr_dtor(&tmp_member); } } /* }}} */ zval *zend_std_read_dimension(zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = Z_OBJCE_P(object); zval *retval; if (EXPECTED(instanceof_function_ex(ce, zend_ce_arrayaccess, 1 TSRMLS_CC) != 0)) { if(offset == NULL) { /* [] construct */ ALLOC_INIT_ZVAL(offset); } else { SEPARATE_ARG_IF_REF(offset); } zend_call_method_with_1_params(&object, ce, NULL, "offsetget", &retval, offset); zval_ptr_dtor(&offset); if (UNEXPECTED(!retval)) { if (UNEXPECTED(!EG(exception))) { zend_error_noreturn(E_ERROR, "Undefined offset for object of type %s used as array", ce->name); } return 0; } /* Undo PZVAL_LOCK() */ Z_DELREF_P(retval); return retval; } else { zend_error_noreturn(E_ERROR, "Cannot use object of type %s as array", ce->name); return 0; } } /* }}} */ static void zend_std_write_dimension(zval *object, zval *offset, zval *value TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = Z_OBJCE_P(object); if (EXPECTED(instanceof_function_ex(ce, zend_ce_arrayaccess, 1 TSRMLS_CC) != 0)) { if (!offset) { ALLOC_INIT_ZVAL(offset); } else { SEPARATE_ARG_IF_REF(offset); } zend_call_method_with_2_params(&object, ce, NULL, "offsetset", NULL, offset, value); zval_ptr_dtor(&offset); } else { zend_error_noreturn(E_ERROR, "Cannot use object of type %s as array", ce->name); } } /* }}} */ static int zend_std_has_dimension(zval *object, zval *offset, int check_empty TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = Z_OBJCE_P(object); zval *retval; int result; if (EXPECTED(instanceof_function_ex(ce, zend_ce_arrayaccess, 1 TSRMLS_CC) != 0)) { SEPARATE_ARG_IF_REF(offset); zend_call_method_with_1_params(&object, ce, NULL, "offsetexists", &retval, offset); if (EXPECTED(retval != NULL)) { result = i_zend_is_true(retval); zval_ptr_dtor(&retval); if (check_empty && result && EXPECTED(!EG(exception))) { zend_call_method_with_1_params(&object, ce, NULL, "offsetget", &retval, offset); if (retval) { result = i_zend_is_true(retval); zval_ptr_dtor(&retval); } } } else { result = 0; } zval_ptr_dtor(&offset); } else { zend_error_noreturn(E_ERROR, "Cannot use object of type %s as array", ce->name); return 0; } return result; } /* }}} */ static zval **zend_std_get_property_ptr_ptr(zval *object, zval *member, const zend_literal *key TSRMLS_DC) /* {{{ */ { zend_object *zobj; zval tmp_member; zval **retval; zend_property_info *property_info; zobj = Z_OBJ_P(object); if (UNEXPECTED(Z_TYPE_P(member) != IS_STRING)) { tmp_member = *member; zval_copy_ctor(&tmp_member); convert_to_string(&tmp_member); member = &tmp_member; key = NULL; } #if DEBUG_OBJECT_HANDLERS fprintf(stderr, "Ptr object #%d property: %s\n", Z_OBJ_HANDLE_P(object), Z_STRVAL_P(member)); #endif property_info = zend_get_property_info_quick(zobj->ce, member, (zobj->ce->__get != NULL), key TSRMLS_CC); if (UNEXPECTED(!property_info) || ((EXPECTED((property_info->flags & ZEND_ACC_STATIC) == 0) && property_info->offset >= 0) ? (zobj->properties ? ((retval = (zval**)zobj->properties_table[property_info->offset]) == NULL) : (*(retval = &zobj->properties_table[property_info->offset]) == NULL)) : (UNEXPECTED(!zobj->properties) || UNEXPECTED(zend_hash_quick_find(zobj->properties, property_info->name, property_info->name_length+1, property_info->h, (void **) &retval) == FAILURE)))) { zval *new_zval; zend_guard *guard; if (!zobj->ce->__get || zend_get_property_guard(zobj, property_info, member, &guard) != SUCCESS || (property_info && guard->in_get)) { /* we don't have access controls - will just add it */ new_zval = &EG(uninitialized_zval); /* zend_error(E_NOTICE, "Undefined property: %s", Z_STRVAL_P(member)); */ Z_ADDREF_P(new_zval); if (EXPECTED((property_info->flags & ZEND_ACC_STATIC) == 0) && property_info->offset >= 0) { if (!zobj->properties) { zobj->properties_table[property_info->offset] = new_zval; retval = &zobj->properties_table[property_info->offset]; } else if (zobj->properties_table[property_info->offset]) { *(zval**)zobj->properties_table[property_info->offset] = new_zval; retval = (zval**)zobj->properties_table[property_info->offset]; } else { zend_hash_quick_update(zobj->properties, property_info->name, property_info->name_length+1, property_info->h, &new_zval, sizeof(zval *), (void**)&zobj->properties_table[property_info->offset]); retval = (zval**)zobj->properties_table[property_info->offset]; } } else { if (!zobj->properties) { rebuild_object_properties(zobj); } zend_hash_quick_update(zobj->properties, property_info->name, property_info->name_length+1, property_info->h, &new_zval, sizeof(zval *), (void **) &retval); } } else { /* we do have getter - fail and let it try again with usual get/set */ retval = NULL; } } if (UNEXPECTED(member == &tmp_member)) { zval_dtor(member); } return retval; } /* }}} */ static void zend_std_unset_property(zval *object, zval *member, const zend_literal *key TSRMLS_DC) /* {{{ */ { zend_object *zobj; zval *tmp_member = NULL; zend_property_info *property_info; zobj = Z_OBJ_P(object); if (UNEXPECTED(Z_TYPE_P(member) != IS_STRING)) { ALLOC_ZVAL(tmp_member); *tmp_member = *member; INIT_PZVAL(tmp_member); zval_copy_ctor(tmp_member); convert_to_string(tmp_member); member = tmp_member; key = NULL; } property_info = zend_get_property_info_quick(zobj->ce, member, (zobj->ce->__unset != NULL), key TSRMLS_CC); if (EXPECTED(property_info != NULL) && EXPECTED((property_info->flags & ZEND_ACC_STATIC) == 0) && !zobj->properties && property_info->offset >= 0 && EXPECTED(zobj->properties_table[property_info->offset] != NULL)) { zval_ptr_dtor(&zobj->properties_table[property_info->offset]); zobj->properties_table[property_info->offset] = NULL; } else if (UNEXPECTED(!property_info) || !zobj->properties || UNEXPECTED(zend_hash_quick_del(zobj->properties, property_info->name, property_info->name_length+1, property_info->h) == FAILURE)) { zend_guard *guard = NULL; if (zobj->ce->__unset && zend_get_property_guard(zobj, property_info, member, &guard) == SUCCESS && !guard->in_unset) { /* have unseter - try with it! */ Z_ADDREF_P(object); if (PZVAL_IS_REF(object)) { SEPARATE_ZVAL(&object); } guard->in_unset = 1; /* prevent circular unsetting */ zend_std_call_unsetter(object, member TSRMLS_CC); guard->in_unset = 0; zval_ptr_dtor(&object); } else if (zobj->ce->__unset && guard && guard->in_unset == 1) { if (Z_STRVAL_P(member)[0] == '\0') { if (Z_STRLEN_P(member) == 0) { zend_error(E_ERROR, "Cannot access empty property"); } else { zend_error(E_ERROR, "Cannot access property started with '\\0'"); } } } } else if (EXPECTED(property_info != NULL) && EXPECTED((property_info->flags & ZEND_ACC_STATIC) == 0) && property_info->offset >= 0) { zobj->properties_table[property_info->offset] = NULL; } if (UNEXPECTED(tmp_member != NULL)) { zval_ptr_dtor(&tmp_member); } } /* }}} */ static void zend_std_unset_dimension(zval *object, zval *offset TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = Z_OBJCE_P(object); if (instanceof_function_ex(ce, zend_ce_arrayaccess, 1 TSRMLS_CC)) { SEPARATE_ARG_IF_REF(offset); zend_call_method_with_1_params(&object, ce, NULL, "offsetunset", NULL, offset); zval_ptr_dtor(&offset); } else { zend_error_noreturn(E_ERROR, "Cannot use object of type %s as array", ce->name); } } /* }}} */ ZEND_API void zend_std_call_user_call(INTERNAL_FUNCTION_PARAMETERS) /* {{{ */ { zend_internal_function *func = (zend_internal_function *)EG(current_execute_data)->function_state.function; zval *method_name_ptr, *method_args_ptr; zval *method_result_ptr = NULL; zend_class_entry *ce = Z_OBJCE_P(this_ptr); ALLOC_ZVAL(method_args_ptr); INIT_PZVAL(method_args_ptr); array_init_size(method_args_ptr, ZEND_NUM_ARGS()); if (UNEXPECTED(zend_copy_parameters_array(ZEND_NUM_ARGS(), method_args_ptr TSRMLS_CC) == FAILURE)) { zval_dtor(method_args_ptr); zend_error_noreturn(E_ERROR, "Cannot get arguments for __call"); RETURN_FALSE; } ALLOC_ZVAL(method_name_ptr); INIT_PZVAL(method_name_ptr); ZVAL_STRING(method_name_ptr, func->function_name, 0); /* no dup - it's a copy */ /* __call handler is called with two arguments: method name array of method parameters */ zend_call_method_with_2_params(&this_ptr, ce, &ce->__call, ZEND_CALL_FUNC_NAME, &method_result_ptr, method_name_ptr, method_args_ptr); if (method_result_ptr) { if (Z_ISREF_P(method_result_ptr) || Z_REFCOUNT_P(method_result_ptr) > 1) { RETVAL_ZVAL(method_result_ptr, 1, 1); } else { RETVAL_ZVAL(method_result_ptr, 0, 1); } } /* now destruct all auxiliaries */ zval_ptr_dtor(&method_args_ptr); zval_ptr_dtor(&method_name_ptr); /* destruct the function also, then - we have allocated it in get_method */ efree(func); } /* }}} */ /* Ensures that we're allowed to call a private method. * Returns the function address that should be called, or NULL * if no such function exists. */ static inline zend_function *zend_check_private_int(zend_function *fbc, zend_class_entry *ce, char *function_name_strval, int function_name_strlen, ulong hash_value TSRMLS_DC) /* {{{ */ { if (!ce) { return 0; } /* We may call a private function if: * 1. The class of our object is the same as the scope, and the private * function (EX(fbc)) has the same scope. * 2. One of our parent classes are the same as the scope, and it contains * a private function with the same name that has the same scope. */ if (fbc->common.scope == ce && EG(scope) == ce) { /* rule #1 checks out ok, allow the function call */ return fbc; } /* Check rule #2 */ ce = ce->parent; while (ce) { if (ce == EG(scope)) { if (zend_hash_quick_find(&ce->function_table, function_name_strval, function_name_strlen+1, hash_value, (void **) &fbc)==SUCCESS && fbc->op_array.fn_flags & ZEND_ACC_PRIVATE && fbc->common.scope == EG(scope)) { return fbc; } break; } ce = ce->parent; } return NULL; } /* }}} */ ZEND_API int zend_check_private(zend_function *fbc, zend_class_entry *ce, char *function_name_strval, int function_name_strlen TSRMLS_DC) /* {{{ */ { return zend_check_private_int(fbc, ce, function_name_strval, function_name_strlen, zend_hash_func(function_name_strval, function_name_strlen+1) TSRMLS_CC) != NULL; } /* }}} */ /* Ensures that we're allowed to call a protected method. */ ZEND_API int zend_check_protected(zend_class_entry *ce, zend_class_entry *scope) /* {{{ */ { zend_class_entry *fbc_scope = ce; /* Is the context that's calling the function, the same as one of * the function's parents? */ while (fbc_scope) { if (fbc_scope==scope) { return 1; } fbc_scope = fbc_scope->parent; } /* Is the function's scope the same as our current object context, * or any of the parents of our context? */ while (scope) { if (scope==ce) { return 1; } scope = scope->parent; } return 0; } /* }}} */ static inline zend_class_entry * zend_get_function_root_class(zend_function *fbc) /* {{{ */ { return fbc->common.prototype ? fbc->common.prototype->common.scope : fbc->common.scope; } /* }}} */ static inline union _zend_function *zend_get_user_call_function(zend_class_entry *ce, const char *method_name, int method_len) /* {{{ */ { zend_internal_function *call_user_call = emalloc(sizeof(zend_internal_function)); call_user_call->type = ZEND_INTERNAL_FUNCTION; call_user_call->module = (ce->type == ZEND_INTERNAL_CLASS) ? ce->info.internal.module : NULL; call_user_call->handler = zend_std_call_user_call; call_user_call->arg_info = NULL; call_user_call->num_args = 0; call_user_call->scope = ce; call_user_call->fn_flags = ZEND_ACC_CALL_VIA_HANDLER; call_user_call->function_name = estrndup(method_name, method_len); return (union _zend_function *)call_user_call; } /* }}} */ static union _zend_function *zend_std_get_method(zval **object_ptr, char *method_name, int method_len, const zend_literal *key TSRMLS_DC) /* {{{ */ { zend_function *fbc; zval *object = *object_ptr; zend_object *zobj = Z_OBJ_P(object); ulong hash_value; char *lc_method_name; ALLOCA_FLAG(use_heap) if (EXPECTED(key != NULL)) { lc_method_name = Z_STRVAL(key->constant); hash_value = key->hash_value; } else { lc_method_name = do_alloca(method_len+1, use_heap); /* Create a zend_copy_str_tolower(dest, src, src_length); */ zend_str_tolower_copy(lc_method_name, method_name, method_len); hash_value = zend_hash_func(lc_method_name, method_len+1); } if (UNEXPECTED(zend_hash_quick_find(&zobj->ce->function_table, lc_method_name, method_len+1, hash_value, (void **)&fbc) == FAILURE)) { if (UNEXPECTED(!key)) { free_alloca(lc_method_name, use_heap); } if (zobj->ce->__call) { return zend_get_user_call_function(zobj->ce, method_name, method_len); } else { return NULL; } } /* Check access level */ if (fbc->op_array.fn_flags & ZEND_ACC_PRIVATE) { zend_function *updated_fbc; /* Ensure that if we're calling a private function, we're allowed to do so. * If we're not and __call() handler exists, invoke it, otherwise error out. */ updated_fbc = zend_check_private_int(fbc, Z_OBJ_HANDLER_P(object, get_class_entry)(object TSRMLS_CC), lc_method_name, method_len, hash_value TSRMLS_CC); if (EXPECTED(updated_fbc != NULL)) { fbc = updated_fbc; } else { if (zobj->ce->__call) { fbc = zend_get_user_call_function(zobj->ce, method_name, method_len); } else { zend_error_noreturn(E_ERROR, "Call to %s method %s::%s() from context '%s'", zend_visibility_string(fbc->common.fn_flags), ZEND_FN_SCOPE_NAME(fbc), method_name, EG(scope) ? EG(scope)->name : ""); } } } else { /* Ensure that we haven't overridden a private function and end up calling * the overriding public function... */ if (EG(scope) && is_derived_class(fbc->common.scope, EG(scope)) && fbc->op_array.fn_flags & ZEND_ACC_CHANGED) { zend_function *priv_fbc; if (zend_hash_quick_find(&EG(scope)->function_table, lc_method_name, method_len+1, hash_value, (void **) &priv_fbc)==SUCCESS && priv_fbc->common.fn_flags & ZEND_ACC_PRIVATE && priv_fbc->common.scope == EG(scope)) { fbc = priv_fbc; } } if ((fbc->common.fn_flags & ZEND_ACC_PROTECTED)) { /* Ensure that if we're calling a protected function, we're allowed to do so. * If we're not and __call() handler exists, invoke it, otherwise error out. */ if (UNEXPECTED(!zend_check_protected(zend_get_function_root_class(fbc), EG(scope)))) { if (zobj->ce->__call) { fbc = zend_get_user_call_function(zobj->ce, method_name, method_len); } else { zend_error_noreturn(E_ERROR, "Call to %s method %s::%s() from context '%s'", zend_visibility_string(fbc->common.fn_flags), ZEND_FN_SCOPE_NAME(fbc), method_name, EG(scope) ? EG(scope)->name : ""); } } } } if (UNEXPECTED(!key)) { free_alloca(lc_method_name, use_heap); } return fbc; } /* }}} */ ZEND_API void zend_std_callstatic_user_call(INTERNAL_FUNCTION_PARAMETERS) /* {{{ */ { zend_internal_function *func = (zend_internal_function *)EG(current_execute_data)->function_state.function; zval *method_name_ptr, *method_args_ptr; zval *method_result_ptr = NULL; zend_class_entry *ce = EG(scope); ALLOC_ZVAL(method_args_ptr); INIT_PZVAL(method_args_ptr); array_init_size(method_args_ptr, ZEND_NUM_ARGS()); if (UNEXPECTED(zend_copy_parameters_array(ZEND_NUM_ARGS(), method_args_ptr TSRMLS_CC) == FAILURE)) { zval_dtor(method_args_ptr); zend_error_noreturn(E_ERROR, "Cannot get arguments for " ZEND_CALLSTATIC_FUNC_NAME); RETURN_FALSE; } ALLOC_ZVAL(method_name_ptr); INIT_PZVAL(method_name_ptr); ZVAL_STRING(method_name_ptr, func->function_name, 0); /* no dup - it's a copy */ /* __callStatic handler is called with two arguments: method name array of method parameters */ zend_call_method_with_2_params(NULL, ce, &ce->__callstatic, ZEND_CALLSTATIC_FUNC_NAME, &method_result_ptr, method_name_ptr, method_args_ptr); if (method_result_ptr) { if (Z_ISREF_P(method_result_ptr) || Z_REFCOUNT_P(method_result_ptr) > 1) { RETVAL_ZVAL(method_result_ptr, 1, 1); } else { RETVAL_ZVAL(method_result_ptr, 0, 1); } } /* now destruct all auxiliaries */ zval_ptr_dtor(&method_args_ptr); zval_ptr_dtor(&method_name_ptr); /* destruct the function also, then - we have allocated it in get_method */ efree(func); } /* }}} */ static inline union _zend_function *zend_get_user_callstatic_function(zend_class_entry *ce, const char *method_name, int method_len) /* {{{ */ { zend_internal_function *callstatic_user_call = emalloc(sizeof(zend_internal_function)); callstatic_user_call->type = ZEND_INTERNAL_FUNCTION; callstatic_user_call->module = (ce->type == ZEND_INTERNAL_CLASS) ? ce->info.internal.module : NULL; callstatic_user_call->handler = zend_std_callstatic_user_call; callstatic_user_call->arg_info = NULL; callstatic_user_call->num_args = 0; callstatic_user_call->scope = ce; callstatic_user_call->fn_flags = ZEND_ACC_STATIC | ZEND_ACC_PUBLIC | ZEND_ACC_CALL_VIA_HANDLER; callstatic_user_call->function_name = estrndup(method_name, method_len); return (zend_function *)callstatic_user_call; } /* }}} */ /* This is not (yet?) in the API, but it belongs in the built-in objects callbacks */ ZEND_API zend_function *zend_std_get_static_method(zend_class_entry *ce, char *function_name_strval, int function_name_strlen, const zend_literal *key TSRMLS_DC) /* {{{ */ { zend_function *fbc = NULL; char *lc_class_name, *lc_function_name = NULL; ulong hash_value; ALLOCA_FLAG(use_heap) if (EXPECTED(key != NULL)) { lc_function_name = Z_STRVAL(key->constant); hash_value = key->hash_value; } else { lc_function_name = do_alloca(function_name_strlen+1, use_heap); /* Create a zend_copy_str_tolower(dest, src, src_length); */ zend_str_tolower_copy(lc_function_name, function_name_strval, function_name_strlen); hash_value = zend_hash_func(lc_function_name, function_name_strlen+1); } if (function_name_strlen == ce->name_length && ce->constructor) { lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); /* Only change the method to the constructor if the constructor isn't called __construct * we check for __ so we can be binary safe for lowering, we should use ZEND_CONSTRUCTOR_FUNC_NAME */ if (!memcmp(lc_class_name, lc_function_name, function_name_strlen) && memcmp(ce->constructor->common.function_name, "__", sizeof("__") - 1)) { fbc = ce->constructor; } efree(lc_class_name); } if (EXPECTED(!fbc) && UNEXPECTED(zend_hash_quick_find(&ce->function_table, lc_function_name, function_name_strlen+1, hash_value, (void **) &fbc)==FAILURE)) { if (UNEXPECTED(!key)) { free_alloca(lc_function_name, use_heap); } if (ce->__call && EG(This) && Z_OBJ_HT_P(EG(This))->get_class_entry && instanceof_function(Z_OBJCE_P(EG(This)), ce TSRMLS_CC)) { return zend_get_user_call_function(ce, function_name_strval, function_name_strlen); } else if (ce->__callstatic) { return zend_get_user_callstatic_function(ce, function_name_strval, function_name_strlen); } else { return NULL; } } #if MBO_0 /* right now this function is used for non static method lookup too */ /* Is the function static */ if (UNEXPECTED(!(fbc->common.fn_flags & ZEND_ACC_STATIC))) { zend_error_noreturn(E_ERROR, "Cannot call non static method %s::%s() without object", ZEND_FN_SCOPE_NAME(fbc), fbc->common.function_name); } #endif if (fbc->op_array.fn_flags & ZEND_ACC_PUBLIC) { /* No further checks necessary, most common case */ } else if (fbc->op_array.fn_flags & ZEND_ACC_PRIVATE) { zend_function *updated_fbc; /* Ensure that if we're calling a private function, we're allowed to do so. */ updated_fbc = zend_check_private_int(fbc, EG(scope), lc_function_name, function_name_strlen, hash_value TSRMLS_CC); if (EXPECTED(updated_fbc != NULL)) { fbc = updated_fbc; } else { if (ce->__callstatic) { fbc = zend_get_user_callstatic_function(ce, function_name_strval, function_name_strlen); } else { zend_error_noreturn(E_ERROR, "Call to %s method %s::%s() from context '%s'", zend_visibility_string(fbc->common.fn_flags), ZEND_FN_SCOPE_NAME(fbc), function_name_strval, EG(scope) ? EG(scope)->name : ""); } } } else if ((fbc->common.fn_flags & ZEND_ACC_PROTECTED)) { /* Ensure that if we're calling a protected function, we're allowed to do so. */ if (UNEXPECTED(!zend_check_protected(zend_get_function_root_class(fbc), EG(scope)))) { if (ce->__callstatic) { fbc = zend_get_user_callstatic_function(ce, function_name_strval, function_name_strlen); } else { zend_error_noreturn(E_ERROR, "Call to %s method %s::%s() from context '%s'", zend_visibility_string(fbc->common.fn_flags), ZEND_FN_SCOPE_NAME(fbc), function_name_strval, EG(scope) ? EG(scope)->name : ""); } } } if (UNEXPECTED(!key)) { free_alloca(lc_function_name, use_heap); } return fbc; } /* }}} */ ZEND_API zval **zend_std_get_static_property(zend_class_entry *ce, char *property_name, int property_name_len, zend_bool silent, const zend_literal *key TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; ulong hash_value; if (UNEXPECTED(!key) || (property_info = CACHED_POLYMORPHIC_PTR(key->cache_slot, ce)) == NULL) { if (EXPECTED(key != NULL)) { hash_value = key->hash_value; } else { hash_value = zend_hash_func(property_name, property_name_len+1); } if (UNEXPECTED(zend_hash_quick_find(&ce->properties_info, property_name, property_name_len+1, hash_value, (void **) &property_info)==FAILURE)) { if (!silent) { zend_error_noreturn(E_ERROR, "Access to undeclared static property: %s::$%s", ce->name, property_name); } return NULL; } #if DEBUG_OBJECT_HANDLERS zend_printf("Access type for %s::%s is %s\n", ce->name, property_name, zend_visibility_string(property_info->flags)); #endif if (UNEXPECTED(!zend_verify_property_access(property_info, ce TSRMLS_CC))) { if (!silent) { zend_error_noreturn(E_ERROR, "Cannot access %s property %s::$%s", zend_visibility_string(property_info->flags), ce->name, property_name); } return NULL; } if (UNEXPECTED((property_info->flags & ZEND_ACC_STATIC) == 0)) { if (!silent) { zend_error_noreturn(E_ERROR, "Access to undeclared static property: %s::$%s", ce->name, property_name); } return NULL; } zend_update_class_constants(ce TSRMLS_CC); if (EXPECTED(key != NULL)) { CACHE_POLYMORPHIC_PTR(key->cache_slot, ce, property_info); } } return &CE_STATIC_MEMBERS(ce)[property_info->offset]; } /* }}} */ ZEND_API zend_bool zend_std_unset_static_property(zend_class_entry *ce, char *property_name, int property_name_len, const zend_literal *key TSRMLS_DC) /* {{{ */ { zend_error_noreturn(E_ERROR, "Attempt to unset static property %s::$%s", ce->name, property_name); return 0; } /* }}} */ ZEND_API union _zend_function *zend_std_get_constructor(zval *object TSRMLS_DC) /* {{{ */ { zend_object *zobj = Z_OBJ_P(object); zend_function *constructor = zobj->ce->constructor; if (constructor) { if (constructor->op_array.fn_flags & ZEND_ACC_PUBLIC) { /* No further checks necessary */ } else if (constructor->op_array.fn_flags & ZEND_ACC_PRIVATE) { /* Ensure that if we're calling a private function, we're allowed to do so. */ if (UNEXPECTED(constructor->common.scope != EG(scope))) { if (EG(scope)) { zend_error_noreturn(E_ERROR, "Call to private %s::%s() from context '%s'", constructor->common.scope->name, constructor->common.function_name, EG(scope)->name); } else { zend_error_noreturn(E_ERROR, "Call to private %s::%s() from invalid context", constructor->common.scope->name, constructor->common.function_name); } } } else if ((constructor->common.fn_flags & ZEND_ACC_PROTECTED)) { /* Ensure that if we're calling a protected function, we're allowed to do so. * Constructors only have prototype if they are defined by an interface but * it is the compilers responsibility to take care of the prototype. */ if (UNEXPECTED(!zend_check_protected(zend_get_function_root_class(constructor), EG(scope)))) { if (EG(scope)) { zend_error_noreturn(E_ERROR, "Call to protected %s::%s() from context '%s'", constructor->common.scope->name, constructor->common.function_name, EG(scope)->name); } else { zend_error_noreturn(E_ERROR, "Call to protected %s::%s() from invalid context", constructor->common.scope->name, constructor->common.function_name); } } } } return constructor; } /* }}} */ int zend_compare_symbol_tables_i(HashTable *ht1, HashTable *ht2 TSRMLS_DC); static int zend_std_compare_objects(zval *o1, zval *o2 TSRMLS_DC) /* {{{ */ { zend_object *zobj1, *zobj2; zobj1 = Z_OBJ_P(o1); zobj2 = Z_OBJ_P(o2); if (zobj1->ce != zobj2->ce) { return 1; /* different classes */ } if (!zobj1->properties && !zobj2->properties) { int i; for (i = 0; i < zobj1->ce->default_properties_count; i++) { if (zobj1->properties_table[i]) { if (zobj2->properties_table[i]) { zval result; if (compare_function(&result, zobj1->properties_table[i], zobj2->properties_table[i] TSRMLS_CC)==FAILURE) { return 1; } if (Z_LVAL(result) != 0) { return Z_LVAL(result); } } else { return 1; } } else { if (zobj2->properties_table[i]) { return 1; } else { return 0; } } } return 0; } else { if (!zobj1->properties) { rebuild_object_properties(zobj1); } if (!zobj2->properties) { rebuild_object_properties(zobj2); } return zend_compare_symbol_tables_i(zobj1->properties, zobj2->properties TSRMLS_CC); } } /* }}} */ static int zend_std_has_property(zval *object, zval *member, int has_set_exists, const zend_literal *key TSRMLS_DC) /* {{{ */ { zend_object *zobj; int result; zval **value = NULL; zval *tmp_member = NULL; zend_property_info *property_info; zobj = Z_OBJ_P(object); if (UNEXPECTED(Z_TYPE_P(member) != IS_STRING)) { ALLOC_ZVAL(tmp_member); *tmp_member = *member; INIT_PZVAL(tmp_member); zval_copy_ctor(tmp_member); convert_to_string(tmp_member); member = tmp_member; key = NULL; } #if DEBUG_OBJECT_HANDLERS fprintf(stderr, "Read object #%d property: %s\n", Z_OBJ_HANDLE_P(object), Z_STRVAL_P(member)); #endif property_info = zend_get_property_info_quick(zobj->ce, member, 1, key TSRMLS_CC); if (UNEXPECTED(!property_info) || ((EXPECTED((property_info->flags & ZEND_ACC_STATIC) == 0) && property_info->offset >= 0) ? (zobj->properties ? ((value = (zval**)zobj->properties_table[property_info->offset]) == NULL) : (*(value = &zobj->properties_table[property_info->offset]) == NULL)) : (UNEXPECTED(!zobj->properties) || UNEXPECTED(zend_hash_quick_find(zobj->properties, property_info->name, property_info->name_length+1, property_info->h, (void **) &value) == FAILURE)))) { zend_guard *guard; result = 0; if ((has_set_exists != 2) && zobj->ce->__isset && zend_get_property_guard(zobj, property_info, member, &guard) == SUCCESS && !guard->in_isset) { zval *rv; /* have issetter - try with it! */ Z_ADDREF_P(object); if (PZVAL_IS_REF(object)) { SEPARATE_ZVAL(&object); } guard->in_isset = 1; /* prevent circular getting */ rv = zend_std_call_issetter(object, member TSRMLS_CC); if (rv) { result = zend_is_true(rv); zval_ptr_dtor(&rv); if (has_set_exists && result) { if (EXPECTED(!EG(exception)) && zobj->ce->__get && !guard->in_get) { guard->in_get = 1; rv = zend_std_call_getter(object, member TSRMLS_CC); guard->in_get = 0; if (rv) { Z_ADDREF_P(rv); result = i_zend_is_true(rv); zval_ptr_dtor(&rv); } else { result = 0; } } else { result = 0; } } } guard->in_isset = 0; zval_ptr_dtor(&object); } } else { switch (has_set_exists) { case 0: result = (Z_TYPE_PP(value) != IS_NULL); break; default: result = zend_is_true(*value); break; case 2: result = 1; break; } } if (UNEXPECTED(tmp_member != NULL)) { zval_ptr_dtor(&tmp_member); } return result; } /* }}} */ zend_class_entry *zend_std_object_get_class(const zval *object TSRMLS_DC) /* {{{ */ { zend_object *zobj; zobj = Z_OBJ_P(object); return zobj->ce; } /* }}} */ int zend_std_object_get_class_name(const zval *object, char **class_name, zend_uint *class_name_len, int parent TSRMLS_DC) /* {{{ */ { zend_object *zobj; zend_class_entry *ce; zobj = Z_OBJ_P(object); if (parent) { if (!zobj->ce->parent) { return FAILURE; } ce = zobj->ce->parent; } else { ce = zobj->ce; } *class_name_len = ce->name_length; *class_name = estrndup(ce->name, ce->name_length); return SUCCESS; } /* }}} */ ZEND_API int zend_std_cast_object_tostring(zval *readobj, zval *writeobj, int type TSRMLS_DC) /* {{{ */ { zval *retval; zend_class_entry *ce; switch (type) { case IS_STRING: ce = Z_OBJCE_P(readobj); if (ce->__tostring && (zend_call_method_with_0_params(&readobj, ce, &ce->__tostring, "__tostring", &retval) || EG(exception))) { if (UNEXPECTED(EG(exception) != NULL)) { if (retval) { zval_ptr_dtor(&retval); } zend_error_noreturn(E_ERROR, "Method %s::__toString() must not throw an exception", ce->name); return FAILURE; } if (EXPECTED(Z_TYPE_P(retval) == IS_STRING)) { INIT_PZVAL(writeobj); if (readobj == writeobj) { zval_dtor(readobj); } ZVAL_ZVAL(writeobj, retval, 1, 1); if (Z_TYPE_P(writeobj) != type) { convert_to_explicit_type(writeobj, type); } return SUCCESS; } else { zval_ptr_dtor(&retval); INIT_PZVAL(writeobj); if (readobj == writeobj) { zval_dtor(readobj); } ZVAL_EMPTY_STRING(writeobj); zend_error(E_RECOVERABLE_ERROR, "Method %s::__toString() must return a string value", ce->name); return SUCCESS; } } return FAILURE; case IS_BOOL: INIT_PZVAL(writeobj); ZVAL_BOOL(writeobj, 1); return SUCCESS; case IS_LONG: ce = Z_OBJCE_P(readobj); zend_error(E_NOTICE, "Object of class %s could not be converted to int", ce->name); INIT_PZVAL(writeobj); if (readobj == writeobj) { zval_dtor(readobj); } ZVAL_LONG(writeobj, 1); return SUCCESS; case IS_DOUBLE: ce = Z_OBJCE_P(readobj); zend_error(E_NOTICE, "Object of class %s could not be converted to double", ce->name); INIT_PZVAL(writeobj); if (readobj == writeobj) { zval_dtor(readobj); } ZVAL_DOUBLE(writeobj, 1); return SUCCESS; default: INIT_PZVAL(writeobj); Z_TYPE_P(writeobj) = IS_NULL; break; } return FAILURE; } /* }}} */ int zend_std_get_closure(zval *obj, zend_class_entry **ce_ptr, zend_function **fptr_ptr, zval **zobj_ptr TSRMLS_DC) /* {{{ */ { zend_class_entry *ce; if (Z_TYPE_P(obj) != IS_OBJECT) { return FAILURE; } ce = Z_OBJCE_P(obj); if (zend_hash_find(&ce->function_table, ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME), (void**)fptr_ptr) == FAILURE) { return FAILURE; } *ce_ptr = ce; if ((*fptr_ptr)->common.fn_flags & ZEND_ACC_STATIC) { if (zobj_ptr) { *zobj_ptr = NULL; } } else { if (zobj_ptr) { *zobj_ptr = obj; } } return SUCCESS; } /* }}} */ ZEND_API zend_object_handlers std_object_handlers = { zend_objects_store_add_ref, /* add_ref */ zend_objects_store_del_ref, /* del_ref */ zend_objects_clone_obj, /* clone_obj */ zend_std_read_property, /* read_property */ zend_std_write_property, /* write_property */ zend_std_read_dimension, /* read_dimension */ zend_std_write_dimension, /* write_dimension */ zend_std_get_property_ptr_ptr, /* get_property_ptr_ptr */ NULL, /* get */ NULL, /* set */ zend_std_has_property, /* has_property */ zend_std_unset_property, /* unset_property */ zend_std_has_dimension, /* has_dimension */ zend_std_unset_dimension, /* unset_dimension */ zend_std_get_properties, /* get_properties */ zend_std_get_method, /* get_method */ NULL, /* call_method */ zend_std_get_constructor, /* get_constructor */ zend_std_object_get_class, /* get_class_entry */ zend_std_object_get_class_name, /* get_class_name */ zend_std_compare_objects, /* compare_objects */ zend_std_cast_object_tostring, /* cast_object */ NULL, /* count_elements */ NULL, /* get_debug_info */ zend_std_get_closure, /* get_closure */ }; /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-04-06-187eb235fe-2e25ec9eb7.c
manybugs_data_35
/* mpz_gcdext(g, s, t, a, b) -- Set G to gcd(a, b), and S and T such that g = as + bt. Copyright 1991, 1993, 1994, 1995, 1996, 1997, 2000, 2001, 2005, 2011 Free Software Foundation, Inc. This file is part of the GNU MP Library. The GNU MP Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. The GNU MP Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU MP Library. If not, see http://www.gnu.org/licenses/. */ #include <stdio.h> /* for NULL */ #include "gmp.h" #include "gmp-impl.h" void mpz_gcdext (mpz_ptr g, mpz_ptr s, mpz_ptr t, mpz_srcptr a, mpz_srcptr b) { mp_size_t asize, bsize; mp_srcptr ap, bp; mp_ptr tmp_ap, tmp_bp; mp_size_t gsize, ssize, tmp_ssize; mp_ptr gp, sp, tmp_gp, tmp_sp; __mpz_struct stmp, gtmp; TMP_DECL; /* mpn_gcdext requires that U >= V. Therefore, we often have to swap U and V. This in turn leads to a lot of complications. The computed cofactor will be the wrong one, so we have to fix that up at the end. */ asize = ABS (SIZ (a)); bsize = ABS (SIZ (b)); ap = PTR (a); bp = PTR (b); if (asize < bsize || (asize == bsize && mpn_cmp (ap, bp, asize) < 0)) { MPZ_SRCPTR_SWAP (a, b); MPN_SRCPTR_SWAP (ap, asize, bp, bsize); MPZ_PTR_SWAP (s, t); } if (bsize == 0) { /* g = |a|, s = sign(a), t = 0. */ ssize = SIZ (a) >= 0 ? 1 : -1; if (ALLOC (g) < asize) _mpz_realloc (g, asize); gp = PTR (g); MPN_COPY (gp, ap, asize); SIZ (g) = asize; if (t != NULL) SIZ (t) = 0; if (s != NULL) { SIZ (s) = ssize; PTR (s)[0] = 1; } return; } TMP_MARK; tmp_ap = TMP_ALLOC_LIMBS (asize); tmp_bp = TMP_ALLOC_LIMBS (bsize); MPN_COPY (tmp_ap, ap, asize); MPN_COPY (tmp_bp, bp, bsize); tmp_gp = TMP_ALLOC_LIMBS (bsize); tmp_sp = TMP_ALLOC_LIMBS (bsize); gsize = mpn_gcdext (tmp_gp, tmp_sp, &tmp_ssize, tmp_ap, asize, tmp_bp, bsize); ssize = ABS (tmp_ssize); PTR (&gtmp) = tmp_gp; SIZ (&gtmp) = gsize; PTR (&stmp) = tmp_sp; SIZ (&stmp) = (tmp_ssize ^ SIZ (a)) >= 0 ? ssize : -ssize; if (t != NULL) { mpz_t x; MPZ_TMP_INIT (x, ssize + asize + 1); mpz_mul (x, &stmp, a); mpz_sub (x, &gtmp, x); mpz_divexact (t, x, b); } if (s != NULL) { if (ALLOC (s) < ssize) _mpz_realloc (s, ssize); sp = PTR (s); MPN_COPY (sp, tmp_sp, ssize); SIZ (s) = SIZ (&stmp); } if (ALLOC (g) < gsize) _mpz_realloc (g, gsize); gp = PTR (g); MPN_COPY (gp, tmp_gp, gsize); SIZ (g) = gsize; TMP_FREE; } /* mpz_gcdext(g, s, t, a, b) -- Set G to gcd(a, b), and S and T such that g = as + bt. Copyright 1991, 1993, 1994, 1995, 1996, 1997, 2000, 2001, 2005, 2011 Free Software Foundation, Inc. This file is part of the GNU MP Library. The GNU MP Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. The GNU MP Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU MP Library. If not, see http://www.gnu.org/licenses/. */ #include <stdio.h> /* for NULL */ #include "gmp.h" #include "gmp-impl.h" void mpz_gcdext (mpz_ptr g, mpz_ptr s, mpz_ptr t, mpz_srcptr a, mpz_srcptr b) { mp_size_t asize, bsize; mp_srcptr ap, bp; mp_ptr tmp_ap, tmp_bp; mp_size_t gsize, ssize, tmp_ssize; mp_ptr gp, sp, tmp_gp, tmp_sp; __mpz_struct stmp, gtmp; TMP_DECL; /* mpn_gcdext requires that U >= V. Therefore, we often have to swap U and V. This in turn leads to a lot of complications. The computed cofactor will be the wrong one, so we have to fix that up at the end. */ asize = ABS (SIZ (a)); bsize = ABS (SIZ (b)); ap = PTR (a); bp = PTR (b); if (asize < bsize || (asize == bsize && mpn_cmp (ap, bp, asize) < 0)) { MPZ_SRCPTR_SWAP (a, b); MPN_SRCPTR_SWAP (ap, asize, bp, bsize); MPZ_PTR_SWAP (s, t); } if (bsize == 0) { /* g = |a|, s = sgn(a), t = 0. */ ssize = SIZ (a) >= 0 ? (asize != 0) : -1; if (ALLOC (g) < asize) _mpz_realloc (g, asize); gp = PTR (g); MPN_COPY (gp, ap, asize); SIZ (g) = asize; if (t != NULL) SIZ (t) = 0; if (s != NULL) { SIZ (s) = ssize; PTR (s)[0] = 1; } return; } TMP_MARK; tmp_ap = TMP_ALLOC_LIMBS (asize); tmp_bp = TMP_ALLOC_LIMBS (bsize); MPN_COPY (tmp_ap, ap, asize); MPN_COPY (tmp_bp, bp, bsize); tmp_gp = TMP_ALLOC_LIMBS (bsize); tmp_sp = TMP_ALLOC_LIMBS (bsize); gsize = mpn_gcdext (tmp_gp, tmp_sp, &tmp_ssize, tmp_ap, asize, tmp_bp, bsize); ssize = ABS (tmp_ssize); PTR (&gtmp) = tmp_gp; SIZ (&gtmp) = gsize; PTR (&stmp) = tmp_sp; SIZ (&stmp) = (tmp_ssize ^ SIZ (a)) >= 0 ? ssize : -ssize; if (t != NULL) { mpz_t x; MPZ_TMP_INIT (x, ssize + asize + 1); mpz_mul (x, &stmp, a); mpz_sub (x, &gtmp, x); mpz_divexact (t, x, b); } if (s != NULL) { if (ALLOC (s) < ssize) _mpz_realloc (s, ssize); sp = PTR (s); MPN_COPY (sp, tmp_sp, ssize); SIZ (s) = SIZ (&stmp); } if (ALLOC (g) < gsize) _mpz_realloc (g, gsize); gp = PTR (g); MPN_COPY (gp, tmp_gp, gsize); SIZ (g) = gsize; TMP_FREE; }
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/gmp_14166-14167.c
manybugs_data_36
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2012 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Rasmus Lerdorf <[email protected]> | | Jaakko Hyvätti <[email protected]> | | Wez Furlong <[email protected]> | | Gustavo Lopes <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ /* * HTML entity resources: * * http://www.unicode.org/Public/MAPPINGS/OBSOLETE/UNI2SGML.TXT * * XHTML 1.0 DTD * http://www.w3.org/TR/2002/REC-xhtml1-20020801/dtds.html#h-A2 * * From HTML 4.01 strict DTD: * http://www.w3.org/TR/html4/HTMLlat1.ent * http://www.w3.org/TR/html4/HTMLsymbol.ent * http://www.w3.org/TR/html4/HTMLspecial.ent * * HTML 5: * http://dev.w3.org/html5/spec/Overview.html#named-character-references */ #include "php.h" #if PHP_WIN32 #include "config.w32.h" #else #include <php_config.h> #endif #include "php_standard.h" #include "php_string.h" #include "SAPI.h" #if HAVE_LOCALE_H #include <locale.h> #endif #if HAVE_LANGINFO_H #include <langinfo.h> #endif #include <zend_hash.h> #include "html_tables.h" /* Macro for disabling flag of translation of non-basic entities where this isn't supported. * Not appropriate for html_entity_decode/htmlspecialchars_decode */ #define LIMIT_ALL(all, doctype, charset) do { \ (all) = (all) && !CHARSET_PARTIAL_SUPPORT((charset)) && ((doctype) != ENT_HTML_DOC_XML1); \ } while (0) #define MB_FAILURE(pos, advance) do { \ *cursor = pos + (advance); \ *status = FAILURE; \ return 0; \ } while (0) #define CHECK_LEN(pos, chars_need) ((str_len - (pos)) >= (chars_need)) /* valid as single byte character or leading byte */ #define utf8_lead(c) ((c) < 0x80 || ((c) >= 0xC2 && (c) <= 0xF4)) /* whether it's actually valid depends on other stuff; * this macro cannot check for non-shortest forms, surrogates or * code points above 0x10FFFF */ #define utf8_trail(c) ((c) >= 0x80 && (c) <= 0xBF) #define gb2312_lead(c) ((c) != 0x8E && (c) != 0x8F && (c) != 0xA0 && (c) != 0xFF) #define gb2312_trail(c) ((c) >= 0xA1 && (c) <= 0xFE) #define sjis_lead(c) ((c) != 0x80 && (c) != 0xA0 && (c) < 0xFD) #define sjis_trail(c) ((c) >= 0x40 && (c) != 0x7F && (c) < 0xFD) /* {{{ get_next_char */ static inline unsigned int get_next_char( enum entity_charset charset, const unsigned char *str, size_t str_len, size_t *cursor, int *status) { size_t pos = *cursor; unsigned int this_char = 0; *status = SUCCESS; assert(pos <= str_len); if (!CHECK_LEN(pos, 1)) MB_FAILURE(pos, 1); switch (charset) { case cs_utf_8: { /* We'll follow strategy 2. from section 3.6.1 of UTR #36: * "In a reported illegal byte sequence, do not include any * non-initial byte that encodes a valid character or is a leading * byte for a valid sequence." */ unsigned char c; c = str[pos]; if (c < 0x80) { this_char = c; pos++; } else if (c < 0xc2) { MB_FAILURE(pos, 1); } else if (c < 0xe0) { if (!CHECK_LEN(pos, 2)) MB_FAILURE(pos, 1); if (!utf8_trail(str[pos + 1])) { MB_FAILURE(pos, utf8_lead(str[pos + 1]) ? 1 : 2); } this_char = ((c & 0x1f) << 6) | (str[pos + 1] & 0x3f); if (this_char < 0x80) { /* non-shortest form */ MB_FAILURE(pos, 2); } pos += 2; } else if (c < 0xf0) { size_t avail = str_len - pos; if (avail < 3 || !utf8_trail(str[pos + 1]) || !utf8_trail(str[pos + 2])) { if (avail < 2 || utf8_lead(str[pos + 1])) MB_FAILURE(pos, 1); else if (avail < 3 || utf8_lead(str[pos + 2])) MB_FAILURE(pos, 2); else MB_FAILURE(pos, 3); } this_char = ((c & 0x0f) << 12) | ((str[pos + 1] & 0x3f) << 6) | (str[pos + 2] & 0x3f); if (this_char < 0x800) { /* non-shortest form */ MB_FAILURE(pos, 3); } else if (this_char >= 0xd800 && this_char <= 0xdfff) { /* surrogate */ MB_FAILURE(pos, 3); } pos += 3; } else if (c < 0xf5) { size_t avail = str_len - pos; if (avail < 4 || !utf8_trail(str[pos + 1]) || !utf8_trail(str[pos + 2]) || !utf8_trail(str[pos + 3])) { if (avail < 2 || utf8_lead(str[pos + 1])) MB_FAILURE(pos, 1); else if (avail < 3 || utf8_lead(str[pos + 2])) MB_FAILURE(pos, 2); else if (avail < 4 || utf8_lead(str[pos + 3])) MB_FAILURE(pos, 3); else MB_FAILURE(pos, 4); } this_char = ((c & 0x07) << 18) | ((str[pos + 1] & 0x3f) << 12) | ((str[pos + 2] & 0x3f) << 6) | (str[pos + 3] & 0x3f); if (this_char < 0x10000 || this_char > 0x10FFFF) { /* non-shortest form or outside range */ MB_FAILURE(pos, 4); } pos += 4; } else { MB_FAILURE(pos, 1); } } break; case cs_big5: /* reference http://demo.icu-project.org/icu-bin/convexp?conv=big5 */ { unsigned char c = str[pos]; if (c >= 0x81 && c <= 0xFE) { unsigned char next; if (!CHECK_LEN(pos, 2)) MB_FAILURE(pos, 1); next = str[pos + 1]; if ((next >= 0x40 && next <= 0x7E) || (next >= 0xA1 && next <= 0xFE)) { this_char = (c << 8) | next; } else { MB_FAILURE(pos, 1); } pos += 2; } else { this_char = c; pos += 1; } } break; case cs_big5hkscs: { unsigned char c = str[pos]; if (c >= 0x81 && c <= 0xFE) { unsigned char next; if (!CHECK_LEN(pos, 2)) MB_FAILURE(pos, 1); next = str[pos + 1]; if ((next >= 0x40 && next <= 0x7E) || (next >= 0xA1 && next <= 0xFE)) { this_char = (c << 8) | next; } else if (next != 0x80 && next != 0xFF) { MB_FAILURE(pos, 1); } else { MB_FAILURE(pos, 2); } pos += 2; } else { this_char = c; pos += 1; } } break; case cs_gb2312: /* EUC-CN */ { unsigned char c = str[pos]; if (c >= 0xA1 && c <= 0xFE) { unsigned char next; if (!CHECK_LEN(pos, 2)) MB_FAILURE(pos, 1); next = str[pos + 1]; if (gb2312_trail(next)) { this_char = (c << 8) | next; } else if (gb2312_lead(next)) { MB_FAILURE(pos, 1); } else { MB_FAILURE(pos, 2); } pos += 2; } else if (gb2312_lead(c)) { this_char = c; pos += 1; } else { MB_FAILURE(pos, 1); } } break; case cs_sjis: { unsigned char c = str[pos]; if ((c >= 0x81 && c <= 0x9F) || (c >= 0xE0 && c <= 0xFC)) { unsigned char next; if (!CHECK_LEN(pos, 2)) MB_FAILURE(pos, 1); next = str[pos + 1]; if (sjis_trail(next)) { this_char = (c << 8) | next; } else if (sjis_lead(next)) { MB_FAILURE(pos, 1); } else { MB_FAILURE(pos, 2); } pos += 2; } else if (c < 0x80 || (c >= 0xA1 && c <= 0xDF)) { this_char = c; pos += 1; } else { MB_FAILURE(pos, 1); } } break; case cs_eucjp: { unsigned char c = str[pos]; if (c >= 0xA1 && c <= 0xFE) { unsigned next; if (!CHECK_LEN(pos, 2)) MB_FAILURE(pos, 1); next = str[pos + 1]; if (next >= 0xA1 && next <= 0xFE) { /* this a jis kanji char */ this_char = (c << 8) | next; } else { MB_FAILURE(pos, (next != 0xA0 && next != 0xFF) ? 1 : 2); } pos += 2; } else if (c == 0x8E) { unsigned next; if (!CHECK_LEN(pos, 2)) MB_FAILURE(pos, 1); next = str[pos + 1]; if (next >= 0xA1 && next <= 0xDF) { /* JIS X 0201 kana */ this_char = (c << 8) | next; } else { MB_FAILURE(pos, (next != 0xA0 && next != 0xFF) ? 1 : 2); } pos += 2; } else if (c == 0x8F) { size_t avail = str_len - pos; if (avail < 3 || !(str[pos + 1] >= 0xA1 && str[pos + 1] <= 0xFE) || !(str[pos + 2] >= 0xA1 && str[pos + 2] <= 0xFE)) { if (avail < 2 || (str[pos + 1] != 0xA0 && str[pos + 1] != 0xFF)) MB_FAILURE(pos, 1); else if (avail < 3 || (str[pos + 2] != 0xA0 && str[pos + 2] != 0xFF)) MB_FAILURE(pos, 2); else MB_FAILURE(pos, 3); } else { /* JIS X 0212 hojo-kanji */ this_char = (c << 16) | (str[pos + 1] << 8) | str[pos + 2]; } pos += 3; } else if (c != 0xA0 && c != 0xFF) { /* character encoded in 1 code unit */ this_char = c; pos += 1; } else { MB_FAILURE(pos, 1); } } break; default: /* single-byte charsets */ this_char = str[pos++]; break; } *cursor = pos; return this_char; } /* }}} */ /* {{{ php_next_utf8_char * Public interface for get_next_char used with UTF-8 */ PHPAPI unsigned int php_next_utf8_char( const unsigned char *str, size_t str_len, size_t *cursor, int *status) { return get_next_char(cs_utf_8, str, str_len, cursor, status); } /* }}} */ /* {{{ entity_charset determine_charset * returns the charset identifier based on current locale or a hint. * defaults to UTF-8 */ static enum entity_charset determine_charset(char *charset_hint TSRMLS_DC) { int i; enum entity_charset charset = cs_utf_8; int len = 0; const zend_encoding *zenc; /* Default is now UTF-8 */ if (charset_hint == NULL) return cs_utf_8; if ((len = strlen(charset_hint)) != 0) { goto det_charset; } zenc = zend_multibyte_get_internal_encoding(TSRMLS_C); if (zenc != NULL) { charset_hint = (char *)zend_multibyte_get_encoding_name(zenc); if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) { if ((len == 4) /* sizeof (none|auto|pass) */ && (!memcmp("pass", charset_hint, 4) || !memcmp("auto", charset_hint, 4) || !memcmp("auto", charset_hint, 4))) { charset_hint = NULL; len = 0; } else { goto det_charset; } } } charset_hint = SG(default_charset); if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) { goto det_charset; } /* try to detect the charset for the locale */ #if HAVE_NL_LANGINFO && HAVE_LOCALE_H && defined(CODESET) charset_hint = nl_langinfo(CODESET); if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) { goto det_charset; } #endif #if HAVE_LOCALE_H /* try to figure out the charset from the locale */ { char *localename; char *dot, *at; /* lang[_territory][.codeset][@modifier] */ localename = setlocale(LC_CTYPE, NULL); dot = strchr(localename, '.'); if (dot) { dot++; /* locale specifies a codeset */ at = strchr(dot, '@'); if (at) len = at - dot; else len = strlen(dot); charset_hint = dot; } else { /* no explicit name; see if the name itself * is the charset */ charset_hint = localename; len = strlen(charset_hint); } } #endif det_charset: if (charset_hint) { int found = 0; /* now walk the charset map and look for the codeset */ for (i = 0; charset_map[i].codeset; i++) { if (len == strlen(charset_map[i].codeset) && strncasecmp(charset_hint, charset_map[i].codeset, len) == 0) { charset = charset_map[i].charset; found = 1; break; } } if (!found) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "charset `%s' not supported, assuming utf-8", charset_hint); } } return charset; } /* }}} */ /* {{{ php_utf32_utf8 */ static inline size_t php_utf32_utf8(unsigned char *buf, unsigned k) { size_t retval = 0; /* assert(0x0 <= k <= 0x10FFFF); */ if (k < 0x80) { buf[0] = k; retval = 1; } else if (k < 0x800) { buf[0] = 0xc0 | (k >> 6); buf[1] = 0x80 | (k & 0x3f); retval = 2; } else if (k < 0x10000) { buf[0] = 0xe0 | (k >> 12); buf[1] = 0x80 | ((k >> 6) & 0x3f); buf[2] = 0x80 | (k & 0x3f); retval = 3; } else { buf[0] = 0xf0 | (k >> 18); buf[1] = 0x80 | ((k >> 12) & 0x3f); buf[2] = 0x80 | ((k >> 6) & 0x3f); buf[3] = 0x80 | (k & 0x3f); retval = 4; } /* UTF-8 has been restricted to max 4 bytes since RFC 3629 */ return retval; } /* }}} */ /* {{{ php_mb2_int_to_char * Convert back big endian int representation of sequence of one or two 8-bit code units. */ static inline size_t php_mb2_int_to_char(unsigned char *buf, unsigned k) { assert(k <= 0xFFFFU); /* one or two bytes */ if (k <= 0xFFU) { /* 1 */ buf[0] = k; return 1U; } else { /* 2 */ buf[0] = k >> 8; buf[1] = k & 0xFFU; return 2U; } } /* }}} */ /* {{{ php_mb3_int_to_char * Convert back big endian int representation of sequence of one to three 8-bit code units. * For EUC-JP. */ static inline size_t php_mb3_int_to_char(unsigned char *buf, unsigned k) { assert(k <= 0xFFFFFFU); /* one to three bytes */ if (k <= 0xFFU) { /* 1 */ buf[0] = k; return 1U; } else if (k <= 0xFFFFU) { /* 2 */ buf[0] = k >> 8; buf[1] = k & 0xFFU; return 2U; } else { buf[0] = k >> 16; buf[1] = (k >> 8) & 0xFFU; buf[2] = k & 0xFFU; return 3U; } } /* }}} */ /* {{{ unimap_bsearc_cmp * Binary search of unicode code points in unicode <--> charset mapping. * Returns the code point in the target charset (whose mapping table was given) or 0 if * the unicode code point is not in the table. */ static inline unsigned char unimap_bsearch(const uni_to_enc *table, unsigned code_key_a, size_t num) { const uni_to_enc *l = table, *h = &table[num-1], *m; unsigned short code_key; /* we have no mappings outside the BMP */ if (code_key_a > 0xFFFFU) return 0; code_key = (unsigned short) code_key_a; while (l <= h) { m = l + (h - l) / 2; if (code_key < m->un_code_point) h = m - 1; else if (code_key > m->un_code_point) l = m + 1; else return m->cs_code; } return 0; } /* }}} */ /* {{{ map_from_unicode */ static inline int map_from_unicode(unsigned code, enum entity_charset charset, unsigned *res) { unsigned char found; const uni_to_enc *table; size_t table_size; switch (charset) { case cs_8859_1: /* identity mapping of code points to unicode */ if (code > 0xFF) { return FAILURE; } *res = code; break; case cs_8859_5: if (code <= 0xA0 || code == 0xAD /* soft hyphen */) { *res = code; } else if (code == 0x2116) { *res = 0xF0; /* numero sign */ } else if (code == 0xA7) { *res = 0xFD; /* section sign */ } else if (code >= 0x0401 && code <= 0x044F) { if (code == 0x040D || code == 0x0450 || code == 0x045D) return FAILURE; *res = code - 0x360; } else { return FAILURE; } break; case cs_8859_15: if (code < 0xA4 || (code > 0xBE && code <= 0xFF)) { *res = code; } else { /* between A4 and 0xBE */ found = unimap_bsearch(unimap_iso885915, code, sizeof(unimap_iso885915) / sizeof(*unimap_iso885915)); if (found) *res = found; else return FAILURE; } break; case cs_cp1252: if (code <= 0x7F || (code >= 0xA0 && code <= 0xFF)) { *res = code; } else { found = unimap_bsearch(unimap_win1252, code, sizeof(unimap_win1252) / sizeof(*unimap_win1252)); if (found) *res = found; else return FAILURE; } break; case cs_macroman: if (code == 0x7F) return FAILURE; table = unimap_macroman; table_size = sizeof(unimap_macroman) / sizeof(*unimap_macroman); goto table_over_7F; case cs_cp1251: table = unimap_win1251; table_size = sizeof(unimap_win1251) / sizeof(*unimap_win1251); goto table_over_7F; case cs_koi8r: table = unimap_koi8r; table_size = sizeof(unimap_koi8r) / sizeof(*unimap_koi8r); goto table_over_7F; case cs_cp866: table = unimap_cp866; table_size = sizeof(unimap_cp866) / sizeof(*unimap_cp866); table_over_7F: if (code <= 0x7F) { *res = code; } else { found = unimap_bsearch(table, code, table_size); if (found) *res = found; else return FAILURE; } break; /* from here on, only map the possible characters in the ASCII range. * to improve support here, it's a matter of building the unicode mappings. * See <http://www.unicode.org/Public/6.0.0/ucd/Unihan.zip> */ case cs_sjis: case cs_eucjp: /* we interpret 0x5C as the Yen symbol. This is not universal. * See <http://www.w3.org/Submission/japanese-xml/#ambiguity_of_yen> */ if (code >= 0x20 && code <= 0x7D) { if (code == 0x5C) return FAILURE; *res = code; } else { return FAILURE; } break; case cs_big5: case cs_big5hkscs: case cs_gb2312: if (code >= 0x20 && code <= 0x7D) { *res = code; } else { return FAILURE; } break; default: return FAILURE; } return SUCCESS; } /* }}} */ /* {{{ */ static inline void map_to_unicode(unsigned code, const enc_to_uni *table, unsigned *res) { /* only single byte encodings are currently supported; assumed code <= 0xFF */ *res = table->inner[ENT_ENC_TO_UNI_STAGE1(code)]->uni_cp[ENT_ENC_TO_UNI_STAGE2(code)]; } /* }}} */ /* {{{ unicode_cp_is_allowed */ static inline int unicode_cp_is_allowed(unsigned uni_cp, int document_type) { /* XML 1.0 HTML 4.01 HTML 5 * 0x09..0x0A 0x09..0x0A 0x09..0x0A * 0x0D 0x0D 0x0C..0x0D * 0x0020..0xD7FF 0x20..0x7E 0x20..0x7E * 0x00A0..0xD7FF 0x00A0..0xD7FF * 0xE000..0xFFFD 0xE000..0x10FFFF 0xE000..0xFDCF * 0x010000..0x10FFFF 0xFDF0..0x10FFFF (*) * * (*) exclude code points where ((code & 0xFFFF) >= 0xFFFE) * * References: * XML 1.0: <http://www.w3.org/TR/REC-xml/#charsets> * HTML 4.01: <http://www.w3.org/TR/1999/PR-html40-19990824/sgml/sgmldecl.html> * HTML 5: <http://dev.w3.org/html5/spec/Overview.html#preprocessing-the-input-stream> * * Not sure this is the relevant part for HTML 5, though. I opted to * disallow the characters that would result in a parse error when * preprocessing of the input stream. See also section 8.1.3. * * It's unclear if XHTML 1.0 allows C1 characters. I'll opt to apply to * XHTML 1.0 the same rules as for XML 1.0. * See <http://cmsmcq.com/2007/C1.xml>. */ switch (document_type) { case ENT_HTML_DOC_HTML401: return (uni_cp >= 0x20 && uni_cp <= 0x7E) || (uni_cp == 0x0A || uni_cp == 0x09 || uni_cp == 0x0D) || (uni_cp >= 0xA0 && uni_cp <= 0xD7FF) || (uni_cp >= 0xE000 && uni_cp <= 0x10FFFF); case ENT_HTML_DOC_HTML5: return (uni_cp >= 0x20 && uni_cp <= 0x7E) || (uni_cp >= 0x09 && uni_cp <= 0x0D && uni_cp != 0x0B) || /* form feed U+0C allowed */ (uni_cp >= 0xA0 && uni_cp <= 0xD7FF) || (uni_cp >= 0xE000 && uni_cp <= 0x10FFFF && ((uni_cp & 0xFFFF) < 0xFFFE) && /* last two of each plane (nonchars) disallowed */ (uni_cp < 0xFDD0 || uni_cp > 0xFDEF)); /* U+FDD0-U+FDEF (nonchars) disallowed */ case ENT_HTML_DOC_XHTML: case ENT_HTML_DOC_XML1: return (uni_cp >= 0x20 && uni_cp <= 0xD7FF) || (uni_cp == 0x0A || uni_cp == 0x09 || uni_cp == 0x0D) || (uni_cp >= 0xE000 && uni_cp <= 0x10FFFF && uni_cp != 0xFFFE && uni_cp != 0xFFFF); default: return 1; } } /* }}} */ /* {{{ unicode_cp_is_allowed */ static inline int numeric_entity_is_allowed(unsigned uni_cp, int document_type) { /* less restrictive than unicode_cp_is_allowed */ switch (document_type) { case ENT_HTML_DOC_HTML401: /* all non-SGML characters (those marked with UNUSED in DESCSET) should be * representable with numeric entities */ return uni_cp <= 0x10FFFF; case ENT_HTML_DOC_HTML5: /* 8.1.4. The numeric character reference forms described above are allowed to * reference any Unicode code point other than U+0000, U+000D, permanently * undefined Unicode characters (noncharacters), and control characters other * than space characters (U+0009, U+000A, U+000C and U+000D) */ /* seems to allow surrogate characters, then */ return (uni_cp >= 0x20 && uni_cp <= 0x7E) || (uni_cp >= 0x09 && uni_cp <= 0x0C && uni_cp != 0x0B) || /* form feed U+0C allowed, but not U+0D */ (uni_cp >= 0xA0 && uni_cp <= 0x10FFFF && ((uni_cp & 0xFFFF) < 0xFFFE) && /* last two of each plane (nonchars) disallowed */ (uni_cp < 0xFDD0 || uni_cp > 0xFDEF)); /* U+FDD0-U+FDEF (nonchars) disallowed */ case ENT_HTML_DOC_XHTML: case ENT_HTML_DOC_XML1: /* OTOH, XML 1.0 requires "character references to match the production for Char * See <http://www.w3.org/TR/REC-xml/#NT-CharRef> */ return unicode_cp_is_allowed(uni_cp, document_type); default: return 1; } } /* }}} */ /* {{{ process_numeric_entity * Auxiliary function to traverse_for_entities. * On input, *buf should point to the first character after # and on output, it's the last * byte read, no matter if there was success or insuccess. */ static inline int process_numeric_entity(const char **buf, unsigned *code_point) { long code_l; int hexadecimal = (**buf == 'x' || **buf == 'X'); /* TODO: XML apparently disallows "X" */ char *endptr; if (hexadecimal && (**buf != '\0')) (*buf)++; /* strtol allows whitespace and other stuff in the beginning * we're not interested */ if ((hexadecimal && !isxdigit(**buf)) || (!hexadecimal && !isdigit(**buf))) { return FAILURE; } code_l = strtol(*buf, &endptr, hexadecimal ? 16 : 10); /* we're guaranteed there were valid digits, so *endptr > buf */ *buf = endptr; if (**buf != ';') return FAILURE; /* many more are invalid, but that depends on whether it's HTML * (and which version) or XML. */ if (code_l > 0x10FFFFL) return FAILURE; if (code_point != NULL) *code_point = (unsigned)code_l; return SUCCESS; } /* }}} */ /* {{{ process_named_entity */ static inline int process_named_entity_html(const char **buf, const char **start, size_t *length) { *start = *buf; /* "&" is represented by a 0x26 in all supported encodings. That means * the byte after represents a character or is the leading byte of an * sequence of 8-bit code units. If in the ranges below, it represents * necessarily a alpha character because none of the supported encodings * has an overlap with ASCII in the leading byte (only on the second one) */ while ((**buf >= 'a' && **buf <= 'z') || (**buf >= 'A' && **buf <= 'Z') || (**buf >= '0' && **buf <= '9')) { (*buf)++; } if (**buf != ';') return FAILURE; /* cast to size_t OK as the quantity is always non-negative */ *length = *buf - *start; if (*length == 0) return FAILURE; return SUCCESS; } /* }}} */ /* {{{ resolve_named_entity_html */ static inline int resolve_named_entity_html(const char *start, size_t length, const entity_ht *ht, unsigned *uni_cp1, unsigned *uni_cp2) { const entity_cp_map *s; ulong hash = zend_inline_hash_func(start, length); s = ht->buckets[hash % ht->num_elems]; while (s->entity) { if (s->entity_len == length) { if (memcmp(start, s->entity, length) == 0) { *uni_cp1 = s->codepoint1; *uni_cp2 = s->codepoint2; return SUCCESS; } } s++; } return FAILURE; } /* }}} */ static inline size_t write_octet_sequence(unsigned char *buf, enum entity_charset charset, unsigned code) { /* code is not necessarily a unicode code point */ switch (charset) { case cs_utf_8: return php_utf32_utf8(buf, code); case cs_8859_1: case cs_cp1252: case cs_8859_15: case cs_koi8r: case cs_cp1251: case cs_8859_5: case cs_cp866: case cs_macroman: /* single byte stuff */ *buf = code; return 1; case cs_big5: case cs_big5hkscs: case cs_sjis: case cs_gb2312: /* we don't have complete unicode mappings for these yet in entity_decode, * and we opt to pass through the octet sequences for these in htmlentities * instead of converting to an int and then converting back. */ #if 0 return php_mb2_int_to_char(buf, code); #else #ifdef ZEND_DEBUG assert(code <= 0xFFU); #endif *buf = code; return 1; #endif case cs_eucjp: #if 0 /* idem */ return php_mb2_int_to_char(buf, code); #else #ifdef ZEND_DEBUG assert(code <= 0xFFU); #endif *buf = code; return 1; #endif default: assert(0); return 0; } } /* {{{ traverse_for_entities * Auxiliary function to php_unescape_html_entities(). * - The argument "all" determines if all numeric entities are decode or only those * that correspond to quotes (depending on quote_style). */ /* maximum expansion (factor 1.2) for HTML 5 with &nGt; and &nLt; */ /* +2 is 1 because of rest (probably unnecessary), 1 because of terminating 0 */ #define TRAVERSE_FOR_ENTITIES_EXPAND_SIZE(oldlen) ((oldlen) + (oldlen) / 5 + 2) static void traverse_for_entities( const char *old, size_t oldlen, char *ret, /* should have allocated TRAVERSE_FOR_ENTITIES_EXPAND_SIZE(olden) */ size_t *retlen, int all, int flags, const entity_ht *inv_map, enum entity_charset charset) { const char *p, *lim; char *q; int doctype = flags & ENT_HTML_DOC_TYPE_MASK; lim = old + oldlen; /* terminator address */ assert(*lim == '\0'); for (p = old, q = ret; p < lim;) { unsigned code, code2 = 0; const char *next = NULL; /* when set, next > p, otherwise possible inf loop */ /* Shift JIS, Big5 and HKSCS use multi-byte encodings where an * ASCII range byte can be part of a multi-byte sequence. * However, they start at 0x40, therefore if we find a 0x26 byte, * we're sure it represents the '&' character. */ /* assumes there are no single-char entities */ if (p[0] != '&' || (p + 3 >= lim)) { *(q++) = *(p++); continue; } /* now p[3] is surely valid and is no terminator */ /* numerical entity */ if (p[1] == '#') { next = &p[2]; if (process_numeric_entity(&next, &code) == FAILURE) goto invalid_code; /* If we're in htmlspecialchars_decode, we're only decoding entities * that represent &, <, >, " and '. Is this one of them? */ if (!all && (code > 63U || stage3_table_be_apos_00000[code].data.ent.entity == NULL)) goto invalid_code; /* are we allowed to decode this entity in this document type? * HTML 5 is the only that has a character that cannot be used in * a numeric entity but is allowed literally (U+000D). The * unoptimized version would be ... || !numeric_entity_is_allowed(code) */ if (!unicode_cp_is_allowed(code, doctype) || (doctype == ENT_HTML_DOC_HTML5 && code == 0x0D)) goto invalid_code; } else { const char *start; size_t ent_len; next = &p[1]; start = next; if (process_named_entity_html(&next, &start, &ent_len) == FAILURE) goto invalid_code; if (resolve_named_entity_html(start, ent_len, inv_map, &code, &code2) == FAILURE) { if (doctype == ENT_HTML_DOC_XHTML && ent_len == 4 && start[0] == 'a' && start[1] == 'p' && start[2] == 'o' && start[3] == 's') { /* uses html4 inv_map, which doesn't include apos;. This is a * hack to support it */ code = (unsigned) '\''; } else { goto invalid_code; } } } assert(*next == ';'); if (((code == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) || (code == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))) /* && code2 == '\0' always true for current maps */) goto invalid_code; /* deal with encodings other than utf-8/iso-8859-1 */ if (!CHARSET_UNICODE_COMPAT(charset)) { /* replace unicode code point */ if (map_from_unicode(code, charset, &code) == FAILURE || code2 != 0) goto invalid_code; /* not representable in target charset */ } q += write_octet_sequence(q, charset, code); if (code2) { q += write_octet_sequence(q, charset, code2); } /* jump over the valid entity; may go beyond size of buffer; np */ p = next + 1; continue; invalid_code: for (; p < next; p++) { *(q++) = *p; } } *q = '\0'; *retlen = (size_t)(q - ret); } /* }}} */ /* {{{ unescape_inverse_map */ static const entity_ht *unescape_inverse_map(int all, int flags) { int document_type = flags & ENT_HTML_DOC_TYPE_MASK; if (all) { switch (document_type) { case ENT_HTML_DOC_HTML401: case ENT_HTML_DOC_XHTML: /* but watch out for &apos;...*/ return &ent_ht_html4; case ENT_HTML_DOC_HTML5: return &ent_ht_html5; default: return &ent_ht_be_apos; } } else { switch (document_type) { case ENT_HTML_DOC_HTML401: return &ent_ht_be_noapos; default: return &ent_ht_be_apos; } } } /* }}} */ /* {{{ determine_entity_table * Entity table to use. Note that entity tables are defined in terms of * unicode code points */ static entity_table_opt determine_entity_table(int all, int doctype) { entity_table_opt retval = {NULL}; assert(!(doctype == ENT_HTML_DOC_XML1 && all)); if (all) { retval.ms_table = (doctype == ENT_HTML_DOC_HTML5) ? entity_ms_table_html5 : entity_ms_table_html4; } else { retval.table = (doctype == ENT_HTML_DOC_HTML401) ? stage3_table_be_noapos_00000 : stage3_table_be_apos_00000; } return retval; } /* }}} */ /* {{{ php_unescape_html_entities * The parameter "all" should be true to decode all possible entities, false to decode * only the basic ones, i.e., those in basic_entities_ex + the numeric entities * that correspond to quotes. */ PHPAPI char *php_unescape_html_entities(unsigned char *old, size_t oldlen, size_t *newlen, int all, int flags, char *hint_charset TSRMLS_DC) { size_t retlen; char *ret; enum entity_charset charset; const entity_ht *inverse_map = NULL; size_t new_size = TRAVERSE_FOR_ENTITIES_EXPAND_SIZE(oldlen); if (all) { charset = determine_charset(hint_charset TSRMLS_CC); } else { charset = cs_8859_1; /* charset shouldn't matter, use ISO-8859-1 for performance */ } /* don't use LIMIT_ALL! */ if (oldlen > new_size) { /* overflow, refuse to do anything */ ret = estrndup((char*)old, oldlen); retlen = oldlen; goto empty_source; } ret = emalloc(new_size); *ret = '\0'; retlen = oldlen; if (retlen == 0) { goto empty_source; } inverse_map = unescape_inverse_map(all, flags); /* replace numeric entities */ traverse_for_entities(old, oldlen, ret, &retlen, all, flags, inverse_map, charset); empty_source: *newlen = retlen; return ret; } /* }}} */ PHPAPI char *php_escape_html_entities(unsigned char *old, size_t oldlen, size_t *newlen, int all, int flags, char *hint_charset TSRMLS_DC) { return php_escape_html_entities_ex(old, oldlen, newlen, all, flags, hint_charset, 1 TSRMLS_CC); } /* {{{ find_entity_for_char */ static inline void find_entity_for_char( unsigned int k, enum entity_charset charset, const entity_stage1_row *table, const unsigned char **entity, size_t *entity_len, unsigned char *old, size_t oldlen, size_t *cursor) { unsigned stage1_idx = ENT_STAGE1_INDEX(k); const entity_stage3_row *c; if (stage1_idx > 0x1D) { *entity = NULL; *entity_len = 0; return; } c = &table[stage1_idx][ENT_STAGE2_INDEX(k)][ENT_STAGE3_INDEX(k)]; if (!c->ambiguous) { *entity = (const unsigned char *)c->data.ent.entity; *entity_len = c->data.ent.entity_len; } else { /* peek at next char */ size_t cursor_before = *cursor; int status = SUCCESS; unsigned next_char; if (!(*cursor < oldlen)) goto no_suitable_2nd; next_char = get_next_char(charset, old, oldlen, cursor, &status); if (status == FAILURE) goto no_suitable_2nd; { const entity_multicodepoint_row *s, *e; s = &c->data.multicodepoint_table[1]; e = s - 1 + c->data.multicodepoint_table[0].leading_entry.size; /* we could do a binary search but it's not worth it since we have * at most two entries... */ for ( ; s <= e; s++) { if (s->normal_entry.second_cp == next_char) { *entity = s->normal_entry.entity; *entity_len = s->normal_entry.entity_len; return; } } } no_suitable_2nd: *cursor = cursor_before; *entity = (const unsigned char *) c->data.multicodepoint_table[0].leading_entry.default_entity; *entity_len = c->data.multicodepoint_table[0].leading_entry.default_entity_len; } } /* }}} */ /* {{{ find_entity_for_char_basic */ static inline void find_entity_for_char_basic( unsigned int k, const entity_stage3_row *table, const unsigned char **entity, size_t *entity_len) { if (k >= 64U) { *entity = NULL; *entity_len = 0; return; } *entity = table[k].data.ent.entity; *entity_len = table[k].data.ent.entity_len; } /* }}} */ /* {{{ php_escape_html_entities */ PHPAPI char *php_escape_html_entities_ex(unsigned char *old, size_t oldlen, size_t *newlen, int all, int flags, char *hint_charset, zend_bool double_encode TSRMLS_DC) { size_t cursor, maxlen, len; char *replaced; enum entity_charset charset = determine_charset(hint_charset TSRMLS_CC); int doctype = flags & ENT_HTML_DOC_TYPE_MASK; entity_table_opt entity_table; const enc_to_uni *to_uni_table = NULL; const entity_ht *inv_map = NULL; /* used for !double_encode */ /* only used if flags includes ENT_HTML_IGNORE_ERRORS or ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS */ const unsigned char *replacement; size_t replacement_len; if (all) { /* replace with all named entities */ if (CHARSET_PARTIAL_SUPPORT(charset)) { php_error_docref0(NULL TSRMLS_CC, E_STRICT, "Only basic entities " "substitution is supported for multi-byte encodings other than UTF-8; " "functionality is equivalent to htmlspecialchars"); } LIMIT_ALL(all, doctype, charset); } entity_table = determine_entity_table(all, doctype); if (all && !CHARSET_UNICODE_COMPAT(charset)) { to_uni_table = enc_to_uni_index[charset]; } if (!double_encode) { /* first arg is 1 because we want to identify valid named entities * even if we are only encoding the basic ones */ inv_map = unescape_inverse_map(1, flags); } if (flags & (ENT_HTML_SUBSTITUTE_ERRORS | ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS)) { if (charset == cs_utf_8) { replacement = (const unsigned char*)"\xEF\xBF\xBD"; replacement_len = sizeof("\xEF\xBF\xBD") - 1; } else { replacement = (const unsigned char*)"&#xFFFD;"; replacement_len = sizeof("&#xFFFD;") - 1; } } /* initial estimate */ if (oldlen < 64) { maxlen = 128; } else { maxlen = 2 * oldlen; if (maxlen < oldlen) { zend_error_noreturn(E_ERROR, "Input string is too long"); return NULL; } } replaced = emalloc(maxlen + 1); /* adding 1 is safe: maxlen is even */ len = 0; cursor = 0; while (cursor < oldlen) { const unsigned char *mbsequence = NULL; size_t mbseqlen = 0, cursor_before = cursor; int status = SUCCESS; unsigned int this_char = get_next_char(charset, old, oldlen, &cursor, &status); /* guarantee we have at least 40 bytes to write. * In HTML5, entities may take up to 33 bytes */ if (len > maxlen - 40) { /* maxlen can never be smaller than 128 */ replaced = safe_erealloc(replaced, maxlen , 1, 128 + 1); maxlen += 128; } if (status == FAILURE) { /* invalid MB sequence */ if (flags & ENT_HTML_IGNORE_ERRORS) { continue; } else if (flags & ENT_HTML_SUBSTITUTE_ERRORS) { memcpy(&replaced[len], replacement, replacement_len); len += replacement_len; continue; } else { efree(replaced); *newlen = 0; return STR_EMPTY_ALLOC(); } } else { /* SUCCESS */ mbsequence = &old[cursor_before]; mbseqlen = cursor - cursor_before; } if (this_char != '&') { /* no entity on this position */ const unsigned char *rep = NULL; size_t rep_len = 0; if (((this_char == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) || (this_char == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE)))) goto pass_char_through; if (all) { /* false that CHARSET_PARTIAL_SUPPORT(charset) */ if (to_uni_table != NULL) { /* !CHARSET_UNICODE_COMPAT therefore not UTF-8; since UTF-8 * is the only multibyte encoding with !CHARSET_PARTIAL_SUPPORT, * we're using a single byte encoding */ map_to_unicode(this_char, to_uni_table, &this_char); if (this_char == 0xFFFF) /* no mapping; pass through */ goto pass_char_through; } /* the cursor may advance */ find_entity_for_char(this_char, charset, entity_table.ms_table, &rep, &rep_len, old, oldlen, &cursor); } else { find_entity_for_char_basic(this_char, entity_table.table, &rep, &rep_len); } if (rep != NULL) { replaced[len++] = '&'; memcpy(&replaced[len], rep, rep_len); len += rep_len; replaced[len++] = ';'; } else { /* we did not find an entity for this char. * check for its validity, if its valid pass it unchanged */ if (flags & ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS) { if (CHARSET_UNICODE_COMPAT(charset)) { if (!unicode_cp_is_allowed(this_char, doctype)) { mbsequence = replacement; mbseqlen = replacement_len; } } else if (to_uni_table) { if (!all) /* otherwise we already did this */ map_to_unicode(this_char, to_uni_table, &this_char); if (!unicode_cp_is_allowed(this_char, doctype)) { mbsequence = replacement; mbseqlen = replacement_len; } } else { /* not a unicode code point, unless, coincidentally, it's in * the 0x20..0x7D range (except 0x5C in sjis). We know nothing * about other code points, because we have no tables. Since * Unicode code points in that range are not disallowed in any * document type, we could do nothing. However, conversion * tables frequently map 0x00-0x1F to the respective C0 code * points. Let's play it safe and admit that's the case */ if (this_char <= 0x7D && !unicode_cp_is_allowed(this_char, doctype)) { mbsequence = replacement; mbseqlen = replacement_len; } } } pass_char_through: if (mbseqlen > 1) { memcpy(replaced + len, mbsequence, mbseqlen); len += mbseqlen; } else { replaced[len++] = mbsequence[0]; } } } else { /* this_char == '&' */ if (double_encode) { encode_amp: memcpy(&replaced[len], "&amp;", sizeof("&amp;") - 1); len += sizeof("&amp;") - 1; } else { /* no double encode */ /* check if entity is valid */ size_t ent_len; /* not counting & or ; */ /* peek at next char */ if (old[cursor] == '#') { /* numeric entity */ unsigned code_point; int valid; char *pos = (char*)&old[cursor+1]; valid = process_numeric_entity((const char **)&pos, &code_point); if (valid == FAILURE) goto encode_amp; if (flags & ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS) { if (!numeric_entity_is_allowed(code_point, doctype)) goto encode_amp; } ent_len = pos - (char*)&old[cursor]; } else { /* named entity */ /* check for vality of named entity */ const char *start = &old[cursor], *next = start; unsigned dummy1, dummy2; if (process_named_entity_html(&next, &start, &ent_len) == FAILURE) goto encode_amp; if (resolve_named_entity_html(start, ent_len, inv_map, &dummy1, &dummy2) == FAILURE) { if (!(doctype == ENT_HTML_DOC_XHTML && ent_len == 4 && start[0] == 'a' && start[1] == 'p' && start[2] == 'o' && start[3] == 's')) { /* uses html4 inv_map, which doesn't include apos;. This is a * hack to support it */ goto encode_amp; } } } /* checks passed; copy entity to result */ /* entity size is unbounded, we may need more memory */ /* at this point maxlen - len >= 40 */ if (maxlen - len < ent_len + 2 /* & and ; */) { /* ent_len < oldlen, which is certainly <= SIZE_MAX/2 */ replaced = safe_erealloc(replaced, maxlen, 1, ent_len + 128 + 1); maxlen += ent_len + 128; } replaced[len++] = '&'; memcpy(&replaced[len], &old[cursor], ent_len); len += ent_len; replaced[len++] = ';'; cursor += ent_len + 1; } } } replaced[len] = '\0'; *newlen = len; return replaced; } /* }}} */ /* {{{ php_html_entities */ static void php_html_entities(INTERNAL_FUNCTION_PARAMETERS, int all) { char *str, *hint_charset = NULL; int str_len, hint_charset_len = 0; size_t new_len; long flags = ENT_COMPAT; char *replaced; zend_bool double_encode = 1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!b", &str, &str_len, &flags, &hint_charset, &hint_charset_len, &double_encode) == FAILURE) { return; } replaced = php_escape_html_entities_ex(str, str_len, &new_len, all, (int) flags, hint_charset, double_encode TSRMLS_CC); RETVAL_STRINGL(replaced, (int)new_len, 0); } /* }}} */ #define HTML_SPECIALCHARS 0 #define HTML_ENTITIES 1 /* {{{ register_html_constants */ void register_html_constants(INIT_FUNC_ARGS) { REGISTER_LONG_CONSTANT("HTML_SPECIALCHARS", HTML_SPECIALCHARS, CONST_PERSISTENT|CONST_CS); REGISTER_LONG_CONSTANT("HTML_ENTITIES", HTML_ENTITIES, CONST_PERSISTENT|CONST_CS); REGISTER_LONG_CONSTANT("ENT_COMPAT", ENT_COMPAT, CONST_PERSISTENT|CONST_CS); REGISTER_LONG_CONSTANT("ENT_QUOTES", ENT_QUOTES, CONST_PERSISTENT|CONST_CS); REGISTER_LONG_CONSTANT("ENT_NOQUOTES", ENT_NOQUOTES, CONST_PERSISTENT|CONST_CS); REGISTER_LONG_CONSTANT("ENT_IGNORE", ENT_IGNORE, CONST_PERSISTENT|CONST_CS); REGISTER_LONG_CONSTANT("ENT_SUBSTITUTE", ENT_SUBSTITUTE, CONST_PERSISTENT|CONST_CS); REGISTER_LONG_CONSTANT("ENT_DISALLOWED", ENT_DISALLOWED, CONST_PERSISTENT|CONST_CS); REGISTER_LONG_CONSTANT("ENT_HTML401", ENT_HTML401, CONST_PERSISTENT|CONST_CS); REGISTER_LONG_CONSTANT("ENT_XML1", ENT_XML1, CONST_PERSISTENT|CONST_CS); REGISTER_LONG_CONSTANT("ENT_XHTML", ENT_XHTML, CONST_PERSISTENT|CONST_CS); REGISTER_LONG_CONSTANT("ENT_HTML5", ENT_HTML5, CONST_PERSISTENT|CONST_CS); } /* }}} */ /* {{{ proto string htmlspecialchars(string string [, int quote_style[, string charset[, bool double_encode]]]) Convert special characters to HTML entities */ PHP_FUNCTION(htmlspecialchars) { php_html_entities(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto string htmlspecialchars_decode(string string [, int quote_style]) Convert special HTML entities back to characters */ PHP_FUNCTION(htmlspecialchars_decode) { char *str; int str_len; size_t new_len = 0; long quote_style = ENT_COMPAT; char *replaced; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &str, &str_len, &quote_style) == FAILURE) { return; } replaced = php_unescape_html_entities(str, str_len, &new_len, 0 /*!all*/, quote_style, NULL TSRMLS_CC); if (replaced) { RETURN_STRINGL(replaced, (int)new_len, 0); } RETURN_FALSE; } /* }}} */ /* {{{ proto string html_entity_decode(string string [, int quote_style][, string charset]) Convert all HTML entities to their applicable characters */ PHP_FUNCTION(html_entity_decode) { char *str, *hint_charset = NULL; int str_len, hint_charset_len = 0; size_t new_len = 0; long quote_style = ENT_COMPAT; char *replaced; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls", &str, &str_len, &quote_style, &hint_charset, &hint_charset_len) == FAILURE) { return; } replaced = php_unescape_html_entities(str, str_len, &new_len, 1 /*all*/, quote_style, hint_charset TSRMLS_CC); if (replaced) { RETURN_STRINGL(replaced, (int)new_len, 0); } RETURN_FALSE; } /* }}} */ /* {{{ proto string htmlentities(string string [, int quote_style[, string charset[, bool double_encode]]]) Convert all applicable characters to HTML entities */ PHP_FUNCTION(htmlentities) { php_html_entities(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ write_s3row_data */ static inline void write_s3row_data( const entity_stage3_row *r, unsigned orig_cp, enum entity_charset charset, zval *arr) { char key[9] = ""; /* two unicode code points in UTF-8 */ char entity[LONGEST_ENTITY_LENGTH + 2] = {'&'}; size_t written_k1; written_k1 = write_octet_sequence(key, charset, orig_cp); if (!r->ambiguous) { size_t l = r->data.ent.entity_len; memcpy(&entity[1], r->data.ent.entity, l); entity[l + 1] = ';'; add_assoc_stringl_ex(arr, key, written_k1 + 1, entity, l + 2, 1); } else { unsigned i, num_entries; const entity_multicodepoint_row *mcpr = r->data.multicodepoint_table; if (mcpr[0].leading_entry.default_entity != NULL) { size_t l = mcpr[0].leading_entry.default_entity_len; memcpy(&entity[1], mcpr[0].leading_entry.default_entity, l); entity[l + 1] = ';'; add_assoc_stringl_ex(arr, key, written_k1 + 1, entity, l + 2, 1); } num_entries = mcpr[0].leading_entry.size; for (i = 1; i <= num_entries; i++) { size_t l, written_k2; unsigned uni_cp, spe_cp; uni_cp = mcpr[i].normal_entry.second_cp; l = mcpr[i].normal_entry.entity_len; if (!CHARSET_UNICODE_COMPAT(charset)) { if (map_from_unicode(uni_cp, charset, &spe_cp) == FAILURE) continue; /* non representable in this charset */ } else { spe_cp = uni_cp; } written_k2 = write_octet_sequence(&key[written_k1], charset, spe_cp); memcpy(&entity[1], mcpr[i].normal_entry.entity, l); entity[l + 1] = ';'; entity[l + 1] = '\0'; add_assoc_stringl_ex(arr, key, written_k1 + written_k2 + 1, entity, l + 1, 1); } } } /* }}} */ /* {{{ proto array get_html_translation_table([int table [, int flags [, string charset_hint]]]) Returns the internal translation table used by htmlspecialchars and htmlentities */ PHP_FUNCTION(get_html_translation_table) { long all = HTML_SPECIALCHARS, flags = ENT_COMPAT; int doctype; entity_table_opt entity_table; const enc_to_uni *to_uni_table; char *charset_hint = NULL; int charset_hint_len; enum entity_charset charset; /* in this function we have to jump through some loops because we're * getting the translated table from data structures that are optimized for * random access, not traversal */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lls", &all, &flags, &charset_hint, &charset_hint_len) == FAILURE) { return; } charset = determine_charset(charset_hint TSRMLS_CC); doctype = flags & ENT_HTML_DOC_TYPE_MASK; LIMIT_ALL(all, doctype, charset); array_init(return_value); entity_table = determine_entity_table(all, doctype); if (all && !CHARSET_UNICODE_COMPAT(charset)) { to_uni_table = enc_to_uni_index[charset]; } if (all) { /* HTML_ENTITIES (actually, any non-zero value for 1st param) */ const entity_stage1_row *ms_table = entity_table.ms_table; if (CHARSET_UNICODE_COMPAT(charset)) { unsigned i, j, k, max_i, max_j, max_k; /* no mapping to unicode required */ if (CHARSET_SINGLE_BYTE(charset)) { max_i = 1; max_j = 1; max_k = 64; } else { max_i = 0x1E; max_j = 64; max_k = 64; } for (i = 0; i < max_i; i++) { if (ms_table[i] == empty_stage2_table) continue; for (j = 0; j < max_j; j++) { if (ms_table[i][j] == empty_stage3_table) continue; for (k = 0; k < max_k; k++) { const entity_stage3_row *r = &ms_table[i][j][k]; unsigned code; if (r->data.ent.entity == NULL) continue; code = ENT_CODE_POINT_FROM_STAGES(i, j, k); if (((code == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) || (code == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE)))) continue; write_s3row_data(r, code, charset, return_value); } } } } else { /* we have to iterate through the set of code points for this * encoding and map them to unicode code points */ unsigned i; for (i = 0; i <= 0xFF; i++) { const entity_stage3_row *r; unsigned uni_cp; /* can be done before mapping, they're invariant */ if (((i == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) || (i == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE)))) continue; map_to_unicode(i, to_uni_table, &uni_cp); r = &ms_table[ENT_STAGE1_INDEX(uni_cp)][ENT_STAGE2_INDEX(uni_cp)][ENT_STAGE3_INDEX(uni_cp)]; if (r->data.ent.entity == NULL) continue; write_s3row_data(r, i, charset, return_value); } } } else { /* we could use sizeof(stage3_table_be_apos_00000) as well */ unsigned j, numelems = sizeof(stage3_table_be_noapos_00000) / sizeof(*stage3_table_be_noapos_00000); for (j = 0; j < numelems; j++) { const entity_stage3_row *r = &entity_table.table[j]; if (r->data.ent.entity == NULL) continue; if (((j == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) || (j == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE)))) continue; /* charset is indifferent, used cs_8859_1 for efficiency */ write_s3row_data(r, j, cs_8859_1, return_value); } } } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2012 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Rasmus Lerdorf <[email protected]> | | Jaakko Hyvätti <[email protected]> | | Wez Furlong <[email protected]> | | Gustavo Lopes <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ /* * HTML entity resources: * * http://www.unicode.org/Public/MAPPINGS/OBSOLETE/UNI2SGML.TXT * * XHTML 1.0 DTD * http://www.w3.org/TR/2002/REC-xhtml1-20020801/dtds.html#h-A2 * * From HTML 4.01 strict DTD: * http://www.w3.org/TR/html4/HTMLlat1.ent * http://www.w3.org/TR/html4/HTMLsymbol.ent * http://www.w3.org/TR/html4/HTMLspecial.ent * * HTML 5: * http://dev.w3.org/html5/spec/Overview.html#named-character-references */ #include "php.h" #if PHP_WIN32 #include "config.w32.h" #else #include <php_config.h> #endif #include "php_standard.h" #include "php_string.h" #include "SAPI.h" #if HAVE_LOCALE_H #include <locale.h> #endif #if HAVE_LANGINFO_H #include <langinfo.h> #endif #include <zend_hash.h> #include "html_tables.h" /* Macro for disabling flag of translation of non-basic entities where this isn't supported. * Not appropriate for html_entity_decode/htmlspecialchars_decode */ #define LIMIT_ALL(all, doctype, charset) do { \ (all) = (all) && !CHARSET_PARTIAL_SUPPORT((charset)) && ((doctype) != ENT_HTML_DOC_XML1); \ } while (0) #define MB_FAILURE(pos, advance) do { \ *cursor = pos + (advance); \ *status = FAILURE; \ return 0; \ } while (0) #define CHECK_LEN(pos, chars_need) ((str_len - (pos)) >= (chars_need)) /* valid as single byte character or leading byte */ #define utf8_lead(c) ((c) < 0x80 || ((c) >= 0xC2 && (c) <= 0xF4)) /* whether it's actually valid depends on other stuff; * this macro cannot check for non-shortest forms, surrogates or * code points above 0x10FFFF */ #define utf8_trail(c) ((c) >= 0x80 && (c) <= 0xBF) #define gb2312_lead(c) ((c) != 0x8E && (c) != 0x8F && (c) != 0xA0 && (c) != 0xFF) #define gb2312_trail(c) ((c) >= 0xA1 && (c) <= 0xFE) #define sjis_lead(c) ((c) != 0x80 && (c) != 0xA0 && (c) < 0xFD) #define sjis_trail(c) ((c) >= 0x40 && (c) != 0x7F && (c) < 0xFD) /* {{{ get_next_char */ static inline unsigned int get_next_char( enum entity_charset charset, const unsigned char *str, size_t str_len, size_t *cursor, int *status) { size_t pos = *cursor; unsigned int this_char = 0; *status = SUCCESS; assert(pos <= str_len); if (!CHECK_LEN(pos, 1)) MB_FAILURE(pos, 1); switch (charset) { case cs_utf_8: { /* We'll follow strategy 2. from section 3.6.1 of UTR #36: * "In a reported illegal byte sequence, do not include any * non-initial byte that encodes a valid character or is a leading * byte for a valid sequence." */ unsigned char c; c = str[pos]; if (c < 0x80) { this_char = c; pos++; } else if (c < 0xc2) { MB_FAILURE(pos, 1); } else if (c < 0xe0) { if (!CHECK_LEN(pos, 2)) MB_FAILURE(pos, 1); if (!utf8_trail(str[pos + 1])) { MB_FAILURE(pos, utf8_lead(str[pos + 1]) ? 1 : 2); } this_char = ((c & 0x1f) << 6) | (str[pos + 1] & 0x3f); if (this_char < 0x80) { /* non-shortest form */ MB_FAILURE(pos, 2); } pos += 2; } else if (c < 0xf0) { size_t avail = str_len - pos; if (avail < 3 || !utf8_trail(str[pos + 1]) || !utf8_trail(str[pos + 2])) { if (avail < 2 || utf8_lead(str[pos + 1])) MB_FAILURE(pos, 1); else if (avail < 3 || utf8_lead(str[pos + 2])) MB_FAILURE(pos, 2); else MB_FAILURE(pos, 3); } this_char = ((c & 0x0f) << 12) | ((str[pos + 1] & 0x3f) << 6) | (str[pos + 2] & 0x3f); if (this_char < 0x800) { /* non-shortest form */ MB_FAILURE(pos, 3); } else if (this_char >= 0xd800 && this_char <= 0xdfff) { /* surrogate */ MB_FAILURE(pos, 3); } pos += 3; } else if (c < 0xf5) { size_t avail = str_len - pos; if (avail < 4 || !utf8_trail(str[pos + 1]) || !utf8_trail(str[pos + 2]) || !utf8_trail(str[pos + 3])) { if (avail < 2 || utf8_lead(str[pos + 1])) MB_FAILURE(pos, 1); else if (avail < 3 || utf8_lead(str[pos + 2])) MB_FAILURE(pos, 2); else if (avail < 4 || utf8_lead(str[pos + 3])) MB_FAILURE(pos, 3); else MB_FAILURE(pos, 4); } this_char = ((c & 0x07) << 18) | ((str[pos + 1] & 0x3f) << 12) | ((str[pos + 2] & 0x3f) << 6) | (str[pos + 3] & 0x3f); if (this_char < 0x10000 || this_char > 0x10FFFF) { /* non-shortest form or outside range */ MB_FAILURE(pos, 4); } pos += 4; } else { MB_FAILURE(pos, 1); } } break; case cs_big5: /* reference http://demo.icu-project.org/icu-bin/convexp?conv=big5 */ { unsigned char c = str[pos]; if (c >= 0x81 && c <= 0xFE) { unsigned char next; if (!CHECK_LEN(pos, 2)) MB_FAILURE(pos, 1); next = str[pos + 1]; if ((next >= 0x40 && next <= 0x7E) || (next >= 0xA1 && next <= 0xFE)) { this_char = (c << 8) | next; } else { MB_FAILURE(pos, 1); } pos += 2; } else { this_char = c; pos += 1; } } break; case cs_big5hkscs: { unsigned char c = str[pos]; if (c >= 0x81 && c <= 0xFE) { unsigned char next; if (!CHECK_LEN(pos, 2)) MB_FAILURE(pos, 1); next = str[pos + 1]; if ((next >= 0x40 && next <= 0x7E) || (next >= 0xA1 && next <= 0xFE)) { this_char = (c << 8) | next; } else if (next != 0x80 && next != 0xFF) { MB_FAILURE(pos, 1); } else { MB_FAILURE(pos, 2); } pos += 2; } else { this_char = c; pos += 1; } } break; case cs_gb2312: /* EUC-CN */ { unsigned char c = str[pos]; if (c >= 0xA1 && c <= 0xFE) { unsigned char next; if (!CHECK_LEN(pos, 2)) MB_FAILURE(pos, 1); next = str[pos + 1]; if (gb2312_trail(next)) { this_char = (c << 8) | next; } else if (gb2312_lead(next)) { MB_FAILURE(pos, 1); } else { MB_FAILURE(pos, 2); } pos += 2; } else if (gb2312_lead(c)) { this_char = c; pos += 1; } else { MB_FAILURE(pos, 1); } } break; case cs_sjis: { unsigned char c = str[pos]; if ((c >= 0x81 && c <= 0x9F) || (c >= 0xE0 && c <= 0xFC)) { unsigned char next; if (!CHECK_LEN(pos, 2)) MB_FAILURE(pos, 1); next = str[pos + 1]; if (sjis_trail(next)) { this_char = (c << 8) | next; } else if (sjis_lead(next)) { MB_FAILURE(pos, 1); } else { MB_FAILURE(pos, 2); } pos += 2; } else if (c < 0x80 || (c >= 0xA1 && c <= 0xDF)) { this_char = c; pos += 1; } else { MB_FAILURE(pos, 1); } } break; case cs_eucjp: { unsigned char c = str[pos]; if (c >= 0xA1 && c <= 0xFE) { unsigned next; if (!CHECK_LEN(pos, 2)) MB_FAILURE(pos, 1); next = str[pos + 1]; if (next >= 0xA1 && next <= 0xFE) { /* this a jis kanji char */ this_char = (c << 8) | next; } else { MB_FAILURE(pos, (next != 0xA0 && next != 0xFF) ? 1 : 2); } pos += 2; } else if (c == 0x8E) { unsigned next; if (!CHECK_LEN(pos, 2)) MB_FAILURE(pos, 1); next = str[pos + 1]; if (next >= 0xA1 && next <= 0xDF) { /* JIS X 0201 kana */ this_char = (c << 8) | next; } else { MB_FAILURE(pos, (next != 0xA0 && next != 0xFF) ? 1 : 2); } pos += 2; } else if (c == 0x8F) { size_t avail = str_len - pos; if (avail < 3 || !(str[pos + 1] >= 0xA1 && str[pos + 1] <= 0xFE) || !(str[pos + 2] >= 0xA1 && str[pos + 2] <= 0xFE)) { if (avail < 2 || (str[pos + 1] != 0xA0 && str[pos + 1] != 0xFF)) MB_FAILURE(pos, 1); else if (avail < 3 || (str[pos + 2] != 0xA0 && str[pos + 2] != 0xFF)) MB_FAILURE(pos, 2); else MB_FAILURE(pos, 3); } else { /* JIS X 0212 hojo-kanji */ this_char = (c << 16) | (str[pos + 1] << 8) | str[pos + 2]; } pos += 3; } else if (c != 0xA0 && c != 0xFF) { /* character encoded in 1 code unit */ this_char = c; pos += 1; } else { MB_FAILURE(pos, 1); } } break; default: /* single-byte charsets */ this_char = str[pos++]; break; } *cursor = pos; return this_char; } /* }}} */ /* {{{ php_next_utf8_char * Public interface for get_next_char used with UTF-8 */ PHPAPI unsigned int php_next_utf8_char( const unsigned char *str, size_t str_len, size_t *cursor, int *status) { return get_next_char(cs_utf_8, str, str_len, cursor, status); } /* }}} */ /* {{{ entity_charset determine_charset * returns the charset identifier based on current locale or a hint. * defaults to UTF-8 */ static enum entity_charset determine_charset(char *charset_hint TSRMLS_DC) { int i; enum entity_charset charset = cs_utf_8; int len = 0; const zend_encoding *zenc; /* Default is now UTF-8 */ if (charset_hint == NULL) return cs_utf_8; if ((len = strlen(charset_hint)) != 0) { goto det_charset; } zenc = zend_multibyte_get_internal_encoding(TSRMLS_C); if (zenc != NULL) { charset_hint = (char *)zend_multibyte_get_encoding_name(zenc); if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) { if ((len == 4) /* sizeof (none|auto|pass) */ && (!memcmp("pass", charset_hint, 4) || !memcmp("auto", charset_hint, 4) || !memcmp("auto", charset_hint, 4))) { charset_hint = NULL; len = 0; } else { goto det_charset; } } } charset_hint = SG(default_charset); if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) { goto det_charset; } /* try to detect the charset for the locale */ #if HAVE_NL_LANGINFO && HAVE_LOCALE_H && defined(CODESET) charset_hint = nl_langinfo(CODESET); if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) { goto det_charset; } #endif #if HAVE_LOCALE_H /* try to figure out the charset from the locale */ { char *localename; char *dot, *at; /* lang[_territory][.codeset][@modifier] */ localename = setlocale(LC_CTYPE, NULL); dot = strchr(localename, '.'); if (dot) { dot++; /* locale specifies a codeset */ at = strchr(dot, '@'); if (at) len = at - dot; else len = strlen(dot); charset_hint = dot; } else { /* no explicit name; see if the name itself * is the charset */ charset_hint = localename; len = strlen(charset_hint); } } #endif det_charset: if (charset_hint) { int found = 0; /* now walk the charset map and look for the codeset */ for (i = 0; charset_map[i].codeset; i++) { if (len == strlen(charset_map[i].codeset) && strncasecmp(charset_hint, charset_map[i].codeset, len) == 0) { charset = charset_map[i].charset; found = 1; break; } } if (!found) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "charset `%s' not supported, assuming utf-8", charset_hint); } } return charset; } /* }}} */ /* {{{ php_utf32_utf8 */ static inline size_t php_utf32_utf8(unsigned char *buf, unsigned k) { size_t retval = 0; /* assert(0x0 <= k <= 0x10FFFF); */ if (k < 0x80) { buf[0] = k; retval = 1; } else if (k < 0x800) { buf[0] = 0xc0 | (k >> 6); buf[1] = 0x80 | (k & 0x3f); retval = 2; } else if (k < 0x10000) { buf[0] = 0xe0 | (k >> 12); buf[1] = 0x80 | ((k >> 6) & 0x3f); buf[2] = 0x80 | (k & 0x3f); retval = 3; } else { buf[0] = 0xf0 | (k >> 18); buf[1] = 0x80 | ((k >> 12) & 0x3f); buf[2] = 0x80 | ((k >> 6) & 0x3f); buf[3] = 0x80 | (k & 0x3f); retval = 4; } /* UTF-8 has been restricted to max 4 bytes since RFC 3629 */ return retval; } /* }}} */ /* {{{ php_mb2_int_to_char * Convert back big endian int representation of sequence of one or two 8-bit code units. */ static inline size_t php_mb2_int_to_char(unsigned char *buf, unsigned k) { assert(k <= 0xFFFFU); /* one or two bytes */ if (k <= 0xFFU) { /* 1 */ buf[0] = k; return 1U; } else { /* 2 */ buf[0] = k >> 8; buf[1] = k & 0xFFU; return 2U; } } /* }}} */ /* {{{ php_mb3_int_to_char * Convert back big endian int representation of sequence of one to three 8-bit code units. * For EUC-JP. */ static inline size_t php_mb3_int_to_char(unsigned char *buf, unsigned k) { assert(k <= 0xFFFFFFU); /* one to three bytes */ if (k <= 0xFFU) { /* 1 */ buf[0] = k; return 1U; } else if (k <= 0xFFFFU) { /* 2 */ buf[0] = k >> 8; buf[1] = k & 0xFFU; return 2U; } else { buf[0] = k >> 16; buf[1] = (k >> 8) & 0xFFU; buf[2] = k & 0xFFU; return 3U; } } /* }}} */ /* {{{ unimap_bsearc_cmp * Binary search of unicode code points in unicode <--> charset mapping. * Returns the code point in the target charset (whose mapping table was given) or 0 if * the unicode code point is not in the table. */ static inline unsigned char unimap_bsearch(const uni_to_enc *table, unsigned code_key_a, size_t num) { const uni_to_enc *l = table, *h = &table[num-1], *m; unsigned short code_key; /* we have no mappings outside the BMP */ if (code_key_a > 0xFFFFU) return 0; code_key = (unsigned short) code_key_a; while (l <= h) { m = l + (h - l) / 2; if (code_key < m->un_code_point) h = m - 1; else if (code_key > m->un_code_point) l = m + 1; else return m->cs_code; } return 0; } /* }}} */ /* {{{ map_from_unicode */ static inline int map_from_unicode(unsigned code, enum entity_charset charset, unsigned *res) { unsigned char found; const uni_to_enc *table; size_t table_size; switch (charset) { case cs_8859_1: /* identity mapping of code points to unicode */ if (code > 0xFF) { return FAILURE; } *res = code; break; case cs_8859_5: if (code <= 0xA0 || code == 0xAD /* soft hyphen */) { *res = code; } else if (code == 0x2116) { *res = 0xF0; /* numero sign */ } else if (code == 0xA7) { *res = 0xFD; /* section sign */ } else if (code >= 0x0401 && code <= 0x044F) { if (code == 0x040D || code == 0x0450 || code == 0x045D) return FAILURE; *res = code - 0x360; } else { return FAILURE; } break; case cs_8859_15: if (code < 0xA4 || (code > 0xBE && code <= 0xFF)) { *res = code; } else { /* between A4 and 0xBE */ found = unimap_bsearch(unimap_iso885915, code, sizeof(unimap_iso885915) / sizeof(*unimap_iso885915)); if (found) *res = found; else return FAILURE; } break; case cs_cp1252: if (code <= 0x7F || (code >= 0xA0 && code <= 0xFF)) { *res = code; } else { found = unimap_bsearch(unimap_win1252, code, sizeof(unimap_win1252) / sizeof(*unimap_win1252)); if (found) *res = found; else return FAILURE; } break; case cs_macroman: if (code == 0x7F) return FAILURE; table = unimap_macroman; table_size = sizeof(unimap_macroman) / sizeof(*unimap_macroman); goto table_over_7F; case cs_cp1251: table = unimap_win1251; table_size = sizeof(unimap_win1251) / sizeof(*unimap_win1251); goto table_over_7F; case cs_koi8r: table = unimap_koi8r; table_size = sizeof(unimap_koi8r) / sizeof(*unimap_koi8r); goto table_over_7F; case cs_cp866: table = unimap_cp866; table_size = sizeof(unimap_cp866) / sizeof(*unimap_cp866); table_over_7F: if (code <= 0x7F) { *res = code; } else { found = unimap_bsearch(table, code, table_size); if (found) *res = found; else return FAILURE; } break; /* from here on, only map the possible characters in the ASCII range. * to improve support here, it's a matter of building the unicode mappings. * See <http://www.unicode.org/Public/6.0.0/ucd/Unihan.zip> */ case cs_sjis: case cs_eucjp: /* we interpret 0x5C as the Yen symbol. This is not universal. * See <http://www.w3.org/Submission/japanese-xml/#ambiguity_of_yen> */ if (code >= 0x20 && code <= 0x7D) { if (code == 0x5C) return FAILURE; *res = code; } else { return FAILURE; } break; case cs_big5: case cs_big5hkscs: case cs_gb2312: if (code >= 0x20 && code <= 0x7D) { *res = code; } else { return FAILURE; } break; default: return FAILURE; } return SUCCESS; } /* }}} */ /* {{{ */ static inline void map_to_unicode(unsigned code, const enc_to_uni *table, unsigned *res) { /* only single byte encodings are currently supported; assumed code <= 0xFF */ *res = table->inner[ENT_ENC_TO_UNI_STAGE1(code)]->uni_cp[ENT_ENC_TO_UNI_STAGE2(code)]; } /* }}} */ /* {{{ unicode_cp_is_allowed */ static inline int unicode_cp_is_allowed(unsigned uni_cp, int document_type) { /* XML 1.0 HTML 4.01 HTML 5 * 0x09..0x0A 0x09..0x0A 0x09..0x0A * 0x0D 0x0D 0x0C..0x0D * 0x0020..0xD7FF 0x20..0x7E 0x20..0x7E * 0x00A0..0xD7FF 0x00A0..0xD7FF * 0xE000..0xFFFD 0xE000..0x10FFFF 0xE000..0xFDCF * 0x010000..0x10FFFF 0xFDF0..0x10FFFF (*) * * (*) exclude code points where ((code & 0xFFFF) >= 0xFFFE) * * References: * XML 1.0: <http://www.w3.org/TR/REC-xml/#charsets> * HTML 4.01: <http://www.w3.org/TR/1999/PR-html40-19990824/sgml/sgmldecl.html> * HTML 5: <http://dev.w3.org/html5/spec/Overview.html#preprocessing-the-input-stream> * * Not sure this is the relevant part for HTML 5, though. I opted to * disallow the characters that would result in a parse error when * preprocessing of the input stream. See also section 8.1.3. * * It's unclear if XHTML 1.0 allows C1 characters. I'll opt to apply to * XHTML 1.0 the same rules as for XML 1.0. * See <http://cmsmcq.com/2007/C1.xml>. */ switch (document_type) { case ENT_HTML_DOC_HTML401: return (uni_cp >= 0x20 && uni_cp <= 0x7E) || (uni_cp == 0x0A || uni_cp == 0x09 || uni_cp == 0x0D) || (uni_cp >= 0xA0 && uni_cp <= 0xD7FF) || (uni_cp >= 0xE000 && uni_cp <= 0x10FFFF); case ENT_HTML_DOC_HTML5: return (uni_cp >= 0x20 && uni_cp <= 0x7E) || (uni_cp >= 0x09 && uni_cp <= 0x0D && uni_cp != 0x0B) || /* form feed U+0C allowed */ (uni_cp >= 0xA0 && uni_cp <= 0xD7FF) || (uni_cp >= 0xE000 && uni_cp <= 0x10FFFF && ((uni_cp & 0xFFFF) < 0xFFFE) && /* last two of each plane (nonchars) disallowed */ (uni_cp < 0xFDD0 || uni_cp > 0xFDEF)); /* U+FDD0-U+FDEF (nonchars) disallowed */ case ENT_HTML_DOC_XHTML: case ENT_HTML_DOC_XML1: return (uni_cp >= 0x20 && uni_cp <= 0xD7FF) || (uni_cp == 0x0A || uni_cp == 0x09 || uni_cp == 0x0D) || (uni_cp >= 0xE000 && uni_cp <= 0x10FFFF && uni_cp != 0xFFFE && uni_cp != 0xFFFF); default: return 1; } } /* }}} */ /* {{{ unicode_cp_is_allowed */ static inline int numeric_entity_is_allowed(unsigned uni_cp, int document_type) { /* less restrictive than unicode_cp_is_allowed */ switch (document_type) { case ENT_HTML_DOC_HTML401: /* all non-SGML characters (those marked with UNUSED in DESCSET) should be * representable with numeric entities */ return uni_cp <= 0x10FFFF; case ENT_HTML_DOC_HTML5: /* 8.1.4. The numeric character reference forms described above are allowed to * reference any Unicode code point other than U+0000, U+000D, permanently * undefined Unicode characters (noncharacters), and control characters other * than space characters (U+0009, U+000A, U+000C and U+000D) */ /* seems to allow surrogate characters, then */ return (uni_cp >= 0x20 && uni_cp <= 0x7E) || (uni_cp >= 0x09 && uni_cp <= 0x0C && uni_cp != 0x0B) || /* form feed U+0C allowed, but not U+0D */ (uni_cp >= 0xA0 && uni_cp <= 0x10FFFF && ((uni_cp & 0xFFFF) < 0xFFFE) && /* last two of each plane (nonchars) disallowed */ (uni_cp < 0xFDD0 || uni_cp > 0xFDEF)); /* U+FDD0-U+FDEF (nonchars) disallowed */ case ENT_HTML_DOC_XHTML: case ENT_HTML_DOC_XML1: /* OTOH, XML 1.0 requires "character references to match the production for Char * See <http://www.w3.org/TR/REC-xml/#NT-CharRef> */ return unicode_cp_is_allowed(uni_cp, document_type); default: return 1; } } /* }}} */ /* {{{ process_numeric_entity * Auxiliary function to traverse_for_entities. * On input, *buf should point to the first character after # and on output, it's the last * byte read, no matter if there was success or insuccess. */ static inline int process_numeric_entity(const char **buf, unsigned *code_point) { long code_l; int hexadecimal = (**buf == 'x' || **buf == 'X'); /* TODO: XML apparently disallows "X" */ char *endptr; if (hexadecimal && (**buf != '\0')) (*buf)++; /* strtol allows whitespace and other stuff in the beginning * we're not interested */ if ((hexadecimal && !isxdigit(**buf)) || (!hexadecimal && !isdigit(**buf))) { return FAILURE; } code_l = strtol(*buf, &endptr, hexadecimal ? 16 : 10); /* we're guaranteed there were valid digits, so *endptr > buf */ *buf = endptr; if (**buf != ';') return FAILURE; /* many more are invalid, but that depends on whether it's HTML * (and which version) or XML. */ if (code_l > 0x10FFFFL) return FAILURE; if (code_point != NULL) *code_point = (unsigned)code_l; return SUCCESS; } /* }}} */ /* {{{ process_named_entity */ static inline int process_named_entity_html(const char **buf, const char **start, size_t *length) { *start = *buf; /* "&" is represented by a 0x26 in all supported encodings. That means * the byte after represents a character or is the leading byte of an * sequence of 8-bit code units. If in the ranges below, it represents * necessarily a alpha character because none of the supported encodings * has an overlap with ASCII in the leading byte (only on the second one) */ while ((**buf >= 'a' && **buf <= 'z') || (**buf >= 'A' && **buf <= 'Z') || (**buf >= '0' && **buf <= '9')) { (*buf)++; } if (**buf != ';') return FAILURE; /* cast to size_t OK as the quantity is always non-negative */ *length = *buf - *start; if (*length == 0) return FAILURE; return SUCCESS; } /* }}} */ /* {{{ resolve_named_entity_html */ static inline int resolve_named_entity_html(const char *start, size_t length, const entity_ht *ht, unsigned *uni_cp1, unsigned *uni_cp2) { const entity_cp_map *s; ulong hash = zend_inline_hash_func(start, length); s = ht->buckets[hash % ht->num_elems]; while (s->entity) { if (s->entity_len == length) { if (memcmp(start, s->entity, length) == 0) { *uni_cp1 = s->codepoint1; *uni_cp2 = s->codepoint2; return SUCCESS; } } s++; } return FAILURE; } /* }}} */ static inline size_t write_octet_sequence(unsigned char *buf, enum entity_charset charset, unsigned code) { /* code is not necessarily a unicode code point */ switch (charset) { case cs_utf_8: return php_utf32_utf8(buf, code); case cs_8859_1: case cs_cp1252: case cs_8859_15: case cs_koi8r: case cs_cp1251: case cs_8859_5: case cs_cp866: case cs_macroman: /* single byte stuff */ *buf = code; return 1; case cs_big5: case cs_big5hkscs: case cs_sjis: case cs_gb2312: /* we don't have complete unicode mappings for these yet in entity_decode, * and we opt to pass through the octet sequences for these in htmlentities * instead of converting to an int and then converting back. */ #if 0 return php_mb2_int_to_char(buf, code); #else #ifdef ZEND_DEBUG assert(code <= 0xFFU); #endif *buf = code; return 1; #endif case cs_eucjp: #if 0 /* idem */ return php_mb2_int_to_char(buf, code); #else #ifdef ZEND_DEBUG assert(code <= 0xFFU); #endif *buf = code; return 1; #endif default: assert(0); return 0; } } /* {{{ traverse_for_entities * Auxiliary function to php_unescape_html_entities(). * - The argument "all" determines if all numeric entities are decode or only those * that correspond to quotes (depending on quote_style). */ /* maximum expansion (factor 1.2) for HTML 5 with &nGt; and &nLt; */ /* +2 is 1 because of rest (probably unnecessary), 1 because of terminating 0 */ #define TRAVERSE_FOR_ENTITIES_EXPAND_SIZE(oldlen) ((oldlen) + (oldlen) / 5 + 2) static void traverse_for_entities( const char *old, size_t oldlen, char *ret, /* should have allocated TRAVERSE_FOR_ENTITIES_EXPAND_SIZE(olden) */ size_t *retlen, int all, int flags, const entity_ht *inv_map, enum entity_charset charset) { const char *p, *lim; char *q; int doctype = flags & ENT_HTML_DOC_TYPE_MASK; lim = old + oldlen; /* terminator address */ assert(*lim == '\0'); for (p = old, q = ret; p < lim;) { unsigned code, code2 = 0; const char *next = NULL; /* when set, next > p, otherwise possible inf loop */ /* Shift JIS, Big5 and HKSCS use multi-byte encodings where an * ASCII range byte can be part of a multi-byte sequence. * However, they start at 0x40, therefore if we find a 0x26 byte, * we're sure it represents the '&' character. */ /* assumes there are no single-char entities */ if (p[0] != '&' || (p + 3 >= lim)) { *(q++) = *(p++); continue; } /* now p[3] is surely valid and is no terminator */ /* numerical entity */ if (p[1] == '#') { next = &p[2]; if (process_numeric_entity(&next, &code) == FAILURE) goto invalid_code; /* If we're in htmlspecialchars_decode, we're only decoding entities * that represent &, <, >, " and '. Is this one of them? */ if (!all && (code > 63U || stage3_table_be_apos_00000[code].data.ent.entity == NULL)) goto invalid_code; /* are we allowed to decode this entity in this document type? * HTML 5 is the only that has a character that cannot be used in * a numeric entity but is allowed literally (U+000D). The * unoptimized version would be ... || !numeric_entity_is_allowed(code) */ if (!unicode_cp_is_allowed(code, doctype) || (doctype == ENT_HTML_DOC_HTML5 && code == 0x0D)) goto invalid_code; } else { const char *start; size_t ent_len; next = &p[1]; start = next; if (process_named_entity_html(&next, &start, &ent_len) == FAILURE) goto invalid_code; if (resolve_named_entity_html(start, ent_len, inv_map, &code, &code2) == FAILURE) { if (doctype == ENT_HTML_DOC_XHTML && ent_len == 4 && start[0] == 'a' && start[1] == 'p' && start[2] == 'o' && start[3] == 's') { /* uses html4 inv_map, which doesn't include apos;. This is a * hack to support it */ code = (unsigned) '\''; } else { goto invalid_code; } } } assert(*next == ';'); if (((code == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) || (code == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))) /* && code2 == '\0' always true for current maps */) goto invalid_code; /* UTF-8 doesn't need mapping (ISO-8859-1 doesn't either, but * the call is needed to ensure the codepoint <= U+00FF) */ if (charset != cs_utf_8) { /* replace unicode code point */ if (map_from_unicode(code, charset, &code) == FAILURE || code2 != 0) goto invalid_code; /* not representable in target charset */ } q += write_octet_sequence(q, charset, code); if (code2) { q += write_octet_sequence(q, charset, code2); } /* jump over the valid entity; may go beyond size of buffer; np */ p = next + 1; continue; invalid_code: for (; p < next; p++) { *(q++) = *p; } } *q = '\0'; *retlen = (size_t)(q - ret); } /* }}} */ /* {{{ unescape_inverse_map */ static const entity_ht *unescape_inverse_map(int all, int flags) { int document_type = flags & ENT_HTML_DOC_TYPE_MASK; if (all) { switch (document_type) { case ENT_HTML_DOC_HTML401: case ENT_HTML_DOC_XHTML: /* but watch out for &apos;...*/ return &ent_ht_html4; case ENT_HTML_DOC_HTML5: return &ent_ht_html5; default: return &ent_ht_be_apos; } } else { switch (document_type) { case ENT_HTML_DOC_HTML401: return &ent_ht_be_noapos; default: return &ent_ht_be_apos; } } } /* }}} */ /* {{{ determine_entity_table * Entity table to use. Note that entity tables are defined in terms of * unicode code points */ static entity_table_opt determine_entity_table(int all, int doctype) { entity_table_opt retval = {NULL}; assert(!(doctype == ENT_HTML_DOC_XML1 && all)); if (all) { retval.ms_table = (doctype == ENT_HTML_DOC_HTML5) ? entity_ms_table_html5 : entity_ms_table_html4; } else { retval.table = (doctype == ENT_HTML_DOC_HTML401) ? stage3_table_be_noapos_00000 : stage3_table_be_apos_00000; } return retval; } /* }}} */ /* {{{ php_unescape_html_entities * The parameter "all" should be true to decode all possible entities, false to decode * only the basic ones, i.e., those in basic_entities_ex + the numeric entities * that correspond to quotes. */ PHPAPI char *php_unescape_html_entities(unsigned char *old, size_t oldlen, size_t *newlen, int all, int flags, char *hint_charset TSRMLS_DC) { size_t retlen; char *ret; enum entity_charset charset; const entity_ht *inverse_map = NULL; size_t new_size = TRAVERSE_FOR_ENTITIES_EXPAND_SIZE(oldlen); if (all) { charset = determine_charset(hint_charset TSRMLS_CC); } else { charset = cs_8859_1; /* charset shouldn't matter, use ISO-8859-1 for performance */ } /* don't use LIMIT_ALL! */ if (oldlen > new_size) { /* overflow, refuse to do anything */ ret = estrndup((char*)old, oldlen); retlen = oldlen; goto empty_source; } ret = emalloc(new_size); *ret = '\0'; retlen = oldlen; if (retlen == 0) { goto empty_source; } inverse_map = unescape_inverse_map(all, flags); /* replace numeric entities */ traverse_for_entities(old, oldlen, ret, &retlen, all, flags, inverse_map, charset); empty_source: *newlen = retlen; return ret; } /* }}} */ PHPAPI char *php_escape_html_entities(unsigned char *old, size_t oldlen, size_t *newlen, int all, int flags, char *hint_charset TSRMLS_DC) { return php_escape_html_entities_ex(old, oldlen, newlen, all, flags, hint_charset, 1 TSRMLS_CC); } /* {{{ find_entity_for_char */ static inline void find_entity_for_char( unsigned int k, enum entity_charset charset, const entity_stage1_row *table, const unsigned char **entity, size_t *entity_len, unsigned char *old, size_t oldlen, size_t *cursor) { unsigned stage1_idx = ENT_STAGE1_INDEX(k); const entity_stage3_row *c; if (stage1_idx > 0x1D) { *entity = NULL; *entity_len = 0; return; } c = &table[stage1_idx][ENT_STAGE2_INDEX(k)][ENT_STAGE3_INDEX(k)]; if (!c->ambiguous) { *entity = (const unsigned char *)c->data.ent.entity; *entity_len = c->data.ent.entity_len; } else { /* peek at next char */ size_t cursor_before = *cursor; int status = SUCCESS; unsigned next_char; if (!(*cursor < oldlen)) goto no_suitable_2nd; next_char = get_next_char(charset, old, oldlen, cursor, &status); if (status == FAILURE) goto no_suitable_2nd; { const entity_multicodepoint_row *s, *e; s = &c->data.multicodepoint_table[1]; e = s - 1 + c->data.multicodepoint_table[0].leading_entry.size; /* we could do a binary search but it's not worth it since we have * at most two entries... */ for ( ; s <= e; s++) { if (s->normal_entry.second_cp == next_char) { *entity = s->normal_entry.entity; *entity_len = s->normal_entry.entity_len; return; } } } no_suitable_2nd: *cursor = cursor_before; *entity = (const unsigned char *) c->data.multicodepoint_table[0].leading_entry.default_entity; *entity_len = c->data.multicodepoint_table[0].leading_entry.default_entity_len; } } /* }}} */ /* {{{ find_entity_for_char_basic */ static inline void find_entity_for_char_basic( unsigned int k, const entity_stage3_row *table, const unsigned char **entity, size_t *entity_len) { if (k >= 64U) { *entity = NULL; *entity_len = 0; return; } *entity = table[k].data.ent.entity; *entity_len = table[k].data.ent.entity_len; } /* }}} */ /* {{{ php_escape_html_entities */ PHPAPI char *php_escape_html_entities_ex(unsigned char *old, size_t oldlen, size_t *newlen, int all, int flags, char *hint_charset, zend_bool double_encode TSRMLS_DC) { size_t cursor, maxlen, len; char *replaced; enum entity_charset charset = determine_charset(hint_charset TSRMLS_CC); int doctype = flags & ENT_HTML_DOC_TYPE_MASK; entity_table_opt entity_table; const enc_to_uni *to_uni_table = NULL; const entity_ht *inv_map = NULL; /* used for !double_encode */ /* only used if flags includes ENT_HTML_IGNORE_ERRORS or ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS */ const unsigned char *replacement; size_t replacement_len; if (all) { /* replace with all named entities */ if (CHARSET_PARTIAL_SUPPORT(charset)) { php_error_docref0(NULL TSRMLS_CC, E_STRICT, "Only basic entities " "substitution is supported for multi-byte encodings other than UTF-8; " "functionality is equivalent to htmlspecialchars"); } LIMIT_ALL(all, doctype, charset); } entity_table = determine_entity_table(all, doctype); if (all && !CHARSET_UNICODE_COMPAT(charset)) { to_uni_table = enc_to_uni_index[charset]; } if (!double_encode) { /* first arg is 1 because we want to identify valid named entities * even if we are only encoding the basic ones */ inv_map = unescape_inverse_map(1, flags); } if (flags & (ENT_HTML_SUBSTITUTE_ERRORS | ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS)) { if (charset == cs_utf_8) { replacement = (const unsigned char*)"\xEF\xBF\xBD"; replacement_len = sizeof("\xEF\xBF\xBD") - 1; } else { replacement = (const unsigned char*)"&#xFFFD;"; replacement_len = sizeof("&#xFFFD;") - 1; } } /* initial estimate */ if (oldlen < 64) { maxlen = 128; } else { maxlen = 2 * oldlen; if (maxlen < oldlen) { zend_error_noreturn(E_ERROR, "Input string is too long"); return NULL; } } replaced = emalloc(maxlen + 1); /* adding 1 is safe: maxlen is even */ len = 0; cursor = 0; while (cursor < oldlen) { const unsigned char *mbsequence = NULL; size_t mbseqlen = 0, cursor_before = cursor; int status = SUCCESS; unsigned int this_char = get_next_char(charset, old, oldlen, &cursor, &status); /* guarantee we have at least 40 bytes to write. * In HTML5, entities may take up to 33 bytes */ if (len > maxlen - 40) { /* maxlen can never be smaller than 128 */ replaced = safe_erealloc(replaced, maxlen , 1, 128 + 1); maxlen += 128; } if (status == FAILURE) { /* invalid MB sequence */ if (flags & ENT_HTML_IGNORE_ERRORS) { continue; } else if (flags & ENT_HTML_SUBSTITUTE_ERRORS) { memcpy(&replaced[len], replacement, replacement_len); len += replacement_len; continue; } else { efree(replaced); *newlen = 0; return STR_EMPTY_ALLOC(); } } else { /* SUCCESS */ mbsequence = &old[cursor_before]; mbseqlen = cursor - cursor_before; } if (this_char != '&') { /* no entity on this position */ const unsigned char *rep = NULL; size_t rep_len = 0; if (((this_char == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) || (this_char == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE)))) goto pass_char_through; if (all) { /* false that CHARSET_PARTIAL_SUPPORT(charset) */ if (to_uni_table != NULL) { /* !CHARSET_UNICODE_COMPAT therefore not UTF-8; since UTF-8 * is the only multibyte encoding with !CHARSET_PARTIAL_SUPPORT, * we're using a single byte encoding */ map_to_unicode(this_char, to_uni_table, &this_char); if (this_char == 0xFFFF) /* no mapping; pass through */ goto pass_char_through; } /* the cursor may advance */ find_entity_for_char(this_char, charset, entity_table.ms_table, &rep, &rep_len, old, oldlen, &cursor); } else { find_entity_for_char_basic(this_char, entity_table.table, &rep, &rep_len); } if (rep != NULL) { replaced[len++] = '&'; memcpy(&replaced[len], rep, rep_len); len += rep_len; replaced[len++] = ';'; } else { /* we did not find an entity for this char. * check for its validity, if its valid pass it unchanged */ if (flags & ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS) { if (CHARSET_UNICODE_COMPAT(charset)) { if (!unicode_cp_is_allowed(this_char, doctype)) { mbsequence = replacement; mbseqlen = replacement_len; } } else if (to_uni_table) { if (!all) /* otherwise we already did this */ map_to_unicode(this_char, to_uni_table, &this_char); if (!unicode_cp_is_allowed(this_char, doctype)) { mbsequence = replacement; mbseqlen = replacement_len; } } else { /* not a unicode code point, unless, coincidentally, it's in * the 0x20..0x7D range (except 0x5C in sjis). We know nothing * about other code points, because we have no tables. Since * Unicode code points in that range are not disallowed in any * document type, we could do nothing. However, conversion * tables frequently map 0x00-0x1F to the respective C0 code * points. Let's play it safe and admit that's the case */ if (this_char <= 0x7D && !unicode_cp_is_allowed(this_char, doctype)) { mbsequence = replacement; mbseqlen = replacement_len; } } } pass_char_through: if (mbseqlen > 1) { memcpy(replaced + len, mbsequence, mbseqlen); len += mbseqlen; } else { replaced[len++] = mbsequence[0]; } } } else { /* this_char == '&' */ if (double_encode) { encode_amp: memcpy(&replaced[len], "&amp;", sizeof("&amp;") - 1); len += sizeof("&amp;") - 1; } else { /* no double encode */ /* check if entity is valid */ size_t ent_len; /* not counting & or ; */ /* peek at next char */ if (old[cursor] == '#') { /* numeric entity */ unsigned code_point; int valid; char *pos = (char*)&old[cursor+1]; valid = process_numeric_entity((const char **)&pos, &code_point); if (valid == FAILURE) goto encode_amp; if (flags & ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS) { if (!numeric_entity_is_allowed(code_point, doctype)) goto encode_amp; } ent_len = pos - (char*)&old[cursor]; } else { /* named entity */ /* check for vality of named entity */ const char *start = &old[cursor], *next = start; unsigned dummy1, dummy2; if (process_named_entity_html(&next, &start, &ent_len) == FAILURE) goto encode_amp; if (resolve_named_entity_html(start, ent_len, inv_map, &dummy1, &dummy2) == FAILURE) { if (!(doctype == ENT_HTML_DOC_XHTML && ent_len == 4 && start[0] == 'a' && start[1] == 'p' && start[2] == 'o' && start[3] == 's')) { /* uses html4 inv_map, which doesn't include apos;. This is a * hack to support it */ goto encode_amp; } } } /* checks passed; copy entity to result */ /* entity size is unbounded, we may need more memory */ /* at this point maxlen - len >= 40 */ if (maxlen - len < ent_len + 2 /* & and ; */) { /* ent_len < oldlen, which is certainly <= SIZE_MAX/2 */ replaced = safe_erealloc(replaced, maxlen, 1, ent_len + 128 + 1); maxlen += ent_len + 128; } replaced[len++] = '&'; memcpy(&replaced[len], &old[cursor], ent_len); len += ent_len; replaced[len++] = ';'; cursor += ent_len + 1; } } } replaced[len] = '\0'; *newlen = len; return replaced; } /* }}} */ /* {{{ php_html_entities */ static void php_html_entities(INTERNAL_FUNCTION_PARAMETERS, int all) { char *str, *hint_charset = NULL; int str_len, hint_charset_len = 0; size_t new_len; long flags = ENT_COMPAT; char *replaced; zend_bool double_encode = 1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!b", &str, &str_len, &flags, &hint_charset, &hint_charset_len, &double_encode) == FAILURE) { return; } replaced = php_escape_html_entities_ex(str, str_len, &new_len, all, (int) flags, hint_charset, double_encode TSRMLS_CC); RETVAL_STRINGL(replaced, (int)new_len, 0); } /* }}} */ #define HTML_SPECIALCHARS 0 #define HTML_ENTITIES 1 /* {{{ register_html_constants */ void register_html_constants(INIT_FUNC_ARGS) { REGISTER_LONG_CONSTANT("HTML_SPECIALCHARS", HTML_SPECIALCHARS, CONST_PERSISTENT|CONST_CS); REGISTER_LONG_CONSTANT("HTML_ENTITIES", HTML_ENTITIES, CONST_PERSISTENT|CONST_CS); REGISTER_LONG_CONSTANT("ENT_COMPAT", ENT_COMPAT, CONST_PERSISTENT|CONST_CS); REGISTER_LONG_CONSTANT("ENT_QUOTES", ENT_QUOTES, CONST_PERSISTENT|CONST_CS); REGISTER_LONG_CONSTANT("ENT_NOQUOTES", ENT_NOQUOTES, CONST_PERSISTENT|CONST_CS); REGISTER_LONG_CONSTANT("ENT_IGNORE", ENT_IGNORE, CONST_PERSISTENT|CONST_CS); REGISTER_LONG_CONSTANT("ENT_SUBSTITUTE", ENT_SUBSTITUTE, CONST_PERSISTENT|CONST_CS); REGISTER_LONG_CONSTANT("ENT_DISALLOWED", ENT_DISALLOWED, CONST_PERSISTENT|CONST_CS); REGISTER_LONG_CONSTANT("ENT_HTML401", ENT_HTML401, CONST_PERSISTENT|CONST_CS); REGISTER_LONG_CONSTANT("ENT_XML1", ENT_XML1, CONST_PERSISTENT|CONST_CS); REGISTER_LONG_CONSTANT("ENT_XHTML", ENT_XHTML, CONST_PERSISTENT|CONST_CS); REGISTER_LONG_CONSTANT("ENT_HTML5", ENT_HTML5, CONST_PERSISTENT|CONST_CS); } /* }}} */ /* {{{ proto string htmlspecialchars(string string [, int quote_style[, string charset[, bool double_encode]]]) Convert special characters to HTML entities */ PHP_FUNCTION(htmlspecialchars) { php_html_entities(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto string htmlspecialchars_decode(string string [, int quote_style]) Convert special HTML entities back to characters */ PHP_FUNCTION(htmlspecialchars_decode) { char *str; int str_len; size_t new_len = 0; long quote_style = ENT_COMPAT; char *replaced; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &str, &str_len, &quote_style) == FAILURE) { return; } replaced = php_unescape_html_entities(str, str_len, &new_len, 0 /*!all*/, quote_style, NULL TSRMLS_CC); if (replaced) { RETURN_STRINGL(replaced, (int)new_len, 0); } RETURN_FALSE; } /* }}} */ /* {{{ proto string html_entity_decode(string string [, int quote_style][, string charset]) Convert all HTML entities to their applicable characters */ PHP_FUNCTION(html_entity_decode) { char *str, *hint_charset = NULL; int str_len, hint_charset_len = 0; size_t new_len = 0; long quote_style = ENT_COMPAT; char *replaced; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls", &str, &str_len, &quote_style, &hint_charset, &hint_charset_len) == FAILURE) { return; } replaced = php_unescape_html_entities(str, str_len, &new_len, 1 /*all*/, quote_style, hint_charset TSRMLS_CC); if (replaced) { RETURN_STRINGL(replaced, (int)new_len, 0); } RETURN_FALSE; } /* }}} */ /* {{{ proto string htmlentities(string string [, int quote_style[, string charset[, bool double_encode]]]) Convert all applicable characters to HTML entities */ PHP_FUNCTION(htmlentities) { php_html_entities(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ write_s3row_data */ static inline void write_s3row_data( const entity_stage3_row *r, unsigned orig_cp, enum entity_charset charset, zval *arr) { char key[9] = ""; /* two unicode code points in UTF-8 */ char entity[LONGEST_ENTITY_LENGTH + 2] = {'&'}; size_t written_k1; written_k1 = write_octet_sequence(key, charset, orig_cp); if (!r->ambiguous) { size_t l = r->data.ent.entity_len; memcpy(&entity[1], r->data.ent.entity, l); entity[l + 1] = ';'; add_assoc_stringl_ex(arr, key, written_k1 + 1, entity, l + 2, 1); } else { unsigned i, num_entries; const entity_multicodepoint_row *mcpr = r->data.multicodepoint_table; if (mcpr[0].leading_entry.default_entity != NULL) { size_t l = mcpr[0].leading_entry.default_entity_len; memcpy(&entity[1], mcpr[0].leading_entry.default_entity, l); entity[l + 1] = ';'; add_assoc_stringl_ex(arr, key, written_k1 + 1, entity, l + 2, 1); } num_entries = mcpr[0].leading_entry.size; for (i = 1; i <= num_entries; i++) { size_t l, written_k2; unsigned uni_cp, spe_cp; uni_cp = mcpr[i].normal_entry.second_cp; l = mcpr[i].normal_entry.entity_len; if (!CHARSET_UNICODE_COMPAT(charset)) { if (map_from_unicode(uni_cp, charset, &spe_cp) == FAILURE) continue; /* non representable in this charset */ } else { spe_cp = uni_cp; } written_k2 = write_octet_sequence(&key[written_k1], charset, spe_cp); memcpy(&entity[1], mcpr[i].normal_entry.entity, l); entity[l + 1] = ';'; entity[l + 1] = '\0'; add_assoc_stringl_ex(arr, key, written_k1 + written_k2 + 1, entity, l + 1, 1); } } } /* }}} */ /* {{{ proto array get_html_translation_table([int table [, int flags [, string charset_hint]]]) Returns the internal translation table used by htmlspecialchars and htmlentities */ PHP_FUNCTION(get_html_translation_table) { long all = HTML_SPECIALCHARS, flags = ENT_COMPAT; int doctype; entity_table_opt entity_table; const enc_to_uni *to_uni_table; char *charset_hint = NULL; int charset_hint_len; enum entity_charset charset; /* in this function we have to jump through some loops because we're * getting the translated table from data structures that are optimized for * random access, not traversal */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lls", &all, &flags, &charset_hint, &charset_hint_len) == FAILURE) { return; } charset = determine_charset(charset_hint TSRMLS_CC); doctype = flags & ENT_HTML_DOC_TYPE_MASK; LIMIT_ALL(all, doctype, charset); array_init(return_value); entity_table = determine_entity_table(all, doctype); if (all && !CHARSET_UNICODE_COMPAT(charset)) { to_uni_table = enc_to_uni_index[charset]; } if (all) { /* HTML_ENTITIES (actually, any non-zero value for 1st param) */ const entity_stage1_row *ms_table = entity_table.ms_table; if (CHARSET_UNICODE_COMPAT(charset)) { unsigned i, j, k, max_i, max_j, max_k; /* no mapping to unicode required */ if (CHARSET_SINGLE_BYTE(charset)) { max_i = 1; max_j = 1; max_k = 64; } else { max_i = 0x1E; max_j = 64; max_k = 64; } for (i = 0; i < max_i; i++) { if (ms_table[i] == empty_stage2_table) continue; for (j = 0; j < max_j; j++) { if (ms_table[i][j] == empty_stage3_table) continue; for (k = 0; k < max_k; k++) { const entity_stage3_row *r = &ms_table[i][j][k]; unsigned code; if (r->data.ent.entity == NULL) continue; code = ENT_CODE_POINT_FROM_STAGES(i, j, k); if (((code == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) || (code == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE)))) continue; write_s3row_data(r, code, charset, return_value); } } } } else { /* we have to iterate through the set of code points for this * encoding and map them to unicode code points */ unsigned i; for (i = 0; i <= 0xFF; i++) { const entity_stage3_row *r; unsigned uni_cp; /* can be done before mapping, they're invariant */ if (((i == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) || (i == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE)))) continue; map_to_unicode(i, to_uni_table, &uni_cp); r = &ms_table[ENT_STAGE1_INDEX(uni_cp)][ENT_STAGE2_INDEX(uni_cp)][ENT_STAGE3_INDEX(uni_cp)]; if (r->data.ent.entity == NULL) continue; write_s3row_data(r, i, charset, return_value); } } } else { /* we could use sizeof(stage3_table_be_apos_00000) as well */ unsigned j, numelems = sizeof(stage3_table_be_noapos_00000) / sizeof(*stage3_table_be_noapos_00000); for (j = 0; j < numelems; j++) { const entity_stage3_row *r = &entity_table.table[j]; if (r->data.ent.entity == NULL) continue; if (((j == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) || (j == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE)))) continue; /* charset is indifferent, used cs_8859_1 for efficiency */ write_s3row_data(r, j, cs_8859_1, return_value); } } } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2012-03-12-7aefbf70a8-efc94f3115.c
manybugs_data_37
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Wez Furlong <[email protected]> | | Borrowed code from: | | Rasmus Lerdorf <[email protected]> | | Jim Winstead <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #define _GNU_SOURCE #include "php.h" #include "php_globals.h" #include "php_network.h" #include "php_open_temporary_file.h" #include "ext/standard/file.h" #include "ext/standard/basic_functions.h" /* for BG(mmap_file) (not strictly required) */ #include "ext/standard/php_string.h" /* for php_memnstr, used by php_stream_get_record() */ #include <stddef.h> #include <fcntl.h> #include "php_streams_int.h" /* {{{ resource and registration code */ /* Global wrapper hash, copied to FG(stream_wrappers) on registration of volatile wrapper */ static HashTable url_stream_wrappers_hash; static int le_stream = FAILURE; /* true global */ static int le_pstream = FAILURE; /* true global */ static int le_stream_filter = FAILURE; /* true global */ PHPAPI int php_file_le_stream(void) { return le_stream; } PHPAPI int php_file_le_pstream(void) { return le_pstream; } PHPAPI int php_file_le_stream_filter(void) { return le_stream_filter; } PHPAPI HashTable *_php_stream_get_url_stream_wrappers_hash(TSRMLS_D) { return (FG(stream_wrappers) ? FG(stream_wrappers) : &url_stream_wrappers_hash); } PHPAPI HashTable *php_stream_get_url_stream_wrappers_hash_global(void) { return &url_stream_wrappers_hash; } static int _php_stream_release_context(zend_rsrc_list_entry *le, void *pContext TSRMLS_DC) { if (le->ptr == pContext) { return --le->refcount == 0; } return 0; } static int forget_persistent_resource_id_numbers(zend_rsrc_list_entry *rsrc TSRMLS_DC) { php_stream *stream; if (Z_TYPE_P(rsrc) != le_pstream) { return 0; } stream = (php_stream*)rsrc->ptr; #if STREAM_DEBUG fprintf(stderr, "forget_persistent: %s:%p\n", stream->ops->label, stream); #endif stream->rsrc_id = FAILURE; if (stream->context) { zend_hash_apply_with_argument(&EG(regular_list), (apply_func_arg_t) _php_stream_release_context, stream->context TSRMLS_CC); stream->context = NULL; } return 0; } PHP_RSHUTDOWN_FUNCTION(streams) { zend_hash_apply(&EG(persistent_list), (apply_func_t)forget_persistent_resource_id_numbers TSRMLS_CC); return SUCCESS; } PHPAPI php_stream *php_stream_encloses(php_stream *enclosing, php_stream *enclosed) { php_stream *orig = enclosed->enclosing_stream; php_stream_auto_cleanup(enclosed); enclosed->enclosing_stream = enclosing; return orig; } PHPAPI int php_stream_from_persistent_id(const char *persistent_id, php_stream **stream TSRMLS_DC) { zend_rsrc_list_entry *le; if (zend_hash_find(&EG(persistent_list), (char*)persistent_id, strlen(persistent_id)+1, (void*) &le) == SUCCESS) { if (Z_TYPE_P(le) == le_pstream) { if (stream) { HashPosition pos; zend_rsrc_list_entry *regentry; ulong index = -1; /* intentional */ /* see if this persistent resource already has been loaded to the * regular list; allowing the same resource in several entries in the * regular list causes trouble (see bug #54623) */ zend_hash_internal_pointer_reset_ex(&EG(regular_list), &pos); while (zend_hash_get_current_data_ex(&EG(regular_list), (void **)&regentry, &pos) == SUCCESS) { if (regentry->ptr == le->ptr) { zend_hash_get_current_key_ex(&EG(regular_list), NULL, NULL, &index, 0, &pos); break; } zend_hash_move_forward_ex(&EG(regular_list), &pos); } *stream = (php_stream*)le->ptr; if (index == -1) { /* not found in regular list */ le->refcount++; (*stream)->rsrc_id = ZEND_REGISTER_RESOURCE(NULL, *stream, le_pstream); } else { regentry->refcount++; (*stream)->rsrc_id = index; } } return PHP_STREAM_PERSISTENT_SUCCESS; } return PHP_STREAM_PERSISTENT_FAILURE; } return PHP_STREAM_PERSISTENT_NOT_EXIST; } /* }}} */ /* {{{ wrapper error reporting */ void php_stream_display_wrapper_errors(php_stream_wrapper *wrapper, const char *path, const char *caption TSRMLS_DC) { char *tmp = estrdup(path); char *msg; int free_msg = 0; php_stream_wrapper orig_wrapper; if (wrapper) { if (wrapper->err_count > 0) { int i; size_t l; int brlen; char *br; if (PG(html_errors)) { brlen = 7; br = "<br />\n"; } else { brlen = 1; br = "\n"; } for (i = 0, l = 0; i < wrapper->err_count; i++) { l += strlen(wrapper->err_stack[i]); if (i < wrapper->err_count - 1) { l += brlen; } } msg = emalloc(l + 1); msg[0] = '\0'; for (i = 0; i < wrapper->err_count; i++) { strcat(msg, wrapper->err_stack[i]); if (i < wrapper->err_count - 1) { strcat(msg, br); } } free_msg = 1; } else { if (wrapper == &php_plain_files_wrapper) { msg = strerror(errno); } else { msg = "operation failed"; } } } else { msg = "no suitable wrapper could be found"; } php_strip_url_passwd(tmp); if (wrapper) { /* see bug #52935 */ orig_wrapper = *wrapper; wrapper->err_stack = NULL; wrapper->err_count = 0; } php_error_docref1(NULL TSRMLS_CC, tmp, E_WARNING, "%s: %s", caption, msg); if (wrapper) { *wrapper = orig_wrapper; } efree(tmp); if (free_msg) { efree(msg); } } void php_stream_tidy_wrapper_error_log(php_stream_wrapper *wrapper TSRMLS_DC) { if (wrapper) { /* tidy up the error stack */ int i; for (i = 0; i < wrapper->err_count; i++) { efree(wrapper->err_stack[i]); } if (wrapper->err_stack) { efree(wrapper->err_stack); } wrapper->err_stack = NULL; wrapper->err_count = 0; } } PHPAPI void php_stream_wrapper_log_error(php_stream_wrapper *wrapper, int options TSRMLS_DC, const char *fmt, ...) { va_list args; char *buffer = NULL; va_start(args, fmt); vspprintf(&buffer, 0, fmt, args); va_end(args); if (options & REPORT_ERRORS || wrapper == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", buffer); efree(buffer); } else { /* append to stack */ wrapper->err_stack = erealloc(wrapper->err_stack, (wrapper->err_count + 1) * sizeof(char *)); if (wrapper->err_stack) { wrapper->err_stack[wrapper->err_count++] = buffer; } } } /* }}} */ /* allocate a new stream for a particular ops */ PHPAPI php_stream *_php_stream_alloc(php_stream_ops *ops, void *abstract, const char *persistent_id, const char *mode STREAMS_DC TSRMLS_DC) /* {{{ */ { php_stream *ret; ret = (php_stream*) pemalloc_rel_orig(sizeof(php_stream), persistent_id ? 1 : 0); memset(ret, 0, sizeof(php_stream)); ret->readfilters.stream = ret; ret->writefilters.stream = ret; #if STREAM_DEBUG fprintf(stderr, "stream_alloc: %s:%p persistent=%s\n", ops->label, ret, persistent_id); #endif ret->ops = ops; ret->abstract = abstract; ret->is_persistent = persistent_id ? 1 : 0; ret->chunk_size = FG(def_chunk_size); #if ZEND_DEBUG ret->open_filename = __zend_orig_filename ? __zend_orig_filename : __zend_filename; ret->open_lineno = __zend_orig_lineno ? __zend_orig_lineno : __zend_lineno; #endif if (FG(auto_detect_line_endings)) { ret->flags |= PHP_STREAM_FLAG_DETECT_EOL; } if (persistent_id) { zend_rsrc_list_entry le; Z_TYPE(le) = le_pstream; le.ptr = ret; le.refcount = 0; if (FAILURE == zend_hash_update(&EG(persistent_list), (char *)persistent_id, strlen(persistent_id) + 1, (void *)&le, sizeof(le), NULL)) { pefree(ret, 1); return NULL; } } ret->rsrc_id = ZEND_REGISTER_RESOURCE(NULL, ret, persistent_id ? le_pstream : le_stream); strlcpy(ret->mode, mode, sizeof(ret->mode)); ret->wrapper = NULL; ret->wrapperthis = NULL; ret->wrapperdata = NULL; ret->stdiocast = NULL; ret->orig_path = NULL; ret->context = NULL; ret->readbuf = NULL; ret->enclosing_stream = NULL; return ret; } /* }}} */ PHPAPI int _php_stream_free_enclosed(php_stream *stream_enclosed, int close_options TSRMLS_DC) /* {{{ */ { return _php_stream_free(stream_enclosed, close_options | PHP_STREAM_FREE_IGNORE_ENCLOSING TSRMLS_CC); } /* }}} */ #if STREAM_DEBUG static const char *_php_stream_pretty_free_options(int close_options, char *out) { if (close_options & PHP_STREAM_FREE_CALL_DTOR) strcat(out, "CALL_DTOR, "); if (close_options & PHP_STREAM_FREE_RELEASE_STREAM) strcat(out, "RELEASE_STREAM, "); if (close_options & PHP_STREAM_FREE_PRESERVE_HANDLE) strcat(out, "PREVERSE_HANDLE, "); if (close_options & PHP_STREAM_FREE_RSRC_DTOR) strcat(out, "RSRC_DTOR, "); if (close_options & PHP_STREAM_FREE_PERSISTENT) strcat(out, "PERSISTENT, "); if (close_options & PHP_STREAM_FREE_IGNORE_ENCLOSING) strcat(out, "IGNORE_ENCLOSING, "); if (out[0] != '\0') out[strlen(out) - 2] = '\0'; return out; } #endif static int _php_stream_free_persistent(zend_rsrc_list_entry *le, void *pStream TSRMLS_DC) { return le->ptr == pStream; } PHPAPI int _php_stream_free(php_stream *stream, int close_options TSRMLS_DC) /* {{{ */ { int ret = 1; int preserve_handle = close_options & PHP_STREAM_FREE_PRESERVE_HANDLE ? 1 : 0; int release_cast = 1; php_stream_context *context = stream->context; if (stream->flags & PHP_STREAM_FLAG_NO_CLOSE) { preserve_handle = 1; } #if STREAM_DEBUG { char out[200] = ""; fprintf(stderr, "stream_free: %s:%p[%s] in_free=%d opts=%s\n", stream->ops->label, stream, stream->orig_path, stream->in_free, _php_stream_pretty_free_options(close_options, out)); } #endif if (stream->in_free) { /* hopefully called recursively from the enclosing stream; the pointer was NULLed below */ if ((stream->in_free == 1) && (close_options & PHP_STREAM_FREE_IGNORE_ENCLOSING) && (stream->enclosing_stream == NULL)) { close_options |= PHP_STREAM_FREE_RSRC_DTOR; /* restore flag */ } else { return 1; /* recursion protection */ } } stream->in_free++; /* force correct order on enclosing/enclosed stream destruction (only from resource * destructor as in when reverse destroying the resource list) */ if ((close_options & PHP_STREAM_FREE_RSRC_DTOR) && !(close_options & PHP_STREAM_FREE_IGNORE_ENCLOSING) && (close_options & (PHP_STREAM_FREE_CALL_DTOR | PHP_STREAM_FREE_RELEASE_STREAM)) && /* always? */ (stream->enclosing_stream != NULL)) { php_stream *enclosing_stream = stream->enclosing_stream; stream->enclosing_stream = NULL; /* we force PHP_STREAM_CALL_DTOR because that's from where the * enclosing stream can free this stream. We remove rsrc_dtor because * we want the enclosing stream to be deleted from the resource list */ return _php_stream_free(enclosing_stream, (close_options | PHP_STREAM_FREE_CALL_DTOR) & ~PHP_STREAM_FREE_RSRC_DTOR TSRMLS_CC); } /* if we are releasing the stream only (and preserving the underlying handle), * we need to do things a little differently. * We are only ever called like this when the stream is cast to a FILE* * for include (or other similar) purposes. * */ if (preserve_handle) { if (stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FOPENCOOKIE) { /* If the stream was fopencookied, we must NOT touch anything * here, as the cookied stream relies on it all. * Instead, mark the stream as OK to auto-clean */ php_stream_auto_cleanup(stream); stream->in_free--; return 0; } /* otherwise, make sure that we don't close the FILE* from a cast */ release_cast = 0; } #if STREAM_DEBUG fprintf(stderr, "stream_free: %s:%p[%s] preserve_handle=%d release_cast=%d remove_rsrc=%d\n", stream->ops->label, stream, stream->orig_path, preserve_handle, release_cast, (close_options & PHP_STREAM_FREE_RSRC_DTOR) == 0); #endif /* make sure everything is saved */ _php_stream_flush(stream, 1 TSRMLS_CC); /* If not called from the resource dtor, remove the stream from the resource list. */ if ((close_options & PHP_STREAM_FREE_RSRC_DTOR) == 0) { /* zend_list_delete actually only decreases the refcount; if we're * releasing the stream, we want to actually delete the resource from * the resource list, otherwise the resource will point to invalid memory. * In any case, let's always completely delete it from the resource list, * not only when PHP_STREAM_FREE_RELEASE_STREAM is set */ while (zend_list_delete(stream->rsrc_id) == SUCCESS) {} } /* Remove stream from any context link list */ if (stream->context && stream->context->links) { php_stream_context_del_link(stream->context, stream); } if (close_options & PHP_STREAM_FREE_CALL_DTOR) { if (release_cast && stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FOPENCOOKIE) { /* calling fclose on an fopencookied stream will ultimately call this very same function. If we were called via fclose, the cookie_closer unsets the fclose_stdiocast flags, so we can be sure that we only reach here when PHP code calls php_stream_free. Lets let the cookie code clean it all up. */ stream->in_free = 0; return fclose(stream->stdiocast); } ret = stream->ops->close(stream, preserve_handle ? 0 : 1 TSRMLS_CC); stream->abstract = NULL; /* tidy up any FILE* that might have been fdopened */ if (release_cast && stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FDOPEN && stream->stdiocast) { fclose(stream->stdiocast); stream->stdiocast = NULL; stream->fclose_stdiocast = PHP_STREAM_FCLOSE_NONE; } } if (close_options & PHP_STREAM_FREE_RELEASE_STREAM) { while (stream->readfilters.head) { php_stream_filter_remove(stream->readfilters.head, 1 TSRMLS_CC); } while (stream->writefilters.head) { php_stream_filter_remove(stream->writefilters.head, 1 TSRMLS_CC); } if (stream->wrapper && stream->wrapper->wops && stream->wrapper->wops->stream_closer) { stream->wrapper->wops->stream_closer(stream->wrapper, stream TSRMLS_CC); stream->wrapper = NULL; } if (stream->wrapperdata) { zval_ptr_dtor(&stream->wrapperdata); stream->wrapperdata = NULL; } if (stream->readbuf) { pefree(stream->readbuf, stream->is_persistent); stream->readbuf = NULL; } if (stream->is_persistent && (close_options & PHP_STREAM_FREE_PERSISTENT)) { /* we don't work with *stream but need its value for comparison */ zend_hash_apply_with_argument(&EG(persistent_list), (apply_func_arg_t) _php_stream_free_persistent, stream TSRMLS_CC); } #if ZEND_DEBUG if ((close_options & PHP_STREAM_FREE_RSRC_DTOR) && (stream->__exposed == 0) && (EG(error_reporting) & E_WARNING)) { /* it leaked: Lets deliberately NOT pefree it so that the memory manager shows it * as leaked; it will log a warning, but lets help it out and display what kind * of stream it was. */ char *leakinfo; spprintf(&leakinfo, 0, __FILE__ "(%d) : Stream of type '%s' %p (path:%s) was not closed\n", __LINE__, stream->ops->label, stream, stream->orig_path); if (stream->orig_path) { pefree(stream->orig_path, stream->is_persistent); stream->orig_path = NULL; } # if defined(PHP_WIN32) OutputDebugString(leakinfo); # else fprintf(stderr, "%s", leakinfo); # endif efree(leakinfo); } else { if (stream->orig_path) { pefree(stream->orig_path, stream->is_persistent); stream->orig_path = NULL; } pefree(stream, stream->is_persistent); } #else if (stream->orig_path) { pefree(stream->orig_path, stream->is_persistent); stream->orig_path = NULL; } pefree(stream, stream->is_persistent); #endif } if (context) { zend_list_delete(context->rsrc_id); } return ret; } /* }}} */ /* {{{ generic stream operations */ static void php_stream_fill_read_buffer(php_stream *stream, size_t size TSRMLS_DC) { /* allocate/fill the buffer */ if (stream->readfilters.head) { char *chunk_buf; int err_flag = 0; php_stream_bucket_brigade brig_in = { NULL, NULL }, brig_out = { NULL, NULL }; php_stream_bucket_brigade *brig_inp = &brig_in, *brig_outp = &brig_out, *brig_swap; /* Invalidate the existing cache, otherwise reads can fail, see note in main/streams/filter.c::_php_stream_filter_append */ stream->writepos = stream->readpos = 0; /* allocate a buffer for reading chunks */ chunk_buf = emalloc(stream->chunk_size); while (!stream->eof && !err_flag && (stream->writepos - stream->readpos < (off_t)size)) { size_t justread = 0; int flags; php_stream_bucket *bucket; php_stream_filter_status_t status = PSFS_ERR_FATAL; php_stream_filter *filter; /* read a chunk into a bucket */ justread = stream->ops->read(stream, chunk_buf, stream->chunk_size TSRMLS_CC); if (justread && justread != (size_t)-1) { bucket = php_stream_bucket_new(stream, chunk_buf, justread, 0, 0 TSRMLS_CC); /* after this call, bucket is owned by the brigade */ php_stream_bucket_append(brig_inp, bucket TSRMLS_CC); flags = PSFS_FLAG_NORMAL; } else { flags = stream->eof ? PSFS_FLAG_FLUSH_CLOSE : PSFS_FLAG_FLUSH_INC; } /* wind the handle... */ for (filter = stream->readfilters.head; filter; filter = filter->next) { status = filter->fops->filter(stream, filter, brig_inp, brig_outp, NULL, flags TSRMLS_CC); if (status != PSFS_PASS_ON) { break; } /* brig_out becomes brig_in. * brig_in will always be empty here, as the filter MUST attach any un-consumed buckets * to its own brigade */ brig_swap = brig_inp; brig_inp = brig_outp; brig_outp = brig_swap; memset(brig_outp, 0, sizeof(*brig_outp)); } switch (status) { case PSFS_PASS_ON: /* we get here when the last filter in the chain has data to pass on. * in this situation, we are passing the brig_in brigade into the * stream read buffer */ while (brig_inp->head) { bucket = brig_inp->head; /* grow buffer to hold this bucket * TODO: this can fail for persistent streams */ if (stream->readbuflen - stream->writepos < bucket->buflen) { stream->readbuflen += bucket->buflen; stream->readbuf = perealloc(stream->readbuf, stream->readbuflen, stream->is_persistent); } memcpy(stream->readbuf + stream->writepos, bucket->buf, bucket->buflen); stream->writepos += bucket->buflen; php_stream_bucket_unlink(bucket TSRMLS_CC); php_stream_bucket_delref(bucket TSRMLS_CC); } break; case PSFS_FEED_ME: /* when a filter needs feeding, there is no brig_out to deal with. * we simply continue the loop; if the caller needs more data, * we will read again, otherwise out job is done here */ if (justread == 0) { /* there is no data */ err_flag = 1; break; } continue; case PSFS_ERR_FATAL: /* some fatal error. Theoretically, the stream is borked, so all * further reads should fail. */ err_flag = 1; break; } if (justread == 0 || justread == (size_t)-1) { break; } } efree(chunk_buf); } else { /* is there enough data in the buffer ? */ if (stream->writepos - stream->readpos < (off_t)size) { size_t justread = 0; /* reduce buffer memory consumption if possible, to avoid a realloc */ if (stream->readbuf && stream->readbuflen - stream->writepos < stream->chunk_size) { memmove(stream->readbuf, stream->readbuf + stream->readpos, stream->readbuflen - stream->readpos); stream->writepos -= stream->readpos; stream->readpos = 0; } /* grow the buffer if required * TODO: this can fail for persistent streams */ if (stream->readbuflen - stream->writepos < stream->chunk_size) { stream->readbuflen += stream->chunk_size; stream->readbuf = perealloc(stream->readbuf, stream->readbuflen, stream->is_persistent); } justread = stream->ops->read(stream, stream->readbuf + stream->writepos, stream->readbuflen - stream->writepos TSRMLS_CC); if (justread != (size_t)-1) { stream->writepos += justread; } } } } PHPAPI size_t _php_stream_read(php_stream *stream, char *buf, size_t size TSRMLS_DC) { size_t toread = 0, didread = 0; while (size > 0) { /* take from the read buffer first. * It is possible that a buffered stream was switched to non-buffered, so we * drain the remainder of the buffer before using the "raw" read mode for * the excess */ if (stream->writepos > stream->readpos) { toread = stream->writepos - stream->readpos; if (toread > size) { toread = size; } memcpy(buf, stream->readbuf + stream->readpos, toread); stream->readpos += toread; size -= toread; buf += toread; didread += toread; } /* ignore eof here; the underlying state might have changed */ if (size == 0) { break; } if (!stream->readfilters.head && (stream->flags & PHP_STREAM_FLAG_NO_BUFFER || stream->chunk_size == 1)) { toread = stream->ops->read(stream, buf, size TSRMLS_CC); } else { php_stream_fill_read_buffer(stream, size TSRMLS_CC); toread = stream->writepos - stream->readpos; if (toread > size) { toread = size; } if (toread > 0) { memcpy(buf, stream->readbuf + stream->readpos, toread); stream->readpos += toread; } } if (toread > 0) { didread += toread; buf += toread; size -= toread; } else { /* EOF, or temporary end of data (for non-blocking mode). */ break; } /* just break anyway, to avoid greedy read */ if (stream->wrapper != &php_plain_files_wrapper) { break; } } if (didread > 0) { stream->position += didread; } return didread; } PHPAPI int _php_stream_eof(php_stream *stream TSRMLS_DC) { /* if there is data in the buffer, it's not EOF */ if (stream->writepos - stream->readpos > 0) { return 0; } /* use the configured timeout when checking eof */ if (!stream->eof && PHP_STREAM_OPTION_RETURN_ERR == php_stream_set_option(stream, PHP_STREAM_OPTION_CHECK_LIVENESS, 0, NULL)) { stream->eof = 1; } return stream->eof; } PHPAPI int _php_stream_putc(php_stream *stream, int c TSRMLS_DC) { unsigned char buf = c; if (php_stream_write(stream, &buf, 1) > 0) { return 1; } return EOF; } PHPAPI int _php_stream_getc(php_stream *stream TSRMLS_DC) { char buf; if (php_stream_read(stream, &buf, 1) > 0) { return buf & 0xff; } return EOF; } PHPAPI int _php_stream_puts(php_stream *stream, char *buf TSRMLS_DC) { int len; char newline[2] = "\n"; /* is this OK for Win? */ len = strlen(buf); if (len > 0 && php_stream_write(stream, buf, len) && php_stream_write(stream, newline, 1)) { return 1; } return 0; } PHPAPI int _php_stream_stat(php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC) { memset(ssb, 0, sizeof(*ssb)); /* if the stream was wrapped, allow the wrapper to stat it */ if (stream->wrapper && stream->wrapper->wops->stream_stat != NULL) { return stream->wrapper->wops->stream_stat(stream->wrapper, stream, ssb TSRMLS_CC); } /* if the stream doesn't directly support stat-ing, return with failure. * We could try and emulate this by casting to a FD and fstat-ing it, * but since the fd might not represent the actual underlying content * this would give bogus results. */ if (stream->ops->stat == NULL) { return -1; } return (stream->ops->stat)(stream, ssb TSRMLS_CC); } PHPAPI char *php_stream_locate_eol(php_stream *stream, char *buf, size_t buf_len TSRMLS_DC) { size_t avail; char *cr, *lf, *eol = NULL; char *readptr; if (!buf) { readptr = stream->readbuf + stream->readpos; avail = stream->writepos - stream->readpos; } else { readptr = buf; avail = buf_len; } /* Look for EOL */ if (stream->flags & PHP_STREAM_FLAG_DETECT_EOL) { cr = memchr(readptr, '\r', avail); lf = memchr(readptr, '\n', avail); if (cr && lf != cr + 1 && !(lf && lf < cr)) { /* mac */ stream->flags ^= PHP_STREAM_FLAG_DETECT_EOL; stream->flags |= PHP_STREAM_FLAG_EOL_MAC; eol = cr; } else if ((cr && lf && cr == lf - 1) || (lf)) { /* dos or unix endings */ stream->flags ^= PHP_STREAM_FLAG_DETECT_EOL; eol = lf; } } else if (stream->flags & PHP_STREAM_FLAG_EOL_MAC) { eol = memchr(readptr, '\r', avail); } else { /* unix (and dos) line endings */ eol = memchr(readptr, '\n', avail); } return eol; } /* If buf == NULL, the buffer will be allocated automatically and will be of an * appropriate length to hold the line, regardless of the line length, memory * permitting */ PHPAPI char *_php_stream_get_line(php_stream *stream, char *buf, size_t maxlen, size_t *returned_len TSRMLS_DC) { size_t avail = 0; size_t current_buf_size = 0; size_t total_copied = 0; int grow_mode = 0; char *bufstart = buf; if (buf == NULL) { grow_mode = 1; } else if (maxlen == 0) { return NULL; } /* * If the underlying stream operations block when no new data is readable, * we need to take extra precautions. * * If there is buffered data available, we check for a EOL. If it exists, * we pass the data immediately back to the caller. This saves a call * to the read implementation and will not block where blocking * is not necessary at all. * * If the stream buffer contains more data than the caller requested, * we can also avoid that costly step and simply return that data. */ for (;;) { avail = stream->writepos - stream->readpos; if (avail > 0) { size_t cpysz = 0; char *readptr; char *eol; int done = 0; readptr = stream->readbuf + stream->readpos; eol = php_stream_locate_eol(stream, NULL, 0 TSRMLS_CC); if (eol) { cpysz = eol - readptr + 1; done = 1; } else { cpysz = avail; } if (grow_mode) { /* allow room for a NUL. If this realloc is really a realloc * (ie: second time around), we get an extra byte. In most * cases, with the default chunk size of 8K, we will only * incur that overhead once. When people have lines longer * than 8K, we waste 1 byte per additional 8K or so. * That seems acceptable to me, to avoid making this code * hard to follow */ bufstart = erealloc(bufstart, current_buf_size + cpysz + 1); current_buf_size += cpysz + 1; buf = bufstart + total_copied; } else { if (cpysz >= maxlen - 1) { cpysz = maxlen - 1; done = 1; } } memcpy(buf, readptr, cpysz); stream->position += cpysz; stream->readpos += cpysz; buf += cpysz; maxlen -= cpysz; total_copied += cpysz; if (done) { break; } } else if (stream->eof) { break; } else { /* XXX: Should be fine to always read chunk_size */ size_t toread; if (grow_mode) { toread = stream->chunk_size; } else { toread = maxlen - 1; if (toread > stream->chunk_size) { toread = stream->chunk_size; } } php_stream_fill_read_buffer(stream, toread TSRMLS_CC); if (stream->writepos - stream->readpos == 0) { break; } } } if (total_copied == 0) { if (grow_mode) { assert(bufstart == NULL); } return NULL; } buf[0] = '\0'; if (returned_len) { *returned_len = total_copied; } return bufstart; } PHPAPI char *php_stream_get_record(php_stream *stream, size_t maxlen, size_t *returned_len, char *delim, size_t delim_len TSRMLS_DC) { char *e, *buf; size_t toread, len; int skip = 0; len = stream->writepos - stream->readpos; /* make sure the stream read buffer has maxlen bytes */ while (len < maxlen) { size_t just_read; toread = MIN(maxlen - len, stream->chunk_size); php_stream_fill_read_buffer(stream, len + toread TSRMLS_CC); just_read = (stream->writepos - stream->readpos) - len; len += just_read; /* read operation have less data than request; assume the stream is * temporarily or permanently out of data */ if (just_read < toread) { break; } } if (delim_len == 0 || !delim) { toread = maxlen; } else { size_t seek_len; /* set the maximum number of bytes we're allowed to read from buffer */ seek_len = stream->writepos - stream->readpos; if (seek_len > maxlen) { seek_len = maxlen; } if (delim_len == 1) { e = memchr(stream->readbuf + stream->readpos, *delim, seek_len); } else { e = php_memnstr(stream->readbuf + stream->readpos, delim, delim_len, (stream->readbuf + stream->readpos + seek_len)); } if (!e) { /* return with error if the delimiter string was not found, we * could not completely fill the read buffer with maxlen bytes * and we don't know we've reached end of file. Added with * non-blocking streams in mind, where this situation is frequent */ if (seek_len < maxlen && !stream->eof) { return NULL; } toread = maxlen; } else { toread = e - (char *) stream->readbuf - stream->readpos; /* we found the delimiter, so advance the read pointer past it */ skip = 1; } } if (toread > maxlen && maxlen > 0) { toread = maxlen; } buf = emalloc(toread + 1); *returned_len = php_stream_read(stream, buf, toread); if (skip) { stream->readpos += delim_len; stream->position += delim_len; } buf[*returned_len] = '\0'; return buf; } /* Writes a buffer directly to a stream, using multiple of the chunk size */ static size_t _php_stream_write_buffer(php_stream *stream, const char *buf, size_t count TSRMLS_DC) { size_t didwrite = 0, towrite, justwrote; /* if we have a seekable stream we need to ensure that data is written at the * current stream->position. This means invalidating the read buffer and then * performing a low-level seek */ if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0 && stream->readpos != stream->writepos) { stream->readpos = stream->writepos = 0; stream->ops->seek(stream, stream->position, SEEK_SET, &stream->position TSRMLS_CC); } while (count > 0) { towrite = count; if (towrite > stream->chunk_size) towrite = stream->chunk_size; justwrote = stream->ops->write(stream, buf, towrite TSRMLS_CC); /* convert justwrote to an integer, since normally it is unsigned */ if ((int)justwrote > 0) { buf += justwrote; count -= justwrote; didwrite += justwrote; /* Only screw with the buffer if we can seek, otherwise we lose data * buffered from fifos and sockets */ if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) { stream->position += justwrote; } } else { break; } } return didwrite; } /* push some data through the write filter chain. * buf may be NULL, if flags are set to indicate a flush. * This may trigger a real write to the stream. * Returns the number of bytes consumed from buf by the first filter in the chain. * */ static size_t _php_stream_write_filtered(php_stream *stream, const char *buf, size_t count, int flags TSRMLS_DC) { size_t consumed = 0; php_stream_bucket *bucket; php_stream_bucket_brigade brig_in = { NULL, NULL }, brig_out = { NULL, NULL }; php_stream_bucket_brigade *brig_inp = &brig_in, *brig_outp = &brig_out, *brig_swap; php_stream_filter_status_t status = PSFS_ERR_FATAL; php_stream_filter *filter; if (buf) { bucket = php_stream_bucket_new(stream, (char *)buf, count, 0, 0 TSRMLS_CC); php_stream_bucket_append(&brig_in, bucket TSRMLS_CC); } for (filter = stream->writefilters.head; filter; filter = filter->next) { /* for our return value, we are interested in the number of bytes consumed from * the first filter in the chain */ status = filter->fops->filter(stream, filter, brig_inp, brig_outp, filter == stream->writefilters.head ? &consumed : NULL, flags TSRMLS_CC); if (status != PSFS_PASS_ON) { break; } /* brig_out becomes brig_in. * brig_in will always be empty here, as the filter MUST attach any un-consumed buckets * to its own brigade */ brig_swap = brig_inp; brig_inp = brig_outp; brig_outp = brig_swap; memset(brig_outp, 0, sizeof(*brig_outp)); } switch (status) { case PSFS_PASS_ON: /* filter chain generated some output; push it through to the * underlying stream */ while (brig_inp->head) { bucket = brig_inp->head; _php_stream_write_buffer(stream, bucket->buf, bucket->buflen TSRMLS_CC); /* Potential error situation - eg: no space on device. Perhaps we should keep this brigade * hanging around and try to write it later. * At the moment, we just drop it on the floor * */ php_stream_bucket_unlink(bucket TSRMLS_CC); php_stream_bucket_delref(bucket TSRMLS_CC); } break; case PSFS_FEED_ME: /* need more data before we can push data through to the stream */ break; case PSFS_ERR_FATAL: /* some fatal error. Theoretically, the stream is borked, so all * further writes should fail. */ break; } return consumed; } PHPAPI int _php_stream_flush(php_stream *stream, int closing TSRMLS_DC) { int ret = 0; if (stream->writefilters.head) { _php_stream_write_filtered(stream, NULL, 0, closing ? PSFS_FLAG_FLUSH_CLOSE : PSFS_FLAG_FLUSH_INC TSRMLS_CC); } if (stream->ops->flush) { ret = stream->ops->flush(stream TSRMLS_CC); } return ret; } PHPAPI size_t _php_stream_write(php_stream *stream, const char *buf, size_t count TSRMLS_DC) { if (buf == NULL || count == 0 || stream->ops->write == NULL) { return 0; } if (stream->writefilters.head) { return _php_stream_write_filtered(stream, buf, count, PSFS_FLAG_NORMAL TSRMLS_CC); } else { return _php_stream_write_buffer(stream, buf, count TSRMLS_CC); } } PHPAPI size_t _php_stream_printf(php_stream *stream TSRMLS_DC, const char *fmt, ...) { size_t count; char *buf; va_list ap; va_start(ap, fmt); count = vspprintf(&buf, 0, fmt, ap); va_end(ap); if (!buf) { return 0; /* error condition */ } count = php_stream_write(stream, buf, count); efree(buf); return count; } PHPAPI off_t _php_stream_tell(php_stream *stream TSRMLS_DC) { return stream->position; } PHPAPI int _php_stream_seek(php_stream *stream, off_t offset, int whence TSRMLS_DC) { if (stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FOPENCOOKIE) { /* flush to commit data written to the fopencookie FILE* */ fflush(stream->stdiocast); } /* handle the case where we are in the buffer */ if ((stream->flags & PHP_STREAM_FLAG_NO_BUFFER) == 0) { switch(whence) { case SEEK_CUR: if (offset > 0 && offset <= stream->writepos - stream->readpos) { stream->readpos += offset; /* if offset = ..., then readpos = writepos */ stream->position += offset; stream->eof = 0; return 0; } break; case SEEK_SET: if (offset > stream->position && offset <= stream->position + stream->writepos - stream->readpos) { stream->readpos += offset - stream->position; stream->position = offset; stream->eof = 0; return 0; } break; } } if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) { int ret; if (stream->writefilters.head) { _php_stream_flush(stream, 0 TSRMLS_CC); } switch(whence) { case SEEK_CUR: offset = stream->position + offset; whence = SEEK_SET; break; } ret = stream->ops->seek(stream, offset, whence, &stream->position TSRMLS_CC); if (((stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) || ret == 0) { if (ret == 0) { stream->eof = 0; } /* invalidate the buffer contents */ stream->readpos = stream->writepos = 0; return ret; } /* else the stream has decided that it can't support seeking after all; * fall through to attempt emulation */ } /* emulate forward moving seeks with reads */ if (whence == SEEK_CUR && offset >= 0) { char tmp[1024]; size_t didread; while(offset > 0) { if ((didread = php_stream_read(stream, tmp, MIN(offset, sizeof(tmp)))) == 0) { return -1; } offset -= didread; } stream->eof = 0; return 0; } php_error_docref(NULL TSRMLS_CC, E_WARNING, "stream does not support seeking"); return -1; } PHPAPI int _php_stream_set_option(php_stream *stream, int option, int value, void *ptrparam TSRMLS_DC) { int ret = PHP_STREAM_OPTION_RETURN_NOTIMPL; if (stream->ops->set_option) { ret = stream->ops->set_option(stream, option, value, ptrparam TSRMLS_CC); } if (ret == PHP_STREAM_OPTION_RETURN_NOTIMPL) { switch(option) { case PHP_STREAM_OPTION_SET_CHUNK_SIZE: ret = stream->chunk_size; stream->chunk_size = value; return ret; case PHP_STREAM_OPTION_READ_BUFFER: /* try to match the buffer mode as best we can */ if (value == PHP_STREAM_BUFFER_NONE) { stream->flags |= PHP_STREAM_FLAG_NO_BUFFER; } else if (stream->flags & PHP_STREAM_FLAG_NO_BUFFER) { stream->flags ^= PHP_STREAM_FLAG_NO_BUFFER; } ret = PHP_STREAM_OPTION_RETURN_OK; break; default: ; } } return ret; } PHPAPI int _php_stream_truncate_set_size(php_stream *stream, size_t newsize TSRMLS_DC) { return php_stream_set_option(stream, PHP_STREAM_OPTION_TRUNCATE_API, PHP_STREAM_TRUNCATE_SET_SIZE, &newsize); } PHPAPI size_t _php_stream_passthru(php_stream * stream STREAMS_DC TSRMLS_DC) { size_t bcount = 0; char buf[8192]; int b; if (php_stream_mmap_possible(stream)) { char *p; size_t mapped; p = php_stream_mmap_range(stream, php_stream_tell(stream), PHP_STREAM_MMAP_ALL, PHP_STREAM_MAP_MODE_SHARED_READONLY, &mapped); if (p) { PHPWRITE(p, mapped); php_stream_mmap_unmap_ex(stream, mapped); return mapped; } } while ((b = php_stream_read(stream, buf, sizeof(buf))) > 0) { PHPWRITE(buf, b); bcount += b; } return bcount; } PHPAPI size_t _php_stream_copy_to_mem(php_stream *src, char **buf, size_t maxlen, int persistent STREAMS_DC TSRMLS_DC) { size_t ret = 0; char *ptr; size_t len = 0, max_len; int step = CHUNK_SIZE; int min_room = CHUNK_SIZE / 4; php_stream_statbuf ssbuf; if (maxlen == 0) { return 0; } if (maxlen == PHP_STREAM_COPY_ALL) { maxlen = 0; } if (maxlen > 0) { ptr = *buf = pemalloc_rel_orig(maxlen + 1, persistent); while ((len < maxlen) && !php_stream_eof(src)) { ret = php_stream_read(src, ptr, maxlen - len); if (!ret) { break; } len += ret; ptr += ret; } *ptr = '\0'; return len; } /* avoid many reallocs by allocating a good sized chunk to begin with, if * we can. Note that the stream may be filtered, in which case the stat * result may be inaccurate, as the filter may inflate or deflate the * number of bytes that we can read. In order to avoid an upsize followed * by a downsize of the buffer, overestimate by the step size (which is * 2K). */ if (php_stream_stat(src, &ssbuf) == 0 && ssbuf.sb.st_size > 0) { max_len = ssbuf.sb.st_size + step; } else { max_len = step; } ptr = *buf = pemalloc_rel_orig(max_len, persistent); while((ret = php_stream_read(src, ptr, max_len - len))) { len += ret; if (len + min_room >= max_len) { *buf = perealloc_rel_orig(*buf, max_len + step, persistent); max_len += step; ptr = *buf + len; } else { ptr += ret; } } if (len) { *buf = perealloc_rel_orig(*buf, len + 1, persistent); (*buf)[len] = '\0'; } else { pefree(*buf, persistent); *buf = NULL; } return len; } /* Returns SUCCESS/FAILURE and sets *len to the number of bytes moved */ PHPAPI int _php_stream_copy_to_stream_ex(php_stream *src, php_stream *dest, size_t maxlen, size_t *len STREAMS_DC TSRMLS_DC) { char buf[CHUNK_SIZE]; size_t readchunk; size_t haveread = 0; size_t didread; size_t dummy; php_stream_statbuf ssbuf; if (!len) { len = &dummy; } if (maxlen == 0) { *len = 0; return SUCCESS; } if (maxlen == PHP_STREAM_COPY_ALL) { maxlen = 0; } if (php_stream_stat(src, &ssbuf) == 0) { if (ssbuf.sb.st_size == 0 #ifdef S_ISREG && S_ISREG(ssbuf.sb.st_mode) #endif ) { *len = 0; return SUCCESS; } } if (php_stream_mmap_possible(src)) { char *p; size_t mapped; p = php_stream_mmap_range(src, php_stream_tell(src), maxlen, PHP_STREAM_MAP_MODE_SHARED_READONLY, &mapped); if (p) { mapped = php_stream_write(dest, p, mapped); php_stream_mmap_unmap_ex(src, mapped); *len = mapped; /* we've got at least 1 byte to read. * less than 1 is an error */ if (mapped > 0) { return SUCCESS; } return FAILURE; } } while(1) { readchunk = sizeof(buf); if (maxlen && (maxlen - haveread) < readchunk) { readchunk = maxlen - haveread; } didread = php_stream_read(src, buf, readchunk); if (didread) { /* extra paranoid */ size_t didwrite, towrite; char *writeptr; towrite = didread; writeptr = buf; haveread += didread; while(towrite) { didwrite = php_stream_write(dest, writeptr, towrite); if (didwrite == 0) { *len = haveread - (didread - towrite); return FAILURE; } towrite -= didwrite; writeptr += didwrite; } } else { break; } if (maxlen - haveread == 0) { break; } } *len = haveread; /* we've got at least 1 byte to read. * less than 1 is an error */ if (haveread > 0 || src->eof) { return SUCCESS; } return FAILURE; } /* Returns the number of bytes moved. * Returns 1 when source len is 0. * Deprecated in favor of php_stream_copy_to_stream_ex() */ ZEND_ATTRIBUTE_DEPRECATED PHPAPI size_t _php_stream_copy_to_stream(php_stream *src, php_stream *dest, size_t maxlen STREAMS_DC TSRMLS_DC) { size_t len; int ret = _php_stream_copy_to_stream_ex(src, dest, maxlen, &len STREAMS_REL_CC TSRMLS_CC); if (ret == SUCCESS && len == 0 && maxlen != 0) { return 1; } return len; } /* }}} */ /* {{{ wrapper init and registration */ static void stream_resource_regular_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC) { php_stream *stream = (php_stream*)rsrc->ptr; /* set the return value for pclose */ FG(pclose_ret) = php_stream_free(stream, PHP_STREAM_FREE_CLOSE | PHP_STREAM_FREE_RSRC_DTOR); } static void stream_resource_persistent_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC) { php_stream *stream = (php_stream*)rsrc->ptr; FG(pclose_ret) = php_stream_free(stream, PHP_STREAM_FREE_CLOSE | PHP_STREAM_FREE_RSRC_DTOR); } void php_shutdown_stream_hashes(TSRMLS_D) { if (FG(stream_wrappers)) { zend_hash_destroy(FG(stream_wrappers)); efree(FG(stream_wrappers)); FG(stream_wrappers) = NULL; } if (FG(stream_filters)) { zend_hash_destroy(FG(stream_filters)); efree(FG(stream_filters)); FG(stream_filters) = NULL; } } int php_init_stream_wrappers(int module_number TSRMLS_DC) { le_stream = zend_register_list_destructors_ex(stream_resource_regular_dtor, NULL, "stream", module_number); le_pstream = zend_register_list_destructors_ex(NULL, stream_resource_persistent_dtor, "persistent stream", module_number); /* Filters are cleaned up by the streams they're attached to */ le_stream_filter = zend_register_list_destructors_ex(NULL, NULL, "stream filter", module_number); return ( zend_hash_init(&url_stream_wrappers_hash, 0, NULL, NULL, 1) == SUCCESS && zend_hash_init(php_get_stream_filters_hash_global(), 0, NULL, NULL, 1) == SUCCESS && zend_hash_init(php_stream_xport_get_hash(), 0, NULL, NULL, 1) == SUCCESS && php_stream_xport_register("tcp", php_stream_generic_socket_factory TSRMLS_CC) == SUCCESS && php_stream_xport_register("udp", php_stream_generic_socket_factory TSRMLS_CC) == SUCCESS #if defined(AF_UNIX) && !(defined(PHP_WIN32) || defined(__riscos__) || defined(NETWARE)) && php_stream_xport_register("unix", php_stream_generic_socket_factory TSRMLS_CC) == SUCCESS && php_stream_xport_register("udg", php_stream_generic_socket_factory TSRMLS_CC) == SUCCESS #endif ) ? SUCCESS : FAILURE; } int php_shutdown_stream_wrappers(int module_number TSRMLS_DC) { zend_hash_destroy(&url_stream_wrappers_hash); zend_hash_destroy(php_get_stream_filters_hash_global()); zend_hash_destroy(php_stream_xport_get_hash()); return SUCCESS; } /* Validate protocol scheme names during registration * Must conform to /^[a-zA-Z0-9+.-]+$/ */ static inline int php_stream_wrapper_scheme_validate(char *protocol, int protocol_len) { int i; for(i = 0; i < protocol_len; i++) { if (!isalnum((int)protocol[i]) && protocol[i] != '+' && protocol[i] != '-' && protocol[i] != '.') { return FAILURE; } } return SUCCESS; } /* API for registering GLOBAL wrappers */ PHPAPI int php_register_url_stream_wrapper(char *protocol, php_stream_wrapper *wrapper TSRMLS_DC) { int protocol_len = strlen(protocol); if (php_stream_wrapper_scheme_validate(protocol, protocol_len) == FAILURE) { return FAILURE; } return zend_hash_add(&url_stream_wrappers_hash, protocol, protocol_len + 1, &wrapper, sizeof(wrapper), NULL); } PHPAPI int php_unregister_url_stream_wrapper(char *protocol TSRMLS_DC) { return zend_hash_del(&url_stream_wrappers_hash, protocol, strlen(protocol) + 1); } static void clone_wrapper_hash(TSRMLS_D) { php_stream_wrapper *tmp; ALLOC_HASHTABLE(FG(stream_wrappers)); zend_hash_init(FG(stream_wrappers), zend_hash_num_elements(&url_stream_wrappers_hash), NULL, NULL, 1); zend_hash_copy(FG(stream_wrappers), &url_stream_wrappers_hash, NULL, &tmp, sizeof(tmp)); } /* API for registering VOLATILE wrappers */ PHPAPI int php_register_url_stream_wrapper_volatile(char *protocol, php_stream_wrapper *wrapper TSRMLS_DC) { int protocol_len = strlen(protocol); if (php_stream_wrapper_scheme_validate(protocol, protocol_len) == FAILURE) { return FAILURE; } if (!FG(stream_wrappers)) { clone_wrapper_hash(TSRMLS_C); } return zend_hash_add(FG(stream_wrappers), protocol, protocol_len + 1, &wrapper, sizeof(wrapper), NULL); } PHPAPI int php_unregister_url_stream_wrapper_volatile(char *protocol TSRMLS_DC) { if (!FG(stream_wrappers)) { clone_wrapper_hash(TSRMLS_C); } return zend_hash_del(FG(stream_wrappers), protocol, strlen(protocol) + 1); } /* }}} */ /* {{{ php_stream_locate_url_wrapper */ PHPAPI php_stream_wrapper *php_stream_locate_url_wrapper(const char *path, char **path_for_open, int options TSRMLS_DC) { HashTable *wrapper_hash = (FG(stream_wrappers) ? FG(stream_wrappers) : &url_stream_wrappers_hash); php_stream_wrapper **wrapperpp = NULL; const char *p, *protocol = NULL; int n = 0; if (path_for_open) { *path_for_open = (char*)path; } if (options & IGNORE_URL) { return (options & STREAM_LOCATE_WRAPPERS_ONLY) ? NULL : &php_plain_files_wrapper; } for (p = path; isalnum((int)*p) || *p == '+' || *p == '-' || *p == '.'; p++) { n++; } if ((*p == ':') && (n > 1) && (!strncmp("//", p+1, 2) || (n == 4 && !memcmp("data:", path, 5)))) { protocol = path; } else if (n == 5 && strncasecmp(path, "zlib:", 5) == 0) { /* BC with older php scripts and zlib wrapper */ protocol = "compress.zlib"; n = 13; php_error_docref(NULL TSRMLS_CC, E_WARNING, "Use of \"zlib:\" wrapper is deprecated; please use \"compress.zlib://\" instead"); } if (protocol) { char *tmp = estrndup(protocol, n); if (FAILURE == zend_hash_find(wrapper_hash, (char*)tmp, n + 1, (void**)&wrapperpp)) { php_strtolower(tmp, n); if (FAILURE == zend_hash_find(wrapper_hash, (char*)tmp, n + 1, (void**)&wrapperpp)) { char wrapper_name[32]; if (n >= sizeof(wrapper_name)) { n = sizeof(wrapper_name) - 1; } PHP_STRLCPY(wrapper_name, protocol, sizeof(wrapper_name), n); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to find the wrapper \"%s\" - did you forget to enable it when you configured PHP?", wrapper_name); wrapperpp = NULL; protocol = NULL; } } efree(tmp); } /* TODO: curl based streams probably support file:// properly */ if (!protocol || !strncasecmp(protocol, "file", n)) { /* fall back on regular file access */ php_stream_wrapper *plain_files_wrapper = &php_plain_files_wrapper; if (protocol) { int localhost = 0; if (!strncasecmp(path, "file://localhost/", 17)) { localhost = 1; } #ifdef PHP_WIN32 if (localhost == 0 && path[n+3] != '\0' && path[n+3] != '/' && path[n+4] != ':') { #else if (localhost == 0 && path[n+3] != '\0' && path[n+3] != '/') { #endif if (options & REPORT_ERRORS) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "remote host file access not supported, %s", path); } return NULL; } if (path_for_open) { /* skip past protocol and :/, but handle windows correctly */ *path_for_open = (char*)path + n + 1; if (localhost == 1) { (*path_for_open) += 11; } while (*(++*path_for_open)=='/'); #ifdef PHP_WIN32 if (*(*path_for_open + 1) != ':') #endif (*path_for_open)--; } } if (options & STREAM_LOCATE_WRAPPERS_ONLY) { return NULL; } if (FG(stream_wrappers)) { /* The file:// wrapper may have been disabled/overridden */ if (wrapperpp) { /* It was found so go ahead and provide it */ return *wrapperpp; } /* Check again, the original check might have not known the protocol name */ if (zend_hash_find(wrapper_hash, "file", sizeof("file"), (void**)&wrapperpp) == SUCCESS) { return *wrapperpp; } if (options & REPORT_ERRORS) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "file:// wrapper is disabled in the server configuration"); } return NULL; } return plain_files_wrapper; } if (wrapperpp && (*wrapperpp)->is_url && (options & STREAM_DISABLE_URL_PROTECTION) == 0 && (!PG(allow_url_fopen) || (((options & STREAM_OPEN_FOR_INCLUDE) || PG(in_user_include)) && !PG(allow_url_include)))) { if (options & REPORT_ERRORS) { /* protocol[n] probably isn't '\0' */ char *protocol_dup = estrndup(protocol, n); if (!PG(allow_url_fopen)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s:// wrapper is disabled in the server configuration by allow_url_fopen=0", protocol_dup); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s:// wrapper is disabled in the server configuration by allow_url_include=0", protocol_dup); } efree(protocol_dup); } return NULL; } return *wrapperpp; } /* }}} */ /* {{{ _php_stream_mkdir */ PHPAPI int _php_stream_mkdir(char *path, int mode, int options, php_stream_context *context TSRMLS_DC) { php_stream_wrapper *wrapper = NULL; wrapper = php_stream_locate_url_wrapper(path, NULL, 0 TSRMLS_CC); if (!wrapper || !wrapper->wops || !wrapper->wops->stream_mkdir) { return 0; } return wrapper->wops->stream_mkdir(wrapper, path, mode, options, context TSRMLS_CC); } /* }}} */ /* {{{ _php_stream_rmdir */ PHPAPI int _php_stream_rmdir(char *path, int options, php_stream_context *context TSRMLS_DC) { php_stream_wrapper *wrapper = NULL; wrapper = php_stream_locate_url_wrapper(path, NULL, 0 TSRMLS_CC); if (!wrapper || !wrapper->wops || !wrapper->wops->stream_rmdir) { return 0; } return wrapper->wops->stream_rmdir(wrapper, path, options, context TSRMLS_CC); } /* }}} */ /* {{{ _php_stream_stat_path */ PHPAPI int _php_stream_stat_path(char *path, int flags, php_stream_statbuf *ssb, php_stream_context *context TSRMLS_DC) { php_stream_wrapper *wrapper = NULL; char *path_to_open = path; int ret; /* Try to hit the cache first */ if (flags & PHP_STREAM_URL_STAT_LINK) { if (BG(CurrentLStatFile) && strcmp(path, BG(CurrentLStatFile)) == 0) { memcpy(ssb, &BG(lssb), sizeof(php_stream_statbuf)); return 0; } } else { if (BG(CurrentStatFile) && strcmp(path, BG(CurrentStatFile)) == 0) { memcpy(ssb, &BG(ssb), sizeof(php_stream_statbuf)); return 0; } } wrapper = php_stream_locate_url_wrapper(path, &path_to_open, 0 TSRMLS_CC); if (wrapper && wrapper->wops->url_stat) { ret = wrapper->wops->url_stat(wrapper, path_to_open, flags, ssb, context TSRMLS_CC); if (ret == 0) { /* Drop into cache */ if (flags & PHP_STREAM_URL_STAT_LINK) { if (BG(CurrentLStatFile)) { efree(BG(CurrentLStatFile)); } BG(CurrentLStatFile) = estrdup(path); memcpy(&BG(lssb), ssb, sizeof(php_stream_statbuf)); } else { if (BG(CurrentStatFile)) { efree(BG(CurrentStatFile)); } BG(CurrentStatFile) = estrdup(path); memcpy(&BG(ssb), ssb, sizeof(php_stream_statbuf)); } } return ret; } return -1; } /* }}} */ /* {{{ php_stream_opendir */ PHPAPI php_stream *_php_stream_opendir(char *path, int options, php_stream_context *context STREAMS_DC TSRMLS_DC) { php_stream *stream = NULL; php_stream_wrapper *wrapper = NULL; char *path_to_open; if (!path || !*path) { return NULL; } path_to_open = path; wrapper = php_stream_locate_url_wrapper(path, &path_to_open, options TSRMLS_CC); if (wrapper && wrapper->wops->dir_opener) { stream = wrapper->wops->dir_opener(wrapper, path_to_open, "r", options ^ REPORT_ERRORS, NULL, context STREAMS_REL_CC TSRMLS_CC); if (stream) { stream->wrapper = wrapper; stream->flags |= PHP_STREAM_FLAG_NO_BUFFER | PHP_STREAM_FLAG_IS_DIR; } } else if (wrapper) { php_stream_wrapper_log_error(wrapper, options ^ REPORT_ERRORS TSRMLS_CC, "not implemented"); } if (stream == NULL && (options & REPORT_ERRORS)) { php_stream_display_wrapper_errors(wrapper, path, "failed to open dir" TSRMLS_CC); } php_stream_tidy_wrapper_error_log(wrapper TSRMLS_CC); return stream; } /* }}} */ /* {{{ _php_stream_readdir */ PHPAPI php_stream_dirent *_php_stream_readdir(php_stream *dirstream, php_stream_dirent *ent TSRMLS_DC) { if (sizeof(php_stream_dirent) == php_stream_read(dirstream, (char*)ent, sizeof(php_stream_dirent))) { return ent; } return NULL; } /* }}} */ /* {{{ php_stream_open_wrapper_ex */ PHPAPI php_stream *_php_stream_open_wrapper_ex(char *path, char *mode, int options, char **opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC) { php_stream *stream = NULL; php_stream_wrapper *wrapper = NULL; char *path_to_open; int persistent = options & STREAM_OPEN_PERSISTENT; char *resolved_path = NULL; char *copy_of_path = NULL; if (opened_path) { *opened_path = NULL; } if (!path || !*path) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Filename cannot be empty"); return NULL; } if (options & USE_PATH) { resolved_path = zend_resolve_path(path, strlen(path) TSRMLS_CC); if (resolved_path) { path = resolved_path; /* we've found this file, don't re-check include_path or run realpath */ options |= STREAM_ASSUME_REALPATH; options &= ~USE_PATH; } } path_to_open = path; wrapper = php_stream_locate_url_wrapper(path, &path_to_open, options TSRMLS_CC); if (options & STREAM_USE_URL && (!wrapper || !wrapper->is_url)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "This function may only be used against URLs"); if (resolved_path) { efree(resolved_path); } return NULL; } if (wrapper) { if (!wrapper->wops->stream_opener) { php_stream_wrapper_log_error(wrapper, options ^ REPORT_ERRORS TSRMLS_CC, "wrapper does not support stream open"); } else { stream = wrapper->wops->stream_opener(wrapper, path_to_open, mode, options ^ REPORT_ERRORS, opened_path, context STREAMS_REL_CC TSRMLS_CC); } /* if the caller asked for a persistent stream but the wrapper did not * return one, force an error here */ if (stream && (options & STREAM_OPEN_PERSISTENT) && !stream->is_persistent) { php_stream_wrapper_log_error(wrapper, options ^ REPORT_ERRORS TSRMLS_CC, "wrapper does not support persistent streams"); php_stream_close(stream); stream = NULL; } if (stream) { stream->wrapper = wrapper; } } if (stream) { if (opened_path && !*opened_path && resolved_path) { *opened_path = resolved_path; resolved_path = NULL; } if (stream->orig_path) { pefree(stream->orig_path, persistent); } copy_of_path = pestrdup(path, persistent); stream->orig_path = copy_of_path; #if ZEND_DEBUG stream->open_filename = __zend_orig_filename ? __zend_orig_filename : __zend_filename; stream->open_lineno = __zend_orig_lineno ? __zend_orig_lineno : __zend_lineno; #endif } if (stream != NULL && (options & STREAM_MUST_SEEK)) { php_stream *newstream; switch(php_stream_make_seekable_rel(stream, &newstream, (options & STREAM_WILL_CAST) ? PHP_STREAM_PREFER_STDIO : PHP_STREAM_NO_PREFERENCE)) { case PHP_STREAM_UNCHANGED: if (resolved_path) { efree(resolved_path); } return stream; case PHP_STREAM_RELEASED: if (newstream->orig_path) { pefree(newstream->orig_path, persistent); } newstream->orig_path = pestrdup(path, persistent); if (resolved_path) { efree(resolved_path); } return newstream; default: php_stream_close(stream); stream = NULL; if (options & REPORT_ERRORS) { char *tmp = estrdup(path); php_strip_url_passwd(tmp); php_error_docref1(NULL TSRMLS_CC, tmp, E_WARNING, "could not make seekable - %s", tmp); efree(tmp); options ^= REPORT_ERRORS; } } } if (stream && stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0 && strchr(mode, 'a') && stream->position == 0) { off_t newpos = 0; /* if opened for append, we need to revise our idea of the initial file position */ if (0 == stream->ops->seek(stream, 0, SEEK_CUR, &newpos TSRMLS_CC)) { stream->position = newpos; } } if (stream == NULL && (options & REPORT_ERRORS)) { php_stream_display_wrapper_errors(wrapper, path, "failed to open stream" TSRMLS_CC); if (opened_path && *opened_path) { efree(*opened_path); *opened_path = NULL; } } php_stream_tidy_wrapper_error_log(wrapper TSRMLS_CC); #if ZEND_DEBUG if (stream == NULL && copy_of_path != NULL) { pefree(copy_of_path, persistent); } #endif if (resolved_path) { efree(resolved_path); } return stream; } /* }}} */ /* {{{ context API */ PHPAPI php_stream_context *php_stream_context_set(php_stream *stream, php_stream_context *context) { php_stream_context *oldcontext = stream->context; TSRMLS_FETCH(); stream->context = context; if (context) { zend_list_addref(context->rsrc_id); } if (oldcontext) { zend_list_delete(oldcontext->rsrc_id); } return oldcontext; } PHPAPI void php_stream_notification_notify(php_stream_context *context, int notifycode, int severity, char *xmsg, int xcode, size_t bytes_sofar, size_t bytes_max, void * ptr TSRMLS_DC) { if (context && context->notifier) context->notifier->func(context, notifycode, severity, xmsg, xcode, bytes_sofar, bytes_max, ptr TSRMLS_CC); } PHPAPI void php_stream_context_free(php_stream_context *context) { if (context->options) { zval_ptr_dtor(&context->options); context->options = NULL; } if (context->notifier) { php_stream_notification_free(context->notifier); context->notifier = NULL; } if (context->links) { zval_ptr_dtor(&context->links); context->links = NULL; } efree(context); } PHPAPI php_stream_context *php_stream_context_alloc(TSRMLS_D) { php_stream_context *context; context = ecalloc(1, sizeof(php_stream_context)); context->notifier = NULL; MAKE_STD_ZVAL(context->options); array_init(context->options); context->rsrc_id = ZEND_REGISTER_RESOURCE(NULL, context, php_le_stream_context(TSRMLS_C)); return context; } PHPAPI php_stream_notifier *php_stream_notification_alloc(void) { return ecalloc(1, sizeof(php_stream_notifier)); } PHPAPI void php_stream_notification_free(php_stream_notifier *notifier) { if (notifier->dtor) { notifier->dtor(notifier); } efree(notifier); } PHPAPI int php_stream_context_get_option(php_stream_context *context, const char *wrappername, const char *optionname, zval ***optionvalue) { zval **wrapperhash; if (FAILURE == zend_hash_find(Z_ARRVAL_P(context->options), (char*)wrappername, strlen(wrappername)+1, (void**)&wrapperhash)) { return FAILURE; } return zend_hash_find(Z_ARRVAL_PP(wrapperhash), (char*)optionname, strlen(optionname)+1, (void**)optionvalue); } PHPAPI int php_stream_context_set_option(php_stream_context *context, const char *wrappername, const char *optionname, zval *optionvalue) { zval **wrapperhash; zval *category, *copied_val; ALLOC_INIT_ZVAL(copied_val); *copied_val = *optionvalue; zval_copy_ctor(copied_val); INIT_PZVAL(copied_val); if (FAILURE == zend_hash_find(Z_ARRVAL_P(context->options), (char*)wrappername, strlen(wrappername)+1, (void**)&wrapperhash)) { MAKE_STD_ZVAL(category); array_init(category); if (FAILURE == zend_hash_update(Z_ARRVAL_P(context->options), (char*)wrappername, strlen(wrappername)+1, (void**)&category, sizeof(zval *), NULL)) { return FAILURE; } wrapperhash = &category; } return zend_hash_update(Z_ARRVAL_PP(wrapperhash), (char*)optionname, strlen(optionname)+1, (void**)&copied_val, sizeof(zval *), NULL); } PHPAPI int php_stream_context_get_link(php_stream_context *context, const char *hostent, php_stream **stream) { php_stream **pstream; if (!stream || !hostent || !context || !(context->links)) { return FAILURE; } if (SUCCESS == zend_hash_find(Z_ARRVAL_P(context->links), (char*)hostent, strlen(hostent)+1, (void**)&pstream)) { *stream = *pstream; return SUCCESS; } return FAILURE; } PHPAPI int php_stream_context_set_link(php_stream_context *context, const char *hostent, php_stream *stream) { if (!context) { return FAILURE; } if (!context->links) { ALLOC_INIT_ZVAL(context->links); array_init(context->links); } if (!stream) { /* Delete any entry for <hostent> */ return zend_hash_del(Z_ARRVAL_P(context->links), (char*)hostent, strlen(hostent)+1); } return zend_hash_update(Z_ARRVAL_P(context->links), (char*)hostent, strlen(hostent)+1, (void**)&stream, sizeof(php_stream *), NULL); } PHPAPI int php_stream_context_del_link(php_stream_context *context, php_stream *stream) { php_stream **pstream; char *hostent; int ret = SUCCESS; if (!context || !context->links || !stream) { return FAILURE; } for(zend_hash_internal_pointer_reset(Z_ARRVAL_P(context->links)); SUCCESS == zend_hash_get_current_data(Z_ARRVAL_P(context->links), (void**)&pstream); zend_hash_move_forward(Z_ARRVAL_P(context->links))) { if (*pstream == stream) { if (SUCCESS == zend_hash_get_current_key(Z_ARRVAL_P(context->links), &hostent, NULL, 0)) { if (FAILURE == zend_hash_del(Z_ARRVAL_P(context->links), (char*)hostent, strlen(hostent)+1)) { ret = FAILURE; } } else { ret = FAILURE; } } } return ret; } /* }}} */ /* {{{ php_stream_dirent_alphasort */ PHPAPI int php_stream_dirent_alphasort(const char **a, const char **b) { return strcoll(*a, *b); } /* }}} */ /* {{{ php_stream_dirent_alphasortr */ PHPAPI int php_stream_dirent_alphasortr(const char **a, const char **b) { return strcoll(*b, *a); } /* }}} */ /* {{{ php_stream_scandir */ PHPAPI int _php_stream_scandir(char *dirname, char **namelist[], int flags, php_stream_context *context, int (*compare) (const char **a, const char **b) TSRMLS_DC) { php_stream *stream; php_stream_dirent sdp; char **vector = NULL; int vector_size = 0; int nfiles = 0; if (!namelist) { return FAILURE; } stream = php_stream_opendir(dirname, REPORT_ERRORS, context); if (!stream) { return FAILURE; } while (php_stream_readdir(stream, &sdp)) { if (nfiles == vector_size) { if (vector_size == 0) { vector_size = 10; } else { vector_size *= 2; } vector = (char **) erealloc(vector, vector_size * sizeof(char *)); } vector[nfiles] = estrdup(sdp.d_name); nfiles++; } php_stream_closedir(stream); *namelist = vector; if (compare) { qsort(*namelist, nfiles, sizeof(char *), (int(*)(const void *, const void *))compare); } return nfiles; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Wez Furlong <[email protected]> | | Borrowed code from: | | Rasmus Lerdorf <[email protected]> | | Jim Winstead <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #define _GNU_SOURCE #include "php.h" #include "php_globals.h" #include "php_network.h" #include "php_open_temporary_file.h" #include "ext/standard/file.h" #include "ext/standard/basic_functions.h" /* for BG(mmap_file) (not strictly required) */ #include "ext/standard/php_string.h" /* for php_memnstr, used by php_stream_get_record() */ #include <stddef.h> #include <fcntl.h> #include "php_streams_int.h" /* {{{ resource and registration code */ /* Global wrapper hash, copied to FG(stream_wrappers) on registration of volatile wrapper */ static HashTable url_stream_wrappers_hash; static int le_stream = FAILURE; /* true global */ static int le_pstream = FAILURE; /* true global */ static int le_stream_filter = FAILURE; /* true global */ PHPAPI int php_file_le_stream(void) { return le_stream; } PHPAPI int php_file_le_pstream(void) { return le_pstream; } PHPAPI int php_file_le_stream_filter(void) { return le_stream_filter; } PHPAPI HashTable *_php_stream_get_url_stream_wrappers_hash(TSRMLS_D) { return (FG(stream_wrappers) ? FG(stream_wrappers) : &url_stream_wrappers_hash); } PHPAPI HashTable *php_stream_get_url_stream_wrappers_hash_global(void) { return &url_stream_wrappers_hash; } static int _php_stream_release_context(zend_rsrc_list_entry *le, void *pContext TSRMLS_DC) { if (le->ptr == pContext) { return --le->refcount == 0; } return 0; } static int forget_persistent_resource_id_numbers(zend_rsrc_list_entry *rsrc TSRMLS_DC) { php_stream *stream; if (Z_TYPE_P(rsrc) != le_pstream) { return 0; } stream = (php_stream*)rsrc->ptr; #if STREAM_DEBUG fprintf(stderr, "forget_persistent: %s:%p\n", stream->ops->label, stream); #endif stream->rsrc_id = FAILURE; if (stream->context) { zend_hash_apply_with_argument(&EG(regular_list), (apply_func_arg_t) _php_stream_release_context, stream->context TSRMLS_CC); stream->context = NULL; } return 0; } PHP_RSHUTDOWN_FUNCTION(streams) { zend_hash_apply(&EG(persistent_list), (apply_func_t)forget_persistent_resource_id_numbers TSRMLS_CC); return SUCCESS; } PHPAPI php_stream *php_stream_encloses(php_stream *enclosing, php_stream *enclosed) { php_stream *orig = enclosed->enclosing_stream; php_stream_auto_cleanup(enclosed); enclosed->enclosing_stream = enclosing; return orig; } PHPAPI int php_stream_from_persistent_id(const char *persistent_id, php_stream **stream TSRMLS_DC) { zend_rsrc_list_entry *le; if (zend_hash_find(&EG(persistent_list), (char*)persistent_id, strlen(persistent_id)+1, (void*) &le) == SUCCESS) { if (Z_TYPE_P(le) == le_pstream) { if (stream) { HashPosition pos; zend_rsrc_list_entry *regentry; ulong index = -1; /* intentional */ /* see if this persistent resource already has been loaded to the * regular list; allowing the same resource in several entries in the * regular list causes trouble (see bug #54623) */ zend_hash_internal_pointer_reset_ex(&EG(regular_list), &pos); while (zend_hash_get_current_data_ex(&EG(regular_list), (void **)&regentry, &pos) == SUCCESS) { if (regentry->ptr == le->ptr) { zend_hash_get_current_key_ex(&EG(regular_list), NULL, NULL, &index, 0, &pos); break; } zend_hash_move_forward_ex(&EG(regular_list), &pos); } *stream = (php_stream*)le->ptr; if (index == -1) { /* not found in regular list */ le->refcount++; (*stream)->rsrc_id = ZEND_REGISTER_RESOURCE(NULL, *stream, le_pstream); } else { regentry->refcount++; (*stream)->rsrc_id = index; } } return PHP_STREAM_PERSISTENT_SUCCESS; } return PHP_STREAM_PERSISTENT_FAILURE; } return PHP_STREAM_PERSISTENT_NOT_EXIST; } /* }}} */ /* {{{ wrapper error reporting */ void php_stream_display_wrapper_errors(php_stream_wrapper *wrapper, const char *path, const char *caption TSRMLS_DC) { char *tmp = estrdup(path); char *msg; int free_msg = 0; php_stream_wrapper orig_wrapper; if (wrapper) { if (wrapper->err_count > 0) { int i; size_t l; int brlen; char *br; if (PG(html_errors)) { brlen = 7; br = "<br />\n"; } else { brlen = 1; br = "\n"; } for (i = 0, l = 0; i < wrapper->err_count; i++) { l += strlen(wrapper->err_stack[i]); if (i < wrapper->err_count - 1) { l += brlen; } } msg = emalloc(l + 1); msg[0] = '\0'; for (i = 0; i < wrapper->err_count; i++) { strcat(msg, wrapper->err_stack[i]); if (i < wrapper->err_count - 1) { strcat(msg, br); } } free_msg = 1; } else { if (wrapper == &php_plain_files_wrapper) { msg = strerror(errno); } else { msg = "operation failed"; } } } else { msg = "no suitable wrapper could be found"; } php_strip_url_passwd(tmp); if (wrapper) { /* see bug #52935 */ orig_wrapper = *wrapper; wrapper->err_stack = NULL; wrapper->err_count = 0; } php_error_docref1(NULL TSRMLS_CC, tmp, E_WARNING, "%s: %s", caption, msg); if (wrapper) { *wrapper = orig_wrapper; } efree(tmp); if (free_msg) { efree(msg); } } void php_stream_tidy_wrapper_error_log(php_stream_wrapper *wrapper TSRMLS_DC) { if (wrapper) { /* tidy up the error stack */ int i; for (i = 0; i < wrapper->err_count; i++) { efree(wrapper->err_stack[i]); } if (wrapper->err_stack) { efree(wrapper->err_stack); } wrapper->err_stack = NULL; wrapper->err_count = 0; } } PHPAPI void php_stream_wrapper_log_error(php_stream_wrapper *wrapper, int options TSRMLS_DC, const char *fmt, ...) { va_list args; char *buffer = NULL; va_start(args, fmt); vspprintf(&buffer, 0, fmt, args); va_end(args); if (options & REPORT_ERRORS || wrapper == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", buffer); efree(buffer); } else { /* append to stack */ wrapper->err_stack = erealloc(wrapper->err_stack, (wrapper->err_count + 1) * sizeof(char *)); if (wrapper->err_stack) { wrapper->err_stack[wrapper->err_count++] = buffer; } } } /* }}} */ /* allocate a new stream for a particular ops */ PHPAPI php_stream *_php_stream_alloc(php_stream_ops *ops, void *abstract, const char *persistent_id, const char *mode STREAMS_DC TSRMLS_DC) /* {{{ */ { php_stream *ret; ret = (php_stream*) pemalloc_rel_orig(sizeof(php_stream), persistent_id ? 1 : 0); memset(ret, 0, sizeof(php_stream)); ret->readfilters.stream = ret; ret->writefilters.stream = ret; #if STREAM_DEBUG fprintf(stderr, "stream_alloc: %s:%p persistent=%s\n", ops->label, ret, persistent_id); #endif ret->ops = ops; ret->abstract = abstract; ret->is_persistent = persistent_id ? 1 : 0; ret->chunk_size = FG(def_chunk_size); #if ZEND_DEBUG ret->open_filename = __zend_orig_filename ? __zend_orig_filename : __zend_filename; ret->open_lineno = __zend_orig_lineno ? __zend_orig_lineno : __zend_lineno; #endif if (FG(auto_detect_line_endings)) { ret->flags |= PHP_STREAM_FLAG_DETECT_EOL; } if (persistent_id) { zend_rsrc_list_entry le; Z_TYPE(le) = le_pstream; le.ptr = ret; le.refcount = 0; if (FAILURE == zend_hash_update(&EG(persistent_list), (char *)persistent_id, strlen(persistent_id) + 1, (void *)&le, sizeof(le), NULL)) { pefree(ret, 1); return NULL; } } ret->rsrc_id = ZEND_REGISTER_RESOURCE(NULL, ret, persistent_id ? le_pstream : le_stream); strlcpy(ret->mode, mode, sizeof(ret->mode)); ret->wrapper = NULL; ret->wrapperthis = NULL; ret->wrapperdata = NULL; ret->stdiocast = NULL; ret->orig_path = NULL; ret->context = NULL; ret->readbuf = NULL; ret->enclosing_stream = NULL; return ret; } /* }}} */ PHPAPI int _php_stream_free_enclosed(php_stream *stream_enclosed, int close_options TSRMLS_DC) /* {{{ */ { return _php_stream_free(stream_enclosed, close_options | PHP_STREAM_FREE_IGNORE_ENCLOSING TSRMLS_CC); } /* }}} */ #if STREAM_DEBUG static const char *_php_stream_pretty_free_options(int close_options, char *out) { if (close_options & PHP_STREAM_FREE_CALL_DTOR) strcat(out, "CALL_DTOR, "); if (close_options & PHP_STREAM_FREE_RELEASE_STREAM) strcat(out, "RELEASE_STREAM, "); if (close_options & PHP_STREAM_FREE_PRESERVE_HANDLE) strcat(out, "PREVERSE_HANDLE, "); if (close_options & PHP_STREAM_FREE_RSRC_DTOR) strcat(out, "RSRC_DTOR, "); if (close_options & PHP_STREAM_FREE_PERSISTENT) strcat(out, "PERSISTENT, "); if (close_options & PHP_STREAM_FREE_IGNORE_ENCLOSING) strcat(out, "IGNORE_ENCLOSING, "); if (out[0] != '\0') out[strlen(out) - 2] = '\0'; return out; } #endif static int _php_stream_free_persistent(zend_rsrc_list_entry *le, void *pStream TSRMLS_DC) { return le->ptr == pStream; } PHPAPI int _php_stream_free(php_stream *stream, int close_options TSRMLS_DC) /* {{{ */ { int ret = 1; int preserve_handle = close_options & PHP_STREAM_FREE_PRESERVE_HANDLE ? 1 : 0; int release_cast = 1; php_stream_context *context = stream->context; if (stream->flags & PHP_STREAM_FLAG_NO_CLOSE) { preserve_handle = 1; } #if STREAM_DEBUG { char out[200] = ""; fprintf(stderr, "stream_free: %s:%p[%s] in_free=%d opts=%s\n", stream->ops->label, stream, stream->orig_path, stream->in_free, _php_stream_pretty_free_options(close_options, out)); } #endif if (stream->in_free) { /* hopefully called recursively from the enclosing stream; the pointer was NULLed below */ if ((stream->in_free == 1) && (close_options & PHP_STREAM_FREE_IGNORE_ENCLOSING) && (stream->enclosing_stream == NULL)) { close_options |= PHP_STREAM_FREE_RSRC_DTOR; /* restore flag */ } else { return 1; /* recursion protection */ } } stream->in_free++; /* force correct order on enclosing/enclosed stream destruction (only from resource * destructor as in when reverse destroying the resource list) */ if ((close_options & PHP_STREAM_FREE_RSRC_DTOR) && !(close_options & PHP_STREAM_FREE_IGNORE_ENCLOSING) && (close_options & (PHP_STREAM_FREE_CALL_DTOR | PHP_STREAM_FREE_RELEASE_STREAM)) && /* always? */ (stream->enclosing_stream != NULL)) { php_stream *enclosing_stream = stream->enclosing_stream; stream->enclosing_stream = NULL; /* we force PHP_STREAM_CALL_DTOR because that's from where the * enclosing stream can free this stream. We remove rsrc_dtor because * we want the enclosing stream to be deleted from the resource list */ return _php_stream_free(enclosing_stream, (close_options | PHP_STREAM_FREE_CALL_DTOR) & ~PHP_STREAM_FREE_RSRC_DTOR TSRMLS_CC); } /* if we are releasing the stream only (and preserving the underlying handle), * we need to do things a little differently. * We are only ever called like this when the stream is cast to a FILE* * for include (or other similar) purposes. * */ if (preserve_handle) { if (stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FOPENCOOKIE) { /* If the stream was fopencookied, we must NOT touch anything * here, as the cookied stream relies on it all. * Instead, mark the stream as OK to auto-clean */ php_stream_auto_cleanup(stream); stream->in_free--; return 0; } /* otherwise, make sure that we don't close the FILE* from a cast */ release_cast = 0; } #if STREAM_DEBUG fprintf(stderr, "stream_free: %s:%p[%s] preserve_handle=%d release_cast=%d remove_rsrc=%d\n", stream->ops->label, stream, stream->orig_path, preserve_handle, release_cast, (close_options & PHP_STREAM_FREE_RSRC_DTOR) == 0); #endif /* make sure everything is saved */ _php_stream_flush(stream, 1 TSRMLS_CC); /* If not called from the resource dtor, remove the stream from the resource list. */ if ((close_options & PHP_STREAM_FREE_RSRC_DTOR) == 0) { /* zend_list_delete actually only decreases the refcount; if we're * releasing the stream, we want to actually delete the resource from * the resource list, otherwise the resource will point to invalid memory. * In any case, let's always completely delete it from the resource list, * not only when PHP_STREAM_FREE_RELEASE_STREAM is set */ while (zend_list_delete(stream->rsrc_id) == SUCCESS) {} } /* Remove stream from any context link list */ if (stream->context && stream->context->links) { php_stream_context_del_link(stream->context, stream); } if (close_options & PHP_STREAM_FREE_CALL_DTOR) { if (release_cast && stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FOPENCOOKIE) { /* calling fclose on an fopencookied stream will ultimately call this very same function. If we were called via fclose, the cookie_closer unsets the fclose_stdiocast flags, so we can be sure that we only reach here when PHP code calls php_stream_free. Lets let the cookie code clean it all up. */ stream->in_free = 0; return fclose(stream->stdiocast); } ret = stream->ops->close(stream, preserve_handle ? 0 : 1 TSRMLS_CC); stream->abstract = NULL; /* tidy up any FILE* that might have been fdopened */ if (release_cast && stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FDOPEN && stream->stdiocast) { fclose(stream->stdiocast); stream->stdiocast = NULL; stream->fclose_stdiocast = PHP_STREAM_FCLOSE_NONE; } } if (close_options & PHP_STREAM_FREE_RELEASE_STREAM) { while (stream->readfilters.head) { php_stream_filter_remove(stream->readfilters.head, 1 TSRMLS_CC); } while (stream->writefilters.head) { php_stream_filter_remove(stream->writefilters.head, 1 TSRMLS_CC); } if (stream->wrapper && stream->wrapper->wops && stream->wrapper->wops->stream_closer) { stream->wrapper->wops->stream_closer(stream->wrapper, stream TSRMLS_CC); stream->wrapper = NULL; } if (stream->wrapperdata) { zval_ptr_dtor(&stream->wrapperdata); stream->wrapperdata = NULL; } if (stream->readbuf) { pefree(stream->readbuf, stream->is_persistent); stream->readbuf = NULL; } if (stream->is_persistent && (close_options & PHP_STREAM_FREE_PERSISTENT)) { /* we don't work with *stream but need its value for comparison */ zend_hash_apply_with_argument(&EG(persistent_list), (apply_func_arg_t) _php_stream_free_persistent, stream TSRMLS_CC); } #if ZEND_DEBUG if ((close_options & PHP_STREAM_FREE_RSRC_DTOR) && (stream->__exposed == 0) && (EG(error_reporting) & E_WARNING)) { /* it leaked: Lets deliberately NOT pefree it so that the memory manager shows it * as leaked; it will log a warning, but lets help it out and display what kind * of stream it was. */ char *leakinfo; spprintf(&leakinfo, 0, __FILE__ "(%d) : Stream of type '%s' %p (path:%s) was not closed\n", __LINE__, stream->ops->label, stream, stream->orig_path); if (stream->orig_path) { pefree(stream->orig_path, stream->is_persistent); stream->orig_path = NULL; } # if defined(PHP_WIN32) OutputDebugString(leakinfo); # else fprintf(stderr, "%s", leakinfo); # endif efree(leakinfo); } else { if (stream->orig_path) { pefree(stream->orig_path, stream->is_persistent); stream->orig_path = NULL; } pefree(stream, stream->is_persistent); } #else if (stream->orig_path) { pefree(stream->orig_path, stream->is_persistent); stream->orig_path = NULL; } pefree(stream, stream->is_persistent); #endif } if (context) { zend_list_delete(context->rsrc_id); } return ret; } /* }}} */ /* {{{ generic stream operations */ static void php_stream_fill_read_buffer(php_stream *stream, size_t size TSRMLS_DC) { /* allocate/fill the buffer */ if (stream->readfilters.head) { char *chunk_buf; int err_flag = 0; php_stream_bucket_brigade brig_in = { NULL, NULL }, brig_out = { NULL, NULL }; php_stream_bucket_brigade *brig_inp = &brig_in, *brig_outp = &brig_out, *brig_swap; /* Invalidate the existing cache, otherwise reads can fail, see note in main/streams/filter.c::_php_stream_filter_append */ stream->writepos = stream->readpos = 0; /* allocate a buffer for reading chunks */ chunk_buf = emalloc(stream->chunk_size); while (!stream->eof && !err_flag && (stream->writepos - stream->readpos < (off_t)size)) { size_t justread = 0; int flags; php_stream_bucket *bucket; php_stream_filter_status_t status = PSFS_ERR_FATAL; php_stream_filter *filter; /* read a chunk into a bucket */ justread = stream->ops->read(stream, chunk_buf, stream->chunk_size TSRMLS_CC); if (justread && justread != (size_t)-1) { bucket = php_stream_bucket_new(stream, chunk_buf, justread, 0, 0 TSRMLS_CC); /* after this call, bucket is owned by the brigade */ php_stream_bucket_append(brig_inp, bucket TSRMLS_CC); flags = PSFS_FLAG_NORMAL; } else { flags = stream->eof ? PSFS_FLAG_FLUSH_CLOSE : PSFS_FLAG_FLUSH_INC; } /* wind the handle... */ for (filter = stream->readfilters.head; filter; filter = filter->next) { status = filter->fops->filter(stream, filter, brig_inp, brig_outp, NULL, flags TSRMLS_CC); if (status != PSFS_PASS_ON) { break; } /* brig_out becomes brig_in. * brig_in will always be empty here, as the filter MUST attach any un-consumed buckets * to its own brigade */ brig_swap = brig_inp; brig_inp = brig_outp; brig_outp = brig_swap; memset(brig_outp, 0, sizeof(*brig_outp)); } switch (status) { case PSFS_PASS_ON: /* we get here when the last filter in the chain has data to pass on. * in this situation, we are passing the brig_in brigade into the * stream read buffer */ while (brig_inp->head) { bucket = brig_inp->head; /* grow buffer to hold this bucket * TODO: this can fail for persistent streams */ if (stream->readbuflen - stream->writepos < bucket->buflen) { stream->readbuflen += bucket->buflen; stream->readbuf = perealloc(stream->readbuf, stream->readbuflen, stream->is_persistent); } memcpy(stream->readbuf + stream->writepos, bucket->buf, bucket->buflen); stream->writepos += bucket->buflen; php_stream_bucket_unlink(bucket TSRMLS_CC); php_stream_bucket_delref(bucket TSRMLS_CC); } break; case PSFS_FEED_ME: /* when a filter needs feeding, there is no brig_out to deal with. * we simply continue the loop; if the caller needs more data, * we will read again, otherwise out job is done here */ if (justread == 0) { /* there is no data */ err_flag = 1; break; } continue; case PSFS_ERR_FATAL: /* some fatal error. Theoretically, the stream is borked, so all * further reads should fail. */ err_flag = 1; break; } if (justread == 0 || justread == (size_t)-1) { break; } } efree(chunk_buf); } else { /* is there enough data in the buffer ? */ if (stream->writepos - stream->readpos < (off_t)size) { size_t justread = 0; /* reduce buffer memory consumption if possible, to avoid a realloc */ if (stream->readbuf && stream->readbuflen - stream->writepos < stream->chunk_size) { memmove(stream->readbuf, stream->readbuf + stream->readpos, stream->readbuflen - stream->readpos); stream->writepos -= stream->readpos; stream->readpos = 0; } /* grow the buffer if required * TODO: this can fail for persistent streams */ if (stream->readbuflen - stream->writepos < stream->chunk_size) { stream->readbuflen += stream->chunk_size; stream->readbuf = perealloc(stream->readbuf, stream->readbuflen, stream->is_persistent); } justread = stream->ops->read(stream, stream->readbuf + stream->writepos, stream->readbuflen - stream->writepos TSRMLS_CC); if (justread != (size_t)-1) { stream->writepos += justread; } } } } PHPAPI size_t _php_stream_read(php_stream *stream, char *buf, size_t size TSRMLS_DC) { size_t toread = 0, didread = 0; while (size > 0) { /* take from the read buffer first. * It is possible that a buffered stream was switched to non-buffered, so we * drain the remainder of the buffer before using the "raw" read mode for * the excess */ if (stream->writepos > stream->readpos) { toread = stream->writepos - stream->readpos; if (toread > size) { toread = size; } memcpy(buf, stream->readbuf + stream->readpos, toread); stream->readpos += toread; size -= toread; buf += toread; didread += toread; } /* ignore eof here; the underlying state might have changed */ if (size == 0) { break; } if (!stream->readfilters.head && (stream->flags & PHP_STREAM_FLAG_NO_BUFFER || stream->chunk_size == 1)) { toread = stream->ops->read(stream, buf, size TSRMLS_CC); } else { php_stream_fill_read_buffer(stream, size TSRMLS_CC); toread = stream->writepos - stream->readpos; if (toread > size) { toread = size; } if (toread > 0) { memcpy(buf, stream->readbuf + stream->readpos, toread); stream->readpos += toread; } } if (toread > 0) { didread += toread; buf += toread; size -= toread; } else { /* EOF, or temporary end of data (for non-blocking mode). */ break; } /* just break anyway, to avoid greedy read */ if (stream->wrapper != &php_plain_files_wrapper) { break; } } if (didread > 0) { stream->position += didread; } return didread; } PHPAPI int _php_stream_eof(php_stream *stream TSRMLS_DC) { /* if there is data in the buffer, it's not EOF */ if (stream->writepos - stream->readpos > 0) { return 0; } /* use the configured timeout when checking eof */ if (!stream->eof && PHP_STREAM_OPTION_RETURN_ERR == php_stream_set_option(stream, PHP_STREAM_OPTION_CHECK_LIVENESS, 0, NULL)) { stream->eof = 1; } return stream->eof; } PHPAPI int _php_stream_putc(php_stream *stream, int c TSRMLS_DC) { unsigned char buf = c; if (php_stream_write(stream, &buf, 1) > 0) { return 1; } return EOF; } PHPAPI int _php_stream_getc(php_stream *stream TSRMLS_DC) { char buf; if (php_stream_read(stream, &buf, 1) > 0) { return buf & 0xff; } return EOF; } PHPAPI int _php_stream_puts(php_stream *stream, char *buf TSRMLS_DC) { int len; char newline[2] = "\n"; /* is this OK for Win? */ len = strlen(buf); if (len > 0 && php_stream_write(stream, buf, len) && php_stream_write(stream, newline, 1)) { return 1; } return 0; } PHPAPI int _php_stream_stat(php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC) { memset(ssb, 0, sizeof(*ssb)); /* if the stream was wrapped, allow the wrapper to stat it */ if (stream->wrapper && stream->wrapper->wops->stream_stat != NULL) { return stream->wrapper->wops->stream_stat(stream->wrapper, stream, ssb TSRMLS_CC); } /* if the stream doesn't directly support stat-ing, return with failure. * We could try and emulate this by casting to a FD and fstat-ing it, * but since the fd might not represent the actual underlying content * this would give bogus results. */ if (stream->ops->stat == NULL) { return -1; } return (stream->ops->stat)(stream, ssb TSRMLS_CC); } PHPAPI char *php_stream_locate_eol(php_stream *stream, char *buf, size_t buf_len TSRMLS_DC) { size_t avail; char *cr, *lf, *eol = NULL; char *readptr; if (!buf) { readptr = stream->readbuf + stream->readpos; avail = stream->writepos - stream->readpos; } else { readptr = buf; avail = buf_len; } /* Look for EOL */ if (stream->flags & PHP_STREAM_FLAG_DETECT_EOL) { cr = memchr(readptr, '\r', avail); lf = memchr(readptr, '\n', avail); if (cr && lf != cr + 1 && !(lf && lf < cr)) { /* mac */ stream->flags ^= PHP_STREAM_FLAG_DETECT_EOL; stream->flags |= PHP_STREAM_FLAG_EOL_MAC; eol = cr; } else if ((cr && lf && cr == lf - 1) || (lf)) { /* dos or unix endings */ stream->flags ^= PHP_STREAM_FLAG_DETECT_EOL; eol = lf; } } else if (stream->flags & PHP_STREAM_FLAG_EOL_MAC) { eol = memchr(readptr, '\r', avail); } else { /* unix (and dos) line endings */ eol = memchr(readptr, '\n', avail); } return eol; } /* If buf == NULL, the buffer will be allocated automatically and will be of an * appropriate length to hold the line, regardless of the line length, memory * permitting */ PHPAPI char *_php_stream_get_line(php_stream *stream, char *buf, size_t maxlen, size_t *returned_len TSRMLS_DC) { size_t avail = 0; size_t current_buf_size = 0; size_t total_copied = 0; int grow_mode = 0; char *bufstart = buf; if (buf == NULL) { grow_mode = 1; } else if (maxlen == 0) { return NULL; } /* * If the underlying stream operations block when no new data is readable, * we need to take extra precautions. * * If there is buffered data available, we check for a EOL. If it exists, * we pass the data immediately back to the caller. This saves a call * to the read implementation and will not block where blocking * is not necessary at all. * * If the stream buffer contains more data than the caller requested, * we can also avoid that costly step and simply return that data. */ for (;;) { avail = stream->writepos - stream->readpos; if (avail > 0) { size_t cpysz = 0; char *readptr; char *eol; int done = 0; readptr = stream->readbuf + stream->readpos; eol = php_stream_locate_eol(stream, NULL, 0 TSRMLS_CC); if (eol) { cpysz = eol - readptr + 1; done = 1; } else { cpysz = avail; } if (grow_mode) { /* allow room for a NUL. If this realloc is really a realloc * (ie: second time around), we get an extra byte. In most * cases, with the default chunk size of 8K, we will only * incur that overhead once. When people have lines longer * than 8K, we waste 1 byte per additional 8K or so. * That seems acceptable to me, to avoid making this code * hard to follow */ bufstart = erealloc(bufstart, current_buf_size + cpysz + 1); current_buf_size += cpysz + 1; buf = bufstart + total_copied; } else { if (cpysz >= maxlen - 1) { cpysz = maxlen - 1; done = 1; } } memcpy(buf, readptr, cpysz); stream->position += cpysz; stream->readpos += cpysz; buf += cpysz; maxlen -= cpysz; total_copied += cpysz; if (done) { break; } } else if (stream->eof) { break; } else { /* XXX: Should be fine to always read chunk_size */ size_t toread; if (grow_mode) { toread = stream->chunk_size; } else { toread = maxlen - 1; if (toread > stream->chunk_size) { toread = stream->chunk_size; } } php_stream_fill_read_buffer(stream, toread TSRMLS_CC); if (stream->writepos - stream->readpos == 0) { break; } } } if (total_copied == 0) { if (grow_mode) { assert(bufstart == NULL); } return NULL; } buf[0] = '\0'; if (returned_len) { *returned_len = total_copied; } return bufstart; } PHPAPI char *php_stream_get_record(php_stream *stream, size_t maxlen, size_t *returned_len, char *delim, size_t delim_len TSRMLS_DC) { char *e, *buf; size_t toread, len; int skip = 0; len = stream->writepos - stream->readpos; /* make sure the stream read buffer has maxlen bytes */ while (len < maxlen) { size_t just_read; toread = MIN(maxlen - len, stream->chunk_size); php_stream_fill_read_buffer(stream, len + toread TSRMLS_CC); just_read = (stream->writepos - stream->readpos) - len; len += just_read; /* Assume the stream is temporarily or permanently out of data */ if (just_read == 0) { break; } } if (delim_len == 0 || !delim) { toread = maxlen; } else { size_t seek_len; /* set the maximum number of bytes we're allowed to read from buffer */ seek_len = stream->writepos - stream->readpos; if (seek_len > maxlen) { seek_len = maxlen; } if (delim_len == 1) { e = memchr(stream->readbuf + stream->readpos, *delim, seek_len); } else { e = php_memnstr(stream->readbuf + stream->readpos, delim, delim_len, (stream->readbuf + stream->readpos + seek_len)); } if (!e) { /* return with error if the delimiter string was not found, we * could not completely fill the read buffer with maxlen bytes * and we don't know we've reached end of file. Added with * non-blocking streams in mind, where this situation is frequent */ if (seek_len < maxlen && !stream->eof) { return NULL; } toread = maxlen; } else { toread = e - (char *) stream->readbuf - stream->readpos; /* we found the delimiter, so advance the read pointer past it */ skip = 1; } } if (toread > maxlen && maxlen > 0) { toread = maxlen; } buf = emalloc(toread + 1); *returned_len = php_stream_read(stream, buf, toread); if (skip) { stream->readpos += delim_len; stream->position += delim_len; } buf[*returned_len] = '\0'; return buf; } /* Writes a buffer directly to a stream, using multiple of the chunk size */ static size_t _php_stream_write_buffer(php_stream *stream, const char *buf, size_t count TSRMLS_DC) { size_t didwrite = 0, towrite, justwrote; /* if we have a seekable stream we need to ensure that data is written at the * current stream->position. This means invalidating the read buffer and then * performing a low-level seek */ if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0 && stream->readpos != stream->writepos) { stream->readpos = stream->writepos = 0; stream->ops->seek(stream, stream->position, SEEK_SET, &stream->position TSRMLS_CC); } while (count > 0) { towrite = count; if (towrite > stream->chunk_size) towrite = stream->chunk_size; justwrote = stream->ops->write(stream, buf, towrite TSRMLS_CC); /* convert justwrote to an integer, since normally it is unsigned */ if ((int)justwrote > 0) { buf += justwrote; count -= justwrote; didwrite += justwrote; /* Only screw with the buffer if we can seek, otherwise we lose data * buffered from fifos and sockets */ if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) { stream->position += justwrote; } } else { break; } } return didwrite; } /* push some data through the write filter chain. * buf may be NULL, if flags are set to indicate a flush. * This may trigger a real write to the stream. * Returns the number of bytes consumed from buf by the first filter in the chain. * */ static size_t _php_stream_write_filtered(php_stream *stream, const char *buf, size_t count, int flags TSRMLS_DC) { size_t consumed = 0; php_stream_bucket *bucket; php_stream_bucket_brigade brig_in = { NULL, NULL }, brig_out = { NULL, NULL }; php_stream_bucket_brigade *brig_inp = &brig_in, *brig_outp = &brig_out, *brig_swap; php_stream_filter_status_t status = PSFS_ERR_FATAL; php_stream_filter *filter; if (buf) { bucket = php_stream_bucket_new(stream, (char *)buf, count, 0, 0 TSRMLS_CC); php_stream_bucket_append(&brig_in, bucket TSRMLS_CC); } for (filter = stream->writefilters.head; filter; filter = filter->next) { /* for our return value, we are interested in the number of bytes consumed from * the first filter in the chain */ status = filter->fops->filter(stream, filter, brig_inp, brig_outp, filter == stream->writefilters.head ? &consumed : NULL, flags TSRMLS_CC); if (status != PSFS_PASS_ON) { break; } /* brig_out becomes brig_in. * brig_in will always be empty here, as the filter MUST attach any un-consumed buckets * to its own brigade */ brig_swap = brig_inp; brig_inp = brig_outp; brig_outp = brig_swap; memset(brig_outp, 0, sizeof(*brig_outp)); } switch (status) { case PSFS_PASS_ON: /* filter chain generated some output; push it through to the * underlying stream */ while (brig_inp->head) { bucket = brig_inp->head; _php_stream_write_buffer(stream, bucket->buf, bucket->buflen TSRMLS_CC); /* Potential error situation - eg: no space on device. Perhaps we should keep this brigade * hanging around and try to write it later. * At the moment, we just drop it on the floor * */ php_stream_bucket_unlink(bucket TSRMLS_CC); php_stream_bucket_delref(bucket TSRMLS_CC); } break; case PSFS_FEED_ME: /* need more data before we can push data through to the stream */ break; case PSFS_ERR_FATAL: /* some fatal error. Theoretically, the stream is borked, so all * further writes should fail. */ break; } return consumed; } PHPAPI int _php_stream_flush(php_stream *stream, int closing TSRMLS_DC) { int ret = 0; if (stream->writefilters.head) { _php_stream_write_filtered(stream, NULL, 0, closing ? PSFS_FLAG_FLUSH_CLOSE : PSFS_FLAG_FLUSH_INC TSRMLS_CC); } if (stream->ops->flush) { ret = stream->ops->flush(stream TSRMLS_CC); } return ret; } PHPAPI size_t _php_stream_write(php_stream *stream, const char *buf, size_t count TSRMLS_DC) { if (buf == NULL || count == 0 || stream->ops->write == NULL) { return 0; } if (stream->writefilters.head) { return _php_stream_write_filtered(stream, buf, count, PSFS_FLAG_NORMAL TSRMLS_CC); } else { return _php_stream_write_buffer(stream, buf, count TSRMLS_CC); } } PHPAPI size_t _php_stream_printf(php_stream *stream TSRMLS_DC, const char *fmt, ...) { size_t count; char *buf; va_list ap; va_start(ap, fmt); count = vspprintf(&buf, 0, fmt, ap); va_end(ap); if (!buf) { return 0; /* error condition */ } count = php_stream_write(stream, buf, count); efree(buf); return count; } PHPAPI off_t _php_stream_tell(php_stream *stream TSRMLS_DC) { return stream->position; } PHPAPI int _php_stream_seek(php_stream *stream, off_t offset, int whence TSRMLS_DC) { if (stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FOPENCOOKIE) { /* flush to commit data written to the fopencookie FILE* */ fflush(stream->stdiocast); } /* handle the case where we are in the buffer */ if ((stream->flags & PHP_STREAM_FLAG_NO_BUFFER) == 0) { switch(whence) { case SEEK_CUR: if (offset > 0 && offset <= stream->writepos - stream->readpos) { stream->readpos += offset; /* if offset = ..., then readpos = writepos */ stream->position += offset; stream->eof = 0; return 0; } break; case SEEK_SET: if (offset > stream->position && offset <= stream->position + stream->writepos - stream->readpos) { stream->readpos += offset - stream->position; stream->position = offset; stream->eof = 0; return 0; } break; } } if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) { int ret; if (stream->writefilters.head) { _php_stream_flush(stream, 0 TSRMLS_CC); } switch(whence) { case SEEK_CUR: offset = stream->position + offset; whence = SEEK_SET; break; } ret = stream->ops->seek(stream, offset, whence, &stream->position TSRMLS_CC); if (((stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) || ret == 0) { if (ret == 0) { stream->eof = 0; } /* invalidate the buffer contents */ stream->readpos = stream->writepos = 0; return ret; } /* else the stream has decided that it can't support seeking after all; * fall through to attempt emulation */ } /* emulate forward moving seeks with reads */ if (whence == SEEK_CUR && offset >= 0) { char tmp[1024]; size_t didread; while(offset > 0) { if ((didread = php_stream_read(stream, tmp, MIN(offset, sizeof(tmp)))) == 0) { return -1; } offset -= didread; } stream->eof = 0; return 0; } php_error_docref(NULL TSRMLS_CC, E_WARNING, "stream does not support seeking"); return -1; } PHPAPI int _php_stream_set_option(php_stream *stream, int option, int value, void *ptrparam TSRMLS_DC) { int ret = PHP_STREAM_OPTION_RETURN_NOTIMPL; if (stream->ops->set_option) { ret = stream->ops->set_option(stream, option, value, ptrparam TSRMLS_CC); } if (ret == PHP_STREAM_OPTION_RETURN_NOTIMPL) { switch(option) { case PHP_STREAM_OPTION_SET_CHUNK_SIZE: ret = stream->chunk_size; stream->chunk_size = value; return ret; case PHP_STREAM_OPTION_READ_BUFFER: /* try to match the buffer mode as best we can */ if (value == PHP_STREAM_BUFFER_NONE) { stream->flags |= PHP_STREAM_FLAG_NO_BUFFER; } else if (stream->flags & PHP_STREAM_FLAG_NO_BUFFER) { stream->flags ^= PHP_STREAM_FLAG_NO_BUFFER; } ret = PHP_STREAM_OPTION_RETURN_OK; break; default: ; } } return ret; } PHPAPI int _php_stream_truncate_set_size(php_stream *stream, size_t newsize TSRMLS_DC) { return php_stream_set_option(stream, PHP_STREAM_OPTION_TRUNCATE_API, PHP_STREAM_TRUNCATE_SET_SIZE, &newsize); } PHPAPI size_t _php_stream_passthru(php_stream * stream STREAMS_DC TSRMLS_DC) { size_t bcount = 0; char buf[8192]; int b; if (php_stream_mmap_possible(stream)) { char *p; size_t mapped; p = php_stream_mmap_range(stream, php_stream_tell(stream), PHP_STREAM_MMAP_ALL, PHP_STREAM_MAP_MODE_SHARED_READONLY, &mapped); if (p) { PHPWRITE(p, mapped); php_stream_mmap_unmap_ex(stream, mapped); return mapped; } } while ((b = php_stream_read(stream, buf, sizeof(buf))) > 0) { PHPWRITE(buf, b); bcount += b; } return bcount; } PHPAPI size_t _php_stream_copy_to_mem(php_stream *src, char **buf, size_t maxlen, int persistent STREAMS_DC TSRMLS_DC) { size_t ret = 0; char *ptr; size_t len = 0, max_len; int step = CHUNK_SIZE; int min_room = CHUNK_SIZE / 4; php_stream_statbuf ssbuf; if (maxlen == 0) { return 0; } if (maxlen == PHP_STREAM_COPY_ALL) { maxlen = 0; } if (maxlen > 0) { ptr = *buf = pemalloc_rel_orig(maxlen + 1, persistent); while ((len < maxlen) && !php_stream_eof(src)) { ret = php_stream_read(src, ptr, maxlen - len); if (!ret) { break; } len += ret; ptr += ret; } *ptr = '\0'; return len; } /* avoid many reallocs by allocating a good sized chunk to begin with, if * we can. Note that the stream may be filtered, in which case the stat * result may be inaccurate, as the filter may inflate or deflate the * number of bytes that we can read. In order to avoid an upsize followed * by a downsize of the buffer, overestimate by the step size (which is * 2K). */ if (php_stream_stat(src, &ssbuf) == 0 && ssbuf.sb.st_size > 0) { max_len = ssbuf.sb.st_size + step; } else { max_len = step; } ptr = *buf = pemalloc_rel_orig(max_len, persistent); while((ret = php_stream_read(src, ptr, max_len - len))) { len += ret; if (len + min_room >= max_len) { *buf = perealloc_rel_orig(*buf, max_len + step, persistent); max_len += step; ptr = *buf + len; } else { ptr += ret; } } if (len) { *buf = perealloc_rel_orig(*buf, len + 1, persistent); (*buf)[len] = '\0'; } else { pefree(*buf, persistent); *buf = NULL; } return len; } /* Returns SUCCESS/FAILURE and sets *len to the number of bytes moved */ PHPAPI int _php_stream_copy_to_stream_ex(php_stream *src, php_stream *dest, size_t maxlen, size_t *len STREAMS_DC TSRMLS_DC) { char buf[CHUNK_SIZE]; size_t readchunk; size_t haveread = 0; size_t didread; size_t dummy; php_stream_statbuf ssbuf; if (!len) { len = &dummy; } if (maxlen == 0) { *len = 0; return SUCCESS; } if (maxlen == PHP_STREAM_COPY_ALL) { maxlen = 0; } if (php_stream_stat(src, &ssbuf) == 0) { if (ssbuf.sb.st_size == 0 #ifdef S_ISREG && S_ISREG(ssbuf.sb.st_mode) #endif ) { *len = 0; return SUCCESS; } } if (php_stream_mmap_possible(src)) { char *p; size_t mapped; p = php_stream_mmap_range(src, php_stream_tell(src), maxlen, PHP_STREAM_MAP_MODE_SHARED_READONLY, &mapped); if (p) { mapped = php_stream_write(dest, p, mapped); php_stream_mmap_unmap_ex(src, mapped); *len = mapped; /* we've got at least 1 byte to read. * less than 1 is an error */ if (mapped > 0) { return SUCCESS; } return FAILURE; } } while(1) { readchunk = sizeof(buf); if (maxlen && (maxlen - haveread) < readchunk) { readchunk = maxlen - haveread; } didread = php_stream_read(src, buf, readchunk); if (didread) { /* extra paranoid */ size_t didwrite, towrite; char *writeptr; towrite = didread; writeptr = buf; haveread += didread; while(towrite) { didwrite = php_stream_write(dest, writeptr, towrite); if (didwrite == 0) { *len = haveread - (didread - towrite); return FAILURE; } towrite -= didwrite; writeptr += didwrite; } } else { break; } if (maxlen - haveread == 0) { break; } } *len = haveread; /* we've got at least 1 byte to read. * less than 1 is an error */ if (haveread > 0 || src->eof) { return SUCCESS; } return FAILURE; } /* Returns the number of bytes moved. * Returns 1 when source len is 0. * Deprecated in favor of php_stream_copy_to_stream_ex() */ ZEND_ATTRIBUTE_DEPRECATED PHPAPI size_t _php_stream_copy_to_stream(php_stream *src, php_stream *dest, size_t maxlen STREAMS_DC TSRMLS_DC) { size_t len; int ret = _php_stream_copy_to_stream_ex(src, dest, maxlen, &len STREAMS_REL_CC TSRMLS_CC); if (ret == SUCCESS && len == 0 && maxlen != 0) { return 1; } return len; } /* }}} */ /* {{{ wrapper init and registration */ static void stream_resource_regular_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC) { php_stream *stream = (php_stream*)rsrc->ptr; /* set the return value for pclose */ FG(pclose_ret) = php_stream_free(stream, PHP_STREAM_FREE_CLOSE | PHP_STREAM_FREE_RSRC_DTOR); } static void stream_resource_persistent_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC) { php_stream *stream = (php_stream*)rsrc->ptr; FG(pclose_ret) = php_stream_free(stream, PHP_STREAM_FREE_CLOSE | PHP_STREAM_FREE_RSRC_DTOR); } void php_shutdown_stream_hashes(TSRMLS_D) { if (FG(stream_wrappers)) { zend_hash_destroy(FG(stream_wrappers)); efree(FG(stream_wrappers)); FG(stream_wrappers) = NULL; } if (FG(stream_filters)) { zend_hash_destroy(FG(stream_filters)); efree(FG(stream_filters)); FG(stream_filters) = NULL; } } int php_init_stream_wrappers(int module_number TSRMLS_DC) { le_stream = zend_register_list_destructors_ex(stream_resource_regular_dtor, NULL, "stream", module_number); le_pstream = zend_register_list_destructors_ex(NULL, stream_resource_persistent_dtor, "persistent stream", module_number); /* Filters are cleaned up by the streams they're attached to */ le_stream_filter = zend_register_list_destructors_ex(NULL, NULL, "stream filter", module_number); return ( zend_hash_init(&url_stream_wrappers_hash, 0, NULL, NULL, 1) == SUCCESS && zend_hash_init(php_get_stream_filters_hash_global(), 0, NULL, NULL, 1) == SUCCESS && zend_hash_init(php_stream_xport_get_hash(), 0, NULL, NULL, 1) == SUCCESS && php_stream_xport_register("tcp", php_stream_generic_socket_factory TSRMLS_CC) == SUCCESS && php_stream_xport_register("udp", php_stream_generic_socket_factory TSRMLS_CC) == SUCCESS #if defined(AF_UNIX) && !(defined(PHP_WIN32) || defined(__riscos__) || defined(NETWARE)) && php_stream_xport_register("unix", php_stream_generic_socket_factory TSRMLS_CC) == SUCCESS && php_stream_xport_register("udg", php_stream_generic_socket_factory TSRMLS_CC) == SUCCESS #endif ) ? SUCCESS : FAILURE; } int php_shutdown_stream_wrappers(int module_number TSRMLS_DC) { zend_hash_destroy(&url_stream_wrappers_hash); zend_hash_destroy(php_get_stream_filters_hash_global()); zend_hash_destroy(php_stream_xport_get_hash()); return SUCCESS; } /* Validate protocol scheme names during registration * Must conform to /^[a-zA-Z0-9+.-]+$/ */ static inline int php_stream_wrapper_scheme_validate(char *protocol, int protocol_len) { int i; for(i = 0; i < protocol_len; i++) { if (!isalnum((int)protocol[i]) && protocol[i] != '+' && protocol[i] != '-' && protocol[i] != '.') { return FAILURE; } } return SUCCESS; } /* API for registering GLOBAL wrappers */ PHPAPI int php_register_url_stream_wrapper(char *protocol, php_stream_wrapper *wrapper TSRMLS_DC) { int protocol_len = strlen(protocol); if (php_stream_wrapper_scheme_validate(protocol, protocol_len) == FAILURE) { return FAILURE; } return zend_hash_add(&url_stream_wrappers_hash, protocol, protocol_len + 1, &wrapper, sizeof(wrapper), NULL); } PHPAPI int php_unregister_url_stream_wrapper(char *protocol TSRMLS_DC) { return zend_hash_del(&url_stream_wrappers_hash, protocol, strlen(protocol) + 1); } static void clone_wrapper_hash(TSRMLS_D) { php_stream_wrapper *tmp; ALLOC_HASHTABLE(FG(stream_wrappers)); zend_hash_init(FG(stream_wrappers), zend_hash_num_elements(&url_stream_wrappers_hash), NULL, NULL, 1); zend_hash_copy(FG(stream_wrappers), &url_stream_wrappers_hash, NULL, &tmp, sizeof(tmp)); } /* API for registering VOLATILE wrappers */ PHPAPI int php_register_url_stream_wrapper_volatile(char *protocol, php_stream_wrapper *wrapper TSRMLS_DC) { int protocol_len = strlen(protocol); if (php_stream_wrapper_scheme_validate(protocol, protocol_len) == FAILURE) { return FAILURE; } if (!FG(stream_wrappers)) { clone_wrapper_hash(TSRMLS_C); } return zend_hash_add(FG(stream_wrappers), protocol, protocol_len + 1, &wrapper, sizeof(wrapper), NULL); } PHPAPI int php_unregister_url_stream_wrapper_volatile(char *protocol TSRMLS_DC) { if (!FG(stream_wrappers)) { clone_wrapper_hash(TSRMLS_C); } return zend_hash_del(FG(stream_wrappers), protocol, strlen(protocol) + 1); } /* }}} */ /* {{{ php_stream_locate_url_wrapper */ PHPAPI php_stream_wrapper *php_stream_locate_url_wrapper(const char *path, char **path_for_open, int options TSRMLS_DC) { HashTable *wrapper_hash = (FG(stream_wrappers) ? FG(stream_wrappers) : &url_stream_wrappers_hash); php_stream_wrapper **wrapperpp = NULL; const char *p, *protocol = NULL; int n = 0; if (path_for_open) { *path_for_open = (char*)path; } if (options & IGNORE_URL) { return (options & STREAM_LOCATE_WRAPPERS_ONLY) ? NULL : &php_plain_files_wrapper; } for (p = path; isalnum((int)*p) || *p == '+' || *p == '-' || *p == '.'; p++) { n++; } if ((*p == ':') && (n > 1) && (!strncmp("//", p+1, 2) || (n == 4 && !memcmp("data:", path, 5)))) { protocol = path; } else if (n == 5 && strncasecmp(path, "zlib:", 5) == 0) { /* BC with older php scripts and zlib wrapper */ protocol = "compress.zlib"; n = 13; php_error_docref(NULL TSRMLS_CC, E_WARNING, "Use of \"zlib:\" wrapper is deprecated; please use \"compress.zlib://\" instead"); } if (protocol) { char *tmp = estrndup(protocol, n); if (FAILURE == zend_hash_find(wrapper_hash, (char*)tmp, n + 1, (void**)&wrapperpp)) { php_strtolower(tmp, n); if (FAILURE == zend_hash_find(wrapper_hash, (char*)tmp, n + 1, (void**)&wrapperpp)) { char wrapper_name[32]; if (n >= sizeof(wrapper_name)) { n = sizeof(wrapper_name) - 1; } PHP_STRLCPY(wrapper_name, protocol, sizeof(wrapper_name), n); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to find the wrapper \"%s\" - did you forget to enable it when you configured PHP?", wrapper_name); wrapperpp = NULL; protocol = NULL; } } efree(tmp); } /* TODO: curl based streams probably support file:// properly */ if (!protocol || !strncasecmp(protocol, "file", n)) { /* fall back on regular file access */ php_stream_wrapper *plain_files_wrapper = &php_plain_files_wrapper; if (protocol) { int localhost = 0; if (!strncasecmp(path, "file://localhost/", 17)) { localhost = 1; } #ifdef PHP_WIN32 if (localhost == 0 && path[n+3] != '\0' && path[n+3] != '/' && path[n+4] != ':') { #else if (localhost == 0 && path[n+3] != '\0' && path[n+3] != '/') { #endif if (options & REPORT_ERRORS) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "remote host file access not supported, %s", path); } return NULL; } if (path_for_open) { /* skip past protocol and :/, but handle windows correctly */ *path_for_open = (char*)path + n + 1; if (localhost == 1) { (*path_for_open) += 11; } while (*(++*path_for_open)=='/'); #ifdef PHP_WIN32 if (*(*path_for_open + 1) != ':') #endif (*path_for_open)--; } } if (options & STREAM_LOCATE_WRAPPERS_ONLY) { return NULL; } if (FG(stream_wrappers)) { /* The file:// wrapper may have been disabled/overridden */ if (wrapperpp) { /* It was found so go ahead and provide it */ return *wrapperpp; } /* Check again, the original check might have not known the protocol name */ if (zend_hash_find(wrapper_hash, "file", sizeof("file"), (void**)&wrapperpp) == SUCCESS) { return *wrapperpp; } if (options & REPORT_ERRORS) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "file:// wrapper is disabled in the server configuration"); } return NULL; } return plain_files_wrapper; } if (wrapperpp && (*wrapperpp)->is_url && (options & STREAM_DISABLE_URL_PROTECTION) == 0 && (!PG(allow_url_fopen) || (((options & STREAM_OPEN_FOR_INCLUDE) || PG(in_user_include)) && !PG(allow_url_include)))) { if (options & REPORT_ERRORS) { /* protocol[n] probably isn't '\0' */ char *protocol_dup = estrndup(protocol, n); if (!PG(allow_url_fopen)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s:// wrapper is disabled in the server configuration by allow_url_fopen=0", protocol_dup); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s:// wrapper is disabled in the server configuration by allow_url_include=0", protocol_dup); } efree(protocol_dup); } return NULL; } return *wrapperpp; } /* }}} */ /* {{{ _php_stream_mkdir */ PHPAPI int _php_stream_mkdir(char *path, int mode, int options, php_stream_context *context TSRMLS_DC) { php_stream_wrapper *wrapper = NULL; wrapper = php_stream_locate_url_wrapper(path, NULL, 0 TSRMLS_CC); if (!wrapper || !wrapper->wops || !wrapper->wops->stream_mkdir) { return 0; } return wrapper->wops->stream_mkdir(wrapper, path, mode, options, context TSRMLS_CC); } /* }}} */ /* {{{ _php_stream_rmdir */ PHPAPI int _php_stream_rmdir(char *path, int options, php_stream_context *context TSRMLS_DC) { php_stream_wrapper *wrapper = NULL; wrapper = php_stream_locate_url_wrapper(path, NULL, 0 TSRMLS_CC); if (!wrapper || !wrapper->wops || !wrapper->wops->stream_rmdir) { return 0; } return wrapper->wops->stream_rmdir(wrapper, path, options, context TSRMLS_CC); } /* }}} */ /* {{{ _php_stream_stat_path */ PHPAPI int _php_stream_stat_path(char *path, int flags, php_stream_statbuf *ssb, php_stream_context *context TSRMLS_DC) { php_stream_wrapper *wrapper = NULL; char *path_to_open = path; int ret; /* Try to hit the cache first */ if (flags & PHP_STREAM_URL_STAT_LINK) { if (BG(CurrentLStatFile) && strcmp(path, BG(CurrentLStatFile)) == 0) { memcpy(ssb, &BG(lssb), sizeof(php_stream_statbuf)); return 0; } } else { if (BG(CurrentStatFile) && strcmp(path, BG(CurrentStatFile)) == 0) { memcpy(ssb, &BG(ssb), sizeof(php_stream_statbuf)); return 0; } } wrapper = php_stream_locate_url_wrapper(path, &path_to_open, 0 TSRMLS_CC); if (wrapper && wrapper->wops->url_stat) { ret = wrapper->wops->url_stat(wrapper, path_to_open, flags, ssb, context TSRMLS_CC); if (ret == 0) { /* Drop into cache */ if (flags & PHP_STREAM_URL_STAT_LINK) { if (BG(CurrentLStatFile)) { efree(BG(CurrentLStatFile)); } BG(CurrentLStatFile) = estrdup(path); memcpy(&BG(lssb), ssb, sizeof(php_stream_statbuf)); } else { if (BG(CurrentStatFile)) { efree(BG(CurrentStatFile)); } BG(CurrentStatFile) = estrdup(path); memcpy(&BG(ssb), ssb, sizeof(php_stream_statbuf)); } } return ret; } return -1; } /* }}} */ /* {{{ php_stream_opendir */ PHPAPI php_stream *_php_stream_opendir(char *path, int options, php_stream_context *context STREAMS_DC TSRMLS_DC) { php_stream *stream = NULL; php_stream_wrapper *wrapper = NULL; char *path_to_open; if (!path || !*path) { return NULL; } path_to_open = path; wrapper = php_stream_locate_url_wrapper(path, &path_to_open, options TSRMLS_CC); if (wrapper && wrapper->wops->dir_opener) { stream = wrapper->wops->dir_opener(wrapper, path_to_open, "r", options ^ REPORT_ERRORS, NULL, context STREAMS_REL_CC TSRMLS_CC); if (stream) { stream->wrapper = wrapper; stream->flags |= PHP_STREAM_FLAG_NO_BUFFER | PHP_STREAM_FLAG_IS_DIR; } } else if (wrapper) { php_stream_wrapper_log_error(wrapper, options ^ REPORT_ERRORS TSRMLS_CC, "not implemented"); } if (stream == NULL && (options & REPORT_ERRORS)) { php_stream_display_wrapper_errors(wrapper, path, "failed to open dir" TSRMLS_CC); } php_stream_tidy_wrapper_error_log(wrapper TSRMLS_CC); return stream; } /* }}} */ /* {{{ _php_stream_readdir */ PHPAPI php_stream_dirent *_php_stream_readdir(php_stream *dirstream, php_stream_dirent *ent TSRMLS_DC) { if (sizeof(php_stream_dirent) == php_stream_read(dirstream, (char*)ent, sizeof(php_stream_dirent))) { return ent; } return NULL; } /* }}} */ /* {{{ php_stream_open_wrapper_ex */ PHPAPI php_stream *_php_stream_open_wrapper_ex(char *path, char *mode, int options, char **opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC) { php_stream *stream = NULL; php_stream_wrapper *wrapper = NULL; char *path_to_open; int persistent = options & STREAM_OPEN_PERSISTENT; char *resolved_path = NULL; char *copy_of_path = NULL; if (opened_path) { *opened_path = NULL; } if (!path || !*path) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Filename cannot be empty"); return NULL; } if (options & USE_PATH) { resolved_path = zend_resolve_path(path, strlen(path) TSRMLS_CC); if (resolved_path) { path = resolved_path; /* we've found this file, don't re-check include_path or run realpath */ options |= STREAM_ASSUME_REALPATH; options &= ~USE_PATH; } } path_to_open = path; wrapper = php_stream_locate_url_wrapper(path, &path_to_open, options TSRMLS_CC); if (options & STREAM_USE_URL && (!wrapper || !wrapper->is_url)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "This function may only be used against URLs"); if (resolved_path) { efree(resolved_path); } return NULL; } if (wrapper) { if (!wrapper->wops->stream_opener) { php_stream_wrapper_log_error(wrapper, options ^ REPORT_ERRORS TSRMLS_CC, "wrapper does not support stream open"); } else { stream = wrapper->wops->stream_opener(wrapper, path_to_open, mode, options ^ REPORT_ERRORS, opened_path, context STREAMS_REL_CC TSRMLS_CC); } /* if the caller asked for a persistent stream but the wrapper did not * return one, force an error here */ if (stream && (options & STREAM_OPEN_PERSISTENT) && !stream->is_persistent) { php_stream_wrapper_log_error(wrapper, options ^ REPORT_ERRORS TSRMLS_CC, "wrapper does not support persistent streams"); php_stream_close(stream); stream = NULL; } if (stream) { stream->wrapper = wrapper; } } if (stream) { if (opened_path && !*opened_path && resolved_path) { *opened_path = resolved_path; resolved_path = NULL; } if (stream->orig_path) { pefree(stream->orig_path, persistent); } copy_of_path = pestrdup(path, persistent); stream->orig_path = copy_of_path; #if ZEND_DEBUG stream->open_filename = __zend_orig_filename ? __zend_orig_filename : __zend_filename; stream->open_lineno = __zend_orig_lineno ? __zend_orig_lineno : __zend_lineno; #endif } if (stream != NULL && (options & STREAM_MUST_SEEK)) { php_stream *newstream; switch(php_stream_make_seekable_rel(stream, &newstream, (options & STREAM_WILL_CAST) ? PHP_STREAM_PREFER_STDIO : PHP_STREAM_NO_PREFERENCE)) { case PHP_STREAM_UNCHANGED: if (resolved_path) { efree(resolved_path); } return stream; case PHP_STREAM_RELEASED: if (newstream->orig_path) { pefree(newstream->orig_path, persistent); } newstream->orig_path = pestrdup(path, persistent); if (resolved_path) { efree(resolved_path); } return newstream; default: php_stream_close(stream); stream = NULL; if (options & REPORT_ERRORS) { char *tmp = estrdup(path); php_strip_url_passwd(tmp); php_error_docref1(NULL TSRMLS_CC, tmp, E_WARNING, "could not make seekable - %s", tmp); efree(tmp); options ^= REPORT_ERRORS; } } } if (stream && stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0 && strchr(mode, 'a') && stream->position == 0) { off_t newpos = 0; /* if opened for append, we need to revise our idea of the initial file position */ if (0 == stream->ops->seek(stream, 0, SEEK_CUR, &newpos TSRMLS_CC)) { stream->position = newpos; } } if (stream == NULL && (options & REPORT_ERRORS)) { php_stream_display_wrapper_errors(wrapper, path, "failed to open stream" TSRMLS_CC); if (opened_path && *opened_path) { efree(*opened_path); *opened_path = NULL; } } php_stream_tidy_wrapper_error_log(wrapper TSRMLS_CC); #if ZEND_DEBUG if (stream == NULL && copy_of_path != NULL) { pefree(copy_of_path, persistent); } #endif if (resolved_path) { efree(resolved_path); } return stream; } /* }}} */ /* {{{ context API */ PHPAPI php_stream_context *php_stream_context_set(php_stream *stream, php_stream_context *context) { php_stream_context *oldcontext = stream->context; TSRMLS_FETCH(); stream->context = context; if (context) { zend_list_addref(context->rsrc_id); } if (oldcontext) { zend_list_delete(oldcontext->rsrc_id); } return oldcontext; } PHPAPI void php_stream_notification_notify(php_stream_context *context, int notifycode, int severity, char *xmsg, int xcode, size_t bytes_sofar, size_t bytes_max, void * ptr TSRMLS_DC) { if (context && context->notifier) context->notifier->func(context, notifycode, severity, xmsg, xcode, bytes_sofar, bytes_max, ptr TSRMLS_CC); } PHPAPI void php_stream_context_free(php_stream_context *context) { if (context->options) { zval_ptr_dtor(&context->options); context->options = NULL; } if (context->notifier) { php_stream_notification_free(context->notifier); context->notifier = NULL; } if (context->links) { zval_ptr_dtor(&context->links); context->links = NULL; } efree(context); } PHPAPI php_stream_context *php_stream_context_alloc(TSRMLS_D) { php_stream_context *context; context = ecalloc(1, sizeof(php_stream_context)); context->notifier = NULL; MAKE_STD_ZVAL(context->options); array_init(context->options); context->rsrc_id = ZEND_REGISTER_RESOURCE(NULL, context, php_le_stream_context(TSRMLS_C)); return context; } PHPAPI php_stream_notifier *php_stream_notification_alloc(void) { return ecalloc(1, sizeof(php_stream_notifier)); } PHPAPI void php_stream_notification_free(php_stream_notifier *notifier) { if (notifier->dtor) { notifier->dtor(notifier); } efree(notifier); } PHPAPI int php_stream_context_get_option(php_stream_context *context, const char *wrappername, const char *optionname, zval ***optionvalue) { zval **wrapperhash; if (FAILURE == zend_hash_find(Z_ARRVAL_P(context->options), (char*)wrappername, strlen(wrappername)+1, (void**)&wrapperhash)) { return FAILURE; } return zend_hash_find(Z_ARRVAL_PP(wrapperhash), (char*)optionname, strlen(optionname)+1, (void**)optionvalue); } PHPAPI int php_stream_context_set_option(php_stream_context *context, const char *wrappername, const char *optionname, zval *optionvalue) { zval **wrapperhash; zval *category, *copied_val; ALLOC_INIT_ZVAL(copied_val); *copied_val = *optionvalue; zval_copy_ctor(copied_val); INIT_PZVAL(copied_val); if (FAILURE == zend_hash_find(Z_ARRVAL_P(context->options), (char*)wrappername, strlen(wrappername)+1, (void**)&wrapperhash)) { MAKE_STD_ZVAL(category); array_init(category); if (FAILURE == zend_hash_update(Z_ARRVAL_P(context->options), (char*)wrappername, strlen(wrappername)+1, (void**)&category, sizeof(zval *), NULL)) { return FAILURE; } wrapperhash = &category; } return zend_hash_update(Z_ARRVAL_PP(wrapperhash), (char*)optionname, strlen(optionname)+1, (void**)&copied_val, sizeof(zval *), NULL); } PHPAPI int php_stream_context_get_link(php_stream_context *context, const char *hostent, php_stream **stream) { php_stream **pstream; if (!stream || !hostent || !context || !(context->links)) { return FAILURE; } if (SUCCESS == zend_hash_find(Z_ARRVAL_P(context->links), (char*)hostent, strlen(hostent)+1, (void**)&pstream)) { *stream = *pstream; return SUCCESS; } return FAILURE; } PHPAPI int php_stream_context_set_link(php_stream_context *context, const char *hostent, php_stream *stream) { if (!context) { return FAILURE; } if (!context->links) { ALLOC_INIT_ZVAL(context->links); array_init(context->links); } if (!stream) { /* Delete any entry for <hostent> */ return zend_hash_del(Z_ARRVAL_P(context->links), (char*)hostent, strlen(hostent)+1); } return zend_hash_update(Z_ARRVAL_P(context->links), (char*)hostent, strlen(hostent)+1, (void**)&stream, sizeof(php_stream *), NULL); } PHPAPI int php_stream_context_del_link(php_stream_context *context, php_stream *stream) { php_stream **pstream; char *hostent; int ret = SUCCESS; if (!context || !context->links || !stream) { return FAILURE; } for(zend_hash_internal_pointer_reset(Z_ARRVAL_P(context->links)); SUCCESS == zend_hash_get_current_data(Z_ARRVAL_P(context->links), (void**)&pstream); zend_hash_move_forward(Z_ARRVAL_P(context->links))) { if (*pstream == stream) { if (SUCCESS == zend_hash_get_current_key(Z_ARRVAL_P(context->links), &hostent, NULL, 0)) { if (FAILURE == zend_hash_del(Z_ARRVAL_P(context->links), (char*)hostent, strlen(hostent)+1)) { ret = FAILURE; } } else { ret = FAILURE; } } } return ret; } /* }}} */ /* {{{ php_stream_dirent_alphasort */ PHPAPI int php_stream_dirent_alphasort(const char **a, const char **b) { return strcoll(*a, *b); } /* }}} */ /* {{{ php_stream_dirent_alphasortr */ PHPAPI int php_stream_dirent_alphasortr(const char **a, const char **b) { return strcoll(*b, *a); } /* }}} */ /* {{{ php_stream_scandir */ PHPAPI int _php_stream_scandir(char *dirname, char **namelist[], int flags, php_stream_context *context, int (*compare) (const char **a, const char **b) TSRMLS_DC) { php_stream *stream; php_stream_dirent sdp; char **vector = NULL; int vector_size = 0; int nfiles = 0; if (!namelist) { return FAILURE; } stream = php_stream_opendir(dirname, REPORT_ERRORS, context); if (!stream) { return FAILURE; } while (php_stream_readdir(stream, &sdp)) { if (nfiles == vector_size) { if (vector_size == 0) { vector_size = 10; } else { vector_size *= 2; } vector = (char **) erealloc(vector, vector_size * sizeof(char *)); } vector[nfiles] = estrdup(sdp.d_name); nfiles++; } php_stream_closedir(stream); *namelist = vector; if (compare) { qsort(*namelist, nfiles, sizeof(char *), (int(*)(const void *, const void *))compare); } return nfiles; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-12-10-74343ca506-52c36e60c4.c
manybugs_data_38
/* Generated by re2c 0.13.5 on Tue Jan 17 11:54:12 2012 */ #line 1 "Zend/zend_language_scanner.l" /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2012 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Marcus Boerger <[email protected]> | | Nuno Lopes <[email protected]> | | Scott MacVicar <[email protected]> | | Flex version authors: | | Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #if 0 # define YYDEBUG(s, c) printf("state: %d char: %c\n", s, c) #else # define YYDEBUG(s, c) #endif #include "zend_language_scanner_defs.h" #include <errno.h> #include "zend.h" #include "zend_alloc.h" #include <zend_language_parser.h> #include "zend_compile.h" #include "zend_language_scanner.h" #include "zend_highlight.h" #include "zend_constants.h" #include "zend_variables.h" #include "zend_operators.h" #include "zend_API.h" #include "zend_strtod.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "tsrm_config_common.h" #define YYCTYPE unsigned char #define YYFILL(n) { if ((YYCURSOR + n) >= (YYLIMIT + ZEND_MMAP_AHEAD)) { return 0; } } #define YYCURSOR SCNG(yy_cursor) #define YYLIMIT SCNG(yy_limit) #define YYMARKER SCNG(yy_marker) #define YYGETCONDITION() SCNG(yy_state) #define YYSETCONDITION(s) SCNG(yy_state) = s #define STATE(name) yyc##name /* emulate flex constructs */ #define BEGIN(state) YYSETCONDITION(STATE(state)) #define YYSTATE YYGETCONDITION() #define yytext ((char*)SCNG(yy_text)) #define yyleng SCNG(yy_leng) #define yyless(x) do { YYCURSOR = (unsigned char*)yytext + x; \ yyleng = (unsigned int)x; } while(0) #define yymore() goto yymore_restart /* perform sanity check. If this message is triggered you should increase the ZEND_MMAP_AHEAD value in the zend_streams.h file */ #define YYMAXFILL 16 #if ZEND_MMAP_AHEAD < YYMAXFILL # error ZEND_MMAP_AHEAD should be greater than or equal to YYMAXFILL #endif #ifdef HAVE_STDARG_H # include <stdarg.h> #endif #ifdef HAVE_UNISTD_H # include <unistd.h> #endif /* Globals Macros */ #define SCNG LANG_SCNG #ifdef ZTS ZEND_API ts_rsrc_id language_scanner_globals_id; #else ZEND_API zend_php_scanner_globals language_scanner_globals; #endif #define HANDLE_NEWLINES(s, l) \ do { \ char *p = (s), *boundary = p+(l); \ \ while (p<boundary) { \ if (*p == '\n' || (*p == '\r' && (*(p+1) != '\n'))) { \ CG(zend_lineno)++; \ } \ p++; \ } \ } while (0) #define HANDLE_NEWLINE(c) \ { \ if (c == '\n' || c == '\r') { \ CG(zend_lineno)++; \ } \ } /* To save initial string length after scanning to first variable, CG(doc_comment_len) can be reused */ #define SET_DOUBLE_QUOTES_SCANNED_LENGTH(len) CG(doc_comment_len) = (len) #define GET_DOUBLE_QUOTES_SCANNED_LENGTH() CG(doc_comment_len) #define IS_LABEL_START(c) (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z') || (c) == '_' || (c) >= 0x7F) #define ZEND_IS_OCT(c) ((c)>='0' && (c)<='7') #define ZEND_IS_HEX(c) (((c)>='0' && (c)<='9') || ((c)>='a' && (c)<='f') || ((c)>='A' && (c)<='F')) BEGIN_EXTERN_C() static size_t encoding_filter_script_to_internal(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) { const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding(TSRMLS_C); assert(internal_encoding && zend_multibyte_check_lexer_compatibility(internal_encoding)); return zend_multibyte_encoding_converter(to, to_length, from, from_length, internal_encoding, LANG_SCNG(script_encoding) TSRMLS_CC); } static size_t encoding_filter_script_to_intermediate(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) { return zend_multibyte_encoding_converter(to, to_length, from, from_length, zend_multibyte_encoding_utf8, LANG_SCNG(script_encoding) TSRMLS_CC); } static size_t encoding_filter_intermediate_to_script(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) { return zend_multibyte_encoding_converter(to, to_length, from, from_length, LANG_SCNG(script_encoding), zend_multibyte_encoding_utf8 TSRMLS_CC); } static size_t encoding_filter_intermediate_to_internal(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) { const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding(TSRMLS_C); assert(internal_encoding && zend_multibyte_check_lexer_compatibility(internal_encoding)); return zend_multibyte_encoding_converter(to, to_length, from, from_length, internal_encoding, zend_multibyte_encoding_utf8 TSRMLS_CC); } static void _yy_push_state(int new_state TSRMLS_DC) { zend_stack_push(&SCNG(state_stack), (void *) &YYGETCONDITION(), sizeof(int)); YYSETCONDITION(new_state); } #define yy_push_state(state_and_tsrm) _yy_push_state(yyc##state_and_tsrm) static void yy_pop_state(TSRMLS_D) { int *stack_state; zend_stack_top(&SCNG(state_stack), (void **) &stack_state); YYSETCONDITION(*stack_state); zend_stack_del_top(&SCNG(state_stack)); } static void yy_scan_buffer(char *str, unsigned int len TSRMLS_DC) { YYCURSOR = (YYCTYPE*)str; YYLIMIT = YYCURSOR + len; if (!SCNG(yy_start)) { SCNG(yy_start) = YYCURSOR; } } void startup_scanner(TSRMLS_D) { CG(parse_error) = 0; CG(heredoc) = NULL; CG(heredoc_len) = 0; CG(doc_comment) = NULL; CG(doc_comment_len) = 0; zend_stack_init(&SCNG(state_stack)); } void shutdown_scanner(TSRMLS_D) { if (CG(heredoc)) { efree(CG(heredoc)); CG(heredoc_len)=0; } CG(parse_error) = 0; zend_stack_destroy(&SCNG(state_stack)); RESET_DOC_COMMENT(); } ZEND_API void zend_save_lexical_state(zend_lex_state *lex_state TSRMLS_DC) { lex_state->yy_leng = SCNG(yy_leng); lex_state->yy_start = SCNG(yy_start); lex_state->yy_text = SCNG(yy_text); lex_state->yy_cursor = SCNG(yy_cursor); lex_state->yy_marker = SCNG(yy_marker); lex_state->yy_limit = SCNG(yy_limit); lex_state->state_stack = SCNG(state_stack); zend_stack_init(&SCNG(state_stack)); lex_state->in = SCNG(yy_in); lex_state->yy_state = YYSTATE; lex_state->filename = zend_get_compiled_filename(TSRMLS_C); lex_state->lineno = CG(zend_lineno); lex_state->script_org = SCNG(script_org); lex_state->script_org_size = SCNG(script_org_size); lex_state->script_filtered = SCNG(script_filtered); lex_state->script_filtered_size = SCNG(script_filtered_size); lex_state->input_filter = SCNG(input_filter); lex_state->output_filter = SCNG(output_filter); lex_state->script_encoding = SCNG(script_encoding); } ZEND_API void zend_restore_lexical_state(zend_lex_state *lex_state TSRMLS_DC) { SCNG(yy_leng) = lex_state->yy_leng; SCNG(yy_start) = lex_state->yy_start; SCNG(yy_text) = lex_state->yy_text; SCNG(yy_cursor) = lex_state->yy_cursor; SCNG(yy_marker) = lex_state->yy_marker; SCNG(yy_limit) = lex_state->yy_limit; zend_stack_destroy(&SCNG(state_stack)); SCNG(state_stack) = lex_state->state_stack; SCNG(yy_in) = lex_state->in; YYSETCONDITION(lex_state->yy_state); CG(zend_lineno) = lex_state->lineno; zend_restore_compiled_filename(lex_state->filename TSRMLS_CC); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } SCNG(script_org) = lex_state->script_org; SCNG(script_org_size) = lex_state->script_org_size; SCNG(script_filtered) = lex_state->script_filtered; SCNG(script_filtered_size) = lex_state->script_filtered_size; SCNG(input_filter) = lex_state->input_filter; SCNG(output_filter) = lex_state->output_filter; SCNG(script_encoding) = lex_state->script_encoding; if (CG(heredoc)) { efree(CG(heredoc)); CG(heredoc) = NULL; CG(heredoc_len) = 0; } } ZEND_API void zend_destroy_file_handle(zend_file_handle *file_handle TSRMLS_DC) { zend_llist_del_element(&CG(open_files), file_handle, (int (*)(void *, void *)) zend_compare_file_handles); /* zend_file_handle_dtor() operates on the copy, so we have to NULLify the original here */ file_handle->opened_path = NULL; if (file_handle->free_filename) { file_handle->filename = NULL; } } #define BOM_UTF32_BE "\x00\x00\xfe\xff" #define BOM_UTF32_LE "\xff\xfe\x00\x00" #define BOM_UTF16_BE "\xfe\xff" #define BOM_UTF16_LE "\xff\xfe" #define BOM_UTF8 "\xef\xbb\xbf" static const zend_encoding *zend_multibyte_detect_utf_encoding(const unsigned char *script, size_t script_size TSRMLS_DC) { const unsigned char *p; int wchar_size = 2; int le = 0; /* utf-16 or utf-32? */ p = script; while ((p-script) < script_size) { p = memchr(p, 0, script_size-(p-script)-2); if (!p) { break; } if (*(p+1) == '\0' && *(p+2) == '\0') { wchar_size = 4; break; } /* searching for UTF-32 specific byte orders, so this will do */ p += 4; } /* BE or LE? */ p = script; while ((p-script) < script_size) { if (*p == '\0' && *(p+wchar_size-1) != '\0') { /* BE */ le = 0; break; } else if (*p != '\0' && *(p+wchar_size-1) == '\0') { /* LE* */ le = 1; break; } p += wchar_size; } if (wchar_size == 2) { return le ? zend_multibyte_encoding_utf16le : zend_multibyte_encoding_utf16be; } else { return le ? zend_multibyte_encoding_utf32le : zend_multibyte_encoding_utf32be; } return NULL; } static const zend_encoding* zend_multibyte_detect_unicode(TSRMLS_D) { const zend_encoding *script_encoding = NULL; int bom_size; unsigned char *pos1, *pos2; if (LANG_SCNG(script_org_size) < sizeof(BOM_UTF32_LE)-1) { return NULL; } /* check out BOM */ if (!memcmp(LANG_SCNG(script_org), BOM_UTF32_BE, sizeof(BOM_UTF32_BE)-1)) { script_encoding = zend_multibyte_encoding_utf32be; bom_size = sizeof(BOM_UTF32_BE)-1; } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF32_LE, sizeof(BOM_UTF32_LE)-1)) { script_encoding = zend_multibyte_encoding_utf32le; bom_size = sizeof(BOM_UTF32_LE)-1; } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF16_BE, sizeof(BOM_UTF16_BE)-1)) { script_encoding = zend_multibyte_encoding_utf16be; bom_size = sizeof(BOM_UTF16_BE)-1; } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF16_LE, sizeof(BOM_UTF16_LE)-1)) { script_encoding = zend_multibyte_encoding_utf16le; bom_size = sizeof(BOM_UTF16_LE)-1; } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF8, sizeof(BOM_UTF8)-1)) { script_encoding = zend_multibyte_encoding_utf8; bom_size = sizeof(BOM_UTF8)-1; } if (script_encoding) { /* remove BOM */ LANG_SCNG(script_org) += bom_size; LANG_SCNG(script_org_size) -= bom_size; return script_encoding; } /* script contains NULL bytes -> auto-detection */ if ((pos1 = memchr(LANG_SCNG(script_org), 0, LANG_SCNG(script_org_size)))) { /* check if the NULL byte is after the __HALT_COMPILER(); */ pos2 = LANG_SCNG(script_org); while (pos1 - pos2 >= sizeof("__HALT_COMPILER();")-1) { pos2 = memchr(pos2, '_', pos1 - pos2); if (!pos2) break; pos2++; if (strncasecmp((char*)pos2, "_HALT_COMPILER", sizeof("_HALT_COMPILER")-1) == 0) { pos2 += sizeof("_HALT_COMPILER")-1; while (*pos2 == ' ' || *pos2 == '\t' || *pos2 == '\r' || *pos2 == '\n') { pos2++; } if (*pos2 == '(') { pos2++; while (*pos2 == ' ' || *pos2 == '\t' || *pos2 == '\r' || *pos2 == '\n') { pos2++; } if (*pos2 == ')') { pos2++; while (*pos2 == ' ' || *pos2 == '\t' || *pos2 == '\r' || *pos2 == '\n') { pos2++; } if (*pos2 == ';') { return NULL; } } } } } /* make best effort if BOM is missing */ return zend_multibyte_detect_utf_encoding(LANG_SCNG(script_org), LANG_SCNG(script_org_size) TSRMLS_CC); } return NULL; } static const zend_encoding* zend_multibyte_find_script_encoding(TSRMLS_D) { const zend_encoding *script_encoding; if (CG(detect_unicode)) { /* check out bom(byte order mark) and see if containing wchars */ script_encoding = zend_multibyte_detect_unicode(TSRMLS_C); if (script_encoding != NULL) { /* bom or wchar detection is prior to 'script_encoding' option */ return script_encoding; } } /* if no script_encoding specified, just leave alone */ if (!CG(script_encoding_list) || !CG(script_encoding_list_size)) { return NULL; } /* if multiple encodings specified, detect automagically */ if (CG(script_encoding_list_size) > 1) { return zend_multibyte_encoding_detector(LANG_SCNG(script_org), LANG_SCNG(script_org_size), CG(script_encoding_list), CG(script_encoding_list_size) TSRMLS_CC); } return CG(script_encoding_list)[0]; } ZEND_API int zend_multibyte_set_filter(const zend_encoding *onetime_encoding TSRMLS_DC) { const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding(TSRMLS_C); const zend_encoding *script_encoding = onetime_encoding ? onetime_encoding: zend_multibyte_find_script_encoding(TSRMLS_C); if (!script_encoding) { return FAILURE; } /* judge input/output filter */ LANG_SCNG(script_encoding) = script_encoding; LANG_SCNG(input_filter) = NULL; LANG_SCNG(output_filter) = NULL; if (!internal_encoding || LANG_SCNG(script_encoding) == internal_encoding) { if (!zend_multibyte_check_lexer_compatibility(LANG_SCNG(script_encoding))) { /* and if not, work around w/ script_encoding -> utf-8 -> script_encoding conversion */ LANG_SCNG(input_filter) = encoding_filter_script_to_intermediate; LANG_SCNG(output_filter) = encoding_filter_intermediate_to_script; } else { LANG_SCNG(input_filter) = NULL; LANG_SCNG(output_filter) = NULL; } return SUCCESS; } if (zend_multibyte_check_lexer_compatibility(internal_encoding)) { LANG_SCNG(input_filter) = encoding_filter_script_to_internal; LANG_SCNG(output_filter) = NULL; } else if (zend_multibyte_check_lexer_compatibility(LANG_SCNG(script_encoding))) { LANG_SCNG(input_filter) = NULL; LANG_SCNG(output_filter) = encoding_filter_script_to_internal; } else { /* both script and internal encodings are incompatible w/ flex */ LANG_SCNG(input_filter) = encoding_filter_script_to_intermediate; LANG_SCNG(output_filter) = encoding_filter_intermediate_to_internal; } return 0; } ZEND_API int open_file_for_scanning(zend_file_handle *file_handle TSRMLS_DC) { const char *file_path = NULL; char *buf; size_t size, offset = 0; /* The shebang line was read, get the current position to obtain the buffer start */ if (CG(start_lineno) == 2 && file_handle->type == ZEND_HANDLE_FP && file_handle->handle.fp) { if ((offset = ftell(file_handle->handle.fp)) == -1) { offset = 0; } } if (zend_stream_fixup(file_handle, &buf, &size TSRMLS_CC) == FAILURE) { return FAILURE; } zend_llist_add_element(&CG(open_files), file_handle); if (file_handle->handle.stream.handle >= (void*)file_handle && file_handle->handle.stream.handle <= (void*)(file_handle+1)) { zend_file_handle *fh = (zend_file_handle*)zend_llist_get_last(&CG(open_files)); size_t diff = (char*)file_handle->handle.stream.handle - (char*)file_handle; fh->handle.stream.handle = (void*)(((char*)fh) + diff); file_handle->handle.stream.handle = fh->handle.stream.handle; } /* Reset the scanner for scanning the new file */ SCNG(yy_in) = file_handle; SCNG(yy_start) = NULL; if (size != -1) { if (CG(multibyte)) { SCNG(script_org) = (unsigned char*)buf; SCNG(script_org_size) = size; SCNG(script_filtered) = NULL; zend_multibyte_set_filter(NULL TSRMLS_CC); if (SCNG(input_filter)) { if ((size_t)-1 == SCNG(input_filter)(&SCNG(script_filtered), &SCNG(script_filtered_size), SCNG(script_org), SCNG(script_org_size) TSRMLS_CC)) { zend_error_noreturn(E_COMPILE_ERROR, "Could not convert the script from the detected " "encoding \"%s\" to a compatible encoding", zend_multibyte_get_encoding_name(LANG_SCNG(script_encoding))); } buf = (char*)SCNG(script_filtered); size = SCNG(script_filtered_size); } } SCNG(yy_start) = (unsigned char *)buf - offset; yy_scan_buffer(buf, size TSRMLS_CC); } else { zend_error_noreturn(E_COMPILE_ERROR, "zend_stream_mmap() failed"); } BEGIN(INITIAL); if (file_handle->opened_path) { file_path = file_handle->opened_path; } else { file_path = file_handle->filename; } zend_set_compiled_filename(file_path TSRMLS_CC); if (CG(start_lineno)) { CG(zend_lineno) = CG(start_lineno); CG(start_lineno) = 0; } else { CG(zend_lineno) = 1; } CG(increment_lineno) = 0; return SUCCESS; } END_EXTERN_C() ZEND_API zend_op_array *compile_file(zend_file_handle *file_handle, int type TSRMLS_DC) { zend_lex_state original_lex_state; zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array)); zend_op_array *original_active_op_array = CG(active_op_array); zend_op_array *retval=NULL; int compiler_result; zend_bool compilation_successful=0; znode retval_znode; zend_bool original_in_compilation = CG(in_compilation); retval_znode.op_type = IS_CONST; retval_znode.u.constant.type = IS_LONG; retval_znode.u.constant.value.lval = 1; Z_UNSET_ISREF(retval_znode.u.constant); Z_SET_REFCOUNT(retval_znode.u.constant, 1); zend_save_lexical_state(&original_lex_state TSRMLS_CC); retval = op_array; /* success oriented */ if (open_file_for_scanning(file_handle TSRMLS_CC)==FAILURE) { if (type==ZEND_REQUIRE) { zend_message_dispatcher(ZMSG_FAILED_REQUIRE_FOPEN, file_handle->filename TSRMLS_CC); zend_bailout(); } else { zend_message_dispatcher(ZMSG_FAILED_INCLUDE_FOPEN, file_handle->filename TSRMLS_CC); } compilation_successful=0; } else { init_op_array(op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(in_compilation) = 1; CG(active_op_array) = op_array; zend_init_compiler_context(TSRMLS_C); compiler_result = zendparse(TSRMLS_C); zend_do_return(&retval_znode, 0 TSRMLS_CC); CG(in_compilation) = original_in_compilation; if (compiler_result==1) { /* parser error */ zend_bailout(); } compilation_successful=1; } if (retval) { CG(active_op_array) = original_active_op_array; if (compilation_successful) { pass_two(op_array TSRMLS_CC); zend_release_labels(TSRMLS_C); } else { efree(op_array); retval = NULL; } } zend_restore_lexical_state(&original_lex_state TSRMLS_CC); return retval; } zend_op_array *compile_filename(int type, zval *filename TSRMLS_DC) { zend_file_handle file_handle; zval tmp; zend_op_array *retval; char *opened_path = NULL; if (filename->type != IS_STRING) { tmp = *filename; zval_copy_ctor(&tmp); convert_to_string(&tmp); filename = &tmp; } file_handle.filename = filename->value.str.val; file_handle.free_filename = 0; file_handle.type = ZEND_HANDLE_FILENAME; file_handle.opened_path = NULL; file_handle.handle.fp = NULL; retval = zend_compile_file(&file_handle, type TSRMLS_CC); if (retval && file_handle.handle.stream.handle) { int dummy = 1; if (!file_handle.opened_path) { file_handle.opened_path = opened_path = estrndup(filename->value.str.val, filename->value.str.len); } zend_hash_add(&EG(included_files), file_handle.opened_path, strlen(file_handle.opened_path)+1, (void *)&dummy, sizeof(int), NULL); if (opened_path) { efree(opened_path); } } zend_destroy_file_handle(&file_handle TSRMLS_CC); if (filename==&tmp) { zval_dtor(&tmp); } return retval; } ZEND_API int zend_prepare_string_for_scanning(zval *str, char *filename TSRMLS_DC) { char *buf; size_t size; /* enforce two trailing NULLs for flex... */ if (IS_INTERNED(str->value.str.val)) { char *tmp = safe_emalloc(1, str->value.str.len, ZEND_MMAP_AHEAD); memcpy(tmp, str->value.str.val, str->value.str.len + ZEND_MMAP_AHEAD); str->value.str.val = tmp; } else { str->value.str.val = safe_erealloc(str->value.str.val, 1, str->value.str.len, ZEND_MMAP_AHEAD); } memset(str->value.str.val + str->value.str.len, 0, ZEND_MMAP_AHEAD); SCNG(yy_in) = NULL; SCNG(yy_start) = NULL; buf = str->value.str.val; size = str->value.str.len; if (CG(multibyte)) { SCNG(script_org) = (unsigned char*)buf; SCNG(script_org_size) = size; SCNG(script_filtered) = NULL; zend_multibyte_set_filter(zend_multibyte_get_internal_encoding(TSRMLS_C) TSRMLS_CC); if (SCNG(input_filter)) { if ((size_t)-1 == SCNG(input_filter)(&SCNG(script_filtered), &SCNG(script_filtered_size), SCNG(script_org), SCNG(script_org_size) TSRMLS_CC)) { zend_error_noreturn(E_COMPILE_ERROR, "Could not convert the script from the detected " "encoding \"%s\" to a compatible encoding", zend_multibyte_get_encoding_name(LANG_SCNG(script_encoding))); } buf = (char*)SCNG(script_filtered); size = SCNG(script_filtered_size); } } yy_scan_buffer(buf, size TSRMLS_CC); zend_set_compiled_filename(filename TSRMLS_CC); CG(zend_lineno) = 1; CG(increment_lineno) = 0; return SUCCESS; } ZEND_API size_t zend_get_scanned_file_offset(TSRMLS_D) { size_t offset = SCNG(yy_cursor) - SCNG(yy_start); if (SCNG(input_filter)) { size_t original_offset = offset, length = 0; do { unsigned char *p = NULL; if ((size_t)-1 == SCNG(input_filter)(&p, &length, SCNG(script_org), offset TSRMLS_CC)) { return (size_t)-1; } efree(p); if (length > original_offset) { offset--; } else if (length < original_offset) { offset++; } } while (original_offset != length); } return offset; } zend_op_array *compile_string(zval *source_string, char *filename TSRMLS_DC) { zend_lex_state original_lex_state; zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array)); zend_op_array *original_active_op_array = CG(active_op_array); zend_op_array *retval; zval tmp; int compiler_result; zend_bool original_in_compilation = CG(in_compilation); if (source_string->value.str.len==0) { efree(op_array); return NULL; } CG(in_compilation) = 1; tmp = *source_string; zval_copy_ctor(&tmp); convert_to_string(&tmp); source_string = &tmp; zend_save_lexical_state(&original_lex_state TSRMLS_CC); if (zend_prepare_string_for_scanning(source_string, filename TSRMLS_CC)==FAILURE) { efree(op_array); retval = NULL; } else { zend_bool orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(op_array, ZEND_EVAL_CODE, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; CG(active_op_array) = op_array; zend_init_compiler_context(TSRMLS_C); BEGIN(ST_IN_SCRIPTING); compiler_result = zendparse(TSRMLS_C); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } if (compiler_result==1) { CG(active_op_array) = original_active_op_array; CG(unclean_shutdown)=1; destroy_op_array(op_array TSRMLS_CC); efree(op_array); retval = NULL; } else { zend_do_return(NULL, 0 TSRMLS_CC); CG(active_op_array) = original_active_op_array; pass_two(op_array TSRMLS_CC); zend_release_labels(TSRMLS_C); retval = op_array; } } zend_restore_lexical_state(&original_lex_state TSRMLS_CC); zval_dtor(&tmp); CG(in_compilation) = original_in_compilation; return retval; } BEGIN_EXTERN_C() int highlight_file(char *filename, zend_syntax_highlighter_ini *syntax_highlighter_ini TSRMLS_DC) { zend_lex_state original_lex_state; zend_file_handle file_handle; file_handle.type = ZEND_HANDLE_FILENAME; file_handle.filename = filename; file_handle.free_filename = 0; file_handle.opened_path = NULL; zend_save_lexical_state(&original_lex_state TSRMLS_CC); if (open_file_for_scanning(&file_handle TSRMLS_CC)==FAILURE) { zend_message_dispatcher(ZMSG_FAILED_HIGHLIGHT_FOPEN, filename TSRMLS_CC); zend_restore_lexical_state(&original_lex_state TSRMLS_CC); return FAILURE; } zend_highlight(syntax_highlighter_ini TSRMLS_CC); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } zend_destroy_file_handle(&file_handle TSRMLS_CC); zend_restore_lexical_state(&original_lex_state TSRMLS_CC); return SUCCESS; } int highlight_string(zval *str, zend_syntax_highlighter_ini *syntax_highlighter_ini, char *str_name TSRMLS_DC) { zend_lex_state original_lex_state; zval tmp = *str; str = &tmp; zval_copy_ctor(str); zend_save_lexical_state(&original_lex_state TSRMLS_CC); if (zend_prepare_string_for_scanning(str, str_name TSRMLS_CC)==FAILURE) { zend_restore_lexical_state(&original_lex_state TSRMLS_CC); return FAILURE; } BEGIN(INITIAL); zend_highlight(syntax_highlighter_ini TSRMLS_CC); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } zend_restore_lexical_state(&original_lex_state TSRMLS_CC); zval_dtor(str); return SUCCESS; } ZEND_API void zend_multibyte_yyinput_again(zend_encoding_filter old_input_filter, const zend_encoding *old_encoding TSRMLS_DC) { size_t length; unsigned char *new_yy_start; /* convert and set */ if (!SCNG(input_filter)) { if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } SCNG(script_filtered_size) = 0; length = SCNG(script_org_size); new_yy_start = SCNG(script_org); } else { if ((size_t)-1 == SCNG(input_filter)(&new_yy_start, &length, SCNG(script_org), SCNG(script_org_size) TSRMLS_CC)) { zend_error_noreturn(E_COMPILE_ERROR, "Could not convert the script from the detected " "encoding \"%s\" to a compatible encoding", zend_multibyte_get_encoding_name(LANG_SCNG(script_encoding))); } SCNG(script_filtered) = new_yy_start; SCNG(script_filtered_size) = length; } SCNG(yy_cursor) = new_yy_start + (SCNG(yy_cursor) - SCNG(yy_start)); SCNG(yy_marker) = new_yy_start + (SCNG(yy_marker) - SCNG(yy_start)); SCNG(yy_text) = new_yy_start + (SCNG(yy_text) - SCNG(yy_start)); SCNG(yy_limit) = new_yy_start + (SCNG(yy_limit) - SCNG(yy_start)); SCNG(yy_start) = new_yy_start; } # define zend_copy_value(zendlval, yytext, yyleng) \ if (SCNG(output_filter)) { \ size_t sz = 0; \ SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)yytext, (size_t)yyleng TSRMLS_CC); \ zendlval->value.str.len = sz; \ } else { \ zendlval->value.str.val = (char *) estrndup(yytext, yyleng); \ zendlval->value.str.len = yyleng; \ } static void zend_scan_escape_string(zval *zendlval, char *str, int len, char quote_type TSRMLS_DC) { register char *s, *t; char *end; ZVAL_STRINGL(zendlval, str, len, 1); /* convert escape sequences */ s = t = zendlval->value.str.val; end = s+zendlval->value.str.len; while (s<end) { if (*s=='\\') { s++; if (s >= end) { *t++ = '\\'; break; } switch(*s) { case 'n': *t++ = '\n'; zendlval->value.str.len--; break; case 'r': *t++ = '\r'; zendlval->value.str.len--; break; case 't': *t++ = '\t'; zendlval->value.str.len--; break; case 'f': *t++ = '\f'; zendlval->value.str.len--; break; case 'v': *t++ = '\v'; zendlval->value.str.len--; break; case 'e': *t++ = '\e'; zendlval->value.str.len--; break; case '"': case '`': if (*s != quote_type) { *t++ = '\\'; *t++ = *s; break; } case '\\': case '$': *t++ = *s; zendlval->value.str.len--; break; case 'x': case 'X': if (ZEND_IS_HEX(*(s+1))) { char hex_buf[3] = { 0, 0, 0 }; zendlval->value.str.len--; /* for the 'x' */ hex_buf[0] = *(++s); zendlval->value.str.len--; if (ZEND_IS_HEX(*(s+1))) { hex_buf[1] = *(++s); zendlval->value.str.len--; } *t++ = (char) strtol(hex_buf, NULL, 16); } else { *t++ = '\\'; *t++ = *s; } break; default: /* check for an octal */ if (ZEND_IS_OCT(*s)) { char octal_buf[4] = { 0, 0, 0, 0 }; octal_buf[0] = *s; zendlval->value.str.len--; if (ZEND_IS_OCT(*(s+1))) { octal_buf[1] = *(++s); zendlval->value.str.len--; if (ZEND_IS_OCT(*(s+1))) { octal_buf[2] = *(++s); zendlval->value.str.len--; } } *t++ = (char) strtol(octal_buf, NULL, 8); } else { *t++ = '\\'; *t++ = *s; } break; } } else { *t++ = *s; } if (*s == '\n' || (*s == '\r' && (*(s+1) != '\n'))) { CG(zend_lineno)++; } s++; } *t = 0; if (SCNG(output_filter)) { size_t sz = 0; s = zendlval->value.str.val; SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)s, (size_t)zendlval->value.str.len TSRMLS_CC); zendlval->value.str.len = sz; efree(s); } } int lex_scan(zval *zendlval TSRMLS_DC) { restart: SCNG(yy_text) = YYCURSOR; yymore_restart: #line 995 "Zend/zend_language_scanner.c" { YYCTYPE yych; unsigned int yyaccept = 0; if (YYGETCONDITION() < 5) { if (YYGETCONDITION() < 2) { if (YYGETCONDITION() < 1) { goto yyc_ST_IN_SCRIPTING; } else { goto yyc_ST_LOOKING_FOR_PROPERTY; } } else { if (YYGETCONDITION() < 3) { goto yyc_ST_BACKQUOTE; } else { if (YYGETCONDITION() < 4) { goto yyc_ST_DOUBLE_QUOTES; } else { goto yyc_ST_HEREDOC; } } } } else { if (YYGETCONDITION() < 7) { if (YYGETCONDITION() < 6) { goto yyc_ST_LOOKING_FOR_VARNAME; } else { goto yyc_ST_VAR_OFFSET; } } else { if (YYGETCONDITION() < 8) { goto yyc_INITIAL; } else { if (YYGETCONDITION() < 9) { goto yyc_ST_END_HEREDOC; } else { goto yyc_ST_NOWDOC; } } } } /* *********************************** */ yyc_INITIAL: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; YYDEBUG(0, *YYCURSOR); YYFILL(8); yych = *YYCURSOR; if (yych != '<') goto yy4; YYDEBUG(2, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '?') { if (yych == '%') goto yy7; if (yych >= '?') goto yy5; } else { if (yych <= 'S') { if (yych >= 'S') goto yy9; } else { if (yych == 's') goto yy9; } } yy3: YYDEBUG(3, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1775 "Zend/zend_language_scanner.l" { if (YYCURSOR > YYLIMIT) { return 0; } inline_char_handler: while (1) { YYCTYPE *ptr = memchr(YYCURSOR, '<', YYLIMIT - YYCURSOR); YYCURSOR = ptr ? ptr + 1 : YYLIMIT; if (YYCURSOR < YYLIMIT) { switch (*YYCURSOR) { case '?': if (CG(short_tags) || !strncasecmp((char*)YYCURSOR + 1, "php", 3) || (*(YYCURSOR + 1) == '=')) { /* Assume [ \t\n\r] follows "php" */ break; } continue; case '%': if (CG(asp_tags)) { break; } continue; case 's': case 'S': /* Probably NOT an opening PHP <script> tag, so don't end the HTML chunk yet * If it is, the PHP <script> tag rule checks for any HTML scanned before it */ YYCURSOR--; yymore(); default: continue; } YYCURSOR--; } break; } inline_html: yyleng = YYCURSOR - SCNG(yy_text); if (SCNG(output_filter)) { int readsize; size_t sz = 0; readsize = SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)yytext, (size_t)yyleng TSRMLS_CC); zendlval->value.str.len = sz; if (readsize < yyleng) { yyless(readsize); } } else { zendlval->value.str.val = (char *) estrndup(yytext, yyleng); zendlval->value.str.len = yyleng; } zendlval->type = IS_STRING; HANDLE_NEWLINES(yytext, yyleng); return T_INLINE_HTML; } #line 1154 "Zend/zend_language_scanner.c" yy4: YYDEBUG(4, *YYCURSOR); yych = *++YYCURSOR; goto yy3; yy5: YYDEBUG(5, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'O') { if (yych == '=') goto yy45; } else { if (yych <= 'P') goto yy47; if (yych == 'p') goto yy47; } yy6: YYDEBUG(6, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1763 "Zend/zend_language_scanner.l" { if (CG(short_tags)) { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG; } else { goto inline_char_handler; } } #line 1184 "Zend/zend_language_scanner.c" yy7: YYDEBUG(7, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '=') goto yy43; YYDEBUG(8, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1740 "Zend/zend_language_scanner.l" { if (CG(asp_tags)) { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG; } else { goto inline_char_handler; } } #line 1203 "Zend/zend_language_scanner.c" yy9: YYDEBUG(9, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy11; if (yych == 'c') goto yy11; yy10: YYDEBUG(10, *YYCURSOR); YYCURSOR = YYMARKER; if (yyaccept <= 0) { goto yy3; } else { goto yy6; } yy11: YYDEBUG(11, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy12; if (yych != 'r') goto yy10; yy12: YYDEBUG(12, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy13; if (yych != 'i') goto yy10; yy13: YYDEBUG(13, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy14; if (yych != 'p') goto yy10; yy14: YYDEBUG(14, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy15; if (yych != 't') goto yy10; yy15: YYDEBUG(15, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy10; if (yych == 'l') goto yy10; goto yy17; yy16: YYDEBUG(16, *YYCURSOR); ++YYCURSOR; YYFILL(8); yych = *YYCURSOR; yy17: YYDEBUG(17, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy16; } if (yych == 'L') goto yy18; if (yych != 'l') goto yy10; yy18: YYDEBUG(18, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy19; if (yych != 'a') goto yy10; yy19: YYDEBUG(19, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy20; if (yych != 'n') goto yy10; yy20: YYDEBUG(20, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy21; if (yych != 'g') goto yy10; yy21: YYDEBUG(21, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy22; if (yych != 'u') goto yy10; yy22: YYDEBUG(22, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy23; if (yych != 'a') goto yy10; yy23: YYDEBUG(23, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy24; if (yych != 'g') goto yy10; yy24: YYDEBUG(24, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy25; if (yych != 'e') goto yy10; yy25: YYDEBUG(25, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(26, *YYCURSOR); if (yych <= '\r') { if (yych <= 0x08) goto yy10; if (yych <= '\n') goto yy25; if (yych <= '\f') goto yy10; goto yy25; } else { if (yych <= ' ') { if (yych <= 0x1F) goto yy10; goto yy25; } else { if (yych != '=') goto yy10; } } yy27: YYDEBUG(27, *YYCURSOR); ++YYCURSOR; YYFILL(5); yych = *YYCURSOR; YYDEBUG(28, *YYCURSOR); if (yych <= '!') { if (yych <= '\f') { if (yych <= 0x08) goto yy10; if (yych <= '\n') goto yy27; goto yy10; } else { if (yych <= '\r') goto yy27; if (yych == ' ') goto yy27; goto yy10; } } else { if (yych <= 'O') { if (yych <= '"') goto yy30; if (yych == '\'') goto yy31; goto yy10; } else { if (yych <= 'P') goto yy29; if (yych != 'p') goto yy10; } } yy29: YYDEBUG(29, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy42; if (yych == 'h') goto yy42; goto yy10; yy30: YYDEBUG(30, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy39; if (yych == 'p') goto yy39; goto yy10; yy31: YYDEBUG(31, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy32; if (yych != 'p') goto yy10; yy32: YYDEBUG(32, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy33; if (yych != 'h') goto yy10; yy33: YYDEBUG(33, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy34; if (yych != 'p') goto yy10; yy34: YYDEBUG(34, *YYCURSOR); yych = *++YYCURSOR; if (yych != '\'') goto yy10; yy35: YYDEBUG(35, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(36, *YYCURSOR); if (yych <= '\r') { if (yych <= 0x08) goto yy10; if (yych <= '\n') goto yy35; if (yych <= '\f') goto yy10; goto yy35; } else { if (yych <= ' ') { if (yych <= 0x1F) goto yy10; goto yy35; } else { if (yych != '>') goto yy10; } } YYDEBUG(37, *YYCURSOR); ++YYCURSOR; YYDEBUG(38, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1700 "Zend/zend_language_scanner.l" { YYCTYPE *bracket = (YYCTYPE*)zend_memrchr(yytext, '<', yyleng - (sizeof("script language=php>") - 1)); if (bracket != SCNG(yy_text)) { /* Handle previously scanned HTML, as possible <script> tags found are assumed to not be PHP's */ YYCURSOR = bracket; goto inline_html; } HANDLE_NEWLINES(yytext, yyleng); zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG; } #line 1406 "Zend/zend_language_scanner.c" yy39: YYDEBUG(39, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy40; if (yych != 'h') goto yy10; yy40: YYDEBUG(40, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy41; if (yych != 'p') goto yy10; yy41: YYDEBUG(41, *YYCURSOR); yych = *++YYCURSOR; if (yych == '"') goto yy35; goto yy10; yy42: YYDEBUG(42, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy35; if (yych == 'p') goto yy35; goto yy10; yy43: YYDEBUG(43, *YYCURSOR); ++YYCURSOR; YYDEBUG(44, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1718 "Zend/zend_language_scanner.l" { if (CG(asp_tags)) { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG_WITH_ECHO; } else { goto inline_char_handler; } } #line 1445 "Zend/zend_language_scanner.c" yy45: YYDEBUG(45, *YYCURSOR); ++YYCURSOR; YYDEBUG(46, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1731 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG_WITH_ECHO; } #line 1459 "Zend/zend_language_scanner.c" yy47: YYDEBUG(47, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy48; if (yych != 'h') goto yy10; yy48: YYDEBUG(48, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy49; if (yych != 'p') goto yy10; yy49: YYDEBUG(49, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '\f') { if (yych <= 0x08) goto yy10; if (yych >= '\v') goto yy10; } else { if (yych <= '\r') goto yy52; if (yych != ' ') goto yy10; } yy50: YYDEBUG(50, *YYCURSOR); ++YYCURSOR; yy51: YYDEBUG(51, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1753 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; HANDLE_NEWLINE(yytext[yyleng-1]); BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG; } #line 1495 "Zend/zend_language_scanner.c" yy52: YYDEBUG(52, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '\n') goto yy50; goto yy51; } /* *********************************** */ yyc_ST_BACKQUOTE: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; YYDEBUG(53, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych <= '_') { if (yych != '$') goto yy60; } else { if (yych <= '`') goto yy58; if (yych == '{') goto yy57; goto yy60; } YYDEBUG(55, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '_') { if (yych <= '@') goto yy56; if (yych <= 'Z') goto yy63; if (yych >= '_') goto yy63; } else { if (yych <= 'z') { if (yych >= 'a') goto yy63; } else { if (yych <= '{') goto yy66; if (yych >= 0x7F) goto yy63; } } yy56: YYDEBUG(56, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2226 "Zend/zend_language_scanner.l" { if (YYCURSOR > YYLIMIT) { return 0; } if (yytext[0] == '\\' && YYCURSOR < YYLIMIT) { YYCURSOR++; } while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '`': break; case '$': if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { break; } continue; case '{': if (*YYCURSOR == '$') { break; } continue; case '\\': if (YYCURSOR < YYLIMIT) { YYCURSOR++; } /* fall through */ default: continue; } YYCURSOR--; break; } yyleng = YYCURSOR - SCNG(yy_text); zend_scan_escape_string(zendlval, yytext, yyleng, '`' TSRMLS_CC); return T_ENCAPSED_AND_WHITESPACE; } #line 1607 "Zend/zend_language_scanner.c" yy57: YYDEBUG(57, *YYCURSOR); yych = *++YYCURSOR; if (yych == '$') goto yy61; goto yy56; yy58: YYDEBUG(58, *YYCURSOR); ++YYCURSOR; YYDEBUG(59, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2170 "Zend/zend_language_scanner.l" { BEGIN(ST_IN_SCRIPTING); return '`'; } #line 1623 "Zend/zend_language_scanner.c" yy60: YYDEBUG(60, *YYCURSOR); yych = *++YYCURSOR; goto yy56; yy61: YYDEBUG(61, *YYCURSOR); ++YYCURSOR; YYDEBUG(62, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2157 "Zend/zend_language_scanner.l" { zendlval->value.lval = (long) '{'; yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); yyless(1); return T_CURLY_OPEN; } #line 1640 "Zend/zend_language_scanner.c" yy63: YYDEBUG(63, *YYCURSOR); yyaccept = 0; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(64, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy63; } if (yych == '-') goto yy68; if (yych == '[') goto yy70; yy65: YYDEBUG(65, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1857 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1662 "Zend/zend_language_scanner.c" yy66: YYDEBUG(66, *YYCURSOR); ++YYCURSOR; YYDEBUG(67, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1442 "Zend/zend_language_scanner.l" { yy_push_state(ST_LOOKING_FOR_VARNAME TSRMLS_CC); return T_DOLLAR_OPEN_CURLY_BRACES; } #line 1673 "Zend/zend_language_scanner.c" yy68: YYDEBUG(68, *YYCURSOR); yych = *++YYCURSOR; if (yych == '>') goto yy72; yy69: YYDEBUG(69, *YYCURSOR); YYCURSOR = YYMARKER; goto yy65; yy70: YYDEBUG(70, *YYCURSOR); ++YYCURSOR; YYDEBUG(71, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1849 "Zend/zend_language_scanner.l" { yyless(yyleng - 1); yy_push_state(ST_VAR_OFFSET TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1695 "Zend/zend_language_scanner.c" yy72: YYDEBUG(72, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy69; if (yych <= 'Z') goto yy73; if (yych <= '^') goto yy69; } else { if (yych <= '`') goto yy69; if (yych <= 'z') goto yy73; if (yych <= '~') goto yy69; } yy73: YYDEBUG(73, *YYCURSOR); ++YYCURSOR; YYDEBUG(74, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1839 "Zend/zend_language_scanner.l" { yyless(yyleng - 3); yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1721 "Zend/zend_language_scanner.c" } /* *********************************** */ yyc_ST_DOUBLE_QUOTES: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; YYDEBUG(75, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych <= '#') { if (yych == '"') goto yy80; goto yy82; } else { if (yych <= '$') goto yy77; if (yych == '{') goto yy79; goto yy82; } yy77: YYDEBUG(77, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '_') { if (yych <= '@') goto yy78; if (yych <= 'Z') goto yy85; if (yych >= '_') goto yy85; } else { if (yych <= 'z') { if (yych >= 'a') goto yy85; } else { if (yych <= '{') goto yy88; if (yych >= 0x7F) goto yy85; } } yy78: YYDEBUG(78, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2176 "Zend/zend_language_scanner.l" { if (GET_DOUBLE_QUOTES_SCANNED_LENGTH()) { YYCURSOR += GET_DOUBLE_QUOTES_SCANNED_LENGTH() - 1; SET_DOUBLE_QUOTES_SCANNED_LENGTH(0); goto double_quotes_scan_done; } if (YYCURSOR > YYLIMIT) { return 0; } if (yytext[0] == '\\' && YYCURSOR < YYLIMIT) { YYCURSOR++; } while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '"': break; case '$': if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { break; } continue; case '{': if (*YYCURSOR == '$') { break; } continue; case '\\': if (YYCURSOR < YYLIMIT) { YYCURSOR++; } /* fall through */ default: continue; } YYCURSOR--; break; } double_quotes_scan_done: yyleng = YYCURSOR - SCNG(yy_text); zend_scan_escape_string(zendlval, yytext, yyleng, '"' TSRMLS_CC); return T_ENCAPSED_AND_WHITESPACE; } #line 1838 "Zend/zend_language_scanner.c" yy79: YYDEBUG(79, *YYCURSOR); yych = *++YYCURSOR; if (yych == '$') goto yy83; goto yy78; yy80: YYDEBUG(80, *YYCURSOR); ++YYCURSOR; YYDEBUG(81, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2165 "Zend/zend_language_scanner.l" { BEGIN(ST_IN_SCRIPTING); return '"'; } #line 1854 "Zend/zend_language_scanner.c" yy82: YYDEBUG(82, *YYCURSOR); yych = *++YYCURSOR; goto yy78; yy83: YYDEBUG(83, *YYCURSOR); ++YYCURSOR; YYDEBUG(84, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2157 "Zend/zend_language_scanner.l" { zendlval->value.lval = (long) '{'; yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); yyless(1); return T_CURLY_OPEN; } #line 1871 "Zend/zend_language_scanner.c" yy85: YYDEBUG(85, *YYCURSOR); yyaccept = 0; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(86, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy85; } if (yych == '-') goto yy90; if (yych == '[') goto yy92; yy87: YYDEBUG(87, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1857 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1893 "Zend/zend_language_scanner.c" yy88: YYDEBUG(88, *YYCURSOR); ++YYCURSOR; YYDEBUG(89, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1442 "Zend/zend_language_scanner.l" { yy_push_state(ST_LOOKING_FOR_VARNAME TSRMLS_CC); return T_DOLLAR_OPEN_CURLY_BRACES; } #line 1904 "Zend/zend_language_scanner.c" yy90: YYDEBUG(90, *YYCURSOR); yych = *++YYCURSOR; if (yych == '>') goto yy94; yy91: YYDEBUG(91, *YYCURSOR); YYCURSOR = YYMARKER; goto yy87; yy92: YYDEBUG(92, *YYCURSOR); ++YYCURSOR; YYDEBUG(93, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1849 "Zend/zend_language_scanner.l" { yyless(yyleng - 1); yy_push_state(ST_VAR_OFFSET TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1926 "Zend/zend_language_scanner.c" yy94: YYDEBUG(94, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy91; if (yych <= 'Z') goto yy95; if (yych <= '^') goto yy91; } else { if (yych <= '`') goto yy91; if (yych <= 'z') goto yy95; if (yych <= '~') goto yy91; } yy95: YYDEBUG(95, *YYCURSOR); ++YYCURSOR; YYDEBUG(96, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1839 "Zend/zend_language_scanner.l" { yyless(yyleng - 3); yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1952 "Zend/zend_language_scanner.c" } /* *********************************** */ yyc_ST_END_HEREDOC: YYDEBUG(97, *YYCURSOR); YYFILL(1); yych = *YYCURSOR; YYDEBUG(99, *YYCURSOR); ++YYCURSOR; YYDEBUG(100, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2144 "Zend/zend_language_scanner.l" { YYCURSOR += CG(heredoc_len) - 1; yyleng = CG(heredoc_len); Z_STRVAL_P(zendlval) = CG(heredoc); Z_STRLEN_P(zendlval) = CG(heredoc_len); CG(heredoc) = NULL; CG(heredoc_len) = 0; BEGIN(ST_IN_SCRIPTING); return T_END_HEREDOC; } #line 1975 "Zend/zend_language_scanner.c" /* *********************************** */ yyc_ST_HEREDOC: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; YYDEBUG(101, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych == '$') goto yy103; if (yych == '{') goto yy105; goto yy106; yy103: YYDEBUG(103, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '_') { if (yych <= '@') goto yy104; if (yych <= 'Z') goto yy109; if (yych >= '_') goto yy109; } else { if (yych <= 'z') { if (yych >= 'a') goto yy109; } else { if (yych <= '{') goto yy112; if (yych >= 0x7F) goto yy109; } } yy104: YYDEBUG(104, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2268 "Zend/zend_language_scanner.l" { int newline = 0; if (YYCURSOR > YYLIMIT) { return 0; } YYCURSOR--; while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '\r': if (*YYCURSOR == '\n') { YYCURSOR++; } /* fall through */ case '\n': /* Check for ending label on the next line */ if (IS_LABEL_START(*YYCURSOR) && CG(heredoc_len) < YYLIMIT - YYCURSOR && !memcmp(YYCURSOR, CG(heredoc), CG(heredoc_len))) { YYCTYPE *end = YYCURSOR + CG(heredoc_len); if (*end == ';') { end++; } if (*end == '\n' || *end == '\r') { /* newline before label will be subtracted from returned text, but * yyleng/yytext will include it, for zend_highlight/strip, tokenizer, etc. */ if (YYCURSOR[-2] == '\r' && YYCURSOR[-1] == '\n') { newline = 2; /* Windows newline */ } else { newline = 1; } CG(increment_lineno) = 1; /* For newline before label */ BEGIN(ST_END_HEREDOC); goto heredoc_scan_done; } } continue; case '$': if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { break; } continue; case '{': if (*YYCURSOR == '$') { break; } continue; case '\\': if (YYCURSOR < YYLIMIT && *YYCURSOR != '\n' && *YYCURSOR != '\r') { YYCURSOR++; } /* fall through */ default: continue; } YYCURSOR--; break; } heredoc_scan_done: yyleng = YYCURSOR - SCNG(yy_text); zend_scan_escape_string(zendlval, yytext, yyleng - newline, 0 TSRMLS_CC); return T_ENCAPSED_AND_WHITESPACE; } #line 2108 "Zend/zend_language_scanner.c" yy105: YYDEBUG(105, *YYCURSOR); yych = *++YYCURSOR; if (yych == '$') goto yy107; goto yy104; yy106: YYDEBUG(106, *YYCURSOR); yych = *++YYCURSOR; goto yy104; yy107: YYDEBUG(107, *YYCURSOR); ++YYCURSOR; YYDEBUG(108, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2157 "Zend/zend_language_scanner.l" { zendlval->value.lval = (long) '{'; yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); yyless(1); return T_CURLY_OPEN; } #line 2130 "Zend/zend_language_scanner.c" yy109: YYDEBUG(109, *YYCURSOR); yyaccept = 0; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(110, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy109; } if (yych == '-') goto yy114; if (yych == '[') goto yy116; yy111: YYDEBUG(111, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1857 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 2152 "Zend/zend_language_scanner.c" yy112: YYDEBUG(112, *YYCURSOR); ++YYCURSOR; YYDEBUG(113, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1442 "Zend/zend_language_scanner.l" { yy_push_state(ST_LOOKING_FOR_VARNAME TSRMLS_CC); return T_DOLLAR_OPEN_CURLY_BRACES; } #line 2163 "Zend/zend_language_scanner.c" yy114: YYDEBUG(114, *YYCURSOR); yych = *++YYCURSOR; if (yych == '>') goto yy118; yy115: YYDEBUG(115, *YYCURSOR); YYCURSOR = YYMARKER; goto yy111; yy116: YYDEBUG(116, *YYCURSOR); ++YYCURSOR; YYDEBUG(117, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1849 "Zend/zend_language_scanner.l" { yyless(yyleng - 1); yy_push_state(ST_VAR_OFFSET TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 2185 "Zend/zend_language_scanner.c" yy118: YYDEBUG(118, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy115; if (yych <= 'Z') goto yy119; if (yych <= '^') goto yy115; } else { if (yych <= '`') goto yy115; if (yych <= 'z') goto yy119; if (yych <= '~') goto yy115; } yy119: YYDEBUG(119, *YYCURSOR); ++YYCURSOR; YYDEBUG(120, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1839 "Zend/zend_language_scanner.l" { yyless(yyleng - 3); yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 2211 "Zend/zend_language_scanner.c" } /* *********************************** */ yyc_ST_IN_SCRIPTING: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 64, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 60, 60, 44, 44, 44, 44, 44, 44, 44, 44, 0, 0, 0, 0, 0, 0, 0, 36, 36, 36, 36, 36, 36, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 4, 0, 36, 36, 36, 36, 36, 36, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, }; YYDEBUG(121, *YYCURSOR); YYFILL(16); yych = *YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case '\v': case '\f': case 0x0E: case 0x0F: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1A: case 0x1B: case 0x1C: case 0x1D: case 0x1E: case 0x1F: goto yy183; case '\t': case '\n': case '\r': case ' ': goto yy139; case '!': goto yy152; case '"': goto yy179; case '#': goto yy175; case '$': goto yy164; case '%': goto yy158; case '&': goto yy159; case '\'': goto yy177; case '(': goto yy146; case ')': case ',': case ';': case '@': case '[': case ']': case '~': goto yy165; case '*': goto yy155; case '+': goto yy151; case '-': goto yy137; case '.': goto yy157; case '/': goto yy156; case '0': goto yy171; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy173; case ':': goto yy141; case '<': goto yy153; case '=': goto yy149; case '>': goto yy154; case '?': goto yy166; case 'A': case 'a': goto yy132; case 'B': case 'b': goto yy134; case 'C': case 'c': goto yy127; case 'D': case 'd': goto yy125; case 'E': case 'e': goto yy123; case 'F': case 'f': goto yy126; case 'G': case 'g': goto yy135; case 'I': case 'i': goto yy130; case 'L': case 'l': goto yy150; case 'N': case 'n': goto yy144; case 'O': case 'o': goto yy162; case 'P': case 'p': goto yy136; case 'R': case 'r': goto yy128; case 'S': case 's': goto yy133; case 'T': case 't': goto yy129; case 'U': case 'u': goto yy147; case 'V': case 'v': goto yy145; case 'W': case 'w': goto yy131; case 'X': case 'x': goto yy163; case '\\': goto yy142; case '^': goto yy161; case '_': goto yy148; case '`': goto yy181; case '{': goto yy167; case '|': goto yy160; case '}': goto yy169; default: goto yy174; } yy123: YYDEBUG(123, *YYCURSOR); ++YYCURSOR; YYDEBUG(-1, yych); switch ((yych = *YYCURSOR)) { case 'C': case 'c': goto yy726; case 'L': case 'l': goto yy727; case 'M': case 'm': goto yy728; case 'N': case 'n': goto yy729; case 'V': case 'v': goto yy730; case 'X': case 'x': goto yy731; default: goto yy186; } yy124: YYDEBUG(124, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1880 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, yytext, yyleng); zendlval->type = IS_STRING; return T_STRING; } #line 2398 "Zend/zend_language_scanner.c" yy125: YYDEBUG(125, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= 'H') { if (yych == 'E') goto yy708; goto yy186; } else { if (yych <= 'I') goto yy709; if (yych <= 'N') goto yy186; goto yy710; } } else { if (yych <= 'h') { if (yych == 'e') goto yy708; goto yy186; } else { if (yych <= 'i') goto yy709; if (yych == 'o') goto yy710; goto yy186; } } yy126: YYDEBUG(126, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= 'N') { if (yych == 'I') goto yy687; goto yy186; } else { if (yych <= 'O') goto yy688; if (yych <= 'T') goto yy186; goto yy689; } } else { if (yych <= 'n') { if (yych == 'i') goto yy687; goto yy186; } else { if (yych <= 'o') goto yy688; if (yych == 'u') goto yy689; goto yy186; } } yy127: YYDEBUG(127, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= 'K') { if (yych == 'A') goto yy652; goto yy186; } else { if (yych <= 'L') goto yy653; if (yych <= 'N') goto yy186; goto yy654; } } else { if (yych <= 'k') { if (yych == 'a') goto yy652; goto yy186; } else { if (yych <= 'l') goto yy653; if (yych == 'o') goto yy654; goto yy186; } } yy128: YYDEBUG(128, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy634; if (yych == 'e') goto yy634; goto yy186; yy129: YYDEBUG(129, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych == 'H') goto yy622; if (yych <= 'Q') goto yy186; goto yy623; } else { if (yych <= 'h') { if (yych <= 'g') goto yy186; goto yy622; } else { if (yych == 'r') goto yy623; goto yy186; } } yy130: YYDEBUG(130, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= 'L') { if (yych == 'F') goto yy569; goto yy186; } else { if (yych <= 'M') goto yy571; if (yych <= 'N') goto yy572; if (yych <= 'R') goto yy186; goto yy573; } } else { if (yych <= 'm') { if (yych == 'f') goto yy569; if (yych <= 'l') goto yy186; goto yy571; } else { if (yych <= 'n') goto yy572; if (yych == 's') goto yy573; goto yy186; } } yy131: YYDEBUG(131, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy564; if (yych == 'h') goto yy564; goto yy186; yy132: YYDEBUG(132, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= 'M') { if (yych == 'B') goto yy546; goto yy186; } else { if (yych <= 'N') goto yy547; if (yych <= 'Q') goto yy186; if (yych <= 'R') goto yy548; goto yy549; } } else { if (yych <= 'n') { if (yych == 'b') goto yy546; if (yych <= 'm') goto yy186; goto yy547; } else { if (yych <= 'q') goto yy186; if (yych <= 'r') goto yy548; if (yych <= 's') goto yy549; goto yy186; } } yy133: YYDEBUG(133, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'W') { if (yych == 'T') goto yy534; if (yych <= 'V') goto yy186; goto yy535; } else { if (yych <= 't') { if (yych <= 's') goto yy186; goto yy534; } else { if (yych == 'w') goto yy535; goto yy186; } } yy134: YYDEBUG(134, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ';') { if (yych <= '"') { if (yych <= '!') goto yy186; goto yy526; } else { if (yych == '\'') goto yy527; goto yy186; } } else { if (yych <= 'R') { if (yych <= '<') goto yy525; if (yych <= 'Q') goto yy186; goto yy528; } else { if (yych == 'r') goto yy528; goto yy186; } } yy135: YYDEBUG(135, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'L') goto yy515; if (yych <= 'N') goto yy186; goto yy516; } else { if (yych <= 'l') { if (yych <= 'k') goto yy186; goto yy515; } else { if (yych == 'o') goto yy516; goto yy186; } } yy136: YYDEBUG(136, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'R') goto yy491; if (yych <= 'T') goto yy186; goto yy492; } else { if (yych <= 'r') { if (yych <= 'q') goto yy186; goto yy491; } else { if (yych == 'u') goto yy492; goto yy186; } } yy137: YYDEBUG(137, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '<') { if (yych == '-') goto yy487; } else { if (yych <= '=') goto yy485; if (yych <= '>') goto yy489; } yy138: YYDEBUG(138, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1431 "Zend/zend_language_scanner.l" { return yytext[0]; } #line 2628 "Zend/zend_language_scanner.c" yy139: YYDEBUG(139, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy484; yy140: YYDEBUG(140, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1162 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; HANDLE_NEWLINES(yytext, yyleng); return T_WHITESPACE; } #line 2645 "Zend/zend_language_scanner.c" yy141: YYDEBUG(141, *YYCURSOR); yych = *++YYCURSOR; if (yych == ':') goto yy481; goto yy138; yy142: YYDEBUG(142, *YYCURSOR); ++YYCURSOR; YYDEBUG(143, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1191 "Zend/zend_language_scanner.l" { return T_NS_SEPARATOR; } #line 2660 "Zend/zend_language_scanner.c" yy144: YYDEBUG(144, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych == 'A') goto yy469; if (yych <= 'D') goto yy186; goto yy470; } else { if (yych <= 'a') { if (yych <= '`') goto yy186; goto yy469; } else { if (yych == 'e') goto yy470; goto yy186; } } yy145: YYDEBUG(145, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy466; if (yych == 'a') goto yy466; goto yy186; yy146: YYDEBUG(146, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy391; if (yych <= 0x1F) goto yy138; goto yy391; } else { if (yych <= '@') goto yy138; if (yych == 'C') goto yy138; goto yy391; } } else { if (yych <= 'I') { if (yych == 'F') goto yy391; if (yych <= 'H') goto yy138; goto yy391; } else { if (yych == 'O') goto yy391; if (yych <= 'Q') goto yy138; goto yy391; } } } else { if (yych <= 'f') { if (yych <= 'b') { if (yych == 'U') goto yy391; if (yych <= '`') goto yy138; goto yy391; } else { if (yych == 'd') goto yy391; if (yych <= 'e') goto yy138; goto yy391; } } else { if (yych <= 'o') { if (yych == 'i') goto yy391; if (yych <= 'n') goto yy138; goto yy391; } else { if (yych <= 's') { if (yych <= 'q') goto yy138; goto yy391; } else { if (yych == 'u') goto yy391; goto yy138; } } } } yy147: YYDEBUG(147, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych == 'N') goto yy382; if (yych <= 'R') goto yy186; goto yy383; } else { if (yych <= 'n') { if (yych <= 'm') goto yy186; goto yy382; } else { if (yych == 's') goto yy383; goto yy186; } } yy148: YYDEBUG(148, *YYCURSOR); yych = *++YYCURSOR; if (yych == '_') goto yy300; goto yy186; yy149: YYDEBUG(149, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '<') goto yy138; if (yych <= '=') goto yy294; if (yych <= '>') goto yy296; goto yy138; yy150: YYDEBUG(150, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy290; if (yych == 'i') goto yy290; goto yy186; yy151: YYDEBUG(151, *YYCURSOR); yych = *++YYCURSOR; if (yych == '+') goto yy288; if (yych == '=') goto yy286; goto yy138; yy152: YYDEBUG(152, *YYCURSOR); yych = *++YYCURSOR; if (yych == '=') goto yy283; goto yy138; yy153: YYDEBUG(153, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ';') { if (yych == '/') goto yy255; goto yy138; } else { if (yych <= '<') goto yy253; if (yych <= '=') goto yy256; if (yych <= '>') goto yy258; goto yy138; } yy154: YYDEBUG(154, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '<') goto yy138; if (yych <= '=') goto yy249; if (yych <= '>') goto yy247; goto yy138; yy155: YYDEBUG(155, *YYCURSOR); yych = *++YYCURSOR; if (yych == '=') goto yy245; goto yy138; yy156: YYDEBUG(156, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '.') { if (yych == '*') goto yy237; goto yy138; } else { if (yych <= '/') goto yy239; if (yych == '=') goto yy240; goto yy138; } yy157: YYDEBUG(157, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy138; if (yych <= '9') goto yy233; if (yych == '=') goto yy235; goto yy138; yy158: YYDEBUG(158, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '<') goto yy138; if (yych <= '=') goto yy229; if (yych <= '>') goto yy227; goto yy138; yy159: YYDEBUG(159, *YYCURSOR); yych = *++YYCURSOR; if (yych == '&') goto yy223; if (yych == '=') goto yy225; goto yy138; yy160: YYDEBUG(160, *YYCURSOR); yych = *++YYCURSOR; if (yych == '=') goto yy221; if (yych == '|') goto yy219; goto yy138; yy161: YYDEBUG(161, *YYCURSOR); yych = *++YYCURSOR; if (yych == '=') goto yy217; goto yy138; yy162: YYDEBUG(162, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy215; if (yych == 'r') goto yy215; goto yy186; yy163: YYDEBUG(163, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy212; if (yych == 'o') goto yy212; goto yy186; yy164: YYDEBUG(164, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy138; if (yych <= 'Z') goto yy209; if (yych <= '^') goto yy138; goto yy209; } else { if (yych <= '`') goto yy138; if (yych <= 'z') goto yy209; if (yych <= '~') goto yy138; goto yy209; } yy165: YYDEBUG(165, *YYCURSOR); yych = *++YYCURSOR; goto yy138; yy166: YYDEBUG(166, *YYCURSOR); yych = *++YYCURSOR; if (yych == '>') goto yy205; goto yy138; yy167: YYDEBUG(167, *YYCURSOR); ++YYCURSOR; YYDEBUG(168, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1436 "Zend/zend_language_scanner.l" { yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); return '{'; } #line 2893 "Zend/zend_language_scanner.c" yy169: YYDEBUG(169, *YYCURSOR); ++YYCURSOR; YYDEBUG(170, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1448 "Zend/zend_language_scanner.l" { RESET_DOC_COMMENT(); if (!zend_stack_is_empty(&SCNG(state_stack))) { yy_pop_state(TSRMLS_C); } return '}'; } #line 2907 "Zend/zend_language_scanner.c" yy171: YYDEBUG(171, *YYCURSOR); yyaccept = 2; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'E') { if (yych <= '9') { if (yych == '.') goto yy187; if (yych >= '0') goto yy190; } else { if (yych == 'B') goto yy198; if (yych >= 'E') goto yy192; } } else { if (yych <= 'b') { if (yych == 'X') goto yy197; if (yych >= 'b') goto yy198; } else { if (yych <= 'e') { if (yych >= 'e') goto yy192; } else { if (yych == 'x') goto yy197; } } } yy172: YYDEBUG(172, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1494 "Zend/zend_language_scanner.l" { if (yyleng < MAX_LENGTH_OF_LONG - 1) { /* Won't overflow */ zendlval->value.lval = strtol(yytext, NULL, 0); } else { errno = 0; zendlval->value.lval = strtol(yytext, NULL, 0); if (errno == ERANGE) { /* Overflow */ if (yytext[0] == '0') { /* octal overflow */ zendlval->value.dval = zend_oct_strtod(yytext, NULL); } else { zendlval->value.dval = zend_strtod(yytext, NULL); } zendlval->type = IS_DOUBLE; return T_DNUMBER; } } zendlval->type = IS_LONG; return T_LNUMBER; } #line 2956 "Zend/zend_language_scanner.c" yy173: YYDEBUG(173, *YYCURSOR); yyaccept = 2; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych == '.') goto yy187; if (yych <= '/') goto yy172; goto yy190; } else { if (yych <= 'E') { if (yych <= 'D') goto yy172; goto yy192; } else { if (yych == 'e') goto yy192; goto yy172; } } yy174: YYDEBUG(174, *YYCURSOR); yych = *++YYCURSOR; goto yy186; yy175: YYDEBUG(175, *YYCURSOR); ++YYCURSOR; yy176: YYDEBUG(176, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1887 "Zend/zend_language_scanner.l" { while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '\r': if (*YYCURSOR == '\n') { YYCURSOR++; } /* fall through */ case '\n': CG(zend_lineno)++; break; case '%': if (!CG(asp_tags)) { continue; } /* fall through */ case '?': if (*YYCURSOR == '>') { YYCURSOR--; break; } /* fall through */ default: continue; } break; } yyleng = YYCURSOR - SCNG(yy_text); return T_COMMENT; } #line 3018 "Zend/zend_language_scanner.c" yy177: YYDEBUG(177, *YYCURSOR); ++YYCURSOR; yy178: YYDEBUG(178, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1978 "Zend/zend_language_scanner.l" { register char *s, *t; char *end; int bprefix = (yytext[0] != '\'') ? 1 : 0; while (1) { if (YYCURSOR < YYLIMIT) { if (*YYCURSOR == '\'') { YYCURSOR++; yyleng = YYCURSOR - SCNG(yy_text); break; } else if (*YYCURSOR++ == '\\' && YYCURSOR < YYLIMIT) { YYCURSOR++; } } else { yyleng = YYLIMIT - SCNG(yy_text); /* Unclosed single quotes; treat similar to double quotes, but without a separate token * for ' (unrecognized by parser), instead of old flex fallback to "Unexpected character..." * rule, which continued in ST_IN_SCRIPTING state after the quote */ return T_ENCAPSED_AND_WHITESPACE; } } zendlval->value.str.val = estrndup(yytext+bprefix+1, yyleng-bprefix-2); zendlval->value.str.len = yyleng-bprefix-2; zendlval->type = IS_STRING; /* convert escape sequences */ s = t = zendlval->value.str.val; end = s+zendlval->value.str.len; while (s<end) { if (*s=='\\') { s++; switch(*s) { case '\\': case '\'': *t++ = *s; zendlval->value.str.len--; break; default: *t++ = '\\'; *t++ = *s; break; } } else { *t++ = *s; } if (*s == '\n' || (*s == '\r' && (*(s+1) != '\n'))) { CG(zend_lineno)++; } s++; } *t = 0; if (SCNG(output_filter)) { size_t sz = 0; s = zendlval->value.str.val; SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)s, (size_t)zendlval->value.str.len TSRMLS_CC); zendlval->value.str.len = sz; efree(s); } return T_CONSTANT_ENCAPSED_STRING; } #line 3093 "Zend/zend_language_scanner.c" yy179: YYDEBUG(179, *YYCURSOR); ++YYCURSOR; yy180: YYDEBUG(180, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2047 "Zend/zend_language_scanner.l" { int bprefix = (yytext[0] != '"') ? 1 : 0; while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '"': yyleng = YYCURSOR - SCNG(yy_text); zend_scan_escape_string(zendlval, yytext+bprefix+1, yyleng-bprefix-2, '"' TSRMLS_CC); return T_CONSTANT_ENCAPSED_STRING; case '$': if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { break; } continue; case '{': if (*YYCURSOR == '$') { break; } continue; case '\\': if (YYCURSOR < YYLIMIT) { YYCURSOR++; } /* fall through */ default: continue; } YYCURSOR--; break; } /* Remember how much was scanned to save rescanning */ SET_DOUBLE_QUOTES_SCANNED_LENGTH(YYCURSOR - SCNG(yy_text) - yyleng); YYCURSOR = SCNG(yy_text) + yyleng; BEGIN(ST_DOUBLE_QUOTES); return '"'; } #line 3141 "Zend/zend_language_scanner.c" yy181: YYDEBUG(181, *YYCURSOR); ++YYCURSOR; YYDEBUG(182, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2138 "Zend/zend_language_scanner.l" { BEGIN(ST_BACKQUOTE); return '`'; } #line 3152 "Zend/zend_language_scanner.c" yy183: YYDEBUG(183, *YYCURSOR); ++YYCURSOR; YYDEBUG(184, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2396 "Zend/zend_language_scanner.l" { if (YYCURSOR > YYLIMIT) { return 0; } zend_error(E_COMPILE_WARNING,"Unexpected character in input: '%c' (ASCII=%d) state=%d", yytext[0], yytext[0], YYSTATE); goto restart; } #line 3167 "Zend/zend_language_scanner.c" yy185: YYDEBUG(185, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy186: YYDEBUG(186, *YYCURSOR); if (yybm[0+yych] & 4) { goto yy185; } goto yy124; yy187: YYDEBUG(187, *YYCURSOR); yyaccept = 3; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(188, *YYCURSOR); if (yybm[0+yych] & 8) { goto yy187; } if (yych == 'E') goto yy192; if (yych == 'e') goto yy192; yy189: YYDEBUG(189, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1555 "Zend/zend_language_scanner.l" { zendlval->value.dval = zend_strtod(yytext, NULL); zendlval->type = IS_DOUBLE; return T_DNUMBER; } #line 3200 "Zend/zend_language_scanner.c" yy190: YYDEBUG(190, *YYCURSOR); yyaccept = 2; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(191, *YYCURSOR); if (yych <= '9') { if (yych == '.') goto yy187; if (yych <= '/') goto yy172; goto yy190; } else { if (yych <= 'E') { if (yych <= 'D') goto yy172; } else { if (yych != 'e') goto yy172; } } yy192: YYDEBUG(192, *YYCURSOR); yych = *++YYCURSOR; if (yych <= ',') { if (yych == '+') goto yy194; } else { if (yych <= '-') goto yy194; if (yych <= '/') goto yy193; if (yych <= '9') goto yy195; } yy193: YYDEBUG(193, *YYCURSOR); YYCURSOR = YYMARKER; if (yyaccept <= 2) { if (yyaccept <= 1) { if (yyaccept <= 0) { goto yy124; } else { goto yy138; } } else { goto yy172; } } else { if (yyaccept <= 4) { if (yyaccept <= 3) { goto yy189; } else { goto yy238; } } else { goto yy254; } } yy194: YYDEBUG(194, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy193; if (yych >= ':') goto yy193; yy195: YYDEBUG(195, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(196, *YYCURSOR); if (yych <= '/') goto yy189; if (yych <= '9') goto yy195; goto yy189; yy197: YYDEBUG(197, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 32) { goto yy202; } goto yy193; yy198: YYDEBUG(198, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 16) { goto yy199; } goto yy193; yy199: YYDEBUG(199, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(200, *YYCURSOR); if (yybm[0+yych] & 16) { goto yy199; } YYDEBUG(201, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1473 "Zend/zend_language_scanner.l" { char *bin = yytext + 2; /* Skip "0b" */ int len = yyleng - 2; /* Skip any leading 0s */ while (*bin == '0') { ++bin; --len; } if (len < SIZEOF_LONG * 8) { zendlval->value.lval = strtol(bin, NULL, 2); zendlval->type = IS_LONG; return T_LNUMBER; } else { zendlval->value.dval = zend_bin_strtod(bin, NULL); zendlval->type = IS_DOUBLE; return T_DNUMBER; } } #line 3313 "Zend/zend_language_scanner.c" yy202: YYDEBUG(202, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(203, *YYCURSOR); if (yybm[0+yych] & 32) { goto yy202; } YYDEBUG(204, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1515 "Zend/zend_language_scanner.l" { char *hex = yytext + 2; /* Skip "0x" */ int len = yyleng - 2; /* Skip any leading 0s */ while (*hex == '0') { hex++; len--; } if (len < SIZEOF_LONG * 2 || (len == SIZEOF_LONG * 2 && *hex <= '7')) { zendlval->value.lval = strtol(hex, NULL, 16); zendlval->type = IS_LONG; return T_LNUMBER; } else { zendlval->value.dval = zend_hex_strtod(hex, NULL); zendlval->type = IS_DOUBLE; return T_DNUMBER; } } #line 3346 "Zend/zend_language_scanner.c" yy205: YYDEBUG(205, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '\n') goto yy207; if (yych == '\r') goto yy208; yy206: YYDEBUG(206, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1955 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(INITIAL); return T_CLOSE_TAG; /* implicit ';' at php-end tag */ } #line 3363 "Zend/zend_language_scanner.c" yy207: YYDEBUG(207, *YYCURSOR); yych = *++YYCURSOR; goto yy206; yy208: YYDEBUG(208, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\n') goto yy207; goto yy206; yy209: YYDEBUG(209, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(210, *YYCURSOR); if (yych <= '^') { if (yych <= '9') { if (yych >= '0') goto yy209; } else { if (yych <= '@') goto yy211; if (yych <= 'Z') goto yy209; } } else { if (yych <= '`') { if (yych <= '_') goto yy209; } else { if (yych <= 'z') goto yy209; if (yych >= 0x7F) goto yy209; } } yy211: YYDEBUG(211, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1857 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 3403 "Zend/zend_language_scanner.c" yy212: YYDEBUG(212, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy213; if (yych != 'r') goto yy186; yy213: YYDEBUG(213, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(214, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1419 "Zend/zend_language_scanner.l" { return T_LOGICAL_XOR; } #line 3421 "Zend/zend_language_scanner.c" yy215: YYDEBUG(215, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(216, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1411 "Zend/zend_language_scanner.l" { return T_LOGICAL_OR; } #line 3434 "Zend/zend_language_scanner.c" yy217: YYDEBUG(217, *YYCURSOR); ++YYCURSOR; YYDEBUG(218, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1399 "Zend/zend_language_scanner.l" { return T_XOR_EQUAL; } #line 3444 "Zend/zend_language_scanner.c" yy219: YYDEBUG(219, *YYCURSOR); ++YYCURSOR; YYDEBUG(220, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1403 "Zend/zend_language_scanner.l" { return T_BOOLEAN_OR; } #line 3454 "Zend/zend_language_scanner.c" yy221: YYDEBUG(221, *YYCURSOR); ++YYCURSOR; YYDEBUG(222, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1395 "Zend/zend_language_scanner.l" { return T_OR_EQUAL; } #line 3464 "Zend/zend_language_scanner.c" yy223: YYDEBUG(223, *YYCURSOR); ++YYCURSOR; YYDEBUG(224, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1407 "Zend/zend_language_scanner.l" { return T_BOOLEAN_AND; } #line 3474 "Zend/zend_language_scanner.c" yy225: YYDEBUG(225, *YYCURSOR); ++YYCURSOR; YYDEBUG(226, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1391 "Zend/zend_language_scanner.l" { return T_AND_EQUAL; } #line 3484 "Zend/zend_language_scanner.c" yy227: YYDEBUG(227, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '\n') goto yy231; if (yych == '\r') goto yy232; yy228: YYDEBUG(228, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1964 "Zend/zend_language_scanner.l" { if (CG(asp_tags)) { BEGIN(INITIAL); zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; zendlval->value.str.val = yytext; /* no copying - intentional */ return T_CLOSE_TAG; /* implicit ';' at php-end tag */ } else { yyless(1); return yytext[0]; } } #line 3506 "Zend/zend_language_scanner.c" yy229: YYDEBUG(229, *YYCURSOR); ++YYCURSOR; YYDEBUG(230, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1379 "Zend/zend_language_scanner.l" { return T_MOD_EQUAL; } #line 3516 "Zend/zend_language_scanner.c" yy231: YYDEBUG(231, *YYCURSOR); yych = *++YYCURSOR; goto yy228; yy232: YYDEBUG(232, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\n') goto yy231; goto yy228; yy233: YYDEBUG(233, *YYCURSOR); yyaccept = 3; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(234, *YYCURSOR); if (yych <= 'D') { if (yych <= '/') goto yy189; if (yych <= '9') goto yy233; goto yy189; } else { if (yych <= 'E') goto yy192; if (yych == 'e') goto yy192; goto yy189; } yy235: YYDEBUG(235, *YYCURSOR); ++YYCURSOR; YYDEBUG(236, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1375 "Zend/zend_language_scanner.l" { return T_CONCAT_EQUAL; } #line 3551 "Zend/zend_language_scanner.c" yy237: YYDEBUG(237, *YYCURSOR); yyaccept = 4; yych = *(YYMARKER = ++YYCURSOR); if (yych == '*') goto yy242; yy238: YYDEBUG(238, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1921 "Zend/zend_language_scanner.l" { int doc_com; if (yyleng > 2) { doc_com = 1; RESET_DOC_COMMENT(); } else { doc_com = 0; } while (YYCURSOR < YYLIMIT) { if (*YYCURSOR++ == '*' && *YYCURSOR == '/') { break; } } if (YYCURSOR < YYLIMIT) { YYCURSOR++; } else { zend_error(E_COMPILE_WARNING, "Unterminated comment starting line %d", CG(zend_lineno)); } yyleng = YYCURSOR - SCNG(yy_text); HANDLE_NEWLINES(yytext, yyleng); if (doc_com) { CG(doc_comment) = estrndup(yytext, yyleng); CG(doc_comment_len) = yyleng; return T_DOC_COMMENT; } return T_COMMENT; } #line 3594 "Zend/zend_language_scanner.c" yy239: YYDEBUG(239, *YYCURSOR); yych = *++YYCURSOR; goto yy176; yy240: YYDEBUG(240, *YYCURSOR); ++YYCURSOR; YYDEBUG(241, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1371 "Zend/zend_language_scanner.l" { return T_DIV_EQUAL; } #line 3608 "Zend/zend_language_scanner.c" yy242: YYDEBUG(242, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 64) { goto yy243; } goto yy193; yy243: YYDEBUG(243, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(244, *YYCURSOR); if (yybm[0+yych] & 64) { goto yy243; } goto yy238; yy245: YYDEBUG(245, *YYCURSOR); ++YYCURSOR; YYDEBUG(246, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1367 "Zend/zend_language_scanner.l" { return T_MUL_EQUAL; } #line 3635 "Zend/zend_language_scanner.c" yy247: YYDEBUG(247, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '=') goto yy251; YYDEBUG(248, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1427 "Zend/zend_language_scanner.l" { return T_SR; } #line 3646 "Zend/zend_language_scanner.c" yy249: YYDEBUG(249, *YYCURSOR); ++YYCURSOR; YYDEBUG(250, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1355 "Zend/zend_language_scanner.l" { return T_IS_GREATER_OR_EQUAL; } #line 3656 "Zend/zend_language_scanner.c" yy251: YYDEBUG(251, *YYCURSOR); ++YYCURSOR; YYDEBUG(252, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1387 "Zend/zend_language_scanner.l" { return T_SR_EQUAL; } #line 3666 "Zend/zend_language_scanner.c" yy253: YYDEBUG(253, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ';') goto yy254; if (yych <= '<') goto yy269; if (yych <= '=') goto yy267; yy254: YYDEBUG(254, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1423 "Zend/zend_language_scanner.l" { return T_SL; } #line 3681 "Zend/zend_language_scanner.c" yy255: YYDEBUG(255, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy260; if (yych == 's') goto yy260; goto yy193; yy256: YYDEBUG(256, *YYCURSOR); ++YYCURSOR; YYDEBUG(257, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1351 "Zend/zend_language_scanner.l" { return T_IS_SMALLER_OR_EQUAL; } #line 3697 "Zend/zend_language_scanner.c" yy258: YYDEBUG(258, *YYCURSOR); ++YYCURSOR; yy259: YYDEBUG(259, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1347 "Zend/zend_language_scanner.l" { return T_IS_NOT_EQUAL; } #line 3708 "Zend/zend_language_scanner.c" yy260: YYDEBUG(260, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy261; if (yych != 'c') goto yy193; yy261: YYDEBUG(261, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy262; if (yych != 'r') goto yy193; yy262: YYDEBUG(262, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy263; if (yych != 'i') goto yy193; yy263: YYDEBUG(263, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy264; if (yych != 'p') goto yy193; yy264: YYDEBUG(264, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy265; if (yych != 't') goto yy193; yy265: YYDEBUG(265, *YYCURSOR); ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(266, *YYCURSOR); if (yych <= '\r') { if (yych <= 0x08) goto yy193; if (yych <= '\n') goto yy265; if (yych <= '\f') goto yy193; goto yy265; } else { if (yych <= ' ') { if (yych <= 0x1F) goto yy193; goto yy265; } else { if (yych == '>') goto yy205; goto yy193; } } yy267: YYDEBUG(267, *YYCURSOR); ++YYCURSOR; YYDEBUG(268, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1383 "Zend/zend_language_scanner.l" { return T_SL_EQUAL; } #line 3763 "Zend/zend_language_scanner.c" yy269: YYDEBUG(269, *YYCURSOR); ++YYCURSOR; YYFILL(2); yych = *YYCURSOR; YYDEBUG(270, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy269; } if (yych <= 'Z') { if (yych <= '&') { if (yych == '"') goto yy274; goto yy193; } else { if (yych <= '\'') goto yy273; if (yych <= '@') goto yy193; } } else { if (yych <= '`') { if (yych != '_') goto yy193; } else { if (yych <= 'z') goto yy271; if (yych <= '~') goto yy193; } } yy271: YYDEBUG(271, *YYCURSOR); ++YYCURSOR; YYFILL(2); yych = *YYCURSOR; YYDEBUG(272, *YYCURSOR); if (yych <= '@') { if (yych <= '\f') { if (yych == '\n') goto yy278; goto yy193; } else { if (yych <= '\r') goto yy280; if (yych <= '/') goto yy193; if (yych <= '9') goto yy271; goto yy193; } } else { if (yych <= '_') { if (yych <= 'Z') goto yy271; if (yych <= '^') goto yy193; goto yy271; } else { if (yych <= '`') goto yy193; if (yych <= 'z') goto yy271; if (yych <= '~') goto yy193; goto yy271; } } yy273: YYDEBUG(273, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\'') goto yy193; if (yych <= '/') goto yy282; if (yych <= '9') goto yy193; goto yy282; yy274: YYDEBUG(274, *YYCURSOR); yych = *++YYCURSOR; if (yych == '"') goto yy193; if (yych <= '/') goto yy276; if (yych <= '9') goto yy193; goto yy276; yy275: YYDEBUG(275, *YYCURSOR); ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; yy276: YYDEBUG(276, *YYCURSOR); if (yych <= 'Z') { if (yych <= '/') { if (yych != '"') goto yy193; } else { if (yych <= '9') goto yy275; if (yych <= '@') goto yy193; goto yy275; } } else { if (yych <= '`') { if (yych == '_') goto yy275; goto yy193; } else { if (yych <= 'z') goto yy275; if (yych <= '~') goto yy193; goto yy275; } } yy277: YYDEBUG(277, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\n') goto yy278; if (yych == '\r') goto yy280; goto yy193; yy278: YYDEBUG(278, *YYCURSOR); ++YYCURSOR; yy279: YYDEBUG(279, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2089 "Zend/zend_language_scanner.l" { char *s; int bprefix = (yytext[0] != '<') ? 1 : 0; /* save old heredoc label */ Z_STRVAL_P(zendlval) = CG(heredoc); Z_STRLEN_P(zendlval) = CG(heredoc_len); CG(zend_lineno)++; CG(heredoc_len) = yyleng-bprefix-3-1-(yytext[yyleng-2]=='\r'?1:0); s = yytext+bprefix+3; while ((*s == ' ') || (*s == '\t')) { s++; CG(heredoc_len)--; } if (*s == '\'') { s++; CG(heredoc_len) -= 2; BEGIN(ST_NOWDOC); } else { if (*s == '"') { s++; CG(heredoc_len) -= 2; } BEGIN(ST_HEREDOC); } CG(heredoc) = estrndup(s, CG(heredoc_len)); /* Check for ending label on the next line */ if (CG(heredoc_len) < YYLIMIT - YYCURSOR && !memcmp(YYCURSOR, s, CG(heredoc_len))) { YYCTYPE *end = YYCURSOR + CG(heredoc_len); if (*end == ';') { end++; } if (*end == '\n' || *end == '\r') { BEGIN(ST_END_HEREDOC); } } return T_START_HEREDOC; } #line 3916 "Zend/zend_language_scanner.c" yy280: YYDEBUG(280, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\n') goto yy278; goto yy279; yy281: YYDEBUG(281, *YYCURSOR); ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; yy282: YYDEBUG(282, *YYCURSOR); if (yych <= 'Z') { if (yych <= '/') { if (yych == '\'') goto yy277; goto yy193; } else { if (yych <= '9') goto yy281; if (yych <= '@') goto yy193; goto yy281; } } else { if (yych <= '`') { if (yych == '_') goto yy281; goto yy193; } else { if (yych <= 'z') goto yy281; if (yych <= '~') goto yy193; goto yy281; } } yy283: YYDEBUG(283, *YYCURSOR); yych = *++YYCURSOR; if (yych != '=') goto yy259; YYDEBUG(284, *YYCURSOR); ++YYCURSOR; YYDEBUG(285, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1339 "Zend/zend_language_scanner.l" { return T_IS_NOT_IDENTICAL; } #line 3960 "Zend/zend_language_scanner.c" yy286: YYDEBUG(286, *YYCURSOR); ++YYCURSOR; YYDEBUG(287, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1359 "Zend/zend_language_scanner.l" { return T_PLUS_EQUAL; } #line 3970 "Zend/zend_language_scanner.c" yy288: YYDEBUG(288, *YYCURSOR); ++YYCURSOR; YYDEBUG(289, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1327 "Zend/zend_language_scanner.l" { return T_INC; } #line 3980 "Zend/zend_language_scanner.c" yy290: YYDEBUG(290, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy291; if (yych != 's') goto yy186; yy291: YYDEBUG(291, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy292; if (yych != 't') goto yy186; yy292: YYDEBUG(292, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(293, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1315 "Zend/zend_language_scanner.l" { return T_LIST; } #line 4003 "Zend/zend_language_scanner.c" yy294: YYDEBUG(294, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '=') goto yy298; YYDEBUG(295, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1343 "Zend/zend_language_scanner.l" { return T_IS_EQUAL; } #line 4014 "Zend/zend_language_scanner.c" yy296: YYDEBUG(296, *YYCURSOR); ++YYCURSOR; YYDEBUG(297, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1311 "Zend/zend_language_scanner.l" { return T_DOUBLE_ARROW; } #line 4024 "Zend/zend_language_scanner.c" yy298: YYDEBUG(298, *YYCURSOR); ++YYCURSOR; YYDEBUG(299, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1335 "Zend/zend_language_scanner.l" { return T_IS_IDENTICAL; } #line 4034 "Zend/zend_language_scanner.c" yy300: YYDEBUG(300, *YYCURSOR); yych = *++YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case 'C': case 'c': goto yy302; case 'D': case 'd': goto yy307; case 'F': case 'f': goto yy304; case 'H': case 'h': goto yy301; case 'L': case 'l': goto yy306; case 'M': case 'm': goto yy305; case 'N': case 'n': goto yy308; case 'T': case 't': goto yy303; default: goto yy186; } yy301: YYDEBUG(301, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy369; if (yych == 'a') goto yy369; goto yy186; yy302: YYDEBUG(302, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy362; if (yych == 'l') goto yy362; goto yy186; yy303: YYDEBUG(303, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy355; if (yych == 'r') goto yy355; goto yy186; yy304: YYDEBUG(304, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'I') goto yy339; if (yych <= 'T') goto yy186; goto yy340; } else { if (yych <= 'i') { if (yych <= 'h') goto yy186; goto yy339; } else { if (yych == 'u') goto yy340; goto yy186; } } yy305: YYDEBUG(305, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy331; if (yych == 'e') goto yy331; goto yy186; yy306: YYDEBUG(306, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy325; if (yych == 'i') goto yy325; goto yy186; yy307: YYDEBUG(307, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy320; if (yych == 'i') goto yy320; goto yy186; yy308: YYDEBUG(308, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy309; if (yych != 'a') goto yy186; yy309: YYDEBUG(309, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy310; if (yych != 'm') goto yy186; yy310: YYDEBUG(310, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy311; if (yych != 'e') goto yy186; yy311: YYDEBUG(311, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy312; if (yych != 's') goto yy186; yy312: YYDEBUG(312, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy313; if (yych != 'p') goto yy186; yy313: YYDEBUG(313, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy314; if (yych != 'a') goto yy186; yy314: YYDEBUG(314, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy315; if (yych != 'c') goto yy186; yy315: YYDEBUG(315, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy316; if (yych != 'e') goto yy186; yy316: YYDEBUG(316, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(317, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(318, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(319, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1690 "Zend/zend_language_scanner.l" { if (CG(current_namespace)) { *zendlval = *CG(current_namespace); zval_copy_ctor(zendlval); } else { ZVAL_EMPTY_STRING(zendlval); } return T_NS_C; } #line 4174 "Zend/zend_language_scanner.c" yy320: YYDEBUG(320, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy321; if (yych != 'r') goto yy186; yy321: YYDEBUG(321, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(322, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(323, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(324, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1663 "Zend/zend_language_scanner.l" { char *filename = zend_get_compiled_filename(TSRMLS_C); const size_t filename_len = strlen(filename); char *dirname; if (!filename) { filename = ""; } dirname = estrndup(filename, filename_len); zend_dirname(dirname, filename_len); if (strcmp(dirname, ".") == 0) { dirname = erealloc(dirname, MAXPATHLEN); #if HAVE_GETCWD VCWD_GETCWD(dirname, MAXPATHLEN); #elif HAVE_GETWD VCWD_GETWD(dirname); #endif } zendlval->value.str.len = strlen(dirname); zendlval->value.str.val = dirname; zendlval->type = IS_STRING; return T_DIR; } #line 4221 "Zend/zend_language_scanner.c" yy325: YYDEBUG(325, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy326; if (yych != 'n') goto yy186; yy326: YYDEBUG(326, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy327; if (yych != 'e') goto yy186; yy327: YYDEBUG(327, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(328, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(329, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(330, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1645 "Zend/zend_language_scanner.l" { zendlval->value.lval = CG(zend_lineno); zendlval->type = IS_LONG; return T_LINE; } #line 4252 "Zend/zend_language_scanner.c" yy331: YYDEBUG(331, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy332; if (yych != 't') goto yy186; yy332: YYDEBUG(332, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy333; if (yych != 'h') goto yy186; yy333: YYDEBUG(333, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy334; if (yych != 'o') goto yy186; yy334: YYDEBUG(334, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy335; if (yych != 'd') goto yy186; yy335: YYDEBUG(335, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(336, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(337, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(338, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1624 "Zend/zend_language_scanner.l" { const char *class_name = CG(active_class_entry) ? CG(active_class_entry)->name : NULL; const char *func_name = CG(active_op_array)? CG(active_op_array)->function_name : NULL; size_t len = 0; if (class_name) { len += strlen(class_name) + 2; } if (func_name) { len += strlen(func_name); } zendlval->value.str.len = zend_spprintf(&zendlval->value.str.val, 0, "%s%s%s", class_name ? class_name : "", class_name && func_name ? "::" : "", func_name ? func_name : "" ); zendlval->type = IS_STRING; return T_METHOD_C; } #line 4308 "Zend/zend_language_scanner.c" yy339: YYDEBUG(339, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy350; if (yych == 'l') goto yy350; goto yy186; yy340: YYDEBUG(340, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy341; if (yych != 'n') goto yy186; yy341: YYDEBUG(341, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy342; if (yych != 'c') goto yy186; yy342: YYDEBUG(342, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy343; if (yych != 't') goto yy186; yy343: YYDEBUG(343, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy344; if (yych != 'i') goto yy186; yy344: YYDEBUG(344, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy345; if (yych != 'o') goto yy186; yy345: YYDEBUG(345, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy346; if (yych != 'n') goto yy186; yy346: YYDEBUG(346, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(347, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(348, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(349, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1608 "Zend/zend_language_scanner.l" { const char *func_name = NULL; if (CG(active_op_array)) { func_name = CG(active_op_array)->function_name; } if (!func_name) { func_name = ""; } zendlval->value.str.len = strlen(func_name); zendlval->value.str.val = estrndup(func_name, zendlval->value.str.len); zendlval->type = IS_STRING; return T_FUNC_C; } #line 4375 "Zend/zend_language_scanner.c" yy350: YYDEBUG(350, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy351; if (yych != 'e') goto yy186; yy351: YYDEBUG(351, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(352, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(353, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(354, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1651 "Zend/zend_language_scanner.l" { char *filename = zend_get_compiled_filename(TSRMLS_C); if (!filename) { filename = ""; } zendlval->value.str.len = strlen(filename); zendlval->value.str.val = estrndup(filename, zendlval->value.str.len); zendlval->type = IS_STRING; return T_FILE; } #line 4407 "Zend/zend_language_scanner.c" yy355: YYDEBUG(355, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy356; if (yych != 'a') goto yy186; yy356: YYDEBUG(356, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy357; if (yych != 'i') goto yy186; yy357: YYDEBUG(357, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy358; if (yych != 't') goto yy186; yy358: YYDEBUG(358, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(359, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(360, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(361, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1588 "Zend/zend_language_scanner.l" { const char *trait_name = NULL; if (CG(active_class_entry) && (ZEND_ACC_TRAIT == (CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT))) { trait_name = CG(active_class_entry)->name; } if (!trait_name) { trait_name = ""; } zendlval->value.str.len = strlen(trait_name); zendlval->value.str.val = estrndup(trait_name, zendlval->value.str.len); zendlval->type = IS_STRING; return T_TRAIT_C; } #line 4457 "Zend/zend_language_scanner.c" yy362: YYDEBUG(362, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy363; if (yych != 'a') goto yy186; yy363: YYDEBUG(363, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy364; if (yych != 's') goto yy186; yy364: YYDEBUG(364, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy365; if (yych != 's') goto yy186; yy365: YYDEBUG(365, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(366, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(367, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(368, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1561 "Zend/zend_language_scanner.l" { const char *class_name = NULL; if (CG(active_class_entry) && (ZEND_ACC_TRAIT == (CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT))) { /* We create a special __CLASS__ constant that is going to be resolved at run-time */ zendlval->value.str.len = sizeof("__CLASS__")-1; zendlval->value.str.val = estrndup("__CLASS__", zendlval->value.str.len); zendlval->type = IS_CONSTANT; } else { if (CG(active_class_entry)) { class_name = CG(active_class_entry)->name; } if (!class_name) { class_name = ""; } zendlval->value.str.len = strlen(class_name); zendlval->value.str.val = estrndup(class_name, zendlval->value.str.len); zendlval->type = IS_STRING; } return T_CLASS_C; } #line 4514 "Zend/zend_language_scanner.c" yy369: YYDEBUG(369, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy370; if (yych != 'l') goto yy186; yy370: YYDEBUG(370, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy371; if (yych != 't') goto yy186; yy371: YYDEBUG(371, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(372, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy373; if (yych != 'c') goto yy186; yy373: YYDEBUG(373, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy374; if (yych != 'o') goto yy186; yy374: YYDEBUG(374, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy375; if (yych != 'm') goto yy186; yy375: YYDEBUG(375, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy376; if (yych != 'p') goto yy186; yy376: YYDEBUG(376, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy377; if (yych != 'i') goto yy186; yy377: YYDEBUG(377, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy378; if (yych != 'l') goto yy186; yy378: YYDEBUG(378, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy379; if (yych != 'e') goto yy186; yy379: YYDEBUG(379, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy380; if (yych != 'r') goto yy186; yy380: YYDEBUG(380, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(381, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1279 "Zend/zend_language_scanner.l" { return T_HALT_COMPILER; } #line 4580 "Zend/zend_language_scanner.c" yy382: YYDEBUG(382, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy386; if (yych == 's') goto yy386; goto yy186; yy383: YYDEBUG(383, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy384; if (yych != 'e') goto yy186; yy384: YYDEBUG(384, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(385, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1259 "Zend/zend_language_scanner.l" { return T_USE; } #line 4604 "Zend/zend_language_scanner.c" yy386: YYDEBUG(386, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy387; if (yych != 'e') goto yy186; yy387: YYDEBUG(387, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy388; if (yych != 't') goto yy186; yy388: YYDEBUG(388, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(389, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1307 "Zend/zend_language_scanner.l" { return T_UNSET; } #line 4627 "Zend/zend_language_scanner.c" yy390: YYDEBUG(390, *YYCURSOR); ++YYCURSOR; YYFILL(7); yych = *YYCURSOR; yy391: YYDEBUG(391, *YYCURSOR); if (yych <= 'S') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy390; if (yych <= 0x1F) goto yy193; goto yy390; } else { if (yych <= 'A') { if (yych <= '@') goto yy193; goto yy395; } else { if (yych <= 'B') goto yy393; if (yych <= 'C') goto yy193; goto yy398; } } } else { if (yych <= 'I') { if (yych == 'F') goto yy399; if (yych <= 'H') goto yy193; goto yy400; } else { if (yych <= 'O') { if (yych <= 'N') goto yy193; goto yy394; } else { if (yych <= 'Q') goto yy193; if (yych <= 'R') goto yy397; goto yy396; } } } } else { if (yych <= 'f') { if (yych <= 'a') { if (yych == 'U') goto yy392; if (yych <= '`') goto yy193; goto yy395; } else { if (yych <= 'c') { if (yych <= 'b') goto yy393; goto yy193; } else { if (yych <= 'd') goto yy398; if (yych <= 'e') goto yy193; goto yy399; } } } else { if (yych <= 'q') { if (yych <= 'i') { if (yych <= 'h') goto yy193; goto yy400; } else { if (yych == 'o') goto yy394; goto yy193; } } else { if (yych <= 's') { if (yych <= 'r') goto yy397; goto yy396; } else { if (yych != 'u') goto yy193; } } } } yy392: YYDEBUG(392, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy459; if (yych == 'n') goto yy459; goto yy193; yy393: YYDEBUG(393, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'I') goto yy446; if (yych <= 'N') goto yy193; goto yy447; } else { if (yych <= 'i') { if (yych <= 'h') goto yy193; goto yy446; } else { if (yych == 'o') goto yy447; goto yy193; } } yy394: YYDEBUG(394, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy438; if (yych == 'b') goto yy438; goto yy193; yy395: YYDEBUG(395, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy431; if (yych == 'r') goto yy431; goto yy193; yy396: YYDEBUG(396, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy423; if (yych == 't') goto yy423; goto yy193; yy397: YYDEBUG(397, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy421; if (yych == 'e') goto yy421; goto yy193; yy398: YYDEBUG(398, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy417; if (yych == 'o') goto yy417; goto yy193; yy399: YYDEBUG(399, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy410; if (yych == 'l') goto yy410; goto yy193; yy400: YYDEBUG(400, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy401; if (yych != 'n') goto yy193; yy401: YYDEBUG(401, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy402; if (yych != 't') goto yy193; yy402: YYDEBUG(402, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy403; if (yych != 'e') goto yy405; yy403: YYDEBUG(403, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy408; if (yych == 'g') goto yy408; goto yy193; yy404: YYDEBUG(404, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy405: YYDEBUG(405, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy404; goto yy193; } else { if (yych <= ' ') goto yy404; if (yych != ')') goto yy193; } YYDEBUG(406, *YYCURSOR); ++YYCURSOR; YYDEBUG(407, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1207 "Zend/zend_language_scanner.l" { return T_INT_CAST; } #line 4803 "Zend/zend_language_scanner.c" yy408: YYDEBUG(408, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy409; if (yych != 'e') goto yy193; yy409: YYDEBUG(409, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy404; if (yych == 'r') goto yy404; goto yy193; yy410: YYDEBUG(410, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy411; if (yych != 'o') goto yy193; yy411: YYDEBUG(411, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy412; if (yych != 'a') goto yy193; yy412: YYDEBUG(412, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy413; if (yych != 't') goto yy193; yy413: YYDEBUG(413, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(414, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy413; goto yy193; } else { if (yych <= ' ') goto yy413; if (yych != ')') goto yy193; } YYDEBUG(415, *YYCURSOR); ++YYCURSOR; YYDEBUG(416, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1211 "Zend/zend_language_scanner.l" { return T_DOUBLE_CAST; } #line 4851 "Zend/zend_language_scanner.c" yy417: YYDEBUG(417, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy418; if (yych != 'u') goto yy193; yy418: YYDEBUG(418, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy419; if (yych != 'b') goto yy193; yy419: YYDEBUG(419, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy420; if (yych != 'l') goto yy193; yy420: YYDEBUG(420, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy413; if (yych == 'e') goto yy413; goto yy193; yy421: YYDEBUG(421, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy422; if (yych != 'a') goto yy193; yy422: YYDEBUG(422, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy413; if (yych == 'l') goto yy413; goto yy193; yy423: YYDEBUG(423, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy424; if (yych != 'r') goto yy193; yy424: YYDEBUG(424, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy425; if (yych != 'i') goto yy193; yy425: YYDEBUG(425, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy426; if (yych != 'n') goto yy193; yy426: YYDEBUG(426, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy427; if (yych != 'g') goto yy193; yy427: YYDEBUG(427, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(428, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy427; goto yy193; } else { if (yych <= ' ') goto yy427; if (yych != ')') goto yy193; } YYDEBUG(429, *YYCURSOR); ++YYCURSOR; YYDEBUG(430, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1215 "Zend/zend_language_scanner.l" { return T_STRING_CAST; } #line 4925 "Zend/zend_language_scanner.c" yy431: YYDEBUG(431, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy432; if (yych != 'r') goto yy193; yy432: YYDEBUG(432, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy433; if (yych != 'a') goto yy193; yy433: YYDEBUG(433, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy434; if (yych != 'y') goto yy193; yy434: YYDEBUG(434, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(435, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy434; goto yy193; } else { if (yych <= ' ') goto yy434; if (yych != ')') goto yy193; } YYDEBUG(436, *YYCURSOR); ++YYCURSOR; YYDEBUG(437, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1219 "Zend/zend_language_scanner.l" { return T_ARRAY_CAST; } #line 4962 "Zend/zend_language_scanner.c" yy438: YYDEBUG(438, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'J') goto yy439; if (yych != 'j') goto yy193; yy439: YYDEBUG(439, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy440; if (yych != 'e') goto yy193; yy440: YYDEBUG(440, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy441; if (yych != 'c') goto yy193; yy441: YYDEBUG(441, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy442; if (yych != 't') goto yy193; yy442: YYDEBUG(442, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(443, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy442; goto yy193; } else { if (yych <= ' ') goto yy442; if (yych != ')') goto yy193; } YYDEBUG(444, *YYCURSOR); ++YYCURSOR; YYDEBUG(445, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1223 "Zend/zend_language_scanner.l" { return T_OBJECT_CAST; } #line 5004 "Zend/zend_language_scanner.c" yy446: YYDEBUG(446, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy456; if (yych == 'n') goto yy456; goto yy193; yy447: YYDEBUG(447, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy448; if (yych != 'o') goto yy193; yy448: YYDEBUG(448, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy449; if (yych != 'l') goto yy193; yy449: YYDEBUG(449, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy454; if (yych == 'e') goto yy454; goto yy451; yy450: YYDEBUG(450, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy451: YYDEBUG(451, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy450; goto yy193; } else { if (yych <= ' ') goto yy450; if (yych != ')') goto yy193; } YYDEBUG(452, *YYCURSOR); ++YYCURSOR; YYDEBUG(453, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1227 "Zend/zend_language_scanner.l" { return T_BOOL_CAST; } #line 5049 "Zend/zend_language_scanner.c" yy454: YYDEBUG(454, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy455; if (yych != 'a') goto yy193; yy455: YYDEBUG(455, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy450; if (yych == 'n') goto yy450; goto yy193; yy456: YYDEBUG(456, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy457; if (yych != 'a') goto yy193; yy457: YYDEBUG(457, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy458; if (yych != 'r') goto yy193; yy458: YYDEBUG(458, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy427; if (yych == 'y') goto yy427; goto yy193; yy459: YYDEBUG(459, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy460; if (yych != 's') goto yy193; yy460: YYDEBUG(460, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy461; if (yych != 'e') goto yy193; yy461: YYDEBUG(461, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy462; if (yych != 't') goto yy193; yy462: YYDEBUG(462, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(463, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy462; goto yy193; } else { if (yych <= ' ') goto yy462; if (yych != ')') goto yy193; } YYDEBUG(464, *YYCURSOR); ++YYCURSOR; YYDEBUG(465, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1231 "Zend/zend_language_scanner.l" { return T_UNSET_CAST; } #line 5113 "Zend/zend_language_scanner.c" yy466: YYDEBUG(466, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy467; if (yych != 'r') goto yy186; yy467: YYDEBUG(467, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(468, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1203 "Zend/zend_language_scanner.l" { return T_VAR; } #line 5131 "Zend/zend_language_scanner.c" yy469: YYDEBUG(469, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy473; if (yych == 'm') goto yy473; goto yy186; yy470: YYDEBUG(470, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'W') goto yy471; if (yych != 'w') goto yy186; yy471: YYDEBUG(471, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(472, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1195 "Zend/zend_language_scanner.l" { return T_NEW; } #line 5155 "Zend/zend_language_scanner.c" yy473: YYDEBUG(473, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy474; if (yych != 'e') goto yy186; yy474: YYDEBUG(474, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy475; if (yych != 's') goto yy186; yy475: YYDEBUG(475, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy476; if (yych != 'p') goto yy186; yy476: YYDEBUG(476, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy477; if (yych != 'a') goto yy186; yy477: YYDEBUG(477, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy478; if (yych != 'c') goto yy186; yy478: YYDEBUG(478, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy479; if (yych != 'e') goto yy186; yy479: YYDEBUG(479, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(480, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1255 "Zend/zend_language_scanner.l" { return T_NAMESPACE; } #line 5198 "Zend/zend_language_scanner.c" yy481: YYDEBUG(481, *YYCURSOR); ++YYCURSOR; YYDEBUG(482, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1187 "Zend/zend_language_scanner.l" { return T_PAAMAYIM_NEKUDOTAYIM; } #line 5208 "Zend/zend_language_scanner.c" yy483: YYDEBUG(483, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy484: YYDEBUG(484, *YYCURSOR); if (yych <= '\f') { if (yych <= 0x08) goto yy140; if (yych <= '\n') goto yy483; goto yy140; } else { if (yych <= '\r') goto yy483; if (yych == ' ') goto yy483; goto yy140; } yy485: YYDEBUG(485, *YYCURSOR); ++YYCURSOR; YYDEBUG(486, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1363 "Zend/zend_language_scanner.l" { return T_MINUS_EQUAL; } #line 5234 "Zend/zend_language_scanner.c" yy487: YYDEBUG(487, *YYCURSOR); ++YYCURSOR; YYDEBUG(488, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1331 "Zend/zend_language_scanner.l" { return T_DEC; } #line 5244 "Zend/zend_language_scanner.c" yy489: YYDEBUG(489, *YYCURSOR); ++YYCURSOR; YYDEBUG(490, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1157 "Zend/zend_language_scanner.l" { yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC); return T_OBJECT_OPERATOR; } #line 5255 "Zend/zend_language_scanner.c" yy491: YYDEBUG(491, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'I') goto yy498; if (yych <= 'N') goto yy186; goto yy499; } else { if (yych <= 'i') { if (yych <= 'h') goto yy186; goto yy498; } else { if (yych == 'o') goto yy499; goto yy186; } } yy492: YYDEBUG(492, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy493; if (yych != 'b') goto yy186; yy493: YYDEBUG(493, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy494; if (yych != 'l') goto yy186; yy494: YYDEBUG(494, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy495; if (yych != 'i') goto yy186; yy495: YYDEBUG(495, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy496; if (yych != 'c') goto yy186; yy496: YYDEBUG(496, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(497, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1303 "Zend/zend_language_scanner.l" { return T_PUBLIC; } #line 5304 "Zend/zend_language_scanner.c" yy498: YYDEBUG(498, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'V') { if (yych == 'N') goto yy507; if (yych <= 'U') goto yy186; goto yy508; } else { if (yych <= 'n') { if (yych <= 'm') goto yy186; goto yy507; } else { if (yych == 'v') goto yy508; goto yy186; } } yy499: YYDEBUG(499, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy500; if (yych != 't') goto yy186; yy500: YYDEBUG(500, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy501; if (yych != 'e') goto yy186; yy501: YYDEBUG(501, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy502; if (yych != 'c') goto yy186; yy502: YYDEBUG(502, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy503; if (yych != 't') goto yy186; yy503: YYDEBUG(503, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy504; if (yych != 'e') goto yy186; yy504: YYDEBUG(504, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy505; if (yych != 'd') goto yy186; yy505: YYDEBUG(505, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(506, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1299 "Zend/zend_language_scanner.l" { return T_PROTECTED; } #line 5363 "Zend/zend_language_scanner.c" yy507: YYDEBUG(507, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy513; if (yych == 't') goto yy513; goto yy186; yy508: YYDEBUG(508, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy509; if (yych != 'a') goto yy186; yy509: YYDEBUG(509, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy510; if (yych != 't') goto yy186; yy510: YYDEBUG(510, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy511; if (yych != 'e') goto yy186; yy511: YYDEBUG(511, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(512, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1295 "Zend/zend_language_scanner.l" { return T_PRIVATE; } #line 5397 "Zend/zend_language_scanner.c" yy513: YYDEBUG(513, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(514, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1133 "Zend/zend_language_scanner.l" { return T_PRINT; } #line 5410 "Zend/zend_language_scanner.c" yy515: YYDEBUG(515, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy520; if (yych == 'o') goto yy520; goto yy186; yy516: YYDEBUG(516, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy517; if (yych != 't') goto yy186; yy517: YYDEBUG(517, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy518; if (yych != 'o') goto yy186; yy518: YYDEBUG(518, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(519, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1125 "Zend/zend_language_scanner.l" { return T_GOTO; } #line 5439 "Zend/zend_language_scanner.c" yy520: YYDEBUG(520, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy521; if (yych != 'b') goto yy186; yy521: YYDEBUG(521, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy522; if (yych != 'a') goto yy186; yy522: YYDEBUG(522, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy523; if (yych != 'l') goto yy186; yy523: YYDEBUG(523, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(524, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1267 "Zend/zend_language_scanner.l" { return T_GLOBAL; } #line 5467 "Zend/zend_language_scanner.c" yy525: YYDEBUG(525, *YYCURSOR); yych = *++YYCURSOR; if (yych == '<') goto yy533; goto yy193; yy526: YYDEBUG(526, *YYCURSOR); yych = *++YYCURSOR; goto yy180; yy527: YYDEBUG(527, *YYCURSOR); yych = *++YYCURSOR; goto yy178; yy528: YYDEBUG(528, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy529; if (yych != 'e') goto yy186; yy529: YYDEBUG(529, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy530; if (yych != 'a') goto yy186; yy530: YYDEBUG(530, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'K') goto yy531; if (yych != 'k') goto yy186; yy531: YYDEBUG(531, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(532, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1117 "Zend/zend_language_scanner.l" { return T_BREAK; } #line 5508 "Zend/zend_language_scanner.c" yy533: YYDEBUG(533, *YYCURSOR); yych = *++YYCURSOR; if (yych == '<') goto yy269; goto yy193; yy534: YYDEBUG(534, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy541; if (yych == 'a') goto yy541; goto yy186; yy535: YYDEBUG(535, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy536; if (yych != 'i') goto yy186; yy536: YYDEBUG(536, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy537; if (yych != 't') goto yy186; yy537: YYDEBUG(537, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy538; if (yych != 'c') goto yy186; yy538: YYDEBUG(538, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy539; if (yych != 'h') goto yy186; yy539: YYDEBUG(539, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(540, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1101 "Zend/zend_language_scanner.l" { return T_SWITCH; } #line 5552 "Zend/zend_language_scanner.c" yy541: YYDEBUG(541, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy542; if (yych != 't') goto yy186; yy542: YYDEBUG(542, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy543; if (yych != 'i') goto yy186; yy543: YYDEBUG(543, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy544; if (yych != 'c') goto yy186; yy544: YYDEBUG(544, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(545, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1283 "Zend/zend_language_scanner.l" { return T_STATIC; } #line 5580 "Zend/zend_language_scanner.c" yy546: YYDEBUG(546, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy557; if (yych == 's') goto yy557; goto yy186; yy547: YYDEBUG(547, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy555; if (yych == 'd') goto yy555; goto yy186; yy548: YYDEBUG(548, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy551; if (yych == 'r') goto yy551; goto yy186; yy549: YYDEBUG(549, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(550, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1097 "Zend/zend_language_scanner.l" { return T_AS; } #line 5611 "Zend/zend_language_scanner.c" yy551: YYDEBUG(551, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy552; if (yych != 'a') goto yy186; yy552: YYDEBUG(552, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy553; if (yych != 'y') goto yy186; yy553: YYDEBUG(553, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(554, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1319 "Zend/zend_language_scanner.l" { return T_ARRAY; } #line 5634 "Zend/zend_language_scanner.c" yy555: YYDEBUG(555, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(556, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1415 "Zend/zend_language_scanner.l" { return T_LOGICAL_AND; } #line 5647 "Zend/zend_language_scanner.c" yy557: YYDEBUG(557, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy558; if (yych != 't') goto yy186; yy558: YYDEBUG(558, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy559; if (yych != 'r') goto yy186; yy559: YYDEBUG(559, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy560; if (yych != 'a') goto yy186; yy560: YYDEBUG(560, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy561; if (yych != 'c') goto yy186; yy561: YYDEBUG(561, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy562; if (yych != 't') goto yy186; yy562: YYDEBUG(562, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(563, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1287 "Zend/zend_language_scanner.l" { return T_ABSTRACT; } #line 5685 "Zend/zend_language_scanner.c" yy564: YYDEBUG(564, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy565; if (yych != 'i') goto yy186; yy565: YYDEBUG(565, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy566; if (yych != 'l') goto yy186; yy566: YYDEBUG(566, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy567; if (yych != 'e') goto yy186; yy567: YYDEBUG(567, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(568, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1057 "Zend/zend_language_scanner.l" { return T_WHILE; } #line 5713 "Zend/zend_language_scanner.c" yy569: YYDEBUG(569, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(570, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1041 "Zend/zend_language_scanner.l" { return T_IF; } #line 5726 "Zend/zend_language_scanner.c" yy571: YYDEBUG(571, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy613; if (yych == 'p') goto yy613; goto yy186; yy572: YYDEBUG(572, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= 'C') { if (yych <= 'B') goto yy186; goto yy580; } else { if (yych <= 'R') goto yy186; if (yych <= 'S') goto yy578; goto yy579; } } else { if (yych <= 'r') { if (yych == 'c') goto yy580; goto yy186; } else { if (yych <= 's') goto yy578; if (yych <= 't') goto yy579; goto yy186; } } yy573: YYDEBUG(573, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy574; if (yych != 's') goto yy186; yy574: YYDEBUG(574, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy575; if (yych != 'e') goto yy186; yy575: YYDEBUG(575, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy576; if (yych != 't') goto yy186; yy576: YYDEBUG(576, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(577, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1271 "Zend/zend_language_scanner.l" { return T_ISSET; } #line 5782 "Zend/zend_language_scanner.c" yy578: YYDEBUG(578, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy599; if (yych == 't') goto yy599; goto yy186; yy579: YYDEBUG(579, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy592; if (yych == 'e') goto yy592; goto yy186; yy580: YYDEBUG(580, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy581; if (yych != 'l') goto yy186; yy581: YYDEBUG(581, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy582; if (yych != 'u') goto yy186; yy582: YYDEBUG(582, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy583; if (yych != 'd') goto yy186; yy583: YYDEBUG(583, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy584; if (yych != 'e') goto yy186; yy584: YYDEBUG(584, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '9') { if (yych >= '0') goto yy185; } else { if (yych <= '@') goto yy585; if (yych <= 'Z') goto yy185; } } else { if (yych <= '`') { if (yych <= '_') goto yy586; } else { if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy585: YYDEBUG(585, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1239 "Zend/zend_language_scanner.l" { return T_INCLUDE; } #line 5840 "Zend/zend_language_scanner.c" yy586: YYDEBUG(586, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy587; if (yych != 'o') goto yy186; yy587: YYDEBUG(587, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy588; if (yych != 'n') goto yy186; yy588: YYDEBUG(588, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy589; if (yych != 'c') goto yy186; yy589: YYDEBUG(589, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy590; if (yych != 'e') goto yy186; yy590: YYDEBUG(590, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(591, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1243 "Zend/zend_language_scanner.l" { return T_INCLUDE_ONCE; } #line 5873 "Zend/zend_language_scanner.c" yy592: YYDEBUG(592, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy593; if (yych != 'r') goto yy186; yy593: YYDEBUG(593, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy594; if (yych != 'f') goto yy186; yy594: YYDEBUG(594, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy595; if (yych != 'a') goto yy186; yy595: YYDEBUG(595, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy596; if (yych != 'c') goto yy186; yy596: YYDEBUG(596, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy597; if (yych != 'e') goto yy186; yy597: YYDEBUG(597, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(598, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1141 "Zend/zend_language_scanner.l" { return T_INTERFACE; } #line 5911 "Zend/zend_language_scanner.c" yy599: YYDEBUG(599, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych == 'A') goto yy600; if (yych <= 'D') goto yy186; goto yy601; } else { if (yych <= 'a') { if (yych <= '`') goto yy186; } else { if (yych == 'e') goto yy601; goto yy186; } } yy600: YYDEBUG(600, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy607; if (yych == 'n') goto yy607; goto yy186; yy601: YYDEBUG(601, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy602; if (yych != 'a') goto yy186; yy602: YYDEBUG(602, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy603; if (yych != 'd') goto yy186; yy603: YYDEBUG(603, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy604; if (yych != 'o') goto yy186; yy604: YYDEBUG(604, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy605; if (yych != 'f') goto yy186; yy605: YYDEBUG(605, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(606, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1263 "Zend/zend_language_scanner.l" { return T_INSTEADOF; } #line 5965 "Zend/zend_language_scanner.c" yy607: YYDEBUG(607, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy608; if (yych != 'c') goto yy186; yy608: YYDEBUG(608, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy609; if (yych != 'e') goto yy186; yy609: YYDEBUG(609, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy610; if (yych != 'o') goto yy186; yy610: YYDEBUG(610, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy611; if (yych != 'f') goto yy186; yy611: YYDEBUG(611, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(612, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1093 "Zend/zend_language_scanner.l" { return T_INSTANCEOF; } #line 5998 "Zend/zend_language_scanner.c" yy613: YYDEBUG(613, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy614; if (yych != 'l') goto yy186; yy614: YYDEBUG(614, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy615; if (yych != 'e') goto yy186; yy615: YYDEBUG(615, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy616; if (yych != 'm') goto yy186; yy616: YYDEBUG(616, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy617; if (yych != 'e') goto yy186; yy617: YYDEBUG(617, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy618; if (yych != 'n') goto yy186; yy618: YYDEBUG(618, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy619; if (yych != 't') goto yy186; yy619: YYDEBUG(619, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy620; if (yych != 's') goto yy186; yy620: YYDEBUG(620, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(621, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1153 "Zend/zend_language_scanner.l" { return T_IMPLEMENTS; } #line 6046 "Zend/zend_language_scanner.c" yy622: YYDEBUG(622, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy630; if (yych == 'r') goto yy630; goto yy186; yy623: YYDEBUG(623, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych == 'A') goto yy626; if (yych <= 'X') goto yy186; } else { if (yych <= 'a') { if (yych <= '`') goto yy186; goto yy626; } else { if (yych != 'y') goto yy186; } } YYDEBUG(624, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(625, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1029 "Zend/zend_language_scanner.l" { return T_TRY; } #line 6078 "Zend/zend_language_scanner.c" yy626: YYDEBUG(626, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy627; if (yych != 'i') goto yy186; yy627: YYDEBUG(627, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy628; if (yych != 't') goto yy186; yy628: YYDEBUG(628, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(629, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1145 "Zend/zend_language_scanner.l" { return T_TRAIT; } #line 6101 "Zend/zend_language_scanner.c" yy630: YYDEBUG(630, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy631; if (yych != 'o') goto yy186; yy631: YYDEBUG(631, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'W') goto yy632; if (yych != 'w') goto yy186; yy632: YYDEBUG(632, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(633, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1037 "Zend/zend_language_scanner.l" { return T_THROW; } #line 6124 "Zend/zend_language_scanner.c" yy634: YYDEBUG(634, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych == 'Q') goto yy636; if (yych <= 'S') goto yy186; } else { if (yych <= 'q') { if (yych <= 'p') goto yy186; goto yy636; } else { if (yych != 't') goto yy186; } } YYDEBUG(635, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy648; if (yych == 'u') goto yy648; goto yy186; yy636: YYDEBUG(636, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy637; if (yych != 'u') goto yy186; yy637: YYDEBUG(637, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy638; if (yych != 'i') goto yy186; yy638: YYDEBUG(638, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy639; if (yych != 'r') goto yy186; yy639: YYDEBUG(639, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy640; if (yych != 'e') goto yy186; yy640: YYDEBUG(640, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '9') { if (yych >= '0') goto yy185; } else { if (yych <= '@') goto yy641; if (yych <= 'Z') goto yy185; } } else { if (yych <= '`') { if (yych <= '_') goto yy642; } else { if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy641: YYDEBUG(641, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1247 "Zend/zend_language_scanner.l" { return T_REQUIRE; } #line 6189 "Zend/zend_language_scanner.c" yy642: YYDEBUG(642, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy643; if (yych != 'o') goto yy186; yy643: YYDEBUG(643, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy644; if (yych != 'n') goto yy186; yy644: YYDEBUG(644, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy645; if (yych != 'c') goto yy186; yy645: YYDEBUG(645, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy646; if (yych != 'e') goto yy186; yy646: YYDEBUG(646, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(647, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1251 "Zend/zend_language_scanner.l" { return T_REQUIRE_ONCE; } #line 6222 "Zend/zend_language_scanner.c" yy648: YYDEBUG(648, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy649; if (yych != 'r') goto yy186; yy649: YYDEBUG(649, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy650; if (yych != 'n') goto yy186; yy650: YYDEBUG(650, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(651, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1025 "Zend/zend_language_scanner.l" { return T_RETURN; } #line 6245 "Zend/zend_language_scanner.c" yy652: YYDEBUG(652, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= 'L') { if (yych <= 'K') goto yy186; goto yy675; } else { if (yych <= 'R') goto yy186; if (yych <= 'S') goto yy674; goto yy673; } } else { if (yych <= 'r') { if (yych == 'l') goto yy675; goto yy186; } else { if (yych <= 's') goto yy674; if (yych <= 't') goto yy673; goto yy186; } } yy653: YYDEBUG(653, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'A') goto yy665; if (yych <= 'N') goto yy186; goto yy666; } else { if (yych <= 'a') { if (yych <= '`') goto yy186; goto yy665; } else { if (yych == 'o') goto yy666; goto yy186; } } yy654: YYDEBUG(654, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy655; if (yych != 'n') goto yy186; yy655: YYDEBUG(655, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= 'R') goto yy186; if (yych >= 'T') goto yy657; } else { if (yych <= 'r') goto yy186; if (yych <= 's') goto yy656; if (yych <= 't') goto yy657; goto yy186; } yy656: YYDEBUG(656, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy663; if (yych == 't') goto yy663; goto yy186; yy657: YYDEBUG(657, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy658; if (yych != 'i') goto yy186; yy658: YYDEBUG(658, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy659; if (yych != 'n') goto yy186; yy659: YYDEBUG(659, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy660; if (yych != 'u') goto yy186; yy660: YYDEBUG(660, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy661; if (yych != 'e') goto yy186; yy661: YYDEBUG(661, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(662, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1121 "Zend/zend_language_scanner.l" { return T_CONTINUE; } #line 6339 "Zend/zend_language_scanner.c" yy663: YYDEBUG(663, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(664, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1021 "Zend/zend_language_scanner.l" { return T_CONST; } #line 6352 "Zend/zend_language_scanner.c" yy665: YYDEBUG(665, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy670; if (yych == 's') goto yy670; goto yy186; yy666: YYDEBUG(666, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy667; if (yych != 'n') goto yy186; yy667: YYDEBUG(667, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy668; if (yych != 'e') goto yy186; yy668: YYDEBUG(668, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(669, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1199 "Zend/zend_language_scanner.l" { return T_CLONE; } #line 6381 "Zend/zend_language_scanner.c" yy670: YYDEBUG(670, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy671; if (yych != 's') goto yy186; yy671: YYDEBUG(671, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(672, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1137 "Zend/zend_language_scanner.l" { return T_CLASS; } #line 6399 "Zend/zend_language_scanner.c" yy673: YYDEBUG(673, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy684; if (yych == 'c') goto yy684; goto yy186; yy674: YYDEBUG(674, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy682; if (yych == 'e') goto yy682; goto yy186; yy675: YYDEBUG(675, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy676; if (yych != 'l') goto yy186; yy676: YYDEBUG(676, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy677; if (yych != 'a') goto yy186; yy677: YYDEBUG(677, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy678; if (yych != 'b') goto yy186; yy678: YYDEBUG(678, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy679; if (yych != 'l') goto yy186; yy679: YYDEBUG(679, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy680; if (yych != 'e') goto yy186; yy680: YYDEBUG(680, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(681, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1323 "Zend/zend_language_scanner.l" { return T_CALLABLE; } #line 6449 "Zend/zend_language_scanner.c" yy682: YYDEBUG(682, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(683, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1109 "Zend/zend_language_scanner.l" { return T_CASE; } #line 6462 "Zend/zend_language_scanner.c" yy684: YYDEBUG(684, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy685; if (yych != 'h') goto yy186; yy685: YYDEBUG(685, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(686, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1033 "Zend/zend_language_scanner.l" { return T_CATCH; } #line 6480 "Zend/zend_language_scanner.c" yy687: YYDEBUG(687, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy704; if (yych == 'n') goto yy704; goto yy186; yy688: YYDEBUG(688, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy697; if (yych == 'r') goto yy697; goto yy186; yy689: YYDEBUG(689, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy690; if (yych != 'n') goto yy186; yy690: YYDEBUG(690, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy691; if (yych != 'c') goto yy186; yy691: YYDEBUG(691, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy692; if (yych != 't') goto yy186; yy692: YYDEBUG(692, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy693; if (yych != 'i') goto yy186; yy693: YYDEBUG(693, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy694; if (yych != 'o') goto yy186; yy694: YYDEBUG(694, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy695; if (yych != 'n') goto yy186; yy695: YYDEBUG(695, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(696, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1017 "Zend/zend_language_scanner.l" { return T_FUNCTION; } #line 6535 "Zend/zend_language_scanner.c" yy697: YYDEBUG(697, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '@') { if (yych <= '/') goto yy698; if (yych <= '9') goto yy185; } else { if (yych == 'E') goto yy699; if (yych <= 'Z') goto yy185; } } else { if (yych <= 'd') { if (yych != '`') goto yy185; } else { if (yych <= 'e') goto yy699; if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy698: YYDEBUG(698, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1069 "Zend/zend_language_scanner.l" { return T_FOR; } #line 6563 "Zend/zend_language_scanner.c" yy699: YYDEBUG(699, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy700; if (yych != 'a') goto yy186; yy700: YYDEBUG(700, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy701; if (yych != 'c') goto yy186; yy701: YYDEBUG(701, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy702; if (yych != 'h') goto yy186; yy702: YYDEBUG(702, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(703, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1077 "Zend/zend_language_scanner.l" { return T_FOREACH; } #line 6591 "Zend/zend_language_scanner.c" yy704: YYDEBUG(704, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy705; if (yych != 'a') goto yy186; yy705: YYDEBUG(705, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy706; if (yych != 'l') goto yy186; yy706: YYDEBUG(706, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(707, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1291 "Zend/zend_language_scanner.l" { return T_FINAL; } #line 6614 "Zend/zend_language_scanner.c" yy708: YYDEBUG(708, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'F') { if (yych == 'C') goto yy714; if (yych <= 'E') goto yy186; goto yy715; } else { if (yych <= 'c') { if (yych <= 'b') goto yy186; goto yy714; } else { if (yych == 'f') goto yy715; goto yy186; } } yy709: YYDEBUG(709, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy712; if (yych == 'e') goto yy712; goto yy186; yy710: YYDEBUG(710, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(711, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1065 "Zend/zend_language_scanner.l" { return T_DO; } #line 6649 "Zend/zend_language_scanner.c" yy712: YYDEBUG(712, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(713, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1013 "Zend/zend_language_scanner.l" { return T_EXIT; } #line 6662 "Zend/zend_language_scanner.c" yy714: YYDEBUG(714, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy721; if (yych == 'l') goto yy721; goto yy186; yy715: YYDEBUG(715, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy716; if (yych != 'a') goto yy186; yy716: YYDEBUG(716, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy717; if (yych != 'u') goto yy186; yy717: YYDEBUG(717, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy718; if (yych != 'l') goto yy186; yy718: YYDEBUG(718, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy719; if (yych != 't') goto yy186; yy719: YYDEBUG(719, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(720, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1113 "Zend/zend_language_scanner.l" { return T_DEFAULT; } #line 6701 "Zend/zend_language_scanner.c" yy721: YYDEBUG(721, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy722; if (yych != 'a') goto yy186; yy722: YYDEBUG(722, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy723; if (yych != 'r') goto yy186; yy723: YYDEBUG(723, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy724; if (yych != 'e') goto yy186; yy724: YYDEBUG(724, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(725, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1085 "Zend/zend_language_scanner.l" { return T_DECLARE; } #line 6729 "Zend/zend_language_scanner.c" yy726: YYDEBUG(726, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy788; if (yych == 'h') goto yy788; goto yy186; yy727: YYDEBUG(727, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy782; if (yych == 's') goto yy782; goto yy186; yy728: YYDEBUG(728, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy778; if (yych == 'p') goto yy778; goto yy186; yy729: YYDEBUG(729, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy744; if (yych == 'd') goto yy744; goto yy186; yy730: YYDEBUG(730, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy741; if (yych == 'a') goto yy741; goto yy186; yy731: YYDEBUG(731, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych == 'I') goto yy732; if (yych <= 'S') goto yy186; goto yy733; } else { if (yych <= 'i') { if (yych <= 'h') goto yy186; } else { if (yych == 't') goto yy733; goto yy186; } } yy732: YYDEBUG(732, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy739; if (yych == 't') goto yy739; goto yy186; yy733: YYDEBUG(733, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy734; if (yych != 'e') goto yy186; yy734: YYDEBUG(734, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy735; if (yych != 'n') goto yy186; yy735: YYDEBUG(735, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy736; if (yych != 'd') goto yy186; yy736: YYDEBUG(736, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy737; if (yych != 's') goto yy186; yy737: YYDEBUG(737, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(738, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1149 "Zend/zend_language_scanner.l" { return T_EXTENDS; } #line 6813 "Zend/zend_language_scanner.c" yy739: YYDEBUG(739, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(740, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1009 "Zend/zend_language_scanner.l" { return T_EXIT; } #line 6826 "Zend/zend_language_scanner.c" yy741: YYDEBUG(741, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy742; if (yych != 'l') goto yy186; yy742: YYDEBUG(742, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(743, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1235 "Zend/zend_language_scanner.l" { return T_EVAL; } #line 6844 "Zend/zend_language_scanner.c" yy744: YYDEBUG(744, *YYCURSOR); yych = *++YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case 'D': case 'd': goto yy745; case 'F': case 'f': goto yy746; case 'I': case 'i': goto yy747; case 'S': case 's': goto yy748; case 'W': case 'w': goto yy749; default: goto yy186; } yy745: YYDEBUG(745, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy771; if (yych == 'e') goto yy771; goto yy186; yy746: YYDEBUG(746, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy763; if (yych == 'o') goto yy763; goto yy186; yy747: YYDEBUG(747, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy761; if (yych == 'f') goto yy761; goto yy186; yy748: YYDEBUG(748, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'W') goto yy755; if (yych == 'w') goto yy755; goto yy186; yy749: YYDEBUG(749, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy750; if (yych != 'h') goto yy186; yy750: YYDEBUG(750, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy751; if (yych != 'i') goto yy186; yy751: YYDEBUG(751, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy752; if (yych != 'l') goto yy186; yy752: YYDEBUG(752, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy753; if (yych != 'e') goto yy186; yy753: YYDEBUG(753, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(754, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1061 "Zend/zend_language_scanner.l" { return T_ENDWHILE; } #line 6918 "Zend/zend_language_scanner.c" yy755: YYDEBUG(755, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy756; if (yych != 'i') goto yy186; yy756: YYDEBUG(756, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy757; if (yych != 't') goto yy186; yy757: YYDEBUG(757, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy758; if (yych != 'c') goto yy186; yy758: YYDEBUG(758, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy759; if (yych != 'h') goto yy186; yy759: YYDEBUG(759, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(760, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1105 "Zend/zend_language_scanner.l" { return T_ENDSWITCH; } #line 6951 "Zend/zend_language_scanner.c" yy761: YYDEBUG(761, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(762, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1049 "Zend/zend_language_scanner.l" { return T_ENDIF; } #line 6964 "Zend/zend_language_scanner.c" yy763: YYDEBUG(763, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy764; if (yych != 'r') goto yy186; yy764: YYDEBUG(764, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '@') { if (yych <= '/') goto yy765; if (yych <= '9') goto yy185; } else { if (yych == 'E') goto yy766; if (yych <= 'Z') goto yy185; } } else { if (yych <= 'd') { if (yych != '`') goto yy185; } else { if (yych <= 'e') goto yy766; if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy765: YYDEBUG(765, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1073 "Zend/zend_language_scanner.l" { return T_ENDFOR; } #line 6997 "Zend/zend_language_scanner.c" yy766: YYDEBUG(766, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy767; if (yych != 'a') goto yy186; yy767: YYDEBUG(767, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy768; if (yych != 'c') goto yy186; yy768: YYDEBUG(768, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy769; if (yych != 'h') goto yy186; yy769: YYDEBUG(769, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(770, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1081 "Zend/zend_language_scanner.l" { return T_ENDFOREACH; } #line 7025 "Zend/zend_language_scanner.c" yy771: YYDEBUG(771, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy772; if (yych != 'c') goto yy186; yy772: YYDEBUG(772, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy773; if (yych != 'l') goto yy186; yy773: YYDEBUG(773, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy774; if (yych != 'a') goto yy186; yy774: YYDEBUG(774, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy775; if (yych != 'r') goto yy186; yy775: YYDEBUG(775, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy776; if (yych != 'e') goto yy186; yy776: YYDEBUG(776, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(777, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1089 "Zend/zend_language_scanner.l" { return T_ENDDECLARE; } #line 7063 "Zend/zend_language_scanner.c" yy778: YYDEBUG(778, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy779; if (yych != 't') goto yy186; yy779: YYDEBUG(779, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy780; if (yych != 'y') goto yy186; yy780: YYDEBUG(780, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(781, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1275 "Zend/zend_language_scanner.l" { return T_EMPTY; } #line 7086 "Zend/zend_language_scanner.c" yy782: YYDEBUG(782, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy783; if (yych != 'e') goto yy186; yy783: YYDEBUG(783, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '@') { if (yych <= '/') goto yy784; if (yych <= '9') goto yy185; } else { if (yych == 'I') goto yy785; if (yych <= 'Z') goto yy185; } } else { if (yych <= 'h') { if (yych != '`') goto yy185; } else { if (yych <= 'i') goto yy785; if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy784: YYDEBUG(784, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1053 "Zend/zend_language_scanner.l" { return T_ELSE; } #line 7119 "Zend/zend_language_scanner.c" yy785: YYDEBUG(785, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy786; if (yych != 'f') goto yy186; yy786: YYDEBUG(786, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(787, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1045 "Zend/zend_language_scanner.l" { return T_ELSEIF; } #line 7137 "Zend/zend_language_scanner.c" yy788: YYDEBUG(788, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy789; if (yych != 'o') goto yy186; yy789: YYDEBUG(789, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(790, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1129 "Zend/zend_language_scanner.l" { return T_ECHO; } #line 7155 "Zend/zend_language_scanner.c" } /* *********************************** */ yyc_ST_LOOKING_FOR_PROPERTY: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 0, 0, 0, 0, 0, 0, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 0, 0, 0, 0, 64, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 0, 0, 0, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, }; YYDEBUG(791, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych <= '-') { if (yych <= '\r') { if (yych <= 0x08) goto yy799; if (yych <= '\n') goto yy793; if (yych <= '\f') goto yy799; } else { if (yych == ' ') goto yy793; if (yych <= ',') goto yy799; goto yy795; } } else { if (yych <= '_') { if (yych <= '@') goto yy799; if (yych <= 'Z') goto yy797; if (yych <= '^') goto yy799; goto yy797; } else { if (yych <= '`') goto yy799; if (yych <= 'z') goto yy797; if (yych <= '~') goto yy799; goto yy797; } } yy793: YYDEBUG(793, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy805; yy794: YYDEBUG(794, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1162 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; HANDLE_NEWLINES(yytext, yyleng); return T_WHITESPACE; } #line 7236 "Zend/zend_language_scanner.c" yy795: YYDEBUG(795, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '>') goto yy802; yy796: YYDEBUG(796, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1181 "Zend/zend_language_scanner.l" { yyless(0); yy_pop_state(TSRMLS_C); goto restart; } #line 7250 "Zend/zend_language_scanner.c" yy797: YYDEBUG(797, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy801; yy798: YYDEBUG(798, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1174 "Zend/zend_language_scanner.l" { yy_pop_state(TSRMLS_C); zend_copy_value(zendlval, yytext, yyleng); zendlval->type = IS_STRING; return T_STRING; } #line 7266 "Zend/zend_language_scanner.c" yy799: YYDEBUG(799, *YYCURSOR); yych = *++YYCURSOR; goto yy796; yy800: YYDEBUG(800, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy801: YYDEBUG(801, *YYCURSOR); if (yybm[0+yych] & 64) { goto yy800; } goto yy798; yy802: YYDEBUG(802, *YYCURSOR); ++YYCURSOR; YYDEBUG(803, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1170 "Zend/zend_language_scanner.l" { return T_OBJECT_OPERATOR; } #line 7291 "Zend/zend_language_scanner.c" yy804: YYDEBUG(804, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy805: YYDEBUG(805, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy804; } goto yy794; } /* *********************************** */ yyc_ST_LOOKING_FOR_VARNAME: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; YYDEBUG(806, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy810; if (yych <= 'Z') goto yy808; if (yych <= '^') goto yy810; } else { if (yych <= '`') goto yy810; if (yych <= 'z') goto yy808; if (yych <= '~') goto yy810; } yy808: YYDEBUG(808, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy813; yy809: YYDEBUG(809, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1457 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, yytext, yyleng); zendlval->type = IS_STRING; yy_pop_state(TSRMLS_C); yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); return T_STRING_VARNAME; } #line 7369 "Zend/zend_language_scanner.c" yy810: YYDEBUG(810, *YYCURSOR); ++YYCURSOR; YYDEBUG(811, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1466 "Zend/zend_language_scanner.l" { yyless(0); yy_pop_state(TSRMLS_C); yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); goto restart; } #line 7382 "Zend/zend_language_scanner.c" yy812: YYDEBUG(812, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy813: YYDEBUG(813, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy812; } goto yy809; } /* *********************************** */ yyc_ST_NOWDOC: YYDEBUG(814, *YYCURSOR); YYFILL(1); yych = *YYCURSOR; YYDEBUG(816, *YYCURSOR); ++YYCURSOR; YYDEBUG(817, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2340 "Zend/zend_language_scanner.l" { int newline = 0; if (YYCURSOR > YYLIMIT) { return 0; } YYCURSOR--; while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '\r': if (*YYCURSOR == '\n') { YYCURSOR++; } /* fall through */ case '\n': /* Check for ending label on the next line */ if (IS_LABEL_START(*YYCURSOR) && CG(heredoc_len) < YYLIMIT - YYCURSOR && !memcmp(YYCURSOR, CG(heredoc), CG(heredoc_len))) { YYCTYPE *end = YYCURSOR + CG(heredoc_len); if (*end == ';') { end++; } if (*end == '\n' || *end == '\r') { /* newline before label will be subtracted from returned text, but * yyleng/yytext will include it, for zend_highlight/strip, tokenizer, etc. */ if (YYCURSOR[-2] == '\r' && YYCURSOR[-1] == '\n') { newline = 2; /* Windows newline */ } else { newline = 1; } CG(increment_lineno) = 1; /* For newline before label */ BEGIN(ST_END_HEREDOC); goto nowdoc_scan_done; } } /* fall through */ default: continue; } } nowdoc_scan_done: yyleng = YYCURSOR - SCNG(yy_text); zend_copy_value(zendlval, yytext, yyleng - newline); zendlval->type = IS_STRING; HANDLE_NEWLINES(yytext, yyleng - newline); return T_ENCAPSED_AND_WHITESPACE; } #line 7459 "Zend/zend_language_scanner.c" /* *********************************** */ yyc_ST_VAR_OFFSET: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 240, 240, 112, 112, 112, 112, 112, 112, 112, 112, 0, 0, 0, 0, 0, 0, 0, 80, 80, 80, 80, 80, 80, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 16, 0, 80, 80, 80, 80, 80, 80, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, }; YYDEBUG(818, *YYCURSOR); YYFILL(3); yych = *YYCURSOR; if (yych <= '/') { if (yych <= ' ') { if (yych <= '\f') { if (yych <= 0x08) goto yy832; if (yych <= '\n') goto yy828; goto yy832; } else { if (yych <= '\r') goto yy828; if (yych <= 0x1F) goto yy832; goto yy828; } } else { if (yych <= '$') { if (yych <= '"') goto yy827; if (yych <= '#') goto yy828; goto yy823; } else { if (yych == '\'') goto yy828; goto yy827; } } } else { if (yych <= '\\') { if (yych <= '@') { if (yych <= '0') goto yy820; if (yych <= '9') goto yy822; goto yy827; } else { if (yych <= 'Z') goto yy830; if (yych <= '[') goto yy827; goto yy828; } } else { if (yych <= '_') { if (yych <= ']') goto yy825; if (yych <= '^') goto yy827; goto yy830; } else { if (yych <= '`') goto yy827; if (yych <= 'z') goto yy830; if (yych <= '~') goto yy827; goto yy830; } } } yy820: YYDEBUG(820, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'W') { if (yych <= '9') { if (yych >= '0') goto yy844; } else { if (yych == 'B') goto yy841; } } else { if (yych <= 'b') { if (yych <= 'X') goto yy843; if (yych >= 'b') goto yy841; } else { if (yych == 'x') goto yy843; } } yy821: YYDEBUG(821, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1536 "Zend/zend_language_scanner.l" { /* Offset could be treated as a long */ if (yyleng < MAX_LENGTH_OF_LONG - 1 || (yyleng == MAX_LENGTH_OF_LONG - 1 && strcmp(yytext, long_min_digits) < 0)) { zendlval->value.lval = strtol(yytext, NULL, 10); zendlval->type = IS_LONG; } else { zendlval->value.str.val = (char *)estrndup(yytext, yyleng); zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; } return T_NUM_STRING; } #line 7578 "Zend/zend_language_scanner.c" yy822: YYDEBUG(822, *YYCURSOR); yych = *++YYCURSOR; goto yy840; yy823: YYDEBUG(823, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '_') { if (yych <= '@') goto yy824; if (yych <= 'Z') goto yy836; if (yych >= '_') goto yy836; } else { if (yych <= '`') goto yy824; if (yych <= 'z') goto yy836; if (yych >= 0x7F) goto yy836; } yy824: YYDEBUG(824, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1868 "Zend/zend_language_scanner.l" { /* Only '[' can be valid, but returning other tokens will allow a more explicit parse error */ return yytext[0]; } #line 7603 "Zend/zend_language_scanner.c" yy825: YYDEBUG(825, *YYCURSOR); ++YYCURSOR; YYDEBUG(826, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1863 "Zend/zend_language_scanner.l" { yy_pop_state(TSRMLS_C); return ']'; } #line 7614 "Zend/zend_language_scanner.c" yy827: YYDEBUG(827, *YYCURSOR); yych = *++YYCURSOR; goto yy824; yy828: YYDEBUG(828, *YYCURSOR); ++YYCURSOR; YYDEBUG(829, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1873 "Zend/zend_language_scanner.l" { /* Invalid rule to return a more explicit parse error with proper line number */ yyless(0); yy_pop_state(TSRMLS_C); return T_ENCAPSED_AND_WHITESPACE; } #line 7631 "Zend/zend_language_scanner.c" yy830: YYDEBUG(830, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy835; yy831: YYDEBUG(831, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1880 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, yytext, yyleng); zendlval->type = IS_STRING; return T_STRING; } #line 7646 "Zend/zend_language_scanner.c" yy832: YYDEBUG(832, *YYCURSOR); ++YYCURSOR; YYDEBUG(833, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2396 "Zend/zend_language_scanner.l" { if (YYCURSOR > YYLIMIT) { return 0; } zend_error(E_COMPILE_WARNING,"Unexpected character in input: '%c' (ASCII=%d) state=%d", yytext[0], yytext[0], YYSTATE); goto restart; } #line 7661 "Zend/zend_language_scanner.c" yy834: YYDEBUG(834, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy835: YYDEBUG(835, *YYCURSOR); if (yybm[0+yych] & 16) { goto yy834; } goto yy831; yy836: YYDEBUG(836, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(837, *YYCURSOR); if (yych <= '^') { if (yych <= '9') { if (yych >= '0') goto yy836; } else { if (yych <= '@') goto yy838; if (yych <= 'Z') goto yy836; } } else { if (yych <= '`') { if (yych <= '_') goto yy836; } else { if (yych <= 'z') goto yy836; if (yych >= 0x7F) goto yy836; } } yy838: YYDEBUG(838, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1857 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 7703 "Zend/zend_language_scanner.c" yy839: YYDEBUG(839, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy840: YYDEBUG(840, *YYCURSOR); if (yybm[0+yych] & 32) { goto yy839; } goto yy821; yy841: YYDEBUG(841, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 128) { goto yy849; } yy842: YYDEBUG(842, *YYCURSOR); YYCURSOR = YYMARKER; goto yy821; yy843: YYDEBUG(843, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 64) { goto yy847; } goto yy842; yy844: YYDEBUG(844, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(845, *YYCURSOR); if (yych <= '/') goto yy846; if (yych <= '9') goto yy844; yy846: YYDEBUG(846, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1548 "Zend/zend_language_scanner.l" { /* Offset must be treated as a string */ zendlval->value.str.val = (char *)estrndup(yytext, yyleng); zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; return T_NUM_STRING; } #line 7750 "Zend/zend_language_scanner.c" yy847: YYDEBUG(847, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(848, *YYCURSOR); if (yybm[0+yych] & 64) { goto yy847; } goto yy846; yy849: YYDEBUG(849, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(850, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy849; } goto yy846; } } #line 2405 "Zend/zend_language_scanner.l" } /* Generated by re2c 0.13.5 on Wed Feb 15 17:27:19 2012 */ #line 1 "Zend/zend_language_scanner.l" /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2012 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Marcus Boerger <[email protected]> | | Nuno Lopes <[email protected]> | | Scott MacVicar <[email protected]> | | Flex version authors: | | Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #if 0 # define YYDEBUG(s, c) printf("state: %d char: %c\n", s, c) #else # define YYDEBUG(s, c) #endif #include "zend_language_scanner_defs.h" #include <errno.h> #include "zend.h" #include "zend_alloc.h" #include <zend_language_parser.h> #include "zend_compile.h" #include "zend_language_scanner.h" #include "zend_highlight.h" #include "zend_constants.h" #include "zend_variables.h" #include "zend_operators.h" #include "zend_API.h" #include "zend_strtod.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "tsrm_config_common.h" #define YYCTYPE unsigned char #define YYFILL(n) { if ((YYCURSOR + n) >= (YYLIMIT + ZEND_MMAP_AHEAD)) { return 0; } } #define YYCURSOR SCNG(yy_cursor) #define YYLIMIT SCNG(yy_limit) #define YYMARKER SCNG(yy_marker) #define YYGETCONDITION() SCNG(yy_state) #define YYSETCONDITION(s) SCNG(yy_state) = s #define STATE(name) yyc##name /* emulate flex constructs */ #define BEGIN(state) YYSETCONDITION(STATE(state)) #define YYSTATE YYGETCONDITION() #define yytext ((char*)SCNG(yy_text)) #define yyleng SCNG(yy_leng) #define yyless(x) do { YYCURSOR = (unsigned char*)yytext + x; \ yyleng = (unsigned int)x; } while(0) #define yymore() goto yymore_restart /* perform sanity check. If this message is triggered you should increase the ZEND_MMAP_AHEAD value in the zend_streams.h file */ #define YYMAXFILL 16 #if ZEND_MMAP_AHEAD < YYMAXFILL # error ZEND_MMAP_AHEAD should be greater than or equal to YYMAXFILL #endif #ifdef HAVE_STDARG_H # include <stdarg.h> #endif #ifdef HAVE_UNISTD_H # include <unistd.h> #endif /* Globals Macros */ #define SCNG LANG_SCNG #ifdef ZTS ZEND_API ts_rsrc_id language_scanner_globals_id; #else ZEND_API zend_php_scanner_globals language_scanner_globals; #endif #define HANDLE_NEWLINES(s, l) \ do { \ char *p = (s), *boundary = p+(l); \ \ while (p<boundary) { \ if (*p == '\n' || (*p == '\r' && (*(p+1) != '\n'))) { \ CG(zend_lineno)++; \ } \ p++; \ } \ } while (0) #define HANDLE_NEWLINE(c) \ { \ if (c == '\n' || c == '\r') { \ CG(zend_lineno)++; \ } \ } /* To save initial string length after scanning to first variable, CG(doc_comment_len) can be reused */ #define SET_DOUBLE_QUOTES_SCANNED_LENGTH(len) CG(doc_comment_len) = (len) #define GET_DOUBLE_QUOTES_SCANNED_LENGTH() CG(doc_comment_len) #define IS_LABEL_START(c) (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z') || (c) == '_' || (c) >= 0x7F) #define ZEND_IS_OCT(c) ((c)>='0' && (c)<='7') #define ZEND_IS_HEX(c) (((c)>='0' && (c)<='9') || ((c)>='a' && (c)<='f') || ((c)>='A' && (c)<='F')) BEGIN_EXTERN_C() static size_t encoding_filter_script_to_internal(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) { const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding(TSRMLS_C); assert(internal_encoding && zend_multibyte_check_lexer_compatibility(internal_encoding)); return zend_multibyte_encoding_converter(to, to_length, from, from_length, internal_encoding, LANG_SCNG(script_encoding) TSRMLS_CC); } static size_t encoding_filter_script_to_intermediate(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) { return zend_multibyte_encoding_converter(to, to_length, from, from_length, zend_multibyte_encoding_utf8, LANG_SCNG(script_encoding) TSRMLS_CC); } static size_t encoding_filter_intermediate_to_script(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) { return zend_multibyte_encoding_converter(to, to_length, from, from_length, LANG_SCNG(script_encoding), zend_multibyte_encoding_utf8 TSRMLS_CC); } static size_t encoding_filter_intermediate_to_internal(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) { const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding(TSRMLS_C); assert(internal_encoding && zend_multibyte_check_lexer_compatibility(internal_encoding)); return zend_multibyte_encoding_converter(to, to_length, from, from_length, internal_encoding, zend_multibyte_encoding_utf8 TSRMLS_CC); } static void _yy_push_state(int new_state TSRMLS_DC) { zend_stack_push(&SCNG(state_stack), (void *) &YYGETCONDITION(), sizeof(int)); YYSETCONDITION(new_state); } #define yy_push_state(state_and_tsrm) _yy_push_state(yyc##state_and_tsrm) static void yy_pop_state(TSRMLS_D) { int *stack_state; zend_stack_top(&SCNG(state_stack), (void **) &stack_state); YYSETCONDITION(*stack_state); zend_stack_del_top(&SCNG(state_stack)); } static void yy_scan_buffer(char *str, unsigned int len TSRMLS_DC) { YYCURSOR = (YYCTYPE*)str; YYLIMIT = YYCURSOR + len; if (!SCNG(yy_start)) { SCNG(yy_start) = YYCURSOR; } } void startup_scanner(TSRMLS_D) { CG(parse_error) = 0; CG(heredoc) = NULL; CG(heredoc_len) = 0; CG(doc_comment) = NULL; CG(doc_comment_len) = 0; zend_stack_init(&SCNG(state_stack)); } void shutdown_scanner(TSRMLS_D) { if (CG(heredoc)) { efree(CG(heredoc)); CG(heredoc_len)=0; } CG(parse_error) = 0; zend_stack_destroy(&SCNG(state_stack)); RESET_DOC_COMMENT(); } ZEND_API void zend_save_lexical_state(zend_lex_state *lex_state TSRMLS_DC) { lex_state->yy_leng = SCNG(yy_leng); lex_state->yy_start = SCNG(yy_start); lex_state->yy_text = SCNG(yy_text); lex_state->yy_cursor = SCNG(yy_cursor); lex_state->yy_marker = SCNG(yy_marker); lex_state->yy_limit = SCNG(yy_limit); lex_state->state_stack = SCNG(state_stack); zend_stack_init(&SCNG(state_stack)); lex_state->in = SCNG(yy_in); lex_state->yy_state = YYSTATE; lex_state->filename = zend_get_compiled_filename(TSRMLS_C); lex_state->lineno = CG(zend_lineno); lex_state->script_org = SCNG(script_org); lex_state->script_org_size = SCNG(script_org_size); lex_state->script_filtered = SCNG(script_filtered); lex_state->script_filtered_size = SCNG(script_filtered_size); lex_state->input_filter = SCNG(input_filter); lex_state->output_filter = SCNG(output_filter); lex_state->script_encoding = SCNG(script_encoding); } ZEND_API void zend_restore_lexical_state(zend_lex_state *lex_state TSRMLS_DC) { SCNG(yy_leng) = lex_state->yy_leng; SCNG(yy_start) = lex_state->yy_start; SCNG(yy_text) = lex_state->yy_text; SCNG(yy_cursor) = lex_state->yy_cursor; SCNG(yy_marker) = lex_state->yy_marker; SCNG(yy_limit) = lex_state->yy_limit; zend_stack_destroy(&SCNG(state_stack)); SCNG(state_stack) = lex_state->state_stack; SCNG(yy_in) = lex_state->in; YYSETCONDITION(lex_state->yy_state); CG(zend_lineno) = lex_state->lineno; zend_restore_compiled_filename(lex_state->filename TSRMLS_CC); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } SCNG(script_org) = lex_state->script_org; SCNG(script_org_size) = lex_state->script_org_size; SCNG(script_filtered) = lex_state->script_filtered; SCNG(script_filtered_size) = lex_state->script_filtered_size; SCNG(input_filter) = lex_state->input_filter; SCNG(output_filter) = lex_state->output_filter; SCNG(script_encoding) = lex_state->script_encoding; if (CG(heredoc)) { efree(CG(heredoc)); CG(heredoc) = NULL; CG(heredoc_len) = 0; } } ZEND_API void zend_destroy_file_handle(zend_file_handle *file_handle TSRMLS_DC) { zend_llist_del_element(&CG(open_files), file_handle, (int (*)(void *, void *)) zend_compare_file_handles); /* zend_file_handle_dtor() operates on the copy, so we have to NULLify the original here */ file_handle->opened_path = NULL; if (file_handle->free_filename) { file_handle->filename = NULL; } } #define BOM_UTF32_BE "\x00\x00\xfe\xff" #define BOM_UTF32_LE "\xff\xfe\x00\x00" #define BOM_UTF16_BE "\xfe\xff" #define BOM_UTF16_LE "\xff\xfe" #define BOM_UTF8 "\xef\xbb\xbf" static const zend_encoding *zend_multibyte_detect_utf_encoding(const unsigned char *script, size_t script_size TSRMLS_DC) { const unsigned char *p; int wchar_size = 2; int le = 0; /* utf-16 or utf-32? */ p = script; while ((p-script) < script_size) { p = memchr(p, 0, script_size-(p-script)-2); if (!p) { break; } if (*(p+1) == '\0' && *(p+2) == '\0') { wchar_size = 4; break; } /* searching for UTF-32 specific byte orders, so this will do */ p += 4; } /* BE or LE? */ p = script; while ((p-script) < script_size) { if (*p == '\0' && *(p+wchar_size-1) != '\0') { /* BE */ le = 0; break; } else if (*p != '\0' && *(p+wchar_size-1) == '\0') { /* LE* */ le = 1; break; } p += wchar_size; } if (wchar_size == 2) { return le ? zend_multibyte_encoding_utf16le : zend_multibyte_encoding_utf16be; } else { return le ? zend_multibyte_encoding_utf32le : zend_multibyte_encoding_utf32be; } return NULL; } static const zend_encoding* zend_multibyte_detect_unicode(TSRMLS_D) { const zend_encoding *script_encoding = NULL; int bom_size; unsigned char *pos1, *pos2; if (LANG_SCNG(script_org_size) < sizeof(BOM_UTF32_LE)-1) { return NULL; } /* check out BOM */ if (!memcmp(LANG_SCNG(script_org), BOM_UTF32_BE, sizeof(BOM_UTF32_BE)-1)) { script_encoding = zend_multibyte_encoding_utf32be; bom_size = sizeof(BOM_UTF32_BE)-1; } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF32_LE, sizeof(BOM_UTF32_LE)-1)) { script_encoding = zend_multibyte_encoding_utf32le; bom_size = sizeof(BOM_UTF32_LE)-1; } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF16_BE, sizeof(BOM_UTF16_BE)-1)) { script_encoding = zend_multibyte_encoding_utf16be; bom_size = sizeof(BOM_UTF16_BE)-1; } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF16_LE, sizeof(BOM_UTF16_LE)-1)) { script_encoding = zend_multibyte_encoding_utf16le; bom_size = sizeof(BOM_UTF16_LE)-1; } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF8, sizeof(BOM_UTF8)-1)) { script_encoding = zend_multibyte_encoding_utf8; bom_size = sizeof(BOM_UTF8)-1; } if (script_encoding) { /* remove BOM */ LANG_SCNG(script_org) += bom_size; LANG_SCNG(script_org_size) -= bom_size; return script_encoding; } /* script contains NULL bytes -> auto-detection */ if ((pos1 = memchr(LANG_SCNG(script_org), 0, LANG_SCNG(script_org_size)))) { /* check if the NULL byte is after the __HALT_COMPILER(); */ pos2 = LANG_SCNG(script_org); while (pos1 - pos2 >= sizeof("__HALT_COMPILER();")-1) { pos2 = memchr(pos2, '_', pos1 - pos2); if (!pos2) break; pos2++; if (strncasecmp((char*)pos2, "_HALT_COMPILER", sizeof("_HALT_COMPILER")-1) == 0) { pos2 += sizeof("_HALT_COMPILER")-1; while (*pos2 == ' ' || *pos2 == '\t' || *pos2 == '\r' || *pos2 == '\n') { pos2++; } if (*pos2 == '(') { pos2++; while (*pos2 == ' ' || *pos2 == '\t' || *pos2 == '\r' || *pos2 == '\n') { pos2++; } if (*pos2 == ')') { pos2++; while (*pos2 == ' ' || *pos2 == '\t' || *pos2 == '\r' || *pos2 == '\n') { pos2++; } if (*pos2 == ';') { return NULL; } } } } } /* make best effort if BOM is missing */ return zend_multibyte_detect_utf_encoding(LANG_SCNG(script_org), LANG_SCNG(script_org_size) TSRMLS_CC); } return NULL; } static const zend_encoding* zend_multibyte_find_script_encoding(TSRMLS_D) { const zend_encoding *script_encoding; if (CG(detect_unicode)) { /* check out bom(byte order mark) and see if containing wchars */ script_encoding = zend_multibyte_detect_unicode(TSRMLS_C); if (script_encoding != NULL) { /* bom or wchar detection is prior to 'script_encoding' option */ return script_encoding; } } /* if no script_encoding specified, just leave alone */ if (!CG(script_encoding_list) || !CG(script_encoding_list_size)) { return NULL; } /* if multiple encodings specified, detect automagically */ if (CG(script_encoding_list_size) > 1) { return zend_multibyte_encoding_detector(LANG_SCNG(script_org), LANG_SCNG(script_org_size), CG(script_encoding_list), CG(script_encoding_list_size) TSRMLS_CC); } return CG(script_encoding_list)[0]; } ZEND_API int zend_multibyte_set_filter(const zend_encoding *onetime_encoding TSRMLS_DC) { const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding(TSRMLS_C); const zend_encoding *script_encoding = onetime_encoding ? onetime_encoding: zend_multibyte_find_script_encoding(TSRMLS_C); if (!script_encoding) { return FAILURE; } /* judge input/output filter */ LANG_SCNG(script_encoding) = script_encoding; LANG_SCNG(input_filter) = NULL; LANG_SCNG(output_filter) = NULL; if (!internal_encoding || LANG_SCNG(script_encoding) == internal_encoding) { if (!zend_multibyte_check_lexer_compatibility(LANG_SCNG(script_encoding))) { /* and if not, work around w/ script_encoding -> utf-8 -> script_encoding conversion */ LANG_SCNG(input_filter) = encoding_filter_script_to_intermediate; LANG_SCNG(output_filter) = encoding_filter_intermediate_to_script; } else { LANG_SCNG(input_filter) = NULL; LANG_SCNG(output_filter) = NULL; } return SUCCESS; } if (zend_multibyte_check_lexer_compatibility(internal_encoding)) { LANG_SCNG(input_filter) = encoding_filter_script_to_internal; LANG_SCNG(output_filter) = NULL; } else if (zend_multibyte_check_lexer_compatibility(LANG_SCNG(script_encoding))) { LANG_SCNG(input_filter) = NULL; LANG_SCNG(output_filter) = encoding_filter_script_to_internal; } else { /* both script and internal encodings are incompatible w/ flex */ LANG_SCNG(input_filter) = encoding_filter_script_to_intermediate; LANG_SCNG(output_filter) = encoding_filter_intermediate_to_internal; } return 0; } ZEND_API int open_file_for_scanning(zend_file_handle *file_handle TSRMLS_DC) { const char *file_path = NULL; char *buf; size_t size, offset = 0; /* The shebang line was read, get the current position to obtain the buffer start */ if (CG(start_lineno) == 2 && file_handle->type == ZEND_HANDLE_FP && file_handle->handle.fp) { if ((offset = ftell(file_handle->handle.fp)) == -1) { offset = 0; } } if (zend_stream_fixup(file_handle, &buf, &size TSRMLS_CC) == FAILURE) { return FAILURE; } zend_llist_add_element(&CG(open_files), file_handle); if (file_handle->handle.stream.handle >= (void*)file_handle && file_handle->handle.stream.handle <= (void*)(file_handle+1)) { zend_file_handle *fh = (zend_file_handle*)zend_llist_get_last(&CG(open_files)); size_t diff = (char*)file_handle->handle.stream.handle - (char*)file_handle; fh->handle.stream.handle = (void*)(((char*)fh) + diff); file_handle->handle.stream.handle = fh->handle.stream.handle; } /* Reset the scanner for scanning the new file */ SCNG(yy_in) = file_handle; SCNG(yy_start) = NULL; if (size != -1) { if (CG(multibyte)) { SCNG(script_org) = (unsigned char*)buf; SCNG(script_org_size) = size; SCNG(script_filtered) = NULL; zend_multibyte_set_filter(NULL TSRMLS_CC); if (SCNG(input_filter)) { if ((size_t)-1 == SCNG(input_filter)(&SCNG(script_filtered), &SCNG(script_filtered_size), SCNG(script_org), SCNG(script_org_size) TSRMLS_CC)) { zend_error_noreturn(E_COMPILE_ERROR, "Could not convert the script from the detected " "encoding \"%s\" to a compatible encoding", zend_multibyte_get_encoding_name(LANG_SCNG(script_encoding))); } buf = (char*)SCNG(script_filtered); size = SCNG(script_filtered_size); } } SCNG(yy_start) = (unsigned char *)buf - offset; yy_scan_buffer(buf, size TSRMLS_CC); } else { zend_error_noreturn(E_COMPILE_ERROR, "zend_stream_mmap() failed"); } BEGIN(INITIAL); if (file_handle->opened_path) { file_path = file_handle->opened_path; } else { file_path = file_handle->filename; } zend_set_compiled_filename(file_path TSRMLS_CC); if (CG(start_lineno)) { CG(zend_lineno) = CG(start_lineno); CG(start_lineno) = 0; } else { CG(zend_lineno) = 1; } CG(increment_lineno) = 0; return SUCCESS; } END_EXTERN_C() ZEND_API zend_op_array *compile_file(zend_file_handle *file_handle, int type TSRMLS_DC) { zend_lex_state original_lex_state; zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array)); zend_op_array *original_active_op_array = CG(active_op_array); zend_op_array *retval=NULL; int compiler_result; zend_bool compilation_successful=0; znode retval_znode; zend_bool original_in_compilation = CG(in_compilation); retval_znode.op_type = IS_CONST; retval_znode.u.constant.type = IS_LONG; retval_znode.u.constant.value.lval = 1; Z_UNSET_ISREF(retval_znode.u.constant); Z_SET_REFCOUNT(retval_znode.u.constant, 1); zend_save_lexical_state(&original_lex_state TSRMLS_CC); retval = op_array; /* success oriented */ if (open_file_for_scanning(file_handle TSRMLS_CC)==FAILURE) { if (type==ZEND_REQUIRE) { zend_message_dispatcher(ZMSG_FAILED_REQUIRE_FOPEN, file_handle->filename TSRMLS_CC); zend_bailout(); } else { zend_message_dispatcher(ZMSG_FAILED_INCLUDE_FOPEN, file_handle->filename TSRMLS_CC); } compilation_successful=0; } else { init_op_array(op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(in_compilation) = 1; CG(active_op_array) = op_array; zend_init_compiler_context(TSRMLS_C); compiler_result = zendparse(TSRMLS_C); zend_do_return(&retval_znode, 0 TSRMLS_CC); CG(in_compilation) = original_in_compilation; if (compiler_result==1) { /* parser error */ zend_bailout(); } compilation_successful=1; } if (retval) { CG(active_op_array) = original_active_op_array; if (compilation_successful) { pass_two(op_array TSRMLS_CC); zend_release_labels(TSRMLS_C); } else { efree(op_array); retval = NULL; } } zend_restore_lexical_state(&original_lex_state TSRMLS_CC); return retval; } zend_op_array *compile_filename(int type, zval *filename TSRMLS_DC) { zend_file_handle file_handle; zval tmp; zend_op_array *retval; char *opened_path = NULL; if (filename->type != IS_STRING) { tmp = *filename; zval_copy_ctor(&tmp); convert_to_string(&tmp); filename = &tmp; } file_handle.filename = filename->value.str.val; file_handle.free_filename = 0; file_handle.type = ZEND_HANDLE_FILENAME; file_handle.opened_path = NULL; file_handle.handle.fp = NULL; retval = zend_compile_file(&file_handle, type TSRMLS_CC); if (retval && file_handle.handle.stream.handle) { int dummy = 1; if (!file_handle.opened_path) { file_handle.opened_path = opened_path = estrndup(filename->value.str.val, filename->value.str.len); } zend_hash_add(&EG(included_files), file_handle.opened_path, strlen(file_handle.opened_path)+1, (void *)&dummy, sizeof(int), NULL); if (opened_path) { efree(opened_path); } } zend_destroy_file_handle(&file_handle TSRMLS_CC); if (filename==&tmp) { zval_dtor(&tmp); } return retval; } ZEND_API int zend_prepare_string_for_scanning(zval *str, char *filename TSRMLS_DC) { char *buf; size_t size; /* enforce two trailing NULLs for flex... */ if (IS_INTERNED(str->value.str.val)) { char *tmp = safe_emalloc(1, str->value.str.len, ZEND_MMAP_AHEAD); memcpy(tmp, str->value.str.val, str->value.str.len + ZEND_MMAP_AHEAD); str->value.str.val = tmp; } else { str->value.str.val = safe_erealloc(str->value.str.val, 1, str->value.str.len, ZEND_MMAP_AHEAD); } memset(str->value.str.val + str->value.str.len, 0, ZEND_MMAP_AHEAD); SCNG(yy_in) = NULL; SCNG(yy_start) = NULL; buf = str->value.str.val; size = str->value.str.len; if (CG(multibyte)) { SCNG(script_org) = (unsigned char*)buf; SCNG(script_org_size) = size; SCNG(script_filtered) = NULL; zend_multibyte_set_filter(zend_multibyte_get_internal_encoding(TSRMLS_C) TSRMLS_CC); if (SCNG(input_filter)) { if ((size_t)-1 == SCNG(input_filter)(&SCNG(script_filtered), &SCNG(script_filtered_size), SCNG(script_org), SCNG(script_org_size) TSRMLS_CC)) { zend_error_noreturn(E_COMPILE_ERROR, "Could not convert the script from the detected " "encoding \"%s\" to a compatible encoding", zend_multibyte_get_encoding_name(LANG_SCNG(script_encoding))); } buf = (char*)SCNG(script_filtered); size = SCNG(script_filtered_size); } } yy_scan_buffer(buf, size TSRMLS_CC); zend_set_compiled_filename(filename TSRMLS_CC); CG(zend_lineno) = 1; CG(increment_lineno) = 0; return SUCCESS; } ZEND_API size_t zend_get_scanned_file_offset(TSRMLS_D) { size_t offset = SCNG(yy_cursor) - SCNG(yy_start); if (SCNG(input_filter)) { size_t original_offset = offset, length = 0; do { unsigned char *p = NULL; if ((size_t)-1 == SCNG(input_filter)(&p, &length, SCNG(script_org), offset TSRMLS_CC)) { return (size_t)-1; } efree(p); if (length > original_offset) { offset--; } else if (length < original_offset) { offset++; } } while (original_offset != length); } return offset; } zend_op_array *compile_string(zval *source_string, char *filename TSRMLS_DC) { zend_lex_state original_lex_state; zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array)); zend_op_array *original_active_op_array = CG(active_op_array); zend_op_array *retval; zval tmp; int compiler_result; zend_bool original_in_compilation = CG(in_compilation); if (source_string->value.str.len==0) { efree(op_array); return NULL; } CG(in_compilation) = 1; tmp = *source_string; zval_copy_ctor(&tmp); convert_to_string(&tmp); source_string = &tmp; zend_save_lexical_state(&original_lex_state TSRMLS_CC); if (zend_prepare_string_for_scanning(source_string, filename TSRMLS_CC)==FAILURE) { efree(op_array); retval = NULL; } else { zend_bool orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(op_array, ZEND_EVAL_CODE, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; CG(active_op_array) = op_array; zend_init_compiler_context(TSRMLS_C); BEGIN(ST_IN_SCRIPTING); compiler_result = zendparse(TSRMLS_C); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } if (compiler_result==1) { CG(active_op_array) = original_active_op_array; CG(unclean_shutdown)=1; destroy_op_array(op_array TSRMLS_CC); efree(op_array); retval = NULL; } else { zend_do_return(NULL, 0 TSRMLS_CC); CG(active_op_array) = original_active_op_array; pass_two(op_array TSRMLS_CC); zend_release_labels(TSRMLS_C); retval = op_array; } } zend_restore_lexical_state(&original_lex_state TSRMLS_CC); zval_dtor(&tmp); CG(in_compilation) = original_in_compilation; return retval; } BEGIN_EXTERN_C() int highlight_file(char *filename, zend_syntax_highlighter_ini *syntax_highlighter_ini TSRMLS_DC) { zend_lex_state original_lex_state; zend_file_handle file_handle; file_handle.type = ZEND_HANDLE_FILENAME; file_handle.filename = filename; file_handle.free_filename = 0; file_handle.opened_path = NULL; zend_save_lexical_state(&original_lex_state TSRMLS_CC); if (open_file_for_scanning(&file_handle TSRMLS_CC)==FAILURE) { zend_message_dispatcher(ZMSG_FAILED_HIGHLIGHT_FOPEN, filename TSRMLS_CC); zend_restore_lexical_state(&original_lex_state TSRMLS_CC); return FAILURE; } zend_highlight(syntax_highlighter_ini TSRMLS_CC); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } zend_destroy_file_handle(&file_handle TSRMLS_CC); zend_restore_lexical_state(&original_lex_state TSRMLS_CC); return SUCCESS; } int highlight_string(zval *str, zend_syntax_highlighter_ini *syntax_highlighter_ini, char *str_name TSRMLS_DC) { zend_lex_state original_lex_state; zval tmp = *str; str = &tmp; zval_copy_ctor(str); zend_save_lexical_state(&original_lex_state TSRMLS_CC); if (zend_prepare_string_for_scanning(str, str_name TSRMLS_CC)==FAILURE) { zend_restore_lexical_state(&original_lex_state TSRMLS_CC); return FAILURE; } BEGIN(INITIAL); zend_highlight(syntax_highlighter_ini TSRMLS_CC); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } zend_restore_lexical_state(&original_lex_state TSRMLS_CC); zval_dtor(str); return SUCCESS; } ZEND_API void zend_multibyte_yyinput_again(zend_encoding_filter old_input_filter, const zend_encoding *old_encoding TSRMLS_DC) { size_t length; unsigned char *new_yy_start; /* convert and set */ if (!SCNG(input_filter)) { if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } SCNG(script_filtered_size) = 0; length = SCNG(script_org_size); new_yy_start = SCNG(script_org); } else { if ((size_t)-1 == SCNG(input_filter)(&new_yy_start, &length, SCNG(script_org), SCNG(script_org_size) TSRMLS_CC)) { zend_error_noreturn(E_COMPILE_ERROR, "Could not convert the script from the detected " "encoding \"%s\" to a compatible encoding", zend_multibyte_get_encoding_name(LANG_SCNG(script_encoding))); } SCNG(script_filtered) = new_yy_start; SCNG(script_filtered_size) = length; } SCNG(yy_cursor) = new_yy_start + (SCNG(yy_cursor) - SCNG(yy_start)); SCNG(yy_marker) = new_yy_start + (SCNG(yy_marker) - SCNG(yy_start)); SCNG(yy_text) = new_yy_start + (SCNG(yy_text) - SCNG(yy_start)); SCNG(yy_limit) = new_yy_start + (SCNG(yy_limit) - SCNG(yy_start)); SCNG(yy_start) = new_yy_start; } # define zend_copy_value(zendlval, yytext, yyleng) \ if (SCNG(output_filter)) { \ size_t sz = 0; \ SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)yytext, (size_t)yyleng TSRMLS_CC); \ zendlval->value.str.len = sz; \ } else { \ zendlval->value.str.val = (char *) estrndup(yytext, yyleng); \ zendlval->value.str.len = yyleng; \ } static void zend_scan_escape_string(zval *zendlval, char *str, int len, char quote_type TSRMLS_DC) { register char *s, *t; char *end; ZVAL_STRINGL(zendlval, str, len, 1); /* convert escape sequences */ s = t = zendlval->value.str.val; end = s+zendlval->value.str.len; while (s<end) { if (*s=='\\') { s++; if (s >= end) { *t++ = '\\'; break; } switch(*s) { case 'n': *t++ = '\n'; zendlval->value.str.len--; break; case 'r': *t++ = '\r'; zendlval->value.str.len--; break; case 't': *t++ = '\t'; zendlval->value.str.len--; break; case 'f': *t++ = '\f'; zendlval->value.str.len--; break; case 'v': *t++ = '\v'; zendlval->value.str.len--; break; case 'e': *t++ = '\e'; zendlval->value.str.len--; break; case '"': case '`': if (*s != quote_type) { *t++ = '\\'; *t++ = *s; break; } case '\\': case '$': *t++ = *s; zendlval->value.str.len--; break; case 'x': case 'X': if (ZEND_IS_HEX(*(s+1))) { char hex_buf[3] = { 0, 0, 0 }; zendlval->value.str.len--; /* for the 'x' */ hex_buf[0] = *(++s); zendlval->value.str.len--; if (ZEND_IS_HEX(*(s+1))) { hex_buf[1] = *(++s); zendlval->value.str.len--; } *t++ = (char) strtol(hex_buf, NULL, 16); } else { *t++ = '\\'; *t++ = *s; } break; default: /* check for an octal */ if (ZEND_IS_OCT(*s)) { char octal_buf[4] = { 0, 0, 0, 0 }; octal_buf[0] = *s; zendlval->value.str.len--; if (ZEND_IS_OCT(*(s+1))) { octal_buf[1] = *(++s); zendlval->value.str.len--; if (ZEND_IS_OCT(*(s+1))) { octal_buf[2] = *(++s); zendlval->value.str.len--; } } *t++ = (char) strtol(octal_buf, NULL, 8); } else { *t++ = '\\'; *t++ = *s; } break; } } else { *t++ = *s; } if (*s == '\n' || (*s == '\r' && (*(s+1) != '\n'))) { CG(zend_lineno)++; } s++; } *t = 0; if (SCNG(output_filter)) { size_t sz = 0; s = zendlval->value.str.val; SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)s, (size_t)zendlval->value.str.len TSRMLS_CC); zendlval->value.str.len = sz; efree(s); } } int lex_scan(zval *zendlval TSRMLS_DC) { restart: SCNG(yy_text) = YYCURSOR; yymore_restart: #line 995 "Zend/zend_language_scanner.c" { YYCTYPE yych; unsigned int yyaccept = 0; if (YYGETCONDITION() < 5) { if (YYGETCONDITION() < 2) { if (YYGETCONDITION() < 1) { goto yyc_ST_IN_SCRIPTING; } else { goto yyc_ST_LOOKING_FOR_PROPERTY; } } else { if (YYGETCONDITION() < 3) { goto yyc_ST_BACKQUOTE; } else { if (YYGETCONDITION() < 4) { goto yyc_ST_DOUBLE_QUOTES; } else { goto yyc_ST_HEREDOC; } } } } else { if (YYGETCONDITION() < 7) { if (YYGETCONDITION() < 6) { goto yyc_ST_LOOKING_FOR_VARNAME; } else { goto yyc_ST_VAR_OFFSET; } } else { if (YYGETCONDITION() < 8) { goto yyc_INITIAL; } else { if (YYGETCONDITION() < 9) { goto yyc_ST_END_HEREDOC; } else { goto yyc_ST_NOWDOC; } } } } /* *********************************** */ yyc_INITIAL: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; YYDEBUG(0, *YYCURSOR); YYFILL(8); yych = *YYCURSOR; if (yych != '<') goto yy4; YYDEBUG(2, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '?') { if (yych == '%') goto yy7; if (yych >= '?') goto yy5; } else { if (yych <= 'S') { if (yych >= 'S') goto yy9; } else { if (yych == 's') goto yy9; } } yy3: YYDEBUG(3, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1779 "Zend/zend_language_scanner.l" { if (YYCURSOR > YYLIMIT) { return 0; } inline_char_handler: while (1) { YYCTYPE *ptr = memchr(YYCURSOR, '<', YYLIMIT - YYCURSOR); YYCURSOR = ptr ? ptr + 1 : YYLIMIT; if (YYCURSOR < YYLIMIT) { switch (*YYCURSOR) { case '?': if (CG(short_tags) || !strncasecmp((char*)YYCURSOR + 1, "php", 3) || (*(YYCURSOR + 1) == '=')) { /* Assume [ \t\n\r] follows "php" */ break; } continue; case '%': if (CG(asp_tags)) { break; } continue; case 's': case 'S': /* Probably NOT an opening PHP <script> tag, so don't end the HTML chunk yet * If it is, the PHP <script> tag rule checks for any HTML scanned before it */ YYCURSOR--; yymore(); default: continue; } YYCURSOR--; } break; } inline_html: yyleng = YYCURSOR - SCNG(yy_text); if (SCNG(output_filter)) { int readsize; size_t sz = 0; readsize = SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)yytext, (size_t)yyleng TSRMLS_CC); zendlval->value.str.len = sz; if (readsize < yyleng) { yyless(readsize); } } else { zendlval->value.str.val = (char *) estrndup(yytext, yyleng); zendlval->value.str.len = yyleng; } zendlval->type = IS_STRING; HANDLE_NEWLINES(yytext, yyleng); return T_INLINE_HTML; } #line 1154 "Zend/zend_language_scanner.c" yy4: YYDEBUG(4, *YYCURSOR); yych = *++YYCURSOR; goto yy3; yy5: YYDEBUG(5, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'O') { if (yych == '=') goto yy45; } else { if (yych <= 'P') goto yy47; if (yych == 'p') goto yy47; } yy6: YYDEBUG(6, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1767 "Zend/zend_language_scanner.l" { if (CG(short_tags)) { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG; } else { goto inline_char_handler; } } #line 1184 "Zend/zend_language_scanner.c" yy7: YYDEBUG(7, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '=') goto yy43; YYDEBUG(8, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1744 "Zend/zend_language_scanner.l" { if (CG(asp_tags)) { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG; } else { goto inline_char_handler; } } #line 1203 "Zend/zend_language_scanner.c" yy9: YYDEBUG(9, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy11; if (yych == 'c') goto yy11; yy10: YYDEBUG(10, *YYCURSOR); YYCURSOR = YYMARKER; if (yyaccept <= 0) { goto yy3; } else { goto yy6; } yy11: YYDEBUG(11, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy12; if (yych != 'r') goto yy10; yy12: YYDEBUG(12, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy13; if (yych != 'i') goto yy10; yy13: YYDEBUG(13, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy14; if (yych != 'p') goto yy10; yy14: YYDEBUG(14, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy15; if (yych != 't') goto yy10; yy15: YYDEBUG(15, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy10; if (yych == 'l') goto yy10; goto yy17; yy16: YYDEBUG(16, *YYCURSOR); ++YYCURSOR; YYFILL(8); yych = *YYCURSOR; yy17: YYDEBUG(17, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy16; } if (yych == 'L') goto yy18; if (yych != 'l') goto yy10; yy18: YYDEBUG(18, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy19; if (yych != 'a') goto yy10; yy19: YYDEBUG(19, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy20; if (yych != 'n') goto yy10; yy20: YYDEBUG(20, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy21; if (yych != 'g') goto yy10; yy21: YYDEBUG(21, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy22; if (yych != 'u') goto yy10; yy22: YYDEBUG(22, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy23; if (yych != 'a') goto yy10; yy23: YYDEBUG(23, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy24; if (yych != 'g') goto yy10; yy24: YYDEBUG(24, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy25; if (yych != 'e') goto yy10; yy25: YYDEBUG(25, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(26, *YYCURSOR); if (yych <= '\r') { if (yych <= 0x08) goto yy10; if (yych <= '\n') goto yy25; if (yych <= '\f') goto yy10; goto yy25; } else { if (yych <= ' ') { if (yych <= 0x1F) goto yy10; goto yy25; } else { if (yych != '=') goto yy10; } } yy27: YYDEBUG(27, *YYCURSOR); ++YYCURSOR; YYFILL(5); yych = *YYCURSOR; YYDEBUG(28, *YYCURSOR); if (yych <= '!') { if (yych <= '\f') { if (yych <= 0x08) goto yy10; if (yych <= '\n') goto yy27; goto yy10; } else { if (yych <= '\r') goto yy27; if (yych == ' ') goto yy27; goto yy10; } } else { if (yych <= 'O') { if (yych <= '"') goto yy30; if (yych == '\'') goto yy31; goto yy10; } else { if (yych <= 'P') goto yy29; if (yych != 'p') goto yy10; } } yy29: YYDEBUG(29, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy42; if (yych == 'h') goto yy42; goto yy10; yy30: YYDEBUG(30, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy39; if (yych == 'p') goto yy39; goto yy10; yy31: YYDEBUG(31, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy32; if (yych != 'p') goto yy10; yy32: YYDEBUG(32, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy33; if (yych != 'h') goto yy10; yy33: YYDEBUG(33, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy34; if (yych != 'p') goto yy10; yy34: YYDEBUG(34, *YYCURSOR); yych = *++YYCURSOR; if (yych != '\'') goto yy10; yy35: YYDEBUG(35, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(36, *YYCURSOR); if (yych <= '\r') { if (yych <= 0x08) goto yy10; if (yych <= '\n') goto yy35; if (yych <= '\f') goto yy10; goto yy35; } else { if (yych <= ' ') { if (yych <= 0x1F) goto yy10; goto yy35; } else { if (yych != '>') goto yy10; } } YYDEBUG(37, *YYCURSOR); ++YYCURSOR; YYDEBUG(38, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1704 "Zend/zend_language_scanner.l" { YYCTYPE *bracket = (YYCTYPE*)zend_memrchr(yytext, '<', yyleng - (sizeof("script language=php>") - 1)); if (bracket != SCNG(yy_text)) { /* Handle previously scanned HTML, as possible <script> tags found are assumed to not be PHP's */ YYCURSOR = bracket; goto inline_html; } HANDLE_NEWLINES(yytext, yyleng); zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG; } #line 1406 "Zend/zend_language_scanner.c" yy39: YYDEBUG(39, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy40; if (yych != 'h') goto yy10; yy40: YYDEBUG(40, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy41; if (yych != 'p') goto yy10; yy41: YYDEBUG(41, *YYCURSOR); yych = *++YYCURSOR; if (yych == '"') goto yy35; goto yy10; yy42: YYDEBUG(42, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy35; if (yych == 'p') goto yy35; goto yy10; yy43: YYDEBUG(43, *YYCURSOR); ++YYCURSOR; YYDEBUG(44, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1722 "Zend/zend_language_scanner.l" { if (CG(asp_tags)) { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG_WITH_ECHO; } else { goto inline_char_handler; } } #line 1445 "Zend/zend_language_scanner.c" yy45: YYDEBUG(45, *YYCURSOR); ++YYCURSOR; YYDEBUG(46, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1735 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG_WITH_ECHO; } #line 1459 "Zend/zend_language_scanner.c" yy47: YYDEBUG(47, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy48; if (yych != 'h') goto yy10; yy48: YYDEBUG(48, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy49; if (yych != 'p') goto yy10; yy49: YYDEBUG(49, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '\f') { if (yych <= 0x08) goto yy10; if (yych >= '\v') goto yy10; } else { if (yych <= '\r') goto yy52; if (yych != ' ') goto yy10; } yy50: YYDEBUG(50, *YYCURSOR); ++YYCURSOR; yy51: YYDEBUG(51, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1757 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; HANDLE_NEWLINE(yytext[yyleng-1]); BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG; } #line 1495 "Zend/zend_language_scanner.c" yy52: YYDEBUG(52, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '\n') goto yy50; goto yy51; } /* *********************************** */ yyc_ST_BACKQUOTE: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; YYDEBUG(53, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych <= '_') { if (yych != '$') goto yy60; } else { if (yych <= '`') goto yy58; if (yych == '{') goto yy57; goto yy60; } YYDEBUG(55, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '_') { if (yych <= '@') goto yy56; if (yych <= 'Z') goto yy63; if (yych >= '_') goto yy63; } else { if (yych <= 'z') { if (yych >= 'a') goto yy63; } else { if (yych <= '{') goto yy66; if (yych >= 0x7F) goto yy63; } } yy56: YYDEBUG(56, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2230 "Zend/zend_language_scanner.l" { if (YYCURSOR > YYLIMIT) { return 0; } if (yytext[0] == '\\' && YYCURSOR < YYLIMIT) { YYCURSOR++; } while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '`': break; case '$': if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { break; } continue; case '{': if (*YYCURSOR == '$') { break; } continue; case '\\': if (YYCURSOR < YYLIMIT) { YYCURSOR++; } /* fall through */ default: continue; } YYCURSOR--; break; } yyleng = YYCURSOR - SCNG(yy_text); zend_scan_escape_string(zendlval, yytext, yyleng, '`' TSRMLS_CC); return T_ENCAPSED_AND_WHITESPACE; } #line 1607 "Zend/zend_language_scanner.c" yy57: YYDEBUG(57, *YYCURSOR); yych = *++YYCURSOR; if (yych == '$') goto yy61; goto yy56; yy58: YYDEBUG(58, *YYCURSOR); ++YYCURSOR; YYDEBUG(59, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2174 "Zend/zend_language_scanner.l" { BEGIN(ST_IN_SCRIPTING); return '`'; } #line 1623 "Zend/zend_language_scanner.c" yy60: YYDEBUG(60, *YYCURSOR); yych = *++YYCURSOR; goto yy56; yy61: YYDEBUG(61, *YYCURSOR); ++YYCURSOR; YYDEBUG(62, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2161 "Zend/zend_language_scanner.l" { zendlval->value.lval = (long) '{'; yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); yyless(1); return T_CURLY_OPEN; } #line 1640 "Zend/zend_language_scanner.c" yy63: YYDEBUG(63, *YYCURSOR); yyaccept = 0; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(64, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy63; } if (yych == '-') goto yy68; if (yych == '[') goto yy70; yy65: YYDEBUG(65, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1861 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1662 "Zend/zend_language_scanner.c" yy66: YYDEBUG(66, *YYCURSOR); ++YYCURSOR; YYDEBUG(67, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1442 "Zend/zend_language_scanner.l" { yy_push_state(ST_LOOKING_FOR_VARNAME TSRMLS_CC); return T_DOLLAR_OPEN_CURLY_BRACES; } #line 1673 "Zend/zend_language_scanner.c" yy68: YYDEBUG(68, *YYCURSOR); yych = *++YYCURSOR; if (yych == '>') goto yy72; yy69: YYDEBUG(69, *YYCURSOR); YYCURSOR = YYMARKER; goto yy65; yy70: YYDEBUG(70, *YYCURSOR); ++YYCURSOR; YYDEBUG(71, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1853 "Zend/zend_language_scanner.l" { yyless(yyleng - 1); yy_push_state(ST_VAR_OFFSET TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1695 "Zend/zend_language_scanner.c" yy72: YYDEBUG(72, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy69; if (yych <= 'Z') goto yy73; if (yych <= '^') goto yy69; } else { if (yych <= '`') goto yy69; if (yych <= 'z') goto yy73; if (yych <= '~') goto yy69; } yy73: YYDEBUG(73, *YYCURSOR); ++YYCURSOR; YYDEBUG(74, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1843 "Zend/zend_language_scanner.l" { yyless(yyleng - 3); yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1721 "Zend/zend_language_scanner.c" } /* *********************************** */ yyc_ST_DOUBLE_QUOTES: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; YYDEBUG(75, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych <= '#') { if (yych == '"') goto yy80; goto yy82; } else { if (yych <= '$') goto yy77; if (yych == '{') goto yy79; goto yy82; } yy77: YYDEBUG(77, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '_') { if (yych <= '@') goto yy78; if (yych <= 'Z') goto yy85; if (yych >= '_') goto yy85; } else { if (yych <= 'z') { if (yych >= 'a') goto yy85; } else { if (yych <= '{') goto yy88; if (yych >= 0x7F) goto yy85; } } yy78: YYDEBUG(78, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2180 "Zend/zend_language_scanner.l" { if (GET_DOUBLE_QUOTES_SCANNED_LENGTH()) { YYCURSOR += GET_DOUBLE_QUOTES_SCANNED_LENGTH() - 1; SET_DOUBLE_QUOTES_SCANNED_LENGTH(0); goto double_quotes_scan_done; } if (YYCURSOR > YYLIMIT) { return 0; } if (yytext[0] == '\\' && YYCURSOR < YYLIMIT) { YYCURSOR++; } while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '"': break; case '$': if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { break; } continue; case '{': if (*YYCURSOR == '$') { break; } continue; case '\\': if (YYCURSOR < YYLIMIT) { YYCURSOR++; } /* fall through */ default: continue; } YYCURSOR--; break; } double_quotes_scan_done: yyleng = YYCURSOR - SCNG(yy_text); zend_scan_escape_string(zendlval, yytext, yyleng, '"' TSRMLS_CC); return T_ENCAPSED_AND_WHITESPACE; } #line 1838 "Zend/zend_language_scanner.c" yy79: YYDEBUG(79, *YYCURSOR); yych = *++YYCURSOR; if (yych == '$') goto yy83; goto yy78; yy80: YYDEBUG(80, *YYCURSOR); ++YYCURSOR; YYDEBUG(81, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2169 "Zend/zend_language_scanner.l" { BEGIN(ST_IN_SCRIPTING); return '"'; } #line 1854 "Zend/zend_language_scanner.c" yy82: YYDEBUG(82, *YYCURSOR); yych = *++YYCURSOR; goto yy78; yy83: YYDEBUG(83, *YYCURSOR); ++YYCURSOR; YYDEBUG(84, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2161 "Zend/zend_language_scanner.l" { zendlval->value.lval = (long) '{'; yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); yyless(1); return T_CURLY_OPEN; } #line 1871 "Zend/zend_language_scanner.c" yy85: YYDEBUG(85, *YYCURSOR); yyaccept = 0; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(86, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy85; } if (yych == '-') goto yy90; if (yych == '[') goto yy92; yy87: YYDEBUG(87, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1861 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1893 "Zend/zend_language_scanner.c" yy88: YYDEBUG(88, *YYCURSOR); ++YYCURSOR; YYDEBUG(89, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1442 "Zend/zend_language_scanner.l" { yy_push_state(ST_LOOKING_FOR_VARNAME TSRMLS_CC); return T_DOLLAR_OPEN_CURLY_BRACES; } #line 1904 "Zend/zend_language_scanner.c" yy90: YYDEBUG(90, *YYCURSOR); yych = *++YYCURSOR; if (yych == '>') goto yy94; yy91: YYDEBUG(91, *YYCURSOR); YYCURSOR = YYMARKER; goto yy87; yy92: YYDEBUG(92, *YYCURSOR); ++YYCURSOR; YYDEBUG(93, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1853 "Zend/zend_language_scanner.l" { yyless(yyleng - 1); yy_push_state(ST_VAR_OFFSET TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1926 "Zend/zend_language_scanner.c" yy94: YYDEBUG(94, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy91; if (yych <= 'Z') goto yy95; if (yych <= '^') goto yy91; } else { if (yych <= '`') goto yy91; if (yych <= 'z') goto yy95; if (yych <= '~') goto yy91; } yy95: YYDEBUG(95, *YYCURSOR); ++YYCURSOR; YYDEBUG(96, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1843 "Zend/zend_language_scanner.l" { yyless(yyleng - 3); yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1952 "Zend/zend_language_scanner.c" } /* *********************************** */ yyc_ST_END_HEREDOC: YYDEBUG(97, *YYCURSOR); YYFILL(1); yych = *YYCURSOR; YYDEBUG(99, *YYCURSOR); ++YYCURSOR; YYDEBUG(100, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2148 "Zend/zend_language_scanner.l" { YYCURSOR += CG(heredoc_len) - 1; yyleng = CG(heredoc_len); Z_STRVAL_P(zendlval) = CG(heredoc); Z_STRLEN_P(zendlval) = CG(heredoc_len); CG(heredoc) = NULL; CG(heredoc_len) = 0; BEGIN(ST_IN_SCRIPTING); return T_END_HEREDOC; } #line 1975 "Zend/zend_language_scanner.c" /* *********************************** */ yyc_ST_HEREDOC: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; YYDEBUG(101, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych == '$') goto yy103; if (yych == '{') goto yy105; goto yy106; yy103: YYDEBUG(103, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '_') { if (yych <= '@') goto yy104; if (yych <= 'Z') goto yy109; if (yych >= '_') goto yy109; } else { if (yych <= 'z') { if (yych >= 'a') goto yy109; } else { if (yych <= '{') goto yy112; if (yych >= 0x7F) goto yy109; } } yy104: YYDEBUG(104, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2272 "Zend/zend_language_scanner.l" { int newline = 0; if (YYCURSOR > YYLIMIT) { return 0; } YYCURSOR--; while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '\r': if (*YYCURSOR == '\n') { YYCURSOR++; } /* fall through */ case '\n': /* Check for ending label on the next line */ if (IS_LABEL_START(*YYCURSOR) && CG(heredoc_len) < YYLIMIT - YYCURSOR && !memcmp(YYCURSOR, CG(heredoc), CG(heredoc_len))) { YYCTYPE *end = YYCURSOR + CG(heredoc_len); if (*end == ';') { end++; } if (*end == '\n' || *end == '\r') { /* newline before label will be subtracted from returned text, but * yyleng/yytext will include it, for zend_highlight/strip, tokenizer, etc. */ if (YYCURSOR[-2] == '\r' && YYCURSOR[-1] == '\n') { newline = 2; /* Windows newline */ } else { newline = 1; } CG(increment_lineno) = 1; /* For newline before label */ BEGIN(ST_END_HEREDOC); goto heredoc_scan_done; } } continue; case '$': if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { break; } continue; case '{': if (*YYCURSOR == '$') { break; } continue; case '\\': if (YYCURSOR < YYLIMIT && *YYCURSOR != '\n' && *YYCURSOR != '\r') { YYCURSOR++; } /* fall through */ default: continue; } YYCURSOR--; break; } heredoc_scan_done: yyleng = YYCURSOR - SCNG(yy_text); zend_scan_escape_string(zendlval, yytext, yyleng - newline, 0 TSRMLS_CC); return T_ENCAPSED_AND_WHITESPACE; } #line 2108 "Zend/zend_language_scanner.c" yy105: YYDEBUG(105, *YYCURSOR); yych = *++YYCURSOR; if (yych == '$') goto yy107; goto yy104; yy106: YYDEBUG(106, *YYCURSOR); yych = *++YYCURSOR; goto yy104; yy107: YYDEBUG(107, *YYCURSOR); ++YYCURSOR; YYDEBUG(108, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2161 "Zend/zend_language_scanner.l" { zendlval->value.lval = (long) '{'; yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); yyless(1); return T_CURLY_OPEN; } #line 2130 "Zend/zend_language_scanner.c" yy109: YYDEBUG(109, *YYCURSOR); yyaccept = 0; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(110, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy109; } if (yych == '-') goto yy114; if (yych == '[') goto yy116; yy111: YYDEBUG(111, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1861 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 2152 "Zend/zend_language_scanner.c" yy112: YYDEBUG(112, *YYCURSOR); ++YYCURSOR; YYDEBUG(113, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1442 "Zend/zend_language_scanner.l" { yy_push_state(ST_LOOKING_FOR_VARNAME TSRMLS_CC); return T_DOLLAR_OPEN_CURLY_BRACES; } #line 2163 "Zend/zend_language_scanner.c" yy114: YYDEBUG(114, *YYCURSOR); yych = *++YYCURSOR; if (yych == '>') goto yy118; yy115: YYDEBUG(115, *YYCURSOR); YYCURSOR = YYMARKER; goto yy111; yy116: YYDEBUG(116, *YYCURSOR); ++YYCURSOR; YYDEBUG(117, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1853 "Zend/zend_language_scanner.l" { yyless(yyleng - 1); yy_push_state(ST_VAR_OFFSET TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 2185 "Zend/zend_language_scanner.c" yy118: YYDEBUG(118, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy115; if (yych <= 'Z') goto yy119; if (yych <= '^') goto yy115; } else { if (yych <= '`') goto yy115; if (yych <= 'z') goto yy119; if (yych <= '~') goto yy115; } yy119: YYDEBUG(119, *YYCURSOR); ++YYCURSOR; YYDEBUG(120, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1843 "Zend/zend_language_scanner.l" { yyless(yyleng - 3); yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 2211 "Zend/zend_language_scanner.c" } /* *********************************** */ yyc_ST_IN_SCRIPTING: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 64, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 60, 60, 44, 44, 44, 44, 44, 44, 44, 44, 0, 0, 0, 0, 0, 0, 0, 36, 36, 36, 36, 36, 36, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 4, 0, 36, 36, 36, 36, 36, 36, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, }; YYDEBUG(121, *YYCURSOR); YYFILL(16); yych = *YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case '\v': case '\f': case 0x0E: case 0x0F: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1A: case 0x1B: case 0x1C: case 0x1D: case 0x1E: case 0x1F: goto yy183; case '\t': case '\n': case '\r': case ' ': goto yy139; case '!': goto yy152; case '"': goto yy179; case '#': goto yy175; case '$': goto yy164; case '%': goto yy158; case '&': goto yy159; case '\'': goto yy177; case '(': goto yy146; case ')': case ',': case ';': case '@': case '[': case ']': case '~': goto yy165; case '*': goto yy155; case '+': goto yy151; case '-': goto yy137; case '.': goto yy157; case '/': goto yy156; case '0': goto yy171; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy173; case ':': goto yy141; case '<': goto yy153; case '=': goto yy149; case '>': goto yy154; case '?': goto yy166; case 'A': case 'a': goto yy132; case 'B': case 'b': goto yy134; case 'C': case 'c': goto yy127; case 'D': case 'd': goto yy125; case 'E': case 'e': goto yy123; case 'F': case 'f': goto yy126; case 'G': case 'g': goto yy135; case 'I': case 'i': goto yy130; case 'L': case 'l': goto yy150; case 'N': case 'n': goto yy144; case 'O': case 'o': goto yy162; case 'P': case 'p': goto yy136; case 'R': case 'r': goto yy128; case 'S': case 's': goto yy133; case 'T': case 't': goto yy129; case 'U': case 'u': goto yy147; case 'V': case 'v': goto yy145; case 'W': case 'w': goto yy131; case 'X': case 'x': goto yy163; case '\\': goto yy142; case '^': goto yy161; case '_': goto yy148; case '`': goto yy181; case '{': goto yy167; case '|': goto yy160; case '}': goto yy169; default: goto yy174; } yy123: YYDEBUG(123, *YYCURSOR); ++YYCURSOR; YYDEBUG(-1, yych); switch ((yych = *YYCURSOR)) { case 'C': case 'c': goto yy726; case 'L': case 'l': goto yy727; case 'M': case 'm': goto yy728; case 'N': case 'n': goto yy729; case 'V': case 'v': goto yy730; case 'X': case 'x': goto yy731; default: goto yy186; } yy124: YYDEBUG(124, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1884 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, yytext, yyleng); zendlval->type = IS_STRING; return T_STRING; } #line 2398 "Zend/zend_language_scanner.c" yy125: YYDEBUG(125, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= 'H') { if (yych == 'E') goto yy708; goto yy186; } else { if (yych <= 'I') goto yy709; if (yych <= 'N') goto yy186; goto yy710; } } else { if (yych <= 'h') { if (yych == 'e') goto yy708; goto yy186; } else { if (yych <= 'i') goto yy709; if (yych == 'o') goto yy710; goto yy186; } } yy126: YYDEBUG(126, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= 'N') { if (yych == 'I') goto yy687; goto yy186; } else { if (yych <= 'O') goto yy688; if (yych <= 'T') goto yy186; goto yy689; } } else { if (yych <= 'n') { if (yych == 'i') goto yy687; goto yy186; } else { if (yych <= 'o') goto yy688; if (yych == 'u') goto yy689; goto yy186; } } yy127: YYDEBUG(127, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= 'K') { if (yych == 'A') goto yy652; goto yy186; } else { if (yych <= 'L') goto yy653; if (yych <= 'N') goto yy186; goto yy654; } } else { if (yych <= 'k') { if (yych == 'a') goto yy652; goto yy186; } else { if (yych <= 'l') goto yy653; if (yych == 'o') goto yy654; goto yy186; } } yy128: YYDEBUG(128, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy634; if (yych == 'e') goto yy634; goto yy186; yy129: YYDEBUG(129, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych == 'H') goto yy622; if (yych <= 'Q') goto yy186; goto yy623; } else { if (yych <= 'h') { if (yych <= 'g') goto yy186; goto yy622; } else { if (yych == 'r') goto yy623; goto yy186; } } yy130: YYDEBUG(130, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= 'L') { if (yych == 'F') goto yy569; goto yy186; } else { if (yych <= 'M') goto yy571; if (yych <= 'N') goto yy572; if (yych <= 'R') goto yy186; goto yy573; } } else { if (yych <= 'm') { if (yych == 'f') goto yy569; if (yych <= 'l') goto yy186; goto yy571; } else { if (yych <= 'n') goto yy572; if (yych == 's') goto yy573; goto yy186; } } yy131: YYDEBUG(131, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy564; if (yych == 'h') goto yy564; goto yy186; yy132: YYDEBUG(132, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= 'M') { if (yych == 'B') goto yy546; goto yy186; } else { if (yych <= 'N') goto yy547; if (yych <= 'Q') goto yy186; if (yych <= 'R') goto yy548; goto yy549; } } else { if (yych <= 'n') { if (yych == 'b') goto yy546; if (yych <= 'm') goto yy186; goto yy547; } else { if (yych <= 'q') goto yy186; if (yych <= 'r') goto yy548; if (yych <= 's') goto yy549; goto yy186; } } yy133: YYDEBUG(133, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'W') { if (yych == 'T') goto yy534; if (yych <= 'V') goto yy186; goto yy535; } else { if (yych <= 't') { if (yych <= 's') goto yy186; goto yy534; } else { if (yych == 'w') goto yy535; goto yy186; } } yy134: YYDEBUG(134, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ';') { if (yych <= '"') { if (yych <= '!') goto yy186; goto yy526; } else { if (yych == '\'') goto yy527; goto yy186; } } else { if (yych <= 'R') { if (yych <= '<') goto yy525; if (yych <= 'Q') goto yy186; goto yy528; } else { if (yych == 'r') goto yy528; goto yy186; } } yy135: YYDEBUG(135, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'L') goto yy515; if (yych <= 'N') goto yy186; goto yy516; } else { if (yych <= 'l') { if (yych <= 'k') goto yy186; goto yy515; } else { if (yych == 'o') goto yy516; goto yy186; } } yy136: YYDEBUG(136, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'R') goto yy491; if (yych <= 'T') goto yy186; goto yy492; } else { if (yych <= 'r') { if (yych <= 'q') goto yy186; goto yy491; } else { if (yych == 'u') goto yy492; goto yy186; } } yy137: YYDEBUG(137, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '<') { if (yych == '-') goto yy487; } else { if (yych <= '=') goto yy485; if (yych <= '>') goto yy489; } yy138: YYDEBUG(138, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1431 "Zend/zend_language_scanner.l" { return yytext[0]; } #line 2628 "Zend/zend_language_scanner.c" yy139: YYDEBUG(139, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy484; yy140: YYDEBUG(140, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1162 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; HANDLE_NEWLINES(yytext, yyleng); return T_WHITESPACE; } #line 2645 "Zend/zend_language_scanner.c" yy141: YYDEBUG(141, *YYCURSOR); yych = *++YYCURSOR; if (yych == ':') goto yy481; goto yy138; yy142: YYDEBUG(142, *YYCURSOR); ++YYCURSOR; YYDEBUG(143, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1191 "Zend/zend_language_scanner.l" { return T_NS_SEPARATOR; } #line 2660 "Zend/zend_language_scanner.c" yy144: YYDEBUG(144, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych == 'A') goto yy469; if (yych <= 'D') goto yy186; goto yy470; } else { if (yych <= 'a') { if (yych <= '`') goto yy186; goto yy469; } else { if (yych == 'e') goto yy470; goto yy186; } } yy145: YYDEBUG(145, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy466; if (yych == 'a') goto yy466; goto yy186; yy146: YYDEBUG(146, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy391; if (yych <= 0x1F) goto yy138; goto yy391; } else { if (yych <= '@') goto yy138; if (yych == 'C') goto yy138; goto yy391; } } else { if (yych <= 'I') { if (yych == 'F') goto yy391; if (yych <= 'H') goto yy138; goto yy391; } else { if (yych == 'O') goto yy391; if (yych <= 'Q') goto yy138; goto yy391; } } } else { if (yych <= 'f') { if (yych <= 'b') { if (yych == 'U') goto yy391; if (yych <= '`') goto yy138; goto yy391; } else { if (yych == 'd') goto yy391; if (yych <= 'e') goto yy138; goto yy391; } } else { if (yych <= 'o') { if (yych == 'i') goto yy391; if (yych <= 'n') goto yy138; goto yy391; } else { if (yych <= 's') { if (yych <= 'q') goto yy138; goto yy391; } else { if (yych == 'u') goto yy391; goto yy138; } } } } yy147: YYDEBUG(147, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych == 'N') goto yy382; if (yych <= 'R') goto yy186; goto yy383; } else { if (yych <= 'n') { if (yych <= 'm') goto yy186; goto yy382; } else { if (yych == 's') goto yy383; goto yy186; } } yy148: YYDEBUG(148, *YYCURSOR); yych = *++YYCURSOR; if (yych == '_') goto yy300; goto yy186; yy149: YYDEBUG(149, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '<') goto yy138; if (yych <= '=') goto yy294; if (yych <= '>') goto yy296; goto yy138; yy150: YYDEBUG(150, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy290; if (yych == 'i') goto yy290; goto yy186; yy151: YYDEBUG(151, *YYCURSOR); yych = *++YYCURSOR; if (yych == '+') goto yy288; if (yych == '=') goto yy286; goto yy138; yy152: YYDEBUG(152, *YYCURSOR); yych = *++YYCURSOR; if (yych == '=') goto yy283; goto yy138; yy153: YYDEBUG(153, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ';') { if (yych == '/') goto yy255; goto yy138; } else { if (yych <= '<') goto yy253; if (yych <= '=') goto yy256; if (yych <= '>') goto yy258; goto yy138; } yy154: YYDEBUG(154, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '<') goto yy138; if (yych <= '=') goto yy249; if (yych <= '>') goto yy247; goto yy138; yy155: YYDEBUG(155, *YYCURSOR); yych = *++YYCURSOR; if (yych == '=') goto yy245; goto yy138; yy156: YYDEBUG(156, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '.') { if (yych == '*') goto yy237; goto yy138; } else { if (yych <= '/') goto yy239; if (yych == '=') goto yy240; goto yy138; } yy157: YYDEBUG(157, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy138; if (yych <= '9') goto yy233; if (yych == '=') goto yy235; goto yy138; yy158: YYDEBUG(158, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '<') goto yy138; if (yych <= '=') goto yy229; if (yych <= '>') goto yy227; goto yy138; yy159: YYDEBUG(159, *YYCURSOR); yych = *++YYCURSOR; if (yych == '&') goto yy223; if (yych == '=') goto yy225; goto yy138; yy160: YYDEBUG(160, *YYCURSOR); yych = *++YYCURSOR; if (yych == '=') goto yy221; if (yych == '|') goto yy219; goto yy138; yy161: YYDEBUG(161, *YYCURSOR); yych = *++YYCURSOR; if (yych == '=') goto yy217; goto yy138; yy162: YYDEBUG(162, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy215; if (yych == 'r') goto yy215; goto yy186; yy163: YYDEBUG(163, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy212; if (yych == 'o') goto yy212; goto yy186; yy164: YYDEBUG(164, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy138; if (yych <= 'Z') goto yy209; if (yych <= '^') goto yy138; goto yy209; } else { if (yych <= '`') goto yy138; if (yych <= 'z') goto yy209; if (yych <= '~') goto yy138; goto yy209; } yy165: YYDEBUG(165, *YYCURSOR); yych = *++YYCURSOR; goto yy138; yy166: YYDEBUG(166, *YYCURSOR); yych = *++YYCURSOR; if (yych == '>') goto yy205; goto yy138; yy167: YYDEBUG(167, *YYCURSOR); ++YYCURSOR; YYDEBUG(168, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1436 "Zend/zend_language_scanner.l" { yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); return '{'; } #line 2893 "Zend/zend_language_scanner.c" yy169: YYDEBUG(169, *YYCURSOR); ++YYCURSOR; YYDEBUG(170, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1448 "Zend/zend_language_scanner.l" { RESET_DOC_COMMENT(); if (!zend_stack_is_empty(&SCNG(state_stack))) { yy_pop_state(TSRMLS_C); } return '}'; } #line 2907 "Zend/zend_language_scanner.c" yy171: YYDEBUG(171, *YYCURSOR); yyaccept = 2; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'E') { if (yych <= '9') { if (yych == '.') goto yy187; if (yych >= '0') goto yy190; } else { if (yych == 'B') goto yy198; if (yych >= 'E') goto yy192; } } else { if (yych <= 'b') { if (yych == 'X') goto yy197; if (yych >= 'b') goto yy198; } else { if (yych <= 'e') { if (yych >= 'e') goto yy192; } else { if (yych == 'x') goto yy197; } } } yy172: YYDEBUG(172, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1494 "Zend/zend_language_scanner.l" { if (yyleng < MAX_LENGTH_OF_LONG - 1) { /* Won't overflow */ zendlval->value.lval = strtol(yytext, NULL, 0); } else { errno = 0; zendlval->value.lval = strtol(yytext, NULL, 0); if (errno == ERANGE) { /* Overflow */ if (yytext[0] == '0') { /* octal overflow */ zendlval->value.dval = zend_oct_strtod(yytext, NULL); } else { zendlval->value.dval = zend_strtod(yytext, NULL); } zendlval->type = IS_DOUBLE; return T_DNUMBER; } } zendlval->type = IS_LONG; return T_LNUMBER; } #line 2956 "Zend/zend_language_scanner.c" yy173: YYDEBUG(173, *YYCURSOR); yyaccept = 2; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych == '.') goto yy187; if (yych <= '/') goto yy172; goto yy190; } else { if (yych <= 'E') { if (yych <= 'D') goto yy172; goto yy192; } else { if (yych == 'e') goto yy192; goto yy172; } } yy174: YYDEBUG(174, *YYCURSOR); yych = *++YYCURSOR; goto yy186; yy175: YYDEBUG(175, *YYCURSOR); ++YYCURSOR; yy176: YYDEBUG(176, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1891 "Zend/zend_language_scanner.l" { while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '\r': if (*YYCURSOR == '\n') { YYCURSOR++; } /* fall through */ case '\n': CG(zend_lineno)++; break; case '%': if (!CG(asp_tags)) { continue; } /* fall through */ case '?': if (*YYCURSOR == '>') { YYCURSOR--; break; } /* fall through */ default: continue; } break; } yyleng = YYCURSOR - SCNG(yy_text); return T_COMMENT; } #line 3018 "Zend/zend_language_scanner.c" yy177: YYDEBUG(177, *YYCURSOR); ++YYCURSOR; yy178: YYDEBUG(178, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1982 "Zend/zend_language_scanner.l" { register char *s, *t; char *end; int bprefix = (yytext[0] != '\'') ? 1 : 0; while (1) { if (YYCURSOR < YYLIMIT) { if (*YYCURSOR == '\'') { YYCURSOR++; yyleng = YYCURSOR - SCNG(yy_text); break; } else if (*YYCURSOR++ == '\\' && YYCURSOR < YYLIMIT) { YYCURSOR++; } } else { yyleng = YYLIMIT - SCNG(yy_text); /* Unclosed single quotes; treat similar to double quotes, but without a separate token * for ' (unrecognized by parser), instead of old flex fallback to "Unexpected character..." * rule, which continued in ST_IN_SCRIPTING state after the quote */ return T_ENCAPSED_AND_WHITESPACE; } } zendlval->value.str.val = estrndup(yytext+bprefix+1, yyleng-bprefix-2); zendlval->value.str.len = yyleng-bprefix-2; zendlval->type = IS_STRING; /* convert escape sequences */ s = t = zendlval->value.str.val; end = s+zendlval->value.str.len; while (s<end) { if (*s=='\\') { s++; switch(*s) { case '\\': case '\'': *t++ = *s; zendlval->value.str.len--; break; default: *t++ = '\\'; *t++ = *s; break; } } else { *t++ = *s; } if (*s == '\n' || (*s == '\r' && (*(s+1) != '\n'))) { CG(zend_lineno)++; } s++; } *t = 0; if (SCNG(output_filter)) { size_t sz = 0; s = zendlval->value.str.val; SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)s, (size_t)zendlval->value.str.len TSRMLS_CC); zendlval->value.str.len = sz; efree(s); } return T_CONSTANT_ENCAPSED_STRING; } #line 3093 "Zend/zend_language_scanner.c" yy179: YYDEBUG(179, *YYCURSOR); ++YYCURSOR; yy180: YYDEBUG(180, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2051 "Zend/zend_language_scanner.l" { int bprefix = (yytext[0] != '"') ? 1 : 0; while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '"': yyleng = YYCURSOR - SCNG(yy_text); zend_scan_escape_string(zendlval, yytext+bprefix+1, yyleng-bprefix-2, '"' TSRMLS_CC); return T_CONSTANT_ENCAPSED_STRING; case '$': if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { break; } continue; case '{': if (*YYCURSOR == '$') { break; } continue; case '\\': if (YYCURSOR < YYLIMIT) { YYCURSOR++; } /* fall through */ default: continue; } YYCURSOR--; break; } /* Remember how much was scanned to save rescanning */ SET_DOUBLE_QUOTES_SCANNED_LENGTH(YYCURSOR - SCNG(yy_text) - yyleng); YYCURSOR = SCNG(yy_text) + yyleng; BEGIN(ST_DOUBLE_QUOTES); return '"'; } #line 3141 "Zend/zend_language_scanner.c" yy181: YYDEBUG(181, *YYCURSOR); ++YYCURSOR; YYDEBUG(182, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2142 "Zend/zend_language_scanner.l" { BEGIN(ST_BACKQUOTE); return '`'; } #line 3152 "Zend/zend_language_scanner.c" yy183: YYDEBUG(183, *YYCURSOR); ++YYCURSOR; YYDEBUG(184, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2400 "Zend/zend_language_scanner.l" { if (YYCURSOR > YYLIMIT) { return 0; } zend_error(E_COMPILE_WARNING,"Unexpected character in input: '%c' (ASCII=%d) state=%d", yytext[0], yytext[0], YYSTATE); goto restart; } #line 3167 "Zend/zend_language_scanner.c" yy185: YYDEBUG(185, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy186: YYDEBUG(186, *YYCURSOR); if (yybm[0+yych] & 4) { goto yy185; } goto yy124; yy187: YYDEBUG(187, *YYCURSOR); yyaccept = 3; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(188, *YYCURSOR); if (yybm[0+yych] & 8) { goto yy187; } if (yych == 'E') goto yy192; if (yych == 'e') goto yy192; yy189: YYDEBUG(189, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1559 "Zend/zend_language_scanner.l" { zendlval->value.dval = zend_strtod(yytext, NULL); zendlval->type = IS_DOUBLE; return T_DNUMBER; } #line 3200 "Zend/zend_language_scanner.c" yy190: YYDEBUG(190, *YYCURSOR); yyaccept = 2; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(191, *YYCURSOR); if (yych <= '9') { if (yych == '.') goto yy187; if (yych <= '/') goto yy172; goto yy190; } else { if (yych <= 'E') { if (yych <= 'D') goto yy172; } else { if (yych != 'e') goto yy172; } } yy192: YYDEBUG(192, *YYCURSOR); yych = *++YYCURSOR; if (yych <= ',') { if (yych == '+') goto yy194; } else { if (yych <= '-') goto yy194; if (yych <= '/') goto yy193; if (yych <= '9') goto yy195; } yy193: YYDEBUG(193, *YYCURSOR); YYCURSOR = YYMARKER; if (yyaccept <= 2) { if (yyaccept <= 1) { if (yyaccept <= 0) { goto yy124; } else { goto yy138; } } else { goto yy172; } } else { if (yyaccept <= 4) { if (yyaccept <= 3) { goto yy189; } else { goto yy238; } } else { goto yy254; } } yy194: YYDEBUG(194, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy193; if (yych >= ':') goto yy193; yy195: YYDEBUG(195, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(196, *YYCURSOR); if (yych <= '/') goto yy189; if (yych <= '9') goto yy195; goto yy189; yy197: YYDEBUG(197, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 32) { goto yy202; } goto yy193; yy198: YYDEBUG(198, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 16) { goto yy199; } goto yy193; yy199: YYDEBUG(199, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(200, *YYCURSOR); if (yybm[0+yych] & 16) { goto yy199; } YYDEBUG(201, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1473 "Zend/zend_language_scanner.l" { char *bin = yytext + 2; /* Skip "0b" */ int len = yyleng - 2; /* Skip any leading 0s */ while (*bin == '0') { ++bin; --len; } if (len < SIZEOF_LONG * 8) { zendlval->value.lval = strtol(bin, NULL, 2); zendlval->type = IS_LONG; return T_LNUMBER; } else { zendlval->value.dval = zend_bin_strtod(bin, NULL); zendlval->type = IS_DOUBLE; return T_DNUMBER; } } #line 3313 "Zend/zend_language_scanner.c" yy202: YYDEBUG(202, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(203, *YYCURSOR); if (yybm[0+yych] & 32) { goto yy202; } YYDEBUG(204, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1515 "Zend/zend_language_scanner.l" { char *hex = yytext + 2; /* Skip "0x" */ int len = yyleng - 2; /* Skip any leading 0s */ while (*hex == '0') { hex++; len--; } if (len < SIZEOF_LONG * 2 || (len == SIZEOF_LONG * 2 && *hex <= '7')) { if (len == 0) { zendlval->value.lval = 0; } else { zendlval->value.lval = strtol(hex, NULL, 16); } zendlval->type = IS_LONG; return T_LNUMBER; } else { zendlval->value.dval = zend_hex_strtod(hex, NULL); zendlval->type = IS_DOUBLE; return T_DNUMBER; } } #line 3350 "Zend/zend_language_scanner.c" yy205: YYDEBUG(205, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '\n') goto yy207; if (yych == '\r') goto yy208; yy206: YYDEBUG(206, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1959 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(INITIAL); return T_CLOSE_TAG; /* implicit ';' at php-end tag */ } #line 3367 "Zend/zend_language_scanner.c" yy207: YYDEBUG(207, *YYCURSOR); yych = *++YYCURSOR; goto yy206; yy208: YYDEBUG(208, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\n') goto yy207; goto yy206; yy209: YYDEBUG(209, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(210, *YYCURSOR); if (yych <= '^') { if (yych <= '9') { if (yych >= '0') goto yy209; } else { if (yych <= '@') goto yy211; if (yych <= 'Z') goto yy209; } } else { if (yych <= '`') { if (yych <= '_') goto yy209; } else { if (yych <= 'z') goto yy209; if (yych >= 0x7F) goto yy209; } } yy211: YYDEBUG(211, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1861 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 3407 "Zend/zend_language_scanner.c" yy212: YYDEBUG(212, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy213; if (yych != 'r') goto yy186; yy213: YYDEBUG(213, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(214, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1419 "Zend/zend_language_scanner.l" { return T_LOGICAL_XOR; } #line 3425 "Zend/zend_language_scanner.c" yy215: YYDEBUG(215, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(216, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1411 "Zend/zend_language_scanner.l" { return T_LOGICAL_OR; } #line 3438 "Zend/zend_language_scanner.c" yy217: YYDEBUG(217, *YYCURSOR); ++YYCURSOR; YYDEBUG(218, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1399 "Zend/zend_language_scanner.l" { return T_XOR_EQUAL; } #line 3448 "Zend/zend_language_scanner.c" yy219: YYDEBUG(219, *YYCURSOR); ++YYCURSOR; YYDEBUG(220, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1403 "Zend/zend_language_scanner.l" { return T_BOOLEAN_OR; } #line 3458 "Zend/zend_language_scanner.c" yy221: YYDEBUG(221, *YYCURSOR); ++YYCURSOR; YYDEBUG(222, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1395 "Zend/zend_language_scanner.l" { return T_OR_EQUAL; } #line 3468 "Zend/zend_language_scanner.c" yy223: YYDEBUG(223, *YYCURSOR); ++YYCURSOR; YYDEBUG(224, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1407 "Zend/zend_language_scanner.l" { return T_BOOLEAN_AND; } #line 3478 "Zend/zend_language_scanner.c" yy225: YYDEBUG(225, *YYCURSOR); ++YYCURSOR; YYDEBUG(226, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1391 "Zend/zend_language_scanner.l" { return T_AND_EQUAL; } #line 3488 "Zend/zend_language_scanner.c" yy227: YYDEBUG(227, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '\n') goto yy231; if (yych == '\r') goto yy232; yy228: YYDEBUG(228, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1968 "Zend/zend_language_scanner.l" { if (CG(asp_tags)) { BEGIN(INITIAL); zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; zendlval->value.str.val = yytext; /* no copying - intentional */ return T_CLOSE_TAG; /* implicit ';' at php-end tag */ } else { yyless(1); return yytext[0]; } } #line 3510 "Zend/zend_language_scanner.c" yy229: YYDEBUG(229, *YYCURSOR); ++YYCURSOR; YYDEBUG(230, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1379 "Zend/zend_language_scanner.l" { return T_MOD_EQUAL; } #line 3520 "Zend/zend_language_scanner.c" yy231: YYDEBUG(231, *YYCURSOR); yych = *++YYCURSOR; goto yy228; yy232: YYDEBUG(232, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\n') goto yy231; goto yy228; yy233: YYDEBUG(233, *YYCURSOR); yyaccept = 3; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(234, *YYCURSOR); if (yych <= 'D') { if (yych <= '/') goto yy189; if (yych <= '9') goto yy233; goto yy189; } else { if (yych <= 'E') goto yy192; if (yych == 'e') goto yy192; goto yy189; } yy235: YYDEBUG(235, *YYCURSOR); ++YYCURSOR; YYDEBUG(236, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1375 "Zend/zend_language_scanner.l" { return T_CONCAT_EQUAL; } #line 3555 "Zend/zend_language_scanner.c" yy237: YYDEBUG(237, *YYCURSOR); yyaccept = 4; yych = *(YYMARKER = ++YYCURSOR); if (yych == '*') goto yy242; yy238: YYDEBUG(238, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1925 "Zend/zend_language_scanner.l" { int doc_com; if (yyleng > 2) { doc_com = 1; RESET_DOC_COMMENT(); } else { doc_com = 0; } while (YYCURSOR < YYLIMIT) { if (*YYCURSOR++ == '*' && *YYCURSOR == '/') { break; } } if (YYCURSOR < YYLIMIT) { YYCURSOR++; } else { zend_error(E_COMPILE_WARNING, "Unterminated comment starting line %d", CG(zend_lineno)); } yyleng = YYCURSOR - SCNG(yy_text); HANDLE_NEWLINES(yytext, yyleng); if (doc_com) { CG(doc_comment) = estrndup(yytext, yyleng); CG(doc_comment_len) = yyleng; return T_DOC_COMMENT; } return T_COMMENT; } #line 3598 "Zend/zend_language_scanner.c" yy239: YYDEBUG(239, *YYCURSOR); yych = *++YYCURSOR; goto yy176; yy240: YYDEBUG(240, *YYCURSOR); ++YYCURSOR; YYDEBUG(241, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1371 "Zend/zend_language_scanner.l" { return T_DIV_EQUAL; } #line 3612 "Zend/zend_language_scanner.c" yy242: YYDEBUG(242, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 64) { goto yy243; } goto yy193; yy243: YYDEBUG(243, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(244, *YYCURSOR); if (yybm[0+yych] & 64) { goto yy243; } goto yy238; yy245: YYDEBUG(245, *YYCURSOR); ++YYCURSOR; YYDEBUG(246, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1367 "Zend/zend_language_scanner.l" { return T_MUL_EQUAL; } #line 3639 "Zend/zend_language_scanner.c" yy247: YYDEBUG(247, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '=') goto yy251; YYDEBUG(248, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1427 "Zend/zend_language_scanner.l" { return T_SR; } #line 3650 "Zend/zend_language_scanner.c" yy249: YYDEBUG(249, *YYCURSOR); ++YYCURSOR; YYDEBUG(250, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1355 "Zend/zend_language_scanner.l" { return T_IS_GREATER_OR_EQUAL; } #line 3660 "Zend/zend_language_scanner.c" yy251: YYDEBUG(251, *YYCURSOR); ++YYCURSOR; YYDEBUG(252, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1387 "Zend/zend_language_scanner.l" { return T_SR_EQUAL; } #line 3670 "Zend/zend_language_scanner.c" yy253: YYDEBUG(253, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ';') goto yy254; if (yych <= '<') goto yy269; if (yych <= '=') goto yy267; yy254: YYDEBUG(254, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1423 "Zend/zend_language_scanner.l" { return T_SL; } #line 3685 "Zend/zend_language_scanner.c" yy255: YYDEBUG(255, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy260; if (yych == 's') goto yy260; goto yy193; yy256: YYDEBUG(256, *YYCURSOR); ++YYCURSOR; YYDEBUG(257, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1351 "Zend/zend_language_scanner.l" { return T_IS_SMALLER_OR_EQUAL; } #line 3701 "Zend/zend_language_scanner.c" yy258: YYDEBUG(258, *YYCURSOR); ++YYCURSOR; yy259: YYDEBUG(259, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1347 "Zend/zend_language_scanner.l" { return T_IS_NOT_EQUAL; } #line 3712 "Zend/zend_language_scanner.c" yy260: YYDEBUG(260, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy261; if (yych != 'c') goto yy193; yy261: YYDEBUG(261, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy262; if (yych != 'r') goto yy193; yy262: YYDEBUG(262, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy263; if (yych != 'i') goto yy193; yy263: YYDEBUG(263, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy264; if (yych != 'p') goto yy193; yy264: YYDEBUG(264, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy265; if (yych != 't') goto yy193; yy265: YYDEBUG(265, *YYCURSOR); ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(266, *YYCURSOR); if (yych <= '\r') { if (yych <= 0x08) goto yy193; if (yych <= '\n') goto yy265; if (yych <= '\f') goto yy193; goto yy265; } else { if (yych <= ' ') { if (yych <= 0x1F) goto yy193; goto yy265; } else { if (yych == '>') goto yy205; goto yy193; } } yy267: YYDEBUG(267, *YYCURSOR); ++YYCURSOR; YYDEBUG(268, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1383 "Zend/zend_language_scanner.l" { return T_SL_EQUAL; } #line 3767 "Zend/zend_language_scanner.c" yy269: YYDEBUG(269, *YYCURSOR); ++YYCURSOR; YYFILL(2); yych = *YYCURSOR; YYDEBUG(270, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy269; } if (yych <= 'Z') { if (yych <= '&') { if (yych == '"') goto yy274; goto yy193; } else { if (yych <= '\'') goto yy273; if (yych <= '@') goto yy193; } } else { if (yych <= '`') { if (yych != '_') goto yy193; } else { if (yych <= 'z') goto yy271; if (yych <= '~') goto yy193; } } yy271: YYDEBUG(271, *YYCURSOR); ++YYCURSOR; YYFILL(2); yych = *YYCURSOR; YYDEBUG(272, *YYCURSOR); if (yych <= '@') { if (yych <= '\f') { if (yych == '\n') goto yy278; goto yy193; } else { if (yych <= '\r') goto yy280; if (yych <= '/') goto yy193; if (yych <= '9') goto yy271; goto yy193; } } else { if (yych <= '_') { if (yych <= 'Z') goto yy271; if (yych <= '^') goto yy193; goto yy271; } else { if (yych <= '`') goto yy193; if (yych <= 'z') goto yy271; if (yych <= '~') goto yy193; goto yy271; } } yy273: YYDEBUG(273, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\'') goto yy193; if (yych <= '/') goto yy282; if (yych <= '9') goto yy193; goto yy282; yy274: YYDEBUG(274, *YYCURSOR); yych = *++YYCURSOR; if (yych == '"') goto yy193; if (yych <= '/') goto yy276; if (yych <= '9') goto yy193; goto yy276; yy275: YYDEBUG(275, *YYCURSOR); ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; yy276: YYDEBUG(276, *YYCURSOR); if (yych <= 'Z') { if (yych <= '/') { if (yych != '"') goto yy193; } else { if (yych <= '9') goto yy275; if (yych <= '@') goto yy193; goto yy275; } } else { if (yych <= '`') { if (yych == '_') goto yy275; goto yy193; } else { if (yych <= 'z') goto yy275; if (yych <= '~') goto yy193; goto yy275; } } yy277: YYDEBUG(277, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\n') goto yy278; if (yych == '\r') goto yy280; goto yy193; yy278: YYDEBUG(278, *YYCURSOR); ++YYCURSOR; yy279: YYDEBUG(279, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2093 "Zend/zend_language_scanner.l" { char *s; int bprefix = (yytext[0] != '<') ? 1 : 0; /* save old heredoc label */ Z_STRVAL_P(zendlval) = CG(heredoc); Z_STRLEN_P(zendlval) = CG(heredoc_len); CG(zend_lineno)++; CG(heredoc_len) = yyleng-bprefix-3-1-(yytext[yyleng-2]=='\r'?1:0); s = yytext+bprefix+3; while ((*s == ' ') || (*s == '\t')) { s++; CG(heredoc_len)--; } if (*s == '\'') { s++; CG(heredoc_len) -= 2; BEGIN(ST_NOWDOC); } else { if (*s == '"') { s++; CG(heredoc_len) -= 2; } BEGIN(ST_HEREDOC); } CG(heredoc) = estrndup(s, CG(heredoc_len)); /* Check for ending label on the next line */ if (CG(heredoc_len) < YYLIMIT - YYCURSOR && !memcmp(YYCURSOR, s, CG(heredoc_len))) { YYCTYPE *end = YYCURSOR + CG(heredoc_len); if (*end == ';') { end++; } if (*end == '\n' || *end == '\r') { BEGIN(ST_END_HEREDOC); } } return T_START_HEREDOC; } #line 3920 "Zend/zend_language_scanner.c" yy280: YYDEBUG(280, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\n') goto yy278; goto yy279; yy281: YYDEBUG(281, *YYCURSOR); ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; yy282: YYDEBUG(282, *YYCURSOR); if (yych <= 'Z') { if (yych <= '/') { if (yych == '\'') goto yy277; goto yy193; } else { if (yych <= '9') goto yy281; if (yych <= '@') goto yy193; goto yy281; } } else { if (yych <= '`') { if (yych == '_') goto yy281; goto yy193; } else { if (yych <= 'z') goto yy281; if (yych <= '~') goto yy193; goto yy281; } } yy283: YYDEBUG(283, *YYCURSOR); yych = *++YYCURSOR; if (yych != '=') goto yy259; YYDEBUG(284, *YYCURSOR); ++YYCURSOR; YYDEBUG(285, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1339 "Zend/zend_language_scanner.l" { return T_IS_NOT_IDENTICAL; } #line 3964 "Zend/zend_language_scanner.c" yy286: YYDEBUG(286, *YYCURSOR); ++YYCURSOR; YYDEBUG(287, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1359 "Zend/zend_language_scanner.l" { return T_PLUS_EQUAL; } #line 3974 "Zend/zend_language_scanner.c" yy288: YYDEBUG(288, *YYCURSOR); ++YYCURSOR; YYDEBUG(289, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1327 "Zend/zend_language_scanner.l" { return T_INC; } #line 3984 "Zend/zend_language_scanner.c" yy290: YYDEBUG(290, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy291; if (yych != 's') goto yy186; yy291: YYDEBUG(291, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy292; if (yych != 't') goto yy186; yy292: YYDEBUG(292, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(293, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1315 "Zend/zend_language_scanner.l" { return T_LIST; } #line 4007 "Zend/zend_language_scanner.c" yy294: YYDEBUG(294, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '=') goto yy298; YYDEBUG(295, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1343 "Zend/zend_language_scanner.l" { return T_IS_EQUAL; } #line 4018 "Zend/zend_language_scanner.c" yy296: YYDEBUG(296, *YYCURSOR); ++YYCURSOR; YYDEBUG(297, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1311 "Zend/zend_language_scanner.l" { return T_DOUBLE_ARROW; } #line 4028 "Zend/zend_language_scanner.c" yy298: YYDEBUG(298, *YYCURSOR); ++YYCURSOR; YYDEBUG(299, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1335 "Zend/zend_language_scanner.l" { return T_IS_IDENTICAL; } #line 4038 "Zend/zend_language_scanner.c" yy300: YYDEBUG(300, *YYCURSOR); yych = *++YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case 'C': case 'c': goto yy302; case 'D': case 'd': goto yy307; case 'F': case 'f': goto yy304; case 'H': case 'h': goto yy301; case 'L': case 'l': goto yy306; case 'M': case 'm': goto yy305; case 'N': case 'n': goto yy308; case 'T': case 't': goto yy303; default: goto yy186; } yy301: YYDEBUG(301, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy369; if (yych == 'a') goto yy369; goto yy186; yy302: YYDEBUG(302, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy362; if (yych == 'l') goto yy362; goto yy186; yy303: YYDEBUG(303, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy355; if (yych == 'r') goto yy355; goto yy186; yy304: YYDEBUG(304, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'I') goto yy339; if (yych <= 'T') goto yy186; goto yy340; } else { if (yych <= 'i') { if (yych <= 'h') goto yy186; goto yy339; } else { if (yych == 'u') goto yy340; goto yy186; } } yy305: YYDEBUG(305, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy331; if (yych == 'e') goto yy331; goto yy186; yy306: YYDEBUG(306, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy325; if (yych == 'i') goto yy325; goto yy186; yy307: YYDEBUG(307, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy320; if (yych == 'i') goto yy320; goto yy186; yy308: YYDEBUG(308, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy309; if (yych != 'a') goto yy186; yy309: YYDEBUG(309, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy310; if (yych != 'm') goto yy186; yy310: YYDEBUG(310, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy311; if (yych != 'e') goto yy186; yy311: YYDEBUG(311, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy312; if (yych != 's') goto yy186; yy312: YYDEBUG(312, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy313; if (yych != 'p') goto yy186; yy313: YYDEBUG(313, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy314; if (yych != 'a') goto yy186; yy314: YYDEBUG(314, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy315; if (yych != 'c') goto yy186; yy315: YYDEBUG(315, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy316; if (yych != 'e') goto yy186; yy316: YYDEBUG(316, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(317, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(318, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(319, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1694 "Zend/zend_language_scanner.l" { if (CG(current_namespace)) { *zendlval = *CG(current_namespace); zval_copy_ctor(zendlval); } else { ZVAL_EMPTY_STRING(zendlval); } return T_NS_C; } #line 4178 "Zend/zend_language_scanner.c" yy320: YYDEBUG(320, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy321; if (yych != 'r') goto yy186; yy321: YYDEBUG(321, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(322, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(323, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(324, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1667 "Zend/zend_language_scanner.l" { char *filename = zend_get_compiled_filename(TSRMLS_C); const size_t filename_len = strlen(filename); char *dirname; if (!filename) { filename = ""; } dirname = estrndup(filename, filename_len); zend_dirname(dirname, filename_len); if (strcmp(dirname, ".") == 0) { dirname = erealloc(dirname, MAXPATHLEN); #if HAVE_GETCWD VCWD_GETCWD(dirname, MAXPATHLEN); #elif HAVE_GETWD VCWD_GETWD(dirname); #endif } zendlval->value.str.len = strlen(dirname); zendlval->value.str.val = dirname; zendlval->type = IS_STRING; return T_DIR; } #line 4225 "Zend/zend_language_scanner.c" yy325: YYDEBUG(325, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy326; if (yych != 'n') goto yy186; yy326: YYDEBUG(326, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy327; if (yych != 'e') goto yy186; yy327: YYDEBUG(327, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(328, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(329, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(330, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1649 "Zend/zend_language_scanner.l" { zendlval->value.lval = CG(zend_lineno); zendlval->type = IS_LONG; return T_LINE; } #line 4256 "Zend/zend_language_scanner.c" yy331: YYDEBUG(331, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy332; if (yych != 't') goto yy186; yy332: YYDEBUG(332, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy333; if (yych != 'h') goto yy186; yy333: YYDEBUG(333, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy334; if (yych != 'o') goto yy186; yy334: YYDEBUG(334, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy335; if (yych != 'd') goto yy186; yy335: YYDEBUG(335, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(336, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(337, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(338, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1628 "Zend/zend_language_scanner.l" { const char *class_name = CG(active_class_entry) ? CG(active_class_entry)->name : NULL; const char *func_name = CG(active_op_array)? CG(active_op_array)->function_name : NULL; size_t len = 0; if (class_name) { len += strlen(class_name) + 2; } if (func_name) { len += strlen(func_name); } zendlval->value.str.len = zend_spprintf(&zendlval->value.str.val, 0, "%s%s%s", class_name ? class_name : "", class_name && func_name ? "::" : "", func_name ? func_name : "" ); zendlval->type = IS_STRING; return T_METHOD_C; } #line 4312 "Zend/zend_language_scanner.c" yy339: YYDEBUG(339, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy350; if (yych == 'l') goto yy350; goto yy186; yy340: YYDEBUG(340, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy341; if (yych != 'n') goto yy186; yy341: YYDEBUG(341, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy342; if (yych != 'c') goto yy186; yy342: YYDEBUG(342, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy343; if (yych != 't') goto yy186; yy343: YYDEBUG(343, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy344; if (yych != 'i') goto yy186; yy344: YYDEBUG(344, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy345; if (yych != 'o') goto yy186; yy345: YYDEBUG(345, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy346; if (yych != 'n') goto yy186; yy346: YYDEBUG(346, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(347, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(348, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(349, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1612 "Zend/zend_language_scanner.l" { const char *func_name = NULL; if (CG(active_op_array)) { func_name = CG(active_op_array)->function_name; } if (!func_name) { func_name = ""; } zendlval->value.str.len = strlen(func_name); zendlval->value.str.val = estrndup(func_name, zendlval->value.str.len); zendlval->type = IS_STRING; return T_FUNC_C; } #line 4379 "Zend/zend_language_scanner.c" yy350: YYDEBUG(350, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy351; if (yych != 'e') goto yy186; yy351: YYDEBUG(351, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(352, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(353, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(354, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1655 "Zend/zend_language_scanner.l" { char *filename = zend_get_compiled_filename(TSRMLS_C); if (!filename) { filename = ""; } zendlval->value.str.len = strlen(filename); zendlval->value.str.val = estrndup(filename, zendlval->value.str.len); zendlval->type = IS_STRING; return T_FILE; } #line 4411 "Zend/zend_language_scanner.c" yy355: YYDEBUG(355, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy356; if (yych != 'a') goto yy186; yy356: YYDEBUG(356, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy357; if (yych != 'i') goto yy186; yy357: YYDEBUG(357, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy358; if (yych != 't') goto yy186; yy358: YYDEBUG(358, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(359, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(360, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(361, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1592 "Zend/zend_language_scanner.l" { const char *trait_name = NULL; if (CG(active_class_entry) && (ZEND_ACC_TRAIT == (CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT))) { trait_name = CG(active_class_entry)->name; } if (!trait_name) { trait_name = ""; } zendlval->value.str.len = strlen(trait_name); zendlval->value.str.val = estrndup(trait_name, zendlval->value.str.len); zendlval->type = IS_STRING; return T_TRAIT_C; } #line 4461 "Zend/zend_language_scanner.c" yy362: YYDEBUG(362, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy363; if (yych != 'a') goto yy186; yy363: YYDEBUG(363, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy364; if (yych != 's') goto yy186; yy364: YYDEBUG(364, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy365; if (yych != 's') goto yy186; yy365: YYDEBUG(365, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(366, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(367, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(368, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1565 "Zend/zend_language_scanner.l" { const char *class_name = NULL; if (CG(active_class_entry) && (ZEND_ACC_TRAIT == (CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT))) { /* We create a special __CLASS__ constant that is going to be resolved at run-time */ zendlval->value.str.len = sizeof("__CLASS__")-1; zendlval->value.str.val = estrndup("__CLASS__", zendlval->value.str.len); zendlval->type = IS_CONSTANT; } else { if (CG(active_class_entry)) { class_name = CG(active_class_entry)->name; } if (!class_name) { class_name = ""; } zendlval->value.str.len = strlen(class_name); zendlval->value.str.val = estrndup(class_name, zendlval->value.str.len); zendlval->type = IS_STRING; } return T_CLASS_C; } #line 4518 "Zend/zend_language_scanner.c" yy369: YYDEBUG(369, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy370; if (yych != 'l') goto yy186; yy370: YYDEBUG(370, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy371; if (yych != 't') goto yy186; yy371: YYDEBUG(371, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(372, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy373; if (yych != 'c') goto yy186; yy373: YYDEBUG(373, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy374; if (yych != 'o') goto yy186; yy374: YYDEBUG(374, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy375; if (yych != 'm') goto yy186; yy375: YYDEBUG(375, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy376; if (yych != 'p') goto yy186; yy376: YYDEBUG(376, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy377; if (yych != 'i') goto yy186; yy377: YYDEBUG(377, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy378; if (yych != 'l') goto yy186; yy378: YYDEBUG(378, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy379; if (yych != 'e') goto yy186; yy379: YYDEBUG(379, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy380; if (yych != 'r') goto yy186; yy380: YYDEBUG(380, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(381, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1279 "Zend/zend_language_scanner.l" { return T_HALT_COMPILER; } #line 4584 "Zend/zend_language_scanner.c" yy382: YYDEBUG(382, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy386; if (yych == 's') goto yy386; goto yy186; yy383: YYDEBUG(383, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy384; if (yych != 'e') goto yy186; yy384: YYDEBUG(384, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(385, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1259 "Zend/zend_language_scanner.l" { return T_USE; } #line 4608 "Zend/zend_language_scanner.c" yy386: YYDEBUG(386, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy387; if (yych != 'e') goto yy186; yy387: YYDEBUG(387, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy388; if (yych != 't') goto yy186; yy388: YYDEBUG(388, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(389, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1307 "Zend/zend_language_scanner.l" { return T_UNSET; } #line 4631 "Zend/zend_language_scanner.c" yy390: YYDEBUG(390, *YYCURSOR); ++YYCURSOR; YYFILL(7); yych = *YYCURSOR; yy391: YYDEBUG(391, *YYCURSOR); if (yych <= 'S') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy390; if (yych <= 0x1F) goto yy193; goto yy390; } else { if (yych <= 'A') { if (yych <= '@') goto yy193; goto yy395; } else { if (yych <= 'B') goto yy393; if (yych <= 'C') goto yy193; goto yy398; } } } else { if (yych <= 'I') { if (yych == 'F') goto yy399; if (yych <= 'H') goto yy193; goto yy400; } else { if (yych <= 'O') { if (yych <= 'N') goto yy193; goto yy394; } else { if (yych <= 'Q') goto yy193; if (yych <= 'R') goto yy397; goto yy396; } } } } else { if (yych <= 'f') { if (yych <= 'a') { if (yych == 'U') goto yy392; if (yych <= '`') goto yy193; goto yy395; } else { if (yych <= 'c') { if (yych <= 'b') goto yy393; goto yy193; } else { if (yych <= 'd') goto yy398; if (yych <= 'e') goto yy193; goto yy399; } } } else { if (yych <= 'q') { if (yych <= 'i') { if (yych <= 'h') goto yy193; goto yy400; } else { if (yych == 'o') goto yy394; goto yy193; } } else { if (yych <= 's') { if (yych <= 'r') goto yy397; goto yy396; } else { if (yych != 'u') goto yy193; } } } } yy392: YYDEBUG(392, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy459; if (yych == 'n') goto yy459; goto yy193; yy393: YYDEBUG(393, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'I') goto yy446; if (yych <= 'N') goto yy193; goto yy447; } else { if (yych <= 'i') { if (yych <= 'h') goto yy193; goto yy446; } else { if (yych == 'o') goto yy447; goto yy193; } } yy394: YYDEBUG(394, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy438; if (yych == 'b') goto yy438; goto yy193; yy395: YYDEBUG(395, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy431; if (yych == 'r') goto yy431; goto yy193; yy396: YYDEBUG(396, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy423; if (yych == 't') goto yy423; goto yy193; yy397: YYDEBUG(397, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy421; if (yych == 'e') goto yy421; goto yy193; yy398: YYDEBUG(398, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy417; if (yych == 'o') goto yy417; goto yy193; yy399: YYDEBUG(399, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy410; if (yych == 'l') goto yy410; goto yy193; yy400: YYDEBUG(400, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy401; if (yych != 'n') goto yy193; yy401: YYDEBUG(401, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy402; if (yych != 't') goto yy193; yy402: YYDEBUG(402, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy403; if (yych != 'e') goto yy405; yy403: YYDEBUG(403, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy408; if (yych == 'g') goto yy408; goto yy193; yy404: YYDEBUG(404, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy405: YYDEBUG(405, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy404; goto yy193; } else { if (yych <= ' ') goto yy404; if (yych != ')') goto yy193; } YYDEBUG(406, *YYCURSOR); ++YYCURSOR; YYDEBUG(407, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1207 "Zend/zend_language_scanner.l" { return T_INT_CAST; } #line 4807 "Zend/zend_language_scanner.c" yy408: YYDEBUG(408, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy409; if (yych != 'e') goto yy193; yy409: YYDEBUG(409, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy404; if (yych == 'r') goto yy404; goto yy193; yy410: YYDEBUG(410, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy411; if (yych != 'o') goto yy193; yy411: YYDEBUG(411, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy412; if (yych != 'a') goto yy193; yy412: YYDEBUG(412, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy413; if (yych != 't') goto yy193; yy413: YYDEBUG(413, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(414, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy413; goto yy193; } else { if (yych <= ' ') goto yy413; if (yych != ')') goto yy193; } YYDEBUG(415, *YYCURSOR); ++YYCURSOR; YYDEBUG(416, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1211 "Zend/zend_language_scanner.l" { return T_DOUBLE_CAST; } #line 4855 "Zend/zend_language_scanner.c" yy417: YYDEBUG(417, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy418; if (yych != 'u') goto yy193; yy418: YYDEBUG(418, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy419; if (yych != 'b') goto yy193; yy419: YYDEBUG(419, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy420; if (yych != 'l') goto yy193; yy420: YYDEBUG(420, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy413; if (yych == 'e') goto yy413; goto yy193; yy421: YYDEBUG(421, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy422; if (yych != 'a') goto yy193; yy422: YYDEBUG(422, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy413; if (yych == 'l') goto yy413; goto yy193; yy423: YYDEBUG(423, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy424; if (yych != 'r') goto yy193; yy424: YYDEBUG(424, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy425; if (yych != 'i') goto yy193; yy425: YYDEBUG(425, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy426; if (yych != 'n') goto yy193; yy426: YYDEBUG(426, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy427; if (yych != 'g') goto yy193; yy427: YYDEBUG(427, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(428, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy427; goto yy193; } else { if (yych <= ' ') goto yy427; if (yych != ')') goto yy193; } YYDEBUG(429, *YYCURSOR); ++YYCURSOR; YYDEBUG(430, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1215 "Zend/zend_language_scanner.l" { return T_STRING_CAST; } #line 4929 "Zend/zend_language_scanner.c" yy431: YYDEBUG(431, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy432; if (yych != 'r') goto yy193; yy432: YYDEBUG(432, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy433; if (yych != 'a') goto yy193; yy433: YYDEBUG(433, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy434; if (yych != 'y') goto yy193; yy434: YYDEBUG(434, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(435, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy434; goto yy193; } else { if (yych <= ' ') goto yy434; if (yych != ')') goto yy193; } YYDEBUG(436, *YYCURSOR); ++YYCURSOR; YYDEBUG(437, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1219 "Zend/zend_language_scanner.l" { return T_ARRAY_CAST; } #line 4966 "Zend/zend_language_scanner.c" yy438: YYDEBUG(438, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'J') goto yy439; if (yych != 'j') goto yy193; yy439: YYDEBUG(439, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy440; if (yych != 'e') goto yy193; yy440: YYDEBUG(440, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy441; if (yych != 'c') goto yy193; yy441: YYDEBUG(441, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy442; if (yych != 't') goto yy193; yy442: YYDEBUG(442, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(443, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy442; goto yy193; } else { if (yych <= ' ') goto yy442; if (yych != ')') goto yy193; } YYDEBUG(444, *YYCURSOR); ++YYCURSOR; YYDEBUG(445, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1223 "Zend/zend_language_scanner.l" { return T_OBJECT_CAST; } #line 5008 "Zend/zend_language_scanner.c" yy446: YYDEBUG(446, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy456; if (yych == 'n') goto yy456; goto yy193; yy447: YYDEBUG(447, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy448; if (yych != 'o') goto yy193; yy448: YYDEBUG(448, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy449; if (yych != 'l') goto yy193; yy449: YYDEBUG(449, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy454; if (yych == 'e') goto yy454; goto yy451; yy450: YYDEBUG(450, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy451: YYDEBUG(451, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy450; goto yy193; } else { if (yych <= ' ') goto yy450; if (yych != ')') goto yy193; } YYDEBUG(452, *YYCURSOR); ++YYCURSOR; YYDEBUG(453, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1227 "Zend/zend_language_scanner.l" { return T_BOOL_CAST; } #line 5053 "Zend/zend_language_scanner.c" yy454: YYDEBUG(454, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy455; if (yych != 'a') goto yy193; yy455: YYDEBUG(455, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy450; if (yych == 'n') goto yy450; goto yy193; yy456: YYDEBUG(456, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy457; if (yych != 'a') goto yy193; yy457: YYDEBUG(457, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy458; if (yych != 'r') goto yy193; yy458: YYDEBUG(458, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy427; if (yych == 'y') goto yy427; goto yy193; yy459: YYDEBUG(459, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy460; if (yych != 's') goto yy193; yy460: YYDEBUG(460, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy461; if (yych != 'e') goto yy193; yy461: YYDEBUG(461, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy462; if (yych != 't') goto yy193; yy462: YYDEBUG(462, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(463, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy462; goto yy193; } else { if (yych <= ' ') goto yy462; if (yych != ')') goto yy193; } YYDEBUG(464, *YYCURSOR); ++YYCURSOR; YYDEBUG(465, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1231 "Zend/zend_language_scanner.l" { return T_UNSET_CAST; } #line 5117 "Zend/zend_language_scanner.c" yy466: YYDEBUG(466, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy467; if (yych != 'r') goto yy186; yy467: YYDEBUG(467, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(468, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1203 "Zend/zend_language_scanner.l" { return T_VAR; } #line 5135 "Zend/zend_language_scanner.c" yy469: YYDEBUG(469, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy473; if (yych == 'm') goto yy473; goto yy186; yy470: YYDEBUG(470, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'W') goto yy471; if (yych != 'w') goto yy186; yy471: YYDEBUG(471, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(472, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1195 "Zend/zend_language_scanner.l" { return T_NEW; } #line 5159 "Zend/zend_language_scanner.c" yy473: YYDEBUG(473, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy474; if (yych != 'e') goto yy186; yy474: YYDEBUG(474, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy475; if (yych != 's') goto yy186; yy475: YYDEBUG(475, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy476; if (yych != 'p') goto yy186; yy476: YYDEBUG(476, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy477; if (yych != 'a') goto yy186; yy477: YYDEBUG(477, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy478; if (yych != 'c') goto yy186; yy478: YYDEBUG(478, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy479; if (yych != 'e') goto yy186; yy479: YYDEBUG(479, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(480, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1255 "Zend/zend_language_scanner.l" { return T_NAMESPACE; } #line 5202 "Zend/zend_language_scanner.c" yy481: YYDEBUG(481, *YYCURSOR); ++YYCURSOR; YYDEBUG(482, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1187 "Zend/zend_language_scanner.l" { return T_PAAMAYIM_NEKUDOTAYIM; } #line 5212 "Zend/zend_language_scanner.c" yy483: YYDEBUG(483, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy484: YYDEBUG(484, *YYCURSOR); if (yych <= '\f') { if (yych <= 0x08) goto yy140; if (yych <= '\n') goto yy483; goto yy140; } else { if (yych <= '\r') goto yy483; if (yych == ' ') goto yy483; goto yy140; } yy485: YYDEBUG(485, *YYCURSOR); ++YYCURSOR; YYDEBUG(486, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1363 "Zend/zend_language_scanner.l" { return T_MINUS_EQUAL; } #line 5238 "Zend/zend_language_scanner.c" yy487: YYDEBUG(487, *YYCURSOR); ++YYCURSOR; YYDEBUG(488, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1331 "Zend/zend_language_scanner.l" { return T_DEC; } #line 5248 "Zend/zend_language_scanner.c" yy489: YYDEBUG(489, *YYCURSOR); ++YYCURSOR; YYDEBUG(490, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1157 "Zend/zend_language_scanner.l" { yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC); return T_OBJECT_OPERATOR; } #line 5259 "Zend/zend_language_scanner.c" yy491: YYDEBUG(491, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'I') goto yy498; if (yych <= 'N') goto yy186; goto yy499; } else { if (yych <= 'i') { if (yych <= 'h') goto yy186; goto yy498; } else { if (yych == 'o') goto yy499; goto yy186; } } yy492: YYDEBUG(492, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy493; if (yych != 'b') goto yy186; yy493: YYDEBUG(493, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy494; if (yych != 'l') goto yy186; yy494: YYDEBUG(494, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy495; if (yych != 'i') goto yy186; yy495: YYDEBUG(495, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy496; if (yych != 'c') goto yy186; yy496: YYDEBUG(496, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(497, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1303 "Zend/zend_language_scanner.l" { return T_PUBLIC; } #line 5308 "Zend/zend_language_scanner.c" yy498: YYDEBUG(498, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'V') { if (yych == 'N') goto yy507; if (yych <= 'U') goto yy186; goto yy508; } else { if (yych <= 'n') { if (yych <= 'm') goto yy186; goto yy507; } else { if (yych == 'v') goto yy508; goto yy186; } } yy499: YYDEBUG(499, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy500; if (yych != 't') goto yy186; yy500: YYDEBUG(500, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy501; if (yych != 'e') goto yy186; yy501: YYDEBUG(501, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy502; if (yych != 'c') goto yy186; yy502: YYDEBUG(502, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy503; if (yych != 't') goto yy186; yy503: YYDEBUG(503, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy504; if (yych != 'e') goto yy186; yy504: YYDEBUG(504, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy505; if (yych != 'd') goto yy186; yy505: YYDEBUG(505, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(506, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1299 "Zend/zend_language_scanner.l" { return T_PROTECTED; } #line 5367 "Zend/zend_language_scanner.c" yy507: YYDEBUG(507, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy513; if (yych == 't') goto yy513; goto yy186; yy508: YYDEBUG(508, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy509; if (yych != 'a') goto yy186; yy509: YYDEBUG(509, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy510; if (yych != 't') goto yy186; yy510: YYDEBUG(510, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy511; if (yych != 'e') goto yy186; yy511: YYDEBUG(511, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(512, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1295 "Zend/zend_language_scanner.l" { return T_PRIVATE; } #line 5401 "Zend/zend_language_scanner.c" yy513: YYDEBUG(513, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(514, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1133 "Zend/zend_language_scanner.l" { return T_PRINT; } #line 5414 "Zend/zend_language_scanner.c" yy515: YYDEBUG(515, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy520; if (yych == 'o') goto yy520; goto yy186; yy516: YYDEBUG(516, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy517; if (yych != 't') goto yy186; yy517: YYDEBUG(517, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy518; if (yych != 'o') goto yy186; yy518: YYDEBUG(518, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(519, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1125 "Zend/zend_language_scanner.l" { return T_GOTO; } #line 5443 "Zend/zend_language_scanner.c" yy520: YYDEBUG(520, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy521; if (yych != 'b') goto yy186; yy521: YYDEBUG(521, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy522; if (yych != 'a') goto yy186; yy522: YYDEBUG(522, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy523; if (yych != 'l') goto yy186; yy523: YYDEBUG(523, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(524, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1267 "Zend/zend_language_scanner.l" { return T_GLOBAL; } #line 5471 "Zend/zend_language_scanner.c" yy525: YYDEBUG(525, *YYCURSOR); yych = *++YYCURSOR; if (yych == '<') goto yy533; goto yy193; yy526: YYDEBUG(526, *YYCURSOR); yych = *++YYCURSOR; goto yy180; yy527: YYDEBUG(527, *YYCURSOR); yych = *++YYCURSOR; goto yy178; yy528: YYDEBUG(528, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy529; if (yych != 'e') goto yy186; yy529: YYDEBUG(529, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy530; if (yych != 'a') goto yy186; yy530: YYDEBUG(530, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'K') goto yy531; if (yych != 'k') goto yy186; yy531: YYDEBUG(531, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(532, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1117 "Zend/zend_language_scanner.l" { return T_BREAK; } #line 5512 "Zend/zend_language_scanner.c" yy533: YYDEBUG(533, *YYCURSOR); yych = *++YYCURSOR; if (yych == '<') goto yy269; goto yy193; yy534: YYDEBUG(534, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy541; if (yych == 'a') goto yy541; goto yy186; yy535: YYDEBUG(535, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy536; if (yych != 'i') goto yy186; yy536: YYDEBUG(536, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy537; if (yych != 't') goto yy186; yy537: YYDEBUG(537, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy538; if (yych != 'c') goto yy186; yy538: YYDEBUG(538, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy539; if (yych != 'h') goto yy186; yy539: YYDEBUG(539, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(540, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1101 "Zend/zend_language_scanner.l" { return T_SWITCH; } #line 5556 "Zend/zend_language_scanner.c" yy541: YYDEBUG(541, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy542; if (yych != 't') goto yy186; yy542: YYDEBUG(542, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy543; if (yych != 'i') goto yy186; yy543: YYDEBUG(543, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy544; if (yych != 'c') goto yy186; yy544: YYDEBUG(544, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(545, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1283 "Zend/zend_language_scanner.l" { return T_STATIC; } #line 5584 "Zend/zend_language_scanner.c" yy546: YYDEBUG(546, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy557; if (yych == 's') goto yy557; goto yy186; yy547: YYDEBUG(547, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy555; if (yych == 'd') goto yy555; goto yy186; yy548: YYDEBUG(548, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy551; if (yych == 'r') goto yy551; goto yy186; yy549: YYDEBUG(549, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(550, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1097 "Zend/zend_language_scanner.l" { return T_AS; } #line 5615 "Zend/zend_language_scanner.c" yy551: YYDEBUG(551, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy552; if (yych != 'a') goto yy186; yy552: YYDEBUG(552, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy553; if (yych != 'y') goto yy186; yy553: YYDEBUG(553, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(554, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1319 "Zend/zend_language_scanner.l" { return T_ARRAY; } #line 5638 "Zend/zend_language_scanner.c" yy555: YYDEBUG(555, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(556, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1415 "Zend/zend_language_scanner.l" { return T_LOGICAL_AND; } #line 5651 "Zend/zend_language_scanner.c" yy557: YYDEBUG(557, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy558; if (yych != 't') goto yy186; yy558: YYDEBUG(558, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy559; if (yych != 'r') goto yy186; yy559: YYDEBUG(559, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy560; if (yych != 'a') goto yy186; yy560: YYDEBUG(560, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy561; if (yych != 'c') goto yy186; yy561: YYDEBUG(561, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy562; if (yych != 't') goto yy186; yy562: YYDEBUG(562, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(563, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1287 "Zend/zend_language_scanner.l" { return T_ABSTRACT; } #line 5689 "Zend/zend_language_scanner.c" yy564: YYDEBUG(564, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy565; if (yych != 'i') goto yy186; yy565: YYDEBUG(565, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy566; if (yych != 'l') goto yy186; yy566: YYDEBUG(566, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy567; if (yych != 'e') goto yy186; yy567: YYDEBUG(567, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(568, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1057 "Zend/zend_language_scanner.l" { return T_WHILE; } #line 5717 "Zend/zend_language_scanner.c" yy569: YYDEBUG(569, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(570, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1041 "Zend/zend_language_scanner.l" { return T_IF; } #line 5730 "Zend/zend_language_scanner.c" yy571: YYDEBUG(571, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy613; if (yych == 'p') goto yy613; goto yy186; yy572: YYDEBUG(572, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= 'C') { if (yych <= 'B') goto yy186; goto yy580; } else { if (yych <= 'R') goto yy186; if (yych <= 'S') goto yy578; goto yy579; } } else { if (yych <= 'r') { if (yych == 'c') goto yy580; goto yy186; } else { if (yych <= 's') goto yy578; if (yych <= 't') goto yy579; goto yy186; } } yy573: YYDEBUG(573, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy574; if (yych != 's') goto yy186; yy574: YYDEBUG(574, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy575; if (yych != 'e') goto yy186; yy575: YYDEBUG(575, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy576; if (yych != 't') goto yy186; yy576: YYDEBUG(576, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(577, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1271 "Zend/zend_language_scanner.l" { return T_ISSET; } #line 5786 "Zend/zend_language_scanner.c" yy578: YYDEBUG(578, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy599; if (yych == 't') goto yy599; goto yy186; yy579: YYDEBUG(579, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy592; if (yych == 'e') goto yy592; goto yy186; yy580: YYDEBUG(580, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy581; if (yych != 'l') goto yy186; yy581: YYDEBUG(581, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy582; if (yych != 'u') goto yy186; yy582: YYDEBUG(582, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy583; if (yych != 'd') goto yy186; yy583: YYDEBUG(583, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy584; if (yych != 'e') goto yy186; yy584: YYDEBUG(584, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '9') { if (yych >= '0') goto yy185; } else { if (yych <= '@') goto yy585; if (yych <= 'Z') goto yy185; } } else { if (yych <= '`') { if (yych <= '_') goto yy586; } else { if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy585: YYDEBUG(585, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1239 "Zend/zend_language_scanner.l" { return T_INCLUDE; } #line 5844 "Zend/zend_language_scanner.c" yy586: YYDEBUG(586, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy587; if (yych != 'o') goto yy186; yy587: YYDEBUG(587, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy588; if (yych != 'n') goto yy186; yy588: YYDEBUG(588, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy589; if (yych != 'c') goto yy186; yy589: YYDEBUG(589, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy590; if (yych != 'e') goto yy186; yy590: YYDEBUG(590, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(591, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1243 "Zend/zend_language_scanner.l" { return T_INCLUDE_ONCE; } #line 5877 "Zend/zend_language_scanner.c" yy592: YYDEBUG(592, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy593; if (yych != 'r') goto yy186; yy593: YYDEBUG(593, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy594; if (yych != 'f') goto yy186; yy594: YYDEBUG(594, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy595; if (yych != 'a') goto yy186; yy595: YYDEBUG(595, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy596; if (yych != 'c') goto yy186; yy596: YYDEBUG(596, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy597; if (yych != 'e') goto yy186; yy597: YYDEBUG(597, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(598, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1141 "Zend/zend_language_scanner.l" { return T_INTERFACE; } #line 5915 "Zend/zend_language_scanner.c" yy599: YYDEBUG(599, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych == 'A') goto yy600; if (yych <= 'D') goto yy186; goto yy601; } else { if (yych <= 'a') { if (yych <= '`') goto yy186; } else { if (yych == 'e') goto yy601; goto yy186; } } yy600: YYDEBUG(600, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy607; if (yych == 'n') goto yy607; goto yy186; yy601: YYDEBUG(601, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy602; if (yych != 'a') goto yy186; yy602: YYDEBUG(602, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy603; if (yych != 'd') goto yy186; yy603: YYDEBUG(603, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy604; if (yych != 'o') goto yy186; yy604: YYDEBUG(604, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy605; if (yych != 'f') goto yy186; yy605: YYDEBUG(605, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(606, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1263 "Zend/zend_language_scanner.l" { return T_INSTEADOF; } #line 5969 "Zend/zend_language_scanner.c" yy607: YYDEBUG(607, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy608; if (yych != 'c') goto yy186; yy608: YYDEBUG(608, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy609; if (yych != 'e') goto yy186; yy609: YYDEBUG(609, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy610; if (yych != 'o') goto yy186; yy610: YYDEBUG(610, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy611; if (yych != 'f') goto yy186; yy611: YYDEBUG(611, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(612, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1093 "Zend/zend_language_scanner.l" { return T_INSTANCEOF; } #line 6002 "Zend/zend_language_scanner.c" yy613: YYDEBUG(613, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy614; if (yych != 'l') goto yy186; yy614: YYDEBUG(614, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy615; if (yych != 'e') goto yy186; yy615: YYDEBUG(615, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy616; if (yych != 'm') goto yy186; yy616: YYDEBUG(616, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy617; if (yych != 'e') goto yy186; yy617: YYDEBUG(617, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy618; if (yych != 'n') goto yy186; yy618: YYDEBUG(618, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy619; if (yych != 't') goto yy186; yy619: YYDEBUG(619, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy620; if (yych != 's') goto yy186; yy620: YYDEBUG(620, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(621, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1153 "Zend/zend_language_scanner.l" { return T_IMPLEMENTS; } #line 6050 "Zend/zend_language_scanner.c" yy622: YYDEBUG(622, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy630; if (yych == 'r') goto yy630; goto yy186; yy623: YYDEBUG(623, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych == 'A') goto yy626; if (yych <= 'X') goto yy186; } else { if (yych <= 'a') { if (yych <= '`') goto yy186; goto yy626; } else { if (yych != 'y') goto yy186; } } YYDEBUG(624, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(625, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1029 "Zend/zend_language_scanner.l" { return T_TRY; } #line 6082 "Zend/zend_language_scanner.c" yy626: YYDEBUG(626, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy627; if (yych != 'i') goto yy186; yy627: YYDEBUG(627, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy628; if (yych != 't') goto yy186; yy628: YYDEBUG(628, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(629, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1145 "Zend/zend_language_scanner.l" { return T_TRAIT; } #line 6105 "Zend/zend_language_scanner.c" yy630: YYDEBUG(630, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy631; if (yych != 'o') goto yy186; yy631: YYDEBUG(631, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'W') goto yy632; if (yych != 'w') goto yy186; yy632: YYDEBUG(632, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(633, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1037 "Zend/zend_language_scanner.l" { return T_THROW; } #line 6128 "Zend/zend_language_scanner.c" yy634: YYDEBUG(634, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych == 'Q') goto yy636; if (yych <= 'S') goto yy186; } else { if (yych <= 'q') { if (yych <= 'p') goto yy186; goto yy636; } else { if (yych != 't') goto yy186; } } YYDEBUG(635, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy648; if (yych == 'u') goto yy648; goto yy186; yy636: YYDEBUG(636, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy637; if (yych != 'u') goto yy186; yy637: YYDEBUG(637, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy638; if (yych != 'i') goto yy186; yy638: YYDEBUG(638, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy639; if (yych != 'r') goto yy186; yy639: YYDEBUG(639, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy640; if (yych != 'e') goto yy186; yy640: YYDEBUG(640, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '9') { if (yych >= '0') goto yy185; } else { if (yych <= '@') goto yy641; if (yych <= 'Z') goto yy185; } } else { if (yych <= '`') { if (yych <= '_') goto yy642; } else { if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy641: YYDEBUG(641, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1247 "Zend/zend_language_scanner.l" { return T_REQUIRE; } #line 6193 "Zend/zend_language_scanner.c" yy642: YYDEBUG(642, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy643; if (yych != 'o') goto yy186; yy643: YYDEBUG(643, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy644; if (yych != 'n') goto yy186; yy644: YYDEBUG(644, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy645; if (yych != 'c') goto yy186; yy645: YYDEBUG(645, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy646; if (yych != 'e') goto yy186; yy646: YYDEBUG(646, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(647, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1251 "Zend/zend_language_scanner.l" { return T_REQUIRE_ONCE; } #line 6226 "Zend/zend_language_scanner.c" yy648: YYDEBUG(648, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy649; if (yych != 'r') goto yy186; yy649: YYDEBUG(649, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy650; if (yych != 'n') goto yy186; yy650: YYDEBUG(650, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(651, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1025 "Zend/zend_language_scanner.l" { return T_RETURN; } #line 6249 "Zend/zend_language_scanner.c" yy652: YYDEBUG(652, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= 'L') { if (yych <= 'K') goto yy186; goto yy675; } else { if (yych <= 'R') goto yy186; if (yych <= 'S') goto yy674; goto yy673; } } else { if (yych <= 'r') { if (yych == 'l') goto yy675; goto yy186; } else { if (yych <= 's') goto yy674; if (yych <= 't') goto yy673; goto yy186; } } yy653: YYDEBUG(653, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'A') goto yy665; if (yych <= 'N') goto yy186; goto yy666; } else { if (yych <= 'a') { if (yych <= '`') goto yy186; goto yy665; } else { if (yych == 'o') goto yy666; goto yy186; } } yy654: YYDEBUG(654, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy655; if (yych != 'n') goto yy186; yy655: YYDEBUG(655, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= 'R') goto yy186; if (yych >= 'T') goto yy657; } else { if (yych <= 'r') goto yy186; if (yych <= 's') goto yy656; if (yych <= 't') goto yy657; goto yy186; } yy656: YYDEBUG(656, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy663; if (yych == 't') goto yy663; goto yy186; yy657: YYDEBUG(657, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy658; if (yych != 'i') goto yy186; yy658: YYDEBUG(658, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy659; if (yych != 'n') goto yy186; yy659: YYDEBUG(659, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy660; if (yych != 'u') goto yy186; yy660: YYDEBUG(660, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy661; if (yych != 'e') goto yy186; yy661: YYDEBUG(661, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(662, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1121 "Zend/zend_language_scanner.l" { return T_CONTINUE; } #line 6343 "Zend/zend_language_scanner.c" yy663: YYDEBUG(663, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(664, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1021 "Zend/zend_language_scanner.l" { return T_CONST; } #line 6356 "Zend/zend_language_scanner.c" yy665: YYDEBUG(665, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy670; if (yych == 's') goto yy670; goto yy186; yy666: YYDEBUG(666, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy667; if (yych != 'n') goto yy186; yy667: YYDEBUG(667, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy668; if (yych != 'e') goto yy186; yy668: YYDEBUG(668, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(669, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1199 "Zend/zend_language_scanner.l" { return T_CLONE; } #line 6385 "Zend/zend_language_scanner.c" yy670: YYDEBUG(670, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy671; if (yych != 's') goto yy186; yy671: YYDEBUG(671, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(672, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1137 "Zend/zend_language_scanner.l" { return T_CLASS; } #line 6403 "Zend/zend_language_scanner.c" yy673: YYDEBUG(673, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy684; if (yych == 'c') goto yy684; goto yy186; yy674: YYDEBUG(674, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy682; if (yych == 'e') goto yy682; goto yy186; yy675: YYDEBUG(675, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy676; if (yych != 'l') goto yy186; yy676: YYDEBUG(676, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy677; if (yych != 'a') goto yy186; yy677: YYDEBUG(677, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy678; if (yych != 'b') goto yy186; yy678: YYDEBUG(678, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy679; if (yych != 'l') goto yy186; yy679: YYDEBUG(679, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy680; if (yych != 'e') goto yy186; yy680: YYDEBUG(680, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(681, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1323 "Zend/zend_language_scanner.l" { return T_CALLABLE; } #line 6453 "Zend/zend_language_scanner.c" yy682: YYDEBUG(682, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(683, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1109 "Zend/zend_language_scanner.l" { return T_CASE; } #line 6466 "Zend/zend_language_scanner.c" yy684: YYDEBUG(684, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy685; if (yych != 'h') goto yy186; yy685: YYDEBUG(685, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(686, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1033 "Zend/zend_language_scanner.l" { return T_CATCH; } #line 6484 "Zend/zend_language_scanner.c" yy687: YYDEBUG(687, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy704; if (yych == 'n') goto yy704; goto yy186; yy688: YYDEBUG(688, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy697; if (yych == 'r') goto yy697; goto yy186; yy689: YYDEBUG(689, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy690; if (yych != 'n') goto yy186; yy690: YYDEBUG(690, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy691; if (yych != 'c') goto yy186; yy691: YYDEBUG(691, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy692; if (yych != 't') goto yy186; yy692: YYDEBUG(692, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy693; if (yych != 'i') goto yy186; yy693: YYDEBUG(693, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy694; if (yych != 'o') goto yy186; yy694: YYDEBUG(694, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy695; if (yych != 'n') goto yy186; yy695: YYDEBUG(695, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(696, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1017 "Zend/zend_language_scanner.l" { return T_FUNCTION; } #line 6539 "Zend/zend_language_scanner.c" yy697: YYDEBUG(697, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '@') { if (yych <= '/') goto yy698; if (yych <= '9') goto yy185; } else { if (yych == 'E') goto yy699; if (yych <= 'Z') goto yy185; } } else { if (yych <= 'd') { if (yych != '`') goto yy185; } else { if (yych <= 'e') goto yy699; if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy698: YYDEBUG(698, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1069 "Zend/zend_language_scanner.l" { return T_FOR; } #line 6567 "Zend/zend_language_scanner.c" yy699: YYDEBUG(699, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy700; if (yych != 'a') goto yy186; yy700: YYDEBUG(700, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy701; if (yych != 'c') goto yy186; yy701: YYDEBUG(701, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy702; if (yych != 'h') goto yy186; yy702: YYDEBUG(702, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(703, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1077 "Zend/zend_language_scanner.l" { return T_FOREACH; } #line 6595 "Zend/zend_language_scanner.c" yy704: YYDEBUG(704, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy705; if (yych != 'a') goto yy186; yy705: YYDEBUG(705, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy706; if (yych != 'l') goto yy186; yy706: YYDEBUG(706, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(707, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1291 "Zend/zend_language_scanner.l" { return T_FINAL; } #line 6618 "Zend/zend_language_scanner.c" yy708: YYDEBUG(708, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'F') { if (yych == 'C') goto yy714; if (yych <= 'E') goto yy186; goto yy715; } else { if (yych <= 'c') { if (yych <= 'b') goto yy186; goto yy714; } else { if (yych == 'f') goto yy715; goto yy186; } } yy709: YYDEBUG(709, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy712; if (yych == 'e') goto yy712; goto yy186; yy710: YYDEBUG(710, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(711, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1065 "Zend/zend_language_scanner.l" { return T_DO; } #line 6653 "Zend/zend_language_scanner.c" yy712: YYDEBUG(712, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(713, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1013 "Zend/zend_language_scanner.l" { return T_EXIT; } #line 6666 "Zend/zend_language_scanner.c" yy714: YYDEBUG(714, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy721; if (yych == 'l') goto yy721; goto yy186; yy715: YYDEBUG(715, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy716; if (yych != 'a') goto yy186; yy716: YYDEBUG(716, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy717; if (yych != 'u') goto yy186; yy717: YYDEBUG(717, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy718; if (yych != 'l') goto yy186; yy718: YYDEBUG(718, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy719; if (yych != 't') goto yy186; yy719: YYDEBUG(719, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(720, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1113 "Zend/zend_language_scanner.l" { return T_DEFAULT; } #line 6705 "Zend/zend_language_scanner.c" yy721: YYDEBUG(721, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy722; if (yych != 'a') goto yy186; yy722: YYDEBUG(722, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy723; if (yych != 'r') goto yy186; yy723: YYDEBUG(723, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy724; if (yych != 'e') goto yy186; yy724: YYDEBUG(724, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(725, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1085 "Zend/zend_language_scanner.l" { return T_DECLARE; } #line 6733 "Zend/zend_language_scanner.c" yy726: YYDEBUG(726, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy788; if (yych == 'h') goto yy788; goto yy186; yy727: YYDEBUG(727, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy782; if (yych == 's') goto yy782; goto yy186; yy728: YYDEBUG(728, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy778; if (yych == 'p') goto yy778; goto yy186; yy729: YYDEBUG(729, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy744; if (yych == 'd') goto yy744; goto yy186; yy730: YYDEBUG(730, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy741; if (yych == 'a') goto yy741; goto yy186; yy731: YYDEBUG(731, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych == 'I') goto yy732; if (yych <= 'S') goto yy186; goto yy733; } else { if (yych <= 'i') { if (yych <= 'h') goto yy186; } else { if (yych == 't') goto yy733; goto yy186; } } yy732: YYDEBUG(732, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy739; if (yych == 't') goto yy739; goto yy186; yy733: YYDEBUG(733, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy734; if (yych != 'e') goto yy186; yy734: YYDEBUG(734, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy735; if (yych != 'n') goto yy186; yy735: YYDEBUG(735, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy736; if (yych != 'd') goto yy186; yy736: YYDEBUG(736, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy737; if (yych != 's') goto yy186; yy737: YYDEBUG(737, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(738, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1149 "Zend/zend_language_scanner.l" { return T_EXTENDS; } #line 6817 "Zend/zend_language_scanner.c" yy739: YYDEBUG(739, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(740, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1009 "Zend/zend_language_scanner.l" { return T_EXIT; } #line 6830 "Zend/zend_language_scanner.c" yy741: YYDEBUG(741, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy742; if (yych != 'l') goto yy186; yy742: YYDEBUG(742, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(743, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1235 "Zend/zend_language_scanner.l" { return T_EVAL; } #line 6848 "Zend/zend_language_scanner.c" yy744: YYDEBUG(744, *YYCURSOR); yych = *++YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case 'D': case 'd': goto yy745; case 'F': case 'f': goto yy746; case 'I': case 'i': goto yy747; case 'S': case 's': goto yy748; case 'W': case 'w': goto yy749; default: goto yy186; } yy745: YYDEBUG(745, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy771; if (yych == 'e') goto yy771; goto yy186; yy746: YYDEBUG(746, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy763; if (yych == 'o') goto yy763; goto yy186; yy747: YYDEBUG(747, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy761; if (yych == 'f') goto yy761; goto yy186; yy748: YYDEBUG(748, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'W') goto yy755; if (yych == 'w') goto yy755; goto yy186; yy749: YYDEBUG(749, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy750; if (yych != 'h') goto yy186; yy750: YYDEBUG(750, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy751; if (yych != 'i') goto yy186; yy751: YYDEBUG(751, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy752; if (yych != 'l') goto yy186; yy752: YYDEBUG(752, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy753; if (yych != 'e') goto yy186; yy753: YYDEBUG(753, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(754, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1061 "Zend/zend_language_scanner.l" { return T_ENDWHILE; } #line 6922 "Zend/zend_language_scanner.c" yy755: YYDEBUG(755, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy756; if (yych != 'i') goto yy186; yy756: YYDEBUG(756, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy757; if (yych != 't') goto yy186; yy757: YYDEBUG(757, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy758; if (yych != 'c') goto yy186; yy758: YYDEBUG(758, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy759; if (yych != 'h') goto yy186; yy759: YYDEBUG(759, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(760, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1105 "Zend/zend_language_scanner.l" { return T_ENDSWITCH; } #line 6955 "Zend/zend_language_scanner.c" yy761: YYDEBUG(761, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(762, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1049 "Zend/zend_language_scanner.l" { return T_ENDIF; } #line 6968 "Zend/zend_language_scanner.c" yy763: YYDEBUG(763, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy764; if (yych != 'r') goto yy186; yy764: YYDEBUG(764, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '@') { if (yych <= '/') goto yy765; if (yych <= '9') goto yy185; } else { if (yych == 'E') goto yy766; if (yych <= 'Z') goto yy185; } } else { if (yych <= 'd') { if (yych != '`') goto yy185; } else { if (yych <= 'e') goto yy766; if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy765: YYDEBUG(765, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1073 "Zend/zend_language_scanner.l" { return T_ENDFOR; } #line 7001 "Zend/zend_language_scanner.c" yy766: YYDEBUG(766, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy767; if (yych != 'a') goto yy186; yy767: YYDEBUG(767, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy768; if (yych != 'c') goto yy186; yy768: YYDEBUG(768, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy769; if (yych != 'h') goto yy186; yy769: YYDEBUG(769, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(770, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1081 "Zend/zend_language_scanner.l" { return T_ENDFOREACH; } #line 7029 "Zend/zend_language_scanner.c" yy771: YYDEBUG(771, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy772; if (yych != 'c') goto yy186; yy772: YYDEBUG(772, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy773; if (yych != 'l') goto yy186; yy773: YYDEBUG(773, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy774; if (yych != 'a') goto yy186; yy774: YYDEBUG(774, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy775; if (yych != 'r') goto yy186; yy775: YYDEBUG(775, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy776; if (yych != 'e') goto yy186; yy776: YYDEBUG(776, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(777, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1089 "Zend/zend_language_scanner.l" { return T_ENDDECLARE; } #line 7067 "Zend/zend_language_scanner.c" yy778: YYDEBUG(778, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy779; if (yych != 't') goto yy186; yy779: YYDEBUG(779, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy780; if (yych != 'y') goto yy186; yy780: YYDEBUG(780, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(781, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1275 "Zend/zend_language_scanner.l" { return T_EMPTY; } #line 7090 "Zend/zend_language_scanner.c" yy782: YYDEBUG(782, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy783; if (yych != 'e') goto yy186; yy783: YYDEBUG(783, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '@') { if (yych <= '/') goto yy784; if (yych <= '9') goto yy185; } else { if (yych == 'I') goto yy785; if (yych <= 'Z') goto yy185; } } else { if (yych <= 'h') { if (yych != '`') goto yy185; } else { if (yych <= 'i') goto yy785; if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy784: YYDEBUG(784, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1053 "Zend/zend_language_scanner.l" { return T_ELSE; } #line 7123 "Zend/zend_language_scanner.c" yy785: YYDEBUG(785, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy786; if (yych != 'f') goto yy186; yy786: YYDEBUG(786, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(787, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1045 "Zend/zend_language_scanner.l" { return T_ELSEIF; } #line 7141 "Zend/zend_language_scanner.c" yy788: YYDEBUG(788, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy789; if (yych != 'o') goto yy186; yy789: YYDEBUG(789, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(790, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1129 "Zend/zend_language_scanner.l" { return T_ECHO; } #line 7159 "Zend/zend_language_scanner.c" } /* *********************************** */ yyc_ST_LOOKING_FOR_PROPERTY: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 0, 0, 0, 0, 0, 0, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 0, 0, 0, 0, 64, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 0, 0, 0, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, }; YYDEBUG(791, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych <= '-') { if (yych <= '\r') { if (yych <= 0x08) goto yy799; if (yych <= '\n') goto yy793; if (yych <= '\f') goto yy799; } else { if (yych == ' ') goto yy793; if (yych <= ',') goto yy799; goto yy795; } } else { if (yych <= '_') { if (yych <= '@') goto yy799; if (yych <= 'Z') goto yy797; if (yych <= '^') goto yy799; goto yy797; } else { if (yych <= '`') goto yy799; if (yych <= 'z') goto yy797; if (yych <= '~') goto yy799; goto yy797; } } yy793: YYDEBUG(793, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy805; yy794: YYDEBUG(794, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1162 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; HANDLE_NEWLINES(yytext, yyleng); return T_WHITESPACE; } #line 7240 "Zend/zend_language_scanner.c" yy795: YYDEBUG(795, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '>') goto yy802; yy796: YYDEBUG(796, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1181 "Zend/zend_language_scanner.l" { yyless(0); yy_pop_state(TSRMLS_C); goto restart; } #line 7254 "Zend/zend_language_scanner.c" yy797: YYDEBUG(797, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy801; yy798: YYDEBUG(798, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1174 "Zend/zend_language_scanner.l" { yy_pop_state(TSRMLS_C); zend_copy_value(zendlval, yytext, yyleng); zendlval->type = IS_STRING; return T_STRING; } #line 7270 "Zend/zend_language_scanner.c" yy799: YYDEBUG(799, *YYCURSOR); yych = *++YYCURSOR; goto yy796; yy800: YYDEBUG(800, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy801: YYDEBUG(801, *YYCURSOR); if (yybm[0+yych] & 64) { goto yy800; } goto yy798; yy802: YYDEBUG(802, *YYCURSOR); ++YYCURSOR; YYDEBUG(803, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1170 "Zend/zend_language_scanner.l" { return T_OBJECT_OPERATOR; } #line 7295 "Zend/zend_language_scanner.c" yy804: YYDEBUG(804, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy805: YYDEBUG(805, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy804; } goto yy794; } /* *********************************** */ yyc_ST_LOOKING_FOR_VARNAME: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; YYDEBUG(806, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy810; if (yych <= 'Z') goto yy808; if (yych <= '^') goto yy810; } else { if (yych <= '`') goto yy810; if (yych <= 'z') goto yy808; if (yych <= '~') goto yy810; } yy808: YYDEBUG(808, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy813; yy809: YYDEBUG(809, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1457 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, yytext, yyleng); zendlval->type = IS_STRING; yy_pop_state(TSRMLS_C); yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); return T_STRING_VARNAME; } #line 7373 "Zend/zend_language_scanner.c" yy810: YYDEBUG(810, *YYCURSOR); ++YYCURSOR; YYDEBUG(811, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1466 "Zend/zend_language_scanner.l" { yyless(0); yy_pop_state(TSRMLS_C); yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); goto restart; } #line 7386 "Zend/zend_language_scanner.c" yy812: YYDEBUG(812, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy813: YYDEBUG(813, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy812; } goto yy809; } /* *********************************** */ yyc_ST_NOWDOC: YYDEBUG(814, *YYCURSOR); YYFILL(1); yych = *YYCURSOR; YYDEBUG(816, *YYCURSOR); ++YYCURSOR; YYDEBUG(817, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2344 "Zend/zend_language_scanner.l" { int newline = 0; if (YYCURSOR > YYLIMIT) { return 0; } YYCURSOR--; while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '\r': if (*YYCURSOR == '\n') { YYCURSOR++; } /* fall through */ case '\n': /* Check for ending label on the next line */ if (IS_LABEL_START(*YYCURSOR) && CG(heredoc_len) < YYLIMIT - YYCURSOR && !memcmp(YYCURSOR, CG(heredoc), CG(heredoc_len))) { YYCTYPE *end = YYCURSOR + CG(heredoc_len); if (*end == ';') { end++; } if (*end == '\n' || *end == '\r') { /* newline before label will be subtracted from returned text, but * yyleng/yytext will include it, for zend_highlight/strip, tokenizer, etc. */ if (YYCURSOR[-2] == '\r' && YYCURSOR[-1] == '\n') { newline = 2; /* Windows newline */ } else { newline = 1; } CG(increment_lineno) = 1; /* For newline before label */ BEGIN(ST_END_HEREDOC); goto nowdoc_scan_done; } } /* fall through */ default: continue; } } nowdoc_scan_done: yyleng = YYCURSOR - SCNG(yy_text); zend_copy_value(zendlval, yytext, yyleng - newline); zendlval->type = IS_STRING; HANDLE_NEWLINES(yytext, yyleng - newline); return T_ENCAPSED_AND_WHITESPACE; } #line 7463 "Zend/zend_language_scanner.c" /* *********************************** */ yyc_ST_VAR_OFFSET: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 240, 240, 112, 112, 112, 112, 112, 112, 112, 112, 0, 0, 0, 0, 0, 0, 0, 80, 80, 80, 80, 80, 80, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 16, 0, 80, 80, 80, 80, 80, 80, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, }; YYDEBUG(818, *YYCURSOR); YYFILL(3); yych = *YYCURSOR; if (yych <= '/') { if (yych <= ' ') { if (yych <= '\f') { if (yych <= 0x08) goto yy832; if (yych <= '\n') goto yy828; goto yy832; } else { if (yych <= '\r') goto yy828; if (yych <= 0x1F) goto yy832; goto yy828; } } else { if (yych <= '$') { if (yych <= '"') goto yy827; if (yych <= '#') goto yy828; goto yy823; } else { if (yych == '\'') goto yy828; goto yy827; } } } else { if (yych <= '\\') { if (yych <= '@') { if (yych <= '0') goto yy820; if (yych <= '9') goto yy822; goto yy827; } else { if (yych <= 'Z') goto yy830; if (yych <= '[') goto yy827; goto yy828; } } else { if (yych <= '_') { if (yych <= ']') goto yy825; if (yych <= '^') goto yy827; goto yy830; } else { if (yych <= '`') goto yy827; if (yych <= 'z') goto yy830; if (yych <= '~') goto yy827; goto yy830; } } } yy820: YYDEBUG(820, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'W') { if (yych <= '9') { if (yych >= '0') goto yy844; } else { if (yych == 'B') goto yy841; } } else { if (yych <= 'b') { if (yych <= 'X') goto yy843; if (yych >= 'b') goto yy841; } else { if (yych == 'x') goto yy843; } } yy821: YYDEBUG(821, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1540 "Zend/zend_language_scanner.l" { /* Offset could be treated as a long */ if (yyleng < MAX_LENGTH_OF_LONG - 1 || (yyleng == MAX_LENGTH_OF_LONG - 1 && strcmp(yytext, long_min_digits) < 0)) { zendlval->value.lval = strtol(yytext, NULL, 10); zendlval->type = IS_LONG; } else { zendlval->value.str.val = (char *)estrndup(yytext, yyleng); zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; } return T_NUM_STRING; } #line 7582 "Zend/zend_language_scanner.c" yy822: YYDEBUG(822, *YYCURSOR); yych = *++YYCURSOR; goto yy840; yy823: YYDEBUG(823, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '_') { if (yych <= '@') goto yy824; if (yych <= 'Z') goto yy836; if (yych >= '_') goto yy836; } else { if (yych <= '`') goto yy824; if (yych <= 'z') goto yy836; if (yych >= 0x7F) goto yy836; } yy824: YYDEBUG(824, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1872 "Zend/zend_language_scanner.l" { /* Only '[' can be valid, but returning other tokens will allow a more explicit parse error */ return yytext[0]; } #line 7607 "Zend/zend_language_scanner.c" yy825: YYDEBUG(825, *YYCURSOR); ++YYCURSOR; YYDEBUG(826, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1867 "Zend/zend_language_scanner.l" { yy_pop_state(TSRMLS_C); return ']'; } #line 7618 "Zend/zend_language_scanner.c" yy827: YYDEBUG(827, *YYCURSOR); yych = *++YYCURSOR; goto yy824; yy828: YYDEBUG(828, *YYCURSOR); ++YYCURSOR; YYDEBUG(829, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1877 "Zend/zend_language_scanner.l" { /* Invalid rule to return a more explicit parse error with proper line number */ yyless(0); yy_pop_state(TSRMLS_C); return T_ENCAPSED_AND_WHITESPACE; } #line 7635 "Zend/zend_language_scanner.c" yy830: YYDEBUG(830, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy835; yy831: YYDEBUG(831, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1884 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, yytext, yyleng); zendlval->type = IS_STRING; return T_STRING; } #line 7650 "Zend/zend_language_scanner.c" yy832: YYDEBUG(832, *YYCURSOR); ++YYCURSOR; YYDEBUG(833, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2400 "Zend/zend_language_scanner.l" { if (YYCURSOR > YYLIMIT) { return 0; } zend_error(E_COMPILE_WARNING,"Unexpected character in input: '%c' (ASCII=%d) state=%d", yytext[0], yytext[0], YYSTATE); goto restart; } #line 7665 "Zend/zend_language_scanner.c" yy834: YYDEBUG(834, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy835: YYDEBUG(835, *YYCURSOR); if (yybm[0+yych] & 16) { goto yy834; } goto yy831; yy836: YYDEBUG(836, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(837, *YYCURSOR); if (yych <= '^') { if (yych <= '9') { if (yych >= '0') goto yy836; } else { if (yych <= '@') goto yy838; if (yych <= 'Z') goto yy836; } } else { if (yych <= '`') { if (yych <= '_') goto yy836; } else { if (yych <= 'z') goto yy836; if (yych >= 0x7F) goto yy836; } } yy838: YYDEBUG(838, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1861 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 7707 "Zend/zend_language_scanner.c" yy839: YYDEBUG(839, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy840: YYDEBUG(840, *YYCURSOR); if (yybm[0+yych] & 32) { goto yy839; } goto yy821; yy841: YYDEBUG(841, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 128) { goto yy849; } yy842: YYDEBUG(842, *YYCURSOR); YYCURSOR = YYMARKER; goto yy821; yy843: YYDEBUG(843, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 64) { goto yy847; } goto yy842; yy844: YYDEBUG(844, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(845, *YYCURSOR); if (yych <= '/') goto yy846; if (yych <= '9') goto yy844; yy846: YYDEBUG(846, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1552 "Zend/zend_language_scanner.l" { /* Offset must be treated as a string */ zendlval->value.str.val = (char *)estrndup(yytext, yyleng); zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; return T_NUM_STRING; } #line 7754 "Zend/zend_language_scanner.c" yy847: YYDEBUG(847, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(848, *YYCURSOR); if (yybm[0+yych] & 64) { goto yy847; } goto yy846; yy849: YYDEBUG(849, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(850, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy849; } goto yy846; } } #line 2409 "Zend/zend_language_scanner.l" }
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2012-02-20-0cb26060af-eefefddc0e.c
manybugs_data_39
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <zend_language_parser.h> #include "zend.h" #include "zend_compile.h" #include "zend_constants.h" #include "zend_llist.h" #include "zend_API.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "zend_multibyte.h" #include "zend_language_scanner.h" #define CONSTANT_EX(op_array, op) \ (op_array)->literals[op].constant #define CONSTANT(op) \ CONSTANT_EX(CG(active_op_array), op) #define SET_NODE(target, src) do { \ target ## _type = (src)->op_type; \ if ((src)->op_type == IS_CONST) { \ target.constant = zend_add_literal(CG(active_op_array), &(src)->u.constant TSRMLS_CC); \ } else { \ target = (src)->u.op; \ } \ } while (0) #define GET_NODE(target, src) do { \ (target)->op_type = src ## _type; \ if ((target)->op_type == IS_CONST) { \ (target)->u.constant = CONSTANT(src.constant); \ } else { \ (target)->u.op = src; \ (target)->EA = 0; \ } \ } while (0) #define COPY_NODE(target, src) do { \ target ## _type = src ## _type; \ target = src; \ } while (0) #define CALCULATE_LITERAL_HASH(num) do { \ if (IS_INTERNED(Z_STRVAL(CONSTANT(num)))) { \ Z_HASH_P(&CONSTANT(num)) = INTERNED_HASH(Z_STRVAL(CONSTANT(num))); \ } else { \ Z_HASH_P(&CONSTANT(num)) = zend_hash_func(Z_STRVAL(CONSTANT(num)), Z_STRLEN(CONSTANT(num))+1); \ } \ } while (0) #define GET_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot++; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ } \ } while (0) #define POLYMORPHIC_CACHE_SLOT_SIZE 2 #define GET_POLYMORPHIC_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot; \ CG(active_op_array)->last_cache_slot += POLYMORPHIC_CACHE_SLOT_SIZE; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 2] = NULL; \ } \ } while (0) #define FREE_POLYMORPHIC_CACHE_SLOT(literal) do { \ if (CG(active_op_array)->literals[literal].cache_slot == \ CG(active_op_array)->last_cache_slot - POLYMORPHIC_CACHE_SLOT_SIZE) { \ CG(active_op_array)->literals[literal].cache_slot = -1; \ CG(active_op_array)->last_cache_slot -= POLYMORPHIC_CACHE_SLOT_SIZE; \ } \ } while (0) ZEND_API zend_op_array *(*zend_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); ZEND_API zend_op_array *(*zend_compile_string)(zval *source_string, char *filename TSRMLS_DC); #ifndef ZTS ZEND_API zend_compiler_globals compiler_globals; ZEND_API zend_executor_globals executor_globals; #endif static void zend_duplicate_property_info(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = estrndup(property_info->name, property_info->name_length); } if (property_info->doc_comment) { property_info->doc_comment = estrndup(property_info->doc_comment, property_info->doc_comment_len); } } /* }}} */ static void zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = zend_strndup(property_info->name, property_info->name_length); } } /* }}} */ static void zend_destroy_property_info(zend_property_info *property_info) /* {{{ */ { str_efree(property_info->name); if (property_info->doc_comment) { efree((char*)property_info->doc_comment); } } /* }}} */ static void zend_destroy_property_info_internal(zend_property_info *property_info) /* {{{ */ { str_free((char*)property_info->name); } /* }}} */ static void build_runtime_defined_function_key(zval *result, const char *name, int name_length TSRMLS_DC) /* {{{ */ { char char_pos_buf[32]; uint char_pos_len; const char *filename; char_pos_len = zend_sprintf(char_pos_buf, "%p", LANG_SCNG(yy_text)); if (CG(active_op_array)->filename) { filename = CG(active_op_array)->filename; } else { filename = "-"; } /* NULL, name length, filename length, last accepting char position length */ result->value.str.len = 1+name_length+strlen(filename)+char_pos_len; /* must be binary safe */ result->value.str.val = (char *) safe_emalloc(result->value.str.len, 1, 1); result->value.str.val[0] = '\0'; sprintf(result->value.str.val+1, "%s%s%s", name, filename, char_pos_buf); result->type = IS_STRING; Z_SET_REFCOUNT_P(result, 1); } /* }}} */ static void init_compiler_declarables(TSRMLS_D) /* {{{ */ { Z_TYPE(CG(declarables).ticks) = IS_LONG; Z_LVAL(CG(declarables).ticks) = 0; } /* }}} */ void zend_init_compiler_context(TSRMLS_D) /* {{{ */ { CG(context).opcodes_size = (CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) ? INITIAL_INTERACTIVE_OP_ARRAY_SIZE : INITIAL_OP_ARRAY_SIZE; CG(context).vars_size = 0; CG(context).literals_size = 0; CG(context).current_brk_cont = -1; CG(context).backpatch_count = 0; CG(context).labels = NULL; } /* }}} */ void zend_init_compiler_data_structures(TSRMLS_D) /* {{{ */ { zend_stack_init(&CG(bp_stack)); zend_stack_init(&CG(function_call_stack)); zend_stack_init(&CG(switch_cond_stack)); zend_stack_init(&CG(foreach_copy_stack)); zend_stack_init(&CG(object_stack)); zend_stack_init(&CG(declare_stack)); CG(active_class_entry) = NULL; zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_stack_init(&CG(list_stack)); CG(in_compilation) = 0; CG(start_lineno) = 0; CG(current_namespace) = NULL; CG(in_namespace) = 0; CG(has_bracketed_namespaces) = 0; CG(current_import) = NULL; init_compiler_declarables(TSRMLS_C); zend_stack_init(&CG(context_stack)); CG(encoding_declared) = 0; } /* }}} */ ZEND_API void file_handle_dtor(zend_file_handle *fh) /* {{{ */ { TSRMLS_FETCH(); zend_file_handle_dtor(fh TSRMLS_CC); } /* }}} */ void init_compiler(TSRMLS_D) /* {{{ */ { CG(active_op_array) = NULL; zend_init_compiler_data_structures(TSRMLS_C); zend_init_rsrc_list(TSRMLS_C); zend_hash_init(&CG(filenames_table), 5, NULL, (dtor_func_t) free_estring, 0); zend_llist_init(&CG(open_files), sizeof(zend_file_handle), (void (*)(void *)) file_handle_dtor, 0); CG(unclean_shutdown) = 0; } /* }}} */ void shutdown_compiler(TSRMLS_D) /* {{{ */ { zend_stack_destroy(&CG(bp_stack)); zend_stack_destroy(&CG(function_call_stack)); zend_stack_destroy(&CG(switch_cond_stack)); zend_stack_destroy(&CG(foreach_copy_stack)); zend_stack_destroy(&CG(object_stack)); zend_stack_destroy(&CG(declare_stack)); zend_stack_destroy(&CG(list_stack)); zend_hash_destroy(&CG(filenames_table)); zend_llist_destroy(&CG(open_files)); zend_stack_destroy(&CG(context_stack)); } /* }}} */ ZEND_API char *zend_set_compiled_filename(const char *new_compiled_filename TSRMLS_DC) /* {{{ */ { char **pp, *p; int length = strlen(new_compiled_filename); if (zend_hash_find(&CG(filenames_table), new_compiled_filename, length+1, (void **) &pp) == SUCCESS) { CG(compiled_filename) = *pp; return *pp; } p = estrndup(new_compiled_filename, length); zend_hash_update(&CG(filenames_table), new_compiled_filename, length+1, &p, sizeof(char *), (void **) &pp); CG(compiled_filename) = p; return p; } /* }}} */ ZEND_API void zend_restore_compiled_filename(char *original_compiled_filename TSRMLS_DC) /* {{{ */ { CG(compiled_filename) = original_compiled_filename; } /* }}} */ ZEND_API char *zend_get_compiled_filename(TSRMLS_D) /* {{{ */ { return CG(compiled_filename); } /* }}} */ ZEND_API int zend_get_compiled_lineno(TSRMLS_D) /* {{{ */ { return CG(zend_lineno); } /* }}} */ ZEND_API zend_bool zend_is_compiling(TSRMLS_D) /* {{{ */ { return CG(in_compilation); } /* }}} */ static zend_uint get_temporary_variable(zend_op_array *op_array) /* {{{ */ { return (op_array->T)++ * ZEND_MM_ALIGNED_SIZE(sizeof(temp_variable)); } /* }}} */ static int lookup_cv(zend_op_array *op_array, char* name, int name_len, ulong hash TSRMLS_DC) /* {{{ */ { int i = 0; ulong hash_value = hash ? hash : zend_inline_hash_func(name, name_len+1); while (i < op_array->last_var) { if (op_array->vars[i].name == name || (op_array->vars[i].hash_value == hash_value && op_array->vars[i].name_len == name_len && memcmp(op_array->vars[i].name, name, name_len) == 0)) { str_efree(name); return i; } i++; } i = op_array->last_var; op_array->last_var++; if (op_array->last_var > CG(context).vars_size) { CG(context).vars_size += 16; /* FIXME */ op_array->vars = erealloc(op_array->vars, CG(context).vars_size * sizeof(zend_compiled_variable)); } op_array->vars[i].name = zend_new_interned_string(name, name_len + 1, 1 TSRMLS_CC); op_array->vars[i].name_len = name_len; op_array->vars[i].hash_value = hash_value; return i; } /* }}} */ void zend_del_literal(zend_op_array *op_array, int n) /* {{{ */ { zval_dtor(&CONSTANT_EX(op_array, n)); if (n + 1 == op_array->last_literal) { op_array->last_literal--; } else { Z_TYPE(CONSTANT_EX(op_array, n)) = IS_NULL; } } /* }}} */ /* Common part of zend_add_literal and zend_append_individual_literal */ static inline void zend_insert_literal(zend_op_array *op_array, const zval *zv, int literal_position TSRMLS_DC) /* {{{ */ { if (Z_TYPE_P(zv) == IS_STRING || Z_TYPE_P(zv) == IS_CONSTANT) { zval *z = (zval*)zv; Z_STRVAL_P(z) = (char*)zend_new_interned_string(Z_STRVAL_P(zv), Z_STRLEN_P(zv) + 1, 1 TSRMLS_CC); } CONSTANT_EX(op_array, literal_position) = *zv; Z_SET_REFCOUNT(CONSTANT_EX(op_array, literal_position), 2); Z_SET_ISREF(CONSTANT_EX(op_array, literal_position)); op_array->literals[literal_position].hash_value = 0; op_array->literals[literal_position].cache_slot = -1; } /* }}} */ /* Is used while compiling a function, using the context to keep track of an approximate size to avoid to relocate to often. Literals are truncated to actual size in the second compiler pass (pass_two()). */ int zend_add_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; if (i >= CG(context).literals_size) { while (i >= CG(context).literals_size) { CG(context).literals_size += 16; /* FIXME */ } op_array->literals = (zend_literal*)erealloc(op_array->literals, CG(context).literals_size * sizeof(zend_literal)); } zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ /* Is used after normal compilation to append an additional literal. Allocation is done precisely here. */ int zend_append_individual_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; op_array->literals = (zend_literal*)erealloc(op_array->literals, (i + 1) * sizeof(zend_literal)); zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ int zend_add_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_ns_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; const char *ns_separator; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); ns_separator = (const char*)zend_memrchr(Z_STRVAL_P(zv), '\\', Z_STRLEN_P(zv)) + 1; lc_len = Z_STRLEN_P(zv) - (ns_separator - Z_STRVAL_P(zv)); lc_name = zend_str_tolower_dup(ns_separator, lc_len); ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_class_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } if (Z_STRVAL_P(zv)[0] == '\\') { lc_len = Z_STRLEN_P(zv) - 1; lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv) + 1, lc_len); } else { lc_len = Z_STRLEN_P(zv); lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), lc_len); } ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); GET_CACHE_SLOT(ret); return ret; } /* }}} */ int zend_add_const_name_literal(zend_op_array *op_array, const zval *zv, int unqualified TSRMLS_DC) /* {{{ */ { int ret, tmp_literal; char *name, *tmp_name; const char *ns_separator; int name_len, ns_len; zval c; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } /* skip leading '\\' */ if (Z_STRVAL_P(zv)[0] == '\\') { name_len = Z_STRLEN_P(zv) - 1; name = Z_STRVAL_P(zv) + 1; } else { name_len = Z_STRLEN_P(zv); name = Z_STRVAL_P(zv); } ns_separator = zend_memrchr(name, '\\', name_len); if (ns_separator) { ns_len = ns_separator - name; } else { ns_len = 0; } if (ns_len) { /* lowercased namespace name & original constant name */ tmp_name = estrndup(name, name_len); zend_str_tolower(tmp_name, ns_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased namespace name & lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); } if (ns_len) { if (!unqualified) { return ret; } ns_len++; name += ns_len; name_len -= ns_len; } /* original constant name */ tmp_name = estrndup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); return ret; } /* }}} */ #define LITERAL_STRINGL(op, str, len, copy) do { \ zval _c; \ ZVAL_STRINGL(&_c, str, len, copy); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG(op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG_EX(op_array, op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(op_array, &_c TSRMLS_CC); \ } while (0) #define LITERAL_NULL(op) do { \ zval _c; \ INIT_ZVAL( _c); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) static inline zend_bool zend_is_function_or_method_call(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; return ((type & ZEND_PARSED_METHOD_CALL) || (type == ZEND_PARSED_FUNCTION_CALL)); } /* }}} */ void zend_do_binary_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_unary_op(zend_uchar op, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); GET_NODE(result, opline->result); SET_UNUSED(opline->op2); } /* }}} */ #define MAKE_NOP(opline) { opline->opcode = ZEND_NOP; memset(&opline->result,0,sizeof(opline->result)); memset(&opline->op1,0,sizeof(opline->op1)); memset(&opline->op2,0,sizeof(opline->op2)); opline->result_type=opline->op1_type=opline->op2_type=IS_UNUSED; } static void zend_do_op_data(zend_op *data_op, const znode *value TSRMLS_DC) /* {{{ */ { data_op->opcode = ZEND_OP_DATA; SET_NODE(data_op->op1, value); SET_UNUSED(data_op->op2); } /* }}} */ void zend_do_binary_assign_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; switch (last_op->opcode) { case ZEND_FETCH_OBJ_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, op2 TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; case ZEND_FETCH_DIM_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_DIM; zend_do_op_data(opline, op2 TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result,last_op->result); return; default: break; } } opline->opcode = op; SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void fetch_simple_variable_ex(znode *result, znode *varname, int bp, zend_uchar op TSRMLS_DC) /* {{{ */ { zend_op opline; zend_op *opline_ptr; zend_llist *fetch_list_ptr; if (varname->op_type == IS_CONST) { ulong hash = 0; if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } else if (IS_INTERNED(Z_STRVAL(varname->u.constant))) { hash = INTERNED_HASH(Z_STRVAL(varname->u.constant)); } if (!zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC) && !(varname->u.constant.value.str.len == (sizeof("this")-1) && !memcmp(varname->u.constant.value.str.val, "this", sizeof("this"))) && (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE)) { result->op_type = IS_CV; result->u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC); varname->u.constant.value.str.val = (char*)CG(active_op_array)->vars[result->u.op.var].name; result->EA = 0; return; } } if (bp) { opline_ptr = &opline; init_op(opline_ptr TSRMLS_CC); } else { opline_ptr = get_next_op(CG(active_op_array) TSRMLS_CC); } opline_ptr->opcode = op; opline_ptr->result_type = IS_VAR; opline_ptr->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline_ptr->op1, varname); GET_NODE(result, opline_ptr->result); SET_UNUSED(opline_ptr->op2); opline_ptr->extended_value = ZEND_FETCH_LOCAL; if (varname->op_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline_ptr->op1.constant); if (zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC)) { opline_ptr->extended_value = ZEND_FETCH_GLOBAL; } } if (bp) { zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); zend_llist_add_element(fetch_list_ptr, opline_ptr); } } /* }}} */ void fetch_simple_variable(znode *result, znode *varname, int bp TSRMLS_DC) /* {{{ */ { /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ fetch_simple_variable_ex(result, varname, bp, ZEND_FETCH_W TSRMLS_CC); } /* }}} */ void zend_do_fetch_static_member(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { znode class_node; zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline_ptr; zend_op opline; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); } zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (result->op_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[result->u.op.var].name), CG(active_op_array)->vars[result->u.op.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } GET_NODE(result,opline.result); opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; opline_ptr = &opline; zend_llist_add_element(fetch_list_ptr, &opline); } else { le = fetch_list_ptr->head; opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode != ZEND_FETCH_W && opline_ptr->op1_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[opline_ptr->op1.var].name), CG(active_op_array)->vars[opline_ptr->op1.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; COPY_NODE(opline_ptr->op1, opline.result); zend_llist_prepend_element(fetch_list_ptr, &opline); } else { if (opline_ptr->op1_type == IS_CONST) { GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op1.constant); } if (class_node.op_type == IS_CONST) { opline_ptr->op2_type = IS_CONST; opline_ptr->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline_ptr->op2, &class_node); } opline_ptr->extended_value |= ZEND_FETCH_STATIC_MEMBER; } } } /* }}} */ void fetch_array_begin(znode *result, znode *varname, znode *first_dim TSRMLS_DC) /* {{{ */ { fetch_simple_variable(result, varname, 1 TSRMLS_CC); fetch_array_dim(result, result, first_dim TSRMLS_CC); } /* }}} */ void fetch_array_dim(znode *result, const znode *parent, const znode *dim TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (zend_is_function_or_method_call(parent)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, parent); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_DIM_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, parent); SET_NODE(opline.op2, dim); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline.op2.constant)), Z_STRLEN(CONSTANT(opline.op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline.op2.constant)); ZVAL_LONG(&CONSTANT(opline.op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline.op2.constant); } } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void fetch_string_offset(znode *result, const znode *parent, const znode *offset TSRMLS_DC) /* {{{ */ { fetch_array_dim(result, parent, offset TSRMLS_CC); } /* }}} */ void zend_do_print(znode *result, const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->opcode = ZEND_PRINT; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_echo(const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ECHO; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_abstract_method(const znode *function_name, znode *modifiers, const znode *body TSRMLS_DC) /* {{{ */ { char *method_type; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { Z_LVAL(modifiers->u.constant) |= ZEND_ACC_ABSTRACT; method_type = "Interface"; } else { method_type = "Abstract"; } if (modifiers->u.constant.value.lval & ZEND_ACC_ABSTRACT) { if(modifiers->u.constant.value.lval & ZEND_ACC_PRIVATE) { zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot be declared private", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } if (Z_LVAL(body->u.constant) == ZEND_ACC_ABSTRACT) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_RAISE_ABSTRACT_ERROR; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } else { /* we had code in the function body */ zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot contain body", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } else { if (body->u.constant.value.lval == ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Non-abstract method %s::%s() must contain body", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } } /* }}} */ static zend_bool opline_is_fetch_this(const zend_op *opline TSRMLS_DC) /* {{{ */ { if ((opline->opcode == ZEND_FETCH_W) && (opline->op1_type == IS_CONST) && (Z_TYPE(CONSTANT(opline->op1.constant)) == IS_STRING) && (Z_HASH_P(&CONSTANT(opline->op1.constant)) == THIS_HASHVAL) && (Z_STRLEN(CONSTANT(opline->op1.constant)) == (sizeof("this")-1)) && !memcmp(Z_STRVAL(CONSTANT(opline->op1.constant)), "this", sizeof("this"))) { return 1; } else { return 0; } } /* }}} */ void zend_do_assign(znode *result, znode *variable, znode *value TSRMLS_DC) /* {{{ */ { int last_op_number; zend_op *opline; if (value->op_type == IS_CV) { zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (fetch_list_ptr && fetch_list_ptr->head) { opline = (zend_op *)fetch_list_ptr->head->data; if (opline->opcode == ZEND_FETCH_DIM_W && opline->op1_type == IS_CV && opline->op1.var == value->u.op.var) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_R; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->op1_type = IS_CONST; LITERAL_STRINGL(opline->op1, CG(active_op_array)->vars[value->u.op.var].name, CG(active_op_array)->vars[value->u.op.var].name_len, 1); CALCULATE_LITERAL_HASH(opline->op1.constant); SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_LOCAL; GET_NODE(value, opline->result); } } } zend_do_end_variable_parse(variable, BP_VAR_W, 0 TSRMLS_CC); last_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (variable->op_type == IS_CV) { if (variable->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (variable->op_type == IS_VAR) { int n = 0; while (last_op_number - n > 0) { zend_op *last_op; last_op = &CG(active_op_array)->opcodes[last_op_number-n-1]; if (last_op->result_type == IS_VAR && last_op->result.var == variable->u.op.var) { if (last_op->opcode == ZEND_FETCH_OBJ_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, value TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (last_op->opcode == ZEND_FETCH_DIM_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ /* TBFixed: this can realloc opcodes, leaving last_op pointing wrong */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_DIM; zend_do_op_data(opline, value TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (opline_is_fetch_this(last_op TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } else { break; } } n++; } } opline->opcode = ZEND_ASSIGN; SET_NODE(opline->op1, variable); SET_NODE(opline->op2, value); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_assign_ref(znode *result, const znode *lvar, const znode *rvar TSRMLS_DC) /* {{{ */ { zend_op *opline; if (lvar->op_type == IS_CV) { if (lvar->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (lvar->op_type == IS_VAR) { int last_op_number = get_next_op_number(CG(active_op_array)); if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline_is_fetch_this(opline TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ASSIGN_REF; if (zend_is_function_or_method_call(rvar)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } else if (rvar->EA & ZEND_PARSED_NEW) { opline->extended_value = ZEND_RETURNS_NEW; } else { opline->extended_value = 0; } if (result) { opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } else { opline->result_type = IS_UNUSED | EXT_TYPE_UNUSED; } SET_NODE(opline->op1, lvar); SET_NODE(opline->op2, rvar); } /* }}} */ static inline void do_begin_loop(TSRMLS_D) /* {{{ */ { zend_brk_cont_element *brk_cont_element; int parent; parent = CG(context).current_brk_cont; CG(context).current_brk_cont = CG(active_op_array)->last_brk_cont; brk_cont_element = get_next_brk_cont_element(CG(active_op_array)); brk_cont_element->start = get_next_op_number(CG(active_op_array)); brk_cont_element->parent = parent; } /* }}} */ static inline void do_end_loop(int cont_addr, int has_loop_var TSRMLS_DC) /* {{{ */ { if (!has_loop_var) { /* The start fileld is used to free temporary variables in case of exceptions. * We won't try to free something of we don't have loop variable. */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].start = -1; } CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = cont_addr; CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; } /* }}} */ void zend_do_while_cond(const znode *expr, znode *close_bracket_token TSRMLS_DC) /* {{{ */ { int while_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, expr); close_bracket_token->u.op.opline_num = while_cond_op_number; SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_while_end(const znode *while_token, const znode *close_bracket_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* add unconditional jump */ opline->opcode = ZEND_JMP; opline->op1.opline_num = while_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* update while's conditional jmp */ CG(active_op_array)->opcodes[close_bracket_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); do_end_loop(while_token->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_cond(const znode *expr, znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { int for_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZNZ; SET_NODE(opline->op1, expr); /* the conditional expression */ second_semicolon_token->u.op.opline_num = for_cond_op_number; SET_UNUSED(opline->op2); } /* }}} */ void zend_do_for_before_statement(const znode *cond_start, const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = cond_start->u.op.opline_num; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_end(const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = second_semicolon_token->u.op.opline_num+1; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_end_loop(second_semicolon_token->u.op.opline_num+1, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_pre_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_PRE_INC)?ZEND_PRE_INC_OBJ:ZEND_PRE_DEC_OBJ; last_op->result_type = IS_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_post_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_POST_INC)?ZEND_POST_INC_OBJ:ZEND_POST_DEC_OBJ; last_op->result_type = IS_TMP_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_if_cond(const znode *cond, znode *closing_bracket_token TSRMLS_DC) /* {{{ */ { int if_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); closing_bracket_token->u.op.opline_num = if_cond_op_number; SET_UNUSED(opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_if_after_statement(const znode *closing_bracket_token, unsigned char initialize TSRMLS_DC) /* {{{ */ { int if_end_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; /* save for backpatching */ if (initialize) { zend_llist jmp_list; zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); } zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &if_end_op_number); CG(active_op_array)->opcodes[closing_bracket_token->u.op.opline_num].op2.opline_num = if_end_op_number+1; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_if_end(TSRMLS_D) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_llist *jmp_list_ptr; zend_llist_element *le; zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); for (le=jmp_list_ptr->head; le; le = le->next) { CG(active_op_array)->opcodes[*((int *) le->data)].op1.opline_num = next_op_number; } zend_llist_destroy(jmp_list_ptr); zend_stack_del_top(&CG(bp_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_check_writable_variable(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; if (type & ZEND_PARSED_METHOD_CALL) { zend_error(E_COMPILE_ERROR, "Can't use method return value in write context"); } if (type == ZEND_PARSED_FUNCTION_CALL) { zend_error(E_COMPILE_ERROR, "Can't use function return value in write context"); } } /* }}} */ void zend_do_begin_variable_parse(TSRMLS_D) /* {{{ */ { zend_llist fetch_list; zend_llist_init(&fetch_list, sizeof(zend_op), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &fetch_list, sizeof(zend_llist)); } /* }}} */ void zend_do_end_variable_parse(znode *variable, int type, int arg_offset TSRMLS_DC) /* {{{ */ { zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline = NULL; zend_op *opline_ptr; zend_uint this_var = -1; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); le = fetch_list_ptr->head; /* TODO: $foo->x->y->z = 1 should fetch "x" and "y" for R or RW, not just W */ if (le) { opline_ptr = (zend_op *)le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { /* convert to FETCH_?(this) into IS_CV */ if (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE) { this_var = opline_ptr->result.var; if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), Z_STRVAL(CONSTANT(opline_ptr->op1.constant)), Z_STRLEN(CONSTANT(opline_ptr->op1.constant)), Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC); Z_TYPE(CONSTANT(opline_ptr->op1.constant)) = IS_NULL; } else { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); } le = le->next; if (variable->op_type == IS_VAR && variable->u.op.var == this_var) { variable->op_type = IS_CV; variable->u.op.var = CG(active_op_array)->this_var; } } else if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } while (le) { opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode == ZEND_SEPARATE) { if (type != BP_VAR_R && type != BP_VAR_IS) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); } le = le->next; continue; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); if (opline->op1_type == IS_VAR && opline->op1.var == this_var) { opline->op1_type = IS_CV; opline->op1.var = CG(active_op_array)->this_var; } switch (type) { case BP_VAR_R: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode -= 3; break; case BP_VAR_W: break; case BP_VAR_RW: opline->opcode += 3; break; case BP_VAR_IS: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode += 6; /* 3+3 */ break; case BP_VAR_FUNC_ARG: opline->opcode += 9; /* 3+3+3 */ opline->extended_value |= arg_offset; break; case BP_VAR_UNSET: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for unsetting"); } opline->opcode += 12; /* 3+3+3+3 */ break; } le = le->next; } if (opline && type == BP_VAR_W && arg_offset) { opline->extended_value |= ZEND_FETCH_MAKE_REF; } } zend_llist_destroy(fetch_list_ptr); zend_stack_del_top(&CG(bp_stack)); } /* }}} */ void zend_do_add_string(znode *result, const znode *op1, znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline; if (Z_STRLEN(op2->u.constant) > 1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_STRING; } else if (Z_STRLEN(op2->u.constant) == 1) { int ch = *Z_STRVAL(op2->u.constant); /* Free memory and use ZEND_ADD_CHAR in case of 1 character strings */ efree(Z_STRVAL(op2->u.constant)); ZVAL_LONG(&op2->u.constant, ch); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_CHAR; } else { /* String can be empty after a variable at the end of a heredoc */ efree(Z_STRVAL(op2->u.constant)); return; } if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_add_variable(znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_VAR; if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_free(znode *op1 TSRMLS_DC) /* {{{ */ { if (op1->op_type==IS_TMP_VAR) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else if (op1->op_type==IS_VAR) { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; while (opline->opcode == ZEND_END_SILENCE || opline->opcode == ZEND_EXT_FCALL_END || opline->opcode == ZEND_OP_DATA) { opline--; } if (opline->result_type == IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_FETCH_R || opline->opcode == ZEND_FETCH_DIM_R || opline->opcode == ZEND_FETCH_OBJ_R || opline->opcode == ZEND_QM_ASSIGN_VAR) { /* It's very rare and useless case. It's better to use additional FREE opcode and simplify the FETCH handlers their selves */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else { opline->result_type |= EXT_TYPE_UNUSED; } } else { while (opline>CG(active_op_array)->opcodes) { if (opline->opcode == ZEND_FETCH_DIM_R && opline->op1_type == IS_VAR && opline->op1.var == op1->u.op.var) { /* This should the end of a list() construct * Mark its result as unused */ opline->extended_value = ZEND_FETCH_STANDARD; break; } else if (opline->result_type==IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_NEW) { opline->result_type |= EXT_TYPE_UNUSED; } break; } opline--; } } } else if (op1->op_type == IS_CONST) { zval_dtor(&op1->u.constant); } } /* }}} */ int zend_do_verify_access_types(const znode *current_access_type, const znode *new_modifier) /* {{{ */ { if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_PPP_MASK) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Multiple access type modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_ABSTRACT) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Multiple abstract modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_STATIC) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Multiple static modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_FINAL) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Multiple final modifiers are not allowed"); } if (((Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)) & (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) == (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Cannot use the final modifier on an abstract class member"); } return (Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)); } /* }}} */ void zend_do_begin_function_declaration(znode *function_token, znode *function_name, int is_method, int return_reference, znode *fn_flags_znode TSRMLS_DC) /* {{{ */ { zend_op_array op_array; char *name = function_name->u.constant.value.str.val; int name_len = function_name->u.constant.value.str.len; int function_begin_line = function_token->u.op.opline_num; zend_uint fn_flags; const char *lcname; zend_bool orig_interactive; ALLOCA_FLAG(use_heap) if (is_method) { if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((Z_LVAL(fn_flags_znode->u.constant) & ~(ZEND_ACC_STATIC|ZEND_ACC_PUBLIC))) { zend_error(E_COMPILE_ERROR, "Access type for interface method %s::%s() must be omitted", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } Z_LVAL(fn_flags_znode->u.constant) |= ZEND_ACC_ABSTRACT; /* propagates to the rest of the parser */ } fn_flags = Z_LVAL(fn_flags_znode->u.constant); /* must be done *after* the above check */ } else { fn_flags = 0; } if ((fn_flags & ZEND_ACC_STATIC) && (fn_flags & ZEND_ACC_ABSTRACT) && !(CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_STRICT, "Static function %s%s%s() should not be abstract", is_method ? CG(active_class_entry)->name : "", is_method ? "::" : "", Z_STRVAL(function_name->u.constant)); } function_token->u.op_array = CG(active_op_array); orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(&op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; op_array.function_name = name; if (return_reference) { op_array.fn_flags |= ZEND_ACC_RETURN_REFERENCE; } op_array.fn_flags |= fn_flags; op_array.scope = is_method?CG(active_class_entry):NULL; op_array.prototype = NULL; op_array.line_start = zend_get_compiled_lineno(TSRMLS_C); if (is_method) { int result; lcname = zend_new_interned_string(zend_str_tolower_dup(name, name_len), name_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lcname)) { result = zend_hash_quick_add(&CG(active_class_entry)->function_table, lcname, name_len+1, INTERNED_HASH(lcname), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } else { result = zend_hash_add(&CG(active_class_entry)->function_table, lcname, name_len+1, &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } if (result == FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::%s()", CG(active_class_entry)->name, name); } zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); if (fn_flags & ZEND_ACC_ABSTRACT) { CG(active_class_entry)->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (!(fn_flags & ZEND_ACC_PPP_MASK)) { fn_flags |= ZEND_ACC_PUBLIC; } if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } } } else { char *class_lcname; class_lcname = do_alloca(CG(active_class_entry)->name_length + 1, use_heap); zend_str_tolower_copy(class_lcname, CG(active_class_entry)->name, CG(active_class_entry)->name_length); /* Improve after RC: cache the lowercase class name */ if ((CG(active_class_entry)->name_length == name_len) && ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT) && (!memcmp(class_lcname, lcname, name_len))) { if (!CG(active_class_entry)->constructor) { CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } } else if ((name_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)))) { if (CG(active_class_entry)->constructor) { zend_error(E_STRICT, "Redefining already defined constructor for class %s", CG(active_class_entry)->name); } CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1))) { CG(active_class_entry)->destructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1))) { CG(active_class_entry)->clone = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } CG(active_class_entry)->__call = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } CG(active_class_entry)->__callstatic = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } CG(active_class_entry)->__get = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } CG(active_class_entry)->__set = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } CG(active_class_entry)->__unset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } CG(active_class_entry)->__isset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } CG(active_class_entry)->__tostring = (zend_function *) CG(active_op_array); } else if (!(fn_flags & ZEND_ACC_STATIC)) { CG(active_op_array)->fn_flags |= ZEND_ACC_ALLOW_STATIC; } free_alloca(class_lcname, use_heap); } str_efree(lcname); } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zval key; if (CG(current_namespace)) { /* Prefix function name with current namespcae name */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, function_name TSRMLS_CC); op_array.function_name = Z_STRVAL(tmp.u.constant); name_len = Z_STRLEN(tmp.u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), name_len); } else { lcname = zend_str_tolower_dup(name, name_len); } opline->opcode = ZEND_DECLARE_FUNCTION; opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, name_len TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; LITERAL_STRINGL(opline->op2, lcname, name_len, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); opline->extended_value = ZEND_DECLARE_FUNCTION; zend_hash_quick_update(CG(function_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); } if (CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_NOP; opline->lineno = function_begin_line; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } { /* Push a seperator to the switch and foreach stacks */ zend_switch_entry switch_entry; switch_entry.cond.op_type = IS_UNUSED; switch_entry.default_case = 0; switch_entry.control_var = 0; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); { /* Foreach stack separator */ zend_op dummy_opline; dummy_opline.result_type = IS_UNUSED; dummy_opline.op1_type = IS_UNUSED; zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); } } if (CG(doc_comment)) { CG(active_op_array)->doc_comment = CG(doc_comment); CG(active_op_array)->doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_begin_lambda_function_declaration(znode *result, znode *function_token, int return_reference, int is_static TSRMLS_DC) /* {{{ */ { znode function_name; zend_op_array *current_op_array = CG(active_op_array); int current_op_number = get_next_op_number(CG(active_op_array)); zend_op *current_op; function_name.op_type = IS_CONST; ZVAL_STRINGL(&function_name.u.constant, "{closure}", sizeof("{closure}")-1, 1); zend_do_begin_function_declaration(function_token, &function_name, 0, return_reference, NULL TSRMLS_CC); result->op_type = IS_TMP_VAR; result->u.op.var = get_temporary_variable(current_op_array); current_op = &current_op_array->opcodes[current_op_number]; current_op->opcode = ZEND_DECLARE_LAMBDA_FUNCTION; zend_del_literal(current_op_array, current_op->op2.constant); SET_UNUSED(current_op->op2); SET_NODE(current_op->result, result); if (is_static) { CG(active_op_array)->fn_flags |= ZEND_ACC_STATIC; } CG(active_op_array)->fn_flags |= ZEND_ACC_CLOSURE; } /* }}} */ void zend_do_handle_exception(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_HANDLE_EXCEPTION; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_function_declaration(const znode *function_token TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; zend_do_extended_info(TSRMLS_C); zend_do_return(NULL, 0 TSRMLS_CC); pass_two(CG(active_op_array) TSRMLS_CC); zend_release_labels(TSRMLS_C); if (CG(active_class_entry)) { zend_check_magic_method_implementation(CG(active_class_entry), (zend_function*)CG(active_op_array), E_COMPILE_ERROR TSRMLS_CC); } else { /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(CG(active_op_array)->function_name); zend_str_tolower_copy(lcname, CG(active_op_array)->function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME)) && CG(active_op_array)->num_args != 1) { zend_error(E_COMPILE_ERROR, "%s() must take exactly 1 argument", ZEND_AUTOLOAD_FUNC_NAME); } } CG(active_op_array)->line_end = zend_get_compiled_lineno(TSRMLS_C); CG(active_op_array) = function_token->u.op_array; /* Pop the switch and foreach seperators */ zend_stack_del_top(&CG(switch_cond_stack)); zend_stack_del_top(&CG(foreach_copy_stack)); } /* }}} */ void zend_do_receive_arg(zend_uchar op, znode *varname, const znode *offset, const znode *initialization, znode *class_type, zend_uchar pass_by_reference TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_arg_info *cur_arg_info; znode var; if (class_type->op_type == IS_CONST && Z_TYPE(class_type->u.constant) == IS_STRING && Z_STRLEN(class_type->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_type->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } if (zend_is_auto_global_quick(Z_STRVAL(varname->u.constant), Z_STRLEN(varname->u.constant), 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign auto-global variable %s", Z_STRVAL(varname->u.constant)); } else { var.op_type = IS_CV; var.u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(varname->u.constant) = (char*)CG(active_op_array)->vars[var.u.op.var].name; var.EA = 0; if (CG(active_op_array)->vars[var.u.op.var].hash_value == THIS_HASHVAL && Z_STRLEN(varname->u.constant) == sizeof("this")-1 && !memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this")-1)) { if (CG(active_op_array)->scope && (CG(active_op_array)->fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } CG(active_op_array)->this_var = var.u.op.var; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->num_args++; opline->opcode = op; SET_NODE(opline->result, &var); SET_NODE(opline->op1, offset); if (op == ZEND_RECV_INIT) { SET_NODE(opline->op2, initialization); } else { CG(active_op_array)->required_num_args = CG(active_op_array)->num_args; SET_UNUSED(opline->op2); } CG(active_op_array)->arg_info = erealloc(CG(active_op_array)->arg_info, sizeof(zend_arg_info)*(CG(active_op_array)->num_args)); cur_arg_info = &CG(active_op_array)->arg_info[CG(active_op_array)->num_args-1]; cur_arg_info->name = zend_new_interned_string(estrndup(varname->u.constant.value.str.val, varname->u.constant.value.str.len), varname->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->name_len = varname->u.constant.value.str.len; cur_arg_info->type_hint = 0; cur_arg_info->allow_null = 1; cur_arg_info->pass_by_reference = pass_by_reference; cur_arg_info->class_name = NULL; cur_arg_info->class_name_len = 0; if (class_type->op_type != IS_UNUSED) { cur_arg_info->allow_null = 0; if (class_type->u.constant.type != IS_NULL) { if (class_type->u.constant.type == IS_ARRAY) { cur_arg_info->type_hint = IS_ARRAY; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else if (Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Default value for parameters with array type hint can only be an array or NULL"); } } } else if (class_type->u.constant.type == IS_CALLABLE) { cur_arg_info->type_hint = IS_CALLABLE; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with callable type hint can only be NULL"); } } } else { cur_arg_info->type_hint = IS_OBJECT; if (ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_type->u.constant), Z_STRLEN(class_type->u.constant))) { zend_resolve_class_name(class_type, opline->extended_value, 1 TSRMLS_CC); } Z_STRVAL(class_type->u.constant) = (char*)zend_new_interned_string(class_type->u.constant.value.str.val, class_type->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->class_name = class_type->u.constant.value.str.val; cur_arg_info->class_name_len = class_type->u.constant.value.str.len; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with a class type hint can only be NULL"); } } } } } } /* }}} */ int zend_do_begin_function_call(znode *function_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { zend_function *function; char *lcname; char *is_compound = memchr(Z_STRVAL(function_name->u.constant), '\\', Z_STRLEN(function_name->u.constant)); zend_resolve_non_class_name(function_name, check_namespace TSRMLS_CC); if (check_namespace && CG(current_namespace) && !is_compound) { /* We assume we call function from the current namespace if it is not prefixed. */ /* In run-time PHP will check for function with full name and internal function with short name */ zend_do_begin_dynamic_function_call(function_name, 1 TSRMLS_CC); return 1; } lcname = zend_str_tolower_dup(function_name->u.constant.value.str.val, function_name->u.constant.value.str.len); if ((zend_hash_find(CG(function_table), lcname, function_name->u.constant.value.str.len+1, (void **) &function)==FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_FUNCTIONS) && (function->type == ZEND_INTERNAL_FUNCTION))) { zend_do_begin_dynamic_function_call(function_name, 0 TSRMLS_CC); efree(lcname); return 1; /* Dynamic */ } efree(function_name->u.constant.value.str.val); function_name->u.constant.value.str.val = lcname; zend_stack_push(&CG(function_call_stack), (void *) &function, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 0; } /* }}} */ void zend_do_begin_method_call(znode *left_bracket TSRMLS_DC) /* {{{ */ { zend_op *last_op; int last_op_number; unsigned char *ptr = NULL; zend_do_end_variable_parse(left_bracket, BP_VAR_R, 0 TSRMLS_CC); zend_do_begin_variable_parse(TSRMLS_C); last_op_number = get_next_op_number(CG(active_op_array))-1; last_op = &CG(active_op_array)->opcodes[last_op_number]; if ((last_op->op2_type == IS_CONST) && (Z_TYPE(CONSTANT(last_op->op2.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(last_op->op2.constant)) == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !zend_binary_strcasecmp(Z_STRVAL(CONSTANT(last_op->op2.constant)), Z_STRLEN(CONSTANT(last_op->op2.constant)), ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1)) { zend_error(E_COMPILE_ERROR, "Cannot call __clone() method on objects - use 'clone $obj' instead"); } if (last_op->opcode == ZEND_FETCH_OBJ_R) { if (last_op->op2_type == IS_CONST) { zval name; name = CONSTANT(last_op->op2.constant); if (!IS_INTERNED(Z_STRVAL(name))) { Z_STRVAL(name) = estrndup(Z_STRVAL(name), Z_STRLEN(name)); } FREE_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); last_op->op2.constant = zend_add_func_name_literal(CG(active_op_array), &name TSRMLS_CC); GET_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); } last_op->opcode = ZEND_INIT_METHOD_CALL; SET_UNUSED(last_op->result); Z_LVAL(left_bracket->u.constant) = ZEND_INIT_FCALL_BY_NAME; } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (left_bracket->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &left_bracket->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, left_bracket); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_do_clone(znode *result, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CLONE; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_begin_dynamic_function_call(znode *function_name, int ns_call TSRMLS_DC) /* {{{ */ { unsigned char *ptr = NULL; zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (ns_call) { /* In run-time PHP will check for function with full name and internal function with short name */ opline->opcode = ZEND_INIT_NS_FCALL_BY_NAME; SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_ns_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (function_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, function_name); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_resolve_non_class_name(znode *element_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; int len; zval **ns; char *lcname, *compound = memchr(Z_STRVAL(element_name->u.constant), '\\', Z_STRLEN(element_name->u.constant)); if (Z_STRVAL(element_name->u.constant)[0] == '\\') { /* name starts with \ so it is known and unambiguos, nothing to do here but shorten it */ memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+1, Z_STRLEN(element_name->u.constant)); --Z_STRLEN(element_name->u.constant); return; } if(!check_namespace) { return; } if (compound && CG(current_import)) { len = compound - Z_STRVAL(element_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(element_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(element_name->u.constant) -= len; memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+len, Z_STRLEN(element_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, element_name TSRMLS_CC); *element_name = tmp; efree(lcname); return; } efree(lcname); } if (CG(current_namespace)) { tmp = *element_name; Z_STRLEN(tmp.u.constant) = sizeof("\\")-1 + Z_STRLEN(element_name->u.constant) + Z_STRLEN_P(CG(current_namespace)); Z_STRVAL(tmp.u.constant) = (char *) emalloc(Z_STRLEN(tmp.u.constant)+1); memcpy(Z_STRVAL(tmp.u.constant), Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace))]), "\\", sizeof("\\")-1); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace)) + sizeof("\\")-1]), Z_STRVAL(element_name->u.constant), Z_STRLEN(element_name->u.constant)+1); STR_FREE(Z_STRVAL(element_name->u.constant)); *element_name = tmp; } } /* }}} */ void zend_resolve_class_name(znode *class_name, ulong fetch_type, int check_ns_name TSRMLS_DC) /* {{{ */ { char *compound; char *lcname; zval **ns; znode tmp; int len; compound = memchr(Z_STRVAL(class_name->u.constant), '\\', Z_STRLEN(class_name->u.constant)); if (compound) { /* This is a compound class name that contains namespace prefix */ if (Z_STRVAL(class_name->u.constant)[0] == '\\') { /* The STRING name has "\" prefix */ Z_STRLEN(class_name->u.constant) -= 1; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+1, Z_STRLEN(class_name->u.constant)+1); Z_STRVAL(class_name->u.constant) = erealloc( Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1); if (ZEND_FETCH_CLASS_DEFAULT != zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "'\\%s' is an invalid class name", Z_STRVAL(class_name->u.constant)); } } else { if (CG(current_import)) { len = compound - Z_STRVAL(class_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(class_name->u.constant) -= len; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+len, Z_STRLEN(class_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; efree(lcname); return; } efree(lcname); } /* Here name is not prefixed with \ and not imported */ if (CG(current_namespace)) { tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } } } else if (CG(current_import) || CG(current_namespace)) { /* this is a plain name (without \) */ lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns) == SUCCESS) { /* The given name is an import name. Substitute it. */ zval_dtor(&class_name->u.constant); class_name->u.constant = **ns; zval_copy_ctor(&class_name->u.constant); } else if (CG(current_namespace)) { /* plain name, no import - prepend current namespace to it */ tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } efree(lcname); } } /* }}} */ void zend_do_fetch_class(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { long fetch_class_op_number; zend_op *opline; if (class_name->op_type == IS_CONST && Z_TYPE(class_name->u.constant) == IS_STRING && Z_STRLEN(class_name->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_name->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } fetch_class_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CLASS; SET_UNUSED(opline->op1); opline->extended_value = ZEND_FETCH_CLASS_GLOBAL; CG(catch_begin) = fetch_class_op_number; if (class_name->op_type == IS_CONST) { int fetch_type; fetch_type = zend_get_class_fetch_type(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); switch (fetch_type) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: SET_UNUSED(opline->op2); opline->extended_value = fetch_type; zval_dtor(&class_name->u.constant); break; default: zend_resolve_class_name(class_name, opline->extended_value, 0 TSRMLS_CC); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_name->u.constant TSRMLS_CC); break; } } else { SET_NODE(opline->op2, class_name); } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; /* FIXME: Hack so that INIT_FCALL_BY_NAME still knows this is a class */ GET_NODE(result, opline->result); result->EA = opline->extended_value; } /* }}} */ void zend_do_label(znode *label TSRMLS_DC) /* {{{ */ { zend_label dest; if (!CG(context).labels) { ALLOC_HASHTABLE(CG(context).labels); zend_hash_init(CG(context).labels, 4, NULL, NULL, 0); } dest.brk_cont = CG(context).current_brk_cont; dest.opline_num = get_next_op_number(CG(active_op_array)); if (zend_hash_add(CG(context).labels, Z_STRVAL(label->u.constant), Z_STRLEN(label->u.constant) + 1, (void**)&dest, sizeof(zend_label), NULL) == FAILURE) { zend_error(E_COMPILE_ERROR, "Label '%s' already defined", Z_STRVAL(label->u.constant)); } /* Done with label now */ zval_dtor(&label->u.constant); } /* }}} */ void zend_resolve_goto_label(zend_op_array *op_array, zend_op *opline, int pass2 TSRMLS_DC) /* {{{ */ { zend_label *dest; long current, distance; zval *label; if (pass2) { label = opline->op2.zv; } else { label = &CONSTANT_EX(op_array, opline->op2.constant); } if (CG(context).labels == NULL || zend_hash_find(CG(context).labels, Z_STRVAL_P(label), Z_STRLEN_P(label)+1, (void**)&dest) == FAILURE) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; zend_error(E_COMPILE_ERROR, "'goto' to undefined label '%s'", Z_STRVAL_P(label)); } else { /* Label is not defined. Delay to pass 2. */ INC_BPC(op_array); return; } } opline->op1.opline_num = dest->opline_num; zval_dtor(label); Z_TYPE_P(label) = IS_NULL; /* Check that we are not moving into loop or switch */ current = opline->extended_value; for (distance = 0; current != dest->brk_cont; distance++) { if (current == -1) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; } zend_error(E_COMPILE_ERROR, "'goto' into loop or switch statement is disallowed"); } current = op_array->brk_cont_array[current].parent; } if (distance == 0) { /* Nothing to break out of, optimize to ZEND_JMP */ opline->opcode = ZEND_JMP; opline->extended_value = 0; SET_UNUSED(opline->op2); } else { /* Set real break distance */ ZVAL_LONG(label, distance); } if (pass2) { DEC_BPC(op_array); } } /* }}} */ void zend_do_goto(const znode *label TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_GOTO; opline->extended_value = CG(context).current_brk_cont; SET_UNUSED(opline->op1); SET_NODE(opline->op2, label); zend_resolve_goto_label(CG(active_op_array), opline, 0 TSRMLS_CC); } /* }}} */ void zend_release_labels(TSRMLS_D) /* {{{ */ { if (CG(context).labels) { zend_hash_destroy(CG(context).labels); FREE_HASHTABLE(CG(context).labels); } if (!zend_stack_is_empty(&CG(context_stack))) { zend_compiler_context *ctx; zend_stack_top(&CG(context_stack), (void**)&ctx); CG(context) = *ctx; zend_stack_del_top(&CG(context_stack)); } } /* }}} */ void zend_do_build_full_name(znode *result, znode *prefix, znode *name, int is_class_member TSRMLS_DC) /* {{{ */ { zend_uint length; if (!result) { result = prefix; } else { *result = *prefix; } if (is_class_member) { length = sizeof("::")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "::", sizeof("::")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("::")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } else { length = sizeof("\\")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "\\", sizeof("\\")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("\\")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } } /* }}} */ int zend_do_begin_class_member_function_call(znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { znode class_node; unsigned char *ptr = NULL; zend_op *opline; if (method_name->op_type == IS_CONST) { char *lcname = zend_str_tolower_dup(Z_STRVAL(method_name->u.constant), Z_STRLEN(method_name->u.constant)); if ((sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == Z_STRLEN(method_name->u.constant) && memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == 0) { zval_dtor(&method_name->u.constant); method_name->op_type = IS_UNUSED; } efree(lcname); } if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; opline = get_next_op(CG(active_op_array) TSRMLS_CC); } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->extended_value = class_node.EA ; } opline->opcode = ZEND_INIT_STATIC_METHOD_CALL; if (class_node.op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, &class_node); } if (method_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &method_name->u.constant TSRMLS_CC); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } } else { SET_NODE(opline->op2, method_name); } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 1; /* Dynamic */ } /* }}} */ void zend_do_end_function_call(znode *function_name, znode *result, const znode *argument_list, int is_method, int is_dynamic_fcall TSRMLS_DC) /* {{{ */ { zend_op *opline; if (is_method && function_name && function_name->op_type == IS_UNUSED) { /* clone */ if (Z_LVAL(argument_list->u.constant) != 0) { zend_error(E_WARNING, "Clone method does not require arguments"); } opline = &CG(active_op_array)->opcodes[Z_LVAL(function_name->u.constant)]; } else { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (!is_method && !is_dynamic_fcall && function_name->op_type==IS_CONST) { opline->opcode = ZEND_DO_FCALL; SET_NODE(opline->op1, function_name); CALCULATE_LITERAL_HASH(opline->op1.constant); GET_CACHE_SLOT(opline->op1.constant); } else { opline->opcode = ZEND_DO_FCALL_BY_NAME; SET_UNUSED(opline->op1); } } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(result, opline->result) ; SET_UNUSED(opline->op2); zend_stack_del_top(&CG(function_call_stack)); opline->extended_value = Z_LVAL(argument_list->u.constant); } /* }}} */ void zend_do_pass_param(znode *param, zend_uchar op, int offset TSRMLS_DC) /* {{{ */ { zend_op *opline; int original_op=op; zend_function **function_ptr_ptr, *function_ptr; int send_by_reference; int send_function = 0; zend_stack_top(&CG(function_call_stack), (void **) &function_ptr_ptr); function_ptr = *function_ptr_ptr; if (original_op == ZEND_SEND_REF) { if (function_ptr && function_ptr->common.function_name && function_ptr->common.type == ZEND_USER_FUNCTION && !ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed; " "If you would like to pass argument by reference, modify the declaration of %s().", function_ptr->common.function_name); } else { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed"); } return; } if (function_ptr) { if (ARG_MAY_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { if (param->op_type & (IS_VAR|IS_CV) && original_op != ZEND_SEND_VAL) { send_by_reference = 1; if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION | ZEND_ARG_SEND_SILENT; } } else { op = ZEND_SEND_VAL; send_by_reference = 0; } } else { send_by_reference = ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset) ? ZEND_ARG_SEND_BY_REF : 0; } } else { send_by_reference = 0; } if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION; } else if (op == ZEND_SEND_VAL && (param->op_type & (IS_VAR|IS_CV))) { op = ZEND_SEND_VAR_NO_REF; } if (op!=ZEND_SEND_VAR_NO_REF && send_by_reference==ZEND_ARG_SEND_BY_REF) { /* change to passing by reference */ switch (param->op_type) { case IS_VAR: case IS_CV: op = ZEND_SEND_REF; break; default: zend_error(E_COMPILE_ERROR, "Only variables can be passed by reference"); break; } } if (original_op == ZEND_SEND_VAR) { switch (op) { case ZEND_SEND_VAR_NO_REF: zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); break; case ZEND_SEND_VAR: if (function_ptr) { zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(param, BP_VAR_FUNC_ARG, offset TSRMLS_CC); } break; case ZEND_SEND_REF: zend_do_end_variable_parse(param, BP_VAR_W, 0 TSRMLS_CC); break; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (op == ZEND_SEND_VAR_NO_REF) { if (function_ptr) { opline->extended_value = ZEND_ARG_COMPILE_TIME_BOUND | send_by_reference | send_function; } else { opline->extended_value = send_function; } } else { if (function_ptr) { opline->extended_value = ZEND_DO_FCALL; } else { opline->extended_value = ZEND_DO_FCALL_BY_NAME; } } opline->opcode = op; SET_NODE(opline->op1, param); opline->op2.opline_num = offset; SET_UNUSED(opline->op2); } /* }}} */ static int generate_free_switch_expr(const zend_switch_entry *switch_entry TSRMLS_DC) /* {{{ */ { zend_op *opline; if (switch_entry->cond.op_type != IS_VAR && switch_entry->cond.op_type != IS_TMP_VAR) { return (switch_entry->cond.op_type == IS_UNUSED); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry->cond); SET_UNUSED(opline->op2); opline->extended_value = 0; return 0; } /* }}} */ static int generate_free_foreach_copy(const zend_op *foreach_copy TSRMLS_DC) /* {{{ */ { zend_op *opline; /* If we reach the seperator then stop applying the stack */ if (foreach_copy->result_type == IS_UNUSED && foreach_copy->op1_type == IS_UNUSED) { return 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->result_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->result); SET_UNUSED(opline->op2); opline->extended_value = 1; if (foreach_copy->op1_type != IS_UNUSED) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->op1_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->op1); SET_UNUSED(opline->op2); opline->extended_value = 0; } return 0; } /* }}} */ void zend_do_return(znode *expr, int do_end_vparse TSRMLS_DC) /* {{{ */ { zend_op *opline; int start_op_number, end_op_number; if (do_end_vparse) { if ((CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) && !zend_is_function_or_method_call(expr)) { zend_do_end_variable_parse(expr, BP_VAR_W, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(expr, BP_VAR_R, 0 TSRMLS_CC); } } start_op_number = get_next_op_number(CG(active_op_array)); #ifdef ZTS zend_stack_apply_with_argument(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_switch_expr TSRMLS_CC); zend_stack_apply_with_argument(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_foreach_copy TSRMLS_CC); #else zend_stack_apply(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_switch_expr); zend_stack_apply(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_foreach_copy); #endif end_op_number = get_next_op_number(CG(active_op_array)); while (start_op_number < end_op_number) { CG(active_op_array)->opcodes[start_op_number].extended_value |= EXT_TYPE_FREE_ON_RETURN; start_op_number++; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) ? ZEND_RETURN_BY_REF : ZEND_RETURN; if (expr) { SET_NODE(opline->op1, expr); if (do_end_vparse && zend_is_function_or_method_call(expr)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } } else { opline->op1_type = IS_CONST; LITERAL_NULL(opline->op1); } SET_UNUSED(opline->op2); } /* }}} */ static int zend_add_try_element(zend_uint try_op TSRMLS_DC) /* {{{ */ { int try_catch_offset = CG(active_op_array)->last_try_catch++; CG(active_op_array)->try_catch_array = erealloc(CG(active_op_array)->try_catch_array, sizeof(zend_try_catch_element)*CG(active_op_array)->last_try_catch); CG(active_op_array)->try_catch_array[try_catch_offset].try_op = try_op; return try_catch_offset; } /* }}} */ static void zend_add_catch_element(int offset, zend_uint catch_op TSRMLS_DC) /* {{{ */ { CG(active_op_array)->try_catch_array[offset].catch_op = catch_op; } /* }}} */ void zend_do_first_catch(znode *open_parentheses TSRMLS_DC) /* {{{ */ { open_parentheses->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_initialize_try_catch_element(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist jmp_list; zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); zend_add_catch_element(try_token->u.op.opline_num, get_next_op_number(CG(active_op_array)) TSRMLS_CC); } /* }}} */ void zend_do_mark_last_catch(const znode *first_catch, const znode *last_additional_catch TSRMLS_DC) /* {{{ */ { CG(active_op_array)->last--; zend_do_if_end(TSRMLS_C); if (last_additional_catch->u.op.opline_num == -1) { CG(active_op_array)->opcodes[first_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[first_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } else { CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_try(znode *try_token TSRMLS_DC) /* {{{ */ { try_token->u.op.opline_num = zend_add_try_element(get_next_op_number(CG(active_op_array)) TSRMLS_CC); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_catch(znode *try_token, znode *class_name, znode *catch_var, znode *first_catch TSRMLS_DC) /* {{{ */ { long catch_op_number; zend_op *opline; znode catch_class; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); catch_class = *class_name; } else { zend_error(E_COMPILE_ERROR, "Bad class name in the catch statement"); } catch_op_number = get_next_op_number(CG(active_op_array)); if (first_catch) { first_catch->u.op.opline_num = catch_op_number; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CATCH; opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &catch_class.u.constant TSRMLS_CC); opline->op2_type = IS_CV; opline->op2.var = lookup_cv(CG(active_op_array), catch_var->u.constant.value.str.val, catch_var->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(catch_var->u.constant) = (char*)CG(active_op_array)->vars[opline->op2.var].name; opline->result.num = 0; /* 1 means it's the last catch in the block */ try_token->u.op.opline_num = catch_op_number; } /* }}} */ void zend_do_end_catch(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); CG(active_op_array)->opcodes[try_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_throw(const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_THROW; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); } /* }}} */ ZEND_API void function_add_ref(zend_function *function) /* {{{ */ { if (function->type == ZEND_USER_FUNCTION) { zend_op_array *op_array = &function->op_array; (*op_array->refcount)++; if (op_array->static_variables) { HashTable *static_variables = op_array->static_variables; zval *tmp_zval; ALLOC_HASHTABLE(op_array->static_variables); zend_hash_init(op_array->static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(op_array->static_variables, static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_zval, sizeof(zval *)); } op_array->run_time_cache = NULL; } } /* }}} */ static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */ { zend_function *function; if (!ce->parent) { return; } /* You cannot change create_object */ ce->create_object = ce->parent->create_object; /* Inherit special functions if needed */ if (!ce->get_iterator) { ce->get_iterator = ce->parent->get_iterator; } if (!ce->iterator_funcs.funcs) { ce->iterator_funcs.funcs = ce->parent->iterator_funcs.funcs; } if (!ce->__get) { ce->__get = ce->parent->__get; } if (!ce->__set) { ce->__set = ce->parent->__set; } if (!ce->__unset) { ce->__unset = ce->parent->__unset; } if (!ce->__isset) { ce->__isset = ce->parent->__isset; } if (!ce->__call) { ce->__call = ce->parent->__call; } if (!ce->__callstatic) { ce->__callstatic = ce->parent->__callstatic; } if (!ce->__tostring) { ce->__tostring = ce->parent->__tostring; } if (!ce->clone) { ce->clone = ce->parent->clone; } if(!ce->serialize) { ce->serialize = ce->parent->serialize; } if(!ce->unserialize) { ce->unserialize = ce->parent->unserialize; } if (!ce->destructor) { ce->destructor = ce->parent->destructor; } if (ce->constructor) { if (ce->parent->constructor && ce->parent->constructor->common.fn_flags & ZEND_ACC_FINAL) { zend_error(E_ERROR, "Cannot override final %s::%s() with %s::%s()", ce->parent->name, ce->parent->constructor->common.function_name, ce->name, ce->constructor->common.function_name ); } return; } if (zend_hash_find(&ce->parent->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), (void **)&function)==SUCCESS) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), function, sizeof(zend_function), NULL); function_add_ref(function); } else { /* Don't inherit the old style constructor if we already have the new style constructor */ char *lc_class_name; char *lc_parent_class_name; lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); if (!zend_hash_exists(&ce->function_table, lc_class_name, ce->name_length+1)) { lc_parent_class_name = zend_str_tolower_dup(ce->parent->name, ce->parent->name_length); if (!zend_hash_exists(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1) && zend_hash_find(&ce->parent->function_table, lc_parent_class_name, ce->parent->name_length+1, (void **)&function)==SUCCESS) { if (function->common.fn_flags & ZEND_ACC_CTOR) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1, function, sizeof(zend_function), NULL); function_add_ref(function); } } efree(lc_parent_class_name); } efree(lc_class_name); } ce->constructor = ce->parent->constructor; } /* }}} */ char *zend_visibility_string(zend_uint fn_flags) /* {{{ */ { if (fn_flags & ZEND_ACC_PRIVATE) { return "private"; } if (fn_flags & ZEND_ACC_PROTECTED) { return "protected"; } if (fn_flags & ZEND_ACC_PUBLIC) { return "public"; } return ""; } /* }}} */ static void do_inherit_method(zend_function *function) /* {{{ */ { /* The class entry of the derived function intentionally remains the same * as that of the parent class. That allows us to know in which context * we're running, and handle private method calls properly. */ function_add_ref(function); } /* }}} */ static zend_bool zend_do_perform_implementation_check(const zend_function *fe, const zend_function *proto TSRMLS_DC) /* {{{ */ { zend_uint i; /* If it's a user function then arg_info == NULL means we don't have any parameters but * we still need to do the arg number checks. We are only willing to ignore this for internal * functions because extensions don't always define arg_info. */ if (!proto || (!proto->common.arg_info && proto->common.type != ZEND_USER_FUNCTION)) { return 1; } /* Checks for constructors only if they are declared in an interface, * or explicitly marked as abstract */ if ((fe->common.fn_flags & ZEND_ACC_CTOR) && ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)) { return 1; } /* check number of arguments */ if (proto->common.required_num_args < fe->common.required_num_args || proto->common.num_args > fe->common.num_args) { return 0; } if (fe->common.type != ZEND_USER_FUNCTION && (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) != 0 && (fe->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) == 0) { return 0; } /* by-ref constraints on return values are covariant */ if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) { return 0; } for (i=0; i < proto->common.num_args; i++) { if (ZEND_LOG_XOR(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)) { /* Only one has a type hint and the other one doesn't */ return 0; } if (fe->common.arg_info[i].class_name && strcasecmp(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)!=0) { const char *colon; if (fe->common.type != ZEND_USER_FUNCTION) { return 0; } else if (strchr(proto->common.arg_info[i].class_name, '\\') != NULL || (colon = zend_memrchr(fe->common.arg_info[i].class_name, '\\', fe->common.arg_info[i].class_name_len)) == NULL || strcasecmp(colon+1, proto->common.arg_info[i].class_name) != 0) { zend_class_entry **fe_ce, **proto_ce; int found, found2; found = zend_lookup_class(fe->common.arg_info[i].class_name, fe->common.arg_info[i].class_name_len, &fe_ce TSRMLS_CC); found2 = zend_lookup_class(proto->common.arg_info[i].class_name, proto->common.arg_info[i].class_name_len, &proto_ce TSRMLS_CC); /* Check for class alias */ if (found != SUCCESS || found2 != SUCCESS || (*fe_ce)->type == ZEND_INTERNAL_CLASS || (*proto_ce)->type == ZEND_INTERNAL_CLASS || *fe_ce != *proto_ce) { return 0; } } } if (fe->common.arg_info[i].type_hint != proto->common.arg_info[i].type_hint) { /* Incompatible type hint */ return 0; } /* by-ref constraints on arguments are invariant */ if (fe->common.arg_info[i].pass_by_reference != proto->common.arg_info[i].pass_by_reference) { return 0; } } if (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) { for (i=proto->common.num_args; i < fe->common.num_args; i++) { if (!fe->common.arg_info[i].pass_by_reference) { return 0; } } } return 1; } /* }}} */ #define REALLOC_BUF_IF_EXCEED(buf, offset, length, size) \ if (UNEXPECTED(offset - buf + size >= length)) { \ length += size + 1; \ buf = erealloc(buf, length); \ } static char * zend_get_function_declaration(zend_function *fptr TSRMLS_DC) /* {{{ */ { char *offset, *buf; zend_uint length = 1024; offset = buf = (char *)emalloc(length * sizeof(char)); if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { *(offset++) = '&'; *(offset++) = ' '; } if (fptr->common.scope) { memcpy(offset, fptr->common.scope->name, fptr->common.scope->name_length); offset += fptr->common.scope->name_length; *(offset++) = ':'; *(offset++) = ':'; } { size_t name_len = strlen(fptr->common.function_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, name_len); memcpy(offset, fptr->common.function_name, name_len); offset += name_len; } *(offset++) = '('; if (fptr->common.arg_info) { zend_uint i, required; zend_arg_info *arg_info = fptr->common.arg_info; required = fptr->common.required_num_args; for (i = 0; i < fptr->common.num_args;) { if (arg_info->class_name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->class_name_len); memcpy(offset, arg_info->class_name, arg_info->class_name_len); offset += arg_info->class_name_len; *(offset++) = ' '; } else if (arg_info->type_hint) { zend_uint type_name_len; char *type_name = zend_get_type_by_const(arg_info->type_hint); type_name_len = strlen(type_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, type_name_len); memcpy(offset, type_name, type_name_len); offset += type_name_len; *(offset++) = ' '; } if (arg_info->pass_by_reference) { *(offset++) = '&'; } *(offset++) = '$'; if (arg_info->name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->name_len); memcpy(offset, arg_info->name, arg_info->name_len); offset += arg_info->name_len; } else { zend_uint idx = i; memcpy(offset, "param", 5); offset += 5; do { *(offset++) = (char) (idx % 10) + '0'; idx /= 10; } while (idx > 0); } if (i >= required) { *(offset++) = ' '; *(offset++) = '='; *(offset++) = ' '; if (fptr->type == ZEND_USER_FUNCTION) { zend_op *precv = NULL; { zend_uint idx = i; zend_op *op = ((zend_op_array *)fptr)->opcodes; zend_op *end = op + ((zend_op_array *)fptr)->last; ++idx; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT) && op->op1.num == (long)idx) { precv = op; } ++op; } } if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) { zval *zv, zv_copy; int use_copy; ALLOC_ZVAL(zv); *zv = *precv->op2.zv; zval_copy_ctor(zv); INIT_PZVAL(zv); zval_update_constant_ex(&zv, (void*)1, fptr->common.scope TSRMLS_CC); if (Z_TYPE_P(zv) == IS_BOOL) { if (Z_LVAL_P(zv)) { memcpy(offset, "true", 4); offset += 4; } else { memcpy(offset, "false", 5); offset += 5; } } else if (Z_TYPE_P(zv) == IS_NULL) { memcpy(offset, "NULL", 4); offset += 4; } else if (Z_TYPE_P(zv) == IS_STRING) { *(offset++) = '\''; REALLOC_BUF_IF_EXCEED(buf, offset, length, MIN(Z_STRLEN_P(zv), 10)); memcpy(offset, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 10)); offset += MIN(Z_STRLEN_P(zv), 10); if (Z_STRLEN_P(zv) > 10) { *(offset++) = '.'; *(offset++) = '.'; *(offset++) = '.'; } *(offset++) = '\''; } else if (Z_TYPE_P(zv) == IS_ARRAY) { memcpy(offset, "Array", 5); offset += 5; } else { zend_make_printable_zval(zv, &zv_copy, &use_copy); REALLOC_BUF_IF_EXCEED(buf, offset, length, Z_STRLEN(zv_copy)); memcpy(offset, Z_STRVAL(zv_copy), Z_STRLEN(zv_copy)); offset += Z_STRLEN(zv_copy); if (use_copy) { zval_dtor(&zv_copy); } } zval_ptr_dtor(&zv); } } else { memcpy(offset, "NULL", 4); offset += 4; } } if (++i < fptr->common.num_args) { *(offset++) = ','; *(offset++) = ' '; } arg_info++; REALLOC_BUF_IF_EXCEED(buf, offset, length, 32); } } *(offset++) = ')'; *offset = '\0'; return buf; } /* }}} */ static void do_inheritance_check_on_method(zend_function *child, zend_function *parent TSRMLS_DC) /* {{{ */ { zend_uint child_flags; zend_uint parent_flags = parent->common.fn_flags; if (parent->common.fn_flags & ZEND_ACC_ABSTRACT && parent->common.scope != (child->common.prototype ? child->common.prototype->common.scope : child->common.scope) && child->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_IMPLEMENTED_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Can't inherit abstract function %s::%s() (previously declared abstract in %s)", parent->common.scope->name, child->common.function_name, child->common.prototype ? child->common.prototype->common.scope->name : child->common.scope->name); } if (parent_flags & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot override final method %s::%s()", ZEND_FN_SCOPE_NAME(parent), child->common.function_name); } child_flags = child->common.fn_flags; /* You cannot change from static to non static and vice versa. */ if ((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC)) { if (child->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot make non static method %s::%s() static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } else { zend_error(E_COMPILE_ERROR, "Cannot make static method %s::%s() non static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } } /* Disallow making an inherited method abstract. */ if ((child_flags & ZEND_ACC_ABSTRACT) && !(parent_flags & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Cannot make non abstract method %s::%s() abstract in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } if (parent_flags & ZEND_ACC_CHANGED) { child->common.fn_flags |= ZEND_ACC_CHANGED; } else { /* Prevent derived classes from restricting access that was available in parent classes */ if ((child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::%s() must be %s (as in class %s)%s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if (((child_flags & ZEND_ACC_PPP_MASK) < (parent_flags & ZEND_ACC_PPP_MASK)) && ((parent_flags & ZEND_ACC_PPP_MASK) & ZEND_ACC_PRIVATE)) { child->common.fn_flags |= ZEND_ACC_CHANGED; } } if (parent_flags & ZEND_ACC_PRIVATE) { child->common.prototype = NULL; } else if (parent_flags & ZEND_ACC_ABSTRACT) { child->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; child->common.prototype = parent; } else if (!(parent->common.fn_flags & ZEND_ACC_CTOR) || (parent->common.prototype && (parent->common.prototype->common.scope->ce_flags & ZEND_ACC_INTERFACE))) { /* ctors only have a prototype if it comes from an interface */ child->common.prototype = parent->common.prototype ? parent->common.prototype : parent; } if (child->common.prototype && (child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { if (!zend_do_perform_implementation_check(child, child->common.prototype TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s::%s() must be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_get_function_declaration(child->common.prototype TSRMLS_CC)); } } else if (EG(error_reporting) & E_STRICT || EG(user_error_handler)) { /* Check E_STRICT (or custom error handler) before the check so that we save some time */ if (!zend_do_perform_implementation_check(child, parent TSRMLS_CC)) { char *method_prototype = zend_get_function_declaration(child->common.prototype TSRMLS_CC); zend_error(E_STRICT, "Declaration of %s::%s() should be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, method_prototype); efree(method_prototype); } } } /* }}} */ static zend_bool do_inherit_method_check(HashTable *child_function_table, zend_function *parent, const zend_hash_key *hash_key, zend_class_entry *child_ce) /* {{{ */ { zend_uint parent_flags = parent->common.fn_flags; zend_function *child; TSRMLS_FETCH(); if (zend_hash_quick_find(child_function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child)==FAILURE) { if (parent_flags & (ZEND_ACC_ABSTRACT)) { child_ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } return 1; /* method doesn't exist in child, copy from parent */ } do_inheritance_check_on_method(child, parent TSRMLS_CC); return 0; } /* }}} */ static zend_bool do_inherit_property_access_check(HashTable *target_ht, zend_property_info *parent_info, const zend_hash_key *hash_key, zend_class_entry *ce) /* {{{ */ { zend_property_info *child_info; zend_class_entry *parent_ce = ce->parent; if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW)) { if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { child_info->flags |= ZEND_ACC_CHANGED; } else { zend_hash_quick_update(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, parent_info, sizeof(zend_property_info), (void **) &child_info); if(ce->type & ZEND_INTERNAL_CLASS) { zend_duplicate_property_info_internal(child_info); } else { zend_duplicate_property_info(child_info); } child_info->flags &= ~ZEND_ACC_PRIVATE; /* it's not private anymore */ child_info->flags |= ZEND_ACC_SHADOW; /* but it's a shadow of private */ } return 0; /* don't copy access information to child */ } if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { if ((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s", (parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", parent_ce->name, hash_key->arKey, (child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ce->name, hash_key->arKey); } if(parent_info->flags & ZEND_ACC_CHANGED) { child_info->flags |= ZEND_ACC_CHANGED; } if ((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ce->name, hash_key->arKey, zend_visibility_string(parent_info->flags), parent_ce->name, (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if ((child_info->flags & ZEND_ACC_STATIC) == 0) { Z_DELREF_P(ce->default_properties_table[parent_info->offset]); ce->default_properties_table[parent_info->offset] = ce->default_properties_table[child_info->offset]; ce->default_properties_table[child_info->offset] = NULL; child_info->offset = parent_info->offset; } return 0; /* Don't copy from parent */ } else { return 1; /* Copy from parent */ } } /* }}} */ static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce TSRMLS_CC) == FAILURE) { zend_error(E_CORE_ERROR, "Class %s could not implement interface %s", ce->name, iface->name); } if (ce == iface) { zend_error(E_ERROR, "Interface %s cannot implement itself", ce->name); } } /* }}} */ ZEND_API void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface TSRMLS_DC) /* {{{ */ { /* expects interface to be contained in ce's interface list already */ zend_uint i, ce_num, if_num = iface->num_interfaces; zend_class_entry *entry; if (if_num==0) { return; } ce_num = ce->num_interfaces; if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } /* Inherit the interfaces, only if they're not already inherited by the class */ while (if_num--) { entry = iface->interfaces[if_num]; for (i = 0; i < ce_num; i++) { if (ce->interfaces[i] == entry) { break; } } if (i == ce_num) { ce->interfaces[ce->num_interfaces++] = entry; } } /* and now call the implementing handlers */ while (ce_num < ce->num_interfaces) { do_implement_interface(ce, ce->interfaces[ce_num++] TSRMLS_CC); } } /* }}} */ #ifdef ZTS static void zval_internal_ctor(zval **p) /* {{{ */ { zval *orig_ptr = *p; ALLOC_ZVAL(*p); MAKE_COPY_ZVAL(&orig_ptr, *p); } /* }}} */ # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) (((parent_ce)->type != (ce)->type) ? zval_internal_ctor : zval_add_ref)) #else # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) zval_add_ref) #endif ZEND_API void zend_do_inheritance(zend_class_entry *ce, zend_class_entry *parent_ce TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; if ((ce->ce_flags & ZEND_ACC_INTERFACE) && !(parent_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ce->name, parent_ce->name); } if (parent_ce->ce_flags & ZEND_ACC_FINAL_CLASS) { zend_error(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ce->name, parent_ce->name); } ce->parent = parent_ce; /* Copy serialize/unserialize callbacks */ if (!ce->serialize) { ce->serialize = parent_ce->serialize; } if (!ce->unserialize) { ce->unserialize = parent_ce->unserialize; } /* Inherit interfaces */ zend_do_inherit_interfaces(ce, parent_ce TSRMLS_CC); /* Inherit properties */ if (parent_ce->default_properties_count) { int i = ce->default_properties_count + parent_ce->default_properties_count; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_properties_count) { while (i-- > parent_ce->default_properties_count) { ce->default_properties_table[i] = ce->default_properties_table[i - parent_ce->default_properties_count]; } } for (i = 0; i < parent_ce->default_properties_count; i++) { ce->default_properties_table[i] = parent_ce->default_properties_table[i]; if (ce->default_properties_table[i]) { #ifdef ZTS if (parent_ce->type != ce->type) { zval *p; ALLOC_ZVAL(p); MAKE_COPY_ZVAL(&ce->default_properties_table[i], p); ce->default_properties_table[i] = p; } else { Z_ADDREF_P(ce->default_properties_table[i]); } #else Z_ADDREF_P(ce->default_properties_table[i]); #endif } } ce->default_properties_count += parent_ce->default_properties_count; } if (parent_ce->type != ce->type) { /* User class extends internal class */ zend_update_class_constants(parent_ce TSRMLS_CC); if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = erealloc(ce->default_static_members_table, sizeof(void*) * i); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&CE_STATIC_MEMBERS(parent_ce)[i]); ce->default_static_members_table[i] = CE_STATIC_MEMBERS(parent_ce)[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; ce->static_members_table = ce->default_static_members_table; } } else { if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&parent_ce->default_static_members_table[i]); ce->default_static_members_table[i] = parent_ce->default_static_members_table[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } } for (zend_hash_internal_pointer_reset(&ce->properties_info); zend_hash_get_current_data(&ce->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->properties_info)) { if (property_info->ce == ce) { if (property_info->flags & ZEND_ACC_STATIC) { property_info->offset += parent_ce->default_static_members_count; } else { property_info->offset += parent_ce->default_properties_count; } } } zend_hash_merge_ex(&ce->properties_info, &parent_ce->properties_info, (copy_ctor_func_t) (ce->type & ZEND_INTERNAL_CLASS ? zend_duplicate_property_info_internal : zend_duplicate_property_info), sizeof(zend_property_info), (merge_checker_func_t) do_inherit_property_access_check, ce); zend_hash_merge(&ce->constants_table, &parent_ce->constants_table, zval_property_ctor(parent_ce, ce), NULL, sizeof(zval *), 0); zend_hash_merge_ex(&ce->function_table, &parent_ce->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_inherit_parent_constructor(ce); if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS && ce->type == ZEND_INTERNAL_CLASS) { ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } else if (!(ce->ce_flags & ZEND_ACC_IMPLEMENT_INTERFACES) && !(ce->ce_flags & ZEND_ACC_IMPLEMENT_TRAITS)) { /* The verification will be done in runtime by ZEND_VERIFY_ABSTRACT_CLASS */ zend_verify_abstract_class(ce TSRMLS_CC); } ce->ce_flags |= parent_ce->ce_flags & ZEND_HAS_STATIC_IN_METHODS; } /* }}} */ static zend_bool do_inherit_constant_check(HashTable *child_constants_table, const zval **parent_constant, const zend_hash_key *hash_key, const zend_class_entry *iface) /* {{{ */ { zval **old_constant; if (zend_hash_quick_find(child_constants_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**)&old_constant) == SUCCESS) { if (*old_constant != *parent_constant) { zend_error(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", hash_key->arKey, iface->name); } return 0; } return 1; } /* }}} */ static int do_interface_constant_check(zval **val TSRMLS_DC, int num_args, va_list args, const zend_hash_key *key) /* {{{ */ { zend_class_entry **iface = va_arg(args, zend_class_entry**); do_inherit_constant_check(&(*iface)->constants_table, (const zval **) val, key, *iface); return ZEND_HASH_APPLY_KEEP; } /* }}} */ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_iface_num = ce->num_interfaces; zend_uint parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0; for (i = 0; i < ce->num_interfaces; i++) { if (ce->interfaces[i] == NULL) { memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i)); i--; } else if (ce->interfaces[i] == iface) { if (i < parent_iface_num) { ignore = 1; } else { zend_error(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ce->name, iface->name); } } } if (ignore) { /* Check for attempt to redeclare interface constants */ zend_hash_apply_with_arguments(&ce->constants_table TSRMLS_CC, (apply_func_args_t) do_interface_constant_check, 1, &iface); } else { if (ce->num_interfaces >= current_iface_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } } ce->interfaces[ce->num_interfaces++] = iface; zend_hash_merge_ex(&ce->constants_table, &iface->constants_table, (copy_ctor_func_t) zval_add_ref, sizeof(zval *), (merge_checker_func_t) do_inherit_constant_check, iface); zend_hash_merge_ex(&ce->function_table, &iface->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_implement_interface(ce, iface TSRMLS_CC); zend_do_inherit_interfaces(ce, iface TSRMLS_CC); } } /* }}} */ ZEND_API void zend_do_implement_trait(zend_class_entry *ce, zend_class_entry *trait TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_trait_num = ce->num_traits; zend_uint parent_trait_num = ce->parent ? ce->parent->num_traits : 0; for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == NULL) { memmove(ce->traits + i, ce->traits + i + 1, sizeof(zend_class_entry*) * (--ce->num_traits - i)); i--; } else if (ce->traits[i] == trait) { if (i < parent_trait_num) { ignore = 1; } } } if (!ignore) { if (ce->num_traits >= current_trait_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->traits = (zend_class_entry **) realloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } else { ce->traits = (zend_class_entry **) erealloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } } ce->traits[ce->num_traits++] = trait; } } /* }}} */ static int zend_traits_merge_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { size_t current; size_t i; size_t count; HashTable* resulting_table; HashTable** function_tables; zend_class_entry *ce; size_t collision = 0; size_t abstract_solved = 0; zend_function* other_trait_fn; current = va_arg(args, size_t); /* index of current trait */ count = va_arg(args, size_t); resulting_table = va_arg(args, HashTable*); function_tables = va_arg(args, HashTable**); ce = va_arg(args, zend_class_entry*); for (i = 0; i < count; i++) { if (i == current) { continue; /* just skip this, cause its the table this function is applied on */ } if (zend_hash_quick_find(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&other_trait_fn) == SUCCESS) { /* if it is an abstract method, there is no collision */ if (other_trait_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible */ do_inheritance_check_on_method(fn, other_trait_fn TSRMLS_CC); /* we can savely free and remove it from other table */ zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } else { /* if it is not an abstract method, there is still no collision */ /* if fn is an abstract method */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible */ do_inheritance_check_on_method(other_trait_fn, fn TSRMLS_CC); /* just mark as solved, will be added if its own trait is processed */ abstract_solved = 1; } else { /* but else, we have a collision of non-abstract methods */ collision++; zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } } } if (collision) { zend_function* class_fn; /* make sure method is not already overridden in class */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&class_fn) == FAILURE || class_fn->common.scope != ce) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because there are collisions with other trait methods on %s", fn->common.function_name, ce->name); } zend_function_dtor(fn); } else if (abstract_solved) { zend_function_dtor(fn); } else { /* Add it to result function table */ if (zend_hash_quick_add(resulting_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, fn, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating resulting trait method table", fn->common.function_name); } } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ /* {{{ Originates from php_runkit_function_copy_ctor Duplicate structures in an op_array where necessary to make an outright duplicate */ static void zend_traits_duplicate_function(zend_function *fe, zend_class_entry *target_ce, char *newname TSRMLS_DC) { zend_literal *literals_copy; zend_compiled_variable *dupvars; zend_op *opcode_copy; zval class_name_zv; int class_name_literal; int i; int number_of_literals; if (fe->op_array.static_variables) { HashTable *tmpHash; ALLOC_HASHTABLE(tmpHash); zend_hash_init(tmpHash, zend_hash_num_elements(fe->op_array.static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_apply_with_arguments(fe->op_array.static_variables TSRMLS_CC, (apply_func_args_t)zval_copy_static_var, 1, tmpHash); fe->op_array.static_variables = tmpHash; } number_of_literals = fe->op_array.last_literal; literals_copy = (zend_literal*)emalloc(number_of_literals * sizeof(zend_literal)); for (i = 0; i < number_of_literals; i++) { literals_copy[i] = fe->op_array.literals[i]; zval_copy_ctor(&literals_copy[i].constant); } fe->op_array.literals = literals_copy; fe->op_array.refcount = emalloc(sizeof(zend_uint)); *(fe->op_array.refcount) = 1; if (fe->op_array.vars) { i = fe->op_array.last_var; dupvars = safe_emalloc(fe->op_array.last_var, sizeof(zend_compiled_variable), 0); while (i > 0) { i--; dupvars[i].name = estrndup(fe->op_array.vars[i].name, fe->op_array.vars[i].name_len); dupvars[i].name_len = fe->op_array.vars[i].name_len; dupvars[i].hash_value = fe->op_array.vars[i].hash_value; } fe->op_array.vars = dupvars; } else { fe->op_array.vars = NULL; } opcode_copy = safe_emalloc(sizeof(zend_op), fe->op_array.last, 0); for(i = 0; i < fe->op_array.last; i++) { opcode_copy[i] = fe->op_array.opcodes[i]; if (opcode_copy[i].op1_type != IS_CONST) { if (opcode_copy[i].op1.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op1.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op1.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op1.jmp_addr - fe->op_array.opcodes); } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op1.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op1.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op1.zv = &fe->op_array.literals[class_name_literal].constant; } } if (opcode_copy[i].op2_type != IS_CONST) { if (opcode_copy[i].op2.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op2.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op2.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op2.jmp_addr - fe->op_array.opcodes); } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op2.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op2.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op2.zv = &fe->op_array.literals[class_name_literal].constant; } } } fe->op_array.opcodes = opcode_copy; fe->op_array.function_name = newname; /* was setting it to fe which does not work since fe is stack allocated and not a stable address */ /* fe->op_array.prototype = fe->op_array.prototype; */ if (fe->op_array.arg_info) { zend_arg_info *tmpArginfo; tmpArginfo = safe_emalloc(sizeof(zend_arg_info), fe->op_array.num_args, 0); for(i = 0; i < fe->op_array.num_args; i++) { tmpArginfo[i] = fe->op_array.arg_info[i]; tmpArginfo[i].name = estrndup(tmpArginfo[i].name, tmpArginfo[i].name_len); if (tmpArginfo[i].class_name) { tmpArginfo[i].class_name = estrndup(tmpArginfo[i].class_name, tmpArginfo[i].class_name_len); } } fe->op_array.arg_info = tmpArginfo; } fe->op_array.doc_comment = estrndup(fe->op_array.doc_comment, fe->op_array.doc_comment_len); fe->op_array.try_catch_array = (zend_try_catch_element*)estrndup((char*)fe->op_array.try_catch_array, sizeof(zend_try_catch_element) * fe->op_array.last_try_catch); fe->op_array.brk_cont_array = (zend_brk_cont_element*)estrndup((char*)fe->op_array.brk_cont_array, sizeof(zend_brk_cont_element) * fe->op_array.last_brk_cont); } /* }}} */ static void zend_add_magic_methods(zend_class_entry* ce, const char* mname, uint mname_len, zend_function* fe TSRMLS_DC) { if ( !strncmp(mname, ZEND_CLONE_FUNC_NAME, mname_len)) { ce->clone = fe; fe->common.fn_flags |= ZEND_ACC_CLONE; } else if (!strncmp(mname, ZEND_CONSTRUCTOR_FUNC_NAME, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } else if (!strncmp(mname, ZEND_DESTRUCTOR_FUNC_NAME, mname_len)) { ce->destructor = fe; fe->common.fn_flags |= ZEND_ACC_DTOR; } else if (!strncmp(mname, ZEND_GET_FUNC_NAME, mname_len)) ce->__get = fe; else if (!strncmp(mname, ZEND_SET_FUNC_NAME, mname_len)) ce->__set = fe; else if (!strncmp(mname, ZEND_CALL_FUNC_NAME, mname_len)) ce->__call = fe; else if (!strncmp(mname, ZEND_UNSET_FUNC_NAME, mname_len)) ce->__unset = fe; else if (!strncmp(mname, ZEND_ISSET_FUNC_NAME, mname_len)) ce->__isset = fe; else if (!strncmp(mname, ZEND_CALLSTATIC_FUNC_NAME, mname_len)) ce->__callstatic= fe; else if (!strncmp(mname, ZEND_TOSTRING_FUNC_NAME, mname_len)) ce->__tostring = fe; else if (ce->name_length + 1 == mname_len) { char *lowercase_name = emalloc(ce->name_length + 1); zend_str_tolower_copy(lowercase_name, ce->name, ce->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, ce->name_length + 1, 1 TSRMLS_CC); if (!memcmp(mname, lowercase_name, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } str_efree(lowercase_name); } } static int zend_traits_merge_functions_to_class(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zend_class_entry *ce = va_arg(args, zend_class_entry*); int add = 0; zend_function* existing_fn; zend_function fn_copy, *fn_copy_p; zend_function* prototype = NULL; /* is used to determine the prototype according to the inheritance chain */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &existing_fn) == FAILURE) { add = 1; /* not found */ } else if (existing_fn->common.scope != ce) { add = 1; /* or inherited from other class or interface */ } if (add) { zend_function* parent_function; if (ce->parent && zend_hash_quick_find(&ce->parent->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &parent_function) != FAILURE) { prototype = parent_function; /* ->common.fn_flags |= ZEND_ACC_ABSTRACT; */ /* we got that method in the parent class, and are going to override it, except, if the trait is just asking to have an abstract method implemented. */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* then we clean up an skip this method */ zend_function_dtor(fn); return ZEND_HASH_APPLY_REMOVE; } } fn->common.scope = ce; fn->common.prototype = prototype; if (prototype && (prototype->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT || prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { fn->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; } else if (fn->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT) { /* remove ZEND_ACC_IMPLEMENTED_ABSTRACT flag, think it shouldn't be copied to class */ fn->common.fn_flags = fn->common.fn_flags - ZEND_ACC_IMPLEMENTED_ABSTRACT; } /* check whether the trait method fullfills the inheritance requirements */ if (prototype) { do_inheritance_check_on_method(fn, prototype TSRMLS_CC); } /* one more thing: make sure we properly implement an abstract method */ if (existing_fn && existing_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { do_inheritance_check_on_method(fn, existing_fn TSRMLS_CC); } /* delete inherited fn if the function to be added is not abstract */ if (existing_fn && existing_fn->common.scope != ce && (fn->common.fn_flags & ZEND_ACC_ABSTRACT) == 0) { /* it is just a reference which was added to the subclass while doing the inheritance, so we can deleted now, and will add the overriding method afterwards. Except, if we try to add an abstract function, then we should not delete the inherited one */ zend_hash_quick_del(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h); } if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (fn->op_array.static_variables) { ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, ce, estrdup(fn->common.function_name) TSRMLS_CC); if (zend_hash_quick_update(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, &fn_copy, sizeof(zend_function), (void**)&fn_copy_p)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating class method table", hash_key->arKey); } zend_add_magic_methods(ce, hash_key->arKey, hash_key->nKeyLength, fn_copy_p TSRMLS_CC); zend_function_dtor(fn); } else { zend_function_dtor(fn); } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ static int zend_traits_copy_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { HashTable* target; zend_class_entry *target_ce; zend_trait_alias** aliases; HashTable* exclude_table; char* lcname; unsigned int fnname_len; zend_function fn_copy; void* dummy; size_t i = 0; target = va_arg(args, HashTable*); target_ce = va_arg(args, zend_class_entry*); aliases = va_arg(args, zend_trait_alias**); exclude_table = va_arg(args, HashTable*); fnname_len = strlen(fn->common.function_name); /* apply aliases which are qualified with a class name, there should not be any ambiguity */ if (aliases) { while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias != NULL && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && aliases[i]->trait_method->mname_len == fnname_len && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(aliases[i]->alias, aliases[i]->alias_len) TSRMLS_CC); /* if it is 0, no modifieres has been changed */ if (aliases[i]->modifiers) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } lcname = zend_str_tolower_dup(aliases[i]->alias, aliases[i]->alias_len); if (zend_hash_add(target, lcname, aliases[i]->alias_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add aliased trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } efree(lcname); } i++; } } lcname = zend_str_tolower_dup(fn->common.function_name, fnname_len); if (exclude_table == NULL || zend_hash_find(exclude_table, lcname, fnname_len, &dummy) == FAILURE) { /* is not in hashtable, thus, function is not to be excluded */ fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(fn->common.function_name, fnname_len) TSRMLS_CC); /* apply aliases which are not qualified by a class name, or which have not * alias name, just setting visibility */ if (aliases) { i = 0; while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias == NULL && aliases[i]->modifiers != 0 && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && (aliases[i]->trait_method->mname_len == fnname_len) && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } i++; } } if (zend_hash_add(target, lcname, fnname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } } efree(lcname); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* Copies function table entries to target function table with applied aliasing */ static void zend_traits_copy_trait_function_table(HashTable *target, zend_class_entry *target_ce, HashTable *source, zend_trait_alias** aliases, HashTable* exclude_table TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_arguments(source TSRMLS_CC, (apply_func_args_t)zend_traits_copy_functions, 4, target, target_ce, aliases, exclude_table); } /* }}} */ static void zend_traits_init_trait_structures(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i, j = 0; zend_trait_precedence *cur_precedence; zend_trait_method_reference *cur_method_ref; /* resolve class references */ if (ce->trait_precedences) { i = 0; while ((cur_precedence = ce->trait_precedences[i])) { if (cur_precedence->exclude_from_classes) { cur_precedence->trait_method->ce = zend_fetch_class(cur_precedence->trait_method->class_name, cur_precedence->trait_method->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); j = 0; while (cur_precedence->exclude_from_classes[j]) { char* class_name = (char*)cur_precedence->exclude_from_classes[j]; zend_uint name_length = strlen(class_name); cur_precedence->exclude_from_classes[j] = zend_fetch_class(class_name, name_length, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); efree(class_name); j++; } } i++; } } if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { if (ce->trait_aliases[i]->trait_method->class_name) { cur_method_ref = ce->trait_aliases[i]->trait_method; cur_method_ref->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); } i++; } } } /* }}} */ static void zend_traits_compile_exclude_table(HashTable* exclude_table, zend_trait_precedence **precedences, zend_class_entry *trait) /* {{{ */ { size_t i = 0, j; if (!precedences) { return; } while (precedences[i]) { if (precedences[i]->exclude_from_classes) { j = 0; while (precedences[i]->exclude_from_classes[j]) { if (precedences[i]->exclude_from_classes[j] == trait) { zend_uint lcname_len = precedences[i]->trait_method->mname_len; char *lcname = zend_str_tolower_dup(precedences[i]->trait_method->method_name, lcname_len); if (zend_hash_add(exclude_table, lcname, lcname_len, NULL, 0, NULL) == FAILURE) { efree(lcname); zend_error(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", precedences[i]->trait_method->method_name, trait->name); } efree(lcname); } ++j; } } ++i; } } /* }}} */ static void zend_do_traits_method_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { HashTable** function_tables; HashTable* resulting_table; HashTable exclude_table; size_t i; /* prepare copies of trait function tables for combination */ function_tables = malloc(sizeof(HashTable*) * ce->num_traits); resulting_table = (HashTable *) malloc(sizeof(HashTable)); /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(resulting_table, 10, NULL, NULL, 1, 0); for (i = 0; i < ce->num_traits; i++) { function_tables[i] = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(function_tables[i], ce->traits[i]->function_table.nNumOfElements, NULL, NULL, 1, 0); if (ce->trait_precedences) { /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(&exclude_table, 2, NULL, NULL, 0, 0); zend_traits_compile_exclude_table(&exclude_table, ce->trait_precedences, ce->traits[i]); /* copies functions, applies defined aliasing, and excludes unused trait methods */ zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, &exclude_table TSRMLS_CC); zend_hash_graceful_destroy(&exclude_table); } else { zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, NULL TSRMLS_CC); } } /* now merge trait methods */ for (i = 0; i < ce->num_traits; i++) { zend_hash_apply_with_arguments(function_tables[i] TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions, 5, i, ce->num_traits, resulting_table, function_tables, ce); } /* Now the resulting_table contains all trait methods we would have to * add to the class in the following step the methods are inserted into the method table * if there is already a method with the same name it is replaced iff ce != fn.scope * --> all inherited methods are overridden, methods defined in the class are left untouched */ zend_hash_apply_with_arguments(resulting_table TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions_to_class, 1, ce); /* free temporary function tables */ for (i = 0; i < ce->num_traits; i++) { /* zend_hash_destroy(function_tables[i]); */ zend_hash_graceful_destroy(function_tables[i]); free(function_tables[i]); } free(function_tables); /* free temporary resulting table */ /* zend_hash_destroy(resulting_table); */ zend_hash_graceful_destroy(resulting_table); free(resulting_table); } /* }}} */ static zend_class_entry* find_first_definition(zend_class_entry *ce, size_t current_trait, const char* prop_name, int prop_name_length, ulong prop_hash, zend_class_entry *coliding_ce) /* {{{ */ { size_t i; zend_property_info *coliding_prop; for (i = 0; (i < current_trait) && (i < ce->num_traits); i++) { if (zend_hash_quick_find(&ce->traits[i]->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS) { return ce->traits[i]; } } return coliding_ce; } /* }}} */ static void zend_do_traits_property_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i; zend_property_info *property_info; zend_property_info *coliding_prop; zval compare_result; const char* prop_name; int prop_name_length; ulong prop_hash; const char* class_name_unused; zend_bool prop_found; zend_bool not_compatible; zval* prop_value; /* In the following steps the properties are inserted into the property table * for that, a very strict approach is applied: * - check for compatibility, if not compatible with any property in class -> fatal * - if compatible, then strict notice */ for (i = 0; i < ce->num_traits; i++) { for (zend_hash_internal_pointer_reset(&ce->traits[i]->properties_info); zend_hash_get_current_data(&ce->traits[i]->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->traits[i]->properties_info)) { /* first get the unmangeld name if necessary, * then check whether the property is already there */ if ((property_info->flags & ZEND_ACC_PPP_MASK) == ZEND_ACC_PUBLIC) { prop_hash = property_info->h; prop_name = property_info->name; prop_name_length = property_info->name_length; prop_found = zend_hash_quick_find(&ce->properties_info, property_info->name, property_info->name_length+1, property_info->h, (void **) &coliding_prop) == SUCCESS; } else { /* for private and protected we need to unmangle the names */ zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name_unused, &prop_name); prop_name_length = strlen(prop_name); prop_hash = zend_get_hash_value(prop_name, prop_name_length + 1); prop_found = zend_hash_quick_find(&ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS; } /* next: check for conflicts with current class */ if (prop_found) { if (coliding_prop->flags & ZEND_ACC_SHADOW) { /* this one is inherited, lets look it up in its own class */ zend_hash_quick_find(&coliding_prop->ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop); } if ((coliding_prop->flags & ZEND_ACC_PPP_MASK) == (property_info->flags & ZEND_ACC_PPP_MASK)) { /* flags are identical, now the value needs to be checked */ if (property_info->flags & ZEND_ACC_STATIC) { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_static_members_table[coliding_prop->offset], ce->traits[i]->default_static_members_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } else { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_properties_table[coliding_prop->offset], ce->traits[i]->default_properties_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } } else { /* the flags are not identical, thus, we assume properties are not compatible */ not_compatible = 1; } if (not_compatible) { zend_error(E_COMPILE_ERROR, "%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } else { zend_error(E_STRICT, "%s and %s define the same property ($%s) in the composition of %s. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } } /* property not found, so lets add it */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); zend_declare_property_ex(ce, prop_name, prop_name_length, prop_value, property_info->flags, property_info->doc_comment, property_info->doc_comment_len TSRMLS_CC); } } } /* }}} */ ZEND_API void zend_do_bind_traits(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { if (ce->num_traits <= 0) { return; } /* complete initialization of trait strutures in ce */ zend_traits_init_trait_structures(ce TSRMLS_CC); /* first care about all methods to be flattened into the class */ zend_do_traits_method_binding(ce TSRMLS_CC); /* then flatten the properties into it, to, mostly to notfiy developer about problems */ zend_do_traits_property_binding(ce TSRMLS_CC); /* verify that all abstract methods from traits have been implemented */ zend_verify_abstract_class(ce TSRMLS_CC); /* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */ if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { ce->ce_flags -= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } } /* }}} */ ZEND_API int do_bind_function(const zend_op_array *op_array, zend_op *opline, HashTable *function_table, zend_bool compile_time) /* {{{ */ { zend_function *function; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } zend_hash_quick_find(function_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void *) &function); if (zend_hash_quick_add(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), function, sizeof(zend_function), NULL)==FAILURE) { int error_level = compile_time ? E_COMPILE_ERROR : E_ERROR; zend_function *old_function; if (zend_hash_quick_find(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), (void *) &old_function)==SUCCESS && old_function->type == ZEND_USER_FUNCTION && old_function->op_array.last > 0) { zend_error(error_level, "Cannot redeclare %s() (previously declared in %s:%d)", function->common.function_name, old_function->op_array.filename, old_function->op_array.opcodes[0].lineno); } else { zend_error(error_level, "Cannot redeclare %s()", function->common.function_name); } return FAILURE; } else { (*function->op_array.refcount)++; function->op_array.static_variables = NULL; /* NULL out the unbound function */ return SUCCESS; } } /* }}} */ void zend_add_trait_precedence(znode *precedence_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_precedences, precedence_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_add_trait_alias(znode *alias_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_aliases, alias_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_prepare_reference(znode *result, znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { zend_trait_method_reference *method_ref = emalloc(sizeof(zend_trait_method_reference)); method_ref->ce = NULL; /* REM: There should not be a need for copying, zend_do_begin_class_declaration is also just using that string */ if (class_name) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); method_ref->class_name = Z_STRVAL(class_name->u.constant); method_ref->cname_len = Z_STRLEN(class_name->u.constant); } else { method_ref->class_name = NULL; method_ref->cname_len = 0; } method_ref->method_name = Z_STRVAL(method_name->u.constant); method_ref->mname_len = Z_STRLEN(method_name->u.constant); result->u.op.ptr = method_ref; result->op_type = IS_TMP_VAR; } /* }}} */ void zend_prepare_trait_alias(znode *result, znode *method_reference, znode *modifiers, znode *alias TSRMLS_DC) /* {{{ */ { zend_trait_alias *trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_alias->modifiers = Z_LVAL(modifiers->u.constant); if (Z_LVAL(modifiers->u.constant) == ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot use 'static' as method modifier"); return; } if (alias) { trait_alias->alias = Z_STRVAL(alias->u.constant); trait_alias->alias_len = Z_STRLEN(alias->u.constant); } else { trait_alias->alias = NULL; } trait_alias->function = NULL; result->u.op.ptr = trait_alias; } /* }}} */ void zend_prepare_trait_precedence(znode *result, znode *method_reference, znode *trait_list TSRMLS_DC) /* {{{ */ { zend_trait_precedence *trait_precedence = emalloc(sizeof(zend_trait_precedence)); trait_precedence->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_precedence->exclude_from_classes = (zend_class_entry**) trait_list->u.op.ptr; trait_precedence->function = NULL; result->u.op.ptr = trait_precedence; } /* }}} */ ZEND_API zend_class_entry *do_bind_class(const zend_op_array* op_array, const zend_op *opline, HashTable *class_table, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } if (zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce)==FAILURE) { zend_error(E_COMPILE_ERROR, "Internal Zend error - Missing class information for %s", Z_STRVAL_P(op1)); return NULL; } else { ce = *pce; } ce->refcount++; if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), &ce, sizeof(zend_class_entry *), NULL)==FAILURE) { ce->refcount--; if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return NULL; } else { if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLEMENT_INTERFACES))) { zend_verify_abstract_class(ce TSRMLS_CC); } return ce; } } /* }}} */ ZEND_API zend_class_entry *do_bind_inherited_class(const zend_op_array *op_array, const zend_op *opline, HashTable *class_table, zend_class_entry *parent_ce, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; int found_ce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } found_ce = zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce); if (found_ce == FAILURE) { if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", Z_STRVAL_P(op2)); } return NULL; } else { ce = *pce; } if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ce->name, parent_ce->name); } else if ((parent_ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ce->name, parent_ce->name); } zend_do_inheritance(ce, parent_ce TSRMLS_CC); ce->refcount++; /* Register the derived class */ if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), pce, sizeof(zend_class_entry *), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return ce; } /* }}} */ void zend_do_early_binding(TSRMLS_D) /* {{{ */ { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; HashTable *table; while (opline->opcode == ZEND_TICKS && opline > CG(active_op_array)->opcodes) { opline--; } switch (opline->opcode) { case ZEND_DECLARE_FUNCTION: if (do_bind_function(CG(active_op_array), opline, CG(function_table), 1) == FAILURE) { return; } table = CG(function_table); break; case ZEND_DECLARE_CLASS: if (do_bind_class(CG(active_op_array), opline, CG(class_table), 1 TSRMLS_CC) == NULL) { return; } table = CG(class_table); break; case ZEND_DECLARE_INHERITED_CLASS: { zend_op *fetch_class_opline = opline-1; zval *parent_name; zend_class_entry **pce; parent_name = &CONSTANT(fetch_class_opline->op2.constant); if ((zend_lookup_class(Z_STRVAL_P(parent_name), Z_STRLEN_P(parent_name), &pce TSRMLS_CC) == FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_CLASSES) && ((*pce)->type == ZEND_INTERNAL_CLASS))) { if (CG(compiler_options) & ZEND_COMPILE_DELAYED_BINDING) { zend_uint *opline_num = &CG(active_op_array)->early_binding; while (*opline_num != -1) { opline_num = &CG(active_op_array)->opcodes[*opline_num].result.opline_num; } *opline_num = opline - CG(active_op_array)->opcodes; opline->opcode = ZEND_DECLARE_INHERITED_CLASS_DELAYED; opline->result_type = IS_UNUSED; opline->result.opline_num = -1; } return; } if (do_bind_inherited_class(CG(active_op_array), opline, CG(class_table), *pce, 1 TSRMLS_CC) == NULL) { return; } /* clear unnecessary ZEND_FETCH_CLASS opcode */ zend_del_literal(CG(active_op_array), fetch_class_opline->op2.constant); MAKE_NOP(fetch_class_opline); table = CG(class_table); break; } case ZEND_VERIFY_ABSTRACT_CLASS: case ZEND_ADD_INTERFACE: case ZEND_ADD_TRAIT: case ZEND_BIND_TRAITS: /* We currently don't early-bind classes that implement interfaces */ /* Classes with traits are handled exactly the same, no early-bind here */ return; default: zend_error(E_COMPILE_ERROR, "Invalid binding type"); return; } zend_hash_quick_del(table, Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant)), Z_HASH_P(&CONSTANT(opline->op1.constant))); zend_del_literal(CG(active_op_array), opline->op1.constant); zend_del_literal(CG(active_op_array), opline->op2.constant); MAKE_NOP(opline); } /* }}} */ ZEND_API void zend_do_delayed_early_binding(const zend_op_array *op_array TSRMLS_DC) /* {{{ */ { if (op_array->early_binding != -1) { zend_bool orig_in_compilation = CG(in_compilation); zend_uint opline_num = op_array->early_binding; zend_class_entry **pce; CG(in_compilation) = 1; while (opline_num != -1) { if (zend_lookup_class(Z_STRVAL_P(op_array->opcodes[opline_num-1].op2.zv), Z_STRLEN_P(op_array->opcodes[opline_num-1].op2.zv), &pce TSRMLS_CC) == SUCCESS) { do_bind_inherited_class(op_array, &op_array->opcodes[opline_num], EG(class_table), *pce, 0 TSRMLS_CC); } opline_num = op_array->opcodes[opline_num].result.opline_num; } CG(in_compilation) = orig_in_compilation; } } /* }}} */ void zend_do_boolean_or_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_or_end(znode *result, const znode *expr1, const znode *expr2, znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_boolean_and_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_and_end(znode *result, const znode *expr1, const znode *expr2, const znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_do_while_begin(TSRMLS_D) /* {{{ */ { do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_do_while_end(const znode *do_token, const znode *expr_open_bracket, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ; SET_NODE(opline->op1, expr); opline->op2.opline_num = do_token->u.op.opline_num; SET_UNUSED(opline->op2); do_end_loop(expr_open_bracket->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_brk_cont(zend_uchar op, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->op1.opline_num = CG(context).current_brk_cont; SET_UNUSED(opline->op1); if (expr) { if (expr->op_type != IS_CONST) { zend_error(E_COMPILE_ERROR, "'%s' operator with non-constant operand is no longer supported", op == ZEND_BRK ? "break" : "continue"); } else if (Z_TYPE(expr->u.constant) != IS_LONG || Z_LVAL(expr->u.constant) < 1) { zend_error(E_COMPILE_ERROR, "'%s' operator accepts only positive numbers", op == ZEND_BRK ? "break" : "continue"); } SET_NODE(opline->op2, expr); } else { LITERAL_LONG(opline->op2, 1); opline->op2_type = IS_CONST; } } /* }}} */ void zend_do_switch_cond(const znode *cond TSRMLS_DC) /* {{{ */ { zend_switch_entry switch_entry; switch_entry.cond = *cond; switch_entry.default_case = -1; switch_entry.control_var = -1; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_switch_end(const znode *case_list TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); /* add code to jmp to default case */ if (switch_entry_ptr->default_case != -1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->op1.opline_num = switch_entry_ptr->default_case; } if (case_list->op_type != IS_UNUSED) { /* non-empty switch */ int next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* remember break/continue loop information */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; if (switch_entry_ptr->cond.op_type==IS_VAR || switch_entry_ptr->cond.op_type==IS_TMP_VAR) { /* emit free for the switch condition*/ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry_ptr->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_UNUSED(opline->op2); } if (switch_entry_ptr->cond.op_type == IS_CONST) { zval_dtor(&switch_entry_ptr->cond.u.constant); } zend_stack_del_top(&CG(switch_cond_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_case_before_statement(const znode *case_list, znode *case_token, const znode *case_expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); int next_op_number; zend_switch_entry *switch_entry_ptr; znode result; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); if (switch_entry_ptr->control_var == -1) { switch_entry_ptr->control_var = get_temporary_variable(CG(active_op_array)); } opline->opcode = ZEND_CASE; opline->result.var = switch_entry_ptr->control_var; opline->result_type = IS_TMP_VAR; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_NODE(opline->op2, case_expr); if (opline->op1_type == IS_CONST) { zval_copy_ctor(&CONSTANT(opline->op1.constant)); } GET_NODE(&result, opline->result); next_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, &result); SET_UNUSED(opline->op2); case_token->u.op.opline_num = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_case_after_statement(znode *result, const znode *case_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); result->u.op.opline_num = next_op_number; switch (CG(active_op_array)->opcodes[case_token->u.op.opline_num].opcode) { case ZEND_JMP: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); break; case ZEND_JMPZ: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); break; } } /* }}} */ void zend_do_default_before_statement(const znode *case_list, znode *default_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); default_token->u.op.opline_num = next_op_number; next_op_number = get_next_op_number(CG(active_op_array)); switch_entry_ptr->default_case = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_begin_class_declaration(const znode *class_token, znode *class_name, const znode *parent_class_name TSRMLS_DC) /* {{{ */ { zend_op *opline; int doing_inheritance = 0; zend_class_entry *new_class_entry; char *lcname; int error = 0; zval **ns_name, key; if (CG(active_class_entry)) { zend_error(E_COMPILE_ERROR, "Class declarations may not be nested"); return; } lcname = zend_str_tolower_dup(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); if (!(strcmp(lcname, "self") && strcmp(lcname, "parent"))) { efree(lcname); zend_error(E_COMPILE_ERROR, "Cannot use '%s' as class name as it is reserved", Z_STRVAL(class_name->u.constant)); } /* Class name must not conflict with import names */ if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns_name) == SUCCESS) { error = 1; } if (CG(current_namespace)) { /* Prefix class name with name of current namespace */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); class_name = &tmp; efree(lcname); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); } if (error) { char *tmp = zend_str_tolower_dup(Z_STRVAL_PP(ns_name), Z_STRLEN_PP(ns_name)); if (Z_STRLEN_PP(ns_name) != Z_STRLEN(class_name->u.constant) || memcmp(tmp, lcname, Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "Cannot declare class %s because the name is already in use", Z_STRVAL(class_name->u.constant)); } efree(tmp); } new_class_entry = emalloc(sizeof(zend_class_entry)); new_class_entry->type = ZEND_USER_CLASS; new_class_entry->name = zend_new_interned_string(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1, 1 TSRMLS_CC); new_class_entry->name_length = Z_STRLEN(class_name->u.constant); zend_initialize_class_data(new_class_entry, 1 TSRMLS_CC); new_class_entry->info.user.filename = zend_get_compiled_filename(TSRMLS_C); new_class_entry->info.user.line_start = class_token->u.op.opline_num; new_class_entry->ce_flags |= class_token->EA; if (parent_class_name && parent_class_name->op_type != IS_UNUSED) { switch (parent_class_name->EA) { case ZEND_FETCH_CLASS_SELF: zend_error(E_COMPILE_ERROR, "Cannot use 'self' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_PARENT: zend_error(E_COMPILE_ERROR, "Cannot use 'parent' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use 'static' as class name as it is reserved"); break; default: break; } doing_inheritance = 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, new_class_entry->name_length TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; if (doing_inheritance) { /* Make sure a trait does not try to extend a class */ if ((new_class_entry->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "A trait (%s) cannot extend a class", new_class_entry->name); } opline->extended_value = parent_class_name->u.op.var; opline->opcode = ZEND_DECLARE_INHERITED_CLASS; } else { opline->opcode = ZEND_DECLARE_CLASS; } LITERAL_STRINGL(opline->op2, lcname, new_class_entry->name_length, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); zend_hash_quick_update(CG(class_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &new_class_entry, sizeof(zend_class_entry *), NULL); CG(active_class_entry) = new_class_entry; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(&CG(implementing_class), opline->result); if (CG(doc_comment)) { CG(active_class_entry)->info.user.doc_comment = CG(doc_comment); CG(active_class_entry)->info.user.doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ static void do_verify_abstract_class(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_VERIFY_ABSTRACT_CLASS; SET_NODE(opline->op1, &CG(implementing_class)); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_class_declaration(const znode *class_token, const znode *parent_token TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); if (ce->constructor) { ce->constructor->common.fn_flags |= ZEND_ACC_CTOR; if (ce->constructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Constructor %s::%s() cannot be static", ce->name, ce->constructor->common.function_name); } } if (ce->destructor) { ce->destructor->common.fn_flags |= ZEND_ACC_DTOR; if (ce->destructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Destructor %s::%s() cannot be static", ce->name, ce->destructor->common.function_name); } } if (ce->clone) { ce->clone->common.fn_flags |= ZEND_ACC_CLONE; if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static", ce->name, ce->clone->common.function_name); } } ce->info.user.line_end = zend_get_compiled_lineno(TSRMLS_C); /* Check for traits and proceed like with interfaces. * The only difference will be a combined handling of them in the end. * Thus, we need another opcode here. */ if (ce->num_traits > 0) { zend_op *opline; ce->traits = NULL; ce->num_traits = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_TRAITS; /* opcode generation: */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BIND_TRAITS; SET_NODE(opline->op1, &CG(implementing_class)); } if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) && ((parent_token->op_type != IS_UNUSED) || (ce->num_interfaces > 0))) { zend_verify_abstract_class(ce TSRMLS_CC); if (ce->num_interfaces) { do_verify_abstract_class(TSRMLS_C); } } /* Inherit interfaces; reset number to zero, we need it for above check and * will restore it during actual implementation. * The ZEND_ACC_IMPLEMENT_INTERFACES flag disables double call to * zend_verify_abstract_class() */ if (ce->num_interfaces > 0) { ce->interfaces = NULL; ce->num_interfaces = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_INTERFACES; } CG(active_class_entry) = NULL; } /* }}} */ void zend_do_implements_interface(znode *interface_name TSRMLS_DC) /* {{{ */ { zend_op *opline; /* Traits can not implement interfaces */ if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface on '%s' since it is a Trait", Z_STRVAL(interface_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(interface_name->u.constant), Z_STRLEN(interface_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface name as it is reserved", Z_STRVAL(interface_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_INTERFACE; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(interface_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = (opline->extended_value & ~ZEND_FETCH_CLASS_MASK) | ZEND_FETCH_CLASS_INTERFACE; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &interface_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_interfaces++; } /* }}} */ void zend_do_implements_trait(znode *trait_name TSRMLS_DC) /* {{{ */ { zend_op *opline; if ((CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Cannot use traits inside of interfaces. %s is used in %s", Z_STRVAL(trait_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(trait_name->u.constant), Z_STRLEN(trait_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as trait name as it is reserved", Z_STRVAL(trait_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_TRAIT; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(trait_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = ZEND_FETCH_CLASS_TRAIT; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &trait_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_traits++; } /* }}} */ ZEND_API void zend_mangle_property_name(char **dest, int *dest_length, const char *src1, int src1_length, const char *src2, int src2_length, int internal) /* {{{ */ { char *prop_name; int prop_name_length; prop_name_length = 1 + src1_length + 1 + src2_length; prop_name = pemalloc(prop_name_length + 1, internal); prop_name[0] = '\0'; memcpy(prop_name + 1, src1, src1_length+1); memcpy(prop_name + 1 + src1_length + 1, src2, src2_length+1); *dest = prop_name; *dest_length = prop_name_length; } /* }}} */ static int zend_strnlen(const char* s, int maxlen) /* {{{ */ { int len = 0; while (*s++ && maxlen--) len++; return len; } /* }}} */ ZEND_API int zend_unmangle_property_name(const char *mangled_property, int len, const char **class_name, const char **prop_name) /* {{{ */ { int class_name_len; *class_name = NULL; if (mangled_property[0]!=0) { *prop_name = mangled_property; return SUCCESS; } if (len < 3 || mangled_property[1]==0) { zend_error(E_NOTICE, "Illegal member variable name"); *prop_name = mangled_property; return FAILURE; } class_name_len = zend_strnlen(mangled_property+1, --len - 1) + 1; if (class_name_len >= len || mangled_property[class_name_len]!=0) { zend_error(E_NOTICE, "Corrupt member variable name"); *prop_name = mangled_property; return FAILURE; } *class_name = mangled_property+1; *prop_name = (*class_name)+class_name_len; return SUCCESS; } /* }}} */ void zend_do_declare_property(const znode *var_name, const znode *value, zend_uint access_type TSRMLS_DC) /* {{{ */ { zval *property; zend_property_info *existing_property_info; char *comment = NULL; int comment_len = 0; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Interfaces may not include member variables"); } if (access_type & ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Properties cannot be declared abstract"); } if (access_type & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot declare property %s::$%s final, the final modifier is allowed only for methods and classes", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } if (zend_hash_find(&CG(active_class_entry)->properties_info, var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, (void **) &existing_property_info)==SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::$%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } ALLOC_ZVAL(property); if (value) { *property = value->u.constant; } else { INIT_PZVAL(property); Z_TYPE_P(property) = IS_NULL; } if (CG(doc_comment)) { comment = CG(doc_comment); comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } zend_declare_property_ex(CG(active_class_entry), zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len + 1, 0 TSRMLS_CC), var_name->u.constant.value.str.len, property, access_type, comment, comment_len TSRMLS_CC); efree(var_name->u.constant.value.str.val); } /* }}} */ void zend_do_declare_class_constant(znode *var_name, const znode *value TSRMLS_DC) /* {{{ */ { zval *property; const char *cname = NULL; int result; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed in class constants"); return; } if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Traits cannot have constants"); return; } ALLOC_ZVAL(property); *property = value->u.constant; cname = zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, 0 TSRMLS_CC); if (IS_INTERNED(cname)) { result = zend_hash_quick_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, INTERNED_HASH(cname), &property, sizeof(zval *), NULL); } else { result = zend_hash_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, &property, sizeof(zval *), NULL); } if (result == FAILURE) { FREE_ZVAL(property); zend_error(E_COMPILE_ERROR, "Cannot redefine class constant %s::%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } FREE_PNODE(var_name); if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_fetch_property(znode *result, znode *object, const znode *property TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (object->op_type == IS_CV) { if (object->u.op.var == CG(active_op_array)->this_var) { object->op_type = IS_UNUSED; /* this means $this for objects */ } } else if (fetch_list_ptr->count == 1) { zend_llist_element *le = fetch_list_ptr->head; zend_op *opline_ptr = (zend_op *) le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); SET_UNUSED(opline_ptr->op1); /* this means $this for objects */ SET_NODE(opline_ptr->op2, property); /* if it was usual fetch, we change it to object fetch */ switch (opline_ptr->opcode) { case ZEND_FETCH_W: opline_ptr->opcode = ZEND_FETCH_OBJ_W; break; case ZEND_FETCH_R: opline_ptr->opcode = ZEND_FETCH_OBJ_R; break; case ZEND_FETCH_RW: opline_ptr->opcode = ZEND_FETCH_OBJ_RW; break; case ZEND_FETCH_IS: opline_ptr->opcode = ZEND_FETCH_OBJ_IS; break; case ZEND_FETCH_UNSET: opline_ptr->opcode = ZEND_FETCH_OBJ_UNSET; break; case ZEND_FETCH_FUNC_ARG: opline_ptr->opcode = ZEND_FETCH_OBJ_FUNC_ARG; break; } if (opline_ptr->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline_ptr->op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline_ptr->op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op2.constant); } GET_NODE(result, opline_ptr->result); return; } } if (zend_is_function_or_method_call(object)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, object); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_OBJ_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, object); SET_NODE(opline.op2, property); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline.op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op2.constant); } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void zend_do_halt_compiler_register(TSRMLS_D) /* {{{ */ { char *name, *cfilename; char haltoff[] = "__COMPILER_HALT_OFFSET__"; int len, clen; cfilename = zend_get_compiled_filename(TSRMLS_C); clen = strlen(cfilename); zend_mangle_property_name(&name, &len, haltoff, sizeof(haltoff) - 1, cfilename, clen, 0); zend_register_long_constant(name, len+1, zend_get_scanned_file_offset(TSRMLS_C), CONST_CS, 0 TSRMLS_CC); pefree(name, 0); if (CG(in_namespace)) { zend_do_end_namespace(TSRMLS_C); } } /* }}} */ void zend_do_push_object(const znode *object TSRMLS_DC) /* {{{ */ { zend_stack_push(&CG(object_stack), object, sizeof(znode)); } /* }}} */ void zend_do_pop_object(znode *object TSRMLS_DC) /* {{{ */ { if (object) { znode *tmp; zend_stack_top(&CG(object_stack), (void **) &tmp); *object = *tmp; } zend_stack_del_top(&CG(object_stack)); } /* }}} */ void zend_do_begin_new_object(znode *new_token, znode *class_type TSRMLS_DC) /* {{{ */ { zend_op *opline; unsigned char *ptr = NULL; new_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_NEW; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, class_type); SET_UNUSED(opline->op2); zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(unsigned char *)); } /* }}} */ void zend_do_end_new_object(znode *result, const znode *new_token, const znode *argument_list TSRMLS_DC) /* {{{ */ { znode ctor_result; zend_do_end_function_call(NULL, &ctor_result, argument_list, 1, 0 TSRMLS_CC); zend_do_free(&ctor_result TSRMLS_CC); CG(active_op_array)->opcodes[new_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, CG(active_op_array)->opcodes[new_token->u.op.opline_num].result); } /* }}} */ static zend_constant* zend_get_ct_const(const zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = NULL; if (Z_STRVAL_P(const_name)[0] == '\\') { if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name), (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name)-1); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name), (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } } else if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)+1, (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name)+1, (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } if (c->flags & CONST_CT_SUBST) { return c; } if (all_internal_constants_substitution && (c->flags & CONST_PERSISTENT) && !(CG(compiler_options) & ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION) && Z_TYPE(c->value) != IS_CONSTANT && Z_TYPE(c->value) != IS_CONSTANT_ARRAY) { return c; } return NULL; } /* }}} */ static int zend_constant_ct_subst(znode *result, zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = zend_get_ct_const(const_name, all_internal_constants_substitution TSRMLS_CC); if (c) { zval_dtor(const_name); result->op_type = IS_CONST; result->u.constant = c->value; zval_copy_ctor(&result->u.constant); INIT_PZVAL(&result->u.constant); return 1; } return 0; } /* }}} */ void zend_do_fetch_constant(znode *result, znode *constant_container, znode *constant_name, int mode, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; zend_op *opline; int type; char *compound; ulong fetch_type = 0; if (constant_container) { switch (mode) { case ZEND_CT: /* this is a class constant */ type = zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant)); if (ZEND_FETCH_CLASS_STATIC == type) { zend_error(E_ERROR, "\"static::\" is not allowed in compile-time constants"); } else if (ZEND_FETCH_CLASS_DEFAULT == type) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } zend_do_build_full_name(NULL, constant_container, constant_name, 1 TSRMLS_CC); *result = *constant_container; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: if (constant_container->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant))) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } else { zend_do_fetch_class(&tmp, constant_container TSRMLS_CC); constant_container = &tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); if (constant_container->op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &constant_container->u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, constant_container); } SET_NODE(opline->op2, constant_name); CALCULATE_LITERAL_HASH(opline->op2.constant); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } GET_NODE(result, opline->result); break; } return; } /* namespace constant */ /* only one that did not contain \ from the start can be converted to string if unknown */ switch (mode) { case ZEND_CT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); /* this is a namespace constant, or an unprefixed constant */ if (zend_constant_ct_subst(result, &constant_name->u.constant, 0 TSRMLS_CC)) { break; } zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(!compound) { fetch_type |= IS_CONSTANT_UNQUALIFIED; } *result = *constant_name; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(zend_constant_ct_subst(result, &constant_name->u.constant, 1 TSRMLS_CC)) { break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; if (compound) { /* the name is unambiguous */ opline->extended_value = 0; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } else { opline->extended_value = IS_CONSTANT_UNQUALIFIED; if (CG(current_namespace)) { opline->extended_value |= IS_CONSTANT_IN_NAMESPACE; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 1 TSRMLS_CC); } else { opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } } GET_CACHE_SLOT(opline->op2.constant); break; } } /* }}} */ void zend_do_shell_exec(znode *result, const znode *cmd TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); switch (cmd->op_type) { case IS_CONST: case IS_TMP_VAR: opline->opcode = ZEND_SEND_VAL; break; default: opline->opcode = ZEND_SEND_VAR; break; } SET_NODE(opline->op1, cmd); opline->op2.opline_num = 0; opline->extended_value = ZEND_DO_FCALL; SET_UNUSED(opline->op2); /* FIXME: exception support not added to this op2 */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DO_FCALL; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; LITERAL_STRINGL(opline->op1, estrndup("shell_exec", sizeof("shell_exec")-1), sizeof("shell_exec")-1, 0); CALCULATE_LITERAL_HASH(opline->op1.constant); opline->op1_type = IS_CONST; GET_CACHE_SLOT(opline->op1.constant); opline->extended_value = 1; SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_init_array(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_ARRAY; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; GET_NODE(result, opline->result); if (expr) { SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } } else { SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_array_element(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_ARRAY_ELEMENT; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_static_array_element(znode *result, znode *offset, const znode *expr) /* {{{ */ { zval *element; ALLOC_ZVAL(element); *element = expr->u.constant; if (offset) { switch (offset->u.constant.type & IS_CONSTANT_TYPE_MASK) { case IS_CONSTANT: /* Ugly hack to denote that this value has a constant index */ Z_TYPE_P(element) |= IS_CONSTANT_INDEX; Z_STRVAL(offset->u.constant) = erealloc(Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+1] = Z_TYPE(offset->u.constant); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+2] = 0; zend_symtable_update(result->u.constant.value.ht, Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_STRING: zend_symtable_update(result->u.constant.value.ht, offset->u.constant.value.str.val, offset->u.constant.value.str.len+1, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_NULL: zend_symtable_update(Z_ARRVAL(result->u.constant), "", 1, &element, sizeof(zval *), NULL); break; case IS_LONG: case IS_BOOL: zend_hash_index_update(Z_ARRVAL(result->u.constant), Z_LVAL(offset->u.constant), &element, sizeof(zval *), NULL); break; case IS_DOUBLE: zend_hash_index_update(Z_ARRVAL(result->u.constant), zend_dval_to_lval(Z_DVAL(offset->u.constant)), &element, sizeof(zval *), NULL); break; case IS_CONSTANT_ARRAY: zend_error(E_ERROR, "Illegal offset type"); break; } } else { zend_hash_next_index_insert(Z_ARRVAL(result->u.constant), &element, sizeof(zval *), NULL); } } /* }}} */ void zend_do_add_list_element(const znode *element TSRMLS_DC) /* {{{ */ { list_llist_element lle; if (element) { zend_check_writable_variable(element); lle.var = *element; zend_llist_copy(&lle.dimensions, &CG(dimension_llist)); zend_llist_prepend_element(&CG(list_llist), &lle); } (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_new_list_begin(TSRMLS_D) /* {{{ */ { int current_dimension = 0; zend_llist_add_element(&CG(dimension_llist), &current_dimension); } /* }}} */ void zend_do_new_list_end(TSRMLS_D) /* {{{ */ { zend_llist_remove_tail(&CG(dimension_llist)); (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_list_init(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(list_stack), &CG(list_llist), sizeof(zend_llist)); zend_stack_push(&CG(list_stack), &CG(dimension_llist), sizeof(zend_llist)); zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_do_new_list_begin(TSRMLS_C); } /* }}} */ void zend_do_list_end(znode *result, znode *expr TSRMLS_DC) /* {{{ */ { zend_llist_element *le; zend_llist_element *dimension; zend_op *opline; znode last_container; le = CG(list_llist).head; while (le) { zend_llist *tmp_dimension_llist = &((list_llist_element *)le->data)->dimensions; dimension = tmp_dimension_llist->head; while (dimension) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (dimension == tmp_dimension_llist->head) { /* first */ last_container = *expr; switch (expr->op_type) { case IS_VAR: case IS_CV: opline->opcode = ZEND_FETCH_DIM_R; break; case IS_TMP_VAR: opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; case IS_CONST: /* fetch_dim_tmp_var will handle this bogus fetch */ zval_copy_ctor(&expr->u.constant); opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; } opline->extended_value |= ZEND_FETCH_ADD_LOCK; } else { opline->opcode = ZEND_FETCH_DIM_R; } opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, &last_container); opline->op2_type = IS_CONST; LITERAL_LONG(opline->op2, *((int *) dimension->data)); GET_NODE(&last_container, opline->result); dimension = dimension->next; } ((list_llist_element *) le->data)->value = last_container; zend_llist_destroy(&((list_llist_element *) le->data)->dimensions); zend_do_assign(result, &((list_llist_element *) le->data)->var, &((list_llist_element *) le->data)->value TSRMLS_CC); zend_do_free(result TSRMLS_CC); le = le->next; } zend_llist_destroy(&CG(dimension_llist)); zend_llist_destroy(&CG(list_llist)); *result = *expr; { zend_llist *p; /* restore previous lists */ zend_stack_top(&CG(list_stack), (void **) &p); CG(dimension_llist) = *p; zend_stack_del_top(&CG(list_stack)); zend_stack_top(&CG(list_stack), (void **) &p); CG(list_llist) = *p; zend_stack_del_top(&CG(list_stack)); } } /* }}} */ void zend_init_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = emalloc(sizeof(void*) * 2); list[0] = item; list[1] = NULL; *(void**)result = list; } /* }}} */ void zend_add_to_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = *(void**)result; size_t n = 0; while (list && list[n]) { n++; } list = erealloc(list, sizeof(void*) * (n+2)); list[n] = item; list[n+1] = NULL; *(void**)result = list; } /* }}} */ void zend_do_fetch_static_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zval *tmp; zend_op *opline; znode lval; znode result; ALLOC_ZVAL(tmp); if (static_assignment) { *tmp = static_assignment->u.constant; } else { INIT_ZVAL(*tmp); } if (!CG(active_op_array)->static_variables) { if (CG(active_op_array)->scope) { CG(active_op_array)->scope->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } ALLOC_HASHTABLE(CG(active_op_array)->static_variables); zend_hash_init(CG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } zend_hash_update(CG(active_op_array)->static_variables, varname->u.constant.value.str.val, varname->u.constant.value.str.len+1, &tmp, sizeof(zval *), NULL); if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (fetch_type == ZEND_FETCH_LEXICAL) ? ZEND_FETCH_R : ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_STATIC; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ if (fetch_type == ZEND_FETCH_LEXICAL) { znode dummy; zend_do_begin_variable_parse(TSRMLS_C); zend_do_assign(&dummy, &lval, &result TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } else { zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); } CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_fetch_lexical_variable(znode *varname, zend_bool is_ref TSRMLS_DC) /* {{{ */ { znode value; if (Z_STRLEN(varname->u.constant) == sizeof("this") - 1 && memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this") - 1) == 0) { zend_error(E_COMPILE_ERROR, "Cannot use $this as lexical variable"); return; } value.op_type = IS_CONST; ZVAL_NULL(&value.u.constant); Z_TYPE(value.u.constant) |= is_ref ? IS_LEXICAL_REF : IS_LEXICAL_VAR; Z_SET_REFCOUNT_P(&value.u.constant, 1); Z_UNSET_ISREF_P(&value.u.constant); zend_do_fetch_static_variable(varname, &value, is_ref ? ZEND_FETCH_STATIC : ZEND_FETCH_LEXICAL TSRMLS_CC); } /* }}} */ void zend_do_fetch_global_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zend_op *opline; znode lval; znode result; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = fetch_type; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_cast(znode *result, const znode *expr, int type TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CAST; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } /* }}} */ void zend_do_include_or_eval(int type, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_do_extended_fcall_begin(TSRMLS_C); { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INCLUDE_OR_EVAL; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } zend_do_extended_fcall_end(TSRMLS_C); } /* }}} */ void zend_do_indirect_references(znode *result, const znode *num_references, znode *variable TSRMLS_DC) /* {{{ */ { int i; zend_do_end_variable_parse(variable, BP_VAR_R, 0 TSRMLS_CC); for (i=1; i<num_references->u.constant.value.lval; i++) { fetch_simple_variable_ex(result, variable, 0, ZEND_FETCH_R TSRMLS_CC); *variable = *result; } zend_do_begin_variable_parse(TSRMLS_C); fetch_simple_variable(result, variable, 1 TSRMLS_CC); /* there is a chance someone is accessing $this */ if (CG(active_op_array)->scope && CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } /* }}} */ void zend_do_unset(const znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_UNSET_VAR; SET_NODE(opline->op1, variable); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); opline->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_UNSET: last_op->opcode = ZEND_UNSET_VAR; SET_UNUSED(last_op->result); break; case ZEND_FETCH_DIM_UNSET: last_op->opcode = ZEND_UNSET_DIM; SET_UNUSED(last_op->result); break; case ZEND_FETCH_OBJ_UNSET: last_op->opcode = ZEND_UNSET_OBJ; SET_UNUSED(last_op->result); break; } } } /* }}} */ void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_do_end_variable_parse(variable, BP_VAR_IS, 0 TSRMLS_CC); zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { last_op = get_next_op(CG(active_op_array) TSRMLS_CC); last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; SET_NODE(last_op->op1, variable); SET_UNUSED(last_op->op2); last_op->result.var = get_temporary_variable(CG(active_op_array)); last_op->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; break; case ZEND_FETCH_DIM_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_DIM_OBJ; break; case ZEND_FETCH_OBJ_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_PROP_OBJ; break; } } last_op->result_type = IS_TMP_VAR; last_op->extended_value |= type; GET_NODE(result, last_op->result); } /* }}} */ void zend_do_instanceof(znode *result, const znode *expr, const znode *class_znode, int type TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline->opcode == ZEND_FETCH_CLASS) { opline->extended_value |= ZEND_FETCH_CLASS_NO_AUTOLOAD; } } if (expr->op_type == IS_CONST) { zend_error(E_COMPILE_ERROR, "instanceof expects an object instance, constant given"); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INSTANCEOF; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_NODE(opline->op2, class_znode); GET_NODE(result, opline->result); } /* }}} */ void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_bool is_variable; zend_bool push_container = 0; zend_op dummy_opline; if (variable) { if (zend_is_function_or_method_call(array)) { is_variable = 0; } else { is_variable = 1; } /* save the location of FETCH_W instruction(s) */ open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); zend_do_end_variable_parse(array, BP_VAR_W, 0 TSRMLS_CC); if (CG(active_op_array)->last > 0 && CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) { /* Only lock the container if we are fetching from a real container and not $this */ if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1_type == IS_VAR) { CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK; push_container = 1; } } } else { is_variable = 0; open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* save the location of FE_RESET */ foreach_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* Preform array reset */ opline->opcode = ZEND_FE_RESET; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, array); SET_UNUSED(opline->op2); opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0; COPY_NODE(dummy_opline.result, opline->result); if (push_container) { COPY_NODE(dummy_opline.op1, CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1); } else { dummy_opline.op1_type = IS_UNUSED; } zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); /* save the location of FE_FETCH */ as_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FE_FETCH; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); COPY_NODE(opline->op1, dummy_opline.result); opline->extended_value = 0; SET_UNUSED(opline->op2); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_OP_DATA; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); } /* }}} */ void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC) /* {{{ */ { zend_op *opline; znode dummy, value_node; zend_bool assign_by_ref=0; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num]; if (key->op_type != IS_UNUSED) { znode *tmp; /* switch between the key and value... */ tmp = key; key = value; value = tmp; /* Mark extended_value in case both key and value are being used */ opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; } if ((key->op_type != IS_UNUSED) && (key->EA & ZEND_PARSED_REFERENCE_VARIABLE)) { zend_error(E_COMPILE_ERROR, "Key element cannot be a reference"); } if (value->EA & ZEND_PARSED_REFERENCE_VARIABLE) { assign_by_ref = 1; if (!(opline-1)->extended_value) { zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression"); } /* Mark extended_value for assign-by-reference */ opline->extended_value |= ZEND_FE_FETCH_BYREF; CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; } else { zend_op *foreach_copy; zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.op.opline_num]; zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.op.opline_num]; /* Change "write context" into "read context" */ fetch->extended_value = 0; /* reset ZEND_FE_RESET_VARIABLE */ while (fetch != end) { --fetch; if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } if (fetch->opcode == ZEND_SEPARATE) { MAKE_NOP(fetch); } else { fetch->opcode -= 3; /* FETCH_W -> FETCH_R */ } } /* prevent double SWITCH_FREE */ zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy); foreach_copy->op1_type = IS_UNUSED; } GET_NODE(&value_node, opline->result); if (assign_by_ref) { zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); /* Mark FE_FETCH as IS_VAR as it holds the data directly as a value */ zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC); } else { zend_do_assign(&dummy, value, &value_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } if (key->op_type != IS_UNUSED) { znode key_node; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num+1]; opline->result_type = IS_TMP_VAR; opline->result.opline_num = get_temporary_variable(CG(active_op_array)); GET_NODE(&key_node, opline->result); zend_do_assign(&dummy, key, &key_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_foreach_end(const znode *foreach_token, const znode *as_token TSRMLS_DC) /* {{{ */ { zend_op *container_ptr; zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = as_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_RESET */ CG(active_op_array)->opcodes[as_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_FETCH */ do_end_loop(as_token->u.op.opline_num, 1 TSRMLS_CC); zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr); generate_free_foreach_copy(container_ptr TSRMLS_CC); zend_stack_del_top(&CG(foreach_copy_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_declare_begin(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(declare_stack), &CG(declarables), sizeof(zend_declarables)); } /* }}} */ void zend_do_declare_stmt(znode *var, znode *val TSRMLS_DC) /* {{{ */ { if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "ticks", sizeof("ticks")-1)) { convert_to_long(&val->u.constant); CG(declarables).ticks = val->u.constant; } else if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "encoding", sizeof("encoding")-1)) { if ((Z_TYPE(val->u.constant) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Cannot use constants as encoding"); } /* * Check that the pragma comes before any opcodes. If the compilation * got as far as this, the previous portion of the script must have been * parseable according to the .ini script_encoding setting. We still * want to tell them to put declare() at the top. */ { int num = CG(active_op_array)->last; /* ignore ZEND_EXT_STMT and ZEND_TICKS */ while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Encoding declaration pragma must be the very first statement in the script"); } } if (CG(multibyte)) { const zend_encoding *new_encoding, *old_encoding; zend_encoding_filter old_input_filter; CG(encoding_declared) = 1; convert_to_string(&val->u.constant); new_encoding = zend_multibyte_fetch_encoding(val->u.constant.value.str.val TSRMLS_CC); if (!new_encoding) { zend_error(E_COMPILE_WARNING, "Unsupported encoding [%s]", val->u.constant.value.str.val); } else { old_input_filter = LANG_SCNG(input_filter); old_encoding = LANG_SCNG(script_encoding); zend_multibyte_set_filter(new_encoding TSRMLS_CC); /* need to re-scan if input filter changed */ if (old_input_filter != LANG_SCNG(input_filter) || (old_input_filter && new_encoding != old_encoding)) { zend_multibyte_yyinput_again(old_input_filter, old_encoding TSRMLS_CC); } } } else { zend_error(E_COMPILE_WARNING, "declare(encoding=...) ignored because Zend multibyte feature is turned off by settings"); } zval_dtor(&val->u.constant); } else { zend_error(E_COMPILE_WARNING, "Unsupported declare '%s'", var->u.constant.value.str.val); zval_dtor(&val->u.constant); } zval_dtor(&var->u.constant); } /* }}} */ void zend_do_declare_end(const znode *declare_token TSRMLS_DC) /* {{{ */ { zend_declarables *declarables; zend_stack_top(&CG(declare_stack), (void **) &declarables); /* We should restore if there was more than (current - start) - (ticks?1:0) opcodes */ if ((get_next_op_number(CG(active_op_array)) - declare_token->u.op.opline_num) - ((Z_LVAL(CG(declarables).ticks))?1:0)) { CG(declarables) = *declarables; } } /* }}} */ void zend_do_exit(znode *result, const znode *message TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXIT; SET_NODE(opline->op1, message); SET_UNUSED(opline->op2); result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_BOOL; Z_LVAL(result->u.constant) = 1; } /* }}} */ void zend_do_begin_silence(znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BEGIN_SILENCE; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); GET_NODE(strudel_token, opline->result); } /* }}} */ void zend_do_end_silence(const znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_END_SILENCE; SET_NODE(opline->op1, strudel_token); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_jmp_set(const znode *value, znode *jmp_token, znode *colon_token TSRMLS_DC) /* {{{ */ { int op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (value->op_type == IS_VAR || value->op_type == IS_CV) { opline->opcode = ZEND_JMP_SET_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_JMP_SET; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, value); SET_UNUSED(opline->op2); GET_NODE(colon_token, opline->result); jmp_token->u.op .opline_num = op_number; INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_jmp_set_else(znode *result, const znode *false_value, const znode *jmp_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, colon_token); if (colon_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].opcode = ZEND_JMP_SET_VAR; CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } opline->extended_value = 0; SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_qm_op(const znode *cond, znode *qm_token TSRMLS_DC) /* {{{ */ { int jmpz_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); SET_UNUSED(opline->op2); opline->op2.opline_num = jmpz_op_number; GET_NODE(qm_token, opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_qm_true(const znode *true_value, znode *qm_token, znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->opcodes[qm_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array))+1; /* jmp over the ZEND_JMP */ if (true_value->op_type == IS_VAR || true_value->op_type == IS_CV) { opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, true_value); SET_UNUSED(opline->op2); GET_NODE(qm_token, opline->result); colon_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_qm_false(znode *result, const znode *false_value, const znode *qm_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, qm_token); if (qm_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].opcode = ZEND_QM_ASSIGN_VAR; CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[colon_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, opline->result); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_extended_info(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_STMT; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_begin(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_BEGIN; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_end(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_END; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_ticks(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_TICKS; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->extended_value = Z_LVAL(CG(declarables).ticks); } /* }}} */ zend_bool zend_is_auto_global_quick(const char *name, uint name_len, ulong hashval TSRMLS_DC) /* {{{ */ { zend_auto_global *auto_global; ulong hash = hashval ? hashval : zend_hash_func(name, name_len+1); if (zend_hash_quick_find(CG(auto_globals), name, name_len+1, hash, (void **) &auto_global)==SUCCESS) { if (auto_global->armed) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } return 1; } return 0; } /* }}} */ zend_bool zend_is_auto_global(const char *name, uint name_len TSRMLS_DC) /* {{{ */ { return zend_is_auto_global_quick(name, name_len, 0 TSRMLS_CC); } /* }}} */ int zend_register_auto_global(const char *name, uint name_len, zend_bool jit, zend_auto_global_callback auto_global_callback TSRMLS_DC) /* {{{ */ { zend_auto_global auto_global; auto_global.name = zend_new_interned_string((char*)name, name_len + 1, 0 TSRMLS_CC); auto_global.name_len = name_len; auto_global.auto_global_callback = auto_global_callback; auto_global.jit = jit; return zend_hash_add(CG(auto_globals), name, name_len+1, &auto_global, sizeof(zend_auto_global), NULL); } /* }}} */ static int zend_auto_global_init(zend_auto_global *auto_global TSRMLS_DC) /* {{{ */ { if (auto_global->jit) { auto_global->armed = 1; } else if (auto_global->auto_global_callback) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } else { auto_global->armed = 0; } return 0; } /* }}} */ ZEND_API void zend_activate_auto_globals(TSRMLS_D) /* {{{ */ { zend_hash_apply(CG(auto_globals), (apply_func_t) zend_auto_global_init TSRMLS_CC); } /* }}} */ int zendlex(znode *zendlval TSRMLS_DC) /* {{{ */ { int retval; if (CG(increment_lineno)) { CG(zend_lineno)++; CG(increment_lineno) = 0; } again: Z_TYPE(zendlval->u.constant) = IS_LONG; retval = lex_scan(&zendlval->u.constant TSRMLS_CC); switch (retval) { case T_COMMENT: case T_DOC_COMMENT: case T_OPEN_TAG: case T_WHITESPACE: goto again; case T_CLOSE_TAG: if (LANG_SCNG(yy_text)[LANG_SCNG(yy_leng)-1] != '>') { CG(increment_lineno) = 1; } if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { goto again; } retval = ';'; /* implicit ; */ break; case T_OPEN_TAG_WITH_ECHO: retval = T_ECHO; break; case T_END_HEREDOC: efree(Z_STRVAL(zendlval->u.constant)); break; } INIT_PZVAL(&zendlval->u.constant); zendlval->op_type = IS_CONST; return retval; } /* }}} */ ZEND_API void zend_initialize_class_data(zend_class_entry *ce, zend_bool nullify_handlers TSRMLS_DC) /* {{{ */ { zend_bool persistent_hashes = (ce->type == ZEND_INTERNAL_CLASS) ? 1 : 0; dtor_func_t zval_ptr_dtor_func = ((persistent_hashes) ? ZVAL_INTERNAL_PTR_DTOR : ZVAL_PTR_DTOR); ce->refcount = 1; ce->ce_flags = 0; ce->default_properties_table = NULL; ce->default_static_members_table = NULL; zend_hash_init_ex(&ce->properties_info, 0, NULL, (dtor_func_t) (persistent_hashes ? zend_destroy_property_info_internal : zend_destroy_property_info), persistent_hashes, 0); zend_hash_init_ex(&ce->constants_table, 0, NULL, zval_ptr_dtor_func, persistent_hashes, 0); zend_hash_init_ex(&ce->function_table, 0, NULL, ZEND_FUNCTION_DTOR, persistent_hashes, 0); if (ce->type == ZEND_INTERNAL_CLASS) { #ifdef ZTS int n = zend_hash_num_elements(CG(class_table)); if (CG(static_members_table) && n >= CG(last_static_member)) { /* Support for run-time declaration: dl() */ CG(last_static_member) = n+1; CG(static_members_table) = realloc(CG(static_members_table), (n+1)*sizeof(zval**)); CG(static_members_table)[n] = NULL; } ce->static_members_table = (zval**)(zend_intptr_t)n; #else ce->static_members_table = NULL; #endif } else { ce->static_members_table = ce->default_static_members_table; ce->info.user.doc_comment = NULL; ce->info.user.doc_comment_len = 0; } ce->default_properties_count = 0; ce->default_static_members_count = 0; if (nullify_handlers) { ce->constructor = NULL; ce->destructor = NULL; ce->clone = NULL; ce->__get = NULL; ce->__set = NULL; ce->__unset = NULL; ce->__isset = NULL; ce->__call = NULL; ce->__callstatic = NULL; ce->__tostring = NULL; ce->create_object = NULL; ce->get_iterator = NULL; ce->iterator_funcs.funcs = NULL; ce->interface_gets_implemented = NULL; ce->get_static_method = NULL; ce->parent = NULL; ce->num_interfaces = 0; ce->interfaces = NULL; ce->num_traits = 0; ce->traits = NULL; ce->trait_aliases = NULL; ce->trait_precedences = NULL; ce->serialize = NULL; ce->unserialize = NULL; ce->serialize_func = NULL; ce->unserialize_func = NULL; if (ce->type == ZEND_INTERNAL_CLASS) { ce->info.internal.module = NULL; ce->info.internal.builtin_functions = NULL; } } } /* }}} */ int zend_get_class_fetch_type(const char *class_name, uint class_name_len) /* {{{ */ { if ((class_name_len == sizeof("self")-1) && !memcmp(class_name, "self", sizeof("self")-1)) { return ZEND_FETCH_CLASS_SELF; } else if ((class_name_len == sizeof("parent")-1) && !memcmp(class_name, "parent", sizeof("parent")-1)) { return ZEND_FETCH_CLASS_PARENT; } else if ((class_name_len == sizeof("static")-1) && !memcmp(class_name, "static", sizeof("static")-1)) { return ZEND_FETCH_CLASS_STATIC; } else { return ZEND_FETCH_CLASS_DEFAULT; } } /* }}} */ ZEND_API const char* zend_get_compiled_variable_name(const zend_op_array *op_array, zend_uint var, int* name_len) /* {{{ */ { if (name_len) { *name_len = op_array->vars[var].name_len; } return op_array->vars[var].name; } /* }}} */ void zend_do_build_namespace_name(znode *result, znode *prefix, znode *name TSRMLS_DC) /* {{{ */ { if (prefix) { *result = *prefix; if (Z_TYPE(result->u.constant) == IS_STRING && Z_STRLEN(result->u.constant) == 0) { /* namespace\ */ if (CG(current_namespace)) { znode tmp; zval_dtor(&result->u.constant); tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(result, NULL, &tmp TSRMLS_CC); } } } else { result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_STRING; Z_STRVAL(result->u.constant) = NULL; Z_STRLEN(result->u.constant) = 0; } /* prefix = result */ zend_do_build_full_name(NULL, result, name, 0 TSRMLS_CC); } /* }}} */ void zend_do_begin_namespace(const znode *name, zend_bool with_bracket TSRMLS_DC) /* {{{ */ { char *lcname; /* handle mixed syntax declaration or nested namespaces */ if (!CG(has_bracketed_namespaces)) { if (CG(current_namespace)) { /* previous namespace declarations were unbracketed */ if (with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } } } else { /* previous namespace declarations were bracketed */ if (!with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } else if (CG(current_namespace) || CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "Namespace declarations cannot be nested"); } } if (((!with_bracket && !CG(current_namespace)) || (with_bracket && !CG(has_bracketed_namespaces))) && CG(active_op_array)->last > 0) { /* ignore ZEND_EXT_STMT and ZEND_TICKS */ int num = CG(active_op_array)->last; while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Namespace declaration statement has to be the very first statement in the script"); } } CG(in_namespace) = 1; if (with_bracket) { CG(has_bracketed_namespaces) = 1; } if (name) { lcname = zend_str_tolower_dup(Z_STRVAL(name->u.constant), Z_STRLEN(name->u.constant)); if (((Z_STRLEN(name->u.constant) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN(name->u.constant) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as namespace name", Z_STRVAL(name->u.constant)); } efree(lcname); if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); } else { ALLOC_ZVAL(CG(current_namespace)); } *CG(current_namespace) = name->u.constant; } else { if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_use(znode *ns_name, znode *new_name, int is_global TSRMLS_DC) /* {{{ */ { char *lcname; zval *name, *ns, tmp; zend_bool warn = 0; zend_class_entry **pce; if (!CG(current_import)) { CG(current_import) = emalloc(sizeof(HashTable)); zend_hash_init(CG(current_import), 0, NULL, ZVAL_PTR_DTOR, 0); } ALLOC_ZVAL(ns); *ns = ns_name->u.constant; if (new_name) { name = &new_name->u.constant; } else { const char *p; /* The form "use A\B" is eqivalent to "use A\B as B". So we extract the last part of compound name to use as a new_name */ name = &tmp; p = zend_memrchr(Z_STRVAL_P(ns), '\\', Z_STRLEN_P(ns)); if (p) { ZVAL_STRING(name, p+1, 1); } else { *name = *ns; zval_copy_ctor(name); warn = !is_global && !CG(current_namespace); } } lcname = zend_str_tolower_dup(Z_STRVAL_P(name), Z_STRLEN_P(name)); if (((Z_STRLEN_P(name) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN_P(name) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because '%s' is a special class name", Z_STRVAL_P(ns), Z_STRVAL_P(name), Z_STRVAL_P(name)); } if (CG(current_namespace)) { /* Prefix import name with current namespace name to avoid conflicts with classes */ char *c_ns_name = emalloc(Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) + 1); zend_str_tolower_copy(c_ns_name, Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); c_ns_name[Z_STRLEN_P(CG(current_namespace))] = '\\'; memcpy(c_ns_name+Z_STRLEN_P(CG(current_namespace))+1, lcname, Z_STRLEN_P(name)+1); if (zend_hash_exists(CG(class_table), c_ns_name, Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name)+1)) { char *tmp2 = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) || memcmp(tmp2, c_ns_name, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(tmp2); } efree(c_ns_name); } else if (zend_hash_find(CG(class_table), lcname, Z_STRLEN_P(name)+1, (void**)&pce) == SUCCESS && (*pce)->type == ZEND_USER_CLASS && (*pce)->info.user.filename == CG(compiled_filename)) { char *c_tmp = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(name) || memcmp(c_tmp, lcname, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(c_tmp); } if (zend_hash_add(CG(current_import), lcname, Z_STRLEN_P(name)+1, &ns, sizeof(zval*), NULL) != SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } if (warn) { if (!strcmp(Z_STRVAL_P(name), "strict")) { zend_error(E_COMPILE_ERROR, "You seem to be trying to use a different language..."); } zend_error(E_WARNING, "The use statement with non-compound name '%s' has no effect", Z_STRVAL_P(name)); } efree(lcname); zval_dtor(name); } /* }}} */ void zend_do_declare_constant(znode *name, znode *value TSRMLS_DC) /* {{{ */ { zend_op *opline; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed as constants"); } if (zend_get_ct_const(&name->u.constant, 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare constant '%s'", Z_STRVAL(name->u.constant)); } if (CG(current_namespace)) { /* Prefix constant name with name of current namespace, lowercased */ znode tmp; tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); Z_STRVAL(tmp.u.constant) = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), Z_STRLEN(tmp.u.constant)); zend_do_build_namespace_name(&tmp, &tmp, name TSRMLS_CC); *name = tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DECLARE_CONST; SET_UNUSED(opline->result); SET_NODE(opline->op1, name); SET_NODE(opline->op2, value); } /* }}} */ void zend_verify_namespace(TSRMLS_D) /* {{{ */ { if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "No code may exist outside of namespace {}"); } } /* }}} */ void zend_do_end_namespace(TSRMLS_D) /* {{{ */ { CG(in_namespace) = 0; if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_end_compilation(TSRMLS_D) /* {{{ */ { CG(has_bracketed_namespaces) = 0; zend_do_end_namespace(TSRMLS_C); } /* }}} */ /* {{{ zend_dirname Returns directory name component of path */ ZEND_API size_t zend_dirname(char *path, size_t len) { register char *end = path + len - 1; unsigned int len_adjust = 0; #ifdef PHP_WIN32 /* Note that on Win32 CWD is per drive (heritage from CP/M). * This means dirname("c:foo") maps to "c:." or "c:" - which means CWD on C: drive. */ if ((2 <= len) && isalpha((int)((unsigned char *)path)[0]) && (':' == path[1])) { /* Skip over the drive spec (if any) so as not to change */ path += 2; len_adjust += 2; if (2 == len) { /* Return "c:" on Win32 for dirname("c:"). * It would be more consistent to return "c:." * but that would require making the string *longer*. */ return len; } } #elif defined(NETWARE) /* * Find the first occurence of : from the left * move the path pointer to the position just after : * increment the len_adjust to the length of path till colon character(inclusive) * If there is no character beyond : simple return len */ char *colonpos = NULL; colonpos = strchr(path, ':'); if (colonpos != NULL) { len_adjust = ((colonpos - path) + 1); path += len_adjust; if (len_adjust == len) { return len; } } #endif if (len == 0) { /* Illegal use of this function */ return 0; } /* Strip trailing slashes */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { /* The path only contained slashes */ path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } /* Strip filename */ while (end >= path && !IS_SLASH_P(end)) { end--; } if (end < path) { /* No slash found, therefore return '.' */ #ifdef NETWARE if (len_adjust == 0) { path[0] = '.'; path[1] = '\0'; return 1; /* only one character */ } else { path[0] = '\0'; return len_adjust; } #else path[0] = '.'; path[1] = '\0'; return 1 + len_adjust; #endif } /* Strip slashes which came before the file name */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } *(end+1) = '\0'; return (size_t)(end + 1 - path) + len_adjust; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */ /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <zend_language_parser.h> #include "zend.h" #include "zend_compile.h" #include "zend_constants.h" #include "zend_llist.h" #include "zend_API.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "zend_multibyte.h" #include "zend_language_scanner.h" #define CONSTANT_EX(op_array, op) \ (op_array)->literals[op].constant #define CONSTANT(op) \ CONSTANT_EX(CG(active_op_array), op) #define SET_NODE(target, src) do { \ target ## _type = (src)->op_type; \ if ((src)->op_type == IS_CONST) { \ target.constant = zend_add_literal(CG(active_op_array), &(src)->u.constant TSRMLS_CC); \ } else { \ target = (src)->u.op; \ } \ } while (0) #define GET_NODE(target, src) do { \ (target)->op_type = src ## _type; \ if ((target)->op_type == IS_CONST) { \ (target)->u.constant = CONSTANT(src.constant); \ } else { \ (target)->u.op = src; \ (target)->EA = 0; \ } \ } while (0) #define COPY_NODE(target, src) do { \ target ## _type = src ## _type; \ target = src; \ } while (0) #define CALCULATE_LITERAL_HASH(num) do { \ if (IS_INTERNED(Z_STRVAL(CONSTANT(num)))) { \ Z_HASH_P(&CONSTANT(num)) = INTERNED_HASH(Z_STRVAL(CONSTANT(num))); \ } else { \ Z_HASH_P(&CONSTANT(num)) = zend_hash_func(Z_STRVAL(CONSTANT(num)), Z_STRLEN(CONSTANT(num))+1); \ } \ } while (0) #define GET_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot++; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ } \ } while (0) #define POLYMORPHIC_CACHE_SLOT_SIZE 2 #define GET_POLYMORPHIC_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot; \ CG(active_op_array)->last_cache_slot += POLYMORPHIC_CACHE_SLOT_SIZE; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 2] = NULL; \ } \ } while (0) #define FREE_POLYMORPHIC_CACHE_SLOT(literal) do { \ if (CG(active_op_array)->literals[literal].cache_slot == \ CG(active_op_array)->last_cache_slot - POLYMORPHIC_CACHE_SLOT_SIZE) { \ CG(active_op_array)->literals[literal].cache_slot = -1; \ CG(active_op_array)->last_cache_slot -= POLYMORPHIC_CACHE_SLOT_SIZE; \ } \ } while (0) ZEND_API zend_op_array *(*zend_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); ZEND_API zend_op_array *(*zend_compile_string)(zval *source_string, char *filename TSRMLS_DC); #ifndef ZTS ZEND_API zend_compiler_globals compiler_globals; ZEND_API zend_executor_globals executor_globals; #endif static void zend_duplicate_property_info(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = estrndup(property_info->name, property_info->name_length); } if (property_info->doc_comment) { property_info->doc_comment = estrndup(property_info->doc_comment, property_info->doc_comment_len); } } /* }}} */ static void zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = zend_strndup(property_info->name, property_info->name_length); } } /* }}} */ static void zend_destroy_property_info(zend_property_info *property_info) /* {{{ */ { str_efree(property_info->name); if (property_info->doc_comment) { efree((char*)property_info->doc_comment); } } /* }}} */ static void zend_destroy_property_info_internal(zend_property_info *property_info) /* {{{ */ { str_free((char*)property_info->name); } /* }}} */ static void build_runtime_defined_function_key(zval *result, const char *name, int name_length TSRMLS_DC) /* {{{ */ { char char_pos_buf[32]; uint char_pos_len; const char *filename; char_pos_len = zend_sprintf(char_pos_buf, "%p", LANG_SCNG(yy_text)); if (CG(active_op_array)->filename) { filename = CG(active_op_array)->filename; } else { filename = "-"; } /* NULL, name length, filename length, last accepting char position length */ result->value.str.len = 1+name_length+strlen(filename)+char_pos_len; /* must be binary safe */ result->value.str.val = (char *) safe_emalloc(result->value.str.len, 1, 1); result->value.str.val[0] = '\0'; sprintf(result->value.str.val+1, "%s%s%s", name, filename, char_pos_buf); result->type = IS_STRING; Z_SET_REFCOUNT_P(result, 1); } /* }}} */ static void init_compiler_declarables(TSRMLS_D) /* {{{ */ { Z_TYPE(CG(declarables).ticks) = IS_LONG; Z_LVAL(CG(declarables).ticks) = 0; } /* }}} */ void zend_init_compiler_context(TSRMLS_D) /* {{{ */ { CG(context).opcodes_size = (CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) ? INITIAL_INTERACTIVE_OP_ARRAY_SIZE : INITIAL_OP_ARRAY_SIZE; CG(context).vars_size = 0; CG(context).literals_size = 0; CG(context).current_brk_cont = -1; CG(context).backpatch_count = 0; CG(context).labels = NULL; } /* }}} */ void zend_init_compiler_data_structures(TSRMLS_D) /* {{{ */ { zend_stack_init(&CG(bp_stack)); zend_stack_init(&CG(function_call_stack)); zend_stack_init(&CG(switch_cond_stack)); zend_stack_init(&CG(foreach_copy_stack)); zend_stack_init(&CG(object_stack)); zend_stack_init(&CG(declare_stack)); CG(active_class_entry) = NULL; zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_stack_init(&CG(list_stack)); CG(in_compilation) = 0; CG(start_lineno) = 0; CG(current_namespace) = NULL; CG(in_namespace) = 0; CG(has_bracketed_namespaces) = 0; CG(current_import) = NULL; init_compiler_declarables(TSRMLS_C); zend_stack_init(&CG(context_stack)); CG(encoding_declared) = 0; } /* }}} */ ZEND_API void file_handle_dtor(zend_file_handle *fh) /* {{{ */ { TSRMLS_FETCH(); zend_file_handle_dtor(fh TSRMLS_CC); } /* }}} */ void init_compiler(TSRMLS_D) /* {{{ */ { CG(active_op_array) = NULL; zend_init_compiler_data_structures(TSRMLS_C); zend_init_rsrc_list(TSRMLS_C); zend_hash_init(&CG(filenames_table), 5, NULL, (dtor_func_t) free_estring, 0); zend_llist_init(&CG(open_files), sizeof(zend_file_handle), (void (*)(void *)) file_handle_dtor, 0); CG(unclean_shutdown) = 0; } /* }}} */ void shutdown_compiler(TSRMLS_D) /* {{{ */ { zend_stack_destroy(&CG(bp_stack)); zend_stack_destroy(&CG(function_call_stack)); zend_stack_destroy(&CG(switch_cond_stack)); zend_stack_destroy(&CG(foreach_copy_stack)); zend_stack_destroy(&CG(object_stack)); zend_stack_destroy(&CG(declare_stack)); zend_stack_destroy(&CG(list_stack)); zend_hash_destroy(&CG(filenames_table)); zend_llist_destroy(&CG(open_files)); zend_stack_destroy(&CG(context_stack)); } /* }}} */ ZEND_API char *zend_set_compiled_filename(const char *new_compiled_filename TSRMLS_DC) /* {{{ */ { char **pp, *p; int length = strlen(new_compiled_filename); if (zend_hash_find(&CG(filenames_table), new_compiled_filename, length+1, (void **) &pp) == SUCCESS) { CG(compiled_filename) = *pp; return *pp; } p = estrndup(new_compiled_filename, length); zend_hash_update(&CG(filenames_table), new_compiled_filename, length+1, &p, sizeof(char *), (void **) &pp); CG(compiled_filename) = p; return p; } /* }}} */ ZEND_API void zend_restore_compiled_filename(char *original_compiled_filename TSRMLS_DC) /* {{{ */ { CG(compiled_filename) = original_compiled_filename; } /* }}} */ ZEND_API char *zend_get_compiled_filename(TSRMLS_D) /* {{{ */ { return CG(compiled_filename); } /* }}} */ ZEND_API int zend_get_compiled_lineno(TSRMLS_D) /* {{{ */ { return CG(zend_lineno); } /* }}} */ ZEND_API zend_bool zend_is_compiling(TSRMLS_D) /* {{{ */ { return CG(in_compilation); } /* }}} */ static zend_uint get_temporary_variable(zend_op_array *op_array) /* {{{ */ { return (op_array->T)++ * ZEND_MM_ALIGNED_SIZE(sizeof(temp_variable)); } /* }}} */ static int lookup_cv(zend_op_array *op_array, char* name, int name_len, ulong hash TSRMLS_DC) /* {{{ */ { int i = 0; ulong hash_value = hash ? hash : zend_inline_hash_func(name, name_len+1); while (i < op_array->last_var) { if (op_array->vars[i].name == name || (op_array->vars[i].hash_value == hash_value && op_array->vars[i].name_len == name_len && memcmp(op_array->vars[i].name, name, name_len) == 0)) { str_efree(name); return i; } i++; } i = op_array->last_var; op_array->last_var++; if (op_array->last_var > CG(context).vars_size) { CG(context).vars_size += 16; /* FIXME */ op_array->vars = erealloc(op_array->vars, CG(context).vars_size * sizeof(zend_compiled_variable)); } op_array->vars[i].name = zend_new_interned_string(name, name_len + 1, 1 TSRMLS_CC); op_array->vars[i].name_len = name_len; op_array->vars[i].hash_value = hash_value; return i; } /* }}} */ void zend_del_literal(zend_op_array *op_array, int n) /* {{{ */ { zval_dtor(&CONSTANT_EX(op_array, n)); if (n + 1 == op_array->last_literal) { op_array->last_literal--; } else { Z_TYPE(CONSTANT_EX(op_array, n)) = IS_NULL; } } /* }}} */ /* Common part of zend_add_literal and zend_append_individual_literal */ static inline void zend_insert_literal(zend_op_array *op_array, const zval *zv, int literal_position TSRMLS_DC) /* {{{ */ { if (Z_TYPE_P(zv) == IS_STRING || Z_TYPE_P(zv) == IS_CONSTANT) { zval *z = (zval*)zv; Z_STRVAL_P(z) = (char*)zend_new_interned_string(Z_STRVAL_P(zv), Z_STRLEN_P(zv) + 1, 1 TSRMLS_CC); } CONSTANT_EX(op_array, literal_position) = *zv; Z_SET_REFCOUNT(CONSTANT_EX(op_array, literal_position), 2); Z_SET_ISREF(CONSTANT_EX(op_array, literal_position)); op_array->literals[literal_position].hash_value = 0; op_array->literals[literal_position].cache_slot = -1; } /* }}} */ /* Is used while compiling a function, using the context to keep track of an approximate size to avoid to relocate to often. Literals are truncated to actual size in the second compiler pass (pass_two()). */ int zend_add_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; if (i >= CG(context).literals_size) { while (i >= CG(context).literals_size) { CG(context).literals_size += 16; /* FIXME */ } op_array->literals = (zend_literal*)erealloc(op_array->literals, CG(context).literals_size * sizeof(zend_literal)); } zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ /* Is used after normal compilation to append an additional literal. Allocation is done precisely here. */ int zend_append_individual_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; op_array->literals = (zend_literal*)erealloc(op_array->literals, (i + 1) * sizeof(zend_literal)); zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ int zend_add_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_ns_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; const char *ns_separator; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); ns_separator = (const char*)zend_memrchr(Z_STRVAL_P(zv), '\\', Z_STRLEN_P(zv)) + 1; lc_len = Z_STRLEN_P(zv) - (ns_separator - Z_STRVAL_P(zv)); lc_name = zend_str_tolower_dup(ns_separator, lc_len); ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_class_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } if (Z_STRVAL_P(zv)[0] == '\\') { lc_len = Z_STRLEN_P(zv) - 1; lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv) + 1, lc_len); } else { lc_len = Z_STRLEN_P(zv); lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), lc_len); } ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); GET_CACHE_SLOT(ret); return ret; } /* }}} */ int zend_add_const_name_literal(zend_op_array *op_array, const zval *zv, int unqualified TSRMLS_DC) /* {{{ */ { int ret, tmp_literal; char *name, *tmp_name; const char *ns_separator; int name_len, ns_len; zval c; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } /* skip leading '\\' */ if (Z_STRVAL_P(zv)[0] == '\\') { name_len = Z_STRLEN_P(zv) - 1; name = Z_STRVAL_P(zv) + 1; } else { name_len = Z_STRLEN_P(zv); name = Z_STRVAL_P(zv); } ns_separator = zend_memrchr(name, '\\', name_len); if (ns_separator) { ns_len = ns_separator - name; } else { ns_len = 0; } if (ns_len) { /* lowercased namespace name & original constant name */ tmp_name = estrndup(name, name_len); zend_str_tolower(tmp_name, ns_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased namespace name & lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); } if (ns_len) { if (!unqualified) { return ret; } ns_len++; name += ns_len; name_len -= ns_len; } /* original constant name */ tmp_name = estrndup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); return ret; } /* }}} */ #define LITERAL_STRINGL(op, str, len, copy) do { \ zval _c; \ ZVAL_STRINGL(&_c, str, len, copy); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG(op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG_EX(op_array, op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(op_array, &_c TSRMLS_CC); \ } while (0) #define LITERAL_NULL(op) do { \ zval _c; \ INIT_ZVAL( _c); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) static inline zend_bool zend_is_function_or_method_call(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; return ((type & ZEND_PARSED_METHOD_CALL) || (type == ZEND_PARSED_FUNCTION_CALL)); } /* }}} */ void zend_do_binary_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_unary_op(zend_uchar op, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); GET_NODE(result, opline->result); SET_UNUSED(opline->op2); } /* }}} */ #define MAKE_NOP(opline) { opline->opcode = ZEND_NOP; memset(&opline->result,0,sizeof(opline->result)); memset(&opline->op1,0,sizeof(opline->op1)); memset(&opline->op2,0,sizeof(opline->op2)); opline->result_type=opline->op1_type=opline->op2_type=IS_UNUSED; } static void zend_do_op_data(zend_op *data_op, const znode *value TSRMLS_DC) /* {{{ */ { data_op->opcode = ZEND_OP_DATA; SET_NODE(data_op->op1, value); SET_UNUSED(data_op->op2); } /* }}} */ void zend_do_binary_assign_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; switch (last_op->opcode) { case ZEND_FETCH_OBJ_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, op2 TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; case ZEND_FETCH_DIM_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_DIM; zend_do_op_data(opline, op2 TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result,last_op->result); return; default: break; } } opline->opcode = op; SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void fetch_simple_variable_ex(znode *result, znode *varname, int bp, zend_uchar op TSRMLS_DC) /* {{{ */ { zend_op opline; zend_op *opline_ptr; zend_llist *fetch_list_ptr; if (varname->op_type == IS_CONST) { ulong hash = 0; if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } else if (IS_INTERNED(Z_STRVAL(varname->u.constant))) { hash = INTERNED_HASH(Z_STRVAL(varname->u.constant)); } if (!zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC) && !(varname->u.constant.value.str.len == (sizeof("this")-1) && !memcmp(varname->u.constant.value.str.val, "this", sizeof("this"))) && (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE)) { result->op_type = IS_CV; result->u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC); varname->u.constant.value.str.val = (char*)CG(active_op_array)->vars[result->u.op.var].name; result->EA = 0; return; } } if (bp) { opline_ptr = &opline; init_op(opline_ptr TSRMLS_CC); } else { opline_ptr = get_next_op(CG(active_op_array) TSRMLS_CC); } opline_ptr->opcode = op; opline_ptr->result_type = IS_VAR; opline_ptr->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline_ptr->op1, varname); GET_NODE(result, opline_ptr->result); SET_UNUSED(opline_ptr->op2); opline_ptr->extended_value = ZEND_FETCH_LOCAL; if (varname->op_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline_ptr->op1.constant); if (zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC)) { opline_ptr->extended_value = ZEND_FETCH_GLOBAL; } } if (bp) { zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); zend_llist_add_element(fetch_list_ptr, opline_ptr); } } /* }}} */ void fetch_simple_variable(znode *result, znode *varname, int bp TSRMLS_DC) /* {{{ */ { /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ fetch_simple_variable_ex(result, varname, bp, ZEND_FETCH_W TSRMLS_CC); } /* }}} */ void zend_do_fetch_static_member(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { znode class_node; zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline_ptr; zend_op opline; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); } zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (result->op_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[result->u.op.var].name), CG(active_op_array)->vars[result->u.op.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } GET_NODE(result,opline.result); opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; opline_ptr = &opline; zend_llist_add_element(fetch_list_ptr, &opline); } else { le = fetch_list_ptr->head; opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode != ZEND_FETCH_W && opline_ptr->op1_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[opline_ptr->op1.var].name), CG(active_op_array)->vars[opline_ptr->op1.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; COPY_NODE(opline_ptr->op1, opline.result); zend_llist_prepend_element(fetch_list_ptr, &opline); } else { if (opline_ptr->op1_type == IS_CONST) { GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op1.constant); } if (class_node.op_type == IS_CONST) { opline_ptr->op2_type = IS_CONST; opline_ptr->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline_ptr->op2, &class_node); } opline_ptr->extended_value |= ZEND_FETCH_STATIC_MEMBER; } } } /* }}} */ void fetch_array_begin(znode *result, znode *varname, znode *first_dim TSRMLS_DC) /* {{{ */ { fetch_simple_variable(result, varname, 1 TSRMLS_CC); fetch_array_dim(result, result, first_dim TSRMLS_CC); } /* }}} */ void fetch_array_dim(znode *result, const znode *parent, const znode *dim TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (zend_is_function_or_method_call(parent)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, parent); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_DIM_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, parent); SET_NODE(opline.op2, dim); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline.op2.constant)), Z_STRLEN(CONSTANT(opline.op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline.op2.constant)); ZVAL_LONG(&CONSTANT(opline.op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline.op2.constant); } } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void fetch_string_offset(znode *result, const znode *parent, const znode *offset TSRMLS_DC) /* {{{ */ { fetch_array_dim(result, parent, offset TSRMLS_CC); } /* }}} */ void zend_do_print(znode *result, const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->opcode = ZEND_PRINT; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_echo(const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ECHO; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_abstract_method(const znode *function_name, znode *modifiers, const znode *body TSRMLS_DC) /* {{{ */ { char *method_type; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { Z_LVAL(modifiers->u.constant) |= ZEND_ACC_ABSTRACT; method_type = "Interface"; } else { method_type = "Abstract"; } if (modifiers->u.constant.value.lval & ZEND_ACC_ABSTRACT) { if(modifiers->u.constant.value.lval & ZEND_ACC_PRIVATE) { zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot be declared private", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } if (Z_LVAL(body->u.constant) == ZEND_ACC_ABSTRACT) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_RAISE_ABSTRACT_ERROR; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } else { /* we had code in the function body */ zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot contain body", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } else { if (body->u.constant.value.lval == ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Non-abstract method %s::%s() must contain body", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } } /* }}} */ static zend_bool opline_is_fetch_this(const zend_op *opline TSRMLS_DC) /* {{{ */ { if ((opline->opcode == ZEND_FETCH_W) && (opline->op1_type == IS_CONST) && (Z_TYPE(CONSTANT(opline->op1.constant)) == IS_STRING) && (Z_HASH_P(&CONSTANT(opline->op1.constant)) == THIS_HASHVAL) && (Z_STRLEN(CONSTANT(opline->op1.constant)) == (sizeof("this")-1)) && !memcmp(Z_STRVAL(CONSTANT(opline->op1.constant)), "this", sizeof("this"))) { return 1; } else { return 0; } } /* }}} */ void zend_do_assign(znode *result, znode *variable, znode *value TSRMLS_DC) /* {{{ */ { int last_op_number; zend_op *opline; if (value->op_type == IS_CV) { zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (fetch_list_ptr && fetch_list_ptr->head) { opline = (zend_op *)fetch_list_ptr->head->data; if (opline->opcode == ZEND_FETCH_DIM_W && opline->op1_type == IS_CV && opline->op1.var == value->u.op.var) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_R; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->op1_type = IS_CONST; LITERAL_STRINGL(opline->op1, CG(active_op_array)->vars[value->u.op.var].name, CG(active_op_array)->vars[value->u.op.var].name_len, 1); CALCULATE_LITERAL_HASH(opline->op1.constant); SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_LOCAL; GET_NODE(value, opline->result); } } } zend_do_end_variable_parse(variable, BP_VAR_W, 0 TSRMLS_CC); last_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (variable->op_type == IS_CV) { if (variable->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (variable->op_type == IS_VAR) { int n = 0; while (last_op_number - n > 0) { zend_op *last_op; last_op = &CG(active_op_array)->opcodes[last_op_number-n-1]; if (last_op->result_type == IS_VAR && last_op->result.var == variable->u.op.var) { if (last_op->opcode == ZEND_FETCH_OBJ_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, value TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (last_op->opcode == ZEND_FETCH_DIM_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ /* TBFixed: this can realloc opcodes, leaving last_op pointing wrong */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_DIM; zend_do_op_data(opline, value TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (opline_is_fetch_this(last_op TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } else { break; } } n++; } } opline->opcode = ZEND_ASSIGN; SET_NODE(opline->op1, variable); SET_NODE(opline->op2, value); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_assign_ref(znode *result, const znode *lvar, const znode *rvar TSRMLS_DC) /* {{{ */ { zend_op *opline; if (lvar->op_type == IS_CV) { if (lvar->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (lvar->op_type == IS_VAR) { int last_op_number = get_next_op_number(CG(active_op_array)); if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline_is_fetch_this(opline TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ASSIGN_REF; if (zend_is_function_or_method_call(rvar)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } else if (rvar->EA & ZEND_PARSED_NEW) { opline->extended_value = ZEND_RETURNS_NEW; } else { opline->extended_value = 0; } if (result) { opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } else { opline->result_type = IS_UNUSED | EXT_TYPE_UNUSED; } SET_NODE(opline->op1, lvar); SET_NODE(opline->op2, rvar); } /* }}} */ static inline void do_begin_loop(TSRMLS_D) /* {{{ */ { zend_brk_cont_element *brk_cont_element; int parent; parent = CG(context).current_brk_cont; CG(context).current_brk_cont = CG(active_op_array)->last_brk_cont; brk_cont_element = get_next_brk_cont_element(CG(active_op_array)); brk_cont_element->start = get_next_op_number(CG(active_op_array)); brk_cont_element->parent = parent; } /* }}} */ static inline void do_end_loop(int cont_addr, int has_loop_var TSRMLS_DC) /* {{{ */ { if (!has_loop_var) { /* The start fileld is used to free temporary variables in case of exceptions. * We won't try to free something of we don't have loop variable. */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].start = -1; } CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = cont_addr; CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; } /* }}} */ void zend_do_while_cond(const znode *expr, znode *close_bracket_token TSRMLS_DC) /* {{{ */ { int while_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, expr); close_bracket_token->u.op.opline_num = while_cond_op_number; SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_while_end(const znode *while_token, const znode *close_bracket_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* add unconditional jump */ opline->opcode = ZEND_JMP; opline->op1.opline_num = while_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* update while's conditional jmp */ CG(active_op_array)->opcodes[close_bracket_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); do_end_loop(while_token->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_cond(const znode *expr, znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { int for_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZNZ; SET_NODE(opline->op1, expr); /* the conditional expression */ second_semicolon_token->u.op.opline_num = for_cond_op_number; SET_UNUSED(opline->op2); } /* }}} */ void zend_do_for_before_statement(const znode *cond_start, const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = cond_start->u.op.opline_num; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_end(const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = second_semicolon_token->u.op.opline_num+1; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_end_loop(second_semicolon_token->u.op.opline_num+1, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_pre_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_PRE_INC)?ZEND_PRE_INC_OBJ:ZEND_PRE_DEC_OBJ; last_op->result_type = IS_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_post_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_POST_INC)?ZEND_POST_INC_OBJ:ZEND_POST_DEC_OBJ; last_op->result_type = IS_TMP_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_if_cond(const znode *cond, znode *closing_bracket_token TSRMLS_DC) /* {{{ */ { int if_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); closing_bracket_token->u.op.opline_num = if_cond_op_number; SET_UNUSED(opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_if_after_statement(const znode *closing_bracket_token, unsigned char initialize TSRMLS_DC) /* {{{ */ { int if_end_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; /* save for backpatching */ if (initialize) { zend_llist jmp_list; zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); } zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &if_end_op_number); CG(active_op_array)->opcodes[closing_bracket_token->u.op.opline_num].op2.opline_num = if_end_op_number+1; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_if_end(TSRMLS_D) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_llist *jmp_list_ptr; zend_llist_element *le; zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); for (le=jmp_list_ptr->head; le; le = le->next) { CG(active_op_array)->opcodes[*((int *) le->data)].op1.opline_num = next_op_number; } zend_llist_destroy(jmp_list_ptr); zend_stack_del_top(&CG(bp_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_check_writable_variable(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; if (type & ZEND_PARSED_METHOD_CALL) { zend_error(E_COMPILE_ERROR, "Can't use method return value in write context"); } if (type == ZEND_PARSED_FUNCTION_CALL) { zend_error(E_COMPILE_ERROR, "Can't use function return value in write context"); } } /* }}} */ void zend_do_begin_variable_parse(TSRMLS_D) /* {{{ */ { zend_llist fetch_list; zend_llist_init(&fetch_list, sizeof(zend_op), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &fetch_list, sizeof(zend_llist)); } /* }}} */ void zend_do_end_variable_parse(znode *variable, int type, int arg_offset TSRMLS_DC) /* {{{ */ { zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline = NULL; zend_op *opline_ptr; zend_uint this_var = -1; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); le = fetch_list_ptr->head; /* TODO: $foo->x->y->z = 1 should fetch "x" and "y" for R or RW, not just W */ if (le) { opline_ptr = (zend_op *)le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { /* convert to FETCH_?(this) into IS_CV */ if (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE) { this_var = opline_ptr->result.var; if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), Z_STRVAL(CONSTANT(opline_ptr->op1.constant)), Z_STRLEN(CONSTANT(opline_ptr->op1.constant)), Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC); Z_TYPE(CONSTANT(opline_ptr->op1.constant)) = IS_NULL; } else { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); } le = le->next; if (variable->op_type == IS_VAR && variable->u.op.var == this_var) { variable->op_type = IS_CV; variable->u.op.var = CG(active_op_array)->this_var; } } else if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } while (le) { opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode == ZEND_SEPARATE) { if (type != BP_VAR_R && type != BP_VAR_IS) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); } le = le->next; continue; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); if (opline->op1_type == IS_VAR && opline->op1.var == this_var) { opline->op1_type = IS_CV; opline->op1.var = CG(active_op_array)->this_var; } switch (type) { case BP_VAR_R: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode -= 3; break; case BP_VAR_W: break; case BP_VAR_RW: opline->opcode += 3; break; case BP_VAR_IS: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode += 6; /* 3+3 */ break; case BP_VAR_FUNC_ARG: opline->opcode += 9; /* 3+3+3 */ opline->extended_value |= arg_offset; break; case BP_VAR_UNSET: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for unsetting"); } opline->opcode += 12; /* 3+3+3+3 */ break; } le = le->next; } if (opline && type == BP_VAR_W && arg_offset) { opline->extended_value |= ZEND_FETCH_MAKE_REF; } } zend_llist_destroy(fetch_list_ptr); zend_stack_del_top(&CG(bp_stack)); } /* }}} */ void zend_do_add_string(znode *result, const znode *op1, znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline; if (Z_STRLEN(op2->u.constant) > 1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_STRING; } else if (Z_STRLEN(op2->u.constant) == 1) { int ch = *Z_STRVAL(op2->u.constant); /* Free memory and use ZEND_ADD_CHAR in case of 1 character strings */ efree(Z_STRVAL(op2->u.constant)); ZVAL_LONG(&op2->u.constant, ch); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_CHAR; } else { /* String can be empty after a variable at the end of a heredoc */ efree(Z_STRVAL(op2->u.constant)); return; } if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_add_variable(znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_VAR; if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_free(znode *op1 TSRMLS_DC) /* {{{ */ { if (op1->op_type==IS_TMP_VAR) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else if (op1->op_type==IS_VAR) { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; while (opline->opcode == ZEND_END_SILENCE || opline->opcode == ZEND_EXT_FCALL_END || opline->opcode == ZEND_OP_DATA) { opline--; } if (opline->result_type == IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_FETCH_R || opline->opcode == ZEND_FETCH_DIM_R || opline->opcode == ZEND_FETCH_OBJ_R || opline->opcode == ZEND_QM_ASSIGN_VAR) { /* It's very rare and useless case. It's better to use additional FREE opcode and simplify the FETCH handlers their selves */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else { opline->result_type |= EXT_TYPE_UNUSED; } } else { while (opline>CG(active_op_array)->opcodes) { if (opline->opcode == ZEND_FETCH_DIM_R && opline->op1_type == IS_VAR && opline->op1.var == op1->u.op.var) { /* This should the end of a list() construct * Mark its result as unused */ opline->extended_value = ZEND_FETCH_STANDARD; break; } else if (opline->result_type==IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_NEW) { opline->result_type |= EXT_TYPE_UNUSED; } break; } opline--; } } } else if (op1->op_type == IS_CONST) { zval_dtor(&op1->u.constant); } } /* }}} */ int zend_do_verify_access_types(const znode *current_access_type, const znode *new_modifier) /* {{{ */ { if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_PPP_MASK) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Multiple access type modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_ABSTRACT) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Multiple abstract modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_STATIC) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Multiple static modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_FINAL) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Multiple final modifiers are not allowed"); } if (((Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)) & (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) == (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Cannot use the final modifier on an abstract class member"); } return (Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)); } /* }}} */ void zend_do_begin_function_declaration(znode *function_token, znode *function_name, int is_method, int return_reference, znode *fn_flags_znode TSRMLS_DC) /* {{{ */ { zend_op_array op_array; char *name = function_name->u.constant.value.str.val; int name_len = function_name->u.constant.value.str.len; int function_begin_line = function_token->u.op.opline_num; zend_uint fn_flags; const char *lcname; zend_bool orig_interactive; ALLOCA_FLAG(use_heap) if (is_method) { if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((Z_LVAL(fn_flags_znode->u.constant) & ~(ZEND_ACC_STATIC|ZEND_ACC_PUBLIC))) { zend_error(E_COMPILE_ERROR, "Access type for interface method %s::%s() must be omitted", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } Z_LVAL(fn_flags_znode->u.constant) |= ZEND_ACC_ABSTRACT; /* propagates to the rest of the parser */ } fn_flags = Z_LVAL(fn_flags_znode->u.constant); /* must be done *after* the above check */ } else { fn_flags = 0; } if ((fn_flags & ZEND_ACC_STATIC) && (fn_flags & ZEND_ACC_ABSTRACT) && !(CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_STRICT, "Static function %s%s%s() should not be abstract", is_method ? CG(active_class_entry)->name : "", is_method ? "::" : "", Z_STRVAL(function_name->u.constant)); } function_token->u.op_array = CG(active_op_array); orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(&op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; op_array.function_name = name; if (return_reference) { op_array.fn_flags |= ZEND_ACC_RETURN_REFERENCE; } op_array.fn_flags |= fn_flags; op_array.scope = is_method?CG(active_class_entry):NULL; op_array.prototype = NULL; op_array.line_start = zend_get_compiled_lineno(TSRMLS_C); if (is_method) { int result; lcname = zend_new_interned_string(zend_str_tolower_dup(name, name_len), name_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lcname)) { result = zend_hash_quick_add(&CG(active_class_entry)->function_table, lcname, name_len+1, INTERNED_HASH(lcname), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } else { result = zend_hash_add(&CG(active_class_entry)->function_table, lcname, name_len+1, &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } if (result == FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::%s()", CG(active_class_entry)->name, name); } zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); if (fn_flags & ZEND_ACC_ABSTRACT) { CG(active_class_entry)->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (!(fn_flags & ZEND_ACC_PPP_MASK)) { fn_flags |= ZEND_ACC_PUBLIC; } if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } } } else { char *class_lcname; class_lcname = do_alloca(CG(active_class_entry)->name_length + 1, use_heap); zend_str_tolower_copy(class_lcname, CG(active_class_entry)->name, CG(active_class_entry)->name_length); /* Improve after RC: cache the lowercase class name */ if ((CG(active_class_entry)->name_length == name_len) && ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT) && (!memcmp(class_lcname, lcname, name_len))) { if (!CG(active_class_entry)->constructor) { CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } } else if ((name_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)))) { if (CG(active_class_entry)->constructor) { zend_error(E_STRICT, "Redefining already defined constructor for class %s", CG(active_class_entry)->name); } CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1))) { CG(active_class_entry)->destructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1))) { CG(active_class_entry)->clone = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } CG(active_class_entry)->__call = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } CG(active_class_entry)->__callstatic = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } CG(active_class_entry)->__get = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } CG(active_class_entry)->__set = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } CG(active_class_entry)->__unset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } CG(active_class_entry)->__isset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } CG(active_class_entry)->__tostring = (zend_function *) CG(active_op_array); } else if (!(fn_flags & ZEND_ACC_STATIC)) { CG(active_op_array)->fn_flags |= ZEND_ACC_ALLOW_STATIC; } free_alloca(class_lcname, use_heap); } str_efree(lcname); } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zval key; if (CG(current_namespace)) { /* Prefix function name with current namespcae name */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, function_name TSRMLS_CC); op_array.function_name = Z_STRVAL(tmp.u.constant); name_len = Z_STRLEN(tmp.u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), name_len); } else { lcname = zend_str_tolower_dup(name, name_len); } opline->opcode = ZEND_DECLARE_FUNCTION; opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, name_len TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; LITERAL_STRINGL(opline->op2, lcname, name_len, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); opline->extended_value = ZEND_DECLARE_FUNCTION; zend_hash_quick_update(CG(function_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); } if (CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_NOP; opline->lineno = function_begin_line; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } { /* Push a seperator to the switch and foreach stacks */ zend_switch_entry switch_entry; switch_entry.cond.op_type = IS_UNUSED; switch_entry.default_case = 0; switch_entry.control_var = 0; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); { /* Foreach stack separator */ zend_op dummy_opline; dummy_opline.result_type = IS_UNUSED; dummy_opline.op1_type = IS_UNUSED; zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); } } if (CG(doc_comment)) { CG(active_op_array)->doc_comment = CG(doc_comment); CG(active_op_array)->doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_begin_lambda_function_declaration(znode *result, znode *function_token, int return_reference, int is_static TSRMLS_DC) /* {{{ */ { znode function_name; zend_op_array *current_op_array = CG(active_op_array); int current_op_number = get_next_op_number(CG(active_op_array)); zend_op *current_op; function_name.op_type = IS_CONST; ZVAL_STRINGL(&function_name.u.constant, "{closure}", sizeof("{closure}")-1, 1); zend_do_begin_function_declaration(function_token, &function_name, 0, return_reference, NULL TSRMLS_CC); result->op_type = IS_TMP_VAR; result->u.op.var = get_temporary_variable(current_op_array); current_op = &current_op_array->opcodes[current_op_number]; current_op->opcode = ZEND_DECLARE_LAMBDA_FUNCTION; zend_del_literal(current_op_array, current_op->op2.constant); SET_UNUSED(current_op->op2); SET_NODE(current_op->result, result); if (is_static) { CG(active_op_array)->fn_flags |= ZEND_ACC_STATIC; } CG(active_op_array)->fn_flags |= ZEND_ACC_CLOSURE; } /* }}} */ void zend_do_handle_exception(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_HANDLE_EXCEPTION; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_function_declaration(const znode *function_token TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; zend_do_extended_info(TSRMLS_C); zend_do_return(NULL, 0 TSRMLS_CC); pass_two(CG(active_op_array) TSRMLS_CC); zend_release_labels(TSRMLS_C); if (CG(active_class_entry)) { zend_check_magic_method_implementation(CG(active_class_entry), (zend_function*)CG(active_op_array), E_COMPILE_ERROR TSRMLS_CC); } else { /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(CG(active_op_array)->function_name); zend_str_tolower_copy(lcname, CG(active_op_array)->function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME)) && CG(active_op_array)->num_args != 1) { zend_error(E_COMPILE_ERROR, "%s() must take exactly 1 argument", ZEND_AUTOLOAD_FUNC_NAME); } } CG(active_op_array)->line_end = zend_get_compiled_lineno(TSRMLS_C); CG(active_op_array) = function_token->u.op_array; /* Pop the switch and foreach seperators */ zend_stack_del_top(&CG(switch_cond_stack)); zend_stack_del_top(&CG(foreach_copy_stack)); } /* }}} */ void zend_do_receive_arg(zend_uchar op, znode *varname, const znode *offset, const znode *initialization, znode *class_type, zend_uchar pass_by_reference TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_arg_info *cur_arg_info; znode var; if (class_type->op_type == IS_CONST && Z_TYPE(class_type->u.constant) == IS_STRING && Z_STRLEN(class_type->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_type->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } if (zend_is_auto_global_quick(Z_STRVAL(varname->u.constant), Z_STRLEN(varname->u.constant), 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign auto-global variable %s", Z_STRVAL(varname->u.constant)); } else { var.op_type = IS_CV; var.u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(varname->u.constant) = (char*)CG(active_op_array)->vars[var.u.op.var].name; var.EA = 0; if (CG(active_op_array)->vars[var.u.op.var].hash_value == THIS_HASHVAL && Z_STRLEN(varname->u.constant) == sizeof("this")-1 && !memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this")-1)) { if (CG(active_op_array)->scope && (CG(active_op_array)->fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } CG(active_op_array)->this_var = var.u.op.var; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->num_args++; opline->opcode = op; SET_NODE(opline->result, &var); SET_NODE(opline->op1, offset); if (op == ZEND_RECV_INIT) { SET_NODE(opline->op2, initialization); } else { CG(active_op_array)->required_num_args = CG(active_op_array)->num_args; SET_UNUSED(opline->op2); } CG(active_op_array)->arg_info = erealloc(CG(active_op_array)->arg_info, sizeof(zend_arg_info)*(CG(active_op_array)->num_args)); cur_arg_info = &CG(active_op_array)->arg_info[CG(active_op_array)->num_args-1]; cur_arg_info->name = zend_new_interned_string(estrndup(varname->u.constant.value.str.val, varname->u.constant.value.str.len), varname->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->name_len = varname->u.constant.value.str.len; cur_arg_info->type_hint = 0; cur_arg_info->allow_null = 1; cur_arg_info->pass_by_reference = pass_by_reference; cur_arg_info->class_name = NULL; cur_arg_info->class_name_len = 0; if (class_type->op_type != IS_UNUSED) { cur_arg_info->allow_null = 0; if (class_type->u.constant.type != IS_NULL) { if (class_type->u.constant.type == IS_ARRAY) { cur_arg_info->type_hint = IS_ARRAY; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else if (Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Default value for parameters with array type hint can only be an array or NULL"); } } } else if (class_type->u.constant.type == IS_CALLABLE) { cur_arg_info->type_hint = IS_CALLABLE; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with callable type hint can only be NULL"); } } } else { cur_arg_info->type_hint = IS_OBJECT; if (ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_type->u.constant), Z_STRLEN(class_type->u.constant))) { zend_resolve_class_name(class_type, opline->extended_value, 1 TSRMLS_CC); } Z_STRVAL(class_type->u.constant) = (char*)zend_new_interned_string(class_type->u.constant.value.str.val, class_type->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->class_name = class_type->u.constant.value.str.val; cur_arg_info->class_name_len = class_type->u.constant.value.str.len; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with a class type hint can only be NULL"); } } } } } } /* }}} */ int zend_do_begin_function_call(znode *function_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { zend_function *function; char *lcname; char *is_compound = memchr(Z_STRVAL(function_name->u.constant), '\\', Z_STRLEN(function_name->u.constant)); zend_resolve_non_class_name(function_name, check_namespace TSRMLS_CC); if (check_namespace && CG(current_namespace) && !is_compound) { /* We assume we call function from the current namespace if it is not prefixed. */ /* In run-time PHP will check for function with full name and internal function with short name */ zend_do_begin_dynamic_function_call(function_name, 1 TSRMLS_CC); return 1; } lcname = zend_str_tolower_dup(function_name->u.constant.value.str.val, function_name->u.constant.value.str.len); if ((zend_hash_find(CG(function_table), lcname, function_name->u.constant.value.str.len+1, (void **) &function)==FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_FUNCTIONS) && (function->type == ZEND_INTERNAL_FUNCTION))) { zend_do_begin_dynamic_function_call(function_name, 0 TSRMLS_CC); efree(lcname); return 1; /* Dynamic */ } efree(function_name->u.constant.value.str.val); function_name->u.constant.value.str.val = lcname; zend_stack_push(&CG(function_call_stack), (void *) &function, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 0; } /* }}} */ void zend_do_begin_method_call(znode *left_bracket TSRMLS_DC) /* {{{ */ { zend_op *last_op; int last_op_number; unsigned char *ptr = NULL; zend_do_end_variable_parse(left_bracket, BP_VAR_R, 0 TSRMLS_CC); zend_do_begin_variable_parse(TSRMLS_C); last_op_number = get_next_op_number(CG(active_op_array))-1; last_op = &CG(active_op_array)->opcodes[last_op_number]; if ((last_op->op2_type == IS_CONST) && (Z_TYPE(CONSTANT(last_op->op2.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(last_op->op2.constant)) == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !zend_binary_strcasecmp(Z_STRVAL(CONSTANT(last_op->op2.constant)), Z_STRLEN(CONSTANT(last_op->op2.constant)), ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1)) { zend_error(E_COMPILE_ERROR, "Cannot call __clone() method on objects - use 'clone $obj' instead"); } if (last_op->opcode == ZEND_FETCH_OBJ_R) { if (last_op->op2_type == IS_CONST) { zval name; name = CONSTANT(last_op->op2.constant); if (!IS_INTERNED(Z_STRVAL(name))) { Z_STRVAL(name) = estrndup(Z_STRVAL(name), Z_STRLEN(name)); } FREE_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); last_op->op2.constant = zend_add_func_name_literal(CG(active_op_array), &name TSRMLS_CC); GET_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); } last_op->opcode = ZEND_INIT_METHOD_CALL; SET_UNUSED(last_op->result); Z_LVAL(left_bracket->u.constant) = ZEND_INIT_FCALL_BY_NAME; } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (left_bracket->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &left_bracket->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, left_bracket); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_do_clone(znode *result, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CLONE; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_begin_dynamic_function_call(znode *function_name, int ns_call TSRMLS_DC) /* {{{ */ { unsigned char *ptr = NULL; zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (ns_call) { /* In run-time PHP will check for function with full name and internal function with short name */ opline->opcode = ZEND_INIT_NS_FCALL_BY_NAME; SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_ns_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (function_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, function_name); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_resolve_non_class_name(znode *element_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; int len; zval **ns; char *lcname, *compound = memchr(Z_STRVAL(element_name->u.constant), '\\', Z_STRLEN(element_name->u.constant)); if (Z_STRVAL(element_name->u.constant)[0] == '\\') { /* name starts with \ so it is known and unambiguos, nothing to do here but shorten it */ memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+1, Z_STRLEN(element_name->u.constant)); --Z_STRLEN(element_name->u.constant); return; } if(!check_namespace) { return; } if (compound && CG(current_import)) { len = compound - Z_STRVAL(element_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(element_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(element_name->u.constant) -= len; memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+len, Z_STRLEN(element_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, element_name TSRMLS_CC); *element_name = tmp; efree(lcname); return; } efree(lcname); } if (CG(current_namespace)) { tmp = *element_name; Z_STRLEN(tmp.u.constant) = sizeof("\\")-1 + Z_STRLEN(element_name->u.constant) + Z_STRLEN_P(CG(current_namespace)); Z_STRVAL(tmp.u.constant) = (char *) emalloc(Z_STRLEN(tmp.u.constant)+1); memcpy(Z_STRVAL(tmp.u.constant), Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace))]), "\\", sizeof("\\")-1); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace)) + sizeof("\\")-1]), Z_STRVAL(element_name->u.constant), Z_STRLEN(element_name->u.constant)+1); STR_FREE(Z_STRVAL(element_name->u.constant)); *element_name = tmp; } } /* }}} */ void zend_resolve_class_name(znode *class_name, ulong fetch_type, int check_ns_name TSRMLS_DC) /* {{{ */ { char *compound; char *lcname; zval **ns; znode tmp; int len; compound = memchr(Z_STRVAL(class_name->u.constant), '\\', Z_STRLEN(class_name->u.constant)); if (compound) { /* This is a compound class name that contains namespace prefix */ if (Z_STRVAL(class_name->u.constant)[0] == '\\') { /* The STRING name has "\" prefix */ Z_STRLEN(class_name->u.constant) -= 1; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+1, Z_STRLEN(class_name->u.constant)+1); Z_STRVAL(class_name->u.constant) = erealloc( Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1); if (ZEND_FETCH_CLASS_DEFAULT != zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "'\\%s' is an invalid class name", Z_STRVAL(class_name->u.constant)); } } else { if (CG(current_import)) { len = compound - Z_STRVAL(class_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(class_name->u.constant) -= len; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+len, Z_STRLEN(class_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; efree(lcname); return; } efree(lcname); } /* Here name is not prefixed with \ and not imported */ if (CG(current_namespace)) { tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } } } else if (CG(current_import) || CG(current_namespace)) { /* this is a plain name (without \) */ lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns) == SUCCESS) { /* The given name is an import name. Substitute it. */ zval_dtor(&class_name->u.constant); class_name->u.constant = **ns; zval_copy_ctor(&class_name->u.constant); } else if (CG(current_namespace)) { /* plain name, no import - prepend current namespace to it */ tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } efree(lcname); } } /* }}} */ void zend_do_fetch_class(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { long fetch_class_op_number; zend_op *opline; if (class_name->op_type == IS_CONST && Z_TYPE(class_name->u.constant) == IS_STRING && Z_STRLEN(class_name->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_name->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } fetch_class_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CLASS; SET_UNUSED(opline->op1); opline->extended_value = ZEND_FETCH_CLASS_GLOBAL; CG(catch_begin) = fetch_class_op_number; if (class_name->op_type == IS_CONST) { int fetch_type; fetch_type = zend_get_class_fetch_type(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); switch (fetch_type) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: SET_UNUSED(opline->op2); opline->extended_value = fetch_type; zval_dtor(&class_name->u.constant); break; default: zend_resolve_class_name(class_name, opline->extended_value, 0 TSRMLS_CC); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_name->u.constant TSRMLS_CC); break; } } else { SET_NODE(opline->op2, class_name); } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; /* FIXME: Hack so that INIT_FCALL_BY_NAME still knows this is a class */ GET_NODE(result, opline->result); result->EA = opline->extended_value; } /* }}} */ void zend_do_label(znode *label TSRMLS_DC) /* {{{ */ { zend_label dest; if (!CG(context).labels) { ALLOC_HASHTABLE(CG(context).labels); zend_hash_init(CG(context).labels, 4, NULL, NULL, 0); } dest.brk_cont = CG(context).current_brk_cont; dest.opline_num = get_next_op_number(CG(active_op_array)); if (zend_hash_add(CG(context).labels, Z_STRVAL(label->u.constant), Z_STRLEN(label->u.constant) + 1, (void**)&dest, sizeof(zend_label), NULL) == FAILURE) { zend_error(E_COMPILE_ERROR, "Label '%s' already defined", Z_STRVAL(label->u.constant)); } /* Done with label now */ zval_dtor(&label->u.constant); } /* }}} */ void zend_resolve_goto_label(zend_op_array *op_array, zend_op *opline, int pass2 TSRMLS_DC) /* {{{ */ { zend_label *dest; long current, distance; zval *label; if (pass2) { label = opline->op2.zv; } else { label = &CONSTANT_EX(op_array, opline->op2.constant); } if (CG(context).labels == NULL || zend_hash_find(CG(context).labels, Z_STRVAL_P(label), Z_STRLEN_P(label)+1, (void**)&dest) == FAILURE) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; zend_error(E_COMPILE_ERROR, "'goto' to undefined label '%s'", Z_STRVAL_P(label)); } else { /* Label is not defined. Delay to pass 2. */ INC_BPC(op_array); return; } } opline->op1.opline_num = dest->opline_num; zval_dtor(label); Z_TYPE_P(label) = IS_NULL; /* Check that we are not moving into loop or switch */ current = opline->extended_value; for (distance = 0; current != dest->brk_cont; distance++) { if (current == -1) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; } zend_error(E_COMPILE_ERROR, "'goto' into loop or switch statement is disallowed"); } current = op_array->brk_cont_array[current].parent; } if (distance == 0) { /* Nothing to break out of, optimize to ZEND_JMP */ opline->opcode = ZEND_JMP; opline->extended_value = 0; SET_UNUSED(opline->op2); } else { /* Set real break distance */ ZVAL_LONG(label, distance); } if (pass2) { DEC_BPC(op_array); } } /* }}} */ void zend_do_goto(const znode *label TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_GOTO; opline->extended_value = CG(context).current_brk_cont; SET_UNUSED(opline->op1); SET_NODE(opline->op2, label); zend_resolve_goto_label(CG(active_op_array), opline, 0 TSRMLS_CC); } /* }}} */ void zend_release_labels(TSRMLS_D) /* {{{ */ { if (CG(context).labels) { zend_hash_destroy(CG(context).labels); FREE_HASHTABLE(CG(context).labels); } if (!zend_stack_is_empty(&CG(context_stack))) { zend_compiler_context *ctx; zend_stack_top(&CG(context_stack), (void**)&ctx); CG(context) = *ctx; zend_stack_del_top(&CG(context_stack)); } } /* }}} */ void zend_do_build_full_name(znode *result, znode *prefix, znode *name, int is_class_member TSRMLS_DC) /* {{{ */ { zend_uint length; if (!result) { result = prefix; } else { *result = *prefix; } if (is_class_member) { length = sizeof("::")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "::", sizeof("::")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("::")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } else { length = sizeof("\\")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "\\", sizeof("\\")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("\\")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } } /* }}} */ int zend_do_begin_class_member_function_call(znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { znode class_node; unsigned char *ptr = NULL; zend_op *opline; if (method_name->op_type == IS_CONST) { char *lcname = zend_str_tolower_dup(Z_STRVAL(method_name->u.constant), Z_STRLEN(method_name->u.constant)); if ((sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == Z_STRLEN(method_name->u.constant) && memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == 0) { zval_dtor(&method_name->u.constant); method_name->op_type = IS_UNUSED; } efree(lcname); } if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; opline = get_next_op(CG(active_op_array) TSRMLS_CC); } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->extended_value = class_node.EA ; } opline->opcode = ZEND_INIT_STATIC_METHOD_CALL; if (class_node.op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, &class_node); } if (method_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &method_name->u.constant TSRMLS_CC); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } } else { SET_NODE(opline->op2, method_name); } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 1; /* Dynamic */ } /* }}} */ void zend_do_end_function_call(znode *function_name, znode *result, const znode *argument_list, int is_method, int is_dynamic_fcall TSRMLS_DC) /* {{{ */ { zend_op *opline; if (is_method && function_name && function_name->op_type == IS_UNUSED) { /* clone */ if (Z_LVAL(argument_list->u.constant) != 0) { zend_error(E_WARNING, "Clone method does not require arguments"); } opline = &CG(active_op_array)->opcodes[Z_LVAL(function_name->u.constant)]; } else { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (!is_method && !is_dynamic_fcall && function_name->op_type==IS_CONST) { opline->opcode = ZEND_DO_FCALL; SET_NODE(opline->op1, function_name); CALCULATE_LITERAL_HASH(opline->op1.constant); GET_CACHE_SLOT(opline->op1.constant); } else { opline->opcode = ZEND_DO_FCALL_BY_NAME; SET_UNUSED(opline->op1); } } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(result, opline->result) ; SET_UNUSED(opline->op2); zend_stack_del_top(&CG(function_call_stack)); opline->extended_value = Z_LVAL(argument_list->u.constant); } /* }}} */ void zend_do_pass_param(znode *param, zend_uchar op, int offset TSRMLS_DC) /* {{{ */ { zend_op *opline; int original_op=op; zend_function **function_ptr_ptr, *function_ptr; int send_by_reference; int send_function = 0; zend_stack_top(&CG(function_call_stack), (void **) &function_ptr_ptr); function_ptr = *function_ptr_ptr; if (original_op == ZEND_SEND_REF) { if (function_ptr && function_ptr->common.function_name && function_ptr->common.type == ZEND_USER_FUNCTION && !ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed; " "If you would like to pass argument by reference, modify the declaration of %s().", function_ptr->common.function_name); } else { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed"); } return; } if (function_ptr) { if (ARG_MAY_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { if (param->op_type & (IS_VAR|IS_CV) && original_op != ZEND_SEND_VAL) { send_by_reference = 1; if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION | ZEND_ARG_SEND_SILENT; } } else { op = ZEND_SEND_VAL; send_by_reference = 0; } } else { send_by_reference = ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset) ? ZEND_ARG_SEND_BY_REF : 0; } } else { send_by_reference = 0; } if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION; } else if (op == ZEND_SEND_VAL && (param->op_type & (IS_VAR|IS_CV))) { op = ZEND_SEND_VAR_NO_REF; } if (op!=ZEND_SEND_VAR_NO_REF && send_by_reference==ZEND_ARG_SEND_BY_REF) { /* change to passing by reference */ switch (param->op_type) { case IS_VAR: case IS_CV: op = ZEND_SEND_REF; break; default: zend_error(E_COMPILE_ERROR, "Only variables can be passed by reference"); break; } } if (original_op == ZEND_SEND_VAR) { switch (op) { case ZEND_SEND_VAR_NO_REF: zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); break; case ZEND_SEND_VAR: if (function_ptr) { zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(param, BP_VAR_FUNC_ARG, offset TSRMLS_CC); } break; case ZEND_SEND_REF: zend_do_end_variable_parse(param, BP_VAR_W, 0 TSRMLS_CC); break; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (op == ZEND_SEND_VAR_NO_REF) { if (function_ptr) { opline->extended_value = ZEND_ARG_COMPILE_TIME_BOUND | send_by_reference | send_function; } else { opline->extended_value = send_function; } } else { if (function_ptr) { opline->extended_value = ZEND_DO_FCALL; } else { opline->extended_value = ZEND_DO_FCALL_BY_NAME; } } opline->opcode = op; SET_NODE(opline->op1, param); opline->op2.opline_num = offset; SET_UNUSED(opline->op2); } /* }}} */ static int generate_free_switch_expr(const zend_switch_entry *switch_entry TSRMLS_DC) /* {{{ */ { zend_op *opline; if (switch_entry->cond.op_type != IS_VAR && switch_entry->cond.op_type != IS_TMP_VAR) { return (switch_entry->cond.op_type == IS_UNUSED); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry->cond); SET_UNUSED(opline->op2); opline->extended_value = 0; return 0; } /* }}} */ static int generate_free_foreach_copy(const zend_op *foreach_copy TSRMLS_DC) /* {{{ */ { zend_op *opline; /* If we reach the seperator then stop applying the stack */ if (foreach_copy->result_type == IS_UNUSED && foreach_copy->op1_type == IS_UNUSED) { return 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->result_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->result); SET_UNUSED(opline->op2); opline->extended_value = 1; if (foreach_copy->op1_type != IS_UNUSED) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->op1_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->op1); SET_UNUSED(opline->op2); opline->extended_value = 0; } return 0; } /* }}} */ void zend_do_return(znode *expr, int do_end_vparse TSRMLS_DC) /* {{{ */ { zend_op *opline; int start_op_number, end_op_number; if (do_end_vparse) { if ((CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) && !zend_is_function_or_method_call(expr)) { zend_do_end_variable_parse(expr, BP_VAR_W, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(expr, BP_VAR_R, 0 TSRMLS_CC); } } start_op_number = get_next_op_number(CG(active_op_array)); #ifdef ZTS zend_stack_apply_with_argument(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_switch_expr TSRMLS_CC); zend_stack_apply_with_argument(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_foreach_copy TSRMLS_CC); #else zend_stack_apply(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_switch_expr); zend_stack_apply(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_foreach_copy); #endif end_op_number = get_next_op_number(CG(active_op_array)); while (start_op_number < end_op_number) { CG(active_op_array)->opcodes[start_op_number].extended_value |= EXT_TYPE_FREE_ON_RETURN; start_op_number++; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) ? ZEND_RETURN_BY_REF : ZEND_RETURN; if (expr) { SET_NODE(opline->op1, expr); if (do_end_vparse && zend_is_function_or_method_call(expr)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } } else { opline->op1_type = IS_CONST; LITERAL_NULL(opline->op1); } SET_UNUSED(opline->op2); } /* }}} */ static int zend_add_try_element(zend_uint try_op TSRMLS_DC) /* {{{ */ { int try_catch_offset = CG(active_op_array)->last_try_catch++; CG(active_op_array)->try_catch_array = erealloc(CG(active_op_array)->try_catch_array, sizeof(zend_try_catch_element)*CG(active_op_array)->last_try_catch); CG(active_op_array)->try_catch_array[try_catch_offset].try_op = try_op; return try_catch_offset; } /* }}} */ static void zend_add_catch_element(int offset, zend_uint catch_op TSRMLS_DC) /* {{{ */ { CG(active_op_array)->try_catch_array[offset].catch_op = catch_op; } /* }}} */ void zend_do_first_catch(znode *open_parentheses TSRMLS_DC) /* {{{ */ { open_parentheses->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_initialize_try_catch_element(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist jmp_list; zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); zend_add_catch_element(try_token->u.op.opline_num, get_next_op_number(CG(active_op_array)) TSRMLS_CC); } /* }}} */ void zend_do_mark_last_catch(const znode *first_catch, const znode *last_additional_catch TSRMLS_DC) /* {{{ */ { CG(active_op_array)->last--; zend_do_if_end(TSRMLS_C); if (last_additional_catch->u.op.opline_num == -1) { CG(active_op_array)->opcodes[first_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[first_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } else { CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_try(znode *try_token TSRMLS_DC) /* {{{ */ { try_token->u.op.opline_num = zend_add_try_element(get_next_op_number(CG(active_op_array)) TSRMLS_CC); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_catch(znode *try_token, znode *class_name, znode *catch_var, znode *first_catch TSRMLS_DC) /* {{{ */ { long catch_op_number; zend_op *opline; znode catch_class; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); catch_class = *class_name; } else { zend_error(E_COMPILE_ERROR, "Bad class name in the catch statement"); } catch_op_number = get_next_op_number(CG(active_op_array)); if (first_catch) { first_catch->u.op.opline_num = catch_op_number; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CATCH; opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &catch_class.u.constant TSRMLS_CC); opline->op2_type = IS_CV; opline->op2.var = lookup_cv(CG(active_op_array), catch_var->u.constant.value.str.val, catch_var->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(catch_var->u.constant) = (char*)CG(active_op_array)->vars[opline->op2.var].name; opline->result.num = 0; /* 1 means it's the last catch in the block */ try_token->u.op.opline_num = catch_op_number; } /* }}} */ void zend_do_end_catch(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); CG(active_op_array)->opcodes[try_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_throw(const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_THROW; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); } /* }}} */ ZEND_API void function_add_ref(zend_function *function) /* {{{ */ { if (function->type == ZEND_USER_FUNCTION) { zend_op_array *op_array = &function->op_array; (*op_array->refcount)++; if (op_array->static_variables) { HashTable *static_variables = op_array->static_variables; zval *tmp_zval; ALLOC_HASHTABLE(op_array->static_variables); zend_hash_init(op_array->static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(op_array->static_variables, static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_zval, sizeof(zval *)); } op_array->run_time_cache = NULL; } } /* }}} */ static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */ { zend_function *function; if (!ce->parent) { return; } /* You cannot change create_object */ ce->create_object = ce->parent->create_object; /* Inherit special functions if needed */ if (!ce->get_iterator) { ce->get_iterator = ce->parent->get_iterator; } if (!ce->iterator_funcs.funcs) { ce->iterator_funcs.funcs = ce->parent->iterator_funcs.funcs; } if (!ce->__get) { ce->__get = ce->parent->__get; } if (!ce->__set) { ce->__set = ce->parent->__set; } if (!ce->__unset) { ce->__unset = ce->parent->__unset; } if (!ce->__isset) { ce->__isset = ce->parent->__isset; } if (!ce->__call) { ce->__call = ce->parent->__call; } if (!ce->__callstatic) { ce->__callstatic = ce->parent->__callstatic; } if (!ce->__tostring) { ce->__tostring = ce->parent->__tostring; } if (!ce->clone) { ce->clone = ce->parent->clone; } if(!ce->serialize) { ce->serialize = ce->parent->serialize; } if(!ce->unserialize) { ce->unserialize = ce->parent->unserialize; } if (!ce->destructor) { ce->destructor = ce->parent->destructor; } if (ce->constructor) { if (ce->parent->constructor && ce->parent->constructor->common.fn_flags & ZEND_ACC_FINAL) { zend_error(E_ERROR, "Cannot override final %s::%s() with %s::%s()", ce->parent->name, ce->parent->constructor->common.function_name, ce->name, ce->constructor->common.function_name ); } return; } if (zend_hash_find(&ce->parent->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), (void **)&function)==SUCCESS) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), function, sizeof(zend_function), NULL); function_add_ref(function); } else { /* Don't inherit the old style constructor if we already have the new style constructor */ char *lc_class_name; char *lc_parent_class_name; lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); if (!zend_hash_exists(&ce->function_table, lc_class_name, ce->name_length+1)) { lc_parent_class_name = zend_str_tolower_dup(ce->parent->name, ce->parent->name_length); if (!zend_hash_exists(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1) && zend_hash_find(&ce->parent->function_table, lc_parent_class_name, ce->parent->name_length+1, (void **)&function)==SUCCESS) { if (function->common.fn_flags & ZEND_ACC_CTOR) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1, function, sizeof(zend_function), NULL); function_add_ref(function); } } efree(lc_parent_class_name); } efree(lc_class_name); } ce->constructor = ce->parent->constructor; } /* }}} */ char *zend_visibility_string(zend_uint fn_flags) /* {{{ */ { if (fn_flags & ZEND_ACC_PRIVATE) { return "private"; } if (fn_flags & ZEND_ACC_PROTECTED) { return "protected"; } if (fn_flags & ZEND_ACC_PUBLIC) { return "public"; } return ""; } /* }}} */ static void do_inherit_method(zend_function *function) /* {{{ */ { /* The class entry of the derived function intentionally remains the same * as that of the parent class. That allows us to know in which context * we're running, and handle private method calls properly. */ function_add_ref(function); } /* }}} */ static zend_bool zend_do_perform_implementation_check(const zend_function *fe, const zend_function *proto TSRMLS_DC) /* {{{ */ { zend_uint i; /* If it's a user function then arg_info == NULL means we don't have any parameters but * we still need to do the arg number checks. We are only willing to ignore this for internal * functions because extensions don't always define arg_info. */ if (!proto || (!proto->common.arg_info && proto->common.type != ZEND_USER_FUNCTION)) { return 1; } /* Checks for constructors only if they are declared in an interface, * or explicitly marked as abstract */ if ((fe->common.fn_flags & ZEND_ACC_CTOR) && ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)) { return 1; } /* check number of arguments */ if (proto->common.required_num_args < fe->common.required_num_args || proto->common.num_args > fe->common.num_args) { return 0; } if (fe->common.type != ZEND_USER_FUNCTION && (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) != 0 && (fe->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) == 0) { return 0; } /* by-ref constraints on return values are covariant */ if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) { return 0; } for (i=0; i < proto->common.num_args; i++) { if (ZEND_LOG_XOR(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)) { /* Only one has a type hint and the other one doesn't */ return 0; } if (fe->common.arg_info[i].class_name && strcasecmp(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)!=0) { const char *colon; if (fe->common.type != ZEND_USER_FUNCTION) { return 0; } else if (strchr(proto->common.arg_info[i].class_name, '\\') != NULL || (colon = zend_memrchr(fe->common.arg_info[i].class_name, '\\', fe->common.arg_info[i].class_name_len)) == NULL || strcasecmp(colon+1, proto->common.arg_info[i].class_name) != 0) { zend_class_entry **fe_ce, **proto_ce; int found, found2; found = zend_lookup_class(fe->common.arg_info[i].class_name, fe->common.arg_info[i].class_name_len, &fe_ce TSRMLS_CC); found2 = zend_lookup_class(proto->common.arg_info[i].class_name, proto->common.arg_info[i].class_name_len, &proto_ce TSRMLS_CC); /* Check for class alias */ if (found != SUCCESS || found2 != SUCCESS || (*fe_ce)->type == ZEND_INTERNAL_CLASS || (*proto_ce)->type == ZEND_INTERNAL_CLASS || *fe_ce != *proto_ce) { return 0; } } } if (fe->common.arg_info[i].type_hint != proto->common.arg_info[i].type_hint) { /* Incompatible type hint */ return 0; } /* by-ref constraints on arguments are invariant */ if (fe->common.arg_info[i].pass_by_reference != proto->common.arg_info[i].pass_by_reference) { return 0; } } if (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) { for (i=proto->common.num_args; i < fe->common.num_args; i++) { if (!fe->common.arg_info[i].pass_by_reference) { return 0; } } } return 1; } /* }}} */ #define REALLOC_BUF_IF_EXCEED(buf, offset, length, size) \ if (UNEXPECTED(offset - buf + size >= length)) { \ length += size + 1; \ buf = erealloc(buf, length); \ } static char * zend_get_function_declaration(zend_function *fptr TSRMLS_DC) /* {{{ */ { char *offset, *buf; zend_uint length = 1024; offset = buf = (char *)emalloc(length * sizeof(char)); if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { *(offset++) = '&'; *(offset++) = ' '; } if (fptr->common.scope) { memcpy(offset, fptr->common.scope->name, fptr->common.scope->name_length); offset += fptr->common.scope->name_length; *(offset++) = ':'; *(offset++) = ':'; } { size_t name_len = strlen(fptr->common.function_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, name_len); memcpy(offset, fptr->common.function_name, name_len); offset += name_len; } *(offset++) = '('; if (fptr->common.arg_info) { zend_uint i, required; zend_arg_info *arg_info = fptr->common.arg_info; required = fptr->common.required_num_args; for (i = 0; i < fptr->common.num_args;) { if (arg_info->class_name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->class_name_len); memcpy(offset, arg_info->class_name, arg_info->class_name_len); offset += arg_info->class_name_len; *(offset++) = ' '; } else if (arg_info->type_hint) { zend_uint type_name_len; char *type_name = zend_get_type_by_const(arg_info->type_hint); type_name_len = strlen(type_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, type_name_len); memcpy(offset, type_name, type_name_len); offset += type_name_len; *(offset++) = ' '; } if (arg_info->pass_by_reference) { *(offset++) = '&'; } *(offset++) = '$'; if (arg_info->name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->name_len); memcpy(offset, arg_info->name, arg_info->name_len); offset += arg_info->name_len; } else { zend_uint idx = i; memcpy(offset, "param", 5); offset += 5; do { *(offset++) = (char) (idx % 10) + '0'; idx /= 10; } while (idx > 0); } if (i >= required) { *(offset++) = ' '; *(offset++) = '='; *(offset++) = ' '; if (fptr->type == ZEND_USER_FUNCTION) { zend_op *precv = NULL; { zend_uint idx = i; zend_op *op = ((zend_op_array *)fptr)->opcodes; zend_op *end = op + ((zend_op_array *)fptr)->last; ++idx; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT) && op->op1.num == (long)idx) { precv = op; } ++op; } } if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) { zval *zv, zv_copy; int use_copy; ALLOC_ZVAL(zv); *zv = *precv->op2.zv; zval_copy_ctor(zv); INIT_PZVAL(zv); zval_update_constant_ex(&zv, (void*)1, fptr->common.scope TSRMLS_CC); if (Z_TYPE_P(zv) == IS_BOOL) { if (Z_LVAL_P(zv)) { memcpy(offset, "true", 4); offset += 4; } else { memcpy(offset, "false", 5); offset += 5; } } else if (Z_TYPE_P(zv) == IS_NULL) { memcpy(offset, "NULL", 4); offset += 4; } else if (Z_TYPE_P(zv) == IS_STRING) { *(offset++) = '\''; REALLOC_BUF_IF_EXCEED(buf, offset, length, MIN(Z_STRLEN_P(zv), 10)); memcpy(offset, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 10)); offset += MIN(Z_STRLEN_P(zv), 10); if (Z_STRLEN_P(zv) > 10) { *(offset++) = '.'; *(offset++) = '.'; *(offset++) = '.'; } *(offset++) = '\''; } else if (Z_TYPE_P(zv) == IS_ARRAY) { memcpy(offset, "Array", 5); offset += 5; } else { zend_make_printable_zval(zv, &zv_copy, &use_copy); REALLOC_BUF_IF_EXCEED(buf, offset, length, Z_STRLEN(zv_copy)); memcpy(offset, Z_STRVAL(zv_copy), Z_STRLEN(zv_copy)); offset += Z_STRLEN(zv_copy); if (use_copy) { zval_dtor(&zv_copy); } } zval_ptr_dtor(&zv); } } else { memcpy(offset, "NULL", 4); offset += 4; } } if (++i < fptr->common.num_args) { *(offset++) = ','; *(offset++) = ' '; } arg_info++; REALLOC_BUF_IF_EXCEED(buf, offset, length, 32); } } *(offset++) = ')'; *offset = '\0'; return buf; } /* }}} */ static void do_inheritance_check_on_method(zend_function *child, zend_function *parent TSRMLS_DC) /* {{{ */ { zend_uint child_flags; zend_uint parent_flags = parent->common.fn_flags; if (parent->common.fn_flags & ZEND_ACC_ABSTRACT && parent->common.scope != (child->common.prototype ? child->common.prototype->common.scope : child->common.scope) && child->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_IMPLEMENTED_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Can't inherit abstract function %s::%s() (previously declared abstract in %s)", parent->common.scope->name, child->common.function_name, child->common.prototype ? child->common.prototype->common.scope->name : child->common.scope->name); } if (parent_flags & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot override final method %s::%s()", ZEND_FN_SCOPE_NAME(parent), child->common.function_name); } child_flags = child->common.fn_flags; /* You cannot change from static to non static and vice versa. */ if ((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC)) { if (child->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot make non static method %s::%s() static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } else { zend_error(E_COMPILE_ERROR, "Cannot make static method %s::%s() non static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } } /* Disallow making an inherited method abstract. */ if ((child_flags & ZEND_ACC_ABSTRACT) && !(parent_flags & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Cannot make non abstract method %s::%s() abstract in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } if (parent_flags & ZEND_ACC_CHANGED) { child->common.fn_flags |= ZEND_ACC_CHANGED; } else { /* Prevent derived classes from restricting access that was available in parent classes */ if ((child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::%s() must be %s (as in class %s)%s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if (((child_flags & ZEND_ACC_PPP_MASK) < (parent_flags & ZEND_ACC_PPP_MASK)) && ((parent_flags & ZEND_ACC_PPP_MASK) & ZEND_ACC_PRIVATE)) { child->common.fn_flags |= ZEND_ACC_CHANGED; } } if (parent_flags & ZEND_ACC_PRIVATE) { child->common.prototype = NULL; } else if (parent_flags & ZEND_ACC_ABSTRACT) { child->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; child->common.prototype = parent; } else if (!(parent->common.fn_flags & ZEND_ACC_CTOR) || (parent->common.prototype && (parent->common.prototype->common.scope->ce_flags & ZEND_ACC_INTERFACE))) { /* ctors only have a prototype if it comes from an interface */ child->common.prototype = parent->common.prototype ? parent->common.prototype : parent; } if (child->common.prototype && (child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { if (!zend_do_perform_implementation_check(child, child->common.prototype TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s::%s() must be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_get_function_declaration(child->common.prototype TSRMLS_CC)); } } else if (EG(error_reporting) & E_STRICT || EG(user_error_handler)) { /* Check E_STRICT (or custom error handler) before the check so that we save some time */ if (!zend_do_perform_implementation_check(child, parent TSRMLS_CC)) { char *method_prototype = zend_get_function_declaration(child->common.prototype TSRMLS_CC); zend_error(E_STRICT, "Declaration of %s::%s() should be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, method_prototype); efree(method_prototype); } } } /* }}} */ static zend_bool do_inherit_method_check(HashTable *child_function_table, zend_function *parent, const zend_hash_key *hash_key, zend_class_entry *child_ce) /* {{{ */ { zend_uint parent_flags = parent->common.fn_flags; zend_function *child; TSRMLS_FETCH(); if (zend_hash_quick_find(child_function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child)==FAILURE) { if (parent_flags & (ZEND_ACC_ABSTRACT)) { child_ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } return 1; /* method doesn't exist in child, copy from parent */ } do_inheritance_check_on_method(child, parent TSRMLS_CC); return 0; } /* }}} */ static zend_bool do_inherit_property_access_check(HashTable *target_ht, zend_property_info *parent_info, const zend_hash_key *hash_key, zend_class_entry *ce) /* {{{ */ { zend_property_info *child_info; zend_class_entry *parent_ce = ce->parent; if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW)) { if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { child_info->flags |= ZEND_ACC_CHANGED; } else { zend_hash_quick_update(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, parent_info, sizeof(zend_property_info), (void **) &child_info); if(ce->type & ZEND_INTERNAL_CLASS) { zend_duplicate_property_info_internal(child_info); } else { zend_duplicate_property_info(child_info); } child_info->flags &= ~ZEND_ACC_PRIVATE; /* it's not private anymore */ child_info->flags |= ZEND_ACC_SHADOW; /* but it's a shadow of private */ } return 0; /* don't copy access information to child */ } if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { if ((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s", (parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", parent_ce->name, hash_key->arKey, (child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ce->name, hash_key->arKey); } if(parent_info->flags & ZEND_ACC_CHANGED) { child_info->flags |= ZEND_ACC_CHANGED; } if ((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ce->name, hash_key->arKey, zend_visibility_string(parent_info->flags), parent_ce->name, (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if ((child_info->flags & ZEND_ACC_STATIC) == 0) { Z_DELREF_P(ce->default_properties_table[parent_info->offset]); ce->default_properties_table[parent_info->offset] = ce->default_properties_table[child_info->offset]; ce->default_properties_table[child_info->offset] = NULL; child_info->offset = parent_info->offset; } return 0; /* Don't copy from parent */ } else { return 1; /* Copy from parent */ } } /* }}} */ static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce TSRMLS_CC) == FAILURE) { zend_error(E_CORE_ERROR, "Class %s could not implement interface %s", ce->name, iface->name); } if (ce == iface) { zend_error(E_ERROR, "Interface %s cannot implement itself", ce->name); } } /* }}} */ ZEND_API void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface TSRMLS_DC) /* {{{ */ { /* expects interface to be contained in ce's interface list already */ zend_uint i, ce_num, if_num = iface->num_interfaces; zend_class_entry *entry; if (if_num==0) { return; } ce_num = ce->num_interfaces; if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } /* Inherit the interfaces, only if they're not already inherited by the class */ while (if_num--) { entry = iface->interfaces[if_num]; for (i = 0; i < ce_num; i++) { if (ce->interfaces[i] == entry) { break; } } if (i == ce_num) { ce->interfaces[ce->num_interfaces++] = entry; } } /* and now call the implementing handlers */ while (ce_num < ce->num_interfaces) { do_implement_interface(ce, ce->interfaces[ce_num++] TSRMLS_CC); } } /* }}} */ #ifdef ZTS static void zval_internal_ctor(zval **p) /* {{{ */ { zval *orig_ptr = *p; ALLOC_ZVAL(*p); MAKE_COPY_ZVAL(&orig_ptr, *p); } /* }}} */ # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) (((parent_ce)->type != (ce)->type) ? zval_internal_ctor : zval_add_ref)) #else # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) zval_add_ref) #endif ZEND_API void zend_do_inheritance(zend_class_entry *ce, zend_class_entry *parent_ce TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; if ((ce->ce_flags & ZEND_ACC_INTERFACE) && !(parent_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ce->name, parent_ce->name); } if (parent_ce->ce_flags & ZEND_ACC_FINAL_CLASS) { zend_error(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ce->name, parent_ce->name); } ce->parent = parent_ce; /* Copy serialize/unserialize callbacks */ if (!ce->serialize) { ce->serialize = parent_ce->serialize; } if (!ce->unserialize) { ce->unserialize = parent_ce->unserialize; } /* Inherit interfaces */ zend_do_inherit_interfaces(ce, parent_ce TSRMLS_CC); /* Inherit properties */ if (parent_ce->default_properties_count) { int i = ce->default_properties_count + parent_ce->default_properties_count; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_properties_count) { while (i-- > parent_ce->default_properties_count) { ce->default_properties_table[i] = ce->default_properties_table[i - parent_ce->default_properties_count]; } } for (i = 0; i < parent_ce->default_properties_count; i++) { ce->default_properties_table[i] = parent_ce->default_properties_table[i]; if (ce->default_properties_table[i]) { #ifdef ZTS if (parent_ce->type != ce->type) { zval *p; ALLOC_ZVAL(p); MAKE_COPY_ZVAL(&ce->default_properties_table[i], p); ce->default_properties_table[i] = p; } else { Z_ADDREF_P(ce->default_properties_table[i]); } #else Z_ADDREF_P(ce->default_properties_table[i]); #endif } } ce->default_properties_count += parent_ce->default_properties_count; } if (parent_ce->type != ce->type) { /* User class extends internal class */ zend_update_class_constants(parent_ce TSRMLS_CC); if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = erealloc(ce->default_static_members_table, sizeof(void*) * i); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&CE_STATIC_MEMBERS(parent_ce)[i]); ce->default_static_members_table[i] = CE_STATIC_MEMBERS(parent_ce)[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; ce->static_members_table = ce->default_static_members_table; } } else { if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&parent_ce->default_static_members_table[i]); ce->default_static_members_table[i] = parent_ce->default_static_members_table[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } } for (zend_hash_internal_pointer_reset(&ce->properties_info); zend_hash_get_current_data(&ce->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->properties_info)) { if (property_info->ce == ce) { if (property_info->flags & ZEND_ACC_STATIC) { property_info->offset += parent_ce->default_static_members_count; } else { property_info->offset += parent_ce->default_properties_count; } } } zend_hash_merge_ex(&ce->properties_info, &parent_ce->properties_info, (copy_ctor_func_t) (ce->type & ZEND_INTERNAL_CLASS ? zend_duplicate_property_info_internal : zend_duplicate_property_info), sizeof(zend_property_info), (merge_checker_func_t) do_inherit_property_access_check, ce); zend_hash_merge(&ce->constants_table, &parent_ce->constants_table, zval_property_ctor(parent_ce, ce), NULL, sizeof(zval *), 0); zend_hash_merge_ex(&ce->function_table, &parent_ce->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_inherit_parent_constructor(ce); if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS && ce->type == ZEND_INTERNAL_CLASS) { ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } else if (!(ce->ce_flags & ZEND_ACC_IMPLEMENT_INTERFACES) && !(ce->ce_flags & ZEND_ACC_IMPLEMENT_TRAITS)) { /* The verification will be done in runtime by ZEND_VERIFY_ABSTRACT_CLASS */ zend_verify_abstract_class(ce TSRMLS_CC); } ce->ce_flags |= parent_ce->ce_flags & ZEND_HAS_STATIC_IN_METHODS; } /* }}} */ static zend_bool do_inherit_constant_check(HashTable *child_constants_table, const zval **parent_constant, const zend_hash_key *hash_key, const zend_class_entry *iface) /* {{{ */ { zval **old_constant; if (zend_hash_quick_find(child_constants_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**)&old_constant) == SUCCESS) { if (*old_constant != *parent_constant) { zend_error(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", hash_key->arKey, iface->name); } return 0; } return 1; } /* }}} */ static int do_interface_constant_check(zval **val TSRMLS_DC, int num_args, va_list args, const zend_hash_key *key) /* {{{ */ { zend_class_entry **iface = va_arg(args, zend_class_entry**); do_inherit_constant_check(&(*iface)->constants_table, (const zval **) val, key, *iface); return ZEND_HASH_APPLY_KEEP; } /* }}} */ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_iface_num = ce->num_interfaces; zend_uint parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0; for (i = 0; i < ce->num_interfaces; i++) { if (ce->interfaces[i] == NULL) { memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i)); i--; } else if (ce->interfaces[i] == iface) { if (i < parent_iface_num) { ignore = 1; } else { zend_error(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ce->name, iface->name); } } } if (ignore) { /* Check for attempt to redeclare interface constants */ zend_hash_apply_with_arguments(&ce->constants_table TSRMLS_CC, (apply_func_args_t) do_interface_constant_check, 1, &iface); } else { if (ce->num_interfaces >= current_iface_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } } ce->interfaces[ce->num_interfaces++] = iface; zend_hash_merge_ex(&ce->constants_table, &iface->constants_table, (copy_ctor_func_t) zval_add_ref, sizeof(zval *), (merge_checker_func_t) do_inherit_constant_check, iface); zend_hash_merge_ex(&ce->function_table, &iface->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_implement_interface(ce, iface TSRMLS_CC); zend_do_inherit_interfaces(ce, iface TSRMLS_CC); } } /* }}} */ ZEND_API void zend_do_implement_trait(zend_class_entry *ce, zend_class_entry *trait TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_trait_num = ce->num_traits; zend_uint parent_trait_num = ce->parent ? ce->parent->num_traits : 0; for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == NULL) { memmove(ce->traits + i, ce->traits + i + 1, sizeof(zend_class_entry*) * (--ce->num_traits - i)); i--; } else if (ce->traits[i] == trait) { if (i < parent_trait_num) { ignore = 1; } } } if (!ignore) { if (ce->num_traits >= current_trait_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->traits = (zend_class_entry **) realloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } else { ce->traits = (zend_class_entry **) erealloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } } ce->traits[ce->num_traits++] = trait; } } /* }}} */ static int zend_traits_merge_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { size_t current; size_t i; size_t count; HashTable* resulting_table; HashTable** function_tables; zend_class_entry *ce; size_t collision = 0; size_t abstract_solved = 0; zend_function* other_trait_fn; current = va_arg(args, size_t); /* index of current trait */ count = va_arg(args, size_t); resulting_table = va_arg(args, HashTable*); function_tables = va_arg(args, HashTable**); ce = va_arg(args, zend_class_entry*); for (i = 0; i < count; i++) { if (i == current) { continue; /* just skip this, cause its the table this function is applied on */ } if (zend_hash_quick_find(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&other_trait_fn) == SUCCESS) { /* if it is an abstract method, there is no collision */ if (other_trait_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible */ do_inheritance_check_on_method(fn, other_trait_fn TSRMLS_CC); /* we can savely free and remove it from other table */ zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } else { /* if it is not an abstract method, there is still no collision */ /* if fn is an abstract method */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible */ do_inheritance_check_on_method(other_trait_fn, fn TSRMLS_CC); /* just mark as solved, will be added if its own trait is processed */ abstract_solved = 1; } else { /* but else, we have a collision of non-abstract methods */ collision++; zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } } } if (collision) { zend_function* class_fn; /* make sure method is not already overridden in class */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&class_fn) == FAILURE || class_fn->common.scope != ce) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because there are collisions with other trait methods on %s", fn->common.function_name, ce->name); } zend_function_dtor(fn); } else if (abstract_solved) { zend_function_dtor(fn); } else { /* Add it to result function table */ if (zend_hash_quick_add(resulting_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, fn, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating resulting trait method table", fn->common.function_name); } } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ /* {{{ Originates from php_runkit_function_copy_ctor Duplicate structures in an op_array where necessary to make an outright duplicate */ static void zend_traits_duplicate_function(zend_function *fe, zend_class_entry *target_ce, char *newname TSRMLS_DC) { zend_literal *literals_copy; zend_compiled_variable *dupvars; zend_op *opcode_copy; zval class_name_zv; int class_name_literal; int i; int number_of_literals; if (fe->op_array.static_variables) { HashTable *tmpHash; ALLOC_HASHTABLE(tmpHash); zend_hash_init(tmpHash, zend_hash_num_elements(fe->op_array.static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_apply_with_arguments(fe->op_array.static_variables TSRMLS_CC, (apply_func_args_t)zval_copy_static_var, 1, tmpHash); fe->op_array.static_variables = tmpHash; } number_of_literals = fe->op_array.last_literal; literals_copy = (zend_literal*)emalloc(number_of_literals * sizeof(zend_literal)); for (i = 0; i < number_of_literals; i++) { literals_copy[i] = fe->op_array.literals[i]; zval_copy_ctor(&literals_copy[i].constant); } fe->op_array.literals = literals_copy; fe->op_array.refcount = emalloc(sizeof(zend_uint)); *(fe->op_array.refcount) = 1; if (fe->op_array.vars) { i = fe->op_array.last_var; dupvars = safe_emalloc(fe->op_array.last_var, sizeof(zend_compiled_variable), 0); while (i > 0) { i--; dupvars[i].name = estrndup(fe->op_array.vars[i].name, fe->op_array.vars[i].name_len); dupvars[i].name_len = fe->op_array.vars[i].name_len; dupvars[i].hash_value = fe->op_array.vars[i].hash_value; } fe->op_array.vars = dupvars; } else { fe->op_array.vars = NULL; } opcode_copy = safe_emalloc(sizeof(zend_op), fe->op_array.last, 0); for(i = 0; i < fe->op_array.last; i++) { opcode_copy[i] = fe->op_array.opcodes[i]; if (opcode_copy[i].op1_type != IS_CONST) { if (opcode_copy[i].op1.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op1.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op1.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op1.jmp_addr - fe->op_array.opcodes); } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op1.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op1.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op1.zv = &fe->op_array.literals[class_name_literal].constant; } } if (opcode_copy[i].op2_type != IS_CONST) { if (opcode_copy[i].op2.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op2.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op2.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op2.jmp_addr - fe->op_array.opcodes); } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op2.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op2.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op2.zv = &fe->op_array.literals[class_name_literal].constant; } } } fe->op_array.opcodes = opcode_copy; fe->op_array.function_name = newname; /* was setting it to fe which does not work since fe is stack allocated and not a stable address */ /* fe->op_array.prototype = fe->op_array.prototype; */ if (fe->op_array.arg_info) { zend_arg_info *tmpArginfo; tmpArginfo = safe_emalloc(sizeof(zend_arg_info), fe->op_array.num_args, 0); for(i = 0; i < fe->op_array.num_args; i++) { tmpArginfo[i] = fe->op_array.arg_info[i]; tmpArginfo[i].name = estrndup(tmpArginfo[i].name, tmpArginfo[i].name_len); if (tmpArginfo[i].class_name) { tmpArginfo[i].class_name = estrndup(tmpArginfo[i].class_name, tmpArginfo[i].class_name_len); } } fe->op_array.arg_info = tmpArginfo; } fe->op_array.doc_comment = estrndup(fe->op_array.doc_comment, fe->op_array.doc_comment_len); fe->op_array.try_catch_array = (zend_try_catch_element*)estrndup((char*)fe->op_array.try_catch_array, sizeof(zend_try_catch_element) * fe->op_array.last_try_catch); fe->op_array.brk_cont_array = (zend_brk_cont_element*)estrndup((char*)fe->op_array.brk_cont_array, sizeof(zend_brk_cont_element) * fe->op_array.last_brk_cont); } /* }}} */ static void zend_add_magic_methods(zend_class_entry* ce, const char* mname, uint mname_len, zend_function* fe TSRMLS_DC) { if ( !strncmp(mname, ZEND_CLONE_FUNC_NAME, mname_len)) { ce->clone = fe; fe->common.fn_flags |= ZEND_ACC_CLONE; } else if (!strncmp(mname, ZEND_CONSTRUCTOR_FUNC_NAME, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } else if (!strncmp(mname, ZEND_DESTRUCTOR_FUNC_NAME, mname_len)) { ce->destructor = fe; fe->common.fn_flags |= ZEND_ACC_DTOR; } else if (!strncmp(mname, ZEND_GET_FUNC_NAME, mname_len)) ce->__get = fe; else if (!strncmp(mname, ZEND_SET_FUNC_NAME, mname_len)) ce->__set = fe; else if (!strncmp(mname, ZEND_CALL_FUNC_NAME, mname_len)) ce->__call = fe; else if (!strncmp(mname, ZEND_UNSET_FUNC_NAME, mname_len)) ce->__unset = fe; else if (!strncmp(mname, ZEND_ISSET_FUNC_NAME, mname_len)) ce->__isset = fe; else if (!strncmp(mname, ZEND_CALLSTATIC_FUNC_NAME, mname_len)) ce->__callstatic= fe; else if (!strncmp(mname, ZEND_TOSTRING_FUNC_NAME, mname_len)) ce->__tostring = fe; else if (ce->name_length + 1 == mname_len) { char *lowercase_name = emalloc(ce->name_length + 1); zend_str_tolower_copy(lowercase_name, ce->name, ce->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, ce->name_length + 1, 1 TSRMLS_CC); if (!memcmp(mname, lowercase_name, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } str_efree(lowercase_name); } } static int zend_traits_merge_functions_to_class(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zend_class_entry *ce = va_arg(args, zend_class_entry*); int add = 0; zend_function* existing_fn = NULL; zend_function fn_copy, *fn_copy_p; zend_function* prototype = NULL; /* is used to determine the prototype according to the inheritance chain */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &existing_fn) == FAILURE) { add = 1; /* not found */ } else if (existing_fn->common.scope != ce) { add = 1; /* or inherited from other class or interface */ } if (add) { zend_function* parent_function; if (ce->parent && zend_hash_quick_find(&ce->parent->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &parent_function) != FAILURE) { prototype = parent_function; /* ->common.fn_flags |= ZEND_ACC_ABSTRACT; */ /* we got that method in the parent class, and are going to override it, except, if the trait is just asking to have an abstract method implemented. */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* then we clean up an skip this method */ zend_function_dtor(fn); return ZEND_HASH_APPLY_REMOVE; } } fn->common.scope = ce; fn->common.prototype = prototype; if (prototype && (prototype->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT || prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { fn->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; } else if (fn->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT) { /* remove ZEND_ACC_IMPLEMENTED_ABSTRACT flag, think it shouldn't be copied to class */ fn->common.fn_flags = fn->common.fn_flags - ZEND_ACC_IMPLEMENTED_ABSTRACT; } /* check whether the trait method fullfills the inheritance requirements */ if (prototype) { do_inheritance_check_on_method(fn, prototype TSRMLS_CC); } /* one more thing: make sure we properly implement an abstract method */ if (existing_fn && existing_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { do_inheritance_check_on_method(fn, existing_fn TSRMLS_CC); } /* delete inherited fn if the function to be added is not abstract */ if (existing_fn && existing_fn->common.scope != ce && (fn->common.fn_flags & ZEND_ACC_ABSTRACT) == 0) { /* it is just a reference which was added to the subclass while doing the inheritance, so we can deleted now, and will add the overriding method afterwards. Except, if we try to add an abstract function, then we should not delete the inherited one */ zend_hash_quick_del(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h); } if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (fn->op_array.static_variables) { ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, ce, estrdup(fn->common.function_name) TSRMLS_CC); if (zend_hash_quick_update(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, &fn_copy, sizeof(zend_function), (void**)&fn_copy_p)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating class method table", hash_key->arKey); } zend_add_magic_methods(ce, hash_key->arKey, hash_key->nKeyLength, fn_copy_p TSRMLS_CC); zend_function_dtor(fn); } else { zend_function_dtor(fn); } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ static int zend_traits_copy_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { HashTable* target; zend_class_entry *target_ce; zend_trait_alias** aliases; HashTable* exclude_table; char* lcname; unsigned int fnname_len; zend_function fn_copy; void* dummy; size_t i = 0; target = va_arg(args, HashTable*); target_ce = va_arg(args, zend_class_entry*); aliases = va_arg(args, zend_trait_alias**); exclude_table = va_arg(args, HashTable*); fnname_len = strlen(fn->common.function_name); /* apply aliases which are qualified with a class name, there should not be any ambiguity */ if (aliases) { while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias != NULL && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && aliases[i]->trait_method->mname_len == fnname_len && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(aliases[i]->alias, aliases[i]->alias_len) TSRMLS_CC); /* if it is 0, no modifieres has been changed */ if (aliases[i]->modifiers) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } lcname = zend_str_tolower_dup(aliases[i]->alias, aliases[i]->alias_len); if (zend_hash_add(target, lcname, aliases[i]->alias_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add aliased trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } efree(lcname); } i++; } } lcname = zend_str_tolower_dup(fn->common.function_name, fnname_len); if (exclude_table == NULL || zend_hash_find(exclude_table, lcname, fnname_len, &dummy) == FAILURE) { /* is not in hashtable, thus, function is not to be excluded */ fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(fn->common.function_name, fnname_len) TSRMLS_CC); /* apply aliases which are not qualified by a class name, or which have not * alias name, just setting visibility */ if (aliases) { i = 0; while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias == NULL && aliases[i]->modifiers != 0 && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && (aliases[i]->trait_method->mname_len == fnname_len) && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } i++; } } if (zend_hash_add(target, lcname, fnname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } } efree(lcname); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* Copies function table entries to target function table with applied aliasing */ static void zend_traits_copy_trait_function_table(HashTable *target, zend_class_entry *target_ce, HashTable *source, zend_trait_alias** aliases, HashTable* exclude_table TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_arguments(source TSRMLS_CC, (apply_func_args_t)zend_traits_copy_functions, 4, target, target_ce, aliases, exclude_table); } /* }}} */ static void zend_traits_init_trait_structures(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i, j = 0; zend_trait_precedence *cur_precedence; zend_trait_method_reference *cur_method_ref; /* resolve class references */ if (ce->trait_precedences) { i = 0; while ((cur_precedence = ce->trait_precedences[i])) { if (cur_precedence->exclude_from_classes) { cur_precedence->trait_method->ce = zend_fetch_class(cur_precedence->trait_method->class_name, cur_precedence->trait_method->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); j = 0; while (cur_precedence->exclude_from_classes[j]) { char* class_name = (char*)cur_precedence->exclude_from_classes[j]; zend_uint name_length = strlen(class_name); cur_precedence->exclude_from_classes[j] = zend_fetch_class(class_name, name_length, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); efree(class_name); j++; } } i++; } } if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { if (ce->trait_aliases[i]->trait_method->class_name) { cur_method_ref = ce->trait_aliases[i]->trait_method; cur_method_ref->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); } i++; } } } /* }}} */ static void zend_traits_compile_exclude_table(HashTable* exclude_table, zend_trait_precedence **precedences, zend_class_entry *trait) /* {{{ */ { size_t i = 0, j; if (!precedences) { return; } while (precedences[i]) { if (precedences[i]->exclude_from_classes) { j = 0; while (precedences[i]->exclude_from_classes[j]) { if (precedences[i]->exclude_from_classes[j] == trait) { zend_uint lcname_len = precedences[i]->trait_method->mname_len; char *lcname = zend_str_tolower_dup(precedences[i]->trait_method->method_name, lcname_len); if (zend_hash_add(exclude_table, lcname, lcname_len, NULL, 0, NULL) == FAILURE) { efree(lcname); zend_error(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", precedences[i]->trait_method->method_name, trait->name); } efree(lcname); } ++j; } } ++i; } } /* }}} */ static void zend_do_traits_method_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { HashTable** function_tables; HashTable* resulting_table; HashTable exclude_table; size_t i; /* prepare copies of trait function tables for combination */ function_tables = malloc(sizeof(HashTable*) * ce->num_traits); resulting_table = (HashTable *) malloc(sizeof(HashTable)); /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(resulting_table, 10, NULL, NULL, 1, 0); for (i = 0; i < ce->num_traits; i++) { function_tables[i] = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(function_tables[i], ce->traits[i]->function_table.nNumOfElements, NULL, NULL, 1, 0); if (ce->trait_precedences) { /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(&exclude_table, 2, NULL, NULL, 0, 0); zend_traits_compile_exclude_table(&exclude_table, ce->trait_precedences, ce->traits[i]); /* copies functions, applies defined aliasing, and excludes unused trait methods */ zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, &exclude_table TSRMLS_CC); zend_hash_graceful_destroy(&exclude_table); } else { zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, NULL TSRMLS_CC); } } /* now merge trait methods */ for (i = 0; i < ce->num_traits; i++) { zend_hash_apply_with_arguments(function_tables[i] TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions, 5, i, ce->num_traits, resulting_table, function_tables, ce); } /* Now the resulting_table contains all trait methods we would have to * add to the class in the following step the methods are inserted into the method table * if there is already a method with the same name it is replaced iff ce != fn.scope * --> all inherited methods are overridden, methods defined in the class are left untouched */ zend_hash_apply_with_arguments(resulting_table TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions_to_class, 1, ce); /* free temporary function tables */ for (i = 0; i < ce->num_traits; i++) { /* zend_hash_destroy(function_tables[i]); */ zend_hash_graceful_destroy(function_tables[i]); free(function_tables[i]); } free(function_tables); /* free temporary resulting table */ /* zend_hash_destroy(resulting_table); */ zend_hash_graceful_destroy(resulting_table); free(resulting_table); } /* }}} */ static zend_class_entry* find_first_definition(zend_class_entry *ce, size_t current_trait, const char* prop_name, int prop_name_length, ulong prop_hash, zend_class_entry *coliding_ce) /* {{{ */ { size_t i; zend_property_info *coliding_prop; for (i = 0; (i < current_trait) && (i < ce->num_traits); i++) { if (zend_hash_quick_find(&ce->traits[i]->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS) { return ce->traits[i]; } } return coliding_ce; } /* }}} */ static void zend_do_traits_property_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i; zend_property_info *property_info; zend_property_info *coliding_prop; zval compare_result; const char* prop_name; int prop_name_length; ulong prop_hash; const char* class_name_unused; zend_bool prop_found; zend_bool not_compatible; zval* prop_value; /* In the following steps the properties are inserted into the property table * for that, a very strict approach is applied: * - check for compatibility, if not compatible with any property in class -> fatal * - if compatible, then strict notice */ for (i = 0; i < ce->num_traits; i++) { for (zend_hash_internal_pointer_reset(&ce->traits[i]->properties_info); zend_hash_get_current_data(&ce->traits[i]->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->traits[i]->properties_info)) { /* first get the unmangeld name if necessary, * then check whether the property is already there */ if ((property_info->flags & ZEND_ACC_PPP_MASK) == ZEND_ACC_PUBLIC) { prop_hash = property_info->h; prop_name = property_info->name; prop_name_length = property_info->name_length; prop_found = zend_hash_quick_find(&ce->properties_info, property_info->name, property_info->name_length+1, property_info->h, (void **) &coliding_prop) == SUCCESS; } else { /* for private and protected we need to unmangle the names */ zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name_unused, &prop_name); prop_name_length = strlen(prop_name); prop_hash = zend_get_hash_value(prop_name, prop_name_length + 1); prop_found = zend_hash_quick_find(&ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS; } /* next: check for conflicts with current class */ if (prop_found) { if (coliding_prop->flags & ZEND_ACC_SHADOW) { /* this one is inherited, lets look it up in its own class */ zend_hash_quick_find(&coliding_prop->ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop); } if ((coliding_prop->flags & ZEND_ACC_PPP_MASK) == (property_info->flags & ZEND_ACC_PPP_MASK)) { /* flags are identical, now the value needs to be checked */ if (property_info->flags & ZEND_ACC_STATIC) { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_static_members_table[coliding_prop->offset], ce->traits[i]->default_static_members_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } else { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_properties_table[coliding_prop->offset], ce->traits[i]->default_properties_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } } else { /* the flags are not identical, thus, we assume properties are not compatible */ not_compatible = 1; } if (not_compatible) { zend_error(E_COMPILE_ERROR, "%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } else { zend_error(E_STRICT, "%s and %s define the same property ($%s) in the composition of %s. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } } /* property not found, so lets add it */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); zend_declare_property_ex(ce, prop_name, prop_name_length, prop_value, property_info->flags, property_info->doc_comment, property_info->doc_comment_len TSRMLS_CC); } } } /* }}} */ ZEND_API void zend_do_bind_traits(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { if (ce->num_traits <= 0) { return; } /* complete initialization of trait strutures in ce */ zend_traits_init_trait_structures(ce TSRMLS_CC); /* first care about all methods to be flattened into the class */ zend_do_traits_method_binding(ce TSRMLS_CC); /* then flatten the properties into it, to, mostly to notfiy developer about problems */ zend_do_traits_property_binding(ce TSRMLS_CC); /* verify that all abstract methods from traits have been implemented */ zend_verify_abstract_class(ce TSRMLS_CC); /* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */ if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { ce->ce_flags -= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } } /* }}} */ ZEND_API int do_bind_function(const zend_op_array *op_array, zend_op *opline, HashTable *function_table, zend_bool compile_time) /* {{{ */ { zend_function *function; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } zend_hash_quick_find(function_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void *) &function); if (zend_hash_quick_add(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), function, sizeof(zend_function), NULL)==FAILURE) { int error_level = compile_time ? E_COMPILE_ERROR : E_ERROR; zend_function *old_function; if (zend_hash_quick_find(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), (void *) &old_function)==SUCCESS && old_function->type == ZEND_USER_FUNCTION && old_function->op_array.last > 0) { zend_error(error_level, "Cannot redeclare %s() (previously declared in %s:%d)", function->common.function_name, old_function->op_array.filename, old_function->op_array.opcodes[0].lineno); } else { zend_error(error_level, "Cannot redeclare %s()", function->common.function_name); } return FAILURE; } else { (*function->op_array.refcount)++; function->op_array.static_variables = NULL; /* NULL out the unbound function */ return SUCCESS; } } /* }}} */ void zend_add_trait_precedence(znode *precedence_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_precedences, precedence_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_add_trait_alias(znode *alias_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_aliases, alias_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_prepare_reference(znode *result, znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { zend_trait_method_reference *method_ref = emalloc(sizeof(zend_trait_method_reference)); method_ref->ce = NULL; /* REM: There should not be a need for copying, zend_do_begin_class_declaration is also just using that string */ if (class_name) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); method_ref->class_name = Z_STRVAL(class_name->u.constant); method_ref->cname_len = Z_STRLEN(class_name->u.constant); } else { method_ref->class_name = NULL; method_ref->cname_len = 0; } method_ref->method_name = Z_STRVAL(method_name->u.constant); method_ref->mname_len = Z_STRLEN(method_name->u.constant); result->u.op.ptr = method_ref; result->op_type = IS_TMP_VAR; } /* }}} */ void zend_prepare_trait_alias(znode *result, znode *method_reference, znode *modifiers, znode *alias TSRMLS_DC) /* {{{ */ { zend_trait_alias *trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_alias->modifiers = Z_LVAL(modifiers->u.constant); if (Z_LVAL(modifiers->u.constant) == ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot use 'static' as method modifier"); return; } if (alias) { trait_alias->alias = Z_STRVAL(alias->u.constant); trait_alias->alias_len = Z_STRLEN(alias->u.constant); } else { trait_alias->alias = NULL; } trait_alias->function = NULL; result->u.op.ptr = trait_alias; } /* }}} */ void zend_prepare_trait_precedence(znode *result, znode *method_reference, znode *trait_list TSRMLS_DC) /* {{{ */ { zend_trait_precedence *trait_precedence = emalloc(sizeof(zend_trait_precedence)); trait_precedence->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_precedence->exclude_from_classes = (zend_class_entry**) trait_list->u.op.ptr; trait_precedence->function = NULL; result->u.op.ptr = trait_precedence; } /* }}} */ ZEND_API zend_class_entry *do_bind_class(const zend_op_array* op_array, const zend_op *opline, HashTable *class_table, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } if (zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce)==FAILURE) { zend_error(E_COMPILE_ERROR, "Internal Zend error - Missing class information for %s", Z_STRVAL_P(op1)); return NULL; } else { ce = *pce; } ce->refcount++; if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), &ce, sizeof(zend_class_entry *), NULL)==FAILURE) { ce->refcount--; if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return NULL; } else { if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLEMENT_INTERFACES))) { zend_verify_abstract_class(ce TSRMLS_CC); } return ce; } } /* }}} */ ZEND_API zend_class_entry *do_bind_inherited_class(const zend_op_array *op_array, const zend_op *opline, HashTable *class_table, zend_class_entry *parent_ce, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; int found_ce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } found_ce = zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce); if (found_ce == FAILURE) { if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", Z_STRVAL_P(op2)); } return NULL; } else { ce = *pce; } if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ce->name, parent_ce->name); } else if ((parent_ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ce->name, parent_ce->name); } zend_do_inheritance(ce, parent_ce TSRMLS_CC); ce->refcount++; /* Register the derived class */ if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), pce, sizeof(zend_class_entry *), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return ce; } /* }}} */ void zend_do_early_binding(TSRMLS_D) /* {{{ */ { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; HashTable *table; while (opline->opcode == ZEND_TICKS && opline > CG(active_op_array)->opcodes) { opline--; } switch (opline->opcode) { case ZEND_DECLARE_FUNCTION: if (do_bind_function(CG(active_op_array), opline, CG(function_table), 1) == FAILURE) { return; } table = CG(function_table); break; case ZEND_DECLARE_CLASS: if (do_bind_class(CG(active_op_array), opline, CG(class_table), 1 TSRMLS_CC) == NULL) { return; } table = CG(class_table); break; case ZEND_DECLARE_INHERITED_CLASS: { zend_op *fetch_class_opline = opline-1; zval *parent_name; zend_class_entry **pce; parent_name = &CONSTANT(fetch_class_opline->op2.constant); if ((zend_lookup_class(Z_STRVAL_P(parent_name), Z_STRLEN_P(parent_name), &pce TSRMLS_CC) == FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_CLASSES) && ((*pce)->type == ZEND_INTERNAL_CLASS))) { if (CG(compiler_options) & ZEND_COMPILE_DELAYED_BINDING) { zend_uint *opline_num = &CG(active_op_array)->early_binding; while (*opline_num != -1) { opline_num = &CG(active_op_array)->opcodes[*opline_num].result.opline_num; } *opline_num = opline - CG(active_op_array)->opcodes; opline->opcode = ZEND_DECLARE_INHERITED_CLASS_DELAYED; opline->result_type = IS_UNUSED; opline->result.opline_num = -1; } return; } if (do_bind_inherited_class(CG(active_op_array), opline, CG(class_table), *pce, 1 TSRMLS_CC) == NULL) { return; } /* clear unnecessary ZEND_FETCH_CLASS opcode */ zend_del_literal(CG(active_op_array), fetch_class_opline->op2.constant); MAKE_NOP(fetch_class_opline); table = CG(class_table); break; } case ZEND_VERIFY_ABSTRACT_CLASS: case ZEND_ADD_INTERFACE: case ZEND_ADD_TRAIT: case ZEND_BIND_TRAITS: /* We currently don't early-bind classes that implement interfaces */ /* Classes with traits are handled exactly the same, no early-bind here */ return; default: zend_error(E_COMPILE_ERROR, "Invalid binding type"); return; } zend_hash_quick_del(table, Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant)), Z_HASH_P(&CONSTANT(opline->op1.constant))); zend_del_literal(CG(active_op_array), opline->op1.constant); zend_del_literal(CG(active_op_array), opline->op2.constant); MAKE_NOP(opline); } /* }}} */ ZEND_API void zend_do_delayed_early_binding(const zend_op_array *op_array TSRMLS_DC) /* {{{ */ { if (op_array->early_binding != -1) { zend_bool orig_in_compilation = CG(in_compilation); zend_uint opline_num = op_array->early_binding; zend_class_entry **pce; CG(in_compilation) = 1; while (opline_num != -1) { if (zend_lookup_class(Z_STRVAL_P(op_array->opcodes[opline_num-1].op2.zv), Z_STRLEN_P(op_array->opcodes[opline_num-1].op2.zv), &pce TSRMLS_CC) == SUCCESS) { do_bind_inherited_class(op_array, &op_array->opcodes[opline_num], EG(class_table), *pce, 0 TSRMLS_CC); } opline_num = op_array->opcodes[opline_num].result.opline_num; } CG(in_compilation) = orig_in_compilation; } } /* }}} */ void zend_do_boolean_or_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_or_end(znode *result, const znode *expr1, const znode *expr2, znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_boolean_and_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_and_end(znode *result, const znode *expr1, const znode *expr2, const znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_do_while_begin(TSRMLS_D) /* {{{ */ { do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_do_while_end(const znode *do_token, const znode *expr_open_bracket, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ; SET_NODE(opline->op1, expr); opline->op2.opline_num = do_token->u.op.opline_num; SET_UNUSED(opline->op2); do_end_loop(expr_open_bracket->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_brk_cont(zend_uchar op, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->op1.opline_num = CG(context).current_brk_cont; SET_UNUSED(opline->op1); if (expr) { if (expr->op_type != IS_CONST) { zend_error(E_COMPILE_ERROR, "'%s' operator with non-constant operand is no longer supported", op == ZEND_BRK ? "break" : "continue"); } else if (Z_TYPE(expr->u.constant) != IS_LONG || Z_LVAL(expr->u.constant) < 1) { zend_error(E_COMPILE_ERROR, "'%s' operator accepts only positive numbers", op == ZEND_BRK ? "break" : "continue"); } SET_NODE(opline->op2, expr); } else { LITERAL_LONG(opline->op2, 1); opline->op2_type = IS_CONST; } } /* }}} */ void zend_do_switch_cond(const znode *cond TSRMLS_DC) /* {{{ */ { zend_switch_entry switch_entry; switch_entry.cond = *cond; switch_entry.default_case = -1; switch_entry.control_var = -1; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_switch_end(const znode *case_list TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); /* add code to jmp to default case */ if (switch_entry_ptr->default_case != -1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->op1.opline_num = switch_entry_ptr->default_case; } if (case_list->op_type != IS_UNUSED) { /* non-empty switch */ int next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* remember break/continue loop information */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; if (switch_entry_ptr->cond.op_type==IS_VAR || switch_entry_ptr->cond.op_type==IS_TMP_VAR) { /* emit free for the switch condition*/ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry_ptr->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_UNUSED(opline->op2); } if (switch_entry_ptr->cond.op_type == IS_CONST) { zval_dtor(&switch_entry_ptr->cond.u.constant); } zend_stack_del_top(&CG(switch_cond_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_case_before_statement(const znode *case_list, znode *case_token, const znode *case_expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); int next_op_number; zend_switch_entry *switch_entry_ptr; znode result; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); if (switch_entry_ptr->control_var == -1) { switch_entry_ptr->control_var = get_temporary_variable(CG(active_op_array)); } opline->opcode = ZEND_CASE; opline->result.var = switch_entry_ptr->control_var; opline->result_type = IS_TMP_VAR; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_NODE(opline->op2, case_expr); if (opline->op1_type == IS_CONST) { zval_copy_ctor(&CONSTANT(opline->op1.constant)); } GET_NODE(&result, opline->result); next_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, &result); SET_UNUSED(opline->op2); case_token->u.op.opline_num = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_case_after_statement(znode *result, const znode *case_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); result->u.op.opline_num = next_op_number; switch (CG(active_op_array)->opcodes[case_token->u.op.opline_num].opcode) { case ZEND_JMP: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); break; case ZEND_JMPZ: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); break; } } /* }}} */ void zend_do_default_before_statement(const znode *case_list, znode *default_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); default_token->u.op.opline_num = next_op_number; next_op_number = get_next_op_number(CG(active_op_array)); switch_entry_ptr->default_case = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_begin_class_declaration(const znode *class_token, znode *class_name, const znode *parent_class_name TSRMLS_DC) /* {{{ */ { zend_op *opline; int doing_inheritance = 0; zend_class_entry *new_class_entry; char *lcname; int error = 0; zval **ns_name, key; if (CG(active_class_entry)) { zend_error(E_COMPILE_ERROR, "Class declarations may not be nested"); return; } lcname = zend_str_tolower_dup(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); if (!(strcmp(lcname, "self") && strcmp(lcname, "parent"))) { efree(lcname); zend_error(E_COMPILE_ERROR, "Cannot use '%s' as class name as it is reserved", Z_STRVAL(class_name->u.constant)); } /* Class name must not conflict with import names */ if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns_name) == SUCCESS) { error = 1; } if (CG(current_namespace)) { /* Prefix class name with name of current namespace */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); class_name = &tmp; efree(lcname); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); } if (error) { char *tmp = zend_str_tolower_dup(Z_STRVAL_PP(ns_name), Z_STRLEN_PP(ns_name)); if (Z_STRLEN_PP(ns_name) != Z_STRLEN(class_name->u.constant) || memcmp(tmp, lcname, Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "Cannot declare class %s because the name is already in use", Z_STRVAL(class_name->u.constant)); } efree(tmp); } new_class_entry = emalloc(sizeof(zend_class_entry)); new_class_entry->type = ZEND_USER_CLASS; new_class_entry->name = zend_new_interned_string(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1, 1 TSRMLS_CC); new_class_entry->name_length = Z_STRLEN(class_name->u.constant); zend_initialize_class_data(new_class_entry, 1 TSRMLS_CC); new_class_entry->info.user.filename = zend_get_compiled_filename(TSRMLS_C); new_class_entry->info.user.line_start = class_token->u.op.opline_num; new_class_entry->ce_flags |= class_token->EA; if (parent_class_name && parent_class_name->op_type != IS_UNUSED) { switch (parent_class_name->EA) { case ZEND_FETCH_CLASS_SELF: zend_error(E_COMPILE_ERROR, "Cannot use 'self' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_PARENT: zend_error(E_COMPILE_ERROR, "Cannot use 'parent' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use 'static' as class name as it is reserved"); break; default: break; } doing_inheritance = 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, new_class_entry->name_length TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; if (doing_inheritance) { /* Make sure a trait does not try to extend a class */ if ((new_class_entry->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "A trait (%s) cannot extend a class", new_class_entry->name); } opline->extended_value = parent_class_name->u.op.var; opline->opcode = ZEND_DECLARE_INHERITED_CLASS; } else { opline->opcode = ZEND_DECLARE_CLASS; } LITERAL_STRINGL(opline->op2, lcname, new_class_entry->name_length, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); zend_hash_quick_update(CG(class_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &new_class_entry, sizeof(zend_class_entry *), NULL); CG(active_class_entry) = new_class_entry; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(&CG(implementing_class), opline->result); if (CG(doc_comment)) { CG(active_class_entry)->info.user.doc_comment = CG(doc_comment); CG(active_class_entry)->info.user.doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ static void do_verify_abstract_class(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_VERIFY_ABSTRACT_CLASS; SET_NODE(opline->op1, &CG(implementing_class)); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_class_declaration(const znode *class_token, const znode *parent_token TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); if (ce->constructor) { ce->constructor->common.fn_flags |= ZEND_ACC_CTOR; if (ce->constructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Constructor %s::%s() cannot be static", ce->name, ce->constructor->common.function_name); } } if (ce->destructor) { ce->destructor->common.fn_flags |= ZEND_ACC_DTOR; if (ce->destructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Destructor %s::%s() cannot be static", ce->name, ce->destructor->common.function_name); } } if (ce->clone) { ce->clone->common.fn_flags |= ZEND_ACC_CLONE; if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static", ce->name, ce->clone->common.function_name); } } ce->info.user.line_end = zend_get_compiled_lineno(TSRMLS_C); /* Check for traits and proceed like with interfaces. * The only difference will be a combined handling of them in the end. * Thus, we need another opcode here. */ if (ce->num_traits > 0) { zend_op *opline; ce->traits = NULL; ce->num_traits = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_TRAITS; /* opcode generation: */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BIND_TRAITS; SET_NODE(opline->op1, &CG(implementing_class)); } if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) && ((parent_token->op_type != IS_UNUSED) || (ce->num_interfaces > 0))) { zend_verify_abstract_class(ce TSRMLS_CC); if (ce->num_interfaces) { do_verify_abstract_class(TSRMLS_C); } } /* Inherit interfaces; reset number to zero, we need it for above check and * will restore it during actual implementation. * The ZEND_ACC_IMPLEMENT_INTERFACES flag disables double call to * zend_verify_abstract_class() */ if (ce->num_interfaces > 0) { ce->interfaces = NULL; ce->num_interfaces = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_INTERFACES; } CG(active_class_entry) = NULL; } /* }}} */ void zend_do_implements_interface(znode *interface_name TSRMLS_DC) /* {{{ */ { zend_op *opline; /* Traits can not implement interfaces */ if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface on '%s' since it is a Trait", Z_STRVAL(interface_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(interface_name->u.constant), Z_STRLEN(interface_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface name as it is reserved", Z_STRVAL(interface_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_INTERFACE; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(interface_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = (opline->extended_value & ~ZEND_FETCH_CLASS_MASK) | ZEND_FETCH_CLASS_INTERFACE; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &interface_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_interfaces++; } /* }}} */ void zend_do_implements_trait(znode *trait_name TSRMLS_DC) /* {{{ */ { zend_op *opline; if ((CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Cannot use traits inside of interfaces. %s is used in %s", Z_STRVAL(trait_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(trait_name->u.constant), Z_STRLEN(trait_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as trait name as it is reserved", Z_STRVAL(trait_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_TRAIT; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(trait_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = ZEND_FETCH_CLASS_TRAIT; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &trait_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_traits++; } /* }}} */ ZEND_API void zend_mangle_property_name(char **dest, int *dest_length, const char *src1, int src1_length, const char *src2, int src2_length, int internal) /* {{{ */ { char *prop_name; int prop_name_length; prop_name_length = 1 + src1_length + 1 + src2_length; prop_name = pemalloc(prop_name_length + 1, internal); prop_name[0] = '\0'; memcpy(prop_name + 1, src1, src1_length+1); memcpy(prop_name + 1 + src1_length + 1, src2, src2_length+1); *dest = prop_name; *dest_length = prop_name_length; } /* }}} */ static int zend_strnlen(const char* s, int maxlen) /* {{{ */ { int len = 0; while (*s++ && maxlen--) len++; return len; } /* }}} */ ZEND_API int zend_unmangle_property_name(const char *mangled_property, int len, const char **class_name, const char **prop_name) /* {{{ */ { int class_name_len; *class_name = NULL; if (mangled_property[0]!=0) { *prop_name = mangled_property; return SUCCESS; } if (len < 3 || mangled_property[1]==0) { zend_error(E_NOTICE, "Illegal member variable name"); *prop_name = mangled_property; return FAILURE; } class_name_len = zend_strnlen(mangled_property+1, --len - 1) + 1; if (class_name_len >= len || mangled_property[class_name_len]!=0) { zend_error(E_NOTICE, "Corrupt member variable name"); *prop_name = mangled_property; return FAILURE; } *class_name = mangled_property+1; *prop_name = (*class_name)+class_name_len; return SUCCESS; } /* }}} */ void zend_do_declare_property(const znode *var_name, const znode *value, zend_uint access_type TSRMLS_DC) /* {{{ */ { zval *property; zend_property_info *existing_property_info; char *comment = NULL; int comment_len = 0; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Interfaces may not include member variables"); } if (access_type & ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Properties cannot be declared abstract"); } if (access_type & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot declare property %s::$%s final, the final modifier is allowed only for methods and classes", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } if (zend_hash_find(&CG(active_class_entry)->properties_info, var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, (void **) &existing_property_info)==SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::$%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } ALLOC_ZVAL(property); if (value) { *property = value->u.constant; } else { INIT_PZVAL(property); Z_TYPE_P(property) = IS_NULL; } if (CG(doc_comment)) { comment = CG(doc_comment); comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } zend_declare_property_ex(CG(active_class_entry), zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len + 1, 0 TSRMLS_CC), var_name->u.constant.value.str.len, property, access_type, comment, comment_len TSRMLS_CC); efree(var_name->u.constant.value.str.val); } /* }}} */ void zend_do_declare_class_constant(znode *var_name, const znode *value TSRMLS_DC) /* {{{ */ { zval *property; const char *cname = NULL; int result; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed in class constants"); return; } if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Traits cannot have constants"); return; } ALLOC_ZVAL(property); *property = value->u.constant; cname = zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, 0 TSRMLS_CC); if (IS_INTERNED(cname)) { result = zend_hash_quick_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, INTERNED_HASH(cname), &property, sizeof(zval *), NULL); } else { result = zend_hash_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, &property, sizeof(zval *), NULL); } if (result == FAILURE) { FREE_ZVAL(property); zend_error(E_COMPILE_ERROR, "Cannot redefine class constant %s::%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } FREE_PNODE(var_name); if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_fetch_property(znode *result, znode *object, const znode *property TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (object->op_type == IS_CV) { if (object->u.op.var == CG(active_op_array)->this_var) { object->op_type = IS_UNUSED; /* this means $this for objects */ } } else if (fetch_list_ptr->count == 1) { zend_llist_element *le = fetch_list_ptr->head; zend_op *opline_ptr = (zend_op *) le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); SET_UNUSED(opline_ptr->op1); /* this means $this for objects */ SET_NODE(opline_ptr->op2, property); /* if it was usual fetch, we change it to object fetch */ switch (opline_ptr->opcode) { case ZEND_FETCH_W: opline_ptr->opcode = ZEND_FETCH_OBJ_W; break; case ZEND_FETCH_R: opline_ptr->opcode = ZEND_FETCH_OBJ_R; break; case ZEND_FETCH_RW: opline_ptr->opcode = ZEND_FETCH_OBJ_RW; break; case ZEND_FETCH_IS: opline_ptr->opcode = ZEND_FETCH_OBJ_IS; break; case ZEND_FETCH_UNSET: opline_ptr->opcode = ZEND_FETCH_OBJ_UNSET; break; case ZEND_FETCH_FUNC_ARG: opline_ptr->opcode = ZEND_FETCH_OBJ_FUNC_ARG; break; } if (opline_ptr->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline_ptr->op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline_ptr->op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op2.constant); } GET_NODE(result, opline_ptr->result); return; } } if (zend_is_function_or_method_call(object)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, object); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_OBJ_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, object); SET_NODE(opline.op2, property); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline.op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op2.constant); } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void zend_do_halt_compiler_register(TSRMLS_D) /* {{{ */ { char *name, *cfilename; char haltoff[] = "__COMPILER_HALT_OFFSET__"; int len, clen; cfilename = zend_get_compiled_filename(TSRMLS_C); clen = strlen(cfilename); zend_mangle_property_name(&name, &len, haltoff, sizeof(haltoff) - 1, cfilename, clen, 0); zend_register_long_constant(name, len+1, zend_get_scanned_file_offset(TSRMLS_C), CONST_CS, 0 TSRMLS_CC); pefree(name, 0); if (CG(in_namespace)) { zend_do_end_namespace(TSRMLS_C); } } /* }}} */ void zend_do_push_object(const znode *object TSRMLS_DC) /* {{{ */ { zend_stack_push(&CG(object_stack), object, sizeof(znode)); } /* }}} */ void zend_do_pop_object(znode *object TSRMLS_DC) /* {{{ */ { if (object) { znode *tmp; zend_stack_top(&CG(object_stack), (void **) &tmp); *object = *tmp; } zend_stack_del_top(&CG(object_stack)); } /* }}} */ void zend_do_begin_new_object(znode *new_token, znode *class_type TSRMLS_DC) /* {{{ */ { zend_op *opline; unsigned char *ptr = NULL; new_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_NEW; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, class_type); SET_UNUSED(opline->op2); zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(unsigned char *)); } /* }}} */ void zend_do_end_new_object(znode *result, const znode *new_token, const znode *argument_list TSRMLS_DC) /* {{{ */ { znode ctor_result; zend_do_end_function_call(NULL, &ctor_result, argument_list, 1, 0 TSRMLS_CC); zend_do_free(&ctor_result TSRMLS_CC); CG(active_op_array)->opcodes[new_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, CG(active_op_array)->opcodes[new_token->u.op.opline_num].result); } /* }}} */ static zend_constant* zend_get_ct_const(const zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = NULL; if (Z_STRVAL_P(const_name)[0] == '\\') { if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name), (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name)-1); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name), (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } } else if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)+1, (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name)+1, (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } if (c->flags & CONST_CT_SUBST) { return c; } if (all_internal_constants_substitution && (c->flags & CONST_PERSISTENT) && !(CG(compiler_options) & ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION) && Z_TYPE(c->value) != IS_CONSTANT && Z_TYPE(c->value) != IS_CONSTANT_ARRAY) { return c; } return NULL; } /* }}} */ static int zend_constant_ct_subst(znode *result, zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = zend_get_ct_const(const_name, all_internal_constants_substitution TSRMLS_CC); if (c) { zval_dtor(const_name); result->op_type = IS_CONST; result->u.constant = c->value; zval_copy_ctor(&result->u.constant); INIT_PZVAL(&result->u.constant); return 1; } return 0; } /* }}} */ void zend_do_fetch_constant(znode *result, znode *constant_container, znode *constant_name, int mode, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; zend_op *opline; int type; char *compound; ulong fetch_type = 0; if (constant_container) { switch (mode) { case ZEND_CT: /* this is a class constant */ type = zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant)); if (ZEND_FETCH_CLASS_STATIC == type) { zend_error(E_ERROR, "\"static::\" is not allowed in compile-time constants"); } else if (ZEND_FETCH_CLASS_DEFAULT == type) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } zend_do_build_full_name(NULL, constant_container, constant_name, 1 TSRMLS_CC); *result = *constant_container; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: if (constant_container->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant))) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } else { zend_do_fetch_class(&tmp, constant_container TSRMLS_CC); constant_container = &tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); if (constant_container->op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &constant_container->u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, constant_container); } SET_NODE(opline->op2, constant_name); CALCULATE_LITERAL_HASH(opline->op2.constant); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } GET_NODE(result, opline->result); break; } return; } /* namespace constant */ /* only one that did not contain \ from the start can be converted to string if unknown */ switch (mode) { case ZEND_CT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); /* this is a namespace constant, or an unprefixed constant */ if (zend_constant_ct_subst(result, &constant_name->u.constant, 0 TSRMLS_CC)) { break; } zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(!compound) { fetch_type |= IS_CONSTANT_UNQUALIFIED; } *result = *constant_name; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(zend_constant_ct_subst(result, &constant_name->u.constant, 1 TSRMLS_CC)) { break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; if (compound) { /* the name is unambiguous */ opline->extended_value = 0; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } else { opline->extended_value = IS_CONSTANT_UNQUALIFIED; if (CG(current_namespace)) { opline->extended_value |= IS_CONSTANT_IN_NAMESPACE; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 1 TSRMLS_CC); } else { opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } } GET_CACHE_SLOT(opline->op2.constant); break; } } /* }}} */ void zend_do_shell_exec(znode *result, const znode *cmd TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); switch (cmd->op_type) { case IS_CONST: case IS_TMP_VAR: opline->opcode = ZEND_SEND_VAL; break; default: opline->opcode = ZEND_SEND_VAR; break; } SET_NODE(opline->op1, cmd); opline->op2.opline_num = 0; opline->extended_value = ZEND_DO_FCALL; SET_UNUSED(opline->op2); /* FIXME: exception support not added to this op2 */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DO_FCALL; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; LITERAL_STRINGL(opline->op1, estrndup("shell_exec", sizeof("shell_exec")-1), sizeof("shell_exec")-1, 0); CALCULATE_LITERAL_HASH(opline->op1.constant); opline->op1_type = IS_CONST; GET_CACHE_SLOT(opline->op1.constant); opline->extended_value = 1; SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_init_array(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_ARRAY; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; GET_NODE(result, opline->result); if (expr) { SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } } else { SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_array_element(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_ARRAY_ELEMENT; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_static_array_element(znode *result, znode *offset, const znode *expr) /* {{{ */ { zval *element; ALLOC_ZVAL(element); *element = expr->u.constant; if (offset) { switch (offset->u.constant.type & IS_CONSTANT_TYPE_MASK) { case IS_CONSTANT: /* Ugly hack to denote that this value has a constant index */ Z_TYPE_P(element) |= IS_CONSTANT_INDEX; Z_STRVAL(offset->u.constant) = erealloc(Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+1] = Z_TYPE(offset->u.constant); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+2] = 0; zend_symtable_update(result->u.constant.value.ht, Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_STRING: zend_symtable_update(result->u.constant.value.ht, offset->u.constant.value.str.val, offset->u.constant.value.str.len+1, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_NULL: zend_symtable_update(Z_ARRVAL(result->u.constant), "", 1, &element, sizeof(zval *), NULL); break; case IS_LONG: case IS_BOOL: zend_hash_index_update(Z_ARRVAL(result->u.constant), Z_LVAL(offset->u.constant), &element, sizeof(zval *), NULL); break; case IS_DOUBLE: zend_hash_index_update(Z_ARRVAL(result->u.constant), zend_dval_to_lval(Z_DVAL(offset->u.constant)), &element, sizeof(zval *), NULL); break; case IS_CONSTANT_ARRAY: zend_error(E_ERROR, "Illegal offset type"); break; } } else { zend_hash_next_index_insert(Z_ARRVAL(result->u.constant), &element, sizeof(zval *), NULL); } } /* }}} */ void zend_do_add_list_element(const znode *element TSRMLS_DC) /* {{{ */ { list_llist_element lle; if (element) { zend_check_writable_variable(element); lle.var = *element; zend_llist_copy(&lle.dimensions, &CG(dimension_llist)); zend_llist_prepend_element(&CG(list_llist), &lle); } (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_new_list_begin(TSRMLS_D) /* {{{ */ { int current_dimension = 0; zend_llist_add_element(&CG(dimension_llist), &current_dimension); } /* }}} */ void zend_do_new_list_end(TSRMLS_D) /* {{{ */ { zend_llist_remove_tail(&CG(dimension_llist)); (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_list_init(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(list_stack), &CG(list_llist), sizeof(zend_llist)); zend_stack_push(&CG(list_stack), &CG(dimension_llist), sizeof(zend_llist)); zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_do_new_list_begin(TSRMLS_C); } /* }}} */ void zend_do_list_end(znode *result, znode *expr TSRMLS_DC) /* {{{ */ { zend_llist_element *le; zend_llist_element *dimension; zend_op *opline; znode last_container; le = CG(list_llist).head; while (le) { zend_llist *tmp_dimension_llist = &((list_llist_element *)le->data)->dimensions; dimension = tmp_dimension_llist->head; while (dimension) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (dimension == tmp_dimension_llist->head) { /* first */ last_container = *expr; switch (expr->op_type) { case IS_VAR: case IS_CV: opline->opcode = ZEND_FETCH_DIM_R; break; case IS_TMP_VAR: opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; case IS_CONST: /* fetch_dim_tmp_var will handle this bogus fetch */ zval_copy_ctor(&expr->u.constant); opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; } opline->extended_value |= ZEND_FETCH_ADD_LOCK; } else { opline->opcode = ZEND_FETCH_DIM_R; } opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, &last_container); opline->op2_type = IS_CONST; LITERAL_LONG(opline->op2, *((int *) dimension->data)); GET_NODE(&last_container, opline->result); dimension = dimension->next; } ((list_llist_element *) le->data)->value = last_container; zend_llist_destroy(&((list_llist_element *) le->data)->dimensions); zend_do_assign(result, &((list_llist_element *) le->data)->var, &((list_llist_element *) le->data)->value TSRMLS_CC); zend_do_free(result TSRMLS_CC); le = le->next; } zend_llist_destroy(&CG(dimension_llist)); zend_llist_destroy(&CG(list_llist)); *result = *expr; { zend_llist *p; /* restore previous lists */ zend_stack_top(&CG(list_stack), (void **) &p); CG(dimension_llist) = *p; zend_stack_del_top(&CG(list_stack)); zend_stack_top(&CG(list_stack), (void **) &p); CG(list_llist) = *p; zend_stack_del_top(&CG(list_stack)); } } /* }}} */ void zend_init_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = emalloc(sizeof(void*) * 2); list[0] = item; list[1] = NULL; *(void**)result = list; } /* }}} */ void zend_add_to_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = *(void**)result; size_t n = 0; while (list && list[n]) { n++; } list = erealloc(list, sizeof(void*) * (n+2)); list[n] = item; list[n+1] = NULL; *(void**)result = list; } /* }}} */ void zend_do_fetch_static_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zval *tmp; zend_op *opline; znode lval; znode result; ALLOC_ZVAL(tmp); if (static_assignment) { *tmp = static_assignment->u.constant; } else { INIT_ZVAL(*tmp); } if (!CG(active_op_array)->static_variables) { if (CG(active_op_array)->scope) { CG(active_op_array)->scope->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } ALLOC_HASHTABLE(CG(active_op_array)->static_variables); zend_hash_init(CG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } zend_hash_update(CG(active_op_array)->static_variables, varname->u.constant.value.str.val, varname->u.constant.value.str.len+1, &tmp, sizeof(zval *), NULL); if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (fetch_type == ZEND_FETCH_LEXICAL) ? ZEND_FETCH_R : ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_STATIC; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ if (fetch_type == ZEND_FETCH_LEXICAL) { znode dummy; zend_do_begin_variable_parse(TSRMLS_C); zend_do_assign(&dummy, &lval, &result TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } else { zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); } CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_fetch_lexical_variable(znode *varname, zend_bool is_ref TSRMLS_DC) /* {{{ */ { znode value; if (Z_STRLEN(varname->u.constant) == sizeof("this") - 1 && memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this") - 1) == 0) { zend_error(E_COMPILE_ERROR, "Cannot use $this as lexical variable"); return; } value.op_type = IS_CONST; ZVAL_NULL(&value.u.constant); Z_TYPE(value.u.constant) |= is_ref ? IS_LEXICAL_REF : IS_LEXICAL_VAR; Z_SET_REFCOUNT_P(&value.u.constant, 1); Z_UNSET_ISREF_P(&value.u.constant); zend_do_fetch_static_variable(varname, &value, is_ref ? ZEND_FETCH_STATIC : ZEND_FETCH_LEXICAL TSRMLS_CC); } /* }}} */ void zend_do_fetch_global_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zend_op *opline; znode lval; znode result; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = fetch_type; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_cast(znode *result, const znode *expr, int type TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CAST; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } /* }}} */ void zend_do_include_or_eval(int type, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_do_extended_fcall_begin(TSRMLS_C); { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INCLUDE_OR_EVAL; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } zend_do_extended_fcall_end(TSRMLS_C); } /* }}} */ void zend_do_indirect_references(znode *result, const znode *num_references, znode *variable TSRMLS_DC) /* {{{ */ { int i; zend_do_end_variable_parse(variable, BP_VAR_R, 0 TSRMLS_CC); for (i=1; i<num_references->u.constant.value.lval; i++) { fetch_simple_variable_ex(result, variable, 0, ZEND_FETCH_R TSRMLS_CC); *variable = *result; } zend_do_begin_variable_parse(TSRMLS_C); fetch_simple_variable(result, variable, 1 TSRMLS_CC); /* there is a chance someone is accessing $this */ if (CG(active_op_array)->scope && CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } /* }}} */ void zend_do_unset(const znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_UNSET_VAR; SET_NODE(opline->op1, variable); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); opline->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_UNSET: last_op->opcode = ZEND_UNSET_VAR; SET_UNUSED(last_op->result); break; case ZEND_FETCH_DIM_UNSET: last_op->opcode = ZEND_UNSET_DIM; SET_UNUSED(last_op->result); break; case ZEND_FETCH_OBJ_UNSET: last_op->opcode = ZEND_UNSET_OBJ; SET_UNUSED(last_op->result); break; } } } /* }}} */ void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_do_end_variable_parse(variable, BP_VAR_IS, 0 TSRMLS_CC); zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { last_op = get_next_op(CG(active_op_array) TSRMLS_CC); last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; SET_NODE(last_op->op1, variable); SET_UNUSED(last_op->op2); last_op->result.var = get_temporary_variable(CG(active_op_array)); last_op->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; break; case ZEND_FETCH_DIM_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_DIM_OBJ; break; case ZEND_FETCH_OBJ_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_PROP_OBJ; break; } } last_op->result_type = IS_TMP_VAR; last_op->extended_value |= type; GET_NODE(result, last_op->result); } /* }}} */ void zend_do_instanceof(znode *result, const znode *expr, const znode *class_znode, int type TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline->opcode == ZEND_FETCH_CLASS) { opline->extended_value |= ZEND_FETCH_CLASS_NO_AUTOLOAD; } } if (expr->op_type == IS_CONST) { zend_error(E_COMPILE_ERROR, "instanceof expects an object instance, constant given"); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INSTANCEOF; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_NODE(opline->op2, class_znode); GET_NODE(result, opline->result); } /* }}} */ void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_bool is_variable; zend_bool push_container = 0; zend_op dummy_opline; if (variable) { if (zend_is_function_or_method_call(array)) { is_variable = 0; } else { is_variable = 1; } /* save the location of FETCH_W instruction(s) */ open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); zend_do_end_variable_parse(array, BP_VAR_W, 0 TSRMLS_CC); if (CG(active_op_array)->last > 0 && CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) { /* Only lock the container if we are fetching from a real container and not $this */ if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1_type == IS_VAR) { CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK; push_container = 1; } } } else { is_variable = 0; open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* save the location of FE_RESET */ foreach_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* Preform array reset */ opline->opcode = ZEND_FE_RESET; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, array); SET_UNUSED(opline->op2); opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0; COPY_NODE(dummy_opline.result, opline->result); if (push_container) { COPY_NODE(dummy_opline.op1, CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1); } else { dummy_opline.op1_type = IS_UNUSED; } zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); /* save the location of FE_FETCH */ as_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FE_FETCH; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); COPY_NODE(opline->op1, dummy_opline.result); opline->extended_value = 0; SET_UNUSED(opline->op2); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_OP_DATA; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); } /* }}} */ void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC) /* {{{ */ { zend_op *opline; znode dummy, value_node; zend_bool assign_by_ref=0; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num]; if (key->op_type != IS_UNUSED) { znode *tmp; /* switch between the key and value... */ tmp = key; key = value; value = tmp; /* Mark extended_value in case both key and value are being used */ opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; } if ((key->op_type != IS_UNUSED) && (key->EA & ZEND_PARSED_REFERENCE_VARIABLE)) { zend_error(E_COMPILE_ERROR, "Key element cannot be a reference"); } if (value->EA & ZEND_PARSED_REFERENCE_VARIABLE) { assign_by_ref = 1; if (!(opline-1)->extended_value) { zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression"); } /* Mark extended_value for assign-by-reference */ opline->extended_value |= ZEND_FE_FETCH_BYREF; CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; } else { zend_op *foreach_copy; zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.op.opline_num]; zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.op.opline_num]; /* Change "write context" into "read context" */ fetch->extended_value = 0; /* reset ZEND_FE_RESET_VARIABLE */ while (fetch != end) { --fetch; if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } if (fetch->opcode == ZEND_SEPARATE) { MAKE_NOP(fetch); } else { fetch->opcode -= 3; /* FETCH_W -> FETCH_R */ } } /* prevent double SWITCH_FREE */ zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy); foreach_copy->op1_type = IS_UNUSED; } GET_NODE(&value_node, opline->result); if (assign_by_ref) { zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); /* Mark FE_FETCH as IS_VAR as it holds the data directly as a value */ zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC); } else { zend_do_assign(&dummy, value, &value_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } if (key->op_type != IS_UNUSED) { znode key_node; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num+1]; opline->result_type = IS_TMP_VAR; opline->result.opline_num = get_temporary_variable(CG(active_op_array)); GET_NODE(&key_node, opline->result); zend_do_assign(&dummy, key, &key_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_foreach_end(const znode *foreach_token, const znode *as_token TSRMLS_DC) /* {{{ */ { zend_op *container_ptr; zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = as_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_RESET */ CG(active_op_array)->opcodes[as_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_FETCH */ do_end_loop(as_token->u.op.opline_num, 1 TSRMLS_CC); zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr); generate_free_foreach_copy(container_ptr TSRMLS_CC); zend_stack_del_top(&CG(foreach_copy_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_declare_begin(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(declare_stack), &CG(declarables), sizeof(zend_declarables)); } /* }}} */ void zend_do_declare_stmt(znode *var, znode *val TSRMLS_DC) /* {{{ */ { if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "ticks", sizeof("ticks")-1)) { convert_to_long(&val->u.constant); CG(declarables).ticks = val->u.constant; } else if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "encoding", sizeof("encoding")-1)) { if ((Z_TYPE(val->u.constant) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Cannot use constants as encoding"); } /* * Check that the pragma comes before any opcodes. If the compilation * got as far as this, the previous portion of the script must have been * parseable according to the .ini script_encoding setting. We still * want to tell them to put declare() at the top. */ { int num = CG(active_op_array)->last; /* ignore ZEND_EXT_STMT and ZEND_TICKS */ while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Encoding declaration pragma must be the very first statement in the script"); } } if (CG(multibyte)) { const zend_encoding *new_encoding, *old_encoding; zend_encoding_filter old_input_filter; CG(encoding_declared) = 1; convert_to_string(&val->u.constant); new_encoding = zend_multibyte_fetch_encoding(val->u.constant.value.str.val TSRMLS_CC); if (!new_encoding) { zend_error(E_COMPILE_WARNING, "Unsupported encoding [%s]", val->u.constant.value.str.val); } else { old_input_filter = LANG_SCNG(input_filter); old_encoding = LANG_SCNG(script_encoding); zend_multibyte_set_filter(new_encoding TSRMLS_CC); /* need to re-scan if input filter changed */ if (old_input_filter != LANG_SCNG(input_filter) || (old_input_filter && new_encoding != old_encoding)) { zend_multibyte_yyinput_again(old_input_filter, old_encoding TSRMLS_CC); } } } else { zend_error(E_COMPILE_WARNING, "declare(encoding=...) ignored because Zend multibyte feature is turned off by settings"); } zval_dtor(&val->u.constant); } else { zend_error(E_COMPILE_WARNING, "Unsupported declare '%s'", var->u.constant.value.str.val); zval_dtor(&val->u.constant); } zval_dtor(&var->u.constant); } /* }}} */ void zend_do_declare_end(const znode *declare_token TSRMLS_DC) /* {{{ */ { zend_declarables *declarables; zend_stack_top(&CG(declare_stack), (void **) &declarables); /* We should restore if there was more than (current - start) - (ticks?1:0) opcodes */ if ((get_next_op_number(CG(active_op_array)) - declare_token->u.op.opline_num) - ((Z_LVAL(CG(declarables).ticks))?1:0)) { CG(declarables) = *declarables; } } /* }}} */ void zend_do_exit(znode *result, const znode *message TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXIT; SET_NODE(opline->op1, message); SET_UNUSED(opline->op2); result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_BOOL; Z_LVAL(result->u.constant) = 1; } /* }}} */ void zend_do_begin_silence(znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BEGIN_SILENCE; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); GET_NODE(strudel_token, opline->result); } /* }}} */ void zend_do_end_silence(const znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_END_SILENCE; SET_NODE(opline->op1, strudel_token); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_jmp_set(const znode *value, znode *jmp_token, znode *colon_token TSRMLS_DC) /* {{{ */ { int op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (value->op_type == IS_VAR || value->op_type == IS_CV) { opline->opcode = ZEND_JMP_SET_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_JMP_SET; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, value); SET_UNUSED(opline->op2); GET_NODE(colon_token, opline->result); jmp_token->u.op .opline_num = op_number; INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_jmp_set_else(znode *result, const znode *false_value, const znode *jmp_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, colon_token); if (colon_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].opcode = ZEND_JMP_SET_VAR; CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } opline->extended_value = 0; SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_qm_op(const znode *cond, znode *qm_token TSRMLS_DC) /* {{{ */ { int jmpz_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); SET_UNUSED(opline->op2); opline->op2.opline_num = jmpz_op_number; GET_NODE(qm_token, opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_qm_true(const znode *true_value, znode *qm_token, znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->opcodes[qm_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array))+1; /* jmp over the ZEND_JMP */ if (true_value->op_type == IS_VAR || true_value->op_type == IS_CV) { opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, true_value); SET_UNUSED(opline->op2); GET_NODE(qm_token, opline->result); colon_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_qm_false(znode *result, const znode *false_value, const znode *qm_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, qm_token); if (qm_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].opcode = ZEND_QM_ASSIGN_VAR; CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[colon_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, opline->result); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_extended_info(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_STMT; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_begin(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_BEGIN; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_end(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_END; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_ticks(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_TICKS; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->extended_value = Z_LVAL(CG(declarables).ticks); } /* }}} */ zend_bool zend_is_auto_global_quick(const char *name, uint name_len, ulong hashval TSRMLS_DC) /* {{{ */ { zend_auto_global *auto_global; ulong hash = hashval ? hashval : zend_hash_func(name, name_len+1); if (zend_hash_quick_find(CG(auto_globals), name, name_len+1, hash, (void **) &auto_global)==SUCCESS) { if (auto_global->armed) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } return 1; } return 0; } /* }}} */ zend_bool zend_is_auto_global(const char *name, uint name_len TSRMLS_DC) /* {{{ */ { return zend_is_auto_global_quick(name, name_len, 0 TSRMLS_CC); } /* }}} */ int zend_register_auto_global(const char *name, uint name_len, zend_bool jit, zend_auto_global_callback auto_global_callback TSRMLS_DC) /* {{{ */ { zend_auto_global auto_global; auto_global.name = zend_new_interned_string((char*)name, name_len + 1, 0 TSRMLS_CC); auto_global.name_len = name_len; auto_global.auto_global_callback = auto_global_callback; auto_global.jit = jit; return zend_hash_add(CG(auto_globals), name, name_len+1, &auto_global, sizeof(zend_auto_global), NULL); } /* }}} */ static int zend_auto_global_init(zend_auto_global *auto_global TSRMLS_DC) /* {{{ */ { if (auto_global->jit) { auto_global->armed = 1; } else if (auto_global->auto_global_callback) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } else { auto_global->armed = 0; } return 0; } /* }}} */ ZEND_API void zend_activate_auto_globals(TSRMLS_D) /* {{{ */ { zend_hash_apply(CG(auto_globals), (apply_func_t) zend_auto_global_init TSRMLS_CC); } /* }}} */ int zendlex(znode *zendlval TSRMLS_DC) /* {{{ */ { int retval; if (CG(increment_lineno)) { CG(zend_lineno)++; CG(increment_lineno) = 0; } again: Z_TYPE(zendlval->u.constant) = IS_LONG; retval = lex_scan(&zendlval->u.constant TSRMLS_CC); switch (retval) { case T_COMMENT: case T_DOC_COMMENT: case T_OPEN_TAG: case T_WHITESPACE: goto again; case T_CLOSE_TAG: if (LANG_SCNG(yy_text)[LANG_SCNG(yy_leng)-1] != '>') { CG(increment_lineno) = 1; } if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { goto again; } retval = ';'; /* implicit ; */ break; case T_OPEN_TAG_WITH_ECHO: retval = T_ECHO; break; case T_END_HEREDOC: efree(Z_STRVAL(zendlval->u.constant)); break; } INIT_PZVAL(&zendlval->u.constant); zendlval->op_type = IS_CONST; return retval; } /* }}} */ ZEND_API void zend_initialize_class_data(zend_class_entry *ce, zend_bool nullify_handlers TSRMLS_DC) /* {{{ */ { zend_bool persistent_hashes = (ce->type == ZEND_INTERNAL_CLASS) ? 1 : 0; dtor_func_t zval_ptr_dtor_func = ((persistent_hashes) ? ZVAL_INTERNAL_PTR_DTOR : ZVAL_PTR_DTOR); ce->refcount = 1; ce->ce_flags = 0; ce->default_properties_table = NULL; ce->default_static_members_table = NULL; zend_hash_init_ex(&ce->properties_info, 0, NULL, (dtor_func_t) (persistent_hashes ? zend_destroy_property_info_internal : zend_destroy_property_info), persistent_hashes, 0); zend_hash_init_ex(&ce->constants_table, 0, NULL, zval_ptr_dtor_func, persistent_hashes, 0); zend_hash_init_ex(&ce->function_table, 0, NULL, ZEND_FUNCTION_DTOR, persistent_hashes, 0); if (ce->type == ZEND_INTERNAL_CLASS) { #ifdef ZTS int n = zend_hash_num_elements(CG(class_table)); if (CG(static_members_table) && n >= CG(last_static_member)) { /* Support for run-time declaration: dl() */ CG(last_static_member) = n+1; CG(static_members_table) = realloc(CG(static_members_table), (n+1)*sizeof(zval**)); CG(static_members_table)[n] = NULL; } ce->static_members_table = (zval**)(zend_intptr_t)n; #else ce->static_members_table = NULL; #endif } else { ce->static_members_table = ce->default_static_members_table; ce->info.user.doc_comment = NULL; ce->info.user.doc_comment_len = 0; } ce->default_properties_count = 0; ce->default_static_members_count = 0; if (nullify_handlers) { ce->constructor = NULL; ce->destructor = NULL; ce->clone = NULL; ce->__get = NULL; ce->__set = NULL; ce->__unset = NULL; ce->__isset = NULL; ce->__call = NULL; ce->__callstatic = NULL; ce->__tostring = NULL; ce->create_object = NULL; ce->get_iterator = NULL; ce->iterator_funcs.funcs = NULL; ce->interface_gets_implemented = NULL; ce->get_static_method = NULL; ce->parent = NULL; ce->num_interfaces = 0; ce->interfaces = NULL; ce->num_traits = 0; ce->traits = NULL; ce->trait_aliases = NULL; ce->trait_precedences = NULL; ce->serialize = NULL; ce->unserialize = NULL; ce->serialize_func = NULL; ce->unserialize_func = NULL; if (ce->type == ZEND_INTERNAL_CLASS) { ce->info.internal.module = NULL; ce->info.internal.builtin_functions = NULL; } } } /* }}} */ int zend_get_class_fetch_type(const char *class_name, uint class_name_len) /* {{{ */ { if ((class_name_len == sizeof("self")-1) && !memcmp(class_name, "self", sizeof("self")-1)) { return ZEND_FETCH_CLASS_SELF; } else if ((class_name_len == sizeof("parent")-1) && !memcmp(class_name, "parent", sizeof("parent")-1)) { return ZEND_FETCH_CLASS_PARENT; } else if ((class_name_len == sizeof("static")-1) && !memcmp(class_name, "static", sizeof("static")-1)) { return ZEND_FETCH_CLASS_STATIC; } else { return ZEND_FETCH_CLASS_DEFAULT; } } /* }}} */ ZEND_API const char* zend_get_compiled_variable_name(const zend_op_array *op_array, zend_uint var, int* name_len) /* {{{ */ { if (name_len) { *name_len = op_array->vars[var].name_len; } return op_array->vars[var].name; } /* }}} */ void zend_do_build_namespace_name(znode *result, znode *prefix, znode *name TSRMLS_DC) /* {{{ */ { if (prefix) { *result = *prefix; if (Z_TYPE(result->u.constant) == IS_STRING && Z_STRLEN(result->u.constant) == 0) { /* namespace\ */ if (CG(current_namespace)) { znode tmp; zval_dtor(&result->u.constant); tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(result, NULL, &tmp TSRMLS_CC); } } } else { result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_STRING; Z_STRVAL(result->u.constant) = NULL; Z_STRLEN(result->u.constant) = 0; } /* prefix = result */ zend_do_build_full_name(NULL, result, name, 0 TSRMLS_CC); } /* }}} */ void zend_do_begin_namespace(const znode *name, zend_bool with_bracket TSRMLS_DC) /* {{{ */ { char *lcname; /* handle mixed syntax declaration or nested namespaces */ if (!CG(has_bracketed_namespaces)) { if (CG(current_namespace)) { /* previous namespace declarations were unbracketed */ if (with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } } } else { /* previous namespace declarations were bracketed */ if (!with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } else if (CG(current_namespace) || CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "Namespace declarations cannot be nested"); } } if (((!with_bracket && !CG(current_namespace)) || (with_bracket && !CG(has_bracketed_namespaces))) && CG(active_op_array)->last > 0) { /* ignore ZEND_EXT_STMT and ZEND_TICKS */ int num = CG(active_op_array)->last; while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Namespace declaration statement has to be the very first statement in the script"); } } CG(in_namespace) = 1; if (with_bracket) { CG(has_bracketed_namespaces) = 1; } if (name) { lcname = zend_str_tolower_dup(Z_STRVAL(name->u.constant), Z_STRLEN(name->u.constant)); if (((Z_STRLEN(name->u.constant) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN(name->u.constant) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as namespace name", Z_STRVAL(name->u.constant)); } efree(lcname); if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); } else { ALLOC_ZVAL(CG(current_namespace)); } *CG(current_namespace) = name->u.constant; } else { if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_use(znode *ns_name, znode *new_name, int is_global TSRMLS_DC) /* {{{ */ { char *lcname; zval *name, *ns, tmp; zend_bool warn = 0; zend_class_entry **pce; if (!CG(current_import)) { CG(current_import) = emalloc(sizeof(HashTable)); zend_hash_init(CG(current_import), 0, NULL, ZVAL_PTR_DTOR, 0); } ALLOC_ZVAL(ns); *ns = ns_name->u.constant; if (new_name) { name = &new_name->u.constant; } else { const char *p; /* The form "use A\B" is eqivalent to "use A\B as B". So we extract the last part of compound name to use as a new_name */ name = &tmp; p = zend_memrchr(Z_STRVAL_P(ns), '\\', Z_STRLEN_P(ns)); if (p) { ZVAL_STRING(name, p+1, 1); } else { *name = *ns; zval_copy_ctor(name); warn = !is_global && !CG(current_namespace); } } lcname = zend_str_tolower_dup(Z_STRVAL_P(name), Z_STRLEN_P(name)); if (((Z_STRLEN_P(name) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN_P(name) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because '%s' is a special class name", Z_STRVAL_P(ns), Z_STRVAL_P(name), Z_STRVAL_P(name)); } if (CG(current_namespace)) { /* Prefix import name with current namespace name to avoid conflicts with classes */ char *c_ns_name = emalloc(Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) + 1); zend_str_tolower_copy(c_ns_name, Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); c_ns_name[Z_STRLEN_P(CG(current_namespace))] = '\\'; memcpy(c_ns_name+Z_STRLEN_P(CG(current_namespace))+1, lcname, Z_STRLEN_P(name)+1); if (zend_hash_exists(CG(class_table), c_ns_name, Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name)+1)) { char *tmp2 = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) || memcmp(tmp2, c_ns_name, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(tmp2); } efree(c_ns_name); } else if (zend_hash_find(CG(class_table), lcname, Z_STRLEN_P(name)+1, (void**)&pce) == SUCCESS && (*pce)->type == ZEND_USER_CLASS && (*pce)->info.user.filename == CG(compiled_filename)) { char *c_tmp = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(name) || memcmp(c_tmp, lcname, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(c_tmp); } if (zend_hash_add(CG(current_import), lcname, Z_STRLEN_P(name)+1, &ns, sizeof(zval*), NULL) != SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } if (warn) { if (!strcmp(Z_STRVAL_P(name), "strict")) { zend_error(E_COMPILE_ERROR, "You seem to be trying to use a different language..."); } zend_error(E_WARNING, "The use statement with non-compound name '%s' has no effect", Z_STRVAL_P(name)); } efree(lcname); zval_dtor(name); } /* }}} */ void zend_do_declare_constant(znode *name, znode *value TSRMLS_DC) /* {{{ */ { zend_op *opline; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed as constants"); } if (zend_get_ct_const(&name->u.constant, 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare constant '%s'", Z_STRVAL(name->u.constant)); } if (CG(current_namespace)) { /* Prefix constant name with name of current namespace, lowercased */ znode tmp; tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); Z_STRVAL(tmp.u.constant) = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), Z_STRLEN(tmp.u.constant)); zend_do_build_namespace_name(&tmp, &tmp, name TSRMLS_CC); *name = tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DECLARE_CONST; SET_UNUSED(opline->result); SET_NODE(opline->op1, name); SET_NODE(opline->op2, value); } /* }}} */ void zend_verify_namespace(TSRMLS_D) /* {{{ */ { if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "No code may exist outside of namespace {}"); } } /* }}} */ void zend_do_end_namespace(TSRMLS_D) /* {{{ */ { CG(in_namespace) = 0; if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_end_compilation(TSRMLS_D) /* {{{ */ { CG(has_bracketed_namespaces) = 0; zend_do_end_namespace(TSRMLS_C); } /* }}} */ /* {{{ zend_dirname Returns directory name component of path */ ZEND_API size_t zend_dirname(char *path, size_t len) { register char *end = path + len - 1; unsigned int len_adjust = 0; #ifdef PHP_WIN32 /* Note that on Win32 CWD is per drive (heritage from CP/M). * This means dirname("c:foo") maps to "c:." or "c:" - which means CWD on C: drive. */ if ((2 <= len) && isalpha((int)((unsigned char *)path)[0]) && (':' == path[1])) { /* Skip over the drive spec (if any) so as not to change */ path += 2; len_adjust += 2; if (2 == len) { /* Return "c:" on Win32 for dirname("c:"). * It would be more consistent to return "c:." * but that would require making the string *longer*. */ return len; } } #elif defined(NETWARE) /* * Find the first occurence of : from the left * move the path pointer to the position just after : * increment the len_adjust to the length of path till colon character(inclusive) * If there is no character beyond : simple return len */ char *colonpos = NULL; colonpos = strchr(path, ':'); if (colonpos != NULL) { len_adjust = ((colonpos - path) + 1); path += len_adjust; if (len_adjust == len) { return len; } } #endif if (len == 0) { /* Illegal use of this function */ return 0; } /* Strip trailing slashes */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { /* The path only contained slashes */ path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } /* Strip filename */ while (end >= path && !IS_SLASH_P(end)) { end--; } if (end < path) { /* No slash found, therefore return '.' */ #ifdef NETWARE if (len_adjust == 0) { path[0] = '.'; path[1] = '\0'; return 1; /* only one character */ } else { path[0] = '\0'; return len_adjust; } #else path[0] = '.'; path[1] = '\0'; return 1 + len_adjust; #endif } /* Strip slashes which came before the file name */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } *(end+1) = '\0'; return (size_t)(end + 1 - path) + len_adjust; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-11-02-de50e98a07-8d520d6296.c
manybugs_data_40
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "zend.h" #include "zend_constants.h" #include "zend_execute.h" #include "zend_variables.h" #include "zend_operators.h" #include "zend_globals.h" void free_zend_constant(zend_constant *c) { if (!(c->flags & CONST_PERSISTENT)) { zval_dtor(&c->value); } str_free(c->name); } void copy_zend_constant(zend_constant *c) { if (!IS_INTERNED(c->name)) { c->name = zend_strndup(c->name, c->name_len - 1); } if (!(c->flags & CONST_PERSISTENT)) { zval_copy_ctor(&c->value); } } void zend_copy_constants(HashTable *target, HashTable *source) { zend_constant tmp_constant; zend_hash_copy(target, source, (copy_ctor_func_t) copy_zend_constant, &tmp_constant, sizeof(zend_constant)); } static int clean_non_persistent_constant(const zend_constant *c TSRMLS_DC) { return (c->flags & CONST_PERSISTENT) ? ZEND_HASH_APPLY_STOP : ZEND_HASH_APPLY_REMOVE; } static int clean_non_persistent_constant_full(const zend_constant *c TSRMLS_DC) { return (c->flags & CONST_PERSISTENT) ? 0 : 1; } static int clean_module_constant(const zend_constant *c, int *module_number TSRMLS_DC) { if (c->module_number == *module_number) { return 1; } else { return 0; } } void clean_module_constants(int module_number TSRMLS_DC) { zend_hash_apply_with_argument(EG(zend_constants), (apply_func_arg_t) clean_module_constant, (void *) &module_number TSRMLS_CC); } int zend_startup_constants(TSRMLS_D) { EG(zend_constants) = (HashTable *) malloc(sizeof(HashTable)); if (zend_hash_init(EG(zend_constants), 20, NULL, ZEND_CONSTANT_DTOR, 1)==FAILURE) { return FAILURE; } return SUCCESS; } void zend_register_standard_constants(TSRMLS_D) { REGISTER_MAIN_LONG_CONSTANT("E_ERROR", E_ERROR, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_RECOVERABLE_ERROR", E_RECOVERABLE_ERROR, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_WARNING", E_WARNING, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_PARSE", E_PARSE, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_NOTICE", E_NOTICE, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_STRICT", E_STRICT, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_DEPRECATED", E_DEPRECATED, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_CORE_ERROR", E_CORE_ERROR, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_CORE_WARNING", E_CORE_WARNING, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_COMPILE_ERROR", E_COMPILE_ERROR, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_COMPILE_WARNING", E_COMPILE_WARNING, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_USER_ERROR", E_USER_ERROR, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_USER_WARNING", E_USER_WARNING, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_USER_NOTICE", E_USER_NOTICE, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_USER_DEPRECATED", E_USER_DEPRECATED, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_ALL", E_ALL, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("DEBUG_BACKTRACE_PROVIDE_OBJECT", DEBUG_BACKTRACE_PROVIDE_OBJECT, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("DEBUG_BACKTRACE_IGNORE_ARGS", DEBUG_BACKTRACE_IGNORE_ARGS, CONST_PERSISTENT | CONST_CS); /* true/false constants */ { zend_constant c; c.flags = CONST_PERSISTENT | CONST_CT_SUBST; c.module_number = 0; c.name = zend_strndup(ZEND_STRL("TRUE")); c.name_len = sizeof("TRUE"); c.value.value.lval = 1; c.value.type = IS_BOOL; zend_register_constant(&c TSRMLS_CC); c.name = zend_strndup(ZEND_STRL("FALSE")); c.name_len = sizeof("FALSE"); c.value.value.lval = 0; c.value.type = IS_BOOL; zend_register_constant(&c TSRMLS_CC); c.name = zend_strndup(ZEND_STRL("NULL")); c.name_len = sizeof("NULL"); c.value.type = IS_NULL; zend_register_constant(&c TSRMLS_CC); c.flags = CONST_PERSISTENT | CONST_CS; c.name = zend_strndup(ZEND_STRL("ZEND_THREAD_SAFE")); c.name_len = sizeof("ZEND_THREAD_SAFE"); c.value.value.lval = ZTS_V; c.value.type = IS_BOOL; zend_register_constant(&c TSRMLS_CC); c.name = zend_strndup(ZEND_STRL("ZEND_DEBUG_BUILD")); c.name_len = sizeof("ZEND_DEBUG_BUILD"); c.value.value.lval = ZEND_DEBUG; c.value.type = IS_BOOL; zend_register_constant(&c TSRMLS_CC); } } int zend_shutdown_constants(TSRMLS_D) { zend_hash_destroy(EG(zend_constants)); free(EG(zend_constants)); return SUCCESS; } void clean_non_persistent_constants(TSRMLS_D) { if (EG(full_tables_cleanup)) { zend_hash_apply(EG(zend_constants), (apply_func_t) clean_non_persistent_constant_full TSRMLS_CC); } else { zend_hash_reverse_apply(EG(zend_constants), (apply_func_t) clean_non_persistent_constant TSRMLS_CC); } } ZEND_API void zend_register_long_constant(const char *name, uint name_len, long lval, int flags, int module_number TSRMLS_DC) { zend_constant c; c.value.type = IS_LONG; c.value.value.lval = lval; c.flags = flags; c.name = zend_strndup(name, name_len-1); c.name_len = name_len; c.module_number = module_number; zend_register_constant(&c TSRMLS_CC); } ZEND_API void zend_register_double_constant(const char *name, uint name_len, double dval, int flags, int module_number TSRMLS_DC) { zend_constant c; c.value.type = IS_DOUBLE; c.value.value.dval = dval; c.flags = flags; c.name = zend_strndup(name, name_len-1); c.name_len = name_len; c.module_number = module_number; zend_register_constant(&c TSRMLS_CC); } ZEND_API void zend_register_stringl_constant(const char *name, uint name_len, char *strval, uint strlen, int flags, int module_number TSRMLS_DC) { zend_constant c; c.value.type = IS_STRING; c.value.value.str.val = strval; c.value.value.str.len = strlen; c.flags = flags; c.name = zend_strndup(name, name_len-1); c.name_len = name_len; c.module_number = module_number; zend_register_constant(&c TSRMLS_CC); } ZEND_API void zend_register_string_constant(const char *name, uint name_len, char *strval, int flags, int module_number TSRMLS_DC) { zend_register_stringl_constant(name, name_len, strval, strlen(strval), flags, module_number TSRMLS_CC); } static int zend_get_halt_offset_constant(const char *name, uint name_len, zend_constant **c TSRMLS_DC) { int ret; static char haltoff[] = "__COMPILER_HALT_OFFSET__"; if (!EG(in_execution)) { return 0; } else if (name_len == sizeof("__COMPILER_HALT_OFFSET__")-1 && !memcmp(name, "__COMPILER_HALT_OFFSET__", sizeof("__COMPILER_HALT_OFFSET__")-1)) { char *cfilename, *haltname; int len, clen; cfilename = zend_get_executed_filename(TSRMLS_C); clen = strlen(cfilename); /* check for __COMPILER_HALT_OFFSET__ */ zend_mangle_property_name(&haltname, &len, haltoff, sizeof("__COMPILER_HALT_OFFSET__") - 1, cfilename, clen, 0); ret = zend_hash_find(EG(zend_constants), haltname, len+1, (void **) c); efree(haltname); return (ret == SUCCESS); } else { return 0; } } ZEND_API int zend_get_constant(const char *name, uint name_len, zval *result TSRMLS_DC) { zend_constant *c; int retval = 1; char *lookup_name; if (zend_hash_find(EG(zend_constants), name, name_len+1, (void **) &c) == FAILURE) { lookup_name = zend_str_tolower_dup(name, name_len); if (zend_hash_find(EG(zend_constants), lookup_name, name_len+1, (void **) &c)==SUCCESS) { if (c->flags & CONST_CS) { retval=0; } } else { retval = zend_get_halt_offset_constant(name, name_len, &c TSRMLS_CC); } efree(lookup_name); } if (retval) { *result = c->value; zval_copy_ctor(result); Z_SET_REFCOUNT_P(result, 1); Z_UNSET_ISREF_P(result); } return retval; } ZEND_API int zend_get_constant_ex(const char *name, uint name_len, zval *result, zend_class_entry *scope, ulong flags TSRMLS_DC) { zend_constant *c; int retval = 1; const char *colon; zend_class_entry *ce = NULL; char *class_name; zval **ret_constant; /* Skip leading \\ */ if (name[0] == '\\') { name += 1; name_len -= 1; } if ((colon = zend_memrchr(name, ':', name_len)) && colon > name && (*(colon - 1) == ':')) { int class_name_len = colon - name - 1; int const_name_len = name_len - class_name_len - 2; const char *constant_name = colon + 1; char *lcname; class_name = estrndup(name, class_name_len); lcname = zend_str_tolower_dup(class_name, class_name_len); if (!scope) { if (EG(in_execution)) { scope = EG(scope); } else { scope = CG(active_class_entry); } } if (class_name_len == sizeof("self")-1 && !memcmp(lcname, "self", sizeof("self")-1)) { if (scope) { ce = scope; } else { zend_error(E_ERROR, "Cannot access self:: when no class scope is active"); retval = 0; } efree(lcname); } else if (class_name_len == sizeof("parent")-1 && !memcmp(lcname, "parent", sizeof("parent")-1)) { if (!scope) { zend_error(E_ERROR, "Cannot access parent:: when no class scope is active"); } else if (!scope->parent) { zend_error(E_ERROR, "Cannot access parent:: when current class scope has no parent"); } else { ce = scope->parent; } efree(lcname); } else if (class_name_len == sizeof("static")-1 && !memcmp(lcname, "static", sizeof("static")-1)) { if (EG(called_scope)) { ce = EG(called_scope); } else { zend_error(E_ERROR, "Cannot access static:: when no class scope is active"); } efree(lcname); } else { efree(lcname); ce = zend_fetch_class(class_name, class_name_len, flags TSRMLS_CC); } if (retval && ce) { if (zend_hash_find(&ce->constants_table, constant_name, const_name_len+1, (void **) &ret_constant) != SUCCESS) { retval = 0; if ((flags & ZEND_FETCH_CLASS_SILENT) == 0) { zend_error(E_ERROR, "Undefined class constant '%s::%s'", class_name, constant_name); } } } else if (!ce) { retval = 0; } efree(class_name); goto finish; } /* non-class constant */ if ((colon = zend_memrchr(name, '\\', name_len)) != NULL) { /* compound constant name */ int prefix_len = colon - name; int const_name_len = name_len - prefix_len - 1; const char *constant_name = colon + 1; char *lcname; int found_const = 0; lcname = zend_str_tolower_dup(name, prefix_len); /* Check for namespace constant */ /* Concatenate lowercase namespace name and constant name */ lcname = erealloc(lcname, prefix_len + 1 + const_name_len + 1); lcname[prefix_len] = '\\'; memcpy(lcname + prefix_len + 1, constant_name, const_name_len + 1); if (zend_hash_find(EG(zend_constants), lcname, prefix_len + 1 + const_name_len + 1, (void **) &c) == SUCCESS) { found_const = 1; } else { /* try lowercase */ zend_str_tolower(lcname + prefix_len + 1, const_name_len); if (zend_hash_find(EG(zend_constants), lcname, prefix_len + 1 + const_name_len + 1, (void **) &c) == SUCCESS) { if ((c->flags & CONST_CS) == 0) { found_const = 1; } } } efree(lcname); if(found_const) { *result = c->value; zval_update_constant_ex(&result, (void*)1, NULL TSRMLS_CC); zval_copy_ctor(result); Z_SET_REFCOUNT_P(result, 1); Z_UNSET_ISREF_P(result); return 1; } /* name requires runtime resolution, need to check non-namespaced name */ if ((flags & IS_CONSTANT_UNQUALIFIED) != 0) { name = constant_name; name_len = const_name_len; return zend_get_constant(name, name_len, result TSRMLS_CC); } retval = 0; finish: if (retval) { zval_update_constant_ex(ret_constant, (void*)1, ce TSRMLS_CC); *result = **ret_constant; zval_copy_ctor(result); INIT_PZVAL(result); } return retval; } return zend_get_constant(name, name_len, result TSRMLS_CC); } zend_constant *zend_quick_get_constant(const zend_literal *key, ulong flags TSRMLS_DC) { zend_constant *c; if (zend_hash_quick_find(EG(zend_constants), Z_STRVAL(key->constant), Z_STRLEN(key->constant) + 1, key->hash_value, (void **) &c) == FAILURE) { key++; if (zend_hash_quick_find(EG(zend_constants), Z_STRVAL(key->constant), Z_STRLEN(key->constant) + 1, key->hash_value, (void **) &c) == FAILURE || (c->flags & CONST_CS) != 0) { if ((flags & (IS_CONSTANT_IN_NAMESPACE|IS_CONSTANT_UNQUALIFIED)) == (IS_CONSTANT_IN_NAMESPACE|IS_CONSTANT_UNQUALIFIED)) { key++; if (zend_hash_quick_find(EG(zend_constants), Z_STRVAL(key->constant), Z_STRLEN(key->constant) + 1, key->hash_value, (void **) &c) == FAILURE) { key++; if (zend_hash_quick_find(EG(zend_constants), Z_STRVAL(key->constant), Z_STRLEN(key->constant) + 1, key->hash_value, (void **) &c) == FAILURE || (c->flags & CONST_CS) != 0) { key--; if (!zend_get_halt_offset_constant(Z_STRVAL(key->constant), Z_STRLEN(key->constant), &c TSRMLS_CC)) { return NULL; } } } } else { key--; if (!zend_get_halt_offset_constant(Z_STRVAL(key->constant), Z_STRLEN(key->constant), &c TSRMLS_CC)) { return NULL; } } } } return c; } ZEND_API int zend_register_constant(zend_constant *c TSRMLS_DC) { char *lowercase_name = NULL; char *name; int ret = SUCCESS; #if 0 printf("Registering constant for module %d\n", c->module_number); #endif if (!(c->flags & CONST_CS)) { /* keep in mind that c->name_len already contains the '\0' */ lowercase_name = estrndup(c->name, c->name_len-1); zend_str_tolower(lowercase_name, c->name_len-1); lowercase_name = zend_new_interned_string(lowercase_name, c->name_len, 1 TSRMLS_CC); name = lowercase_name; } else { char *slash = strrchr(c->name, '\\'); if(slash) { lowercase_name = estrndup(c->name, c->name_len-1); zend_str_tolower(lowercase_name, slash-c->name); lowercase_name = zend_new_interned_string(lowercase_name, c->name_len, 1 TSRMLS_CC); name = lowercase_name; } else { name = c->name; } } /* Check if the user is trying to define the internal pseudo constant name __COMPILER_HALT_OFFSET__ */ if ((c->name_len == sizeof("__COMPILER_HALT_OFFSET__") && !memcmp(name, "__COMPILER_HALT_OFFSET__", sizeof("__COMPILER_HALT_OFFSET__")-1)) || zend_hash_add(EG(zend_constants), name, c->name_len, (void *) c, sizeof(zend_constant), NULL)==FAILURE) { /* The internal __COMPILER_HALT_OFFSET__ is prefixed by NULL byte */ if (c->name[0] == '\0' && c->name_len > sizeof("\0__COMPILER_HALT_OFFSET__") && memcmp(name, "\0__COMPILER_HALT_OFFSET__", sizeof("\0__COMPILER_HALT_OFFSET__")) == 0) { name++; } zend_error(E_NOTICE,"Constant %s already defined", name); str_free(c->name); if (!(c->flags & CONST_PERSISTENT)) { zval_dtor(&c->value); } ret = FAILURE; } if (lowercase_name && !IS_INTERNED(lowercase_name)) { efree(lowercase_name); } return ret; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */ /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "zend.h" #include "zend_constants.h" #include "zend_execute.h" #include "zend_variables.h" #include "zend_operators.h" #include "zend_globals.h" void free_zend_constant(zend_constant *c) { if (!(c->flags & CONST_PERSISTENT)) { zval_dtor(&c->value); } str_free(c->name); } void copy_zend_constant(zend_constant *c) { if (!IS_INTERNED(c->name)) { c->name = zend_strndup(c->name, c->name_len - 1); } if (!(c->flags & CONST_PERSISTENT)) { zval_copy_ctor(&c->value); } } void zend_copy_constants(HashTable *target, HashTable *source) { zend_constant tmp_constant; zend_hash_copy(target, source, (copy_ctor_func_t) copy_zend_constant, &tmp_constant, sizeof(zend_constant)); } static int clean_non_persistent_constant(const zend_constant *c TSRMLS_DC) { return (c->flags & CONST_PERSISTENT) ? ZEND_HASH_APPLY_STOP : ZEND_HASH_APPLY_REMOVE; } static int clean_non_persistent_constant_full(const zend_constant *c TSRMLS_DC) { return (c->flags & CONST_PERSISTENT) ? 0 : 1; } static int clean_module_constant(const zend_constant *c, int *module_number TSRMLS_DC) { if (c->module_number == *module_number) { return 1; } else { return 0; } } void clean_module_constants(int module_number TSRMLS_DC) { zend_hash_apply_with_argument(EG(zend_constants), (apply_func_arg_t) clean_module_constant, (void *) &module_number TSRMLS_CC); } int zend_startup_constants(TSRMLS_D) { EG(zend_constants) = (HashTable *) malloc(sizeof(HashTable)); if (zend_hash_init(EG(zend_constants), 20, NULL, ZEND_CONSTANT_DTOR, 1)==FAILURE) { return FAILURE; } return SUCCESS; } void zend_register_standard_constants(TSRMLS_D) { REGISTER_MAIN_LONG_CONSTANT("E_ERROR", E_ERROR, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_RECOVERABLE_ERROR", E_RECOVERABLE_ERROR, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_WARNING", E_WARNING, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_PARSE", E_PARSE, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_NOTICE", E_NOTICE, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_STRICT", E_STRICT, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_DEPRECATED", E_DEPRECATED, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_CORE_ERROR", E_CORE_ERROR, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_CORE_WARNING", E_CORE_WARNING, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_COMPILE_ERROR", E_COMPILE_ERROR, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_COMPILE_WARNING", E_COMPILE_WARNING, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_USER_ERROR", E_USER_ERROR, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_USER_WARNING", E_USER_WARNING, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_USER_NOTICE", E_USER_NOTICE, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_USER_DEPRECATED", E_USER_DEPRECATED, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("E_ALL", E_ALL, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("DEBUG_BACKTRACE_PROVIDE_OBJECT", DEBUG_BACKTRACE_PROVIDE_OBJECT, CONST_PERSISTENT | CONST_CS); REGISTER_MAIN_LONG_CONSTANT("DEBUG_BACKTRACE_IGNORE_ARGS", DEBUG_BACKTRACE_IGNORE_ARGS, CONST_PERSISTENT | CONST_CS); /* true/false constants */ { zend_constant c; c.flags = CONST_PERSISTENT | CONST_CT_SUBST; c.module_number = 0; c.name = zend_strndup(ZEND_STRL("TRUE")); c.name_len = sizeof("TRUE"); c.value.value.lval = 1; c.value.type = IS_BOOL; zend_register_constant(&c TSRMLS_CC); c.name = zend_strndup(ZEND_STRL("FALSE")); c.name_len = sizeof("FALSE"); c.value.value.lval = 0; c.value.type = IS_BOOL; zend_register_constant(&c TSRMLS_CC); c.name = zend_strndup(ZEND_STRL("NULL")); c.name_len = sizeof("NULL"); c.value.type = IS_NULL; zend_register_constant(&c TSRMLS_CC); c.flags = CONST_PERSISTENT; c.name = zend_strndup(ZEND_STRL("ZEND_THREAD_SAFE")); c.name_len = sizeof("ZEND_THREAD_SAFE"); c.value.value.lval = ZTS_V; c.value.type = IS_BOOL; zend_register_constant(&c TSRMLS_CC); c.name = zend_strndup(ZEND_STRL("ZEND_DEBUG_BUILD")); c.name_len = sizeof("ZEND_DEBUG_BUILD"); c.value.value.lval = ZEND_DEBUG; c.value.type = IS_BOOL; zend_register_constant(&c TSRMLS_CC); } } int zend_shutdown_constants(TSRMLS_D) { zend_hash_destroy(EG(zend_constants)); free(EG(zend_constants)); return SUCCESS; } void clean_non_persistent_constants(TSRMLS_D) { if (EG(full_tables_cleanup)) { zend_hash_apply(EG(zend_constants), (apply_func_t) clean_non_persistent_constant_full TSRMLS_CC); } else { zend_hash_reverse_apply(EG(zend_constants), (apply_func_t) clean_non_persistent_constant TSRMLS_CC); } } ZEND_API void zend_register_long_constant(const char *name, uint name_len, long lval, int flags, int module_number TSRMLS_DC) { zend_constant c; c.value.type = IS_LONG; c.value.value.lval = lval; c.flags = flags; c.name = zend_strndup(name, name_len-1); c.name_len = name_len; c.module_number = module_number; zend_register_constant(&c TSRMLS_CC); } ZEND_API void zend_register_double_constant(const char *name, uint name_len, double dval, int flags, int module_number TSRMLS_DC) { zend_constant c; c.value.type = IS_DOUBLE; c.value.value.dval = dval; c.flags = flags; c.name = zend_strndup(name, name_len-1); c.name_len = name_len; c.module_number = module_number; zend_register_constant(&c TSRMLS_CC); } ZEND_API void zend_register_stringl_constant(const char *name, uint name_len, char *strval, uint strlen, int flags, int module_number TSRMLS_DC) { zend_constant c; c.value.type = IS_STRING; c.value.value.str.val = strval; c.value.value.str.len = strlen; c.flags = flags; c.name = zend_strndup(name, name_len-1); c.name_len = name_len; c.module_number = module_number; zend_register_constant(&c TSRMLS_CC); } ZEND_API void zend_register_string_constant(const char *name, uint name_len, char *strval, int flags, int module_number TSRMLS_DC) { zend_register_stringl_constant(name, name_len, strval, strlen(strval), flags, module_number TSRMLS_CC); } static int zend_get_halt_offset_constant(const char *name, uint name_len, zend_constant **c TSRMLS_DC) { int ret; static char haltoff[] = "__COMPILER_HALT_OFFSET__"; if (!EG(in_execution)) { return 0; } else if (name_len == sizeof("__COMPILER_HALT_OFFSET__")-1 && !memcmp(name, "__COMPILER_HALT_OFFSET__", sizeof("__COMPILER_HALT_OFFSET__")-1)) { char *cfilename, *haltname; int len, clen; cfilename = zend_get_executed_filename(TSRMLS_C); clen = strlen(cfilename); /* check for __COMPILER_HALT_OFFSET__ */ zend_mangle_property_name(&haltname, &len, haltoff, sizeof("__COMPILER_HALT_OFFSET__") - 1, cfilename, clen, 0); ret = zend_hash_find(EG(zend_constants), haltname, len+1, (void **) c); efree(haltname); return (ret == SUCCESS); } else { return 0; } } ZEND_API int zend_get_constant(const char *name, uint name_len, zval *result TSRMLS_DC) { zend_constant *c; int retval = 1; char *lookup_name; if (zend_hash_find(EG(zend_constants), name, name_len+1, (void **) &c) == FAILURE) { lookup_name = zend_str_tolower_dup(name, name_len); if (zend_hash_find(EG(zend_constants), lookup_name, name_len+1, (void **) &c)==SUCCESS) { if (c->flags & CONST_CS) { retval=0; } } else { retval = zend_get_halt_offset_constant(name, name_len, &c TSRMLS_CC); } efree(lookup_name); } if (retval) { *result = c->value; zval_copy_ctor(result); Z_SET_REFCOUNT_P(result, 1); Z_UNSET_ISREF_P(result); } return retval; } ZEND_API int zend_get_constant_ex(const char *name, uint name_len, zval *result, zend_class_entry *scope, ulong flags TSRMLS_DC) { zend_constant *c; int retval = 1; const char *colon; zend_class_entry *ce = NULL; char *class_name; zval **ret_constant; /* Skip leading \\ */ if (name[0] == '\\') { name += 1; name_len -= 1; } if ((colon = zend_memrchr(name, ':', name_len)) && colon > name && (*(colon - 1) == ':')) { int class_name_len = colon - name - 1; int const_name_len = name_len - class_name_len - 2; const char *constant_name = colon + 1; char *lcname; class_name = estrndup(name, class_name_len); lcname = zend_str_tolower_dup(class_name, class_name_len); if (!scope) { if (EG(in_execution)) { scope = EG(scope); } else { scope = CG(active_class_entry); } } if (class_name_len == sizeof("self")-1 && !memcmp(lcname, "self", sizeof("self")-1)) { if (scope) { ce = scope; } else { zend_error(E_ERROR, "Cannot access self:: when no class scope is active"); retval = 0; } efree(lcname); } else if (class_name_len == sizeof("parent")-1 && !memcmp(lcname, "parent", sizeof("parent")-1)) { if (!scope) { zend_error(E_ERROR, "Cannot access parent:: when no class scope is active"); } else if (!scope->parent) { zend_error(E_ERROR, "Cannot access parent:: when current class scope has no parent"); } else { ce = scope->parent; } efree(lcname); } else if (class_name_len == sizeof("static")-1 && !memcmp(lcname, "static", sizeof("static")-1)) { if (EG(called_scope)) { ce = EG(called_scope); } else { zend_error(E_ERROR, "Cannot access static:: when no class scope is active"); } efree(lcname); } else { efree(lcname); ce = zend_fetch_class(class_name, class_name_len, flags TSRMLS_CC); } if (retval && ce) { if (zend_hash_find(&ce->constants_table, constant_name, const_name_len+1, (void **) &ret_constant) != SUCCESS) { retval = 0; if ((flags & ZEND_FETCH_CLASS_SILENT) == 0) { zend_error(E_ERROR, "Undefined class constant '%s::%s'", class_name, constant_name); } } } else if (!ce) { retval = 0; } efree(class_name); goto finish; } /* non-class constant */ if ((colon = zend_memrchr(name, '\\', name_len)) != NULL) { /* compound constant name */ int prefix_len = colon - name; int const_name_len = name_len - prefix_len - 1; const char *constant_name = colon + 1; char *lcname; int found_const = 0; lcname = zend_str_tolower_dup(name, prefix_len); /* Check for namespace constant */ /* Concatenate lowercase namespace name and constant name */ lcname = erealloc(lcname, prefix_len + 1 + const_name_len + 1); lcname[prefix_len] = '\\'; memcpy(lcname + prefix_len + 1, constant_name, const_name_len + 1); if (zend_hash_find(EG(zend_constants), lcname, prefix_len + 1 + const_name_len + 1, (void **) &c) == SUCCESS) { found_const = 1; } else { /* try lowercase */ zend_str_tolower(lcname + prefix_len + 1, const_name_len); if (zend_hash_find(EG(zend_constants), lcname, prefix_len + 1 + const_name_len + 1, (void **) &c) == SUCCESS) { if ((c->flags & CONST_CS) == 0) { found_const = 1; } } } efree(lcname); if(found_const) { *result = c->value; zval_update_constant_ex(&result, (void*)1, NULL TSRMLS_CC); zval_copy_ctor(result); Z_SET_REFCOUNT_P(result, 1); Z_UNSET_ISREF_P(result); return 1; } /* name requires runtime resolution, need to check non-namespaced name */ if ((flags & IS_CONSTANT_UNQUALIFIED) != 0) { name = constant_name; name_len = const_name_len; return zend_get_constant(name, name_len, result TSRMLS_CC); } retval = 0; finish: if (retval) { zval_update_constant_ex(ret_constant, (void*)1, ce TSRMLS_CC); *result = **ret_constant; zval_copy_ctor(result); INIT_PZVAL(result); } return retval; } return zend_get_constant(name, name_len, result TSRMLS_CC); } zend_constant *zend_quick_get_constant(const zend_literal *key, ulong flags TSRMLS_DC) { zend_constant *c; if (zend_hash_quick_find(EG(zend_constants), Z_STRVAL(key->constant), Z_STRLEN(key->constant) + 1, key->hash_value, (void **) &c) == FAILURE) { key++; if (zend_hash_quick_find(EG(zend_constants), Z_STRVAL(key->constant), Z_STRLEN(key->constant) + 1, key->hash_value, (void **) &c) == FAILURE || (c->flags & CONST_CS) != 0) { if ((flags & (IS_CONSTANT_IN_NAMESPACE|IS_CONSTANT_UNQUALIFIED)) == (IS_CONSTANT_IN_NAMESPACE|IS_CONSTANT_UNQUALIFIED)) { key++; if (zend_hash_quick_find(EG(zend_constants), Z_STRVAL(key->constant), Z_STRLEN(key->constant) + 1, key->hash_value, (void **) &c) == FAILURE) { key++; if (zend_hash_quick_find(EG(zend_constants), Z_STRVAL(key->constant), Z_STRLEN(key->constant) + 1, key->hash_value, (void **) &c) == FAILURE || (c->flags & CONST_CS) != 0) { key--; if (!zend_get_halt_offset_constant(Z_STRVAL(key->constant), Z_STRLEN(key->constant), &c TSRMLS_CC)) { return NULL; } } } } else { key--; if (!zend_get_halt_offset_constant(Z_STRVAL(key->constant), Z_STRLEN(key->constant), &c TSRMLS_CC)) { return NULL; } } } } return c; } ZEND_API int zend_register_constant(zend_constant *c TSRMLS_DC) { char *lowercase_name = NULL; char *name; int ret = SUCCESS; #if 0 printf("Registering constant for module %d\n", c->module_number); #endif if (!(c->flags & CONST_CS)) { /* keep in mind that c->name_len already contains the '\0' */ lowercase_name = estrndup(c->name, c->name_len-1); zend_str_tolower(lowercase_name, c->name_len-1); lowercase_name = zend_new_interned_string(lowercase_name, c->name_len, 1 TSRMLS_CC); name = lowercase_name; } else { char *slash = strrchr(c->name, '\\'); if(slash) { lowercase_name = estrndup(c->name, c->name_len-1); zend_str_tolower(lowercase_name, slash-c->name); lowercase_name = zend_new_interned_string(lowercase_name, c->name_len, 1 TSRMLS_CC); name = lowercase_name; } else { name = c->name; } } /* Check if the user is trying to define the internal pseudo constant name __COMPILER_HALT_OFFSET__ */ if ((c->name_len == sizeof("__COMPILER_HALT_OFFSET__") && !memcmp(name, "__COMPILER_HALT_OFFSET__", sizeof("__COMPILER_HALT_OFFSET__")-1)) || zend_hash_add(EG(zend_constants), name, c->name_len, (void *) c, sizeof(zend_constant), NULL)==FAILURE) { /* The internal __COMPILER_HALT_OFFSET__ is prefixed by NULL byte */ if (c->name[0] == '\0' && c->name_len > sizeof("\0__COMPILER_HALT_OFFSET__") && memcmp(name, "\0__COMPILER_HALT_OFFSET__", sizeof("\0__COMPILER_HALT_OFFSET__")) == 0) { name++; } zend_error(E_NOTICE,"Constant %s already defined", name); str_free(c->name); if (!(c->flags & CONST_PERSISTENT)) { zval_dtor(&c->value); } ret = FAILURE; } if (lowercase_name && !IS_INTERNED(lowercase_name)) { efree(lowercase_name); } return ret; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-05-17-453c954f8a-daecb2c0f4.c
manybugs_data_41
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2012 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Zeev Suraski <[email protected]> | | Thies C. Arntzen <[email protected]> | | Marcus Boerger <[email protected]> | | New API: Michael Wallner <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifndef PHP_OUTPUT_DEBUG # define PHP_OUTPUT_DEBUG 0 #endif #ifndef PHP_OUTPUT_NOINLINE # define PHP_OUTPUT_NOINLINE 0 #endif #include "php.h" #include "ext/standard/head.h" #include "ext/standard/url_scanner_ex.h" #include "SAPI.h" #include "zend_stack.h" #include "php_output.h" ZEND_DECLARE_MODULE_GLOBALS(output); const char php_output_default_handler_name[sizeof("default output handler")] = "default output handler"; const char php_output_devnull_handler_name[sizeof("null output handler")] = "null output handler"; #if PHP_OUTPUT_NOINLINE || PHP_OUTPUT_DEBUG # undef inline # define inline #endif /* {{{ aliases, conflict and reverse conflict hash tables */ static HashTable php_output_handler_aliases; static HashTable php_output_handler_conflicts; static HashTable php_output_handler_reverse_conflicts; /* }}} */ /* {{{ forward declarations */ static inline int php_output_lock_error(int op TSRMLS_DC); static inline void php_output_op(int op, const char *str, size_t len TSRMLS_DC); static inline php_output_handler *php_output_handler_init(const char *name, size_t name_len, size_t chunk_size, int flags TSRMLS_DC); static inline php_output_handler_status_t php_output_handler_op(php_output_handler *handler, php_output_context *context); static inline int php_output_handler_append(php_output_handler *handler, const php_output_buffer *buf TSRMLS_DC); static inline zval *php_output_handler_status(php_output_handler *handler, zval *entry); static inline php_output_context *php_output_context_init(php_output_context *context, int op TSRMLS_DC); static inline void php_output_context_reset(php_output_context *context); static inline void php_output_context_swap(php_output_context *context); static inline void php_output_context_dtor(php_output_context *context); static inline int php_output_stack_pop(int flags TSRMLS_DC); static int php_output_stack_apply_op(void *h, void *c); static int php_output_stack_apply_clean(void *h, void *c); static int php_output_stack_apply_list(void *h, void *z); static int php_output_stack_apply_status(void *h, void *z); static int php_output_handler_compat_func(void **handler_context, php_output_context *output_context); static int php_output_handler_default_func(void **handler_context, php_output_context *output_context); static int php_output_handler_devnull_func(void **handler_context, php_output_context *output_context); /* }}} */ /* {{{ static void php_output_init_globals(zend_output_globals *G) * Initialize the module globals on MINIT */ static inline void php_output_init_globals(zend_output_globals *G) { memset(G, 0, sizeof(*G)); } /* }}} */ /* {{{ void php_output_startup(void) * Set up module globals and initalize the conflict and reverse conflict hash tables */ PHPAPI void php_output_startup(void) { ZEND_INIT_MODULE_GLOBALS(output, php_output_init_globals, NULL); zend_hash_init(&php_output_handler_aliases, 0, NULL, NULL, 1); zend_hash_init(&php_output_handler_conflicts, 0, NULL, NULL, 1); zend_hash_init(&php_output_handler_reverse_conflicts, 0, NULL, (void (*)(void *)) zend_hash_destroy, 1); } /* }}} */ /* {{{ void php_output_shutdown(void) * Destroy module globals and the conflict and reverse conflict hash tables */ PHPAPI void php_output_shutdown(void) { zend_hash_destroy(&php_output_handler_aliases); zend_hash_destroy(&php_output_handler_conflicts); zend_hash_destroy(&php_output_handler_reverse_conflicts); } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_activate(TSRMLS_D) * Reset output globals and setup the output handler stack */ PHPAPI int php_output_activate(TSRMLS_D) { #ifdef ZTS memset((*((void ***) tsrm_ls))[TSRM_UNSHUFFLE_RSRC_ID(output_globals_id)], 0, sizeof(zend_output_globals)); #else memset(&output_globals, 0, sizeof(zend_output_globals)); #endif zend_stack_init(&OG(handlers)); return SUCCESS; } /* }}} */ /* {{{ void php_output_deactivate(TSRMLS_D) * Destroy the output handler stack */ PHPAPI void php_output_deactivate(TSRMLS_D) { php_output_handler **handler = NULL; OG(active) = NULL; OG(running) = NULL; /* release all output handlers */ if (OG(handlers).elements) { while (SUCCESS == zend_stack_top(&OG(handlers), (void *) &handler)) { php_output_handler_free(handler TSRMLS_CC); zend_stack_del_top(&OG(handlers)); } zend_stack_destroy(&OG(handlers)); } } /* }}} */ /* {{{ void php_output_register_constants() */ PHPAPI void php_output_register_constants(TSRMLS_D) { REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_START", PHP_OUTPUT_HANDLER_START, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_WRITE", PHP_OUTPUT_HANDLER_WRITE, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_FLUSH", PHP_OUTPUT_HANDLER_FLUSH, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_CLEAN", PHP_OUTPUT_HANDLER_CLEAN, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_FINAL", PHP_OUTPUT_HANDLER_FINAL, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_CONT", PHP_OUTPUT_HANDLER_WRITE, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_END", PHP_OUTPUT_HANDLER_FINAL, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_CLEANABLE", PHP_OUTPUT_HANDLER_CLEANABLE, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_FLUSHABLE", PHP_OUTPUT_HANDLER_FLUSHABLE, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_REMOVABLE", PHP_OUTPUT_HANDLER_REMOVABLE, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_STDFLAGS", PHP_OUTPUT_HANDLER_STDFLAGS, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_STARTED", PHP_OUTPUT_HANDLER_STARTED, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_DISABLED", PHP_OUTPUT_HANDLER_DISABLED, CONST_CS | CONST_PERSISTENT); } /* }}} */ /* {{{ void php_output_set_status(int status TSRMLS_DC) * Used by SAPIs to disable output */ PHPAPI void php_output_set_status(int status TSRMLS_DC) { OG(flags) = status & 0xf; } /* }}} */ /* {{{ int php_output_get_status(TSRMLS_C) * Get output control status */ PHPAPI int php_output_get_status(TSRMLS_D) { return OG(flags) | (OG(active) ? PHP_OUTPUT_ACTIVE : 0) | (OG(running)? PHP_OUTPUT_LOCKED : 0); } /* }}} */ /* {{{ int php_output_write_unbuffered(const char *str, size_t len TSRMLS_DC) * Unbuffered write */ PHPAPI int php_output_write_unbuffered(const char *str, size_t len TSRMLS_DC) { if (OG(flags) & PHP_OUTPUT_DISABLED) { return 0; } return sapi_module.ub_write(str, len TSRMLS_CC); } /* }}} */ /* {{{ int php_output_write(const char *str, size_t len TSRMLS_DC) * Buffered write */ PHPAPI int php_output_write(const char *str, size_t len TSRMLS_DC) { if (OG(flags) & PHP_OUTPUT_DISABLED) { return 0; } php_output_op(PHP_OUTPUT_HANDLER_WRITE, str, len TSRMLS_CC); return (int) len; } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_flush(TSRMLS_D) * Flush the most recent output handlers buffer */ PHPAPI int php_output_flush(TSRMLS_D) { php_output_context context; if (OG(active) && (OG(active)->flags & PHP_OUTPUT_HANDLER_FLUSHABLE)) { php_output_context_init(&context, PHP_OUTPUT_HANDLER_FLUSH TSRMLS_CC); php_output_handler_op(OG(active), &context); if (context.out.data && context.out.used) { zend_stack_del_top(&OG(handlers)); php_output_write(context.out.data, context.out.used TSRMLS_CC); zend_stack_push(&OG(handlers), &OG(active), sizeof(php_output_handler *)); } php_output_context_dtor(&context); return SUCCESS; } return FAILURE; } /* }}} */ /* {{{ void php_output_flush_all(TSRMLS_C) * Flush all output buffers subsequently */ PHPAPI void php_output_flush_all(TSRMLS_D) { if (OG(active)) { php_output_op(PHP_OUTPUT_HANDLER_FLUSH, NULL, 0 TSRMLS_CC); } } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_clean(TSRMLS_D) * Cleans the most recent output handlers buffer if the handler is cleanable */ PHPAPI int php_output_clean(TSRMLS_D) { php_output_context context; if (OG(active) && (OG(active)->flags & PHP_OUTPUT_HANDLER_CLEANABLE)) { OG(active)->buffer.used = 0; php_output_context_init(&context, PHP_OUTPUT_HANDLER_CLEAN TSRMLS_CC); php_output_handler_op(OG(active), &context); php_output_context_dtor(&context); return SUCCESS; } return FAILURE; } /* }}} */ /* {{{ void php_output_clean_all(TSRMLS_D) * Cleans all output handler buffers, without regard whether the handler is cleanable */ PHPAPI void php_output_clean_all(TSRMLS_D) { php_output_context context; if (OG(active)) { php_output_context_init(&context, PHP_OUTPUT_HANDLER_CLEAN TSRMLS_CC); zend_stack_apply_with_argument(&OG(handlers), ZEND_STACK_APPLY_TOPDOWN, php_output_stack_apply_clean, &context); } } /* {{{ SUCCESS|FAILURE php_output_end(TSRMLS_D) * Finalizes the most recent output handler at pops it off the stack if the handler is removable */ PHPAPI int php_output_end(TSRMLS_D) { if (php_output_stack_pop(PHP_OUTPUT_POP_TRY TSRMLS_CC)) { return SUCCESS; } return FAILURE; } /* }}} */ /* {{{ void php_output_end_all(TSRMLS_D) * Finalizes all output handlers and ends output buffering without regard whether a handler is removable */ PHPAPI void php_output_end_all(TSRMLS_D) { while (OG(active) && php_output_stack_pop(PHP_OUTPUT_POP_FORCE TSRMLS_CC)); } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_discard(TSRMLS_D) * Discards the most recent output handlers buffer and pops it off the stack if the handler is removable */ PHPAPI int php_output_discard(TSRMLS_D) { if (php_output_stack_pop(PHP_OUTPUT_POP_DISCARD|PHP_OUTPUT_POP_TRY TSRMLS_CC)) { return SUCCESS; } return FAILURE; } /* }}} */ /* {{{ void php_output_discard_all(TSRMLS_D) * Discard all output handlers and buffers without regard whether a handler is removable */ PHPAPI void php_output_discard_all(TSRMLS_D) { while (OG(active)) { php_output_stack_pop(PHP_OUTPUT_POP_DISCARD|PHP_OUTPUT_POP_FORCE TSRMLS_CC); } } /* }}} */ /* {{{ int php_output_get_level(TSRMLS_D) * Get output buffering level, ie. how many output handlers the stack contains */ PHPAPI int php_output_get_level(TSRMLS_D) { return OG(active) ? zend_stack_count(&OG(handlers)) : 0; } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_get_contents(zval *z TSRMLS_DC) * Get the contents of the active output handlers buffer */ PHPAPI int php_output_get_contents(zval *p TSRMLS_DC) { if (OG(active)) { ZVAL_STRINGL(p, OG(active)->buffer.data, OG(active)->buffer.used, 1); return SUCCESS; } else { ZVAL_NULL(p); return FAILURE; } } /* {{{ SUCCESS|FAILURE php_output_get_length(zval *z TSRMLS_DC) * Get the length of the active output handlers buffer */ PHPAPI int php_output_get_length(zval *p TSRMLS_DC) { if (OG(active)) { ZVAL_LONG(p, OG(active)->buffer.used); return SUCCESS; } else { ZVAL_NULL(p); return FAILURE; } } /* }}} */ /* {{{ php_output_handler* php_output_get_active_handler(TSRMLS_D) * Get active output handler */ PHPAPI php_output_handler* php_output_get_active_handler(TSRMLS_D) { return OG(active); } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_handler_start_default(TSRMLS_D) * Start a "default output handler" */ PHPAPI int php_output_start_default(TSRMLS_D) { php_output_handler *handler; handler = php_output_handler_create_internal(ZEND_STRL(php_output_default_handler_name), php_output_handler_default_func, 0, PHP_OUTPUT_HANDLER_STDFLAGS TSRMLS_CC); if (SUCCESS == php_output_handler_start(handler TSRMLS_CC)) { return SUCCESS; } php_output_handler_free(&handler TSRMLS_CC); return FAILURE; } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_handler_start_devnull(TSRMLS_D) * Start a "null output handler" */ PHPAPI int php_output_start_devnull(TSRMLS_D) { php_output_handler *handler; handler = php_output_handler_create_internal(ZEND_STRL(php_output_devnull_handler_name), php_output_handler_devnull_func, PHP_OUTPUT_HANDLER_DEFAULT_SIZE, 0 TSRMLS_CC); if (SUCCESS == php_output_handler_start(handler TSRMLS_CC)) { return SUCCESS; } php_output_handler_free(&handler TSRMLS_CC); return FAILURE; } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_start_user(zval *handler, size_t chunk_size, int flags TSRMLS_DC) * Start a user level output handler */ PHPAPI int php_output_start_user(zval *output_handler, size_t chunk_size, int flags TSRMLS_DC) { php_output_handler *handler; if (output_handler) { handler = php_output_handler_create_user(output_handler, chunk_size, flags TSRMLS_CC); } else { handler = php_output_handler_create_internal(ZEND_STRL(php_output_default_handler_name), php_output_handler_default_func, chunk_size, flags TSRMLS_CC); } if (SUCCESS == php_output_handler_start(handler TSRMLS_CC)) { return SUCCESS; } php_output_handler_free(&handler TSRMLS_CC); return FAILURE; } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_start_internal(zval *name, php_output_handler_func_t handler, size_t chunk_size, int flags TSRMLS_DC) * Start an internal output handler that does not have to maintain a non-global state */ PHPAPI int php_output_start_internal(const char *name, size_t name_len, php_output_handler_func_t output_handler, size_t chunk_size, int flags TSRMLS_DC) { php_output_handler *handler; handler = php_output_handler_create_internal(name, name_len, php_output_handler_compat_func, chunk_size, flags TSRMLS_CC); php_output_handler_set_context(handler, output_handler, NULL TSRMLS_CC); if (SUCCESS == php_output_handler_start(handler TSRMLS_CC)) { return SUCCESS; } php_output_handler_free(&handler TSRMLS_CC); return FAILURE; } /* }}} */ /* {{{ php_output_handler *php_output_handler_create_user(zval *handler, size_t chunk_size, int flags TSRMLS_DC) * Create a user level output handler */ PHPAPI php_output_handler *php_output_handler_create_user(zval *output_handler, size_t chunk_size, int flags TSRMLS_DC) { char *handler_name = NULL, *error = NULL; php_output_handler *handler = NULL; php_output_handler_alias_ctor_t *alias = NULL; php_output_handler_user_func_t *user = NULL; switch (Z_TYPE_P(output_handler)) { case IS_NULL: handler = php_output_handler_create_internal(ZEND_STRL(php_output_default_handler_name), php_output_handler_default_func, chunk_size, flags TSRMLS_CC); break; case IS_STRING: if (Z_STRLEN_P(output_handler) && (alias = php_output_handler_alias(Z_STRVAL_P(output_handler), Z_STRLEN_P(output_handler) TSRMLS_CC))) { handler = (*alias)(Z_STRVAL_P(output_handler), Z_STRLEN_P(output_handler), chunk_size, flags TSRMLS_CC); break; } default: user = ecalloc(1, sizeof(php_output_handler_user_func_t)); if (SUCCESS == zend_fcall_info_init(output_handler, 0, &user->fci, &user->fcc, &handler_name, &error TSRMLS_CC)) { handler = php_output_handler_init(handler_name, strlen(handler_name), chunk_size, (flags & ~0xf) | PHP_OUTPUT_HANDLER_USER TSRMLS_CC); Z_ADDREF_P(output_handler); user->zoh = output_handler; handler->func.user = user; } else { efree(user); } if (error) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_WARNING, "%s", error); efree(error); } if (handler_name) { efree(handler_name); } } return handler; } /* }}} */ /* {{{ php_output_handler *php_output_handler_create_internal(zval *name, php_output_handler_context_func_t handler, size_t chunk_size, int flags TSRMLS_DC) * Create an internal output handler that can maintain a non-global state */ PHPAPI php_output_handler *php_output_handler_create_internal(const char *name, size_t name_len, php_output_handler_context_func_t output_handler, size_t chunk_size, int flags TSRMLS_DC) { php_output_handler *handler; handler = php_output_handler_init(name, name_len, chunk_size, (flags & ~0xf) | PHP_OUTPUT_HANDLER_INTERNAL TSRMLS_CC); handler->func.internal = output_handler; return handler; } /* }}} */ /* {{{ void php_output_handler_set_context(php_output_handler *handler, void *opaq, void (*dtor)(void* TSRMLS_DC) TSRMLS_DC) * Set the context/state of an output handler. Calls the dtor of the previous context if there is one */ PHPAPI void php_output_handler_set_context(php_output_handler *handler, void *opaq, void (*dtor)(void* TSRMLS_DC) TSRMLS_DC) { if (handler->dtor && handler->opaq) { handler->dtor(handler->opaq TSRMLS_CC); } handler->dtor = dtor; handler->opaq = opaq; } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_handler_start(php_output_handler *handler TSRMLS_DC) * Starts the set up output handler and pushes it on top of the stack. Checks for any conflicts regarding the output handler to start */ PHPAPI int php_output_handler_start(php_output_handler *handler TSRMLS_DC) { HashPosition pos; HashTable *rconflicts; php_output_handler_conflict_check_t *conflict; if (php_output_lock_error(PHP_OUTPUT_HANDLER_START TSRMLS_CC) || !handler) { return FAILURE; } if (SUCCESS == zend_hash_find(&php_output_handler_conflicts, handler->name, handler->name_len+1, (void *) &conflict)) { if (SUCCESS != (*conflict)(handler->name, handler->name_len TSRMLS_CC)) { return FAILURE; } } if (SUCCESS == zend_hash_find(&php_output_handler_reverse_conflicts, handler->name, handler->name_len+1, (void *) &rconflicts)) { for (zend_hash_internal_pointer_reset_ex(rconflicts, &pos); zend_hash_get_current_data_ex(rconflicts, (void *) &conflict, &pos) == SUCCESS; zend_hash_move_forward_ex(rconflicts, &pos) ) { if (SUCCESS != (*conflict)(handler->name, handler->name_len TSRMLS_CC)) { return FAILURE; } } } /* zend_stack_push never returns SUCCESS but FAILURE or stack level */ if (FAILURE == (handler->level = zend_stack_push(&OG(handlers), &handler, sizeof(php_output_handler *)))) { return FAILURE; } OG(active) = handler; return SUCCESS; } /* }}} */ /* {{{ int php_output_handler_started(zval *name TSRMLS_DC) * Check whether a certain output handler is in use */ PHPAPI int php_output_handler_started(const char *name, size_t name_len TSRMLS_DC) { php_output_handler ***handlers; int i, count = php_output_get_level(TSRMLS_C); if (count) { handlers = (php_output_handler ***) zend_stack_base(&OG(handlers)); for (i = 0; i < count; ++i) { if (name_len == (*(handlers[i]))->name_len && !memcmp((*(handlers[i]))->name, name, name_len)) { return 1; } } } return 0; } /* }}} */ /* {{{ int php_output_handler_conflict(zval *handler_new, zval *handler_old TSRMLS_DC) * Check whether a certain handler is in use and issue a warning that the new handler would conflict with the already used one */ PHPAPI int php_output_handler_conflict(const char *handler_new, size_t handler_new_len, const char *handler_set, size_t handler_set_len TSRMLS_DC) { if (php_output_handler_started(handler_set, handler_set_len TSRMLS_CC)) { if (handler_new_len != handler_set_len || memcmp(handler_new, handler_set, handler_set_len)) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_WARNING, "output handler '%s' conflicts with '%s'", handler_new, handler_set); } else { php_error_docref("ref.outcontrol" TSRMLS_CC, E_WARNING, "output handler '%s' cannot be used twice", handler_new); } return 1; } return 0; } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_handler_conflict_register(zval *name, php_output_handler_conflict_check_t check_func TSRMLS_DC) * Register a conflict checking function on MINIT */ PHPAPI int php_output_handler_conflict_register(const char *name, size_t name_len, php_output_handler_conflict_check_t check_func TSRMLS_DC) { if (!EG(current_module)) { zend_error(E_ERROR, "Cannot register an output handler conflict outside of MINIT"); return FAILURE; } return zend_hash_update(&php_output_handler_conflicts, name, name_len+1, &check_func, sizeof(php_output_handler_conflict_check_t *), NULL); } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_handler_reverse_conflict_register(zval *name, php_output_handler_conflict_check_t check_func TSRMLS_DC) * Register a reverse conflict checking function on MINIT */ PHPAPI int php_output_handler_reverse_conflict_register(const char *name, size_t name_len, php_output_handler_conflict_check_t check_func TSRMLS_DC) { HashTable rev, *rev_ptr = NULL; if (!EG(current_module)) { zend_error(E_ERROR, "Cannot register a reverse output handler conflict outside of MINIT"); return FAILURE; } if (SUCCESS == zend_hash_find(&php_output_handler_reverse_conflicts, name, name_len+1, (void *) &rev_ptr)) { return zend_hash_next_index_insert(rev_ptr, &check_func, sizeof(php_output_handler_conflict_check_t *), NULL); } else { zend_hash_init(&rev, 1, NULL, NULL, 1); if (SUCCESS != zend_hash_next_index_insert(&rev, &check_func, sizeof(php_output_handler_conflict_check_t *), NULL)) { zend_hash_destroy(&rev); return FAILURE; } if (SUCCESS != zend_hash_update(&php_output_handler_reverse_conflicts, name, name_len+1, &rev, sizeof(HashTable), NULL)) { zend_hash_destroy(&rev); return FAILURE; } return SUCCESS; } } /* }}} */ /* {{{ php_output_handler_alias_ctor_t php_output_handler_alias(zval *name TSRMLS_DC) * Get an internal output handler for a user handler if it exists */ PHPAPI php_output_handler_alias_ctor_t *php_output_handler_alias(const char *name, size_t name_len TSRMLS_DC) { php_output_handler_alias_ctor_t *func = NULL; zend_hash_find(&php_output_handler_aliases, name, name_len+1, (void *) &func); return func; } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_handler_alias_register(zval *name, php_output_handler_alias_ctor_t func TSRMLS_DC) * Registers an internal output handler as alias for a user handler */ PHPAPI int php_output_handler_alias_register(const char *name, size_t name_len, php_output_handler_alias_ctor_t func TSRMLS_DC) { if (!EG(current_module)) { zend_error(E_ERROR, "Cannot register an output handler alias outside of MINIT"); return FAILURE; } return zend_hash_update(&php_output_handler_aliases, name, name_len+1, &func, sizeof(php_output_handler_alias_ctor_t *), NULL); } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_handler_hook(php_output_handler_hook_t type, void *arg TSMRLS_DC) * Output handler hook for output handler functions to check/modify the current handlers abilities */ PHPAPI int php_output_handler_hook(php_output_handler_hook_t type, void *arg TSRMLS_DC) { if (OG(running)) { switch (type) { case PHP_OUTPUT_HANDLER_HOOK_GET_OPAQ: *(void ***) arg = &OG(running)->opaq; return SUCCESS; case PHP_OUTPUT_HANDLER_HOOK_GET_FLAGS: *(int *) arg = OG(running)->flags; return SUCCESS; case PHP_OUTPUT_HANDLER_HOOK_GET_LEVEL: *(int *) arg = OG(running)->level; return SUCCESS; case PHP_OUTPUT_HANDLER_HOOK_IMMUTABLE: OG(running)->flags &= ~(PHP_OUTPUT_HANDLER_REMOVABLE|PHP_OUTPUT_HANDLER_CLEANABLE); return SUCCESS; case PHP_OUTPUT_HANDLER_HOOK_DISABLE: OG(running)->flags |= PHP_OUTPUT_HANDLER_DISABLED; return SUCCESS; default: break; } } return FAILURE; } /* }}} */ /* {{{ void php_output_handler_dtor(php_output_handler *handler TSRMLS_DC) * Destroy an output handler */ PHPAPI void php_output_handler_dtor(php_output_handler *handler TSRMLS_DC) { STR_FREE(handler->name); STR_FREE(handler->buffer.data); if (handler->flags & PHP_OUTPUT_HANDLER_USER) { zval_ptr_dtor(&handler->func.user->zoh); efree(handler->func.user); } if (handler->dtor && handler->opaq) { handler->dtor(handler->opaq TSRMLS_CC); } memset(handler, 0, sizeof(*handler)); } /* }}} */ /* {{{ void php_output_handler_free(php_output_handler **handler TSMRLS_DC) * Destroy and free an output handler */ PHPAPI void php_output_handler_free(php_output_handler **h TSRMLS_DC) { if (*h) { php_output_handler_dtor(*h TSRMLS_CC); efree(*h); *h = NULL; } } /* }}} */ /* void php_output_set_implicit_flush(int enabled TSRMLS_DC) * Enable or disable implicit flush */ PHPAPI void php_output_set_implicit_flush(int flush TSRMLS_DC) { if (flush) { OG(flags) |= PHP_OUTPUT_IMPLICITFLUSH; } else { OG(flags) &= ~PHP_OUTPUT_IMPLICITFLUSH; } } /* }}} */ /* {{{ char *php_output_get_start_filename(TSRMLS_D) * Get the file name where output has started */ PHPAPI const char *php_output_get_start_filename(TSRMLS_D) { return OG(output_start_filename); } /* }}} */ /* {{{ int php_output_get_start_lineno(TSRMLS_D) * Get the line number where output has started */ PHPAPI int php_output_get_start_lineno(TSRMLS_D) { return OG(output_start_lineno); } /* }}} */ /* {{{ static int php_output_lock_error(int op TSRMLS_DC) * Checks whether an unallowed operation is attempted from within the output handler and issues a fatal error */ static inline int php_output_lock_error(int op TSRMLS_DC) { /* if there's no ob active, ob has been stopped */ if (op && OG(active) && OG(running)) { /* fatal error */ php_output_deactivate(TSRMLS_C); php_error_docref("ref.outcontrol" TSRMLS_CC, E_ERROR, "Cannot use output buffering in output buffering display handlers"); return 1; } return 0; } /* }}} */ /* {{{ static php_output_context *php_output_context_init(php_output_context *context, int op TSRMLS_DC) * Initialize a new output context */ static inline php_output_context *php_output_context_init(php_output_context *context, int op TSRMLS_DC) { if (!context) { context = emalloc(sizeof(php_output_context)); } memset(context, 0, sizeof(php_output_context)); TSRMLS_SET_CTX(context->tsrm_ls); context->op = op; return context; } /* }}} */ /* {{{ static void php_output_context_reset(php_output_context *context) * Reset an output context */ static inline void php_output_context_reset(php_output_context *context) { int op = context->op; php_output_context_dtor(context); memset(context, 0, sizeof(php_output_context)); context->op = op; } /* }}} */ /* {{{ static void php_output_context_feed(php_output_context *context, char *, size_t, size_t) * Feed output contexts input buffer */ static inline void php_output_context_feed(php_output_context *context, char *data, size_t size, size_t used, zend_bool free) { if (context->in.free && context->in.data) { efree(context->in.data); } context->in.data = data; context->in.used = used; context->in.free = free; context->in.size = size; } /* }}} */ /* {{{ static void php_output_context_swap(php_output_context *context) * Swap output contexts buffers */ static inline void php_output_context_swap(php_output_context *context) { if (context->in.free && context->in.data) { efree(context->in.data); } context->in.data = context->out.data; context->in.used = context->out.used; context->in.free = context->out.free; context->in.size = context->out.size; context->out.data = NULL; context->out.used = 0; context->out.free = 0; context->out.size = 0; } /* }}} */ /* {{{ static void php_output_context_pass(php_output_context *context) * Pass input to output buffer */ static inline void php_output_context_pass(php_output_context *context) { context->out.data = context->in.data; context->out.used = context->in.used; context->out.size = context->in.size; context->out.free = context->in.free; context->in.data = NULL; context->in.used = 0; context->in.free = 0; context->in.size = 0; } /* }}} */ /* {{{ static void php_output_context_dtor(php_output_context *context) * Destroy the contents of an output context */ static inline void php_output_context_dtor(php_output_context *context) { if (context->in.free && context->in.data) { efree(context->in.data); context->in.data = NULL; } if (context->out.free && context->out.data) { efree(context->out.data); context->out.data = NULL; } } /* }}} */ /* {{{ static php_output_handler *php_output_handler_init(zval *name, size_t chunk_size, int flags TSRMLS_DC) * Allocates and initializes a php_output_handler structure */ static inline php_output_handler *php_output_handler_init(const char *name, size_t name_len, size_t chunk_size, int flags TSRMLS_DC) { php_output_handler *handler; handler = ecalloc(1, sizeof(php_output_handler)); handler->name = estrndup(name, name_len); handler->name_len = name_len; handler->size = chunk_size; handler->flags = flags; handler->buffer.size = PHP_OUTPUT_HANDLER_INITBUF_SIZE(chunk_size); handler->buffer.data = emalloc(handler->buffer.size); return handler; } /* }}} */ /* {{{ static int php_output_handler_appen(php_output_handler *handler, const php_output_buffer *buf TSRMLS_DC) * Appends input to the output handlers buffer and indicates whether the buffer does not have to be processed by the output handler */ static inline int php_output_handler_append(php_output_handler *handler, const php_output_buffer *buf TSRMLS_DC) { if (buf->used) { OG(flags) |= PHP_OUTPUT_WRITTEN; /* store it away */ if ((handler->buffer.size - handler->buffer.used) <= buf->used) { size_t grow_int = PHP_OUTPUT_HANDLER_INITBUF_SIZE(handler->size); size_t grow_buf = PHP_OUTPUT_HANDLER_INITBUF_SIZE(buf->used - (handler->buffer.size - handler->buffer.used)); size_t grow_max = MAX(grow_int, grow_buf); handler->buffer.data = erealloc(handler->buffer.data, handler->buffer.size + grow_max); handler->buffer.size += grow_max; } memcpy(handler->buffer.data + handler->buffer.used, buf->data, buf->used); handler->buffer.used += buf->used; /* chunked buffering */ if (handler->size && (handler->buffer.used >= handler->size)) { /* store away errors and/or any intermediate output */ return OG(running) ? 1 : 0; } } return 1; } /* }}} */ /* {{{ static php_output_handler_status_t php_output_handler_op(php_output_handler *handler, php_output_context *context) * Output handler operation dispatcher, applying context op to the php_output_handler handler */ static inline php_output_handler_status_t php_output_handler_op(php_output_handler *handler, php_output_context *context) { php_output_handler_status_t status; int original_op = context->op; PHP_OUTPUT_TSRMLS(context); #if PHP_OUTPUT_DEBUG fprintf(stderr, ">>> op(%d, " "handler=%p, " "name=%s, " "flags=%d, " "buffer.data=%s, " "buffer.used=%zu, " "buffer.size=%zu, " "in.data=%s, " "in.used=%zu)\n", context->op, handler, handler->name, handler->flags, handler->buffer.used?handler->buffer.data:"", handler->buffer.used, handler->buffer.size, context->in.used?context->in.data:"", context->in.used ); #endif if (php_output_lock_error(context->op TSRMLS_CC)) { /* fatal error */ return PHP_OUTPUT_HANDLER_FAILURE; } /* storable? */ if (php_output_handler_append(handler, &context->in TSRMLS_CC) && !context->op) { status = PHP_OUTPUT_HANDLER_NO_DATA; } else { /* need to start? */ if (!(handler->flags & PHP_OUTPUT_HANDLER_STARTED)) { context->op |= PHP_OUTPUT_HANDLER_START; } OG(running) = handler; if (handler->flags & PHP_OUTPUT_HANDLER_USER) { zval *retval = NULL, *ob_data, *ob_mode; MAKE_STD_ZVAL(ob_data); ZVAL_STRINGL(ob_data, handler->buffer.data, handler->buffer.used, 1); MAKE_STD_ZVAL(ob_mode); ZVAL_LONG(ob_mode, (long) context->op); zend_fcall_info_argn(&handler->func.user->fci TSRMLS_CC, 2, &ob_data, &ob_mode); #define PHP_OUTPUT_USER_SUCCESS(retval) (retval && !(Z_TYPE_P(retval) == IS_BOOL && Z_BVAL_P(retval)==0)) if (SUCCESS == zend_fcall_info_call(&handler->func.user->fci, &handler->func.user->fcc, &retval, NULL TSRMLS_CC) && PHP_OUTPUT_USER_SUCCESS(retval)) { /* user handler may have returned TRUE */ status = PHP_OUTPUT_HANDLER_NO_DATA; if (Z_TYPE_P(retval) != IS_BOOL) { convert_to_string_ex(&retval); if (Z_STRLEN_P(retval)) { context->out.data = estrndup(Z_STRVAL_P(retval), Z_STRLEN_P(retval)); context->out.used = Z_STRLEN_P(retval); context->out.free = 1; status = PHP_OUTPUT_HANDLER_SUCCESS; } } } else { /* call failed, pass internal buffer along */ status = PHP_OUTPUT_HANDLER_FAILURE; } zend_fcall_info_argn(&handler->func.user->fci TSRMLS_CC, 0); zval_ptr_dtor(&ob_data); zval_ptr_dtor(&ob_mode); if (retval) { zval_ptr_dtor(&retval); } } else { php_output_context_feed(context, handler->buffer.data, handler->buffer.size, handler->buffer.used, 0); if (SUCCESS == handler->func.internal(&handler->opaq, context)) { if (context->out.used) { status = PHP_OUTPUT_HANDLER_SUCCESS; } else { status = PHP_OUTPUT_HANDLER_NO_DATA; } } else { status = PHP_OUTPUT_HANDLER_FAILURE; } } handler->flags |= PHP_OUTPUT_HANDLER_STARTED; OG(running) = NULL; } switch (status) { case PHP_OUTPUT_HANDLER_FAILURE: /* disable this handler */ handler->flags |= PHP_OUTPUT_HANDLER_DISABLED; /* discard any output */ if (context->out.data && context->out.free) { efree(context->out.data); } /* returns handlers buffer */ context->out.data = handler->buffer.data; context->out.used = handler->buffer.used; context->out.free = 1; handler->buffer.data = NULL; handler->buffer.used = 0; handler->buffer.size = 0; break; case PHP_OUTPUT_HANDLER_SUCCESS: /* no more buffered data */ handler->buffer.used = 0; break; case PHP_OUTPUT_HANDLER_NO_DATA: /* handler ate all */ php_output_context_reset(context); break; } context->op = original_op; return status; } /* }}} */ /* {{{ static void php_output_op(int op, const char *str, size_t len TSRMLS_DC) * Output op dispatcher, passes input and output handlers output through the output handler stack until it gets written to the SAPI */ static inline void php_output_op(int op, const char *str, size_t len TSRMLS_DC) { php_output_context context; php_output_handler **active; int obh_cnt; if (php_output_lock_error(op TSRMLS_CC)) { return; } php_output_context_init(&context, op TSRMLS_CC); /* * broken up for better performance: * - apply op to the one active handler; note that OG(active) might be popped off the stack on a flush * - or apply op to the handler stack */ if (OG(active) && (obh_cnt = zend_stack_count(&OG(handlers)))) { context.in.data = (char *) str; context.in.used = len; if (obh_cnt > 1) { zend_stack_apply_with_argument(&OG(handlers), ZEND_STACK_APPLY_TOPDOWN, php_output_stack_apply_op, &context); } else if ((SUCCESS == zend_stack_top(&OG(handlers), (void *) &active)) && (!((*active)->flags & PHP_OUTPUT_HANDLER_DISABLED))) { php_output_handler_op(*active, &context); } else { php_output_context_pass(&context); } } else { context.out.data = (char *) str; context.out.used = len; } if (context.out.data && context.out.used) { #if PHP_OUTPUT_DEBUG fprintf(stderr, "::: sapi_write('%s', %zu)\n", context.out.data, context.out.used); #endif if (!SG(headers_sent) && php_header(TSRMLS_C)) { if (zend_is_compiling(TSRMLS_C)) { OG(output_start_filename) = zend_get_compiled_filename(TSRMLS_C); OG(output_start_lineno) = zend_get_compiled_lineno(TSRMLS_C); } else if (zend_is_executing(TSRMLS_C)) { OG(output_start_filename) = zend_get_executed_filename(TSRMLS_C); OG(output_start_lineno) = zend_get_executed_lineno(TSRMLS_C); } #if PHP_OUTPUT_DEBUG fprintf(stderr, "!!! output started at: %s (%d)\n", OG(output_start_filename), OG(output_start_lineno)); #endif } sapi_module.ub_write(context.out.data, context.out.used TSRMLS_CC); if (OG(flags) & PHP_OUTPUT_IMPLICITFLUSH) { sapi_flush(TSRMLS_C); } OG(flags) |= PHP_OUTPUT_SENT; } php_output_context_dtor(&context); } /* }}} */ /* {{{ static int php_output_stack_apply_op(void *h, void *c) * Operation callback for the stack apply function */ static int php_output_stack_apply_op(void *h, void *c) { int was_disabled; php_output_handler_status_t status; php_output_handler *handler = *(php_output_handler **) h; php_output_context *context = (php_output_context *) c; if ((was_disabled = (handler->flags & PHP_OUTPUT_HANDLER_DISABLED))) { status = PHP_OUTPUT_HANDLER_FAILURE; } else { status = php_output_handler_op(handler, context); } /* * handler ate all => break * handler returned data or failed resp. is disabled => continue */ switch (status) { case PHP_OUTPUT_HANDLER_NO_DATA: return 1; case PHP_OUTPUT_HANDLER_SUCCESS: /* swap contexts buffers, unless this is the last handler in the stack */ if (handler->level) { php_output_context_swap(context); } return 0; case PHP_OUTPUT_HANDLER_FAILURE: default: if (was_disabled) { /* pass input along, if it's the last handler in the stack */ if (!handler->level) { php_output_context_pass(context); } } else { /* swap buffers, unless this is the last handler */ if (handler->level) { php_output_context_swap(context); } } return 0; } } /* }}} */ /* {{{ static int php_output_stack_apply_clean(void *h, void *c) * Clean callback for the stack apply function */ static int php_output_stack_apply_clean(void *h, void *c) { php_output_handler *handler = *(php_output_handler **) h; php_output_context *context = (php_output_context *) c; handler->buffer.used = 0; php_output_handler_op(handler, context); php_output_context_reset(context); return 0; } /* }}} */ /* {{{ static int php_output_stack_apply_list(void *h, void *z) * List callback for the stack apply function */ static int php_output_stack_apply_list(void *h, void *z) { php_output_handler *handler = *(php_output_handler **) h; zval *array = (zval *) z; add_next_index_stringl(array, handler->name, handler->name_len, 1); return 0; } /* }}} */ /* {{{ static int php_output_stack_apply_status(void *h, void *z) * Status callback for the stack apply function */ static int php_output_stack_apply_status(void *h, void *z) { php_output_handler *handler = *(php_output_handler **) h; zval *array = (zval *) z; add_next_index_zval(array, php_output_handler_status(handler, NULL)); return 0; } /* {{{ static zval *php_output_handler_status(php_output_handler *handler, zval *entry) * Returns an array with the status of the output handler */ static inline zval *php_output_handler_status(php_output_handler *handler, zval *entry) { if (!entry) { MAKE_STD_ZVAL(entry); array_init(entry); } add_assoc_stringl(entry, "name", handler->name, handler->name_len, 1); add_assoc_long(entry, "type", (long) (handler->flags & 0xf)); add_assoc_long(entry, "flags", (long) handler->flags); add_assoc_long(entry, "level", (long) handler->level); add_assoc_long(entry, "chunk_size", (long) handler->size); add_assoc_long(entry, "buffer_size", (long) handler->buffer.size); add_assoc_long(entry, "buffer_used", (long) handler->buffer.used); return entry; } /* }}} */ /* {{{ static int php_output_stack_pop(int flags TSRMLS_DC) * Pops an output handler off the stack */ static inline int php_output_stack_pop(int flags TSRMLS_DC) { php_output_context context; php_output_handler **current, *orphan = OG(active); if (!orphan) { if (!(flags & PHP_OUTPUT_POP_SILENT)) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_NOTICE, "failed to %s buffer. No buffer to %s", (flags&PHP_OUTPUT_POP_DISCARD)?"discard":"send", (flags&PHP_OUTPUT_POP_DISCARD)?"discard":"send"); } return 0; } else if (!(flags & PHP_OUTPUT_POP_FORCE) && !(orphan->flags & PHP_OUTPUT_HANDLER_REMOVABLE)) { if (!(flags & PHP_OUTPUT_POP_SILENT)) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_NOTICE, "failed to %s buffer of %s (%d)", (flags&PHP_OUTPUT_POP_DISCARD)?"discard":"send", orphan->name, orphan->level); } return 0; } else { php_output_context_init(&context, PHP_OUTPUT_HANDLER_FINAL TSRMLS_CC); /* don't run the output handler if it's disabled */ if (!(orphan->flags & PHP_OUTPUT_HANDLER_DISABLED)) { /* didn't it start yet? */ if (!(orphan->flags & PHP_OUTPUT_HANDLER_STARTED)) { context.op |= PHP_OUTPUT_HANDLER_START; } /* signal that we're cleaning up */ if (flags & PHP_OUTPUT_POP_DISCARD) { context.op |= PHP_OUTPUT_HANDLER_CLEAN; orphan->buffer.used = 0; } php_output_handler_op(orphan, &context); } /* pop it off the stack */ zend_stack_del_top(&OG(handlers)); if (SUCCESS == zend_stack_top(&OG(handlers), (void *) &current)) { OG(active) = *current; } else { OG(active) = NULL; } /* pass output along */ if (context.out.data && context.out.used && !(flags & PHP_OUTPUT_POP_DISCARD)) { php_output_write(context.out.data, context.out.used TSRMLS_CC); } /* destroy the handler (after write!) */ php_output_handler_free(&orphan TSRMLS_CC); php_output_context_dtor(&context); return 1; } } /* }}} */ /* {{{ static SUCCESS|FAILURE php_output_handler_compat_func(void *ctx, php_output_context *) * php_output_handler_context_func_t for php_output_handler_func_t output handlers */ static int php_output_handler_compat_func(void **handler_context, php_output_context *output_context) { php_output_handler_func_t func = *(php_output_handler_func_t *) handler_context; PHP_OUTPUT_TSRMLS(output_context); if (func) { uint safe_out_len; func(output_context->in.data, output_context->in.used, &output_context->out.data, &safe_out_len, output_context->op TSRMLS_CC); output_context->out.used = safe_out_len; output_context->out.free = 1; return SUCCESS; } return FAILURE; } /* }}} */ /* {{{ static SUCCESS|FAILURE php_output_handler_default_func(void *ctx, php_output_context *) * Default output handler */ static int php_output_handler_default_func(void **handler_context, php_output_context *output_context) { php_output_context_pass(output_context); return SUCCESS; } /* }}} */ /* {{{ static SUCCESS|FAILURE php_output_handler_devnull_func(void *ctx, php_output_context *) * Null output handler */ static int php_output_handler_devnull_func(void **handler_context, php_output_context *output_context) { return SUCCESS; } /* }}} */ /* * USERLAND (nearly 1:1 of old output.c) */ /* {{{ proto bool ob_start([string|array user_function [, int chunk_size [, int flags]]]) Turn on Output Buffering (specifying an optional output handler). */ PHP_FUNCTION(ob_start) { zval *output_handler = NULL; long chunk_size = 0; long flags = PHP_OUTPUT_HANDLER_STDFLAGS; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z/ll", &output_handler, &chunk_size, &flags) == FAILURE) { return; } if (chunk_size < 0) { chunk_size = 0; } if (php_output_start_user(output_handler, chunk_size, flags TSRMLS_CC) == FAILURE) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_NOTICE, "failed to create buffer"); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool ob_flush(void) Flush (send) contents of the output buffer. The last buffer content is sent to next buffer */ PHP_FUNCTION(ob_flush) { if (zend_parse_parameters_none() == FAILURE) { return; } if (!OG(active)) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_NOTICE, "failed to flush buffer. No buffer to flush"); RETURN_FALSE; } if (SUCCESS != php_output_flush(TSRMLS_C)) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_NOTICE, "failed to flush buffer of %s (%d)", OG(active)->name, OG(active)->level); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool ob_clean(void) Clean (delete) the current output buffer */ PHP_FUNCTION(ob_clean) { if (zend_parse_parameters_none() == FAILURE) { return; } if (!OG(active)) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_NOTICE, "failed to delete buffer. No buffer to delete"); RETURN_FALSE; } if (SUCCESS != php_output_clean(TSRMLS_C)) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_NOTICE, "failed to delete buffer of %s (%d)", OG(active)->name, OG(active)->level); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool ob_end_flush(void) Flush (send) the output buffer, and delete current output buffer */ PHP_FUNCTION(ob_end_flush) { if (zend_parse_parameters_none() == FAILURE) { return; } if (!OG(active)) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_NOTICE, "failed to delete and flush buffer. No buffer to delete or flush"); RETURN_FALSE; } RETURN_BOOL(SUCCESS == php_output_end(TSRMLS_C)); } /* }}} */ /* {{{ proto bool ob_end_clean(void) Clean the output buffer, and delete current output buffer */ PHP_FUNCTION(ob_end_clean) { if (zend_parse_parameters_none() == FAILURE) { return; } if (!OG(active)) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_NOTICE, "failed to delete buffer. No buffer to delete"); RETURN_FALSE; } RETURN_BOOL(SUCCESS == php_output_discard(TSRMLS_C)); } /* }}} */ /* {{{ proto bool ob_get_flush(void) Get current buffer contents, flush (send) the output buffer, and delete current output buffer */ PHP_FUNCTION(ob_get_flush) { if (zend_parse_parameters_none() == FAILURE) { return; } if (php_output_get_contents(return_value TSRMLS_CC) == FAILURE) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_NOTICE, "failed to delete and flush buffer. No buffer to delete or flush"); RETURN_FALSE; } if (SUCCESS != php_output_end(TSRMLS_C)) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_NOTICE, "failed to delete buffer of %s (%d)", OG(active)->name, OG(active)->level); } } /* }}} */ /* {{{ proto bool ob_get_clean(void) Get current buffer contents and delete current output buffer */ PHP_FUNCTION(ob_get_clean) { if (zend_parse_parameters_none() == FAILURE) { return; } if(!OG(active)) { RETURN_FALSE; } if (php_output_get_contents(return_value TSRMLS_CC) == FAILURE) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_NOTICE, "failed to delete buffer. No buffer to delete"); RETURN_FALSE; } if (SUCCESS != php_output_discard(TSRMLS_C)) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_NOTICE, "failed to delete buffer of %s (%d)", OG(active)->name, OG(active)->level); } } /* }}} */ /* {{{ proto string ob_get_contents(void) Return the contents of the output buffer */ PHP_FUNCTION(ob_get_contents) { if (zend_parse_parameters_none() == FAILURE) { return; } if (php_output_get_contents(return_value TSRMLS_CC) == FAILURE) { RETURN_FALSE; } } /* }}} */ /* {{{ proto int ob_get_level(void) Return the nesting level of the output buffer */ PHP_FUNCTION(ob_get_level) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(php_output_get_level(TSRMLS_C)); } /* }}} */ /* {{{ proto int ob_get_length(void) Return the length of the output buffer */ PHP_FUNCTION(ob_get_length) { if (zend_parse_parameters_none() == FAILURE) { return; } if (php_output_get_length(return_value TSRMLS_CC) == FAILURE) { RETURN_FALSE; } } /* }}} */ /* {{{ proto false|array ob_list_handlers() List all output_buffers in an array */ PHP_FUNCTION(ob_list_handlers) { if (zend_parse_parameters_none() == FAILURE) { return; } array_init(return_value); if (!OG(active)) { return; } zend_stack_apply_with_argument(&OG(handlers), ZEND_STACK_APPLY_BOTTOMUP, php_output_stack_apply_list, return_value); } /* }}} */ /* {{{ proto false|array ob_get_status([bool full_status]) Return the status of the active or all output buffers */ PHP_FUNCTION(ob_get_status) { zend_bool full_status = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &full_status) == FAILURE) { return; } array_init(return_value); if (!OG(active)) { return; } if (full_status) { zend_stack_apply_with_argument(&OG(handlers), ZEND_STACK_APPLY_BOTTOMUP, php_output_stack_apply_status, return_value); } else { php_output_handler_status(OG(active), return_value); } } /* }}} */ /* {{{ proto void ob_implicit_flush([int flag]) Turn implicit flush on/off and is equivalent to calling flush() after every output call */ PHP_FUNCTION(ob_implicit_flush) { long flag = 1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &flag) == FAILURE) { return; } php_output_set_implicit_flush(flag TSRMLS_CC); } /* }}} */ /* {{{ proto bool output_reset_rewrite_vars(void) Reset(clear) URL rewriter values */ PHP_FUNCTION(output_reset_rewrite_vars) { if (php_url_scanner_reset_vars(TSRMLS_C) == SUCCESS) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool output_add_rewrite_var(string name, string value) Add URL rewriter values */ PHP_FUNCTION(output_add_rewrite_var) { char *name, *value; int name_len, value_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &name, &name_len, &value, &value_len) == FAILURE) { return; } if (php_url_scanner_add_var(name, name_len, value, value_len, 1 TSRMLS_CC) == SUCCESS) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2012 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Zeev Suraski <[email protected]> | | Thies C. Arntzen <[email protected]> | | Marcus Boerger <[email protected]> | | New API: Michael Wallner <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifndef PHP_OUTPUT_DEBUG # define PHP_OUTPUT_DEBUG 0 #endif #ifndef PHP_OUTPUT_NOINLINE # define PHP_OUTPUT_NOINLINE 0 #endif #include "php.h" #include "ext/standard/head.h" #include "ext/standard/url_scanner_ex.h" #include "SAPI.h" #include "zend_stack.h" #include "php_output.h" ZEND_DECLARE_MODULE_GLOBALS(output); const char php_output_default_handler_name[sizeof("default output handler")] = "default output handler"; const char php_output_devnull_handler_name[sizeof("null output handler")] = "null output handler"; #if PHP_OUTPUT_NOINLINE || PHP_OUTPUT_DEBUG # undef inline # define inline #endif /* {{{ aliases, conflict and reverse conflict hash tables */ static HashTable php_output_handler_aliases; static HashTable php_output_handler_conflicts; static HashTable php_output_handler_reverse_conflicts; /* }}} */ /* {{{ forward declarations */ static inline int php_output_lock_error(int op TSRMLS_DC); static inline void php_output_op(int op, const char *str, size_t len TSRMLS_DC); static inline php_output_handler *php_output_handler_init(const char *name, size_t name_len, size_t chunk_size, int flags TSRMLS_DC); static inline php_output_handler_status_t php_output_handler_op(php_output_handler *handler, php_output_context *context); static inline int php_output_handler_append(php_output_handler *handler, const php_output_buffer *buf TSRMLS_DC); static inline zval *php_output_handler_status(php_output_handler *handler, zval *entry); static inline php_output_context *php_output_context_init(php_output_context *context, int op TSRMLS_DC); static inline void php_output_context_reset(php_output_context *context); static inline void php_output_context_swap(php_output_context *context); static inline void php_output_context_dtor(php_output_context *context); static inline int php_output_stack_pop(int flags TSRMLS_DC); static int php_output_stack_apply_op(void *h, void *c); static int php_output_stack_apply_clean(void *h, void *c); static int php_output_stack_apply_list(void *h, void *z); static int php_output_stack_apply_status(void *h, void *z); static int php_output_handler_compat_func(void **handler_context, php_output_context *output_context); static int php_output_handler_default_func(void **handler_context, php_output_context *output_context); static int php_output_handler_devnull_func(void **handler_context, php_output_context *output_context); /* }}} */ /* {{{ static void php_output_init_globals(zend_output_globals *G) * Initialize the module globals on MINIT */ static inline void php_output_init_globals(zend_output_globals *G) { memset(G, 0, sizeof(*G)); } /* }}} */ /* {{{ void php_output_startup(void) * Set up module globals and initalize the conflict and reverse conflict hash tables */ PHPAPI void php_output_startup(void) { ZEND_INIT_MODULE_GLOBALS(output, php_output_init_globals, NULL); zend_hash_init(&php_output_handler_aliases, 0, NULL, NULL, 1); zend_hash_init(&php_output_handler_conflicts, 0, NULL, NULL, 1); zend_hash_init(&php_output_handler_reverse_conflicts, 0, NULL, (void (*)(void *)) zend_hash_destroy, 1); } /* }}} */ /* {{{ void php_output_shutdown(void) * Destroy module globals and the conflict and reverse conflict hash tables */ PHPAPI void php_output_shutdown(void) { zend_hash_destroy(&php_output_handler_aliases); zend_hash_destroy(&php_output_handler_conflicts); zend_hash_destroy(&php_output_handler_reverse_conflicts); } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_activate(TSRMLS_D) * Reset output globals and setup the output handler stack */ PHPAPI int php_output_activate(TSRMLS_D) { #ifdef ZTS memset((*((void ***) tsrm_ls))[TSRM_UNSHUFFLE_RSRC_ID(output_globals_id)], 0, sizeof(zend_output_globals)); #else memset(&output_globals, 0, sizeof(zend_output_globals)); #endif zend_stack_init(&OG(handlers)); return SUCCESS; } /* }}} */ /* {{{ void php_output_deactivate(TSRMLS_D) * Destroy the output handler stack */ PHPAPI void php_output_deactivate(TSRMLS_D) { php_output_handler **handler = NULL; OG(active) = NULL; OG(running) = NULL; /* release all output handlers */ if (OG(handlers).elements) { while (SUCCESS == zend_stack_top(&OG(handlers), (void *) &handler)) { php_output_handler_free(handler TSRMLS_CC); zend_stack_del_top(&OG(handlers)); } zend_stack_destroy(&OG(handlers)); } } /* }}} */ /* {{{ void php_output_register_constants() */ PHPAPI void php_output_register_constants(TSRMLS_D) { REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_START", PHP_OUTPUT_HANDLER_START, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_WRITE", PHP_OUTPUT_HANDLER_WRITE, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_FLUSH", PHP_OUTPUT_HANDLER_FLUSH, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_CLEAN", PHP_OUTPUT_HANDLER_CLEAN, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_FINAL", PHP_OUTPUT_HANDLER_FINAL, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_CONT", PHP_OUTPUT_HANDLER_WRITE, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_END", PHP_OUTPUT_HANDLER_FINAL, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_CLEANABLE", PHP_OUTPUT_HANDLER_CLEANABLE, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_FLUSHABLE", PHP_OUTPUT_HANDLER_FLUSHABLE, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_REMOVABLE", PHP_OUTPUT_HANDLER_REMOVABLE, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_STDFLAGS", PHP_OUTPUT_HANDLER_STDFLAGS, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_STARTED", PHP_OUTPUT_HANDLER_STARTED, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_DISABLED", PHP_OUTPUT_HANDLER_DISABLED, CONST_CS | CONST_PERSISTENT); } /* }}} */ /* {{{ void php_output_set_status(int status TSRMLS_DC) * Used by SAPIs to disable output */ PHPAPI void php_output_set_status(int status TSRMLS_DC) { OG(flags) = status & 0xf; } /* }}} */ /* {{{ int php_output_get_status(TSRMLS_C) * Get output control status */ PHPAPI int php_output_get_status(TSRMLS_D) { return OG(flags) | (OG(active) ? PHP_OUTPUT_ACTIVE : 0) | (OG(running)? PHP_OUTPUT_LOCKED : 0); } /* }}} */ /* {{{ int php_output_write_unbuffered(const char *str, size_t len TSRMLS_DC) * Unbuffered write */ PHPAPI int php_output_write_unbuffered(const char *str, size_t len TSRMLS_DC) { if (OG(flags) & PHP_OUTPUT_DISABLED) { return 0; } return sapi_module.ub_write(str, len TSRMLS_CC); } /* }}} */ /* {{{ int php_output_write(const char *str, size_t len TSRMLS_DC) * Buffered write */ PHPAPI int php_output_write(const char *str, size_t len TSRMLS_DC) { if (OG(flags) & PHP_OUTPUT_DISABLED) { return 0; } php_output_op(PHP_OUTPUT_HANDLER_WRITE, str, len TSRMLS_CC); return (int) len; } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_flush(TSRMLS_D) * Flush the most recent output handlers buffer */ PHPAPI int php_output_flush(TSRMLS_D) { php_output_context context; if (OG(active) && (OG(active)->flags & PHP_OUTPUT_HANDLER_FLUSHABLE)) { php_output_context_init(&context, PHP_OUTPUT_HANDLER_FLUSH TSRMLS_CC); php_output_handler_op(OG(active), &context); if (context.out.data && context.out.used) { zend_stack_del_top(&OG(handlers)); php_output_write(context.out.data, context.out.used TSRMLS_CC); zend_stack_push(&OG(handlers), &OG(active), sizeof(php_output_handler *)); } php_output_context_dtor(&context); return SUCCESS; } return FAILURE; } /* }}} */ /* {{{ void php_output_flush_all(TSRMLS_C) * Flush all output buffers subsequently */ PHPAPI void php_output_flush_all(TSRMLS_D) { if (OG(active)) { php_output_op(PHP_OUTPUT_HANDLER_FLUSH, NULL, 0 TSRMLS_CC); } } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_clean(TSRMLS_D) * Cleans the most recent output handlers buffer if the handler is cleanable */ PHPAPI int php_output_clean(TSRMLS_D) { php_output_context context; if (OG(active) && (OG(active)->flags & PHP_OUTPUT_HANDLER_CLEANABLE)) { OG(active)->buffer.used = 0; php_output_context_init(&context, PHP_OUTPUT_HANDLER_CLEAN TSRMLS_CC); php_output_handler_op(OG(active), &context); php_output_context_dtor(&context); return SUCCESS; } return FAILURE; } /* }}} */ /* {{{ void php_output_clean_all(TSRMLS_D) * Cleans all output handler buffers, without regard whether the handler is cleanable */ PHPAPI void php_output_clean_all(TSRMLS_D) { php_output_context context; if (OG(active)) { php_output_context_init(&context, PHP_OUTPUT_HANDLER_CLEAN TSRMLS_CC); zend_stack_apply_with_argument(&OG(handlers), ZEND_STACK_APPLY_TOPDOWN, php_output_stack_apply_clean, &context); } } /* {{{ SUCCESS|FAILURE php_output_end(TSRMLS_D) * Finalizes the most recent output handler at pops it off the stack if the handler is removable */ PHPAPI int php_output_end(TSRMLS_D) { if (php_output_stack_pop(PHP_OUTPUT_POP_TRY TSRMLS_CC)) { return SUCCESS; } return FAILURE; } /* }}} */ /* {{{ void php_output_end_all(TSRMLS_D) * Finalizes all output handlers and ends output buffering without regard whether a handler is removable */ PHPAPI void php_output_end_all(TSRMLS_D) { while (OG(active) && php_output_stack_pop(PHP_OUTPUT_POP_FORCE TSRMLS_CC)); } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_discard(TSRMLS_D) * Discards the most recent output handlers buffer and pops it off the stack if the handler is removable */ PHPAPI int php_output_discard(TSRMLS_D) { if (php_output_stack_pop(PHP_OUTPUT_POP_DISCARD|PHP_OUTPUT_POP_TRY TSRMLS_CC)) { return SUCCESS; } return FAILURE; } /* }}} */ /* {{{ void php_output_discard_all(TSRMLS_D) * Discard all output handlers and buffers without regard whether a handler is removable */ PHPAPI void php_output_discard_all(TSRMLS_D) { while (OG(active)) { php_output_stack_pop(PHP_OUTPUT_POP_DISCARD|PHP_OUTPUT_POP_FORCE TSRMLS_CC); } } /* }}} */ /* {{{ int php_output_get_level(TSRMLS_D) * Get output buffering level, ie. how many output handlers the stack contains */ PHPAPI int php_output_get_level(TSRMLS_D) { return OG(active) ? zend_stack_count(&OG(handlers)) : 0; } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_get_contents(zval *z TSRMLS_DC) * Get the contents of the active output handlers buffer */ PHPAPI int php_output_get_contents(zval *p TSRMLS_DC) { if (OG(active)) { ZVAL_STRINGL(p, OG(active)->buffer.data, OG(active)->buffer.used, 1); return SUCCESS; } else { ZVAL_NULL(p); return FAILURE; } } /* {{{ SUCCESS|FAILURE php_output_get_length(zval *z TSRMLS_DC) * Get the length of the active output handlers buffer */ PHPAPI int php_output_get_length(zval *p TSRMLS_DC) { if (OG(active)) { ZVAL_LONG(p, OG(active)->buffer.used); return SUCCESS; } else { ZVAL_NULL(p); return FAILURE; } } /* }}} */ /* {{{ php_output_handler* php_output_get_active_handler(TSRMLS_D) * Get active output handler */ PHPAPI php_output_handler* php_output_get_active_handler(TSRMLS_D) { return OG(active); } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_handler_start_default(TSRMLS_D) * Start a "default output handler" */ PHPAPI int php_output_start_default(TSRMLS_D) { php_output_handler *handler; handler = php_output_handler_create_internal(ZEND_STRL(php_output_default_handler_name), php_output_handler_default_func, 0, PHP_OUTPUT_HANDLER_STDFLAGS TSRMLS_CC); if (SUCCESS == php_output_handler_start(handler TSRMLS_CC)) { return SUCCESS; } php_output_handler_free(&handler TSRMLS_CC); return FAILURE; } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_handler_start_devnull(TSRMLS_D) * Start a "null output handler" */ PHPAPI int php_output_start_devnull(TSRMLS_D) { php_output_handler *handler; handler = php_output_handler_create_internal(ZEND_STRL(php_output_devnull_handler_name), php_output_handler_devnull_func, PHP_OUTPUT_HANDLER_DEFAULT_SIZE, 0 TSRMLS_CC); if (SUCCESS == php_output_handler_start(handler TSRMLS_CC)) { return SUCCESS; } php_output_handler_free(&handler TSRMLS_CC); return FAILURE; } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_start_user(zval *handler, size_t chunk_size, int flags TSRMLS_DC) * Start a user level output handler */ PHPAPI int php_output_start_user(zval *output_handler, size_t chunk_size, int flags TSRMLS_DC) { php_output_handler *handler; if (output_handler) { handler = php_output_handler_create_user(output_handler, chunk_size, flags TSRMLS_CC); } else { handler = php_output_handler_create_internal(ZEND_STRL(php_output_default_handler_name), php_output_handler_default_func, chunk_size, flags TSRMLS_CC); } if (SUCCESS == php_output_handler_start(handler TSRMLS_CC)) { return SUCCESS; } php_output_handler_free(&handler TSRMLS_CC); return FAILURE; } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_start_internal(zval *name, php_output_handler_func_t handler, size_t chunk_size, int flags TSRMLS_DC) * Start an internal output handler that does not have to maintain a non-global state */ PHPAPI int php_output_start_internal(const char *name, size_t name_len, php_output_handler_func_t output_handler, size_t chunk_size, int flags TSRMLS_DC) { php_output_handler *handler; handler = php_output_handler_create_internal(name, name_len, php_output_handler_compat_func, chunk_size, flags TSRMLS_CC); php_output_handler_set_context(handler, output_handler, NULL TSRMLS_CC); if (SUCCESS == php_output_handler_start(handler TSRMLS_CC)) { return SUCCESS; } php_output_handler_free(&handler TSRMLS_CC); return FAILURE; } /* }}} */ /* {{{ php_output_handler *php_output_handler_create_user(zval *handler, size_t chunk_size, int flags TSRMLS_DC) * Create a user level output handler */ PHPAPI php_output_handler *php_output_handler_create_user(zval *output_handler, size_t chunk_size, int flags TSRMLS_DC) { char *handler_name = NULL, *error = NULL; php_output_handler *handler = NULL; php_output_handler_alias_ctor_t *alias = NULL; php_output_handler_user_func_t *user = NULL; switch (Z_TYPE_P(output_handler)) { case IS_NULL: handler = php_output_handler_create_internal(ZEND_STRL(php_output_default_handler_name), php_output_handler_default_func, chunk_size, flags TSRMLS_CC); break; case IS_STRING: if (Z_STRLEN_P(output_handler) && (alias = php_output_handler_alias(Z_STRVAL_P(output_handler), Z_STRLEN_P(output_handler) TSRMLS_CC))) { handler = (*alias)(Z_STRVAL_P(output_handler), Z_STRLEN_P(output_handler), chunk_size, flags TSRMLS_CC); break; } default: user = ecalloc(1, sizeof(php_output_handler_user_func_t)); if (SUCCESS == zend_fcall_info_init(output_handler, 0, &user->fci, &user->fcc, &handler_name, &error TSRMLS_CC)) { handler = php_output_handler_init(handler_name, strlen(handler_name), chunk_size, (flags & ~0xf) | PHP_OUTPUT_HANDLER_USER TSRMLS_CC); Z_ADDREF_P(output_handler); user->zoh = output_handler; handler->func.user = user; } else { efree(user); } if (error) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_WARNING, "%s", error); efree(error); } if (handler_name) { efree(handler_name); } } return handler; } /* }}} */ /* {{{ php_output_handler *php_output_handler_create_internal(zval *name, php_output_handler_context_func_t handler, size_t chunk_size, int flags TSRMLS_DC) * Create an internal output handler that can maintain a non-global state */ PHPAPI php_output_handler *php_output_handler_create_internal(const char *name, size_t name_len, php_output_handler_context_func_t output_handler, size_t chunk_size, int flags TSRMLS_DC) { php_output_handler *handler; handler = php_output_handler_init(name, name_len, chunk_size, (flags & ~0xf) | PHP_OUTPUT_HANDLER_INTERNAL TSRMLS_CC); handler->func.internal = output_handler; return handler; } /* }}} */ /* {{{ void php_output_handler_set_context(php_output_handler *handler, void *opaq, void (*dtor)(void* TSRMLS_DC) TSRMLS_DC) * Set the context/state of an output handler. Calls the dtor of the previous context if there is one */ PHPAPI void php_output_handler_set_context(php_output_handler *handler, void *opaq, void (*dtor)(void* TSRMLS_DC) TSRMLS_DC) { if (handler->dtor && handler->opaq) { handler->dtor(handler->opaq TSRMLS_CC); } handler->dtor = dtor; handler->opaq = opaq; } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_handler_start(php_output_handler *handler TSRMLS_DC) * Starts the set up output handler and pushes it on top of the stack. Checks for any conflicts regarding the output handler to start */ PHPAPI int php_output_handler_start(php_output_handler *handler TSRMLS_DC) { HashPosition pos; HashTable *rconflicts; php_output_handler_conflict_check_t *conflict; if (php_output_lock_error(PHP_OUTPUT_HANDLER_START TSRMLS_CC) || !handler) { return FAILURE; } if (SUCCESS == zend_hash_find(&php_output_handler_conflicts, handler->name, handler->name_len+1, (void *) &conflict)) { if (SUCCESS != (*conflict)(handler->name, handler->name_len TSRMLS_CC)) { return FAILURE; } } if (SUCCESS == zend_hash_find(&php_output_handler_reverse_conflicts, handler->name, handler->name_len+1, (void *) &rconflicts)) { for (zend_hash_internal_pointer_reset_ex(rconflicts, &pos); zend_hash_get_current_data_ex(rconflicts, (void *) &conflict, &pos) == SUCCESS; zend_hash_move_forward_ex(rconflicts, &pos) ) { if (SUCCESS != (*conflict)(handler->name, handler->name_len TSRMLS_CC)) { return FAILURE; } } } /* zend_stack_push never returns SUCCESS but FAILURE or stack level */ if (FAILURE == (handler->level = zend_stack_push(&OG(handlers), &handler, sizeof(php_output_handler *)))) { return FAILURE; } OG(active) = handler; return SUCCESS; } /* }}} */ /* {{{ int php_output_handler_started(zval *name TSRMLS_DC) * Check whether a certain output handler is in use */ PHPAPI int php_output_handler_started(const char *name, size_t name_len TSRMLS_DC) { php_output_handler ***handlers; int i, count = php_output_get_level(TSRMLS_C); if (count) { handlers = (php_output_handler ***) zend_stack_base(&OG(handlers)); for (i = 0; i < count; ++i) { if (name_len == (*(handlers[i]))->name_len && !memcmp((*(handlers[i]))->name, name, name_len)) { return 1; } } } return 0; } /* }}} */ /* {{{ int php_output_handler_conflict(zval *handler_new, zval *handler_old TSRMLS_DC) * Check whether a certain handler is in use and issue a warning that the new handler would conflict with the already used one */ PHPAPI int php_output_handler_conflict(const char *handler_new, size_t handler_new_len, const char *handler_set, size_t handler_set_len TSRMLS_DC) { if (php_output_handler_started(handler_set, handler_set_len TSRMLS_CC)) { if (handler_new_len != handler_set_len || memcmp(handler_new, handler_set, handler_set_len)) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_WARNING, "output handler '%s' conflicts with '%s'", handler_new, handler_set); } else { php_error_docref("ref.outcontrol" TSRMLS_CC, E_WARNING, "output handler '%s' cannot be used twice", handler_new); } return 1; } return 0; } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_handler_conflict_register(zval *name, php_output_handler_conflict_check_t check_func TSRMLS_DC) * Register a conflict checking function on MINIT */ PHPAPI int php_output_handler_conflict_register(const char *name, size_t name_len, php_output_handler_conflict_check_t check_func TSRMLS_DC) { if (!EG(current_module)) { zend_error(E_ERROR, "Cannot register an output handler conflict outside of MINIT"); return FAILURE; } return zend_hash_update(&php_output_handler_conflicts, name, name_len+1, &check_func, sizeof(php_output_handler_conflict_check_t *), NULL); } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_handler_reverse_conflict_register(zval *name, php_output_handler_conflict_check_t check_func TSRMLS_DC) * Register a reverse conflict checking function on MINIT */ PHPAPI int php_output_handler_reverse_conflict_register(const char *name, size_t name_len, php_output_handler_conflict_check_t check_func TSRMLS_DC) { HashTable rev, *rev_ptr = NULL; if (!EG(current_module)) { zend_error(E_ERROR, "Cannot register a reverse output handler conflict outside of MINIT"); return FAILURE; } if (SUCCESS == zend_hash_find(&php_output_handler_reverse_conflicts, name, name_len+1, (void *) &rev_ptr)) { return zend_hash_next_index_insert(rev_ptr, &check_func, sizeof(php_output_handler_conflict_check_t *), NULL); } else { zend_hash_init(&rev, 1, NULL, NULL, 1); if (SUCCESS != zend_hash_next_index_insert(&rev, &check_func, sizeof(php_output_handler_conflict_check_t *), NULL)) { zend_hash_destroy(&rev); return FAILURE; } if (SUCCESS != zend_hash_update(&php_output_handler_reverse_conflicts, name, name_len+1, &rev, sizeof(HashTable), NULL)) { zend_hash_destroy(&rev); return FAILURE; } return SUCCESS; } } /* }}} */ /* {{{ php_output_handler_alias_ctor_t php_output_handler_alias(zval *name TSRMLS_DC) * Get an internal output handler for a user handler if it exists */ PHPAPI php_output_handler_alias_ctor_t *php_output_handler_alias(const char *name, size_t name_len TSRMLS_DC) { php_output_handler_alias_ctor_t *func = NULL; zend_hash_find(&php_output_handler_aliases, name, name_len+1, (void *) &func); return func; } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_handler_alias_register(zval *name, php_output_handler_alias_ctor_t func TSRMLS_DC) * Registers an internal output handler as alias for a user handler */ PHPAPI int php_output_handler_alias_register(const char *name, size_t name_len, php_output_handler_alias_ctor_t func TSRMLS_DC) { if (!EG(current_module)) { zend_error(E_ERROR, "Cannot register an output handler alias outside of MINIT"); return FAILURE; } return zend_hash_update(&php_output_handler_aliases, name, name_len+1, &func, sizeof(php_output_handler_alias_ctor_t *), NULL); } /* }}} */ /* {{{ SUCCESS|FAILURE php_output_handler_hook(php_output_handler_hook_t type, void *arg TSMRLS_DC) * Output handler hook for output handler functions to check/modify the current handlers abilities */ PHPAPI int php_output_handler_hook(php_output_handler_hook_t type, void *arg TSRMLS_DC) { if (OG(running)) { switch (type) { case PHP_OUTPUT_HANDLER_HOOK_GET_OPAQ: *(void ***) arg = &OG(running)->opaq; return SUCCESS; case PHP_OUTPUT_HANDLER_HOOK_GET_FLAGS: *(int *) arg = OG(running)->flags; return SUCCESS; case PHP_OUTPUT_HANDLER_HOOK_GET_LEVEL: *(int *) arg = OG(running)->level; return SUCCESS; case PHP_OUTPUT_HANDLER_HOOK_IMMUTABLE: OG(running)->flags &= ~(PHP_OUTPUT_HANDLER_REMOVABLE|PHP_OUTPUT_HANDLER_CLEANABLE); return SUCCESS; case PHP_OUTPUT_HANDLER_HOOK_DISABLE: OG(running)->flags |= PHP_OUTPUT_HANDLER_DISABLED; return SUCCESS; default: break; } } return FAILURE; } /* }}} */ /* {{{ void php_output_handler_dtor(php_output_handler *handler TSRMLS_DC) * Destroy an output handler */ PHPAPI void php_output_handler_dtor(php_output_handler *handler TSRMLS_DC) { STR_FREE(handler->name); STR_FREE(handler->buffer.data); if (handler->flags & PHP_OUTPUT_HANDLER_USER) { zval_ptr_dtor(&handler->func.user->zoh); efree(handler->func.user); } if (handler->dtor && handler->opaq) { handler->dtor(handler->opaq TSRMLS_CC); } memset(handler, 0, sizeof(*handler)); } /* }}} */ /* {{{ void php_output_handler_free(php_output_handler **handler TSMRLS_DC) * Destroy and free an output handler */ PHPAPI void php_output_handler_free(php_output_handler **h TSRMLS_DC) { if (*h) { php_output_handler_dtor(*h TSRMLS_CC); efree(*h); *h = NULL; } } /* }}} */ /* void php_output_set_implicit_flush(int enabled TSRMLS_DC) * Enable or disable implicit flush */ PHPAPI void php_output_set_implicit_flush(int flush TSRMLS_DC) { if (flush) { OG(flags) |= PHP_OUTPUT_IMPLICITFLUSH; } else { OG(flags) &= ~PHP_OUTPUT_IMPLICITFLUSH; } } /* }}} */ /* {{{ char *php_output_get_start_filename(TSRMLS_D) * Get the file name where output has started */ PHPAPI const char *php_output_get_start_filename(TSRMLS_D) { return OG(output_start_filename); } /* }}} */ /* {{{ int php_output_get_start_lineno(TSRMLS_D) * Get the line number where output has started */ PHPAPI int php_output_get_start_lineno(TSRMLS_D) { return OG(output_start_lineno); } /* }}} */ /* {{{ static int php_output_lock_error(int op TSRMLS_DC) * Checks whether an unallowed operation is attempted from within the output handler and issues a fatal error */ static inline int php_output_lock_error(int op TSRMLS_DC) { /* if there's no ob active, ob has been stopped */ if (op && OG(active) && OG(running)) { /* fatal error */ php_output_deactivate(TSRMLS_C); php_error_docref("ref.outcontrol" TSRMLS_CC, E_ERROR, "Cannot use output buffering in output buffering display handlers"); return 1; } return 0; } /* }}} */ /* {{{ static php_output_context *php_output_context_init(php_output_context *context, int op TSRMLS_DC) * Initialize a new output context */ static inline php_output_context *php_output_context_init(php_output_context *context, int op TSRMLS_DC) { if (!context) { context = emalloc(sizeof(php_output_context)); } memset(context, 0, sizeof(php_output_context)); TSRMLS_SET_CTX(context->tsrm_ls); context->op = op; return context; } /* }}} */ /* {{{ static void php_output_context_reset(php_output_context *context) * Reset an output context */ static inline void php_output_context_reset(php_output_context *context) { int op = context->op; php_output_context_dtor(context); memset(context, 0, sizeof(php_output_context)); context->op = op; } /* }}} */ /* {{{ static void php_output_context_feed(php_output_context *context, char *, size_t, size_t) * Feed output contexts input buffer */ static inline void php_output_context_feed(php_output_context *context, char *data, size_t size, size_t used, zend_bool free) { if (context->in.free && context->in.data) { efree(context->in.data); } context->in.data = data; context->in.used = used; context->in.free = free; context->in.size = size; } /* }}} */ /* {{{ static void php_output_context_swap(php_output_context *context) * Swap output contexts buffers */ static inline void php_output_context_swap(php_output_context *context) { if (context->in.free && context->in.data) { efree(context->in.data); } context->in.data = context->out.data; context->in.used = context->out.used; context->in.free = context->out.free; context->in.size = context->out.size; context->out.data = NULL; context->out.used = 0; context->out.free = 0; context->out.size = 0; } /* }}} */ /* {{{ static void php_output_context_pass(php_output_context *context) * Pass input to output buffer */ static inline void php_output_context_pass(php_output_context *context) { context->out.data = context->in.data; context->out.used = context->in.used; context->out.size = context->in.size; context->out.free = context->in.free; context->in.data = NULL; context->in.used = 0; context->in.free = 0; context->in.size = 0; } /* }}} */ /* {{{ static void php_output_context_dtor(php_output_context *context) * Destroy the contents of an output context */ static inline void php_output_context_dtor(php_output_context *context) { if (context->in.free && context->in.data) { efree(context->in.data); context->in.data = NULL; } if (context->out.free && context->out.data) { efree(context->out.data); context->out.data = NULL; } } /* }}} */ /* {{{ static php_output_handler *php_output_handler_init(zval *name, size_t chunk_size, int flags TSRMLS_DC) * Allocates and initializes a php_output_handler structure */ static inline php_output_handler *php_output_handler_init(const char *name, size_t name_len, size_t chunk_size, int flags TSRMLS_DC) { php_output_handler *handler; handler = ecalloc(1, sizeof(php_output_handler)); handler->name = estrndup(name, name_len); handler->name_len = name_len; handler->size = chunk_size; handler->flags = flags; handler->buffer.size = PHP_OUTPUT_HANDLER_INITBUF_SIZE(chunk_size); handler->buffer.data = emalloc(handler->buffer.size); return handler; } /* }}} */ /* {{{ static int php_output_handler_appen(php_output_handler *handler, const php_output_buffer *buf TSRMLS_DC) * Appends input to the output handlers buffer and indicates whether the buffer does not have to be processed by the output handler */ static inline int php_output_handler_append(php_output_handler *handler, const php_output_buffer *buf TSRMLS_DC) { if (buf->used) { OG(flags) |= PHP_OUTPUT_WRITTEN; /* store it away */ if ((handler->buffer.size - handler->buffer.used) <= buf->used) { size_t grow_int = PHP_OUTPUT_HANDLER_INITBUF_SIZE(handler->size); size_t grow_buf = PHP_OUTPUT_HANDLER_INITBUF_SIZE(buf->used - (handler->buffer.size - handler->buffer.used)); size_t grow_max = MAX(grow_int, grow_buf); handler->buffer.data = erealloc(handler->buffer.data, handler->buffer.size + grow_max); handler->buffer.size += grow_max; } memcpy(handler->buffer.data + handler->buffer.used, buf->data, buf->used); handler->buffer.used += buf->used; /* chunked buffering */ if (handler->size && (handler->buffer.used >= handler->size)) { /* store away errors and/or any intermediate output */ return OG(running) ? 1 : 0; } } return 1; } /* }}} */ /* {{{ static php_output_handler_status_t php_output_handler_op(php_output_handler *handler, php_output_context *context) * Output handler operation dispatcher, applying context op to the php_output_handler handler */ static inline php_output_handler_status_t php_output_handler_op(php_output_handler *handler, php_output_context *context) { php_output_handler_status_t status; int original_op = context->op; PHP_OUTPUT_TSRMLS(context); #if PHP_OUTPUT_DEBUG fprintf(stderr, ">>> op(%d, " "handler=%p, " "name=%s, " "flags=%d, " "buffer.data=%s, " "buffer.used=%zu, " "buffer.size=%zu, " "in.data=%s, " "in.used=%zu)\n", context->op, handler, handler->name, handler->flags, handler->buffer.used?handler->buffer.data:"", handler->buffer.used, handler->buffer.size, context->in.used?context->in.data:"", context->in.used ); #endif if (php_output_lock_error(context->op TSRMLS_CC)) { /* fatal error */ return PHP_OUTPUT_HANDLER_FAILURE; } /* storable? */ if (php_output_handler_append(handler, &context->in TSRMLS_CC) && !context->op) { context->op = original_op; return PHP_OUTPUT_HANDLER_NO_DATA; } else { /* need to start? */ if (!(handler->flags & PHP_OUTPUT_HANDLER_STARTED)) { context->op |= PHP_OUTPUT_HANDLER_START; } OG(running) = handler; if (handler->flags & PHP_OUTPUT_HANDLER_USER) { zval *retval = NULL, *ob_data, *ob_mode; MAKE_STD_ZVAL(ob_data); ZVAL_STRINGL(ob_data, handler->buffer.data, handler->buffer.used, 1); MAKE_STD_ZVAL(ob_mode); ZVAL_LONG(ob_mode, (long) context->op); zend_fcall_info_argn(&handler->func.user->fci TSRMLS_CC, 2, &ob_data, &ob_mode); #define PHP_OUTPUT_USER_SUCCESS(retval) (retval && !(Z_TYPE_P(retval) == IS_BOOL && Z_BVAL_P(retval)==0)) if (SUCCESS == zend_fcall_info_call(&handler->func.user->fci, &handler->func.user->fcc, &retval, NULL TSRMLS_CC) && PHP_OUTPUT_USER_SUCCESS(retval)) { /* user handler may have returned TRUE */ status = PHP_OUTPUT_HANDLER_NO_DATA; if (Z_TYPE_P(retval) != IS_BOOL) { convert_to_string_ex(&retval); if (Z_STRLEN_P(retval)) { context->out.data = estrndup(Z_STRVAL_P(retval), Z_STRLEN_P(retval)); context->out.used = Z_STRLEN_P(retval); context->out.free = 1; status = PHP_OUTPUT_HANDLER_SUCCESS; } } } else { /* call failed, pass internal buffer along */ status = PHP_OUTPUT_HANDLER_FAILURE; } zend_fcall_info_argn(&handler->func.user->fci TSRMLS_CC, 0); zval_ptr_dtor(&ob_data); zval_ptr_dtor(&ob_mode); if (retval) { zval_ptr_dtor(&retval); } } else { php_output_context_feed(context, handler->buffer.data, handler->buffer.size, handler->buffer.used, 0); if (SUCCESS == handler->func.internal(&handler->opaq, context)) { if (context->out.used) { status = PHP_OUTPUT_HANDLER_SUCCESS; } else { status = PHP_OUTPUT_HANDLER_NO_DATA; } } else { status = PHP_OUTPUT_HANDLER_FAILURE; } } handler->flags |= PHP_OUTPUT_HANDLER_STARTED; OG(running) = NULL; } switch (status) { case PHP_OUTPUT_HANDLER_FAILURE: /* disable this handler */ handler->flags |= PHP_OUTPUT_HANDLER_DISABLED; /* discard any output */ if (context->out.data && context->out.free) { efree(context->out.data); } /* returns handlers buffer */ context->out.data = handler->buffer.data; context->out.used = handler->buffer.used; context->out.free = 1; handler->buffer.data = NULL; handler->buffer.used = 0; handler->buffer.size = 0; break; case PHP_OUTPUT_HANDLER_NO_DATA: /* handler ate all */ php_output_context_reset(context); /* no break */ case PHP_OUTPUT_HANDLER_SUCCESS: /* no more buffered data */ handler->buffer.used = 0; break; } context->op = original_op; return status; } /* }}} */ /* {{{ static void php_output_op(int op, const char *str, size_t len TSRMLS_DC) * Output op dispatcher, passes input and output handlers output through the output handler stack until it gets written to the SAPI */ static inline void php_output_op(int op, const char *str, size_t len TSRMLS_DC) { php_output_context context; php_output_handler **active; int obh_cnt; if (php_output_lock_error(op TSRMLS_CC)) { return; } php_output_context_init(&context, op TSRMLS_CC); /* * broken up for better performance: * - apply op to the one active handler; note that OG(active) might be popped off the stack on a flush * - or apply op to the handler stack */ if (OG(active) && (obh_cnt = zend_stack_count(&OG(handlers)))) { context.in.data = (char *) str; context.in.used = len; if (obh_cnt > 1) { zend_stack_apply_with_argument(&OG(handlers), ZEND_STACK_APPLY_TOPDOWN, php_output_stack_apply_op, &context); } else if ((SUCCESS == zend_stack_top(&OG(handlers), (void *) &active)) && (!((*active)->flags & PHP_OUTPUT_HANDLER_DISABLED))) { php_output_handler_op(*active, &context); } else { php_output_context_pass(&context); } } else { context.out.data = (char *) str; context.out.used = len; } if (context.out.data && context.out.used) { #if PHP_OUTPUT_DEBUG fprintf(stderr, "::: sapi_write('%s', %zu)\n", context.out.data, context.out.used); #endif if (!SG(headers_sent) && php_header(TSRMLS_C)) { if (zend_is_compiling(TSRMLS_C)) { OG(output_start_filename) = zend_get_compiled_filename(TSRMLS_C); OG(output_start_lineno) = zend_get_compiled_lineno(TSRMLS_C); } else if (zend_is_executing(TSRMLS_C)) { OG(output_start_filename) = zend_get_executed_filename(TSRMLS_C); OG(output_start_lineno) = zend_get_executed_lineno(TSRMLS_C); } #if PHP_OUTPUT_DEBUG fprintf(stderr, "!!! output started at: %s (%d)\n", OG(output_start_filename), OG(output_start_lineno)); #endif } sapi_module.ub_write(context.out.data, context.out.used TSRMLS_CC); if (OG(flags) & PHP_OUTPUT_IMPLICITFLUSH) { sapi_flush(TSRMLS_C); } OG(flags) |= PHP_OUTPUT_SENT; } php_output_context_dtor(&context); } /* }}} */ /* {{{ static int php_output_stack_apply_op(void *h, void *c) * Operation callback for the stack apply function */ static int php_output_stack_apply_op(void *h, void *c) { int was_disabled; php_output_handler_status_t status; php_output_handler *handler = *(php_output_handler **) h; php_output_context *context = (php_output_context *) c; if ((was_disabled = (handler->flags & PHP_OUTPUT_HANDLER_DISABLED))) { status = PHP_OUTPUT_HANDLER_FAILURE; } else { status = php_output_handler_op(handler, context); } /* * handler ate all => break * handler returned data or failed resp. is disabled => continue */ switch (status) { case PHP_OUTPUT_HANDLER_NO_DATA: return 1; case PHP_OUTPUT_HANDLER_SUCCESS: /* swap contexts buffers, unless this is the last handler in the stack */ if (handler->level) { php_output_context_swap(context); } return 0; case PHP_OUTPUT_HANDLER_FAILURE: default: if (was_disabled) { /* pass input along, if it's the last handler in the stack */ if (!handler->level) { php_output_context_pass(context); } } else { /* swap buffers, unless this is the last handler */ if (handler->level) { php_output_context_swap(context); } } return 0; } } /* }}} */ /* {{{ static int php_output_stack_apply_clean(void *h, void *c) * Clean callback for the stack apply function */ static int php_output_stack_apply_clean(void *h, void *c) { php_output_handler *handler = *(php_output_handler **) h; php_output_context *context = (php_output_context *) c; handler->buffer.used = 0; php_output_handler_op(handler, context); php_output_context_reset(context); return 0; } /* }}} */ /* {{{ static int php_output_stack_apply_list(void *h, void *z) * List callback for the stack apply function */ static int php_output_stack_apply_list(void *h, void *z) { php_output_handler *handler = *(php_output_handler **) h; zval *array = (zval *) z; add_next_index_stringl(array, handler->name, handler->name_len, 1); return 0; } /* }}} */ /* {{{ static int php_output_stack_apply_status(void *h, void *z) * Status callback for the stack apply function */ static int php_output_stack_apply_status(void *h, void *z) { php_output_handler *handler = *(php_output_handler **) h; zval *array = (zval *) z; add_next_index_zval(array, php_output_handler_status(handler, NULL)); return 0; } /* {{{ static zval *php_output_handler_status(php_output_handler *handler, zval *entry) * Returns an array with the status of the output handler */ static inline zval *php_output_handler_status(php_output_handler *handler, zval *entry) { if (!entry) { MAKE_STD_ZVAL(entry); array_init(entry); } add_assoc_stringl(entry, "name", handler->name, handler->name_len, 1); add_assoc_long(entry, "type", (long) (handler->flags & 0xf)); add_assoc_long(entry, "flags", (long) handler->flags); add_assoc_long(entry, "level", (long) handler->level); add_assoc_long(entry, "chunk_size", (long) handler->size); add_assoc_long(entry, "buffer_size", (long) handler->buffer.size); add_assoc_long(entry, "buffer_used", (long) handler->buffer.used); return entry; } /* }}} */ /* {{{ static int php_output_stack_pop(int flags TSRMLS_DC) * Pops an output handler off the stack */ static inline int php_output_stack_pop(int flags TSRMLS_DC) { php_output_context context; php_output_handler **current, *orphan = OG(active); if (!orphan) { if (!(flags & PHP_OUTPUT_POP_SILENT)) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_NOTICE, "failed to %s buffer. No buffer to %s", (flags&PHP_OUTPUT_POP_DISCARD)?"discard":"send", (flags&PHP_OUTPUT_POP_DISCARD)?"discard":"send"); } return 0; } else if (!(flags & PHP_OUTPUT_POP_FORCE) && !(orphan->flags & PHP_OUTPUT_HANDLER_REMOVABLE)) { if (!(flags & PHP_OUTPUT_POP_SILENT)) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_NOTICE, "failed to %s buffer of %s (%d)", (flags&PHP_OUTPUT_POP_DISCARD)?"discard":"send", orphan->name, orphan->level); } return 0; } else { php_output_context_init(&context, PHP_OUTPUT_HANDLER_FINAL TSRMLS_CC); /* don't run the output handler if it's disabled */ if (!(orphan->flags & PHP_OUTPUT_HANDLER_DISABLED)) { /* didn't it start yet? */ if (!(orphan->flags & PHP_OUTPUT_HANDLER_STARTED)) { context.op |= PHP_OUTPUT_HANDLER_START; } /* signal that we're cleaning up */ if (flags & PHP_OUTPUT_POP_DISCARD) { context.op |= PHP_OUTPUT_HANDLER_CLEAN; orphan->buffer.used = 0; } php_output_handler_op(orphan, &context); } /* pop it off the stack */ zend_stack_del_top(&OG(handlers)); if (SUCCESS == zend_stack_top(&OG(handlers), (void *) &current)) { OG(active) = *current; } else { OG(active) = NULL; } /* pass output along */ if (context.out.data && context.out.used && !(flags & PHP_OUTPUT_POP_DISCARD)) { php_output_write(context.out.data, context.out.used TSRMLS_CC); } /* destroy the handler (after write!) */ php_output_handler_free(&orphan TSRMLS_CC); php_output_context_dtor(&context); return 1; } } /* }}} */ /* {{{ static SUCCESS|FAILURE php_output_handler_compat_func(void *ctx, php_output_context *) * php_output_handler_context_func_t for php_output_handler_func_t output handlers */ static int php_output_handler_compat_func(void **handler_context, php_output_context *output_context) { php_output_handler_func_t func = *(php_output_handler_func_t *) handler_context; PHP_OUTPUT_TSRMLS(output_context); if (func) { uint safe_out_len; func(output_context->in.data, output_context->in.used, &output_context->out.data, &safe_out_len, output_context->op TSRMLS_CC); output_context->out.used = safe_out_len; output_context->out.free = 1; return SUCCESS; } return FAILURE; } /* }}} */ /* {{{ static SUCCESS|FAILURE php_output_handler_default_func(void *ctx, php_output_context *) * Default output handler */ static int php_output_handler_default_func(void **handler_context, php_output_context *output_context) { php_output_context_pass(output_context); return SUCCESS; } /* }}} */ /* {{{ static SUCCESS|FAILURE php_output_handler_devnull_func(void *ctx, php_output_context *) * Null output handler */ static int php_output_handler_devnull_func(void **handler_context, php_output_context *output_context) { return SUCCESS; } /* }}} */ /* * USERLAND (nearly 1:1 of old output.c) */ /* {{{ proto bool ob_start([string|array user_function [, int chunk_size [, int flags]]]) Turn on Output Buffering (specifying an optional output handler). */ PHP_FUNCTION(ob_start) { zval *output_handler = NULL; long chunk_size = 0; long flags = PHP_OUTPUT_HANDLER_STDFLAGS; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z/ll", &output_handler, &chunk_size, &flags) == FAILURE) { return; } if (chunk_size < 0) { chunk_size = 0; } if (php_output_start_user(output_handler, chunk_size, flags TSRMLS_CC) == FAILURE) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_NOTICE, "failed to create buffer"); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool ob_flush(void) Flush (send) contents of the output buffer. The last buffer content is sent to next buffer */ PHP_FUNCTION(ob_flush) { if (zend_parse_parameters_none() == FAILURE) { return; } if (!OG(active)) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_NOTICE, "failed to flush buffer. No buffer to flush"); RETURN_FALSE; } if (SUCCESS != php_output_flush(TSRMLS_C)) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_NOTICE, "failed to flush buffer of %s (%d)", OG(active)->name, OG(active)->level); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool ob_clean(void) Clean (delete) the current output buffer */ PHP_FUNCTION(ob_clean) { if (zend_parse_parameters_none() == FAILURE) { return; } if (!OG(active)) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_NOTICE, "failed to delete buffer. No buffer to delete"); RETURN_FALSE; } if (SUCCESS != php_output_clean(TSRMLS_C)) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_NOTICE, "failed to delete buffer of %s (%d)", OG(active)->name, OG(active)->level); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool ob_end_flush(void) Flush (send) the output buffer, and delete current output buffer */ PHP_FUNCTION(ob_end_flush) { if (zend_parse_parameters_none() == FAILURE) { return; } if (!OG(active)) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_NOTICE, "failed to delete and flush buffer. No buffer to delete or flush"); RETURN_FALSE; } RETURN_BOOL(SUCCESS == php_output_end(TSRMLS_C)); } /* }}} */ /* {{{ proto bool ob_end_clean(void) Clean the output buffer, and delete current output buffer */ PHP_FUNCTION(ob_end_clean) { if (zend_parse_parameters_none() == FAILURE) { return; } if (!OG(active)) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_NOTICE, "failed to delete buffer. No buffer to delete"); RETURN_FALSE; } RETURN_BOOL(SUCCESS == php_output_discard(TSRMLS_C)); } /* }}} */ /* {{{ proto bool ob_get_flush(void) Get current buffer contents, flush (send) the output buffer, and delete current output buffer */ PHP_FUNCTION(ob_get_flush) { if (zend_parse_parameters_none() == FAILURE) { return; } if (php_output_get_contents(return_value TSRMLS_CC) == FAILURE) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_NOTICE, "failed to delete and flush buffer. No buffer to delete or flush"); RETURN_FALSE; } if (SUCCESS != php_output_end(TSRMLS_C)) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_NOTICE, "failed to delete buffer of %s (%d)", OG(active)->name, OG(active)->level); } } /* }}} */ /* {{{ proto bool ob_get_clean(void) Get current buffer contents and delete current output buffer */ PHP_FUNCTION(ob_get_clean) { if (zend_parse_parameters_none() == FAILURE) { return; } if(!OG(active)) { RETURN_FALSE; } if (php_output_get_contents(return_value TSRMLS_CC) == FAILURE) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_NOTICE, "failed to delete buffer. No buffer to delete"); RETURN_FALSE; } if (SUCCESS != php_output_discard(TSRMLS_C)) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_NOTICE, "failed to delete buffer of %s (%d)", OG(active)->name, OG(active)->level); } } /* }}} */ /* {{{ proto string ob_get_contents(void) Return the contents of the output buffer */ PHP_FUNCTION(ob_get_contents) { if (zend_parse_parameters_none() == FAILURE) { return; } if (php_output_get_contents(return_value TSRMLS_CC) == FAILURE) { RETURN_FALSE; } } /* }}} */ /* {{{ proto int ob_get_level(void) Return the nesting level of the output buffer */ PHP_FUNCTION(ob_get_level) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(php_output_get_level(TSRMLS_C)); } /* }}} */ /* {{{ proto int ob_get_length(void) Return the length of the output buffer */ PHP_FUNCTION(ob_get_length) { if (zend_parse_parameters_none() == FAILURE) { return; } if (php_output_get_length(return_value TSRMLS_CC) == FAILURE) { RETURN_FALSE; } } /* }}} */ /* {{{ proto false|array ob_list_handlers() List all output_buffers in an array */ PHP_FUNCTION(ob_list_handlers) { if (zend_parse_parameters_none() == FAILURE) { return; } array_init(return_value); if (!OG(active)) { return; } zend_stack_apply_with_argument(&OG(handlers), ZEND_STACK_APPLY_BOTTOMUP, php_output_stack_apply_list, return_value); } /* }}} */ /* {{{ proto false|array ob_get_status([bool full_status]) Return the status of the active or all output buffers */ PHP_FUNCTION(ob_get_status) { zend_bool full_status = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &full_status) == FAILURE) { return; } array_init(return_value); if (!OG(active)) { return; } if (full_status) { zend_stack_apply_with_argument(&OG(handlers), ZEND_STACK_APPLY_BOTTOMUP, php_output_stack_apply_status, return_value); } else { php_output_handler_status(OG(active), return_value); } } /* }}} */ /* {{{ proto void ob_implicit_flush([int flag]) Turn implicit flush on/off and is equivalent to calling flush() after every output call */ PHP_FUNCTION(ob_implicit_flush) { long flag = 1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &flag) == FAILURE) { return; } php_output_set_implicit_flush(flag TSRMLS_CC); } /* }}} */ /* {{{ proto bool output_reset_rewrite_vars(void) Reset(clear) URL rewriter values */ PHP_FUNCTION(output_reset_rewrite_vars) { if (php_url_scanner_reset_vars(TSRMLS_C) == SUCCESS) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool output_add_rewrite_var(string name, string value) Add URL rewriter values */ PHP_FUNCTION(output_add_rewrite_var) { char *name, *value; int name_len, value_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &name, &name_len, &value, &value_len) == FAILURE) { return; } if (php_url_scanner_add_var(name, name_len, value, value_len, 1 TSRMLS_CC) == SUCCESS) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2012-01-16-36df53421e-f32760bd40.c
manybugs_data_42
/* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library. * Scanline-oriented Read Support */ #include "tiffiop.h" #include <stdio.h> int TIFFFillStrip(TIFF* tif, uint32 strip); int TIFFFillTile(TIFF* tif, uint32 tile); static int TIFFStartStrip(TIFF* tif, uint32 strip); static int TIFFStartTile(TIFF* tif, uint32 tile); static int TIFFCheckRead(TIFF*, int); #define NOSTRIP ((uint32)(-1)) /* undefined state */ #define NOTILE ((uint32)(-1)) /* undefined state */ /* * Seek to a random row+sample in a file. */ static int TIFFSeek(TIFF* tif, uint32 row, uint16 sample) { register TIFFDirectory *td = &tif->tif_dir; uint32 strip; if (row >= td->td_imagelength) { /* out of range */ TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "%lu: Row out of range, max %lu", (unsigned long) row, (unsigned long) td->td_imagelength); return (0); } if (td->td_planarconfig == PLANARCONFIG_SEPARATE) { if (sample >= td->td_samplesperpixel) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "%lu: Sample out of range, max %lu", (unsigned long) sample, (unsigned long) td->td_samplesperpixel); return (0); } strip = (uint32)sample*td->td_stripsperimage + row/td->td_rowsperstrip; } else strip = row / td->td_rowsperstrip; if (strip != tif->tif_curstrip) { /* different strip, refill */ if (!TIFFFillStrip(tif, strip)) return (0); } else if (row < tif->tif_row) { /* * Moving backwards within the same strip: backup * to the start and then decode forward (below). * * NB: If you're planning on lots of random access within a * strip, it's better to just read and decode the entire * strip, and then access the decoded data in a random fashion. */ if (!TIFFStartStrip(tif, strip)) return (0); } if (row != tif->tif_row) { /* * Seek forward to the desired row. */ if (!(*tif->tif_seek)(tif, row - tif->tif_row)) return (0); tif->tif_row = row; } return (1); } int TIFFReadScanline(TIFF* tif, void* buf, uint32 row, uint16 sample) { int e; if (!TIFFCheckRead(tif, 0)) return (-1); if( (e = TIFFSeek(tif, row, sample)) != 0) { /* * Decompress desired row into user buffer. */ e = (*tif->tif_decoderow) (tif, (uint8*) buf, tif->tif_scanlinesize, sample); /* we are now poised at the beginning of the next row */ tif->tif_row = row + 1; if (e) (*tif->tif_postdecode)(tif, (uint8*) buf, tif->tif_scanlinesize); } return (e > 0 ? 1 : -1); } /* * Read a strip of data and decompress the specified * amount into the user-supplied buffer. */ tmsize_t TIFFReadEncodedStrip(TIFF* tif, uint32 strip, void* buf, tmsize_t size) { static const char module[] = "TIFFReadEncodedStrip"; TIFFDirectory *td = &tif->tif_dir; uint32 rowsperstrip; uint32 stripsperplane; uint32 stripinplane; uint16 plane; uint32 rows; tmsize_t stripsize; if (!TIFFCheckRead(tif,0)) return((tmsize_t)(-1)); if (strip>=td->td_nstrips) { TIFFErrorExt(tif->tif_clientdata,module, "%uld: Strip out of range, max %uld",(unsigned long)strip, (unsigned long)td->td_nstrips); return((tmsize_t)(-1)); } /* * Calculate the strip size according to the number of * rows in the strip (check for truncated last strip on any * of the separations). */ rowsperstrip=td->td_rowsperstrip; if (rowsperstrip>td->td_imagelength) rowsperstrip=td->td_imagelength; stripsperplane=((td->td_imagelength+rowsperstrip-1)/rowsperstrip); stripinplane=(strip%stripsperplane); plane=(strip/stripsperplane); rows=td->td_imagelength-stripinplane*rowsperstrip; if (rows>rowsperstrip) rows=rowsperstrip; stripsize=TIFFVStripSize(tif,rows); if (stripsize==0) return((tmsize_t)(-1)); if ((size!=(tmsize_t)(-1))&&(size<stripsize)) stripsize=size; if (!TIFFFillStrip(tif,strip)) return((tmsize_t)(-1)); if ((*tif->tif_decodestrip)(tif,buf,size,plane)<=0) return((tmsize_t)(-1)); (*tif->tif_postdecode)(tif,buf,size); return(size); } static tmsize_t TIFFReadRawStrip1(TIFF* tif, uint32 strip, void* buf, tmsize_t size, const char* module) { TIFFDirectory *td = &tif->tif_dir; assert((tif->tif_flags&TIFF_NOREADRAW)==0); if (!isMapped(tif)) { tmsize_t cc; if (!SeekOK(tif, td->td_stripoffset[strip])) { TIFFErrorExt(tif->tif_clientdata, module, "Seek error at scanline %lu, strip %lu", (unsigned long) tif->tif_row, (unsigned long) strip); return ((tmsize_t)(-1)); } cc = TIFFReadFile(tif, buf, size); if (cc != size) { TIFFErrorExt(tif->tif_clientdata, module, "Read error at scanline %lu; got %llu bytes, expected %llu", tif->tif_name, (unsigned long) tif->tif_row, (unsigned long long) cc, (unsigned long long) size); return ((tmsize_t)(-1)); } } else { tmsize_t ma,mb; tmsize_t n; ma=(tmsize_t)td->td_stripoffset[strip]; mb=ma+size; if (((uint64)ma!=td->td_stripoffset[strip])||(ma>tif->tif_size)) n=0; else if ((mb<ma)||(mb<size)||(mb>tif->tif_size)) n=tif->tif_size-ma; else n=size; if (n!=size) { TIFFErrorExt(tif->tif_clientdata, module, "Read error at scanline %lu, strip %lu; got %llu bytes, expected %llu", (unsigned long) tif->tif_row, (unsigned long) strip, (unsigned long long) n, (unsigned long long) size); return ((tmsize_t)(-1)); } _TIFFmemcpy(buf, tif->tif_base + ma, size); } return (size); } /* * Read a strip of data from the file. */ tmsize_t TIFFReadRawStrip(TIFF* tif, uint32 strip, void* buf, tmsize_t size) { static const char module[] = "TIFFReadRawStrip"; TIFFDirectory *td = &tif->tif_dir; uint64 bytecount; tmsize_t bytecountm; if (!TIFFCheckRead(tif, 0)) return ((tmsize_t)(-1)); if (strip >= td->td_nstrips) { TIFFErrorExt(tif->tif_clientdata, module, "%lu: Strip out of range, max %lu", (unsigned long) strip, (unsigned long) td->td_nstrips); return ((tmsize_t)(-1)); } if (tif->tif_flags&TIFF_NOREADRAW) { TIFFErrorExt(tif->tif_clientdata, module, "Compression scheme does not support access to raw uncompressed data"); return ((tmsize_t)(-1)); } bytecount = td->td_stripbytecount[strip]; if (bytecount <= 0) { TIFFErrorExt(tif->tif_clientdata, module, "%llu: Invalid strip byte count, strip %lu", (unsigned long long) bytecount, (unsigned long) strip); return ((tmsize_t)(-1)); } bytecountm = (tmsize_t)bytecount; if ((uint64)bytecountm!=bytecount) { TIFFErrorExt(tif->tif_clientdata, module, "Integer overflow"); return ((tmsize_t)(-1)); } if (size != (tmsize_t)(-1) && size < bytecountm) bytecountm = size; return (TIFFReadRawStrip1(tif, strip, buf, bytecountm, module)); } /* * Read the specified strip and setup for decoding. The data buffer is * expanded, as necessary, to hold the strip's data. */ int TIFFFillStrip(TIFF* tif, uint32 strip) { static const char module[] = "TIFFFillStrip"; TIFFDirectory *td = &tif->tif_dir; if ((tif->tif_flags&TIFF_NOREADRAW)==0) { uint64 bytecount = td->td_stripbytecount[strip]; if (bytecount <= 0) { TIFFErrorExt(tif->tif_clientdata, module, "Invalid strip byte count %llu, strip %lu", (unsigned long) bytecount, (unsigned long) strip); return (0); } if (isMapped(tif) && (isFillOrder(tif, td->td_fillorder) || (tif->tif_flags & TIFF_NOBITREV))) { /* * The image is mapped into memory and we either don't * need to flip bits or the compression routine is * going to handle this operation itself. In this * case, avoid copying the raw data and instead just * reference the data from the memory mapped file * image. This assumes that the decompression * routines do not modify the contents of the raw data * buffer (if they try to, the application will get a * fault since the file is mapped read-only). */ if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata) _TIFFfree(tif->tif_rawdata); tif->tif_flags &= ~TIFF_MYBUFFER; /* * We must check for overflow, potentially causing * an OOB read. Instead of simple * * td->td_stripoffset[strip]+bytecount > tif->tif_size * * comparison (which can overflow) we do the following * two comparisons: */ if (bytecount > (uint64)tif->tif_size || td->td_stripoffset[strip] > (uint64)tif->tif_size - bytecount) { /* * This error message might seem strange, but * it's what would happen if a read were done * instead. */ TIFFErrorExt(tif->tif_clientdata, module, "Read error on strip %lu; " "got %llu bytes, expected %llu", (unsigned long) strip, (unsigned long long) tif->tif_size - td->td_stripoffset[strip], (unsigned long long) bytecount); tif->tif_curstrip = NOSTRIP; return (0); } tif->tif_rawdatasize = (tmsize_t)bytecount; tif->tif_rawdata = tif->tif_base + (tmsize_t)td->td_stripoffset[strip]; } else { /* * Expand raw data buffer, if needed, to hold data * strip coming from file (perhaps should set upper * bound on the size of a buffer we'll use?). */ tmsize_t bytecountm; bytecountm=(tmsize_t)bytecount; if ((uint64)bytecountm!=bytecount) { TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow"); return(0); } if (bytecountm > tif->tif_rawdatasize) { tif->tif_curstrip = NOSTRIP; if ((tif->tif_flags & TIFF_MYBUFFER) == 0) { TIFFErrorExt(tif->tif_clientdata, module, "Data buffer too small to hold strip %lu", (unsigned long) strip); return (0); } if (!TIFFReadBufferSetup(tif, 0, bytecountm)) return (0); } if (TIFFReadRawStrip1(tif, strip, tif->tif_rawdata, bytecountm, module) != bytecountm) return (0); if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits(tif->tif_rawdata, bytecountm); } } return (TIFFStartStrip(tif, strip)); } /* * Tile-oriented Read Support * Contributed by Nancy Cam (Silicon Graphics). */ /* * Read and decompress a tile of data. The * tile is selected by the (x,y,z,s) coordinates. */ tmsize_t TIFFReadTile(TIFF* tif, void* buf, uint32 x, uint32 y, uint32 z, uint16 s) { if (!TIFFCheckRead(tif, 1) || !TIFFCheckTile(tif, x, y, z, s)) return ((tmsize_t)(-1)); return (TIFFReadEncodedTile(tif, TIFFComputeTile(tif, x, y, z, s), buf, (tmsize_t)(-1))); } /* * Read a tile of data and decompress the specified * amount into the user-supplied buffer. */ tmsize_t TIFFReadEncodedTile(TIFF* tif, uint32 tile, void* buf, tmsize_t size) { static const char module[] = "TIFFReadEncodedTile"; TIFFDirectory *td = &tif->tif_dir; tmsize_t tilesize = tif->tif_tilesize; if (!TIFFCheckRead(tif, 1)) return ((tmsize_t)(-1)); if (tile >= td->td_nstrips) { TIFFErrorExt(tif->tif_clientdata, module, "%lud: Tile out of range, max %lud", (unsigned long) tile, (unsigned long) td->td_nstrips); return ((tmsize_t)(-1)); } if (size == (tmsize_t)(-1)) size = tilesize; else if (size > tilesize) size = tilesize; if (TIFFFillTile(tif, tile) && (*tif->tif_decodetile)(tif, (uint8*) buf, size, (uint16)(tile/td->td_stripsperimage))) { (*tif->tif_postdecode)(tif, (uint8*) buf, size); return (size); } else return ((tmsize_t)(-1)); } static tmsize_t TIFFReadRawTile1(TIFF* tif, uint32 tile, void* buf, tmsize_t size, const char* module) { TIFFDirectory *td = &tif->tif_dir; assert((tif->tif_flags&TIFF_NOREADRAW)==0); if (!isMapped(tif)) { tmsize_t cc; if (!SeekOK(tif, td->td_stripoffset[tile])) { TIFFErrorExt(tif->tif_clientdata, module, "Seek error at row %lud, col %lud, tile %lud", (unsigned long) tif->tif_row, (unsigned long) tif->tif_col, (unsigned long) tile); return ((tmsize_t)(-1)); } cc = TIFFReadFile(tif, buf, size); if (cc != size) { TIFFErrorExt(tif->tif_clientdata, module, "Read error at row %lud, col %lud; got %llu bytes, expected %llu", (unsigned long) tif->tif_row, (unsigned long) tif->tif_col, (unsigned long long) cc, (unsigned long long) size); return ((tmsize_t)(-1)); } } else { tmsize_t ma,mb; tmsize_t n; ma=(tmsize_t)td->td_stripoffset[tile]; mb=ma+size; if (((uint64)ma!=td->td_stripoffset[tile])||(ma>tif->tif_size)) n=0; else if ((mb<ma)||(mb<size)||(mb>tif->tif_size)) n=tif->tif_size-ma; else n=size; if (n!=size) { TIFFErrorExt(tif->tif_clientdata, module, "Read error at row %lud, col %lud, tile %lud; got %llu bytes, expected %llu", (unsigned long) tif->tif_row, (unsigned long) tif->tif_col, (unsigned long) tile, (unsigned long long) n, (unsigned long long) size); return ((tmsize_t)(-1)); } _TIFFmemcpy(buf, tif->tif_base + ma, size); } return (size); } /* * Read a tile of data from the file. */ tmsize_t TIFFReadRawTile(TIFF* tif, uint32 tile, void* buf, tmsize_t size) { static const char module[] = "TIFFReadRawTile"; TIFFDirectory *td = &tif->tif_dir; uint64 bytecount64; tmsize_t bytecountm; if (!TIFFCheckRead(tif, 1)) return ((tmsize_t)(-1)); if (tile >= td->td_nstrips) { TIFFErrorExt(tif->tif_clientdata, module, "%lu: Tile out of range, max %lu", (unsigned long) tile, (unsigned long) td->td_nstrips); return ((tmsize_t)(-1)); } if (tif->tif_flags&TIFF_NOREADRAW) { TIFFErrorExt(tif->tif_clientdata, module, "Compression scheme does not support access to raw uncompressed data"); return ((tmsize_t)(-1)); } bytecount64 = td->td_stripbytecount[tile]; if (size != (tmsize_t)(-1) && (uint64)size < bytecount64) bytecount64 = (uint64)size; bytecountm = (tmsize_t)bytecount64; if ((uint64)bytecountm!=bytecount64) { TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow"); return ((tmsize_t)(-1)); } return (TIFFReadRawTile1(tif, tile, buf, bytecountm, module)); } /* * Read the specified tile and setup for decoding. The data buffer is * expanded, as necessary, to hold the tile's data. */ int TIFFFillTile(TIFF* tif, uint32 tile) { static const char module[] = "TIFFFillTile"; TIFFDirectory *td = &tif->tif_dir; if ((tif->tif_flags&TIFF_NOREADRAW)==0) { uint64 bytecount = td->td_stripbytecount[tile]; if (bytecount <= 0) { TIFFErrorExt(tif->tif_clientdata, module, "%llu: Invalid tile byte count, tile %lu", (unsigned long long) bytecount, (unsigned long) tile); return (0); } if (isMapped(tif) && (isFillOrder(tif, td->td_fillorder) || (tif->tif_flags & TIFF_NOBITREV))) { /* * The image is mapped into memory and we either don't * need to flip bits or the compression routine is * going to handle this operation itself. In this * case, avoid copying the raw data and instead just * reference the data from the memory mapped file * image. This assumes that the decompression * routines do not modify the contents of the raw data * buffer (if they try to, the application will get a * fault since the file is mapped read-only). */ if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata) _TIFFfree(tif->tif_rawdata); tif->tif_flags &= ~TIFF_MYBUFFER; /* * We must check for overflow, potentially causing * an OOB read. Instead of simple * * td->td_stripoffset[tile]+bytecount > tif->tif_size * * comparison (which can overflow) we do the following * two comparisons: */ if (bytecount > (uint64)tif->tif_size || td->td_stripoffset[tile] > (uint64)tif->tif_size - bytecount) { tif->tif_curtile = NOTILE; return (0); } tif->tif_rawdatasize = (tmsize_t)bytecount; tif->tif_rawdata = tif->tif_base + (tmsize_t)td->td_stripoffset[tile]; } else { /* * Expand raw data buffer, if needed, to hold data * tile coming from file (perhaps should set upper * bound on the size of a buffer we'll use?). */ tmsize_t bytecountm; bytecountm=(tmsize_t)bytecount; if ((uint64)bytecountm!=bytecount) { TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow"); return(0); } if (bytecountm > tif->tif_rawdatasize) { tif->tif_curtile = NOTILE; if ((tif->tif_flags & TIFF_MYBUFFER) == 0) { TIFFErrorExt(tif->tif_clientdata, module, "Data buffer too small to hold tile %lud", (unsigned long) tile); return (0); } if (!TIFFReadBufferSetup(tif, 0, bytecountm)) return (0); } if (TIFFReadRawTile1(tif, tile, tif->tif_rawdata, bytecountm, module) != bytecountm) return (0); if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits(tif->tif_rawdata, bytecountm); } } return (TIFFStartTile(tif, tile)); } /* * Setup the raw data buffer in preparation for * reading a strip of raw data. If the buffer * is specified as zero, then a buffer of appropriate * size is allocated by the library. Otherwise, * the client must guarantee that the buffer is * large enough to hold any individual strip of * raw data. */ int TIFFReadBufferSetup(TIFF* tif, void* bp, tmsize_t size) { static const char module[] = "TIFFReadBufferSetup"; assert((tif->tif_flags&TIFF_NOREADRAW)==0); if (tif->tif_rawdata) { if (tif->tif_flags & TIFF_MYBUFFER) _TIFFfree(tif->tif_rawdata); tif->tif_rawdata = NULL; } if (bp) { tif->tif_rawdatasize = size; tif->tif_rawdata = (uint8*) bp; tif->tif_flags &= ~TIFF_MYBUFFER; } else { tif->tif_rawdatasize = (tmsize_t)TIFFroundup_64((uint64)size, 1024); if (tif->tif_rawdatasize==0) tif->tif_rawdatasize=(tmsize_t)(-1); tif->tif_rawdata = (uint8*) _TIFFmalloc(tif->tif_rawdatasize); tif->tif_flags |= TIFF_MYBUFFER; } if (tif->tif_rawdata == NULL) { TIFFErrorExt(tif->tif_clientdata, module, "No space for data buffer at scanline %lud", (unsigned long) tif->tif_row); tif->tif_rawdatasize = 0; return (0); } return (1); } /* * Set state to appear as if a * strip has just been read in. */ static int TIFFStartStrip(TIFF* tif, uint32 strip) { TIFFDirectory *td = &tif->tif_dir; if ((tif->tif_flags & TIFF_CODERSETUP) == 0) { if (!(*tif->tif_setupdecode)(tif)) return (0); tif->tif_flags |= TIFF_CODERSETUP; } tif->tif_curstrip = strip; tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip; if (tif->tif_flags&TIFF_NOREADRAW) { tif->tif_rawcp = NULL; tif->tif_rawcc = 0; } else { tif->tif_rawcp = tif->tif_rawdata; tif->tif_rawcc = (tmsize_t)td->td_stripbytecount[strip]; } return ((*tif->tif_predecode)(tif, (uint16)(strip / td->td_stripsperimage))); } /* * Set state to appear as if a * tile has just been read in. */ static int TIFFStartTile(TIFF* tif, uint32 tile) { TIFFDirectory *td = &tif->tif_dir; if ((tif->tif_flags & TIFF_CODERSETUP) == 0) { if (!(*tif->tif_setupdecode)(tif)) return (0); tif->tif_flags |= TIFF_CODERSETUP; } tif->tif_curtile = tile; tif->tif_row = (tile % TIFFhowmany_32(td->td_imagewidth, td->td_tilewidth)) * td->td_tilelength; tif->tif_col = (tile % TIFFhowmany_32(td->td_imagelength, td->td_tilelength)) * td->td_tilewidth; if (tif->tif_flags&TIFF_NOREADRAW) { tif->tif_rawcp = NULL; tif->tif_rawcc = 0; } else { tif->tif_rawcp = tif->tif_rawdata; tif->tif_rawcc = (tmsize_t)td->td_stripbytecount[tile]; } return ((*tif->tif_predecode)(tif, (uint16)(tile/td->td_stripsperimage))); } static int TIFFCheckRead(TIFF* tif, int tiles) { if (tif->tif_mode == O_WRONLY) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "File not open for reading"); return (0); } if (tiles ^ isTiled(tif)) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, tiles ? "Can not read tiles from a stripped image" : "Can not read scanlines from a tiled image"); return (0); } return (1); } void _TIFFNoPostDecode(TIFF* tif, uint8* buf, tmsize_t cc) { (void) tif; (void) buf; (void) cc; } void _TIFFSwab16BitData(TIFF* tif, uint8* buf, tmsize_t cc) { (void) tif; assert((cc & 1) == 0); TIFFSwabArrayOfShort((uint16*) buf, cc/2); } void _TIFFSwab24BitData(TIFF* tif, uint8* buf, tmsize_t cc) { (void) tif; assert((cc % 3) == 0); TIFFSwabArrayOfTriples((uint8*) buf, cc/3); } void _TIFFSwab32BitData(TIFF* tif, uint8* buf, tmsize_t cc) { (void) tif; assert((cc & 3) == 0); TIFFSwabArrayOfLong((uint32*) buf, cc/4); } void _TIFFSwab64BitData(TIFF* tif, uint8* buf, tmsize_t cc) { (void) tif; assert((cc & 7) == 0); TIFFSwabArrayOfDouble((double*) buf, cc/8); } /* vim: set ts=8 sts=8 sw=8 noet: */ /* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library. * Scanline-oriented Read Support */ #include "tiffiop.h" #include <stdio.h> int TIFFFillStrip(TIFF* tif, uint32 strip); int TIFFFillTile(TIFF* tif, uint32 tile); static int TIFFStartStrip(TIFF* tif, uint32 strip); static int TIFFStartTile(TIFF* tif, uint32 tile); static int TIFFCheckRead(TIFF*, int); #define NOSTRIP ((uint32)(-1)) /* undefined state */ #define NOTILE ((uint32)(-1)) /* undefined state */ /* * Seek to a random row+sample in a file. */ static int TIFFSeek(TIFF* tif, uint32 row, uint16 sample) { register TIFFDirectory *td = &tif->tif_dir; uint32 strip; if (row >= td->td_imagelength) { /* out of range */ TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "%lu: Row out of range, max %lu", (unsigned long) row, (unsigned long) td->td_imagelength); return (0); } if (td->td_planarconfig == PLANARCONFIG_SEPARATE) { if (sample >= td->td_samplesperpixel) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "%lu: Sample out of range, max %lu", (unsigned long) sample, (unsigned long) td->td_samplesperpixel); return (0); } strip = (uint32)sample*td->td_stripsperimage + row/td->td_rowsperstrip; } else strip = row / td->td_rowsperstrip; if (strip != tif->tif_curstrip) { /* different strip, refill */ if (!TIFFFillStrip(tif, strip)) return (0); } else if (row < tif->tif_row) { /* * Moving backwards within the same strip: backup * to the start and then decode forward (below). * * NB: If you're planning on lots of random access within a * strip, it's better to just read and decode the entire * strip, and then access the decoded data in a random fashion. */ if (!TIFFStartStrip(tif, strip)) return (0); } if (row != tif->tif_row) { /* * Seek forward to the desired row. */ if (!(*tif->tif_seek)(tif, row - tif->tif_row)) return (0); tif->tif_row = row; } return (1); } int TIFFReadScanline(TIFF* tif, void* buf, uint32 row, uint16 sample) { int e; if (!TIFFCheckRead(tif, 0)) return (-1); if( (e = TIFFSeek(tif, row, sample)) != 0) { /* * Decompress desired row into user buffer. */ e = (*tif->tif_decoderow) (tif, (uint8*) buf, tif->tif_scanlinesize, sample); /* we are now poised at the beginning of the next row */ tif->tif_row = row + 1; if (e) (*tif->tif_postdecode)(tif, (uint8*) buf, tif->tif_scanlinesize); } return (e > 0 ? 1 : -1); } /* * Read a strip of data and decompress the specified * amount into the user-supplied buffer. */ tmsize_t TIFFReadEncodedStrip(TIFF* tif, uint32 strip, void* buf, tmsize_t size) { static const char module[] = "TIFFReadEncodedStrip"; TIFFDirectory *td = &tif->tif_dir; uint32 rowsperstrip; uint32 stripsperplane; uint32 stripinplane; uint16 plane; uint32 rows; tmsize_t stripsize; if (!TIFFCheckRead(tif,0)) return((tmsize_t)(-1)); if (strip>=td->td_nstrips) { TIFFErrorExt(tif->tif_clientdata,module, "%uld: Strip out of range, max %uld",(unsigned long)strip, (unsigned long)td->td_nstrips); return((tmsize_t)(-1)); } /* * Calculate the strip size according to the number of * rows in the strip (check for truncated last strip on any * of the separations). */ rowsperstrip=td->td_rowsperstrip; if (rowsperstrip>td->td_imagelength) rowsperstrip=td->td_imagelength; stripsperplane=((td->td_imagelength+rowsperstrip-1)/rowsperstrip); stripinplane=(strip%stripsperplane); plane=(strip/stripsperplane); rows=td->td_imagelength-stripinplane*rowsperstrip; if (rows>rowsperstrip) rows=rowsperstrip; stripsize=TIFFVStripSize(tif,rows); if (stripsize==0) return((tmsize_t)(-1)); if ((size!=(tmsize_t)(-1))&&(size<stripsize)) stripsize=size; if (!TIFFFillStrip(tif,strip)) return((tmsize_t)(-1)); if ((*tif->tif_decodestrip)(tif,buf,stripsize,plane)<=0) return((tmsize_t)(-1)); (*tif->tif_postdecode)(tif,buf,stripsize); return(stripsize); } static tmsize_t TIFFReadRawStrip1(TIFF* tif, uint32 strip, void* buf, tmsize_t size, const char* module) { TIFFDirectory *td = &tif->tif_dir; assert((tif->tif_flags&TIFF_NOREADRAW)==0); if (!isMapped(tif)) { tmsize_t cc; if (!SeekOK(tif, td->td_stripoffset[strip])) { TIFFErrorExt(tif->tif_clientdata, module, "Seek error at scanline %lu, strip %lu", (unsigned long) tif->tif_row, (unsigned long) strip); return ((tmsize_t)(-1)); } cc = TIFFReadFile(tif, buf, size); if (cc != size) { TIFFErrorExt(tif->tif_clientdata, module, "Read error at scanline %lu; got %llu bytes, expected %llu", tif->tif_name, (unsigned long) tif->tif_row, (unsigned long long) cc, (unsigned long long) size); return ((tmsize_t)(-1)); } } else { tmsize_t ma,mb; tmsize_t n; ma=(tmsize_t)td->td_stripoffset[strip]; mb=ma+size; if (((uint64)ma!=td->td_stripoffset[strip])||(ma>tif->tif_size)) n=0; else if ((mb<ma)||(mb<size)||(mb>tif->tif_size)) n=tif->tif_size-ma; else n=size; if (n!=size) { TIFFErrorExt(tif->tif_clientdata, module, "Read error at scanline %lu, strip %lu; got %llu bytes, expected %llu", (unsigned long) tif->tif_row, (unsigned long) strip, (unsigned long long) n, (unsigned long long) size); return ((tmsize_t)(-1)); } _TIFFmemcpy(buf, tif->tif_base + ma, size); } return (size); } /* * Read a strip of data from the file. */ tmsize_t TIFFReadRawStrip(TIFF* tif, uint32 strip, void* buf, tmsize_t size) { static const char module[] = "TIFFReadRawStrip"; TIFFDirectory *td = &tif->tif_dir; uint64 bytecount; tmsize_t bytecountm; if (!TIFFCheckRead(tif, 0)) return ((tmsize_t)(-1)); if (strip >= td->td_nstrips) { TIFFErrorExt(tif->tif_clientdata, module, "%lu: Strip out of range, max %lu", (unsigned long) strip, (unsigned long) td->td_nstrips); return ((tmsize_t)(-1)); } if (tif->tif_flags&TIFF_NOREADRAW) { TIFFErrorExt(tif->tif_clientdata, module, "Compression scheme does not support access to raw uncompressed data"); return ((tmsize_t)(-1)); } bytecount = td->td_stripbytecount[strip]; if (bytecount <= 0) { TIFFErrorExt(tif->tif_clientdata, module, "%llu: Invalid strip byte count, strip %lu", (unsigned long long) bytecount, (unsigned long) strip); return ((tmsize_t)(-1)); } bytecountm = (tmsize_t)bytecount; if ((uint64)bytecountm!=bytecount) { TIFFErrorExt(tif->tif_clientdata, module, "Integer overflow"); return ((tmsize_t)(-1)); } if (size != (tmsize_t)(-1) && size < bytecountm) bytecountm = size; return (TIFFReadRawStrip1(tif, strip, buf, bytecountm, module)); } /* * Read the specified strip and setup for decoding. The data buffer is * expanded, as necessary, to hold the strip's data. */ int TIFFFillStrip(TIFF* tif, uint32 strip) { static const char module[] = "TIFFFillStrip"; TIFFDirectory *td = &tif->tif_dir; if ((tif->tif_flags&TIFF_NOREADRAW)==0) { uint64 bytecount = td->td_stripbytecount[strip]; if (bytecount <= 0) { TIFFErrorExt(tif->tif_clientdata, module, "Invalid strip byte count %llu, strip %lu", (unsigned long) bytecount, (unsigned long) strip); return (0); } if (isMapped(tif) && (isFillOrder(tif, td->td_fillorder) || (tif->tif_flags & TIFF_NOBITREV))) { /* * The image is mapped into memory and we either don't * need to flip bits or the compression routine is * going to handle this operation itself. In this * case, avoid copying the raw data and instead just * reference the data from the memory mapped file * image. This assumes that the decompression * routines do not modify the contents of the raw data * buffer (if they try to, the application will get a * fault since the file is mapped read-only). */ if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata) _TIFFfree(tif->tif_rawdata); tif->tif_flags &= ~TIFF_MYBUFFER; /* * We must check for overflow, potentially causing * an OOB read. Instead of simple * * td->td_stripoffset[strip]+bytecount > tif->tif_size * * comparison (which can overflow) we do the following * two comparisons: */ if (bytecount > (uint64)tif->tif_size || td->td_stripoffset[strip] > (uint64)tif->tif_size - bytecount) { /* * This error message might seem strange, but * it's what would happen if a read were done * instead. */ TIFFErrorExt(tif->tif_clientdata, module, "Read error on strip %lu; " "got %llu bytes, expected %llu", (unsigned long) strip, (unsigned long long) tif->tif_size - td->td_stripoffset[strip], (unsigned long long) bytecount); tif->tif_curstrip = NOSTRIP; return (0); } tif->tif_rawdatasize = (tmsize_t)bytecount; tif->tif_rawdata = tif->tif_base + (tmsize_t)td->td_stripoffset[strip]; } else { /* * Expand raw data buffer, if needed, to hold data * strip coming from file (perhaps should set upper * bound on the size of a buffer we'll use?). */ tmsize_t bytecountm; bytecountm=(tmsize_t)bytecount; if ((uint64)bytecountm!=bytecount) { TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow"); return(0); } if (bytecountm > tif->tif_rawdatasize) { tif->tif_curstrip = NOSTRIP; if ((tif->tif_flags & TIFF_MYBUFFER) == 0) { TIFFErrorExt(tif->tif_clientdata, module, "Data buffer too small to hold strip %lu", (unsigned long) strip); return (0); } if (!TIFFReadBufferSetup(tif, 0, bytecountm)) return (0); } if (TIFFReadRawStrip1(tif, strip, tif->tif_rawdata, bytecountm, module) != bytecountm) return (0); if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits(tif->tif_rawdata, bytecountm); } } return (TIFFStartStrip(tif, strip)); } /* * Tile-oriented Read Support * Contributed by Nancy Cam (Silicon Graphics). */ /* * Read and decompress a tile of data. The * tile is selected by the (x,y,z,s) coordinates. */ tmsize_t TIFFReadTile(TIFF* tif, void* buf, uint32 x, uint32 y, uint32 z, uint16 s) { if (!TIFFCheckRead(tif, 1) || !TIFFCheckTile(tif, x, y, z, s)) return ((tmsize_t)(-1)); return (TIFFReadEncodedTile(tif, TIFFComputeTile(tif, x, y, z, s), buf, (tmsize_t)(-1))); } /* * Read a tile of data and decompress the specified * amount into the user-supplied buffer. */ tmsize_t TIFFReadEncodedTile(TIFF* tif, uint32 tile, void* buf, tmsize_t size) { static const char module[] = "TIFFReadEncodedTile"; TIFFDirectory *td = &tif->tif_dir; tmsize_t tilesize = tif->tif_tilesize; if (!TIFFCheckRead(tif, 1)) return ((tmsize_t)(-1)); if (tile >= td->td_nstrips) { TIFFErrorExt(tif->tif_clientdata, module, "%lud: Tile out of range, max %lud", (unsigned long) tile, (unsigned long) td->td_nstrips); return ((tmsize_t)(-1)); } if (size == (tmsize_t)(-1)) size = tilesize; else if (size > tilesize) size = tilesize; if (TIFFFillTile(tif, tile) && (*tif->tif_decodetile)(tif, (uint8*) buf, size, (uint16)(tile/td->td_stripsperimage))) { (*tif->tif_postdecode)(tif, (uint8*) buf, size); return (size); } else return ((tmsize_t)(-1)); } static tmsize_t TIFFReadRawTile1(TIFF* tif, uint32 tile, void* buf, tmsize_t size, const char* module) { TIFFDirectory *td = &tif->tif_dir; assert((tif->tif_flags&TIFF_NOREADRAW)==0); if (!isMapped(tif)) { tmsize_t cc; if (!SeekOK(tif, td->td_stripoffset[tile])) { TIFFErrorExt(tif->tif_clientdata, module, "Seek error at row %lud, col %lud, tile %lud", (unsigned long) tif->tif_row, (unsigned long) tif->tif_col, (unsigned long) tile); return ((tmsize_t)(-1)); } cc = TIFFReadFile(tif, buf, size); if (cc != size) { TIFFErrorExt(tif->tif_clientdata, module, "Read error at row %lud, col %lud; got %llu bytes, expected %llu", (unsigned long) tif->tif_row, (unsigned long) tif->tif_col, (unsigned long long) cc, (unsigned long long) size); return ((tmsize_t)(-1)); } } else { tmsize_t ma,mb; tmsize_t n; ma=(tmsize_t)td->td_stripoffset[tile]; mb=ma+size; if (((uint64)ma!=td->td_stripoffset[tile])||(ma>tif->tif_size)) n=0; else if ((mb<ma)||(mb<size)||(mb>tif->tif_size)) n=tif->tif_size-ma; else n=size; if (n!=size) { TIFFErrorExt(tif->tif_clientdata, module, "Read error at row %lud, col %lud, tile %lud; got %llu bytes, expected %llu", (unsigned long) tif->tif_row, (unsigned long) tif->tif_col, (unsigned long) tile, (unsigned long long) n, (unsigned long long) size); return ((tmsize_t)(-1)); } _TIFFmemcpy(buf, tif->tif_base + ma, size); } return (size); } /* * Read a tile of data from the file. */ tmsize_t TIFFReadRawTile(TIFF* tif, uint32 tile, void* buf, tmsize_t size) { static const char module[] = "TIFFReadRawTile"; TIFFDirectory *td = &tif->tif_dir; uint64 bytecount64; tmsize_t bytecountm; if (!TIFFCheckRead(tif, 1)) return ((tmsize_t)(-1)); if (tile >= td->td_nstrips) { TIFFErrorExt(tif->tif_clientdata, module, "%lu: Tile out of range, max %lu", (unsigned long) tile, (unsigned long) td->td_nstrips); return ((tmsize_t)(-1)); } if (tif->tif_flags&TIFF_NOREADRAW) { TIFFErrorExt(tif->tif_clientdata, module, "Compression scheme does not support access to raw uncompressed data"); return ((tmsize_t)(-1)); } bytecount64 = td->td_stripbytecount[tile]; if (size != (tmsize_t)(-1) && (uint64)size < bytecount64) bytecount64 = (uint64)size; bytecountm = (tmsize_t)bytecount64; if ((uint64)bytecountm!=bytecount64) { TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow"); return ((tmsize_t)(-1)); } return (TIFFReadRawTile1(tif, tile, buf, bytecountm, module)); } /* * Read the specified tile and setup for decoding. The data buffer is * expanded, as necessary, to hold the tile's data. */ int TIFFFillTile(TIFF* tif, uint32 tile) { static const char module[] = "TIFFFillTile"; TIFFDirectory *td = &tif->tif_dir; if ((tif->tif_flags&TIFF_NOREADRAW)==0) { uint64 bytecount = td->td_stripbytecount[tile]; if (bytecount <= 0) { TIFFErrorExt(tif->tif_clientdata, module, "%llu: Invalid tile byte count, tile %lu", (unsigned long long) bytecount, (unsigned long) tile); return (0); } if (isMapped(tif) && (isFillOrder(tif, td->td_fillorder) || (tif->tif_flags & TIFF_NOBITREV))) { /* * The image is mapped into memory and we either don't * need to flip bits or the compression routine is * going to handle this operation itself. In this * case, avoid copying the raw data and instead just * reference the data from the memory mapped file * image. This assumes that the decompression * routines do not modify the contents of the raw data * buffer (if they try to, the application will get a * fault since the file is mapped read-only). */ if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata) _TIFFfree(tif->tif_rawdata); tif->tif_flags &= ~TIFF_MYBUFFER; /* * We must check for overflow, potentially causing * an OOB read. Instead of simple * * td->td_stripoffset[tile]+bytecount > tif->tif_size * * comparison (which can overflow) we do the following * two comparisons: */ if (bytecount > (uint64)tif->tif_size || td->td_stripoffset[tile] > (uint64)tif->tif_size - bytecount) { tif->tif_curtile = NOTILE; return (0); } tif->tif_rawdatasize = (tmsize_t)bytecount; tif->tif_rawdata = tif->tif_base + (tmsize_t)td->td_stripoffset[tile]; } else { /* * Expand raw data buffer, if needed, to hold data * tile coming from file (perhaps should set upper * bound on the size of a buffer we'll use?). */ tmsize_t bytecountm; bytecountm=(tmsize_t)bytecount; if ((uint64)bytecountm!=bytecount) { TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow"); return(0); } if (bytecountm > tif->tif_rawdatasize) { tif->tif_curtile = NOTILE; if ((tif->tif_flags & TIFF_MYBUFFER) == 0) { TIFFErrorExt(tif->tif_clientdata, module, "Data buffer too small to hold tile %lud", (unsigned long) tile); return (0); } if (!TIFFReadBufferSetup(tif, 0, bytecountm)) return (0); } if (TIFFReadRawTile1(tif, tile, tif->tif_rawdata, bytecountm, module) != bytecountm) return (0); if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits(tif->tif_rawdata, bytecountm); } } return (TIFFStartTile(tif, tile)); } /* * Setup the raw data buffer in preparation for * reading a strip of raw data. If the buffer * is specified as zero, then a buffer of appropriate * size is allocated by the library. Otherwise, * the client must guarantee that the buffer is * large enough to hold any individual strip of * raw data. */ int TIFFReadBufferSetup(TIFF* tif, void* bp, tmsize_t size) { static const char module[] = "TIFFReadBufferSetup"; assert((tif->tif_flags&TIFF_NOREADRAW)==0); if (tif->tif_rawdata) { if (tif->tif_flags & TIFF_MYBUFFER) _TIFFfree(tif->tif_rawdata); tif->tif_rawdata = NULL; } if (bp) { tif->tif_rawdatasize = size; tif->tif_rawdata = (uint8*) bp; tif->tif_flags &= ~TIFF_MYBUFFER; } else { tif->tif_rawdatasize = (tmsize_t)TIFFroundup_64((uint64)size, 1024); if (tif->tif_rawdatasize==0) tif->tif_rawdatasize=(tmsize_t)(-1); tif->tif_rawdata = (uint8*) _TIFFmalloc(tif->tif_rawdatasize); tif->tif_flags |= TIFF_MYBUFFER; } if (tif->tif_rawdata == NULL) { TIFFErrorExt(tif->tif_clientdata, module, "No space for data buffer at scanline %lud", (unsigned long) tif->tif_row); tif->tif_rawdatasize = 0; return (0); } return (1); } /* * Set state to appear as if a * strip has just been read in. */ static int TIFFStartStrip(TIFF* tif, uint32 strip) { TIFFDirectory *td = &tif->tif_dir; if ((tif->tif_flags & TIFF_CODERSETUP) == 0) { if (!(*tif->tif_setupdecode)(tif)) return (0); tif->tif_flags |= TIFF_CODERSETUP; } tif->tif_curstrip = strip; tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip; if (tif->tif_flags&TIFF_NOREADRAW) { tif->tif_rawcp = NULL; tif->tif_rawcc = 0; } else { tif->tif_rawcp = tif->tif_rawdata; tif->tif_rawcc = (tmsize_t)td->td_stripbytecount[strip]; } return ((*tif->tif_predecode)(tif, (uint16)(strip / td->td_stripsperimage))); } /* * Set state to appear as if a * tile has just been read in. */ static int TIFFStartTile(TIFF* tif, uint32 tile) { TIFFDirectory *td = &tif->tif_dir; if ((tif->tif_flags & TIFF_CODERSETUP) == 0) { if (!(*tif->tif_setupdecode)(tif)) return (0); tif->tif_flags |= TIFF_CODERSETUP; } tif->tif_curtile = tile; tif->tif_row = (tile % TIFFhowmany_32(td->td_imagewidth, td->td_tilewidth)) * td->td_tilelength; tif->tif_col = (tile % TIFFhowmany_32(td->td_imagelength, td->td_tilelength)) * td->td_tilewidth; if (tif->tif_flags&TIFF_NOREADRAW) { tif->tif_rawcp = NULL; tif->tif_rawcc = 0; } else { tif->tif_rawcp = tif->tif_rawdata; tif->tif_rawcc = (tmsize_t)td->td_stripbytecount[tile]; } return ((*tif->tif_predecode)(tif, (uint16)(tile/td->td_stripsperimage))); } static int TIFFCheckRead(TIFF* tif, int tiles) { if (tif->tif_mode == O_WRONLY) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "File not open for reading"); return (0); } if (tiles ^ isTiled(tif)) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, tiles ? "Can not read tiles from a stripped image" : "Can not read scanlines from a tiled image"); return (0); } return (1); } void _TIFFNoPostDecode(TIFF* tif, uint8* buf, tmsize_t cc) { (void) tif; (void) buf; (void) cc; } void _TIFFSwab16BitData(TIFF* tif, uint8* buf, tmsize_t cc) { (void) tif; assert((cc & 1) == 0); TIFFSwabArrayOfShort((uint16*) buf, cc/2); } void _TIFFSwab24BitData(TIFF* tif, uint8* buf, tmsize_t cc) { (void) tif; assert((cc % 3) == 0); TIFFSwabArrayOfTriples((uint8*) buf, cc/3); } void _TIFFSwab32BitData(TIFF* tif, uint8* buf, tmsize_t cc) { (void) tif; assert((cc & 3) == 0); TIFFSwabArrayOfLong((uint32*) buf, cc/4); } void _TIFFSwab64BitData(TIFF* tif, uint8* buf, tmsize_t cc) { (void) tif; assert((cc & 7) == 0); TIFFSwabArrayOfDouble((double*) buf, cc/8); } /* vim: set ts=8 sts=8 sw=8 noet: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/libtiff_2007-07-13-09e8220-f2d989d.c
manybugs_data_43
/* +----------------------------------------------------------------------+ | phar php single-file executable PHP extension | +----------------------------------------------------------------------+ | Copyright (c) 2005-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Gregory Beaver <[email protected]> | | Marcus Boerger <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #define PHAR_MAIN 1 #include "phar_internal.h" #include "SAPI.h" #include "func_interceptors.h" static void destroy_phar_data(void *pDest); ZEND_DECLARE_MODULE_GLOBALS(phar) #if PHP_VERSION_ID >= 50300 char *(*phar_save_resolve_path)(const char *filename, int filename_len TSRMLS_DC); #endif /** * set's phar->is_writeable based on the current INI value */ static int phar_set_writeable_bit(void *pDest, void *argument TSRMLS_DC) /* {{{ */ { zend_bool keep = *(zend_bool *)argument; phar_archive_data *phar = *(phar_archive_data **)pDest; if (!phar->is_data) { phar->is_writeable = !keep; } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* if the original value is 0 (disabled), then allow setting/unsetting at will. Otherwise only allow 1 (enabled), and error on disabling */ ZEND_INI_MH(phar_ini_modify_handler) /* {{{ */ { zend_bool old, ini; if (entry->name_length == 14) { old = PHAR_G(readonly_orig); } else { old = PHAR_G(require_hash_orig); } if (new_value_length == 2 && !strcasecmp("on", new_value)) { ini = (zend_bool) 1; } else if (new_value_length == 3 && !strcasecmp("yes", new_value)) { ini = (zend_bool) 1; } else if (new_value_length == 4 && !strcasecmp("true", new_value)) { ini = (zend_bool) 1; } else { ini = (zend_bool) atoi(new_value); } /* do not allow unsetting in runtime */ if (stage == ZEND_INI_STAGE_STARTUP) { if (entry->name_length == 14) { PHAR_G(readonly_orig) = ini; } else { PHAR_G(require_hash_orig) = ini; } } else if (old && !ini) { return FAILURE; } if (entry->name_length == 14) { PHAR_G(readonly) = ini; if (PHAR_GLOBALS->request_init && PHAR_GLOBALS->phar_fname_map.arBuckets) { zend_hash_apply_with_argument(&(PHAR_GLOBALS->phar_fname_map), phar_set_writeable_bit, (void *)&ini TSRMLS_CC); } } else { PHAR_G(require_hash) = ini; } return SUCCESS; } /* }}}*/ /* this global stores the global cached pre-parsed manifests */ HashTable cached_phars; HashTable cached_alias; static void phar_split_cache_list(TSRMLS_D) /* {{{ */ { char *tmp; char *key, *lasts, *end; char ds[2]; phar_archive_data *phar; uint i = 0; if (!PHAR_GLOBALS->cache_list || !(PHAR_GLOBALS->cache_list[0])) { return; } ds[0] = DEFAULT_DIR_SEPARATOR; ds[1] = '\0'; tmp = estrdup(PHAR_GLOBALS->cache_list); /* fake request startup */ PHAR_GLOBALS->request_init = 1; if (zend_hash_init(&EG(regular_list), 0, NULL, NULL, 0) == SUCCESS) { EG(regular_list).nNextFreeElement=1; /* we don't want resource id 0 */ } PHAR_G(has_bz2) = zend_hash_exists(&module_registry, "bz2", sizeof("bz2")); PHAR_G(has_zlib) = zend_hash_exists(&module_registry, "zlib", sizeof("zlib")); /* these two are dummies and will be destroyed later */ zend_hash_init(&cached_phars, sizeof(phar_archive_data*), zend_get_hash_value, destroy_phar_data, 1); zend_hash_init(&cached_alias, sizeof(phar_archive_data*), zend_get_hash_value, NULL, 1); /* these two are real and will be copied over cached_phars/cached_alias later */ zend_hash_init(&(PHAR_GLOBALS->phar_fname_map), sizeof(phar_archive_data*), zend_get_hash_value, destroy_phar_data, 1); zend_hash_init(&(PHAR_GLOBALS->phar_alias_map), sizeof(phar_archive_data*), zend_get_hash_value, NULL, 1); PHAR_GLOBALS->manifest_cached = 1; PHAR_GLOBALS->persist = 1; for (key = php_strtok_r(tmp, ds, &lasts); key; key = php_strtok_r(NULL, ds, &lasts)) { end = strchr(key, DEFAULT_DIR_SEPARATOR); if (end) { if (SUCCESS == phar_open_from_filename(key, end - key, NULL, 0, 0, &phar, NULL TSRMLS_CC)) { finish_up: phar->phar_pos = i++; php_stream_close(phar->fp); phar->fp = NULL; } else { finish_error: PHAR_GLOBALS->persist = 0; PHAR_GLOBALS->manifest_cached = 0; efree(tmp); zend_hash_destroy(&(PHAR_G(phar_fname_map))); PHAR_GLOBALS->phar_fname_map.arBuckets = 0; zend_hash_destroy(&(PHAR_G(phar_alias_map))); PHAR_GLOBALS->phar_alias_map.arBuckets = 0; zend_hash_destroy(&cached_phars); zend_hash_destroy(&cached_alias); zend_hash_graceful_reverse_destroy(&EG(regular_list)); memset(&EG(regular_list), 0, sizeof(HashTable)); /* free cached manifests */ PHAR_GLOBALS->request_init = 0; return; } } else { if (SUCCESS == phar_open_from_filename(key, strlen(key), NULL, 0, 0, &phar, NULL TSRMLS_CC)) { goto finish_up; } else { goto finish_error; } } } PHAR_GLOBALS->persist = 0; PHAR_GLOBALS->request_init = 0; /* destroy dummy values from before */ zend_hash_destroy(&cached_phars); zend_hash_destroy(&cached_alias); cached_phars = PHAR_GLOBALS->phar_fname_map; cached_alias = PHAR_GLOBALS->phar_alias_map; PHAR_GLOBALS->phar_fname_map.arBuckets = 0; PHAR_GLOBALS->phar_alias_map.arBuckets = 0; zend_hash_graceful_reverse_destroy(&EG(regular_list)); memset(&EG(regular_list), 0, sizeof(HashTable)); efree(tmp); } /* }}} */ ZEND_INI_MH(phar_ini_cache_list) /* {{{ */ { PHAR_G(cache_list) = new_value; if (stage == ZEND_INI_STAGE_STARTUP) { phar_split_cache_list(TSRMLS_C); } return SUCCESS; } /* }}} */ PHP_INI_BEGIN() STD_PHP_INI_BOOLEAN( "phar.readonly", "1", PHP_INI_ALL, phar_ini_modify_handler, readonly, zend_phar_globals, phar_globals) STD_PHP_INI_BOOLEAN( "phar.require_hash", "1", PHP_INI_ALL, phar_ini_modify_handler, require_hash, zend_phar_globals, phar_globals) STD_PHP_INI_ENTRY("phar.cache_list", "", PHP_INI_SYSTEM, phar_ini_cache_list, cache_list, zend_phar_globals, phar_globals) PHP_INI_END() /** * When all uses of a phar have been concluded, this frees the manifest * and the phar slot */ void phar_destroy_phar_data(phar_archive_data *phar TSRMLS_DC) /* {{{ */ { if (phar->alias && phar->alias != phar->fname) { pefree(phar->alias, phar->is_persistent); phar->alias = NULL; } if (phar->fname) { pefree(phar->fname, phar->is_persistent); phar->fname = NULL; } if (phar->signature) { pefree(phar->signature, phar->is_persistent); phar->signature = NULL; } if (phar->manifest.arBuckets) { zend_hash_destroy(&phar->manifest); phar->manifest.arBuckets = NULL; } if (phar->mounted_dirs.arBuckets) { zend_hash_destroy(&phar->mounted_dirs); phar->mounted_dirs.arBuckets = NULL; } if (phar->virtual_dirs.arBuckets) { zend_hash_destroy(&phar->virtual_dirs); phar->virtual_dirs.arBuckets = NULL; } if (phar->metadata) { if (phar->is_persistent) { if (phar->metadata_len) { /* for zip comments that are strings */ free(phar->metadata); } else { zval_internal_ptr_dtor(&phar->metadata); } } else { zval_ptr_dtor(&phar->metadata); } phar->metadata_len = 0; phar->metadata = 0; } if (phar->fp) { php_stream_close(phar->fp); phar->fp = 0; } if (phar->ufp) { php_stream_close(phar->ufp); phar->ufp = 0; } pefree(phar, phar->is_persistent); } /* }}}*/ /** * Delete refcount and destruct if needed. On destruct return 1 else 0. */ int phar_archive_delref(phar_archive_data *phar TSRMLS_DC) /* {{{ */ { if (phar->is_persistent) { return 0; } if (--phar->refcount < 0) { if (PHAR_GLOBALS->request_done || zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), phar->fname, phar->fname_len) != SUCCESS) { phar_destroy_phar_data(phar TSRMLS_CC); } return 1; } else if (!phar->refcount) { /* invalidate phar cache */ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; if (phar->fp && !(phar->flags & PHAR_FILE_COMPRESSION_MASK)) { /* close open file handle - allows removal or rename of the file on windows, which has greedy locking only close if the archive was not already compressed. If it was compressed, then the fp does not refer to the original file */ php_stream_close(phar->fp); phar->fp = NULL; } if (!zend_hash_num_elements(&phar->manifest)) { /* this is a new phar that has perhaps had an alias/metadata set, but has never been flushed */ if (zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), phar->fname, phar->fname_len) != SUCCESS) { phar_destroy_phar_data(phar TSRMLS_CC); } return 1; } } return 0; } /* }}}*/ /** * Destroy phar's in shutdown, here we don't care about aliases */ static void destroy_phar_data_only(void *pDest) /* {{{ */ { phar_archive_data *phar_data = *(phar_archive_data **) pDest; TSRMLS_FETCH(); if (EG(exception) || --phar_data->refcount < 0) { phar_destroy_phar_data(phar_data TSRMLS_CC); } } /* }}}*/ /** * Delete aliases to phar's that got kicked out of the global table */ static int phar_unalias_apply(void *pDest, void *argument TSRMLS_DC) /* {{{ */ { return *(void**)pDest == argument ? ZEND_HASH_APPLY_REMOVE : ZEND_HASH_APPLY_KEEP; } /* }}} */ /** * Delete aliases to phar's that got kicked out of the global table */ static int phar_tmpclose_apply(void *pDest TSRMLS_DC) /* {{{ */ { phar_entry_info *entry = (phar_entry_info *) pDest; if (entry->fp_type != PHAR_TMP) { return ZEND_HASH_APPLY_KEEP; } if (entry->fp && !entry->fp_refcount) { php_stream_close(entry->fp); entry->fp = NULL; } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /** * Filename map destructor */ static void destroy_phar_data(void *pDest) /* {{{ */ { phar_archive_data *phar_data = *(phar_archive_data **) pDest; TSRMLS_FETCH(); if (PHAR_GLOBALS->request_ends) { /* first, iterate over the manifest and close all PHAR_TMP entry fp handles, this prevents unnecessary unfreed stream resources */ zend_hash_apply(&(phar_data->manifest), phar_tmpclose_apply TSRMLS_CC); destroy_phar_data_only(pDest); return; } zend_hash_apply_with_argument(&(PHAR_GLOBALS->phar_alias_map), phar_unalias_apply, phar_data TSRMLS_CC); if (--phar_data->refcount < 0) { phar_destroy_phar_data(phar_data TSRMLS_CC); } } /* }}}*/ /** * destructor for the manifest hash, frees each file's entry */ void destroy_phar_manifest_entry(void *pDest) /* {{{ */ { phar_entry_info *entry = (phar_entry_info *)pDest; TSRMLS_FETCH(); if (entry->cfp) { php_stream_close(entry->cfp); entry->cfp = 0; } if (entry->fp) { php_stream_close(entry->fp); entry->fp = 0; } if (entry->metadata) { if (entry->is_persistent) { if (entry->metadata_len) { /* for zip comments that are strings */ free(entry->metadata); } else { zval_internal_ptr_dtor(&entry->metadata); } } else { zval_ptr_dtor(&entry->metadata); } entry->metadata_len = 0; entry->metadata = 0; } if (entry->metadata_str.c) { smart_str_free(&entry->metadata_str); entry->metadata_str.c = 0; } pefree(entry->filename, entry->is_persistent); if (entry->link) { pefree(entry->link, entry->is_persistent); entry->link = 0; } if (entry->tmp) { pefree(entry->tmp, entry->is_persistent); entry->tmp = 0; } } /* }}} */ int phar_entry_delref(phar_entry_data *idata TSRMLS_DC) /* {{{ */ { int ret = 0; if (idata->internal_file && !idata->internal_file->is_persistent) { if (--idata->internal_file->fp_refcount < 0) { idata->internal_file->fp_refcount = 0; } if (idata->fp && idata->fp != idata->phar->fp && idata->fp != idata->phar->ufp && idata->fp != idata->internal_file->fp) { php_stream_close(idata->fp); } /* if phar_get_or_create_entry_data returns a sub-directory, we have to free it */ if (idata->internal_file->is_temp_dir) { destroy_phar_manifest_entry((void *)idata->internal_file); efree(idata->internal_file); } } phar_archive_delref(idata->phar TSRMLS_CC); efree(idata); return ret; } /* }}} */ /** * Removes an entry, either by actually removing it or by marking it. */ void phar_entry_remove(phar_entry_data *idata, char **error TSRMLS_DC) /* {{{ */ { phar_archive_data *phar; phar = idata->phar; if (idata->internal_file->fp_refcount < 2) { if (idata->fp && idata->fp != idata->phar->fp && idata->fp != idata->phar->ufp && idata->fp != idata->internal_file->fp) { php_stream_close(idata->fp); } zend_hash_del(&idata->phar->manifest, idata->internal_file->filename, idata->internal_file->filename_len); idata->phar->refcount--; efree(idata); } else { idata->internal_file->is_deleted = 1; phar_entry_delref(idata TSRMLS_CC); } if (!phar->donotflush) { phar_flush(phar, 0, 0, 0, error TSRMLS_CC); } } /* }}} */ #define MAPPHAR_ALLOC_FAIL(msg) \ if (fp) {\ php_stream_close(fp);\ }\ if (error) {\ spprintf(error, 0, msg, fname);\ }\ return FAILURE; #define MAPPHAR_FAIL(msg) \ efree(savebuf);\ if (mydata) {\ phar_destroy_phar_data(mydata TSRMLS_CC);\ }\ if (signature) {\ pefree(signature, PHAR_G(persist));\ }\ MAPPHAR_ALLOC_FAIL(msg) #ifdef WORDS_BIGENDIAN # define PHAR_GET_32(buffer, var) \ var = ((((unsigned char*)(buffer))[3]) << 24) \ | ((((unsigned char*)(buffer))[2]) << 16) \ | ((((unsigned char*)(buffer))[1]) << 8) \ | (((unsigned char*)(buffer))[0]); \ (buffer) += 4 # define PHAR_GET_16(buffer, var) \ var = ((((unsigned char*)(buffer))[1]) << 8) \ | (((unsigned char*)(buffer))[0]); \ (buffer) += 2 #else # define PHAR_GET_32(buffer, var) \ memcpy(&var, buffer, sizeof(var)); \ buffer += 4 # define PHAR_GET_16(buffer, var) \ var = *(php_uint16*)(buffer); \ buffer += 2 #endif #define PHAR_ZIP_16(var) ((php_uint16)((((php_uint16)var[0]) & 0xff) | \ (((php_uint16)var[1]) & 0xff) << 8)) #define PHAR_ZIP_32(var) ((php_uint32)((((php_uint32)var[0]) & 0xff) | \ (((php_uint32)var[1]) & 0xff) << 8 | \ (((php_uint32)var[2]) & 0xff) << 16 | \ (((php_uint32)var[3]) & 0xff) << 24)) /** * Open an already loaded phar */ int phar_open_parsed_phar(char *fname, int fname_len, char *alias, int alias_len, int is_data, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { phar_archive_data *phar; #ifdef PHP_WIN32 char *unixfname; #endif if (error) { *error = NULL; } #ifdef PHP_WIN32 unixfname = estrndup(fname, fname_len); phar_unixify_path_separators(unixfname, fname_len); if (SUCCESS == phar_get_archive(&phar, unixfname, fname_len, alias, alias_len, error TSRMLS_CC) && ((alias && fname_len == phar->fname_len && !strncmp(unixfname, phar->fname, fname_len)) || !alias) ) { phar_entry_info *stub; efree(unixfname); #else if (SUCCESS == phar_get_archive(&phar, fname, fname_len, alias, alias_len, error TSRMLS_CC) && ((alias && fname_len == phar->fname_len && !strncmp(fname, phar->fname, fname_len)) || !alias) ) { phar_entry_info *stub; #endif /* logic above is as follows: If an explicit alias was requested, ensure the filename passed in matches the phar's filename. If no alias was passed in, then it can match either and be valid */ if (!is_data) { /* prevent any ".phar" without a stub getting through */ if (!phar->halt_offset && !phar->is_brandnew && (phar->is_tar || phar->is_zip)) { if (PHAR_G(readonly) && FAILURE == zend_hash_find(&(phar->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1, (void **)&stub)) { if (error) { spprintf(error, 0, "'%s' is not a phar archive. Use PharData::__construct() for a standard zip or tar archive", fname); } return FAILURE; } } } if (pphar) { *pphar = phar; } return SUCCESS; } else { #ifdef PHP_WIN32 efree(unixfname); #endif if (pphar) { *pphar = NULL; } if (phar && error && !(options & REPORT_ERRORS)) { efree(error); } return FAILURE; } } /* }}}*/ /** * Parse out metadata from the manifest for a single file * * Meta-data is in this format: * [len32][data...] * * data is the serialized zval */ int phar_parse_metadata(char **buffer, zval **metadata, int zip_metadata_len TSRMLS_DC) /* {{{ */ { const unsigned char *p; php_uint32 buf_len; php_unserialize_data_t var_hash; if (!zip_metadata_len) { PHAR_GET_32(*buffer, buf_len); } else { buf_len = zip_metadata_len; } if (buf_len) { ALLOC_ZVAL(*metadata); INIT_ZVAL(**metadata); p = (const unsigned char*) *buffer; PHP_VAR_UNSERIALIZE_INIT(var_hash); if (!php_var_unserialize(metadata, &p, p + buf_len, &var_hash TSRMLS_CC)) { PHP_VAR_UNSERIALIZE_DESTROY(var_hash); zval_ptr_dtor(metadata); *metadata = NULL; return FAILURE; } PHP_VAR_UNSERIALIZE_DESTROY(var_hash); if (PHAR_G(persist)) { /* lazy init metadata */ zval_ptr_dtor(metadata); *metadata = (zval *) pemalloc(buf_len, 1); memcpy(*metadata, *buffer, buf_len); *buffer += buf_len; return SUCCESS; } } else { *metadata = NULL; } if (!zip_metadata_len) { *buffer += buf_len; } return SUCCESS; } /* }}}*/ /** * Does not check for a previously opened phar in the cache. * * Parse a new one and add it to the cache, returning either SUCCESS or * FAILURE, and setting pphar to the pointer to the manifest entry * * This is used by phar_open_from_filename to process the manifest, but can be called * directly. */ static int phar_parse_pharfile(php_stream *fp, char *fname, int fname_len, char *alias, int alias_len, long halt_offset, phar_archive_data** pphar, php_uint32 compression, char **error TSRMLS_DC) /* {{{ */ { char b32[4], *buffer, *endbuffer, *savebuf; phar_archive_data *mydata = NULL; phar_entry_info entry; php_uint32 manifest_len, manifest_count, manifest_flags, manifest_index, tmp_len, sig_flags; php_uint16 manifest_ver; long offset; int register_alias, sig_len, temp_alias = 0; char *signature = NULL; if (pphar) { *pphar = NULL; } if (error) { *error = NULL; } /* check for ?>\n and increment accordingly */ if (-1 == php_stream_seek(fp, halt_offset, SEEK_SET)) { MAPPHAR_ALLOC_FAIL("cannot seek to __HALT_COMPILER(); location in phar \"%s\"") } buffer = b32; if (3 != php_stream_read(fp, buffer, 3)) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at stub end)") } if ((*buffer == ' ' || *buffer == '\n') && *(buffer + 1) == '?' && *(buffer + 2) == '>') { int nextchar; halt_offset += 3; if (EOF == (nextchar = php_stream_getc(fp))) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at stub end)") } if ((char) nextchar == '\r') { /* if we have an \r we require an \n as well */ if (EOF == (nextchar = php_stream_getc(fp)) || (char)nextchar != '\n') { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at stub end)") } ++halt_offset; } if ((char) nextchar == '\n') { ++halt_offset; } } /* make sure we are at the right location to read the manifest */ if (-1 == php_stream_seek(fp, halt_offset, SEEK_SET)) { MAPPHAR_ALLOC_FAIL("cannot seek to __HALT_COMPILER(); location in phar \"%s\"") } /* read in manifest */ buffer = b32; if (4 != php_stream_read(fp, buffer, 4)) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at manifest length)") } PHAR_GET_32(buffer, manifest_len); if (manifest_len > 1048576 * 100) { /* prevent serious memory issues by limiting manifest to at most 100 MB in length */ MAPPHAR_ALLOC_FAIL("manifest cannot be larger than 100 MB in phar \"%s\"") } buffer = (char *)emalloc(manifest_len); savebuf = buffer; endbuffer = buffer + manifest_len; if (manifest_len < 10 || manifest_len != php_stream_read(fp, buffer, manifest_len)) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest header)") } /* extract the number of entries */ PHAR_GET_32(buffer, manifest_count); if (manifest_count == 0) { MAPPHAR_FAIL("in phar \"%s\", manifest claims to have zero entries. Phars must have at least 1 entry"); } /* extract API version, lowest nibble currently unused */ manifest_ver = (((unsigned char)buffer[0]) << 8) + ((unsigned char)buffer[1]); buffer += 2; if ((manifest_ver & PHAR_API_VER_MASK) < PHAR_API_MIN_READ) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" is API version %1.u.%1.u.%1.u, and cannot be processed", fname, manifest_ver >> 12, (manifest_ver >> 8) & 0xF, (manifest_ver >> 4) & 0x0F); } return FAILURE; } PHAR_GET_32(buffer, manifest_flags); manifest_flags &= ~PHAR_HDR_COMPRESSION_MASK; manifest_flags &= ~PHAR_FILE_COMPRESSION_MASK; /* remember whether this entire phar was compressed with gz/bzip2 */ manifest_flags |= compression; /* The lowest nibble contains the phar wide flags. The compression flags can */ /* be ignored on reading because it is being generated anyways. */ if (manifest_flags & PHAR_HDR_SIGNATURE) { char sig_buf[8], *sig_ptr = sig_buf; off_t read_len; size_t end_of_phar; if (-1 == php_stream_seek(fp, -8, SEEK_END) || (read_len = php_stream_tell(fp)) < 20 || 8 != php_stream_read(fp, sig_buf, 8) || memcmp(sig_buf+4, "GBMB", 4)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } PHAR_GET_32(sig_ptr, sig_flags); switch(sig_flags) { case PHAR_SIG_OPENSSL: { php_uint32 signature_len; char *sig; off_t whence; /* we store the signature followed by the signature length */ if (-1 == php_stream_seek(fp, -12, SEEK_CUR) || 4 != php_stream_read(fp, sig_buf, 4)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" openssl signature length could not be read", fname); } return FAILURE; } sig_ptr = sig_buf; PHAR_GET_32(sig_ptr, signature_len); sig = (char *) emalloc(signature_len); whence = signature_len + 4; whence = -whence; if (-1 == php_stream_seek(fp, whence, SEEK_CUR) || !(end_of_phar = php_stream_tell(fp)) || signature_len != php_stream_read(fp, sig, signature_len)) { efree(savebuf); efree(sig); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" openssl signature could not be read", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, end_of_phar, PHAR_SIG_OPENSSL, sig, signature_len, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); efree(sig); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" openssl signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } efree(sig); } break; #if PHAR_HASH_OK case PHAR_SIG_SHA512: { unsigned char digest[64]; php_stream_seek(fp, -(8 + 64), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_SHA512, (char *)digest, 64, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" SHA512 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } case PHAR_SIG_SHA256: { unsigned char digest[32]; php_stream_seek(fp, -(8 + 32), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_SHA256, (char *)digest, 32, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" SHA256 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } #else case PHAR_SIG_SHA512: case PHAR_SIG_SHA256: efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a unsupported signature", fname); } return FAILURE; #endif case PHAR_SIG_SHA1: { unsigned char digest[20]; php_stream_seek(fp, -(8 + 20), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_SHA1, (char *)digest, 20, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" SHA1 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } case PHAR_SIG_MD5: { unsigned char digest[16]; php_stream_seek(fp, -(8 + 16), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_MD5, (char *)digest, 16, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" MD5 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } default: efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken or unsupported signature", fname); } return FAILURE; } } else if (PHAR_G(require_hash)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" does not have a signature", fname); } return FAILURE; } else { sig_flags = 0; sig_len = 0; } /* extract alias */ PHAR_GET_32(buffer, tmp_len); if (buffer + tmp_len > endbuffer) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (buffer overrun)"); } if (manifest_len < 10 + tmp_len) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest header)") } /* tmp_len = 0 says alias length is 0, which means the alias is not stored in the phar */ if (tmp_len) { /* if the alias is stored we enforce it (implicit overrides explicit) */ if (alias && alias_len && (alias_len != (int)tmp_len || strncmp(alias, buffer, tmp_len))) { buffer[tmp_len] = '\0'; php_stream_close(fp); if (signature) { efree(signature); } if (error) { spprintf(error, 0, "cannot load phar \"%s\" with implicit alias \"%s\" under different alias \"%s\"", fname, buffer, alias); } efree(savebuf); return FAILURE; } alias_len = tmp_len; alias = buffer; buffer += tmp_len; register_alias = 1; } else if (!alias_len || !alias) { /* if we neither have an explicit nor an implicit alias, we use the filename */ alias = NULL; alias_len = 0; register_alias = 0; } else if (alias_len) { register_alias = 1; temp_alias = 1; } /* we have 5 32-bit items plus 1 byte at least */ if (manifest_count > ((manifest_len - 10 - tmp_len) / (5 * 4 + 1))) { /* prevent serious memory issues */ MAPPHAR_FAIL("internal corruption of phar \"%s\" (too many manifest entries for size of manifest)") } mydata = pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist)); mydata->is_persistent = PHAR_G(persist); /* check whether we have meta data, zero check works regardless of byte order */ if (mydata->is_persistent) { PHAR_GET_32(buffer, mydata->metadata_len); if (phar_parse_metadata(&buffer, &mydata->metadata, mydata->metadata_len TSRMLS_CC) == FAILURE) { MAPPHAR_FAIL("unable to read phar metadata in .phar file \"%s\""); } } else { if (phar_parse_metadata(&buffer, &mydata->metadata, 0 TSRMLS_CC) == FAILURE) { MAPPHAR_FAIL("unable to read phar metadata in .phar file \"%s\""); } } /* set up our manifest */ zend_hash_init(&mydata->manifest, manifest_count, zend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)mydata->is_persistent); zend_hash_init(&mydata->mounted_dirs, 5, zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); zend_hash_init(&mydata->virtual_dirs, manifest_count * 2, zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); mydata->fname = pestrndup(fname, fname_len, mydata->is_persistent); #ifdef PHP_WIN32 phar_unixify_path_separators(mydata->fname, fname_len); #endif mydata->fname_len = fname_len; offset = halt_offset + manifest_len + 4; memset(&entry, 0, sizeof(phar_entry_info)); entry.phar = mydata; entry.fp_type = PHAR_FP; entry.is_persistent = mydata->is_persistent; for (manifest_index = 0; manifest_index < manifest_count; ++manifest_index) { if (buffer + 4 > endbuffer) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest entry)") } PHAR_GET_32(buffer, entry.filename_len); if (entry.filename_len == 0) { MAPPHAR_FAIL("zero-length filename encountered in phar \"%s\""); } if (entry.is_persistent) { entry.manifest_pos = manifest_index; } if (buffer + entry.filename_len + 20 > endbuffer) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest entry)"); } if ((manifest_ver & PHAR_API_VER_MASK) >= PHAR_API_MIN_DIR && buffer[entry.filename_len - 1] == '/') { entry.is_dir = 1; } else { entry.is_dir = 0; } phar_add_virtual_dirs(mydata, buffer, entry.filename_len TSRMLS_CC); entry.filename = pestrndup(buffer, entry.filename_len, entry.is_persistent); buffer += entry.filename_len; PHAR_GET_32(buffer, entry.uncompressed_filesize); PHAR_GET_32(buffer, entry.timestamp); if (offset == halt_offset + (int)manifest_len + 4) { mydata->min_timestamp = entry.timestamp; mydata->max_timestamp = entry.timestamp; } else { if (mydata->min_timestamp > entry.timestamp) { mydata->min_timestamp = entry.timestamp; } else if (mydata->max_timestamp < entry.timestamp) { mydata->max_timestamp = entry.timestamp; } } PHAR_GET_32(buffer, entry.compressed_filesize); PHAR_GET_32(buffer, entry.crc32); PHAR_GET_32(buffer, entry.flags); if (entry.is_dir) { entry.filename_len--; entry.flags |= PHAR_ENT_PERM_DEF_DIR; } if (entry.is_persistent) { PHAR_GET_32(buffer, entry.metadata_len); if (!entry.metadata_len) buffer -= 4; if (phar_parse_metadata(&buffer, &entry.metadata, entry.metadata_len TSRMLS_CC) == FAILURE) { pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("unable to read file metadata in .phar file \"%s\""); } } else { if (phar_parse_metadata(&buffer, &entry.metadata, 0 TSRMLS_CC) == FAILURE) { pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("unable to read file metadata in .phar file \"%s\""); } } entry.offset = entry.offset_abs = offset; offset += entry.compressed_filesize; switch (entry.flags & PHAR_ENT_COMPRESSION_MASK) { case PHAR_ENT_COMPRESSED_GZ: if (!PHAR_G(has_zlib)) { if (entry.metadata) { if (entry.is_persistent) { free(entry.metadata); } else { zval_ptr_dtor(&entry.metadata); } } pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("zlib extension is required for gz compressed .phar file \"%s\""); } break; case PHAR_ENT_COMPRESSED_BZ2: if (!PHAR_G(has_bz2)) { if (entry.metadata) { if (entry.is_persistent) { free(entry.metadata); } else { zval_ptr_dtor(&entry.metadata); } } pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("bz2 extension is required for bzip2 compressed .phar file \"%s\""); } break; default: if (entry.uncompressed_filesize != entry.compressed_filesize) { if (entry.metadata) { if (entry.is_persistent) { free(entry.metadata); } else { zval_ptr_dtor(&entry.metadata); } } pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("internal corruption of phar \"%s\" (compressed and uncompressed size does not match for uncompressed entry)"); } break; } manifest_flags |= (entry.flags & PHAR_ENT_COMPRESSION_MASK); /* if signature matched, no need to check CRC32 for each file */ entry.is_crc_checked = (manifest_flags & PHAR_HDR_SIGNATURE ? 1 : 0); phar_set_inode(&entry TSRMLS_CC); zend_hash_add(&mydata->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info), NULL); } snprintf(mydata->version, sizeof(mydata->version), "%u.%u.%u", manifest_ver >> 12, (manifest_ver >> 8) & 0xF, (manifest_ver >> 4) & 0xF); mydata->internal_file_start = halt_offset + manifest_len + 4; mydata->halt_offset = halt_offset; mydata->flags = manifest_flags; endbuffer = strrchr(mydata->fname, '/'); if (endbuffer) { mydata->ext = memchr(endbuffer, '.', (mydata->fname + fname_len) - endbuffer); if (mydata->ext == endbuffer) { mydata->ext = memchr(endbuffer + 1, '.', (mydata->fname + fname_len) - endbuffer - 1); } if (mydata->ext) { mydata->ext_len = (mydata->fname + mydata->fname_len) - mydata->ext; } } mydata->alias = alias ? pestrndup(alias, alias_len, mydata->is_persistent) : pestrndup(mydata->fname, fname_len, mydata->is_persistent); mydata->alias_len = alias ? alias_len : fname_len; mydata->sig_flags = sig_flags; mydata->fp = fp; mydata->sig_len = sig_len; mydata->signature = signature; phar_request_initialize(TSRMLS_C); if (register_alias) { phar_archive_data **fd_ptr; mydata->is_temporary_alias = temp_alias; if (!phar_validate_alias(mydata->alias, mydata->alias_len)) { signature = NULL; fp = NULL; MAPPHAR_FAIL("Cannot open archive \"%s\", invalid alias"); } if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) { if (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) { signature = NULL; fp = NULL; MAPPHAR_FAIL("Cannot open archive \"%s\", alias is already in use by existing archive"); } } zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&mydata, sizeof(phar_archive_data*), NULL); } else { mydata->is_temporary_alias = 1; } zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len, (void*)&mydata, sizeof(phar_archive_data*), NULL); efree(savebuf); if (pphar) { *pphar = mydata; } return SUCCESS; } /* }}} */ /** * Create or open a phar for writing */ int phar_open_or_create_filename(char *fname, int fname_len, char *alias, int alias_len, int is_data, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { const char *ext_str, *z; char *my_error; int ext_len; phar_archive_data **test, *unused = NULL; test = &unused; if (error) { *error = NULL; } /* first try to open an existing file */ if (phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, !is_data, 0, 1 TSRMLS_CC) == SUCCESS) { goto check_file; } /* next try to create a new file */ if (FAILURE == phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, !is_data, 1, 1 TSRMLS_CC)) { if (error) { if (ext_len == -2) { spprintf(error, 0, "Cannot create a phar archive from a URL like \"%s\". Phar objects can only be created from local files", fname); } else { spprintf(error, 0, "Cannot create phar '%s', file extension (or combination) not recognised", fname); } } return FAILURE; } check_file: if (phar_open_parsed_phar(fname, fname_len, alias, alias_len, is_data, options, test, &my_error TSRMLS_CC) == SUCCESS) { if (pphar) { *pphar = *test; } if ((*test)->is_data && !(*test)->is_tar && !(*test)->is_zip) { if (error) { spprintf(error, 0, "Cannot open '%s' as a PharData object. Use Phar::__construct() for executable archives", fname); } return FAILURE; } if (PHAR_G(readonly) && !(*test)->is_data && ((*test)->is_tar || (*test)->is_zip)) { phar_entry_info *stub; if (FAILURE == zend_hash_find(&((*test)->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1, (void **)&stub)) { spprintf(error, 0, "'%s' is not a phar archive. Use PharData::__construct() for a standard zip or tar archive", fname); return FAILURE; } } if (!PHAR_G(readonly) || (*test)->is_data) { (*test)->is_writeable = 1; } return SUCCESS; } else if (my_error) { if (error) { *error = my_error; } else { efree(my_error); } return FAILURE; } if (ext_len > 3 && (z = memchr(ext_str, 'z', ext_len)) && ((ext_str + ext_len) - z >= 2) && !memcmp(z + 1, "ip", 2)) { /* assume zip-based phar */ return phar_open_or_create_zip(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC); } if (ext_len > 3 && (z = memchr(ext_str, 't', ext_len)) && ((ext_str + ext_len) - z >= 2) && !memcmp(z + 1, "ar", 2)) { /* assume tar-based phar */ return phar_open_or_create_tar(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC); } return phar_create_or_parse_filename(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC); } /* }}} */ int phar_create_or_parse_filename(char *fname, int fname_len, char *alias, int alias_len, int is_data, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { phar_archive_data *mydata; php_stream *fp; char *actual = NULL, *p; if (!pphar) { pphar = &mydata; } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { return FAILURE; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { return FAILURE; } /* first open readonly so it won't be created if not present */ fp = php_stream_open_wrapper(fname, "rb", IGNORE_URL|STREAM_MUST_SEEK|0, &actual); if (actual) { fname = actual; fname_len = strlen(actual); } if (fp) { if (phar_open_from_fp(fp, fname, fname_len, alias, alias_len, options, pphar, is_data, error TSRMLS_CC) == SUCCESS) { if ((*pphar)->is_data || !PHAR_G(readonly)) { (*pphar)->is_writeable = 1; } if (actual) { efree(actual); } return SUCCESS; } else { /* file exists, but is either corrupt or not a phar archive */ if (actual) { efree(actual); } return FAILURE; } } if (actual) { efree(actual); } if (PHAR_G(readonly) && !is_data) { if (options & REPORT_ERRORS) { if (error) { spprintf(error, 0, "creating archive \"%s\" disabled by the php.ini setting phar.readonly", fname); } } return FAILURE; } /* set up our manifest */ mydata = ecalloc(1, sizeof(phar_archive_data)); mydata->fname = expand_filepath(fname, NULL TSRMLS_CC); fname_len = strlen(mydata->fname); #ifdef PHP_WIN32 phar_unixify_path_separators(mydata->fname, fname_len); #endif p = strrchr(mydata->fname, '/'); if (p) { mydata->ext = memchr(p, '.', (mydata->fname + fname_len) - p); if (mydata->ext == p) { mydata->ext = memchr(p + 1, '.', (mydata->fname + fname_len) - p - 1); } if (mydata->ext) { mydata->ext_len = (mydata->fname + fname_len) - mydata->ext; } } if (pphar) { *pphar = mydata; } zend_hash_init(&mydata->manifest, sizeof(phar_entry_info), zend_get_hash_value, destroy_phar_manifest_entry, 0); zend_hash_init(&mydata->mounted_dirs, sizeof(char *), zend_get_hash_value, NULL, 0); zend_hash_init(&mydata->virtual_dirs, sizeof(char *), zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); mydata->fname_len = fname_len; snprintf(mydata->version, sizeof(mydata->version), "%s", PHP_PHAR_API_VERSION); mydata->is_temporary_alias = alias ? 0 : 1; mydata->internal_file_start = -1; mydata->fp = NULL; mydata->is_writeable = 1; mydata->is_brandnew = 1; phar_request_initialize(TSRMLS_C); zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len, (void*)&mydata, sizeof(phar_archive_data*), NULL); if (is_data) { alias = NULL; alias_len = 0; mydata->is_data = 1; /* assume tar format, PharData can specify other */ mydata->is_tar = 1; } else { phar_archive_data **fd_ptr; if (alias && SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) { if (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) { if (error) { spprintf(error, 4096, "phar error: phar \"%s\" cannot set alias \"%s\", already in use by another phar archive", mydata->fname, alias); } zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len); if (pphar) { *pphar = NULL; } return FAILURE; } } mydata->alias = alias ? estrndup(alias, alias_len) : estrndup(mydata->fname, fname_len); mydata->alias_len = alias ? alias_len : fname_len; } if (alias_len && alias) { if (FAILURE == zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&mydata, sizeof(phar_archive_data*), NULL)) { if (options & REPORT_ERRORS) { if (error) { spprintf(error, 0, "archive \"%s\" cannot be associated with alias \"%s\", already in use", fname, alias); } } zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len); if (pphar) { *pphar = NULL; } return FAILURE; } } return SUCCESS; } /* }}}*/ /** * Return an already opened filename. * * Or scan a phar file for the required __HALT_COMPILER(); ?> token and verify * that the manifest is proper, then pass it to phar_parse_pharfile(). SUCCESS * or FAILURE is returned and pphar is set to a pointer to the phar's manifest */ int phar_open_from_filename(char *fname, int fname_len, char *alias, int alias_len, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { php_stream *fp; char *actual; int ret, is_data = 0; if (error) { *error = NULL; } if (!strstr(fname, ".phar")) { is_data = 1; } if (phar_open_parsed_phar(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC) == SUCCESS) { return SUCCESS; } else if (error && *error) { return FAILURE; } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { return FAILURE; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { return FAILURE; } fp = php_stream_open_wrapper(fname, "rb", IGNORE_URL|STREAM_MUST_SEEK, &actual); if (!fp) { if (options & REPORT_ERRORS) { if (error) { spprintf(error, 0, "unable to open phar for reading \"%s\"", fname); } } if (actual) { efree(actual); } return FAILURE; } if (actual) { fname = actual; fname_len = strlen(actual); } ret = phar_open_from_fp(fp, fname, fname_len, alias, alias_len, options, pphar, is_data, error TSRMLS_CC); if (actual) { efree(actual); } return ret; } /* }}}*/ static inline char *phar_strnstr(const char *buf, int buf_len, const char *search, int search_len) /* {{{ */ { const char *c; int so_far = 0; if (buf_len < search_len) { return NULL; } c = buf - 1; do { if (!(c = memchr(c + 1, search[0], buf_len - search_len - so_far))) { return (char *) NULL; } so_far = c - buf; if (so_far >= (buf_len - search_len)) { return (char *) NULL; } if (!memcmp(c, search, search_len)) { return (char *) c; } } while (1); } /* }}} */ /** * Scan an open fp for the required __HALT_COMPILER(); ?> token and verify * that the manifest is proper, then pass it to phar_parse_pharfile(). SUCCESS * or FAILURE is returned and pphar is set to a pointer to the phar's manifest */ static int phar_open_from_fp(php_stream* fp, char *fname, int fname_len, char *alias, int alias_len, int options, phar_archive_data** pphar, int is_data, char **error TSRMLS_DC) /* {{{ */ { const char token[] = "__HALT_COMPILER();"; const char zip_magic[] = "PK\x03\x04"; const char gz_magic[] = "\x1f\x8b\x08"; const char bz_magic[] = "BZh"; char *pos, buffer[1024 + sizeof(token)], test = '\0'; const long readsize = sizeof(buffer) - sizeof(token); const long tokenlen = sizeof(token) - 1; long halt_offset; size_t got; php_uint32 compression = PHAR_FILE_COMPRESSED_NONE; if (error) { *error = NULL; } if (-1 == php_stream_rewind(fp)) { MAPPHAR_ALLOC_FAIL("cannot rewind phar \"%s\"") } buffer[sizeof(buffer)-1] = '\0'; memset(buffer, 32, sizeof(token)); halt_offset = 0; /* Maybe it's better to compile the file instead of just searching, */ /* but we only want the offset. So we want a .re scanner to find it. */ while(!php_stream_eof(fp)) { if ((got = php_stream_read(fp, buffer+tokenlen, readsize)) < (size_t) tokenlen) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated entry)") } if (!test) { test = '\1'; pos = buffer+tokenlen; if (!memcmp(pos, gz_magic, 3)) { char err = 0; php_stream_filter *filter; php_stream *temp; /* to properly decompress, we have to tell zlib to look for a zlib or gzip header */ zval filterparams; if (!PHAR_G(has_zlib)) { MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\" to temporary file, enable zlib extension in php.ini") } array_init(&filterparams); /* this is defined in zlib's zconf.h */ #ifndef MAX_WBITS #define MAX_WBITS 15 #endif add_assoc_long(&filterparams, "window", MAX_WBITS + 32); /* entire file is gzip-compressed, uncompress to temporary file */ if (!(temp = php_stream_fopen_tmpfile())) { MAPPHAR_ALLOC_FAIL("unable to create temporary file for decompression of gzipped phar archive \"%s\"") } php_stream_rewind(fp); filter = php_stream_filter_create("zlib.inflate", &filterparams, php_stream_is_persistent(fp) TSRMLS_CC); if (!filter) { err = 1; add_assoc_long(&filterparams, "window", MAX_WBITS); filter = php_stream_filter_create("zlib.inflate", &filterparams, php_stream_is_persistent(fp) TSRMLS_CC); zval_dtor(&filterparams); if (!filter) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\", ext/zlib is buggy in PHP versions older than 5.2.6") } } else { zval_dtor(&filterparams); } php_stream_filter_append(&temp->writefilters, filter); if (SUCCESS != phar_stream_copy_to_stream(fp, temp, PHP_STREAM_COPY_ALL, NULL)) { if (err) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\", ext/zlib is buggy in PHP versions older than 5.2.6") } php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\" to temporary file") } php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(fp); fp = temp; php_stream_rewind(fp); compression = PHAR_FILE_COMPRESSED_GZ; /* now, start over */ test = '\0'; continue; } else if (!memcmp(pos, bz_magic, 3)) { php_stream_filter *filter; php_stream *temp; if (!PHAR_G(has_bz2)) { MAPPHAR_ALLOC_FAIL("unable to decompress bzipped phar archive \"%s\" to temporary file, enable bz2 extension in php.ini") } /* entire file is bzip-compressed, uncompress to temporary file */ if (!(temp = php_stream_fopen_tmpfile())) { MAPPHAR_ALLOC_FAIL("unable to create temporary file for decompression of bzipped phar archive \"%s\"") } php_stream_rewind(fp); filter = php_stream_filter_create("bzip2.decompress", NULL, php_stream_is_persistent(fp) TSRMLS_CC); if (!filter) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress bzipped phar archive \"%s\", filter creation failed") } php_stream_filter_append(&temp->writefilters, filter); if (SUCCESS != phar_stream_copy_to_stream(fp, temp, PHP_STREAM_COPY_ALL, NULL)) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress bzipped phar archive \"%s\" to temporary file") } php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(fp); fp = temp; php_stream_rewind(fp); compression = PHAR_FILE_COMPRESSED_BZ2; /* now, start over */ test = '\0'; continue; } if (!memcmp(pos, zip_magic, 4)) { php_stream_seek(fp, 0, SEEK_END); return phar_parse_zipfile(fp, fname, fname_len, alias, alias_len, pphar, error TSRMLS_CC); } if (got > 512) { if (phar_is_tar(pos, fname)) { php_stream_rewind(fp); return phar_parse_tarfile(fp, fname, fname_len, alias, alias_len, pphar, is_data, compression, error TSRMLS_CC); } } } if (got > 0 && (pos = phar_strnstr(buffer, got + sizeof(token), token, sizeof(token)-1)) != NULL) { halt_offset += (pos - buffer); /* no -tokenlen+tokenlen here */ return phar_parse_pharfile(fp, fname, fname_len, alias, alias_len, halt_offset, pphar, compression, error TSRMLS_CC); } halt_offset += got; memmove(buffer, buffer + tokenlen, got + 1); } MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (__HALT_COMPILER(); not found)") } /* }}} */ /* * given the location of the file extension and the start of the file path, * determine the end of the portion of the path (i.e. /path/to/file.ext/blah * grabs "/path/to/file.ext" as does the straight /path/to/file.ext), * stat it to determine if it exists. * if so, check to see if it is a directory and fail if so * if not, check to see if its dirname() exists (i.e. "/path/to") and is a directory * succeed if we are creating the file, otherwise fail. */ static int phar_analyze_path(const char *fname, const char *ext, int ext_len, int for_create TSRMLS_DC) /* {{{ */ { php_stream_statbuf ssb; char *realpath; char *filename = estrndup(fname, (ext - fname) + ext_len); if ((realpath = expand_filepath(filename, NULL TSRMLS_CC))) { #ifdef PHP_WIN32 phar_unixify_path_separators(realpath, strlen(realpath)); #endif if (zend_hash_exists(&(PHAR_GLOBALS->phar_fname_map), realpath, strlen(realpath))) { efree(realpath); efree(filename); return SUCCESS; } if (PHAR_G(manifest_cached) && zend_hash_exists(&cached_phars, realpath, strlen(realpath))) { efree(realpath); efree(filename); return SUCCESS; } efree(realpath); } if (SUCCESS == php_stream_stat_path((char *) filename, &ssb)) { efree(filename); if (ssb.sb.st_mode & S_IFDIR) { return FAILURE; } if (for_create == 1) { return FAILURE; } return SUCCESS; } else { char *slash; if (!for_create) { efree(filename); return FAILURE; } slash = (char *) strrchr(filename, '/'); if (slash) { *slash = '\0'; } if (SUCCESS != php_stream_stat_path((char *) filename, &ssb)) { if (!slash) { if (!(realpath = expand_filepath(filename, NULL TSRMLS_CC))) { efree(filename); return FAILURE; } #ifdef PHP_WIN32 phar_unixify_path_separators(realpath, strlen(realpath)); #endif slash = strstr(realpath, filename) + ((ext - fname) + ext_len); *slash = '\0'; slash = strrchr(realpath, '/'); if (slash) { *slash = '\0'; } else { efree(realpath); efree(filename); return FAILURE; } if (SUCCESS != php_stream_stat_path(realpath, &ssb)) { efree(realpath); efree(filename); return FAILURE; } efree(realpath); if (ssb.sb.st_mode & S_IFDIR) { efree(filename); return SUCCESS; } } efree(filename); return FAILURE; } efree(filename); if (ssb.sb.st_mode & S_IFDIR) { return SUCCESS; } return FAILURE; } } /* }}} */ /* check for ".phar" in extension */ static int phar_check_str(const char *fname, const char *ext_str, int ext_len, int executable, int for_create TSRMLS_DC) /* {{{ */ { char test[51]; const char *pos; if (ext_len >= 50) { return FAILURE; } if (executable == 1) { /* copy "." as well */ memcpy(test, ext_str - 1, ext_len + 1); test[ext_len + 1] = '\0'; /* executable phars must contain ".phar" as a valid extension (phar://.pharmy/oops is invalid) */ /* (phar://hi/there/.phar/oops is also invalid) */ pos = strstr(test, ".phar"); if (pos && (*(pos - 1) != '/') && (pos += 5) && (*pos == '\0' || *pos == '/' || *pos == '.')) { return phar_analyze_path(fname, ext_str, ext_len, for_create TSRMLS_CC); } else { return FAILURE; } } /* data phars need only contain a single non-"." to be valid */ if (!executable) { pos = strstr(ext_str, ".phar"); if (!(pos && (*(pos - 1) != '/') && (pos += 5) && (*pos == '\0' || *pos == '/' || *pos == '.')) && *(ext_str + 1) != '.' && *(ext_str + 1) != '/' && *(ext_str + 1) != '\0') { return phar_analyze_path(fname, ext_str, ext_len, for_create TSRMLS_CC); } } else { if (*(ext_str + 1) != '.' && *(ext_str + 1) != '/' && *(ext_str + 1) != '\0') { return phar_analyze_path(fname, ext_str, ext_len, for_create TSRMLS_CC); } } return FAILURE; } /* }}} */ /* * if executable is 1, only returns SUCCESS if the extension is one of the tar/zip .phar extensions * if executable is 0, it returns SUCCESS only if the filename does *not* contain ".phar" anywhere, and treats * the first extension as the filename extension * * if an extension is found, it sets ext_str to the location of the file extension in filename, * and ext_len to the length of the extension. * for urls like "phar://alias/oops" it instead sets ext_len to -1 and returns FAILURE, which tells * the calling function to use "alias" as the phar alias * * the last parameter should be set to tell the thing to assume that filename is the full path, and only to check the * extension rules, not to iterate. */ int phar_detect_phar_fname_ext(const char *filename, int filename_len, const char **ext_str, int *ext_len, int executable, int for_create, int is_complete TSRMLS_DC) /* {{{ */ { const char *pos, *slash; *ext_str = NULL; *ext_len = 0; if (!filename_len || filename_len == 1) { return FAILURE; } phar_request_initialize(TSRMLS_C); /* first check for alias in first segment */ pos = memchr(filename, '/', filename_len); if (pos && pos != filename) { /* check for url like http:// or phar:// */ if (*(pos - 1) == ':' && (pos - filename) < filename_len - 1 && *(pos + 1) == '/') { *ext_len = -2; *ext_str = NULL; return FAILURE; } if (zend_hash_exists(&(PHAR_GLOBALS->phar_alias_map), (char *) filename, pos - filename)) { *ext_str = pos; *ext_len = -1; return FAILURE; } if (PHAR_G(manifest_cached) && zend_hash_exists(&cached_alias, (char *) filename, pos - filename)) { *ext_str = pos; *ext_len = -1; return FAILURE; } } if (zend_hash_num_elements(&(PHAR_GLOBALS->phar_fname_map)) || PHAR_G(manifest_cached)) { phar_archive_data **pphar; if (is_complete) { if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), (char *) filename, filename_len, (void **)&pphar)) { *ext_str = filename + (filename_len - (*pphar)->ext_len); woohoo: *ext_len = (*pphar)->ext_len; if (executable == 2) { return SUCCESS; } if (executable == 1 && !(*pphar)->is_data) { return SUCCESS; } if (!executable && (*pphar)->is_data) { return SUCCESS; } return FAILURE; } if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, (char *) filename, filename_len, (void **)&pphar)) { *ext_str = filename + (filename_len - (*pphar)->ext_len); goto woohoo; } } else { phar_zstr key; char *str_key; uint keylen; ulong unused; zend_hash_internal_pointer_reset(&(PHAR_GLOBALS->phar_fname_map)); while (FAILURE != zend_hash_has_more_elements(&(PHAR_GLOBALS->phar_fname_map))) { if (HASH_KEY_NON_EXISTANT == zend_hash_get_current_key_ex(&(PHAR_GLOBALS->phar_fname_map), &key, &keylen, &unused, 0, NULL)) { break; } PHAR_STR(key, str_key); if (keylen > (uint) filename_len) { zend_hash_move_forward(&(PHAR_GLOBALS->phar_fname_map)); PHAR_STR_FREE(str_key); continue; } if (!memcmp(filename, str_key, keylen) && ((uint)filename_len == keylen || filename[keylen] == '/' || filename[keylen] == '\0')) { PHAR_STR_FREE(str_key); if (FAILURE == zend_hash_get_current_data(&(PHAR_GLOBALS->phar_fname_map), (void **) &pphar)) { break; } *ext_str = filename + (keylen - (*pphar)->ext_len); goto woohoo; } PHAR_STR_FREE(str_key); zend_hash_move_forward(&(PHAR_GLOBALS->phar_fname_map)); } if (PHAR_G(manifest_cached)) { zend_hash_internal_pointer_reset(&cached_phars); while (FAILURE != zend_hash_has_more_elements(&cached_phars)) { if (HASH_KEY_NON_EXISTANT == zend_hash_get_current_key_ex(&cached_phars, &key, &keylen, &unused, 0, NULL)) { break; } PHAR_STR(key, str_key); if (keylen > (uint) filename_len) { zend_hash_move_forward(&cached_phars); PHAR_STR_FREE(str_key); continue; } if (!memcmp(filename, str_key, keylen) && ((uint)filename_len == keylen || filename[keylen] == '/' || filename[keylen] == '\0')) { PHAR_STR_FREE(str_key); if (FAILURE == zend_hash_get_current_data(&cached_phars, (void **) &pphar)) { break; } *ext_str = filename + (keylen - (*pphar)->ext_len); goto woohoo; } PHAR_STR_FREE(str_key); zend_hash_move_forward(&cached_phars); } } } } pos = memchr(filename + 1, '.', filename_len); next_extension: if (!pos) { return FAILURE; } while (pos != filename && (*(pos - 1) == '/' || *(pos - 1) == '\0')) { pos = memchr(pos + 1, '.', filename_len - (pos - filename) + 1); if (!pos) { return FAILURE; } } slash = memchr(pos, '/', filename_len - (pos - filename)); if (!slash) { /* this is a url like "phar://blah.phar" with no directory */ *ext_str = pos; *ext_len = strlen(pos); /* file extension must contain "phar" */ switch (phar_check_str(filename, *ext_str, *ext_len, executable, for_create TSRMLS_CC)) { case SUCCESS: return SUCCESS; case FAILURE: /* we are at the end of the string, so we fail */ return FAILURE; } } /* we've found an extension that ends at a directory separator */ *ext_str = pos; *ext_len = slash - pos; switch (phar_check_str(filename, *ext_str, *ext_len, executable, for_create TSRMLS_CC)) { case SUCCESS: return SUCCESS; case FAILURE: /* look for more extensions */ pos = strchr(pos + 1, '.'); if (pos) { *ext_str = NULL; *ext_len = 0; } goto next_extension; } return FAILURE; } /* }}} */ static int php_check_dots(const char *element, int n) /* {{{ */ { for(n--; n >= 0; --n) { if (element[n] != '.') { return 1; } } return 0; } /* }}} */ #define IS_DIRECTORY_UP(element, len) \ (len >= 2 && !php_check_dots(element, len)) #define IS_DIRECTORY_CURRENT(element, len) \ (len == 1 && element[0] == '.') #define IS_BACKSLASH(c) ((c) == '/') #ifdef COMPILE_DL_PHAR /* stupid-ass non-extern declaration in tsrm_strtok.h breaks dumbass MS compiler */ static inline int in_character_class(char ch, const char *delim) /* {{{ */ { while (*delim) { if (*delim == ch) { return 1; } ++delim; } return 0; } /* }}} */ char *tsrm_strtok_r(char *s, const char *delim, char **last) /* {{{ */ { char *token; if (s == NULL) { s = *last; } while (*s && in_character_class(*s, delim)) { ++s; } if (!*s) { return NULL; } token = s; while (*s && !in_character_class(*s, delim)) { ++s; } if (!*s) { *last = s; } else { *s = '\0'; *last = s + 1; } return token; } /* }}} */ #endif /** * Remove .. and . references within a phar filename */ char *phar_fix_filepath(char *path, int *new_len, int use_cwd TSRMLS_DC) /* {{{ */ { char newpath[MAXPATHLEN]; int newpath_len; char *ptr; char *tok; int ptr_length, path_length = *new_len; if (PHAR_G(cwd_len) && use_cwd && path_length > 2 && path[0] == '.' && path[1] == '/') { newpath_len = PHAR_G(cwd_len); memcpy(newpath, PHAR_G(cwd), newpath_len); } else { newpath[0] = '/'; newpath_len = 1; } ptr = path; if (*ptr == '/') { ++ptr; } tok = ptr; do { ptr = memchr(ptr, '/', path_length - (ptr - path)); } while (ptr && ptr - tok == 0 && *ptr == '/' && ++ptr && ++tok); if (!ptr && (path_length - (tok - path))) { switch (path_length - (tok - path)) { case 1: if (*tok == '.') { efree(path); *new_len = 1; return estrndup("/", 1); } break; case 2: if (tok[0] == '.' && tok[1] == '.') { efree(path); *new_len = 1; return estrndup("/", 1); } } return path; } while (ptr) { ptr_length = ptr - tok; last_time: if (IS_DIRECTORY_UP(tok, ptr_length)) { #define PREVIOUS newpath[newpath_len - 1] while (newpath_len > 1 && !IS_BACKSLASH(PREVIOUS)) { newpath_len--; } if (newpath[0] != '/') { newpath[newpath_len] = '\0'; } else if (newpath_len > 1) { --newpath_len; } } else if (!IS_DIRECTORY_CURRENT(tok, ptr_length)) { if (newpath_len > 1) { newpath[newpath_len++] = '/'; memcpy(newpath + newpath_len, tok, ptr_length+1); } else { memcpy(newpath + newpath_len, tok, ptr_length+1); } newpath_len += ptr_length; } if (ptr == path + path_length) { break; } tok = ++ptr; do { ptr = memchr(ptr, '/', path_length - (ptr - path)); } while (ptr && ptr - tok == 0 && *ptr == '/' && ++ptr && ++tok); if (!ptr && (path_length - (tok - path))) { ptr_length = path_length - (tok - path); ptr = path + path_length; goto last_time; } } efree(path); *new_len = newpath_len; return estrndup(newpath, newpath_len); } /* }}} */ /** * Process a phar stream name, ensuring we can handle any of: * * - whatever.phar * - whatever.phar.gz * - whatever.phar.bz2 * - whatever.phar.php * * Optionally the name might start with 'phar://' * * This is used by phar_parse_url() */ int phar_split_fname(char *filename, int filename_len, char **arch, int *arch_len, char **entry, int *entry_len, int executable, int for_create TSRMLS_DC) /* {{{ */ { const char *ext_str; #ifdef PHP_WIN32 char *save; #endif int ext_len, free_filename = 0; if (!strncasecmp(filename, "phar://", 7)) { filename += 7; filename_len -= 7; } ext_len = 0; #ifdef PHP_WIN32 free_filename = 1; save = filename; filename = estrndup(filename, filename_len); phar_unixify_path_separators(filename, filename_len); #endif if (phar_detect_phar_fname_ext(filename, filename_len, &ext_str, &ext_len, executable, for_create, 0 TSRMLS_CC) == FAILURE) { if (ext_len != -1) { if (!ext_str) { /* no / detected, restore arch for error message */ #ifdef PHP_WIN32 *arch = save; #else *arch = filename; #endif } if (free_filename) { efree(filename); } return FAILURE; } ext_len = 0; /* no extension detected - instead we are dealing with an alias */ } *arch_len = ext_str - filename + ext_len; *arch = estrndup(filename, *arch_len); if (ext_str[ext_len]) { *entry_len = filename_len - *arch_len; *entry = estrndup(ext_str+ext_len, *entry_len); #ifdef PHP_WIN32 phar_unixify_path_separators(*entry, *entry_len); #endif *entry = phar_fix_filepath(*entry, entry_len, 0 TSRMLS_CC); } else { *entry_len = 1; *entry = estrndup("/", 1); } if (free_filename) { efree(filename); } return SUCCESS; } /* }}} */ /** * Invoked when a user calls Phar::mapPhar() from within an executing .phar * to set up its manifest directly */ int phar_open_executed_filename(char *alias, int alias_len, char **error TSRMLS_DC) /* {{{ */ { char *fname; zval *halt_constant; php_stream *fp; int fname_len; char *actual = NULL; int ret; if (error) { *error = NULL; } fname = zend_get_executed_filename(TSRMLS_C); fname_len = strlen(fname); if (phar_open_parsed_phar(fname, fname_len, alias, alias_len, 0, REPORT_ERRORS, NULL, 0 TSRMLS_CC) == SUCCESS) { return SUCCESS; } if (!strcmp(fname, "[no active file]")) { if (error) { spprintf(error, 0, "cannot initialize a phar outside of PHP execution"); } return FAILURE; } MAKE_STD_ZVAL(halt_constant); if (0 == zend_get_constant("__COMPILER_HALT_OFFSET__", 24, halt_constant TSRMLS_CC)) { FREE_ZVAL(halt_constant); if (error) { spprintf(error, 0, "__HALT_COMPILER(); must be declared in a phar"); } return FAILURE; } FREE_ZVAL(halt_constant); #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { return FAILURE; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { return FAILURE; } fp = php_stream_open_wrapper(fname, "rb", IGNORE_URL|STREAM_MUST_SEEK|REPORT_ERRORS, &actual); if (!fp) { if (error) { spprintf(error, 0, "unable to open phar for reading \"%s\"", fname); } if (actual) { efree(actual); } return FAILURE; } if (actual) { fname = actual; fname_len = strlen(actual); } ret = phar_open_from_fp(fp, fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, 0, error TSRMLS_CC); if (actual) { efree(actual); } return ret; } /* }}} */ /** * Validate the CRC32 of a file opened from within the phar */ int phar_postprocess_file(phar_entry_data *idata, php_uint32 crc32, char **error, int process_zip TSRMLS_DC) /* {{{ */ { php_uint32 crc = ~0; int len = idata->internal_file->uncompressed_filesize; php_stream *fp = idata->fp; phar_entry_info *entry = idata->internal_file; if (error) { *error = NULL; } if (entry->is_zip && process_zip > 0) { /* verify local file header */ phar_zip_file_header local; phar_zip_data_desc desc; if (SUCCESS != phar_open_archive_fp(idata->phar TSRMLS_CC)) { spprintf(error, 0, "phar error: unable to open zip-based phar archive \"%s\" to verify local file header for file \"%s\"", idata->phar->fname, entry->filename); return FAILURE; } php_stream_seek(phar_get_entrypfp(idata->internal_file TSRMLS_CC), entry->header_offset, SEEK_SET); if (sizeof(local) != php_stream_read(phar_get_entrypfp(idata->internal_file TSRMLS_CC), (char *) &local, sizeof(local))) { spprintf(error, 0, "phar error: internal corruption of zip-based phar \"%s\" (cannot read local file header for file \"%s\")", idata->phar->fname, entry->filename); return FAILURE; } /* check for data descriptor */ if (((PHAR_ZIP_16(local.flags)) & 0x8) == 0x8) { php_stream_seek(phar_get_entrypfp(idata->internal_file TSRMLS_CC), entry->header_offset + sizeof(local) + PHAR_ZIP_16(local.filename_len) + PHAR_ZIP_16(local.extra_len) + entry->compressed_filesize, SEEK_SET); if (sizeof(desc) != php_stream_read(phar_get_entrypfp(idata->internal_file TSRMLS_CC), (char *) &desc, sizeof(desc))) { spprintf(error, 0, "phar error: internal corruption of zip-based phar \"%s\" (cannot read local data descriptor for file \"%s\")", idata->phar->fname, entry->filename); return FAILURE; } if (desc.signature[0] == 'P' && desc.signature[1] == 'K') { memcpy(&(local.crc32), &(desc.crc32), 12); } else { /* old data descriptors have no signature */ memcpy(&(local.crc32), &desc, 12); } } /* verify local header */ if (entry->filename_len != PHAR_ZIP_16(local.filename_len) || entry->crc32 != PHAR_ZIP_32(local.crc32) || entry->uncompressed_filesize != PHAR_ZIP_32(local.uncompsize) || entry->compressed_filesize != PHAR_ZIP_32(local.compsize)) { spprintf(error, 0, "phar error: internal corruption of zip-based phar \"%s\" (local header of file \"%s\" does not match central directory)", idata->phar->fname, entry->filename); return FAILURE; } /* construct actual offset to file start - local extra_len can be different from central extra_len */ entry->offset = entry->offset_abs = sizeof(local) + entry->header_offset + PHAR_ZIP_16(local.filename_len) + PHAR_ZIP_16(local.extra_len); if (idata->zero && idata->zero != entry->offset_abs) { idata->zero = entry->offset_abs; } } if (process_zip == 1) { return SUCCESS; } php_stream_seek(fp, idata->zero, SEEK_SET); while (len--) { CRC32(crc, php_stream_getc(fp)); } php_stream_seek(fp, idata->zero, SEEK_SET); if (~crc == crc32) { entry->is_crc_checked = 1; return SUCCESS; } else { spprintf(error, 0, "phar error: internal corruption of phar \"%s\" (crc32 mismatch on file \"%s\")", idata->phar->fname, entry->filename); return FAILURE; } } /* }}} */ static inline void phar_set_32(char *buffer, int var) /* {{{ */ { #ifdef WORDS_BIGENDIAN *((buffer) + 3) = (unsigned char) (((var) >> 24) & 0xFF); *((buffer) + 2) = (unsigned char) (((var) >> 16) & 0xFF); *((buffer) + 1) = (unsigned char) (((var) >> 8) & 0xFF); *((buffer) + 0) = (unsigned char) ((var) & 0xFF); #else memcpy(buffer, &var, sizeof(var)); #endif } /* }}} */ static int phar_flush_clean_deleted_apply(void *data TSRMLS_DC) /* {{{ */ { phar_entry_info *entry = (phar_entry_info *)data; if (entry->fp_refcount <= 0 && entry->is_deleted) { return ZEND_HASH_APPLY_REMOVE; } else { return ZEND_HASH_APPLY_KEEP; } } /* }}} */ #include "stub.h" char *phar_create_default_stub(const char *index_php, const char *web_index, size_t *len, char **error TSRMLS_DC) /* {{{ */ { char *stub = NULL; int index_len, web_len; size_t dummy; if (!len) { len = &dummy; } if (error) { *error = NULL; } if (!index_php) { index_php = "index.php"; } if (!web_index) { web_index = "index.php"; } index_len = strlen(index_php); web_len = strlen(web_index); if (index_len > 400) { /* ridiculous size not allowed for index.php startup filename */ if (error) { spprintf(error, 0, "Illegal filename passed in for stub creation, was %d characters long, and only 400 or less is allowed", index_len); return NULL; } } if (web_len > 400) { /* ridiculous size not allowed for index.php startup filename */ if (error) { spprintf(error, 0, "Illegal web filename passed in for stub creation, was %d characters long, and only 400 or less is allowed", web_len); return NULL; } } phar_get_stub(index_php, web_index, len, &stub, index_len+1, web_len+1 TSRMLS_CC); return stub; } /* }}} */ /** * Save phar contents to disk * * user_stub contains either a string, or a resource pointer, if len is a negative length. * user_stub and len should be both 0 if the default or existing stub should be used */ int phar_flush(phar_archive_data *phar, char *user_stub, long len, int convert, char **error TSRMLS_DC) /* {{{ */ { char halt_stub[] = "__HALT_COMPILER();"; char *newstub, *tmp; phar_entry_info *entry, *newentry; int halt_offset, restore_alias_len, global_flags = 0, closeoldfile; char *pos, has_dirs = 0; char manifest[18], entry_buffer[24]; off_t manifest_ftell; long offset; size_t wrote; php_uint32 manifest_len, mytime, loc, new_manifest_count; php_uint32 newcrc32; php_stream *file, *oldfile, *newfile, *stubfile; php_stream_filter *filter; php_serialize_data_t metadata_hash; smart_str main_metadata_str = {0}; int free_user_stub, free_fp = 1, free_ufp = 1; if (phar->is_persistent) { if (error) { spprintf(error, 0, "internal error: attempt to flush cached zip-based phar \"%s\"", phar->fname); } return EOF; } if (error) { *error = NULL; } if (!zend_hash_num_elements(&phar->manifest) && !user_stub) { return EOF; } zend_hash_clean(&phar->virtual_dirs); if (phar->is_zip) { return phar_zip_flush(phar, user_stub, len, convert, error TSRMLS_CC); } if (phar->is_tar) { return phar_tar_flush(phar, user_stub, len, convert, error TSRMLS_CC); } if (PHAR_G(readonly)) { return EOF; } if (phar->fp && !phar->is_brandnew) { oldfile = phar->fp; closeoldfile = 0; php_stream_rewind(oldfile); } else { oldfile = php_stream_open_wrapper(phar->fname, "rb", 0, NULL); closeoldfile = oldfile != NULL; } newfile = php_stream_fopen_tmpfile(); if (!newfile) { if (error) { spprintf(error, 0, "unable to create temporary file"); } if (closeoldfile) { php_stream_close(oldfile); } return EOF; } if (user_stub) { if (len < 0) { /* resource passed in */ if (!(php_stream_from_zval_no_verify(stubfile, (zval **)user_stub))) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to access resource to copy stub to new phar \"%s\"", phar->fname); } return EOF; } if (len == -1) { len = PHP_STREAM_COPY_ALL; } else { len = -len; } user_stub = 0; #if PHP_MAJOR_VERSION >= 6 if (!(len = php_stream_copy_to_mem(stubfile, (void **) &user_stub, len, 0)) || !user_stub) { #else if (!(len = php_stream_copy_to_mem(stubfile, &user_stub, len, 0)) || !user_stub) { #endif if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to read resource to copy stub to new phar \"%s\"", phar->fname); } return EOF; } free_user_stub = 1; } else { free_user_stub = 0; } tmp = estrndup(user_stub, len); if ((pos = php_stristr(tmp, halt_stub, len, sizeof(halt_stub) - 1)) == NULL) { efree(tmp); if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "illegal stub for phar \"%s\"", phar->fname); } if (free_user_stub) { efree(user_stub); } return EOF; } pos = user_stub + (pos - tmp); efree(tmp); len = pos - user_stub + 18; if ((size_t)len != php_stream_write(newfile, user_stub, len) || 5 != php_stream_write(newfile, " ?>\r\n", 5)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to create stub from string in new phar \"%s\"", phar->fname); } if (free_user_stub) { efree(user_stub); } return EOF; } phar->halt_offset = len + 5; if (free_user_stub) { efree(user_stub); } } else { size_t written; if (!user_stub && phar->halt_offset && oldfile && !phar->is_brandnew) { phar_stream_copy_to_stream(oldfile, newfile, phar->halt_offset, &written); newstub = NULL; } else { /* this is either a brand new phar or a default stub overwrite */ newstub = phar_create_default_stub(NULL, NULL, &(phar->halt_offset), NULL TSRMLS_CC); written = php_stream_write(newfile, newstub, phar->halt_offset); } if (phar->halt_offset != written) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { if (newstub) { spprintf(error, 0, "unable to create stub in new phar \"%s\"", phar->fname); } else { spprintf(error, 0, "unable to copy stub of old phar to new phar \"%s\"", phar->fname); } } if (newstub) { efree(newstub); } return EOF; } if (newstub) { efree(newstub); } } manifest_ftell = php_stream_tell(newfile); halt_offset = manifest_ftell; /* Check whether we can get rid of some of the deleted entries which are * unused. However some might still be in use so even after this clean-up * we need to skip entries marked is_deleted. */ zend_hash_apply(&phar->manifest, phar_flush_clean_deleted_apply TSRMLS_CC); /* compress as necessary, calculate crcs, serialize meta-data, manifest size, and file sizes */ main_metadata_str.c = 0; if (phar->metadata) { PHP_VAR_SERIALIZE_INIT(metadata_hash); php_var_serialize(&main_metadata_str, &phar->metadata, &metadata_hash TSRMLS_CC); PHP_VAR_SERIALIZE_DESTROY(metadata_hash); } else { main_metadata_str.len = 0; } new_manifest_count = 0; offset = 0; for (zend_hash_internal_pointer_reset(&phar->manifest); zend_hash_has_more_elements(&phar->manifest) == SUCCESS; zend_hash_move_forward(&phar->manifest)) { if (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) { continue; } if (entry->cfp) { /* did we forget to get rid of cfp last time? */ php_stream_close(entry->cfp); entry->cfp = 0; } if (entry->is_deleted || entry->is_mounted) { /* remove this from the new phar */ continue; } if (!entry->is_modified && entry->fp_refcount) { /* open file pointers refer to this fp, do not free the stream */ switch (entry->fp_type) { case PHAR_FP: free_fp = 0; break; case PHAR_UFP: free_ufp = 0; default: break; } } /* after excluding deleted files, calculate manifest size in bytes and number of entries */ ++new_manifest_count; phar_add_virtual_dirs(phar, entry->filename, entry->filename_len TSRMLS_CC); if (entry->is_dir) { /* we use this to calculate API version, 1.1.1 is used for phars with directories */ has_dirs = 1; } if (entry->metadata) { if (entry->metadata_str.c) { smart_str_free(&entry->metadata_str); } entry->metadata_str.c = 0; entry->metadata_str.len = 0; PHP_VAR_SERIALIZE_INIT(metadata_hash); php_var_serialize(&entry->metadata_str, &entry->metadata, &metadata_hash TSRMLS_CC); PHP_VAR_SERIALIZE_DESTROY(metadata_hash); } else { if (entry->metadata_str.c) { smart_str_free(&entry->metadata_str); } entry->metadata_str.c = 0; entry->metadata_str.len = 0; } /* 32 bits for filename length, length of filename, manifest + metadata, and add 1 for trailing / if a directory */ offset += 4 + entry->filename_len + sizeof(entry_buffer) + entry->metadata_str.len + (entry->is_dir ? 1 : 0); /* compress and rehash as necessary */ if ((oldfile && !entry->is_modified) || entry->is_dir) { if (entry->fp_type == PHAR_UFP) { /* reset so we can copy the compressed data over */ entry->fp_type = PHAR_FP; } continue; } if (!phar_get_efp(entry, 0 TSRMLS_CC)) { /* re-open internal file pointer just-in-time */ newentry = phar_open_jit(phar, entry, error TSRMLS_CC); if (!newentry) { /* major problem re-opening, so we ignore this file and the error */ efree(*error); *error = NULL; continue; } entry = newentry; } file = phar_get_efp(entry, 0 TSRMLS_CC); if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 1 TSRMLS_CC)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } newcrc32 = ~0; mytime = entry->uncompressed_filesize; for (loc = 0;loc < mytime; ++loc) { CRC32(newcrc32, php_stream_getc(file)); } entry->crc32 = ~newcrc32; entry->is_crc_checked = 1; if (!(entry->flags & PHAR_ENT_COMPRESSION_MASK)) { /* not compressed */ entry->compressed_filesize = entry->uncompressed_filesize; continue; } filter = php_stream_filter_create(phar_compress_filter(entry, 0), NULL, 0 TSRMLS_CC); if (!filter) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (entry->flags & PHAR_ENT_COMPRESSED_GZ) { if (error) { spprintf(error, 0, "unable to gzip compress file \"%s\" to new phar \"%s\"", entry->filename, phar->fname); } } else { if (error) { spprintf(error, 0, "unable to bzip2 compress file \"%s\" to new phar \"%s\"", entry->filename, phar->fname); } } return EOF; } /* create new file that holds the compressed version */ /* work around inability to specify freedom in write and strictness in read count */ entry->cfp = php_stream_fopen_tmpfile(); if (!entry->cfp) { if (error) { spprintf(error, 0, "unable to create temporary file"); } if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); return EOF; } php_stream_flush(file); if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 0 TSRMLS_CC)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } php_stream_filter_append((&entry->cfp->writefilters), filter); if (SUCCESS != phar_stream_copy_to_stream(file, entry->cfp, entry->uncompressed_filesize, NULL)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to copy compressed file contents of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } php_stream_filter_flush(filter, 1); php_stream_flush(entry->cfp); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_seek(entry->cfp, 0, SEEK_END); entry->compressed_filesize = (php_uint32) php_stream_tell(entry->cfp); /* generate crc on compressed file */ php_stream_rewind(entry->cfp); entry->old_flags = entry->flags; entry->is_modified = 1; global_flags |= (entry->flags & PHAR_ENT_COMPRESSION_MASK); } global_flags |= PHAR_HDR_SIGNATURE; /* write out manifest pre-header */ /* 4: manifest length * 4: manifest entry count * 2: phar version * 4: phar global flags * 4: alias length * ?: the alias itself * 4: phar metadata length * ?: phar metadata */ restore_alias_len = phar->alias_len; if (phar->is_temporary_alias) { phar->alias_len = 0; } manifest_len = offset + phar->alias_len + sizeof(manifest) + main_metadata_str.len; phar_set_32(manifest, manifest_len); phar_set_32(manifest+4, new_manifest_count); if (has_dirs) { *(manifest + 8) = (unsigned char) (((PHAR_API_VERSION) >> 8) & 0xFF); *(manifest + 9) = (unsigned char) (((PHAR_API_VERSION) & 0xF0)); } else { *(manifest + 8) = (unsigned char) (((PHAR_API_VERSION_NODIR) >> 8) & 0xFF); *(manifest + 9) = (unsigned char) (((PHAR_API_VERSION_NODIR) & 0xF0)); } phar_set_32(manifest+10, global_flags); phar_set_32(manifest+14, phar->alias_len); /* write the manifest header */ if (sizeof(manifest) != php_stream_write(newfile, manifest, sizeof(manifest)) || (size_t)phar->alias_len != php_stream_write(newfile, phar->alias, phar->alias_len)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); phar->alias_len = restore_alias_len; if (error) { spprintf(error, 0, "unable to write manifest header of new phar \"%s\"", phar->fname); } return EOF; } phar->alias_len = restore_alias_len; phar_set_32(manifest, main_metadata_str.len); if (4 != php_stream_write(newfile, manifest, 4) || (main_metadata_str.len && main_metadata_str.len != php_stream_write(newfile, main_metadata_str.c, main_metadata_str.len))) { smart_str_free(&main_metadata_str); if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); phar->alias_len = restore_alias_len; if (error) { spprintf(error, 0, "unable to write manifest meta-data of new phar \"%s\"", phar->fname); } return EOF; } smart_str_free(&main_metadata_str); /* re-calculate the manifest location to simplify later code */ manifest_ftell = php_stream_tell(newfile); /* now write the manifest */ for (zend_hash_internal_pointer_reset(&phar->manifest); zend_hash_has_more_elements(&phar->manifest) == SUCCESS; zend_hash_move_forward(&phar->manifest)) { if (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) { continue; } if (entry->is_deleted || entry->is_mounted) { /* remove this from the new phar if deleted, ignore if mounted */ continue; } if (entry->is_dir) { /* add 1 for trailing slash */ phar_set_32(entry_buffer, entry->filename_len + 1); } else { phar_set_32(entry_buffer, entry->filename_len); } if (4 != php_stream_write(newfile, entry_buffer, 4) || entry->filename_len != php_stream_write(newfile, entry->filename, entry->filename_len) || (entry->is_dir && 1 != php_stream_write(newfile, "/", 1))) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { if (entry->is_dir) { spprintf(error, 0, "unable to write filename of directory \"%s\" to manifest of new phar \"%s\"", entry->filename, phar->fname); } else { spprintf(error, 0, "unable to write filename of file \"%s\" to manifest of new phar \"%s\"", entry->filename, phar->fname); } } return EOF; } /* set the manifest meta-data: 4: uncompressed filesize 4: creation timestamp 4: compressed filesize 4: crc32 4: flags 4: metadata-len +: metadata */ mytime = time(NULL); phar_set_32(entry_buffer, entry->uncompressed_filesize); phar_set_32(entry_buffer+4, mytime); phar_set_32(entry_buffer+8, entry->compressed_filesize); phar_set_32(entry_buffer+12, entry->crc32); phar_set_32(entry_buffer+16, entry->flags); phar_set_32(entry_buffer+20, entry->metadata_str.len); if (sizeof(entry_buffer) != php_stream_write(newfile, entry_buffer, sizeof(entry_buffer)) || entry->metadata_str.len != php_stream_write(newfile, entry->metadata_str.c, entry->metadata_str.len)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to write temporary manifest of file \"%s\" to manifest of new phar \"%s\"", entry->filename, phar->fname); } return EOF; } } /* now copy the actual file data to the new phar */ offset = php_stream_tell(newfile); for (zend_hash_internal_pointer_reset(&phar->manifest); zend_hash_has_more_elements(&phar->manifest) == SUCCESS; zend_hash_move_forward(&phar->manifest)) { if (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) { continue; } if (entry->is_deleted || entry->is_dir || entry->is_mounted) { continue; } if (entry->cfp) { file = entry->cfp; php_stream_rewind(file); } else { file = phar_get_efp(entry, 0 TSRMLS_CC); if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 0 TSRMLS_CC)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } } if (!file) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } /* this will have changed for all files that have either changed compression or been modified */ entry->offset = entry->offset_abs = offset; offset += entry->compressed_filesize; phar_stream_copy_to_stream(file, newfile, entry->compressed_filesize, &wrote); if (entry->compressed_filesize != wrote) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to write contents of file \"%s\" to new phar \"%s\"", entry->filename, phar->fname); } return EOF; } entry->is_modified = 0; if (entry->cfp) { php_stream_close(entry->cfp); entry->cfp = NULL; } if (entry->fp_type == PHAR_MOD) { /* this fp is in use by a phar_entry_data returned by phar_get_entry_data, it will be closed when the phar_entry_data is phar_entry_delref'ed */ if (entry->fp_refcount == 0 && entry->fp != phar->fp && entry->fp != phar->ufp) { php_stream_close(entry->fp); } entry->fp = NULL; entry->fp_type = PHAR_FP; } else if (entry->fp_type == PHAR_UFP) { entry->fp_type = PHAR_FP; } } /* append signature */ if (global_flags & PHAR_HDR_SIGNATURE) { char sig_buf[4]; php_stream_rewind(newfile); if (phar->signature) { efree(phar->signature); phar->signature = NULL; } switch(phar->sig_flags) { #ifndef PHAR_HASH_OK case PHAR_SIG_SHA512: case PHAR_SIG_SHA256: if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to write contents of file \"%s\" to new phar \"%s\" with requested hash type", entry->filename, phar->fname); } return EOF; #endif default: { char *digest = NULL; int digest_len; if (FAILURE == phar_create_signature(phar, newfile, &digest, &digest_len, error TSRMLS_CC)) { if (error) { char *save = *error; spprintf(error, 0, "phar error: unable to write signature: %s", save); efree(save); } if (digest) { efree(digest); } if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); return EOF; } php_stream_write(newfile, digest, digest_len); efree(digest); if (phar->sig_flags == PHAR_SIG_OPENSSL) { phar_set_32(sig_buf, digest_len); php_stream_write(newfile, sig_buf, 4); } break; } } phar_set_32(sig_buf, phar->sig_flags); php_stream_write(newfile, sig_buf, 4); php_stream_write(newfile, "GBMB", 4); } /* finally, close the temp file, rename the original phar, move the temp to the old phar, unlink the old phar, and reload it into memory */ if (phar->fp && free_fp) { php_stream_close(phar->fp); } if (phar->ufp) { if (free_ufp) { php_stream_close(phar->ufp); } phar->ufp = NULL; } if (closeoldfile) { php_stream_close(oldfile); } phar->internal_file_start = halt_offset + manifest_len + 4; phar->halt_offset = halt_offset; phar->is_brandnew = 0; php_stream_rewind(newfile); if (phar->donotflush) { /* deferred flush */ phar->fp = newfile; } else { phar->fp = php_stream_open_wrapper(phar->fname, "w+b", IGNORE_URL|STREAM_MUST_SEEK|REPORT_ERRORS, NULL); if (!phar->fp) { phar->fp = newfile; if (error) { spprintf(error, 4096, "unable to open new phar \"%s\" for writing", phar->fname); } return EOF; } if (phar->flags & PHAR_FILE_COMPRESSED_GZ) { /* to properly compress, we have to tell zlib to add a zlib header */ zval filterparams; array_init(&filterparams); add_assoc_long(&filterparams, "window", MAX_WBITS+16); filter = php_stream_filter_create("zlib.deflate", &filterparams, php_stream_is_persistent(phar->fp) TSRMLS_CC); zval_dtor(&filterparams); if (!filter) { if (error) { spprintf(error, 4096, "unable to compress all contents of phar \"%s\" using zlib, PHP versions older than 5.2.6 have a buggy zlib", phar->fname); } return EOF; } php_stream_filter_append(&phar->fp->writefilters, filter); phar_stream_copy_to_stream(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL); php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(phar->fp); /* use the temp stream as our base */ phar->fp = newfile; } else if (phar->flags & PHAR_FILE_COMPRESSED_BZ2) { filter = php_stream_filter_create("bzip2.compress", NULL, php_stream_is_persistent(phar->fp) TSRMLS_CC); php_stream_filter_append(&phar->fp->writefilters, filter); phar_stream_copy_to_stream(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL); php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(phar->fp); /* use the temp stream as our base */ phar->fp = newfile; } else { phar_stream_copy_to_stream(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL); /* we could also reopen the file in "rb" mode but there is no need for that */ php_stream_close(newfile); } } if (-1 == php_stream_seek(phar->fp, phar->halt_offset, SEEK_SET)) { if (error) { spprintf(error, 0, "unable to seek to __HALT_COMPILER(); in new phar \"%s\"", phar->fname); } return EOF; } return EOF; } /* }}} */ #ifdef COMPILE_DL_PHAR ZEND_GET_MODULE(phar) #endif /* {{{ phar_functions[] * * Every user visible function must have an entry in phar_functions[]. */ zend_function_entry phar_functions[] = { {NULL, NULL, NULL} /* Must be the last line in phar_functions[] */ }; /* }}}*/ static size_t phar_zend_stream_reader(void *handle, char *buf, size_t len TSRMLS_DC) /* {{{ */ { return php_stream_read(phar_get_pharfp((phar_archive_data*)handle TSRMLS_CC), buf, len); } /* }}} */ #if PHP_VERSION_ID >= 50300 static size_t phar_zend_stream_fsizer(void *handle TSRMLS_DC) /* {{{ */ { return ((phar_archive_data*)handle)->halt_offset + 32; } /* }}} */ #else /* PHP_VERSION_ID */ static long phar_stream_fteller_for_zend(void *handle TSRMLS_DC) /* {{{ */ { return (long)php_stream_tell(phar_get_pharfp((phar_archive_data*)handle TSRMLS_CC)); } /* }}} */ #endif zend_op_array *(*phar_orig_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); #if PHP_VERSION_ID >= 50300 #define phar_orig_zend_open zend_stream_open_function static char *phar_resolve_path(const char *filename, int filename_len TSRMLS_DC) { return phar_find_in_include_path((char *) filename, filename_len, NULL TSRMLS_CC); } #else int (*phar_orig_zend_open)(const char *filename, zend_file_handle *handle TSRMLS_DC); #endif static zend_op_array *phar_compile_file(zend_file_handle *file_handle, int type TSRMLS_DC) /* {{{ */ { zend_op_array *res; char *name = NULL; int failed; phar_archive_data *phar; if (!file_handle || !file_handle->filename) { return phar_orig_compile_file(file_handle, type TSRMLS_CC); } if (strstr(file_handle->filename, ".phar") && !strstr(file_handle->filename, "://")) { if (SUCCESS == phar_open_from_filename(file_handle->filename, strlen(file_handle->filename), NULL, 0, 0, &phar, NULL TSRMLS_CC)) { if (phar->is_zip || phar->is_tar) { zend_file_handle f = *file_handle; /* zip or tar-based phar */ spprintf(&name, 4096, "phar://%s/%s", file_handle->filename, ".phar/stub.php"); if (SUCCESS == phar_orig_zend_open((const char *)name, file_handle TSRMLS_CC)) { efree(name); name = NULL; file_handle->filename = f.filename; if (file_handle->opened_path) { efree(file_handle->opened_path); } file_handle->opened_path = f.opened_path; file_handle->free_filename = f.free_filename; } else { *file_handle = f; } } else if (phar->flags & PHAR_FILE_COMPRESSION_MASK) { /* compressed phar */ #if PHP_VERSION_ID >= 50300 file_handle->type = ZEND_HANDLE_STREAM; /* we do our own reading directly from the phar, don't change the next line */ file_handle->handle.stream.handle = phar; file_handle->handle.stream.reader = phar_zend_stream_reader; file_handle->handle.stream.closer = NULL; file_handle->handle.stream.fsizer = phar_zend_stream_fsizer; file_handle->handle.stream.isatty = 0; phar->is_persistent ? php_stream_rewind(PHAR_GLOBALS->cached_fp[phar->phar_pos].fp) : php_stream_rewind(phar->fp); memset(&file_handle->handle.stream.mmap, 0, sizeof(file_handle->handle.stream.mmap)); #else /* PHP_VERSION_ID */ file_handle->type = ZEND_HANDLE_STREAM; /* we do our own reading directly from the phar, don't change the next line */ file_handle->handle.stream.handle = phar; file_handle->handle.stream.reader = phar_zend_stream_reader; file_handle->handle.stream.closer = NULL; /* don't close - let phar handle this one */ file_handle->handle.stream.fteller = phar_stream_fteller_for_zend; file_handle->handle.stream.interactive = 0; phar->is_persistent ? php_stream_rewind(PHAR_GLOBALS->cached_fp[phar->phar_pos].fp) : php_stream_rewind(phar->fp); #endif } } } zend_try { failed = 0; res = phar_orig_compile_file(file_handle, type TSRMLS_CC); } zend_catch { failed = 1; } zend_end_try(); if (name) { efree(name); } if (failed) { zend_bailout(); } return res; } /* }}} */ #if PHP_VERSION_ID < 50300 int phar_zend_open(const char *filename, zend_file_handle *handle TSRMLS_DC) /* {{{ */ { char *arch, *entry; int arch_len, entry_len; /* this code is obsoleted in php 5.3 */ entry = (char *) filename; if (!IS_ABSOLUTE_PATH(entry, strlen(entry)) && !strstr(entry, "://")) { phar_archive_data **pphar = NULL; char *fname; int fname_len; fname = zend_get_executed_filename(TSRMLS_C); fname_len = strlen(fname); if (fname_len > 7 && !strncasecmp(fname, "phar://", 7)) { if (SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 1, 0 TSRMLS_CC)) { zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), arch, arch_len, (void **) &pphar); if (!pphar && PHAR_G(manifest_cached)) { zend_hash_find(&cached_phars, arch, arch_len, (void **) &pphar); } efree(arch); efree(entry); } } /* retrieving an include within the current directory, so use this if possible */ if (!(entry = phar_find_in_include_path((char *) filename, strlen(filename), NULL TSRMLS_CC))) { /* this file is not in the phar, use the original path */ goto skip_phar; } if (SUCCESS == phar_orig_zend_open(entry, handle TSRMLS_CC)) { if (!handle->opened_path) { handle->opened_path = entry; } if (entry != filename) { handle->free_filename = 1; } return SUCCESS; } if (entry != filename) { efree(entry); } return FAILURE; } skip_phar: return phar_orig_zend_open(filename, handle TSRMLS_CC); } /* }}} */ #endif typedef zend_op_array* (zend_compile_t)(zend_file_handle*, int TSRMLS_DC); typedef zend_compile_t* (compile_hook)(zend_compile_t *ptr); PHP_GINIT_FUNCTION(phar) /* {{{ */ { phar_mime_type mime; memset(phar_globals, 0, sizeof(zend_phar_globals)); phar_globals->readonly = 1; zend_hash_init(&phar_globals->mime_types, 0, NULL, NULL, 1); #define PHAR_SET_MIME(mimetype, ret, fileext) \ mime.mime = mimetype; \ mime.len = sizeof((mimetype))+1; \ mime.type = ret; \ zend_hash_add(&phar_globals->mime_types, fileext, sizeof(fileext)-1, (void *)&mime, sizeof(phar_mime_type), NULL); \ PHAR_SET_MIME("text/html", PHAR_MIME_PHPS, "phps") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "c") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "cc") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "cpp") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "c++") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "dtd") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "h") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "log") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "rng") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "txt") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "xsd") PHAR_SET_MIME("", PHAR_MIME_PHP, "php") PHAR_SET_MIME("", PHAR_MIME_PHP, "inc") PHAR_SET_MIME("video/avi", PHAR_MIME_OTHER, "avi") PHAR_SET_MIME("image/bmp", PHAR_MIME_OTHER, "bmp") PHAR_SET_MIME("text/css", PHAR_MIME_OTHER, "css") PHAR_SET_MIME("image/gif", PHAR_MIME_OTHER, "gif") PHAR_SET_MIME("text/html", PHAR_MIME_OTHER, "htm") PHAR_SET_MIME("text/html", PHAR_MIME_OTHER, "html") PHAR_SET_MIME("text/html", PHAR_MIME_OTHER, "htmls") PHAR_SET_MIME("image/x-ico", PHAR_MIME_OTHER, "ico") PHAR_SET_MIME("image/jpeg", PHAR_MIME_OTHER, "jpe") PHAR_SET_MIME("image/jpeg", PHAR_MIME_OTHER, "jpg") PHAR_SET_MIME("image/jpeg", PHAR_MIME_OTHER, "jpeg") PHAR_SET_MIME("application/x-javascript", PHAR_MIME_OTHER, "js") PHAR_SET_MIME("audio/midi", PHAR_MIME_OTHER, "midi") PHAR_SET_MIME("audio/midi", PHAR_MIME_OTHER, "mid") PHAR_SET_MIME("audio/mod", PHAR_MIME_OTHER, "mod") PHAR_SET_MIME("movie/quicktime", PHAR_MIME_OTHER, "mov") PHAR_SET_MIME("audio/mp3", PHAR_MIME_OTHER, "mp3") PHAR_SET_MIME("video/mpeg", PHAR_MIME_OTHER, "mpg") PHAR_SET_MIME("video/mpeg", PHAR_MIME_OTHER, "mpeg") PHAR_SET_MIME("application/pdf", PHAR_MIME_OTHER, "pdf") PHAR_SET_MIME("image/png", PHAR_MIME_OTHER, "png") PHAR_SET_MIME("application/shockwave-flash", PHAR_MIME_OTHER, "swf") PHAR_SET_MIME("image/tiff", PHAR_MIME_OTHER, "tif") PHAR_SET_MIME("image/tiff", PHAR_MIME_OTHER, "tiff") PHAR_SET_MIME("audio/wav", PHAR_MIME_OTHER, "wav") PHAR_SET_MIME("image/xbm", PHAR_MIME_OTHER, "xbm") PHAR_SET_MIME("text/xml", PHAR_MIME_OTHER, "xml") phar_restore_orig_functions(TSRMLS_C); } /* }}} */ PHP_GSHUTDOWN_FUNCTION(phar) /* {{{ */ { zend_hash_destroy(&phar_globals->mime_types); } /* }}} */ PHP_MINIT_FUNCTION(phar) /* {{{ */ { REGISTER_INI_ENTRIES(); phar_orig_compile_file = zend_compile_file; zend_compile_file = phar_compile_file; #if PHP_VERSION_ID >= 50300 phar_save_resolve_path = zend_resolve_path; zend_resolve_path = phar_resolve_path; #else phar_orig_zend_open = zend_stream_open_function; zend_stream_open_function = phar_zend_open; #endif phar_object_init(TSRMLS_C); phar_intercept_functions_init(TSRMLS_C); phar_save_orig_functions(TSRMLS_C); return php_register_url_stream_wrapper("phar", &php_stream_phar_wrapper TSRMLS_CC); } /* }}} */ PHP_MSHUTDOWN_FUNCTION(phar) /* {{{ */ { php_unregister_url_stream_wrapper("phar" TSRMLS_CC); phar_intercept_functions_shutdown(TSRMLS_C); if (zend_compile_file == phar_compile_file) { zend_compile_file = phar_orig_compile_file; } #if PHP_VERSION_ID < 50300 if (zend_stream_open_function == phar_zend_open) { zend_stream_open_function = phar_orig_zend_open; } #endif if (PHAR_G(manifest_cached)) { zend_hash_destroy(&(cached_phars)); zend_hash_destroy(&(cached_alias)); } return SUCCESS; } /* }}} */ void phar_request_initialize(TSRMLS_D) /* {{{ */ { if (!PHAR_GLOBALS->request_init) { PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; PHAR_G(has_bz2) = zend_hash_exists(&module_registry, "bz2", sizeof("bz2")); PHAR_G(has_zlib) = zend_hash_exists(&module_registry, "zlib", sizeof("zlib")); PHAR_GLOBALS->request_init = 1; PHAR_GLOBALS->request_ends = 0; PHAR_GLOBALS->request_done = 0; zend_hash_init(&(PHAR_GLOBALS->phar_fname_map), 5, zend_get_hash_value, destroy_phar_data, 0); zend_hash_init(&(PHAR_GLOBALS->phar_persist_map), 5, zend_get_hash_value, NULL, 0); zend_hash_init(&(PHAR_GLOBALS->phar_alias_map), 5, zend_get_hash_value, NULL, 0); if (PHAR_G(manifest_cached)) { phar_archive_data **pphar; phar_entry_fp *stuff = (phar_entry_fp *) ecalloc(zend_hash_num_elements(&cached_phars), sizeof(phar_entry_fp)); for (zend_hash_internal_pointer_reset(&cached_phars); zend_hash_get_current_data(&cached_phars, (void **)&pphar) == SUCCESS; zend_hash_move_forward(&cached_phars)) { stuff[pphar[0]->phar_pos].manifest = (phar_entry_fp_info *) ecalloc( zend_hash_num_elements(&(pphar[0]->manifest)), sizeof(phar_entry_fp_info)); } PHAR_GLOBALS->cached_fp = stuff; } PHAR_GLOBALS->phar_SERVER_mung_list = 0; PHAR_G(cwd) = NULL; PHAR_G(cwd_len) = 0; PHAR_G(cwd_init) = 0; } } /* }}} */ PHP_RSHUTDOWN_FUNCTION(phar) /* {{{ */ { int i; PHAR_GLOBALS->request_ends = 1; if (PHAR_GLOBALS->request_init) { phar_release_functions(TSRMLS_C); zend_hash_destroy(&(PHAR_GLOBALS->phar_alias_map)); PHAR_GLOBALS->phar_alias_map.arBuckets = NULL; zend_hash_destroy(&(PHAR_GLOBALS->phar_fname_map)); PHAR_GLOBALS->phar_fname_map.arBuckets = NULL; zend_hash_destroy(&(PHAR_GLOBALS->phar_persist_map)); PHAR_GLOBALS->phar_persist_map.arBuckets = NULL; PHAR_GLOBALS->phar_SERVER_mung_list = 0; if (PHAR_GLOBALS->cached_fp) { for (i = 0; i < zend_hash_num_elements(&cached_phars); ++i) { if (PHAR_GLOBALS->cached_fp[i].fp) { php_stream_close(PHAR_GLOBALS->cached_fp[i].fp); } if (PHAR_GLOBALS->cached_fp[i].ufp) { php_stream_close(PHAR_GLOBALS->cached_fp[i].ufp); } efree(PHAR_GLOBALS->cached_fp[i].manifest); } efree(PHAR_GLOBALS->cached_fp); PHAR_GLOBALS->cached_fp = 0; } PHAR_GLOBALS->request_init = 0; if (PHAR_G(cwd)) { efree(PHAR_G(cwd)); } PHAR_G(cwd) = NULL; PHAR_G(cwd_len) = 0; PHAR_G(cwd_init) = 0; } PHAR_GLOBALS->request_done = 1; return SUCCESS; } /* }}} */ PHP_MINFO_FUNCTION(phar) /* {{{ */ { phar_request_initialize(TSRMLS_C); php_info_print_table_start(); php_info_print_table_header(2, "Phar: PHP Archive support", "enabled"); php_info_print_table_row(2, "Phar EXT version", PHP_PHAR_VERSION); php_info_print_table_row(2, "Phar API version", PHP_PHAR_API_VERSION); php_info_print_table_row(2, "SVN revision", "$Revision$"); php_info_print_table_row(2, "Phar-based phar archives", "enabled"); php_info_print_table_row(2, "Tar-based phar archives", "enabled"); php_info_print_table_row(2, "ZIP-based phar archives", "enabled"); if (PHAR_G(has_zlib)) { php_info_print_table_row(2, "gzip compression", "enabled"); } else { php_info_print_table_row(2, "gzip compression", "disabled (install ext/zlib)"); } if (PHAR_G(has_bz2)) { php_info_print_table_row(2, "bzip2 compression", "enabled"); } else { php_info_print_table_row(2, "bzip2 compression", "disabled (install pecl/bz2)"); } #ifdef PHAR_HAVE_OPENSSL php_info_print_table_row(2, "Native OpenSSL support", "enabled"); #else if (zend_hash_exists(&module_registry, "openssl", sizeof("openssl"))) { php_info_print_table_row(2, "OpenSSL support", "enabled"); } else { php_info_print_table_row(2, "OpenSSL support", "disabled (install ext/openssl)"); } #endif php_info_print_table_end(); php_info_print_box_start(0); PUTS("Phar based on pear/PHP_Archive, original concept by Davey Shafik."); PUTS(!sapi_module.phpinfo_as_text?"<br />":"\n"); PUTS("Phar fully realized by Gregory Beaver and Marcus Boerger."); PUTS(!sapi_module.phpinfo_as_text?"<br />":"\n"); PUTS("Portions of tar implementation Copyright (c) 2003-2009 Tim Kientzle."); php_info_print_box_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ /* {{{ phar_module_entry */ static const zend_module_dep phar_deps[] = { ZEND_MOD_OPTIONAL("apc") ZEND_MOD_OPTIONAL("bz2") ZEND_MOD_OPTIONAL("openssl") ZEND_MOD_OPTIONAL("zlib") ZEND_MOD_OPTIONAL("standard") #if defined(HAVE_HASH) && !defined(COMPILE_DL_HASH) ZEND_MOD_REQUIRED("hash") #endif #if HAVE_SPL ZEND_MOD_REQUIRED("spl") #endif {NULL, NULL, NULL} }; zend_module_entry phar_module_entry = { STANDARD_MODULE_HEADER_EX, NULL, phar_deps, "Phar", phar_functions, PHP_MINIT(phar), PHP_MSHUTDOWN(phar), NULL, PHP_RSHUTDOWN(phar), PHP_MINFO(phar), PHP_PHAR_VERSION, PHP_MODULE_GLOBALS(phar), /* globals descriptor */ PHP_GINIT(phar), /* globals ctor */ PHP_GSHUTDOWN(phar), /* globals dtor */ NULL, /* post deactivate */ STANDARD_MODULE_PROPERTIES_EX }; /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | phar php single-file executable PHP extension | +----------------------------------------------------------------------+ | Copyright (c) 2005-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Gregory Beaver <[email protected]> | | Marcus Boerger <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #define PHAR_MAIN 1 #include "phar_internal.h" #include "SAPI.h" #include "func_interceptors.h" static void destroy_phar_data(void *pDest); ZEND_DECLARE_MODULE_GLOBALS(phar) #if PHP_VERSION_ID >= 50300 char *(*phar_save_resolve_path)(const char *filename, int filename_len TSRMLS_DC); #endif /** * set's phar->is_writeable based on the current INI value */ static int phar_set_writeable_bit(void *pDest, void *argument TSRMLS_DC) /* {{{ */ { zend_bool keep = *(zend_bool *)argument; phar_archive_data *phar = *(phar_archive_data **)pDest; if (!phar->is_data) { phar->is_writeable = !keep; } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* if the original value is 0 (disabled), then allow setting/unsetting at will. Otherwise only allow 1 (enabled), and error on disabling */ ZEND_INI_MH(phar_ini_modify_handler) /* {{{ */ { zend_bool old, ini; if (entry->name_length == 14) { old = PHAR_G(readonly_orig); } else { old = PHAR_G(require_hash_orig); } if (new_value_length == 2 && !strcasecmp("on", new_value)) { ini = (zend_bool) 1; } else if (new_value_length == 3 && !strcasecmp("yes", new_value)) { ini = (zend_bool) 1; } else if (new_value_length == 4 && !strcasecmp("true", new_value)) { ini = (zend_bool) 1; } else { ini = (zend_bool) atoi(new_value); } /* do not allow unsetting in runtime */ if (stage == ZEND_INI_STAGE_STARTUP) { if (entry->name_length == 14) { PHAR_G(readonly_orig) = ini; } else { PHAR_G(require_hash_orig) = ini; } } else if (old && !ini) { return FAILURE; } if (entry->name_length == 14) { PHAR_G(readonly) = ini; if (PHAR_GLOBALS->request_init && PHAR_GLOBALS->phar_fname_map.arBuckets) { zend_hash_apply_with_argument(&(PHAR_GLOBALS->phar_fname_map), phar_set_writeable_bit, (void *)&ini TSRMLS_CC); } } else { PHAR_G(require_hash) = ini; } return SUCCESS; } /* }}}*/ /* this global stores the global cached pre-parsed manifests */ HashTable cached_phars; HashTable cached_alias; static void phar_split_cache_list(TSRMLS_D) /* {{{ */ { char *tmp; char *key, *lasts, *end; char ds[2]; phar_archive_data *phar; uint i = 0; if (!PHAR_GLOBALS->cache_list || !(PHAR_GLOBALS->cache_list[0])) { return; } ds[0] = DEFAULT_DIR_SEPARATOR; ds[1] = '\0'; tmp = estrdup(PHAR_GLOBALS->cache_list); /* fake request startup */ PHAR_GLOBALS->request_init = 1; if (zend_hash_init(&EG(regular_list), 0, NULL, NULL, 0) == SUCCESS) { EG(regular_list).nNextFreeElement=1; /* we don't want resource id 0 */ } PHAR_G(has_bz2) = zend_hash_exists(&module_registry, "bz2", sizeof("bz2")); PHAR_G(has_zlib) = zend_hash_exists(&module_registry, "zlib", sizeof("zlib")); /* these two are dummies and will be destroyed later */ zend_hash_init(&cached_phars, sizeof(phar_archive_data*), zend_get_hash_value, destroy_phar_data, 1); zend_hash_init(&cached_alias, sizeof(phar_archive_data*), zend_get_hash_value, NULL, 1); /* these two are real and will be copied over cached_phars/cached_alias later */ zend_hash_init(&(PHAR_GLOBALS->phar_fname_map), sizeof(phar_archive_data*), zend_get_hash_value, destroy_phar_data, 1); zend_hash_init(&(PHAR_GLOBALS->phar_alias_map), sizeof(phar_archive_data*), zend_get_hash_value, NULL, 1); PHAR_GLOBALS->manifest_cached = 1; PHAR_GLOBALS->persist = 1; for (key = php_strtok_r(tmp, ds, &lasts); key; key = php_strtok_r(NULL, ds, &lasts)) { end = strchr(key, DEFAULT_DIR_SEPARATOR); if (end) { if (SUCCESS == phar_open_from_filename(key, end - key, NULL, 0, 0, &phar, NULL TSRMLS_CC)) { finish_up: phar->phar_pos = i++; php_stream_close(phar->fp); phar->fp = NULL; } else { finish_error: PHAR_GLOBALS->persist = 0; PHAR_GLOBALS->manifest_cached = 0; efree(tmp); zend_hash_destroy(&(PHAR_G(phar_fname_map))); PHAR_GLOBALS->phar_fname_map.arBuckets = 0; zend_hash_destroy(&(PHAR_G(phar_alias_map))); PHAR_GLOBALS->phar_alias_map.arBuckets = 0; zend_hash_destroy(&cached_phars); zend_hash_destroy(&cached_alias); zend_hash_graceful_reverse_destroy(&EG(regular_list)); memset(&EG(regular_list), 0, sizeof(HashTable)); /* free cached manifests */ PHAR_GLOBALS->request_init = 0; return; } } else { if (SUCCESS == phar_open_from_filename(key, strlen(key), NULL, 0, 0, &phar, NULL TSRMLS_CC)) { goto finish_up; } else { goto finish_error; } } } PHAR_GLOBALS->persist = 0; PHAR_GLOBALS->request_init = 0; /* destroy dummy values from before */ zend_hash_destroy(&cached_phars); zend_hash_destroy(&cached_alias); cached_phars = PHAR_GLOBALS->phar_fname_map; cached_alias = PHAR_GLOBALS->phar_alias_map; PHAR_GLOBALS->phar_fname_map.arBuckets = 0; PHAR_GLOBALS->phar_alias_map.arBuckets = 0; zend_hash_graceful_reverse_destroy(&EG(regular_list)); memset(&EG(regular_list), 0, sizeof(HashTable)); efree(tmp); } /* }}} */ ZEND_INI_MH(phar_ini_cache_list) /* {{{ */ { PHAR_G(cache_list) = new_value; if (stage == ZEND_INI_STAGE_STARTUP) { phar_split_cache_list(TSRMLS_C); } return SUCCESS; } /* }}} */ PHP_INI_BEGIN() STD_PHP_INI_BOOLEAN( "phar.readonly", "1", PHP_INI_ALL, phar_ini_modify_handler, readonly, zend_phar_globals, phar_globals) STD_PHP_INI_BOOLEAN( "phar.require_hash", "1", PHP_INI_ALL, phar_ini_modify_handler, require_hash, zend_phar_globals, phar_globals) STD_PHP_INI_ENTRY("phar.cache_list", "", PHP_INI_SYSTEM, phar_ini_cache_list, cache_list, zend_phar_globals, phar_globals) PHP_INI_END() /** * When all uses of a phar have been concluded, this frees the manifest * and the phar slot */ void phar_destroy_phar_data(phar_archive_data *phar TSRMLS_DC) /* {{{ */ { if (phar->alias && phar->alias != phar->fname) { pefree(phar->alias, phar->is_persistent); phar->alias = NULL; } if (phar->fname) { pefree(phar->fname, phar->is_persistent); phar->fname = NULL; } if (phar->signature) { pefree(phar->signature, phar->is_persistent); phar->signature = NULL; } if (phar->manifest.arBuckets) { zend_hash_destroy(&phar->manifest); phar->manifest.arBuckets = NULL; } if (phar->mounted_dirs.arBuckets) { zend_hash_destroy(&phar->mounted_dirs); phar->mounted_dirs.arBuckets = NULL; } if (phar->virtual_dirs.arBuckets) { zend_hash_destroy(&phar->virtual_dirs); phar->virtual_dirs.arBuckets = NULL; } if (phar->metadata) { if (phar->is_persistent) { if (phar->metadata_len) { /* for zip comments that are strings */ free(phar->metadata); } else { zval_internal_ptr_dtor(&phar->metadata); } } else { zval_ptr_dtor(&phar->metadata); } phar->metadata_len = 0; phar->metadata = 0; } if (phar->fp) { php_stream_close(phar->fp); phar->fp = 0; } if (phar->ufp) { php_stream_close(phar->ufp); phar->ufp = 0; } pefree(phar, phar->is_persistent); } /* }}}*/ /** * Delete refcount and destruct if needed. On destruct return 1 else 0. */ int phar_archive_delref(phar_archive_data *phar TSRMLS_DC) /* {{{ */ { if (phar->is_persistent) { return 0; } if (--phar->refcount < 0) { if (PHAR_GLOBALS->request_done || zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), phar->fname, phar->fname_len) != SUCCESS) { phar_destroy_phar_data(phar TSRMLS_CC); } return 1; } else if (!phar->refcount) { /* invalidate phar cache */ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; if (phar->fp && !(phar->flags & PHAR_FILE_COMPRESSION_MASK)) { /* close open file handle - allows removal or rename of the file on windows, which has greedy locking only close if the archive was not already compressed. If it was compressed, then the fp does not refer to the original file */ php_stream_close(phar->fp); phar->fp = NULL; } if (!zend_hash_num_elements(&phar->manifest)) { /* this is a new phar that has perhaps had an alias/metadata set, but has never been flushed */ if (zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), phar->fname, phar->fname_len) != SUCCESS) { phar_destroy_phar_data(phar TSRMLS_CC); } return 1; } } return 0; } /* }}}*/ /** * Destroy phar's in shutdown, here we don't care about aliases */ static void destroy_phar_data_only(void *pDest) /* {{{ */ { phar_archive_data *phar_data = *(phar_archive_data **) pDest; TSRMLS_FETCH(); if (EG(exception) || --phar_data->refcount < 0) { phar_destroy_phar_data(phar_data TSRMLS_CC); } } /* }}}*/ /** * Delete aliases to phar's that got kicked out of the global table */ static int phar_unalias_apply(void *pDest, void *argument TSRMLS_DC) /* {{{ */ { return *(void**)pDest == argument ? ZEND_HASH_APPLY_REMOVE : ZEND_HASH_APPLY_KEEP; } /* }}} */ /** * Delete aliases to phar's that got kicked out of the global table */ static int phar_tmpclose_apply(void *pDest TSRMLS_DC) /* {{{ */ { phar_entry_info *entry = (phar_entry_info *) pDest; if (entry->fp_type != PHAR_TMP) { return ZEND_HASH_APPLY_KEEP; } if (entry->fp && !entry->fp_refcount) { php_stream_close(entry->fp); entry->fp = NULL; } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /** * Filename map destructor */ static void destroy_phar_data(void *pDest) /* {{{ */ { phar_archive_data *phar_data = *(phar_archive_data **) pDest; TSRMLS_FETCH(); if (PHAR_GLOBALS->request_ends) { /* first, iterate over the manifest and close all PHAR_TMP entry fp handles, this prevents unnecessary unfreed stream resources */ zend_hash_apply(&(phar_data->manifest), phar_tmpclose_apply TSRMLS_CC); destroy_phar_data_only(pDest); return; } zend_hash_apply_with_argument(&(PHAR_GLOBALS->phar_alias_map), phar_unalias_apply, phar_data TSRMLS_CC); if (--phar_data->refcount < 0) { phar_destroy_phar_data(phar_data TSRMLS_CC); } } /* }}}*/ /** * destructor for the manifest hash, frees each file's entry */ void destroy_phar_manifest_entry(void *pDest) /* {{{ */ { phar_entry_info *entry = (phar_entry_info *)pDest; TSRMLS_FETCH(); if (entry->cfp) { php_stream_close(entry->cfp); entry->cfp = 0; } if (entry->fp) { php_stream_close(entry->fp); entry->fp = 0; } if (entry->metadata) { if (entry->is_persistent) { if (entry->metadata_len) { /* for zip comments that are strings */ free(entry->metadata); } else { zval_internal_ptr_dtor(&entry->metadata); } } else { zval_ptr_dtor(&entry->metadata); } entry->metadata_len = 0; entry->metadata = 0; } if (entry->metadata_str.c) { smart_str_free(&entry->metadata_str); entry->metadata_str.c = 0; } pefree(entry->filename, entry->is_persistent); if (entry->link) { pefree(entry->link, entry->is_persistent); entry->link = 0; } if (entry->tmp) { pefree(entry->tmp, entry->is_persistent); entry->tmp = 0; } } /* }}} */ int phar_entry_delref(phar_entry_data *idata TSRMLS_DC) /* {{{ */ { int ret = 0; if (idata->internal_file && !idata->internal_file->is_persistent) { if (--idata->internal_file->fp_refcount < 0) { idata->internal_file->fp_refcount = 0; } if (idata->fp && idata->fp != idata->phar->fp && idata->fp != idata->phar->ufp && idata->fp != idata->internal_file->fp) { php_stream_close(idata->fp); } /* if phar_get_or_create_entry_data returns a sub-directory, we have to free it */ if (idata->internal_file->is_temp_dir) { destroy_phar_manifest_entry((void *)idata->internal_file); efree(idata->internal_file); } } phar_archive_delref(idata->phar TSRMLS_CC); efree(idata); return ret; } /* }}} */ /** * Removes an entry, either by actually removing it or by marking it. */ void phar_entry_remove(phar_entry_data *idata, char **error TSRMLS_DC) /* {{{ */ { phar_archive_data *phar; phar = idata->phar; if (idata->internal_file->fp_refcount < 2) { if (idata->fp && idata->fp != idata->phar->fp && idata->fp != idata->phar->ufp && idata->fp != idata->internal_file->fp) { php_stream_close(idata->fp); } zend_hash_del(&idata->phar->manifest, idata->internal_file->filename, idata->internal_file->filename_len); idata->phar->refcount--; efree(idata); } else { idata->internal_file->is_deleted = 1; phar_entry_delref(idata TSRMLS_CC); } if (!phar->donotflush) { phar_flush(phar, 0, 0, 0, error TSRMLS_CC); } } /* }}} */ #define MAPPHAR_ALLOC_FAIL(msg) \ if (fp) {\ php_stream_close(fp);\ }\ if (error) {\ spprintf(error, 0, msg, fname);\ }\ return FAILURE; #define MAPPHAR_FAIL(msg) \ efree(savebuf);\ if (mydata) {\ phar_destroy_phar_data(mydata TSRMLS_CC);\ }\ if (signature) {\ pefree(signature, PHAR_G(persist));\ }\ MAPPHAR_ALLOC_FAIL(msg) #ifdef WORDS_BIGENDIAN # define PHAR_GET_32(buffer, var) \ var = ((((unsigned char*)(buffer))[3]) << 24) \ | ((((unsigned char*)(buffer))[2]) << 16) \ | ((((unsigned char*)(buffer))[1]) << 8) \ | (((unsigned char*)(buffer))[0]); \ (buffer) += 4 # define PHAR_GET_16(buffer, var) \ var = ((((unsigned char*)(buffer))[1]) << 8) \ | (((unsigned char*)(buffer))[0]); \ (buffer) += 2 #else # define PHAR_GET_32(buffer, var) \ memcpy(&var, buffer, sizeof(var)); \ buffer += 4 # define PHAR_GET_16(buffer, var) \ var = *(php_uint16*)(buffer); \ buffer += 2 #endif #define PHAR_ZIP_16(var) ((php_uint16)((((php_uint16)var[0]) & 0xff) | \ (((php_uint16)var[1]) & 0xff) << 8)) #define PHAR_ZIP_32(var) ((php_uint32)((((php_uint32)var[0]) & 0xff) | \ (((php_uint32)var[1]) & 0xff) << 8 | \ (((php_uint32)var[2]) & 0xff) << 16 | \ (((php_uint32)var[3]) & 0xff) << 24)) /** * Open an already loaded phar */ int phar_open_parsed_phar(char *fname, int fname_len, char *alias, int alias_len, int is_data, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { phar_archive_data *phar; #ifdef PHP_WIN32 char *unixfname; #endif if (error) { *error = NULL; } #ifdef PHP_WIN32 unixfname = estrndup(fname, fname_len); phar_unixify_path_separators(unixfname, fname_len); if (SUCCESS == phar_get_archive(&phar, unixfname, fname_len, alias, alias_len, error TSRMLS_CC) && ((alias && fname_len == phar->fname_len && !strncmp(unixfname, phar->fname, fname_len)) || !alias) ) { phar_entry_info *stub; efree(unixfname); #else if (SUCCESS == phar_get_archive(&phar, fname, fname_len, alias, alias_len, error TSRMLS_CC) && ((alias && fname_len == phar->fname_len && !strncmp(fname, phar->fname, fname_len)) || !alias) ) { phar_entry_info *stub; #endif /* logic above is as follows: If an explicit alias was requested, ensure the filename passed in matches the phar's filename. If no alias was passed in, then it can match either and be valid */ if (!is_data) { /* prevent any ".phar" without a stub getting through */ if (!phar->halt_offset && !phar->is_brandnew && (phar->is_tar || phar->is_zip)) { if (PHAR_G(readonly) && FAILURE == zend_hash_find(&(phar->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1, (void **)&stub)) { if (error) { spprintf(error, 0, "'%s' is not a phar archive. Use PharData::__construct() for a standard zip or tar archive", fname); } return FAILURE; } } } if (pphar) { *pphar = phar; } return SUCCESS; } else { #ifdef PHP_WIN32 efree(unixfname); #endif if (pphar) { *pphar = NULL; } if (phar && error && !(options & REPORT_ERRORS)) { efree(error); } return FAILURE; } } /* }}}*/ /** * Parse out metadata from the manifest for a single file * * Meta-data is in this format: * [len32][data...] * * data is the serialized zval */ int phar_parse_metadata(char **buffer, zval **metadata, int zip_metadata_len TSRMLS_DC) /* {{{ */ { const unsigned char *p; php_uint32 buf_len; php_unserialize_data_t var_hash; if (!zip_metadata_len) { PHAR_GET_32(*buffer, buf_len); } else { buf_len = zip_metadata_len; } if (buf_len) { ALLOC_ZVAL(*metadata); INIT_ZVAL(**metadata); p = (const unsigned char*) *buffer; PHP_VAR_UNSERIALIZE_INIT(var_hash); if (!php_var_unserialize(metadata, &p, p + buf_len, &var_hash TSRMLS_CC)) { PHP_VAR_UNSERIALIZE_DESTROY(var_hash); zval_ptr_dtor(metadata); *metadata = NULL; return FAILURE; } PHP_VAR_UNSERIALIZE_DESTROY(var_hash); if (PHAR_G(persist)) { /* lazy init metadata */ zval_ptr_dtor(metadata); *metadata = (zval *) pemalloc(buf_len, 1); memcpy(*metadata, *buffer, buf_len); *buffer += buf_len; return SUCCESS; } } else { *metadata = NULL; } if (!zip_metadata_len) { *buffer += buf_len; } return SUCCESS; } /* }}}*/ /** * Does not check for a previously opened phar in the cache. * * Parse a new one and add it to the cache, returning either SUCCESS or * FAILURE, and setting pphar to the pointer to the manifest entry * * This is used by phar_open_from_filename to process the manifest, but can be called * directly. */ static int phar_parse_pharfile(php_stream *fp, char *fname, int fname_len, char *alias, int alias_len, long halt_offset, phar_archive_data** pphar, php_uint32 compression, char **error TSRMLS_DC) /* {{{ */ { char b32[4], *buffer, *endbuffer, *savebuf; phar_archive_data *mydata = NULL; phar_entry_info entry; php_uint32 manifest_len, manifest_count, manifest_flags, manifest_index, tmp_len, sig_flags; php_uint16 manifest_ver; long offset; int register_alias, sig_len, temp_alias = 0; char *signature = NULL; if (pphar) { *pphar = NULL; } if (error) { *error = NULL; } /* check for ?>\n and increment accordingly */ if (-1 == php_stream_seek(fp, halt_offset, SEEK_SET)) { MAPPHAR_ALLOC_FAIL("cannot seek to __HALT_COMPILER(); location in phar \"%s\"") } buffer = b32; if (3 != php_stream_read(fp, buffer, 3)) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at stub end)") } if ((*buffer == ' ' || *buffer == '\n') && *(buffer + 1) == '?' && *(buffer + 2) == '>') { int nextchar; halt_offset += 3; if (EOF == (nextchar = php_stream_getc(fp))) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at stub end)") } if ((char) nextchar == '\r') { /* if we have an \r we require an \n as well */ if (EOF == (nextchar = php_stream_getc(fp)) || (char)nextchar != '\n') { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at stub end)") } ++halt_offset; } if ((char) nextchar == '\n') { ++halt_offset; } } /* make sure we are at the right location to read the manifest */ if (-1 == php_stream_seek(fp, halt_offset, SEEK_SET)) { MAPPHAR_ALLOC_FAIL("cannot seek to __HALT_COMPILER(); location in phar \"%s\"") } /* read in manifest */ buffer = b32; if (4 != php_stream_read(fp, buffer, 4)) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at manifest length)") } PHAR_GET_32(buffer, manifest_len); if (manifest_len > 1048576 * 100) { /* prevent serious memory issues by limiting manifest to at most 100 MB in length */ MAPPHAR_ALLOC_FAIL("manifest cannot be larger than 100 MB in phar \"%s\"") } buffer = (char *)emalloc(manifest_len); savebuf = buffer; endbuffer = buffer + manifest_len; if (manifest_len < 10 || manifest_len != php_stream_read(fp, buffer, manifest_len)) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest header)") } /* extract the number of entries */ PHAR_GET_32(buffer, manifest_count); if (manifest_count == 0) { MAPPHAR_FAIL("in phar \"%s\", manifest claims to have zero entries. Phars must have at least 1 entry"); } /* extract API version, lowest nibble currently unused */ manifest_ver = (((unsigned char)buffer[0]) << 8) + ((unsigned char)buffer[1]); buffer += 2; if ((manifest_ver & PHAR_API_VER_MASK) < PHAR_API_MIN_READ) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" is API version %1.u.%1.u.%1.u, and cannot be processed", fname, manifest_ver >> 12, (manifest_ver >> 8) & 0xF, (manifest_ver >> 4) & 0x0F); } return FAILURE; } PHAR_GET_32(buffer, manifest_flags); manifest_flags &= ~PHAR_HDR_COMPRESSION_MASK; manifest_flags &= ~PHAR_FILE_COMPRESSION_MASK; /* remember whether this entire phar was compressed with gz/bzip2 */ manifest_flags |= compression; /* The lowest nibble contains the phar wide flags. The compression flags can */ /* be ignored on reading because it is being generated anyways. */ if (manifest_flags & PHAR_HDR_SIGNATURE) { char sig_buf[8], *sig_ptr = sig_buf; off_t read_len; size_t end_of_phar; if (-1 == php_stream_seek(fp, -8, SEEK_END) || (read_len = php_stream_tell(fp)) < 20 || 8 != php_stream_read(fp, sig_buf, 8) || memcmp(sig_buf+4, "GBMB", 4)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } PHAR_GET_32(sig_ptr, sig_flags); switch(sig_flags) { case PHAR_SIG_OPENSSL: { php_uint32 signature_len; char *sig; off_t whence; /* we store the signature followed by the signature length */ if (-1 == php_stream_seek(fp, -12, SEEK_CUR) || 4 != php_stream_read(fp, sig_buf, 4)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" openssl signature length could not be read", fname); } return FAILURE; } sig_ptr = sig_buf; PHAR_GET_32(sig_ptr, signature_len); sig = (char *) emalloc(signature_len); whence = signature_len + 4; whence = -whence; if (-1 == php_stream_seek(fp, whence, SEEK_CUR) || !(end_of_phar = php_stream_tell(fp)) || signature_len != php_stream_read(fp, sig, signature_len)) { efree(savebuf); efree(sig); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" openssl signature could not be read", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, end_of_phar, PHAR_SIG_OPENSSL, sig, signature_len, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); efree(sig); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" openssl signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } efree(sig); } break; #if PHAR_HASH_OK case PHAR_SIG_SHA512: { unsigned char digest[64]; php_stream_seek(fp, -(8 + 64), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_SHA512, (char *)digest, 64, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" SHA512 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } case PHAR_SIG_SHA256: { unsigned char digest[32]; php_stream_seek(fp, -(8 + 32), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_SHA256, (char *)digest, 32, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" SHA256 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } #else case PHAR_SIG_SHA512: case PHAR_SIG_SHA256: efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a unsupported signature", fname); } return FAILURE; #endif case PHAR_SIG_SHA1: { unsigned char digest[20]; php_stream_seek(fp, -(8 + 20), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_SHA1, (char *)digest, 20, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" SHA1 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } case PHAR_SIG_MD5: { unsigned char digest[16]; php_stream_seek(fp, -(8 + 16), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_MD5, (char *)digest, 16, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" MD5 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } default: efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken or unsupported signature", fname); } return FAILURE; } } else if (PHAR_G(require_hash)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" does not have a signature", fname); } return FAILURE; } else { sig_flags = 0; sig_len = 0; } /* extract alias */ PHAR_GET_32(buffer, tmp_len); if (buffer + tmp_len > endbuffer) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (buffer overrun)"); } if (manifest_len < 10 + tmp_len) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest header)") } /* tmp_len = 0 says alias length is 0, which means the alias is not stored in the phar */ if (tmp_len) { /* if the alias is stored we enforce it (implicit overrides explicit) */ if (alias && alias_len && (alias_len != (int)tmp_len || strncmp(alias, buffer, tmp_len))) { buffer[tmp_len] = '\0'; php_stream_close(fp); if (signature) { efree(signature); } if (error) { spprintf(error, 0, "cannot load phar \"%s\" with implicit alias \"%s\" under different alias \"%s\"", fname, buffer, alias); } efree(savebuf); return FAILURE; } alias_len = tmp_len; alias = buffer; buffer += tmp_len; register_alias = 1; } else if (!alias_len || !alias) { /* if we neither have an explicit nor an implicit alias, we use the filename */ alias = NULL; alias_len = 0; register_alias = 0; } else if (alias_len) { register_alias = 1; temp_alias = 1; } /* we have 5 32-bit items plus 1 byte at least */ if (manifest_count > ((manifest_len - 10 - tmp_len) / (5 * 4 + 1))) { /* prevent serious memory issues */ MAPPHAR_FAIL("internal corruption of phar \"%s\" (too many manifest entries for size of manifest)") } mydata = pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist)); mydata->is_persistent = PHAR_G(persist); /* check whether we have meta data, zero check works regardless of byte order */ if (mydata->is_persistent) { PHAR_GET_32(buffer, mydata->metadata_len); if (phar_parse_metadata(&buffer, &mydata->metadata, mydata->metadata_len TSRMLS_CC) == FAILURE) { MAPPHAR_FAIL("unable to read phar metadata in .phar file \"%s\""); } } else { if (phar_parse_metadata(&buffer, &mydata->metadata, 0 TSRMLS_CC) == FAILURE) { MAPPHAR_FAIL("unable to read phar metadata in .phar file \"%s\""); } } /* set up our manifest */ zend_hash_init(&mydata->manifest, manifest_count, zend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)mydata->is_persistent); zend_hash_init(&mydata->mounted_dirs, 5, zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); zend_hash_init(&mydata->virtual_dirs, manifest_count * 2, zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); mydata->fname = pestrndup(fname, fname_len, mydata->is_persistent); #ifdef PHP_WIN32 phar_unixify_path_separators(mydata->fname, fname_len); #endif mydata->fname_len = fname_len; offset = halt_offset + manifest_len + 4; memset(&entry, 0, sizeof(phar_entry_info)); entry.phar = mydata; entry.fp_type = PHAR_FP; entry.is_persistent = mydata->is_persistent; for (manifest_index = 0; manifest_index < manifest_count; ++manifest_index) { if (buffer + 4 > endbuffer) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest entry)") } PHAR_GET_32(buffer, entry.filename_len); if (entry.filename_len == 0) { MAPPHAR_FAIL("zero-length filename encountered in phar \"%s\""); } if (entry.is_persistent) { entry.manifest_pos = manifest_index; } if (buffer + entry.filename_len + 20 > endbuffer) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest entry)"); } if ((manifest_ver & PHAR_API_VER_MASK) >= PHAR_API_MIN_DIR && buffer[entry.filename_len - 1] == '/') { entry.is_dir = 1; } else { entry.is_dir = 0; } phar_add_virtual_dirs(mydata, buffer, entry.filename_len TSRMLS_CC); entry.filename = pestrndup(buffer, entry.filename_len, entry.is_persistent); buffer += entry.filename_len; PHAR_GET_32(buffer, entry.uncompressed_filesize); PHAR_GET_32(buffer, entry.timestamp); if (offset == halt_offset + (int)manifest_len + 4) { mydata->min_timestamp = entry.timestamp; mydata->max_timestamp = entry.timestamp; } else { if (mydata->min_timestamp > entry.timestamp) { mydata->min_timestamp = entry.timestamp; } else if (mydata->max_timestamp < entry.timestamp) { mydata->max_timestamp = entry.timestamp; } } PHAR_GET_32(buffer, entry.compressed_filesize); PHAR_GET_32(buffer, entry.crc32); PHAR_GET_32(buffer, entry.flags); if (entry.is_dir) { entry.filename_len--; entry.flags |= PHAR_ENT_PERM_DEF_DIR; } if (entry.is_persistent) { PHAR_GET_32(buffer, entry.metadata_len); if (!entry.metadata_len) buffer -= 4; if (phar_parse_metadata(&buffer, &entry.metadata, entry.metadata_len TSRMLS_CC) == FAILURE) { pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("unable to read file metadata in .phar file \"%s\""); } } else { if (phar_parse_metadata(&buffer, &entry.metadata, 0 TSRMLS_CC) == FAILURE) { pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("unable to read file metadata in .phar file \"%s\""); } } entry.offset = entry.offset_abs = offset; offset += entry.compressed_filesize; switch (entry.flags & PHAR_ENT_COMPRESSION_MASK) { case PHAR_ENT_COMPRESSED_GZ: if (!PHAR_G(has_zlib)) { if (entry.metadata) { if (entry.is_persistent) { free(entry.metadata); } else { zval_ptr_dtor(&entry.metadata); } } pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("zlib extension is required for gz compressed .phar file \"%s\""); } break; case PHAR_ENT_COMPRESSED_BZ2: if (!PHAR_G(has_bz2)) { if (entry.metadata) { if (entry.is_persistent) { free(entry.metadata); } else { zval_ptr_dtor(&entry.metadata); } } pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("bz2 extension is required for bzip2 compressed .phar file \"%s\""); } break; default: if (entry.uncompressed_filesize != entry.compressed_filesize) { if (entry.metadata) { if (entry.is_persistent) { free(entry.metadata); } else { zval_ptr_dtor(&entry.metadata); } } pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("internal corruption of phar \"%s\" (compressed and uncompressed size does not match for uncompressed entry)"); } break; } manifest_flags |= (entry.flags & PHAR_ENT_COMPRESSION_MASK); /* if signature matched, no need to check CRC32 for each file */ entry.is_crc_checked = (manifest_flags & PHAR_HDR_SIGNATURE ? 1 : 0); phar_set_inode(&entry TSRMLS_CC); zend_hash_add(&mydata->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info), NULL); } snprintf(mydata->version, sizeof(mydata->version), "%u.%u.%u", manifest_ver >> 12, (manifest_ver >> 8) & 0xF, (manifest_ver >> 4) & 0xF); mydata->internal_file_start = halt_offset + manifest_len + 4; mydata->halt_offset = halt_offset; mydata->flags = manifest_flags; endbuffer = strrchr(mydata->fname, '/'); if (endbuffer) { mydata->ext = memchr(endbuffer, '.', (mydata->fname + fname_len) - endbuffer); if (mydata->ext == endbuffer) { mydata->ext = memchr(endbuffer + 1, '.', (mydata->fname + fname_len) - endbuffer - 1); } if (mydata->ext) { mydata->ext_len = (mydata->fname + mydata->fname_len) - mydata->ext; } } mydata->alias = alias ? pestrndup(alias, alias_len, mydata->is_persistent) : pestrndup(mydata->fname, fname_len, mydata->is_persistent); mydata->alias_len = alias ? alias_len : fname_len; mydata->sig_flags = sig_flags; mydata->fp = fp; mydata->sig_len = sig_len; mydata->signature = signature; phar_request_initialize(TSRMLS_C); if (register_alias) { phar_archive_data **fd_ptr; mydata->is_temporary_alias = temp_alias; if (!phar_validate_alias(mydata->alias, mydata->alias_len)) { signature = NULL; fp = NULL; MAPPHAR_FAIL("Cannot open archive \"%s\", invalid alias"); } if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) { if (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) { signature = NULL; fp = NULL; MAPPHAR_FAIL("Cannot open archive \"%s\", alias is already in use by existing archive"); } } zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&mydata, sizeof(phar_archive_data*), NULL); } else { mydata->is_temporary_alias = 1; } zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len, (void*)&mydata, sizeof(phar_archive_data*), NULL); efree(savebuf); if (pphar) { *pphar = mydata; } return SUCCESS; } /* }}} */ /** * Create or open a phar for writing */ int phar_open_or_create_filename(char *fname, int fname_len, char *alias, int alias_len, int is_data, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { const char *ext_str, *z; char *my_error; int ext_len; phar_archive_data **test, *unused = NULL; test = &unused; if (error) { *error = NULL; } /* first try to open an existing file */ if (phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, !is_data, 0, 1 TSRMLS_CC) == SUCCESS) { goto check_file; } /* next try to create a new file */ if (FAILURE == phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, !is_data, 1, 1 TSRMLS_CC)) { if (error) { if (ext_len == -2) { spprintf(error, 0, "Cannot create a phar archive from a URL like \"%s\". Phar objects can only be created from local files", fname); } else { spprintf(error, 0, "Cannot create phar '%s', file extension (or combination) not recognised or the directory does not exist", fname); } } return FAILURE; } check_file: if (phar_open_parsed_phar(fname, fname_len, alias, alias_len, is_data, options, test, &my_error TSRMLS_CC) == SUCCESS) { if (pphar) { *pphar = *test; } if ((*test)->is_data && !(*test)->is_tar && !(*test)->is_zip) { if (error) { spprintf(error, 0, "Cannot open '%s' as a PharData object. Use Phar::__construct() for executable archives", fname); } return FAILURE; } if (PHAR_G(readonly) && !(*test)->is_data && ((*test)->is_tar || (*test)->is_zip)) { phar_entry_info *stub; if (FAILURE == zend_hash_find(&((*test)->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1, (void **)&stub)) { spprintf(error, 0, "'%s' is not a phar archive. Use PharData::__construct() for a standard zip or tar archive", fname); return FAILURE; } } if (!PHAR_G(readonly) || (*test)->is_data) { (*test)->is_writeable = 1; } return SUCCESS; } else if (my_error) { if (error) { *error = my_error; } else { efree(my_error); } return FAILURE; } if (ext_len > 3 && (z = memchr(ext_str, 'z', ext_len)) && ((ext_str + ext_len) - z >= 2) && !memcmp(z + 1, "ip", 2)) { /* assume zip-based phar */ return phar_open_or_create_zip(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC); } if (ext_len > 3 && (z = memchr(ext_str, 't', ext_len)) && ((ext_str + ext_len) - z >= 2) && !memcmp(z + 1, "ar", 2)) { /* assume tar-based phar */ return phar_open_or_create_tar(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC); } return phar_create_or_parse_filename(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC); } /* }}} */ int phar_create_or_parse_filename(char *fname, int fname_len, char *alias, int alias_len, int is_data, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { phar_archive_data *mydata; php_stream *fp; char *actual = NULL, *p; if (!pphar) { pphar = &mydata; } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { return FAILURE; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { return FAILURE; } /* first open readonly so it won't be created if not present */ fp = php_stream_open_wrapper(fname, "rb", IGNORE_URL|STREAM_MUST_SEEK|0, &actual); if (actual) { fname = actual; fname_len = strlen(actual); } if (fp) { if (phar_open_from_fp(fp, fname, fname_len, alias, alias_len, options, pphar, is_data, error TSRMLS_CC) == SUCCESS) { if ((*pphar)->is_data || !PHAR_G(readonly)) { (*pphar)->is_writeable = 1; } if (actual) { efree(actual); } return SUCCESS; } else { /* file exists, but is either corrupt or not a phar archive */ if (actual) { efree(actual); } return FAILURE; } } if (actual) { efree(actual); } if (PHAR_G(readonly) && !is_data) { if (options & REPORT_ERRORS) { if (error) { spprintf(error, 0, "creating archive \"%s\" disabled by the php.ini setting phar.readonly", fname); } } return FAILURE; } /* set up our manifest */ mydata = ecalloc(1, sizeof(phar_archive_data)); mydata->fname = expand_filepath(fname, NULL TSRMLS_CC); fname_len = strlen(mydata->fname); #ifdef PHP_WIN32 phar_unixify_path_separators(mydata->fname, fname_len); #endif p = strrchr(mydata->fname, '/'); if (p) { mydata->ext = memchr(p, '.', (mydata->fname + fname_len) - p); if (mydata->ext == p) { mydata->ext = memchr(p + 1, '.', (mydata->fname + fname_len) - p - 1); } if (mydata->ext) { mydata->ext_len = (mydata->fname + fname_len) - mydata->ext; } } if (pphar) { *pphar = mydata; } zend_hash_init(&mydata->manifest, sizeof(phar_entry_info), zend_get_hash_value, destroy_phar_manifest_entry, 0); zend_hash_init(&mydata->mounted_dirs, sizeof(char *), zend_get_hash_value, NULL, 0); zend_hash_init(&mydata->virtual_dirs, sizeof(char *), zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); mydata->fname_len = fname_len; snprintf(mydata->version, sizeof(mydata->version), "%s", PHP_PHAR_API_VERSION); mydata->is_temporary_alias = alias ? 0 : 1; mydata->internal_file_start = -1; mydata->fp = NULL; mydata->is_writeable = 1; mydata->is_brandnew = 1; phar_request_initialize(TSRMLS_C); zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len, (void*)&mydata, sizeof(phar_archive_data*), NULL); if (is_data) { alias = NULL; alias_len = 0; mydata->is_data = 1; /* assume tar format, PharData can specify other */ mydata->is_tar = 1; } else { phar_archive_data **fd_ptr; if (alias && SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) { if (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) { if (error) { spprintf(error, 4096, "phar error: phar \"%s\" cannot set alias \"%s\", already in use by another phar archive", mydata->fname, alias); } zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len); if (pphar) { *pphar = NULL; } return FAILURE; } } mydata->alias = alias ? estrndup(alias, alias_len) : estrndup(mydata->fname, fname_len); mydata->alias_len = alias ? alias_len : fname_len; } if (alias_len && alias) { if (FAILURE == zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&mydata, sizeof(phar_archive_data*), NULL)) { if (options & REPORT_ERRORS) { if (error) { spprintf(error, 0, "archive \"%s\" cannot be associated with alias \"%s\", already in use", fname, alias); } } zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len); if (pphar) { *pphar = NULL; } return FAILURE; } } return SUCCESS; } /* }}}*/ /** * Return an already opened filename. * * Or scan a phar file for the required __HALT_COMPILER(); ?> token and verify * that the manifest is proper, then pass it to phar_parse_pharfile(). SUCCESS * or FAILURE is returned and pphar is set to a pointer to the phar's manifest */ int phar_open_from_filename(char *fname, int fname_len, char *alias, int alias_len, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { php_stream *fp; char *actual; int ret, is_data = 0; if (error) { *error = NULL; } if (!strstr(fname, ".phar")) { is_data = 1; } if (phar_open_parsed_phar(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC) == SUCCESS) { return SUCCESS; } else if (error && *error) { return FAILURE; } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { return FAILURE; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { return FAILURE; } fp = php_stream_open_wrapper(fname, "rb", IGNORE_URL|STREAM_MUST_SEEK, &actual); if (!fp) { if (options & REPORT_ERRORS) { if (error) { spprintf(error, 0, "unable to open phar for reading \"%s\"", fname); } } if (actual) { efree(actual); } return FAILURE; } if (actual) { fname = actual; fname_len = strlen(actual); } ret = phar_open_from_fp(fp, fname, fname_len, alias, alias_len, options, pphar, is_data, error TSRMLS_CC); if (actual) { efree(actual); } return ret; } /* }}}*/ static inline char *phar_strnstr(const char *buf, int buf_len, const char *search, int search_len) /* {{{ */ { const char *c; int so_far = 0; if (buf_len < search_len) { return NULL; } c = buf - 1; do { if (!(c = memchr(c + 1, search[0], buf_len - search_len - so_far))) { return (char *) NULL; } so_far = c - buf; if (so_far >= (buf_len - search_len)) { return (char *) NULL; } if (!memcmp(c, search, search_len)) { return (char *) c; } } while (1); } /* }}} */ /** * Scan an open fp for the required __HALT_COMPILER(); ?> token and verify * that the manifest is proper, then pass it to phar_parse_pharfile(). SUCCESS * or FAILURE is returned and pphar is set to a pointer to the phar's manifest */ static int phar_open_from_fp(php_stream* fp, char *fname, int fname_len, char *alias, int alias_len, int options, phar_archive_data** pphar, int is_data, char **error TSRMLS_DC) /* {{{ */ { const char token[] = "__HALT_COMPILER();"; const char zip_magic[] = "PK\x03\x04"; const char gz_magic[] = "\x1f\x8b\x08"; const char bz_magic[] = "BZh"; char *pos, buffer[1024 + sizeof(token)], test = '\0'; const long readsize = sizeof(buffer) - sizeof(token); const long tokenlen = sizeof(token) - 1; long halt_offset; size_t got; php_uint32 compression = PHAR_FILE_COMPRESSED_NONE; if (error) { *error = NULL; } if (-1 == php_stream_rewind(fp)) { MAPPHAR_ALLOC_FAIL("cannot rewind phar \"%s\"") } buffer[sizeof(buffer)-1] = '\0'; memset(buffer, 32, sizeof(token)); halt_offset = 0; /* Maybe it's better to compile the file instead of just searching, */ /* but we only want the offset. So we want a .re scanner to find it. */ while(!php_stream_eof(fp)) { if ((got = php_stream_read(fp, buffer+tokenlen, readsize)) < (size_t) tokenlen) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated entry)") } if (!test) { test = '\1'; pos = buffer+tokenlen; if (!memcmp(pos, gz_magic, 3)) { char err = 0; php_stream_filter *filter; php_stream *temp; /* to properly decompress, we have to tell zlib to look for a zlib or gzip header */ zval filterparams; if (!PHAR_G(has_zlib)) { MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\" to temporary file, enable zlib extension in php.ini") } array_init(&filterparams); /* this is defined in zlib's zconf.h */ #ifndef MAX_WBITS #define MAX_WBITS 15 #endif add_assoc_long(&filterparams, "window", MAX_WBITS + 32); /* entire file is gzip-compressed, uncompress to temporary file */ if (!(temp = php_stream_fopen_tmpfile())) { MAPPHAR_ALLOC_FAIL("unable to create temporary file for decompression of gzipped phar archive \"%s\"") } php_stream_rewind(fp); filter = php_stream_filter_create("zlib.inflate", &filterparams, php_stream_is_persistent(fp) TSRMLS_CC); if (!filter) { err = 1; add_assoc_long(&filterparams, "window", MAX_WBITS); filter = php_stream_filter_create("zlib.inflate", &filterparams, php_stream_is_persistent(fp) TSRMLS_CC); zval_dtor(&filterparams); if (!filter) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\", ext/zlib is buggy in PHP versions older than 5.2.6") } } else { zval_dtor(&filterparams); } php_stream_filter_append(&temp->writefilters, filter); if (SUCCESS != phar_stream_copy_to_stream(fp, temp, PHP_STREAM_COPY_ALL, NULL)) { if (err) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\", ext/zlib is buggy in PHP versions older than 5.2.6") } php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\" to temporary file") } php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(fp); fp = temp; php_stream_rewind(fp); compression = PHAR_FILE_COMPRESSED_GZ; /* now, start over */ test = '\0'; continue; } else if (!memcmp(pos, bz_magic, 3)) { php_stream_filter *filter; php_stream *temp; if (!PHAR_G(has_bz2)) { MAPPHAR_ALLOC_FAIL("unable to decompress bzipped phar archive \"%s\" to temporary file, enable bz2 extension in php.ini") } /* entire file is bzip-compressed, uncompress to temporary file */ if (!(temp = php_stream_fopen_tmpfile())) { MAPPHAR_ALLOC_FAIL("unable to create temporary file for decompression of bzipped phar archive \"%s\"") } php_stream_rewind(fp); filter = php_stream_filter_create("bzip2.decompress", NULL, php_stream_is_persistent(fp) TSRMLS_CC); if (!filter) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress bzipped phar archive \"%s\", filter creation failed") } php_stream_filter_append(&temp->writefilters, filter); if (SUCCESS != phar_stream_copy_to_stream(fp, temp, PHP_STREAM_COPY_ALL, NULL)) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress bzipped phar archive \"%s\" to temporary file") } php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(fp); fp = temp; php_stream_rewind(fp); compression = PHAR_FILE_COMPRESSED_BZ2; /* now, start over */ test = '\0'; continue; } if (!memcmp(pos, zip_magic, 4)) { php_stream_seek(fp, 0, SEEK_END); return phar_parse_zipfile(fp, fname, fname_len, alias, alias_len, pphar, error TSRMLS_CC); } if (got > 512) { if (phar_is_tar(pos, fname)) { php_stream_rewind(fp); return phar_parse_tarfile(fp, fname, fname_len, alias, alias_len, pphar, is_data, compression, error TSRMLS_CC); } } } if (got > 0 && (pos = phar_strnstr(buffer, got + sizeof(token), token, sizeof(token)-1)) != NULL) { halt_offset += (pos - buffer); /* no -tokenlen+tokenlen here */ return phar_parse_pharfile(fp, fname, fname_len, alias, alias_len, halt_offset, pphar, compression, error TSRMLS_CC); } halt_offset += got; memmove(buffer, buffer + tokenlen, got + 1); } MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (__HALT_COMPILER(); not found)") } /* }}} */ /* * given the location of the file extension and the start of the file path, * determine the end of the portion of the path (i.e. /path/to/file.ext/blah * grabs "/path/to/file.ext" as does the straight /path/to/file.ext), * stat it to determine if it exists. * if so, check to see if it is a directory and fail if so * if not, check to see if its dirname() exists (i.e. "/path/to") and is a directory * succeed if we are creating the file, otherwise fail. */ static int phar_analyze_path(const char *fname, const char *ext, int ext_len, int for_create TSRMLS_DC) /* {{{ */ { php_stream_statbuf ssb; char *realpath; char *filename = estrndup(fname, (ext - fname) + ext_len); if ((realpath = expand_filepath(filename, NULL TSRMLS_CC))) { #ifdef PHP_WIN32 phar_unixify_path_separators(realpath, strlen(realpath)); #endif if (zend_hash_exists(&(PHAR_GLOBALS->phar_fname_map), realpath, strlen(realpath))) { efree(realpath); efree(filename); return SUCCESS; } if (PHAR_G(manifest_cached) && zend_hash_exists(&cached_phars, realpath, strlen(realpath))) { efree(realpath); efree(filename); return SUCCESS; } efree(realpath); } if (SUCCESS == php_stream_stat_path((char *) filename, &ssb)) { efree(filename); if (ssb.sb.st_mode & S_IFDIR) { return FAILURE; } if (for_create == 1) { return FAILURE; } return SUCCESS; } else { char *slash; if (!for_create) { efree(filename); return FAILURE; } slash = (char *) strrchr(filename, '/'); if (slash) { *slash = '\0'; } if (SUCCESS != php_stream_stat_path((char *) filename, &ssb)) { if (!slash) { if (!(realpath = expand_filepath(filename, NULL TSRMLS_CC))) { efree(filename); return FAILURE; } #ifdef PHP_WIN32 phar_unixify_path_separators(realpath, strlen(realpath)); #endif slash = strstr(realpath, filename) + ((ext - fname) + ext_len); *slash = '\0'; slash = strrchr(realpath, '/'); if (slash) { *slash = '\0'; } else { efree(realpath); efree(filename); return FAILURE; } if (SUCCESS != php_stream_stat_path(realpath, &ssb)) { efree(realpath); efree(filename); return FAILURE; } efree(realpath); if (ssb.sb.st_mode & S_IFDIR) { efree(filename); return SUCCESS; } } efree(filename); return FAILURE; } efree(filename); if (ssb.sb.st_mode & S_IFDIR) { return SUCCESS; } return FAILURE; } } /* }}} */ /* check for ".phar" in extension */ static int phar_check_str(const char *fname, const char *ext_str, int ext_len, int executable, int for_create TSRMLS_DC) /* {{{ */ { char test[51]; const char *pos; if (ext_len >= 50) { return FAILURE; } if (executable == 1) { /* copy "." as well */ memcpy(test, ext_str - 1, ext_len + 1); test[ext_len + 1] = '\0'; /* executable phars must contain ".phar" as a valid extension (phar://.pharmy/oops is invalid) */ /* (phar://hi/there/.phar/oops is also invalid) */ pos = strstr(test, ".phar"); if (pos && (*(pos - 1) != '/') && (pos += 5) && (*pos == '\0' || *pos == '/' || *pos == '.')) { return phar_analyze_path(fname, ext_str, ext_len, for_create TSRMLS_CC); } else { return FAILURE; } } /* data phars need only contain a single non-"." to be valid */ if (!executable) { pos = strstr(ext_str, ".phar"); if (!(pos && (*(pos - 1) != '/') && (pos += 5) && (*pos == '\0' || *pos == '/' || *pos == '.')) && *(ext_str + 1) != '.' && *(ext_str + 1) != '/' && *(ext_str + 1) != '\0') { return phar_analyze_path(fname, ext_str, ext_len, for_create TSRMLS_CC); } } else { if (*(ext_str + 1) != '.' && *(ext_str + 1) != '/' && *(ext_str + 1) != '\0') { return phar_analyze_path(fname, ext_str, ext_len, for_create TSRMLS_CC); } } return FAILURE; } /* }}} */ /* * if executable is 1, only returns SUCCESS if the extension is one of the tar/zip .phar extensions * if executable is 0, it returns SUCCESS only if the filename does *not* contain ".phar" anywhere, and treats * the first extension as the filename extension * * if an extension is found, it sets ext_str to the location of the file extension in filename, * and ext_len to the length of the extension. * for urls like "phar://alias/oops" it instead sets ext_len to -1 and returns FAILURE, which tells * the calling function to use "alias" as the phar alias * * the last parameter should be set to tell the thing to assume that filename is the full path, and only to check the * extension rules, not to iterate. */ int phar_detect_phar_fname_ext(const char *filename, int filename_len, const char **ext_str, int *ext_len, int executable, int for_create, int is_complete TSRMLS_DC) /* {{{ */ { const char *pos, *slash; *ext_str = NULL; *ext_len = 0; if (!filename_len || filename_len == 1) { return FAILURE; } phar_request_initialize(TSRMLS_C); /* first check for alias in first segment */ pos = memchr(filename, '/', filename_len); if (pos && pos != filename) { /* check for url like http:// or phar:// */ if (*(pos - 1) == ':' && (pos - filename) < filename_len - 1 && *(pos + 1) == '/') { *ext_len = -2; *ext_str = NULL; return FAILURE; } if (zend_hash_exists(&(PHAR_GLOBALS->phar_alias_map), (char *) filename, pos - filename)) { *ext_str = pos; *ext_len = -1; return FAILURE; } if (PHAR_G(manifest_cached) && zend_hash_exists(&cached_alias, (char *) filename, pos - filename)) { *ext_str = pos; *ext_len = -1; return FAILURE; } } if (zend_hash_num_elements(&(PHAR_GLOBALS->phar_fname_map)) || PHAR_G(manifest_cached)) { phar_archive_data **pphar; if (is_complete) { if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), (char *) filename, filename_len, (void **)&pphar)) { *ext_str = filename + (filename_len - (*pphar)->ext_len); woohoo: *ext_len = (*pphar)->ext_len; if (executable == 2) { return SUCCESS; } if (executable == 1 && !(*pphar)->is_data) { return SUCCESS; } if (!executable && (*pphar)->is_data) { return SUCCESS; } return FAILURE; } if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, (char *) filename, filename_len, (void **)&pphar)) { *ext_str = filename + (filename_len - (*pphar)->ext_len); goto woohoo; } } else { phar_zstr key; char *str_key; uint keylen; ulong unused; zend_hash_internal_pointer_reset(&(PHAR_GLOBALS->phar_fname_map)); while (FAILURE != zend_hash_has_more_elements(&(PHAR_GLOBALS->phar_fname_map))) { if (HASH_KEY_NON_EXISTANT == zend_hash_get_current_key_ex(&(PHAR_GLOBALS->phar_fname_map), &key, &keylen, &unused, 0, NULL)) { break; } PHAR_STR(key, str_key); if (keylen > (uint) filename_len) { zend_hash_move_forward(&(PHAR_GLOBALS->phar_fname_map)); PHAR_STR_FREE(str_key); continue; } if (!memcmp(filename, str_key, keylen) && ((uint)filename_len == keylen || filename[keylen] == '/' || filename[keylen] == '\0')) { PHAR_STR_FREE(str_key); if (FAILURE == zend_hash_get_current_data(&(PHAR_GLOBALS->phar_fname_map), (void **) &pphar)) { break; } *ext_str = filename + (keylen - (*pphar)->ext_len); goto woohoo; } PHAR_STR_FREE(str_key); zend_hash_move_forward(&(PHAR_GLOBALS->phar_fname_map)); } if (PHAR_G(manifest_cached)) { zend_hash_internal_pointer_reset(&cached_phars); while (FAILURE != zend_hash_has_more_elements(&cached_phars)) { if (HASH_KEY_NON_EXISTANT == zend_hash_get_current_key_ex(&cached_phars, &key, &keylen, &unused, 0, NULL)) { break; } PHAR_STR(key, str_key); if (keylen > (uint) filename_len) { zend_hash_move_forward(&cached_phars); PHAR_STR_FREE(str_key); continue; } if (!memcmp(filename, str_key, keylen) && ((uint)filename_len == keylen || filename[keylen] == '/' || filename[keylen] == '\0')) { PHAR_STR_FREE(str_key); if (FAILURE == zend_hash_get_current_data(&cached_phars, (void **) &pphar)) { break; } *ext_str = filename + (keylen - (*pphar)->ext_len); goto woohoo; } PHAR_STR_FREE(str_key); zend_hash_move_forward(&cached_phars); } } } } pos = memchr(filename + 1, '.', filename_len); next_extension: if (!pos) { return FAILURE; } while (pos != filename && (*(pos - 1) == '/' || *(pos - 1) == '\0')) { pos = memchr(pos + 1, '.', filename_len - (pos - filename) + 1); if (!pos) { return FAILURE; } } slash = memchr(pos, '/', filename_len - (pos - filename)); if (!slash) { /* this is a url like "phar://blah.phar" with no directory */ *ext_str = pos; *ext_len = strlen(pos); /* file extension must contain "phar" */ switch (phar_check_str(filename, *ext_str, *ext_len, executable, for_create TSRMLS_CC)) { case SUCCESS: return SUCCESS; case FAILURE: /* we are at the end of the string, so we fail */ return FAILURE; } } /* we've found an extension that ends at a directory separator */ *ext_str = pos; *ext_len = slash - pos; switch (phar_check_str(filename, *ext_str, *ext_len, executable, for_create TSRMLS_CC)) { case SUCCESS: return SUCCESS; case FAILURE: /* look for more extensions */ pos = strchr(pos + 1, '.'); if (pos) { *ext_str = NULL; *ext_len = 0; } goto next_extension; } return FAILURE; } /* }}} */ static int php_check_dots(const char *element, int n) /* {{{ */ { for(n--; n >= 0; --n) { if (element[n] != '.') { return 1; } } return 0; } /* }}} */ #define IS_DIRECTORY_UP(element, len) \ (len >= 2 && !php_check_dots(element, len)) #define IS_DIRECTORY_CURRENT(element, len) \ (len == 1 && element[0] == '.') #define IS_BACKSLASH(c) ((c) == '/') #ifdef COMPILE_DL_PHAR /* stupid-ass non-extern declaration in tsrm_strtok.h breaks dumbass MS compiler */ static inline int in_character_class(char ch, const char *delim) /* {{{ */ { while (*delim) { if (*delim == ch) { return 1; } ++delim; } return 0; } /* }}} */ char *tsrm_strtok_r(char *s, const char *delim, char **last) /* {{{ */ { char *token; if (s == NULL) { s = *last; } while (*s && in_character_class(*s, delim)) { ++s; } if (!*s) { return NULL; } token = s; while (*s && !in_character_class(*s, delim)) { ++s; } if (!*s) { *last = s; } else { *s = '\0'; *last = s + 1; } return token; } /* }}} */ #endif /** * Remove .. and . references within a phar filename */ char *phar_fix_filepath(char *path, int *new_len, int use_cwd TSRMLS_DC) /* {{{ */ { char newpath[MAXPATHLEN]; int newpath_len; char *ptr; char *tok; int ptr_length, path_length = *new_len; if (PHAR_G(cwd_len) && use_cwd && path_length > 2 && path[0] == '.' && path[1] == '/') { newpath_len = PHAR_G(cwd_len); memcpy(newpath, PHAR_G(cwd), newpath_len); } else { newpath[0] = '/'; newpath_len = 1; } ptr = path; if (*ptr == '/') { ++ptr; } tok = ptr; do { ptr = memchr(ptr, '/', path_length - (ptr - path)); } while (ptr && ptr - tok == 0 && *ptr == '/' && ++ptr && ++tok); if (!ptr && (path_length - (tok - path))) { switch (path_length - (tok - path)) { case 1: if (*tok == '.') { efree(path); *new_len = 1; return estrndup("/", 1); } break; case 2: if (tok[0] == '.' && tok[1] == '.') { efree(path); *new_len = 1; return estrndup("/", 1); } } return path; } while (ptr) { ptr_length = ptr - tok; last_time: if (IS_DIRECTORY_UP(tok, ptr_length)) { #define PREVIOUS newpath[newpath_len - 1] while (newpath_len > 1 && !IS_BACKSLASH(PREVIOUS)) { newpath_len--; } if (newpath[0] != '/') { newpath[newpath_len] = '\0'; } else if (newpath_len > 1) { --newpath_len; } } else if (!IS_DIRECTORY_CURRENT(tok, ptr_length)) { if (newpath_len > 1) { newpath[newpath_len++] = '/'; memcpy(newpath + newpath_len, tok, ptr_length+1); } else { memcpy(newpath + newpath_len, tok, ptr_length+1); } newpath_len += ptr_length; } if (ptr == path + path_length) { break; } tok = ++ptr; do { ptr = memchr(ptr, '/', path_length - (ptr - path)); } while (ptr && ptr - tok == 0 && *ptr == '/' && ++ptr && ++tok); if (!ptr && (path_length - (tok - path))) { ptr_length = path_length - (tok - path); ptr = path + path_length; goto last_time; } } efree(path); *new_len = newpath_len; return estrndup(newpath, newpath_len); } /* }}} */ /** * Process a phar stream name, ensuring we can handle any of: * * - whatever.phar * - whatever.phar.gz * - whatever.phar.bz2 * - whatever.phar.php * * Optionally the name might start with 'phar://' * * This is used by phar_parse_url() */ int phar_split_fname(char *filename, int filename_len, char **arch, int *arch_len, char **entry, int *entry_len, int executable, int for_create TSRMLS_DC) /* {{{ */ { const char *ext_str; #ifdef PHP_WIN32 char *save; #endif int ext_len, free_filename = 0; if (!strncasecmp(filename, "phar://", 7)) { filename += 7; filename_len -= 7; } ext_len = 0; #ifdef PHP_WIN32 free_filename = 1; save = filename; filename = estrndup(filename, filename_len); phar_unixify_path_separators(filename, filename_len); #endif if (phar_detect_phar_fname_ext(filename, filename_len, &ext_str, &ext_len, executable, for_create, 0 TSRMLS_CC) == FAILURE) { if (ext_len != -1) { if (!ext_str) { /* no / detected, restore arch for error message */ #ifdef PHP_WIN32 *arch = save; #else *arch = filename; #endif } if (free_filename) { efree(filename); } return FAILURE; } ext_len = 0; /* no extension detected - instead we are dealing with an alias */ } *arch_len = ext_str - filename + ext_len; *arch = estrndup(filename, *arch_len); if (ext_str[ext_len]) { *entry_len = filename_len - *arch_len; *entry = estrndup(ext_str+ext_len, *entry_len); #ifdef PHP_WIN32 phar_unixify_path_separators(*entry, *entry_len); #endif *entry = phar_fix_filepath(*entry, entry_len, 0 TSRMLS_CC); } else { *entry_len = 1; *entry = estrndup("/", 1); } if (free_filename) { efree(filename); } return SUCCESS; } /* }}} */ /** * Invoked when a user calls Phar::mapPhar() from within an executing .phar * to set up its manifest directly */ int phar_open_executed_filename(char *alias, int alias_len, char **error TSRMLS_DC) /* {{{ */ { char *fname; zval *halt_constant; php_stream *fp; int fname_len; char *actual = NULL; int ret; if (error) { *error = NULL; } fname = zend_get_executed_filename(TSRMLS_C); fname_len = strlen(fname); if (phar_open_parsed_phar(fname, fname_len, alias, alias_len, 0, REPORT_ERRORS, NULL, 0 TSRMLS_CC) == SUCCESS) { return SUCCESS; } if (!strcmp(fname, "[no active file]")) { if (error) { spprintf(error, 0, "cannot initialize a phar outside of PHP execution"); } return FAILURE; } MAKE_STD_ZVAL(halt_constant); if (0 == zend_get_constant("__COMPILER_HALT_OFFSET__", 24, halt_constant TSRMLS_CC)) { FREE_ZVAL(halt_constant); if (error) { spprintf(error, 0, "__HALT_COMPILER(); must be declared in a phar"); } return FAILURE; } FREE_ZVAL(halt_constant); #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { return FAILURE; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { return FAILURE; } fp = php_stream_open_wrapper(fname, "rb", IGNORE_URL|STREAM_MUST_SEEK|REPORT_ERRORS, &actual); if (!fp) { if (error) { spprintf(error, 0, "unable to open phar for reading \"%s\"", fname); } if (actual) { efree(actual); } return FAILURE; } if (actual) { fname = actual; fname_len = strlen(actual); } ret = phar_open_from_fp(fp, fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, 0, error TSRMLS_CC); if (actual) { efree(actual); } return ret; } /* }}} */ /** * Validate the CRC32 of a file opened from within the phar */ int phar_postprocess_file(phar_entry_data *idata, php_uint32 crc32, char **error, int process_zip TSRMLS_DC) /* {{{ */ { php_uint32 crc = ~0; int len = idata->internal_file->uncompressed_filesize; php_stream *fp = idata->fp; phar_entry_info *entry = idata->internal_file; if (error) { *error = NULL; } if (entry->is_zip && process_zip > 0) { /* verify local file header */ phar_zip_file_header local; phar_zip_data_desc desc; if (SUCCESS != phar_open_archive_fp(idata->phar TSRMLS_CC)) { spprintf(error, 0, "phar error: unable to open zip-based phar archive \"%s\" to verify local file header for file \"%s\"", idata->phar->fname, entry->filename); return FAILURE; } php_stream_seek(phar_get_entrypfp(idata->internal_file TSRMLS_CC), entry->header_offset, SEEK_SET); if (sizeof(local) != php_stream_read(phar_get_entrypfp(idata->internal_file TSRMLS_CC), (char *) &local, sizeof(local))) { spprintf(error, 0, "phar error: internal corruption of zip-based phar \"%s\" (cannot read local file header for file \"%s\")", idata->phar->fname, entry->filename); return FAILURE; } /* check for data descriptor */ if (((PHAR_ZIP_16(local.flags)) & 0x8) == 0x8) { php_stream_seek(phar_get_entrypfp(idata->internal_file TSRMLS_CC), entry->header_offset + sizeof(local) + PHAR_ZIP_16(local.filename_len) + PHAR_ZIP_16(local.extra_len) + entry->compressed_filesize, SEEK_SET); if (sizeof(desc) != php_stream_read(phar_get_entrypfp(idata->internal_file TSRMLS_CC), (char *) &desc, sizeof(desc))) { spprintf(error, 0, "phar error: internal corruption of zip-based phar \"%s\" (cannot read local data descriptor for file \"%s\")", idata->phar->fname, entry->filename); return FAILURE; } if (desc.signature[0] == 'P' && desc.signature[1] == 'K') { memcpy(&(local.crc32), &(desc.crc32), 12); } else { /* old data descriptors have no signature */ memcpy(&(local.crc32), &desc, 12); } } /* verify local header */ if (entry->filename_len != PHAR_ZIP_16(local.filename_len) || entry->crc32 != PHAR_ZIP_32(local.crc32) || entry->uncompressed_filesize != PHAR_ZIP_32(local.uncompsize) || entry->compressed_filesize != PHAR_ZIP_32(local.compsize)) { spprintf(error, 0, "phar error: internal corruption of zip-based phar \"%s\" (local header of file \"%s\" does not match central directory)", idata->phar->fname, entry->filename); return FAILURE; } /* construct actual offset to file start - local extra_len can be different from central extra_len */ entry->offset = entry->offset_abs = sizeof(local) + entry->header_offset + PHAR_ZIP_16(local.filename_len) + PHAR_ZIP_16(local.extra_len); if (idata->zero && idata->zero != entry->offset_abs) { idata->zero = entry->offset_abs; } } if (process_zip == 1) { return SUCCESS; } php_stream_seek(fp, idata->zero, SEEK_SET); while (len--) { CRC32(crc, php_stream_getc(fp)); } php_stream_seek(fp, idata->zero, SEEK_SET); if (~crc == crc32) { entry->is_crc_checked = 1; return SUCCESS; } else { spprintf(error, 0, "phar error: internal corruption of phar \"%s\" (crc32 mismatch on file \"%s\")", idata->phar->fname, entry->filename); return FAILURE; } } /* }}} */ static inline void phar_set_32(char *buffer, int var) /* {{{ */ { #ifdef WORDS_BIGENDIAN *((buffer) + 3) = (unsigned char) (((var) >> 24) & 0xFF); *((buffer) + 2) = (unsigned char) (((var) >> 16) & 0xFF); *((buffer) + 1) = (unsigned char) (((var) >> 8) & 0xFF); *((buffer) + 0) = (unsigned char) ((var) & 0xFF); #else memcpy(buffer, &var, sizeof(var)); #endif } /* }}} */ static int phar_flush_clean_deleted_apply(void *data TSRMLS_DC) /* {{{ */ { phar_entry_info *entry = (phar_entry_info *)data; if (entry->fp_refcount <= 0 && entry->is_deleted) { return ZEND_HASH_APPLY_REMOVE; } else { return ZEND_HASH_APPLY_KEEP; } } /* }}} */ #include "stub.h" char *phar_create_default_stub(const char *index_php, const char *web_index, size_t *len, char **error TSRMLS_DC) /* {{{ */ { char *stub = NULL; int index_len, web_len; size_t dummy; if (!len) { len = &dummy; } if (error) { *error = NULL; } if (!index_php) { index_php = "index.php"; } if (!web_index) { web_index = "index.php"; } index_len = strlen(index_php); web_len = strlen(web_index); if (index_len > 400) { /* ridiculous size not allowed for index.php startup filename */ if (error) { spprintf(error, 0, "Illegal filename passed in for stub creation, was %d characters long, and only 400 or less is allowed", index_len); return NULL; } } if (web_len > 400) { /* ridiculous size not allowed for index.php startup filename */ if (error) { spprintf(error, 0, "Illegal web filename passed in for stub creation, was %d characters long, and only 400 or less is allowed", web_len); return NULL; } } phar_get_stub(index_php, web_index, len, &stub, index_len+1, web_len+1 TSRMLS_CC); return stub; } /* }}} */ /** * Save phar contents to disk * * user_stub contains either a string, or a resource pointer, if len is a negative length. * user_stub and len should be both 0 if the default or existing stub should be used */ int phar_flush(phar_archive_data *phar, char *user_stub, long len, int convert, char **error TSRMLS_DC) /* {{{ */ { char halt_stub[] = "__HALT_COMPILER();"; char *newstub, *tmp; phar_entry_info *entry, *newentry; int halt_offset, restore_alias_len, global_flags = 0, closeoldfile; char *pos, has_dirs = 0; char manifest[18], entry_buffer[24]; off_t manifest_ftell; long offset; size_t wrote; php_uint32 manifest_len, mytime, loc, new_manifest_count; php_uint32 newcrc32; php_stream *file, *oldfile, *newfile, *stubfile; php_stream_filter *filter; php_serialize_data_t metadata_hash; smart_str main_metadata_str = {0}; int free_user_stub, free_fp = 1, free_ufp = 1; if (phar->is_persistent) { if (error) { spprintf(error, 0, "internal error: attempt to flush cached zip-based phar \"%s\"", phar->fname); } return EOF; } if (error) { *error = NULL; } if (!zend_hash_num_elements(&phar->manifest) && !user_stub) { return EOF; } zend_hash_clean(&phar->virtual_dirs); if (phar->is_zip) { return phar_zip_flush(phar, user_stub, len, convert, error TSRMLS_CC); } if (phar->is_tar) { return phar_tar_flush(phar, user_stub, len, convert, error TSRMLS_CC); } if (PHAR_G(readonly)) { return EOF; } if (phar->fp && !phar->is_brandnew) { oldfile = phar->fp; closeoldfile = 0; php_stream_rewind(oldfile); } else { oldfile = php_stream_open_wrapper(phar->fname, "rb", 0, NULL); closeoldfile = oldfile != NULL; } newfile = php_stream_fopen_tmpfile(); if (!newfile) { if (error) { spprintf(error, 0, "unable to create temporary file"); } if (closeoldfile) { php_stream_close(oldfile); } return EOF; } if (user_stub) { if (len < 0) { /* resource passed in */ if (!(php_stream_from_zval_no_verify(stubfile, (zval **)user_stub))) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to access resource to copy stub to new phar \"%s\"", phar->fname); } return EOF; } if (len == -1) { len = PHP_STREAM_COPY_ALL; } else { len = -len; } user_stub = 0; #if PHP_MAJOR_VERSION >= 6 if (!(len = php_stream_copy_to_mem(stubfile, (void **) &user_stub, len, 0)) || !user_stub) { #else if (!(len = php_stream_copy_to_mem(stubfile, &user_stub, len, 0)) || !user_stub) { #endif if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to read resource to copy stub to new phar \"%s\"", phar->fname); } return EOF; } free_user_stub = 1; } else { free_user_stub = 0; } tmp = estrndup(user_stub, len); if ((pos = php_stristr(tmp, halt_stub, len, sizeof(halt_stub) - 1)) == NULL) { efree(tmp); if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "illegal stub for phar \"%s\"", phar->fname); } if (free_user_stub) { efree(user_stub); } return EOF; } pos = user_stub + (pos - tmp); efree(tmp); len = pos - user_stub + 18; if ((size_t)len != php_stream_write(newfile, user_stub, len) || 5 != php_stream_write(newfile, " ?>\r\n", 5)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to create stub from string in new phar \"%s\"", phar->fname); } if (free_user_stub) { efree(user_stub); } return EOF; } phar->halt_offset = len + 5; if (free_user_stub) { efree(user_stub); } } else { size_t written; if (!user_stub && phar->halt_offset && oldfile && !phar->is_brandnew) { phar_stream_copy_to_stream(oldfile, newfile, phar->halt_offset, &written); newstub = NULL; } else { /* this is either a brand new phar or a default stub overwrite */ newstub = phar_create_default_stub(NULL, NULL, &(phar->halt_offset), NULL TSRMLS_CC); written = php_stream_write(newfile, newstub, phar->halt_offset); } if (phar->halt_offset != written) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { if (newstub) { spprintf(error, 0, "unable to create stub in new phar \"%s\"", phar->fname); } else { spprintf(error, 0, "unable to copy stub of old phar to new phar \"%s\"", phar->fname); } } if (newstub) { efree(newstub); } return EOF; } if (newstub) { efree(newstub); } } manifest_ftell = php_stream_tell(newfile); halt_offset = manifest_ftell; /* Check whether we can get rid of some of the deleted entries which are * unused. However some might still be in use so even after this clean-up * we need to skip entries marked is_deleted. */ zend_hash_apply(&phar->manifest, phar_flush_clean_deleted_apply TSRMLS_CC); /* compress as necessary, calculate crcs, serialize meta-data, manifest size, and file sizes */ main_metadata_str.c = 0; if (phar->metadata) { PHP_VAR_SERIALIZE_INIT(metadata_hash); php_var_serialize(&main_metadata_str, &phar->metadata, &metadata_hash TSRMLS_CC); PHP_VAR_SERIALIZE_DESTROY(metadata_hash); } else { main_metadata_str.len = 0; } new_manifest_count = 0; offset = 0; for (zend_hash_internal_pointer_reset(&phar->manifest); zend_hash_has_more_elements(&phar->manifest) == SUCCESS; zend_hash_move_forward(&phar->manifest)) { if (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) { continue; } if (entry->cfp) { /* did we forget to get rid of cfp last time? */ php_stream_close(entry->cfp); entry->cfp = 0; } if (entry->is_deleted || entry->is_mounted) { /* remove this from the new phar */ continue; } if (!entry->is_modified && entry->fp_refcount) { /* open file pointers refer to this fp, do not free the stream */ switch (entry->fp_type) { case PHAR_FP: free_fp = 0; break; case PHAR_UFP: free_ufp = 0; default: break; } } /* after excluding deleted files, calculate manifest size in bytes and number of entries */ ++new_manifest_count; phar_add_virtual_dirs(phar, entry->filename, entry->filename_len TSRMLS_CC); if (entry->is_dir) { /* we use this to calculate API version, 1.1.1 is used for phars with directories */ has_dirs = 1; } if (entry->metadata) { if (entry->metadata_str.c) { smart_str_free(&entry->metadata_str); } entry->metadata_str.c = 0; entry->metadata_str.len = 0; PHP_VAR_SERIALIZE_INIT(metadata_hash); php_var_serialize(&entry->metadata_str, &entry->metadata, &metadata_hash TSRMLS_CC); PHP_VAR_SERIALIZE_DESTROY(metadata_hash); } else { if (entry->metadata_str.c) { smart_str_free(&entry->metadata_str); } entry->metadata_str.c = 0; entry->metadata_str.len = 0; } /* 32 bits for filename length, length of filename, manifest + metadata, and add 1 for trailing / if a directory */ offset += 4 + entry->filename_len + sizeof(entry_buffer) + entry->metadata_str.len + (entry->is_dir ? 1 : 0); /* compress and rehash as necessary */ if ((oldfile && !entry->is_modified) || entry->is_dir) { if (entry->fp_type == PHAR_UFP) { /* reset so we can copy the compressed data over */ entry->fp_type = PHAR_FP; } continue; } if (!phar_get_efp(entry, 0 TSRMLS_CC)) { /* re-open internal file pointer just-in-time */ newentry = phar_open_jit(phar, entry, error TSRMLS_CC); if (!newentry) { /* major problem re-opening, so we ignore this file and the error */ efree(*error); *error = NULL; continue; } entry = newentry; } file = phar_get_efp(entry, 0 TSRMLS_CC); if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 1 TSRMLS_CC)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } newcrc32 = ~0; mytime = entry->uncompressed_filesize; for (loc = 0;loc < mytime; ++loc) { CRC32(newcrc32, php_stream_getc(file)); } entry->crc32 = ~newcrc32; entry->is_crc_checked = 1; if (!(entry->flags & PHAR_ENT_COMPRESSION_MASK)) { /* not compressed */ entry->compressed_filesize = entry->uncompressed_filesize; continue; } filter = php_stream_filter_create(phar_compress_filter(entry, 0), NULL, 0 TSRMLS_CC); if (!filter) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (entry->flags & PHAR_ENT_COMPRESSED_GZ) { if (error) { spprintf(error, 0, "unable to gzip compress file \"%s\" to new phar \"%s\"", entry->filename, phar->fname); } } else { if (error) { spprintf(error, 0, "unable to bzip2 compress file \"%s\" to new phar \"%s\"", entry->filename, phar->fname); } } return EOF; } /* create new file that holds the compressed version */ /* work around inability to specify freedom in write and strictness in read count */ entry->cfp = php_stream_fopen_tmpfile(); if (!entry->cfp) { if (error) { spprintf(error, 0, "unable to create temporary file"); } if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); return EOF; } php_stream_flush(file); if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 0 TSRMLS_CC)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } php_stream_filter_append((&entry->cfp->writefilters), filter); if (SUCCESS != phar_stream_copy_to_stream(file, entry->cfp, entry->uncompressed_filesize, NULL)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to copy compressed file contents of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } php_stream_filter_flush(filter, 1); php_stream_flush(entry->cfp); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_seek(entry->cfp, 0, SEEK_END); entry->compressed_filesize = (php_uint32) php_stream_tell(entry->cfp); /* generate crc on compressed file */ php_stream_rewind(entry->cfp); entry->old_flags = entry->flags; entry->is_modified = 1; global_flags |= (entry->flags & PHAR_ENT_COMPRESSION_MASK); } global_flags |= PHAR_HDR_SIGNATURE; /* write out manifest pre-header */ /* 4: manifest length * 4: manifest entry count * 2: phar version * 4: phar global flags * 4: alias length * ?: the alias itself * 4: phar metadata length * ?: phar metadata */ restore_alias_len = phar->alias_len; if (phar->is_temporary_alias) { phar->alias_len = 0; } manifest_len = offset + phar->alias_len + sizeof(manifest) + main_metadata_str.len; phar_set_32(manifest, manifest_len); phar_set_32(manifest+4, new_manifest_count); if (has_dirs) { *(manifest + 8) = (unsigned char) (((PHAR_API_VERSION) >> 8) & 0xFF); *(manifest + 9) = (unsigned char) (((PHAR_API_VERSION) & 0xF0)); } else { *(manifest + 8) = (unsigned char) (((PHAR_API_VERSION_NODIR) >> 8) & 0xFF); *(manifest + 9) = (unsigned char) (((PHAR_API_VERSION_NODIR) & 0xF0)); } phar_set_32(manifest+10, global_flags); phar_set_32(manifest+14, phar->alias_len); /* write the manifest header */ if (sizeof(manifest) != php_stream_write(newfile, manifest, sizeof(manifest)) || (size_t)phar->alias_len != php_stream_write(newfile, phar->alias, phar->alias_len)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); phar->alias_len = restore_alias_len; if (error) { spprintf(error, 0, "unable to write manifest header of new phar \"%s\"", phar->fname); } return EOF; } phar->alias_len = restore_alias_len; phar_set_32(manifest, main_metadata_str.len); if (4 != php_stream_write(newfile, manifest, 4) || (main_metadata_str.len && main_metadata_str.len != php_stream_write(newfile, main_metadata_str.c, main_metadata_str.len))) { smart_str_free(&main_metadata_str); if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); phar->alias_len = restore_alias_len; if (error) { spprintf(error, 0, "unable to write manifest meta-data of new phar \"%s\"", phar->fname); } return EOF; } smart_str_free(&main_metadata_str); /* re-calculate the manifest location to simplify later code */ manifest_ftell = php_stream_tell(newfile); /* now write the manifest */ for (zend_hash_internal_pointer_reset(&phar->manifest); zend_hash_has_more_elements(&phar->manifest) == SUCCESS; zend_hash_move_forward(&phar->manifest)) { if (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) { continue; } if (entry->is_deleted || entry->is_mounted) { /* remove this from the new phar if deleted, ignore if mounted */ continue; } if (entry->is_dir) { /* add 1 for trailing slash */ phar_set_32(entry_buffer, entry->filename_len + 1); } else { phar_set_32(entry_buffer, entry->filename_len); } if (4 != php_stream_write(newfile, entry_buffer, 4) || entry->filename_len != php_stream_write(newfile, entry->filename, entry->filename_len) || (entry->is_dir && 1 != php_stream_write(newfile, "/", 1))) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { if (entry->is_dir) { spprintf(error, 0, "unable to write filename of directory \"%s\" to manifest of new phar \"%s\"", entry->filename, phar->fname); } else { spprintf(error, 0, "unable to write filename of file \"%s\" to manifest of new phar \"%s\"", entry->filename, phar->fname); } } return EOF; } /* set the manifest meta-data: 4: uncompressed filesize 4: creation timestamp 4: compressed filesize 4: crc32 4: flags 4: metadata-len +: metadata */ mytime = time(NULL); phar_set_32(entry_buffer, entry->uncompressed_filesize); phar_set_32(entry_buffer+4, mytime); phar_set_32(entry_buffer+8, entry->compressed_filesize); phar_set_32(entry_buffer+12, entry->crc32); phar_set_32(entry_buffer+16, entry->flags); phar_set_32(entry_buffer+20, entry->metadata_str.len); if (sizeof(entry_buffer) != php_stream_write(newfile, entry_buffer, sizeof(entry_buffer)) || entry->metadata_str.len != php_stream_write(newfile, entry->metadata_str.c, entry->metadata_str.len)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to write temporary manifest of file \"%s\" to manifest of new phar \"%s\"", entry->filename, phar->fname); } return EOF; } } /* now copy the actual file data to the new phar */ offset = php_stream_tell(newfile); for (zend_hash_internal_pointer_reset(&phar->manifest); zend_hash_has_more_elements(&phar->manifest) == SUCCESS; zend_hash_move_forward(&phar->manifest)) { if (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) { continue; } if (entry->is_deleted || entry->is_dir || entry->is_mounted) { continue; } if (entry->cfp) { file = entry->cfp; php_stream_rewind(file); } else { file = phar_get_efp(entry, 0 TSRMLS_CC); if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 0 TSRMLS_CC)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } } if (!file) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } /* this will have changed for all files that have either changed compression or been modified */ entry->offset = entry->offset_abs = offset; offset += entry->compressed_filesize; phar_stream_copy_to_stream(file, newfile, entry->compressed_filesize, &wrote); if (entry->compressed_filesize != wrote) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to write contents of file \"%s\" to new phar \"%s\"", entry->filename, phar->fname); } return EOF; } entry->is_modified = 0; if (entry->cfp) { php_stream_close(entry->cfp); entry->cfp = NULL; } if (entry->fp_type == PHAR_MOD) { /* this fp is in use by a phar_entry_data returned by phar_get_entry_data, it will be closed when the phar_entry_data is phar_entry_delref'ed */ if (entry->fp_refcount == 0 && entry->fp != phar->fp && entry->fp != phar->ufp) { php_stream_close(entry->fp); } entry->fp = NULL; entry->fp_type = PHAR_FP; } else if (entry->fp_type == PHAR_UFP) { entry->fp_type = PHAR_FP; } } /* append signature */ if (global_flags & PHAR_HDR_SIGNATURE) { char sig_buf[4]; php_stream_rewind(newfile); if (phar->signature) { efree(phar->signature); phar->signature = NULL; } switch(phar->sig_flags) { #ifndef PHAR_HASH_OK case PHAR_SIG_SHA512: case PHAR_SIG_SHA256: if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to write contents of file \"%s\" to new phar \"%s\" with requested hash type", entry->filename, phar->fname); } return EOF; #endif default: { char *digest = NULL; int digest_len; if (FAILURE == phar_create_signature(phar, newfile, &digest, &digest_len, error TSRMLS_CC)) { if (error) { char *save = *error; spprintf(error, 0, "phar error: unable to write signature: %s", save); efree(save); } if (digest) { efree(digest); } if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); return EOF; } php_stream_write(newfile, digest, digest_len); efree(digest); if (phar->sig_flags == PHAR_SIG_OPENSSL) { phar_set_32(sig_buf, digest_len); php_stream_write(newfile, sig_buf, 4); } break; } } phar_set_32(sig_buf, phar->sig_flags); php_stream_write(newfile, sig_buf, 4); php_stream_write(newfile, "GBMB", 4); } /* finally, close the temp file, rename the original phar, move the temp to the old phar, unlink the old phar, and reload it into memory */ if (phar->fp && free_fp) { php_stream_close(phar->fp); } if (phar->ufp) { if (free_ufp) { php_stream_close(phar->ufp); } phar->ufp = NULL; } if (closeoldfile) { php_stream_close(oldfile); } phar->internal_file_start = halt_offset + manifest_len + 4; phar->halt_offset = halt_offset; phar->is_brandnew = 0; php_stream_rewind(newfile); if (phar->donotflush) { /* deferred flush */ phar->fp = newfile; } else { phar->fp = php_stream_open_wrapper(phar->fname, "w+b", IGNORE_URL|STREAM_MUST_SEEK|REPORT_ERRORS, NULL); if (!phar->fp) { phar->fp = newfile; if (error) { spprintf(error, 4096, "unable to open new phar \"%s\" for writing", phar->fname); } return EOF; } if (phar->flags & PHAR_FILE_COMPRESSED_GZ) { /* to properly compress, we have to tell zlib to add a zlib header */ zval filterparams; array_init(&filterparams); add_assoc_long(&filterparams, "window", MAX_WBITS+16); filter = php_stream_filter_create("zlib.deflate", &filterparams, php_stream_is_persistent(phar->fp) TSRMLS_CC); zval_dtor(&filterparams); if (!filter) { if (error) { spprintf(error, 4096, "unable to compress all contents of phar \"%s\" using zlib, PHP versions older than 5.2.6 have a buggy zlib", phar->fname); } return EOF; } php_stream_filter_append(&phar->fp->writefilters, filter); phar_stream_copy_to_stream(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL); php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(phar->fp); /* use the temp stream as our base */ phar->fp = newfile; } else if (phar->flags & PHAR_FILE_COMPRESSED_BZ2) { filter = php_stream_filter_create("bzip2.compress", NULL, php_stream_is_persistent(phar->fp) TSRMLS_CC); php_stream_filter_append(&phar->fp->writefilters, filter); phar_stream_copy_to_stream(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL); php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(phar->fp); /* use the temp stream as our base */ phar->fp = newfile; } else { phar_stream_copy_to_stream(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL); /* we could also reopen the file in "rb" mode but there is no need for that */ php_stream_close(newfile); } } if (-1 == php_stream_seek(phar->fp, phar->halt_offset, SEEK_SET)) { if (error) { spprintf(error, 0, "unable to seek to __HALT_COMPILER(); in new phar \"%s\"", phar->fname); } return EOF; } return EOF; } /* }}} */ #ifdef COMPILE_DL_PHAR ZEND_GET_MODULE(phar) #endif /* {{{ phar_functions[] * * Every user visible function must have an entry in phar_functions[]. */ zend_function_entry phar_functions[] = { {NULL, NULL, NULL} /* Must be the last line in phar_functions[] */ }; /* }}}*/ static size_t phar_zend_stream_reader(void *handle, char *buf, size_t len TSRMLS_DC) /* {{{ */ { return php_stream_read(phar_get_pharfp((phar_archive_data*)handle TSRMLS_CC), buf, len); } /* }}} */ #if PHP_VERSION_ID >= 50300 static size_t phar_zend_stream_fsizer(void *handle TSRMLS_DC) /* {{{ */ { return ((phar_archive_data*)handle)->halt_offset + 32; } /* }}} */ #else /* PHP_VERSION_ID */ static long phar_stream_fteller_for_zend(void *handle TSRMLS_DC) /* {{{ */ { return (long)php_stream_tell(phar_get_pharfp((phar_archive_data*)handle TSRMLS_CC)); } /* }}} */ #endif zend_op_array *(*phar_orig_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); #if PHP_VERSION_ID >= 50300 #define phar_orig_zend_open zend_stream_open_function static char *phar_resolve_path(const char *filename, int filename_len TSRMLS_DC) { return phar_find_in_include_path((char *) filename, filename_len, NULL TSRMLS_CC); } #else int (*phar_orig_zend_open)(const char *filename, zend_file_handle *handle TSRMLS_DC); #endif static zend_op_array *phar_compile_file(zend_file_handle *file_handle, int type TSRMLS_DC) /* {{{ */ { zend_op_array *res; char *name = NULL; int failed; phar_archive_data *phar; if (!file_handle || !file_handle->filename) { return phar_orig_compile_file(file_handle, type TSRMLS_CC); } if (strstr(file_handle->filename, ".phar") && !strstr(file_handle->filename, "://")) { if (SUCCESS == phar_open_from_filename(file_handle->filename, strlen(file_handle->filename), NULL, 0, 0, &phar, NULL TSRMLS_CC)) { if (phar->is_zip || phar->is_tar) { zend_file_handle f = *file_handle; /* zip or tar-based phar */ spprintf(&name, 4096, "phar://%s/%s", file_handle->filename, ".phar/stub.php"); if (SUCCESS == phar_orig_zend_open((const char *)name, file_handle TSRMLS_CC)) { efree(name); name = NULL; file_handle->filename = f.filename; if (file_handle->opened_path) { efree(file_handle->opened_path); } file_handle->opened_path = f.opened_path; file_handle->free_filename = f.free_filename; } else { *file_handle = f; } } else if (phar->flags & PHAR_FILE_COMPRESSION_MASK) { /* compressed phar */ #if PHP_VERSION_ID >= 50300 file_handle->type = ZEND_HANDLE_STREAM; /* we do our own reading directly from the phar, don't change the next line */ file_handle->handle.stream.handle = phar; file_handle->handle.stream.reader = phar_zend_stream_reader; file_handle->handle.stream.closer = NULL; file_handle->handle.stream.fsizer = phar_zend_stream_fsizer; file_handle->handle.stream.isatty = 0; phar->is_persistent ? php_stream_rewind(PHAR_GLOBALS->cached_fp[phar->phar_pos].fp) : php_stream_rewind(phar->fp); memset(&file_handle->handle.stream.mmap, 0, sizeof(file_handle->handle.stream.mmap)); #else /* PHP_VERSION_ID */ file_handle->type = ZEND_HANDLE_STREAM; /* we do our own reading directly from the phar, don't change the next line */ file_handle->handle.stream.handle = phar; file_handle->handle.stream.reader = phar_zend_stream_reader; file_handle->handle.stream.closer = NULL; /* don't close - let phar handle this one */ file_handle->handle.stream.fteller = phar_stream_fteller_for_zend; file_handle->handle.stream.interactive = 0; phar->is_persistent ? php_stream_rewind(PHAR_GLOBALS->cached_fp[phar->phar_pos].fp) : php_stream_rewind(phar->fp); #endif } } } zend_try { failed = 0; res = phar_orig_compile_file(file_handle, type TSRMLS_CC); } zend_catch { failed = 1; } zend_end_try(); if (name) { efree(name); } if (failed) { zend_bailout(); } return res; } /* }}} */ #if PHP_VERSION_ID < 50300 int phar_zend_open(const char *filename, zend_file_handle *handle TSRMLS_DC) /* {{{ */ { char *arch, *entry; int arch_len, entry_len; /* this code is obsoleted in php 5.3 */ entry = (char *) filename; if (!IS_ABSOLUTE_PATH(entry, strlen(entry)) && !strstr(entry, "://")) { phar_archive_data **pphar = NULL; char *fname; int fname_len; fname = zend_get_executed_filename(TSRMLS_C); fname_len = strlen(fname); if (fname_len > 7 && !strncasecmp(fname, "phar://", 7)) { if (SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 1, 0 TSRMLS_CC)) { zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), arch, arch_len, (void **) &pphar); if (!pphar && PHAR_G(manifest_cached)) { zend_hash_find(&cached_phars, arch, arch_len, (void **) &pphar); } efree(arch); efree(entry); } } /* retrieving an include within the current directory, so use this if possible */ if (!(entry = phar_find_in_include_path((char *) filename, strlen(filename), NULL TSRMLS_CC))) { /* this file is not in the phar, use the original path */ goto skip_phar; } if (SUCCESS == phar_orig_zend_open(entry, handle TSRMLS_CC)) { if (!handle->opened_path) { handle->opened_path = entry; } if (entry != filename) { handle->free_filename = 1; } return SUCCESS; } if (entry != filename) { efree(entry); } return FAILURE; } skip_phar: return phar_orig_zend_open(filename, handle TSRMLS_CC); } /* }}} */ #endif typedef zend_op_array* (zend_compile_t)(zend_file_handle*, int TSRMLS_DC); typedef zend_compile_t* (compile_hook)(zend_compile_t *ptr); PHP_GINIT_FUNCTION(phar) /* {{{ */ { phar_mime_type mime; memset(phar_globals, 0, sizeof(zend_phar_globals)); phar_globals->readonly = 1; zend_hash_init(&phar_globals->mime_types, 0, NULL, NULL, 1); #define PHAR_SET_MIME(mimetype, ret, fileext) \ mime.mime = mimetype; \ mime.len = sizeof((mimetype))+1; \ mime.type = ret; \ zend_hash_add(&phar_globals->mime_types, fileext, sizeof(fileext)-1, (void *)&mime, sizeof(phar_mime_type), NULL); \ PHAR_SET_MIME("text/html", PHAR_MIME_PHPS, "phps") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "c") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "cc") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "cpp") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "c++") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "dtd") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "h") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "log") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "rng") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "txt") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "xsd") PHAR_SET_MIME("", PHAR_MIME_PHP, "php") PHAR_SET_MIME("", PHAR_MIME_PHP, "inc") PHAR_SET_MIME("video/avi", PHAR_MIME_OTHER, "avi") PHAR_SET_MIME("image/bmp", PHAR_MIME_OTHER, "bmp") PHAR_SET_MIME("text/css", PHAR_MIME_OTHER, "css") PHAR_SET_MIME("image/gif", PHAR_MIME_OTHER, "gif") PHAR_SET_MIME("text/html", PHAR_MIME_OTHER, "htm") PHAR_SET_MIME("text/html", PHAR_MIME_OTHER, "html") PHAR_SET_MIME("text/html", PHAR_MIME_OTHER, "htmls") PHAR_SET_MIME("image/x-ico", PHAR_MIME_OTHER, "ico") PHAR_SET_MIME("image/jpeg", PHAR_MIME_OTHER, "jpe") PHAR_SET_MIME("image/jpeg", PHAR_MIME_OTHER, "jpg") PHAR_SET_MIME("image/jpeg", PHAR_MIME_OTHER, "jpeg") PHAR_SET_MIME("application/x-javascript", PHAR_MIME_OTHER, "js") PHAR_SET_MIME("audio/midi", PHAR_MIME_OTHER, "midi") PHAR_SET_MIME("audio/midi", PHAR_MIME_OTHER, "mid") PHAR_SET_MIME("audio/mod", PHAR_MIME_OTHER, "mod") PHAR_SET_MIME("movie/quicktime", PHAR_MIME_OTHER, "mov") PHAR_SET_MIME("audio/mp3", PHAR_MIME_OTHER, "mp3") PHAR_SET_MIME("video/mpeg", PHAR_MIME_OTHER, "mpg") PHAR_SET_MIME("video/mpeg", PHAR_MIME_OTHER, "mpeg") PHAR_SET_MIME("application/pdf", PHAR_MIME_OTHER, "pdf") PHAR_SET_MIME("image/png", PHAR_MIME_OTHER, "png") PHAR_SET_MIME("application/shockwave-flash", PHAR_MIME_OTHER, "swf") PHAR_SET_MIME("image/tiff", PHAR_MIME_OTHER, "tif") PHAR_SET_MIME("image/tiff", PHAR_MIME_OTHER, "tiff") PHAR_SET_MIME("audio/wav", PHAR_MIME_OTHER, "wav") PHAR_SET_MIME("image/xbm", PHAR_MIME_OTHER, "xbm") PHAR_SET_MIME("text/xml", PHAR_MIME_OTHER, "xml") phar_restore_orig_functions(TSRMLS_C); } /* }}} */ PHP_GSHUTDOWN_FUNCTION(phar) /* {{{ */ { zend_hash_destroy(&phar_globals->mime_types); } /* }}} */ PHP_MINIT_FUNCTION(phar) /* {{{ */ { REGISTER_INI_ENTRIES(); phar_orig_compile_file = zend_compile_file; zend_compile_file = phar_compile_file; #if PHP_VERSION_ID >= 50300 phar_save_resolve_path = zend_resolve_path; zend_resolve_path = phar_resolve_path; #else phar_orig_zend_open = zend_stream_open_function; zend_stream_open_function = phar_zend_open; #endif phar_object_init(TSRMLS_C); phar_intercept_functions_init(TSRMLS_C); phar_save_orig_functions(TSRMLS_C); return php_register_url_stream_wrapper("phar", &php_stream_phar_wrapper TSRMLS_CC); } /* }}} */ PHP_MSHUTDOWN_FUNCTION(phar) /* {{{ */ { php_unregister_url_stream_wrapper("phar" TSRMLS_CC); phar_intercept_functions_shutdown(TSRMLS_C); if (zend_compile_file == phar_compile_file) { zend_compile_file = phar_orig_compile_file; } #if PHP_VERSION_ID < 50300 if (zend_stream_open_function == phar_zend_open) { zend_stream_open_function = phar_orig_zend_open; } #endif if (PHAR_G(manifest_cached)) { zend_hash_destroy(&(cached_phars)); zend_hash_destroy(&(cached_alias)); } return SUCCESS; } /* }}} */ void phar_request_initialize(TSRMLS_D) /* {{{ */ { if (!PHAR_GLOBALS->request_init) { PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; PHAR_G(has_bz2) = zend_hash_exists(&module_registry, "bz2", sizeof("bz2")); PHAR_G(has_zlib) = zend_hash_exists(&module_registry, "zlib", sizeof("zlib")); PHAR_GLOBALS->request_init = 1; PHAR_GLOBALS->request_ends = 0; PHAR_GLOBALS->request_done = 0; zend_hash_init(&(PHAR_GLOBALS->phar_fname_map), 5, zend_get_hash_value, destroy_phar_data, 0); zend_hash_init(&(PHAR_GLOBALS->phar_persist_map), 5, zend_get_hash_value, NULL, 0); zend_hash_init(&(PHAR_GLOBALS->phar_alias_map), 5, zend_get_hash_value, NULL, 0); if (PHAR_G(manifest_cached)) { phar_archive_data **pphar; phar_entry_fp *stuff = (phar_entry_fp *) ecalloc(zend_hash_num_elements(&cached_phars), sizeof(phar_entry_fp)); for (zend_hash_internal_pointer_reset(&cached_phars); zend_hash_get_current_data(&cached_phars, (void **)&pphar) == SUCCESS; zend_hash_move_forward(&cached_phars)) { stuff[pphar[0]->phar_pos].manifest = (phar_entry_fp_info *) ecalloc( zend_hash_num_elements(&(pphar[0]->manifest)), sizeof(phar_entry_fp_info)); } PHAR_GLOBALS->cached_fp = stuff; } PHAR_GLOBALS->phar_SERVER_mung_list = 0; PHAR_G(cwd) = NULL; PHAR_G(cwd_len) = 0; PHAR_G(cwd_init) = 0; } } /* }}} */ PHP_RSHUTDOWN_FUNCTION(phar) /* {{{ */ { int i; PHAR_GLOBALS->request_ends = 1; if (PHAR_GLOBALS->request_init) { phar_release_functions(TSRMLS_C); zend_hash_destroy(&(PHAR_GLOBALS->phar_alias_map)); PHAR_GLOBALS->phar_alias_map.arBuckets = NULL; zend_hash_destroy(&(PHAR_GLOBALS->phar_fname_map)); PHAR_GLOBALS->phar_fname_map.arBuckets = NULL; zend_hash_destroy(&(PHAR_GLOBALS->phar_persist_map)); PHAR_GLOBALS->phar_persist_map.arBuckets = NULL; PHAR_GLOBALS->phar_SERVER_mung_list = 0; if (PHAR_GLOBALS->cached_fp) { for (i = 0; i < zend_hash_num_elements(&cached_phars); ++i) { if (PHAR_GLOBALS->cached_fp[i].fp) { php_stream_close(PHAR_GLOBALS->cached_fp[i].fp); } if (PHAR_GLOBALS->cached_fp[i].ufp) { php_stream_close(PHAR_GLOBALS->cached_fp[i].ufp); } efree(PHAR_GLOBALS->cached_fp[i].manifest); } efree(PHAR_GLOBALS->cached_fp); PHAR_GLOBALS->cached_fp = 0; } PHAR_GLOBALS->request_init = 0; if (PHAR_G(cwd)) { efree(PHAR_G(cwd)); } PHAR_G(cwd) = NULL; PHAR_G(cwd_len) = 0; PHAR_G(cwd_init) = 0; } PHAR_GLOBALS->request_done = 1; return SUCCESS; } /* }}} */ PHP_MINFO_FUNCTION(phar) /* {{{ */ { phar_request_initialize(TSRMLS_C); php_info_print_table_start(); php_info_print_table_header(2, "Phar: PHP Archive support", "enabled"); php_info_print_table_row(2, "Phar EXT version", PHP_PHAR_VERSION); php_info_print_table_row(2, "Phar API version", PHP_PHAR_API_VERSION); php_info_print_table_row(2, "SVN revision", "$Revision$"); php_info_print_table_row(2, "Phar-based phar archives", "enabled"); php_info_print_table_row(2, "Tar-based phar archives", "enabled"); php_info_print_table_row(2, "ZIP-based phar archives", "enabled"); if (PHAR_G(has_zlib)) { php_info_print_table_row(2, "gzip compression", "enabled"); } else { php_info_print_table_row(2, "gzip compression", "disabled (install ext/zlib)"); } if (PHAR_G(has_bz2)) { php_info_print_table_row(2, "bzip2 compression", "enabled"); } else { php_info_print_table_row(2, "bzip2 compression", "disabled (install pecl/bz2)"); } #ifdef PHAR_HAVE_OPENSSL php_info_print_table_row(2, "Native OpenSSL support", "enabled"); #else if (zend_hash_exists(&module_registry, "openssl", sizeof("openssl"))) { php_info_print_table_row(2, "OpenSSL support", "enabled"); } else { php_info_print_table_row(2, "OpenSSL support", "disabled (install ext/openssl)"); } #endif php_info_print_table_end(); php_info_print_box_start(0); PUTS("Phar based on pear/PHP_Archive, original concept by Davey Shafik."); PUTS(!sapi_module.phpinfo_as_text?"<br />":"\n"); PUTS("Phar fully realized by Gregory Beaver and Marcus Boerger."); PUTS(!sapi_module.phpinfo_as_text?"<br />":"\n"); PUTS("Portions of tar implementation Copyright (c) 2003-2009 Tim Kientzle."); php_info_print_box_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ /* {{{ phar_module_entry */ static const zend_module_dep phar_deps[] = { ZEND_MOD_OPTIONAL("apc") ZEND_MOD_OPTIONAL("bz2") ZEND_MOD_OPTIONAL("openssl") ZEND_MOD_OPTIONAL("zlib") ZEND_MOD_OPTIONAL("standard") #if defined(HAVE_HASH) && !defined(COMPILE_DL_HASH) ZEND_MOD_REQUIRED("hash") #endif #if HAVE_SPL ZEND_MOD_REQUIRED("spl") #endif {NULL, NULL, NULL} }; zend_module_entry phar_module_entry = { STANDARD_MODULE_HEADER_EX, NULL, phar_deps, "Phar", phar_functions, PHP_MINIT(phar), PHP_MSHUTDOWN(phar), NULL, PHP_RSHUTDOWN(phar), PHP_MINFO(phar), PHP_PHAR_VERSION, PHP_MODULE_GLOBALS(phar), /* globals descriptor */ PHP_GINIT(phar), /* globals ctor */ PHP_GSHUTDOWN(phar), /* globals dtor */ NULL, /* post deactivate */ STANDARD_MODULE_PROPERTIES_EX }; /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-02-01-fefe9fc5c7-0927309852.c
manybugs_data_44
/*--------------------------------------------------------------------*/ /*--- An implementation of malloc/free which doesn't use sbrk. ---*/ /*--- m_mallocfree.c ---*/ /*--------------------------------------------------------------------*/ /* This file is part of Valgrind, a dynamic binary instrumentation framework. Copyright (C) 2000-2011 Julian Seward [email protected] This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. The GNU General Public License is contained in the file COPYING. */ #include "pub_core_basics.h" #include "pub_core_vki.h" #include "pub_core_debuglog.h" #include "pub_core_libcbase.h" #include "pub_core_aspacemgr.h" #include "pub_core_libcassert.h" #include "pub_core_libcprint.h" #include "pub_core_mallocfree.h" #include "pub_core_options.h" #include "pub_core_libcsetjmp.h" // to keep _threadstate.h happy #include "pub_core_threadstate.h" // For VG_INVALID_THREADID #include "pub_core_transtab.h" #include "pub_core_tooliface.h" #include "pub_tool_inner.h" #if defined(ENABLE_INNER_CLIENT_REQUEST) #include "memcheck/memcheck.h" #endif // #define DEBUG_MALLOC // turn on heavyweight debugging machinery // #define VERBOSE_MALLOC // make verbose, esp. in debugging machinery /* Number and total size of blocks in free queue. Used by mallinfo(). */ Long VG_(free_queue_volume) = 0; Long VG_(free_queue_length) = 0; static void cc_analyse_alloc_arena ( ArenaId aid ); /* fwds */ /*------------------------------------------------------------*/ /*--- Main types ---*/ /*------------------------------------------------------------*/ #define N_MALLOC_LISTS 112 // do not change this // The amount you can ask for is limited only by sizeof(SizeT)... #define MAX_PSZB (~((SizeT)0x0)) // Each arena has a sorted array of superblocks, which expands // dynamically. This is its initial size. #define SBLOCKS_SIZE_INITIAL 50 typedef UChar UByte; /* Layout of an in-use block: cost center (OPTIONAL) (VG_MIN_MALLOC_SZB bytes, only when h-p enabled) this block total szB (sizeof(SizeT) bytes) red zone bytes (depends on Arena.rz_szB, but >= sizeof(void*)) (payload bytes) red zone bytes (depends on Arena.rz_szB, but >= sizeof(void*)) this block total szB (sizeof(SizeT) bytes) Layout of a block on the free list: cost center (OPTIONAL) (VG_MIN_MALLOC_SZB bytes, only when h-p enabled) this block total szB (sizeof(SizeT) bytes) freelist previous ptr (sizeof(void*) bytes) excess red zone bytes (if Arena.rz_szB > sizeof(void*)) (payload bytes) excess red zone bytes (if Arena.rz_szB > sizeof(void*)) freelist next ptr (sizeof(void*) bytes) this block total szB (sizeof(SizeT) bytes) Total size in bytes (bszB) and payload size in bytes (pszB) are related by: bszB == pszB + 2*sizeof(SizeT) + 2*a->rz_szB when heap profiling is not enabled, and bszB == pszB + 2*sizeof(SizeT) + 2*a->rz_szB + VG_MIN_MALLOC_SZB when it is enabled. It follows that the minimum overhead per heap block for arenas used by the core is: 32-bit platforms: 2*4 + 2*4 == 16 bytes 64-bit platforms: 2*8 + 2*8 == 32 bytes when heap profiling is not enabled, and 32-bit platforms: 2*4 + 2*4 + 8 == 24 bytes 64-bit platforms: 2*8 + 2*8 + 16 == 48 bytes when it is enabled. In all cases, extra overhead may be incurred when rounding the payload size up to VG_MIN_MALLOC_SZB. Furthermore, both size fields in the block have their least-significant bit set if the block is not in use, and unset if it is in use. (The bottom 3 or so bits are always free for this because of alignment.) A block size of zero is not possible, because a block always has at least two SizeTs and two pointers of overhead. Nb: All Block payloads must be VG_MIN_MALLOC_SZB-aligned. This is achieved by ensuring that Superblocks are VG_MIN_MALLOC_SZB-aligned (see newSuperblock() for how), and that the lengths of the following things are a multiple of VG_MIN_MALLOC_SZB: - Superblock admin section lengths (due to elastic padding) - Block admin section (low and high) lengths (due to elastic redzones) - Block payload lengths (due to req_pszB rounding up) The heap-profile cost-center field is 8 bytes even on 32 bit platforms. This is so as to keep the payload field 8-aligned. On a 64-bit platform, this cc-field contains a pointer to a const HChar*, which is the cost center name. On 32-bit platforms, the pointer lives in the lower-addressed half of the field, regardless of the endianness of the host. */ typedef struct { // No fields are actually used in this struct, because a Block has // many variable sized fields and so can't be accessed // meaningfully with normal fields. So we use access functions all // the time. This struct gives us a type to use, though. Also, we // make sizeof(Block) 1 byte so that we can do arithmetic with the // Block* type in increments of 1! UByte dummy; } Block; // A superblock. 'padding' is never used, it just ensures that if the // entire Superblock is aligned to VG_MIN_MALLOC_SZB, then payload_bytes[] // will be too. It can add small amounts of padding unnecessarily -- eg. // 8-bytes on 32-bit machines with an 8-byte VG_MIN_MALLOC_SZB -- because // it's too hard to make a constant expression that works perfectly in all // cases. // 'unsplittable' is set to NULL if superblock can be splitted, otherwise // it is set to the address of the superblock. An unsplittable superblock // will contain only one allocated block. An unsplittable superblock will // be unmapped when its (only) allocated block is freed. // The free space at the end of an unsplittable superblock is not used to // make a free block. Note that this means that an unsplittable superblock can // have up to slightly less than 1 page of unused bytes at the end of the // superblock. // 'unsplittable' is used to avoid quadratic memory usage for linear // reallocation of big structures // (see http://bugs.kde.org/show_bug.cgi?id=250101). // ??? unsplittable replaces 'void *padding2'. Choosed this // ??? to avoid changing the alignment logic. Maybe something cleaner // ??? can be done. // A splittable block can be reclaimed when all its blocks are freed : // the reclaim of such a block is deferred till either another superblock // of the same arena can be reclaimed or till a new superblock is needed // in any arena. // payload_bytes[] is made a single big Block when the Superblock is // created, and then can be split and the splittings remerged, but Blocks // always cover its entire length -- there's never any unused bytes at the // end, for example. typedef struct _Superblock { SizeT n_payload_bytes; struct _Superblock* unsplittable; UByte padding[ VG_MIN_MALLOC_SZB - ((sizeof(struct _Superblock*) + sizeof(SizeT)) % VG_MIN_MALLOC_SZB) ]; UByte payload_bytes[0]; } Superblock; // An arena. 'freelist' is a circular, doubly-linked list. 'rz_szB' is // elastic, in that it can be bigger than asked-for to ensure alignment. typedef struct { Char* name; Bool clientmem; // Allocates in the client address space? SizeT rz_szB; // Red zone size in bytes SizeT min_sblock_szB; // Minimum superblock size in bytes SizeT min_unsplittable_sblock_szB; // Minimum unsplittable superblock size in bytes. To be marked as // unsplittable, a superblock must have a // size >= min_unsplittable_sblock_szB and cannot be splitted. // So, to avoid big overhead, superblocks used to provide aligned // blocks on big alignments are splittable. // Unsplittable superblocks will be reclaimed when their (only) // allocated block is freed. // Smaller size superblocks are splittable and can be reclaimed when all // their blocks are freed. Block* freelist[N_MALLOC_LISTS]; // A dynamically expanding, ordered array of (pointers to) // superblocks in the arena. If this array is expanded, which // is rare, the previous space it occupies is simply abandoned. // To avoid having to get yet another block from m_aspacemgr for // the first incarnation of this array, the first allocation of // it is within this struct. If it has to be expanded then the // new space is acquired from m_aspacemgr as you would expect. Superblock** sblocks; SizeT sblocks_size; SizeT sblocks_used; Superblock* sblocks_initial[SBLOCKS_SIZE_INITIAL]; Superblock* deferred_reclaimed_sb; // Stats only. ULong stats__nreclaim_unsplit; ULong stats__nreclaim_split; /* total # of reclaim executed for unsplittable/splittable superblocks */ SizeT stats__bytes_on_loan; SizeT stats__bytes_mmaped; SizeT stats__bytes_on_loan_max; ULong stats__tot_blocks; /* total # blocks alloc'd */ ULong stats__tot_bytes; /* total # bytes alloc'd */ ULong stats__nsearches; /* total # freelist checks */ // If profiling, when should the next profile happen at // (in terms of stats__bytes_on_loan_max) ? SizeT next_profile_at; SizeT stats__bytes_mmaped_max; } Arena; /*------------------------------------------------------------*/ /*--- Low-level functions for working with Blocks. ---*/ /*------------------------------------------------------------*/ #define SIZE_T_0x1 ((SizeT)0x1) static char* probably_your_fault = "This is probably caused by your program erroneously writing past the\n" "end of a heap block and corrupting heap metadata. If you fix any\n" "invalid writes reported by Memcheck, this assertion failure will\n" "probably go away. Please try that before reporting this as a bug.\n"; // Mark a bszB as in-use, and not in-use, and remove the in-use attribute. static __inline__ SizeT mk_inuse_bszB ( SizeT bszB ) { vg_assert2(bszB != 0, probably_your_fault); return bszB & (~SIZE_T_0x1); } static __inline__ SizeT mk_free_bszB ( SizeT bszB ) { vg_assert2(bszB != 0, probably_your_fault); return bszB | SIZE_T_0x1; } static __inline__ SizeT mk_plain_bszB ( SizeT bszB ) { vg_assert2(bszB != 0, probably_your_fault); return bszB & (~SIZE_T_0x1); } // return either 0 or sizeof(ULong) depending on whether or not // heap profiling is engaged #define hp_overhead_szB() set_at_init_hp_overhead_szB static SizeT set_at_init_hp_overhead_szB = -1000000; // startup value chosen to very likely cause a problem if used before // a proper value is given by ensure_mm_init. //--------------------------------------------------------------------------- // Get a block's size as stored, ie with the in-use/free attribute. static __inline__ SizeT get_bszB_as_is ( Block* b ) { UByte* b2 = (UByte*)b; SizeT bszB_lo = *(SizeT*)&b2[0 + hp_overhead_szB()]; SizeT bszB_hi = *(SizeT*)&b2[mk_plain_bszB(bszB_lo) - sizeof(SizeT)]; vg_assert2(bszB_lo == bszB_hi, "Heap block lo/hi size mismatch: lo = %llu, hi = %llu.\n%s", (ULong)bszB_lo, (ULong)bszB_hi, probably_your_fault); return bszB_lo; } // Get a block's plain size, ie. remove the in-use/free attribute. static __inline__ SizeT get_bszB ( Block* b ) { return mk_plain_bszB(get_bszB_as_is(b)); } // Set the size fields of a block. bszB may have the in-use/free attribute. static __inline__ void set_bszB ( Block* b, SizeT bszB ) { UByte* b2 = (UByte*)b; *(SizeT*)&b2[0 + hp_overhead_szB()] = bszB; *(SizeT*)&b2[mk_plain_bszB(bszB) - sizeof(SizeT)] = bszB; } //--------------------------------------------------------------------------- // Does this block have the in-use attribute? static __inline__ Bool is_inuse_block ( Block* b ) { SizeT bszB = get_bszB_as_is(b); vg_assert2(bszB != 0, probably_your_fault); return (0 != (bszB & SIZE_T_0x1)) ? False : True; } //--------------------------------------------------------------------------- // Return the lower, upper and total overhead in bytes for a block. // These are determined purely by which arena the block lives in. static __inline__ SizeT overhead_szB_lo ( Arena* a ) { return hp_overhead_szB() + sizeof(SizeT) + a->rz_szB; } static __inline__ SizeT overhead_szB_hi ( Arena* a ) { return a->rz_szB + sizeof(SizeT); } static __inline__ SizeT overhead_szB ( Arena* a ) { return overhead_szB_lo(a) + overhead_szB_hi(a); } //--------------------------------------------------------------------------- // Return the minimum bszB for a block in this arena. Can have zero-length // payloads, so it's the size of the admin bytes. static __inline__ SizeT min_useful_bszB ( Arena* a ) { return overhead_szB(a); } //--------------------------------------------------------------------------- // Convert payload size <--> block size (both in bytes). static __inline__ SizeT pszB_to_bszB ( Arena* a, SizeT pszB ) { return pszB + overhead_szB(a); } static __inline__ SizeT bszB_to_pszB ( Arena* a, SizeT bszB ) { vg_assert2(bszB >= overhead_szB(a), probably_your_fault); return bszB - overhead_szB(a); } //--------------------------------------------------------------------------- // Get a block's payload size. static __inline__ SizeT get_pszB ( Arena* a, Block* b ) { return bszB_to_pszB(a, get_bszB(b)); } //--------------------------------------------------------------------------- // Given the addr of a block, return the addr of its payload, and vice versa. static __inline__ UByte* get_block_payload ( Arena* a, Block* b ) { UByte* b2 = (UByte*)b; return & b2[ overhead_szB_lo(a) ]; } // Given the addr of a block's payload, return the addr of the block itself. static __inline__ Block* get_payload_block ( Arena* a, UByte* payload ) { return (Block*)&payload[ -overhead_szB_lo(a) ]; } //--------------------------------------------------------------------------- // Set and get the next and previous link fields of a block. static __inline__ void set_prev_b ( Block* b, Block* prev_p ) { UByte* b2 = (UByte*)b; *(Block**)&b2[hp_overhead_szB() + sizeof(SizeT)] = prev_p; } static __inline__ void set_next_b ( Block* b, Block* next_p ) { UByte* b2 = (UByte*)b; *(Block**)&b2[get_bszB(b) - sizeof(SizeT) - sizeof(void*)] = next_p; } static __inline__ Block* get_prev_b ( Block* b ) { UByte* b2 = (UByte*)b; return *(Block**)&b2[hp_overhead_szB() + sizeof(SizeT)]; } static __inline__ Block* get_next_b ( Block* b ) { UByte* b2 = (UByte*)b; return *(Block**)&b2[get_bszB(b) - sizeof(SizeT) - sizeof(void*)]; } //--------------------------------------------------------------------------- // Set and get the cost-center field of a block. static __inline__ void set_cc ( Block* b, HChar* cc ) { UByte* b2 = (UByte*)b; vg_assert( VG_(clo_profile_heap) ); *(HChar**)&b2[0] = cc; } static __inline__ HChar* get_cc ( Block* b ) { UByte* b2 = (UByte*)b; vg_assert( VG_(clo_profile_heap) ); return *(HChar**)&b2[0]; } //--------------------------------------------------------------------------- // Get the block immediately preceding this one in the Superblock. static __inline__ Block* get_predecessor_block ( Block* b ) { UByte* b2 = (UByte*)b; SizeT bszB = mk_plain_bszB( (*(SizeT*)&b2[-sizeof(SizeT)]) ); return (Block*)&b2[-bszB]; } //--------------------------------------------------------------------------- // Read and write the lower and upper red-zone bytes of a block. static __inline__ void set_rz_lo_byte ( Block* b, UInt rz_byteno, UByte v ) { UByte* b2 = (UByte*)b; b2[hp_overhead_szB() + sizeof(SizeT) + rz_byteno] = v; } static __inline__ void set_rz_hi_byte ( Block* b, UInt rz_byteno, UByte v ) { UByte* b2 = (UByte*)b; b2[get_bszB(b) - sizeof(SizeT) - rz_byteno - 1] = v; } static __inline__ UByte get_rz_lo_byte ( Block* b, UInt rz_byteno ) { UByte* b2 = (UByte*)b; return b2[hp_overhead_szB() + sizeof(SizeT) + rz_byteno]; } static __inline__ UByte get_rz_hi_byte ( Block* b, UInt rz_byteno ) { UByte* b2 = (UByte*)b; return b2[get_bszB(b) - sizeof(SizeT) - rz_byteno - 1]; } /*------------------------------------------------------------*/ /*--- Arena management ---*/ /*------------------------------------------------------------*/ #define CORE_ARENA_MIN_SZB 1048576 // The arena structures themselves. static Arena vg_arena[VG_N_ARENAS]; // Functions external to this module identify arenas using ArenaIds, // not Arena*s. This fn converts the former to the latter. static Arena* arenaId_to_ArenaP ( ArenaId arena ) { vg_assert(arena >= 0 && arena < VG_N_ARENAS); return & vg_arena[arena]; } // Initialise an arena. rz_szB is the minimum redzone size; it might be // made bigger to ensure that VG_MIN_MALLOC_SZB is observed. static void arena_init ( ArenaId aid, Char* name, SizeT rz_szB, SizeT min_sblock_szB, SizeT min_unsplittable_sblock_szB ) { SizeT i; Arena* a = arenaId_to_ArenaP(aid); // Ensure redzones are a reasonable size. They must always be at least // the size of a pointer, for holding the prev/next pointer (see the layout // details at the top of this file). vg_assert(rz_szB < 128); if (rz_szB < sizeof(void*)) rz_szB = sizeof(void*); vg_assert((min_sblock_szB % VKI_PAGE_SIZE) == 0); a->name = name; a->clientmem = ( VG_AR_CLIENT == aid ? True : False ); // The size of the low and high admin sections in a block must be a // multiple of VG_MIN_MALLOC_SZB. So we round up the asked-for // redzone size if necessary to achieve this. a->rz_szB = rz_szB; while (0 != overhead_szB_lo(a) % VG_MIN_MALLOC_SZB) a->rz_szB++; vg_assert(overhead_szB_lo(a) - hp_overhead_szB() == overhead_szB_hi(a)); a->min_sblock_szB = min_sblock_szB; a->min_unsplittable_sblock_szB = min_unsplittable_sblock_szB; for (i = 0; i < N_MALLOC_LISTS; i++) a->freelist[i] = NULL; a->sblocks = & a->sblocks_initial[0]; a->sblocks_size = SBLOCKS_SIZE_INITIAL; a->sblocks_used = 0; a->stats__nreclaim_unsplit = 0; a->stats__nreclaim_split = 0; a->stats__bytes_on_loan = 0; a->stats__bytes_mmaped = 0; a->stats__bytes_on_loan_max = 0; a->stats__bytes_mmaped_max = 0; a->stats__tot_blocks = 0; a->stats__tot_bytes = 0; a->stats__nsearches = 0; a->next_profile_at = 25 * 1000 * 1000; vg_assert(sizeof(a->sblocks_initial) == SBLOCKS_SIZE_INITIAL * sizeof(Superblock*)); } /* Print vital stats for an arena. */ void VG_(print_all_arena_stats) ( void ) { UInt i; for (i = 0; i < VG_N_ARENAS; i++) { Arena* a = arenaId_to_ArenaP(i); VG_(message)(Vg_DebugMsg, "%8s: %8ld/%8ld max/curr mmap'd, " "%llu/%llu unsplit/split sb unmmap'd, " "%8ld/%8ld max/curr, " "%10llu/%10llu totalloc-blocks/bytes," " %10llu searches\n", a->name, a->stats__bytes_mmaped_max, a->stats__bytes_mmaped, a->stats__nreclaim_unsplit, a->stats__nreclaim_split, a->stats__bytes_on_loan_max, a->stats__bytes_on_loan, a->stats__tot_blocks, a->stats__tot_bytes, a->stats__nsearches ); } } void VG_(print_arena_cc_analysis) ( void ) { UInt i; vg_assert( VG_(clo_profile_heap) ); for (i = 0; i < VG_N_ARENAS; i++) { cc_analyse_alloc_arena(i); } } /* This library is self-initialising, as it makes this more self-contained, less coupled with the outside world. Hence VG_(arena_malloc)() and VG_(arena_free)() below always call ensure_mm_init() to ensure things are correctly initialised. We initialise the client arena separately (and later) because the core must do non-client allocation before the tool has a chance to set the client arena's redzone size. */ static Bool client_inited = False; static Bool nonclient_inited = False; static void ensure_mm_init ( ArenaId aid ) { static SizeT client_rz_szB = 8; // default: be paranoid /* We use checked red zones (of various sizes) for our internal stuff, and an unchecked zone of arbitrary size for the client. Of course the client's red zone can be checked by the tool, eg. by using addressibility maps, but not by the mechanism implemented here, which merely checks at the time of freeing that the red zone bytes are unchanged. Nb: redzone sizes are *minimums*; they could be made bigger to ensure alignment. Eg. with 8 byte alignment, on 32-bit machines 4 stays as 4, but 16 becomes 20; but on 64-bit machines 4 becomes 8, and 16 stays as 16 --- the extra 4 bytes in both are accounted for by the larger prev/next ptr. */ if (VG_AR_CLIENT == aid) { Int ar_client_sbszB; if (client_inited) { // This assertion ensures that a tool cannot try to change the client // redzone size with VG_(needs_malloc_replacement)() after this module // has done its first allocation from the client arena. if (VG_(needs).malloc_replacement) vg_assert(client_rz_szB == VG_(tdict).tool_client_redzone_szB); return; } // Check and set the client arena redzone size if (VG_(needs).malloc_replacement) { client_rz_szB = VG_(tdict).tool_client_redzone_szB; // 128 is no special figure, just something not too big if (client_rz_szB > 128) { VG_(printf)( "\nTool error:\n" " specified redzone size is too big (%llu)\n", (ULong)client_rz_szB); VG_(exit)(1); } } // Initialise the client arena. On all platforms, // increasing the superblock size reduces the number of superblocks // in the client arena, which makes findSb cheaper. ar_client_sbszB = 4194304; // superblocks with a size > ar_client_sbszB will be unsplittable // (unless used for providing memalign-ed blocks). arena_init ( VG_AR_CLIENT, "client", client_rz_szB, ar_client_sbszB, ar_client_sbszB+1); client_inited = True; } else { if (nonclient_inited) { return; } set_at_init_hp_overhead_szB = VG_(clo_profile_heap) ? VG_MIN_MALLOC_SZB : 0; // Initialise the non-client arenas // Similarly to client arena, big allocations will be unsplittable. arena_init ( VG_AR_CORE, "core", 4, 1048576, 1048576+1 ); arena_init ( VG_AR_TOOL, "tool", 4, 4194304, 4194304+1 ); arena_init ( VG_AR_DINFO, "dinfo", 4, 1048576, 1048576+1 ); arena_init ( VG_AR_DEMANGLE, "demangle", 4, 65536, 65536+1 ); arena_init ( VG_AR_EXECTXT, "exectxt", 4, 1048576, 1048576+1 ); arena_init ( VG_AR_ERRORS, "errors", 4, 65536, 65536+1 ); arena_init ( VG_AR_TTAUX, "ttaux", 4, 65536, 65536+1 ); nonclient_inited = True; } # ifdef DEBUG_MALLOC VG_(printf)("ZZZ1\n"); VG_(sanity_check_malloc_all)(); VG_(printf)("ZZZ2\n"); # endif } /*------------------------------------------------------------*/ /*--- Superblock management ---*/ /*------------------------------------------------------------*/ __attribute__((noreturn)) void VG_(out_of_memory_NORETURN) ( HChar* who, SizeT szB ) { static Bool alreadyCrashing = False; ULong tot_alloc = VG_(am_get_anonsize_total)(); Char* s1 = "\n" " Valgrind's memory management: out of memory:\n" " %s's request for %llu bytes failed.\n" " %llu bytes have already been allocated.\n" " Valgrind cannot continue. Sorry.\n\n" " There are several possible reasons for this.\n" " - You have some kind of memory limit in place. Look at the\n" " output of 'ulimit -a'. Is there a limit on the size of\n" " virtual memory or address space?\n" " - You have run out of swap space.\n" " - Valgrind has a bug. If you think this is the case or you are\n" " not sure, please let us know and we'll try to fix it.\n" " Please note that programs can take substantially more memory than\n" " normal when running under Valgrind tools, eg. up to twice or\n" " more, depending on the tool. On a 64-bit machine, Valgrind\n" " should be able to make use of up 32GB memory. On a 32-bit\n" " machine, Valgrind should be able to use all the memory available\n" " to a single process, up to 4GB if that's how you have your\n" " kernel configured. Most 32-bit Linux setups allow a maximum of\n" " 3GB per process.\n\n" " Whatever the reason, Valgrind cannot continue. Sorry.\n"; if (!alreadyCrashing) { alreadyCrashing = True; VG_(message)(Vg_UserMsg, s1, who, (ULong)szB, tot_alloc); } else { VG_(debugLog)(0,"mallocfree", s1, who, (ULong)szB, tot_alloc); } VG_(exit)(1); } // Align ptr p upwards to an align-sized boundary. static void* align_upwards ( void* p, SizeT align ) { Addr a = (Addr)p; if ((a % align) == 0) return (void*)a; return (void*)(a - (a % align) + align); } // Forward definition. static void deferred_reclaimSuperblock ( Arena* a, Superblock* sb); // If not enough memory available, either aborts (for non-client memory) // or returns 0 (for client memory). static Superblock* newSuperblock ( Arena* a, SizeT cszB ) { Superblock* sb; SysRes sres; Bool unsplittable; ArenaId aid; // A new superblock is needed for arena a. We will execute the deferred // reclaim in all arenas in order to minimise fragmentation and // peak memory usage. for (aid = 0; aid < VG_N_ARENAS; aid++) { Arena* arena = arenaId_to_ArenaP(aid); if (arena->deferred_reclaimed_sb != NULL) deferred_reclaimSuperblock (arena, NULL); } // Take into account admin bytes in the Superblock. cszB += sizeof(Superblock); if (cszB < a->min_sblock_szB) cszB = a->min_sblock_szB; cszB = VG_PGROUNDUP(cszB); if (cszB >= a->min_unsplittable_sblock_szB) unsplittable = True; else unsplittable = False; if (a->clientmem) { // client allocation -- return 0 to client if it fails if (unsplittable) sres = VG_(am_mmap_anon_float_client) ( cszB, VKI_PROT_READ|VKI_PROT_WRITE|VKI_PROT_EXEC ); else sres = VG_(am_sbrk_anon_float_client) ( cszB, VKI_PROT_READ|VKI_PROT_WRITE|VKI_PROT_EXEC ); if (sr_isError(sres)) return 0; sb = (Superblock*)(AddrH)sr_Res(sres); // Mark this segment as containing client heap. The leak // checker needs to be able to identify such segments so as not // to use them as sources of roots during leak checks. VG_(am_set_segment_isCH_if_SkAnonC)( (NSegment*) VG_(am_find_nsegment)( (Addr)sb ) ); } else { // non-client allocation -- abort if it fails if (unsplittable) sres = VG_(am_mmap_anon_float_valgrind)( cszB ); else sres = VG_(am_sbrk_anon_float_valgrind)( cszB ); if (sr_isError(sres)) { VG_(out_of_memory_NORETURN)("newSuperblock", cszB); /* NOTREACHED */ sb = NULL; /* keep gcc happy */ } else { sb = (Superblock*)(AddrH)sr_Res(sres); } } vg_assert(NULL != sb); INNER_REQUEST(VALGRIND_MAKE_MEM_UNDEFINED(sb, cszB)); vg_assert(0 == (Addr)sb % VG_MIN_MALLOC_SZB); sb->n_payload_bytes = cszB - sizeof(Superblock); sb->unsplittable = (unsplittable ? sb : NULL); a->stats__bytes_mmaped += cszB; if (a->stats__bytes_mmaped > a->stats__bytes_mmaped_max) a->stats__bytes_mmaped_max = a->stats__bytes_mmaped; VG_(debugLog)(1, "mallocfree", "newSuperblock at %p (pszB %7ld) %s owner %s/%s\n", sb, sb->n_payload_bytes, (unsplittable ? "unsplittable" : ""), a->clientmem ? "CLIENT" : "VALGRIND", a->name ); return sb; } // Reclaims the given superblock: // * removes sb from arena sblocks list. // * munmap the superblock segment. static void reclaimSuperblock ( Arena* a, Superblock* sb) { SysRes sres; SizeT cszB; UInt i, j; VG_(debugLog)(1, "mallocfree", "reclaimSuperblock at %p (pszB %7ld) %s owner %s/%s\n", sb, sb->n_payload_bytes, (sb->unsplittable ? "unsplittable" : ""), a->clientmem ? "CLIENT" : "VALGRIND", a->name ); // Take into account admin bytes in the Superblock. cszB = sizeof(Superblock) + sb->n_payload_bytes; // removes sb from superblock list. for (i = 0; i < a->sblocks_used; i++) { if (a->sblocks[i] == sb) break; } vg_assert(i >= 0 && i < a->sblocks_used); for (j = i; j < a->sblocks_used; j++) a->sblocks[j] = a->sblocks[j+1]; a->sblocks_used--; a->sblocks[a->sblocks_used] = NULL; // paranoia: NULLify ptr to reclaimed sb or NULLify copy of ptr to last sb. a->stats__bytes_mmaped -= cszB; if (sb->unsplittable) a->stats__nreclaim_unsplit++; else a->stats__nreclaim_split++; // Now that the sb is removed from the list, mnumap its space. if (a->clientmem) { // reclaimable client allocation Bool need_discard = False; sres = VG_(am_munmap_client)(&need_discard, (Addr) sb, cszB); vg_assert2(! sr_isError(sres), "superblock client munmap failure\n"); /* We somewhat help the client by discarding the range. Note however that if the client has JITted some code in a small block that was freed, we do not provide this 'discard support' */ /* JRS 2011-Sept-26: it would be nice to move the discard outwards somewhat (in terms of calls) so as to make it easier to verify that there will be no nonterminating recursive set of calls a result of calling VG_(discard_translations). Another day, perhaps. */ if (need_discard) VG_(discard_translations) ((Addr) sb, cszB, "reclaimSuperblock"); } else { // reclaimable non-client allocation sres = VG_(am_munmap_valgrind)((Addr) sb, cszB); vg_assert2(! sr_isError(sres), "superblock valgrind munmap failure\n"); } } // Find the superblock containing the given chunk. static Superblock* findSb ( Arena* a, Block* b ) { SizeT min = 0; SizeT max = a->sblocks_used; while (min <= max) { Superblock * sb; SizeT pos = min + (max - min)/2; vg_assert(pos >= 0 && pos < a->sblocks_used); sb = a->sblocks[pos]; if ((Block*)&sb->payload_bytes[0] <= b && b < (Block*)&sb->payload_bytes[sb->n_payload_bytes]) { return sb; } else if ((Block*)&sb->payload_bytes[0] <= b) { min = pos + 1; } else { max = pos - 1; } } VG_(printf)("findSb: can't find pointer %p in arena '%s'\n", b, a->name ); VG_(core_panic)("findSb: VG_(arena_free)() in wrong arena?"); return NULL; /*NOTREACHED*/ } /*------------------------------------------------------------*/ /*--- Functions for working with freelists. ---*/ /*------------------------------------------------------------*/ // Nb: Determination of which freelist a block lives on is based on the // payload size, not block size. // Convert a payload size in bytes to a freelist number. static UInt pszB_to_listNo ( SizeT pszB ) { SizeT n = pszB / VG_MIN_MALLOC_SZB; vg_assert(0 == pszB % VG_MIN_MALLOC_SZB); // The first 64 lists hold blocks of size VG_MIN_MALLOC_SZB * list_num. // The final 48 hold bigger blocks. if (n < 64) return (UInt)n; /* Exponential slope up, factor 1.05 */ if (n < 67) return 64; if (n < 70) return 65; if (n < 74) return 66; if (n < 77) return 67; if (n < 81) return 68; if (n < 85) return 69; if (n < 90) return 70; if (n < 94) return 71; if (n < 99) return 72; if (n < 104) return 73; if (n < 109) return 74; if (n < 114) return 75; if (n < 120) return 76; if (n < 126) return 77; if (n < 133) return 78; if (n < 139) return 79; /* Exponential slope up, factor 1.10 */ if (n < 153) return 80; if (n < 169) return 81; if (n < 185) return 82; if (n < 204) return 83; if (n < 224) return 84; if (n < 247) return 85; if (n < 272) return 86; if (n < 299) return 87; if (n < 329) return 88; if (n < 362) return 89; if (n < 398) return 90; if (n < 438) return 91; if (n < 482) return 92; if (n < 530) return 93; if (n < 583) return 94; if (n < 641) return 95; /* Exponential slope up, factor 1.20 */ if (n < 770) return 96; if (n < 924) return 97; if (n < 1109) return 98; if (n < 1331) return 99; if (n < 1597) return 100; if (n < 1916) return 101; if (n < 2300) return 102; if (n < 2760) return 103; if (n < 3312) return 104; if (n < 3974) return 105; if (n < 4769) return 106; if (n < 5723) return 107; if (n < 6868) return 108; if (n < 8241) return 109; if (n < 9890) return 110; return 111; } // What is the minimum payload size for a given list? static SizeT listNo_to_pszB_min ( UInt listNo ) { /* Repeatedly computing this function at every request is expensive. Hence at the first call just cache the result for every possible argument. */ static SizeT cache[N_MALLOC_LISTS]; static Bool cache_valid = False; if (!cache_valid) { UInt i; for (i = 0; i < N_MALLOC_LISTS; i++) { SizeT pszB = 0; while (pszB_to_listNo(pszB) < i) pszB += VG_MIN_MALLOC_SZB; cache[i] = pszB; } cache_valid = True; } /* Returned cached answer. */ vg_assert(listNo <= N_MALLOC_LISTS); return cache[listNo]; } // What is the maximum payload size for a given list? static SizeT listNo_to_pszB_max ( UInt listNo ) { vg_assert(listNo <= N_MALLOC_LISTS); if (listNo == N_MALLOC_LISTS-1) { return MAX_PSZB; } else { return listNo_to_pszB_min(listNo+1) - 1; } } /* A nasty hack to try and reduce fragmentation. Try and replace a->freelist[lno] with another block on the same list but with a lower address, with the idea of attempting to recycle the same blocks rather than cruise through the address space. */ static void swizzle ( Arena* a, UInt lno ) { Block* p_best; Block* pp; Block* pn; UInt i; p_best = a->freelist[lno]; if (p_best == NULL) return; pn = pp = p_best; // This loop bound was 20 for a long time, but experiments showed that // reducing it to 10 gave the same result in all the tests, and 5 got the // same result in 85--100% of cases. And it's called often enough to be // noticeable in programs that allocated a lot. for (i = 0; i < 5; i++) { pn = get_next_b(pn); pp = get_prev_b(pp); if (pn < p_best) p_best = pn; if (pp < p_best) p_best = pp; } if (p_best < a->freelist[lno]) { # ifdef VERBOSE_MALLOC VG_(printf)("retreat by %ld\n", (Word)(a->freelist[lno] - p_best)); # endif a->freelist[lno] = p_best; } } /*------------------------------------------------------------*/ /*--- Sanity-check/debugging machinery. ---*/ /*------------------------------------------------------------*/ #define REDZONE_LO_MASK 0x31 #define REDZONE_HI_MASK 0x7c // Do some crude sanity checks on a Block. static Bool blockSane ( Arena* a, Block* b ) { # define BLEAT(str) VG_(printf)("blockSane: fail -- %s\n",str) UInt i; // The lo and hi size fields will be checked (indirectly) by the call // to get_rz_hi_byte(). if (!a->clientmem && is_inuse_block(b)) { // In the inner, for memcheck sake, temporarily mark redzone accessible. INNER_REQUEST(VALGRIND_MAKE_MEM_DEFINED (b + hp_overhead_szB() + sizeof(SizeT), a->rz_szB)); INNER_REQUEST(VALGRIND_MAKE_MEM_DEFINED (b + get_bszB(b) - sizeof(SizeT) - a->rz_szB, a->rz_szB)); for (i = 0; i < a->rz_szB; i++) { if (get_rz_lo_byte(b, i) != (UByte)(((Addr)b&0xff) ^ REDZONE_LO_MASK)) {BLEAT("redzone-lo");return False;} if (get_rz_hi_byte(b, i) != (UByte)(((Addr)b&0xff) ^ REDZONE_HI_MASK)) {BLEAT("redzone-hi");return False;} } INNER_REQUEST(VALGRIND_MAKE_MEM_NOACCESS (b + hp_overhead_szB() + sizeof(SizeT), a->rz_szB)); INNER_REQUEST(VALGRIND_MAKE_MEM_NOACCESS (b + get_bszB(b) - sizeof(SizeT) - a->rz_szB, a->rz_szB)); } return True; # undef BLEAT } // Print superblocks (only for debugging). static void ppSuperblocks ( Arena* a ) { UInt i, j, blockno = 1; SizeT b_bszB; for (j = 0; j < a->sblocks_used; ++j) { Superblock * sb = a->sblocks[j]; VG_(printf)( "\n" ); VG_(printf)( "superblock %d at %p %s, sb->n_pl_bs = %lu\n", blockno++, sb, (sb->unsplittable ? "unsplittable" : ""), sb->n_payload_bytes); for (i = 0; i < sb->n_payload_bytes; i += b_bszB) { Block* b = (Block*)&sb->payload_bytes[i]; b_bszB = get_bszB(b); VG_(printf)( " block at %d, bszB %lu: ", i, b_bszB ); VG_(printf)( "%s, ", is_inuse_block(b) ? "inuse" : "free"); VG_(printf)( "%s\n", blockSane(a, b) ? "ok" : "BAD" ); } vg_assert(i == sb->n_payload_bytes); // no overshoot at end of Sb } VG_(printf)( "end of superblocks\n\n" ); } // Sanity check both the superblocks and the chains. static void sanity_check_malloc_arena ( ArenaId aid ) { UInt i, j, superblockctr, blockctr_sb, blockctr_li; UInt blockctr_sb_free, listno; SizeT b_bszB, b_pszB, list_min_pszB, list_max_pszB; Bool thisFree, lastWasFree, sblockarrOK; Block* b; Block* b_prev; SizeT arena_bytes_on_loan; Arena* a; # define BOMB VG_(core_panic)("sanity_check_malloc_arena") a = arenaId_to_ArenaP(aid); // Check the superblock array. sblockarrOK = a->sblocks != NULL && a->sblocks_size >= SBLOCKS_SIZE_INITIAL && a->sblocks_used <= a->sblocks_size && (a->sblocks_size == SBLOCKS_SIZE_INITIAL ? (a->sblocks == &a->sblocks_initial[0]) : (a->sblocks != &a->sblocks_initial[0])); if (!sblockarrOK) { VG_(printf)("sanity_check_malloc_arena: sblock array BAD\n"); BOMB; } // First, traverse all the superblocks, inspecting the Blocks in each. superblockctr = blockctr_sb = blockctr_sb_free = 0; arena_bytes_on_loan = 0; for (j = 0; j < a->sblocks_used; ++j) { Superblock * sb = a->sblocks[j]; lastWasFree = False; superblockctr++; for (i = 0; i < sb->n_payload_bytes; i += mk_plain_bszB(b_bszB)) { blockctr_sb++; b = (Block*)&sb->payload_bytes[i]; b_bszB = get_bszB_as_is(b); if (!blockSane(a, b)) { VG_(printf)("sanity_check_malloc_arena: sb %p, block %d " "(bszB %lu): BAD\n", sb, i, b_bszB ); BOMB; } thisFree = !is_inuse_block(b); if (thisFree && lastWasFree) { VG_(printf)("sanity_check_malloc_arena: sb %p, block %d " "(bszB %lu): UNMERGED FREES\n", sb, i, b_bszB ); BOMB; } if (thisFree) blockctr_sb_free++; if (!thisFree) arena_bytes_on_loan += bszB_to_pszB(a, b_bszB); lastWasFree = thisFree; } if (i > sb->n_payload_bytes) { VG_(printf)( "sanity_check_malloc_arena: sb %p: last block " "overshoots end\n", sb); BOMB; } } if (arena_bytes_on_loan != a->stats__bytes_on_loan) { # ifdef VERBOSE_MALLOC VG_(printf)( "sanity_check_malloc_arena: a->bytes_on_loan %lu, " "arena_bytes_on_loan %lu: " "MISMATCH\n", a->bytes_on_loan, arena_bytes_on_loan); # endif ppSuperblocks(a); BOMB; } /* Second, traverse each list, checking that the back pointers make sense, counting blocks encountered, and checking that each block is an appropriate size for this list. */ blockctr_li = 0; for (listno = 0; listno < N_MALLOC_LISTS; listno++) { list_min_pszB = listNo_to_pszB_min(listno); list_max_pszB = listNo_to_pszB_max(listno); b = a->freelist[listno]; if (b == NULL) continue; while (True) { b_prev = b; b = get_next_b(b); if (get_prev_b(b) != b_prev) { VG_(printf)( "sanity_check_malloc_arena: list %d at %p: " "BAD LINKAGE\n", listno, b ); BOMB; } b_pszB = get_pszB(a, b); if (b_pszB < list_min_pszB || b_pszB > list_max_pszB) { VG_(printf)( "sanity_check_malloc_arena: list %d at %p: " "WRONG CHAIN SIZE %luB (%luB, %luB)\n", listno, b, b_pszB, list_min_pszB, list_max_pszB ); BOMB; } blockctr_li++; if (b == a->freelist[listno]) break; } } if (blockctr_sb_free != blockctr_li) { # ifdef VERBOSE_MALLOC VG_(printf)( "sanity_check_malloc_arena: BLOCK COUNT MISMATCH " "(via sbs %d, via lists %d)\n", blockctr_sb_free, blockctr_li ); # endif ppSuperblocks(a); BOMB; } if (VG_(clo_verbosity) > 2) VG_(message)(Vg_DebugMsg, "%8s: %2d sbs, %5d bs, %2d/%-2d free bs, " "%7ld mmap, %7ld loan\n", a->name, superblockctr, blockctr_sb, blockctr_sb_free, blockctr_li, a->stats__bytes_mmaped, a->stats__bytes_on_loan); # undef BOMB } #define N_AN_CCS 1000 typedef struct { ULong nBytes; ULong nBlocks; HChar* cc; } AnCC; static AnCC anCCs[N_AN_CCS]; static Int cmp_AnCC_by_vol ( void* v1, void* v2 ) { AnCC* ancc1 = (AnCC*)v1; AnCC* ancc2 = (AnCC*)v2; if (ancc1->nBytes < ancc2->nBytes) return -1; if (ancc1->nBytes > ancc2->nBytes) return 1; return 0; } static void cc_analyse_alloc_arena ( ArenaId aid ) { Word i, j, k; Arena* a; Block* b; Bool thisFree, lastWasFree; SizeT b_bszB; HChar* cc; UInt n_ccs = 0; //return; a = arenaId_to_ArenaP(aid); if (a->name == NULL) { /* arena is not in use, is not initialised and will fail the sanity check that follows. */ return; } sanity_check_malloc_arena(aid); VG_(printf)( "-------- Arena \"%s\": %lu/%lu max/curr mmap'd, " "%llu/%llu unsplit/split sb unmmap'd, " "%lu/%lu max/curr on_loan --------\n", a->name, a->stats__bytes_mmaped_max, a->stats__bytes_mmaped, a->stats__nreclaim_unsplit, a->stats__nreclaim_split, a->stats__bytes_on_loan_max, a->stats__bytes_on_loan ); for (j = 0; j < a->sblocks_used; ++j) { Superblock * sb = a->sblocks[j]; lastWasFree = False; for (i = 0; i < sb->n_payload_bytes; i += mk_plain_bszB(b_bszB)) { b = (Block*)&sb->payload_bytes[i]; b_bszB = get_bszB_as_is(b); if (!blockSane(a, b)) { VG_(printf)("sanity_check_malloc_arena: sb %p, block %ld " "(bszB %lu): BAD\n", sb, i, b_bszB ); tl_assert(0); } thisFree = !is_inuse_block(b); if (thisFree && lastWasFree) { VG_(printf)("sanity_check_malloc_arena: sb %p, block %ld " "(bszB %lu): UNMERGED FREES\n", sb, i, b_bszB ); tl_assert(0); } lastWasFree = thisFree; if (thisFree) continue; if (0) VG_(printf)("block: inUse=%d pszB=%d cc=%s\n", (Int)(!thisFree), (Int)bszB_to_pszB(a, b_bszB), get_cc(b)); cc = get_cc(b); tl_assert(cc); for (k = 0; k < n_ccs; k++) { tl_assert(anCCs[k].cc); if (0 == VG_(strcmp)(cc, anCCs[k].cc)) break; } tl_assert(k >= 0 && k <= n_ccs); if (k == n_ccs) { tl_assert(n_ccs < N_AN_CCS-1); n_ccs++; anCCs[k].nBytes = 0; anCCs[k].nBlocks = 0; anCCs[k].cc = cc; } tl_assert(k >= 0 && k < n_ccs && k < N_AN_CCS); anCCs[k].nBytes += (ULong)bszB_to_pszB(a, b_bszB); anCCs[k].nBlocks++; } if (i > sb->n_payload_bytes) { VG_(printf)( "sanity_check_malloc_arena: sb %p: last block " "overshoots end\n", sb); tl_assert(0); } } VG_(ssort)( &anCCs[0], n_ccs, sizeof(anCCs[0]), cmp_AnCC_by_vol ); for (k = 0; k < n_ccs; k++) { VG_(printf)("%'13llu in %'9llu: %s\n", anCCs[k].nBytes, anCCs[k].nBlocks, anCCs[k].cc ); } VG_(printf)("\n"); } void VG_(sanity_check_malloc_all) ( void ) { UInt i; for (i = 0; i < VG_N_ARENAS; i++) { if (i == VG_AR_CLIENT && !client_inited) continue; sanity_check_malloc_arena ( i ); } } /*------------------------------------------------------------*/ /*--- Creating and deleting blocks. ---*/ /*------------------------------------------------------------*/ // Mark the bytes at b .. b+bszB-1 as not in use, and add them to the // relevant free list. static void mkFreeBlock ( Arena* a, Block* b, SizeT bszB, UInt b_lno ) { SizeT pszB = bszB_to_pszB(a, bszB); vg_assert(b_lno == pszB_to_listNo(pszB)); INNER_REQUEST(VALGRIND_MAKE_MEM_UNDEFINED(b, bszB)); // Set the size fields and indicate not-in-use. set_bszB(b, mk_free_bszB(bszB)); // Add to the relevant list. if (a->freelist[b_lno] == NULL) { set_prev_b(b, b); set_next_b(b, b); a->freelist[b_lno] = b; } else { Block* b_prev = get_prev_b(a->freelist[b_lno]); Block* b_next = a->freelist[b_lno]; set_next_b(b_prev, b); set_prev_b(b_next, b); set_next_b(b, b_next); set_prev_b(b, b_prev); } # ifdef DEBUG_MALLOC (void)blockSane(a,b); # endif } // Mark the bytes at b .. b+bszB-1 as in use, and set up the block // appropriately. static void mkInuseBlock ( Arena* a, Block* b, SizeT bszB ) { UInt i; vg_assert(bszB >= min_useful_bszB(a)); INNER_REQUEST(VALGRIND_MAKE_MEM_UNDEFINED(b, bszB)); set_bszB(b, mk_inuse_bszB(bszB)); set_prev_b(b, NULL); // Take off freelist set_next_b(b, NULL); // ditto if (!a->clientmem) { for (i = 0; i < a->rz_szB; i++) { set_rz_lo_byte(b, i, (UByte)(((Addr)b&0xff) ^ REDZONE_LO_MASK)); set_rz_hi_byte(b, i, (UByte)(((Addr)b&0xff) ^ REDZONE_HI_MASK)); } } # ifdef DEBUG_MALLOC (void)blockSane(a,b); # endif } // Remove a block from a given list. Does no sanity checking. static void unlinkBlock ( Arena* a, Block* b, UInt listno ) { vg_assert(listno < N_MALLOC_LISTS); if (get_prev_b(b) == b) { // Only one element in the list; treat it specially. vg_assert(get_next_b(b) == b); a->freelist[listno] = NULL; } else { Block* b_prev = get_prev_b(b); Block* b_next = get_next_b(b); a->freelist[listno] = b_prev; set_next_b(b_prev, b_next); set_prev_b(b_next, b_prev); swizzle ( a, listno ); } set_prev_b(b, NULL); set_next_b(b, NULL); } /*------------------------------------------------------------*/ /*--- Core-visible functions. ---*/ /*------------------------------------------------------------*/ // Align the request size. static __inline__ SizeT align_req_pszB ( SizeT req_pszB ) { SizeT n = VG_MIN_MALLOC_SZB-1; return ((req_pszB + n) & (~n)); } void* VG_(arena_malloc) ( ArenaId aid, HChar* cc, SizeT req_pszB ) { SizeT req_bszB, frag_bszB, b_bszB; UInt lno, i; Superblock* new_sb = NULL; Block* b = NULL; Arena* a; void* v; UWord stats__nsearches = 0; ensure_mm_init(aid); a = arenaId_to_ArenaP(aid); vg_assert(req_pszB < MAX_PSZB); req_pszB = align_req_pszB(req_pszB); req_bszB = pszB_to_bszB(a, req_pszB); // You must provide a cost-center name against which to charge // this allocation; it isn't optional. vg_assert(cc); // Scan through all the big-enough freelists for a block. // // Nb: this scanning might be expensive in some cases. Eg. if you // allocate lots of small objects without freeing them, but no // medium-sized objects, it will repeatedly scanning through the whole // list, and each time not find any free blocks until the last element. // // If this becomes a noticeable problem... the loop answers the question // "where is the first nonempty list above me?" And most of the time, // you ask the same question and get the same answer. So it would be // good to somehow cache the results of previous searches. // One possibility is an array (with N_MALLOC_LISTS elements) of // shortcuts. shortcut[i] would give the index number of the nearest // larger list above list i which is non-empty. Then this loop isn't // necessary. However, we'd have to modify some section [ .. i-1] of the // shortcut array every time a list [i] changes from empty to nonempty or // back. This would require care to avoid pathological worst-case // behaviour. // for (lno = pszB_to_listNo(req_pszB); lno < N_MALLOC_LISTS; lno++) { UWord nsearches_this_level = 0; b = a->freelist[lno]; if (NULL == b) continue; // If this list is empty, try the next one. while (True) { stats__nsearches++; nsearches_this_level++; if (UNLIKELY(nsearches_this_level >= 100) && lno < N_MALLOC_LISTS-1) { /* Avoid excessive scanning on this freelist, and instead try the next one up. But first, move this freelist's start pointer one element along, so as to ensure that subsequent searches of this list don't endlessly revisit only these 100 elements, but in fact slowly progress through the entire list. */ b = a->freelist[lno]; vg_assert(b); // this list must be nonempty! a->freelist[lno] = get_next_b(b); // step one along break; } b_bszB = get_bszB(b); if (b_bszB >= req_bszB) goto obtained_block; // success! b = get_next_b(b); if (b == a->freelist[lno]) break; // traversed entire freelist } } // If we reach here, no suitable block found, allocate a new superblock vg_assert(lno == N_MALLOC_LISTS); new_sb = newSuperblock(a, req_bszB); if (NULL == new_sb) { // Should only fail if for client, otherwise, should have aborted // already. vg_assert(VG_AR_CLIENT == aid); return NULL; } vg_assert(a->sblocks_used <= a->sblocks_size); if (a->sblocks_used == a->sblocks_size) { Superblock ** array; SysRes sres = VG_(am_sbrk_anon_float_valgrind)(sizeof(Superblock *) * a->sblocks_size * 2); if (sr_isError(sres)) { VG_(out_of_memory_NORETURN)("arena_init", sizeof(Superblock *) * a->sblocks_size * 2); /* NOTREACHED */ } array = (Superblock**)(AddrH)sr_Res(sres); for (i = 0; i < a->sblocks_used; ++i) array[i] = a->sblocks[i]; a->sblocks_size *= 2; a->sblocks = array; VG_(debugLog)(1, "mallocfree", "sblock array for arena `%s' resized to %ld\n", a->name, a->sblocks_size); } vg_assert(a->sblocks_used < a->sblocks_size); i = a->sblocks_used; while (i > 0) { if (a->sblocks[i-1] > new_sb) { a->sblocks[i] = a->sblocks[i-1]; } else { break; } --i; } a->sblocks[i] = new_sb; a->sblocks_used++; b = (Block*)&new_sb->payload_bytes[0]; lno = pszB_to_listNo(bszB_to_pszB(a, new_sb->n_payload_bytes)); mkFreeBlock ( a, b, new_sb->n_payload_bytes, lno); if (VG_(clo_profile_heap)) set_cc(b, "admin.free-new-sb-1"); // fall through obtained_block: // Ok, we can allocate from b, which lives in list lno. vg_assert(b != NULL); vg_assert(lno < N_MALLOC_LISTS); vg_assert(a->freelist[lno] != NULL); b_bszB = get_bszB(b); // req_bszB is the size of the block we are after. b_bszB is the // size of what we've actually got. */ vg_assert(b_bszB >= req_bszB); // Could we split this block and still get a useful fragment? // A block in an unsplittable superblock can never be splitted. frag_bszB = b_bszB - req_bszB; if (frag_bszB >= min_useful_bszB(a) && (NULL == new_sb || ! new_sb->unsplittable)) { // Yes, split block in two, put the fragment on the appropriate free // list, and update b_bszB accordingly. // printf( "split %dB into %dB and %dB\n", b_bszB, req_bszB, frag_bszB ); unlinkBlock(a, b, lno); mkInuseBlock(a, b, req_bszB); if (VG_(clo_profile_heap)) set_cc(b, cc); mkFreeBlock(a, &b[req_bszB], frag_bszB, pszB_to_listNo(bszB_to_pszB(a, frag_bszB))); if (VG_(clo_profile_heap)) set_cc(&b[req_bszB], "admin.fragmentation-1"); b_bszB = get_bszB(b); } else { // No, mark as in use and use as-is. unlinkBlock(a, b, lno); mkInuseBlock(a, b, b_bszB); if (VG_(clo_profile_heap)) set_cc(b, cc); } // Update stats SizeT loaned = bszB_to_pszB(a, b_bszB); a->stats__bytes_on_loan += loaned; if (a->stats__bytes_on_loan > a->stats__bytes_on_loan_max) { a->stats__bytes_on_loan_max = a->stats__bytes_on_loan; if (a->stats__bytes_on_loan_max >= a->next_profile_at) { /* next profile after 10% more growth */ a->next_profile_at = (SizeT)( (((ULong)a->stats__bytes_on_loan_max) * 105ULL) / 100ULL ); if (VG_(clo_profile_heap)) cc_analyse_alloc_arena(aid); } } a->stats__tot_blocks += (ULong)1; a->stats__tot_bytes += (ULong)loaned; a->stats__nsearches += (ULong)stats__nsearches; # ifdef DEBUG_MALLOC sanity_check_malloc_arena(aid); # endif v = get_block_payload(a, b); vg_assert( (((Addr)v) & (VG_MIN_MALLOC_SZB-1)) == 0 ); // Which size should we pass to VALGRIND_MALLOCLIKE_BLOCK ? // We have 2 possible options: // 1. The final resulting usable size. // 2. The initial (non-aligned) req_pszB. // Memcheck implements option 2 easily, as the initial requested size // is maintained in the mc_chunk data structure. // This is not as easy in the core, as there is no such structure. // (note: using the aligned req_pszB is not simpler than 2, as // requesting an aligned req_pszB might still be satisfied by returning // a (slightly) bigger block than requested if the remaining part of // of a free block is not big enough to make a free block by itself). // Implement Sol 2 can be done the following way: // After having called VALGRIND_MALLOCLIKE_BLOCK, the non accessible // redzone just after the block can be used to determine the // initial requested size. // Currently, not implemented => we use Option 1. INNER_REQUEST (VALGRIND_MALLOCLIKE_BLOCK(v, VG_(arena_malloc_usable_size)(aid, v), a->rz_szB, False)); /* For debugging/testing purposes, fill the newly allocated area with a definite value in an attempt to shake out any uninitialised uses of the data (by V core / V tools, not by the client). Testing on 25 Nov 07 with the values 0x00, 0xFF, 0x55, 0xAA showed no differences in the regression tests on amd64-linux. Note, is disabled by default. */ if (0 && aid != VG_AR_CLIENT) VG_(memset)(v, 0xAA, (SizeT)req_pszB); return v; } // If arena has already a deferred reclaimed superblock and // this superblock is still reclaimable, then this superblock is first // reclaimed. // sb becomes then the new arena deferred superblock. // Passing NULL as sb allows to reclaim a deferred sb without setting a new // deferred reclaim. static void deferred_reclaimSuperblock ( Arena* a, Superblock* sb) { if (sb == NULL) { if (!a->deferred_reclaimed_sb) // no deferred sb to reclaim now, nothing to do in the future => // return directly. return; VG_(debugLog)(1, "mallocfree", "deferred_reclaimSuperblock NULL " "(prev %p) owner %s/%s\n", a->deferred_reclaimed_sb, a->clientmem ? "CLIENT" : "VALGRIND", a->name ); } else VG_(debugLog)(1, "mallocfree", "deferred_reclaimSuperblock at %p (pszB %7ld) %s " "(prev %p) owner %s/%s\n", sb, sb->n_payload_bytes, (sb->unsplittable ? "unsplittable" : ""), a->deferred_reclaimed_sb, a->clientmem ? "CLIENT" : "VALGRIND", a->name ); if (a->deferred_reclaimed_sb && a->deferred_reclaimed_sb != sb) { // If we are deferring another block that the current block deferred, // then if this block can stil be reclaimed, reclaim it now. // Note that we might have a re-deferred reclaim of the same block // with a sequence: free (causing a deferred reclaim of sb) // alloc (using a piece of memory of the deferred sb) // free of the just alloc-ed block (causing a re-defer). UByte* def_sb_start; UByte* def_sb_end; Superblock* def_sb; Block* b; def_sb = a->deferred_reclaimed_sb; def_sb_start = &def_sb->payload_bytes[0]; def_sb_end = &def_sb->payload_bytes[def_sb->n_payload_bytes - 1]; b = (Block *)def_sb_start; vg_assert (blockSane(a, b)); // Check if the deferred_reclaimed_sb is still reclaimable. // If yes, we will execute the reclaim. if (!is_inuse_block(b)) { // b (at the beginning of def_sb) is not in use. UInt b_listno; SizeT b_bszB, b_pszB; b_bszB = get_bszB(b); b_pszB = bszB_to_pszB(a, b_bszB); if (b + b_bszB-1 == (Block*)def_sb_end) { // b (not in use) covers the full superblock. // => def_sb is still reclaimable // => execute now the reclaim of this def_sb. b_listno = pszB_to_listNo(b_pszB); unlinkBlock( a, b, b_listno ); reclaimSuperblock (a, def_sb); a->deferred_reclaimed_sb = NULL; } } } // sb (possibly NULL) becomes the new deferred reclaimed superblock. a->deferred_reclaimed_sb = sb; } void VG_(arena_free) ( ArenaId aid, void* ptr ) { Superblock* sb; UByte* sb_start; UByte* sb_end; Block* other_b; Block* b; SizeT b_bszB, b_pszB, other_bszB; UInt b_listno; Arena* a; ensure_mm_init(aid); a = arenaId_to_ArenaP(aid); if (ptr == NULL) { return; } b = get_payload_block(a, ptr); /* If this is one of V's areas, check carefully the block we're getting back. This picks up simple block-end overruns. */ if (aid != VG_AR_CLIENT) vg_assert(blockSane(a, b)); b_bszB = get_bszB(b); b_pszB = bszB_to_pszB(a, b_bszB); sb = findSb( a, b ); sb_start = &sb->payload_bytes[0]; sb_end = &sb->payload_bytes[sb->n_payload_bytes - 1]; a->stats__bytes_on_loan -= b_pszB; /* If this is one of V's areas, fill it up with junk to enhance the chances of catching any later reads of it. Note, 0xDD is carefully chosen junk :-), in that: (1) 0xDDDDDDDD is an invalid and non-word-aligned address on most systems, and (2) 0xDD is a value which is unlikely to be generated by the new compressed Vbits representation for memcheck. */ if (aid != VG_AR_CLIENT) VG_(memset)(ptr, 0xDD, (SizeT)b_pszB); if (! sb->unsplittable) { // Put this chunk back on a list somewhere. b_listno = pszB_to_listNo(b_pszB); mkFreeBlock( a, b, b_bszB, b_listno ); if (VG_(clo_profile_heap)) set_cc(b, "admin.free-1"); // See if this block can be merged with its successor. // First test if we're far enough before the superblock's end to possibly // have a successor. other_b = b + b_bszB; if (other_b+min_useful_bszB(a)-1 <= (Block*)sb_end) { // Ok, we have a successor, merge if it's not in use. other_bszB = get_bszB(other_b); if (!is_inuse_block(other_b)) { // VG_(printf)( "merge-successor\n"); # ifdef DEBUG_MALLOC vg_assert(blockSane(a, other_b)); # endif unlinkBlock( a, b, b_listno ); unlinkBlock( a, other_b, pszB_to_listNo(bszB_to_pszB(a,other_bszB)) ); b_bszB += other_bszB; b_listno = pszB_to_listNo(bszB_to_pszB(a, b_bszB)); mkFreeBlock( a, b, b_bszB, b_listno ); if (VG_(clo_profile_heap)) set_cc(b, "admin.free-2"); } } else { // Not enough space for successor: check that b is the last block // ie. there are no unused bytes at the end of the Superblock. vg_assert(other_b-1 == (Block*)sb_end); } // Then see if this block can be merged with its predecessor. // First test if we're far enough after the superblock's start to possibly // have a predecessor. if (b >= (Block*)sb_start + min_useful_bszB(a)) { // Ok, we have a predecessor, merge if it's not in use. other_b = get_predecessor_block( b ); other_bszB = get_bszB(other_b); if (!is_inuse_block(other_b)) { // VG_(printf)( "merge-predecessor\n"); unlinkBlock( a, b, b_listno ); unlinkBlock( a, other_b, pszB_to_listNo(bszB_to_pszB(a, other_bszB)) ); b = other_b; b_bszB += other_bszB; b_listno = pszB_to_listNo(bszB_to_pszB(a, b_bszB)); mkFreeBlock( a, b, b_bszB, b_listno ); if (VG_(clo_profile_heap)) set_cc(b, "admin.free-3"); } } else { // Not enough space for predecessor: check that b is the first block, // ie. there are no unused bytes at the start of the Superblock. vg_assert((Block*)sb_start == b); } /* If the block b just merged is the only block of the superblock sb, then we defer reclaim sb. */ if ( ((Block*)sb_start == b) && (b + b_bszB-1 == (Block*)sb_end) ) { deferred_reclaimSuperblock (a, sb); } // Inform that ptr has been released. We give redzone size // 0 instead of a->rz_szB as proper accessibility is done just after. INNER_REQUEST(VALGRIND_FREELIKE_BLOCK(ptr, 0)); // We need to (re-)establish the minimum accessibility needed // for free list management. E.g. if block ptr has been put in a free // list and a neighbour block is released afterwards, the // "lo" and "hi" portions of the block ptr will be accessed to // glue the 2 blocks together. // We could mark the whole block as not accessible, and each time // transiently mark accessible the needed lo/hi parts. Not done as this // is quite complex, for very little expected additional bug detection. // fully unaccessible. Note that the below marks the (possibly) merged // block, not the block corresponding to the ptr argument. // First mark the whole block unaccessible. INNER_REQUEST(VALGRIND_MAKE_MEM_NOACCESS(b, b_bszB)); // Then mark the relevant administrative headers as defined. // No need to mark the heap profile portion as defined, this is not // used for free blocks. INNER_REQUEST(VALGRIND_MAKE_MEM_DEFINED(b + hp_overhead_szB(), sizeof(SizeT) + sizeof(void*))); INNER_REQUEST(VALGRIND_MAKE_MEM_DEFINED(b + b_bszB - sizeof(SizeT) - sizeof(void*), sizeof(SizeT) + sizeof(void*))); } else { // b must be first block (i.e. no unused bytes at the beginning) vg_assert((Block*)sb_start == b); // b must be last block (i.e. no unused bytes at the end) other_b = b + b_bszB; vg_assert(other_b-1 == (Block*)sb_end); // Inform that ptr has been released. Redzone size value // is not relevant (so we give 0 instead of a->rz_szB) // as it is expected that the aspacemgr munmap will be used by // outer to mark the whole superblock as unaccessible. INNER_REQUEST(VALGRIND_FREELIKE_BLOCK(ptr, 0)); // Reclaim immediately the unsplittable superblock sb. reclaimSuperblock (a, sb); } # ifdef DEBUG_MALLOC sanity_check_malloc_arena(aid); # endif } /* The idea for malloc_aligned() is to allocate a big block, base, and then split it into two parts: frag, which is returned to the the free pool, and align, which is the bit we're really after. Here's a picture. L and H denote the block lower and upper overheads, in bytes. The details are gruesome. Note it is slightly complicated because the initial request to generate base may return a bigger block than we asked for, so it is important to distinguish the base request size and the base actual size. frag_b align_b | | | frag_p | align_p | | | | v v v v +---+ +---+---+ +---+ | L |----------------| H | L |---------------| H | +---+ +---+---+ +---+ ^ ^ ^ | | : | base_p this addr must be aligned | base_b . . . . . . . <------ frag_bszB -------> . . . . <------------- base_pszB_act -----------> . . . . . . . . */ void* VG_(arena_memalign) ( ArenaId aid, HChar* cc, SizeT req_alignB, SizeT req_pszB ) { SizeT base_pszB_req, base_pszB_act, frag_bszB; Block *base_b, *align_b; UByte *base_p, *align_p; SizeT saved_bytes_on_loan; Arena* a; ensure_mm_init(aid); a = arenaId_to_ArenaP(aid); vg_assert(req_pszB < MAX_PSZB); // You must provide a cost-center name against which to charge // this allocation; it isn't optional. vg_assert(cc); // Check that the requested alignment seems reasonable; that is, is // a power of 2. if (req_alignB < VG_MIN_MALLOC_SZB || req_alignB > 1048576 || VG_(log2)( req_alignB ) == -1 /* not a power of 2 */) { VG_(printf)("VG_(arena_memalign)(%p, %lu, %lu)\n" "bad alignment value %lu\n" "(it is too small, too big, or not a power of two)", a, req_alignB, req_pszB, req_alignB ); VG_(core_panic)("VG_(arena_memalign)"); /*NOTREACHED*/ } // Paranoid vg_assert(req_alignB % VG_MIN_MALLOC_SZB == 0); /* Required payload size for the aligned chunk. */ req_pszB = align_req_pszB(req_pszB); /* Payload size to request for the big block that we will split up. */ base_pszB_req = req_pszB + min_useful_bszB(a) + req_alignB; /* Payload ptr for the block we are going to split. Note this changes a->bytes_on_loan; we save and restore it ourselves. */ saved_bytes_on_loan = a->stats__bytes_on_loan; { /* As we will split the block given back by VG_(arena_malloc), we have to (temporarily) disable unsplittable for this arena, as unsplittable superblocks cannot be splitted. */ const SizeT save_min_unsplittable_sblock_szB = a->min_unsplittable_sblock_szB; a->min_unsplittable_sblock_szB = MAX_PSZB; base_p = VG_(arena_malloc) ( aid, cc, base_pszB_req ); a->min_unsplittable_sblock_szB = save_min_unsplittable_sblock_szB; } a->stats__bytes_on_loan = saved_bytes_on_loan; /* Give up if we couldn't allocate enough space */ if (base_p == 0) return 0; /* base_p was marked as allocated by VALGRIND_MALLOCLIKE_BLOCK inside VG_(arena_malloc). We need to indicate it is free, then we need to mark it undefined to allow the below code to access is. */ INNER_REQUEST(VALGRIND_FREELIKE_BLOCK(base_p, a->rz_szB)); INNER_REQUEST(VALGRIND_MAKE_MEM_UNDEFINED(base_p, base_pszB_req)); /* Block ptr for the block we are going to split. */ base_b = get_payload_block ( a, base_p ); /* Pointer to the payload of the aligned block we are going to return. This has to be suitably aligned. */ align_p = align_upwards ( base_b + 2 * overhead_szB_lo(a) + overhead_szB_hi(a), req_alignB ); align_b = get_payload_block(a, align_p); /* The block size of the fragment we will create. This must be big enough to actually create a fragment. */ frag_bszB = align_b - base_b; vg_assert(frag_bszB >= min_useful_bszB(a)); /* The actual payload size of the block we are going to split. */ base_pszB_act = get_pszB(a, base_b); /* Create the fragment block, and put it back on the relevant free list. */ mkFreeBlock ( a, base_b, frag_bszB, pszB_to_listNo(bszB_to_pszB(a, frag_bszB)) ); if (VG_(clo_profile_heap)) set_cc(base_b, "admin.frag-memalign-1"); /* Create the aligned block. */ mkInuseBlock ( a, align_b, base_p + base_pszB_act + overhead_szB_hi(a) - (UByte*)align_b ); if (VG_(clo_profile_heap)) set_cc(align_b, cc); /* Final sanity checks. */ vg_assert( is_inuse_block(get_payload_block(a, align_p)) ); vg_assert(req_pszB <= get_pszB(a, get_payload_block(a, align_p))); a->stats__bytes_on_loan += get_pszB(a, get_payload_block(a, align_p)); if (a->stats__bytes_on_loan > a->stats__bytes_on_loan_max) { a->stats__bytes_on_loan_max = a->stats__bytes_on_loan; } /* a->stats__tot_blocks, a->stats__tot_bytes, a->stats__nsearches are updated by the call to VG_(arena_malloc) just a few lines above. So we don't need to update them here. */ # ifdef DEBUG_MALLOC sanity_check_malloc_arena(aid); # endif vg_assert( (((Addr)align_p) % req_alignB) == 0 ); INNER_REQUEST(VALGRIND_MALLOCLIKE_BLOCK(align_p, req_pszB, a->rz_szB, False)); return align_p; } SizeT VG_(arena_malloc_usable_size) ( ArenaId aid, void* ptr ) { Arena* a = arenaId_to_ArenaP(aid); Block* b = get_payload_block(a, ptr); return get_pszB(a, b); } // Implementation of mallinfo(). There is no recent standard that defines // the behavior of mallinfo(). The meaning of the fields in struct mallinfo // is as follows: // // struct mallinfo { // int arena; /* total space in arena */ // int ordblks; /* number of ordinary blocks */ // int smblks; /* number of small blocks */ // int hblks; /* number of holding blocks */ // int hblkhd; /* space in holding block headers */ // int usmblks; /* space in small blocks in use */ // int fsmblks; /* space in free small blocks */ // int uordblks; /* space in ordinary blocks in use */ // int fordblks; /* space in free ordinary blocks */ // int keepcost; /* space penalty if keep option */ // /* is used */ // }; // // The glibc documentation about mallinfo (which is somewhat outdated) can // be found here: // http://www.gnu.org/software/libtool/manual/libc/Statistics-of-Malloc.html // // See also http://bugs.kde.org/show_bug.cgi?id=160956. // // Regarding the implementation of VG_(mallinfo)(): we cannot return the // whole struct as the library function does, because this is called by a // client request. So instead we use a pointer to do call by reference. void VG_(mallinfo) ( ThreadId tid, struct vg_mallinfo* mi ) { UWord i, free_blocks, free_blocks_size; Arena* a = arenaId_to_ArenaP(VG_AR_CLIENT); // Traverse free list and calculate free blocks statistics. // This may seem slow but glibc works the same way. free_blocks_size = free_blocks = 0; for (i = 0; i < N_MALLOC_LISTS; i++) { Block* b = a->freelist[i]; if (b == NULL) continue; for (;;) { free_blocks++; free_blocks_size += (UWord)get_pszB(a, b); b = get_next_b(b); if (b == a->freelist[i]) break; } } // We don't have fastbins so smblks & fsmblks are always 0. Also we don't // have a separate mmap allocator so set hblks & hblkhd to 0. mi->arena = a->stats__bytes_mmaped; mi->ordblks = free_blocks + VG_(free_queue_length); mi->smblks = 0; mi->hblks = 0; mi->hblkhd = 0; mi->usmblks = 0; mi->fsmblks = 0; mi->uordblks = a->stats__bytes_on_loan - VG_(free_queue_volume); mi->fordblks = free_blocks_size + VG_(free_queue_volume); mi->keepcost = 0; // may want some value in here } /*------------------------------------------------------------*/ /*--- Services layered on top of malloc/free. ---*/ /*------------------------------------------------------------*/ void* VG_(arena_calloc) ( ArenaId aid, HChar* cc, SizeT nmemb, SizeT bytes_per_memb ) { SizeT size; UChar* p; size = nmemb * bytes_per_memb; vg_assert(size >= nmemb && size >= bytes_per_memb);// check against overflow p = VG_(arena_malloc) ( aid, cc, size ); VG_(memset)(p, 0, size); return p; } void* VG_(arena_realloc) ( ArenaId aid, HChar* cc, void* ptr, SizeT req_pszB ) { Arena* a; SizeT old_pszB; UChar *p_new; Block* b; ensure_mm_init(aid); a = arenaId_to_ArenaP(aid); vg_assert(req_pszB < MAX_PSZB); if (NULL == ptr) { return VG_(arena_malloc)(aid, cc, req_pszB); } if (req_pszB == 0) { VG_(arena_free)(aid, ptr); return NULL; } b = get_payload_block(a, ptr); vg_assert(blockSane(a, b)); vg_assert(is_inuse_block(b)); old_pszB = get_pszB(a, b); if (req_pszB <= old_pszB) { return ptr; } p_new = VG_(arena_malloc) ( aid, cc, req_pszB ); VG_(memcpy)(p_new, ptr, old_pszB); VG_(arena_free)(aid, ptr); return p_new; } /* Inline just for the wrapper VG_(strdup) below */ __inline__ Char* VG_(arena_strdup) ( ArenaId aid, HChar* cc, const Char* s ) { Int i; Int len; Char* res; if (s == NULL) return NULL; len = VG_(strlen)(s) + 1; res = VG_(arena_malloc) (aid, cc, len); for (i = 0; i < len; i++) res[i] = s[i]; return res; } /*------------------------------------------------------------*/ /*--- Tool-visible functions. ---*/ /*------------------------------------------------------------*/ // All just wrappers to avoid exposing arenas to tools. void* VG_(malloc) ( HChar* cc, SizeT nbytes ) { return VG_(arena_malloc) ( VG_AR_TOOL, cc, nbytes ); } void VG_(free) ( void* ptr ) { VG_(arena_free) ( VG_AR_TOOL, ptr ); } void* VG_(calloc) ( HChar* cc, SizeT nmemb, SizeT bytes_per_memb ) { return VG_(arena_calloc) ( VG_AR_TOOL, cc, nmemb, bytes_per_memb ); } void* VG_(realloc) ( HChar* cc, void* ptr, SizeT size ) { return VG_(arena_realloc) ( VG_AR_TOOL, cc, ptr, size ); } Char* VG_(strdup) ( HChar* cc, const Char* s ) { return VG_(arena_strdup) ( VG_AR_TOOL, cc, s ); } // Useful for querying user blocks. SizeT VG_(malloc_usable_size) ( void* p ) { return VG_(arena_malloc_usable_size)(VG_AR_CLIENT, p); } /*--------------------------------------------------------------------*/ /*--- end ---*/ /*--------------------------------------------------------------------*/ /*--------------------------------------------------------------------*/ /*--- An implementation of malloc/free which doesn't use sbrk. ---*/ /*--- m_mallocfree.c ---*/ /*--------------------------------------------------------------------*/ /* This file is part of Valgrind, a dynamic binary instrumentation framework. Copyright (C) 2000-2011 Julian Seward [email protected] This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. The GNU General Public License is contained in the file COPYING. */ #include "pub_core_basics.h" #include "pub_core_vki.h" #include "pub_core_debuglog.h" #include "pub_core_libcbase.h" #include "pub_core_aspacemgr.h" #include "pub_core_libcassert.h" #include "pub_core_libcprint.h" #include "pub_core_mallocfree.h" #include "pub_core_options.h" #include "pub_core_libcsetjmp.h" // to keep _threadstate.h happy #include "pub_core_threadstate.h" // For VG_INVALID_THREADID #include "pub_core_transtab.h" #include "pub_core_tooliface.h" #include "pub_tool_inner.h" #if defined(ENABLE_INNER_CLIENT_REQUEST) #include "memcheck/memcheck.h" #endif // #define DEBUG_MALLOC // turn on heavyweight debugging machinery // #define VERBOSE_MALLOC // make verbose, esp. in debugging machinery /* Number and total size of blocks in free queue. Used by mallinfo(). */ Long VG_(free_queue_volume) = 0; Long VG_(free_queue_length) = 0; static void cc_analyse_alloc_arena ( ArenaId aid ); /* fwds */ /*------------------------------------------------------------*/ /*--- Main types ---*/ /*------------------------------------------------------------*/ #define N_MALLOC_LISTS 112 // do not change this // The amount you can ask for is limited only by sizeof(SizeT)... #define MAX_PSZB (~((SizeT)0x0)) // Each arena has a sorted array of superblocks, which expands // dynamically. This is its initial size. #define SBLOCKS_SIZE_INITIAL 50 typedef UChar UByte; /* Layout of an in-use block: cost center (OPTIONAL) (VG_MIN_MALLOC_SZB bytes, only when h-p enabled) this block total szB (sizeof(SizeT) bytes) red zone bytes (depends on Arena.rz_szB, but >= sizeof(void*)) (payload bytes) red zone bytes (depends on Arena.rz_szB, but >= sizeof(void*)) this block total szB (sizeof(SizeT) bytes) Layout of a block on the free list: cost center (OPTIONAL) (VG_MIN_MALLOC_SZB bytes, only when h-p enabled) this block total szB (sizeof(SizeT) bytes) freelist previous ptr (sizeof(void*) bytes) excess red zone bytes (if Arena.rz_szB > sizeof(void*)) (payload bytes) excess red zone bytes (if Arena.rz_szB > sizeof(void*)) freelist next ptr (sizeof(void*) bytes) this block total szB (sizeof(SizeT) bytes) Total size in bytes (bszB) and payload size in bytes (pszB) are related by: bszB == pszB + 2*sizeof(SizeT) + 2*a->rz_szB when heap profiling is not enabled, and bszB == pszB + 2*sizeof(SizeT) + 2*a->rz_szB + VG_MIN_MALLOC_SZB when it is enabled. It follows that the minimum overhead per heap block for arenas used by the core is: 32-bit platforms: 2*4 + 2*4 == 16 bytes 64-bit platforms: 2*8 + 2*8 == 32 bytes when heap profiling is not enabled, and 32-bit platforms: 2*4 + 2*4 + 8 == 24 bytes 64-bit platforms: 2*8 + 2*8 + 16 == 48 bytes when it is enabled. In all cases, extra overhead may be incurred when rounding the payload size up to VG_MIN_MALLOC_SZB. Furthermore, both size fields in the block have their least-significant bit set if the block is not in use, and unset if it is in use. (The bottom 3 or so bits are always free for this because of alignment.) A block size of zero is not possible, because a block always has at least two SizeTs and two pointers of overhead. Nb: All Block payloads must be VG_MIN_MALLOC_SZB-aligned. This is achieved by ensuring that Superblocks are VG_MIN_MALLOC_SZB-aligned (see newSuperblock() for how), and that the lengths of the following things are a multiple of VG_MIN_MALLOC_SZB: - Superblock admin section lengths (due to elastic padding) - Block admin section (low and high) lengths (due to elastic redzones) - Block payload lengths (due to req_pszB rounding up) The heap-profile cost-center field is 8 bytes even on 32 bit platforms. This is so as to keep the payload field 8-aligned. On a 64-bit platform, this cc-field contains a pointer to a const HChar*, which is the cost center name. On 32-bit platforms, the pointer lives in the lower-addressed half of the field, regardless of the endianness of the host. */ typedef struct { // No fields are actually used in this struct, because a Block has // many variable sized fields and so can't be accessed // meaningfully with normal fields. So we use access functions all // the time. This struct gives us a type to use, though. Also, we // make sizeof(Block) 1 byte so that we can do arithmetic with the // Block* type in increments of 1! UByte dummy; } Block; // A superblock. 'padding' is never used, it just ensures that if the // entire Superblock is aligned to VG_MIN_MALLOC_SZB, then payload_bytes[] // will be too. It can add small amounts of padding unnecessarily -- eg. // 8-bytes on 32-bit machines with an 8-byte VG_MIN_MALLOC_SZB -- because // it's too hard to make a constant expression that works perfectly in all // cases. // 'unsplittable' is set to NULL if superblock can be splitted, otherwise // it is set to the address of the superblock. An unsplittable superblock // will contain only one allocated block. An unsplittable superblock will // be unmapped when its (only) allocated block is freed. // The free space at the end of an unsplittable superblock is not used to // make a free block. Note that this means that an unsplittable superblock can // have up to slightly less than 1 page of unused bytes at the end of the // superblock. // 'unsplittable' is used to avoid quadratic memory usage for linear // reallocation of big structures // (see http://bugs.kde.org/show_bug.cgi?id=250101). // ??? unsplittable replaces 'void *padding2'. Choosed this // ??? to avoid changing the alignment logic. Maybe something cleaner // ??? can be done. // A splittable block can be reclaimed when all its blocks are freed : // the reclaim of such a block is deferred till either another superblock // of the same arena can be reclaimed or till a new superblock is needed // in any arena. // payload_bytes[] is made a single big Block when the Superblock is // created, and then can be split and the splittings remerged, but Blocks // always cover its entire length -- there's never any unused bytes at the // end, for example. typedef struct _Superblock { SizeT n_payload_bytes; struct _Superblock* unsplittable; UByte padding[ VG_MIN_MALLOC_SZB - ((sizeof(struct _Superblock*) + sizeof(SizeT)) % VG_MIN_MALLOC_SZB) ]; UByte payload_bytes[0]; } Superblock; // An arena. 'freelist' is a circular, doubly-linked list. 'rz_szB' is // elastic, in that it can be bigger than asked-for to ensure alignment. typedef struct { Char* name; Bool clientmem; // Allocates in the client address space? SizeT rz_szB; // Red zone size in bytes SizeT min_sblock_szB; // Minimum superblock size in bytes SizeT min_unsplittable_sblock_szB; // Minimum unsplittable superblock size in bytes. To be marked as // unsplittable, a superblock must have a // size >= min_unsplittable_sblock_szB and cannot be splitted. // So, to avoid big overhead, superblocks used to provide aligned // blocks on big alignments are splittable. // Unsplittable superblocks will be reclaimed when their (only) // allocated block is freed. // Smaller size superblocks are splittable and can be reclaimed when all // their blocks are freed. Block* freelist[N_MALLOC_LISTS]; // A dynamically expanding, ordered array of (pointers to) // superblocks in the arena. If this array is expanded, which // is rare, the previous space it occupies is simply abandoned. // To avoid having to get yet another block from m_aspacemgr for // the first incarnation of this array, the first allocation of // it is within this struct. If it has to be expanded then the // new space is acquired from m_aspacemgr as you would expect. Superblock** sblocks; SizeT sblocks_size; SizeT sblocks_used; Superblock* sblocks_initial[SBLOCKS_SIZE_INITIAL]; Superblock* deferred_reclaimed_sb; // Stats only. ULong stats__nreclaim_unsplit; ULong stats__nreclaim_split; /* total # of reclaim executed for unsplittable/splittable superblocks */ SizeT stats__bytes_on_loan; SizeT stats__bytes_mmaped; SizeT stats__bytes_on_loan_max; ULong stats__tot_blocks; /* total # blocks alloc'd */ ULong stats__tot_bytes; /* total # bytes alloc'd */ ULong stats__nsearches; /* total # freelist checks */ // If profiling, when should the next profile happen at // (in terms of stats__bytes_on_loan_max) ? SizeT next_profile_at; SizeT stats__bytes_mmaped_max; } Arena; /*------------------------------------------------------------*/ /*--- Low-level functions for working with Blocks. ---*/ /*------------------------------------------------------------*/ #define SIZE_T_0x1 ((SizeT)0x1) static char* probably_your_fault = "This is probably caused by your program erroneously writing past the\n" "end of a heap block and corrupting heap metadata. If you fix any\n" "invalid writes reported by Memcheck, this assertion failure will\n" "probably go away. Please try that before reporting this as a bug.\n"; // Mark a bszB as in-use, and not in-use, and remove the in-use attribute. static __inline__ SizeT mk_inuse_bszB ( SizeT bszB ) { vg_assert2(bszB != 0, probably_your_fault); return bszB & (~SIZE_T_0x1); } static __inline__ SizeT mk_free_bszB ( SizeT bszB ) { vg_assert2(bszB != 0, probably_your_fault); return bszB | SIZE_T_0x1; } static __inline__ SizeT mk_plain_bszB ( SizeT bszB ) { vg_assert2(bszB != 0, probably_your_fault); return bszB & (~SIZE_T_0x1); } // return either 0 or sizeof(ULong) depending on whether or not // heap profiling is engaged #define hp_overhead_szB() set_at_init_hp_overhead_szB static SizeT set_at_init_hp_overhead_szB = -1000000; // startup value chosen to very likely cause a problem if used before // a proper value is given by ensure_mm_init. //--------------------------------------------------------------------------- // Get a block's size as stored, ie with the in-use/free attribute. static __inline__ SizeT get_bszB_as_is ( Block* b ) { UByte* b2 = (UByte*)b; SizeT bszB_lo = *(SizeT*)&b2[0 + hp_overhead_szB()]; SizeT bszB_hi = *(SizeT*)&b2[mk_plain_bszB(bszB_lo) - sizeof(SizeT)]; vg_assert2(bszB_lo == bszB_hi, "Heap block lo/hi size mismatch: lo = %llu, hi = %llu.\n%s", (ULong)bszB_lo, (ULong)bszB_hi, probably_your_fault); return bszB_lo; } // Get a block's plain size, ie. remove the in-use/free attribute. static __inline__ SizeT get_bszB ( Block* b ) { return mk_plain_bszB(get_bszB_as_is(b)); } // Set the size fields of a block. bszB may have the in-use/free attribute. static __inline__ void set_bszB ( Block* b, SizeT bszB ) { UByte* b2 = (UByte*)b; *(SizeT*)&b2[0 + hp_overhead_szB()] = bszB; *(SizeT*)&b2[mk_plain_bszB(bszB) - sizeof(SizeT)] = bszB; } //--------------------------------------------------------------------------- // Does this block have the in-use attribute? static __inline__ Bool is_inuse_block ( Block* b ) { SizeT bszB = get_bszB_as_is(b); vg_assert2(bszB != 0, probably_your_fault); return (0 != (bszB & SIZE_T_0x1)) ? False : True; } //--------------------------------------------------------------------------- // Return the lower, upper and total overhead in bytes for a block. // These are determined purely by which arena the block lives in. static __inline__ SizeT overhead_szB_lo ( Arena* a ) { return hp_overhead_szB() + sizeof(SizeT) + a->rz_szB; } static __inline__ SizeT overhead_szB_hi ( Arena* a ) { return a->rz_szB + sizeof(SizeT); } static __inline__ SizeT overhead_szB ( Arena* a ) { return overhead_szB_lo(a) + overhead_szB_hi(a); } //--------------------------------------------------------------------------- // Return the minimum bszB for a block in this arena. Can have zero-length // payloads, so it's the size of the admin bytes. static __inline__ SizeT min_useful_bszB ( Arena* a ) { return overhead_szB(a); } //--------------------------------------------------------------------------- // Convert payload size <--> block size (both in bytes). static __inline__ SizeT pszB_to_bszB ( Arena* a, SizeT pszB ) { return pszB + overhead_szB(a); } static __inline__ SizeT bszB_to_pszB ( Arena* a, SizeT bszB ) { vg_assert2(bszB >= overhead_szB(a), probably_your_fault); return bszB - overhead_szB(a); } //--------------------------------------------------------------------------- // Get a block's payload size. static __inline__ SizeT get_pszB ( Arena* a, Block* b ) { return bszB_to_pszB(a, get_bszB(b)); } //--------------------------------------------------------------------------- // Given the addr of a block, return the addr of its payload, and vice versa. static __inline__ UByte* get_block_payload ( Arena* a, Block* b ) { UByte* b2 = (UByte*)b; return & b2[ overhead_szB_lo(a) ]; } // Given the addr of a block's payload, return the addr of the block itself. static __inline__ Block* get_payload_block ( Arena* a, UByte* payload ) { return (Block*)&payload[ -overhead_szB_lo(a) ]; } //--------------------------------------------------------------------------- // Set and get the next and previous link fields of a block. static __inline__ void set_prev_b ( Block* b, Block* prev_p ) { UByte* b2 = (UByte*)b; *(Block**)&b2[hp_overhead_szB() + sizeof(SizeT)] = prev_p; } static __inline__ void set_next_b ( Block* b, Block* next_p ) { UByte* b2 = (UByte*)b; *(Block**)&b2[get_bszB(b) - sizeof(SizeT) - sizeof(void*)] = next_p; } static __inline__ Block* get_prev_b ( Block* b ) { UByte* b2 = (UByte*)b; return *(Block**)&b2[hp_overhead_szB() + sizeof(SizeT)]; } static __inline__ Block* get_next_b ( Block* b ) { UByte* b2 = (UByte*)b; return *(Block**)&b2[get_bszB(b) - sizeof(SizeT) - sizeof(void*)]; } //--------------------------------------------------------------------------- // Set and get the cost-center field of a block. static __inline__ void set_cc ( Block* b, HChar* cc ) { UByte* b2 = (UByte*)b; vg_assert( VG_(clo_profile_heap) ); *(HChar**)&b2[0] = cc; } static __inline__ HChar* get_cc ( Block* b ) { UByte* b2 = (UByte*)b; vg_assert( VG_(clo_profile_heap) ); return *(HChar**)&b2[0]; } //--------------------------------------------------------------------------- // Get the block immediately preceding this one in the Superblock. static __inline__ Block* get_predecessor_block ( Block* b ) { UByte* b2 = (UByte*)b; SizeT bszB = mk_plain_bszB( (*(SizeT*)&b2[-sizeof(SizeT)]) ); return (Block*)&b2[-bszB]; } //--------------------------------------------------------------------------- // Read and write the lower and upper red-zone bytes of a block. static __inline__ void set_rz_lo_byte ( Block* b, UInt rz_byteno, UByte v ) { UByte* b2 = (UByte*)b; b2[hp_overhead_szB() + sizeof(SizeT) + rz_byteno] = v; } static __inline__ void set_rz_hi_byte ( Block* b, UInt rz_byteno, UByte v ) { UByte* b2 = (UByte*)b; b2[get_bszB(b) - sizeof(SizeT) - rz_byteno - 1] = v; } static __inline__ UByte get_rz_lo_byte ( Block* b, UInt rz_byteno ) { UByte* b2 = (UByte*)b; return b2[hp_overhead_szB() + sizeof(SizeT) + rz_byteno]; } static __inline__ UByte get_rz_hi_byte ( Block* b, UInt rz_byteno ) { UByte* b2 = (UByte*)b; return b2[get_bszB(b) - sizeof(SizeT) - rz_byteno - 1]; } /*------------------------------------------------------------*/ /*--- Arena management ---*/ /*------------------------------------------------------------*/ #define CORE_ARENA_MIN_SZB 1048576 // The arena structures themselves. static Arena vg_arena[VG_N_ARENAS]; // Functions external to this module identify arenas using ArenaIds, // not Arena*s. This fn converts the former to the latter. static Arena* arenaId_to_ArenaP ( ArenaId arena ) { vg_assert(arena >= 0 && arena < VG_N_ARENAS); return & vg_arena[arena]; } // Initialise an arena. rz_szB is the minimum redzone size; it might be // made bigger to ensure that VG_MIN_MALLOC_SZB is observed. static void arena_init ( ArenaId aid, Char* name, SizeT rz_szB, SizeT min_sblock_szB, SizeT min_unsplittable_sblock_szB ) { SizeT i; Arena* a = arenaId_to_ArenaP(aid); // Ensure redzones are a reasonable size. They must always be at least // the size of a pointer, for holding the prev/next pointer (see the layout // details at the top of this file). vg_assert(rz_szB < 128); if (rz_szB < sizeof(void*)) rz_szB = sizeof(void*); vg_assert((min_sblock_szB % VKI_PAGE_SIZE) == 0); a->name = name; a->clientmem = ( VG_AR_CLIENT == aid ? True : False ); // The size of the low and high admin sections in a block must be a // multiple of VG_MIN_MALLOC_SZB. So we round up the asked-for // redzone size if necessary to achieve this. a->rz_szB = rz_szB; while (0 != overhead_szB_lo(a) % VG_MIN_MALLOC_SZB) a->rz_szB++; vg_assert(overhead_szB_lo(a) - hp_overhead_szB() == overhead_szB_hi(a)); a->min_sblock_szB = min_sblock_szB; a->min_unsplittable_sblock_szB = min_unsplittable_sblock_szB; for (i = 0; i < N_MALLOC_LISTS; i++) a->freelist[i] = NULL; a->sblocks = & a->sblocks_initial[0]; a->sblocks_size = SBLOCKS_SIZE_INITIAL; a->sblocks_used = 0; a->stats__nreclaim_unsplit = 0; a->stats__nreclaim_split = 0; a->stats__bytes_on_loan = 0; a->stats__bytes_mmaped = 0; a->stats__bytes_on_loan_max = 0; a->stats__bytes_mmaped_max = 0; a->stats__tot_blocks = 0; a->stats__tot_bytes = 0; a->stats__nsearches = 0; a->next_profile_at = 25 * 1000 * 1000; vg_assert(sizeof(a->sblocks_initial) == SBLOCKS_SIZE_INITIAL * sizeof(Superblock*)); } /* Print vital stats for an arena. */ void VG_(print_all_arena_stats) ( void ) { UInt i; for (i = 0; i < VG_N_ARENAS; i++) { Arena* a = arenaId_to_ArenaP(i); VG_(message)(Vg_DebugMsg, "%8s: %8ld/%8ld max/curr mmap'd, " "%llu/%llu unsplit/split sb unmmap'd, " "%8ld/%8ld max/curr, " "%10llu/%10llu totalloc-blocks/bytes," " %10llu searches\n", a->name, a->stats__bytes_mmaped_max, a->stats__bytes_mmaped, a->stats__nreclaim_unsplit, a->stats__nreclaim_split, a->stats__bytes_on_loan_max, a->stats__bytes_on_loan, a->stats__tot_blocks, a->stats__tot_bytes, a->stats__nsearches ); } } void VG_(print_arena_cc_analysis) ( void ) { UInt i; vg_assert( VG_(clo_profile_heap) ); for (i = 0; i < VG_N_ARENAS; i++) { cc_analyse_alloc_arena(i); } } /* This library is self-initialising, as it makes this more self-contained, less coupled with the outside world. Hence VG_(arena_malloc)() and VG_(arena_free)() below always call ensure_mm_init() to ensure things are correctly initialised. We initialise the client arena separately (and later) because the core must do non-client allocation before the tool has a chance to set the client arena's redzone size. */ static Bool client_inited = False; static Bool nonclient_inited = False; static void ensure_mm_init ( ArenaId aid ) { static SizeT client_rz_szB = 8; // default: be paranoid /* We use checked red zones (of various sizes) for our internal stuff, and an unchecked zone of arbitrary size for the client. Of course the client's red zone can be checked by the tool, eg. by using addressibility maps, but not by the mechanism implemented here, which merely checks at the time of freeing that the red zone bytes are unchanged. Nb: redzone sizes are *minimums*; they could be made bigger to ensure alignment. Eg. with 8 byte alignment, on 32-bit machines 4 stays as 4, but 16 becomes 20; but on 64-bit machines 4 becomes 8, and 16 stays as 16 --- the extra 4 bytes in both are accounted for by the larger prev/next ptr. */ if (VG_AR_CLIENT == aid) { Int ar_client_sbszB; if (client_inited) { // This assertion ensures that a tool cannot try to change the client // redzone size with VG_(needs_malloc_replacement)() after this module // has done its first allocation from the client arena. if (VG_(needs).malloc_replacement) vg_assert(client_rz_szB == VG_(tdict).tool_client_redzone_szB); return; } // Check and set the client arena redzone size if (VG_(needs).malloc_replacement) { client_rz_szB = VG_(tdict).tool_client_redzone_szB; // 128 is no special figure, just something not too big if (client_rz_szB > 128) { VG_(printf)( "\nTool error:\n" " specified redzone size is too big (%llu)\n", (ULong)client_rz_szB); VG_(exit)(1); } } // Initialise the client arena. On all platforms, // increasing the superblock size reduces the number of superblocks // in the client arena, which makes findSb cheaper. ar_client_sbszB = 4194304; // superblocks with a size > ar_client_sbszB will be unsplittable // (unless used for providing memalign-ed blocks). arena_init ( VG_AR_CLIENT, "client", client_rz_szB, ar_client_sbszB, ar_client_sbszB+1); client_inited = True; } else { if (nonclient_inited) { return; } set_at_init_hp_overhead_szB = VG_(clo_profile_heap) ? VG_MIN_MALLOC_SZB : 0; // Initialise the non-client arenas // Similarly to client arena, big allocations will be unsplittable. arena_init ( VG_AR_CORE, "core", 4, 1048576, 1048576+1 ); arena_init ( VG_AR_TOOL, "tool", 4, 4194304, 4194304+1 ); arena_init ( VG_AR_DINFO, "dinfo", 4, 1048576, 1048576+1 ); arena_init ( VG_AR_DEMANGLE, "demangle", 4, 65536, 65536+1 ); arena_init ( VG_AR_EXECTXT, "exectxt", 4, 1048576, 1048576+1 ); arena_init ( VG_AR_ERRORS, "errors", 4, 65536, 65536+1 ); arena_init ( VG_AR_TTAUX, "ttaux", 4, 65536, 65536+1 ); nonclient_inited = True; } # ifdef DEBUG_MALLOC VG_(printf)("ZZZ1\n"); VG_(sanity_check_malloc_all)(); VG_(printf)("ZZZ2\n"); # endif } /*------------------------------------------------------------*/ /*--- Superblock management ---*/ /*------------------------------------------------------------*/ __attribute__((noreturn)) void VG_(out_of_memory_NORETURN) ( HChar* who, SizeT szB ) { static Bool alreadyCrashing = False; ULong tot_alloc = VG_(am_get_anonsize_total)(); Char* s1 = "\n" " Valgrind's memory management: out of memory:\n" " %s's request for %llu bytes failed.\n" " %llu bytes have already been allocated.\n" " Valgrind cannot continue. Sorry.\n\n" " There are several possible reasons for this.\n" " - You have some kind of memory limit in place. Look at the\n" " output of 'ulimit -a'. Is there a limit on the size of\n" " virtual memory or address space?\n" " - You have run out of swap space.\n" " - Valgrind has a bug. If you think this is the case or you are\n" " not sure, please let us know and we'll try to fix it.\n" " Please note that programs can take substantially more memory than\n" " normal when running under Valgrind tools, eg. up to twice or\n" " more, depending on the tool. On a 64-bit machine, Valgrind\n" " should be able to make use of up 32GB memory. On a 32-bit\n" " machine, Valgrind should be able to use all the memory available\n" " to a single process, up to 4GB if that's how you have your\n" " kernel configured. Most 32-bit Linux setups allow a maximum of\n" " 3GB per process.\n\n" " Whatever the reason, Valgrind cannot continue. Sorry.\n"; if (!alreadyCrashing) { alreadyCrashing = True; VG_(message)(Vg_UserMsg, s1, who, (ULong)szB, tot_alloc); } else { VG_(debugLog)(0,"mallocfree", s1, who, (ULong)szB, tot_alloc); } VG_(exit)(1); } // Align ptr p upwards to an align-sized boundary. static void* align_upwards ( void* p, SizeT align ) { Addr a = (Addr)p; if ((a % align) == 0) return (void*)a; return (void*)(a - (a % align) + align); } // Forward definition. static void deferred_reclaimSuperblock ( Arena* a, Superblock* sb); // If not enough memory available, either aborts (for non-client memory) // or returns 0 (for client memory). static Superblock* newSuperblock ( Arena* a, SizeT cszB ) { Superblock* sb; SysRes sres; Bool unsplittable; ArenaId aid; // A new superblock is needed for arena a. We will execute the deferred // reclaim in all arenas in order to minimise fragmentation and // peak memory usage. for (aid = 0; aid < VG_N_ARENAS; aid++) { Arena* arena = arenaId_to_ArenaP(aid); if (arena->deferred_reclaimed_sb != NULL) deferred_reclaimSuperblock (arena, NULL); } // Take into account admin bytes in the Superblock. cszB += sizeof(Superblock); if (cszB < a->min_sblock_szB) cszB = a->min_sblock_szB; cszB = VG_PGROUNDUP(cszB); if (cszB >= a->min_unsplittable_sblock_szB) unsplittable = True; else unsplittable = False; if (a->clientmem) { // client allocation -- return 0 to client if it fails if (unsplittable) sres = VG_(am_mmap_anon_float_client) ( cszB, VKI_PROT_READ|VKI_PROT_WRITE|VKI_PROT_EXEC ); else sres = VG_(am_sbrk_anon_float_client) ( cszB, VKI_PROT_READ|VKI_PROT_WRITE|VKI_PROT_EXEC ); if (sr_isError(sres)) return 0; sb = (Superblock*)(AddrH)sr_Res(sres); // Mark this segment as containing client heap. The leak // checker needs to be able to identify such segments so as not // to use them as sources of roots during leak checks. VG_(am_set_segment_isCH_if_SkAnonC)( (NSegment*) VG_(am_find_nsegment)( (Addr)sb ) ); } else { // non-client allocation -- abort if it fails if (unsplittable) sres = VG_(am_mmap_anon_float_valgrind)( cszB ); else sres = VG_(am_sbrk_anon_float_valgrind)( cszB ); if (sr_isError(sres)) { VG_(out_of_memory_NORETURN)("newSuperblock", cszB); /* NOTREACHED */ sb = NULL; /* keep gcc happy */ } else { sb = (Superblock*)(AddrH)sr_Res(sres); } } vg_assert(NULL != sb); INNER_REQUEST(VALGRIND_MAKE_MEM_UNDEFINED(sb, cszB)); vg_assert(0 == (Addr)sb % VG_MIN_MALLOC_SZB); sb->n_payload_bytes = cszB - sizeof(Superblock); sb->unsplittable = (unsplittable ? sb : NULL); a->stats__bytes_mmaped += cszB; if (a->stats__bytes_mmaped > a->stats__bytes_mmaped_max) a->stats__bytes_mmaped_max = a->stats__bytes_mmaped; VG_(debugLog)(1, "mallocfree", "newSuperblock at %p (pszB %7ld) %s owner %s/%s\n", sb, sb->n_payload_bytes, (unsplittable ? "unsplittable" : ""), a->clientmem ? "CLIENT" : "VALGRIND", a->name ); return sb; } // Reclaims the given superblock: // * removes sb from arena sblocks list. // * munmap the superblock segment. static void reclaimSuperblock ( Arena* a, Superblock* sb) { SysRes sres; SizeT cszB; UInt i, j; VG_(debugLog)(1, "mallocfree", "reclaimSuperblock at %p (pszB %7ld) %s owner %s/%s\n", sb, sb->n_payload_bytes, (sb->unsplittable ? "unsplittable" : ""), a->clientmem ? "CLIENT" : "VALGRIND", a->name ); // Take into account admin bytes in the Superblock. cszB = sizeof(Superblock) + sb->n_payload_bytes; // removes sb from superblock list. for (i = 0; i < a->sblocks_used; i++) { if (a->sblocks[i] == sb) break; } vg_assert(i >= 0 && i < a->sblocks_used); for (j = i; j < a->sblocks_used; j++) a->sblocks[j] = a->sblocks[j+1]; a->sblocks_used--; a->sblocks[a->sblocks_used] = NULL; // paranoia: NULLify ptr to reclaimed sb or NULLify copy of ptr to last sb. a->stats__bytes_mmaped -= cszB; if (sb->unsplittable) a->stats__nreclaim_unsplit++; else a->stats__nreclaim_split++; // Now that the sb is removed from the list, mnumap its space. if (a->clientmem) { // reclaimable client allocation Bool need_discard = False; sres = VG_(am_munmap_client)(&need_discard, (Addr) sb, cszB); vg_assert2(! sr_isError(sres), "superblock client munmap failure\n"); /* We somewhat help the client by discarding the range. Note however that if the client has JITted some code in a small block that was freed, we do not provide this 'discard support' */ /* JRS 2011-Sept-26: it would be nice to move the discard outwards somewhat (in terms of calls) so as to make it easier to verify that there will be no nonterminating recursive set of calls a result of calling VG_(discard_translations). Another day, perhaps. */ if (need_discard) VG_(discard_translations) ((Addr) sb, cszB, "reclaimSuperblock"); } else { // reclaimable non-client allocation sres = VG_(am_munmap_valgrind)((Addr) sb, cszB); vg_assert2(! sr_isError(sres), "superblock valgrind munmap failure\n"); } } // Find the superblock containing the given chunk. static Superblock* findSb ( Arena* a, Block* b ) { SizeT min = 0; SizeT max = a->sblocks_used; while (min <= max) { Superblock * sb; SizeT pos = min + (max - min)/2; vg_assert(pos >= 0 && pos < a->sblocks_used); sb = a->sblocks[pos]; if ((Block*)&sb->payload_bytes[0] <= b && b < (Block*)&sb->payload_bytes[sb->n_payload_bytes]) { return sb; } else if ((Block*)&sb->payload_bytes[0] <= b) { min = pos + 1; } else { max = pos - 1; } } VG_(printf)("findSb: can't find pointer %p in arena '%s'\n", b, a->name ); VG_(core_panic)("findSb: VG_(arena_free)() in wrong arena?"); return NULL; /*NOTREACHED*/ } /*------------------------------------------------------------*/ /*--- Functions for working with freelists. ---*/ /*------------------------------------------------------------*/ // Nb: Determination of which freelist a block lives on is based on the // payload size, not block size. // Convert a payload size in bytes to a freelist number. static UInt pszB_to_listNo ( SizeT pszB ) { SizeT n = pszB / VG_MIN_MALLOC_SZB; vg_assert(0 == pszB % VG_MIN_MALLOC_SZB); // The first 64 lists hold blocks of size VG_MIN_MALLOC_SZB * list_num. // The final 48 hold bigger blocks. if (n < 64) return (UInt)n; /* Exponential slope up, factor 1.05 */ if (n < 67) return 64; if (n < 70) return 65; if (n < 74) return 66; if (n < 77) return 67; if (n < 81) return 68; if (n < 85) return 69; if (n < 90) return 70; if (n < 94) return 71; if (n < 99) return 72; if (n < 104) return 73; if (n < 109) return 74; if (n < 114) return 75; if (n < 120) return 76; if (n < 126) return 77; if (n < 133) return 78; if (n < 139) return 79; /* Exponential slope up, factor 1.10 */ if (n < 153) return 80; if (n < 169) return 81; if (n < 185) return 82; if (n < 204) return 83; if (n < 224) return 84; if (n < 247) return 85; if (n < 272) return 86; if (n < 299) return 87; if (n < 329) return 88; if (n < 362) return 89; if (n < 398) return 90; if (n < 438) return 91; if (n < 482) return 92; if (n < 530) return 93; if (n < 583) return 94; if (n < 641) return 95; /* Exponential slope up, factor 1.20 */ if (n < 770) return 96; if (n < 924) return 97; if (n < 1109) return 98; if (n < 1331) return 99; if (n < 1597) return 100; if (n < 1916) return 101; if (n < 2300) return 102; if (n < 2760) return 103; if (n < 3312) return 104; if (n < 3974) return 105; if (n < 4769) return 106; if (n < 5723) return 107; if (n < 6868) return 108; if (n < 8241) return 109; if (n < 9890) return 110; return 111; } // What is the minimum payload size for a given list? static SizeT listNo_to_pszB_min ( UInt listNo ) { /* Repeatedly computing this function at every request is expensive. Hence at the first call just cache the result for every possible argument. */ static SizeT cache[N_MALLOC_LISTS]; static Bool cache_valid = False; if (!cache_valid) { UInt i; for (i = 0; i < N_MALLOC_LISTS; i++) { SizeT pszB = 0; while (pszB_to_listNo(pszB) < i) pszB += VG_MIN_MALLOC_SZB; cache[i] = pszB; } cache_valid = True; } /* Returned cached answer. */ vg_assert(listNo <= N_MALLOC_LISTS); return cache[listNo]; } // What is the maximum payload size for a given list? static SizeT listNo_to_pszB_max ( UInt listNo ) { vg_assert(listNo <= N_MALLOC_LISTS); if (listNo == N_MALLOC_LISTS-1) { return MAX_PSZB; } else { return listNo_to_pszB_min(listNo+1) - 1; } } /* A nasty hack to try and reduce fragmentation. Try and replace a->freelist[lno] with another block on the same list but with a lower address, with the idea of attempting to recycle the same blocks rather than cruise through the address space. */ static void swizzle ( Arena* a, UInt lno ) { Block* p_best; Block* pp; Block* pn; UInt i; p_best = a->freelist[lno]; if (p_best == NULL) return; pn = pp = p_best; // This loop bound was 20 for a long time, but experiments showed that // reducing it to 10 gave the same result in all the tests, and 5 got the // same result in 85--100% of cases. And it's called often enough to be // noticeable in programs that allocated a lot. for (i = 0; i < 5; i++) { pn = get_next_b(pn); pp = get_prev_b(pp); if (pn < p_best) p_best = pn; if (pp < p_best) p_best = pp; } if (p_best < a->freelist[lno]) { # ifdef VERBOSE_MALLOC VG_(printf)("retreat by %ld\n", (Word)(a->freelist[lno] - p_best)); # endif a->freelist[lno] = p_best; } } /*------------------------------------------------------------*/ /*--- Sanity-check/debugging machinery. ---*/ /*------------------------------------------------------------*/ #define REDZONE_LO_MASK 0x31 #define REDZONE_HI_MASK 0x7c // Do some crude sanity checks on a Block. static Bool blockSane ( Arena* a, Block* b ) { # define BLEAT(str) VG_(printf)("blockSane: fail -- %s\n",str) UInt i; // The lo and hi size fields will be checked (indirectly) by the call // to get_rz_hi_byte(). if (!a->clientmem && is_inuse_block(b)) { // In the inner, for memcheck sake, temporarily mark redzone accessible. INNER_REQUEST(VALGRIND_MAKE_MEM_DEFINED (b + hp_overhead_szB() + sizeof(SizeT), a->rz_szB)); INNER_REQUEST(VALGRIND_MAKE_MEM_DEFINED (b + get_bszB(b) - sizeof(SizeT) - a->rz_szB, a->rz_szB)); for (i = 0; i < a->rz_szB; i++) { if (get_rz_lo_byte(b, i) != (UByte)(((Addr)b&0xff) ^ REDZONE_LO_MASK)) {BLEAT("redzone-lo");return False;} if (get_rz_hi_byte(b, i) != (UByte)(((Addr)b&0xff) ^ REDZONE_HI_MASK)) {BLEAT("redzone-hi");return False;} } INNER_REQUEST(VALGRIND_MAKE_MEM_NOACCESS (b + hp_overhead_szB() + sizeof(SizeT), a->rz_szB)); INNER_REQUEST(VALGRIND_MAKE_MEM_NOACCESS (b + get_bszB(b) - sizeof(SizeT) - a->rz_szB, a->rz_szB)); } return True; # undef BLEAT } // Print superblocks (only for debugging). static void ppSuperblocks ( Arena* a ) { UInt i, j, blockno = 1; SizeT b_bszB; for (j = 0; j < a->sblocks_used; ++j) { Superblock * sb = a->sblocks[j]; VG_(printf)( "\n" ); VG_(printf)( "superblock %d at %p %s, sb->n_pl_bs = %lu\n", blockno++, sb, (sb->unsplittable ? "unsplittable" : ""), sb->n_payload_bytes); for (i = 0; i < sb->n_payload_bytes; i += b_bszB) { Block* b = (Block*)&sb->payload_bytes[i]; b_bszB = get_bszB(b); VG_(printf)( " block at %d, bszB %lu: ", i, b_bszB ); VG_(printf)( "%s, ", is_inuse_block(b) ? "inuse" : "free"); VG_(printf)( "%s\n", blockSane(a, b) ? "ok" : "BAD" ); } vg_assert(i == sb->n_payload_bytes); // no overshoot at end of Sb } VG_(printf)( "end of superblocks\n\n" ); } // Sanity check both the superblocks and the chains. static void sanity_check_malloc_arena ( ArenaId aid ) { UInt i, j, superblockctr, blockctr_sb, blockctr_li; UInt blockctr_sb_free, listno; SizeT b_bszB, b_pszB, list_min_pszB, list_max_pszB; Bool thisFree, lastWasFree, sblockarrOK; Block* b; Block* b_prev; SizeT arena_bytes_on_loan; Arena* a; # define BOMB VG_(core_panic)("sanity_check_malloc_arena") a = arenaId_to_ArenaP(aid); // Check the superblock array. sblockarrOK = a->sblocks != NULL && a->sblocks_size >= SBLOCKS_SIZE_INITIAL && a->sblocks_used <= a->sblocks_size && (a->sblocks_size == SBLOCKS_SIZE_INITIAL ? (a->sblocks == &a->sblocks_initial[0]) : (a->sblocks != &a->sblocks_initial[0])); if (!sblockarrOK) { VG_(printf)("sanity_check_malloc_arena: sblock array BAD\n"); BOMB; } // First, traverse all the superblocks, inspecting the Blocks in each. superblockctr = blockctr_sb = blockctr_sb_free = 0; arena_bytes_on_loan = 0; for (j = 0; j < a->sblocks_used; ++j) { Superblock * sb = a->sblocks[j]; lastWasFree = False; superblockctr++; for (i = 0; i < sb->n_payload_bytes; i += mk_plain_bszB(b_bszB)) { blockctr_sb++; b = (Block*)&sb->payload_bytes[i]; b_bszB = get_bszB_as_is(b); if (!blockSane(a, b)) { VG_(printf)("sanity_check_malloc_arena: sb %p, block %d " "(bszB %lu): BAD\n", sb, i, b_bszB ); BOMB; } thisFree = !is_inuse_block(b); if (thisFree && lastWasFree) { VG_(printf)("sanity_check_malloc_arena: sb %p, block %d " "(bszB %lu): UNMERGED FREES\n", sb, i, b_bszB ); BOMB; } if (thisFree) blockctr_sb_free++; if (!thisFree) arena_bytes_on_loan += bszB_to_pszB(a, b_bszB); lastWasFree = thisFree; } if (i > sb->n_payload_bytes) { VG_(printf)( "sanity_check_malloc_arena: sb %p: last block " "overshoots end\n", sb); BOMB; } } if (arena_bytes_on_loan != a->stats__bytes_on_loan) { # ifdef VERBOSE_MALLOC VG_(printf)( "sanity_check_malloc_arena: a->bytes_on_loan %lu, " "arena_bytes_on_loan %lu: " "MISMATCH\n", a->bytes_on_loan, arena_bytes_on_loan); # endif ppSuperblocks(a); BOMB; } /* Second, traverse each list, checking that the back pointers make sense, counting blocks encountered, and checking that each block is an appropriate size for this list. */ blockctr_li = 0; for (listno = 0; listno < N_MALLOC_LISTS; listno++) { list_min_pszB = listNo_to_pszB_min(listno); list_max_pszB = listNo_to_pszB_max(listno); b = a->freelist[listno]; if (b == NULL) continue; while (True) { b_prev = b; b = get_next_b(b); if (get_prev_b(b) != b_prev) { VG_(printf)( "sanity_check_malloc_arena: list %d at %p: " "BAD LINKAGE\n", listno, b ); BOMB; } b_pszB = get_pszB(a, b); if (b_pszB < list_min_pszB || b_pszB > list_max_pszB) { VG_(printf)( "sanity_check_malloc_arena: list %d at %p: " "WRONG CHAIN SIZE %luB (%luB, %luB)\n", listno, b, b_pszB, list_min_pszB, list_max_pszB ); BOMB; } blockctr_li++; if (b == a->freelist[listno]) break; } } if (blockctr_sb_free != blockctr_li) { # ifdef VERBOSE_MALLOC VG_(printf)( "sanity_check_malloc_arena: BLOCK COUNT MISMATCH " "(via sbs %d, via lists %d)\n", blockctr_sb_free, blockctr_li ); # endif ppSuperblocks(a); BOMB; } if (VG_(clo_verbosity) > 2) VG_(message)(Vg_DebugMsg, "%8s: %2d sbs, %5d bs, %2d/%-2d free bs, " "%7ld mmap, %7ld loan\n", a->name, superblockctr, blockctr_sb, blockctr_sb_free, blockctr_li, a->stats__bytes_mmaped, a->stats__bytes_on_loan); # undef BOMB } #define N_AN_CCS 1000 typedef struct { ULong nBytes; ULong nBlocks; HChar* cc; } AnCC; static AnCC anCCs[N_AN_CCS]; static Int cmp_AnCC_by_vol ( void* v1, void* v2 ) { AnCC* ancc1 = (AnCC*)v1; AnCC* ancc2 = (AnCC*)v2; if (ancc1->nBytes < ancc2->nBytes) return -1; if (ancc1->nBytes > ancc2->nBytes) return 1; return 0; } static void cc_analyse_alloc_arena ( ArenaId aid ) { Word i, j, k; Arena* a; Block* b; Bool thisFree, lastWasFree; SizeT b_bszB; HChar* cc; UInt n_ccs = 0; //return; a = arenaId_to_ArenaP(aid); if (a->name == NULL) { /* arena is not in use, is not initialised and will fail the sanity check that follows. */ return; } sanity_check_malloc_arena(aid); VG_(printf)( "-------- Arena \"%s\": %lu/%lu max/curr mmap'd, " "%llu/%llu unsplit/split sb unmmap'd, " "%lu/%lu max/curr on_loan --------\n", a->name, a->stats__bytes_mmaped_max, a->stats__bytes_mmaped, a->stats__nreclaim_unsplit, a->stats__nreclaim_split, a->stats__bytes_on_loan_max, a->stats__bytes_on_loan ); for (j = 0; j < a->sblocks_used; ++j) { Superblock * sb = a->sblocks[j]; lastWasFree = False; for (i = 0; i < sb->n_payload_bytes; i += mk_plain_bszB(b_bszB)) { b = (Block*)&sb->payload_bytes[i]; b_bszB = get_bszB_as_is(b); if (!blockSane(a, b)) { VG_(printf)("sanity_check_malloc_arena: sb %p, block %ld " "(bszB %lu): BAD\n", sb, i, b_bszB ); tl_assert(0); } thisFree = !is_inuse_block(b); if (thisFree && lastWasFree) { VG_(printf)("sanity_check_malloc_arena: sb %p, block %ld " "(bszB %lu): UNMERGED FREES\n", sb, i, b_bszB ); tl_assert(0); } lastWasFree = thisFree; if (thisFree) continue; if (0) VG_(printf)("block: inUse=%d pszB=%d cc=%s\n", (Int)(!thisFree), (Int)bszB_to_pszB(a, b_bszB), get_cc(b)); cc = get_cc(b); tl_assert(cc); for (k = 0; k < n_ccs; k++) { tl_assert(anCCs[k].cc); if (0 == VG_(strcmp)(cc, anCCs[k].cc)) break; } tl_assert(k >= 0 && k <= n_ccs); if (k == n_ccs) { tl_assert(n_ccs < N_AN_CCS-1); n_ccs++; anCCs[k].nBytes = 0; anCCs[k].nBlocks = 0; anCCs[k].cc = cc; } tl_assert(k >= 0 && k < n_ccs && k < N_AN_CCS); anCCs[k].nBytes += (ULong)bszB_to_pszB(a, b_bszB); anCCs[k].nBlocks++; } if (i > sb->n_payload_bytes) { VG_(printf)( "sanity_check_malloc_arena: sb %p: last block " "overshoots end\n", sb); tl_assert(0); } } VG_(ssort)( &anCCs[0], n_ccs, sizeof(anCCs[0]), cmp_AnCC_by_vol ); for (k = 0; k < n_ccs; k++) { VG_(printf)("%'13llu in %'9llu: %s\n", anCCs[k].nBytes, anCCs[k].nBlocks, anCCs[k].cc ); } VG_(printf)("\n"); } void VG_(sanity_check_malloc_all) ( void ) { UInt i; for (i = 0; i < VG_N_ARENAS; i++) { if (i == VG_AR_CLIENT && !client_inited) continue; sanity_check_malloc_arena ( i ); } } /*------------------------------------------------------------*/ /*--- Creating and deleting blocks. ---*/ /*------------------------------------------------------------*/ // Mark the bytes at b .. b+bszB-1 as not in use, and add them to the // relevant free list. static void mkFreeBlock ( Arena* a, Block* b, SizeT bszB, UInt b_lno ) { SizeT pszB = bszB_to_pszB(a, bszB); vg_assert(b_lno == pszB_to_listNo(pszB)); INNER_REQUEST(VALGRIND_MAKE_MEM_UNDEFINED(b, bszB)); // Set the size fields and indicate not-in-use. set_bszB(b, mk_free_bszB(bszB)); // Add to the relevant list. if (a->freelist[b_lno] == NULL) { set_prev_b(b, b); set_next_b(b, b); a->freelist[b_lno] = b; } else { Block* b_prev = get_prev_b(a->freelist[b_lno]); Block* b_next = a->freelist[b_lno]; set_next_b(b_prev, b); set_prev_b(b_next, b); set_next_b(b, b_next); set_prev_b(b, b_prev); } # ifdef DEBUG_MALLOC (void)blockSane(a,b); # endif } // Mark the bytes at b .. b+bszB-1 as in use, and set up the block // appropriately. static void mkInuseBlock ( Arena* a, Block* b, SizeT bszB ) { UInt i; vg_assert(bszB >= min_useful_bszB(a)); INNER_REQUEST(VALGRIND_MAKE_MEM_UNDEFINED(b, bszB)); set_bszB(b, mk_inuse_bszB(bszB)); set_prev_b(b, NULL); // Take off freelist set_next_b(b, NULL); // ditto if (!a->clientmem) { for (i = 0; i < a->rz_szB; i++) { set_rz_lo_byte(b, i, (UByte)(((Addr)b&0xff) ^ REDZONE_LO_MASK)); set_rz_hi_byte(b, i, (UByte)(((Addr)b&0xff) ^ REDZONE_HI_MASK)); } } # ifdef DEBUG_MALLOC (void)blockSane(a,b); # endif } // Remove a block from a given list. Does no sanity checking. static void unlinkBlock ( Arena* a, Block* b, UInt listno ) { vg_assert(listno < N_MALLOC_LISTS); if (get_prev_b(b) == b) { // Only one element in the list; treat it specially. vg_assert(get_next_b(b) == b); a->freelist[listno] = NULL; } else { Block* b_prev = get_prev_b(b); Block* b_next = get_next_b(b); a->freelist[listno] = b_prev; set_next_b(b_prev, b_next); set_prev_b(b_next, b_prev); swizzle ( a, listno ); } set_prev_b(b, NULL); set_next_b(b, NULL); } /*------------------------------------------------------------*/ /*--- Core-visible functions. ---*/ /*------------------------------------------------------------*/ // Align the request size. static __inline__ SizeT align_req_pszB ( SizeT req_pszB ) { SizeT n = VG_MIN_MALLOC_SZB-1; return ((req_pszB + n) & (~n)); } void* VG_(arena_malloc) ( ArenaId aid, HChar* cc, SizeT req_pszB ) { SizeT req_bszB, frag_bszB, b_bszB; UInt lno, i; Superblock* new_sb = NULL; Block* b = NULL; Arena* a; void* v; UWord stats__nsearches = 0; ensure_mm_init(aid); a = arenaId_to_ArenaP(aid); vg_assert(req_pszB < MAX_PSZB); req_pszB = align_req_pszB(req_pszB); req_bszB = pszB_to_bszB(a, req_pszB); // You must provide a cost-center name against which to charge // this allocation; it isn't optional. vg_assert(cc); // Scan through all the big-enough freelists for a block. // // Nb: this scanning might be expensive in some cases. Eg. if you // allocate lots of small objects without freeing them, but no // medium-sized objects, it will repeatedly scanning through the whole // list, and each time not find any free blocks until the last element. // // If this becomes a noticeable problem... the loop answers the question // "where is the first nonempty list above me?" And most of the time, // you ask the same question and get the same answer. So it would be // good to somehow cache the results of previous searches. // One possibility is an array (with N_MALLOC_LISTS elements) of // shortcuts. shortcut[i] would give the index number of the nearest // larger list above list i which is non-empty. Then this loop isn't // necessary. However, we'd have to modify some section [ .. i-1] of the // shortcut array every time a list [i] changes from empty to nonempty or // back. This would require care to avoid pathological worst-case // behaviour. // for (lno = pszB_to_listNo(req_pszB); lno < N_MALLOC_LISTS; lno++) { UWord nsearches_this_level = 0; b = a->freelist[lno]; if (NULL == b) continue; // If this list is empty, try the next one. while (True) { stats__nsearches++; nsearches_this_level++; if (UNLIKELY(nsearches_this_level >= 100) && lno < N_MALLOC_LISTS-1) { /* Avoid excessive scanning on this freelist, and instead try the next one up. But first, move this freelist's start pointer one element along, so as to ensure that subsequent searches of this list don't endlessly revisit only these 100 elements, but in fact slowly progress through the entire list. */ b = a->freelist[lno]; vg_assert(b); // this list must be nonempty! a->freelist[lno] = get_next_b(b); // step one along break; } b_bszB = get_bszB(b); if (b_bszB >= req_bszB) goto obtained_block; // success! b = get_next_b(b); if (b == a->freelist[lno]) break; // traversed entire freelist } } // If we reach here, no suitable block found, allocate a new superblock vg_assert(lno == N_MALLOC_LISTS); new_sb = newSuperblock(a, req_bszB); if (NULL == new_sb) { // Should only fail if for client, otherwise, should have aborted // already. vg_assert(VG_AR_CLIENT == aid); return NULL; } vg_assert(a->sblocks_used <= a->sblocks_size); if (a->sblocks_used == a->sblocks_size) { Superblock ** array; SysRes sres = VG_(am_sbrk_anon_float_valgrind)(sizeof(Superblock *) * a->sblocks_size * 2); if (sr_isError(sres)) { VG_(out_of_memory_NORETURN)("arena_init", sizeof(Superblock *) * a->sblocks_size * 2); /* NOTREACHED */ } array = (Superblock**)(AddrH)sr_Res(sres); for (i = 0; i < a->sblocks_used; ++i) array[i] = a->sblocks[i]; a->sblocks_size *= 2; a->sblocks = array; VG_(debugLog)(1, "mallocfree", "sblock array for arena `%s' resized to %ld\n", a->name, a->sblocks_size); } vg_assert(a->sblocks_used < a->sblocks_size); i = a->sblocks_used; while (i > 0) { if (a->sblocks[i-1] > new_sb) { a->sblocks[i] = a->sblocks[i-1]; } else { break; } --i; } a->sblocks[i] = new_sb; a->sblocks_used++; b = (Block*)&new_sb->payload_bytes[0]; lno = pszB_to_listNo(bszB_to_pszB(a, new_sb->n_payload_bytes)); mkFreeBlock ( a, b, new_sb->n_payload_bytes, lno); if (VG_(clo_profile_heap)) set_cc(b, "admin.free-new-sb-1"); // fall through obtained_block: // Ok, we can allocate from b, which lives in list lno. vg_assert(b != NULL); vg_assert(lno < N_MALLOC_LISTS); vg_assert(a->freelist[lno] != NULL); b_bszB = get_bszB(b); // req_bszB is the size of the block we are after. b_bszB is the // size of what we've actually got. */ vg_assert(b_bszB >= req_bszB); // Could we split this block and still get a useful fragment? // A block in an unsplittable superblock can never be splitted. frag_bszB = b_bszB - req_bszB; if (frag_bszB >= min_useful_bszB(a) && (NULL == new_sb || ! new_sb->unsplittable)) { // Yes, split block in two, put the fragment on the appropriate free // list, and update b_bszB accordingly. // printf( "split %dB into %dB and %dB\n", b_bszB, req_bszB, frag_bszB ); unlinkBlock(a, b, lno); mkInuseBlock(a, b, req_bszB); if (VG_(clo_profile_heap)) set_cc(b, cc); mkFreeBlock(a, &b[req_bszB], frag_bszB, pszB_to_listNo(bszB_to_pszB(a, frag_bszB))); if (VG_(clo_profile_heap)) set_cc(&b[req_bszB], "admin.fragmentation-1"); b_bszB = get_bszB(b); } else { // No, mark as in use and use as-is. unlinkBlock(a, b, lno); mkInuseBlock(a, b, b_bszB); if (VG_(clo_profile_heap)) set_cc(b, cc); } // Update stats SizeT loaned = bszB_to_pszB(a, b_bszB); a->stats__bytes_on_loan += loaned; if (a->stats__bytes_on_loan > a->stats__bytes_on_loan_max) { a->stats__bytes_on_loan_max = a->stats__bytes_on_loan; if (a->stats__bytes_on_loan_max >= a->next_profile_at) { /* next profile after 10% more growth */ a->next_profile_at = (SizeT)( (((ULong)a->stats__bytes_on_loan_max) * 105ULL) / 100ULL ); if (VG_(clo_profile_heap)) cc_analyse_alloc_arena(aid); } } a->stats__tot_blocks += (ULong)1; a->stats__tot_bytes += (ULong)loaned; a->stats__nsearches += (ULong)stats__nsearches; # ifdef DEBUG_MALLOC sanity_check_malloc_arena(aid); # endif v = get_block_payload(a, b); vg_assert( (((Addr)v) & (VG_MIN_MALLOC_SZB-1)) == 0 ); // Which size should we pass to VALGRIND_MALLOCLIKE_BLOCK ? // We have 2 possible options: // 1. The final resulting usable size. // 2. The initial (non-aligned) req_pszB. // Memcheck implements option 2 easily, as the initial requested size // is maintained in the mc_chunk data structure. // This is not as easy in the core, as there is no such structure. // (note: using the aligned req_pszB is not simpler than 2, as // requesting an aligned req_pszB might still be satisfied by returning // a (slightly) bigger block than requested if the remaining part of // of a free block is not big enough to make a free block by itself). // Implement Sol 2 can be done the following way: // After having called VALGRIND_MALLOCLIKE_BLOCK, the non accessible // redzone just after the block can be used to determine the // initial requested size. // Currently, not implemented => we use Option 1. INNER_REQUEST (VALGRIND_MALLOCLIKE_BLOCK(v, VG_(arena_malloc_usable_size)(aid, v), a->rz_szB, False)); /* For debugging/testing purposes, fill the newly allocated area with a definite value in an attempt to shake out any uninitialised uses of the data (by V core / V tools, not by the client). Testing on 25 Nov 07 with the values 0x00, 0xFF, 0x55, 0xAA showed no differences in the regression tests on amd64-linux. Note, is disabled by default. */ if (0 && aid != VG_AR_CLIENT) VG_(memset)(v, 0xAA, (SizeT)req_pszB); return v; } // If arena has already a deferred reclaimed superblock and // this superblock is still reclaimable, then this superblock is first // reclaimed. // sb becomes then the new arena deferred superblock. // Passing NULL as sb allows to reclaim a deferred sb without setting a new // deferred reclaim. static void deferred_reclaimSuperblock ( Arena* a, Superblock* sb) { if (sb == NULL) { if (!a->deferred_reclaimed_sb) // no deferred sb to reclaim now, nothing to do in the future => // return directly. return; VG_(debugLog)(1, "mallocfree", "deferred_reclaimSuperblock NULL " "(prev %p) owner %s/%s\n", a->deferred_reclaimed_sb, a->clientmem ? "CLIENT" : "VALGRIND", a->name ); } else VG_(debugLog)(1, "mallocfree", "deferred_reclaimSuperblock at %p (pszB %7ld) %s " "(prev %p) owner %s/%s\n", sb, sb->n_payload_bytes, (sb->unsplittable ? "unsplittable" : ""), a->deferred_reclaimed_sb, a->clientmem ? "CLIENT" : "VALGRIND", a->name ); if (a->deferred_reclaimed_sb && a->deferred_reclaimed_sb != sb) { // If we are deferring another block that the current block deferred, // then if this block can stil be reclaimed, reclaim it now. // Note that we might have a re-deferred reclaim of the same block // with a sequence: free (causing a deferred reclaim of sb) // alloc (using a piece of memory of the deferred sb) // free of the just alloc-ed block (causing a re-defer). UByte* def_sb_start; UByte* def_sb_end; Superblock* def_sb; Block* b; def_sb = a->deferred_reclaimed_sb; def_sb_start = &def_sb->payload_bytes[0]; def_sb_end = &def_sb->payload_bytes[def_sb->n_payload_bytes - 1]; b = (Block *)def_sb_start; vg_assert (blockSane(a, b)); // Check if the deferred_reclaimed_sb is still reclaimable. // If yes, we will execute the reclaim. if (!is_inuse_block(b)) { // b (at the beginning of def_sb) is not in use. UInt b_listno; SizeT b_bszB, b_pszB; b_bszB = get_bszB(b); b_pszB = bszB_to_pszB(a, b_bszB); if (b + b_bszB-1 == (Block*)def_sb_end) { // b (not in use) covers the full superblock. // => def_sb is still reclaimable // => execute now the reclaim of this def_sb. b_listno = pszB_to_listNo(b_pszB); unlinkBlock( a, b, b_listno ); reclaimSuperblock (a, def_sb); a->deferred_reclaimed_sb = NULL; } } } // sb (possibly NULL) becomes the new deferred reclaimed superblock. a->deferred_reclaimed_sb = sb; } void VG_(arena_free) ( ArenaId aid, void* ptr ) { Superblock* sb; UByte* sb_start; UByte* sb_end; Block* other_b; Block* b; SizeT b_bszB, b_pszB, other_bszB; UInt b_listno; Arena* a; ensure_mm_init(aid); a = arenaId_to_ArenaP(aid); if (ptr == NULL) { return; } b = get_payload_block(a, ptr); /* If this is one of V's areas, check carefully the block we're getting back. This picks up simple block-end overruns. */ if (aid != VG_AR_CLIENT) vg_assert(blockSane(a, b)); b_bszB = get_bszB(b); b_pszB = bszB_to_pszB(a, b_bszB); sb = findSb( a, b ); sb_start = &sb->payload_bytes[0]; sb_end = &sb->payload_bytes[sb->n_payload_bytes - 1]; a->stats__bytes_on_loan -= b_pszB; /* If this is one of V's areas, fill it up with junk to enhance the chances of catching any later reads of it. Note, 0xDD is carefully chosen junk :-), in that: (1) 0xDDDDDDDD is an invalid and non-word-aligned address on most systems, and (2) 0xDD is a value which is unlikely to be generated by the new compressed Vbits representation for memcheck. */ if (aid != VG_AR_CLIENT) VG_(memset)(ptr, 0xDD, (SizeT)b_pszB); if (! sb->unsplittable) { // Put this chunk back on a list somewhere. b_listno = pszB_to_listNo(b_pszB); mkFreeBlock( a, b, b_bszB, b_listno ); if (VG_(clo_profile_heap)) set_cc(b, "admin.free-1"); // See if this block can be merged with its successor. // First test if we're far enough before the superblock's end to possibly // have a successor. other_b = b + b_bszB; if (other_b+min_useful_bszB(a)-1 <= (Block*)sb_end) { // Ok, we have a successor, merge if it's not in use. other_bszB = get_bszB(other_b); if (!is_inuse_block(other_b)) { // VG_(printf)( "merge-successor\n"); # ifdef DEBUG_MALLOC vg_assert(blockSane(a, other_b)); # endif unlinkBlock( a, b, b_listno ); unlinkBlock( a, other_b, pszB_to_listNo(bszB_to_pszB(a,other_bszB)) ); b_bszB += other_bszB; b_listno = pszB_to_listNo(bszB_to_pszB(a, b_bszB)); mkFreeBlock( a, b, b_bszB, b_listno ); if (VG_(clo_profile_heap)) set_cc(b, "admin.free-2"); } } else { // Not enough space for successor: check that b is the last block // ie. there are no unused bytes at the end of the Superblock. vg_assert(other_b-1 == (Block*)sb_end); } // Then see if this block can be merged with its predecessor. // First test if we're far enough after the superblock's start to possibly // have a predecessor. if (b >= (Block*)sb_start + min_useful_bszB(a)) { // Ok, we have a predecessor, merge if it's not in use. other_b = get_predecessor_block( b ); other_bszB = get_bszB(other_b); if (!is_inuse_block(other_b)) { // VG_(printf)( "merge-predecessor\n"); unlinkBlock( a, b, b_listno ); unlinkBlock( a, other_b, pszB_to_listNo(bszB_to_pszB(a, other_bszB)) ); b = other_b; b_bszB += other_bszB; b_listno = pszB_to_listNo(bszB_to_pszB(a, b_bszB)); mkFreeBlock( a, b, b_bszB, b_listno ); if (VG_(clo_profile_heap)) set_cc(b, "admin.free-3"); } } else { // Not enough space for predecessor: check that b is the first block, // ie. there are no unused bytes at the start of the Superblock. vg_assert((Block*)sb_start == b); } /* If the block b just merged is the only block of the superblock sb, then we defer reclaim sb. */ if ( ((Block*)sb_start == b) && (b + b_bszB-1 == (Block*)sb_end) ) { deferred_reclaimSuperblock (a, sb); } // Inform that ptr has been released. We give redzone size // 0 instead of a->rz_szB as proper accessibility is done just after. INNER_REQUEST(VALGRIND_FREELIKE_BLOCK(ptr, 0)); // We need to (re-)establish the minimum accessibility needed // for free list management. E.g. if block ptr has been put in a free // list and a neighbour block is released afterwards, the // "lo" and "hi" portions of the block ptr will be accessed to // glue the 2 blocks together. // We could mark the whole block as not accessible, and each time // transiently mark accessible the needed lo/hi parts. Not done as this // is quite complex, for very little expected additional bug detection. // fully unaccessible. Note that the below marks the (possibly) merged // block, not the block corresponding to the ptr argument. // First mark the whole block unaccessible. INNER_REQUEST(VALGRIND_MAKE_MEM_NOACCESS(b, b_bszB)); // Then mark the relevant administrative headers as defined. // No need to mark the heap profile portion as defined, this is not // used for free blocks. INNER_REQUEST(VALGRIND_MAKE_MEM_DEFINED(b + hp_overhead_szB(), sizeof(SizeT) + sizeof(void*))); INNER_REQUEST(VALGRIND_MAKE_MEM_DEFINED(b + b_bszB - sizeof(SizeT) - sizeof(void*), sizeof(SizeT) + sizeof(void*))); } else { // b must be first block (i.e. no unused bytes at the beginning) vg_assert((Block*)sb_start == b); // b must be last block (i.e. no unused bytes at the end) other_b = b + b_bszB; vg_assert(other_b-1 == (Block*)sb_end); // Inform that ptr has been released. Redzone size value // is not relevant (so we give 0 instead of a->rz_szB) // as it is expected that the aspacemgr munmap will be used by // outer to mark the whole superblock as unaccessible. INNER_REQUEST(VALGRIND_FREELIKE_BLOCK(ptr, 0)); // Reclaim immediately the unsplittable superblock sb. reclaimSuperblock (a, sb); } # ifdef DEBUG_MALLOC sanity_check_malloc_arena(aid); # endif } /* The idea for malloc_aligned() is to allocate a big block, base, and then split it into two parts: frag, which is returned to the the free pool, and align, which is the bit we're really after. Here's a picture. L and H denote the block lower and upper overheads, in bytes. The details are gruesome. Note it is slightly complicated because the initial request to generate base may return a bigger block than we asked for, so it is important to distinguish the base request size and the base actual size. frag_b align_b | | | frag_p | align_p | | | | v v v v +---+ +---+---+ +---+ | L |----------------| H | L |---------------| H | +---+ +---+---+ +---+ ^ ^ ^ | | : | base_p this addr must be aligned | base_b . . . . . . . <------ frag_bszB -------> . . . . <------------- base_pszB_act -----------> . . . . . . . . */ void* VG_(arena_memalign) ( ArenaId aid, HChar* cc, SizeT req_alignB, SizeT req_pszB ) { SizeT base_pszB_req, base_pszB_act, frag_bszB; Block *base_b, *align_b; UByte *base_p, *align_p; SizeT saved_bytes_on_loan; Arena* a; ensure_mm_init(aid); a = arenaId_to_ArenaP(aid); vg_assert(req_pszB < MAX_PSZB); // You must provide a cost-center name against which to charge // this allocation; it isn't optional. vg_assert(cc); // Check that the requested alignment has a plausible size. // Check that the requested alignment seems reasonable; that is, is // a power of 2. if (req_alignB < VG_MIN_MALLOC_SZB || req_alignB > 16 * 1024 * 1024 || VG_(log2)( req_alignB ) == -1 /* not a power of 2 */) { VG_(printf)("VG_(arena_memalign)(%p, %lu, %lu)\n" "bad alignment value %lu\n" "(it is too small, too big, or not a power of two)", a, req_alignB, req_pszB, req_alignB ); VG_(core_panic)("VG_(arena_memalign)"); /*NOTREACHED*/ } // Paranoid vg_assert(req_alignB % VG_MIN_MALLOC_SZB == 0); /* Required payload size for the aligned chunk. */ req_pszB = align_req_pszB(req_pszB); /* Payload size to request for the big block that we will split up. */ base_pszB_req = req_pszB + min_useful_bszB(a) + req_alignB; /* Payload ptr for the block we are going to split. Note this changes a->bytes_on_loan; we save and restore it ourselves. */ saved_bytes_on_loan = a->stats__bytes_on_loan; { /* As we will split the block given back by VG_(arena_malloc), we have to (temporarily) disable unsplittable for this arena, as unsplittable superblocks cannot be splitted. */ const SizeT save_min_unsplittable_sblock_szB = a->min_unsplittable_sblock_szB; a->min_unsplittable_sblock_szB = MAX_PSZB; base_p = VG_(arena_malloc) ( aid, cc, base_pszB_req ); a->min_unsplittable_sblock_szB = save_min_unsplittable_sblock_szB; } a->stats__bytes_on_loan = saved_bytes_on_loan; /* Give up if we couldn't allocate enough space */ if (base_p == 0) return 0; /* base_p was marked as allocated by VALGRIND_MALLOCLIKE_BLOCK inside VG_(arena_malloc). We need to indicate it is free, then we need to mark it undefined to allow the below code to access is. */ INNER_REQUEST(VALGRIND_FREELIKE_BLOCK(base_p, a->rz_szB)); INNER_REQUEST(VALGRIND_MAKE_MEM_UNDEFINED(base_p, base_pszB_req)); /* Block ptr for the block we are going to split. */ base_b = get_payload_block ( a, base_p ); /* Pointer to the payload of the aligned block we are going to return. This has to be suitably aligned. */ align_p = align_upwards ( base_b + 2 * overhead_szB_lo(a) + overhead_szB_hi(a), req_alignB ); align_b = get_payload_block(a, align_p); /* The block size of the fragment we will create. This must be big enough to actually create a fragment. */ frag_bszB = align_b - base_b; vg_assert(frag_bszB >= min_useful_bszB(a)); /* The actual payload size of the block we are going to split. */ base_pszB_act = get_pszB(a, base_b); /* Create the fragment block, and put it back on the relevant free list. */ mkFreeBlock ( a, base_b, frag_bszB, pszB_to_listNo(bszB_to_pszB(a, frag_bszB)) ); if (VG_(clo_profile_heap)) set_cc(base_b, "admin.frag-memalign-1"); /* Create the aligned block. */ mkInuseBlock ( a, align_b, base_p + base_pszB_act + overhead_szB_hi(a) - (UByte*)align_b ); if (VG_(clo_profile_heap)) set_cc(align_b, cc); /* Final sanity checks. */ vg_assert( is_inuse_block(get_payload_block(a, align_p)) ); vg_assert(req_pszB <= get_pszB(a, get_payload_block(a, align_p))); a->stats__bytes_on_loan += get_pszB(a, get_payload_block(a, align_p)); if (a->stats__bytes_on_loan > a->stats__bytes_on_loan_max) { a->stats__bytes_on_loan_max = a->stats__bytes_on_loan; } /* a->stats__tot_blocks, a->stats__tot_bytes, a->stats__nsearches are updated by the call to VG_(arena_malloc) just a few lines above. So we don't need to update them here. */ # ifdef DEBUG_MALLOC sanity_check_malloc_arena(aid); # endif vg_assert( (((Addr)align_p) % req_alignB) == 0 ); INNER_REQUEST(VALGRIND_MALLOCLIKE_BLOCK(align_p, req_pszB, a->rz_szB, False)); return align_p; } SizeT VG_(arena_malloc_usable_size) ( ArenaId aid, void* ptr ) { Arena* a = arenaId_to_ArenaP(aid); Block* b = get_payload_block(a, ptr); return get_pszB(a, b); } // Implementation of mallinfo(). There is no recent standard that defines // the behavior of mallinfo(). The meaning of the fields in struct mallinfo // is as follows: // // struct mallinfo { // int arena; /* total space in arena */ // int ordblks; /* number of ordinary blocks */ // int smblks; /* number of small blocks */ // int hblks; /* number of holding blocks */ // int hblkhd; /* space in holding block headers */ // int usmblks; /* space in small blocks in use */ // int fsmblks; /* space in free small blocks */ // int uordblks; /* space in ordinary blocks in use */ // int fordblks; /* space in free ordinary blocks */ // int keepcost; /* space penalty if keep option */ // /* is used */ // }; // // The glibc documentation about mallinfo (which is somewhat outdated) can // be found here: // http://www.gnu.org/software/libtool/manual/libc/Statistics-of-Malloc.html // // See also http://bugs.kde.org/show_bug.cgi?id=160956. // // Regarding the implementation of VG_(mallinfo)(): we cannot return the // whole struct as the library function does, because this is called by a // client request. So instead we use a pointer to do call by reference. void VG_(mallinfo) ( ThreadId tid, struct vg_mallinfo* mi ) { UWord i, free_blocks, free_blocks_size; Arena* a = arenaId_to_ArenaP(VG_AR_CLIENT); // Traverse free list and calculate free blocks statistics. // This may seem slow but glibc works the same way. free_blocks_size = free_blocks = 0; for (i = 0; i < N_MALLOC_LISTS; i++) { Block* b = a->freelist[i]; if (b == NULL) continue; for (;;) { free_blocks++; free_blocks_size += (UWord)get_pszB(a, b); b = get_next_b(b); if (b == a->freelist[i]) break; } } // We don't have fastbins so smblks & fsmblks are always 0. Also we don't // have a separate mmap allocator so set hblks & hblkhd to 0. mi->arena = a->stats__bytes_mmaped; mi->ordblks = free_blocks + VG_(free_queue_length); mi->smblks = 0; mi->hblks = 0; mi->hblkhd = 0; mi->usmblks = 0; mi->fsmblks = 0; mi->uordblks = a->stats__bytes_on_loan - VG_(free_queue_volume); mi->fordblks = free_blocks_size + VG_(free_queue_volume); mi->keepcost = 0; // may want some value in here } /*------------------------------------------------------------*/ /*--- Services layered on top of malloc/free. ---*/ /*------------------------------------------------------------*/ void* VG_(arena_calloc) ( ArenaId aid, HChar* cc, SizeT nmemb, SizeT bytes_per_memb ) { SizeT size; UChar* p; size = nmemb * bytes_per_memb; vg_assert(size >= nmemb && size >= bytes_per_memb);// check against overflow p = VG_(arena_malloc) ( aid, cc, size ); VG_(memset)(p, 0, size); return p; } void* VG_(arena_realloc) ( ArenaId aid, HChar* cc, void* ptr, SizeT req_pszB ) { Arena* a; SizeT old_pszB; UChar *p_new; Block* b; ensure_mm_init(aid); a = arenaId_to_ArenaP(aid); vg_assert(req_pszB < MAX_PSZB); if (NULL == ptr) { return VG_(arena_malloc)(aid, cc, req_pszB); } if (req_pszB == 0) { VG_(arena_free)(aid, ptr); return NULL; } b = get_payload_block(a, ptr); vg_assert(blockSane(a, b)); vg_assert(is_inuse_block(b)); old_pszB = get_pszB(a, b); if (req_pszB <= old_pszB) { return ptr; } p_new = VG_(arena_malloc) ( aid, cc, req_pszB ); VG_(memcpy)(p_new, ptr, old_pszB); VG_(arena_free)(aid, ptr); return p_new; } /* Inline just for the wrapper VG_(strdup) below */ __inline__ Char* VG_(arena_strdup) ( ArenaId aid, HChar* cc, const Char* s ) { Int i; Int len; Char* res; if (s == NULL) return NULL; len = VG_(strlen)(s) + 1; res = VG_(arena_malloc) (aid, cc, len); for (i = 0; i < len; i++) res[i] = s[i]; return res; } /*------------------------------------------------------------*/ /*--- Tool-visible functions. ---*/ /*------------------------------------------------------------*/ // All just wrappers to avoid exposing arenas to tools. void* VG_(malloc) ( HChar* cc, SizeT nbytes ) { return VG_(arena_malloc) ( VG_AR_TOOL, cc, nbytes ); } void VG_(free) ( void* ptr ) { VG_(arena_free) ( VG_AR_TOOL, ptr ); } void* VG_(calloc) ( HChar* cc, SizeT nmemb, SizeT bytes_per_memb ) { return VG_(arena_calloc) ( VG_AR_TOOL, cc, nmemb, bytes_per_memb ); } void* VG_(realloc) ( HChar* cc, void* ptr, SizeT size ) { return VG_(arena_realloc) ( VG_AR_TOOL, cc, ptr, size ); } Char* VG_(strdup) ( HChar* cc, const Char* s ) { return VG_(arena_strdup) ( VG_AR_TOOL, cc, s ); } // Useful for querying user blocks. SizeT VG_(malloc_usable_size) ( void* p ) { return VG_(arena_malloc_usable_size)(VG_AR_CLIENT, p); } /*--------------------------------------------------------------------*/ /*--- end ---*/ /*--------------------------------------------------------------------*/
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/valgrind_12641-12642.c
manybugs_data_45
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Jim Winstead <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <stdlib.h> #include <string.h> #include <ctype.h> #include <sys/types.h> #include "php.h" #include "url.h" #include "file.h" #ifdef _OSD_POSIX #ifndef APACHE #error On this EBCDIC platform, PHP is only supported as an Apache module. #else /*APACHE*/ #ifndef CHARSET_EBCDIC #define CHARSET_EBCDIC /* this machine uses EBCDIC, not ASCII! */ #endif #include "ebcdic.h" #endif /*APACHE*/ #endif /*_OSD_POSIX*/ /* {{{ free_url */ PHPAPI void php_url_free(php_url *theurl) { if (theurl->scheme) efree(theurl->scheme); if (theurl->user) efree(theurl->user); if (theurl->pass) efree(theurl->pass); if (theurl->host) efree(theurl->host); if (theurl->path) efree(theurl->path); if (theurl->query) efree(theurl->query); if (theurl->fragment) efree(theurl->fragment); efree(theurl); } /* }}} */ /* {{{ php_replace_controlchars */ PHPAPI char *php_replace_controlchars_ex(char *str, int len) { unsigned char *s = (unsigned char *)str; unsigned char *e = (unsigned char *)str + len; if (!str) { return (NULL); } while (s < e) { if (iscntrl(*s)) { *s='_'; } s++; } return (str); } /* }}} */ PHPAPI char *php_replace_controlchars(char *str) { return php_replace_controlchars_ex(str, strlen(str)); } PHPAPI php_url *php_url_parse(char const *str) { return php_url_parse_ex(str, strlen(str)); } /* {{{ php_url_parse */ PHPAPI php_url *php_url_parse_ex(char const *str, int length) { char port_buf[6]; php_url *ret = ecalloc(1, sizeof(php_url)); char const *s, *e, *p, *pp, *ue; s = str; ue = s + length; /* parse scheme */ if ((e = memchr(s, ':', length)) && (e - s)) { /* validate scheme */ p = s; while (p < e) { /* scheme = 1*[ lowalpha | digit | "+" | "-" | "." ] */ if (!isalpha(*p) && !isdigit(*p) && *p != '+' && *p != '.' && *p != '-') { if (e + 1 < ue) { goto parse_port; } else { goto just_path; } } p++; } if (*(e + 1) == '\0') { /* only scheme is available */ ret->scheme = estrndup(s, (e - s)); php_replace_controlchars_ex(ret->scheme, (e - s)); goto end; } /* * certain schemas like mailto: and zlib: may not have any / after them * this check ensures we support those. */ if (*(e+1) != '/') { /* check if the data we get is a port this allows us to * correctly parse things like a.com:80 */ p = e + 1; while (isdigit(*p)) { p++; } if ((*p == '\0' || *p == '/') && (p - e) < 7) { goto parse_port; } ret->scheme = estrndup(s, (e-s)); php_replace_controlchars_ex(ret->scheme, (e - s)); length -= ++e - s; s = e; goto just_path; } else { ret->scheme = estrndup(s, (e-s)); php_replace_controlchars_ex(ret->scheme, (e - s)); if (*(e+2) == '/') { s = e + 3; if (!strncasecmp("file", ret->scheme, sizeof("file"))) { if (*(e + 3) == '/') { /* support windows drive letters as in: file:///c:/somedir/file.txt */ if (*(e + 5) == ':') { s = e + 4; } goto nohost; } } } else { if (!strncasecmp("file", ret->scheme, sizeof("file"))) { s = e + 1; goto nohost; } else { length -= ++e - s; s = e; goto just_path; } } } } else if (e) { /* no scheme, look for port */ parse_port: p = e + 1; pp = p; while (pp-p < 6 && isdigit(*pp)) { pp++; } if (pp-p < 6 && (*pp == '/' || *pp == '\0')) { memcpy(port_buf, p, (pp-p)); port_buf[pp-p] = '\0'; ret->port = atoi(port_buf); } else { goto just_path; } } else { just_path: ue = s + length; goto nohost; } e = ue; if (!(p = memchr(s, '/', (ue - s)))) { char *query, *fragment; query = memchr(s, '?', (ue - s)); fragment = memchr(s, '#', (ue - s)); if (query && fragment) { if (query > fragment) { p = e = fragment; } else { p = e = query; } } else if (query) { p = e = query; } else if (fragment) { p = e = fragment; } } else { e = p; } /* check for login and password */ if ((p = zend_memrchr(s, '@', (e-s)))) { if ((pp = memchr(s, ':', (p-s)))) { if ((pp-s) > 0) { ret->user = estrndup(s, (pp-s)); php_replace_controlchars_ex(ret->user, (pp - s)); } pp++; if (p-pp > 0) { ret->pass = estrndup(pp, (p-pp)); php_replace_controlchars_ex(ret->pass, (p-pp)); } } else { ret->user = estrndup(s, (p-s)); php_replace_controlchars_ex(ret->user, (p-s)); } s = p + 1; } /* check for port */ if (*s == '[' && *(e-1) == ']') { /* Short circuit portscan, we're dealing with an IPv6 embedded address */ p = s; } else { /* memrchr is a GNU specific extension Emulate for wide compatability */ for(p = e; *p != ':' && p >= s; p--); } if (p >= s && *p == ':') { if (!ret->port) { p++; if (e-p > 5) { /* port cannot be longer then 5 characters */ STR_FREE(ret->scheme); STR_FREE(ret->user); STR_FREE(ret->pass); efree(ret); return NULL; } else if (e - p > 0) { memcpy(port_buf, p, (e-p)); port_buf[e-p] = '\0'; ret->port = atoi(port_buf); } p--; } } else { p = e; } /* check if we have a valid host, if we don't reject the string as url */ if ((p-s) < 1) { STR_FREE(ret->scheme); STR_FREE(ret->user); STR_FREE(ret->pass); efree(ret); return NULL; } ret->host = estrndup(s, (p-s)); php_replace_controlchars_ex(ret->host, (p - s)); if (e == ue) { return ret; } s = e; nohost: if ((p = memchr(s, '?', (ue - s)))) { pp = strchr(s, '#'); if (pp && pp < p) { p = pp; goto label_parse; } if (p - s) { ret->path = estrndup(s, (p-s)); php_replace_controlchars_ex(ret->path, (p - s)); } if (pp) { if (pp - ++p) { ret->query = estrndup(p, (pp-p)); php_replace_controlchars_ex(ret->query, (pp - p)); } p = pp; goto label_parse; } else if (++p - ue) { ret->query = estrndup(p, (ue-p)); php_replace_controlchars_ex(ret->query, (ue - p)); } } else if ((p = memchr(s, '#', (ue - s)))) { if (p - s) { ret->path = estrndup(s, (p-s)); php_replace_controlchars_ex(ret->path, (p - s)); } label_parse: p++; if (ue - p) { ret->fragment = estrndup(p, (ue-p)); php_replace_controlchars_ex(ret->fragment, (ue - p)); } } else { ret->path = estrndup(s, (ue-s)); php_replace_controlchars_ex(ret->path, (ue - s)); } end: return ret; } /* }}} */ /* {{{ proto mixed parse_url(string url, [int url_component]) Parse a URL and return its components */ PHP_FUNCTION(parse_url) { char *str; int str_len; php_url *resource; long key = -1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &str, &str_len, &key) == FAILURE) { return; } resource = php_url_parse_ex(str, str_len); if (resource == NULL) { /* @todo Find a method to determine why php_url_parse_ex() failed */ RETURN_FALSE; } if (key > -1) { switch (key) { case PHP_URL_SCHEME: if (resource->scheme != NULL) RETVAL_STRING(resource->scheme, 1); break; case PHP_URL_HOST: if (resource->host != NULL) RETVAL_STRING(resource->host, 1); break; case PHP_URL_PORT: if (resource->port != 0) RETVAL_LONG(resource->port); break; case PHP_URL_USER: if (resource->user != NULL) RETVAL_STRING(resource->user, 1); break; case PHP_URL_PASS: if (resource->pass != NULL) RETVAL_STRING(resource->pass, 1); break; case PHP_URL_PATH: if (resource->path != NULL) RETVAL_STRING(resource->path, 1); break; case PHP_URL_QUERY: if (resource->query != NULL) RETVAL_STRING(resource->query, 1); break; case PHP_URL_FRAGMENT: if (resource->fragment != NULL) RETVAL_STRING(resource->fragment, 1); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid URL component identifier %ld", key); RETVAL_FALSE; } goto done; } /* allocate an array for return */ array_init(return_value); /* add the various elements to the array */ if (resource->scheme != NULL) add_assoc_string(return_value, "scheme", resource->scheme, 1); if (resource->host != NULL) add_assoc_string(return_value, "host", resource->host, 1); if (resource->port != 0) add_assoc_long(return_value, "port", resource->port); if (resource->user != NULL) add_assoc_string(return_value, "user", resource->user, 1); if (resource->pass != NULL) add_assoc_string(return_value, "pass", resource->pass, 1); if (resource->path != NULL) add_assoc_string(return_value, "path", resource->path, 1); if (resource->query != NULL) add_assoc_string(return_value, "query", resource->query, 1); if (resource->fragment != NULL) add_assoc_string(return_value, "fragment", resource->fragment, 1); done: php_url_free(resource); } /* }}} */ /* {{{ php_htoi */ static int php_htoi(char *s) { int value; int c; c = ((unsigned char *)s)[0]; if (isupper(c)) c = tolower(c); value = (c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10) * 16; c = ((unsigned char *)s)[1]; if (isupper(c)) c = tolower(c); value += c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10; return (value); } /* }}} */ /* rfc1738: ...The characters ";", "/", "?", ":", "@", "=" and "&" are the characters which may be reserved for special meaning within a scheme... ...Thus, only alphanumerics, the special characters "$-_.+!*'(),", and reserved characters used for their reserved purposes may be used unencoded within a URL... For added safety, we only leave -_. unencoded. */ static unsigned char hexchars[] = "0123456789ABCDEF"; /* {{{ php_url_encode */ PHPAPI char *php_url_encode(char const *s, int len, int *new_length) { register unsigned char c; unsigned char *to, *start; unsigned char const *from, *end; from = (unsigned char *)s; end = (unsigned char *)s + len; start = to = (unsigned char *) safe_emalloc(3, len, 1); while (from < end) { c = *from++; if (c == ' ') { *to++ = '+'; #ifndef CHARSET_EBCDIC } else if ((c < '0' && c != '-' && c != '.') || (c < 'A' && c > '9') || (c > 'Z' && c < 'a' && c != '_') || (c > 'z')) { to[0] = '%'; to[1] = hexchars[c >> 4]; to[2] = hexchars[c & 15]; to += 3; #else /*CHARSET_EBCDIC*/ } else if (!isalnum(c) && strchr("_-.", c) == NULL) { /* Allow only alphanumeric chars and '_', '-', '.'; escape the rest */ to[0] = '%'; to[1] = hexchars[os_toascii[c] >> 4]; to[2] = hexchars[os_toascii[c] & 15]; to += 3; #endif /*CHARSET_EBCDIC*/ } else { *to++ = c; } } *to = 0; if (new_length) { *new_length = to - start; } return (char *) start; } /* }}} */ /* {{{ proto string urlencode(string str) URL-encodes string */ PHP_FUNCTION(urlencode) { char *in_str, *out_str; int in_str_len, out_str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str, &in_str_len) == FAILURE) { return; } out_str = php_url_encode(in_str, in_str_len, &out_str_len); RETURN_STRINGL(out_str, out_str_len, 0); } /* }}} */ /* {{{ proto string urldecode(string str) Decodes URL-encoded string */ PHP_FUNCTION(urldecode) { char *in_str, *out_str; int in_str_len, out_str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str, &in_str_len) == FAILURE) { return; } out_str = estrndup(in_str, in_str_len); out_str_len = php_url_decode(out_str, in_str_len); RETURN_STRINGL(out_str, out_str_len, 0); } /* }}} */ /* {{{ php_url_decode */ PHPAPI int php_url_decode(char *str, int len) { char *dest = str; char *data = str; while (len--) { if (*data == '+') { *dest = ' '; } else if (*data == '%' && len >= 2 && isxdigit((int) *(data + 1)) && isxdigit((int) *(data + 2))) { #ifndef CHARSET_EBCDIC *dest = (char) php_htoi(data + 1); #else *dest = os_toebcdic[(char) php_htoi(data + 1)]; #endif data += 2; len -= 2; } else { *dest = *data; } data++; dest++; } *dest = '\0'; return dest - str; } /* }}} */ /* {{{ php_raw_url_encode */ PHPAPI char *php_raw_url_encode(char const *s, int len, int *new_length) { register int x, y; unsigned char *str; str = (unsigned char *) safe_emalloc(3, len, 1); for (x = 0, y = 0; len--; x++, y++) { str[y] = (unsigned char) s[x]; #ifndef CHARSET_EBCDIC if ((str[y] < '0' && str[y] != '-' && str[y] != '.') || (str[y] < 'A' && str[y] > '9') || (str[y] > 'Z' && str[y] < 'a' && str[y] != '_') || (str[y] > 'z' && str[y] != '~')) { str[y++] = '%'; str[y++] = hexchars[(unsigned char) s[x] >> 4]; str[y] = hexchars[(unsigned char) s[x] & 15]; #else /*CHARSET_EBCDIC*/ if (!isalnum(str[y]) && strchr("_-.~", str[y]) != NULL) { str[y++] = '%'; str[y++] = hexchars[os_toascii[(unsigned char) s[x]] >> 4]; str[y] = hexchars[os_toascii[(unsigned char) s[x]] & 15]; #endif /*CHARSET_EBCDIC*/ } } str[y] = '\0'; if (new_length) { *new_length = y; } return ((char *) str); } /* }}} */ /* {{{ proto string rawurlencode(string str) URL-encodes string */ PHP_FUNCTION(rawurlencode) { char *in_str, *out_str; int in_str_len, out_str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str, &in_str_len) == FAILURE) { return; } out_str = php_raw_url_encode(in_str, in_str_len, &out_str_len); RETURN_STRINGL(out_str, out_str_len, 0); } /* }}} */ /* {{{ proto string rawurldecode(string str) Decodes URL-encodes string */ PHP_FUNCTION(rawurldecode) { char *in_str, *out_str; int in_str_len, out_str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str, &in_str_len) == FAILURE) { return; } out_str = estrndup(in_str, in_str_len); out_str_len = php_raw_url_decode(out_str, in_str_len); RETURN_STRINGL(out_str, out_str_len, 0); } /* }}} */ /* {{{ php_raw_url_decode */ PHPAPI int php_raw_url_decode(char *str, int len) { char *dest = str; char *data = str; while (len--) { if (*data == '%' && len >= 2 && isxdigit((int) *(data + 1)) && isxdigit((int) *(data + 2))) { #ifndef CHARSET_EBCDIC *dest = (char) php_htoi(data + 1); #else *dest = os_toebcdic[(char) php_htoi(data + 1)]; #endif data += 2; len -= 2; } else { *dest = *data; } data++; dest++; } *dest = '\0'; return dest - str; } /* }}} */ /* {{{ proto array get_headers(string url[, int format]) fetches all the headers sent by the server in response to a HTTP request */ PHP_FUNCTION(get_headers) { char *url; int url_len; php_stream_context *context; php_stream *stream; zval **prev_val, **hdr = NULL, **h; HashPosition pos; HashTable *hashT; long format = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &url, &url_len, &format) == FAILURE) { return; } context = FG(default_context) ? FG(default_context) : (FG(default_context) = php_stream_context_alloc(TSRMLS_C)); if (!(stream = php_stream_open_wrapper_ex(url, "r", REPORT_ERRORS | STREAM_USE_URL | STREAM_ONLY_GET_HEADERS, NULL, context))) { RETURN_FALSE; } if (!stream->wrapperdata || Z_TYPE_P(stream->wrapperdata) != IS_ARRAY) { php_stream_close(stream); RETURN_FALSE; } array_init(return_value); /* check for curl-wrappers that provide headers via a special "headers" element */ if (zend_hash_find(HASH_OF(stream->wrapperdata), "headers", sizeof("headers"), (void **)&h) != FAILURE && Z_TYPE_PP(h) == IS_ARRAY) { /* curl-wrappers don't load data until the 1st read */ if (!Z_ARRVAL_PP(h)->nNumOfElements) { php_stream_getc(stream); } zend_hash_find(HASH_OF(stream->wrapperdata), "headers", sizeof("headers"), (void **)&h); hashT = Z_ARRVAL_PP(h); } else { hashT = HASH_OF(stream->wrapperdata); } zend_hash_internal_pointer_reset_ex(hashT, &pos); while (zend_hash_get_current_data_ex(hashT, (void**)&hdr, &pos) != FAILURE) { if (!hdr || Z_TYPE_PP(hdr) != IS_STRING) { zend_hash_move_forward_ex(hashT, &pos); continue; } if (!format) { no_name_header: add_next_index_stringl(return_value, Z_STRVAL_PP(hdr), Z_STRLEN_PP(hdr), 1); } else { char c; char *s, *p; if ((p = strchr(Z_STRVAL_PP(hdr), ':'))) { c = *p; *p = '\0'; s = p + 1; while (isspace((int)*(unsigned char *)s)) { s++; } if (zend_hash_find(HASH_OF(return_value), Z_STRVAL_PP(hdr), (p - Z_STRVAL_PP(hdr) + 1), (void **) &prev_val) == FAILURE) { add_assoc_stringl_ex(return_value, Z_STRVAL_PP(hdr), (p - Z_STRVAL_PP(hdr) + 1), s, (Z_STRLEN_PP(hdr) - (s - Z_STRVAL_PP(hdr))), 1); } else { /* some headers may occur more then once, therefor we need to remake the string into an array */ convert_to_array(*prev_val); add_next_index_stringl(*prev_val, s, (Z_STRLEN_PP(hdr) - (s - Z_STRVAL_PP(hdr))), 1); } *p = c; } else { goto no_name_header; } } zend_hash_move_forward_ex(hashT, &pos); } php_stream_close(stream); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Jim Winstead <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <stdlib.h> #include <string.h> #include <ctype.h> #include <sys/types.h> #include "php.h" #include "url.h" #include "file.h" #ifdef _OSD_POSIX #ifndef APACHE #error On this EBCDIC platform, PHP is only supported as an Apache module. #else /*APACHE*/ #ifndef CHARSET_EBCDIC #define CHARSET_EBCDIC /* this machine uses EBCDIC, not ASCII! */ #endif #include "ebcdic.h" #endif /*APACHE*/ #endif /*_OSD_POSIX*/ /* {{{ free_url */ PHPAPI void php_url_free(php_url *theurl) { if (theurl->scheme) efree(theurl->scheme); if (theurl->user) efree(theurl->user); if (theurl->pass) efree(theurl->pass); if (theurl->host) efree(theurl->host); if (theurl->path) efree(theurl->path); if (theurl->query) efree(theurl->query); if (theurl->fragment) efree(theurl->fragment); efree(theurl); } /* }}} */ /* {{{ php_replace_controlchars */ PHPAPI char *php_replace_controlchars_ex(char *str, int len) { unsigned char *s = (unsigned char *)str; unsigned char *e = (unsigned char *)str + len; if (!str) { return (NULL); } while (s < e) { if (iscntrl(*s)) { *s='_'; } s++; } return (str); } /* }}} */ PHPAPI char *php_replace_controlchars(char *str) { return php_replace_controlchars_ex(str, strlen(str)); } PHPAPI php_url *php_url_parse(char const *str) { return php_url_parse_ex(str, strlen(str)); } /* {{{ php_url_parse */ PHPAPI php_url *php_url_parse_ex(char const *str, int length) { char port_buf[6]; php_url *ret = ecalloc(1, sizeof(php_url)); char const *s, *e, *p, *pp, *ue; s = str; ue = s + length; /* parse scheme */ if ((e = memchr(s, ':', length)) && (e - s)) { /* validate scheme */ p = s; while (p < e) { /* scheme = 1*[ lowalpha | digit | "+" | "-" | "." ] */ if (!isalpha(*p) && !isdigit(*p) && *p != '+' && *p != '.' && *p != '-') { if (e + 1 < ue) { goto parse_port; } else { goto just_path; } } p++; } if (*(e + 1) == '\0') { /* only scheme is available */ ret->scheme = estrndup(s, (e - s)); php_replace_controlchars_ex(ret->scheme, (e - s)); goto end; } /* * certain schemas like mailto: and zlib: may not have any / after them * this check ensures we support those. */ if (*(e+1) != '/') { /* check if the data we get is a port this allows us to * correctly parse things like a.com:80 */ p = e + 1; while (isdigit(*p)) { p++; } if ((*p == '\0' || *p == '/') && (p - e) < 7) { goto parse_port; } ret->scheme = estrndup(s, (e-s)); php_replace_controlchars_ex(ret->scheme, (e - s)); length -= ++e - s; s = e; goto just_path; } else { ret->scheme = estrndup(s, (e-s)); php_replace_controlchars_ex(ret->scheme, (e - s)); if (*(e+2) == '/') { s = e + 3; if (!strncasecmp("file", ret->scheme, sizeof("file"))) { if (*(e + 3) == '/') { /* support windows drive letters as in: file:///c:/somedir/file.txt */ if (*(e + 5) == ':') { s = e + 4; } goto nohost; } } } else { if (!strncasecmp("file", ret->scheme, sizeof("file"))) { s = e + 1; goto nohost; } else { length -= ++e - s; s = e; goto just_path; } } } } else if (e) { /* no scheme, look for port */ parse_port: p = e + 1; pp = p; while (pp-p < 6 && isdigit(*pp)) { pp++; } if (pp-p < 6 && (*pp == '/' || *pp == '\0')) { memcpy(port_buf, p, (pp-p)); port_buf[pp-p] = '\0'; ret->port = atoi(port_buf); if (!ret->port && (pp - p) > 0) { STR_FREE(ret->scheme); efree(ret); return NULL; } } else { goto just_path; } } else { just_path: ue = s + length; goto nohost; } e = ue; if (!(p = memchr(s, '/', (ue - s)))) { char *query, *fragment; query = memchr(s, '?', (ue - s)); fragment = memchr(s, '#', (ue - s)); if (query && fragment) { if (query > fragment) { p = e = fragment; } else { p = e = query; } } else if (query) { p = e = query; } else if (fragment) { p = e = fragment; } } else { e = p; } /* check for login and password */ if ((p = zend_memrchr(s, '@', (e-s)))) { if ((pp = memchr(s, ':', (p-s)))) { if ((pp-s) > 0) { ret->user = estrndup(s, (pp-s)); php_replace_controlchars_ex(ret->user, (pp - s)); } pp++; if (p-pp > 0) { ret->pass = estrndup(pp, (p-pp)); php_replace_controlchars_ex(ret->pass, (p-pp)); } } else { ret->user = estrndup(s, (p-s)); php_replace_controlchars_ex(ret->user, (p-s)); } s = p + 1; } /* check for port */ if (*s == '[' && *(e-1) == ']') { /* Short circuit portscan, we're dealing with an IPv6 embedded address */ p = s; } else { /* memrchr is a GNU specific extension Emulate for wide compatability */ for(p = e; *p != ':' && p >= s; p--); } if (p >= s && *p == ':') { if (!ret->port) { p++; if (e-p > 5) { /* port cannot be longer then 5 characters */ STR_FREE(ret->scheme); STR_FREE(ret->user); STR_FREE(ret->pass); efree(ret); return NULL; } else if (e - p > 0) { memcpy(port_buf, p, (e-p)); port_buf[e-p] = '\0'; ret->port = atoi(port_buf); if (!ret->port && (e - p)) { STR_FREE(ret->scheme); STR_FREE(ret->user); STR_FREE(ret->pass); efree(ret); return NULL; } } p--; } } else { p = e; } /* check if we have a valid host, if we don't reject the string as url */ if ((p-s) < 1) { STR_FREE(ret->scheme); STR_FREE(ret->user); STR_FREE(ret->pass); efree(ret); return NULL; } ret->host = estrndup(s, (p-s)); php_replace_controlchars_ex(ret->host, (p - s)); if (e == ue) { return ret; } s = e; nohost: if ((p = memchr(s, '?', (ue - s)))) { pp = strchr(s, '#'); if (pp && pp < p) { p = pp; goto label_parse; } if (p - s) { ret->path = estrndup(s, (p-s)); php_replace_controlchars_ex(ret->path, (p - s)); } if (pp) { if (pp - ++p) { ret->query = estrndup(p, (pp-p)); php_replace_controlchars_ex(ret->query, (pp - p)); } p = pp; goto label_parse; } else if (++p - ue) { ret->query = estrndup(p, (ue-p)); php_replace_controlchars_ex(ret->query, (ue - p)); } } else if ((p = memchr(s, '#', (ue - s)))) { if (p - s) { ret->path = estrndup(s, (p-s)); php_replace_controlchars_ex(ret->path, (p - s)); } label_parse: p++; if (ue - p) { ret->fragment = estrndup(p, (ue-p)); php_replace_controlchars_ex(ret->fragment, (ue - p)); } } else { ret->path = estrndup(s, (ue-s)); php_replace_controlchars_ex(ret->path, (ue - s)); } end: return ret; } /* }}} */ /* {{{ proto mixed parse_url(string url, [int url_component]) Parse a URL and return its components */ PHP_FUNCTION(parse_url) { char *str; int str_len; php_url *resource; long key = -1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &str, &str_len, &key) == FAILURE) { return; } resource = php_url_parse_ex(str, str_len); if (resource == NULL) { /* @todo Find a method to determine why php_url_parse_ex() failed */ RETURN_FALSE; } if (key > -1) { switch (key) { case PHP_URL_SCHEME: if (resource->scheme != NULL) RETVAL_STRING(resource->scheme, 1); break; case PHP_URL_HOST: if (resource->host != NULL) RETVAL_STRING(resource->host, 1); break; case PHP_URL_PORT: if (resource->port != 0) RETVAL_LONG(resource->port); break; case PHP_URL_USER: if (resource->user != NULL) RETVAL_STRING(resource->user, 1); break; case PHP_URL_PASS: if (resource->pass != NULL) RETVAL_STRING(resource->pass, 1); break; case PHP_URL_PATH: if (resource->path != NULL) RETVAL_STRING(resource->path, 1); break; case PHP_URL_QUERY: if (resource->query != NULL) RETVAL_STRING(resource->query, 1); break; case PHP_URL_FRAGMENT: if (resource->fragment != NULL) RETVAL_STRING(resource->fragment, 1); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid URL component identifier %ld", key); RETVAL_FALSE; } goto done; } /* allocate an array for return */ array_init(return_value); /* add the various elements to the array */ if (resource->scheme != NULL) add_assoc_string(return_value, "scheme", resource->scheme, 1); if (resource->host != NULL) add_assoc_string(return_value, "host", resource->host, 1); if (resource->port != 0) add_assoc_long(return_value, "port", resource->port); if (resource->user != NULL) add_assoc_string(return_value, "user", resource->user, 1); if (resource->pass != NULL) add_assoc_string(return_value, "pass", resource->pass, 1); if (resource->path != NULL) add_assoc_string(return_value, "path", resource->path, 1); if (resource->query != NULL) add_assoc_string(return_value, "query", resource->query, 1); if (resource->fragment != NULL) add_assoc_string(return_value, "fragment", resource->fragment, 1); done: php_url_free(resource); } /* }}} */ /* {{{ php_htoi */ static int php_htoi(char *s) { int value; int c; c = ((unsigned char *)s)[0]; if (isupper(c)) c = tolower(c); value = (c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10) * 16; c = ((unsigned char *)s)[1]; if (isupper(c)) c = tolower(c); value += c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10; return (value); } /* }}} */ /* rfc1738: ...The characters ";", "/", "?", ":", "@", "=" and "&" are the characters which may be reserved for special meaning within a scheme... ...Thus, only alphanumerics, the special characters "$-_.+!*'(),", and reserved characters used for their reserved purposes may be used unencoded within a URL... For added safety, we only leave -_. unencoded. */ static unsigned char hexchars[] = "0123456789ABCDEF"; /* {{{ php_url_encode */ PHPAPI char *php_url_encode(char const *s, int len, int *new_length) { register unsigned char c; unsigned char *to, *start; unsigned char const *from, *end; from = (unsigned char *)s; end = (unsigned char *)s + len; start = to = (unsigned char *) safe_emalloc(3, len, 1); while (from < end) { c = *from++; if (c == ' ') { *to++ = '+'; #ifndef CHARSET_EBCDIC } else if ((c < '0' && c != '-' && c != '.') || (c < 'A' && c > '9') || (c > 'Z' && c < 'a' && c != '_') || (c > 'z')) { to[0] = '%'; to[1] = hexchars[c >> 4]; to[2] = hexchars[c & 15]; to += 3; #else /*CHARSET_EBCDIC*/ } else if (!isalnum(c) && strchr("_-.", c) == NULL) { /* Allow only alphanumeric chars and '_', '-', '.'; escape the rest */ to[0] = '%'; to[1] = hexchars[os_toascii[c] >> 4]; to[2] = hexchars[os_toascii[c] & 15]; to += 3; #endif /*CHARSET_EBCDIC*/ } else { *to++ = c; } } *to = 0; if (new_length) { *new_length = to - start; } return (char *) start; } /* }}} */ /* {{{ proto string urlencode(string str) URL-encodes string */ PHP_FUNCTION(urlencode) { char *in_str, *out_str; int in_str_len, out_str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str, &in_str_len) == FAILURE) { return; } out_str = php_url_encode(in_str, in_str_len, &out_str_len); RETURN_STRINGL(out_str, out_str_len, 0); } /* }}} */ /* {{{ proto string urldecode(string str) Decodes URL-encoded string */ PHP_FUNCTION(urldecode) { char *in_str, *out_str; int in_str_len, out_str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str, &in_str_len) == FAILURE) { return; } out_str = estrndup(in_str, in_str_len); out_str_len = php_url_decode(out_str, in_str_len); RETURN_STRINGL(out_str, out_str_len, 0); } /* }}} */ /* {{{ php_url_decode */ PHPAPI int php_url_decode(char *str, int len) { char *dest = str; char *data = str; while (len--) { if (*data == '+') { *dest = ' '; } else if (*data == '%' && len >= 2 && isxdigit((int) *(data + 1)) && isxdigit((int) *(data + 2))) { #ifndef CHARSET_EBCDIC *dest = (char) php_htoi(data + 1); #else *dest = os_toebcdic[(char) php_htoi(data + 1)]; #endif data += 2; len -= 2; } else { *dest = *data; } data++; dest++; } *dest = '\0'; return dest - str; } /* }}} */ /* {{{ php_raw_url_encode */ PHPAPI char *php_raw_url_encode(char const *s, int len, int *new_length) { register int x, y; unsigned char *str; str = (unsigned char *) safe_emalloc(3, len, 1); for (x = 0, y = 0; len--; x++, y++) { str[y] = (unsigned char) s[x]; #ifndef CHARSET_EBCDIC if ((str[y] < '0' && str[y] != '-' && str[y] != '.') || (str[y] < 'A' && str[y] > '9') || (str[y] > 'Z' && str[y] < 'a' && str[y] != '_') || (str[y] > 'z' && str[y] != '~')) { str[y++] = '%'; str[y++] = hexchars[(unsigned char) s[x] >> 4]; str[y] = hexchars[(unsigned char) s[x] & 15]; #else /*CHARSET_EBCDIC*/ if (!isalnum(str[y]) && strchr("_-.~", str[y]) != NULL) { str[y++] = '%'; str[y++] = hexchars[os_toascii[(unsigned char) s[x]] >> 4]; str[y] = hexchars[os_toascii[(unsigned char) s[x]] & 15]; #endif /*CHARSET_EBCDIC*/ } } str[y] = '\0'; if (new_length) { *new_length = y; } return ((char *) str); } /* }}} */ /* {{{ proto string rawurlencode(string str) URL-encodes string */ PHP_FUNCTION(rawurlencode) { char *in_str, *out_str; int in_str_len, out_str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str, &in_str_len) == FAILURE) { return; } out_str = php_raw_url_encode(in_str, in_str_len, &out_str_len); RETURN_STRINGL(out_str, out_str_len, 0); } /* }}} */ /* {{{ proto string rawurldecode(string str) Decodes URL-encodes string */ PHP_FUNCTION(rawurldecode) { char *in_str, *out_str; int in_str_len, out_str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str, &in_str_len) == FAILURE) { return; } out_str = estrndup(in_str, in_str_len); out_str_len = php_raw_url_decode(out_str, in_str_len); RETURN_STRINGL(out_str, out_str_len, 0); } /* }}} */ /* {{{ php_raw_url_decode */ PHPAPI int php_raw_url_decode(char *str, int len) { char *dest = str; char *data = str; while (len--) { if (*data == '%' && len >= 2 && isxdigit((int) *(data + 1)) && isxdigit((int) *(data + 2))) { #ifndef CHARSET_EBCDIC *dest = (char) php_htoi(data + 1); #else *dest = os_toebcdic[(char) php_htoi(data + 1)]; #endif data += 2; len -= 2; } else { *dest = *data; } data++; dest++; } *dest = '\0'; return dest - str; } /* }}} */ /* {{{ proto array get_headers(string url[, int format]) fetches all the headers sent by the server in response to a HTTP request */ PHP_FUNCTION(get_headers) { char *url; int url_len; php_stream_context *context; php_stream *stream; zval **prev_val, **hdr = NULL, **h; HashPosition pos; HashTable *hashT; long format = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &url, &url_len, &format) == FAILURE) { return; } context = FG(default_context) ? FG(default_context) : (FG(default_context) = php_stream_context_alloc(TSRMLS_C)); if (!(stream = php_stream_open_wrapper_ex(url, "r", REPORT_ERRORS | STREAM_USE_URL | STREAM_ONLY_GET_HEADERS, NULL, context))) { RETURN_FALSE; } if (!stream->wrapperdata || Z_TYPE_P(stream->wrapperdata) != IS_ARRAY) { php_stream_close(stream); RETURN_FALSE; } array_init(return_value); /* check for curl-wrappers that provide headers via a special "headers" element */ if (zend_hash_find(HASH_OF(stream->wrapperdata), "headers", sizeof("headers"), (void **)&h) != FAILURE && Z_TYPE_PP(h) == IS_ARRAY) { /* curl-wrappers don't load data until the 1st read */ if (!Z_ARRVAL_PP(h)->nNumOfElements) { php_stream_getc(stream); } zend_hash_find(HASH_OF(stream->wrapperdata), "headers", sizeof("headers"), (void **)&h); hashT = Z_ARRVAL_PP(h); } else { hashT = HASH_OF(stream->wrapperdata); } zend_hash_internal_pointer_reset_ex(hashT, &pos); while (zend_hash_get_current_data_ex(hashT, (void**)&hdr, &pos) != FAILURE) { if (!hdr || Z_TYPE_PP(hdr) != IS_STRING) { zend_hash_move_forward_ex(hashT, &pos); continue; } if (!format) { no_name_header: add_next_index_stringl(return_value, Z_STRVAL_PP(hdr), Z_STRLEN_PP(hdr), 1); } else { char c; char *s, *p; if ((p = strchr(Z_STRVAL_PP(hdr), ':'))) { c = *p; *p = '\0'; s = p + 1; while (isspace((int)*(unsigned char *)s)) { s++; } if (zend_hash_find(HASH_OF(return_value), Z_STRVAL_PP(hdr), (p - Z_STRVAL_PP(hdr) + 1), (void **) &prev_val) == FAILURE) { add_assoc_stringl_ex(return_value, Z_STRVAL_PP(hdr), (p - Z_STRVAL_PP(hdr) + 1), s, (Z_STRLEN_PP(hdr) - (s - Z_STRVAL_PP(hdr))), 1); } else { /* some headers may occur more then once, therefor we need to remake the string into an array */ convert_to_array(*prev_val); add_next_index_stringl(*prev_val, s, (Z_STRLEN_PP(hdr) - (s - Z_STRVAL_PP(hdr))), 1); } *p = c; } else { goto no_name_header; } } zend_hash_move_forward_ex(hashT, &pos); } php_stream_close(stream); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-02-04-793cfe1376-109b8e99e0.c
manybugs_data_46
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2012 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "php.h" #include "php_streams.h" #include "php_main.h" #include "php_globals.h" #include "php_ini.h" #include "php_standard.h" #include "php_math.h" #include "php_http.h" #include "php_incomplete_class.h" #include "php_getopt.h" #include "ext/standard/info.h" #include "ext/session/php_session.h" #include "zend_operators.h" #include "ext/standard/php_dns.h" #include "ext/standard/php_uuencode.h" #ifdef PHP_WIN32 #include "win32/php_win32_globals.h" #include "win32/time.h" #endif typedef struct yy_buffer_state *YY_BUFFER_STATE; #include "zend.h" #include "zend_ini_scanner.h" #include "zend_language_scanner.h" #include <zend_language_parser.h> #include <stdarg.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <stdio.h> #ifndef PHP_WIN32 #include <sys/types.h> #include <sys/stat.h> #endif #ifdef NETWARE #include <netinet/in.h> #endif #ifndef PHP_WIN32 # include <netdb.h> #else #include "win32/inet.h" #endif #if HAVE_ARPA_INET_H # include <arpa/inet.h> #endif #if HAVE_UNISTD_H # include <unistd.h> #endif #if HAVE_STRING_H # include <string.h> #else # include <strings.h> #endif #if HAVE_LOCALE_H # include <locale.h> #endif #if HAVE_SYS_MMAN_H # include <sys/mman.h> #endif #if HAVE_SYS_LOADAVG_H # include <sys/loadavg.h> #endif #ifdef PHP_WIN32 # include "win32/unistd.h" #endif #ifndef INADDR_NONE #define INADDR_NONE ((unsigned long int) -1) #endif #include "zend_globals.h" #include "php_globals.h" #include "SAPI.h" #include "php_ticks.h" #ifdef ZTS PHPAPI int basic_globals_id; #else PHPAPI php_basic_globals basic_globals; #endif #include "php_fopen_wrappers.h" #include "streamsfuncs.h" static zend_class_entry *incomplete_class_entry = NULL; typedef struct _user_tick_function_entry { zval **arguments; int arg_count; int calling; } user_tick_function_entry; /* some prototypes for local functions */ static void user_shutdown_function_dtor(php_shutdown_function_entry *shutdown_function_entry); static void user_tick_function_dtor(user_tick_function_entry *tick_function_entry); static HashTable basic_submodules; #undef sprintf /* {{{ arginfo */ /* {{{ main/main.c */ ZEND_BEGIN_ARG_INFO(arginfo_set_time_limit, 0) ZEND_ARG_INFO(0, seconds) ZEND_END_ARG_INFO() /* }}} */ /* {{{ main/sapi.c */ ZEND_BEGIN_ARG_INFO(arginfo_header_register_callback, 0) ZEND_ARG_INFO(0, callback) ZEND_END_ARG_INFO() /* }}} */ /* {{{ main/output.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_ob_start, 0, 0, 0) ZEND_ARG_INFO(0, user_function) ZEND_ARG_INFO(0, chunk_size) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ob_flush, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ob_clean, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ob_end_flush, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ob_end_clean, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ob_get_flush, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ob_get_clean, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ob_get_contents, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ob_get_level, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ob_get_length, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ob_list_handlers, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ob_get_status, 0, 0, 0) ZEND_ARG_INFO(0, full_status) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ob_implicit_flush, 0, 0, 0) ZEND_ARG_INFO(0, flag) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_output_reset_rewrite_vars, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_output_add_rewrite_var, 0) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() /* }}} */ /* {{{ main/streams/userspace.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_wrapper_register, 0, 0, 2) ZEND_ARG_INFO(0, protocol) ZEND_ARG_INFO(0, classname) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_wrapper_unregister, 0) ZEND_ARG_INFO(0, protocol) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_wrapper_restore, 0) ZEND_ARG_INFO(0, protocol) ZEND_END_ARG_INFO() /* }}} */ /* {{{ array.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_krsort, 0, 0, 1) ZEND_ARG_INFO(1, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_ARG_INFO(0, sort_flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ksort, 0, 0, 1) ZEND_ARG_INFO(1, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_ARG_INFO(0, sort_flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_count, 0, 0, 1) ZEND_ARG_INFO(0, var) ZEND_ARG_INFO(0, mode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_natsort, 0) ZEND_ARG_INFO(1, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_natcasesort, 0) ZEND_ARG_INFO(1, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_asort, 0, 0, 1) ZEND_ARG_INFO(1, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_ARG_INFO(0, sort_flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_arsort, 0, 0, 1) ZEND_ARG_INFO(1, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_ARG_INFO(0, sort_flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_sort, 0, 0, 1) ZEND_ARG_INFO(1, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_ARG_INFO(0, sort_flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_rsort, 0, 0, 1) ZEND_ARG_INFO(1, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_ARG_INFO(0, sort_flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_usort, 0) ZEND_ARG_INFO(1, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_ARG_INFO(0, cmp_function) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_uasort, 0) ZEND_ARG_INFO(1, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_ARG_INFO(0, cmp_function) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_uksort, 0) ZEND_ARG_INFO(1, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_ARG_INFO(0, cmp_function) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_end, 0) ZEND_ARG_INFO(1, arg) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_prev, 0) ZEND_ARG_INFO(1, arg) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_next, 0) ZEND_ARG_INFO(1, arg) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reset, 0) ZEND_ARG_INFO(1, arg) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_current, ZEND_SEND_PREFER_REF) ZEND_ARG_INFO(ZEND_SEND_PREFER_REF, arg) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_key, ZEND_SEND_PREFER_REF) ZEND_ARG_INFO(ZEND_SEND_PREFER_REF, arg) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_min, 0, 0, 1) ZEND_ARG_INFO(0, arg1) ZEND_ARG_INFO(0, arg2) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_max, 0, 0, 1) ZEND_ARG_INFO(0, arg1) ZEND_ARG_INFO(0, arg2) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_walk, 0, 0, 2) ZEND_ARG_INFO(1, input) /* ARRAY_INFO(1, arg, 0) */ ZEND_ARG_INFO(0, funcname) ZEND_ARG_INFO(0, userdata) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_walk_recursive, 0, 0, 2) ZEND_ARG_INFO(1, input) /* ARRAY_INFO(1, arg, 0) */ ZEND_ARG_INFO(0, funcname) ZEND_ARG_INFO(0, userdata) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_in_array, 0, 0, 2) ZEND_ARG_INFO(0, needle) ZEND_ARG_INFO(0, haystack) /* ARRAY_INFO(0, haystack, 0) */ ZEND_ARG_INFO(0, strict) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_search, 0, 0, 2) ZEND_ARG_INFO(0, needle) ZEND_ARG_INFO(0, haystack) /* ARRAY_INFO(0, haystack, 0) */ ZEND_ARG_INFO(0, strict) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_extract, 0, 0, 1) ZEND_ARG_INFO(ZEND_SEND_PREFER_REF, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, extract_type) ZEND_ARG_INFO(0, prefix) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_compact, 0, 0, 1) ZEND_ARG_INFO(0, var_names) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_fill, 0) ZEND_ARG_INFO(0, start_key) ZEND_ARG_INFO(0, num) ZEND_ARG_INFO(0, val) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_fill_keys, 0) ZEND_ARG_INFO(0, keys) /* ARRAY_INFO(0, keys, 0) */ ZEND_ARG_INFO(0, val) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_range, 0, 0, 2) ZEND_ARG_INFO(0, low) ZEND_ARG_INFO(0, high) ZEND_ARG_INFO(0, step) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_shuffle, 0) ZEND_ARG_INFO(1, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_push, 0, 0, 2) ZEND_ARG_INFO(1, stack) /* ARRAY_INFO(1, stack, 0) */ ZEND_ARG_INFO(0, var) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_pop, 0) ZEND_ARG_INFO(1, stack) /* ARRAY_INFO(1, stack, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_shift, 0) ZEND_ARG_INFO(1, stack) /* ARRAY_INFO(1, stack, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_unshift, 0, 0, 2) ZEND_ARG_INFO(1, stack) /* ARRAY_INFO(1, stack, 0) */ ZEND_ARG_INFO(0, var) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_splice, 0, 0, 2) ZEND_ARG_INFO(1, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_ARG_INFO(0, offset) ZEND_ARG_INFO(0, length) ZEND_ARG_INFO(0, replacement) /* ARRAY_INFO(0, arg, 1) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_slice, 0, 0, 2) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_ARG_INFO(0, offset) ZEND_ARG_INFO(0, length) ZEND_ARG_INFO(0, preserve_keys) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_merge, 0, 0, 2) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, ...) /* ARRAY_INFO(0, ..., 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_merge_recursive, 0, 0, 2) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, ...) /* ARRAY_INFO(0, arg, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_replace, 0, 0, 2) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, ...) /* ARRAY_INFO(0, ..., 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_replace_recursive, 0, 0, 2) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, ...) /* ARRAY_INFO(0, arg, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_keys, 0, 0, 1) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, search_value) ZEND_ARG_INFO(0, strict) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_values, 0) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_count_values, 0) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_reverse, 0, 0, 1) ZEND_ARG_INFO(0, input) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, preserve_keys) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_pad, 0) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, pad_size) ZEND_ARG_INFO(0, pad_value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_flip, 0) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_change_key_case, 0, 0, 1) ZEND_ARG_INFO(0, input) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, case) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_unique, 0) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_intersect_key, 0, 0, 2) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, ...) /* ARRAY_INFO(0, ..., 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_intersect_ukey, 0) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, callback_key_compare_func) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_intersect, 0, 0, 2) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, ...) /* ARRAY_INFO(0, ..., 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_uintersect, 0) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, callback_data_compare_func) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_intersect_assoc, 0, 0, 2) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, ...) /* ARRAY_INFO(0, ..., 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_uintersect_assoc, 0) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, callback_data_compare_func) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_intersect_uassoc, 0) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, callback_key_compare_func) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_uintersect_uassoc, 0) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, callback_data_compare_func) ZEND_ARG_INFO(0, callback_key_compare_func) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_diff_key, 0, 0, 2) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, ...) /* ARRAY_INFO(0, ..., 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_diff_ukey, 0) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, callback_key_comp_func) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_diff, 0, 0, 2) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, ...) /* ARRAY_INFO(0, ..., 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_udiff, 0) ZEND_ARG_INFO(0, arr1) ZEND_ARG_INFO(0, arr2) ZEND_ARG_INFO(0, callback_data_comp_func) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_diff_assoc, 0, 0, 2) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, ...) /* ARRAY_INFO(0, ..., 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_diff_uassoc, 0) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, callback_data_comp_func) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_udiff_assoc, 0) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, callback_key_comp_func) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_udiff_uassoc, 0) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, callback_data_comp_func) ZEND_ARG_INFO(0, callback_key_comp_func) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_multisort, ZEND_SEND_PREFER_REF, 0, 1) ZEND_ARG_INFO(ZEND_SEND_PREFER_REF, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(ZEND_SEND_PREFER_REF, SORT_ASC_or_SORT_DESC) ZEND_ARG_INFO(ZEND_SEND_PREFER_REF, SORT_REGULAR_or_SORT_NUMERIC_or_SORT_STRING) ZEND_ARG_INFO(ZEND_SEND_PREFER_REF, arr2) ZEND_ARG_INFO(ZEND_SEND_PREFER_REF, SORT_ASC_or_SORT_DESC) ZEND_ARG_INFO(ZEND_SEND_PREFER_REF, SORT_REGULAR_or_SORT_NUMERIC_or_SORT_STRING) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_rand, 0, 0, 1) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, num_req) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_sum, 0) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_product, 0) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_reduce, 0, 0, 2) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, callback) ZEND_ARG_INFO(0, initial) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_filter, 0, 0, 1) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, callback) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_map, 0, 0, 2) ZEND_ARG_INFO(0, callback) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_key_exists, 0) ZEND_ARG_INFO(0, key) ZEND_ARG_INFO(0, search) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_chunk, 0, 0, 2) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, size) ZEND_ARG_INFO(0, preserve_keys) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_combine, 0) ZEND_ARG_INFO(0, keys) /* ARRAY_INFO(0, keys, 0) */ ZEND_ARG_INFO(0, values) /* ARRAY_INFO(0, values, 0) */ ZEND_END_ARG_INFO() /* }}} */ /* {{{ basic_functions.c */ ZEND_BEGIN_ARG_INFO(arginfo_get_magic_quotes_gpc, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_get_magic_quotes_runtime, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_set_magic_quotes_runtime, 0, 0, 1) ZEND_ARG_INFO(0, new_setting) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_constant, 0) ZEND_ARG_INFO(0, const_name) ZEND_END_ARG_INFO() #ifdef HAVE_INET_NTOP ZEND_BEGIN_ARG_INFO(arginfo_inet_ntop, 0) ZEND_ARG_INFO(0, in_addr) ZEND_END_ARG_INFO() #endif #ifdef HAVE_INET_PTON ZEND_BEGIN_ARG_INFO(arginfo_inet_pton, 0) ZEND_ARG_INFO(0, ip_address) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO(arginfo_ip2long, 0) ZEND_ARG_INFO(0, ip_address) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_long2ip, 0) ZEND_ARG_INFO(0, proper_address) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_getenv, 0) ZEND_ARG_INFO(0, varname) ZEND_END_ARG_INFO() #ifdef HAVE_PUTENV ZEND_BEGIN_ARG_INFO(arginfo_putenv, 0) ZEND_ARG_INFO(0, setting) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_getopt, 0, 0, 1) ZEND_ARG_INFO(0, options) ZEND_ARG_INFO(0, opts) /* ARRAY_INFO(0, opts, 1) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_flush, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_sleep, 0) ZEND_ARG_INFO(0, seconds) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_usleep, 0) ZEND_ARG_INFO(0, micro_seconds) ZEND_END_ARG_INFO() #if HAVE_NANOSLEEP ZEND_BEGIN_ARG_INFO(arginfo_time_nanosleep, 0) ZEND_ARG_INFO(0, seconds) ZEND_ARG_INFO(0, nanoseconds) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_time_sleep_until, 0) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO(arginfo_get_current_user, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_get_cfg_var, 0) ZEND_ARG_INFO(0, option_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_error_log, 0, 0, 1) ZEND_ARG_INFO(0, message) ZEND_ARG_INFO(0, message_type) ZEND_ARG_INFO(0, destination) ZEND_ARG_INFO(0, extra_headers) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_error_get_last, 0, 0, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_call_user_func, 0, 0, 1) ZEND_ARG_INFO(0, function_name) ZEND_ARG_INFO(0, parmeter) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_call_user_func_array, 0, 0, 2) ZEND_ARG_INFO(0, function_name) ZEND_ARG_INFO(0, parameters) /* ARRAY_INFO(0, parameters, 1) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_call_user_method, 0, 0, 2) ZEND_ARG_INFO(0, method_name) ZEND_ARG_INFO(1, object) ZEND_ARG_INFO(0, parameter) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_call_user_method_array, 0) ZEND_ARG_INFO(0, method_name) ZEND_ARG_INFO(1, object) ZEND_ARG_INFO(0, params) /* ARRAY_INFO(0, params, 1) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_forward_static_call, 0, 0, 1) ZEND_ARG_INFO(0, function_name) ZEND_ARG_INFO(0, parameter) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_forward_static_call_array, 0, 0, 2) ZEND_ARG_INFO(0, function_name) ZEND_ARG_INFO(0, parameters) /* ARRAY_INFO(0, parameters, 1) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_register_shutdown_function, 0) ZEND_ARG_INFO(0, function_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_highlight_file, 0, 0, 1) ZEND_ARG_INFO(0, file_name) ZEND_ARG_INFO(0, return) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_php_strip_whitespace, 0) ZEND_ARG_INFO(0, file_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_highlight_string, 0, 0, 1) ZEND_ARG_INFO(0, string) ZEND_ARG_INFO(0, return) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ini_get, 0) ZEND_ARG_INFO(0, varname) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ini_get_all, 0, 0, 0) ZEND_ARG_INFO(0, extension) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ini_set, 0) ZEND_ARG_INFO(0, varname) ZEND_ARG_INFO(0, newvalue) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ini_restore, 0) ZEND_ARG_INFO(0, varname) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_set_include_path, 0) ZEND_ARG_INFO(0, new_include_path) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_get_include_path, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_restore_include_path, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_print_r, 0, 0, 1) ZEND_ARG_INFO(0, var) ZEND_ARG_INFO(0, return) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_connection_aborted, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_connection_status, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ignore_user_abort, 0, 0, 0) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() #if HAVE_GETSERVBYNAME ZEND_BEGIN_ARG_INFO(arginfo_getservbyname, 0) ZEND_ARG_INFO(0, service) ZEND_ARG_INFO(0, protocol) ZEND_END_ARG_INFO() #endif #if HAVE_GETSERVBYPORT ZEND_BEGIN_ARG_INFO(arginfo_getservbyport, 0) ZEND_ARG_INFO(0, port) ZEND_ARG_INFO(0, protocol) ZEND_END_ARG_INFO() #endif #if HAVE_GETPROTOBYNAME ZEND_BEGIN_ARG_INFO(arginfo_getprotobyname, 0) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() #endif #if HAVE_GETPROTOBYNUMBER ZEND_BEGIN_ARG_INFO(arginfo_getprotobynumber, 0) ZEND_ARG_INFO(0, proto) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_register_tick_function, 0, 0, 1) ZEND_ARG_INFO(0, function_name) ZEND_ARG_INFO(0, arg) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_unregister_tick_function, 0) ZEND_ARG_INFO(0, function_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_uploaded_file, 0) ZEND_ARG_INFO(0, path) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_move_uploaded_file, 0) ZEND_ARG_INFO(0, path) ZEND_ARG_INFO(0, new_path) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_parse_ini_file, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, process_sections) ZEND_ARG_INFO(0, scanner_mode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_parse_ini_string, 0, 0, 1) ZEND_ARG_INFO(0, ini_string) ZEND_ARG_INFO(0, process_sections) ZEND_ARG_INFO(0, scanner_mode) ZEND_END_ARG_INFO() #if ZEND_DEBUG ZEND_BEGIN_ARG_INFO(arginfo_config_get_hash, 0) ZEND_END_ARG_INFO() #endif #ifdef HAVE_GETLOADAVG ZEND_BEGIN_ARG_INFO(arginfo_sys_getloadavg, 0) ZEND_END_ARG_INFO() #endif /* }}} */ /* {{{ assert.c */ ZEND_BEGIN_ARG_INFO(arginfo_assert, 0) ZEND_ARG_INFO(0, assertion) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_assert_options, 0, 0, 1) ZEND_ARG_INFO(0, what) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() /* }}} */ /* {{{ base64.c */ ZEND_BEGIN_ARG_INFO(arginfo_base64_encode, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_base64_decode, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, strict) ZEND_END_ARG_INFO() /* }}} */ /* {{{ browscap.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_get_browser, 0, 0, 0) ZEND_ARG_INFO(0, browser_name) ZEND_ARG_INFO(0, return_array) ZEND_END_ARG_INFO() /* }}} */ /* {{{ crc32.c */ ZEND_BEGIN_ARG_INFO(arginfo_crc32, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() /* }}} */ /* {{{ crypt.c */ #if HAVE_CRYPT ZEND_BEGIN_ARG_INFO_EX(arginfo_crypt, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, salt) ZEND_END_ARG_INFO() #endif /* }}} */ /* {{{ cyr_convert.c */ ZEND_BEGIN_ARG_INFO(arginfo_convert_cyr_string, 0) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, from) ZEND_ARG_INFO(0, to) ZEND_END_ARG_INFO() /* }}} */ /* {{{ datetime.c */ #if HAVE_STRPTIME ZEND_BEGIN_ARG_INFO(arginfo_strptime, 0) ZEND_ARG_INFO(0, timestamp) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() #endif /* }}} */ /* {{{ dir.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_opendir, 0, 0, 1) ZEND_ARG_INFO(0, path) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_dir, 0, 0, 1) ZEND_ARG_INFO(0, directory) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_closedir, 0, 0, 0) ZEND_ARG_INFO(0, dir_handle) ZEND_END_ARG_INFO() #if defined(HAVE_CHROOT) && !defined(ZTS) && ENABLE_CHROOT_FUNC ZEND_BEGIN_ARG_INFO(arginfo_chroot, 0) ZEND_ARG_INFO(0, directory) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO(arginfo_chdir, 0) ZEND_ARG_INFO(0, directory) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_getcwd, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_rewinddir, 0, 0, 0) ZEND_ARG_INFO(0, dir_handle) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_readdir, 0, 0, 0) ZEND_ARG_INFO(0, dir_handle) ZEND_END_ARG_INFO() #ifdef HAVE_GLOB ZEND_BEGIN_ARG_INFO_EX(arginfo_glob, 0, 0, 1) ZEND_ARG_INFO(0, pattern) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_scandir, 0, 0, 1) ZEND_ARG_INFO(0, dir) ZEND_ARG_INFO(0, sorting_order) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() /* }}} */ /* {{{ arginfo ext/standard/dl.c */ ZEND_BEGIN_ARG_INFO(arginfo_dl, 0) ZEND_ARG_INFO(0, extension_filename) ZEND_END_ARG_INFO() /* }}} */ /* {{{ dns.c */ ZEND_BEGIN_ARG_INFO(arginfo_gethostbyaddr, 0) ZEND_ARG_INFO(0, ip_address) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_gethostbyname, 0) ZEND_ARG_INFO(0, hostname) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_gethostbynamel, 0) ZEND_ARG_INFO(0, hostname) ZEND_END_ARG_INFO() #ifdef HAVE_GETHOSTNAME ZEND_BEGIN_ARG_INFO(arginfo_gethostname, 0) ZEND_END_ARG_INFO() #endif #if defined(PHP_WIN32) || (HAVE_DNS_SEARCH_FUNC && !(defined(__BEOS__) || defined(NETWARE))) ZEND_BEGIN_ARG_INFO_EX(arginfo_dns_check_record, 0, 0, 1) ZEND_ARG_INFO(0, host) ZEND_ARG_INFO(0, type) ZEND_END_ARG_INFO() # if defined(PHP_WIN32) || HAVE_FULL_DNS_FUNCS ZEND_BEGIN_ARG_INFO_EX(arginfo_dns_get_record, 0, 0, 1) ZEND_ARG_INFO(0, hostname) ZEND_ARG_INFO(0, type) ZEND_ARG_ARRAY_INFO(1, authns, 1) ZEND_ARG_ARRAY_INFO(1, addtl, 1) ZEND_ARG_INFO(0, raw) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_dns_get_mx, 0, 0, 2) ZEND_ARG_INFO(0, hostname) ZEND_ARG_INFO(1, mxhosts) /* ARRAY_INFO(1, mxhosts, 1) */ ZEND_ARG_INFO(1, weight) /* ARRAY_INFO(1, weight, 1) */ ZEND_END_ARG_INFO() # endif #endif /* defined(PHP_WIN32) || (HAVE_DNS_SEARCH_FUNC && !(defined(__BEOS__) || defined(NETWARE))) */ /* }}} */ /* {{{ exec.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_exec, 0, 0, 1) ZEND_ARG_INFO(0, command) ZEND_ARG_INFO(1, output) /* ARRAY_INFO(1, output, 1) */ ZEND_ARG_INFO(1, return_value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_system, 0, 0, 1) ZEND_ARG_INFO(0, command) ZEND_ARG_INFO(1, return_value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_passthru, 0, 0, 1) ZEND_ARG_INFO(0, command) ZEND_ARG_INFO(1, return_value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_escapeshellcmd, 0) ZEND_ARG_INFO(0, command) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_escapeshellarg, 0) ZEND_ARG_INFO(0, arg) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_shell_exec, 0) ZEND_ARG_INFO(0, cmd) ZEND_END_ARG_INFO() #ifdef HAVE_NICE ZEND_BEGIN_ARG_INFO(arginfo_proc_nice, 0) ZEND_ARG_INFO(0, priority) ZEND_END_ARG_INFO() #endif /* }}} */ /* {{{ file.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_flock, 0, 0, 2) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, operation) ZEND_ARG_INFO(1, wouldblock) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_get_meta_tags, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, use_include_path) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_get_contents, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, flags) ZEND_ARG_INFO(0, context) ZEND_ARG_INFO(0, offset) ZEND_ARG_INFO(0, maxlen) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_put_contents, 0, 0, 2) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, data) ZEND_ARG_INFO(0, flags) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, flags) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_tempnam, 0) ZEND_ARG_INFO(0, dir) ZEND_ARG_INFO(0, prefix) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_tmpfile, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_fopen, 0, 0, 2) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, mode) ZEND_ARG_INFO(0, use_include_path) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_fclose, 0) ZEND_ARG_INFO(0, fp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_popen, 0) ZEND_ARG_INFO(0, command) ZEND_ARG_INFO(0, mode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_pclose, 0) ZEND_ARG_INFO(0, fp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_feof, 0) ZEND_ARG_INFO(0, fp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_fgets, 0, 0, 1) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, length) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_fgetc, 0) ZEND_ARG_INFO(0, fp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_fgetss, 0, 0, 1) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, length) ZEND_ARG_INFO(0, allowable_tags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_fscanf, 1, 0, 2) ZEND_ARG_INFO(0, stream) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(1, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_fwrite, 0, 0, 2) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, length) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_fflush, 0) ZEND_ARG_INFO(0, fp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_rewind, 0) ZEND_ARG_INFO(0, fp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ftell, 0) ZEND_ARG_INFO(0, fp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_fseek, 0, 0, 2) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, offset) ZEND_ARG_INFO(0, whence) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mkdir, 0, 0, 1) ZEND_ARG_INFO(0, pathname) ZEND_ARG_INFO(0, mode) ZEND_ARG_INFO(0, recursive) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_rmdir, 0, 0, 1) ZEND_ARG_INFO(0, dirname) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_readfile, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, flags) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_umask, 0, 0, 0) ZEND_ARG_INFO(0, mask) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_fpassthru, 0) ZEND_ARG_INFO(0, fp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_rename, 0, 0, 2) ZEND_ARG_INFO(0, old_name) ZEND_ARG_INFO(0, new_name) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_unlink, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ftruncate, 0) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, size) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_fstat, 0) ZEND_ARG_INFO(0, fp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_copy, 0) ZEND_ARG_INFO(0, source_file) ZEND_ARG_INFO(0, destination_file) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_fread, 0) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, length) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_fputcsv, 0, 0, 2) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, fields) /* ARRAY_INFO(0, fields, 1) */ ZEND_ARG_INFO(0, delimiter) ZEND_ARG_INFO(0, enclosure) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_fgetcsv, 0, 0, 1) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, length) ZEND_ARG_INFO(0, delimiter) ZEND_ARG_INFO(0, enclosure) ZEND_ARG_INFO(0, escape) ZEND_END_ARG_INFO() #if (!defined(__BEOS__) && !defined(NETWARE) && HAVE_REALPATH) || defined(ZTS) ZEND_BEGIN_ARG_INFO(arginfo_realpath, 0) ZEND_ARG_INFO(0, path) ZEND_END_ARG_INFO() #endif #ifdef HAVE_FNMATCH ZEND_BEGIN_ARG_INFO_EX(arginfo_fnmatch, 0, 0, 2) ZEND_ARG_INFO(0, pattern) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO(arginfo_sys_get_temp_dir, 0) ZEND_END_ARG_INFO() /* }}} */ /* {{{ filestat.c */ ZEND_BEGIN_ARG_INFO(arginfo_disk_total_space, 0) ZEND_ARG_INFO(0, path) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_disk_free_space, 0) ZEND_ARG_INFO(0, path) ZEND_END_ARG_INFO() #ifndef NETWARE ZEND_BEGIN_ARG_INFO(arginfo_chgrp, 0) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, group) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_chown, 0) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, user) ZEND_END_ARG_INFO() #endif #if HAVE_LCHOWN ZEND_BEGIN_ARG_INFO(arginfo_lchgrp, 0) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, group) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_lchown, 0) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, user) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO(arginfo_chmod, 0) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, mode) ZEND_END_ARG_INFO() #if HAVE_UTIME ZEND_BEGIN_ARG_INFO_EX(arginfo_touch, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, atime) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_clearstatcache, 0, 0, 0) ZEND_ARG_INFO(0, clear_realpath_cache) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_realpath_cache_size, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_realpath_cache_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_fileperms, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_fileinode, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_filesize, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_fileowner, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_filegroup, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_fileatime, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_filemtime, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_filectime, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_filetype, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_writable, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_readable, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_executable, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_file, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_dir, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_link, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_file_exists, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_lstat, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stat, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() /* }}} */ /* {{{ formatted_print.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_sprintf, 0, 0, 2) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, arg1) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_vsprintf, 0) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, args) /* ARRAY_INFO(0, args, 1) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_printf, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, arg1) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_vprintf, 0) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, args) /* ARRAY_INFO(0, args, 1) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_fprintf, 0, 0, 2) ZEND_ARG_INFO(0, stream) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, arg1) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_vfprintf, 0) ZEND_ARG_INFO(0, stream) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, args) /* ARRAY_INFO(0, args, 1) */ ZEND_END_ARG_INFO() /* }}} */ /* {{{ fsock.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_fsockopen, 0, 0, 2) ZEND_ARG_INFO(0, hostname) ZEND_ARG_INFO(0, port) ZEND_ARG_INFO(1, errno) ZEND_ARG_INFO(1, errstr) ZEND_ARG_INFO(0, timeout) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pfsockopen, 0, 0, 2) ZEND_ARG_INFO(0, hostname) ZEND_ARG_INFO(0, port) ZEND_ARG_INFO(1, errno) ZEND_ARG_INFO(1, errstr) ZEND_ARG_INFO(0, timeout) ZEND_END_ARG_INFO() /* }}} */ /* {{{ ftok.c */ #if HAVE_FTOK ZEND_BEGIN_ARG_INFO(arginfo_ftok, 0) ZEND_ARG_INFO(0, pathname) ZEND_ARG_INFO(0, proj) ZEND_END_ARG_INFO() #endif /* }}} */ /* {{{ head.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_header, 0, 0, 1) ZEND_ARG_INFO(0, header) ZEND_ARG_INFO(0, replace) ZEND_ARG_INFO(0, http_response_code) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_header_remove, 0, 0, 0) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_setcookie, 0, 0, 1) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, value) ZEND_ARG_INFO(0, expires) ZEND_ARG_INFO(0, path) ZEND_ARG_INFO(0, domain) ZEND_ARG_INFO(0, secure) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_setrawcookie, 0, 0, 1) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, value) ZEND_ARG_INFO(0, expires) ZEND_ARG_INFO(0, path) ZEND_ARG_INFO(0, domain) ZEND_ARG_INFO(0, secure) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_headers_sent, 0, 0, 0) ZEND_ARG_INFO(1, file) ZEND_ARG_INFO(1, line) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_headers_list, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_http_response_code, 0, 0, 0) ZEND_ARG_INFO(0, response_code) ZEND_END_ARG_INFO() /* }}} */ /* {{{ html.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_htmlspecialchars, 0, 0, 1) ZEND_ARG_INFO(0, string) ZEND_ARG_INFO(0, quote_style) ZEND_ARG_INFO(0, charset) ZEND_ARG_INFO(0, double_encode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_htmlspecialchars_decode, 0, 0, 1) ZEND_ARG_INFO(0, string) ZEND_ARG_INFO(0, quote_style) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_html_entity_decode, 0, 0, 1) ZEND_ARG_INFO(0, string) ZEND_ARG_INFO(0, quote_style) ZEND_ARG_INFO(0, charset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_htmlentities, 0, 0, 1) ZEND_ARG_INFO(0, string) ZEND_ARG_INFO(0, quote_style) ZEND_ARG_INFO(0, charset) ZEND_ARG_INFO(0, double_encode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_get_html_translation_table, 0, 0, 0) ZEND_ARG_INFO(0, table) ZEND_ARG_INFO(0, quote_style) ZEND_END_ARG_INFO() /* }}} */ /* {{{ http.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_http_build_query, 0, 0, 1) ZEND_ARG_INFO(0, formdata) ZEND_ARG_INFO(0, prefix) ZEND_ARG_INFO(0, arg_separator) ZEND_ARG_INFO(0, enc_type) ZEND_END_ARG_INFO() /* }}} */ /* {{{ image.c */ ZEND_BEGIN_ARG_INFO(arginfo_image_type_to_mime_type, 0) ZEND_ARG_INFO(0, imagetype) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_image_type_to_extension, 0, 0, 1) ZEND_ARG_INFO(0, imagetype) ZEND_ARG_INFO(0, include_dot) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_getimagesize, 0, 0, 1) ZEND_ARG_INFO(0, imagefile) ZEND_ARG_INFO(1, info) /* ARRAY_INFO(1, info, 1) */ ZEND_END_ARG_INFO() /* }}} */ /* {{{ info.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_phpinfo, 0, 0, 0) ZEND_ARG_INFO(0, what) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phpversion, 0, 0, 0) ZEND_ARG_INFO(0, extension) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phpcredits, 0, 0, 0) ZEND_ARG_INFO(0, flag) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_php_logo_guid, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_php_real_logo_guid, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_php_egg_logo_guid, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_zend_logo_guid, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_php_sapi_name, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_php_uname, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_php_ini_scanned_files, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_php_ini_loaded_file, 0) ZEND_END_ARG_INFO() /* }}} */ /* {{{ iptc.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_iptcembed, 0, 0, 2) ZEND_ARG_INFO(0, iptcdata) ZEND_ARG_INFO(0, jpeg_file_name) ZEND_ARG_INFO(0, spool) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_iptcparse, 0) ZEND_ARG_INFO(0, iptcdata) ZEND_END_ARG_INFO() /* }}} */ /* {{{ lcg.c */ ZEND_BEGIN_ARG_INFO(arginfo_lcg_value, 0) ZEND_END_ARG_INFO() /* }}} */ /* {{{ levenshtein.c */ ZEND_BEGIN_ARG_INFO(arginfo_levenshtein, 0) ZEND_ARG_INFO(0, str1) ZEND_ARG_INFO(0, str2) ZEND_ARG_INFO(0, cost_ins) ZEND_ARG_INFO(0, cost_rep) ZEND_ARG_INFO(0, cost_del) ZEND_END_ARG_INFO() /* }}} */ /* {{{ link.c */ #if defined(HAVE_SYMLINK) || defined(PHP_WIN32) ZEND_BEGIN_ARG_INFO(arginfo_readlink, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_linkinfo, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_symlink, 0) ZEND_ARG_INFO(0, target) ZEND_ARG_INFO(0, link) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_link, 0) ZEND_ARG_INFO(0, target) ZEND_ARG_INFO(0, link) ZEND_END_ARG_INFO() #endif /* }}} */ /* {{{ mail.c */ ZEND_BEGIN_ARG_INFO(arginfo_ezmlm_hash, 0) ZEND_ARG_INFO(0, addr) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mail, 0, 0, 3) ZEND_ARG_INFO(0, to) ZEND_ARG_INFO(0, subject) ZEND_ARG_INFO(0, message) ZEND_ARG_INFO(0, additional_headers) ZEND_ARG_INFO(0, additional_parameters) ZEND_END_ARG_INFO() /* }}} */ /* {{{ math.c */ ZEND_BEGIN_ARG_INFO(arginfo_abs, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ceil, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_floor, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_round, 0, 0, 1) ZEND_ARG_INFO(0, number) ZEND_ARG_INFO(0, precision) ZEND_ARG_INFO(0, mode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_sin, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_cos, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_tan, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_asin, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_acos, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_atan, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_atan2, 0) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, x) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_sinh, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_cosh, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_tanh, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_asinh, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_acosh, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_atanh, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_pi, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_finite, 0) ZEND_ARG_INFO(0, val) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_infinite, 0) ZEND_ARG_INFO(0, val) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_nan, 0) ZEND_ARG_INFO(0, val) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_pow, 0) ZEND_ARG_INFO(0, base) ZEND_ARG_INFO(0, exponent) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_exp, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_expm1, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_log1p, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_log, 0, 0, 1) ZEND_ARG_INFO(0, number) ZEND_ARG_INFO(0, base) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_log10, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_sqrt, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_hypot, 0) ZEND_ARG_INFO(0, num1) ZEND_ARG_INFO(0, num2) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_deg2rad, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_rad2deg, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_bindec, 0) ZEND_ARG_INFO(0, binary_number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_hexdec, 0) ZEND_ARG_INFO(0, hexadecimal_number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_octdec, 0) ZEND_ARG_INFO(0, octal_number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_decbin, 0) ZEND_ARG_INFO(0, decimal_number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_decoct, 0) ZEND_ARG_INFO(0, decimal_number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_dechex, 0) ZEND_ARG_INFO(0, decimal_number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_base_convert, 0) ZEND_ARG_INFO(0, number) ZEND_ARG_INFO(0, frombase) ZEND_ARG_INFO(0, tobase) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_number_format, 0, 0, 1) ZEND_ARG_INFO(0, number) ZEND_ARG_INFO(0, num_decimal_places) ZEND_ARG_INFO(0, dec_seperator) ZEND_ARG_INFO(0, thousands_seperator) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_fmod, 0) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_END_ARG_INFO() /* }}} */ /* {{{ md5.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_md5, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, raw_output) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_md5_file, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, raw_output) ZEND_END_ARG_INFO() /* }}} */ /* {{{ metaphone.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_metaphone, 0, 0, 1) ZEND_ARG_INFO(0, text) ZEND_ARG_INFO(0, phones) ZEND_END_ARG_INFO() /* }}} */ /* {{{ microtime.c */ #ifdef HAVE_GETTIMEOFDAY ZEND_BEGIN_ARG_INFO_EX(arginfo_microtime, 0, 0, 0) ZEND_ARG_INFO(0, get_as_float) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_gettimeofday, 0, 0, 0) ZEND_ARG_INFO(0, get_as_float) ZEND_END_ARG_INFO() #endif #ifdef HAVE_GETRUSAGE ZEND_BEGIN_ARG_INFO_EX(arginfo_getrusage, 0, 0, 0) ZEND_ARG_INFO(0, who) ZEND_END_ARG_INFO() #endif /* }}} */ /* {{{ pack.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_pack, 0, 0, 2) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, arg1) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_unpack, 0) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, input) ZEND_END_ARG_INFO() /* }}} */ /* {{{ pageinfo.c */ ZEND_BEGIN_ARG_INFO(arginfo_getmyuid, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_getmygid, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_getmypid, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_getmyinode, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_getlastmod, 0) ZEND_END_ARG_INFO() /* }}} */ /* {{{ proc_open.c */ #ifdef PHP_CAN_SUPPORT_PROC_OPEN ZEND_BEGIN_ARG_INFO_EX(arginfo_proc_terminate, 0, 0, 1) ZEND_ARG_INFO(0, process) ZEND_ARG_INFO(0, signal) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_proc_close, 0) ZEND_ARG_INFO(0, process) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_proc_get_status, 0) ZEND_ARG_INFO(0, process) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_proc_open, 0, 0, 3) ZEND_ARG_INFO(0, command) ZEND_ARG_INFO(0, descriptorspec) /* ARRAY_INFO(0, descriptorspec, 1) */ ZEND_ARG_INFO(1, pipes) /* ARRAY_INFO(1, pipes, 1) */ ZEND_ARG_INFO(0, cwd) ZEND_ARG_INFO(0, env) /* ARRAY_INFO(0, env, 1) */ ZEND_ARG_INFO(0, other_options) /* ARRAY_INFO(0, other_options, 1) */ ZEND_END_ARG_INFO() #endif /* }}} */ /* {{{ quot_print.c */ ZEND_BEGIN_ARG_INFO(arginfo_quoted_printable_decode, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() /* }}} */ /* {{{ quot_print.c */ ZEND_BEGIN_ARG_INFO(arginfo_quoted_printable_encode, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() /* }}} */ /* {{{ rand.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_srand, 0, 0, 0) ZEND_ARG_INFO(0, seed) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mt_srand, 0, 0, 0) ZEND_ARG_INFO(0, seed) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_rand, 0, 0, 0) ZEND_ARG_INFO(0, min) ZEND_ARG_INFO(0, max) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mt_rand, 0, 0, 0) ZEND_ARG_INFO(0, min) ZEND_ARG_INFO(0, max) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_getrandmax, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_mt_getrandmax, 0) ZEND_END_ARG_INFO() /* }}} */ /* {{{ sha1.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_sha1, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, raw_output) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_sha1_file, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, raw_output) ZEND_END_ARG_INFO() /* }}} */ /* {{{ soundex.c */ ZEND_BEGIN_ARG_INFO(arginfo_soundex, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() /* }}} */ /* {{{ streamsfuncs.c */ #if HAVE_SOCKETPAIR ZEND_BEGIN_ARG_INFO(arginfo_stream_socket_pair, 0) ZEND_ARG_INFO(0, domain) ZEND_ARG_INFO(0, type) ZEND_ARG_INFO(0, protocol) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_socket_client, 0, 0, 1) ZEND_ARG_INFO(0, remoteaddress) ZEND_ARG_INFO(1, errcode) ZEND_ARG_INFO(1, errstring) ZEND_ARG_INFO(0, timeout) ZEND_ARG_INFO(0, flags) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_socket_server, 0, 0, 1) ZEND_ARG_INFO(0, localaddress) ZEND_ARG_INFO(1, errcode) ZEND_ARG_INFO(1, errstring) ZEND_ARG_INFO(0, flags) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_socket_accept, 0, 0, 1) ZEND_ARG_INFO(0, serverstream) ZEND_ARG_INFO(0, timeout) ZEND_ARG_INFO(1, peername) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_socket_get_name, 0) ZEND_ARG_INFO(0, stream) ZEND_ARG_INFO(0, want_peer) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_socket_sendto, 0, 0, 2) ZEND_ARG_INFO(0, stream) ZEND_ARG_INFO(0, data) ZEND_ARG_INFO(0, flags) ZEND_ARG_INFO(0, target_addr) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_socket_recvfrom, 0, 0, 2) ZEND_ARG_INFO(0, stream) ZEND_ARG_INFO(0, amount) ZEND_ARG_INFO(0, flags) ZEND_ARG_INFO(1, remote_addr) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_get_contents, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_ARG_INFO(0, maxlen) ZEND_ARG_INFO(0, offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_copy_to_stream, 0, 0, 2) ZEND_ARG_INFO(0, source) ZEND_ARG_INFO(0, dest) ZEND_ARG_INFO(0, maxlen) ZEND_ARG_INFO(0, pos) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_get_meta_data, 0) ZEND_ARG_INFO(0, fp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_get_transports, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_get_wrappers, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_resolve_include_path, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_is_local, 0) ZEND_ARG_INFO(0, stream) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_supports_lock, 0, 0, 1) ZEND_ARG_INFO(0, stream) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_select, 0, 0, 4) ZEND_ARG_INFO(1, read_streams) /* ARRAY_INFO(1, read_streams, 1) */ ZEND_ARG_INFO(1, write_streams) /* ARRAY_INFO(1, write_streams, 1) */ ZEND_ARG_INFO(1, except_streams) /* ARRAY_INFO(1, except_streams, 1) */ ZEND_ARG_INFO(0, tv_sec) ZEND_ARG_INFO(0, tv_usec) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_context_get_options, 0) ZEND_ARG_INFO(0, stream_or_context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_context_set_option, 0) ZEND_ARG_INFO(0, stream_or_context) ZEND_ARG_INFO(0, wrappername) ZEND_ARG_INFO(0, optionname) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_context_set_params, 0) ZEND_ARG_INFO(0, stream_or_context) ZEND_ARG_INFO(0, options) /* ARRAY_INFO(0, options, 1) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_context_get_params, 0, ZEND_RETURN_VALUE, 1) ZEND_ARG_INFO(0, stream_or_context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_context_get_default, 0, 0, 0) ZEND_ARG_INFO(0, options) /* ARRAY_INFO(0, options, 1) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_context_set_default, 0) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_context_create, 0, 0, 0) ZEND_ARG_INFO(0, options) /* ARRAY_INFO(0, options, 1) */ ZEND_ARG_INFO(0, params) /* ARRAY_INFO(0, params, 1) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_filter_prepend, 0, 0, 2) ZEND_ARG_INFO(0, stream) ZEND_ARG_INFO(0, filtername) ZEND_ARG_INFO(0, read_write) ZEND_ARG_INFO(0, filterparams) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_filter_append, 0, 0, 2) ZEND_ARG_INFO(0, stream) ZEND_ARG_INFO(0, filtername) ZEND_ARG_INFO(0, read_write) ZEND_ARG_INFO(0, filterparams) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_filter_remove, 0) ZEND_ARG_INFO(0, stream_filter) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_get_line, 0, 0, 2) ZEND_ARG_INFO(0, stream) ZEND_ARG_INFO(0, maxlen) ZEND_ARG_INFO(0, ending) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_set_blocking, 0) ZEND_ARG_INFO(0, socket) ZEND_ARG_INFO(0, mode) ZEND_END_ARG_INFO() #if HAVE_SYS_TIME_H || defined(PHP_WIN32) ZEND_BEGIN_ARG_INFO(arginfo_stream_set_timeout, 0) ZEND_ARG_INFO(0, stream) ZEND_ARG_INFO(0, seconds) ZEND_ARG_INFO(0, microseconds) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO(arginfo_stream_set_read_buffer, 0) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, buffer) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_set_write_buffer, 0) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, buffer) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_set_chunk_size, 0) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, chunk_size) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_socket_enable_crypto, 0, 0, 2) ZEND_ARG_INFO(0, stream) ZEND_ARG_INFO(0, enable) ZEND_ARG_INFO(0, cryptokind) ZEND_ARG_INFO(0, sessionstream) ZEND_END_ARG_INFO() #ifdef HAVE_SHUTDOWN ZEND_BEGIN_ARG_INFO(arginfo_stream_socket_shutdown, 0) ZEND_ARG_INFO(0, stream) ZEND_ARG_INFO(0, how) ZEND_END_ARG_INFO() #endif /* }}} */ /* {{{ string.c */ ZEND_BEGIN_ARG_INFO(arginfo_bin2hex, 0) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_hex2bin, 0) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strspn, 0, 0, 2) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, mask) ZEND_ARG_INFO(0, start) ZEND_ARG_INFO(0, len) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strcspn, 0, 0, 2) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, mask) ZEND_ARG_INFO(0, start) ZEND_ARG_INFO(0, len) ZEND_END_ARG_INFO() #if HAVE_NL_LANGINFO ZEND_BEGIN_ARG_INFO(arginfo_nl_langinfo, 0) ZEND_ARG_INFO(0, item) ZEND_END_ARG_INFO() #endif #ifdef HAVE_STRCOLL ZEND_BEGIN_ARG_INFO(arginfo_strcoll, 0) ZEND_ARG_INFO(0, str1) ZEND_ARG_INFO(0, str2) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_trim, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, character_mask) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_rtrim, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, character_mask) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ltrim, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, character_mask) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wordwrap, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, width) ZEND_ARG_INFO(0, break) ZEND_ARG_INFO(0, cut) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_explode, 0, 0, 2) ZEND_ARG_INFO(0, separator) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, limit) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_implode, 0) ZEND_ARG_INFO(0, glue) ZEND_ARG_INFO(0, pieces) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_strtok, 0) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, token) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_strtoupper, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_strtolower, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_basename, 0, 0, 1) ZEND_ARG_INFO(0, path) ZEND_ARG_INFO(0, suffix) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_dirname, 0) ZEND_ARG_INFO(0, path) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pathinfo, 0, 0, 1) ZEND_ARG_INFO(0, path) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stristr, 0, 0, 2) ZEND_ARG_INFO(0, haystack) ZEND_ARG_INFO(0, needle) ZEND_ARG_INFO(0, part) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strstr, 0, 0, 2) ZEND_ARG_INFO(0, haystack) ZEND_ARG_INFO(0, needle) ZEND_ARG_INFO(0, part) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strpos, 0, 0, 2) ZEND_ARG_INFO(0, haystack) ZEND_ARG_INFO(0, needle) ZEND_ARG_INFO(0, offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stripos, 0, 0, 2) ZEND_ARG_INFO(0, haystack) ZEND_ARG_INFO(0, needle) ZEND_ARG_INFO(0, offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strrpos, 0, 0, 2) ZEND_ARG_INFO(0, haystack) ZEND_ARG_INFO(0, needle) ZEND_ARG_INFO(0, offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strripos, 0, 0, 2) ZEND_ARG_INFO(0, haystack) ZEND_ARG_INFO(0, needle) ZEND_ARG_INFO(0, offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_strrchr, 0) ZEND_ARG_INFO(0, haystack) ZEND_ARG_INFO(0, needle) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_chunk_split, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, chunklen) ZEND_ARG_INFO(0, ending) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_substr, 0, 0, 2) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, start) ZEND_ARG_INFO(0, length) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_substr_replace, 0, 0, 3) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, replace) ZEND_ARG_INFO(0, start) ZEND_ARG_INFO(0, length) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_quotemeta, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ord, 0) ZEND_ARG_INFO(0, character) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_chr, 0) ZEND_ARG_INFO(0, codepoint) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ucfirst, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_lcfirst, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ucwords, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strtr, 0, 0, 2) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, from) ZEND_ARG_INFO(0, to) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_strrev, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_similar_text, 0, 0, 2) ZEND_ARG_INFO(0, str1) ZEND_ARG_INFO(0, str2) ZEND_ARG_INFO(1, percent) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_addcslashes, 0) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, charlist) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_addslashes, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stripcslashes, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stripslashes, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_str_replace, 0, 0, 3) ZEND_ARG_INFO(0, search) ZEND_ARG_INFO(0, replace) ZEND_ARG_INFO(0, subject) ZEND_ARG_INFO(1, replace_count) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_str_ireplace, 0, 0, 3) ZEND_ARG_INFO(0, search) ZEND_ARG_INFO(0, replace) ZEND_ARG_INFO(0, subject) ZEND_ARG_INFO(1, replace_count) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_hebrev, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, max_chars_per_line) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_hebrevc, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, max_chars_per_line) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_nl2br, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, is_xhtml) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strip_tags, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, allowable_tags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_setlocale, 0, 0, 2) ZEND_ARG_INFO(0, category) ZEND_ARG_INFO(0, locale) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_parse_str, 0, 0, 1) ZEND_ARG_INFO(0, encoded_string) ZEND_ARG_INFO(1, result) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_str_getcsv, 0, 0, 1) ZEND_ARG_INFO(0, string) ZEND_ARG_INFO(0, delimiter) ZEND_ARG_INFO(0, enclosure) ZEND_ARG_INFO(0, escape) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_str_repeat, 0) ZEND_ARG_INFO(0, input) ZEND_ARG_INFO(0, mult) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_count_chars, 0, 0, 1) ZEND_ARG_INFO(0, input) ZEND_ARG_INFO(0, mode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_strnatcmp, 0) ZEND_ARG_INFO(0, s1) ZEND_ARG_INFO(0, s2) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_localeconv, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_strnatcasecmp, 0) ZEND_ARG_INFO(0, s1) ZEND_ARG_INFO(0, s2) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_substr_count, 0, 0, 2) ZEND_ARG_INFO(0, haystack) ZEND_ARG_INFO(0, needle) ZEND_ARG_INFO(0, offset) ZEND_ARG_INFO(0, length) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_str_pad, 0, 0, 2) ZEND_ARG_INFO(0, input) ZEND_ARG_INFO(0, pad_length) ZEND_ARG_INFO(0, pad_string) ZEND_ARG_INFO(0, pad_type) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_sscanf, 1, 0, 2) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(1, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_str_rot13, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_str_shuffle, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_str_word_count, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, charlist) ZEND_END_ARG_INFO() #ifdef HAVE_STRFMON ZEND_BEGIN_ARG_INFO(arginfo_money_format, 0) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_str_split, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, split_length) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strpbrk, 0, 0, 1) ZEND_ARG_INFO(0, haystack) ZEND_ARG_INFO(0, char_list) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_substr_compare, 0, 0, 3) ZEND_ARG_INFO(0, main_str) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, offset) ZEND_ARG_INFO(0, length) ZEND_ARG_INFO(0, case_sensitivity) ZEND_END_ARG_INFO() /* }}} */ /* {{{ syslog.c */ #ifdef HAVE_SYSLOG_H ZEND_BEGIN_ARG_INFO(arginfo_openlog, 0) ZEND_ARG_INFO(0, ident) ZEND_ARG_INFO(0, option) ZEND_ARG_INFO(0, facility) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_closelog, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_syslog, 0) ZEND_ARG_INFO(0, priority) ZEND_ARG_INFO(0, message) ZEND_END_ARG_INFO() #endif /* }}} */ /* {{{ type.c */ ZEND_BEGIN_ARG_INFO(arginfo_gettype, 0) ZEND_ARG_INFO(0, var) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_settype, 0) ZEND_ARG_INFO(1, var) ZEND_ARG_INFO(0, type) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_intval, 0, 0, 1) ZEND_ARG_INFO(0, var) ZEND_ARG_INFO(0, base) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_floatval, 0) ZEND_ARG_INFO(0, var) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_strval, 0) ZEND_ARG_INFO(0, var) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_null, 0) ZEND_ARG_INFO(0, var) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_resource, 0) ZEND_ARG_INFO(0, var) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_bool, 0) ZEND_ARG_INFO(0, var) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_long, 0) ZEND_ARG_INFO(0, var) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_float, 0) ZEND_ARG_INFO(0, var) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_string, 0) ZEND_ARG_INFO(0, var) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_array, 0) ZEND_ARG_INFO(0, var) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_object, 0) ZEND_ARG_INFO(0, var) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_numeric, 0) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_scalar, 0) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_is_callable, 0, 0, 1) ZEND_ARG_INFO(0, var) ZEND_ARG_INFO(0, syntax_only) ZEND_ARG_INFO(1, callable_name) ZEND_END_ARG_INFO() /* }}} */ /* {{{ uniqid.c */ #ifdef HAVE_GETTIMEOFDAY ZEND_BEGIN_ARG_INFO_EX(arginfo_uniqid, 0, 0, 0) ZEND_ARG_INFO(0, prefix) ZEND_ARG_INFO(0, more_entropy) ZEND_END_ARG_INFO() #endif /* }}} */ /* {{{ url.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_parse_url, 0, 0, 1) ZEND_ARG_INFO(0, url) ZEND_ARG_INFO(0, component) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_urlencode, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_urldecode, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_rawurlencode, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_rawurldecode, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_get_headers, 0, 0, 1) ZEND_ARG_INFO(0, url) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() /* }}} */ /* {{{ user_filters.c */ ZEND_BEGIN_ARG_INFO(arginfo_stream_bucket_make_writeable, 0) ZEND_ARG_INFO(0, brigade) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_bucket_prepend, 0) ZEND_ARG_INFO(0, brigade) ZEND_ARG_INFO(0, bucket) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_bucket_append, 0) ZEND_ARG_INFO(0, brigade) ZEND_ARG_INFO(0, bucket) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_bucket_new, 0) ZEND_ARG_INFO(0, stream) ZEND_ARG_INFO(0, buffer) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_get_filters, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_filter_register, 0) ZEND_ARG_INFO(0, filtername) ZEND_ARG_INFO(0, classname) ZEND_END_ARG_INFO() /* }}} */ /* {{{ uuencode.c */ ZEND_BEGIN_ARG_INFO(arginfo_convert_uuencode, 0) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_convert_uudecode, 0) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO() /* }}} */ /* {{{ var.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_var_dump, 0, 0, 1) ZEND_ARG_INFO(0, var) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_debug_zval_dump, 0, 0, 1) ZEND_ARG_INFO(0, var) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_var_export, 0, 0, 1) ZEND_ARG_INFO(0, var) ZEND_ARG_INFO(0, return) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_serialize, 0) ZEND_ARG_INFO(0, var) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_unserialize, 0) ZEND_ARG_INFO(0, variable_representation) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_memory_get_usage, 0, 0, 0) ZEND_ARG_INFO(0, real_usage) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_memory_get_peak_usage, 0, 0, 0) ZEND_ARG_INFO(0, real_usage) ZEND_END_ARG_INFO() /* }}} */ /* {{{ versioning.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_version_compare, 0, 0, 2) ZEND_ARG_INFO(0, ver1) ZEND_ARG_INFO(0, ver2) ZEND_ARG_INFO(0, oper) ZEND_END_ARG_INFO() /* }}} */ /* }}} */ const zend_function_entry basic_functions[] = { /* {{{ */ PHP_FE(constant, arginfo_constant) PHP_FE(bin2hex, arginfo_bin2hex) PHP_FE(hex2bin, arginfo_hex2bin) PHP_FE(sleep, arginfo_sleep) PHP_FE(usleep, arginfo_usleep) #if HAVE_NANOSLEEP PHP_FE(time_nanosleep, arginfo_time_nanosleep) PHP_FE(time_sleep_until, arginfo_time_sleep_until) #endif #if HAVE_STRPTIME PHP_FE(strptime, arginfo_strptime) #endif PHP_FE(flush, arginfo_flush) PHP_FE(wordwrap, arginfo_wordwrap) PHP_FE(htmlspecialchars, arginfo_htmlspecialchars) PHP_FE(htmlentities, arginfo_htmlentities) PHP_FE(html_entity_decode, arginfo_html_entity_decode) PHP_FE(htmlspecialchars_decode, arginfo_htmlspecialchars_decode) PHP_FE(get_html_translation_table, arginfo_get_html_translation_table) PHP_FE(sha1, arginfo_sha1) PHP_FE(sha1_file, arginfo_sha1_file) PHP_NAMED_FE(md5,php_if_md5, arginfo_md5) PHP_NAMED_FE(md5_file,php_if_md5_file, arginfo_md5_file) PHP_NAMED_FE(crc32,php_if_crc32, arginfo_crc32) PHP_FE(iptcparse, arginfo_iptcparse) PHP_FE(iptcembed, arginfo_iptcembed) PHP_FE(getimagesize, arginfo_getimagesize) PHP_FE(getimagesizefromstring, arginfo_getimagesize) PHP_FE(image_type_to_mime_type, arginfo_image_type_to_mime_type) PHP_FE(image_type_to_extension, arginfo_image_type_to_extension) PHP_FE(phpinfo, arginfo_phpinfo) PHP_FE(phpversion, arginfo_phpversion) PHP_FE(phpcredits, arginfo_phpcredits) PHP_FE(php_logo_guid, arginfo_php_logo_guid) PHP_FE(php_real_logo_guid, arginfo_php_real_logo_guid) PHP_FE(php_egg_logo_guid, arginfo_php_egg_logo_guid) PHP_FE(zend_logo_guid, arginfo_zend_logo_guid) PHP_FE(php_sapi_name, arginfo_php_sapi_name) PHP_FE(php_uname, arginfo_php_uname) PHP_FE(php_ini_scanned_files, arginfo_php_ini_scanned_files) PHP_FE(php_ini_loaded_file, arginfo_php_ini_loaded_file) PHP_FE(strnatcmp, arginfo_strnatcmp) PHP_FE(strnatcasecmp, arginfo_strnatcasecmp) PHP_FE(substr_count, arginfo_substr_count) PHP_FE(strspn, arginfo_strspn) PHP_FE(strcspn, arginfo_strcspn) PHP_FE(strtok, arginfo_strtok) PHP_FE(strtoupper, arginfo_strtoupper) PHP_FE(strtolower, arginfo_strtolower) PHP_FE(strpos, arginfo_strpos) PHP_FE(stripos, arginfo_stripos) PHP_FE(strrpos, arginfo_strrpos) PHP_FE(strripos, arginfo_strripos) PHP_FE(strrev, arginfo_strrev) PHP_FE(hebrev, arginfo_hebrev) PHP_FE(hebrevc, arginfo_hebrevc) PHP_FE(nl2br, arginfo_nl2br) PHP_FE(basename, arginfo_basename) PHP_FE(dirname, arginfo_dirname) PHP_FE(pathinfo, arginfo_pathinfo) PHP_FE(stripslashes, arginfo_stripslashes) PHP_FE(stripcslashes, arginfo_stripcslashes) PHP_FE(strstr, arginfo_strstr) PHP_FE(stristr, arginfo_stristr) PHP_FE(strrchr, arginfo_strrchr) PHP_FE(str_shuffle, arginfo_str_shuffle) PHP_FE(str_word_count, arginfo_str_word_count) PHP_FE(str_split, arginfo_str_split) PHP_FE(strpbrk, arginfo_strpbrk) PHP_FE(substr_compare, arginfo_substr_compare) #ifdef HAVE_STRCOLL PHP_FE(strcoll, arginfo_strcoll) #endif #ifdef HAVE_STRFMON PHP_FE(money_format, arginfo_money_format) #endif PHP_FE(substr, arginfo_substr) PHP_FE(substr_replace, arginfo_substr_replace) PHP_FE(quotemeta, arginfo_quotemeta) PHP_FE(ucfirst, arginfo_ucfirst) PHP_FE(lcfirst, arginfo_lcfirst) PHP_FE(ucwords, arginfo_ucwords) PHP_FE(strtr, arginfo_strtr) PHP_FE(addslashes, arginfo_addslashes) PHP_FE(addcslashes, arginfo_addcslashes) PHP_FE(rtrim, arginfo_rtrim) PHP_FE(str_replace, arginfo_str_replace) PHP_FE(str_ireplace, arginfo_str_ireplace) PHP_FE(str_repeat, arginfo_str_repeat) PHP_FE(count_chars, arginfo_count_chars) PHP_FE(chunk_split, arginfo_chunk_split) PHP_FE(trim, arginfo_trim) PHP_FE(ltrim, arginfo_ltrim) PHP_FE(strip_tags, arginfo_strip_tags) PHP_FE(similar_text, arginfo_similar_text) PHP_FE(explode, arginfo_explode) PHP_FE(implode, arginfo_implode) PHP_FALIAS(join, implode, arginfo_implode) PHP_FE(setlocale, arginfo_setlocale) PHP_FE(localeconv, arginfo_localeconv) #if HAVE_NL_LANGINFO PHP_FE(nl_langinfo, arginfo_nl_langinfo) #endif PHP_FE(soundex, arginfo_soundex) PHP_FE(levenshtein, arginfo_levenshtein) PHP_FE(chr, arginfo_chr) PHP_FE(ord, arginfo_ord) PHP_FE(parse_str, arginfo_parse_str) PHP_FE(str_getcsv, arginfo_str_getcsv) PHP_FE(str_pad, arginfo_str_pad) PHP_FALIAS(chop, rtrim, arginfo_rtrim) PHP_FALIAS(strchr, strstr, arginfo_strstr) PHP_NAMED_FE(sprintf, PHP_FN(user_sprintf), arginfo_sprintf) PHP_NAMED_FE(printf, PHP_FN(user_printf), arginfo_printf) PHP_FE(vprintf, arginfo_vprintf) PHP_FE(vsprintf, arginfo_vsprintf) PHP_FE(fprintf, arginfo_fprintf) PHP_FE(vfprintf, arginfo_vfprintf) PHP_FE(sscanf, arginfo_sscanf) PHP_FE(fscanf, arginfo_fscanf) PHP_FE(parse_url, arginfo_parse_url) PHP_FE(urlencode, arginfo_urlencode) PHP_FE(urldecode, arginfo_urldecode) PHP_FE(rawurlencode, arginfo_rawurlencode) PHP_FE(rawurldecode, arginfo_rawurldecode) PHP_FE(http_build_query, arginfo_http_build_query) #if defined(HAVE_SYMLINK) || defined(PHP_WIN32) PHP_FE(readlink, arginfo_readlink) PHP_FE(linkinfo, arginfo_linkinfo) PHP_FE(symlink, arginfo_symlink) PHP_FE(link, arginfo_link) #endif PHP_FE(unlink, arginfo_unlink) PHP_FE(exec, arginfo_exec) PHP_FE(system, arginfo_system) PHP_FE(escapeshellcmd, arginfo_escapeshellcmd) PHP_FE(escapeshellarg, arginfo_escapeshellarg) PHP_FE(passthru, arginfo_passthru) PHP_FE(shell_exec, arginfo_shell_exec) #ifdef PHP_CAN_SUPPORT_PROC_OPEN PHP_FE(proc_open, arginfo_proc_open) PHP_FE(proc_close, arginfo_proc_close) PHP_FE(proc_terminate, arginfo_proc_terminate) PHP_FE(proc_get_status, arginfo_proc_get_status) #endif #ifdef HAVE_NICE PHP_FE(proc_nice, arginfo_proc_nice) #endif PHP_FE(rand, arginfo_rand) PHP_FE(srand, arginfo_srand) PHP_FE(getrandmax, arginfo_getrandmax) PHP_FE(mt_rand, arginfo_mt_rand) PHP_FE(mt_srand, arginfo_mt_srand) PHP_FE(mt_getrandmax, arginfo_mt_getrandmax) #if HAVE_GETSERVBYNAME PHP_FE(getservbyname, arginfo_getservbyname) #endif #if HAVE_GETSERVBYPORT PHP_FE(getservbyport, arginfo_getservbyport) #endif #if HAVE_GETPROTOBYNAME PHP_FE(getprotobyname, arginfo_getprotobyname) #endif #if HAVE_GETPROTOBYNUMBER PHP_FE(getprotobynumber, arginfo_getprotobynumber) #endif PHP_FE(getmyuid, arginfo_getmyuid) PHP_FE(getmygid, arginfo_getmygid) PHP_FE(getmypid, arginfo_getmypid) PHP_FE(getmyinode, arginfo_getmyinode) PHP_FE(getlastmod, arginfo_getlastmod) PHP_FE(base64_decode, arginfo_base64_decode) PHP_FE(base64_encode, arginfo_base64_encode) PHP_FE(convert_uuencode, arginfo_convert_uuencode) PHP_FE(convert_uudecode, arginfo_convert_uudecode) PHP_FE(abs, arginfo_abs) PHP_FE(ceil, arginfo_ceil) PHP_FE(floor, arginfo_floor) PHP_FE(round, arginfo_round) PHP_FE(sin, arginfo_sin) PHP_FE(cos, arginfo_cos) PHP_FE(tan, arginfo_tan) PHP_FE(asin, arginfo_asin) PHP_FE(acos, arginfo_acos) PHP_FE(atan, arginfo_atan) PHP_FE(atanh, arginfo_atanh) PHP_FE(atan2, arginfo_atan2) PHP_FE(sinh, arginfo_sinh) PHP_FE(cosh, arginfo_cosh) PHP_FE(tanh, arginfo_tanh) PHP_FE(asinh, arginfo_asinh) PHP_FE(acosh, arginfo_acosh) PHP_FE(expm1, arginfo_expm1) PHP_FE(log1p, arginfo_log1p) PHP_FE(pi, arginfo_pi) PHP_FE(is_finite, arginfo_is_finite) PHP_FE(is_nan, arginfo_is_nan) PHP_FE(is_infinite, arginfo_is_infinite) PHP_FE(pow, arginfo_pow) PHP_FE(exp, arginfo_exp) PHP_FE(log, arginfo_log) PHP_FE(log10, arginfo_log10) PHP_FE(sqrt, arginfo_sqrt) PHP_FE(hypot, arginfo_hypot) PHP_FE(deg2rad, arginfo_deg2rad) PHP_FE(rad2deg, arginfo_rad2deg) PHP_FE(bindec, arginfo_bindec) PHP_FE(hexdec, arginfo_hexdec) PHP_FE(octdec, arginfo_octdec) PHP_FE(decbin, arginfo_decbin) PHP_FE(decoct, arginfo_decoct) PHP_FE(dechex, arginfo_dechex) PHP_FE(base_convert, arginfo_base_convert) PHP_FE(number_format, arginfo_number_format) PHP_FE(fmod, arginfo_fmod) #ifdef HAVE_INET_NTOP PHP_RAW_NAMED_FE(inet_ntop, php_inet_ntop, arginfo_inet_ntop) #endif #ifdef HAVE_INET_PTON PHP_RAW_NAMED_FE(inet_pton, php_inet_pton, arginfo_inet_pton) #endif PHP_FE(ip2long, arginfo_ip2long) PHP_FE(long2ip, arginfo_long2ip) PHP_FE(getenv, arginfo_getenv) #ifdef HAVE_PUTENV PHP_FE(putenv, arginfo_putenv) #endif PHP_FE(getopt, arginfo_getopt) #ifdef HAVE_GETLOADAVG PHP_FE(sys_getloadavg, arginfo_sys_getloadavg) #endif #ifdef HAVE_GETTIMEOFDAY PHP_FE(microtime, arginfo_microtime) PHP_FE(gettimeofday, arginfo_gettimeofday) #endif #ifdef HAVE_GETRUSAGE PHP_FE(getrusage, arginfo_getrusage) #endif #ifdef HAVE_GETTIMEOFDAY PHP_FE(uniqid, arginfo_uniqid) #endif PHP_FE(quoted_printable_decode, arginfo_quoted_printable_decode) PHP_FE(quoted_printable_encode, arginfo_quoted_printable_encode) PHP_FE(convert_cyr_string, arginfo_convert_cyr_string) PHP_FE(get_current_user, arginfo_get_current_user) PHP_FE(set_time_limit, arginfo_set_time_limit) PHP_FE(header_register_callback, arginfo_header_register_callback) PHP_FE(get_cfg_var, arginfo_get_cfg_var) PHP_DEP_FALIAS(magic_quotes_runtime, set_magic_quotes_runtime, arginfo_set_magic_quotes_runtime) PHP_DEP_FE(set_magic_quotes_runtime, arginfo_set_magic_quotes_runtime) PHP_FE(get_magic_quotes_gpc, arginfo_get_magic_quotes_gpc) PHP_FE(get_magic_quotes_runtime, arginfo_get_magic_quotes_runtime) PHP_FE(error_log, arginfo_error_log) PHP_FE(error_get_last, arginfo_error_get_last) PHP_FE(call_user_func, arginfo_call_user_func) PHP_FE(call_user_func_array, arginfo_call_user_func_array) PHP_DEP_FE(call_user_method, arginfo_call_user_method) PHP_DEP_FE(call_user_method_array, arginfo_call_user_method_array) PHP_FE(forward_static_call, arginfo_forward_static_call) PHP_FE(forward_static_call_array, arginfo_forward_static_call_array) PHP_FE(serialize, arginfo_serialize) PHP_FE(unserialize, arginfo_unserialize) PHP_FE(var_dump, arginfo_var_dump) PHP_FE(var_export, arginfo_var_export) PHP_FE(debug_zval_dump, arginfo_debug_zval_dump) PHP_FE(print_r, arginfo_print_r) PHP_FE(memory_get_usage, arginfo_memory_get_usage) PHP_FE(memory_get_peak_usage, arginfo_memory_get_peak_usage) PHP_FE(register_shutdown_function, arginfo_register_shutdown_function) PHP_FE(register_tick_function, arginfo_register_tick_function) PHP_FE(unregister_tick_function, arginfo_unregister_tick_function) PHP_FE(highlight_file, arginfo_highlight_file) PHP_FALIAS(show_source, highlight_file, arginfo_highlight_file) PHP_FE(highlight_string, arginfo_highlight_string) PHP_FE(php_strip_whitespace, arginfo_php_strip_whitespace) PHP_FE(ini_get, arginfo_ini_get) PHP_FE(ini_get_all, arginfo_ini_get_all) PHP_FE(ini_set, arginfo_ini_set) PHP_FALIAS(ini_alter, ini_set, arginfo_ini_set) PHP_FE(ini_restore, arginfo_ini_restore) PHP_FE(get_include_path, arginfo_get_include_path) PHP_FE(set_include_path, arginfo_set_include_path) PHP_FE(restore_include_path, arginfo_restore_include_path) PHP_FE(setcookie, arginfo_setcookie) PHP_FE(setrawcookie, arginfo_setrawcookie) PHP_FE(header, arginfo_header) PHP_FE(header_remove, arginfo_header_remove) PHP_FE(headers_sent, arginfo_headers_sent) PHP_FE(headers_list, arginfo_headers_list) PHP_FE(http_response_code, arginfo_http_response_code) PHP_FE(connection_aborted, arginfo_connection_aborted) PHP_FE(connection_status, arginfo_connection_status) PHP_FE(ignore_user_abort, arginfo_ignore_user_abort) PHP_FE(parse_ini_file, arginfo_parse_ini_file) PHP_FE(parse_ini_string, arginfo_parse_ini_string) #if ZEND_DEBUG PHP_FE(config_get_hash, arginfo_config_get_hash) #endif PHP_FE(is_uploaded_file, arginfo_is_uploaded_file) PHP_FE(move_uploaded_file, arginfo_move_uploaded_file) /* functions from dns.c */ PHP_FE(gethostbyaddr, arginfo_gethostbyaddr) PHP_FE(gethostbyname, arginfo_gethostbyname) PHP_FE(gethostbynamel, arginfo_gethostbynamel) #ifdef HAVE_GETHOSTNAME PHP_FE(gethostname, arginfo_gethostname) #endif #if defined(PHP_WIN32) || (HAVE_DNS_SEARCH_FUNC && !(defined(__BEOS__) || defined(NETWARE))) PHP_FE(dns_check_record, arginfo_dns_check_record) PHP_FALIAS(checkdnsrr, dns_check_record, arginfo_dns_check_record) # if defined(PHP_WIN32) || HAVE_FULL_DNS_FUNCS PHP_FE(dns_get_mx, arginfo_dns_get_mx) PHP_FALIAS(getmxrr, dns_get_mx, arginfo_dns_get_mx) PHP_FE(dns_get_record, arginfo_dns_get_record) # endif #endif /* functions from type.c */ PHP_FE(intval, arginfo_intval) PHP_FE(floatval, arginfo_floatval) PHP_FALIAS(doubleval, floatval, arginfo_floatval) PHP_FE(strval, arginfo_strval) PHP_FE(gettype, arginfo_gettype) PHP_FE(settype, arginfo_settype) PHP_FE(is_null, arginfo_is_null) PHP_FE(is_resource, arginfo_is_resource) PHP_FE(is_bool, arginfo_is_bool) PHP_FE(is_long, arginfo_is_long) PHP_FE(is_float, arginfo_is_float) PHP_FALIAS(is_int, is_long, arginfo_is_long) PHP_FALIAS(is_integer, is_long, arginfo_is_long) PHP_FALIAS(is_double, is_float, arginfo_is_float) PHP_FALIAS(is_real, is_float, arginfo_is_float) PHP_FE(is_numeric, arginfo_is_numeric) PHP_FE(is_string, arginfo_is_string) PHP_FE(is_array, arginfo_is_array) PHP_FE(is_object, arginfo_is_object) PHP_FE(is_scalar, arginfo_is_scalar) PHP_FE(is_callable, arginfo_is_callable) /* functions from file.c */ PHP_FE(pclose, arginfo_pclose) PHP_FE(popen, arginfo_popen) PHP_FE(readfile, arginfo_readfile) PHP_FE(rewind, arginfo_rewind) PHP_FE(rmdir, arginfo_rmdir) PHP_FE(umask, arginfo_umask) PHP_FE(fclose, arginfo_fclose) PHP_FE(feof, arginfo_feof) PHP_FE(fgetc, arginfo_fgetc) PHP_FE(fgets, arginfo_fgets) PHP_FE(fgetss, arginfo_fgetss) PHP_FE(fread, arginfo_fread) PHP_NAMED_FE(fopen, php_if_fopen, arginfo_fopen) PHP_FE(fpassthru, arginfo_fpassthru) PHP_NAMED_FE(ftruncate, php_if_ftruncate, arginfo_ftruncate) PHP_NAMED_FE(fstat, php_if_fstat, arginfo_fstat) PHP_FE(fseek, arginfo_fseek) PHP_FE(ftell, arginfo_ftell) PHP_FE(fflush, arginfo_fflush) PHP_FE(fwrite, arginfo_fwrite) PHP_FALIAS(fputs, fwrite, arginfo_fwrite) PHP_FE(mkdir, arginfo_mkdir) PHP_FE(rename, arginfo_rename) PHP_FE(copy, arginfo_copy) PHP_FE(tempnam, arginfo_tempnam) PHP_NAMED_FE(tmpfile, php_if_tmpfile, arginfo_tmpfile) PHP_FE(file, arginfo_file) PHP_FE(file_get_contents, arginfo_file_get_contents) PHP_FE(file_put_contents, arginfo_file_put_contents) PHP_FE(stream_select, arginfo_stream_select) PHP_FE(stream_context_create, arginfo_stream_context_create) PHP_FE(stream_context_set_params, arginfo_stream_context_set_params) PHP_FE(stream_context_get_params, arginfo_stream_context_get_params) PHP_FE(stream_context_set_option, arginfo_stream_context_set_option) PHP_FE(stream_context_get_options, arginfo_stream_context_get_options) PHP_FE(stream_context_get_default, arginfo_stream_context_get_default) PHP_FE(stream_context_set_default, arginfo_stream_context_set_default) PHP_FE(stream_filter_prepend, arginfo_stream_filter_prepend) PHP_FE(stream_filter_append, arginfo_stream_filter_append) PHP_FE(stream_filter_remove, arginfo_stream_filter_remove) PHP_FE(stream_socket_client, arginfo_stream_socket_client) PHP_FE(stream_socket_server, arginfo_stream_socket_server) PHP_FE(stream_socket_accept, arginfo_stream_socket_accept) PHP_FE(stream_socket_get_name, arginfo_stream_socket_get_name) PHP_FE(stream_socket_recvfrom, arginfo_stream_socket_recvfrom) PHP_FE(stream_socket_sendto, arginfo_stream_socket_sendto) PHP_FE(stream_socket_enable_crypto, arginfo_stream_socket_enable_crypto) #ifdef HAVE_SHUTDOWN PHP_FE(stream_socket_shutdown, arginfo_stream_socket_shutdown) #endif #if HAVE_SOCKETPAIR PHP_FE(stream_socket_pair, arginfo_stream_socket_pair) #endif PHP_FE(stream_copy_to_stream, arginfo_stream_copy_to_stream) PHP_FE(stream_get_contents, arginfo_stream_get_contents) PHP_FE(stream_supports_lock, arginfo_stream_supports_lock) PHP_FE(fgetcsv, arginfo_fgetcsv) PHP_FE(fputcsv, arginfo_fputcsv) PHP_FE(flock, arginfo_flock) PHP_FE(get_meta_tags, arginfo_get_meta_tags) PHP_FE(stream_set_read_buffer, arginfo_stream_set_read_buffer) PHP_FE(stream_set_write_buffer, arginfo_stream_set_write_buffer) PHP_FALIAS(set_file_buffer, stream_set_write_buffer, arginfo_stream_set_write_buffer) PHP_FE(stream_set_chunk_size, arginfo_stream_set_chunk_size) PHP_DEP_FALIAS(set_socket_blocking, stream_set_blocking, arginfo_stream_set_blocking) PHP_FE(stream_set_blocking, arginfo_stream_set_blocking) PHP_FALIAS(socket_set_blocking, stream_set_blocking, arginfo_stream_set_blocking) PHP_FE(stream_get_meta_data, arginfo_stream_get_meta_data) PHP_FE(stream_get_line, arginfo_stream_get_line) PHP_FE(stream_wrapper_register, arginfo_stream_wrapper_register) PHP_FALIAS(stream_register_wrapper, stream_wrapper_register, arginfo_stream_wrapper_register) PHP_FE(stream_wrapper_unregister, arginfo_stream_wrapper_unregister) PHP_FE(stream_wrapper_restore, arginfo_stream_wrapper_restore) PHP_FE(stream_get_wrappers, arginfo_stream_get_wrappers) PHP_FE(stream_get_transports, arginfo_stream_get_transports) PHP_FE(stream_resolve_include_path, arginfo_stream_resolve_include_path) PHP_FE(stream_is_local, arginfo_stream_is_local) PHP_FE(get_headers, arginfo_get_headers) #if HAVE_SYS_TIME_H || defined(PHP_WIN32) PHP_FE(stream_set_timeout, arginfo_stream_set_timeout) PHP_FALIAS(socket_set_timeout, stream_set_timeout, arginfo_stream_set_timeout) #endif PHP_FALIAS(socket_get_status, stream_get_meta_data, arginfo_stream_get_meta_data) #if (!defined(__BEOS__) && !defined(NETWARE) && HAVE_REALPATH) || defined(ZTS) PHP_FE(realpath, arginfo_realpath) #endif #ifdef HAVE_FNMATCH PHP_FE(fnmatch, arginfo_fnmatch) #endif /* functions from fsock.c */ PHP_FE(fsockopen, arginfo_fsockopen) PHP_FE(pfsockopen, arginfo_pfsockopen) /* functions from pack.c */ PHP_FE(pack, arginfo_pack) PHP_FE(unpack, arginfo_unpack) /* functions from browscap.c */ PHP_FE(get_browser, arginfo_get_browser) #if HAVE_CRYPT /* functions from crypt.c */ PHP_FE(crypt, arginfo_crypt) #endif /* functions from dir.c */ PHP_FE(opendir, arginfo_opendir) PHP_FE(closedir, arginfo_closedir) PHP_FE(chdir, arginfo_chdir) #if defined(HAVE_CHROOT) && !defined(ZTS) && ENABLE_CHROOT_FUNC PHP_FE(chroot, arginfo_chroot) #endif PHP_FE(getcwd, arginfo_getcwd) PHP_FE(rewinddir, arginfo_rewinddir) PHP_NAMED_FE(readdir, php_if_readdir, arginfo_readdir) PHP_FALIAS(dir, getdir, arginfo_dir) PHP_FE(scandir, arginfo_scandir) #ifdef HAVE_GLOB PHP_FE(glob, arginfo_glob) #endif /* functions from filestat.c */ PHP_FE(fileatime, arginfo_fileatime) PHP_FE(filectime, arginfo_filectime) PHP_FE(filegroup, arginfo_filegroup) PHP_FE(fileinode, arginfo_fileinode) PHP_FE(filemtime, arginfo_filemtime) PHP_FE(fileowner, arginfo_fileowner) PHP_FE(fileperms, arginfo_fileperms) PHP_FE(filesize, arginfo_filesize) PHP_FE(filetype, arginfo_filetype) PHP_FE(file_exists, arginfo_file_exists) PHP_FE(is_writable, arginfo_is_writable) PHP_FALIAS(is_writeable, is_writable, arginfo_is_writable) PHP_FE(is_readable, arginfo_is_readable) PHP_FE(is_executable, arginfo_is_executable) PHP_FE(is_file, arginfo_is_file) PHP_FE(is_dir, arginfo_is_dir) PHP_FE(is_link, arginfo_is_link) PHP_NAMED_FE(stat, php_if_stat, arginfo_stat) PHP_NAMED_FE(lstat, php_if_lstat, arginfo_lstat) #ifndef NETWARE PHP_FE(chown, arginfo_chown) PHP_FE(chgrp, arginfo_chgrp) #endif #if HAVE_LCHOWN PHP_FE(lchown, arginfo_lchown) #endif #if HAVE_LCHOWN PHP_FE(lchgrp, arginfo_lchgrp) #endif PHP_FE(chmod, arginfo_chmod) #if HAVE_UTIME PHP_FE(touch, arginfo_touch) #endif PHP_FE(clearstatcache, arginfo_clearstatcache) PHP_FE(disk_total_space, arginfo_disk_total_space) PHP_FE(disk_free_space, arginfo_disk_free_space) PHP_FALIAS(diskfreespace, disk_free_space, arginfo_disk_free_space) PHP_FE(realpath_cache_size, arginfo_realpath_cache_size) PHP_FE(realpath_cache_get, arginfo_realpath_cache_get) /* functions from mail.c */ PHP_FE(mail, arginfo_mail) PHP_FE(ezmlm_hash, arginfo_ezmlm_hash) /* functions from syslog.c */ #ifdef HAVE_SYSLOG_H PHP_FE(openlog, arginfo_openlog) PHP_FE(syslog, arginfo_syslog) PHP_FE(closelog, arginfo_closelog) #endif /* functions from lcg.c */ PHP_FE(lcg_value, arginfo_lcg_value) /* functions from metaphone.c */ PHP_FE(metaphone, arginfo_metaphone) /* functions from output.c */ PHP_FE(ob_start, arginfo_ob_start) PHP_FE(ob_flush, arginfo_ob_flush) PHP_FE(ob_clean, arginfo_ob_clean) PHP_FE(ob_end_flush, arginfo_ob_end_flush) PHP_FE(ob_end_clean, arginfo_ob_end_clean) PHP_FE(ob_get_flush, arginfo_ob_get_flush) PHP_FE(ob_get_clean, arginfo_ob_get_clean) PHP_FE(ob_get_length, arginfo_ob_get_length) PHP_FE(ob_get_level, arginfo_ob_get_level) PHP_FE(ob_get_status, arginfo_ob_get_status) PHP_FE(ob_get_contents, arginfo_ob_get_contents) PHP_FE(ob_implicit_flush, arginfo_ob_implicit_flush) PHP_FE(ob_list_handlers, arginfo_ob_list_handlers) /* functions from array.c */ PHP_FE(ksort, arginfo_ksort) PHP_FE(krsort, arginfo_krsort) PHP_FE(natsort, arginfo_natsort) PHP_FE(natcasesort, arginfo_natcasesort) PHP_FE(asort, arginfo_asort) PHP_FE(arsort, arginfo_arsort) PHP_FE(sort, arginfo_sort) PHP_FE(rsort, arginfo_rsort) PHP_FE(usort, arginfo_usort) PHP_FE(uasort, arginfo_uasort) PHP_FE(uksort, arginfo_uksort) PHP_FE(shuffle, arginfo_shuffle) PHP_FE(array_walk, arginfo_array_walk) PHP_FE(array_walk_recursive, arginfo_array_walk_recursive) PHP_FE(count, arginfo_count) PHP_FE(end, arginfo_end) PHP_FE(prev, arginfo_prev) PHP_FE(next, arginfo_next) PHP_FE(reset, arginfo_reset) PHP_FE(current, arginfo_current) PHP_FE(key, arginfo_key) PHP_FE(min, arginfo_min) PHP_FE(max, arginfo_max) PHP_FE(in_array, arginfo_in_array) PHP_FE(array_search, arginfo_array_search) PHP_FE(extract, arginfo_extract) PHP_FE(compact, arginfo_compact) PHP_FE(array_fill, arginfo_array_fill) PHP_FE(array_fill_keys, arginfo_array_fill_keys) PHP_FE(range, arginfo_range) PHP_FE(array_multisort, arginfo_array_multisort) PHP_FE(array_push, arginfo_array_push) PHP_FE(array_pop, arginfo_array_pop) PHP_FE(array_shift, arginfo_array_shift) PHP_FE(array_unshift, arginfo_array_unshift) PHP_FE(array_splice, arginfo_array_splice) PHP_FE(array_slice, arginfo_array_slice) PHP_FE(array_merge, arginfo_array_merge) PHP_FE(array_merge_recursive, arginfo_array_merge_recursive) PHP_FE(array_replace, arginfo_array_replace) PHP_FE(array_replace_recursive, arginfo_array_replace_recursive) PHP_FE(array_keys, arginfo_array_keys) PHP_FE(array_values, arginfo_array_values) PHP_FE(array_count_values, arginfo_array_count_values) PHP_FE(array_reverse, arginfo_array_reverse) PHP_FE(array_reduce, arginfo_array_reduce) PHP_FE(array_pad, arginfo_array_pad) PHP_FE(array_flip, arginfo_array_flip) PHP_FE(array_change_key_case, arginfo_array_change_key_case) PHP_FE(array_rand, arginfo_array_rand) PHP_FE(array_unique, arginfo_array_unique) PHP_FE(array_intersect, arginfo_array_intersect) PHP_FE(array_intersect_key, arginfo_array_intersect_key) PHP_FE(array_intersect_ukey, arginfo_array_intersect_ukey) PHP_FE(array_uintersect, arginfo_array_uintersect) PHP_FE(array_intersect_assoc, arginfo_array_intersect_assoc) PHP_FE(array_uintersect_assoc, arginfo_array_uintersect_assoc) PHP_FE(array_intersect_uassoc, arginfo_array_intersect_uassoc) PHP_FE(array_uintersect_uassoc, arginfo_array_uintersect_uassoc) PHP_FE(array_diff, arginfo_array_diff) PHP_FE(array_diff_key, arginfo_array_diff_key) PHP_FE(array_diff_ukey, arginfo_array_diff_ukey) PHP_FE(array_udiff, arginfo_array_udiff) PHP_FE(array_diff_assoc, arginfo_array_diff_assoc) PHP_FE(array_udiff_assoc, arginfo_array_udiff_assoc) PHP_FE(array_diff_uassoc, arginfo_array_diff_uassoc) PHP_FE(array_udiff_uassoc, arginfo_array_udiff_uassoc) PHP_FE(array_sum, arginfo_array_sum) PHP_FE(array_product, arginfo_array_product) PHP_FE(array_filter, arginfo_array_filter) PHP_FE(array_map, arginfo_array_map) PHP_FE(array_chunk, arginfo_array_chunk) PHP_FE(array_combine, arginfo_array_combine) PHP_FE(array_key_exists, arginfo_array_key_exists) /* aliases from array.c */ PHP_FALIAS(pos, current, arginfo_current) PHP_FALIAS(sizeof, count, arginfo_count) PHP_FALIAS(key_exists, array_key_exists, arginfo_array_key_exists) /* functions from assert.c */ PHP_FE(assert, arginfo_assert) PHP_FE(assert_options, arginfo_assert_options) /* functions from versioning.c */ PHP_FE(version_compare, arginfo_version_compare) /* functions from ftok.c*/ #if HAVE_FTOK PHP_FE(ftok, arginfo_ftok) #endif PHP_FE(str_rot13, arginfo_str_rot13) PHP_FE(stream_get_filters, arginfo_stream_get_filters) PHP_FE(stream_filter_register, arginfo_stream_filter_register) PHP_FE(stream_bucket_make_writeable, arginfo_stream_bucket_make_writeable) PHP_FE(stream_bucket_prepend, arginfo_stream_bucket_prepend) PHP_FE(stream_bucket_append, arginfo_stream_bucket_append) PHP_FE(stream_bucket_new, arginfo_stream_bucket_new) PHP_FE(output_add_rewrite_var, arginfo_output_add_rewrite_var) PHP_FE(output_reset_rewrite_vars, arginfo_output_reset_rewrite_vars) PHP_FE(sys_get_temp_dir, arginfo_sys_get_temp_dir) PHP_FE_END }; /* }}} */ static const zend_module_dep standard_deps[] = { /* {{{ */ ZEND_MOD_OPTIONAL("session") ZEND_MOD_END }; /* }}} */ zend_module_entry basic_functions_module = { /* {{{ */ STANDARD_MODULE_HEADER_EX, NULL, standard_deps, "standard", /* extension name */ basic_functions, /* function list */ PHP_MINIT(basic), /* process startup */ PHP_MSHUTDOWN(basic), /* process shutdown */ PHP_RINIT(basic), /* request startup */ PHP_RSHUTDOWN(basic), /* request shutdown */ PHP_MINFO(basic), /* extension info */ PHP_VERSION, /* extension version */ STANDARD_MODULE_PROPERTIES }; /* }}} */ #if defined(HAVE_PUTENV) static void php_putenv_destructor(putenv_entry *pe) /* {{{ */ { if (pe->previous_value) { #if _MSC_VER >= 1300 /* VS.Net has a bug in putenv() when setting a variable that * is already set; if the SetEnvironmentVariable() API call * fails, the Crt will double free() a string. * We try to avoid this by setting our own value first */ SetEnvironmentVariable(pe->key, "bugbug"); #endif putenv(pe->previous_value); # if defined(PHP_WIN32) efree(pe->previous_value); # endif } else { # if HAVE_UNSETENV unsetenv(pe->key); # elif defined(PHP_WIN32) SetEnvironmentVariable(pe->key, NULL); # else char **env; for (env = environ; env != NULL && *env != NULL; env++) { if (!strncmp(*env, pe->key, pe->key_len) && (*env)[pe->key_len] == '=') { /* found it */ *env = ""; break; } } # endif } #ifdef HAVE_TZSET /* don't forget to reset the various libc globals that * we might have changed by an earlier call to tzset(). */ if (!strncmp(pe->key, "TZ", pe->key_len)) { tzset(); } #endif efree(pe->putenv_string); efree(pe->key); } /* }}} */ #endif static void basic_globals_ctor(php_basic_globals *basic_globals_p TSRMLS_DC) /* {{{ */ { BG(rand_is_seeded) = 0; BG(mt_rand_is_seeded) = 0; BG(umask) = -1; BG(next) = NULL; BG(left) = -1; BG(user_tick_functions) = NULL; BG(user_filter_map) = NULL; BG(serialize_lock) = 0; memset(&BG(serialize), 0, sizeof(BG(serialize))); memset(&BG(unserialize), 0, sizeof(BG(unserialize))); memset(&BG(url_adapt_state_ex), 0, sizeof(BG(url_adapt_state_ex))); #if defined(_REENTRANT) && defined(HAVE_MBRLEN) && defined(HAVE_MBSTATE_T) memset(&BG(mblen_state), 0, sizeof(BG(mblen_state))); #endif BG(incomplete_class) = incomplete_class_entry; BG(page_uid) = -1; BG(page_gid) = -1; } /* }}} */ static void basic_globals_dtor(php_basic_globals *basic_globals_p TSRMLS_DC) /* {{{ */ { if (BG(url_adapt_state_ex).tags) { zend_hash_destroy(BG(url_adapt_state_ex).tags); free(BG(url_adapt_state_ex).tags); } } /* }}} */ #define PHP_DOUBLE_INFINITY_HIGH 0x7ff00000 #define PHP_DOUBLE_QUIET_NAN_HIGH 0xfff80000 PHPAPI double php_get_nan(void) /* {{{ */ { #if HAVE_HUGE_VAL_NAN return HUGE_VAL + -HUGE_VAL; #elif defined(__i386__) || defined(_X86_) || defined(ALPHA) || defined(_ALPHA) || defined(__alpha) double val = 0.0; ((php_uint32*)&val)[1] = PHP_DOUBLE_QUIET_NAN_HIGH; ((php_uint32*)&val)[0] = 0; return val; #elif HAVE_ATOF_ACCEPTS_NAN return atof("NAN"); #else return 0.0/0.0; #endif } /* }}} */ PHPAPI double php_get_inf(void) /* {{{ */ { #if HAVE_HUGE_VAL_INF return HUGE_VAL; #elif defined(__i386__) || defined(_X86_) || defined(ALPHA) || defined(_ALPHA) || defined(__alpha) double val = 0.0; ((php_uint32*)&val)[1] = PHP_DOUBLE_INFINITY_HIGH; ((php_uint32*)&val)[0] = 0; return val; #elif HAVE_ATOF_ACCEPTS_INF return atof("INF"); #else return 1.0/0.0; #endif } /* }}} */ #define BASIC_MINIT_SUBMODULE(module) \ if (PHP_MINIT(module)(INIT_FUNC_ARGS_PASSTHRU) == SUCCESS) {\ BASIC_ADD_SUBMODULE(module); \ } #define BASIC_ADD_SUBMODULE(module) \ zend_hash_add_empty_element(&basic_submodules, #module, strlen(#module)); #define BASIC_RINIT_SUBMODULE(module) \ if (zend_hash_exists(&basic_submodules, #module, strlen(#module))) { \ PHP_RINIT(module)(INIT_FUNC_ARGS_PASSTHRU); \ } #define BASIC_MINFO_SUBMODULE(module) \ if (zend_hash_exists(&basic_submodules, #module, strlen(#module))) { \ PHP_MINFO(module)(ZEND_MODULE_INFO_FUNC_ARGS_PASSTHRU); \ } #define BASIC_RSHUTDOWN_SUBMODULE(module) \ if (zend_hash_exists(&basic_submodules, #module, strlen(#module))) { \ PHP_RSHUTDOWN(module)(SHUTDOWN_FUNC_ARGS_PASSTHRU); \ } #define BASIC_MSHUTDOWN_SUBMODULE(module) \ if (zend_hash_exists(&basic_submodules, #module, strlen(#module))) { \ PHP_MSHUTDOWN(module)(SHUTDOWN_FUNC_ARGS_PASSTHRU); \ } PHP_MINIT_FUNCTION(basic) /* {{{ */ { #ifdef ZTS ts_allocate_id(&basic_globals_id, sizeof(php_basic_globals), (ts_allocate_ctor) basic_globals_ctor, (ts_allocate_dtor) basic_globals_dtor); #ifdef PHP_WIN32 ts_allocate_id(&php_win32_core_globals_id, sizeof(php_win32_core_globals), (ts_allocate_ctor)php_win32_core_globals_ctor, (ts_allocate_dtor)php_win32_core_globals_dtor ); #endif #else basic_globals_ctor(&basic_globals TSRMLS_CC); #ifdef PHP_WIN32 php_win32_core_globals_ctor(&the_php_win32_core_globals TSRMLS_CC); #endif #endif zend_hash_init(&basic_submodules, 0, NULL, NULL, 1); BG(incomplete_class) = incomplete_class_entry = php_create_incomplete_class(TSRMLS_C); REGISTER_LONG_CONSTANT("CONNECTION_ABORTED", PHP_CONNECTION_ABORTED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("CONNECTION_NORMAL", PHP_CONNECTION_NORMAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("CONNECTION_TIMEOUT", PHP_CONNECTION_TIMEOUT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INI_USER", ZEND_INI_USER, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INI_PERDIR", ZEND_INI_PERDIR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INI_SYSTEM", ZEND_INI_SYSTEM, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INI_ALL", ZEND_INI_ALL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INI_SCANNER_NORMAL", ZEND_INI_SCANNER_NORMAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INI_SCANNER_RAW", ZEND_INI_SCANNER_RAW, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_URL_SCHEME", PHP_URL_SCHEME, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_URL_HOST", PHP_URL_HOST, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_URL_PORT", PHP_URL_PORT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_URL_USER", PHP_URL_USER, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_URL_PASS", PHP_URL_PASS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_URL_PATH", PHP_URL_PATH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_URL_QUERY", PHP_URL_QUERY, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_URL_FRAGMENT", PHP_URL_FRAGMENT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_QUERY_RFC1738", PHP_QUERY_RFC1738, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_QUERY_RFC3986", PHP_QUERY_RFC3986, CONST_CS | CONST_PERSISTENT); #define REGISTER_MATH_CONSTANT(x) REGISTER_DOUBLE_CONSTANT(#x, x, CONST_CS | CONST_PERSISTENT) REGISTER_MATH_CONSTANT(M_E); REGISTER_MATH_CONSTANT(M_LOG2E); REGISTER_MATH_CONSTANT(M_LOG10E); REGISTER_MATH_CONSTANT(M_LN2); REGISTER_MATH_CONSTANT(M_LN10); REGISTER_MATH_CONSTANT(M_PI); REGISTER_MATH_CONSTANT(M_PI_2); REGISTER_MATH_CONSTANT(M_PI_4); REGISTER_MATH_CONSTANT(M_1_PI); REGISTER_MATH_CONSTANT(M_2_PI); REGISTER_MATH_CONSTANT(M_SQRTPI); REGISTER_MATH_CONSTANT(M_2_SQRTPI); REGISTER_MATH_CONSTANT(M_LNPI); REGISTER_MATH_CONSTANT(M_EULER); REGISTER_MATH_CONSTANT(M_SQRT2); REGISTER_MATH_CONSTANT(M_SQRT1_2); REGISTER_MATH_CONSTANT(M_SQRT3); REGISTER_DOUBLE_CONSTANT("INF", php_get_inf(), CONST_CS | CONST_PERSISTENT); REGISTER_DOUBLE_CONSTANT("NAN", php_get_nan(), CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_ROUND_HALF_UP", PHP_ROUND_HALF_UP, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_ROUND_HALF_DOWN", PHP_ROUND_HALF_DOWN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_ROUND_HALF_EVEN", PHP_ROUND_HALF_EVEN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_ROUND_HALF_ODD", PHP_ROUND_HALF_ODD, CONST_CS | CONST_PERSISTENT); #if ENABLE_TEST_CLASS test_class_startup(); #endif register_phpinfo_constants(INIT_FUNC_ARGS_PASSTHRU); register_html_constants(INIT_FUNC_ARGS_PASSTHRU); register_string_constants(INIT_FUNC_ARGS_PASSTHRU); BASIC_ADD_SUBMODULE(dl) BASIC_ADD_SUBMODULE(mail) BASIC_MINIT_SUBMODULE(file) BASIC_MINIT_SUBMODULE(pack) BASIC_MINIT_SUBMODULE(browscap) BASIC_MINIT_SUBMODULE(standard_filters) BASIC_MINIT_SUBMODULE(user_filters) #if defined(HAVE_LOCALECONV) && defined(ZTS) BASIC_MINIT_SUBMODULE(localeconv) #endif #if defined(HAVE_NL_LANGINFO) BASIC_MINIT_SUBMODULE(nl_langinfo) #endif #if HAVE_CRYPT BASIC_MINIT_SUBMODULE(crypt) #endif BASIC_MINIT_SUBMODULE(lcg) BASIC_MINIT_SUBMODULE(dir) #ifdef HAVE_SYSLOG_H BASIC_MINIT_SUBMODULE(syslog) #endif BASIC_MINIT_SUBMODULE(array) BASIC_MINIT_SUBMODULE(assert) BASIC_MINIT_SUBMODULE(url_scanner_ex) #ifdef PHP_CAN_SUPPORT_PROC_OPEN BASIC_MINIT_SUBMODULE(proc_open) #endif BASIC_MINIT_SUBMODULE(user_streams) BASIC_MINIT_SUBMODULE(imagetypes) php_register_url_stream_wrapper("php", &php_stream_php_wrapper TSRMLS_CC); php_register_url_stream_wrapper("file", &php_plain_files_wrapper TSRMLS_CC); #ifdef HAVE_GLOB php_register_url_stream_wrapper("glob", &php_glob_stream_wrapper TSRMLS_CC); #endif php_register_url_stream_wrapper("data", &php_stream_rfc2397_wrapper TSRMLS_CC); #ifndef PHP_CURL_URL_WRAPPERS php_register_url_stream_wrapper("http", &php_stream_http_wrapper TSRMLS_CC); php_register_url_stream_wrapper("ftp", &php_stream_ftp_wrapper TSRMLS_CC); #endif #if defined(PHP_WIN32) || (HAVE_DNS_SEARCH_FUNC && !(defined(__BEOS__) || defined(NETWARE))) # if defined(PHP_WIN32) || HAVE_FULL_DNS_FUNCS BASIC_MINIT_SUBMODULE(dns) # endif #endif return SUCCESS; } /* }}} */ PHP_MSHUTDOWN_FUNCTION(basic) /* {{{ */ { #ifdef HAVE_SYSLOG_H PHP_MSHUTDOWN(syslog)(SHUTDOWN_FUNC_ARGS_PASSTHRU); #endif #ifdef ZTS ts_free_id(basic_globals_id); #ifdef PHP_WIN32 ts_free_id(php_win32_core_globals_id); #endif #else basic_globals_dtor(&basic_globals TSRMLS_CC); #ifdef PHP_WIN32 php_win32_core_globals_dtor(&the_php_win32_core_globals TSRMLS_CC); #endif #endif php_unregister_url_stream_wrapper("php" TSRMLS_CC); #ifndef PHP_CURL_URL_WRAPPERS php_unregister_url_stream_wrapper("http" TSRMLS_CC); php_unregister_url_stream_wrapper("ftp" TSRMLS_CC); #endif BASIC_MSHUTDOWN_SUBMODULE(browscap) BASIC_MSHUTDOWN_SUBMODULE(array) BASIC_MSHUTDOWN_SUBMODULE(assert) BASIC_MSHUTDOWN_SUBMODULE(url_scanner_ex) BASIC_MSHUTDOWN_SUBMODULE(file) BASIC_MSHUTDOWN_SUBMODULE(standard_filters) #if defined(HAVE_LOCALECONV) && defined(ZTS) BASIC_MSHUTDOWN_SUBMODULE(localeconv) #endif #if HAVE_CRYPT BASIC_MSHUTDOWN_SUBMODULE(crypt) #endif zend_hash_destroy(&basic_submodules); return SUCCESS; } /* }}} */ PHP_RINIT_FUNCTION(basic) /* {{{ */ { memset(BG(strtok_table), 0, 256); BG(strtok_string) = NULL; BG(strtok_zval) = NULL; BG(strtok_last) = NULL; BG(locale_string) = NULL; BG(array_walk_fci) = empty_fcall_info; BG(array_walk_fci_cache) = empty_fcall_info_cache; BG(user_compare_fci) = empty_fcall_info; BG(user_compare_fci_cache) = empty_fcall_info_cache; BG(page_uid) = -1; BG(page_gid) = -1; BG(page_inode) = -1; BG(page_mtime) = -1; #ifdef HAVE_PUTENV if (zend_hash_init(&BG(putenv_ht), 1, NULL, (void (*)(void *)) php_putenv_destructor, 0) == FAILURE) { return FAILURE; } #endif BG(user_shutdown_function_names) = NULL; PHP_RINIT(filestat)(INIT_FUNC_ARGS_PASSTHRU); #ifdef HAVE_SYSLOG_H BASIC_RINIT_SUBMODULE(syslog) #endif BASIC_RINIT_SUBMODULE(dir) BASIC_RINIT_SUBMODULE(url_scanner_ex) /* Setup default context */ FG(default_context) = NULL; /* Default to global wrappers only */ FG(stream_wrappers) = NULL; /* Default to global filters only */ FG(stream_filters) = NULL; FG(wrapper_errors) = NULL; return SUCCESS; } /* }}} */ PHP_RSHUTDOWN_FUNCTION(basic) /* {{{ */ { if (BG(strtok_zval)) { zval_ptr_dtor(&BG(strtok_zval)); } BG(strtok_string) = NULL; BG(strtok_zval) = NULL; #ifdef HAVE_PUTENV zend_hash_destroy(&BG(putenv_ht)); #endif if (BG(umask) != -1) { umask(BG(umask)); } /* Check if locale was changed and change it back * to the value in startup environment */ if (BG(locale_string) != NULL) { setlocale(LC_ALL, "C"); setlocale(LC_CTYPE, ""); zend_update_current_locale(); } STR_FREE(BG(locale_string)); BG(locale_string) = NULL; /* FG(stream_wrappers) and FG(stream_filters) are destroyed * during php_request_shutdown() */ PHP_RSHUTDOWN(filestat)(SHUTDOWN_FUNC_ARGS_PASSTHRU); #ifdef HAVE_SYSLOG_H #ifdef PHP_WIN32 BASIC_RSHUTDOWN_SUBMODULE(syslog)(SHUTDOWN_FUNC_ARGS_PASSTHRU); #endif #endif BASIC_RSHUTDOWN_SUBMODULE(assert) BASIC_RSHUTDOWN_SUBMODULE(url_scanner_ex) BASIC_RSHUTDOWN_SUBMODULE(streams) #ifdef PHP_WIN32 BASIC_RSHUTDOWN_SUBMODULE(win32_core_globals) #endif if (BG(user_tick_functions)) { zend_llist_destroy(BG(user_tick_functions)); efree(BG(user_tick_functions)); BG(user_tick_functions) = NULL; } BASIC_RSHUTDOWN_SUBMODULE(user_filters) BASIC_RSHUTDOWN_SUBMODULE(browscap) BG(page_uid) = -1; BG(page_gid) = -1; return SUCCESS; } /* }}} */ PHP_MINFO_FUNCTION(basic) /* {{{ */ { php_info_print_table_start(); BASIC_MINFO_SUBMODULE(dl) BASIC_MINFO_SUBMODULE(mail) php_info_print_table_end(); BASIC_MINFO_SUBMODULE(assert) } /* }}} */ /* {{{ proto mixed constant(string const_name) Given the name of a constant this function will return the constant's associated value */ PHP_FUNCTION(constant) { char *const_name; int const_name_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &const_name, &const_name_len) == FAILURE) { return; } if (!zend_get_constant_ex(const_name, const_name_len, return_value, NULL, ZEND_FETCH_CLASS_SILENT TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't find constant %s", const_name); RETURN_NULL(); } } /* }}} */ #ifdef HAVE_INET_NTOP /* {{{ proto string inet_ntop(string in_addr) Converts a packed inet address to a human readable IP address string */ PHP_NAMED_FUNCTION(php_inet_ntop) { char *address; int address_len, af = AF_INET; char buffer[40]; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &address, &address_len) == FAILURE) { RETURN_FALSE; } #ifdef HAVE_IPV6 if (address_len == 16) { af = AF_INET6; } else #endif if (address_len != 4) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid in_addr value"); RETURN_FALSE; } if (!inet_ntop(af, address, buffer, sizeof(buffer))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "An unknown error occured"); RETURN_FALSE; } RETURN_STRING(buffer, 1); } /* }}} */ #endif /* HAVE_INET_NTOP */ #ifdef HAVE_INET_PTON /* {{{ proto string inet_pton(string ip_address) Converts a human readable IP address to a packed binary string */ PHP_NAMED_FUNCTION(php_inet_pton) { int ret, af = AF_INET; char *address; int address_len; char buffer[17]; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &address, &address_len) == FAILURE) { RETURN_FALSE; } memset(buffer, 0, sizeof(buffer)); #ifdef HAVE_IPV6 if (strchr(address, ':')) { af = AF_INET6; } else #endif if (!strchr(address, '.')) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unrecognized address %s", address); RETURN_FALSE; } ret = inet_pton(af, address, buffer); if (ret <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unrecognized address %s", address); RETURN_FALSE; } RETURN_STRINGL(buffer, af == AF_INET ? 4 : 16, 1); } /* }}} */ #endif /* HAVE_INET_PTON */ /* {{{ proto int ip2long(string ip_address) Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address */ PHP_FUNCTION(ip2long) { char *addr; int addr_len; #ifdef HAVE_INET_PTON struct in_addr ip; #else unsigned long int ip; #endif if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &addr, &addr_len) == FAILURE) { return; } #ifdef HAVE_INET_PTON if (addr_len == 0 || inet_pton(AF_INET, addr, &ip) != 1) { RETURN_FALSE; } RETURN_LONG(ntohl(ip.s_addr)); #else if (addr_len == 0 || (ip = inet_addr(addr)) == INADDR_NONE) { /* The only special case when we should return -1 ourselves, * because inet_addr() considers it wrong. We return 0xFFFFFFFF and * not -1 or ~0 because of 32/64bit issues. */ if (addr_len == sizeof("255.255.255.255") - 1 && !memcmp(addr, "255.255.255.255", sizeof("255.255.255.255") - 1) ) { RETURN_LONG(0xFFFFFFFF); } RETURN_FALSE; } RETURN_LONG(ntohl(ip)); #endif } /* }}} */ /* {{{ proto string long2ip(int proper_address) Converts an (IPv4) Internet network address into a string in Internet standard dotted format */ PHP_FUNCTION(long2ip) { /* "It's a long but it's not, PHP ints are signed */ char *ip; int ip_len; unsigned long n; struct in_addr myaddr; #ifdef HAVE_INET_PTON char str[40]; #endif if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &ip, &ip_len) == FAILURE) { return; } n = strtoul(ip, NULL, 0); myaddr.s_addr = htonl(n); #ifdef HAVE_INET_PTON if (inet_ntop(AF_INET, &myaddr, str, sizeof(str))) { RETURN_STRING(str, 1); } else { RETURN_FALSE; } #else RETURN_STRING(inet_ntoa(myaddr), 1); #endif } /* }}} */ /******************** * System Functions * ********************/ /* {{{ proto string getenv(string varname) Get the value of an environment variable */ PHP_FUNCTION(getenv) { char *ptr, *str; int str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &str, &str_len) == FAILURE) { RETURN_FALSE; } /* SAPI method returns an emalloc()'d string */ ptr = sapi_getenv(str, str_len TSRMLS_CC); if (ptr) { RETURN_STRING(ptr, 0); } #ifdef PHP_WIN32 { char dummybuf; int size; SetLastError(0); /*If the given bugger is not large enough to hold the data, the return value is the buffer size, in characters, required to hold the string and its terminating null character. We use this return value to alloc the final buffer. */ size = GetEnvironmentVariableA(str, &dummybuf, 0); if (GetLastError() == ERROR_ENVVAR_NOT_FOUND) { /* The environment variable doesn't exist. */ RETURN_FALSE; } if (size == 0) { /* env exists, but it is empty */ RETURN_EMPTY_STRING(); } ptr = emalloc(size); size = GetEnvironmentVariableA(str, ptr, size); if (size == 0) { /* has been removed between the two calls */ efree(ptr); RETURN_EMPTY_STRING(); } else { RETURN_STRING(ptr, 0); } } #else /* system method returns a const */ ptr = getenv(str); if (ptr) { RETURN_STRING(ptr, 1); } #endif RETURN_FALSE; } /* }}} */ #ifdef HAVE_PUTENV /* {{{ proto bool putenv(string setting) Set the value of an environment variable */ PHP_FUNCTION(putenv) { char *setting; int setting_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &setting, &setting_len) == FAILURE) { return; } if (setting_len) { char *p, **env; putenv_entry pe; #ifdef PHP_WIN32 char *value = NULL; int equals = 0; int error_code; #endif pe.putenv_string = estrndup(setting, setting_len); pe.key = estrndup(setting, setting_len); if ((p = strchr(pe.key, '='))) { /* nullify the '=' if there is one */ *p = '\0'; #ifdef PHP_WIN32 equals = 1; #endif } pe.key_len = strlen(pe.key); #ifdef PHP_WIN32 if (equals) { if (pe.key_len < setting_len - 1) { value = p + 1; } else { /* empty string*/ value = p; } } #endif zend_hash_del(&BG(putenv_ht), pe.key, pe.key_len+1); /* find previous value */ pe.previous_value = NULL; for (env = environ; env != NULL && *env != NULL; env++) { if (!strncmp(*env, pe.key, pe.key_len) && (*env)[pe.key_len] == '=') { /* found it */ #if defined(PHP_WIN32) /* must copy previous value because MSVCRT's putenv can free the string without notice */ pe.previous_value = estrdup(*env); #else pe.previous_value = *env; #endif break; } } #if HAVE_UNSETENV if (!p) { /* no '=' means we want to unset it */ unsetenv(pe.putenv_string); } if (!p || putenv(pe.putenv_string) == 0) { /* success */ #else # ifndef PHP_WIN32 if (putenv(pe.putenv_string) == 0) { /* success */ # else error_code = SetEnvironmentVariable(pe.key, value); # if _MSC_VER < 1500 /* Yet another VC6 bug, unset may return env not found */ if (error_code != 0 || (error_code == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND)) { # else if (error_code != 0) { /* success */ # endif # endif #endif zend_hash_add(&BG(putenv_ht), pe.key, pe.key_len + 1, (void **) &pe, sizeof(putenv_entry), NULL); #ifdef HAVE_TZSET if (!strncmp(pe.key, "TZ", pe.key_len)) { tzset(); } #endif RETURN_TRUE; } else { efree(pe.putenv_string); efree(pe.key); RETURN_FALSE; } } php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid parameter syntax"); RETURN_FALSE; } /* }}} */ #endif /* {{{ free_argv() Free the memory allocated to an argv array. */ static void free_argv(char **argv, int argc) { int i; if (argv) { for (i = 0; i < argc; i++) { if (argv[i]) { efree(argv[i]); } } efree(argv); } } /* }}} */ /* {{{ free_longopts() Free the memory allocated to an longopt array. */ static void free_longopts(opt_struct *longopts) { opt_struct *p; if (longopts) { for (p = longopts; p && p->opt_char != '-'; p++) { if (p->opt_name != NULL) { efree((char *)(p->opt_name)); } } } } /* }}} */ /* {{{ parse_opts() Convert the typical getopt input characters to the php_getopt struct array */ static int parse_opts(char * opts, opt_struct ** result) { opt_struct * paras = NULL; unsigned int i, count = 0; for (i = 0; i < strlen(opts); i++) { if ((opts[i] >= 48 && opts[i] <= 57) || (opts[i] >= 65 && opts[i] <= 90) || (opts[i] >= 97 && opts[i] <= 122) ) { count++; } } paras = safe_emalloc(sizeof(opt_struct), count, 0); memset(paras, 0, sizeof(opt_struct) * count); *result = paras; while ( (*opts >= 48 && *opts <= 57) || /* 0 - 9 */ (*opts >= 65 && *opts <= 90) || /* A - Z */ (*opts >= 97 && *opts <= 122) /* a - z */ ) { paras->opt_char = *opts; paras->need_param = (*(++opts) == ':') ? 1 : 0; paras->opt_name = NULL; if (paras->need_param == 1) { opts++; if (*opts == ':') { paras->need_param++; opts++; } } paras++; } return count; } /* }}} */ /* {{{ proto array getopt(string options [, array longopts]) Get options from the command line argument list */ PHP_FUNCTION(getopt) { char *options = NULL, **argv = NULL; char opt[2] = { '\0' }; char *optname; int argc = 0, options_len = 0, len, o; char *php_optarg = NULL; int php_optind = 1; zval *val, **args = NULL, *p_longopts = NULL; int optname_len = 0; opt_struct *opts, *orig_opts; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|a", &options, &options_len, &p_longopts) == FAILURE) { RETURN_FALSE; } /* Get argv from the global symbol table. We calculate argc ourselves * in order to be on the safe side, even though it is also available * from the symbol table. */ if (PG(http_globals)[TRACK_VARS_SERVER] && (zend_hash_find(HASH_OF(PG(http_globals)[TRACK_VARS_SERVER]), "argv", sizeof("argv"), (void **) &args) != FAILURE || zend_hash_find(&EG(symbol_table), "argv", sizeof("argv"), (void **) &args) != FAILURE) && Z_TYPE_PP(args) == IS_ARRAY ) { int pos = 0; zval **entry; argc = zend_hash_num_elements(Z_ARRVAL_PP(args)); /* Attempt to allocate enough memory to hold all of the arguments * and a trailing NULL */ argv = (char **) safe_emalloc(sizeof(char *), (argc + 1), 0); /* Reset the array indexes. */ zend_hash_internal_pointer_reset(Z_ARRVAL_PP(args)); /* Iterate over the hash to construct the argv array. */ while (zend_hash_get_current_data(Z_ARRVAL_PP(args), (void **)&entry) == SUCCESS) { zval arg, *arg_ptr = *entry; if (Z_TYPE_PP(entry) != IS_STRING) { arg = **entry; zval_copy_ctor(&arg); convert_to_string(&arg); arg_ptr = &arg; } argv[pos++] = estrdup(Z_STRVAL_P(arg_ptr)); if (arg_ptr != *entry) { zval_dtor(&arg); } zend_hash_move_forward(Z_ARRVAL_PP(args)); } /* The C Standard requires argv[argc] to be NULL - this might * keep some getopt implementations happy. */ argv[argc] = NULL; } else { /* Return false if we can't find argv. */ RETURN_FALSE; } len = parse_opts(options, &opts); if (p_longopts) { int count; zval **entry; count = zend_hash_num_elements(Z_ARRVAL_P(p_longopts)); /* the first <len> slots are filled by the one short ops * we now extend our array and jump to the new added structs */ opts = (opt_struct *) erealloc(opts, sizeof(opt_struct) * (len + count + 1)); orig_opts = opts; opts += len; memset(opts, 0, count * sizeof(opt_struct)); /* Reset the array indexes. */ zend_hash_internal_pointer_reset(Z_ARRVAL_P(p_longopts)); /* Iterate over the hash to construct the argv array. */ while (zend_hash_get_current_data(Z_ARRVAL_P(p_longopts), (void **)&entry) == SUCCESS) { zval arg, *arg_ptr = *entry; if (Z_TYPE_PP(entry) != IS_STRING) { arg = **entry; zval_copy_ctor(&arg); convert_to_string(&arg); arg_ptr = &arg; } opts->need_param = 0; opts->opt_name = estrdup(Z_STRVAL_P(arg_ptr)); len = strlen(opts->opt_name); if ((len > 0) && (opts->opt_name[len - 1] == ':')) { opts->need_param++; opts->opt_name[len - 1] = '\0'; if ((len > 1) && (opts->opt_name[len - 2] == ':')) { opts->need_param++; opts->opt_name[len - 2] = '\0'; } } opts->opt_char = 0; opts++; if (arg_ptr != *entry) { zval_dtor(&arg); } zend_hash_move_forward(Z_ARRVAL_P(p_longopts)); } } else { opts = (opt_struct*) erealloc(opts, sizeof(opt_struct) * (len + 1)); orig_opts = opts; opts += len; } /* php_getopt want to identify the last param */ opts->opt_char = '-'; opts->need_param = 0; opts->opt_name = NULL; /* Initialize the return value as an array. */ array_init(return_value); /* after our pointer arithmetic jump back to the first element */ opts = orig_opts; while ((o = php_getopt(argc, argv, opts, &php_optarg, &php_optind, 0, 1)) != -1) { /* Skip unknown arguments. */ if (o == '?') { continue; } /* Prepare the option character and the argument string. */ if (o == 0) { optname = opts[php_optidx].opt_name; } else { if (o == 1) { o = '-'; } opt[0] = o; optname = opt; } MAKE_STD_ZVAL(val); if (php_optarg != NULL) { /* keep the arg as binary, since the encoding is not known */ ZVAL_STRING(val, php_optarg, 1); } else { ZVAL_FALSE(val); } /* Add this option / argument pair to the result hash. */ optname_len = strlen(optname); if (!(optname_len > 1 && optname[0] == '0') && is_numeric_string(optname, optname_len, NULL, NULL, 0) == IS_LONG) { /* numeric string */ int optname_int = atoi(optname); if (zend_hash_index_find(HASH_OF(return_value), optname_int, (void **)&args) != FAILURE) { if (Z_TYPE_PP(args) != IS_ARRAY) { convert_to_array_ex(args); } zend_hash_next_index_insert(HASH_OF(*args), (void *)&val, sizeof(zval *), NULL); } else { zend_hash_index_update(HASH_OF(return_value), optname_int, &val, sizeof(zval *), NULL); } } else { /* other strings */ if (zend_hash_find(HASH_OF(return_value), optname, strlen(optname)+1, (void **)&args) != FAILURE) { if (Z_TYPE_PP(args) != IS_ARRAY) { convert_to_array_ex(args); } zend_hash_next_index_insert(HASH_OF(*args), (void *)&val, sizeof(zval *), NULL); } else { zend_hash_add(HASH_OF(return_value), optname, strlen(optname)+1, (void *)&val, sizeof(zval *), NULL); } } php_optarg = NULL; } free_longopts(orig_opts); efree(orig_opts); free_argv(argv, argc); } /* }}} */ /* {{{ proto void flush(void) Flush the output buffer */ PHP_FUNCTION(flush) { sapi_flush(TSRMLS_C); } /* }}} */ /* {{{ proto void sleep(int seconds) Delay for a given number of seconds */ PHP_FUNCTION(sleep) { long num; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &num) == FAILURE) { RETURN_FALSE; } if (num < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number of seconds must be greater than or equal to 0"); RETURN_FALSE; } #ifdef PHP_SLEEP_NON_VOID RETURN_LONG(php_sleep(num)); #else php_sleep(num); #endif } /* }}} */ /* {{{ proto void usleep(int micro_seconds) Delay for a given number of micro seconds */ PHP_FUNCTION(usleep) { #if HAVE_USLEEP long num; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &num) == FAILURE) { return; } if (num < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number of microseconds must be greater than or equal to 0"); RETURN_FALSE; } usleep(num); #endif } /* }}} */ #if HAVE_NANOSLEEP /* {{{ proto mixed time_nanosleep(long seconds, long nanoseconds) Delay for a number of seconds and nano seconds */ PHP_FUNCTION(time_nanosleep) { long tv_sec, tv_nsec; struct timespec php_req, php_rem; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll", &tv_sec, &tv_nsec) == FAILURE) { return; } php_req.tv_sec = (time_t) tv_sec; php_req.tv_nsec = tv_nsec; if (!nanosleep(&php_req, &php_rem)) { RETURN_TRUE; } else if (errno == EINTR) { array_init(return_value); add_assoc_long_ex(return_value, "seconds", sizeof("seconds"), php_rem.tv_sec); add_assoc_long_ex(return_value, "nanoseconds", sizeof("nanoseconds"), php_rem.tv_nsec); return; } else if (errno == EINVAL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "nanoseconds was not in the range 0 to 999 999 999 or seconds was negative"); } RETURN_FALSE; } /* }}} */ /* {{{ proto mixed time_sleep_until(float timestamp) Make the script sleep until the specified time */ PHP_FUNCTION(time_sleep_until) { double d_ts, c_ts; struct timeval tm; struct timespec php_req, php_rem; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "d", &d_ts) == FAILURE) { return; } if (gettimeofday((struct timeval *) &tm, NULL) != 0) { RETURN_FALSE; } c_ts = (double)(d_ts - tm.tv_sec - tm.tv_usec / 1000000.00); if (c_ts < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Sleep until to time is less than current time"); RETURN_FALSE; } php_req.tv_sec = (time_t) c_ts; if (php_req.tv_sec > c_ts) { /* rounding up occurred */ php_req.tv_sec--; } /* 1sec = 1000000000 nanoseconds */ php_req.tv_nsec = (long) ((c_ts - php_req.tv_sec) * 1000000000.00); while (nanosleep(&php_req, &php_rem)) { if (errno == EINTR) { php_req.tv_sec = php_rem.tv_sec; php_req.tv_nsec = php_rem.tv_nsec; } else { RETURN_FALSE; } } RETURN_TRUE; } /* }}} */ #endif /* {{{ proto string get_current_user(void) Get the name of the owner of the current PHP script */ PHP_FUNCTION(get_current_user) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_STRING(php_get_current_user(TSRMLS_C), 1); } /* }}} */ /* {{{ add_config_entry_cb */ static int add_config_entry_cb(zval *entry TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) { zval *retval = (zval *)va_arg(args, zval*); zval *tmp; if (Z_TYPE_P(entry) == IS_STRING) { if (hash_key->nKeyLength > 0) { add_assoc_stringl_ex(retval, hash_key->arKey, hash_key->nKeyLength, Z_STRVAL_P(entry), Z_STRLEN_P(entry), 1); } else { add_index_stringl(retval, hash_key->h, Z_STRVAL_P(entry), Z_STRLEN_P(entry), 1); } } else if (Z_TYPE_P(entry) == IS_ARRAY) { MAKE_STD_ZVAL(tmp); array_init(tmp); zend_hash_apply_with_arguments(Z_ARRVAL_P(entry) TSRMLS_CC, (apply_func_args_t) add_config_entry_cb, 1, tmp); add_assoc_zval_ex(retval, hash_key->arKey, hash_key->nKeyLength, tmp); } return 0; } /* }}} */ /* {{{ proto mixed get_cfg_var(string option_name) Get the value of a PHP configuration option */ PHP_FUNCTION(get_cfg_var) { char *varname; int varname_len; zval *retval; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &varname, &varname_len) == FAILURE) { return; } retval = cfg_get_entry(varname, varname_len + 1); if (retval) { if (Z_TYPE_P(retval) == IS_ARRAY) { array_init(return_value); zend_hash_apply_with_arguments(Z_ARRVAL_P(retval) TSRMLS_CC, (apply_func_args_t) add_config_entry_cb, 1, return_value); return; } else { RETURN_STRING(Z_STRVAL_P(retval), 1); } } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool set_magic_quotes_runtime(int new_setting) magic_quotes_runtime is not supported anymore */ PHP_FUNCTION(set_magic_quotes_runtime) { zend_bool new_setting; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "b", &new_setting) == FAILURE) { return; } if (new_setting) { php_error_docref(NULL TSRMLS_CC, E_CORE_ERROR, "magic_quotes_runtime is not supported anymore"); } RETURN_FALSE; } /* }}} */ /* {{{ proto int get_magic_quotes_runtime(void) Get the current active configuration setting of magic_quotes_runtime */ PHP_FUNCTION(get_magic_quotes_runtime) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_FALSE; } /* }}} */ /* {{{ proto int get_magic_quotes_gpc(void) Get the current active configuration setting of magic_quotes_gpc */ PHP_FUNCTION(get_magic_quotes_gpc) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_FALSE; } /* }}} */ /* 1st arg = error message 2nd arg = error option 3rd arg = optional parameters (email address or tcp address) 4th arg = used for additional headers if email error options: 0 = send to php_error_log (uses syslog or file depending on ini setting) 1 = send via email to 3rd parameter 4th option = additional headers 2 = send via tcp/ip to 3rd parameter (name or ip:port) 3 = save to file in 3rd parameter 4 = send to SAPI logger directly */ /* {{{ proto bool error_log(string message [, int message_type [, string destination [, string extra_headers]]]) Send an error message somewhere */ PHP_FUNCTION(error_log) { char *message, *opt = NULL, *headers = NULL; int message_len, opt_len = 0, headers_len = 0; int opt_err = 0, argc = ZEND_NUM_ARGS(); long erropt = 0; if (zend_parse_parameters(argc TSRMLS_CC, "s|lps", &message, &message_len, &erropt, &opt, &opt_len, &headers, &headers_len) == FAILURE) { return; } if (argc > 1) { opt_err = erropt; } if (_php_error_log_ex(opt_err, message, message_len, opt, headers TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* For BC (not binary-safe!) */ PHPAPI int _php_error_log(int opt_err, char *message, char *opt, char *headers TSRMLS_DC) /* {{{ */ { return _php_error_log_ex(opt_err, message, (opt_err == 3) ? strlen(message) : 0, opt, headers TSRMLS_CC); } /* }}} */ PHPAPI int _php_error_log_ex(int opt_err, char *message, int message_len, char *opt, char *headers TSRMLS_DC) /* {{{ */ { php_stream *stream = NULL; switch (opt_err) { case 1: /*send an email */ if (!php_mail(opt, "PHP error_log message", message, headers, NULL TSRMLS_CC)) { return FAILURE; } break; case 2: /*send to an address */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "TCP/IP option not available!"); return FAILURE; break; case 3: /*save to a file */ stream = php_stream_open_wrapper(opt, "a", IGNORE_URL_WIN | REPORT_ERRORS, NULL); if (!stream) { return FAILURE; } php_stream_write(stream, message, message_len); php_stream_close(stream); break; case 4: /* send to SAPI */ if (sapi_module.log_message) { sapi_module.log_message(message TSRMLS_CC); } else { return FAILURE; } break; default: php_log_err(message TSRMLS_CC); break; } return SUCCESS; } /* }}} */ /* {{{ proto array error_get_last() Get the last occurred error as associative array. Returns NULL if there hasn't been an error yet. */ PHP_FUNCTION(error_get_last) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "") == FAILURE) { return; } if (PG(last_error_message)) { array_init(return_value); add_assoc_long_ex(return_value, "type", sizeof("type"), PG(last_error_type)); add_assoc_string_ex(return_value, "message", sizeof("message"), PG(last_error_message), 1); add_assoc_string_ex(return_value, "file", sizeof("file"), PG(last_error_file)?PG(last_error_file):"-", 1 ); add_assoc_long_ex(return_value, "line", sizeof("line"), PG(last_error_lineno)); } } /* }}} */ /* {{{ proto mixed call_user_func(mixed function_name [, mixed parmeter] [, mixed ...]) Call a user function which is the first parameter */ PHP_FUNCTION(call_user_func) { zval *retval_ptr = NULL; zend_fcall_info fci; zend_fcall_info_cache fci_cache; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "f*", &fci, &fci_cache, &fci.params, &fci.param_count) == FAILURE) { return; } fci.retval_ptr_ptr = &retval_ptr; if (zend_call_function(&fci, &fci_cache TSRMLS_CC) == SUCCESS && fci.retval_ptr_ptr && *fci.retval_ptr_ptr) { COPY_PZVAL_TO_ZVAL(*return_value, *fci.retval_ptr_ptr); } if (fci.params) { efree(fci.params); } } /* }}} */ /* {{{ proto mixed call_user_func_array(string function_name, array parameters) Call a user function which is the first parameter with the arguments contained in array */ PHP_FUNCTION(call_user_func_array) { zval *params, *retval_ptr = NULL; zend_fcall_info fci; zend_fcall_info_cache fci_cache; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "fa/", &fci, &fci_cache, &params) == FAILURE) { return; } zend_fcall_info_args(&fci, params TSRMLS_CC); fci.retval_ptr_ptr = &retval_ptr; if (zend_call_function(&fci, &fci_cache TSRMLS_CC) == SUCCESS && fci.retval_ptr_ptr && *fci.retval_ptr_ptr) { COPY_PZVAL_TO_ZVAL(*return_value, *fci.retval_ptr_ptr); } zend_fcall_info_args_clear(&fci, 1); } /* }}} */ /* {{{ proto mixed call_user_method(string method_name, mixed object [, mixed parameter] [, mixed ...]) Call a user method on a specific object or class */ PHP_FUNCTION(call_user_method) { zval ***params = NULL; int n_params = 0; zval *retval_ptr; zval *callback, *object; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z/z*", &callback, &object, &params, &n_params) == FAILURE) { return; } if (Z_TYPE_P(object) != IS_OBJECT && Z_TYPE_P(object) != IS_STRING ) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Second argument is not an object or class name"); if (params) { efree(params); } RETURN_FALSE; } convert_to_string(callback); if (call_user_function_ex(EG(function_table), &object, callback, &retval_ptr, n_params, params, 0, NULL TSRMLS_CC) == SUCCESS) { if (retval_ptr) { COPY_PZVAL_TO_ZVAL(*return_value, retval_ptr); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call %s()", Z_STRVAL_P(callback)); } if (n_params) { efree(params); } } /* }}} */ /* {{{ proto mixed call_user_method_array(string method_name, mixed object, array params) Call a user method on a specific object or class using a parameter array */ PHP_FUNCTION(call_user_method_array) { zval *params, ***method_args = NULL, *retval_ptr; zval *callback, *object; HashTable *params_ar; int num_elems, element = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z/zA/", &callback, &object, &params) == FAILURE) { return; } if (Z_TYPE_P(object) != IS_OBJECT && Z_TYPE_P(object) != IS_STRING ) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Second argument is not an object or class name"); RETURN_FALSE; } convert_to_string(callback); params_ar = HASH_OF(params); num_elems = zend_hash_num_elements(params_ar); method_args = (zval ***) safe_emalloc(sizeof(zval **), num_elems, 0); for (zend_hash_internal_pointer_reset(params_ar); zend_hash_get_current_data(params_ar, (void **) &(method_args[element])) == SUCCESS; zend_hash_move_forward(params_ar) ) { element++; } if (call_user_function_ex(EG(function_table), &object, callback, &retval_ptr, num_elems, method_args, 0, NULL TSRMLS_CC) == SUCCESS) { if (retval_ptr) { COPY_PZVAL_TO_ZVAL(*return_value, retval_ptr); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call %s()", Z_STRVAL_P(callback)); } efree(method_args); } /* }}} */ /* {{{ proto mixed forward_static_call(mixed function_name [, mixed parmeter] [, mixed ...]) U Call a user function which is the first parameter */ PHP_FUNCTION(forward_static_call) { zval *retval_ptr = NULL; zend_fcall_info fci; zend_fcall_info_cache fci_cache; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "f*", &fci, &fci_cache, &fci.params, &fci.param_count) == FAILURE) { return; } if (!EG(active_op_array)->scope) { zend_error(E_ERROR, "Cannot call forward_static_call() when no class scope is active"); } fci.retval_ptr_ptr = &retval_ptr; if (EG(called_scope) && instanceof_function(EG(called_scope), fci_cache.calling_scope TSRMLS_CC)) { fci_cache.called_scope = EG(called_scope); } if (zend_call_function(&fci, &fci_cache TSRMLS_CC) == SUCCESS && fci.retval_ptr_ptr && *fci.retval_ptr_ptr) { COPY_PZVAL_TO_ZVAL(*return_value, *fci.retval_ptr_ptr); } if (fci.params) { efree(fci.params); } } /* }}} */ /* {{{ proto mixed call_user_func_array(string function_name, array parameters) U Call a user function which is the first parameter with the arguments contained in array */ PHP_FUNCTION(forward_static_call_array) { zval *params, *retval_ptr = NULL; zend_fcall_info fci; zend_fcall_info_cache fci_cache; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "fa/", &fci, &fci_cache, &params) == FAILURE) { return; } zend_fcall_info_args(&fci, params TSRMLS_CC); fci.retval_ptr_ptr = &retval_ptr; if (EG(called_scope) && instanceof_function(EG(called_scope), fci_cache.calling_scope TSRMLS_CC)) { fci_cache.called_scope = EG(called_scope); } if (zend_call_function(&fci, &fci_cache TSRMLS_CC) == SUCCESS && fci.retval_ptr_ptr && *fci.retval_ptr_ptr) { COPY_PZVAL_TO_ZVAL(*return_value, *fci.retval_ptr_ptr); } zend_fcall_info_args_clear(&fci, 1); } /* }}} */ void user_shutdown_function_dtor(php_shutdown_function_entry *shutdown_function_entry) /* {{{ */ { int i; for (i = 0; i < shutdown_function_entry->arg_count; i++) { zval_ptr_dtor(&shutdown_function_entry->arguments[i]); } efree(shutdown_function_entry->arguments); } /* }}} */ void user_tick_function_dtor(user_tick_function_entry *tick_function_entry) /* {{{ */ { int i; for (i = 0; i < tick_function_entry->arg_count; i++) { zval_ptr_dtor(&tick_function_entry->arguments[i]); } efree(tick_function_entry->arguments); } /* }}} */ static int user_shutdown_function_call(php_shutdown_function_entry *shutdown_function_entry TSRMLS_DC) /* {{{ */ { zval retval; char *function_name; if (!zend_is_callable(shutdown_function_entry->arguments[0], 0, &function_name TSRMLS_CC)) { php_error(E_WARNING, "(Registered shutdown functions) Unable to call %s() - function does not exist", function_name); if (function_name) { efree(function_name); } return 0; } if (function_name) { efree(function_name); } if (call_user_function(EG(function_table), NULL, shutdown_function_entry->arguments[0], &retval, shutdown_function_entry->arg_count - 1, shutdown_function_entry->arguments + 1 TSRMLS_CC ) == SUCCESS) { zval_dtor(&retval); } return 0; } /* }}} */ static void user_tick_function_call(user_tick_function_entry *tick_fe TSRMLS_DC) /* {{{ */ { zval retval; zval *function = tick_fe->arguments[0]; /* Prevent reentrant calls to the same user ticks function */ if (! tick_fe->calling) { tick_fe->calling = 1; if (call_user_function( EG(function_table), NULL, function, &retval, tick_fe->arg_count - 1, tick_fe->arguments + 1 TSRMLS_CC) == SUCCESS) { zval_dtor(&retval); } else { zval **obj, **method; if (Z_TYPE_P(function) == IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call %s() - function does not exist", Z_STRVAL_P(function)); } else if ( Z_TYPE_P(function) == IS_ARRAY && zend_hash_index_find(Z_ARRVAL_P(function), 0, (void **) &obj) == SUCCESS && zend_hash_index_find(Z_ARRVAL_P(function), 1, (void **) &method) == SUCCESS && Z_TYPE_PP(obj) == IS_OBJECT && Z_TYPE_PP(method) == IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call %s::%s() - function does not exist", Z_OBJCE_PP(obj)->name, Z_STRVAL_PP(method)); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call tick function"); } } tick_fe->calling = 0; } } /* }}} */ static void run_user_tick_functions(int tick_count) /* {{{ */ { TSRMLS_FETCH(); zend_llist_apply(BG(user_tick_functions), (llist_apply_func_t) user_tick_function_call TSRMLS_CC); } /* }}} */ static int user_tick_function_compare(user_tick_function_entry * tick_fe1, user_tick_function_entry * tick_fe2) /* {{{ */ { zval *func1 = tick_fe1->arguments[0]; zval *func2 = tick_fe2->arguments[0]; int ret; TSRMLS_FETCH(); if (Z_TYPE_P(func1) == IS_STRING && Z_TYPE_P(func2) == IS_STRING) { ret = (zend_binary_zval_strcmp(func1, func2) == 0); } else if (Z_TYPE_P(func1) == IS_ARRAY && Z_TYPE_P(func2) == IS_ARRAY) { zval result; zend_compare_arrays(&result, func1, func2 TSRMLS_CC); ret = (Z_LVAL(result) == 0); } else if (Z_TYPE_P(func1) == IS_OBJECT && Z_TYPE_P(func2) == IS_OBJECT) { zval result; zend_compare_objects(&result, func1, func2 TSRMLS_CC); ret = (Z_LVAL(result) == 0); } else { ret = 0; } if (ret && tick_fe1->calling) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to delete tick function executed at the moment"); return 0; } return ret; } /* }}} */ void php_call_shutdown_functions(TSRMLS_D) /* {{{ */ { if (BG(user_shutdown_function_names)) { zend_try { zend_hash_apply(BG(user_shutdown_function_names), (apply_func_t) user_shutdown_function_call TSRMLS_CC); } zend_end_try(); php_free_shutdown_functions(TSRMLS_C); } } /* }}} */ void php_free_shutdown_functions(TSRMLS_D) /* {{{ */ { if (BG(user_shutdown_function_names)) zend_try { zend_hash_destroy(BG(user_shutdown_function_names)); FREE_HASHTABLE(BG(user_shutdown_function_names)); BG(user_shutdown_function_names) = NULL; } zend_end_try(); } /* }}} */ /* {{{ proto void register_shutdown_function(callback function) U Register a user-level function to be called on request termination */ PHP_FUNCTION(register_shutdown_function) { php_shutdown_function_entry shutdown_function_entry; char *callback_name = NULL; int i; shutdown_function_entry.arg_count = ZEND_NUM_ARGS(); if (shutdown_function_entry.arg_count < 1) { WRONG_PARAM_COUNT; } shutdown_function_entry.arguments = (zval **) safe_emalloc(sizeof(zval *), shutdown_function_entry.arg_count, 0); if (zend_get_parameters_array(ht, shutdown_function_entry.arg_count, shutdown_function_entry.arguments) == FAILURE) { efree(shutdown_function_entry.arguments); RETURN_FALSE; } /* Prevent entering of anything but valid callback (syntax check only!) */ if (!zend_is_callable(shutdown_function_entry.arguments[0], 0, &callback_name TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid shutdown callback '%s' passed", callback_name); efree(shutdown_function_entry.arguments); RETVAL_FALSE; } else { if (!BG(user_shutdown_function_names)) { ALLOC_HASHTABLE(BG(user_shutdown_function_names)); zend_hash_init(BG(user_shutdown_function_names), 0, NULL, (void (*)(void *)) user_shutdown_function_dtor, 0); } for (i = 0; i < shutdown_function_entry.arg_count; i++) { Z_ADDREF_P(shutdown_function_entry.arguments[i]); } zend_hash_next_index_insert(BG(user_shutdown_function_names), &shutdown_function_entry, sizeof(php_shutdown_function_entry), NULL); } if (callback_name) { efree(callback_name); } } /* }}} */ PHPAPI zend_bool register_user_shutdown_function(char *function_name, size_t function_len, php_shutdown_function_entry *shutdown_function_entry TSRMLS_DC) /* {{{ */ { if (!BG(user_shutdown_function_names)) { ALLOC_HASHTABLE(BG(user_shutdown_function_names)); zend_hash_init(BG(user_shutdown_function_names), 0, NULL, (void (*)(void *)) user_shutdown_function_dtor, 0); } return zend_hash_update(BG(user_shutdown_function_names), function_name, function_len, shutdown_function_entry, sizeof(php_shutdown_function_entry), NULL) != FAILURE; } /* }}} */ PHPAPI zend_bool remove_user_shutdown_function(char *function_name, size_t function_len TSRMLS_DC) /* {{{ */ { if (BG(user_shutdown_function_names)) { return zend_hash_del_key_or_index(BG(user_shutdown_function_names), function_name, function_len, 0, HASH_DEL_KEY) != FAILURE; } return 0; } /* }}} */ PHPAPI zend_bool append_user_shutdown_function(php_shutdown_function_entry shutdown_function_entry TSRMLS_DC) /* {{{ */ { if (!BG(user_shutdown_function_names)) { ALLOC_HASHTABLE(BG(user_shutdown_function_names)); zend_hash_init(BG(user_shutdown_function_names), 0, NULL, (void (*)(void *)) user_shutdown_function_dtor, 0); } return zend_hash_next_index_insert(BG(user_shutdown_function_names), &shutdown_function_entry, sizeof(php_shutdown_function_entry), NULL) != FAILURE; } /* }}} */ ZEND_API void php_get_highlight_struct(zend_syntax_highlighter_ini *syntax_highlighter_ini) /* {{{ */ { syntax_highlighter_ini->highlight_comment = INI_STR("highlight.comment"); syntax_highlighter_ini->highlight_default = INI_STR("highlight.default"); syntax_highlighter_ini->highlight_html = INI_STR("highlight.html"); syntax_highlighter_ini->highlight_keyword = INI_STR("highlight.keyword"); syntax_highlighter_ini->highlight_string = INI_STR("highlight.string"); } /* }}} */ /* {{{ proto bool highlight_file(string file_name [, bool return] ) Syntax highlight a source file */ PHP_FUNCTION(highlight_file) { char *filename; int filename_len, ret; zend_syntax_highlighter_ini syntax_highlighter_ini; zend_bool i = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|b", &filename, &filename_len, &i) == FAILURE) { RETURN_FALSE; } if (php_check_open_basedir(filename TSRMLS_CC)) { RETURN_FALSE; } if (i) { php_output_start_default(TSRMLS_C); } php_get_highlight_struct(&syntax_highlighter_ini); ret = highlight_file(filename, &syntax_highlighter_ini TSRMLS_CC); if (ret == FAILURE) { if (i) { php_output_end(TSRMLS_C); } RETURN_FALSE; } if (i) { php_output_get_contents(return_value TSRMLS_CC); php_output_discard(TSRMLS_C); } else { RETURN_TRUE; } } /* }}} */ /* {{{ proto string php_strip_whitespace(string file_name) Return source with stripped comments and whitespace */ PHP_FUNCTION(php_strip_whitespace) { char *filename; int filename_len; zend_lex_state original_lex_state; zend_file_handle file_handle = {0}; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &filename, &filename_len) == FAILURE) { RETURN_FALSE; } php_output_start_default(TSRMLS_C); file_handle.type = ZEND_HANDLE_FILENAME; file_handle.filename = filename; file_handle.free_filename = 0; file_handle.opened_path = NULL; zend_save_lexical_state(&original_lex_state TSRMLS_CC); if (open_file_for_scanning(&file_handle TSRMLS_CC) == FAILURE) { zend_restore_lexical_state(&original_lex_state TSRMLS_CC); php_output_end(TSRMLS_C); RETURN_EMPTY_STRING(); } zend_strip(TSRMLS_C); zend_destroy_file_handle(&file_handle TSRMLS_CC); zend_restore_lexical_state(&original_lex_state TSRMLS_CC); php_output_get_contents(return_value TSRMLS_CC); php_output_discard(TSRMLS_C); } /* }}} */ /* {{{ proto bool highlight_string(string string [, bool return] ) Syntax highlight a string or optionally return it */ PHP_FUNCTION(highlight_string) { zval **expr; zend_syntax_highlighter_ini syntax_highlighter_ini; char *hicompiled_string_description; zend_bool i = 0; int old_error_reporting = EG(error_reporting); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z|b", &expr, &i) == FAILURE) { RETURN_FALSE; } convert_to_string_ex(expr); if (i) { php_output_start_default(TSRMLS_C); } EG(error_reporting) = E_ERROR; php_get_highlight_struct(&syntax_highlighter_ini); hicompiled_string_description = zend_make_compiled_string_description("highlighted code" TSRMLS_CC); if (highlight_string(*expr, &syntax_highlighter_ini, hicompiled_string_description TSRMLS_CC) == FAILURE) { efree(hicompiled_string_description); EG(error_reporting) = old_error_reporting; if (i) { php_output_end(TSRMLS_C); } RETURN_FALSE; } efree(hicompiled_string_description); EG(error_reporting) = old_error_reporting; if (i) { php_output_get_contents(return_value TSRMLS_CC); php_output_discard(TSRMLS_C); } else { RETURN_TRUE; } } /* }}} */ /* {{{ proto string ini_get(string varname) Get a configuration option */ PHP_FUNCTION(ini_get) { char *varname, *str; int varname_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &varname, &varname_len) == FAILURE) { return; } str = zend_ini_string(varname, varname_len + 1, 0); if (!str) { RETURN_FALSE; } RETURN_STRING(str, 1); } /* }}} */ static int php_ini_get_option(zend_ini_entry *ini_entry TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zval *ini_array = va_arg(args, zval *); int module_number = va_arg(args, int); int details = va_arg(args, int); zval *option; if (module_number != 0 && ini_entry->module_number != module_number) { return 0; } if (hash_key->nKeyLength == 0 || hash_key->arKey[0] != 0 ) { if (details) { MAKE_STD_ZVAL(option); array_init(option); if (ini_entry->orig_value) { add_assoc_stringl(option, "global_value", ini_entry->orig_value, ini_entry->orig_value_length, 1); } else if (ini_entry->value) { add_assoc_stringl(option, "global_value", ini_entry->value, ini_entry->value_length, 1); } else { add_assoc_null(option, "global_value"); } if (ini_entry->value) { add_assoc_stringl(option, "local_value", ini_entry->value, ini_entry->value_length, 1); } else { add_assoc_null(option, "local_value"); } add_assoc_long(option, "access", ini_entry->modifiable); add_assoc_zval_ex(ini_array, ini_entry->name, ini_entry->name_length, option); } else { if (ini_entry->value) { add_assoc_stringl(ini_array, ini_entry->name, ini_entry->value, ini_entry->value_length, 1); } else { add_assoc_null(ini_array, ini_entry->name); } } } return 0; } /* }}} */ /* {{{ proto array ini_get_all([string extension[, bool details = true]]) Get all configuration options */ PHP_FUNCTION(ini_get_all) { char *extname = NULL; int extname_len = 0, extnumber = 0; zend_module_entry *module; zend_bool details = 1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!b", &extname, &extname_len, &details) == FAILURE) { return; } zend_ini_sort_entries(TSRMLS_C); if (extname) { if (zend_hash_find(&module_registry, extname, extname_len+1, (void **) &module) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to find extension '%s'", extname); RETURN_FALSE; } extnumber = module->module_number; } array_init(return_value); zend_hash_apply_with_arguments(EG(ini_directives) TSRMLS_CC, (apply_func_args_t) php_ini_get_option, 2, return_value, extnumber, details); } /* }}} */ static int php_ini_check_path(char *option_name, int option_len, char *new_option_name, int new_option_len) /* {{{ */ { if (option_len != (new_option_len - 1)) { return 0; } return !strncmp(option_name, new_option_name, option_len); } /* }}} */ /* {{{ proto string ini_set(string varname, string newvalue) Set a configuration option, returns false on error and the old value of the configuration option on success */ PHP_FUNCTION(ini_set) { char *varname, *new_value; int varname_len, new_value_len; char *old_value; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &varname, &varname_len, &new_value, &new_value_len) == FAILURE) { return; } old_value = zend_ini_string(varname, varname_len + 1, 0); /* copy to return here, because alter might free it! */ if (old_value) { RETVAL_STRING(old_value, 1); } else { RETVAL_FALSE; } #define _CHECK_PATH(var, var_len, ini) php_ini_check_path(var, var_len, ini, sizeof(ini)) /* open basedir check */ if (PG(open_basedir)) { if (_CHECK_PATH(varname, varname_len, "error_log") || _CHECK_PATH(varname, varname_len, "java.class.path") || _CHECK_PATH(varname, varname_len, "java.home") || _CHECK_PATH(varname, varname_len, "mail.log") || _CHECK_PATH(varname, varname_len, "java.library.path") || _CHECK_PATH(varname, varname_len, "vpopmail.directory")) { if (php_check_open_basedir(new_value TSRMLS_CC)) { zval_dtor(return_value); RETURN_FALSE; } } } if (zend_alter_ini_entry_ex(varname, varname_len + 1, new_value, new_value_len, PHP_INI_USER, PHP_INI_STAGE_RUNTIME, 0 TSRMLS_CC) == FAILURE) { zval_dtor(return_value); RETURN_FALSE; } } /* }}} */ /* {{{ proto void ini_restore(string varname) Restore the value of a configuration option specified by varname */ PHP_FUNCTION(ini_restore) { char *varname; int varname_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &varname, &varname_len) == FAILURE) { return; } zend_restore_ini_entry(varname, varname_len+1, PHP_INI_STAGE_RUNTIME); } /* }}} */ /* {{{ proto string set_include_path(string new_include_path) Sets the include_path configuration option */ PHP_FUNCTION(set_include_path) { char *new_value; int new_value_len; char *old_value; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &new_value, &new_value_len) == FAILURE) { return; } old_value = zend_ini_string("include_path", sizeof("include_path"), 0); /* copy to return here, because alter might free it! */ if (old_value) { RETVAL_STRING(old_value, 1); } else { RETVAL_FALSE; } if (zend_alter_ini_entry_ex("include_path", sizeof("include_path"), new_value, new_value_len, PHP_INI_USER, PHP_INI_STAGE_RUNTIME, 0 TSRMLS_CC) == FAILURE) { zval_dtor(return_value); RETURN_FALSE; } } /* }}} */ /* {{{ proto string get_include_path() Get the current include_path configuration option */ PHP_FUNCTION(get_include_path) { char *str; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "") == FAILURE) { return; } str = zend_ini_string("include_path", sizeof("include_path"), 0); if (str == NULL) { RETURN_FALSE; } RETURN_STRING(str, 1); } /* }}} */ /* {{{ proto void restore_include_path() Restore the value of the include_path configuration option */ PHP_FUNCTION(restore_include_path) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "") == FAILURE) { return; } zend_restore_ini_entry("include_path", sizeof("include_path"), PHP_INI_STAGE_RUNTIME); } /* }}} */ /* {{{ proto mixed print_r(mixed var [, bool return]) Prints out or returns information about the specified variable */ PHP_FUNCTION(print_r) { zval *var; zend_bool do_return = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|b", &var, &do_return) == FAILURE) { RETURN_FALSE; } if (do_return) { php_output_start_default(TSRMLS_C); } zend_print_zval_r(var, 0 TSRMLS_CC); if (do_return) { php_output_get_contents(return_value TSRMLS_CC); php_output_discard(TSRMLS_C); } else { RETURN_TRUE; } } /* }}} */ /* {{{ proto int connection_aborted(void) Returns true if client disconnected */ PHP_FUNCTION(connection_aborted) { RETURN_LONG(PG(connection_status) & PHP_CONNECTION_ABORTED); } /* }}} */ /* {{{ proto int connection_status(void) Returns the connection status bitfield */ PHP_FUNCTION(connection_status) { RETURN_LONG(PG(connection_status)); } /* }}} */ /* {{{ proto int ignore_user_abort([string value]) Set whether we want to ignore a user abort event or not */ PHP_FUNCTION(ignore_user_abort) { char *arg = NULL; int arg_len = 0; int old_setting; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &arg, &arg_len) == FAILURE) { return; } old_setting = PG(ignore_user_abort); if (arg) { zend_alter_ini_entry_ex("ignore_user_abort", sizeof("ignore_user_abort"), arg, arg_len, PHP_INI_USER, PHP_INI_STAGE_RUNTIME, 0 TSRMLS_CC); } RETURN_LONG(old_setting); } /* }}} */ #if HAVE_GETSERVBYNAME /* {{{ proto int getservbyname(string service, string protocol) Returns port associated with service. Protocol must be "tcp" or "udp" */ PHP_FUNCTION(getservbyname) { char *name, *proto; int name_len, proto_len; struct servent *serv; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &name, &name_len, &proto, &proto_len) == FAILURE) { return; } /* empty string behaves like NULL on windows implementation of getservbyname. Let be portable instead. */ #ifdef PHP_WIN32 if (proto_len == 0) { RETURN_FALSE; } #endif serv = getservbyname(name, proto); if (serv == NULL) { RETURN_FALSE; } RETURN_LONG(ntohs(serv->s_port)); } /* }}} */ #endif #if HAVE_GETSERVBYPORT /* {{{ proto string getservbyport(int port, string protocol) Returns service name associated with port. Protocol must be "tcp" or "udp" */ PHP_FUNCTION(getservbyport) { char *proto; int proto_len; long port; struct servent *serv; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ls", &port, &proto, &proto_len) == FAILURE) { return; } serv = getservbyport(htons((unsigned short) port), proto); if (serv == NULL) { RETURN_FALSE; } RETURN_STRING(serv->s_name, 1); } /* }}} */ #endif #if HAVE_GETPROTOBYNAME /* {{{ proto int getprotobyname(string name) Returns protocol number associated with name as per /etc/protocols */ PHP_FUNCTION(getprotobyname) { char *name; int name_len; struct protoent *ent; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) { return; } ent = getprotobyname(name); if (ent == NULL) { RETURN_FALSE; } RETURN_LONG(ent->p_proto); } /* }}} */ #endif #if HAVE_GETPROTOBYNUMBER /* {{{ proto string getprotobynumber(int proto) Returns protocol name associated with protocol number proto */ PHP_FUNCTION(getprotobynumber) { long proto; struct protoent *ent; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &proto) == FAILURE) { return; } ent = getprotobynumber(proto); if (ent == NULL) { RETURN_FALSE; } RETURN_STRING(ent->p_name, 1); } /* }}} */ #endif /* {{{ proto bool register_tick_function(string function_name [, mixed arg [, mixed ... ]]) Registers a tick callback function */ PHP_FUNCTION(register_tick_function) { user_tick_function_entry tick_fe; int i; char *function_name = NULL; tick_fe.calling = 0; tick_fe.arg_count = ZEND_NUM_ARGS(); if (tick_fe.arg_count < 1) { WRONG_PARAM_COUNT; } tick_fe.arguments = (zval **) safe_emalloc(sizeof(zval *), tick_fe.arg_count, 0); if (zend_get_parameters_array(ht, tick_fe.arg_count, tick_fe.arguments) == FAILURE) { efree(tick_fe.arguments); RETURN_FALSE; } if (!zend_is_callable(tick_fe.arguments[0], 0, &function_name TSRMLS_CC)) { efree(tick_fe.arguments); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid tick callback '%s' passed", function_name); efree(function_name); RETURN_FALSE; } else if (function_name) { efree(function_name); } if (Z_TYPE_P(tick_fe.arguments[0]) != IS_ARRAY && Z_TYPE_P(tick_fe.arguments[0]) != IS_OBJECT) { convert_to_string_ex(&tick_fe.arguments[0]); } if (!BG(user_tick_functions)) { BG(user_tick_functions) = (zend_llist *) emalloc(sizeof(zend_llist)); zend_llist_init(BG(user_tick_functions), sizeof(user_tick_function_entry), (llist_dtor_func_t) user_tick_function_dtor, 0); php_add_tick_function(run_user_tick_functions); } for (i = 0; i < tick_fe.arg_count; i++) { Z_ADDREF_P(tick_fe.arguments[i]); } zend_llist_add_element(BG(user_tick_functions), &tick_fe); RETURN_TRUE; } /* }}} */ /* {{{ proto void unregister_tick_function(string function_name) Unregisters a tick callback function */ PHP_FUNCTION(unregister_tick_function) { zval *function; user_tick_function_entry tick_fe; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z/", &function) == FAILURE) { return; } if (!BG(user_tick_functions)) { return; } if (Z_TYPE_P(function) != IS_ARRAY) { convert_to_string(function); } tick_fe.arguments = (zval **) emalloc(sizeof(zval *)); tick_fe.arguments[0] = function; tick_fe.arg_count = 1; zend_llist_del_element(BG(user_tick_functions), &tick_fe, (int (*)(void *, void *)) user_tick_function_compare); efree(tick_fe.arguments); } /* }}} */ /* {{{ proto bool is_uploaded_file(string path) Check if file was created by rfc1867 upload */ PHP_FUNCTION(is_uploaded_file) { char *path; int path_len; if (!SG(rfc1867_uploaded_files)) { RETURN_FALSE; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &path, &path_len) == FAILURE) { return; } if (zend_hash_exists(SG(rfc1867_uploaded_files), path, path_len + 1)) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool move_uploaded_file(string path, string new_path) Move a file if and only if it was created by an upload */ PHP_FUNCTION(move_uploaded_file) { char *path, *new_path; int path_len, new_path_len; zend_bool successful = 0; #ifndef PHP_WIN32 int oldmask; int ret; #endif if (!SG(rfc1867_uploaded_files)) { RETURN_FALSE; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &path, &path_len, &new_path, &new_path_len) == FAILURE) { return; } if (!zend_hash_exists(SG(rfc1867_uploaded_files), path, path_len + 1)) { RETURN_FALSE; } if (php_check_open_basedir(new_path TSRMLS_CC)) { RETURN_FALSE; } if (VCWD_RENAME(path, new_path) == 0) { successful = 1; #ifndef PHP_WIN32 oldmask = umask(077); umask(oldmask); ret = VCWD_CHMOD(new_path, 0666 & ~oldmask); if (ret == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", strerror(errno)); } #endif } else if (php_copy_file_ex(path, new_path, STREAM_DISABLE_OPEN_BASEDIR TSRMLS_CC) == SUCCESS) { VCWD_UNLINK(path); successful = 1; } if (successful) { zend_hash_del(SG(rfc1867_uploaded_files), path, path_len + 1); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to move '%s' to '%s'", path, new_path); } RETURN_BOOL(successful); } /* }}} */ /* {{{ php_simple_ini_parser_cb */ static void php_simple_ini_parser_cb(zval *arg1, zval *arg2, zval *arg3, int callback_type, zval *arr TSRMLS_DC) { zval *element; switch (callback_type) { case ZEND_INI_PARSER_ENTRY: if (!arg2) { /* bare string - nothing to do */ break; } ALLOC_ZVAL(element); MAKE_COPY_ZVAL(&arg2, element); zend_symtable_update(Z_ARRVAL_P(arr), Z_STRVAL_P(arg1), Z_STRLEN_P(arg1) + 1, &element, sizeof(zval *), NULL); break; case ZEND_INI_PARSER_POP_ENTRY: { zval *hash, **find_hash; if (!arg2) { /* bare string - nothing to do */ break; } if (!(Z_STRLEN_P(arg1) > 1 && Z_STRVAL_P(arg1)[0] == '0') && is_numeric_string(Z_STRVAL_P(arg1), Z_STRLEN_P(arg1), NULL, NULL, 0) == IS_LONG) { ulong key = (ulong) zend_atol(Z_STRVAL_P(arg1), Z_STRLEN_P(arg1)); if (zend_hash_index_find(Z_ARRVAL_P(arr), key, (void **) &find_hash) == FAILURE) { ALLOC_ZVAL(hash); INIT_PZVAL(hash); array_init(hash); zend_hash_index_update(Z_ARRVAL_P(arr), key, &hash, sizeof(zval *), NULL); } else { hash = *find_hash; } } else { if (zend_hash_find(Z_ARRVAL_P(arr), Z_STRVAL_P(arg1), Z_STRLEN_P(arg1) + 1, (void **) &find_hash) == FAILURE) { ALLOC_ZVAL(hash); INIT_PZVAL(hash); array_init(hash); zend_hash_update(Z_ARRVAL_P(arr), Z_STRVAL_P(arg1), Z_STRLEN_P(arg1) + 1, &hash, sizeof(zval *), NULL); } else { hash = *find_hash; } } if (Z_TYPE_P(hash) != IS_ARRAY) { zval_dtor(hash); INIT_PZVAL(hash); array_init(hash); } ALLOC_ZVAL(element); MAKE_COPY_ZVAL(&arg2, element); if (arg3 && Z_STRLEN_P(arg3) > 0) { add_assoc_zval_ex(hash, Z_STRVAL_P(arg3), Z_STRLEN_P(arg3) + 1, element); } else { add_next_index_zval(hash, element); } } break; case ZEND_INI_PARSER_SECTION: break; } } /* }}} */ /* {{{ php_ini_parser_cb_with_sections */ static void php_ini_parser_cb_with_sections(zval *arg1, zval *arg2, zval *arg3, int callback_type, zval *arr TSRMLS_DC) { if (callback_type == ZEND_INI_PARSER_SECTION) { MAKE_STD_ZVAL(BG(active_ini_file_section)); array_init(BG(active_ini_file_section)); zend_symtable_update(Z_ARRVAL_P(arr), Z_STRVAL_P(arg1), Z_STRLEN_P(arg1) + 1, &BG(active_ini_file_section), sizeof(zval *), NULL); } else if (arg2) { zval *active_arr; if (BG(active_ini_file_section)) { active_arr = BG(active_ini_file_section); } else { active_arr = arr; } php_simple_ini_parser_cb(arg1, arg2, arg3, callback_type, active_arr TSRMLS_CC); } } /* }}} */ /* {{{ proto array parse_ini_file(string filename [, bool process_sections [, int scanner_mode]]) Parse configuration file */ PHP_FUNCTION(parse_ini_file) { char *filename = NULL; int filename_len = 0; zend_bool process_sections = 0; long scanner_mode = ZEND_INI_SCANNER_NORMAL; zend_file_handle fh; zend_ini_parser_cb_t ini_parser_cb; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|bl", &filename, &filename_len, &process_sections, &scanner_mode) == FAILURE) { RETURN_FALSE; } if (filename_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Filename cannot be empty!"); RETURN_FALSE; } /* Set callback function */ if (process_sections) { BG(active_ini_file_section) = NULL; ini_parser_cb = (zend_ini_parser_cb_t) php_ini_parser_cb_with_sections; } else { ini_parser_cb = (zend_ini_parser_cb_t) php_simple_ini_parser_cb; } /* Setup filehandle */ memset(&fh, 0, sizeof(fh)); fh.filename = filename; fh.type = ZEND_HANDLE_FILENAME; array_init(return_value); if (zend_parse_ini_file(&fh, 0, scanner_mode, ini_parser_cb, return_value TSRMLS_CC) == FAILURE) { zend_hash_destroy(Z_ARRVAL_P(return_value)); efree(Z_ARRVAL_P(return_value)); RETURN_FALSE; } } /* }}} */ /* {{{ proto array parse_ini_string(string ini_string [, bool process_sections [, int scanner_mode]]) Parse configuration string */ PHP_FUNCTION(parse_ini_string) { char *string = NULL, *str = NULL; int str_len = 0; zend_bool process_sections = 0; long scanner_mode = ZEND_INI_SCANNER_NORMAL; zend_ini_parser_cb_t ini_parser_cb; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|bl", &str, &str_len, &process_sections, &scanner_mode) == FAILURE) { RETURN_FALSE; } if (INT_MAX - str_len < ZEND_MMAP_AHEAD) { RETVAL_FALSE; } /* Set callback function */ if (process_sections) { BG(active_ini_file_section) = NULL; ini_parser_cb = (zend_ini_parser_cb_t) php_ini_parser_cb_with_sections; } else { ini_parser_cb = (zend_ini_parser_cb_t) php_simple_ini_parser_cb; } /* Setup string */ string = (char *) emalloc(str_len + ZEND_MMAP_AHEAD); memcpy(string, str, str_len); memset(string + str_len, 0, ZEND_MMAP_AHEAD); array_init(return_value); if (zend_parse_ini_string(string, 0, scanner_mode, ini_parser_cb, return_value TSRMLS_CC) == FAILURE) { zend_hash_destroy(Z_ARRVAL_P(return_value)); efree(Z_ARRVAL_P(return_value)); RETVAL_FALSE; } efree(string); } /* }}} */ #if ZEND_DEBUG /* This function returns an array of ALL valid ini options with values and * is not the same as ini_get_all() which returns only registered ini options. Only useful for devs to debug php.ini scanner/parser! */ PHP_FUNCTION(config_get_hash) /* {{{ */ { HashTable *hash = php_ini_get_configuration_hash(); array_init(return_value); zend_hash_apply_with_arguments(hash TSRMLS_CC, (apply_func_args_t) add_config_entry_cb, 1, return_value); } /* }}} */ #endif #ifdef HAVE_GETLOADAVG /* {{{ proto array sys_getloadavg() */ PHP_FUNCTION(sys_getloadavg) { double load[3]; if (zend_parse_parameters_none() == FAILURE) { return; } if (getloadavg(load, 3) == -1) { RETURN_FALSE; } else { array_init(return_value); add_index_double(return_value, 0, load[0]); add_index_double(return_value, 1, load[1]); add_index_double(return_value, 2, load[2]); } } /* }}} */ #endif /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: fdm=marker * vim: noet sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2012 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "php.h" #include "php_streams.h" #include "php_main.h" #include "php_globals.h" #include "php_ini.h" #include "php_standard.h" #include "php_math.h" #include "php_http.h" #include "php_incomplete_class.h" #include "php_getopt.h" #include "ext/standard/info.h" #include "ext/session/php_session.h" #include "zend_operators.h" #include "ext/standard/php_dns.h" #include "ext/standard/php_uuencode.h" #ifdef PHP_WIN32 #include "win32/php_win32_globals.h" #include "win32/time.h" #endif typedef struct yy_buffer_state *YY_BUFFER_STATE; #include "zend.h" #include "zend_ini_scanner.h" #include "zend_language_scanner.h" #include <zend_language_parser.h> #include <stdarg.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <stdio.h> #ifndef PHP_WIN32 #include <sys/types.h> #include <sys/stat.h> #endif #ifdef NETWARE #include <netinet/in.h> #endif #ifndef PHP_WIN32 # include <netdb.h> #else #include "win32/inet.h" #endif #if HAVE_ARPA_INET_H # include <arpa/inet.h> #endif #if HAVE_UNISTD_H # include <unistd.h> #endif #if HAVE_STRING_H # include <string.h> #else # include <strings.h> #endif #if HAVE_LOCALE_H # include <locale.h> #endif #if HAVE_SYS_MMAN_H # include <sys/mman.h> #endif #if HAVE_SYS_LOADAVG_H # include <sys/loadavg.h> #endif #ifdef PHP_WIN32 # include "win32/unistd.h" #endif #ifndef INADDR_NONE #define INADDR_NONE ((unsigned long int) -1) #endif #include "zend_globals.h" #include "php_globals.h" #include "SAPI.h" #include "php_ticks.h" #ifdef ZTS PHPAPI int basic_globals_id; #else PHPAPI php_basic_globals basic_globals; #endif #include "php_fopen_wrappers.h" #include "streamsfuncs.h" static zend_class_entry *incomplete_class_entry = NULL; typedef struct _user_tick_function_entry { zval **arguments; int arg_count; int calling; } user_tick_function_entry; /* some prototypes for local functions */ static void user_shutdown_function_dtor(php_shutdown_function_entry *shutdown_function_entry); static void user_tick_function_dtor(user_tick_function_entry *tick_function_entry); static HashTable basic_submodules; #undef sprintf /* {{{ arginfo */ /* {{{ main/main.c */ ZEND_BEGIN_ARG_INFO(arginfo_set_time_limit, 0) ZEND_ARG_INFO(0, seconds) ZEND_END_ARG_INFO() /* }}} */ /* {{{ main/sapi.c */ ZEND_BEGIN_ARG_INFO(arginfo_header_register_callback, 0) ZEND_ARG_INFO(0, callback) ZEND_END_ARG_INFO() /* }}} */ /* {{{ main/output.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_ob_start, 0, 0, 0) ZEND_ARG_INFO(0, user_function) ZEND_ARG_INFO(0, chunk_size) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ob_flush, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ob_clean, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ob_end_flush, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ob_end_clean, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ob_get_flush, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ob_get_clean, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ob_get_contents, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ob_get_level, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ob_get_length, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ob_list_handlers, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ob_get_status, 0, 0, 0) ZEND_ARG_INFO(0, full_status) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ob_implicit_flush, 0, 0, 0) ZEND_ARG_INFO(0, flag) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_output_reset_rewrite_vars, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_output_add_rewrite_var, 0) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() /* }}} */ /* {{{ main/streams/userspace.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_wrapper_register, 0, 0, 2) ZEND_ARG_INFO(0, protocol) ZEND_ARG_INFO(0, classname) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_wrapper_unregister, 0) ZEND_ARG_INFO(0, protocol) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_wrapper_restore, 0) ZEND_ARG_INFO(0, protocol) ZEND_END_ARG_INFO() /* }}} */ /* {{{ array.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_krsort, 0, 0, 1) ZEND_ARG_INFO(1, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_ARG_INFO(0, sort_flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ksort, 0, 0, 1) ZEND_ARG_INFO(1, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_ARG_INFO(0, sort_flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_count, 0, 0, 1) ZEND_ARG_INFO(0, var) ZEND_ARG_INFO(0, mode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_natsort, 0) ZEND_ARG_INFO(1, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_natcasesort, 0) ZEND_ARG_INFO(1, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_asort, 0, 0, 1) ZEND_ARG_INFO(1, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_ARG_INFO(0, sort_flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_arsort, 0, 0, 1) ZEND_ARG_INFO(1, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_ARG_INFO(0, sort_flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_sort, 0, 0, 1) ZEND_ARG_INFO(1, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_ARG_INFO(0, sort_flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_rsort, 0, 0, 1) ZEND_ARG_INFO(1, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_ARG_INFO(0, sort_flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_usort, 0) ZEND_ARG_INFO(1, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_ARG_INFO(0, cmp_function) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_uasort, 0) ZEND_ARG_INFO(1, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_ARG_INFO(0, cmp_function) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_uksort, 0) ZEND_ARG_INFO(1, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_ARG_INFO(0, cmp_function) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_end, 0) ZEND_ARG_INFO(1, arg) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_prev, 0) ZEND_ARG_INFO(1, arg) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_next, 0) ZEND_ARG_INFO(1, arg) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reset, 0) ZEND_ARG_INFO(1, arg) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_current, ZEND_SEND_PREFER_REF) ZEND_ARG_INFO(ZEND_SEND_PREFER_REF, arg) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_key, ZEND_SEND_PREFER_REF) ZEND_ARG_INFO(ZEND_SEND_PREFER_REF, arg) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_min, 0, 0, 1) ZEND_ARG_INFO(0, arg1) ZEND_ARG_INFO(0, arg2) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_max, 0, 0, 1) ZEND_ARG_INFO(0, arg1) ZEND_ARG_INFO(0, arg2) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_walk, 0, 0, 2) ZEND_ARG_INFO(1, input) /* ARRAY_INFO(1, arg, 0) */ ZEND_ARG_INFO(0, funcname) ZEND_ARG_INFO(0, userdata) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_walk_recursive, 0, 0, 2) ZEND_ARG_INFO(1, input) /* ARRAY_INFO(1, arg, 0) */ ZEND_ARG_INFO(0, funcname) ZEND_ARG_INFO(0, userdata) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_in_array, 0, 0, 2) ZEND_ARG_INFO(0, needle) ZEND_ARG_INFO(0, haystack) /* ARRAY_INFO(0, haystack, 0) */ ZEND_ARG_INFO(0, strict) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_search, 0, 0, 2) ZEND_ARG_INFO(0, needle) ZEND_ARG_INFO(0, haystack) /* ARRAY_INFO(0, haystack, 0) */ ZEND_ARG_INFO(0, strict) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_extract, 0, 0, 1) ZEND_ARG_INFO(ZEND_SEND_PREFER_REF, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, extract_type) ZEND_ARG_INFO(0, prefix) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_compact, 0, 0, 1) ZEND_ARG_INFO(0, var_names) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_fill, 0) ZEND_ARG_INFO(0, start_key) ZEND_ARG_INFO(0, num) ZEND_ARG_INFO(0, val) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_fill_keys, 0) ZEND_ARG_INFO(0, keys) /* ARRAY_INFO(0, keys, 0) */ ZEND_ARG_INFO(0, val) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_range, 0, 0, 2) ZEND_ARG_INFO(0, low) ZEND_ARG_INFO(0, high) ZEND_ARG_INFO(0, step) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_shuffle, 0) ZEND_ARG_INFO(1, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_push, 0, 0, 2) ZEND_ARG_INFO(1, stack) /* ARRAY_INFO(1, stack, 0) */ ZEND_ARG_INFO(0, var) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_pop, 0) ZEND_ARG_INFO(1, stack) /* ARRAY_INFO(1, stack, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_shift, 0) ZEND_ARG_INFO(1, stack) /* ARRAY_INFO(1, stack, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_unshift, 0, 0, 2) ZEND_ARG_INFO(1, stack) /* ARRAY_INFO(1, stack, 0) */ ZEND_ARG_INFO(0, var) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_splice, 0, 0, 2) ZEND_ARG_INFO(1, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_ARG_INFO(0, offset) ZEND_ARG_INFO(0, length) ZEND_ARG_INFO(0, replacement) /* ARRAY_INFO(0, arg, 1) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_slice, 0, 0, 2) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(1, arg, 0) */ ZEND_ARG_INFO(0, offset) ZEND_ARG_INFO(0, length) ZEND_ARG_INFO(0, preserve_keys) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_merge, 0, 0, 2) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, ...) /* ARRAY_INFO(0, ..., 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_merge_recursive, 0, 0, 2) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, ...) /* ARRAY_INFO(0, arg, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_replace, 0, 0, 2) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, ...) /* ARRAY_INFO(0, ..., 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_replace_recursive, 0, 0, 2) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, ...) /* ARRAY_INFO(0, arg, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_keys, 0, 0, 1) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, search_value) ZEND_ARG_INFO(0, strict) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_values, 0) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_count_values, 0) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_reverse, 0, 0, 1) ZEND_ARG_INFO(0, input) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, preserve_keys) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_pad, 0) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, pad_size) ZEND_ARG_INFO(0, pad_value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_flip, 0) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_change_key_case, 0, 0, 1) ZEND_ARG_INFO(0, input) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, case) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_unique, 0) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_intersect_key, 0, 0, 2) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, ...) /* ARRAY_INFO(0, ..., 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_intersect_ukey, 0) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, callback_key_compare_func) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_intersect, 0, 0, 2) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, ...) /* ARRAY_INFO(0, ..., 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_uintersect, 0) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, callback_data_compare_func) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_intersect_assoc, 0, 0, 2) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, ...) /* ARRAY_INFO(0, ..., 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_uintersect_assoc, 0) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, callback_data_compare_func) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_intersect_uassoc, 0) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, callback_key_compare_func) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_uintersect_uassoc, 0) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, callback_data_compare_func) ZEND_ARG_INFO(0, callback_key_compare_func) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_diff_key, 0, 0, 2) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, ...) /* ARRAY_INFO(0, ..., 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_diff_ukey, 0) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, callback_key_comp_func) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_diff, 0, 0, 2) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, ...) /* ARRAY_INFO(0, ..., 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_udiff, 0) ZEND_ARG_INFO(0, arr1) ZEND_ARG_INFO(0, arr2) ZEND_ARG_INFO(0, callback_data_comp_func) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_diff_assoc, 0, 0, 2) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, ...) /* ARRAY_INFO(0, ..., 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_diff_uassoc, 0) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, callback_data_comp_func) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_udiff_assoc, 0) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, callback_key_comp_func) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_udiff_uassoc, 0) ZEND_ARG_INFO(0, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(0, arr2) /* ARRAY_INFO(0, arg2, 0) */ ZEND_ARG_INFO(0, callback_data_comp_func) ZEND_ARG_INFO(0, callback_key_comp_func) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_multisort, ZEND_SEND_PREFER_REF, 0, 1) ZEND_ARG_INFO(ZEND_SEND_PREFER_REF, arr1) /* ARRAY_INFO(0, arg1, 0) */ ZEND_ARG_INFO(ZEND_SEND_PREFER_REF, SORT_ASC_or_SORT_DESC) ZEND_ARG_INFO(ZEND_SEND_PREFER_REF, SORT_REGULAR_or_SORT_NUMERIC_or_SORT_STRING) ZEND_ARG_INFO(ZEND_SEND_PREFER_REF, arr2) ZEND_ARG_INFO(ZEND_SEND_PREFER_REF, SORT_ASC_or_SORT_DESC) ZEND_ARG_INFO(ZEND_SEND_PREFER_REF, SORT_REGULAR_or_SORT_NUMERIC_or_SORT_STRING) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_rand, 0, 0, 1) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, num_req) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_sum, 0) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_product, 0) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_reduce, 0, 0, 2) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, callback) ZEND_ARG_INFO(0, initial) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_filter, 0, 0, 1) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, callback) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_map, 0, 0, 2) ZEND_ARG_INFO(0, callback) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_key_exists, 0) ZEND_ARG_INFO(0, key) ZEND_ARG_INFO(0, search) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_chunk, 0, 0, 2) ZEND_ARG_INFO(0, arg) /* ARRAY_INFO(0, arg, 0) */ ZEND_ARG_INFO(0, size) ZEND_ARG_INFO(0, preserve_keys) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_combine, 0) ZEND_ARG_INFO(0, keys) /* ARRAY_INFO(0, keys, 0) */ ZEND_ARG_INFO(0, values) /* ARRAY_INFO(0, values, 0) */ ZEND_END_ARG_INFO() /* }}} */ /* {{{ basic_functions.c */ ZEND_BEGIN_ARG_INFO(arginfo_get_magic_quotes_gpc, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_get_magic_quotes_runtime, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_set_magic_quotes_runtime, 0, 0, 1) ZEND_ARG_INFO(0, new_setting) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_constant, 0) ZEND_ARG_INFO(0, const_name) ZEND_END_ARG_INFO() #ifdef HAVE_INET_NTOP ZEND_BEGIN_ARG_INFO(arginfo_inet_ntop, 0) ZEND_ARG_INFO(0, in_addr) ZEND_END_ARG_INFO() #endif #ifdef HAVE_INET_PTON ZEND_BEGIN_ARG_INFO(arginfo_inet_pton, 0) ZEND_ARG_INFO(0, ip_address) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO(arginfo_ip2long, 0) ZEND_ARG_INFO(0, ip_address) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_long2ip, 0) ZEND_ARG_INFO(0, proper_address) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_getenv, 0) ZEND_ARG_INFO(0, varname) ZEND_END_ARG_INFO() #ifdef HAVE_PUTENV ZEND_BEGIN_ARG_INFO(arginfo_putenv, 0) ZEND_ARG_INFO(0, setting) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_getopt, 0, 0, 1) ZEND_ARG_INFO(0, options) ZEND_ARG_INFO(0, opts) /* ARRAY_INFO(0, opts, 1) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_flush, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_sleep, 0) ZEND_ARG_INFO(0, seconds) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_usleep, 0) ZEND_ARG_INFO(0, micro_seconds) ZEND_END_ARG_INFO() #if HAVE_NANOSLEEP ZEND_BEGIN_ARG_INFO(arginfo_time_nanosleep, 0) ZEND_ARG_INFO(0, seconds) ZEND_ARG_INFO(0, nanoseconds) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_time_sleep_until, 0) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO(arginfo_get_current_user, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_get_cfg_var, 0) ZEND_ARG_INFO(0, option_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_error_log, 0, 0, 1) ZEND_ARG_INFO(0, message) ZEND_ARG_INFO(0, message_type) ZEND_ARG_INFO(0, destination) ZEND_ARG_INFO(0, extra_headers) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_error_get_last, 0, 0, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_call_user_func, 0, 0, 1) ZEND_ARG_INFO(0, function_name) ZEND_ARG_INFO(0, parmeter) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_call_user_func_array, 0, 0, 2) ZEND_ARG_INFO(0, function_name) ZEND_ARG_INFO(0, parameters) /* ARRAY_INFO(0, parameters, 1) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_call_user_method, 0, 0, 2) ZEND_ARG_INFO(0, method_name) ZEND_ARG_INFO(1, object) ZEND_ARG_INFO(0, parameter) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_call_user_method_array, 0) ZEND_ARG_INFO(0, method_name) ZEND_ARG_INFO(1, object) ZEND_ARG_INFO(0, params) /* ARRAY_INFO(0, params, 1) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_forward_static_call, 0, 0, 1) ZEND_ARG_INFO(0, function_name) ZEND_ARG_INFO(0, parameter) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_forward_static_call_array, 0, 0, 2) ZEND_ARG_INFO(0, function_name) ZEND_ARG_INFO(0, parameters) /* ARRAY_INFO(0, parameters, 1) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_register_shutdown_function, 0) ZEND_ARG_INFO(0, function_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_highlight_file, 0, 0, 1) ZEND_ARG_INFO(0, file_name) ZEND_ARG_INFO(0, return) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_php_strip_whitespace, 0) ZEND_ARG_INFO(0, file_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_highlight_string, 0, 0, 1) ZEND_ARG_INFO(0, string) ZEND_ARG_INFO(0, return) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ini_get, 0) ZEND_ARG_INFO(0, varname) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ini_get_all, 0, 0, 0) ZEND_ARG_INFO(0, extension) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ini_set, 0) ZEND_ARG_INFO(0, varname) ZEND_ARG_INFO(0, newvalue) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ini_restore, 0) ZEND_ARG_INFO(0, varname) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_set_include_path, 0) ZEND_ARG_INFO(0, new_include_path) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_get_include_path, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_restore_include_path, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_print_r, 0, 0, 1) ZEND_ARG_INFO(0, var) ZEND_ARG_INFO(0, return) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_connection_aborted, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_connection_status, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ignore_user_abort, 0, 0, 0) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() #if HAVE_GETSERVBYNAME ZEND_BEGIN_ARG_INFO(arginfo_getservbyname, 0) ZEND_ARG_INFO(0, service) ZEND_ARG_INFO(0, protocol) ZEND_END_ARG_INFO() #endif #if HAVE_GETSERVBYPORT ZEND_BEGIN_ARG_INFO(arginfo_getservbyport, 0) ZEND_ARG_INFO(0, port) ZEND_ARG_INFO(0, protocol) ZEND_END_ARG_INFO() #endif #if HAVE_GETPROTOBYNAME ZEND_BEGIN_ARG_INFO(arginfo_getprotobyname, 0) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() #endif #if HAVE_GETPROTOBYNUMBER ZEND_BEGIN_ARG_INFO(arginfo_getprotobynumber, 0) ZEND_ARG_INFO(0, proto) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_register_tick_function, 0, 0, 1) ZEND_ARG_INFO(0, function_name) ZEND_ARG_INFO(0, arg) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_unregister_tick_function, 0) ZEND_ARG_INFO(0, function_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_uploaded_file, 0) ZEND_ARG_INFO(0, path) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_move_uploaded_file, 0) ZEND_ARG_INFO(0, path) ZEND_ARG_INFO(0, new_path) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_parse_ini_file, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, process_sections) ZEND_ARG_INFO(0, scanner_mode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_parse_ini_string, 0, 0, 1) ZEND_ARG_INFO(0, ini_string) ZEND_ARG_INFO(0, process_sections) ZEND_ARG_INFO(0, scanner_mode) ZEND_END_ARG_INFO() #if ZEND_DEBUG ZEND_BEGIN_ARG_INFO(arginfo_config_get_hash, 0) ZEND_END_ARG_INFO() #endif #ifdef HAVE_GETLOADAVG ZEND_BEGIN_ARG_INFO(arginfo_sys_getloadavg, 0) ZEND_END_ARG_INFO() #endif /* }}} */ /* {{{ assert.c */ ZEND_BEGIN_ARG_INFO(arginfo_assert, 0) ZEND_ARG_INFO(0, assertion) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_assert_options, 0, 0, 1) ZEND_ARG_INFO(0, what) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() /* }}} */ /* {{{ base64.c */ ZEND_BEGIN_ARG_INFO(arginfo_base64_encode, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_base64_decode, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, strict) ZEND_END_ARG_INFO() /* }}} */ /* {{{ browscap.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_get_browser, 0, 0, 0) ZEND_ARG_INFO(0, browser_name) ZEND_ARG_INFO(0, return_array) ZEND_END_ARG_INFO() /* }}} */ /* {{{ crc32.c */ ZEND_BEGIN_ARG_INFO(arginfo_crc32, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() /* }}} */ /* {{{ crypt.c */ #if HAVE_CRYPT ZEND_BEGIN_ARG_INFO_EX(arginfo_crypt, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, salt) ZEND_END_ARG_INFO() #endif /* }}} */ /* {{{ cyr_convert.c */ ZEND_BEGIN_ARG_INFO(arginfo_convert_cyr_string, 0) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, from) ZEND_ARG_INFO(0, to) ZEND_END_ARG_INFO() /* }}} */ /* {{{ datetime.c */ #if HAVE_STRPTIME ZEND_BEGIN_ARG_INFO(arginfo_strptime, 0) ZEND_ARG_INFO(0, timestamp) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() #endif /* }}} */ /* {{{ dir.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_opendir, 0, 0, 1) ZEND_ARG_INFO(0, path) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_dir, 0, 0, 1) ZEND_ARG_INFO(0, directory) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_closedir, 0, 0, 0) ZEND_ARG_INFO(0, dir_handle) ZEND_END_ARG_INFO() #if defined(HAVE_CHROOT) && !defined(ZTS) && ENABLE_CHROOT_FUNC ZEND_BEGIN_ARG_INFO(arginfo_chroot, 0) ZEND_ARG_INFO(0, directory) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO(arginfo_chdir, 0) ZEND_ARG_INFO(0, directory) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_getcwd, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_rewinddir, 0, 0, 0) ZEND_ARG_INFO(0, dir_handle) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_readdir, 0, 0, 0) ZEND_ARG_INFO(0, dir_handle) ZEND_END_ARG_INFO() #ifdef HAVE_GLOB ZEND_BEGIN_ARG_INFO_EX(arginfo_glob, 0, 0, 1) ZEND_ARG_INFO(0, pattern) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_scandir, 0, 0, 1) ZEND_ARG_INFO(0, dir) ZEND_ARG_INFO(0, sorting_order) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() /* }}} */ /* {{{ arginfo ext/standard/dl.c */ ZEND_BEGIN_ARG_INFO(arginfo_dl, 0) ZEND_ARG_INFO(0, extension_filename) ZEND_END_ARG_INFO() /* }}} */ /* {{{ dns.c */ ZEND_BEGIN_ARG_INFO(arginfo_gethostbyaddr, 0) ZEND_ARG_INFO(0, ip_address) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_gethostbyname, 0) ZEND_ARG_INFO(0, hostname) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_gethostbynamel, 0) ZEND_ARG_INFO(0, hostname) ZEND_END_ARG_INFO() #ifdef HAVE_GETHOSTNAME ZEND_BEGIN_ARG_INFO(arginfo_gethostname, 0) ZEND_END_ARG_INFO() #endif #if defined(PHP_WIN32) || (HAVE_DNS_SEARCH_FUNC && !(defined(__BEOS__) || defined(NETWARE))) ZEND_BEGIN_ARG_INFO_EX(arginfo_dns_check_record, 0, 0, 1) ZEND_ARG_INFO(0, host) ZEND_ARG_INFO(0, type) ZEND_END_ARG_INFO() # if defined(PHP_WIN32) || HAVE_FULL_DNS_FUNCS ZEND_BEGIN_ARG_INFO_EX(arginfo_dns_get_record, 0, 0, 1) ZEND_ARG_INFO(0, hostname) ZEND_ARG_INFO(0, type) ZEND_ARG_ARRAY_INFO(1, authns, 1) ZEND_ARG_ARRAY_INFO(1, addtl, 1) ZEND_ARG_INFO(0, raw) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_dns_get_mx, 0, 0, 2) ZEND_ARG_INFO(0, hostname) ZEND_ARG_INFO(1, mxhosts) /* ARRAY_INFO(1, mxhosts, 1) */ ZEND_ARG_INFO(1, weight) /* ARRAY_INFO(1, weight, 1) */ ZEND_END_ARG_INFO() # endif #endif /* defined(PHP_WIN32) || (HAVE_DNS_SEARCH_FUNC && !(defined(__BEOS__) || defined(NETWARE))) */ /* }}} */ /* {{{ exec.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_exec, 0, 0, 1) ZEND_ARG_INFO(0, command) ZEND_ARG_INFO(1, output) /* ARRAY_INFO(1, output, 1) */ ZEND_ARG_INFO(1, return_value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_system, 0, 0, 1) ZEND_ARG_INFO(0, command) ZEND_ARG_INFO(1, return_value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_passthru, 0, 0, 1) ZEND_ARG_INFO(0, command) ZEND_ARG_INFO(1, return_value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_escapeshellcmd, 0) ZEND_ARG_INFO(0, command) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_escapeshellarg, 0) ZEND_ARG_INFO(0, arg) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_shell_exec, 0) ZEND_ARG_INFO(0, cmd) ZEND_END_ARG_INFO() #ifdef HAVE_NICE ZEND_BEGIN_ARG_INFO(arginfo_proc_nice, 0) ZEND_ARG_INFO(0, priority) ZEND_END_ARG_INFO() #endif /* }}} */ /* {{{ file.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_flock, 0, 0, 2) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, operation) ZEND_ARG_INFO(1, wouldblock) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_get_meta_tags, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, use_include_path) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_get_contents, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, flags) ZEND_ARG_INFO(0, context) ZEND_ARG_INFO(0, offset) ZEND_ARG_INFO(0, maxlen) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_put_contents, 0, 0, 2) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, data) ZEND_ARG_INFO(0, flags) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, flags) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_tempnam, 0) ZEND_ARG_INFO(0, dir) ZEND_ARG_INFO(0, prefix) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_tmpfile, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_fopen, 0, 0, 2) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, mode) ZEND_ARG_INFO(0, use_include_path) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_fclose, 0) ZEND_ARG_INFO(0, fp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_popen, 0) ZEND_ARG_INFO(0, command) ZEND_ARG_INFO(0, mode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_pclose, 0) ZEND_ARG_INFO(0, fp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_feof, 0) ZEND_ARG_INFO(0, fp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_fgets, 0, 0, 1) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, length) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_fgetc, 0) ZEND_ARG_INFO(0, fp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_fgetss, 0, 0, 1) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, length) ZEND_ARG_INFO(0, allowable_tags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_fscanf, 1, 0, 2) ZEND_ARG_INFO(0, stream) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(1, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_fwrite, 0, 0, 2) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, length) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_fflush, 0) ZEND_ARG_INFO(0, fp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_rewind, 0) ZEND_ARG_INFO(0, fp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ftell, 0) ZEND_ARG_INFO(0, fp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_fseek, 0, 0, 2) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, offset) ZEND_ARG_INFO(0, whence) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mkdir, 0, 0, 1) ZEND_ARG_INFO(0, pathname) ZEND_ARG_INFO(0, mode) ZEND_ARG_INFO(0, recursive) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_rmdir, 0, 0, 1) ZEND_ARG_INFO(0, dirname) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_readfile, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, flags) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_umask, 0, 0, 0) ZEND_ARG_INFO(0, mask) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_fpassthru, 0) ZEND_ARG_INFO(0, fp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_rename, 0, 0, 2) ZEND_ARG_INFO(0, old_name) ZEND_ARG_INFO(0, new_name) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_unlink, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ftruncate, 0) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, size) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_fstat, 0) ZEND_ARG_INFO(0, fp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_copy, 0) ZEND_ARG_INFO(0, source_file) ZEND_ARG_INFO(0, destination_file) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_fread, 0) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, length) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_fputcsv, 0, 0, 2) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, fields) /* ARRAY_INFO(0, fields, 1) */ ZEND_ARG_INFO(0, delimiter) ZEND_ARG_INFO(0, enclosure) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_fgetcsv, 0, 0, 1) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, length) ZEND_ARG_INFO(0, delimiter) ZEND_ARG_INFO(0, enclosure) ZEND_ARG_INFO(0, escape) ZEND_END_ARG_INFO() #if (!defined(__BEOS__) && !defined(NETWARE) && HAVE_REALPATH) || defined(ZTS) ZEND_BEGIN_ARG_INFO(arginfo_realpath, 0) ZEND_ARG_INFO(0, path) ZEND_END_ARG_INFO() #endif #ifdef HAVE_FNMATCH ZEND_BEGIN_ARG_INFO_EX(arginfo_fnmatch, 0, 0, 2) ZEND_ARG_INFO(0, pattern) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO(arginfo_sys_get_temp_dir, 0) ZEND_END_ARG_INFO() /* }}} */ /* {{{ filestat.c */ ZEND_BEGIN_ARG_INFO(arginfo_disk_total_space, 0) ZEND_ARG_INFO(0, path) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_disk_free_space, 0) ZEND_ARG_INFO(0, path) ZEND_END_ARG_INFO() #ifndef NETWARE ZEND_BEGIN_ARG_INFO(arginfo_chgrp, 0) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, group) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_chown, 0) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, user) ZEND_END_ARG_INFO() #endif #if HAVE_LCHOWN ZEND_BEGIN_ARG_INFO(arginfo_lchgrp, 0) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, group) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_lchown, 0) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, user) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO(arginfo_chmod, 0) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, mode) ZEND_END_ARG_INFO() #if HAVE_UTIME ZEND_BEGIN_ARG_INFO_EX(arginfo_touch, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, atime) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_clearstatcache, 0, 0, 0) ZEND_ARG_INFO(0, clear_realpath_cache) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_realpath_cache_size, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_realpath_cache_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_fileperms, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_fileinode, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_filesize, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_fileowner, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_filegroup, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_fileatime, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_filemtime, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_filectime, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_filetype, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_writable, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_readable, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_executable, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_file, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_dir, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_link, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_file_exists, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_lstat, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stat, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() /* }}} */ /* {{{ formatted_print.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_sprintf, 0, 0, 2) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, arg1) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_vsprintf, 0) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, args) /* ARRAY_INFO(0, args, 1) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_printf, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, arg1) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_vprintf, 0) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, args) /* ARRAY_INFO(0, args, 1) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_fprintf, 0, 0, 2) ZEND_ARG_INFO(0, stream) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, arg1) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_vfprintf, 0) ZEND_ARG_INFO(0, stream) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, args) /* ARRAY_INFO(0, args, 1) */ ZEND_END_ARG_INFO() /* }}} */ /* {{{ fsock.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_fsockopen, 0, 0, 2) ZEND_ARG_INFO(0, hostname) ZEND_ARG_INFO(0, port) ZEND_ARG_INFO(1, errno) ZEND_ARG_INFO(1, errstr) ZEND_ARG_INFO(0, timeout) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pfsockopen, 0, 0, 2) ZEND_ARG_INFO(0, hostname) ZEND_ARG_INFO(0, port) ZEND_ARG_INFO(1, errno) ZEND_ARG_INFO(1, errstr) ZEND_ARG_INFO(0, timeout) ZEND_END_ARG_INFO() /* }}} */ /* {{{ ftok.c */ #if HAVE_FTOK ZEND_BEGIN_ARG_INFO(arginfo_ftok, 0) ZEND_ARG_INFO(0, pathname) ZEND_ARG_INFO(0, proj) ZEND_END_ARG_INFO() #endif /* }}} */ /* {{{ head.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_header, 0, 0, 1) ZEND_ARG_INFO(0, header) ZEND_ARG_INFO(0, replace) ZEND_ARG_INFO(0, http_response_code) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_header_remove, 0, 0, 0) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_setcookie, 0, 0, 1) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, value) ZEND_ARG_INFO(0, expires) ZEND_ARG_INFO(0, path) ZEND_ARG_INFO(0, domain) ZEND_ARG_INFO(0, secure) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_setrawcookie, 0, 0, 1) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, value) ZEND_ARG_INFO(0, expires) ZEND_ARG_INFO(0, path) ZEND_ARG_INFO(0, domain) ZEND_ARG_INFO(0, secure) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_headers_sent, 0, 0, 0) ZEND_ARG_INFO(1, file) ZEND_ARG_INFO(1, line) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_headers_list, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_http_response_code, 0, 0, 0) ZEND_ARG_INFO(0, response_code) ZEND_END_ARG_INFO() /* }}} */ /* {{{ html.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_htmlspecialchars, 0, 0, 1) ZEND_ARG_INFO(0, string) ZEND_ARG_INFO(0, quote_style) ZEND_ARG_INFO(0, charset) ZEND_ARG_INFO(0, double_encode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_htmlspecialchars_decode, 0, 0, 1) ZEND_ARG_INFO(0, string) ZEND_ARG_INFO(0, quote_style) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_html_entity_decode, 0, 0, 1) ZEND_ARG_INFO(0, string) ZEND_ARG_INFO(0, quote_style) ZEND_ARG_INFO(0, charset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_htmlentities, 0, 0, 1) ZEND_ARG_INFO(0, string) ZEND_ARG_INFO(0, quote_style) ZEND_ARG_INFO(0, charset) ZEND_ARG_INFO(0, double_encode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_get_html_translation_table, 0, 0, 0) ZEND_ARG_INFO(0, table) ZEND_ARG_INFO(0, quote_style) ZEND_END_ARG_INFO() /* }}} */ /* {{{ http.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_http_build_query, 0, 0, 1) ZEND_ARG_INFO(0, formdata) ZEND_ARG_INFO(0, prefix) ZEND_ARG_INFO(0, arg_separator) ZEND_ARG_INFO(0, enc_type) ZEND_END_ARG_INFO() /* }}} */ /* {{{ image.c */ ZEND_BEGIN_ARG_INFO(arginfo_image_type_to_mime_type, 0) ZEND_ARG_INFO(0, imagetype) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_image_type_to_extension, 0, 0, 1) ZEND_ARG_INFO(0, imagetype) ZEND_ARG_INFO(0, include_dot) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_getimagesize, 0, 0, 1) ZEND_ARG_INFO(0, imagefile) ZEND_ARG_INFO(1, info) /* ARRAY_INFO(1, info, 1) */ ZEND_END_ARG_INFO() /* }}} */ /* {{{ info.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_phpinfo, 0, 0, 0) ZEND_ARG_INFO(0, what) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phpversion, 0, 0, 0) ZEND_ARG_INFO(0, extension) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phpcredits, 0, 0, 0) ZEND_ARG_INFO(0, flag) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_php_logo_guid, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_php_real_logo_guid, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_php_egg_logo_guid, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_zend_logo_guid, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_php_sapi_name, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_php_uname, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_php_ini_scanned_files, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_php_ini_loaded_file, 0) ZEND_END_ARG_INFO() /* }}} */ /* {{{ iptc.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_iptcembed, 0, 0, 2) ZEND_ARG_INFO(0, iptcdata) ZEND_ARG_INFO(0, jpeg_file_name) ZEND_ARG_INFO(0, spool) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_iptcparse, 0) ZEND_ARG_INFO(0, iptcdata) ZEND_END_ARG_INFO() /* }}} */ /* {{{ lcg.c */ ZEND_BEGIN_ARG_INFO(arginfo_lcg_value, 0) ZEND_END_ARG_INFO() /* }}} */ /* {{{ levenshtein.c */ ZEND_BEGIN_ARG_INFO(arginfo_levenshtein, 0) ZEND_ARG_INFO(0, str1) ZEND_ARG_INFO(0, str2) ZEND_ARG_INFO(0, cost_ins) ZEND_ARG_INFO(0, cost_rep) ZEND_ARG_INFO(0, cost_del) ZEND_END_ARG_INFO() /* }}} */ /* {{{ link.c */ #if defined(HAVE_SYMLINK) || defined(PHP_WIN32) ZEND_BEGIN_ARG_INFO(arginfo_readlink, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_linkinfo, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_symlink, 0) ZEND_ARG_INFO(0, target) ZEND_ARG_INFO(0, link) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_link, 0) ZEND_ARG_INFO(0, target) ZEND_ARG_INFO(0, link) ZEND_END_ARG_INFO() #endif /* }}} */ /* {{{ mail.c */ ZEND_BEGIN_ARG_INFO(arginfo_ezmlm_hash, 0) ZEND_ARG_INFO(0, addr) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mail, 0, 0, 3) ZEND_ARG_INFO(0, to) ZEND_ARG_INFO(0, subject) ZEND_ARG_INFO(0, message) ZEND_ARG_INFO(0, additional_headers) ZEND_ARG_INFO(0, additional_parameters) ZEND_END_ARG_INFO() /* }}} */ /* {{{ math.c */ ZEND_BEGIN_ARG_INFO(arginfo_abs, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ceil, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_floor, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_round, 0, 0, 1) ZEND_ARG_INFO(0, number) ZEND_ARG_INFO(0, precision) ZEND_ARG_INFO(0, mode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_sin, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_cos, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_tan, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_asin, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_acos, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_atan, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_atan2, 0) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, x) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_sinh, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_cosh, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_tanh, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_asinh, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_acosh, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_atanh, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_pi, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_finite, 0) ZEND_ARG_INFO(0, val) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_infinite, 0) ZEND_ARG_INFO(0, val) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_nan, 0) ZEND_ARG_INFO(0, val) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_pow, 0) ZEND_ARG_INFO(0, base) ZEND_ARG_INFO(0, exponent) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_exp, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_expm1, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_log1p, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_log, 0, 0, 1) ZEND_ARG_INFO(0, number) ZEND_ARG_INFO(0, base) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_log10, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_sqrt, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_hypot, 0) ZEND_ARG_INFO(0, num1) ZEND_ARG_INFO(0, num2) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_deg2rad, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_rad2deg, 0) ZEND_ARG_INFO(0, number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_bindec, 0) ZEND_ARG_INFO(0, binary_number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_hexdec, 0) ZEND_ARG_INFO(0, hexadecimal_number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_octdec, 0) ZEND_ARG_INFO(0, octal_number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_decbin, 0) ZEND_ARG_INFO(0, decimal_number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_decoct, 0) ZEND_ARG_INFO(0, decimal_number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_dechex, 0) ZEND_ARG_INFO(0, decimal_number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_base_convert, 0) ZEND_ARG_INFO(0, number) ZEND_ARG_INFO(0, frombase) ZEND_ARG_INFO(0, tobase) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_number_format, 0, 0, 1) ZEND_ARG_INFO(0, number) ZEND_ARG_INFO(0, num_decimal_places) ZEND_ARG_INFO(0, dec_seperator) ZEND_ARG_INFO(0, thousands_seperator) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_fmod, 0) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_END_ARG_INFO() /* }}} */ /* {{{ md5.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_md5, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, raw_output) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_md5_file, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, raw_output) ZEND_END_ARG_INFO() /* }}} */ /* {{{ metaphone.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_metaphone, 0, 0, 1) ZEND_ARG_INFO(0, text) ZEND_ARG_INFO(0, phones) ZEND_END_ARG_INFO() /* }}} */ /* {{{ microtime.c */ #ifdef HAVE_GETTIMEOFDAY ZEND_BEGIN_ARG_INFO_EX(arginfo_microtime, 0, 0, 0) ZEND_ARG_INFO(0, get_as_float) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_gettimeofday, 0, 0, 0) ZEND_ARG_INFO(0, get_as_float) ZEND_END_ARG_INFO() #endif #ifdef HAVE_GETRUSAGE ZEND_BEGIN_ARG_INFO_EX(arginfo_getrusage, 0, 0, 0) ZEND_ARG_INFO(0, who) ZEND_END_ARG_INFO() #endif /* }}} */ /* {{{ pack.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_pack, 0, 0, 2) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, arg1) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_unpack, 0) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, input) ZEND_END_ARG_INFO() /* }}} */ /* {{{ pageinfo.c */ ZEND_BEGIN_ARG_INFO(arginfo_getmyuid, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_getmygid, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_getmypid, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_getmyinode, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_getlastmod, 0) ZEND_END_ARG_INFO() /* }}} */ /* {{{ proc_open.c */ #ifdef PHP_CAN_SUPPORT_PROC_OPEN ZEND_BEGIN_ARG_INFO_EX(arginfo_proc_terminate, 0, 0, 1) ZEND_ARG_INFO(0, process) ZEND_ARG_INFO(0, signal) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_proc_close, 0) ZEND_ARG_INFO(0, process) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_proc_get_status, 0) ZEND_ARG_INFO(0, process) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_proc_open, 0, 0, 3) ZEND_ARG_INFO(0, command) ZEND_ARG_INFO(0, descriptorspec) /* ARRAY_INFO(0, descriptorspec, 1) */ ZEND_ARG_INFO(1, pipes) /* ARRAY_INFO(1, pipes, 1) */ ZEND_ARG_INFO(0, cwd) ZEND_ARG_INFO(0, env) /* ARRAY_INFO(0, env, 1) */ ZEND_ARG_INFO(0, other_options) /* ARRAY_INFO(0, other_options, 1) */ ZEND_END_ARG_INFO() #endif /* }}} */ /* {{{ quot_print.c */ ZEND_BEGIN_ARG_INFO(arginfo_quoted_printable_decode, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() /* }}} */ /* {{{ quot_print.c */ ZEND_BEGIN_ARG_INFO(arginfo_quoted_printable_encode, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() /* }}} */ /* {{{ rand.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_srand, 0, 0, 0) ZEND_ARG_INFO(0, seed) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mt_srand, 0, 0, 0) ZEND_ARG_INFO(0, seed) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_rand, 0, 0, 0) ZEND_ARG_INFO(0, min) ZEND_ARG_INFO(0, max) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mt_rand, 0, 0, 0) ZEND_ARG_INFO(0, min) ZEND_ARG_INFO(0, max) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_getrandmax, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_mt_getrandmax, 0) ZEND_END_ARG_INFO() /* }}} */ /* {{{ sha1.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_sha1, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, raw_output) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_sha1_file, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, raw_output) ZEND_END_ARG_INFO() /* }}} */ /* {{{ soundex.c */ ZEND_BEGIN_ARG_INFO(arginfo_soundex, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() /* }}} */ /* {{{ streamsfuncs.c */ #if HAVE_SOCKETPAIR ZEND_BEGIN_ARG_INFO(arginfo_stream_socket_pair, 0) ZEND_ARG_INFO(0, domain) ZEND_ARG_INFO(0, type) ZEND_ARG_INFO(0, protocol) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_socket_client, 0, 0, 1) ZEND_ARG_INFO(0, remoteaddress) ZEND_ARG_INFO(1, errcode) ZEND_ARG_INFO(1, errstring) ZEND_ARG_INFO(0, timeout) ZEND_ARG_INFO(0, flags) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_socket_server, 0, 0, 1) ZEND_ARG_INFO(0, localaddress) ZEND_ARG_INFO(1, errcode) ZEND_ARG_INFO(1, errstring) ZEND_ARG_INFO(0, flags) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_socket_accept, 0, 0, 1) ZEND_ARG_INFO(0, serverstream) ZEND_ARG_INFO(0, timeout) ZEND_ARG_INFO(1, peername) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_socket_get_name, 0) ZEND_ARG_INFO(0, stream) ZEND_ARG_INFO(0, want_peer) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_socket_sendto, 0, 0, 2) ZEND_ARG_INFO(0, stream) ZEND_ARG_INFO(0, data) ZEND_ARG_INFO(0, flags) ZEND_ARG_INFO(0, target_addr) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_socket_recvfrom, 0, 0, 2) ZEND_ARG_INFO(0, stream) ZEND_ARG_INFO(0, amount) ZEND_ARG_INFO(0, flags) ZEND_ARG_INFO(1, remote_addr) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_get_contents, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_ARG_INFO(0, maxlen) ZEND_ARG_INFO(0, offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_copy_to_stream, 0, 0, 2) ZEND_ARG_INFO(0, source) ZEND_ARG_INFO(0, dest) ZEND_ARG_INFO(0, maxlen) ZEND_ARG_INFO(0, pos) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_get_meta_data, 0) ZEND_ARG_INFO(0, fp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_get_transports, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_get_wrappers, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_resolve_include_path, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_is_local, 0) ZEND_ARG_INFO(0, stream) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_supports_lock, 0, 0, 1) ZEND_ARG_INFO(0, stream) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_select, 0, 0, 4) ZEND_ARG_INFO(1, read_streams) /* ARRAY_INFO(1, read_streams, 1) */ ZEND_ARG_INFO(1, write_streams) /* ARRAY_INFO(1, write_streams, 1) */ ZEND_ARG_INFO(1, except_streams) /* ARRAY_INFO(1, except_streams, 1) */ ZEND_ARG_INFO(0, tv_sec) ZEND_ARG_INFO(0, tv_usec) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_context_get_options, 0) ZEND_ARG_INFO(0, stream_or_context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_context_set_option, 0) ZEND_ARG_INFO(0, stream_or_context) ZEND_ARG_INFO(0, wrappername) ZEND_ARG_INFO(0, optionname) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_context_set_params, 0) ZEND_ARG_INFO(0, stream_or_context) ZEND_ARG_INFO(0, options) /* ARRAY_INFO(0, options, 1) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_context_get_params, 0, ZEND_RETURN_VALUE, 1) ZEND_ARG_INFO(0, stream_or_context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_context_get_default, 0, 0, 0) ZEND_ARG_INFO(0, options) /* ARRAY_INFO(0, options, 1) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_context_set_default, 0) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_context_create, 0, 0, 0) ZEND_ARG_INFO(0, options) /* ARRAY_INFO(0, options, 1) */ ZEND_ARG_INFO(0, params) /* ARRAY_INFO(0, params, 1) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_filter_prepend, 0, 0, 2) ZEND_ARG_INFO(0, stream) ZEND_ARG_INFO(0, filtername) ZEND_ARG_INFO(0, read_write) ZEND_ARG_INFO(0, filterparams) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_filter_append, 0, 0, 2) ZEND_ARG_INFO(0, stream) ZEND_ARG_INFO(0, filtername) ZEND_ARG_INFO(0, read_write) ZEND_ARG_INFO(0, filterparams) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_filter_remove, 0) ZEND_ARG_INFO(0, stream_filter) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_get_line, 0, 0, 2) ZEND_ARG_INFO(0, stream) ZEND_ARG_INFO(0, maxlen) ZEND_ARG_INFO(0, ending) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_set_blocking, 0) ZEND_ARG_INFO(0, socket) ZEND_ARG_INFO(0, mode) ZEND_END_ARG_INFO() #if HAVE_SYS_TIME_H || defined(PHP_WIN32) ZEND_BEGIN_ARG_INFO(arginfo_stream_set_timeout, 0) ZEND_ARG_INFO(0, stream) ZEND_ARG_INFO(0, seconds) ZEND_ARG_INFO(0, microseconds) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO(arginfo_stream_set_read_buffer, 0) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, buffer) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_set_write_buffer, 0) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, buffer) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_set_chunk_size, 0) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, chunk_size) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stream_socket_enable_crypto, 0, 0, 2) ZEND_ARG_INFO(0, stream) ZEND_ARG_INFO(0, enable) ZEND_ARG_INFO(0, cryptokind) ZEND_ARG_INFO(0, sessionstream) ZEND_END_ARG_INFO() #ifdef HAVE_SHUTDOWN ZEND_BEGIN_ARG_INFO(arginfo_stream_socket_shutdown, 0) ZEND_ARG_INFO(0, stream) ZEND_ARG_INFO(0, how) ZEND_END_ARG_INFO() #endif /* }}} */ /* {{{ string.c */ ZEND_BEGIN_ARG_INFO(arginfo_bin2hex, 0) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_hex2bin, 0) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strspn, 0, 0, 2) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, mask) ZEND_ARG_INFO(0, start) ZEND_ARG_INFO(0, len) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strcspn, 0, 0, 2) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, mask) ZEND_ARG_INFO(0, start) ZEND_ARG_INFO(0, len) ZEND_END_ARG_INFO() #if HAVE_NL_LANGINFO ZEND_BEGIN_ARG_INFO(arginfo_nl_langinfo, 0) ZEND_ARG_INFO(0, item) ZEND_END_ARG_INFO() #endif #ifdef HAVE_STRCOLL ZEND_BEGIN_ARG_INFO(arginfo_strcoll, 0) ZEND_ARG_INFO(0, str1) ZEND_ARG_INFO(0, str2) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_trim, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, character_mask) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_rtrim, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, character_mask) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ltrim, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, character_mask) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wordwrap, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, width) ZEND_ARG_INFO(0, break) ZEND_ARG_INFO(0, cut) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_explode, 0, 0, 2) ZEND_ARG_INFO(0, separator) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, limit) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_implode, 0) ZEND_ARG_INFO(0, glue) ZEND_ARG_INFO(0, pieces) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_strtok, 0) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, token) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_strtoupper, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_strtolower, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_basename, 0, 0, 1) ZEND_ARG_INFO(0, path) ZEND_ARG_INFO(0, suffix) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_dirname, 0) ZEND_ARG_INFO(0, path) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pathinfo, 0, 0, 1) ZEND_ARG_INFO(0, path) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stristr, 0, 0, 2) ZEND_ARG_INFO(0, haystack) ZEND_ARG_INFO(0, needle) ZEND_ARG_INFO(0, part) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strstr, 0, 0, 2) ZEND_ARG_INFO(0, haystack) ZEND_ARG_INFO(0, needle) ZEND_ARG_INFO(0, part) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strpos, 0, 0, 2) ZEND_ARG_INFO(0, haystack) ZEND_ARG_INFO(0, needle) ZEND_ARG_INFO(0, offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_stripos, 0, 0, 2) ZEND_ARG_INFO(0, haystack) ZEND_ARG_INFO(0, needle) ZEND_ARG_INFO(0, offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strrpos, 0, 0, 2) ZEND_ARG_INFO(0, haystack) ZEND_ARG_INFO(0, needle) ZEND_ARG_INFO(0, offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strripos, 0, 0, 2) ZEND_ARG_INFO(0, haystack) ZEND_ARG_INFO(0, needle) ZEND_ARG_INFO(0, offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_strrchr, 0) ZEND_ARG_INFO(0, haystack) ZEND_ARG_INFO(0, needle) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_chunk_split, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, chunklen) ZEND_ARG_INFO(0, ending) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_substr, 0, 0, 2) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, start) ZEND_ARG_INFO(0, length) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_substr_replace, 0, 0, 3) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, replace) ZEND_ARG_INFO(0, start) ZEND_ARG_INFO(0, length) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_quotemeta, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ord, 0) ZEND_ARG_INFO(0, character) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_chr, 0) ZEND_ARG_INFO(0, codepoint) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ucfirst, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_lcfirst, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ucwords, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strtr, 0, 0, 2) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, from) ZEND_ARG_INFO(0, to) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_strrev, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_similar_text, 0, 0, 2) ZEND_ARG_INFO(0, str1) ZEND_ARG_INFO(0, str2) ZEND_ARG_INFO(1, percent) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_addcslashes, 0) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, charlist) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_addslashes, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stripcslashes, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stripslashes, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_str_replace, 0, 0, 3) ZEND_ARG_INFO(0, search) ZEND_ARG_INFO(0, replace) ZEND_ARG_INFO(0, subject) ZEND_ARG_INFO(1, replace_count) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_str_ireplace, 0, 0, 3) ZEND_ARG_INFO(0, search) ZEND_ARG_INFO(0, replace) ZEND_ARG_INFO(0, subject) ZEND_ARG_INFO(1, replace_count) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_hebrev, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, max_chars_per_line) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_hebrevc, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, max_chars_per_line) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_nl2br, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, is_xhtml) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strip_tags, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, allowable_tags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_setlocale, 0, 0, 2) ZEND_ARG_INFO(0, category) ZEND_ARG_INFO(0, locale) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_parse_str, 0, 0, 1) ZEND_ARG_INFO(0, encoded_string) ZEND_ARG_INFO(1, result) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_str_getcsv, 0, 0, 1) ZEND_ARG_INFO(0, string) ZEND_ARG_INFO(0, delimiter) ZEND_ARG_INFO(0, enclosure) ZEND_ARG_INFO(0, escape) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_str_repeat, 0) ZEND_ARG_INFO(0, input) ZEND_ARG_INFO(0, mult) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_count_chars, 0, 0, 1) ZEND_ARG_INFO(0, input) ZEND_ARG_INFO(0, mode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_strnatcmp, 0) ZEND_ARG_INFO(0, s1) ZEND_ARG_INFO(0, s2) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_localeconv, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_strnatcasecmp, 0) ZEND_ARG_INFO(0, s1) ZEND_ARG_INFO(0, s2) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_substr_count, 0, 0, 2) ZEND_ARG_INFO(0, haystack) ZEND_ARG_INFO(0, needle) ZEND_ARG_INFO(0, offset) ZEND_ARG_INFO(0, length) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_str_pad, 0, 0, 2) ZEND_ARG_INFO(0, input) ZEND_ARG_INFO(0, pad_length) ZEND_ARG_INFO(0, pad_string) ZEND_ARG_INFO(0, pad_type) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_sscanf, 1, 0, 2) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(1, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_str_rot13, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_str_shuffle, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_str_word_count, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, charlist) ZEND_END_ARG_INFO() #ifdef HAVE_STRFMON ZEND_BEGIN_ARG_INFO(arginfo_money_format, 0) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_str_split, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, split_length) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strpbrk, 0, 0, 1) ZEND_ARG_INFO(0, haystack) ZEND_ARG_INFO(0, char_list) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_substr_compare, 0, 0, 3) ZEND_ARG_INFO(0, main_str) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, offset) ZEND_ARG_INFO(0, length) ZEND_ARG_INFO(0, case_sensitivity) ZEND_END_ARG_INFO() /* }}} */ /* {{{ syslog.c */ #ifdef HAVE_SYSLOG_H ZEND_BEGIN_ARG_INFO(arginfo_openlog, 0) ZEND_ARG_INFO(0, ident) ZEND_ARG_INFO(0, option) ZEND_ARG_INFO(0, facility) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_closelog, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_syslog, 0) ZEND_ARG_INFO(0, priority) ZEND_ARG_INFO(0, message) ZEND_END_ARG_INFO() #endif /* }}} */ /* {{{ type.c */ ZEND_BEGIN_ARG_INFO(arginfo_gettype, 0) ZEND_ARG_INFO(0, var) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_settype, 0) ZEND_ARG_INFO(1, var) ZEND_ARG_INFO(0, type) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_intval, 0, 0, 1) ZEND_ARG_INFO(0, var) ZEND_ARG_INFO(0, base) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_floatval, 0) ZEND_ARG_INFO(0, var) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_strval, 0) ZEND_ARG_INFO(0, var) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_null, 0) ZEND_ARG_INFO(0, var) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_resource, 0) ZEND_ARG_INFO(0, var) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_bool, 0) ZEND_ARG_INFO(0, var) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_long, 0) ZEND_ARG_INFO(0, var) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_float, 0) ZEND_ARG_INFO(0, var) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_string, 0) ZEND_ARG_INFO(0, var) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_array, 0) ZEND_ARG_INFO(0, var) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_object, 0) ZEND_ARG_INFO(0, var) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_numeric, 0) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_is_scalar, 0) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_is_callable, 0, 0, 1) ZEND_ARG_INFO(0, var) ZEND_ARG_INFO(0, syntax_only) ZEND_ARG_INFO(1, callable_name) ZEND_END_ARG_INFO() /* }}} */ /* {{{ uniqid.c */ #ifdef HAVE_GETTIMEOFDAY ZEND_BEGIN_ARG_INFO_EX(arginfo_uniqid, 0, 0, 0) ZEND_ARG_INFO(0, prefix) ZEND_ARG_INFO(0, more_entropy) ZEND_END_ARG_INFO() #endif /* }}} */ /* {{{ url.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_parse_url, 0, 0, 1) ZEND_ARG_INFO(0, url) ZEND_ARG_INFO(0, component) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_urlencode, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_urldecode, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_rawurlencode, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_rawurldecode, 0) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_get_headers, 0, 0, 1) ZEND_ARG_INFO(0, url) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() /* }}} */ /* {{{ user_filters.c */ ZEND_BEGIN_ARG_INFO(arginfo_stream_bucket_make_writeable, 0) ZEND_ARG_INFO(0, brigade) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_bucket_prepend, 0) ZEND_ARG_INFO(0, brigade) ZEND_ARG_INFO(0, bucket) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_bucket_append, 0) ZEND_ARG_INFO(0, brigade) ZEND_ARG_INFO(0, bucket) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_bucket_new, 0) ZEND_ARG_INFO(0, stream) ZEND_ARG_INFO(0, buffer) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_get_filters, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_stream_filter_register, 0) ZEND_ARG_INFO(0, filtername) ZEND_ARG_INFO(0, classname) ZEND_END_ARG_INFO() /* }}} */ /* {{{ uuencode.c */ ZEND_BEGIN_ARG_INFO(arginfo_convert_uuencode, 0) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_convert_uudecode, 0) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO() /* }}} */ /* {{{ var.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_var_dump, 0, 0, 1) ZEND_ARG_INFO(0, var) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_debug_zval_dump, 0, 0, 1) ZEND_ARG_INFO(0, var) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_var_export, 0, 0, 1) ZEND_ARG_INFO(0, var) ZEND_ARG_INFO(0, return) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_serialize, 0) ZEND_ARG_INFO(0, var) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_unserialize, 0) ZEND_ARG_INFO(0, variable_representation) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_memory_get_usage, 0, 0, 0) ZEND_ARG_INFO(0, real_usage) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_memory_get_peak_usage, 0, 0, 0) ZEND_ARG_INFO(0, real_usage) ZEND_END_ARG_INFO() /* }}} */ /* {{{ versioning.c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_version_compare, 0, 0, 2) ZEND_ARG_INFO(0, ver1) ZEND_ARG_INFO(0, ver2) ZEND_ARG_INFO(0, oper) ZEND_END_ARG_INFO() /* }}} */ /* }}} */ const zend_function_entry basic_functions[] = { /* {{{ */ PHP_FE(constant, arginfo_constant) PHP_FE(bin2hex, arginfo_bin2hex) PHP_FE(hex2bin, arginfo_hex2bin) PHP_FE(sleep, arginfo_sleep) PHP_FE(usleep, arginfo_usleep) #if HAVE_NANOSLEEP PHP_FE(time_nanosleep, arginfo_time_nanosleep) PHP_FE(time_sleep_until, arginfo_time_sleep_until) #endif #if HAVE_STRPTIME PHP_FE(strptime, arginfo_strptime) #endif PHP_FE(flush, arginfo_flush) PHP_FE(wordwrap, arginfo_wordwrap) PHP_FE(htmlspecialchars, arginfo_htmlspecialchars) PHP_FE(htmlentities, arginfo_htmlentities) PHP_FE(html_entity_decode, arginfo_html_entity_decode) PHP_FE(htmlspecialchars_decode, arginfo_htmlspecialchars_decode) PHP_FE(get_html_translation_table, arginfo_get_html_translation_table) PHP_FE(sha1, arginfo_sha1) PHP_FE(sha1_file, arginfo_sha1_file) PHP_NAMED_FE(md5,php_if_md5, arginfo_md5) PHP_NAMED_FE(md5_file,php_if_md5_file, arginfo_md5_file) PHP_NAMED_FE(crc32,php_if_crc32, arginfo_crc32) PHP_FE(iptcparse, arginfo_iptcparse) PHP_FE(iptcembed, arginfo_iptcembed) PHP_FE(getimagesize, arginfo_getimagesize) PHP_FE(getimagesizefromstring, arginfo_getimagesize) PHP_FE(image_type_to_mime_type, arginfo_image_type_to_mime_type) PHP_FE(image_type_to_extension, arginfo_image_type_to_extension) PHP_FE(phpinfo, arginfo_phpinfo) PHP_FE(phpversion, arginfo_phpversion) PHP_FE(phpcredits, arginfo_phpcredits) PHP_FE(php_logo_guid, arginfo_php_logo_guid) PHP_FE(php_real_logo_guid, arginfo_php_real_logo_guid) PHP_FE(php_egg_logo_guid, arginfo_php_egg_logo_guid) PHP_FE(zend_logo_guid, arginfo_zend_logo_guid) PHP_FE(php_sapi_name, arginfo_php_sapi_name) PHP_FE(php_uname, arginfo_php_uname) PHP_FE(php_ini_scanned_files, arginfo_php_ini_scanned_files) PHP_FE(php_ini_loaded_file, arginfo_php_ini_loaded_file) PHP_FE(strnatcmp, arginfo_strnatcmp) PHP_FE(strnatcasecmp, arginfo_strnatcasecmp) PHP_FE(substr_count, arginfo_substr_count) PHP_FE(strspn, arginfo_strspn) PHP_FE(strcspn, arginfo_strcspn) PHP_FE(strtok, arginfo_strtok) PHP_FE(strtoupper, arginfo_strtoupper) PHP_FE(strtolower, arginfo_strtolower) PHP_FE(strpos, arginfo_strpos) PHP_FE(stripos, arginfo_stripos) PHP_FE(strrpos, arginfo_strrpos) PHP_FE(strripos, arginfo_strripos) PHP_FE(strrev, arginfo_strrev) PHP_FE(hebrev, arginfo_hebrev) PHP_FE(hebrevc, arginfo_hebrevc) PHP_FE(nl2br, arginfo_nl2br) PHP_FE(basename, arginfo_basename) PHP_FE(dirname, arginfo_dirname) PHP_FE(pathinfo, arginfo_pathinfo) PHP_FE(stripslashes, arginfo_stripslashes) PHP_FE(stripcslashes, arginfo_stripcslashes) PHP_FE(strstr, arginfo_strstr) PHP_FE(stristr, arginfo_stristr) PHP_FE(strrchr, arginfo_strrchr) PHP_FE(str_shuffle, arginfo_str_shuffle) PHP_FE(str_word_count, arginfo_str_word_count) PHP_FE(str_split, arginfo_str_split) PHP_FE(strpbrk, arginfo_strpbrk) PHP_FE(substr_compare, arginfo_substr_compare) #ifdef HAVE_STRCOLL PHP_FE(strcoll, arginfo_strcoll) #endif #ifdef HAVE_STRFMON PHP_FE(money_format, arginfo_money_format) #endif PHP_FE(substr, arginfo_substr) PHP_FE(substr_replace, arginfo_substr_replace) PHP_FE(quotemeta, arginfo_quotemeta) PHP_FE(ucfirst, arginfo_ucfirst) PHP_FE(lcfirst, arginfo_lcfirst) PHP_FE(ucwords, arginfo_ucwords) PHP_FE(strtr, arginfo_strtr) PHP_FE(addslashes, arginfo_addslashes) PHP_FE(addcslashes, arginfo_addcslashes) PHP_FE(rtrim, arginfo_rtrim) PHP_FE(str_replace, arginfo_str_replace) PHP_FE(str_ireplace, arginfo_str_ireplace) PHP_FE(str_repeat, arginfo_str_repeat) PHP_FE(count_chars, arginfo_count_chars) PHP_FE(chunk_split, arginfo_chunk_split) PHP_FE(trim, arginfo_trim) PHP_FE(ltrim, arginfo_ltrim) PHP_FE(strip_tags, arginfo_strip_tags) PHP_FE(similar_text, arginfo_similar_text) PHP_FE(explode, arginfo_explode) PHP_FE(implode, arginfo_implode) PHP_FALIAS(join, implode, arginfo_implode) PHP_FE(setlocale, arginfo_setlocale) PHP_FE(localeconv, arginfo_localeconv) #if HAVE_NL_LANGINFO PHP_FE(nl_langinfo, arginfo_nl_langinfo) #endif PHP_FE(soundex, arginfo_soundex) PHP_FE(levenshtein, arginfo_levenshtein) PHP_FE(chr, arginfo_chr) PHP_FE(ord, arginfo_ord) PHP_FE(parse_str, arginfo_parse_str) PHP_FE(str_getcsv, arginfo_str_getcsv) PHP_FE(str_pad, arginfo_str_pad) PHP_FALIAS(chop, rtrim, arginfo_rtrim) PHP_FALIAS(strchr, strstr, arginfo_strstr) PHP_NAMED_FE(sprintf, PHP_FN(user_sprintf), arginfo_sprintf) PHP_NAMED_FE(printf, PHP_FN(user_printf), arginfo_printf) PHP_FE(vprintf, arginfo_vprintf) PHP_FE(vsprintf, arginfo_vsprintf) PHP_FE(fprintf, arginfo_fprintf) PHP_FE(vfprintf, arginfo_vfprintf) PHP_FE(sscanf, arginfo_sscanf) PHP_FE(fscanf, arginfo_fscanf) PHP_FE(parse_url, arginfo_parse_url) PHP_FE(urlencode, arginfo_urlencode) PHP_FE(urldecode, arginfo_urldecode) PHP_FE(rawurlencode, arginfo_rawurlencode) PHP_FE(rawurldecode, arginfo_rawurldecode) PHP_FE(http_build_query, arginfo_http_build_query) #if defined(HAVE_SYMLINK) || defined(PHP_WIN32) PHP_FE(readlink, arginfo_readlink) PHP_FE(linkinfo, arginfo_linkinfo) PHP_FE(symlink, arginfo_symlink) PHP_FE(link, arginfo_link) #endif PHP_FE(unlink, arginfo_unlink) PHP_FE(exec, arginfo_exec) PHP_FE(system, arginfo_system) PHP_FE(escapeshellcmd, arginfo_escapeshellcmd) PHP_FE(escapeshellarg, arginfo_escapeshellarg) PHP_FE(passthru, arginfo_passthru) PHP_FE(shell_exec, arginfo_shell_exec) #ifdef PHP_CAN_SUPPORT_PROC_OPEN PHP_FE(proc_open, arginfo_proc_open) PHP_FE(proc_close, arginfo_proc_close) PHP_FE(proc_terminate, arginfo_proc_terminate) PHP_FE(proc_get_status, arginfo_proc_get_status) #endif #ifdef HAVE_NICE PHP_FE(proc_nice, arginfo_proc_nice) #endif PHP_FE(rand, arginfo_rand) PHP_FE(srand, arginfo_srand) PHP_FE(getrandmax, arginfo_getrandmax) PHP_FE(mt_rand, arginfo_mt_rand) PHP_FE(mt_srand, arginfo_mt_srand) PHP_FE(mt_getrandmax, arginfo_mt_getrandmax) #if HAVE_GETSERVBYNAME PHP_FE(getservbyname, arginfo_getservbyname) #endif #if HAVE_GETSERVBYPORT PHP_FE(getservbyport, arginfo_getservbyport) #endif #if HAVE_GETPROTOBYNAME PHP_FE(getprotobyname, arginfo_getprotobyname) #endif #if HAVE_GETPROTOBYNUMBER PHP_FE(getprotobynumber, arginfo_getprotobynumber) #endif PHP_FE(getmyuid, arginfo_getmyuid) PHP_FE(getmygid, arginfo_getmygid) PHP_FE(getmypid, arginfo_getmypid) PHP_FE(getmyinode, arginfo_getmyinode) PHP_FE(getlastmod, arginfo_getlastmod) PHP_FE(base64_decode, arginfo_base64_decode) PHP_FE(base64_encode, arginfo_base64_encode) PHP_FE(convert_uuencode, arginfo_convert_uuencode) PHP_FE(convert_uudecode, arginfo_convert_uudecode) PHP_FE(abs, arginfo_abs) PHP_FE(ceil, arginfo_ceil) PHP_FE(floor, arginfo_floor) PHP_FE(round, arginfo_round) PHP_FE(sin, arginfo_sin) PHP_FE(cos, arginfo_cos) PHP_FE(tan, arginfo_tan) PHP_FE(asin, arginfo_asin) PHP_FE(acos, arginfo_acos) PHP_FE(atan, arginfo_atan) PHP_FE(atanh, arginfo_atanh) PHP_FE(atan2, arginfo_atan2) PHP_FE(sinh, arginfo_sinh) PHP_FE(cosh, arginfo_cosh) PHP_FE(tanh, arginfo_tanh) PHP_FE(asinh, arginfo_asinh) PHP_FE(acosh, arginfo_acosh) PHP_FE(expm1, arginfo_expm1) PHP_FE(log1p, arginfo_log1p) PHP_FE(pi, arginfo_pi) PHP_FE(is_finite, arginfo_is_finite) PHP_FE(is_nan, arginfo_is_nan) PHP_FE(is_infinite, arginfo_is_infinite) PHP_FE(pow, arginfo_pow) PHP_FE(exp, arginfo_exp) PHP_FE(log, arginfo_log) PHP_FE(log10, arginfo_log10) PHP_FE(sqrt, arginfo_sqrt) PHP_FE(hypot, arginfo_hypot) PHP_FE(deg2rad, arginfo_deg2rad) PHP_FE(rad2deg, arginfo_rad2deg) PHP_FE(bindec, arginfo_bindec) PHP_FE(hexdec, arginfo_hexdec) PHP_FE(octdec, arginfo_octdec) PHP_FE(decbin, arginfo_decbin) PHP_FE(decoct, arginfo_decoct) PHP_FE(dechex, arginfo_dechex) PHP_FE(base_convert, arginfo_base_convert) PHP_FE(number_format, arginfo_number_format) PHP_FE(fmod, arginfo_fmod) #ifdef HAVE_INET_NTOP PHP_RAW_NAMED_FE(inet_ntop, php_inet_ntop, arginfo_inet_ntop) #endif #ifdef HAVE_INET_PTON PHP_RAW_NAMED_FE(inet_pton, php_inet_pton, arginfo_inet_pton) #endif PHP_FE(ip2long, arginfo_ip2long) PHP_FE(long2ip, arginfo_long2ip) PHP_FE(getenv, arginfo_getenv) #ifdef HAVE_PUTENV PHP_FE(putenv, arginfo_putenv) #endif PHP_FE(getopt, arginfo_getopt) #ifdef HAVE_GETLOADAVG PHP_FE(sys_getloadavg, arginfo_sys_getloadavg) #endif #ifdef HAVE_GETTIMEOFDAY PHP_FE(microtime, arginfo_microtime) PHP_FE(gettimeofday, arginfo_gettimeofday) #endif #ifdef HAVE_GETRUSAGE PHP_FE(getrusage, arginfo_getrusage) #endif #ifdef HAVE_GETTIMEOFDAY PHP_FE(uniqid, arginfo_uniqid) #endif PHP_FE(quoted_printable_decode, arginfo_quoted_printable_decode) PHP_FE(quoted_printable_encode, arginfo_quoted_printable_encode) PHP_FE(convert_cyr_string, arginfo_convert_cyr_string) PHP_FE(get_current_user, arginfo_get_current_user) PHP_FE(set_time_limit, arginfo_set_time_limit) PHP_FE(header_register_callback, arginfo_header_register_callback) PHP_FE(get_cfg_var, arginfo_get_cfg_var) PHP_DEP_FALIAS(magic_quotes_runtime, set_magic_quotes_runtime, arginfo_set_magic_quotes_runtime) PHP_DEP_FE(set_magic_quotes_runtime, arginfo_set_magic_quotes_runtime) PHP_FE(get_magic_quotes_gpc, arginfo_get_magic_quotes_gpc) PHP_FE(get_magic_quotes_runtime, arginfo_get_magic_quotes_runtime) PHP_FE(error_log, arginfo_error_log) PHP_FE(error_get_last, arginfo_error_get_last) PHP_FE(call_user_func, arginfo_call_user_func) PHP_FE(call_user_func_array, arginfo_call_user_func_array) PHP_DEP_FE(call_user_method, arginfo_call_user_method) PHP_DEP_FE(call_user_method_array, arginfo_call_user_method_array) PHP_FE(forward_static_call, arginfo_forward_static_call) PHP_FE(forward_static_call_array, arginfo_forward_static_call_array) PHP_FE(serialize, arginfo_serialize) PHP_FE(unserialize, arginfo_unserialize) PHP_FE(var_dump, arginfo_var_dump) PHP_FE(var_export, arginfo_var_export) PHP_FE(debug_zval_dump, arginfo_debug_zval_dump) PHP_FE(print_r, arginfo_print_r) PHP_FE(memory_get_usage, arginfo_memory_get_usage) PHP_FE(memory_get_peak_usage, arginfo_memory_get_peak_usage) PHP_FE(register_shutdown_function, arginfo_register_shutdown_function) PHP_FE(register_tick_function, arginfo_register_tick_function) PHP_FE(unregister_tick_function, arginfo_unregister_tick_function) PHP_FE(highlight_file, arginfo_highlight_file) PHP_FALIAS(show_source, highlight_file, arginfo_highlight_file) PHP_FE(highlight_string, arginfo_highlight_string) PHP_FE(php_strip_whitespace, arginfo_php_strip_whitespace) PHP_FE(ini_get, arginfo_ini_get) PHP_FE(ini_get_all, arginfo_ini_get_all) PHP_FE(ini_set, arginfo_ini_set) PHP_FALIAS(ini_alter, ini_set, arginfo_ini_set) PHP_FE(ini_restore, arginfo_ini_restore) PHP_FE(get_include_path, arginfo_get_include_path) PHP_FE(set_include_path, arginfo_set_include_path) PHP_FE(restore_include_path, arginfo_restore_include_path) PHP_FE(setcookie, arginfo_setcookie) PHP_FE(setrawcookie, arginfo_setrawcookie) PHP_FE(header, arginfo_header) PHP_FE(header_remove, arginfo_header_remove) PHP_FE(headers_sent, arginfo_headers_sent) PHP_FE(headers_list, arginfo_headers_list) PHP_FE(http_response_code, arginfo_http_response_code) PHP_FE(connection_aborted, arginfo_connection_aborted) PHP_FE(connection_status, arginfo_connection_status) PHP_FE(ignore_user_abort, arginfo_ignore_user_abort) PHP_FE(parse_ini_file, arginfo_parse_ini_file) PHP_FE(parse_ini_string, arginfo_parse_ini_string) #if ZEND_DEBUG PHP_FE(config_get_hash, arginfo_config_get_hash) #endif PHP_FE(is_uploaded_file, arginfo_is_uploaded_file) PHP_FE(move_uploaded_file, arginfo_move_uploaded_file) /* functions from dns.c */ PHP_FE(gethostbyaddr, arginfo_gethostbyaddr) PHP_FE(gethostbyname, arginfo_gethostbyname) PHP_FE(gethostbynamel, arginfo_gethostbynamel) #ifdef HAVE_GETHOSTNAME PHP_FE(gethostname, arginfo_gethostname) #endif #if defined(PHP_WIN32) || (HAVE_DNS_SEARCH_FUNC && !(defined(__BEOS__) || defined(NETWARE))) PHP_FE(dns_check_record, arginfo_dns_check_record) PHP_FALIAS(checkdnsrr, dns_check_record, arginfo_dns_check_record) # if defined(PHP_WIN32) || HAVE_FULL_DNS_FUNCS PHP_FE(dns_get_mx, arginfo_dns_get_mx) PHP_FALIAS(getmxrr, dns_get_mx, arginfo_dns_get_mx) PHP_FE(dns_get_record, arginfo_dns_get_record) # endif #endif /* functions from type.c */ PHP_FE(intval, arginfo_intval) PHP_FE(floatval, arginfo_floatval) PHP_FALIAS(doubleval, floatval, arginfo_floatval) PHP_FE(strval, arginfo_strval) PHP_FE(gettype, arginfo_gettype) PHP_FE(settype, arginfo_settype) PHP_FE(is_null, arginfo_is_null) PHP_FE(is_resource, arginfo_is_resource) PHP_FE(is_bool, arginfo_is_bool) PHP_FE(is_long, arginfo_is_long) PHP_FE(is_float, arginfo_is_float) PHP_FALIAS(is_int, is_long, arginfo_is_long) PHP_FALIAS(is_integer, is_long, arginfo_is_long) PHP_FALIAS(is_double, is_float, arginfo_is_float) PHP_FALIAS(is_real, is_float, arginfo_is_float) PHP_FE(is_numeric, arginfo_is_numeric) PHP_FE(is_string, arginfo_is_string) PHP_FE(is_array, arginfo_is_array) PHP_FE(is_object, arginfo_is_object) PHP_FE(is_scalar, arginfo_is_scalar) PHP_FE(is_callable, arginfo_is_callable) /* functions from file.c */ PHP_FE(pclose, arginfo_pclose) PHP_FE(popen, arginfo_popen) PHP_FE(readfile, arginfo_readfile) PHP_FE(rewind, arginfo_rewind) PHP_FE(rmdir, arginfo_rmdir) PHP_FE(umask, arginfo_umask) PHP_FE(fclose, arginfo_fclose) PHP_FE(feof, arginfo_feof) PHP_FE(fgetc, arginfo_fgetc) PHP_FE(fgets, arginfo_fgets) PHP_FE(fgetss, arginfo_fgetss) PHP_FE(fread, arginfo_fread) PHP_NAMED_FE(fopen, php_if_fopen, arginfo_fopen) PHP_FE(fpassthru, arginfo_fpassthru) PHP_NAMED_FE(ftruncate, php_if_ftruncate, arginfo_ftruncate) PHP_NAMED_FE(fstat, php_if_fstat, arginfo_fstat) PHP_FE(fseek, arginfo_fseek) PHP_FE(ftell, arginfo_ftell) PHP_FE(fflush, arginfo_fflush) PHP_FE(fwrite, arginfo_fwrite) PHP_FALIAS(fputs, fwrite, arginfo_fwrite) PHP_FE(mkdir, arginfo_mkdir) PHP_FE(rename, arginfo_rename) PHP_FE(copy, arginfo_copy) PHP_FE(tempnam, arginfo_tempnam) PHP_NAMED_FE(tmpfile, php_if_tmpfile, arginfo_tmpfile) PHP_FE(file, arginfo_file) PHP_FE(file_get_contents, arginfo_file_get_contents) PHP_FE(file_put_contents, arginfo_file_put_contents) PHP_FE(stream_select, arginfo_stream_select) PHP_FE(stream_context_create, arginfo_stream_context_create) PHP_FE(stream_context_set_params, arginfo_stream_context_set_params) PHP_FE(stream_context_get_params, arginfo_stream_context_get_params) PHP_FE(stream_context_set_option, arginfo_stream_context_set_option) PHP_FE(stream_context_get_options, arginfo_stream_context_get_options) PHP_FE(stream_context_get_default, arginfo_stream_context_get_default) PHP_FE(stream_context_set_default, arginfo_stream_context_set_default) PHP_FE(stream_filter_prepend, arginfo_stream_filter_prepend) PHP_FE(stream_filter_append, arginfo_stream_filter_append) PHP_FE(stream_filter_remove, arginfo_stream_filter_remove) PHP_FE(stream_socket_client, arginfo_stream_socket_client) PHP_FE(stream_socket_server, arginfo_stream_socket_server) PHP_FE(stream_socket_accept, arginfo_stream_socket_accept) PHP_FE(stream_socket_get_name, arginfo_stream_socket_get_name) PHP_FE(stream_socket_recvfrom, arginfo_stream_socket_recvfrom) PHP_FE(stream_socket_sendto, arginfo_stream_socket_sendto) PHP_FE(stream_socket_enable_crypto, arginfo_stream_socket_enable_crypto) #ifdef HAVE_SHUTDOWN PHP_FE(stream_socket_shutdown, arginfo_stream_socket_shutdown) #endif #if HAVE_SOCKETPAIR PHP_FE(stream_socket_pair, arginfo_stream_socket_pair) #endif PHP_FE(stream_copy_to_stream, arginfo_stream_copy_to_stream) PHP_FE(stream_get_contents, arginfo_stream_get_contents) PHP_FE(stream_supports_lock, arginfo_stream_supports_lock) PHP_FE(fgetcsv, arginfo_fgetcsv) PHP_FE(fputcsv, arginfo_fputcsv) PHP_FE(flock, arginfo_flock) PHP_FE(get_meta_tags, arginfo_get_meta_tags) PHP_FE(stream_set_read_buffer, arginfo_stream_set_read_buffer) PHP_FE(stream_set_write_buffer, arginfo_stream_set_write_buffer) PHP_FALIAS(set_file_buffer, stream_set_write_buffer, arginfo_stream_set_write_buffer) PHP_FE(stream_set_chunk_size, arginfo_stream_set_chunk_size) PHP_DEP_FALIAS(set_socket_blocking, stream_set_blocking, arginfo_stream_set_blocking) PHP_FE(stream_set_blocking, arginfo_stream_set_blocking) PHP_FALIAS(socket_set_blocking, stream_set_blocking, arginfo_stream_set_blocking) PHP_FE(stream_get_meta_data, arginfo_stream_get_meta_data) PHP_FE(stream_get_line, arginfo_stream_get_line) PHP_FE(stream_wrapper_register, arginfo_stream_wrapper_register) PHP_FALIAS(stream_register_wrapper, stream_wrapper_register, arginfo_stream_wrapper_register) PHP_FE(stream_wrapper_unregister, arginfo_stream_wrapper_unregister) PHP_FE(stream_wrapper_restore, arginfo_stream_wrapper_restore) PHP_FE(stream_get_wrappers, arginfo_stream_get_wrappers) PHP_FE(stream_get_transports, arginfo_stream_get_transports) PHP_FE(stream_resolve_include_path, arginfo_stream_resolve_include_path) PHP_FE(stream_is_local, arginfo_stream_is_local) PHP_FE(get_headers, arginfo_get_headers) #if HAVE_SYS_TIME_H || defined(PHP_WIN32) PHP_FE(stream_set_timeout, arginfo_stream_set_timeout) PHP_FALIAS(socket_set_timeout, stream_set_timeout, arginfo_stream_set_timeout) #endif PHP_FALIAS(socket_get_status, stream_get_meta_data, arginfo_stream_get_meta_data) #if (!defined(__BEOS__) && !defined(NETWARE) && HAVE_REALPATH) || defined(ZTS) PHP_FE(realpath, arginfo_realpath) #endif #ifdef HAVE_FNMATCH PHP_FE(fnmatch, arginfo_fnmatch) #endif /* functions from fsock.c */ PHP_FE(fsockopen, arginfo_fsockopen) PHP_FE(pfsockopen, arginfo_pfsockopen) /* functions from pack.c */ PHP_FE(pack, arginfo_pack) PHP_FE(unpack, arginfo_unpack) /* functions from browscap.c */ PHP_FE(get_browser, arginfo_get_browser) #if HAVE_CRYPT /* functions from crypt.c */ PHP_FE(crypt, arginfo_crypt) #endif /* functions from dir.c */ PHP_FE(opendir, arginfo_opendir) PHP_FE(closedir, arginfo_closedir) PHP_FE(chdir, arginfo_chdir) #if defined(HAVE_CHROOT) && !defined(ZTS) && ENABLE_CHROOT_FUNC PHP_FE(chroot, arginfo_chroot) #endif PHP_FE(getcwd, arginfo_getcwd) PHP_FE(rewinddir, arginfo_rewinddir) PHP_NAMED_FE(readdir, php_if_readdir, arginfo_readdir) PHP_FALIAS(dir, getdir, arginfo_dir) PHP_FE(scandir, arginfo_scandir) #ifdef HAVE_GLOB PHP_FE(glob, arginfo_glob) #endif /* functions from filestat.c */ PHP_FE(fileatime, arginfo_fileatime) PHP_FE(filectime, arginfo_filectime) PHP_FE(filegroup, arginfo_filegroup) PHP_FE(fileinode, arginfo_fileinode) PHP_FE(filemtime, arginfo_filemtime) PHP_FE(fileowner, arginfo_fileowner) PHP_FE(fileperms, arginfo_fileperms) PHP_FE(filesize, arginfo_filesize) PHP_FE(filetype, arginfo_filetype) PHP_FE(file_exists, arginfo_file_exists) PHP_FE(is_writable, arginfo_is_writable) PHP_FALIAS(is_writeable, is_writable, arginfo_is_writable) PHP_FE(is_readable, arginfo_is_readable) PHP_FE(is_executable, arginfo_is_executable) PHP_FE(is_file, arginfo_is_file) PHP_FE(is_dir, arginfo_is_dir) PHP_FE(is_link, arginfo_is_link) PHP_NAMED_FE(stat, php_if_stat, arginfo_stat) PHP_NAMED_FE(lstat, php_if_lstat, arginfo_lstat) #ifndef NETWARE PHP_FE(chown, arginfo_chown) PHP_FE(chgrp, arginfo_chgrp) #endif #if HAVE_LCHOWN PHP_FE(lchown, arginfo_lchown) #endif #if HAVE_LCHOWN PHP_FE(lchgrp, arginfo_lchgrp) #endif PHP_FE(chmod, arginfo_chmod) #if HAVE_UTIME PHP_FE(touch, arginfo_touch) #endif PHP_FE(clearstatcache, arginfo_clearstatcache) PHP_FE(disk_total_space, arginfo_disk_total_space) PHP_FE(disk_free_space, arginfo_disk_free_space) PHP_FALIAS(diskfreespace, disk_free_space, arginfo_disk_free_space) PHP_FE(realpath_cache_size, arginfo_realpath_cache_size) PHP_FE(realpath_cache_get, arginfo_realpath_cache_get) /* functions from mail.c */ PHP_FE(mail, arginfo_mail) PHP_FE(ezmlm_hash, arginfo_ezmlm_hash) /* functions from syslog.c */ #ifdef HAVE_SYSLOG_H PHP_FE(openlog, arginfo_openlog) PHP_FE(syslog, arginfo_syslog) PHP_FE(closelog, arginfo_closelog) #endif /* functions from lcg.c */ PHP_FE(lcg_value, arginfo_lcg_value) /* functions from metaphone.c */ PHP_FE(metaphone, arginfo_metaphone) /* functions from output.c */ PHP_FE(ob_start, arginfo_ob_start) PHP_FE(ob_flush, arginfo_ob_flush) PHP_FE(ob_clean, arginfo_ob_clean) PHP_FE(ob_end_flush, arginfo_ob_end_flush) PHP_FE(ob_end_clean, arginfo_ob_end_clean) PHP_FE(ob_get_flush, arginfo_ob_get_flush) PHP_FE(ob_get_clean, arginfo_ob_get_clean) PHP_FE(ob_get_length, arginfo_ob_get_length) PHP_FE(ob_get_level, arginfo_ob_get_level) PHP_FE(ob_get_status, arginfo_ob_get_status) PHP_FE(ob_get_contents, arginfo_ob_get_contents) PHP_FE(ob_implicit_flush, arginfo_ob_implicit_flush) PHP_FE(ob_list_handlers, arginfo_ob_list_handlers) /* functions from array.c */ PHP_FE(ksort, arginfo_ksort) PHP_FE(krsort, arginfo_krsort) PHP_FE(natsort, arginfo_natsort) PHP_FE(natcasesort, arginfo_natcasesort) PHP_FE(asort, arginfo_asort) PHP_FE(arsort, arginfo_arsort) PHP_FE(sort, arginfo_sort) PHP_FE(rsort, arginfo_rsort) PHP_FE(usort, arginfo_usort) PHP_FE(uasort, arginfo_uasort) PHP_FE(uksort, arginfo_uksort) PHP_FE(shuffle, arginfo_shuffle) PHP_FE(array_walk, arginfo_array_walk) PHP_FE(array_walk_recursive, arginfo_array_walk_recursive) PHP_FE(count, arginfo_count) PHP_FE(end, arginfo_end) PHP_FE(prev, arginfo_prev) PHP_FE(next, arginfo_next) PHP_FE(reset, arginfo_reset) PHP_FE(current, arginfo_current) PHP_FE(key, arginfo_key) PHP_FE(min, arginfo_min) PHP_FE(max, arginfo_max) PHP_FE(in_array, arginfo_in_array) PHP_FE(array_search, arginfo_array_search) PHP_FE(extract, arginfo_extract) PHP_FE(compact, arginfo_compact) PHP_FE(array_fill, arginfo_array_fill) PHP_FE(array_fill_keys, arginfo_array_fill_keys) PHP_FE(range, arginfo_range) PHP_FE(array_multisort, arginfo_array_multisort) PHP_FE(array_push, arginfo_array_push) PHP_FE(array_pop, arginfo_array_pop) PHP_FE(array_shift, arginfo_array_shift) PHP_FE(array_unshift, arginfo_array_unshift) PHP_FE(array_splice, arginfo_array_splice) PHP_FE(array_slice, arginfo_array_slice) PHP_FE(array_merge, arginfo_array_merge) PHP_FE(array_merge_recursive, arginfo_array_merge_recursive) PHP_FE(array_replace, arginfo_array_replace) PHP_FE(array_replace_recursive, arginfo_array_replace_recursive) PHP_FE(array_keys, arginfo_array_keys) PHP_FE(array_values, arginfo_array_values) PHP_FE(array_count_values, arginfo_array_count_values) PHP_FE(array_reverse, arginfo_array_reverse) PHP_FE(array_reduce, arginfo_array_reduce) PHP_FE(array_pad, arginfo_array_pad) PHP_FE(array_flip, arginfo_array_flip) PHP_FE(array_change_key_case, arginfo_array_change_key_case) PHP_FE(array_rand, arginfo_array_rand) PHP_FE(array_unique, arginfo_array_unique) PHP_FE(array_intersect, arginfo_array_intersect) PHP_FE(array_intersect_key, arginfo_array_intersect_key) PHP_FE(array_intersect_ukey, arginfo_array_intersect_ukey) PHP_FE(array_uintersect, arginfo_array_uintersect) PHP_FE(array_intersect_assoc, arginfo_array_intersect_assoc) PHP_FE(array_uintersect_assoc, arginfo_array_uintersect_assoc) PHP_FE(array_intersect_uassoc, arginfo_array_intersect_uassoc) PHP_FE(array_uintersect_uassoc, arginfo_array_uintersect_uassoc) PHP_FE(array_diff, arginfo_array_diff) PHP_FE(array_diff_key, arginfo_array_diff_key) PHP_FE(array_diff_ukey, arginfo_array_diff_ukey) PHP_FE(array_udiff, arginfo_array_udiff) PHP_FE(array_diff_assoc, arginfo_array_diff_assoc) PHP_FE(array_udiff_assoc, arginfo_array_udiff_assoc) PHP_FE(array_diff_uassoc, arginfo_array_diff_uassoc) PHP_FE(array_udiff_uassoc, arginfo_array_udiff_uassoc) PHP_FE(array_sum, arginfo_array_sum) PHP_FE(array_product, arginfo_array_product) PHP_FE(array_filter, arginfo_array_filter) PHP_FE(array_map, arginfo_array_map) PHP_FE(array_chunk, arginfo_array_chunk) PHP_FE(array_combine, arginfo_array_combine) PHP_FE(array_key_exists, arginfo_array_key_exists) /* aliases from array.c */ PHP_FALIAS(pos, current, arginfo_current) PHP_FALIAS(sizeof, count, arginfo_count) PHP_FALIAS(key_exists, array_key_exists, arginfo_array_key_exists) /* functions from assert.c */ PHP_FE(assert, arginfo_assert) PHP_FE(assert_options, arginfo_assert_options) /* functions from versioning.c */ PHP_FE(version_compare, arginfo_version_compare) /* functions from ftok.c*/ #if HAVE_FTOK PHP_FE(ftok, arginfo_ftok) #endif PHP_FE(str_rot13, arginfo_str_rot13) PHP_FE(stream_get_filters, arginfo_stream_get_filters) PHP_FE(stream_filter_register, arginfo_stream_filter_register) PHP_FE(stream_bucket_make_writeable, arginfo_stream_bucket_make_writeable) PHP_FE(stream_bucket_prepend, arginfo_stream_bucket_prepend) PHP_FE(stream_bucket_append, arginfo_stream_bucket_append) PHP_FE(stream_bucket_new, arginfo_stream_bucket_new) PHP_FE(output_add_rewrite_var, arginfo_output_add_rewrite_var) PHP_FE(output_reset_rewrite_vars, arginfo_output_reset_rewrite_vars) PHP_FE(sys_get_temp_dir, arginfo_sys_get_temp_dir) PHP_FE_END }; /* }}} */ static const zend_module_dep standard_deps[] = { /* {{{ */ ZEND_MOD_OPTIONAL("session") ZEND_MOD_END }; /* }}} */ zend_module_entry basic_functions_module = { /* {{{ */ STANDARD_MODULE_HEADER_EX, NULL, standard_deps, "standard", /* extension name */ basic_functions, /* function list */ PHP_MINIT(basic), /* process startup */ PHP_MSHUTDOWN(basic), /* process shutdown */ PHP_RINIT(basic), /* request startup */ PHP_RSHUTDOWN(basic), /* request shutdown */ PHP_MINFO(basic), /* extension info */ PHP_VERSION, /* extension version */ STANDARD_MODULE_PROPERTIES }; /* }}} */ #if defined(HAVE_PUTENV) static void php_putenv_destructor(putenv_entry *pe) /* {{{ */ { if (pe->previous_value) { #if _MSC_VER >= 1300 /* VS.Net has a bug in putenv() when setting a variable that * is already set; if the SetEnvironmentVariable() API call * fails, the Crt will double free() a string. * We try to avoid this by setting our own value first */ SetEnvironmentVariable(pe->key, "bugbug"); #endif putenv(pe->previous_value); # if defined(PHP_WIN32) efree(pe->previous_value); # endif } else { # if HAVE_UNSETENV unsetenv(pe->key); # elif defined(PHP_WIN32) SetEnvironmentVariable(pe->key, NULL); # else char **env; for (env = environ; env != NULL && *env != NULL; env++) { if (!strncmp(*env, pe->key, pe->key_len) && (*env)[pe->key_len] == '=') { /* found it */ *env = ""; break; } } # endif } #ifdef HAVE_TZSET /* don't forget to reset the various libc globals that * we might have changed by an earlier call to tzset(). */ if (!strncmp(pe->key, "TZ", pe->key_len)) { tzset(); } #endif efree(pe->putenv_string); efree(pe->key); } /* }}} */ #endif static void basic_globals_ctor(php_basic_globals *basic_globals_p TSRMLS_DC) /* {{{ */ { BG(rand_is_seeded) = 0; BG(mt_rand_is_seeded) = 0; BG(umask) = -1; BG(next) = NULL; BG(left) = -1; BG(user_tick_functions) = NULL; BG(user_filter_map) = NULL; BG(serialize_lock) = 0; memset(&BG(serialize), 0, sizeof(BG(serialize))); memset(&BG(unserialize), 0, sizeof(BG(unserialize))); memset(&BG(url_adapt_state_ex), 0, sizeof(BG(url_adapt_state_ex))); #if defined(_REENTRANT) && defined(HAVE_MBRLEN) && defined(HAVE_MBSTATE_T) memset(&BG(mblen_state), 0, sizeof(BG(mblen_state))); #endif BG(incomplete_class) = incomplete_class_entry; BG(page_uid) = -1; BG(page_gid) = -1; } /* }}} */ static void basic_globals_dtor(php_basic_globals *basic_globals_p TSRMLS_DC) /* {{{ */ { if (BG(url_adapt_state_ex).tags) { zend_hash_destroy(BG(url_adapt_state_ex).tags); free(BG(url_adapt_state_ex).tags); } } /* }}} */ #define PHP_DOUBLE_INFINITY_HIGH 0x7ff00000 #define PHP_DOUBLE_QUIET_NAN_HIGH 0xfff80000 PHPAPI double php_get_nan(void) /* {{{ */ { #if HAVE_HUGE_VAL_NAN return HUGE_VAL + -HUGE_VAL; #elif defined(__i386__) || defined(_X86_) || defined(ALPHA) || defined(_ALPHA) || defined(__alpha) double val = 0.0; ((php_uint32*)&val)[1] = PHP_DOUBLE_QUIET_NAN_HIGH; ((php_uint32*)&val)[0] = 0; return val; #elif HAVE_ATOF_ACCEPTS_NAN return atof("NAN"); #else return 0.0/0.0; #endif } /* }}} */ PHPAPI double php_get_inf(void) /* {{{ */ { #if HAVE_HUGE_VAL_INF return HUGE_VAL; #elif defined(__i386__) || defined(_X86_) || defined(ALPHA) || defined(_ALPHA) || defined(__alpha) double val = 0.0; ((php_uint32*)&val)[1] = PHP_DOUBLE_INFINITY_HIGH; ((php_uint32*)&val)[0] = 0; return val; #elif HAVE_ATOF_ACCEPTS_INF return atof("INF"); #else return 1.0/0.0; #endif } /* }}} */ #define BASIC_MINIT_SUBMODULE(module) \ if (PHP_MINIT(module)(INIT_FUNC_ARGS_PASSTHRU) == SUCCESS) {\ BASIC_ADD_SUBMODULE(module); \ } #define BASIC_ADD_SUBMODULE(module) \ zend_hash_add_empty_element(&basic_submodules, #module, strlen(#module)); #define BASIC_RINIT_SUBMODULE(module) \ if (zend_hash_exists(&basic_submodules, #module, strlen(#module))) { \ PHP_RINIT(module)(INIT_FUNC_ARGS_PASSTHRU); \ } #define BASIC_MINFO_SUBMODULE(module) \ if (zend_hash_exists(&basic_submodules, #module, strlen(#module))) { \ PHP_MINFO(module)(ZEND_MODULE_INFO_FUNC_ARGS_PASSTHRU); \ } #define BASIC_RSHUTDOWN_SUBMODULE(module) \ if (zend_hash_exists(&basic_submodules, #module, strlen(#module))) { \ PHP_RSHUTDOWN(module)(SHUTDOWN_FUNC_ARGS_PASSTHRU); \ } #define BASIC_MSHUTDOWN_SUBMODULE(module) \ if (zend_hash_exists(&basic_submodules, #module, strlen(#module))) { \ PHP_MSHUTDOWN(module)(SHUTDOWN_FUNC_ARGS_PASSTHRU); \ } PHP_MINIT_FUNCTION(basic) /* {{{ */ { #ifdef ZTS ts_allocate_id(&basic_globals_id, sizeof(php_basic_globals), (ts_allocate_ctor) basic_globals_ctor, (ts_allocate_dtor) basic_globals_dtor); #ifdef PHP_WIN32 ts_allocate_id(&php_win32_core_globals_id, sizeof(php_win32_core_globals), (ts_allocate_ctor)php_win32_core_globals_ctor, (ts_allocate_dtor)php_win32_core_globals_dtor ); #endif #else basic_globals_ctor(&basic_globals TSRMLS_CC); #ifdef PHP_WIN32 php_win32_core_globals_ctor(&the_php_win32_core_globals TSRMLS_CC); #endif #endif zend_hash_init(&basic_submodules, 0, NULL, NULL, 1); BG(incomplete_class) = incomplete_class_entry = php_create_incomplete_class(TSRMLS_C); REGISTER_LONG_CONSTANT("CONNECTION_ABORTED", PHP_CONNECTION_ABORTED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("CONNECTION_NORMAL", PHP_CONNECTION_NORMAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("CONNECTION_TIMEOUT", PHP_CONNECTION_TIMEOUT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INI_USER", ZEND_INI_USER, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INI_PERDIR", ZEND_INI_PERDIR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INI_SYSTEM", ZEND_INI_SYSTEM, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INI_ALL", ZEND_INI_ALL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INI_SCANNER_NORMAL", ZEND_INI_SCANNER_NORMAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INI_SCANNER_RAW", ZEND_INI_SCANNER_RAW, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_URL_SCHEME", PHP_URL_SCHEME, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_URL_HOST", PHP_URL_HOST, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_URL_PORT", PHP_URL_PORT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_URL_USER", PHP_URL_USER, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_URL_PASS", PHP_URL_PASS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_URL_PATH", PHP_URL_PATH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_URL_QUERY", PHP_URL_QUERY, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_URL_FRAGMENT", PHP_URL_FRAGMENT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_QUERY_RFC1738", PHP_QUERY_RFC1738, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_QUERY_RFC3986", PHP_QUERY_RFC3986, CONST_CS | CONST_PERSISTENT); #define REGISTER_MATH_CONSTANT(x) REGISTER_DOUBLE_CONSTANT(#x, x, CONST_CS | CONST_PERSISTENT) REGISTER_MATH_CONSTANT(M_E); REGISTER_MATH_CONSTANT(M_LOG2E); REGISTER_MATH_CONSTANT(M_LOG10E); REGISTER_MATH_CONSTANT(M_LN2); REGISTER_MATH_CONSTANT(M_LN10); REGISTER_MATH_CONSTANT(M_PI); REGISTER_MATH_CONSTANT(M_PI_2); REGISTER_MATH_CONSTANT(M_PI_4); REGISTER_MATH_CONSTANT(M_1_PI); REGISTER_MATH_CONSTANT(M_2_PI); REGISTER_MATH_CONSTANT(M_SQRTPI); REGISTER_MATH_CONSTANT(M_2_SQRTPI); REGISTER_MATH_CONSTANT(M_LNPI); REGISTER_MATH_CONSTANT(M_EULER); REGISTER_MATH_CONSTANT(M_SQRT2); REGISTER_MATH_CONSTANT(M_SQRT1_2); REGISTER_MATH_CONSTANT(M_SQRT3); REGISTER_DOUBLE_CONSTANT("INF", php_get_inf(), CONST_CS | CONST_PERSISTENT); REGISTER_DOUBLE_CONSTANT("NAN", php_get_nan(), CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_ROUND_HALF_UP", PHP_ROUND_HALF_UP, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_ROUND_HALF_DOWN", PHP_ROUND_HALF_DOWN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_ROUND_HALF_EVEN", PHP_ROUND_HALF_EVEN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PHP_ROUND_HALF_ODD", PHP_ROUND_HALF_ODD, CONST_CS | CONST_PERSISTENT); #if ENABLE_TEST_CLASS test_class_startup(); #endif register_phpinfo_constants(INIT_FUNC_ARGS_PASSTHRU); register_html_constants(INIT_FUNC_ARGS_PASSTHRU); register_string_constants(INIT_FUNC_ARGS_PASSTHRU); BASIC_ADD_SUBMODULE(dl) BASIC_ADD_SUBMODULE(mail) BASIC_MINIT_SUBMODULE(file) BASIC_MINIT_SUBMODULE(pack) BASIC_MINIT_SUBMODULE(browscap) BASIC_MINIT_SUBMODULE(standard_filters) BASIC_MINIT_SUBMODULE(user_filters) #if defined(HAVE_LOCALECONV) && defined(ZTS) BASIC_MINIT_SUBMODULE(localeconv) #endif #if defined(HAVE_NL_LANGINFO) BASIC_MINIT_SUBMODULE(nl_langinfo) #endif #if HAVE_CRYPT BASIC_MINIT_SUBMODULE(crypt) #endif BASIC_MINIT_SUBMODULE(lcg) BASIC_MINIT_SUBMODULE(dir) #ifdef HAVE_SYSLOG_H BASIC_MINIT_SUBMODULE(syslog) #endif BASIC_MINIT_SUBMODULE(array) BASIC_MINIT_SUBMODULE(assert) BASIC_MINIT_SUBMODULE(url_scanner_ex) #ifdef PHP_CAN_SUPPORT_PROC_OPEN BASIC_MINIT_SUBMODULE(proc_open) #endif BASIC_MINIT_SUBMODULE(user_streams) BASIC_MINIT_SUBMODULE(imagetypes) php_register_url_stream_wrapper("php", &php_stream_php_wrapper TSRMLS_CC); php_register_url_stream_wrapper("file", &php_plain_files_wrapper TSRMLS_CC); #ifdef HAVE_GLOB php_register_url_stream_wrapper("glob", &php_glob_stream_wrapper TSRMLS_CC); #endif php_register_url_stream_wrapper("data", &php_stream_rfc2397_wrapper TSRMLS_CC); #ifndef PHP_CURL_URL_WRAPPERS php_register_url_stream_wrapper("http", &php_stream_http_wrapper TSRMLS_CC); php_register_url_stream_wrapper("ftp", &php_stream_ftp_wrapper TSRMLS_CC); #endif #if defined(PHP_WIN32) || (HAVE_DNS_SEARCH_FUNC && !(defined(__BEOS__) || defined(NETWARE))) # if defined(PHP_WIN32) || HAVE_FULL_DNS_FUNCS BASIC_MINIT_SUBMODULE(dns) # endif #endif return SUCCESS; } /* }}} */ PHP_MSHUTDOWN_FUNCTION(basic) /* {{{ */ { #ifdef HAVE_SYSLOG_H PHP_MSHUTDOWN(syslog)(SHUTDOWN_FUNC_ARGS_PASSTHRU); #endif #ifdef ZTS ts_free_id(basic_globals_id); #ifdef PHP_WIN32 ts_free_id(php_win32_core_globals_id); #endif #else basic_globals_dtor(&basic_globals TSRMLS_CC); #ifdef PHP_WIN32 php_win32_core_globals_dtor(&the_php_win32_core_globals TSRMLS_CC); #endif #endif php_unregister_url_stream_wrapper("php" TSRMLS_CC); #ifndef PHP_CURL_URL_WRAPPERS php_unregister_url_stream_wrapper("http" TSRMLS_CC); php_unregister_url_stream_wrapper("ftp" TSRMLS_CC); #endif BASIC_MSHUTDOWN_SUBMODULE(browscap) BASIC_MSHUTDOWN_SUBMODULE(array) BASIC_MSHUTDOWN_SUBMODULE(assert) BASIC_MSHUTDOWN_SUBMODULE(url_scanner_ex) BASIC_MSHUTDOWN_SUBMODULE(file) BASIC_MSHUTDOWN_SUBMODULE(standard_filters) #if defined(HAVE_LOCALECONV) && defined(ZTS) BASIC_MSHUTDOWN_SUBMODULE(localeconv) #endif #if HAVE_CRYPT BASIC_MSHUTDOWN_SUBMODULE(crypt) #endif zend_hash_destroy(&basic_submodules); return SUCCESS; } /* }}} */ PHP_RINIT_FUNCTION(basic) /* {{{ */ { memset(BG(strtok_table), 0, 256); BG(strtok_string) = NULL; BG(strtok_zval) = NULL; BG(strtok_last) = NULL; BG(locale_string) = NULL; BG(array_walk_fci) = empty_fcall_info; BG(array_walk_fci_cache) = empty_fcall_info_cache; BG(user_compare_fci) = empty_fcall_info; BG(user_compare_fci_cache) = empty_fcall_info_cache; BG(page_uid) = -1; BG(page_gid) = -1; BG(page_inode) = -1; BG(page_mtime) = -1; #ifdef HAVE_PUTENV if (zend_hash_init(&BG(putenv_ht), 1, NULL, (void (*)(void *)) php_putenv_destructor, 0) == FAILURE) { return FAILURE; } #endif BG(user_shutdown_function_names) = NULL; PHP_RINIT(filestat)(INIT_FUNC_ARGS_PASSTHRU); #ifdef HAVE_SYSLOG_H BASIC_RINIT_SUBMODULE(syslog) #endif BASIC_RINIT_SUBMODULE(dir) BASIC_RINIT_SUBMODULE(url_scanner_ex) /* Setup default context */ FG(default_context) = NULL; /* Default to global wrappers only */ FG(stream_wrappers) = NULL; /* Default to global filters only */ FG(stream_filters) = NULL; FG(wrapper_errors) = NULL; return SUCCESS; } /* }}} */ PHP_RSHUTDOWN_FUNCTION(basic) /* {{{ */ { if (BG(strtok_zval)) { zval_ptr_dtor(&BG(strtok_zval)); } BG(strtok_string) = NULL; BG(strtok_zval) = NULL; #ifdef HAVE_PUTENV zend_hash_destroy(&BG(putenv_ht)); #endif if (BG(umask) != -1) { umask(BG(umask)); } /* Check if locale was changed and change it back * to the value in startup environment */ if (BG(locale_string) != NULL) { setlocale(LC_ALL, "C"); setlocale(LC_CTYPE, ""); zend_update_current_locale(); } STR_FREE(BG(locale_string)); BG(locale_string) = NULL; /* FG(stream_wrappers) and FG(stream_filters) are destroyed * during php_request_shutdown() */ PHP_RSHUTDOWN(filestat)(SHUTDOWN_FUNC_ARGS_PASSTHRU); #ifdef HAVE_SYSLOG_H #ifdef PHP_WIN32 BASIC_RSHUTDOWN_SUBMODULE(syslog)(SHUTDOWN_FUNC_ARGS_PASSTHRU); #endif #endif BASIC_RSHUTDOWN_SUBMODULE(assert) BASIC_RSHUTDOWN_SUBMODULE(url_scanner_ex) BASIC_RSHUTDOWN_SUBMODULE(streams) #ifdef PHP_WIN32 BASIC_RSHUTDOWN_SUBMODULE(win32_core_globals) #endif if (BG(user_tick_functions)) { zend_llist_destroy(BG(user_tick_functions)); efree(BG(user_tick_functions)); BG(user_tick_functions) = NULL; } BASIC_RSHUTDOWN_SUBMODULE(user_filters) BASIC_RSHUTDOWN_SUBMODULE(browscap) BG(page_uid) = -1; BG(page_gid) = -1; return SUCCESS; } /* }}} */ PHP_MINFO_FUNCTION(basic) /* {{{ */ { php_info_print_table_start(); BASIC_MINFO_SUBMODULE(dl) BASIC_MINFO_SUBMODULE(mail) php_info_print_table_end(); BASIC_MINFO_SUBMODULE(assert) } /* }}} */ /* {{{ proto mixed constant(string const_name) Given the name of a constant this function will return the constant's associated value */ PHP_FUNCTION(constant) { char *const_name; int const_name_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &const_name, &const_name_len) == FAILURE) { return; } if (!zend_get_constant_ex(const_name, const_name_len, return_value, NULL, ZEND_FETCH_CLASS_SILENT TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't find constant %s", const_name); RETURN_NULL(); } } /* }}} */ #ifdef HAVE_INET_NTOP /* {{{ proto string inet_ntop(string in_addr) Converts a packed inet address to a human readable IP address string */ PHP_NAMED_FUNCTION(php_inet_ntop) { char *address; int address_len, af = AF_INET; char buffer[40]; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &address, &address_len) == FAILURE) { RETURN_FALSE; } #ifdef HAVE_IPV6 if (address_len == 16) { af = AF_INET6; } else #endif if (address_len != 4) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid in_addr value"); RETURN_FALSE; } if (!inet_ntop(af, address, buffer, sizeof(buffer))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "An unknown error occured"); RETURN_FALSE; } RETURN_STRING(buffer, 1); } /* }}} */ #endif /* HAVE_INET_NTOP */ #ifdef HAVE_INET_PTON /* {{{ proto string inet_pton(string ip_address) Converts a human readable IP address to a packed binary string */ PHP_NAMED_FUNCTION(php_inet_pton) { int ret, af = AF_INET; char *address; int address_len; char buffer[17]; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &address, &address_len) == FAILURE) { RETURN_FALSE; } memset(buffer, 0, sizeof(buffer)); #ifdef HAVE_IPV6 if (strchr(address, ':')) { af = AF_INET6; } else #endif if (!strchr(address, '.')) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unrecognized address %s", address); RETURN_FALSE; } ret = inet_pton(af, address, buffer); if (ret <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unrecognized address %s", address); RETURN_FALSE; } RETURN_STRINGL(buffer, af == AF_INET ? 4 : 16, 1); } /* }}} */ #endif /* HAVE_INET_PTON */ /* {{{ proto int ip2long(string ip_address) Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address */ PHP_FUNCTION(ip2long) { char *addr; int addr_len; #ifdef HAVE_INET_PTON struct in_addr ip; #else unsigned long int ip; #endif if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &addr, &addr_len) == FAILURE) { return; } #ifdef HAVE_INET_PTON if (addr_len == 0 || inet_pton(AF_INET, addr, &ip) != 1) { RETURN_FALSE; } RETURN_LONG(ntohl(ip.s_addr)); #else if (addr_len == 0 || (ip = inet_addr(addr)) == INADDR_NONE) { /* The only special case when we should return -1 ourselves, * because inet_addr() considers it wrong. We return 0xFFFFFFFF and * not -1 or ~0 because of 32/64bit issues. */ if (addr_len == sizeof("255.255.255.255") - 1 && !memcmp(addr, "255.255.255.255", sizeof("255.255.255.255") - 1) ) { RETURN_LONG(0xFFFFFFFF); } RETURN_FALSE; } RETURN_LONG(ntohl(ip)); #endif } /* }}} */ /* {{{ proto string long2ip(int proper_address) Converts an (IPv4) Internet network address into a string in Internet standard dotted format */ PHP_FUNCTION(long2ip) { /* "It's a long but it's not, PHP ints are signed */ char *ip; int ip_len; unsigned long n; struct in_addr myaddr; #ifdef HAVE_INET_PTON char str[40]; #endif if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &ip, &ip_len) == FAILURE) { return; } n = strtoul(ip, NULL, 0); myaddr.s_addr = htonl(n); #ifdef HAVE_INET_PTON if (inet_ntop(AF_INET, &myaddr, str, sizeof(str))) { RETURN_STRING(str, 1); } else { RETURN_FALSE; } #else RETURN_STRING(inet_ntoa(myaddr), 1); #endif } /* }}} */ /******************** * System Functions * ********************/ /* {{{ proto string getenv(string varname) Get the value of an environment variable */ PHP_FUNCTION(getenv) { char *ptr, *str; int str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &str, &str_len) == FAILURE) { RETURN_FALSE; } /* SAPI method returns an emalloc()'d string */ ptr = sapi_getenv(str, str_len TSRMLS_CC); if (ptr) { RETURN_STRING(ptr, 0); } #ifdef PHP_WIN32 { char dummybuf; int size; SetLastError(0); /*If the given bugger is not large enough to hold the data, the return value is the buffer size, in characters, required to hold the string and its terminating null character. We use this return value to alloc the final buffer. */ size = GetEnvironmentVariableA(str, &dummybuf, 0); if (GetLastError() == ERROR_ENVVAR_NOT_FOUND) { /* The environment variable doesn't exist. */ RETURN_FALSE; } if (size == 0) { /* env exists, but it is empty */ RETURN_EMPTY_STRING(); } ptr = emalloc(size); size = GetEnvironmentVariableA(str, ptr, size); if (size == 0) { /* has been removed between the two calls */ efree(ptr); RETURN_EMPTY_STRING(); } else { RETURN_STRING(ptr, 0); } } #else /* system method returns a const */ ptr = getenv(str); if (ptr) { RETURN_STRING(ptr, 1); } #endif RETURN_FALSE; } /* }}} */ #ifdef HAVE_PUTENV /* {{{ proto bool putenv(string setting) Set the value of an environment variable */ PHP_FUNCTION(putenv) { char *setting; int setting_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &setting, &setting_len) == FAILURE) { return; } if (setting_len) { char *p, **env; putenv_entry pe; #ifdef PHP_WIN32 char *value = NULL; int equals = 0; int error_code; #endif pe.putenv_string = estrndup(setting, setting_len); pe.key = estrndup(setting, setting_len); if ((p = strchr(pe.key, '='))) { /* nullify the '=' if there is one */ *p = '\0'; #ifdef PHP_WIN32 equals = 1; #endif } pe.key_len = strlen(pe.key); #ifdef PHP_WIN32 if (equals) { if (pe.key_len < setting_len - 1) { value = p + 1; } else { /* empty string*/ value = p; } } #endif zend_hash_del(&BG(putenv_ht), pe.key, pe.key_len+1); /* find previous value */ pe.previous_value = NULL; for (env = environ; env != NULL && *env != NULL; env++) { if (!strncmp(*env, pe.key, pe.key_len) && (*env)[pe.key_len] == '=') { /* found it */ #if defined(PHP_WIN32) /* must copy previous value because MSVCRT's putenv can free the string without notice */ pe.previous_value = estrdup(*env); #else pe.previous_value = *env; #endif break; } } #if HAVE_UNSETENV if (!p) { /* no '=' means we want to unset it */ unsetenv(pe.putenv_string); } if (!p || putenv(pe.putenv_string) == 0) { /* success */ #else # ifndef PHP_WIN32 if (putenv(pe.putenv_string) == 0) { /* success */ # else error_code = SetEnvironmentVariable(pe.key, value); # if _MSC_VER < 1500 /* Yet another VC6 bug, unset may return env not found */ if (error_code != 0 || (error_code == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND)) { # else if (error_code != 0) { /* success */ # endif # endif #endif zend_hash_add(&BG(putenv_ht), pe.key, pe.key_len + 1, (void **) &pe, sizeof(putenv_entry), NULL); #ifdef HAVE_TZSET if (!strncmp(pe.key, "TZ", pe.key_len)) { tzset(); } #endif RETURN_TRUE; } else { efree(pe.putenv_string); efree(pe.key); RETURN_FALSE; } } php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid parameter syntax"); RETURN_FALSE; } /* }}} */ #endif /* {{{ free_argv() Free the memory allocated to an argv array. */ static void free_argv(char **argv, int argc) { int i; if (argv) { for (i = 0; i < argc; i++) { if (argv[i]) { efree(argv[i]); } } efree(argv); } } /* }}} */ /* {{{ free_longopts() Free the memory allocated to an longopt array. */ static void free_longopts(opt_struct *longopts) { opt_struct *p; if (longopts) { for (p = longopts; p && p->opt_char != '-'; p++) { if (p->opt_name != NULL) { efree((char *)(p->opt_name)); } } } } /* }}} */ /* {{{ parse_opts() Convert the typical getopt input characters to the php_getopt struct array */ static int parse_opts(char * opts, opt_struct ** result) { opt_struct * paras = NULL; unsigned int i, count = 0; for (i = 0; i < strlen(opts); i++) { if ((opts[i] >= 48 && opts[i] <= 57) || (opts[i] >= 65 && opts[i] <= 90) || (opts[i] >= 97 && opts[i] <= 122) ) { count++; } } paras = safe_emalloc(sizeof(opt_struct), count, 0); memset(paras, 0, sizeof(opt_struct) * count); *result = paras; while ( (*opts >= 48 && *opts <= 57) || /* 0 - 9 */ (*opts >= 65 && *opts <= 90) || /* A - Z */ (*opts >= 97 && *opts <= 122) /* a - z */ ) { paras->opt_char = *opts; paras->need_param = (*(++opts) == ':') ? 1 : 0; paras->opt_name = NULL; if (paras->need_param == 1) { opts++; if (*opts == ':') { paras->need_param++; opts++; } } paras++; } return count; } /* }}} */ /* {{{ proto array getopt(string options [, array longopts]) Get options from the command line argument list */ PHP_FUNCTION(getopt) { char *options = NULL, **argv = NULL; char opt[2] = { '\0' }; char *optname; int argc = 0, options_len = 0, len, o; char *php_optarg = NULL; int php_optind = 1; zval *val, **args = NULL, *p_longopts = NULL; int optname_len = 0; opt_struct *opts, *orig_opts; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|a", &options, &options_len, &p_longopts) == FAILURE) { RETURN_FALSE; } /* Get argv from the global symbol table. We calculate argc ourselves * in order to be on the safe side, even though it is also available * from the symbol table. */ if (PG(http_globals)[TRACK_VARS_SERVER] && (zend_hash_find(HASH_OF(PG(http_globals)[TRACK_VARS_SERVER]), "argv", sizeof("argv"), (void **) &args) != FAILURE || zend_hash_find(&EG(symbol_table), "argv", sizeof("argv"), (void **) &args) != FAILURE) && Z_TYPE_PP(args) == IS_ARRAY ) { int pos = 0; zval **entry; argc = zend_hash_num_elements(Z_ARRVAL_PP(args)); /* Attempt to allocate enough memory to hold all of the arguments * and a trailing NULL */ argv = (char **) safe_emalloc(sizeof(char *), (argc + 1), 0); /* Reset the array indexes. */ zend_hash_internal_pointer_reset(Z_ARRVAL_PP(args)); /* Iterate over the hash to construct the argv array. */ while (zend_hash_get_current_data(Z_ARRVAL_PP(args), (void **)&entry) == SUCCESS) { zval arg, *arg_ptr = *entry; if (Z_TYPE_PP(entry) != IS_STRING) { arg = **entry; zval_copy_ctor(&arg); convert_to_string(&arg); arg_ptr = &arg; } argv[pos++] = estrdup(Z_STRVAL_P(arg_ptr)); if (arg_ptr != *entry) { zval_dtor(&arg); } zend_hash_move_forward(Z_ARRVAL_PP(args)); } /* The C Standard requires argv[argc] to be NULL - this might * keep some getopt implementations happy. */ argv[argc] = NULL; } else { /* Return false if we can't find argv. */ RETURN_FALSE; } len = parse_opts(options, &opts); if (p_longopts) { int count; zval **entry; count = zend_hash_num_elements(Z_ARRVAL_P(p_longopts)); /* the first <len> slots are filled by the one short ops * we now extend our array and jump to the new added structs */ opts = (opt_struct *) erealloc(opts, sizeof(opt_struct) * (len + count + 1)); orig_opts = opts; opts += len; memset(opts, 0, count * sizeof(opt_struct)); /* Reset the array indexes. */ zend_hash_internal_pointer_reset(Z_ARRVAL_P(p_longopts)); /* Iterate over the hash to construct the argv array. */ while (zend_hash_get_current_data(Z_ARRVAL_P(p_longopts), (void **)&entry) == SUCCESS) { zval arg, *arg_ptr = *entry; if (Z_TYPE_PP(entry) != IS_STRING) { arg = **entry; zval_copy_ctor(&arg); convert_to_string(&arg); arg_ptr = &arg; } opts->need_param = 0; opts->opt_name = estrdup(Z_STRVAL_P(arg_ptr)); len = strlen(opts->opt_name); if ((len > 0) && (opts->opt_name[len - 1] == ':')) { opts->need_param++; opts->opt_name[len - 1] = '\0'; if ((len > 1) && (opts->opt_name[len - 2] == ':')) { opts->need_param++; opts->opt_name[len - 2] = '\0'; } } opts->opt_char = 0; opts++; if (arg_ptr != *entry) { zval_dtor(&arg); } zend_hash_move_forward(Z_ARRVAL_P(p_longopts)); } } else { opts = (opt_struct*) erealloc(opts, sizeof(opt_struct) * (len + 1)); orig_opts = opts; opts += len; } /* php_getopt want to identify the last param */ opts->opt_char = '-'; opts->need_param = 0; opts->opt_name = NULL; /* Initialize the return value as an array. */ array_init(return_value); /* after our pointer arithmetic jump back to the first element */ opts = orig_opts; while ((o = php_getopt(argc, argv, opts, &php_optarg, &php_optind, 0, 1)) != -1) { /* Skip unknown arguments. */ if (o == '?') { continue; } /* Prepare the option character and the argument string. */ if (o == 0) { optname = opts[php_optidx].opt_name; } else { if (o == 1) { o = '-'; } opt[0] = o; optname = opt; } MAKE_STD_ZVAL(val); if (php_optarg != NULL) { /* keep the arg as binary, since the encoding is not known */ ZVAL_STRING(val, php_optarg, 1); } else { ZVAL_FALSE(val); } /* Add this option / argument pair to the result hash. */ optname_len = strlen(optname); if (!(optname_len > 1 && optname[0] == '0') && is_numeric_string(optname, optname_len, NULL, NULL, 0) == IS_LONG) { /* numeric string */ int optname_int = atoi(optname); if (zend_hash_index_find(HASH_OF(return_value), optname_int, (void **)&args) != FAILURE) { if (Z_TYPE_PP(args) != IS_ARRAY) { convert_to_array_ex(args); } zend_hash_next_index_insert(HASH_OF(*args), (void *)&val, sizeof(zval *), NULL); } else { zend_hash_index_update(HASH_OF(return_value), optname_int, &val, sizeof(zval *), NULL); } } else { /* other strings */ if (zend_hash_find(HASH_OF(return_value), optname, strlen(optname)+1, (void **)&args) != FAILURE) { if (Z_TYPE_PP(args) != IS_ARRAY) { convert_to_array_ex(args); } zend_hash_next_index_insert(HASH_OF(*args), (void *)&val, sizeof(zval *), NULL); } else { zend_hash_add(HASH_OF(return_value), optname, strlen(optname)+1, (void *)&val, sizeof(zval *), NULL); } } php_optarg = NULL; } free_longopts(orig_opts); efree(orig_opts); free_argv(argv, argc); } /* }}} */ /* {{{ proto void flush(void) Flush the output buffer */ PHP_FUNCTION(flush) { sapi_flush(TSRMLS_C); } /* }}} */ /* {{{ proto void sleep(int seconds) Delay for a given number of seconds */ PHP_FUNCTION(sleep) { long num; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &num) == FAILURE) { RETURN_FALSE; } if (num < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number of seconds must be greater than or equal to 0"); RETURN_FALSE; } #ifdef PHP_SLEEP_NON_VOID RETURN_LONG(php_sleep(num)); #else php_sleep(num); #endif } /* }}} */ /* {{{ proto void usleep(int micro_seconds) Delay for a given number of micro seconds */ PHP_FUNCTION(usleep) { #if HAVE_USLEEP long num; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &num) == FAILURE) { return; } if (num < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number of microseconds must be greater than or equal to 0"); RETURN_FALSE; } usleep(num); #endif } /* }}} */ #if HAVE_NANOSLEEP /* {{{ proto mixed time_nanosleep(long seconds, long nanoseconds) Delay for a number of seconds and nano seconds */ PHP_FUNCTION(time_nanosleep) { long tv_sec, tv_nsec; struct timespec php_req, php_rem; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll", &tv_sec, &tv_nsec) == FAILURE) { return; } if (tv_sec < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The seconds value must be greater than 0"); RETURN_FALSE; } if (tv_nsec < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The nanoseconds value must be greater than 0"); RETURN_FALSE; } php_req.tv_sec = (time_t) tv_sec; php_req.tv_nsec = tv_nsec; if (!nanosleep(&php_req, &php_rem)) { RETURN_TRUE; } else if (errno == EINTR) { array_init(return_value); add_assoc_long_ex(return_value, "seconds", sizeof("seconds"), php_rem.tv_sec); add_assoc_long_ex(return_value, "nanoseconds", sizeof("nanoseconds"), php_rem.tv_nsec); return; } else if (errno == EINVAL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "nanoseconds was not in the range 0 to 999 999 999 or seconds was negative"); } RETURN_FALSE; } /* }}} */ /* {{{ proto mixed time_sleep_until(float timestamp) Make the script sleep until the specified time */ PHP_FUNCTION(time_sleep_until) { double d_ts, c_ts; struct timeval tm; struct timespec php_req, php_rem; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "d", &d_ts) == FAILURE) { return; } if (gettimeofday((struct timeval *) &tm, NULL) != 0) { RETURN_FALSE; } c_ts = (double)(d_ts - tm.tv_sec - tm.tv_usec / 1000000.00); if (c_ts < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Sleep until to time is less than current time"); RETURN_FALSE; } php_req.tv_sec = (time_t) c_ts; if (php_req.tv_sec > c_ts) { /* rounding up occurred */ php_req.tv_sec--; } /* 1sec = 1000000000 nanoseconds */ php_req.tv_nsec = (long) ((c_ts - php_req.tv_sec) * 1000000000.00); while (nanosleep(&php_req, &php_rem)) { if (errno == EINTR) { php_req.tv_sec = php_rem.tv_sec; php_req.tv_nsec = php_rem.tv_nsec; } else { RETURN_FALSE; } } RETURN_TRUE; } /* }}} */ #endif /* {{{ proto string get_current_user(void) Get the name of the owner of the current PHP script */ PHP_FUNCTION(get_current_user) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_STRING(php_get_current_user(TSRMLS_C), 1); } /* }}} */ /* {{{ add_config_entry_cb */ static int add_config_entry_cb(zval *entry TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) { zval *retval = (zval *)va_arg(args, zval*); zval *tmp; if (Z_TYPE_P(entry) == IS_STRING) { if (hash_key->nKeyLength > 0) { add_assoc_stringl_ex(retval, hash_key->arKey, hash_key->nKeyLength, Z_STRVAL_P(entry), Z_STRLEN_P(entry), 1); } else { add_index_stringl(retval, hash_key->h, Z_STRVAL_P(entry), Z_STRLEN_P(entry), 1); } } else if (Z_TYPE_P(entry) == IS_ARRAY) { MAKE_STD_ZVAL(tmp); array_init(tmp); zend_hash_apply_with_arguments(Z_ARRVAL_P(entry) TSRMLS_CC, (apply_func_args_t) add_config_entry_cb, 1, tmp); add_assoc_zval_ex(retval, hash_key->arKey, hash_key->nKeyLength, tmp); } return 0; } /* }}} */ /* {{{ proto mixed get_cfg_var(string option_name) Get the value of a PHP configuration option */ PHP_FUNCTION(get_cfg_var) { char *varname; int varname_len; zval *retval; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &varname, &varname_len) == FAILURE) { return; } retval = cfg_get_entry(varname, varname_len + 1); if (retval) { if (Z_TYPE_P(retval) == IS_ARRAY) { array_init(return_value); zend_hash_apply_with_arguments(Z_ARRVAL_P(retval) TSRMLS_CC, (apply_func_args_t) add_config_entry_cb, 1, return_value); return; } else { RETURN_STRING(Z_STRVAL_P(retval), 1); } } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool set_magic_quotes_runtime(int new_setting) magic_quotes_runtime is not supported anymore */ PHP_FUNCTION(set_magic_quotes_runtime) { zend_bool new_setting; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "b", &new_setting) == FAILURE) { return; } if (new_setting) { php_error_docref(NULL TSRMLS_CC, E_CORE_ERROR, "magic_quotes_runtime is not supported anymore"); } RETURN_FALSE; } /* }}} */ /* {{{ proto int get_magic_quotes_runtime(void) Get the current active configuration setting of magic_quotes_runtime */ PHP_FUNCTION(get_magic_quotes_runtime) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_FALSE; } /* }}} */ /* {{{ proto int get_magic_quotes_gpc(void) Get the current active configuration setting of magic_quotes_gpc */ PHP_FUNCTION(get_magic_quotes_gpc) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_FALSE; } /* }}} */ /* 1st arg = error message 2nd arg = error option 3rd arg = optional parameters (email address or tcp address) 4th arg = used for additional headers if email error options: 0 = send to php_error_log (uses syslog or file depending on ini setting) 1 = send via email to 3rd parameter 4th option = additional headers 2 = send via tcp/ip to 3rd parameter (name or ip:port) 3 = save to file in 3rd parameter 4 = send to SAPI logger directly */ /* {{{ proto bool error_log(string message [, int message_type [, string destination [, string extra_headers]]]) Send an error message somewhere */ PHP_FUNCTION(error_log) { char *message, *opt = NULL, *headers = NULL; int message_len, opt_len = 0, headers_len = 0; int opt_err = 0, argc = ZEND_NUM_ARGS(); long erropt = 0; if (zend_parse_parameters(argc TSRMLS_CC, "s|lps", &message, &message_len, &erropt, &opt, &opt_len, &headers, &headers_len) == FAILURE) { return; } if (argc > 1) { opt_err = erropt; } if (_php_error_log_ex(opt_err, message, message_len, opt, headers TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* For BC (not binary-safe!) */ PHPAPI int _php_error_log(int opt_err, char *message, char *opt, char *headers TSRMLS_DC) /* {{{ */ { return _php_error_log_ex(opt_err, message, (opt_err == 3) ? strlen(message) : 0, opt, headers TSRMLS_CC); } /* }}} */ PHPAPI int _php_error_log_ex(int opt_err, char *message, int message_len, char *opt, char *headers TSRMLS_DC) /* {{{ */ { php_stream *stream = NULL; switch (opt_err) { case 1: /*send an email */ if (!php_mail(opt, "PHP error_log message", message, headers, NULL TSRMLS_CC)) { return FAILURE; } break; case 2: /*send to an address */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "TCP/IP option not available!"); return FAILURE; break; case 3: /*save to a file */ stream = php_stream_open_wrapper(opt, "a", IGNORE_URL_WIN | REPORT_ERRORS, NULL); if (!stream) { return FAILURE; } php_stream_write(stream, message, message_len); php_stream_close(stream); break; case 4: /* send to SAPI */ if (sapi_module.log_message) { sapi_module.log_message(message TSRMLS_CC); } else { return FAILURE; } break; default: php_log_err(message TSRMLS_CC); break; } return SUCCESS; } /* }}} */ /* {{{ proto array error_get_last() Get the last occurred error as associative array. Returns NULL if there hasn't been an error yet. */ PHP_FUNCTION(error_get_last) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "") == FAILURE) { return; } if (PG(last_error_message)) { array_init(return_value); add_assoc_long_ex(return_value, "type", sizeof("type"), PG(last_error_type)); add_assoc_string_ex(return_value, "message", sizeof("message"), PG(last_error_message), 1); add_assoc_string_ex(return_value, "file", sizeof("file"), PG(last_error_file)?PG(last_error_file):"-", 1 ); add_assoc_long_ex(return_value, "line", sizeof("line"), PG(last_error_lineno)); } } /* }}} */ /* {{{ proto mixed call_user_func(mixed function_name [, mixed parmeter] [, mixed ...]) Call a user function which is the first parameter */ PHP_FUNCTION(call_user_func) { zval *retval_ptr = NULL; zend_fcall_info fci; zend_fcall_info_cache fci_cache; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "f*", &fci, &fci_cache, &fci.params, &fci.param_count) == FAILURE) { return; } fci.retval_ptr_ptr = &retval_ptr; if (zend_call_function(&fci, &fci_cache TSRMLS_CC) == SUCCESS && fci.retval_ptr_ptr && *fci.retval_ptr_ptr) { COPY_PZVAL_TO_ZVAL(*return_value, *fci.retval_ptr_ptr); } if (fci.params) { efree(fci.params); } } /* }}} */ /* {{{ proto mixed call_user_func_array(string function_name, array parameters) Call a user function which is the first parameter with the arguments contained in array */ PHP_FUNCTION(call_user_func_array) { zval *params, *retval_ptr = NULL; zend_fcall_info fci; zend_fcall_info_cache fci_cache; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "fa/", &fci, &fci_cache, &params) == FAILURE) { return; } zend_fcall_info_args(&fci, params TSRMLS_CC); fci.retval_ptr_ptr = &retval_ptr; if (zend_call_function(&fci, &fci_cache TSRMLS_CC) == SUCCESS && fci.retval_ptr_ptr && *fci.retval_ptr_ptr) { COPY_PZVAL_TO_ZVAL(*return_value, *fci.retval_ptr_ptr); } zend_fcall_info_args_clear(&fci, 1); } /* }}} */ /* {{{ proto mixed call_user_method(string method_name, mixed object [, mixed parameter] [, mixed ...]) Call a user method on a specific object or class */ PHP_FUNCTION(call_user_method) { zval ***params = NULL; int n_params = 0; zval *retval_ptr; zval *callback, *object; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z/z*", &callback, &object, &params, &n_params) == FAILURE) { return; } if (Z_TYPE_P(object) != IS_OBJECT && Z_TYPE_P(object) != IS_STRING ) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Second argument is not an object or class name"); if (params) { efree(params); } RETURN_FALSE; } convert_to_string(callback); if (call_user_function_ex(EG(function_table), &object, callback, &retval_ptr, n_params, params, 0, NULL TSRMLS_CC) == SUCCESS) { if (retval_ptr) { COPY_PZVAL_TO_ZVAL(*return_value, retval_ptr); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call %s()", Z_STRVAL_P(callback)); } if (n_params) { efree(params); } } /* }}} */ /* {{{ proto mixed call_user_method_array(string method_name, mixed object, array params) Call a user method on a specific object or class using a parameter array */ PHP_FUNCTION(call_user_method_array) { zval *params, ***method_args = NULL, *retval_ptr; zval *callback, *object; HashTable *params_ar; int num_elems, element = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z/zA/", &callback, &object, &params) == FAILURE) { return; } if (Z_TYPE_P(object) != IS_OBJECT && Z_TYPE_P(object) != IS_STRING ) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Second argument is not an object or class name"); RETURN_FALSE; } convert_to_string(callback); params_ar = HASH_OF(params); num_elems = zend_hash_num_elements(params_ar); method_args = (zval ***) safe_emalloc(sizeof(zval **), num_elems, 0); for (zend_hash_internal_pointer_reset(params_ar); zend_hash_get_current_data(params_ar, (void **) &(method_args[element])) == SUCCESS; zend_hash_move_forward(params_ar) ) { element++; } if (call_user_function_ex(EG(function_table), &object, callback, &retval_ptr, num_elems, method_args, 0, NULL TSRMLS_CC) == SUCCESS) { if (retval_ptr) { COPY_PZVAL_TO_ZVAL(*return_value, retval_ptr); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call %s()", Z_STRVAL_P(callback)); } efree(method_args); } /* }}} */ /* {{{ proto mixed forward_static_call(mixed function_name [, mixed parmeter] [, mixed ...]) U Call a user function which is the first parameter */ PHP_FUNCTION(forward_static_call) { zval *retval_ptr = NULL; zend_fcall_info fci; zend_fcall_info_cache fci_cache; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "f*", &fci, &fci_cache, &fci.params, &fci.param_count) == FAILURE) { return; } if (!EG(active_op_array)->scope) { zend_error(E_ERROR, "Cannot call forward_static_call() when no class scope is active"); } fci.retval_ptr_ptr = &retval_ptr; if (EG(called_scope) && instanceof_function(EG(called_scope), fci_cache.calling_scope TSRMLS_CC)) { fci_cache.called_scope = EG(called_scope); } if (zend_call_function(&fci, &fci_cache TSRMLS_CC) == SUCCESS && fci.retval_ptr_ptr && *fci.retval_ptr_ptr) { COPY_PZVAL_TO_ZVAL(*return_value, *fci.retval_ptr_ptr); } if (fci.params) { efree(fci.params); } } /* }}} */ /* {{{ proto mixed call_user_func_array(string function_name, array parameters) U Call a user function which is the first parameter with the arguments contained in array */ PHP_FUNCTION(forward_static_call_array) { zval *params, *retval_ptr = NULL; zend_fcall_info fci; zend_fcall_info_cache fci_cache; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "fa/", &fci, &fci_cache, &params) == FAILURE) { return; } zend_fcall_info_args(&fci, params TSRMLS_CC); fci.retval_ptr_ptr = &retval_ptr; if (EG(called_scope) && instanceof_function(EG(called_scope), fci_cache.calling_scope TSRMLS_CC)) { fci_cache.called_scope = EG(called_scope); } if (zend_call_function(&fci, &fci_cache TSRMLS_CC) == SUCCESS && fci.retval_ptr_ptr && *fci.retval_ptr_ptr) { COPY_PZVAL_TO_ZVAL(*return_value, *fci.retval_ptr_ptr); } zend_fcall_info_args_clear(&fci, 1); } /* }}} */ void user_shutdown_function_dtor(php_shutdown_function_entry *shutdown_function_entry) /* {{{ */ { int i; for (i = 0; i < shutdown_function_entry->arg_count; i++) { zval_ptr_dtor(&shutdown_function_entry->arguments[i]); } efree(shutdown_function_entry->arguments); } /* }}} */ void user_tick_function_dtor(user_tick_function_entry *tick_function_entry) /* {{{ */ { int i; for (i = 0; i < tick_function_entry->arg_count; i++) { zval_ptr_dtor(&tick_function_entry->arguments[i]); } efree(tick_function_entry->arguments); } /* }}} */ static int user_shutdown_function_call(php_shutdown_function_entry *shutdown_function_entry TSRMLS_DC) /* {{{ */ { zval retval; char *function_name; if (!zend_is_callable(shutdown_function_entry->arguments[0], 0, &function_name TSRMLS_CC)) { php_error(E_WARNING, "(Registered shutdown functions) Unable to call %s() - function does not exist", function_name); if (function_name) { efree(function_name); } return 0; } if (function_name) { efree(function_name); } if (call_user_function(EG(function_table), NULL, shutdown_function_entry->arguments[0], &retval, shutdown_function_entry->arg_count - 1, shutdown_function_entry->arguments + 1 TSRMLS_CC ) == SUCCESS) { zval_dtor(&retval); } return 0; } /* }}} */ static void user_tick_function_call(user_tick_function_entry *tick_fe TSRMLS_DC) /* {{{ */ { zval retval; zval *function = tick_fe->arguments[0]; /* Prevent reentrant calls to the same user ticks function */ if (! tick_fe->calling) { tick_fe->calling = 1; if (call_user_function( EG(function_table), NULL, function, &retval, tick_fe->arg_count - 1, tick_fe->arguments + 1 TSRMLS_CC) == SUCCESS) { zval_dtor(&retval); } else { zval **obj, **method; if (Z_TYPE_P(function) == IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call %s() - function does not exist", Z_STRVAL_P(function)); } else if ( Z_TYPE_P(function) == IS_ARRAY && zend_hash_index_find(Z_ARRVAL_P(function), 0, (void **) &obj) == SUCCESS && zend_hash_index_find(Z_ARRVAL_P(function), 1, (void **) &method) == SUCCESS && Z_TYPE_PP(obj) == IS_OBJECT && Z_TYPE_PP(method) == IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call %s::%s() - function does not exist", Z_OBJCE_PP(obj)->name, Z_STRVAL_PP(method)); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call tick function"); } } tick_fe->calling = 0; } } /* }}} */ static void run_user_tick_functions(int tick_count) /* {{{ */ { TSRMLS_FETCH(); zend_llist_apply(BG(user_tick_functions), (llist_apply_func_t) user_tick_function_call TSRMLS_CC); } /* }}} */ static int user_tick_function_compare(user_tick_function_entry * tick_fe1, user_tick_function_entry * tick_fe2) /* {{{ */ { zval *func1 = tick_fe1->arguments[0]; zval *func2 = tick_fe2->arguments[0]; int ret; TSRMLS_FETCH(); if (Z_TYPE_P(func1) == IS_STRING && Z_TYPE_P(func2) == IS_STRING) { ret = (zend_binary_zval_strcmp(func1, func2) == 0); } else if (Z_TYPE_P(func1) == IS_ARRAY && Z_TYPE_P(func2) == IS_ARRAY) { zval result; zend_compare_arrays(&result, func1, func2 TSRMLS_CC); ret = (Z_LVAL(result) == 0); } else if (Z_TYPE_P(func1) == IS_OBJECT && Z_TYPE_P(func2) == IS_OBJECT) { zval result; zend_compare_objects(&result, func1, func2 TSRMLS_CC); ret = (Z_LVAL(result) == 0); } else { ret = 0; } if (ret && tick_fe1->calling) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to delete tick function executed at the moment"); return 0; } return ret; } /* }}} */ void php_call_shutdown_functions(TSRMLS_D) /* {{{ */ { if (BG(user_shutdown_function_names)) { zend_try { zend_hash_apply(BG(user_shutdown_function_names), (apply_func_t) user_shutdown_function_call TSRMLS_CC); } zend_end_try(); php_free_shutdown_functions(TSRMLS_C); } } /* }}} */ void php_free_shutdown_functions(TSRMLS_D) /* {{{ */ { if (BG(user_shutdown_function_names)) zend_try { zend_hash_destroy(BG(user_shutdown_function_names)); FREE_HASHTABLE(BG(user_shutdown_function_names)); BG(user_shutdown_function_names) = NULL; } zend_end_try(); } /* }}} */ /* {{{ proto void register_shutdown_function(callback function) U Register a user-level function to be called on request termination */ PHP_FUNCTION(register_shutdown_function) { php_shutdown_function_entry shutdown_function_entry; char *callback_name = NULL; int i; shutdown_function_entry.arg_count = ZEND_NUM_ARGS(); if (shutdown_function_entry.arg_count < 1) { WRONG_PARAM_COUNT; } shutdown_function_entry.arguments = (zval **) safe_emalloc(sizeof(zval *), shutdown_function_entry.arg_count, 0); if (zend_get_parameters_array(ht, shutdown_function_entry.arg_count, shutdown_function_entry.arguments) == FAILURE) { efree(shutdown_function_entry.arguments); RETURN_FALSE; } /* Prevent entering of anything but valid callback (syntax check only!) */ if (!zend_is_callable(shutdown_function_entry.arguments[0], 0, &callback_name TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid shutdown callback '%s' passed", callback_name); efree(shutdown_function_entry.arguments); RETVAL_FALSE; } else { if (!BG(user_shutdown_function_names)) { ALLOC_HASHTABLE(BG(user_shutdown_function_names)); zend_hash_init(BG(user_shutdown_function_names), 0, NULL, (void (*)(void *)) user_shutdown_function_dtor, 0); } for (i = 0; i < shutdown_function_entry.arg_count; i++) { Z_ADDREF_P(shutdown_function_entry.arguments[i]); } zend_hash_next_index_insert(BG(user_shutdown_function_names), &shutdown_function_entry, sizeof(php_shutdown_function_entry), NULL); } if (callback_name) { efree(callback_name); } } /* }}} */ PHPAPI zend_bool register_user_shutdown_function(char *function_name, size_t function_len, php_shutdown_function_entry *shutdown_function_entry TSRMLS_DC) /* {{{ */ { if (!BG(user_shutdown_function_names)) { ALLOC_HASHTABLE(BG(user_shutdown_function_names)); zend_hash_init(BG(user_shutdown_function_names), 0, NULL, (void (*)(void *)) user_shutdown_function_dtor, 0); } return zend_hash_update(BG(user_shutdown_function_names), function_name, function_len, shutdown_function_entry, sizeof(php_shutdown_function_entry), NULL) != FAILURE; } /* }}} */ PHPAPI zend_bool remove_user_shutdown_function(char *function_name, size_t function_len TSRMLS_DC) /* {{{ */ { if (BG(user_shutdown_function_names)) { return zend_hash_del_key_or_index(BG(user_shutdown_function_names), function_name, function_len, 0, HASH_DEL_KEY) != FAILURE; } return 0; } /* }}} */ PHPAPI zend_bool append_user_shutdown_function(php_shutdown_function_entry shutdown_function_entry TSRMLS_DC) /* {{{ */ { if (!BG(user_shutdown_function_names)) { ALLOC_HASHTABLE(BG(user_shutdown_function_names)); zend_hash_init(BG(user_shutdown_function_names), 0, NULL, (void (*)(void *)) user_shutdown_function_dtor, 0); } return zend_hash_next_index_insert(BG(user_shutdown_function_names), &shutdown_function_entry, sizeof(php_shutdown_function_entry), NULL) != FAILURE; } /* }}} */ ZEND_API void php_get_highlight_struct(zend_syntax_highlighter_ini *syntax_highlighter_ini) /* {{{ */ { syntax_highlighter_ini->highlight_comment = INI_STR("highlight.comment"); syntax_highlighter_ini->highlight_default = INI_STR("highlight.default"); syntax_highlighter_ini->highlight_html = INI_STR("highlight.html"); syntax_highlighter_ini->highlight_keyword = INI_STR("highlight.keyword"); syntax_highlighter_ini->highlight_string = INI_STR("highlight.string"); } /* }}} */ /* {{{ proto bool highlight_file(string file_name [, bool return] ) Syntax highlight a source file */ PHP_FUNCTION(highlight_file) { char *filename; int filename_len, ret; zend_syntax_highlighter_ini syntax_highlighter_ini; zend_bool i = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|b", &filename, &filename_len, &i) == FAILURE) { RETURN_FALSE; } if (php_check_open_basedir(filename TSRMLS_CC)) { RETURN_FALSE; } if (i) { php_output_start_default(TSRMLS_C); } php_get_highlight_struct(&syntax_highlighter_ini); ret = highlight_file(filename, &syntax_highlighter_ini TSRMLS_CC); if (ret == FAILURE) { if (i) { php_output_end(TSRMLS_C); } RETURN_FALSE; } if (i) { php_output_get_contents(return_value TSRMLS_CC); php_output_discard(TSRMLS_C); } else { RETURN_TRUE; } } /* }}} */ /* {{{ proto string php_strip_whitespace(string file_name) Return source with stripped comments and whitespace */ PHP_FUNCTION(php_strip_whitespace) { char *filename; int filename_len; zend_lex_state original_lex_state; zend_file_handle file_handle = {0}; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &filename, &filename_len) == FAILURE) { RETURN_FALSE; } php_output_start_default(TSRMLS_C); file_handle.type = ZEND_HANDLE_FILENAME; file_handle.filename = filename; file_handle.free_filename = 0; file_handle.opened_path = NULL; zend_save_lexical_state(&original_lex_state TSRMLS_CC); if (open_file_for_scanning(&file_handle TSRMLS_CC) == FAILURE) { zend_restore_lexical_state(&original_lex_state TSRMLS_CC); php_output_end(TSRMLS_C); RETURN_EMPTY_STRING(); } zend_strip(TSRMLS_C); zend_destroy_file_handle(&file_handle TSRMLS_CC); zend_restore_lexical_state(&original_lex_state TSRMLS_CC); php_output_get_contents(return_value TSRMLS_CC); php_output_discard(TSRMLS_C); } /* }}} */ /* {{{ proto bool highlight_string(string string [, bool return] ) Syntax highlight a string or optionally return it */ PHP_FUNCTION(highlight_string) { zval **expr; zend_syntax_highlighter_ini syntax_highlighter_ini; char *hicompiled_string_description; zend_bool i = 0; int old_error_reporting = EG(error_reporting); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z|b", &expr, &i) == FAILURE) { RETURN_FALSE; } convert_to_string_ex(expr); if (i) { php_output_start_default(TSRMLS_C); } EG(error_reporting) = E_ERROR; php_get_highlight_struct(&syntax_highlighter_ini); hicompiled_string_description = zend_make_compiled_string_description("highlighted code" TSRMLS_CC); if (highlight_string(*expr, &syntax_highlighter_ini, hicompiled_string_description TSRMLS_CC) == FAILURE) { efree(hicompiled_string_description); EG(error_reporting) = old_error_reporting; if (i) { php_output_end(TSRMLS_C); } RETURN_FALSE; } efree(hicompiled_string_description); EG(error_reporting) = old_error_reporting; if (i) { php_output_get_contents(return_value TSRMLS_CC); php_output_discard(TSRMLS_C); } else { RETURN_TRUE; } } /* }}} */ /* {{{ proto string ini_get(string varname) Get a configuration option */ PHP_FUNCTION(ini_get) { char *varname, *str; int varname_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &varname, &varname_len) == FAILURE) { return; } str = zend_ini_string(varname, varname_len + 1, 0); if (!str) { RETURN_FALSE; } RETURN_STRING(str, 1); } /* }}} */ static int php_ini_get_option(zend_ini_entry *ini_entry TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zval *ini_array = va_arg(args, zval *); int module_number = va_arg(args, int); int details = va_arg(args, int); zval *option; if (module_number != 0 && ini_entry->module_number != module_number) { return 0; } if (hash_key->nKeyLength == 0 || hash_key->arKey[0] != 0 ) { if (details) { MAKE_STD_ZVAL(option); array_init(option); if (ini_entry->orig_value) { add_assoc_stringl(option, "global_value", ini_entry->orig_value, ini_entry->orig_value_length, 1); } else if (ini_entry->value) { add_assoc_stringl(option, "global_value", ini_entry->value, ini_entry->value_length, 1); } else { add_assoc_null(option, "global_value"); } if (ini_entry->value) { add_assoc_stringl(option, "local_value", ini_entry->value, ini_entry->value_length, 1); } else { add_assoc_null(option, "local_value"); } add_assoc_long(option, "access", ini_entry->modifiable); add_assoc_zval_ex(ini_array, ini_entry->name, ini_entry->name_length, option); } else { if (ini_entry->value) { add_assoc_stringl(ini_array, ini_entry->name, ini_entry->value, ini_entry->value_length, 1); } else { add_assoc_null(ini_array, ini_entry->name); } } } return 0; } /* }}} */ /* {{{ proto array ini_get_all([string extension[, bool details = true]]) Get all configuration options */ PHP_FUNCTION(ini_get_all) { char *extname = NULL; int extname_len = 0, extnumber = 0; zend_module_entry *module; zend_bool details = 1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!b", &extname, &extname_len, &details) == FAILURE) { return; } zend_ini_sort_entries(TSRMLS_C); if (extname) { if (zend_hash_find(&module_registry, extname, extname_len+1, (void **) &module) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to find extension '%s'", extname); RETURN_FALSE; } extnumber = module->module_number; } array_init(return_value); zend_hash_apply_with_arguments(EG(ini_directives) TSRMLS_CC, (apply_func_args_t) php_ini_get_option, 2, return_value, extnumber, details); } /* }}} */ static int php_ini_check_path(char *option_name, int option_len, char *new_option_name, int new_option_len) /* {{{ */ { if (option_len != (new_option_len - 1)) { return 0; } return !strncmp(option_name, new_option_name, option_len); } /* }}} */ /* {{{ proto string ini_set(string varname, string newvalue) Set a configuration option, returns false on error and the old value of the configuration option on success */ PHP_FUNCTION(ini_set) { char *varname, *new_value; int varname_len, new_value_len; char *old_value; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &varname, &varname_len, &new_value, &new_value_len) == FAILURE) { return; } old_value = zend_ini_string(varname, varname_len + 1, 0); /* copy to return here, because alter might free it! */ if (old_value) { RETVAL_STRING(old_value, 1); } else { RETVAL_FALSE; } #define _CHECK_PATH(var, var_len, ini) php_ini_check_path(var, var_len, ini, sizeof(ini)) /* open basedir check */ if (PG(open_basedir)) { if (_CHECK_PATH(varname, varname_len, "error_log") || _CHECK_PATH(varname, varname_len, "java.class.path") || _CHECK_PATH(varname, varname_len, "java.home") || _CHECK_PATH(varname, varname_len, "mail.log") || _CHECK_PATH(varname, varname_len, "java.library.path") || _CHECK_PATH(varname, varname_len, "vpopmail.directory")) { if (php_check_open_basedir(new_value TSRMLS_CC)) { zval_dtor(return_value); RETURN_FALSE; } } } if (zend_alter_ini_entry_ex(varname, varname_len + 1, new_value, new_value_len, PHP_INI_USER, PHP_INI_STAGE_RUNTIME, 0 TSRMLS_CC) == FAILURE) { zval_dtor(return_value); RETURN_FALSE; } } /* }}} */ /* {{{ proto void ini_restore(string varname) Restore the value of a configuration option specified by varname */ PHP_FUNCTION(ini_restore) { char *varname; int varname_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &varname, &varname_len) == FAILURE) { return; } zend_restore_ini_entry(varname, varname_len+1, PHP_INI_STAGE_RUNTIME); } /* }}} */ /* {{{ proto string set_include_path(string new_include_path) Sets the include_path configuration option */ PHP_FUNCTION(set_include_path) { char *new_value; int new_value_len; char *old_value; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &new_value, &new_value_len) == FAILURE) { return; } old_value = zend_ini_string("include_path", sizeof("include_path"), 0); /* copy to return here, because alter might free it! */ if (old_value) { RETVAL_STRING(old_value, 1); } else { RETVAL_FALSE; } if (zend_alter_ini_entry_ex("include_path", sizeof("include_path"), new_value, new_value_len, PHP_INI_USER, PHP_INI_STAGE_RUNTIME, 0 TSRMLS_CC) == FAILURE) { zval_dtor(return_value); RETURN_FALSE; } } /* }}} */ /* {{{ proto string get_include_path() Get the current include_path configuration option */ PHP_FUNCTION(get_include_path) { char *str; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "") == FAILURE) { return; } str = zend_ini_string("include_path", sizeof("include_path"), 0); if (str == NULL) { RETURN_FALSE; } RETURN_STRING(str, 1); } /* }}} */ /* {{{ proto void restore_include_path() Restore the value of the include_path configuration option */ PHP_FUNCTION(restore_include_path) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "") == FAILURE) { return; } zend_restore_ini_entry("include_path", sizeof("include_path"), PHP_INI_STAGE_RUNTIME); } /* }}} */ /* {{{ proto mixed print_r(mixed var [, bool return]) Prints out or returns information about the specified variable */ PHP_FUNCTION(print_r) { zval *var; zend_bool do_return = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|b", &var, &do_return) == FAILURE) { RETURN_FALSE; } if (do_return) { php_output_start_default(TSRMLS_C); } zend_print_zval_r(var, 0 TSRMLS_CC); if (do_return) { php_output_get_contents(return_value TSRMLS_CC); php_output_discard(TSRMLS_C); } else { RETURN_TRUE; } } /* }}} */ /* {{{ proto int connection_aborted(void) Returns true if client disconnected */ PHP_FUNCTION(connection_aborted) { RETURN_LONG(PG(connection_status) & PHP_CONNECTION_ABORTED); } /* }}} */ /* {{{ proto int connection_status(void) Returns the connection status bitfield */ PHP_FUNCTION(connection_status) { RETURN_LONG(PG(connection_status)); } /* }}} */ /* {{{ proto int ignore_user_abort([string value]) Set whether we want to ignore a user abort event or not */ PHP_FUNCTION(ignore_user_abort) { char *arg = NULL; int arg_len = 0; int old_setting; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &arg, &arg_len) == FAILURE) { return; } old_setting = PG(ignore_user_abort); if (arg) { zend_alter_ini_entry_ex("ignore_user_abort", sizeof("ignore_user_abort"), arg, arg_len, PHP_INI_USER, PHP_INI_STAGE_RUNTIME, 0 TSRMLS_CC); } RETURN_LONG(old_setting); } /* }}} */ #if HAVE_GETSERVBYNAME /* {{{ proto int getservbyname(string service, string protocol) Returns port associated with service. Protocol must be "tcp" or "udp" */ PHP_FUNCTION(getservbyname) { char *name, *proto; int name_len, proto_len; struct servent *serv; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &name, &name_len, &proto, &proto_len) == FAILURE) { return; } /* empty string behaves like NULL on windows implementation of getservbyname. Let be portable instead. */ #ifdef PHP_WIN32 if (proto_len == 0) { RETURN_FALSE; } #endif serv = getservbyname(name, proto); if (serv == NULL) { RETURN_FALSE; } RETURN_LONG(ntohs(serv->s_port)); } /* }}} */ #endif #if HAVE_GETSERVBYPORT /* {{{ proto string getservbyport(int port, string protocol) Returns service name associated with port. Protocol must be "tcp" or "udp" */ PHP_FUNCTION(getservbyport) { char *proto; int proto_len; long port; struct servent *serv; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ls", &port, &proto, &proto_len) == FAILURE) { return; } serv = getservbyport(htons((unsigned short) port), proto); if (serv == NULL) { RETURN_FALSE; } RETURN_STRING(serv->s_name, 1); } /* }}} */ #endif #if HAVE_GETPROTOBYNAME /* {{{ proto int getprotobyname(string name) Returns protocol number associated with name as per /etc/protocols */ PHP_FUNCTION(getprotobyname) { char *name; int name_len; struct protoent *ent; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) { return; } ent = getprotobyname(name); if (ent == NULL) { RETURN_FALSE; } RETURN_LONG(ent->p_proto); } /* }}} */ #endif #if HAVE_GETPROTOBYNUMBER /* {{{ proto string getprotobynumber(int proto) Returns protocol name associated with protocol number proto */ PHP_FUNCTION(getprotobynumber) { long proto; struct protoent *ent; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &proto) == FAILURE) { return; } ent = getprotobynumber(proto); if (ent == NULL) { RETURN_FALSE; } RETURN_STRING(ent->p_name, 1); } /* }}} */ #endif /* {{{ proto bool register_tick_function(string function_name [, mixed arg [, mixed ... ]]) Registers a tick callback function */ PHP_FUNCTION(register_tick_function) { user_tick_function_entry tick_fe; int i; char *function_name = NULL; tick_fe.calling = 0; tick_fe.arg_count = ZEND_NUM_ARGS(); if (tick_fe.arg_count < 1) { WRONG_PARAM_COUNT; } tick_fe.arguments = (zval **) safe_emalloc(sizeof(zval *), tick_fe.arg_count, 0); if (zend_get_parameters_array(ht, tick_fe.arg_count, tick_fe.arguments) == FAILURE) { efree(tick_fe.arguments); RETURN_FALSE; } if (!zend_is_callable(tick_fe.arguments[0], 0, &function_name TSRMLS_CC)) { efree(tick_fe.arguments); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid tick callback '%s' passed", function_name); efree(function_name); RETURN_FALSE; } else if (function_name) { efree(function_name); } if (Z_TYPE_P(tick_fe.arguments[0]) != IS_ARRAY && Z_TYPE_P(tick_fe.arguments[0]) != IS_OBJECT) { convert_to_string_ex(&tick_fe.arguments[0]); } if (!BG(user_tick_functions)) { BG(user_tick_functions) = (zend_llist *) emalloc(sizeof(zend_llist)); zend_llist_init(BG(user_tick_functions), sizeof(user_tick_function_entry), (llist_dtor_func_t) user_tick_function_dtor, 0); php_add_tick_function(run_user_tick_functions); } for (i = 0; i < tick_fe.arg_count; i++) { Z_ADDREF_P(tick_fe.arguments[i]); } zend_llist_add_element(BG(user_tick_functions), &tick_fe); RETURN_TRUE; } /* }}} */ /* {{{ proto void unregister_tick_function(string function_name) Unregisters a tick callback function */ PHP_FUNCTION(unregister_tick_function) { zval *function; user_tick_function_entry tick_fe; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z/", &function) == FAILURE) { return; } if (!BG(user_tick_functions)) { return; } if (Z_TYPE_P(function) != IS_ARRAY) { convert_to_string(function); } tick_fe.arguments = (zval **) emalloc(sizeof(zval *)); tick_fe.arguments[0] = function; tick_fe.arg_count = 1; zend_llist_del_element(BG(user_tick_functions), &tick_fe, (int (*)(void *, void *)) user_tick_function_compare); efree(tick_fe.arguments); } /* }}} */ /* {{{ proto bool is_uploaded_file(string path) Check if file was created by rfc1867 upload */ PHP_FUNCTION(is_uploaded_file) { char *path; int path_len; if (!SG(rfc1867_uploaded_files)) { RETURN_FALSE; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &path, &path_len) == FAILURE) { return; } if (zend_hash_exists(SG(rfc1867_uploaded_files), path, path_len + 1)) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool move_uploaded_file(string path, string new_path) Move a file if and only if it was created by an upload */ PHP_FUNCTION(move_uploaded_file) { char *path, *new_path; int path_len, new_path_len; zend_bool successful = 0; #ifndef PHP_WIN32 int oldmask; int ret; #endif if (!SG(rfc1867_uploaded_files)) { RETURN_FALSE; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &path, &path_len, &new_path, &new_path_len) == FAILURE) { return; } if (!zend_hash_exists(SG(rfc1867_uploaded_files), path, path_len + 1)) { RETURN_FALSE; } if (php_check_open_basedir(new_path TSRMLS_CC)) { RETURN_FALSE; } if (VCWD_RENAME(path, new_path) == 0) { successful = 1; #ifndef PHP_WIN32 oldmask = umask(077); umask(oldmask); ret = VCWD_CHMOD(new_path, 0666 & ~oldmask); if (ret == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", strerror(errno)); } #endif } else if (php_copy_file_ex(path, new_path, STREAM_DISABLE_OPEN_BASEDIR TSRMLS_CC) == SUCCESS) { VCWD_UNLINK(path); successful = 1; } if (successful) { zend_hash_del(SG(rfc1867_uploaded_files), path, path_len + 1); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to move '%s' to '%s'", path, new_path); } RETURN_BOOL(successful); } /* }}} */ /* {{{ php_simple_ini_parser_cb */ static void php_simple_ini_parser_cb(zval *arg1, zval *arg2, zval *arg3, int callback_type, zval *arr TSRMLS_DC) { zval *element; switch (callback_type) { case ZEND_INI_PARSER_ENTRY: if (!arg2) { /* bare string - nothing to do */ break; } ALLOC_ZVAL(element); MAKE_COPY_ZVAL(&arg2, element); zend_symtable_update(Z_ARRVAL_P(arr), Z_STRVAL_P(arg1), Z_STRLEN_P(arg1) + 1, &element, sizeof(zval *), NULL); break; case ZEND_INI_PARSER_POP_ENTRY: { zval *hash, **find_hash; if (!arg2) { /* bare string - nothing to do */ break; } if (!(Z_STRLEN_P(arg1) > 1 && Z_STRVAL_P(arg1)[0] == '0') && is_numeric_string(Z_STRVAL_P(arg1), Z_STRLEN_P(arg1), NULL, NULL, 0) == IS_LONG) { ulong key = (ulong) zend_atol(Z_STRVAL_P(arg1), Z_STRLEN_P(arg1)); if (zend_hash_index_find(Z_ARRVAL_P(arr), key, (void **) &find_hash) == FAILURE) { ALLOC_ZVAL(hash); INIT_PZVAL(hash); array_init(hash); zend_hash_index_update(Z_ARRVAL_P(arr), key, &hash, sizeof(zval *), NULL); } else { hash = *find_hash; } } else { if (zend_hash_find(Z_ARRVAL_P(arr), Z_STRVAL_P(arg1), Z_STRLEN_P(arg1) + 1, (void **) &find_hash) == FAILURE) { ALLOC_ZVAL(hash); INIT_PZVAL(hash); array_init(hash); zend_hash_update(Z_ARRVAL_P(arr), Z_STRVAL_P(arg1), Z_STRLEN_P(arg1) + 1, &hash, sizeof(zval *), NULL); } else { hash = *find_hash; } } if (Z_TYPE_P(hash) != IS_ARRAY) { zval_dtor(hash); INIT_PZVAL(hash); array_init(hash); } ALLOC_ZVAL(element); MAKE_COPY_ZVAL(&arg2, element); if (arg3 && Z_STRLEN_P(arg3) > 0) { add_assoc_zval_ex(hash, Z_STRVAL_P(arg3), Z_STRLEN_P(arg3) + 1, element); } else { add_next_index_zval(hash, element); } } break; case ZEND_INI_PARSER_SECTION: break; } } /* }}} */ /* {{{ php_ini_parser_cb_with_sections */ static void php_ini_parser_cb_with_sections(zval *arg1, zval *arg2, zval *arg3, int callback_type, zval *arr TSRMLS_DC) { if (callback_type == ZEND_INI_PARSER_SECTION) { MAKE_STD_ZVAL(BG(active_ini_file_section)); array_init(BG(active_ini_file_section)); zend_symtable_update(Z_ARRVAL_P(arr), Z_STRVAL_P(arg1), Z_STRLEN_P(arg1) + 1, &BG(active_ini_file_section), sizeof(zval *), NULL); } else if (arg2) { zval *active_arr; if (BG(active_ini_file_section)) { active_arr = BG(active_ini_file_section); } else { active_arr = arr; } php_simple_ini_parser_cb(arg1, arg2, arg3, callback_type, active_arr TSRMLS_CC); } } /* }}} */ /* {{{ proto array parse_ini_file(string filename [, bool process_sections [, int scanner_mode]]) Parse configuration file */ PHP_FUNCTION(parse_ini_file) { char *filename = NULL; int filename_len = 0; zend_bool process_sections = 0; long scanner_mode = ZEND_INI_SCANNER_NORMAL; zend_file_handle fh; zend_ini_parser_cb_t ini_parser_cb; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|bl", &filename, &filename_len, &process_sections, &scanner_mode) == FAILURE) { RETURN_FALSE; } if (filename_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Filename cannot be empty!"); RETURN_FALSE; } /* Set callback function */ if (process_sections) { BG(active_ini_file_section) = NULL; ini_parser_cb = (zend_ini_parser_cb_t) php_ini_parser_cb_with_sections; } else { ini_parser_cb = (zend_ini_parser_cb_t) php_simple_ini_parser_cb; } /* Setup filehandle */ memset(&fh, 0, sizeof(fh)); fh.filename = filename; fh.type = ZEND_HANDLE_FILENAME; array_init(return_value); if (zend_parse_ini_file(&fh, 0, scanner_mode, ini_parser_cb, return_value TSRMLS_CC) == FAILURE) { zend_hash_destroy(Z_ARRVAL_P(return_value)); efree(Z_ARRVAL_P(return_value)); RETURN_FALSE; } } /* }}} */ /* {{{ proto array parse_ini_string(string ini_string [, bool process_sections [, int scanner_mode]]) Parse configuration string */ PHP_FUNCTION(parse_ini_string) { char *string = NULL, *str = NULL; int str_len = 0; zend_bool process_sections = 0; long scanner_mode = ZEND_INI_SCANNER_NORMAL; zend_ini_parser_cb_t ini_parser_cb; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|bl", &str, &str_len, &process_sections, &scanner_mode) == FAILURE) { RETURN_FALSE; } if (INT_MAX - str_len < ZEND_MMAP_AHEAD) { RETVAL_FALSE; } /* Set callback function */ if (process_sections) { BG(active_ini_file_section) = NULL; ini_parser_cb = (zend_ini_parser_cb_t) php_ini_parser_cb_with_sections; } else { ini_parser_cb = (zend_ini_parser_cb_t) php_simple_ini_parser_cb; } /* Setup string */ string = (char *) emalloc(str_len + ZEND_MMAP_AHEAD); memcpy(string, str, str_len); memset(string + str_len, 0, ZEND_MMAP_AHEAD); array_init(return_value); if (zend_parse_ini_string(string, 0, scanner_mode, ini_parser_cb, return_value TSRMLS_CC) == FAILURE) { zend_hash_destroy(Z_ARRVAL_P(return_value)); efree(Z_ARRVAL_P(return_value)); RETVAL_FALSE; } efree(string); } /* }}} */ #if ZEND_DEBUG /* This function returns an array of ALL valid ini options with values and * is not the same as ini_get_all() which returns only registered ini options. Only useful for devs to debug php.ini scanner/parser! */ PHP_FUNCTION(config_get_hash) /* {{{ */ { HashTable *hash = php_ini_get_configuration_hash(); array_init(return_value); zend_hash_apply_with_arguments(hash TSRMLS_CC, (apply_func_args_t) add_config_entry_cb, 1, return_value); } /* }}} */ #endif #ifdef HAVE_GETLOADAVG /* {{{ proto array sys_getloadavg() */ PHP_FUNCTION(sys_getloadavg) { double load[3]; if (zend_parse_parameters_none() == FAILURE) { return; } if (getloadavg(load, 3) == -1) { RETURN_FALSE; } else { array_init(return_value); add_index_double(return_value, 0, load[0]); add_index_double(return_value, 1, load[1]); add_index_double(return_value, 2, load[2]); } } /* }}} */ #endif /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: fdm=marker * vim: noet sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2012-03-12-438a30f1e7-7337a901b7.c
manybugs_data_47
/* $Id$ */ /* tiffcrop.c -- a port of tiffcp.c extended to include manipulations of * the image data through additional options listed below * * Original code: * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. * * The portions of the current code that are derived from tiffcp are primarly * in the areas of lowlevel reading and writing of scanlines and tiles though * some of the original functions have been extended to support arbitrary bit * depths. These functions are presented at the top of this file. * * Additions (c) Richard Nolde 2006-2009 Last Updated 1/6/2009 * IN NO EVENT SHALL RICHARD NOLDE BE LIABLE FOR ANY SPECIAL, INCIDENTAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * Add support for the options below to extract sections of image(s) * and to modify the whole image or selected portions of each image by * rotations, mirroring, and colorscale/colormap inversion of selected * types of TIFF images when appropriate. Some color model dependent * functions are restricted to bilevel or 8 bit per sample data. * See the man page for the full explanations. * * Options: * -h Display the syntax guide. * -v Report the version and last build date for tiffcrop * -z x1,y1,x2,y2:x3,y3,x4,y4:..xN,yN,xN + 1, yN + 1 * Specify a series of coordinates to define rectangular * regions by the top left and lower right corners. * -e c|d|i|m|s export mode for images and selections from input images * combined All images and selections are written to a single file (default) * with multiple selections from one image combined into a single image * divided All images and selections are written to a single file * with each selection from one image written to a new image * image Each input image is written to a new file (numeric filename sequence) * with multiple selections from the image combined into one image * multiple Each input image is written to a new file (numeric filename sequence) * with each selection from the image written to a new image * separated Individual selections from each image are written to separate files * -U units [in, cm, px ] inches, centimeters or pixels * -H # Set horizontal resolution of output images to # * -V # Set vertical resolution of output images to # * -J # Horizontal margin of output page to # expressed in current * units * -K # Vertical margin of output page to # expressed in current * units * -X # Horizontal dimension of region to extract expressed in current * units * -Y # Vertical dimension of region to extract expressed in current * units * -O orient Orientation for output image, portrait, landscape, auto * -P page Page size for output image segments, eg letter, legal, tabloid, * etc. * -S cols:rows Divide the image into equal sized segments using cols across * and rows down * -E t|l|r|b Edge to use as origin * -m #,#,#,# Margins from edges for selection: top, left, bottom, right * (commas separated) * -Z #:#,#:# Zones of the image designated as zone X of Y, * eg 1:3 would be first of three equal portions measured * from reference edge * -N odd|even|#,#-#,#|last * Select sequences and/or ranges of images within file * to process. The words odd or even may be used to specify * all odd or even numbered images the word last may be used * in place of a number in the sequence to indicate the final * image in the file without knowing how many images there are. * -R # Rotate image or crop selection by 90,180,or 270 degrees * clockwise * -F h|v Flip (mirror) image or crop selection horizontally * or vertically * -I [black|white|data|both] * Invert color space, eg dark to light for bilevel and grayscale images * If argument is white or black, set the PHOTOMETRIC_INTERPRETATION * tag to MinIsBlack or MinIsWhite without altering the image data * If the argument is data or both, the image data are modified: * both inverts the data and the PHOTOMETRIC_INTERPRETATION tag, * data inverts the data but not the PHOTOMETRIC_INTERPRETATION tag * -D input:<filename1>,output:<filename2>,format:<raw|txt>,level:N,debug:N * Dump raw data for input and/or output images to individual files * in raw (binary) format or text (ASCII) representing binary data * as strings of 1s and 0s. The filename arguments are used as stems * from which individual files are created for each image. Text format * includes annotations for image parameters and scanline info. Level * selects which functions dump data, with higher numbers selecting * lower level, scanline level routines. Debug reports a limited set * of messages to monitor progess without enabling dump logs. */ #include "tif_config.h" #include "tiffiop.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <ctype.h> #include <limits.h> #include <sys/stat.h> #include <assert.h> #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #ifdef HAVE_STDINT_H # include <stdint.h> #endif #ifndef HAVE_GETOPT extern int getopt(int, char**, char*); #endif #include "tiffio.h" #if defined(VMS) # define unlink delete #endif #ifndef PATH_MAX #define PATH_MAX 1024 #endif #ifndef streq #define streq(a,b) (strcmp((a),(b)) == 0) #endif #define strneq(a,b,n) (strncmp((a),(b),(n)) == 0) /* NB: the uint32 casts are to silence certain ANSI-C compilers */ #define TIFFhowmany(x, y) ((((uint32)(x))+(((uint32)(y))-1))/((uint32)(y))) #define TIFFhowmany8(x) (((x)&0x07)?((uint32)(x)>>3)+1:(uint32)(x)>>3) #define TRUE 1 #define FALSE 0 /* * Definitions and data structures required to support cropping and image * manipulations. */ #define EDGE_TOP 1 #define EDGE_LEFT 2 #define EDGE_BOTTOM 3 #define EDGE_RIGHT 4 #define EDGE_CENTER 5 #define MIRROR_HORIZ 1 #define MIRROR_VERT 2 #define MIRROR_BOTH 3 #define ROTATECW_90 8 #define ROTATECW_180 16 #define ROTATECW_270 32 #define ROTATE_ANY ROTATECW_90 || ROTATECW_180 || ROTATECW_270 #define CROP_NONE 0 #define CROP_MARGINS 1 #define CROP_WIDTH 2 #define CROP_LENGTH 4 #define CROP_ZONES 8 #define CROP_REGIONS 16 #define CROP_ROTATE 32 #define CROP_MIRROR 64 #define CROP_INVERT 128 /* Modes for writing out images and selections */ #define ONE_FILE_COMPOSITE 0 /* One file, sections combined sections */ #define ONE_FILE_SEPARATED 1 /* One file, sections to new IFDs */ #define FILE_PER_IMAGE_COMPOSITE 2 /* One file per image, combined sections */ #define FILE_PER_IMAGE_SEPARATED 3 /* One file per input image */ #define FILE_PER_SELECTION 4 /* One file per selection */ #define COMPOSITE_IMAGES 0 /* Selections combined into one image */ #define SEPARATED_IMAGES 1 /* Selections saved to separate images */ #define STRIP 1 #define TILE 2 #define MAX_REGIONS 8 /* number of regions to extract from a single page */ #define MAX_OUTBUFFS 8 /* must match larger of zones or regions */ #define MAX_SECTIONS 32 /* number of sections per page to write to output */ #define MAX_IMAGES 1024 /* number of images in descrete list, not in the file */ #define MAX_SAMPLES 8 /* maximum number of samples per pixel supported */ #define MAX_BITS_PER_SAMPLE 64 /* maximum bit depth supported */ #define DUMP_NONE 0 #define DUMP_TEXT 1 #define DUMP_RAW 2 /* Offsets into buffer for margins and fixed width and length segments */ struct offset { uint32 tmargin; uint32 lmargin; uint32 bmargin; uint32 rmargin; uint32 crop_width; uint32 crop_length; uint32 startx; uint32 endx; uint32 starty; uint32 endy; }; /* Description of a zone within the image. Position 1 of 3 zones would be * the first third of the image. These are computed after margins and * width/length requests are applied so that you can extract multiple * zones from within a larger region for OCR or barcode recognition. */ struct buffinfo { uint32 size; /* size of this buffer */ unsigned char *buffer; /* address of the allocated buffer */ }; struct zone { int position; /* ordinal of segment to be extracted */ int total; /* total equal sized divisions of crop area */ }; struct pageseg { uint32 x1; /* index of left edge */ uint32 x2; /* index of right edge */ uint32 y1; /* index of top edge */ uint32 y2; /* index of bottom edge */ int position; /* ordinal of segment to be extracted */ int total; /* total equal sized divisions of crop area */ uint32 buffsize; /* size of buffer needed to hold the cropped zone */ }; struct coordpairs { double X1; /* index of left edge in current units */ double X2; /* index of right edge in current units */ double Y1; /* index of top edge in current units */ double Y2; /* index of bottom edge in current units */ }; struct region { uint32 x1; /* pixel offset of left edge */ uint32 x2; /* pixel offset of right edge */ uint32 y1; /* pixel offset of top edge */ uint32 y2; /* picel offset of bottom edge */ uint32 width; /* width in pixels */ uint32 length; /* length in pixels */ uint32 buffsize; /* size of buffer needed to hold the cropped region */ unsigned char *buffptr; /* address of start of the region */ }; /* Cropping parameters from command line and image data */ struct crop_mask { double width; /* Selection width for master crop region in requested units */ double length; /* Selection length for master crop region in requesed units */ double margins[4]; /* Top, left, bottom, right margins */ float xres; /* Horizontal resolution read from image*/ float yres; /* Vertical resolution read from image */ uint32 combined_width; /* Width of combined cropped zones */ uint32 combined_length; /* Length of combined cropped zones */ uint32 bufftotal; /* Size of buffer needed to hold all the cropped region */ uint16 img_mode; /* Composite or separate images created from zones or regions */ uint16 exp_mode; /* Export input images or selections to one or more files */ uint16 crop_mode; /* Crop options to be applied */ uint16 res_unit; /* Resolution unit for margins and selections */ uint16 edge_ref; /* Reference edge for sections extraction and combination */ uint16 rotation; /* Clockwise rotation of the extracted region or image */ uint16 mirror; /* Mirror extracted region or image horizontally or vertically */ uint16 invert; /* Invert the color map of image or region */ uint16 photometric; /* Status of photometric interpretation for inverted image */ uint16 selections; /* Number of regions or zones selected */ uint16 regions; /* Number of regions delimited by corner coordinates */ struct region regionlist[MAX_REGIONS]; /* Regions within page or master crop region */ uint16 zones; /* Number of zones delimited by Ordinal:Total requested */ struct zone zonelist[MAX_REGIONS]; /* Zones indices to define a region */ struct coordpairs corners[MAX_REGIONS]; /* Coordinates of upper left and lower right corner */ }; #define MAX_PAPERNAMES 49 #define MAX_PAPERNAME_LENGTH 15 #define DEFAULT_RESUNIT RESUNIT_INCH #define DEFAULT_PAGE_HEIGHT 14.0 #define DEFAULT_PAGE_WIDTH 8.5 #define DEFAULT_RESOLUTION 300 #define DEFAULT_PAPER_SIZE "legal" #define ORIENTATION_NONE 0 #define ORIENTATION_PORTRAIT 1 #define ORIENTATION_LANDSCAPE 2 #define ORIENTATION_SEASCAPE 4 #define ORIENTATION_AUTO 16 #define PAGE_MODE_NONE 0 #define PAGE_MODE_RESOLUTION 1 #define PAGE_MODE_PAPERSIZE 2 #define PAGE_MODE_MARGINS 4 #define PAGE_MODE_ROWSCOLS 8 #define INVERT_DATA_ONLY 10 #define INVERT_DATA_AND_TAG 11 struct paperdef { char name[MAX_PAPERNAME_LENGTH]; double width; double length; double asratio; }; /* Paper Size Width Length Aspect Ratio */ struct paperdef PaperTable[MAX_PAPERNAMES] = { {"default", 8.500, 14.000, 0.607}, {"pa4", 8.264, 11.000, 0.751}, {"letter", 8.500, 11.000, 0.773}, {"legal", 8.500, 14.000, 0.607}, {"half-letter", 8.500, 5.514, 1.542}, {"executive", 7.264, 10.528, 0.690}, {"tabloid", 11.000, 17.000, 0.647}, {"11x17", 11.000, 17.000, 0.647}, {"ledger", 17.000, 11.000, 1.545}, {"archa", 9.000, 12.000, 0.750}, {"archb", 12.000, 18.000, 0.667}, {"archc", 18.000, 24.000, 0.750}, {"archd", 24.000, 36.000, 0.667}, {"arche", 36.000, 48.000, 0.750}, {"csheet", 17.000, 22.000, 0.773}, {"dsheet", 22.000, 34.000, 0.647}, {"esheet", 34.000, 44.000, 0.773}, {"superb", 11.708, 17.042, 0.687}, {"commercial", 4.139, 9.528, 0.434}, {"monarch", 3.889, 7.528, 0.517}, {"envelope-dl", 4.333, 8.681, 0.499}, {"envelope-c5", 6.389, 9.028, 0.708}, {"europostcard", 4.139, 5.833, 0.710}, {"a0", 33.111, 46.806, 0.707}, {"a1", 23.389, 33.111, 0.706}, {"a2", 16.542, 23.389, 0.707}, {"a3", 11.694, 16.542, 0.707}, {"a4", 8.264, 11.694, 0.707}, {"a5", 5.833, 8.264, 0.706}, {"a6", 4.125, 5.833, 0.707}, {"a7", 2.917, 4.125, 0.707}, {"a8", 2.056, 2.917, 0.705}, {"a9", 1.458, 2.056, 0.709}, {"a10", 1.014, 1.458, 0.695}, {"b0", 39.375, 55.667, 0.707}, {"b1", 27.833, 39.375, 0.707}, {"b2", 19.681, 27.833, 0.707}, {"b3", 13.903, 19.681, 0.706}, {"b4", 9.847, 13.903, 0.708}, {"b5", 6.931, 9.847, 0.704}, {"b6", 4.917, 6.931, 0.709}, {"c0", 36.097, 51.069, 0.707}, {"c1", 25.514, 36.097, 0.707}, {"c2", 18.028, 25.514, 0.707}, {"c3", 12.750, 18.028, 0.707}, {"c4", 9.014, 12.750, 0.707}, {"c5", 6.375, 9.014, 0.707}, {"c6", 4.486, 6.375, 0.704}, {"", 0.000, 0.000, 1.000}, }; /* Structure to define in input image parameters */ struct image_data { float xres; float yres; uint32 width; uint32 length; uint16 res_unit; uint16 bps; uint16 spp; uint16 planar; uint16 photometric; uint16 orientation; uint16 adjustments; }; /* Structure to define the output image modifiers */ struct pagedef { char name[16]; double width; /* width in pixels */ double length; /* length in pixels */ double hmargin; /* margins to subtract from width of sections */ double vmargin; /* margins to subtract from height of sections */ double hres; /* horizontal resolution for output */ double vres; /* vertical resolution for output */ uint32 mode; /* bitmask of modifiers to page format */ uint16 res_unit; /* resolution unit for output image */ unsigned int rows; /* number of section rows */ unsigned int cols; /* number of section cols */ unsigned int orient; /* portrait, landscape, seascape, auto */ }; struct dump_opts { int debug; int format; int level; char mode[4]; char infilename[PATH_MAX + 1]; char outfilename[PATH_MAX + 1]; FILE *infile; FILE *outfile; }; /* globals */ static int outtiled = -1; static uint32 tilewidth; static uint32 tilelength; static uint16 config; static uint16 compression; static uint16 predictor; static uint16 fillorder; static uint32 rowsperstrip; static uint32 g3opts; static int ignore = FALSE; /* if true, ignore read errors */ static uint32 defg3opts = (uint32) -1; static int quality = 75; /* JPEG quality */ static int jpegcolormode = JPEGCOLORMODE_RGB; static uint16 defcompression = (uint16) -1; static uint16 defpredictor = (uint16) -1; static int pageNum = 0; static int little_endian = 1; /* Functions adapted from tiffcp with additions or modifications */ static int readContigStripsIntoBuffer (TIFF*, uint8*, uint32, uint32, tsample_t); static int readSeparateStripsIntoBuffer (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int readContigTilesIntoBuffer (TIFF*, uint8*, uint32, uint32, tsample_t); static int readSeparateTilesIntoBuffer (TIFF*, uint8*, uint32, uint32, tsample_t); static int writeBufferToContigStrips (TIFF*, uint8*, uint32, uint32, tsample_t); static int writeBufferToContigTiles (TIFF*, uint8*, uint32, uint32, tsample_t); static int writeBufferToSeparateStrips (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int writeBufferToSeparateTiles (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int extractContigSamplesToBuffer (uint8 *, uint8 *, uint32, uint32, int, int, tsample_t, uint16, uint16, struct dump_opts *); static void cpStripToTile (uint8*, uint8*, uint32, uint32, int, int); static void cpSeparateBufToContigBuf(uint8 *, uint8 *, uint32, uint32 , int, int, tsample_t, int); static int processCompressOptions(char*); static void usage(void); /* New functions by Richard Nolde not found in tiffcp */ static void initImageData (struct image_data *); static void initCropMasks (struct crop_mask *); static void initPageSetup (struct pagedef *, struct pageseg *, struct buffinfo []); static void initDumpOptions(struct dump_opts *); /* Command line and file naming functions */ void process_command_opts (int, char *[], char *, char *, uint32 *, uint16 *, uint16 *, uint32 *, uint32 *, uint32 *, struct crop_mask *, struct pagedef *, struct dump_opts *, unsigned int *, unsigned int *); static int update_output_file (TIFF **, char *, int, char *, unsigned int *); /* * High level functions for whole image manipulation */ static int get_page_geometry (char *, struct pagedef*); static int computeInputPixelOffsets(struct crop_mask *, struct image_data *, struct offset *); static int computeOutputPixelOffsets (struct crop_mask *, struct image_data *, struct pagedef *, struct pageseg *, struct dump_opts *); static int loadImage(TIFF *, struct image_data *, struct dump_opts *, unsigned char **); static int correct_orientation(struct image_data *, unsigned char **); static int getCropOffsets(struct image_data *, struct crop_mask *, struct dump_opts *); static int processCropSelections(struct image_data *, struct crop_mask *, unsigned char **, struct buffinfo []); static int writeSelections(TIFF *, TIFF **, struct crop_mask *, struct image_data *, struct dump_opts *, struct buffinfo [], char *, char *, unsigned int*, unsigned int); /* Section functions */ static int createImageSection(uint32, unsigned char **); static int extractImageSection(struct image_data *, struct pageseg *, unsigned char *, unsigned char *); static int writeSingleSection(TIFF *, TIFF *, struct image_data *, struct dump_opts *, uint32, uint32, double, double, unsigned char *); static int writeImageSections(TIFF *, TIFF *, struct image_data *, struct pagedef *, struct pageseg *, struct dump_opts *, unsigned char *, unsigned char **); /* Whole image functions */ static int createCroppedImage(struct image_data *, struct crop_mask *, unsigned char **, unsigned char **); static int writeCroppedImage(TIFF *, TIFF *, struct image_data *image, struct dump_opts * dump, uint32, uint32, unsigned char *, int, int); /* Image manipulation functions */ static int rotateContigSamples8bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateContigSamples16bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateContigSamples24bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateContigSamples32bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateImage(uint16, struct image_data *, uint32 *, uint32 *, unsigned char **); static int mirrorImage(uint16, uint16, uint16, uint32, uint32, unsigned char *); static int invertImage(uint16, uint16, uint16, uint32, uint32, unsigned char *); /* Functions to reverse the sequence of samples in a scanline */ static int reverseSamples8bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamples16bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamples24bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamples32bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamplesBytes (uint16, uint16, uint32, uint8 *, uint8 *); /* Functions for manipulating individual samples in an image */ static int extractSeparateRegion(struct image_data *, struct crop_mask *, unsigned char *, unsigned char *, int); static int extractCompositeRegions(struct image_data *, struct crop_mask *, unsigned char *, unsigned char *); static int extractContigSamples8bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamples16bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamples24bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamples32bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamplesBytes (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamplesShifted8bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesShifted16bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesShifted24bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesShifted32bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); /* Functions to combine separate planes into interleaved planes */ static int combineSeparateSamples8bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamples16bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamples24bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamples32bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamplesBytes (unsigned char *[], unsigned char *, uint32, uint32, tsample_t, uint16, FILE *, int, int); /* Dump functions for debugging */ static void dump_info (FILE *, int, char *, char *, ...); static int dump_data (FILE *, int, char *, unsigned char *, uint32); static int dump_byte (FILE *, int, char *, unsigned char); static int dump_short (FILE *, int, char *, uint16); static int dump_long (FILE *, int, char *, uint32); static int dump_wide (FILE *, int, char *, uint64); static int dump_buffer (FILE *, int, uint32, uint32, uint32, unsigned char *); /* End function declarations */ /* Functions derived in whole or in part from tiffcp */ /* The following functions are taken largely intact from tiffcp */ static char tiffcrop_version_id[] = "2.0"; static char tiffcrop_rev_date[] = "01-06-2009"; static char* stuff[] = { "usage: tiffcrop [options] source1 ... sourceN destination", "where options are:", " -h Print this syntax listing", " -v Print tiffcrop version identifier and last revision date", " ", " -a Append to output instead of overwriting", " -d offset Set initial directory offset, counting first image as one, not zero", " -p contig Pack samples contiguously (e.g. RGBRGB...)", " -p separate Store samples separately (e.g. RRR...GGG...BBB...)", " -s Write output in strips", " -t Write output in tiles", " -i Ignore read errors", " ", " -r # Make each strip have no more than # rows", " -w # Set output tile width (pixels)", " -l # Set output tile length (pixels)", " ", " -f lsb2msb Force lsb-to-msb FillOrder for output", " -f msb2lsb Force msb-to-lsb FillOrder for output", "", " -c lzw[:opts] Compress output with Lempel-Ziv & Welch encoding", " -c zip[:opts] Compress output with deflate encoding", " -c jpeg[:opts] compress output with JPEG encoding", " -c packbits Compress output with packbits encoding", " -c g3[:opts] Compress output with CCITT Group 3 encoding", " -c g4 Compress output with CCITT Group 4 encoding", " -c none Use no compression algorithm on output", " ", "Group 3 options:", " 1d Use default CCITT Group 3 1D-encoding", " 2d Use optional CCITT Group 3 2D-encoding", " fill Byte-align EOL codes", "For example, -c g3:2d:fill to get G3-2D-encoded data with byte-aligned EOLs", " ", "JPEG options:", " # Set compression quality level (0-100, default 75)", " r Output color image as RGB rather than YCbCr", "For example, -c jpeg:r:50 to get JPEG-encoded RGB data with 50% comp. quality", " ", "LZW and deflate options:", " # Set predictor value", "For example, -c lzw:2 to get LZW-encoded data with horizontal differencing", " ", "Page and selection options:", " -N odd|even|#,#-#,#|last sequences and ranges of images within file to process", " The words odd or even may be used to specify all odd or even numbered images.", " The word last may be used in place of a number in the sequence to indicate.", " The final image in the file without knowing how many images there are.", " Numbers are counted from one even though TIFF IFDs are counted from zero.", " ", " -E t|l|r|b edge to use as origin for width and length of crop region", " -U units [in, cm, px ] inches, centimeters or pixels", " ", " -m #,#,#,# margins from edges for selection: top, left, bottom, right separated by commas", " -X # horizontal dimension of region to extract expressed in current units", " -Y # vertical dimension of region to extract expressed in current units", " -Z #:#,#:# zones of the image designated as position X of Y,", " eg 1:3 would be first of three equal portions measured from reference edge", " -z x1,y1,x2,y2:...:xN,yN,xN+1,yN+1", " regions of the image designated by upper left and lower right coordinates", "", "Export grouping options:", " -e c|d|i|m|s export mode for images and selections from input images.", " When exporting a composite image from multiple zones or regions", " (combined and image modes), the selections must have equal sizes", " for the axis perpendicular to the edge specified with -E.", " c|combined All images and selections are written to a single file (default).", " with multiple selections from one image combined into a single image.", " d|divided All images and selections are written to a single file", " with each selection from one image written to a new image.", " i|image Each input image is written to a new file (numeric filename sequence)", " with multiple selections from the image combined into one image.", " m|multiple Each input image is written to a new file (numeric filename sequence)", " with each selection from the image written to a new image.", " s|separated Individual selections from each image are written to separate files.", "", "Output options:", " -H # Set horizontal resolution of output images to #", " -V # Set vertical resolution of output images to #", " -J # Set horizontal margin of output page to # expressed in current units", " -K # Set verticalal margin of output page to # expressed in current units", " ", " -O orient orientation for output image, portrait, landscape, auto", " -P page page size for output image segments, eg letter, legal, tabloid, etc", " -S cols:rows Divide the image into equal sized segments using cols across and rows down.", " ", " -F hor|vert|both", " flip (mirror) image or region horizontally, vertically, or both", " -R # [90,180,or 270] degrees clockwise rotation of image or extracted region", " -I [black|white|data|both]", " invert color space, eg dark to light for bilevel and grayscale images", " If argument is white or black, set the PHOTOMETRIC_INTERPRETATION ", " tag to MinIsBlack or MinIsWhite without altering the image data", " If the argument is data or both, the image data are modified:", " both inverts the data and the PHOTOMETRIC_INTERPRETATION tag,", " data inverts the data but not the PHOTOMETRIC_INTERPRETATION tag", " ", "-D opt1:value1,opt2:value2,opt3:value3:opt4:value4", " Debug/dump program progress and/or data to non-TIFF files.", " Options include the following and must be joined as a comma", " separate list. The use of this option is generally limited to", " program debugging and development of future options.", " ", " debug:N Display limited program progress indicators where larger N", " increase the level of detail. The program must be compiled with", " -DDEBUG -DDEBUG2 to enable full debug reporting", "", " format:txt|raw Format any logged data as ASCII text or raw binary ", " values. ASCII text dumps include strings of ones and zeroes", " representing the binary values in the image data plus identifying headers.", " ", " level:N Specify the level of detail presented in the dump files.", " This can vary from dumps of the entire input or output image data to dumps", " of data processed by specific functions. Current range of levels is 1 to 3.", " ", " input:full-path-to-directory/input-dumpname", " ", " output:full-path-to-directory/output-dumpnaem", " ", " When dump files are being written, each image will be written to a separate", " file with the name built by adding a numeric sequence value to the dumpname", " and an extension of .txt for ASCII dumps or .bin for binary dumps.", " ", " The four debug/dump options are independent, though it makes little sense to", " specify a dump file without specifying a detail level.", " ", NULL }; static int readContigTilesIntoBuffer (TIFF* in, uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp) { int status = 1; tdata_t tilebuf = _TIFFmalloc(TIFFTileSize(in)); uint32 imagew = TIFFScanlineSize(in); uint32 tilew = TIFFTileRowSize(in); int iskew = imagew - tilew; uint8* bufp = (uint8*) buf; uint32 tw, tl; uint32 row; (void) spp; if (tilebuf == 0) return 0; (void) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); (void) TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); for (row = 0; row < imagelength; row += tl) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { if (TIFFReadTile(in, tilebuf, col, row, 0, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile at %lu %lu", (unsigned long) col, (unsigned long) row); status = 0; goto done; } if (colb + tilew > imagew) { uint32 width = imagew - colb; uint32 oskew = tilew - width; cpStripToTile(bufp + colb, tilebuf, nrow, width, oskew + iskew, oskew ); } else cpStripToTile(bufp + colb, tilebuf, nrow, tilew, iskew, 0); colb += tilew; } bufp += imagew * nrow; } done: _TIFFfree(tilebuf); return status; } static int readSeparateTilesIntoBuffer (TIFF* in, uint8 *buf, uint32 imagelength, uint32 imagewidth, uint16 spp) { int status = 1; uint32 imagew = TIFFRasterScanlineSize(in); uint32 tilew = TIFFTileRowSize(in); int iskew = imagew - tilew*spp; tdata_t tilebuf = _TIFFmalloc(TIFFTileSize(in)); uint8* bufp = (uint8*) buf; uint32 tw, tl; uint32 row; uint16 bps, bytes_per_sample; if (tilebuf == 0) return 0; (void) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); (void) TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); (void) TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps); assert( bps % 8 == 0 ); bytes_per_sample = bps/8; for (row = 0; row < imagelength; row += tl) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { tsample_t s; for (s = 0; s < spp; s++) { if (TIFFReadTile(in, tilebuf, col, row, 0, s) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile at %lu %lu, " "sample %lu", (unsigned long) col, (unsigned long) row, (unsigned long) s); status = 0; goto done; } /* * Tile is clipped horizontally. Calculate * visible portion and skewing factors. */ if (colb + tilew*spp > imagew) { uint32 width = imagew - colb; int oskew = tilew*spp - width; cpSeparateBufToContigBuf( bufp+colb+s*bytes_per_sample, tilebuf, nrow, width/(spp*bytes_per_sample), oskew + iskew, oskew/spp, spp, bytes_per_sample); } else cpSeparateBufToContigBuf( bufp+colb+s*bytes_per_sample, tilebuf, nrow, tw, iskew, 0, spp, bytes_per_sample); } colb += tilew*spp; } bufp += imagew * nrow; } done: _TIFFfree(tilebuf); return status; } static int writeBufferToContigStrips(TIFF* out, uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp) { uint32 row, rowsperstrip; tstrip_t strip = 0; (void) imagewidth; (void) spp; (void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); for (row = 0; row < imagelength; row += rowsperstrip) { uint32 nrows = (row+rowsperstrip > imagelength) ? imagelength-row : rowsperstrip; tsize_t stripsize = TIFFVStripSize(out, nrows); if (TIFFWriteEncodedStrip(out, strip++, buf, stripsize) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1); return 0; } buf += stripsize; } return 1; } /* Function modified from original tiffcp version with plans to * extend so that plannar orientation separate images do not have * all samples for each channel written before all sampels for the * next channel. Current code is very similar in design to original. */ static int writeBufferToSeparateStrips (TIFF* out, uint8* buf, uint32 length, uint32 width, uint16 spp, struct dump_opts *dump) { uint8 *src; uint16 bps; uint32 row, nrows, rowsize, rowsperstrip; uint32 bytes_per_sample; tsample_t s; tstrip_t strip = 0; tsize_t stripsize = TIFFStripSize(out); tsize_t rowstripsize, scanlinesize = TIFFScanlineSize(out); tsize_t total_bytes = 0; tdata_t obuf; (void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); (void) TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps); bytes_per_sample = (bps + 7) / 8; rowsize = ((bps * spp * width) + 7) / 8; rowstripsize = rowsperstrip * bytes_per_sample * (width + 1); obuf = _TIFFmalloc (rowstripsize); if (obuf == NULL) return (0); for (s = 0; s < spp; s++) { for (row = 0; row < length; row += rowsperstrip) { nrows = (row + rowsperstrip > length) ? length - row : rowsperstrip; stripsize = TIFFVStripSize(out, nrows); src = buf + (row * rowsize); total_bytes += stripsize; memset (obuf, '\0', rowstripsize); if (extractContigSamplesToBuffer(obuf, src, nrows, width, 0, 0, s, spp, bps, dump)) { _TIFFfree(obuf); return (0); } if ((dump->outfile != NULL) && (dump->level == 1)) { dump_info(dump->outfile, dump->format,"", "Sample %2d, Strip: %2d, bytes: %4d, Row %4d, bytes: %4d, Input offset: %6d", s + 1, strip + 1, stripsize, row + 1, scanlinesize, src - buf); dump_buffer(dump->outfile, dump->format, nrows, scanlinesize, row, obuf); } if (TIFFWriteEncodedStrip(out, strip++, obuf, stripsize) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1); _TIFFfree(obuf); return 0; } } } /* Abandoning this code for now. Would be nice to be able to write * one or more rows of each color to successive strips, rather than * all the rows of a given color before any rows of the next color. tsize_t row_buffsize; row_buffsize = scanlinesize + (((spp + bps) + 7) / 8); obuf = _TIFFmalloc (row_buffsize); if (obuf == NULL) return (0); TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip); for (row = 0; row < length; row++) { src = buf + (row * rowsize); total_bytes += scanlinesize; for (s = 0; s < spp; s++) { memset (obuf, '\0', row_buffsize); if (extractContigSamplesToBuffer(obuf, src, 1, width, 0, 0, s, spp, bps, dump)) { _TIFFfree(obuf); return (0); } if ((dump->outfile != NULL) && (dump->level == 1)) { dump_info(dump->outfile, dump->format,"", "Row %4d, Sample %2d, bytes: %4d, Input offset: %6d", row + 1, s + 1, scanlinesize, src - buf); dump_buffer(dump->outfile, dump->format, nrows, scanlinesize, row, obuf); } if (TIFFWriteScanline(out, obuf, row, s) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", row + 1); _TIFFfree(obuf); return 0; } } } */ _TIFFfree(obuf); return 1; } static int writeBufferToContigTiles (TIFF* out, uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp) { uint32 imagew = TIFFScanlineSize(out); uint32 tilew = TIFFTileRowSize(out); int iskew = imagew - tilew; tdata_t obuf = _TIFFmalloc(TIFFTileSize(out)); uint8* bufp = (uint8*) buf; uint32 tl, tw; uint32 row; (void) spp; if (obuf == NULL) return 0; (void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl); (void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw); for (row = 0; row < imagelength; row += tilelength) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { /* * Tile is clipped horizontally. Calculate * visible portion and skewing factors. */ if (colb + tilew > imagew) { uint32 width = imagew - colb; int oskew = tilew - width; cpStripToTile(obuf, bufp + colb, nrow, width, oskew, oskew + iskew); } else cpStripToTile(obuf, bufp + colb, nrow, tilew, 0, iskew); if (TIFFWriteTile(out, obuf, col, row, 0, 0) < 0) { TIFFError(TIFFFileName(out), "Error, can't write tile at %lu %lu", (unsigned long) col, (unsigned long) row); _TIFFfree(obuf); return 0; } colb += tilew; } bufp += nrow * imagew; } _TIFFfree(obuf); return 1; } static int writeBufferToSeparateTiles (TIFF* out, uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp, struct dump_opts * dump) { uint32 imagew = TIFFScanlineSize(out); tsize_t tilew = TIFFTileRowSize(out); uint32 iimagew = TIFFRasterScanlineSize(out); int iskew = iimagew - tilew*spp; tdata_t obuf = _TIFFmalloc(TIFFTileSize(out)); uint8* bufp = (uint8*) buf; uint32 tl, tw; uint32 row; uint16 bps, bytes_per_sample; if (obuf == NULL) return 0; (void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl); (void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw); (void) TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps); assert( bps % 8 == 0 ); bytes_per_sample = (bps + 7)/8; for (row = 0; row < imagelength; row += tl) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { tsample_t s; for (s = 0; s < spp; s++) { /* * Tile is clipped horizontally. Calculate * visible portion and skewing factors. */ if (colb + tilew > imagew) { uint32 width = (imagew - colb); int oskew = tilew - width; extractContigSamplesToBuffer(obuf, bufp + (colb*spp) + s, nrow, width/bytes_per_sample, oskew, (oskew*spp)+iskew, s, spp, bps, dump); } else extractContigSamplesToBuffer(obuf, bufp + (colb*spp) + s, nrow, tilewidth, 0, iskew, s, spp, bps, dump); if (TIFFWriteTile(out, obuf, col, row, 0, s) < 0) { TIFFError(TIFFFileName(out), "Error, can't write tile at %lu %lu " "sample %lu", (unsigned long) col, (unsigned long) row, (unsigned long) s); _TIFFfree(obuf); return 0; } } colb += tilew; } bufp += nrow * iimagew; } _TIFFfree(obuf); return 1; } static void processG3Options(char* cp) { if( (cp = strchr(cp, ':')) ) { if (defg3opts == (uint32) -1) defg3opts = 0; do { cp++; if (strneq(cp, "1d", 2)) defg3opts &= ~GROUP3OPT_2DENCODING; else if (strneq(cp, "2d", 2)) defg3opts |= GROUP3OPT_2DENCODING; else if (strneq(cp, "fill", 4)) defg3opts |= GROUP3OPT_FILLBITS; else usage(); } while( (cp = strchr(cp, ':')) ); } } static int processCompressOptions(char* opt) { if (streq(opt, "none")) { defcompression = COMPRESSION_NONE; } else if (streq(opt, "packbits")) { defcompression = COMPRESSION_PACKBITS; } else if (strneq(opt, "jpeg", 4)) { char* cp = strchr(opt, ':'); defcompression = COMPRESSION_JPEG; while( cp ) { if (isdigit((int)cp[1])) quality = atoi(cp+1); else if (cp[1] == 'r' ) jpegcolormode = JPEGCOLORMODE_RAW; else usage(); cp = strchr(cp+1,':'); } } else if (strneq(opt, "g3", 2)) { processG3Options(opt); defcompression = COMPRESSION_CCITTFAX3; } else if (streq(opt, "g4")) { defcompression = COMPRESSION_CCITTFAX4; } else if (strneq(opt, "lzw", 3)) { char* cp = strchr(opt, ':'); if (cp) defpredictor = atoi(cp+1); defcompression = COMPRESSION_LZW; } else if (strneq(opt, "zip", 3)) { char* cp = strchr(opt, ':'); if (cp) defpredictor = atoi(cp+1); defcompression = COMPRESSION_ADOBE_DEFLATE; } else return (0); return (1); } static void usage(void) { char buf[BUFSIZ]; int i; setbuf(stderr, buf); fprintf(stderr, "\n%s\n", TIFFGetVersion()); for (i = 0; stuff[i] != NULL; i++) fprintf(stderr, "%s\n", stuff[i]); exit(-1); } #define CopyField(tag, v) \ if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v) #define CopyField2(tag, v1, v2) \ if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2) #define CopyField3(tag, v1, v2, v3) \ if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3) #define CopyField4(tag, v1, v2, v3, v4) \ if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4) static void cpTag(TIFF* in, TIFF* out, uint16 tag, uint16 count, TIFFDataType type) { switch (type) { case TIFF_SHORT: if (count == 1) { uint16 shortv; CopyField(tag, shortv); } else if (count == 2) { uint16 shortv1, shortv2; CopyField2(tag, shortv1, shortv2); } else if (count == 4) { uint16 *tr, *tg, *tb, *ta; CopyField4(tag, tr, tg, tb, ta); } else if (count == (uint16) -1) { uint16 shortv1; uint16* shortav; CopyField2(tag, shortv1, shortav); } break; case TIFF_LONG: { uint32 longv; CopyField(tag, longv); } break; case TIFF_RATIONAL: if (count == 1) { float floatv; CopyField(tag, floatv); } else if (count == (uint16) -1) { float* floatav; CopyField(tag, floatav); } break; case TIFF_ASCII: { char* stringv; CopyField(tag, stringv); } break; case TIFF_DOUBLE: if (count == 1) { double doublev; CopyField(tag, doublev); } else if (count == (uint16) -1) { double* doubleav; CopyField(tag, doubleav); } break; default: TIFFError(TIFFFileName(in), "Data type %d is not supported, tag %d skipped.", tag, type); } } static struct cpTag { uint16 tag; uint16 count; TIFFDataType type; } tags[] = { { TIFFTAG_SUBFILETYPE, 1, TIFF_LONG }, { TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT }, { TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII }, { TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII }, { TIFFTAG_MAKE, 1, TIFF_ASCII }, { TIFFTAG_MODEL, 1, TIFF_ASCII }, { TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT }, { TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT }, { TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL }, { TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL }, { TIFFTAG_PAGENAME, 1, TIFF_ASCII }, { TIFFTAG_XPOSITION, 1, TIFF_RATIONAL }, { TIFFTAG_YPOSITION, 1, TIFF_RATIONAL }, { TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT }, { TIFFTAG_SOFTWARE, 1, TIFF_ASCII }, { TIFFTAG_DATETIME, 1, TIFF_ASCII }, { TIFFTAG_ARTIST, 1, TIFF_ASCII }, { TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII }, { TIFFTAG_WHITEPOINT, (uint16) -1, TIFF_RATIONAL }, { TIFFTAG_PRIMARYCHROMATICITIES,(uint16) -1,TIFF_RATIONAL }, { TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT }, { TIFFTAG_INKSET, 1, TIFF_SHORT }, { TIFFTAG_DOTRANGE, 2, TIFF_SHORT }, { TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII }, { TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT }, { TIFFTAG_YCBCRCOEFFICIENTS, (uint16) -1,TIFF_RATIONAL }, { TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT }, { TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT }, { TIFFTAG_REFERENCEBLACKWHITE, (uint16) -1,TIFF_RATIONAL }, { TIFFTAG_EXTRASAMPLES, (uint16) -1, TIFF_SHORT }, { TIFFTAG_SMINSAMPLEVALUE, 1, TIFF_DOUBLE }, { TIFFTAG_SMAXSAMPLEVALUE, 1, TIFF_DOUBLE }, { TIFFTAG_STONITS, 1, TIFF_DOUBLE }, }; #define NTAGS (sizeof (tags) / sizeof (tags[0])) #define CopyTag(tag, count, type) cpTag(in, out, tag, count, type) static void cpStripToTile(uint8* out, uint8* in, uint32 rows, uint32 cols, int outskew, int inskew) { while (rows-- > 0) { uint32 j = cols; while (j-- > 0) *out++ = *in++; out += outskew; in += inskew; } } /* Fucntions written by Richard Nolde, with exceptions noted. */ void process_command_opts (int argc, char *argv[], char *mp, char *mode, uint32 *dirnum, uint16 *defconfig, uint16 *deffillorder, uint32 *deftilewidth, uint32 *deftilelength, uint32 *defrowsperstrip, struct crop_mask *crop_data, struct pagedef *page, struct dump_opts *dump, unsigned int *imagelist, unsigned int *image_count ) { int c, good_args = 0; char *opt_offset = NULL; /* Position in string of value sought */ char *opt_ptr = NULL; /* Pointer to next token in option set */ char *sep = NULL; /* Pointer to a token separator */ unsigned int i, j, start, end; extern int optind; extern char* optarg; *mp++ = 'w'; *mp = '\0'; while ((c = getopt(argc, argv, "ac:d:e:f:hil:m:p:r:stvw:z:BCD:E:F:H:I:J:K:LMN:O:P:R:S:U:V:X:Y:Z:")) != -1) { good_args++; switch (c) { case 'a': mode[0] = 'a'; /* append to output */ break; case 'c': if (!processCompressOptions(optarg)) /* compression scheme */ { TIFFError ("Unknown compression option", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'd': start = strtoul(optarg, NULL, 0); /* initial IFD offset */ if (start == 0) { TIFFError ("","Directory offset must be greater than zero"); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } *dirnum = start - 1; break; case 'e': switch (tolower(optarg[0])) /* image export modes*/ { case 'c': crop_data->exp_mode = ONE_FILE_COMPOSITE; crop_data->img_mode = COMPOSITE_IMAGES; break; /* Composite */ case 'd': crop_data->exp_mode = ONE_FILE_SEPARATED; crop_data->img_mode = SEPARATED_IMAGES; break; /* Divided */ case 'i': crop_data->exp_mode = FILE_PER_IMAGE_COMPOSITE; crop_data->img_mode = COMPOSITE_IMAGES; break; /* Image */ case 'm': crop_data->exp_mode = FILE_PER_IMAGE_SEPARATED; crop_data->img_mode = SEPARATED_IMAGES; break; /* Multiple */ case 's': crop_data->exp_mode = FILE_PER_SELECTION; crop_data->img_mode = SEPARATED_IMAGES; break; /* Sections */ default: TIFFError ("Unknown export mode","%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'f': if (streq(optarg, "lsb2msb")) /* fill order */ *deffillorder = FILLORDER_LSB2MSB; else if (streq(optarg, "msb2lsb")) *deffillorder = FILLORDER_MSB2LSB; else { TIFFError ("Unknown fill order", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'h': usage(); break; case 'i': ignore = TRUE; /* ignore errors */ break; case 'l': outtiled = TRUE; /* tile length */ *deftilelength = atoi(optarg); break; case 'p': /* planar configuration */ if (streq(optarg, "separate")) *defconfig = PLANARCONFIG_SEPARATE; else if (streq(optarg, "contig")) *defconfig = PLANARCONFIG_CONTIG; else { TIFFError ("Unkown planar configuration", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'r': /* rows/strip */ *defrowsperstrip = atol(optarg); break; case 's': /* generate stripped output */ outtiled = FALSE; break; case 't': /* generate tiled output */ outtiled = TRUE; break; case 'v': TIFFError ("Tiffcrop version", "%s, last updated: %s", tiffcrop_version_id, tiffcrop_rev_date); TIFFError ("Tiffcp code", "Copyright (c) 1988-1997 Sam Leffler"); TIFFError (" ", "Copyright (c) 1991-1997 Silicon Graphics, Inc"); TIFFError ("Tiffcrop additions", "Copyright (c) 2007-2009 Richard Nolde"); exit (0); break; case 'w': /* tile width */ outtiled = TRUE; *deftilewidth = atoi(optarg); break; case 'z': /* regions of an image specified as x1,y1,x2,y2:x3,y3,x4,y4 etc */ crop_data->crop_mode |= CROP_REGIONS; for (i = 0, opt_ptr = strtok (optarg, ":"); ((opt_ptr != NULL) && (i < MAX_REGIONS)); (opt_ptr = strtok (NULL, ":")), i++) { crop_data->regions++; if (sscanf(opt_ptr, "%lf,%lf,%lf,%lf", &crop_data->corners[i].X1, &crop_data->corners[i].Y1, &crop_data->corners[i].X2, &crop_data->corners[i].Y2) != 4) { TIFFError ("Unable to parse coordinates for region", "%d %s", i, optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } } /* check for remaining elements over MAX_REGIONS */ if ((opt_ptr != NULL) && (i >= MAX_REGIONS)) { TIFFError ("Region list exceeds limit of", "%d regions %s", MAX_REGIONS, optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1);; } break; /* options for file open modes */ case 'B': *mp++ = 'b'; *mp = '\0'; break; case 'L': *mp++ = 'l'; *mp = '\0'; break; case 'M': *mp++ = 'm'; *mp = '\0'; break; case 'C': *mp++ = 'c'; *mp = '\0'; break; /* options for Debugging / data dump */ case 'D': for (i = 0, opt_ptr = strtok (optarg, ","); (opt_ptr != NULL); (opt_ptr = strtok (NULL, ",")), i++) { opt_offset = strpbrk(opt_ptr, ":="); /* opt_offset = strchr(opt_ptr, ':'); */ if (opt_offset == NULL) { TIFFError("Invalid dump option", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } *opt_offset = '\0'; /* convert option to lowercase */ end = strlen (opt_ptr); for (i = 0; i < end; i++) *(opt_ptr + i) = tolower(*(opt_ptr + i)); /* Look for dump format specification */ if (strncmp(opt_ptr, "for", 3) == 0) { /* convert value to lowercase */ end = strlen (opt_offset + 1); for (i = 1; i <= end; i++) *(opt_offset + i) = tolower(*(opt_offset + i)); /* check dump format value */ if (strncmp (opt_offset + 1, "txt", 3) == 0) { dump->format = DUMP_TEXT; strcpy (dump->mode, "w"); } else { if (strncmp(opt_offset + 1, "raw", 3) == 0) { dump->format = DUMP_RAW; strcpy (dump->mode, "wb"); } else { TIFFError("parse_command_opts", "Unknown dump format %s", opt_offset + 1); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } } } else { /* Look for dump level specification */ if (strncmp (opt_ptr, "lev", 3) == 0) dump->level = atoi(opt_offset + 1); /* Look for input data dump file name */ if (strncmp (opt_ptr, "in", 2) == 0) strncpy (dump->infilename, opt_offset + 1, PATH_MAX - 20); /* Look for output data dump file name */ if (strncmp (opt_ptr, "out", 3) == 0) strncpy (dump->outfilename, opt_offset + 1, PATH_MAX - 20); if (strncmp (opt_ptr, "deb", 3) == 0) dump->debug = atoi(opt_offset + 1); } } if ((strlen(dump->infilename)) || (strlen(dump->outfilename))) { if (dump->level == 1) TIFFError("","Defaulting to dump level 1, no data."); if (dump->format == DUMP_NONE) { TIFFError("", "You must specify a dump format for dump files"); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } } break; /* image manipulation routine options */ case 'm': /* margins to exclude from selection, uppercase M was already used */ /* order of values must be TOP, LEFT, BOTTOM, RIGHT */ crop_data->crop_mode |= CROP_MARGINS; for (i = 0, opt_ptr = strtok (optarg, ",:"); ((opt_ptr != NULL) && (i < 4)); (opt_ptr = strtok (NULL, ",:")), i++) { crop_data->margins[i] = atof(opt_ptr); } break; case 'E': /* edge reference */ switch (tolower(optarg[0])) { case 't': crop_data->edge_ref = EDGE_TOP; break; case 'b': crop_data->edge_ref = EDGE_BOTTOM; break; case 'l': crop_data->edge_ref = EDGE_LEFT; break; case 'r': crop_data->edge_ref = EDGE_RIGHT; break; default: TIFFError ("Edge reference must be top, bottom, left, or right", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'F': /* flip eg mirror image or cropped segment, M was already used */ crop_data->crop_mode |= CROP_MIRROR; switch (tolower(optarg[0])) { case 'h': crop_data->mirror = MIRROR_HORIZ; break; case 'v': crop_data->mirror = MIRROR_VERT; break; case 'b': crop_data->mirror = MIRROR_BOTH; break; default: TIFFError ("Flip mode must be horiz, vert, or both", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'H': /* set horizontal resolution to new value */ page->hres = atof (optarg); page->mode |= PAGE_MODE_RESOLUTION; break; case 'I': /* invert the color space, eg black to white */ crop_data->crop_mode |= CROP_INVERT; /* The PHOTOMETIC_INTERPRETATION tag may be updated */ if (streq(optarg, "black")) { crop_data->photometric = PHOTOMETRIC_MINISBLACK; continue; } if (streq(optarg, "white")) { crop_data->photometric = PHOTOMETRIC_MINISWHITE; continue; } if (streq(optarg, "data")) { crop_data->photometric = INVERT_DATA_ONLY; continue; } if (streq(optarg, "both")) { crop_data->photometric = INVERT_DATA_AND_TAG; continue; } TIFFError("Missing or unknown option for inverting PHOTOMETRIC_INTERPRETATION", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); break; case 'J': /* horizontal margin for sectioned ouput pages */ page->hmargin = atof(optarg); page->mode |= PAGE_MODE_MARGINS; break; case 'K': /* vertical margin for sectioned ouput pages*/ page->vmargin = atof(optarg); page->mode |= PAGE_MODE_MARGINS; break; case 'N': /* list of images to process */ for (i = 0, opt_ptr = strtok (optarg, ","); ((opt_ptr != NULL) && (i < MAX_IMAGES)); (opt_ptr = strtok (NULL, ","))) { /* We do not know how many images are in file yet * so we build a list to include the maximum allowed * and follow it until we hit the end of the file. * Image count is not accurate for odd, even, last * so page numbers won't be valid either. */ if (streq(opt_ptr, "odd")) { for (j = 1; j <= MAX_IMAGES; j += 2) imagelist[i++] = j; *image_count = (MAX_IMAGES - 1) / 2; break; } else { if (streq(opt_ptr, "even")) { for (j = 2; j <= MAX_IMAGES; j += 2) imagelist[i++] = j; *image_count = MAX_IMAGES / 2; break; } else { if (streq(opt_ptr, "last")) imagelist[i++] = MAX_IMAGES; else /* single value between commas */ { sep = strpbrk(opt_ptr, ":-"); if (!sep) imagelist[i++] = atoi(opt_ptr) - 1; else { *sep = '\0'; start = atoi (opt_ptr); if (!strcmp((sep + 1), "last")) end = MAX_IMAGES; else end = atoi (sep + 1); for (j = start; j <= end && j - start + i < MAX_IMAGES; j++) imagelist[i++] = j - 1; } } } } } *image_count = i; break; case 'O': /* page orientation */ switch (tolower(optarg[0])) { case 'a': page->orient = ORIENTATION_AUTO; break; case 'p': page->orient = ORIENTATION_PORTRAIT; break; case 'l': page->orient = ORIENTATION_LANDSCAPE; break; default: TIFFError ("Orientation must be portrait, landscape, or auto.", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'P': /* page size selection */ if (get_page_geometry (optarg, page)) { if (!strcmp(optarg, "list")) { TIFFError("", "Name Width Length (in inches)"); for (i = 0; i < MAX_PAPERNAMES - 1; i++) TIFFError ("", "%-15.15s %5.2f %5.2f", PaperTable[i].name, PaperTable[i].width, PaperTable[i].length); exit (-1); } TIFFError ("Invalid paper size", "%s", optarg); TIFFError ("", "Select one of:"); TIFFError("", "Name Width Length (in inches)"); for (i = 0; i < MAX_PAPERNAMES - 1; i++) TIFFError ("", "%-15.15s %5.2f %5.2f", PaperTable[i].name, PaperTable[i].width, PaperTable[i].length); exit (-1); } else { page->mode |= PAGE_MODE_PAPERSIZE; } break; case 'R': /* rotate image or cropped segment */ crop_data->crop_mode |= CROP_ROTATE; switch (strtoul(optarg, NULL, 0)) { case 90: crop_data->rotation = (uint16)90; break; case 180: crop_data->rotation = (uint16)180; break; case 270: crop_data->rotation = (uint16)270; break; default: TIFFError ("Rotation must be 90, 180, or 270 degrees clockwise", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'S': /* subdivide into Cols:Rows sections, eg 3:2 would be 3 across and 2 down */ sep = strpbrk(optarg, ",:"); if (sep) { *sep = '\0'; page->cols = atoi(optarg); page->rows = atoi(sep +1); } else { page->cols = atoi(optarg); page->rows = atoi(optarg); } if ((page->cols * page->rows) > MAX_SECTIONS) { TIFFError ("Limit for subdivisions, ie rows x columns, exceeded", "%d", MAX_SECTIONS); exit (-1); } page->mode |= PAGE_MODE_ROWSCOLS; break; case 'U': /* units for measurements and offsets */ if (streq(optarg, "in")) { crop_data->res_unit = RESUNIT_INCH; page->res_unit = RESUNIT_INCH; } else if (streq(optarg, "cm")) { crop_data->res_unit = RESUNIT_CENTIMETER; page->res_unit = RESUNIT_CENTIMETER; } else if (streq(optarg, "px")) { crop_data->res_unit = RESUNIT_NONE; page->res_unit = RESUNIT_NONE; } else { TIFFError ("Illegal unit of measure","%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'V': /* set vertical resolution to new value */ page->vres = atof (optarg); page->mode |= PAGE_MODE_RESOLUTION; break; case 'X': /* selection width */ crop_data->crop_mode |= CROP_WIDTH; crop_data->width = atof(optarg); break; case 'Y': /* selection length */ crop_data->crop_mode |= CROP_LENGTH; crop_data->length = atof(optarg); break; case 'Z': /* zones of an image X:Y read as zone X of Y */ crop_data->crop_mode |= CROP_ZONES; for (i = 0, opt_ptr = strtok (optarg, ","); ((opt_ptr != NULL) && (i < MAX_REGIONS)); (opt_ptr = strtok (NULL, ",")), i++) { crop_data->zones++; opt_offset = strchr(opt_ptr, ':'); *opt_offset = '\0'; crop_data->zonelist[i].position = atoi(opt_ptr); crop_data->zonelist[i].total = atoi(opt_offset + 1); } /* check for remaining elements over MAX_REGIONS */ if ((opt_ptr != NULL) && (i >= MAX_REGIONS)) { TIFFError("Zone list exceeds region limit", "%d", MAX_REGIONS); exit (-1); } break; case '?': TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); /*NOTREACHED*/ } } } /* end process_command_opts */ /* Start a new output file if one has not been previously opened or * autoindex is set to non-zero. Update page and file counters * so TIFFTAG PAGENUM will be correct in image. */ static int update_output_file (TIFF **tiffout, char *mode, int autoindex, char *outname, unsigned int *page) { static int findex = 0; /* file sequence indicator */ char *sep; char filenum[16]; char export_ext[16]; char exportname[PATH_MAX]; strcpy (export_ext, ".tiff"); if (autoindex && (*tiffout != NULL)) { /* Close any export file that was previously opened */ TIFFClose (*tiffout); *tiffout = NULL; } strncpy (exportname, outname, PATH_MAX - 15); if (*tiffout == NULL) /* This is a new export file */ { if (autoindex) { /* create a new filename for each export */ findex++; if ((sep = strstr(exportname, ".tif")) || (sep = strstr(exportname, ".TIF"))) { strncpy (export_ext, sep, 5); *sep = '\0'; } else strncpy (export_ext, ".tiff", 5); export_ext[5] = '\0'; sprintf (filenum, "-%03d%s", findex, export_ext); filenum[15] = '\0'; strncat (exportname, filenum, 14); } *tiffout = TIFFOpen(exportname, mode); if (*tiffout == NULL) { TIFFError("update_output_file", "Unable to open output file %s\n", exportname); return (1); } *page = 0; return (0); } else (*page)++; return (0); } /* end update_output_file */ int main(int argc, char* argv[]) { uint16 defconfig = (uint16) -1; uint16 deffillorder = 0; uint32 deftilewidth = (uint32) -1; uint32 deftilelength = (uint32) -1; uint32 defrowsperstrip = (uint32) 0; uint32 dirnum = 0; extern int optind; TIFF *in = NULL; TIFF *out = NULL; char mode[10]; char *mp = mode; /** RJN additions **/ struct image_data image; /* Image parameters for one image */ struct crop_mask crop; /* Cropping parameters for all images */ struct pagedef page; /* Page definition for output pages */ struct pageseg sections[MAX_SECTIONS]; /* Sections of one output page */ struct buffinfo seg_buffs[MAX_SECTIONS]; /* Segment buffer sizes and pointers */ struct dump_opts dump; /* Data dump options */ unsigned char *read_buff = NULL; /* Input image data buffer */ unsigned char *crop_buff = NULL; /* Crop area buffer */ unsigned char *sect_buff = NULL; /* Image section buffer */ unsigned char *sect_src = NULL; /* Image section buffer pointer */ unsigned int imagelist[MAX_IMAGES + 1]; /* individually specified images */ unsigned int image_count = 0; unsigned int dump_images = 0; unsigned int next_image = 0; unsigned int next_page = 0; unsigned int total_pages = 0; unsigned int total_images = 0; unsigned int end_of_input = FALSE; int seg, length; char temp_filename[PATH_MAX + 1]; memset (temp_filename, '\0', PATH_MAX + 1); little_endian = *((unsigned char *)&little_endian) & '1'; initImageData(&image); initCropMasks(&crop); initPageSetup(&page, sections, seg_buffs); initDumpOptions(&dump); process_command_opts (argc, argv, mp, mode, &dirnum, &defconfig, &deffillorder, &deftilewidth, &deftilelength, &defrowsperstrip, &crop, &page, &dump, imagelist, &image_count); if (argc - optind < 2) usage(); if ((argc - optind) == 2) pageNum = -1; else total_images = 0; /* read multiple input files and write to output file(s) */ while (optind < argc - 1) { in = TIFFOpen (argv[optind], "r"); if (in == NULL) return (-3); /* If only one input file is specified, we can use directory count */ total_images = TIFFNumberOfDirectories(in); if (image_count == 0) { dirnum = 0; total_pages = total_images; /* Only valid with single input file */ } else { dirnum = (tdir_t)(imagelist[next_image] - 1); next_image++; /* Total pages only valid for enumerated list of pages not derived * using odd, even, or last keywords. */ if (image_count > total_images) image_count = total_images; total_pages = image_count; } /* MAX_IMAGES is used for special case "last" in selection list */ if (dirnum == (MAX_IMAGES - 1)) dirnum = total_images - 1; if (dirnum > (total_images)) { TIFFError (TIFFFileName(in), "Invalid image number %d, File contains only %d images", (int)dirnum + 1, total_images); if (out != NULL) (void) TIFFClose(out); return (1); } if (dirnum != 0 && !TIFFSetDirectory(in, (tdir_t)dirnum)) { TIFFError(TIFFFileName(in),"Error, setting subdirectory at %d", dirnum); if (out != NULL) (void) TIFFClose(out); return (1); } end_of_input = FALSE; while (end_of_input == FALSE) { config = defconfig; compression = defcompression; predictor = defpredictor; fillorder = deffillorder; rowsperstrip = defrowsperstrip; tilewidth = deftilewidth; tilelength = deftilelength; g3opts = defg3opts; if (dump.format != DUMP_NONE) { /* manage input and/or output dump files here */ dump_images++; length = strlen(dump.infilename); if (length > 0) { if (dump.infile != NULL) fclose (dump.infile); sprintf (temp_filename, "%s-read-%03d.%s", dump.infilename, dump_images, (dump.format == DUMP_TEXT) ? "txt" : "raw"); if ((dump.infile = fopen(temp_filename, dump.mode)) == NULL) { TIFFError ("Unable to open dump file %s for writing", temp_filename); exit (-1); } dump_info(dump.infile, dump.format, "Reading image","%d from %s", dump_images, TIFFFileName(in)); } length = strlen(dump.outfilename); if (length > 0) { if (dump.outfile != NULL) fclose (dump.outfile); sprintf (temp_filename, "%s-write-%03d.%s", dump.outfilename, dump_images, (dump.format == DUMP_TEXT) ? "txt" : "raw"); if ((dump.outfile = fopen(temp_filename, dump.mode)) == NULL) { TIFFError ("Unable to open dump file %s for writing", temp_filename); exit (-1); } dump_info(dump.outfile, dump.format, "Writing image","%d from %s", dump_images, TIFFFileName(in)); } } if (dump.debug) TIFFError("main", "Reading image %4d of %4d total pages.", dirnum + 1, total_pages); if (loadImage(in, &image, &dump, &read_buff)) { TIFFError("main", "Unable to load source image"); exit (-1); } /* Correct the image orientation if it was not ORIENTATION_TOPLEFT. */ if (image.adjustments != 0) { if (correct_orientation(&image, &read_buff)) TIFFError("main", "Unable to correct image orientation"); } if (getCropOffsets(&image, &crop, &dump)) { TIFFError("main", "Unable to define crop regions"); exit (-1); } if (crop.selections > 0) { if (processCropSelections(&image, &crop, &read_buff, seg_buffs)) { TIFFError("main", "Unable to process image selections"); exit (-1); } } else /* Single image segment without zones or regions */ { if (createCroppedImage(&image, &crop, &read_buff, &crop_buff)) { TIFFError("main", "Unable to create output image"); exit (-1); } } if (page.mode == PAGE_MODE_NONE) { /* Whole image or sections not based on output page size */ if (crop.selections > 0) { writeSelections(in, &out, &crop, &image, &dump, seg_buffs, mp, argv[argc - 1], &next_page, total_pages); } else /* One file all images and sections */ { if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1], &next_page)) exit (1); if (writeCroppedImage(in, out, &image, &dump,crop.combined_width, crop.combined_length, crop_buff, next_page, total_pages)) { TIFFError("main", "Unable to write new image"); exit (-1); } } } else { /* If we used a crop buffer, our data is there, otherwise it is * in the read_buffer */ if (crop_buff != NULL) sect_src = crop_buff; else sect_src = read_buff; /* Break input image into pages or rows and columns */ if (computeOutputPixelOffsets(&crop, &image, &page, sections, &dump)) { TIFFError("main", "Unable to compute output section data"); exit (-1); } /* If there are multiple files on the command line, the final one is assumed * to be the output filename into which the images are written. */ if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1], &next_page)) exit (1); if (writeImageSections(in, out, &image, &page, sections, &dump, sect_src, &sect_buff)) { TIFFError("main", "Unable to write image sections"); exit (-1); } } /* No image list specified, just read the next image */ if (image_count == 0) dirnum++; else { dirnum = (tdir_t)(imagelist[next_image] - 1); next_image++; } if (dirnum == MAX_IMAGES - 1) dirnum = TIFFNumberOfDirectories(in) - 1; if (!TIFFSetDirectory(in, (tdir_t)dirnum)) end_of_input = TRUE; } TIFFClose(in); optind++; } /* If we did not use the read buffer as the crop buffer */ if (read_buff) _TIFFfree(read_buff); if (crop_buff) _TIFFfree(crop_buff); if (sect_buff) _TIFFfree(sect_buff); /* Clean up any segment buffers used for zones or regions */ for (seg = 0; seg < crop.selections; seg++) _TIFFfree (seg_buffs[seg].buffer); if (dump.format != DUMP_NONE) { if (dump.infile != NULL) fclose (dump.infile); if (dump.outfile != NULL) { dump_info (dump.outfile, dump.format, "", "Completed run for %s", TIFFFileName(out)); fclose (dump.outfile); } } TIFFClose(out); return (0); } /* end main */ /* Debugging functions */ static int dump_data (FILE *dumpfile, int format, char *dump_tag, unsigned char *data, uint32 count) { int j, k; uint32 i; char dump_array[10]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file\n"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (i = 0; i < count; i++) { for (j = 0, k = 7; j < 8; j++, k--) { bitset = (*(data + i)) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); } dump_array[8] = '\0'; fprintf (dumpfile," %s", dump_array); } fprintf (dumpfile,"\n"); } else { if ((fwrite (data, 1, count, dumpfile)) != count) { TIFFError ("", "Unable to write binary data to dump file\n"); return (1); } } return (0); } static int dump_byte (FILE *dumpfile, int format, char *dump_tag, unsigned char data) { int j, k; char dump_array[10]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file\n"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 7; j < 8; j++, k--) { bitset = data & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); } dump_array[8] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 1, 1, dumpfile)) != 1) { TIFFError ("", "Unable to write binary data to dump file\n"); return (1); } } return (0); } static int dump_short (FILE *dumpfile, int format, char *dump_tag, uint16 data) { int j, k; char dump_array[20]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file\n"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 15; k >= 0; j++, k--) { bitset = data & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); if ((k % 8) == 0) sprintf(&dump_array[++j], " "); } dump_array[17] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 2, 1, dumpfile)) != 2) { TIFFError ("", "Unable to write binary data to dump file\n"); return (1); } } return (0); } static int dump_long (FILE *dumpfile, int format, char *dump_tag, uint32 data) { int j, k; char dump_array[40]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file\n"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 31; k >= 0; j++, k--) { bitset = data & (((uint32)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); if ((k % 8) == 0) sprintf(&dump_array[++j], " "); } dump_array[35] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 4, 1, dumpfile)) != 4) { TIFFError ("", "Unable to write binary data to dump file\n"); return (1); } } return (0); } static int dump_wide (FILE *dumpfile, int format, char *dump_tag, uint64 data) { int j, k; char dump_array[80]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file\n"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 63; k >= 0; j++, k--) { bitset = data & (((uint64)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); if ((k % 8) == 0) sprintf(&dump_array[++j], " "); } dump_array[71] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 8, 1, dumpfile)) != 8) { TIFFError ("", "Unable to write binary data to dump file\n"); return (1); } } return (0); } static void dump_info(FILE *dumpfile, int format, char *prefix, char *msg, ...) { if (format == DUMP_TEXT) { va_list ap; va_start(ap, msg); fprintf(dumpfile, "%s ", prefix); vfprintf(dumpfile, msg, ap); fprintf(dumpfile, "\n"); } } static int dump_buffer (FILE* dumpfile, int format, uint32 rows, uint32 width, uint32 row, unsigned char *buff) { int j, k; uint32 i; unsigned char * dump_ptr; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file\n"); return (1); } for (i = 0; i < rows; i++) { dump_ptr = buff + (i * width); if (format == DUMP_TEXT) dump_info (dumpfile, format, "", "Row %4d, %d bytes at offset %d", row + i + 1, width, row * width); for (j = 0, k = width; k >= 10; j += 10, k -= 10, dump_ptr += 10) dump_data (dumpfile, format, "", dump_ptr, 10); if (k > 0) dump_data (dumpfile, format, "", dump_ptr, k); } return (0); } /* Extract one or more samples from an interleaved buffer. If count == 1, * only the sample plane indicated by sample will be extracted. If count > 1, * count samples beginning at sample will be extracted. Portions of a * scanline can be extracted by specifying a start and end value. */ static int extractContigSamplesBytes (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int i, bytes_per_sample, sindex; uint32 col, dst_rowsize, bit_offset; uint32 src_byte, src_bit; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamplesBytes","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesBytes", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesBytes", "Invalid end column value %d ignored", end); end = cols; } dst_rowsize = (bps * (end - start) * count) / 8; bytes_per_sample = (bps + 7) / 8; /* Optimize case for copying all samples */ if (count == spp) { src = in + (start * spp * bytes_per_sample); _TIFFmemcpy (dst, src, dst_rowsize); } else { for (col = start; col < end; col++) { for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { bit_offset = col * bps * spp; if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; for (i = 0; i < bytes_per_sample; i++) *dst++ = *src++; } } } return (0); } /* end extractContigSamplesBytes */ static int extractContigSamples8bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamples8bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples8bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples8bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = 0; maskbits = (uint8)-1 >> ( 8 - bps); buff1 = buff2 = 0; for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (8 - src_bit - bps); buff1 = ((*src) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; } else buff2 = (buff2 | (buff1 >> ready_bits)); ready_bits += bps; } } while (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; ready_bits -= 8; } return (0); } /* end extractContigSamples8bits */ static int extractContigSamples16bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; uint8 *src = in; uint8 *dst = out; unsigned char swapbuff[2]; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamples16bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples16bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples16bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = 0; maskbits = (uint16)-1 >> (16 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (16 - src_bit - bps); if (little_endian) { swapbuff[1] = *src; swapbuff[0] = *(src + 1); } else { swapbuff[0] = *src; swapbuff[1] = *(src + 1); } buff1 = *((uint16 *)swapbuff); buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 8) /* add another bps bits to the buffer */ { bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; } return (0); } /* end extractContigSamples16bits */ static int extractContigSamples24bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; uint8 *src = in; uint8 *dst = out; unsigned char swapbuff[4]; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamples24bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples24bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples24bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = 0; maskbits = (uint32)-1 >> ( 32 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (32 - src_bit - bps); if (little_endian) { swapbuff[3] = *src; swapbuff[2] = *(src + 1); swapbuff[1] = *(src + 2); swapbuff[0] = *(src + 3); } else { swapbuff[0] = *src; swapbuff[1] = *(src + 1); swapbuff[2] = *(src + 2); swapbuff[3] = *(src + 3); } buff1 = *((uint32 *)swapbuff); buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 16) /* add another bps bits to the buffer */ { bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end extractContigSamples24bits */ static int extractContigSamples32bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0, shift_width = 0; uint32 col, src_byte, src_bit, bit_offset; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; uint8 *src = in; uint8 *dst = out; unsigned char swapbuff1[4]; unsigned char swapbuff2[4]; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamples32bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples32bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples32bits", "Invalid end column value %d ignored", end); end = cols; } shift_width = ((bps + 7) / 8) + 1; ready_bits = 0; maskbits = (uint64)-1 >> ( 64 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (64 - src_bit - bps); if (little_endian) { swapbuff1[3] = *src; swapbuff1[2] = *(src + 1); swapbuff1[1] = *(src + 2); swapbuff1[0] = *(src + 3); } else { swapbuff1[0] = *src; swapbuff1[1] = *(src + 1); swapbuff1[2] = *(src + 2); swapbuff1[3] = *(src + 3); } longbuff1 = *((uint32 *)swapbuff1); memset (swapbuff2, '\0', sizeof(swapbuff2)); if (little_endian) { swapbuff2[3] = *src; swapbuff2[2] = *(src + 1); swapbuff2[1] = *(src + 2); swapbuff2[0] = *(src + 3); } else { swapbuff2[0] = *src; swapbuff2[1] = *(src + 1); swapbuff2[2] = *(src + 2); swapbuff2[3] = *(src + 3); } longbuff2 = *((uint32 *)swapbuff2); buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 32) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end extractContigSamples32bits */ static int extractContigSamplesShifted8bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamplesShifted8bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted8bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted8bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = shift; maskbits = (uint8)-1 >> ( 8 - bps); buff1 = buff2 = 0; for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (8 - src_bit - bps); buff1 = ((*src) & matchbits) << (src_bit); if ((col == start) && (sindex == sample)) buff2 = *src & ((uint8)-1) << (shift); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ |= buff2; buff2 = buff1; ready_bits -= 8; } else buff2 = buff2 | (buff1 >> ready_bits); ready_bits += bps; } } while (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted8bits */ static int extractContigSamplesShifted16bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; uint8 *src = in; uint8 *dst = out; unsigned char swapbuff[2]; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamplesShifted16bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted16bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted16bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = shift; maskbits = (uint16)-1 >> (16 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (16 - src_bit - bps); if (little_endian) { swapbuff[1] = *src; swapbuff[0] = *(src + 1); } else { swapbuff[0] = *src; swapbuff[1] = *(src + 1); } buff1 = *((uint16 *)swapbuff); if ((col == start) && (sindex == sample)) buff2 = buff1 & ((uint16)-1) << (8 - shift); buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 8) /* add another bps bits to the buffer */ buff2 = buff2 | (buff1 >> ready_bits); else /* If we have a full buffer's worth, write it out */ { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted16bits */ static int extractContigSamplesShifted24bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; uint8 *src = in; uint8 *dst = out; unsigned char swapbuff[4]; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamplesShifted24bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted24bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted24bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = shift; maskbits = (uint32)-1 >> ( 32 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (32 - src_bit - bps); if (little_endian) { swapbuff[3] = *src; swapbuff[2] = *(src + 1); swapbuff[1] = *(src + 2); swapbuff[0] = *(src + 3); } else { swapbuff[0] = *src; swapbuff[1] = *(src + 1); swapbuff[2] = *(src + 2); swapbuff[3] = *(src + 3); } buff1 = *((uint32 *)swapbuff); if ((col == start) && (sindex == sample)) buff2 = buff1 & ((uint32)-1) << (16 - shift); buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 16) /* add another bps bits to the buffer */ { bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted24bits */ static int extractContigSamplesShifted32bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0, shift_width = 0; uint32 col, src_byte, src_bit, bit_offset; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; uint8 *src = in; uint8 *dst = out; unsigned char swapbuff1[4]; unsigned char swapbuff2[4]; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamplesShifted32bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted32bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted32bits", "Invalid end column value %d ignored", end); end = cols; } shift_width = ((bps + 7) / 8) + 1; ready_bits = shift; maskbits = (uint64)-1 >> ( 64 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (64 - src_bit - bps); if (little_endian) { swapbuff1[3] = *src; swapbuff1[2] = *(src + 1); swapbuff1[1] = *(src + 2); swapbuff1[0] = *(src + 3); } else { swapbuff1[0] = *src; swapbuff1[1] = *(src + 1); swapbuff1[2] = *(src + 2); swapbuff1[3] = *(src + 3); } longbuff1 = *((uint32 *)swapbuff1); memset (swapbuff2, '\0', sizeof(swapbuff2)); if (little_endian) { swapbuff2[3] = *src; swapbuff2[2] = *(src + 1); swapbuff2[1] = *(src + 2); swapbuff2[0] = *(src + 3); } else { swapbuff2[0] = *src; swapbuff2[1] = *(src + 1); swapbuff2[2] = *(src + 2); swapbuff2[3] = *(src + 3); } longbuff2 = *((uint32 *)swapbuff2); buff3 = ((uint64)longbuff1 << 32) | longbuff2; if ((col == start) && (sindex == sample)) buff2 = buff3 & ((uint64)-1) << (32 - shift); buff1 = (buff3 & matchbits) << (src_bit); if (ready_bits < 32) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted32bits */ static int extractContigSamplesToBuffer(uint8 *out, uint8 *in, uint32 rows, uint32 cols, int outskew, int inskew, tsample_t sample, uint16 spp, uint16 bps, struct dump_opts *dump) { int shift_width, bytes_per_sample, bytes_per_pixel; uint32 src_rowsize, src_offset, row, first_col = 0; uint32 dst_rowsize, dst_offset; tsample_t count = 1; uint8 *src, *dst; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } src_rowsize = ((bps * spp * cols) + 7) / 8; dst_rowsize = ((bps * cols) + 7) / 8; if ((dump->outfile != NULL) && (dump->level == 4)) { dump_info (dump->outfile, dump->format, "extractContigSamplesToBuffer", "Sample %d, %d rows", sample + 1, rows + 1); } for (row = 0; row < rows; row++) { src_offset = row * src_rowsize; dst_offset = row * dst_rowsize; src = in + src_offset; dst = out + dst_offset; /* pack the data into the scanline */ switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; case 1: if (extractContigSamples8bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; case 2: if (extractContigSamples16bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; case 3: if (extractContigSamples24bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; case 4: case 5: if (extractContigSamples32bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; default: TIFFError ("extractContigSamplesToBuffer", "Unsupported bit depth: %d", bps); return (1); } if ((dump->outfile != NULL) && (dump->level == 4)) dump_buffer(dump->outfile, dump->format, 1, dst_rowsize, row, dst); out += outskew; in += inskew; } return (0); } /* end extractContigSamplesToBuffer */ /* This will not work unless bps is a multiple of 8 */ static void cpSeparateBufToContigBuf(uint8 *out, uint8 *in, uint32 rows, uint32 cols, int outskew, int inskew, tsample_t spp, int bytes_per_sample) { while (rows-- > 0) { uint32 j = cols; while (j-- > 0) { int n = bytes_per_sample; while( n-- ) { *out++ = *in++; } out += (spp-1)*bytes_per_sample; } out += outskew; in += inskew; } } /* end of cpSeparateBufToContifBuf */ static int readContigStripsIntoBuffer (TIFF* in, uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp) { tsize_t scanlinesize = TIFFScanlineSize(in); uint8* bufp = buf; uint32 row; (void) imagewidth; (void) spp; for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, (tdata_t) bufp, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in),"Error, can't read scanline %lu", (unsigned long) row); return 0; } bufp += scanlinesize; } return 1; } /* end readContigStripsIntoBuffer */ static int combineSeparateSamples8bits (uint8 *in[], uint8 *out, uint32 row, uint32 cols, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0; int bytes_per_sample = 0; uint32 dst_rowsize; uint32 bit_offset; uint32 col, src_byte = 0, src_bit = 0; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[32]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples8bits","Invalid input or output buffer"); return (1); } bytes_per_sample = (bps + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint8)-1 >> ( 8 - bps); ready_bits = 0; buff1 = buff2 = 0; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (8 - src_bit - bps); /* load up next sample from each plane */ for (s = 0; s < spp; s++) { src = in[s] + src_byte; buff1 = ((*src) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; strcpy (action, "Flush"); } else { buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Match bits", matchbits); dump_byte (dumpfile, format, "Src bits", *src); dump_byte (dumpfile, format, "Buff1 bits", buff1); dump_byte (dumpfile, format, "Buff2 bits", buff2); dump_info (dumpfile, format, "","%s", action); } } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", buff1); } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamples8bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out); } return (0); } /* end combineSeparateSamples8bits */ static int combineSeparateSamples16bits (uint8 *in[], uint8 *out, uint32 row, uint32 cols, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0, bytes_per_sample = 0; uint32 dst_rowsize; uint32 bit_offset; uint32 col, src_byte = 0, src_bit = 0; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; unsigned char swapbuff[2]; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples16bits","Invalid input or output buffer"); return (1); } bytes_per_sample = (bps + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint16)-1 >> (16 - bps); ready_bits = 0; buff1 = buff2 = 0; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (16 - src_bit - bps); for (s = 0; s < spp; s++) { src = in[s] + src_byte; if (little_endian) { swapbuff[1] = *src; swapbuff[0] = *(src + 1); } else { swapbuff[0] = *src; swapbuff[1] = *(src + 1); } buff1 = *((uint16 *)swapbuff); buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_short (dumpfile, format, "Match bits", matchbits); dump_data (dumpfile, format, "Src bits", src, 2); dump_short (dumpfile, format, "Buff1 bits", buff1); dump_short (dumpfile, format, "Buff2 bits", buff2); dump_byte (dumpfile, format, "Write byte", bytebuff); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", bytebuff); } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamples16bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out); } return (0); } /* end combineSeparateSamples16bits */ static int combineSeparateSamples24bits (uint8 *in[], uint8 *out, uint32 row, uint32 cols, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0, bytes_per_sample = 0; uint32 dst_rowsize; uint32 bit_offset; uint32 col, src_byte = 0, src_bit = 0; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; unsigned char swapbuff[4]; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples24bits","Invalid input or output buffer"); return (1); } bytes_per_sample = (bps + 7) / 8; dst_rowsize = ((bps * cols) + 7) / 8; maskbits = (uint32)-1 >> ( 32 - bps); ready_bits = 0; buff1 = buff2 = 0; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (32 - src_bit - bps); for (s = 0; s < spp; s++) { src = in[s] + src_byte; if (little_endian) { swapbuff[3] = *src; swapbuff[2] = *(src + 1); swapbuff[1] = *(src + 2); swapbuff[0] = *(src + 3); } else { swapbuff[0] = *src; swapbuff[1] = *(src + 1); swapbuff[2] = *(src + 2); swapbuff[3] = *(src + 3); } buff1 = *((uint32 *)swapbuff); buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 16) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamples24bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out); } return (0); } /* end combineSeparateSamples24bits */ static int combineSeparateSamples32bits (uint8 *in[], uint8 *out, uint32 row, uint32 cols, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0, bytes_per_sample = 0, shift_width = 0; uint32 dst_rowsize; uint32 bit_offset; uint32 src_byte = 0, src_bit = 0; uint32 col; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; unsigned char swapbuff1[4]; unsigned char swapbuff2[4]; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples32bits","Invalid input or output buffer"); return (1); } bytes_per_sample = (bps + 7) / 8; dst_rowsize = ((bps * cols) + 7) / 8; maskbits = (uint64)-1 >> ( 64 - bps); shift_width = ((bps + 7) / 8) + 1; ready_bits = 0; buff1 = buff2 = 0; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (64 - src_bit - bps); for (s = 0; s < spp; s++) { src = in[s] + src_byte; if (little_endian) { swapbuff1[3] = *src; swapbuff1[2] = *(src + 1); swapbuff1[1] = *(src + 2); swapbuff1[0] = *(src + 3); } else { swapbuff1[0] = *src; swapbuff1[1] = *(src + 1); swapbuff1[2] = *(src + 2); swapbuff1[3] = *(src + 3); } longbuff1 = *((uint32 *)swapbuff1); memset (swapbuff2, '\0', sizeof(swapbuff2)); if (little_endian) { swapbuff2[3] = *src; swapbuff2[2] = *(src + 1); swapbuff2[1] = *(src + 2); swapbuff2[0] = *(src + 3); } else { swapbuff2[0] = *src; swapbuff2[1] = *(src + 1); swapbuff2[2] = *(src + 2); swapbuff2[3] = *(src + 3); } longbuff2 = *((uint32 *)swapbuff2); buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 32) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Sample %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_wide (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 8); dump_wide (dumpfile, format, "Buff1 bits ", buff1); dump_wide (dumpfile, format, "Buff2 bits ", buff2); dump_info (dumpfile, format, "", "Ready bits: %d, %s", ready_bits, action); } } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamples32bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out); } return (0); } /* end combineSeparateSamples32bits */ static int combineSeparateSamplesBytes (unsigned char *srcbuffs[], unsigned char *out, uint32 row, uint32 width, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int i, bytes_per_sample, bytes_per_pixel, dst_rowsize, shift_width; uint32 col, col_offset; unsigned char *src; unsigned char *dst; tsample_t s; src = srcbuffs[0]; dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamplesBytes","Invalid buffer address"); return (1); } bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_sample; else shift_width = bytes_per_pixel; if ((dumpfile != NULL) && (level == 2)) { for (s = 0; s < spp; s++) { dump_info (dumpfile, format, "combineSeparateSamplesBytes","Input data, Sample %d", s); dump_buffer(dumpfile, format, 1, width, row, srcbuffs[s]); } } dst_rowsize = ((bps * spp * width) + 7) / 8; for (col = 0; col < width; col++) { col_offset = col * (bps / 8); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = srcbuffs[s] + col_offset; for (i = 0; i < bytes_per_sample; i++) *(dst + i) = *(src + i); src += bytes_per_sample; dst += bytes_per_sample; } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamplesBytes","Output data, combined samples"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out); } return (0); } /* end combineSeparateSamplesBytes */ static int readSeparateStripsIntoBuffer (TIFF *in, uint8 *obuf, uint32 length, uint32 width, uint16 spp, struct dump_opts *dump) { int i, bytes_per_sample, bytes_per_pixel, shift_width; uint16 bps; uint32 row, src_rowsize, dst_rowsize; tsample_t s; tsize_t scanlinesize = TIFFScanlineSize(in); unsigned char *srcbuffs[MAX_SAMPLES]; unsigned char *buff = NULL; unsigned char *dst = NULL; (void) TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps); if (obuf == NULL) { TIFFError("readSeparateStripsIntoBuffer","Invalid buffer argument"); return (0); } bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; src_rowsize = ((bps * width) + 7) / 8; dst_rowsize = ((bps * width * spp) + 7) / 8; dst = obuf; if ((dump->infile != NULL) && (dump->level == 3)) { dump_info (dump->infile, dump->format, "", "Image width %d, length %d, Scanline size, %4d bytes", width, length, scanlinesize); dump_info (dump->infile, dump->format, "", "Bits per sample %d, Samples per pixel %d, Shift width %d", bps, spp, shift_width); } /* allocate scanline buffers for each sample */ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { srcbuffs[s] = NULL; buff = _TIFFmalloc(src_rowsize); if (!buff) { TIFFError ("readSeparateStripsIntoBuffer", "Unable to allocate read buffer for sample %d", s); for (i = 0; i < s; i++) _TIFFfree (srcbuffs[i]); return 0; } srcbuffs[s] = buff; } /* read and process one scanline from each sample */ for (row = 0; row < length; row++) { for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { buff = srcbuffs[s]; /* read one scanline in the current sample color */ if (TIFFReadScanline(in, buff, row, s) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu for sample %d", (unsigned long) row, s + 1); for (i = 0; i < s; i++) _TIFFfree (srcbuffs[i]); return (0); } } /* combine the samples in each scanline */ dst = obuf + (row * dst_rowsize); if ((bps % 8) == 0) { if (combineSeparateSamplesBytes (srcbuffs, dst, row, width, spp, bps, dump->infile, dump->format, dump->level)) { for (i = 0; i < spp; i++) _TIFFfree (srcbuffs[i]); return (0); } } else { switch (shift_width) { case 1: if (combineSeparateSamples8bits (srcbuffs, dst, row, width, spp, bps, dump->infile, dump->format, dump->level)) { for (i = 0; i < spp; i++) _TIFFfree (srcbuffs[i]); return (0); } break; case 2: if (combineSeparateSamples16bits (srcbuffs, dst, row, width, spp, bps, dump->infile, dump->format, dump->level)) { for (i = 0; i < spp; i++) _TIFFfree (srcbuffs[i]); return (0); } break; case 3: if (combineSeparateSamples24bits (srcbuffs, dst, row, width, spp, bps, dump->infile, dump->format, dump->level)) { for (i = 0; i < spp; i++) _TIFFfree (srcbuffs[i]); return (0); } break; case 4: case 5: case 6: case 7: case 8: if (combineSeparateSamples32bits (srcbuffs, dst, row, width, spp, bps, dump->infile, dump->format, dump->level)) { for (i = 0; i < spp; i++) _TIFFfree (srcbuffs[i]); return (0); } break; default: TIFFError ("readSeparateStripsIntoBuffer", "Unsupported bit depth: %d", bps); for (i = 0; i < spp; i++) _TIFFfree (srcbuffs[i]); return (0); } } } /* free any buffers allocated for each plane or scanline and * any temporary buffers */ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { buff = srcbuffs[s]; if (buff != NULL) _TIFFfree(buff); } return (1); } /* end readSeparateStripsIntoBuffer */ static int get_page_geometry (char *name, struct pagedef *page) { char *ptr; int n; for (ptr = name; *ptr; ptr++) *ptr = (char)tolower((int)*ptr); for (n = 0; n < MAX_PAPERNAMES; n++) { if (strcmp(name, PaperTable[n].name) == 0) { page->width = PaperTable[n].width; page->length = PaperTable[n].length; strncpy (page->name, PaperTable[n].name, 15); page->name[15] = '\0'; return (0); } } return (1); } static void initPageSetup (struct pagedef *page, struct pageseg *pagelist, struct buffinfo seg_buffs[]) { int i; strcpy (page->name, ""); page->mode = PAGE_MODE_NONE; page->res_unit = RESUNIT_NONE; page->hres = 0.0; page->vres = 0.0; page->width = 0.0; page->length = 0.0; page->hmargin = 0.0; page->vmargin = 0.0; page->rows = 0; page->cols = 0; page->orient = ORIENTATION_NONE; for (i = 0; i < MAX_SECTIONS; i++) { pagelist[i].x1 = (uint32)0; pagelist[i].x2 = (uint32)0; pagelist[i].y1 = (uint32)0; pagelist[i].y2 = (uint32)0; pagelist[i].buffsize = (uint32)0; pagelist[i].position = 0; pagelist[i].total = 0; } for (i = 0; i < MAX_OUTBUFFS; i++) { seg_buffs[i].size = 0; seg_buffs[i].buffer = NULL; } } static void initImageData (struct image_data *image) { image->xres = 0.0; image->yres = 0.0; image->width = 0; image->length = 0; image->res_unit = RESUNIT_NONE; image->bps = 0; image->spp = 0; image->planar = 0; image->photometric = 0; image->orientation = 0; image->adjustments = 0; } static void initCropMasks (struct crop_mask *cps) { int i; cps->crop_mode = CROP_NONE; cps->res_unit = RESUNIT_NONE; cps->edge_ref = EDGE_TOP; cps->width = 0; cps->length = 0; for (i = 0; i < 4; i++) cps->margins[i] = 0.0; cps->bufftotal = (uint32)0; cps->combined_width = (uint32)0; cps->combined_length = (uint32)0; cps->rotation = (uint16)0; cps->photometric = INVERT_DATA_AND_TAG; cps->mirror = (uint16)0; cps->invert = (uint16)0; cps->zones = (uint32)0; cps->regions = (uint32)0; for (i = 0; i < MAX_REGIONS; i++) { cps->corners[i].X1 = 0.0; cps->corners[i].X2 = 0.0; cps->corners[i].Y1 = 0.0; cps->corners[i].Y2 = 0.0; cps->regionlist[i].x1 = 0; cps->regionlist[i].x2 = 0; cps->regionlist[i].y1 = 0; cps->regionlist[i].y2 = 0; cps->regionlist[i].width = 0; cps->regionlist[i].length = 0; cps->regionlist[i].buffsize = 0; cps->regionlist[i].buffptr = NULL; cps->zonelist[i].position = 0; cps->zonelist[i].total = 0; } cps->exp_mode = ONE_FILE_COMPOSITE; cps->img_mode = COMPOSITE_IMAGES; } static void initDumpOptions(struct dump_opts *dump) { dump->debug = 0; dump->format = DUMP_NONE; dump->level = 1; sprintf (dump->mode, "w"); memset (dump->infilename, '\0', PATH_MAX + 1); memset (dump->outfilename, '\0',PATH_MAX + 1); dump->infile = NULL; dump->outfile = NULL; } /* Compute pixel offsets into the image for margins and fixed regions */ static int computeInputPixelOffsets(struct crop_mask *crop, struct image_data *image, struct offset *off) { double scale; float xres, yres; /* Values for these offsets are in pixels from start of image, not bytes, * and are indexed from zero to width - 1 or length - 1 */ uint32 tmargin, bmargin, lmargin, rmargin; uint32 startx, endx; /* offsets of first and last columns to extract */ uint32 starty, endy; /* offsets of first and last row to extract */ uint32 width, length, crop_width, crop_length; uint32 i, max_width, max_length, zwidth, zlength, buffsize; uint32 x1, x2, y1, y2; if (image->res_unit != RESUNIT_INCH && image->res_unit != RESUNIT_CENTIMETER) { xres = 1.0; yres = 1.0; } else { if (((image->xres == 0) || (image->yres == 0)) && ((crop->crop_mode & CROP_REGIONS) || (crop->crop_mode & CROP_MARGINS) || (crop->crop_mode & CROP_LENGTH) || (crop->crop_mode & CROP_WIDTH))) { TIFFError("computeInputPixelOffsets", "Cannot compute margins or fixed size sections without image resolution"); TIFFError("computeInputPixelOffsets", "Specify units in pixels and try again"); return (-1); } xres = image->xres; yres = image->yres; } /* Translate user units to image units */ scale = 1.0; switch (crop->res_unit) { case RESUNIT_CENTIMETER: if (image->res_unit == RESUNIT_INCH) scale = 1.0/2.54; break; case RESUNIT_INCH: if (image->res_unit == RESUNIT_CENTIMETER) scale = 2.54; break; case RESUNIT_NONE: /* Dimensions in pixels */ default: break; } if (crop->crop_mode & CROP_REGIONS) { max_width = max_length = 0; for (i = 0; i < crop->regions; i++) { if ((crop->res_unit == RESUNIT_INCH) || (crop->res_unit == RESUNIT_CENTIMETER)) { x1 = (uint32) (crop->corners[i].X1 * scale * xres); x2 = (uint32) (crop->corners[i].X2 * scale * xres); y1 = (uint32) (crop->corners[i].Y1 * scale * yres); y2 = (uint32) (crop->corners[i].Y2 * scale * yres); } else { x1 = (uint32) (crop->corners[i].X1); x2 = (uint32) (crop->corners[i].X2); y1 = (uint32) (crop->corners[i].Y1); y2 = (uint32) (crop->corners[i].Y2); } if (x1 < 1) crop->regionlist[i].x1 = 0; else crop->regionlist[i].x1 = (uint32) (x1 - 1); if (x2 > image->width - 1) crop->regionlist[i].x2 = image->width - 1; else crop->regionlist[i].x2 = (uint32) (x2 - 1); zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1; if (y1 < 1) crop->regionlist[i].y1 = 0; else crop->regionlist[i].y1 = (uint32) (y1 - 1); if (y2 > image->length - 1) crop->regionlist[i].y2 = image->length - 1; else crop->regionlist[i].y2 = (uint32) (y2 - 1); zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1; if (zwidth > max_width) max_width = zwidth; if (zlength > max_length) max_length = zlength; buffsize = (uint32) (((zwidth * image->bps * image->spp + 7 ) / 8) * (zlength + 1)); /* buffsize = (uint32) (((zwidth * image->bps + 7 ) / 8) * image->spp * (zlength + 1)); */ crop->regionlist[i].buffsize = buffsize; crop->bufftotal += buffsize; if (crop->img_mode == COMPOSITE_IMAGES) { switch (crop->edge_ref) { case EDGE_LEFT: case EDGE_RIGHT: crop->combined_length = zlength; crop->combined_width += zwidth; break; case EDGE_BOTTOM: case EDGE_TOP: /* width from left, length from top */ default: crop->combined_width = zwidth; crop->combined_length += zlength; break; } } } return (0); } /* Convert crop margins into offsets into image * Margins are expressed as pixel rows and columns, not bytes */ if (crop->crop_mode & CROP_MARGINS) { if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER) { /* User has specified pixels as reference unit */ tmargin = (uint32)(crop->margins[0]); lmargin = (uint32)(crop->margins[1]); bmargin = (uint32)(crop->margins[2]); rmargin = (uint32)(crop->margins[3]); } else { /* inches or centimeters specified */ tmargin = (uint32)(crop->margins[0] * scale * yres); lmargin = (uint32)(crop->margins[1] * scale * xres); bmargin = (uint32)(crop->margins[2] * scale * yres); rmargin = (uint32)(crop->margins[3] * scale * xres); } if ((lmargin + rmargin) > image->width) { TIFFError("computeInputPixelOffsets", "Combined left and right margins exceed image width"); lmargin = (uint32) 0; rmargin = (uint32) 0; return (-1); } if ((tmargin + bmargin) > image->length) { TIFFError("computeInputPixelOffsets", "Combined top and bottom margins exceed image length"); tmargin = (uint32) 0; bmargin = (uint32) 0; return (-1); } } else { /* no margins requested */ tmargin = (uint32) 0; lmargin = (uint32) 0; bmargin = (uint32) 0; rmargin = (uint32) 0; } /* Width, height, and margins are expressed as pixel offsets into image */ if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER) { if (crop->crop_mode & CROP_WIDTH) width = (uint32)crop->width; else width = image->width - lmargin - rmargin; if (crop->crop_mode & CROP_LENGTH) length = (uint32)crop->length; else length = image->length - tmargin - bmargin; } else { if (crop->crop_mode & CROP_WIDTH) width = (uint32)(crop->width * scale * image->xres); else width = image->width - lmargin - rmargin; if (crop->crop_mode & CROP_LENGTH) length = (uint32)(crop->length * scale * image->yres); else length = image->length - tmargin - bmargin; } off->tmargin = tmargin; off->bmargin = bmargin; off->lmargin = lmargin; off->rmargin = rmargin; /* Calculate regions defined by margins, width, and length. * Coordinates expressed as 0 to imagewidth - 1, imagelength - 1, * since they are used to compute offsets into buffers */ switch (crop->edge_ref) { case EDGE_BOTTOM: startx = lmargin; if ((startx + width) >= (image->width - rmargin)) endx = image->width - rmargin - 1; else endx = startx + width - 1; endy = image->length - bmargin - 1; if ((endy - length) <= tmargin) starty = tmargin; else starty = endy - length + 1; break; case EDGE_RIGHT: endx = image->width - rmargin - 1; if ((endx - width) <= lmargin) startx = lmargin; else startx = endx - width + 1; starty = tmargin; if ((starty + length) >= (image->length - bmargin)) endy = image->length - bmargin - 1; else endy = starty + length - 1; break; case EDGE_TOP: /* width from left, length from top */ case EDGE_LEFT: default: startx = lmargin; if ((startx + width) >= (image->width - rmargin)) endx = image->width - rmargin - 1; else endx = startx + width - 1; starty = tmargin; if ((starty + length) >= (image->length - bmargin)) endy = image->length - bmargin - 1; else endy = starty + length - 1; break; } off->startx = startx; off->starty = starty; off->endx = endx; off->endy = endy; crop_width = endx - startx + 1; crop_length = endy - starty + 1; if (crop_width <= 0) { TIFFError("computeInputPixelOffsets", "Invalid left/right margins and /or image crop width requested"); return (-1); } if (crop_width > image->width) crop_width = image->width; if (crop_length <= 0) { TIFFError("computeInputPixelOffsets", "Invalid top/bottom margins and /or image crop length requested"); return (-1); } if (crop_length > image->length) crop_length = image->length; off->crop_width = crop_width; off->crop_length = crop_length; return (0); } /* end computeInputPixelOffsets */ /* * Translate crop options into pixel offsets for one or more regions of the image. * Options are applied in this order: margins, specific width and length, zones, * but all are optional. Margins are relative to each edge. Width, length and * zones are relative to the specified reference edge. Zones are expressed as * X:Y where X is the ordinal value in a set of Y equal sized portions. eg. * 2:3 would indicate the middle third of the region qualified by margins and * any explicit width and length specified. Regions are specified by coordinates * of the top left and lower right corners with range 1 to width or height. */ static int getCropOffsets(struct image_data *image, struct crop_mask *crop, struct dump_opts *dump) { struct offset offsets; int i; int32 test2; uint32 test, seg, total, need_buff = 0; uint32 buffsize; uint32 zwidth, zlength; memset(&offsets, '\0', sizeof(struct offset)); crop->bufftotal = 0; crop->combined_width = (uint32)0; crop->combined_length = (uint32)0; crop->selections = 0; /* Compute pixel offsets if margins or fixed width or length specified */ if ((crop->crop_mode & CROP_MARGINS) || (crop->crop_mode & CROP_REGIONS) || (crop->crop_mode & CROP_LENGTH) || (crop->crop_mode & CROP_WIDTH)) { if (computeInputPixelOffsets(crop, image, &offsets)) { TIFFError ("getCropOffsets", "Unable to compute crop margins"); return (-1); } need_buff = TRUE; crop->selections = crop->regions; /* Regions are only calculated from top and left edges with no margins */ if (crop->crop_mode & CROP_REGIONS) return (0); } else { /* cropped area is the full image */ offsets.tmargin = 0; offsets.lmargin = 0; offsets.bmargin = 0; offsets.rmargin = 0; offsets.crop_width = image->width; offsets.crop_length = image->length; offsets.startx = 0; offsets.endx = image->width - 1; offsets.starty = 0; offsets.endy = image->length - 1; need_buff = FALSE; } if (dump->outfile != NULL) { dump_info (dump->outfile, dump->format, "", "Margins: Top: %d Left: %d Bottom: %d Right: %d", offsets.tmargin, offsets.lmargin, offsets.bmargin, offsets.rmargin); dump_info (dump->outfile, dump->format, "", "Crop region within margins: Adjusted Width: %6d Length: %6d", offsets.crop_width, offsets.crop_length); } if (!(crop->crop_mode & CROP_ZONES)) /* no crop zones requested */ { if (need_buff == FALSE) /* No margins or fixed width or length areas */ { crop->selections = 0; crop->combined_width = image->width; crop->combined_length = image->length; return (0); } else { /* Use one region for margins and fixed width or length areas * even though it was not formally declared as a region. */ crop->selections = 1; crop->zones = 1; crop->zonelist[0].total = 1; crop->zonelist[0].position = 1; } } else crop->selections = crop->zones; for (i = 0; i < crop->zones; i++) { seg = crop->zonelist[i].position; total = crop->zonelist[i].total; switch (crop->edge_ref) { case EDGE_LEFT: /* zones from left to right, length from top */ zlength = offsets.crop_length; crop->regionlist[i].y1 = offsets.starty; crop->regionlist[i].y2 = offsets.endy; crop->regionlist[i].x1 = offsets.startx + (uint32)(offsets.crop_width * 1.0 * (seg - 1) / total); test = offsets.startx + (uint32)(offsets.crop_width * 1.0 * seg / total); if (test > image->width - 1) crop->regionlist[i].x2 = image->width - 1; else crop->regionlist[i].x2 = test - 1; zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ crop->combined_length = (uint32)zlength; if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_width += (uint32)zwidth; else crop->combined_width = (uint32)zwidth; break; case EDGE_BOTTOM: /* width from left, zones from bottom to top */ zwidth = offsets.crop_width; crop->regionlist[i].x1 = offsets.startx; crop->regionlist[i].x2 = offsets.endx; test2 = offsets.endy - (uint32)(offsets.crop_length * 1.0 * seg / total); if (test2 < 1 ) crop->regionlist[i].y1 = 0; else crop->regionlist[i].y1 = test2 + 1; test = offsets.endy - (uint32)(offsets.crop_length * 1.0 * (seg - 1) / total); if (test > (image->length - 1)) crop->regionlist[i].y2 = image->length - 1; else crop->regionlist[i].y2 = test; zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_length += (uint32)zlength; else crop->combined_length = (uint32)zlength; crop->combined_width = (uint32)zwidth; break; case EDGE_RIGHT: /* zones from right to left, length from top */ zlength = offsets.crop_length; crop->regionlist[i].y1 = offsets.starty; crop->regionlist[i].y2 = offsets.endy; crop->regionlist[i].x1 = offsets.startx + (uint32)(offsets.crop_width * (total - seg) * 1.0 / total); test = offsets.startx + (uint32)(offsets.crop_width * (total - seg + 1) * 1.0 / total); if (test > image->width - 1) crop->regionlist[i].x2 = image->width - 1; else crop->regionlist[i].x2 = test - 1; zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ crop->combined_length = (uint32)zlength; if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_width += (uint32)zwidth; else crop->combined_width = (uint32)zwidth; break; case EDGE_TOP: /* width from left, zones from top to bottom */ default: zwidth = offsets.crop_width; crop->regionlist[i].x1 = offsets.startx; crop->regionlist[i].x2 = offsets.endx; crop->regionlist[i].y1 = offsets.starty + (uint32)(offsets.crop_length * 1.0 * (seg - 1) / total); test = offsets.starty + (uint32)(offsets.crop_length * 1.0 * seg / total); if (test > image->length - 1) crop->regionlist[i].y2 = image->length - 1; else crop->regionlist[i].y2 = test - 1; zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_length += (uint32)zlength; else crop->combined_length = (uint32)zlength; crop->combined_width = (uint32)zwidth; break; } /* end switch statement */ buffsize = (uint32) ((((zwidth * image->bps * image->spp) + 7 ) / 8) * (zlength + 1)); crop->regionlist[i].width = (uint32) zwidth; crop->regionlist[i].length = (uint32) zlength; crop->regionlist[i].buffsize = buffsize; crop->bufftotal += buffsize; if (dump->outfile != NULL) dump_info (dump->outfile, dump->format, "", "Zone %d, width: %4d, length: %4d, x1: %4d x2: %4d y1: %4d y2: %4d", i + 1, (uint32)zwidth, (uint32)zlength, crop->regionlist[i].x1, crop->regionlist[i].x2, crop->regionlist[i].y1, crop->regionlist[i].y2); } return (0); } /* end getCropOffsets */ static int computeOutputPixelOffsets (struct crop_mask *crop, struct image_data *image, struct pagedef *page, struct pageseg *sections, struct dump_opts* dump) { double scale; uint32 iwidth, ilength; /* Input image width and length */ uint32 owidth, olength; /* Output image width and length */ uint32 pwidth, plength; /* Output page width and length */ uint32 orows, ocols; /* rows and cols for output */ uint32 hmargin, vmargin; /* Horizontal and vertical margins */ uint32 x1, x2, y1, y2, line_bytes; unsigned int orientation; uint32 i, j, k; scale = 1.0; if (page->res_unit == RESUNIT_NONE) page->res_unit = image->res_unit; switch (image->res_unit) { case RESUNIT_CENTIMETER: if (page->res_unit == RESUNIT_INCH) scale = 1.0/2.54; break; case RESUNIT_INCH: if (page->res_unit == RESUNIT_CENTIMETER) scale = 2.54; break; case RESUNIT_NONE: /* Dimensions in pixels */ default: break; } /* get width, height, resolutions of input image selection */ if (crop->combined_width > 0) iwidth = crop->combined_width; else iwidth = image->width; if (crop->combined_length > 0) ilength = crop->combined_length; else ilength = image->length; if (page->hres <= 1.0) page->hres = image->xres; if (page->vres <= 1.0) page->vres = image->yres; if ((page->hres < 1.0) || (page->vres < 1.0)) { TIFFError("computeOutputPixelOffsets", "Invalid horizontal or vertical resolution specified or read from input image"); return (1); } /* If no page sizes are being specified, we just use the input image size to * calculate maximum margins that can be taken from image. */ if (page->width <= 0) pwidth = iwidth; else pwidth = page->width; if (page->length <= 0) plength = ilength; else plength = page->length; if (dump->debug) { TIFFError("", "Page size: %s, Vres: %3.2f, Hres: %3.2f, " "Hmargin: %3.2f, Vmargin: %3.2f\n", page->name, page->vres, page->hres, page->hmargin, page->vmargin); TIFFError("", "Res_unit: %d, Scale: %3.2f, Page width: %d, length: %d\n", page->res_unit, scale, pwidth, plength); } /* compute margins at specified unit and resolution */ if (page->mode & PAGE_MODE_MARGINS) { if (page->res_unit == RESUNIT_INCH || page->res_unit == RESUNIT_CENTIMETER) { /* inches or centimeters specified */ hmargin = (uint32)(page->hmargin * scale * page->hres * ((image->bps + 7)/ 8)); vmargin = (uint32)(page->vmargin * scale * page->vres * ((image->bps + 7)/ 8)); } else { /* Otherwise user has specified pixels as reference unit */ hmargin = (uint32)(page->hmargin * scale * ((image->bps + 7)/ 8)); vmargin = (uint32)(page->vmargin * scale * ((image->bps + 7)/ 8)); } if ((hmargin * 2.0) > (pwidth * page->hres)) { TIFFError("computeOutputPixelOffsets", "Combined left and right margins exceed page width"); hmargin = (uint32) 0; return (-1); } if ((vmargin * 2.0) > (plength * page->vres)) { TIFFError("computeOutputPixelOffsets", "Combined top and bottom margins exceed page length"); vmargin = (uint32) 0; return (-1); } } else { hmargin = 0; vmargin = 0; } if (page->mode & PAGE_MODE_ROWSCOLS ) { /* Maybe someday but not for now */ if (page->mode & PAGE_MODE_MARGINS) TIFFError("computeOutputPixelOffsets", "Output margins cannot be specified with rows and columns"); owidth = TIFFhowmany(iwidth, page->cols); olength = TIFFhowmany(ilength, page->rows); } else { if (page->mode & PAGE_MODE_PAPERSIZE ) { owidth = (uint32)((pwidth * page->hres) - (hmargin * 2)); olength = (uint32)((plength * page->vres) - (vmargin * 2)); } else { owidth = (uint32)(iwidth - (hmargin * 2 * page->hres)); olength = (uint32)(ilength - (vmargin * 2 * page->vres)); } } if (owidth > iwidth) owidth = iwidth; if (olength > ilength) olength = ilength; /* Compute the number of pages required for Portrait or Landscape */ switch (page->orient) { case ORIENTATION_NONE: case ORIENTATION_PORTRAIT: ocols = TIFFhowmany(iwidth, owidth); orows = TIFFhowmany(ilength, olength); orientation = ORIENTATION_PORTRAIT; break; case ORIENTATION_LANDSCAPE: ocols = TIFFhowmany(iwidth, olength); orows = TIFFhowmany(ilength, owidth); x1 = olength; olength = owidth; owidth = x1; orientation = ORIENTATION_LANDSCAPE; break; case ORIENTATION_AUTO: default: x1 = TIFFhowmany(iwidth, owidth); x2 = TIFFhowmany(ilength, olength); y1 = TIFFhowmany(iwidth, olength); y2 = TIFFhowmany(ilength, owidth); if ( (x1 * x2) < (y1 * y2)) { /* Portrait */ ocols = x1; orows = x2; orientation = ORIENTATION_PORTRAIT; } else { /* Landscape */ ocols = y1; orows = y2; x1 = olength; olength = owidth; owidth = x1; orientation = ORIENTATION_LANDSCAPE; } } if (ocols < 1) ocols = 1; if (orows < 1) orows = 1; /* If user did not specify rows and cols, set them from calcuation */ if (page->rows < 1) page->rows = orows; if (page->cols < 1) page->cols = ocols; line_bytes = TIFFhowmany8(owidth * image->bps) * image->spp; if ((page->rows * page->cols) > MAX_SECTIONS) { TIFFError("computeOutputPixelOffsets", "Rows and Columns exceed maximum sections\nIncrease resolution or reduce sections"); return (-1); } /* build the list of offsets for each output section */ for (k = 0, i = 0 && k <= MAX_SECTIONS; i < orows; i++) { y1 = (uint32)(olength * i); y2 = (uint32)(olength * (i + 1) - 1); if (y2 >= ilength) y2 = ilength - 1; for (j = 0; j < ocols; j++, k++) { x1 = (uint32)(owidth * j); x2 = (uint32)(owidth * (j + 1) - 1); if (x2 >= iwidth) x2 = iwidth - 1; sections[k].x1 = x1; sections[k].x2 = x2; sections[k].y1 = y1; sections[k].y2 = y2; sections[k].buffsize = line_bytes * olength; sections[k].position = k + 1; sections[k].total = orows * ocols; } } return (0); } /* end computeOutputPixelOffsets */ static int loadImage(TIFF* in, struct image_data *image, struct dump_opts * dump, unsigned char **read_ptr) { uint32 i; float xres=0.0, yres=0.0; uint16 nstrips, ntiles, planar, bps, spp, res_unit, photometric, orientation; uint32 width, length, rowsperstrip; uint32 stsize, tlsize, buffsize, scanlinesize; unsigned char *read_buff = NULL; unsigned char *new_buff = NULL; int readunit = 0; static uint32 prev_readsize = 0; TIFFGetFieldDefaulted(in, TIFFTAG_BITSPERSAMPLE, &bps); TIFFGetFieldDefaulted(in, TIFFTAG_SAMPLESPERPIXEL, &spp); TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar); TIFFGetFieldDefaulted(in, TIFFTAG_ORIENTATION, &orientation); TIFFGetField(in, TIFFTAG_PHOTOMETRIC, &photometric); TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width); TIFFGetField(in, TIFFTAG_IMAGELENGTH, &length); TIFFGetField(in, TIFFTAG_XRESOLUTION, &xres); TIFFGetField(in, TIFFTAG_YRESOLUTION, &yres); TIFFGetFieldDefaulted(in, TIFFTAG_RESOLUTIONUNIT, &res_unit); scanlinesize = TIFFScanlineSize(in); image->bps = bps; image->spp = spp; image->planar = planar; image->width = width; image->length = length; image->xres = xres; image->yres = yres; image->res_unit = res_unit; image->photometric = photometric; image->orientation = orientation; switch (orientation) { case 0: case ORIENTATION_TOPLEFT: image->adjustments = 0; break; case ORIENTATION_TOPRIGHT: image->adjustments = MIRROR_HORIZ; break; case ORIENTATION_BOTRIGHT: image->adjustments = ROTATECW_180; break; case ORIENTATION_BOTLEFT: image->adjustments = MIRROR_VERT; break; case ORIENTATION_LEFTTOP: image->adjustments = MIRROR_VERT | ROTATECW_90; break; case ORIENTATION_RIGHTTOP: image->adjustments = ROTATECW_90; break; case ORIENTATION_RIGHTBOT: image->adjustments = MIRROR_VERT | ROTATECW_270; break; case ORIENTATION_LEFTBOT: image->adjustments = ROTATECW_270; break; default: image->adjustments = 0; image->orientation = ORIENTATION_TOPLEFT; } if ((bps == 0) || (spp == 0)) { TIFFError("loadImage", "Invalid samples per pixel (%d) or bits per sample (%d)", spp, bps); return (-1); } if (TIFFIsTiled(in)) { readunit = TILE; tlsize = TIFFTileSize(in); ntiles = TIFFNumberOfTiles(in); buffsize = tlsize * ntiles; if (dump->infile != NULL) dump_info (dump->infile, dump->format, "", "Tilesize: %u, Number of Tiles: %u, Scanline size: %u", tlsize, ntiles, scanlinesize); } else { readunit = STRIP; TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); stsize = TIFFStripSize(in); nstrips = TIFFNumberOfStrips(in); buffsize = stsize * nstrips; if (dump->infile != NULL) dump_info (dump->infile, dump->format, "", "Stripsize: %u, Number of Strips: %u, Rows per Strip: %u, Scanline size: %u", stsize, nstrips, rowsperstrip, scanlinesize); } read_buff = *read_ptr; if (!read_buff) read_buff = (unsigned char *)_TIFFmalloc(buffsize); else { if (prev_readsize < buffsize) { new_buff = _TIFFrealloc(read_buff, buffsize); if (!new_buff) { free (read_buff); read_buff = (unsigned char *)_TIFFmalloc(buffsize); } else read_buff = new_buff; } } if (!read_buff) { TIFFError("loadImage", "Unable to allocate/reallocate read buffer"); return (-1); } _TIFFmemset(read_buff, '\0', buffsize); prev_readsize = buffsize; *read_ptr = read_buff; /* N.B. The read functions used copy separate plane data into a buffer as interleaved * samples rather than separate planes so the same logic works to extract regions * regardless of the way the data are organized in the input file. */ switch (readunit) { case STRIP: if (planar == PLANARCONFIG_CONTIG) { if (!(readContigStripsIntoBuffer(in, read_buff, length, width, spp))) { TIFFError("loadImage", "Unable to read contiguous strips into buffer"); return (-1); } } else { if (!(readSeparateStripsIntoBuffer(in, read_buff, length, width, spp, dump))) { TIFFError("loadImage", "Unable to read separate strips into buffer"); return (-1); } } break; case TILE: if (planar == PLANARCONFIG_CONTIG) { if (!(readContigTilesIntoBuffer(in, read_buff, length, width, spp))) { TIFFError("loadImage", "Unable to read contiguous tiles into buffer"); return (-1); } } else { if (!(readSeparateTilesIntoBuffer(in, read_buff, length, width, spp))) { TIFFError("loadImage", "Unable to read separate tiles into buffer"); return (-1); } } break; default: TIFFError("loadImage", "Unsupported image file format"); return (-1); break; } if ((dump->infile != NULL) && (dump->level == 2)) { dump_info (dump->infile, dump->format, "loadImage", "Image width %d, length %d, Raw image data, %4d bytes", width, length, buffsize); dump_info (dump->infile, dump->format, "", "Bits per sample %d, Samples per pixel %d", bps, spp); for (i = 0; i < length; i++) dump_buffer(dump->infile, dump->format, 1, scanlinesize, i, read_buff + (i * scanlinesize)); } return (0); } /* end loadImage */ static int correct_orientation(struct image_data *image, unsigned char **work_buff_ptr) { uint16 mirror, rotation; unsigned char *work_buff; work_buff = *work_buff_ptr; if ((image == NULL) || (work_buff == NULL)) { TIFFError ("correct_orientatin", "Invalid image or buffer pointer"); return (-1); } if ((image->adjustments & MIRROR_HORIZ) || (image->adjustments & MIRROR_VERT)) { mirror = (uint16)(image->adjustments & MIRROR_BOTH); if (mirrorImage(image->spp, image->bps, mirror, image->width, image->length, work_buff)) { TIFFError ("correct_orientation", "Unable to mirror image"); return (-1); } } if (image->adjustments & ROTATE_ANY) { if (image->adjustments & ROTATECW_90) rotation = (uint16) 90; else if (image->adjustments & ROTATECW_180) rotation = (uint16) 180; else if (image->adjustments & ROTATECW_270) rotation = (uint16) 270; else { TIFFError ("correct_orientation", "Invalid rotation value: %d", image->adjustments & ROTATE_ANY); return (-1); } if (rotateImage(rotation, image, &image->width, &image->length, work_buff_ptr)) { TIFFError ("correct_orientation", "Unable to rotate image"); return (-1); } image->orientation = ORIENTATION_TOPLEFT; } return (0); } /* end correct_orientation */ /* Extract multiple zones from an image and combine into a single composite image */ static int extractCompositeRegions(struct image_data *image, struct crop_mask *crop, unsigned char *read_buff, unsigned char *crop_buff) { int shift_width, bytes_per_sample, bytes_per_pixel; uint32 i, trailing_bits, prev_trailing_bits; uint32 row, first_row, last_row, first_col, last_col; uint32 src_rowsize, dst_rowsize, src_offset, dst_offset; uint32 crop_width, crop_length, img_width, img_length; uint32 prev_length, prev_width, composite_width; uint16 bps, spp; uint8 *src, *dst; tsample_t count, sample = 0; /* Update to extract one or more samples */ img_width = image->width; img_length = image->length; bps = image->bps; spp = image->spp; count = spp; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } src = read_buff; dst = crop_buff; /* These are setup for adding additional sections */ prev_width = prev_length = 0; prev_trailing_bits = trailing_bits = 0; composite_width = crop->combined_width; crop->combined_width = 0; crop->combined_length = 0; for (i = 0; i < crop->selections; i++) { /* rows, columns, width, length are expressed in pixels */ first_row = crop->regionlist[i].y1; last_row = crop->regionlist[i].y2; first_col = crop->regionlist[i].x1; last_col = crop->regionlist[i].x2; crop_width = last_col - first_col + 1; crop_length = last_row - first_row + 1; /* These should not be needed for composite images */ crop->regionlist[i].width = crop_width; crop->regionlist[i].length = crop_length; crop->regionlist[i].buffptr = crop_buff; src_rowsize = ((img_width * bps * spp) + 7) / 8; dst_rowsize = (((crop_width * bps * count) + 7) / 8); switch (crop->edge_ref) { default: case EDGE_TOP: case EDGE_BOTTOM: if ((i > 0) && (crop_width != crop->regionlist[i - 1].width)) { TIFFError ("extractCompositeRegions", "Only equal width regions can be combined for -E top or bottom"); return (1); } crop->combined_width = crop_width; crop->combined_length += crop_length; for (row = first_row; row <= last_row; row++) { src_offset = row * src_rowsize; dst_offset = (row - first_row) * dst_rowsize; src = read_buff + src_offset; dst = crop_buff + dst_offset + (prev_length * dst_rowsize); switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 1: if (extractContigSamplesShifted8bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 2: if (extractContigSamplesShifted16bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 3: if (extractContigSamplesShifted24bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; default: TIFFError("extractCompositeRegions", "Unsupported bit depth %d", bps); return (1); } } prev_length += crop_length; break; case EDGE_LEFT: /* splice the pieces of each row together, side by side */ case EDGE_RIGHT: if ((i > 0) && (crop_length != crop->regionlist[i - 1].length)) { TIFFError ("extractCompositeRegions", "Only equal length regions can be combined for -E left or right"); return (1); } crop->combined_width += crop_width; crop->combined_length = crop_length; dst_rowsize = (((composite_width * bps * count) + 7) / 8); trailing_bits = (crop_width * bps * count) % 8; for (row = first_row; row <= last_row; row++) { src_offset = row * src_rowsize; dst_offset = (row - first_row) * dst_rowsize; src = read_buff + src_offset; dst = crop_buff + dst_offset + prev_width; switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 1: if (extractContigSamplesShifted8bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 2: if (extractContigSamplesShifted16bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 3: if (extractContigSamplesShifted24bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; default: TIFFError("extractCompositeRegions", "Unsupported bit depth %d", bps); return (1); } } prev_width += (crop_width * bps * count) / 8; prev_trailing_bits += trailing_bits; if (prev_trailing_bits > 7) prev_trailing_bits-= 8; break; } } if (crop->combined_width != composite_width) TIFFError("combineSeparateRegions","Combined width does not match composite width"); return (0); } /* end extractCompositeRegions */ /* Copy a single region of input buffer to an output buffer. * The read functions used copy separate plane data into a buffer * as interleaved samples rather than separate planes so the same * logic works to extract regions regardless of the way the data * are organized in the input file. This function can be used to * extract one or more samples from the input image by updating the * parameters for starting sample and number of samples to copy in the * fifth and eighth arguments of the call to extractContigSamples. * They would be passed as new elements of the crop_mask struct. */ static int extractSeparateRegion(struct image_data *image, struct crop_mask *crop, unsigned char *read_buff, unsigned char *crop_buff, int region) { int shift_width, prev_trailing_bits = 0; uint32 bytes_per_sample, bytes_per_pixel; uint32 src_rowsize, dst_rowsize; uint32 row, first_row, last_row, first_col, last_col; uint32 src_offset, dst_offset; uint32 crop_width, crop_length, img_width, img_length; uint16 bps, spp; uint8 *src, *dst; tsample_t count, sample = 0; /* Update to extract more or more samples */ img_width = image->width; img_length = image->length; bps = image->bps; spp = image->spp; count = spp; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; /* Byte aligned data only */ else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } /* rows, columns, width, length are expressed in pixels */ first_row = crop->regionlist[region].y1; last_row = crop->regionlist[region].y2; first_col = crop->regionlist[region].x1; last_col = crop->regionlist[region].x2; crop_width = last_col - first_col + 1; crop_length = last_row - first_row + 1; crop->regionlist[region].width = crop_width; crop->regionlist[region].length = crop_length; crop->regionlist[region].buffptr = crop_buff; src = read_buff; dst = crop_buff; src_rowsize = ((img_width * bps * spp) + 7) / 8; dst_rowsize = (((crop_width * bps * spp) + 7) / 8); for (row = first_row; row <= last_row; row++) { src_offset = row * src_rowsize; dst_offset = (row - first_row) * dst_rowsize; src = read_buff + src_offset; dst = crop_buff + dst_offset; switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; case 1: if (extractContigSamplesShifted8bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; case 2: if (extractContigSamplesShifted16bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; case 3: if (extractContigSamplesShifted24bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; default: TIFFError("extractSeparateRegion", "Unsupported bit depth %d", bps); return (1); } } return (0); } /* end extractSeparateRegion */ static int extractImageSection(struct image_data *image, struct pageseg *section, unsigned char *src_buff, unsigned char *sect_buff) { unsigned char bytebuff1, bytebuff2; unsigned char *src, *dst; uint32 img_width, img_length, img_rowsize; uint32 j, shift1, shift2, trailing_bits; uint32 row, first_row, last_row, first_col, last_col; uint32 src_offset, dst_offset, row_offset, col_offset; uint32 offset1, offset2, full_bytes; uint32 sect_width, sect_length; uint16 bps, spp; #ifdef DEBUG2 int k; unsigned char bitset; static char *bitarray = NULL; #endif img_width = image->width; img_length = image->length; bps = image->bps; spp = image->spp; src = src_buff; dst = sect_buff; src_offset = 0; dst_offset = 0; #ifdef DEBUG2 if (bitarray == NULL) { if ((bitarray = (char *)malloc(img_width)) == NULL) { TIFFError ("", "DEBUG: Unable to allocate debugging bitarray\n"); return (-1); } } #endif /* rows, columns, width, length are expressed in pixels */ first_row = section->y1; last_row = section->y2; first_col = section->x1; last_col = section->x2; sect_width = last_col - first_col + 1; sect_length = last_row - first_row + 1; img_rowsize = ((img_width * bps + 7) / 8) * spp; full_bytes = (sect_width * spp * bps) / 8; /* number of COMPLETE bytes per row in section */ trailing_bits = (sect_width * bps) % 8; #ifdef DEBUG2 TIFFError ("", "First row: %d, last row: %d, First col: %d, last col: %d\n", first_row, last_row, first_col, last_col); TIFFError ("", "Image width: %d, Image length: %d, bps: %d, spp: %d\n", img_width, img_length, bps, spp); TIFFError ("", "Sect width: %d, Sect length: %d, full bytes: %d trailing bits %d\n", sect_width, sect_length, full_bytes, trailing_bits); #endif if ((bps % 8) == 0) { col_offset = first_col * spp * bps / 8; for (row = first_row; row <= last_row; row++) { /* row_offset = row * img_width * spp * bps / 8; */ row_offset = row * img_rowsize; src_offset = row_offset + col_offset; #ifdef DEBUG2 TIFFError ("", "Src offset: %8d, Dst offset: %8d\n", src_offset, dst_offset); #endif _TIFFmemcpy (sect_buff + dst_offset, src_buff + src_offset, full_bytes); dst_offset += full_bytes; } } else { /* bps != 8 */ shift1 = spp * ((first_col * bps) % 8); shift2 = spp * ((last_col * bps) % 8); for (row = first_row; row <= last_row; row++) { /* pull out the first byte */ row_offset = row * img_rowsize; offset1 = row_offset + (first_col * bps / 8); offset2 = row_offset + (last_col * bps / 8); #ifdef DEBUG2 for (j = 0, k = 7; j < 8; j++, k--) { bitset = *(src_buff + offset1) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } sprintf(&bitarray[8], " "); sprintf(&bitarray[9], " "); for (j = 10, k = 7; j < 18; j++, k--) { bitset = *(src_buff + offset2) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[18] = '\0'; TIFFError ("", "Row: %3d Offset1: %d, Shift1: %d, Offset2: %d, Shift2: %d\n", row, offset1, shift1, offset2, shift2); #endif bytebuff1 = bytebuff2 = 0; if (shift1 == 0) /* the region is byte and sample alligned */ { _TIFFmemcpy (sect_buff + dst_offset, src_buff + offset1, full_bytes); #ifdef DEBUG2 TIFFError ("", " Alligned data src offset1: %8d, Dst offset: %8d\n", offset1, dst_offset); sprintf(&bitarray[18], "\n"); sprintf(&bitarray[19], "\t"); for (j = 20, k = 7; j < 28; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[28] = ' '; bitarray[29] = ' '; #endif dst_offset += full_bytes; if (trailing_bits != 0) { bytebuff2 = src_buff[offset2] & ((unsigned char)255 << (7 - shift2)); sect_buff[dst_offset] = bytebuff2; #ifdef DEBUG2 TIFFError ("", " Trailing bits src offset: %8d, Dst offset: %8d\n", offset2, dst_offset); for (j = 30, k = 7; j < 38; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[38] = '\0'; TIFFError ("", "\tFirst and last bytes before and after masking:\n\t%s\n\n", bitarray); #endif dst_offset++; } } else /* each destination byte will have to be built from two source bytes*/ { #ifdef DEBUG2 TIFFError ("", " Unalligned data src offset: %8d, Dst offset: %8d\n", offset1 , dst_offset); #endif for (j = 0; j <= full_bytes; j++) { bytebuff1 = src_buff[offset1 + j] & ((unsigned char)255 >> shift1); bytebuff2 = src_buff[offset1 + j + 1] & ((unsigned char)255 << (7 - shift1)); sect_buff[dst_offset + j] = (bytebuff1 << shift1) | (bytebuff2 >> (8 - shift1)); } #ifdef DEBUG2 sprintf(&bitarray[18], "\n"); sprintf(&bitarray[19], "\t"); for (j = 20, k = 7; j < 28; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[28] = ' '; bitarray[29] = ' '; #endif dst_offset += full_bytes; if (trailing_bits != 0) { #ifdef DEBUG2 TIFFError ("", " Trailing bits src offset: %8d, Dst offset: %8d\n", offset1 + full_bytes, dst_offset); #endif if (shift2 > shift1) { bytebuff1 = src_buff[offset1 + full_bytes] & ((unsigned char)255 << (7 - shift2)); bytebuff2 = bytebuff1 & ((unsigned char)255 << shift1); sect_buff[dst_offset] = bytebuff2; #ifdef DEBUG2 TIFFError ("", " Shift2 > Shift1\n"); #endif } else { if (shift2 < shift1) { bytebuff2 = ((unsigned char)255 << (shift1 - shift2 - 1)); sect_buff[dst_offset] &= bytebuff2; #ifdef DEBUG2 TIFFError ("", " Shift2 < Shift1\n"); #endif } #ifdef DEBUG2 else TIFFError ("", " Shift2 == Shift1\n"); #endif } } #ifdef DEBUG2 sprintf(&bitarray[28], " "); sprintf(&bitarray[29], " "); for (j = 30, k = 7; j < 38; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[38] = '\0'; TIFFError ("", "\tFirst and last bytes before and after masking:\n\t%s\n\n", bitarray); #endif dst_offset++; } } } return (0); } /* end extractImageSection */ static int writeSelections(TIFF *in, TIFF **out, struct crop_mask *crop, struct image_data *image, struct dump_opts *dump, struct buffinfo seg_buffs[], char *mp, char *filename, unsigned int *page, unsigned int total_pages) { int i, page_count; int autoindex = 0; unsigned char *crop_buff = NULL; /* Where we open a new file depends on the export mode */ switch (crop->exp_mode) { case ONE_FILE_COMPOSITE: /* Regions combined into single image */ autoindex = 0; crop_buff = seg_buffs[0].buffer; if (update_output_file (out, mp, autoindex, filename, page)) return (1); page_count = total_pages; if (writeCroppedImage(in, *out, image, dump, crop->combined_width, crop->combined_length, crop_buff, *page, total_pages)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } break; case ONE_FILE_SEPARATED: /* Regions as separated images */ autoindex = 0; if (update_output_file (out, mp, autoindex, filename, page)) return (1); page_count = crop->selections * total_pages; for (i = 0; i < crop->selections; i++) { crop_buff = seg_buffs[i].buffer; if (writeCroppedImage(in, *out, image, dump, crop->regionlist[i].width, crop->regionlist[i].length, crop_buff, *page, page_count)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } } break; case FILE_PER_IMAGE_COMPOSITE: /* Regions as composite image */ autoindex = 1; if (update_output_file (out, mp, autoindex, filename, page)) return (1); crop_buff = seg_buffs[0].buffer; if (writeCroppedImage(in, *out, image, dump, crop->combined_width, crop->combined_length, crop_buff, *page, total_pages)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } break; case FILE_PER_IMAGE_SEPARATED: /* Regions as separated images */ autoindex = 1; page_count = crop->selections; if (update_output_file (out, mp, autoindex, filename, page)) return (1); for (i = 0; i < crop->selections; i++) { crop_buff = seg_buffs[i].buffer; /* Write the current region to the current file */ if (writeCroppedImage(in, *out, image, dump, crop->regionlist[i].width, crop->regionlist[i].length, crop_buff, *page, page_count)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } } break; case FILE_PER_SELECTION: autoindex = 1; page_count = 1; for (i = 0; i < crop->selections; i++) { if (update_output_file (out, mp, autoindex, filename, page)) return (1); crop_buff = seg_buffs[i].buffer; /* Write the current region to the current file */ if (writeCroppedImage(in, *out, image, dump, crop->regionlist[i].width, crop->regionlist[i].length, crop_buff, *page, page_count)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } } break; default: return (1); } return (0); } /* end writeRegions */ static int writeImageSections(TIFF *in, TIFF *out, struct image_data *image, struct pagedef *page, struct pageseg *sections, struct dump_opts * dump, unsigned char *src_buff, unsigned char **sect_buff_ptr) { double hres, vres; uint32 i, k, width, length, sectsize; unsigned char *sect_buff = *sect_buff_ptr; hres = page->hres; vres = page->vres; #ifdef DEBUG TIFFError("", "Writing %d sections for each original page. Hres: %3.2f Vres: %3.2f\n", page->rows * page->cols, hres, vres); #endif k = page->cols * page->rows; if ((k < 1) || (k > MAX_SECTIONS)) { TIFFError("writeImageSections", "%d Rows and Columns exceed maximum sections\nIncrease resolution or reduce sections", k); return (-1); } for (i = 0; i < k; i++) { width = sections[i].x2 - sections[i].x1 + 1; length = sections[i].y2 - sections[i].y1 + 1; sectsize = (uint32) ceil((width * image->bps + 7) / (double)8) * image->spp * length; /* allocate a buffer if we don't have one already */ if (createImageSection(sectsize, sect_buff_ptr)) { TIFFError("writeImageSections", "Unable to allocate section buffer"); exit (-1); } sect_buff = *sect_buff_ptr; #ifdef DEBUG TIFFError ("", "\nSection: %d, Width: %4d, Length: %4d, x1: %4d x2: %4d y1: %4d y2: %4d\n", i + 1, width, length, sections[i].x1, sections[i].x2, sections[i].y1, sections[i].y2); #endif if (extractImageSection (image, &sections[i], src_buff, sect_buff)) { TIFFError("writeImageSections", "Unable to extract image sections"); exit (-1); } /* call the write routine here instead of outside the loop */ if (writeSingleSection(in, out, image, dump, width, length, hres, vres, sect_buff)) { TIFFError("writeImageSections", "Unable to write image section"); exit (-1); } } return (0); } /* end writeImageSections */ /* Code in this function is heavily indebted to code in tiffcp * with modifications by Richard Nolde to handle orientation correctly. */ static int writeSingleSection(TIFF *in, TIFF *out, struct image_data *image, struct dump_opts *dump, uint32 width, uint32 length, double hres, double vres, unsigned char *sect_buff) { uint16 bps, spp; struct cpTag* p; #ifdef DEBUG TIFFError ("", "\nWriting single section: Width %d Length: %d Hres: %4.1f, Vres: %4.1f\n\n", width, length, hres, vres); #endif TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width); TIFFSetField(out, TIFFTAG_IMAGELENGTH, length); CopyField(TIFFTAG_BITSPERSAMPLE, bps); CopyField(TIFFTAG_SAMPLESPERPIXEL, spp); if (compression != (uint16)-1) TIFFSetField(out, TIFFTAG_COMPRESSION, compression); else CopyField(TIFFTAG_COMPRESSION, compression); if (compression == COMPRESSION_JPEG) { uint16 input_compression, input_photometric; if (TIFFGetField(in, TIFFTAG_COMPRESSION, &input_compression) && input_compression == COMPRESSION_JPEG) { TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } if (TIFFGetField(in, TIFFTAG_PHOTOMETRIC, &input_photometric)) { if(input_photometric == PHOTOMETRIC_RGB) { if (jpegcolormode == JPEGCOLORMODE_RGB) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB); } else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric); } } else { if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric); } if (fillorder != 0) TIFFSetField(out, TIFFTAG_FILLORDER, fillorder); else CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT); /* The loadimage function reads input orientation and sets * image->orientation. The correct_image_orientation function * applies the required rotation and mirror operations to * present the data in TOPLEFT orientation and updates * image->orientation if any transforms are performed, * as per EXIF standard. Original tiffcp code removed here. */ TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation); /* * Choose tiles/strip for the output image according to * the command line arguments (-tiles, -strips) and the * structure of the input image. */ if (outtiled == -1) outtiled = TIFFIsTiled(in); if (outtiled) { /* * Setup output file's tile width&height. If either * is not specified, use either the value from the * input image or, if nothing is defined, use the * library default. */ if (tilewidth == (uint32) -1) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth); if (tilelength == (uint32) -1) TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength); if (tilewidth > width) tilewidth = width; if (tilelength > length) tilelength = length; TIFFDefaultTileSize(out, &tilewidth, &tilelength); TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth); TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength); } else { /* * RowsPerStrip is left unspecified: use either the * value from the input image or, if nothing is defined, * use the library default. */ if (rowsperstrip == (uint32) 0) { if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip)) { rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip); } if (rowsperstrip > length && rowsperstrip != (uint32)-1) rowsperstrip = length; } else if (rowsperstrip == (uint32) -1) rowsperstrip = length; TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip); } if (config != (uint16) -1) TIFFSetField(out, TIFFTAG_PLANARCONFIG, config); else CopyField(TIFFTAG_PLANARCONFIG, config); if (spp <= 4) CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT); CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT); /* SMinSampleValue & SMaxSampleValue */ switch (compression) { case COMPRESSION_JPEG: TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality); TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode); break; case COMPRESSION_LZW: case COMPRESSION_ADOBE_DEFLATE: case COMPRESSION_DEFLATE: if (predictor != (uint16)-1) TIFFSetField(out, TIFFTAG_PREDICTOR, predictor); else CopyField(TIFFTAG_PREDICTOR, predictor); break; case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: if (compression == COMPRESSION_CCITTFAX3) { if (g3opts != (uint32) -1) TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts); else CopyField(TIFFTAG_GROUP3OPTIONS, g3opts); } else CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG); CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG); CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII); break; } { uint32 len32; void** data; if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data)) TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data); } { uint16 ninks; const char* inknames; if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) { TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks); if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) { int inknameslen = strlen(inknames) + 1; const char* cp = inknames; while (ninks > 1) { cp = strchr(cp, '\0'); if (cp) { cp++; inknameslen += (strlen(cp) + 1); } ninks--; } TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames); } } } { unsigned short pg0, pg1; if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) { if (pageNum < 0) /* only one input file */ TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1); else TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0); } } for (p = tags; p < &tags[NTAGS]; p++) CopyTag(p->tag, p->count, p->type); /* Update these since they are overwritten from input res by loop above */ TIFFSetField(out, TIFFTAG_XRESOLUTION, (float)hres); TIFFSetField(out, TIFFTAG_YRESOLUTION, (float)vres); /* Compute the tile or strip dimensions and write to disk */ if (outtiled) { if (config == PLANARCONFIG_CONTIG) { writeBufferToContigTiles (out, sect_buff, length, width, spp); } else writeBufferToSeparateTiles (out, sect_buff, length, width, spp, dump); } else { if (config == PLANARCONFIG_CONTIG) { writeBufferToContigStrips (out, sect_buff, length, width, spp); } else { writeBufferToSeparateStrips(out, sect_buff, length, width, spp, dump); } } if (!TIFFWriteDirectory(out)) { TIFFClose(out); return (-1); } return (0); } /* end writeSingleSection */ /* Create a buffer to write one section at a time */ static int createImageSection(uint32 sectsize, unsigned char **sect_buff_ptr) { unsigned char *sect_buff = NULL; unsigned char *new_buff = NULL; static uint32 prev_sectsize = 0; sect_buff = *sect_buff_ptr; if (!sect_buff) { sect_buff = (unsigned char *)_TIFFmalloc(sectsize); *sect_buff_ptr = sect_buff; _TIFFmemset(sect_buff, 0, sectsize); } else { if (prev_sectsize < sectsize) { new_buff = _TIFFrealloc(sect_buff, sectsize); if (!new_buff) { free (sect_buff); sect_buff = (unsigned char *)_TIFFmalloc(sectsize); } else sect_buff = new_buff; _TIFFmemset(sect_buff, 0, sectsize); } } if (!sect_buff) { TIFFError("createImageSection", "Unable to allocate/reallocate section buffer"); return (-1); } prev_sectsize = sectsize; *sect_buff_ptr = sect_buff; return (0); } /* end createImageSection */ /* Process selections defined by regions, zones, margins, or fixed sized areas */ static int processCropSelections(struct image_data *image, struct crop_mask *crop, unsigned char **read_buff_ptr, struct buffinfo seg_buffs[]) { int i; uint32 width, length, total_width, total_length; tsize_t cropsize; unsigned char *crop_buff = NULL; unsigned char *read_buff = NULL; unsigned char *next_buff = NULL; tsize_t prev_cropsize = 0; read_buff = *read_buff_ptr; if (crop->img_mode == COMPOSITE_IMAGES) { cropsize = crop->bufftotal; crop_buff = seg_buffs[0].buffer; if (!crop_buff) crop_buff = (unsigned char *)_TIFFmalloc(cropsize); else { prev_cropsize = seg_buffs[0].size; if (prev_cropsize < cropsize) { next_buff = _TIFFrealloc(crop_buff, cropsize); if (! next_buff) { _TIFFfree (crop_buff); crop_buff = (unsigned char *)_TIFFmalloc(cropsize); } else crop_buff = next_buff; } } if (!crop_buff) { TIFFError("processCropSelections", "Unable to allocate/reallocate crop buffer"); return (-1); } _TIFFmemset(crop_buff, 0, cropsize); seg_buffs[0].buffer = crop_buff; seg_buffs[0].size = cropsize; /* Checks for matching width or length as required */ if (extractCompositeRegions(image, crop, read_buff, crop_buff) != 0) return (1); if (crop->crop_mode & CROP_INVERT) { switch (crop->photometric) { /* Just change the interpretation */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: image->photometric = crop->photometric; break; case INVERT_DATA_ONLY: case INVERT_DATA_AND_TAG: if (invertImage(image->photometric, image->spp, image->bps, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("processCropSelections", "Failed to invert colorspace for composite regions"); return (-1); } if (crop->photometric == INVERT_DATA_AND_TAG) { switch (image->photometric) { case PHOTOMETRIC_MINISWHITE: image->photometric = PHOTOMETRIC_MINISBLACK; break; case PHOTOMETRIC_MINISBLACK: image->photometric = PHOTOMETRIC_MINISWHITE; break; default: break; } } break; default: break; } } /* Mirror and Rotate will not work with multiple regions unless they are the same width */ if (crop->crop_mode & CROP_MIRROR) { if (mirrorImage(image->spp, image->bps, crop->mirror, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("processCropSelections", "Failed to mirror composite regions %s", (crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically"); return (-1); } } if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */ { if (rotateImage(crop->rotation, image, &crop->combined_width, &crop->combined_length, &crop_buff)) { TIFFError("processCropSelections", "Failed to rotate composite regions by %d degrees", crop->rotation); return (-1); } seg_buffs[0].buffer = crop_buff; seg_buffs[0].size = (((crop->combined_width * image->bps + 7 ) / 8) * image->spp) * crop->combined_length; } } else /* Separated Images */ { total_width = total_length = 0; for (i = 0; i < crop->selections; i++) { cropsize = crop->bufftotal; crop_buff = seg_buffs[i].buffer; if (!crop_buff) crop_buff = (unsigned char *)_TIFFmalloc(cropsize); else { prev_cropsize = seg_buffs[0].size; if (prev_cropsize < cropsize) { next_buff = _TIFFrealloc(crop_buff, cropsize); if (! next_buff) { _TIFFfree (crop_buff); crop_buff = (unsigned char *)_TIFFmalloc(cropsize); } else crop_buff = next_buff; } } if (!crop_buff) { TIFFError("processCropSelections", "Unable to allocate/reallocate crop buffer"); return (-1); } _TIFFmemset(crop_buff, 0, cropsize); seg_buffs[i].buffer = crop_buff; seg_buffs[i].size = cropsize; if (extractSeparateRegion(image, crop, read_buff, crop_buff, i)) { TIFFError("processCropSelections", "Unable to extract cropped region %d from image", i); return (-1); } width = crop->regionlist[i].width; length = crop->regionlist[i].length; if (crop->crop_mode & CROP_INVERT) { switch (crop->photometric) { /* Just change the interpretation */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: image->photometric = crop->photometric; break; case INVERT_DATA_ONLY: case INVERT_DATA_AND_TAG: if (invertImage(image->photometric, image->spp, image->bps, width, length, crop_buff)) { TIFFError("processCropSelections", "Failed to invert colorspace for region"); return (-1); } if (crop->photometric == INVERT_DATA_AND_TAG) { switch (image->photometric) { case PHOTOMETRIC_MINISWHITE: image->photometric = PHOTOMETRIC_MINISBLACK; break; case PHOTOMETRIC_MINISBLACK: image->photometric = PHOTOMETRIC_MINISWHITE; break; default: break; } } break; default: break; } } if (crop->crop_mode & CROP_MIRROR) { if (mirrorImage(image->spp, image->bps, crop->mirror, width, length, crop_buff)) { TIFFError("processCropSelections", "Failed to mirror crop region %s", (crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically"); return (-1); } } if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */ { if (rotateImage(crop->rotation, image, &crop->regionlist[i].width, &crop->regionlist[i].length, &crop_buff)) { TIFFError("processCropSelections", "Failed to rotate crop region by %d degrees", crop->rotation); return (-1); } total_width += crop->regionlist[i].width; total_length += crop->regionlist[i].length; crop->combined_width = total_width; crop->combined_length = total_length; seg_buffs[i].buffer = crop_buff; seg_buffs[i].size = (((crop->regionlist[i].width * image->bps + 7 ) / 8) * image->spp) * crop->regionlist[i].length; } } } return (0); } /* end processCropSelections */ /* Copy the crop section of the data from the current image into a buffer * and adjust the IFD values to reflect the new size. If no cropping is * required, use the origial read buffer as the crop buffer. * * There is quite a bit of redundancy between this routine and the more * specialized processCropSelections, but this provides * the most optimized path when no Zones or Regions are required. */ static int createCroppedImage(struct image_data *image, struct crop_mask *crop, unsigned char **read_buff_ptr, unsigned char **crop_buff_ptr) { tsize_t cropsize; unsigned char *read_buff = NULL; unsigned char *crop_buff = NULL; unsigned char *new_buff = NULL; static tsize_t prev_cropsize = 0; read_buff = *read_buff_ptr; /* process full image, no crop buffer needed */ crop_buff = read_buff; *crop_buff_ptr = read_buff; crop->combined_width = image->width; crop->combined_length = image->length; cropsize = crop->bufftotal; crop_buff = *crop_buff_ptr; if (!crop_buff) { crop_buff = (unsigned char *)_TIFFmalloc(cropsize); *crop_buff_ptr = crop_buff; _TIFFmemset(crop_buff, 0, cropsize); prev_cropsize = cropsize; } else { if (prev_cropsize < cropsize) { new_buff = _TIFFrealloc(crop_buff, cropsize); if (!new_buff) { free (crop_buff); crop_buff = (unsigned char *)_TIFFmalloc(cropsize); } else crop_buff = new_buff; _TIFFmemset(crop_buff, 0, cropsize); } } if (!crop_buff) { TIFFError("createCroppedImage", "Unable to allocate/reallocate crop buffer"); return (-1); } *crop_buff_ptr = crop_buff; if (crop->crop_mode & CROP_INVERT) { switch (crop->photometric) { /* Just change the interpretation */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: image->photometric = crop->photometric; break; case INVERT_DATA_ONLY: case INVERT_DATA_AND_TAG: if (invertImage(image->photometric, image->spp, image->bps, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("createCroppedImage", "Failed to invert colorspace for image or cropped selection"); return (-1); } if (crop->photometric == INVERT_DATA_AND_TAG) { switch (image->photometric) { case PHOTOMETRIC_MINISWHITE: image->photometric = PHOTOMETRIC_MINISBLACK; break; case PHOTOMETRIC_MINISBLACK: image->photometric = PHOTOMETRIC_MINISWHITE; break; default: break; } } break; default: break; } } if (crop->crop_mode & CROP_MIRROR) { if (mirrorImage(image->spp, image->bps, crop->mirror, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("createCroppedImage", "Failed to mirror image or cropped selection %s", (crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically"); return (-1); } } if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */ { if (rotateImage(crop->rotation, image, &crop->combined_width, &crop->combined_length, crop_buff_ptr)) { TIFFError("createCroppedImage", "Failed to rotate image or cropped selection by %d degrees", crop->rotation); return (-1); } } if (crop_buff == read_buff) /* we used the read buffer for the crop buffer */ *read_buff_ptr = NULL; /* so we don't try to free it later */ return (0); } /* end createCroppedImage */ /* The code in this function is heavily indebted to code from tiffcp. */ static int writeCroppedImage(TIFF *in, TIFF *out, struct image_data *image, struct dump_opts *dump, uint32 width, uint32 length, unsigned char *crop_buff, int pagenum, int total_pages) { uint16 bps, spp; struct cpTag* p; TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width); TIFFSetField(out, TIFFTAG_IMAGELENGTH, length); CopyField(TIFFTAG_BITSPERSAMPLE, bps); CopyField(TIFFTAG_SAMPLESPERPIXEL, spp); if (compression != (uint16)-1) TIFFSetField(out, TIFFTAG_COMPRESSION, compression); else CopyField(TIFFTAG_COMPRESSION, compression); if (compression == COMPRESSION_JPEG) { uint16 input_compression, input_photometric; if (TIFFGetField(in, TIFFTAG_COMPRESSION, &input_compression) && input_compression == COMPRESSION_JPEG) { TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } if (TIFFGetField(in, TIFFTAG_PHOTOMETRIC, &input_photometric)) { if(input_photometric == PHOTOMETRIC_RGB) { if (jpegcolormode == JPEGCOLORMODE_RGB) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB); } else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric); } } else { if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric); } if (fillorder != 0) TIFFSetField(out, TIFFTAG_FILLORDER, fillorder); else CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT); /* The loadimage function reads input orientation and sets * image->orientation. The correct_image_orientation function * applies the required rotation and mirror operations to * present the data in TOPLEFT orientation and updates * image->orientation if any transforms are performed, * as per EXIF standard. */ TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation); /* * Choose tiles/strip for the output image according to * the command line arguments (-tiles, -strips) and the * structure of the input image. */ if (outtiled == -1) outtiled = TIFFIsTiled(in); if (outtiled) { /* * Setup output file's tile width&height. If either * is not specified, use either the value from the * input image or, if nothing is defined, use the * library default. */ if (tilewidth == (uint32) -1) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth); if (tilelength == (uint32) -1) TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength); if (tilewidth > width) tilewidth = width; if (tilelength > length) tilelength = length; TIFFDefaultTileSize(out, &tilewidth, &tilelength); TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth); TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength); } else { /* * RowsPerStrip is left unspecified: use either the * value from the input image or, if nothing is defined, * use the library default. */ if (rowsperstrip == (uint32) 0) { if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip)) { rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip); } if (rowsperstrip > length) rowsperstrip = length; } else if (rowsperstrip == (uint32) -1) rowsperstrip = length; TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip); } if (config != (uint16) -1) TIFFSetField(out, TIFFTAG_PLANARCONFIG, config); else CopyField(TIFFTAG_PLANARCONFIG, config); if (spp <= 4) CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT); CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT); /* SMinSampleValue & SMaxSampleValue */ switch (compression) { case COMPRESSION_JPEG: TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality); TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode); break; case COMPRESSION_LZW: case COMPRESSION_ADOBE_DEFLATE: case COMPRESSION_DEFLATE: if (predictor != (uint16)-1) TIFFSetField(out, TIFFTAG_PREDICTOR, predictor); else CopyField(TIFFTAG_PREDICTOR, predictor); break; case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: if (compression == COMPRESSION_CCITTFAX3) { if (g3opts != (uint32) -1) TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts); else CopyField(TIFFTAG_GROUP3OPTIONS, g3opts); } else CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG); CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG); CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII); break; } { uint32 len32; void** data; if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data)) TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data); } { uint16 ninks; const char* inknames; if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) { TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks); if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) { int inknameslen = strlen(inknames) + 1; const char* cp = inknames; while (ninks > 1) { cp = strchr(cp, '\0'); if (cp) { cp++; inknameslen += (strlen(cp) + 1); } ninks--; } TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames); } } } { unsigned short pg0, pg1; if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) { TIFFSetField(out, TIFFTAG_PAGENUMBER, pagenum, total_pages); } } for (p = tags; p < &tags[NTAGS]; p++) CopyTag(p->tag, p->count, p->type); /* Compute the tile or strip dimensions and write to disk */ if (outtiled) { if (config == PLANARCONFIG_CONTIG) { writeBufferToContigTiles (out, crop_buff, length, width, spp); } else writeBufferToSeparateTiles (out, crop_buff, length, width, spp, dump); } else { if (config == PLANARCONFIG_CONTIG) { writeBufferToContigStrips (out, crop_buff, length, width, spp); } else { writeBufferToSeparateStrips(out, crop_buff, length, width, spp, dump); } } if (!TIFFWriteDirectory(out)) { TIFFClose(out); return (-1); } return (0); } /* end writeCroppedImage */ static int rotateContigSamples8bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0; uint32 src_byte = 0, src_bit = 0; uint32 row, rowsize = 0, bit_offset = 0; uint8 matchbits = 0, maskbits = 0; uint8 buff1 = 0, buff2 = 0; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples8bits","Invalid src or destination buffer"); return (1); } rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint8)-1 >> ( 8 - bps); buff1 = buff2 = 0; for (row = 0; row < length ; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (8 - src_bit - bps); buff1 = ((*next) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; } else { buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; } return (0); } /* end rotateContigSamples8bits */ static int rotateContigSamples16bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0; uint32 row, rowsize, bit_offset; uint32 src_byte = 0, src_bit = 0; uint16 matchbits = 0, maskbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; uint8 swapbuff[2]; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples16bits","Invalid src or destination buffer"); return (1); } rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint16)-1 >> (16 - bps); buff1 = buff2 = 0; for (row = 0; row < length; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (16 - src_bit - bps); if (little_endian) { swapbuff[1] = *next; swapbuff[0] = *(next + 1); } else { swapbuff[0] = *next; swapbuff[1] = *(next + 1); } buff1 = *((uint16 *)swapbuff); buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } else { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; } return (0); } /* end rotateContigSamples16bits */ static int rotateContigSamples24bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0; uint32 row, rowsize, bit_offset; uint32 src_byte = 0, src_bit = 0; uint32 matchbits = 0, maskbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; uint8 swapbuff[4]; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples24bits","Invalid src or destination buffer"); return (1); } rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint32)-1 >> (32 - bps); buff1 = buff2 = 0; for (row = 0; row < length; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (32 - src_bit - bps); if (little_endian) { swapbuff[3] = *next; swapbuff[2] = *(next + 1); swapbuff[1] = *(next + 2); swapbuff[0] = *(next + 3); } else { swapbuff[0] = *next; swapbuff[1] = *(next + 1); swapbuff[2] = *(next + 2); swapbuff[3] = *(next + 3); } buff1 = *((uint32 *)swapbuff); buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 16) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end rotateContigSamples24bits */ static int rotateContigSamples32bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0, shift_width = 0; int bytes_per_sample, bytes_per_pixel; uint32 row, rowsize, bit_offset; uint32 src_byte, src_bit; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; unsigned char swapbuff1[4]; unsigned char swapbuff2[4]; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples24bits","Invalid src or destination buffer"); return (1); } bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint64)-1 >> (64 - bps); buff1 = buff2 = 0; for (row = 0; row < length; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (64 - src_bit - bps); if (little_endian) { swapbuff1[3] = *next; swapbuff1[2] = *(next + 1); swapbuff1[1] = *(next + 2); swapbuff1[0] = *(next + 3); } else { swapbuff1[0] = *next; swapbuff1[1] = *(next + 1); swapbuff1[2] = *(next + 2); swapbuff1[3] = *(next + 3); } longbuff1 = *((uint32 *)swapbuff1); memset (swapbuff2, '\0', sizeof(swapbuff2)); if (little_endian) { swapbuff2[3] = *next; swapbuff2[2] = *(next + 1); swapbuff2[1] = *(next + 2); swapbuff2[0] = *(next + 3); } else { swapbuff2[0] = *next; swapbuff2[1] = *(next + 1); swapbuff2[2] = *(next + 2); swapbuff2[3] = *(next + 3); } longbuff2 = *((uint32 *)swapbuff2); buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); if (ready_bits < 32) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end rotateContigSamples32bits */ /* Rotate an image by a multiple of 90 degrees clockwise */ static int rotateImage(uint16 rotation, struct image_data *image, uint32 *img_width, uint32 *img_length, unsigned char **ibuff_ptr) { int shift_width; uint32 bytes_per_pixel, bytes_per_sample; uint32 row, rowsize, src_offset, dst_offset; uint32 i, col, width, length; uint32 colsize, buffsize, col_offset, pix_offset; unsigned char *ibuff; unsigned char *src; unsigned char *dst; uint16 spp, bps; float res_temp; unsigned char *rbuff = NULL; width = *img_width; length = *img_length; spp = image->spp; bps = image->bps; rowsize = ((bps * spp * width) + 7) / 8; colsize = ((bps * spp * length) + 7) / 8; if ((colsize * width) > (rowsize * length)) buffsize = (colsize + 1) * width; else buffsize = (rowsize + 1) * length; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; switch (rotation) { case 0: case 360: return (0); case 90: case 180: case 270: break; default: TIFFError("rotateImage", "Invalid rotation angle %d", rotation); return (-1); } if (!(rbuff = (unsigned char *)_TIFFmalloc(buffsize))) { TIFFError("rotateImage", "Unable to allocate rotation buffer of %1u bytes", buffsize); return (-1); } _TIFFmemset(rbuff, '\0', buffsize); ibuff = *ibuff_ptr; switch (rotation) { case 180: if ((bps % 8) == 0) /* byte alligned data */ { src = ibuff; pix_offset = (spp * bps) / 8; for (row = 0; row < length; row++) { dst_offset = (length - row - 1) * rowsize; for (col = 0; col < width; col++) { col_offset = (width - col - 1) * pix_offset; dst = rbuff + dst_offset + col_offset; for (i = 0; i < bytes_per_pixel; i++) *dst++ = *src++; } } } else { /* non 8 bit per sample data */ for (row = 0; row < length; row++) { src_offset = row * rowsize; dst_offset = (length - row - 1) * rowsize; src = ibuff + src_offset; dst = rbuff + dst_offset; switch (shift_width) { case 1: if (reverseSamples8bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 2: if (reverseSamples16bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 3: if (reverseSamples24bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 4: case 5: if (reverseSamples32bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; default: TIFFError("rotateImage","Unsupported bit depth %d", bps); _TIFFfree(rbuff); return (-1); } } } _TIFFfree(ibuff); *(ibuff_ptr) = rbuff; break; case 90: if ((bps % 8) == 0) /* byte aligned data */ { for (col = 0; col < width; col++) { src_offset = ((length - 1) * rowsize) + (col * bytes_per_pixel); dst_offset = col * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; for (row = length; row > 0; row--) { for (i = 0; i < bytes_per_pixel; i++) *dst++ = *(src + i); src -= rowsize; } } } else { /* non 8 bit per sample data */ for (col = 0; col < width; col++) { src_offset = (length - 1) * rowsize; dst_offset = col * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; switch (shift_width) { case 1: if (rotateContigSamples8bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 2: if (rotateContigSamples16bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 3: if (rotateContigSamples24bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 4: case 5: if (rotateContigSamples32bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; default: TIFFError("rotateImage","Unsupported bit depth %d", bps); _TIFFfree(rbuff); return (-1); } } } _TIFFfree(ibuff); *(ibuff_ptr) = rbuff; *img_width = length; *img_length = width; image->width = length; image->length = width; res_temp = image->xres; image->xres = image->yres; image->yres = res_temp; break; case 270: if ((bps % 8) == 0) /* byte aligned data */ { for (col = 0; col < width; col++) { src_offset = col * bytes_per_pixel; dst_offset = (width - col - 1) * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; for (row = length; row > 0; row--) { for (i = 0; i < bytes_per_pixel; i++) *dst++ = *(src + i); src += rowsize; } } } else { /* non 8 bit per sample data */ for (col = 0; col < width; col++) { src_offset = 0; dst_offset = (width - col - 1) * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; switch (shift_width) { case 1: if (rotateContigSamples8bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 2: if (rotateContigSamples16bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 3: if (rotateContigSamples24bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 4: case 5: if (rotateContigSamples32bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; default: TIFFError("rotateImage","Unsupported bit depth %d", bps); _TIFFfree(rbuff); return (-1); } } } _TIFFfree(ibuff); *(ibuff_ptr) = rbuff; *img_width = length; *img_length = width; image->width = length; image->length = width; res_temp = image->xres; image->xres = image->yres; image->yres = res_temp; break; default: break; } return (0); } /* end rotateImage */ static int reverseSamples8bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0; uint32 col; uint32 src_byte, src_bit; uint32 bit_offset = 0; uint8 matchbits = 0, maskbits = 0; uint8 buff1 = 0, buff2 = 0; unsigned char *src; unsigned char *dst; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSamples8bits","Invalid image or work buffer"); return (1); } ready_bits = 0; maskbits = (uint8)-1 >> ( 8 - bps); dst = obuff; for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; matchbits = maskbits << (8 - src_bit - bps); buff1 = ((*src) & matchbits) << (src_bit); if (ready_bits < 8) buff2 = (buff2 | (buff1 >> ready_bits)); else /* If we have a full buffer's worth, write it out */ { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; } ready_bits += bps; } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; } return (0); } /* end reverseSamples8bits */ static int reverseSamples16bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0; uint32 col; uint32 src_byte = 0, src_bit = 0; uint32 bit_offset = 0; uint16 matchbits = 0, maskbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; unsigned char *src; unsigned char *dst; unsigned char swapbuff[2]; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSample16bits","Invalid image or work buffer"); return (1); } ready_bits = 0; maskbits = (uint16)-1 >> (16 - bps); dst = obuff; for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; matchbits = maskbits << (16 - src_bit - bps); if (little_endian) { swapbuff[1] = *src; swapbuff[0] = *(src + 1); } else { swapbuff[0] = *src; swapbuff[1] = *(src + 1); } buff1 = *((uint16 *)swapbuff); buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 8) { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } ready_bits += bps; } } if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; } return (0); } /* end reverseSamples16bits */ static int reverseSamples24bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0; uint32 col; uint32 src_byte = 0, src_bit = 0; uint32 bit_offset = 0; uint32 matchbits = 0, maskbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; unsigned char *src; unsigned char *dst; unsigned char swapbuff[4]; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSamples24bits","Invalid image or work buffer"); return (1); } ready_bits = 0; maskbits = (uint32)-1 >> (32 - bps); dst = obuff; for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; matchbits = maskbits << (32 - src_bit - bps); if (little_endian) { swapbuff[3] = *src; swapbuff[2] = *(src + 1); swapbuff[1] = *(src + 2); swapbuff[0] = *(src + 3); } else { swapbuff[0] = *src; swapbuff[1] = *(src + 1); swapbuff[2] = *(src + 2); swapbuff[3] = *(src + 3); } buff1 = *((uint32 *)swapbuff); buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 16) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end reverseSamples24bits */ static int reverseSamples32bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0, shift_width = 0; int bytes_per_sample, bytes_per_pixel; uint32 bit_offset; uint32 src_byte = 0, src_bit = 0; uint32 col; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; unsigned char *src; unsigned char *dst; unsigned char swapbuff1[4]; unsigned char swapbuff2[4]; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSamples32bits","Invalid image or work buffer"); return (1); } ready_bits = 0; maskbits = (uint64)-1 >> (64 - bps); dst = obuff; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; matchbits = maskbits << (64 - src_bit - bps); if (little_endian) { swapbuff1[3] = *src; swapbuff1[2] = *(src + 1); swapbuff1[1] = *(src + 2); swapbuff1[0] = *(src + 3); } else { swapbuff1[0] = *src; swapbuff1[1] = *(src + 1); swapbuff1[2] = *(src + 2); swapbuff1[3] = *(src + 3); } longbuff1 = *((uint32 *)swapbuff1); memset (swapbuff2, '\0', sizeof(swapbuff2)); if (little_endian) { swapbuff2[3] = *src; swapbuff2[2] = *(src + 1); swapbuff2[1] = *(src + 2); swapbuff2[0] = *(src + 3); } else { swapbuff2[0] = *src; swapbuff2[1] = *(src + 1); swapbuff2[2] = *(src + 2); swapbuff2[3] = *(src + 3); } longbuff2 = *((uint32 *)swapbuff2); buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); if (ready_bits < 32) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end reverseSamples32bits */ static int reverseSamplesBytes (uint16 spp, uint16 bps, uint32 width, uint8 *src, uint8 *dst) { int i; uint32 col, bytes_per_pixel, col_offset; uint8 bytebuff1; unsigned char swapbuff[32]; if ((src == NULL) || (dst == NULL)) { TIFFError("reverseSamplesBytes","Invalid input or output buffer"); return (1); } bytes_per_pixel = ((bps * spp) + 7) / 8; switch (bps / 8) { case 8: /* Use memcpy for multiple bytes per sample data */ case 4: case 3: case 2: for (col = 0; col < (width / 2); col++) { col_offset = col * bytes_per_pixel; _TIFFmemcpy (swapbuff, src + col_offset, bytes_per_pixel); _TIFFmemcpy (src + col_offset, dst - col_offset - bytes_per_pixel, bytes_per_pixel); _TIFFmemcpy (dst - col_offset - bytes_per_pixel, swapbuff, bytes_per_pixel); } break; case 1: /* Use byte copy only for single byte per sample data */ for (col = 0; col < (width / 2); col++) { for (i = 0; i < spp; i++) { bytebuff1 = *src; *src++ = *(dst - spp + i); *(dst - spp + i) = bytebuff1; } dst -= spp; } break; default: TIFFError("reverseSamplesBytes","Unsupported bit depth %d", bps); return (1); } return (0); } /* end reverseSamplesBytes */ /* Mirror an image horizontally or vertically */ static int mirrorImage(uint16 spp, uint16 bps, uint16 mirror, uint32 width, uint32 length, unsigned char *ibuff) { int shift_width; uint32 bytes_per_pixel, bytes_per_sample; uint32 row, rowsize, row_offset; unsigned char *line_buff = NULL; unsigned char *src; unsigned char *dst; src = ibuff; rowsize = ((width * bps * spp) + 7) / 8; switch (mirror) { case MIRROR_BOTH: case MIRROR_VERT: line_buff = (unsigned char *)_TIFFmalloc(rowsize); if (line_buff == NULL) { TIFFError ("mirrorImage", "Unable to allocate mirror line buffer of %1u bytes", rowsize); return (-1); } dst = ibuff + (rowsize * (length - 1)); for (row = 0; row < length / 2; row++) { _TIFFmemcpy(line_buff, src, rowsize); _TIFFmemcpy(src, dst, rowsize); _TIFFmemcpy(dst, line_buff, rowsize); src += (rowsize); dst -= (rowsize); } if (line_buff) _TIFFfree(line_buff); if (mirror == MIRROR_VERT) break; case MIRROR_HORIZ : if ((bps % 8) == 0) /* byte alligned data */ { for (row = 0; row < length; row++) { row_offset = row * rowsize; src = ibuff + row_offset; dst = ibuff + row_offset + rowsize; if (reverseSamplesBytes(spp, bps, width, src, dst)) { return (-1); } } } else { /* non 8 bit per sample data */ if (!(line_buff = (unsigned char *)_TIFFmalloc(rowsize + 1))) { TIFFError("mirrorImage", "Unable to allocate mirror line buffer"); return (-1); } bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; for (row = 0; row < length; row++) { row_offset = row * rowsize; src = ibuff + row_offset; _TIFFmemset (line_buff, '\0', rowsize); switch (shift_width) { case 1: if (reverseSamples8bits(spp, bps, width, src, line_buff)) { _TIFFfree(line_buff); return (-1); } _TIFFmemcpy (src, line_buff, rowsize); break; case 2: if (reverseSamples16bits(spp, bps, width, src, line_buff)) { _TIFFfree(line_buff); return (-1); } _TIFFmemcpy (src, line_buff, rowsize); break; case 3: if (reverseSamples24bits(spp, bps, width, src, line_buff)) { _TIFFfree(line_buff); return (-1); } _TIFFmemcpy (src, line_buff, rowsize); break; case 4: case 5: if (reverseSamples32bits(spp, bps, width, src, line_buff)) { _TIFFfree(line_buff); return (-1); } _TIFFmemcpy (src, line_buff, rowsize); break; default: TIFFError("mirrorImage","Unsupported bit depth %d", bps); _TIFFfree(line_buff); return (-1); } } if (line_buff) _TIFFfree(line_buff); } break; default: TIFFError ("mirrorImage", "Invalid mirror axis %d", mirror); return (-1); break; } return (0); } /* Invert the light and dark values for a bilevel or grayscale image */ static int invertImage(uint16 photometric, uint16 spp, uint16 bps, uint32 width, uint32 length, unsigned char *work_buff) { uint32 row, col; unsigned char bytebuff1, bytebuff2, bytebuff3, bytebuff4; unsigned char *src; uint16 *src_uint16; uint32 *src_uint32; if (spp != 1) { TIFFError("invertImage", "Image inversion not supported for more than one sample per pixel"); return (-1); } if (photometric != PHOTOMETRIC_MINISWHITE && photometric != PHOTOMETRIC_MINISBLACK) { TIFFError("invertImage", "Only black and white and grayscale images can be inverted"); return (-1); } src = work_buff; if (src == NULL) { TIFFError ("invertImage", "Invalid crop buffer passed to invertImage"); return (-1); } switch (bps) { case 32: src_uint32 = (uint32 *)src; for (row = 0; row < length; row++) for (col = 0; col < width; col++) { *src_uint32 = (uint32)0xFFFFFFFF - *src_uint32; src_uint32++; } break; case 16: src_uint16 = (uint16 *)src; for (row = 0; row < length; row++) for (col = 0; col < width; col++) { *src_uint16 = (uint16)0xFFFF - *src_uint16; src_uint16++; } break; case 8: for (row = 0; row < length; row++) for (col = 0; col < width; col++) { *src = (uint8)255 - *src; src++; } break; case 4: for (row = 0; row < length; row++) for (col = 0; col < width; col++) { bytebuff1 = 16 - (uint8)(*src & 240 >> 4); bytebuff2 = 16 - (*src & 15); *src = bytebuff1 << 4 & bytebuff2; src++; } break; case 2: for (row = 0; row < length; row++) for (col = 0; col < width; col++) { bytebuff1 = 4 - (uint8)(*src & 192 >> 6); bytebuff2 = 4 - (uint8)(*src & 48 >> 4); bytebuff3 = 4 - (uint8)(*src & 12 >> 2); bytebuff4 = 4 - (uint8)(*src & 3); *src = (bytebuff1 << 6) || (bytebuff2 << 4) || (bytebuff3 << 2) || bytebuff4; src++; } break; case 1: for (row = 0; row < length; row++) for (col = 0; col < width; col += 8 /(spp * bps)) { *src = ~(*src); src++; } break; default: TIFFError("invertImage", "Unsupported bit depth %d", bps); return (-1); } return (0); } /* vim: set ts=8 sts=8 sw=8 noet: */ /* $Id$ */ /* tiffcrop.c -- a port of tiffcp.c extended to include manipulations of * the image data through additional options listed below * * Original code: * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. * * The portions of the current code that are derived from tiffcp are primarly * in the areas of lowlevel reading and writing of scanlines and tiles though * some of the original functions have been extended to support arbitrary bit * depths. These functions are presented at the top of this file. * * Additions (c) Richard Nolde 2006-2009 Last Updated 1/6/2009 * IN NO EVENT SHALL RICHARD NOLDE BE LIABLE FOR ANY SPECIAL, INCIDENTAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * Add support for the options below to extract sections of image(s) * and to modify the whole image or selected portions of each image by * rotations, mirroring, and colorscale/colormap inversion of selected * types of TIFF images when appropriate. Some color model dependent * functions are restricted to bilevel or 8 bit per sample data. * See the man page for the full explanations. * * Options: * -h Display the syntax guide. * -v Report the version and last build date for tiffcrop * -z x1,y1,x2,y2:x3,y3,x4,y4:..xN,yN,xN + 1, yN + 1 * Specify a series of coordinates to define rectangular * regions by the top left and lower right corners. * -e c|d|i|m|s export mode for images and selections from input images * combined All images and selections are written to a single file (default) * with multiple selections from one image combined into a single image * divided All images and selections are written to a single file * with each selection from one image written to a new image * image Each input image is written to a new file (numeric filename sequence) * with multiple selections from the image combined into one image * multiple Each input image is written to a new file (numeric filename sequence) * with each selection from the image written to a new image * separated Individual selections from each image are written to separate files * -U units [in, cm, px ] inches, centimeters or pixels * -H # Set horizontal resolution of output images to # * -V # Set vertical resolution of output images to # * -J # Horizontal margin of output page to # expressed in current * units * -K # Vertical margin of output page to # expressed in current * units * -X # Horizontal dimension of region to extract expressed in current * units * -Y # Vertical dimension of region to extract expressed in current * units * -O orient Orientation for output image, portrait, landscape, auto * -P page Page size for output image segments, eg letter, legal, tabloid, * etc. * -S cols:rows Divide the image into equal sized segments using cols across * and rows down * -E t|l|r|b Edge to use as origin * -m #,#,#,# Margins from edges for selection: top, left, bottom, right * (commas separated) * -Z #:#,#:# Zones of the image designated as zone X of Y, * eg 1:3 would be first of three equal portions measured * from reference edge * -N odd|even|#,#-#,#|last * Select sequences and/or ranges of images within file * to process. The words odd or even may be used to specify * all odd or even numbered images the word last may be used * in place of a number in the sequence to indicate the final * image in the file without knowing how many images there are. * -R # Rotate image or crop selection by 90,180,or 270 degrees * clockwise * -F h|v Flip (mirror) image or crop selection horizontally * or vertically * -I [black|white|data|both] * Invert color space, eg dark to light for bilevel and grayscale images * If argument is white or black, set the PHOTOMETRIC_INTERPRETATION * tag to MinIsBlack or MinIsWhite without altering the image data * If the argument is data or both, the image data are modified: * both inverts the data and the PHOTOMETRIC_INTERPRETATION tag, * data inverts the data but not the PHOTOMETRIC_INTERPRETATION tag * -D input:<filename1>,output:<filename2>,format:<raw|txt>,level:N,debug:N * Dump raw data for input and/or output images to individual files * in raw (binary) format or text (ASCII) representing binary data * as strings of 1s and 0s. The filename arguments are used as stems * from which individual files are created for each image. Text format * includes annotations for image parameters and scanline info. Level * selects which functions dump data, with higher numbers selecting * lower level, scanline level routines. Debug reports a limited set * of messages to monitor progess without enabling dump logs. */ #include "tif_config.h" #include "tiffiop.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <ctype.h> #include <limits.h> #include <sys/stat.h> #include <assert.h> #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #ifdef HAVE_STDINT_H # include <stdint.h> #endif #ifndef HAVE_GETOPT extern int getopt(int, char**, char*); #endif #include "tiffio.h" #if defined(VMS) # define unlink delete #endif #ifndef PATH_MAX #define PATH_MAX 1024 #endif #ifndef streq #define streq(a,b) (strcmp((a),(b)) == 0) #endif #define strneq(a,b,n) (strncmp((a),(b),(n)) == 0) /* NB: the uint32 casts are to silence certain ANSI-C compilers */ #define TIFFhowmany(x, y) ((((uint32)(x))+(((uint32)(y))-1))/((uint32)(y))) #define TIFFhowmany8(x) (((x)&0x07)?((uint32)(x)>>3)+1:(uint32)(x)>>3) #define TRUE 1 #define FALSE 0 /* * Definitions and data structures required to support cropping and image * manipulations. */ #define EDGE_TOP 1 #define EDGE_LEFT 2 #define EDGE_BOTTOM 3 #define EDGE_RIGHT 4 #define EDGE_CENTER 5 #define MIRROR_HORIZ 1 #define MIRROR_VERT 2 #define MIRROR_BOTH 3 #define ROTATECW_90 8 #define ROTATECW_180 16 #define ROTATECW_270 32 #define ROTATE_ANY ROTATECW_90 || ROTATECW_180 || ROTATECW_270 #define CROP_NONE 0 #define CROP_MARGINS 1 #define CROP_WIDTH 2 #define CROP_LENGTH 4 #define CROP_ZONES 8 #define CROP_REGIONS 16 #define CROP_ROTATE 32 #define CROP_MIRROR 64 #define CROP_INVERT 128 /* Modes for writing out images and selections */ #define ONE_FILE_COMPOSITE 0 /* One file, sections combined sections */ #define ONE_FILE_SEPARATED 1 /* One file, sections to new IFDs */ #define FILE_PER_IMAGE_COMPOSITE 2 /* One file per image, combined sections */ #define FILE_PER_IMAGE_SEPARATED 3 /* One file per input image */ #define FILE_PER_SELECTION 4 /* One file per selection */ #define COMPOSITE_IMAGES 0 /* Selections combined into one image */ #define SEPARATED_IMAGES 1 /* Selections saved to separate images */ #define STRIP 1 #define TILE 2 #define MAX_REGIONS 8 /* number of regions to extract from a single page */ #define MAX_OUTBUFFS 8 /* must match larger of zones or regions */ #define MAX_SECTIONS 32 /* number of sections per page to write to output */ #define MAX_IMAGES 1024 /* number of images in descrete list, not in the file */ #define MAX_SAMPLES 8 /* maximum number of samples per pixel supported */ #define MAX_BITS_PER_SAMPLE 64 /* maximum bit depth supported */ #define DUMP_NONE 0 #define DUMP_TEXT 1 #define DUMP_RAW 2 /* Offsets into buffer for margins and fixed width and length segments */ struct offset { uint32 tmargin; uint32 lmargin; uint32 bmargin; uint32 rmargin; uint32 crop_width; uint32 crop_length; uint32 startx; uint32 endx; uint32 starty; uint32 endy; }; /* Description of a zone within the image. Position 1 of 3 zones would be * the first third of the image. These are computed after margins and * width/length requests are applied so that you can extract multiple * zones from within a larger region for OCR or barcode recognition. */ struct buffinfo { uint32 size; /* size of this buffer */ unsigned char *buffer; /* address of the allocated buffer */ }; struct zone { int position; /* ordinal of segment to be extracted */ int total; /* total equal sized divisions of crop area */ }; struct pageseg { uint32 x1; /* index of left edge */ uint32 x2; /* index of right edge */ uint32 y1; /* index of top edge */ uint32 y2; /* index of bottom edge */ int position; /* ordinal of segment to be extracted */ int total; /* total equal sized divisions of crop area */ uint32 buffsize; /* size of buffer needed to hold the cropped zone */ }; struct coordpairs { double X1; /* index of left edge in current units */ double X2; /* index of right edge in current units */ double Y1; /* index of top edge in current units */ double Y2; /* index of bottom edge in current units */ }; struct region { uint32 x1; /* pixel offset of left edge */ uint32 x2; /* pixel offset of right edge */ uint32 y1; /* pixel offset of top edge */ uint32 y2; /* picel offset of bottom edge */ uint32 width; /* width in pixels */ uint32 length; /* length in pixels */ uint32 buffsize; /* size of buffer needed to hold the cropped region */ unsigned char *buffptr; /* address of start of the region */ }; /* Cropping parameters from command line and image data */ struct crop_mask { double width; /* Selection width for master crop region in requested units */ double length; /* Selection length for master crop region in requesed units */ double margins[4]; /* Top, left, bottom, right margins */ float xres; /* Horizontal resolution read from image*/ float yres; /* Vertical resolution read from image */ uint32 combined_width; /* Width of combined cropped zones */ uint32 combined_length; /* Length of combined cropped zones */ uint32 bufftotal; /* Size of buffer needed to hold all the cropped region */ uint16 img_mode; /* Composite or separate images created from zones or regions */ uint16 exp_mode; /* Export input images or selections to one or more files */ uint16 crop_mode; /* Crop options to be applied */ uint16 res_unit; /* Resolution unit for margins and selections */ uint16 edge_ref; /* Reference edge for sections extraction and combination */ uint16 rotation; /* Clockwise rotation of the extracted region or image */ uint16 mirror; /* Mirror extracted region or image horizontally or vertically */ uint16 invert; /* Invert the color map of image or region */ uint16 photometric; /* Status of photometric interpretation for inverted image */ uint16 selections; /* Number of regions or zones selected */ uint16 regions; /* Number of regions delimited by corner coordinates */ struct region regionlist[MAX_REGIONS]; /* Regions within page or master crop region */ uint16 zones; /* Number of zones delimited by Ordinal:Total requested */ struct zone zonelist[MAX_REGIONS]; /* Zones indices to define a region */ struct coordpairs corners[MAX_REGIONS]; /* Coordinates of upper left and lower right corner */ }; #define MAX_PAPERNAMES 49 #define MAX_PAPERNAME_LENGTH 15 #define DEFAULT_RESUNIT RESUNIT_INCH #define DEFAULT_PAGE_HEIGHT 14.0 #define DEFAULT_PAGE_WIDTH 8.5 #define DEFAULT_RESOLUTION 300 #define DEFAULT_PAPER_SIZE "legal" #define ORIENTATION_NONE 0 #define ORIENTATION_PORTRAIT 1 #define ORIENTATION_LANDSCAPE 2 #define ORIENTATION_SEASCAPE 4 #define ORIENTATION_AUTO 16 #define PAGE_MODE_NONE 0 #define PAGE_MODE_RESOLUTION 1 #define PAGE_MODE_PAPERSIZE 2 #define PAGE_MODE_MARGINS 4 #define PAGE_MODE_ROWSCOLS 8 #define INVERT_DATA_ONLY 10 #define INVERT_DATA_AND_TAG 11 struct paperdef { char name[MAX_PAPERNAME_LENGTH]; double width; double length; double asratio; }; /* Paper Size Width Length Aspect Ratio */ struct paperdef PaperTable[MAX_PAPERNAMES] = { {"default", 8.500, 14.000, 0.607}, {"pa4", 8.264, 11.000, 0.751}, {"letter", 8.500, 11.000, 0.773}, {"legal", 8.500, 14.000, 0.607}, {"half-letter", 8.500, 5.514, 1.542}, {"executive", 7.264, 10.528, 0.690}, {"tabloid", 11.000, 17.000, 0.647}, {"11x17", 11.000, 17.000, 0.647}, {"ledger", 17.000, 11.000, 1.545}, {"archa", 9.000, 12.000, 0.750}, {"archb", 12.000, 18.000, 0.667}, {"archc", 18.000, 24.000, 0.750}, {"archd", 24.000, 36.000, 0.667}, {"arche", 36.000, 48.000, 0.750}, {"csheet", 17.000, 22.000, 0.773}, {"dsheet", 22.000, 34.000, 0.647}, {"esheet", 34.000, 44.000, 0.773}, {"superb", 11.708, 17.042, 0.687}, {"commercial", 4.139, 9.528, 0.434}, {"monarch", 3.889, 7.528, 0.517}, {"envelope-dl", 4.333, 8.681, 0.499}, {"envelope-c5", 6.389, 9.028, 0.708}, {"europostcard", 4.139, 5.833, 0.710}, {"a0", 33.111, 46.806, 0.707}, {"a1", 23.389, 33.111, 0.706}, {"a2", 16.542, 23.389, 0.707}, {"a3", 11.694, 16.542, 0.707}, {"a4", 8.264, 11.694, 0.707}, {"a5", 5.833, 8.264, 0.706}, {"a6", 4.125, 5.833, 0.707}, {"a7", 2.917, 4.125, 0.707}, {"a8", 2.056, 2.917, 0.705}, {"a9", 1.458, 2.056, 0.709}, {"a10", 1.014, 1.458, 0.695}, {"b0", 39.375, 55.667, 0.707}, {"b1", 27.833, 39.375, 0.707}, {"b2", 19.681, 27.833, 0.707}, {"b3", 13.903, 19.681, 0.706}, {"b4", 9.847, 13.903, 0.708}, {"b5", 6.931, 9.847, 0.704}, {"b6", 4.917, 6.931, 0.709}, {"c0", 36.097, 51.069, 0.707}, {"c1", 25.514, 36.097, 0.707}, {"c2", 18.028, 25.514, 0.707}, {"c3", 12.750, 18.028, 0.707}, {"c4", 9.014, 12.750, 0.707}, {"c5", 6.375, 9.014, 0.707}, {"c6", 4.486, 6.375, 0.704}, {"", 0.000, 0.000, 1.000}, }; /* Structure to define in input image parameters */ struct image_data { float xres; float yres; uint32 width; uint32 length; uint16 res_unit; uint16 bps; uint16 spp; uint16 planar; uint16 photometric; uint16 orientation; uint16 adjustments; }; /* Structure to define the output image modifiers */ struct pagedef { char name[16]; double width; /* width in pixels */ double length; /* length in pixels */ double hmargin; /* margins to subtract from width of sections */ double vmargin; /* margins to subtract from height of sections */ double hres; /* horizontal resolution for output */ double vres; /* vertical resolution for output */ uint32 mode; /* bitmask of modifiers to page format */ uint16 res_unit; /* resolution unit for output image */ unsigned int rows; /* number of section rows */ unsigned int cols; /* number of section cols */ unsigned int orient; /* portrait, landscape, seascape, auto */ }; struct dump_opts { int debug; int format; int level; char mode[4]; char infilename[PATH_MAX + 1]; char outfilename[PATH_MAX + 1]; FILE *infile; FILE *outfile; }; /* globals */ static int outtiled = -1; static uint32 tilewidth; static uint32 tilelength; static uint16 config; static uint16 compression; static uint16 predictor; static uint16 fillorder; static uint32 rowsperstrip; static uint32 g3opts; static int ignore = FALSE; /* if true, ignore read errors */ static uint32 defg3opts = (uint32) -1; static int quality = 75; /* JPEG quality */ static int jpegcolormode = JPEGCOLORMODE_RGB; static uint16 defcompression = (uint16) -1; static uint16 defpredictor = (uint16) -1; static int pageNum = 0; static int little_endian = 1; /* Functions adapted from tiffcp with additions or modifications */ static int readContigStripsIntoBuffer (TIFF*, uint8*, uint32, uint32, tsample_t); static int readSeparateStripsIntoBuffer (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int readContigTilesIntoBuffer (TIFF*, uint8*, uint32, uint32, tsample_t); static int readSeparateTilesIntoBuffer (TIFF*, uint8*, uint32, uint32, tsample_t); static int writeBufferToContigStrips (TIFF*, uint8*, uint32, uint32, tsample_t); static int writeBufferToContigTiles (TIFF*, uint8*, uint32, uint32, tsample_t); static int writeBufferToSeparateStrips (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int writeBufferToSeparateTiles (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int extractContigSamplesToBuffer (uint8 *, uint8 *, uint32, uint32, int, int, tsample_t, uint16, uint16, struct dump_opts *); static void cpStripToTile (uint8*, uint8*, uint32, uint32, int, int); static void cpSeparateBufToContigBuf(uint8 *, uint8 *, uint32, uint32 , int, int, tsample_t, int); static int processCompressOptions(char*); static void usage(void); /* New functions by Richard Nolde not found in tiffcp */ static void initImageData (struct image_data *); static void initCropMasks (struct crop_mask *); static void initPageSetup (struct pagedef *, struct pageseg *, struct buffinfo []); static void initDumpOptions(struct dump_opts *); /* Command line and file naming functions */ void process_command_opts (int, char *[], char *, char *, uint32 *, uint16 *, uint16 *, uint32 *, uint32 *, uint32 *, struct crop_mask *, struct pagedef *, struct dump_opts *, unsigned int *, unsigned int *); static int update_output_file (TIFF **, char *, int, char *, unsigned int *); /* * High level functions for whole image manipulation */ static int get_page_geometry (char *, struct pagedef*); static int computeInputPixelOffsets(struct crop_mask *, struct image_data *, struct offset *); static int computeOutputPixelOffsets (struct crop_mask *, struct image_data *, struct pagedef *, struct pageseg *, struct dump_opts *); static int loadImage(TIFF *, struct image_data *, struct dump_opts *, unsigned char **); static int correct_orientation(struct image_data *, unsigned char **); static int getCropOffsets(struct image_data *, struct crop_mask *, struct dump_opts *); static int processCropSelections(struct image_data *, struct crop_mask *, unsigned char **, struct buffinfo []); static int writeSelections(TIFF *, TIFF **, struct crop_mask *, struct image_data *, struct dump_opts *, struct buffinfo [], char *, char *, unsigned int*, unsigned int); /* Section functions */ static int createImageSection(uint32, unsigned char **); static int extractImageSection(struct image_data *, struct pageseg *, unsigned char *, unsigned char *); static int writeSingleSection(TIFF *, TIFF *, struct image_data *, struct dump_opts *, uint32, uint32, double, double, unsigned char *); static int writeImageSections(TIFF *, TIFF *, struct image_data *, struct pagedef *, struct pageseg *, struct dump_opts *, unsigned char *, unsigned char **); /* Whole image functions */ static int createCroppedImage(struct image_data *, struct crop_mask *, unsigned char **, unsigned char **); static int writeCroppedImage(TIFF *, TIFF *, struct image_data *image, struct dump_opts * dump, uint32, uint32, unsigned char *, int, int); /* Image manipulation functions */ static int rotateContigSamples8bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateContigSamples16bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateContigSamples24bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateContigSamples32bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateImage(uint16, struct image_data *, uint32 *, uint32 *, unsigned char **); static int mirrorImage(uint16, uint16, uint16, uint32, uint32, unsigned char *); static int invertImage(uint16, uint16, uint16, uint32, uint32, unsigned char *); /* Functions to reverse the sequence of samples in a scanline */ static int reverseSamples8bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamples16bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamples24bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamples32bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamplesBytes (uint16, uint16, uint32, uint8 *, uint8 *); /* Functions for manipulating individual samples in an image */ static int extractSeparateRegion(struct image_data *, struct crop_mask *, unsigned char *, unsigned char *, int); static int extractCompositeRegions(struct image_data *, struct crop_mask *, unsigned char *, unsigned char *); static int extractContigSamples8bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamples16bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamples24bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamples32bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamplesBytes (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamplesShifted8bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesShifted16bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesShifted24bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesShifted32bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); /* Functions to combine separate planes into interleaved planes */ static int combineSeparateSamples8bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamples16bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamples24bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamples32bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamplesBytes (unsigned char *[], unsigned char *, uint32, uint32, tsample_t, uint16, FILE *, int, int); /* Dump functions for debugging */ static void dump_info (FILE *, int, char *, char *, ...); static int dump_data (FILE *, int, char *, unsigned char *, uint32); static int dump_byte (FILE *, int, char *, unsigned char); static int dump_short (FILE *, int, char *, uint16); static int dump_long (FILE *, int, char *, uint32); static int dump_wide (FILE *, int, char *, uint64); static int dump_buffer (FILE *, int, uint32, uint32, uint32, unsigned char *); /* End function declarations */ /* Functions derived in whole or in part from tiffcp */ /* The following functions are taken largely intact from tiffcp */ static char tiffcrop_version_id[] = "2.0"; static char tiffcrop_rev_date[] = "01-06-2009"; static char* stuff[] = { "usage: tiffcrop [options] source1 ... sourceN destination", "where options are:", " -h Print this syntax listing", " -v Print tiffcrop version identifier and last revision date", " ", " -a Append to output instead of overwriting", " -d offset Set initial directory offset, counting first image as one, not zero", " -p contig Pack samples contiguously (e.g. RGBRGB...)", " -p separate Store samples separately (e.g. RRR...GGG...BBB...)", " -s Write output in strips", " -t Write output in tiles", " -i Ignore read errors", " ", " -r # Make each strip have no more than # rows", " -w # Set output tile width (pixels)", " -l # Set output tile length (pixels)", " ", " -f lsb2msb Force lsb-to-msb FillOrder for output", " -f msb2lsb Force msb-to-lsb FillOrder for output", "", " -c lzw[:opts] Compress output with Lempel-Ziv & Welch encoding", " -c zip[:opts] Compress output with deflate encoding", " -c jpeg[:opts] compress output with JPEG encoding", " -c packbits Compress output with packbits encoding", " -c g3[:opts] Compress output with CCITT Group 3 encoding", " -c g4 Compress output with CCITT Group 4 encoding", " -c none Use no compression algorithm on output", " ", "Group 3 options:", " 1d Use default CCITT Group 3 1D-encoding", " 2d Use optional CCITT Group 3 2D-encoding", " fill Byte-align EOL codes", "For example, -c g3:2d:fill to get G3-2D-encoded data with byte-aligned EOLs", " ", "JPEG options:", " # Set compression quality level (0-100, default 75)", " r Output color image as RGB rather than YCbCr", "For example, -c jpeg:r:50 to get JPEG-encoded RGB data with 50% comp. quality", " ", "LZW and deflate options:", " # Set predictor value", "For example, -c lzw:2 to get LZW-encoded data with horizontal differencing", " ", "Page and selection options:", " -N odd|even|#,#-#,#|last sequences and ranges of images within file to process", " The words odd or even may be used to specify all odd or even numbered images.", " The word last may be used in place of a number in the sequence to indicate.", " The final image in the file without knowing how many images there are.", " Numbers are counted from one even though TIFF IFDs are counted from zero.", " ", " -E t|l|r|b edge to use as origin for width and length of crop region", " -U units [in, cm, px ] inches, centimeters or pixels", " ", " -m #,#,#,# margins from edges for selection: top, left, bottom, right separated by commas", " -X # horizontal dimension of region to extract expressed in current units", " -Y # vertical dimension of region to extract expressed in current units", " -Z #:#,#:# zones of the image designated as position X of Y,", " eg 1:3 would be first of three equal portions measured from reference edge", " -z x1,y1,x2,y2:...:xN,yN,xN+1,yN+1", " regions of the image designated by upper left and lower right coordinates", "", "Export grouping options:", " -e c|d|i|m|s export mode for images and selections from input images.", " When exporting a composite image from multiple zones or regions", " (combined and image modes), the selections must have equal sizes", " for the axis perpendicular to the edge specified with -E.", " c|combined All images and selections are written to a single file (default).", " with multiple selections from one image combined into a single image.", " d|divided All images and selections are written to a single file", " with each selection from one image written to a new image.", " i|image Each input image is written to a new file (numeric filename sequence)", " with multiple selections from the image combined into one image.", " m|multiple Each input image is written to a new file (numeric filename sequence)", " with each selection from the image written to a new image.", " s|separated Individual selections from each image are written to separate files.", "", "Output options:", " -H # Set horizontal resolution of output images to #", " -V # Set vertical resolution of output images to #", " -J # Set horizontal margin of output page to # expressed in current units", " -K # Set verticalal margin of output page to # expressed in current units", " ", " -O orient orientation for output image, portrait, landscape, auto", " -P page page size for output image segments, eg letter, legal, tabloid, etc", " -S cols:rows Divide the image into equal sized segments using cols across and rows down.", " ", " -F hor|vert|both", " flip (mirror) image or region horizontally, vertically, or both", " -R # [90,180,or 270] degrees clockwise rotation of image or extracted region", " -I [black|white|data|both]", " invert color space, eg dark to light for bilevel and grayscale images", " If argument is white or black, set the PHOTOMETRIC_INTERPRETATION ", " tag to MinIsBlack or MinIsWhite without altering the image data", " If the argument is data or both, the image data are modified:", " both inverts the data and the PHOTOMETRIC_INTERPRETATION tag,", " data inverts the data but not the PHOTOMETRIC_INTERPRETATION tag", " ", "-D opt1:value1,opt2:value2,opt3:value3:opt4:value4", " Debug/dump program progress and/or data to non-TIFF files.", " Options include the following and must be joined as a comma", " separate list. The use of this option is generally limited to", " program debugging and development of future options.", " ", " debug:N Display limited program progress indicators where larger N", " increase the level of detail. The program must be compiled with", " -DDEBUG -DDEBUG2 to enable full debug reporting", "", " format:txt|raw Format any logged data as ASCII text or raw binary ", " values. ASCII text dumps include strings of ones and zeroes", " representing the binary values in the image data plus identifying headers.", " ", " level:N Specify the level of detail presented in the dump files.", " This can vary from dumps of the entire input or output image data to dumps", " of data processed by specific functions. Current range of levels is 1 to 3.", " ", " input:full-path-to-directory/input-dumpname", " ", " output:full-path-to-directory/output-dumpnaem", " ", " When dump files are being written, each image will be written to a separate", " file with the name built by adding a numeric sequence value to the dumpname", " and an extension of .txt for ASCII dumps or .bin for binary dumps.", " ", " The four debug/dump options are independent, though it makes little sense to", " specify a dump file without specifying a detail level.", " ", NULL }; static int readContigTilesIntoBuffer (TIFF* in, uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp) { int status = 1; tdata_t tilebuf = _TIFFmalloc(TIFFTileSize(in)); uint32 imagew = TIFFScanlineSize(in); uint32 tilew = TIFFTileRowSize(in); int iskew = imagew - tilew; uint8* bufp = (uint8*) buf; uint32 tw, tl; uint32 row; (void) spp; if (tilebuf == 0) return 0; (void) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); (void) TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); for (row = 0; row < imagelength; row += tl) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { if (TIFFReadTile(in, tilebuf, col, row, 0, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile at %lu %lu", (unsigned long) col, (unsigned long) row); status = 0; goto done; } if (colb + tilew > imagew) { uint32 width = imagew - colb; uint32 oskew = tilew - width; cpStripToTile(bufp + colb, tilebuf, nrow, width, oskew + iskew, oskew ); } else cpStripToTile(bufp + colb, tilebuf, nrow, tilew, iskew, 0); colb += tilew; } bufp += imagew * nrow; } done: _TIFFfree(tilebuf); return status; } static int readSeparateTilesIntoBuffer (TIFF* in, uint8 *buf, uint32 imagelength, uint32 imagewidth, uint16 spp) { int status = 1; uint32 imagew = TIFFRasterScanlineSize(in); uint32 tilew = TIFFTileRowSize(in); int iskew = imagew - tilew*spp; tdata_t tilebuf = _TIFFmalloc(TIFFTileSize(in)); uint8* bufp = (uint8*) buf; uint32 tw, tl; uint32 row; uint16 bps, bytes_per_sample; if (tilebuf == 0) return 0; (void) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); (void) TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); (void) TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps); assert( bps % 8 == 0 ); bytes_per_sample = bps/8; for (row = 0; row < imagelength; row += tl) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { tsample_t s; for (s = 0; s < spp; s++) { if (TIFFReadTile(in, tilebuf, col, row, 0, s) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile at %lu %lu, " "sample %lu", (unsigned long) col, (unsigned long) row, (unsigned long) s); status = 0; goto done; } /* * Tile is clipped horizontally. Calculate * visible portion and skewing factors. */ if (colb + tilew*spp > imagew) { uint32 width = imagew - colb; int oskew = tilew*spp - width; cpSeparateBufToContigBuf( bufp+colb+s*bytes_per_sample, tilebuf, nrow, width/(spp*bytes_per_sample), oskew + iskew, oskew/spp, spp, bytes_per_sample); } else cpSeparateBufToContigBuf( bufp+colb+s*bytes_per_sample, tilebuf, nrow, tw, iskew, 0, spp, bytes_per_sample); } colb += tilew*spp; } bufp += imagew * nrow; } done: _TIFFfree(tilebuf); return status; } static int writeBufferToContigStrips(TIFF* out, uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp) { uint32 row, rowsperstrip; tstrip_t strip = 0; (void) imagewidth; (void) spp; (void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); for (row = 0; row < imagelength; row += rowsperstrip) { uint32 nrows = (row+rowsperstrip > imagelength) ? imagelength-row : rowsperstrip; tsize_t stripsize = TIFFVStripSize(out, nrows); if (TIFFWriteEncodedStrip(out, strip++, buf, stripsize) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1); return 0; } buf += stripsize; } return 1; } /* Function modified from original tiffcp version with plans to * extend so that plannar orientation separate images do not have * all samples for each channel written before all sampels for the * next channel. Current code is very similar in design to original. */ static int writeBufferToSeparateStrips (TIFF* out, uint8* buf, uint32 length, uint32 width, uint16 spp, struct dump_opts *dump) { uint8 *src; uint16 bps; uint32 row, nrows, rowsize, rowsperstrip; uint32 bytes_per_sample; tsample_t s; tstrip_t strip = 0; tsize_t stripsize = TIFFStripSize(out); tsize_t rowstripsize, scanlinesize = TIFFScanlineSize(out); tsize_t total_bytes = 0; tdata_t obuf; (void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); (void) TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps); bytes_per_sample = (bps + 7) / 8; rowsize = ((bps * spp * width) + 7) / 8; rowstripsize = rowsperstrip * bytes_per_sample * (width + 1); obuf = _TIFFmalloc (rowstripsize); if (obuf == NULL) return (0); for (s = 0; s < spp; s++) { for (row = 0; row < length; row += rowsperstrip) { nrows = (row + rowsperstrip > length) ? length - row : rowsperstrip; stripsize = TIFFVStripSize(out, nrows); src = buf + (row * rowsize); total_bytes += stripsize; memset (obuf, '\0', rowstripsize); if (extractContigSamplesToBuffer(obuf, src, nrows, width, 0, 0, s, spp, bps, dump)) { _TIFFfree(obuf); return (0); } if ((dump->outfile != NULL) && (dump->level == 1)) { dump_info(dump->outfile, dump->format,"", "Sample %2d, Strip: %2d, bytes: %4d, Row %4d, bytes: %4d, Input offset: %6d", s + 1, strip + 1, stripsize, row + 1, scanlinesize, src - buf); dump_buffer(dump->outfile, dump->format, nrows, scanlinesize, row, obuf); } if (TIFFWriteEncodedStrip(out, strip++, obuf, stripsize) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1); _TIFFfree(obuf); return 0; } } } /* Abandoning this code for now. Would be nice to be able to write * one or more rows of each color to successive strips, rather than * all the rows of a given color before any rows of the next color. tsize_t row_buffsize; row_buffsize = scanlinesize + (((spp + bps) + 7) / 8); obuf = _TIFFmalloc (row_buffsize); if (obuf == NULL) return (0); TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip); for (row = 0; row < length; row++) { src = buf + (row * rowsize); total_bytes += scanlinesize; for (s = 0; s < spp; s++) { memset (obuf, '\0', row_buffsize); if (extractContigSamplesToBuffer(obuf, src, 1, width, 0, 0, s, spp, bps, dump)) { _TIFFfree(obuf); return (0); } if ((dump->outfile != NULL) && (dump->level == 1)) { dump_info(dump->outfile, dump->format,"", "Row %4d, Sample %2d, bytes: %4d, Input offset: %6d", row + 1, s + 1, scanlinesize, src - buf); dump_buffer(dump->outfile, dump->format, nrows, scanlinesize, row, obuf); } if (TIFFWriteScanline(out, obuf, row, s) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", row + 1); _TIFFfree(obuf); return 0; } } } */ _TIFFfree(obuf); return 1; } static int writeBufferToContigTiles (TIFF* out, uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp) { uint32 imagew = TIFFScanlineSize(out); uint32 tilew = TIFFTileRowSize(out); int iskew = imagew - tilew; tdata_t obuf = _TIFFmalloc(TIFFTileSize(out)); uint8* bufp = (uint8*) buf; uint32 tl, tw; uint32 row; (void) spp; if (obuf == NULL) return 0; (void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl); (void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw); for (row = 0; row < imagelength; row += tilelength) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { /* * Tile is clipped horizontally. Calculate * visible portion and skewing factors. */ if (colb + tilew > imagew) { uint32 width = imagew - colb; int oskew = tilew - width; cpStripToTile(obuf, bufp + colb, nrow, width, oskew, oskew + iskew); } else cpStripToTile(obuf, bufp + colb, nrow, tilew, 0, iskew); if (TIFFWriteTile(out, obuf, col, row, 0, 0) < 0) { TIFFError(TIFFFileName(out), "Error, can't write tile at %lu %lu", (unsigned long) col, (unsigned long) row); _TIFFfree(obuf); return 0; } colb += tilew; } bufp += nrow * imagew; } _TIFFfree(obuf); return 1; } static int writeBufferToSeparateTiles (TIFF* out, uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp, struct dump_opts * dump) { uint32 imagew = TIFFScanlineSize(out); tsize_t tilew = TIFFTileRowSize(out); uint32 iimagew = TIFFRasterScanlineSize(out); int iskew = iimagew - tilew*spp; tdata_t obuf = _TIFFmalloc(TIFFTileSize(out)); uint8* bufp = (uint8*) buf; uint32 tl, tw; uint32 row; uint16 bps, bytes_per_sample; if (obuf == NULL) return 0; (void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl); (void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw); (void) TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps); assert( bps % 8 == 0 ); bytes_per_sample = (bps + 7)/8; for (row = 0; row < imagelength; row += tl) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { tsample_t s; for (s = 0; s < spp; s++) { /* * Tile is clipped horizontally. Calculate * visible portion and skewing factors. */ if (colb + tilew > imagew) { uint32 width = (imagew - colb); int oskew = tilew - width; extractContigSamplesToBuffer(obuf, bufp + (colb*spp) + s, nrow, width/bytes_per_sample, oskew, (oskew*spp)+iskew, s, spp, bps, dump); } else extractContigSamplesToBuffer(obuf, bufp + (colb*spp) + s, nrow, tilewidth, 0, iskew, s, spp, bps, dump); if (TIFFWriteTile(out, obuf, col, row, 0, s) < 0) { TIFFError(TIFFFileName(out), "Error, can't write tile at %lu %lu " "sample %lu", (unsigned long) col, (unsigned long) row, (unsigned long) s); _TIFFfree(obuf); return 0; } } colb += tilew; } bufp += nrow * iimagew; } _TIFFfree(obuf); return 1; } static void processG3Options(char* cp) { if( (cp = strchr(cp, ':')) ) { if (defg3opts == (uint32) -1) defg3opts = 0; do { cp++; if (strneq(cp, "1d", 2)) defg3opts &= ~GROUP3OPT_2DENCODING; else if (strneq(cp, "2d", 2)) defg3opts |= GROUP3OPT_2DENCODING; else if (strneq(cp, "fill", 4)) defg3opts |= GROUP3OPT_FILLBITS; else usage(); } while( (cp = strchr(cp, ':')) ); } } static int processCompressOptions(char* opt) { if (streq(opt, "none")) { defcompression = COMPRESSION_NONE; } else if (streq(opt, "packbits")) { defcompression = COMPRESSION_PACKBITS; } else if (strneq(opt, "jpeg", 4)) { char* cp = strchr(opt, ':'); defcompression = COMPRESSION_JPEG; while( cp ) { if (isdigit((int)cp[1])) quality = atoi(cp+1); else if (cp[1] == 'r' ) jpegcolormode = JPEGCOLORMODE_RAW; else usage(); cp = strchr(cp+1,':'); } } else if (strneq(opt, "g3", 2)) { processG3Options(opt); defcompression = COMPRESSION_CCITTFAX3; } else if (streq(opt, "g4")) { defcompression = COMPRESSION_CCITTFAX4; } else if (strneq(opt, "lzw", 3)) { char* cp = strchr(opt, ':'); if (cp) defpredictor = atoi(cp+1); defcompression = COMPRESSION_LZW; } else if (strneq(opt, "zip", 3)) { char* cp = strchr(opt, ':'); if (cp) defpredictor = atoi(cp+1); defcompression = COMPRESSION_ADOBE_DEFLATE; } else return (0); return (1); } static void usage(void) { char buf[BUFSIZ]; int i; setbuf(stderr, buf); fprintf(stderr, "\n%s\n", TIFFGetVersion()); for (i = 0; stuff[i] != NULL; i++) fprintf(stderr, "%s\n", stuff[i]); exit(-1); } #define CopyField(tag, v) \ if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v) #define CopyField2(tag, v1, v2) \ if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2) #define CopyField3(tag, v1, v2, v3) \ if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3) #define CopyField4(tag, v1, v2, v3, v4) \ if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4) static void cpTag(TIFF* in, TIFF* out, uint16 tag, uint16 count, TIFFDataType type) { switch (type) { case TIFF_SHORT: if (count == 1) { uint16 shortv; CopyField(tag, shortv); } else if (count == 2) { uint16 shortv1, shortv2; CopyField2(tag, shortv1, shortv2); } else if (count == 4) { uint16 *tr, *tg, *tb, *ta; CopyField4(tag, tr, tg, tb, ta); } else if (count == (uint16) -1) { uint16 shortv1; uint16* shortav; CopyField2(tag, shortv1, shortav); } break; case TIFF_LONG: { uint32 longv; CopyField(tag, longv); } break; case TIFF_RATIONAL: if (count == 1) { float floatv; CopyField(tag, floatv); } else if (count == (uint16) -1) { float* floatav; CopyField(tag, floatav); } break; case TIFF_ASCII: { char* stringv; CopyField(tag, stringv); } break; case TIFF_DOUBLE: if (count == 1) { double doublev; CopyField(tag, doublev); } else if (count == (uint16) -1) { double* doubleav; CopyField(tag, doubleav); } break; default: TIFFError(TIFFFileName(in), "Data type %d is not supported, tag %d skipped.", tag, type); } } static struct cpTag { uint16 tag; uint16 count; TIFFDataType type; } tags[] = { { TIFFTAG_SUBFILETYPE, 1, TIFF_LONG }, { TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT }, { TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII }, { TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII }, { TIFFTAG_MAKE, 1, TIFF_ASCII }, { TIFFTAG_MODEL, 1, TIFF_ASCII }, { TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT }, { TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT }, { TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL }, { TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL }, { TIFFTAG_PAGENAME, 1, TIFF_ASCII }, { TIFFTAG_XPOSITION, 1, TIFF_RATIONAL }, { TIFFTAG_YPOSITION, 1, TIFF_RATIONAL }, { TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT }, { TIFFTAG_SOFTWARE, 1, TIFF_ASCII }, { TIFFTAG_DATETIME, 1, TIFF_ASCII }, { TIFFTAG_ARTIST, 1, TIFF_ASCII }, { TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII }, { TIFFTAG_WHITEPOINT, (uint16) -1, TIFF_RATIONAL }, { TIFFTAG_PRIMARYCHROMATICITIES,(uint16) -1,TIFF_RATIONAL }, { TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT }, { TIFFTAG_INKSET, 1, TIFF_SHORT }, { TIFFTAG_DOTRANGE, 2, TIFF_SHORT }, { TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII }, { TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT }, { TIFFTAG_YCBCRCOEFFICIENTS, (uint16) -1,TIFF_RATIONAL }, { TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT }, { TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT }, { TIFFTAG_REFERENCEBLACKWHITE, (uint16) -1,TIFF_RATIONAL }, { TIFFTAG_EXTRASAMPLES, (uint16) -1, TIFF_SHORT }, { TIFFTAG_SMINSAMPLEVALUE, 1, TIFF_DOUBLE }, { TIFFTAG_SMAXSAMPLEVALUE, 1, TIFF_DOUBLE }, { TIFFTAG_STONITS, 1, TIFF_DOUBLE }, }; #define NTAGS (sizeof (tags) / sizeof (tags[0])) #define CopyTag(tag, count, type) cpTag(in, out, tag, count, type) static void cpStripToTile(uint8* out, uint8* in, uint32 rows, uint32 cols, int outskew, int inskew) { while (rows-- > 0) { uint32 j = cols; while (j-- > 0) *out++ = *in++; out += outskew; in += inskew; } } /* Fucntions written by Richard Nolde, with exceptions noted. */ void process_command_opts (int argc, char *argv[], char *mp, char *mode, uint32 *dirnum, uint16 *defconfig, uint16 *deffillorder, uint32 *deftilewidth, uint32 *deftilelength, uint32 *defrowsperstrip, struct crop_mask *crop_data, struct pagedef *page, struct dump_opts *dump, unsigned int *imagelist, unsigned int *image_count ) { int c, good_args = 0; char *opt_offset = NULL; /* Position in string of value sought */ char *opt_ptr = NULL; /* Pointer to next token in option set */ char *sep = NULL; /* Pointer to a token separator */ unsigned int i, j, start, end; extern int optind; extern char* optarg; *mp++ = 'w'; *mp = '\0'; while ((c = getopt(argc, argv, "ac:d:e:f:hil:m:p:r:stvw:z:BCD:E:F:H:I:J:K:LMN:O:P:R:S:U:V:X:Y:Z:")) != -1) { good_args++; switch (c) { case 'a': mode[0] = 'a'; /* append to output */ break; case 'c': if (!processCompressOptions(optarg)) /* compression scheme */ { TIFFError ("Unknown compression option", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'd': start = strtoul(optarg, NULL, 0); /* initial IFD offset */ if (start == 0) { TIFFError ("","Directory offset must be greater than zero"); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } *dirnum = start - 1; break; case 'e': switch (tolower(optarg[0])) /* image export modes*/ { case 'c': crop_data->exp_mode = ONE_FILE_COMPOSITE; crop_data->img_mode = COMPOSITE_IMAGES; break; /* Composite */ case 'd': crop_data->exp_mode = ONE_FILE_SEPARATED; crop_data->img_mode = SEPARATED_IMAGES; break; /* Divided */ case 'i': crop_data->exp_mode = FILE_PER_IMAGE_COMPOSITE; crop_data->img_mode = COMPOSITE_IMAGES; break; /* Image */ case 'm': crop_data->exp_mode = FILE_PER_IMAGE_SEPARATED; crop_data->img_mode = SEPARATED_IMAGES; break; /* Multiple */ case 's': crop_data->exp_mode = FILE_PER_SELECTION; crop_data->img_mode = SEPARATED_IMAGES; break; /* Sections */ default: TIFFError ("Unknown export mode","%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'f': if (streq(optarg, "lsb2msb")) /* fill order */ *deffillorder = FILLORDER_LSB2MSB; else if (streq(optarg, "msb2lsb")) *deffillorder = FILLORDER_MSB2LSB; else { TIFFError ("Unknown fill order", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'h': usage(); break; case 'i': ignore = TRUE; /* ignore errors */ break; case 'l': outtiled = TRUE; /* tile length */ *deftilelength = atoi(optarg); break; case 'p': /* planar configuration */ if (streq(optarg, "separate")) *defconfig = PLANARCONFIG_SEPARATE; else if (streq(optarg, "contig")) *defconfig = PLANARCONFIG_CONTIG; else { TIFFError ("Unkown planar configuration", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'r': /* rows/strip */ *defrowsperstrip = atol(optarg); break; case 's': /* generate stripped output */ outtiled = FALSE; break; case 't': /* generate tiled output */ outtiled = TRUE; break; case 'v': TIFFError ("Tiffcrop version", "%s, last updated: %s", tiffcrop_version_id, tiffcrop_rev_date); TIFFError ("Tiffcp code", "Copyright (c) 1988-1997 Sam Leffler"); TIFFError (" ", "Copyright (c) 1991-1997 Silicon Graphics, Inc"); TIFFError ("Tiffcrop additions", "Copyright (c) 2007-2009 Richard Nolde"); exit (0); break; case 'w': /* tile width */ outtiled = TRUE; *deftilewidth = atoi(optarg); break; case 'z': /* regions of an image specified as x1,y1,x2,y2:x3,y3,x4,y4 etc */ crop_data->crop_mode |= CROP_REGIONS; for (i = 0, opt_ptr = strtok (optarg, ":"); ((opt_ptr != NULL) && (i < MAX_REGIONS)); (opt_ptr = strtok (NULL, ":")), i++) { crop_data->regions++; if (sscanf(opt_ptr, "%lf,%lf,%lf,%lf", &crop_data->corners[i].X1, &crop_data->corners[i].Y1, &crop_data->corners[i].X2, &crop_data->corners[i].Y2) != 4) { TIFFError ("Unable to parse coordinates for region", "%d %s", i, optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } } /* check for remaining elements over MAX_REGIONS */ if ((opt_ptr != NULL) && (i >= MAX_REGIONS)) { TIFFError ("Region list exceeds limit of", "%d regions %s", MAX_REGIONS, optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1);; } break; /* options for file open modes */ case 'B': *mp++ = 'b'; *mp = '\0'; break; case 'L': *mp++ = 'l'; *mp = '\0'; break; case 'M': *mp++ = 'm'; *mp = '\0'; break; case 'C': *mp++ = 'c'; *mp = '\0'; break; /* options for Debugging / data dump */ case 'D': for (i = 0, opt_ptr = strtok (optarg, ","); (opt_ptr != NULL); (opt_ptr = strtok (NULL, ",")), i++) { opt_offset = strpbrk(opt_ptr, ":="); /* opt_offset = strchr(opt_ptr, ':'); */ if (opt_offset == NULL) { TIFFError("Invalid dump option", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } *opt_offset = '\0'; /* convert option to lowercase */ end = strlen (opt_ptr); for (i = 0; i < end; i++) *(opt_ptr + i) = tolower(*(opt_ptr + i)); /* Look for dump format specification */ if (strncmp(opt_ptr, "for", 3) == 0) { /* convert value to lowercase */ end = strlen (opt_offset + 1); for (i = 1; i <= end; i++) *(opt_offset + i) = tolower(*(opt_offset + i)); /* check dump format value */ if (strncmp (opt_offset + 1, "txt", 3) == 0) { dump->format = DUMP_TEXT; strcpy (dump->mode, "w"); } else { if (strncmp(opt_offset + 1, "raw", 3) == 0) { dump->format = DUMP_RAW; strcpy (dump->mode, "wb"); } else { TIFFError("parse_command_opts", "Unknown dump format %s", opt_offset + 1); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } } } else { /* Look for dump level specification */ if (strncmp (opt_ptr, "lev", 3) == 0) dump->level = atoi(opt_offset + 1); /* Look for input data dump file name */ if (strncmp (opt_ptr, "in", 2) == 0) strncpy (dump->infilename, opt_offset + 1, PATH_MAX - 20); /* Look for output data dump file name */ if (strncmp (opt_ptr, "out", 3) == 0) strncpy (dump->outfilename, opt_offset + 1, PATH_MAX - 20); if (strncmp (opt_ptr, "deb", 3) == 0) dump->debug = atoi(opt_offset + 1); } } if ((strlen(dump->infilename)) || (strlen(dump->outfilename))) { if (dump->level == 1) TIFFError("","Defaulting to dump level 1, no data."); if (dump->format == DUMP_NONE) { TIFFError("", "You must specify a dump format for dump files"); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } } break; /* image manipulation routine options */ case 'm': /* margins to exclude from selection, uppercase M was already used */ /* order of values must be TOP, LEFT, BOTTOM, RIGHT */ crop_data->crop_mode |= CROP_MARGINS; for (i = 0, opt_ptr = strtok (optarg, ",:"); ((opt_ptr != NULL) && (i < 4)); (opt_ptr = strtok (NULL, ",:")), i++) { crop_data->margins[i] = atof(opt_ptr); } break; case 'E': /* edge reference */ switch (tolower(optarg[0])) { case 't': crop_data->edge_ref = EDGE_TOP; break; case 'b': crop_data->edge_ref = EDGE_BOTTOM; break; case 'l': crop_data->edge_ref = EDGE_LEFT; break; case 'r': crop_data->edge_ref = EDGE_RIGHT; break; default: TIFFError ("Edge reference must be top, bottom, left, or right", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'F': /* flip eg mirror image or cropped segment, M was already used */ crop_data->crop_mode |= CROP_MIRROR; switch (tolower(optarg[0])) { case 'h': crop_data->mirror = MIRROR_HORIZ; break; case 'v': crop_data->mirror = MIRROR_VERT; break; case 'b': crop_data->mirror = MIRROR_BOTH; break; default: TIFFError ("Flip mode must be horiz, vert, or both", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'H': /* set horizontal resolution to new value */ page->hres = atof (optarg); page->mode |= PAGE_MODE_RESOLUTION; break; case 'I': /* invert the color space, eg black to white */ crop_data->crop_mode |= CROP_INVERT; /* The PHOTOMETIC_INTERPRETATION tag may be updated */ if (streq(optarg, "black")) { crop_data->photometric = PHOTOMETRIC_MINISBLACK; continue; } if (streq(optarg, "white")) { crop_data->photometric = PHOTOMETRIC_MINISWHITE; continue; } if (streq(optarg, "data")) { crop_data->photometric = INVERT_DATA_ONLY; continue; } if (streq(optarg, "both")) { crop_data->photometric = INVERT_DATA_AND_TAG; continue; } TIFFError("Missing or unknown option for inverting PHOTOMETRIC_INTERPRETATION", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); break; case 'J': /* horizontal margin for sectioned ouput pages */ page->hmargin = atof(optarg); page->mode |= PAGE_MODE_MARGINS; break; case 'K': /* vertical margin for sectioned ouput pages*/ page->vmargin = atof(optarg); page->mode |= PAGE_MODE_MARGINS; break; case 'N': /* list of images to process */ for (i = 0, opt_ptr = strtok (optarg, ","); ((opt_ptr != NULL) && (i < MAX_IMAGES)); (opt_ptr = strtok (NULL, ","))) { /* We do not know how many images are in file yet * so we build a list to include the maximum allowed * and follow it until we hit the end of the file. * Image count is not accurate for odd, even, last * so page numbers won't be valid either. */ if (streq(opt_ptr, "odd")) { for (j = 1; j <= MAX_IMAGES; j += 2) imagelist[i++] = j; *image_count = (MAX_IMAGES - 1) / 2; break; } else { if (streq(opt_ptr, "even")) { for (j = 2; j <= MAX_IMAGES; j += 2) imagelist[i++] = j; *image_count = MAX_IMAGES / 2; break; } else { if (streq(opt_ptr, "last")) imagelist[i++] = MAX_IMAGES; else /* single value between commas */ { sep = strpbrk(opt_ptr, ":-"); if (!sep) imagelist[i++] = atoi(opt_ptr) - 1; else { *sep = '\0'; start = atoi (opt_ptr); if (!strcmp((sep + 1), "last")) end = MAX_IMAGES; else end = atoi (sep + 1); for (j = start; j <= end && j - start + i < MAX_IMAGES; j++) imagelist[i++] = j - 1; } } } } } *image_count = i; break; case 'O': /* page orientation */ switch (tolower(optarg[0])) { case 'a': page->orient = ORIENTATION_AUTO; break; case 'p': page->orient = ORIENTATION_PORTRAIT; break; case 'l': page->orient = ORIENTATION_LANDSCAPE; break; default: TIFFError ("Orientation must be portrait, landscape, or auto.", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'P': /* page size selection */ if (get_page_geometry (optarg, page)) { if (!strcmp(optarg, "list")) { TIFFError("", "Name Width Length (in inches)"); for (i = 0; i < MAX_PAPERNAMES - 1; i++) TIFFError ("", "%-15.15s %5.2f %5.2f", PaperTable[i].name, PaperTable[i].width, PaperTable[i].length); exit (-1); } TIFFError ("Invalid paper size", "%s", optarg); TIFFError ("", "Select one of:"); TIFFError("", "Name Width Length (in inches)"); for (i = 0; i < MAX_PAPERNAMES - 1; i++) TIFFError ("", "%-15.15s %5.2f %5.2f", PaperTable[i].name, PaperTable[i].width, PaperTable[i].length); exit (-1); } else { page->mode |= PAGE_MODE_PAPERSIZE; } break; case 'R': /* rotate image or cropped segment */ crop_data->crop_mode |= CROP_ROTATE; switch (strtoul(optarg, NULL, 0)) { case 90: crop_data->rotation = (uint16)90; break; case 180: crop_data->rotation = (uint16)180; break; case 270: crop_data->rotation = (uint16)270; break; default: TIFFError ("Rotation must be 90, 180, or 270 degrees clockwise", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'S': /* subdivide into Cols:Rows sections, eg 3:2 would be 3 across and 2 down */ sep = strpbrk(optarg, ",:"); if (sep) { *sep = '\0'; page->cols = atoi(optarg); page->rows = atoi(sep +1); } else { page->cols = atoi(optarg); page->rows = atoi(optarg); } if ((page->cols * page->rows) > MAX_SECTIONS) { TIFFError ("Limit for subdivisions, ie rows x columns, exceeded", "%d", MAX_SECTIONS); exit (-1); } page->mode |= PAGE_MODE_ROWSCOLS; break; case 'U': /* units for measurements and offsets */ if (streq(optarg, "in")) { crop_data->res_unit = RESUNIT_INCH; page->res_unit = RESUNIT_INCH; } else if (streq(optarg, "cm")) { crop_data->res_unit = RESUNIT_CENTIMETER; page->res_unit = RESUNIT_CENTIMETER; } else if (streq(optarg, "px")) { crop_data->res_unit = RESUNIT_NONE; page->res_unit = RESUNIT_NONE; } else { TIFFError ("Illegal unit of measure","%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'V': /* set vertical resolution to new value */ page->vres = atof (optarg); page->mode |= PAGE_MODE_RESOLUTION; break; case 'X': /* selection width */ crop_data->crop_mode |= CROP_WIDTH; crop_data->width = atof(optarg); break; case 'Y': /* selection length */ crop_data->crop_mode |= CROP_LENGTH; crop_data->length = atof(optarg); break; case 'Z': /* zones of an image X:Y read as zone X of Y */ crop_data->crop_mode |= CROP_ZONES; for (i = 0, opt_ptr = strtok (optarg, ","); ((opt_ptr != NULL) && (i < MAX_REGIONS)); (opt_ptr = strtok (NULL, ",")), i++) { crop_data->zones++; opt_offset = strchr(opt_ptr, ':'); *opt_offset = '\0'; crop_data->zonelist[i].position = atoi(opt_ptr); crop_data->zonelist[i].total = atoi(opt_offset + 1); } /* check for remaining elements over MAX_REGIONS */ if ((opt_ptr != NULL) && (i >= MAX_REGIONS)) { TIFFError("Zone list exceeds region limit", "%d", MAX_REGIONS); exit (-1); } break; case '?': TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); /*NOTREACHED*/ } } } /* end process_command_opts */ /* Start a new output file if one has not been previously opened or * autoindex is set to non-zero. Update page and file counters * so TIFFTAG PAGENUM will be correct in image. */ static int update_output_file (TIFF **tiffout, char *mode, int autoindex, char *outname, unsigned int *page) { static int findex = 0; /* file sequence indicator */ char *sep; char filenum[16]; char export_ext[16]; char exportname[PATH_MAX]; strcpy (export_ext, ".tiff"); if (autoindex && (*tiffout != NULL)) { /* Close any export file that was previously opened */ TIFFClose (*tiffout); *tiffout = NULL; } strncpy (exportname, outname, PATH_MAX - 15); if (*tiffout == NULL) /* This is a new export file */ { if (autoindex) { /* create a new filename for each export */ findex++; if ((sep = strstr(exportname, ".tif")) || (sep = strstr(exportname, ".TIF"))) { strncpy (export_ext, sep, 5); *sep = '\0'; } else strncpy (export_ext, ".tiff", 5); export_ext[5] = '\0'; sprintf (filenum, "-%03d%s", findex, export_ext); filenum[15] = '\0'; strncat (exportname, filenum, 14); } *tiffout = TIFFOpen(exportname, mode); if (*tiffout == NULL) { TIFFError("update_output_file", "Unable to open output file %s\n", exportname); return (1); } *page = 0; return (0); } else (*page)++; return (0); } /* end update_output_file */ int main(int argc, char* argv[]) { uint16 defconfig = (uint16) -1; uint16 deffillorder = 0; uint32 deftilewidth = (uint32) -1; uint32 deftilelength = (uint32) -1; uint32 defrowsperstrip = (uint32) 0; uint32 dirnum = 0; extern int optind; TIFF *in = NULL; TIFF *out = NULL; char mode[10]; char *mp = mode; /** RJN additions **/ struct image_data image; /* Image parameters for one image */ struct crop_mask crop; /* Cropping parameters for all images */ struct pagedef page; /* Page definition for output pages */ struct pageseg sections[MAX_SECTIONS]; /* Sections of one output page */ struct buffinfo seg_buffs[MAX_SECTIONS]; /* Segment buffer sizes and pointers */ struct dump_opts dump; /* Data dump options */ unsigned char *read_buff = NULL; /* Input image data buffer */ unsigned char *crop_buff = NULL; /* Crop area buffer */ unsigned char *sect_buff = NULL; /* Image section buffer */ unsigned char *sect_src = NULL; /* Image section buffer pointer */ unsigned int imagelist[MAX_IMAGES + 1]; /* individually specified images */ unsigned int image_count = 0; unsigned int dump_images = 0; unsigned int next_image = 0; unsigned int next_page = 0; unsigned int total_pages = 0; unsigned int total_images = 0; unsigned int end_of_input = FALSE; int seg, length; char temp_filename[PATH_MAX + 1]; memset (temp_filename, '\0', PATH_MAX + 1); little_endian = *((unsigned char *)&little_endian) & '1'; initImageData(&image); initCropMasks(&crop); initPageSetup(&page, sections, seg_buffs); initDumpOptions(&dump); process_command_opts (argc, argv, mp, mode, &dirnum, &defconfig, &deffillorder, &deftilewidth, &deftilelength, &defrowsperstrip, &crop, &page, &dump, imagelist, &image_count); if (argc - optind < 2) usage(); if ((argc - optind) == 2) pageNum = -1; else total_images = 0; /* read multiple input files and write to output file(s) */ while (optind < argc - 1) { in = TIFFOpen (argv[optind], "r"); if (in == NULL) return (-3); /* If only one input file is specified, we can use directory count */ total_images = TIFFNumberOfDirectories(in); if (image_count == 0) { dirnum = 0; total_pages = total_images; /* Only valid with single input file */ } else { dirnum = (tdir_t)(imagelist[next_image] - 1); next_image++; /* Total pages only valid for enumerated list of pages not derived * using odd, even, or last keywords. */ if (image_count > total_images) image_count = total_images; total_pages = image_count; } /* MAX_IMAGES is used for special case "last" in selection list */ if (dirnum == (MAX_IMAGES - 1)) dirnum = total_images - 1; if (dirnum > (total_images)) { TIFFError (TIFFFileName(in), "Invalid image number %d, File contains only %d images", (int)dirnum + 1, total_images); if (out != NULL) (void) TIFFClose(out); return (1); } if (dirnum != 0 && !TIFFSetDirectory(in, (tdir_t)dirnum)) { TIFFError(TIFFFileName(in),"Error, setting subdirectory at %d", dirnum); if (out != NULL) (void) TIFFClose(out); return (1); } end_of_input = FALSE; while (end_of_input == FALSE) { config = defconfig; compression = defcompression; predictor = defpredictor; fillorder = deffillorder; rowsperstrip = defrowsperstrip; tilewidth = deftilewidth; tilelength = deftilelength; g3opts = defg3opts; if (dump.format != DUMP_NONE) { /* manage input and/or output dump files here */ dump_images++; length = strlen(dump.infilename); if (length > 0) { if (dump.infile != NULL) fclose (dump.infile); sprintf (temp_filename, "%s-read-%03d.%s", dump.infilename, dump_images, (dump.format == DUMP_TEXT) ? "txt" : "raw"); if ((dump.infile = fopen(temp_filename, dump.mode)) == NULL) { TIFFError ("Unable to open dump file %s for writing", temp_filename); exit (-1); } dump_info(dump.infile, dump.format, "Reading image","%d from %s", dump_images, TIFFFileName(in)); } length = strlen(dump.outfilename); if (length > 0) { if (dump.outfile != NULL) fclose (dump.outfile); sprintf (temp_filename, "%s-write-%03d.%s", dump.outfilename, dump_images, (dump.format == DUMP_TEXT) ? "txt" : "raw"); if ((dump.outfile = fopen(temp_filename, dump.mode)) == NULL) { TIFFError ("Unable to open dump file %s for writing", temp_filename); exit (-1); } dump_info(dump.outfile, dump.format, "Writing image","%d from %s", dump_images, TIFFFileName(in)); } } if (dump.debug) TIFFError("main", "Reading image %4d of %4d total pages.", dirnum + 1, total_pages); if (loadImage(in, &image, &dump, &read_buff)) { TIFFError("main", "Unable to load source image"); exit (-1); } /* Correct the image orientation if it was not ORIENTATION_TOPLEFT. */ if (image.adjustments != 0) { if (correct_orientation(&image, &read_buff)) TIFFError("main", "Unable to correct image orientation"); } if (getCropOffsets(&image, &crop, &dump)) { TIFFError("main", "Unable to define crop regions"); exit (-1); } if (crop.selections > 0) { if (processCropSelections(&image, &crop, &read_buff, seg_buffs)) { TIFFError("main", "Unable to process image selections"); exit (-1); } } else /* Single image segment without zones or regions */ { if (createCroppedImage(&image, &crop, &read_buff, &crop_buff)) { TIFFError("main", "Unable to create output image"); exit (-1); } } if (page.mode == PAGE_MODE_NONE) { /* Whole image or sections not based on output page size */ if (crop.selections > 0) { writeSelections(in, &out, &crop, &image, &dump, seg_buffs, mp, argv[argc - 1], &next_page, total_pages); } else /* One file all images and sections */ { if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1], &next_page)) exit (1); if (writeCroppedImage(in, out, &image, &dump,crop.combined_width, crop.combined_length, crop_buff, next_page, total_pages)) { TIFFError("main", "Unable to write new image"); exit (-1); } } } else { /* If we used a crop buffer, our data is there, otherwise it is * in the read_buffer */ if (crop_buff != NULL) sect_src = crop_buff; else sect_src = read_buff; /* Break input image into pages or rows and columns */ if (computeOutputPixelOffsets(&crop, &image, &page, sections, &dump)) { TIFFError("main", "Unable to compute output section data"); exit (-1); } /* If there are multiple files on the command line, the final one is assumed * to be the output filename into which the images are written. */ if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1], &next_page)) exit (1); if (writeImageSections(in, out, &image, &page, sections, &dump, sect_src, &sect_buff)) { TIFFError("main", "Unable to write image sections"); exit (-1); } } /* No image list specified, just read the next image */ if (image_count == 0) dirnum++; else { dirnum = (tdir_t)(imagelist[next_image] - 1); next_image++; } if (dirnum == MAX_IMAGES - 1) dirnum = TIFFNumberOfDirectories(in) - 1; if (!TIFFSetDirectory(in, (tdir_t)dirnum)) end_of_input = TRUE; } TIFFClose(in); optind++; } /* If we did not use the read buffer as the crop buffer */ if (read_buff) _TIFFfree(read_buff); if (crop_buff) _TIFFfree(crop_buff); if (sect_buff) _TIFFfree(sect_buff); /* Clean up any segment buffers used for zones or regions */ for (seg = 0; seg < crop.selections; seg++) _TIFFfree (seg_buffs[seg].buffer); if (dump.format != DUMP_NONE) { if (dump.infile != NULL) fclose (dump.infile); if (dump.outfile != NULL) { dump_info (dump.outfile, dump.format, "", "Completed run for %s", TIFFFileName(out)); fclose (dump.outfile); } } TIFFClose(out); return (0); } /* end main */ /* Debugging functions */ static int dump_data (FILE *dumpfile, int format, char *dump_tag, unsigned char *data, uint32 count) { int j, k; uint32 i; char dump_array[10]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file\n"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (i = 0; i < count; i++) { for (j = 0, k = 7; j < 8; j++, k--) { bitset = (*(data + i)) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); } dump_array[8] = '\0'; fprintf (dumpfile," %s", dump_array); } fprintf (dumpfile,"\n"); } else { if ((fwrite (data, 1, count, dumpfile)) != count) { TIFFError ("", "Unable to write binary data to dump file\n"); return (1); } } return (0); } static int dump_byte (FILE *dumpfile, int format, char *dump_tag, unsigned char data) { int j, k; char dump_array[10]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file\n"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 7; j < 8; j++, k--) { bitset = data & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); } dump_array[8] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 1, 1, dumpfile)) != 1) { TIFFError ("", "Unable to write binary data to dump file\n"); return (1); } } return (0); } static int dump_short (FILE *dumpfile, int format, char *dump_tag, uint16 data) { int j, k; char dump_array[20]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file\n"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 15; k >= 0; j++, k--) { bitset = data & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); if ((k % 8) == 0) sprintf(&dump_array[++j], " "); } dump_array[17] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 2, 1, dumpfile)) != 2) { TIFFError ("", "Unable to write binary data to dump file\n"); return (1); } } return (0); } static int dump_long (FILE *dumpfile, int format, char *dump_tag, uint32 data) { int j, k; char dump_array[40]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file\n"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 31; k >= 0; j++, k--) { bitset = data & (((uint32)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); if ((k % 8) == 0) sprintf(&dump_array[++j], " "); } dump_array[35] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 4, 1, dumpfile)) != 4) { TIFFError ("", "Unable to write binary data to dump file\n"); return (1); } } return (0); } static int dump_wide (FILE *dumpfile, int format, char *dump_tag, uint64 data) { int j, k; char dump_array[80]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file\n"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 63; k >= 0; j++, k--) { bitset = data & (((uint64)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); if ((k % 8) == 0) sprintf(&dump_array[++j], " "); } dump_array[71] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 8, 1, dumpfile)) != 8) { TIFFError ("", "Unable to write binary data to dump file\n"); return (1); } } return (0); } static void dump_info(FILE *dumpfile, int format, char *prefix, char *msg, ...) { if (format == DUMP_TEXT) { va_list ap; va_start(ap, msg); fprintf(dumpfile, "%s ", prefix); vfprintf(dumpfile, msg, ap); fprintf(dumpfile, "\n"); } } static int dump_buffer (FILE* dumpfile, int format, uint32 rows, uint32 width, uint32 row, unsigned char *buff) { int j, k; uint32 i; unsigned char * dump_ptr; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file\n"); return (1); } for (i = 0; i < rows; i++) { dump_ptr = buff + (i * width); if (format == DUMP_TEXT) dump_info (dumpfile, format, "", "Row %4d, %d bytes at offset %d", row + i + 1, width, row * width); for (j = 0, k = width; k >= 10; j += 10, k -= 10, dump_ptr += 10) dump_data (dumpfile, format, "", dump_ptr, 10); if (k > 0) dump_data (dumpfile, format, "", dump_ptr, k); } return (0); } /* Extract one or more samples from an interleaved buffer. If count == 1, * only the sample plane indicated by sample will be extracted. If count > 1, * count samples beginning at sample will be extracted. Portions of a * scanline can be extracted by specifying a start and end value. */ static int extractContigSamplesBytes (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int i, bytes_per_sample, sindex; uint32 col, dst_rowsize, bit_offset; uint32 src_byte, src_bit; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamplesBytes","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesBytes", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesBytes", "Invalid end column value %d ignored", end); end = cols; } dst_rowsize = (bps * (end - start) * count) / 8; bytes_per_sample = (bps + 7) / 8; /* Optimize case for copying all samples */ if (count == spp) { src = in + (start * spp * bytes_per_sample); _TIFFmemcpy (dst, src, dst_rowsize); } else { for (col = start; col < end; col++) { for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { bit_offset = col * bps * spp; if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; for (i = 0; i < bytes_per_sample; i++) *dst++ = *src++; } } } return (0); } /* end extractContigSamplesBytes */ static int extractContigSamples8bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamples8bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples8bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples8bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = 0; maskbits = (uint8)-1 >> ( 8 - bps); buff1 = buff2 = 0; for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (8 - src_bit - bps); buff1 = ((*src) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; } else buff2 = (buff2 | (buff1 >> ready_bits)); ready_bits += bps; } } while (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; ready_bits -= 8; } return (0); } /* end extractContigSamples8bits */ static int extractContigSamples16bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; uint8 *src = in; uint8 *dst = out; unsigned char swapbuff[2]; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamples16bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples16bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples16bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = 0; maskbits = (uint16)-1 >> (16 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (16 - src_bit - bps); if (little_endian) { swapbuff[1] = *src; swapbuff[0] = *(src + 1); } else { swapbuff[0] = *src; swapbuff[1] = *(src + 1); } buff1 = *((uint16 *)swapbuff); buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 8) /* add another bps bits to the buffer */ { bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; } return (0); } /* end extractContigSamples16bits */ static int extractContigSamples24bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; uint8 *src = in; uint8 *dst = out; unsigned char swapbuff[4]; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamples24bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples24bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples24bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = 0; maskbits = (uint32)-1 >> ( 32 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (32 - src_bit - bps); if (little_endian) { swapbuff[3] = *src; swapbuff[2] = *(src + 1); swapbuff[1] = *(src + 2); swapbuff[0] = *(src + 3); } else { swapbuff[0] = *src; swapbuff[1] = *(src + 1); swapbuff[2] = *(src + 2); swapbuff[3] = *(src + 3); } buff1 = *((uint32 *)swapbuff); buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 16) /* add another bps bits to the buffer */ { bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end extractContigSamples24bits */ static int extractContigSamples32bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0, shift_width = 0; uint32 col, src_byte, src_bit, bit_offset; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; uint8 *src = in; uint8 *dst = out; unsigned char swapbuff1[4]; unsigned char swapbuff2[4]; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamples32bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples32bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples32bits", "Invalid end column value %d ignored", end); end = cols; } shift_width = ((bps + 7) / 8) + 1; ready_bits = 0; maskbits = (uint64)-1 >> ( 64 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (64 - src_bit - bps); if (little_endian) { swapbuff1[3] = *src; swapbuff1[2] = *(src + 1); swapbuff1[1] = *(src + 2); swapbuff1[0] = *(src + 3); } else { swapbuff1[0] = *src; swapbuff1[1] = *(src + 1); swapbuff1[2] = *(src + 2); swapbuff1[3] = *(src + 3); } longbuff1 = *((uint32 *)swapbuff1); memset (swapbuff2, '\0', sizeof(swapbuff2)); if (little_endian) { swapbuff2[3] = *src; swapbuff2[2] = *(src + 1); swapbuff2[1] = *(src + 2); swapbuff2[0] = *(src + 3); } else { swapbuff2[0] = *src; swapbuff2[1] = *(src + 1); swapbuff2[2] = *(src + 2); swapbuff2[3] = *(src + 3); } longbuff2 = *((uint32 *)swapbuff2); buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 32) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end extractContigSamples32bits */ static int extractContigSamplesShifted8bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamplesShifted8bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted8bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted8bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = shift; maskbits = (uint8)-1 >> ( 8 - bps); buff1 = buff2 = 0; for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (8 - src_bit - bps); buff1 = ((*src) & matchbits) << (src_bit); if ((col == start) && (sindex == sample)) buff2 = *src & ((uint8)-1) << (shift); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ |= buff2; buff2 = buff1; ready_bits -= 8; } else buff2 = buff2 | (buff1 >> ready_bits); ready_bits += bps; } } while (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted8bits */ static int extractContigSamplesShifted16bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; uint8 *src = in; uint8 *dst = out; unsigned char swapbuff[2]; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamplesShifted16bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted16bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted16bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = shift; maskbits = (uint16)-1 >> (16 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (16 - src_bit - bps); if (little_endian) { swapbuff[1] = *src; swapbuff[0] = *(src + 1); } else { swapbuff[0] = *src; swapbuff[1] = *(src + 1); } buff1 = *((uint16 *)swapbuff); if ((col == start) && (sindex == sample)) buff2 = buff1 & ((uint16)-1) << (8 - shift); buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 8) /* add another bps bits to the buffer */ buff2 = buff2 | (buff1 >> ready_bits); else /* If we have a full buffer's worth, write it out */ { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted16bits */ static int extractContigSamplesShifted24bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; uint8 *src = in; uint8 *dst = out; unsigned char swapbuff[4]; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamplesShifted24bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted24bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted24bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = shift; maskbits = (uint32)-1 >> ( 32 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (32 - src_bit - bps); if (little_endian) { swapbuff[3] = *src; swapbuff[2] = *(src + 1); swapbuff[1] = *(src + 2); swapbuff[0] = *(src + 3); } else { swapbuff[0] = *src; swapbuff[1] = *(src + 1); swapbuff[2] = *(src + 2); swapbuff[3] = *(src + 3); } buff1 = *((uint32 *)swapbuff); if ((col == start) && (sindex == sample)) buff2 = buff1 & ((uint32)-1) << (16 - shift); buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 16) /* add another bps bits to the buffer */ { bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted24bits */ static int extractContigSamplesShifted32bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0, shift_width = 0; uint32 col, src_byte, src_bit, bit_offset; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; uint8 *src = in; uint8 *dst = out; unsigned char swapbuff1[4]; unsigned char swapbuff2[4]; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamplesShifted32bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted32bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted32bits", "Invalid end column value %d ignored", end); end = cols; } shift_width = ((bps + 7) / 8) + 1; ready_bits = shift; maskbits = (uint64)-1 >> ( 64 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (64 - src_bit - bps); if (little_endian) { swapbuff1[3] = *src; swapbuff1[2] = *(src + 1); swapbuff1[1] = *(src + 2); swapbuff1[0] = *(src + 3); } else { swapbuff1[0] = *src; swapbuff1[1] = *(src + 1); swapbuff1[2] = *(src + 2); swapbuff1[3] = *(src + 3); } longbuff1 = *((uint32 *)swapbuff1); memset (swapbuff2, '\0', sizeof(swapbuff2)); if (little_endian) { swapbuff2[3] = *src; swapbuff2[2] = *(src + 1); swapbuff2[1] = *(src + 2); swapbuff2[0] = *(src + 3); } else { swapbuff2[0] = *src; swapbuff2[1] = *(src + 1); swapbuff2[2] = *(src + 2); swapbuff2[3] = *(src + 3); } longbuff2 = *((uint32 *)swapbuff2); buff3 = ((uint64)longbuff1 << 32) | longbuff2; if ((col == start) && (sindex == sample)) buff2 = buff3 & ((uint64)-1) << (32 - shift); buff1 = (buff3 & matchbits) << (src_bit); if (ready_bits < 32) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted32bits */ static int extractContigSamplesToBuffer(uint8 *out, uint8 *in, uint32 rows, uint32 cols, int outskew, int inskew, tsample_t sample, uint16 spp, uint16 bps, struct dump_opts *dump) { int shift_width, bytes_per_sample, bytes_per_pixel; uint32 src_rowsize, src_offset, row, first_col = 0; uint32 dst_rowsize, dst_offset; tsample_t count = 1; uint8 *src, *dst; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } src_rowsize = ((bps * spp * cols) + 7) / 8; dst_rowsize = ((bps * cols) + 7) / 8; if ((dump->outfile != NULL) && (dump->level == 4)) { dump_info (dump->outfile, dump->format, "extractContigSamplesToBuffer", "Sample %d, %d rows", sample + 1, rows + 1); } for (row = 0; row < rows; row++) { src_offset = row * src_rowsize; dst_offset = row * dst_rowsize; src = in + src_offset; dst = out + dst_offset; /* pack the data into the scanline */ switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; case 1: if (extractContigSamples8bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; case 2: if (extractContigSamples16bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; case 3: if (extractContigSamples24bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; case 4: case 5: if (extractContigSamples32bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; default: TIFFError ("extractContigSamplesToBuffer", "Unsupported bit depth: %d", bps); return (1); } if ((dump->outfile != NULL) && (dump->level == 4)) dump_buffer(dump->outfile, dump->format, 1, dst_rowsize, row, dst); out += outskew; in += inskew; } return (0); } /* end extractContigSamplesToBuffer */ /* This will not work unless bps is a multiple of 8 */ static void cpSeparateBufToContigBuf(uint8 *out, uint8 *in, uint32 rows, uint32 cols, int outskew, int inskew, tsample_t spp, int bytes_per_sample) { while (rows-- > 0) { uint32 j = cols; while (j-- > 0) { int n = bytes_per_sample; while( n-- ) { *out++ = *in++; } out += (spp-1)*bytes_per_sample; } out += outskew; in += inskew; } } /* end of cpSeparateBufToContifBuf */ static int readContigStripsIntoBuffer (TIFF* in, uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp) { tsize_t scanlinesize = TIFFScanlineSize(in); uint8* bufp = buf; uint32 row; (void) imagewidth; (void) spp; for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, (tdata_t) bufp, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in),"Error, can't read scanline %lu", (unsigned long) row); return 0; } bufp += scanlinesize; } return 1; } /* end readContigStripsIntoBuffer */ static int combineSeparateSamples8bits (uint8 *in[], uint8 *out, uint32 row, uint32 cols, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0; int bytes_per_sample = 0; uint32 dst_rowsize; uint32 bit_offset; uint32 col, src_byte = 0, src_bit = 0; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[32]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples8bits","Invalid input or output buffer"); return (1); } bytes_per_sample = (bps + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint8)-1 >> ( 8 - bps); ready_bits = 0; buff1 = buff2 = 0; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (8 - src_bit - bps); /* load up next sample from each plane */ for (s = 0; s < spp; s++) { src = in[s] + src_byte; buff1 = ((*src) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; strcpy (action, "Flush"); } else { buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Match bits", matchbits); dump_byte (dumpfile, format, "Src bits", *src); dump_byte (dumpfile, format, "Buff1 bits", buff1); dump_byte (dumpfile, format, "Buff2 bits", buff2); dump_info (dumpfile, format, "","%s", action); } } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", buff1); } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamples8bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out); } return (0); } /* end combineSeparateSamples8bits */ static int combineSeparateSamples16bits (uint8 *in[], uint8 *out, uint32 row, uint32 cols, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0, bytes_per_sample = 0; uint32 dst_rowsize; uint32 bit_offset; uint32 col, src_byte = 0, src_bit = 0; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; unsigned char swapbuff[2]; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples16bits","Invalid input or output buffer"); return (1); } bytes_per_sample = (bps + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint16)-1 >> (16 - bps); ready_bits = 0; buff1 = buff2 = 0; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (16 - src_bit - bps); for (s = 0; s < spp; s++) { src = in[s] + src_byte; if (little_endian) { swapbuff[1] = *src; swapbuff[0] = *(src + 1); } else { swapbuff[0] = *src; swapbuff[1] = *(src + 1); } buff1 = *((uint16 *)swapbuff); buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_short (dumpfile, format, "Match bits", matchbits); dump_data (dumpfile, format, "Src bits", src, 2); dump_short (dumpfile, format, "Buff1 bits", buff1); dump_short (dumpfile, format, "Buff2 bits", buff2); dump_byte (dumpfile, format, "Write byte", bytebuff); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", bytebuff); } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamples16bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out); } return (0); } /* end combineSeparateSamples16bits */ static int combineSeparateSamples24bits (uint8 *in[], uint8 *out, uint32 row, uint32 cols, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0, bytes_per_sample = 0; uint32 dst_rowsize; uint32 bit_offset; uint32 col, src_byte = 0, src_bit = 0; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; unsigned char swapbuff[4]; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples24bits","Invalid input or output buffer"); return (1); } bytes_per_sample = (bps + 7) / 8; dst_rowsize = ((bps * cols) + 7) / 8; maskbits = (uint32)-1 >> ( 32 - bps); ready_bits = 0; buff1 = buff2 = 0; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (32 - src_bit - bps); for (s = 0; s < spp; s++) { src = in[s] + src_byte; if (little_endian) { swapbuff[3] = *src; swapbuff[2] = *(src + 1); swapbuff[1] = *(src + 2); swapbuff[0] = *(src + 3); } else { swapbuff[0] = *src; swapbuff[1] = *(src + 1); swapbuff[2] = *(src + 2); swapbuff[3] = *(src + 3); } buff1 = *((uint32 *)swapbuff); buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 16) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamples24bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out); } return (0); } /* end combineSeparateSamples24bits */ static int combineSeparateSamples32bits (uint8 *in[], uint8 *out, uint32 row, uint32 cols, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0, bytes_per_sample = 0, shift_width = 0; uint32 dst_rowsize; uint32 bit_offset; uint32 src_byte = 0, src_bit = 0; uint32 col; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; unsigned char swapbuff1[4]; unsigned char swapbuff2[4]; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples32bits","Invalid input or output buffer"); return (1); } bytes_per_sample = (bps + 7) / 8; dst_rowsize = ((bps * cols) + 7) / 8; maskbits = (uint64)-1 >> ( 64 - bps); shift_width = ((bps + 7) / 8) + 1; ready_bits = 0; buff1 = buff2 = 0; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (64 - src_bit - bps); for (s = 0; s < spp; s++) { src = in[s] + src_byte; if (little_endian) { swapbuff1[3] = *src; swapbuff1[2] = *(src + 1); swapbuff1[1] = *(src + 2); swapbuff1[0] = *(src + 3); } else { swapbuff1[0] = *src; swapbuff1[1] = *(src + 1); swapbuff1[2] = *(src + 2); swapbuff1[3] = *(src + 3); } longbuff1 = *((uint32 *)swapbuff1); memset (swapbuff2, '\0', sizeof(swapbuff2)); if (little_endian) { swapbuff2[3] = *src; swapbuff2[2] = *(src + 1); swapbuff2[1] = *(src + 2); swapbuff2[0] = *(src + 3); } else { swapbuff2[0] = *src; swapbuff2[1] = *(src + 1); swapbuff2[2] = *(src + 2); swapbuff2[3] = *(src + 3); } longbuff2 = *((uint32 *)swapbuff2); buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 32) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Sample %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_wide (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 8); dump_wide (dumpfile, format, "Buff1 bits ", buff1); dump_wide (dumpfile, format, "Buff2 bits ", buff2); dump_info (dumpfile, format, "", "Ready bits: %d, %s", ready_bits, action); } } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamples32bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out); } return (0); } /* end combineSeparateSamples32bits */ static int combineSeparateSamplesBytes (unsigned char *srcbuffs[], unsigned char *out, uint32 row, uint32 width, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int i, bytes_per_sample, bytes_per_pixel, dst_rowsize, shift_width; uint32 col, col_offset; unsigned char *src; unsigned char *dst; tsample_t s; src = srcbuffs[0]; dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamplesBytes","Invalid buffer address"); return (1); } bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_sample; else shift_width = bytes_per_pixel; if ((dumpfile != NULL) && (level == 2)) { for (s = 0; s < spp; s++) { dump_info (dumpfile, format, "combineSeparateSamplesBytes","Input data, Sample %d", s); dump_buffer(dumpfile, format, 1, width, row, srcbuffs[s]); } } dst_rowsize = ((bps * spp * width) + 7) / 8; for (col = 0; col < width; col++) { col_offset = col * (bps / 8); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = srcbuffs[s] + col_offset; for (i = 0; i < bytes_per_sample; i++) *(dst + i) = *(src + i); src += bytes_per_sample; dst += bytes_per_sample; } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamplesBytes","Output data, combined samples"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out); } return (0); } /* end combineSeparateSamplesBytes */ static int readSeparateStripsIntoBuffer (TIFF *in, uint8 *obuf, uint32 length, uint32 width, uint16 spp, struct dump_opts *dump) { int i, bytes_per_sample, bytes_per_pixel, shift_width; uint16 bps; uint32 row, src_rowsize, dst_rowsize; tsample_t s; tsize_t scanlinesize = TIFFScanlineSize(in); unsigned char *srcbuffs[MAX_SAMPLES]; unsigned char *buff = NULL; unsigned char *dst = NULL; (void) TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps); if (obuf == NULL) { TIFFError("readSeparateStripsIntoBuffer","Invalid buffer argument"); return (0); } bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; src_rowsize = ((bps * width) + 7) / 8; dst_rowsize = ((bps * width * spp) + 7) / 8; dst = obuf; if ((dump->infile != NULL) && (dump->level == 3)) { dump_info (dump->infile, dump->format, "", "Image width %d, length %d, Scanline size, %4d bytes", width, length, scanlinesize); dump_info (dump->infile, dump->format, "", "Bits per sample %d, Samples per pixel %d, Shift width %d", bps, spp, shift_width); } /* allocate scanline buffers for each sample */ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { srcbuffs[s] = NULL; buff = _TIFFmalloc(src_rowsize); if (!buff) { TIFFError ("readSeparateStripsIntoBuffer", "Unable to allocate read buffer for sample %d", s); for (i = 0; i < s; i++) _TIFFfree (srcbuffs[i]); return 0; } srcbuffs[s] = buff; } /* read and process one scanline from each sample */ for (row = 0; row < length; row++) { for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { buff = srcbuffs[s]; /* read one scanline in the current sample color */ if (TIFFReadScanline(in, buff, row, s) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu for sample %d", (unsigned long) row, s + 1); for (i = 0; i < s; i++) _TIFFfree (srcbuffs[i]); return (0); } } /* combine the samples in each scanline */ dst = obuf + (row * dst_rowsize); if ((bps % 8) == 0) { if (combineSeparateSamplesBytes (srcbuffs, dst, row, width, spp, bps, dump->infile, dump->format, dump->level)) { for (i = 0; i < spp; i++) _TIFFfree (srcbuffs[i]); return (0); } } else { switch (shift_width) { case 1: if (combineSeparateSamples8bits (srcbuffs, dst, row, width, spp, bps, dump->infile, dump->format, dump->level)) { for (i = 0; i < spp; i++) _TIFFfree (srcbuffs[i]); return (0); } break; case 2: if (combineSeparateSamples16bits (srcbuffs, dst, row, width, spp, bps, dump->infile, dump->format, dump->level)) { for (i = 0; i < spp; i++) _TIFFfree (srcbuffs[i]); return (0); } break; case 3: if (combineSeparateSamples24bits (srcbuffs, dst, row, width, spp, bps, dump->infile, dump->format, dump->level)) { for (i = 0; i < spp; i++) _TIFFfree (srcbuffs[i]); return (0); } break; case 4: case 5: case 6: case 7: case 8: if (combineSeparateSamples32bits (srcbuffs, dst, row, width, spp, bps, dump->infile, dump->format, dump->level)) { for (i = 0; i < spp; i++) _TIFFfree (srcbuffs[i]); return (0); } break; default: TIFFError ("readSeparateStripsIntoBuffer", "Unsupported bit depth: %d", bps); for (i = 0; i < spp; i++) _TIFFfree (srcbuffs[i]); return (0); } } } /* free any buffers allocated for each plane or scanline and * any temporary buffers */ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { buff = srcbuffs[s]; if (buff != NULL) _TIFFfree(buff); } return (1); } /* end readSeparateStripsIntoBuffer */ static int get_page_geometry (char *name, struct pagedef *page) { char *ptr; int n; for (ptr = name; *ptr; ptr++) *ptr = (char)tolower((int)*ptr); for (n = 0; n < MAX_PAPERNAMES; n++) { if (strcmp(name, PaperTable[n].name) == 0) { page->width = PaperTable[n].width; page->length = PaperTable[n].length; strncpy (page->name, PaperTable[n].name, 15); page->name[15] = '\0'; return (0); } } return (1); } static void initPageSetup (struct pagedef *page, struct pageseg *pagelist, struct buffinfo seg_buffs[]) { int i; strcpy (page->name, ""); page->mode = PAGE_MODE_NONE; page->res_unit = RESUNIT_NONE; page->hres = 0.0; page->vres = 0.0; page->width = 0.0; page->length = 0.0; page->hmargin = 0.0; page->vmargin = 0.0; page->rows = 0; page->cols = 0; page->orient = ORIENTATION_NONE; for (i = 0; i < MAX_SECTIONS; i++) { pagelist[i].x1 = (uint32)0; pagelist[i].x2 = (uint32)0; pagelist[i].y1 = (uint32)0; pagelist[i].y2 = (uint32)0; pagelist[i].buffsize = (uint32)0; pagelist[i].position = 0; pagelist[i].total = 0; } for (i = 0; i < MAX_OUTBUFFS; i++) { seg_buffs[i].size = 0; seg_buffs[i].buffer = NULL; } } static void initImageData (struct image_data *image) { image->xres = 0.0; image->yres = 0.0; image->width = 0; image->length = 0; image->res_unit = RESUNIT_NONE; image->bps = 0; image->spp = 0; image->planar = 0; image->photometric = 0; image->orientation = 0; image->adjustments = 0; } static void initCropMasks (struct crop_mask *cps) { int i; cps->crop_mode = CROP_NONE; cps->res_unit = RESUNIT_NONE; cps->edge_ref = EDGE_TOP; cps->width = 0; cps->length = 0; for (i = 0; i < 4; i++) cps->margins[i] = 0.0; cps->bufftotal = (uint32)0; cps->combined_width = (uint32)0; cps->combined_length = (uint32)0; cps->rotation = (uint16)0; cps->photometric = INVERT_DATA_AND_TAG; cps->mirror = (uint16)0; cps->invert = (uint16)0; cps->zones = (uint32)0; cps->regions = (uint32)0; for (i = 0; i < MAX_REGIONS; i++) { cps->corners[i].X1 = 0.0; cps->corners[i].X2 = 0.0; cps->corners[i].Y1 = 0.0; cps->corners[i].Y2 = 0.0; cps->regionlist[i].x1 = 0; cps->regionlist[i].x2 = 0; cps->regionlist[i].y1 = 0; cps->regionlist[i].y2 = 0; cps->regionlist[i].width = 0; cps->regionlist[i].length = 0; cps->regionlist[i].buffsize = 0; cps->regionlist[i].buffptr = NULL; cps->zonelist[i].position = 0; cps->zonelist[i].total = 0; } cps->exp_mode = ONE_FILE_COMPOSITE; cps->img_mode = COMPOSITE_IMAGES; } static void initDumpOptions(struct dump_opts *dump) { dump->debug = 0; dump->format = DUMP_NONE; dump->level = 1; sprintf (dump->mode, "w"); memset (dump->infilename, '\0', PATH_MAX + 1); memset (dump->outfilename, '\0',PATH_MAX + 1); dump->infile = NULL; dump->outfile = NULL; } /* Compute pixel offsets into the image for margins and fixed regions */ static int computeInputPixelOffsets(struct crop_mask *crop, struct image_data *image, struct offset *off) { double scale; float xres, yres; /* Values for these offsets are in pixels from start of image, not bytes, * and are indexed from zero to width - 1 or length - 1 */ uint32 tmargin, bmargin, lmargin, rmargin; uint32 startx, endx; /* offsets of first and last columns to extract */ uint32 starty, endy; /* offsets of first and last row to extract */ uint32 width, length, crop_width, crop_length; uint32 i, max_width, max_length, zwidth, zlength, buffsize; uint32 x1, x2, y1, y2; if (image->res_unit != RESUNIT_INCH && image->res_unit != RESUNIT_CENTIMETER) { xres = 1.0; yres = 1.0; } else { if (((image->xres == 0) || (image->yres == 0)) && ((crop->crop_mode & CROP_REGIONS) || (crop->crop_mode & CROP_MARGINS) || (crop->crop_mode & CROP_LENGTH) || (crop->crop_mode & CROP_WIDTH))) { TIFFError("computeInputPixelOffsets", "Cannot compute margins or fixed size sections without image resolution"); TIFFError("computeInputPixelOffsets", "Specify units in pixels and try again"); return (-1); } xres = image->xres; yres = image->yres; } /* Translate user units to image units */ scale = 1.0; switch (crop->res_unit) { case RESUNIT_CENTIMETER: if (image->res_unit == RESUNIT_INCH) scale = 1.0/2.54; break; case RESUNIT_INCH: if (image->res_unit == RESUNIT_CENTIMETER) scale = 2.54; break; case RESUNIT_NONE: /* Dimensions in pixels */ default: break; } if (crop->crop_mode & CROP_REGIONS) { max_width = max_length = 0; for (i = 0; i < crop->regions; i++) { if ((crop->res_unit == RESUNIT_INCH) || (crop->res_unit == RESUNIT_CENTIMETER)) { x1 = (uint32) (crop->corners[i].X1 * scale * xres); x2 = (uint32) (crop->corners[i].X2 * scale * xres); y1 = (uint32) (crop->corners[i].Y1 * scale * yres); y2 = (uint32) (crop->corners[i].Y2 * scale * yres); } else { x1 = (uint32) (crop->corners[i].X1); x2 = (uint32) (crop->corners[i].X2); y1 = (uint32) (crop->corners[i].Y1); y2 = (uint32) (crop->corners[i].Y2); } if (x1 < 1) crop->regionlist[i].x1 = 0; else crop->regionlist[i].x1 = (uint32) (x1 - 1); if (x2 > image->width - 1) crop->regionlist[i].x2 = image->width - 1; else crop->regionlist[i].x2 = (uint32) (x2 - 1); zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1; if (y1 < 1) crop->regionlist[i].y1 = 0; else crop->regionlist[i].y1 = (uint32) (y1 - 1); if (y2 > image->length - 1) crop->regionlist[i].y2 = image->length - 1; else crop->regionlist[i].y2 = (uint32) (y2 - 1); zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1; if (zwidth > max_width) max_width = zwidth; if (zlength > max_length) max_length = zlength; buffsize = (uint32) (((zwidth * image->bps * image->spp + 7 ) / 8) * (zlength + 1)); /* buffsize = (uint32) (((zwidth * image->bps + 7 ) / 8) * image->spp * (zlength + 1)); */ crop->regionlist[i].buffsize = buffsize; crop->bufftotal += buffsize; if (crop->img_mode == COMPOSITE_IMAGES) { switch (crop->edge_ref) { case EDGE_LEFT: case EDGE_RIGHT: crop->combined_length = zlength; crop->combined_width += zwidth; break; case EDGE_BOTTOM: case EDGE_TOP: /* width from left, length from top */ default: crop->combined_width = zwidth; crop->combined_length += zlength; break; } } } return (0); } /* Convert crop margins into offsets into image * Margins are expressed as pixel rows and columns, not bytes */ if (crop->crop_mode & CROP_MARGINS) { if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER) { /* User has specified pixels as reference unit */ tmargin = (uint32)(crop->margins[0]); lmargin = (uint32)(crop->margins[1]); bmargin = (uint32)(crop->margins[2]); rmargin = (uint32)(crop->margins[3]); } else { /* inches or centimeters specified */ tmargin = (uint32)(crop->margins[0] * scale * yres); lmargin = (uint32)(crop->margins[1] * scale * xres); bmargin = (uint32)(crop->margins[2] * scale * yres); rmargin = (uint32)(crop->margins[3] * scale * xres); } if ((lmargin + rmargin) > image->width) { TIFFError("computeInputPixelOffsets", "Combined left and right margins exceed image width"); lmargin = (uint32) 0; rmargin = (uint32) 0; return (-1); } if ((tmargin + bmargin) > image->length) { TIFFError("computeInputPixelOffsets", "Combined top and bottom margins exceed image length"); tmargin = (uint32) 0; bmargin = (uint32) 0; return (-1); } } else { /* no margins requested */ tmargin = (uint32) 0; lmargin = (uint32) 0; bmargin = (uint32) 0; rmargin = (uint32) 0; } /* Width, height, and margins are expressed as pixel offsets into image */ if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER) { if (crop->crop_mode & CROP_WIDTH) width = (uint32)crop->width; else width = image->width - lmargin - rmargin; if (crop->crop_mode & CROP_LENGTH) length = (uint32)crop->length; else length = image->length - tmargin - bmargin; } else { if (crop->crop_mode & CROP_WIDTH) width = (uint32)(crop->width * scale * image->xres); else width = image->width - lmargin - rmargin; if (crop->crop_mode & CROP_LENGTH) length = (uint32)(crop->length * scale * image->yres); else length = image->length - tmargin - bmargin; } off->tmargin = tmargin; off->bmargin = bmargin; off->lmargin = lmargin; off->rmargin = rmargin; /* Calculate regions defined by margins, width, and length. * Coordinates expressed as 0 to imagewidth - 1, imagelength - 1, * since they are used to compute offsets into buffers */ switch (crop->edge_ref) { case EDGE_BOTTOM: startx = lmargin; if ((startx + width) >= (image->width - rmargin)) endx = image->width - rmargin - 1; else endx = startx + width - 1; endy = image->length - bmargin - 1; if ((endy - length) <= tmargin) starty = tmargin; else starty = endy - length + 1; break; case EDGE_RIGHT: endx = image->width - rmargin - 1; if ((endx - width) <= lmargin) startx = lmargin; else startx = endx - width + 1; starty = tmargin; if ((starty + length) >= (image->length - bmargin)) endy = image->length - bmargin - 1; else endy = starty + length - 1; break; case EDGE_TOP: /* width from left, length from top */ case EDGE_LEFT: default: startx = lmargin; if ((startx + width) >= (image->width - rmargin)) endx = image->width - rmargin - 1; else endx = startx + width - 1; starty = tmargin; if ((starty + length) >= (image->length - bmargin)) endy = image->length - bmargin - 1; else endy = starty + length - 1; break; } off->startx = startx; off->starty = starty; off->endx = endx; off->endy = endy; crop_width = endx - startx + 1; crop_length = endy - starty + 1; if (crop_width <= 0) { TIFFError("computeInputPixelOffsets", "Invalid left/right margins and /or image crop width requested"); return (-1); } if (crop_width > image->width) crop_width = image->width; if (crop_length <= 0) { TIFFError("computeInputPixelOffsets", "Invalid top/bottom margins and /or image crop length requested"); return (-1); } if (crop_length > image->length) crop_length = image->length; off->crop_width = crop_width; off->crop_length = crop_length; return (0); } /* end computeInputPixelOffsets */ /* * Translate crop options into pixel offsets for one or more regions of the image. * Options are applied in this order: margins, specific width and length, zones, * but all are optional. Margins are relative to each edge. Width, length and * zones are relative to the specified reference edge. Zones are expressed as * X:Y where X is the ordinal value in a set of Y equal sized portions. eg. * 2:3 would indicate the middle third of the region qualified by margins and * any explicit width and length specified. Regions are specified by coordinates * of the top left and lower right corners with range 1 to width or height. */ static int getCropOffsets(struct image_data *image, struct crop_mask *crop, struct dump_opts *dump) { struct offset offsets; int i; int32 test2; uint32 test, seg, total, need_buff = 0; uint32 buffsize; uint32 zwidth, zlength; memset(&offsets, '\0', sizeof(struct offset)); crop->bufftotal = 0; crop->combined_width = (uint32)0; crop->combined_length = (uint32)0; crop->selections = 0; /* Compute pixel offsets if margins or fixed width or length specified */ if ((crop->crop_mode & CROP_MARGINS) || (crop->crop_mode & CROP_REGIONS) || (crop->crop_mode & CROP_LENGTH) || (crop->crop_mode & CROP_WIDTH)) { if (computeInputPixelOffsets(crop, image, &offsets)) { TIFFError ("getCropOffsets", "Unable to compute crop margins"); return (-1); } need_buff = TRUE; crop->selections = crop->regions; /* Regions are only calculated from top and left edges with no margins */ if (crop->crop_mode & CROP_REGIONS) return (0); } else { /* cropped area is the full image */ offsets.tmargin = 0; offsets.lmargin = 0; offsets.bmargin = 0; offsets.rmargin = 0; offsets.crop_width = image->width; offsets.crop_length = image->length; offsets.startx = 0; offsets.endx = image->width - 1; offsets.starty = 0; offsets.endy = image->length - 1; need_buff = FALSE; } if (dump->outfile != NULL) { dump_info (dump->outfile, dump->format, "", "Margins: Top: %d Left: %d Bottom: %d Right: %d", offsets.tmargin, offsets.lmargin, offsets.bmargin, offsets.rmargin); dump_info (dump->outfile, dump->format, "", "Crop region within margins: Adjusted Width: %6d Length: %6d", offsets.crop_width, offsets.crop_length); } if (!(crop->crop_mode & CROP_ZONES)) /* no crop zones requested */ { if (need_buff == FALSE) /* No margins or fixed width or length areas */ { crop->selections = 0; crop->combined_width = image->width; crop->combined_length = image->length; return (0); } else { /* Use one region for margins and fixed width or length areas * even though it was not formally declared as a region. */ crop->selections = 1; crop->zones = 1; crop->zonelist[0].total = 1; crop->zonelist[0].position = 1; } } else crop->selections = crop->zones; for (i = 0; i < crop->zones; i++) { seg = crop->zonelist[i].position; total = crop->zonelist[i].total; switch (crop->edge_ref) { case EDGE_LEFT: /* zones from left to right, length from top */ zlength = offsets.crop_length; crop->regionlist[i].y1 = offsets.starty; crop->regionlist[i].y2 = offsets.endy; crop->regionlist[i].x1 = offsets.startx + (uint32)(offsets.crop_width * 1.0 * (seg - 1) / total); test = offsets.startx + (uint32)(offsets.crop_width * 1.0 * seg / total); if (test > image->width - 1) crop->regionlist[i].x2 = image->width - 1; else crop->regionlist[i].x2 = test - 1; zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ crop->combined_length = (uint32)zlength; if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_width += (uint32)zwidth; else crop->combined_width = (uint32)zwidth; break; case EDGE_BOTTOM: /* width from left, zones from bottom to top */ zwidth = offsets.crop_width; crop->regionlist[i].x1 = offsets.startx; crop->regionlist[i].x2 = offsets.endx; test2 = offsets.endy - (uint32)(offsets.crop_length * 1.0 * seg / total); if (test2 < 1 ) crop->regionlist[i].y1 = 0; else crop->regionlist[i].y1 = test2 + 1; test = offsets.endy - (uint32)(offsets.crop_length * 1.0 * (seg - 1) / total); if (test > (image->length - 1)) crop->regionlist[i].y2 = image->length - 1; else crop->regionlist[i].y2 = test; zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_length += (uint32)zlength; else crop->combined_length = (uint32)zlength; crop->combined_width = (uint32)zwidth; break; case EDGE_RIGHT: /* zones from right to left, length from top */ zlength = offsets.crop_length; crop->regionlist[i].y1 = offsets.starty; crop->regionlist[i].y2 = offsets.endy; crop->regionlist[i].x1 = offsets.startx + (uint32)(offsets.crop_width * (total - seg) * 1.0 / total); test = offsets.startx + (uint32)(offsets.crop_width * (total - seg + 1) * 1.0 / total); if (test > image->width - 1) crop->regionlist[i].x2 = image->width - 1; else crop->regionlist[i].x2 = test - 1; zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ crop->combined_length = (uint32)zlength; if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_width += (uint32)zwidth; else crop->combined_width = (uint32)zwidth; break; case EDGE_TOP: /* width from left, zones from top to bottom */ default: zwidth = offsets.crop_width; crop->regionlist[i].x1 = offsets.startx; crop->regionlist[i].x2 = offsets.endx; crop->regionlist[i].y1 = offsets.starty + (uint32)(offsets.crop_length * 1.0 * (seg - 1) / total); test = offsets.starty + (uint32)(offsets.crop_length * 1.0 * seg / total); if (test > image->length - 1) crop->regionlist[i].y2 = image->length - 1; else crop->regionlist[i].y2 = test - 1; zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_length += (uint32)zlength; else crop->combined_length = (uint32)zlength; crop->combined_width = (uint32)zwidth; break; } /* end switch statement */ buffsize = (uint32) ((((zwidth * image->bps * image->spp) + 7 ) / 8) * (zlength + 1)); crop->regionlist[i].width = (uint32) zwidth; crop->regionlist[i].length = (uint32) zlength; crop->regionlist[i].buffsize = buffsize; crop->bufftotal += buffsize; if (dump->outfile != NULL) dump_info (dump->outfile, dump->format, "", "Zone %d, width: %4d, length: %4d, x1: %4d x2: %4d y1: %4d y2: %4d", i + 1, (uint32)zwidth, (uint32)zlength, crop->regionlist[i].x1, crop->regionlist[i].x2, crop->regionlist[i].y1, crop->regionlist[i].y2); } return (0); } /* end getCropOffsets */ static int computeOutputPixelOffsets (struct crop_mask *crop, struct image_data *image, struct pagedef *page, struct pageseg *sections, struct dump_opts* dump) { double scale; uint32 iwidth, ilength; /* Input image width and length */ uint32 owidth, olength; /* Output image width and length */ uint32 pwidth, plength; /* Output page width and length */ uint32 orows, ocols; /* rows and cols for output */ uint32 hmargin, vmargin; /* Horizontal and vertical margins */ uint32 x1, x2, y1, y2, line_bytes; unsigned int orientation; uint32 i, j, k; scale = 1.0; if (page->res_unit == RESUNIT_NONE) page->res_unit = image->res_unit; switch (image->res_unit) { case RESUNIT_CENTIMETER: if (page->res_unit == RESUNIT_INCH) scale = 1.0/2.54; break; case RESUNIT_INCH: if (page->res_unit == RESUNIT_CENTIMETER) scale = 2.54; break; case RESUNIT_NONE: /* Dimensions in pixels */ default: break; } /* get width, height, resolutions of input image selection */ if (crop->combined_width > 0) iwidth = crop->combined_width; else iwidth = image->width; if (crop->combined_length > 0) ilength = crop->combined_length; else ilength = image->length; if (page->hres <= 1.0) page->hres = image->xres; if (page->vres <= 1.0) page->vres = image->yres; if ((page->hres < 1.0) || (page->vres < 1.0)) { TIFFError("computeOutputPixelOffsets", "Invalid horizontal or vertical resolution specified or read from input image"); return (1); } /* If no page sizes are being specified, we just use the input image size to * calculate maximum margins that can be taken from image. */ if (page->width <= 0) pwidth = iwidth; else pwidth = page->width; if (page->length <= 0) plength = ilength; else plength = page->length; if (dump->debug) { TIFFError("", "Page size: %s, Vres: %3.2f, Hres: %3.2f, " "Hmargin: %3.2f, Vmargin: %3.2f\n", page->name, page->vres, page->hres, page->hmargin, page->vmargin); TIFFError("", "Res_unit: %d, Scale: %3.2f, Page width: %d, length: %d\n", page->res_unit, scale, pwidth, plength); } /* compute margins at specified unit and resolution */ if (page->mode & PAGE_MODE_MARGINS) { if (page->res_unit == RESUNIT_INCH || page->res_unit == RESUNIT_CENTIMETER) { /* inches or centimeters specified */ hmargin = (uint32)(page->hmargin * scale * page->hres * ((image->bps + 7)/ 8)); vmargin = (uint32)(page->vmargin * scale * page->vres * ((image->bps + 7)/ 8)); } else { /* Otherwise user has specified pixels as reference unit */ hmargin = (uint32)(page->hmargin * scale * ((image->bps + 7)/ 8)); vmargin = (uint32)(page->vmargin * scale * ((image->bps + 7)/ 8)); } if ((hmargin * 2.0) > (pwidth * page->hres)) { TIFFError("computeOutputPixelOffsets", "Combined left and right margins exceed page width"); hmargin = (uint32) 0; return (-1); } if ((vmargin * 2.0) > (plength * page->vres)) { TIFFError("computeOutputPixelOffsets", "Combined top and bottom margins exceed page length"); vmargin = (uint32) 0; return (-1); } } else { hmargin = 0; vmargin = 0; } if (page->mode & PAGE_MODE_ROWSCOLS ) { /* Maybe someday but not for now */ if (page->mode & PAGE_MODE_MARGINS) TIFFError("computeOutputPixelOffsets", "Output margins cannot be specified with rows and columns"); owidth = TIFFhowmany(iwidth, page->cols); olength = TIFFhowmany(ilength, page->rows); } else { if (page->mode & PAGE_MODE_PAPERSIZE ) { owidth = (uint32)((pwidth * page->hres) - (hmargin * 2)); olength = (uint32)((plength * page->vres) - (vmargin * 2)); } else { owidth = (uint32)(iwidth - (hmargin * 2 * page->hres)); olength = (uint32)(ilength - (vmargin * 2 * page->vres)); } } if (owidth > iwidth) owidth = iwidth; if (olength > ilength) olength = ilength; /* Compute the number of pages required for Portrait or Landscape */ switch (page->orient) { case ORIENTATION_NONE: case ORIENTATION_PORTRAIT: ocols = TIFFhowmany(iwidth, owidth); orows = TIFFhowmany(ilength, olength); orientation = ORIENTATION_PORTRAIT; break; case ORIENTATION_LANDSCAPE: ocols = TIFFhowmany(iwidth, olength); orows = TIFFhowmany(ilength, owidth); x1 = olength; olength = owidth; owidth = x1; orientation = ORIENTATION_LANDSCAPE; break; case ORIENTATION_AUTO: default: x1 = TIFFhowmany(iwidth, owidth); x2 = TIFFhowmany(ilength, olength); y1 = TIFFhowmany(iwidth, olength); y2 = TIFFhowmany(ilength, owidth); if ( (x1 * x2) < (y1 * y2)) { /* Portrait */ ocols = x1; orows = x2; orientation = ORIENTATION_PORTRAIT; } else { /* Landscape */ ocols = y1; orows = y2; x1 = olength; olength = owidth; owidth = x1; orientation = ORIENTATION_LANDSCAPE; } } if (ocols < 1) ocols = 1; if (orows < 1) orows = 1; /* If user did not specify rows and cols, set them from calcuation */ if (page->rows < 1) page->rows = orows; if (page->cols < 1) page->cols = ocols; line_bytes = TIFFhowmany8(owidth * image->bps) * image->spp; if ((page->rows * page->cols) > MAX_SECTIONS) { TIFFError("computeOutputPixelOffsets", "Rows and Columns exceed maximum sections\nIncrease resolution or reduce sections"); return (-1); } /* build the list of offsets for each output section */ for (k = 0, i = 0 && k <= MAX_SECTIONS; i < orows; i++) { y1 = (uint32)(olength * i); y2 = (uint32)(olength * (i + 1) - 1); if (y2 >= ilength) y2 = ilength - 1; for (j = 0; j < ocols; j++, k++) { x1 = (uint32)(owidth * j); x2 = (uint32)(owidth * (j + 1) - 1); if (x2 >= iwidth) x2 = iwidth - 1; sections[k].x1 = x1; sections[k].x2 = x2; sections[k].y1 = y1; sections[k].y2 = y2; sections[k].buffsize = line_bytes * olength; sections[k].position = k + 1; sections[k].total = orows * ocols; } } return (0); } /* end computeOutputPixelOffsets */ static int loadImage(TIFF* in, struct image_data *image, struct dump_opts * dump, unsigned char **read_ptr) { uint32 i; float xres=0.0, yres=0.0; uint16 nstrips, ntiles, planar, bps, spp, res_unit, photometric, orientation; uint32 width, length, rowsperstrip; uint32 stsize, tlsize, buffsize, scanlinesize; unsigned char *read_buff = NULL; unsigned char *new_buff = NULL; int readunit = 0; static uint32 prev_readsize = 0; TIFFGetFieldDefaulted(in, TIFFTAG_BITSPERSAMPLE, &bps); TIFFGetFieldDefaulted(in, TIFFTAG_SAMPLESPERPIXEL, &spp); TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar); TIFFGetFieldDefaulted(in, TIFFTAG_ORIENTATION, &orientation); TIFFGetField(in, TIFFTAG_PHOTOMETRIC, &photometric); TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width); TIFFGetField(in, TIFFTAG_IMAGELENGTH, &length); TIFFGetField(in, TIFFTAG_XRESOLUTION, &xres); TIFFGetField(in, TIFFTAG_YRESOLUTION, &yres); TIFFGetField(in, TIFFTAG_RESOLUTIONUNIT, &res_unit); scanlinesize = TIFFScanlineSize(in); image->bps = bps; image->spp = spp; image->planar = planar; image->width = width; image->length = length; image->xres = xres; image->yres = yres; image->res_unit = res_unit; image->photometric = photometric; image->orientation = orientation; switch (orientation) { case 0: case ORIENTATION_TOPLEFT: image->adjustments = 0; break; case ORIENTATION_TOPRIGHT: image->adjustments = MIRROR_HORIZ; break; case ORIENTATION_BOTRIGHT: image->adjustments = ROTATECW_180; break; case ORIENTATION_BOTLEFT: image->adjustments = MIRROR_VERT; break; case ORIENTATION_LEFTTOP: image->adjustments = MIRROR_VERT | ROTATECW_90; break; case ORIENTATION_RIGHTTOP: image->adjustments = ROTATECW_90; break; case ORIENTATION_RIGHTBOT: image->adjustments = MIRROR_VERT | ROTATECW_270; break; case ORIENTATION_LEFTBOT: image->adjustments = ROTATECW_270; break; default: image->adjustments = 0; image->orientation = ORIENTATION_TOPLEFT; } if ((bps == 0) || (spp == 0)) { TIFFError("loadImage", "Invalid samples per pixel (%d) or bits per sample (%d)", spp, bps); return (-1); } if (TIFFIsTiled(in)) { readunit = TILE; tlsize = TIFFTileSize(in); ntiles = TIFFNumberOfTiles(in); buffsize = tlsize * ntiles; if (dump->infile != NULL) dump_info (dump->infile, dump->format, "", "Tilesize: %u, Number of Tiles: %u, Scanline size: %u", tlsize, ntiles, scanlinesize); } else { readunit = STRIP; TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); stsize = TIFFStripSize(in); nstrips = TIFFNumberOfStrips(in); buffsize = stsize * nstrips; if (dump->infile != NULL) dump_info (dump->infile, dump->format, "", "Stripsize: %u, Number of Strips: %u, Rows per Strip: %u, Scanline size: %u", stsize, nstrips, rowsperstrip, scanlinesize); } read_buff = *read_ptr; if (!read_buff) read_buff = (unsigned char *)_TIFFmalloc(buffsize); else { if (prev_readsize < buffsize) { new_buff = _TIFFrealloc(read_buff, buffsize); if (!new_buff) { free (read_buff); read_buff = (unsigned char *)_TIFFmalloc(buffsize); } else read_buff = new_buff; } } if (!read_buff) { TIFFError("loadImage", "Unable to allocate/reallocate read buffer"); return (-1); } _TIFFmemset(read_buff, '\0', buffsize); prev_readsize = buffsize; *read_ptr = read_buff; /* N.B. The read functions used copy separate plane data into a buffer as interleaved * samples rather than separate planes so the same logic works to extract regions * regardless of the way the data are organized in the input file. */ switch (readunit) { case STRIP: if (planar == PLANARCONFIG_CONTIG) { if (!(readContigStripsIntoBuffer(in, read_buff, length, width, spp))) { TIFFError("loadImage", "Unable to read contiguous strips into buffer"); return (-1); } } else { if (!(readSeparateStripsIntoBuffer(in, read_buff, length, width, spp, dump))) { TIFFError("loadImage", "Unable to read separate strips into buffer"); return (-1); } } break; case TILE: if (planar == PLANARCONFIG_CONTIG) { if (!(readContigTilesIntoBuffer(in, read_buff, length, width, spp))) { TIFFError("loadImage", "Unable to read contiguous tiles into buffer"); return (-1); } } else { if (!(readSeparateTilesIntoBuffer(in, read_buff, length, width, spp))) { TIFFError("loadImage", "Unable to read separate tiles into buffer"); return (-1); } } break; default: TIFFError("loadImage", "Unsupported image file format"); return (-1); break; } if ((dump->infile != NULL) && (dump->level == 2)) { dump_info (dump->infile, dump->format, "loadImage", "Image width %d, length %d, Raw image data, %4d bytes", width, length, buffsize); dump_info (dump->infile, dump->format, "", "Bits per sample %d, Samples per pixel %d", bps, spp); for (i = 0; i < length; i++) dump_buffer(dump->infile, dump->format, 1, scanlinesize, i, read_buff + (i * scanlinesize)); } return (0); } /* end loadImage */ static int correct_orientation(struct image_data *image, unsigned char **work_buff_ptr) { uint16 mirror, rotation; unsigned char *work_buff; work_buff = *work_buff_ptr; if ((image == NULL) || (work_buff == NULL)) { TIFFError ("correct_orientatin", "Invalid image or buffer pointer"); return (-1); } if ((image->adjustments & MIRROR_HORIZ) || (image->adjustments & MIRROR_VERT)) { mirror = (uint16)(image->adjustments & MIRROR_BOTH); if (mirrorImage(image->spp, image->bps, mirror, image->width, image->length, work_buff)) { TIFFError ("correct_orientation", "Unable to mirror image"); return (-1); } } if (image->adjustments & ROTATE_ANY) { if (image->adjustments & ROTATECW_90) rotation = (uint16) 90; else if (image->adjustments & ROTATECW_180) rotation = (uint16) 180; else if (image->adjustments & ROTATECW_270) rotation = (uint16) 270; else { TIFFError ("correct_orientation", "Invalid rotation value: %d", image->adjustments & ROTATE_ANY); return (-1); } if (rotateImage(rotation, image, &image->width, &image->length, work_buff_ptr)) { TIFFError ("correct_orientation", "Unable to rotate image"); return (-1); } image->orientation = ORIENTATION_TOPLEFT; } return (0); } /* end correct_orientation */ /* Extract multiple zones from an image and combine into a single composite image */ static int extractCompositeRegions(struct image_data *image, struct crop_mask *crop, unsigned char *read_buff, unsigned char *crop_buff) { int shift_width, bytes_per_sample, bytes_per_pixel; uint32 i, trailing_bits, prev_trailing_bits; uint32 row, first_row, last_row, first_col, last_col; uint32 src_rowsize, dst_rowsize, src_offset, dst_offset; uint32 crop_width, crop_length, img_width, img_length; uint32 prev_length, prev_width, composite_width; uint16 bps, spp; uint8 *src, *dst; tsample_t count, sample = 0; /* Update to extract one or more samples */ img_width = image->width; img_length = image->length; bps = image->bps; spp = image->spp; count = spp; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } src = read_buff; dst = crop_buff; /* These are setup for adding additional sections */ prev_width = prev_length = 0; prev_trailing_bits = trailing_bits = 0; composite_width = crop->combined_width; crop->combined_width = 0; crop->combined_length = 0; for (i = 0; i < crop->selections; i++) { /* rows, columns, width, length are expressed in pixels */ first_row = crop->regionlist[i].y1; last_row = crop->regionlist[i].y2; first_col = crop->regionlist[i].x1; last_col = crop->regionlist[i].x2; crop_width = last_col - first_col + 1; crop_length = last_row - first_row + 1; /* These should not be needed for composite images */ crop->regionlist[i].width = crop_width; crop->regionlist[i].length = crop_length; crop->regionlist[i].buffptr = crop_buff; src_rowsize = ((img_width * bps * spp) + 7) / 8; dst_rowsize = (((crop_width * bps * count) + 7) / 8); switch (crop->edge_ref) { default: case EDGE_TOP: case EDGE_BOTTOM: if ((i > 0) && (crop_width != crop->regionlist[i - 1].width)) { TIFFError ("extractCompositeRegions", "Only equal width regions can be combined for -E top or bottom"); return (1); } crop->combined_width = crop_width; crop->combined_length += crop_length; for (row = first_row; row <= last_row; row++) { src_offset = row * src_rowsize; dst_offset = (row - first_row) * dst_rowsize; src = read_buff + src_offset; dst = crop_buff + dst_offset + (prev_length * dst_rowsize); switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 1: if (extractContigSamplesShifted8bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 2: if (extractContigSamplesShifted16bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 3: if (extractContigSamplesShifted24bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; default: TIFFError("extractCompositeRegions", "Unsupported bit depth %d", bps); return (1); } } prev_length += crop_length; break; case EDGE_LEFT: /* splice the pieces of each row together, side by side */ case EDGE_RIGHT: if ((i > 0) && (crop_length != crop->regionlist[i - 1].length)) { TIFFError ("extractCompositeRegions", "Only equal length regions can be combined for -E left or right"); return (1); } crop->combined_width += crop_width; crop->combined_length = crop_length; dst_rowsize = (((composite_width * bps * count) + 7) / 8); trailing_bits = (crop_width * bps * count) % 8; for (row = first_row; row <= last_row; row++) { src_offset = row * src_rowsize; dst_offset = (row - first_row) * dst_rowsize; src = read_buff + src_offset; dst = crop_buff + dst_offset + prev_width; switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 1: if (extractContigSamplesShifted8bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 2: if (extractContigSamplesShifted16bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 3: if (extractContigSamplesShifted24bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; default: TIFFError("extractCompositeRegions", "Unsupported bit depth %d", bps); return (1); } } prev_width += (crop_width * bps * count) / 8; prev_trailing_bits += trailing_bits; if (prev_trailing_bits > 7) prev_trailing_bits-= 8; break; } } if (crop->combined_width != composite_width) TIFFError("combineSeparateRegions","Combined width does not match composite width"); return (0); } /* end extractCompositeRegions */ /* Copy a single region of input buffer to an output buffer. * The read functions used copy separate plane data into a buffer * as interleaved samples rather than separate planes so the same * logic works to extract regions regardless of the way the data * are organized in the input file. This function can be used to * extract one or more samples from the input image by updating the * parameters for starting sample and number of samples to copy in the * fifth and eighth arguments of the call to extractContigSamples. * They would be passed as new elements of the crop_mask struct. */ static int extractSeparateRegion(struct image_data *image, struct crop_mask *crop, unsigned char *read_buff, unsigned char *crop_buff, int region) { int shift_width, prev_trailing_bits = 0; uint32 bytes_per_sample, bytes_per_pixel; uint32 src_rowsize, dst_rowsize; uint32 row, first_row, last_row, first_col, last_col; uint32 src_offset, dst_offset; uint32 crop_width, crop_length, img_width, img_length; uint16 bps, spp; uint8 *src, *dst; tsample_t count, sample = 0; /* Update to extract more or more samples */ img_width = image->width; img_length = image->length; bps = image->bps; spp = image->spp; count = spp; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; /* Byte aligned data only */ else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } /* rows, columns, width, length are expressed in pixels */ first_row = crop->regionlist[region].y1; last_row = crop->regionlist[region].y2; first_col = crop->regionlist[region].x1; last_col = crop->regionlist[region].x2; crop_width = last_col - first_col + 1; crop_length = last_row - first_row + 1; crop->regionlist[region].width = crop_width; crop->regionlist[region].length = crop_length; crop->regionlist[region].buffptr = crop_buff; src = read_buff; dst = crop_buff; src_rowsize = ((img_width * bps * spp) + 7) / 8; dst_rowsize = (((crop_width * bps * spp) + 7) / 8); for (row = first_row; row <= last_row; row++) { src_offset = row * src_rowsize; dst_offset = (row - first_row) * dst_rowsize; src = read_buff + src_offset; dst = crop_buff + dst_offset; switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; case 1: if (extractContigSamplesShifted8bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; case 2: if (extractContigSamplesShifted16bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; case 3: if (extractContigSamplesShifted24bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; default: TIFFError("extractSeparateRegion", "Unsupported bit depth %d", bps); return (1); } } return (0); } /* end extractSeparateRegion */ static int extractImageSection(struct image_data *image, struct pageseg *section, unsigned char *src_buff, unsigned char *sect_buff) { unsigned char bytebuff1, bytebuff2; unsigned char *src, *dst; uint32 img_width, img_length, img_rowsize; uint32 j, shift1, shift2, trailing_bits; uint32 row, first_row, last_row, first_col, last_col; uint32 src_offset, dst_offset, row_offset, col_offset; uint32 offset1, offset2, full_bytes; uint32 sect_width, sect_length; uint16 bps, spp; #ifdef DEBUG2 int k; unsigned char bitset; static char *bitarray = NULL; #endif img_width = image->width; img_length = image->length; bps = image->bps; spp = image->spp; src = src_buff; dst = sect_buff; src_offset = 0; dst_offset = 0; #ifdef DEBUG2 if (bitarray == NULL) { if ((bitarray = (char *)malloc(img_width)) == NULL) { TIFFError ("", "DEBUG: Unable to allocate debugging bitarray\n"); return (-1); } } #endif /* rows, columns, width, length are expressed in pixels */ first_row = section->y1; last_row = section->y2; first_col = section->x1; last_col = section->x2; sect_width = last_col - first_col + 1; sect_length = last_row - first_row + 1; img_rowsize = ((img_width * bps + 7) / 8) * spp; full_bytes = (sect_width * spp * bps) / 8; /* number of COMPLETE bytes per row in section */ trailing_bits = (sect_width * bps) % 8; #ifdef DEBUG2 TIFFError ("", "First row: %d, last row: %d, First col: %d, last col: %d\n", first_row, last_row, first_col, last_col); TIFFError ("", "Image width: %d, Image length: %d, bps: %d, spp: %d\n", img_width, img_length, bps, spp); TIFFError ("", "Sect width: %d, Sect length: %d, full bytes: %d trailing bits %d\n", sect_width, sect_length, full_bytes, trailing_bits); #endif if ((bps % 8) == 0) { col_offset = first_col * spp * bps / 8; for (row = first_row; row <= last_row; row++) { /* row_offset = row * img_width * spp * bps / 8; */ row_offset = row * img_rowsize; src_offset = row_offset + col_offset; #ifdef DEBUG2 TIFFError ("", "Src offset: %8d, Dst offset: %8d\n", src_offset, dst_offset); #endif _TIFFmemcpy (sect_buff + dst_offset, src_buff + src_offset, full_bytes); dst_offset += full_bytes; } } else { /* bps != 8 */ shift1 = spp * ((first_col * bps) % 8); shift2 = spp * ((last_col * bps) % 8); for (row = first_row; row <= last_row; row++) { /* pull out the first byte */ row_offset = row * img_rowsize; offset1 = row_offset + (first_col * bps / 8); offset2 = row_offset + (last_col * bps / 8); #ifdef DEBUG2 for (j = 0, k = 7; j < 8; j++, k--) { bitset = *(src_buff + offset1) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } sprintf(&bitarray[8], " "); sprintf(&bitarray[9], " "); for (j = 10, k = 7; j < 18; j++, k--) { bitset = *(src_buff + offset2) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[18] = '\0'; TIFFError ("", "Row: %3d Offset1: %d, Shift1: %d, Offset2: %d, Shift2: %d\n", row, offset1, shift1, offset2, shift2); #endif bytebuff1 = bytebuff2 = 0; if (shift1 == 0) /* the region is byte and sample alligned */ { _TIFFmemcpy (sect_buff + dst_offset, src_buff + offset1, full_bytes); #ifdef DEBUG2 TIFFError ("", " Alligned data src offset1: %8d, Dst offset: %8d\n", offset1, dst_offset); sprintf(&bitarray[18], "\n"); sprintf(&bitarray[19], "\t"); for (j = 20, k = 7; j < 28; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[28] = ' '; bitarray[29] = ' '; #endif dst_offset += full_bytes; if (trailing_bits != 0) { bytebuff2 = src_buff[offset2] & ((unsigned char)255 << (7 - shift2)); sect_buff[dst_offset] = bytebuff2; #ifdef DEBUG2 TIFFError ("", " Trailing bits src offset: %8d, Dst offset: %8d\n", offset2, dst_offset); for (j = 30, k = 7; j < 38; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[38] = '\0'; TIFFError ("", "\tFirst and last bytes before and after masking:\n\t%s\n\n", bitarray); #endif dst_offset++; } } else /* each destination byte will have to be built from two source bytes*/ { #ifdef DEBUG2 TIFFError ("", " Unalligned data src offset: %8d, Dst offset: %8d\n", offset1 , dst_offset); #endif for (j = 0; j <= full_bytes; j++) { bytebuff1 = src_buff[offset1 + j] & ((unsigned char)255 >> shift1); bytebuff2 = src_buff[offset1 + j + 1] & ((unsigned char)255 << (7 - shift1)); sect_buff[dst_offset + j] = (bytebuff1 << shift1) | (bytebuff2 >> (8 - shift1)); } #ifdef DEBUG2 sprintf(&bitarray[18], "\n"); sprintf(&bitarray[19], "\t"); for (j = 20, k = 7; j < 28; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[28] = ' '; bitarray[29] = ' '; #endif dst_offset += full_bytes; if (trailing_bits != 0) { #ifdef DEBUG2 TIFFError ("", " Trailing bits src offset: %8d, Dst offset: %8d\n", offset1 + full_bytes, dst_offset); #endif if (shift2 > shift1) { bytebuff1 = src_buff[offset1 + full_bytes] & ((unsigned char)255 << (7 - shift2)); bytebuff2 = bytebuff1 & ((unsigned char)255 << shift1); sect_buff[dst_offset] = bytebuff2; #ifdef DEBUG2 TIFFError ("", " Shift2 > Shift1\n"); #endif } else { if (shift2 < shift1) { bytebuff2 = ((unsigned char)255 << (shift1 - shift2 - 1)); sect_buff[dst_offset] &= bytebuff2; #ifdef DEBUG2 TIFFError ("", " Shift2 < Shift1\n"); #endif } #ifdef DEBUG2 else TIFFError ("", " Shift2 == Shift1\n"); #endif } } #ifdef DEBUG2 sprintf(&bitarray[28], " "); sprintf(&bitarray[29], " "); for (j = 30, k = 7; j < 38; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[38] = '\0'; TIFFError ("", "\tFirst and last bytes before and after masking:\n\t%s\n\n", bitarray); #endif dst_offset++; } } } return (0); } /* end extractImageSection */ static int writeSelections(TIFF *in, TIFF **out, struct crop_mask *crop, struct image_data *image, struct dump_opts *dump, struct buffinfo seg_buffs[], char *mp, char *filename, unsigned int *page, unsigned int total_pages) { int i, page_count; int autoindex = 0; unsigned char *crop_buff = NULL; /* Where we open a new file depends on the export mode */ switch (crop->exp_mode) { case ONE_FILE_COMPOSITE: /* Regions combined into single image */ autoindex = 0; crop_buff = seg_buffs[0].buffer; if (update_output_file (out, mp, autoindex, filename, page)) return (1); page_count = total_pages; if (writeCroppedImage(in, *out, image, dump, crop->combined_width, crop->combined_length, crop_buff, *page, total_pages)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } break; case ONE_FILE_SEPARATED: /* Regions as separated images */ autoindex = 0; if (update_output_file (out, mp, autoindex, filename, page)) return (1); page_count = crop->selections * total_pages; for (i = 0; i < crop->selections; i++) { crop_buff = seg_buffs[i].buffer; if (writeCroppedImage(in, *out, image, dump, crop->regionlist[i].width, crop->regionlist[i].length, crop_buff, *page, page_count)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } } break; case FILE_PER_IMAGE_COMPOSITE: /* Regions as composite image */ autoindex = 1; if (update_output_file (out, mp, autoindex, filename, page)) return (1); crop_buff = seg_buffs[0].buffer; if (writeCroppedImage(in, *out, image, dump, crop->combined_width, crop->combined_length, crop_buff, *page, total_pages)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } break; case FILE_PER_IMAGE_SEPARATED: /* Regions as separated images */ autoindex = 1; page_count = crop->selections; if (update_output_file (out, mp, autoindex, filename, page)) return (1); for (i = 0; i < crop->selections; i++) { crop_buff = seg_buffs[i].buffer; /* Write the current region to the current file */ if (writeCroppedImage(in, *out, image, dump, crop->regionlist[i].width, crop->regionlist[i].length, crop_buff, *page, page_count)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } } break; case FILE_PER_SELECTION: autoindex = 1; page_count = 1; for (i = 0; i < crop->selections; i++) { if (update_output_file (out, mp, autoindex, filename, page)) return (1); crop_buff = seg_buffs[i].buffer; /* Write the current region to the current file */ if (writeCroppedImage(in, *out, image, dump, crop->regionlist[i].width, crop->regionlist[i].length, crop_buff, *page, page_count)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } } break; default: return (1); } return (0); } /* end writeRegions */ static int writeImageSections(TIFF *in, TIFF *out, struct image_data *image, struct pagedef *page, struct pageseg *sections, struct dump_opts * dump, unsigned char *src_buff, unsigned char **sect_buff_ptr) { double hres, vres; uint32 i, k, width, length, sectsize; unsigned char *sect_buff = *sect_buff_ptr; hres = page->hres; vres = page->vres; #ifdef DEBUG TIFFError("", "Writing %d sections for each original page. Hres: %3.2f Vres: %3.2f\n", page->rows * page->cols, hres, vres); #endif k = page->cols * page->rows; if ((k < 1) || (k > MAX_SECTIONS)) { TIFFError("writeImageSections", "%d Rows and Columns exceed maximum sections\nIncrease resolution or reduce sections", k); return (-1); } for (i = 0; i < k; i++) { width = sections[i].x2 - sections[i].x1 + 1; length = sections[i].y2 - sections[i].y1 + 1; sectsize = (uint32) ceil((width * image->bps + 7) / (double)8) * image->spp * length; /* allocate a buffer if we don't have one already */ if (createImageSection(sectsize, sect_buff_ptr)) { TIFFError("writeImageSections", "Unable to allocate section buffer"); exit (-1); } sect_buff = *sect_buff_ptr; #ifdef DEBUG TIFFError ("", "\nSection: %d, Width: %4d, Length: %4d, x1: %4d x2: %4d y1: %4d y2: %4d\n", i + 1, width, length, sections[i].x1, sections[i].x2, sections[i].y1, sections[i].y2); #endif if (extractImageSection (image, &sections[i], src_buff, sect_buff)) { TIFFError("writeImageSections", "Unable to extract image sections"); exit (-1); } /* call the write routine here instead of outside the loop */ if (writeSingleSection(in, out, image, dump, width, length, hres, vres, sect_buff)) { TIFFError("writeImageSections", "Unable to write image section"); exit (-1); } } return (0); } /* end writeImageSections */ /* Code in this function is heavily indebted to code in tiffcp * with modifications by Richard Nolde to handle orientation correctly. */ static int writeSingleSection(TIFF *in, TIFF *out, struct image_data *image, struct dump_opts *dump, uint32 width, uint32 length, double hres, double vres, unsigned char *sect_buff) { uint16 bps, spp; struct cpTag* p; #ifdef DEBUG TIFFError ("", "\nWriting single section: Width %d Length: %d Hres: %4.1f, Vres: %4.1f\n\n", width, length, hres, vres); #endif TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width); TIFFSetField(out, TIFFTAG_IMAGELENGTH, length); CopyField(TIFFTAG_BITSPERSAMPLE, bps); CopyField(TIFFTAG_SAMPLESPERPIXEL, spp); if (compression != (uint16)-1) TIFFSetField(out, TIFFTAG_COMPRESSION, compression); else CopyField(TIFFTAG_COMPRESSION, compression); if (compression == COMPRESSION_JPEG) { uint16 input_compression, input_photometric; if (TIFFGetField(in, TIFFTAG_COMPRESSION, &input_compression) && input_compression == COMPRESSION_JPEG) { TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } if (TIFFGetField(in, TIFFTAG_PHOTOMETRIC, &input_photometric)) { if(input_photometric == PHOTOMETRIC_RGB) { if (jpegcolormode == JPEGCOLORMODE_RGB) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB); } else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric); } } else { if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric); } if (fillorder != 0) TIFFSetField(out, TIFFTAG_FILLORDER, fillorder); else CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT); /* The loadimage function reads input orientation and sets * image->orientation. The correct_image_orientation function * applies the required rotation and mirror operations to * present the data in TOPLEFT orientation and updates * image->orientation if any transforms are performed, * as per EXIF standard. Original tiffcp code removed here. */ TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation); /* * Choose tiles/strip for the output image according to * the command line arguments (-tiles, -strips) and the * structure of the input image. */ if (outtiled == -1) outtiled = TIFFIsTiled(in); if (outtiled) { /* * Setup output file's tile width&height. If either * is not specified, use either the value from the * input image or, if nothing is defined, use the * library default. */ if (tilewidth == (uint32) -1) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth); if (tilelength == (uint32) -1) TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength); if (tilewidth > width) tilewidth = width; if (tilelength > length) tilelength = length; TIFFDefaultTileSize(out, &tilewidth, &tilelength); TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth); TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength); } else { /* * RowsPerStrip is left unspecified: use either the * value from the input image or, if nothing is defined, * use the library default. */ if (rowsperstrip == (uint32) 0) { if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip)) { rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip); } if (rowsperstrip > length && rowsperstrip != (uint32)-1) rowsperstrip = length; } else if (rowsperstrip == (uint32) -1) rowsperstrip = length; TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip); } if (config != (uint16) -1) TIFFSetField(out, TIFFTAG_PLANARCONFIG, config); else CopyField(TIFFTAG_PLANARCONFIG, config); if (spp <= 4) CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT); CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT); /* SMinSampleValue & SMaxSampleValue */ switch (compression) { case COMPRESSION_JPEG: TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality); TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode); break; case COMPRESSION_LZW: case COMPRESSION_ADOBE_DEFLATE: case COMPRESSION_DEFLATE: if (predictor != (uint16)-1) TIFFSetField(out, TIFFTAG_PREDICTOR, predictor); else CopyField(TIFFTAG_PREDICTOR, predictor); break; case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: if (compression == COMPRESSION_CCITTFAX3) { if (g3opts != (uint32) -1) TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts); else CopyField(TIFFTAG_GROUP3OPTIONS, g3opts); } else CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG); CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG); CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII); break; } { uint32 len32; void** data; if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data)) TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data); } { uint16 ninks; const char* inknames; if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) { TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks); if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) { int inknameslen = strlen(inknames) + 1; const char* cp = inknames; while (ninks > 1) { cp = strchr(cp, '\0'); if (cp) { cp++; inknameslen += (strlen(cp) + 1); } ninks--; } TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames); } } } { unsigned short pg0, pg1; if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) { if (pageNum < 0) /* only one input file */ TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1); else TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0); } } for (p = tags; p < &tags[NTAGS]; p++) CopyTag(p->tag, p->count, p->type); /* Update these since they are overwritten from input res by loop above */ TIFFSetField(out, TIFFTAG_XRESOLUTION, (float)hres); TIFFSetField(out, TIFFTAG_YRESOLUTION, (float)vres); /* Compute the tile or strip dimensions and write to disk */ if (outtiled) { if (config == PLANARCONFIG_CONTIG) { writeBufferToContigTiles (out, sect_buff, length, width, spp); } else writeBufferToSeparateTiles (out, sect_buff, length, width, spp, dump); } else { if (config == PLANARCONFIG_CONTIG) { writeBufferToContigStrips (out, sect_buff, length, width, spp); } else { writeBufferToSeparateStrips(out, sect_buff, length, width, spp, dump); } } if (!TIFFWriteDirectory(out)) { TIFFClose(out); return (-1); } return (0); } /* end writeSingleSection */ /* Create a buffer to write one section at a time */ static int createImageSection(uint32 sectsize, unsigned char **sect_buff_ptr) { unsigned char *sect_buff = NULL; unsigned char *new_buff = NULL; static uint32 prev_sectsize = 0; sect_buff = *sect_buff_ptr; if (!sect_buff) { sect_buff = (unsigned char *)_TIFFmalloc(sectsize); *sect_buff_ptr = sect_buff; _TIFFmemset(sect_buff, 0, sectsize); } else { if (prev_sectsize < sectsize) { new_buff = _TIFFrealloc(sect_buff, sectsize); if (!new_buff) { free (sect_buff); sect_buff = (unsigned char *)_TIFFmalloc(sectsize); } else sect_buff = new_buff; _TIFFmemset(sect_buff, 0, sectsize); } } if (!sect_buff) { TIFFError("createImageSection", "Unable to allocate/reallocate section buffer"); return (-1); } prev_sectsize = sectsize; *sect_buff_ptr = sect_buff; return (0); } /* end createImageSection */ /* Process selections defined by regions, zones, margins, or fixed sized areas */ static int processCropSelections(struct image_data *image, struct crop_mask *crop, unsigned char **read_buff_ptr, struct buffinfo seg_buffs[]) { int i; uint32 width, length, total_width, total_length; tsize_t cropsize; unsigned char *crop_buff = NULL; unsigned char *read_buff = NULL; unsigned char *next_buff = NULL; tsize_t prev_cropsize = 0; read_buff = *read_buff_ptr; if (crop->img_mode == COMPOSITE_IMAGES) { cropsize = crop->bufftotal; crop_buff = seg_buffs[0].buffer; if (!crop_buff) crop_buff = (unsigned char *)_TIFFmalloc(cropsize); else { prev_cropsize = seg_buffs[0].size; if (prev_cropsize < cropsize) { next_buff = _TIFFrealloc(crop_buff, cropsize); if (! next_buff) { _TIFFfree (crop_buff); crop_buff = (unsigned char *)_TIFFmalloc(cropsize); } else crop_buff = next_buff; } } if (!crop_buff) { TIFFError("processCropSelections", "Unable to allocate/reallocate crop buffer"); return (-1); } _TIFFmemset(crop_buff, 0, cropsize); seg_buffs[0].buffer = crop_buff; seg_buffs[0].size = cropsize; /* Checks for matching width or length as required */ if (extractCompositeRegions(image, crop, read_buff, crop_buff) != 0) return (1); if (crop->crop_mode & CROP_INVERT) { switch (crop->photometric) { /* Just change the interpretation */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: image->photometric = crop->photometric; break; case INVERT_DATA_ONLY: case INVERT_DATA_AND_TAG: if (invertImage(image->photometric, image->spp, image->bps, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("processCropSelections", "Failed to invert colorspace for composite regions"); return (-1); } if (crop->photometric == INVERT_DATA_AND_TAG) { switch (image->photometric) { case PHOTOMETRIC_MINISWHITE: image->photometric = PHOTOMETRIC_MINISBLACK; break; case PHOTOMETRIC_MINISBLACK: image->photometric = PHOTOMETRIC_MINISWHITE; break; default: break; } } break; default: break; } } /* Mirror and Rotate will not work with multiple regions unless they are the same width */ if (crop->crop_mode & CROP_MIRROR) { if (mirrorImage(image->spp, image->bps, crop->mirror, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("processCropSelections", "Failed to mirror composite regions %s", (crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically"); return (-1); } } if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */ { if (rotateImage(crop->rotation, image, &crop->combined_width, &crop->combined_length, &crop_buff)) { TIFFError("processCropSelections", "Failed to rotate composite regions by %d degrees", crop->rotation); return (-1); } seg_buffs[0].buffer = crop_buff; seg_buffs[0].size = (((crop->combined_width * image->bps + 7 ) / 8) * image->spp) * crop->combined_length; } } else /* Separated Images */ { total_width = total_length = 0; for (i = 0; i < crop->selections; i++) { cropsize = crop->bufftotal; crop_buff = seg_buffs[i].buffer; if (!crop_buff) crop_buff = (unsigned char *)_TIFFmalloc(cropsize); else { prev_cropsize = seg_buffs[0].size; if (prev_cropsize < cropsize) { next_buff = _TIFFrealloc(crop_buff, cropsize); if (! next_buff) { _TIFFfree (crop_buff); crop_buff = (unsigned char *)_TIFFmalloc(cropsize); } else crop_buff = next_buff; } } if (!crop_buff) { TIFFError("processCropSelections", "Unable to allocate/reallocate crop buffer"); return (-1); } _TIFFmemset(crop_buff, 0, cropsize); seg_buffs[i].buffer = crop_buff; seg_buffs[i].size = cropsize; if (extractSeparateRegion(image, crop, read_buff, crop_buff, i)) { TIFFError("processCropSelections", "Unable to extract cropped region %d from image", i); return (-1); } width = crop->regionlist[i].width; length = crop->regionlist[i].length; if (crop->crop_mode & CROP_INVERT) { switch (crop->photometric) { /* Just change the interpretation */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: image->photometric = crop->photometric; break; case INVERT_DATA_ONLY: case INVERT_DATA_AND_TAG: if (invertImage(image->photometric, image->spp, image->bps, width, length, crop_buff)) { TIFFError("processCropSelections", "Failed to invert colorspace for region"); return (-1); } if (crop->photometric == INVERT_DATA_AND_TAG) { switch (image->photometric) { case PHOTOMETRIC_MINISWHITE: image->photometric = PHOTOMETRIC_MINISBLACK; break; case PHOTOMETRIC_MINISBLACK: image->photometric = PHOTOMETRIC_MINISWHITE; break; default: break; } } break; default: break; } } if (crop->crop_mode & CROP_MIRROR) { if (mirrorImage(image->spp, image->bps, crop->mirror, width, length, crop_buff)) { TIFFError("processCropSelections", "Failed to mirror crop region %s", (crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically"); return (-1); } } if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */ { if (rotateImage(crop->rotation, image, &crop->regionlist[i].width, &crop->regionlist[i].length, &crop_buff)) { TIFFError("processCropSelections", "Failed to rotate crop region by %d degrees", crop->rotation); return (-1); } total_width += crop->regionlist[i].width; total_length += crop->regionlist[i].length; crop->combined_width = total_width; crop->combined_length = total_length; seg_buffs[i].buffer = crop_buff; seg_buffs[i].size = (((crop->regionlist[i].width * image->bps + 7 ) / 8) * image->spp) * crop->regionlist[i].length; } } } return (0); } /* end processCropSelections */ /* Copy the crop section of the data from the current image into a buffer * and adjust the IFD values to reflect the new size. If no cropping is * required, use the origial read buffer as the crop buffer. * * There is quite a bit of redundancy between this routine and the more * specialized processCropSelections, but this provides * the most optimized path when no Zones or Regions are required. */ static int createCroppedImage(struct image_data *image, struct crop_mask *crop, unsigned char **read_buff_ptr, unsigned char **crop_buff_ptr) { tsize_t cropsize; unsigned char *read_buff = NULL; unsigned char *crop_buff = NULL; unsigned char *new_buff = NULL; static tsize_t prev_cropsize = 0; read_buff = *read_buff_ptr; /* process full image, no crop buffer needed */ crop_buff = read_buff; *crop_buff_ptr = read_buff; crop->combined_width = image->width; crop->combined_length = image->length; cropsize = crop->bufftotal; crop_buff = *crop_buff_ptr; if (!crop_buff) { crop_buff = (unsigned char *)_TIFFmalloc(cropsize); *crop_buff_ptr = crop_buff; _TIFFmemset(crop_buff, 0, cropsize); prev_cropsize = cropsize; } else { if (prev_cropsize < cropsize) { new_buff = _TIFFrealloc(crop_buff, cropsize); if (!new_buff) { free (crop_buff); crop_buff = (unsigned char *)_TIFFmalloc(cropsize); } else crop_buff = new_buff; _TIFFmemset(crop_buff, 0, cropsize); } } if (!crop_buff) { TIFFError("createCroppedImage", "Unable to allocate/reallocate crop buffer"); return (-1); } *crop_buff_ptr = crop_buff; if (crop->crop_mode & CROP_INVERT) { switch (crop->photometric) { /* Just change the interpretation */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: image->photometric = crop->photometric; break; case INVERT_DATA_ONLY: case INVERT_DATA_AND_TAG: if (invertImage(image->photometric, image->spp, image->bps, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("createCroppedImage", "Failed to invert colorspace for image or cropped selection"); return (-1); } if (crop->photometric == INVERT_DATA_AND_TAG) { switch (image->photometric) { case PHOTOMETRIC_MINISWHITE: image->photometric = PHOTOMETRIC_MINISBLACK; break; case PHOTOMETRIC_MINISBLACK: image->photometric = PHOTOMETRIC_MINISWHITE; break; default: break; } } break; default: break; } } if (crop->crop_mode & CROP_MIRROR) { if (mirrorImage(image->spp, image->bps, crop->mirror, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("createCroppedImage", "Failed to mirror image or cropped selection %s", (crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically"); return (-1); } } if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */ { if (rotateImage(crop->rotation, image, &crop->combined_width, &crop->combined_length, crop_buff_ptr)) { TIFFError("createCroppedImage", "Failed to rotate image or cropped selection by %d degrees", crop->rotation); return (-1); } } if (crop_buff == read_buff) /* we used the read buffer for the crop buffer */ *read_buff_ptr = NULL; /* so we don't try to free it later */ return (0); } /* end createCroppedImage */ /* The code in this function is heavily indebted to code from tiffcp. */ static int writeCroppedImage(TIFF *in, TIFF *out, struct image_data *image, struct dump_opts *dump, uint32 width, uint32 length, unsigned char *crop_buff, int pagenum, int total_pages) { uint16 bps, spp; struct cpTag* p; TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width); TIFFSetField(out, TIFFTAG_IMAGELENGTH, length); CopyField(TIFFTAG_BITSPERSAMPLE, bps); CopyField(TIFFTAG_SAMPLESPERPIXEL, spp); if (compression != (uint16)-1) TIFFSetField(out, TIFFTAG_COMPRESSION, compression); else CopyField(TIFFTAG_COMPRESSION, compression); if (compression == COMPRESSION_JPEG) { uint16 input_compression, input_photometric; if (TIFFGetField(in, TIFFTAG_COMPRESSION, &input_compression) && input_compression == COMPRESSION_JPEG) { TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } if (TIFFGetField(in, TIFFTAG_PHOTOMETRIC, &input_photometric)) { if(input_photometric == PHOTOMETRIC_RGB) { if (jpegcolormode == JPEGCOLORMODE_RGB) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB); } else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric); } } else { if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric); } if (fillorder != 0) TIFFSetField(out, TIFFTAG_FILLORDER, fillorder); else CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT); /* The loadimage function reads input orientation and sets * image->orientation. The correct_image_orientation function * applies the required rotation and mirror operations to * present the data in TOPLEFT orientation and updates * image->orientation if any transforms are performed, * as per EXIF standard. */ TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation); /* * Choose tiles/strip for the output image according to * the command line arguments (-tiles, -strips) and the * structure of the input image. */ if (outtiled == -1) outtiled = TIFFIsTiled(in); if (outtiled) { /* * Setup output file's tile width&height. If either * is not specified, use either the value from the * input image or, if nothing is defined, use the * library default. */ if (tilewidth == (uint32) -1) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth); if (tilelength == (uint32) -1) TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength); if (tilewidth > width) tilewidth = width; if (tilelength > length) tilelength = length; TIFFDefaultTileSize(out, &tilewidth, &tilelength); TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth); TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength); } else { /* * RowsPerStrip is left unspecified: use either the * value from the input image or, if nothing is defined, * use the library default. */ if (rowsperstrip == (uint32) 0) { if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip)) { rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip); } if (rowsperstrip > length) rowsperstrip = length; } else if (rowsperstrip == (uint32) -1) rowsperstrip = length; TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip); } if (config != (uint16) -1) TIFFSetField(out, TIFFTAG_PLANARCONFIG, config); else CopyField(TIFFTAG_PLANARCONFIG, config); if (spp <= 4) CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT); CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT); /* SMinSampleValue & SMaxSampleValue */ switch (compression) { case COMPRESSION_JPEG: TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality); TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode); break; case COMPRESSION_LZW: case COMPRESSION_ADOBE_DEFLATE: case COMPRESSION_DEFLATE: if (predictor != (uint16)-1) TIFFSetField(out, TIFFTAG_PREDICTOR, predictor); else CopyField(TIFFTAG_PREDICTOR, predictor); break; case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: if (compression == COMPRESSION_CCITTFAX3) { if (g3opts != (uint32) -1) TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts); else CopyField(TIFFTAG_GROUP3OPTIONS, g3opts); } else CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG); CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG); CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII); break; } { uint32 len32; void** data; if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data)) TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data); } { uint16 ninks; const char* inknames; if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) { TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks); if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) { int inknameslen = strlen(inknames) + 1; const char* cp = inknames; while (ninks > 1) { cp = strchr(cp, '\0'); if (cp) { cp++; inknameslen += (strlen(cp) + 1); } ninks--; } TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames); } } } { unsigned short pg0, pg1; if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) { TIFFSetField(out, TIFFTAG_PAGENUMBER, pagenum, total_pages); } } for (p = tags; p < &tags[NTAGS]; p++) CopyTag(p->tag, p->count, p->type); /* Compute the tile or strip dimensions and write to disk */ if (outtiled) { if (config == PLANARCONFIG_CONTIG) { writeBufferToContigTiles (out, crop_buff, length, width, spp); } else writeBufferToSeparateTiles (out, crop_buff, length, width, spp, dump); } else { if (config == PLANARCONFIG_CONTIG) { writeBufferToContigStrips (out, crop_buff, length, width, spp); } else { writeBufferToSeparateStrips(out, crop_buff, length, width, spp, dump); } } if (!TIFFWriteDirectory(out)) { TIFFClose(out); return (-1); } return (0); } /* end writeCroppedImage */ static int rotateContigSamples8bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0; uint32 src_byte = 0, src_bit = 0; uint32 row, rowsize = 0, bit_offset = 0; uint8 matchbits = 0, maskbits = 0; uint8 buff1 = 0, buff2 = 0; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples8bits","Invalid src or destination buffer"); return (1); } rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint8)-1 >> ( 8 - bps); buff1 = buff2 = 0; for (row = 0; row < length ; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (8 - src_bit - bps); buff1 = ((*next) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; } else { buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; } return (0); } /* end rotateContigSamples8bits */ static int rotateContigSamples16bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0; uint32 row, rowsize, bit_offset; uint32 src_byte = 0, src_bit = 0; uint16 matchbits = 0, maskbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; uint8 swapbuff[2]; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples16bits","Invalid src or destination buffer"); return (1); } rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint16)-1 >> (16 - bps); buff1 = buff2 = 0; for (row = 0; row < length; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (16 - src_bit - bps); if (little_endian) { swapbuff[1] = *next; swapbuff[0] = *(next + 1); } else { swapbuff[0] = *next; swapbuff[1] = *(next + 1); } buff1 = *((uint16 *)swapbuff); buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } else { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; } return (0); } /* end rotateContigSamples16bits */ static int rotateContigSamples24bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0; uint32 row, rowsize, bit_offset; uint32 src_byte = 0, src_bit = 0; uint32 matchbits = 0, maskbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; uint8 swapbuff[4]; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples24bits","Invalid src or destination buffer"); return (1); } rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint32)-1 >> (32 - bps); buff1 = buff2 = 0; for (row = 0; row < length; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (32 - src_bit - bps); if (little_endian) { swapbuff[3] = *next; swapbuff[2] = *(next + 1); swapbuff[1] = *(next + 2); swapbuff[0] = *(next + 3); } else { swapbuff[0] = *next; swapbuff[1] = *(next + 1); swapbuff[2] = *(next + 2); swapbuff[3] = *(next + 3); } buff1 = *((uint32 *)swapbuff); buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 16) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end rotateContigSamples24bits */ static int rotateContigSamples32bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0, shift_width = 0; int bytes_per_sample, bytes_per_pixel; uint32 row, rowsize, bit_offset; uint32 src_byte, src_bit; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; unsigned char swapbuff1[4]; unsigned char swapbuff2[4]; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples24bits","Invalid src or destination buffer"); return (1); } bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint64)-1 >> (64 - bps); buff1 = buff2 = 0; for (row = 0; row < length; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (64 - src_bit - bps); if (little_endian) { swapbuff1[3] = *next; swapbuff1[2] = *(next + 1); swapbuff1[1] = *(next + 2); swapbuff1[0] = *(next + 3); } else { swapbuff1[0] = *next; swapbuff1[1] = *(next + 1); swapbuff1[2] = *(next + 2); swapbuff1[3] = *(next + 3); } longbuff1 = *((uint32 *)swapbuff1); memset (swapbuff2, '\0', sizeof(swapbuff2)); if (little_endian) { swapbuff2[3] = *next; swapbuff2[2] = *(next + 1); swapbuff2[1] = *(next + 2); swapbuff2[0] = *(next + 3); } else { swapbuff2[0] = *next; swapbuff2[1] = *(next + 1); swapbuff2[2] = *(next + 2); swapbuff2[3] = *(next + 3); } longbuff2 = *((uint32 *)swapbuff2); buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); if (ready_bits < 32) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end rotateContigSamples32bits */ /* Rotate an image by a multiple of 90 degrees clockwise */ static int rotateImage(uint16 rotation, struct image_data *image, uint32 *img_width, uint32 *img_length, unsigned char **ibuff_ptr) { int shift_width; uint32 bytes_per_pixel, bytes_per_sample; uint32 row, rowsize, src_offset, dst_offset; uint32 i, col, width, length; uint32 colsize, buffsize, col_offset, pix_offset; unsigned char *ibuff; unsigned char *src; unsigned char *dst; uint16 spp, bps; float res_temp; unsigned char *rbuff = NULL; width = *img_width; length = *img_length; spp = image->spp; bps = image->bps; rowsize = ((bps * spp * width) + 7) / 8; colsize = ((bps * spp * length) + 7) / 8; if ((colsize * width) > (rowsize * length)) buffsize = (colsize + 1) * width; else buffsize = (rowsize + 1) * length; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; switch (rotation) { case 0: case 360: return (0); case 90: case 180: case 270: break; default: TIFFError("rotateImage", "Invalid rotation angle %d", rotation); return (-1); } if (!(rbuff = (unsigned char *)_TIFFmalloc(buffsize))) { TIFFError("rotateImage", "Unable to allocate rotation buffer of %1u bytes", buffsize); return (-1); } _TIFFmemset(rbuff, '\0', buffsize); ibuff = *ibuff_ptr; switch (rotation) { case 180: if ((bps % 8) == 0) /* byte alligned data */ { src = ibuff; pix_offset = (spp * bps) / 8; for (row = 0; row < length; row++) { dst_offset = (length - row - 1) * rowsize; for (col = 0; col < width; col++) { col_offset = (width - col - 1) * pix_offset; dst = rbuff + dst_offset + col_offset; for (i = 0; i < bytes_per_pixel; i++) *dst++ = *src++; } } } else { /* non 8 bit per sample data */ for (row = 0; row < length; row++) { src_offset = row * rowsize; dst_offset = (length - row - 1) * rowsize; src = ibuff + src_offset; dst = rbuff + dst_offset; switch (shift_width) { case 1: if (reverseSamples8bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 2: if (reverseSamples16bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 3: if (reverseSamples24bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 4: case 5: if (reverseSamples32bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; default: TIFFError("rotateImage","Unsupported bit depth %d", bps); _TIFFfree(rbuff); return (-1); } } } _TIFFfree(ibuff); *(ibuff_ptr) = rbuff; break; case 90: if ((bps % 8) == 0) /* byte aligned data */ { for (col = 0; col < width; col++) { src_offset = ((length - 1) * rowsize) + (col * bytes_per_pixel); dst_offset = col * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; for (row = length; row > 0; row--) { for (i = 0; i < bytes_per_pixel; i++) *dst++ = *(src + i); src -= rowsize; } } } else { /* non 8 bit per sample data */ for (col = 0; col < width; col++) { src_offset = (length - 1) * rowsize; dst_offset = col * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; switch (shift_width) { case 1: if (rotateContigSamples8bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 2: if (rotateContigSamples16bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 3: if (rotateContigSamples24bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 4: case 5: if (rotateContigSamples32bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; default: TIFFError("rotateImage","Unsupported bit depth %d", bps); _TIFFfree(rbuff); return (-1); } } } _TIFFfree(ibuff); *(ibuff_ptr) = rbuff; *img_width = length; *img_length = width; image->width = length; image->length = width; res_temp = image->xres; image->xres = image->yres; image->yres = res_temp; break; case 270: if ((bps % 8) == 0) /* byte aligned data */ { for (col = 0; col < width; col++) { src_offset = col * bytes_per_pixel; dst_offset = (width - col - 1) * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; for (row = length; row > 0; row--) { for (i = 0; i < bytes_per_pixel; i++) *dst++ = *(src + i); src += rowsize; } } } else { /* non 8 bit per sample data */ for (col = 0; col < width; col++) { src_offset = 0; dst_offset = (width - col - 1) * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; switch (shift_width) { case 1: if (rotateContigSamples8bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 2: if (rotateContigSamples16bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 3: if (rotateContigSamples24bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 4: case 5: if (rotateContigSamples32bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; default: TIFFError("rotateImage","Unsupported bit depth %d", bps); _TIFFfree(rbuff); return (-1); } } } _TIFFfree(ibuff); *(ibuff_ptr) = rbuff; *img_width = length; *img_length = width; image->width = length; image->length = width; res_temp = image->xres; image->xres = image->yres; image->yres = res_temp; break; default: break; } return (0); } /* end rotateImage */ static int reverseSamples8bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0; uint32 col; uint32 src_byte, src_bit; uint32 bit_offset = 0; uint8 matchbits = 0, maskbits = 0; uint8 buff1 = 0, buff2 = 0; unsigned char *src; unsigned char *dst; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSamples8bits","Invalid image or work buffer"); return (1); } ready_bits = 0; maskbits = (uint8)-1 >> ( 8 - bps); dst = obuff; for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; matchbits = maskbits << (8 - src_bit - bps); buff1 = ((*src) & matchbits) << (src_bit); if (ready_bits < 8) buff2 = (buff2 | (buff1 >> ready_bits)); else /* If we have a full buffer's worth, write it out */ { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; } ready_bits += bps; } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; } return (0); } /* end reverseSamples8bits */ static int reverseSamples16bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0; uint32 col; uint32 src_byte = 0, src_bit = 0; uint32 bit_offset = 0; uint16 matchbits = 0, maskbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; unsigned char *src; unsigned char *dst; unsigned char swapbuff[2]; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSample16bits","Invalid image or work buffer"); return (1); } ready_bits = 0; maskbits = (uint16)-1 >> (16 - bps); dst = obuff; for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; matchbits = maskbits << (16 - src_bit - bps); if (little_endian) { swapbuff[1] = *src; swapbuff[0] = *(src + 1); } else { swapbuff[0] = *src; swapbuff[1] = *(src + 1); } buff1 = *((uint16 *)swapbuff); buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 8) { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } ready_bits += bps; } } if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; } return (0); } /* end reverseSamples16bits */ static int reverseSamples24bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0; uint32 col; uint32 src_byte = 0, src_bit = 0; uint32 bit_offset = 0; uint32 matchbits = 0, maskbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; unsigned char *src; unsigned char *dst; unsigned char swapbuff[4]; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSamples24bits","Invalid image or work buffer"); return (1); } ready_bits = 0; maskbits = (uint32)-1 >> (32 - bps); dst = obuff; for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; matchbits = maskbits << (32 - src_bit - bps); if (little_endian) { swapbuff[3] = *src; swapbuff[2] = *(src + 1); swapbuff[1] = *(src + 2); swapbuff[0] = *(src + 3); } else { swapbuff[0] = *src; swapbuff[1] = *(src + 1); swapbuff[2] = *(src + 2); swapbuff[3] = *(src + 3); } buff1 = *((uint32 *)swapbuff); buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 16) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end reverseSamples24bits */ static int reverseSamples32bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0, shift_width = 0; int bytes_per_sample, bytes_per_pixel; uint32 bit_offset; uint32 src_byte = 0, src_bit = 0; uint32 col; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; unsigned char *src; unsigned char *dst; unsigned char swapbuff1[4]; unsigned char swapbuff2[4]; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSamples32bits","Invalid image or work buffer"); return (1); } ready_bits = 0; maskbits = (uint64)-1 >> (64 - bps); dst = obuff; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; matchbits = maskbits << (64 - src_bit - bps); if (little_endian) { swapbuff1[3] = *src; swapbuff1[2] = *(src + 1); swapbuff1[1] = *(src + 2); swapbuff1[0] = *(src + 3); } else { swapbuff1[0] = *src; swapbuff1[1] = *(src + 1); swapbuff1[2] = *(src + 2); swapbuff1[3] = *(src + 3); } longbuff1 = *((uint32 *)swapbuff1); memset (swapbuff2, '\0', sizeof(swapbuff2)); if (little_endian) { swapbuff2[3] = *src; swapbuff2[2] = *(src + 1); swapbuff2[1] = *(src + 2); swapbuff2[0] = *(src + 3); } else { swapbuff2[0] = *src; swapbuff2[1] = *(src + 1); swapbuff2[2] = *(src + 2); swapbuff2[3] = *(src + 3); } longbuff2 = *((uint32 *)swapbuff2); buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); if (ready_bits < 32) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end reverseSamples32bits */ static int reverseSamplesBytes (uint16 spp, uint16 bps, uint32 width, uint8 *src, uint8 *dst) { int i; uint32 col, bytes_per_pixel, col_offset; uint8 bytebuff1; unsigned char swapbuff[32]; if ((src == NULL) || (dst == NULL)) { TIFFError("reverseSamplesBytes","Invalid input or output buffer"); return (1); } bytes_per_pixel = ((bps * spp) + 7) / 8; switch (bps / 8) { case 8: /* Use memcpy for multiple bytes per sample data */ case 4: case 3: case 2: for (col = 0; col < (width / 2); col++) { col_offset = col * bytes_per_pixel; _TIFFmemcpy (swapbuff, src + col_offset, bytes_per_pixel); _TIFFmemcpy (src + col_offset, dst - col_offset - bytes_per_pixel, bytes_per_pixel); _TIFFmemcpy (dst - col_offset - bytes_per_pixel, swapbuff, bytes_per_pixel); } break; case 1: /* Use byte copy only for single byte per sample data */ for (col = 0; col < (width / 2); col++) { for (i = 0; i < spp; i++) { bytebuff1 = *src; *src++ = *(dst - spp + i); *(dst - spp + i) = bytebuff1; } dst -= spp; } break; default: TIFFError("reverseSamplesBytes","Unsupported bit depth %d", bps); return (1); } return (0); } /* end reverseSamplesBytes */ /* Mirror an image horizontally or vertically */ static int mirrorImage(uint16 spp, uint16 bps, uint16 mirror, uint32 width, uint32 length, unsigned char *ibuff) { int shift_width; uint32 bytes_per_pixel, bytes_per_sample; uint32 row, rowsize, row_offset; unsigned char *line_buff = NULL; unsigned char *src; unsigned char *dst; src = ibuff; rowsize = ((width * bps * spp) + 7) / 8; switch (mirror) { case MIRROR_BOTH: case MIRROR_VERT: line_buff = (unsigned char *)_TIFFmalloc(rowsize); if (line_buff == NULL) { TIFFError ("mirrorImage", "Unable to allocate mirror line buffer of %1u bytes", rowsize); return (-1); } dst = ibuff + (rowsize * (length - 1)); for (row = 0; row < length / 2; row++) { _TIFFmemcpy(line_buff, src, rowsize); _TIFFmemcpy(src, dst, rowsize); _TIFFmemcpy(dst, line_buff, rowsize); src += (rowsize); dst -= (rowsize); } if (line_buff) _TIFFfree(line_buff); if (mirror == MIRROR_VERT) break; case MIRROR_HORIZ : if ((bps % 8) == 0) /* byte alligned data */ { for (row = 0; row < length; row++) { row_offset = row * rowsize; src = ibuff + row_offset; dst = ibuff + row_offset + rowsize; if (reverseSamplesBytes(spp, bps, width, src, dst)) { return (-1); } } } else { /* non 8 bit per sample data */ if (!(line_buff = (unsigned char *)_TIFFmalloc(rowsize + 1))) { TIFFError("mirrorImage", "Unable to allocate mirror line buffer"); return (-1); } bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; for (row = 0; row < length; row++) { row_offset = row * rowsize; src = ibuff + row_offset; _TIFFmemset (line_buff, '\0', rowsize); switch (shift_width) { case 1: if (reverseSamples8bits(spp, bps, width, src, line_buff)) { _TIFFfree(line_buff); return (-1); } _TIFFmemcpy (src, line_buff, rowsize); break; case 2: if (reverseSamples16bits(spp, bps, width, src, line_buff)) { _TIFFfree(line_buff); return (-1); } _TIFFmemcpy (src, line_buff, rowsize); break; case 3: if (reverseSamples24bits(spp, bps, width, src, line_buff)) { _TIFFfree(line_buff); return (-1); } _TIFFmemcpy (src, line_buff, rowsize); break; case 4: case 5: if (reverseSamples32bits(spp, bps, width, src, line_buff)) { _TIFFfree(line_buff); return (-1); } _TIFFmemcpy (src, line_buff, rowsize); break; default: TIFFError("mirrorImage","Unsupported bit depth %d", bps); _TIFFfree(line_buff); return (-1); } } if (line_buff) _TIFFfree(line_buff); } break; default: TIFFError ("mirrorImage", "Invalid mirror axis %d", mirror); return (-1); break; } return (0); } /* Invert the light and dark values for a bilevel or grayscale image */ static int invertImage(uint16 photometric, uint16 spp, uint16 bps, uint32 width, uint32 length, unsigned char *work_buff) { uint32 row, col; unsigned char bytebuff1, bytebuff2, bytebuff3, bytebuff4; unsigned char *src; uint16 *src_uint16; uint32 *src_uint32; if (spp != 1) { TIFFError("invertImage", "Image inversion not supported for more than one sample per pixel"); return (-1); } if (photometric != PHOTOMETRIC_MINISWHITE && photometric != PHOTOMETRIC_MINISBLACK) { TIFFError("invertImage", "Only black and white and grayscale images can be inverted"); return (-1); } src = work_buff; if (src == NULL) { TIFFError ("invertImage", "Invalid crop buffer passed to invertImage"); return (-1); } switch (bps) { case 32: src_uint32 = (uint32 *)src; for (row = 0; row < length; row++) for (col = 0; col < width; col++) { *src_uint32 = (uint32)0xFFFFFFFF - *src_uint32; src_uint32++; } break; case 16: src_uint16 = (uint16 *)src; for (row = 0; row < length; row++) for (col = 0; col < width; col++) { *src_uint16 = (uint16)0xFFFF - *src_uint16; src_uint16++; } break; case 8: for (row = 0; row < length; row++) for (col = 0; col < width; col++) { *src = (uint8)255 - *src; src++; } break; case 4: for (row = 0; row < length; row++) for (col = 0; col < width; col++) { bytebuff1 = 16 - (uint8)(*src & 240 >> 4); bytebuff2 = 16 - (*src & 15); *src = bytebuff1 << 4 & bytebuff2; src++; } break; case 2: for (row = 0; row < length; row++) for (col = 0; col < width; col++) { bytebuff1 = 4 - (uint8)(*src & 192 >> 6); bytebuff2 = 4 - (uint8)(*src & 48 >> 4); bytebuff3 = 4 - (uint8)(*src & 12 >> 2); bytebuff4 = 4 - (uint8)(*src & 3); *src = (bytebuff1 << 6) || (bytebuff2 << 4) || (bytebuff3 << 2) || bytebuff4; src++; } break; case 1: for (row = 0; row < length; row++) for (col = 0; col < width; col += 8 /(spp * bps)) { *src = ~(*src); src++; } break; default: TIFFError("invertImage", "Unsupported bit depth %d", bps); return (-1); } return (0); } /* vim: set ts=8 sts=8 sw=8 noet: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/libtiff_2009-02-05-764dbba-2e42d63.c
manybugs_data_48
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Rasmus Lerdorf <[email protected]> | | Stig Bakken <[email protected]> | | Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | PHP 4.0 patches by Thies C. Arntzen ([email protected]) | | PHP streams by Wez Furlong ([email protected]) | +----------------------------------------------------------------------+ */ /* $Id$ */ /* Synced with php 3.0 revision 1.218 1999-06-16 [ssb] */ /* {{{ includes */ #include "php.h" #include "php_globals.h" #include "ext/standard/flock_compat.h" #include "ext/standard/exec.h" #include "ext/standard/php_filestat.h" #include "php_open_temporary_file.h" #include "ext/standard/basic_functions.h" #include "php_ini.h" #include "php_smart_str.h" #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #ifdef PHP_WIN32 # include <io.h> # define O_RDONLY _O_RDONLY # include "win32/param.h" # include "win32/winutil.h" # include "win32/fnmatch.h" #else # if HAVE_SYS_PARAM_H # include <sys/param.h> # endif # if HAVE_SYS_SELECT_H # include <sys/select.h> # endif # if defined(NETWARE) && defined(USE_WINSOCK) # include <novsock2.h> # else # include <sys/socket.h> # include <netinet/in.h> # include <netdb.h> # endif # if HAVE_ARPA_INET_H # include <arpa/inet.h> # endif #endif #include "ext/standard/head.h" #include "php_string.h" #include "file.h" #if HAVE_PWD_H # ifdef PHP_WIN32 # include "win32/pwd.h" # else # include <pwd.h> # endif #endif #ifdef HAVE_SYS_TIME_H # include <sys/time.h> #endif #include "fsock.h" #include "fopen_wrappers.h" #include "streamsfuncs.h" #include "php_globals.h" #ifdef HAVE_SYS_FILE_H # include <sys/file.h> #endif #if MISSING_FCLOSE_DECL extern int fclose(FILE *); #endif #ifdef HAVE_SYS_MMAN_H # include <sys/mman.h> #endif #include "scanf.h" #include "zend_API.h" #ifdef ZTS int file_globals_id; #else php_file_globals file_globals; #endif #if defined(HAVE_FNMATCH) && !defined(PHP_WIN32) # ifndef _GNU_SOURCE # define _GNU_SOURCE # endif # include <fnmatch.h> #endif #ifdef HAVE_WCHAR_H # include <wchar.h> #endif #ifndef S_ISDIR # define S_ISDIR(mode) (((mode)&S_IFMT) == S_IFDIR) #endif /* }}} */ #define PHP_STREAM_TO_ZVAL(stream, arg) \ php_stream_from_zval_no_verify(stream, arg); \ if (stream == NULL) { \ RETURN_FALSE; \ } /* {{{ ZTS-stuff / Globals / Prototypes */ /* sharing globals is *evil* */ static int le_stream_context = FAILURE; PHPAPI int php_le_stream_context(TSRMLS_D) { return le_stream_context; } /* }}} */ /* {{{ Module-Stuff */ static ZEND_RSRC_DTOR_FUNC(file_context_dtor) { php_stream_context *context = (php_stream_context*)rsrc->ptr; if (context->options) { zval_ptr_dtor(&context->options); context->options = NULL; } php_stream_context_free(context); } static void file_globals_ctor(php_file_globals *file_globals_p TSRMLS_DC) { FG(pclose_ret) = 0; FG(user_stream_current_filename) = NULL; FG(def_chunk_size) = PHP_SOCK_CHUNK_SIZE; } static void file_globals_dtor(php_file_globals *file_globals_p TSRMLS_DC) { } PHP_INI_BEGIN() STD_PHP_INI_ENTRY("user_agent", NULL, PHP_INI_ALL, OnUpdateString, user_agent, php_file_globals, file_globals) STD_PHP_INI_ENTRY("from", NULL, PHP_INI_ALL, OnUpdateString, from_address, php_file_globals, file_globals) STD_PHP_INI_ENTRY("default_socket_timeout", "60", PHP_INI_ALL, OnUpdateLong, default_socket_timeout, php_file_globals, file_globals) STD_PHP_INI_ENTRY("auto_detect_line_endings", "0", PHP_INI_ALL, OnUpdateLong, auto_detect_line_endings, php_file_globals, file_globals) PHP_INI_END() PHP_MINIT_FUNCTION(file) { le_stream_context = zend_register_list_destructors_ex(file_context_dtor, NULL, "stream-context", module_number); #ifdef ZTS ts_allocate_id(&file_globals_id, sizeof(php_file_globals), (ts_allocate_ctor) file_globals_ctor, (ts_allocate_dtor) file_globals_dtor); #else file_globals_ctor(&file_globals TSRMLS_CC); #endif REGISTER_INI_ENTRIES(); REGISTER_LONG_CONSTANT("SEEK_SET", SEEK_SET, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SEEK_CUR", SEEK_CUR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SEEK_END", SEEK_END, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LOCK_SH", PHP_LOCK_SH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LOCK_EX", PHP_LOCK_EX, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LOCK_UN", PHP_LOCK_UN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LOCK_NB", PHP_LOCK_NB, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_NOTIFY_CONNECT", PHP_STREAM_NOTIFY_CONNECT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_NOTIFY_AUTH_REQUIRED", PHP_STREAM_NOTIFY_AUTH_REQUIRED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_NOTIFY_AUTH_RESULT", PHP_STREAM_NOTIFY_AUTH_RESULT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_NOTIFY_MIME_TYPE_IS", PHP_STREAM_NOTIFY_MIME_TYPE_IS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_NOTIFY_FILE_SIZE_IS", PHP_STREAM_NOTIFY_FILE_SIZE_IS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_NOTIFY_REDIRECTED", PHP_STREAM_NOTIFY_REDIRECTED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_NOTIFY_PROGRESS", PHP_STREAM_NOTIFY_PROGRESS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_NOTIFY_FAILURE", PHP_STREAM_NOTIFY_FAILURE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_NOTIFY_COMPLETED", PHP_STREAM_NOTIFY_COMPLETED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_NOTIFY_RESOLVE", PHP_STREAM_NOTIFY_RESOLVE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_NOTIFY_SEVERITY_INFO", PHP_STREAM_NOTIFY_SEVERITY_INFO, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_NOTIFY_SEVERITY_WARN", PHP_STREAM_NOTIFY_SEVERITY_WARN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_NOTIFY_SEVERITY_ERR", PHP_STREAM_NOTIFY_SEVERITY_ERR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_FILTER_READ", PHP_STREAM_FILTER_READ, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_FILTER_WRITE", PHP_STREAM_FILTER_WRITE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_FILTER_ALL", PHP_STREAM_FILTER_ALL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_CLIENT_PERSISTENT", PHP_STREAM_CLIENT_PERSISTENT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_CLIENT_ASYNC_CONNECT", PHP_STREAM_CLIENT_ASYNC_CONNECT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_CLIENT_CONNECT", PHP_STREAM_CLIENT_CONNECT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_SSLv2_CLIENT", STREAM_CRYPTO_METHOD_SSLv2_CLIENT, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_SSLv3_CLIENT", STREAM_CRYPTO_METHOD_SSLv3_CLIENT, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_SSLv23_CLIENT", STREAM_CRYPTO_METHOD_SSLv23_CLIENT, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_TLS_CLIENT", STREAM_CRYPTO_METHOD_TLS_CLIENT, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_SSLv2_SERVER", STREAM_CRYPTO_METHOD_SSLv2_SERVER, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_SSLv3_SERVER", STREAM_CRYPTO_METHOD_SSLv3_SERVER, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_SSLv23_SERVER", STREAM_CRYPTO_METHOD_SSLv23_SERVER, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_TLS_SERVER", STREAM_CRYPTO_METHOD_TLS_SERVER, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_SHUT_RD", STREAM_SHUT_RD, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_SHUT_WR", STREAM_SHUT_WR, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_SHUT_RDWR", STREAM_SHUT_RDWR, CONST_CS|CONST_PERSISTENT); #ifdef PF_INET REGISTER_LONG_CONSTANT("STREAM_PF_INET", PF_INET, CONST_CS|CONST_PERSISTENT); #elif defined(AF_INET) REGISTER_LONG_CONSTANT("STREAM_PF_INET", AF_INET, CONST_CS|CONST_PERSISTENT); #endif #if HAVE_IPV6 # ifdef PF_INET6 REGISTER_LONG_CONSTANT("STREAM_PF_INET6", PF_INET6, CONST_CS|CONST_PERSISTENT); # elif defined(AF_INET6) REGISTER_LONG_CONSTANT("STREAM_PF_INET6", AF_INET6, CONST_CS|CONST_PERSISTENT); # endif #endif #ifdef PF_UNIX REGISTER_LONG_CONSTANT("STREAM_PF_UNIX", PF_UNIX, CONST_CS|CONST_PERSISTENT); #elif defined(AF_UNIX) REGISTER_LONG_CONSTANT("STREAM_PF_UNIX", AF_UNIX, CONST_CS|CONST_PERSISTENT); #endif #ifdef IPPROTO_IP /* most people will use this one when calling socket() or socketpair() */ REGISTER_LONG_CONSTANT("STREAM_IPPROTO_IP", IPPROTO_IP, CONST_CS|CONST_PERSISTENT); #endif #ifdef IPPROTO_TCP REGISTER_LONG_CONSTANT("STREAM_IPPROTO_TCP", IPPROTO_TCP, CONST_CS|CONST_PERSISTENT); #endif #ifdef IPPROTO_UDP REGISTER_LONG_CONSTANT("STREAM_IPPROTO_UDP", IPPROTO_UDP, CONST_CS|CONST_PERSISTENT); #endif #ifdef IPPROTO_ICMP REGISTER_LONG_CONSTANT("STREAM_IPPROTO_ICMP", IPPROTO_ICMP, CONST_CS|CONST_PERSISTENT); #endif #ifdef IPPROTO_RAW REGISTER_LONG_CONSTANT("STREAM_IPPROTO_RAW", IPPROTO_RAW, CONST_CS|CONST_PERSISTENT); #endif REGISTER_LONG_CONSTANT("STREAM_SOCK_STREAM", SOCK_STREAM, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_SOCK_DGRAM", SOCK_DGRAM, CONST_CS|CONST_PERSISTENT); #ifdef SOCK_RAW REGISTER_LONG_CONSTANT("STREAM_SOCK_RAW", SOCK_RAW, CONST_CS|CONST_PERSISTENT); #endif #ifdef SOCK_SEQPACKET REGISTER_LONG_CONSTANT("STREAM_SOCK_SEQPACKET", SOCK_SEQPACKET, CONST_CS|CONST_PERSISTENT); #endif #ifdef SOCK_RDM REGISTER_LONG_CONSTANT("STREAM_SOCK_RDM", SOCK_RDM, CONST_CS|CONST_PERSISTENT); #endif REGISTER_LONG_CONSTANT("STREAM_PEEK", STREAM_PEEK, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_OOB", STREAM_OOB, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_SERVER_BIND", STREAM_XPORT_BIND, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_SERVER_LISTEN", STREAM_XPORT_LISTEN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILE_USE_INCLUDE_PATH", PHP_FILE_USE_INCLUDE_PATH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILE_IGNORE_NEW_LINES", PHP_FILE_IGNORE_NEW_LINES, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILE_SKIP_EMPTY_LINES", PHP_FILE_SKIP_EMPTY_LINES, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILE_APPEND", PHP_FILE_APPEND, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILE_NO_DEFAULT_CONTEXT", PHP_FILE_NO_DEFAULT_CONTEXT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILE_TEXT", 0, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILE_BINARY", 0, CONST_CS | CONST_PERSISTENT); #ifdef HAVE_FNMATCH REGISTER_LONG_CONSTANT("FNM_NOESCAPE", FNM_NOESCAPE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FNM_PATHNAME", FNM_PATHNAME, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FNM_PERIOD", FNM_PERIOD, CONST_CS | CONST_PERSISTENT); # ifdef FNM_CASEFOLD /* a GNU extension */ /* TODO emulate if not available */ REGISTER_LONG_CONSTANT("FNM_CASEFOLD", FNM_CASEFOLD, CONST_CS | CONST_PERSISTENT); # endif #endif return SUCCESS; } /* }}} */ PHP_MSHUTDOWN_FUNCTION(file) /* {{{ */ { #ifndef ZTS file_globals_dtor(&file_globals TSRMLS_CC); #endif return SUCCESS; } /* }}} */ static int flock_values[] = { LOCK_SH, LOCK_EX, LOCK_UN }; /* {{{ proto bool flock(resource fp, int operation [, int &wouldblock]) Portable file locking */ PHP_FUNCTION(flock) { zval *arg1, *arg3 = NULL; int act; php_stream *stream; long operation = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl|z", &arg1, &operation, &arg3) == FAILURE) { return; } PHP_STREAM_TO_ZVAL(stream, &arg1); act = operation & 3; if (act < 1 || act > 3) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Illegal operation argument"); RETURN_FALSE; } if (arg3 && PZVAL_IS_REF(arg3)) { convert_to_long_ex(&arg3); Z_LVAL_P(arg3) = 0; } /* flock_values contains all possible actions if (operation & 4) we won't block on the lock */ act = flock_values[act - 1] | (operation & PHP_LOCK_NB ? LOCK_NB : 0); if (php_stream_lock(stream, act)) { if (operation && errno == EWOULDBLOCK && arg3 && PZVAL_IS_REF(arg3)) { Z_LVAL_P(arg3) = 1; } RETURN_FALSE; } RETURN_TRUE; } /* }}} */ #define PHP_META_UNSAFE ".\\+*?[^]$() " /* {{{ proto array get_meta_tags(string filename [, bool use_include_path]) Extracts all meta tag content attributes from a file and returns an array */ PHP_FUNCTION(get_meta_tags) { char *filename; int filename_len; zend_bool use_include_path = 0; int in_tag = 0, done = 0; int looking_for_val = 0, have_name = 0, have_content = 0; int saw_name = 0, saw_content = 0; char *name = NULL, *value = NULL, *temp = NULL; php_meta_tags_token tok, tok_last; php_meta_tags_data md; /* Initiailize our structure */ memset(&md, 0, sizeof(md)); /* Parse arguments */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|b", &filename, &filename_len, &use_include_path) == FAILURE) { return; } md.stream = php_stream_open_wrapper(filename, "rb", (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL); if (!md.stream) { RETURN_FALSE; } array_init(return_value); tok_last = TOK_EOF; while (!done && (tok = php_next_meta_token(&md TSRMLS_CC)) != TOK_EOF) { if (tok == TOK_ID) { if (tok_last == TOK_OPENTAG) { md.in_meta = !strcasecmp("meta", md.token_data); } else if (tok_last == TOK_SLASH && in_tag) { if (strcasecmp("head", md.token_data) == 0) { /* We are done here! */ done = 1; } } else if (tok_last == TOK_EQUAL && looking_for_val) { if (saw_name) { STR_FREE(name); /* Get the NAME attr (Single word attr, non-quoted) */ temp = name = estrndup(md.token_data, md.token_len); while (temp && *temp) { if (strchr(PHP_META_UNSAFE, *temp)) { *temp = '_'; } temp++; } have_name = 1; } else if (saw_content) { STR_FREE(value); value = estrndup(md.token_data, md.token_len); have_content = 1; } looking_for_val = 0; } else { if (md.in_meta) { if (strcasecmp("name", md.token_data) == 0) { saw_name = 1; saw_content = 0; looking_for_val = 1; } else if (strcasecmp("content", md.token_data) == 0) { saw_name = 0; saw_content = 1; looking_for_val = 1; } } } } else if (tok == TOK_STRING && tok_last == TOK_EQUAL && looking_for_val) { if (saw_name) { STR_FREE(name); /* Get the NAME attr (Quoted single/double) */ temp = name = estrndup(md.token_data, md.token_len); while (temp && *temp) { if (strchr(PHP_META_UNSAFE, *temp)) { *temp = '_'; } temp++; } have_name = 1; } else if (saw_content) { STR_FREE(value); value = estrndup(md.token_data, md.token_len); have_content = 1; } looking_for_val = 0; } else if (tok == TOK_OPENTAG) { if (looking_for_val) { looking_for_val = 0; have_name = saw_name = 0; have_content = saw_content = 0; } in_tag = 1; } else if (tok == TOK_CLOSETAG) { if (have_name) { /* For BC */ php_strtolower(name, strlen(name)); if (have_content) { add_assoc_string(return_value, name, value, 1); } else { add_assoc_string(return_value, name, "", 1); } efree(name); STR_FREE(value); } else if (have_content) { efree(value); } name = value = NULL; /* Reset all of our flags */ in_tag = looking_for_val = 0; have_name = saw_name = 0; have_content = saw_content = 0; md.in_meta = 0; } tok_last = tok; if (md.token_data) efree(md.token_data); md.token_data = NULL; } STR_FREE(value); STR_FREE(name); php_stream_close(md.stream); } /* }}} */ /* {{{ proto string file_get_contents(string filename [, bool use_include_path [, resource context [, long offset [, long maxlen]]]]) Read the entire file into a string */ PHP_FUNCTION(file_get_contents) { char *filename; int filename_len; char *contents; zend_bool use_include_path = 0; php_stream *stream; int len; long offset = -1; long maxlen = PHP_STREAM_COPY_ALL; zval *zcontext = NULL; php_stream_context *context = NULL; /* Parse arguments */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|br!ll", &filename, &filename_len, &use_include_path, &zcontext, &offset, &maxlen) == FAILURE) { return; } if (ZEND_NUM_ARGS() == 5 && maxlen < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "length must be greater than or equal to zero"); RETURN_FALSE; } context = php_stream_context_from_zval(zcontext, 0); stream = php_stream_open_wrapper_ex(filename, "rb", (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, context); if (!stream) { RETURN_FALSE; } if (offset > 0 && php_stream_seek(stream, offset, SEEK_SET) < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to seek to position %ld in the stream", offset); php_stream_close(stream); RETURN_FALSE; } if ((len = php_stream_copy_to_mem(stream, &contents, maxlen, 0)) > 0) { RETVAL_STRINGL(contents, len, 0); } else if (len == 0) { RETVAL_EMPTY_STRING(); } else { RETVAL_FALSE; } php_stream_close(stream); } /* }}} */ /* {{{ proto int file_put_contents(string file, mixed data [, int flags [, resource context]]) Write/Create a file with contents data and return the number of bytes written */ PHP_FUNCTION(file_put_contents) { php_stream *stream; char *filename; int filename_len; zval *data; int numbytes = 0; long flags = 0; zval *zcontext = NULL; php_stream_context *context = NULL; php_stream *srcstream = NULL; char mode[3] = "wb"; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "pz/|lr!", &filename, &filename_len, &data, &flags, &zcontext) == FAILURE) { return; } if (Z_TYPE_P(data) == IS_RESOURCE) { php_stream_from_zval(srcstream, &data); } context = php_stream_context_from_zval(zcontext, flags & PHP_FILE_NO_DEFAULT_CONTEXT); if (flags & PHP_FILE_APPEND) { mode[0] = 'a'; } else if (flags & LOCK_EX) { /* check to make sure we are dealing with a regular file */ if (php_memnstr(filename, "://", sizeof("://") - 1, filename + filename_len)) { if (strncasecmp(filename, "file://", sizeof("file://") - 1)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Exclusive locks may only be set for regular files"); RETURN_FALSE; } } mode[0] = 'c'; } mode[2] = '\0'; stream = php_stream_open_wrapper_ex(filename, mode, ((flags & PHP_FILE_USE_INCLUDE_PATH) ? USE_PATH : 0) | REPORT_ERRORS, NULL, context); if (stream == NULL) { RETURN_FALSE; } if (flags & LOCK_EX && (!php_stream_supports_lock(stream) || php_stream_lock(stream, LOCK_EX))) { php_stream_close(stream); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Exclusive locks are not supported for this stream"); RETURN_FALSE; } if (mode[0] == 'c') { php_stream_truncate_set_size(stream, 0); } switch (Z_TYPE_P(data)) { case IS_RESOURCE: { size_t len; if (php_stream_copy_to_stream_ex(srcstream, stream, PHP_STREAM_COPY_ALL, &len) != SUCCESS) { numbytes = -1; } else { numbytes = len; } break; } case IS_NULL: case IS_LONG: case IS_DOUBLE: case IS_BOOL: case IS_CONSTANT: convert_to_string_ex(&data); case IS_STRING: if (Z_STRLEN_P(data)) { numbytes = php_stream_write(stream, Z_STRVAL_P(data), Z_STRLEN_P(data)); if (numbytes != Z_STRLEN_P(data)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Only %d of %d bytes written, possibly out of free disk space", numbytes, Z_STRLEN_P(data)); numbytes = -1; } } break; case IS_ARRAY: if (zend_hash_num_elements(Z_ARRVAL_P(data))) { int bytes_written; zval **tmp; HashPosition pos; zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(data), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(data), (void **) &tmp, &pos) == SUCCESS) { if (Z_TYPE_PP(tmp) != IS_STRING) { SEPARATE_ZVAL(tmp); convert_to_string(*tmp); } if (Z_STRLEN_PP(tmp)) { numbytes += Z_STRLEN_PP(tmp); bytes_written = php_stream_write(stream, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp)); if (bytes_written < 0 || bytes_written != Z_STRLEN_PP(tmp)) { if (bytes_written < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to write %d bytes to %s", Z_STRLEN_PP(tmp), filename); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Only %d of %d bytes written, possibly out of free disk space", bytes_written, Z_STRLEN_PP(tmp)); } numbytes = -1; break; } } zend_hash_move_forward_ex(Z_ARRVAL_P(data), &pos); } } break; case IS_OBJECT: if (Z_OBJ_HT_P(data) != NULL) { zval out; if (zend_std_cast_object_tostring(data, &out, IS_STRING TSRMLS_CC) == SUCCESS) { numbytes = php_stream_write(stream, Z_STRVAL(out), Z_STRLEN(out)); if (numbytes != Z_STRLEN(out)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Only %d of %d bytes written, possibly out of free disk space", numbytes, Z_STRLEN(out)); numbytes = -1; } zval_dtor(&out); break; } } default: numbytes = -1; break; } php_stream_close(stream); if (numbytes < 0) { RETURN_FALSE; } RETURN_LONG(numbytes); } /* }}} */ #define PHP_FILE_BUF_SIZE 80 /* {{{ proto array file(string filename [, int flags[, resource context]]) Read entire file into an array */ PHP_FUNCTION(file) { char *filename; int filename_len; char *target_buf=NULL, *p, *s, *e; register int i = 0; int target_len; char eol_marker = '\n'; long flags = 0; zend_bool use_include_path; zend_bool include_new_line; zend_bool skip_blank_lines; php_stream *stream; zval *zcontext = NULL; php_stream_context *context = NULL; /* Parse arguments */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|lr!", &filename, &filename_len, &flags, &zcontext) == FAILURE) { return; } if (flags < 0 || flags > (PHP_FILE_USE_INCLUDE_PATH | PHP_FILE_IGNORE_NEW_LINES | PHP_FILE_SKIP_EMPTY_LINES | PHP_FILE_NO_DEFAULT_CONTEXT)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%ld' flag is not supported", flags); RETURN_FALSE; } use_include_path = flags & PHP_FILE_USE_INCLUDE_PATH; include_new_line = !(flags & PHP_FILE_IGNORE_NEW_LINES); skip_blank_lines = flags & PHP_FILE_SKIP_EMPTY_LINES; context = php_stream_context_from_zval(zcontext, flags & PHP_FILE_NO_DEFAULT_CONTEXT); stream = php_stream_open_wrapper_ex(filename, "rb", (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, context); if (!stream) { RETURN_FALSE; } /* Initialize return array */ array_init(return_value); if ((target_len = php_stream_copy_to_mem(stream, &target_buf, PHP_STREAM_COPY_ALL, 0))) { s = target_buf; e = target_buf + target_len; if (!(p = php_stream_locate_eol(stream, target_buf, target_len TSRMLS_CC))) { p = e; goto parse_eol; } if (stream->flags & PHP_STREAM_FLAG_EOL_MAC) { eol_marker = '\r'; } /* for performance reasons the code is duplicated, so that the if (include_new_line) * will not need to be done for every single line in the file. */ if (include_new_line) { do { p++; parse_eol: add_index_stringl(return_value, i++, estrndup(s, p-s), p-s, 0); s = p; } while ((p = memchr(p, eol_marker, (e-p)))); } else { do { int windows_eol = 0; if (p != target_buf && eol_marker == '\n' && *(p - 1) == '\r') { windows_eol++; } if (skip_blank_lines && !(p-s-windows_eol)) { s = ++p; continue; } add_index_stringl(return_value, i++, estrndup(s, p-s-windows_eol), p-s-windows_eol, 0); s = ++p; } while ((p = memchr(p, eol_marker, (e-p)))); } /* handle any left overs of files without new lines */ if (s != e) { p = e; goto parse_eol; } } if (target_buf) { efree(target_buf); } php_stream_close(stream); } /* }}} */ /* {{{ proto string tempnam(string dir, string prefix) Create a unique filename in a directory */ PHP_FUNCTION(tempnam) { char *dir, *prefix; int dir_len, prefix_len; size_t p_len; char *opened_path; char *p; int fd; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ps", &dir, &dir_len, &prefix, &prefix_len) == FAILURE) { return; } if (php_check_open_basedir(dir TSRMLS_CC)) { RETURN_FALSE; } php_basename(prefix, prefix_len, NULL, 0, &p, &p_len TSRMLS_CC); if (p_len > 64) { p[63] = '\0'; } RETVAL_FALSE; if ((fd = php_open_temporary_fd(dir, p, &opened_path TSRMLS_CC)) >= 0) { close(fd); RETVAL_STRING(opened_path, 0); } efree(p); } /* }}} */ /* {{{ proto resource tmpfile(void) Create a temporary file that will be deleted automatically after use */ PHP_NAMED_FUNCTION(php_if_tmpfile) { php_stream *stream; if (zend_parse_parameters_none() == FAILURE) { return; } stream = php_stream_fopen_tmpfile(); if (stream) { php_stream_to_zval(stream, return_value); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto resource fopen(string filename, string mode [, bool use_include_path [, resource context]]) Open a file or a URL and return a file pointer */ PHP_NAMED_FUNCTION(php_if_fopen) { char *filename, *mode; int filename_len, mode_len; zend_bool use_include_path = 0; zval *zcontext = NULL; php_stream *stream; php_stream_context *context = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ps|br", &filename, &filename_len, &mode, &mode_len, &use_include_path, &zcontext) == FAILURE) { RETURN_FALSE; } context = php_stream_context_from_zval(zcontext, 0); stream = php_stream_open_wrapper_ex(filename, mode, (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, context); if (stream == NULL) { RETURN_FALSE; } php_stream_to_zval(stream, return_value); } /* }}} */ /* {{{ proto bool fclose(resource fp) Close an open file pointer */ PHPAPI PHP_FUNCTION(fclose) { zval *arg1; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &arg1) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); if ((stream->flags & PHP_STREAM_FLAG_NO_FCLOSE) != 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%d is not a valid stream resource", stream->rsrc_id); RETURN_FALSE; } if (!stream->is_persistent) { php_stream_close(stream); } else { php_stream_pclose(stream); } RETURN_TRUE; } /* }}} */ /* {{{ proto resource popen(string command, string mode) Execute a command and open either a read or a write pipe to it */ PHP_FUNCTION(popen) { char *command, *mode; int command_len, mode_len; FILE *fp; php_stream *stream; char *posix_mode; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ps", &command, &command_len, &mode, &mode_len) == FAILURE) { return; } posix_mode = estrndup(mode, mode_len); #ifndef PHP_WIN32 { char *z = memchr(posix_mode, 'b', mode_len); if (z) { memmove(z, z + 1, mode_len - (z - posix_mode)); } } #endif fp = VCWD_POPEN(command, posix_mode); if (!fp) { php_error_docref2(NULL TSRMLS_CC, command, posix_mode, E_WARNING, "%s", strerror(errno)); efree(posix_mode); RETURN_FALSE; } stream = php_stream_fopen_from_pipe(fp, mode); if (stream == NULL) { php_error_docref2(NULL TSRMLS_CC, command, mode, E_WARNING, "%s", strerror(errno)); RETVAL_FALSE; } else { php_stream_to_zval(stream, return_value); } efree(posix_mode); } /* }}} */ /* {{{ proto int pclose(resource fp) Close a file pointer opened by popen() */ PHP_FUNCTION(pclose) { zval *arg1; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &arg1) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); zend_list_delete(stream->rsrc_id); RETURN_LONG(FG(pclose_ret)); } /* }}} */ /* {{{ proto bool feof(resource fp) Test for end-of-file on a file pointer */ PHPAPI PHP_FUNCTION(feof) { zval *arg1; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &arg1) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); if (php_stream_eof(stream)) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto string fgets(resource fp[, int length]) Get a line from file pointer */ PHPAPI PHP_FUNCTION(fgets) { zval *arg1; long len = 1024; char *buf = NULL; int argc = ZEND_NUM_ARGS(); size_t line_len = 0; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|l", &arg1, &len) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); if (argc == 1) { /* ask streams to give us a buffer of an appropriate size */ buf = php_stream_get_line(stream, NULL, 0, &line_len); if (buf == NULL) { goto exit_failed; } } else if (argc > 1) { if (len <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0"); RETURN_FALSE; } buf = ecalloc(len + 1, sizeof(char)); if (php_stream_get_line(stream, buf, len, &line_len) == NULL) { goto exit_failed; } } ZVAL_STRINGL(return_value, buf, line_len, 0); /* resize buffer if it's much larger than the result. * Only needed if the user requested a buffer size. */ if (argc > 1 && Z_STRLEN_P(return_value) < len / 2) { Z_STRVAL_P(return_value) = erealloc(buf, line_len + 1); } return; exit_failed: RETVAL_FALSE; if (buf) { efree(buf); } } /* }}} */ /* {{{ proto string fgetc(resource fp) Get a character from file pointer */ PHPAPI PHP_FUNCTION(fgetc) { zval *arg1; char buf[2]; int result; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &arg1) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); result = php_stream_getc(stream); if (result == EOF) { RETVAL_FALSE; } else { buf[0] = result; buf[1] = '\0'; RETURN_STRINGL(buf, 1, 1); } } /* }}} */ /* {{{ proto string fgetss(resource fp [, int length [, string allowable_tags]]) Get a line from file pointer and strip HTML tags */ PHPAPI PHP_FUNCTION(fgetss) { zval *fd; long bytes = 0; size_t len = 0; size_t actual_len, retval_len; char *buf = NULL, *retval; php_stream *stream; char *allowed_tags=NULL; int allowed_tags_len=0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|ls", &fd, &bytes, &allowed_tags, &allowed_tags_len) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &fd); if (ZEND_NUM_ARGS() >= 2) { if (bytes <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0"); RETURN_FALSE; } len = (size_t) bytes; buf = safe_emalloc(sizeof(char), (len + 1), 0); /*needed because recv doesnt set null char at end*/ memset(buf, 0, len + 1); } if ((retval = php_stream_get_line(stream, buf, len, &actual_len)) == NULL) { if (buf != NULL) { efree(buf); } RETURN_FALSE; } retval_len = php_strip_tags(retval, actual_len, &stream->fgetss_state, allowed_tags, allowed_tags_len); RETURN_STRINGL(retval, retval_len, 0); } /* }}} */ /* {{{ proto mixed fscanf(resource stream, string format [, string ...]) Implements a mostly ANSI compatible fscanf() */ PHP_FUNCTION(fscanf) { int result, format_len, type, argc = 0; zval ***args = NULL; zval *file_handle; char *buf, *format; size_t len; void *what; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs*", &file_handle, &format, &format_len, &args, &argc) == FAILURE) { return; } what = zend_fetch_resource(&file_handle TSRMLS_CC, -1, "File-Handle", &type, 2, php_file_le_stream(), php_file_le_pstream()); /* we can't do a ZEND_VERIFY_RESOURCE(what), otherwise we end up * with a leak if we have an invalid filehandle. This needs changing * if the code behind ZEND_VERIFY_RESOURCE changed. - cc */ if (!what) { if (args) { efree(args); } RETURN_FALSE; } buf = php_stream_get_line((php_stream *) what, NULL, 0, &len); if (buf == NULL) { if (args) { efree(args); } RETURN_FALSE; } result = php_sscanf_internal(buf, format, argc, args, 0, &return_value TSRMLS_CC); if (args) { efree(args); } efree(buf); if (SCAN_ERROR_WRONG_PARAM_COUNT == result) { WRONG_PARAM_COUNT; } } /* }}} */ /* {{{ proto int fwrite(resource fp, string str [, int length]) Binary-safe file write */ PHPAPI PHP_FUNCTION(fwrite) { zval *arg1; char *arg2; int arg2len; int ret; int num_bytes; long arg3 = 0; char *buffer = NULL; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs|l", &arg1, &arg2, &arg2len, &arg3) == FAILURE) { RETURN_FALSE; } if (ZEND_NUM_ARGS() == 2) { num_bytes = arg2len; } else { num_bytes = MAX(0, MIN((int)arg3, arg2len)); } if (!num_bytes) { RETURN_LONG(0); } PHP_STREAM_TO_ZVAL(stream, &arg1); ret = php_stream_write(stream, buffer ? buffer : arg2, num_bytes); if (buffer) { efree(buffer); } RETURN_LONG(ret); } /* }}} */ /* {{{ proto bool fflush(resource fp) Flushes output */ PHPAPI PHP_FUNCTION(fflush) { zval *arg1; int ret; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &arg1) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); ret = php_stream_flush(stream); if (ret) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool rewind(resource fp) Rewind the position of a file pointer */ PHPAPI PHP_FUNCTION(rewind) { zval *arg1; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &arg1) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); if (-1 == php_stream_rewind(stream)) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto int ftell(resource fp) Get file pointer's read/write position */ PHPAPI PHP_FUNCTION(ftell) { zval *arg1; long ret; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &arg1) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); ret = php_stream_tell(stream); if (ret == -1) { RETURN_FALSE; } RETURN_LONG(ret); } /* }}} */ /* {{{ proto int fseek(resource fp, int offset [, int whence]) Seek on a file pointer */ PHPAPI PHP_FUNCTION(fseek) { zval *arg1; long arg2, whence = SEEK_SET; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl|l", &arg1, &arg2, &whence) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); RETURN_LONG(php_stream_seek(stream, arg2, whence)); } /* }}} */ /* {{{ php_mkdir */ /* DEPRECATED APIs: Use php_stream_mkdir() instead */ PHPAPI int php_mkdir_ex(char *dir, long mode, int options TSRMLS_DC) { int ret; if (php_check_open_basedir(dir TSRMLS_CC)) { return -1; } if ((ret = VCWD_MKDIR(dir, (mode_t)mode)) < 0 && (options & REPORT_ERRORS)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", strerror(errno)); } return ret; } PHPAPI int php_mkdir(char *dir, long mode TSRMLS_DC) { return php_mkdir_ex(dir, mode, REPORT_ERRORS TSRMLS_CC); } /* }}} */ /* {{{ proto bool mkdir(string pathname [, int mode [, bool recursive [, resource context]]]) Create a directory */ PHP_FUNCTION(mkdir) { char *dir; int dir_len; zval *zcontext = NULL; long mode = 0777; zend_bool recursive = 0; php_stream_context *context; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|lbr", &dir, &dir_len, &mode, &recursive, &zcontext) == FAILURE) { RETURN_FALSE; } context = php_stream_context_from_zval(zcontext, 0); RETURN_BOOL(php_stream_mkdir(dir, mode, (recursive ? PHP_STREAM_MKDIR_RECURSIVE : 0) | REPORT_ERRORS, context)); } /* }}} */ /* {{{ proto bool rmdir(string dirname[, resource context]) Remove a directory */ PHP_FUNCTION(rmdir) { char *dir; int dir_len; zval *zcontext = NULL; php_stream_context *context; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|r", &dir, &dir_len, &zcontext) == FAILURE) { RETURN_FALSE; } context = php_stream_context_from_zval(zcontext, 0); RETURN_BOOL(php_stream_rmdir(dir, REPORT_ERRORS, context)); } /* }}} */ /* {{{ proto int readfile(string filename [, bool use_include_path[, resource context]]) Output a file or a URL */ PHP_FUNCTION(readfile) { char *filename; int filename_len; int size = 0; zend_bool use_include_path = 0; zval *zcontext = NULL; php_stream *stream; php_stream_context *context = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|br!", &filename, &filename_len, &use_include_path, &zcontext) == FAILURE) { RETURN_FALSE; } context = php_stream_context_from_zval(zcontext, 0); stream = php_stream_open_wrapper_ex(filename, "rb", (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, context); if (stream) { size = php_stream_passthru(stream); php_stream_close(stream); RETURN_LONG(size); } RETURN_FALSE; } /* }}} */ /* {{{ proto int umask([int mask]) Return or change the umask */ PHP_FUNCTION(umask) { long arg1 = 0; int oldumask; oldumask = umask(077); if (BG(umask) == -1) { BG(umask) = oldumask; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &arg1) == FAILURE) { RETURN_FALSE; } if (ZEND_NUM_ARGS() == 0) { umask(oldumask); } else { umask(arg1); } RETURN_LONG(oldumask); } /* }}} */ /* {{{ proto int fpassthru(resource fp) Output all remaining data from a file pointer */ PHPAPI PHP_FUNCTION(fpassthru) { zval *arg1; int size; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &arg1) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); size = php_stream_passthru(stream); RETURN_LONG(size); } /* }}} */ /* {{{ proto bool rename(string old_name, string new_name[, resource context]) Rename a file */ PHP_FUNCTION(rename) { char *old_name, *new_name; int old_name_len, new_name_len; zval *zcontext = NULL; php_stream_wrapper *wrapper; php_stream_context *context; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "pp|r", &old_name, &old_name_len, &new_name, &new_name_len, &zcontext) == FAILURE) { RETURN_FALSE; } wrapper = php_stream_locate_url_wrapper(old_name, NULL, 0 TSRMLS_CC); if (!wrapper || !wrapper->wops) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to locate stream wrapper"); RETURN_FALSE; } if (!wrapper->wops->rename) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s wrapper does not support renaming", wrapper->wops->label ? wrapper->wops->label : "Source"); RETURN_FALSE; } if (wrapper != php_stream_locate_url_wrapper(new_name, NULL, 0 TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot rename a file across wrapper types"); RETURN_FALSE; } context = php_stream_context_from_zval(zcontext, 0); RETURN_BOOL(wrapper->wops->rename(wrapper, old_name, new_name, 0, context TSRMLS_CC)); } /* }}} */ /* {{{ proto bool unlink(string filename[, context context]) Delete a file */ PHP_FUNCTION(unlink) { char *filename; int filename_len; php_stream_wrapper *wrapper; zval *zcontext = NULL; php_stream_context *context = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|r", &filename, &filename_len, &zcontext) == FAILURE) { RETURN_FALSE; } context = php_stream_context_from_zval(zcontext, 0); wrapper = php_stream_locate_url_wrapper(filename, NULL, 0 TSRMLS_CC); if (!wrapper || !wrapper->wops) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to locate stream wrapper"); RETURN_FALSE; } if (!wrapper->wops->unlink) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s does not allow unlinking", wrapper->wops->label ? wrapper->wops->label : "Wrapper"); RETURN_FALSE; } RETURN_BOOL(wrapper->wops->unlink(wrapper, filename, REPORT_ERRORS, context TSRMLS_CC)); } /* }}} */ /* {{{ proto bool ftruncate(resource fp, int size) Truncate file to 'size' length */ PHP_NAMED_FUNCTION(php_if_ftruncate) { zval *fp; long size; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &fp, &size) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &fp); if (!php_stream_truncate_supported(stream)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can't truncate this stream!"); RETURN_FALSE; } RETURN_BOOL(0 == php_stream_truncate_set_size(stream, size)); } /* }}} */ /* {{{ proto array fstat(resource fp) Stat() on a filehandle */ PHP_NAMED_FUNCTION(php_if_fstat) { zval *fp; zval *stat_dev, *stat_ino, *stat_mode, *stat_nlink, *stat_uid, *stat_gid, *stat_rdev, *stat_size, *stat_atime, *stat_mtime, *stat_ctime, *stat_blksize, *stat_blocks; php_stream *stream; php_stream_statbuf stat_ssb; char *stat_sb_names[13] = { "dev", "ino", "mode", "nlink", "uid", "gid", "rdev", "size", "atime", "mtime", "ctime", "blksize", "blocks" }; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &fp) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &fp); if (php_stream_stat(stream, &stat_ssb)) { RETURN_FALSE; } array_init(return_value); MAKE_LONG_ZVAL_INCREF(stat_dev, stat_ssb.sb.st_dev); MAKE_LONG_ZVAL_INCREF(stat_ino, stat_ssb.sb.st_ino); MAKE_LONG_ZVAL_INCREF(stat_mode, stat_ssb.sb.st_mode); MAKE_LONG_ZVAL_INCREF(stat_nlink, stat_ssb.sb.st_nlink); MAKE_LONG_ZVAL_INCREF(stat_uid, stat_ssb.sb.st_uid); MAKE_LONG_ZVAL_INCREF(stat_gid, stat_ssb.sb.st_gid); #ifdef HAVE_ST_RDEV MAKE_LONG_ZVAL_INCREF(stat_rdev, stat_ssb.sb.st_rdev); #else MAKE_LONG_ZVAL_INCREF(stat_rdev, -1); #endif MAKE_LONG_ZVAL_INCREF(stat_size, stat_ssb.sb.st_size); MAKE_LONG_ZVAL_INCREF(stat_atime, stat_ssb.sb.st_atime); MAKE_LONG_ZVAL_INCREF(stat_mtime, stat_ssb.sb.st_mtime); MAKE_LONG_ZVAL_INCREF(stat_ctime, stat_ssb.sb.st_ctime); #ifdef HAVE_ST_BLKSIZE MAKE_LONG_ZVAL_INCREF(stat_blksize, stat_ssb.sb.st_blksize); #else MAKE_LONG_ZVAL_INCREF(stat_blksize,-1); #endif #ifdef HAVE_ST_BLOCKS MAKE_LONG_ZVAL_INCREF(stat_blocks, stat_ssb.sb.st_blocks); #else MAKE_LONG_ZVAL_INCREF(stat_blocks,-1); #endif /* Store numeric indexes in propper order */ zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_dev, sizeof(zval *), NULL); zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_ino, sizeof(zval *), NULL); zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_mode, sizeof(zval *), NULL); zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_nlink, sizeof(zval *), NULL); zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_uid, sizeof(zval *), NULL); zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_gid, sizeof(zval *), NULL); zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_rdev, sizeof(zval *), NULL); zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_size, sizeof(zval *), NULL); zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_atime, sizeof(zval *), NULL); zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_mtime, sizeof(zval *), NULL); zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_ctime, sizeof(zval *), NULL); zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_blksize, sizeof(zval *), NULL); zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_blocks, sizeof(zval *), NULL); /* Store string indexes referencing the same zval*/ zend_hash_update(HASH_OF(return_value), stat_sb_names[0], strlen(stat_sb_names[0])+1, (void *)&stat_dev, sizeof(zval *), NULL); zend_hash_update(HASH_OF(return_value), stat_sb_names[1], strlen(stat_sb_names[1])+1, (void *)&stat_ino, sizeof(zval *), NULL); zend_hash_update(HASH_OF(return_value), stat_sb_names[2], strlen(stat_sb_names[2])+1, (void *)&stat_mode, sizeof(zval *), NULL); zend_hash_update(HASH_OF(return_value), stat_sb_names[3], strlen(stat_sb_names[3])+1, (void *)&stat_nlink, sizeof(zval *), NULL); zend_hash_update(HASH_OF(return_value), stat_sb_names[4], strlen(stat_sb_names[4])+1, (void *)&stat_uid, sizeof(zval *), NULL); zend_hash_update(HASH_OF(return_value), stat_sb_names[5], strlen(stat_sb_names[5])+1, (void *)&stat_gid, sizeof(zval *), NULL); zend_hash_update(HASH_OF(return_value), stat_sb_names[6], strlen(stat_sb_names[6])+1, (void *)&stat_rdev, sizeof(zval *), NULL); zend_hash_update(HASH_OF(return_value), stat_sb_names[7], strlen(stat_sb_names[7])+1, (void *)&stat_size, sizeof(zval *), NULL); zend_hash_update(HASH_OF(return_value), stat_sb_names[8], strlen(stat_sb_names[8])+1, (void *)&stat_atime, sizeof(zval *), NULL); zend_hash_update(HASH_OF(return_value), stat_sb_names[9], strlen(stat_sb_names[9])+1, (void *)&stat_mtime, sizeof(zval *), NULL); zend_hash_update(HASH_OF(return_value), stat_sb_names[10], strlen(stat_sb_names[10])+1, (void *)&stat_ctime, sizeof(zval *), NULL); zend_hash_update(HASH_OF(return_value), stat_sb_names[11], strlen(stat_sb_names[11])+1, (void *)&stat_blksize, sizeof(zval *), NULL); zend_hash_update(HASH_OF(return_value), stat_sb_names[12], strlen(stat_sb_names[12])+1, (void *)&stat_blocks, sizeof(zval *), NULL); } /* }}} */ /* {{{ proto bool copy(string source_file, string destination_file [, resource context]) Copy a file */ PHP_FUNCTION(copy) { char *source, *target; int source_len, target_len; zval *zcontext = NULL; php_stream_context *context; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "pp|r", &source, &source_len, &target, &target_len, &zcontext) == FAILURE) { return; } if (php_check_open_basedir(source TSRMLS_CC)) { RETURN_FALSE; } context = php_stream_context_from_zval(zcontext, 0); if (php_copy_file_ctx(source, target, 0, context TSRMLS_CC) == SUCCESS) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ php_copy_file */ PHPAPI int php_copy_file(char *src, char *dest TSRMLS_DC) { return php_copy_file_ctx(src, dest, 0, NULL TSRMLS_CC); } /* }}} */ /* {{{ php_copy_file_ex */ PHPAPI int php_copy_file_ex(char *src, char *dest, int src_flg TSRMLS_DC) { return php_copy_file_ctx(src, dest, 0, NULL TSRMLS_CC); } /* }}} */ /* {{{ php_copy_file_ctx */ PHPAPI int php_copy_file_ctx(char *src, char *dest, int src_flg, php_stream_context *ctx TSRMLS_DC) { php_stream *srcstream = NULL, *deststream = NULL; int ret = FAILURE; php_stream_statbuf src_s, dest_s; switch (php_stream_stat_path_ex(src, 0, &src_s, ctx)) { case -1: /* non-statable stream */ goto safe_to_copy; break; case 0: break; default: /* failed to stat file, does not exist? */ return ret; } if (S_ISDIR(src_s.sb.st_mode)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The first argument to copy() function cannot be a directory"); return FAILURE; } switch (php_stream_stat_path_ex(dest, PHP_STREAM_URL_STAT_QUIET, &dest_s, ctx)) { case -1: /* non-statable stream */ goto safe_to_copy; break; case 0: break; default: /* failed to stat file, does not exist? */ return ret; } if (S_ISDIR(dest_s.sb.st_mode)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The second argument to copy() function cannot be a directory"); return FAILURE; } if (!src_s.sb.st_ino || !dest_s.sb.st_ino) { goto no_stat; } if (src_s.sb.st_ino == dest_s.sb.st_ino && src_s.sb.st_dev == dest_s.sb.st_dev) { return ret; } else { goto safe_to_copy; } no_stat: { char *sp, *dp; int res; if ((sp = expand_filepath(src, NULL TSRMLS_CC)) == NULL) { return ret; } if ((dp = expand_filepath(dest, NULL TSRMLS_CC)) == NULL) { efree(sp); goto safe_to_copy; } res = #ifndef PHP_WIN32 !strcmp(sp, dp); #else !strcasecmp(sp, dp); #endif efree(sp); efree(dp); if (res) { return ret; } } safe_to_copy: srcstream = php_stream_open_wrapper_ex(src, "rb", src_flg | REPORT_ERRORS, NULL, ctx); if (!srcstream) { return ret; } deststream = php_stream_open_wrapper_ex(dest, "wb", REPORT_ERRORS, NULL, ctx); if (srcstream && deststream) { ret = php_stream_copy_to_stream_ex(srcstream, deststream, PHP_STREAM_COPY_ALL, NULL); } if (srcstream) { php_stream_close(srcstream); } if (deststream) { php_stream_close(deststream); } return ret; } /* }}} */ /* {{{ proto string fread(resource fp, int length) Binary-safe file read */ PHPAPI PHP_FUNCTION(fread) { zval *arg1; long len; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &arg1, &len) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); if (len <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0"); RETURN_FALSE; } Z_STRVAL_P(return_value) = emalloc(len + 1); Z_STRLEN_P(return_value) = php_stream_read(stream, Z_STRVAL_P(return_value), len); /* needed because recv/read/gzread doesnt put a null at the end*/ Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0; Z_TYPE_P(return_value) = IS_STRING; } /* }}} */ static const char *php_fgetcsv_lookup_trailing_spaces(const char *ptr, size_t len, const char delimiter TSRMLS_DC) /* {{{ */ { int inc_len; unsigned char last_chars[2] = { 0, 0 }; while (len > 0) { inc_len = (*ptr == '\0' ? 1: php_mblen(ptr, len)); switch (inc_len) { case -2: case -1: inc_len = 1; php_ignore_value(php_mblen(NULL, 0)); break; case 0: goto quit_loop; case 1: default: last_chars[0] = last_chars[1]; last_chars[1] = *ptr; break; } ptr += inc_len; len -= inc_len; } quit_loop: switch (last_chars[1]) { case '\n': if (last_chars[0] == '\r') { return ptr - 2; } /* break is omitted intentionally */ case '\r': return ptr - 1; } return ptr; } /* }}} */ #define FPUTCSV_FLD_CHK(c) memchr(Z_STRVAL(field), c, Z_STRLEN(field)) /* {{{ proto int fputcsv(resource fp, array fields [, string delimiter [, string enclosure]]) Format line as CSV and write to file pointer */ PHP_FUNCTION(fputcsv) { char delimiter = ','; /* allow this to be set as parameter */ char enclosure = '"'; /* allow this to be set as parameter */ const char escape_char = '\\'; php_stream *stream; zval *fp = NULL, *fields = NULL; int ret; char *delimiter_str = NULL, *enclosure_str = NULL; int delimiter_str_len = 0, enclosure_str_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra|ss", &fp, &fields, &delimiter_str, &delimiter_str_len, &enclosure_str, &enclosure_str_len) == FAILURE) { return; } if (delimiter_str != NULL) { /* Make sure that there is at least one character in string */ if (delimiter_str_len < 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } else if (delimiter_str_len > 1) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "delimiter must be a single character"); } /* use first character from string */ delimiter = *delimiter_str; } if (enclosure_str != NULL) { if (enclosure_str_len < 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } else if (enclosure_str_len > 1) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "enclosure must be a single character"); } /* use first character from string */ enclosure = *enclosure_str; } PHP_STREAM_TO_ZVAL(stream, &fp); ret = php_fputcsv(stream, fields, delimiter, enclosure, escape_char TSRMLS_CC); RETURN_LONG(ret); } /* }}} */ /* {{{ PHPAPI int php_fputcsv(php_stream *stream, zval *fields, char delimiter, char enclosure, char escape_char TSRMLS_DC) */ PHPAPI int php_fputcsv(php_stream *stream, zval *fields, char delimiter, char enclosure, char escape_char TSRMLS_DC) { int count, i = 0, ret; zval **field_tmp = NULL, field; smart_str csvline = {0}; HashPosition pos; count = zend_hash_num_elements(Z_ARRVAL_P(fields)); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(fields), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(fields), (void **) &field_tmp, &pos) == SUCCESS) { field = **field_tmp; if (Z_TYPE_PP(field_tmp) != IS_STRING) { zval_copy_ctor(&field); convert_to_string(&field); } /* enclose a field that contains a delimiter, an enclosure character, or a newline */ if (FPUTCSV_FLD_CHK(delimiter) || FPUTCSV_FLD_CHK(enclosure) || FPUTCSV_FLD_CHK(escape_char) || FPUTCSV_FLD_CHK('\n') || FPUTCSV_FLD_CHK('\r') || FPUTCSV_FLD_CHK('\t') || FPUTCSV_FLD_CHK(' ') ) { char *ch = Z_STRVAL(field); char *end = ch + Z_STRLEN(field); int escaped = 0; smart_str_appendc(&csvline, enclosure); while (ch < end) { if (*ch == escape_char) { escaped = 1; } else if (!escaped && *ch == enclosure) { smart_str_appendc(&csvline, enclosure); } else { escaped = 0; } smart_str_appendc(&csvline, *ch); ch++; } smart_str_appendc(&csvline, enclosure); } else { smart_str_appendl(&csvline, Z_STRVAL(field), Z_STRLEN(field)); } if (++i != count) { smart_str_appendl(&csvline, &delimiter, 1); } zend_hash_move_forward_ex(Z_ARRVAL_P(fields), &pos); if (Z_TYPE_PP(field_tmp) != IS_STRING) { zval_dtor(&field); } } smart_str_appendc(&csvline, '\n'); smart_str_0(&csvline); ret = php_stream_write(stream, csvline.c, csvline.len); smart_str_free(&csvline); return ret; } /* }}} */ /* {{{ proto array fgetcsv(resource fp [,int length [, string delimiter [, string enclosure [, string escape]]]]) Get line from file pointer and parse for CSV fields */ PHP_FUNCTION(fgetcsv) { char delimiter = ','; /* allow this to be set as parameter */ char enclosure = '"'; /* allow this to be set as parameter */ char escape = '\\'; /* first section exactly as php_fgetss */ long len = 0; size_t buf_len; char *buf; php_stream *stream; { zval *fd, **len_zv = NULL; char *delimiter_str = NULL; int delimiter_str_len = 0; char *enclosure_str = NULL; int enclosure_str_len = 0; char *escape_str = NULL; int escape_str_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|Zsss", &fd, &len_zv, &delimiter_str, &delimiter_str_len, &enclosure_str, &enclosure_str_len, &escape_str, &escape_str_len) == FAILURE ) { return; } if (delimiter_str != NULL) { /* Make sure that there is at least one character in string */ if (delimiter_str_len < 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } else if (delimiter_str_len > 1) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "delimiter must be a single character"); } /* use first character from string */ delimiter = delimiter_str[0]; } if (enclosure_str != NULL) { if (enclosure_str_len < 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } else if (enclosure_str_len > 1) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "enclosure must be a single character"); } /* use first character from string */ enclosure = enclosure_str[0]; } if (escape_str != NULL) { if (escape_str_len < 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be character"); RETURN_FALSE; } else if (escape_str_len > 1) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "escape must be a single character"); } escape = escape_str[0]; } if (len_zv != NULL && Z_TYPE_PP(len_zv) != IS_NULL) { convert_to_long_ex(len_zv); len = Z_LVAL_PP(len_zv); if (len < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter may not be negative"); RETURN_FALSE; } else if (len == 0) { len = -1; } } else { len = -1; } PHP_STREAM_TO_ZVAL(stream, &fd); } if (len < 0) { if ((buf = php_stream_get_line(stream, NULL, 0, &buf_len)) == NULL) { RETURN_FALSE; } } else { buf = emalloc(len + 1); if (php_stream_get_line(stream, buf, len + 1, &buf_len) == NULL) { efree(buf); RETURN_FALSE; } } php_fgetcsv(stream, delimiter, enclosure, escape, buf_len, buf, return_value TSRMLS_CC); } /* }}} */ PHPAPI void php_fgetcsv(php_stream *stream, char delimiter, char enclosure, char escape_char, size_t buf_len, char *buf, zval *return_value TSRMLS_DC) /* {{{ */ { char *temp, *tptr, *bptr, *line_end, *limit; size_t temp_len, line_end_len; int inc_len; zend_bool first_field = 1; /* initialize internal state */ php_ignore_value(php_mblen(NULL, 0)); /* Now into new section that parses buf for delimiter/enclosure fields */ /* Strip trailing space from buf, saving end of line in case required for enclosure field */ bptr = buf; tptr = (char *)php_fgetcsv_lookup_trailing_spaces(buf, buf_len, delimiter TSRMLS_CC); line_end_len = buf_len - (size_t)(tptr - buf); line_end = limit = tptr; /* reserve workspace for building each individual field */ temp_len = buf_len; temp = emalloc(temp_len + line_end_len + 1); /* Initialize return array */ array_init(return_value); /* Main loop to read CSV fields */ /* NB this routine will return a single null entry for a blank line */ do { char *comp_end, *hunk_begin; tptr = temp; inc_len = (bptr < limit ? (*bptr == '\0' ? 1: php_mblen(bptr, limit - bptr)): 0); if (inc_len == 1) { char *tmp = bptr; while ((*tmp != delimiter) && isspace((int)*(unsigned char *)tmp)) { tmp++; } if (*tmp == enclosure) { bptr = tmp; } } if (first_field && bptr == line_end) { add_next_index_null(return_value); break; } first_field = 0; /* 2. Read field, leaving bptr pointing at start of next field */ if (inc_len != 0 && *bptr == enclosure) { int state = 0; bptr++; /* move on to first character in field */ hunk_begin = bptr; /* 2A. handle enclosure delimited field */ for (;;) { switch (inc_len) { case 0: switch (state) { case 2: memcpy(tptr, hunk_begin, bptr - hunk_begin - 1); tptr += (bptr - hunk_begin - 1); hunk_begin = bptr; goto quit_loop_2; case 1: memcpy(tptr, hunk_begin, bptr - hunk_begin); tptr += (bptr - hunk_begin); hunk_begin = bptr; /* break is omitted intentionally */ case 0: { char *new_buf; size_t new_len; char *new_temp; if (hunk_begin != line_end) { memcpy(tptr, hunk_begin, bptr - hunk_begin); tptr += (bptr - hunk_begin); hunk_begin = bptr; } /* add the embedded line end to the field */ memcpy(tptr, line_end, line_end_len); tptr += line_end_len; if (stream == NULL) { goto quit_loop_2; } else if ((new_buf = php_stream_get_line(stream, NULL, 0, &new_len)) == NULL) { /* we've got an unterminated enclosure, * assign all the data from the start of * the enclosure to end of data to the * last element */ if ((size_t)temp_len > (size_t)(limit - buf)) { goto quit_loop_2; } zval_dtor(return_value); RETVAL_FALSE; goto out; } temp_len += new_len; new_temp = erealloc(temp, temp_len); tptr = new_temp + (size_t)(tptr - temp); temp = new_temp; efree(buf); buf_len = new_len; bptr = buf = new_buf; hunk_begin = buf; line_end = limit = (char *)php_fgetcsv_lookup_trailing_spaces(buf, buf_len, delimiter TSRMLS_CC); line_end_len = buf_len - (size_t)(limit - buf); state = 0; } break; } break; case -2: case -1: php_ignore_value(php_mblen(NULL, 0)); /* break is omitted intentionally */ case 1: /* we need to determine if the enclosure is * 'real' or is it escaped */ switch (state) { case 1: /* escaped */ bptr++; state = 0; break; case 2: /* embedded enclosure ? let's check it */ if (*bptr != enclosure) { /* real enclosure */ memcpy(tptr, hunk_begin, bptr - hunk_begin - 1); tptr += (bptr - hunk_begin - 1); hunk_begin = bptr; goto quit_loop_2; } memcpy(tptr, hunk_begin, bptr - hunk_begin); tptr += (bptr - hunk_begin); bptr++; hunk_begin = bptr; state = 0; break; default: if (*bptr == enclosure) { state = 2; } else if (*bptr == escape_char) { state = 1; } bptr++; break; } break; default: switch (state) { case 2: /* real enclosure */ memcpy(tptr, hunk_begin, bptr - hunk_begin - 1); tptr += (bptr - hunk_begin - 1); hunk_begin = bptr; goto quit_loop_2; case 1: bptr += inc_len; memcpy(tptr, hunk_begin, bptr - hunk_begin); tptr += (bptr - hunk_begin); hunk_begin = bptr; break; default: bptr += inc_len; break; } break; } inc_len = (bptr < limit ? (*bptr == '\0' ? 1: php_mblen(bptr, limit - bptr)): 0); } quit_loop_2: /* look up for a delimiter */ for (;;) { switch (inc_len) { case 0: goto quit_loop_3; case -2: case -1: inc_len = 1; php_ignore_value(php_mblen(NULL, 0)); /* break is omitted intentionally */ case 1: if (*bptr == delimiter) { goto quit_loop_3; } break; default: break; } bptr += inc_len; inc_len = (bptr < limit ? (*bptr == '\0' ? 1: php_mblen(bptr, limit - bptr)): 0); } quit_loop_3: memcpy(tptr, hunk_begin, bptr - hunk_begin); tptr += (bptr - hunk_begin); bptr += inc_len; comp_end = tptr; } else { /* 2B. Handle non-enclosure field */ hunk_begin = bptr; for (;;) { switch (inc_len) { case 0: goto quit_loop_4; case -2: case -1: inc_len = 1; php_ignore_value(php_mblen(NULL, 0)); /* break is omitted intentionally */ case 1: if (*bptr == delimiter) { goto quit_loop_4; } break; default: break; } bptr += inc_len; inc_len = (bptr < limit ? (*bptr == '\0' ? 1: php_mblen(bptr, limit - bptr)): 0); } quit_loop_4: memcpy(tptr, hunk_begin, bptr - hunk_begin); tptr += (bptr - hunk_begin); comp_end = (char *)php_fgetcsv_lookup_trailing_spaces(temp, tptr - temp, delimiter TSRMLS_CC); if (*bptr == delimiter) { bptr++; } } /* 3. Now pass our field back to php */ *comp_end = '\0'; add_next_index_stringl(return_value, temp, comp_end - temp, 1); } while (inc_len > 0); out: efree(temp); if (stream) { efree(buf); } } /* }}} */ #if (!defined(__BEOS__) && !defined(NETWARE) && HAVE_REALPATH) || defined(ZTS) /* {{{ proto string realpath(string path) Return the resolved path */ PHP_FUNCTION(realpath) { char *filename; int filename_len; char resolved_path_buff[MAXPATHLEN]; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &filename, &filename_len) == FAILURE) { return; } if (VCWD_REALPATH(filename, resolved_path_buff)) { if (php_check_open_basedir(resolved_path_buff TSRMLS_CC)) { RETURN_FALSE; } #ifdef ZTS if (VCWD_ACCESS(resolved_path_buff, F_OK)) { RETURN_FALSE; } #endif RETURN_STRING(resolved_path_buff, 1); } else { RETURN_FALSE; } } /* }}} */ #endif /* See http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.2 */ #define PHP_META_HTML401_CHARS "-_.:" /* {{{ php_next_meta_token Tokenizes an HTML file for get_meta_tags */ php_meta_tags_token php_next_meta_token(php_meta_tags_data *md TSRMLS_DC) { int ch = 0, compliment; char buff[META_DEF_BUFSIZE + 1]; memset((void *)buff, 0, META_DEF_BUFSIZE + 1); while (md->ulc || (!php_stream_eof(md->stream) && (ch = php_stream_getc(md->stream)))) { if (php_stream_eof(md->stream)) { break; } if (md->ulc) { ch = md->lc; md->ulc = 0; } switch (ch) { case '<': return TOK_OPENTAG; break; case '>': return TOK_CLOSETAG; break; case '=': return TOK_EQUAL; break; case '/': return TOK_SLASH; break; case '\'': case '"': compliment = ch; md->token_len = 0; while (!php_stream_eof(md->stream) && (ch = php_stream_getc(md->stream)) && ch != compliment && ch != '<' && ch != '>') { buff[(md->token_len)++] = ch; if (md->token_len == META_DEF_BUFSIZE) { break; } } if (ch == '<' || ch == '>') { /* Was just an apostrohpe */ md->ulc = 1; md->lc = ch; } /* We don't need to alloc unless we are in a meta tag */ if (md->in_meta) { md->token_data = (char *) emalloc(md->token_len + 1); memcpy(md->token_data, buff, md->token_len+1); } return TOK_STRING; break; case '\n': case '\r': case '\t': break; case ' ': return TOK_SPACE; break; default: if (isalnum(ch)) { md->token_len = 0; buff[(md->token_len)++] = ch; while (!php_stream_eof(md->stream) && (ch = php_stream_getc(md->stream)) && (isalnum(ch) || strchr(PHP_META_HTML401_CHARS, ch))) { buff[(md->token_len)++] = ch; if (md->token_len == META_DEF_BUFSIZE) { break; } } /* This is ugly, but we have to replace ungetc */ if (!isalpha(ch) && ch != '-') { md->ulc = 1; md->lc = ch; } md->token_data = (char *) emalloc(md->token_len + 1); memcpy(md->token_data, buff, md->token_len+1); return TOK_ID; } else { return TOK_OTHER; } break; } } return TOK_EOF; } /* }}} */ #ifdef HAVE_FNMATCH /* {{{ proto bool fnmatch(string pattern, string filename [, int flags]) Match filename against pattern */ PHP_FUNCTION(fnmatch) { char *pattern, *filename; int pattern_len, filename_len; long flags = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "pp|l", &pattern, &pattern_len, &filename, &filename_len, &flags) == FAILURE) { return; } if (filename_len >= MAXPATHLEN) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Filename exceeds the maximum allowed length of %d characters", MAXPATHLEN); RETURN_FALSE; } if (pattern_len >= MAXPATHLEN) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Pattern exceeds the maximum allowed length of %d characters", MAXPATHLEN); RETURN_FALSE; } RETURN_BOOL( ! fnmatch( pattern, filename, flags )); } /* }}} */ #endif /* {{{ proto string sys_get_temp_dir() Returns directory path used for temporary files */ PHP_FUNCTION(sys_get_temp_dir) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_STRING((char *)php_get_temporary_directory(), 1); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Rasmus Lerdorf <[email protected]> | | Stig Bakken <[email protected]> | | Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | PHP 4.0 patches by Thies C. Arntzen ([email protected]) | | PHP streams by Wez Furlong ([email protected]) | +----------------------------------------------------------------------+ */ /* $Id$ */ /* Synced with php 3.0 revision 1.218 1999-06-16 [ssb] */ /* {{{ includes */ #include "php.h" #include "php_globals.h" #include "ext/standard/flock_compat.h" #include "ext/standard/exec.h" #include "ext/standard/php_filestat.h" #include "php_open_temporary_file.h" #include "ext/standard/basic_functions.h" #include "php_ini.h" #include "php_smart_str.h" #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #ifdef PHP_WIN32 # include <io.h> # define O_RDONLY _O_RDONLY # include "win32/param.h" # include "win32/winutil.h" # include "win32/fnmatch.h" #else # if HAVE_SYS_PARAM_H # include <sys/param.h> # endif # if HAVE_SYS_SELECT_H # include <sys/select.h> # endif # if defined(NETWARE) && defined(USE_WINSOCK) # include <novsock2.h> # else # include <sys/socket.h> # include <netinet/in.h> # include <netdb.h> # endif # if HAVE_ARPA_INET_H # include <arpa/inet.h> # endif #endif #include "ext/standard/head.h" #include "php_string.h" #include "file.h" #if HAVE_PWD_H # ifdef PHP_WIN32 # include "win32/pwd.h" # else # include <pwd.h> # endif #endif #ifdef HAVE_SYS_TIME_H # include <sys/time.h> #endif #include "fsock.h" #include "fopen_wrappers.h" #include "streamsfuncs.h" #include "php_globals.h" #ifdef HAVE_SYS_FILE_H # include <sys/file.h> #endif #if MISSING_FCLOSE_DECL extern int fclose(FILE *); #endif #ifdef HAVE_SYS_MMAN_H # include <sys/mman.h> #endif #include "scanf.h" #include "zend_API.h" #ifdef ZTS int file_globals_id; #else php_file_globals file_globals; #endif #if defined(HAVE_FNMATCH) && !defined(PHP_WIN32) # ifndef _GNU_SOURCE # define _GNU_SOURCE # endif # include <fnmatch.h> #endif #ifdef HAVE_WCHAR_H # include <wchar.h> #endif #ifndef S_ISDIR # define S_ISDIR(mode) (((mode)&S_IFMT) == S_IFDIR) #endif /* }}} */ #define PHP_STREAM_TO_ZVAL(stream, arg) \ php_stream_from_zval_no_verify(stream, arg); \ if (stream == NULL) { \ RETURN_FALSE; \ } /* {{{ ZTS-stuff / Globals / Prototypes */ /* sharing globals is *evil* */ static int le_stream_context = FAILURE; PHPAPI int php_le_stream_context(TSRMLS_D) { return le_stream_context; } /* }}} */ /* {{{ Module-Stuff */ static ZEND_RSRC_DTOR_FUNC(file_context_dtor) { php_stream_context *context = (php_stream_context*)rsrc->ptr; if (context->options) { zval_ptr_dtor(&context->options); context->options = NULL; } php_stream_context_free(context); } static void file_globals_ctor(php_file_globals *file_globals_p TSRMLS_DC) { FG(pclose_ret) = 0; FG(user_stream_current_filename) = NULL; FG(def_chunk_size) = PHP_SOCK_CHUNK_SIZE; } static void file_globals_dtor(php_file_globals *file_globals_p TSRMLS_DC) { } PHP_INI_BEGIN() STD_PHP_INI_ENTRY("user_agent", NULL, PHP_INI_ALL, OnUpdateString, user_agent, php_file_globals, file_globals) STD_PHP_INI_ENTRY("from", NULL, PHP_INI_ALL, OnUpdateString, from_address, php_file_globals, file_globals) STD_PHP_INI_ENTRY("default_socket_timeout", "60", PHP_INI_ALL, OnUpdateLong, default_socket_timeout, php_file_globals, file_globals) STD_PHP_INI_ENTRY("auto_detect_line_endings", "0", PHP_INI_ALL, OnUpdateLong, auto_detect_line_endings, php_file_globals, file_globals) PHP_INI_END() PHP_MINIT_FUNCTION(file) { le_stream_context = zend_register_list_destructors_ex(file_context_dtor, NULL, "stream-context", module_number); #ifdef ZTS ts_allocate_id(&file_globals_id, sizeof(php_file_globals), (ts_allocate_ctor) file_globals_ctor, (ts_allocate_dtor) file_globals_dtor); #else file_globals_ctor(&file_globals TSRMLS_CC); #endif REGISTER_INI_ENTRIES(); REGISTER_LONG_CONSTANT("SEEK_SET", SEEK_SET, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SEEK_CUR", SEEK_CUR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SEEK_END", SEEK_END, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LOCK_SH", PHP_LOCK_SH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LOCK_EX", PHP_LOCK_EX, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LOCK_UN", PHP_LOCK_UN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LOCK_NB", PHP_LOCK_NB, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_NOTIFY_CONNECT", PHP_STREAM_NOTIFY_CONNECT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_NOTIFY_AUTH_REQUIRED", PHP_STREAM_NOTIFY_AUTH_REQUIRED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_NOTIFY_AUTH_RESULT", PHP_STREAM_NOTIFY_AUTH_RESULT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_NOTIFY_MIME_TYPE_IS", PHP_STREAM_NOTIFY_MIME_TYPE_IS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_NOTIFY_FILE_SIZE_IS", PHP_STREAM_NOTIFY_FILE_SIZE_IS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_NOTIFY_REDIRECTED", PHP_STREAM_NOTIFY_REDIRECTED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_NOTIFY_PROGRESS", PHP_STREAM_NOTIFY_PROGRESS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_NOTIFY_FAILURE", PHP_STREAM_NOTIFY_FAILURE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_NOTIFY_COMPLETED", PHP_STREAM_NOTIFY_COMPLETED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_NOTIFY_RESOLVE", PHP_STREAM_NOTIFY_RESOLVE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_NOTIFY_SEVERITY_INFO", PHP_STREAM_NOTIFY_SEVERITY_INFO, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_NOTIFY_SEVERITY_WARN", PHP_STREAM_NOTIFY_SEVERITY_WARN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_NOTIFY_SEVERITY_ERR", PHP_STREAM_NOTIFY_SEVERITY_ERR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_FILTER_READ", PHP_STREAM_FILTER_READ, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_FILTER_WRITE", PHP_STREAM_FILTER_WRITE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_FILTER_ALL", PHP_STREAM_FILTER_ALL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_CLIENT_PERSISTENT", PHP_STREAM_CLIENT_PERSISTENT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_CLIENT_ASYNC_CONNECT", PHP_STREAM_CLIENT_ASYNC_CONNECT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_CLIENT_CONNECT", PHP_STREAM_CLIENT_CONNECT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_SSLv2_CLIENT", STREAM_CRYPTO_METHOD_SSLv2_CLIENT, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_SSLv3_CLIENT", STREAM_CRYPTO_METHOD_SSLv3_CLIENT, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_SSLv23_CLIENT", STREAM_CRYPTO_METHOD_SSLv23_CLIENT, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_TLS_CLIENT", STREAM_CRYPTO_METHOD_TLS_CLIENT, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_SSLv2_SERVER", STREAM_CRYPTO_METHOD_SSLv2_SERVER, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_SSLv3_SERVER", STREAM_CRYPTO_METHOD_SSLv3_SERVER, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_SSLv23_SERVER", STREAM_CRYPTO_METHOD_SSLv23_SERVER, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_TLS_SERVER", STREAM_CRYPTO_METHOD_TLS_SERVER, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_SHUT_RD", STREAM_SHUT_RD, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_SHUT_WR", STREAM_SHUT_WR, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_SHUT_RDWR", STREAM_SHUT_RDWR, CONST_CS|CONST_PERSISTENT); #ifdef PF_INET REGISTER_LONG_CONSTANT("STREAM_PF_INET", PF_INET, CONST_CS|CONST_PERSISTENT); #elif defined(AF_INET) REGISTER_LONG_CONSTANT("STREAM_PF_INET", AF_INET, CONST_CS|CONST_PERSISTENT); #endif #if HAVE_IPV6 # ifdef PF_INET6 REGISTER_LONG_CONSTANT("STREAM_PF_INET6", PF_INET6, CONST_CS|CONST_PERSISTENT); # elif defined(AF_INET6) REGISTER_LONG_CONSTANT("STREAM_PF_INET6", AF_INET6, CONST_CS|CONST_PERSISTENT); # endif #endif #ifdef PF_UNIX REGISTER_LONG_CONSTANT("STREAM_PF_UNIX", PF_UNIX, CONST_CS|CONST_PERSISTENT); #elif defined(AF_UNIX) REGISTER_LONG_CONSTANT("STREAM_PF_UNIX", AF_UNIX, CONST_CS|CONST_PERSISTENT); #endif #ifdef IPPROTO_IP /* most people will use this one when calling socket() or socketpair() */ REGISTER_LONG_CONSTANT("STREAM_IPPROTO_IP", IPPROTO_IP, CONST_CS|CONST_PERSISTENT); #endif #ifdef IPPROTO_TCP REGISTER_LONG_CONSTANT("STREAM_IPPROTO_TCP", IPPROTO_TCP, CONST_CS|CONST_PERSISTENT); #endif #ifdef IPPROTO_UDP REGISTER_LONG_CONSTANT("STREAM_IPPROTO_UDP", IPPROTO_UDP, CONST_CS|CONST_PERSISTENT); #endif #ifdef IPPROTO_ICMP REGISTER_LONG_CONSTANT("STREAM_IPPROTO_ICMP", IPPROTO_ICMP, CONST_CS|CONST_PERSISTENT); #endif #ifdef IPPROTO_RAW REGISTER_LONG_CONSTANT("STREAM_IPPROTO_RAW", IPPROTO_RAW, CONST_CS|CONST_PERSISTENT); #endif REGISTER_LONG_CONSTANT("STREAM_SOCK_STREAM", SOCK_STREAM, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_SOCK_DGRAM", SOCK_DGRAM, CONST_CS|CONST_PERSISTENT); #ifdef SOCK_RAW REGISTER_LONG_CONSTANT("STREAM_SOCK_RAW", SOCK_RAW, CONST_CS|CONST_PERSISTENT); #endif #ifdef SOCK_SEQPACKET REGISTER_LONG_CONSTANT("STREAM_SOCK_SEQPACKET", SOCK_SEQPACKET, CONST_CS|CONST_PERSISTENT); #endif #ifdef SOCK_RDM REGISTER_LONG_CONSTANT("STREAM_SOCK_RDM", SOCK_RDM, CONST_CS|CONST_PERSISTENT); #endif REGISTER_LONG_CONSTANT("STREAM_PEEK", STREAM_PEEK, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_OOB", STREAM_OOB, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_SERVER_BIND", STREAM_XPORT_BIND, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_SERVER_LISTEN", STREAM_XPORT_LISTEN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILE_USE_INCLUDE_PATH", PHP_FILE_USE_INCLUDE_PATH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILE_IGNORE_NEW_LINES", PHP_FILE_IGNORE_NEW_LINES, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILE_SKIP_EMPTY_LINES", PHP_FILE_SKIP_EMPTY_LINES, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILE_APPEND", PHP_FILE_APPEND, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILE_NO_DEFAULT_CONTEXT", PHP_FILE_NO_DEFAULT_CONTEXT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILE_TEXT", 0, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILE_BINARY", 0, CONST_CS | CONST_PERSISTENT); #ifdef HAVE_FNMATCH REGISTER_LONG_CONSTANT("FNM_NOESCAPE", FNM_NOESCAPE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FNM_PATHNAME", FNM_PATHNAME, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FNM_PERIOD", FNM_PERIOD, CONST_CS | CONST_PERSISTENT); # ifdef FNM_CASEFOLD /* a GNU extension */ /* TODO emulate if not available */ REGISTER_LONG_CONSTANT("FNM_CASEFOLD", FNM_CASEFOLD, CONST_CS | CONST_PERSISTENT); # endif #endif return SUCCESS; } /* }}} */ PHP_MSHUTDOWN_FUNCTION(file) /* {{{ */ { #ifndef ZTS file_globals_dtor(&file_globals TSRMLS_CC); #endif return SUCCESS; } /* }}} */ static int flock_values[] = { LOCK_SH, LOCK_EX, LOCK_UN }; /* {{{ proto bool flock(resource fp, int operation [, int &wouldblock]) Portable file locking */ PHP_FUNCTION(flock) { zval *arg1, *arg3 = NULL; int act; php_stream *stream; long operation = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl|z", &arg1, &operation, &arg3) == FAILURE) { return; } PHP_STREAM_TO_ZVAL(stream, &arg1); act = operation & 3; if (act < 1 || act > 3) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Illegal operation argument"); RETURN_FALSE; } if (arg3 && PZVAL_IS_REF(arg3)) { convert_to_long_ex(&arg3); Z_LVAL_P(arg3) = 0; } /* flock_values contains all possible actions if (operation & 4) we won't block on the lock */ act = flock_values[act - 1] | (operation & PHP_LOCK_NB ? LOCK_NB : 0); if (php_stream_lock(stream, act)) { if (operation && errno == EWOULDBLOCK && arg3 && PZVAL_IS_REF(arg3)) { Z_LVAL_P(arg3) = 1; } RETURN_FALSE; } RETURN_TRUE; } /* }}} */ #define PHP_META_UNSAFE ".\\+*?[^]$() " /* {{{ proto array get_meta_tags(string filename [, bool use_include_path]) Extracts all meta tag content attributes from a file and returns an array */ PHP_FUNCTION(get_meta_tags) { char *filename; int filename_len; zend_bool use_include_path = 0; int in_tag = 0, done = 0; int looking_for_val = 0, have_name = 0, have_content = 0; int saw_name = 0, saw_content = 0; char *name = NULL, *value = NULL, *temp = NULL; php_meta_tags_token tok, tok_last; php_meta_tags_data md; /* Initiailize our structure */ memset(&md, 0, sizeof(md)); /* Parse arguments */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|b", &filename, &filename_len, &use_include_path) == FAILURE) { return; } md.stream = php_stream_open_wrapper(filename, "rb", (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL); if (!md.stream) { RETURN_FALSE; } array_init(return_value); tok_last = TOK_EOF; while (!done && (tok = php_next_meta_token(&md TSRMLS_CC)) != TOK_EOF) { if (tok == TOK_ID) { if (tok_last == TOK_OPENTAG) { md.in_meta = !strcasecmp("meta", md.token_data); } else if (tok_last == TOK_SLASH && in_tag) { if (strcasecmp("head", md.token_data) == 0) { /* We are done here! */ done = 1; } } else if (tok_last == TOK_EQUAL && looking_for_val) { if (saw_name) { STR_FREE(name); /* Get the NAME attr (Single word attr, non-quoted) */ temp = name = estrndup(md.token_data, md.token_len); while (temp && *temp) { if (strchr(PHP_META_UNSAFE, *temp)) { *temp = '_'; } temp++; } have_name = 1; } else if (saw_content) { STR_FREE(value); value = estrndup(md.token_data, md.token_len); have_content = 1; } looking_for_val = 0; } else { if (md.in_meta) { if (strcasecmp("name", md.token_data) == 0) { saw_name = 1; saw_content = 0; looking_for_val = 1; } else if (strcasecmp("content", md.token_data) == 0) { saw_name = 0; saw_content = 1; looking_for_val = 1; } } } } else if (tok == TOK_STRING && tok_last == TOK_EQUAL && looking_for_val) { if (saw_name) { STR_FREE(name); /* Get the NAME attr (Quoted single/double) */ temp = name = estrndup(md.token_data, md.token_len); while (temp && *temp) { if (strchr(PHP_META_UNSAFE, *temp)) { *temp = '_'; } temp++; } have_name = 1; } else if (saw_content) { STR_FREE(value); value = estrndup(md.token_data, md.token_len); have_content = 1; } looking_for_val = 0; } else if (tok == TOK_OPENTAG) { if (looking_for_val) { looking_for_val = 0; have_name = saw_name = 0; have_content = saw_content = 0; } in_tag = 1; } else if (tok == TOK_CLOSETAG) { if (have_name) { /* For BC */ php_strtolower(name, strlen(name)); if (have_content) { add_assoc_string(return_value, name, value, 1); } else { add_assoc_string(return_value, name, "", 1); } efree(name); STR_FREE(value); } else if (have_content) { efree(value); } name = value = NULL; /* Reset all of our flags */ in_tag = looking_for_val = 0; have_name = saw_name = 0; have_content = saw_content = 0; md.in_meta = 0; } tok_last = tok; if (md.token_data) efree(md.token_data); md.token_data = NULL; } STR_FREE(value); STR_FREE(name); php_stream_close(md.stream); } /* }}} */ /* {{{ proto string file_get_contents(string filename [, bool use_include_path [, resource context [, long offset [, long maxlen]]]]) Read the entire file into a string */ PHP_FUNCTION(file_get_contents) { char *filename; int filename_len; char *contents; zend_bool use_include_path = 0; php_stream *stream; int len; long offset = -1; long maxlen = PHP_STREAM_COPY_ALL; zval *zcontext = NULL; php_stream_context *context = NULL; /* Parse arguments */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|br!ll", &filename, &filename_len, &use_include_path, &zcontext, &offset, &maxlen) == FAILURE) { return; } if (ZEND_NUM_ARGS() == 5 && maxlen < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "length must be greater than or equal to zero"); RETURN_FALSE; } context = php_stream_context_from_zval(zcontext, 0); stream = php_stream_open_wrapper_ex(filename, "rb", (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, context); if (!stream) { RETURN_FALSE; } if (offset > 0 && php_stream_seek(stream, offset, SEEK_SET) < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to seek to position %ld in the stream", offset); php_stream_close(stream); RETURN_FALSE; } if ((len = php_stream_copy_to_mem(stream, &contents, maxlen, 0)) > 0) { RETVAL_STRINGL(contents, len, 0); } else if (len == 0) { RETVAL_EMPTY_STRING(); } else { RETVAL_FALSE; } php_stream_close(stream); } /* }}} */ /* {{{ proto int file_put_contents(string file, mixed data [, int flags [, resource context]]) Write/Create a file with contents data and return the number of bytes written */ PHP_FUNCTION(file_put_contents) { php_stream *stream; char *filename; int filename_len; zval *data; int numbytes = 0; long flags = 0; zval *zcontext = NULL; php_stream_context *context = NULL; php_stream *srcstream = NULL; char mode[3] = "wb"; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "pz/|lr!", &filename, &filename_len, &data, &flags, &zcontext) == FAILURE) { return; } if (Z_TYPE_P(data) == IS_RESOURCE) { php_stream_from_zval(srcstream, &data); } context = php_stream_context_from_zval(zcontext, flags & PHP_FILE_NO_DEFAULT_CONTEXT); if (flags & PHP_FILE_APPEND) { mode[0] = 'a'; } else if (flags & LOCK_EX) { /* check to make sure we are dealing with a regular file */ if (php_memnstr(filename, "://", sizeof("://") - 1, filename + filename_len)) { if (strncasecmp(filename, "file://", sizeof("file://") - 1)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Exclusive locks may only be set for regular files"); RETURN_FALSE; } } mode[0] = 'c'; } mode[2] = '\0'; stream = php_stream_open_wrapper_ex(filename, mode, ((flags & PHP_FILE_USE_INCLUDE_PATH) ? USE_PATH : 0) | REPORT_ERRORS, NULL, context); if (stream == NULL) { RETURN_FALSE; } if (flags & LOCK_EX && (!php_stream_supports_lock(stream) || php_stream_lock(stream, LOCK_EX))) { php_stream_close(stream); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Exclusive locks are not supported for this stream"); RETURN_FALSE; } if (mode[0] == 'c') { php_stream_truncate_set_size(stream, 0); } switch (Z_TYPE_P(data)) { case IS_RESOURCE: { size_t len; if (php_stream_copy_to_stream_ex(srcstream, stream, PHP_STREAM_COPY_ALL, &len) != SUCCESS) { numbytes = -1; } else { numbytes = len; } break; } case IS_NULL: case IS_LONG: case IS_DOUBLE: case IS_BOOL: case IS_CONSTANT: convert_to_string_ex(&data); case IS_STRING: if (Z_STRLEN_P(data)) { numbytes = php_stream_write(stream, Z_STRVAL_P(data), Z_STRLEN_P(data)); if (numbytes != Z_STRLEN_P(data)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Only %d of %d bytes written, possibly out of free disk space", numbytes, Z_STRLEN_P(data)); numbytes = -1; } } break; case IS_ARRAY: if (zend_hash_num_elements(Z_ARRVAL_P(data))) { int bytes_written; zval **tmp; HashPosition pos; zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(data), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(data), (void **) &tmp, &pos) == SUCCESS) { if (Z_TYPE_PP(tmp) != IS_STRING) { SEPARATE_ZVAL(tmp); convert_to_string(*tmp); } if (Z_STRLEN_PP(tmp)) { numbytes += Z_STRLEN_PP(tmp); bytes_written = php_stream_write(stream, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp)); if (bytes_written < 0 || bytes_written != Z_STRLEN_PP(tmp)) { if (bytes_written < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to write %d bytes to %s", Z_STRLEN_PP(tmp), filename); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Only %d of %d bytes written, possibly out of free disk space", bytes_written, Z_STRLEN_PP(tmp)); } numbytes = -1; break; } } zend_hash_move_forward_ex(Z_ARRVAL_P(data), &pos); } } break; case IS_OBJECT: if (Z_OBJ_HT_P(data) != NULL) { zval out; if (zend_std_cast_object_tostring(data, &out, IS_STRING TSRMLS_CC) == SUCCESS) { numbytes = php_stream_write(stream, Z_STRVAL(out), Z_STRLEN(out)); if (numbytes != Z_STRLEN(out)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Only %d of %d bytes written, possibly out of free disk space", numbytes, Z_STRLEN(out)); numbytes = -1; } zval_dtor(&out); break; } } default: numbytes = -1; break; } php_stream_close(stream); if (numbytes < 0) { RETURN_FALSE; } RETURN_LONG(numbytes); } /* }}} */ #define PHP_FILE_BUF_SIZE 80 /* {{{ proto array file(string filename [, int flags[, resource context]]) Read entire file into an array */ PHP_FUNCTION(file) { char *filename; int filename_len; char *target_buf=NULL, *p, *s, *e; register int i = 0; int target_len; char eol_marker = '\n'; long flags = 0; zend_bool use_include_path; zend_bool include_new_line; zend_bool skip_blank_lines; php_stream *stream; zval *zcontext = NULL; php_stream_context *context = NULL; /* Parse arguments */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|lr!", &filename, &filename_len, &flags, &zcontext) == FAILURE) { return; } if (flags < 0 || flags > (PHP_FILE_USE_INCLUDE_PATH | PHP_FILE_IGNORE_NEW_LINES | PHP_FILE_SKIP_EMPTY_LINES | PHP_FILE_NO_DEFAULT_CONTEXT)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%ld' flag is not supported", flags); RETURN_FALSE; } use_include_path = flags & PHP_FILE_USE_INCLUDE_PATH; include_new_line = !(flags & PHP_FILE_IGNORE_NEW_LINES); skip_blank_lines = flags & PHP_FILE_SKIP_EMPTY_LINES; context = php_stream_context_from_zval(zcontext, flags & PHP_FILE_NO_DEFAULT_CONTEXT); stream = php_stream_open_wrapper_ex(filename, "rb", (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, context); if (!stream) { RETURN_FALSE; } /* Initialize return array */ array_init(return_value); if ((target_len = php_stream_copy_to_mem(stream, &target_buf, PHP_STREAM_COPY_ALL, 0))) { s = target_buf; e = target_buf + target_len; if (!(p = php_stream_locate_eol(stream, target_buf, target_len TSRMLS_CC))) { p = e; goto parse_eol; } if (stream->flags & PHP_STREAM_FLAG_EOL_MAC) { eol_marker = '\r'; } /* for performance reasons the code is duplicated, so that the if (include_new_line) * will not need to be done for every single line in the file. */ if (include_new_line) { do { p++; parse_eol: add_index_stringl(return_value, i++, estrndup(s, p-s), p-s, 0); s = p; } while ((p = memchr(p, eol_marker, (e-p)))); } else { do { int windows_eol = 0; if (p != target_buf && eol_marker == '\n' && *(p - 1) == '\r') { windows_eol++; } if (skip_blank_lines && !(p-s-windows_eol)) { s = ++p; continue; } add_index_stringl(return_value, i++, estrndup(s, p-s-windows_eol), p-s-windows_eol, 0); s = ++p; } while ((p = memchr(p, eol_marker, (e-p)))); } /* handle any left overs of files without new lines */ if (s != e) { p = e; goto parse_eol; } } if (target_buf) { efree(target_buf); } php_stream_close(stream); } /* }}} */ /* {{{ proto string tempnam(string dir, string prefix) Create a unique filename in a directory */ PHP_FUNCTION(tempnam) { char *dir, *prefix; int dir_len, prefix_len; size_t p_len; char *opened_path; char *p; int fd; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ps", &dir, &dir_len, &prefix, &prefix_len) == FAILURE) { return; } if (php_check_open_basedir(dir TSRMLS_CC)) { RETURN_FALSE; } php_basename(prefix, prefix_len, NULL, 0, &p, &p_len TSRMLS_CC); if (p_len > 64) { p[63] = '\0'; } RETVAL_FALSE; if ((fd = php_open_temporary_fd_ex(dir, p, &opened_path, 1 TSRMLS_CC)) >= 0) { close(fd); RETVAL_STRING(opened_path, 0); } efree(p); } /* }}} */ /* {{{ proto resource tmpfile(void) Create a temporary file that will be deleted automatically after use */ PHP_NAMED_FUNCTION(php_if_tmpfile) { php_stream *stream; if (zend_parse_parameters_none() == FAILURE) { return; } stream = php_stream_fopen_tmpfile(); if (stream) { php_stream_to_zval(stream, return_value); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto resource fopen(string filename, string mode [, bool use_include_path [, resource context]]) Open a file or a URL and return a file pointer */ PHP_NAMED_FUNCTION(php_if_fopen) { char *filename, *mode; int filename_len, mode_len; zend_bool use_include_path = 0; zval *zcontext = NULL; php_stream *stream; php_stream_context *context = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ps|br", &filename, &filename_len, &mode, &mode_len, &use_include_path, &zcontext) == FAILURE) { RETURN_FALSE; } context = php_stream_context_from_zval(zcontext, 0); stream = php_stream_open_wrapper_ex(filename, mode, (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, context); if (stream == NULL) { RETURN_FALSE; } php_stream_to_zval(stream, return_value); } /* }}} */ /* {{{ proto bool fclose(resource fp) Close an open file pointer */ PHPAPI PHP_FUNCTION(fclose) { zval *arg1; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &arg1) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); if ((stream->flags & PHP_STREAM_FLAG_NO_FCLOSE) != 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%d is not a valid stream resource", stream->rsrc_id); RETURN_FALSE; } if (!stream->is_persistent) { php_stream_close(stream); } else { php_stream_pclose(stream); } RETURN_TRUE; } /* }}} */ /* {{{ proto resource popen(string command, string mode) Execute a command and open either a read or a write pipe to it */ PHP_FUNCTION(popen) { char *command, *mode; int command_len, mode_len; FILE *fp; php_stream *stream; char *posix_mode; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ps", &command, &command_len, &mode, &mode_len) == FAILURE) { return; } posix_mode = estrndup(mode, mode_len); #ifndef PHP_WIN32 { char *z = memchr(posix_mode, 'b', mode_len); if (z) { memmove(z, z + 1, mode_len - (z - posix_mode)); } } #endif fp = VCWD_POPEN(command, posix_mode); if (!fp) { php_error_docref2(NULL TSRMLS_CC, command, posix_mode, E_WARNING, "%s", strerror(errno)); efree(posix_mode); RETURN_FALSE; } stream = php_stream_fopen_from_pipe(fp, mode); if (stream == NULL) { php_error_docref2(NULL TSRMLS_CC, command, mode, E_WARNING, "%s", strerror(errno)); RETVAL_FALSE; } else { php_stream_to_zval(stream, return_value); } efree(posix_mode); } /* }}} */ /* {{{ proto int pclose(resource fp) Close a file pointer opened by popen() */ PHP_FUNCTION(pclose) { zval *arg1; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &arg1) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); zend_list_delete(stream->rsrc_id); RETURN_LONG(FG(pclose_ret)); } /* }}} */ /* {{{ proto bool feof(resource fp) Test for end-of-file on a file pointer */ PHPAPI PHP_FUNCTION(feof) { zval *arg1; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &arg1) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); if (php_stream_eof(stream)) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto string fgets(resource fp[, int length]) Get a line from file pointer */ PHPAPI PHP_FUNCTION(fgets) { zval *arg1; long len = 1024; char *buf = NULL; int argc = ZEND_NUM_ARGS(); size_t line_len = 0; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|l", &arg1, &len) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); if (argc == 1) { /* ask streams to give us a buffer of an appropriate size */ buf = php_stream_get_line(stream, NULL, 0, &line_len); if (buf == NULL) { goto exit_failed; } } else if (argc > 1) { if (len <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0"); RETURN_FALSE; } buf = ecalloc(len + 1, sizeof(char)); if (php_stream_get_line(stream, buf, len, &line_len) == NULL) { goto exit_failed; } } ZVAL_STRINGL(return_value, buf, line_len, 0); /* resize buffer if it's much larger than the result. * Only needed if the user requested a buffer size. */ if (argc > 1 && Z_STRLEN_P(return_value) < len / 2) { Z_STRVAL_P(return_value) = erealloc(buf, line_len + 1); } return; exit_failed: RETVAL_FALSE; if (buf) { efree(buf); } } /* }}} */ /* {{{ proto string fgetc(resource fp) Get a character from file pointer */ PHPAPI PHP_FUNCTION(fgetc) { zval *arg1; char buf[2]; int result; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &arg1) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); result = php_stream_getc(stream); if (result == EOF) { RETVAL_FALSE; } else { buf[0] = result; buf[1] = '\0'; RETURN_STRINGL(buf, 1, 1); } } /* }}} */ /* {{{ proto string fgetss(resource fp [, int length [, string allowable_tags]]) Get a line from file pointer and strip HTML tags */ PHPAPI PHP_FUNCTION(fgetss) { zval *fd; long bytes = 0; size_t len = 0; size_t actual_len, retval_len; char *buf = NULL, *retval; php_stream *stream; char *allowed_tags=NULL; int allowed_tags_len=0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|ls", &fd, &bytes, &allowed_tags, &allowed_tags_len) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &fd); if (ZEND_NUM_ARGS() >= 2) { if (bytes <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0"); RETURN_FALSE; } len = (size_t) bytes; buf = safe_emalloc(sizeof(char), (len + 1), 0); /*needed because recv doesnt set null char at end*/ memset(buf, 0, len + 1); } if ((retval = php_stream_get_line(stream, buf, len, &actual_len)) == NULL) { if (buf != NULL) { efree(buf); } RETURN_FALSE; } retval_len = php_strip_tags(retval, actual_len, &stream->fgetss_state, allowed_tags, allowed_tags_len); RETURN_STRINGL(retval, retval_len, 0); } /* }}} */ /* {{{ proto mixed fscanf(resource stream, string format [, string ...]) Implements a mostly ANSI compatible fscanf() */ PHP_FUNCTION(fscanf) { int result, format_len, type, argc = 0; zval ***args = NULL; zval *file_handle; char *buf, *format; size_t len; void *what; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs*", &file_handle, &format, &format_len, &args, &argc) == FAILURE) { return; } what = zend_fetch_resource(&file_handle TSRMLS_CC, -1, "File-Handle", &type, 2, php_file_le_stream(), php_file_le_pstream()); /* we can't do a ZEND_VERIFY_RESOURCE(what), otherwise we end up * with a leak if we have an invalid filehandle. This needs changing * if the code behind ZEND_VERIFY_RESOURCE changed. - cc */ if (!what) { if (args) { efree(args); } RETURN_FALSE; } buf = php_stream_get_line((php_stream *) what, NULL, 0, &len); if (buf == NULL) { if (args) { efree(args); } RETURN_FALSE; } result = php_sscanf_internal(buf, format, argc, args, 0, &return_value TSRMLS_CC); if (args) { efree(args); } efree(buf); if (SCAN_ERROR_WRONG_PARAM_COUNT == result) { WRONG_PARAM_COUNT; } } /* }}} */ /* {{{ proto int fwrite(resource fp, string str [, int length]) Binary-safe file write */ PHPAPI PHP_FUNCTION(fwrite) { zval *arg1; char *arg2; int arg2len; int ret; int num_bytes; long arg3 = 0; char *buffer = NULL; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs|l", &arg1, &arg2, &arg2len, &arg3) == FAILURE) { RETURN_FALSE; } if (ZEND_NUM_ARGS() == 2) { num_bytes = arg2len; } else { num_bytes = MAX(0, MIN((int)arg3, arg2len)); } if (!num_bytes) { RETURN_LONG(0); } PHP_STREAM_TO_ZVAL(stream, &arg1); ret = php_stream_write(stream, buffer ? buffer : arg2, num_bytes); if (buffer) { efree(buffer); } RETURN_LONG(ret); } /* }}} */ /* {{{ proto bool fflush(resource fp) Flushes output */ PHPAPI PHP_FUNCTION(fflush) { zval *arg1; int ret; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &arg1) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); ret = php_stream_flush(stream); if (ret) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool rewind(resource fp) Rewind the position of a file pointer */ PHPAPI PHP_FUNCTION(rewind) { zval *arg1; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &arg1) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); if (-1 == php_stream_rewind(stream)) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto int ftell(resource fp) Get file pointer's read/write position */ PHPAPI PHP_FUNCTION(ftell) { zval *arg1; long ret; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &arg1) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); ret = php_stream_tell(stream); if (ret == -1) { RETURN_FALSE; } RETURN_LONG(ret); } /* }}} */ /* {{{ proto int fseek(resource fp, int offset [, int whence]) Seek on a file pointer */ PHPAPI PHP_FUNCTION(fseek) { zval *arg1; long arg2, whence = SEEK_SET; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl|l", &arg1, &arg2, &whence) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); RETURN_LONG(php_stream_seek(stream, arg2, whence)); } /* }}} */ /* {{{ php_mkdir */ /* DEPRECATED APIs: Use php_stream_mkdir() instead */ PHPAPI int php_mkdir_ex(char *dir, long mode, int options TSRMLS_DC) { int ret; if (php_check_open_basedir(dir TSRMLS_CC)) { return -1; } if ((ret = VCWD_MKDIR(dir, (mode_t)mode)) < 0 && (options & REPORT_ERRORS)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", strerror(errno)); } return ret; } PHPAPI int php_mkdir(char *dir, long mode TSRMLS_DC) { return php_mkdir_ex(dir, mode, REPORT_ERRORS TSRMLS_CC); } /* }}} */ /* {{{ proto bool mkdir(string pathname [, int mode [, bool recursive [, resource context]]]) Create a directory */ PHP_FUNCTION(mkdir) { char *dir; int dir_len; zval *zcontext = NULL; long mode = 0777; zend_bool recursive = 0; php_stream_context *context; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|lbr", &dir, &dir_len, &mode, &recursive, &zcontext) == FAILURE) { RETURN_FALSE; } context = php_stream_context_from_zval(zcontext, 0); RETURN_BOOL(php_stream_mkdir(dir, mode, (recursive ? PHP_STREAM_MKDIR_RECURSIVE : 0) | REPORT_ERRORS, context)); } /* }}} */ /* {{{ proto bool rmdir(string dirname[, resource context]) Remove a directory */ PHP_FUNCTION(rmdir) { char *dir; int dir_len; zval *zcontext = NULL; php_stream_context *context; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|r", &dir, &dir_len, &zcontext) == FAILURE) { RETURN_FALSE; } context = php_stream_context_from_zval(zcontext, 0); RETURN_BOOL(php_stream_rmdir(dir, REPORT_ERRORS, context)); } /* }}} */ /* {{{ proto int readfile(string filename [, bool use_include_path[, resource context]]) Output a file or a URL */ PHP_FUNCTION(readfile) { char *filename; int filename_len; int size = 0; zend_bool use_include_path = 0; zval *zcontext = NULL; php_stream *stream; php_stream_context *context = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|br!", &filename, &filename_len, &use_include_path, &zcontext) == FAILURE) { RETURN_FALSE; } context = php_stream_context_from_zval(zcontext, 0); stream = php_stream_open_wrapper_ex(filename, "rb", (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, context); if (stream) { size = php_stream_passthru(stream); php_stream_close(stream); RETURN_LONG(size); } RETURN_FALSE; } /* }}} */ /* {{{ proto int umask([int mask]) Return or change the umask */ PHP_FUNCTION(umask) { long arg1 = 0; int oldumask; oldumask = umask(077); if (BG(umask) == -1) { BG(umask) = oldumask; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &arg1) == FAILURE) { RETURN_FALSE; } if (ZEND_NUM_ARGS() == 0) { umask(oldumask); } else { umask(arg1); } RETURN_LONG(oldumask); } /* }}} */ /* {{{ proto int fpassthru(resource fp) Output all remaining data from a file pointer */ PHPAPI PHP_FUNCTION(fpassthru) { zval *arg1; int size; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &arg1) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); size = php_stream_passthru(stream); RETURN_LONG(size); } /* }}} */ /* {{{ proto bool rename(string old_name, string new_name[, resource context]) Rename a file */ PHP_FUNCTION(rename) { char *old_name, *new_name; int old_name_len, new_name_len; zval *zcontext = NULL; php_stream_wrapper *wrapper; php_stream_context *context; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "pp|r", &old_name, &old_name_len, &new_name, &new_name_len, &zcontext) == FAILURE) { RETURN_FALSE; } wrapper = php_stream_locate_url_wrapper(old_name, NULL, 0 TSRMLS_CC); if (!wrapper || !wrapper->wops) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to locate stream wrapper"); RETURN_FALSE; } if (!wrapper->wops->rename) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s wrapper does not support renaming", wrapper->wops->label ? wrapper->wops->label : "Source"); RETURN_FALSE; } if (wrapper != php_stream_locate_url_wrapper(new_name, NULL, 0 TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot rename a file across wrapper types"); RETURN_FALSE; } context = php_stream_context_from_zval(zcontext, 0); RETURN_BOOL(wrapper->wops->rename(wrapper, old_name, new_name, 0, context TSRMLS_CC)); } /* }}} */ /* {{{ proto bool unlink(string filename[, context context]) Delete a file */ PHP_FUNCTION(unlink) { char *filename; int filename_len; php_stream_wrapper *wrapper; zval *zcontext = NULL; php_stream_context *context = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|r", &filename, &filename_len, &zcontext) == FAILURE) { RETURN_FALSE; } context = php_stream_context_from_zval(zcontext, 0); wrapper = php_stream_locate_url_wrapper(filename, NULL, 0 TSRMLS_CC); if (!wrapper || !wrapper->wops) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to locate stream wrapper"); RETURN_FALSE; } if (!wrapper->wops->unlink) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s does not allow unlinking", wrapper->wops->label ? wrapper->wops->label : "Wrapper"); RETURN_FALSE; } RETURN_BOOL(wrapper->wops->unlink(wrapper, filename, REPORT_ERRORS, context TSRMLS_CC)); } /* }}} */ /* {{{ proto bool ftruncate(resource fp, int size) Truncate file to 'size' length */ PHP_NAMED_FUNCTION(php_if_ftruncate) { zval *fp; long size; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &fp, &size) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &fp); if (!php_stream_truncate_supported(stream)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can't truncate this stream!"); RETURN_FALSE; } RETURN_BOOL(0 == php_stream_truncate_set_size(stream, size)); } /* }}} */ /* {{{ proto array fstat(resource fp) Stat() on a filehandle */ PHP_NAMED_FUNCTION(php_if_fstat) { zval *fp; zval *stat_dev, *stat_ino, *stat_mode, *stat_nlink, *stat_uid, *stat_gid, *stat_rdev, *stat_size, *stat_atime, *stat_mtime, *stat_ctime, *stat_blksize, *stat_blocks; php_stream *stream; php_stream_statbuf stat_ssb; char *stat_sb_names[13] = { "dev", "ino", "mode", "nlink", "uid", "gid", "rdev", "size", "atime", "mtime", "ctime", "blksize", "blocks" }; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &fp) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &fp); if (php_stream_stat(stream, &stat_ssb)) { RETURN_FALSE; } array_init(return_value); MAKE_LONG_ZVAL_INCREF(stat_dev, stat_ssb.sb.st_dev); MAKE_LONG_ZVAL_INCREF(stat_ino, stat_ssb.sb.st_ino); MAKE_LONG_ZVAL_INCREF(stat_mode, stat_ssb.sb.st_mode); MAKE_LONG_ZVAL_INCREF(stat_nlink, stat_ssb.sb.st_nlink); MAKE_LONG_ZVAL_INCREF(stat_uid, stat_ssb.sb.st_uid); MAKE_LONG_ZVAL_INCREF(stat_gid, stat_ssb.sb.st_gid); #ifdef HAVE_ST_RDEV MAKE_LONG_ZVAL_INCREF(stat_rdev, stat_ssb.sb.st_rdev); #else MAKE_LONG_ZVAL_INCREF(stat_rdev, -1); #endif MAKE_LONG_ZVAL_INCREF(stat_size, stat_ssb.sb.st_size); MAKE_LONG_ZVAL_INCREF(stat_atime, stat_ssb.sb.st_atime); MAKE_LONG_ZVAL_INCREF(stat_mtime, stat_ssb.sb.st_mtime); MAKE_LONG_ZVAL_INCREF(stat_ctime, stat_ssb.sb.st_ctime); #ifdef HAVE_ST_BLKSIZE MAKE_LONG_ZVAL_INCREF(stat_blksize, stat_ssb.sb.st_blksize); #else MAKE_LONG_ZVAL_INCREF(stat_blksize,-1); #endif #ifdef HAVE_ST_BLOCKS MAKE_LONG_ZVAL_INCREF(stat_blocks, stat_ssb.sb.st_blocks); #else MAKE_LONG_ZVAL_INCREF(stat_blocks,-1); #endif /* Store numeric indexes in propper order */ zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_dev, sizeof(zval *), NULL); zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_ino, sizeof(zval *), NULL); zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_mode, sizeof(zval *), NULL); zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_nlink, sizeof(zval *), NULL); zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_uid, sizeof(zval *), NULL); zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_gid, sizeof(zval *), NULL); zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_rdev, sizeof(zval *), NULL); zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_size, sizeof(zval *), NULL); zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_atime, sizeof(zval *), NULL); zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_mtime, sizeof(zval *), NULL); zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_ctime, sizeof(zval *), NULL); zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_blksize, sizeof(zval *), NULL); zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_blocks, sizeof(zval *), NULL); /* Store string indexes referencing the same zval*/ zend_hash_update(HASH_OF(return_value), stat_sb_names[0], strlen(stat_sb_names[0])+1, (void *)&stat_dev, sizeof(zval *), NULL); zend_hash_update(HASH_OF(return_value), stat_sb_names[1], strlen(stat_sb_names[1])+1, (void *)&stat_ino, sizeof(zval *), NULL); zend_hash_update(HASH_OF(return_value), stat_sb_names[2], strlen(stat_sb_names[2])+1, (void *)&stat_mode, sizeof(zval *), NULL); zend_hash_update(HASH_OF(return_value), stat_sb_names[3], strlen(stat_sb_names[3])+1, (void *)&stat_nlink, sizeof(zval *), NULL); zend_hash_update(HASH_OF(return_value), stat_sb_names[4], strlen(stat_sb_names[4])+1, (void *)&stat_uid, sizeof(zval *), NULL); zend_hash_update(HASH_OF(return_value), stat_sb_names[5], strlen(stat_sb_names[5])+1, (void *)&stat_gid, sizeof(zval *), NULL); zend_hash_update(HASH_OF(return_value), stat_sb_names[6], strlen(stat_sb_names[6])+1, (void *)&stat_rdev, sizeof(zval *), NULL); zend_hash_update(HASH_OF(return_value), stat_sb_names[7], strlen(stat_sb_names[7])+1, (void *)&stat_size, sizeof(zval *), NULL); zend_hash_update(HASH_OF(return_value), stat_sb_names[8], strlen(stat_sb_names[8])+1, (void *)&stat_atime, sizeof(zval *), NULL); zend_hash_update(HASH_OF(return_value), stat_sb_names[9], strlen(stat_sb_names[9])+1, (void *)&stat_mtime, sizeof(zval *), NULL); zend_hash_update(HASH_OF(return_value), stat_sb_names[10], strlen(stat_sb_names[10])+1, (void *)&stat_ctime, sizeof(zval *), NULL); zend_hash_update(HASH_OF(return_value), stat_sb_names[11], strlen(stat_sb_names[11])+1, (void *)&stat_blksize, sizeof(zval *), NULL); zend_hash_update(HASH_OF(return_value), stat_sb_names[12], strlen(stat_sb_names[12])+1, (void *)&stat_blocks, sizeof(zval *), NULL); } /* }}} */ /* {{{ proto bool copy(string source_file, string destination_file [, resource context]) Copy a file */ PHP_FUNCTION(copy) { char *source, *target; int source_len, target_len; zval *zcontext = NULL; php_stream_context *context; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "pp|r", &source, &source_len, &target, &target_len, &zcontext) == FAILURE) { return; } if (php_check_open_basedir(source TSRMLS_CC)) { RETURN_FALSE; } context = php_stream_context_from_zval(zcontext, 0); if (php_copy_file_ctx(source, target, 0, context TSRMLS_CC) == SUCCESS) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ php_copy_file */ PHPAPI int php_copy_file(char *src, char *dest TSRMLS_DC) { return php_copy_file_ctx(src, dest, 0, NULL TSRMLS_CC); } /* }}} */ /* {{{ php_copy_file_ex */ PHPAPI int php_copy_file_ex(char *src, char *dest, int src_flg TSRMLS_DC) { return php_copy_file_ctx(src, dest, 0, NULL TSRMLS_CC); } /* }}} */ /* {{{ php_copy_file_ctx */ PHPAPI int php_copy_file_ctx(char *src, char *dest, int src_flg, php_stream_context *ctx TSRMLS_DC) { php_stream *srcstream = NULL, *deststream = NULL; int ret = FAILURE; php_stream_statbuf src_s, dest_s; switch (php_stream_stat_path_ex(src, 0, &src_s, ctx)) { case -1: /* non-statable stream */ goto safe_to_copy; break; case 0: break; default: /* failed to stat file, does not exist? */ return ret; } if (S_ISDIR(src_s.sb.st_mode)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The first argument to copy() function cannot be a directory"); return FAILURE; } switch (php_stream_stat_path_ex(dest, PHP_STREAM_URL_STAT_QUIET, &dest_s, ctx)) { case -1: /* non-statable stream */ goto safe_to_copy; break; case 0: break; default: /* failed to stat file, does not exist? */ return ret; } if (S_ISDIR(dest_s.sb.st_mode)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The second argument to copy() function cannot be a directory"); return FAILURE; } if (!src_s.sb.st_ino || !dest_s.sb.st_ino) { goto no_stat; } if (src_s.sb.st_ino == dest_s.sb.st_ino && src_s.sb.st_dev == dest_s.sb.st_dev) { return ret; } else { goto safe_to_copy; } no_stat: { char *sp, *dp; int res; if ((sp = expand_filepath(src, NULL TSRMLS_CC)) == NULL) { return ret; } if ((dp = expand_filepath(dest, NULL TSRMLS_CC)) == NULL) { efree(sp); goto safe_to_copy; } res = #ifndef PHP_WIN32 !strcmp(sp, dp); #else !strcasecmp(sp, dp); #endif efree(sp); efree(dp); if (res) { return ret; } } safe_to_copy: srcstream = php_stream_open_wrapper_ex(src, "rb", src_flg | REPORT_ERRORS, NULL, ctx); if (!srcstream) { return ret; } deststream = php_stream_open_wrapper_ex(dest, "wb", REPORT_ERRORS, NULL, ctx); if (srcstream && deststream) { ret = php_stream_copy_to_stream_ex(srcstream, deststream, PHP_STREAM_COPY_ALL, NULL); } if (srcstream) { php_stream_close(srcstream); } if (deststream) { php_stream_close(deststream); } return ret; } /* }}} */ /* {{{ proto string fread(resource fp, int length) Binary-safe file read */ PHPAPI PHP_FUNCTION(fread) { zval *arg1; long len; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &arg1, &len) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); if (len <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0"); RETURN_FALSE; } Z_STRVAL_P(return_value) = emalloc(len + 1); Z_STRLEN_P(return_value) = php_stream_read(stream, Z_STRVAL_P(return_value), len); /* needed because recv/read/gzread doesnt put a null at the end*/ Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0; Z_TYPE_P(return_value) = IS_STRING; } /* }}} */ static const char *php_fgetcsv_lookup_trailing_spaces(const char *ptr, size_t len, const char delimiter TSRMLS_DC) /* {{{ */ { int inc_len; unsigned char last_chars[2] = { 0, 0 }; while (len > 0) { inc_len = (*ptr == '\0' ? 1: php_mblen(ptr, len)); switch (inc_len) { case -2: case -1: inc_len = 1; php_ignore_value(php_mblen(NULL, 0)); break; case 0: goto quit_loop; case 1: default: last_chars[0] = last_chars[1]; last_chars[1] = *ptr; break; } ptr += inc_len; len -= inc_len; } quit_loop: switch (last_chars[1]) { case '\n': if (last_chars[0] == '\r') { return ptr - 2; } /* break is omitted intentionally */ case '\r': return ptr - 1; } return ptr; } /* }}} */ #define FPUTCSV_FLD_CHK(c) memchr(Z_STRVAL(field), c, Z_STRLEN(field)) /* {{{ proto int fputcsv(resource fp, array fields [, string delimiter [, string enclosure]]) Format line as CSV and write to file pointer */ PHP_FUNCTION(fputcsv) { char delimiter = ','; /* allow this to be set as parameter */ char enclosure = '"'; /* allow this to be set as parameter */ const char escape_char = '\\'; php_stream *stream; zval *fp = NULL, *fields = NULL; int ret; char *delimiter_str = NULL, *enclosure_str = NULL; int delimiter_str_len = 0, enclosure_str_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra|ss", &fp, &fields, &delimiter_str, &delimiter_str_len, &enclosure_str, &enclosure_str_len) == FAILURE) { return; } if (delimiter_str != NULL) { /* Make sure that there is at least one character in string */ if (delimiter_str_len < 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } else if (delimiter_str_len > 1) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "delimiter must be a single character"); } /* use first character from string */ delimiter = *delimiter_str; } if (enclosure_str != NULL) { if (enclosure_str_len < 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } else if (enclosure_str_len > 1) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "enclosure must be a single character"); } /* use first character from string */ enclosure = *enclosure_str; } PHP_STREAM_TO_ZVAL(stream, &fp); ret = php_fputcsv(stream, fields, delimiter, enclosure, escape_char TSRMLS_CC); RETURN_LONG(ret); } /* }}} */ /* {{{ PHPAPI int php_fputcsv(php_stream *stream, zval *fields, char delimiter, char enclosure, char escape_char TSRMLS_DC) */ PHPAPI int php_fputcsv(php_stream *stream, zval *fields, char delimiter, char enclosure, char escape_char TSRMLS_DC) { int count, i = 0, ret; zval **field_tmp = NULL, field; smart_str csvline = {0}; HashPosition pos; count = zend_hash_num_elements(Z_ARRVAL_P(fields)); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(fields), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(fields), (void **) &field_tmp, &pos) == SUCCESS) { field = **field_tmp; if (Z_TYPE_PP(field_tmp) != IS_STRING) { zval_copy_ctor(&field); convert_to_string(&field); } /* enclose a field that contains a delimiter, an enclosure character, or a newline */ if (FPUTCSV_FLD_CHK(delimiter) || FPUTCSV_FLD_CHK(enclosure) || FPUTCSV_FLD_CHK(escape_char) || FPUTCSV_FLD_CHK('\n') || FPUTCSV_FLD_CHK('\r') || FPUTCSV_FLD_CHK('\t') || FPUTCSV_FLD_CHK(' ') ) { char *ch = Z_STRVAL(field); char *end = ch + Z_STRLEN(field); int escaped = 0; smart_str_appendc(&csvline, enclosure); while (ch < end) { if (*ch == escape_char) { escaped = 1; } else if (!escaped && *ch == enclosure) { smart_str_appendc(&csvline, enclosure); } else { escaped = 0; } smart_str_appendc(&csvline, *ch); ch++; } smart_str_appendc(&csvline, enclosure); } else { smart_str_appendl(&csvline, Z_STRVAL(field), Z_STRLEN(field)); } if (++i != count) { smart_str_appendl(&csvline, &delimiter, 1); } zend_hash_move_forward_ex(Z_ARRVAL_P(fields), &pos); if (Z_TYPE_PP(field_tmp) != IS_STRING) { zval_dtor(&field); } } smart_str_appendc(&csvline, '\n'); smart_str_0(&csvline); ret = php_stream_write(stream, csvline.c, csvline.len); smart_str_free(&csvline); return ret; } /* }}} */ /* {{{ proto array fgetcsv(resource fp [,int length [, string delimiter [, string enclosure [, string escape]]]]) Get line from file pointer and parse for CSV fields */ PHP_FUNCTION(fgetcsv) { char delimiter = ','; /* allow this to be set as parameter */ char enclosure = '"'; /* allow this to be set as parameter */ char escape = '\\'; /* first section exactly as php_fgetss */ long len = 0; size_t buf_len; char *buf; php_stream *stream; { zval *fd, **len_zv = NULL; char *delimiter_str = NULL; int delimiter_str_len = 0; char *enclosure_str = NULL; int enclosure_str_len = 0; char *escape_str = NULL; int escape_str_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|Zsss", &fd, &len_zv, &delimiter_str, &delimiter_str_len, &enclosure_str, &enclosure_str_len, &escape_str, &escape_str_len) == FAILURE ) { return; } if (delimiter_str != NULL) { /* Make sure that there is at least one character in string */ if (delimiter_str_len < 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } else if (delimiter_str_len > 1) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "delimiter must be a single character"); } /* use first character from string */ delimiter = delimiter_str[0]; } if (enclosure_str != NULL) { if (enclosure_str_len < 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } else if (enclosure_str_len > 1) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "enclosure must be a single character"); } /* use first character from string */ enclosure = enclosure_str[0]; } if (escape_str != NULL) { if (escape_str_len < 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be character"); RETURN_FALSE; } else if (escape_str_len > 1) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "escape must be a single character"); } escape = escape_str[0]; } if (len_zv != NULL && Z_TYPE_PP(len_zv) != IS_NULL) { convert_to_long_ex(len_zv); len = Z_LVAL_PP(len_zv); if (len < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter may not be negative"); RETURN_FALSE; } else if (len == 0) { len = -1; } } else { len = -1; } PHP_STREAM_TO_ZVAL(stream, &fd); } if (len < 0) { if ((buf = php_stream_get_line(stream, NULL, 0, &buf_len)) == NULL) { RETURN_FALSE; } } else { buf = emalloc(len + 1); if (php_stream_get_line(stream, buf, len + 1, &buf_len) == NULL) { efree(buf); RETURN_FALSE; } } php_fgetcsv(stream, delimiter, enclosure, escape, buf_len, buf, return_value TSRMLS_CC); } /* }}} */ PHPAPI void php_fgetcsv(php_stream *stream, char delimiter, char enclosure, char escape_char, size_t buf_len, char *buf, zval *return_value TSRMLS_DC) /* {{{ */ { char *temp, *tptr, *bptr, *line_end, *limit; size_t temp_len, line_end_len; int inc_len; zend_bool first_field = 1; /* initialize internal state */ php_ignore_value(php_mblen(NULL, 0)); /* Now into new section that parses buf for delimiter/enclosure fields */ /* Strip trailing space from buf, saving end of line in case required for enclosure field */ bptr = buf; tptr = (char *)php_fgetcsv_lookup_trailing_spaces(buf, buf_len, delimiter TSRMLS_CC); line_end_len = buf_len - (size_t)(tptr - buf); line_end = limit = tptr; /* reserve workspace for building each individual field */ temp_len = buf_len; temp = emalloc(temp_len + line_end_len + 1); /* Initialize return array */ array_init(return_value); /* Main loop to read CSV fields */ /* NB this routine will return a single null entry for a blank line */ do { char *comp_end, *hunk_begin; tptr = temp; inc_len = (bptr < limit ? (*bptr == '\0' ? 1: php_mblen(bptr, limit - bptr)): 0); if (inc_len == 1) { char *tmp = bptr; while ((*tmp != delimiter) && isspace((int)*(unsigned char *)tmp)) { tmp++; } if (*tmp == enclosure) { bptr = tmp; } } if (first_field && bptr == line_end) { add_next_index_null(return_value); break; } first_field = 0; /* 2. Read field, leaving bptr pointing at start of next field */ if (inc_len != 0 && *bptr == enclosure) { int state = 0; bptr++; /* move on to first character in field */ hunk_begin = bptr; /* 2A. handle enclosure delimited field */ for (;;) { switch (inc_len) { case 0: switch (state) { case 2: memcpy(tptr, hunk_begin, bptr - hunk_begin - 1); tptr += (bptr - hunk_begin - 1); hunk_begin = bptr; goto quit_loop_2; case 1: memcpy(tptr, hunk_begin, bptr - hunk_begin); tptr += (bptr - hunk_begin); hunk_begin = bptr; /* break is omitted intentionally */ case 0: { char *new_buf; size_t new_len; char *new_temp; if (hunk_begin != line_end) { memcpy(tptr, hunk_begin, bptr - hunk_begin); tptr += (bptr - hunk_begin); hunk_begin = bptr; } /* add the embedded line end to the field */ memcpy(tptr, line_end, line_end_len); tptr += line_end_len; if (stream == NULL) { goto quit_loop_2; } else if ((new_buf = php_stream_get_line(stream, NULL, 0, &new_len)) == NULL) { /* we've got an unterminated enclosure, * assign all the data from the start of * the enclosure to end of data to the * last element */ if ((size_t)temp_len > (size_t)(limit - buf)) { goto quit_loop_2; } zval_dtor(return_value); RETVAL_FALSE; goto out; } temp_len += new_len; new_temp = erealloc(temp, temp_len); tptr = new_temp + (size_t)(tptr - temp); temp = new_temp; efree(buf); buf_len = new_len; bptr = buf = new_buf; hunk_begin = buf; line_end = limit = (char *)php_fgetcsv_lookup_trailing_spaces(buf, buf_len, delimiter TSRMLS_CC); line_end_len = buf_len - (size_t)(limit - buf); state = 0; } break; } break; case -2: case -1: php_ignore_value(php_mblen(NULL, 0)); /* break is omitted intentionally */ case 1: /* we need to determine if the enclosure is * 'real' or is it escaped */ switch (state) { case 1: /* escaped */ bptr++; state = 0; break; case 2: /* embedded enclosure ? let's check it */ if (*bptr != enclosure) { /* real enclosure */ memcpy(tptr, hunk_begin, bptr - hunk_begin - 1); tptr += (bptr - hunk_begin - 1); hunk_begin = bptr; goto quit_loop_2; } memcpy(tptr, hunk_begin, bptr - hunk_begin); tptr += (bptr - hunk_begin); bptr++; hunk_begin = bptr; state = 0; break; default: if (*bptr == enclosure) { state = 2; } else if (*bptr == escape_char) { state = 1; } bptr++; break; } break; default: switch (state) { case 2: /* real enclosure */ memcpy(tptr, hunk_begin, bptr - hunk_begin - 1); tptr += (bptr - hunk_begin - 1); hunk_begin = bptr; goto quit_loop_2; case 1: bptr += inc_len; memcpy(tptr, hunk_begin, bptr - hunk_begin); tptr += (bptr - hunk_begin); hunk_begin = bptr; break; default: bptr += inc_len; break; } break; } inc_len = (bptr < limit ? (*bptr == '\0' ? 1: php_mblen(bptr, limit - bptr)): 0); } quit_loop_2: /* look up for a delimiter */ for (;;) { switch (inc_len) { case 0: goto quit_loop_3; case -2: case -1: inc_len = 1; php_ignore_value(php_mblen(NULL, 0)); /* break is omitted intentionally */ case 1: if (*bptr == delimiter) { goto quit_loop_3; } break; default: break; } bptr += inc_len; inc_len = (bptr < limit ? (*bptr == '\0' ? 1: php_mblen(bptr, limit - bptr)): 0); } quit_loop_3: memcpy(tptr, hunk_begin, bptr - hunk_begin); tptr += (bptr - hunk_begin); bptr += inc_len; comp_end = tptr; } else { /* 2B. Handle non-enclosure field */ hunk_begin = bptr; for (;;) { switch (inc_len) { case 0: goto quit_loop_4; case -2: case -1: inc_len = 1; php_ignore_value(php_mblen(NULL, 0)); /* break is omitted intentionally */ case 1: if (*bptr == delimiter) { goto quit_loop_4; } break; default: break; } bptr += inc_len; inc_len = (bptr < limit ? (*bptr == '\0' ? 1: php_mblen(bptr, limit - bptr)): 0); } quit_loop_4: memcpy(tptr, hunk_begin, bptr - hunk_begin); tptr += (bptr - hunk_begin); comp_end = (char *)php_fgetcsv_lookup_trailing_spaces(temp, tptr - temp, delimiter TSRMLS_CC); if (*bptr == delimiter) { bptr++; } } /* 3. Now pass our field back to php */ *comp_end = '\0'; add_next_index_stringl(return_value, temp, comp_end - temp, 1); } while (inc_len > 0); out: efree(temp); if (stream) { efree(buf); } } /* }}} */ #if (!defined(__BEOS__) && !defined(NETWARE) && HAVE_REALPATH) || defined(ZTS) /* {{{ proto string realpath(string path) Return the resolved path */ PHP_FUNCTION(realpath) { char *filename; int filename_len; char resolved_path_buff[MAXPATHLEN]; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &filename, &filename_len) == FAILURE) { return; } if (VCWD_REALPATH(filename, resolved_path_buff)) { if (php_check_open_basedir(resolved_path_buff TSRMLS_CC)) { RETURN_FALSE; } #ifdef ZTS if (VCWD_ACCESS(resolved_path_buff, F_OK)) { RETURN_FALSE; } #endif RETURN_STRING(resolved_path_buff, 1); } else { RETURN_FALSE; } } /* }}} */ #endif /* See http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.2 */ #define PHP_META_HTML401_CHARS "-_.:" /* {{{ php_next_meta_token Tokenizes an HTML file for get_meta_tags */ php_meta_tags_token php_next_meta_token(php_meta_tags_data *md TSRMLS_DC) { int ch = 0, compliment; char buff[META_DEF_BUFSIZE + 1]; memset((void *)buff, 0, META_DEF_BUFSIZE + 1); while (md->ulc || (!php_stream_eof(md->stream) && (ch = php_stream_getc(md->stream)))) { if (php_stream_eof(md->stream)) { break; } if (md->ulc) { ch = md->lc; md->ulc = 0; } switch (ch) { case '<': return TOK_OPENTAG; break; case '>': return TOK_CLOSETAG; break; case '=': return TOK_EQUAL; break; case '/': return TOK_SLASH; break; case '\'': case '"': compliment = ch; md->token_len = 0; while (!php_stream_eof(md->stream) && (ch = php_stream_getc(md->stream)) && ch != compliment && ch != '<' && ch != '>') { buff[(md->token_len)++] = ch; if (md->token_len == META_DEF_BUFSIZE) { break; } } if (ch == '<' || ch == '>') { /* Was just an apostrohpe */ md->ulc = 1; md->lc = ch; } /* We don't need to alloc unless we are in a meta tag */ if (md->in_meta) { md->token_data = (char *) emalloc(md->token_len + 1); memcpy(md->token_data, buff, md->token_len+1); } return TOK_STRING; break; case '\n': case '\r': case '\t': break; case ' ': return TOK_SPACE; break; default: if (isalnum(ch)) { md->token_len = 0; buff[(md->token_len)++] = ch; while (!php_stream_eof(md->stream) && (ch = php_stream_getc(md->stream)) && (isalnum(ch) || strchr(PHP_META_HTML401_CHARS, ch))) { buff[(md->token_len)++] = ch; if (md->token_len == META_DEF_BUFSIZE) { break; } } /* This is ugly, but we have to replace ungetc */ if (!isalpha(ch) && ch != '-') { md->ulc = 1; md->lc = ch; } md->token_data = (char *) emalloc(md->token_len + 1); memcpy(md->token_data, buff, md->token_len+1); return TOK_ID; } else { return TOK_OTHER; } break; } } return TOK_EOF; } /* }}} */ #ifdef HAVE_FNMATCH /* {{{ proto bool fnmatch(string pattern, string filename [, int flags]) Match filename against pattern */ PHP_FUNCTION(fnmatch) { char *pattern, *filename; int pattern_len, filename_len; long flags = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "pp|l", &pattern, &pattern_len, &filename, &filename_len, &flags) == FAILURE) { return; } if (filename_len >= MAXPATHLEN) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Filename exceeds the maximum allowed length of %d characters", MAXPATHLEN); RETURN_FALSE; } if (pattern_len >= MAXPATHLEN) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Pattern exceeds the maximum allowed length of %d characters", MAXPATHLEN); RETURN_FALSE; } RETURN_BOOL( ! fnmatch( pattern, filename, flags )); } /* }}} */ #endif /* {{{ proto string sys_get_temp_dir() Returns directory path used for temporary files */ PHP_FUNCTION(sys_get_temp_dir) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_STRING((char *)php_get_temporary_directory(), 1); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-11-15-236120d80e-fb37f3b20d.c
manybugs_data_49
/* reassemble.c * Routines for {fragment,segment} reassembly * * $Id: reassemble.c 37112 2011-05-13 05:19:23Z etxrab $ * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <string.h> #include <epan/packet.h> #include <epan/reassemble.h> #include <epan/emem.h> #include <epan/dissectors/packet-dcerpc.h> typedef struct _fragment_key { address src; address dst; guint32 id; } fragment_key; typedef struct _dcerpc_fragment_key { address src; address dst; guint32 id; e_uuid_t act_id; } dcerpc_fragment_key; #if GLIB_CHECK_VERSION(2,10,0) #else static GMemChunk *fragment_key_chunk = NULL; static GMemChunk *fragment_data_chunk = NULL; static GMemChunk *dcerpc_fragment_key_chunk = NULL; static int fragment_init_count = 200; #endif static void LINK_FRAG(fragment_data *fd_head,fragment_data *fd) { fragment_data *fd_i; /* add fragment to list, keep list sorted */ for(fd_i= fd_head; fd_i->next;fd_i=fd_i->next) { if (fd->offset < fd_i->next->offset ) break; } fd->next=fd_i->next; fd_i->next=fd; } /* copy a fragment key to heap store to insert in the hash */ static void *fragment_key_copy(const void *k) { const fragment_key* key = (const fragment_key*) k; #if GLIB_CHECK_VERSION(2,10,0) fragment_key *new_key = g_slice_new(fragment_key); #else fragment_key *new_key = g_mem_chunk_alloc(fragment_key_chunk); #endif COPY_ADDRESS(&new_key->src, &key->src); COPY_ADDRESS(&new_key->dst, &key->dst); new_key->id = key->id; return new_key; } /* copy a dcerpc fragment key to heap store to insert in the hash */ static void *dcerpc_fragment_key_copy(const void *k) { const dcerpc_fragment_key* key = (const dcerpc_fragment_key*) k; #if GLIB_CHECK_VERSION(2,10,0) dcerpc_fragment_key *new_key = g_slice_new(dcerpc_fragment_key); #else dcerpc_fragment_key *new_key = g_mem_chunk_alloc(dcerpc_fragment_key_chunk); #endif COPY_ADDRESS(&new_key->src, &key->src); COPY_ADDRESS(&new_key->dst, &key->dst); new_key->id = key->id; new_key->act_id = key->act_id; return new_key; } static gint fragment_equal(gconstpointer k1, gconstpointer k2) { const fragment_key* key1 = (const fragment_key*) k1; const fragment_key* key2 = (const fragment_key*) k2; /*key.id is the first item to compare since item is most likely to differ between sessions, thus shortcircuiting the comparasion of addresses. */ return ( ( (key1->id == key2->id) && (ADDRESSES_EQUAL(&key1->src, &key2->src)) && (ADDRESSES_EQUAL(&key1->dst, &key2->dst)) ) ? TRUE : FALSE); } static guint fragment_hash(gconstpointer k) { const fragment_key* key = (const fragment_key*) k; guint hash_val; /* int i; */ hash_val = 0; /* More than likely: in most captures src and dst addresses are the same, and would hash the same. We only use id as the hash as an optimization. for (i = 0; i < key->src.len; i++) hash_val += key->src.data[i]; for (i = 0; i < key->dst.len; i++) hash_val += key->dst.data[i]; */ hash_val += key->id; return hash_val; } static gint dcerpc_fragment_equal(gconstpointer k1, gconstpointer k2) { const dcerpc_fragment_key* key1 = (const dcerpc_fragment_key*) k1; const dcerpc_fragment_key* key2 = (const dcerpc_fragment_key*) k2; /*key.id is the first item to compare since item is most likely to differ between sessions, thus shortcircuiting the comparison of addresses. */ return (((key1->id == key2->id) && (ADDRESSES_EQUAL(&key1->src, &key2->src)) && (ADDRESSES_EQUAL(&key1->dst, &key2->dst)) && (memcmp (&key1->act_id, &key2->act_id, sizeof (e_uuid_t)) == 0)) ? TRUE : FALSE); } static guint dcerpc_fragment_hash(gconstpointer k) { const dcerpc_fragment_key* key = (const dcerpc_fragment_key*) k; guint hash_val; hash_val = 0; hash_val += key->id; hash_val += key->act_id.Data1; hash_val += key->act_id.Data2 << 16; hash_val += key->act_id.Data3; return hash_val; } typedef struct _reassembled_key { guint32 id; guint32 frame; } reassembled_key; static gint reassembled_equal(gconstpointer k1, gconstpointer k2) { const reassembled_key* key1 = (const reassembled_key*) k1; const reassembled_key* key2 = (const reassembled_key*) k2; /* * We assume that the frame numbers are unlikely to be equal, * so we check them first. */ return key1->frame == key2->frame && key1->id == key2->id; } static guint reassembled_hash(gconstpointer k) { const reassembled_key* key = (const reassembled_key*) k; return key->frame; } /* * For a fragment hash table entry, free the associated fragments. * If slices are used (GLIB >= 2.10) the entry value (fd_chain) is * freed herein and the entry is freed when fragment_free_key() * [or dcerpc_fragment_free_key()] is called (as a consequence of * returning TRUE from this function). * If mem_chunks are used, free the address data to which the key * refers; the the actual key and value structures get freed * by "reassemble_cleanup()"). */ static gboolean free_all_fragments(gpointer key_arg _U_, gpointer value, gpointer user_data _U_) { fragment_data *fd_head, *tmp_fd; #if GLIB_CHECK_VERSION(2,10,0) /* If Glib version => 2.10 we do g_hash_table_new_full() and supply a function * to free the key and the addresses. */ #else fragment_key *key = key_arg; /* * Grr. I guess the theory here is that freeing * something sure as heck modifies it, so you * want to ban attempts to free it, but, alas, * if we make the "data" field of an "address" * structure not a "const", the compiler whines if * we try to make it point into the data for a packet, * as that's a "const" array (and should be, as dissectors * shouldn't trash it). * * So we cast the complaint into oblivion, and rely on * the fact that these addresses are known to have had * their data mallocated, i.e. they don't point into, * say, the middle of the data for a packet. */ g_free((gpointer)key->src.data); g_free((gpointer)key->dst.data); #endif for (fd_head = value; fd_head != NULL; fd_head = tmp_fd) { tmp_fd=fd_head->next; if(fd_head->data && !(fd_head->flags&FD_NOT_MALLOCED)) g_free(fd_head->data); #if GLIB_CHECK_VERSION(2,10,0) g_slice_free(fragment_data, fd_head); #endif } return TRUE; } /* ------------------------- */ static fragment_data *new_head(const guint32 flags) { fragment_data *fd_head; /* If head/first structure in list only holds no other data than * 'datalen' then we don't have to change the head of the list * even if we want to keep it sorted */ #if GLIB_CHECK_VERSION(2,10,0) fd_head=g_slice_new0(fragment_data); #else fd_head=g_mem_chunk_alloc0(fragment_data_chunk); #endif fd_head->flags=flags; return fd_head; } /* * For a reassembled-packet hash table entry, free the fragment data * to which the value refers. * (Pre glib 2.10:The actual value structures get freed by "reassemble_cleanup()".) * http://www.wireshark.org/lists/wireshark-dev/200910/msg00074.html */ static gboolean free_all_reassembled_fragments(gpointer key_arg, gpointer value, gpointer user_data _U_) { fragment_data *fd_head, *tmp_fd; reassembled_key *key = (reassembled_key *)key_arg; for (fd_head = value; fd_head != NULL; fd_head = tmp_fd) { tmp_fd=fd_head->next; if(fd_head->data && !(fd_head->flags&FD_NOT_MALLOCED)) { g_free(fd_head->data); /* * A reassembled packet is inserted into the * hash table once for every frame that made * up the reassembled packet; clear the data * pointer so that we only free the data the * first time we see it. */ fd_head->data = NULL; } #if GLIB_CHECK_VERSION(2,10,0) if(key->frame == fd_head->reassembled_in){ g_slice_free(fragment_data, fd_head); } #endif } return TRUE; } #if GLIB_CHECK_VERSION(2,10,0) static void fragment_free_key(void *ptr) { fragment_key *key = (fragment_key *)ptr; if(key){ /* * Free up the copies of the addresses from the old key. */ g_free((gpointer)key->src.data); g_free((gpointer)key->dst.data); g_slice_free(fragment_key, key); } } static void dcerpc_fragment_free_key(void *ptr) { dcerpc_fragment_key *key = (dcerpc_fragment_key *)ptr; if(key){ /* * Free up the copies of the addresses from the old key. */ g_free((gpointer)key->src.data); g_free((gpointer)key->dst.data); g_slice_free(dcerpc_fragment_key, key); } } #endif #if GLIB_CHECK_VERSION(2,10,0) static void reassembled_key_free(void *ptr) { reassembled_key *key = (reassembled_key *)ptr; g_slice_free(reassembled_key, key); } #endif /* * Initialize a fragment table. */ void fragment_table_init(GHashTable **fragment_table) { if (*fragment_table != NULL) { /* * The fragment hash table exists. * * Remove all entries and free fragment data for each entry. * * If slices are used (GLIB >= 2.10) * the keys are freed by calling fragment_free_key() * and the values are freed in free_all_fragments(). * * If mem_chunks are used, the key and value data * are freed by "reassemble_cleanup()". free_all_fragments() * will free the adrress data associated with the key */ g_hash_table_foreach_remove(*fragment_table, free_all_fragments, NULL); } else { #if GLIB_CHECK_VERSION(2,10,0) /* The fragment table does not exist. Create it */ *fragment_table = g_hash_table_new_full(fragment_hash, fragment_equal, fragment_free_key, NULL); #else /* The fragment table does not exist. Create it */ *fragment_table = g_hash_table_new(fragment_hash, fragment_equal); #endif } } void dcerpc_fragment_table_init(GHashTable **fragment_table) { if (*fragment_table != NULL) { /* * The fragment hash table exists. * * Remove all entries and free fragment data for each entry. * * If slices are used (GLIB >= 2.10) * the keys are freed by calling dcerpc_fragment_free_key() * and the values are freed in free_all_fragments(). * * If mem_chunks are used, the key and value data * are freed by "reassemble_cleanup()". free_all_fragments() * will free the adrress data associated with the key */ g_hash_table_foreach_remove(*fragment_table, free_all_fragments, NULL); } else { #if GLIB_CHECK_VERSION(2,10,0) /* The fragment table does not exist. Create it */ *fragment_table = g_hash_table_new_full(dcerpc_fragment_hash, dcerpc_fragment_equal, dcerpc_fragment_free_key, NULL); #else /* The fragment table does not exist. Create it */ *fragment_table = g_hash_table_new(dcerpc_fragment_hash, dcerpc_fragment_equal); #endif } } /* * Initialize a reassembled-packet table. */ void reassembled_table_init(GHashTable **reassembled_table) { if (*reassembled_table != NULL) { /* * The reassembled-packet hash table exists. * * Remove all entries and free reassembled packet * data for each entry. (The key data is freed * by "reassemble_cleanup()".) */ g_hash_table_foreach_remove(*reassembled_table, free_all_reassembled_fragments, NULL); } else { /* The fragment table does not exist. Create it */ #if GLIB_CHECK_VERSION(2,10,0) *reassembled_table = g_hash_table_new_full(reassembled_hash, reassembled_equal, reassembled_key_free, NULL); #else *reassembled_table = g_hash_table_new(reassembled_hash, reassembled_equal); #endif } } /* * Free up all space allocated for fragment keys and data and * reassembled keys. */ void reassemble_cleanup(void) { #if GLIB_CHECK_VERSION(2,10,0) #else if (fragment_key_chunk != NULL) g_mem_chunk_destroy(fragment_key_chunk); if (dcerpc_fragment_key_chunk != NULL) g_mem_chunk_destroy(dcerpc_fragment_key_chunk); if (fragment_data_chunk != NULL) g_mem_chunk_destroy(fragment_data_chunk); fragment_key_chunk = NULL; dcerpc_fragment_key_chunk = NULL; fragment_data_chunk = NULL; #endif } void reassemble_init(void) { #if GLIB_CHECK_VERSION(2,10,0) #else fragment_key_chunk = g_mem_chunk_new("fragment_key_chunk", sizeof(fragment_key), fragment_init_count * sizeof(fragment_key), G_ALLOC_AND_FREE); dcerpc_fragment_key_chunk = g_mem_chunk_new("dcerpc_fragment_key_chunk", sizeof(dcerpc_fragment_key), fragment_init_count * sizeof(dcerpc_fragment_key), G_ALLOC_AND_FREE); fragment_data_chunk = g_mem_chunk_new("fragment_data_chunk", sizeof(fragment_data), fragment_init_count * sizeof(fragment_data), G_ALLOC_ONLY); #endif } /* This function cleans up the stored state and removes the reassembly data and * (with one exception) all allocated memory for matching reassembly. * * The exception is : * If the PDU was already completely reassembled, then the buffer containing the * reassembled data WILL NOT be free()d, and the pointer to that buffer will be * returned. * Othervise the function will return NULL. * * So, if you call fragment_delete and it returns non-NULL, YOU are responsible to * g_free() that buffer. */ unsigned char * fragment_delete(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table) { fragment_data *fd_head, *fd; fragment_key key; unsigned char *data=NULL; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup(fragment_table, &key); if(fd_head==NULL){ /* We do not recognize this as a PDU we have seen before. return */ return NULL; } data=fd_head->data; /* loop over all partial fragments and free any buffers */ for(fd=fd_head->next;fd;){ fragment_data *tmp_fd; tmp_fd=fd->next; if( !(fd->flags&FD_NOT_MALLOCED) ) g_free(fd->data); #if GLIB_CHECK_VERSION(2,10,0) g_slice_free(fragment_data, fd); #else g_mem_chunk_free(fragment_data_chunk, fd); #endif fd=tmp_fd; } #if GLIB_CHECK_VERSION(2,10,0) g_slice_free(fragment_data, fd_head); #else g_mem_chunk_free(fragment_data_chunk, fd_head); #endif g_hash_table_remove(fragment_table, &key); return data; } /* This function is used to check if there is partial or completed reassembly state * matching this packet. I.e. Is there reassembly going on or not for this packet? */ fragment_data * fragment_get(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table) { fragment_data *fd_head; fragment_key key; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup(fragment_table, &key); return fd_head; } /* id *must* be the frame number for this to work! */ fragment_data * fragment_get_reassembled(const guint32 id, GHashTable *reassembled_table) { fragment_data *fd_head; reassembled_key key; /* create key to search hash with */ key.frame = id; key.id = id; fd_head = g_hash_table_lookup(reassembled_table, &key); return fd_head; } fragment_data * fragment_get_reassembled_id(const packet_info *pinfo, const guint32 id, GHashTable *reassembled_table) { fragment_data *fd_head; reassembled_key key; /* create key to search hash with */ key.frame = pinfo->fd->num; key.id = id; fd_head = g_hash_table_lookup(reassembled_table, &key); return fd_head; } /* This function can be used to explicitly set the total length (if known) * for reassembly of a PDU. * This is useful for reassembly of PDUs where one may have the total length specified * in the first fragment instead of as for, say, IPv4 where a flag indicates which * is the last fragment. * * Such protocols might fragment_add with a more_frags==TRUE for every fragment * and just tell the reassembly engine the expected total length of the reassembled data * using fragment_set_tot_len immediately after doing fragment_add for the first packet. * * Note that for FD_BLOCKSEQUENCE tot_len is the index for the tail fragment. * i.e. since the block numbers start at 0, if we specify tot_len==2, that * actually means we want to defragment 3 blocks, block 0, 1 and 2. */ void fragment_set_tot_len(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, const guint32 tot_len) { fragment_data *fd_head; fragment_key key; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup(fragment_table, &key); if(fd_head){ fd_head->datalen = tot_len; fd_head->flags |= FD_DATALEN_SET; } return; } guint32 fragment_get_tot_len(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table) { fragment_data *fd_head; fragment_key key; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup(fragment_table, &key); if(fd_head){ return fd_head->datalen; } return 0; } /* This function will set the partial reassembly flag for a fh. When this function is called, the fh MUST already exist, i.e. the fh MUST be created by the initial call to fragment_add() before this function is called. Also note that this function MUST be called to indicate a fh will be extended (increase the already stored data) */ void fragment_set_partial_reassembly(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table) { fragment_data *fd_head; fragment_key key; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup(fragment_table, &key); /* * XXX - why not do all the stuff done early in "fragment_add_work()", * turning off FD_DEFRAGMENTED and pointing the fragments' data * pointers to the appropriate part of the already-reassembled * data, and clearing the data length and "reassembled in" frame * number, here? We currently have a hack in the TCP dissector * not to set the "reassembled in" value if the "partial reassembly" * flag is set, so that in the first pass through the packets * we don't falsely set a packet as reassembled in that packet * if the dissector decided that even more reassembly was needed. */ if(fd_head){ fd_head->flags |= FD_PARTIAL_REASSEMBLY; } } /* * This function gets rid of an entry from a fragment table, given * a pointer to the key for that entry; it also frees up the key * and the addresses in it. * Note: If we use slices keys are freed by fragment_free_key() [or dcerpc_fragment_free_key()] being called * during g_hash_table_remove(). */ static void fragment_unhash(GHashTable *fragment_table, fragment_key *key) { /* * Remove the entry from the fragment table. */ g_hash_table_remove(fragment_table, key); /* * Free the key itself. */ #if GLIB_CHECK_VERSION(2,10,0) #else /* * Free up the copies of the addresses from the old key. */ g_free((gpointer)key->src.data); g_free((gpointer)key->dst.data); g_mem_chunk_free(fragment_key_chunk, key); #endif } /* * This function adds fragment_data structure to a reassembled-packet * hash table, using the frame numbers of each of the frames from * which it was reassembled as keys, and sets the "reassembled_in" * frame number. */ static void fragment_reassembled(fragment_data *fd_head, const packet_info *pinfo, GHashTable *reassembled_table, const guint32 id) { reassembled_key *new_key; fragment_data *fd; if (fd_head->next == NULL) { /* * This was not fragmented, so there's no fragment * table; just hash it using the current frame number. */ #if GLIB_CHECK_VERSION(2,10,0) new_key = g_slice_new(reassembled_key); #else new_key = se_alloc(sizeof(reassembled_key)); #endif new_key->frame = pinfo->fd->num; new_key->id = id; g_hash_table_insert(reassembled_table, new_key, fd_head); } else { /* * Hash it with the frame numbers for all the frames. */ for (fd = fd_head->next; fd != NULL; fd = fd->next){ #if GLIB_CHECK_VERSION(2,10,0) new_key = g_slice_new(reassembled_key); #else new_key = se_alloc(sizeof(reassembled_key)); #endif new_key->frame = fd->frame; new_key->id = id; g_hash_table_insert(reassembled_table, new_key, fd_head); } } fd_head->flags |= FD_DEFRAGMENTED; fd_head->reassembled_in = pinfo->fd->num; } /* * This function adds a new fragment to the fragment hash table. * If this is the first fragment seen for this datagram, a new entry * is created in the hash table, otherwise this fragment is just added * to the linked list of fragments for this packet. * The list of fragments for a specific datagram is kept sorted for * easier handling. * * Returns a pointer to the head of the fragment data list if we have all the * fragments, NULL otherwise. * * This function assumes frag_offset being a byte offset into the defragment * packet. * * 01-2002 * Once the fh is defragmented (= FD_DEFRAGMENTED set), it can be * extended using the FD_PARTIAL_REASSEMBLY flag. This flag should be set * using fragment_set_partial_reassembly() before calling fragment_add * with the new fragment. FD_TOOLONGFRAGMENT and FD_MULTIPLETAILS flags * are lowered when a new extension process is started. */ static gboolean fragment_add_work(fragment_data *fd_head, tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 frag_offset, const guint32 frag_data_len, const gboolean more_frags) { fragment_data *fd; fragment_data *fd_i; guint32 max, dfpos; unsigned char *old_data; /* create new fd describing this fragment */ #if GLIB_CHECK_VERSION(2,10,0) fd = g_slice_new(fragment_data); #else fd = g_mem_chunk_alloc(fragment_data_chunk); #endif fd->next = NULL; fd->flags = 0; fd->frame = pinfo->fd->num; if (fd->frame > fd_head->frame) fd_head->frame = fd->frame; fd->offset = frag_offset; fd->len = frag_data_len; fd->data = NULL; /* * If it was already defragmented and this new fragment goes beyond * data limits, set flag in already empty fds & point old fds to malloc'ed data. */ if(fd_head->flags & FD_DEFRAGMENTED && (frag_offset+frag_data_len) >= fd_head->datalen && fd_head->flags & FD_PARTIAL_REASSEMBLY){ for(fd_i=fd_head->next; fd_i; fd_i=fd_i->next){ if( !fd_i->data ) { fd_i->data = fd_head->data + fd_i->offset; fd_i->flags |= FD_NOT_MALLOCED; } fd_i->flags &= (~FD_TOOLONGFRAGMENT) & (~FD_MULTIPLETAILS); } fd_head->flags &= ~(FD_DEFRAGMENTED|FD_PARTIAL_REASSEMBLY|FD_DATALEN_SET); fd_head->flags &= (~FD_TOOLONGFRAGMENT) & (~FD_MULTIPLETAILS); fd_head->datalen=0; fd_head->reassembled_in=0; } if (!more_frags) { /* * This is the tail fragment in the sequence. */ if (fd_head->flags & FD_DATALEN_SET) { /* ok we have already seen other tails for this packet * it might be a duplicate. */ if (fd_head->datalen != (fd->offset + fd->len) ){ /* Oops, this tail indicates a different packet * len than the previous ones. Something's wrong. */ fd->flags |= FD_MULTIPLETAILS; fd_head->flags |= FD_MULTIPLETAILS; } } else { /* this was the first tail fragment, now we know the * length of the packet */ fd_head->datalen = fd->offset + fd->len; fd_head->flags |= FD_DATALEN_SET; } } /* If the packet is already defragmented, this MUST be an overlap. * The entire defragmented packet is in fd_head->data. * Even if we have previously defragmented this packet, we still * check it. Someone might play overlap and TTL games. */ if (fd_head->flags & FD_DEFRAGMENTED) { guint32 end_offset = fd->offset + fd->len; fd->flags |= FD_OVERLAP; fd_head->flags |= FD_OVERLAP; /* make sure it's not too long */ if (end_offset > fd_head->datalen || end_offset < fd->offset || end_offset < fd->len) { fd->flags |= FD_TOOLONGFRAGMENT; fd_head->flags |= FD_TOOLONGFRAGMENT; } /* make sure it doesn't conflict with previous data */ else if ( memcmp(fd_head->data+fd->offset, tvb_get_ptr(tvb,offset,fd->len),fd->len) ){ fd->flags |= FD_OVERLAPCONFLICT; fd_head->flags |= FD_OVERLAPCONFLICT; } /* it was just an overlap, link it and return */ LINK_FRAG(fd_head,fd); return TRUE; } /* If we have reached this point, the packet is not defragmented yet. * Save all payload in a buffer until we can defragment. * XXX - what if we didn't capture the entire fragment due * to a too-short snapshot length? */ fd->data = g_malloc(fd->len); tvb_memcpy(tvb, fd->data, offset, fd->len); LINK_FRAG(fd_head,fd); if( !(fd_head->flags & FD_DATALEN_SET) ){ /* if we dont know the datalen, there are still missing * packets. Cheaper than the check below. */ return FALSE; } /* * Check if we have received the entire fragment. * This is easy since the list is sorted and the head is faked. * * First, we compute the amount of contiguous data that's * available. (The check for fd_i->offset <= max rules out * fragments that don't start before or at the end of the * previous fragment, i.e. fragments that have a gap between * them and the previous fragment.) */ max = 0; for (fd_i=fd_head->next;fd_i;fd_i=fd_i->next) { if ( ((fd_i->offset)<=max) && ((fd_i->offset+fd_i->len)>max) ){ max = fd_i->offset+fd_i->len; } } if (max < (fd_head->datalen)) { /* * The amount of contiguous data we have is less than the * amount of data we're trying to reassemble, so we haven't * received all packets yet. */ return FALSE; } if (max > (fd_head->datalen)) { /*XXX not sure if current fd was the TOOLONG*/ /*XXX is it fair to flag current fd*/ /* oops, too long fragment detected */ fd->flags |= FD_TOOLONGFRAGMENT; fd_head->flags |= FD_TOOLONGFRAGMENT; } /* we have received an entire packet, defragment it and * free all fragments */ /* store old data just in case */ old_data=fd_head->data; fd_head->data = g_malloc(max); /* add all data fragments */ for (dfpos=0,fd_i=fd_head;fd_i;fd_i=fd_i->next) { if (fd_i->len) { /* dfpos is always >= than fd_i->offset */ /* No gaps can exist here, max_loop(above) does this */ /* XXX - true? Can we get fd_i->offset+fd-i->len */ /* overflowing, for example? */ /* Actually: there is at least one pathological case wherein there can be fragments * on the list which are for offsets greater than max (i.e.: following a gap after max). * (Apparently a "DESEGMENT_UNTIL_FIN" was involved wherein the FIN packet had an offset * less than the highest fragment offset seen. [Seen from a fuzz-test: bug #2470]). * Note that the "overlap" compare must only be done for fragments with (offset+len) <= max * and thus within the newly g_malloc'd buffer. */ if ( fd_i->offset+fd_i->len > dfpos ) { if (fd_i->offset+fd_i->len > max) g_warning("Reassemble error in frame %u: offset %u + len %u > max %u", pinfo->fd->num, fd_i->offset, fd_i->len, max); else if (dfpos < fd_i->offset) g_warning("Reassemble error in frame %u: dfpos %u < offset %u", pinfo->fd->num, dfpos, fd_i->offset); else if (dfpos-fd_i->offset > fd_i->len) g_warning("Reassemble error in frame %u: dfpos %u - offset %u > len %u", pinfo->fd->num, dfpos, fd_i->offset, fd_i->len); else if (!fd_head->data) g_warning("Reassemble error in frame %u: no data", pinfo->fd->num); else { if (fd_i->offset < dfpos) { fd_i->flags |= FD_OVERLAP; fd_head->flags |= FD_OVERLAP; if ( memcmp(fd_head->data+fd_i->offset, fd_i->data, MIN(fd_i->len,(dfpos-fd_i->offset)) ) ) { fd_i->flags |= FD_OVERLAPCONFLICT; fd_head->flags |= FD_OVERLAPCONFLICT; } } memcpy(fd_head->data+dfpos, fd_i->data+(dfpos-fd_i->offset), fd_i->len-(dfpos-fd_i->offset)); } } else { if (fd_i->offset + fd_i->len < fd_i->offset) /* Integer overflow? */ g_warning("Reassemble error in frame %u: offset %u + len %u < offset", pinfo->fd->num, fd_i->offset, fd_i->len); } if( fd_i->flags & FD_NOT_MALLOCED ) fd_i->flags &= ~FD_NOT_MALLOCED; else g_free(fd_i->data); fd_i->data=NULL; dfpos=MAX(dfpos,(fd_i->offset+fd_i->len)); } } g_free(old_data); /* mark this packet as defragmented. allows us to skip any trailing fragments */ fd_head->flags |= FD_DEFRAGMENTED; fd_head->reassembled_in=pinfo->fd->num; return TRUE; } static fragment_data * fragment_add_common(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, const guint32 frag_offset, const guint32 frag_data_len, const gboolean more_frags, const gboolean check_already_added) { fragment_key key, *new_key; fragment_data *fd_head; fragment_data *fd_item; gboolean already_added=pinfo->fd->flags.visited; /* dissector shouldn't give us garbage tvb info */ DISSECTOR_ASSERT(tvb_bytes_exist(tvb, offset, frag_data_len)); /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup(fragment_table, &key); #if 0 /* debug output of associated fragments. */ /* leave it here for future debugging sessions */ if(strcmp(pinfo->current_proto, "DCERPC") == 0) { printf("proto:%s num:%u id:%u offset:%u len:%u more:%u visited:%u\n", pinfo->current_proto, pinfo->fd->num, id, frag_offset, frag_data_len, more_frags, pinfo->fd->flags.visited); if(fd_head != NULL) { for(fd_item=fd_head->next;fd_item;fd_item=fd_item->next){ printf("fd_frame:%u fd_offset:%u len:%u datalen:%u\n", fd_item->frame, fd_item->offset, fd_item->len, fd_item->datalen); } } } #endif /* * "already_added" is true if "pinfo->fd->flags.visited" is true; * if "pinfo->fd->flags.visited", this isn't the first pass, so * we've already done all the reassembly and added all the * fragments. * * If it's not true, but "check_already_added" is true, just check * if we have seen this fragment before, i.e., if we have already * added it to reassembly. * That can be true even if "pinfo->fd->flags.visited" is false * since we sometimes might call a subdissector multiple times. * As an additional check, just make sure we have not already added * this frame to the reassembly list, if there is a reassembly list; * note that the first item in the reassembly list is not a * fragment, it's a data structure for the reassembled packet. * We don't check it because its "frame" member isn't initialized * to anything, and because it doesn't count in any case. * * And as another additional check, make sure the fragment offsets are * the same, as otherwise we get into trouble if multiple fragments * are in one PDU. */ if (!already_added && check_already_added && fd_head != NULL) { if (pinfo->fd->num <= fd_head->frame) { for(fd_item=fd_head->next;fd_item;fd_item=fd_item->next){ if(pinfo->fd->num==fd_item->frame && frag_offset==fd_item->offset){ already_added=TRUE; } } } } /* have we already added this frame ?*/ if (already_added) { if (fd_head != NULL && fd_head->flags & FD_DEFRAGMENTED) { return fd_head; } else { return NULL; } } if (fd_head==NULL){ /* not found, this must be the first snooped fragment for this * packet. Create list-head. */ fd_head = new_head(0); /* * We're going to use the key to insert the fragment, * so allocate a structure for it, and copy the * addresses, allocating new buffers for the address * data. */ #if GLIB_CHECK_VERSION(2,10,0) new_key = g_slice_new(fragment_key); #else new_key = g_mem_chunk_alloc(fragment_key_chunk); #endif COPY_ADDRESS(&new_key->src, &key.src); COPY_ADDRESS(&new_key->dst, &key.dst); new_key->id = key.id; g_hash_table_insert(fragment_table, new_key, fd_head); } if (fragment_add_work(fd_head, tvb, offset, pinfo, frag_offset, frag_data_len, more_frags)) { /* * Reassembly is complete. */ return fd_head; } else { /* * Reassembly isn't complete. */ return NULL; } } fragment_data * fragment_add(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, const guint32 frag_offset, const guint32 frag_data_len, const gboolean more_frags) { return fragment_add_common(tvb, offset, pinfo, id, fragment_table, frag_offset, frag_data_len, more_frags, TRUE); } /* * For use when you can have multiple fragments in the same frame added * to the same reassembled PDU, e.g. with ONC RPC-over-TCP. */ fragment_data * fragment_add_multiple_ok(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, const guint32 frag_offset, const guint32 frag_data_len, const gboolean more_frags) { return fragment_add_common(tvb, offset, pinfo, id, fragment_table, frag_offset, frag_data_len, more_frags, FALSE); } fragment_data * fragment_add_check(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, GHashTable *reassembled_table, const guint32 frag_offset, const guint32 frag_data_len, const gboolean more_frags) { reassembled_key reass_key; fragment_key key, *new_key, *old_key; gpointer orig_key, value; fragment_data *fd_head; /* * If this isn't the first pass, look for this frame in the table * of reassembled packets. */ if (pinfo->fd->flags.visited) { reass_key.frame = pinfo->fd->num; reass_key.id = id; return g_hash_table_lookup(reassembled_table, &reass_key); } /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; /* Looks up a key in the GHashTable, returning the original key and the associated value * and a gboolean which is TRUE if the key was found. This is useful if you need to free * the memory allocated for the original key, for example before calling g_hash_table_remove() */ if (!g_hash_table_lookup_extended(fragment_table, &key, &orig_key, &value)) { /* not found, this must be the first snooped fragment for this * packet. Create list-head. */ fd_head = new_head(0); /* * We're going to use the key to insert the fragment, * so allocate a structure for it, and copy the * addresses, allocating new buffers for the address * data. */ #if GLIB_CHECK_VERSION(2,10,0) new_key = g_slice_new(fragment_key); #else new_key = g_mem_chunk_alloc(fragment_key_chunk); #endif COPY_ADDRESS(&new_key->src, &key.src); COPY_ADDRESS(&new_key->dst, &key.dst); new_key->id = key.id; g_hash_table_insert(fragment_table, new_key, fd_head); orig_key = new_key; /* for unhashing it later */ } else { /* * We found it. */ fd_head = value; } /* * If this is a short frame, then we can't, and don't, do * reassembly on it. We just give up. */ if (tvb_reported_length(tvb) > tvb_length(tvb)) return NULL; if (fragment_add_work(fd_head, tvb, offset, pinfo, frag_offset, frag_data_len, more_frags)) { /* * Reassembly is complete. * Remove this from the table of in-progress * reassemblies, add it to the table of * reassembled packets, and return it. */ /* * Remove this from the table of in-progress reassemblies, * and free up any memory used for it in that table. */ old_key = orig_key; fragment_unhash(fragment_table, old_key); /* * Add this item to the table of reassembled packets. */ fragment_reassembled(fd_head, pinfo, reassembled_table, id); return fd_head; } else { /* * Reassembly isn't complete. */ return NULL; } } static void fragment_defragment_and_free (fragment_data *fd_head, const packet_info *pinfo) { fragment_data *fd_i = NULL; fragment_data *last_fd = NULL; guint32 dfpos = 0, size = 0; void *old_data = NULL; for(fd_i=fd_head->next;fd_i;fd_i=fd_i->next) { if(!last_fd || last_fd->offset!=fd_i->offset){ size+=fd_i->len; } last_fd=fd_i; } /* store old data in case the fd_i->data pointers refer to it */ old_data=fd_head->data; fd_head->data = g_malloc(size); fd_head->len = size; /* record size for caller */ /* add all data fragments */ last_fd=NULL; for (fd_i=fd_head->next; fd_i; fd_i=fd_i->next) { if (fd_i->len) { if(!last_fd || last_fd->offset != fd_i->offset) { /* First fragment or in-sequence fragment */ memcpy(fd_head->data+dfpos, fd_i->data, fd_i->len); dfpos += fd_i->len; } else { /* duplicate/retransmission/overlap */ fd_i->flags |= FD_OVERLAP; fd_head->flags |= FD_OVERLAP; if(last_fd->len != fd_i->len || memcmp(last_fd->data, fd_i->data, last_fd->len) ) { fd_i->flags |= FD_OVERLAPCONFLICT; fd_head->flags |= FD_OVERLAPCONFLICT; } } } last_fd=fd_i; } /* we have defragmented the pdu, now free all fragments*/ for (fd_i=fd_head->next;fd_i;fd_i=fd_i->next) { if( fd_i->flags & FD_NOT_MALLOCED ) fd_i->flags &= ~FD_NOT_MALLOCED; else g_free(fd_i->data); fd_i->data=NULL; } g_free(old_data); /* mark this packet as defragmented. * allows us to skip any trailing fragments. */ fd_head->flags |= FD_DEFRAGMENTED; fd_head->reassembled_in=pinfo->fd->num; } /* * This function adds a new fragment to the entry for a reassembly * operation. * * The list of fragments for a specific datagram is kept sorted for * easier handling. * * Returns TRUE if we have all the fragments, FALSE otherwise. * * This function assumes frag_number being a block sequence number. * The bsn for the first block is 0. */ static gboolean fragment_add_seq_work(fragment_data *fd_head, tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags, const guint32 flags _U_) { fragment_data *fd; fragment_data *fd_i; fragment_data *last_fd; guint32 max, dfpos; /* if the partial reassembly flag has been set, and we are extending * the pdu, un-reassemble the pdu. This means pointing old fds to malloc'ed data. */ if(fd_head->flags & FD_DEFRAGMENTED && frag_number >= fd_head->datalen && fd_head->flags & FD_PARTIAL_REASSEMBLY){ guint32 lastdfpos = 0; dfpos = 0; for(fd_i=fd_head->next; fd_i; fd_i=fd_i->next){ if( !fd_i->data ) { if( fd_i->flags & FD_OVERLAP ) { /* this is a duplicate of the previous * fragment. */ fd_i->data = fd_head->data + lastdfpos; } else { fd_i->data = fd_head->data + dfpos; lastdfpos = dfpos; dfpos += fd_i->len; } fd_i->flags |= FD_NOT_MALLOCED; } fd_i->flags &= (~FD_TOOLONGFRAGMENT) & (~FD_MULTIPLETAILS); } fd_head->flags &= ~(FD_DEFRAGMENTED|FD_PARTIAL_REASSEMBLY|FD_DATALEN_SET); fd_head->flags &= (~FD_TOOLONGFRAGMENT) & (~FD_MULTIPLETAILS); fd_head->datalen=0; fd_head->reassembled_in=0; } /* create new fd describing this fragment */ #if GLIB_CHECK_VERSION(2,10,0) fd = g_slice_new(fragment_data); #else fd = g_mem_chunk_alloc(fragment_data_chunk); #endif fd->next = NULL; fd->flags = 0; fd->frame = pinfo->fd->num; fd->offset = frag_number; fd->len = frag_data_len; fd->data = NULL; if (!more_frags) { /* * This is the tail fragment in the sequence. */ if (fd_head->flags&FD_DATALEN_SET) { /* ok we have already seen other tails for this packet * it might be a duplicate. */ if (fd_head->datalen != fd->offset ){ /* Oops, this tail indicates a different packet * len than the previous ones. Something's wrong. */ fd->flags |= FD_MULTIPLETAILS; fd_head->flags |= FD_MULTIPLETAILS; } } else { /* this was the first tail fragment, now we know the * sequence number of that fragment (which is NOT * the length of the packet!) */ fd_head->datalen = fd->offset; fd_head->flags |= FD_DATALEN_SET; } } /* If the packet is already defragmented, this MUST be an overlap. * The entire defragmented packet is in fd_head->data * Even if we have previously defragmented this packet, we still check * check it. Someone might play overlap and TTL games. */ if (fd_head->flags & FD_DEFRAGMENTED) { fd->flags |= FD_OVERLAP; fd_head->flags |= FD_OVERLAP; /* make sure it's not past the end */ if (fd->offset > fd_head->datalen) { /* new fragment comes after the end */ fd->flags |= FD_TOOLONGFRAGMENT; fd_head->flags |= FD_TOOLONGFRAGMENT; LINK_FRAG(fd_head,fd); return TRUE; } /* make sure it doesn't conflict with previous data */ dfpos=0; last_fd=NULL; for (fd_i=fd_head->next;fd_i && (fd_i->offset!=fd->offset);fd_i=fd_i->next) { if (!last_fd || last_fd->offset!=fd_i->offset){ dfpos += fd_i->len; } last_fd=fd_i; } if(fd_i){ /* new fragment overlaps existing fragment */ if(fd_i->len!=fd->len){ /* * They have different lengths; this * is definitely a conflict. */ fd->flags |= FD_OVERLAPCONFLICT; fd_head->flags |= FD_OVERLAPCONFLICT; LINK_FRAG(fd_head,fd); return TRUE; } DISSECTOR_ASSERT(fd_head->len >= dfpos + fd->len); if ( memcmp(fd_head->data+dfpos, tvb_get_ptr(tvb,offset,fd->len),fd->len) ){ /* * They have the same length, but the * data isn't the same. */ fd->flags |= FD_OVERLAPCONFLICT; fd_head->flags |= FD_OVERLAPCONFLICT; LINK_FRAG(fd_head,fd); return TRUE; } /* it was just an overlap, link it and return */ LINK_FRAG(fd_head,fd); return TRUE; } else { /* * New fragment doesn't overlap an existing * fragment - there was presumably a gap in * the sequence number space. * * XXX - what should we do here? Is it always * the case that there are no gaps, or are there * protcols using sequence numbers where there * can be gaps? * * If the former, the check below for having * received all the fragments should check for * holes in the sequence number space and for the * first sequence number being 0. If we do that, * the only way we can get here is if this fragment * is past the end of the sequence number space - * but the check for "fd->offset > fd_head->datalen" * would have caught that above, so it can't happen. * * If the latter, we don't have a good way of * knowing whether reassembly is complete if we * get packet out of order such that the "last" * fragment doesn't show up last - but, unless * in-order reliable delivery of fragments is * guaranteed, an implementation of the protocol * has no way of knowing whether reassembly is * complete, either. * * For now, we just link the fragment in and * return. */ LINK_FRAG(fd_head,fd); return TRUE; } } /* If we have reached this point, the packet is not defragmented yet. * Save all payload in a buffer until we can defragment. * XXX - what if we didn't capture the entire fragment due * to a too-short snapshot length? */ /* check len, there may be a fragment with 0 len, that is actually the tail */ if (fd->len) { fd->data = g_malloc(fd->len); tvb_memcpy(tvb, fd->data, offset, fd->len); } LINK_FRAG(fd_head,fd); if( !(fd_head->flags & FD_DATALEN_SET) ){ /* if we dont know the sequence number of the last fragment, * there are definitely still missing packets. Cheaper than * the check below. */ return FALSE; } /* check if we have received the entire fragment * this is easy since the list is sorted and the head is faked. * common case the whole list is scanned. */ max = 0; for(fd_i=fd_head->next;fd_i;fd_i=fd_i->next) { if ( fd_i->offset==max ){ max++; } } /* max will now be datalen+1 if all fragments have been seen */ if (max <= fd_head->datalen) { /* we have not received all packets yet */ return FALSE; } if (max > (fd_head->datalen+1)) { /* oops, too long fragment detected */ fd->flags |= FD_TOOLONGFRAGMENT; fd_head->flags |= FD_TOOLONGFRAGMENT; } /* we have received an entire packet, defragment it and * free all fragments */ fragment_defragment_and_free(fd_head, pinfo); return TRUE; } /* * This function adds a new fragment to the fragment hash table. * If this is the first fragment seen for this datagram, a new entry * is created in the hash table, otherwise this fragment is just added * to the linked list of fragments for this packet. * * Returns a pointer to the head of the fragment data list if we have all the * fragments, NULL otherwise. * * This function assumes frag_number being a block sequence number. * The bsn for the first block is 0. */ fragment_data * fragment_add_seq(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, const guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags) { fragment_key key; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; return fragment_add_seq_key(tvb, offset, pinfo, &key, fragment_key_copy, fragment_table, frag_number, frag_data_len, more_frags, 0); } fragment_data * fragment_add_dcerpc_dg(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, void *v_act_id, GHashTable *fragment_table, const guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags) { e_uuid_t *act_id = (e_uuid_t *)v_act_id; dcerpc_fragment_key key; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; key.act_id = *act_id; return fragment_add_seq_key(tvb, offset, pinfo, &key, dcerpc_fragment_key_copy, fragment_table, frag_number, frag_data_len, more_frags, 0); } fragment_data * fragment_add_seq_key(tvbuff_t *tvb, const int offset, const packet_info *pinfo, void *key, fragment_key_copier key_copier, GHashTable *fragment_table, guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags, const guint32 flags) { fragment_data *fd_head; fd_head = g_hash_table_lookup(fragment_table, key); /* have we already seen this frame ?*/ if (pinfo->fd->flags.visited) { if (fd_head != NULL && fd_head->flags & FD_DEFRAGMENTED) { return fd_head; } else { return NULL; } } if (fd_head==NULL){ /* not found, this must be the first snooped fragment for this * packet. Create list-head. */ fd_head= new_head(FD_BLOCKSEQUENCE); if((flags & (REASSEMBLE_FLAGS_NO_FRAG_NUMBER|REASSEMBLE_FLAGS_802_11_HACK)) && !more_frags) { /* * This is the last fragment for this packet, and * is the only one we've seen. * * Either we don't have sequence numbers, in which * case we assume this is the first fragment for * this packet, or we're doing special 802.11 * processing, in which case we assume it's one * of those reassembled packets with a non-zero * fragment number (see packet-80211.c); just * return a pointer to the head of the list; * fragment_add_seq_check will then add it to the table * of reassembled packets. */ fd_head->reassembled_in=pinfo->fd->num; return fd_head; } /* * We're going to use the key to insert the fragment, * so copy it to a long-term store. */ if(key_copier != NULL) key = key_copier(key); g_hash_table_insert(fragment_table, key, fd_head); /* * If we weren't given an initial fragment number, * make it 0. */ if (flags & REASSEMBLE_FLAGS_NO_FRAG_NUMBER) frag_number = 0; } else { if (flags & REASSEMBLE_FLAGS_NO_FRAG_NUMBER) { fragment_data *fd; /* * If we weren't given an initial fragment number, * use the next expected fragment number as the fragment * number for this fragment. */ for (fd = fd_head; fd != NULL; fd = fd->next) { if (fd->next == NULL) frag_number = fd->offset + 1; } } } /* * XXX I've copied this over from the old separate * fragment_add_seq_check_work, but I'm not convinced it's doing the * right thing -- rav * * If we don't have all the data that is in this fragment, * then we can't, and don't, do reassembly on it. * * If it's the first frame, handle it as an unfragmented packet. * Otherwise, just handle it as a fragment. * * If "more_frags" isn't set, we get rid of the entry in the * hash table for this reassembly, as we don't need it any more. */ if ((flags & REASSEMBLE_FLAGS_CHECK_DATA_PRESENT) && !tvb_bytes_exist(tvb, offset, frag_data_len)) { if (!more_frags) { gpointer orig_key; /* * Remove this from the table of in-progress * reassemblies, and free up any memory used for * it in that table. */ if (g_hash_table_lookup_extended(fragment_table, key, &orig_key, NULL)) { fragment_unhash(fragment_table, (fragment_key *)orig_key); } } fd_head -> flags |= FD_DATA_NOT_PRESENT; return frag_number == 0 ? fd_head : NULL; } if (fragment_add_seq_work(fd_head, tvb, offset, pinfo, frag_number, frag_data_len, more_frags, flags)) { /* * Reassembly is complete. */ return fd_head; } else { /* * Reassembly isn't complete. */ return NULL; } } /* * This does the work for "fragment_add_seq_check()" and * "fragment_add_seq_next()". * * This function assumes frag_number being a block sequence number. * The bsn for the first block is 0. * * If "no_frag_number" is TRUE, it uses the next expected fragment number * as the fragment number if there is a reassembly in progress, otherwise * it uses 0. * * If "no_frag_number" is FALSE, it uses the "frag_number" argument as * the fragment number. * * If this is the first fragment seen for this datagram, a new * "fragment_data" structure is allocated to refer to the reassembled * packet. * * This fragment is added to the linked list of fragments for this packet. * * If "more_frags" is false and REASSEMBLE_FLAGS_802_11_HACK (as the name * implies, a special hack for 802.11) or REASSEMBLE_FLAGS_NO_FRAG_NUMBER * (implying messages must be in order since there's no sequence number) are * set in "flags", then this (one element) list is returned. * * If, after processing this fragment, we have all the fragments, * "fragment_add_seq_check_work()" removes that from the fragment hash * table if necessary and adds it to the table of reassembled fragments, * and returns a pointer to the head of the fragment list. * * Otherwise, it returns NULL. * * XXX - Should we simply return NULL for zero-length fragments? */ static fragment_data * fragment_add_seq_check_work(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, GHashTable *reassembled_table, const guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags, const guint32 flags) { reassembled_key reass_key; fragment_key key; fragment_data *fd_head; /* * Have we already seen this frame? * If so, look for it in the table of reassembled packets. */ if (pinfo->fd->flags.visited) { reass_key.frame = pinfo->fd->num; reass_key.id = id; return g_hash_table_lookup(reassembled_table, &reass_key); } /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = fragment_add_seq_key(tvb, offset, pinfo, &key, fragment_key_copy, fragment_table, frag_number, frag_data_len, more_frags, flags|REASSEMBLE_FLAGS_CHECK_DATA_PRESENT); if (fd_head) { gpointer orig_key; if(fd_head->flags & FD_DATA_NOT_PRESENT) { /* this is the first fragment of a datagram with * truncated fragments. Don't move it to the * reassembled table. */ return fd_head; } /* * Reassembly is complete. * Remove this from the table of in-progress * reassemblies, add it to the table of * reassembled packets, and return it. */ if (g_hash_table_lookup_extended(fragment_table, &key, &orig_key, NULL)) { /* * Remove this from the table of in-progress reassemblies, * and free up any memory used for it in that table. */ fragment_unhash(fragment_table, (fragment_key *)orig_key); } /* * Add this item to the table of reassembled packets. */ fragment_reassembled(fd_head, pinfo, reassembled_table, id); return fd_head; } else { /* * Reassembly isn't complete. */ return NULL; } } fragment_data * fragment_add_seq_check(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, GHashTable *reassembled_table, const guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags) { return fragment_add_seq_check_work(tvb, offset, pinfo, id, fragment_table, reassembled_table, frag_number, frag_data_len, more_frags, 0); } fragment_data * fragment_add_seq_802_11(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, GHashTable *reassembled_table, const guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags) { return fragment_add_seq_check_work(tvb, offset, pinfo, id, fragment_table, reassembled_table, frag_number, frag_data_len, more_frags, REASSEMBLE_FLAGS_802_11_HACK); } fragment_data * fragment_add_seq_next(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, GHashTable *reassembled_table, const guint32 frag_data_len, const gboolean more_frags) { return fragment_add_seq_check_work(tvb, offset, pinfo, id, fragment_table, reassembled_table, 0, frag_data_len, more_frags, REASSEMBLE_FLAGS_NO_FRAG_NUMBER); } void fragment_start_seq_check(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, const guint32 tot_len) { fragment_key key, *new_key; fragment_data *fd_head; /* Have we already seen this frame ?*/ if (pinfo->fd->flags.visited) { return; } /* Create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; /* Check if fragment data exist for this key */ fd_head = g_hash_table_lookup(fragment_table, &key); if (fd_head == NULL) { /* Create list-head. */ #if GLIB_CHECK_VERSION(2,10,0) fd_head = g_slice_new(fragment_data); #else fd_head = g_mem_chunk_alloc(fragment_data_chunk); #endif fd_head->next = NULL; fd_head->datalen = tot_len; fd_head->offset = 0; fd_head->len = 0; fd_head->flags = FD_BLOCKSEQUENCE|FD_DATALEN_SET; fd_head->data = NULL; fd_head->reassembled_in = 0; /* * We're going to use the key to insert the fragment, * so copy it to a long-term store. */ new_key = fragment_key_copy(&key); g_hash_table_insert(fragment_table, new_key, fd_head); } } fragment_data * fragment_end_seq_next(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, GHashTable *reassembled_table) { reassembled_key reass_key; reassembled_key *new_key; fragment_key key; fragment_data *fd_head; /* * Have we already seen this frame? * If so, look for it in the table of reassembled packets. */ if (pinfo->fd->flags.visited) { reass_key.frame = pinfo->fd->num; reass_key.id = id; return g_hash_table_lookup(reassembled_table, &reass_key); } /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup (fragment_table, &key); if (fd_head) { gpointer orig_key; if (fd_head->flags & FD_DATA_NOT_PRESENT) { /* No data added */ return NULL; } fd_head->datalen = fd_head->offset; fd_head->flags |= FD_DATALEN_SET; fragment_defragment_and_free (fd_head, pinfo); /* * Remove this from the table of in-progress * reassemblies, add it to the table of * reassembled packets, and return it. */ if (g_hash_table_lookup_extended(fragment_table, &key, &orig_key, NULL)) { /* * Remove this from the table of in-progress reassemblies, * and free up any memory used for it in that table. */ fragment_unhash(fragment_table, (fragment_key *)orig_key); } /* * Add this item to the table of reassembled packets. */ fragment_reassembled(fd_head, pinfo, reassembled_table, id); if (fd_head->next != NULL) { #if GLIB_CHECK_VERSION(2,10,0) new_key = g_slice_new(reassembled_key); #else new_key = se_alloc(sizeof(reassembled_key)); #endif new_key->frame = pinfo->fd->num; new_key->id = id; g_hash_table_insert(reassembled_table, new_key, fd_head); } return fd_head; } else { /* * Fragment data not found. */ return NULL; } } /* * Process reassembled data; if we're on the frame in which the data * was reassembled, put the fragment information into the protocol * tree, and construct a tvbuff with the reassembled data, otherwise * just put a "reassembled in" item into the protocol tree. */ tvbuff_t * process_reassembled_data(tvbuff_t *tvb, const int offset, packet_info *pinfo, const char *name, fragment_data *fd_head, const fragment_items *fit, gboolean *update_col_infop, proto_tree *tree) { tvbuff_t *next_tvb; gboolean update_col_info; proto_item *frag_tree_item; if (fd_head != NULL && pinfo->fd->num == fd_head->reassembled_in) { /* * OK, we've reassembled this. * Is this something that's been reassembled from more * than one fragment? */ if (fd_head->next != NULL) { /* * Yes. * Allocate a new tvbuff, referring to the * reassembled payload. */ if (fd_head->flags & FD_BLOCKSEQUENCE) { next_tvb = tvb_new_real_data(fd_head->data, fd_head->len, fd_head->len); } else { next_tvb = tvb_new_real_data(fd_head->data, fd_head->datalen, fd_head->datalen); } /* * Add the tvbuff to the list of tvbuffs to which * the tvbuff we were handed refers, so it'll get * cleaned up when that tvbuff is cleaned up. */ tvb_set_child_real_data_tvbuff(tvb, next_tvb); /* Add the defragmented data to the data source list. */ add_new_data_source(pinfo, next_tvb, name); /* show all fragments */ if (fd_head->flags & FD_BLOCKSEQUENCE) { update_col_info = !show_fragment_seq_tree( fd_head, fit, tree, pinfo, next_tvb, &frag_tree_item); } else { update_col_info = !show_fragment_tree(fd_head, fit, tree, pinfo, next_tvb, &frag_tree_item); } } else { /* * No. * Return a tvbuff with the payload. */ next_tvb = tvb_new_subset_remaining(tvb, offset); pinfo->fragmented = FALSE; /* one-fragment packet */ update_col_info = TRUE; } if (update_col_infop != NULL) *update_col_infop = update_col_info; } else { /* * We don't have the complete reassembled payload, or this * isn't the final frame of that payload. */ next_tvb = NULL; /* * If we know what frame this was reassembled in, * and if there's a field to use for the number of * the frame in which the packet was reassembled, * add it to the protocol tree. */ if (fd_head != NULL && fit->hf_reassembled_in != NULL) { proto_tree_add_uint(tree, *(fit->hf_reassembled_in), tvb, 0, 0, fd_head->reassembled_in); } } return next_tvb; } /* * Show a single fragment in a fragment subtree, and put information about * it in the top-level item for that subtree. */ static void show_fragment(fragment_data *fd, const int offset, const fragment_items *fit, proto_tree *ft, proto_item *fi, const gboolean first_frag, const guint32 count, tvbuff_t *tvb) { proto_item *fei=NULL; int hf; if (first_frag) { gchar *name; if (count == 1) { name = g_strdup(proto_registrar_get_name(*(fit->hf_fragment))); } else { name = g_strdup(proto_registrar_get_name(*(fit->hf_fragments))); } proto_item_set_text(fi, "%u %s (%u byte%s): ", count, name, tvb_length(tvb), plurality(tvb_length(tvb), "", "s")); g_free(name); } else { proto_item_append_text(fi, ", "); } proto_item_append_text(fi, "#%u(%u)", fd->frame, fd->len); if (fd->flags & (FD_OVERLAPCONFLICT |FD_MULTIPLETAILS|FD_TOOLONGFRAGMENT) ) { hf = *(fit->hf_fragment_error); } else { hf = *(fit->hf_fragment); } if (fd->len == 0) { fei = proto_tree_add_uint_format(ft, hf, tvb, offset, fd->len, fd->frame, "Frame: %u (no data)", fd->frame); } else { fei = proto_tree_add_uint_format(ft, hf, tvb, offset, fd->len, fd->frame, "Frame: %u, payload: %u-%u (%u byte%s)", fd->frame, offset, offset+fd->len-1, fd->len, plurality(fd->len, "", "s")); } PROTO_ITEM_SET_GENERATED(fei); if (fd->flags & (FD_OVERLAP|FD_OVERLAPCONFLICT |FD_MULTIPLETAILS|FD_TOOLONGFRAGMENT) ) { /* this fragment has some flags set, create a subtree * for it and display the flags. */ proto_tree *fet=NULL; fet = proto_item_add_subtree(fei, *(fit->ett_fragment)); if (fd->flags&FD_OVERLAP) { fei=proto_tree_add_boolean(fet, *(fit->hf_fragment_overlap), tvb, 0, 0, TRUE); PROTO_ITEM_SET_GENERATED(fei); } if (fd->flags&FD_OVERLAPCONFLICT) { fei=proto_tree_add_boolean(fet, *(fit->hf_fragment_overlap_conflict), tvb, 0, 0, TRUE); PROTO_ITEM_SET_GENERATED(fei); } if (fd->flags&FD_MULTIPLETAILS) { fei=proto_tree_add_boolean(fet, *(fit->hf_fragment_multiple_tails), tvb, 0, 0, TRUE); PROTO_ITEM_SET_GENERATED(fei); } if (fd->flags&FD_TOOLONGFRAGMENT) { fei=proto_tree_add_boolean(fet, *(fit->hf_fragment_too_long_fragment), tvb, 0, 0, TRUE); PROTO_ITEM_SET_GENERATED(fei); } } } static gboolean show_fragment_errs_in_col(fragment_data *fd_head, const fragment_items *fit, packet_info *pinfo) { if (fd_head->flags & (FD_OVERLAPCONFLICT |FD_MULTIPLETAILS|FD_TOOLONGFRAGMENT) ) { if (check_col(pinfo->cinfo, COL_INFO)) { col_add_fstr(pinfo->cinfo, COL_INFO, "[Illegal %s]", fit->tag); return TRUE; } } return FALSE; } /* This function will build the fragment subtree; it's for fragments reassembled with "fragment_add()". It will return TRUE if there were fragmentation errors or FALSE if fragmentation was ok. */ gboolean show_fragment_tree(fragment_data *fd_head, const fragment_items *fit, proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, proto_item **fi) { fragment_data *fd; proto_tree *ft; gboolean first_frag; guint32 count = 0; /* It's not fragmented. */ pinfo->fragmented = FALSE; *fi = proto_tree_add_item(tree, *(fit->hf_fragments), tvb, 0, -1, FALSE); PROTO_ITEM_SET_GENERATED(*fi); ft = proto_item_add_subtree(*fi, *(fit->ett_fragments)); first_frag = TRUE; for (fd = fd_head->next; fd != NULL; fd = fd->next) { count++; } for (fd = fd_head->next; fd != NULL; fd = fd->next) { show_fragment(fd, fd->offset, fit, ft, *fi, first_frag, count, tvb); first_frag = FALSE; } if (fit->hf_fragment_count) { proto_item *fli = proto_tree_add_uint(ft, *(fit->hf_fragment_count), tvb, 0, 0, count); PROTO_ITEM_SET_GENERATED(fli); } if (fit->hf_reassembled_length) { proto_item *fli = proto_tree_add_uint(ft, *(fit->hf_reassembled_length), tvb, 0, 0, tvb_length (tvb)); PROTO_ITEM_SET_GENERATED(fli); } return show_fragment_errs_in_col(fd_head, fit, pinfo); } /* This function will build the fragment subtree; it's for fragments reassembled with "fragment_add_seq()" or "fragment_add_seq_check()". It will return TRUE if there were fragmentation errors or FALSE if fragmentation was ok. */ gboolean show_fragment_seq_tree(fragment_data *fd_head, const fragment_items *fit, proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, proto_item **fi) { guint32 offset, next_offset, count = 0; fragment_data *fd, *last_fd; proto_tree *ft; gboolean first_frag; /* It's not fragmented. */ pinfo->fragmented = FALSE; *fi = proto_tree_add_item(tree, *(fit->hf_fragments), tvb, 0, -1, FALSE); PROTO_ITEM_SET_GENERATED(*fi); ft = proto_item_add_subtree(*fi, *(fit->ett_fragments)); offset = 0; next_offset = 0; last_fd = NULL; first_frag = TRUE; for (fd = fd_head->next; fd != NULL; fd = fd->next){ count++; } for (fd = fd_head->next; fd != NULL; fd = fd->next){ if (last_fd == NULL || last_fd->offset != fd->offset) { offset = next_offset; next_offset += fd->len; } last_fd = fd; show_fragment(fd, offset, fit, ft, *fi, first_frag, count, tvb); first_frag = FALSE; } if (fit->hf_fragment_count) { proto_item *fli = proto_tree_add_uint(ft, *(fit->hf_fragment_count), tvb, 0, 0, count); PROTO_ITEM_SET_GENERATED(fli); } if (fit->hf_reassembled_length) { proto_item *fli = proto_tree_add_uint(ft, *(fit->hf_reassembled_length), tvb, 0, 0, tvb_length (tvb)); PROTO_ITEM_SET_GENERATED(fli); } return show_fragment_errs_in_col(fd_head, fit, pinfo); } /* * Local Variables: * c-basic-offset: 8 * indent-tabs-mode: t * tab-width: 8 * End: */ /* reassemble.c * Routines for {fragment,segment} reassembly * * $Id: reassemble.c 36223 2011-03-21 13:28:20Z cmaynard $ * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <string.h> #include <epan/packet.h> #include <epan/reassemble.h> #include <epan/emem.h> #include <epan/dissectors/packet-dcerpc.h> typedef struct _fragment_key { address src; address dst; guint32 id; } fragment_key; typedef struct _dcerpc_fragment_key { address src; address dst; guint32 id; e_uuid_t act_id; } dcerpc_fragment_key; #if GLIB_CHECK_VERSION(2,10,0) #else static GMemChunk *fragment_key_chunk = NULL; static GMemChunk *fragment_data_chunk = NULL; static GMemChunk *dcerpc_fragment_key_chunk = NULL; static int fragment_init_count = 200; #endif static void LINK_FRAG(fragment_data *fd_head,fragment_data *fd) { fragment_data *fd_i; /* add fragment to list, keep list sorted */ for(fd_i= fd_head; fd_i->next;fd_i=fd_i->next) { if (fd->offset < fd_i->next->offset ) break; } fd->next=fd_i->next; fd_i->next=fd; } /* copy a fragment key to heap store to insert in the hash */ static void *fragment_key_copy(const void *k) { const fragment_key* key = (const fragment_key*) k; #if GLIB_CHECK_VERSION(2,10,0) fragment_key *new_key = g_slice_new(fragment_key); #else fragment_key *new_key = g_mem_chunk_alloc(fragment_key_chunk); #endif COPY_ADDRESS(&new_key->src, &key->src); COPY_ADDRESS(&new_key->dst, &key->dst); new_key->id = key->id; return new_key; } /* copy a dcerpc fragment key to heap store to insert in the hash */ static void *dcerpc_fragment_key_copy(const void *k) { const dcerpc_fragment_key* key = (const dcerpc_fragment_key*) k; #if GLIB_CHECK_VERSION(2,10,0) dcerpc_fragment_key *new_key = g_slice_new(dcerpc_fragment_key); #else dcerpc_fragment_key *new_key = g_mem_chunk_alloc(dcerpc_fragment_key_chunk); #endif COPY_ADDRESS(&new_key->src, &key->src); COPY_ADDRESS(&new_key->dst, &key->dst); new_key->id = key->id; new_key->act_id = key->act_id; return new_key; } static gint fragment_equal(gconstpointer k1, gconstpointer k2) { const fragment_key* key1 = (const fragment_key*) k1; const fragment_key* key2 = (const fragment_key*) k2; /*key.id is the first item to compare since item is most likely to differ between sessions, thus shortcircuiting the comparasion of addresses. */ return ( ( (key1->id == key2->id) && (ADDRESSES_EQUAL(&key1->src, &key2->src)) && (ADDRESSES_EQUAL(&key1->dst, &key2->dst)) ) ? TRUE : FALSE); } static guint fragment_hash(gconstpointer k) { const fragment_key* key = (const fragment_key*) k; guint hash_val; /* int i; */ hash_val = 0; /* More than likely: in most captures src and dst addresses are the same, and would hash the same. We only use id as the hash as an optimization. for (i = 0; i < key->src.len; i++) hash_val += key->src.data[i]; for (i = 0; i < key->dst.len; i++) hash_val += key->dst.data[i]; */ hash_val += key->id; return hash_val; } static gint dcerpc_fragment_equal(gconstpointer k1, gconstpointer k2) { const dcerpc_fragment_key* key1 = (const dcerpc_fragment_key*) k1; const dcerpc_fragment_key* key2 = (const dcerpc_fragment_key*) k2; /*key.id is the first item to compare since item is most likely to differ between sessions, thus shortcircuiting the comparison of addresses. */ return (((key1->id == key2->id) && (ADDRESSES_EQUAL(&key1->src, &key2->src)) && (ADDRESSES_EQUAL(&key1->dst, &key2->dst)) && (memcmp (&key1->act_id, &key2->act_id, sizeof (e_uuid_t)) == 0)) ? TRUE : FALSE); } static guint dcerpc_fragment_hash(gconstpointer k) { const dcerpc_fragment_key* key = (const dcerpc_fragment_key*) k; guint hash_val; hash_val = 0; hash_val += key->id; hash_val += key->act_id.Data1; hash_val += key->act_id.Data2 << 16; hash_val += key->act_id.Data3; return hash_val; } typedef struct _reassembled_key { guint32 id; guint32 frame; } reassembled_key; static gint reassembled_equal(gconstpointer k1, gconstpointer k2) { const reassembled_key* key1 = (const reassembled_key*) k1; const reassembled_key* key2 = (const reassembled_key*) k2; /* * We assume that the frame numbers are unlikely to be equal, * so we check them first. */ return key1->frame == key2->frame && key1->id == key2->id; } static guint reassembled_hash(gconstpointer k) { const reassembled_key* key = (const reassembled_key*) k; return key->frame; } /* * For a fragment hash table entry, free the associated fragments. * If slices are used (GLIB >= 2.10) the entry value (fd_chain) is * freed herein and the entry is freed when fragment_free_key() * [or dcerpc_fragment_free_key()] is called (as a consequence of * returning TRUE from this function). * If mem_chunks are used, free the address data to which the key * refers; the the actual key and value structures get freed * by "reassemble_cleanup()"). */ static gboolean free_all_fragments(gpointer key_arg _U_, gpointer value, gpointer user_data _U_) { fragment_data *fd_head, *tmp_fd; #if GLIB_CHECK_VERSION(2,10,0) /* If Glib version => 2.10 we do g_hash_table_new_full() and supply a function * to free the key and the addresses. */ #else fragment_key *key = key_arg; /* * Grr. I guess the theory here is that freeing * something sure as heck modifies it, so you * want to ban attempts to free it, but, alas, * if we make the "data" field of an "address" * structure not a "const", the compiler whines if * we try to make it point into the data for a packet, * as that's a "const" array (and should be, as dissectors * shouldn't trash it). * * So we cast the complaint into oblivion, and rely on * the fact that these addresses are known to have had * their data mallocated, i.e. they don't point into, * say, the middle of the data for a packet. */ g_free((gpointer)key->src.data); g_free((gpointer)key->dst.data); #endif for (fd_head = value; fd_head != NULL; fd_head = tmp_fd) { tmp_fd=fd_head->next; if(fd_head->data && !(fd_head->flags&FD_NOT_MALLOCED)) g_free(fd_head->data); #if GLIB_CHECK_VERSION(2,10,0) g_slice_free(fragment_data, fd_head); #endif } return TRUE; } /* ------------------------- */ static fragment_data *new_head(const guint32 flags) { fragment_data *fd_head; /* If head/first structure in list only holds no other data than * 'datalen' then we don't have to change the head of the list * even if we want to keep it sorted */ #if GLIB_CHECK_VERSION(2,10,0) fd_head=g_slice_new0(fragment_data); #else fd_head=g_mem_chunk_alloc0(fragment_data_chunk); #endif fd_head->flags=flags; return fd_head; } /* * For a reassembled-packet hash table entry, free the fragment data * to which the value refers. * (The actual value structures get freed by "reassemble_cleanup()".) */ static gboolean free_all_reassembled_fragments(gpointer key_arg _U_, gpointer value, gpointer user_data _U_) { fragment_data *fd_head; for (fd_head = value; fd_head != NULL; fd_head = fd_head->next) { if(fd_head->data && !(fd_head->flags&FD_NOT_MALLOCED)) { g_free(fd_head->data); /* * A reassembled packet is inserted into the * hash table once for every frame that made * up the reassembled packet; clear the data * pointer so that we only free the data the * first time we see it. */ fd_head->data = NULL; } } return TRUE; } #if GLIB_CHECK_VERSION(2,10,0) static void fragment_free_key(void *ptr) { fragment_key *key = (fragment_key *)ptr; if(key){ /* * Free up the copies of the addresses from the old key. */ g_free((gpointer)key->src.data); g_free((gpointer)key->dst.data); g_slice_free(fragment_key, key); } } static void dcerpc_fragment_free_key(void *ptr) { dcerpc_fragment_key *key = (dcerpc_fragment_key *)ptr; if(key){ /* * Free up the copies of the addresses from the old key. */ g_free((gpointer)key->src.data); g_free((gpointer)key->dst.data); g_slice_free(dcerpc_fragment_key, key); } } #endif /* * Initialize a fragment table. */ void fragment_table_init(GHashTable **fragment_table) { if (*fragment_table != NULL) { /* * The fragment hash table exists. * * Remove all entries and free fragment data for each entry. * * If slices are used (GLIB >= 2.10) * the keys are freed by calling fragment_free_key() * and the values are freed in free_all_fragments(). * * If mem_chunks are used, the key and value data * are freed by "reassemble_cleanup()". free_all_fragments() * will free the adrress data associated with the key */ g_hash_table_foreach_remove(*fragment_table, free_all_fragments, NULL); } else { #if GLIB_CHECK_VERSION(2,10,0) /* The fragment table does not exist. Create it */ *fragment_table = g_hash_table_new_full(fragment_hash, fragment_equal, fragment_free_key, NULL); #else /* The fragment table does not exist. Create it */ *fragment_table = g_hash_table_new(fragment_hash, fragment_equal); #endif } } void dcerpc_fragment_table_init(GHashTable **fragment_table) { if (*fragment_table != NULL) { /* * The fragment hash table exists. * * Remove all entries and free fragment data for each entry. * * If slices are used (GLIB >= 2.10) * the keys are freed by calling dcerpc_fragment_free_key() * and the values are freed in free_all_fragments(). * * If mem_chunks are used, the key and value data * are freed by "reassemble_cleanup()". free_all_fragments() * will free the adrress data associated with the key */ g_hash_table_foreach_remove(*fragment_table, free_all_fragments, NULL); } else { #if GLIB_CHECK_VERSION(2,10,0) /* The fragment table does not exist. Create it */ *fragment_table = g_hash_table_new_full(dcerpc_fragment_hash, dcerpc_fragment_equal, dcerpc_fragment_free_key, NULL); #else /* The fragment table does not exist. Create it */ *fragment_table = g_hash_table_new(dcerpc_fragment_hash, dcerpc_fragment_equal); #endif } } /* * Initialize a reassembled-packet table. */ void reassembled_table_init(GHashTable **reassembled_table) { if (*reassembled_table != NULL) { /* * The reassembled-packet hash table exists. * * Remove all entries and free reassembled packet * data for each entry. (The key data is freed * by "reassemble_cleanup()".) */ g_hash_table_foreach_remove(*reassembled_table, free_all_reassembled_fragments, NULL); } else { /* The fragment table does not exist. Create it */ *reassembled_table = g_hash_table_new(reassembled_hash, reassembled_equal); } } /* * Free up all space allocated for fragment keys and data and * reassembled keys. */ void reassemble_cleanup(void) { #if GLIB_CHECK_VERSION(2,10,0) #else if (fragment_key_chunk != NULL) g_mem_chunk_destroy(fragment_key_chunk); if (dcerpc_fragment_key_chunk != NULL) g_mem_chunk_destroy(dcerpc_fragment_key_chunk); if (fragment_data_chunk != NULL) g_mem_chunk_destroy(fragment_data_chunk); fragment_key_chunk = NULL; dcerpc_fragment_key_chunk = NULL; fragment_data_chunk = NULL; #endif } void reassemble_init(void) { #if GLIB_CHECK_VERSION(2,10,0) #else fragment_key_chunk = g_mem_chunk_new("fragment_key_chunk", sizeof(fragment_key), fragment_init_count * sizeof(fragment_key), G_ALLOC_AND_FREE); dcerpc_fragment_key_chunk = g_mem_chunk_new("dcerpc_fragment_key_chunk", sizeof(dcerpc_fragment_key), fragment_init_count * sizeof(dcerpc_fragment_key), G_ALLOC_AND_FREE); fragment_data_chunk = g_mem_chunk_new("fragment_data_chunk", sizeof(fragment_data), fragment_init_count * sizeof(fragment_data), G_ALLOC_ONLY); #endif } /* This function cleans up the stored state and removes the reassembly data and * (with one exception) all allocated memory for matching reassembly. * * The exception is : * If the PDU was already completely reassembled, then the buffer containing the * reassembled data WILL NOT be free()d, and the pointer to that buffer will be * returned. * Othervise the function will return NULL. * * So, if you call fragment_delete and it returns non-NULL, YOU are responsible to * g_free() that buffer. */ unsigned char * fragment_delete(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table) { fragment_data *fd_head, *fd; fragment_key key; unsigned char *data=NULL; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup(fragment_table, &key); if(fd_head==NULL){ /* We do not recognize this as a PDU we have seen before. return */ return NULL; } data=fd_head->data; /* loop over all partial fragments and free any buffers */ for(fd=fd_head->next;fd;){ fragment_data *tmp_fd; tmp_fd=fd->next; if( !(fd->flags&FD_NOT_MALLOCED) ) g_free(fd->data); #if GLIB_CHECK_VERSION(2,10,0) g_slice_free(fragment_data, fd); #else g_mem_chunk_free(fragment_data_chunk, fd); #endif fd=tmp_fd; } #if GLIB_CHECK_VERSION(2,10,0) g_slice_free(fragment_data, fd_head); #else g_mem_chunk_free(fragment_data_chunk, fd_head); #endif g_hash_table_remove(fragment_table, &key); return data; } /* This function is used to check if there is partial or completed reassembly state * matching this packet. I.e. Is there reassembly going on or not for this packet? */ fragment_data * fragment_get(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table) { fragment_data *fd_head; fragment_key key; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup(fragment_table, &key); return fd_head; } /* id *must* be the frame number for this to work! */ fragment_data * fragment_get_reassembled(const guint32 id, GHashTable *reassembled_table) { fragment_data *fd_head; reassembled_key key; /* create key to search hash with */ key.frame = id; key.id = id; fd_head = g_hash_table_lookup(reassembled_table, &key); return fd_head; } fragment_data * fragment_get_reassembled_id(const packet_info *pinfo, const guint32 id, GHashTable *reassembled_table) { fragment_data *fd_head; reassembled_key key; /* create key to search hash with */ key.frame = pinfo->fd->num; key.id = id; fd_head = g_hash_table_lookup(reassembled_table, &key); return fd_head; } /* This function can be used to explicitly set the total length (if known) * for reassembly of a PDU. * This is useful for reassembly of PDUs where one may have the total length specified * in the first fragment instead of as for, say, IPv4 where a flag indicates which * is the last fragment. * * Such protocols might fragment_add with a more_frags==TRUE for every fragment * and just tell the reassembly engine the expected total length of the reassembled data * using fragment_set_tot_len immediately after doing fragment_add for the first packet. * * Note that for FD_BLOCKSEQUENCE tot_len is the index for the tail fragment. * i.e. since the block numbers start at 0, if we specify tot_len==2, that * actually means we want to defragment 3 blocks, block 0, 1 and 2. */ void fragment_set_tot_len(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, const guint32 tot_len) { fragment_data *fd_head; fragment_key key; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup(fragment_table, &key); if(fd_head){ fd_head->datalen = tot_len; fd_head->flags |= FD_DATALEN_SET; } return; } guint32 fragment_get_tot_len(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table) { fragment_data *fd_head; fragment_key key; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup(fragment_table, &key); if(fd_head){ return fd_head->datalen; } return 0; } /* This function will set the partial reassembly flag for a fh. When this function is called, the fh MUST already exist, i.e. the fh MUST be created by the initial call to fragment_add() before this function is called. Also note that this function MUST be called to indicate a fh will be extended (increase the already stored data) */ void fragment_set_partial_reassembly(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table) { fragment_data *fd_head; fragment_key key; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup(fragment_table, &key); /* * XXX - why not do all the stuff done early in "fragment_add_work()", * turning off FD_DEFRAGMENTED and pointing the fragments' data * pointers to the appropriate part of the already-reassembled * data, and clearing the data length and "reassembled in" frame * number, here? We currently have a hack in the TCP dissector * not to set the "reassembled in" value if the "partial reassembly" * flag is set, so that in the first pass through the packets * we don't falsely set a packet as reassembled in that packet * if the dissector decided that even more reassembly was needed. */ if(fd_head){ fd_head->flags |= FD_PARTIAL_REASSEMBLY; } } /* * This function gets rid of an entry from a fragment table, given * a pointer to the key for that entry; it also frees up the key * and the addresses in it. * Note: If we use slices keys are freed by fragment_free_key() [or dcerpc_fragment_free_key()] being called * during g_hash_table_remove(). */ static void fragment_unhash(GHashTable *fragment_table, fragment_key *key) { /* * Remove the entry from the fragment table. */ g_hash_table_remove(fragment_table, key); /* * Free the key itself. */ #if GLIB_CHECK_VERSION(2,10,0) #else /* * Free up the copies of the addresses from the old key. */ g_free((gpointer)key->src.data); g_free((gpointer)key->dst.data); g_mem_chunk_free(fragment_key_chunk, key); #endif } /* * This function adds fragment_data structure to a reassembled-packet * hash table, using the frame numbers of each of the frames from * which it was reassembled as keys, and sets the "reassembled_in" * frame number. */ static void fragment_reassembled(fragment_data *fd_head, const packet_info *pinfo, GHashTable *reassembled_table, const guint32 id) { reassembled_key *new_key; fragment_data *fd; if (fd_head->next == NULL) { /* * This was not fragmented, so there's no fragment * table; just hash it using the current frame number. */ new_key = se_alloc(sizeof(reassembled_key)); new_key->frame = pinfo->fd->num; new_key->id = id; g_hash_table_insert(reassembled_table, new_key, fd_head); } else { /* * Hash it with the frame numbers for all the frames. */ for (fd = fd_head->next; fd != NULL; fd = fd->next){ new_key = se_alloc(sizeof(reassembled_key)); new_key->frame = fd->frame; new_key->id = id; g_hash_table_insert(reassembled_table, new_key, fd_head); } } fd_head->flags |= FD_DEFRAGMENTED; fd_head->reassembled_in = pinfo->fd->num; } /* * This function adds a new fragment to the fragment hash table. * If this is the first fragment seen for this datagram, a new entry * is created in the hash table, otherwise this fragment is just added * to the linked list of fragments for this packet. * The list of fragments for a specific datagram is kept sorted for * easier handling. * * Returns a pointer to the head of the fragment data list if we have all the * fragments, NULL otherwise. * * This function assumes frag_offset being a byte offset into the defragment * packet. * * 01-2002 * Once the fh is defragmented (= FD_DEFRAGMENTED set), it can be * extended using the FD_PARTIAL_REASSEMBLY flag. This flag should be set * using fragment_set_partial_reassembly() before calling fragment_add * with the new fragment. FD_TOOLONGFRAGMENT and FD_MULTIPLETAILS flags * are lowered when a new extension process is started. */ static gboolean fragment_add_work(fragment_data *fd_head, tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 frag_offset, const guint32 frag_data_len, const gboolean more_frags) { fragment_data *fd; fragment_data *fd_i; guint32 max, dfpos; unsigned char *old_data; /* create new fd describing this fragment */ #if GLIB_CHECK_VERSION(2,10,0) fd = g_slice_new(fragment_data); #else fd = g_mem_chunk_alloc(fragment_data_chunk); #endif fd->next = NULL; fd->flags = 0; fd->frame = pinfo->fd->num; if (fd->frame > fd_head->frame) fd_head->frame = fd->frame; fd->offset = frag_offset; fd->len = frag_data_len; fd->data = NULL; /* * If it was already defragmented and this new fragment goes beyond * data limits, set flag in already empty fds & point old fds to malloc'ed data. */ if(fd_head->flags & FD_DEFRAGMENTED && (frag_offset+frag_data_len) >= fd_head->datalen && fd_head->flags & FD_PARTIAL_REASSEMBLY){ for(fd_i=fd_head->next; fd_i; fd_i=fd_i->next){ if( !fd_i->data ) { fd_i->data = fd_head->data + fd_i->offset; fd_i->flags |= FD_NOT_MALLOCED; } fd_i->flags &= (~FD_TOOLONGFRAGMENT) & (~FD_MULTIPLETAILS); } fd_head->flags &= ~(FD_DEFRAGMENTED|FD_PARTIAL_REASSEMBLY|FD_DATALEN_SET); fd_head->flags &= (~FD_TOOLONGFRAGMENT) & (~FD_MULTIPLETAILS); fd_head->datalen=0; fd_head->reassembled_in=0; } if (!more_frags) { /* * This is the tail fragment in the sequence. */ if (fd_head->flags & FD_DATALEN_SET) { /* ok we have already seen other tails for this packet * it might be a duplicate. */ if (fd_head->datalen != (fd->offset + fd->len) ){ /* Oops, this tail indicates a different packet * len than the previous ones. Something's wrong. */ fd->flags |= FD_MULTIPLETAILS; fd_head->flags |= FD_MULTIPLETAILS; } } else { /* this was the first tail fragment, now we know the * length of the packet */ fd_head->datalen = fd->offset + fd->len; fd_head->flags |= FD_DATALEN_SET; } } /* If the packet is already defragmented, this MUST be an overlap. * The entire defragmented packet is in fd_head->data. * Even if we have previously defragmented this packet, we still * check it. Someone might play overlap and TTL games. */ if (fd_head->flags & FD_DEFRAGMENTED) { guint32 end_offset = fd->offset + fd->len; fd->flags |= FD_OVERLAP; fd_head->flags |= FD_OVERLAP; /* make sure it's not too long */ if (end_offset > fd_head->datalen || end_offset < fd->offset || end_offset < fd->len) { fd->flags |= FD_TOOLONGFRAGMENT; fd_head->flags |= FD_TOOLONGFRAGMENT; } /* make sure it doesn't conflict with previous data */ else if ( memcmp(fd_head->data+fd->offset, tvb_get_ptr(tvb,offset,fd->len),fd->len) ){ fd->flags |= FD_OVERLAPCONFLICT; fd_head->flags |= FD_OVERLAPCONFLICT; } /* it was just an overlap, link it and return */ LINK_FRAG(fd_head,fd); return TRUE; } /* If we have reached this point, the packet is not defragmented yet. * Save all payload in a buffer until we can defragment. * XXX - what if we didn't capture the entire fragment due * to a too-short snapshot length? */ fd->data = g_malloc(fd->len); tvb_memcpy(tvb, fd->data, offset, fd->len); LINK_FRAG(fd_head,fd); if( !(fd_head->flags & FD_DATALEN_SET) ){ /* if we dont know the datalen, there are still missing * packets. Cheaper than the check below. */ return FALSE; } /* * Check if we have received the entire fragment. * This is easy since the list is sorted and the head is faked. * * First, we compute the amount of contiguous data that's * available. (The check for fd_i->offset <= max rules out * fragments that don't start before or at the end of the * previous fragment, i.e. fragments that have a gap between * them and the previous fragment.) */ max = 0; for (fd_i=fd_head->next;fd_i;fd_i=fd_i->next) { if ( ((fd_i->offset)<=max) && ((fd_i->offset+fd_i->len)>max) ){ max = fd_i->offset+fd_i->len; } } if (max < (fd_head->datalen)) { /* * The amount of contiguous data we have is less than the * amount of data we're trying to reassemble, so we haven't * received all packets yet. */ return FALSE; } if (max > (fd_head->datalen)) { /*XXX not sure if current fd was the TOOLONG*/ /*XXX is it fair to flag current fd*/ /* oops, too long fragment detected */ fd->flags |= FD_TOOLONGFRAGMENT; fd_head->flags |= FD_TOOLONGFRAGMENT; } /* we have received an entire packet, defragment it and * free all fragments */ /* store old data just in case */ old_data=fd_head->data; fd_head->data = g_malloc(max); /* add all data fragments */ for (dfpos=0,fd_i=fd_head;fd_i;fd_i=fd_i->next) { if (fd_i->len) { /* dfpos is always >= than fd_i->offset */ /* No gaps can exist here, max_loop(above) does this */ /* XXX - true? Can we get fd_i->offset+fd-i->len */ /* overflowing, for example? */ /* Actually: there is at least one pathological case wherein there can be fragments * on the list which are for offsets greater than max (i.e.: following a gap after max). * (Apparently a "DESEGMENT_UNTIL_FIN" was involved wherein the FIN packet had an offset * less than the highest fragment offset seen. [Seen from a fuzz-test: bug #2470]). * Note that the "overlap" compare must only be done for fragments with (offset+len) <= max * and thus within the newly g_malloc'd buffer. */ if ( fd_i->offset+fd_i->len > dfpos ) { if (fd_i->offset+fd_i->len > max) g_warning("Reassemble error in frame %u: offset %u + len %u > max %u", pinfo->fd->num, fd_i->offset, fd_i->len, max); else if (dfpos < fd_i->offset) g_warning("Reassemble error in frame %u: dfpos %u < offset %u", pinfo->fd->num, dfpos, fd_i->offset); else if (dfpos-fd_i->offset > fd_i->len) g_warning("Reassemble error in frame %u: dfpos %u - offset %u > len %u", pinfo->fd->num, dfpos, fd_i->offset, fd_i->len); else if (!fd_head->data) g_warning("Reassemble error in frame %u: no data", pinfo->fd->num); else { if (fd_i->offset < dfpos) { fd_i->flags |= FD_OVERLAP; fd_head->flags |= FD_OVERLAP; if ( memcmp(fd_head->data+fd_i->offset, fd_i->data, MIN(fd_i->len,(dfpos-fd_i->offset)) ) ) { fd_i->flags |= FD_OVERLAPCONFLICT; fd_head->flags |= FD_OVERLAPCONFLICT; } } memcpy(fd_head->data+dfpos, fd_i->data+(dfpos-fd_i->offset), fd_i->len-(dfpos-fd_i->offset)); } } else { if (fd_i->offset + fd_i->len < fd_i->offset) /* Integer overflow? */ g_warning("Reassemble error in frame %u: offset %u + len %u < offset", pinfo->fd->num, fd_i->offset, fd_i->len); } if( fd_i->flags & FD_NOT_MALLOCED ) fd_i->flags &= ~FD_NOT_MALLOCED; else g_free(fd_i->data); fd_i->data=NULL; dfpos=MAX(dfpos,(fd_i->offset+fd_i->len)); } } g_free(old_data); /* mark this packet as defragmented. allows us to skip any trailing fragments */ fd_head->flags |= FD_DEFRAGMENTED; fd_head->reassembled_in=pinfo->fd->num; return TRUE; } static fragment_data * fragment_add_common(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, const guint32 frag_offset, const guint32 frag_data_len, const gboolean more_frags, const gboolean check_already_added) { fragment_key key, *new_key; fragment_data *fd_head; fragment_data *fd_item; gboolean already_added=pinfo->fd->flags.visited; /* dissector shouldn't give us garbage tvb info */ DISSECTOR_ASSERT(tvb_bytes_exist(tvb, offset, frag_data_len)); /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup(fragment_table, &key); #if 0 /* debug output of associated fragments. */ /* leave it here for future debugging sessions */ if(strcmp(pinfo->current_proto, "DCERPC") == 0) { printf("proto:%s num:%u id:%u offset:%u len:%u more:%u visited:%u\n", pinfo->current_proto, pinfo->fd->num, id, frag_offset, frag_data_len, more_frags, pinfo->fd->flags.visited); if(fd_head != NULL) { for(fd_item=fd_head->next;fd_item;fd_item=fd_item->next){ printf("fd_frame:%u fd_offset:%u len:%u datalen:%u\n", fd_item->frame, fd_item->offset, fd_item->len, fd_item->datalen); } } } #endif /* * "already_added" is true if "pinfo->fd->flags.visited" is true; * if "pinfo->fd->flags.visited", this isn't the first pass, so * we've already done all the reassembly and added all the * fragments. * * If it's not true, but "check_already_added" is true, just check * if we have seen this fragment before, i.e., if we have already * added it to reassembly. * That can be true even if "pinfo->fd->flags.visited" is false * since we sometimes might call a subdissector multiple times. * As an additional check, just make sure we have not already added * this frame to the reassembly list, if there is a reassembly list; * note that the first item in the reassembly list is not a * fragment, it's a data structure for the reassembled packet. * We don't check it because its "frame" member isn't initialized * to anything, and because it doesn't count in any case. * * And as another additional check, make sure the fragment offsets are * the same, as otherwise we get into trouble if multiple fragments * are in one PDU. */ if (!already_added && check_already_added && fd_head != NULL) { if (pinfo->fd->num <= fd_head->frame) { for(fd_item=fd_head->next;fd_item;fd_item=fd_item->next){ if(pinfo->fd->num==fd_item->frame && frag_offset==fd_item->offset){ already_added=TRUE; } } } } /* have we already added this frame ?*/ if (already_added) { if (fd_head != NULL && fd_head->flags & FD_DEFRAGMENTED) { return fd_head; } else { return NULL; } } if (fd_head==NULL){ /* not found, this must be the first snooped fragment for this * packet. Create list-head. */ fd_head = new_head(0); /* * We're going to use the key to insert the fragment, * so allocate a structure for it, and copy the * addresses, allocating new buffers for the address * data. */ #if GLIB_CHECK_VERSION(2,10,0) new_key = g_slice_new(fragment_key); #else new_key = g_mem_chunk_alloc(fragment_key_chunk); #endif COPY_ADDRESS(&new_key->src, &key.src); COPY_ADDRESS(&new_key->dst, &key.dst); new_key->id = key.id; g_hash_table_insert(fragment_table, new_key, fd_head); } if (fragment_add_work(fd_head, tvb, offset, pinfo, frag_offset, frag_data_len, more_frags)) { /* * Reassembly is complete. */ return fd_head; } else { /* * Reassembly isn't complete. */ return NULL; } } fragment_data * fragment_add(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, const guint32 frag_offset, const guint32 frag_data_len, const gboolean more_frags) { return fragment_add_common(tvb, offset, pinfo, id, fragment_table, frag_offset, frag_data_len, more_frags, TRUE); } /* * For use when you can have multiple fragments in the same frame added * to the same reassembled PDU, e.g. with ONC RPC-over-TCP. */ fragment_data * fragment_add_multiple_ok(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, const guint32 frag_offset, const guint32 frag_data_len, const gboolean more_frags) { return fragment_add_common(tvb, offset, pinfo, id, fragment_table, frag_offset, frag_data_len, more_frags, FALSE); } fragment_data * fragment_add_check(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, GHashTable *reassembled_table, const guint32 frag_offset, const guint32 frag_data_len, const gboolean more_frags) { reassembled_key reass_key; fragment_key key, *new_key, *old_key; gpointer orig_key, value; fragment_data *fd_head; /* * If this isn't the first pass, look for this frame in the table * of reassembled packets. */ if (pinfo->fd->flags.visited) { reass_key.frame = pinfo->fd->num; reass_key.id = id; return g_hash_table_lookup(reassembled_table, &reass_key); } /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; /* Looks up a key in the GHashTable, returning the original key and the associated value * and a gboolean which is TRUE if the key was found. This is useful if you need to free * the memory allocated for the original key, for example before calling g_hash_table_remove() */ if (!g_hash_table_lookup_extended(fragment_table, &key, &orig_key, &value)) { /* not found, this must be the first snooped fragment for this * packet. Create list-head. */ fd_head = new_head(0); /* * We're going to use the key to insert the fragment, * so allocate a structure for it, and copy the * addresses, allocating new buffers for the address * data. */ #if GLIB_CHECK_VERSION(2,10,0) new_key = g_slice_new(fragment_key); #else new_key = g_mem_chunk_alloc(fragment_key_chunk); #endif COPY_ADDRESS(&new_key->src, &key.src); COPY_ADDRESS(&new_key->dst, &key.dst); new_key->id = key.id; g_hash_table_insert(fragment_table, new_key, fd_head); orig_key = new_key; /* for unhashing it later */ } else { /* * We found it. */ fd_head = value; } /* * If this is a short frame, then we can't, and don't, do * reassembly on it. We just give up. */ if (tvb_reported_length(tvb) > tvb_length(tvb)) return NULL; if (fragment_add_work(fd_head, tvb, offset, pinfo, frag_offset, frag_data_len, more_frags)) { /* * Reassembly is complete. * Remove this from the table of in-progress * reassemblies, add it to the table of * reassembled packets, and return it. */ /* * Remove this from the table of in-progress reassemblies, * and free up any memory used for it in that table. */ old_key = orig_key; fragment_unhash(fragment_table, old_key); /* * Add this item to the table of reassembled packets. */ fragment_reassembled(fd_head, pinfo, reassembled_table, id); return fd_head; } else { /* * Reassembly isn't complete. */ return NULL; } } static void fragment_defragment_and_free (fragment_data *fd_head, const packet_info *pinfo) { fragment_data *fd_i = NULL; fragment_data *last_fd = NULL; guint32 dfpos = 0, size = 0; void *old_data = NULL; for(fd_i=fd_head->next;fd_i;fd_i=fd_i->next) { if(!last_fd || last_fd->offset!=fd_i->offset){ size+=fd_i->len; } last_fd=fd_i; } /* store old data in case the fd_i->data pointers refer to it */ old_data=fd_head->data; fd_head->data = g_malloc(size); fd_head->len = size; /* record size for caller */ /* add all data fragments */ last_fd=NULL; for (fd_i=fd_head->next; fd_i; fd_i=fd_i->next) { if (fd_i->len) { if(!last_fd || last_fd->offset != fd_i->offset) { /* First fragment or in-sequence fragment */ memcpy(fd_head->data+dfpos, fd_i->data, fd_i->len); dfpos += fd_i->len; } else { /* duplicate/retransmission/overlap */ fd_i->flags |= FD_OVERLAP; fd_head->flags |= FD_OVERLAP; if(last_fd->len != fd_i->len || memcmp(last_fd->data, fd_i->data, last_fd->len) ) { fd_i->flags |= FD_OVERLAPCONFLICT; fd_head->flags |= FD_OVERLAPCONFLICT; } } } last_fd=fd_i; } /* we have defragmented the pdu, now free all fragments*/ for (fd_i=fd_head->next;fd_i;fd_i=fd_i->next) { if( fd_i->flags & FD_NOT_MALLOCED ) fd_i->flags &= ~FD_NOT_MALLOCED; else g_free(fd_i->data); fd_i->data=NULL; } g_free(old_data); /* mark this packet as defragmented. * allows us to skip any trailing fragments. */ fd_head->flags |= FD_DEFRAGMENTED; fd_head->reassembled_in=pinfo->fd->num; } /* * This function adds a new fragment to the entry for a reassembly * operation. * * The list of fragments for a specific datagram is kept sorted for * easier handling. * * Returns TRUE if we have all the fragments, FALSE otherwise. * * This function assumes frag_number being a block sequence number. * The bsn for the first block is 0. */ static gboolean fragment_add_seq_work(fragment_data *fd_head, tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags, const guint32 flags _U_) { fragment_data *fd; fragment_data *fd_i; fragment_data *last_fd; guint32 max, dfpos; /* if the partial reassembly flag has been set, and we are extending * the pdu, un-reassemble the pdu. This means pointing old fds to malloc'ed data. */ if(fd_head->flags & FD_DEFRAGMENTED && frag_number >= fd_head->datalen && fd_head->flags & FD_PARTIAL_REASSEMBLY){ guint32 lastdfpos = 0; dfpos = 0; for(fd_i=fd_head->next; fd_i; fd_i=fd_i->next){ if( !fd_i->data ) { if( fd_i->flags & FD_OVERLAP ) { /* this is a duplicate of the previous * fragment. */ fd_i->data = fd_head->data + lastdfpos; } else { fd_i->data = fd_head->data + dfpos; lastdfpos = dfpos; dfpos += fd_i->len; } fd_i->flags |= FD_NOT_MALLOCED; } fd_i->flags &= (~FD_TOOLONGFRAGMENT) & (~FD_MULTIPLETAILS); } fd_head->flags &= ~(FD_DEFRAGMENTED|FD_PARTIAL_REASSEMBLY|FD_DATALEN_SET); fd_head->flags &= (~FD_TOOLONGFRAGMENT) & (~FD_MULTIPLETAILS); fd_head->datalen=0; fd_head->reassembled_in=0; } /* create new fd describing this fragment */ #if GLIB_CHECK_VERSION(2,10,0) fd = g_slice_new(fragment_data); #else fd = g_mem_chunk_alloc(fragment_data_chunk); #endif fd->next = NULL; fd->flags = 0; fd->frame = pinfo->fd->num; fd->offset = frag_number; fd->len = frag_data_len; fd->data = NULL; if (!more_frags) { /* * This is the tail fragment in the sequence. */ if (fd_head->flags&FD_DATALEN_SET) { /* ok we have already seen other tails for this packet * it might be a duplicate. */ if (fd_head->datalen != fd->offset ){ /* Oops, this tail indicates a different packet * len than the previous ones. Something's wrong. */ fd->flags |= FD_MULTIPLETAILS; fd_head->flags |= FD_MULTIPLETAILS; } } else { /* this was the first tail fragment, now we know the * sequence number of that fragment (which is NOT * the length of the packet!) */ fd_head->datalen = fd->offset; fd_head->flags |= FD_DATALEN_SET; } } /* If the packet is already defragmented, this MUST be an overlap. * The entire defragmented packet is in fd_head->data * Even if we have previously defragmented this packet, we still check * check it. Someone might play overlap and TTL games. */ if (fd_head->flags & FD_DEFRAGMENTED) { fd->flags |= FD_OVERLAP; fd_head->flags |= FD_OVERLAP; /* make sure it's not past the end */ if (fd->offset > fd_head->datalen) { /* new fragment comes after the end */ fd->flags |= FD_TOOLONGFRAGMENT; fd_head->flags |= FD_TOOLONGFRAGMENT; LINK_FRAG(fd_head,fd); return TRUE; } /* make sure it doesn't conflict with previous data */ dfpos=0; last_fd=NULL; for (fd_i=fd_head->next;fd_i && (fd_i->offset!=fd->offset);fd_i=fd_i->next) { if (!last_fd || last_fd->offset!=fd_i->offset){ dfpos += fd_i->len; } last_fd=fd_i; } if(fd_i){ /* new fragment overlaps existing fragment */ if(fd_i->len!=fd->len){ /* * They have different lengths; this * is definitely a conflict. */ fd->flags |= FD_OVERLAPCONFLICT; fd_head->flags |= FD_OVERLAPCONFLICT; LINK_FRAG(fd_head,fd); return TRUE; } DISSECTOR_ASSERT(fd_head->len >= dfpos + fd->len); if ( memcmp(fd_head->data+dfpos, tvb_get_ptr(tvb,offset,fd->len),fd->len) ){ /* * They have the same length, but the * data isn't the same. */ fd->flags |= FD_OVERLAPCONFLICT; fd_head->flags |= FD_OVERLAPCONFLICT; LINK_FRAG(fd_head,fd); return TRUE; } /* it was just an overlap, link it and return */ LINK_FRAG(fd_head,fd); return TRUE; } else { /* * New fragment doesn't overlap an existing * fragment - there was presumably a gap in * the sequence number space. * * XXX - what should we do here? Is it always * the case that there are no gaps, or are there * protcols using sequence numbers where there * can be gaps? * * If the former, the check below for having * received all the fragments should check for * holes in the sequence number space and for the * first sequence number being 0. If we do that, * the only way we can get here is if this fragment * is past the end of the sequence number space - * but the check for "fd->offset > fd_head->datalen" * would have caught that above, so it can't happen. * * If the latter, we don't have a good way of * knowing whether reassembly is complete if we * get packet out of order such that the "last" * fragment doesn't show up last - but, unless * in-order reliable delivery of fragments is * guaranteed, an implementation of the protocol * has no way of knowing whether reassembly is * complete, either. * * For now, we just link the fragment in and * return. */ LINK_FRAG(fd_head,fd); return TRUE; } } /* If we have reached this point, the packet is not defragmented yet. * Save all payload in a buffer until we can defragment. * XXX - what if we didn't capture the entire fragment due * to a too-short snapshot length? */ /* check len, there may be a fragment with 0 len, that is actually the tail */ if (fd->len) { fd->data = g_malloc(fd->len); tvb_memcpy(tvb, fd->data, offset, fd->len); } LINK_FRAG(fd_head,fd); if( !(fd_head->flags & FD_DATALEN_SET) ){ /* if we dont know the sequence number of the last fragment, * there are definitely still missing packets. Cheaper than * the check below. */ return FALSE; } /* check if we have received the entire fragment * this is easy since the list is sorted and the head is faked. * common case the whole list is scanned. */ max = 0; for(fd_i=fd_head->next;fd_i;fd_i=fd_i->next) { if ( fd_i->offset==max ){ max++; } } /* max will now be datalen+1 if all fragments have been seen */ if (max <= fd_head->datalen) { /* we have not received all packets yet */ return FALSE; } if (max > (fd_head->datalen+1)) { /* oops, too long fragment detected */ fd->flags |= FD_TOOLONGFRAGMENT; fd_head->flags |= FD_TOOLONGFRAGMENT; } /* we have received an entire packet, defragment it and * free all fragments */ fragment_defragment_and_free(fd_head, pinfo); return TRUE; } /* * This function adds a new fragment to the fragment hash table. * If this is the first fragment seen for this datagram, a new entry * is created in the hash table, otherwise this fragment is just added * to the linked list of fragments for this packet. * * Returns a pointer to the head of the fragment data list if we have all the * fragments, NULL otherwise. * * This function assumes frag_number being a block sequence number. * The bsn for the first block is 0. */ fragment_data * fragment_add_seq(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, const guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags) { fragment_key key; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; return fragment_add_seq_key(tvb, offset, pinfo, &key, fragment_key_copy, fragment_table, frag_number, frag_data_len, more_frags, 0); } fragment_data * fragment_add_dcerpc_dg(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, void *v_act_id, GHashTable *fragment_table, const guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags) { e_uuid_t *act_id = (e_uuid_t *)v_act_id; dcerpc_fragment_key key; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; key.act_id = *act_id; return fragment_add_seq_key(tvb, offset, pinfo, &key, dcerpc_fragment_key_copy, fragment_table, frag_number, frag_data_len, more_frags, 0); } fragment_data * fragment_add_seq_key(tvbuff_t *tvb, const int offset, const packet_info *pinfo, void *key, fragment_key_copier key_copier, GHashTable *fragment_table, guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags, const guint32 flags) { fragment_data *fd_head; fd_head = g_hash_table_lookup(fragment_table, key); /* have we already seen this frame ?*/ if (pinfo->fd->flags.visited) { if (fd_head != NULL && fd_head->flags & FD_DEFRAGMENTED) { return fd_head; } else { return NULL; } } if (fd_head==NULL){ /* not found, this must be the first snooped fragment for this * packet. Create list-head. */ fd_head= new_head(FD_BLOCKSEQUENCE); if((flags & (REASSEMBLE_FLAGS_NO_FRAG_NUMBER|REASSEMBLE_FLAGS_802_11_HACK)) && !more_frags) { /* * This is the last fragment for this packet, and * is the only one we've seen. * * Either we don't have sequence numbers, in which * case we assume this is the first fragment for * this packet, or we're doing special 802.11 * processing, in which case we assume it's one * of those reassembled packets with a non-zero * fragment number (see packet-80211.c); just * return a pointer to the head of the list; * fragment_add_seq_check will then add it to the table * of reassembled packets. */ fd_head->reassembled_in=pinfo->fd->num; return fd_head; } /* * We're going to use the key to insert the fragment, * so copy it to a long-term store. */ if(key_copier != NULL) key = key_copier(key); g_hash_table_insert(fragment_table, key, fd_head); /* * If we weren't given an initial fragment number, * make it 0. */ if (flags & REASSEMBLE_FLAGS_NO_FRAG_NUMBER) frag_number = 0; } else { if (flags & REASSEMBLE_FLAGS_NO_FRAG_NUMBER) { fragment_data *fd; /* * If we weren't given an initial fragment number, * use the next expected fragment number as the fragment * number for this fragment. */ for (fd = fd_head; fd != NULL; fd = fd->next) { if (fd->next == NULL) frag_number = fd->offset + 1; } } } /* * XXX I've copied this over from the old separate * fragment_add_seq_check_work, but I'm not convinced it's doing the * right thing -- rav * * If we don't have all the data that is in this fragment, * then we can't, and don't, do reassembly on it. * * If it's the first frame, handle it as an unfragmented packet. * Otherwise, just handle it as a fragment. * * If "more_frags" isn't set, we get rid of the entry in the * hash table for this reassembly, as we don't need it any more. */ if ((flags & REASSEMBLE_FLAGS_CHECK_DATA_PRESENT) && !tvb_bytes_exist(tvb, offset, frag_data_len)) { if (!more_frags) { gpointer orig_key; /* * Remove this from the table of in-progress * reassemblies, and free up any memory used for * it in that table. */ if (g_hash_table_lookup_extended(fragment_table, key, &orig_key, NULL)) { fragment_unhash(fragment_table, (fragment_key *)orig_key); } } fd_head -> flags |= FD_DATA_NOT_PRESENT; return frag_number == 0 ? fd_head : NULL; } if (fragment_add_seq_work(fd_head, tvb, offset, pinfo, frag_number, frag_data_len, more_frags, flags)) { /* * Reassembly is complete. */ return fd_head; } else { /* * Reassembly isn't complete. */ return NULL; } } /* * This does the work for "fragment_add_seq_check()" and * "fragment_add_seq_next()". * * This function assumes frag_number being a block sequence number. * The bsn for the first block is 0. * * If "no_frag_number" is TRUE, it uses the next expected fragment number * as the fragment number if there is a reassembly in progress, otherwise * it uses 0. * * If "no_frag_number" is FALSE, it uses the "frag_number" argument as * the fragment number. * * If this is the first fragment seen for this datagram, a new * "fragment_data" structure is allocated to refer to the reassembled * packet. * * This fragment is added to the linked list of fragments for this packet. * * If "more_frags" is false and REASSEMBLE_FLAGS_802_11_HACK (as the name * implies, a special hack for 802.11) or REASSEMBLE_FLAGS_NO_FRAG_NUMBER * (implying messages must be in order since there's no sequence number) are * set in "flags", then this (one element) list is returned. * * If, after processing this fragment, we have all the fragments, * "fragment_add_seq_check_work()" removes that from the fragment hash * table if necessary and adds it to the table of reassembled fragments, * and returns a pointer to the head of the fragment list. * * Otherwise, it returns NULL. * * XXX - Should we simply return NULL for zero-length fragments? */ static fragment_data * fragment_add_seq_check_work(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, GHashTable *reassembled_table, const guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags, const guint32 flags) { reassembled_key reass_key; fragment_key key; fragment_data *fd_head; /* * Have we already seen this frame? * If so, look for it in the table of reassembled packets. */ if (pinfo->fd->flags.visited) { reass_key.frame = pinfo->fd->num; reass_key.id = id; return g_hash_table_lookup(reassembled_table, &reass_key); } /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = fragment_add_seq_key(tvb, offset, pinfo, &key, fragment_key_copy, fragment_table, frag_number, frag_data_len, more_frags, flags|REASSEMBLE_FLAGS_CHECK_DATA_PRESENT); if (fd_head) { gpointer orig_key; if(fd_head->flags & FD_DATA_NOT_PRESENT) { /* this is the first fragment of a datagram with * truncated fragments. Don't move it to the * reassembled table. */ return fd_head; } /* * Reassembly is complete. * Remove this from the table of in-progress * reassemblies, add it to the table of * reassembled packets, and return it. */ if (g_hash_table_lookup_extended(fragment_table, &key, &orig_key, NULL)) { /* * Remove this from the table of in-progress reassemblies, * and free up any memory used for it in that table. */ fragment_unhash(fragment_table, (fragment_key *)orig_key); } /* * Add this item to the table of reassembled packets. */ fragment_reassembled(fd_head, pinfo, reassembled_table, id); return fd_head; } else { /* * Reassembly isn't complete. */ return NULL; } } fragment_data * fragment_add_seq_check(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, GHashTable *reassembled_table, const guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags) { return fragment_add_seq_check_work(tvb, offset, pinfo, id, fragment_table, reassembled_table, frag_number, frag_data_len, more_frags, 0); } fragment_data * fragment_add_seq_802_11(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, GHashTable *reassembled_table, const guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags) { return fragment_add_seq_check_work(tvb, offset, pinfo, id, fragment_table, reassembled_table, frag_number, frag_data_len, more_frags, REASSEMBLE_FLAGS_802_11_HACK); } fragment_data * fragment_add_seq_next(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, GHashTable *reassembled_table, const guint32 frag_data_len, const gboolean more_frags) { return fragment_add_seq_check_work(tvb, offset, pinfo, id, fragment_table, reassembled_table, 0, frag_data_len, more_frags, REASSEMBLE_FLAGS_NO_FRAG_NUMBER); } void fragment_start_seq_check(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, const guint32 tot_len) { fragment_key key, *new_key; fragment_data *fd_head; /* Have we already seen this frame ?*/ if (pinfo->fd->flags.visited) { return; } /* Create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; /* Check if fragment data exist for this key */ fd_head = g_hash_table_lookup(fragment_table, &key); if (fd_head == NULL) { /* Create list-head. */ #if GLIB_CHECK_VERSION(2,10,0) fd_head = g_slice_new(fragment_data); #else fd_head = g_mem_chunk_alloc(fragment_data_chunk); #endif fd_head->next = NULL; fd_head->datalen = tot_len; fd_head->offset = 0; fd_head->len = 0; fd_head->flags = FD_BLOCKSEQUENCE|FD_DATALEN_SET; fd_head->data = NULL; fd_head->reassembled_in = 0; /* * We're going to use the key to insert the fragment, * so copy it to a long-term store. */ new_key = fragment_key_copy(&key); g_hash_table_insert(fragment_table, new_key, fd_head); } } fragment_data * fragment_end_seq_next(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, GHashTable *reassembled_table) { reassembled_key reass_key; reassembled_key *new_key; fragment_key key; fragment_data *fd_head; /* * Have we already seen this frame? * If so, look for it in the table of reassembled packets. */ if (pinfo->fd->flags.visited) { reass_key.frame = pinfo->fd->num; reass_key.id = id; return g_hash_table_lookup(reassembled_table, &reass_key); } /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup (fragment_table, &key); if (fd_head) { gpointer orig_key; if (fd_head->flags & FD_DATA_NOT_PRESENT) { /* No data added */ return NULL; } fd_head->datalen = fd_head->offset; fd_head->flags |= FD_DATALEN_SET; fragment_defragment_and_free (fd_head, pinfo); /* * Remove this from the table of in-progress * reassemblies, add it to the table of * reassembled packets, and return it. */ if (g_hash_table_lookup_extended(fragment_table, &key, &orig_key, NULL)) { /* * Remove this from the table of in-progress reassemblies, * and free up any memory used for it in that table. */ fragment_unhash(fragment_table, (fragment_key *)orig_key); } /* * Add this item to the table of reassembled packets. */ fragment_reassembled(fd_head, pinfo, reassembled_table, id); if (fd_head->next != NULL) { new_key = se_alloc(sizeof(reassembled_key)); new_key->frame = pinfo->fd->num; new_key->id = id; g_hash_table_insert(reassembled_table, new_key, fd_head); } return fd_head; } else { /* * Fragment data not found. */ return NULL; } } /* * Process reassembled data; if we're on the frame in which the data * was reassembled, put the fragment information into the protocol * tree, and construct a tvbuff with the reassembled data, otherwise * just put a "reassembled in" item into the protocol tree. */ tvbuff_t * process_reassembled_data(tvbuff_t *tvb, const int offset, packet_info *pinfo, const char *name, fragment_data *fd_head, const fragment_items *fit, gboolean *update_col_infop, proto_tree *tree) { tvbuff_t *next_tvb; gboolean update_col_info; proto_item *frag_tree_item; if (fd_head != NULL && pinfo->fd->num == fd_head->reassembled_in) { /* * OK, we've reassembled this. * Is this something that's been reassembled from more * than one fragment? */ if (fd_head->next != NULL) { /* * Yes. * Allocate a new tvbuff, referring to the * reassembled payload. */ if (fd_head->flags & FD_BLOCKSEQUENCE) { next_tvb = tvb_new_real_data(fd_head->data, fd_head->len, fd_head->len); } else { next_tvb = tvb_new_real_data(fd_head->data, fd_head->datalen, fd_head->datalen); } /* * Add the tvbuff to the list of tvbuffs to which * the tvbuff we were handed refers, so it'll get * cleaned up when that tvbuff is cleaned up. */ tvb_set_child_real_data_tvbuff(tvb, next_tvb); /* Add the defragmented data to the data source list. */ add_new_data_source(pinfo, next_tvb, name); /* show all fragments */ if (fd_head->flags & FD_BLOCKSEQUENCE) { update_col_info = !show_fragment_seq_tree( fd_head, fit, tree, pinfo, next_tvb, &frag_tree_item); } else { update_col_info = !show_fragment_tree(fd_head, fit, tree, pinfo, next_tvb, &frag_tree_item); } } else { /* * No. * Return a tvbuff with the payload. */ next_tvb = tvb_new_subset_remaining(tvb, offset); pinfo->fragmented = FALSE; /* one-fragment packet */ update_col_info = TRUE; } if (update_col_infop != NULL) *update_col_infop = update_col_info; } else { /* * We don't have the complete reassembled payload, or this * isn't the final frame of that payload. */ next_tvb = NULL; /* * If we know what frame this was reassembled in, * and if there's a field to use for the number of * the frame in which the packet was reassembled, * add it to the protocol tree. */ if (fd_head != NULL && fit->hf_reassembled_in != NULL) { proto_tree_add_uint(tree, *(fit->hf_reassembled_in), tvb, 0, 0, fd_head->reassembled_in); } } return next_tvb; } /* * Show a single fragment in a fragment subtree, and put information about * it in the top-level item for that subtree. */ static void show_fragment(fragment_data *fd, const int offset, const fragment_items *fit, proto_tree *ft, proto_item *fi, const gboolean first_frag, const guint32 count, tvbuff_t *tvb) { proto_item *fei=NULL; int hf; if (first_frag) { gchar *name; if (count == 1) { name = g_strdup(proto_registrar_get_name(*(fit->hf_fragment))); } else { name = g_strdup(proto_registrar_get_name(*(fit->hf_fragments))); } proto_item_set_text(fi, "%u %s (%u byte%s): ", count, name, tvb_length(tvb), plurality(tvb_length(tvb), "", "s")); g_free(name); } else { proto_item_append_text(fi, ", "); } proto_item_append_text(fi, "#%u(%u)", fd->frame, fd->len); if (fd->flags & (FD_OVERLAPCONFLICT |FD_MULTIPLETAILS|FD_TOOLONGFRAGMENT) ) { hf = *(fit->hf_fragment_error); } else { hf = *(fit->hf_fragment); } if (fd->len == 0) { fei = proto_tree_add_uint_format(ft, hf, tvb, offset, fd->len, fd->frame, "Frame: %u (no data)", fd->frame); } else { fei = proto_tree_add_uint_format(ft, hf, tvb, offset, fd->len, fd->frame, "Frame: %u, payload: %u-%u (%u byte%s)", fd->frame, offset, offset+fd->len-1, fd->len, plurality(fd->len, "", "s")); } PROTO_ITEM_SET_GENERATED(fei); if (fd->flags & (FD_OVERLAP|FD_OVERLAPCONFLICT |FD_MULTIPLETAILS|FD_TOOLONGFRAGMENT) ) { /* this fragment has some flags set, create a subtree * for it and display the flags. */ proto_tree *fet=NULL; fet = proto_item_add_subtree(fei, *(fit->ett_fragment)); if (fd->flags&FD_OVERLAP) { fei=proto_tree_add_boolean(fet, *(fit->hf_fragment_overlap), tvb, 0, 0, TRUE); PROTO_ITEM_SET_GENERATED(fei); } if (fd->flags&FD_OVERLAPCONFLICT) { fei=proto_tree_add_boolean(fet, *(fit->hf_fragment_overlap_conflict), tvb, 0, 0, TRUE); PROTO_ITEM_SET_GENERATED(fei); } if (fd->flags&FD_MULTIPLETAILS) { fei=proto_tree_add_boolean(fet, *(fit->hf_fragment_multiple_tails), tvb, 0, 0, TRUE); PROTO_ITEM_SET_GENERATED(fei); } if (fd->flags&FD_TOOLONGFRAGMENT) { fei=proto_tree_add_boolean(fet, *(fit->hf_fragment_too_long_fragment), tvb, 0, 0, TRUE); PROTO_ITEM_SET_GENERATED(fei); } } } static gboolean show_fragment_errs_in_col(fragment_data *fd_head, const fragment_items *fit, packet_info *pinfo) { if (fd_head->flags & (FD_OVERLAPCONFLICT |FD_MULTIPLETAILS|FD_TOOLONGFRAGMENT) ) { if (check_col(pinfo->cinfo, COL_INFO)) { col_add_fstr(pinfo->cinfo, COL_INFO, "[Illegal %s]", fit->tag); return TRUE; } } return FALSE; } /* This function will build the fragment subtree; it's for fragments reassembled with "fragment_add()". It will return TRUE if there were fragmentation errors or FALSE if fragmentation was ok. */ gboolean show_fragment_tree(fragment_data *fd_head, const fragment_items *fit, proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, proto_item **fi) { fragment_data *fd; proto_tree *ft; gboolean first_frag; guint32 count = 0; /* It's not fragmented. */ pinfo->fragmented = FALSE; *fi = proto_tree_add_item(tree, *(fit->hf_fragments), tvb, 0, -1, FALSE); PROTO_ITEM_SET_GENERATED(*fi); ft = proto_item_add_subtree(*fi, *(fit->ett_fragments)); first_frag = TRUE; for (fd = fd_head->next; fd != NULL; fd = fd->next) { count++; } for (fd = fd_head->next; fd != NULL; fd = fd->next) { show_fragment(fd, fd->offset, fit, ft, *fi, first_frag, count, tvb); first_frag = FALSE; } if (fit->hf_fragment_count) { proto_item *fli = proto_tree_add_uint(ft, *(fit->hf_fragment_count), tvb, 0, 0, count); PROTO_ITEM_SET_GENERATED(fli); } if (fit->hf_reassembled_length) { proto_item *fli = proto_tree_add_uint(ft, *(fit->hf_reassembled_length), tvb, 0, 0, tvb_length (tvb)); PROTO_ITEM_SET_GENERATED(fli); } return show_fragment_errs_in_col(fd_head, fit, pinfo); } /* This function will build the fragment subtree; it's for fragments reassembled with "fragment_add_seq()" or "fragment_add_seq_check()". It will return TRUE if there were fragmentation errors or FALSE if fragmentation was ok. */ gboolean show_fragment_seq_tree(fragment_data *fd_head, const fragment_items *fit, proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, proto_item **fi) { guint32 offset, next_offset, count = 0; fragment_data *fd, *last_fd; proto_tree *ft; gboolean first_frag; /* It's not fragmented. */ pinfo->fragmented = FALSE; *fi = proto_tree_add_item(tree, *(fit->hf_fragments), tvb, 0, -1, FALSE); PROTO_ITEM_SET_GENERATED(*fi); ft = proto_item_add_subtree(*fi, *(fit->ett_fragments)); offset = 0; next_offset = 0; last_fd = NULL; first_frag = TRUE; for (fd = fd_head->next; fd != NULL; fd = fd->next){ count++; } for (fd = fd_head->next; fd != NULL; fd = fd->next){ if (last_fd == NULL || last_fd->offset != fd->offset) { offset = next_offset; next_offset += fd->len; } last_fd = fd; show_fragment(fd, offset, fit, ft, *fi, first_frag, count, tvb); first_frag = FALSE; } if (fit->hf_fragment_count) { proto_item *fli = proto_tree_add_uint(ft, *(fit->hf_fragment_count), tvb, 0, 0, count); PROTO_ITEM_SET_GENERATED(fli); } if (fit->hf_reassembled_length) { proto_item *fli = proto_tree_add_uint(ft, *(fit->hf_reassembled_length), tvb, 0, 0, tvb_length (tvb)); PROTO_ITEM_SET_GENERATED(fli); } return show_fragment_errs_in_col(fd_head, fit, pinfo); } /* * Local Variables: * c-basic-offset: 8 * indent-tabs-mode: t * tab-width: 8 * End: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/wireshark_37112-37111.c
manybugs_data_50
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2012 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Rasmus Lerdorf <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <stdio.h> #include "php.h" #include "ext/standard/php_standard.h" #include "ext/standard/credits.h" #include "php_variables.h" #include "php_globals.h" #include "php_content_types.h" #include "SAPI.h" #include "php_logos.h" #include "zend_globals.h" /* for systems that need to override reading of environment variables */ void _php_import_environment_variables(zval *array_ptr TSRMLS_DC); PHPAPI void (*php_import_environment_variables)(zval *array_ptr TSRMLS_DC) = _php_import_environment_variables; PHPAPI void php_register_variable(char *var, char *strval, zval *track_vars_array TSRMLS_DC) { php_register_variable_safe(var, strval, strlen(strval), track_vars_array TSRMLS_CC); } /* binary-safe version */ PHPAPI void php_register_variable_safe(char *var, char *strval, int str_len, zval *track_vars_array TSRMLS_DC) { zval new_entry; assert(strval != NULL); /* Prepare value */ Z_STRLEN(new_entry) = str_len; Z_STRVAL(new_entry) = estrndup(strval, Z_STRLEN(new_entry)); Z_TYPE(new_entry) = IS_STRING; php_register_variable_ex(var, &new_entry, track_vars_array TSRMLS_CC); } PHPAPI void php_register_variable_ex(char *var_name, zval *val, zval *track_vars_array TSRMLS_DC) { char *p = NULL; char *ip; /* index pointer */ char *index; char *var, *var_orig; int var_len, index_len; zval *gpc_element, **gpc_element_p; zend_bool is_array = 0; HashTable *symtable1 = NULL; ALLOCA_FLAG(use_heap) assert(var_name != NULL); if (track_vars_array) { symtable1 = Z_ARRVAL_P(track_vars_array); } if (!symtable1) { /* Nothing to do */ zval_dtor(val); return; } /* ignore leading spaces in the variable name */ while (*var_name && *var_name==' ') { var_name++; } /* * Prepare variable name */ var_len = strlen(var_name); var = var_orig = do_alloca(var_len + 1, use_heap); memcpy(var_orig, var_name, var_len + 1); /* ensure that we don't have spaces or dots in the variable name (not binary safe) */ for (p = var; *p; p++) { if (*p == ' ' || *p == '.') { *p='_'; } else if (*p == '[') { is_array = 1; ip = p; *p = 0; break; } } var_len = p - var; if (var_len==0) { /* empty variable name, or variable name with a space in it */ zval_dtor(val); free_alloca(var_orig, use_heap); return; } /* GLOBALS hijack attempt, reject parameter */ if (symtable1 == EG(active_symbol_table) && var_len == sizeof("GLOBALS")-1 && !memcmp(var, "GLOBALS", sizeof("GLOBALS")-1)) { zval_dtor(val); free_alloca(var_orig, use_heap); return; } index = var; index_len = var_len; if (is_array) { int nest_level = 0; while (1) { char *index_s; int new_idx_len = 0; if(++nest_level > PG(max_input_nesting_level)) { HashTable *ht; /* too many levels of nesting */ if (track_vars_array) { ht = Z_ARRVAL_P(track_vars_array); zend_hash_del(ht, var, var_len + 1); } zval_dtor(val); /* do not output the error message to the screen, this helps us to to avoid "information disclosure" */ if (!PG(display_errors)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Input variable nesting level exceeded %ld. To increase the limit change max_input_nesting_level in php.ini.", PG(max_input_nesting_level)); } free_alloca(var_orig, use_heap); return; } ip++; index_s = ip; if (isspace(*ip)) { ip++; } if (*ip==']') { index_s = NULL; } else { ip = strchr(ip, ']'); if (!ip) { /* PHP variables cannot contain '[' in their names, so we replace the character with a '_' */ *(index_s - 1) = '_'; index_len = 0; if (index) { index_len = strlen(index); } goto plain_var; return; } *ip = 0; new_idx_len = strlen(index_s); } if (!index) { MAKE_STD_ZVAL(gpc_element); array_init(gpc_element); if (zend_hash_next_index_insert(symtable1, &gpc_element, sizeof(zval *), (void **) &gpc_element_p) == FAILURE) { zval_ptr_dtor(&gpc_element); zval_dtor(val); free_alloca(var_orig, use_heap); return; } } else { if (zend_symtable_find(symtable1, index, index_len + 1, (void **) &gpc_element_p) == FAILURE || Z_TYPE_PP(gpc_element_p) != IS_ARRAY) { if (zend_hash_num_elements(symtable1) <= PG(max_input_vars)) { if (zend_hash_num_elements(symtable1) == PG(max_input_vars)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Input variables exceeded %ld. To increase the limit change max_input_vars in php.ini.", PG(max_input_vars)); } MAKE_STD_ZVAL(gpc_element); array_init(gpc_element); zend_symtable_update(symtable1, index, index_len + 1, &gpc_element, sizeof(zval *), (void **) &gpc_element_p); } else { zval_dtor(val); free_alloca(var_orig, use_heap); return; } } } symtable1 = Z_ARRVAL_PP(gpc_element_p); /* ip pointed to the '[' character, now obtain the key */ index = index_s; index_len = new_idx_len; ip++; if (*ip == '[') { is_array = 1; *ip = 0; } else { goto plain_var; } } } else { plain_var: MAKE_STD_ZVAL(gpc_element); gpc_element->value = val->value; Z_TYPE_P(gpc_element) = Z_TYPE_P(val); if (!index) { if (zend_hash_next_index_insert(symtable1, &gpc_element, sizeof(zval *), (void **) &gpc_element_p) == FAILURE) { zval_ptr_dtor(&gpc_element); } } else { /* * According to rfc2965, more specific paths are listed above the less specific ones. * If we encounter a duplicate cookie name, we should skip it, since it is not possible * to have the same (plain text) cookie name for the same path and we should not overwrite * more specific cookies with the less specific ones. */ if (PG(http_globals)[TRACK_VARS_COOKIE] && symtable1 == Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_COOKIE]) && zend_symtable_exists(symtable1, index, index_len + 1)) { zval_ptr_dtor(&gpc_element); } else { if (zend_hash_num_elements(symtable1) <= PG(max_input_vars)) { if (zend_hash_num_elements(symtable1) == PG(max_input_vars)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Input variables exceeded %ld. To increase the limit change max_input_vars in php.ini.", PG(max_input_vars)); } zend_symtable_update(symtable1, index, index_len + 1, &gpc_element, sizeof(zval *), (void **) &gpc_element_p); } else { zval_ptr_dtor(&gpc_element); } } } } free_alloca(var_orig, use_heap); } SAPI_API SAPI_POST_HANDLER_FUNC(php_std_post_handler) { char *var, *val, *e, *s, *p; zval *array_ptr = (zval *) arg; if (SG(request_info).post_data == NULL) { return; } s = SG(request_info).post_data; e = s + SG(request_info).post_data_length; while (s < e && (p = memchr(s, '&', (e - s)))) { last_value: if ((val = memchr(s, '=', (p - s)))) { /* have a value */ unsigned int val_len, new_val_len; var = s; php_url_decode(var, (val - s)); val++; val_len = php_url_decode(val, (p - val)); val = estrndup(val, val_len); if (sapi_module.input_filter(PARSE_POST, var, &val, val_len, &new_val_len TSRMLS_CC)) { php_register_variable_safe(var, val, new_val_len, array_ptr TSRMLS_CC); } efree(val); } s = p + 1; } if (s < e) { p = e; goto last_value; } } SAPI_API SAPI_INPUT_FILTER_FUNC(php_default_input_filter) { /* TODO: check .ini setting here and apply user-defined input filter */ if(new_val_len) *new_val_len = val_len; return 1; } SAPI_API SAPI_TREAT_DATA_FUNC(php_default_treat_data) { char *res = NULL, *var, *val, *separator = NULL; const char *c_var; zval *array_ptr; int free_buffer = 0; char *strtok_buf = NULL; switch (arg) { case PARSE_POST: case PARSE_GET: case PARSE_COOKIE: ALLOC_ZVAL(array_ptr); array_init(array_ptr); INIT_PZVAL(array_ptr); switch (arg) { case PARSE_POST: if (PG(http_globals)[TRACK_VARS_POST]) { zval_ptr_dtor(&PG(http_globals)[TRACK_VARS_POST]); } PG(http_globals)[TRACK_VARS_POST] = array_ptr; break; case PARSE_GET: if (PG(http_globals)[TRACK_VARS_GET]) { zval_ptr_dtor(&PG(http_globals)[TRACK_VARS_GET]); } PG(http_globals)[TRACK_VARS_GET] = array_ptr; break; case PARSE_COOKIE: if (PG(http_globals)[TRACK_VARS_COOKIE]) { zval_ptr_dtor(&PG(http_globals)[TRACK_VARS_COOKIE]); } PG(http_globals)[TRACK_VARS_COOKIE] = array_ptr; break; } break; default: array_ptr = destArray; break; } if (arg == PARSE_POST) { sapi_handle_post(array_ptr TSRMLS_CC); return; } if (arg == PARSE_GET) { /* GET data */ c_var = SG(request_info).query_string; if (c_var && *c_var) { res = (char *) estrdup(c_var); free_buffer = 1; } else { free_buffer = 0; } } else if (arg == PARSE_COOKIE) { /* Cookie data */ c_var = SG(request_info).cookie_data; if (c_var && *c_var) { res = (char *) estrdup(c_var); free_buffer = 1; } else { free_buffer = 0; } } else if (arg == PARSE_STRING) { /* String data */ res = str; free_buffer = 1; } if (!res) { return; } switch (arg) { case PARSE_GET: case PARSE_STRING: separator = (char *) estrdup(PG(arg_separator).input); break; case PARSE_COOKIE: separator = ";\0"; break; } var = php_strtok_r(res, separator, &strtok_buf); while (var) { val = strchr(var, '='); if (arg == PARSE_COOKIE) { /* Remove leading spaces from cookie names, needed for multi-cookie header where ; can be followed by a space */ while (isspace(*var)) { var++; } if (var == val || *var == '\0') { goto next_cookie; } } if (val) { /* have a value */ int val_len; unsigned int new_val_len; *val++ = '\0'; php_url_decode(var, strlen(var)); val_len = php_url_decode(val, strlen(val)); val = estrndup(val, val_len); if (sapi_module.input_filter(arg, var, &val, val_len, &new_val_len TSRMLS_CC)) { php_register_variable_safe(var, val, new_val_len, array_ptr TSRMLS_CC); } efree(val); } else { int val_len; unsigned int new_val_len; php_url_decode(var, strlen(var)); val_len = 0; val = estrndup("", val_len); if (sapi_module.input_filter(arg, var, &val, val_len, &new_val_len TSRMLS_CC)) { php_register_variable_safe(var, val, new_val_len, array_ptr TSRMLS_CC); } efree(val); } next_cookie: var = php_strtok_r(NULL, separator, &strtok_buf); } if (arg != PARSE_COOKIE) { efree(separator); } if (free_buffer) { efree(res); } } void _php_import_environment_variables(zval *array_ptr TSRMLS_DC) { char buf[128]; char **env, *p, *t = buf; size_t alloc_size = sizeof(buf); unsigned long nlen; /* ptrdiff_t is not portable */ for (env = environ; env != NULL && *env != NULL; env++) { p = strchr(*env, '='); if (!p) { /* malformed entry? */ continue; } nlen = p - *env; if (nlen >= alloc_size) { alloc_size = nlen + 64; t = (t == buf ? emalloc(alloc_size): erealloc(t, alloc_size)); } memcpy(t, *env, nlen); t[nlen] = '\0'; php_register_variable(t, p + 1, array_ptr TSRMLS_CC); } if (t != buf && t != NULL) { efree(t); } } zend_bool php_std_auto_global_callback(char *name, uint name_len TSRMLS_DC) { zend_printf("%s\n", name); return 0; /* don't rearm */ } /* {{{ php_build_argv */ static void php_build_argv(char *s, zval *track_vars_array TSRMLS_DC) { zval *arr, *argc, *tmp; int count = 0; char *ss, *space; if (!(SG(request_info).argc || track_vars_array)) { return; } ALLOC_INIT_ZVAL(arr); array_init(arr); /* Prepare argv */ if (SG(request_info).argc) { /* are we in cli sapi? */ int i; for (i = 0; i < SG(request_info).argc; i++) { ALLOC_ZVAL(tmp); Z_TYPE_P(tmp) = IS_STRING; Z_STRLEN_P(tmp) = strlen(SG(request_info).argv[i]); Z_STRVAL_P(tmp) = estrndup(SG(request_info).argv[i], Z_STRLEN_P(tmp)); INIT_PZVAL(tmp); if (zend_hash_next_index_insert(Z_ARRVAL_P(arr), &tmp, sizeof(zval *), NULL) == FAILURE) { if (Z_TYPE_P(tmp) == IS_STRING) { efree(Z_STRVAL_P(tmp)); } } } } else if (s && *s) { ss = s; while (ss) { space = strchr(ss, '+'); if (space) { *space = '\0'; } /* auto-type */ ALLOC_ZVAL(tmp); Z_TYPE_P(tmp) = IS_STRING; Z_STRLEN_P(tmp) = strlen(ss); Z_STRVAL_P(tmp) = estrndup(ss, Z_STRLEN_P(tmp)); INIT_PZVAL(tmp); count++; if (zend_hash_next_index_insert(Z_ARRVAL_P(arr), &tmp, sizeof(zval *), NULL) == FAILURE) { if (Z_TYPE_P(tmp) == IS_STRING) { efree(Z_STRVAL_P(tmp)); } } if (space) { *space = '+'; ss = space + 1; } else { ss = space; } } } /* prepare argc */ ALLOC_INIT_ZVAL(argc); if (SG(request_info).argc) { Z_LVAL_P(argc) = SG(request_info).argc; } else { Z_LVAL_P(argc) = count; } Z_TYPE_P(argc) = IS_LONG; if (SG(request_info).argc) { Z_ADDREF_P(arr); Z_ADDREF_P(argc); zend_hash_update(&EG(symbol_table), "argv", sizeof("argv"), &arr, sizeof(zval *), NULL); zend_hash_add(&EG(symbol_table), "argc", sizeof("argc"), &argc, sizeof(zval *), NULL); } if (track_vars_array) { Z_ADDREF_P(arr); Z_ADDREF_P(argc); zend_hash_update(Z_ARRVAL_P(track_vars_array), "argv", sizeof("argv"), &arr, sizeof(zval *), NULL); zend_hash_update(Z_ARRVAL_P(track_vars_array), "argc", sizeof("argc"), &argc, sizeof(zval *), NULL); } zval_ptr_dtor(&arr); zval_ptr_dtor(&argc); } /* }}} */ /* {{{ php_handle_special_queries */ PHPAPI int php_handle_special_queries(TSRMLS_D) { if (PG(expose_php) && SG(request_info).query_string && SG(request_info).query_string[0] == '=') { if (php_info_logos(SG(request_info).query_string + 1 TSRMLS_CC)) { return 1; } else if (!strcmp(SG(request_info).query_string + 1, PHP_CREDITS_GUID)) { php_print_credits(PHP_CREDITS_ALL TSRMLS_CC); return 1; } } return 0; } /* }}} */ /* {{{ php_register_server_variables */ static inline void php_register_server_variables(TSRMLS_D) { zval *array_ptr = NULL; ALLOC_ZVAL(array_ptr); array_init(array_ptr); INIT_PZVAL(array_ptr); if (PG(http_globals)[TRACK_VARS_SERVER]) { zval_ptr_dtor(&PG(http_globals)[TRACK_VARS_SERVER]); } PG(http_globals)[TRACK_VARS_SERVER] = array_ptr; /* Server variables */ if (sapi_module.register_server_variables) { sapi_module.register_server_variables(array_ptr TSRMLS_CC); } /* PHP Authentication support */ if (SG(request_info).auth_user) { php_register_variable("PHP_AUTH_USER", SG(request_info).auth_user, array_ptr TSRMLS_CC); } if (SG(request_info).auth_password) { php_register_variable("PHP_AUTH_PW", SG(request_info).auth_password, array_ptr TSRMLS_CC); } if (SG(request_info).auth_digest) { php_register_variable("PHP_AUTH_DIGEST", SG(request_info).auth_digest, array_ptr TSRMLS_CC); } /* store request init time */ { zval request_time_float, request_time_long; Z_TYPE(request_time_float) = IS_DOUBLE; Z_DVAL(request_time_float) = sapi_get_request_time(TSRMLS_C); php_register_variable_ex("REQUEST_TIME_FLOAT", &request_time_float, array_ptr TSRMLS_CC); Z_TYPE(request_time_long) = IS_LONG; Z_LVAL(request_time_long) = zend_dval_to_lval(Z_DVAL(request_time_float)); php_register_variable_ex("REQUEST_TIME", &request_time_long, array_ptr TSRMLS_CC); } } /* }}} */ /* {{{ php_autoglobal_merge */ static void php_autoglobal_merge(HashTable *dest, HashTable *src TSRMLS_DC) { zval **src_entry, **dest_entry; char *string_key; uint string_key_len; ulong num_key; HashPosition pos; int key_type; int globals_check = (dest == (&EG(symbol_table))); zend_hash_internal_pointer_reset_ex(src, &pos); while (zend_hash_get_current_data_ex(src, (void **)&src_entry, &pos) == SUCCESS) { key_type = zend_hash_get_current_key_ex(src, &string_key, &string_key_len, &num_key, 0, &pos); if (Z_TYPE_PP(src_entry) != IS_ARRAY || (key_type == HASH_KEY_IS_STRING && zend_hash_find(dest, string_key, string_key_len, (void **) &dest_entry) != SUCCESS) || (key_type == HASH_KEY_IS_LONG && zend_hash_index_find(dest, num_key, (void **)&dest_entry) != SUCCESS) || Z_TYPE_PP(dest_entry) != IS_ARRAY ) { Z_ADDREF_PP(src_entry); if (key_type == HASH_KEY_IS_STRING) { if (!globals_check || string_key_len != sizeof("GLOBALS") || memcmp(string_key, "GLOBALS", sizeof("GLOBALS") - 1)) { zend_hash_update(dest, string_key, string_key_len, src_entry, sizeof(zval *), NULL); } else { Z_DELREF_PP(src_entry); } } else { zend_hash_index_update(dest, num_key, src_entry, sizeof(zval *), NULL); } } else { SEPARATE_ZVAL(dest_entry); php_autoglobal_merge(Z_ARRVAL_PP(dest_entry), Z_ARRVAL_PP(src_entry) TSRMLS_CC); } zend_hash_move_forward_ex(src, &pos); } } /* }}} */ static zend_bool php_auto_globals_create_server(const char *name, uint name_len TSRMLS_DC); static zend_bool php_auto_globals_create_env(const char *name, uint name_len TSRMLS_DC); static zend_bool php_auto_globals_create_request(const char *name, uint name_len TSRMLS_DC); /* {{{ php_hash_environment */ int php_hash_environment(TSRMLS_D) { memset(PG(http_globals), 0, sizeof(PG(http_globals))); zend_activate_auto_globals(TSRMLS_C); if (PG(register_argc_argv)) { php_build_argv(SG(request_info).query_string, PG(http_globals)[TRACK_VARS_SERVER] TSRMLS_CC); } return SUCCESS; } /* }}} */ static zend_bool php_auto_globals_create_get(const char *name, uint name_len TSRMLS_DC) { zval *vars; if (PG(variables_order) && (strchr(PG(variables_order),'G') || strchr(PG(variables_order),'g'))) { sapi_module.treat_data(PARSE_GET, NULL, NULL TSRMLS_CC); vars = PG(http_globals)[TRACK_VARS_GET]; } else { ALLOC_ZVAL(vars); array_init(vars); INIT_PZVAL(vars); if (PG(http_globals)[TRACK_VARS_GET]) { zval_ptr_dtor(&PG(http_globals)[TRACK_VARS_GET]); } PG(http_globals)[TRACK_VARS_GET] = vars; } zend_hash_update(&EG(symbol_table), name, name_len + 1, &vars, sizeof(zval *), NULL); Z_ADDREF_P(vars); return 0; /* don't rearm */ } static zend_bool php_auto_globals_create_post(const char *name, uint name_len TSRMLS_DC) { zval *vars; if (PG(variables_order) && (strchr(PG(variables_order),'P') || strchr(PG(variables_order),'p')) && !SG(headers_sent) && SG(request_info).request_method && !strcasecmp(SG(request_info).request_method, "POST")) { sapi_module.treat_data(PARSE_POST, NULL, NULL TSRMLS_CC); vars = PG(http_globals)[TRACK_VARS_POST]; } else { ALLOC_ZVAL(vars); array_init(vars); INIT_PZVAL(vars); if (PG(http_globals)[TRACK_VARS_POST]) { zval_ptr_dtor(&PG(http_globals)[TRACK_VARS_POST]); } PG(http_globals)[TRACK_VARS_POST] = vars; } zend_hash_update(&EG(symbol_table), name, name_len + 1, &vars, sizeof(zval *), NULL); Z_ADDREF_P(vars); return 0; /* don't rearm */ } static zend_bool php_auto_globals_create_cookie(const char *name, uint name_len TSRMLS_DC) { zval *vars; if (PG(variables_order) && (strchr(PG(variables_order),'C') || strchr(PG(variables_order),'c'))) { sapi_module.treat_data(PARSE_COOKIE, NULL, NULL TSRMLS_CC); vars = PG(http_globals)[TRACK_VARS_COOKIE]; } else { ALLOC_ZVAL(vars); array_init(vars); INIT_PZVAL(vars); if (PG(http_globals)[TRACK_VARS_COOKIE]) { zval_ptr_dtor(&PG(http_globals)[TRACK_VARS_COOKIE]); } PG(http_globals)[TRACK_VARS_COOKIE] = vars; } zend_hash_update(&EG(symbol_table), name, name_len + 1, &vars, sizeof(zval *), NULL); Z_ADDREF_P(vars); return 0; /* don't rearm */ } static zend_bool php_auto_globals_create_files(const char *name, uint name_len TSRMLS_DC) { zval *vars; if (PG(http_globals)[TRACK_VARS_FILES]) { vars = PG(http_globals)[TRACK_VARS_FILES]; } else { ALLOC_ZVAL(vars); array_init(vars); INIT_PZVAL(vars); PG(http_globals)[TRACK_VARS_FILES] = vars; } zend_hash_update(&EG(symbol_table), name, name_len + 1, &vars, sizeof(zval *), NULL); Z_ADDREF_P(vars); return 0; /* don't rearm */ } static zend_bool php_auto_globals_create_server(const char *name, uint name_len TSRMLS_DC) { if (PG(variables_order) && (strchr(PG(variables_order),'S') || strchr(PG(variables_order),'s'))) { php_register_server_variables(TSRMLS_C); if (PG(register_argc_argv)) { if (SG(request_info).argc) { zval **argc, **argv; if (zend_hash_find(&EG(symbol_table), "argc", sizeof("argc"), (void**)&argc) == SUCCESS && zend_hash_find(&EG(symbol_table), "argv", sizeof("argv"), (void**)&argv) == SUCCESS) { Z_ADDREF_PP(argc); Z_ADDREF_PP(argv); zend_hash_update(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]), "argv", sizeof("argv"), argv, sizeof(zval *), NULL); zend_hash_update(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]), "argc", sizeof("argc"), argc, sizeof(zval *), NULL); } } else { php_build_argv(SG(request_info).query_string, PG(http_globals)[TRACK_VARS_SERVER] TSRMLS_CC); } } } else { zval *server_vars=NULL; ALLOC_ZVAL(server_vars); array_init(server_vars); INIT_PZVAL(server_vars); if (PG(http_globals)[TRACK_VARS_SERVER]) { zval_ptr_dtor(&PG(http_globals)[TRACK_VARS_SERVER]); } PG(http_globals)[TRACK_VARS_SERVER] = server_vars; } zend_hash_update(&EG(symbol_table), name, name_len + 1, &PG(http_globals)[TRACK_VARS_SERVER], sizeof(zval *), NULL); Z_ADDREF_P(PG(http_globals)[TRACK_VARS_SERVER]); return 0; /* don't rearm */ } static zend_bool php_auto_globals_create_env(const char *name, uint name_len TSRMLS_DC) { zval *env_vars = NULL; ALLOC_ZVAL(env_vars); array_init(env_vars); INIT_PZVAL(env_vars); if (PG(http_globals)[TRACK_VARS_ENV]) { zval_ptr_dtor(&PG(http_globals)[TRACK_VARS_ENV]); } PG(http_globals)[TRACK_VARS_ENV] = env_vars; if (PG(variables_order) && (strchr(PG(variables_order),'E') || strchr(PG(variables_order),'e'))) { php_import_environment_variables(PG(http_globals)[TRACK_VARS_ENV] TSRMLS_CC); } zend_hash_update(&EG(symbol_table), name, name_len + 1, &PG(http_globals)[TRACK_VARS_ENV], sizeof(zval *), NULL); Z_ADDREF_P(PG(http_globals)[TRACK_VARS_ENV]); return 0; /* don't rearm */ } static zend_bool php_auto_globals_create_request(const char *name, uint name_len TSRMLS_DC) { zval *form_variables; unsigned char _gpc_flags[3] = {0, 0, 0}; char *p; ALLOC_ZVAL(form_variables); array_init(form_variables); INIT_PZVAL(form_variables); if (PG(request_order) != NULL) { p = PG(request_order); } else { p = PG(variables_order); } for (; p && *p; p++) { switch (*p) { case 'g': case 'G': if (!_gpc_flags[0]) { php_autoglobal_merge(Z_ARRVAL_P(form_variables), Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_GET]) TSRMLS_CC); _gpc_flags[0] = 1; } break; case 'p': case 'P': if (!_gpc_flags[1]) { php_autoglobal_merge(Z_ARRVAL_P(form_variables), Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_POST]) TSRMLS_CC); _gpc_flags[1] = 1; } break; case 'c': case 'C': if (!_gpc_flags[2]) { php_autoglobal_merge(Z_ARRVAL_P(form_variables), Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_COOKIE]) TSRMLS_CC); _gpc_flags[2] = 1; } break; } } zend_hash_update(&EG(symbol_table), name, name_len + 1, &form_variables, sizeof(zval *), NULL); return 0; } void php_startup_auto_globals(TSRMLS_D) { zend_register_auto_global(ZEND_STRL("_GET"), 0, php_auto_globals_create_get TSRMLS_CC); zend_register_auto_global(ZEND_STRL("_POST"), 0, php_auto_globals_create_post TSRMLS_CC); zend_register_auto_global(ZEND_STRL("_COOKIE"), 0, php_auto_globals_create_cookie TSRMLS_CC); zend_register_auto_global(ZEND_STRL("_SERVER"), PG(auto_globals_jit), php_auto_globals_create_server TSRMLS_CC); zend_register_auto_global(ZEND_STRL("_ENV"), PG(auto_globals_jit), php_auto_globals_create_env TSRMLS_CC); zend_register_auto_global(ZEND_STRL("_REQUEST"), PG(auto_globals_jit), php_auto_globals_create_request TSRMLS_CC); zend_register_auto_global(ZEND_STRL("_FILES"), 0, php_auto_globals_create_files TSRMLS_CC); } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2012 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Rasmus Lerdorf <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <stdio.h> #include "php.h" #include "ext/standard/php_standard.h" #include "ext/standard/credits.h" #include "php_variables.h" #include "php_globals.h" #include "php_content_types.h" #include "SAPI.h" #include "php_logos.h" #include "zend_globals.h" /* for systems that need to override reading of environment variables */ void _php_import_environment_variables(zval *array_ptr TSRMLS_DC); PHPAPI void (*php_import_environment_variables)(zval *array_ptr TSRMLS_DC) = _php_import_environment_variables; PHPAPI void php_register_variable(char *var, char *strval, zval *track_vars_array TSRMLS_DC) { php_register_variable_safe(var, strval, strlen(strval), track_vars_array TSRMLS_CC); } /* binary-safe version */ PHPAPI void php_register_variable_safe(char *var, char *strval, int str_len, zval *track_vars_array TSRMLS_DC) { zval new_entry; assert(strval != NULL); /* Prepare value */ Z_STRLEN(new_entry) = str_len; Z_STRVAL(new_entry) = estrndup(strval, Z_STRLEN(new_entry)); Z_TYPE(new_entry) = IS_STRING; php_register_variable_ex(var, &new_entry, track_vars_array TSRMLS_CC); } PHPAPI void php_register_variable_ex(char *var_name, zval *val, zval *track_vars_array TSRMLS_DC) { char *p = NULL; char *ip; /* index pointer */ char *index; char *var, *var_orig; int var_len, index_len; zval *gpc_element, **gpc_element_p; zend_bool is_array = 0; HashTable *symtable1 = NULL; ALLOCA_FLAG(use_heap) assert(var_name != NULL); if (track_vars_array) { symtable1 = Z_ARRVAL_P(track_vars_array); } if (!symtable1) { /* Nothing to do */ zval_dtor(val); return; } /* ignore leading spaces in the variable name */ while (*var_name && *var_name==' ') { var_name++; } /* * Prepare variable name */ var_len = strlen(var_name); var = var_orig = do_alloca(var_len + 1, use_heap); memcpy(var_orig, var_name, var_len + 1); /* ensure that we don't have spaces or dots in the variable name (not binary safe) */ for (p = var; *p; p++) { if (*p == ' ' || *p == '.') { *p='_'; } else if (*p == '[') { is_array = 1; ip = p; *p = 0; break; } } var_len = p - var; if (var_len==0) { /* empty variable name, or variable name with a space in it */ zval_dtor(val); free_alloca(var_orig, use_heap); return; } /* GLOBALS hijack attempt, reject parameter */ if (symtable1 == EG(active_symbol_table) && var_len == sizeof("GLOBALS")-1 && !memcmp(var, "GLOBALS", sizeof("GLOBALS")-1)) { zval_dtor(val); free_alloca(var_orig, use_heap); return; } index = var; index_len = var_len; if (is_array) { int nest_level = 0; while (1) { char *index_s; int new_idx_len = 0; if(++nest_level > PG(max_input_nesting_level)) { HashTable *ht; /* too many levels of nesting */ if (track_vars_array) { ht = Z_ARRVAL_P(track_vars_array); zend_symtable_del(ht, var, var_len + 1); } zval_dtor(val); /* do not output the error message to the screen, this helps us to to avoid "information disclosure" */ if (!PG(display_errors)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Input variable nesting level exceeded %ld. To increase the limit change max_input_nesting_level in php.ini.", PG(max_input_nesting_level)); } free_alloca(var_orig, use_heap); return; } ip++; index_s = ip; if (isspace(*ip)) { ip++; } if (*ip==']') { index_s = NULL; } else { ip = strchr(ip, ']'); if (!ip) { /* PHP variables cannot contain '[' in their names, so we replace the character with a '_' */ *(index_s - 1) = '_'; index_len = 0; if (index) { index_len = strlen(index); } goto plain_var; return; } *ip = 0; new_idx_len = strlen(index_s); } if (!index) { MAKE_STD_ZVAL(gpc_element); array_init(gpc_element); if (zend_hash_next_index_insert(symtable1, &gpc_element, sizeof(zval *), (void **) &gpc_element_p) == FAILURE) { zval_ptr_dtor(&gpc_element); zval_dtor(val); free_alloca(var_orig, use_heap); return; } } else { if (zend_symtable_find(symtable1, index, index_len + 1, (void **) &gpc_element_p) == FAILURE || Z_TYPE_PP(gpc_element_p) != IS_ARRAY) { if (zend_hash_num_elements(symtable1) <= PG(max_input_vars)) { if (zend_hash_num_elements(symtable1) == PG(max_input_vars)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Input variables exceeded %ld. To increase the limit change max_input_vars in php.ini.", PG(max_input_vars)); } MAKE_STD_ZVAL(gpc_element); array_init(gpc_element); zend_symtable_update(symtable1, index, index_len + 1, &gpc_element, sizeof(zval *), (void **) &gpc_element_p); } else { zval_dtor(val); free_alloca(var_orig, use_heap); return; } } } symtable1 = Z_ARRVAL_PP(gpc_element_p); /* ip pointed to the '[' character, now obtain the key */ index = index_s; index_len = new_idx_len; ip++; if (*ip == '[') { is_array = 1; *ip = 0; } else { goto plain_var; } } } else { plain_var: MAKE_STD_ZVAL(gpc_element); gpc_element->value = val->value; Z_TYPE_P(gpc_element) = Z_TYPE_P(val); if (!index) { if (zend_hash_next_index_insert(symtable1, &gpc_element, sizeof(zval *), (void **) &gpc_element_p) == FAILURE) { zval_ptr_dtor(&gpc_element); } } else { /* * According to rfc2965, more specific paths are listed above the less specific ones. * If we encounter a duplicate cookie name, we should skip it, since it is not possible * to have the same (plain text) cookie name for the same path and we should not overwrite * more specific cookies with the less specific ones. */ if (PG(http_globals)[TRACK_VARS_COOKIE] && symtable1 == Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_COOKIE]) && zend_symtable_exists(symtable1, index, index_len + 1)) { zval_ptr_dtor(&gpc_element); } else { if (zend_hash_num_elements(symtable1) <= PG(max_input_vars)) { if (zend_hash_num_elements(symtable1) == PG(max_input_vars)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Input variables exceeded %ld. To increase the limit change max_input_vars in php.ini.", PG(max_input_vars)); } zend_symtable_update(symtable1, index, index_len + 1, &gpc_element, sizeof(zval *), (void **) &gpc_element_p); } else { zval_ptr_dtor(&gpc_element); } } } } free_alloca(var_orig, use_heap); } SAPI_API SAPI_POST_HANDLER_FUNC(php_std_post_handler) { char *var, *val, *e, *s, *p; zval *array_ptr = (zval *) arg; if (SG(request_info).post_data == NULL) { return; } s = SG(request_info).post_data; e = s + SG(request_info).post_data_length; while (s < e && (p = memchr(s, '&', (e - s)))) { last_value: if ((val = memchr(s, '=', (p - s)))) { /* have a value */ unsigned int val_len, new_val_len; var = s; php_url_decode(var, (val - s)); val++; val_len = php_url_decode(val, (p - val)); val = estrndup(val, val_len); if (sapi_module.input_filter(PARSE_POST, var, &val, val_len, &new_val_len TSRMLS_CC)) { php_register_variable_safe(var, val, new_val_len, array_ptr TSRMLS_CC); } efree(val); } s = p + 1; } if (s < e) { p = e; goto last_value; } } SAPI_API SAPI_INPUT_FILTER_FUNC(php_default_input_filter) { /* TODO: check .ini setting here and apply user-defined input filter */ if(new_val_len) *new_val_len = val_len; return 1; } SAPI_API SAPI_TREAT_DATA_FUNC(php_default_treat_data) { char *res = NULL, *var, *val, *separator = NULL; const char *c_var; zval *array_ptr; int free_buffer = 0; char *strtok_buf = NULL; switch (arg) { case PARSE_POST: case PARSE_GET: case PARSE_COOKIE: ALLOC_ZVAL(array_ptr); array_init(array_ptr); INIT_PZVAL(array_ptr); switch (arg) { case PARSE_POST: if (PG(http_globals)[TRACK_VARS_POST]) { zval_ptr_dtor(&PG(http_globals)[TRACK_VARS_POST]); } PG(http_globals)[TRACK_VARS_POST] = array_ptr; break; case PARSE_GET: if (PG(http_globals)[TRACK_VARS_GET]) { zval_ptr_dtor(&PG(http_globals)[TRACK_VARS_GET]); } PG(http_globals)[TRACK_VARS_GET] = array_ptr; break; case PARSE_COOKIE: if (PG(http_globals)[TRACK_VARS_COOKIE]) { zval_ptr_dtor(&PG(http_globals)[TRACK_VARS_COOKIE]); } PG(http_globals)[TRACK_VARS_COOKIE] = array_ptr; break; } break; default: array_ptr = destArray; break; } if (arg == PARSE_POST) { sapi_handle_post(array_ptr TSRMLS_CC); return; } if (arg == PARSE_GET) { /* GET data */ c_var = SG(request_info).query_string; if (c_var && *c_var) { res = (char *) estrdup(c_var); free_buffer = 1; } else { free_buffer = 0; } } else if (arg == PARSE_COOKIE) { /* Cookie data */ c_var = SG(request_info).cookie_data; if (c_var && *c_var) { res = (char *) estrdup(c_var); free_buffer = 1; } else { free_buffer = 0; } } else if (arg == PARSE_STRING) { /* String data */ res = str; free_buffer = 1; } if (!res) { return; } switch (arg) { case PARSE_GET: case PARSE_STRING: separator = (char *) estrdup(PG(arg_separator).input); break; case PARSE_COOKIE: separator = ";\0"; break; } var = php_strtok_r(res, separator, &strtok_buf); while (var) { val = strchr(var, '='); if (arg == PARSE_COOKIE) { /* Remove leading spaces from cookie names, needed for multi-cookie header where ; can be followed by a space */ while (isspace(*var)) { var++; } if (var == val || *var == '\0') { goto next_cookie; } } if (val) { /* have a value */ int val_len; unsigned int new_val_len; *val++ = '\0'; php_url_decode(var, strlen(var)); val_len = php_url_decode(val, strlen(val)); val = estrndup(val, val_len); if (sapi_module.input_filter(arg, var, &val, val_len, &new_val_len TSRMLS_CC)) { php_register_variable_safe(var, val, new_val_len, array_ptr TSRMLS_CC); } efree(val); } else { int val_len; unsigned int new_val_len; php_url_decode(var, strlen(var)); val_len = 0; val = estrndup("", val_len); if (sapi_module.input_filter(arg, var, &val, val_len, &new_val_len TSRMLS_CC)) { php_register_variable_safe(var, val, new_val_len, array_ptr TSRMLS_CC); } efree(val); } next_cookie: var = php_strtok_r(NULL, separator, &strtok_buf); } if (arg != PARSE_COOKIE) { efree(separator); } if (free_buffer) { efree(res); } } void _php_import_environment_variables(zval *array_ptr TSRMLS_DC) { char buf[128]; char **env, *p, *t = buf; size_t alloc_size = sizeof(buf); unsigned long nlen; /* ptrdiff_t is not portable */ for (env = environ; env != NULL && *env != NULL; env++) { p = strchr(*env, '='); if (!p) { /* malformed entry? */ continue; } nlen = p - *env; if (nlen >= alloc_size) { alloc_size = nlen + 64; t = (t == buf ? emalloc(alloc_size): erealloc(t, alloc_size)); } memcpy(t, *env, nlen); t[nlen] = '\0'; php_register_variable(t, p + 1, array_ptr TSRMLS_CC); } if (t != buf && t != NULL) { efree(t); } } zend_bool php_std_auto_global_callback(char *name, uint name_len TSRMLS_DC) { zend_printf("%s\n", name); return 0; /* don't rearm */ } /* {{{ php_build_argv */ static void php_build_argv(char *s, zval *track_vars_array TSRMLS_DC) { zval *arr, *argc, *tmp; int count = 0; char *ss, *space; if (!(SG(request_info).argc || track_vars_array)) { return; } ALLOC_INIT_ZVAL(arr); array_init(arr); /* Prepare argv */ if (SG(request_info).argc) { /* are we in cli sapi? */ int i; for (i = 0; i < SG(request_info).argc; i++) { ALLOC_ZVAL(tmp); Z_TYPE_P(tmp) = IS_STRING; Z_STRLEN_P(tmp) = strlen(SG(request_info).argv[i]); Z_STRVAL_P(tmp) = estrndup(SG(request_info).argv[i], Z_STRLEN_P(tmp)); INIT_PZVAL(tmp); if (zend_hash_next_index_insert(Z_ARRVAL_P(arr), &tmp, sizeof(zval *), NULL) == FAILURE) { if (Z_TYPE_P(tmp) == IS_STRING) { efree(Z_STRVAL_P(tmp)); } } } } else if (s && *s) { ss = s; while (ss) { space = strchr(ss, '+'); if (space) { *space = '\0'; } /* auto-type */ ALLOC_ZVAL(tmp); Z_TYPE_P(tmp) = IS_STRING; Z_STRLEN_P(tmp) = strlen(ss); Z_STRVAL_P(tmp) = estrndup(ss, Z_STRLEN_P(tmp)); INIT_PZVAL(tmp); count++; if (zend_hash_next_index_insert(Z_ARRVAL_P(arr), &tmp, sizeof(zval *), NULL) == FAILURE) { if (Z_TYPE_P(tmp) == IS_STRING) { efree(Z_STRVAL_P(tmp)); } } if (space) { *space = '+'; ss = space + 1; } else { ss = space; } } } /* prepare argc */ ALLOC_INIT_ZVAL(argc); if (SG(request_info).argc) { Z_LVAL_P(argc) = SG(request_info).argc; } else { Z_LVAL_P(argc) = count; } Z_TYPE_P(argc) = IS_LONG; if (SG(request_info).argc) { Z_ADDREF_P(arr); Z_ADDREF_P(argc); zend_hash_update(&EG(symbol_table), "argv", sizeof("argv"), &arr, sizeof(zval *), NULL); zend_hash_add(&EG(symbol_table), "argc", sizeof("argc"), &argc, sizeof(zval *), NULL); } if (track_vars_array) { Z_ADDREF_P(arr); Z_ADDREF_P(argc); zend_hash_update(Z_ARRVAL_P(track_vars_array), "argv", sizeof("argv"), &arr, sizeof(zval *), NULL); zend_hash_update(Z_ARRVAL_P(track_vars_array), "argc", sizeof("argc"), &argc, sizeof(zval *), NULL); } zval_ptr_dtor(&arr); zval_ptr_dtor(&argc); } /* }}} */ /* {{{ php_handle_special_queries */ PHPAPI int php_handle_special_queries(TSRMLS_D) { if (PG(expose_php) && SG(request_info).query_string && SG(request_info).query_string[0] == '=') { if (php_info_logos(SG(request_info).query_string + 1 TSRMLS_CC)) { return 1; } else if (!strcmp(SG(request_info).query_string + 1, PHP_CREDITS_GUID)) { php_print_credits(PHP_CREDITS_ALL TSRMLS_CC); return 1; } } return 0; } /* }}} */ /* {{{ php_register_server_variables */ static inline void php_register_server_variables(TSRMLS_D) { zval *array_ptr = NULL; ALLOC_ZVAL(array_ptr); array_init(array_ptr); INIT_PZVAL(array_ptr); if (PG(http_globals)[TRACK_VARS_SERVER]) { zval_ptr_dtor(&PG(http_globals)[TRACK_VARS_SERVER]); } PG(http_globals)[TRACK_VARS_SERVER] = array_ptr; /* Server variables */ if (sapi_module.register_server_variables) { sapi_module.register_server_variables(array_ptr TSRMLS_CC); } /* PHP Authentication support */ if (SG(request_info).auth_user) { php_register_variable("PHP_AUTH_USER", SG(request_info).auth_user, array_ptr TSRMLS_CC); } if (SG(request_info).auth_password) { php_register_variable("PHP_AUTH_PW", SG(request_info).auth_password, array_ptr TSRMLS_CC); } if (SG(request_info).auth_digest) { php_register_variable("PHP_AUTH_DIGEST", SG(request_info).auth_digest, array_ptr TSRMLS_CC); } /* store request init time */ { zval request_time_float, request_time_long; Z_TYPE(request_time_float) = IS_DOUBLE; Z_DVAL(request_time_float) = sapi_get_request_time(TSRMLS_C); php_register_variable_ex("REQUEST_TIME_FLOAT", &request_time_float, array_ptr TSRMLS_CC); Z_TYPE(request_time_long) = IS_LONG; Z_LVAL(request_time_long) = zend_dval_to_lval(Z_DVAL(request_time_float)); php_register_variable_ex("REQUEST_TIME", &request_time_long, array_ptr TSRMLS_CC); } } /* }}} */ /* {{{ php_autoglobal_merge */ static void php_autoglobal_merge(HashTable *dest, HashTable *src TSRMLS_DC) { zval **src_entry, **dest_entry; char *string_key; uint string_key_len; ulong num_key; HashPosition pos; int key_type; int globals_check = (dest == (&EG(symbol_table))); zend_hash_internal_pointer_reset_ex(src, &pos); while (zend_hash_get_current_data_ex(src, (void **)&src_entry, &pos) == SUCCESS) { key_type = zend_hash_get_current_key_ex(src, &string_key, &string_key_len, &num_key, 0, &pos); if (Z_TYPE_PP(src_entry) != IS_ARRAY || (key_type == HASH_KEY_IS_STRING && zend_hash_find(dest, string_key, string_key_len, (void **) &dest_entry) != SUCCESS) || (key_type == HASH_KEY_IS_LONG && zend_hash_index_find(dest, num_key, (void **)&dest_entry) != SUCCESS) || Z_TYPE_PP(dest_entry) != IS_ARRAY ) { Z_ADDREF_PP(src_entry); if (key_type == HASH_KEY_IS_STRING) { if (!globals_check || string_key_len != sizeof("GLOBALS") || memcmp(string_key, "GLOBALS", sizeof("GLOBALS") - 1)) { zend_hash_update(dest, string_key, string_key_len, src_entry, sizeof(zval *), NULL); } else { Z_DELREF_PP(src_entry); } } else { zend_hash_index_update(dest, num_key, src_entry, sizeof(zval *), NULL); } } else { SEPARATE_ZVAL(dest_entry); php_autoglobal_merge(Z_ARRVAL_PP(dest_entry), Z_ARRVAL_PP(src_entry) TSRMLS_CC); } zend_hash_move_forward_ex(src, &pos); } } /* }}} */ static zend_bool php_auto_globals_create_server(const char *name, uint name_len TSRMLS_DC); static zend_bool php_auto_globals_create_env(const char *name, uint name_len TSRMLS_DC); static zend_bool php_auto_globals_create_request(const char *name, uint name_len TSRMLS_DC); /* {{{ php_hash_environment */ int php_hash_environment(TSRMLS_D) { memset(PG(http_globals), 0, sizeof(PG(http_globals))); zend_activate_auto_globals(TSRMLS_C); if (PG(register_argc_argv)) { php_build_argv(SG(request_info).query_string, PG(http_globals)[TRACK_VARS_SERVER] TSRMLS_CC); } return SUCCESS; } /* }}} */ static zend_bool php_auto_globals_create_get(const char *name, uint name_len TSRMLS_DC) { zval *vars; if (PG(variables_order) && (strchr(PG(variables_order),'G') || strchr(PG(variables_order),'g'))) { sapi_module.treat_data(PARSE_GET, NULL, NULL TSRMLS_CC); vars = PG(http_globals)[TRACK_VARS_GET]; } else { ALLOC_ZVAL(vars); array_init(vars); INIT_PZVAL(vars); if (PG(http_globals)[TRACK_VARS_GET]) { zval_ptr_dtor(&PG(http_globals)[TRACK_VARS_GET]); } PG(http_globals)[TRACK_VARS_GET] = vars; } zend_hash_update(&EG(symbol_table), name, name_len + 1, &vars, sizeof(zval *), NULL); Z_ADDREF_P(vars); return 0; /* don't rearm */ } static zend_bool php_auto_globals_create_post(const char *name, uint name_len TSRMLS_DC) { zval *vars; if (PG(variables_order) && (strchr(PG(variables_order),'P') || strchr(PG(variables_order),'p')) && !SG(headers_sent) && SG(request_info).request_method && !strcasecmp(SG(request_info).request_method, "POST")) { sapi_module.treat_data(PARSE_POST, NULL, NULL TSRMLS_CC); vars = PG(http_globals)[TRACK_VARS_POST]; } else { ALLOC_ZVAL(vars); array_init(vars); INIT_PZVAL(vars); if (PG(http_globals)[TRACK_VARS_POST]) { zval_ptr_dtor(&PG(http_globals)[TRACK_VARS_POST]); } PG(http_globals)[TRACK_VARS_POST] = vars; } zend_hash_update(&EG(symbol_table), name, name_len + 1, &vars, sizeof(zval *), NULL); Z_ADDREF_P(vars); return 0; /* don't rearm */ } static zend_bool php_auto_globals_create_cookie(const char *name, uint name_len TSRMLS_DC) { zval *vars; if (PG(variables_order) && (strchr(PG(variables_order),'C') || strchr(PG(variables_order),'c'))) { sapi_module.treat_data(PARSE_COOKIE, NULL, NULL TSRMLS_CC); vars = PG(http_globals)[TRACK_VARS_COOKIE]; } else { ALLOC_ZVAL(vars); array_init(vars); INIT_PZVAL(vars); if (PG(http_globals)[TRACK_VARS_COOKIE]) { zval_ptr_dtor(&PG(http_globals)[TRACK_VARS_COOKIE]); } PG(http_globals)[TRACK_VARS_COOKIE] = vars; } zend_hash_update(&EG(symbol_table), name, name_len + 1, &vars, sizeof(zval *), NULL); Z_ADDREF_P(vars); return 0; /* don't rearm */ } static zend_bool php_auto_globals_create_files(const char *name, uint name_len TSRMLS_DC) { zval *vars; if (PG(http_globals)[TRACK_VARS_FILES]) { vars = PG(http_globals)[TRACK_VARS_FILES]; } else { ALLOC_ZVAL(vars); array_init(vars); INIT_PZVAL(vars); PG(http_globals)[TRACK_VARS_FILES] = vars; } zend_hash_update(&EG(symbol_table), name, name_len + 1, &vars, sizeof(zval *), NULL); Z_ADDREF_P(vars); return 0; /* don't rearm */ } static zend_bool php_auto_globals_create_server(const char *name, uint name_len TSRMLS_DC) { if (PG(variables_order) && (strchr(PG(variables_order),'S') || strchr(PG(variables_order),'s'))) { php_register_server_variables(TSRMLS_C); if (PG(register_argc_argv)) { if (SG(request_info).argc) { zval **argc, **argv; if (zend_hash_find(&EG(symbol_table), "argc", sizeof("argc"), (void**)&argc) == SUCCESS && zend_hash_find(&EG(symbol_table), "argv", sizeof("argv"), (void**)&argv) == SUCCESS) { Z_ADDREF_PP(argc); Z_ADDREF_PP(argv); zend_hash_update(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]), "argv", sizeof("argv"), argv, sizeof(zval *), NULL); zend_hash_update(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]), "argc", sizeof("argc"), argc, sizeof(zval *), NULL); } } else { php_build_argv(SG(request_info).query_string, PG(http_globals)[TRACK_VARS_SERVER] TSRMLS_CC); } } } else { zval *server_vars=NULL; ALLOC_ZVAL(server_vars); array_init(server_vars); INIT_PZVAL(server_vars); if (PG(http_globals)[TRACK_VARS_SERVER]) { zval_ptr_dtor(&PG(http_globals)[TRACK_VARS_SERVER]); } PG(http_globals)[TRACK_VARS_SERVER] = server_vars; } zend_hash_update(&EG(symbol_table), name, name_len + 1, &PG(http_globals)[TRACK_VARS_SERVER], sizeof(zval *), NULL); Z_ADDREF_P(PG(http_globals)[TRACK_VARS_SERVER]); return 0; /* don't rearm */ } static zend_bool php_auto_globals_create_env(const char *name, uint name_len TSRMLS_DC) { zval *env_vars = NULL; ALLOC_ZVAL(env_vars); array_init(env_vars); INIT_PZVAL(env_vars); if (PG(http_globals)[TRACK_VARS_ENV]) { zval_ptr_dtor(&PG(http_globals)[TRACK_VARS_ENV]); } PG(http_globals)[TRACK_VARS_ENV] = env_vars; if (PG(variables_order) && (strchr(PG(variables_order),'E') || strchr(PG(variables_order),'e'))) { php_import_environment_variables(PG(http_globals)[TRACK_VARS_ENV] TSRMLS_CC); } zend_hash_update(&EG(symbol_table), name, name_len + 1, &PG(http_globals)[TRACK_VARS_ENV], sizeof(zval *), NULL); Z_ADDREF_P(PG(http_globals)[TRACK_VARS_ENV]); return 0; /* don't rearm */ } static zend_bool php_auto_globals_create_request(const char *name, uint name_len TSRMLS_DC) { zval *form_variables; unsigned char _gpc_flags[3] = {0, 0, 0}; char *p; ALLOC_ZVAL(form_variables); array_init(form_variables); INIT_PZVAL(form_variables); if (PG(request_order) != NULL) { p = PG(request_order); } else { p = PG(variables_order); } for (; p && *p; p++) { switch (*p) { case 'g': case 'G': if (!_gpc_flags[0]) { php_autoglobal_merge(Z_ARRVAL_P(form_variables), Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_GET]) TSRMLS_CC); _gpc_flags[0] = 1; } break; case 'p': case 'P': if (!_gpc_flags[1]) { php_autoglobal_merge(Z_ARRVAL_P(form_variables), Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_POST]) TSRMLS_CC); _gpc_flags[1] = 1; } break; case 'c': case 'C': if (!_gpc_flags[2]) { php_autoglobal_merge(Z_ARRVAL_P(form_variables), Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_COOKIE]) TSRMLS_CC); _gpc_flags[2] = 1; } break; } } zend_hash_update(&EG(symbol_table), name, name_len + 1, &form_variables, sizeof(zval *), NULL); return 0; } void php_startup_auto_globals(TSRMLS_D) { zend_register_auto_global(ZEND_STRL("_GET"), 0, php_auto_globals_create_get TSRMLS_CC); zend_register_auto_global(ZEND_STRL("_POST"), 0, php_auto_globals_create_post TSRMLS_CC); zend_register_auto_global(ZEND_STRL("_COOKIE"), 0, php_auto_globals_create_cookie TSRMLS_CC); zend_register_auto_global(ZEND_STRL("_SERVER"), PG(auto_globals_jit), php_auto_globals_create_server TSRMLS_CC); zend_register_auto_global(ZEND_STRL("_ENV"), PG(auto_globals_jit), php_auto_globals_create_env TSRMLS_CC); zend_register_auto_global(ZEND_STRL("_REQUEST"), PG(auto_globals_jit), php_auto_globals_create_request TSRMLS_CC); zend_register_auto_global(ZEND_STRL("_FILES"), 0, php_auto_globals_create_files TSRMLS_CC); } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2012-02-08-ff63c09e6f-6672171672.c
manybugs_data_51
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Christian Stocker <[email protected]> | | Rob Richards <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #if HAVE_LIBXML && HAVE_DOM #include "php_dom.h" #include <libxml/SAX.h> #ifdef LIBXML_SCHEMAS_ENABLED #include <libxml/relaxng.h> #include <libxml/xmlschemas.h> #endif typedef struct _idsIterator idsIterator; struct _idsIterator { xmlChar *elementId; xmlNode *element; }; #define DOM_LOAD_STRING 0 #define DOM_LOAD_FILE 1 /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_element, 0, 0, 1) ZEND_ARG_INFO(0, tagName) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_document_fragment, 0, 0, 0) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_text_node, 0, 0, 1) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_comment, 0, 0, 1) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_cdatasection, 0, 0, 1) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_processing_instruction, 0, 0, 2) ZEND_ARG_INFO(0, target) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_attribute, 0, 0, 1) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_entity_reference, 0, 0, 1) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_get_elements_by_tag_name, 0, 0, 1) ZEND_ARG_INFO(0, tagName) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_import_node, 0, 0, 2) ZEND_ARG_OBJ_INFO(0, importedNode, DOMNode, 0) ZEND_ARG_INFO(0, deep) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_element_ns, 0, 0, 2) ZEND_ARG_INFO(0, namespaceURI) ZEND_ARG_INFO(0, qualifiedName) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_attribute_ns, 0, 0, 2) ZEND_ARG_INFO(0, namespaceURI) ZEND_ARG_INFO(0, qualifiedName) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_get_elements_by_tag_name_ns, 0, 0, 2) ZEND_ARG_INFO(0, namespaceURI) ZEND_ARG_INFO(0, localName) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_get_element_by_id, 0, 0, 1) ZEND_ARG_INFO(0, elementId) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_adopt_node, 0, 0, 1) ZEND_ARG_OBJ_INFO(0, source, DOMNode, 0) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_normalize_document, 0, 0, 0) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_rename_node, 0, 0, 3) ZEND_ARG_OBJ_INFO(0, node, DOMNode, 0) ZEND_ARG_INFO(0, namespaceURI) ZEND_ARG_INFO(0, qualifiedName) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_load, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_save, 0, 0, 1) ZEND_ARG_INFO(0, file) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_loadxml, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_savexml, 0, 0, 0) ZEND_ARG_OBJ_INFO(0, node, DOMNode, 1) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_construct, 0, 0, 0) ZEND_ARG_INFO(0, version) ZEND_ARG_INFO(0, encoding) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_validate, 0, 0, 0) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_xinclude, 0, 0, 0) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_loadhtml, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_loadhtmlfile, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_savehtml, 0, 0, 0) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_savehtmlfile, 0, 0, 1) ZEND_ARG_INFO(0, file) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_schema_validate_file, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_schema_validate_xml, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_relaxNG_validate_file, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_relaxNG_validate_xml, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_registernodeclass, 0, 0, 2) ZEND_ARG_INFO(0, baseClass) ZEND_ARG_INFO(0, extendedClass) ZEND_END_ARG_INFO(); /* }}} */ /* * class DOMDocument extends DOMNode * * URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-i-Document * Since: */ const zend_function_entry php_dom_document_class_functions[] = { /* {{{ */ PHP_FALIAS(createElement, dom_document_create_element, arginfo_dom_document_create_element) PHP_FALIAS(createDocumentFragment, dom_document_create_document_fragment, arginfo_dom_document_create_document_fragment) PHP_FALIAS(createTextNode, dom_document_create_text_node, arginfo_dom_document_create_text_node) PHP_FALIAS(createComment, dom_document_create_comment, arginfo_dom_document_create_comment) PHP_FALIAS(createCDATASection, dom_document_create_cdatasection, arginfo_dom_document_create_cdatasection) PHP_FALIAS(createProcessingInstruction, dom_document_create_processing_instruction, arginfo_dom_document_create_processing_instruction) PHP_FALIAS(createAttribute, dom_document_create_attribute, arginfo_dom_document_create_attribute) PHP_FALIAS(createEntityReference, dom_document_create_entity_reference, arginfo_dom_document_create_entity_reference) PHP_FALIAS(getElementsByTagName, dom_document_get_elements_by_tag_name, arginfo_dom_document_get_elements_by_tag_name) PHP_FALIAS(importNode, dom_document_import_node, arginfo_dom_document_import_node) PHP_FALIAS(createElementNS, dom_document_create_element_ns, arginfo_dom_document_create_element_ns) PHP_FALIAS(createAttributeNS, dom_document_create_attribute_ns, arginfo_dom_document_create_attribute_ns) PHP_FALIAS(getElementsByTagNameNS, dom_document_get_elements_by_tag_name_ns, arginfo_dom_document_get_elements_by_tag_name_ns) PHP_FALIAS(getElementById, dom_document_get_element_by_id, arginfo_dom_document_get_element_by_id) PHP_FALIAS(adoptNode, dom_document_adopt_node, arginfo_dom_document_adopt_node) PHP_FALIAS(normalizeDocument, dom_document_normalize_document, arginfo_dom_document_normalize_document) PHP_FALIAS(renameNode, dom_document_rename_node, arginfo_dom_document_rename_node) PHP_ME(domdocument, load, arginfo_dom_document_load, ZEND_ACC_PUBLIC|ZEND_ACC_ALLOW_STATIC) PHP_FALIAS(save, dom_document_save, arginfo_dom_document_save) PHP_ME(domdocument, loadXML, arginfo_dom_document_loadxml, ZEND_ACC_PUBLIC|ZEND_ACC_ALLOW_STATIC) PHP_FALIAS(saveXML, dom_document_savexml, arginfo_dom_document_savexml) PHP_ME(domdocument, __construct, arginfo_dom_document_construct, ZEND_ACC_PUBLIC) PHP_FALIAS(validate, dom_document_validate, arginfo_dom_document_validate) PHP_FALIAS(xinclude, dom_document_xinclude, arginfo_dom_document_xinclude) #if defined(LIBXML_HTML_ENABLED) PHP_ME(domdocument, loadHTML, arginfo_dom_document_loadhtml, ZEND_ACC_PUBLIC|ZEND_ACC_ALLOW_STATIC) PHP_ME(domdocument, loadHTMLFile, arginfo_dom_document_loadhtmlfile, ZEND_ACC_PUBLIC|ZEND_ACC_ALLOW_STATIC) PHP_FALIAS(saveHTML, dom_document_save_html, arginfo_dom_document_savehtml) PHP_FALIAS(saveHTMLFile, dom_document_save_html_file, arginfo_dom_document_savehtmlfile) #endif /* defined(LIBXML_HTML_ENABLED) */ #if defined(LIBXML_SCHEMAS_ENABLED) PHP_FALIAS(schemaValidate, dom_document_schema_validate_file, arginfo_dom_document_schema_validate_file) PHP_FALIAS(schemaValidateSource, dom_document_schema_validate_xml, arginfo_dom_document_schema_validate_xml) PHP_FALIAS(relaxNGValidate, dom_document_relaxNG_validate_file, arginfo_dom_document_relaxNG_validate_file) PHP_FALIAS(relaxNGValidateSource, dom_document_relaxNG_validate_xml, arginfo_dom_document_relaxNG_validate_xml) #endif PHP_ME(domdocument, registerNodeClass, arginfo_dom_document_registernodeclass, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; /* }}} */ /* {{{ docType DOMDocumentType readonly=yes URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-B63ED1A31 Since: */ int dom_document_doctype_read(dom_object *obj, zval **retval TSRMLS_DC) { xmlDoc *docp; xmlDtdPtr dtdptr; int ret; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } ALLOC_ZVAL(*retval); dtdptr = xmlGetIntSubset(docp); if (!dtdptr) { ZVAL_NULL(*retval); return SUCCESS; } if (NULL == (*retval = php_dom_create_object((xmlNodePtr) dtdptr, &ret, NULL, *retval, obj TSRMLS_CC))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot create required DOM object"); return FAILURE; } return SUCCESS; } /* }}} */ /* {{{ implementation DOMImplementation readonly=yes URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1B793EBA Since: */ int dom_document_implementation_read(dom_object *obj, zval **retval TSRMLS_DC) { ALLOC_ZVAL(*retval); php_dom_create_implementation(retval TSRMLS_CC); return SUCCESS; } /* }}} */ /* {{{ documentElement DOMElement readonly=yes URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-87CD092 Since: */ int dom_document_document_element_read(dom_object *obj, zval **retval TSRMLS_DC) { xmlDoc *docp; xmlNode *root; int ret; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } ALLOC_ZVAL(*retval); root = xmlDocGetRootElement(docp); if (!root) { ZVAL_NULL(*retval); return SUCCESS; } if (NULL == (*retval = php_dom_create_object(root, &ret, NULL, *retval, obj TSRMLS_CC))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot create required DOM object"); return FAILURE; } return SUCCESS; } /* }}} */ /* {{{ encoding string URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-encoding Since: DOM Level 3 */ int dom_document_encoding_read(dom_object *obj, zval **retval TSRMLS_DC) { xmlDoc *docp; char *encoding; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } encoding = (char *) docp->encoding; ALLOC_ZVAL(*retval); if (encoding != NULL) { ZVAL_STRING(*retval, encoding, 1); } else { ZVAL_NULL(*retval); } return SUCCESS; } int dom_document_encoding_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; xmlDoc *docp; xmlCharEncodingHandlerPtr handler; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } if (newval->type != IS_STRING) { if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_string(newval); } handler = xmlFindCharEncodingHandler(Z_STRVAL_P(newval)); if (handler != NULL) { xmlCharEncCloseFunc(handler); if (docp->encoding != NULL) { xmlFree((xmlChar *)docp->encoding); } docp->encoding = xmlStrdup((const xmlChar *) Z_STRVAL_P(newval)); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Document Encoding"); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ standalone boolean readonly=no URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-standalone Since: DOM Level 3 */ int dom_document_standalone_read(dom_object *obj, zval **retval TSRMLS_DC) { xmlDoc *docp; int standalone; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } ALLOC_ZVAL(*retval); standalone = docp->standalone; ZVAL_BOOL(*retval, standalone); return SUCCESS; } int dom_document_standalone_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; xmlDoc *docp; int standalone; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_long(newval); standalone = Z_LVAL_P(newval); if (standalone > 0) { docp->standalone = 1; } else if (standalone < 0) { docp->standalone = -1; } else { docp->standalone = 0; } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ version string readonly=no URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-version Since: DOM Level 3 */ int dom_document_version_read(dom_object *obj, zval **retval TSRMLS_DC) { xmlDoc *docp; char *version; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } version = (char *) docp->version; ALLOC_ZVAL(*retval); if (version != NULL) { ZVAL_STRING(*retval, version, 1); } else { ZVAL_NULL(*retval); } return SUCCESS; } int dom_document_version_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; xmlDoc *docp; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } if (docp->version != NULL) { xmlFree((xmlChar *) docp->version ); } if (newval->type != IS_STRING) { if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_string(newval); } docp->version = xmlStrdup((const xmlChar *) Z_STRVAL_P(newval)); if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ strictErrorChecking boolean readonly=no URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-strictErrorChecking Since: DOM Level 3 */ int dom_document_strict_error_checking_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->stricterror); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_strict_error_checking_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->stricterror = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ formatOutput boolean readonly=no */ int dom_document_format_output_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->formatoutput); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_format_output_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->formatoutput = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ validateOnParse boolean readonly=no */ int dom_document_validate_on_parse_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->validateonparse); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_validate_on_parse_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->validateonparse = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ resolveExternals boolean readonly=no */ int dom_document_resolve_externals_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->resolveexternals); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_resolve_externals_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->resolveexternals = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ preserveWhiteSpace boolean readonly=no */ int dom_document_preserve_whitespace_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->preservewhitespace); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_preserve_whitespace_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->preservewhitespace = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ recover boolean readonly=no */ int dom_document_recover_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->recover); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_recover_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->recover = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ substituteEntities boolean readonly=no */ int dom_document_substitue_entities_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->substituteentities); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_substitue_entities_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->substituteentities = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ documentURI string readonly=no URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-documentURI Since: DOM Level 3 */ int dom_document_document_uri_read(dom_object *obj, zval **retval TSRMLS_DC) { xmlDoc *docp; char *url; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } ALLOC_ZVAL(*retval); url = (char *) docp->URL; if (url != NULL) { ZVAL_STRING(*retval, url, 1); } else { ZVAL_NULL(*retval); } return SUCCESS; } int dom_document_document_uri_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; xmlDoc *docp; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } if (docp->URL != NULL) { xmlFree((xmlChar *) docp->URL); } if (newval->type != IS_STRING) { if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_string(newval); } docp->URL = xmlStrdup((const xmlChar *) Z_STRVAL_P(newval)); if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ config DOMConfiguration readonly=yes URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-config Since: DOM Level 3 */ int dom_document_config_read(dom_object *obj, zval **retval TSRMLS_DC) { ALLOC_ZVAL(*retval); ZVAL_NULL(*retval); return SUCCESS; } /* }}} */ /* {{{ proto DOMElement dom_document_create_element(string tagName [, string value]); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-2141741547 Since: */ PHP_FUNCTION(dom_document_create_element) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp; dom_object *intern; int ret, name_len, value_len; char *name, *value = NULL; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|s", &id, dom_document_class_entry, &name, &name_len, &value, &value_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); if (xmlValidateName((xmlChar *) name, 0) != 0) { php_dom_throw_error(INVALID_CHARACTER_ERR, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } node = xmlNewDocNode(docp, NULL, name, value); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, node, &ret, intern); } /* }}} end dom_document_create_element */ /* {{{ proto DOMDocumentFragment dom_document_create_document_fragment(); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-35CB04B5 Since: */ PHP_FUNCTION(dom_document_create_document_fragment) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp; dom_object *intern; int ret; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &id, dom_document_class_entry) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); node = xmlNewDocFragment(docp); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, node, &ret, intern); } /* }}} end dom_document_create_document_fragment */ /* {{{ proto DOMText dom_document_create_text_node(string data); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1975348127 Since: */ PHP_FUNCTION(dom_document_create_text_node) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp; int ret, value_len; dom_object *intern; char *value; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &value, &value_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); node = xmlNewDocText(docp, (xmlChar *) value); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, node, &ret, intern); } /* }}} end dom_document_create_text_node */ /* {{{ proto DOMComment dom_document_create_comment(string data); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1334481328 Since: */ PHP_FUNCTION(dom_document_create_comment) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp; int ret, value_len; dom_object *intern; char *value; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &value, &value_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); node = xmlNewDocComment(docp, (xmlChar *) value); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, node, &ret, intern); } /* }}} end dom_document_create_comment */ /* {{{ proto DOMCdataSection dom_document_create_cdatasection(string data); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-D26C0AF8 Since: */ PHP_FUNCTION(dom_document_create_cdatasection) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp; int ret, value_len; dom_object *intern; char *value; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &value, &value_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); node = xmlNewCDataBlock(docp, (xmlChar *) value, value_len); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, node, &ret, intern); } /* }}} end dom_document_create_cdatasection */ /* {{{ proto DOMProcessingInstruction dom_document_create_processing_instruction(string target, string data); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-135944439 Since: */ PHP_FUNCTION(dom_document_create_processing_instruction) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp; int ret, value_len, name_len = 0; dom_object *intern; char *name, *value = NULL; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|s", &id, dom_document_class_entry, &name, &name_len, &value, &value_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); if (xmlValidateName((xmlChar *) name, 0) != 0) { php_dom_throw_error(INVALID_CHARACTER_ERR, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } node = xmlNewPI((xmlChar *) name, (xmlChar *) value); if (!node) { RETURN_FALSE; } node->doc = docp; DOM_RET_OBJ(rv, node, &ret, intern); } /* }}} end dom_document_create_processing_instruction */ /* {{{ proto DOMAttr dom_document_create_attribute(string name); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1084891198 Since: */ PHP_FUNCTION(dom_document_create_attribute) { zval *id, *rv = NULL; xmlAttrPtr node; xmlDocPtr docp; int ret, name_len; dom_object *intern; char *name; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &name, &name_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); if (xmlValidateName((xmlChar *) name, 0) != 0) { php_dom_throw_error(INVALID_CHARACTER_ERR, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } node = xmlNewDocProp(docp, (xmlChar *) name, NULL); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, (xmlNodePtr) node, &ret, intern); } /* }}} end dom_document_create_attribute */ /* {{{ proto DOMEntityReference dom_document_create_entity_reference(string name); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-392B75AE Since: */ PHP_FUNCTION(dom_document_create_entity_reference) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp = NULL; dom_object *intern; int ret, name_len; char *name; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &name, &name_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); if (xmlValidateName((xmlChar *) name, 0) != 0) { php_dom_throw_error(INVALID_CHARACTER_ERR, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } node = xmlNewReference(docp, name); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, (xmlNodePtr) node, &ret, intern); } /* }}} end dom_document_create_entity_reference */ /* {{{ proto DOMNodeList dom_document_get_elements_by_tag_name(string tagname); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-A6C9094 Since: */ PHP_FUNCTION(dom_document_get_elements_by_tag_name) { zval *id; xmlDocPtr docp; int name_len; dom_object *intern, *namednode; char *name; xmlChar *local; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &name, &name_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); php_dom_create_interator(return_value, DOM_NODELIST TSRMLS_CC); namednode = (dom_object *)zend_objects_get_address(return_value TSRMLS_CC); local = xmlCharStrndup(name, name_len); dom_namednode_iter(intern, 0, namednode, NULL, local, NULL TSRMLS_CC); } /* }}} end dom_document_get_elements_by_tag_name */ /* {{{ proto DOMNode dom_document_import_node(DOMNode importedNode, boolean deep); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Core-Document-importNode Since: DOM Level 2 */ PHP_FUNCTION(dom_document_import_node) { zval *rv = NULL; zval *id, *node; xmlDocPtr docp; xmlNodePtr nodep, retnodep; dom_object *intern, *nodeobj; int ret; long recursive = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO|l", &id, dom_document_class_entry, &node, dom_node_class_entry, &recursive) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); DOM_GET_OBJ(nodep, node, xmlNodePtr, nodeobj); if (nodep->type == XML_HTML_DOCUMENT_NODE || nodep->type == XML_DOCUMENT_NODE || nodep->type == XML_DOCUMENT_TYPE_NODE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot import: Node Type Not Supported"); RETURN_FALSE; } if (nodep->doc == docp) { retnodep = nodep; } else { if ((recursive == 0) && (nodep->type == XML_ELEMENT_NODE)) { recursive = 2; } retnodep = xmlDocCopyNode(nodep, docp, recursive); if (!retnodep) { RETURN_FALSE; } if ((retnodep->type == XML_ATTRIBUTE_NODE) && (nodep->ns != NULL)) { xmlNsPtr nsptr = NULL; xmlNodePtr root = xmlDocGetRootElement(docp); nsptr = xmlSearchNsByHref (nodep->doc, root, nodep->ns->href); if (nsptr == NULL) { int errorcode; nsptr = dom_get_ns(root, (char *) nodep->ns->href, &errorcode, (char *) nodep->ns->prefix); } xmlSetNs(retnodep, nsptr); } } DOM_RET_OBJ(rv, (xmlNodePtr) retnodep, &ret, intern); } /* }}} end dom_document_import_node */ /* {{{ proto DOMElement dom_document_create_element_ns(string namespaceURI, string qualifiedName [,string value]); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-DocCrElNS Since: DOM Level 2 */ PHP_FUNCTION(dom_document_create_element_ns) { zval *id, *rv = NULL; xmlDocPtr docp; xmlNodePtr nodep = NULL; xmlNsPtr nsptr = NULL; int ret, uri_len = 0, name_len = 0, value_len = 0; char *uri, *name, *value = NULL; char *localname = NULL, *prefix = NULL; int errorcode; dom_object *intern; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os!s|s", &id, dom_document_class_entry, &uri, &uri_len, &name, &name_len, &value, &value_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); errorcode = dom_check_qname(name, &localname, &prefix, uri_len, name_len); if (errorcode == 0) { if (xmlValidateName((xmlChar *) localname, 0) == 0) { nodep = xmlNewDocNode (docp, NULL, localname, value); if (nodep != NULL && uri != NULL) { nsptr = xmlSearchNsByHref (nodep->doc, nodep, uri); if (nsptr == NULL) { nsptr = dom_get_ns(nodep, uri, &errorcode, prefix); } xmlSetNs(nodep, nsptr); } } else { errorcode = INVALID_CHARACTER_ERR; } } xmlFree(localname); if (prefix != NULL) { xmlFree(prefix); } if (errorcode != 0) { if (nodep != NULL) { xmlFreeNode(nodep); } php_dom_throw_error(errorcode, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } if (nodep == NULL) { RETURN_FALSE; } nodep->ns = nsptr; DOM_RET_OBJ(rv, nodep, &ret, intern); } /* }}} end dom_document_create_element_ns */ /* {{{ proto DOMAttr dom_document_create_attribute_ns(string namespaceURI, string qualifiedName); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-DocCrAttrNS Since: DOM Level 2 */ PHP_FUNCTION(dom_document_create_attribute_ns) { zval *id, *rv = NULL; xmlDocPtr docp; xmlNodePtr nodep = NULL, root; xmlNsPtr nsptr; int ret, uri_len = 0, name_len = 0; char *uri, *name; char *localname = NULL, *prefix = NULL; dom_object *intern; int errorcode; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os!s", &id, dom_document_class_entry, &uri, &uri_len, &name, &name_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); root = xmlDocGetRootElement(docp); if (root != NULL) { errorcode = dom_check_qname(name, &localname, &prefix, uri_len, name_len); if (errorcode == 0) { if (xmlValidateName((xmlChar *) localname, 0) == 0) { nodep = (xmlNodePtr) xmlNewDocProp(docp, localname, NULL); if (nodep != NULL && uri_len > 0) { nsptr = xmlSearchNsByHref (nodep->doc, root, uri); if (nsptr == NULL) { nsptr = dom_get_ns(root, uri, &errorcode, prefix); } xmlSetNs(nodep, nsptr); } } else { errorcode = INVALID_CHARACTER_ERR; } } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Document Missing Root Element"); RETURN_FALSE; } xmlFree(localname); if (prefix != NULL) { xmlFree(prefix); } if (errorcode != 0) { if (nodep != NULL) { xmlFreeProp((xmlAttrPtr) nodep); } php_dom_throw_error(errorcode, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } if (nodep == NULL) { RETURN_FALSE; } DOM_RET_OBJ(rv, nodep, &ret, intern); } /* }}} end dom_document_create_attribute_ns */ /* {{{ proto DOMNodeList dom_document_get_elements_by_tag_name_ns(string namespaceURI, string localName); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-getElBTNNS Since: DOM Level 2 */ PHP_FUNCTION(dom_document_get_elements_by_tag_name_ns) { zval *id; xmlDocPtr docp; int uri_len, name_len; dom_object *intern, *namednode; char *uri, *name; xmlChar *local, *nsuri; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oss", &id, dom_document_class_entry, &uri, &uri_len, &name, &name_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); php_dom_create_interator(return_value, DOM_NODELIST TSRMLS_CC); namednode = (dom_object *)zend_objects_get_address(return_value TSRMLS_CC); local = xmlCharStrndup(name, name_len); nsuri = xmlCharStrndup(uri, uri_len); dom_namednode_iter(intern, 0, namednode, NULL, local, nsuri TSRMLS_CC); } /* }}} end dom_document_get_elements_by_tag_name_ns */ /* {{{ proto DOMElement dom_document_get_element_by_id(string elementId); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-getElBId Since: DOM Level 2 */ PHP_FUNCTION(dom_document_get_element_by_id) { zval *id, *rv = NULL; xmlDocPtr docp; xmlAttrPtr attrp; int ret, idname_len; dom_object *intern; char *idname; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &idname, &idname_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); attrp = xmlGetID(docp, (xmlChar *) idname); if (attrp && attrp->parent) { DOM_RET_OBJ(rv, (xmlNodePtr) attrp->parent, &ret, intern); } else { RETVAL_NULL(); } } /* }}} end dom_document_get_element_by_id */ /* {{{ proto DOMNode dom_document_adopt_node(DOMNode source); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-adoptNode Since: DOM Level 3 */ PHP_FUNCTION(dom_document_adopt_node) { DOM_NOT_IMPLEMENTED(); } /* }}} end dom_document_adopt_node */ /* {{{ proto void dom_document_normalize_document(); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-normalizeDocument Since: DOM Level 3 */ PHP_FUNCTION(dom_document_normalize_document) { zval *id; xmlDocPtr docp; dom_object *intern; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &id, dom_document_class_entry) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); dom_normalize((xmlNodePtr) docp TSRMLS_CC); } /* }}} end dom_document_normalize_document */ /* {{{ proto DOMNode dom_document_rename_node(node n, string namespaceURI, string qualifiedName); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-renameNode Since: DOM Level 3 */ PHP_FUNCTION(dom_document_rename_node) { DOM_NOT_IMPLEMENTED(); } /* }}} end dom_document_rename_node */ /* {{{ proto void DOMDocument::__construct([string version], [string encoding]); */ PHP_METHOD(domdocument, __construct) { zval *id; xmlDoc *docp = NULL, *olddoc; dom_object *intern; char *encoding, *version = NULL; int encoding_len = 0, version_len = 0, refcount; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, dom_domexception_class_entry, &error_handling TSRMLS_CC); if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|ss", &id, dom_document_class_entry, &version, &version_len, &encoding, &encoding_len) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } zend_restore_error_handling(&error_handling TSRMLS_CC); docp = xmlNewDoc(version); if (!docp) { php_dom_throw_error(INVALID_STATE_ERR, 1 TSRMLS_CC); RETURN_FALSE; } if (encoding_len > 0) { docp->encoding = (const xmlChar*)xmlStrdup(encoding); } intern = (dom_object *)zend_object_store_get_object(id TSRMLS_CC); if (intern != NULL) { olddoc = (xmlDocPtr) dom_object_get_node(intern); if (olddoc != NULL) { php_libxml_decrement_node_ptr((php_libxml_node_object *) intern TSRMLS_CC); refcount = php_libxml_decrement_doc_ref((php_libxml_node_object *)intern TSRMLS_CC); if (refcount != 0) { olddoc->_private = NULL; } } intern->document = NULL; if (php_libxml_increment_doc_ref((php_libxml_node_object *)intern, docp TSRMLS_CC) == -1) { RETURN_FALSE; } php_libxml_increment_node_ptr((php_libxml_node_object *)intern, (xmlNodePtr)docp, (void *)intern TSRMLS_CC); } } /* }}} end DOMDocument::__construct */ char *_dom_get_valid_file_path(char *source, char *resolved_path, int resolved_path_len TSRMLS_DC) /* {{{ */ { xmlURI *uri; xmlChar *escsource; char *file_dest; int isFileUri = 0; uri = xmlCreateURI(); escsource = xmlURIEscapeStr(source, ":"); xmlParseURIReference(uri, escsource); xmlFree(escsource); if (uri->scheme != NULL) { /* absolute file uris - libxml only supports localhost or empty host */ if (strncasecmp(source, "file:///",8) == 0) { isFileUri = 1; #ifdef PHP_WIN32 source += 8; #else source += 7; #endif } else if (strncasecmp(source, "file://localhost/",17) == 0) { isFileUri = 1; #ifdef PHP_WIN32 source += 17; #else source += 16; #endif } } file_dest = source; if ((uri->scheme == NULL || isFileUri)) { /* XXX possible buffer overflow if VCWD_REALPATH does not know size of resolved_path */ if (!VCWD_REALPATH(source, resolved_path) && !expand_filepath(source, resolved_path TSRMLS_CC)) { xmlFreeURI(uri); return NULL; } file_dest = resolved_path; } xmlFreeURI(uri); return file_dest; } /* }}} */ static xmlDocPtr dom_document_parser(zval *id, int mode, char *source, int source_len, int options TSRMLS_DC) /* {{{ */ { xmlDocPtr ret; xmlParserCtxtPtr ctxt = NULL; dom_doc_propsptr doc_props; dom_object *intern; php_libxml_ref_obj *document = NULL; int validate, recover, resolve_externals, keep_blanks, substitute_ent; int resolved_path_len; int old_error_reporting = 0; char *directory=NULL, resolved_path[MAXPATHLEN]; if (id != NULL) { intern = (dom_object *)zend_object_store_get_object(id TSRMLS_CC); document = intern->document; } doc_props = dom_get_doc_props(document); validate = doc_props->validateonparse; resolve_externals = doc_props->resolveexternals; keep_blanks = doc_props->preservewhitespace; substitute_ent = doc_props->substituteentities; recover = doc_props->recover; if (document == NULL) { efree(doc_props); } xmlInitParser(); if (mode == DOM_LOAD_FILE) { char *file_dest = _dom_get_valid_file_path(source, resolved_path, MAXPATHLEN TSRMLS_CC); if (file_dest) { ctxt = xmlCreateFileParserCtxt(file_dest); } } else { ctxt = xmlCreateMemoryParserCtxt(source, source_len); } if (ctxt == NULL) { return(NULL); } /* If loading from memory, we need to set the base directory for the document */ if (mode != DOM_LOAD_FILE) { #if HAVE_GETCWD directory = VCWD_GETCWD(resolved_path, MAXPATHLEN); #elif HAVE_GETWD directory = VCWD_GETWD(resolved_path); #endif if (directory) { if(ctxt->directory != NULL) { xmlFree((char *) ctxt->directory); } resolved_path_len = strlen(resolved_path); if (resolved_path[resolved_path_len - 1] != DEFAULT_SLASH) { resolved_path[resolved_path_len] = DEFAULT_SLASH; resolved_path[++resolved_path_len] = '\0'; } ctxt->directory = (char *) xmlCanonicPath((const xmlChar *) resolved_path); } } ctxt->vctxt.error = php_libxml_ctx_error; ctxt->vctxt.warning = php_libxml_ctx_warning; if (ctxt->sax != NULL) { ctxt->sax->error = php_libxml_ctx_error; ctxt->sax->warning = php_libxml_ctx_warning; } if (validate && ! (options & XML_PARSE_DTDVALID)) { options |= XML_PARSE_DTDVALID; } if (resolve_externals && ! (options & XML_PARSE_DTDATTR)) { options |= XML_PARSE_DTDATTR; } if (substitute_ent && ! (options & XML_PARSE_NOENT)) { options |= XML_PARSE_NOENT; } if (keep_blanks == 0 && ! (options & XML_PARSE_NOBLANKS)) { options |= XML_PARSE_NOBLANKS; } xmlCtxtUseOptions(ctxt, options); ctxt->recovery = recover; if (recover) { old_error_reporting = EG(error_reporting); EG(error_reporting) = old_error_reporting | E_WARNING; } xmlParseDocument(ctxt); if (ctxt->wellFormed || recover) { ret = ctxt->myDoc; if (ctxt->recovery) { EG(error_reporting) = old_error_reporting; } /* If loading from memory, set the base reference uri for the document */ if (ret && ret->URL == NULL && ctxt->directory != NULL) { ret->URL = xmlStrdup(ctxt->directory); } } else { ret = NULL; xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } xmlFreeParserCtxt(ctxt); return(ret); } /* }}} */ /* {{{ static void dom_parse_document(INTERNAL_FUNCTION_PARAMETERS, int mode) */ static void dom_parse_document(INTERNAL_FUNCTION_PARAMETERS, int mode) { zval *id, *rv = NULL; xmlDoc *docp = NULL, *newdoc; dom_doc_propsptr doc_prop; dom_object *intern; char *source; int source_len, refcount, ret; long options = 0; id = getThis(); if (id != NULL && ! instanceof_function(Z_OBJCE_P(id), dom_document_class_entry TSRMLS_CC)) { id = NULL; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &source, &source_len, &options) == FAILURE) { return; } if (!source_len) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty string supplied as input"); RETURN_FALSE; } newdoc = dom_document_parser(id, mode, source, source_len, options TSRMLS_CC); if (!newdoc) RETURN_FALSE; if (id != NULL) { intern = (dom_object *)zend_object_store_get_object(id TSRMLS_CC); if (intern != NULL) { docp = (xmlDocPtr) dom_object_get_node(intern); doc_prop = NULL; if (docp != NULL) { php_libxml_decrement_node_ptr((php_libxml_node_object *) intern TSRMLS_CC); doc_prop = intern->document->doc_props; intern->document->doc_props = NULL; refcount = php_libxml_decrement_doc_ref((php_libxml_node_object *)intern TSRMLS_CC); if (refcount != 0) { docp->_private = NULL; } } intern->document = NULL; if (php_libxml_increment_doc_ref((php_libxml_node_object *)intern, newdoc TSRMLS_CC) == -1) { RETURN_FALSE; } intern->document->doc_props = doc_prop; } php_libxml_increment_node_ptr((php_libxml_node_object *)intern, (xmlNodePtr)newdoc, (void *)intern TSRMLS_CC); RETURN_TRUE; } else { DOM_RET_OBJ(rv, (xmlNodePtr) newdoc, &ret, NULL); } } /* }}} end dom_parser_document */ /* {{{ proto DOMNode dom_document_load(string source [, int options]); URL: http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-DocumentLS-load Since: DOM Level 3 */ PHP_METHOD(domdocument, load) { dom_parse_document(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_FILE); } /* }}} end dom_document_load */ /* {{{ proto DOMNode dom_document_loadxml(string source [, int options]); URL: http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-DocumentLS-loadXML Since: DOM Level 3 */ PHP_METHOD(domdocument, loadXML) { dom_parse_document(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_STRING); } /* }}} end dom_document_loadxml */ /* {{{ proto int dom_document_save(string file); Convenience method to save to file */ PHP_FUNCTION(dom_document_save) { zval *id; xmlDoc *docp; int file_len = 0, bytes, format, saveempty = 0; dom_object *intern; dom_doc_propsptr doc_props; char *file; long options = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|l", &id, dom_document_class_entry, &file, &file_len, &options) == FAILURE) { return; } if (file_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Filename"); RETURN_FALSE; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); /* encoding handled by property on doc */ doc_props = dom_get_doc_props(intern->document); format = doc_props->formatoutput; if (options & LIBXML_SAVE_NOEMPTYTAG) { saveempty = xmlSaveNoEmptyTags; xmlSaveNoEmptyTags = 1; } bytes = xmlSaveFormatFileEnc(file, docp, NULL, format); if (options & LIBXML_SAVE_NOEMPTYTAG) { xmlSaveNoEmptyTags = saveempty; } if (bytes == -1) { RETURN_FALSE; } RETURN_LONG(bytes); } /* }}} end dom_document_save */ /* {{{ proto string dom_document_savexml([node n]); URL: http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-DocumentLS-saveXML Since: DOM Level 3 */ PHP_FUNCTION(dom_document_savexml) { zval *id, *nodep = NULL; xmlDoc *docp; xmlNode *node; xmlBufferPtr buf; xmlChar *mem; dom_object *intern, *nodeobj; dom_doc_propsptr doc_props; int size, format, saveempty = 0; long options = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|O!l", &id, dom_document_class_entry, &nodep, dom_node_class_entry, &options) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); doc_props = dom_get_doc_props(intern->document); format = doc_props->formatoutput; if (nodep != NULL) { /* Dump contents of Node */ DOM_GET_OBJ(node, nodep, xmlNodePtr, nodeobj); if (node->doc != docp) { php_dom_throw_error(WRONG_DOCUMENT_ERR, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } buf = xmlBufferCreate(); if (!buf) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not fetch buffer"); RETURN_FALSE; } if (options & LIBXML_SAVE_NOEMPTYTAG) { saveempty = xmlSaveNoEmptyTags; xmlSaveNoEmptyTags = 1; } xmlNodeDump(buf, docp, node, 0, format); if (options & LIBXML_SAVE_NOEMPTYTAG) { xmlSaveNoEmptyTags = saveempty; } mem = (xmlChar*) xmlBufferContent(buf); if (!mem) { xmlBufferFree(buf); RETURN_FALSE; } RETVAL_STRING(mem, 1); xmlBufferFree(buf); } else { if (options & LIBXML_SAVE_NOEMPTYTAG) { saveempty = xmlSaveNoEmptyTags; xmlSaveNoEmptyTags = 1; } /* Encoding is handled from the encoding property set on the document */ xmlDocDumpFormatMemory(docp, &mem, &size, format); if (options & LIBXML_SAVE_NOEMPTYTAG) { xmlSaveNoEmptyTags = saveempty; } if (!size) { RETURN_FALSE; } RETVAL_STRINGL(mem, size, 1); xmlFree(mem); } } /* }}} end dom_document_savexml */ static xmlNodePtr php_dom_free_xinclude_node(xmlNodePtr cur TSRMLS_DC) /* {{{ */ { xmlNodePtr xincnode; xincnode = cur; cur = cur->next; xmlUnlinkNode(xincnode); php_libxml_node_free_resource(xincnode TSRMLS_CC); return cur; } /* }}} */ static void php_dom_remove_xinclude_nodes(xmlNodePtr cur TSRMLS_DC) /* {{{ */ { while(cur) { if (cur->type == XML_XINCLUDE_START) { cur = php_dom_free_xinclude_node(cur TSRMLS_CC); /* XML_XINCLUDE_END node will be a sibling of XML_XINCLUDE_START */ while(cur && cur->type != XML_XINCLUDE_END) { /* remove xinclude processing nodes from recursive xincludes */ if (cur->type == XML_ELEMENT_NODE) { php_dom_remove_xinclude_nodes(cur->children TSRMLS_CC); } cur = cur->next; } if (cur && cur->type == XML_XINCLUDE_END) { cur = php_dom_free_xinclude_node(cur TSRMLS_CC); } } else { if (cur->type == XML_ELEMENT_NODE) { php_dom_remove_xinclude_nodes(cur->children TSRMLS_CC); } cur = cur->next; } } } /* }}} */ /* {{{ proto int dom_document_xinclude([int options]) Substitutues xincludes in a DomDocument */ PHP_FUNCTION(dom_document_xinclude) { zval *id; xmlDoc *docp; xmlNodePtr root; long flags = 0; int err; dom_object *intern; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|l", &id, dom_document_class_entry, &flags) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); err = xmlXIncludeProcessFlags(docp, flags); /* XML_XINCLUDE_START and XML_XINCLUDE_END nodes need to be removed as these are added via xmlXIncludeProcess to mark beginning and ending of xincluded document but are not wanted in resulting document - must be done even if err as it could fail after having processed some xincludes */ root = (xmlNodePtr) docp->children; while(root && root->type != XML_ELEMENT_NODE && root->type != XML_XINCLUDE_START) { root = root->next; } if (root) { php_dom_remove_xinclude_nodes(root TSRMLS_CC); } if (err) { RETVAL_LONG(err); } else { RETVAL_FALSE; } } /* }}} */ /* {{{ proto boolean dom_document_validate(); Since: DOM extended */ PHP_FUNCTION(dom_document_validate) { zval *id; xmlDoc *docp; dom_object *intern; xmlValidCtxt *cvp; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &id, dom_document_class_entry) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); cvp = xmlNewValidCtxt(); cvp->userData = NULL; cvp->error = (xmlValidityErrorFunc) php_libxml_error_handler; cvp->warning = (xmlValidityErrorFunc) php_libxml_error_handler; if (xmlValidateDocument(cvp, docp)) { RETVAL_TRUE; } else { RETVAL_FALSE; } xmlFreeValidCtxt(cvp); } /* }}} */ #if defined(LIBXML_SCHEMAS_ENABLED) static void _dom_document_schema_validate(INTERNAL_FUNCTION_PARAMETERS, int type) /* {{{ */ { zval *id; xmlDoc *docp; dom_object *intern; char *source = NULL, *valid_file = NULL; int source_len = 0; xmlSchemaParserCtxtPtr parser; xmlSchemaPtr sptr; xmlSchemaValidCtxtPtr vptr; int is_valid; char resolved_path[MAXPATHLEN + 1]; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &source, &source_len) == FAILURE) { return; } if (source_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Schema source"); RETURN_FALSE; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); switch (type) { case DOM_LOAD_FILE: valid_file = _dom_get_valid_file_path(source, resolved_path, MAXPATHLEN TSRMLS_CC); if (!valid_file) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Schema file source"); RETURN_FALSE; } parser = xmlSchemaNewParserCtxt(valid_file); break; case DOM_LOAD_STRING: parser = xmlSchemaNewMemParserCtxt(source, source_len); /* If loading from memory, we need to set the base directory for the document but it is not apparent how to do that for schema's */ break; default: return; } xmlSchemaSetParserErrors(parser, (xmlSchemaValidityErrorFunc) php_libxml_error_handler, (xmlSchemaValidityWarningFunc) php_libxml_error_handler, parser); sptr = xmlSchemaParse(parser); xmlSchemaFreeParserCtxt(parser); if (!sptr) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Schema"); RETURN_FALSE; } docp = (xmlDocPtr) dom_object_get_node(intern); vptr = xmlSchemaNewValidCtxt(sptr); if (!vptr) { xmlSchemaFree(sptr); php_error(E_ERROR, "Invalid Schema Validation Context"); RETURN_FALSE; } xmlSchemaSetValidErrors(vptr, php_libxml_error_handler, php_libxml_error_handler, vptr); is_valid = xmlSchemaValidateDoc(vptr, docp); xmlSchemaFree(sptr); xmlSchemaFreeValidCtxt(vptr); if (is_valid == 0) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto boolean dom_document_schema_validate_file(string filename); */ PHP_FUNCTION(dom_document_schema_validate_file) { _dom_document_schema_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_FILE); } /* }}} end dom_document_schema_validate_file */ /* {{{ proto boolean dom_document_schema_validate(string source); */ PHP_FUNCTION(dom_document_schema_validate_xml) { _dom_document_schema_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_STRING); } /* }}} end dom_document_schema_validate */ static void _dom_document_relaxNG_validate(INTERNAL_FUNCTION_PARAMETERS, int type) /* {{{ */ { zval *id; xmlDoc *docp; dom_object *intern; char *source = NULL, *valid_file = NULL; int source_len = 0; xmlRelaxNGParserCtxtPtr parser; xmlRelaxNGPtr sptr; xmlRelaxNGValidCtxtPtr vptr; int is_valid; char resolved_path[MAXPATHLEN + 1]; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &source, &source_len) == FAILURE) { return; } if (source_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Schema source"); RETURN_FALSE; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); switch (type) { case DOM_LOAD_FILE: valid_file = _dom_get_valid_file_path(source, resolved_path, MAXPATHLEN TSRMLS_CC); if (!valid_file) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid RelaxNG file source"); RETURN_FALSE; } parser = xmlRelaxNGNewParserCtxt(valid_file); break; case DOM_LOAD_STRING: parser = xmlRelaxNGNewMemParserCtxt(source, source_len); /* If loading from memory, we need to set the base directory for the document but it is not apparent how to do that for schema's */ break; default: return; } xmlRelaxNGSetParserErrors(parser, (xmlRelaxNGValidityErrorFunc) php_libxml_error_handler, (xmlRelaxNGValidityWarningFunc) php_libxml_error_handler, parser); sptr = xmlRelaxNGParse(parser); xmlRelaxNGFreeParserCtxt(parser); if (!sptr) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid RelaxNG"); RETURN_FALSE; } docp = (xmlDocPtr) dom_object_get_node(intern); vptr = xmlRelaxNGNewValidCtxt(sptr); if (!vptr) { xmlRelaxNGFree(sptr); php_error(E_ERROR, "Invalid RelaxNG Validation Context"); RETURN_FALSE; } xmlRelaxNGSetValidErrors(vptr, php_libxml_error_handler, php_libxml_error_handler, vptr); is_valid = xmlRelaxNGValidateDoc(vptr, docp); xmlRelaxNGFree(sptr); xmlRelaxNGFreeValidCtxt(vptr); if (is_valid == 0) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto boolean dom_document_relaxNG_validate_file(string filename); */ PHP_FUNCTION(dom_document_relaxNG_validate_file) { _dom_document_relaxNG_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_FILE); } /* }}} end dom_document_relaxNG_validate_file */ /* {{{ proto boolean dom_document_relaxNG_validate_xml(string source); */ PHP_FUNCTION(dom_document_relaxNG_validate_xml) { _dom_document_relaxNG_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_STRING); } /* }}} end dom_document_relaxNG_validate_xml */ #endif #if defined(LIBXML_HTML_ENABLED) static void dom_load_html(INTERNAL_FUNCTION_PARAMETERS, int mode) /* {{{ */ { zval *id, *rv = NULL; xmlDoc *docp = NULL, *newdoc; dom_object *intern; dom_doc_propsptr doc_prop; char *source; int source_len, refcount, ret; htmlParserCtxtPtr ctxt; id = getThis(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &source, &source_len) == FAILURE) { return; } if (!source_len) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty string supplied as input"); RETURN_FALSE; } if (mode == DOM_LOAD_FILE) { ctxt = htmlCreateFileParserCtxt(source, NULL); } else { source_len = xmlStrlen(source); ctxt = htmlCreateMemoryParserCtxt(source, source_len); } if (!ctxt) { RETURN_FALSE; } ctxt->vctxt.error = php_libxml_ctx_error; ctxt->vctxt.warning = php_libxml_ctx_warning; if (ctxt->sax != NULL) { ctxt->sax->error = php_libxml_ctx_error; ctxt->sax->warning = php_libxml_ctx_warning; } htmlParseDocument(ctxt); newdoc = ctxt->myDoc; htmlFreeParserCtxt(ctxt); if (!newdoc) RETURN_FALSE; if (id != NULL && instanceof_function(Z_OBJCE_P(id), dom_document_class_entry TSRMLS_CC)) { intern = (dom_object *)zend_object_store_get_object(id TSRMLS_CC); if (intern != NULL) { docp = (xmlDocPtr) dom_object_get_node(intern); doc_prop = NULL; if (docp != NULL) { php_libxml_decrement_node_ptr((php_libxml_node_object *) intern TSRMLS_CC); doc_prop = intern->document->doc_props; intern->document->doc_props = NULL; refcount = php_libxml_decrement_doc_ref((php_libxml_node_object *)intern TSRMLS_CC); if (refcount != 0) { docp->_private = NULL; } } intern->document = NULL; if (php_libxml_increment_doc_ref((php_libxml_node_object *)intern, newdoc TSRMLS_CC) == -1) { RETURN_FALSE; } intern->document->doc_props = doc_prop; } php_libxml_increment_node_ptr((php_libxml_node_object *)intern, (xmlNodePtr)newdoc, (void *)intern TSRMLS_CC); RETURN_TRUE; } else { DOM_RET_OBJ(rv, (xmlNodePtr) newdoc, &ret, NULL); } } /* }}} */ /* {{{ proto DOMNode dom_document_load_html_file(string source); Since: DOM extended */ PHP_METHOD(domdocument, loadHTMLFile) { dom_load_html(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_FILE); } /* }}} end dom_document_load_html_file */ /* {{{ proto DOMNode dom_document_load_html(string source); Since: DOM extended */ PHP_METHOD(domdocument, loadHTML) { dom_load_html(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_STRING); } /* }}} end dom_document_load_html */ /* {{{ proto int dom_document_save_html_file(string file); Convenience method to save to file as html */ PHP_FUNCTION(dom_document_save_html_file) { zval *id; xmlDoc *docp; int file_len, bytes, format; dom_object *intern; dom_doc_propsptr doc_props; char *file; const char *encoding; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &file, &file_len) == FAILURE) { return; } if (file_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Filename"); RETURN_FALSE; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); encoding = (const char *) htmlGetMetaEncoding(docp); doc_props = dom_get_doc_props(intern->document); format = doc_props->formatoutput; bytes = htmlSaveFileFormat(file, docp, encoding, format); if (bytes == -1) { RETURN_FALSE; } RETURN_LONG(bytes); } /* }}} end dom_document_save_html_file */ /* {{{ proto string dom_document_save_html(); Convenience method to output as html */ PHP_FUNCTION(dom_document_save_html) { zval *id, *nodep = NULL; xmlDoc *docp; xmlNode *node; xmlBufferPtr buf; dom_object *intern, *nodeobj; xmlChar *mem = NULL; int size, format; dom_doc_propsptr doc_props; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|O!", &id, dom_document_class_entry, &nodep, dom_node_class_entry) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); doc_props = dom_get_doc_props(intern->document); format = doc_props->formatoutput; if (nodep != NULL) { /* Dump contents of Node */ DOM_GET_OBJ(node, nodep, xmlNodePtr, nodeobj); if (node->doc != docp) { php_dom_throw_error(WRONG_DOCUMENT_ERR, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } buf = xmlBufferCreate(); if (!buf) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not fetch buffer"); RETURN_FALSE; } htmlNodeDumpFormatOutput(buf, docp, node, 0, format); mem = (xmlChar*) xmlBufferContent(buf); if (!mem) { RETVAL_FALSE; } else { RETVAL_STRING(mem, 1); } xmlBufferFree(buf); } else { #if LIBXML_VERSION >= 20623 htmlDocDumpMemoryFormat(docp, &mem, &size, format); #else htmlDocDumpMemory(docp, &mem, &size); #endif if (!size) { RETVAL_FALSE; } else { RETVAL_STRINGL(mem, size, 1); } if (mem) xmlFree(mem); } } /* }}} end dom_document_save_html */ #endif /* defined(LIBXML_HTML_ENABLED) */ /* {{{ proto boolean DOMDocument::registerNodeClass(string baseclass, string extendedclass); Register extended class used to create base node type */ PHP_METHOD(domdocument, registerNodeClass) { zval *id; xmlDoc *docp; char *baseclass = NULL, *extendedclass = NULL; int baseclass_len = 0, extendedclass_len = 0; zend_class_entry *basece = NULL, *ce = NULL; dom_object *intern; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oss!", &id, dom_document_class_entry, &baseclass, &baseclass_len, &extendedclass, &extendedclass_len) == FAILURE) { return; } if (baseclass_len) { zend_class_entry **pce; if (zend_lookup_class(baseclass, baseclass_len, &pce TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Class %s does not exist", baseclass); return; } basece = *pce; } if (basece == NULL || ! instanceof_function(basece, dom_node_class_entry TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Class %s is not derived from DOMNode.", baseclass); return; } if (extendedclass_len) { zend_class_entry **pce; if (zend_lookup_class(extendedclass, extendedclass_len, &pce TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Class %s does not exist", extendedclass); } ce = *pce; } if (ce == NULL || instanceof_function(ce, basece TSRMLS_CC)) { DOM_GET_OBJ(docp, id, xmlDocPtr, intern); if (dom_set_doc_classmap(intern->document, basece, ce TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Class %s could not be registered.", extendedclass); } RETURN_TRUE; } else { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Class %s is not derived from %s.", extendedclass, baseclass); } RETURN_FALSE; } /* }}} */ #endif /* HAVE_LIBXML && HAVE_DOM */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Christian Stocker <[email protected]> | | Rob Richards <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #if HAVE_LIBXML && HAVE_DOM #include "php_dom.h" #include <libxml/SAX.h> #ifdef LIBXML_SCHEMAS_ENABLED #include <libxml/relaxng.h> #include <libxml/xmlschemas.h> #endif typedef struct _idsIterator idsIterator; struct _idsIterator { xmlChar *elementId; xmlNode *element; }; #define DOM_LOAD_STRING 0 #define DOM_LOAD_FILE 1 /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_element, 0, 0, 1) ZEND_ARG_INFO(0, tagName) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_document_fragment, 0, 0, 0) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_text_node, 0, 0, 1) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_comment, 0, 0, 1) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_cdatasection, 0, 0, 1) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_processing_instruction, 0, 0, 2) ZEND_ARG_INFO(0, target) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_attribute, 0, 0, 1) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_entity_reference, 0, 0, 1) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_get_elements_by_tag_name, 0, 0, 1) ZEND_ARG_INFO(0, tagName) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_import_node, 0, 0, 2) ZEND_ARG_OBJ_INFO(0, importedNode, DOMNode, 0) ZEND_ARG_INFO(0, deep) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_element_ns, 0, 0, 2) ZEND_ARG_INFO(0, namespaceURI) ZEND_ARG_INFO(0, qualifiedName) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_create_attribute_ns, 0, 0, 2) ZEND_ARG_INFO(0, namespaceURI) ZEND_ARG_INFO(0, qualifiedName) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_get_elements_by_tag_name_ns, 0, 0, 2) ZEND_ARG_INFO(0, namespaceURI) ZEND_ARG_INFO(0, localName) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_get_element_by_id, 0, 0, 1) ZEND_ARG_INFO(0, elementId) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_adopt_node, 0, 0, 1) ZEND_ARG_OBJ_INFO(0, source, DOMNode, 0) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_normalize_document, 0, 0, 0) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_rename_node, 0, 0, 3) ZEND_ARG_OBJ_INFO(0, node, DOMNode, 0) ZEND_ARG_INFO(0, namespaceURI) ZEND_ARG_INFO(0, qualifiedName) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_load, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_save, 0, 0, 1) ZEND_ARG_INFO(0, file) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_loadxml, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_savexml, 0, 0, 0) ZEND_ARG_OBJ_INFO(0, node, DOMNode, 1) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_construct, 0, 0, 0) ZEND_ARG_INFO(0, version) ZEND_ARG_INFO(0, encoding) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_validate, 0, 0, 0) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_xinclude, 0, 0, 0) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_loadhtml, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_loadhtmlfile, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_savehtml, 0, 0, 0) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_savehtmlfile, 0, 0, 1) ZEND_ARG_INFO(0, file) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_schema_validate_file, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_schema_validate_xml, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_relaxNG_validate_file, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_relaxNG_validate_xml, 0, 0, 1) ZEND_ARG_INFO(0, source) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_document_registernodeclass, 0, 0, 2) ZEND_ARG_INFO(0, baseClass) ZEND_ARG_INFO(0, extendedClass) ZEND_END_ARG_INFO(); /* }}} */ /* * class DOMDocument extends DOMNode * * URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-i-Document * Since: */ const zend_function_entry php_dom_document_class_functions[] = { /* {{{ */ PHP_FALIAS(createElement, dom_document_create_element, arginfo_dom_document_create_element) PHP_FALIAS(createDocumentFragment, dom_document_create_document_fragment, arginfo_dom_document_create_document_fragment) PHP_FALIAS(createTextNode, dom_document_create_text_node, arginfo_dom_document_create_text_node) PHP_FALIAS(createComment, dom_document_create_comment, arginfo_dom_document_create_comment) PHP_FALIAS(createCDATASection, dom_document_create_cdatasection, arginfo_dom_document_create_cdatasection) PHP_FALIAS(createProcessingInstruction, dom_document_create_processing_instruction, arginfo_dom_document_create_processing_instruction) PHP_FALIAS(createAttribute, dom_document_create_attribute, arginfo_dom_document_create_attribute) PHP_FALIAS(createEntityReference, dom_document_create_entity_reference, arginfo_dom_document_create_entity_reference) PHP_FALIAS(getElementsByTagName, dom_document_get_elements_by_tag_name, arginfo_dom_document_get_elements_by_tag_name) PHP_FALIAS(importNode, dom_document_import_node, arginfo_dom_document_import_node) PHP_FALIAS(createElementNS, dom_document_create_element_ns, arginfo_dom_document_create_element_ns) PHP_FALIAS(createAttributeNS, dom_document_create_attribute_ns, arginfo_dom_document_create_attribute_ns) PHP_FALIAS(getElementsByTagNameNS, dom_document_get_elements_by_tag_name_ns, arginfo_dom_document_get_elements_by_tag_name_ns) PHP_FALIAS(getElementById, dom_document_get_element_by_id, arginfo_dom_document_get_element_by_id) PHP_FALIAS(adoptNode, dom_document_adopt_node, arginfo_dom_document_adopt_node) PHP_FALIAS(normalizeDocument, dom_document_normalize_document, arginfo_dom_document_normalize_document) PHP_FALIAS(renameNode, dom_document_rename_node, arginfo_dom_document_rename_node) PHP_ME(domdocument, load, arginfo_dom_document_load, ZEND_ACC_PUBLIC|ZEND_ACC_ALLOW_STATIC) PHP_FALIAS(save, dom_document_save, arginfo_dom_document_save) PHP_ME(domdocument, loadXML, arginfo_dom_document_loadxml, ZEND_ACC_PUBLIC|ZEND_ACC_ALLOW_STATIC) PHP_FALIAS(saveXML, dom_document_savexml, arginfo_dom_document_savexml) PHP_ME(domdocument, __construct, arginfo_dom_document_construct, ZEND_ACC_PUBLIC) PHP_FALIAS(validate, dom_document_validate, arginfo_dom_document_validate) PHP_FALIAS(xinclude, dom_document_xinclude, arginfo_dom_document_xinclude) #if defined(LIBXML_HTML_ENABLED) PHP_ME(domdocument, loadHTML, arginfo_dom_document_loadhtml, ZEND_ACC_PUBLIC|ZEND_ACC_ALLOW_STATIC) PHP_ME(domdocument, loadHTMLFile, arginfo_dom_document_loadhtmlfile, ZEND_ACC_PUBLIC|ZEND_ACC_ALLOW_STATIC) PHP_FALIAS(saveHTML, dom_document_save_html, arginfo_dom_document_savehtml) PHP_FALIAS(saveHTMLFile, dom_document_save_html_file, arginfo_dom_document_savehtmlfile) #endif /* defined(LIBXML_HTML_ENABLED) */ #if defined(LIBXML_SCHEMAS_ENABLED) PHP_FALIAS(schemaValidate, dom_document_schema_validate_file, arginfo_dom_document_schema_validate_file) PHP_FALIAS(schemaValidateSource, dom_document_schema_validate_xml, arginfo_dom_document_schema_validate_xml) PHP_FALIAS(relaxNGValidate, dom_document_relaxNG_validate_file, arginfo_dom_document_relaxNG_validate_file) PHP_FALIAS(relaxNGValidateSource, dom_document_relaxNG_validate_xml, arginfo_dom_document_relaxNG_validate_xml) #endif PHP_ME(domdocument, registerNodeClass, arginfo_dom_document_registernodeclass, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; /* }}} */ /* {{{ docType DOMDocumentType readonly=yes URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-B63ED1A31 Since: */ int dom_document_doctype_read(dom_object *obj, zval **retval TSRMLS_DC) { xmlDoc *docp; xmlDtdPtr dtdptr; int ret; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } ALLOC_ZVAL(*retval); dtdptr = xmlGetIntSubset(docp); if (!dtdptr) { ZVAL_NULL(*retval); return SUCCESS; } if (NULL == (*retval = php_dom_create_object((xmlNodePtr) dtdptr, &ret, NULL, *retval, obj TSRMLS_CC))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot create required DOM object"); return FAILURE; } return SUCCESS; } /* }}} */ /* {{{ implementation DOMImplementation readonly=yes URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1B793EBA Since: */ int dom_document_implementation_read(dom_object *obj, zval **retval TSRMLS_DC) { ALLOC_ZVAL(*retval); php_dom_create_implementation(retval TSRMLS_CC); return SUCCESS; } /* }}} */ /* {{{ documentElement DOMElement readonly=yes URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-87CD092 Since: */ int dom_document_document_element_read(dom_object *obj, zval **retval TSRMLS_DC) { xmlDoc *docp; xmlNode *root; int ret; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } ALLOC_ZVAL(*retval); root = xmlDocGetRootElement(docp); if (!root) { ZVAL_NULL(*retval); return SUCCESS; } if (NULL == (*retval = php_dom_create_object(root, &ret, NULL, *retval, obj TSRMLS_CC))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot create required DOM object"); return FAILURE; } return SUCCESS; } /* }}} */ /* {{{ encoding string URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-encoding Since: DOM Level 3 */ int dom_document_encoding_read(dom_object *obj, zval **retval TSRMLS_DC) { xmlDoc *docp; char *encoding; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } encoding = (char *) docp->encoding; ALLOC_ZVAL(*retval); if (encoding != NULL) { ZVAL_STRING(*retval, encoding, 1); } else { ZVAL_NULL(*retval); } return SUCCESS; } int dom_document_encoding_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; xmlDoc *docp; xmlCharEncodingHandlerPtr handler; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } if (newval->type != IS_STRING) { if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_string(newval); } handler = xmlFindCharEncodingHandler(Z_STRVAL_P(newval)); if (handler != NULL) { xmlCharEncCloseFunc(handler); if (docp->encoding != NULL) { xmlFree((xmlChar *)docp->encoding); } docp->encoding = xmlStrdup((const xmlChar *) Z_STRVAL_P(newval)); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Document Encoding"); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ standalone boolean readonly=no URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-standalone Since: DOM Level 3 */ int dom_document_standalone_read(dom_object *obj, zval **retval TSRMLS_DC) { xmlDoc *docp; int standalone; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } ALLOC_ZVAL(*retval); standalone = docp->standalone; ZVAL_BOOL(*retval, standalone); return SUCCESS; } int dom_document_standalone_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; xmlDoc *docp; int standalone; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_long(newval); standalone = Z_LVAL_P(newval); if (standalone > 0) { docp->standalone = 1; } else if (standalone < 0) { docp->standalone = -1; } else { docp->standalone = 0; } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ version string readonly=no URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-version Since: DOM Level 3 */ int dom_document_version_read(dom_object *obj, zval **retval TSRMLS_DC) { xmlDoc *docp; char *version; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } version = (char *) docp->version; ALLOC_ZVAL(*retval); if (version != NULL) { ZVAL_STRING(*retval, version, 1); } else { ZVAL_NULL(*retval); } return SUCCESS; } int dom_document_version_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; xmlDoc *docp; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } if (docp->version != NULL) { xmlFree((xmlChar *) docp->version ); } if (newval->type != IS_STRING) { if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_string(newval); } docp->version = xmlStrdup((const xmlChar *) Z_STRVAL_P(newval)); if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ strictErrorChecking boolean readonly=no URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-strictErrorChecking Since: DOM Level 3 */ int dom_document_strict_error_checking_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->stricterror); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_strict_error_checking_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->stricterror = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ formatOutput boolean readonly=no */ int dom_document_format_output_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->formatoutput); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_format_output_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->formatoutput = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ validateOnParse boolean readonly=no */ int dom_document_validate_on_parse_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->validateonparse); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_validate_on_parse_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->validateonparse = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ resolveExternals boolean readonly=no */ int dom_document_resolve_externals_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->resolveexternals); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_resolve_externals_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->resolveexternals = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ preserveWhiteSpace boolean readonly=no */ int dom_document_preserve_whitespace_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->preservewhitespace); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_preserve_whitespace_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->preservewhitespace = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ recover boolean readonly=no */ int dom_document_recover_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->recover); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_recover_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->recover = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ substituteEntities boolean readonly=no */ int dom_document_substitue_entities_read(dom_object *obj, zval **retval TSRMLS_DC) { dom_doc_propsptr doc_prop; ALLOC_ZVAL(*retval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); ZVAL_BOOL(*retval, doc_prop->substituteentities); } else { ZVAL_FALSE(*retval); } return SUCCESS; } int dom_document_substitue_entities_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; dom_doc_propsptr doc_prop; if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_boolean(newval); if (obj->document) { doc_prop = dom_get_doc_props(obj->document); doc_prop->substituteentities = Z_LVAL_P(newval); } if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ documentURI string readonly=no URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-documentURI Since: DOM Level 3 */ int dom_document_document_uri_read(dom_object *obj, zval **retval TSRMLS_DC) { xmlDoc *docp; char *url; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } ALLOC_ZVAL(*retval); url = (char *) docp->URL; if (url != NULL) { ZVAL_STRING(*retval, url, 1); } else { ZVAL_NULL(*retval); } return SUCCESS; } int dom_document_document_uri_write(dom_object *obj, zval *newval TSRMLS_DC) { zval value_copy; xmlDoc *docp; docp = (xmlDocPtr) dom_object_get_node(obj); if (docp == NULL) { php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); return FAILURE; } if (docp->URL != NULL) { xmlFree((xmlChar *) docp->URL); } if (newval->type != IS_STRING) { if(Z_REFCOUNT_P(newval) > 1) { value_copy = *newval; zval_copy_ctor(&value_copy); newval = &value_copy; } convert_to_string(newval); } docp->URL = xmlStrdup((const xmlChar *) Z_STRVAL_P(newval)); if (newval == &value_copy) { zval_dtor(newval); } return SUCCESS; } /* }}} */ /* {{{ config DOMConfiguration readonly=yes URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-config Since: DOM Level 3 */ int dom_document_config_read(dom_object *obj, zval **retval TSRMLS_DC) { ALLOC_ZVAL(*retval); ZVAL_NULL(*retval); return SUCCESS; } /* }}} */ /* {{{ proto DOMElement dom_document_create_element(string tagName [, string value]); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-2141741547 Since: */ PHP_FUNCTION(dom_document_create_element) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp; dom_object *intern; int ret, name_len, value_len; char *name, *value = NULL; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|s", &id, dom_document_class_entry, &name, &name_len, &value, &value_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); if (xmlValidateName((xmlChar *) name, 0) != 0) { php_dom_throw_error(INVALID_CHARACTER_ERR, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } node = xmlNewDocNode(docp, NULL, name, value); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, node, &ret, intern); } /* }}} end dom_document_create_element */ /* {{{ proto DOMDocumentFragment dom_document_create_document_fragment(); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-35CB04B5 Since: */ PHP_FUNCTION(dom_document_create_document_fragment) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp; dom_object *intern; int ret; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &id, dom_document_class_entry) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); node = xmlNewDocFragment(docp); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, node, &ret, intern); } /* }}} end dom_document_create_document_fragment */ /* {{{ proto DOMText dom_document_create_text_node(string data); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1975348127 Since: */ PHP_FUNCTION(dom_document_create_text_node) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp; int ret, value_len; dom_object *intern; char *value; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &value, &value_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); node = xmlNewDocText(docp, (xmlChar *) value); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, node, &ret, intern); } /* }}} end dom_document_create_text_node */ /* {{{ proto DOMComment dom_document_create_comment(string data); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1334481328 Since: */ PHP_FUNCTION(dom_document_create_comment) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp; int ret, value_len; dom_object *intern; char *value; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &value, &value_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); node = xmlNewDocComment(docp, (xmlChar *) value); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, node, &ret, intern); } /* }}} end dom_document_create_comment */ /* {{{ proto DOMCdataSection dom_document_create_cdatasection(string data); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-D26C0AF8 Since: */ PHP_FUNCTION(dom_document_create_cdatasection) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp; int ret, value_len; dom_object *intern; char *value; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &value, &value_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); node = xmlNewCDataBlock(docp, (xmlChar *) value, value_len); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, node, &ret, intern); } /* }}} end dom_document_create_cdatasection */ /* {{{ proto DOMProcessingInstruction dom_document_create_processing_instruction(string target, string data); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-135944439 Since: */ PHP_FUNCTION(dom_document_create_processing_instruction) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp; int ret, value_len, name_len = 0; dom_object *intern; char *name, *value = NULL; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|s", &id, dom_document_class_entry, &name, &name_len, &value, &value_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); if (xmlValidateName((xmlChar *) name, 0) != 0) { php_dom_throw_error(INVALID_CHARACTER_ERR, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } node = xmlNewPI((xmlChar *) name, (xmlChar *) value); if (!node) { RETURN_FALSE; } node->doc = docp; DOM_RET_OBJ(rv, node, &ret, intern); } /* }}} end dom_document_create_processing_instruction */ /* {{{ proto DOMAttr dom_document_create_attribute(string name); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1084891198 Since: */ PHP_FUNCTION(dom_document_create_attribute) { zval *id, *rv = NULL; xmlAttrPtr node; xmlDocPtr docp; int ret, name_len; dom_object *intern; char *name; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &name, &name_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); if (xmlValidateName((xmlChar *) name, 0) != 0) { php_dom_throw_error(INVALID_CHARACTER_ERR, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } node = xmlNewDocProp(docp, (xmlChar *) name, NULL); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, (xmlNodePtr) node, &ret, intern); } /* }}} end dom_document_create_attribute */ /* {{{ proto DOMEntityReference dom_document_create_entity_reference(string name); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-392B75AE Since: */ PHP_FUNCTION(dom_document_create_entity_reference) { zval *id, *rv = NULL; xmlNode *node; xmlDocPtr docp = NULL; dom_object *intern; int ret, name_len; char *name; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &name, &name_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); if (xmlValidateName((xmlChar *) name, 0) != 0) { php_dom_throw_error(INVALID_CHARACTER_ERR, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } node = xmlNewReference(docp, name); if (!node) { RETURN_FALSE; } DOM_RET_OBJ(rv, (xmlNodePtr) node, &ret, intern); } /* }}} end dom_document_create_entity_reference */ /* {{{ proto DOMNodeList dom_document_get_elements_by_tag_name(string tagname); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-A6C9094 Since: */ PHP_FUNCTION(dom_document_get_elements_by_tag_name) { zval *id; xmlDocPtr docp; int name_len; dom_object *intern, *namednode; char *name; xmlChar *local; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &name, &name_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); php_dom_create_interator(return_value, DOM_NODELIST TSRMLS_CC); namednode = (dom_object *)zend_objects_get_address(return_value TSRMLS_CC); local = xmlCharStrndup(name, name_len); dom_namednode_iter(intern, 0, namednode, NULL, local, NULL TSRMLS_CC); } /* }}} end dom_document_get_elements_by_tag_name */ /* {{{ proto DOMNode dom_document_import_node(DOMNode importedNode, boolean deep); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Core-Document-importNode Since: DOM Level 2 */ PHP_FUNCTION(dom_document_import_node) { zval *rv = NULL; zval *id, *node; xmlDocPtr docp; xmlNodePtr nodep, retnodep; dom_object *intern, *nodeobj; int ret; long recursive = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO|l", &id, dom_document_class_entry, &node, dom_node_class_entry, &recursive) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); DOM_GET_OBJ(nodep, node, xmlNodePtr, nodeobj); if (nodep->type == XML_HTML_DOCUMENT_NODE || nodep->type == XML_DOCUMENT_NODE || nodep->type == XML_DOCUMENT_TYPE_NODE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot import: Node Type Not Supported"); RETURN_FALSE; } if (nodep->doc == docp) { retnodep = nodep; } else { if ((recursive == 0) && (nodep->type == XML_ELEMENT_NODE)) { recursive = 2; } retnodep = xmlDocCopyNode(nodep, docp, recursive); if (!retnodep) { RETURN_FALSE; } if ((retnodep->type == XML_ATTRIBUTE_NODE) && (nodep->ns != NULL)) { xmlNsPtr nsptr = NULL; xmlNodePtr root = xmlDocGetRootElement(docp); nsptr = xmlSearchNsByHref (nodep->doc, root, nodep->ns->href); if (nsptr == NULL) { int errorcode; nsptr = dom_get_ns(root, (char *) nodep->ns->href, &errorcode, (char *) nodep->ns->prefix); } xmlSetNs(retnodep, nsptr); } } DOM_RET_OBJ(rv, (xmlNodePtr) retnodep, &ret, intern); } /* }}} end dom_document_import_node */ /* {{{ proto DOMElement dom_document_create_element_ns(string namespaceURI, string qualifiedName [,string value]); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-DocCrElNS Since: DOM Level 2 */ PHP_FUNCTION(dom_document_create_element_ns) { zval *id, *rv = NULL; xmlDocPtr docp; xmlNodePtr nodep = NULL; xmlNsPtr nsptr = NULL; int ret, uri_len = 0, name_len = 0, value_len = 0; char *uri, *name, *value = NULL; char *localname = NULL, *prefix = NULL; int errorcode; dom_object *intern; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os!s|s", &id, dom_document_class_entry, &uri, &uri_len, &name, &name_len, &value, &value_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); errorcode = dom_check_qname(name, &localname, &prefix, uri_len, name_len); if (errorcode == 0) { if (xmlValidateName((xmlChar *) localname, 0) == 0) { nodep = xmlNewDocNode (docp, NULL, localname, value); if (nodep != NULL && uri != NULL) { nsptr = xmlSearchNsByHref (nodep->doc, nodep, uri); if (nsptr == NULL) { nsptr = dom_get_ns(nodep, uri, &errorcode, prefix); } xmlSetNs(nodep, nsptr); } } else { errorcode = INVALID_CHARACTER_ERR; } } xmlFree(localname); if (prefix != NULL) { xmlFree(prefix); } if (errorcode != 0) { if (nodep != NULL) { xmlFreeNode(nodep); } php_dom_throw_error(errorcode, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } if (nodep == NULL) { RETURN_FALSE; } nodep->ns = nsptr; DOM_RET_OBJ(rv, nodep, &ret, intern); } /* }}} end dom_document_create_element_ns */ /* {{{ proto DOMAttr dom_document_create_attribute_ns(string namespaceURI, string qualifiedName); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-DocCrAttrNS Since: DOM Level 2 */ PHP_FUNCTION(dom_document_create_attribute_ns) { zval *id, *rv = NULL; xmlDocPtr docp; xmlNodePtr nodep = NULL, root; xmlNsPtr nsptr; int ret, uri_len = 0, name_len = 0; char *uri, *name; char *localname = NULL, *prefix = NULL; dom_object *intern; int errorcode; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os!s", &id, dom_document_class_entry, &uri, &uri_len, &name, &name_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); root = xmlDocGetRootElement(docp); if (root != NULL) { errorcode = dom_check_qname(name, &localname, &prefix, uri_len, name_len); if (errorcode == 0) { if (xmlValidateName((xmlChar *) localname, 0) == 0) { nodep = (xmlNodePtr) xmlNewDocProp(docp, localname, NULL); if (nodep != NULL && uri_len > 0) { nsptr = xmlSearchNsByHref (nodep->doc, root, uri); if (nsptr == NULL) { nsptr = dom_get_ns(root, uri, &errorcode, prefix); } xmlSetNs(nodep, nsptr); } } else { errorcode = INVALID_CHARACTER_ERR; } } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Document Missing Root Element"); RETURN_FALSE; } xmlFree(localname); if (prefix != NULL) { xmlFree(prefix); } if (errorcode != 0) { if (nodep != NULL) { xmlFreeProp((xmlAttrPtr) nodep); } php_dom_throw_error(errorcode, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } if (nodep == NULL) { RETURN_FALSE; } DOM_RET_OBJ(rv, nodep, &ret, intern); } /* }}} end dom_document_create_attribute_ns */ /* {{{ proto DOMNodeList dom_document_get_elements_by_tag_name_ns(string namespaceURI, string localName); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-getElBTNNS Since: DOM Level 2 */ PHP_FUNCTION(dom_document_get_elements_by_tag_name_ns) { zval *id; xmlDocPtr docp; int uri_len, name_len; dom_object *intern, *namednode; char *uri, *name; xmlChar *local, *nsuri; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oss", &id, dom_document_class_entry, &uri, &uri_len, &name, &name_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); php_dom_create_interator(return_value, DOM_NODELIST TSRMLS_CC); namednode = (dom_object *)zend_objects_get_address(return_value TSRMLS_CC); local = xmlCharStrndup(name, name_len); nsuri = xmlCharStrndup(uri, uri_len); dom_namednode_iter(intern, 0, namednode, NULL, local, nsuri TSRMLS_CC); } /* }}} end dom_document_get_elements_by_tag_name_ns */ /* {{{ proto DOMElement dom_document_get_element_by_id(string elementId); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-getElBId Since: DOM Level 2 */ PHP_FUNCTION(dom_document_get_element_by_id) { zval *id, *rv = NULL; xmlDocPtr docp; xmlAttrPtr attrp; int ret, idname_len; dom_object *intern; char *idname; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &idname, &idname_len) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); attrp = xmlGetID(docp, (xmlChar *) idname); if (attrp && attrp->parent) { DOM_RET_OBJ(rv, (xmlNodePtr) attrp->parent, &ret, intern); } else { RETVAL_NULL(); } } /* }}} end dom_document_get_element_by_id */ /* {{{ proto DOMNode dom_document_adopt_node(DOMNode source); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-adoptNode Since: DOM Level 3 */ PHP_FUNCTION(dom_document_adopt_node) { DOM_NOT_IMPLEMENTED(); } /* }}} end dom_document_adopt_node */ /* {{{ proto void dom_document_normalize_document(); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-normalizeDocument Since: DOM Level 3 */ PHP_FUNCTION(dom_document_normalize_document) { zval *id; xmlDocPtr docp; dom_object *intern; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &id, dom_document_class_entry) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); dom_normalize((xmlNodePtr) docp TSRMLS_CC); } /* }}} end dom_document_normalize_document */ /* {{{ proto DOMNode dom_document_rename_node(node n, string namespaceURI, string qualifiedName); URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-renameNode Since: DOM Level 3 */ PHP_FUNCTION(dom_document_rename_node) { DOM_NOT_IMPLEMENTED(); } /* }}} end dom_document_rename_node */ /* {{{ proto void DOMDocument::__construct([string version], [string encoding]); */ PHP_METHOD(domdocument, __construct) { zval *id; xmlDoc *docp = NULL, *olddoc; dom_object *intern; char *encoding, *version = NULL; int encoding_len = 0, version_len = 0, refcount; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, dom_domexception_class_entry, &error_handling TSRMLS_CC); if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|ss", &id, dom_document_class_entry, &version, &version_len, &encoding, &encoding_len) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } zend_restore_error_handling(&error_handling TSRMLS_CC); docp = xmlNewDoc(version); if (!docp) { php_dom_throw_error(INVALID_STATE_ERR, 1 TSRMLS_CC); RETURN_FALSE; } if (encoding_len > 0) { docp->encoding = (const xmlChar*)xmlStrdup(encoding); } intern = (dom_object *)zend_object_store_get_object(id TSRMLS_CC); if (intern != NULL) { olddoc = (xmlDocPtr) dom_object_get_node(intern); if (olddoc != NULL) { php_libxml_decrement_node_ptr((php_libxml_node_object *) intern TSRMLS_CC); refcount = php_libxml_decrement_doc_ref((php_libxml_node_object *)intern TSRMLS_CC); if (refcount != 0) { olddoc->_private = NULL; } } intern->document = NULL; if (php_libxml_increment_doc_ref((php_libxml_node_object *)intern, docp TSRMLS_CC) == -1) { RETURN_FALSE; } php_libxml_increment_node_ptr((php_libxml_node_object *)intern, (xmlNodePtr)docp, (void *)intern TSRMLS_CC); } } /* }}} end DOMDocument::__construct */ char *_dom_get_valid_file_path(char *source, char *resolved_path, int resolved_path_len TSRMLS_DC) /* {{{ */ { xmlURI *uri; xmlChar *escsource; char *file_dest; int isFileUri = 0; uri = xmlCreateURI(); escsource = xmlURIEscapeStr(source, ":"); xmlParseURIReference(uri, escsource); xmlFree(escsource); if (uri->scheme != NULL) { /* absolute file uris - libxml only supports localhost or empty host */ if (strncasecmp(source, "file:///",8) == 0) { isFileUri = 1; #ifdef PHP_WIN32 source += 8; #else source += 7; #endif } else if (strncasecmp(source, "file://localhost/",17) == 0) { isFileUri = 1; #ifdef PHP_WIN32 source += 17; #else source += 16; #endif } } file_dest = source; if ((uri->scheme == NULL || isFileUri)) { /* XXX possible buffer overflow if VCWD_REALPATH does not know size of resolved_path */ if (!VCWD_REALPATH(source, resolved_path) && !expand_filepath(source, resolved_path TSRMLS_CC)) { xmlFreeURI(uri); return NULL; } file_dest = resolved_path; } xmlFreeURI(uri); return file_dest; } /* }}} */ static xmlDocPtr dom_document_parser(zval *id, int mode, char *source, int source_len, int options TSRMLS_DC) /* {{{ */ { xmlDocPtr ret; xmlParserCtxtPtr ctxt = NULL; dom_doc_propsptr doc_props; dom_object *intern; php_libxml_ref_obj *document = NULL; int validate, recover, resolve_externals, keep_blanks, substitute_ent; int resolved_path_len; int old_error_reporting = 0; char *directory=NULL, resolved_path[MAXPATHLEN]; if (id != NULL) { intern = (dom_object *)zend_object_store_get_object(id TSRMLS_CC); document = intern->document; } doc_props = dom_get_doc_props(document); validate = doc_props->validateonparse; resolve_externals = doc_props->resolveexternals; keep_blanks = doc_props->preservewhitespace; substitute_ent = doc_props->substituteentities; recover = doc_props->recover; if (document == NULL) { efree(doc_props); } xmlInitParser(); if (mode == DOM_LOAD_FILE) { char *file_dest = _dom_get_valid_file_path(source, resolved_path, MAXPATHLEN TSRMLS_CC); if (file_dest) { ctxt = xmlCreateFileParserCtxt(file_dest); } } else { ctxt = xmlCreateMemoryParserCtxt(source, source_len); } if (ctxt == NULL) { return(NULL); } /* If loading from memory, we need to set the base directory for the document */ if (mode != DOM_LOAD_FILE) { #if HAVE_GETCWD directory = VCWD_GETCWD(resolved_path, MAXPATHLEN); #elif HAVE_GETWD directory = VCWD_GETWD(resolved_path); #endif if (directory) { if(ctxt->directory != NULL) { xmlFree((char *) ctxt->directory); } resolved_path_len = strlen(resolved_path); if (resolved_path[resolved_path_len - 1] != DEFAULT_SLASH) { resolved_path[resolved_path_len] = DEFAULT_SLASH; resolved_path[++resolved_path_len] = '\0'; } ctxt->directory = (char *) xmlCanonicPath((const xmlChar *) resolved_path); } } ctxt->vctxt.error = php_libxml_ctx_error; ctxt->vctxt.warning = php_libxml_ctx_warning; if (ctxt->sax != NULL) { ctxt->sax->error = php_libxml_ctx_error; ctxt->sax->warning = php_libxml_ctx_warning; } if (validate && ! (options & XML_PARSE_DTDVALID)) { options |= XML_PARSE_DTDVALID; } if (resolve_externals && ! (options & XML_PARSE_DTDATTR)) { options |= XML_PARSE_DTDATTR; } if (substitute_ent && ! (options & XML_PARSE_NOENT)) { options |= XML_PARSE_NOENT; } if (keep_blanks == 0 && ! (options & XML_PARSE_NOBLANKS)) { options |= XML_PARSE_NOBLANKS; } xmlCtxtUseOptions(ctxt, options); ctxt->recovery = recover; if (recover) { old_error_reporting = EG(error_reporting); EG(error_reporting) = old_error_reporting | E_WARNING; } xmlParseDocument(ctxt); if (ctxt->wellFormed || recover) { ret = ctxt->myDoc; if (ctxt->recovery) { EG(error_reporting) = old_error_reporting; } /* If loading from memory, set the base reference uri for the document */ if (ret && ret->URL == NULL && ctxt->directory != NULL) { ret->URL = xmlStrdup(ctxt->directory); } } else { ret = NULL; xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } xmlFreeParserCtxt(ctxt); return(ret); } /* }}} */ /* {{{ static void dom_parse_document(INTERNAL_FUNCTION_PARAMETERS, int mode) */ static void dom_parse_document(INTERNAL_FUNCTION_PARAMETERS, int mode) { zval *id, *rv = NULL; xmlDoc *docp = NULL, *newdoc; dom_doc_propsptr doc_prop; dom_object *intern; char *source; int source_len, refcount, ret; long options = 0; id = getThis(); if (id != NULL && ! instanceof_function(Z_OBJCE_P(id), dom_document_class_entry TSRMLS_CC)) { id = NULL; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &source, &source_len, &options) == FAILURE) { return; } if (!source_len) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty string supplied as input"); RETURN_FALSE; } newdoc = dom_document_parser(id, mode, source, source_len, options TSRMLS_CC); if (!newdoc) RETURN_FALSE; if (id != NULL) { intern = (dom_object *)zend_object_store_get_object(id TSRMLS_CC); if (intern != NULL) { docp = (xmlDocPtr) dom_object_get_node(intern); doc_prop = NULL; if (docp != NULL) { php_libxml_decrement_node_ptr((php_libxml_node_object *) intern TSRMLS_CC); doc_prop = intern->document->doc_props; intern->document->doc_props = NULL; refcount = php_libxml_decrement_doc_ref((php_libxml_node_object *)intern TSRMLS_CC); if (refcount != 0) { docp->_private = NULL; } } intern->document = NULL; if (php_libxml_increment_doc_ref((php_libxml_node_object *)intern, newdoc TSRMLS_CC) == -1) { RETURN_FALSE; } intern->document->doc_props = doc_prop; } php_libxml_increment_node_ptr((php_libxml_node_object *)intern, (xmlNodePtr)newdoc, (void *)intern TSRMLS_CC); RETURN_TRUE; } else { DOM_RET_OBJ(rv, (xmlNodePtr) newdoc, &ret, NULL); } } /* }}} end dom_parser_document */ /* {{{ proto DOMNode dom_document_load(string source [, int options]); URL: http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-DocumentLS-load Since: DOM Level 3 */ PHP_METHOD(domdocument, load) { dom_parse_document(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_FILE); } /* }}} end dom_document_load */ /* {{{ proto DOMNode dom_document_loadxml(string source [, int options]); URL: http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-DocumentLS-loadXML Since: DOM Level 3 */ PHP_METHOD(domdocument, loadXML) { dom_parse_document(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_STRING); } /* }}} end dom_document_loadxml */ /* {{{ proto int dom_document_save(string file); Convenience method to save to file */ PHP_FUNCTION(dom_document_save) { zval *id; xmlDoc *docp; int file_len = 0, bytes, format, saveempty = 0; dom_object *intern; dom_doc_propsptr doc_props; char *file; long options = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|l", &id, dom_document_class_entry, &file, &file_len, &options) == FAILURE) { return; } if (file_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Filename"); RETURN_FALSE; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); /* encoding handled by property on doc */ doc_props = dom_get_doc_props(intern->document); format = doc_props->formatoutput; if (options & LIBXML_SAVE_NOEMPTYTAG) { saveempty = xmlSaveNoEmptyTags; xmlSaveNoEmptyTags = 1; } bytes = xmlSaveFormatFileEnc(file, docp, NULL, format); if (options & LIBXML_SAVE_NOEMPTYTAG) { xmlSaveNoEmptyTags = saveempty; } if (bytes == -1) { RETURN_FALSE; } RETURN_LONG(bytes); } /* }}} end dom_document_save */ /* {{{ proto string dom_document_savexml([node n]); URL: http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-DocumentLS-saveXML Since: DOM Level 3 */ PHP_FUNCTION(dom_document_savexml) { zval *id, *nodep = NULL; xmlDoc *docp; xmlNode *node; xmlBufferPtr buf; xmlChar *mem; dom_object *intern, *nodeobj; dom_doc_propsptr doc_props; int size, format, saveempty = 0; long options = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|O!l", &id, dom_document_class_entry, &nodep, dom_node_class_entry, &options) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); doc_props = dom_get_doc_props(intern->document); format = doc_props->formatoutput; if (nodep != NULL) { /* Dump contents of Node */ DOM_GET_OBJ(node, nodep, xmlNodePtr, nodeobj); if (node->doc != docp) { php_dom_throw_error(WRONG_DOCUMENT_ERR, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } buf = xmlBufferCreate(); if (!buf) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not fetch buffer"); RETURN_FALSE; } if (options & LIBXML_SAVE_NOEMPTYTAG) { saveempty = xmlSaveNoEmptyTags; xmlSaveNoEmptyTags = 1; } xmlNodeDump(buf, docp, node, 0, format); if (options & LIBXML_SAVE_NOEMPTYTAG) { xmlSaveNoEmptyTags = saveempty; } mem = (xmlChar*) xmlBufferContent(buf); if (!mem) { xmlBufferFree(buf); RETURN_FALSE; } RETVAL_STRING(mem, 1); xmlBufferFree(buf); } else { if (options & LIBXML_SAVE_NOEMPTYTAG) { saveempty = xmlSaveNoEmptyTags; xmlSaveNoEmptyTags = 1; } /* Encoding is handled from the encoding property set on the document */ xmlDocDumpFormatMemory(docp, &mem, &size, format); if (options & LIBXML_SAVE_NOEMPTYTAG) { xmlSaveNoEmptyTags = saveempty; } if (!size) { RETURN_FALSE; } RETVAL_STRINGL(mem, size, 1); xmlFree(mem); } } /* }}} end dom_document_savexml */ static xmlNodePtr php_dom_free_xinclude_node(xmlNodePtr cur TSRMLS_DC) /* {{{ */ { xmlNodePtr xincnode; xincnode = cur; cur = cur->next; xmlUnlinkNode(xincnode); php_libxml_node_free_resource(xincnode TSRMLS_CC); return cur; } /* }}} */ static void php_dom_remove_xinclude_nodes(xmlNodePtr cur TSRMLS_DC) /* {{{ */ { while(cur) { if (cur->type == XML_XINCLUDE_START) { cur = php_dom_free_xinclude_node(cur TSRMLS_CC); /* XML_XINCLUDE_END node will be a sibling of XML_XINCLUDE_START */ while(cur && cur->type != XML_XINCLUDE_END) { /* remove xinclude processing nodes from recursive xincludes */ if (cur->type == XML_ELEMENT_NODE) { php_dom_remove_xinclude_nodes(cur->children TSRMLS_CC); } cur = cur->next; } if (cur && cur->type == XML_XINCLUDE_END) { cur = php_dom_free_xinclude_node(cur TSRMLS_CC); } } else { if (cur->type == XML_ELEMENT_NODE) { php_dom_remove_xinclude_nodes(cur->children TSRMLS_CC); } cur = cur->next; } } } /* }}} */ /* {{{ proto int dom_document_xinclude([int options]) Substitutues xincludes in a DomDocument */ PHP_FUNCTION(dom_document_xinclude) { zval *id; xmlDoc *docp; xmlNodePtr root; long flags = 0; int err; dom_object *intern; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|l", &id, dom_document_class_entry, &flags) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); err = xmlXIncludeProcessFlags(docp, flags); /* XML_XINCLUDE_START and XML_XINCLUDE_END nodes need to be removed as these are added via xmlXIncludeProcess to mark beginning and ending of xincluded document but are not wanted in resulting document - must be done even if err as it could fail after having processed some xincludes */ root = (xmlNodePtr) docp->children; while(root && root->type != XML_ELEMENT_NODE && root->type != XML_XINCLUDE_START) { root = root->next; } if (root) { php_dom_remove_xinclude_nodes(root TSRMLS_CC); } if (err) { RETVAL_LONG(err); } else { RETVAL_FALSE; } } /* }}} */ /* {{{ proto boolean dom_document_validate(); Since: DOM extended */ PHP_FUNCTION(dom_document_validate) { zval *id; xmlDoc *docp; dom_object *intern; xmlValidCtxt *cvp; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &id, dom_document_class_entry) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); cvp = xmlNewValidCtxt(); cvp->userData = NULL; cvp->error = (xmlValidityErrorFunc) php_libxml_error_handler; cvp->warning = (xmlValidityErrorFunc) php_libxml_error_handler; if (xmlValidateDocument(cvp, docp)) { RETVAL_TRUE; } else { RETVAL_FALSE; } xmlFreeValidCtxt(cvp); } /* }}} */ #if defined(LIBXML_SCHEMAS_ENABLED) static void _dom_document_schema_validate(INTERNAL_FUNCTION_PARAMETERS, int type) /* {{{ */ { zval *id; xmlDoc *docp; dom_object *intern; char *source = NULL, *valid_file = NULL; int source_len = 0; xmlSchemaParserCtxtPtr parser; xmlSchemaPtr sptr; xmlSchemaValidCtxtPtr vptr; int is_valid; char resolved_path[MAXPATHLEN + 1]; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &source, &source_len) == FAILURE) { return; } if (source_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Schema source"); RETURN_FALSE; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); switch (type) { case DOM_LOAD_FILE: valid_file = _dom_get_valid_file_path(source, resolved_path, MAXPATHLEN TSRMLS_CC); if (!valid_file) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Schema file source"); RETURN_FALSE; } parser = xmlSchemaNewParserCtxt(valid_file); break; case DOM_LOAD_STRING: parser = xmlSchemaNewMemParserCtxt(source, source_len); /* If loading from memory, we need to set the base directory for the document but it is not apparent how to do that for schema's */ break; default: return; } xmlSchemaSetParserErrors(parser, (xmlSchemaValidityErrorFunc) php_libxml_error_handler, (xmlSchemaValidityWarningFunc) php_libxml_error_handler, parser); sptr = xmlSchemaParse(parser); xmlSchemaFreeParserCtxt(parser); if (!sptr) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Schema"); RETURN_FALSE; } docp = (xmlDocPtr) dom_object_get_node(intern); vptr = xmlSchemaNewValidCtxt(sptr); if (!vptr) { xmlSchemaFree(sptr); php_error(E_ERROR, "Invalid Schema Validation Context"); RETURN_FALSE; } xmlSchemaSetValidErrors(vptr, php_libxml_error_handler, php_libxml_error_handler, vptr); is_valid = xmlSchemaValidateDoc(vptr, docp); xmlSchemaFree(sptr); xmlSchemaFreeValidCtxt(vptr); if (is_valid == 0) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto boolean dom_document_schema_validate_file(string filename); */ PHP_FUNCTION(dom_document_schema_validate_file) { _dom_document_schema_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_FILE); } /* }}} end dom_document_schema_validate_file */ /* {{{ proto boolean dom_document_schema_validate(string source); */ PHP_FUNCTION(dom_document_schema_validate_xml) { _dom_document_schema_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_STRING); } /* }}} end dom_document_schema_validate */ static void _dom_document_relaxNG_validate(INTERNAL_FUNCTION_PARAMETERS, int type) /* {{{ */ { zval *id; xmlDoc *docp; dom_object *intern; char *source = NULL, *valid_file = NULL; int source_len = 0; xmlRelaxNGParserCtxtPtr parser; xmlRelaxNGPtr sptr; xmlRelaxNGValidCtxtPtr vptr; int is_valid; char resolved_path[MAXPATHLEN + 1]; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &source, &source_len) == FAILURE) { return; } if (source_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Schema source"); RETURN_FALSE; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); switch (type) { case DOM_LOAD_FILE: valid_file = _dom_get_valid_file_path(source, resolved_path, MAXPATHLEN TSRMLS_CC); if (!valid_file) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid RelaxNG file source"); RETURN_FALSE; } parser = xmlRelaxNGNewParserCtxt(valid_file); break; case DOM_LOAD_STRING: parser = xmlRelaxNGNewMemParserCtxt(source, source_len); /* If loading from memory, we need to set the base directory for the document but it is not apparent how to do that for schema's */ break; default: return; } xmlRelaxNGSetParserErrors(parser, (xmlRelaxNGValidityErrorFunc) php_libxml_error_handler, (xmlRelaxNGValidityWarningFunc) php_libxml_error_handler, parser); sptr = xmlRelaxNGParse(parser); xmlRelaxNGFreeParserCtxt(parser); if (!sptr) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid RelaxNG"); RETURN_FALSE; } docp = (xmlDocPtr) dom_object_get_node(intern); vptr = xmlRelaxNGNewValidCtxt(sptr); if (!vptr) { xmlRelaxNGFree(sptr); php_error(E_ERROR, "Invalid RelaxNG Validation Context"); RETURN_FALSE; } xmlRelaxNGSetValidErrors(vptr, php_libxml_error_handler, php_libxml_error_handler, vptr); is_valid = xmlRelaxNGValidateDoc(vptr, docp); xmlRelaxNGFree(sptr); xmlRelaxNGFreeValidCtxt(vptr); if (is_valid == 0) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto boolean dom_document_relaxNG_validate_file(string filename); */ PHP_FUNCTION(dom_document_relaxNG_validate_file) { _dom_document_relaxNG_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_FILE); } /* }}} end dom_document_relaxNG_validate_file */ /* {{{ proto boolean dom_document_relaxNG_validate_xml(string source); */ PHP_FUNCTION(dom_document_relaxNG_validate_xml) { _dom_document_relaxNG_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_STRING); } /* }}} end dom_document_relaxNG_validate_xml */ #endif #if defined(LIBXML_HTML_ENABLED) static void dom_load_html(INTERNAL_FUNCTION_PARAMETERS, int mode) /* {{{ */ { zval *id, *rv = NULL; xmlDoc *docp = NULL, *newdoc; dom_object *intern; dom_doc_propsptr doc_prop; char *source; int source_len, refcount, ret; htmlParserCtxtPtr ctxt; id = getThis(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &source, &source_len) == FAILURE) { return; } if (!source_len) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty string supplied as input"); RETURN_FALSE; } if (mode == DOM_LOAD_FILE) { ctxt = htmlCreateFileParserCtxt(source, NULL); } else { source_len = xmlStrlen(source); ctxt = htmlCreateMemoryParserCtxt(source, source_len); } if (!ctxt) { RETURN_FALSE; } ctxt->vctxt.error = php_libxml_ctx_error; ctxt->vctxt.warning = php_libxml_ctx_warning; if (ctxt->sax != NULL) { ctxt->sax->error = php_libxml_ctx_error; ctxt->sax->warning = php_libxml_ctx_warning; } htmlParseDocument(ctxt); newdoc = ctxt->myDoc; htmlFreeParserCtxt(ctxt); if (!newdoc) RETURN_FALSE; if (id != NULL && instanceof_function(Z_OBJCE_P(id), dom_document_class_entry TSRMLS_CC)) { intern = (dom_object *)zend_object_store_get_object(id TSRMLS_CC); if (intern != NULL) { docp = (xmlDocPtr) dom_object_get_node(intern); doc_prop = NULL; if (docp != NULL) { php_libxml_decrement_node_ptr((php_libxml_node_object *) intern TSRMLS_CC); doc_prop = intern->document->doc_props; intern->document->doc_props = NULL; refcount = php_libxml_decrement_doc_ref((php_libxml_node_object *)intern TSRMLS_CC); if (refcount != 0) { docp->_private = NULL; } } intern->document = NULL; if (php_libxml_increment_doc_ref((php_libxml_node_object *)intern, newdoc TSRMLS_CC) == -1) { RETURN_FALSE; } intern->document->doc_props = doc_prop; } php_libxml_increment_node_ptr((php_libxml_node_object *)intern, (xmlNodePtr)newdoc, (void *)intern TSRMLS_CC); RETURN_TRUE; } else { DOM_RET_OBJ(rv, (xmlNodePtr) newdoc, &ret, NULL); } } /* }}} */ /* {{{ proto DOMNode dom_document_load_html_file(string source); Since: DOM extended */ PHP_METHOD(domdocument, loadHTMLFile) { dom_load_html(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_FILE); } /* }}} end dom_document_load_html_file */ /* {{{ proto DOMNode dom_document_load_html(string source); Since: DOM extended */ PHP_METHOD(domdocument, loadHTML) { dom_load_html(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_STRING); } /* }}} end dom_document_load_html */ /* {{{ proto int dom_document_save_html_file(string file); Convenience method to save to file as html */ PHP_FUNCTION(dom_document_save_html_file) { zval *id; xmlDoc *docp; int file_len, bytes, format; dom_object *intern; dom_doc_propsptr doc_props; char *file; const char *encoding; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &id, dom_document_class_entry, &file, &file_len) == FAILURE) { return; } if (file_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Filename"); RETURN_FALSE; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); encoding = (const char *) htmlGetMetaEncoding(docp); doc_props = dom_get_doc_props(intern->document); format = doc_props->formatoutput; bytes = htmlSaveFileFormat(file, docp, encoding, format); if (bytes == -1) { RETURN_FALSE; } RETURN_LONG(bytes); } /* }}} end dom_document_save_html_file */ /* {{{ proto string dom_document_save_html(); Convenience method to output as html */ PHP_FUNCTION(dom_document_save_html) { zval *id, *nodep = NULL; xmlDoc *docp; xmlNode *node; xmlBufferPtr buf; dom_object *intern, *nodeobj; xmlChar *mem = NULL; int size, format; dom_doc_propsptr doc_props; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|O!", &id, dom_document_class_entry, &nodep, dom_node_class_entry) == FAILURE) { return; } DOM_GET_OBJ(docp, id, xmlDocPtr, intern); doc_props = dom_get_doc_props(intern->document); format = doc_props->formatoutput; if (nodep != NULL) { /* Dump contents of Node */ DOM_GET_OBJ(node, nodep, xmlNodePtr, nodeobj); if (node->doc != docp) { php_dom_throw_error(WRONG_DOCUMENT_ERR, dom_get_strict_error(intern->document) TSRMLS_CC); RETURN_FALSE; } buf = xmlBufferCreate(); if (!buf) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not fetch buffer"); RETURN_FALSE; } size = htmlNodeDump(buf, docp, node); if (size >= 0) { mem = (xmlChar*) xmlBufferContent(buf); if (!mem) { RETVAL_FALSE; } else { RETVAL_STRINGL((const char*) mem, size, 1); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error dumping HTML node"); RETVAL_FALSE; } xmlBufferFree(buf); } else { #if LIBXML_VERSION >= 20623 htmlDocDumpMemoryFormat(docp, &mem, &size, format); #else htmlDocDumpMemory(docp, &mem, &size); #endif if (!size) { RETVAL_FALSE; } else { RETVAL_STRINGL((const char*) mem, size, 1); } if (mem) xmlFree(mem); } } /* }}} end dom_document_save_html */ #endif /* defined(LIBXML_HTML_ENABLED) */ /* {{{ proto boolean DOMDocument::registerNodeClass(string baseclass, string extendedclass); Register extended class used to create base node type */ PHP_METHOD(domdocument, registerNodeClass) { zval *id; xmlDoc *docp; char *baseclass = NULL, *extendedclass = NULL; int baseclass_len = 0, extendedclass_len = 0; zend_class_entry *basece = NULL, *ce = NULL; dom_object *intern; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oss!", &id, dom_document_class_entry, &baseclass, &baseclass_len, &extendedclass, &extendedclass_len) == FAILURE) { return; } if (baseclass_len) { zend_class_entry **pce; if (zend_lookup_class(baseclass, baseclass_len, &pce TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Class %s does not exist", baseclass); return; } basece = *pce; } if (basece == NULL || ! instanceof_function(basece, dom_node_class_entry TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Class %s is not derived from DOMNode.", baseclass); return; } if (extendedclass_len) { zend_class_entry **pce; if (zend_lookup_class(extendedclass, extendedclass_len, &pce TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Class %s does not exist", extendedclass); } ce = *pce; } if (ce == NULL || instanceof_function(ce, basece TSRMLS_CC)) { DOM_GET_OBJ(docp, id, xmlDocPtr, intern); if (dom_set_doc_classmap(intern->document, basece, ce TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Class %s could not be registered.", extendedclass); } RETURN_TRUE; } else { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Class %s is not derived from %s.", extendedclass, baseclass); } RETURN_FALSE; } /* }}} */ #endif /* HAVE_LIBXML && HAVE_DOM */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-01-18-95388b7cda-b9b1fb1827.c
manybugs_data_52
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <zend_language_parser.h> #include "zend.h" #include "zend_compile.h" #include "zend_constants.h" #include "zend_llist.h" #include "zend_API.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "zend_multibyte.h" #include "zend_language_scanner.h" #define CONSTANT_EX(op_array, op) \ (op_array)->literals[op].constant #define CONSTANT(op) \ CONSTANT_EX(CG(active_op_array), op) #define SET_NODE(target, src) do { \ target ## _type = (src)->op_type; \ if ((src)->op_type == IS_CONST) { \ target.constant = zend_add_literal(CG(active_op_array), &(src)->u.constant TSRMLS_CC); \ } else { \ target = (src)->u.op; \ } \ } while (0) #define GET_NODE(target, src) do { \ (target)->op_type = src ## _type; \ if ((target)->op_type == IS_CONST) { \ (target)->u.constant = CONSTANT(src.constant); \ } else { \ (target)->u.op = src; \ (target)->EA = 0; \ } \ } while (0) #define COPY_NODE(target, src) do { \ target ## _type = src ## _type; \ target = src; \ } while (0) #define CALCULATE_LITERAL_HASH(num) do { \ if (IS_INTERNED(Z_STRVAL(CONSTANT(num)))) { \ Z_HASH_P(&CONSTANT(num)) = INTERNED_HASH(Z_STRVAL(CONSTANT(num))); \ } else { \ Z_HASH_P(&CONSTANT(num)) = zend_hash_func(Z_STRVAL(CONSTANT(num)), Z_STRLEN(CONSTANT(num))+1); \ } \ } while (0) #define GET_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot++; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ } \ } while (0) #define POLYMORPHIC_CACHE_SLOT_SIZE 2 #define GET_POLYMORPHIC_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot; \ CG(active_op_array)->last_cache_slot += POLYMORPHIC_CACHE_SLOT_SIZE; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 2] = NULL; \ } \ } while (0) #define FREE_POLYMORPHIC_CACHE_SLOT(literal) do { \ if (CG(active_op_array)->literals[literal].cache_slot == \ CG(active_op_array)->last_cache_slot - POLYMORPHIC_CACHE_SLOT_SIZE) { \ CG(active_op_array)->literals[literal].cache_slot = -1; \ CG(active_op_array)->last_cache_slot -= POLYMORPHIC_CACHE_SLOT_SIZE; \ } \ } while (0) ZEND_API zend_op_array *(*zend_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); ZEND_API zend_op_array *(*zend_compile_string)(zval *source_string, char *filename TSRMLS_DC); #ifndef ZTS ZEND_API zend_compiler_globals compiler_globals; ZEND_API zend_executor_globals executor_globals; #endif static void zend_duplicate_property_info(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = estrndup(property_info->name, property_info->name_length); } if (property_info->doc_comment) { property_info->doc_comment = estrndup(property_info->doc_comment, property_info->doc_comment_len); } } /* }}} */ static void zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = zend_strndup(property_info->name, property_info->name_length); } } /* }}} */ static void zend_destroy_property_info(zend_property_info *property_info) /* {{{ */ { str_efree(property_info->name); if (property_info->doc_comment) { efree((char*)property_info->doc_comment); } } /* }}} */ static void zend_destroy_property_info_internal(zend_property_info *property_info) /* {{{ */ { str_free((char*)property_info->name); } /* }}} */ static void build_runtime_defined_function_key(zval *result, const char *name, int name_length TSRMLS_DC) /* {{{ */ { char char_pos_buf[32]; uint char_pos_len; const char *filename; char_pos_len = zend_sprintf(char_pos_buf, "%p", LANG_SCNG(yy_text)); if (CG(active_op_array)->filename) { filename = CG(active_op_array)->filename; } else { filename = "-"; } /* NULL, name length, filename length, last accepting char position length */ result->value.str.len = 1+name_length+strlen(filename)+char_pos_len; /* must be binary safe */ result->value.str.val = (char *) safe_emalloc(result->value.str.len, 1, 1); result->value.str.val[0] = '\0'; sprintf(result->value.str.val+1, "%s%s%s", name, filename, char_pos_buf); result->type = IS_STRING; Z_SET_REFCOUNT_P(result, 1); } /* }}} */ static void init_compiler_declarables(TSRMLS_D) /* {{{ */ { Z_TYPE(CG(declarables).ticks) = IS_LONG; Z_LVAL(CG(declarables).ticks) = 0; } /* }}} */ void zend_init_compiler_context(TSRMLS_D) /* {{{ */ { CG(context).opcodes_size = (CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) ? INITIAL_INTERACTIVE_OP_ARRAY_SIZE : INITIAL_OP_ARRAY_SIZE; CG(context).vars_size = 0; CG(context).literals_size = 0; CG(context).current_brk_cont = -1; CG(context).backpatch_count = 0; CG(context).labels = NULL; } /* }}} */ void zend_init_compiler_data_structures(TSRMLS_D) /* {{{ */ { zend_stack_init(&CG(bp_stack)); zend_stack_init(&CG(function_call_stack)); zend_stack_init(&CG(switch_cond_stack)); zend_stack_init(&CG(foreach_copy_stack)); zend_stack_init(&CG(object_stack)); zend_stack_init(&CG(declare_stack)); CG(active_class_entry) = NULL; zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_stack_init(&CG(list_stack)); CG(in_compilation) = 0; CG(start_lineno) = 0; CG(current_namespace) = NULL; CG(in_namespace) = 0; CG(has_bracketed_namespaces) = 0; CG(current_import) = NULL; init_compiler_declarables(TSRMLS_C); zend_stack_init(&CG(context_stack)); CG(encoding_declared) = 0; } /* }}} */ ZEND_API void file_handle_dtor(zend_file_handle *fh) /* {{{ */ { TSRMLS_FETCH(); zend_file_handle_dtor(fh TSRMLS_CC); } /* }}} */ void init_compiler(TSRMLS_D) /* {{{ */ { CG(active_op_array) = NULL; zend_init_compiler_data_structures(TSRMLS_C); zend_init_rsrc_list(TSRMLS_C); zend_hash_init(&CG(filenames_table), 5, NULL, (dtor_func_t) free_estring, 0); zend_llist_init(&CG(open_files), sizeof(zend_file_handle), (void (*)(void *)) file_handle_dtor, 0); CG(unclean_shutdown) = 0; } /* }}} */ void shutdown_compiler(TSRMLS_D) /* {{{ */ { zend_stack_destroy(&CG(bp_stack)); zend_stack_destroy(&CG(function_call_stack)); zend_stack_destroy(&CG(switch_cond_stack)); zend_stack_destroy(&CG(foreach_copy_stack)); zend_stack_destroy(&CG(object_stack)); zend_stack_destroy(&CG(declare_stack)); zend_stack_destroy(&CG(list_stack)); zend_hash_destroy(&CG(filenames_table)); zend_llist_destroy(&CG(open_files)); zend_stack_destroy(&CG(context_stack)); } /* }}} */ ZEND_API char *zend_set_compiled_filename(const char *new_compiled_filename TSRMLS_DC) /* {{{ */ { char **pp, *p; int length = strlen(new_compiled_filename); if (zend_hash_find(&CG(filenames_table), new_compiled_filename, length+1, (void **) &pp) == SUCCESS) { CG(compiled_filename) = *pp; return *pp; } p = estrndup(new_compiled_filename, length); zend_hash_update(&CG(filenames_table), new_compiled_filename, length+1, &p, sizeof(char *), (void **) &pp); CG(compiled_filename) = p; return p; } /* }}} */ ZEND_API void zend_restore_compiled_filename(char *original_compiled_filename TSRMLS_DC) /* {{{ */ { CG(compiled_filename) = original_compiled_filename; } /* }}} */ ZEND_API char *zend_get_compiled_filename(TSRMLS_D) /* {{{ */ { return CG(compiled_filename); } /* }}} */ ZEND_API int zend_get_compiled_lineno(TSRMLS_D) /* {{{ */ { return CG(zend_lineno); } /* }}} */ ZEND_API zend_bool zend_is_compiling(TSRMLS_D) /* {{{ */ { return CG(in_compilation); } /* }}} */ static zend_uint get_temporary_variable(zend_op_array *op_array) /* {{{ */ { return (op_array->T)++ * ZEND_MM_ALIGNED_SIZE(sizeof(temp_variable)); } /* }}} */ static int lookup_cv(zend_op_array *op_array, char* name, int name_len, ulong hash TSRMLS_DC) /* {{{ */ { int i = 0; ulong hash_value = hash ? hash : zend_inline_hash_func(name, name_len+1); while (i < op_array->last_var) { if (op_array->vars[i].name == name || (op_array->vars[i].hash_value == hash_value && op_array->vars[i].name_len == name_len && memcmp(op_array->vars[i].name, name, name_len) == 0)) { str_efree(name); return i; } i++; } i = op_array->last_var; op_array->last_var++; if (op_array->last_var > CG(context).vars_size) { CG(context).vars_size += 16; /* FIXME */ op_array->vars = erealloc(op_array->vars, CG(context).vars_size * sizeof(zend_compiled_variable)); } op_array->vars[i].name = zend_new_interned_string(name, name_len + 1, 1 TSRMLS_CC); op_array->vars[i].name_len = name_len; op_array->vars[i].hash_value = hash_value; return i; } /* }}} */ void zend_del_literal(zend_op_array *op_array, int n) /* {{{ */ { zval_dtor(&CONSTANT_EX(op_array, n)); if (n + 1 == op_array->last_literal) { op_array->last_literal--; } else { Z_TYPE(CONSTANT_EX(op_array, n)) = IS_NULL; } } /* }}} */ /* Common part of zend_add_literal and zend_append_individual_literal */ static inline void zend_insert_literal(zend_op_array *op_array, const zval *zv, int literal_position TSRMLS_DC) /* {{{ */ { if (Z_TYPE_P(zv) == IS_STRING || Z_TYPE_P(zv) == IS_CONSTANT) { zval *z = (zval*)zv; Z_STRVAL_P(z) = (char*)zend_new_interned_string(Z_STRVAL_P(zv), Z_STRLEN_P(zv) + 1, 1 TSRMLS_CC); } CONSTANT_EX(op_array, literal_position) = *zv; Z_SET_REFCOUNT(CONSTANT_EX(op_array, literal_position), 2); Z_SET_ISREF(CONSTANT_EX(op_array, literal_position)); op_array->literals[literal_position].hash_value = 0; op_array->literals[literal_position].cache_slot = -1; } /* }}} */ /* Is used while compiling a function, using the context to keep track of an approximate size to avoid to relocate to often. Literals are truncated to actual size in the second compiler pass (pass_two()). */ int zend_add_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; if (i >= CG(context).literals_size) { while (i >= CG(context).literals_size) { CG(context).literals_size += 16; /* FIXME */ } op_array->literals = (zend_literal*)erealloc(op_array->literals, CG(context).literals_size * sizeof(zend_literal)); } zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ /* Is used after normal compilation to append an additional literal. Allocation is done precisely here. */ int zend_append_individual_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; op_array->literals = (zend_literal*)erealloc(op_array->literals, (i + 1) * sizeof(zend_literal)); zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ int zend_add_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_ns_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; const char *ns_separator; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); ns_separator = (const char*)zend_memrchr(Z_STRVAL_P(zv), '\\', Z_STRLEN_P(zv)) + 1; lc_len = Z_STRLEN_P(zv) - (ns_separator - Z_STRVAL_P(zv)); lc_name = zend_str_tolower_dup(ns_separator, lc_len); ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_class_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } if (Z_STRVAL_P(zv)[0] == '\\') { lc_len = Z_STRLEN_P(zv) - 1; lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv) + 1, lc_len); } else { lc_len = Z_STRLEN_P(zv); lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), lc_len); } ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); GET_CACHE_SLOT(ret); return ret; } /* }}} */ int zend_add_const_name_literal(zend_op_array *op_array, const zval *zv, int unqualified TSRMLS_DC) /* {{{ */ { int ret, tmp_literal; char *name, *tmp_name; const char *ns_separator; int name_len, ns_len; zval c; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } /* skip leading '\\' */ if (Z_STRVAL_P(zv)[0] == '\\') { name_len = Z_STRLEN_P(zv) - 1; name = Z_STRVAL_P(zv) + 1; } else { name_len = Z_STRLEN_P(zv); name = Z_STRVAL_P(zv); } ns_separator = zend_memrchr(name, '\\', name_len); if (ns_separator) { ns_len = ns_separator - name; } else { ns_len = 0; } if (ns_len) { /* lowercased namespace name & original constant name */ tmp_name = estrndup(name, name_len); zend_str_tolower(tmp_name, ns_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased namespace name & lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); } if (ns_len) { if (!unqualified) { return ret; } ns_len++; name += ns_len; name_len -= ns_len; } /* original constant name */ tmp_name = estrndup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); return ret; } /* }}} */ #define LITERAL_STRINGL(op, str, len, copy) do { \ zval _c; \ ZVAL_STRINGL(&_c, str, len, copy); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG(op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG_EX(op_array, op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(op_array, &_c TSRMLS_CC); \ } while (0) #define LITERAL_NULL(op) do { \ zval _c; \ INIT_ZVAL( _c); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) static inline zend_bool zend_is_function_or_method_call(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; return ((type & ZEND_PARSED_METHOD_CALL) || (type == ZEND_PARSED_FUNCTION_CALL)); } /* }}} */ void zend_do_binary_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_unary_op(zend_uchar op, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); GET_NODE(result, opline->result); SET_UNUSED(opline->op2); } /* }}} */ #define MAKE_NOP(opline) { opline->opcode = ZEND_NOP; memset(&opline->result,0,sizeof(opline->result)); memset(&opline->op1,0,sizeof(opline->op1)); memset(&opline->op2,0,sizeof(opline->op2)); opline->result_type=opline->op1_type=opline->op2_type=IS_UNUSED; } static void zend_do_op_data(zend_op *data_op, const znode *value TSRMLS_DC) /* {{{ */ { data_op->opcode = ZEND_OP_DATA; SET_NODE(data_op->op1, value); SET_UNUSED(data_op->op2); } /* }}} */ void zend_do_binary_assign_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; switch (last_op->opcode) { case ZEND_FETCH_OBJ_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, op2 TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; case ZEND_FETCH_DIM_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_DIM; zend_do_op_data(opline, op2 TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result,last_op->result); return; default: break; } } opline->opcode = op; SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void fetch_simple_variable_ex(znode *result, znode *varname, int bp, zend_uchar op TSRMLS_DC) /* {{{ */ { zend_op opline; zend_op *opline_ptr; zend_llist *fetch_list_ptr; if (varname->op_type == IS_CONST) { ulong hash = 0; if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } else if (IS_INTERNED(Z_STRVAL(varname->u.constant))) { hash = INTERNED_HASH(Z_STRVAL(varname->u.constant)); } if (!zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC) && !(varname->u.constant.value.str.len == (sizeof("this")-1) && !memcmp(varname->u.constant.value.str.val, "this", sizeof("this"))) && (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE)) { result->op_type = IS_CV; result->u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC); varname->u.constant.value.str.val = (char*)CG(active_op_array)->vars[result->u.op.var].name; result->EA = 0; return; } } if (bp) { opline_ptr = &opline; init_op(opline_ptr TSRMLS_CC); } else { opline_ptr = get_next_op(CG(active_op_array) TSRMLS_CC); } opline_ptr->opcode = op; opline_ptr->result_type = IS_VAR; opline_ptr->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline_ptr->op1, varname); GET_NODE(result, opline_ptr->result); SET_UNUSED(opline_ptr->op2); opline_ptr->extended_value = ZEND_FETCH_LOCAL; if (varname->op_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline_ptr->op1.constant); if (zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC)) { opline_ptr->extended_value = ZEND_FETCH_GLOBAL; } } if (bp) { zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); zend_llist_add_element(fetch_list_ptr, opline_ptr); } } /* }}} */ void fetch_simple_variable(znode *result, znode *varname, int bp TSRMLS_DC) /* {{{ */ { /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ fetch_simple_variable_ex(result, varname, bp, ZEND_FETCH_W TSRMLS_CC); } /* }}} */ void zend_do_fetch_static_member(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { znode class_node; zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline_ptr; zend_op opline; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); } zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (result->op_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[result->u.op.var].name), CG(active_op_array)->vars[result->u.op.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } GET_NODE(result,opline.result); opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; opline_ptr = &opline; zend_llist_add_element(fetch_list_ptr, &opline); } else { le = fetch_list_ptr->head; opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode != ZEND_FETCH_W && opline_ptr->op1_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[opline_ptr->op1.var].name), CG(active_op_array)->vars[opline_ptr->op1.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; COPY_NODE(opline_ptr->op1, opline.result); zend_llist_prepend_element(fetch_list_ptr, &opline); } else { if (opline_ptr->op1_type == IS_CONST) { GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op1.constant); } if (class_node.op_type == IS_CONST) { opline_ptr->op2_type = IS_CONST; opline_ptr->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline_ptr->op2, &class_node); } opline_ptr->extended_value |= ZEND_FETCH_STATIC_MEMBER; } } } /* }}} */ void fetch_array_begin(znode *result, znode *varname, znode *first_dim TSRMLS_DC) /* {{{ */ { fetch_simple_variable(result, varname, 1 TSRMLS_CC); fetch_array_dim(result, result, first_dim TSRMLS_CC); } /* }}} */ void fetch_array_dim(znode *result, const znode *parent, const znode *dim TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (zend_is_function_or_method_call(parent)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, parent); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_DIM_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, parent); SET_NODE(opline.op2, dim); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline.op2.constant)), Z_STRLEN(CONSTANT(opline.op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline.op2.constant)); ZVAL_LONG(&CONSTANT(opline.op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline.op2.constant); } } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void fetch_string_offset(znode *result, const znode *parent, const znode *offset TSRMLS_DC) /* {{{ */ { fetch_array_dim(result, parent, offset TSRMLS_CC); } /* }}} */ void zend_do_print(znode *result, const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->opcode = ZEND_PRINT; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_echo(const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ECHO; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_abstract_method(const znode *function_name, znode *modifiers, const znode *body TSRMLS_DC) /* {{{ */ { char *method_type; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { Z_LVAL(modifiers->u.constant) |= ZEND_ACC_ABSTRACT; method_type = "Interface"; } else { method_type = "Abstract"; } if (modifiers->u.constant.value.lval & ZEND_ACC_ABSTRACT) { if(modifiers->u.constant.value.lval & ZEND_ACC_PRIVATE) { zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot be declared private", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } if (Z_LVAL(body->u.constant) == ZEND_ACC_ABSTRACT) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_RAISE_ABSTRACT_ERROR; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } else { /* we had code in the function body */ zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot contain body", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } else { if (body->u.constant.value.lval == ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Non-abstract method %s::%s() must contain body", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } } /* }}} */ static zend_bool opline_is_fetch_this(const zend_op *opline TSRMLS_DC) /* {{{ */ { if ((opline->opcode == ZEND_FETCH_W) && (opline->op1_type == IS_CONST) && (Z_TYPE(CONSTANT(opline->op1.constant)) == IS_STRING) && (Z_HASH_P(&CONSTANT(opline->op1.constant)) == THIS_HASHVAL) && (Z_STRLEN(CONSTANT(opline->op1.constant)) == (sizeof("this")-1)) && !memcmp(Z_STRVAL(CONSTANT(opline->op1.constant)), "this", sizeof("this"))) { return 1; } else { return 0; } } /* }}} */ void zend_do_assign(znode *result, znode *variable, znode *value TSRMLS_DC) /* {{{ */ { int last_op_number; zend_op *opline; if (value->op_type == IS_CV) { zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (fetch_list_ptr && fetch_list_ptr->head) { opline = (zend_op *)fetch_list_ptr->head->data; if (opline->opcode == ZEND_FETCH_DIM_W && opline->op1_type == IS_CV && opline->op1.var == value->u.op.var) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_R; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->op1_type = IS_CONST; LITERAL_STRINGL(opline->op1, CG(active_op_array)->vars[value->u.op.var].name, CG(active_op_array)->vars[value->u.op.var].name_len, 1); CALCULATE_LITERAL_HASH(opline->op1.constant); SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_LOCAL; GET_NODE(value, opline->result); } } } zend_do_end_variable_parse(variable, BP_VAR_W, 0 TSRMLS_CC); last_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (variable->op_type == IS_CV) { if (variable->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (variable->op_type == IS_VAR) { int n = 0; while (last_op_number - n > 0) { zend_op *last_op; last_op = &CG(active_op_array)->opcodes[last_op_number-n-1]; if (last_op->result_type == IS_VAR && last_op->result.var == variable->u.op.var) { if (last_op->opcode == ZEND_FETCH_OBJ_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, value TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (last_op->opcode == ZEND_FETCH_DIM_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ /* TBFixed: this can realloc opcodes, leaving last_op pointing wrong */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_DIM; zend_do_op_data(opline, value TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (opline_is_fetch_this(last_op TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } else { break; } } n++; } } opline->opcode = ZEND_ASSIGN; SET_NODE(opline->op1, variable); SET_NODE(opline->op2, value); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_assign_ref(znode *result, const znode *lvar, const znode *rvar TSRMLS_DC) /* {{{ */ { zend_op *opline; if (lvar->op_type == IS_CV) { if (lvar->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (lvar->op_type == IS_VAR) { int last_op_number = get_next_op_number(CG(active_op_array)); if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline_is_fetch_this(opline TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ASSIGN_REF; if (zend_is_function_or_method_call(rvar)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } else if (rvar->EA & ZEND_PARSED_NEW) { opline->extended_value = ZEND_RETURNS_NEW; } else { opline->extended_value = 0; } if (result) { opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } else { opline->result_type = IS_UNUSED | EXT_TYPE_UNUSED; } SET_NODE(opline->op1, lvar); SET_NODE(opline->op2, rvar); } /* }}} */ static inline void do_begin_loop(TSRMLS_D) /* {{{ */ { zend_brk_cont_element *brk_cont_element; int parent; parent = CG(context).current_brk_cont; CG(context).current_brk_cont = CG(active_op_array)->last_brk_cont; brk_cont_element = get_next_brk_cont_element(CG(active_op_array)); brk_cont_element->start = get_next_op_number(CG(active_op_array)); brk_cont_element->parent = parent; } /* }}} */ static inline void do_end_loop(int cont_addr, int has_loop_var TSRMLS_DC) /* {{{ */ { if (!has_loop_var) { /* The start fileld is used to free temporary variables in case of exceptions. * We won't try to free something of we don't have loop variable. */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].start = -1; } CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = cont_addr; CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; } /* }}} */ void zend_do_while_cond(const znode *expr, znode *close_bracket_token TSRMLS_DC) /* {{{ */ { int while_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, expr); close_bracket_token->u.op.opline_num = while_cond_op_number; SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_while_end(const znode *while_token, const znode *close_bracket_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* add unconditional jump */ opline->opcode = ZEND_JMP; opline->op1.opline_num = while_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* update while's conditional jmp */ CG(active_op_array)->opcodes[close_bracket_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); do_end_loop(while_token->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_cond(const znode *expr, znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { int for_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZNZ; SET_NODE(opline->op1, expr); /* the conditional expression */ second_semicolon_token->u.op.opline_num = for_cond_op_number; SET_UNUSED(opline->op2); } /* }}} */ void zend_do_for_before_statement(const znode *cond_start, const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = cond_start->u.op.opline_num; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_end(const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = second_semicolon_token->u.op.opline_num+1; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_end_loop(second_semicolon_token->u.op.opline_num+1, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_pre_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_PRE_INC)?ZEND_PRE_INC_OBJ:ZEND_PRE_DEC_OBJ; last_op->result_type = IS_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_post_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_POST_INC)?ZEND_POST_INC_OBJ:ZEND_POST_DEC_OBJ; last_op->result_type = IS_TMP_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_if_cond(const znode *cond, znode *closing_bracket_token TSRMLS_DC) /* {{{ */ { int if_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); closing_bracket_token->u.op.opline_num = if_cond_op_number; SET_UNUSED(opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_if_after_statement(const znode *closing_bracket_token, unsigned char initialize TSRMLS_DC) /* {{{ */ { int if_end_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; /* save for backpatching */ if (initialize) { zend_llist jmp_list; zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); } zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &if_end_op_number); CG(active_op_array)->opcodes[closing_bracket_token->u.op.opline_num].op2.opline_num = if_end_op_number+1; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_if_end(TSRMLS_D) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_llist *jmp_list_ptr; zend_llist_element *le; zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); for (le=jmp_list_ptr->head; le; le = le->next) { CG(active_op_array)->opcodes[*((int *) le->data)].op1.opline_num = next_op_number; } zend_llist_destroy(jmp_list_ptr); zend_stack_del_top(&CG(bp_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_check_writable_variable(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; if (type & ZEND_PARSED_METHOD_CALL) { zend_error(E_COMPILE_ERROR, "Can't use method return value in write context"); } if (type == ZEND_PARSED_FUNCTION_CALL) { zend_error(E_COMPILE_ERROR, "Can't use function return value in write context"); } } /* }}} */ void zend_do_begin_variable_parse(TSRMLS_D) /* {{{ */ { zend_llist fetch_list; zend_llist_init(&fetch_list, sizeof(zend_op), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &fetch_list, sizeof(zend_llist)); } /* }}} */ void zend_do_end_variable_parse(znode *variable, int type, int arg_offset TSRMLS_DC) /* {{{ */ { zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline = NULL; zend_op *opline_ptr; zend_uint this_var = -1; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); le = fetch_list_ptr->head; /* TODO: $foo->x->y->z = 1 should fetch "x" and "y" for R or RW, not just W */ if (le) { opline_ptr = (zend_op *)le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { /* convert to FETCH_?(this) into IS_CV */ if (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE) { this_var = opline_ptr->result.var; if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), Z_STRVAL(CONSTANT(opline_ptr->op1.constant)), Z_STRLEN(CONSTANT(opline_ptr->op1.constant)), Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC); Z_TYPE(CONSTANT(opline_ptr->op1.constant)) = IS_NULL; } else { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); } le = le->next; if (variable->op_type == IS_VAR && variable->u.op.var == this_var) { variable->op_type = IS_CV; variable->u.op.var = CG(active_op_array)->this_var; } } else if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } while (le) { opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode == ZEND_SEPARATE) { if (type != BP_VAR_R && type != BP_VAR_IS) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); } le = le->next; continue; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); if (opline->op1_type == IS_VAR && opline->op1.var == this_var) { opline->op1_type = IS_CV; opline->op1.var = CG(active_op_array)->this_var; } switch (type) { case BP_VAR_R: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode -= 3; break; case BP_VAR_W: break; case BP_VAR_RW: opline->opcode += 3; break; case BP_VAR_IS: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode += 6; /* 3+3 */ break; case BP_VAR_FUNC_ARG: opline->opcode += 9; /* 3+3+3 */ opline->extended_value |= arg_offset; break; case BP_VAR_UNSET: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for unsetting"); } opline->opcode += 12; /* 3+3+3+3 */ break; } le = le->next; } if (opline && type == BP_VAR_W && arg_offset) { opline->extended_value |= ZEND_FETCH_MAKE_REF; } } zend_llist_destroy(fetch_list_ptr); zend_stack_del_top(&CG(bp_stack)); } /* }}} */ void zend_do_add_string(znode *result, const znode *op1, znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline; if (Z_STRLEN(op2->u.constant) > 1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_STRING; } else if (Z_STRLEN(op2->u.constant) == 1) { int ch = *Z_STRVAL(op2->u.constant); /* Free memory and use ZEND_ADD_CHAR in case of 1 character strings */ efree(Z_STRVAL(op2->u.constant)); ZVAL_LONG(&op2->u.constant, ch); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_CHAR; } else { /* String can be empty after a variable at the end of a heredoc */ efree(Z_STRVAL(op2->u.constant)); return; } if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_add_variable(znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_VAR; if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_free(znode *op1 TSRMLS_DC) /* {{{ */ { if (op1->op_type==IS_TMP_VAR) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else if (op1->op_type==IS_VAR) { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; while (opline->opcode == ZEND_END_SILENCE || opline->opcode == ZEND_EXT_FCALL_END || opline->opcode == ZEND_OP_DATA) { opline--; } if (opline->result_type == IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_FETCH_R || opline->opcode == ZEND_FETCH_DIM_R || opline->opcode == ZEND_FETCH_OBJ_R || opline->opcode == ZEND_QM_ASSIGN_VAR) { /* It's very rare and useless case. It's better to use additional FREE opcode and simplify the FETCH handlers their selves */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else { opline->result_type |= EXT_TYPE_UNUSED; } } else { while (opline>CG(active_op_array)->opcodes) { if (opline->opcode == ZEND_FETCH_DIM_R && opline->op1_type == IS_VAR && opline->op1.var == op1->u.op.var) { /* This should the end of a list() construct * Mark its result as unused */ opline->extended_value = ZEND_FETCH_STANDARD; break; } else if (opline->result_type==IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_NEW) { opline->result_type |= EXT_TYPE_UNUSED; } break; } opline--; } } } else if (op1->op_type == IS_CONST) { zval_dtor(&op1->u.constant); } } /* }}} */ int zend_do_verify_access_types(const znode *current_access_type, const znode *new_modifier) /* {{{ */ { if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_PPP_MASK) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Multiple access type modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_ABSTRACT) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Multiple abstract modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_STATIC) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Multiple static modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_FINAL) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Multiple final modifiers are not allowed"); } if (((Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)) & (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) == (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Cannot use the final modifier on an abstract class member"); } return (Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)); } /* }}} */ void zend_do_begin_function_declaration(znode *function_token, znode *function_name, int is_method, int return_reference, znode *fn_flags_znode TSRMLS_DC) /* {{{ */ { zend_op_array op_array; char *name = function_name->u.constant.value.str.val; int name_len = function_name->u.constant.value.str.len; int function_begin_line = function_token->u.op.opline_num; zend_uint fn_flags; const char *lcname; zend_bool orig_interactive; ALLOCA_FLAG(use_heap) if (is_method) { if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((Z_LVAL(fn_flags_znode->u.constant) & ~(ZEND_ACC_STATIC|ZEND_ACC_PUBLIC))) { zend_error(E_COMPILE_ERROR, "Access type for interface method %s::%s() must be omitted", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } Z_LVAL(fn_flags_znode->u.constant) |= ZEND_ACC_ABSTRACT; /* propagates to the rest of the parser */ } fn_flags = Z_LVAL(fn_flags_znode->u.constant); /* must be done *after* the above check */ } else { fn_flags = 0; } if ((fn_flags & ZEND_ACC_STATIC) && (fn_flags & ZEND_ACC_ABSTRACT) && !(CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_STRICT, "Static function %s%s%s() should not be abstract", is_method ? CG(active_class_entry)->name : "", is_method ? "::" : "", Z_STRVAL(function_name->u.constant)); } function_token->u.op_array = CG(active_op_array); orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(&op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; op_array.function_name = name; if (return_reference) { op_array.fn_flags |= ZEND_ACC_RETURN_REFERENCE; } op_array.fn_flags |= fn_flags; op_array.scope = is_method?CG(active_class_entry):NULL; op_array.prototype = NULL; op_array.line_start = zend_get_compiled_lineno(TSRMLS_C); if (is_method) { int result; lcname = zend_new_interned_string(zend_str_tolower_dup(name, name_len), name_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lcname)) { result = zend_hash_quick_add(&CG(active_class_entry)->function_table, lcname, name_len+1, INTERNED_HASH(lcname), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } else { result = zend_hash_add(&CG(active_class_entry)->function_table, lcname, name_len+1, &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } if (result == FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::%s()", CG(active_class_entry)->name, name); } zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); if (fn_flags & ZEND_ACC_ABSTRACT) { CG(active_class_entry)->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (!(fn_flags & ZEND_ACC_PPP_MASK)) { fn_flags |= ZEND_ACC_PUBLIC; } if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } } } else { char *class_lcname; class_lcname = do_alloca(CG(active_class_entry)->name_length + 1, use_heap); zend_str_tolower_copy(class_lcname, CG(active_class_entry)->name, CG(active_class_entry)->name_length); /* Improve after RC: cache the lowercase class name */ if ((CG(active_class_entry)->name_length == name_len) && ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT) && (!memcmp(class_lcname, lcname, name_len))) { if (!CG(active_class_entry)->constructor) { CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } } else if ((name_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)))) { if (CG(active_class_entry)->constructor) { zend_error(E_STRICT, "Redefining already defined constructor for class %s", CG(active_class_entry)->name); } CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1))) { CG(active_class_entry)->destructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1))) { CG(active_class_entry)->clone = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } CG(active_class_entry)->__call = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } CG(active_class_entry)->__callstatic = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } CG(active_class_entry)->__get = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } CG(active_class_entry)->__set = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } CG(active_class_entry)->__unset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } CG(active_class_entry)->__isset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } CG(active_class_entry)->__tostring = (zend_function *) CG(active_op_array); } else if (!(fn_flags & ZEND_ACC_STATIC)) { CG(active_op_array)->fn_flags |= ZEND_ACC_ALLOW_STATIC; } free_alloca(class_lcname, use_heap); } str_efree(lcname); } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zval key; if (CG(current_namespace)) { /* Prefix function name with current namespcae name */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, function_name TSRMLS_CC); op_array.function_name = Z_STRVAL(tmp.u.constant); name_len = Z_STRLEN(tmp.u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), name_len); } else { lcname = zend_str_tolower_dup(name, name_len); } opline->opcode = ZEND_DECLARE_FUNCTION; opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, name_len TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; LITERAL_STRINGL(opline->op2, lcname, name_len, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); opline->extended_value = ZEND_DECLARE_FUNCTION; zend_hash_quick_update(CG(function_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); } if (CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_NOP; opline->lineno = function_begin_line; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } { /* Push a seperator to the switch and foreach stacks */ zend_switch_entry switch_entry; switch_entry.cond.op_type = IS_UNUSED; switch_entry.default_case = 0; switch_entry.control_var = 0; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); { /* Foreach stack separator */ zend_op dummy_opline; dummy_opline.result_type = IS_UNUSED; dummy_opline.op1_type = IS_UNUSED; zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); } } if (CG(doc_comment)) { CG(active_op_array)->doc_comment = CG(doc_comment); CG(active_op_array)->doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_begin_lambda_function_declaration(znode *result, znode *function_token, int return_reference, int is_static TSRMLS_DC) /* {{{ */ { znode function_name; zend_op_array *current_op_array = CG(active_op_array); int current_op_number = get_next_op_number(CG(active_op_array)); zend_op *current_op; function_name.op_type = IS_CONST; ZVAL_STRINGL(&function_name.u.constant, "{closure}", sizeof("{closure}")-1, 1); zend_do_begin_function_declaration(function_token, &function_name, 0, return_reference, NULL TSRMLS_CC); result->op_type = IS_TMP_VAR; result->u.op.var = get_temporary_variable(current_op_array); current_op = &current_op_array->opcodes[current_op_number]; current_op->opcode = ZEND_DECLARE_LAMBDA_FUNCTION; zend_del_literal(current_op_array, current_op->op2.constant); SET_UNUSED(current_op->op2); SET_NODE(current_op->result, result); if (is_static) { CG(active_op_array)->fn_flags |= ZEND_ACC_STATIC; } CG(active_op_array)->fn_flags |= ZEND_ACC_CLOSURE; } /* }}} */ void zend_do_handle_exception(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_HANDLE_EXCEPTION; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_function_declaration(const znode *function_token TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; zend_do_extended_info(TSRMLS_C); zend_do_return(NULL, 0 TSRMLS_CC); pass_two(CG(active_op_array) TSRMLS_CC); zend_release_labels(TSRMLS_C); if (CG(active_class_entry)) { zend_check_magic_method_implementation(CG(active_class_entry), (zend_function*)CG(active_op_array), E_COMPILE_ERROR TSRMLS_CC); } else { /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(CG(active_op_array)->function_name); zend_str_tolower_copy(lcname, CG(active_op_array)->function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME)) && CG(active_op_array)->num_args != 1) { zend_error(E_COMPILE_ERROR, "%s() must take exactly 1 argument", ZEND_AUTOLOAD_FUNC_NAME); } } CG(active_op_array)->line_end = zend_get_compiled_lineno(TSRMLS_C); CG(active_op_array) = function_token->u.op_array; /* Pop the switch and foreach seperators */ zend_stack_del_top(&CG(switch_cond_stack)); zend_stack_del_top(&CG(foreach_copy_stack)); } /* }}} */ void zend_do_receive_arg(zend_uchar op, znode *varname, const znode *offset, const znode *initialization, znode *class_type, zend_uchar pass_by_reference TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_arg_info *cur_arg_info; znode var; if (class_type->op_type == IS_CONST && Z_TYPE(class_type->u.constant) == IS_STRING && Z_STRLEN(class_type->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_type->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } if (zend_is_auto_global_quick(Z_STRVAL(varname->u.constant), Z_STRLEN(varname->u.constant), 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign auto-global variable %s", Z_STRVAL(varname->u.constant)); } else { var.op_type = IS_CV; var.u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(varname->u.constant) = (char*)CG(active_op_array)->vars[var.u.op.var].name; var.EA = 0; if (CG(active_op_array)->vars[var.u.op.var].hash_value == THIS_HASHVAL && Z_STRLEN(varname->u.constant) == sizeof("this")-1 && !memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this")-1)) { if (CG(active_op_array)->scope && (CG(active_op_array)->fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } CG(active_op_array)->this_var = var.u.op.var; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->num_args++; opline->opcode = op; SET_NODE(opline->result, &var); SET_NODE(opline->op1, offset); if (op == ZEND_RECV_INIT) { SET_NODE(opline->op2, initialization); } else { CG(active_op_array)->required_num_args = CG(active_op_array)->num_args; SET_UNUSED(opline->op2); } CG(active_op_array)->arg_info = erealloc(CG(active_op_array)->arg_info, sizeof(zend_arg_info)*(CG(active_op_array)->num_args)); cur_arg_info = &CG(active_op_array)->arg_info[CG(active_op_array)->num_args-1]; cur_arg_info->name = zend_new_interned_string(estrndup(varname->u.constant.value.str.val, varname->u.constant.value.str.len), varname->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->name_len = varname->u.constant.value.str.len; cur_arg_info->type_hint = 0; cur_arg_info->allow_null = 1; cur_arg_info->pass_by_reference = pass_by_reference; cur_arg_info->class_name = NULL; cur_arg_info->class_name_len = 0; if (class_type->op_type != IS_UNUSED) { cur_arg_info->allow_null = 0; if (class_type->u.constant.type != IS_NULL) { if (class_type->u.constant.type == IS_ARRAY) { cur_arg_info->type_hint = IS_ARRAY; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else if (Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Default value for parameters with array type hint can only be an array or NULL"); } } } else if (class_type->u.constant.type == IS_CALLABLE) { cur_arg_info->type_hint = IS_CALLABLE; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with callable type hint can only be NULL"); } } } else { cur_arg_info->type_hint = IS_OBJECT; if (ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_type->u.constant), Z_STRLEN(class_type->u.constant))) { zend_resolve_class_name(class_type, opline->extended_value, 1 TSRMLS_CC); } Z_STRVAL(class_type->u.constant) = (char*)zend_new_interned_string(class_type->u.constant.value.str.val, class_type->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->class_name = class_type->u.constant.value.str.val; cur_arg_info->class_name_len = class_type->u.constant.value.str.len; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with a class type hint can only be NULL"); } } } } } } /* }}} */ int zend_do_begin_function_call(znode *function_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { zend_function *function; char *lcname; char *is_compound = memchr(Z_STRVAL(function_name->u.constant), '\\', Z_STRLEN(function_name->u.constant)); zend_resolve_non_class_name(function_name, check_namespace TSRMLS_CC); if (check_namespace && CG(current_namespace) && !is_compound) { /* We assume we call function from the current namespace if it is not prefixed. */ /* In run-time PHP will check for function with full name and internal function with short name */ zend_do_begin_dynamic_function_call(function_name, 1 TSRMLS_CC); return 1; } lcname = zend_str_tolower_dup(function_name->u.constant.value.str.val, function_name->u.constant.value.str.len); if ((zend_hash_find(CG(function_table), lcname, function_name->u.constant.value.str.len+1, (void **) &function)==FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_FUNCTIONS) && (function->type == ZEND_INTERNAL_FUNCTION))) { zend_do_begin_dynamic_function_call(function_name, 0 TSRMLS_CC); efree(lcname); return 1; /* Dynamic */ } efree(function_name->u.constant.value.str.val); function_name->u.constant.value.str.val = lcname; zend_stack_push(&CG(function_call_stack), (void *) &function, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 0; } /* }}} */ void zend_do_begin_method_call(znode *left_bracket TSRMLS_DC) /* {{{ */ { zend_op *last_op; int last_op_number; unsigned char *ptr = NULL; zend_do_end_variable_parse(left_bracket, BP_VAR_R, 0 TSRMLS_CC); zend_do_begin_variable_parse(TSRMLS_C); last_op_number = get_next_op_number(CG(active_op_array))-1; last_op = &CG(active_op_array)->opcodes[last_op_number]; if ((last_op->op2_type == IS_CONST) && (Z_TYPE(CONSTANT(last_op->op2.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(last_op->op2.constant)) == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !zend_binary_strcasecmp(Z_STRVAL(CONSTANT(last_op->op2.constant)), Z_STRLEN(CONSTANT(last_op->op2.constant)), ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1)) { zend_error(E_COMPILE_ERROR, "Cannot call __clone() method on objects - use 'clone $obj' instead"); } if (last_op->opcode == ZEND_FETCH_OBJ_R) { if (last_op->op2_type == IS_CONST) { zval name; name = CONSTANT(last_op->op2.constant); if (!IS_INTERNED(Z_STRVAL(name))) { Z_STRVAL(name) = estrndup(Z_STRVAL(name), Z_STRLEN(name)); } FREE_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); last_op->op2.constant = zend_add_func_name_literal(CG(active_op_array), &name TSRMLS_CC); GET_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); } last_op->opcode = ZEND_INIT_METHOD_CALL; SET_UNUSED(last_op->result); Z_LVAL(left_bracket->u.constant) = ZEND_INIT_FCALL_BY_NAME; } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (left_bracket->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &left_bracket->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, left_bracket); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_do_clone(znode *result, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CLONE; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_begin_dynamic_function_call(znode *function_name, int ns_call TSRMLS_DC) /* {{{ */ { unsigned char *ptr = NULL; zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (ns_call) { /* In run-time PHP will check for function with full name and internal function with short name */ opline->opcode = ZEND_INIT_NS_FCALL_BY_NAME; SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_ns_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (function_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, function_name); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_resolve_non_class_name(znode *element_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; int len; zval **ns; char *lcname, *compound = memchr(Z_STRVAL(element_name->u.constant), '\\', Z_STRLEN(element_name->u.constant)); if (Z_STRVAL(element_name->u.constant)[0] == '\\') { /* name starts with \ so it is known and unambiguos, nothing to do here but shorten it */ memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+1, Z_STRLEN(element_name->u.constant)); --Z_STRLEN(element_name->u.constant); return; } if(!check_namespace) { return; } if (compound && CG(current_import)) { len = compound - Z_STRVAL(element_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(element_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(element_name->u.constant) -= len; memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+len, Z_STRLEN(element_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, element_name TSRMLS_CC); *element_name = tmp; efree(lcname); return; } efree(lcname); } if (CG(current_namespace)) { tmp = *element_name; Z_STRLEN(tmp.u.constant) = sizeof("\\")-1 + Z_STRLEN(element_name->u.constant) + Z_STRLEN_P(CG(current_namespace)); Z_STRVAL(tmp.u.constant) = (char *) emalloc(Z_STRLEN(tmp.u.constant)+1); memcpy(Z_STRVAL(tmp.u.constant), Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace))]), "\\", sizeof("\\")-1); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace)) + sizeof("\\")-1]), Z_STRVAL(element_name->u.constant), Z_STRLEN(element_name->u.constant)+1); STR_FREE(Z_STRVAL(element_name->u.constant)); *element_name = tmp; } } /* }}} */ void zend_resolve_class_name(znode *class_name, ulong fetch_type, int check_ns_name TSRMLS_DC) /* {{{ */ { char *compound; char *lcname; zval **ns; znode tmp; int len; compound = memchr(Z_STRVAL(class_name->u.constant), '\\', Z_STRLEN(class_name->u.constant)); if (compound) { /* This is a compound class name that contains namespace prefix */ if (Z_STRVAL(class_name->u.constant)[0] == '\\') { /* The STRING name has "\" prefix */ Z_STRLEN(class_name->u.constant) -= 1; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+1, Z_STRLEN(class_name->u.constant)+1); Z_STRVAL(class_name->u.constant) = erealloc( Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1); if (ZEND_FETCH_CLASS_DEFAULT != zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "'\\%s' is an invalid class name", Z_STRVAL(class_name->u.constant)); } } else { if (CG(current_import)) { len = compound - Z_STRVAL(class_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(class_name->u.constant) -= len; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+len, Z_STRLEN(class_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; efree(lcname); return; } efree(lcname); } /* Here name is not prefixed with \ and not imported */ if (CG(current_namespace)) { tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } } } else if (CG(current_import) || CG(current_namespace)) { /* this is a plain name (without \) */ lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns) == SUCCESS) { /* The given name is an import name. Substitute it. */ zval_dtor(&class_name->u.constant); class_name->u.constant = **ns; zval_copy_ctor(&class_name->u.constant); } else if (CG(current_namespace)) { /* plain name, no import - prepend current namespace to it */ tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } efree(lcname); } } /* }}} */ void zend_do_fetch_class(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { long fetch_class_op_number; zend_op *opline; if (class_name->op_type == IS_CONST && Z_TYPE(class_name->u.constant) == IS_STRING && Z_STRLEN(class_name->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_name->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } fetch_class_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CLASS; SET_UNUSED(opline->op1); opline->extended_value = ZEND_FETCH_CLASS_GLOBAL; CG(catch_begin) = fetch_class_op_number; if (class_name->op_type == IS_CONST) { int fetch_type; fetch_type = zend_get_class_fetch_type(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); switch (fetch_type) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: SET_UNUSED(opline->op2); opline->extended_value = fetch_type; zval_dtor(&class_name->u.constant); break; default: zend_resolve_class_name(class_name, opline->extended_value, 0 TSRMLS_CC); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_name->u.constant TSRMLS_CC); break; } } else { SET_NODE(opline->op2, class_name); } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; /* FIXME: Hack so that INIT_FCALL_BY_NAME still knows this is a class */ GET_NODE(result, opline->result); result->EA = opline->extended_value; } /* }}} */ void zend_do_label(znode *label TSRMLS_DC) /* {{{ */ { zend_label dest; if (!CG(context).labels) { ALLOC_HASHTABLE(CG(context).labels); zend_hash_init(CG(context).labels, 4, NULL, NULL, 0); } dest.brk_cont = CG(context).current_brk_cont; dest.opline_num = get_next_op_number(CG(active_op_array)); if (zend_hash_add(CG(context).labels, Z_STRVAL(label->u.constant), Z_STRLEN(label->u.constant) + 1, (void**)&dest, sizeof(zend_label), NULL) == FAILURE) { zend_error(E_COMPILE_ERROR, "Label '%s' already defined", Z_STRVAL(label->u.constant)); } /* Done with label now */ zval_dtor(&label->u.constant); } /* }}} */ void zend_resolve_goto_label(zend_op_array *op_array, zend_op *opline, int pass2 TSRMLS_DC) /* {{{ */ { zend_label *dest; long current, distance; zval *label; if (pass2) { label = opline->op2.zv; } else { label = &CONSTANT_EX(op_array, opline->op2.constant); } if (CG(context).labels == NULL || zend_hash_find(CG(context).labels, Z_STRVAL_P(label), Z_STRLEN_P(label)+1, (void**)&dest) == FAILURE) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; zend_error(E_COMPILE_ERROR, "'goto' to undefined label '%s'", Z_STRVAL_P(label)); } else { /* Label is not defined. Delay to pass 2. */ INC_BPC(op_array); return; } } opline->op1.opline_num = dest->opline_num; zval_dtor(label); Z_TYPE_P(label) = IS_NULL; /* Check that we are not moving into loop or switch */ current = opline->extended_value; for (distance = 0; current != dest->brk_cont; distance++) { if (current == -1) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; } zend_error(E_COMPILE_ERROR, "'goto' into loop or switch statement is disallowed"); } current = op_array->brk_cont_array[current].parent; } if (distance == 0) { /* Nothing to break out of, optimize to ZEND_JMP */ opline->opcode = ZEND_JMP; opline->extended_value = 0; SET_UNUSED(opline->op2); } else { /* Set real break distance */ ZVAL_LONG(label, distance); } if (pass2) { DEC_BPC(op_array); } } /* }}} */ void zend_do_goto(const znode *label TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_GOTO; opline->extended_value = CG(context).current_brk_cont; SET_UNUSED(opline->op1); SET_NODE(opline->op2, label); zend_resolve_goto_label(CG(active_op_array), opline, 0 TSRMLS_CC); } /* }}} */ void zend_release_labels(TSRMLS_D) /* {{{ */ { if (CG(context).labels) { zend_hash_destroy(CG(context).labels); FREE_HASHTABLE(CG(context).labels); } if (!zend_stack_is_empty(&CG(context_stack))) { zend_compiler_context *ctx; zend_stack_top(&CG(context_stack), (void**)&ctx); CG(context) = *ctx; zend_stack_del_top(&CG(context_stack)); } } /* }}} */ void zend_do_build_full_name(znode *result, znode *prefix, znode *name, int is_class_member TSRMLS_DC) /* {{{ */ { zend_uint length; if (!result) { result = prefix; } else { *result = *prefix; } if (is_class_member) { length = sizeof("::")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "::", sizeof("::")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("::")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } else { length = sizeof("\\")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "\\", sizeof("\\")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("\\")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } } /* }}} */ int zend_do_begin_class_member_function_call(znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { znode class_node; unsigned char *ptr = NULL; zend_op *opline; if (method_name->op_type == IS_CONST) { char *lcname = zend_str_tolower_dup(Z_STRVAL(method_name->u.constant), Z_STRLEN(method_name->u.constant)); if ((sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == Z_STRLEN(method_name->u.constant) && memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == 0) { zval_dtor(&method_name->u.constant); method_name->op_type = IS_UNUSED; } efree(lcname); } if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; opline = get_next_op(CG(active_op_array) TSRMLS_CC); } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->extended_value = class_node.EA ; } opline->opcode = ZEND_INIT_STATIC_METHOD_CALL; if (class_node.op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, &class_node); } if (method_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &method_name->u.constant TSRMLS_CC); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } } else { SET_NODE(opline->op2, method_name); } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 1; /* Dynamic */ } /* }}} */ void zend_do_end_function_call(znode *function_name, znode *result, const znode *argument_list, int is_method, int is_dynamic_fcall TSRMLS_DC) /* {{{ */ { zend_op *opline; if (is_method && function_name && function_name->op_type == IS_UNUSED) { /* clone */ if (Z_LVAL(argument_list->u.constant) != 0) { zend_error(E_WARNING, "Clone method does not require arguments"); } opline = &CG(active_op_array)->opcodes[Z_LVAL(function_name->u.constant)]; } else { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (!is_method && !is_dynamic_fcall && function_name->op_type==IS_CONST) { opline->opcode = ZEND_DO_FCALL; SET_NODE(opline->op1, function_name); CALCULATE_LITERAL_HASH(opline->op1.constant); GET_CACHE_SLOT(opline->op1.constant); } else { opline->opcode = ZEND_DO_FCALL_BY_NAME; SET_UNUSED(opline->op1); } } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(result, opline->result) ; SET_UNUSED(opline->op2); zend_stack_del_top(&CG(function_call_stack)); opline->extended_value = Z_LVAL(argument_list->u.constant); } /* }}} */ void zend_do_pass_param(znode *param, zend_uchar op, int offset TSRMLS_DC) /* {{{ */ { zend_op *opline; int original_op=op; zend_function **function_ptr_ptr, *function_ptr; int send_by_reference; int send_function = 0; zend_stack_top(&CG(function_call_stack), (void **) &function_ptr_ptr); function_ptr = *function_ptr_ptr; if (original_op == ZEND_SEND_REF) { if (function_ptr && function_ptr->common.function_name && function_ptr->common.type == ZEND_USER_FUNCTION && !ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed; " "If you would like to pass argument by reference, modify the declaration of %s().", function_ptr->common.function_name); } else { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed"); } return; } if (function_ptr) { if (ARG_MAY_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { if (param->op_type & (IS_VAR|IS_CV) && original_op != ZEND_SEND_VAL) { send_by_reference = 1; if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION | ZEND_ARG_SEND_SILENT; } } else { op = ZEND_SEND_VAL; send_by_reference = 0; } } else { send_by_reference = ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset) ? ZEND_ARG_SEND_BY_REF : 0; } } else { send_by_reference = 0; } if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION; } else if (op == ZEND_SEND_VAL && (param->op_type & (IS_VAR|IS_CV))) { op = ZEND_SEND_VAR_NO_REF; } if (op!=ZEND_SEND_VAR_NO_REF && send_by_reference==ZEND_ARG_SEND_BY_REF) { /* change to passing by reference */ switch (param->op_type) { case IS_VAR: case IS_CV: op = ZEND_SEND_REF; break; default: zend_error(E_COMPILE_ERROR, "Only variables can be passed by reference"); break; } } if (original_op == ZEND_SEND_VAR) { switch (op) { case ZEND_SEND_VAR_NO_REF: zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); break; case ZEND_SEND_VAR: if (function_ptr) { zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(param, BP_VAR_FUNC_ARG, offset TSRMLS_CC); } break; case ZEND_SEND_REF: zend_do_end_variable_parse(param, BP_VAR_W, 0 TSRMLS_CC); break; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (op == ZEND_SEND_VAR_NO_REF) { if (function_ptr) { opline->extended_value = ZEND_ARG_COMPILE_TIME_BOUND | send_by_reference | send_function; } else { opline->extended_value = send_function; } } else { if (function_ptr) { opline->extended_value = ZEND_DO_FCALL; } else { opline->extended_value = ZEND_DO_FCALL_BY_NAME; } } opline->opcode = op; SET_NODE(opline->op1, param); opline->op2.opline_num = offset; SET_UNUSED(opline->op2); } /* }}} */ static int generate_free_switch_expr(const zend_switch_entry *switch_entry TSRMLS_DC) /* {{{ */ { zend_op *opline; if (switch_entry->cond.op_type != IS_VAR && switch_entry->cond.op_type != IS_TMP_VAR) { return (switch_entry->cond.op_type == IS_UNUSED); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry->cond); SET_UNUSED(opline->op2); opline->extended_value = 0; return 0; } /* }}} */ static int generate_free_foreach_copy(const zend_op *foreach_copy TSRMLS_DC) /* {{{ */ { zend_op *opline; /* If we reach the seperator then stop applying the stack */ if (foreach_copy->result_type == IS_UNUSED && foreach_copy->op1_type == IS_UNUSED) { return 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->result_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->result); SET_UNUSED(opline->op2); opline->extended_value = 1; if (foreach_copy->op1_type != IS_UNUSED) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->op1_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->op1); SET_UNUSED(opline->op2); opline->extended_value = 0; } return 0; } /* }}} */ void zend_do_return(znode *expr, int do_end_vparse TSRMLS_DC) /* {{{ */ { zend_op *opline; int start_op_number, end_op_number; if (do_end_vparse) { if ((CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) && !zend_is_function_or_method_call(expr)) { zend_do_end_variable_parse(expr, BP_VAR_W, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(expr, BP_VAR_R, 0 TSRMLS_CC); } } start_op_number = get_next_op_number(CG(active_op_array)); #ifdef ZTS zend_stack_apply_with_argument(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_switch_expr TSRMLS_CC); zend_stack_apply_with_argument(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_foreach_copy TSRMLS_CC); #else zend_stack_apply(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_switch_expr); zend_stack_apply(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_foreach_copy); #endif end_op_number = get_next_op_number(CG(active_op_array)); while (start_op_number < end_op_number) { CG(active_op_array)->opcodes[start_op_number].extended_value |= EXT_TYPE_FREE_ON_RETURN; start_op_number++; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) ? ZEND_RETURN_BY_REF : ZEND_RETURN; if (expr) { SET_NODE(opline->op1, expr); if (do_end_vparse && zend_is_function_or_method_call(expr)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } } else { opline->op1_type = IS_CONST; LITERAL_NULL(opline->op1); } SET_UNUSED(opline->op2); } /* }}} */ static int zend_add_try_element(zend_uint try_op TSRMLS_DC) /* {{{ */ { int try_catch_offset = CG(active_op_array)->last_try_catch++; CG(active_op_array)->try_catch_array = erealloc(CG(active_op_array)->try_catch_array, sizeof(zend_try_catch_element)*CG(active_op_array)->last_try_catch); CG(active_op_array)->try_catch_array[try_catch_offset].try_op = try_op; return try_catch_offset; } /* }}} */ static void zend_add_catch_element(int offset, zend_uint catch_op TSRMLS_DC) /* {{{ */ { CG(active_op_array)->try_catch_array[offset].catch_op = catch_op; } /* }}} */ void zend_do_first_catch(znode *open_parentheses TSRMLS_DC) /* {{{ */ { open_parentheses->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_initialize_try_catch_element(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist jmp_list; zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); zend_add_catch_element(try_token->u.op.opline_num, get_next_op_number(CG(active_op_array)) TSRMLS_CC); } /* }}} */ void zend_do_mark_last_catch(const znode *first_catch, const znode *last_additional_catch TSRMLS_DC) /* {{{ */ { CG(active_op_array)->last--; zend_do_if_end(TSRMLS_C); if (last_additional_catch->u.op.opline_num == -1) { CG(active_op_array)->opcodes[first_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[first_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } else { CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_try(znode *try_token TSRMLS_DC) /* {{{ */ { try_token->u.op.opline_num = zend_add_try_element(get_next_op_number(CG(active_op_array)) TSRMLS_CC); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_catch(znode *try_token, znode *class_name, znode *catch_var, znode *first_catch TSRMLS_DC) /* {{{ */ { long catch_op_number; zend_op *opline; znode catch_class; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); catch_class = *class_name; } else { zend_error(E_COMPILE_ERROR, "Bad class name in the catch statement"); } catch_op_number = get_next_op_number(CG(active_op_array)); if (first_catch) { first_catch->u.op.opline_num = catch_op_number; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CATCH; opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &catch_class.u.constant TSRMLS_CC); opline->op2_type = IS_CV; opline->op2.var = lookup_cv(CG(active_op_array), catch_var->u.constant.value.str.val, catch_var->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(catch_var->u.constant) = (char*)CG(active_op_array)->vars[opline->op2.var].name; opline->result.num = 0; /* 1 means it's the last catch in the block */ try_token->u.op.opline_num = catch_op_number; } /* }}} */ void zend_do_end_catch(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); CG(active_op_array)->opcodes[try_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_throw(const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_THROW; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); } /* }}} */ ZEND_API void function_add_ref(zend_function *function) /* {{{ */ { if (function->type == ZEND_USER_FUNCTION) { zend_op_array *op_array = &function->op_array; (*op_array->refcount)++; if (op_array->static_variables) { HashTable *static_variables = op_array->static_variables; zval *tmp_zval; ALLOC_HASHTABLE(op_array->static_variables); zend_hash_init(op_array->static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(op_array->static_variables, static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_zval, sizeof(zval *)); } op_array->run_time_cache = NULL; } } /* }}} */ static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */ { zend_function *function; if (!ce->parent) { return; } /* You cannot change create_object */ ce->create_object = ce->parent->create_object; /* Inherit special functions if needed */ if (!ce->get_iterator) { ce->get_iterator = ce->parent->get_iterator; } if (!ce->iterator_funcs.funcs) { ce->iterator_funcs.funcs = ce->parent->iterator_funcs.funcs; } if (!ce->__get) { ce->__get = ce->parent->__get; } if (!ce->__set) { ce->__set = ce->parent->__set; } if (!ce->__unset) { ce->__unset = ce->parent->__unset; } if (!ce->__isset) { ce->__isset = ce->parent->__isset; } if (!ce->__call) { ce->__call = ce->parent->__call; } if (!ce->__callstatic) { ce->__callstatic = ce->parent->__callstatic; } if (!ce->__tostring) { ce->__tostring = ce->parent->__tostring; } if (!ce->clone) { ce->clone = ce->parent->clone; } if(!ce->serialize) { ce->serialize = ce->parent->serialize; } if(!ce->unserialize) { ce->unserialize = ce->parent->unserialize; } if (!ce->destructor) { ce->destructor = ce->parent->destructor; } if (ce->constructor) { if (ce->parent->constructor && ce->parent->constructor->common.fn_flags & ZEND_ACC_FINAL) { zend_error(E_ERROR, "Cannot override final %s::%s() with %s::%s()", ce->parent->name, ce->parent->constructor->common.function_name, ce->name, ce->constructor->common.function_name ); } return; } if (zend_hash_find(&ce->parent->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), (void **)&function)==SUCCESS) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), function, sizeof(zend_function), NULL); function_add_ref(function); } else { /* Don't inherit the old style constructor if we already have the new style constructor */ char *lc_class_name; char *lc_parent_class_name; lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); if (!zend_hash_exists(&ce->function_table, lc_class_name, ce->name_length+1)) { lc_parent_class_name = zend_str_tolower_dup(ce->parent->name, ce->parent->name_length); if (!zend_hash_exists(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1) && zend_hash_find(&ce->parent->function_table, lc_parent_class_name, ce->parent->name_length+1, (void **)&function)==SUCCESS) { if (function->common.fn_flags & ZEND_ACC_CTOR) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1, function, sizeof(zend_function), NULL); function_add_ref(function); } } efree(lc_parent_class_name); } efree(lc_class_name); } ce->constructor = ce->parent->constructor; } /* }}} */ char *zend_visibility_string(zend_uint fn_flags) /* {{{ */ { if (fn_flags & ZEND_ACC_PRIVATE) { return "private"; } if (fn_flags & ZEND_ACC_PROTECTED) { return "protected"; } if (fn_flags & ZEND_ACC_PUBLIC) { return "public"; } return ""; } /* }}} */ static void do_inherit_method(zend_function *function) /* {{{ */ { /* The class entry of the derived function intentionally remains the same * as that of the parent class. That allows us to know in which context * we're running, and handle private method calls properly. */ function_add_ref(function); } /* }}} */ static zend_bool zend_do_perform_implementation_check(const zend_function *fe, const zend_function *proto TSRMLS_DC) /* {{{ */ { zend_uint i; /* If it's a user function then arg_info == NULL means we don't have any parameters but * we still need to do the arg number checks. We are only willing to ignore this for internal * functions because extensions don't always define arg_info. */ if (!proto || (!proto->common.arg_info && proto->common.type != ZEND_USER_FUNCTION)) { return 1; } /* Checks for constructors only if they are declared in an interface, * or explicitly marked as abstract */ if ((fe->common.fn_flags & ZEND_ACC_CTOR) && ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)) { return 1; } /* check number of arguments */ if (proto->common.required_num_args < fe->common.required_num_args || proto->common.num_args > fe->common.num_args) { return 0; } if (fe->common.type != ZEND_USER_FUNCTION && (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) != 0 && (fe->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) == 0) { return 0; } /* by-ref constraints on return values are covariant */ if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) { return 0; } for (i=0; i < proto->common.num_args; i++) { if (ZEND_LOG_XOR(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)) { /* Only one has a type hint and the other one doesn't */ return 0; } if (fe->common.arg_info[i].class_name && strcasecmp(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)!=0) { const char *colon; if (fe->common.type != ZEND_USER_FUNCTION) { return 0; } else if (strchr(proto->common.arg_info[i].class_name, '\\') != NULL || (colon = zend_memrchr(fe->common.arg_info[i].class_name, '\\', fe->common.arg_info[i].class_name_len)) == NULL || strcasecmp(colon+1, proto->common.arg_info[i].class_name) != 0) { zend_class_entry **fe_ce, **proto_ce; int found, found2; found = zend_lookup_class(fe->common.arg_info[i].class_name, fe->common.arg_info[i].class_name_len, &fe_ce TSRMLS_CC); found2 = zend_lookup_class(proto->common.arg_info[i].class_name, proto->common.arg_info[i].class_name_len, &proto_ce TSRMLS_CC); /* Check for class alias */ if (found != SUCCESS || found2 != SUCCESS || (*fe_ce)->type == ZEND_INTERNAL_CLASS || (*proto_ce)->type == ZEND_INTERNAL_CLASS || *fe_ce != *proto_ce) { return 0; } } } if (fe->common.arg_info[i].type_hint != proto->common.arg_info[i].type_hint) { /* Incompatible type hint */ return 0; } /* by-ref constraints on arguments are invariant */ if (fe->common.arg_info[i].pass_by_reference != proto->common.arg_info[i].pass_by_reference) { return 0; } } if (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) { for (i=proto->common.num_args; i < fe->common.num_args; i++) { if (!fe->common.arg_info[i].pass_by_reference) { return 0; } } } return 1; } /* }}} */ #define REALLOC_BUF_IF_EXCEED(buf, offset, length, size) \ if (UNEXPECTED(offset - buf + size >= length)) { \ length += size + 1; \ buf = erealloc(buf, length); \ } static char * zend_get_function_declaration(zend_function *fptr TSRMLS_DC) /* {{{ */ { char *offset, *buf; zend_uint length = 1024; offset = buf = (char *)emalloc(length * sizeof(char)); if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { *(offset++) = '&'; *(offset++) = ' '; } if (fptr->common.scope) { memcpy(offset, fptr->common.scope->name, fptr->common.scope->name_length); offset += fptr->common.scope->name_length; *(offset++) = ':'; *(offset++) = ':'; } { size_t name_len = strlen(fptr->common.function_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, name_len); memcpy(offset, fptr->common.function_name, name_len); offset += name_len; } *(offset++) = '('; if (fptr->common.arg_info) { zend_uint i, required; zend_arg_info *arg_info = fptr->common.arg_info; required = fptr->common.required_num_args; for (i = 0; i < fptr->common.num_args;) { if (arg_info->class_name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->class_name_len); memcpy(offset, arg_info->class_name, arg_info->class_name_len); offset += arg_info->class_name_len; *(offset++) = ' '; } else if (arg_info->type_hint) { zend_uint type_name_len; char *type_name = zend_get_type_by_const(arg_info->type_hint); type_name_len = strlen(type_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, type_name_len); memcpy(offset, type_name, type_name_len); offset += type_name_len; *(offset++) = ' '; } if (arg_info->pass_by_reference) { *(offset++) = '&'; } *(offset++) = '$'; if (arg_info->name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->name_len); memcpy(offset, arg_info->name, arg_info->name_len); offset += arg_info->name_len; } else { zend_uint idx = i; memcpy(offset, "param", 5); offset += 5; do { *(offset++) = (char) (idx % 10) + '0'; idx /= 10; } while (idx > 0); } if (i >= required) { *(offset++) = ' '; *(offset++) = '='; *(offset++) = ' '; if (fptr->type == ZEND_USER_FUNCTION) { zend_op *precv = NULL; { zend_uint idx = i; zend_op *op = ((zend_op_array *)fptr)->opcodes; zend_op *end = op + ((zend_op_array *)fptr)->last; ++idx; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT) && op->op1.num == (long)idx) { precv = op; } ++op; } } if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) { zval *zv, zv_copy; int use_copy; ALLOC_ZVAL(zv); *zv = *precv->op2.zv; zval_copy_ctor(zv); INIT_PZVAL(zv); zval_update_constant_ex(&zv, (void*)1, fptr->common.scope TSRMLS_CC); if (Z_TYPE_P(zv) == IS_BOOL) { if (Z_LVAL_P(zv)) { memcpy(offset, "true", 4); offset += 4; } else { memcpy(offset, "false", 5); offset += 5; } } else if (Z_TYPE_P(zv) == IS_NULL) { memcpy(offset, "NULL", 4); offset += 4; } else if (Z_TYPE_P(zv) == IS_STRING) { *(offset++) = '\''; REALLOC_BUF_IF_EXCEED(buf, offset, length, MIN(Z_STRLEN_P(zv), 10)); memcpy(offset, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 10)); offset += MIN(Z_STRLEN_P(zv), 10); if (Z_STRLEN_P(zv) > 10) { *(offset++) = '.'; *(offset++) = '.'; *(offset++) = '.'; } *(offset++) = '\''; } else if (Z_TYPE_P(zv) == IS_ARRAY) { memcpy(offset, "Array", 5); offset += 5; } else { zend_make_printable_zval(zv, &zv_copy, &use_copy); REALLOC_BUF_IF_EXCEED(buf, offset, length, Z_STRLEN(zv_copy)); memcpy(offset, Z_STRVAL(zv_copy), Z_STRLEN(zv_copy)); offset += Z_STRLEN(zv_copy); if (use_copy) { zval_dtor(&zv_copy); } } zval_ptr_dtor(&zv); } } else { memcpy(offset, "NULL", 4); offset += 4; } } if (++i < fptr->common.num_args) { *(offset++) = ','; *(offset++) = ' '; } arg_info++; REALLOC_BUF_IF_EXCEED(buf, offset, length, 32); } } *(offset++) = ')'; *offset = '\0'; return buf; } /* }}} */ static void do_inheritance_check_on_method(zend_function *child, zend_function *parent TSRMLS_DC) /* {{{ */ { zend_uint child_flags; zend_uint parent_flags = parent->common.fn_flags; if (parent->common.fn_flags & ZEND_ACC_ABSTRACT && parent->common.scope != (child->common.prototype ? child->common.prototype->common.scope : child->common.scope) && child->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_IMPLEMENTED_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Can't inherit abstract function %s::%s() (previously declared abstract in %s)", parent->common.scope->name, child->common.function_name, child->common.prototype ? child->common.prototype->common.scope->name : child->common.scope->name); } if (parent_flags & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot override final method %s::%s()", ZEND_FN_SCOPE_NAME(parent), child->common.function_name); } child_flags = child->common.fn_flags; /* You cannot change from static to non static and vice versa. */ if ((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC)) { if (child->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot make non static method %s::%s() static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } else { zend_error(E_COMPILE_ERROR, "Cannot make static method %s::%s() non static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } } /* Disallow making an inherited method abstract. */ if ((child_flags & ZEND_ACC_ABSTRACT) && !(parent_flags & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Cannot make non abstract method %s::%s() abstract in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } if (parent_flags & ZEND_ACC_CHANGED) { child->common.fn_flags |= ZEND_ACC_CHANGED; } else { /* Prevent derived classes from restricting access that was available in parent classes */ if ((child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::%s() must be %s (as in class %s)%s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if (((child_flags & ZEND_ACC_PPP_MASK) < (parent_flags & ZEND_ACC_PPP_MASK)) && ((parent_flags & ZEND_ACC_PPP_MASK) & ZEND_ACC_PRIVATE)) { child->common.fn_flags |= ZEND_ACC_CHANGED; } } if (parent_flags & ZEND_ACC_PRIVATE) { child->common.prototype = NULL; } else if (parent_flags & ZEND_ACC_ABSTRACT) { child->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; child->common.prototype = parent; } else if (!(parent->common.fn_flags & ZEND_ACC_CTOR) || (parent->common.prototype && (parent->common.prototype->common.scope->ce_flags & ZEND_ACC_INTERFACE))) { /* ctors only have a prototype if it comes from an interface */ child->common.prototype = parent->common.prototype ? parent->common.prototype : parent; } if (child->common.prototype && (child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { if (!zend_do_perform_implementation_check(child, child->common.prototype TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s::%s() must be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_get_function_declaration(child->common.prototype TSRMLS_CC)); } } else if (EG(error_reporting) & E_STRICT || EG(user_error_handler)) { /* Check E_STRICT (or custom error handler) before the check so that we save some time */ if (!zend_do_perform_implementation_check(child, parent TSRMLS_CC)) { char *method_prototype = zend_get_function_declaration(child->common.prototype TSRMLS_CC); zend_error(E_STRICT, "Declaration of %s::%s() should be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, method_prototype); efree(method_prototype); } } } /* }}} */ static zend_bool do_inherit_method_check(HashTable *child_function_table, zend_function *parent, const zend_hash_key *hash_key, zend_class_entry *child_ce) /* {{{ */ { zend_uint parent_flags = parent->common.fn_flags; zend_function *child; TSRMLS_FETCH(); if (zend_hash_quick_find(child_function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child)==FAILURE) { if (parent_flags & (ZEND_ACC_ABSTRACT)) { child_ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } return 1; /* method doesn't exist in child, copy from parent */ } do_inheritance_check_on_method(child, parent TSRMLS_CC); return 0; } /* }}} */ static zend_bool do_inherit_property_access_check(HashTable *target_ht, zend_property_info *parent_info, const zend_hash_key *hash_key, zend_class_entry *ce) /* {{{ */ { zend_property_info *child_info; zend_class_entry *parent_ce = ce->parent; if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW)) { if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { child_info->flags |= ZEND_ACC_CHANGED; } else { zend_hash_quick_update(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, parent_info, sizeof(zend_property_info), (void **) &child_info); if(ce->type & ZEND_INTERNAL_CLASS) { zend_duplicate_property_info_internal(child_info); } else { zend_duplicate_property_info(child_info); } child_info->flags &= ~ZEND_ACC_PRIVATE; /* it's not private anymore */ child_info->flags |= ZEND_ACC_SHADOW; /* but it's a shadow of private */ } return 0; /* don't copy access information to child */ } if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { if ((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s", (parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", parent_ce->name, hash_key->arKey, (child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ce->name, hash_key->arKey); } if(parent_info->flags & ZEND_ACC_CHANGED) { child_info->flags |= ZEND_ACC_CHANGED; } if ((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ce->name, hash_key->arKey, zend_visibility_string(parent_info->flags), parent_ce->name, (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if ((child_info->flags & ZEND_ACC_STATIC) == 0) { Z_DELREF_P(ce->default_properties_table[parent_info->offset]); ce->default_properties_table[parent_info->offset] = ce->default_properties_table[child_info->offset]; ce->default_properties_table[child_info->offset] = NULL; child_info->offset = parent_info->offset; } return 0; /* Don't copy from parent */ } else { return 1; /* Copy from parent */ } } /* }}} */ static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce TSRMLS_CC) == FAILURE) { zend_error(E_CORE_ERROR, "Class %s could not implement interface %s", ce->name, iface->name); } if (ce == iface) { zend_error(E_ERROR, "Interface %s cannot implement itself", ce->name); } } /* }}} */ ZEND_API void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface TSRMLS_DC) /* {{{ */ { /* expects interface to be contained in ce's interface list already */ zend_uint i, ce_num, if_num = iface->num_interfaces; zend_class_entry *entry; if (if_num==0) { return; } ce_num = ce->num_interfaces; if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } /* Inherit the interfaces, only if they're not already inherited by the class */ while (if_num--) { entry = iface->interfaces[if_num]; for (i = 0; i < ce_num; i++) { if (ce->interfaces[i] == entry) { break; } } if (i == ce_num) { ce->interfaces[ce->num_interfaces++] = entry; } } /* and now call the implementing handlers */ while (ce_num < ce->num_interfaces) { do_implement_interface(ce, ce->interfaces[ce_num++] TSRMLS_CC); } } /* }}} */ #ifdef ZTS static void zval_internal_ctor(zval **p) /* {{{ */ { zval *orig_ptr = *p; ALLOC_ZVAL(*p); MAKE_COPY_ZVAL(&orig_ptr, *p); } /* }}} */ # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) (((parent_ce)->type != (ce)->type) ? zval_internal_ctor : zval_add_ref)) #else # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) zval_add_ref) #endif ZEND_API void zend_do_inheritance(zend_class_entry *ce, zend_class_entry *parent_ce TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; if ((ce->ce_flags & ZEND_ACC_INTERFACE) && !(parent_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ce->name, parent_ce->name); } if (parent_ce->ce_flags & ZEND_ACC_FINAL_CLASS) { zend_error(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ce->name, parent_ce->name); } ce->parent = parent_ce; /* Copy serialize/unserialize callbacks */ if (!ce->serialize) { ce->serialize = parent_ce->serialize; } if (!ce->unserialize) { ce->unserialize = parent_ce->unserialize; } /* Inherit interfaces */ zend_do_inherit_interfaces(ce, parent_ce TSRMLS_CC); /* Inherit properties */ if (parent_ce->default_properties_count) { int i = ce->default_properties_count + parent_ce->default_properties_count; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_properties_count) { while (i-- > parent_ce->default_properties_count) { ce->default_properties_table[i] = ce->default_properties_table[i - parent_ce->default_properties_count]; } } for (i = 0; i < parent_ce->default_properties_count; i++) { ce->default_properties_table[i] = parent_ce->default_properties_table[i]; if (ce->default_properties_table[i]) { #ifdef ZTS if (parent_ce->type != ce->type) { zval *p; ALLOC_ZVAL(p); MAKE_COPY_ZVAL(&ce->default_properties_table[i], p); ce->default_properties_table[i] = p; } else { Z_ADDREF_P(ce->default_properties_table[i]); } #else Z_ADDREF_P(ce->default_properties_table[i]); #endif } } ce->default_properties_count += parent_ce->default_properties_count; } if (parent_ce->type != ce->type) { /* User class extends internal class */ zend_update_class_constants(parent_ce TSRMLS_CC); if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = erealloc(ce->default_static_members_table, sizeof(void*) * i); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&CE_STATIC_MEMBERS(parent_ce)[i]); ce->default_static_members_table[i] = CE_STATIC_MEMBERS(parent_ce)[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; ce->static_members_table = ce->default_static_members_table; } } else { if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&parent_ce->default_static_members_table[i]); ce->default_static_members_table[i] = parent_ce->default_static_members_table[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } } for (zend_hash_internal_pointer_reset(&ce->properties_info); zend_hash_get_current_data(&ce->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->properties_info)) { if (property_info->ce == ce) { if (property_info->flags & ZEND_ACC_STATIC) { property_info->offset += parent_ce->default_static_members_count; } else { property_info->offset += parent_ce->default_properties_count; } } } zend_hash_merge_ex(&ce->properties_info, &parent_ce->properties_info, (copy_ctor_func_t) (ce->type & ZEND_INTERNAL_CLASS ? zend_duplicate_property_info_internal : zend_duplicate_property_info), sizeof(zend_property_info), (merge_checker_func_t) do_inherit_property_access_check, ce); zend_hash_merge(&ce->constants_table, &parent_ce->constants_table, zval_property_ctor(parent_ce, ce), NULL, sizeof(zval *), 0); zend_hash_merge_ex(&ce->function_table, &parent_ce->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_inherit_parent_constructor(ce); if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS && ce->type == ZEND_INTERNAL_CLASS) { ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } else if (!(ce->ce_flags & ZEND_ACC_IMPLEMENT_INTERFACES) && !(ce->ce_flags & ZEND_ACC_IMPLEMENT_TRAITS)) { /* The verification will be done in runtime by ZEND_VERIFY_ABSTRACT_CLASS */ zend_verify_abstract_class(ce TSRMLS_CC); } ce->ce_flags |= parent_ce->ce_flags & ZEND_HAS_STATIC_IN_METHODS; } /* }}} */ static zend_bool do_inherit_constant_check(HashTable *child_constants_table, const zval **parent_constant, const zend_hash_key *hash_key, const zend_class_entry *iface) /* {{{ */ { zval **old_constant; if (zend_hash_quick_find(child_constants_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**)&old_constant) == SUCCESS) { if (*old_constant != *parent_constant) { zend_error(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", hash_key->arKey, iface->name); } return 0; } return 1; } /* }}} */ static int do_interface_constant_check(zval **val TSRMLS_DC, int num_args, va_list args, const zend_hash_key *key) /* {{{ */ { zend_class_entry **iface = va_arg(args, zend_class_entry**); do_inherit_constant_check(&(*iface)->constants_table, (const zval **) val, key, *iface); return ZEND_HASH_APPLY_KEEP; } /* }}} */ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_iface_num = ce->num_interfaces; zend_uint parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0; for (i = 0; i < ce->num_interfaces; i++) { if (ce->interfaces[i] == NULL) { memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i)); i--; } else if (ce->interfaces[i] == iface) { if (i < parent_iface_num) { ignore = 1; } else { zend_error(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ce->name, iface->name); } } } if (ignore) { /* Check for attempt to redeclare interface constants */ zend_hash_apply_with_arguments(&ce->constants_table TSRMLS_CC, (apply_func_args_t) do_interface_constant_check, 1, &iface); } else { if (ce->num_interfaces >= current_iface_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } } ce->interfaces[ce->num_interfaces++] = iface; zend_hash_merge_ex(&ce->constants_table, &iface->constants_table, (copy_ctor_func_t) zval_add_ref, sizeof(zval *), (merge_checker_func_t) do_inherit_constant_check, iface); zend_hash_merge_ex(&ce->function_table, &iface->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_implement_interface(ce, iface TSRMLS_CC); zend_do_inherit_interfaces(ce, iface TSRMLS_CC); } } /* }}} */ ZEND_API void zend_do_implement_trait(zend_class_entry *ce, zend_class_entry *trait TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_trait_num = ce->num_traits; zend_uint parent_trait_num = ce->parent ? ce->parent->num_traits : 0; for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == NULL) { memmove(ce->traits + i, ce->traits + i + 1, sizeof(zend_class_entry*) * (--ce->num_traits - i)); i--; } else if (ce->traits[i] == trait) { if (i < parent_trait_num) { ignore = 1; } } } if (!ignore) { if (ce->num_traits >= current_trait_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->traits = (zend_class_entry **) realloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } else { ce->traits = (zend_class_entry **) erealloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } } ce->traits[ce->num_traits++] = trait; } } /* }}} */ static int zend_traits_merge_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { size_t current; size_t i; size_t count; HashTable* resulting_table; HashTable** function_tables; zend_class_entry *ce; size_t collision = 0; size_t abstract_solved = 0; zend_function* other_trait_fn; current = va_arg(args, size_t); /* index of current trait */ count = va_arg(args, size_t); resulting_table = va_arg(args, HashTable*); function_tables = va_arg(args, HashTable**); ce = va_arg(args, zend_class_entry*); for (i = 0; i < count; i++) { if (i == current) { continue; /* just skip this, cause its the table this function is applied on */ } if (zend_hash_quick_find(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&other_trait_fn) == SUCCESS) { /* if it is an abstract method, there is no collision */ if (other_trait_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible */ do_inheritance_check_on_method(fn, other_trait_fn TSRMLS_CC); /* we can savely free and remove it from other table */ zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } else { /* if it is not an abstract method, there is still no collision */ /* if fn is an abstract method */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible */ do_inheritance_check_on_method(other_trait_fn, fn TSRMLS_CC); /* just mark as solved, will be added if its own trait is processed */ abstract_solved = 1; } else { /* but else, we have a collision of non-abstract methods */ collision++; zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } } } if (collision) { zend_function* class_fn; /* make sure method is not already overridden in class */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&class_fn) == FAILURE || class_fn->common.scope != ce) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because there are collisions with other trait methods on %s", fn->common.function_name, ce->name); } zend_function_dtor(fn); } else if (abstract_solved) { zend_function_dtor(fn); } else { /* Add it to result function table */ if (zend_hash_quick_add(resulting_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, fn, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating resulting trait method table", fn->common.function_name); } } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ /* {{{ Originates from php_runkit_function_copy_ctor Duplicate structures in an op_array where necessary to make an outright duplicate */ static void zend_traits_duplicate_function(zend_function *fe, zend_class_entry *target_ce, char *newname TSRMLS_DC) { zend_literal *literals_copy; zend_compiled_variable *dupvars; zend_op *opcode_copy; zval class_name_zv; int class_name_literal; int i; int number_of_literals; if (fe->op_array.static_variables) { HashTable *tmpHash; ALLOC_HASHTABLE(tmpHash); zend_hash_init(tmpHash, zend_hash_num_elements(fe->op_array.static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_apply_with_arguments(fe->op_array.static_variables TSRMLS_CC, (apply_func_args_t)zval_copy_static_var, 1, tmpHash); fe->op_array.static_variables = tmpHash; } number_of_literals = fe->op_array.last_literal; literals_copy = (zend_literal*)emalloc(number_of_literals * sizeof(zend_literal)); for (i = 0; i < number_of_literals; i++) { literals_copy[i] = fe->op_array.literals[i]; zval_copy_ctor(&literals_copy[i].constant); } fe->op_array.literals = literals_copy; fe->op_array.refcount = emalloc(sizeof(zend_uint)); *(fe->op_array.refcount) = 1; if (fe->op_array.vars) { i = fe->op_array.last_var; dupvars = safe_emalloc(fe->op_array.last_var, sizeof(zend_compiled_variable), 0); while (i > 0) { i--; dupvars[i].name = estrndup(fe->op_array.vars[i].name, fe->op_array.vars[i].name_len); dupvars[i].name_len = fe->op_array.vars[i].name_len; dupvars[i].hash_value = fe->op_array.vars[i].hash_value; } fe->op_array.vars = dupvars; } else { fe->op_array.vars = NULL; } opcode_copy = safe_emalloc(sizeof(zend_op), fe->op_array.last, 0); for(i = 0; i < fe->op_array.last; i++) { opcode_copy[i] = fe->op_array.opcodes[i]; if (opcode_copy[i].op1_type != IS_CONST) { switch (opcode_copy[i].opcode) { case ZEND_GOTO: case ZEND_JMP: if (opcode_copy[i].op1.jmp_addr && opcode_copy[i].op1.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op1.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op1.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op1.jmp_addr - fe->op_array.opcodes); } break; } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op1.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op1.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op1.zv = &fe->op_array.literals[class_name_literal].constant; } } if (opcode_copy[i].op2_type != IS_CONST) { switch (opcode_copy[i].opcode) { case ZEND_JMPZ: case ZEND_JMPNZ: case ZEND_JMPZ_EX: case ZEND_JMPNZ_EX: case ZEND_JMP_SET: case ZEND_JMP_SET_VAR: if (opcode_copy[i].op2.jmp_addr && opcode_copy[i].op2.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op2.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op2.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op2.jmp_addr - fe->op_array.opcodes); } break; } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op2.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op2.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op2.zv = &fe->op_array.literals[class_name_literal].constant; } } } fe->op_array.opcodes = opcode_copy; fe->op_array.function_name = newname; /* was setting it to fe which does not work since fe is stack allocated and not a stable address */ /* fe->op_array.prototype = fe->op_array.prototype; */ if (fe->op_array.arg_info) { zend_arg_info *tmpArginfo; tmpArginfo = safe_emalloc(sizeof(zend_arg_info), fe->op_array.num_args, 0); for(i = 0; i < fe->op_array.num_args; i++) { tmpArginfo[i] = fe->op_array.arg_info[i]; tmpArginfo[i].name = estrndup(tmpArginfo[i].name, tmpArginfo[i].name_len); if (tmpArginfo[i].class_name) { tmpArginfo[i].class_name = estrndup(tmpArginfo[i].class_name, tmpArginfo[i].class_name_len); } } fe->op_array.arg_info = tmpArginfo; } fe->op_array.doc_comment = estrndup(fe->op_array.doc_comment, fe->op_array.doc_comment_len); fe->op_array.try_catch_array = (zend_try_catch_element*)estrndup((char*)fe->op_array.try_catch_array, sizeof(zend_try_catch_element) * fe->op_array.last_try_catch); fe->op_array.brk_cont_array = (zend_brk_cont_element*)estrndup((char*)fe->op_array.brk_cont_array, sizeof(zend_brk_cont_element) * fe->op_array.last_brk_cont); } /* }}} */ static void zend_add_magic_methods(zend_class_entry* ce, const char* mname, uint mname_len, zend_function* fe TSRMLS_DC) /* {{{ */ { if (!strncmp(mname, ZEND_CLONE_FUNC_NAME, mname_len)) { ce->clone = fe; fe->common.fn_flags |= ZEND_ACC_CLONE; } else if (!strncmp(mname, ZEND_CONSTRUCTOR_FUNC_NAME, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } else if (!strncmp(mname, ZEND_DESTRUCTOR_FUNC_NAME, mname_len)) { ce->destructor = fe; fe->common.fn_flags |= ZEND_ACC_DTOR; } else if (!strncmp(mname, ZEND_GET_FUNC_NAME, mname_len)) ce->__get = fe; else if (!strncmp(mname, ZEND_SET_FUNC_NAME, mname_len)) ce->__set = fe; else if (!strncmp(mname, ZEND_CALL_FUNC_NAME, mname_len)) ce->__call = fe; else if (!strncmp(mname, ZEND_UNSET_FUNC_NAME, mname_len)) ce->__unset = fe; else if (!strncmp(mname, ZEND_ISSET_FUNC_NAME, mname_len)) ce->__isset = fe; else if (!strncmp(mname, ZEND_CALLSTATIC_FUNC_NAME, mname_len)) ce->__callstatic= fe; else if (!strncmp(mname, ZEND_TOSTRING_FUNC_NAME, mname_len)) ce->__tostring = fe; else if (ce->name_length + 1 == mname_len) { char *lowercase_name = emalloc(ce->name_length + 1); zend_str_tolower_copy(lowercase_name, ce->name, ce->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, ce->name_length + 1, 1 TSRMLS_CC); if (!memcmp(mname, lowercase_name, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } str_efree(lowercase_name); } } /* }}} */ static int zend_traits_merge_functions_to_class(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zend_class_entry *ce = va_arg(args, zend_class_entry*); int add = 0; zend_function* existing_fn = NULL; zend_function fn_copy, *fn_copy_p; zend_function* prototype = NULL; /* is used to determine the prototype according to the inheritance chain */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &existing_fn) == FAILURE) { add = 1; /* not found */ } else if (existing_fn->common.scope != ce) { add = 1; /* or inherited from other class or interface */ } if (add) { zend_function* parent_function; if (ce->parent && zend_hash_quick_find(&ce->parent->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &parent_function) != FAILURE) { prototype = parent_function; /* ->common.fn_flags |= ZEND_ACC_ABSTRACT; */ /* we got that method in the parent class, and are going to override it, except, if the trait is just asking to have an abstract method implemented. */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* then we clean up an skip this method */ zend_function_dtor(fn); return ZEND_HASH_APPLY_REMOVE; } } fn->common.scope = ce; fn->common.prototype = prototype; if (prototype && (prototype->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT || prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { fn->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; } else if (fn->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT) { /* remove ZEND_ACC_IMPLEMENTED_ABSTRACT flag, think it shouldn't be copied to class */ fn->common.fn_flags = fn->common.fn_flags - ZEND_ACC_IMPLEMENTED_ABSTRACT; } /* check whether the trait method fullfills the inheritance requirements */ if (prototype) { do_inheritance_check_on_method(fn, prototype TSRMLS_CC); } /* one more thing: make sure we properly implement an abstract method */ if (existing_fn && existing_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { do_inheritance_check_on_method(fn, existing_fn TSRMLS_CC); } /* delete inherited fn if the function to be added is not abstract */ if (existing_fn && existing_fn->common.scope != ce && (fn->common.fn_flags & ZEND_ACC_ABSTRACT) == 0) { /* it is just a reference which was added to the subclass while doing the inheritance, so we can deleted now, and will add the overriding method afterwards. Except, if we try to add an abstract function, then we should not delete the inherited one */ zend_hash_quick_del(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h); } if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (fn->op_array.static_variables) { ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, ce, estrdup(fn->common.function_name) TSRMLS_CC); if (zend_hash_quick_update(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, &fn_copy, sizeof(zend_function), (void**)&fn_copy_p)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating class method table", hash_key->arKey); } zend_add_magic_methods(ce, hash_key->arKey, hash_key->nKeyLength, fn_copy_p TSRMLS_CC); zend_function_dtor(fn); } else { zend_function_dtor(fn); } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ static int zend_traits_copy_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { HashTable* target; zend_class_entry *target_ce; zend_trait_alias** aliases; HashTable* exclude_table; char* lcname; unsigned int fnname_len; zend_function fn_copy; void* dummy; size_t i = 0; target = va_arg(args, HashTable*); target_ce = va_arg(args, zend_class_entry*); aliases = va_arg(args, zend_trait_alias**); exclude_table = va_arg(args, HashTable*); fnname_len = strlen(fn->common.function_name); /* apply aliases which are qualified with a class name, there should not be any ambiguity */ if (aliases) { while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias != NULL && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && aliases[i]->trait_method->mname_len == fnname_len && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(aliases[i]->alias, aliases[i]->alias_len) TSRMLS_CC); /* if it is 0, no modifieres has been changed */ if (aliases[i]->modifiers) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } lcname = zend_str_tolower_dup(aliases[i]->alias, aliases[i]->alias_len); if (zend_hash_add(target, lcname, aliases[i]->alias_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add aliased trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } efree(lcname); } i++; } } lcname = zend_str_tolower_dup(fn->common.function_name, fnname_len); if (exclude_table == NULL || zend_hash_find(exclude_table, lcname, fnname_len, &dummy) == FAILURE) { /* is not in hashtable, thus, function is not to be excluded */ fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(fn->common.function_name, fnname_len) TSRMLS_CC); /* apply aliases which are not qualified by a class name, or which have not * alias name, just setting visibility */ if (aliases) { i = 0; while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias == NULL && aliases[i]->modifiers != 0 && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && (aliases[i]->trait_method->mname_len == fnname_len) && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } i++; } } if (zend_hash_add(target, lcname, fnname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } } efree(lcname); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* Copies function table entries to target function table with applied aliasing */ static void zend_traits_copy_trait_function_table(HashTable *target, zend_class_entry *target_ce, HashTable *source, zend_trait_alias** aliases, HashTable* exclude_table TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_arguments(source TSRMLS_CC, (apply_func_args_t)zend_traits_copy_functions, 4, target, target_ce, aliases, exclude_table); } /* }}} */ static void zend_traits_init_trait_structures(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i, j = 0; zend_trait_precedence *cur_precedence; zend_trait_method_reference *cur_method_ref; /* resolve class references */ if (ce->trait_precedences) { i = 0; while ((cur_precedence = ce->trait_precedences[i])) { if (cur_precedence->exclude_from_classes) { cur_precedence->trait_method->ce = zend_fetch_class(cur_precedence->trait_method->class_name, cur_precedence->trait_method->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); j = 0; while (cur_precedence->exclude_from_classes[j]) { char* class_name = (char*)cur_precedence->exclude_from_classes[j]; zend_uint name_length = strlen(class_name); cur_precedence->exclude_from_classes[j] = zend_fetch_class(class_name, name_length, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); efree(class_name); j++; } } i++; } } if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { if (ce->trait_aliases[i]->trait_method->class_name) { cur_method_ref = ce->trait_aliases[i]->trait_method; cur_method_ref->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); } i++; } } } /* }}} */ static void zend_traits_compile_exclude_table(HashTable* exclude_table, zend_trait_precedence **precedences, zend_class_entry *trait) /* {{{ */ { size_t i = 0, j; if (!precedences) { return; } while (precedences[i]) { if (precedences[i]->exclude_from_classes) { j = 0; while (precedences[i]->exclude_from_classes[j]) { if (precedences[i]->exclude_from_classes[j] == trait) { zend_uint lcname_len = precedences[i]->trait_method->mname_len; char *lcname = zend_str_tolower_dup(precedences[i]->trait_method->method_name, lcname_len); if (zend_hash_add(exclude_table, lcname, lcname_len, NULL, 0, NULL) == FAILURE) { efree(lcname); zend_error(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", precedences[i]->trait_method->method_name, trait->name); } efree(lcname); } ++j; } } ++i; } } /* }}} */ static void zend_do_traits_method_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { HashTable** function_tables; HashTable* resulting_table; HashTable exclude_table; size_t i; /* prepare copies of trait function tables for combination */ function_tables = malloc(sizeof(HashTable*) * ce->num_traits); resulting_table = (HashTable *) malloc(sizeof(HashTable)); /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(resulting_table, 10, NULL, NULL, 1, 0); for (i = 0; i < ce->num_traits; i++) { function_tables[i] = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(function_tables[i], ce->traits[i]->function_table.nNumOfElements, NULL, NULL, 1, 0); if (ce->trait_precedences) { /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(&exclude_table, 2, NULL, NULL, 0, 0); zend_traits_compile_exclude_table(&exclude_table, ce->trait_precedences, ce->traits[i]); /* copies functions, applies defined aliasing, and excludes unused trait methods */ zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, &exclude_table TSRMLS_CC); zend_hash_graceful_destroy(&exclude_table); } else { zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, NULL TSRMLS_CC); } } /* now merge trait methods */ for (i = 0; i < ce->num_traits; i++) { zend_hash_apply_with_arguments(function_tables[i] TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions, 5, i, ce->num_traits, resulting_table, function_tables, ce); } /* Now the resulting_table contains all trait methods we would have to * add to the class in the following step the methods are inserted into the method table * if there is already a method with the same name it is replaced iff ce != fn.scope * --> all inherited methods are overridden, methods defined in the class are left untouched */ zend_hash_apply_with_arguments(resulting_table TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions_to_class, 1, ce); /* free temporary function tables */ for (i = 0; i < ce->num_traits; i++) { /* zend_hash_destroy(function_tables[i]); */ zend_hash_graceful_destroy(function_tables[i]); free(function_tables[i]); } free(function_tables); /* free temporary resulting table */ /* zend_hash_destroy(resulting_table); */ zend_hash_graceful_destroy(resulting_table); free(resulting_table); } /* }}} */ static zend_class_entry* find_first_definition(zend_class_entry *ce, size_t current_trait, const char* prop_name, int prop_name_length, ulong prop_hash, zend_class_entry *coliding_ce) /* {{{ */ { size_t i; zend_property_info *coliding_prop; for (i = 0; (i < current_trait) && (i < ce->num_traits); i++) { if (zend_hash_quick_find(&ce->traits[i]->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS) { return ce->traits[i]; } } return coliding_ce; } /* }}} */ static void zend_do_traits_property_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i; zend_property_info *property_info; zend_property_info *coliding_prop; zval compare_result; const char* prop_name; int prop_name_length; ulong prop_hash; const char* class_name_unused; zend_bool prop_found; zend_bool not_compatible; zval* prop_value; /* In the following steps the properties are inserted into the property table * for that, a very strict approach is applied: * - check for compatibility, if not compatible with any property in class -> fatal * - if compatible, then strict notice */ for (i = 0; i < ce->num_traits; i++) { for (zend_hash_internal_pointer_reset(&ce->traits[i]->properties_info); zend_hash_get_current_data(&ce->traits[i]->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->traits[i]->properties_info)) { /* first get the unmangeld name if necessary, * then check whether the property is already there */ if ((property_info->flags & ZEND_ACC_PPP_MASK) == ZEND_ACC_PUBLIC) { prop_hash = property_info->h; prop_name = property_info->name; prop_name_length = property_info->name_length; prop_found = zend_hash_quick_find(&ce->properties_info, property_info->name, property_info->name_length+1, property_info->h, (void **) &coliding_prop) == SUCCESS; } else { /* for private and protected we need to unmangle the names */ zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name_unused, &prop_name); prop_name_length = strlen(prop_name); prop_hash = zend_get_hash_value(prop_name, prop_name_length + 1); prop_found = zend_hash_quick_find(&ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS; } /* next: check for conflicts with current class */ if (prop_found) { if (coliding_prop->flags & ZEND_ACC_SHADOW) { /* this one is inherited, lets look it up in its own class */ zend_hash_quick_find(&coliding_prop->ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop); } if ((coliding_prop->flags & ZEND_ACC_PPP_MASK) == (property_info->flags & ZEND_ACC_PPP_MASK)) { /* flags are identical, now the value needs to be checked */ if (property_info->flags & ZEND_ACC_STATIC) { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_static_members_table[coliding_prop->offset], ce->traits[i]->default_static_members_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } else { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_properties_table[coliding_prop->offset], ce->traits[i]->default_properties_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } } else { /* the flags are not identical, thus, we assume properties are not compatible */ not_compatible = 1; } if (not_compatible) { zend_error(E_COMPILE_ERROR, "%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } else { zend_error(E_STRICT, "%s and %s define the same property ($%s) in the composition of %s. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } } /* property not found, so lets add it */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); zend_declare_property_ex(ce, prop_name, prop_name_length, prop_value, property_info->flags, property_info->doc_comment, property_info->doc_comment_len TSRMLS_CC); } } } /* }}} */ ZEND_API void zend_do_bind_traits(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { if (ce->num_traits <= 0) { return; } /* complete initialization of trait strutures in ce */ zend_traits_init_trait_structures(ce TSRMLS_CC); /* first care about all methods to be flattened into the class */ zend_do_traits_method_binding(ce TSRMLS_CC); /* then flatten the properties into it, to, mostly to notfiy developer about problems */ zend_do_traits_property_binding(ce TSRMLS_CC); /* verify that all abstract methods from traits have been implemented */ zend_verify_abstract_class(ce TSRMLS_CC); /* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */ if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { ce->ce_flags -= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } } /* }}} */ ZEND_API int do_bind_function(const zend_op_array *op_array, zend_op *opline, HashTable *function_table, zend_bool compile_time) /* {{{ */ { zend_function *function; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } zend_hash_quick_find(function_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void *) &function); if (zend_hash_quick_add(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), function, sizeof(zend_function), NULL)==FAILURE) { int error_level = compile_time ? E_COMPILE_ERROR : E_ERROR; zend_function *old_function; if (zend_hash_quick_find(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), (void *) &old_function)==SUCCESS && old_function->type == ZEND_USER_FUNCTION && old_function->op_array.last > 0) { zend_error(error_level, "Cannot redeclare %s() (previously declared in %s:%d)", function->common.function_name, old_function->op_array.filename, old_function->op_array.opcodes[0].lineno); } else { zend_error(error_level, "Cannot redeclare %s()", function->common.function_name); } return FAILURE; } else { (*function->op_array.refcount)++; function->op_array.static_variables = NULL; /* NULL out the unbound function */ return SUCCESS; } } /* }}} */ void zend_add_trait_precedence(znode *precedence_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_precedences, precedence_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_add_trait_alias(znode *alias_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_aliases, alias_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_prepare_reference(znode *result, znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { zend_trait_method_reference *method_ref = emalloc(sizeof(zend_trait_method_reference)); method_ref->ce = NULL; /* REM: There should not be a need for copying, zend_do_begin_class_declaration is also just using that string */ if (class_name) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); method_ref->class_name = Z_STRVAL(class_name->u.constant); method_ref->cname_len = Z_STRLEN(class_name->u.constant); } else { method_ref->class_name = NULL; method_ref->cname_len = 0; } method_ref->method_name = Z_STRVAL(method_name->u.constant); method_ref->mname_len = Z_STRLEN(method_name->u.constant); result->u.op.ptr = method_ref; result->op_type = IS_TMP_VAR; } /* }}} */ void zend_prepare_trait_alias(znode *result, znode *method_reference, znode *modifiers, znode *alias TSRMLS_DC) /* {{{ */ { zend_trait_alias *trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_alias->modifiers = Z_LVAL(modifiers->u.constant); if (Z_LVAL(modifiers->u.constant) == ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot use 'static' as method modifier"); return; } if (alias) { trait_alias->alias = Z_STRVAL(alias->u.constant); trait_alias->alias_len = Z_STRLEN(alias->u.constant); } else { trait_alias->alias = NULL; } trait_alias->function = NULL; result->u.op.ptr = trait_alias; } /* }}} */ void zend_prepare_trait_precedence(znode *result, znode *method_reference, znode *trait_list TSRMLS_DC) /* {{{ */ { zend_trait_precedence *trait_precedence = emalloc(sizeof(zend_trait_precedence)); trait_precedence->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_precedence->exclude_from_classes = (zend_class_entry**) trait_list->u.op.ptr; trait_precedence->function = NULL; result->u.op.ptr = trait_precedence; } /* }}} */ ZEND_API zend_class_entry *do_bind_class(const zend_op_array* op_array, const zend_op *opline, HashTable *class_table, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } if (zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce)==FAILURE) { zend_error(E_COMPILE_ERROR, "Internal Zend error - Missing class information for %s", Z_STRVAL_P(op1)); return NULL; } else { ce = *pce; } ce->refcount++; if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), &ce, sizeof(zend_class_entry *), NULL)==FAILURE) { ce->refcount--; if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return NULL; } else { if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLEMENT_INTERFACES))) { zend_verify_abstract_class(ce TSRMLS_CC); } return ce; } } /* }}} */ ZEND_API zend_class_entry *do_bind_inherited_class(const zend_op_array *op_array, const zend_op *opline, HashTable *class_table, zend_class_entry *parent_ce, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; int found_ce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } found_ce = zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce); if (found_ce == FAILURE) { if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", Z_STRVAL_P(op2)); } return NULL; } else { ce = *pce; } if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ce->name, parent_ce->name); } else if ((parent_ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ce->name, parent_ce->name); } zend_do_inheritance(ce, parent_ce TSRMLS_CC); ce->refcount++; /* Register the derived class */ if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), pce, sizeof(zend_class_entry *), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return ce; } /* }}} */ void zend_do_early_binding(TSRMLS_D) /* {{{ */ { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; HashTable *table; while (opline->opcode == ZEND_TICKS && opline > CG(active_op_array)->opcodes) { opline--; } switch (opline->opcode) { case ZEND_DECLARE_FUNCTION: if (do_bind_function(CG(active_op_array), opline, CG(function_table), 1) == FAILURE) { return; } table = CG(function_table); break; case ZEND_DECLARE_CLASS: if (do_bind_class(CG(active_op_array), opline, CG(class_table), 1 TSRMLS_CC) == NULL) { return; } table = CG(class_table); break; case ZEND_DECLARE_INHERITED_CLASS: { zend_op *fetch_class_opline = opline-1; zval *parent_name; zend_class_entry **pce; parent_name = &CONSTANT(fetch_class_opline->op2.constant); if ((zend_lookup_class(Z_STRVAL_P(parent_name), Z_STRLEN_P(parent_name), &pce TSRMLS_CC) == FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_CLASSES) && ((*pce)->type == ZEND_INTERNAL_CLASS))) { if (CG(compiler_options) & ZEND_COMPILE_DELAYED_BINDING) { zend_uint *opline_num = &CG(active_op_array)->early_binding; while (*opline_num != -1) { opline_num = &CG(active_op_array)->opcodes[*opline_num].result.opline_num; } *opline_num = opline - CG(active_op_array)->opcodes; opline->opcode = ZEND_DECLARE_INHERITED_CLASS_DELAYED; opline->result_type = IS_UNUSED; opline->result.opline_num = -1; } return; } if (do_bind_inherited_class(CG(active_op_array), opline, CG(class_table), *pce, 1 TSRMLS_CC) == NULL) { return; } /* clear unnecessary ZEND_FETCH_CLASS opcode */ zend_del_literal(CG(active_op_array), fetch_class_opline->op2.constant); MAKE_NOP(fetch_class_opline); table = CG(class_table); break; } case ZEND_VERIFY_ABSTRACT_CLASS: case ZEND_ADD_INTERFACE: case ZEND_ADD_TRAIT: case ZEND_BIND_TRAITS: /* We currently don't early-bind classes that implement interfaces */ /* Classes with traits are handled exactly the same, no early-bind here */ return; default: zend_error(E_COMPILE_ERROR, "Invalid binding type"); return; } zend_hash_quick_del(table, Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant)), Z_HASH_P(&CONSTANT(opline->op1.constant))); zend_del_literal(CG(active_op_array), opline->op1.constant); zend_del_literal(CG(active_op_array), opline->op2.constant); MAKE_NOP(opline); } /* }}} */ ZEND_API void zend_do_delayed_early_binding(const zend_op_array *op_array TSRMLS_DC) /* {{{ */ { if (op_array->early_binding != -1) { zend_bool orig_in_compilation = CG(in_compilation); zend_uint opline_num = op_array->early_binding; zend_class_entry **pce; CG(in_compilation) = 1; while (opline_num != -1) { if (zend_lookup_class(Z_STRVAL_P(op_array->opcodes[opline_num-1].op2.zv), Z_STRLEN_P(op_array->opcodes[opline_num-1].op2.zv), &pce TSRMLS_CC) == SUCCESS) { do_bind_inherited_class(op_array, &op_array->opcodes[opline_num], EG(class_table), *pce, 0 TSRMLS_CC); } opline_num = op_array->opcodes[opline_num].result.opline_num; } CG(in_compilation) = orig_in_compilation; } } /* }}} */ void zend_do_boolean_or_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_or_end(znode *result, const znode *expr1, const znode *expr2, znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_boolean_and_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_and_end(znode *result, const znode *expr1, const znode *expr2, const znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_do_while_begin(TSRMLS_D) /* {{{ */ { do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_do_while_end(const znode *do_token, const znode *expr_open_bracket, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ; SET_NODE(opline->op1, expr); opline->op2.opline_num = do_token->u.op.opline_num; SET_UNUSED(opline->op2); do_end_loop(expr_open_bracket->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_brk_cont(zend_uchar op, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->op1.opline_num = CG(context).current_brk_cont; SET_UNUSED(opline->op1); if (expr) { if (expr->op_type != IS_CONST) { zend_error(E_COMPILE_ERROR, "'%s' operator with non-constant operand is no longer supported", op == ZEND_BRK ? "break" : "continue"); } else if (Z_TYPE(expr->u.constant) != IS_LONG || Z_LVAL(expr->u.constant) < 1) { zend_error(E_COMPILE_ERROR, "'%s' operator accepts only positive numbers", op == ZEND_BRK ? "break" : "continue"); } SET_NODE(opline->op2, expr); } else { LITERAL_LONG(opline->op2, 1); opline->op2_type = IS_CONST; } } /* }}} */ void zend_do_switch_cond(const znode *cond TSRMLS_DC) /* {{{ */ { zend_switch_entry switch_entry; switch_entry.cond = *cond; switch_entry.default_case = -1; switch_entry.control_var = -1; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_switch_end(const znode *case_list TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); /* add code to jmp to default case */ if (switch_entry_ptr->default_case != -1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->op1.opline_num = switch_entry_ptr->default_case; } if (case_list->op_type != IS_UNUSED) { /* non-empty switch */ int next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* remember break/continue loop information */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; if (switch_entry_ptr->cond.op_type==IS_VAR || switch_entry_ptr->cond.op_type==IS_TMP_VAR) { /* emit free for the switch condition*/ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry_ptr->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_UNUSED(opline->op2); } if (switch_entry_ptr->cond.op_type == IS_CONST) { zval_dtor(&switch_entry_ptr->cond.u.constant); } zend_stack_del_top(&CG(switch_cond_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_case_before_statement(const znode *case_list, znode *case_token, const znode *case_expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); int next_op_number; zend_switch_entry *switch_entry_ptr; znode result; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); if (switch_entry_ptr->control_var == -1) { switch_entry_ptr->control_var = get_temporary_variable(CG(active_op_array)); } opline->opcode = ZEND_CASE; opline->result.var = switch_entry_ptr->control_var; opline->result_type = IS_TMP_VAR; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_NODE(opline->op2, case_expr); if (opline->op1_type == IS_CONST) { zval_copy_ctor(&CONSTANT(opline->op1.constant)); } GET_NODE(&result, opline->result); next_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, &result); SET_UNUSED(opline->op2); case_token->u.op.opline_num = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_case_after_statement(znode *result, const znode *case_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); result->u.op.opline_num = next_op_number; switch (CG(active_op_array)->opcodes[case_token->u.op.opline_num].opcode) { case ZEND_JMP: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); break; case ZEND_JMPZ: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); break; } } /* }}} */ void zend_do_default_before_statement(const znode *case_list, znode *default_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); default_token->u.op.opline_num = next_op_number; next_op_number = get_next_op_number(CG(active_op_array)); switch_entry_ptr->default_case = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_begin_class_declaration(const znode *class_token, znode *class_name, const znode *parent_class_name TSRMLS_DC) /* {{{ */ { zend_op *opline; int doing_inheritance = 0; zend_class_entry *new_class_entry; char *lcname; int error = 0; zval **ns_name, key; if (CG(active_class_entry)) { zend_error(E_COMPILE_ERROR, "Class declarations may not be nested"); return; } lcname = zend_str_tolower_dup(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); if (!(strcmp(lcname, "self") && strcmp(lcname, "parent"))) { efree(lcname); zend_error(E_COMPILE_ERROR, "Cannot use '%s' as class name as it is reserved", Z_STRVAL(class_name->u.constant)); } /* Class name must not conflict with import names */ if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns_name) == SUCCESS) { error = 1; } if (CG(current_namespace)) { /* Prefix class name with name of current namespace */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); class_name = &tmp; efree(lcname); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); } if (error) { char *tmp = zend_str_tolower_dup(Z_STRVAL_PP(ns_name), Z_STRLEN_PP(ns_name)); if (Z_STRLEN_PP(ns_name) != Z_STRLEN(class_name->u.constant) || memcmp(tmp, lcname, Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "Cannot declare class %s because the name is already in use", Z_STRVAL(class_name->u.constant)); } efree(tmp); } new_class_entry = emalloc(sizeof(zend_class_entry)); new_class_entry->type = ZEND_USER_CLASS; new_class_entry->name = zend_new_interned_string(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1, 1 TSRMLS_CC); new_class_entry->name_length = Z_STRLEN(class_name->u.constant); zend_initialize_class_data(new_class_entry, 1 TSRMLS_CC); new_class_entry->info.user.filename = zend_get_compiled_filename(TSRMLS_C); new_class_entry->info.user.line_start = class_token->u.op.opline_num; new_class_entry->ce_flags |= class_token->EA; if (parent_class_name && parent_class_name->op_type != IS_UNUSED) { switch (parent_class_name->EA) { case ZEND_FETCH_CLASS_SELF: zend_error(E_COMPILE_ERROR, "Cannot use 'self' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_PARENT: zend_error(E_COMPILE_ERROR, "Cannot use 'parent' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use 'static' as class name as it is reserved"); break; default: break; } doing_inheritance = 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, new_class_entry->name_length TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; if (doing_inheritance) { /* Make sure a trait does not try to extend a class */ if ((new_class_entry->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "A trait (%s) cannot extend a class", new_class_entry->name); } opline->extended_value = parent_class_name->u.op.var; opline->opcode = ZEND_DECLARE_INHERITED_CLASS; } else { opline->opcode = ZEND_DECLARE_CLASS; } LITERAL_STRINGL(opline->op2, lcname, new_class_entry->name_length, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); zend_hash_quick_update(CG(class_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &new_class_entry, sizeof(zend_class_entry *), NULL); CG(active_class_entry) = new_class_entry; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(&CG(implementing_class), opline->result); if (CG(doc_comment)) { CG(active_class_entry)->info.user.doc_comment = CG(doc_comment); CG(active_class_entry)->info.user.doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ static void do_verify_abstract_class(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_VERIFY_ABSTRACT_CLASS; SET_NODE(opline->op1, &CG(implementing_class)); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_class_declaration(const znode *class_token, const znode *parent_token TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); if (ce->constructor) { ce->constructor->common.fn_flags |= ZEND_ACC_CTOR; if (ce->constructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Constructor %s::%s() cannot be static", ce->name, ce->constructor->common.function_name); } } if (ce->destructor) { ce->destructor->common.fn_flags |= ZEND_ACC_DTOR; if (ce->destructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Destructor %s::%s() cannot be static", ce->name, ce->destructor->common.function_name); } } if (ce->clone) { ce->clone->common.fn_flags |= ZEND_ACC_CLONE; if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static", ce->name, ce->clone->common.function_name); } } ce->info.user.line_end = zend_get_compiled_lineno(TSRMLS_C); /* Check for traits and proceed like with interfaces. * The only difference will be a combined handling of them in the end. * Thus, we need another opcode here. */ if (ce->num_traits > 0) { zend_op *opline; ce->traits = NULL; ce->num_traits = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_TRAITS; /* opcode generation: */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BIND_TRAITS; SET_NODE(opline->op1, &CG(implementing_class)); } if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) && ((parent_token->op_type != IS_UNUSED) || (ce->num_interfaces > 0))) { zend_verify_abstract_class(ce TSRMLS_CC); if (ce->num_interfaces) { do_verify_abstract_class(TSRMLS_C); } } /* Inherit interfaces; reset number to zero, we need it for above check and * will restore it during actual implementation. * The ZEND_ACC_IMPLEMENT_INTERFACES flag disables double call to * zend_verify_abstract_class() */ if (ce->num_interfaces > 0) { ce->interfaces = NULL; ce->num_interfaces = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_INTERFACES; } CG(active_class_entry) = NULL; } /* }}} */ void zend_do_implements_interface(znode *interface_name TSRMLS_DC) /* {{{ */ { zend_op *opline; /* Traits can not implement interfaces */ if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface on '%s' since it is a Trait", Z_STRVAL(interface_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(interface_name->u.constant), Z_STRLEN(interface_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface name as it is reserved", Z_STRVAL(interface_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_INTERFACE; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(interface_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = (opline->extended_value & ~ZEND_FETCH_CLASS_MASK) | ZEND_FETCH_CLASS_INTERFACE; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &interface_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_interfaces++; } /* }}} */ void zend_do_implements_trait(znode *trait_name TSRMLS_DC) /* {{{ */ { zend_op *opline; if ((CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Cannot use traits inside of interfaces. %s is used in %s", Z_STRVAL(trait_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(trait_name->u.constant), Z_STRLEN(trait_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as trait name as it is reserved", Z_STRVAL(trait_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_TRAIT; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(trait_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = ZEND_FETCH_CLASS_TRAIT; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &trait_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_traits++; } /* }}} */ ZEND_API void zend_mangle_property_name(char **dest, int *dest_length, const char *src1, int src1_length, const char *src2, int src2_length, int internal) /* {{{ */ { char *prop_name; int prop_name_length; prop_name_length = 1 + src1_length + 1 + src2_length; prop_name = pemalloc(prop_name_length + 1, internal); prop_name[0] = '\0'; memcpy(prop_name + 1, src1, src1_length+1); memcpy(prop_name + 1 + src1_length + 1, src2, src2_length+1); *dest = prop_name; *dest_length = prop_name_length; } /* }}} */ static int zend_strnlen(const char* s, int maxlen) /* {{{ */ { int len = 0; while (*s++ && maxlen--) len++; return len; } /* }}} */ ZEND_API int zend_unmangle_property_name(const char *mangled_property, int len, const char **class_name, const char **prop_name) /* {{{ */ { int class_name_len; *class_name = NULL; if (mangled_property[0]!=0) { *prop_name = mangled_property; return SUCCESS; } if (len < 3 || mangled_property[1]==0) { zend_error(E_NOTICE, "Illegal member variable name"); *prop_name = mangled_property; return FAILURE; } class_name_len = zend_strnlen(mangled_property+1, --len - 1) + 1; if (class_name_len >= len || mangled_property[class_name_len]!=0) { zend_error(E_NOTICE, "Corrupt member variable name"); *prop_name = mangled_property; return FAILURE; } *class_name = mangled_property+1; *prop_name = (*class_name)+class_name_len; return SUCCESS; } /* }}} */ void zend_do_declare_property(const znode *var_name, const znode *value, zend_uint access_type TSRMLS_DC) /* {{{ */ { zval *property; zend_property_info *existing_property_info; char *comment = NULL; int comment_len = 0; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Interfaces may not include member variables"); } if (access_type & ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Properties cannot be declared abstract"); } if (access_type & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot declare property %s::$%s final, the final modifier is allowed only for methods and classes", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } if (zend_hash_find(&CG(active_class_entry)->properties_info, var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, (void **) &existing_property_info)==SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::$%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } ALLOC_ZVAL(property); if (value) { *property = value->u.constant; } else { INIT_PZVAL(property); Z_TYPE_P(property) = IS_NULL; } if (CG(doc_comment)) { comment = CG(doc_comment); comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } zend_declare_property_ex(CG(active_class_entry), zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len + 1, 0 TSRMLS_CC), var_name->u.constant.value.str.len, property, access_type, comment, comment_len TSRMLS_CC); efree(var_name->u.constant.value.str.val); } /* }}} */ void zend_do_declare_class_constant(znode *var_name, const znode *value TSRMLS_DC) /* {{{ */ { zval *property; const char *cname = NULL; int result; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed in class constants"); return; } if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Traits cannot have constants"); return; } ALLOC_ZVAL(property); *property = value->u.constant; cname = zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, 0 TSRMLS_CC); if (IS_INTERNED(cname)) { result = zend_hash_quick_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, INTERNED_HASH(cname), &property, sizeof(zval *), NULL); } else { result = zend_hash_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, &property, sizeof(zval *), NULL); } if (result == FAILURE) { FREE_ZVAL(property); zend_error(E_COMPILE_ERROR, "Cannot redefine class constant %s::%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } FREE_PNODE(var_name); if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_fetch_property(znode *result, znode *object, const znode *property TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (object->op_type == IS_CV) { if (object->u.op.var == CG(active_op_array)->this_var) { object->op_type = IS_UNUSED; /* this means $this for objects */ } } else if (fetch_list_ptr->count == 1) { zend_llist_element *le = fetch_list_ptr->head; zend_op *opline_ptr = (zend_op *) le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); SET_UNUSED(opline_ptr->op1); /* this means $this for objects */ SET_NODE(opline_ptr->op2, property); /* if it was usual fetch, we change it to object fetch */ switch (opline_ptr->opcode) { case ZEND_FETCH_W: opline_ptr->opcode = ZEND_FETCH_OBJ_W; break; case ZEND_FETCH_R: opline_ptr->opcode = ZEND_FETCH_OBJ_R; break; case ZEND_FETCH_RW: opline_ptr->opcode = ZEND_FETCH_OBJ_RW; break; case ZEND_FETCH_IS: opline_ptr->opcode = ZEND_FETCH_OBJ_IS; break; case ZEND_FETCH_UNSET: opline_ptr->opcode = ZEND_FETCH_OBJ_UNSET; break; case ZEND_FETCH_FUNC_ARG: opline_ptr->opcode = ZEND_FETCH_OBJ_FUNC_ARG; break; } if (opline_ptr->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline_ptr->op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline_ptr->op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op2.constant); } GET_NODE(result, opline_ptr->result); return; } } if (zend_is_function_or_method_call(object)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, object); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_OBJ_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, object); SET_NODE(opline.op2, property); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline.op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op2.constant); } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void zend_do_halt_compiler_register(TSRMLS_D) /* {{{ */ { char *name, *cfilename; char haltoff[] = "__COMPILER_HALT_OFFSET__"; int len, clen; cfilename = zend_get_compiled_filename(TSRMLS_C); clen = strlen(cfilename); zend_mangle_property_name(&name, &len, haltoff, sizeof(haltoff) - 1, cfilename, clen, 0); zend_register_long_constant(name, len+1, zend_get_scanned_file_offset(TSRMLS_C), CONST_CS, 0 TSRMLS_CC); pefree(name, 0); if (CG(in_namespace)) { zend_do_end_namespace(TSRMLS_C); } } /* }}} */ void zend_do_push_object(const znode *object TSRMLS_DC) /* {{{ */ { zend_stack_push(&CG(object_stack), object, sizeof(znode)); } /* }}} */ void zend_do_pop_object(znode *object TSRMLS_DC) /* {{{ */ { if (object) { znode *tmp; zend_stack_top(&CG(object_stack), (void **) &tmp); *object = *tmp; } zend_stack_del_top(&CG(object_stack)); } /* }}} */ void zend_do_begin_new_object(znode *new_token, znode *class_type TSRMLS_DC) /* {{{ */ { zend_op *opline; unsigned char *ptr = NULL; new_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_NEW; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, class_type); SET_UNUSED(opline->op2); zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(unsigned char *)); } /* }}} */ void zend_do_end_new_object(znode *result, const znode *new_token, const znode *argument_list TSRMLS_DC) /* {{{ */ { znode ctor_result; zend_do_end_function_call(NULL, &ctor_result, argument_list, 1, 0 TSRMLS_CC); zend_do_free(&ctor_result TSRMLS_CC); CG(active_op_array)->opcodes[new_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, CG(active_op_array)->opcodes[new_token->u.op.opline_num].result); } /* }}} */ static zend_constant* zend_get_ct_const(const zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = NULL; if (Z_STRVAL_P(const_name)[0] == '\\') { if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name), (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name)-1); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name), (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } } else if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)+1, (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name)+1, (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } if (c->flags & CONST_CT_SUBST) { return c; } if (all_internal_constants_substitution && (c->flags & CONST_PERSISTENT) && !(CG(compiler_options) & ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION) && Z_TYPE(c->value) != IS_CONSTANT && Z_TYPE(c->value) != IS_CONSTANT_ARRAY) { return c; } return NULL; } /* }}} */ static int zend_constant_ct_subst(znode *result, zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = zend_get_ct_const(const_name, all_internal_constants_substitution TSRMLS_CC); if (c) { zval_dtor(const_name); result->op_type = IS_CONST; result->u.constant = c->value; zval_copy_ctor(&result->u.constant); INIT_PZVAL(&result->u.constant); return 1; } return 0; } /* }}} */ void zend_do_fetch_constant(znode *result, znode *constant_container, znode *constant_name, int mode, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; zend_op *opline; int type; char *compound; ulong fetch_type = 0; if (constant_container) { switch (mode) { case ZEND_CT: /* this is a class constant */ type = zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant)); if (ZEND_FETCH_CLASS_STATIC == type) { zend_error(E_ERROR, "\"static::\" is not allowed in compile-time constants"); } else if (ZEND_FETCH_CLASS_DEFAULT == type) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } zend_do_build_full_name(NULL, constant_container, constant_name, 1 TSRMLS_CC); *result = *constant_container; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: if (constant_container->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant))) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } else { zend_do_fetch_class(&tmp, constant_container TSRMLS_CC); constant_container = &tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); if (constant_container->op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &constant_container->u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, constant_container); } SET_NODE(opline->op2, constant_name); CALCULATE_LITERAL_HASH(opline->op2.constant); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } GET_NODE(result, opline->result); break; } return; } /* namespace constant */ /* only one that did not contain \ from the start can be converted to string if unknown */ switch (mode) { case ZEND_CT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); /* this is a namespace constant, or an unprefixed constant */ if (zend_constant_ct_subst(result, &constant_name->u.constant, 0 TSRMLS_CC)) { break; } zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(!compound) { fetch_type |= IS_CONSTANT_UNQUALIFIED; } *result = *constant_name; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(zend_constant_ct_subst(result, &constant_name->u.constant, 1 TSRMLS_CC)) { break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; if (compound) { /* the name is unambiguous */ opline->extended_value = 0; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } else { opline->extended_value = IS_CONSTANT_UNQUALIFIED; if (CG(current_namespace)) { opline->extended_value |= IS_CONSTANT_IN_NAMESPACE; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 1 TSRMLS_CC); } else { opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } } GET_CACHE_SLOT(opline->op2.constant); break; } } /* }}} */ void zend_do_shell_exec(znode *result, const znode *cmd TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); switch (cmd->op_type) { case IS_CONST: case IS_TMP_VAR: opline->opcode = ZEND_SEND_VAL; break; default: opline->opcode = ZEND_SEND_VAR; break; } SET_NODE(opline->op1, cmd); opline->op2.opline_num = 0; opline->extended_value = ZEND_DO_FCALL; SET_UNUSED(opline->op2); /* FIXME: exception support not added to this op2 */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DO_FCALL; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; LITERAL_STRINGL(opline->op1, estrndup("shell_exec", sizeof("shell_exec")-1), sizeof("shell_exec")-1, 0); CALCULATE_LITERAL_HASH(opline->op1.constant); opline->op1_type = IS_CONST; GET_CACHE_SLOT(opline->op1.constant); opline->extended_value = 1; SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_init_array(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_ARRAY; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; GET_NODE(result, opline->result); if (expr) { SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } } else { SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_array_element(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_ARRAY_ELEMENT; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_static_array_element(znode *result, znode *offset, const znode *expr) /* {{{ */ { zval *element; ALLOC_ZVAL(element); *element = expr->u.constant; if (offset) { switch (offset->u.constant.type & IS_CONSTANT_TYPE_MASK) { case IS_CONSTANT: /* Ugly hack to denote that this value has a constant index */ Z_TYPE_P(element) |= IS_CONSTANT_INDEX; Z_STRVAL(offset->u.constant) = erealloc(Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+1] = Z_TYPE(offset->u.constant); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+2] = 0; zend_symtable_update(result->u.constant.value.ht, Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_STRING: zend_symtable_update(result->u.constant.value.ht, offset->u.constant.value.str.val, offset->u.constant.value.str.len+1, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_NULL: zend_symtable_update(Z_ARRVAL(result->u.constant), "", 1, &element, sizeof(zval *), NULL); break; case IS_LONG: case IS_BOOL: zend_hash_index_update(Z_ARRVAL(result->u.constant), Z_LVAL(offset->u.constant), &element, sizeof(zval *), NULL); break; case IS_DOUBLE: zend_hash_index_update(Z_ARRVAL(result->u.constant), zend_dval_to_lval(Z_DVAL(offset->u.constant)), &element, sizeof(zval *), NULL); break; case IS_CONSTANT_ARRAY: zend_error(E_ERROR, "Illegal offset type"); break; } } else { zend_hash_next_index_insert(Z_ARRVAL(result->u.constant), &element, sizeof(zval *), NULL); } } /* }}} */ void zend_do_add_list_element(const znode *element TSRMLS_DC) /* {{{ */ { list_llist_element lle; if (element) { zend_check_writable_variable(element); lle.var = *element; zend_llist_copy(&lle.dimensions, &CG(dimension_llist)); zend_llist_prepend_element(&CG(list_llist), &lle); } (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_new_list_begin(TSRMLS_D) /* {{{ */ { int current_dimension = 0; zend_llist_add_element(&CG(dimension_llist), &current_dimension); } /* }}} */ void zend_do_new_list_end(TSRMLS_D) /* {{{ */ { zend_llist_remove_tail(&CG(dimension_llist)); (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_list_init(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(list_stack), &CG(list_llist), sizeof(zend_llist)); zend_stack_push(&CG(list_stack), &CG(dimension_llist), sizeof(zend_llist)); zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_do_new_list_begin(TSRMLS_C); } /* }}} */ void zend_do_list_end(znode *result, znode *expr TSRMLS_DC) /* {{{ */ { zend_llist_element *le; zend_llist_element *dimension; zend_op *opline; znode last_container; le = CG(list_llist).head; while (le) { zend_llist *tmp_dimension_llist = &((list_llist_element *)le->data)->dimensions; dimension = tmp_dimension_llist->head; while (dimension) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (dimension == tmp_dimension_llist->head) { /* first */ last_container = *expr; switch (expr->op_type) { case IS_VAR: case IS_CV: opline->opcode = ZEND_FETCH_DIM_R; break; case IS_TMP_VAR: opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; case IS_CONST: /* fetch_dim_tmp_var will handle this bogus fetch */ zval_copy_ctor(&expr->u.constant); opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; } opline->extended_value |= ZEND_FETCH_ADD_LOCK; } else { opline->opcode = ZEND_FETCH_DIM_R; } opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, &last_container); opline->op2_type = IS_CONST; LITERAL_LONG(opline->op2, *((int *) dimension->data)); GET_NODE(&last_container, opline->result); dimension = dimension->next; } ((list_llist_element *) le->data)->value = last_container; zend_llist_destroy(&((list_llist_element *) le->data)->dimensions); zend_do_assign(result, &((list_llist_element *) le->data)->var, &((list_llist_element *) le->data)->value TSRMLS_CC); zend_do_free(result TSRMLS_CC); le = le->next; } zend_llist_destroy(&CG(dimension_llist)); zend_llist_destroy(&CG(list_llist)); *result = *expr; { zend_llist *p; /* restore previous lists */ zend_stack_top(&CG(list_stack), (void **) &p); CG(dimension_llist) = *p; zend_stack_del_top(&CG(list_stack)); zend_stack_top(&CG(list_stack), (void **) &p); CG(list_llist) = *p; zend_stack_del_top(&CG(list_stack)); } } /* }}} */ void zend_init_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = emalloc(sizeof(void*) * 2); list[0] = item; list[1] = NULL; *(void**)result = list; } /* }}} */ void zend_add_to_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = *(void**)result; size_t n = 0; while (list && list[n]) { n++; } list = erealloc(list, sizeof(void*) * (n+2)); list[n] = item; list[n+1] = NULL; *(void**)result = list; } /* }}} */ void zend_do_fetch_static_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zval *tmp; zend_op *opline; znode lval; znode result; ALLOC_ZVAL(tmp); if (static_assignment) { *tmp = static_assignment->u.constant; } else { INIT_ZVAL(*tmp); } if (!CG(active_op_array)->static_variables) { if (CG(active_op_array)->scope) { CG(active_op_array)->scope->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } ALLOC_HASHTABLE(CG(active_op_array)->static_variables); zend_hash_init(CG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } zend_hash_update(CG(active_op_array)->static_variables, varname->u.constant.value.str.val, varname->u.constant.value.str.len+1, &tmp, sizeof(zval *), NULL); if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (fetch_type == ZEND_FETCH_LEXICAL) ? ZEND_FETCH_R : ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_STATIC; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ if (fetch_type == ZEND_FETCH_LEXICAL) { znode dummy; zend_do_begin_variable_parse(TSRMLS_C); zend_do_assign(&dummy, &lval, &result TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } else { zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); } CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_fetch_lexical_variable(znode *varname, zend_bool is_ref TSRMLS_DC) /* {{{ */ { znode value; if (Z_STRLEN(varname->u.constant) == sizeof("this") - 1 && memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this") - 1) == 0) { zend_error(E_COMPILE_ERROR, "Cannot use $this as lexical variable"); return; } value.op_type = IS_CONST; ZVAL_NULL(&value.u.constant); Z_TYPE(value.u.constant) |= is_ref ? IS_LEXICAL_REF : IS_LEXICAL_VAR; Z_SET_REFCOUNT_P(&value.u.constant, 1); Z_UNSET_ISREF_P(&value.u.constant); zend_do_fetch_static_variable(varname, &value, is_ref ? ZEND_FETCH_STATIC : ZEND_FETCH_LEXICAL TSRMLS_CC); } /* }}} */ void zend_do_fetch_global_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zend_op *opline; znode lval; znode result; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = fetch_type; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_cast(znode *result, const znode *expr, int type TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CAST; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } /* }}} */ void zend_do_include_or_eval(int type, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_do_extended_fcall_begin(TSRMLS_C); { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INCLUDE_OR_EVAL; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } zend_do_extended_fcall_end(TSRMLS_C); } /* }}} */ void zend_do_indirect_references(znode *result, const znode *num_references, znode *variable TSRMLS_DC) /* {{{ */ { int i; zend_do_end_variable_parse(variable, BP_VAR_R, 0 TSRMLS_CC); for (i=1; i<num_references->u.constant.value.lval; i++) { fetch_simple_variable_ex(result, variable, 0, ZEND_FETCH_R TSRMLS_CC); *variable = *result; } zend_do_begin_variable_parse(TSRMLS_C); fetch_simple_variable(result, variable, 1 TSRMLS_CC); /* there is a chance someone is accessing $this */ if (CG(active_op_array)->scope && CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } /* }}} */ void zend_do_unset(const znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_UNSET_VAR; SET_NODE(opline->op1, variable); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); opline->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_UNSET: last_op->opcode = ZEND_UNSET_VAR; SET_UNUSED(last_op->result); break; case ZEND_FETCH_DIM_UNSET: last_op->opcode = ZEND_UNSET_DIM; SET_UNUSED(last_op->result); break; case ZEND_FETCH_OBJ_UNSET: last_op->opcode = ZEND_UNSET_OBJ; SET_UNUSED(last_op->result); break; } } } /* }}} */ void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_do_end_variable_parse(variable, BP_VAR_IS, 0 TSRMLS_CC); zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { last_op = get_next_op(CG(active_op_array) TSRMLS_CC); last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; SET_NODE(last_op->op1, variable); SET_UNUSED(last_op->op2); last_op->result.var = get_temporary_variable(CG(active_op_array)); last_op->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; break; case ZEND_FETCH_DIM_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_DIM_OBJ; break; case ZEND_FETCH_OBJ_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_PROP_OBJ; break; } } last_op->result_type = IS_TMP_VAR; last_op->extended_value |= type; GET_NODE(result, last_op->result); } /* }}} */ void zend_do_instanceof(znode *result, const znode *expr, const znode *class_znode, int type TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline->opcode == ZEND_FETCH_CLASS) { opline->extended_value |= ZEND_FETCH_CLASS_NO_AUTOLOAD; } } if (expr->op_type == IS_CONST) { zend_error(E_COMPILE_ERROR, "instanceof expects an object instance, constant given"); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INSTANCEOF; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_NODE(opline->op2, class_znode); GET_NODE(result, opline->result); } /* }}} */ void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_bool is_variable; zend_bool push_container = 0; zend_op dummy_opline; if (variable) { if (zend_is_function_or_method_call(array)) { is_variable = 0; } else { is_variable = 1; } /* save the location of FETCH_W instruction(s) */ open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); zend_do_end_variable_parse(array, BP_VAR_W, 0 TSRMLS_CC); if (CG(active_op_array)->last > 0 && CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) { /* Only lock the container if we are fetching from a real container and not $this */ if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1_type == IS_VAR) { CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK; push_container = 1; } } } else { is_variable = 0; open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* save the location of FE_RESET */ foreach_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* Preform array reset */ opline->opcode = ZEND_FE_RESET; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, array); SET_UNUSED(opline->op2); opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0; COPY_NODE(dummy_opline.result, opline->result); if (push_container) { COPY_NODE(dummy_opline.op1, CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1); } else { dummy_opline.op1_type = IS_UNUSED; } zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); /* save the location of FE_FETCH */ as_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FE_FETCH; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); COPY_NODE(opline->op1, dummy_opline.result); opline->extended_value = 0; SET_UNUSED(opline->op2); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_OP_DATA; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); } /* }}} */ void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC) /* {{{ */ { zend_op *opline; znode dummy, value_node; zend_bool assign_by_ref=0; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num]; if (key->op_type != IS_UNUSED) { znode *tmp; /* switch between the key and value... */ tmp = key; key = value; value = tmp; /* Mark extended_value in case both key and value are being used */ opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; } if ((key->op_type != IS_UNUSED) && (key->EA & ZEND_PARSED_REFERENCE_VARIABLE)) { zend_error(E_COMPILE_ERROR, "Key element cannot be a reference"); } if (value->EA & ZEND_PARSED_REFERENCE_VARIABLE) { assign_by_ref = 1; if (!(opline-1)->extended_value) { zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression"); } /* Mark extended_value for assign-by-reference */ opline->extended_value |= ZEND_FE_FETCH_BYREF; CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; } else { zend_op *foreach_copy; zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.op.opline_num]; zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.op.opline_num]; /* Change "write context" into "read context" */ fetch->extended_value = 0; /* reset ZEND_FE_RESET_VARIABLE */ while (fetch != end) { --fetch; if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } if (fetch->opcode == ZEND_SEPARATE) { MAKE_NOP(fetch); } else { fetch->opcode -= 3; /* FETCH_W -> FETCH_R */ } } /* prevent double SWITCH_FREE */ zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy); foreach_copy->op1_type = IS_UNUSED; } GET_NODE(&value_node, opline->result); if (assign_by_ref) { zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); /* Mark FE_FETCH as IS_VAR as it holds the data directly as a value */ zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC); } else { zend_do_assign(&dummy, value, &value_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } if (key->op_type != IS_UNUSED) { znode key_node; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num+1]; opline->result_type = IS_TMP_VAR; opline->result.opline_num = get_temporary_variable(CG(active_op_array)); GET_NODE(&key_node, opline->result); zend_do_assign(&dummy, key, &key_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_foreach_end(const znode *foreach_token, const znode *as_token TSRMLS_DC) /* {{{ */ { zend_op *container_ptr; zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = as_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_RESET */ CG(active_op_array)->opcodes[as_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_FETCH */ do_end_loop(as_token->u.op.opline_num, 1 TSRMLS_CC); zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr); generate_free_foreach_copy(container_ptr TSRMLS_CC); zend_stack_del_top(&CG(foreach_copy_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_declare_begin(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(declare_stack), &CG(declarables), sizeof(zend_declarables)); } /* }}} */ void zend_do_declare_stmt(znode *var, znode *val TSRMLS_DC) /* {{{ */ { if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "ticks", sizeof("ticks")-1)) { convert_to_long(&val->u.constant); CG(declarables).ticks = val->u.constant; } else if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "encoding", sizeof("encoding")-1)) { if ((Z_TYPE(val->u.constant) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Cannot use constants as encoding"); } /* * Check that the pragma comes before any opcodes. If the compilation * got as far as this, the previous portion of the script must have been * parseable according to the .ini script_encoding setting. We still * want to tell them to put declare() at the top. */ { int num = CG(active_op_array)->last; /* ignore ZEND_EXT_STMT and ZEND_TICKS */ while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Encoding declaration pragma must be the very first statement in the script"); } } if (CG(multibyte)) { const zend_encoding *new_encoding, *old_encoding; zend_encoding_filter old_input_filter; CG(encoding_declared) = 1; convert_to_string(&val->u.constant); new_encoding = zend_multibyte_fetch_encoding(val->u.constant.value.str.val TSRMLS_CC); if (!new_encoding) { zend_error(E_COMPILE_WARNING, "Unsupported encoding [%s]", val->u.constant.value.str.val); } else { old_input_filter = LANG_SCNG(input_filter); old_encoding = LANG_SCNG(script_encoding); zend_multibyte_set_filter(new_encoding TSRMLS_CC); /* need to re-scan if input filter changed */ if (old_input_filter != LANG_SCNG(input_filter) || (old_input_filter && new_encoding != old_encoding)) { zend_multibyte_yyinput_again(old_input_filter, old_encoding TSRMLS_CC); } } } else { zend_error(E_COMPILE_WARNING, "declare(encoding=...) ignored because Zend multibyte feature is turned off by settings"); } zval_dtor(&val->u.constant); } else { zend_error(E_COMPILE_WARNING, "Unsupported declare '%s'", var->u.constant.value.str.val); zval_dtor(&val->u.constant); } zval_dtor(&var->u.constant); } /* }}} */ void zend_do_declare_end(const znode *declare_token TSRMLS_DC) /* {{{ */ { zend_declarables *declarables; zend_stack_top(&CG(declare_stack), (void **) &declarables); /* We should restore if there was more than (current - start) - (ticks?1:0) opcodes */ if ((get_next_op_number(CG(active_op_array)) - declare_token->u.op.opline_num) - ((Z_LVAL(CG(declarables).ticks))?1:0)) { CG(declarables) = *declarables; } } /* }}} */ void zend_do_exit(znode *result, const znode *message TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXIT; SET_NODE(opline->op1, message); SET_UNUSED(opline->op2); result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_BOOL; Z_LVAL(result->u.constant) = 1; } /* }}} */ void zend_do_begin_silence(znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BEGIN_SILENCE; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); GET_NODE(strudel_token, opline->result); } /* }}} */ void zend_do_end_silence(const znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_END_SILENCE; SET_NODE(opline->op1, strudel_token); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_jmp_set(const znode *value, znode *jmp_token, znode *colon_token TSRMLS_DC) /* {{{ */ { int op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (value->op_type == IS_VAR || value->op_type == IS_CV) { opline->opcode = ZEND_JMP_SET_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_JMP_SET; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, value); SET_UNUSED(opline->op2); GET_NODE(colon_token, opline->result); jmp_token->u.op .opline_num = op_number; INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_jmp_set_else(znode *result, const znode *false_value, const znode *jmp_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, colon_token); if (colon_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].opcode = ZEND_JMP_SET_VAR; CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } opline->extended_value = 0; SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_qm_op(const znode *cond, znode *qm_token TSRMLS_DC) /* {{{ */ { int jmpz_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); SET_UNUSED(opline->op2); opline->op2.opline_num = jmpz_op_number; GET_NODE(qm_token, opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_qm_true(const znode *true_value, znode *qm_token, znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->opcodes[qm_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array))+1; /* jmp over the ZEND_JMP */ if (true_value->op_type == IS_VAR || true_value->op_type == IS_CV) { opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, true_value); SET_UNUSED(opline->op2); GET_NODE(qm_token, opline->result); colon_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_qm_false(znode *result, const znode *false_value, const znode *qm_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, qm_token); if (qm_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].opcode = ZEND_QM_ASSIGN_VAR; CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[colon_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, opline->result); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_extended_info(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_STMT; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_begin(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_BEGIN; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_end(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_END; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_ticks(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_TICKS; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->extended_value = Z_LVAL(CG(declarables).ticks); } /* }}} */ zend_bool zend_is_auto_global_quick(const char *name, uint name_len, ulong hashval TSRMLS_DC) /* {{{ */ { zend_auto_global *auto_global; ulong hash = hashval ? hashval : zend_hash_func(name, name_len+1); if (zend_hash_quick_find(CG(auto_globals), name, name_len+1, hash, (void **) &auto_global)==SUCCESS) { if (auto_global->armed) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } return 1; } return 0; } /* }}} */ zend_bool zend_is_auto_global(const char *name, uint name_len TSRMLS_DC) /* {{{ */ { return zend_is_auto_global_quick(name, name_len, 0 TSRMLS_CC); } /* }}} */ int zend_register_auto_global(const char *name, uint name_len, zend_bool jit, zend_auto_global_callback auto_global_callback TSRMLS_DC) /* {{{ */ { zend_auto_global auto_global; auto_global.name = zend_new_interned_string((char*)name, name_len + 1, 0 TSRMLS_CC); auto_global.name_len = name_len; auto_global.auto_global_callback = auto_global_callback; auto_global.jit = jit; return zend_hash_add(CG(auto_globals), name, name_len+1, &auto_global, sizeof(zend_auto_global), NULL); } /* }}} */ static int zend_auto_global_init(zend_auto_global *auto_global TSRMLS_DC) /* {{{ */ { if (auto_global->jit) { auto_global->armed = 1; } else if (auto_global->auto_global_callback) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } else { auto_global->armed = 0; } return 0; } /* }}} */ ZEND_API void zend_activate_auto_globals(TSRMLS_D) /* {{{ */ { zend_hash_apply(CG(auto_globals), (apply_func_t) zend_auto_global_init TSRMLS_CC); } /* }}} */ int zendlex(znode *zendlval TSRMLS_DC) /* {{{ */ { int retval; if (CG(increment_lineno)) { CG(zend_lineno)++; CG(increment_lineno) = 0; } again: Z_TYPE(zendlval->u.constant) = IS_LONG; retval = lex_scan(&zendlval->u.constant TSRMLS_CC); switch (retval) { case T_COMMENT: case T_DOC_COMMENT: case T_OPEN_TAG: case T_WHITESPACE: goto again; case T_CLOSE_TAG: if (LANG_SCNG(yy_text)[LANG_SCNG(yy_leng)-1] != '>') { CG(increment_lineno) = 1; } if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { goto again; } retval = ';'; /* implicit ; */ break; case T_OPEN_TAG_WITH_ECHO: retval = T_ECHO; break; case T_END_HEREDOC: efree(Z_STRVAL(zendlval->u.constant)); break; } INIT_PZVAL(&zendlval->u.constant); zendlval->op_type = IS_CONST; return retval; } /* }}} */ ZEND_API void zend_initialize_class_data(zend_class_entry *ce, zend_bool nullify_handlers TSRMLS_DC) /* {{{ */ { zend_bool persistent_hashes = (ce->type == ZEND_INTERNAL_CLASS) ? 1 : 0; dtor_func_t zval_ptr_dtor_func = ((persistent_hashes) ? ZVAL_INTERNAL_PTR_DTOR : ZVAL_PTR_DTOR); ce->refcount = 1; ce->ce_flags = 0; ce->default_properties_table = NULL; ce->default_static_members_table = NULL; zend_hash_init_ex(&ce->properties_info, 0, NULL, (dtor_func_t) (persistent_hashes ? zend_destroy_property_info_internal : zend_destroy_property_info), persistent_hashes, 0); zend_hash_init_ex(&ce->constants_table, 0, NULL, zval_ptr_dtor_func, persistent_hashes, 0); zend_hash_init_ex(&ce->function_table, 0, NULL, ZEND_FUNCTION_DTOR, persistent_hashes, 0); if (ce->type == ZEND_INTERNAL_CLASS) { #ifdef ZTS int n = zend_hash_num_elements(CG(class_table)); if (CG(static_members_table) && n >= CG(last_static_member)) { /* Support for run-time declaration: dl() */ CG(last_static_member) = n+1; CG(static_members_table) = realloc(CG(static_members_table), (n+1)*sizeof(zval**)); CG(static_members_table)[n] = NULL; } ce->static_members_table = (zval**)(zend_intptr_t)n; #else ce->static_members_table = NULL; #endif } else { ce->static_members_table = ce->default_static_members_table; ce->info.user.doc_comment = NULL; ce->info.user.doc_comment_len = 0; } ce->default_properties_count = 0; ce->default_static_members_count = 0; if (nullify_handlers) { ce->constructor = NULL; ce->destructor = NULL; ce->clone = NULL; ce->__get = NULL; ce->__set = NULL; ce->__unset = NULL; ce->__isset = NULL; ce->__call = NULL; ce->__callstatic = NULL; ce->__tostring = NULL; ce->create_object = NULL; ce->get_iterator = NULL; ce->iterator_funcs.funcs = NULL; ce->interface_gets_implemented = NULL; ce->get_static_method = NULL; ce->parent = NULL; ce->num_interfaces = 0; ce->interfaces = NULL; ce->num_traits = 0; ce->traits = NULL; ce->trait_aliases = NULL; ce->trait_precedences = NULL; ce->serialize = NULL; ce->unserialize = NULL; ce->serialize_func = NULL; ce->unserialize_func = NULL; if (ce->type == ZEND_INTERNAL_CLASS) { ce->info.internal.module = NULL; ce->info.internal.builtin_functions = NULL; } } } /* }}} */ int zend_get_class_fetch_type(const char *class_name, uint class_name_len) /* {{{ */ { if ((class_name_len == sizeof("self")-1) && !memcmp(class_name, "self", sizeof("self")-1)) { return ZEND_FETCH_CLASS_SELF; } else if ((class_name_len == sizeof("parent")-1) && !memcmp(class_name, "parent", sizeof("parent")-1)) { return ZEND_FETCH_CLASS_PARENT; } else if ((class_name_len == sizeof("static")-1) && !memcmp(class_name, "static", sizeof("static")-1)) { return ZEND_FETCH_CLASS_STATIC; } else { return ZEND_FETCH_CLASS_DEFAULT; } } /* }}} */ ZEND_API const char* zend_get_compiled_variable_name(const zend_op_array *op_array, zend_uint var, int* name_len) /* {{{ */ { if (name_len) { *name_len = op_array->vars[var].name_len; } return op_array->vars[var].name; } /* }}} */ void zend_do_build_namespace_name(znode *result, znode *prefix, znode *name TSRMLS_DC) /* {{{ */ { if (prefix) { *result = *prefix; if (Z_TYPE(result->u.constant) == IS_STRING && Z_STRLEN(result->u.constant) == 0) { /* namespace\ */ if (CG(current_namespace)) { znode tmp; zval_dtor(&result->u.constant); tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(result, NULL, &tmp TSRMLS_CC); } } } else { result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_STRING; Z_STRVAL(result->u.constant) = NULL; Z_STRLEN(result->u.constant) = 0; } /* prefix = result */ zend_do_build_full_name(NULL, result, name, 0 TSRMLS_CC); } /* }}} */ void zend_do_begin_namespace(const znode *name, zend_bool with_bracket TSRMLS_DC) /* {{{ */ { char *lcname; /* handle mixed syntax declaration or nested namespaces */ if (!CG(has_bracketed_namespaces)) { if (CG(current_namespace)) { /* previous namespace declarations were unbracketed */ if (with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } } } else { /* previous namespace declarations were bracketed */ if (!with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } else if (CG(current_namespace) || CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "Namespace declarations cannot be nested"); } } if (((!with_bracket && !CG(current_namespace)) || (with_bracket && !CG(has_bracketed_namespaces))) && CG(active_op_array)->last > 0) { /* ignore ZEND_EXT_STMT and ZEND_TICKS */ int num = CG(active_op_array)->last; while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Namespace declaration statement has to be the very first statement in the script"); } } CG(in_namespace) = 1; if (with_bracket) { CG(has_bracketed_namespaces) = 1; } if (name) { lcname = zend_str_tolower_dup(Z_STRVAL(name->u.constant), Z_STRLEN(name->u.constant)); if (((Z_STRLEN(name->u.constant) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN(name->u.constant) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as namespace name", Z_STRVAL(name->u.constant)); } efree(lcname); if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); } else { ALLOC_ZVAL(CG(current_namespace)); } *CG(current_namespace) = name->u.constant; } else { if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_use(znode *ns_name, znode *new_name, int is_global TSRMLS_DC) /* {{{ */ { char *lcname; zval *name, *ns, tmp; zend_bool warn = 0; zend_class_entry **pce; if (!CG(current_import)) { CG(current_import) = emalloc(sizeof(HashTable)); zend_hash_init(CG(current_import), 0, NULL, ZVAL_PTR_DTOR, 0); } ALLOC_ZVAL(ns); *ns = ns_name->u.constant; if (new_name) { name = &new_name->u.constant; } else { const char *p; /* The form "use A\B" is eqivalent to "use A\B as B". So we extract the last part of compound name to use as a new_name */ name = &tmp; p = zend_memrchr(Z_STRVAL_P(ns), '\\', Z_STRLEN_P(ns)); if (p) { ZVAL_STRING(name, p+1, 1); } else { *name = *ns; zval_copy_ctor(name); warn = !is_global && !CG(current_namespace); } } lcname = zend_str_tolower_dup(Z_STRVAL_P(name), Z_STRLEN_P(name)); if (((Z_STRLEN_P(name) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN_P(name) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because '%s' is a special class name", Z_STRVAL_P(ns), Z_STRVAL_P(name), Z_STRVAL_P(name)); } if (CG(current_namespace)) { /* Prefix import name with current namespace name to avoid conflicts with classes */ char *c_ns_name = emalloc(Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) + 1); zend_str_tolower_copy(c_ns_name, Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); c_ns_name[Z_STRLEN_P(CG(current_namespace))] = '\\'; memcpy(c_ns_name+Z_STRLEN_P(CG(current_namespace))+1, lcname, Z_STRLEN_P(name)+1); if (zend_hash_exists(CG(class_table), c_ns_name, Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name)+1)) { char *tmp2 = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) || memcmp(tmp2, c_ns_name, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(tmp2); } efree(c_ns_name); } else if (zend_hash_find(CG(class_table), lcname, Z_STRLEN_P(name)+1, (void**)&pce) == SUCCESS && (*pce)->type == ZEND_USER_CLASS && (*pce)->info.user.filename == CG(compiled_filename)) { char *c_tmp = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(name) || memcmp(c_tmp, lcname, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(c_tmp); } if (zend_hash_add(CG(current_import), lcname, Z_STRLEN_P(name)+1, &ns, sizeof(zval*), NULL) != SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } if (warn) { if (!strcmp(Z_STRVAL_P(name), "strict")) { zend_error(E_COMPILE_ERROR, "You seem to be trying to use a different language..."); } zend_error(E_WARNING, "The use statement with non-compound name '%s' has no effect", Z_STRVAL_P(name)); } efree(lcname); zval_dtor(name); } /* }}} */ void zend_do_declare_constant(znode *name, znode *value TSRMLS_DC) /* {{{ */ { zend_op *opline; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed as constants"); } if (zend_get_ct_const(&name->u.constant, 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare constant '%s'", Z_STRVAL(name->u.constant)); } if (CG(current_namespace)) { /* Prefix constant name with name of current namespace, lowercased */ znode tmp; tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); Z_STRVAL(tmp.u.constant) = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), Z_STRLEN(tmp.u.constant)); zend_do_build_namespace_name(&tmp, &tmp, name TSRMLS_CC); *name = tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DECLARE_CONST; SET_UNUSED(opline->result); SET_NODE(opline->op1, name); SET_NODE(opline->op2, value); } /* }}} */ void zend_verify_namespace(TSRMLS_D) /* {{{ */ { if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "No code may exist outside of namespace {}"); } } /* }}} */ void zend_do_end_namespace(TSRMLS_D) /* {{{ */ { CG(in_namespace) = 0; if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_end_compilation(TSRMLS_D) /* {{{ */ { CG(has_bracketed_namespaces) = 0; zend_do_end_namespace(TSRMLS_C); } /* }}} */ /* {{{ zend_dirname Returns directory name component of path */ ZEND_API size_t zend_dirname(char *path, size_t len) { register char *end = path + len - 1; unsigned int len_adjust = 0; #ifdef PHP_WIN32 /* Note that on Win32 CWD is per drive (heritage from CP/M). * This means dirname("c:foo") maps to "c:." or "c:" - which means CWD on C: drive. */ if ((2 <= len) && isalpha((int)((unsigned char *)path)[0]) && (':' == path[1])) { /* Skip over the drive spec (if any) so as not to change */ path += 2; len_adjust += 2; if (2 == len) { /* Return "c:" on Win32 for dirname("c:"). * It would be more consistent to return "c:." * but that would require making the string *longer*. */ return len; } } #elif defined(NETWARE) /* * Find the first occurence of : from the left * move the path pointer to the position just after : * increment the len_adjust to the length of path till colon character(inclusive) * If there is no character beyond : simple return len */ char *colonpos = NULL; colonpos = strchr(path, ':'); if (colonpos != NULL) { len_adjust = ((colonpos - path) + 1); path += len_adjust; if (len_adjust == len) { return len; } } #endif if (len == 0) { /* Illegal use of this function */ return 0; } /* Strip trailing slashes */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { /* The path only contained slashes */ path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } /* Strip filename */ while (end >= path && !IS_SLASH_P(end)) { end--; } if (end < path) { /* No slash found, therefore return '.' */ #ifdef NETWARE if (len_adjust == 0) { path[0] = '.'; path[1] = '\0'; return 1; /* only one character */ } else { path[0] = '\0'; return len_adjust; } #else path[0] = '.'; path[1] = '\0'; return 1 + len_adjust; #endif } /* Strip slashes which came before the file name */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } *(end+1) = '\0'; return (size_t)(end + 1 - path) + len_adjust; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */ /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <zend_language_parser.h> #include "zend.h" #include "zend_compile.h" #include "zend_constants.h" #include "zend_llist.h" #include "zend_API.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "zend_multibyte.h" #include "zend_language_scanner.h" #define CONSTANT_EX(op_array, op) \ (op_array)->literals[op].constant #define CONSTANT(op) \ CONSTANT_EX(CG(active_op_array), op) #define SET_NODE(target, src) do { \ target ## _type = (src)->op_type; \ if ((src)->op_type == IS_CONST) { \ target.constant = zend_add_literal(CG(active_op_array), &(src)->u.constant TSRMLS_CC); \ } else { \ target = (src)->u.op; \ } \ } while (0) #define GET_NODE(target, src) do { \ (target)->op_type = src ## _type; \ if ((target)->op_type == IS_CONST) { \ (target)->u.constant = CONSTANT(src.constant); \ } else { \ (target)->u.op = src; \ (target)->EA = 0; \ } \ } while (0) #define COPY_NODE(target, src) do { \ target ## _type = src ## _type; \ target = src; \ } while (0) #define CALCULATE_LITERAL_HASH(num) do { \ if (IS_INTERNED(Z_STRVAL(CONSTANT(num)))) { \ Z_HASH_P(&CONSTANT(num)) = INTERNED_HASH(Z_STRVAL(CONSTANT(num))); \ } else { \ Z_HASH_P(&CONSTANT(num)) = zend_hash_func(Z_STRVAL(CONSTANT(num)), Z_STRLEN(CONSTANT(num))+1); \ } \ } while (0) #define GET_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot++; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ } \ } while (0) #define POLYMORPHIC_CACHE_SLOT_SIZE 2 #define GET_POLYMORPHIC_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot; \ CG(active_op_array)->last_cache_slot += POLYMORPHIC_CACHE_SLOT_SIZE; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 2] = NULL; \ } \ } while (0) #define FREE_POLYMORPHIC_CACHE_SLOT(literal) do { \ if (CG(active_op_array)->literals[literal].cache_slot == \ CG(active_op_array)->last_cache_slot - POLYMORPHIC_CACHE_SLOT_SIZE) { \ CG(active_op_array)->literals[literal].cache_slot = -1; \ CG(active_op_array)->last_cache_slot -= POLYMORPHIC_CACHE_SLOT_SIZE; \ } \ } while (0) ZEND_API zend_op_array *(*zend_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); ZEND_API zend_op_array *(*zend_compile_string)(zval *source_string, char *filename TSRMLS_DC); #ifndef ZTS ZEND_API zend_compiler_globals compiler_globals; ZEND_API zend_executor_globals executor_globals; #endif static void zend_duplicate_property_info(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = estrndup(property_info->name, property_info->name_length); } if (property_info->doc_comment) { property_info->doc_comment = estrndup(property_info->doc_comment, property_info->doc_comment_len); } } /* }}} */ static void zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = zend_strndup(property_info->name, property_info->name_length); } } /* }}} */ static void zend_destroy_property_info(zend_property_info *property_info) /* {{{ */ { str_efree(property_info->name); if (property_info->doc_comment) { efree((char*)property_info->doc_comment); } } /* }}} */ static void zend_destroy_property_info_internal(zend_property_info *property_info) /* {{{ */ { str_free((char*)property_info->name); } /* }}} */ static void build_runtime_defined_function_key(zval *result, const char *name, int name_length TSRMLS_DC) /* {{{ */ { char char_pos_buf[32]; uint char_pos_len; const char *filename; char_pos_len = zend_sprintf(char_pos_buf, "%p", LANG_SCNG(yy_text)); if (CG(active_op_array)->filename) { filename = CG(active_op_array)->filename; } else { filename = "-"; } /* NULL, name length, filename length, last accepting char position length */ result->value.str.len = 1+name_length+strlen(filename)+char_pos_len; /* must be binary safe */ result->value.str.val = (char *) safe_emalloc(result->value.str.len, 1, 1); result->value.str.val[0] = '\0'; sprintf(result->value.str.val+1, "%s%s%s", name, filename, char_pos_buf); result->type = IS_STRING; Z_SET_REFCOUNT_P(result, 1); } /* }}} */ static void init_compiler_declarables(TSRMLS_D) /* {{{ */ { Z_TYPE(CG(declarables).ticks) = IS_LONG; Z_LVAL(CG(declarables).ticks) = 0; } /* }}} */ void zend_init_compiler_context(TSRMLS_D) /* {{{ */ { CG(context).opcodes_size = (CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) ? INITIAL_INTERACTIVE_OP_ARRAY_SIZE : INITIAL_OP_ARRAY_SIZE; CG(context).vars_size = 0; CG(context).literals_size = 0; CG(context).current_brk_cont = -1; CG(context).backpatch_count = 0; CG(context).labels = NULL; } /* }}} */ void zend_init_compiler_data_structures(TSRMLS_D) /* {{{ */ { zend_stack_init(&CG(bp_stack)); zend_stack_init(&CG(function_call_stack)); zend_stack_init(&CG(switch_cond_stack)); zend_stack_init(&CG(foreach_copy_stack)); zend_stack_init(&CG(object_stack)); zend_stack_init(&CG(declare_stack)); CG(active_class_entry) = NULL; zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_stack_init(&CG(list_stack)); CG(in_compilation) = 0; CG(start_lineno) = 0; CG(current_namespace) = NULL; CG(in_namespace) = 0; CG(has_bracketed_namespaces) = 0; CG(current_import) = NULL; init_compiler_declarables(TSRMLS_C); zend_stack_init(&CG(context_stack)); CG(encoding_declared) = 0; } /* }}} */ ZEND_API void file_handle_dtor(zend_file_handle *fh) /* {{{ */ { TSRMLS_FETCH(); zend_file_handle_dtor(fh TSRMLS_CC); } /* }}} */ void init_compiler(TSRMLS_D) /* {{{ */ { CG(active_op_array) = NULL; zend_init_compiler_data_structures(TSRMLS_C); zend_init_rsrc_list(TSRMLS_C); zend_hash_init(&CG(filenames_table), 5, NULL, (dtor_func_t) free_estring, 0); zend_llist_init(&CG(open_files), sizeof(zend_file_handle), (void (*)(void *)) file_handle_dtor, 0); CG(unclean_shutdown) = 0; } /* }}} */ void shutdown_compiler(TSRMLS_D) /* {{{ */ { zend_stack_destroy(&CG(bp_stack)); zend_stack_destroy(&CG(function_call_stack)); zend_stack_destroy(&CG(switch_cond_stack)); zend_stack_destroy(&CG(foreach_copy_stack)); zend_stack_destroy(&CG(object_stack)); zend_stack_destroy(&CG(declare_stack)); zend_stack_destroy(&CG(list_stack)); zend_hash_destroy(&CG(filenames_table)); zend_llist_destroy(&CG(open_files)); zend_stack_destroy(&CG(context_stack)); } /* }}} */ ZEND_API char *zend_set_compiled_filename(const char *new_compiled_filename TSRMLS_DC) /* {{{ */ { char **pp, *p; int length = strlen(new_compiled_filename); if (zend_hash_find(&CG(filenames_table), new_compiled_filename, length+1, (void **) &pp) == SUCCESS) { CG(compiled_filename) = *pp; return *pp; } p = estrndup(new_compiled_filename, length); zend_hash_update(&CG(filenames_table), new_compiled_filename, length+1, &p, sizeof(char *), (void **) &pp); CG(compiled_filename) = p; return p; } /* }}} */ ZEND_API void zend_restore_compiled_filename(char *original_compiled_filename TSRMLS_DC) /* {{{ */ { CG(compiled_filename) = original_compiled_filename; } /* }}} */ ZEND_API char *zend_get_compiled_filename(TSRMLS_D) /* {{{ */ { return CG(compiled_filename); } /* }}} */ ZEND_API int zend_get_compiled_lineno(TSRMLS_D) /* {{{ */ { return CG(zend_lineno); } /* }}} */ ZEND_API zend_bool zend_is_compiling(TSRMLS_D) /* {{{ */ { return CG(in_compilation); } /* }}} */ static zend_uint get_temporary_variable(zend_op_array *op_array) /* {{{ */ { return (op_array->T)++ * ZEND_MM_ALIGNED_SIZE(sizeof(temp_variable)); } /* }}} */ static int lookup_cv(zend_op_array *op_array, char* name, int name_len, ulong hash TSRMLS_DC) /* {{{ */ { int i = 0; ulong hash_value = hash ? hash : zend_inline_hash_func(name, name_len+1); while (i < op_array->last_var) { if (op_array->vars[i].name == name || (op_array->vars[i].hash_value == hash_value && op_array->vars[i].name_len == name_len && memcmp(op_array->vars[i].name, name, name_len) == 0)) { str_efree(name); return i; } i++; } i = op_array->last_var; op_array->last_var++; if (op_array->last_var > CG(context).vars_size) { CG(context).vars_size += 16; /* FIXME */ op_array->vars = erealloc(op_array->vars, CG(context).vars_size * sizeof(zend_compiled_variable)); } op_array->vars[i].name = zend_new_interned_string(name, name_len + 1, 1 TSRMLS_CC); op_array->vars[i].name_len = name_len; op_array->vars[i].hash_value = hash_value; return i; } /* }}} */ void zend_del_literal(zend_op_array *op_array, int n) /* {{{ */ { zval_dtor(&CONSTANT_EX(op_array, n)); if (n + 1 == op_array->last_literal) { op_array->last_literal--; } else { Z_TYPE(CONSTANT_EX(op_array, n)) = IS_NULL; } } /* }}} */ /* Common part of zend_add_literal and zend_append_individual_literal */ static inline void zend_insert_literal(zend_op_array *op_array, const zval *zv, int literal_position TSRMLS_DC) /* {{{ */ { if (Z_TYPE_P(zv) == IS_STRING || Z_TYPE_P(zv) == IS_CONSTANT) { zval *z = (zval*)zv; Z_STRVAL_P(z) = (char*)zend_new_interned_string(Z_STRVAL_P(zv), Z_STRLEN_P(zv) + 1, 1 TSRMLS_CC); } CONSTANT_EX(op_array, literal_position) = *zv; Z_SET_REFCOUNT(CONSTANT_EX(op_array, literal_position), 2); Z_SET_ISREF(CONSTANT_EX(op_array, literal_position)); op_array->literals[literal_position].hash_value = 0; op_array->literals[literal_position].cache_slot = -1; } /* }}} */ /* Is used while compiling a function, using the context to keep track of an approximate size to avoid to relocate to often. Literals are truncated to actual size in the second compiler pass (pass_two()). */ int zend_add_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; if (i >= CG(context).literals_size) { while (i >= CG(context).literals_size) { CG(context).literals_size += 16; /* FIXME */ } op_array->literals = (zend_literal*)erealloc(op_array->literals, CG(context).literals_size * sizeof(zend_literal)); } zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ /* Is used after normal compilation to append an additional literal. Allocation is done precisely here. */ int zend_append_individual_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; op_array->literals = (zend_literal*)erealloc(op_array->literals, (i + 1) * sizeof(zend_literal)); zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ int zend_add_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_ns_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; const char *ns_separator; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); ns_separator = (const char*)zend_memrchr(Z_STRVAL_P(zv), '\\', Z_STRLEN_P(zv)) + 1; lc_len = Z_STRLEN_P(zv) - (ns_separator - Z_STRVAL_P(zv)); lc_name = zend_str_tolower_dup(ns_separator, lc_len); ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_class_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } if (Z_STRVAL_P(zv)[0] == '\\') { lc_len = Z_STRLEN_P(zv) - 1; lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv) + 1, lc_len); } else { lc_len = Z_STRLEN_P(zv); lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), lc_len); } ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); GET_CACHE_SLOT(ret); return ret; } /* }}} */ int zend_add_const_name_literal(zend_op_array *op_array, const zval *zv, int unqualified TSRMLS_DC) /* {{{ */ { int ret, tmp_literal; char *name, *tmp_name; const char *ns_separator; int name_len, ns_len; zval c; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } /* skip leading '\\' */ if (Z_STRVAL_P(zv)[0] == '\\') { name_len = Z_STRLEN_P(zv) - 1; name = Z_STRVAL_P(zv) + 1; } else { name_len = Z_STRLEN_P(zv); name = Z_STRVAL_P(zv); } ns_separator = zend_memrchr(name, '\\', name_len); if (ns_separator) { ns_len = ns_separator - name; } else { ns_len = 0; } if (ns_len) { /* lowercased namespace name & original constant name */ tmp_name = estrndup(name, name_len); zend_str_tolower(tmp_name, ns_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased namespace name & lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); } if (ns_len) { if (!unqualified) { return ret; } ns_len++; name += ns_len; name_len -= ns_len; } /* original constant name */ tmp_name = estrndup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); return ret; } /* }}} */ #define LITERAL_STRINGL(op, str, len, copy) do { \ zval _c; \ ZVAL_STRINGL(&_c, str, len, copy); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG(op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG_EX(op_array, op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(op_array, &_c TSRMLS_CC); \ } while (0) #define LITERAL_NULL(op) do { \ zval _c; \ INIT_ZVAL( _c); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) static inline zend_bool zend_is_function_or_method_call(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; return ((type & ZEND_PARSED_METHOD_CALL) || (type == ZEND_PARSED_FUNCTION_CALL)); } /* }}} */ void zend_do_binary_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_unary_op(zend_uchar op, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); GET_NODE(result, opline->result); SET_UNUSED(opline->op2); } /* }}} */ #define MAKE_NOP(opline) { opline->opcode = ZEND_NOP; memset(&opline->result,0,sizeof(opline->result)); memset(&opline->op1,0,sizeof(opline->op1)); memset(&opline->op2,0,sizeof(opline->op2)); opline->result_type=opline->op1_type=opline->op2_type=IS_UNUSED; } static void zend_do_op_data(zend_op *data_op, const znode *value TSRMLS_DC) /* {{{ */ { data_op->opcode = ZEND_OP_DATA; SET_NODE(data_op->op1, value); SET_UNUSED(data_op->op2); } /* }}} */ void zend_do_binary_assign_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; switch (last_op->opcode) { case ZEND_FETCH_OBJ_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, op2 TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; case ZEND_FETCH_DIM_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_DIM; zend_do_op_data(opline, op2 TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result,last_op->result); return; default: break; } } opline->opcode = op; SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void fetch_simple_variable_ex(znode *result, znode *varname, int bp, zend_uchar op TSRMLS_DC) /* {{{ */ { zend_op opline; zend_op *opline_ptr; zend_llist *fetch_list_ptr; if (varname->op_type == IS_CONST) { ulong hash = 0; if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } else if (IS_INTERNED(Z_STRVAL(varname->u.constant))) { hash = INTERNED_HASH(Z_STRVAL(varname->u.constant)); } if (!zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC) && !(varname->u.constant.value.str.len == (sizeof("this")-1) && !memcmp(varname->u.constant.value.str.val, "this", sizeof("this"))) && (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE)) { result->op_type = IS_CV; result->u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC); varname->u.constant.value.str.val = (char*)CG(active_op_array)->vars[result->u.op.var].name; result->EA = 0; return; } } if (bp) { opline_ptr = &opline; init_op(opline_ptr TSRMLS_CC); } else { opline_ptr = get_next_op(CG(active_op_array) TSRMLS_CC); } opline_ptr->opcode = op; opline_ptr->result_type = IS_VAR; opline_ptr->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline_ptr->op1, varname); GET_NODE(result, opline_ptr->result); SET_UNUSED(opline_ptr->op2); opline_ptr->extended_value = ZEND_FETCH_LOCAL; if (varname->op_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline_ptr->op1.constant); if (zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC)) { opline_ptr->extended_value = ZEND_FETCH_GLOBAL; } } if (bp) { zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); zend_llist_add_element(fetch_list_ptr, opline_ptr); } } /* }}} */ void fetch_simple_variable(znode *result, znode *varname, int bp TSRMLS_DC) /* {{{ */ { /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ fetch_simple_variable_ex(result, varname, bp, ZEND_FETCH_W TSRMLS_CC); } /* }}} */ void zend_do_fetch_static_member(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { znode class_node; zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline_ptr; zend_op opline; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); } zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (result->op_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[result->u.op.var].name), CG(active_op_array)->vars[result->u.op.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } GET_NODE(result,opline.result); opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; opline_ptr = &opline; zend_llist_add_element(fetch_list_ptr, &opline); } else { le = fetch_list_ptr->head; opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode != ZEND_FETCH_W && opline_ptr->op1_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[opline_ptr->op1.var].name), CG(active_op_array)->vars[opline_ptr->op1.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; COPY_NODE(opline_ptr->op1, opline.result); zend_llist_prepend_element(fetch_list_ptr, &opline); } else { if (opline_ptr->op1_type == IS_CONST) { GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op1.constant); } if (class_node.op_type == IS_CONST) { opline_ptr->op2_type = IS_CONST; opline_ptr->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline_ptr->op2, &class_node); } opline_ptr->extended_value |= ZEND_FETCH_STATIC_MEMBER; } } } /* }}} */ void fetch_array_begin(znode *result, znode *varname, znode *first_dim TSRMLS_DC) /* {{{ */ { fetch_simple_variable(result, varname, 1 TSRMLS_CC); fetch_array_dim(result, result, first_dim TSRMLS_CC); } /* }}} */ void fetch_array_dim(znode *result, const znode *parent, const znode *dim TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (zend_is_function_or_method_call(parent)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, parent); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_DIM_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, parent); SET_NODE(opline.op2, dim); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline.op2.constant)), Z_STRLEN(CONSTANT(opline.op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline.op2.constant)); ZVAL_LONG(&CONSTANT(opline.op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline.op2.constant); } } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void fetch_string_offset(znode *result, const znode *parent, const znode *offset TSRMLS_DC) /* {{{ */ { fetch_array_dim(result, parent, offset TSRMLS_CC); } /* }}} */ void zend_do_print(znode *result, const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->opcode = ZEND_PRINT; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_echo(const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ECHO; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_abstract_method(const znode *function_name, znode *modifiers, const znode *body TSRMLS_DC) /* {{{ */ { char *method_type; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { Z_LVAL(modifiers->u.constant) |= ZEND_ACC_ABSTRACT; method_type = "Interface"; } else { method_type = "Abstract"; } if (modifiers->u.constant.value.lval & ZEND_ACC_ABSTRACT) { if(modifiers->u.constant.value.lval & ZEND_ACC_PRIVATE) { zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot be declared private", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } if (Z_LVAL(body->u.constant) == ZEND_ACC_ABSTRACT) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_RAISE_ABSTRACT_ERROR; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } else { /* we had code in the function body */ zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot contain body", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } else { if (body->u.constant.value.lval == ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Non-abstract method %s::%s() must contain body", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } } /* }}} */ static zend_bool opline_is_fetch_this(const zend_op *opline TSRMLS_DC) /* {{{ */ { if ((opline->opcode == ZEND_FETCH_W) && (opline->op1_type == IS_CONST) && (Z_TYPE(CONSTANT(opline->op1.constant)) == IS_STRING) && (Z_HASH_P(&CONSTANT(opline->op1.constant)) == THIS_HASHVAL) && (Z_STRLEN(CONSTANT(opline->op1.constant)) == (sizeof("this")-1)) && !memcmp(Z_STRVAL(CONSTANT(opline->op1.constant)), "this", sizeof("this"))) { return 1; } else { return 0; } } /* }}} */ void zend_do_assign(znode *result, znode *variable, znode *value TSRMLS_DC) /* {{{ */ { int last_op_number; zend_op *opline; if (value->op_type == IS_CV) { zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (fetch_list_ptr && fetch_list_ptr->head) { opline = (zend_op *)fetch_list_ptr->head->data; if (opline->opcode == ZEND_FETCH_DIM_W && opline->op1_type == IS_CV && opline->op1.var == value->u.op.var) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_R; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->op1_type = IS_CONST; LITERAL_STRINGL(opline->op1, CG(active_op_array)->vars[value->u.op.var].name, CG(active_op_array)->vars[value->u.op.var].name_len, 1); CALCULATE_LITERAL_HASH(opline->op1.constant); SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_LOCAL; GET_NODE(value, opline->result); } } } zend_do_end_variable_parse(variable, BP_VAR_W, 0 TSRMLS_CC); last_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (variable->op_type == IS_CV) { if (variable->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (variable->op_type == IS_VAR) { int n = 0; while (last_op_number - n > 0) { zend_op *last_op; last_op = &CG(active_op_array)->opcodes[last_op_number-n-1]; if (last_op->result_type == IS_VAR && last_op->result.var == variable->u.op.var) { if (last_op->opcode == ZEND_FETCH_OBJ_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, value TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (last_op->opcode == ZEND_FETCH_DIM_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ /* TBFixed: this can realloc opcodes, leaving last_op pointing wrong */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_DIM; zend_do_op_data(opline, value TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (opline_is_fetch_this(last_op TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } else { break; } } n++; } } opline->opcode = ZEND_ASSIGN; SET_NODE(opline->op1, variable); SET_NODE(opline->op2, value); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_assign_ref(znode *result, const znode *lvar, const znode *rvar TSRMLS_DC) /* {{{ */ { zend_op *opline; if (lvar->op_type == IS_CV) { if (lvar->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (lvar->op_type == IS_VAR) { int last_op_number = get_next_op_number(CG(active_op_array)); if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline_is_fetch_this(opline TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ASSIGN_REF; if (zend_is_function_or_method_call(rvar)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } else if (rvar->EA & ZEND_PARSED_NEW) { opline->extended_value = ZEND_RETURNS_NEW; } else { opline->extended_value = 0; } if (result) { opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } else { opline->result_type = IS_UNUSED | EXT_TYPE_UNUSED; } SET_NODE(opline->op1, lvar); SET_NODE(opline->op2, rvar); } /* }}} */ static inline void do_begin_loop(TSRMLS_D) /* {{{ */ { zend_brk_cont_element *brk_cont_element; int parent; parent = CG(context).current_brk_cont; CG(context).current_brk_cont = CG(active_op_array)->last_brk_cont; brk_cont_element = get_next_brk_cont_element(CG(active_op_array)); brk_cont_element->start = get_next_op_number(CG(active_op_array)); brk_cont_element->parent = parent; } /* }}} */ static inline void do_end_loop(int cont_addr, int has_loop_var TSRMLS_DC) /* {{{ */ { if (!has_loop_var) { /* The start fileld is used to free temporary variables in case of exceptions. * We won't try to free something of we don't have loop variable. */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].start = -1; } CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = cont_addr; CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; } /* }}} */ void zend_do_while_cond(const znode *expr, znode *close_bracket_token TSRMLS_DC) /* {{{ */ { int while_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, expr); close_bracket_token->u.op.opline_num = while_cond_op_number; SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_while_end(const znode *while_token, const znode *close_bracket_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* add unconditional jump */ opline->opcode = ZEND_JMP; opline->op1.opline_num = while_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* update while's conditional jmp */ CG(active_op_array)->opcodes[close_bracket_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); do_end_loop(while_token->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_cond(const znode *expr, znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { int for_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZNZ; SET_NODE(opline->op1, expr); /* the conditional expression */ second_semicolon_token->u.op.opline_num = for_cond_op_number; SET_UNUSED(opline->op2); } /* }}} */ void zend_do_for_before_statement(const znode *cond_start, const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = cond_start->u.op.opline_num; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_end(const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = second_semicolon_token->u.op.opline_num+1; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_end_loop(second_semicolon_token->u.op.opline_num+1, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_pre_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_PRE_INC)?ZEND_PRE_INC_OBJ:ZEND_PRE_DEC_OBJ; last_op->result_type = IS_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_post_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_POST_INC)?ZEND_POST_INC_OBJ:ZEND_POST_DEC_OBJ; last_op->result_type = IS_TMP_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_if_cond(const znode *cond, znode *closing_bracket_token TSRMLS_DC) /* {{{ */ { int if_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); closing_bracket_token->u.op.opline_num = if_cond_op_number; SET_UNUSED(opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_if_after_statement(const znode *closing_bracket_token, unsigned char initialize TSRMLS_DC) /* {{{ */ { int if_end_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; /* save for backpatching */ if (initialize) { zend_llist jmp_list; zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); } zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &if_end_op_number); CG(active_op_array)->opcodes[closing_bracket_token->u.op.opline_num].op2.opline_num = if_end_op_number+1; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_if_end(TSRMLS_D) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_llist *jmp_list_ptr; zend_llist_element *le; zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); for (le=jmp_list_ptr->head; le; le = le->next) { CG(active_op_array)->opcodes[*((int *) le->data)].op1.opline_num = next_op_number; } zend_llist_destroy(jmp_list_ptr); zend_stack_del_top(&CG(bp_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_check_writable_variable(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; if (type & ZEND_PARSED_METHOD_CALL) { zend_error(E_COMPILE_ERROR, "Can't use method return value in write context"); } if (type == ZEND_PARSED_FUNCTION_CALL) { zend_error(E_COMPILE_ERROR, "Can't use function return value in write context"); } } /* }}} */ void zend_do_begin_variable_parse(TSRMLS_D) /* {{{ */ { zend_llist fetch_list; zend_llist_init(&fetch_list, sizeof(zend_op), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &fetch_list, sizeof(zend_llist)); } /* }}} */ void zend_do_end_variable_parse(znode *variable, int type, int arg_offset TSRMLS_DC) /* {{{ */ { zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline = NULL; zend_op *opline_ptr; zend_uint this_var = -1; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); le = fetch_list_ptr->head; /* TODO: $foo->x->y->z = 1 should fetch "x" and "y" for R or RW, not just W */ if (le) { opline_ptr = (zend_op *)le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { /* convert to FETCH_?(this) into IS_CV */ if (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE) { this_var = opline_ptr->result.var; if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), Z_STRVAL(CONSTANT(opline_ptr->op1.constant)), Z_STRLEN(CONSTANT(opline_ptr->op1.constant)), Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC); Z_TYPE(CONSTANT(opline_ptr->op1.constant)) = IS_NULL; } else { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); } le = le->next; if (variable->op_type == IS_VAR && variable->u.op.var == this_var) { variable->op_type = IS_CV; variable->u.op.var = CG(active_op_array)->this_var; } } else if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } while (le) { opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode == ZEND_SEPARATE) { if (type != BP_VAR_R && type != BP_VAR_IS) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); } le = le->next; continue; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); if (opline->op1_type == IS_VAR && opline->op1.var == this_var) { opline->op1_type = IS_CV; opline->op1.var = CG(active_op_array)->this_var; } switch (type) { case BP_VAR_R: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode -= 3; break; case BP_VAR_W: break; case BP_VAR_RW: opline->opcode += 3; break; case BP_VAR_IS: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode += 6; /* 3+3 */ break; case BP_VAR_FUNC_ARG: opline->opcode += 9; /* 3+3+3 */ opline->extended_value |= arg_offset; break; case BP_VAR_UNSET: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for unsetting"); } opline->opcode += 12; /* 3+3+3+3 */ break; } le = le->next; } if (opline && type == BP_VAR_W && arg_offset) { opline->extended_value |= ZEND_FETCH_MAKE_REF; } } zend_llist_destroy(fetch_list_ptr); zend_stack_del_top(&CG(bp_stack)); } /* }}} */ void zend_do_add_string(znode *result, const znode *op1, znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline; if (Z_STRLEN(op2->u.constant) > 1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_STRING; } else if (Z_STRLEN(op2->u.constant) == 1) { int ch = *Z_STRVAL(op2->u.constant); /* Free memory and use ZEND_ADD_CHAR in case of 1 character strings */ efree(Z_STRVAL(op2->u.constant)); ZVAL_LONG(&op2->u.constant, ch); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_CHAR; } else { /* String can be empty after a variable at the end of a heredoc */ efree(Z_STRVAL(op2->u.constant)); return; } if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_add_variable(znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_VAR; if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_free(znode *op1 TSRMLS_DC) /* {{{ */ { if (op1->op_type==IS_TMP_VAR) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else if (op1->op_type==IS_VAR) { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; while (opline->opcode == ZEND_END_SILENCE || opline->opcode == ZEND_EXT_FCALL_END || opline->opcode == ZEND_OP_DATA) { opline--; } if (opline->result_type == IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_FETCH_R || opline->opcode == ZEND_FETCH_DIM_R || opline->opcode == ZEND_FETCH_OBJ_R || opline->opcode == ZEND_QM_ASSIGN_VAR) { /* It's very rare and useless case. It's better to use additional FREE opcode and simplify the FETCH handlers their selves */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else { opline->result_type |= EXT_TYPE_UNUSED; } } else { while (opline>CG(active_op_array)->opcodes) { if (opline->opcode == ZEND_FETCH_DIM_R && opline->op1_type == IS_VAR && opline->op1.var == op1->u.op.var) { /* This should the end of a list() construct * Mark its result as unused */ opline->extended_value = ZEND_FETCH_STANDARD; break; } else if (opline->result_type==IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_NEW) { opline->result_type |= EXT_TYPE_UNUSED; } break; } opline--; } } } else if (op1->op_type == IS_CONST) { zval_dtor(&op1->u.constant); } } /* }}} */ int zend_do_verify_access_types(const znode *current_access_type, const znode *new_modifier) /* {{{ */ { if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_PPP_MASK) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Multiple access type modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_ABSTRACT) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Multiple abstract modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_STATIC) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Multiple static modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_FINAL) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Multiple final modifiers are not allowed"); } if (((Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)) & (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) == (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Cannot use the final modifier on an abstract class member"); } return (Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)); } /* }}} */ void zend_do_begin_function_declaration(znode *function_token, znode *function_name, int is_method, int return_reference, znode *fn_flags_znode TSRMLS_DC) /* {{{ */ { zend_op_array op_array; char *name = function_name->u.constant.value.str.val; int name_len = function_name->u.constant.value.str.len; int function_begin_line = function_token->u.op.opline_num; zend_uint fn_flags; const char *lcname; zend_bool orig_interactive; ALLOCA_FLAG(use_heap) if (is_method) { if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((Z_LVAL(fn_flags_znode->u.constant) & ~(ZEND_ACC_STATIC|ZEND_ACC_PUBLIC))) { zend_error(E_COMPILE_ERROR, "Access type for interface method %s::%s() must be omitted", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } Z_LVAL(fn_flags_znode->u.constant) |= ZEND_ACC_ABSTRACT; /* propagates to the rest of the parser */ } fn_flags = Z_LVAL(fn_flags_znode->u.constant); /* must be done *after* the above check */ } else { fn_flags = 0; } if ((fn_flags & ZEND_ACC_STATIC) && (fn_flags & ZEND_ACC_ABSTRACT) && !(CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_STRICT, "Static function %s%s%s() should not be abstract", is_method ? CG(active_class_entry)->name : "", is_method ? "::" : "", Z_STRVAL(function_name->u.constant)); } function_token->u.op_array = CG(active_op_array); orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(&op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; op_array.function_name = name; if (return_reference) { op_array.fn_flags |= ZEND_ACC_RETURN_REFERENCE; } op_array.fn_flags |= fn_flags; op_array.scope = is_method?CG(active_class_entry):NULL; op_array.prototype = NULL; op_array.line_start = zend_get_compiled_lineno(TSRMLS_C); if (is_method) { int result; lcname = zend_new_interned_string(zend_str_tolower_dup(name, name_len), name_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lcname)) { result = zend_hash_quick_add(&CG(active_class_entry)->function_table, lcname, name_len+1, INTERNED_HASH(lcname), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } else { result = zend_hash_add(&CG(active_class_entry)->function_table, lcname, name_len+1, &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } if (result == FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::%s()", CG(active_class_entry)->name, name); } zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); if (fn_flags & ZEND_ACC_ABSTRACT) { CG(active_class_entry)->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (!(fn_flags & ZEND_ACC_PPP_MASK)) { fn_flags |= ZEND_ACC_PUBLIC; } if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } } } else { char *class_lcname; class_lcname = do_alloca(CG(active_class_entry)->name_length + 1, use_heap); zend_str_tolower_copy(class_lcname, CG(active_class_entry)->name, CG(active_class_entry)->name_length); /* Improve after RC: cache the lowercase class name */ if ((CG(active_class_entry)->name_length == name_len) && ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT) && (!memcmp(class_lcname, lcname, name_len))) { if (!CG(active_class_entry)->constructor) { CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } } else if ((name_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)))) { if (CG(active_class_entry)->constructor) { zend_error(E_STRICT, "Redefining already defined constructor for class %s", CG(active_class_entry)->name); } CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1))) { CG(active_class_entry)->destructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1))) { CG(active_class_entry)->clone = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } CG(active_class_entry)->__call = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } CG(active_class_entry)->__callstatic = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } CG(active_class_entry)->__get = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } CG(active_class_entry)->__set = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } CG(active_class_entry)->__unset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } CG(active_class_entry)->__isset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } CG(active_class_entry)->__tostring = (zend_function *) CG(active_op_array); } else if (!(fn_flags & ZEND_ACC_STATIC)) { CG(active_op_array)->fn_flags |= ZEND_ACC_ALLOW_STATIC; } free_alloca(class_lcname, use_heap); } str_efree(lcname); } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zval key; if (CG(current_namespace)) { /* Prefix function name with current namespcae name */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, function_name TSRMLS_CC); op_array.function_name = Z_STRVAL(tmp.u.constant); name_len = Z_STRLEN(tmp.u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), name_len); } else { lcname = zend_str_tolower_dup(name, name_len); } opline->opcode = ZEND_DECLARE_FUNCTION; opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, name_len TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; LITERAL_STRINGL(opline->op2, lcname, name_len, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); opline->extended_value = ZEND_DECLARE_FUNCTION; zend_hash_quick_update(CG(function_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); } if (CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_NOP; opline->lineno = function_begin_line; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } { /* Push a seperator to the switch and foreach stacks */ zend_switch_entry switch_entry; switch_entry.cond.op_type = IS_UNUSED; switch_entry.default_case = 0; switch_entry.control_var = 0; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); { /* Foreach stack separator */ zend_op dummy_opline; dummy_opline.result_type = IS_UNUSED; dummy_opline.op1_type = IS_UNUSED; zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); } } if (CG(doc_comment)) { CG(active_op_array)->doc_comment = CG(doc_comment); CG(active_op_array)->doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_begin_lambda_function_declaration(znode *result, znode *function_token, int return_reference, int is_static TSRMLS_DC) /* {{{ */ { znode function_name; zend_op_array *current_op_array = CG(active_op_array); int current_op_number = get_next_op_number(CG(active_op_array)); zend_op *current_op; function_name.op_type = IS_CONST; ZVAL_STRINGL(&function_name.u.constant, "{closure}", sizeof("{closure}")-1, 1); zend_do_begin_function_declaration(function_token, &function_name, 0, return_reference, NULL TSRMLS_CC); result->op_type = IS_TMP_VAR; result->u.op.var = get_temporary_variable(current_op_array); current_op = &current_op_array->opcodes[current_op_number]; current_op->opcode = ZEND_DECLARE_LAMBDA_FUNCTION; zend_del_literal(current_op_array, current_op->op2.constant); SET_UNUSED(current_op->op2); SET_NODE(current_op->result, result); if (is_static) { CG(active_op_array)->fn_flags |= ZEND_ACC_STATIC; } CG(active_op_array)->fn_flags |= ZEND_ACC_CLOSURE; } /* }}} */ void zend_do_handle_exception(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_HANDLE_EXCEPTION; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_function_declaration(const znode *function_token TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; zend_do_extended_info(TSRMLS_C); zend_do_return(NULL, 0 TSRMLS_CC); pass_two(CG(active_op_array) TSRMLS_CC); zend_release_labels(TSRMLS_C); if (CG(active_class_entry)) { zend_check_magic_method_implementation(CG(active_class_entry), (zend_function*)CG(active_op_array), E_COMPILE_ERROR TSRMLS_CC); } else { /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(CG(active_op_array)->function_name); zend_str_tolower_copy(lcname, CG(active_op_array)->function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME)) && CG(active_op_array)->num_args != 1) { zend_error(E_COMPILE_ERROR, "%s() must take exactly 1 argument", ZEND_AUTOLOAD_FUNC_NAME); } } CG(active_op_array)->line_end = zend_get_compiled_lineno(TSRMLS_C); CG(active_op_array) = function_token->u.op_array; /* Pop the switch and foreach seperators */ zend_stack_del_top(&CG(switch_cond_stack)); zend_stack_del_top(&CG(foreach_copy_stack)); } /* }}} */ void zend_do_receive_arg(zend_uchar op, znode *varname, const znode *offset, const znode *initialization, znode *class_type, zend_uchar pass_by_reference TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_arg_info *cur_arg_info; znode var; if (class_type->op_type == IS_CONST && Z_TYPE(class_type->u.constant) == IS_STRING && Z_STRLEN(class_type->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_type->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } if (zend_is_auto_global_quick(Z_STRVAL(varname->u.constant), Z_STRLEN(varname->u.constant), 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign auto-global variable %s", Z_STRVAL(varname->u.constant)); } else { var.op_type = IS_CV; var.u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(varname->u.constant) = (char*)CG(active_op_array)->vars[var.u.op.var].name; var.EA = 0; if (CG(active_op_array)->vars[var.u.op.var].hash_value == THIS_HASHVAL && Z_STRLEN(varname->u.constant) == sizeof("this")-1 && !memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this")-1)) { if (CG(active_op_array)->scope && (CG(active_op_array)->fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } CG(active_op_array)->this_var = var.u.op.var; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->num_args++; opline->opcode = op; SET_NODE(opline->result, &var); SET_NODE(opline->op1, offset); if (op == ZEND_RECV_INIT) { SET_NODE(opline->op2, initialization); } else { CG(active_op_array)->required_num_args = CG(active_op_array)->num_args; SET_UNUSED(opline->op2); } CG(active_op_array)->arg_info = erealloc(CG(active_op_array)->arg_info, sizeof(zend_arg_info)*(CG(active_op_array)->num_args)); cur_arg_info = &CG(active_op_array)->arg_info[CG(active_op_array)->num_args-1]; cur_arg_info->name = zend_new_interned_string(estrndup(varname->u.constant.value.str.val, varname->u.constant.value.str.len), varname->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->name_len = varname->u.constant.value.str.len; cur_arg_info->type_hint = 0; cur_arg_info->allow_null = 1; cur_arg_info->pass_by_reference = pass_by_reference; cur_arg_info->class_name = NULL; cur_arg_info->class_name_len = 0; if (class_type->op_type != IS_UNUSED) { cur_arg_info->allow_null = 0; if (class_type->u.constant.type != IS_NULL) { if (class_type->u.constant.type == IS_ARRAY) { cur_arg_info->type_hint = IS_ARRAY; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else if (Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Default value for parameters with array type hint can only be an array or NULL"); } } } else if (class_type->u.constant.type == IS_CALLABLE) { cur_arg_info->type_hint = IS_CALLABLE; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with callable type hint can only be NULL"); } } } else { cur_arg_info->type_hint = IS_OBJECT; if (ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_type->u.constant), Z_STRLEN(class_type->u.constant))) { zend_resolve_class_name(class_type, opline->extended_value, 1 TSRMLS_CC); } Z_STRVAL(class_type->u.constant) = (char*)zend_new_interned_string(class_type->u.constant.value.str.val, class_type->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->class_name = class_type->u.constant.value.str.val; cur_arg_info->class_name_len = class_type->u.constant.value.str.len; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with a class type hint can only be NULL"); } } } } } } /* }}} */ int zend_do_begin_function_call(znode *function_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { zend_function *function; char *lcname; char *is_compound = memchr(Z_STRVAL(function_name->u.constant), '\\', Z_STRLEN(function_name->u.constant)); zend_resolve_non_class_name(function_name, check_namespace TSRMLS_CC); if (check_namespace && CG(current_namespace) && !is_compound) { /* We assume we call function from the current namespace if it is not prefixed. */ /* In run-time PHP will check for function with full name and internal function with short name */ zend_do_begin_dynamic_function_call(function_name, 1 TSRMLS_CC); return 1; } lcname = zend_str_tolower_dup(function_name->u.constant.value.str.val, function_name->u.constant.value.str.len); if ((zend_hash_find(CG(function_table), lcname, function_name->u.constant.value.str.len+1, (void **) &function)==FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_FUNCTIONS) && (function->type == ZEND_INTERNAL_FUNCTION))) { zend_do_begin_dynamic_function_call(function_name, 0 TSRMLS_CC); efree(lcname); return 1; /* Dynamic */ } efree(function_name->u.constant.value.str.val); function_name->u.constant.value.str.val = lcname; zend_stack_push(&CG(function_call_stack), (void *) &function, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 0; } /* }}} */ void zend_do_begin_method_call(znode *left_bracket TSRMLS_DC) /* {{{ */ { zend_op *last_op; int last_op_number; unsigned char *ptr = NULL; zend_do_end_variable_parse(left_bracket, BP_VAR_R, 0 TSRMLS_CC); zend_do_begin_variable_parse(TSRMLS_C); last_op_number = get_next_op_number(CG(active_op_array))-1; last_op = &CG(active_op_array)->opcodes[last_op_number]; if ((last_op->op2_type == IS_CONST) && (Z_TYPE(CONSTANT(last_op->op2.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(last_op->op2.constant)) == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !zend_binary_strcasecmp(Z_STRVAL(CONSTANT(last_op->op2.constant)), Z_STRLEN(CONSTANT(last_op->op2.constant)), ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1)) { zend_error(E_COMPILE_ERROR, "Cannot call __clone() method on objects - use 'clone $obj' instead"); } if (last_op->opcode == ZEND_FETCH_OBJ_R) { if (last_op->op2_type == IS_CONST) { zval name; name = CONSTANT(last_op->op2.constant); if (!IS_INTERNED(Z_STRVAL(name))) { Z_STRVAL(name) = estrndup(Z_STRVAL(name), Z_STRLEN(name)); } FREE_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); last_op->op2.constant = zend_add_func_name_literal(CG(active_op_array), &name TSRMLS_CC); GET_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); } last_op->opcode = ZEND_INIT_METHOD_CALL; SET_UNUSED(last_op->result); Z_LVAL(left_bracket->u.constant) = ZEND_INIT_FCALL_BY_NAME; } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (left_bracket->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &left_bracket->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, left_bracket); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_do_clone(znode *result, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CLONE; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_begin_dynamic_function_call(znode *function_name, int ns_call TSRMLS_DC) /* {{{ */ { unsigned char *ptr = NULL; zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (ns_call) { /* In run-time PHP will check for function with full name and internal function with short name */ opline->opcode = ZEND_INIT_NS_FCALL_BY_NAME; SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_ns_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (function_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, function_name); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_resolve_non_class_name(znode *element_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; int len; zval **ns; char *lcname, *compound = memchr(Z_STRVAL(element_name->u.constant), '\\', Z_STRLEN(element_name->u.constant)); if (Z_STRVAL(element_name->u.constant)[0] == '\\') { /* name starts with \ so it is known and unambiguos, nothing to do here but shorten it */ memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+1, Z_STRLEN(element_name->u.constant)); --Z_STRLEN(element_name->u.constant); return; } if(!check_namespace) { return; } if (compound && CG(current_import)) { len = compound - Z_STRVAL(element_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(element_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(element_name->u.constant) -= len; memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+len, Z_STRLEN(element_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, element_name TSRMLS_CC); *element_name = tmp; efree(lcname); return; } efree(lcname); } if (CG(current_namespace)) { tmp = *element_name; Z_STRLEN(tmp.u.constant) = sizeof("\\")-1 + Z_STRLEN(element_name->u.constant) + Z_STRLEN_P(CG(current_namespace)); Z_STRVAL(tmp.u.constant) = (char *) emalloc(Z_STRLEN(tmp.u.constant)+1); memcpy(Z_STRVAL(tmp.u.constant), Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace))]), "\\", sizeof("\\")-1); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace)) + sizeof("\\")-1]), Z_STRVAL(element_name->u.constant), Z_STRLEN(element_name->u.constant)+1); STR_FREE(Z_STRVAL(element_name->u.constant)); *element_name = tmp; } } /* }}} */ void zend_resolve_class_name(znode *class_name, ulong fetch_type, int check_ns_name TSRMLS_DC) /* {{{ */ { char *compound; char *lcname; zval **ns; znode tmp; int len; compound = memchr(Z_STRVAL(class_name->u.constant), '\\', Z_STRLEN(class_name->u.constant)); if (compound) { /* This is a compound class name that contains namespace prefix */ if (Z_STRVAL(class_name->u.constant)[0] == '\\') { /* The STRING name has "\" prefix */ Z_STRLEN(class_name->u.constant) -= 1; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+1, Z_STRLEN(class_name->u.constant)+1); Z_STRVAL(class_name->u.constant) = erealloc( Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1); if (ZEND_FETCH_CLASS_DEFAULT != zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "'\\%s' is an invalid class name", Z_STRVAL(class_name->u.constant)); } } else { if (CG(current_import)) { len = compound - Z_STRVAL(class_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(class_name->u.constant) -= len; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+len, Z_STRLEN(class_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; efree(lcname); return; } efree(lcname); } /* Here name is not prefixed with \ and not imported */ if (CG(current_namespace)) { tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } } } else if (CG(current_import) || CG(current_namespace)) { /* this is a plain name (without \) */ lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns) == SUCCESS) { /* The given name is an import name. Substitute it. */ zval_dtor(&class_name->u.constant); class_name->u.constant = **ns; zval_copy_ctor(&class_name->u.constant); } else if (CG(current_namespace)) { /* plain name, no import - prepend current namespace to it */ tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } efree(lcname); } } /* }}} */ void zend_do_fetch_class(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { long fetch_class_op_number; zend_op *opline; if (class_name->op_type == IS_CONST && Z_TYPE(class_name->u.constant) == IS_STRING && Z_STRLEN(class_name->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_name->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } fetch_class_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CLASS; SET_UNUSED(opline->op1); opline->extended_value = ZEND_FETCH_CLASS_GLOBAL; CG(catch_begin) = fetch_class_op_number; if (class_name->op_type == IS_CONST) { int fetch_type; fetch_type = zend_get_class_fetch_type(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); switch (fetch_type) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: SET_UNUSED(opline->op2); opline->extended_value = fetch_type; zval_dtor(&class_name->u.constant); break; default: zend_resolve_class_name(class_name, opline->extended_value, 0 TSRMLS_CC); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_name->u.constant TSRMLS_CC); break; } } else { SET_NODE(opline->op2, class_name); } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; /* FIXME: Hack so that INIT_FCALL_BY_NAME still knows this is a class */ GET_NODE(result, opline->result); result->EA = opline->extended_value; } /* }}} */ void zend_do_label(znode *label TSRMLS_DC) /* {{{ */ { zend_label dest; if (!CG(context).labels) { ALLOC_HASHTABLE(CG(context).labels); zend_hash_init(CG(context).labels, 4, NULL, NULL, 0); } dest.brk_cont = CG(context).current_brk_cont; dest.opline_num = get_next_op_number(CG(active_op_array)); if (zend_hash_add(CG(context).labels, Z_STRVAL(label->u.constant), Z_STRLEN(label->u.constant) + 1, (void**)&dest, sizeof(zend_label), NULL) == FAILURE) { zend_error(E_COMPILE_ERROR, "Label '%s' already defined", Z_STRVAL(label->u.constant)); } /* Done with label now */ zval_dtor(&label->u.constant); } /* }}} */ void zend_resolve_goto_label(zend_op_array *op_array, zend_op *opline, int pass2 TSRMLS_DC) /* {{{ */ { zend_label *dest; long current, distance; zval *label; if (pass2) { label = opline->op2.zv; } else { label = &CONSTANT_EX(op_array, opline->op2.constant); } if (CG(context).labels == NULL || zend_hash_find(CG(context).labels, Z_STRVAL_P(label), Z_STRLEN_P(label)+1, (void**)&dest) == FAILURE) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; zend_error(E_COMPILE_ERROR, "'goto' to undefined label '%s'", Z_STRVAL_P(label)); } else { /* Label is not defined. Delay to pass 2. */ INC_BPC(op_array); return; } } opline->op1.opline_num = dest->opline_num; zval_dtor(label); Z_TYPE_P(label) = IS_NULL; /* Check that we are not moving into loop or switch */ current = opline->extended_value; for (distance = 0; current != dest->brk_cont; distance++) { if (current == -1) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; } zend_error(E_COMPILE_ERROR, "'goto' into loop or switch statement is disallowed"); } current = op_array->brk_cont_array[current].parent; } if (distance == 0) { /* Nothing to break out of, optimize to ZEND_JMP */ opline->opcode = ZEND_JMP; opline->extended_value = 0; SET_UNUSED(opline->op2); } else { /* Set real break distance */ ZVAL_LONG(label, distance); } if (pass2) { DEC_BPC(op_array); } } /* }}} */ void zend_do_goto(const znode *label TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_GOTO; opline->extended_value = CG(context).current_brk_cont; SET_UNUSED(opline->op1); SET_NODE(opline->op2, label); zend_resolve_goto_label(CG(active_op_array), opline, 0 TSRMLS_CC); } /* }}} */ void zend_release_labels(TSRMLS_D) /* {{{ */ { if (CG(context).labels) { zend_hash_destroy(CG(context).labels); FREE_HASHTABLE(CG(context).labels); } if (!zend_stack_is_empty(&CG(context_stack))) { zend_compiler_context *ctx; zend_stack_top(&CG(context_stack), (void**)&ctx); CG(context) = *ctx; zend_stack_del_top(&CG(context_stack)); } } /* }}} */ void zend_do_build_full_name(znode *result, znode *prefix, znode *name, int is_class_member TSRMLS_DC) /* {{{ */ { zend_uint length; if (!result) { result = prefix; } else { *result = *prefix; } if (is_class_member) { length = sizeof("::")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "::", sizeof("::")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("::")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } else { length = sizeof("\\")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "\\", sizeof("\\")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("\\")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } } /* }}} */ int zend_do_begin_class_member_function_call(znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { znode class_node; unsigned char *ptr = NULL; zend_op *opline; if (method_name->op_type == IS_CONST) { char *lcname = zend_str_tolower_dup(Z_STRVAL(method_name->u.constant), Z_STRLEN(method_name->u.constant)); if ((sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == Z_STRLEN(method_name->u.constant) && memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == 0) { zval_dtor(&method_name->u.constant); method_name->op_type = IS_UNUSED; } efree(lcname); } if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; opline = get_next_op(CG(active_op_array) TSRMLS_CC); } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->extended_value = class_node.EA ; } opline->opcode = ZEND_INIT_STATIC_METHOD_CALL; if (class_node.op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, &class_node); } if (method_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &method_name->u.constant TSRMLS_CC); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } } else { SET_NODE(opline->op2, method_name); } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 1; /* Dynamic */ } /* }}} */ void zend_do_end_function_call(znode *function_name, znode *result, const znode *argument_list, int is_method, int is_dynamic_fcall TSRMLS_DC) /* {{{ */ { zend_op *opline; if (is_method && function_name && function_name->op_type == IS_UNUSED) { /* clone */ if (Z_LVAL(argument_list->u.constant) != 0) { zend_error(E_WARNING, "Clone method does not require arguments"); } opline = &CG(active_op_array)->opcodes[Z_LVAL(function_name->u.constant)]; } else { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (!is_method && !is_dynamic_fcall && function_name->op_type==IS_CONST) { opline->opcode = ZEND_DO_FCALL; SET_NODE(opline->op1, function_name); CALCULATE_LITERAL_HASH(opline->op1.constant); GET_CACHE_SLOT(opline->op1.constant); } else { opline->opcode = ZEND_DO_FCALL_BY_NAME; SET_UNUSED(opline->op1); } } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(result, opline->result) ; SET_UNUSED(opline->op2); zend_stack_del_top(&CG(function_call_stack)); opline->extended_value = Z_LVAL(argument_list->u.constant); } /* }}} */ void zend_do_pass_param(znode *param, zend_uchar op, int offset TSRMLS_DC) /* {{{ */ { zend_op *opline; int original_op=op; zend_function **function_ptr_ptr, *function_ptr; int send_by_reference; int send_function = 0; zend_stack_top(&CG(function_call_stack), (void **) &function_ptr_ptr); function_ptr = *function_ptr_ptr; if (original_op == ZEND_SEND_REF) { if (function_ptr && function_ptr->common.function_name && function_ptr->common.type == ZEND_USER_FUNCTION && !ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed; " "If you would like to pass argument by reference, modify the declaration of %s().", function_ptr->common.function_name); } else { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed"); } return; } if (function_ptr) { if (ARG_MAY_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { if (param->op_type & (IS_VAR|IS_CV) && original_op != ZEND_SEND_VAL) { send_by_reference = 1; if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION | ZEND_ARG_SEND_SILENT; } } else { op = ZEND_SEND_VAL; send_by_reference = 0; } } else { send_by_reference = ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset) ? ZEND_ARG_SEND_BY_REF : 0; } } else { send_by_reference = 0; } if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION; } else if (op == ZEND_SEND_VAL && (param->op_type & (IS_VAR|IS_CV))) { op = ZEND_SEND_VAR_NO_REF; } if (op!=ZEND_SEND_VAR_NO_REF && send_by_reference==ZEND_ARG_SEND_BY_REF) { /* change to passing by reference */ switch (param->op_type) { case IS_VAR: case IS_CV: op = ZEND_SEND_REF; break; default: zend_error(E_COMPILE_ERROR, "Only variables can be passed by reference"); break; } } if (original_op == ZEND_SEND_VAR) { switch (op) { case ZEND_SEND_VAR_NO_REF: zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); break; case ZEND_SEND_VAR: if (function_ptr) { zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(param, BP_VAR_FUNC_ARG, offset TSRMLS_CC); } break; case ZEND_SEND_REF: zend_do_end_variable_parse(param, BP_VAR_W, 0 TSRMLS_CC); break; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (op == ZEND_SEND_VAR_NO_REF) { if (function_ptr) { opline->extended_value = ZEND_ARG_COMPILE_TIME_BOUND | send_by_reference | send_function; } else { opline->extended_value = send_function; } } else { if (function_ptr) { opline->extended_value = ZEND_DO_FCALL; } else { opline->extended_value = ZEND_DO_FCALL_BY_NAME; } } opline->opcode = op; SET_NODE(opline->op1, param); opline->op2.opline_num = offset; SET_UNUSED(opline->op2); } /* }}} */ static int generate_free_switch_expr(const zend_switch_entry *switch_entry TSRMLS_DC) /* {{{ */ { zend_op *opline; if (switch_entry->cond.op_type != IS_VAR && switch_entry->cond.op_type != IS_TMP_VAR) { return (switch_entry->cond.op_type == IS_UNUSED); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry->cond); SET_UNUSED(opline->op2); opline->extended_value = 0; return 0; } /* }}} */ static int generate_free_foreach_copy(const zend_op *foreach_copy TSRMLS_DC) /* {{{ */ { zend_op *opline; /* If we reach the seperator then stop applying the stack */ if (foreach_copy->result_type == IS_UNUSED && foreach_copy->op1_type == IS_UNUSED) { return 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->result_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->result); SET_UNUSED(opline->op2); opline->extended_value = 1; if (foreach_copy->op1_type != IS_UNUSED) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->op1_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->op1); SET_UNUSED(opline->op2); opline->extended_value = 0; } return 0; } /* }}} */ void zend_do_return(znode *expr, int do_end_vparse TSRMLS_DC) /* {{{ */ { zend_op *opline; int start_op_number, end_op_number; if (do_end_vparse) { if ((CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) && !zend_is_function_or_method_call(expr)) { zend_do_end_variable_parse(expr, BP_VAR_W, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(expr, BP_VAR_R, 0 TSRMLS_CC); } } start_op_number = get_next_op_number(CG(active_op_array)); #ifdef ZTS zend_stack_apply_with_argument(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_switch_expr TSRMLS_CC); zend_stack_apply_with_argument(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_foreach_copy TSRMLS_CC); #else zend_stack_apply(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_switch_expr); zend_stack_apply(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_foreach_copy); #endif end_op_number = get_next_op_number(CG(active_op_array)); while (start_op_number < end_op_number) { CG(active_op_array)->opcodes[start_op_number].extended_value |= EXT_TYPE_FREE_ON_RETURN; start_op_number++; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) ? ZEND_RETURN_BY_REF : ZEND_RETURN; if (expr) { SET_NODE(opline->op1, expr); if (do_end_vparse && zend_is_function_or_method_call(expr)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } } else { opline->op1_type = IS_CONST; LITERAL_NULL(opline->op1); } SET_UNUSED(opline->op2); } /* }}} */ static int zend_add_try_element(zend_uint try_op TSRMLS_DC) /* {{{ */ { int try_catch_offset = CG(active_op_array)->last_try_catch++; CG(active_op_array)->try_catch_array = erealloc(CG(active_op_array)->try_catch_array, sizeof(zend_try_catch_element)*CG(active_op_array)->last_try_catch); CG(active_op_array)->try_catch_array[try_catch_offset].try_op = try_op; return try_catch_offset; } /* }}} */ static void zend_add_catch_element(int offset, zend_uint catch_op TSRMLS_DC) /* {{{ */ { CG(active_op_array)->try_catch_array[offset].catch_op = catch_op; } /* }}} */ void zend_do_first_catch(znode *open_parentheses TSRMLS_DC) /* {{{ */ { open_parentheses->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_initialize_try_catch_element(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist jmp_list; zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); zend_add_catch_element(try_token->u.op.opline_num, get_next_op_number(CG(active_op_array)) TSRMLS_CC); } /* }}} */ void zend_do_mark_last_catch(const znode *first_catch, const znode *last_additional_catch TSRMLS_DC) /* {{{ */ { CG(active_op_array)->last--; zend_do_if_end(TSRMLS_C); if (last_additional_catch->u.op.opline_num == -1) { CG(active_op_array)->opcodes[first_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[first_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } else { CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_try(znode *try_token TSRMLS_DC) /* {{{ */ { try_token->u.op.opline_num = zend_add_try_element(get_next_op_number(CG(active_op_array)) TSRMLS_CC); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_catch(znode *try_token, znode *class_name, znode *catch_var, znode *first_catch TSRMLS_DC) /* {{{ */ { long catch_op_number; zend_op *opline; znode catch_class; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); catch_class = *class_name; } else { zend_error(E_COMPILE_ERROR, "Bad class name in the catch statement"); } catch_op_number = get_next_op_number(CG(active_op_array)); if (first_catch) { first_catch->u.op.opline_num = catch_op_number; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CATCH; opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &catch_class.u.constant TSRMLS_CC); opline->op2_type = IS_CV; opline->op2.var = lookup_cv(CG(active_op_array), catch_var->u.constant.value.str.val, catch_var->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(catch_var->u.constant) = (char*)CG(active_op_array)->vars[opline->op2.var].name; opline->result.num = 0; /* 1 means it's the last catch in the block */ try_token->u.op.opline_num = catch_op_number; } /* }}} */ void zend_do_end_catch(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); CG(active_op_array)->opcodes[try_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_throw(const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_THROW; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); } /* }}} */ ZEND_API void function_add_ref(zend_function *function) /* {{{ */ { if (function->type == ZEND_USER_FUNCTION) { zend_op_array *op_array = &function->op_array; (*op_array->refcount)++; if (op_array->static_variables) { HashTable *static_variables = op_array->static_variables; zval *tmp_zval; ALLOC_HASHTABLE(op_array->static_variables); zend_hash_init(op_array->static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(op_array->static_variables, static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_zval, sizeof(zval *)); } op_array->run_time_cache = NULL; } } /* }}} */ static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */ { zend_function *function; if (!ce->parent) { return; } /* You cannot change create_object */ ce->create_object = ce->parent->create_object; /* Inherit special functions if needed */ if (!ce->get_iterator) { ce->get_iterator = ce->parent->get_iterator; } if (!ce->iterator_funcs.funcs) { ce->iterator_funcs.funcs = ce->parent->iterator_funcs.funcs; } if (!ce->__get) { ce->__get = ce->parent->__get; } if (!ce->__set) { ce->__set = ce->parent->__set; } if (!ce->__unset) { ce->__unset = ce->parent->__unset; } if (!ce->__isset) { ce->__isset = ce->parent->__isset; } if (!ce->__call) { ce->__call = ce->parent->__call; } if (!ce->__callstatic) { ce->__callstatic = ce->parent->__callstatic; } if (!ce->__tostring) { ce->__tostring = ce->parent->__tostring; } if (!ce->clone) { ce->clone = ce->parent->clone; } if(!ce->serialize) { ce->serialize = ce->parent->serialize; } if(!ce->unserialize) { ce->unserialize = ce->parent->unserialize; } if (!ce->destructor) { ce->destructor = ce->parent->destructor; } if (ce->constructor) { if (ce->parent->constructor && ce->parent->constructor->common.fn_flags & ZEND_ACC_FINAL) { zend_error(E_ERROR, "Cannot override final %s::%s() with %s::%s()", ce->parent->name, ce->parent->constructor->common.function_name, ce->name, ce->constructor->common.function_name ); } return; } if (zend_hash_find(&ce->parent->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), (void **)&function)==SUCCESS) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), function, sizeof(zend_function), NULL); function_add_ref(function); } else { /* Don't inherit the old style constructor if we already have the new style constructor */ char *lc_class_name; char *lc_parent_class_name; lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); if (!zend_hash_exists(&ce->function_table, lc_class_name, ce->name_length+1)) { lc_parent_class_name = zend_str_tolower_dup(ce->parent->name, ce->parent->name_length); if (!zend_hash_exists(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1) && zend_hash_find(&ce->parent->function_table, lc_parent_class_name, ce->parent->name_length+1, (void **)&function)==SUCCESS) { if (function->common.fn_flags & ZEND_ACC_CTOR) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1, function, sizeof(zend_function), NULL); function_add_ref(function); } } efree(lc_parent_class_name); } efree(lc_class_name); } ce->constructor = ce->parent->constructor; } /* }}} */ char *zend_visibility_string(zend_uint fn_flags) /* {{{ */ { if (fn_flags & ZEND_ACC_PRIVATE) { return "private"; } if (fn_flags & ZEND_ACC_PROTECTED) { return "protected"; } if (fn_flags & ZEND_ACC_PUBLIC) { return "public"; } return ""; } /* }}} */ static void do_inherit_method(zend_function *function) /* {{{ */ { /* The class entry of the derived function intentionally remains the same * as that of the parent class. That allows us to know in which context * we're running, and handle private method calls properly. */ function_add_ref(function); } /* }}} */ static zend_bool zend_do_perform_implementation_check(const zend_function *fe, const zend_function *proto TSRMLS_DC) /* {{{ */ { zend_uint i; /* If it's a user function then arg_info == NULL means we don't have any parameters but * we still need to do the arg number checks. We are only willing to ignore this for internal * functions because extensions don't always define arg_info. */ if (!proto || (!proto->common.arg_info && proto->common.type != ZEND_USER_FUNCTION)) { return 1; } /* Checks for constructors only if they are declared in an interface, * or explicitly marked as abstract */ if ((fe->common.fn_flags & ZEND_ACC_CTOR) && ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)) { return 1; } /* check number of arguments */ if (proto->common.required_num_args < fe->common.required_num_args || proto->common.num_args > fe->common.num_args) { return 0; } if (fe->common.type != ZEND_USER_FUNCTION && (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) != 0 && (fe->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) == 0) { return 0; } /* by-ref constraints on return values are covariant */ if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) { return 0; } for (i=0; i < proto->common.num_args; i++) { if (ZEND_LOG_XOR(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)) { /* Only one has a type hint and the other one doesn't */ return 0; } if (fe->common.arg_info[i].class_name && strcasecmp(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)!=0) { const char *colon; if (fe->common.type != ZEND_USER_FUNCTION) { return 0; } else if (strchr(proto->common.arg_info[i].class_name, '\\') != NULL || (colon = zend_memrchr(fe->common.arg_info[i].class_name, '\\', fe->common.arg_info[i].class_name_len)) == NULL || strcasecmp(colon+1, proto->common.arg_info[i].class_name) != 0) { zend_class_entry **fe_ce, **proto_ce; int found, found2; found = zend_lookup_class(fe->common.arg_info[i].class_name, fe->common.arg_info[i].class_name_len, &fe_ce TSRMLS_CC); found2 = zend_lookup_class(proto->common.arg_info[i].class_name, proto->common.arg_info[i].class_name_len, &proto_ce TSRMLS_CC); /* Check for class alias */ if (found != SUCCESS || found2 != SUCCESS || (*fe_ce)->type == ZEND_INTERNAL_CLASS || (*proto_ce)->type == ZEND_INTERNAL_CLASS || *fe_ce != *proto_ce) { return 0; } } } if (fe->common.arg_info[i].type_hint != proto->common.arg_info[i].type_hint) { /* Incompatible type hint */ return 0; } /* by-ref constraints on arguments are invariant */ if (fe->common.arg_info[i].pass_by_reference != proto->common.arg_info[i].pass_by_reference) { return 0; } } if (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) { for (i=proto->common.num_args; i < fe->common.num_args; i++) { if (!fe->common.arg_info[i].pass_by_reference) { return 0; } } } return 1; } /* }}} */ #define REALLOC_BUF_IF_EXCEED(buf, offset, length, size) \ if (UNEXPECTED(offset - buf + size >= length)) { \ length += size + 1; \ buf = erealloc(buf, length); \ } static char * zend_get_function_declaration(zend_function *fptr TSRMLS_DC) /* {{{ */ { char *offset, *buf; zend_uint length = 1024; offset = buf = (char *)emalloc(length * sizeof(char)); if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { *(offset++) = '&'; *(offset++) = ' '; } if (fptr->common.scope) { memcpy(offset, fptr->common.scope->name, fptr->common.scope->name_length); offset += fptr->common.scope->name_length; *(offset++) = ':'; *(offset++) = ':'; } { size_t name_len = strlen(fptr->common.function_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, name_len); memcpy(offset, fptr->common.function_name, name_len); offset += name_len; } *(offset++) = '('; if (fptr->common.arg_info) { zend_uint i, required; zend_arg_info *arg_info = fptr->common.arg_info; required = fptr->common.required_num_args; for (i = 0; i < fptr->common.num_args;) { if (arg_info->class_name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->class_name_len); memcpy(offset, arg_info->class_name, arg_info->class_name_len); offset += arg_info->class_name_len; *(offset++) = ' '; } else if (arg_info->type_hint) { zend_uint type_name_len; char *type_name = zend_get_type_by_const(arg_info->type_hint); type_name_len = strlen(type_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, type_name_len); memcpy(offset, type_name, type_name_len); offset += type_name_len; *(offset++) = ' '; } if (arg_info->pass_by_reference) { *(offset++) = '&'; } *(offset++) = '$'; if (arg_info->name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->name_len); memcpy(offset, arg_info->name, arg_info->name_len); offset += arg_info->name_len; } else { zend_uint idx = i; memcpy(offset, "param", 5); offset += 5; do { *(offset++) = (char) (idx % 10) + '0'; idx /= 10; } while (idx > 0); } if (i >= required) { *(offset++) = ' '; *(offset++) = '='; *(offset++) = ' '; if (fptr->type == ZEND_USER_FUNCTION) { zend_op *precv = NULL; { zend_uint idx = i; zend_op *op = ((zend_op_array *)fptr)->opcodes; zend_op *end = op + ((zend_op_array *)fptr)->last; ++idx; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT) && op->op1.num == (long)idx) { precv = op; } ++op; } } if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) { zval *zv, zv_copy; int use_copy; ALLOC_ZVAL(zv); *zv = *precv->op2.zv; zval_copy_ctor(zv); INIT_PZVAL(zv); zval_update_constant_ex(&zv, (void*)1, fptr->common.scope TSRMLS_CC); if (Z_TYPE_P(zv) == IS_BOOL) { if (Z_LVAL_P(zv)) { memcpy(offset, "true", 4); offset += 4; } else { memcpy(offset, "false", 5); offset += 5; } } else if (Z_TYPE_P(zv) == IS_NULL) { memcpy(offset, "NULL", 4); offset += 4; } else if (Z_TYPE_P(zv) == IS_STRING) { *(offset++) = '\''; REALLOC_BUF_IF_EXCEED(buf, offset, length, MIN(Z_STRLEN_P(zv), 10)); memcpy(offset, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 10)); offset += MIN(Z_STRLEN_P(zv), 10); if (Z_STRLEN_P(zv) > 10) { *(offset++) = '.'; *(offset++) = '.'; *(offset++) = '.'; } *(offset++) = '\''; } else if (Z_TYPE_P(zv) == IS_ARRAY) { memcpy(offset, "Array", 5); offset += 5; } else { zend_make_printable_zval(zv, &zv_copy, &use_copy); REALLOC_BUF_IF_EXCEED(buf, offset, length, Z_STRLEN(zv_copy)); memcpy(offset, Z_STRVAL(zv_copy), Z_STRLEN(zv_copy)); offset += Z_STRLEN(zv_copy); if (use_copy) { zval_dtor(&zv_copy); } } zval_ptr_dtor(&zv); } } else { memcpy(offset, "NULL", 4); offset += 4; } } if (++i < fptr->common.num_args) { *(offset++) = ','; *(offset++) = ' '; } arg_info++; REALLOC_BUF_IF_EXCEED(buf, offset, length, 32); } } *(offset++) = ')'; *offset = '\0'; return buf; } /* }}} */ static void do_inheritance_check_on_method(zend_function *child, zend_function *parent TSRMLS_DC) /* {{{ */ { zend_uint child_flags; zend_uint parent_flags = parent->common.fn_flags; if (parent->common.fn_flags & ZEND_ACC_ABSTRACT && parent->common.scope != (child->common.prototype ? child->common.prototype->common.scope : child->common.scope) && child->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_IMPLEMENTED_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Can't inherit abstract function %s::%s() (previously declared abstract in %s)", parent->common.scope->name, child->common.function_name, child->common.prototype ? child->common.prototype->common.scope->name : child->common.scope->name); } if (parent_flags & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot override final method %s::%s()", ZEND_FN_SCOPE_NAME(parent), child->common.function_name); } child_flags = child->common.fn_flags; /* You cannot change from static to non static and vice versa. */ if ((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC)) { if (child->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot make non static method %s::%s() static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } else { zend_error(E_COMPILE_ERROR, "Cannot make static method %s::%s() non static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } } /* Disallow making an inherited method abstract. */ if ((child_flags & ZEND_ACC_ABSTRACT) && !(parent_flags & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Cannot make non abstract method %s::%s() abstract in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } if (parent_flags & ZEND_ACC_CHANGED) { child->common.fn_flags |= ZEND_ACC_CHANGED; } else { /* Prevent derived classes from restricting access that was available in parent classes */ if ((child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::%s() must be %s (as in class %s)%s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if (((child_flags & ZEND_ACC_PPP_MASK) < (parent_flags & ZEND_ACC_PPP_MASK)) && ((parent_flags & ZEND_ACC_PPP_MASK) & ZEND_ACC_PRIVATE)) { child->common.fn_flags |= ZEND_ACC_CHANGED; } } if (parent_flags & ZEND_ACC_PRIVATE) { child->common.prototype = NULL; } else if (parent_flags & ZEND_ACC_ABSTRACT) { child->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; child->common.prototype = parent; } else if (!(parent->common.fn_flags & ZEND_ACC_CTOR) || (parent->common.prototype && (parent->common.prototype->common.scope->ce_flags & ZEND_ACC_INTERFACE))) { /* ctors only have a prototype if it comes from an interface */ child->common.prototype = parent->common.prototype ? parent->common.prototype : parent; } if (child->common.prototype && (child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { if (!zend_do_perform_implementation_check(child, child->common.prototype TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s::%s() must be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_get_function_declaration(child->common.prototype TSRMLS_CC)); } } else if (EG(error_reporting) & E_STRICT || EG(user_error_handler)) { /* Check E_STRICT (or custom error handler) before the check so that we save some time */ if (!zend_do_perform_implementation_check(child, parent TSRMLS_CC)) { char *method_prototype = zend_get_function_declaration(child->common.prototype TSRMLS_CC); zend_error(E_STRICT, "Declaration of %s::%s() should be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, method_prototype); efree(method_prototype); } } } /* }}} */ static zend_bool do_inherit_method_check(HashTable *child_function_table, zend_function *parent, const zend_hash_key *hash_key, zend_class_entry *child_ce) /* {{{ */ { zend_uint parent_flags = parent->common.fn_flags; zend_function *child; TSRMLS_FETCH(); if (zend_hash_quick_find(child_function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child)==FAILURE) { if (parent_flags & (ZEND_ACC_ABSTRACT)) { child_ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } return 1; /* method doesn't exist in child, copy from parent */ } do_inheritance_check_on_method(child, parent TSRMLS_CC); return 0; } /* }}} */ static zend_bool do_inherit_property_access_check(HashTable *target_ht, zend_property_info *parent_info, const zend_hash_key *hash_key, zend_class_entry *ce) /* {{{ */ { zend_property_info *child_info; zend_class_entry *parent_ce = ce->parent; if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW)) { if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { child_info->flags |= ZEND_ACC_CHANGED; } else { zend_hash_quick_update(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, parent_info, sizeof(zend_property_info), (void **) &child_info); if(ce->type & ZEND_INTERNAL_CLASS) { zend_duplicate_property_info_internal(child_info); } else { zend_duplicate_property_info(child_info); } child_info->flags &= ~ZEND_ACC_PRIVATE; /* it's not private anymore */ child_info->flags |= ZEND_ACC_SHADOW; /* but it's a shadow of private */ } return 0; /* don't copy access information to child */ } if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { if ((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s", (parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", parent_ce->name, hash_key->arKey, (child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ce->name, hash_key->arKey); } if(parent_info->flags & ZEND_ACC_CHANGED) { child_info->flags |= ZEND_ACC_CHANGED; } if ((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ce->name, hash_key->arKey, zend_visibility_string(parent_info->flags), parent_ce->name, (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if ((child_info->flags & ZEND_ACC_STATIC) == 0) { Z_DELREF_P(ce->default_properties_table[parent_info->offset]); ce->default_properties_table[parent_info->offset] = ce->default_properties_table[child_info->offset]; ce->default_properties_table[child_info->offset] = NULL; child_info->offset = parent_info->offset; } return 0; /* Don't copy from parent */ } else { return 1; /* Copy from parent */ } } /* }}} */ static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce TSRMLS_CC) == FAILURE) { zend_error(E_CORE_ERROR, "Class %s could not implement interface %s", ce->name, iface->name); } if (ce == iface) { zend_error(E_ERROR, "Interface %s cannot implement itself", ce->name); } } /* }}} */ ZEND_API void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface TSRMLS_DC) /* {{{ */ { /* expects interface to be contained in ce's interface list already */ zend_uint i, ce_num, if_num = iface->num_interfaces; zend_class_entry *entry; if (if_num==0) { return; } ce_num = ce->num_interfaces; if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } /* Inherit the interfaces, only if they're not already inherited by the class */ while (if_num--) { entry = iface->interfaces[if_num]; for (i = 0; i < ce_num; i++) { if (ce->interfaces[i] == entry) { break; } } if (i == ce_num) { ce->interfaces[ce->num_interfaces++] = entry; } } /* and now call the implementing handlers */ while (ce_num < ce->num_interfaces) { do_implement_interface(ce, ce->interfaces[ce_num++] TSRMLS_CC); } } /* }}} */ #ifdef ZTS static void zval_internal_ctor(zval **p) /* {{{ */ { zval *orig_ptr = *p; ALLOC_ZVAL(*p); MAKE_COPY_ZVAL(&orig_ptr, *p); } /* }}} */ # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) (((parent_ce)->type != (ce)->type) ? zval_internal_ctor : zval_add_ref)) #else # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) zval_add_ref) #endif ZEND_API void zend_do_inheritance(zend_class_entry *ce, zend_class_entry *parent_ce TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; if ((ce->ce_flags & ZEND_ACC_INTERFACE) && !(parent_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ce->name, parent_ce->name); } if (parent_ce->ce_flags & ZEND_ACC_FINAL_CLASS) { zend_error(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ce->name, parent_ce->name); } ce->parent = parent_ce; /* Copy serialize/unserialize callbacks */ if (!ce->serialize) { ce->serialize = parent_ce->serialize; } if (!ce->unserialize) { ce->unserialize = parent_ce->unserialize; } /* Inherit interfaces */ zend_do_inherit_interfaces(ce, parent_ce TSRMLS_CC); /* Inherit properties */ if (parent_ce->default_properties_count) { int i = ce->default_properties_count + parent_ce->default_properties_count; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_properties_count) { while (i-- > parent_ce->default_properties_count) { ce->default_properties_table[i] = ce->default_properties_table[i - parent_ce->default_properties_count]; } } for (i = 0; i < parent_ce->default_properties_count; i++) { ce->default_properties_table[i] = parent_ce->default_properties_table[i]; if (ce->default_properties_table[i]) { #ifdef ZTS if (parent_ce->type != ce->type) { zval *p; ALLOC_ZVAL(p); MAKE_COPY_ZVAL(&ce->default_properties_table[i], p); ce->default_properties_table[i] = p; } else { Z_ADDREF_P(ce->default_properties_table[i]); } #else Z_ADDREF_P(ce->default_properties_table[i]); #endif } } ce->default_properties_count += parent_ce->default_properties_count; } if (parent_ce->type != ce->type) { /* User class extends internal class */ zend_update_class_constants(parent_ce TSRMLS_CC); if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = erealloc(ce->default_static_members_table, sizeof(void*) * i); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&CE_STATIC_MEMBERS(parent_ce)[i]); ce->default_static_members_table[i] = CE_STATIC_MEMBERS(parent_ce)[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; ce->static_members_table = ce->default_static_members_table; } } else { if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&parent_ce->default_static_members_table[i]); ce->default_static_members_table[i] = parent_ce->default_static_members_table[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } } for (zend_hash_internal_pointer_reset(&ce->properties_info); zend_hash_get_current_data(&ce->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->properties_info)) { if (property_info->ce == ce) { if (property_info->flags & ZEND_ACC_STATIC) { property_info->offset += parent_ce->default_static_members_count; } else { property_info->offset += parent_ce->default_properties_count; } } } zend_hash_merge_ex(&ce->properties_info, &parent_ce->properties_info, (copy_ctor_func_t) (ce->type & ZEND_INTERNAL_CLASS ? zend_duplicate_property_info_internal : zend_duplicate_property_info), sizeof(zend_property_info), (merge_checker_func_t) do_inherit_property_access_check, ce); zend_hash_merge(&ce->constants_table, &parent_ce->constants_table, zval_property_ctor(parent_ce, ce), NULL, sizeof(zval *), 0); zend_hash_merge_ex(&ce->function_table, &parent_ce->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_inherit_parent_constructor(ce); if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS && ce->type == ZEND_INTERNAL_CLASS) { ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } else if (!(ce->ce_flags & ZEND_ACC_IMPLEMENT_INTERFACES) && !(ce->ce_flags & ZEND_ACC_IMPLEMENT_TRAITS)) { /* The verification will be done in runtime by ZEND_VERIFY_ABSTRACT_CLASS */ zend_verify_abstract_class(ce TSRMLS_CC); } ce->ce_flags |= parent_ce->ce_flags & ZEND_HAS_STATIC_IN_METHODS; } /* }}} */ static zend_bool do_inherit_constant_check(HashTable *child_constants_table, const zval **parent_constant, const zend_hash_key *hash_key, const zend_class_entry *iface) /* {{{ */ { zval **old_constant; if (zend_hash_quick_find(child_constants_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**)&old_constant) == SUCCESS) { if (*old_constant != *parent_constant) { zend_error(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", hash_key->arKey, iface->name); } return 0; } return 1; } /* }}} */ static int do_interface_constant_check(zval **val TSRMLS_DC, int num_args, va_list args, const zend_hash_key *key) /* {{{ */ { zend_class_entry **iface = va_arg(args, zend_class_entry**); do_inherit_constant_check(&(*iface)->constants_table, (const zval **) val, key, *iface); return ZEND_HASH_APPLY_KEEP; } /* }}} */ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_iface_num = ce->num_interfaces; zend_uint parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0; for (i = 0; i < ce->num_interfaces; i++) { if (ce->interfaces[i] == NULL) { memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i)); i--; } else if (ce->interfaces[i] == iface) { if (i < parent_iface_num) { ignore = 1; } else { zend_error(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ce->name, iface->name); } } } if (ignore) { /* Check for attempt to redeclare interface constants */ zend_hash_apply_with_arguments(&ce->constants_table TSRMLS_CC, (apply_func_args_t) do_interface_constant_check, 1, &iface); } else { if (ce->num_interfaces >= current_iface_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } } ce->interfaces[ce->num_interfaces++] = iface; zend_hash_merge_ex(&ce->constants_table, &iface->constants_table, (copy_ctor_func_t) zval_add_ref, sizeof(zval *), (merge_checker_func_t) do_inherit_constant_check, iface); zend_hash_merge_ex(&ce->function_table, &iface->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_implement_interface(ce, iface TSRMLS_CC); zend_do_inherit_interfaces(ce, iface TSRMLS_CC); } } /* }}} */ ZEND_API void zend_do_implement_trait(zend_class_entry *ce, zend_class_entry *trait TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_trait_num = ce->num_traits; zend_uint parent_trait_num = ce->parent ? ce->parent->num_traits : 0; for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == NULL) { memmove(ce->traits + i, ce->traits + i + 1, sizeof(zend_class_entry*) * (--ce->num_traits - i)); i--; } else if (ce->traits[i] == trait) { if (i < parent_trait_num) { ignore = 1; } } } if (!ignore) { if (ce->num_traits >= current_trait_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->traits = (zend_class_entry **) realloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } else { ce->traits = (zend_class_entry **) erealloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } } ce->traits[ce->num_traits++] = trait; } } /* }}} */ static int zend_traits_merge_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { size_t current; size_t i; size_t count; HashTable* resulting_table; HashTable** function_tables; zend_class_entry *ce; size_t collision = 0; size_t abstract_solved = 0; zend_function* other_trait_fn; current = va_arg(args, size_t); /* index of current trait */ count = va_arg(args, size_t); resulting_table = va_arg(args, HashTable*); function_tables = va_arg(args, HashTable**); ce = va_arg(args, zend_class_entry*); for (i = 0; i < count; i++) { if (i == current) { continue; /* just skip this, cause its the table this function is applied on */ } if (zend_hash_quick_find(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&other_trait_fn) == SUCCESS) { /* if it is an abstract method, there is no collision */ if (other_trait_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* In case both are abstract, just check prototype, but need to do that in both directions */ if ( !zend_do_perform_implementation_check(fn, other_trait_fn TSRMLS_CC) || !zend_do_perform_implementation_check(other_trait_fn, fn TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s must be compatible with %s", //ZEND_FN_SCOPE_NAME(fn), fn->common.function_name, //::%s() zend_get_function_declaration(fn TSRMLS_CC), zend_get_function_declaration(other_trait_fn TSRMLS_CC)); } } else { /* otherwise, do the full check */ do_inheritance_check_on_method(fn, other_trait_fn TSRMLS_CC); } /* we can savely free and remove it from other table */ zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } else { /* if it is not an abstract method, there is still no collision */ /* if fn is an abstract method */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible. Here, we already know other_trait_fn cannot be abstract, full check ok. */ do_inheritance_check_on_method(other_trait_fn, fn TSRMLS_CC); /* just mark as solved, will be added if its own trait is processed */ abstract_solved = 1; } else { /* but else, we have a collision of non-abstract methods */ collision++; zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } } } if (collision) { zend_function* class_fn; /* make sure method is not already overridden in class */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&class_fn) == FAILURE || class_fn->common.scope != ce) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because there are collisions with other trait methods on %s", fn->common.function_name, ce->name); } zend_function_dtor(fn); } else if (abstract_solved) { zend_function_dtor(fn); } else { /* Add it to result function table */ if (zend_hash_quick_add(resulting_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, fn, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating resulting trait method table", fn->common.function_name); } } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ /* {{{ Originates from php_runkit_function_copy_ctor Duplicate structures in an op_array where necessary to make an outright duplicate */ static void zend_traits_duplicate_function(zend_function *fe, zend_class_entry *target_ce, char *newname TSRMLS_DC) { zend_literal *literals_copy; zend_compiled_variable *dupvars; zend_op *opcode_copy; zval class_name_zv; int class_name_literal; int i; int number_of_literals; if (fe->op_array.static_variables) { HashTable *tmpHash; ALLOC_HASHTABLE(tmpHash); zend_hash_init(tmpHash, zend_hash_num_elements(fe->op_array.static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_apply_with_arguments(fe->op_array.static_variables TSRMLS_CC, (apply_func_args_t)zval_copy_static_var, 1, tmpHash); fe->op_array.static_variables = tmpHash; } number_of_literals = fe->op_array.last_literal; literals_copy = (zend_literal*)emalloc(number_of_literals * sizeof(zend_literal)); for (i = 0; i < number_of_literals; i++) { literals_copy[i] = fe->op_array.literals[i]; zval_copy_ctor(&literals_copy[i].constant); } fe->op_array.literals = literals_copy; fe->op_array.refcount = emalloc(sizeof(zend_uint)); *(fe->op_array.refcount) = 1; if (fe->op_array.vars) { i = fe->op_array.last_var; dupvars = safe_emalloc(fe->op_array.last_var, sizeof(zend_compiled_variable), 0); while (i > 0) { i--; dupvars[i].name = estrndup(fe->op_array.vars[i].name, fe->op_array.vars[i].name_len); dupvars[i].name_len = fe->op_array.vars[i].name_len; dupvars[i].hash_value = fe->op_array.vars[i].hash_value; } fe->op_array.vars = dupvars; } else { fe->op_array.vars = NULL; } opcode_copy = safe_emalloc(sizeof(zend_op), fe->op_array.last, 0); for(i = 0; i < fe->op_array.last; i++) { opcode_copy[i] = fe->op_array.opcodes[i]; if (opcode_copy[i].op1_type != IS_CONST) { switch (opcode_copy[i].opcode) { case ZEND_GOTO: case ZEND_JMP: if (opcode_copy[i].op1.jmp_addr && opcode_copy[i].op1.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op1.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op1.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op1.jmp_addr - fe->op_array.opcodes); } break; } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op1.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op1.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op1.zv = &fe->op_array.literals[class_name_literal].constant; } } if (opcode_copy[i].op2_type != IS_CONST) { switch (opcode_copy[i].opcode) { case ZEND_JMPZ: case ZEND_JMPNZ: case ZEND_JMPZ_EX: case ZEND_JMPNZ_EX: case ZEND_JMP_SET: case ZEND_JMP_SET_VAR: if (opcode_copy[i].op2.jmp_addr && opcode_copy[i].op2.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op2.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op2.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op2.jmp_addr - fe->op_array.opcodes); } break; } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op2.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op2.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op2.zv = &fe->op_array.literals[class_name_literal].constant; } } } fe->op_array.opcodes = opcode_copy; fe->op_array.function_name = newname; /* was setting it to fe which does not work since fe is stack allocated and not a stable address */ /* fe->op_array.prototype = fe->op_array.prototype; */ if (fe->op_array.arg_info) { zend_arg_info *tmpArginfo; tmpArginfo = safe_emalloc(sizeof(zend_arg_info), fe->op_array.num_args, 0); for(i = 0; i < fe->op_array.num_args; i++) { tmpArginfo[i] = fe->op_array.arg_info[i]; tmpArginfo[i].name = estrndup(tmpArginfo[i].name, tmpArginfo[i].name_len); if (tmpArginfo[i].class_name) { tmpArginfo[i].class_name = estrndup(tmpArginfo[i].class_name, tmpArginfo[i].class_name_len); } } fe->op_array.arg_info = tmpArginfo; } fe->op_array.doc_comment = estrndup(fe->op_array.doc_comment, fe->op_array.doc_comment_len); fe->op_array.try_catch_array = (zend_try_catch_element*)estrndup((char*)fe->op_array.try_catch_array, sizeof(zend_try_catch_element) * fe->op_array.last_try_catch); fe->op_array.brk_cont_array = (zend_brk_cont_element*)estrndup((char*)fe->op_array.brk_cont_array, sizeof(zend_brk_cont_element) * fe->op_array.last_brk_cont); } /* }}} */ static void zend_add_magic_methods(zend_class_entry* ce, const char* mname, uint mname_len, zend_function* fe TSRMLS_DC) /* {{{ */ { if (!strncmp(mname, ZEND_CLONE_FUNC_NAME, mname_len)) { ce->clone = fe; fe->common.fn_flags |= ZEND_ACC_CLONE; } else if (!strncmp(mname, ZEND_CONSTRUCTOR_FUNC_NAME, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } else if (!strncmp(mname, ZEND_DESTRUCTOR_FUNC_NAME, mname_len)) { ce->destructor = fe; fe->common.fn_flags |= ZEND_ACC_DTOR; } else if (!strncmp(mname, ZEND_GET_FUNC_NAME, mname_len)) ce->__get = fe; else if (!strncmp(mname, ZEND_SET_FUNC_NAME, mname_len)) ce->__set = fe; else if (!strncmp(mname, ZEND_CALL_FUNC_NAME, mname_len)) ce->__call = fe; else if (!strncmp(mname, ZEND_UNSET_FUNC_NAME, mname_len)) ce->__unset = fe; else if (!strncmp(mname, ZEND_ISSET_FUNC_NAME, mname_len)) ce->__isset = fe; else if (!strncmp(mname, ZEND_CALLSTATIC_FUNC_NAME, mname_len)) ce->__callstatic= fe; else if (!strncmp(mname, ZEND_TOSTRING_FUNC_NAME, mname_len)) ce->__tostring = fe; else if (ce->name_length + 1 == mname_len) { char *lowercase_name = emalloc(ce->name_length + 1); zend_str_tolower_copy(lowercase_name, ce->name, ce->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, ce->name_length + 1, 1 TSRMLS_CC); if (!memcmp(mname, lowercase_name, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } str_efree(lowercase_name); } } /* }}} */ static int zend_traits_merge_functions_to_class(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zend_class_entry *ce = va_arg(args, zend_class_entry*); int add = 0; zend_function* existing_fn = NULL; zend_function fn_copy, *fn_copy_p; zend_function* prototype = NULL; /* is used to determine the prototype according to the inheritance chain */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &existing_fn) == FAILURE) { add = 1; /* not found */ } else if (existing_fn->common.scope != ce) { add = 1; /* or inherited from other class or interface */ } if (add) { zend_function* parent_function; if (ce->parent && zend_hash_quick_find(&ce->parent->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &parent_function) != FAILURE) { prototype = parent_function; /* ->common.fn_flags |= ZEND_ACC_ABSTRACT; */ /* we got that method in the parent class, and are going to override it, except, if the trait is just asking to have an abstract method implemented. */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* then we clean up an skip this method */ zend_function_dtor(fn); return ZEND_HASH_APPLY_REMOVE; } } fn->common.scope = ce; fn->common.prototype = prototype; if (prototype && (prototype->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT || prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { fn->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; } else if (fn->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT) { /* remove ZEND_ACC_IMPLEMENTED_ABSTRACT flag, think it shouldn't be copied to class */ fn->common.fn_flags = fn->common.fn_flags - ZEND_ACC_IMPLEMENTED_ABSTRACT; } /* check whether the trait method fullfills the inheritance requirements */ if (prototype) { do_inheritance_check_on_method(fn, prototype TSRMLS_CC); } /* one more thing: make sure we properly implement an abstract method */ if (existing_fn && existing_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { do_inheritance_check_on_method(fn, existing_fn TSRMLS_CC); } /* delete inherited fn if the function to be added is not abstract */ if (existing_fn && existing_fn->common.scope != ce && (fn->common.fn_flags & ZEND_ACC_ABSTRACT) == 0) { /* it is just a reference which was added to the subclass while doing the inheritance, so we can deleted now, and will add the overriding method afterwards. Except, if we try to add an abstract function, then we should not delete the inherited one */ zend_hash_quick_del(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h); } if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (fn->op_array.static_variables) { ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, ce, estrdup(fn->common.function_name) TSRMLS_CC); if (zend_hash_quick_update(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, &fn_copy, sizeof(zend_function), (void**)&fn_copy_p)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating class method table", hash_key->arKey); } zend_add_magic_methods(ce, hash_key->arKey, hash_key->nKeyLength, fn_copy_p TSRMLS_CC); zend_function_dtor(fn); } else { zend_function_dtor(fn); } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ static int zend_traits_copy_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { HashTable* target; zend_class_entry *target_ce; zend_trait_alias** aliases; HashTable* exclude_table; char* lcname; unsigned int fnname_len; zend_function fn_copy; void* dummy; size_t i = 0; target = va_arg(args, HashTable*); target_ce = va_arg(args, zend_class_entry*); aliases = va_arg(args, zend_trait_alias**); exclude_table = va_arg(args, HashTable*); fnname_len = strlen(fn->common.function_name); /* apply aliases which are qualified with a class name, there should not be any ambiguity */ if (aliases) { while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias != NULL && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && aliases[i]->trait_method->mname_len == fnname_len && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(aliases[i]->alias, aliases[i]->alias_len) TSRMLS_CC); /* if it is 0, no modifieres has been changed */ if (aliases[i]->modifiers) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } lcname = zend_str_tolower_dup(aliases[i]->alias, aliases[i]->alias_len); if (zend_hash_add(target, lcname, aliases[i]->alias_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add aliased trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } efree(lcname); } i++; } } lcname = zend_str_tolower_dup(fn->common.function_name, fnname_len); if (exclude_table == NULL || zend_hash_find(exclude_table, lcname, fnname_len, &dummy) == FAILURE) { /* is not in hashtable, thus, function is not to be excluded */ fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(fn->common.function_name, fnname_len) TSRMLS_CC); /* apply aliases which are not qualified by a class name, or which have not * alias name, just setting visibility */ if (aliases) { i = 0; while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias == NULL && aliases[i]->modifiers != 0 && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && (aliases[i]->trait_method->mname_len == fnname_len) && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } i++; } } if (zend_hash_add(target, lcname, fnname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } } efree(lcname); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* Copies function table entries to target function table with applied aliasing */ static void zend_traits_copy_trait_function_table(HashTable *target, zend_class_entry *target_ce, HashTable *source, zend_trait_alias** aliases, HashTable* exclude_table TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_arguments(source TSRMLS_CC, (apply_func_args_t)zend_traits_copy_functions, 4, target, target_ce, aliases, exclude_table); } /* }}} */ static void zend_traits_init_trait_structures(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i, j = 0; zend_trait_precedence *cur_precedence; zend_trait_method_reference *cur_method_ref; /* resolve class references */ if (ce->trait_precedences) { i = 0; while ((cur_precedence = ce->trait_precedences[i])) { if (cur_precedence->exclude_from_classes) { cur_precedence->trait_method->ce = zend_fetch_class(cur_precedence->trait_method->class_name, cur_precedence->trait_method->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); j = 0; while (cur_precedence->exclude_from_classes[j]) { char* class_name = (char*)cur_precedence->exclude_from_classes[j]; zend_uint name_length = strlen(class_name); cur_precedence->exclude_from_classes[j] = zend_fetch_class(class_name, name_length, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); efree(class_name); j++; } } i++; } } if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { if (ce->trait_aliases[i]->trait_method->class_name) { cur_method_ref = ce->trait_aliases[i]->trait_method; cur_method_ref->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); } i++; } } } /* }}} */ static void zend_traits_compile_exclude_table(HashTable* exclude_table, zend_trait_precedence **precedences, zend_class_entry *trait) /* {{{ */ { size_t i = 0, j; if (!precedences) { return; } while (precedences[i]) { if (precedences[i]->exclude_from_classes) { j = 0; while (precedences[i]->exclude_from_classes[j]) { if (precedences[i]->exclude_from_classes[j] == trait) { zend_uint lcname_len = precedences[i]->trait_method->mname_len; char *lcname = zend_str_tolower_dup(precedences[i]->trait_method->method_name, lcname_len); if (zend_hash_add(exclude_table, lcname, lcname_len, NULL, 0, NULL) == FAILURE) { efree(lcname); zend_error(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", precedences[i]->trait_method->method_name, trait->name); } efree(lcname); } ++j; } } ++i; } } /* }}} */ static void zend_do_traits_method_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { HashTable** function_tables; HashTable* resulting_table; HashTable exclude_table; size_t i; /* prepare copies of trait function tables for combination */ function_tables = malloc(sizeof(HashTable*) * ce->num_traits); resulting_table = (HashTable *) malloc(sizeof(HashTable)); /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(resulting_table, 10, NULL, NULL, 1, 0); for (i = 0; i < ce->num_traits; i++) { function_tables[i] = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(function_tables[i], ce->traits[i]->function_table.nNumOfElements, NULL, NULL, 1, 0); if (ce->trait_precedences) { /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(&exclude_table, 2, NULL, NULL, 0, 0); zend_traits_compile_exclude_table(&exclude_table, ce->trait_precedences, ce->traits[i]); /* copies functions, applies defined aliasing, and excludes unused trait methods */ zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, &exclude_table TSRMLS_CC); zend_hash_graceful_destroy(&exclude_table); } else { zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, NULL TSRMLS_CC); } } /* now merge trait methods */ for (i = 0; i < ce->num_traits; i++) { zend_hash_apply_with_arguments(function_tables[i] TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions, 5, i, ce->num_traits, resulting_table, function_tables, ce); } /* Now the resulting_table contains all trait methods we would have to * add to the class in the following step the methods are inserted into the method table * if there is already a method with the same name it is replaced iff ce != fn.scope * --> all inherited methods are overridden, methods defined in the class are left untouched */ zend_hash_apply_with_arguments(resulting_table TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions_to_class, 1, ce); /* free temporary function tables */ for (i = 0; i < ce->num_traits; i++) { /* zend_hash_destroy(function_tables[i]); */ zend_hash_graceful_destroy(function_tables[i]); free(function_tables[i]); } free(function_tables); /* free temporary resulting table */ /* zend_hash_destroy(resulting_table); */ zend_hash_graceful_destroy(resulting_table); free(resulting_table); } /* }}} */ static zend_class_entry* find_first_definition(zend_class_entry *ce, size_t current_trait, const char* prop_name, int prop_name_length, ulong prop_hash, zend_class_entry *coliding_ce) /* {{{ */ { size_t i; zend_property_info *coliding_prop; for (i = 0; (i < current_trait) && (i < ce->num_traits); i++) { if (zend_hash_quick_find(&ce->traits[i]->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS) { return ce->traits[i]; } } return coliding_ce; } /* }}} */ static void zend_do_traits_property_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i; zend_property_info *property_info; zend_property_info *coliding_prop; zval compare_result; const char* prop_name; int prop_name_length; ulong prop_hash; const char* class_name_unused; zend_bool prop_found; zend_bool not_compatible; zval* prop_value; /* In the following steps the properties are inserted into the property table * for that, a very strict approach is applied: * - check for compatibility, if not compatible with any property in class -> fatal * - if compatible, then strict notice */ for (i = 0; i < ce->num_traits; i++) { for (zend_hash_internal_pointer_reset(&ce->traits[i]->properties_info); zend_hash_get_current_data(&ce->traits[i]->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->traits[i]->properties_info)) { /* first get the unmangeld name if necessary, * then check whether the property is already there */ if ((property_info->flags & ZEND_ACC_PPP_MASK) == ZEND_ACC_PUBLIC) { prop_hash = property_info->h; prop_name = property_info->name; prop_name_length = property_info->name_length; prop_found = zend_hash_quick_find(&ce->properties_info, property_info->name, property_info->name_length+1, property_info->h, (void **) &coliding_prop) == SUCCESS; } else { /* for private and protected we need to unmangle the names */ zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name_unused, &prop_name); prop_name_length = strlen(prop_name); prop_hash = zend_get_hash_value(prop_name, prop_name_length + 1); prop_found = zend_hash_quick_find(&ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS; } /* next: check for conflicts with current class */ if (prop_found) { if (coliding_prop->flags & ZEND_ACC_SHADOW) { /* this one is inherited, lets look it up in its own class */ zend_hash_quick_find(&coliding_prop->ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop); } if ((coliding_prop->flags & ZEND_ACC_PPP_MASK) == (property_info->flags & ZEND_ACC_PPP_MASK)) { /* flags are identical, now the value needs to be checked */ if (property_info->flags & ZEND_ACC_STATIC) { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_static_members_table[coliding_prop->offset], ce->traits[i]->default_static_members_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } else { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_properties_table[coliding_prop->offset], ce->traits[i]->default_properties_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } } else { /* the flags are not identical, thus, we assume properties are not compatible */ not_compatible = 1; } if (not_compatible) { zend_error(E_COMPILE_ERROR, "%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } else { zend_error(E_STRICT, "%s and %s define the same property ($%s) in the composition of %s. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } } /* property not found, so lets add it */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); zend_declare_property_ex(ce, prop_name, prop_name_length, prop_value, property_info->flags, property_info->doc_comment, property_info->doc_comment_len TSRMLS_CC); } } } /* }}} */ ZEND_API void zend_do_bind_traits(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { if (ce->num_traits <= 0) { return; } /* complete initialization of trait strutures in ce */ zend_traits_init_trait_structures(ce TSRMLS_CC); /* first care about all methods to be flattened into the class */ zend_do_traits_method_binding(ce TSRMLS_CC); /* then flatten the properties into it, to, mostly to notfiy developer about problems */ zend_do_traits_property_binding(ce TSRMLS_CC); /* verify that all abstract methods from traits have been implemented */ zend_verify_abstract_class(ce TSRMLS_CC); /* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */ if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { ce->ce_flags -= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } } /* }}} */ ZEND_API int do_bind_function(const zend_op_array *op_array, zend_op *opline, HashTable *function_table, zend_bool compile_time) /* {{{ */ { zend_function *function; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } zend_hash_quick_find(function_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void *) &function); if (zend_hash_quick_add(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), function, sizeof(zend_function), NULL)==FAILURE) { int error_level = compile_time ? E_COMPILE_ERROR : E_ERROR; zend_function *old_function; if (zend_hash_quick_find(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), (void *) &old_function)==SUCCESS && old_function->type == ZEND_USER_FUNCTION && old_function->op_array.last > 0) { zend_error(error_level, "Cannot redeclare %s() (previously declared in %s:%d)", function->common.function_name, old_function->op_array.filename, old_function->op_array.opcodes[0].lineno); } else { zend_error(error_level, "Cannot redeclare %s()", function->common.function_name); } return FAILURE; } else { (*function->op_array.refcount)++; function->op_array.static_variables = NULL; /* NULL out the unbound function */ return SUCCESS; } } /* }}} */ void zend_add_trait_precedence(znode *precedence_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_precedences, precedence_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_add_trait_alias(znode *alias_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_aliases, alias_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_prepare_reference(znode *result, znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { zend_trait_method_reference *method_ref = emalloc(sizeof(zend_trait_method_reference)); method_ref->ce = NULL; /* REM: There should not be a need for copying, zend_do_begin_class_declaration is also just using that string */ if (class_name) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); method_ref->class_name = Z_STRVAL(class_name->u.constant); method_ref->cname_len = Z_STRLEN(class_name->u.constant); } else { method_ref->class_name = NULL; method_ref->cname_len = 0; } method_ref->method_name = Z_STRVAL(method_name->u.constant); method_ref->mname_len = Z_STRLEN(method_name->u.constant); result->u.op.ptr = method_ref; result->op_type = IS_TMP_VAR; } /* }}} */ void zend_prepare_trait_alias(znode *result, znode *method_reference, znode *modifiers, znode *alias TSRMLS_DC) /* {{{ */ { zend_trait_alias *trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_alias->modifiers = Z_LVAL(modifiers->u.constant); if (Z_LVAL(modifiers->u.constant) == ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot use 'static' as method modifier"); return; } if (alias) { trait_alias->alias = Z_STRVAL(alias->u.constant); trait_alias->alias_len = Z_STRLEN(alias->u.constant); } else { trait_alias->alias = NULL; } trait_alias->function = NULL; result->u.op.ptr = trait_alias; } /* }}} */ void zend_prepare_trait_precedence(znode *result, znode *method_reference, znode *trait_list TSRMLS_DC) /* {{{ */ { zend_trait_precedence *trait_precedence = emalloc(sizeof(zend_trait_precedence)); trait_precedence->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_precedence->exclude_from_classes = (zend_class_entry**) trait_list->u.op.ptr; trait_precedence->function = NULL; result->u.op.ptr = trait_precedence; } /* }}} */ ZEND_API zend_class_entry *do_bind_class(const zend_op_array* op_array, const zend_op *opline, HashTable *class_table, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } if (zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce)==FAILURE) { zend_error(E_COMPILE_ERROR, "Internal Zend error - Missing class information for %s", Z_STRVAL_P(op1)); return NULL; } else { ce = *pce; } ce->refcount++; if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), &ce, sizeof(zend_class_entry *), NULL)==FAILURE) { ce->refcount--; if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return NULL; } else { if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLEMENT_INTERFACES))) { zend_verify_abstract_class(ce TSRMLS_CC); } return ce; } } /* }}} */ ZEND_API zend_class_entry *do_bind_inherited_class(const zend_op_array *op_array, const zend_op *opline, HashTable *class_table, zend_class_entry *parent_ce, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; int found_ce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } found_ce = zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce); if (found_ce == FAILURE) { if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", Z_STRVAL_P(op2)); } return NULL; } else { ce = *pce; } if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ce->name, parent_ce->name); } else if ((parent_ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ce->name, parent_ce->name); } zend_do_inheritance(ce, parent_ce TSRMLS_CC); ce->refcount++; /* Register the derived class */ if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), pce, sizeof(zend_class_entry *), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return ce; } /* }}} */ void zend_do_early_binding(TSRMLS_D) /* {{{ */ { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; HashTable *table; while (opline->opcode == ZEND_TICKS && opline > CG(active_op_array)->opcodes) { opline--; } switch (opline->opcode) { case ZEND_DECLARE_FUNCTION: if (do_bind_function(CG(active_op_array), opline, CG(function_table), 1) == FAILURE) { return; } table = CG(function_table); break; case ZEND_DECLARE_CLASS: if (do_bind_class(CG(active_op_array), opline, CG(class_table), 1 TSRMLS_CC) == NULL) { return; } table = CG(class_table); break; case ZEND_DECLARE_INHERITED_CLASS: { zend_op *fetch_class_opline = opline-1; zval *parent_name; zend_class_entry **pce; parent_name = &CONSTANT(fetch_class_opline->op2.constant); if ((zend_lookup_class(Z_STRVAL_P(parent_name), Z_STRLEN_P(parent_name), &pce TSRMLS_CC) == FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_CLASSES) && ((*pce)->type == ZEND_INTERNAL_CLASS))) { if (CG(compiler_options) & ZEND_COMPILE_DELAYED_BINDING) { zend_uint *opline_num = &CG(active_op_array)->early_binding; while (*opline_num != -1) { opline_num = &CG(active_op_array)->opcodes[*opline_num].result.opline_num; } *opline_num = opline - CG(active_op_array)->opcodes; opline->opcode = ZEND_DECLARE_INHERITED_CLASS_DELAYED; opline->result_type = IS_UNUSED; opline->result.opline_num = -1; } return; } if (do_bind_inherited_class(CG(active_op_array), opline, CG(class_table), *pce, 1 TSRMLS_CC) == NULL) { return; } /* clear unnecessary ZEND_FETCH_CLASS opcode */ zend_del_literal(CG(active_op_array), fetch_class_opline->op2.constant); MAKE_NOP(fetch_class_opline); table = CG(class_table); break; } case ZEND_VERIFY_ABSTRACT_CLASS: case ZEND_ADD_INTERFACE: case ZEND_ADD_TRAIT: case ZEND_BIND_TRAITS: /* We currently don't early-bind classes that implement interfaces */ /* Classes with traits are handled exactly the same, no early-bind here */ return; default: zend_error(E_COMPILE_ERROR, "Invalid binding type"); return; } zend_hash_quick_del(table, Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant)), Z_HASH_P(&CONSTANT(opline->op1.constant))); zend_del_literal(CG(active_op_array), opline->op1.constant); zend_del_literal(CG(active_op_array), opline->op2.constant); MAKE_NOP(opline); } /* }}} */ ZEND_API void zend_do_delayed_early_binding(const zend_op_array *op_array TSRMLS_DC) /* {{{ */ { if (op_array->early_binding != -1) { zend_bool orig_in_compilation = CG(in_compilation); zend_uint opline_num = op_array->early_binding; zend_class_entry **pce; CG(in_compilation) = 1; while (opline_num != -1) { if (zend_lookup_class(Z_STRVAL_P(op_array->opcodes[opline_num-1].op2.zv), Z_STRLEN_P(op_array->opcodes[opline_num-1].op2.zv), &pce TSRMLS_CC) == SUCCESS) { do_bind_inherited_class(op_array, &op_array->opcodes[opline_num], EG(class_table), *pce, 0 TSRMLS_CC); } opline_num = op_array->opcodes[opline_num].result.opline_num; } CG(in_compilation) = orig_in_compilation; } } /* }}} */ void zend_do_boolean_or_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_or_end(znode *result, const znode *expr1, const znode *expr2, znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_boolean_and_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_and_end(znode *result, const znode *expr1, const znode *expr2, const znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_do_while_begin(TSRMLS_D) /* {{{ */ { do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_do_while_end(const znode *do_token, const znode *expr_open_bracket, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ; SET_NODE(opline->op1, expr); opline->op2.opline_num = do_token->u.op.opline_num; SET_UNUSED(opline->op2); do_end_loop(expr_open_bracket->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_brk_cont(zend_uchar op, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->op1.opline_num = CG(context).current_brk_cont; SET_UNUSED(opline->op1); if (expr) { if (expr->op_type != IS_CONST) { zend_error(E_COMPILE_ERROR, "'%s' operator with non-constant operand is no longer supported", op == ZEND_BRK ? "break" : "continue"); } else if (Z_TYPE(expr->u.constant) != IS_LONG || Z_LVAL(expr->u.constant) < 1) { zend_error(E_COMPILE_ERROR, "'%s' operator accepts only positive numbers", op == ZEND_BRK ? "break" : "continue"); } SET_NODE(opline->op2, expr); } else { LITERAL_LONG(opline->op2, 1); opline->op2_type = IS_CONST; } } /* }}} */ void zend_do_switch_cond(const znode *cond TSRMLS_DC) /* {{{ */ { zend_switch_entry switch_entry; switch_entry.cond = *cond; switch_entry.default_case = -1; switch_entry.control_var = -1; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_switch_end(const znode *case_list TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); /* add code to jmp to default case */ if (switch_entry_ptr->default_case != -1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->op1.opline_num = switch_entry_ptr->default_case; } if (case_list->op_type != IS_UNUSED) { /* non-empty switch */ int next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* remember break/continue loop information */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; if (switch_entry_ptr->cond.op_type==IS_VAR || switch_entry_ptr->cond.op_type==IS_TMP_VAR) { /* emit free for the switch condition*/ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry_ptr->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_UNUSED(opline->op2); } if (switch_entry_ptr->cond.op_type == IS_CONST) { zval_dtor(&switch_entry_ptr->cond.u.constant); } zend_stack_del_top(&CG(switch_cond_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_case_before_statement(const znode *case_list, znode *case_token, const znode *case_expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); int next_op_number; zend_switch_entry *switch_entry_ptr; znode result; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); if (switch_entry_ptr->control_var == -1) { switch_entry_ptr->control_var = get_temporary_variable(CG(active_op_array)); } opline->opcode = ZEND_CASE; opline->result.var = switch_entry_ptr->control_var; opline->result_type = IS_TMP_VAR; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_NODE(opline->op2, case_expr); if (opline->op1_type == IS_CONST) { zval_copy_ctor(&CONSTANT(opline->op1.constant)); } GET_NODE(&result, opline->result); next_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, &result); SET_UNUSED(opline->op2); case_token->u.op.opline_num = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_case_after_statement(znode *result, const znode *case_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); result->u.op.opline_num = next_op_number; switch (CG(active_op_array)->opcodes[case_token->u.op.opline_num].opcode) { case ZEND_JMP: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); break; case ZEND_JMPZ: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); break; } } /* }}} */ void zend_do_default_before_statement(const znode *case_list, znode *default_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); default_token->u.op.opline_num = next_op_number; next_op_number = get_next_op_number(CG(active_op_array)); switch_entry_ptr->default_case = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_begin_class_declaration(const znode *class_token, znode *class_name, const znode *parent_class_name TSRMLS_DC) /* {{{ */ { zend_op *opline; int doing_inheritance = 0; zend_class_entry *new_class_entry; char *lcname; int error = 0; zval **ns_name, key; if (CG(active_class_entry)) { zend_error(E_COMPILE_ERROR, "Class declarations may not be nested"); return; } lcname = zend_str_tolower_dup(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); if (!(strcmp(lcname, "self") && strcmp(lcname, "parent"))) { efree(lcname); zend_error(E_COMPILE_ERROR, "Cannot use '%s' as class name as it is reserved", Z_STRVAL(class_name->u.constant)); } /* Class name must not conflict with import names */ if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns_name) == SUCCESS) { error = 1; } if (CG(current_namespace)) { /* Prefix class name with name of current namespace */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); class_name = &tmp; efree(lcname); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); } if (error) { char *tmp = zend_str_tolower_dup(Z_STRVAL_PP(ns_name), Z_STRLEN_PP(ns_name)); if (Z_STRLEN_PP(ns_name) != Z_STRLEN(class_name->u.constant) || memcmp(tmp, lcname, Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "Cannot declare class %s because the name is already in use", Z_STRVAL(class_name->u.constant)); } efree(tmp); } new_class_entry = emalloc(sizeof(zend_class_entry)); new_class_entry->type = ZEND_USER_CLASS; new_class_entry->name = zend_new_interned_string(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1, 1 TSRMLS_CC); new_class_entry->name_length = Z_STRLEN(class_name->u.constant); zend_initialize_class_data(new_class_entry, 1 TSRMLS_CC); new_class_entry->info.user.filename = zend_get_compiled_filename(TSRMLS_C); new_class_entry->info.user.line_start = class_token->u.op.opline_num; new_class_entry->ce_flags |= class_token->EA; if (parent_class_name && parent_class_name->op_type != IS_UNUSED) { switch (parent_class_name->EA) { case ZEND_FETCH_CLASS_SELF: zend_error(E_COMPILE_ERROR, "Cannot use 'self' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_PARENT: zend_error(E_COMPILE_ERROR, "Cannot use 'parent' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use 'static' as class name as it is reserved"); break; default: break; } doing_inheritance = 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, new_class_entry->name_length TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; if (doing_inheritance) { /* Make sure a trait does not try to extend a class */ if ((new_class_entry->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "A trait (%s) cannot extend a class", new_class_entry->name); } opline->extended_value = parent_class_name->u.op.var; opline->opcode = ZEND_DECLARE_INHERITED_CLASS; } else { opline->opcode = ZEND_DECLARE_CLASS; } LITERAL_STRINGL(opline->op2, lcname, new_class_entry->name_length, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); zend_hash_quick_update(CG(class_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &new_class_entry, sizeof(zend_class_entry *), NULL); CG(active_class_entry) = new_class_entry; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(&CG(implementing_class), opline->result); if (CG(doc_comment)) { CG(active_class_entry)->info.user.doc_comment = CG(doc_comment); CG(active_class_entry)->info.user.doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ static void do_verify_abstract_class(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_VERIFY_ABSTRACT_CLASS; SET_NODE(opline->op1, &CG(implementing_class)); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_class_declaration(const znode *class_token, const znode *parent_token TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); if (ce->constructor) { ce->constructor->common.fn_flags |= ZEND_ACC_CTOR; if (ce->constructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Constructor %s::%s() cannot be static", ce->name, ce->constructor->common.function_name); } } if (ce->destructor) { ce->destructor->common.fn_flags |= ZEND_ACC_DTOR; if (ce->destructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Destructor %s::%s() cannot be static", ce->name, ce->destructor->common.function_name); } } if (ce->clone) { ce->clone->common.fn_flags |= ZEND_ACC_CLONE; if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static", ce->name, ce->clone->common.function_name); } } ce->info.user.line_end = zend_get_compiled_lineno(TSRMLS_C); /* Check for traits and proceed like with interfaces. * The only difference will be a combined handling of them in the end. * Thus, we need another opcode here. */ if (ce->num_traits > 0) { zend_op *opline; ce->traits = NULL; ce->num_traits = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_TRAITS; /* opcode generation: */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BIND_TRAITS; SET_NODE(opline->op1, &CG(implementing_class)); } if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) && ((parent_token->op_type != IS_UNUSED) || (ce->num_interfaces > 0))) { zend_verify_abstract_class(ce TSRMLS_CC); if (ce->num_interfaces) { do_verify_abstract_class(TSRMLS_C); } } /* Inherit interfaces; reset number to zero, we need it for above check and * will restore it during actual implementation. * The ZEND_ACC_IMPLEMENT_INTERFACES flag disables double call to * zend_verify_abstract_class() */ if (ce->num_interfaces > 0) { ce->interfaces = NULL; ce->num_interfaces = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_INTERFACES; } CG(active_class_entry) = NULL; } /* }}} */ void zend_do_implements_interface(znode *interface_name TSRMLS_DC) /* {{{ */ { zend_op *opline; /* Traits can not implement interfaces */ if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface on '%s' since it is a Trait", Z_STRVAL(interface_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(interface_name->u.constant), Z_STRLEN(interface_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface name as it is reserved", Z_STRVAL(interface_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_INTERFACE; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(interface_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = (opline->extended_value & ~ZEND_FETCH_CLASS_MASK) | ZEND_FETCH_CLASS_INTERFACE; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &interface_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_interfaces++; } /* }}} */ void zend_do_implements_trait(znode *trait_name TSRMLS_DC) /* {{{ */ { zend_op *opline; if ((CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Cannot use traits inside of interfaces. %s is used in %s", Z_STRVAL(trait_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(trait_name->u.constant), Z_STRLEN(trait_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as trait name as it is reserved", Z_STRVAL(trait_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_TRAIT; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(trait_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = ZEND_FETCH_CLASS_TRAIT; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &trait_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_traits++; } /* }}} */ ZEND_API void zend_mangle_property_name(char **dest, int *dest_length, const char *src1, int src1_length, const char *src2, int src2_length, int internal) /* {{{ */ { char *prop_name; int prop_name_length; prop_name_length = 1 + src1_length + 1 + src2_length; prop_name = pemalloc(prop_name_length + 1, internal); prop_name[0] = '\0'; memcpy(prop_name + 1, src1, src1_length+1); memcpy(prop_name + 1 + src1_length + 1, src2, src2_length+1); *dest = prop_name; *dest_length = prop_name_length; } /* }}} */ static int zend_strnlen(const char* s, int maxlen) /* {{{ */ { int len = 0; while (*s++ && maxlen--) len++; return len; } /* }}} */ ZEND_API int zend_unmangle_property_name(const char *mangled_property, int len, const char **class_name, const char **prop_name) /* {{{ */ { int class_name_len; *class_name = NULL; if (mangled_property[0]!=0) { *prop_name = mangled_property; return SUCCESS; } if (len < 3 || mangled_property[1]==0) { zend_error(E_NOTICE, "Illegal member variable name"); *prop_name = mangled_property; return FAILURE; } class_name_len = zend_strnlen(mangled_property+1, --len - 1) + 1; if (class_name_len >= len || mangled_property[class_name_len]!=0) { zend_error(E_NOTICE, "Corrupt member variable name"); *prop_name = mangled_property; return FAILURE; } *class_name = mangled_property+1; *prop_name = (*class_name)+class_name_len; return SUCCESS; } /* }}} */ void zend_do_declare_property(const znode *var_name, const znode *value, zend_uint access_type TSRMLS_DC) /* {{{ */ { zval *property; zend_property_info *existing_property_info; char *comment = NULL; int comment_len = 0; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Interfaces may not include member variables"); } if (access_type & ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Properties cannot be declared abstract"); } if (access_type & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot declare property %s::$%s final, the final modifier is allowed only for methods and classes", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } if (zend_hash_find(&CG(active_class_entry)->properties_info, var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, (void **) &existing_property_info)==SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::$%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } ALLOC_ZVAL(property); if (value) { *property = value->u.constant; } else { INIT_PZVAL(property); Z_TYPE_P(property) = IS_NULL; } if (CG(doc_comment)) { comment = CG(doc_comment); comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } zend_declare_property_ex(CG(active_class_entry), zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len + 1, 0 TSRMLS_CC), var_name->u.constant.value.str.len, property, access_type, comment, comment_len TSRMLS_CC); efree(var_name->u.constant.value.str.val); } /* }}} */ void zend_do_declare_class_constant(znode *var_name, const znode *value TSRMLS_DC) /* {{{ */ { zval *property; const char *cname = NULL; int result; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed in class constants"); return; } if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Traits cannot have constants"); return; } ALLOC_ZVAL(property); *property = value->u.constant; cname = zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, 0 TSRMLS_CC); if (IS_INTERNED(cname)) { result = zend_hash_quick_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, INTERNED_HASH(cname), &property, sizeof(zval *), NULL); } else { result = zend_hash_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, &property, sizeof(zval *), NULL); } if (result == FAILURE) { FREE_ZVAL(property); zend_error(E_COMPILE_ERROR, "Cannot redefine class constant %s::%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } FREE_PNODE(var_name); if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_fetch_property(znode *result, znode *object, const znode *property TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (object->op_type == IS_CV) { if (object->u.op.var == CG(active_op_array)->this_var) { object->op_type = IS_UNUSED; /* this means $this for objects */ } } else if (fetch_list_ptr->count == 1) { zend_llist_element *le = fetch_list_ptr->head; zend_op *opline_ptr = (zend_op *) le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); SET_UNUSED(opline_ptr->op1); /* this means $this for objects */ SET_NODE(opline_ptr->op2, property); /* if it was usual fetch, we change it to object fetch */ switch (opline_ptr->opcode) { case ZEND_FETCH_W: opline_ptr->opcode = ZEND_FETCH_OBJ_W; break; case ZEND_FETCH_R: opline_ptr->opcode = ZEND_FETCH_OBJ_R; break; case ZEND_FETCH_RW: opline_ptr->opcode = ZEND_FETCH_OBJ_RW; break; case ZEND_FETCH_IS: opline_ptr->opcode = ZEND_FETCH_OBJ_IS; break; case ZEND_FETCH_UNSET: opline_ptr->opcode = ZEND_FETCH_OBJ_UNSET; break; case ZEND_FETCH_FUNC_ARG: opline_ptr->opcode = ZEND_FETCH_OBJ_FUNC_ARG; break; } if (opline_ptr->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline_ptr->op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline_ptr->op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op2.constant); } GET_NODE(result, opline_ptr->result); return; } } if (zend_is_function_or_method_call(object)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, object); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_OBJ_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, object); SET_NODE(opline.op2, property); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline.op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op2.constant); } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void zend_do_halt_compiler_register(TSRMLS_D) /* {{{ */ { char *name, *cfilename; char haltoff[] = "__COMPILER_HALT_OFFSET__"; int len, clen; cfilename = zend_get_compiled_filename(TSRMLS_C); clen = strlen(cfilename); zend_mangle_property_name(&name, &len, haltoff, sizeof(haltoff) - 1, cfilename, clen, 0); zend_register_long_constant(name, len+1, zend_get_scanned_file_offset(TSRMLS_C), CONST_CS, 0 TSRMLS_CC); pefree(name, 0); if (CG(in_namespace)) { zend_do_end_namespace(TSRMLS_C); } } /* }}} */ void zend_do_push_object(const znode *object TSRMLS_DC) /* {{{ */ { zend_stack_push(&CG(object_stack), object, sizeof(znode)); } /* }}} */ void zend_do_pop_object(znode *object TSRMLS_DC) /* {{{ */ { if (object) { znode *tmp; zend_stack_top(&CG(object_stack), (void **) &tmp); *object = *tmp; } zend_stack_del_top(&CG(object_stack)); } /* }}} */ void zend_do_begin_new_object(znode *new_token, znode *class_type TSRMLS_DC) /* {{{ */ { zend_op *opline; unsigned char *ptr = NULL; new_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_NEW; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, class_type); SET_UNUSED(opline->op2); zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(unsigned char *)); } /* }}} */ void zend_do_end_new_object(znode *result, const znode *new_token, const znode *argument_list TSRMLS_DC) /* {{{ */ { znode ctor_result; zend_do_end_function_call(NULL, &ctor_result, argument_list, 1, 0 TSRMLS_CC); zend_do_free(&ctor_result TSRMLS_CC); CG(active_op_array)->opcodes[new_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, CG(active_op_array)->opcodes[new_token->u.op.opline_num].result); } /* }}} */ static zend_constant* zend_get_ct_const(const zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = NULL; if (Z_STRVAL_P(const_name)[0] == '\\') { if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name), (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name)-1); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name), (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } } else if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)+1, (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name)+1, (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } if (c->flags & CONST_CT_SUBST) { return c; } if (all_internal_constants_substitution && (c->flags & CONST_PERSISTENT) && !(CG(compiler_options) & ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION) && Z_TYPE(c->value) != IS_CONSTANT && Z_TYPE(c->value) != IS_CONSTANT_ARRAY) { return c; } return NULL; } /* }}} */ static int zend_constant_ct_subst(znode *result, zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = zend_get_ct_const(const_name, all_internal_constants_substitution TSRMLS_CC); if (c) { zval_dtor(const_name); result->op_type = IS_CONST; result->u.constant = c->value; zval_copy_ctor(&result->u.constant); INIT_PZVAL(&result->u.constant); return 1; } return 0; } /* }}} */ void zend_do_fetch_constant(znode *result, znode *constant_container, znode *constant_name, int mode, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; zend_op *opline; int type; char *compound; ulong fetch_type = 0; if (constant_container) { switch (mode) { case ZEND_CT: /* this is a class constant */ type = zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant)); if (ZEND_FETCH_CLASS_STATIC == type) { zend_error(E_ERROR, "\"static::\" is not allowed in compile-time constants"); } else if (ZEND_FETCH_CLASS_DEFAULT == type) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } zend_do_build_full_name(NULL, constant_container, constant_name, 1 TSRMLS_CC); *result = *constant_container; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: if (constant_container->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant))) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } else { zend_do_fetch_class(&tmp, constant_container TSRMLS_CC); constant_container = &tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); if (constant_container->op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &constant_container->u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, constant_container); } SET_NODE(opline->op2, constant_name); CALCULATE_LITERAL_HASH(opline->op2.constant); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } GET_NODE(result, opline->result); break; } return; } /* namespace constant */ /* only one that did not contain \ from the start can be converted to string if unknown */ switch (mode) { case ZEND_CT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); /* this is a namespace constant, or an unprefixed constant */ if (zend_constant_ct_subst(result, &constant_name->u.constant, 0 TSRMLS_CC)) { break; } zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(!compound) { fetch_type |= IS_CONSTANT_UNQUALIFIED; } *result = *constant_name; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(zend_constant_ct_subst(result, &constant_name->u.constant, 1 TSRMLS_CC)) { break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; if (compound) { /* the name is unambiguous */ opline->extended_value = 0; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } else { opline->extended_value = IS_CONSTANT_UNQUALIFIED; if (CG(current_namespace)) { opline->extended_value |= IS_CONSTANT_IN_NAMESPACE; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 1 TSRMLS_CC); } else { opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } } GET_CACHE_SLOT(opline->op2.constant); break; } } /* }}} */ void zend_do_shell_exec(znode *result, const znode *cmd TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); switch (cmd->op_type) { case IS_CONST: case IS_TMP_VAR: opline->opcode = ZEND_SEND_VAL; break; default: opline->opcode = ZEND_SEND_VAR; break; } SET_NODE(opline->op1, cmd); opline->op2.opline_num = 0; opline->extended_value = ZEND_DO_FCALL; SET_UNUSED(opline->op2); /* FIXME: exception support not added to this op2 */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DO_FCALL; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; LITERAL_STRINGL(opline->op1, estrndup("shell_exec", sizeof("shell_exec")-1), sizeof("shell_exec")-1, 0); CALCULATE_LITERAL_HASH(opline->op1.constant); opline->op1_type = IS_CONST; GET_CACHE_SLOT(opline->op1.constant); opline->extended_value = 1; SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_init_array(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_ARRAY; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; GET_NODE(result, opline->result); if (expr) { SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } } else { SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_array_element(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_ARRAY_ELEMENT; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_static_array_element(znode *result, znode *offset, const znode *expr) /* {{{ */ { zval *element; ALLOC_ZVAL(element); *element = expr->u.constant; if (offset) { switch (offset->u.constant.type & IS_CONSTANT_TYPE_MASK) { case IS_CONSTANT: /* Ugly hack to denote that this value has a constant index */ Z_TYPE_P(element) |= IS_CONSTANT_INDEX; Z_STRVAL(offset->u.constant) = erealloc(Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+1] = Z_TYPE(offset->u.constant); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+2] = 0; zend_symtable_update(result->u.constant.value.ht, Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_STRING: zend_symtable_update(result->u.constant.value.ht, offset->u.constant.value.str.val, offset->u.constant.value.str.len+1, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_NULL: zend_symtable_update(Z_ARRVAL(result->u.constant), "", 1, &element, sizeof(zval *), NULL); break; case IS_LONG: case IS_BOOL: zend_hash_index_update(Z_ARRVAL(result->u.constant), Z_LVAL(offset->u.constant), &element, sizeof(zval *), NULL); break; case IS_DOUBLE: zend_hash_index_update(Z_ARRVAL(result->u.constant), zend_dval_to_lval(Z_DVAL(offset->u.constant)), &element, sizeof(zval *), NULL); break; case IS_CONSTANT_ARRAY: zend_error(E_ERROR, "Illegal offset type"); break; } } else { zend_hash_next_index_insert(Z_ARRVAL(result->u.constant), &element, sizeof(zval *), NULL); } } /* }}} */ void zend_do_add_list_element(const znode *element TSRMLS_DC) /* {{{ */ { list_llist_element lle; if (element) { zend_check_writable_variable(element); lle.var = *element; zend_llist_copy(&lle.dimensions, &CG(dimension_llist)); zend_llist_prepend_element(&CG(list_llist), &lle); } (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_new_list_begin(TSRMLS_D) /* {{{ */ { int current_dimension = 0; zend_llist_add_element(&CG(dimension_llist), &current_dimension); } /* }}} */ void zend_do_new_list_end(TSRMLS_D) /* {{{ */ { zend_llist_remove_tail(&CG(dimension_llist)); (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_list_init(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(list_stack), &CG(list_llist), sizeof(zend_llist)); zend_stack_push(&CG(list_stack), &CG(dimension_llist), sizeof(zend_llist)); zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_do_new_list_begin(TSRMLS_C); } /* }}} */ void zend_do_list_end(znode *result, znode *expr TSRMLS_DC) /* {{{ */ { zend_llist_element *le; zend_llist_element *dimension; zend_op *opline; znode last_container; le = CG(list_llist).head; while (le) { zend_llist *tmp_dimension_llist = &((list_llist_element *)le->data)->dimensions; dimension = tmp_dimension_llist->head; while (dimension) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (dimension == tmp_dimension_llist->head) { /* first */ last_container = *expr; switch (expr->op_type) { case IS_VAR: case IS_CV: opline->opcode = ZEND_FETCH_DIM_R; break; case IS_TMP_VAR: opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; case IS_CONST: /* fetch_dim_tmp_var will handle this bogus fetch */ zval_copy_ctor(&expr->u.constant); opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; } opline->extended_value |= ZEND_FETCH_ADD_LOCK; } else { opline->opcode = ZEND_FETCH_DIM_R; } opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, &last_container); opline->op2_type = IS_CONST; LITERAL_LONG(opline->op2, *((int *) dimension->data)); GET_NODE(&last_container, opline->result); dimension = dimension->next; } ((list_llist_element *) le->data)->value = last_container; zend_llist_destroy(&((list_llist_element *) le->data)->dimensions); zend_do_assign(result, &((list_llist_element *) le->data)->var, &((list_llist_element *) le->data)->value TSRMLS_CC); zend_do_free(result TSRMLS_CC); le = le->next; } zend_llist_destroy(&CG(dimension_llist)); zend_llist_destroy(&CG(list_llist)); *result = *expr; { zend_llist *p; /* restore previous lists */ zend_stack_top(&CG(list_stack), (void **) &p); CG(dimension_llist) = *p; zend_stack_del_top(&CG(list_stack)); zend_stack_top(&CG(list_stack), (void **) &p); CG(list_llist) = *p; zend_stack_del_top(&CG(list_stack)); } } /* }}} */ void zend_init_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = emalloc(sizeof(void*) * 2); list[0] = item; list[1] = NULL; *(void**)result = list; } /* }}} */ void zend_add_to_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = *(void**)result; size_t n = 0; while (list && list[n]) { n++; } list = erealloc(list, sizeof(void*) * (n+2)); list[n] = item; list[n+1] = NULL; *(void**)result = list; } /* }}} */ void zend_do_fetch_static_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zval *tmp; zend_op *opline; znode lval; znode result; ALLOC_ZVAL(tmp); if (static_assignment) { *tmp = static_assignment->u.constant; } else { INIT_ZVAL(*tmp); } if (!CG(active_op_array)->static_variables) { if (CG(active_op_array)->scope) { CG(active_op_array)->scope->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } ALLOC_HASHTABLE(CG(active_op_array)->static_variables); zend_hash_init(CG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } zend_hash_update(CG(active_op_array)->static_variables, varname->u.constant.value.str.val, varname->u.constant.value.str.len+1, &tmp, sizeof(zval *), NULL); if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (fetch_type == ZEND_FETCH_LEXICAL) ? ZEND_FETCH_R : ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_STATIC; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ if (fetch_type == ZEND_FETCH_LEXICAL) { znode dummy; zend_do_begin_variable_parse(TSRMLS_C); zend_do_assign(&dummy, &lval, &result TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } else { zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); } CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_fetch_lexical_variable(znode *varname, zend_bool is_ref TSRMLS_DC) /* {{{ */ { znode value; if (Z_STRLEN(varname->u.constant) == sizeof("this") - 1 && memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this") - 1) == 0) { zend_error(E_COMPILE_ERROR, "Cannot use $this as lexical variable"); return; } value.op_type = IS_CONST; ZVAL_NULL(&value.u.constant); Z_TYPE(value.u.constant) |= is_ref ? IS_LEXICAL_REF : IS_LEXICAL_VAR; Z_SET_REFCOUNT_P(&value.u.constant, 1); Z_UNSET_ISREF_P(&value.u.constant); zend_do_fetch_static_variable(varname, &value, is_ref ? ZEND_FETCH_STATIC : ZEND_FETCH_LEXICAL TSRMLS_CC); } /* }}} */ void zend_do_fetch_global_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zend_op *opline; znode lval; znode result; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = fetch_type; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_cast(znode *result, const znode *expr, int type TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CAST; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } /* }}} */ void zend_do_include_or_eval(int type, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_do_extended_fcall_begin(TSRMLS_C); { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INCLUDE_OR_EVAL; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } zend_do_extended_fcall_end(TSRMLS_C); } /* }}} */ void zend_do_indirect_references(znode *result, const znode *num_references, znode *variable TSRMLS_DC) /* {{{ */ { int i; zend_do_end_variable_parse(variable, BP_VAR_R, 0 TSRMLS_CC); for (i=1; i<num_references->u.constant.value.lval; i++) { fetch_simple_variable_ex(result, variable, 0, ZEND_FETCH_R TSRMLS_CC); *variable = *result; } zend_do_begin_variable_parse(TSRMLS_C); fetch_simple_variable(result, variable, 1 TSRMLS_CC); /* there is a chance someone is accessing $this */ if (CG(active_op_array)->scope && CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } /* }}} */ void zend_do_unset(const znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_UNSET_VAR; SET_NODE(opline->op1, variable); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); opline->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_UNSET: last_op->opcode = ZEND_UNSET_VAR; SET_UNUSED(last_op->result); break; case ZEND_FETCH_DIM_UNSET: last_op->opcode = ZEND_UNSET_DIM; SET_UNUSED(last_op->result); break; case ZEND_FETCH_OBJ_UNSET: last_op->opcode = ZEND_UNSET_OBJ; SET_UNUSED(last_op->result); break; } } } /* }}} */ void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_do_end_variable_parse(variable, BP_VAR_IS, 0 TSRMLS_CC); zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { last_op = get_next_op(CG(active_op_array) TSRMLS_CC); last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; SET_NODE(last_op->op1, variable); SET_UNUSED(last_op->op2); last_op->result.var = get_temporary_variable(CG(active_op_array)); last_op->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; break; case ZEND_FETCH_DIM_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_DIM_OBJ; break; case ZEND_FETCH_OBJ_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_PROP_OBJ; break; } } last_op->result_type = IS_TMP_VAR; last_op->extended_value |= type; GET_NODE(result, last_op->result); } /* }}} */ void zend_do_instanceof(znode *result, const znode *expr, const znode *class_znode, int type TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline->opcode == ZEND_FETCH_CLASS) { opline->extended_value |= ZEND_FETCH_CLASS_NO_AUTOLOAD; } } if (expr->op_type == IS_CONST) { zend_error(E_COMPILE_ERROR, "instanceof expects an object instance, constant given"); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INSTANCEOF; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_NODE(opline->op2, class_znode); GET_NODE(result, opline->result); } /* }}} */ void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_bool is_variable; zend_bool push_container = 0; zend_op dummy_opline; if (variable) { if (zend_is_function_or_method_call(array)) { is_variable = 0; } else { is_variable = 1; } /* save the location of FETCH_W instruction(s) */ open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); zend_do_end_variable_parse(array, BP_VAR_W, 0 TSRMLS_CC); if (CG(active_op_array)->last > 0 && CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) { /* Only lock the container if we are fetching from a real container and not $this */ if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1_type == IS_VAR) { CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK; push_container = 1; } } } else { is_variable = 0; open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* save the location of FE_RESET */ foreach_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* Preform array reset */ opline->opcode = ZEND_FE_RESET; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, array); SET_UNUSED(opline->op2); opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0; COPY_NODE(dummy_opline.result, opline->result); if (push_container) { COPY_NODE(dummy_opline.op1, CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1); } else { dummy_opline.op1_type = IS_UNUSED; } zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); /* save the location of FE_FETCH */ as_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FE_FETCH; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); COPY_NODE(opline->op1, dummy_opline.result); opline->extended_value = 0; SET_UNUSED(opline->op2); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_OP_DATA; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); } /* }}} */ void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC) /* {{{ */ { zend_op *opline; znode dummy, value_node; zend_bool assign_by_ref=0; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num]; if (key->op_type != IS_UNUSED) { znode *tmp; /* switch between the key and value... */ tmp = key; key = value; value = tmp; /* Mark extended_value in case both key and value are being used */ opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; } if ((key->op_type != IS_UNUSED) && (key->EA & ZEND_PARSED_REFERENCE_VARIABLE)) { zend_error(E_COMPILE_ERROR, "Key element cannot be a reference"); } if (value->EA & ZEND_PARSED_REFERENCE_VARIABLE) { assign_by_ref = 1; if (!(opline-1)->extended_value) { zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression"); } /* Mark extended_value for assign-by-reference */ opline->extended_value |= ZEND_FE_FETCH_BYREF; CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; } else { zend_op *foreach_copy; zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.op.opline_num]; zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.op.opline_num]; /* Change "write context" into "read context" */ fetch->extended_value = 0; /* reset ZEND_FE_RESET_VARIABLE */ while (fetch != end) { --fetch; if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } if (fetch->opcode == ZEND_SEPARATE) { MAKE_NOP(fetch); } else { fetch->opcode -= 3; /* FETCH_W -> FETCH_R */ } } /* prevent double SWITCH_FREE */ zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy); foreach_copy->op1_type = IS_UNUSED; } GET_NODE(&value_node, opline->result); if (assign_by_ref) { zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); /* Mark FE_FETCH as IS_VAR as it holds the data directly as a value */ zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC); } else { zend_do_assign(&dummy, value, &value_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } if (key->op_type != IS_UNUSED) { znode key_node; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num+1]; opline->result_type = IS_TMP_VAR; opline->result.opline_num = get_temporary_variable(CG(active_op_array)); GET_NODE(&key_node, opline->result); zend_do_assign(&dummy, key, &key_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_foreach_end(const znode *foreach_token, const znode *as_token TSRMLS_DC) /* {{{ */ { zend_op *container_ptr; zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = as_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_RESET */ CG(active_op_array)->opcodes[as_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_FETCH */ do_end_loop(as_token->u.op.opline_num, 1 TSRMLS_CC); zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr); generate_free_foreach_copy(container_ptr TSRMLS_CC); zend_stack_del_top(&CG(foreach_copy_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_declare_begin(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(declare_stack), &CG(declarables), sizeof(zend_declarables)); } /* }}} */ void zend_do_declare_stmt(znode *var, znode *val TSRMLS_DC) /* {{{ */ { if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "ticks", sizeof("ticks")-1)) { convert_to_long(&val->u.constant); CG(declarables).ticks = val->u.constant; } else if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "encoding", sizeof("encoding")-1)) { if ((Z_TYPE(val->u.constant) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Cannot use constants as encoding"); } /* * Check that the pragma comes before any opcodes. If the compilation * got as far as this, the previous portion of the script must have been * parseable according to the .ini script_encoding setting. We still * want to tell them to put declare() at the top. */ { int num = CG(active_op_array)->last; /* ignore ZEND_EXT_STMT and ZEND_TICKS */ while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Encoding declaration pragma must be the very first statement in the script"); } } if (CG(multibyte)) { const zend_encoding *new_encoding, *old_encoding; zend_encoding_filter old_input_filter; CG(encoding_declared) = 1; convert_to_string(&val->u.constant); new_encoding = zend_multibyte_fetch_encoding(val->u.constant.value.str.val TSRMLS_CC); if (!new_encoding) { zend_error(E_COMPILE_WARNING, "Unsupported encoding [%s]", val->u.constant.value.str.val); } else { old_input_filter = LANG_SCNG(input_filter); old_encoding = LANG_SCNG(script_encoding); zend_multibyte_set_filter(new_encoding TSRMLS_CC); /* need to re-scan if input filter changed */ if (old_input_filter != LANG_SCNG(input_filter) || (old_input_filter && new_encoding != old_encoding)) { zend_multibyte_yyinput_again(old_input_filter, old_encoding TSRMLS_CC); } } } else { zend_error(E_COMPILE_WARNING, "declare(encoding=...) ignored because Zend multibyte feature is turned off by settings"); } zval_dtor(&val->u.constant); } else { zend_error(E_COMPILE_WARNING, "Unsupported declare '%s'", var->u.constant.value.str.val); zval_dtor(&val->u.constant); } zval_dtor(&var->u.constant); } /* }}} */ void zend_do_declare_end(const znode *declare_token TSRMLS_DC) /* {{{ */ { zend_declarables *declarables; zend_stack_top(&CG(declare_stack), (void **) &declarables); /* We should restore if there was more than (current - start) - (ticks?1:0) opcodes */ if ((get_next_op_number(CG(active_op_array)) - declare_token->u.op.opline_num) - ((Z_LVAL(CG(declarables).ticks))?1:0)) { CG(declarables) = *declarables; } } /* }}} */ void zend_do_exit(znode *result, const znode *message TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXIT; SET_NODE(opline->op1, message); SET_UNUSED(opline->op2); result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_BOOL; Z_LVAL(result->u.constant) = 1; } /* }}} */ void zend_do_begin_silence(znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BEGIN_SILENCE; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); GET_NODE(strudel_token, opline->result); } /* }}} */ void zend_do_end_silence(const znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_END_SILENCE; SET_NODE(opline->op1, strudel_token); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_jmp_set(const znode *value, znode *jmp_token, znode *colon_token TSRMLS_DC) /* {{{ */ { int op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (value->op_type == IS_VAR || value->op_type == IS_CV) { opline->opcode = ZEND_JMP_SET_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_JMP_SET; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, value); SET_UNUSED(opline->op2); GET_NODE(colon_token, opline->result); jmp_token->u.op .opline_num = op_number; INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_jmp_set_else(znode *result, const znode *false_value, const znode *jmp_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, colon_token); if (colon_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].opcode = ZEND_JMP_SET_VAR; CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } opline->extended_value = 0; SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_qm_op(const znode *cond, znode *qm_token TSRMLS_DC) /* {{{ */ { int jmpz_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); SET_UNUSED(opline->op2); opline->op2.opline_num = jmpz_op_number; GET_NODE(qm_token, opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_qm_true(const znode *true_value, znode *qm_token, znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->opcodes[qm_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array))+1; /* jmp over the ZEND_JMP */ if (true_value->op_type == IS_VAR || true_value->op_type == IS_CV) { opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, true_value); SET_UNUSED(opline->op2); GET_NODE(qm_token, opline->result); colon_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_qm_false(znode *result, const znode *false_value, const znode *qm_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, qm_token); if (qm_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].opcode = ZEND_QM_ASSIGN_VAR; CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[colon_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, opline->result); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_extended_info(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_STMT; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_begin(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_BEGIN; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_end(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_END; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_ticks(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_TICKS; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->extended_value = Z_LVAL(CG(declarables).ticks); } /* }}} */ zend_bool zend_is_auto_global_quick(const char *name, uint name_len, ulong hashval TSRMLS_DC) /* {{{ */ { zend_auto_global *auto_global; ulong hash = hashval ? hashval : zend_hash_func(name, name_len+1); if (zend_hash_quick_find(CG(auto_globals), name, name_len+1, hash, (void **) &auto_global)==SUCCESS) { if (auto_global->armed) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } return 1; } return 0; } /* }}} */ zend_bool zend_is_auto_global(const char *name, uint name_len TSRMLS_DC) /* {{{ */ { return zend_is_auto_global_quick(name, name_len, 0 TSRMLS_CC); } /* }}} */ int zend_register_auto_global(const char *name, uint name_len, zend_bool jit, zend_auto_global_callback auto_global_callback TSRMLS_DC) /* {{{ */ { zend_auto_global auto_global; auto_global.name = zend_new_interned_string((char*)name, name_len + 1, 0 TSRMLS_CC); auto_global.name_len = name_len; auto_global.auto_global_callback = auto_global_callback; auto_global.jit = jit; return zend_hash_add(CG(auto_globals), name, name_len+1, &auto_global, sizeof(zend_auto_global), NULL); } /* }}} */ static int zend_auto_global_init(zend_auto_global *auto_global TSRMLS_DC) /* {{{ */ { if (auto_global->jit) { auto_global->armed = 1; } else if (auto_global->auto_global_callback) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } else { auto_global->armed = 0; } return 0; } /* }}} */ ZEND_API void zend_activate_auto_globals(TSRMLS_D) /* {{{ */ { zend_hash_apply(CG(auto_globals), (apply_func_t) zend_auto_global_init TSRMLS_CC); } /* }}} */ int zendlex(znode *zendlval TSRMLS_DC) /* {{{ */ { int retval; if (CG(increment_lineno)) { CG(zend_lineno)++; CG(increment_lineno) = 0; } again: Z_TYPE(zendlval->u.constant) = IS_LONG; retval = lex_scan(&zendlval->u.constant TSRMLS_CC); switch (retval) { case T_COMMENT: case T_DOC_COMMENT: case T_OPEN_TAG: case T_WHITESPACE: goto again; case T_CLOSE_TAG: if (LANG_SCNG(yy_text)[LANG_SCNG(yy_leng)-1] != '>') { CG(increment_lineno) = 1; } if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { goto again; } retval = ';'; /* implicit ; */ break; case T_OPEN_TAG_WITH_ECHO: retval = T_ECHO; break; case T_END_HEREDOC: efree(Z_STRVAL(zendlval->u.constant)); break; } INIT_PZVAL(&zendlval->u.constant); zendlval->op_type = IS_CONST; return retval; } /* }}} */ ZEND_API void zend_initialize_class_data(zend_class_entry *ce, zend_bool nullify_handlers TSRMLS_DC) /* {{{ */ { zend_bool persistent_hashes = (ce->type == ZEND_INTERNAL_CLASS) ? 1 : 0; dtor_func_t zval_ptr_dtor_func = ((persistent_hashes) ? ZVAL_INTERNAL_PTR_DTOR : ZVAL_PTR_DTOR); ce->refcount = 1; ce->ce_flags = 0; ce->default_properties_table = NULL; ce->default_static_members_table = NULL; zend_hash_init_ex(&ce->properties_info, 0, NULL, (dtor_func_t) (persistent_hashes ? zend_destroy_property_info_internal : zend_destroy_property_info), persistent_hashes, 0); zend_hash_init_ex(&ce->constants_table, 0, NULL, zval_ptr_dtor_func, persistent_hashes, 0); zend_hash_init_ex(&ce->function_table, 0, NULL, ZEND_FUNCTION_DTOR, persistent_hashes, 0); if (ce->type == ZEND_INTERNAL_CLASS) { #ifdef ZTS int n = zend_hash_num_elements(CG(class_table)); if (CG(static_members_table) && n >= CG(last_static_member)) { /* Support for run-time declaration: dl() */ CG(last_static_member) = n+1; CG(static_members_table) = realloc(CG(static_members_table), (n+1)*sizeof(zval**)); CG(static_members_table)[n] = NULL; } ce->static_members_table = (zval**)(zend_intptr_t)n; #else ce->static_members_table = NULL; #endif } else { ce->static_members_table = ce->default_static_members_table; ce->info.user.doc_comment = NULL; ce->info.user.doc_comment_len = 0; } ce->default_properties_count = 0; ce->default_static_members_count = 0; if (nullify_handlers) { ce->constructor = NULL; ce->destructor = NULL; ce->clone = NULL; ce->__get = NULL; ce->__set = NULL; ce->__unset = NULL; ce->__isset = NULL; ce->__call = NULL; ce->__callstatic = NULL; ce->__tostring = NULL; ce->create_object = NULL; ce->get_iterator = NULL; ce->iterator_funcs.funcs = NULL; ce->interface_gets_implemented = NULL; ce->get_static_method = NULL; ce->parent = NULL; ce->num_interfaces = 0; ce->interfaces = NULL; ce->num_traits = 0; ce->traits = NULL; ce->trait_aliases = NULL; ce->trait_precedences = NULL; ce->serialize = NULL; ce->unserialize = NULL; ce->serialize_func = NULL; ce->unserialize_func = NULL; if (ce->type == ZEND_INTERNAL_CLASS) { ce->info.internal.module = NULL; ce->info.internal.builtin_functions = NULL; } } } /* }}} */ int zend_get_class_fetch_type(const char *class_name, uint class_name_len) /* {{{ */ { if ((class_name_len == sizeof("self")-1) && !memcmp(class_name, "self", sizeof("self")-1)) { return ZEND_FETCH_CLASS_SELF; } else if ((class_name_len == sizeof("parent")-1) && !memcmp(class_name, "parent", sizeof("parent")-1)) { return ZEND_FETCH_CLASS_PARENT; } else if ((class_name_len == sizeof("static")-1) && !memcmp(class_name, "static", sizeof("static")-1)) { return ZEND_FETCH_CLASS_STATIC; } else { return ZEND_FETCH_CLASS_DEFAULT; } } /* }}} */ ZEND_API const char* zend_get_compiled_variable_name(const zend_op_array *op_array, zend_uint var, int* name_len) /* {{{ */ { if (name_len) { *name_len = op_array->vars[var].name_len; } return op_array->vars[var].name; } /* }}} */ void zend_do_build_namespace_name(znode *result, znode *prefix, znode *name TSRMLS_DC) /* {{{ */ { if (prefix) { *result = *prefix; if (Z_TYPE(result->u.constant) == IS_STRING && Z_STRLEN(result->u.constant) == 0) { /* namespace\ */ if (CG(current_namespace)) { znode tmp; zval_dtor(&result->u.constant); tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(result, NULL, &tmp TSRMLS_CC); } } } else { result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_STRING; Z_STRVAL(result->u.constant) = NULL; Z_STRLEN(result->u.constant) = 0; } /* prefix = result */ zend_do_build_full_name(NULL, result, name, 0 TSRMLS_CC); } /* }}} */ void zend_do_begin_namespace(const znode *name, zend_bool with_bracket TSRMLS_DC) /* {{{ */ { char *lcname; /* handle mixed syntax declaration or nested namespaces */ if (!CG(has_bracketed_namespaces)) { if (CG(current_namespace)) { /* previous namespace declarations were unbracketed */ if (with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } } } else { /* previous namespace declarations were bracketed */ if (!with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } else if (CG(current_namespace) || CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "Namespace declarations cannot be nested"); } } if (((!with_bracket && !CG(current_namespace)) || (with_bracket && !CG(has_bracketed_namespaces))) && CG(active_op_array)->last > 0) { /* ignore ZEND_EXT_STMT and ZEND_TICKS */ int num = CG(active_op_array)->last; while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Namespace declaration statement has to be the very first statement in the script"); } } CG(in_namespace) = 1; if (with_bracket) { CG(has_bracketed_namespaces) = 1; } if (name) { lcname = zend_str_tolower_dup(Z_STRVAL(name->u.constant), Z_STRLEN(name->u.constant)); if (((Z_STRLEN(name->u.constant) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN(name->u.constant) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as namespace name", Z_STRVAL(name->u.constant)); } efree(lcname); if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); } else { ALLOC_ZVAL(CG(current_namespace)); } *CG(current_namespace) = name->u.constant; } else { if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_use(znode *ns_name, znode *new_name, int is_global TSRMLS_DC) /* {{{ */ { char *lcname; zval *name, *ns, tmp; zend_bool warn = 0; zend_class_entry **pce; if (!CG(current_import)) { CG(current_import) = emalloc(sizeof(HashTable)); zend_hash_init(CG(current_import), 0, NULL, ZVAL_PTR_DTOR, 0); } ALLOC_ZVAL(ns); *ns = ns_name->u.constant; if (new_name) { name = &new_name->u.constant; } else { const char *p; /* The form "use A\B" is eqivalent to "use A\B as B". So we extract the last part of compound name to use as a new_name */ name = &tmp; p = zend_memrchr(Z_STRVAL_P(ns), '\\', Z_STRLEN_P(ns)); if (p) { ZVAL_STRING(name, p+1, 1); } else { *name = *ns; zval_copy_ctor(name); warn = !is_global && !CG(current_namespace); } } lcname = zend_str_tolower_dup(Z_STRVAL_P(name), Z_STRLEN_P(name)); if (((Z_STRLEN_P(name) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN_P(name) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because '%s' is a special class name", Z_STRVAL_P(ns), Z_STRVAL_P(name), Z_STRVAL_P(name)); } if (CG(current_namespace)) { /* Prefix import name with current namespace name to avoid conflicts with classes */ char *c_ns_name = emalloc(Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) + 1); zend_str_tolower_copy(c_ns_name, Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); c_ns_name[Z_STRLEN_P(CG(current_namespace))] = '\\'; memcpy(c_ns_name+Z_STRLEN_P(CG(current_namespace))+1, lcname, Z_STRLEN_P(name)+1); if (zend_hash_exists(CG(class_table), c_ns_name, Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name)+1)) { char *tmp2 = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) || memcmp(tmp2, c_ns_name, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(tmp2); } efree(c_ns_name); } else if (zend_hash_find(CG(class_table), lcname, Z_STRLEN_P(name)+1, (void**)&pce) == SUCCESS && (*pce)->type == ZEND_USER_CLASS && (*pce)->info.user.filename == CG(compiled_filename)) { char *c_tmp = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(name) || memcmp(c_tmp, lcname, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(c_tmp); } if (zend_hash_add(CG(current_import), lcname, Z_STRLEN_P(name)+1, &ns, sizeof(zval*), NULL) != SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } if (warn) { if (!strcmp(Z_STRVAL_P(name), "strict")) { zend_error(E_COMPILE_ERROR, "You seem to be trying to use a different language..."); } zend_error(E_WARNING, "The use statement with non-compound name '%s' has no effect", Z_STRVAL_P(name)); } efree(lcname); zval_dtor(name); } /* }}} */ void zend_do_declare_constant(znode *name, znode *value TSRMLS_DC) /* {{{ */ { zend_op *opline; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed as constants"); } if (zend_get_ct_const(&name->u.constant, 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare constant '%s'", Z_STRVAL(name->u.constant)); } if (CG(current_namespace)) { /* Prefix constant name with name of current namespace, lowercased */ znode tmp; tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); Z_STRVAL(tmp.u.constant) = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), Z_STRLEN(tmp.u.constant)); zend_do_build_namespace_name(&tmp, &tmp, name TSRMLS_CC); *name = tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DECLARE_CONST; SET_UNUSED(opline->result); SET_NODE(opline->op1, name); SET_NODE(opline->op2, value); } /* }}} */ void zend_verify_namespace(TSRMLS_D) /* {{{ */ { if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "No code may exist outside of namespace {}"); } } /* }}} */ void zend_do_end_namespace(TSRMLS_D) /* {{{ */ { CG(in_namespace) = 0; if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_end_compilation(TSRMLS_D) /* {{{ */ { CG(has_bracketed_namespaces) = 0; zend_do_end_namespace(TSRMLS_C); } /* }}} */ /* {{{ zend_dirname Returns directory name component of path */ ZEND_API size_t zend_dirname(char *path, size_t len) { register char *end = path + len - 1; unsigned int len_adjust = 0; #ifdef PHP_WIN32 /* Note that on Win32 CWD is per drive (heritage from CP/M). * This means dirname("c:foo") maps to "c:." or "c:" - which means CWD on C: drive. */ if ((2 <= len) && isalpha((int)((unsigned char *)path)[0]) && (':' == path[1])) { /* Skip over the drive spec (if any) so as not to change */ path += 2; len_adjust += 2; if (2 == len) { /* Return "c:" on Win32 for dirname("c:"). * It would be more consistent to return "c:." * but that would require making the string *longer*. */ return len; } } #elif defined(NETWARE) /* * Find the first occurence of : from the left * move the path pointer to the position just after : * increment the len_adjust to the length of path till colon character(inclusive) * If there is no character beyond : simple return len */ char *colonpos = NULL; colonpos = strchr(path, ':'); if (colonpos != NULL) { len_adjust = ((colonpos - path) + 1); path += len_adjust; if (len_adjust == len) { return len; } } #endif if (len == 0) { /* Illegal use of this function */ return 0; } /* Strip trailing slashes */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { /* The path only contained slashes */ path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } /* Strip filename */ while (end >= path && !IS_SLASH_P(end)) { end--; } if (end < path) { /* No slash found, therefore return '.' */ #ifdef NETWARE if (len_adjust == 0) { path[0] = '.'; path[1] = '\0'; return 1; /* only one character */ } else { path[0] = '\0'; return len_adjust; } #else path[0] = '.'; path[1] = '\0'; return 1 + len_adjust; #endif } /* Strip slashes which came before the file name */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } *(end+1) = '\0'; return (size_t)(end + 1 - path) + len_adjust; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-11-04-9da01ac6b6-7334dfd7eb.c
manybugs_data_53
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <zend_language_parser.h> #include "zend.h" #include "zend_compile.h" #include "zend_constants.h" #include "zend_llist.h" #include "zend_API.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "zend_multibyte.h" #include "zend_language_scanner.h" #define CONSTANT_EX(op_array, op) \ (op_array)->literals[op].constant #define CONSTANT(op) \ CONSTANT_EX(CG(active_op_array), op) #define SET_NODE(target, src) do { \ target ## _type = (src)->op_type; \ if ((src)->op_type == IS_CONST) { \ target.constant = zend_add_literal(CG(active_op_array), &(src)->u.constant TSRMLS_CC); \ } else { \ target = (src)->u.op; \ } \ } while (0) #define GET_NODE(target, src) do { \ (target)->op_type = src ## _type; \ if ((target)->op_type == IS_CONST) { \ (target)->u.constant = CONSTANT(src.constant); \ } else { \ (target)->u.op = src; \ (target)->EA = 0; \ } \ } while (0) #define COPY_NODE(target, src) do { \ target ## _type = src ## _type; \ target = src; \ } while (0) #define CALCULATE_LITERAL_HASH(num) do { \ if (IS_INTERNED(Z_STRVAL(CONSTANT(num)))) { \ Z_HASH_P(&CONSTANT(num)) = INTERNED_HASH(Z_STRVAL(CONSTANT(num))); \ } else { \ Z_HASH_P(&CONSTANT(num)) = zend_hash_func(Z_STRVAL(CONSTANT(num)), Z_STRLEN(CONSTANT(num))+1); \ } \ } while (0) #define GET_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot++; \ } while (0) #define POLYMORPHIC_CACHE_SLOT_SIZE 2 #define GET_POLYMORPHIC_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot; \ CG(active_op_array)->last_cache_slot += POLYMORPHIC_CACHE_SLOT_SIZE; \ } while (0) #define FREE_POLYMORPHIC_CACHE_SLOT(literal) do { \ if (CG(active_op_array)->literals[literal].cache_slot == \ CG(active_op_array)->last_cache_slot - POLYMORPHIC_CACHE_SLOT_SIZE) { \ CG(active_op_array)->literals[literal].cache_slot = -1; \ CG(active_op_array)->last_cache_slot -= POLYMORPHIC_CACHE_SLOT_SIZE; \ } \ } while (0) ZEND_API zend_op_array *(*zend_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); ZEND_API zend_op_array *(*zend_compile_string)(zval *source_string, char *filename TSRMLS_DC); #ifndef ZTS ZEND_API zend_compiler_globals compiler_globals; ZEND_API zend_executor_globals executor_globals; #endif static void zend_duplicate_property_info(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = estrndup(property_info->name, property_info->name_length); } if (property_info->doc_comment) { property_info->doc_comment = estrndup(property_info->doc_comment, property_info->doc_comment_len); } } /* }}} */ static void zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = zend_strndup(property_info->name, property_info->name_length); } } /* }}} */ static void zend_destroy_property_info(zend_property_info *property_info) /* {{{ */ { str_efree(property_info->name); if (property_info->doc_comment) { efree(property_info->doc_comment); } } /* }}} */ static void zend_destroy_property_info_internal(zend_property_info *property_info) /* {{{ */ { str_free(property_info->name); } /* }}} */ static void build_runtime_defined_function_key(zval *result, const char *name, int name_length TSRMLS_DC) /* {{{ */ { char char_pos_buf[32]; uint char_pos_len; char *filename; char_pos_len = zend_sprintf(char_pos_buf, "%p", LANG_SCNG(yy_text)); if (CG(active_op_array)->filename) { filename = CG(active_op_array)->filename; } else { filename = "-"; } /* NULL, name length, filename length, last accepting char position length */ result->value.str.len = 1+name_length+strlen(filename)+char_pos_len; /* must be binary safe */ result->value.str.val = (char *) safe_emalloc(result->value.str.len, 1, 1); result->value.str.val[0] = '\0'; sprintf(result->value.str.val+1, "%s%s%s", name, filename, char_pos_buf); result->type = IS_STRING; Z_SET_REFCOUNT_P(result, 1); } /* }}} */ static void init_compiler_declarables(TSRMLS_D) /* {{{ */ { Z_TYPE(CG(declarables).ticks) = IS_LONG; Z_LVAL(CG(declarables).ticks) = 0; } /* }}} */ void zend_init_compiler_context(TSRMLS_D) /* {{{ */ { CG(context).opcodes_size = (CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) ? INITIAL_INTERACTIVE_OP_ARRAY_SIZE : INITIAL_OP_ARRAY_SIZE; CG(context).vars_size = 0; CG(context).literals_size = 0; CG(context).current_brk_cont = -1; CG(context).backpatch_count = 0; CG(context).labels = NULL; } /* }}} */ void zend_init_compiler_data_structures(TSRMLS_D) /* {{{ */ { zend_stack_init(&CG(bp_stack)); zend_stack_init(&CG(function_call_stack)); zend_stack_init(&CG(switch_cond_stack)); zend_stack_init(&CG(foreach_copy_stack)); zend_stack_init(&CG(object_stack)); zend_stack_init(&CG(declare_stack)); CG(active_class_entry) = NULL; zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_stack_init(&CG(list_stack)); CG(in_compilation) = 0; CG(start_lineno) = 0; CG(current_namespace) = NULL; CG(in_namespace) = 0; CG(has_bracketed_namespaces) = 0; CG(current_import) = NULL; init_compiler_declarables(TSRMLS_C); zend_stack_init(&CG(context_stack)); CG(encoding_declared) = 0; } /* }}} */ ZEND_API void file_handle_dtor(zend_file_handle *fh) /* {{{ */ { TSRMLS_FETCH(); zend_file_handle_dtor(fh TSRMLS_CC); } /* }}} */ void init_compiler(TSRMLS_D) /* {{{ */ { CG(active_op_array) = NULL; zend_init_compiler_data_structures(TSRMLS_C); zend_init_rsrc_list(TSRMLS_C); zend_hash_init(&CG(filenames_table), 5, NULL, (dtor_func_t) free_estring, 0); zend_llist_init(&CG(open_files), sizeof(zend_file_handle), (void (*)(void *)) file_handle_dtor, 0); CG(unclean_shutdown) = 0; } /* }}} */ void shutdown_compiler(TSRMLS_D) /* {{{ */ { zend_stack_destroy(&CG(bp_stack)); zend_stack_destroy(&CG(function_call_stack)); zend_stack_destroy(&CG(switch_cond_stack)); zend_stack_destroy(&CG(foreach_copy_stack)); zend_stack_destroy(&CG(object_stack)); zend_stack_destroy(&CG(declare_stack)); zend_stack_destroy(&CG(list_stack)); zend_hash_destroy(&CG(filenames_table)); zend_llist_destroy(&CG(open_files)); zend_stack_destroy(&CG(context_stack)); } /* }}} */ ZEND_API char *zend_set_compiled_filename(const char *new_compiled_filename TSRMLS_DC) /* {{{ */ { char **pp, *p; int length = strlen(new_compiled_filename); if (zend_hash_find(&CG(filenames_table), new_compiled_filename, length+1, (void **) &pp) == SUCCESS) { CG(compiled_filename) = *pp; return *pp; } p = estrndup(new_compiled_filename, length); zend_hash_update(&CG(filenames_table), new_compiled_filename, length+1, &p, sizeof(char *), (void **) &pp); CG(compiled_filename) = p; return p; } /* }}} */ ZEND_API void zend_restore_compiled_filename(char *original_compiled_filename TSRMLS_DC) /* {{{ */ { CG(compiled_filename) = original_compiled_filename; } /* }}} */ ZEND_API char *zend_get_compiled_filename(TSRMLS_D) /* {{{ */ { return CG(compiled_filename); } /* }}} */ ZEND_API int zend_get_compiled_lineno(TSRMLS_D) /* {{{ */ { return CG(zend_lineno); } /* }}} */ ZEND_API zend_bool zend_is_compiling(TSRMLS_D) /* {{{ */ { return CG(in_compilation); } /* }}} */ static zend_uint get_temporary_variable(zend_op_array *op_array) /* {{{ */ { return (op_array->T)++ * ZEND_MM_ALIGNED_SIZE(sizeof(temp_variable)); } /* }}} */ static int lookup_cv(zend_op_array *op_array, char* name, int name_len TSRMLS_DC) /* {{{ */ { int i = 0; ulong hash_value = zend_inline_hash_func(name, name_len+1); while (i < op_array->last_var) { if (op_array->vars[i].name == name || (op_array->vars[i].hash_value == hash_value && op_array->vars[i].name_len == name_len && memcmp(op_array->vars[i].name, name, name_len) == 0)) { str_efree(name); return i; } i++; } i = op_array->last_var; op_array->last_var++; if (op_array->last_var > CG(context).vars_size) { CG(context).vars_size += 16; /* FIXME */ op_array->vars = erealloc(op_array->vars, CG(context).vars_size * sizeof(zend_compiled_variable)); } op_array->vars[i].name = zend_new_interned_string(name, name_len + 1, 1 TSRMLS_CC); op_array->vars[i].name_len = name_len; op_array->vars[i].hash_value = hash_value; return i; } /* }}} */ void zend_del_literal(zend_op_array *op_array, int n) /* {{{ */ { zval_dtor(&CONSTANT_EX(op_array, n)); if (n + 1 == op_array->last_literal) { op_array->last_literal--; } else { Z_TYPE(CONSTANT_EX(op_array, n)) = IS_NULL; } } /* }}} */ int zend_add_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; if (i >= CG(context).literals_size) { CG(context).literals_size += 16; /* FIXME */ op_array->literals = (zend_literal*)erealloc(op_array->literals, CG(context).literals_size * sizeof(zend_literal)); } if (Z_TYPE_P(zv) == IS_STRING || Z_TYPE_P(zv) == IS_CONSTANT) { zval *z = (zval*)zv; TSRMLS_FETCH(); Z_STRVAL_P(z) = zend_new_interned_string(Z_STRVAL_P(zv), Z_STRLEN_P(zv) + 1, 1 TSRMLS_CC); } CONSTANT_EX(op_array, i) = *zv; Z_SET_REFCOUNT(CONSTANT_EX(op_array, i), 2); Z_SET_ISREF(CONSTANT_EX(op_array, i)); op_array->literals[i].hash_value = 0; op_array->literals[i].cache_slot = -1; return i; } /* }}} */ int zend_add_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_ns_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name, *ns_separator; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); ns_separator = (char *) zend_memrchr(Z_STRVAL_P(zv), '\\', Z_STRLEN_P(zv)) + 1; lc_len = Z_STRLEN_P(zv) - (ns_separator - Z_STRVAL_P(zv)); lc_name = zend_str_tolower_dup(ns_separator, lc_len); ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_class_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } if (Z_STRVAL_P(zv)[0] == '\\') { lc_len = Z_STRLEN_P(zv) - 1; lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv) + 1, lc_len); } else { lc_len = Z_STRLEN_P(zv); lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), lc_len); } ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); GET_CACHE_SLOT(ret); return ret; } /* }}} */ int zend_add_const_name_literal(zend_op_array *op_array, const zval *zv, int unqualified TSRMLS_DC) /* {{{ */ { int ret, tmp_literal; char *name, *tmp_name, *ns_separator; int name_len, ns_len; zval c; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } /* skip leading '\\' */ if (Z_STRVAL_P(zv)[0] == '\\') { name_len = Z_STRLEN_P(zv) - 1; name = Z_STRVAL_P(zv) + 1; } else { name_len = Z_STRLEN_P(zv); name = Z_STRVAL_P(zv); } ns_separator = zend_memrchr(name, '\\', name_len); if (ns_separator) { ns_len = ns_separator - name; } else { ns_len = 0; } if (ns_len) { /* lowercased namespace name & original constant name */ tmp_name = estrndup(name, name_len); zend_str_tolower(tmp_name, ns_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased namespace name & lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); } if (ns_len) { if (!unqualified) { return ret; } ns_len++; name += ns_len; name_len -= ns_len; } /* original constant name */ tmp_name = estrndup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); return ret; } /* }}} */ #define LITERAL_STRINGL(op, str, len, copy) do { \ zval _c; \ ZVAL_STRINGL(&_c, str, len, copy); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG(op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG_EX(op_array, op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(op_array, &_c TSRMLS_CC); \ } while (0) #define LITERAL_NULL(op) do { \ zval _c; \ INIT_ZVAL( _c); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) static inline zend_bool zend_is_function_or_method_call(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; return ((type & ZEND_PARSED_METHOD_CALL) || (type == ZEND_PARSED_FUNCTION_CALL)); } /* }}} */ void zend_do_binary_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_unary_op(zend_uchar op, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); GET_NODE(result, opline->result); SET_UNUSED(opline->op2); } /* }}} */ #define MAKE_NOP(opline) { opline->opcode = ZEND_NOP; memset(&opline->result,0,sizeof(opline->result)); memset(&opline->op1,0,sizeof(opline->op1)); memset(&opline->op2,0,sizeof(opline->op2)); opline->result_type=opline->op1_type=opline->op2_type=IS_UNUSED; } static void zend_do_op_data(zend_op *data_op, const znode *value TSRMLS_DC) /* {{{ */ { data_op->opcode = ZEND_OP_DATA; SET_NODE(data_op->op1, value); SET_UNUSED(data_op->op2); } /* }}} */ void zend_do_binary_assign_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; switch (last_op->opcode) { case ZEND_FETCH_OBJ_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, op2 TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; case ZEND_FETCH_DIM_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_DIM; zend_do_op_data(opline, op2 TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result,last_op->result); return; default: break; } } opline->opcode = op; SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void fetch_simple_variable_ex(znode *result, znode *varname, int bp, zend_uchar op TSRMLS_DC) /* {{{ */ { zend_op opline; zend_op *opline_ptr; zend_llist *fetch_list_ptr; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } if (!zend_is_auto_global(varname->u.constant.value.str.val, varname->u.constant.value.str.len TSRMLS_CC) && !(varname->u.constant.value.str.len == (sizeof("this")-1) && !memcmp(varname->u.constant.value.str.val, "this", sizeof("this"))) && (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE)) { result->op_type = IS_CV; result->u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len TSRMLS_CC); varname->u.constant.value.str.val = CG(active_op_array)->vars[result->u.op.var].name; result->EA = 0; return; } } if (bp) { opline_ptr = &opline; init_op(opline_ptr TSRMLS_CC); } else { opline_ptr = get_next_op(CG(active_op_array) TSRMLS_CC); } opline_ptr->opcode = op; opline_ptr->result_type = IS_VAR; opline_ptr->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline_ptr->op1, varname); GET_NODE(result, opline_ptr->result); SET_UNUSED(opline_ptr->op2); opline_ptr->extended_value = ZEND_FETCH_LOCAL; if (varname->op_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline_ptr->op1.constant); if (zend_is_auto_global(varname->u.constant.value.str.val, varname->u.constant.value.str.len TSRMLS_CC)) { opline_ptr->extended_value = ZEND_FETCH_GLOBAL; } } if (bp) { zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); zend_llist_add_element(fetch_list_ptr, opline_ptr); } } /* }}} */ void fetch_simple_variable(znode *result, znode *varname, int bp TSRMLS_DC) /* {{{ */ { /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ fetch_simple_variable_ex(result, varname, bp, ZEND_FETCH_W TSRMLS_CC); } /* }}} */ void zend_do_fetch_static_member(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { znode class_node; zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline_ptr; zend_op opline; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { ulong fetch_type = ZEND_FETCH_CLASS_GLOBAL; zend_resolve_class_name(class_name, &fetch_type, 1 TSRMLS_CC); class_node = *class_name; } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); } zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (result->op_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[result->u.op.var].name), CG(active_op_array)->vars[result->u.op.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } GET_NODE(result,opline.result); opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; opline_ptr = &opline; zend_llist_add_element(fetch_list_ptr, &opline); } else { le = fetch_list_ptr->head; opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode != ZEND_FETCH_W && opline_ptr->op1_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[opline_ptr->op1.var].name), CG(active_op_array)->vars[opline_ptr->op1.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; COPY_NODE(opline_ptr->op1, opline.result); zend_llist_prepend_element(fetch_list_ptr, &opline); } else { if (opline_ptr->op1_type == IS_CONST) { GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op1.constant); } if (class_node.op_type == IS_CONST) { opline_ptr->op2_type = IS_CONST; opline_ptr->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline_ptr->op2, &class_node); } opline_ptr->extended_value |= ZEND_FETCH_STATIC_MEMBER; } } } /* }}} */ void fetch_array_begin(znode *result, znode *varname, znode *first_dim TSRMLS_DC) /* {{{ */ { fetch_simple_variable(result, varname, 1 TSRMLS_CC); fetch_array_dim(result, result, first_dim TSRMLS_CC); } /* }}} */ void fetch_array_dim(znode *result, const znode *parent, const znode *dim TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (zend_is_function_or_method_call(parent)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, parent); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_DIM_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, parent); SET_NODE(opline.op2, dim); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline.op2.constant)), Z_STRLEN(CONSTANT(opline.op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline.op2.constant)); ZVAL_LONG(&CONSTANT(opline.op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline.op2.constant); } } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void fetch_string_offset(znode *result, const znode *parent, const znode *offset TSRMLS_DC) /* {{{ */ { fetch_array_dim(result, parent, offset TSRMLS_CC); } /* }}} */ void zend_do_print(znode *result, const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->opcode = ZEND_PRINT; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_echo(const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ECHO; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_abstract_method(const znode *function_name, znode *modifiers, const znode *body TSRMLS_DC) /* {{{ */ { char *method_type; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { Z_LVAL(modifiers->u.constant) |= ZEND_ACC_ABSTRACT; method_type = "Interface"; } else { method_type = "Abstract"; } if (modifiers->u.constant.value.lval & ZEND_ACC_ABSTRACT) { if(modifiers->u.constant.value.lval & ZEND_ACC_PRIVATE) { zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot be declared private", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } if (Z_LVAL(body->u.constant) == ZEND_ACC_ABSTRACT) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_RAISE_ABSTRACT_ERROR; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } else { /* we had code in the function body */ zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot contain body", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } else { if (body->u.constant.value.lval == ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Non-abstract method %s::%s() must contain body", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } } /* }}} */ static zend_bool opline_is_fetch_this(const zend_op *opline TSRMLS_DC) /* {{{ */ { if ((opline->opcode == ZEND_FETCH_W) && (opline->op1_type == IS_CONST) && (Z_TYPE(CONSTANT(opline->op1.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(opline->op1.constant)) == (sizeof("this")-1)) && !memcmp(Z_STRVAL(CONSTANT(opline->op1.constant)), "this", sizeof("this"))) { return 1; } else { return 0; } } /* }}} */ void zend_do_assign(znode *result, znode *variable, znode *value TSRMLS_DC) /* {{{ */ { int last_op_number; zend_op *opline; if (value->op_type == IS_CV) { zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (fetch_list_ptr && fetch_list_ptr->head) { opline = (zend_op *)fetch_list_ptr->head->data; if (opline->opcode == ZEND_FETCH_DIM_W && opline->op1_type == IS_CV && opline->op1.var == value->u.op.var) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_R; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->op1_type = IS_CONST; LITERAL_STRINGL(opline->op1, CG(active_op_array)->vars[value->u.op.var].name, CG(active_op_array)->vars[value->u.op.var].name_len, 1); CALCULATE_LITERAL_HASH(opline->op1.constant); SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_LOCAL; GET_NODE(value, opline->result); } } } zend_do_end_variable_parse(variable, BP_VAR_W, 0 TSRMLS_CC); last_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (variable->op_type == IS_CV) { if (variable->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (variable->op_type == IS_VAR) { int n = 0; while (last_op_number - n > 0) { zend_op *last_op; last_op = &CG(active_op_array)->opcodes[last_op_number-n-1]; if (last_op->result_type == IS_VAR && last_op->result.var == variable->u.op.var) { if (last_op->opcode == ZEND_FETCH_OBJ_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, value TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (last_op->opcode == ZEND_FETCH_DIM_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ /* TBFixed: this can realloc opcodes, leaving last_op pointing wrong */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_DIM; zend_do_op_data(opline, value TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (opline_is_fetch_this(last_op TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } else { break; } } n++; } } opline->opcode = ZEND_ASSIGN; SET_NODE(opline->op1, variable); SET_NODE(opline->op2, value); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_assign_ref(znode *result, const znode *lvar, const znode *rvar TSRMLS_DC) /* {{{ */ { zend_op *opline; if (lvar->op_type == IS_CV) { if (lvar->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (lvar->op_type == IS_VAR) { int last_op_number = get_next_op_number(CG(active_op_array)); if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline_is_fetch_this(opline TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ASSIGN_REF; if (zend_is_function_or_method_call(rvar)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } else if (rvar->EA & ZEND_PARSED_NEW) { opline->extended_value = ZEND_RETURNS_NEW; } else { opline->extended_value = 0; } if (result) { opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } else { opline->result_type = IS_UNUSED | EXT_TYPE_UNUSED; } SET_NODE(opline->op1, lvar); SET_NODE(opline->op2, rvar); } /* }}} */ static inline void do_begin_loop(TSRMLS_D) /* {{{ */ { zend_brk_cont_element *brk_cont_element; int parent; parent = CG(context).current_brk_cont; CG(context).current_brk_cont = CG(active_op_array)->last_brk_cont; brk_cont_element = get_next_brk_cont_element(CG(active_op_array)); brk_cont_element->start = get_next_op_number(CG(active_op_array)); brk_cont_element->parent = parent; } /* }}} */ static inline void do_end_loop(int cont_addr, int has_loop_var TSRMLS_DC) /* {{{ */ { if (!has_loop_var) { /* The start fileld is used to free temporary variables in case of exceptions. * We won't try to free something of we don't have loop variable. */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].start = -1; } CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = cont_addr; CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; } /* }}} */ void zend_do_while_cond(const znode *expr, znode *close_bracket_token TSRMLS_DC) /* {{{ */ { int while_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, expr); close_bracket_token->u.op.opline_num = while_cond_op_number; SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_while_end(const znode *while_token, const znode *close_bracket_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* add unconditional jump */ opline->opcode = ZEND_JMP; opline->op1.opline_num = while_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* update while's conditional jmp */ CG(active_op_array)->opcodes[close_bracket_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); do_end_loop(while_token->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_cond(const znode *expr, znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { int for_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZNZ; SET_NODE(opline->op1, expr); /* the conditional expression */ second_semicolon_token->u.op.opline_num = for_cond_op_number; SET_UNUSED(opline->op2); } /* }}} */ void zend_do_for_before_statement(const znode *cond_start, const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = cond_start->u.op.opline_num; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_end(const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = second_semicolon_token->u.op.opline_num+1; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_end_loop(second_semicolon_token->u.op.opline_num+1, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_pre_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_PRE_INC)?ZEND_PRE_INC_OBJ:ZEND_PRE_DEC_OBJ; last_op->result_type = IS_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_post_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_POST_INC)?ZEND_POST_INC_OBJ:ZEND_POST_DEC_OBJ; last_op->result_type = IS_TMP_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_if_cond(const znode *cond, znode *closing_bracket_token TSRMLS_DC) /* {{{ */ { int if_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); closing_bracket_token->u.op.opline_num = if_cond_op_number; SET_UNUSED(opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_if_after_statement(const znode *closing_bracket_token, unsigned char initialize TSRMLS_DC) /* {{{ */ { int if_end_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; /* save for backpatching */ if (initialize) { zend_llist jmp_list; zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); } zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &if_end_op_number); CG(active_op_array)->opcodes[closing_bracket_token->u.op.opline_num].op2.opline_num = if_end_op_number+1; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_if_end(TSRMLS_D) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_llist *jmp_list_ptr; zend_llist_element *le; zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); for (le=jmp_list_ptr->head; le; le = le->next) { CG(active_op_array)->opcodes[*((int *) le->data)].op1.opline_num = next_op_number; } zend_llist_destroy(jmp_list_ptr); zend_stack_del_top(&CG(bp_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_check_writable_variable(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; if (type & ZEND_PARSED_METHOD_CALL) { zend_error(E_COMPILE_ERROR, "Can't use method return value in write context"); } if (type == ZEND_PARSED_FUNCTION_CALL) { zend_error(E_COMPILE_ERROR, "Can't use function return value in write context"); } } /* }}} */ void zend_do_begin_variable_parse(TSRMLS_D) /* {{{ */ { zend_llist fetch_list; zend_llist_init(&fetch_list, sizeof(zend_op), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &fetch_list, sizeof(zend_llist)); } /* }}} */ void zend_do_end_variable_parse(znode *variable, int type, int arg_offset TSRMLS_DC) /* {{{ */ { zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline = NULL; zend_op *opline_ptr; zend_uint this_var = -1; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); le = fetch_list_ptr->head; /* TODO: $foo->x->y->z = 1 should fetch "x" and "y" for R or RW, not just W */ if (le) { opline_ptr = (zend_op *)le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { /* convert to FETCH_?(this) into IS_CV */ if (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE) { this_var = opline_ptr->result.var; if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), Z_STRVAL(CONSTANT(opline_ptr->op1.constant)), Z_STRLEN(CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC); Z_TYPE(CONSTANT(opline_ptr->op1.constant)) = IS_NULL; } else { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); } le = le->next; if (variable->op_type == IS_VAR && variable->u.op.var == this_var) { variable->op_type = IS_CV; variable->u.op.var = CG(active_op_array)->this_var; } } else if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1 TSRMLS_CC); } } while (le) { opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode == ZEND_SEPARATE) { if (type != BP_VAR_R && type != BP_VAR_IS) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); } le = le->next; continue; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); if (opline->op1_type == IS_VAR && opline->op1.var == this_var) { opline->op1_type = IS_CV; opline->op1.var = CG(active_op_array)->this_var; } switch (type) { case BP_VAR_R: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode -= 3; break; case BP_VAR_W: break; case BP_VAR_RW: opline->opcode += 3; break; case BP_VAR_IS: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode += 6; /* 3+3 */ break; case BP_VAR_FUNC_ARG: opline->opcode += 9; /* 3+3+3 */ opline->extended_value |= arg_offset; break; case BP_VAR_UNSET: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for unsetting"); } opline->opcode += 12; /* 3+3+3+3 */ break; } le = le->next; } if (opline && type == BP_VAR_W && arg_offset) { opline->extended_value |= ZEND_FETCH_MAKE_REF; } } zend_llist_destroy(fetch_list_ptr); zend_stack_del_top(&CG(bp_stack)); } /* }}} */ void zend_do_add_string(znode *result, const znode *op1, znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline; if (Z_STRLEN(op2->u.constant) > 1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_STRING; } else if (Z_STRLEN(op2->u.constant) == 1) { int ch = *Z_STRVAL(op2->u.constant); /* Free memory and use ZEND_ADD_CHAR in case of 1 character strings */ efree(Z_STRVAL(op2->u.constant)); ZVAL_LONG(&op2->u.constant, ch); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_CHAR; } else { /* String can be empty after a variable at the end of a heredoc */ efree(Z_STRVAL(op2->u.constant)); return; } if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_add_variable(znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_VAR; if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_free(znode *op1 TSRMLS_DC) /* {{{ */ { if (op1->op_type==IS_TMP_VAR) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else if (op1->op_type==IS_VAR) { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; while (opline->opcode == ZEND_END_SILENCE || opline->opcode == ZEND_EXT_FCALL_END || opline->opcode == ZEND_OP_DATA) { opline--; } if (opline->result_type == IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_FETCH_R || opline->opcode == ZEND_FETCH_DIM_R || opline->opcode == ZEND_FETCH_OBJ_R) { /* It's very rare and useless case. It's better to use additional FREE opcode and simplify the FETCH handlers their selves */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else { opline->result_type |= EXT_TYPE_UNUSED; } } else { while (opline>CG(active_op_array)->opcodes) { if (opline->opcode == ZEND_FETCH_DIM_R && opline->op1_type == IS_VAR && opline->op1.var == op1->u.op.var) { /* This should the end of a list() construct * Mark its result as unused */ opline->extended_value = ZEND_FETCH_STANDARD; break; } else if (opline->result_type==IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_NEW) { opline->result_type |= EXT_TYPE_UNUSED; } break; } opline--; } } } else if (op1->op_type == IS_CONST) { zval_dtor(&op1->u.constant); } } /* }}} */ int zend_do_verify_access_types(const znode *current_access_type, const znode *new_modifier) /* {{{ */ { if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_PPP_MASK) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Multiple access type modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_ABSTRACT) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Multiple abstract modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_STATIC) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Multiple static modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_FINAL) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Multiple final modifiers are not allowed"); } if (((Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)) & (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) == (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Cannot use the final modifier on an abstract class member"); } return (Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)); } /* }}} */ void zend_do_begin_function_declaration(znode *function_token, znode *function_name, int is_method, int return_reference, znode *fn_flags_znode TSRMLS_DC) /* {{{ */ { zend_op_array op_array; char *name = function_name->u.constant.value.str.val; int name_len = function_name->u.constant.value.str.len; int function_begin_line = function_token->u.op.opline_num; zend_uint fn_flags; char *lcname; zend_bool orig_interactive; ALLOCA_FLAG(use_heap) if (is_method) { if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((Z_LVAL(fn_flags_znode->u.constant) & ~(ZEND_ACC_STATIC|ZEND_ACC_PUBLIC))) { zend_error(E_COMPILE_ERROR, "Access type for interface method %s::%s() must be omitted", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } Z_LVAL(fn_flags_znode->u.constant) |= ZEND_ACC_ABSTRACT; /* propagates to the rest of the parser */ } fn_flags = Z_LVAL(fn_flags_znode->u.constant); /* must be done *after* the above check */ } else { fn_flags = 0; } if ((fn_flags & ZEND_ACC_STATIC) && (fn_flags & ZEND_ACC_ABSTRACT) && !(CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_STRICT, "Static function %s%s%s() should not be abstract", is_method ? CG(active_class_entry)->name : "", is_method ? "::" : "", Z_STRVAL(function_name->u.constant)); } function_token->u.op_array = CG(active_op_array); orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(&op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; op_array.function_name = name; if (return_reference) { op_array.fn_flags |= ZEND_ACC_RETURN_REFERENCE; } op_array.fn_flags |= fn_flags; op_array.scope = is_method?CG(active_class_entry):NULL; op_array.prototype = NULL; op_array.line_start = zend_get_compiled_lineno(TSRMLS_C); if (is_method) { lcname = zend_new_interned_string(zend_str_tolower_dup(name, name_len), name_len + 1, 1 TSRMLS_CC); if (zend_hash_add(&CG(active_class_entry)->function_table, lcname, name_len+1, &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)) == FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::%s()", CG(active_class_entry)->name, name); } zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); if (fn_flags & ZEND_ACC_ABSTRACT) { CG(active_class_entry)->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (!(fn_flags & ZEND_ACC_PPP_MASK)) { fn_flags |= ZEND_ACC_PUBLIC; } if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } } } else { char *class_lcname; class_lcname = do_alloca(CG(active_class_entry)->name_length + 1, use_heap); zend_str_tolower_copy(class_lcname, CG(active_class_entry)->name, CG(active_class_entry)->name_length); /* Improve after RC: cache the lowercase class name */ if ((CG(active_class_entry)->name_length == name_len) && ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT) && (!memcmp(class_lcname, lcname, name_len))) { if (!CG(active_class_entry)->constructor) { CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } } else if ((name_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)))) { if (CG(active_class_entry)->constructor) { zend_error(E_STRICT, "Redefining already defined constructor for class %s", CG(active_class_entry)->name); } CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1))) { CG(active_class_entry)->destructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1))) { CG(active_class_entry)->clone = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } CG(active_class_entry)->__call = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } CG(active_class_entry)->__callstatic = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } CG(active_class_entry)->__get = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } CG(active_class_entry)->__set = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } CG(active_class_entry)->__unset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } CG(active_class_entry)->__isset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } CG(active_class_entry)->__tostring = (zend_function *) CG(active_op_array); } else if (!(fn_flags & ZEND_ACC_STATIC)) { CG(active_op_array)->fn_flags |= ZEND_ACC_ALLOW_STATIC; } free_alloca(class_lcname, use_heap); } str_efree(lcname); } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zval key; if (CG(current_namespace)) { /* Prefix function name with current namespcae name */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, function_name TSRMLS_CC); op_array.function_name = Z_STRVAL(tmp.u.constant); name_len = Z_STRLEN(tmp.u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), name_len); } else { lcname = zend_str_tolower_dup(name, name_len); } opline->opcode = ZEND_DECLARE_FUNCTION; opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, name_len TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; LITERAL_STRINGL(opline->op2, lcname, name_len, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); opline->extended_value = ZEND_DECLARE_FUNCTION; zend_hash_quick_update(CG(function_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); } if (CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_NOP; opline->lineno = function_begin_line; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } { /* Push a seperator to the switch and foreach stacks */ zend_switch_entry switch_entry; switch_entry.cond.op_type = IS_UNUSED; switch_entry.default_case = 0; switch_entry.control_var = 0; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); { /* Foreach stack separator */ zend_op dummy_opline; dummy_opline.result_type = IS_UNUSED; dummy_opline.op1_type = IS_UNUSED; zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); } } if (CG(doc_comment)) { CG(active_op_array)->doc_comment = CG(doc_comment); CG(active_op_array)->doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_begin_lambda_function_declaration(znode *result, znode *function_token, int return_reference, int is_static TSRMLS_DC) /* {{{ */ { znode function_name; zend_op_array *current_op_array = CG(active_op_array); int current_op_number = get_next_op_number(CG(active_op_array)); zend_op *current_op; function_name.op_type = IS_CONST; ZVAL_STRINGL(&function_name.u.constant, "{closure}", sizeof("{closure}")-1, 1); zend_do_begin_function_declaration(function_token, &function_name, 0, return_reference, NULL TSRMLS_CC); result->op_type = IS_TMP_VAR; result->u.op.var = get_temporary_variable(current_op_array); current_op = &current_op_array->opcodes[current_op_number]; current_op->opcode = ZEND_DECLARE_LAMBDA_FUNCTION; zend_del_literal(current_op_array, current_op->op2.constant); SET_UNUSED(current_op->op2); SET_NODE(current_op->result, result); if (is_static) { CG(active_op_array)->fn_flags |= ZEND_ACC_STATIC; } CG(active_op_array)->fn_flags |= ZEND_ACC_CLOSURE; } /* }}} */ void zend_do_handle_exception(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_HANDLE_EXCEPTION; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_function_declaration(const znode *function_token TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; zend_do_extended_info(TSRMLS_C); zend_do_return(NULL, 0 TSRMLS_CC); pass_two(CG(active_op_array) TSRMLS_CC); zend_release_labels(TSRMLS_C); if (CG(active_class_entry)) { zend_check_magic_method_implementation(CG(active_class_entry), (zend_function*)CG(active_op_array), E_COMPILE_ERROR TSRMLS_CC); } else { /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(CG(active_op_array)->function_name); zend_str_tolower_copy(lcname, CG(active_op_array)->function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME)) && CG(active_op_array)->num_args != 1) { zend_error(E_COMPILE_ERROR, "%s() must take exactly 1 argument", ZEND_AUTOLOAD_FUNC_NAME); } } CG(active_op_array)->line_end = zend_get_compiled_lineno(TSRMLS_C); CG(active_op_array) = function_token->u.op_array; /* Pop the switch and foreach seperators */ zend_stack_del_top(&CG(switch_cond_stack)); zend_stack_del_top(&CG(foreach_copy_stack)); } /* }}} */ void zend_do_receive_arg(zend_uchar op, znode *varname, const znode *offset, const znode *initialization, znode *class_type, zend_uchar pass_by_reference TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_arg_info *cur_arg_info; znode var; if (class_type->op_type == IS_CONST && Z_TYPE(class_type->u.constant) == IS_STRING && Z_STRLEN(class_type->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_type->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } if (zend_is_auto_global(Z_STRVAL(varname->u.constant), Z_STRLEN(varname->u.constant) TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign auto-global variable %s", Z_STRVAL(varname->u.constant)); } else { var.op_type = IS_CV; var.u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len TSRMLS_CC); varname->u.constant.value.str.val = CG(active_op_array)->vars[var.u.op.var].name; var.EA = 0; if (Z_STRLEN(varname->u.constant) == sizeof("this")-1 && !memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this")-1)) { if (CG(active_op_array)->scope && (CG(active_op_array)->fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } CG(active_op_array)->this_var = var.u.op.var; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->num_args++; opline->opcode = op; SET_NODE(opline->result, &var); SET_NODE(opline->op1, offset); if (op == ZEND_RECV_INIT) { SET_NODE(opline->op2, initialization); } else { CG(active_op_array)->required_num_args = CG(active_op_array)->num_args; SET_UNUSED(opline->op2); } CG(active_op_array)->arg_info = erealloc(CG(active_op_array)->arg_info, sizeof(zend_arg_info)*(CG(active_op_array)->num_args)); cur_arg_info = &CG(active_op_array)->arg_info[CG(active_op_array)->num_args-1]; cur_arg_info->name = zend_new_interned_string(estrndup(varname->u.constant.value.str.val, varname->u.constant.value.str.len), varname->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->name_len = varname->u.constant.value.str.len; cur_arg_info->type_hint = 0; cur_arg_info->allow_null = 1; cur_arg_info->pass_by_reference = pass_by_reference; cur_arg_info->class_name = NULL; cur_arg_info->class_name_len = 0; if (class_type->op_type != IS_UNUSED) { cur_arg_info->allow_null = 0; cur_arg_info->type_hint = class_type->u.constant.type; switch (class_type->u.constant.type) { case IS_CLASS: if (ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_type->u.constant), Z_STRLEN(class_type->u.constant))) { zend_resolve_class_name(class_type, &opline->extended_value, 1 TSRMLS_CC); } class_type->u.constant.value.str.val = zend_new_interned_string(class_type->u.constant.value.str.val, class_type->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->class_name = class_type->u.constant.value.str.val; cur_arg_info->class_name_len = class_type->u.constant.value.str.len; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with a class type hint can only be NULL"); } } break; case IS_ARRAY: if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else if (Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Default value for parameters with array type hint can only be an array or NULL"); } } break; /* scalar type hinting */ case IS_SCALAR: if (op == ZEND_RECV_INIT && Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { break; } /* fall through */ /* scalar type hinting */ case IS_NUMERIC: if (op == ZEND_RECV_INIT && (Z_TYPE(initialization->u.constant) == IS_LONG || Z_TYPE(initialization->u.constant) == IS_DOUBLE)) { break; } /* fall through */ case IS_BOOL: case IS_STRING: case IS_LONG: case IS_DOUBLE: case IS_RESOURCE: case IS_OBJECT: if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) != class_type->u.constant.type && Z_TYPE(initialization->u.constant) != IS_NULL && (Z_TYPE(initialization->u.constant) & IS_CONSTANT_TYPE_MASK) != IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Default value for parameters with %s type hint can only be %s or NULL", zend_get_type_by_const(class_type->u.constant.type), zend_get_type_by_const(class_type->u.constant.type)); } else if (Z_TYPE(initialization->u.constant) == IS_NULL) { cur_arg_info->allow_null = 1; } } break; default: zend_error(E_COMPILE_ERROR, "Unknown type hint"); } } } /* }}} */ int zend_do_begin_function_call(znode *function_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { zend_function *function; char *lcname; char *is_compound = memchr(Z_STRVAL(function_name->u.constant), '\\', Z_STRLEN(function_name->u.constant)); zend_resolve_non_class_name(function_name, check_namespace TSRMLS_CC); if (check_namespace && CG(current_namespace) && !is_compound) { /* We assume we call function from the current namespace if it is not prefixed. */ /* In run-time PHP will check for function with full name and internal function with short name */ zend_do_begin_dynamic_function_call(function_name, 1 TSRMLS_CC); return 1; } lcname = zend_str_tolower_dup(function_name->u.constant.value.str.val, function_name->u.constant.value.str.len); if ((zend_hash_find(CG(function_table), lcname, function_name->u.constant.value.str.len+1, (void **) &function)==FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_FUNCTIONS) && (function->type == ZEND_INTERNAL_FUNCTION))) { zend_do_begin_dynamic_function_call(function_name, 0 TSRMLS_CC); efree(lcname); return 1; /* Dynamic */ } efree(function_name->u.constant.value.str.val); function_name->u.constant.value.str.val = lcname; zend_stack_push(&CG(function_call_stack), (void *) &function, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 0; } /* }}} */ void zend_do_begin_method_call(znode *left_bracket TSRMLS_DC) /* {{{ */ { zend_op *last_op; int last_op_number; unsigned char *ptr = NULL; zend_do_end_variable_parse(left_bracket, BP_VAR_R, 0 TSRMLS_CC); zend_do_begin_variable_parse(TSRMLS_C); last_op_number = get_next_op_number(CG(active_op_array))-1; last_op = &CG(active_op_array)->opcodes[last_op_number]; if ((last_op->op2_type == IS_CONST) && (Z_TYPE(CONSTANT(last_op->op2.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(last_op->op2.constant)) == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !zend_binary_strcasecmp(Z_STRVAL(CONSTANT(last_op->op2.constant)), Z_STRLEN(CONSTANT(last_op->op2.constant)), ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1)) { zend_error(E_COMPILE_ERROR, "Cannot call __clone() method on objects - use 'clone $obj' instead"); } if (last_op->opcode == ZEND_FETCH_OBJ_R) { if (last_op->op2_type == IS_CONST) { zval name; name = CONSTANT(last_op->op2.constant); if (!IS_INTERNED(Z_STRVAL(name))) { Z_STRVAL(name) = estrndup(Z_STRVAL(name), Z_STRLEN(name)); } FREE_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); last_op->op2.constant = zend_add_func_name_literal(CG(active_op_array), &name TSRMLS_CC); GET_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); } last_op->opcode = ZEND_INIT_METHOD_CALL; SET_UNUSED(last_op->result); Z_LVAL(left_bracket->u.constant) = ZEND_INIT_FCALL_BY_NAME; } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (left_bracket->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &left_bracket->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, left_bracket); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_do_clone(znode *result, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CLONE; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_begin_dynamic_function_call(znode *function_name, int ns_call TSRMLS_DC) /* {{{ */ { unsigned char *ptr = NULL; zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (ns_call) { /* In run-time PHP will check for function with full name and internal function with short name */ opline->opcode = ZEND_INIT_NS_FCALL_BY_NAME; SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_ns_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (function_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, function_name); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_resolve_non_class_name(znode *element_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; int len; zval **ns; char *lcname, *compound = memchr(Z_STRVAL(element_name->u.constant), '\\', Z_STRLEN(element_name->u.constant)); if (Z_STRVAL(element_name->u.constant)[0] == '\\') { /* name starts with \ so it is known and unambiguos, nothing to do here but shorten it */ memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+1, Z_STRLEN(element_name->u.constant)); --Z_STRLEN(element_name->u.constant); return; } if(!check_namespace) { return; } if (compound && CG(current_import)) { len = compound - Z_STRVAL(element_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(element_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(element_name->u.constant) -= len; memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+len, Z_STRLEN(element_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, element_name TSRMLS_CC); *element_name = tmp; efree(lcname); return; } efree(lcname); } if (CG(current_namespace)) { tmp = *element_name; Z_STRLEN(tmp.u.constant) = sizeof("\\")-1 + Z_STRLEN(element_name->u.constant) + Z_STRLEN_P(CG(current_namespace)); Z_STRVAL(tmp.u.constant) = (char *) emalloc(Z_STRLEN(tmp.u.constant)+1); memcpy(Z_STRVAL(tmp.u.constant), Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace))]), "\\", sizeof("\\")-1); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace)) + sizeof("\\")-1]), Z_STRVAL(element_name->u.constant), Z_STRLEN(element_name->u.constant)+1); STR_FREE(Z_STRVAL(element_name->u.constant)); *element_name = tmp; } } /* }}} */ void zend_resolve_class_name(znode *class_name, ulong *fetch_type, int check_ns_name TSRMLS_DC) /* {{{ */ { char *compound; char *lcname; zval **ns; znode tmp; int len; compound = memchr(Z_STRVAL(class_name->u.constant), '\\', Z_STRLEN(class_name->u.constant)); if (compound) { /* This is a compound class name that contains namespace prefix */ if (Z_STRVAL(class_name->u.constant)[0] == '\\') { /* The STRING name has "\" prefix */ Z_STRLEN(class_name->u.constant) -= 1; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+1, Z_STRLEN(class_name->u.constant)+1); Z_STRVAL(class_name->u.constant) = erealloc( Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1); if (ZEND_FETCH_CLASS_DEFAULT != zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "'\\%s' is an invalid class name", Z_STRVAL(class_name->u.constant)); } } else { if (CG(current_import)) { len = compound - Z_STRVAL(class_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(class_name->u.constant) -= len; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+len, Z_STRLEN(class_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; efree(lcname); return; } efree(lcname); } /* Here name is not prefixed with \ and not imported */ if (CG(current_namespace)) { tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } } } else if (CG(current_import) || CG(current_namespace)) { /* this is a plain name (without \) */ lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns) == SUCCESS) { /* The given name is an import name. Substitute it. */ zval_dtor(&class_name->u.constant); class_name->u.constant = **ns; zval_copy_ctor(&class_name->u.constant); } else if (CG(current_namespace)) { /* plain name, no import - prepend current namespace to it */ tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } efree(lcname); } } /* }}} */ void zend_do_fetch_class(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { long fetch_class_op_number; zend_op *opline; if (class_name->op_type == IS_CONST && Z_TYPE(class_name->u.constant) == IS_STRING && Z_STRLEN(class_name->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_name->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } fetch_class_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CLASS; SET_UNUSED(opline->op1); opline->extended_value = ZEND_FETCH_CLASS_GLOBAL; CG(catch_begin) = fetch_class_op_number; if (class_name->op_type == IS_CONST) { int fetch_type; fetch_type = zend_get_class_fetch_type(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); switch (fetch_type) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: SET_UNUSED(opline->op2); opline->extended_value = fetch_type; zval_dtor(&class_name->u.constant); break; default: zend_resolve_class_name(class_name, &opline->extended_value, 0 TSRMLS_CC); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_name->u.constant TSRMLS_CC); break; } } else { SET_NODE(opline->op2, class_name); } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; /* FIXME: Hack so that INIT_FCALL_BY_NAME still knows this is a class */ GET_NODE(result, opline->result); result->EA = opline->extended_value; } /* }}} */ void zend_do_label(znode *label TSRMLS_DC) /* {{{ */ { zend_label dest; if (!CG(context).labels) { ALLOC_HASHTABLE(CG(context).labels); zend_hash_init(CG(context).labels, 4, NULL, NULL, 0); } dest.brk_cont = CG(context).current_brk_cont; dest.opline_num = get_next_op_number(CG(active_op_array)); if (zend_hash_add(CG(context).labels, Z_STRVAL(label->u.constant), Z_STRLEN(label->u.constant) + 1, (void**)&dest, sizeof(zend_label), NULL) == FAILURE) { zend_error(E_COMPILE_ERROR, "Label '%s' already defined", Z_STRVAL(label->u.constant)); } /* Done with label now */ zval_dtor(&label->u.constant); } /* }}} */ void zend_resolve_goto_label(zend_op_array *op_array, zend_op *opline, int pass2 TSRMLS_DC) /* {{{ */ { zend_label *dest; long current, distance; zval *label; if (pass2) { label = opline->op2.zv; } else { label = &CONSTANT_EX(op_array, opline->op2.constant); } if (CG(context).labels == NULL || zend_hash_find(CG(context).labels, Z_STRVAL_P(label), Z_STRLEN_P(label)+1, (void**)&dest) == FAILURE) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; zend_error(E_COMPILE_ERROR, "'goto' to undefined label '%s'", Z_STRVAL_P(label)); } else { /* Label is not defined. Delay to pass 2. */ INC_BPC(op_array); return; } } opline->op1.opline_num = dest->opline_num; zval_dtor(label); Z_TYPE_P(label) = IS_NULL; /* Check that we are not moving into loop or switch */ current = opline->extended_value; for (distance = 0; current != dest->brk_cont; distance++) { if (current == -1) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; } zend_error(E_COMPILE_ERROR, "'goto' into loop or switch statement is disallowed"); } current = op_array->brk_cont_array[current].parent; } if (distance == 0) { /* Nothing to break out of, optimize to ZEND_JMP */ opline->opcode = ZEND_JMP; opline->extended_value = 0; SET_UNUSED(opline->op2); } else { /* Set real break distance */ ZVAL_LONG(label, distance); } if (pass2) { DEC_BPC(op_array); } } /* }}} */ void zend_do_goto(const znode *label TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_GOTO; opline->extended_value = CG(context).current_brk_cont; SET_UNUSED(opline->op1); SET_NODE(opline->op2, label); zend_resolve_goto_label(CG(active_op_array), opline, 0 TSRMLS_CC); } /* }}} */ void zend_release_labels(TSRMLS_D) /* {{{ */ { if (CG(context).labels) { zend_hash_destroy(CG(context).labels); FREE_HASHTABLE(CG(context).labels); } if (!zend_stack_is_empty(&CG(context_stack))) { zend_compiler_context *ctx; zend_stack_top(&CG(context_stack), (void**)&ctx); CG(context) = *ctx; zend_stack_del_top(&CG(context_stack)); } } /* }}} */ void zend_do_build_full_name(znode *result, znode *prefix, znode *name, int is_class_member TSRMLS_DC) /* {{{ */ { zend_uint length; if (!result) { result = prefix; } else { *result = *prefix; } if (is_class_member) { length = sizeof("::")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "::", sizeof("::")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("::")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } else { length = sizeof("\\")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "\\", sizeof("\\")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("\\")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } } /* }}} */ int zend_do_begin_class_member_function_call(znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { znode class_node; unsigned char *ptr = NULL; zend_op *opline; ulong fetch_type = 0; if (method_name->op_type == IS_CONST) { char *lcname = zend_str_tolower_dup(Z_STRVAL(method_name->u.constant), Z_STRLEN(method_name->u.constant)); if ((sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == Z_STRLEN(method_name->u.constant) && memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == 0) { zval_dtor(&method_name->u.constant); method_name->op_type = IS_UNUSED; } efree(lcname); } if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { fetch_type = ZEND_FETCH_CLASS_GLOBAL; zend_resolve_class_name(class_name, &fetch_type, 1 TSRMLS_CC); class_node = *class_name; opline = get_next_op(CG(active_op_array) TSRMLS_CC); } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->extended_value = class_node.EA ; } opline->opcode = ZEND_INIT_STATIC_METHOD_CALL; if (class_node.op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, &class_node); } if (method_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &method_name->u.constant TSRMLS_CC); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } } else { SET_NODE(opline->op2, method_name); } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 1; /* Dynamic */ } /* }}} */ void zend_do_end_function_call(znode *function_name, znode *result, const znode *argument_list, int is_method, int is_dynamic_fcall TSRMLS_DC) /* {{{ */ { zend_op *opline; if (is_method && function_name && function_name->op_type == IS_UNUSED) { /* clone */ if (Z_LVAL(argument_list->u.constant) != 0) { zend_error(E_WARNING, "Clone method does not require arguments"); } opline = &CG(active_op_array)->opcodes[Z_LVAL(function_name->u.constant)]; } else { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (!is_method && !is_dynamic_fcall && function_name->op_type==IS_CONST) { opline->opcode = ZEND_DO_FCALL; SET_NODE(opline->op1, function_name); CALCULATE_LITERAL_HASH(opline->op1.constant); GET_CACHE_SLOT(opline->op1.constant); } else { opline->opcode = ZEND_DO_FCALL_BY_NAME; SET_UNUSED(opline->op1); } } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(result, opline->result) ; SET_UNUSED(opline->op2); zend_stack_del_top(&CG(function_call_stack)); opline->extended_value = Z_LVAL(argument_list->u.constant); } /* }}} */ void zend_do_pass_param(znode *param, zend_uchar op, int offset TSRMLS_DC) /* {{{ */ { zend_op *opline; int original_op=op; zend_function **function_ptr_ptr, *function_ptr; int send_by_reference; int send_function = 0; zend_stack_top(&CG(function_call_stack), (void **) &function_ptr_ptr); function_ptr = *function_ptr_ptr; if (original_op == ZEND_SEND_REF) { if (function_ptr && function_ptr->common.function_name && function_ptr->common.type == ZEND_USER_FUNCTION && !ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed; " "If you would like to pass argument by reference, modify the declaration of %s().", function_ptr->common.function_name); } else { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed"); } return; } if (function_ptr) { if (ARG_MAY_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { if (param->op_type & (IS_VAR|IS_CV)) { send_by_reference = 1; if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION | ZEND_ARG_SEND_SILENT; } } else { op = ZEND_SEND_VAL; send_by_reference = 0; } } else { send_by_reference = ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset) ? ZEND_ARG_SEND_BY_REF : 0; } } else { send_by_reference = 0; } if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION; } else if (op == ZEND_SEND_VAL && (param->op_type & (IS_VAR|IS_CV))) { op = ZEND_SEND_VAR_NO_REF; } if (op!=ZEND_SEND_VAR_NO_REF && send_by_reference==ZEND_ARG_SEND_BY_REF) { /* change to passing by reference */ switch (param->op_type) { case IS_VAR: case IS_CV: op = ZEND_SEND_REF; break; default: zend_error(E_COMPILE_ERROR, "Only variables can be passed by reference"); break; } } if (original_op == ZEND_SEND_VAR) { switch (op) { case ZEND_SEND_VAR_NO_REF: zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); break; case ZEND_SEND_VAR: if (function_ptr) { zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(param, BP_VAR_FUNC_ARG, offset TSRMLS_CC); } break; case ZEND_SEND_REF: zend_do_end_variable_parse(param, BP_VAR_W, 0 TSRMLS_CC); break; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (op == ZEND_SEND_VAR_NO_REF) { if (function_ptr) { opline->extended_value = ZEND_ARG_COMPILE_TIME_BOUND | send_by_reference | send_function; } else { opline->extended_value = send_function; } } else { if (function_ptr) { opline->extended_value = ZEND_DO_FCALL; } else { opline->extended_value = ZEND_DO_FCALL_BY_NAME; } } opline->opcode = op; SET_NODE(opline->op1, param); opline->op2.opline_num = offset; SET_UNUSED(opline->op2); } /* }}} */ static int generate_free_switch_expr(const zend_switch_entry *switch_entry TSRMLS_DC) /* {{{ */ { zend_op *opline; if (switch_entry->cond.op_type != IS_VAR && switch_entry->cond.op_type != IS_TMP_VAR) { return (switch_entry->cond.op_type == IS_UNUSED); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry->cond); SET_UNUSED(opline->op2); opline->extended_value = 0; return 0; } /* }}} */ static int generate_free_foreach_copy(const zend_op *foreach_copy TSRMLS_DC) /* {{{ */ { zend_op *opline; /* If we reach the seperator then stop applying the stack */ if (foreach_copy->result_type == IS_UNUSED && foreach_copy->op1_type == IS_UNUSED) { return 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->result_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->result); SET_UNUSED(opline->op2); opline->extended_value = 1; if (foreach_copy->op1_type != IS_UNUSED) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->op1_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->op1); SET_UNUSED(opline->op2); opline->extended_value = 0; } return 0; } /* }}} */ void zend_do_return(znode *expr, int do_end_vparse TSRMLS_DC) /* {{{ */ { zend_op *opline; int start_op_number, end_op_number; if (do_end_vparse) { if ((CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) && !zend_is_function_or_method_call(expr)) { zend_do_end_variable_parse(expr, BP_VAR_W, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(expr, BP_VAR_R, 0 TSRMLS_CC); } } start_op_number = get_next_op_number(CG(active_op_array)); #ifdef ZTS zend_stack_apply_with_argument(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_switch_expr TSRMLS_CC); zend_stack_apply_with_argument(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_foreach_copy TSRMLS_CC); #else zend_stack_apply(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_switch_expr); zend_stack_apply(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_foreach_copy); #endif end_op_number = get_next_op_number(CG(active_op_array)); while (start_op_number < end_op_number) { CG(active_op_array)->opcodes[start_op_number].extended_value |= EXT_TYPE_FREE_ON_RETURN; start_op_number++; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) ? ZEND_RETURN_BY_REF : ZEND_RETURN; if (expr) { SET_NODE(opline->op1, expr); if (do_end_vparse && zend_is_function_or_method_call(expr)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } } else { opline->op1_type = IS_CONST; LITERAL_NULL(opline->op1); } SET_UNUSED(opline->op2); } /* }}} */ static int zend_add_try_element(zend_uint try_op TSRMLS_DC) /* {{{ */ { int try_catch_offset = CG(active_op_array)->last_try_catch++; CG(active_op_array)->try_catch_array = erealloc(CG(active_op_array)->try_catch_array, sizeof(zend_try_catch_element)*CG(active_op_array)->last_try_catch); CG(active_op_array)->try_catch_array[try_catch_offset].try_op = try_op; return try_catch_offset; } /* }}} */ static void zend_add_catch_element(int offset, zend_uint catch_op TSRMLS_DC) /* {{{ */ { CG(active_op_array)->try_catch_array[offset].catch_op = catch_op; } /* }}} */ void zend_do_first_catch(znode *open_parentheses TSRMLS_DC) /* {{{ */ { open_parentheses->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_initialize_try_catch_element(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist jmp_list; zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); zend_add_catch_element(try_token->u.op.opline_num, get_next_op_number(CG(active_op_array)) TSRMLS_CC); } /* }}} */ void zend_do_mark_last_catch(const znode *first_catch, const znode *last_additional_catch TSRMLS_DC) /* {{{ */ { CG(active_op_array)->last--; zend_do_if_end(TSRMLS_C); if (last_additional_catch->u.op.opline_num == -1) { CG(active_op_array)->opcodes[first_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[first_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } else { CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_try(znode *try_token TSRMLS_DC) /* {{{ */ { try_token->u.op.opline_num = zend_add_try_element(get_next_op_number(CG(active_op_array)) TSRMLS_CC); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_catch(znode *try_token, znode *class_name, znode *catch_var, znode *first_catch TSRMLS_DC) /* {{{ */ { long catch_op_number; zend_op *opline; znode catch_class; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { ulong fetch_type = ZEND_FETCH_CLASS_GLOBAL; zend_resolve_class_name(class_name, &fetch_type, 1 TSRMLS_CC); catch_class = *class_name; } else { zend_error(E_COMPILE_ERROR, "Bad class name in the catch statement"); } catch_op_number = get_next_op_number(CG(active_op_array)); if (first_catch) { first_catch->u.op.opline_num = catch_op_number; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CATCH; opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &catch_class.u.constant TSRMLS_CC); opline->op2_type = IS_CV; opline->op2.var = lookup_cv(CG(active_op_array), catch_var->u.constant.value.str.val, catch_var->u.constant.value.str.len TSRMLS_CC); catch_var->u.constant.value.str.val = CG(active_op_array)->vars[opline->op2.var].name; opline->result.num = 0; /* 1 means it's the last catch in the block */ try_token->u.op.opline_num = catch_op_number; } /* }}} */ void zend_do_end_catch(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); CG(active_op_array)->opcodes[try_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_throw(const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_THROW; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); } /* }}} */ ZEND_API void function_add_ref(zend_function *function) /* {{{ */ { if (function->type == ZEND_USER_FUNCTION) { zend_op_array *op_array = &function->op_array; (*op_array->refcount)++; if (op_array->static_variables) { HashTable *static_variables = op_array->static_variables; zval *tmp_zval; ALLOC_HASHTABLE(op_array->static_variables); zend_hash_init(op_array->static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(op_array->static_variables, static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_zval, sizeof(zval *)); } op_array->run_time_cache = NULL; } } /* }}} */ static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */ { zend_function *function; if (!ce->parent) { return; } /* You cannot change create_object */ ce->create_object = ce->parent->create_object; /* Inherit special functions if needed */ if (!ce->get_iterator) { ce->get_iterator = ce->parent->get_iterator; } if (!ce->iterator_funcs.funcs) { ce->iterator_funcs.funcs = ce->parent->iterator_funcs.funcs; } if (!ce->__get) { ce->__get = ce->parent->__get; } if (!ce->__set) { ce->__set = ce->parent->__set; } if (!ce->__unset) { ce->__unset = ce->parent->__unset; } if (!ce->__isset) { ce->__isset = ce->parent->__isset; } if (!ce->__call) { ce->__call = ce->parent->__call; } if (!ce->__callstatic) { ce->__callstatic = ce->parent->__callstatic; } if (!ce->__tostring) { ce->__tostring = ce->parent->__tostring; } if (!ce->clone) { ce->clone = ce->parent->clone; } if(!ce->serialize) { ce->serialize = ce->parent->serialize; } if(!ce->unserialize) { ce->unserialize = ce->parent->unserialize; } if (!ce->destructor) { ce->destructor = ce->parent->destructor; } if (ce->constructor) { if (ce->parent->constructor && ce->parent->constructor->common.fn_flags & ZEND_ACC_FINAL) { zend_error(E_ERROR, "Cannot override final %s::%s() with %s::%s()", ce->parent->name, ce->parent->constructor->common.function_name, ce->name, ce->constructor->common.function_name ); } return; } if (zend_hash_find(&ce->parent->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), (void **)&function)==SUCCESS) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), function, sizeof(zend_function), NULL); function_add_ref(function); } else { /* Don't inherit the old style constructor if we already have the new style constructor */ char *lc_class_name; char *lc_parent_class_name; lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); if (!zend_hash_exists(&ce->function_table, lc_class_name, ce->name_length+1)) { lc_parent_class_name = zend_str_tolower_dup(ce->parent->name, ce->parent->name_length); if (!zend_hash_exists(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1) && zend_hash_find(&ce->parent->function_table, lc_parent_class_name, ce->parent->name_length+1, (void **)&function)==SUCCESS) { if (function->common.fn_flags & ZEND_ACC_CTOR) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1, function, sizeof(zend_function), NULL); function_add_ref(function); } } efree(lc_parent_class_name); } efree(lc_class_name); } ce->constructor = ce->parent->constructor; } /* }}} */ char *zend_visibility_string(zend_uint fn_flags) /* {{{ */ { if (fn_flags & ZEND_ACC_PRIVATE) { return "private"; } if (fn_flags & ZEND_ACC_PROTECTED) { return "protected"; } if (fn_flags & ZEND_ACC_PUBLIC) { return "public"; } return ""; } /* }}} */ static void do_inherit_method(zend_function *function) /* {{{ */ { /* The class entry of the derived function intentionally remains the same * as that of the parent class. That allows us to know in which context * we're running, and handle private method calls properly. */ function_add_ref(function); } /* }}} */ static zend_bool zend_do_perform_implementation_check(const zend_function *fe, const zend_function *proto) /* {{{ */ { zend_uint i; /* If it's a user function then arg_info == NULL means we don't have any parameters but * we still need to do the arg number checks. We are only willing to ignore this for internal * functions because extensions don't always define arg_info. */ if (!proto || (!proto->common.arg_info && proto->common.type != ZEND_USER_FUNCTION)) { return 1; } /* Checks for constructors only if they are declared in an interface, * or explicitly marked as abstract */ if ((fe->common.fn_flags & ZEND_ACC_CTOR) && ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)) { return 1; } /* check number of arguments */ if (proto->common.required_num_args < fe->common.required_num_args || proto->common.num_args > fe->common.num_args) { return 0; } if (fe->common.type != ZEND_USER_FUNCTION && (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) != 0 && (fe->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) == 0) { return 0; } /* by-ref constraints on return values are covariant */ if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) { return 0; } for (i=0; i < proto->common.num_args; i++) { if (ZEND_LOG_XOR(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)) { /* Only one has a type hint and the other one doesn't */ return 0; } if (fe->common.arg_info[i].class_name && strcasecmp(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)!=0) { char *colon; if (fe->common.type != ZEND_USER_FUNCTION || strchr(proto->common.arg_info[i].class_name, '\\') != NULL || (colon = zend_memrchr(fe->common.arg_info[i].class_name, '\\', fe->common.arg_info[i].class_name_len)) == NULL || strcasecmp(colon+1, proto->common.arg_info[i].class_name) != 0) { return 0; } } if (fe->common.arg_info[i].type_hint != proto->common.arg_info[i].type_hint) { /* Incompatible type hint */ return 0; } /* by-ref constraints on arguments are invariant */ if (fe->common.arg_info[i].pass_by_reference != proto->common.arg_info[i].pass_by_reference) { return 0; } } if (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) { for (i=proto->common.num_args; i < fe->common.num_args; i++) { if (!fe->common.arg_info[i].pass_by_reference) { return 0; } } } return 1; } /* }}} */ static void do_inheritance_check_on_method(zend_function *child, zend_function *parent TSRMLS_DC) { zend_uint child_flags; zend_uint parent_flags = parent->common.fn_flags; if (parent->common.fn_flags & ZEND_ACC_ABSTRACT && parent->common.scope != (child->common.prototype ? child->common.prototype->common.scope : child->common.scope) && child->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_IMPLEMENTED_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Can't inherit abstract function %s::%s() (previously declared abstract in %s)", parent->common.scope->name, child->common.function_name, child->common.prototype ? child->common.prototype->common.scope->name : child->common.scope->name); } if (parent_flags & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot override final method %s::%s()", ZEND_FN_SCOPE_NAME(parent), child->common.function_name); } child_flags = child->common.fn_flags; /* You cannot change from static to non static and vice versa. */ if ((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC)) { if (child->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot make non static method %s::%s() static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } else { zend_error(E_COMPILE_ERROR, "Cannot make static method %s::%s() non static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } } /* Disallow making an inherited method abstract. */ if ((child_flags & ZEND_ACC_ABSTRACT) && !(parent_flags & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Cannot make non abstract method %s::%s() abstract in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } if (parent_flags & ZEND_ACC_CHANGED) { child->common.fn_flags |= ZEND_ACC_CHANGED; } else { /* Prevent derived classes from restricting access that was available in parent classes */ if ((child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::%s() must be %s (as in class %s)%s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if (((child_flags & ZEND_ACC_PPP_MASK) < (parent_flags & ZEND_ACC_PPP_MASK)) && ((parent_flags & ZEND_ACC_PPP_MASK) & ZEND_ACC_PRIVATE)) { child->common.fn_flags |= ZEND_ACC_CHANGED; } } if (parent_flags & ZEND_ACC_PRIVATE) { child->common.prototype = NULL; } else if (parent_flags & ZEND_ACC_ABSTRACT) { child->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; child->common.prototype = parent; } else if (!(parent->common.fn_flags & ZEND_ACC_CTOR) || (parent->common.prototype && (parent->common.prototype->common.scope->ce_flags & ZEND_ACC_INTERFACE))) { /* ctors only have a prototype if it comes from an interface */ child->common.prototype = parent->common.prototype ? parent->common.prototype : parent; } if (child->common.prototype && (child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { if (!zend_do_perform_implementation_check(child, child->common.prototype)) { zend_error(E_COMPILE_ERROR, "Declaration of %s::%s() must be compatible with that of %s::%s()", ZEND_FN_SCOPE_NAME(child), child->common.function_name, ZEND_FN_SCOPE_NAME(child->common.prototype), child->common.prototype->common.function_name); } } else if (EG(error_reporting) & E_STRICT || EG(user_error_handler)) { /* Check E_STRICT (or custom error handler) before the check so that we save some time */ if (!zend_do_perform_implementation_check(child, parent)) { zend_error(E_STRICT, "Declaration of %s::%s() should be compatible with that of %s::%s()", ZEND_FN_SCOPE_NAME(child), child->common.function_name, ZEND_FN_SCOPE_NAME(parent), parent->common.function_name); } } } static zend_bool do_inherit_method_check(HashTable *child_function_table, zend_function *parent, const zend_hash_key *hash_key, zend_class_entry *child_ce) /* {{{ */ { zend_uint parent_flags = parent->common.fn_flags; zend_function *child; TSRMLS_FETCH(); if (zend_hash_quick_find(child_function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child)==FAILURE) { if (parent_flags & (ZEND_ACC_ABSTRACT)) { child_ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } return 1; /* method doesn't exist in child, copy from parent */ } do_inheritance_check_on_method(child, parent TSRMLS_CC); return 0; } /* }}} */ static zend_bool do_inherit_property_access_check(HashTable *target_ht, zend_property_info *parent_info, const zend_hash_key *hash_key, zend_class_entry *ce) /* {{{ */ { zend_property_info *child_info; zend_class_entry *parent_ce = ce->parent; if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW)) { if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { child_info->flags |= ZEND_ACC_CHANGED; } else { zend_hash_quick_update(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, parent_info, sizeof(zend_property_info), (void **) &child_info); if(ce->type & ZEND_INTERNAL_CLASS) { zend_duplicate_property_info_internal(child_info); } else { zend_duplicate_property_info(child_info); } child_info->flags &= ~ZEND_ACC_PRIVATE; /* it's not private anymore */ child_info->flags |= ZEND_ACC_SHADOW; /* but it's a shadow of private */ } return 0; /* don't copy access information to child */ } if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { if ((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s", (parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", parent_ce->name, hash_key->arKey, (child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ce->name, hash_key->arKey); } if(parent_info->flags & ZEND_ACC_CHANGED) { child_info->flags |= ZEND_ACC_CHANGED; } if ((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ce->name, hash_key->arKey, zend_visibility_string(parent_info->flags), parent_ce->name, (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if ((child_info->flags & ZEND_ACC_STATIC) == 0) { Z_DELREF_P(ce->default_properties_table[parent_info->offset]); ce->default_properties_table[parent_info->offset] = ce->default_properties_table[child_info->offset]; ce->default_properties_table[child_info->offset] = NULL; child_info->offset = parent_info->offset; } return 0; /* Don't copy from parent */ } else { return 1; /* Copy from parent */ } } /* }}} */ static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce TSRMLS_CC) == FAILURE) { zend_error(E_CORE_ERROR, "Class %s could not implement interface %s", ce->name, iface->name); } if (ce == iface) { zend_error(E_ERROR, "Interface %s cannot implement itself", ce->name); } } /* }}} */ ZEND_API void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface TSRMLS_DC) /* {{{ */ { /* expects interface to be contained in ce's interface list already */ zend_uint i, ce_num, if_num = iface->num_interfaces; zend_class_entry *entry; if (if_num==0) { return; } ce_num = ce->num_interfaces; if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } /* Inherit the interfaces, only if they're not already inherited by the class */ while (if_num--) { entry = iface->interfaces[if_num]; for (i = 0; i < ce_num; i++) { if (ce->interfaces[i] == entry) { break; } } if (i == ce_num) { ce->interfaces[ce->num_interfaces++] = entry; } } /* and now call the implementing handlers */ while (ce_num < ce->num_interfaces) { do_implement_interface(ce, ce->interfaces[ce_num++] TSRMLS_CC); } } /* }}} */ #ifdef ZTS static void zval_internal_ctor(zval **p) /* {{{ */ { zval *orig_ptr = *p; ALLOC_ZVAL(*p); MAKE_COPY_ZVAL(&orig_ptr, *p); } /* }}} */ # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) (((parent_ce)->type != (ce)->type) ? zval_internal_ctor : zval_add_ref)) #else # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) zval_add_ref) #endif ZEND_API void zend_do_inheritance(zend_class_entry *ce, zend_class_entry *parent_ce TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; if ((ce->ce_flags & ZEND_ACC_INTERFACE) && !(parent_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ce->name, parent_ce->name); } if (parent_ce->ce_flags & ZEND_ACC_FINAL_CLASS) { zend_error(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ce->name, parent_ce->name); } ce->parent = parent_ce; /* Copy serialize/unserialize callbacks */ if (!ce->serialize) { ce->serialize = parent_ce->serialize; } if (!ce->unserialize) { ce->unserialize = parent_ce->unserialize; } /* Inherit interfaces */ zend_do_inherit_interfaces(ce, parent_ce TSRMLS_CC); /* Inherit properties */ if (parent_ce->default_properties_count) { int i = ce->default_properties_count + parent_ce->default_properties_count; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_properties_count) { while (i-- > parent_ce->default_properties_count) { ce->default_properties_table[i] = ce->default_properties_table[i - parent_ce->default_properties_count]; } } for (i = 0; i < parent_ce->default_properties_count; i++) { ce->default_properties_table[i] = parent_ce->default_properties_table[i]; if (ce->default_properties_table[i]) { #ifdef ZTS if (parent_ce->type != ce->type) { zval *p; ALLOC_ZVAL(p); MAKE_COPY_ZVAL(&ce->default_properties_table[i], p); ce->default_properties_table[i] = p; } else { Z_ADDREF_P(ce->default_properties_table[i]); } #else Z_ADDREF_P(ce->default_properties_table[i]); #endif } } ce->default_properties_count += parent_ce->default_properties_count; } if (parent_ce->type != ce->type) { /* User class extends internal class */ zend_update_class_constants(parent_ce TSRMLS_CC); if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = erealloc(ce->default_static_members_table, sizeof(void*) * i); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&CE_STATIC_MEMBERS(parent_ce)[i]); ce->default_static_members_table[i] = CE_STATIC_MEMBERS(parent_ce)[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; ce->static_members_table = ce->default_static_members_table; } } else { if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&parent_ce->default_static_members_table[i]); ce->default_static_members_table[i] = parent_ce->default_static_members_table[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } } for (zend_hash_internal_pointer_reset(&ce->properties_info); zend_hash_get_current_data(&ce->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->properties_info)) { if (property_info->ce == ce) { if (property_info->flags & ZEND_ACC_STATIC) { property_info->offset += parent_ce->default_static_members_count; } else { property_info->offset += parent_ce->default_properties_count; } } } zend_hash_merge_ex(&ce->properties_info, &parent_ce->properties_info, (copy_ctor_func_t) (ce->type & ZEND_INTERNAL_CLASS ? zend_duplicate_property_info_internal : zend_duplicate_property_info), sizeof(zend_property_info), (merge_checker_func_t) do_inherit_property_access_check, ce); zend_hash_merge(&ce->constants_table, &parent_ce->constants_table, zval_property_ctor(parent_ce, ce), NULL, sizeof(zval *), 0); zend_hash_merge_ex(&ce->function_table, &parent_ce->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_inherit_parent_constructor(ce); if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS && ce->type == ZEND_INTERNAL_CLASS) { ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } else if (!(ce->ce_flags & ZEND_ACC_IMPLEMENT_INTERFACES) && !(ce->ce_flags & ZEND_ACC_IMPLEMENT_TRAITS)) { /* The verification will be done in runtime by ZEND_VERIFY_ABSTRACT_CLASS */ zend_verify_abstract_class(ce TSRMLS_CC); } ce->ce_flags |= parent_ce->ce_flags & ZEND_HAS_STATIC_IN_METHODS; } /* }}} */ static zend_bool do_inherit_constant_check(HashTable *child_constants_table, const zval **parent_constant, const zend_hash_key *hash_key, const zend_class_entry *iface) /* {{{ */ { zval **old_constant; if (zend_hash_quick_find(child_constants_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**)&old_constant) == SUCCESS) { if (*old_constant != *parent_constant) { zend_error(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", hash_key->arKey, iface->name); } return 0; } return 1; } /* }}} */ static int do_interface_constant_check(zval **val TSRMLS_DC, int num_args, va_list args, const zend_hash_key *key) /* {{{ */ { zend_class_entry **iface = va_arg(args, zend_class_entry**); do_inherit_constant_check(&(*iface)->constants_table, (const zval **) val, key, *iface); return ZEND_HASH_APPLY_KEEP; } /* }}} */ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_iface_num = ce->num_interfaces; zend_uint parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0; for (i = 0; i < ce->num_interfaces; i++) { if (ce->interfaces[i] == NULL) { memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i)); i--; } else if (ce->interfaces[i] == iface) { if (i < parent_iface_num) { ignore = 1; } else { zend_error(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ce->name, iface->name); } } } if (ignore) { /* Check for attempt to redeclare interface constants */ zend_hash_apply_with_arguments(&ce->constants_table TSRMLS_CC, (apply_func_args_t) do_interface_constant_check, 1, &iface); } else { if (ce->num_interfaces >= current_iface_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } } ce->interfaces[ce->num_interfaces++] = iface; zend_hash_merge_ex(&ce->constants_table, &iface->constants_table, (copy_ctor_func_t) zval_add_ref, sizeof(zval *), (merge_checker_func_t) do_inherit_constant_check, iface); zend_hash_merge_ex(&ce->function_table, &iface->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_implement_interface(ce, iface TSRMLS_CC); zend_do_inherit_interfaces(ce, iface TSRMLS_CC); } } /* }}} */ ZEND_API void zend_do_implement_trait(zend_class_entry *ce, zend_class_entry *trait TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_trait_num = ce->num_traits; zend_uint parent_trait_num = ce->parent ? ce->parent->num_traits : 0; for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == NULL) { memmove(ce->traits + i, ce->traits + i + 1, sizeof(zend_class_entry*) * (--ce->num_traits - i)); i--; } else if (ce->traits[i] == trait) { if (i < parent_trait_num) { ignore = 1; } } } if (!ignore) { if (ce->num_traits >= current_trait_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->traits = (zend_class_entry **) realloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } else { ce->traits = (zend_class_entry **) erealloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } } ce->traits[ce->num_traits++] = trait; } } /* }}} */ static int zend_traits_merge_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { size_t current; size_t i; size_t count; HashTable* resulting_table; HashTable** function_tables; zend_class_entry *ce; size_t collision = 0; size_t abstract_solved = 0; /* unsigned int name_len; */ zend_function* other_trait_fn; current = va_arg(args, size_t); /* index of current trait */ count = va_arg(args, size_t); resulting_table = va_arg(args, HashTable*); function_tables = va_arg(args, HashTable**); ce = va_arg(args, zend_class_entry*); for (i = 0; i < count; i++) { if (i == current) { continue; /* just skip this, cause its the table this function is applied on */ } if (zend_hash_quick_find(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&other_trait_fn) == SUCCESS) { /* if it is an abstract method, there is no collision */ if (other_trait_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* we can savely free and remove it from other table */ zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } else { /* if it is not an abstract method, there is still no collision */ /* if fn is an abstract method */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* just mark as solved, will be added if its own trait is processed */ abstract_solved = 1; } else { /* but else, we have a collision of non-abstract methods */ collision++; zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } } } if (collision) { zend_function* class_fn; /* make sure method is not already overridden in class */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&class_fn) == FAILURE || class_fn->common.scope != ce) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because there are collisions with other trait methods on %s", fn->common.function_name, ce->name); } zend_function_dtor(fn); } else if (abstract_solved) { zend_function_dtor(fn); } else { /* Add it to result function table */ if (zend_hash_quick_add(resulting_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, fn, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating resulting trait method table", fn->common.function_name); } } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ #define IS_EQUAL(mname, mname_len, str) \ strncmp(mname, str, mname_len) #define _ADD_MAGIC_METHOD(ce, mname, mname_len, fe) { \ if (!IS_EQUAL(mname, mname_len, "__clone")) { (ce)->clone = (fe); (fe)->common.fn_flags |= ZEND_ACC_CLONE; } \ else if (!IS_EQUAL(mname, mname_len, "__construct")) { (ce)->constructor = (fe); (fe)->common.fn_flags |= ZEND_ACC_CTOR; } \ else if (!IS_EQUAL(mname, mname_len, "__destruct")) { (ce)->destructor = (fe); (fe)->common.fn_flags |= ZEND_ACC_DTOR; } \ else if (!IS_EQUAL(mname, mname_len, "__get")) (ce)->__get = (fe); \ else if (!IS_EQUAL(mname, mname_len, "__set")) (ce)->__set = (fe); \ else if (!IS_EQUAL(mname, mname_len, "__call")) (ce)->__call = (fe); \ else if (!IS_EQUAL(mname, mname_len, "__unset")) (ce)->__unset = (fe); \ else if (!IS_EQUAL(mname, mname_len, "__isset")) (ce)->__isset = (fe); \ else if (!IS_EQUAL(mname, mname_len, "__callstatic"))(ce)->__callstatic = (fe); \ else if (!IS_EQUAL(mname, mname_len, "__tostring")) (ce)->__tostring = (fe); \ else if (!IS_EQUAL(mname, mname_len, "serialize_func")) (ce)->serialize_func = (fe); \ else if (!IS_EQUAL(mname, mname_len, "unserialize_func"))(ce)->unserialize_func = (fe); \ } /* {{{ Originates from php_runkit_function_copy_ctor Duplicate structures in an op_array where necessary to make an outright duplicate */ static void zend_traits_duplicate_function(zend_function *fe, char *newname TSRMLS_DC) { zend_literal *literals_copy; zend_compiled_variable *dupvars; zend_op *opcode_copy; int i; if (fe->op_array.static_variables) { HashTable *tmpHash; ALLOC_HASHTABLE(tmpHash); zend_hash_init(tmpHash, zend_hash_num_elements(fe->op_array.static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_apply_with_arguments(tmpHash TSRMLS_CC, (apply_func_args_t)zval_copy_static_var, 1, fe->op_array.static_variables); fe->op_array.static_variables = tmpHash; } fe->op_array.refcount = emalloc(sizeof(zend_uint)); *(fe->op_array.refcount) = 1; i = fe->op_array.last_var; dupvars = safe_emalloc(fe->op_array.last_var, sizeof(zend_compiled_variable), 0); while (i > 0) { i--; dupvars[i].name = estrndup(fe->op_array.vars[i].name, fe->op_array.vars[i].name_len); dupvars[i].name_len = fe->op_array.vars[i].name_len; dupvars[i].hash_value = fe->op_array.vars[i].hash_value; } fe->op_array.vars = dupvars; opcode_copy = safe_emalloc(sizeof(zend_op), fe->op_array.last, 0); for(i = 0; i < fe->op_array.last; i++) { opcode_copy[i] = fe->op_array.opcodes[i]; if (opcode_copy[i].op1_type != IS_CONST) { if (opcode_copy[i].op1.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op1.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op1.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op1.jmp_addr - fe->op_array.opcodes); } } if (opcode_copy[i].op2_type != IS_CONST) { if (opcode_copy[i].op2.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op2.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op2.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op2.jmp_addr - fe->op_array.opcodes); } } } fe->op_array.opcodes = opcode_copy; fe->op_array.function_name = newname; /* was setting it to fe which does not work since fe is stack allocated and not a stable address */ /* fe->op_array.prototype = fe->op_array.prototype; */ if (fe->op_array.arg_info) { zend_arg_info *tmpArginfo; tmpArginfo = safe_emalloc(sizeof(zend_arg_info), fe->op_array.num_args, 0); for(i = 0; i < fe->op_array.num_args; i++) { tmpArginfo[i] = fe->op_array.arg_info[i]; tmpArginfo[i].name = estrndup(tmpArginfo[i].name, tmpArginfo[i].name_len); if (tmpArginfo[i].class_name) { tmpArginfo[i].class_name = estrndup(tmpArginfo[i].class_name, tmpArginfo[i].class_name_len); } } fe->op_array.arg_info = tmpArginfo; } fe->op_array.doc_comment = estrndup(fe->op_array.doc_comment, fe->op_array.doc_comment_len); fe->op_array.try_catch_array = (zend_try_catch_element*)estrndup((char*)fe->op_array.try_catch_array, sizeof(zend_try_catch_element) * fe->op_array.last_try_catch); fe->op_array.brk_cont_array = (zend_brk_cont_element*)estrndup((char*)fe->op_array.brk_cont_array, sizeof(zend_brk_cont_element) * fe->op_array.last_brk_cont); /* TODO: check whether there is something similar and whether that is ok */ literals_copy = (zend_literal*)emalloc(fe->op_array.last_literal * sizeof(zend_literal)); for (i = 0; i < fe->op_array.last_literal; i++) { literals_copy[i] = fe->op_array.literals[i]; zval_copy_ctor(&literals_copy[i].constant); } fe->op_array.literals = literals_copy; } /* }}}} */ static int zend_traits_merge_functions_to_class(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) { zend_class_entry *ce = va_arg(args, zend_class_entry*); int add = 0; zend_function* existing_fn; zend_function fn_copy, *fn_copy_p; zend_function* prototype = NULL; /* is used to determine the prototype according to the inheritance chain */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &existing_fn) == FAILURE) { add = 1; /* not found */ } else if (existing_fn->common.scope != ce) { add = 1; /* or inherited from other class or interface */ /* it is just a reference which was added to the subclass while doing the inheritance */ /* prototype = existing_fn; */ /* memory is scrambled anyway???? */ /* function_add_ref(prototype); */ zend_hash_quick_del(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h); } if (add) { zend_function* parent_function; if (ce->parent && zend_hash_quick_find(&ce->parent->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &parent_function) != FAILURE) { prototype = parent_function; /* ->common.fn_flags |= ZEND_ACC_ABSTRACT; */ } fn->common.scope = ce; fn->common.prototype = prototype; if (prototype && (prototype->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT || prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { fn->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; } else if (fn->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT) { /* remove ZEND_ACC_IMPLEMENTED_ABSTRACT flag, think it shouldn't be copied to class */ fn->common.fn_flags = fn->common.fn_flags - ZEND_ACC_IMPLEMENTED_ABSTRACT; } /* check whether the trait method fullfills the inheritance requirements */ if (prototype) { do_inheritance_check_on_method(fn, prototype TSRMLS_CC); } if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (fn->op_array.static_variables) { ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, estrdup(fn->common.function_name) TSRMLS_CC); if (zend_hash_quick_update(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, &fn_copy, sizeof(zend_function), (void**)&fn_copy_p)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating class method table", hash_key->arKey); } _ADD_MAGIC_METHOD(ce, hash_key->arKey, hash_key->nKeyLength, fn_copy_p); /* it could be necessary to update child classes as well */ /* zend_hash_apply_with_arguments(EG(class_table) TSRMLS_CC, (apply_func_args_t)php_runkit_update_children_methods, 5, dce, dce, &dfe, dfunc, dfunc_len); */ zend_function_dtor(fn); } else { zend_function_dtor(fn); } return ZEND_HASH_APPLY_REMOVE; } static int zend_traits_copy_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) { HashTable* target; zend_trait_alias** aliases; HashTable* exclude_table; char* lcname; unsigned int lcname_len; unsigned int fnname_len; zend_function fn_copy; void* dummy; size_t i = 0; target = va_arg(args, HashTable*); aliases = va_arg(args, zend_trait_alias**); exclude_table = va_arg(args, HashTable*); fnname_len = strlen(fn->common.function_name); /* apply aliases which are qualified with a class name, there should not be any ambiguity */ if (aliases) { while (aliases[i]) { if (!aliases[i]->trait_method->ce || (fn->common.scope == aliases[i]->trait_method->ce && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0))) { if (aliases[i]->alias) { fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, estrndup(aliases[i]->alias, aliases[i]->alias_len) TSRMLS_CC); if (aliases[i]->modifiers) { /* if it is 0, no modifieres has been changed */ fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } } lcname_len = aliases[i]->alias_len; lcname = zend_str_tolower_dup(aliases[i]->alias, lcname_len); if (zend_hash_add(target, lcname, lcname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add aliased trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } /* aliases[i]->function = fn_copy; */ efree(lcname); } } i++; } } lcname = zend_str_tolower_dup(fn->common.function_name, fnname_len); if (zend_hash_find(exclude_table, lcname, fnname_len, &dummy) == FAILURE) { /* is not in hashtable, thus, function is not to be excluded */ fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, estrndup(fn->common.function_name, fnname_len) TSRMLS_CC); /* apply aliases which are not qualified by a class name, or which have not alias name, just setting visibility */ if (aliases) { i = 0; while (aliases[i]) { if ((!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { if (!aliases[i]->alias && aliases[i]->modifiers) { /* if it is 0, no modifieres has been changed */ fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } } } i++; } } if (zend_hash_add(target, lcname, fnname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } } efree(lcname); return ZEND_HASH_APPLY_KEEP; } /** * Copies function table entries to target function table with applied aliasing */ static void zend_traits_copy_trait_function_table(HashTable *target, HashTable *source, zend_trait_alias** aliases, HashTable* exclude_table TSRMLS_DC) { zend_hash_apply_with_arguments(source TSRMLS_CC, (apply_func_args_t)zend_traits_copy_functions, 3, /* 3 is number of args for apply_func */ target, aliases, exclude_table); } static void zend_traits_init_trait_structures(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i, j = 0; zend_trait_precedence *cur_precedence; zend_trait_method_reference *cur_method_ref; zend_class_entry *cur_ce; /* resolve class references */ if (ce->trait_precedences) { i = 0; while ((cur_precedence = ce->trait_precedences[i])) { cur_ce = zend_fetch_class(cur_precedence->trait_method->class_name, cur_precedence->trait_method->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); cur_precedence->trait_method->ce = cur_ce; if (cur_precedence->exclude_from_classes) { j = 0; while (cur_precedence->exclude_from_classes[j]) { char* class_name = (char*)cur_precedence->exclude_from_classes[j]; zend_uint name_length = strlen(class_name); cur_ce = zend_fetch_class(class_name, name_length, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); efree(class_name); cur_precedence->exclude_from_classes[j] = cur_ce; j++; } } i++; } } if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { cur_method_ref = ce->trait_aliases[i]->trait_method; if (cur_method_ref->class_name) { cur_method_ref->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); } i++; } } } /* }}} */ static void zend_traits_compile_exclude_table(HashTable* exclude_table, zend_trait_precedence **precedences, zend_class_entry *trait) { size_t i, j; if (precedences) { i = 0; while (precedences[i]) { if (precedences[i]->exclude_from_classes) { j = 0; while (precedences[i]->exclude_from_classes[j]) { if (precedences[i]->exclude_from_classes[j] == trait) { zend_uint lcname_len = precedences[i]->trait_method->mname_len; char* lcname = zend_str_tolower_dup(precedences[i]->trait_method->method_name, lcname_len); if (zend_hash_add(exclude_table, lcname, lcname_len, NULL, 0, NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", precedences[i]->trait_method->method_name, trait->name); } efree(lcname); } j++; } } i++; } } } static void zend_do_traits_method_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { HashTable** function_tables; HashTable* resulting_table; HashTable exclude_table; size_t i; /* prepare copies of trait function tables for combination */ function_tables = malloc(sizeof(HashTable*) * ce->num_traits); resulting_table = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(resulting_table, 10, /* TODO: revisit this start size, may be its not optimal */ /* NULL, ZEND_FUNCTION_DTOR, 0, 0); */ NULL, NULL, 0, 0); for (i = 0; i < ce->num_traits; i++) { function_tables[i] = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(function_tables[i], ce->traits[i]->function_table.nNumOfElements, /* NULL, ZEND_FUNCTION_DTOR, 0, 0); */ NULL, NULL, 0, 0); zend_hash_init_ex(&exclude_table, 2, /* TODO: revisit this start size, may be its not optimal */ NULL, NULL, 0, 0); zend_traits_compile_exclude_table(&exclude_table, ce->trait_precedences, ce->traits[i]); /* copies functions, applies defined aliasing, and excludes unused trait methods */ zend_traits_copy_trait_function_table(function_tables[i], &ce->traits[i]->function_table, ce->trait_aliases, &exclude_table TSRMLS_CC); zend_hash_graceful_destroy(&exclude_table); } /* now merge trait methods */ for (i = 0; i < ce->num_traits; i++) { zend_hash_apply_with_arguments(function_tables[i] TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions, 5, /* 5 is number of args for apply_func */ i, ce->num_traits, resulting_table, function_tables, ce); } /* now the resulting_table contains all trait methods we would have to add to the class in the following step the methods are inserted into the method table if there is already a method with the same name it is replaced iff ce != fn.scope --> all inherited methods are overridden, methods defined in the class are left untouched */ zend_hash_apply_with_arguments(resulting_table TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions_to_class, 1, ce); /* free temporary function tables */ for (i = 0; i < ce->num_traits; i++) { /* zend_hash_destroy(function_tables[i]); */ zend_hash_graceful_destroy(function_tables[i]); free(function_tables[i]); } free(function_tables); /* free temporary resulting table */ /* zend_hash_destroy(resulting_table); */ zend_hash_graceful_destroy(resulting_table); free(resulting_table); } static zend_class_entry* find_first_definition(zend_class_entry *ce, size_t current_trait, char* prop_name, int prop_name_length, zend_class_entry *coliding_ce) /* {{{ */ { size_t i; zend_property_info *coliding_prop; for (i = 0; (i < current_trait) && (i < ce->num_traits); i++) { if (zend_hash_find(&ce->traits[i]->properties_info, prop_name, prop_name_length+1, (void **) &coliding_prop) == SUCCESS) { return ce->traits[i]; } } return coliding_ce; } static void zend_do_traits_property_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i; zend_property_info *property_info; zend_property_info *coliding_prop; zval compare_result; char* prop_name; int prop_name_length; char* class_name_unused; zend_bool prop_found; zend_bool not_compatible; zval* prop_value; /* in the following steps the properties are inserted into the property table for that, a very strict approach is applied: - check for compatibility, if not compatible with any property in class -> fatal - if compatible, then strict notice */ for (i = 0; i < ce->num_traits; i++) { for (zend_hash_internal_pointer_reset(&ce->traits[i]->properties_info); zend_hash_get_current_data(&ce->traits[i]->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->traits[i]->properties_info)) { /* property_info now contains the property */ /* first get the unmangeld name if necessary, then check whether the property is already there */ if ((property_info->flags & ZEND_ACC_PPP_MASK) == ZEND_ACC_PUBLIC) { prop_name = property_info->name; prop_name_length = property_info->name_length; prop_found = zend_hash_quick_find(&ce->properties_info, property_info->name, property_info->name_length+1, property_info->h, (void **) &coliding_prop) == SUCCESS; } else { /* for private and protected we need to unmangle the names */ zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name_unused, &prop_name); prop_name_length = strlen(prop_name); prop_found = zend_hash_find(&ce->properties_info, prop_name, prop_name_length+1, (void **) &coliding_prop) == SUCCESS; } /* next: check for conflicts with current class */ if (prop_found) { if (coliding_prop->flags & ZEND_ACC_SHADOW) { /* this one is inherited, lets look it up in its own class */ zend_hash_find(&coliding_prop->ce->properties_info, prop_name, prop_name_length+1, (void **) &coliding_prop); } if ((coliding_prop->flags & ZEND_ACC_PPP_MASK) == (property_info->flags & ZEND_ACC_PPP_MASK)) { /* flags are identical, now the value needs to be checked */ if (property_info->flags & ZEND_ACC_STATIC) { not_compatible = compare_function(&compare_result, ce->default_static_members_table[coliding_prop->offset], ce->traits[i]->default_static_members_table[property_info->offset] TSRMLS_CC) == FAILURE; } else { not_compatible = compare_function(&compare_result, ce->default_properties_table[coliding_prop->offset], ce->traits[i]->default_properties_table[property_info->offset] TSRMLS_CC) == FAILURE; } } else { /* the flags are not identical, thus, we assume properties are not compatible */ not_compatible = 1; } if (not_compatible) { zend_error(E_COMPILE_ERROR, "%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } else { zend_error(E_STRICT, "%s and %s define the same property ($%s) in the composition of %s. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } } /* property not found, so lets add it */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); zend_declare_property_ex(ce, prop_name, prop_name_length, prop_value, property_info->flags, property_info->doc_comment, property_info->doc_comment_len TSRMLS_CC); } } } ZEND_API void zend_do_bind_traits(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { if (ce->num_traits <= 0) { return; } /* complete initialization of trait strutures in ce */ zend_traits_init_trait_structures(ce TSRMLS_CC); /* first care about all methods to be flattened into the class */ zend_do_traits_method_binding(ce TSRMLS_CC); /* then flatten the properties into it, to, mostly to notfiy developer about problems */ zend_do_traits_property_binding(ce TSRMLS_CC); /* verify that all abstract methods from traits have been implemented */ zend_verify_abstract_class(ce TSRMLS_CC); /* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */ if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { ce->ce_flags -= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } } /* }}} */ ZEND_API int do_bind_function(const zend_op_array *op_array, zend_op *opline, HashTable *function_table, zend_bool compile_time) /* {{{ */ { zend_function *function; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } zend_hash_quick_find(function_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void *) &function); if (zend_hash_quick_add(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), function, sizeof(zend_function), NULL)==FAILURE) { int error_level = compile_time ? E_COMPILE_ERROR : E_ERROR; zend_function *old_function; if (zend_hash_quick_find(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), (void *) &old_function)==SUCCESS && old_function->type == ZEND_USER_FUNCTION && old_function->op_array.last > 0) { zend_error(error_level, "Cannot redeclare %s() (previously declared in %s:%d)", function->common.function_name, old_function->op_array.filename, old_function->op_array.opcodes[0].lineno); } else { zend_error(error_level, "Cannot redeclare %s()", function->common.function_name); } return FAILURE; } else { (*function->op_array.refcount)++; function->op_array.static_variables = NULL; /* NULL out the unbound function */ return SUCCESS; } } /* }}} */ void zend_add_trait_precedence(znode *precedence_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_precedences, precedence_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_add_trait_alias(znode *alias_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_aliases, alias_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_prepare_reference(znode *result, znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { zend_trait_method_reference *method_ref = emalloc(sizeof(zend_trait_method_reference)); method_ref->ce = NULL; /* REM: There should not be a need for copying, zend_do_begin_class_declaration is also just using that string */ if (class_name) { method_ref->class_name = Z_STRVAL(class_name->u.constant); method_ref->cname_len = Z_STRLEN(class_name->u.constant); } else { method_ref->class_name = NULL; method_ref->cname_len = 0; } method_ref->method_name = Z_STRVAL(method_name->u.constant); method_ref->mname_len = Z_STRLEN(method_name->u.constant); result->u.op.ptr = method_ref; result->op_type = IS_TMP_VAR; } /* }}} */ void zend_prepare_trait_alias(znode *result, znode *method_reference, znode *modifiers, znode *alias TSRMLS_DC) /* {{{ */ { zend_trait_alias *trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_alias->modifiers = Z_LVAL(modifiers->u.constant); if (Z_LVAL(modifiers->u.constant) == ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot use 'static' as method modifier"); return; } if (alias) { trait_alias->alias = Z_STRVAL(alias->u.constant); trait_alias->alias_len = Z_STRLEN(alias->u.constant); } else { trait_alias->alias = NULL; } trait_alias->function = NULL; result->u.op.ptr = trait_alias; } /* }}} */ /*void init_trait_alias(znode* result, const znode* method_name, const znode* alias, const znode* modifiers TSRMLS_DC)*/ /* {{{ */ /*{ zend_trait_alias* trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->method_name = Z_UNIVAL(method_name->u.constant); // may be method is only excluded, then the alias node is NULL if (alias) { trait_alias->alias = Z_UNIVAL(alias->u.constant); trait_alias->modifiers = Z_LVAL(modifiers->u.constant); } else { } trait_alias->function = NULL; result->u.var = trait_alias; } */ /* }}} */ void zend_prepare_trait_precedence(znode *result, znode *method_reference, znode *trait_list TSRMLS_DC) /* {{{ */ { zend_trait_precedence *trait_precedence = emalloc(sizeof(zend_trait_precedence)); trait_precedence->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_precedence->exclude_from_classes = (zend_class_entry**) trait_list->u.op.ptr; trait_precedence->function = NULL; result->u.op.ptr = trait_precedence; } /* }}} */ ZEND_API zend_class_entry *do_bind_class(const zend_op_array* op_array, const zend_op *opline, HashTable *class_table, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } if (zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce)==FAILURE) { zend_error(E_COMPILE_ERROR, "Internal Zend error - Missing class information for %s", Z_STRVAL_P(op1)); return NULL; } else { ce = *pce; } ce->refcount++; if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), &ce, sizeof(zend_class_entry *), NULL)==FAILURE) { ce->refcount--; if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return NULL; } else { if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLEMENT_INTERFACES))) { zend_verify_abstract_class(ce TSRMLS_CC); } return ce; } } /* }}} */ ZEND_API zend_class_entry *do_bind_inherited_class(const zend_op_array *op_array, const zend_op *opline, HashTable *class_table, zend_class_entry *parent_ce, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; int found_ce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } found_ce = zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce); if (found_ce == FAILURE) { if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", Z_STRVAL_P(op2)); } return NULL; } else { ce = *pce; } if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ce->name, parent_ce->name); } else if ((parent_ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ce->name, parent_ce->name); } zend_do_inheritance(ce, parent_ce TSRMLS_CC); ce->refcount++; /* Register the derived class */ if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), pce, sizeof(zend_class_entry *), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return ce; } /* }}} */ void zend_do_early_binding(TSRMLS_D) /* {{{ */ { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; HashTable *table; while (opline->opcode == ZEND_TICKS && opline > CG(active_op_array)->opcodes) { opline--; } switch (opline->opcode) { case ZEND_DECLARE_FUNCTION: if (do_bind_function(CG(active_op_array), opline, CG(function_table), 1) == FAILURE) { return; } table = CG(function_table); break; case ZEND_DECLARE_CLASS: if (do_bind_class(CG(active_op_array), opline, CG(class_table), 1 TSRMLS_CC) == NULL) { return; } table = CG(class_table); break; case ZEND_DECLARE_INHERITED_CLASS: { zend_op *fetch_class_opline = opline-1; zval *parent_name; zend_class_entry **pce; parent_name = &CONSTANT(fetch_class_opline->op2.constant); if ((zend_lookup_class(Z_STRVAL_P(parent_name), Z_STRLEN_P(parent_name), &pce TSRMLS_CC) == FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_CLASSES) && ((*pce)->type == ZEND_INTERNAL_CLASS))) { if (CG(compiler_options) & ZEND_COMPILE_DELAYED_BINDING) { zend_uint *opline_num = &CG(active_op_array)->early_binding; while (*opline_num != -1) { opline_num = &CG(active_op_array)->opcodes[*opline_num].result.opline_num; } *opline_num = opline - CG(active_op_array)->opcodes; opline->opcode = ZEND_DECLARE_INHERITED_CLASS_DELAYED; opline->result_type = IS_UNUSED; opline->result.opline_num = -1; } return; } if (do_bind_inherited_class(CG(active_op_array), opline, CG(class_table), *pce, 1 TSRMLS_CC) == NULL) { return; } /* clear unnecessary ZEND_FETCH_CLASS opcode */ zend_del_literal(CG(active_op_array), fetch_class_opline->op2.constant); MAKE_NOP(fetch_class_opline); table = CG(class_table); break; } case ZEND_VERIFY_ABSTRACT_CLASS: case ZEND_ADD_INTERFACE: case ZEND_ADD_TRAIT: case ZEND_BIND_TRAITS: /* We currently don't early-bind classes that implement interfaces */ /* Classes with traits are handled exactly the same, no early-bind here */ return; default: zend_error(E_COMPILE_ERROR, "Invalid binding type"); return; } zend_hash_quick_del(table, Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant)), Z_HASH_P(&CONSTANT(opline->op1.constant))); zend_del_literal(CG(active_op_array), opline->op1.constant); zend_del_literal(CG(active_op_array), opline->op2.constant); MAKE_NOP(opline); } /* }}} */ ZEND_API void zend_do_delayed_early_binding(const zend_op_array *op_array TSRMLS_DC) /* {{{ */ { if (op_array->early_binding != -1) { zend_bool orig_in_compilation = CG(in_compilation); zend_uint opline_num = op_array->early_binding; zend_class_entry **pce; CG(in_compilation) = 1; while (opline_num != -1) { if (zend_lookup_class(Z_STRVAL_P(op_array->opcodes[opline_num-1].op2.zv), Z_STRLEN_P(op_array->opcodes[opline_num-1].op2.zv), &pce TSRMLS_CC) == SUCCESS) { do_bind_inherited_class(op_array, &op_array->opcodes[opline_num], EG(class_table), *pce, 0 TSRMLS_CC); } opline_num = op_array->opcodes[opline_num].result.opline_num; } CG(in_compilation) = orig_in_compilation; } } /* }}} */ void zend_do_boolean_or_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_or_end(znode *result, const znode *expr1, const znode *expr2, znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_boolean_and_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_and_end(znode *result, const znode *expr1, const znode *expr2, const znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_do_while_begin(TSRMLS_D) /* {{{ */ { do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_do_while_end(const znode *do_token, const znode *expr_open_bracket, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ; SET_NODE(opline->op1, expr); opline->op2.opline_num = do_token->u.op.opline_num; SET_UNUSED(opline->op2); do_end_loop(expr_open_bracket->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_brk_cont(zend_uchar op, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->op1.opline_num = CG(context).current_brk_cont; SET_UNUSED(opline->op1); if (expr) { if (expr->op_type != IS_CONST) { zend_error(E_COMPILE_ERROR, "'%s' operator with non-constant operand is no longer supported", op == ZEND_BRK ? "break" : "continue"); } else if (Z_TYPE(expr->u.constant) != IS_LONG || Z_LVAL(expr->u.constant) < 1) { zend_error(E_COMPILE_ERROR, "'%s' operator accepts only positive numbers", op == ZEND_BRK ? "break" : "continue"); } SET_NODE(opline->op2, expr); } else { LITERAL_LONG(opline->op2, 1); opline->op2_type = IS_CONST; } } /* }}} */ void zend_do_switch_cond(const znode *cond TSRMLS_DC) /* {{{ */ { zend_switch_entry switch_entry; switch_entry.cond = *cond; switch_entry.default_case = -1; switch_entry.control_var = -1; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_switch_end(const znode *case_list TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); /* add code to jmp to default case */ if (switch_entry_ptr->default_case != -1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->op1.opline_num = switch_entry_ptr->default_case; } if (case_list->op_type != IS_UNUSED) { /* non-empty switch */ int next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* remember break/continue loop information */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; if (switch_entry_ptr->cond.op_type==IS_VAR || switch_entry_ptr->cond.op_type==IS_TMP_VAR) { /* emit free for the switch condition*/ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry_ptr->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_UNUSED(opline->op2); } if (switch_entry_ptr->cond.op_type == IS_CONST) { zval_dtor(&switch_entry_ptr->cond.u.constant); } zend_stack_del_top(&CG(switch_cond_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_case_before_statement(const znode *case_list, znode *case_token, const znode *case_expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); int next_op_number; zend_switch_entry *switch_entry_ptr; znode result; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); if (switch_entry_ptr->control_var == -1) { switch_entry_ptr->control_var = get_temporary_variable(CG(active_op_array)); } opline->opcode = ZEND_CASE; opline->result.var = switch_entry_ptr->control_var; opline->result_type = IS_TMP_VAR; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_NODE(opline->op2, case_expr); if (opline->op1_type == IS_CONST) { zval_copy_ctor(&CONSTANT(opline->op1.constant)); } GET_NODE(&result, opline->result); next_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, &result); SET_UNUSED(opline->op2); case_token->u.op.opline_num = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_case_after_statement(znode *result, const znode *case_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); result->u.op.opline_num = next_op_number; switch (CG(active_op_array)->opcodes[case_token->u.op.opline_num].opcode) { case ZEND_JMP: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); break; case ZEND_JMPZ: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); break; } } /* }}} */ void zend_do_default_before_statement(const znode *case_list, znode *default_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); default_token->u.op.opline_num = next_op_number; next_op_number = get_next_op_number(CG(active_op_array)); switch_entry_ptr->default_case = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_begin_class_declaration(const znode *class_token, znode *class_name, const znode *parent_class_name TSRMLS_DC) /* {{{ */ { zend_op *opline; int doing_inheritance = 0; zend_class_entry *new_class_entry; char *lcname; int error = 0; zval **ns_name, key; if (CG(active_class_entry)) { zend_error(E_COMPILE_ERROR, "Class declarations may not be nested"); return; } lcname = zend_str_tolower_dup(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); if (!(strcmp(lcname, "self") && strcmp(lcname, "parent"))) { efree(lcname); zend_error(E_COMPILE_ERROR, "Cannot use '%s' as class name as it is reserved", class_name->u.constant.value.str.val); } /* Class name must not conflict with import names */ if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns_name) == SUCCESS) { error = 1; } if (CG(current_namespace)) { /* Prefix class name with name of current namespace */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); class_name = &tmp; efree(lcname); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); } if (error) { char *tmp = zend_str_tolower_dup(Z_STRVAL_PP(ns_name), Z_STRLEN_PP(ns_name)); if (Z_STRLEN_PP(ns_name) != Z_STRLEN(class_name->u.constant) || memcmp(tmp, lcname, Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "Cannot declare class %s because the name is already in use", Z_STRVAL(class_name->u.constant)); } efree(tmp); } new_class_entry = emalloc(sizeof(zend_class_entry)); new_class_entry->type = ZEND_USER_CLASS; new_class_entry->name = zend_new_interned_string(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1, 1 TSRMLS_CC); new_class_entry->name_length = Z_STRLEN(class_name->u.constant); zend_initialize_class_data(new_class_entry, 1 TSRMLS_CC); new_class_entry->info.user.filename = zend_get_compiled_filename(TSRMLS_C); new_class_entry->info.user.line_start = class_token->u.op.opline_num; new_class_entry->ce_flags |= class_token->EA; if (parent_class_name && parent_class_name->op_type != IS_UNUSED) { switch (parent_class_name->EA) { case ZEND_FETCH_CLASS_SELF: zend_error(E_COMPILE_ERROR, "Cannot use 'self' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_PARENT: zend_error(E_COMPILE_ERROR, "Cannot use 'parent' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use 'static' as class name as it is reserved"); break; default: break; } doing_inheritance = 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, new_class_entry->name_length TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; if (doing_inheritance) { opline->extended_value = parent_class_name->u.op.var; opline->opcode = ZEND_DECLARE_INHERITED_CLASS; } else { opline->opcode = ZEND_DECLARE_CLASS; } LITERAL_STRINGL(opline->op2, lcname, new_class_entry->name_length, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); zend_hash_quick_update(CG(class_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &new_class_entry, sizeof(zend_class_entry *), NULL); CG(active_class_entry) = new_class_entry; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(&CG(implementing_class), opline->result); if (CG(doc_comment)) { CG(active_class_entry)->info.user.doc_comment = CG(doc_comment); CG(active_class_entry)->info.user.doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ static void do_verify_abstract_class(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_VERIFY_ABSTRACT_CLASS; SET_NODE(opline->op1, &CG(implementing_class)); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_class_declaration(const znode *class_token, const znode *parent_token TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); if (ce->constructor) { ce->constructor->common.fn_flags |= ZEND_ACC_CTOR; if (ce->constructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Constructor %s::%s() cannot be static", ce->name, ce->constructor->common.function_name); } } if (ce->destructor) { ce->destructor->common.fn_flags |= ZEND_ACC_DTOR; if (ce->destructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Destructor %s::%s() cannot be static", ce->name, ce->destructor->common.function_name); } } if (ce->clone) { ce->clone->common.fn_flags |= ZEND_ACC_CLONE; if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static", ce->name, ce->clone->common.function_name); } } ce->info.user.line_end = zend_get_compiled_lineno(TSRMLS_C); /* Check for traits and proceed like with interfaces. * The only difference will be a combined handling of them in the end. * Thus, we need another opcode here. */ if (ce->num_traits > 0) { zend_op *opline; ce->traits = NULL; ce->num_traits = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_TRAITS; /* opcode generation: */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BIND_TRAITS; SET_NODE(opline->op1, &CG(implementing_class)); } if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) && ((parent_token->op_type != IS_UNUSED) || (ce->num_interfaces > 0))) { zend_verify_abstract_class(ce TSRMLS_CC); if (ce->num_interfaces) { do_verify_abstract_class(TSRMLS_C); } } /* Inherit interfaces; reset number to zero, we need it for above check and * will restore it during actual implementation. * The ZEND_ACC_IMPLEMENT_INTERFACES flag disables double call to * zend_verify_abstract_class() */ if (ce->num_interfaces > 0) { ce->interfaces = NULL; ce->num_interfaces = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_INTERFACES; } CG(active_class_entry) = NULL; } /* }}} */ void zend_do_implements_interface(znode *interface_name TSRMLS_DC) /* {{{ */ { zend_op *opline; /* Traits can not implement interfaces */ if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface on '%s' since it is a Trait", Z_STRVAL(interface_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(interface_name->u.constant), Z_STRLEN(interface_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface name as it is reserved", Z_STRVAL(interface_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_INTERFACE; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(interface_name, &opline->extended_value, 0 TSRMLS_CC); opline->extended_value = (opline->extended_value & ~ZEND_FETCH_CLASS_MASK) | ZEND_FETCH_CLASS_INTERFACE; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &interface_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_interfaces++; } /* }}} */ void zend_do_implements_trait(znode *trait_name TSRMLS_DC) /* {{{ */ { zend_op *opline; switch (zend_get_class_fetch_type(Z_STRVAL(trait_name->u.constant), Z_STRLEN(trait_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as trait name as it is reserved", Z_STRVAL(trait_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_TRAIT; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(trait_name, &opline->extended_value, 0 TSRMLS_CC); opline->extended_value = ZEND_FETCH_CLASS_TRAIT; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &trait_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_traits++; } /* }}} */ ZEND_API void zend_mangle_property_name(char **dest, int *dest_length, const char *src1, int src1_length, const char *src2, int src2_length, int internal) /* {{{ */ { char *prop_name; int prop_name_length; prop_name_length = 1 + src1_length + 1 + src2_length; prop_name = pemalloc(prop_name_length + 1, internal); prop_name[0] = '\0'; memcpy(prop_name + 1, src1, src1_length+1); memcpy(prop_name + 1 + src1_length + 1, src2, src2_length+1); *dest = prop_name; *dest_length = prop_name_length; } /* }}} */ static int zend_strnlen(const char* s, int maxlen) /* {{{ */ { int len = 0; while (*s++ && maxlen--) len++; return len; } /* }}} */ ZEND_API int zend_unmangle_property_name(char *mangled_property, int len, char **class_name, char **prop_name) /* {{{ */ { int class_name_len; *class_name = NULL; if (mangled_property[0]!=0) { *prop_name = mangled_property; return SUCCESS; } if (len < 3 || mangled_property[1]==0) { zend_error(E_NOTICE, "Illegal member variable name"); *prop_name = mangled_property; return FAILURE; } class_name_len = zend_strnlen(mangled_property+1, --len - 1) + 1; if (class_name_len >= len || mangled_property[class_name_len]!=0) { zend_error(E_NOTICE, "Corrupt member variable name"); *prop_name = mangled_property; return FAILURE; } *class_name = mangled_property+1; *prop_name = (*class_name)+class_name_len; return SUCCESS; } /* }}} */ void zend_do_declare_property(const znode *var_name, const znode *value, zend_uint access_type TSRMLS_DC) /* {{{ */ { zval *property; zend_property_info *existing_property_info; char *comment = NULL; int comment_len = 0; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Interfaces may not include member variables"); } if (access_type & ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Properties cannot be declared abstract"); } if (access_type & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot declare property %s::$%s final, the final modifier is allowed only for methods and classes", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } if (zend_hash_find(&CG(active_class_entry)->properties_info, var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, (void **) &existing_property_info)==SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::$%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } ALLOC_ZVAL(property); if (value) { *property = value->u.constant; } else { INIT_PZVAL(property); Z_TYPE_P(property) = IS_NULL; } if (CG(doc_comment)) { comment = CG(doc_comment); comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } zend_declare_property_ex(CG(active_class_entry), zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len + 1, 0 TSRMLS_CC), var_name->u.constant.value.str.len, property, access_type, comment, comment_len TSRMLS_CC); efree(var_name->u.constant.value.str.val); } /* }}} */ void zend_do_declare_class_constant(znode *var_name, const znode *value TSRMLS_DC) /* {{{ */ { zval *property; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed in class constants"); return; } if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Traits cannot have constants"); return; } ALLOC_ZVAL(property); *property = value->u.constant; if (zend_hash_add(&CG(active_class_entry)->constants_table, zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, 0 TSRMLS_CC), var_name->u.constant.value.str.len+1, &property, sizeof(zval *), NULL)==FAILURE) { FREE_ZVAL(property); zend_error(E_COMPILE_ERROR, "Cannot redefine class constant %s::%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } FREE_PNODE(var_name); if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_fetch_property(znode *result, znode *object, const znode *property TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (object->op_type == IS_CV) { if (object->u.op.var == CG(active_op_array)->this_var) { object->op_type = IS_UNUSED; /* this means $this for objects */ } } else if (fetch_list_ptr->count == 1) { zend_llist_element *le = fetch_list_ptr->head; zend_op *opline_ptr = (zend_op *) le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); SET_UNUSED(opline_ptr->op1); /* this means $this for objects */ SET_NODE(opline_ptr->op2, property); /* if it was usual fetch, we change it to object fetch */ switch (opline_ptr->opcode) { case ZEND_FETCH_W: opline_ptr->opcode = ZEND_FETCH_OBJ_W; break; case ZEND_FETCH_R: opline_ptr->opcode = ZEND_FETCH_OBJ_R; break; case ZEND_FETCH_RW: opline_ptr->opcode = ZEND_FETCH_OBJ_RW; break; case ZEND_FETCH_IS: opline_ptr->opcode = ZEND_FETCH_OBJ_IS; break; case ZEND_FETCH_UNSET: opline_ptr->opcode = ZEND_FETCH_OBJ_UNSET; break; case ZEND_FETCH_FUNC_ARG: opline_ptr->opcode = ZEND_FETCH_OBJ_FUNC_ARG; break; } if (opline_ptr->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline_ptr->op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline_ptr->op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op2.constant); } GET_NODE(result, opline_ptr->result); return; } } if (zend_is_function_or_method_call(object)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, object); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_OBJ_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, object); SET_NODE(opline.op2, property); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline.op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op2.constant); } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void zend_do_halt_compiler_register(TSRMLS_D) /* {{{ */ { char *name, *cfilename; char haltoff[] = "__COMPILER_HALT_OFFSET__"; int len, clen; cfilename = zend_get_compiled_filename(TSRMLS_C); clen = strlen(cfilename); zend_mangle_property_name(&name, &len, haltoff, sizeof(haltoff) - 1, cfilename, clen, 0); zend_register_long_constant(name, len+1, zend_get_scanned_file_offset(TSRMLS_C), CONST_CS, 0 TSRMLS_CC); pefree(name, 0); } /* }}} */ void zend_do_push_object(const znode *object TSRMLS_DC) /* {{{ */ { zend_stack_push(&CG(object_stack), object, sizeof(znode)); } /* }}} */ void zend_do_pop_object(znode *object TSRMLS_DC) /* {{{ */ { if (object) { znode *tmp; zend_stack_top(&CG(object_stack), (void **) &tmp); *object = *tmp; } zend_stack_del_top(&CG(object_stack)); } /* }}} */ void zend_do_begin_new_object(znode *new_token, znode *class_type TSRMLS_DC) /* {{{ */ { zend_op *opline; unsigned char *ptr = NULL; new_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_NEW; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, class_type); SET_UNUSED(opline->op2); zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(unsigned char *)); } /* }}} */ void zend_do_end_new_object(znode *result, const znode *new_token, const znode *argument_list TSRMLS_DC) /* {{{ */ { znode ctor_result; zend_do_end_function_call(NULL, &ctor_result, argument_list, 1, 0 TSRMLS_CC); zend_do_free(&ctor_result TSRMLS_CC); CG(active_op_array)->opcodes[new_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, CG(active_op_array)->opcodes[new_token->u.op.opline_num].result); } /* }}} */ static zend_constant* zend_get_ct_const(const zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = NULL; if (Z_STRVAL_P(const_name)[0] == '\\') { if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name), (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name)-1); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name), (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } } else if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)+1, (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name)+1, (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } if (c->flags & CONST_CT_SUBST) { return c; } if (all_internal_constants_substitution && (c->flags & CONST_PERSISTENT) && !(CG(compiler_options) & ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION) && Z_TYPE(c->value) != IS_CONSTANT && Z_TYPE(c->value) != IS_CONSTANT_ARRAY) { return c; } return NULL; } /* }}} */ static int zend_constant_ct_subst(znode *result, zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = zend_get_ct_const(const_name, all_internal_constants_substitution TSRMLS_CC); if (c) { zval_dtor(const_name); result->op_type = IS_CONST; result->u.constant = c->value; zval_copy_ctor(&result->u.constant); INIT_PZVAL(&result->u.constant); return 1; } return 0; } /* }}} */ void zend_do_fetch_constant(znode *result, znode *constant_container, znode *constant_name, int mode, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; zend_op *opline; int type; char *compound; ulong fetch_type = 0; if (constant_container) { switch (mode) { case ZEND_CT: /* this is a class constant */ type = zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant)); if (ZEND_FETCH_CLASS_STATIC == type) { zend_error(E_ERROR, "\"static::\" is not allowed in compile-time constants"); } else if (ZEND_FETCH_CLASS_DEFAULT == type) { zend_resolve_class_name(constant_container, &fetch_type, 1 TSRMLS_CC); } zend_do_build_full_name(NULL, constant_container, constant_name, 1 TSRMLS_CC); *result = *constant_container; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: if (constant_container->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant))) { zend_resolve_class_name(constant_container, &fetch_type, 1 TSRMLS_CC); } else { zend_do_fetch_class(&tmp, constant_container TSRMLS_CC); constant_container = &tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); if (constant_container->op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &constant_container->u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, constant_container); } SET_NODE(opline->op2, constant_name); CALCULATE_LITERAL_HASH(opline->op2.constant); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } GET_NODE(result, opline->result); break; } return; } /* namespace constant */ /* only one that did not contain \ from the start can be converted to string if unknown */ switch (mode) { case ZEND_CT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); /* this is a namespace constant, or an unprefixed constant */ if (zend_constant_ct_subst(result, &constant_name->u.constant, 0 TSRMLS_CC)) { break; } zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(!compound) { fetch_type |= IS_CONSTANT_UNQUALIFIED; } *result = *constant_name; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(zend_constant_ct_subst(result, &constant_name->u.constant, 1 TSRMLS_CC)) { break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; if (compound) { /* the name is unambiguous */ opline->extended_value = 0; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } else { opline->extended_value = IS_CONSTANT_UNQUALIFIED; if (CG(current_namespace)) { opline->extended_value |= IS_CONSTANT_IN_NAMESPACE; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 1 TSRMLS_CC); } else { opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } } GET_CACHE_SLOT(opline->op2.constant); break; } } /* }}} */ void zend_do_shell_exec(znode *result, const znode *cmd TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); switch (cmd->op_type) { case IS_CONST: case IS_TMP_VAR: opline->opcode = ZEND_SEND_VAL; break; default: opline->opcode = ZEND_SEND_VAR; break; } SET_NODE(opline->op1, cmd); opline->op2.opline_num = 0; opline->extended_value = ZEND_DO_FCALL; SET_UNUSED(opline->op2); /* FIXME: exception support not added to this op2 */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DO_FCALL; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; LITERAL_STRINGL(opline->op1, estrndup("shell_exec", sizeof("shell_exec")-1), sizeof("shell_exec")-1, 0); CALCULATE_LITERAL_HASH(opline->op1.constant); opline->op1_type = IS_CONST; GET_CACHE_SLOT(opline->op1.constant); opline->extended_value = 1; SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_init_array(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_ARRAY; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; GET_NODE(result, opline->result); if (expr) { SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } } else { SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_array_element(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_ARRAY_ELEMENT; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_static_array_element(znode *result, znode *offset, const znode *expr) /* {{{ */ { zval *element; ALLOC_ZVAL(element); *element = expr->u.constant; if (offset) { switch (offset->u.constant.type & IS_CONSTANT_TYPE_MASK) { case IS_CONSTANT: /* Ugly hack to denote that this value has a constant index */ Z_TYPE_P(element) |= IS_CONSTANT_INDEX; Z_STRVAL(offset->u.constant) = erealloc(Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+1] = Z_TYPE(offset->u.constant); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+2] = 0; zend_symtable_update(result->u.constant.value.ht, Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_STRING: zend_symtable_update(result->u.constant.value.ht, offset->u.constant.value.str.val, offset->u.constant.value.str.len+1, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_NULL: zend_symtable_update(Z_ARRVAL(result->u.constant), "", 1, &element, sizeof(zval *), NULL); break; case IS_LONG: case IS_BOOL: zend_hash_index_update(Z_ARRVAL(result->u.constant), Z_LVAL(offset->u.constant), &element, sizeof(zval *), NULL); break; case IS_DOUBLE: zend_hash_index_update(Z_ARRVAL(result->u.constant), zend_dval_to_lval(Z_DVAL(offset->u.constant)), &element, sizeof(zval *), NULL); break; case IS_CONSTANT_ARRAY: zend_error(E_ERROR, "Illegal offset type"); break; } } else { zend_hash_next_index_insert(Z_ARRVAL(result->u.constant), &element, sizeof(zval *), NULL); } } /* }}} */ void zend_do_add_list_element(const znode *element TSRMLS_DC) /* {{{ */ { list_llist_element lle; if (element) { zend_check_writable_variable(element); lle.var = *element; zend_llist_copy(&lle.dimensions, &CG(dimension_llist)); zend_llist_prepend_element(&CG(list_llist), &lle); } (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_new_list_begin(TSRMLS_D) /* {{{ */ { int current_dimension = 0; zend_llist_add_element(&CG(dimension_llist), &current_dimension); } /* }}} */ void zend_do_new_list_end(TSRMLS_D) /* {{{ */ { zend_llist_remove_tail(&CG(dimension_llist)); (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_list_init(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(list_stack), &CG(list_llist), sizeof(zend_llist)); zend_stack_push(&CG(list_stack), &CG(dimension_llist), sizeof(zend_llist)); zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_do_new_list_begin(TSRMLS_C); } /* }}} */ void zend_do_list_end(znode *result, znode *expr TSRMLS_DC) /* {{{ */ { zend_llist_element *le; zend_llist_element *dimension; zend_op *opline; znode last_container; le = CG(list_llist).head; while (le) { zend_llist *tmp_dimension_llist = &((list_llist_element *)le->data)->dimensions; dimension = tmp_dimension_llist->head; while (dimension) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (dimension == tmp_dimension_llist->head) { /* first */ last_container = *expr; switch (expr->op_type) { case IS_VAR: case IS_CV: opline->opcode = ZEND_FETCH_DIM_R; break; case IS_TMP_VAR: opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; case IS_CONST: /* fetch_dim_tmp_var will handle this bogus fetch */ zval_copy_ctor(&expr->u.constant); opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; } opline->extended_value |= ZEND_FETCH_ADD_LOCK; } else { opline->opcode = ZEND_FETCH_DIM_R; } opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, &last_container); opline->op2_type = IS_CONST; LITERAL_LONG(opline->op2, *((int *) dimension->data)); GET_NODE(&last_container, opline->result); dimension = dimension->next; } ((list_llist_element *) le->data)->value = last_container; zend_llist_destroy(&((list_llist_element *) le->data)->dimensions); zend_do_assign(result, &((list_llist_element *) le->data)->var, &((list_llist_element *) le->data)->value TSRMLS_CC); zend_do_free(result TSRMLS_CC); le = le->next; } zend_llist_destroy(&CG(dimension_llist)); zend_llist_destroy(&CG(list_llist)); *result = *expr; { zend_llist *p; /* restore previous lists */ zend_stack_top(&CG(list_stack), (void **) &p); CG(dimension_llist) = *p; zend_stack_del_top(&CG(list_stack)); zend_stack_top(&CG(list_stack), (void **) &p); CG(list_llist) = *p; zend_stack_del_top(&CG(list_stack)); } } /* }}} */ void zend_init_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = emalloc(sizeof(void*) * 2); list[0] = item; list[1] = NULL; *(void**)result = list; } /* }}} */ void zend_add_to_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = *(void**)result; size_t n = 0; while (list && list[n]) { n++; } list = erealloc(list, sizeof(void*) * (n+2)); list[n] = item; list[n+1] = NULL; *(void**)result = list; } /* }}} */ void zend_do_fetch_static_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zval *tmp; zend_op *opline; znode lval; znode result; ALLOC_ZVAL(tmp); if (static_assignment) { *tmp = static_assignment->u.constant; } else { INIT_ZVAL(*tmp); } if (!CG(active_op_array)->static_variables) { if (CG(active_op_array)->scope) { CG(active_op_array)->scope->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } ALLOC_HASHTABLE(CG(active_op_array)->static_variables); zend_hash_init(CG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } zend_hash_update(CG(active_op_array)->static_variables, varname->u.constant.value.str.val, varname->u.constant.value.str.len+1, &tmp, sizeof(zval *), NULL); if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (fetch_type == ZEND_FETCH_LEXICAL) ? ZEND_FETCH_R : ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_STATIC; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ if (fetch_type == ZEND_FETCH_LEXICAL) { znode dummy; zend_do_begin_variable_parse(TSRMLS_C); zend_do_assign(&dummy, &lval, &result TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } else { zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); } CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_fetch_lexical_variable(znode *varname, zend_bool is_ref TSRMLS_DC) /* {{{ */ { znode value; if (Z_STRLEN(varname->u.constant) == sizeof("this") - 1 && memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this") - 1) == 0) { zend_error(E_COMPILE_ERROR, "Cannot use $this as lexical variable"); return; } value.op_type = IS_CONST; ZVAL_NULL(&value.u.constant); Z_TYPE(value.u.constant) |= is_ref ? IS_LEXICAL_REF : IS_LEXICAL_VAR; Z_SET_REFCOUNT_P(&value.u.constant, 1); Z_UNSET_ISREF_P(&value.u.constant); zend_do_fetch_static_variable(varname, &value, is_ref ? ZEND_FETCH_STATIC : ZEND_FETCH_LEXICAL TSRMLS_CC); } /* }}} */ void zend_do_fetch_global_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zend_op *opline; znode lval; znode result; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = fetch_type; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_cast(znode *result, const znode *expr, int type TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CAST; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } /* }}} */ void zend_do_include_or_eval(int type, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_do_extended_fcall_begin(TSRMLS_C); { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INCLUDE_OR_EVAL; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } zend_do_extended_fcall_end(TSRMLS_C); } /* }}} */ void zend_do_indirect_references(znode *result, const znode *num_references, znode *variable TSRMLS_DC) /* {{{ */ { int i; zend_do_end_variable_parse(variable, BP_VAR_R, 0 TSRMLS_CC); for (i=1; i<num_references->u.constant.value.lval; i++) { fetch_simple_variable_ex(result, variable, 0, ZEND_FETCH_R TSRMLS_CC); *variable = *result; } zend_do_begin_variable_parse(TSRMLS_C); fetch_simple_variable(result, variable, 1 TSRMLS_CC); /* there is a chance someone is accessing $this */ if (CG(active_op_array)->scope && CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1 TSRMLS_CC); } } /* }}} */ void zend_do_unset(const znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_UNSET_VAR; SET_NODE(opline->op1, variable); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); opline->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_UNSET: last_op->opcode = ZEND_UNSET_VAR; SET_UNUSED(last_op->result); break; case ZEND_FETCH_DIM_UNSET: last_op->opcode = ZEND_UNSET_DIM; SET_UNUSED(last_op->result); break; case ZEND_FETCH_OBJ_UNSET: last_op->opcode = ZEND_UNSET_OBJ; SET_UNUSED(last_op->result); break; } } } /* }}} */ void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_do_end_variable_parse(variable, BP_VAR_IS, 0 TSRMLS_CC); zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { last_op = get_next_op(CG(active_op_array) TSRMLS_CC); last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; SET_NODE(last_op->op1, variable); SET_UNUSED(last_op->op2); last_op->result.var = get_temporary_variable(CG(active_op_array)); last_op->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; break; case ZEND_FETCH_DIM_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_DIM_OBJ; break; case ZEND_FETCH_OBJ_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_PROP_OBJ; break; } } last_op->result_type = IS_TMP_VAR; last_op->extended_value |= type; GET_NODE(result, last_op->result); } /* }}} */ void zend_do_instanceof(znode *result, const znode *expr, const znode *class_znode, int type TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline->opcode == ZEND_FETCH_CLASS) { opline->extended_value |= ZEND_FETCH_CLASS_NO_AUTOLOAD; } } if (expr->op_type == IS_CONST) { zend_error(E_COMPILE_ERROR, "instanceof expects an object instance, constant given"); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INSTANCEOF; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_NODE(opline->op2, class_znode); GET_NODE(result, opline->result); } /* }}} */ void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_bool is_variable; zend_bool push_container = 0; zend_op dummy_opline; if (variable) { if (zend_is_function_or_method_call(array)) { is_variable = 0; } else { is_variable = 1; } /* save the location of FETCH_W instruction(s) */ open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); zend_do_end_variable_parse(array, BP_VAR_W, 0 TSRMLS_CC); if (CG(active_op_array)->last > 0 && CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) { /* Only lock the container if we are fetching from a real container and not $this */ if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1_type == IS_VAR) { CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK; push_container = 1; } } } else { is_variable = 0; open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* save the location of FE_RESET */ foreach_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* Preform array reset */ opline->opcode = ZEND_FE_RESET; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, array); SET_UNUSED(opline->op2); opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0; COPY_NODE(dummy_opline.result, opline->result); if (push_container) { COPY_NODE(dummy_opline.op1, CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1); } else { dummy_opline.op1_type = IS_UNUSED; } zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); /* save the location of FE_FETCH */ as_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FE_FETCH; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); COPY_NODE(opline->op1, dummy_opline.result); opline->extended_value = 0; SET_UNUSED(opline->op2); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_OP_DATA; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); } /* }}} */ void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC) /* {{{ */ { zend_op *opline; znode dummy, value_node; zend_bool assign_by_ref=0; opline = &CG(active_op_array)->opcodes[as_token->u.op. opline_num]; if (key->op_type != IS_UNUSED) { znode *tmp; /* switch between the key and value... */ tmp = key; key = value; value = tmp; /* Mark extended_value in case both key and value are being used */ opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; } if ((key->op_type != IS_UNUSED) && (key->EA & ZEND_PARSED_REFERENCE_VARIABLE)) { zend_error(E_COMPILE_ERROR, "Key element cannot be a reference"); } if (value->EA & ZEND_PARSED_REFERENCE_VARIABLE) { assign_by_ref = 1; if (!(opline-1)->extended_value) { zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression"); } /* Mark extended_value for assign-by-reference */ opline->extended_value |= ZEND_FE_FETCH_BYREF; CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; } else { zend_op *foreach_copy; zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.op.opline_num]; zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.op.opline_num]; /* Change "write context" into "read context" */ fetch->extended_value = 0; /* reset ZEND_FE_RESET_VARIABLE */ while (fetch != end) { --fetch; if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } if (fetch->opcode == ZEND_SEPARATE) { MAKE_NOP(fetch); } else { fetch->opcode -= 3; /* FETCH_W -> FETCH_R */ } } /* prevent double SWITCH_FREE */ zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy); foreach_copy->op1_type = IS_UNUSED; } GET_NODE(&value_node, opline->result); if (assign_by_ref) { zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); /* Mark FE_FETCH as IS_VAR as it holds the data directly as a value */ zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC); } else { zend_do_assign(&dummy, value, &value_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } if (key->op_type != IS_UNUSED) { znode key_node; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num+1]; opline->result_type = IS_TMP_VAR; opline->result.opline_num = get_temporary_variable(CG(active_op_array)); GET_NODE(&key_node, opline->result); zend_do_assign(&dummy, key, &key_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_foreach_end(const znode *foreach_token, const znode *as_token TSRMLS_DC) /* {{{ */ { zend_op *container_ptr; zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = as_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_RESET */ CG(active_op_array)->opcodes[as_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_FETCH */ do_end_loop(as_token->u.op.opline_num, 1 TSRMLS_CC); zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr); generate_free_foreach_copy(container_ptr TSRMLS_CC); zend_stack_del_top(&CG(foreach_copy_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_declare_begin(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(declare_stack), &CG(declarables), sizeof(zend_declarables)); } /* }}} */ void zend_do_declare_stmt(znode *var, znode *val TSRMLS_DC) /* {{{ */ { if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "ticks", sizeof("ticks")-1)) { convert_to_long(&val->u.constant); CG(declarables).ticks = val->u.constant; } else if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "encoding", sizeof("encoding")-1)) { if ((Z_TYPE(val->u.constant) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Cannot use constants as encoding"); } /* * Check that the pragma comes before any opcodes. If the compilation * got as far as this, the previous portion of the script must have been * parseable according to the .ini script_encoding setting. We still * want to tell them to put declare() at the top. */ { int num = CG(active_op_array)->last; /* ignore ZEND_EXT_STMT and ZEND_TICKS */ while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Encoding declaration pragma must be the very first statement in the script"); } } if (CG(multibyte)) { zend_encoding *new_encoding, *old_encoding; zend_encoding_filter old_input_filter; CG(encoding_declared) = 1; convert_to_string(&val->u.constant); new_encoding = zend_multibyte_fetch_encoding(val->u.constant.value.str.val TSRMLS_CC); if (!new_encoding) { zend_error(E_COMPILE_WARNING, "Unsupported encoding [%s]", val->u.constant.value.str.val); } else { old_input_filter = LANG_SCNG(input_filter); old_encoding = LANG_SCNG(script_encoding); zend_multibyte_set_filter(new_encoding TSRMLS_CC); /* need to re-scan if input filter changed */ if (old_input_filter != LANG_SCNG(input_filter) || (old_input_filter && new_encoding != old_encoding)) { zend_multibyte_yyinput_again(old_input_filter, old_encoding TSRMLS_CC); } } } else { zend_error(E_COMPILE_WARNING, "declare(encoding=...) ignored because Zend multibyte feature is turned off by settings"); } zval_dtor(&val->u.constant); } else { zend_error(E_COMPILE_WARNING, "Unsupported declare '%s'", var->u.constant.value.str.val); zval_dtor(&val->u.constant); } zval_dtor(&var->u.constant); } /* }}} */ void zend_do_declare_end(const znode *declare_token TSRMLS_DC) /* {{{ */ { zend_declarables *declarables; zend_stack_top(&CG(declare_stack), (void **) &declarables); /* We should restore if there was more than (current - start) - (ticks?1:0) opcodes */ if ((get_next_op_number(CG(active_op_array)) - declare_token->u.op.opline_num) - ((Z_LVAL(CG(declarables).ticks))?1:0)) { CG(declarables) = *declarables; } } /* }}} */ void zend_do_exit(znode *result, const znode *message TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXIT; SET_NODE(opline->op1, message); SET_UNUSED(opline->op2); result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_BOOL; Z_LVAL(result->u.constant) = 1; } /* }}} */ void zend_do_begin_silence(znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BEGIN_SILENCE; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); GET_NODE(strudel_token, opline->result); } /* }}} */ void zend_do_end_silence(const znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_END_SILENCE; SET_NODE(opline->op1, strudel_token); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_jmp_set(const znode *value, znode *jmp_token, znode *colon_token TSRMLS_DC) /* {{{ */ { int op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP_SET; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, value); SET_UNUSED(opline->op2); GET_NODE(colon_token, opline->result); jmp_token->u.op .opline_num = op_number; INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_jmp_set_else(znode *result, const znode *false_value, const znode *jmp_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_QM_ASSIGN; opline->extended_value = 0; SET_NODE(opline->result, colon_token); SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_qm_op(const znode *cond, znode *qm_token TSRMLS_DC) /* {{{ */ { int jmpz_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); SET_UNUSED(opline->op2); opline->op2.opline_num = jmpz_op_number; GET_NODE(qm_token, opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_qm_true(const znode *true_value, znode *qm_token, znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->opcodes[qm_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array))+1; /* jmp over the ZEND_JMP */ opline->opcode = ZEND_QM_ASSIGN; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, true_value); SET_UNUSED(opline->op2); GET_NODE(qm_token, opline->result); colon_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_qm_false(znode *result, const znode *false_value, const znode *qm_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_QM_ASSIGN; SET_NODE(opline->result, qm_token); SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[colon_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, opline->result); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_extended_info(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_STMT; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_begin(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_BEGIN; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_end(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_END; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_ticks(TSRMLS_D) /* {{{ */ { if (Z_LVAL(CG(declarables).ticks)) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_TICKS; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->extended_value = Z_LVAL(CG(declarables).ticks); } } /* }}} */ zend_bool zend_is_auto_global(const char *name, uint name_len TSRMLS_DC) /* {{{ */ { zend_auto_global *auto_global; if (zend_hash_find(CG(auto_globals), name, name_len+1, (void **) &auto_global)==SUCCESS) { if (auto_global->armed) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } return 1; } return 0; } /* }}} */ int zend_register_auto_global(const char *name, uint name_len, zend_bool jit, zend_auto_global_callback auto_global_callback TSRMLS_DC) /* {{{ */ { zend_auto_global auto_global; auto_global.name = zend_new_interned_string((char*)name, name_len + 1, 0 TSRMLS_CC); auto_global.name_len = name_len; auto_global.auto_global_callback = auto_global_callback; auto_global.jit = jit; return zend_hash_add(CG(auto_globals), name, name_len+1, &auto_global, sizeof(zend_auto_global), NULL); } /* }}} */ static int zend_auto_global_init(zend_auto_global *auto_global TSRMLS_DC) /* {{{ */ { if (auto_global->jit) { auto_global->armed = 1; } else if (auto_global->auto_global_callback) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } else { auto_global->armed = 0; } return 0; } /* }}} */ ZEND_API void zend_activate_auto_globals(TSRMLS_D) /* {{{ */ { zend_hash_apply(CG(auto_globals), (apply_func_t) zend_auto_global_init TSRMLS_CC); } /* }}} */ int zendlex(znode *zendlval TSRMLS_DC) /* {{{ */ { int retval; if (CG(increment_lineno)) { CG(zend_lineno)++; CG(increment_lineno) = 0; } again: Z_TYPE(zendlval->u.constant) = IS_LONG; retval = lex_scan(&zendlval->u.constant TSRMLS_CC); switch (retval) { case T_COMMENT: case T_DOC_COMMENT: case T_OPEN_TAG: case T_WHITESPACE: goto again; case T_CLOSE_TAG: if (LANG_SCNG(yy_text)[LANG_SCNG(yy_leng)-1] != '>') { CG(increment_lineno) = 1; } if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { goto again; } retval = ';'; /* implicit ; */ break; case T_OPEN_TAG_WITH_ECHO: retval = T_ECHO; break; case T_END_HEREDOC: efree(Z_STRVAL(zendlval->u.constant)); break; } INIT_PZVAL(&zendlval->u.constant); zendlval->op_type = IS_CONST; return retval; } /* }}} */ ZEND_API void zend_initialize_class_data(zend_class_entry *ce, zend_bool nullify_handlers TSRMLS_DC) /* {{{ */ { zend_bool persistent_hashes = (ce->type == ZEND_INTERNAL_CLASS) ? 1 : 0; dtor_func_t zval_ptr_dtor_func = ((persistent_hashes) ? ZVAL_INTERNAL_PTR_DTOR : ZVAL_PTR_DTOR); ce->refcount = 1; ce->ce_flags = 0; ce->default_properties_table = NULL; ce->default_static_members_table = NULL; zend_hash_init_ex(&ce->properties_info, 0, NULL, (dtor_func_t) (persistent_hashes ? zend_destroy_property_info_internal : zend_destroy_property_info), persistent_hashes, 0); zend_hash_init_ex(&ce->constants_table, 0, NULL, zval_ptr_dtor_func, persistent_hashes, 0); zend_hash_init_ex(&ce->function_table, 0, NULL, ZEND_FUNCTION_DTOR, persistent_hashes, 0); if (ce->type == ZEND_INTERNAL_CLASS) { #ifdef ZTS int n = zend_hash_num_elements(CG(class_table)); if (CG(static_members_table) && n >= CG(last_static_member)) { /* Support for run-time declaration: dl() */ CG(last_static_member) = n+1; CG(static_members_table) = realloc(CG(static_members_table), (n+1)*sizeof(zval**)); CG(static_members_table)[n] = NULL; } ce->static_members_table = (zval**)(zend_intptr_t)n; #else ce->static_members_table = NULL; #endif } else { ce->static_members_table = ce->default_static_members_table; ce->info.user.doc_comment = NULL; ce->info.user.doc_comment_len = 0; } ce->default_properties_count = 0; ce->default_static_members_count = 0; if (nullify_handlers) { ce->constructor = NULL; ce->destructor = NULL; ce->clone = NULL; ce->__get = NULL; ce->__set = NULL; ce->__unset = NULL; ce->__isset = NULL; ce->__call = NULL; ce->__callstatic = NULL; ce->__tostring = NULL; ce->create_object = NULL; ce->get_iterator = NULL; ce->iterator_funcs.funcs = NULL; ce->interface_gets_implemented = NULL; ce->get_static_method = NULL; ce->parent = NULL; ce->num_interfaces = 0; ce->interfaces = NULL; ce->num_traits = 0; ce->traits = NULL; ce->trait_aliases = NULL; ce->trait_precedences = NULL; ce->serialize = NULL; ce->unserialize = NULL; ce->serialize_func = NULL; ce->unserialize_func = NULL; if (ce->type == ZEND_INTERNAL_CLASS) { ce->info.internal.module = NULL; ce->info.internal.builtin_functions = NULL; } } } /* }}} */ int zend_get_class_fetch_type(const char *class_name, uint class_name_len) /* {{{ */ { if ((class_name_len == sizeof("self")-1) && !memcmp(class_name, "self", sizeof("self")-1)) { return ZEND_FETCH_CLASS_SELF; } else if ((class_name_len == sizeof("parent")-1) && !memcmp(class_name, "parent", sizeof("parent")-1)) { return ZEND_FETCH_CLASS_PARENT; } else if ((class_name_len == sizeof("static")-1) && !memcmp(class_name, "static", sizeof("static")-1)) { return ZEND_FETCH_CLASS_STATIC; } else { return ZEND_FETCH_CLASS_DEFAULT; } } /* }}} */ ZEND_API char* zend_get_compiled_variable_name(const zend_op_array *op_array, zend_uint var, int* name_len) /* {{{ */ { if (name_len) { *name_len = op_array->vars[var].name_len; } return op_array->vars[var].name; } /* }}} */ void zend_do_build_namespace_name(znode *result, znode *prefix, znode *name TSRMLS_DC) /* {{{ */ { if (prefix) { *result = *prefix; if (Z_TYPE(result->u.constant) == IS_STRING && Z_STRLEN(result->u.constant) == 0) { /* namespace\ */ if (CG(current_namespace)) { znode tmp; zval_dtor(&result->u.constant); tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(result, NULL, &tmp TSRMLS_CC); } } } else { result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_STRING; Z_STRVAL(result->u.constant) = NULL; Z_STRLEN(result->u.constant) = 0; } /* prefix = result */ zend_do_build_full_name(NULL, result, name, 0 TSRMLS_CC); } /* }}} */ void zend_do_begin_namespace(const znode *name, zend_bool with_bracket TSRMLS_DC) /* {{{ */ { char *lcname; /* handle mixed syntax declaration or nested namespaces */ if (!CG(has_bracketed_namespaces)) { if (CG(current_namespace)) { /* previous namespace declarations were unbracketed */ if (with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } } } else { /* previous namespace declarations were bracketed */ if (!with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } else if (CG(current_namespace) || CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "Namespace declarations cannot be nested"); } } if (((!with_bracket && !CG(current_namespace)) || (with_bracket && !CG(has_bracketed_namespaces))) && CG(active_op_array)->last > 0) { /* ignore ZEND_EXT_STMT and ZEND_TICKS */ int num = CG(active_op_array)->last; while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Namespace declaration statement has to be the very first statement in the script"); } } CG(in_namespace) = 1; if (with_bracket) { CG(has_bracketed_namespaces) = 1; } if (name) { lcname = zend_str_tolower_dup(Z_STRVAL(name->u.constant), Z_STRLEN(name->u.constant)); if (((Z_STRLEN(name->u.constant) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN(name->u.constant) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as namespace name", Z_STRVAL(name->u.constant)); } efree(lcname); if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); } else { ALLOC_ZVAL(CG(current_namespace)); } *CG(current_namespace) = name->u.constant; } else { if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_use(znode *ns_name, znode *new_name, int is_global TSRMLS_DC) /* {{{ */ { char *lcname; zval *name, *ns, tmp; zend_bool warn = 0; zend_class_entry **pce; if (!CG(current_import)) { CG(current_import) = emalloc(sizeof(HashTable)); zend_hash_init(CG(current_import), 0, NULL, ZVAL_PTR_DTOR, 0); } ALLOC_ZVAL(ns); *ns = ns_name->u.constant; if (new_name) { name = &new_name->u.constant; } else { char *p; /* The form "use A\B" is eqivalent to "use A\B as B". So we extract the last part of compound name to use as a new_name */ name = &tmp; p = zend_memrchr(Z_STRVAL_P(ns), '\\', Z_STRLEN_P(ns)); if (p) { ZVAL_STRING(name, p+1, 1); } else { *name = *ns; zval_copy_ctor(name); warn = !is_global && !CG(current_namespace); } } lcname = zend_str_tolower_dup(Z_STRVAL_P(name), Z_STRLEN_P(name)); if (((Z_STRLEN_P(name) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN_P(name) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because '%s' is a special class name", Z_STRVAL_P(ns), Z_STRVAL_P(name), Z_STRVAL_P(name)); } if (CG(current_namespace)) { /* Prefix import name with current namespace name to avoid conflicts with classes */ char *c_ns_name = emalloc(Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) + 1); zend_str_tolower_copy(c_ns_name, Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); c_ns_name[Z_STRLEN_P(CG(current_namespace))] = '\\'; memcpy(c_ns_name+Z_STRLEN_P(CG(current_namespace))+1, lcname, Z_STRLEN_P(name)+1); if (zend_hash_exists(CG(class_table), c_ns_name, Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name)+1)) { char *tmp2 = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) || memcmp(tmp2, c_ns_name, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(tmp2); } efree(c_ns_name); } else if (zend_hash_find(CG(class_table), lcname, Z_STRLEN_P(name)+1, (void**)&pce) == SUCCESS && (*pce)->type == ZEND_USER_CLASS && (*pce)->info.user.filename == CG(compiled_filename)) { char *c_tmp = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(name) || memcmp(c_tmp, lcname, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(c_tmp); } if (zend_hash_add(CG(current_import), lcname, Z_STRLEN_P(name)+1, &ns, sizeof(zval*), NULL) != SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } if (warn) { zend_error(E_WARNING, "The use statement with non-compound name '%s' has no effect", Z_STRVAL_P(name)); } efree(lcname); zval_dtor(name); } /* }}} */ void zend_do_declare_constant(znode *name, znode *value TSRMLS_DC) /* {{{ */ { zend_op *opline; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed as constants"); } if (zend_get_ct_const(&name->u.constant, 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare constant '%s'", Z_STRVAL(name->u.constant)); } if (CG(current_namespace)) { /* Prefix constant name with name of current namespace, lowercased */ znode tmp; tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); Z_STRVAL(tmp.u.constant) = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), Z_STRLEN(tmp.u.constant)); zend_do_build_namespace_name(&tmp, &tmp, name TSRMLS_CC); *name = tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DECLARE_CONST; SET_UNUSED(opline->result); SET_NODE(opline->op1, name); SET_NODE(opline->op2, value); } /* }}} */ void zend_verify_namespace(TSRMLS_D) /* {{{ */ { if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "No code may exist outside of namespace {}"); } } /* }}} */ void zend_do_end_namespace(TSRMLS_D) /* {{{ */ { CG(in_namespace) = 0; if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_end_compilation(TSRMLS_D) /* {{{ */ { CG(has_bracketed_namespaces) = 0; zend_do_end_namespace(TSRMLS_C); } /* }}} */ /* {{{ zend_dirname Returns directory name component of path */ ZEND_API size_t zend_dirname(char *path, size_t len) { register char *end = path + len - 1; unsigned int len_adjust = 0; #ifdef PHP_WIN32 /* Note that on Win32 CWD is per drive (heritage from CP/M). * This means dirname("c:foo") maps to "c:." or "c:" - which means CWD on C: drive. */ if ((2 <= len) && isalpha((int)((unsigned char *)path)[0]) && (':' == path[1])) { /* Skip over the drive spec (if any) so as not to change */ path += 2; len_adjust += 2; if (2 == len) { /* Return "c:" on Win32 for dirname("c:"). * It would be more consistent to return "c:." * but that would require making the string *longer*. */ return len; } } #elif defined(NETWARE) /* * Find the first occurence of : from the left * move the path pointer to the position just after : * increment the len_adjust to the length of path till colon character(inclusive) * If there is no character beyond : simple return len */ char *colonpos = NULL; colonpos = strchr(path, ':'); if (colonpos != NULL) { len_adjust = ((colonpos - path) + 1); path += len_adjust; if (len_adjust == len) { return len; } } #endif if (len == 0) { /* Illegal use of this function */ return 0; } /* Strip trailing slashes */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { /* The path only contained slashes */ path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } /* Strip filename */ while (end >= path && !IS_SLASH_P(end)) { end--; } if (end < path) { /* No slash found, therefore return '.' */ #ifdef NETWARE if (len_adjust == 0) { path[0] = '.'; path[1] = '\0'; return 1; /* only one character */ } else { path[0] = '\0'; return len_adjust; } #else path[0] = '.'; path[1] = '\0'; return 1 + len_adjust; #endif } /* Strip slashes which came before the file name */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } *(end+1) = '\0'; return (size_t)(end + 1 - path) + len_adjust; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */ /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <zend_language_parser.h> #include "zend.h" #include "zend_compile.h" #include "zend_constants.h" #include "zend_llist.h" #include "zend_API.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "zend_multibyte.h" #include "zend_language_scanner.h" #define CONSTANT_EX(op_array, op) \ (op_array)->literals[op].constant #define CONSTANT(op) \ CONSTANT_EX(CG(active_op_array), op) #define SET_NODE(target, src) do { \ target ## _type = (src)->op_type; \ if ((src)->op_type == IS_CONST) { \ target.constant = zend_add_literal(CG(active_op_array), &(src)->u.constant TSRMLS_CC); \ } else { \ target = (src)->u.op; \ } \ } while (0) #define GET_NODE(target, src) do { \ (target)->op_type = src ## _type; \ if ((target)->op_type == IS_CONST) { \ (target)->u.constant = CONSTANT(src.constant); \ } else { \ (target)->u.op = src; \ (target)->EA = 0; \ } \ } while (0) #define COPY_NODE(target, src) do { \ target ## _type = src ## _type; \ target = src; \ } while (0) #define CALCULATE_LITERAL_HASH(num) do { \ if (IS_INTERNED(Z_STRVAL(CONSTANT(num)))) { \ Z_HASH_P(&CONSTANT(num)) = INTERNED_HASH(Z_STRVAL(CONSTANT(num))); \ } else { \ Z_HASH_P(&CONSTANT(num)) = zend_hash_func(Z_STRVAL(CONSTANT(num)), Z_STRLEN(CONSTANT(num))+1); \ } \ } while (0) #define GET_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot++; \ } while (0) #define POLYMORPHIC_CACHE_SLOT_SIZE 2 #define GET_POLYMORPHIC_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot; \ CG(active_op_array)->last_cache_slot += POLYMORPHIC_CACHE_SLOT_SIZE; \ } while (0) #define FREE_POLYMORPHIC_CACHE_SLOT(literal) do { \ if (CG(active_op_array)->literals[literal].cache_slot == \ CG(active_op_array)->last_cache_slot - POLYMORPHIC_CACHE_SLOT_SIZE) { \ CG(active_op_array)->literals[literal].cache_slot = -1; \ CG(active_op_array)->last_cache_slot -= POLYMORPHIC_CACHE_SLOT_SIZE; \ } \ } while (0) ZEND_API zend_op_array *(*zend_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); ZEND_API zend_op_array *(*zend_compile_string)(zval *source_string, char *filename TSRMLS_DC); #ifndef ZTS ZEND_API zend_compiler_globals compiler_globals; ZEND_API zend_executor_globals executor_globals; #endif static void zend_duplicate_property_info(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = estrndup(property_info->name, property_info->name_length); } if (property_info->doc_comment) { property_info->doc_comment = estrndup(property_info->doc_comment, property_info->doc_comment_len); } } /* }}} */ static void zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = zend_strndup(property_info->name, property_info->name_length); } } /* }}} */ static void zend_destroy_property_info(zend_property_info *property_info) /* {{{ */ { str_efree(property_info->name); if (property_info->doc_comment) { efree(property_info->doc_comment); } } /* }}} */ static void zend_destroy_property_info_internal(zend_property_info *property_info) /* {{{ */ { str_free(property_info->name); } /* }}} */ static void build_runtime_defined_function_key(zval *result, const char *name, int name_length TSRMLS_DC) /* {{{ */ { char char_pos_buf[32]; uint char_pos_len; char *filename; char_pos_len = zend_sprintf(char_pos_buf, "%p", LANG_SCNG(yy_text)); if (CG(active_op_array)->filename) { filename = CG(active_op_array)->filename; } else { filename = "-"; } /* NULL, name length, filename length, last accepting char position length */ result->value.str.len = 1+name_length+strlen(filename)+char_pos_len; /* must be binary safe */ result->value.str.val = (char *) safe_emalloc(result->value.str.len, 1, 1); result->value.str.val[0] = '\0'; sprintf(result->value.str.val+1, "%s%s%s", name, filename, char_pos_buf); result->type = IS_STRING; Z_SET_REFCOUNT_P(result, 1); } /* }}} */ static void init_compiler_declarables(TSRMLS_D) /* {{{ */ { Z_TYPE(CG(declarables).ticks) = IS_LONG; Z_LVAL(CG(declarables).ticks) = 0; } /* }}} */ void zend_init_compiler_context(TSRMLS_D) /* {{{ */ { CG(context).opcodes_size = (CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) ? INITIAL_INTERACTIVE_OP_ARRAY_SIZE : INITIAL_OP_ARRAY_SIZE; CG(context).vars_size = 0; CG(context).literals_size = 0; CG(context).current_brk_cont = -1; CG(context).backpatch_count = 0; CG(context).labels = NULL; } /* }}} */ void zend_init_compiler_data_structures(TSRMLS_D) /* {{{ */ { zend_stack_init(&CG(bp_stack)); zend_stack_init(&CG(function_call_stack)); zend_stack_init(&CG(switch_cond_stack)); zend_stack_init(&CG(foreach_copy_stack)); zend_stack_init(&CG(object_stack)); zend_stack_init(&CG(declare_stack)); CG(active_class_entry) = NULL; zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_stack_init(&CG(list_stack)); CG(in_compilation) = 0; CG(start_lineno) = 0; CG(current_namespace) = NULL; CG(in_namespace) = 0; CG(has_bracketed_namespaces) = 0; CG(current_import) = NULL; init_compiler_declarables(TSRMLS_C); zend_stack_init(&CG(context_stack)); CG(encoding_declared) = 0; } /* }}} */ ZEND_API void file_handle_dtor(zend_file_handle *fh) /* {{{ */ { TSRMLS_FETCH(); zend_file_handle_dtor(fh TSRMLS_CC); } /* }}} */ void init_compiler(TSRMLS_D) /* {{{ */ { CG(active_op_array) = NULL; zend_init_compiler_data_structures(TSRMLS_C); zend_init_rsrc_list(TSRMLS_C); zend_hash_init(&CG(filenames_table), 5, NULL, (dtor_func_t) free_estring, 0); zend_llist_init(&CG(open_files), sizeof(zend_file_handle), (void (*)(void *)) file_handle_dtor, 0); CG(unclean_shutdown) = 0; } /* }}} */ void shutdown_compiler(TSRMLS_D) /* {{{ */ { zend_stack_destroy(&CG(bp_stack)); zend_stack_destroy(&CG(function_call_stack)); zend_stack_destroy(&CG(switch_cond_stack)); zend_stack_destroy(&CG(foreach_copy_stack)); zend_stack_destroy(&CG(object_stack)); zend_stack_destroy(&CG(declare_stack)); zend_stack_destroy(&CG(list_stack)); zend_hash_destroy(&CG(filenames_table)); zend_llist_destroy(&CG(open_files)); zend_stack_destroy(&CG(context_stack)); } /* }}} */ ZEND_API char *zend_set_compiled_filename(const char *new_compiled_filename TSRMLS_DC) /* {{{ */ { char **pp, *p; int length = strlen(new_compiled_filename); if (zend_hash_find(&CG(filenames_table), new_compiled_filename, length+1, (void **) &pp) == SUCCESS) { CG(compiled_filename) = *pp; return *pp; } p = estrndup(new_compiled_filename, length); zend_hash_update(&CG(filenames_table), new_compiled_filename, length+1, &p, sizeof(char *), (void **) &pp); CG(compiled_filename) = p; return p; } /* }}} */ ZEND_API void zend_restore_compiled_filename(char *original_compiled_filename TSRMLS_DC) /* {{{ */ { CG(compiled_filename) = original_compiled_filename; } /* }}} */ ZEND_API char *zend_get_compiled_filename(TSRMLS_D) /* {{{ */ { return CG(compiled_filename); } /* }}} */ ZEND_API int zend_get_compiled_lineno(TSRMLS_D) /* {{{ */ { return CG(zend_lineno); } /* }}} */ ZEND_API zend_bool zend_is_compiling(TSRMLS_D) /* {{{ */ { return CG(in_compilation); } /* }}} */ static zend_uint get_temporary_variable(zend_op_array *op_array) /* {{{ */ { return (op_array->T)++ * ZEND_MM_ALIGNED_SIZE(sizeof(temp_variable)); } /* }}} */ static int lookup_cv(zend_op_array *op_array, char* name, int name_len TSRMLS_DC) /* {{{ */ { int i = 0; ulong hash_value = zend_inline_hash_func(name, name_len+1); while (i < op_array->last_var) { if (op_array->vars[i].name == name || (op_array->vars[i].hash_value == hash_value && op_array->vars[i].name_len == name_len && memcmp(op_array->vars[i].name, name, name_len) == 0)) { str_efree(name); return i; } i++; } i = op_array->last_var; op_array->last_var++; if (op_array->last_var > CG(context).vars_size) { CG(context).vars_size += 16; /* FIXME */ op_array->vars = erealloc(op_array->vars, CG(context).vars_size * sizeof(zend_compiled_variable)); } op_array->vars[i].name = zend_new_interned_string(name, name_len + 1, 1 TSRMLS_CC); op_array->vars[i].name_len = name_len; op_array->vars[i].hash_value = hash_value; return i; } /* }}} */ void zend_del_literal(zend_op_array *op_array, int n) /* {{{ */ { zval_dtor(&CONSTANT_EX(op_array, n)); if (n + 1 == op_array->last_literal) { op_array->last_literal--; } else { Z_TYPE(CONSTANT_EX(op_array, n)) = IS_NULL; } } /* }}} */ int zend_add_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; if (i >= CG(context).literals_size) { CG(context).literals_size += 16; /* FIXME */ op_array->literals = (zend_literal*)erealloc(op_array->literals, CG(context).literals_size * sizeof(zend_literal)); } if (Z_TYPE_P(zv) == IS_STRING || Z_TYPE_P(zv) == IS_CONSTANT) { zval *z = (zval*)zv; TSRMLS_FETCH(); Z_STRVAL_P(z) = zend_new_interned_string(Z_STRVAL_P(zv), Z_STRLEN_P(zv) + 1, 1 TSRMLS_CC); } CONSTANT_EX(op_array, i) = *zv; Z_SET_REFCOUNT(CONSTANT_EX(op_array, i), 2); Z_SET_ISREF(CONSTANT_EX(op_array, i)); op_array->literals[i].hash_value = 0; op_array->literals[i].cache_slot = -1; return i; } /* }}} */ int zend_add_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_ns_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name, *ns_separator; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); ns_separator = (char *) zend_memrchr(Z_STRVAL_P(zv), '\\', Z_STRLEN_P(zv)) + 1; lc_len = Z_STRLEN_P(zv) - (ns_separator - Z_STRVAL_P(zv)); lc_name = zend_str_tolower_dup(ns_separator, lc_len); ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_class_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } if (Z_STRVAL_P(zv)[0] == '\\') { lc_len = Z_STRLEN_P(zv) - 1; lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv) + 1, lc_len); } else { lc_len = Z_STRLEN_P(zv); lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), lc_len); } ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); GET_CACHE_SLOT(ret); return ret; } /* }}} */ int zend_add_const_name_literal(zend_op_array *op_array, const zval *zv, int unqualified TSRMLS_DC) /* {{{ */ { int ret, tmp_literal; char *name, *tmp_name, *ns_separator; int name_len, ns_len; zval c; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } /* skip leading '\\' */ if (Z_STRVAL_P(zv)[0] == '\\') { name_len = Z_STRLEN_P(zv) - 1; name = Z_STRVAL_P(zv) + 1; } else { name_len = Z_STRLEN_P(zv); name = Z_STRVAL_P(zv); } ns_separator = zend_memrchr(name, '\\', name_len); if (ns_separator) { ns_len = ns_separator - name; } else { ns_len = 0; } if (ns_len) { /* lowercased namespace name & original constant name */ tmp_name = estrndup(name, name_len); zend_str_tolower(tmp_name, ns_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased namespace name & lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); } if (ns_len) { if (!unqualified) { return ret; } ns_len++; name += ns_len; name_len -= ns_len; } /* original constant name */ tmp_name = estrndup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); return ret; } /* }}} */ #define LITERAL_STRINGL(op, str, len, copy) do { \ zval _c; \ ZVAL_STRINGL(&_c, str, len, copy); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG(op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG_EX(op_array, op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(op_array, &_c TSRMLS_CC); \ } while (0) #define LITERAL_NULL(op) do { \ zval _c; \ INIT_ZVAL( _c); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) static inline zend_bool zend_is_function_or_method_call(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; return ((type & ZEND_PARSED_METHOD_CALL) || (type == ZEND_PARSED_FUNCTION_CALL)); } /* }}} */ void zend_do_binary_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_unary_op(zend_uchar op, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); GET_NODE(result, opline->result); SET_UNUSED(opline->op2); } /* }}} */ #define MAKE_NOP(opline) { opline->opcode = ZEND_NOP; memset(&opline->result,0,sizeof(opline->result)); memset(&opline->op1,0,sizeof(opline->op1)); memset(&opline->op2,0,sizeof(opline->op2)); opline->result_type=opline->op1_type=opline->op2_type=IS_UNUSED; } static void zend_do_op_data(zend_op *data_op, const znode *value TSRMLS_DC) /* {{{ */ { data_op->opcode = ZEND_OP_DATA; SET_NODE(data_op->op1, value); SET_UNUSED(data_op->op2); } /* }}} */ void zend_do_binary_assign_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; switch (last_op->opcode) { case ZEND_FETCH_OBJ_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, op2 TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; case ZEND_FETCH_DIM_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_DIM; zend_do_op_data(opline, op2 TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result,last_op->result); return; default: break; } } opline->opcode = op; SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void fetch_simple_variable_ex(znode *result, znode *varname, int bp, zend_uchar op TSRMLS_DC) /* {{{ */ { zend_op opline; zend_op *opline_ptr; zend_llist *fetch_list_ptr; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } if (!zend_is_auto_global(varname->u.constant.value.str.val, varname->u.constant.value.str.len TSRMLS_CC) && !(varname->u.constant.value.str.len == (sizeof("this")-1) && !memcmp(varname->u.constant.value.str.val, "this", sizeof("this"))) && (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE)) { result->op_type = IS_CV; result->u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len TSRMLS_CC); varname->u.constant.value.str.val = CG(active_op_array)->vars[result->u.op.var].name; result->EA = 0; return; } } if (bp) { opline_ptr = &opline; init_op(opline_ptr TSRMLS_CC); } else { opline_ptr = get_next_op(CG(active_op_array) TSRMLS_CC); } opline_ptr->opcode = op; opline_ptr->result_type = IS_VAR; opline_ptr->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline_ptr->op1, varname); GET_NODE(result, opline_ptr->result); SET_UNUSED(opline_ptr->op2); opline_ptr->extended_value = ZEND_FETCH_LOCAL; if (varname->op_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline_ptr->op1.constant); if (zend_is_auto_global(varname->u.constant.value.str.val, varname->u.constant.value.str.len TSRMLS_CC)) { opline_ptr->extended_value = ZEND_FETCH_GLOBAL; } } if (bp) { zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); zend_llist_add_element(fetch_list_ptr, opline_ptr); } } /* }}} */ void fetch_simple_variable(znode *result, znode *varname, int bp TSRMLS_DC) /* {{{ */ { /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ fetch_simple_variable_ex(result, varname, bp, ZEND_FETCH_W TSRMLS_CC); } /* }}} */ void zend_do_fetch_static_member(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { znode class_node; zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline_ptr; zend_op opline; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { ulong fetch_type = ZEND_FETCH_CLASS_GLOBAL; zend_resolve_class_name(class_name, &fetch_type, 1 TSRMLS_CC); class_node = *class_name; } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); } zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (result->op_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[result->u.op.var].name), CG(active_op_array)->vars[result->u.op.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } GET_NODE(result,opline.result); opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; opline_ptr = &opline; zend_llist_add_element(fetch_list_ptr, &opline); } else { le = fetch_list_ptr->head; opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode != ZEND_FETCH_W && opline_ptr->op1_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[opline_ptr->op1.var].name), CG(active_op_array)->vars[opline_ptr->op1.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; COPY_NODE(opline_ptr->op1, opline.result); zend_llist_prepend_element(fetch_list_ptr, &opline); } else { if (opline_ptr->op1_type == IS_CONST) { GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op1.constant); } if (class_node.op_type == IS_CONST) { opline_ptr->op2_type = IS_CONST; opline_ptr->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline_ptr->op2, &class_node); } opline_ptr->extended_value |= ZEND_FETCH_STATIC_MEMBER; } } } /* }}} */ void fetch_array_begin(znode *result, znode *varname, znode *first_dim TSRMLS_DC) /* {{{ */ { fetch_simple_variable(result, varname, 1 TSRMLS_CC); fetch_array_dim(result, result, first_dim TSRMLS_CC); } /* }}} */ void fetch_array_dim(znode *result, const znode *parent, const znode *dim TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (zend_is_function_or_method_call(parent)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, parent); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_DIM_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, parent); SET_NODE(opline.op2, dim); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline.op2.constant)), Z_STRLEN(CONSTANT(opline.op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline.op2.constant)); ZVAL_LONG(&CONSTANT(opline.op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline.op2.constant); } } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void fetch_string_offset(znode *result, const znode *parent, const znode *offset TSRMLS_DC) /* {{{ */ { fetch_array_dim(result, parent, offset TSRMLS_CC); } /* }}} */ void zend_do_print(znode *result, const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->opcode = ZEND_PRINT; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_echo(const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ECHO; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_abstract_method(const znode *function_name, znode *modifiers, const znode *body TSRMLS_DC) /* {{{ */ { char *method_type; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { Z_LVAL(modifiers->u.constant) |= ZEND_ACC_ABSTRACT; method_type = "Interface"; } else { method_type = "Abstract"; } if (modifiers->u.constant.value.lval & ZEND_ACC_ABSTRACT) { if(modifiers->u.constant.value.lval & ZEND_ACC_PRIVATE) { zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot be declared private", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } if (Z_LVAL(body->u.constant) == ZEND_ACC_ABSTRACT) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_RAISE_ABSTRACT_ERROR; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } else { /* we had code in the function body */ zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot contain body", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } else { if (body->u.constant.value.lval == ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Non-abstract method %s::%s() must contain body", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } } /* }}} */ static zend_bool opline_is_fetch_this(const zend_op *opline TSRMLS_DC) /* {{{ */ { if ((opline->opcode == ZEND_FETCH_W) && (opline->op1_type == IS_CONST) && (Z_TYPE(CONSTANT(opline->op1.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(opline->op1.constant)) == (sizeof("this")-1)) && !memcmp(Z_STRVAL(CONSTANT(opline->op1.constant)), "this", sizeof("this"))) { return 1; } else { return 0; } } /* }}} */ void zend_do_assign(znode *result, znode *variable, znode *value TSRMLS_DC) /* {{{ */ { int last_op_number; zend_op *opline; if (value->op_type == IS_CV) { zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (fetch_list_ptr && fetch_list_ptr->head) { opline = (zend_op *)fetch_list_ptr->head->data; if (opline->opcode == ZEND_FETCH_DIM_W && opline->op1_type == IS_CV && opline->op1.var == value->u.op.var) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_R; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->op1_type = IS_CONST; LITERAL_STRINGL(opline->op1, CG(active_op_array)->vars[value->u.op.var].name, CG(active_op_array)->vars[value->u.op.var].name_len, 1); CALCULATE_LITERAL_HASH(opline->op1.constant); SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_LOCAL; GET_NODE(value, opline->result); } } } zend_do_end_variable_parse(variable, BP_VAR_W, 0 TSRMLS_CC); last_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (variable->op_type == IS_CV) { if (variable->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (variable->op_type == IS_VAR) { int n = 0; while (last_op_number - n > 0) { zend_op *last_op; last_op = &CG(active_op_array)->opcodes[last_op_number-n-1]; if (last_op->result_type == IS_VAR && last_op->result.var == variable->u.op.var) { if (last_op->opcode == ZEND_FETCH_OBJ_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, value TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (last_op->opcode == ZEND_FETCH_DIM_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ /* TBFixed: this can realloc opcodes, leaving last_op pointing wrong */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_DIM; zend_do_op_data(opline, value TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (opline_is_fetch_this(last_op TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } else { break; } } n++; } } opline->opcode = ZEND_ASSIGN; SET_NODE(opline->op1, variable); SET_NODE(opline->op2, value); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_assign_ref(znode *result, const znode *lvar, const znode *rvar TSRMLS_DC) /* {{{ */ { zend_op *opline; if (lvar->op_type == IS_CV) { if (lvar->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (lvar->op_type == IS_VAR) { int last_op_number = get_next_op_number(CG(active_op_array)); if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline_is_fetch_this(opline TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ASSIGN_REF; if (zend_is_function_or_method_call(rvar)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } else if (rvar->EA & ZEND_PARSED_NEW) { opline->extended_value = ZEND_RETURNS_NEW; } else { opline->extended_value = 0; } if (result) { opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } else { opline->result_type = IS_UNUSED | EXT_TYPE_UNUSED; } SET_NODE(opline->op1, lvar); SET_NODE(opline->op2, rvar); } /* }}} */ static inline void do_begin_loop(TSRMLS_D) /* {{{ */ { zend_brk_cont_element *brk_cont_element; int parent; parent = CG(context).current_brk_cont; CG(context).current_brk_cont = CG(active_op_array)->last_brk_cont; brk_cont_element = get_next_brk_cont_element(CG(active_op_array)); brk_cont_element->start = get_next_op_number(CG(active_op_array)); brk_cont_element->parent = parent; } /* }}} */ static inline void do_end_loop(int cont_addr, int has_loop_var TSRMLS_DC) /* {{{ */ { if (!has_loop_var) { /* The start fileld is used to free temporary variables in case of exceptions. * We won't try to free something of we don't have loop variable. */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].start = -1; } CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = cont_addr; CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; } /* }}} */ void zend_do_while_cond(const znode *expr, znode *close_bracket_token TSRMLS_DC) /* {{{ */ { int while_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, expr); close_bracket_token->u.op.opline_num = while_cond_op_number; SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_while_end(const znode *while_token, const znode *close_bracket_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* add unconditional jump */ opline->opcode = ZEND_JMP; opline->op1.opline_num = while_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* update while's conditional jmp */ CG(active_op_array)->opcodes[close_bracket_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); do_end_loop(while_token->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_cond(const znode *expr, znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { int for_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZNZ; SET_NODE(opline->op1, expr); /* the conditional expression */ second_semicolon_token->u.op.opline_num = for_cond_op_number; SET_UNUSED(opline->op2); } /* }}} */ void zend_do_for_before_statement(const znode *cond_start, const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = cond_start->u.op.opline_num; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_end(const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = second_semicolon_token->u.op.opline_num+1; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_end_loop(second_semicolon_token->u.op.opline_num+1, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_pre_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_PRE_INC)?ZEND_PRE_INC_OBJ:ZEND_PRE_DEC_OBJ; last_op->result_type = IS_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_post_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_POST_INC)?ZEND_POST_INC_OBJ:ZEND_POST_DEC_OBJ; last_op->result_type = IS_TMP_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_if_cond(const znode *cond, znode *closing_bracket_token TSRMLS_DC) /* {{{ */ { int if_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); closing_bracket_token->u.op.opline_num = if_cond_op_number; SET_UNUSED(opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_if_after_statement(const znode *closing_bracket_token, unsigned char initialize TSRMLS_DC) /* {{{ */ { int if_end_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; /* save for backpatching */ if (initialize) { zend_llist jmp_list; zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); } zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &if_end_op_number); CG(active_op_array)->opcodes[closing_bracket_token->u.op.opline_num].op2.opline_num = if_end_op_number+1; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_if_end(TSRMLS_D) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_llist *jmp_list_ptr; zend_llist_element *le; zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); for (le=jmp_list_ptr->head; le; le = le->next) { CG(active_op_array)->opcodes[*((int *) le->data)].op1.opline_num = next_op_number; } zend_llist_destroy(jmp_list_ptr); zend_stack_del_top(&CG(bp_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_check_writable_variable(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; if (type & ZEND_PARSED_METHOD_CALL) { zend_error(E_COMPILE_ERROR, "Can't use method return value in write context"); } if (type == ZEND_PARSED_FUNCTION_CALL) { zend_error(E_COMPILE_ERROR, "Can't use function return value in write context"); } } /* }}} */ void zend_do_begin_variable_parse(TSRMLS_D) /* {{{ */ { zend_llist fetch_list; zend_llist_init(&fetch_list, sizeof(zend_op), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &fetch_list, sizeof(zend_llist)); } /* }}} */ void zend_do_end_variable_parse(znode *variable, int type, int arg_offset TSRMLS_DC) /* {{{ */ { zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline = NULL; zend_op *opline_ptr; zend_uint this_var = -1; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); le = fetch_list_ptr->head; /* TODO: $foo->x->y->z = 1 should fetch "x" and "y" for R or RW, not just W */ if (le) { opline_ptr = (zend_op *)le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { /* convert to FETCH_?(this) into IS_CV */ if (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE) { this_var = opline_ptr->result.var; if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), Z_STRVAL(CONSTANT(opline_ptr->op1.constant)), Z_STRLEN(CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC); Z_TYPE(CONSTANT(opline_ptr->op1.constant)) = IS_NULL; } else { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); } le = le->next; if (variable->op_type == IS_VAR && variable->u.op.var == this_var) { variable->op_type = IS_CV; variable->u.op.var = CG(active_op_array)->this_var; } } else if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1 TSRMLS_CC); } } while (le) { opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode == ZEND_SEPARATE) { if (type != BP_VAR_R && type != BP_VAR_IS) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); } le = le->next; continue; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); if (opline->op1_type == IS_VAR && opline->op1.var == this_var) { opline->op1_type = IS_CV; opline->op1.var = CG(active_op_array)->this_var; } switch (type) { case BP_VAR_R: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode -= 3; break; case BP_VAR_W: break; case BP_VAR_RW: opline->opcode += 3; break; case BP_VAR_IS: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode += 6; /* 3+3 */ break; case BP_VAR_FUNC_ARG: opline->opcode += 9; /* 3+3+3 */ opline->extended_value |= arg_offset; break; case BP_VAR_UNSET: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for unsetting"); } opline->opcode += 12; /* 3+3+3+3 */ break; } le = le->next; } if (opline && type == BP_VAR_W && arg_offset) { opline->extended_value |= ZEND_FETCH_MAKE_REF; } } zend_llist_destroy(fetch_list_ptr); zend_stack_del_top(&CG(bp_stack)); } /* }}} */ void zend_do_add_string(znode *result, const znode *op1, znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline; if (Z_STRLEN(op2->u.constant) > 1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_STRING; } else if (Z_STRLEN(op2->u.constant) == 1) { int ch = *Z_STRVAL(op2->u.constant); /* Free memory and use ZEND_ADD_CHAR in case of 1 character strings */ efree(Z_STRVAL(op2->u.constant)); ZVAL_LONG(&op2->u.constant, ch); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_CHAR; } else { /* String can be empty after a variable at the end of a heredoc */ efree(Z_STRVAL(op2->u.constant)); return; } if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_add_variable(znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_VAR; if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_free(znode *op1 TSRMLS_DC) /* {{{ */ { if (op1->op_type==IS_TMP_VAR) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else if (op1->op_type==IS_VAR) { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; while (opline->opcode == ZEND_END_SILENCE || opline->opcode == ZEND_EXT_FCALL_END || opline->opcode == ZEND_OP_DATA) { opline--; } if (opline->result_type == IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_FETCH_R || opline->opcode == ZEND_FETCH_DIM_R || opline->opcode == ZEND_FETCH_OBJ_R) { /* It's very rare and useless case. It's better to use additional FREE opcode and simplify the FETCH handlers their selves */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else { opline->result_type |= EXT_TYPE_UNUSED; } } else { while (opline>CG(active_op_array)->opcodes) { if (opline->opcode == ZEND_FETCH_DIM_R && opline->op1_type == IS_VAR && opline->op1.var == op1->u.op.var) { /* This should the end of a list() construct * Mark its result as unused */ opline->extended_value = ZEND_FETCH_STANDARD; break; } else if (opline->result_type==IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_NEW) { opline->result_type |= EXT_TYPE_UNUSED; } break; } opline--; } } } else if (op1->op_type == IS_CONST) { zval_dtor(&op1->u.constant); } } /* }}} */ int zend_do_verify_access_types(const znode *current_access_type, const znode *new_modifier) /* {{{ */ { if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_PPP_MASK) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Multiple access type modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_ABSTRACT) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Multiple abstract modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_STATIC) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Multiple static modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_FINAL) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Multiple final modifiers are not allowed"); } if (((Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)) & (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) == (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Cannot use the final modifier on an abstract class member"); } return (Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)); } /* }}} */ void zend_do_begin_function_declaration(znode *function_token, znode *function_name, int is_method, int return_reference, znode *fn_flags_znode TSRMLS_DC) /* {{{ */ { zend_op_array op_array; char *name = function_name->u.constant.value.str.val; int name_len = function_name->u.constant.value.str.len; int function_begin_line = function_token->u.op.opline_num; zend_uint fn_flags; char *lcname; zend_bool orig_interactive; ALLOCA_FLAG(use_heap) if (is_method) { if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((Z_LVAL(fn_flags_znode->u.constant) & ~(ZEND_ACC_STATIC|ZEND_ACC_PUBLIC))) { zend_error(E_COMPILE_ERROR, "Access type for interface method %s::%s() must be omitted", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } Z_LVAL(fn_flags_znode->u.constant) |= ZEND_ACC_ABSTRACT; /* propagates to the rest of the parser */ } fn_flags = Z_LVAL(fn_flags_znode->u.constant); /* must be done *after* the above check */ } else { fn_flags = 0; } if ((fn_flags & ZEND_ACC_STATIC) && (fn_flags & ZEND_ACC_ABSTRACT) && !(CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_STRICT, "Static function %s%s%s() should not be abstract", is_method ? CG(active_class_entry)->name : "", is_method ? "::" : "", Z_STRVAL(function_name->u.constant)); } function_token->u.op_array = CG(active_op_array); orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(&op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; op_array.function_name = name; if (return_reference) { op_array.fn_flags |= ZEND_ACC_RETURN_REFERENCE; } op_array.fn_flags |= fn_flags; op_array.scope = is_method?CG(active_class_entry):NULL; op_array.prototype = NULL; op_array.line_start = zend_get_compiled_lineno(TSRMLS_C); if (is_method) { lcname = zend_new_interned_string(zend_str_tolower_dup(name, name_len), name_len + 1, 1 TSRMLS_CC); if (zend_hash_add(&CG(active_class_entry)->function_table, lcname, name_len+1, &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)) == FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::%s()", CG(active_class_entry)->name, name); } zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); if (fn_flags & ZEND_ACC_ABSTRACT) { CG(active_class_entry)->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (!(fn_flags & ZEND_ACC_PPP_MASK)) { fn_flags |= ZEND_ACC_PUBLIC; } if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } } } else { char *class_lcname; class_lcname = do_alloca(CG(active_class_entry)->name_length + 1, use_heap); zend_str_tolower_copy(class_lcname, CG(active_class_entry)->name, CG(active_class_entry)->name_length); /* Improve after RC: cache the lowercase class name */ if ((CG(active_class_entry)->name_length == name_len) && ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT) && (!memcmp(class_lcname, lcname, name_len))) { if (!CG(active_class_entry)->constructor) { CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } } else if ((name_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)))) { if (CG(active_class_entry)->constructor) { zend_error(E_STRICT, "Redefining already defined constructor for class %s", CG(active_class_entry)->name); } CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1))) { CG(active_class_entry)->destructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1))) { CG(active_class_entry)->clone = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } CG(active_class_entry)->__call = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } CG(active_class_entry)->__callstatic = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } CG(active_class_entry)->__get = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } CG(active_class_entry)->__set = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } CG(active_class_entry)->__unset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } CG(active_class_entry)->__isset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } CG(active_class_entry)->__tostring = (zend_function *) CG(active_op_array); } else if (!(fn_flags & ZEND_ACC_STATIC)) { CG(active_op_array)->fn_flags |= ZEND_ACC_ALLOW_STATIC; } free_alloca(class_lcname, use_heap); } str_efree(lcname); } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zval key; if (CG(current_namespace)) { /* Prefix function name with current namespcae name */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, function_name TSRMLS_CC); op_array.function_name = Z_STRVAL(tmp.u.constant); name_len = Z_STRLEN(tmp.u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), name_len); } else { lcname = zend_str_tolower_dup(name, name_len); } opline->opcode = ZEND_DECLARE_FUNCTION; opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, name_len TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; LITERAL_STRINGL(opline->op2, lcname, name_len, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); opline->extended_value = ZEND_DECLARE_FUNCTION; zend_hash_quick_update(CG(function_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); } if (CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_NOP; opline->lineno = function_begin_line; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } { /* Push a seperator to the switch and foreach stacks */ zend_switch_entry switch_entry; switch_entry.cond.op_type = IS_UNUSED; switch_entry.default_case = 0; switch_entry.control_var = 0; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); { /* Foreach stack separator */ zend_op dummy_opline; dummy_opline.result_type = IS_UNUSED; dummy_opline.op1_type = IS_UNUSED; zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); } } if (CG(doc_comment)) { CG(active_op_array)->doc_comment = CG(doc_comment); CG(active_op_array)->doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_begin_lambda_function_declaration(znode *result, znode *function_token, int return_reference, int is_static TSRMLS_DC) /* {{{ */ { znode function_name; zend_op_array *current_op_array = CG(active_op_array); int current_op_number = get_next_op_number(CG(active_op_array)); zend_op *current_op; function_name.op_type = IS_CONST; ZVAL_STRINGL(&function_name.u.constant, "{closure}", sizeof("{closure}")-1, 1); zend_do_begin_function_declaration(function_token, &function_name, 0, return_reference, NULL TSRMLS_CC); result->op_type = IS_TMP_VAR; result->u.op.var = get_temporary_variable(current_op_array); current_op = &current_op_array->opcodes[current_op_number]; current_op->opcode = ZEND_DECLARE_LAMBDA_FUNCTION; zend_del_literal(current_op_array, current_op->op2.constant); SET_UNUSED(current_op->op2); SET_NODE(current_op->result, result); if (is_static) { CG(active_op_array)->fn_flags |= ZEND_ACC_STATIC; } CG(active_op_array)->fn_flags |= ZEND_ACC_CLOSURE; } /* }}} */ void zend_do_handle_exception(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_HANDLE_EXCEPTION; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_function_declaration(const znode *function_token TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; zend_do_extended_info(TSRMLS_C); zend_do_return(NULL, 0 TSRMLS_CC); pass_two(CG(active_op_array) TSRMLS_CC); zend_release_labels(TSRMLS_C); if (CG(active_class_entry)) { zend_check_magic_method_implementation(CG(active_class_entry), (zend_function*)CG(active_op_array), E_COMPILE_ERROR TSRMLS_CC); } else { /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(CG(active_op_array)->function_name); zend_str_tolower_copy(lcname, CG(active_op_array)->function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME)) && CG(active_op_array)->num_args != 1) { zend_error(E_COMPILE_ERROR, "%s() must take exactly 1 argument", ZEND_AUTOLOAD_FUNC_NAME); } } CG(active_op_array)->line_end = zend_get_compiled_lineno(TSRMLS_C); CG(active_op_array) = function_token->u.op_array; /* Pop the switch and foreach seperators */ zend_stack_del_top(&CG(switch_cond_stack)); zend_stack_del_top(&CG(foreach_copy_stack)); } /* }}} */ void zend_do_receive_arg(zend_uchar op, znode *varname, const znode *offset, const znode *initialization, znode *class_type, zend_uchar pass_by_reference TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_arg_info *cur_arg_info; znode var; if (class_type->op_type == IS_CONST && Z_TYPE(class_type->u.constant) == IS_STRING && Z_STRLEN(class_type->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_type->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } if (zend_is_auto_global(Z_STRVAL(varname->u.constant), Z_STRLEN(varname->u.constant) TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign auto-global variable %s", Z_STRVAL(varname->u.constant)); } else { var.op_type = IS_CV; var.u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len TSRMLS_CC); varname->u.constant.value.str.val = CG(active_op_array)->vars[var.u.op.var].name; var.EA = 0; if (Z_STRLEN(varname->u.constant) == sizeof("this")-1 && !memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this")-1)) { if (CG(active_op_array)->scope && (CG(active_op_array)->fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } CG(active_op_array)->this_var = var.u.op.var; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->num_args++; opline->opcode = op; SET_NODE(opline->result, &var); SET_NODE(opline->op1, offset); if (op == ZEND_RECV_INIT) { SET_NODE(opline->op2, initialization); } else { CG(active_op_array)->required_num_args = CG(active_op_array)->num_args; SET_UNUSED(opline->op2); } CG(active_op_array)->arg_info = erealloc(CG(active_op_array)->arg_info, sizeof(zend_arg_info)*(CG(active_op_array)->num_args)); cur_arg_info = &CG(active_op_array)->arg_info[CG(active_op_array)->num_args-1]; cur_arg_info->name = zend_new_interned_string(estrndup(varname->u.constant.value.str.val, varname->u.constant.value.str.len), varname->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->name_len = varname->u.constant.value.str.len; cur_arg_info->type_hint = 0; cur_arg_info->allow_null = 1; cur_arg_info->pass_by_reference = pass_by_reference; cur_arg_info->class_name = NULL; cur_arg_info->class_name_len = 0; if (class_type->op_type != IS_UNUSED) { cur_arg_info->allow_null = 0; cur_arg_info->type_hint = class_type->u.constant.type; switch (class_type->u.constant.type) { case IS_CLASS: if (ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_type->u.constant), Z_STRLEN(class_type->u.constant))) { zend_resolve_class_name(class_type, &opline->extended_value, 1 TSRMLS_CC); } class_type->u.constant.value.str.val = zend_new_interned_string(class_type->u.constant.value.str.val, class_type->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->class_name = class_type->u.constant.value.str.val; cur_arg_info->class_name_len = class_type->u.constant.value.str.len; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with a class type hint can only be NULL"); } } break; case IS_ARRAY: if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else if (Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Default value for parameters with array type hint can only be an array or NULL"); } } break; /* scalar type hinting */ case IS_SCALAR: if (op == ZEND_RECV_INIT && Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { break; } /* fall through */ /* scalar type hinting */ case IS_NUMERIC: if (op == ZEND_RECV_INIT && (Z_TYPE(initialization->u.constant) == IS_LONG || Z_TYPE(initialization->u.constant) == IS_DOUBLE)) { break; } /* fall through */ case IS_BOOL: case IS_STRING: case IS_LONG: case IS_DOUBLE: case IS_RESOURCE: case IS_OBJECT: if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) != class_type->u.constant.type && Z_TYPE(initialization->u.constant) != IS_NULL && (Z_TYPE(initialization->u.constant) & IS_CONSTANT_TYPE_MASK) != IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Default value for parameters with %s type hint can only be %s or NULL", zend_get_type_by_const(class_type->u.constant.type), zend_get_type_by_const(class_type->u.constant.type)); } else if (Z_TYPE(initialization->u.constant) == IS_NULL) { cur_arg_info->allow_null = 1; } } break; default: zend_error(E_COMPILE_ERROR, "Unknown type hint"); } } } /* }}} */ int zend_do_begin_function_call(znode *function_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { zend_function *function; char *lcname; char *is_compound = memchr(Z_STRVAL(function_name->u.constant), '\\', Z_STRLEN(function_name->u.constant)); zend_resolve_non_class_name(function_name, check_namespace TSRMLS_CC); if (check_namespace && CG(current_namespace) && !is_compound) { /* We assume we call function from the current namespace if it is not prefixed. */ /* In run-time PHP will check for function with full name and internal function with short name */ zend_do_begin_dynamic_function_call(function_name, 1 TSRMLS_CC); return 1; } lcname = zend_str_tolower_dup(function_name->u.constant.value.str.val, function_name->u.constant.value.str.len); if ((zend_hash_find(CG(function_table), lcname, function_name->u.constant.value.str.len+1, (void **) &function)==FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_FUNCTIONS) && (function->type == ZEND_INTERNAL_FUNCTION))) { zend_do_begin_dynamic_function_call(function_name, 0 TSRMLS_CC); efree(lcname); return 1; /* Dynamic */ } efree(function_name->u.constant.value.str.val); function_name->u.constant.value.str.val = lcname; zend_stack_push(&CG(function_call_stack), (void *) &function, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 0; } /* }}} */ void zend_do_begin_method_call(znode *left_bracket TSRMLS_DC) /* {{{ */ { zend_op *last_op; int last_op_number; unsigned char *ptr = NULL; zend_do_end_variable_parse(left_bracket, BP_VAR_R, 0 TSRMLS_CC); zend_do_begin_variable_parse(TSRMLS_C); last_op_number = get_next_op_number(CG(active_op_array))-1; last_op = &CG(active_op_array)->opcodes[last_op_number]; if ((last_op->op2_type == IS_CONST) && (Z_TYPE(CONSTANT(last_op->op2.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(last_op->op2.constant)) == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !zend_binary_strcasecmp(Z_STRVAL(CONSTANT(last_op->op2.constant)), Z_STRLEN(CONSTANT(last_op->op2.constant)), ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1)) { zend_error(E_COMPILE_ERROR, "Cannot call __clone() method on objects - use 'clone $obj' instead"); } if (last_op->opcode == ZEND_FETCH_OBJ_R) { if (last_op->op2_type == IS_CONST) { zval name; name = CONSTANT(last_op->op2.constant); if (!IS_INTERNED(Z_STRVAL(name))) { Z_STRVAL(name) = estrndup(Z_STRVAL(name), Z_STRLEN(name)); } FREE_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); last_op->op2.constant = zend_add_func_name_literal(CG(active_op_array), &name TSRMLS_CC); GET_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); } last_op->opcode = ZEND_INIT_METHOD_CALL; SET_UNUSED(last_op->result); Z_LVAL(left_bracket->u.constant) = ZEND_INIT_FCALL_BY_NAME; } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (left_bracket->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &left_bracket->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, left_bracket); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_do_clone(znode *result, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CLONE; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_begin_dynamic_function_call(znode *function_name, int ns_call TSRMLS_DC) /* {{{ */ { unsigned char *ptr = NULL; zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (ns_call) { /* In run-time PHP will check for function with full name and internal function with short name */ opline->opcode = ZEND_INIT_NS_FCALL_BY_NAME; SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_ns_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (function_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, function_name); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_resolve_non_class_name(znode *element_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; int len; zval **ns; char *lcname, *compound = memchr(Z_STRVAL(element_name->u.constant), '\\', Z_STRLEN(element_name->u.constant)); if (Z_STRVAL(element_name->u.constant)[0] == '\\') { /* name starts with \ so it is known and unambiguos, nothing to do here but shorten it */ memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+1, Z_STRLEN(element_name->u.constant)); --Z_STRLEN(element_name->u.constant); return; } if(!check_namespace) { return; } if (compound && CG(current_import)) { len = compound - Z_STRVAL(element_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(element_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(element_name->u.constant) -= len; memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+len, Z_STRLEN(element_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, element_name TSRMLS_CC); *element_name = tmp; efree(lcname); return; } efree(lcname); } if (CG(current_namespace)) { tmp = *element_name; Z_STRLEN(tmp.u.constant) = sizeof("\\")-1 + Z_STRLEN(element_name->u.constant) + Z_STRLEN_P(CG(current_namespace)); Z_STRVAL(tmp.u.constant) = (char *) emalloc(Z_STRLEN(tmp.u.constant)+1); memcpy(Z_STRVAL(tmp.u.constant), Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace))]), "\\", sizeof("\\")-1); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace)) + sizeof("\\")-1]), Z_STRVAL(element_name->u.constant), Z_STRLEN(element_name->u.constant)+1); STR_FREE(Z_STRVAL(element_name->u.constant)); *element_name = tmp; } } /* }}} */ void zend_resolve_class_name(znode *class_name, ulong *fetch_type, int check_ns_name TSRMLS_DC) /* {{{ */ { char *compound; char *lcname; zval **ns; znode tmp; int len; compound = memchr(Z_STRVAL(class_name->u.constant), '\\', Z_STRLEN(class_name->u.constant)); if (compound) { /* This is a compound class name that contains namespace prefix */ if (Z_STRVAL(class_name->u.constant)[0] == '\\') { /* The STRING name has "\" prefix */ Z_STRLEN(class_name->u.constant) -= 1; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+1, Z_STRLEN(class_name->u.constant)+1); Z_STRVAL(class_name->u.constant) = erealloc( Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1); if (ZEND_FETCH_CLASS_DEFAULT != zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "'\\%s' is an invalid class name", Z_STRVAL(class_name->u.constant)); } } else { if (CG(current_import)) { len = compound - Z_STRVAL(class_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(class_name->u.constant) -= len; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+len, Z_STRLEN(class_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; efree(lcname); return; } efree(lcname); } /* Here name is not prefixed with \ and not imported */ if (CG(current_namespace)) { tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } } } else if (CG(current_import) || CG(current_namespace)) { /* this is a plain name (without \) */ lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns) == SUCCESS) { /* The given name is an import name. Substitute it. */ zval_dtor(&class_name->u.constant); class_name->u.constant = **ns; zval_copy_ctor(&class_name->u.constant); } else if (CG(current_namespace)) { /* plain name, no import - prepend current namespace to it */ tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } efree(lcname); } } /* }}} */ void zend_do_fetch_class(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { long fetch_class_op_number; zend_op *opline; if (class_name->op_type == IS_CONST && Z_TYPE(class_name->u.constant) == IS_STRING && Z_STRLEN(class_name->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_name->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } fetch_class_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CLASS; SET_UNUSED(opline->op1); opline->extended_value = ZEND_FETCH_CLASS_GLOBAL; CG(catch_begin) = fetch_class_op_number; if (class_name->op_type == IS_CONST) { int fetch_type; fetch_type = zend_get_class_fetch_type(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); switch (fetch_type) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: SET_UNUSED(opline->op2); opline->extended_value = fetch_type; zval_dtor(&class_name->u.constant); break; default: zend_resolve_class_name(class_name, &opline->extended_value, 0 TSRMLS_CC); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_name->u.constant TSRMLS_CC); break; } } else { SET_NODE(opline->op2, class_name); } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; /* FIXME: Hack so that INIT_FCALL_BY_NAME still knows this is a class */ GET_NODE(result, opline->result); result->EA = opline->extended_value; } /* }}} */ void zend_do_label(znode *label TSRMLS_DC) /* {{{ */ { zend_label dest; if (!CG(context).labels) { ALLOC_HASHTABLE(CG(context).labels); zend_hash_init(CG(context).labels, 4, NULL, NULL, 0); } dest.brk_cont = CG(context).current_brk_cont; dest.opline_num = get_next_op_number(CG(active_op_array)); if (zend_hash_add(CG(context).labels, Z_STRVAL(label->u.constant), Z_STRLEN(label->u.constant) + 1, (void**)&dest, sizeof(zend_label), NULL) == FAILURE) { zend_error(E_COMPILE_ERROR, "Label '%s' already defined", Z_STRVAL(label->u.constant)); } /* Done with label now */ zval_dtor(&label->u.constant); } /* }}} */ void zend_resolve_goto_label(zend_op_array *op_array, zend_op *opline, int pass2 TSRMLS_DC) /* {{{ */ { zend_label *dest; long current, distance; zval *label; if (pass2) { label = opline->op2.zv; } else { label = &CONSTANT_EX(op_array, opline->op2.constant); } if (CG(context).labels == NULL || zend_hash_find(CG(context).labels, Z_STRVAL_P(label), Z_STRLEN_P(label)+1, (void**)&dest) == FAILURE) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; zend_error(E_COMPILE_ERROR, "'goto' to undefined label '%s'", Z_STRVAL_P(label)); } else { /* Label is not defined. Delay to pass 2. */ INC_BPC(op_array); return; } } opline->op1.opline_num = dest->opline_num; zval_dtor(label); Z_TYPE_P(label) = IS_NULL; /* Check that we are not moving into loop or switch */ current = opline->extended_value; for (distance = 0; current != dest->brk_cont; distance++) { if (current == -1) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; } zend_error(E_COMPILE_ERROR, "'goto' into loop or switch statement is disallowed"); } current = op_array->brk_cont_array[current].parent; } if (distance == 0) { /* Nothing to break out of, optimize to ZEND_JMP */ opline->opcode = ZEND_JMP; opline->extended_value = 0; SET_UNUSED(opline->op2); } else { /* Set real break distance */ ZVAL_LONG(label, distance); } if (pass2) { DEC_BPC(op_array); } } /* }}} */ void zend_do_goto(const znode *label TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_GOTO; opline->extended_value = CG(context).current_brk_cont; SET_UNUSED(opline->op1); SET_NODE(opline->op2, label); zend_resolve_goto_label(CG(active_op_array), opline, 0 TSRMLS_CC); } /* }}} */ void zend_release_labels(TSRMLS_D) /* {{{ */ { if (CG(context).labels) { zend_hash_destroy(CG(context).labels); FREE_HASHTABLE(CG(context).labels); } if (!zend_stack_is_empty(&CG(context_stack))) { zend_compiler_context *ctx; zend_stack_top(&CG(context_stack), (void**)&ctx); CG(context) = *ctx; zend_stack_del_top(&CG(context_stack)); } } /* }}} */ void zend_do_build_full_name(znode *result, znode *prefix, znode *name, int is_class_member TSRMLS_DC) /* {{{ */ { zend_uint length; if (!result) { result = prefix; } else { *result = *prefix; } if (is_class_member) { length = sizeof("::")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "::", sizeof("::")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("::")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } else { length = sizeof("\\")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "\\", sizeof("\\")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("\\")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } } /* }}} */ int zend_do_begin_class_member_function_call(znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { znode class_node; unsigned char *ptr = NULL; zend_op *opline; ulong fetch_type = 0; if (method_name->op_type == IS_CONST) { char *lcname = zend_str_tolower_dup(Z_STRVAL(method_name->u.constant), Z_STRLEN(method_name->u.constant)); if ((sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == Z_STRLEN(method_name->u.constant) && memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == 0) { zval_dtor(&method_name->u.constant); method_name->op_type = IS_UNUSED; } efree(lcname); } if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { fetch_type = ZEND_FETCH_CLASS_GLOBAL; zend_resolve_class_name(class_name, &fetch_type, 1 TSRMLS_CC); class_node = *class_name; opline = get_next_op(CG(active_op_array) TSRMLS_CC); } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->extended_value = class_node.EA ; } opline->opcode = ZEND_INIT_STATIC_METHOD_CALL; if (class_node.op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, &class_node); } if (method_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &method_name->u.constant TSRMLS_CC); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } } else { SET_NODE(opline->op2, method_name); } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 1; /* Dynamic */ } /* }}} */ void zend_do_end_function_call(znode *function_name, znode *result, const znode *argument_list, int is_method, int is_dynamic_fcall TSRMLS_DC) /* {{{ */ { zend_op *opline; if (is_method && function_name && function_name->op_type == IS_UNUSED) { /* clone */ if (Z_LVAL(argument_list->u.constant) != 0) { zend_error(E_WARNING, "Clone method does not require arguments"); } opline = &CG(active_op_array)->opcodes[Z_LVAL(function_name->u.constant)]; } else { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (!is_method && !is_dynamic_fcall && function_name->op_type==IS_CONST) { opline->opcode = ZEND_DO_FCALL; SET_NODE(opline->op1, function_name); CALCULATE_LITERAL_HASH(opline->op1.constant); GET_CACHE_SLOT(opline->op1.constant); } else { opline->opcode = ZEND_DO_FCALL_BY_NAME; SET_UNUSED(opline->op1); } } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(result, opline->result) ; SET_UNUSED(opline->op2); zend_stack_del_top(&CG(function_call_stack)); opline->extended_value = Z_LVAL(argument_list->u.constant); } /* }}} */ void zend_do_pass_param(znode *param, zend_uchar op, int offset TSRMLS_DC) /* {{{ */ { zend_op *opline; int original_op=op; zend_function **function_ptr_ptr, *function_ptr; int send_by_reference; int send_function = 0; zend_stack_top(&CG(function_call_stack), (void **) &function_ptr_ptr); function_ptr = *function_ptr_ptr; if (original_op == ZEND_SEND_REF) { if (function_ptr && function_ptr->common.function_name && function_ptr->common.type == ZEND_USER_FUNCTION && !ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed; " "If you would like to pass argument by reference, modify the declaration of %s().", function_ptr->common.function_name); } else { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed"); } return; } if (function_ptr) { if (ARG_MAY_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { if (param->op_type & (IS_VAR|IS_CV)) { send_by_reference = 1; if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION | ZEND_ARG_SEND_SILENT; } } else { op = ZEND_SEND_VAL; send_by_reference = 0; } } else { send_by_reference = ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset) ? ZEND_ARG_SEND_BY_REF : 0; } } else { send_by_reference = 0; } if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION; } else if (op == ZEND_SEND_VAL && (param->op_type & (IS_VAR|IS_CV))) { op = ZEND_SEND_VAR_NO_REF; } if (op!=ZEND_SEND_VAR_NO_REF && send_by_reference==ZEND_ARG_SEND_BY_REF) { /* change to passing by reference */ switch (param->op_type) { case IS_VAR: case IS_CV: op = ZEND_SEND_REF; break; default: zend_error(E_COMPILE_ERROR, "Only variables can be passed by reference"); break; } } if (original_op == ZEND_SEND_VAR) { switch (op) { case ZEND_SEND_VAR_NO_REF: zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); break; case ZEND_SEND_VAR: if (function_ptr) { zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(param, BP_VAR_FUNC_ARG, offset TSRMLS_CC); } break; case ZEND_SEND_REF: zend_do_end_variable_parse(param, BP_VAR_W, 0 TSRMLS_CC); break; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (op == ZEND_SEND_VAR_NO_REF) { if (function_ptr) { opline->extended_value = ZEND_ARG_COMPILE_TIME_BOUND | send_by_reference | send_function; } else { opline->extended_value = send_function; } } else { if (function_ptr) { opline->extended_value = ZEND_DO_FCALL; } else { opline->extended_value = ZEND_DO_FCALL_BY_NAME; } } opline->opcode = op; SET_NODE(opline->op1, param); opline->op2.opline_num = offset; SET_UNUSED(opline->op2); } /* }}} */ static int generate_free_switch_expr(const zend_switch_entry *switch_entry TSRMLS_DC) /* {{{ */ { zend_op *opline; if (switch_entry->cond.op_type != IS_VAR && switch_entry->cond.op_type != IS_TMP_VAR) { return (switch_entry->cond.op_type == IS_UNUSED); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry->cond); SET_UNUSED(opline->op2); opline->extended_value = 0; return 0; } /* }}} */ static int generate_free_foreach_copy(const zend_op *foreach_copy TSRMLS_DC) /* {{{ */ { zend_op *opline; /* If we reach the seperator then stop applying the stack */ if (foreach_copy->result_type == IS_UNUSED && foreach_copy->op1_type == IS_UNUSED) { return 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->result_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->result); SET_UNUSED(opline->op2); opline->extended_value = 1; if (foreach_copy->op1_type != IS_UNUSED) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->op1_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->op1); SET_UNUSED(opline->op2); opline->extended_value = 0; } return 0; } /* }}} */ void zend_do_return(znode *expr, int do_end_vparse TSRMLS_DC) /* {{{ */ { zend_op *opline; int start_op_number, end_op_number; if (do_end_vparse) { if ((CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) && !zend_is_function_or_method_call(expr)) { zend_do_end_variable_parse(expr, BP_VAR_W, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(expr, BP_VAR_R, 0 TSRMLS_CC); } } start_op_number = get_next_op_number(CG(active_op_array)); #ifdef ZTS zend_stack_apply_with_argument(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_switch_expr TSRMLS_CC); zend_stack_apply_with_argument(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_foreach_copy TSRMLS_CC); #else zend_stack_apply(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_switch_expr); zend_stack_apply(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_foreach_copy); #endif end_op_number = get_next_op_number(CG(active_op_array)); while (start_op_number < end_op_number) { CG(active_op_array)->opcodes[start_op_number].extended_value |= EXT_TYPE_FREE_ON_RETURN; start_op_number++; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) ? ZEND_RETURN_BY_REF : ZEND_RETURN; if (expr) { SET_NODE(opline->op1, expr); if (do_end_vparse && zend_is_function_or_method_call(expr)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } } else { opline->op1_type = IS_CONST; LITERAL_NULL(opline->op1); } SET_UNUSED(opline->op2); } /* }}} */ static int zend_add_try_element(zend_uint try_op TSRMLS_DC) /* {{{ */ { int try_catch_offset = CG(active_op_array)->last_try_catch++; CG(active_op_array)->try_catch_array = erealloc(CG(active_op_array)->try_catch_array, sizeof(zend_try_catch_element)*CG(active_op_array)->last_try_catch); CG(active_op_array)->try_catch_array[try_catch_offset].try_op = try_op; return try_catch_offset; } /* }}} */ static void zend_add_catch_element(int offset, zend_uint catch_op TSRMLS_DC) /* {{{ */ { CG(active_op_array)->try_catch_array[offset].catch_op = catch_op; } /* }}} */ void zend_do_first_catch(znode *open_parentheses TSRMLS_DC) /* {{{ */ { open_parentheses->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_initialize_try_catch_element(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist jmp_list; zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); zend_add_catch_element(try_token->u.op.opline_num, get_next_op_number(CG(active_op_array)) TSRMLS_CC); } /* }}} */ void zend_do_mark_last_catch(const znode *first_catch, const znode *last_additional_catch TSRMLS_DC) /* {{{ */ { CG(active_op_array)->last--; zend_do_if_end(TSRMLS_C); if (last_additional_catch->u.op.opline_num == -1) { CG(active_op_array)->opcodes[first_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[first_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } else { CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_try(znode *try_token TSRMLS_DC) /* {{{ */ { try_token->u.op.opline_num = zend_add_try_element(get_next_op_number(CG(active_op_array)) TSRMLS_CC); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_catch(znode *try_token, znode *class_name, znode *catch_var, znode *first_catch TSRMLS_DC) /* {{{ */ { long catch_op_number; zend_op *opline; znode catch_class; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { ulong fetch_type = ZEND_FETCH_CLASS_GLOBAL; zend_resolve_class_name(class_name, &fetch_type, 1 TSRMLS_CC); catch_class = *class_name; } else { zend_error(E_COMPILE_ERROR, "Bad class name in the catch statement"); } catch_op_number = get_next_op_number(CG(active_op_array)); if (first_catch) { first_catch->u.op.opline_num = catch_op_number; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CATCH; opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &catch_class.u.constant TSRMLS_CC); opline->op2_type = IS_CV; opline->op2.var = lookup_cv(CG(active_op_array), catch_var->u.constant.value.str.val, catch_var->u.constant.value.str.len TSRMLS_CC); catch_var->u.constant.value.str.val = CG(active_op_array)->vars[opline->op2.var].name; opline->result.num = 0; /* 1 means it's the last catch in the block */ try_token->u.op.opline_num = catch_op_number; } /* }}} */ void zend_do_end_catch(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); CG(active_op_array)->opcodes[try_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_throw(const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_THROW; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); } /* }}} */ ZEND_API void function_add_ref(zend_function *function) /* {{{ */ { if (function->type == ZEND_USER_FUNCTION) { zend_op_array *op_array = &function->op_array; (*op_array->refcount)++; if (op_array->static_variables) { HashTable *static_variables = op_array->static_variables; zval *tmp_zval; ALLOC_HASHTABLE(op_array->static_variables); zend_hash_init(op_array->static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(op_array->static_variables, static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_zval, sizeof(zval *)); } op_array->run_time_cache = NULL; } } /* }}} */ static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */ { zend_function *function; if (!ce->parent) { return; } /* You cannot change create_object */ ce->create_object = ce->parent->create_object; /* Inherit special functions if needed */ if (!ce->get_iterator) { ce->get_iterator = ce->parent->get_iterator; } if (!ce->iterator_funcs.funcs) { ce->iterator_funcs.funcs = ce->parent->iterator_funcs.funcs; } if (!ce->__get) { ce->__get = ce->parent->__get; } if (!ce->__set) { ce->__set = ce->parent->__set; } if (!ce->__unset) { ce->__unset = ce->parent->__unset; } if (!ce->__isset) { ce->__isset = ce->parent->__isset; } if (!ce->__call) { ce->__call = ce->parent->__call; } if (!ce->__callstatic) { ce->__callstatic = ce->parent->__callstatic; } if (!ce->__tostring) { ce->__tostring = ce->parent->__tostring; } if (!ce->clone) { ce->clone = ce->parent->clone; } if(!ce->serialize) { ce->serialize = ce->parent->serialize; } if(!ce->unserialize) { ce->unserialize = ce->parent->unserialize; } if (!ce->destructor) { ce->destructor = ce->parent->destructor; } if (ce->constructor) { if (ce->parent->constructor && ce->parent->constructor->common.fn_flags & ZEND_ACC_FINAL) { zend_error(E_ERROR, "Cannot override final %s::%s() with %s::%s()", ce->parent->name, ce->parent->constructor->common.function_name, ce->name, ce->constructor->common.function_name ); } return; } if (zend_hash_find(&ce->parent->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), (void **)&function)==SUCCESS) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), function, sizeof(zend_function), NULL); function_add_ref(function); } else { /* Don't inherit the old style constructor if we already have the new style constructor */ char *lc_class_name; char *lc_parent_class_name; lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); if (!zend_hash_exists(&ce->function_table, lc_class_name, ce->name_length+1)) { lc_parent_class_name = zend_str_tolower_dup(ce->parent->name, ce->parent->name_length); if (!zend_hash_exists(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1) && zend_hash_find(&ce->parent->function_table, lc_parent_class_name, ce->parent->name_length+1, (void **)&function)==SUCCESS) { if (function->common.fn_flags & ZEND_ACC_CTOR) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1, function, sizeof(zend_function), NULL); function_add_ref(function); } } efree(lc_parent_class_name); } efree(lc_class_name); } ce->constructor = ce->parent->constructor; } /* }}} */ char *zend_visibility_string(zend_uint fn_flags) /* {{{ */ { if (fn_flags & ZEND_ACC_PRIVATE) { return "private"; } if (fn_flags & ZEND_ACC_PROTECTED) { return "protected"; } if (fn_flags & ZEND_ACC_PUBLIC) { return "public"; } return ""; } /* }}} */ static void do_inherit_method(zend_function *function) /* {{{ */ { /* The class entry of the derived function intentionally remains the same * as that of the parent class. That allows us to know in which context * we're running, and handle private method calls properly. */ function_add_ref(function); } /* }}} */ static zend_bool zend_do_perform_implementation_check(const zend_function *fe, const zend_function *proto) /* {{{ */ { zend_uint i; /* If it's a user function then arg_info == NULL means we don't have any parameters but * we still need to do the arg number checks. We are only willing to ignore this for internal * functions because extensions don't always define arg_info. */ if (!proto || (!proto->common.arg_info && proto->common.type != ZEND_USER_FUNCTION)) { return 1; } /* Checks for constructors only if they are declared in an interface, * or explicitly marked as abstract */ if ((fe->common.fn_flags & ZEND_ACC_CTOR) && ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)) { return 1; } /* check number of arguments */ if (proto->common.required_num_args < fe->common.required_num_args || proto->common.num_args > fe->common.num_args) { return 0; } if (fe->common.type != ZEND_USER_FUNCTION && (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) != 0 && (fe->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) == 0) { return 0; } /* by-ref constraints on return values are covariant */ if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) { return 0; } for (i=0; i < proto->common.num_args; i++) { if (ZEND_LOG_XOR(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)) { /* Only one has a type hint and the other one doesn't */ return 0; } if (fe->common.arg_info[i].class_name && strcasecmp(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)!=0) { char *colon; if (fe->common.type != ZEND_USER_FUNCTION || strchr(proto->common.arg_info[i].class_name, '\\') != NULL || (colon = zend_memrchr(fe->common.arg_info[i].class_name, '\\', fe->common.arg_info[i].class_name_len)) == NULL || strcasecmp(colon+1, proto->common.arg_info[i].class_name) != 0) { return 0; } } if (fe->common.arg_info[i].type_hint != proto->common.arg_info[i].type_hint) { /* Incompatible type hint */ return 0; } /* by-ref constraints on arguments are invariant */ if (fe->common.arg_info[i].pass_by_reference != proto->common.arg_info[i].pass_by_reference) { return 0; } } if (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) { for (i=proto->common.num_args; i < fe->common.num_args; i++) { if (!fe->common.arg_info[i].pass_by_reference) { return 0; } } } return 1; } /* }}} */ static void do_inheritance_check_on_method(zend_function *child, zend_function *parent TSRMLS_DC) { zend_uint child_flags; zend_uint parent_flags = parent->common.fn_flags; if (parent->common.fn_flags & ZEND_ACC_ABSTRACT && parent->common.scope != (child->common.prototype ? child->common.prototype->common.scope : child->common.scope) && child->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_IMPLEMENTED_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Can't inherit abstract function %s::%s() (previously declared abstract in %s)", parent->common.scope->name, child->common.function_name, child->common.prototype ? child->common.prototype->common.scope->name : child->common.scope->name); } if (parent_flags & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot override final method %s::%s()", ZEND_FN_SCOPE_NAME(parent), child->common.function_name); } child_flags = child->common.fn_flags; /* You cannot change from static to non static and vice versa. */ if ((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC)) { if (child->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot make non static method %s::%s() static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } else { zend_error(E_COMPILE_ERROR, "Cannot make static method %s::%s() non static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } } /* Disallow making an inherited method abstract. */ if ((child_flags & ZEND_ACC_ABSTRACT) && !(parent_flags & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Cannot make non abstract method %s::%s() abstract in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } if (parent_flags & ZEND_ACC_CHANGED) { child->common.fn_flags |= ZEND_ACC_CHANGED; } else { /* Prevent derived classes from restricting access that was available in parent classes */ if ((child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::%s() must be %s (as in class %s)%s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if (((child_flags & ZEND_ACC_PPP_MASK) < (parent_flags & ZEND_ACC_PPP_MASK)) && ((parent_flags & ZEND_ACC_PPP_MASK) & ZEND_ACC_PRIVATE)) { child->common.fn_flags |= ZEND_ACC_CHANGED; } } if (parent_flags & ZEND_ACC_PRIVATE) { child->common.prototype = NULL; } else if (parent_flags & ZEND_ACC_ABSTRACT) { child->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; child->common.prototype = parent; } else if (!(parent->common.fn_flags & ZEND_ACC_CTOR) || (parent->common.prototype && (parent->common.prototype->common.scope->ce_flags & ZEND_ACC_INTERFACE))) { /* ctors only have a prototype if it comes from an interface */ child->common.prototype = parent->common.prototype ? parent->common.prototype : parent; } if (child->common.prototype && (child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { if (!zend_do_perform_implementation_check(child, child->common.prototype)) { zend_error(E_COMPILE_ERROR, "Declaration of %s::%s() must be compatible with that of %s::%s()", ZEND_FN_SCOPE_NAME(child), child->common.function_name, ZEND_FN_SCOPE_NAME(child->common.prototype), child->common.prototype->common.function_name); } } else if (EG(error_reporting) & E_STRICT || EG(user_error_handler)) { /* Check E_STRICT (or custom error handler) before the check so that we save some time */ if (!zend_do_perform_implementation_check(child, parent)) { zend_error(E_STRICT, "Declaration of %s::%s() should be compatible with that of %s::%s()", ZEND_FN_SCOPE_NAME(child), child->common.function_name, ZEND_FN_SCOPE_NAME(parent), parent->common.function_name); } } } static zend_bool do_inherit_method_check(HashTable *child_function_table, zend_function *parent, const zend_hash_key *hash_key, zend_class_entry *child_ce) /* {{{ */ { zend_uint parent_flags = parent->common.fn_flags; zend_function *child; TSRMLS_FETCH(); if (zend_hash_quick_find(child_function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child)==FAILURE) { if (parent_flags & (ZEND_ACC_ABSTRACT)) { child_ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } return 1; /* method doesn't exist in child, copy from parent */ } do_inheritance_check_on_method(child, parent TSRMLS_CC); return 0; } /* }}} */ static zend_bool do_inherit_property_access_check(HashTable *target_ht, zend_property_info *parent_info, const zend_hash_key *hash_key, zend_class_entry *ce) /* {{{ */ { zend_property_info *child_info; zend_class_entry *parent_ce = ce->parent; if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW)) { if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { child_info->flags |= ZEND_ACC_CHANGED; } else { zend_hash_quick_update(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, parent_info, sizeof(zend_property_info), (void **) &child_info); if(ce->type & ZEND_INTERNAL_CLASS) { zend_duplicate_property_info_internal(child_info); } else { zend_duplicate_property_info(child_info); } child_info->flags &= ~ZEND_ACC_PRIVATE; /* it's not private anymore */ child_info->flags |= ZEND_ACC_SHADOW; /* but it's a shadow of private */ } return 0; /* don't copy access information to child */ } if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { if ((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s", (parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", parent_ce->name, hash_key->arKey, (child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ce->name, hash_key->arKey); } if(parent_info->flags & ZEND_ACC_CHANGED) { child_info->flags |= ZEND_ACC_CHANGED; } if ((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ce->name, hash_key->arKey, zend_visibility_string(parent_info->flags), parent_ce->name, (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if ((child_info->flags & ZEND_ACC_STATIC) == 0) { Z_DELREF_P(ce->default_properties_table[parent_info->offset]); ce->default_properties_table[parent_info->offset] = ce->default_properties_table[child_info->offset]; ce->default_properties_table[child_info->offset] = NULL; child_info->offset = parent_info->offset; } return 0; /* Don't copy from parent */ } else { return 1; /* Copy from parent */ } } /* }}} */ static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce TSRMLS_CC) == FAILURE) { zend_error(E_CORE_ERROR, "Class %s could not implement interface %s", ce->name, iface->name); } if (ce == iface) { zend_error(E_ERROR, "Interface %s cannot implement itself", ce->name); } } /* }}} */ ZEND_API void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface TSRMLS_DC) /* {{{ */ { /* expects interface to be contained in ce's interface list already */ zend_uint i, ce_num, if_num = iface->num_interfaces; zend_class_entry *entry; if (if_num==0) { return; } ce_num = ce->num_interfaces; if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } /* Inherit the interfaces, only if they're not already inherited by the class */ while (if_num--) { entry = iface->interfaces[if_num]; for (i = 0; i < ce_num; i++) { if (ce->interfaces[i] == entry) { break; } } if (i == ce_num) { ce->interfaces[ce->num_interfaces++] = entry; } } /* and now call the implementing handlers */ while (ce_num < ce->num_interfaces) { do_implement_interface(ce, ce->interfaces[ce_num++] TSRMLS_CC); } } /* }}} */ #ifdef ZTS static void zval_internal_ctor(zval **p) /* {{{ */ { zval *orig_ptr = *p; ALLOC_ZVAL(*p); MAKE_COPY_ZVAL(&orig_ptr, *p); } /* }}} */ # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) (((parent_ce)->type != (ce)->type) ? zval_internal_ctor : zval_add_ref)) #else # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) zval_add_ref) #endif ZEND_API void zend_do_inheritance(zend_class_entry *ce, zend_class_entry *parent_ce TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; if ((ce->ce_flags & ZEND_ACC_INTERFACE) && !(parent_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ce->name, parent_ce->name); } if (parent_ce->ce_flags & ZEND_ACC_FINAL_CLASS) { zend_error(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ce->name, parent_ce->name); } ce->parent = parent_ce; /* Copy serialize/unserialize callbacks */ if (!ce->serialize) { ce->serialize = parent_ce->serialize; } if (!ce->unserialize) { ce->unserialize = parent_ce->unserialize; } /* Inherit interfaces */ zend_do_inherit_interfaces(ce, parent_ce TSRMLS_CC); /* Inherit properties */ if (parent_ce->default_properties_count) { int i = ce->default_properties_count + parent_ce->default_properties_count; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_properties_count) { while (i-- > parent_ce->default_properties_count) { ce->default_properties_table[i] = ce->default_properties_table[i - parent_ce->default_properties_count]; } } for (i = 0; i < parent_ce->default_properties_count; i++) { ce->default_properties_table[i] = parent_ce->default_properties_table[i]; if (ce->default_properties_table[i]) { #ifdef ZTS if (parent_ce->type != ce->type) { zval *p; ALLOC_ZVAL(p); MAKE_COPY_ZVAL(&ce->default_properties_table[i], p); ce->default_properties_table[i] = p; } else { Z_ADDREF_P(ce->default_properties_table[i]); } #else Z_ADDREF_P(ce->default_properties_table[i]); #endif } } ce->default_properties_count += parent_ce->default_properties_count; } if (parent_ce->type != ce->type) { /* User class extends internal class */ zend_update_class_constants(parent_ce TSRMLS_CC); if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = erealloc(ce->default_static_members_table, sizeof(void*) * i); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&CE_STATIC_MEMBERS(parent_ce)[i]); ce->default_static_members_table[i] = CE_STATIC_MEMBERS(parent_ce)[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; ce->static_members_table = ce->default_static_members_table; } } else { if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&parent_ce->default_static_members_table[i]); ce->default_static_members_table[i] = parent_ce->default_static_members_table[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } } for (zend_hash_internal_pointer_reset(&ce->properties_info); zend_hash_get_current_data(&ce->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->properties_info)) { if (property_info->ce == ce) { if (property_info->flags & ZEND_ACC_STATIC) { property_info->offset += parent_ce->default_static_members_count; } else { property_info->offset += parent_ce->default_properties_count; } } } zend_hash_merge_ex(&ce->properties_info, &parent_ce->properties_info, (copy_ctor_func_t) (ce->type & ZEND_INTERNAL_CLASS ? zend_duplicate_property_info_internal : zend_duplicate_property_info), sizeof(zend_property_info), (merge_checker_func_t) do_inherit_property_access_check, ce); zend_hash_merge(&ce->constants_table, &parent_ce->constants_table, zval_property_ctor(parent_ce, ce), NULL, sizeof(zval *), 0); zend_hash_merge_ex(&ce->function_table, &parent_ce->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_inherit_parent_constructor(ce); if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS && ce->type == ZEND_INTERNAL_CLASS) { ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } else if (!(ce->ce_flags & ZEND_ACC_IMPLEMENT_INTERFACES) && !(ce->ce_flags & ZEND_ACC_IMPLEMENT_TRAITS)) { /* The verification will be done in runtime by ZEND_VERIFY_ABSTRACT_CLASS */ zend_verify_abstract_class(ce TSRMLS_CC); } ce->ce_flags |= parent_ce->ce_flags & ZEND_HAS_STATIC_IN_METHODS; } /* }}} */ static zend_bool do_inherit_constant_check(HashTable *child_constants_table, const zval **parent_constant, const zend_hash_key *hash_key, const zend_class_entry *iface) /* {{{ */ { zval **old_constant; if (zend_hash_quick_find(child_constants_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**)&old_constant) == SUCCESS) { if (*old_constant != *parent_constant) { zend_error(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", hash_key->arKey, iface->name); } return 0; } return 1; } /* }}} */ static int do_interface_constant_check(zval **val TSRMLS_DC, int num_args, va_list args, const zend_hash_key *key) /* {{{ */ { zend_class_entry **iface = va_arg(args, zend_class_entry**); do_inherit_constant_check(&(*iface)->constants_table, (const zval **) val, key, *iface); return ZEND_HASH_APPLY_KEEP; } /* }}} */ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_iface_num = ce->num_interfaces; zend_uint parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0; for (i = 0; i < ce->num_interfaces; i++) { if (ce->interfaces[i] == NULL) { memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i)); i--; } else if (ce->interfaces[i] == iface) { if (i < parent_iface_num) { ignore = 1; } else { zend_error(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ce->name, iface->name); } } } if (ignore) { /* Check for attempt to redeclare interface constants */ zend_hash_apply_with_arguments(&ce->constants_table TSRMLS_CC, (apply_func_args_t) do_interface_constant_check, 1, &iface); } else { if (ce->num_interfaces >= current_iface_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } } ce->interfaces[ce->num_interfaces++] = iface; zend_hash_merge_ex(&ce->constants_table, &iface->constants_table, (copy_ctor_func_t) zval_add_ref, sizeof(zval *), (merge_checker_func_t) do_inherit_constant_check, iface); zend_hash_merge_ex(&ce->function_table, &iface->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_implement_interface(ce, iface TSRMLS_CC); zend_do_inherit_interfaces(ce, iface TSRMLS_CC); } } /* }}} */ ZEND_API void zend_do_implement_trait(zend_class_entry *ce, zend_class_entry *trait TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_trait_num = ce->num_traits; zend_uint parent_trait_num = ce->parent ? ce->parent->num_traits : 0; for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == NULL) { memmove(ce->traits + i, ce->traits + i + 1, sizeof(zend_class_entry*) * (--ce->num_traits - i)); i--; } else if (ce->traits[i] == trait) { if (i < parent_trait_num) { ignore = 1; } } } if (!ignore) { if (ce->num_traits >= current_trait_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->traits = (zend_class_entry **) realloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } else { ce->traits = (zend_class_entry **) erealloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } } ce->traits[ce->num_traits++] = trait; } } /* }}} */ static int zend_traits_merge_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { size_t current; size_t i; size_t count; HashTable* resulting_table; HashTable** function_tables; zend_class_entry *ce; size_t collision = 0; size_t abstract_solved = 0; /* unsigned int name_len; */ zend_function* other_trait_fn; current = va_arg(args, size_t); /* index of current trait */ count = va_arg(args, size_t); resulting_table = va_arg(args, HashTable*); function_tables = va_arg(args, HashTable**); ce = va_arg(args, zend_class_entry*); for (i = 0; i < count; i++) { if (i == current) { continue; /* just skip this, cause its the table this function is applied on */ } if (zend_hash_quick_find(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&other_trait_fn) == SUCCESS) { /* if it is an abstract method, there is no collision */ if (other_trait_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* we can savely free and remove it from other table */ zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } else { /* if it is not an abstract method, there is still no collision */ /* if fn is an abstract method */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* just mark as solved, will be added if its own trait is processed */ abstract_solved = 1; } else { /* but else, we have a collision of non-abstract methods */ collision++; zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } } } if (collision) { zend_function* class_fn; /* make sure method is not already overridden in class */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&class_fn) == FAILURE || class_fn->common.scope != ce) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because there are collisions with other trait methods on %s", fn->common.function_name, ce->name); } zend_function_dtor(fn); } else if (abstract_solved) { zend_function_dtor(fn); } else { /* Add it to result function table */ if (zend_hash_quick_add(resulting_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, fn, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating resulting trait method table", fn->common.function_name); } } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ #define IS_EQUAL(mname, mname_len, str) \ strncmp(mname, str, mname_len) #define _ADD_MAGIC_METHOD(ce, mname, mname_len, fe) { \ if (!IS_EQUAL(mname, mname_len, "__clone")) { (ce)->clone = (fe); (fe)->common.fn_flags |= ZEND_ACC_CLONE; } \ else if (!IS_EQUAL(mname, mname_len, "__construct")) { (ce)->constructor = (fe); (fe)->common.fn_flags |= ZEND_ACC_CTOR; } \ else if (!IS_EQUAL(mname, mname_len, "__destruct")) { (ce)->destructor = (fe); (fe)->common.fn_flags |= ZEND_ACC_DTOR; } \ else if (!IS_EQUAL(mname, mname_len, "__get")) (ce)->__get = (fe); \ else if (!IS_EQUAL(mname, mname_len, "__set")) (ce)->__set = (fe); \ else if (!IS_EQUAL(mname, mname_len, "__call")) (ce)->__call = (fe); \ else if (!IS_EQUAL(mname, mname_len, "__unset")) (ce)->__unset = (fe); \ else if (!IS_EQUAL(mname, mname_len, "__isset")) (ce)->__isset = (fe); \ else if (!IS_EQUAL(mname, mname_len, "__callstatic"))(ce)->__callstatic = (fe); \ else if (!IS_EQUAL(mname, mname_len, "__tostring")) (ce)->__tostring = (fe); \ else if (!IS_EQUAL(mname, mname_len, "serialize_func")) (ce)->serialize_func = (fe); \ else if (!IS_EQUAL(mname, mname_len, "unserialize_func"))(ce)->unserialize_func = (fe); \ } /* {{{ Originates from php_runkit_function_copy_ctor Duplicate structures in an op_array where necessary to make an outright duplicate */ static void zend_traits_duplicate_function(zend_function *fe, char *newname TSRMLS_DC) { zend_literal *literals_copy; zend_compiled_variable *dupvars; zend_op *opcode_copy; int i; if (fe->op_array.static_variables) { HashTable *tmpHash; ALLOC_HASHTABLE(tmpHash); zend_hash_init(tmpHash, zend_hash_num_elements(fe->op_array.static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_apply_with_arguments(tmpHash TSRMLS_CC, (apply_func_args_t)zval_copy_static_var, 1, fe->op_array.static_variables); fe->op_array.static_variables = tmpHash; } fe->op_array.refcount = emalloc(sizeof(zend_uint)); *(fe->op_array.refcount) = 1; i = fe->op_array.last_var; dupvars = safe_emalloc(fe->op_array.last_var, sizeof(zend_compiled_variable), 0); while (i > 0) { i--; dupvars[i].name = estrndup(fe->op_array.vars[i].name, fe->op_array.vars[i].name_len); dupvars[i].name_len = fe->op_array.vars[i].name_len; dupvars[i].hash_value = fe->op_array.vars[i].hash_value; } fe->op_array.vars = dupvars; opcode_copy = safe_emalloc(sizeof(zend_op), fe->op_array.last, 0); for(i = 0; i < fe->op_array.last; i++) { opcode_copy[i] = fe->op_array.opcodes[i]; if (opcode_copy[i].op1_type != IS_CONST) { if (opcode_copy[i].op1.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op1.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op1.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op1.jmp_addr - fe->op_array.opcodes); } } if (opcode_copy[i].op2_type != IS_CONST) { if (opcode_copy[i].op2.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op2.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op2.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op2.jmp_addr - fe->op_array.opcodes); } } } fe->op_array.opcodes = opcode_copy; fe->op_array.function_name = newname; /* was setting it to fe which does not work since fe is stack allocated and not a stable address */ /* fe->op_array.prototype = fe->op_array.prototype; */ if (fe->op_array.arg_info) { zend_arg_info *tmpArginfo; tmpArginfo = safe_emalloc(sizeof(zend_arg_info), fe->op_array.num_args, 0); for(i = 0; i < fe->op_array.num_args; i++) { tmpArginfo[i] = fe->op_array.arg_info[i]; tmpArginfo[i].name = estrndup(tmpArginfo[i].name, tmpArginfo[i].name_len); if (tmpArginfo[i].class_name) { tmpArginfo[i].class_name = estrndup(tmpArginfo[i].class_name, tmpArginfo[i].class_name_len); } } fe->op_array.arg_info = tmpArginfo; } fe->op_array.doc_comment = estrndup(fe->op_array.doc_comment, fe->op_array.doc_comment_len); fe->op_array.try_catch_array = (zend_try_catch_element*)estrndup((char*)fe->op_array.try_catch_array, sizeof(zend_try_catch_element) * fe->op_array.last_try_catch); fe->op_array.brk_cont_array = (zend_brk_cont_element*)estrndup((char*)fe->op_array.brk_cont_array, sizeof(zend_brk_cont_element) * fe->op_array.last_brk_cont); /* TODO: check whether there is something similar and whether that is ok */ literals_copy = (zend_literal*)emalloc(fe->op_array.last_literal * sizeof(zend_literal)); for (i = 0; i < fe->op_array.last_literal; i++) { literals_copy[i] = fe->op_array.literals[i]; zval_copy_ctor(&literals_copy[i].constant); } fe->op_array.literals = literals_copy; } /* }}}} */ static int zend_traits_merge_functions_to_class(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) { zend_class_entry *ce = va_arg(args, zend_class_entry*); int add = 0; zend_function* existing_fn; zend_function fn_copy, *fn_copy_p; zend_function* prototype = NULL; /* is used to determine the prototype according to the inheritance chain */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &existing_fn) == FAILURE) { add = 1; /* not found */ } else if (existing_fn->common.scope != ce) { add = 1; /* or inherited from other class or interface */ /* it is just a reference which was added to the subclass while doing the inheritance */ /* prototype = existing_fn; */ /* memory is scrambled anyway???? */ /* function_add_ref(prototype); */ zend_hash_quick_del(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h); } if (add) { zend_function* parent_function; if (ce->parent && zend_hash_quick_find(&ce->parent->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &parent_function) != FAILURE) { prototype = parent_function; /* ->common.fn_flags |= ZEND_ACC_ABSTRACT; */ } fn->common.scope = ce; fn->common.prototype = prototype; if (prototype && (prototype->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT || prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { fn->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; } else if (fn->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT) { /* remove ZEND_ACC_IMPLEMENTED_ABSTRACT flag, think it shouldn't be copied to class */ fn->common.fn_flags = fn->common.fn_flags - ZEND_ACC_IMPLEMENTED_ABSTRACT; } /* check whether the trait method fullfills the inheritance requirements */ if (prototype) { do_inheritance_check_on_method(fn, prototype TSRMLS_CC); } if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (fn->op_array.static_variables) { ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, estrdup(fn->common.function_name) TSRMLS_CC); if (zend_hash_quick_update(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, &fn_copy, sizeof(zend_function), (void**)&fn_copy_p)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating class method table", hash_key->arKey); } _ADD_MAGIC_METHOD(ce, hash_key->arKey, hash_key->nKeyLength, fn_copy_p); /* it could be necessary to update child classes as well */ /* zend_hash_apply_with_arguments(EG(class_table) TSRMLS_CC, (apply_func_args_t)php_runkit_update_children_methods, 5, dce, dce, &dfe, dfunc, dfunc_len); */ zend_function_dtor(fn); } else { zend_function_dtor(fn); } return ZEND_HASH_APPLY_REMOVE; } static int zend_traits_copy_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) { HashTable* target; zend_trait_alias** aliases; HashTable* exclude_table; char* lcname; unsigned int lcname_len; unsigned int fnname_len; zend_function fn_copy; void* dummy; size_t i = 0; target = va_arg(args, HashTable*); aliases = va_arg(args, zend_trait_alias**); exclude_table = va_arg(args, HashTable*); fnname_len = strlen(fn->common.function_name); /* apply aliases which are qualified with a class name, there should not be any ambiguity */ if (aliases) { while (aliases[i]) { if (/* Scope unset or equal to the function we compare to */ (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && /* and, the alias applies to fn */ (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { if (aliases[i]->alias) { fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, estrndup(aliases[i]->alias, aliases[i]->alias_len) TSRMLS_CC); if (aliases[i]->modifiers) { /* if it is 0, no modifieres has been changed */ fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } } lcname_len = aliases[i]->alias_len; lcname = zend_str_tolower_dup(aliases[i]->alias, lcname_len); if (zend_hash_add(target, lcname, lcname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add aliased trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } /* aliases[i]->function = fn_copy; */ efree(lcname); } } i++; } } lcname = zend_str_tolower_dup(fn->common.function_name, fnname_len); if (zend_hash_find(exclude_table, lcname, fnname_len, &dummy) == FAILURE) { /* is not in hashtable, thus, function is not to be excluded */ fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, estrndup(fn->common.function_name, fnname_len) TSRMLS_CC); /* apply aliases which are not qualified by a class name, or which have not alias name, just setting visibility */ if (aliases) { i = 0; while (aliases[i]) { if (/* Scope unset or equal to the function we compare to */ (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && /* and, the alias applies to fn */ (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { if (!aliases[i]->alias && aliases[i]->modifiers) { /* if it is 0, no modifieres has been changed */ fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } } } i++; } } if (zend_hash_add(target, lcname, fnname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } } efree(lcname); return ZEND_HASH_APPLY_KEEP; } /** * Copies function table entries to target function table with applied aliasing */ static void zend_traits_copy_trait_function_table(HashTable *target, HashTable *source, zend_trait_alias** aliases, HashTable* exclude_table TSRMLS_DC) { zend_hash_apply_with_arguments(source TSRMLS_CC, (apply_func_args_t)zend_traits_copy_functions, 3, /* 3 is number of args for apply_func */ target, aliases, exclude_table); } static void zend_traits_init_trait_structures(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i, j = 0; zend_trait_precedence *cur_precedence; zend_trait_method_reference *cur_method_ref; zend_class_entry *cur_ce; /* resolve class references */ if (ce->trait_precedences) { i = 0; while ((cur_precedence = ce->trait_precedences[i])) { cur_ce = zend_fetch_class(cur_precedence->trait_method->class_name, cur_precedence->trait_method->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); cur_precedence->trait_method->ce = cur_ce; if (cur_precedence->exclude_from_classes) { j = 0; while (cur_precedence->exclude_from_classes[j]) { char* class_name = (char*)cur_precedence->exclude_from_classes[j]; zend_uint name_length = strlen(class_name); cur_ce = zend_fetch_class(class_name, name_length, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); efree(class_name); cur_precedence->exclude_from_classes[j] = cur_ce; j++; } } i++; } } if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { cur_method_ref = ce->trait_aliases[i]->trait_method; if (cur_method_ref->class_name) { cur_method_ref->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); } i++; } } } /* }}} */ static void zend_traits_compile_exclude_table(HashTable* exclude_table, zend_trait_precedence **precedences, zend_class_entry *trait) { size_t i, j; if (precedences) { i = 0; while (precedences[i]) { if (precedences[i]->exclude_from_classes) { j = 0; while (precedences[i]->exclude_from_classes[j]) { if (precedences[i]->exclude_from_classes[j] == trait) { zend_uint lcname_len = precedences[i]->trait_method->mname_len; char* lcname = zend_str_tolower_dup(precedences[i]->trait_method->method_name, lcname_len); if (zend_hash_add(exclude_table, lcname, lcname_len, NULL, 0, NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", precedences[i]->trait_method->method_name, trait->name); } efree(lcname); } j++; } } i++; } } } static void zend_do_traits_method_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { HashTable** function_tables; HashTable* resulting_table; HashTable exclude_table; size_t i; /* prepare copies of trait function tables for combination */ function_tables = malloc(sizeof(HashTable*) * ce->num_traits); resulting_table = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(resulting_table, 10, /* TODO: revisit this start size, may be its not optimal */ /* NULL, ZEND_FUNCTION_DTOR, 0, 0); */ NULL, NULL, 0, 0); for (i = 0; i < ce->num_traits; i++) { function_tables[i] = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(function_tables[i], ce->traits[i]->function_table.nNumOfElements, /* NULL, ZEND_FUNCTION_DTOR, 0, 0); */ NULL, NULL, 0, 0); zend_hash_init_ex(&exclude_table, 2, /* TODO: revisit this start size, may be its not optimal */ NULL, NULL, 0, 0); zend_traits_compile_exclude_table(&exclude_table, ce->trait_precedences, ce->traits[i]); /* copies functions, applies defined aliasing, and excludes unused trait methods */ zend_traits_copy_trait_function_table(function_tables[i], &ce->traits[i]->function_table, ce->trait_aliases, &exclude_table TSRMLS_CC); zend_hash_graceful_destroy(&exclude_table); } /* now merge trait methods */ for (i = 0; i < ce->num_traits; i++) { zend_hash_apply_with_arguments(function_tables[i] TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions, 5, /* 5 is number of args for apply_func */ i, ce->num_traits, resulting_table, function_tables, ce); } /* now the resulting_table contains all trait methods we would have to add to the class in the following step the methods are inserted into the method table if there is already a method with the same name it is replaced iff ce != fn.scope --> all inherited methods are overridden, methods defined in the class are left untouched */ zend_hash_apply_with_arguments(resulting_table TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions_to_class, 1, ce); /* free temporary function tables */ for (i = 0; i < ce->num_traits; i++) { /* zend_hash_destroy(function_tables[i]); */ zend_hash_graceful_destroy(function_tables[i]); free(function_tables[i]); } free(function_tables); /* free temporary resulting table */ /* zend_hash_destroy(resulting_table); */ zend_hash_graceful_destroy(resulting_table); free(resulting_table); } static zend_class_entry* find_first_definition(zend_class_entry *ce, size_t current_trait, char* prop_name, int prop_name_length, zend_class_entry *coliding_ce) /* {{{ */ { size_t i; zend_property_info *coliding_prop; for (i = 0; (i < current_trait) && (i < ce->num_traits); i++) { if (zend_hash_find(&ce->traits[i]->properties_info, prop_name, prop_name_length+1, (void **) &coliding_prop) == SUCCESS) { return ce->traits[i]; } } return coliding_ce; } static void zend_do_traits_property_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i; zend_property_info *property_info; zend_property_info *coliding_prop; zval compare_result; char* prop_name; int prop_name_length; char* class_name_unused; zend_bool prop_found; zend_bool not_compatible; zval* prop_value; /* in the following steps the properties are inserted into the property table for that, a very strict approach is applied: - check for compatibility, if not compatible with any property in class -> fatal - if compatible, then strict notice */ for (i = 0; i < ce->num_traits; i++) { for (zend_hash_internal_pointer_reset(&ce->traits[i]->properties_info); zend_hash_get_current_data(&ce->traits[i]->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->traits[i]->properties_info)) { /* property_info now contains the property */ /* first get the unmangeld name if necessary, then check whether the property is already there */ if ((property_info->flags & ZEND_ACC_PPP_MASK) == ZEND_ACC_PUBLIC) { prop_name = property_info->name; prop_name_length = property_info->name_length; prop_found = zend_hash_quick_find(&ce->properties_info, property_info->name, property_info->name_length+1, property_info->h, (void **) &coliding_prop) == SUCCESS; } else { /* for private and protected we need to unmangle the names */ zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name_unused, &prop_name); prop_name_length = strlen(prop_name); prop_found = zend_hash_find(&ce->properties_info, prop_name, prop_name_length+1, (void **) &coliding_prop) == SUCCESS; } /* next: check for conflicts with current class */ if (prop_found) { if (coliding_prop->flags & ZEND_ACC_SHADOW) { /* this one is inherited, lets look it up in its own class */ zend_hash_find(&coliding_prop->ce->properties_info, prop_name, prop_name_length+1, (void **) &coliding_prop); } if ((coliding_prop->flags & ZEND_ACC_PPP_MASK) == (property_info->flags & ZEND_ACC_PPP_MASK)) { /* flags are identical, now the value needs to be checked */ if (property_info->flags & ZEND_ACC_STATIC) { not_compatible = compare_function(&compare_result, ce->default_static_members_table[coliding_prop->offset], ce->traits[i]->default_static_members_table[property_info->offset] TSRMLS_CC) == FAILURE; } else { not_compatible = compare_function(&compare_result, ce->default_properties_table[coliding_prop->offset], ce->traits[i]->default_properties_table[property_info->offset] TSRMLS_CC) == FAILURE; } } else { /* the flags are not identical, thus, we assume properties are not compatible */ not_compatible = 1; } if (not_compatible) { zend_error(E_COMPILE_ERROR, "%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } else { zend_error(E_STRICT, "%s and %s define the same property ($%s) in the composition of %s. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } } /* property not found, so lets add it */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); zend_declare_property_ex(ce, prop_name, prop_name_length, prop_value, property_info->flags, property_info->doc_comment, property_info->doc_comment_len TSRMLS_CC); } } } ZEND_API void zend_do_bind_traits(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { if (ce->num_traits <= 0) { return; } /* complete initialization of trait strutures in ce */ zend_traits_init_trait_structures(ce TSRMLS_CC); /* first care about all methods to be flattened into the class */ zend_do_traits_method_binding(ce TSRMLS_CC); /* then flatten the properties into it, to, mostly to notfiy developer about problems */ zend_do_traits_property_binding(ce TSRMLS_CC); /* verify that all abstract methods from traits have been implemented */ zend_verify_abstract_class(ce TSRMLS_CC); /* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */ if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { ce->ce_flags -= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } } /* }}} */ ZEND_API int do_bind_function(const zend_op_array *op_array, zend_op *opline, HashTable *function_table, zend_bool compile_time) /* {{{ */ { zend_function *function; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } zend_hash_quick_find(function_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void *) &function); if (zend_hash_quick_add(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), function, sizeof(zend_function), NULL)==FAILURE) { int error_level = compile_time ? E_COMPILE_ERROR : E_ERROR; zend_function *old_function; if (zend_hash_quick_find(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), (void *) &old_function)==SUCCESS && old_function->type == ZEND_USER_FUNCTION && old_function->op_array.last > 0) { zend_error(error_level, "Cannot redeclare %s() (previously declared in %s:%d)", function->common.function_name, old_function->op_array.filename, old_function->op_array.opcodes[0].lineno); } else { zend_error(error_level, "Cannot redeclare %s()", function->common.function_name); } return FAILURE; } else { (*function->op_array.refcount)++; function->op_array.static_variables = NULL; /* NULL out the unbound function */ return SUCCESS; } } /* }}} */ void zend_add_trait_precedence(znode *precedence_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_precedences, precedence_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_add_trait_alias(znode *alias_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_aliases, alias_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_prepare_reference(znode *result, znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { zend_trait_method_reference *method_ref = emalloc(sizeof(zend_trait_method_reference)); method_ref->ce = NULL; /* REM: There should not be a need for copying, zend_do_begin_class_declaration is also just using that string */ if (class_name) { method_ref->class_name = Z_STRVAL(class_name->u.constant); method_ref->cname_len = Z_STRLEN(class_name->u.constant); } else { method_ref->class_name = NULL; method_ref->cname_len = 0; } method_ref->method_name = Z_STRVAL(method_name->u.constant); method_ref->mname_len = Z_STRLEN(method_name->u.constant); result->u.op.ptr = method_ref; result->op_type = IS_TMP_VAR; } /* }}} */ void zend_prepare_trait_alias(znode *result, znode *method_reference, znode *modifiers, znode *alias TSRMLS_DC) /* {{{ */ { zend_trait_alias *trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_alias->modifiers = Z_LVAL(modifiers->u.constant); if (Z_LVAL(modifiers->u.constant) == ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot use 'static' as method modifier"); return; } if (alias) { trait_alias->alias = Z_STRVAL(alias->u.constant); trait_alias->alias_len = Z_STRLEN(alias->u.constant); } else { trait_alias->alias = NULL; } trait_alias->function = NULL; result->u.op.ptr = trait_alias; } /* }}} */ /*void init_trait_alias(znode* result, const znode* method_name, const znode* alias, const znode* modifiers TSRMLS_DC)*/ /* {{{ */ /*{ zend_trait_alias* trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->method_name = Z_UNIVAL(method_name->u.constant); // may be method is only excluded, then the alias node is NULL if (alias) { trait_alias->alias = Z_UNIVAL(alias->u.constant); trait_alias->modifiers = Z_LVAL(modifiers->u.constant); } else { } trait_alias->function = NULL; result->u.var = trait_alias; } */ /* }}} */ void zend_prepare_trait_precedence(znode *result, znode *method_reference, znode *trait_list TSRMLS_DC) /* {{{ */ { zend_trait_precedence *trait_precedence = emalloc(sizeof(zend_trait_precedence)); trait_precedence->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_precedence->exclude_from_classes = (zend_class_entry**) trait_list->u.op.ptr; trait_precedence->function = NULL; result->u.op.ptr = trait_precedence; } /* }}} */ ZEND_API zend_class_entry *do_bind_class(const zend_op_array* op_array, const zend_op *opline, HashTable *class_table, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } if (zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce)==FAILURE) { zend_error(E_COMPILE_ERROR, "Internal Zend error - Missing class information for %s", Z_STRVAL_P(op1)); return NULL; } else { ce = *pce; } ce->refcount++; if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), &ce, sizeof(zend_class_entry *), NULL)==FAILURE) { ce->refcount--; if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return NULL; } else { if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLEMENT_INTERFACES))) { zend_verify_abstract_class(ce TSRMLS_CC); } return ce; } } /* }}} */ ZEND_API zend_class_entry *do_bind_inherited_class(const zend_op_array *op_array, const zend_op *opline, HashTable *class_table, zend_class_entry *parent_ce, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; int found_ce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } found_ce = zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce); if (found_ce == FAILURE) { if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", Z_STRVAL_P(op2)); } return NULL; } else { ce = *pce; } if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ce->name, parent_ce->name); } else if ((parent_ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ce->name, parent_ce->name); } zend_do_inheritance(ce, parent_ce TSRMLS_CC); ce->refcount++; /* Register the derived class */ if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), pce, sizeof(zend_class_entry *), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return ce; } /* }}} */ void zend_do_early_binding(TSRMLS_D) /* {{{ */ { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; HashTable *table; while (opline->opcode == ZEND_TICKS && opline > CG(active_op_array)->opcodes) { opline--; } switch (opline->opcode) { case ZEND_DECLARE_FUNCTION: if (do_bind_function(CG(active_op_array), opline, CG(function_table), 1) == FAILURE) { return; } table = CG(function_table); break; case ZEND_DECLARE_CLASS: if (do_bind_class(CG(active_op_array), opline, CG(class_table), 1 TSRMLS_CC) == NULL) { return; } table = CG(class_table); break; case ZEND_DECLARE_INHERITED_CLASS: { zend_op *fetch_class_opline = opline-1; zval *parent_name; zend_class_entry **pce; parent_name = &CONSTANT(fetch_class_opline->op2.constant); if ((zend_lookup_class(Z_STRVAL_P(parent_name), Z_STRLEN_P(parent_name), &pce TSRMLS_CC) == FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_CLASSES) && ((*pce)->type == ZEND_INTERNAL_CLASS))) { if (CG(compiler_options) & ZEND_COMPILE_DELAYED_BINDING) { zend_uint *opline_num = &CG(active_op_array)->early_binding; while (*opline_num != -1) { opline_num = &CG(active_op_array)->opcodes[*opline_num].result.opline_num; } *opline_num = opline - CG(active_op_array)->opcodes; opline->opcode = ZEND_DECLARE_INHERITED_CLASS_DELAYED; opline->result_type = IS_UNUSED; opline->result.opline_num = -1; } return; } if (do_bind_inherited_class(CG(active_op_array), opline, CG(class_table), *pce, 1 TSRMLS_CC) == NULL) { return; } /* clear unnecessary ZEND_FETCH_CLASS opcode */ zend_del_literal(CG(active_op_array), fetch_class_opline->op2.constant); MAKE_NOP(fetch_class_opline); table = CG(class_table); break; } case ZEND_VERIFY_ABSTRACT_CLASS: case ZEND_ADD_INTERFACE: case ZEND_ADD_TRAIT: case ZEND_BIND_TRAITS: /* We currently don't early-bind classes that implement interfaces */ /* Classes with traits are handled exactly the same, no early-bind here */ return; default: zend_error(E_COMPILE_ERROR, "Invalid binding type"); return; } zend_hash_quick_del(table, Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant)), Z_HASH_P(&CONSTANT(opline->op1.constant))); zend_del_literal(CG(active_op_array), opline->op1.constant); zend_del_literal(CG(active_op_array), opline->op2.constant); MAKE_NOP(opline); } /* }}} */ ZEND_API void zend_do_delayed_early_binding(const zend_op_array *op_array TSRMLS_DC) /* {{{ */ { if (op_array->early_binding != -1) { zend_bool orig_in_compilation = CG(in_compilation); zend_uint opline_num = op_array->early_binding; zend_class_entry **pce; CG(in_compilation) = 1; while (opline_num != -1) { if (zend_lookup_class(Z_STRVAL_P(op_array->opcodes[opline_num-1].op2.zv), Z_STRLEN_P(op_array->opcodes[opline_num-1].op2.zv), &pce TSRMLS_CC) == SUCCESS) { do_bind_inherited_class(op_array, &op_array->opcodes[opline_num], EG(class_table), *pce, 0 TSRMLS_CC); } opline_num = op_array->opcodes[opline_num].result.opline_num; } CG(in_compilation) = orig_in_compilation; } } /* }}} */ void zend_do_boolean_or_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_or_end(znode *result, const znode *expr1, const znode *expr2, znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_boolean_and_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_and_end(znode *result, const znode *expr1, const znode *expr2, const znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_do_while_begin(TSRMLS_D) /* {{{ */ { do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_do_while_end(const znode *do_token, const znode *expr_open_bracket, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ; SET_NODE(opline->op1, expr); opline->op2.opline_num = do_token->u.op.opline_num; SET_UNUSED(opline->op2); do_end_loop(expr_open_bracket->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_brk_cont(zend_uchar op, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->op1.opline_num = CG(context).current_brk_cont; SET_UNUSED(opline->op1); if (expr) { if (expr->op_type != IS_CONST) { zend_error(E_COMPILE_ERROR, "'%s' operator with non-constant operand is no longer supported", op == ZEND_BRK ? "break" : "continue"); } else if (Z_TYPE(expr->u.constant) != IS_LONG || Z_LVAL(expr->u.constant) < 1) { zend_error(E_COMPILE_ERROR, "'%s' operator accepts only positive numbers", op == ZEND_BRK ? "break" : "continue"); } SET_NODE(opline->op2, expr); } else { LITERAL_LONG(opline->op2, 1); opline->op2_type = IS_CONST; } } /* }}} */ void zend_do_switch_cond(const znode *cond TSRMLS_DC) /* {{{ */ { zend_switch_entry switch_entry; switch_entry.cond = *cond; switch_entry.default_case = -1; switch_entry.control_var = -1; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_switch_end(const znode *case_list TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); /* add code to jmp to default case */ if (switch_entry_ptr->default_case != -1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->op1.opline_num = switch_entry_ptr->default_case; } if (case_list->op_type != IS_UNUSED) { /* non-empty switch */ int next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* remember break/continue loop information */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; if (switch_entry_ptr->cond.op_type==IS_VAR || switch_entry_ptr->cond.op_type==IS_TMP_VAR) { /* emit free for the switch condition*/ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry_ptr->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_UNUSED(opline->op2); } if (switch_entry_ptr->cond.op_type == IS_CONST) { zval_dtor(&switch_entry_ptr->cond.u.constant); } zend_stack_del_top(&CG(switch_cond_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_case_before_statement(const znode *case_list, znode *case_token, const znode *case_expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); int next_op_number; zend_switch_entry *switch_entry_ptr; znode result; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); if (switch_entry_ptr->control_var == -1) { switch_entry_ptr->control_var = get_temporary_variable(CG(active_op_array)); } opline->opcode = ZEND_CASE; opline->result.var = switch_entry_ptr->control_var; opline->result_type = IS_TMP_VAR; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_NODE(opline->op2, case_expr); if (opline->op1_type == IS_CONST) { zval_copy_ctor(&CONSTANT(opline->op1.constant)); } GET_NODE(&result, opline->result); next_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, &result); SET_UNUSED(opline->op2); case_token->u.op.opline_num = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_case_after_statement(znode *result, const znode *case_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); result->u.op.opline_num = next_op_number; switch (CG(active_op_array)->opcodes[case_token->u.op.opline_num].opcode) { case ZEND_JMP: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); break; case ZEND_JMPZ: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); break; } } /* }}} */ void zend_do_default_before_statement(const znode *case_list, znode *default_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); default_token->u.op.opline_num = next_op_number; next_op_number = get_next_op_number(CG(active_op_array)); switch_entry_ptr->default_case = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_begin_class_declaration(const znode *class_token, znode *class_name, const znode *parent_class_name TSRMLS_DC) /* {{{ */ { zend_op *opline; int doing_inheritance = 0; zend_class_entry *new_class_entry; char *lcname; int error = 0; zval **ns_name, key; if (CG(active_class_entry)) { zend_error(E_COMPILE_ERROR, "Class declarations may not be nested"); return; } lcname = zend_str_tolower_dup(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); if (!(strcmp(lcname, "self") && strcmp(lcname, "parent"))) { efree(lcname); zend_error(E_COMPILE_ERROR, "Cannot use '%s' as class name as it is reserved", class_name->u.constant.value.str.val); } /* Class name must not conflict with import names */ if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns_name) == SUCCESS) { error = 1; } if (CG(current_namespace)) { /* Prefix class name with name of current namespace */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); class_name = &tmp; efree(lcname); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); } if (error) { char *tmp = zend_str_tolower_dup(Z_STRVAL_PP(ns_name), Z_STRLEN_PP(ns_name)); if (Z_STRLEN_PP(ns_name) != Z_STRLEN(class_name->u.constant) || memcmp(tmp, lcname, Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "Cannot declare class %s because the name is already in use", Z_STRVAL(class_name->u.constant)); } efree(tmp); } new_class_entry = emalloc(sizeof(zend_class_entry)); new_class_entry->type = ZEND_USER_CLASS; new_class_entry->name = zend_new_interned_string(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1, 1 TSRMLS_CC); new_class_entry->name_length = Z_STRLEN(class_name->u.constant); zend_initialize_class_data(new_class_entry, 1 TSRMLS_CC); new_class_entry->info.user.filename = zend_get_compiled_filename(TSRMLS_C); new_class_entry->info.user.line_start = class_token->u.op.opline_num; new_class_entry->ce_flags |= class_token->EA; if (parent_class_name && parent_class_name->op_type != IS_UNUSED) { switch (parent_class_name->EA) { case ZEND_FETCH_CLASS_SELF: zend_error(E_COMPILE_ERROR, "Cannot use 'self' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_PARENT: zend_error(E_COMPILE_ERROR, "Cannot use 'parent' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use 'static' as class name as it is reserved"); break; default: break; } doing_inheritance = 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, new_class_entry->name_length TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; if (doing_inheritance) { opline->extended_value = parent_class_name->u.op.var; opline->opcode = ZEND_DECLARE_INHERITED_CLASS; } else { opline->opcode = ZEND_DECLARE_CLASS; } LITERAL_STRINGL(opline->op2, lcname, new_class_entry->name_length, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); zend_hash_quick_update(CG(class_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &new_class_entry, sizeof(zend_class_entry *), NULL); CG(active_class_entry) = new_class_entry; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(&CG(implementing_class), opline->result); if (CG(doc_comment)) { CG(active_class_entry)->info.user.doc_comment = CG(doc_comment); CG(active_class_entry)->info.user.doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ static void do_verify_abstract_class(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_VERIFY_ABSTRACT_CLASS; SET_NODE(opline->op1, &CG(implementing_class)); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_class_declaration(const znode *class_token, const znode *parent_token TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); if (ce->constructor) { ce->constructor->common.fn_flags |= ZEND_ACC_CTOR; if (ce->constructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Constructor %s::%s() cannot be static", ce->name, ce->constructor->common.function_name); } } if (ce->destructor) { ce->destructor->common.fn_flags |= ZEND_ACC_DTOR; if (ce->destructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Destructor %s::%s() cannot be static", ce->name, ce->destructor->common.function_name); } } if (ce->clone) { ce->clone->common.fn_flags |= ZEND_ACC_CLONE; if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static", ce->name, ce->clone->common.function_name); } } ce->info.user.line_end = zend_get_compiled_lineno(TSRMLS_C); /* Check for traits and proceed like with interfaces. * The only difference will be a combined handling of them in the end. * Thus, we need another opcode here. */ if (ce->num_traits > 0) { zend_op *opline; ce->traits = NULL; ce->num_traits = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_TRAITS; /* opcode generation: */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BIND_TRAITS; SET_NODE(opline->op1, &CG(implementing_class)); } if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) && ((parent_token->op_type != IS_UNUSED) || (ce->num_interfaces > 0))) { zend_verify_abstract_class(ce TSRMLS_CC); if (ce->num_interfaces) { do_verify_abstract_class(TSRMLS_C); } } /* Inherit interfaces; reset number to zero, we need it for above check and * will restore it during actual implementation. * The ZEND_ACC_IMPLEMENT_INTERFACES flag disables double call to * zend_verify_abstract_class() */ if (ce->num_interfaces > 0) { ce->interfaces = NULL; ce->num_interfaces = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_INTERFACES; } CG(active_class_entry) = NULL; } /* }}} */ void zend_do_implements_interface(znode *interface_name TSRMLS_DC) /* {{{ */ { zend_op *opline; /* Traits can not implement interfaces */ if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface on '%s' since it is a Trait", Z_STRVAL(interface_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(interface_name->u.constant), Z_STRLEN(interface_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface name as it is reserved", Z_STRVAL(interface_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_INTERFACE; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(interface_name, &opline->extended_value, 0 TSRMLS_CC); opline->extended_value = (opline->extended_value & ~ZEND_FETCH_CLASS_MASK) | ZEND_FETCH_CLASS_INTERFACE; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &interface_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_interfaces++; } /* }}} */ void zend_do_implements_trait(znode *trait_name TSRMLS_DC) /* {{{ */ { zend_op *opline; switch (zend_get_class_fetch_type(Z_STRVAL(trait_name->u.constant), Z_STRLEN(trait_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as trait name as it is reserved", Z_STRVAL(trait_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_TRAIT; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(trait_name, &opline->extended_value, 0 TSRMLS_CC); opline->extended_value = ZEND_FETCH_CLASS_TRAIT; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &trait_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_traits++; } /* }}} */ ZEND_API void zend_mangle_property_name(char **dest, int *dest_length, const char *src1, int src1_length, const char *src2, int src2_length, int internal) /* {{{ */ { char *prop_name; int prop_name_length; prop_name_length = 1 + src1_length + 1 + src2_length; prop_name = pemalloc(prop_name_length + 1, internal); prop_name[0] = '\0'; memcpy(prop_name + 1, src1, src1_length+1); memcpy(prop_name + 1 + src1_length + 1, src2, src2_length+1); *dest = prop_name; *dest_length = prop_name_length; } /* }}} */ static int zend_strnlen(const char* s, int maxlen) /* {{{ */ { int len = 0; while (*s++ && maxlen--) len++; return len; } /* }}} */ ZEND_API int zend_unmangle_property_name(char *mangled_property, int len, char **class_name, char **prop_name) /* {{{ */ { int class_name_len; *class_name = NULL; if (mangled_property[0]!=0) { *prop_name = mangled_property; return SUCCESS; } if (len < 3 || mangled_property[1]==0) { zend_error(E_NOTICE, "Illegal member variable name"); *prop_name = mangled_property; return FAILURE; } class_name_len = zend_strnlen(mangled_property+1, --len - 1) + 1; if (class_name_len >= len || mangled_property[class_name_len]!=0) { zend_error(E_NOTICE, "Corrupt member variable name"); *prop_name = mangled_property; return FAILURE; } *class_name = mangled_property+1; *prop_name = (*class_name)+class_name_len; return SUCCESS; } /* }}} */ void zend_do_declare_property(const znode *var_name, const znode *value, zend_uint access_type TSRMLS_DC) /* {{{ */ { zval *property; zend_property_info *existing_property_info; char *comment = NULL; int comment_len = 0; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Interfaces may not include member variables"); } if (access_type & ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Properties cannot be declared abstract"); } if (access_type & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot declare property %s::$%s final, the final modifier is allowed only for methods and classes", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } if (zend_hash_find(&CG(active_class_entry)->properties_info, var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, (void **) &existing_property_info)==SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::$%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } ALLOC_ZVAL(property); if (value) { *property = value->u.constant; } else { INIT_PZVAL(property); Z_TYPE_P(property) = IS_NULL; } if (CG(doc_comment)) { comment = CG(doc_comment); comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } zend_declare_property_ex(CG(active_class_entry), zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len + 1, 0 TSRMLS_CC), var_name->u.constant.value.str.len, property, access_type, comment, comment_len TSRMLS_CC); efree(var_name->u.constant.value.str.val); } /* }}} */ void zend_do_declare_class_constant(znode *var_name, const znode *value TSRMLS_DC) /* {{{ */ { zval *property; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed in class constants"); return; } if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Traits cannot have constants"); return; } ALLOC_ZVAL(property); *property = value->u.constant; if (zend_hash_add(&CG(active_class_entry)->constants_table, zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, 0 TSRMLS_CC), var_name->u.constant.value.str.len+1, &property, sizeof(zval *), NULL)==FAILURE) { FREE_ZVAL(property); zend_error(E_COMPILE_ERROR, "Cannot redefine class constant %s::%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } FREE_PNODE(var_name); if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_fetch_property(znode *result, znode *object, const znode *property TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (object->op_type == IS_CV) { if (object->u.op.var == CG(active_op_array)->this_var) { object->op_type = IS_UNUSED; /* this means $this for objects */ } } else if (fetch_list_ptr->count == 1) { zend_llist_element *le = fetch_list_ptr->head; zend_op *opline_ptr = (zend_op *) le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); SET_UNUSED(opline_ptr->op1); /* this means $this for objects */ SET_NODE(opline_ptr->op2, property); /* if it was usual fetch, we change it to object fetch */ switch (opline_ptr->opcode) { case ZEND_FETCH_W: opline_ptr->opcode = ZEND_FETCH_OBJ_W; break; case ZEND_FETCH_R: opline_ptr->opcode = ZEND_FETCH_OBJ_R; break; case ZEND_FETCH_RW: opline_ptr->opcode = ZEND_FETCH_OBJ_RW; break; case ZEND_FETCH_IS: opline_ptr->opcode = ZEND_FETCH_OBJ_IS; break; case ZEND_FETCH_UNSET: opline_ptr->opcode = ZEND_FETCH_OBJ_UNSET; break; case ZEND_FETCH_FUNC_ARG: opline_ptr->opcode = ZEND_FETCH_OBJ_FUNC_ARG; break; } if (opline_ptr->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline_ptr->op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline_ptr->op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op2.constant); } GET_NODE(result, opline_ptr->result); return; } } if (zend_is_function_or_method_call(object)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, object); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_OBJ_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, object); SET_NODE(opline.op2, property); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline.op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op2.constant); } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void zend_do_halt_compiler_register(TSRMLS_D) /* {{{ */ { char *name, *cfilename; char haltoff[] = "__COMPILER_HALT_OFFSET__"; int len, clen; cfilename = zend_get_compiled_filename(TSRMLS_C); clen = strlen(cfilename); zend_mangle_property_name(&name, &len, haltoff, sizeof(haltoff) - 1, cfilename, clen, 0); zend_register_long_constant(name, len+1, zend_get_scanned_file_offset(TSRMLS_C), CONST_CS, 0 TSRMLS_CC); pefree(name, 0); } /* }}} */ void zend_do_push_object(const znode *object TSRMLS_DC) /* {{{ */ { zend_stack_push(&CG(object_stack), object, sizeof(znode)); } /* }}} */ void zend_do_pop_object(znode *object TSRMLS_DC) /* {{{ */ { if (object) { znode *tmp; zend_stack_top(&CG(object_stack), (void **) &tmp); *object = *tmp; } zend_stack_del_top(&CG(object_stack)); } /* }}} */ void zend_do_begin_new_object(znode *new_token, znode *class_type TSRMLS_DC) /* {{{ */ { zend_op *opline; unsigned char *ptr = NULL; new_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_NEW; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, class_type); SET_UNUSED(opline->op2); zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(unsigned char *)); } /* }}} */ void zend_do_end_new_object(znode *result, const znode *new_token, const znode *argument_list TSRMLS_DC) /* {{{ */ { znode ctor_result; zend_do_end_function_call(NULL, &ctor_result, argument_list, 1, 0 TSRMLS_CC); zend_do_free(&ctor_result TSRMLS_CC); CG(active_op_array)->opcodes[new_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, CG(active_op_array)->opcodes[new_token->u.op.opline_num].result); } /* }}} */ static zend_constant* zend_get_ct_const(const zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = NULL; if (Z_STRVAL_P(const_name)[0] == '\\') { if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name), (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name)-1); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name), (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } } else if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)+1, (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name)+1, (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } if (c->flags & CONST_CT_SUBST) { return c; } if (all_internal_constants_substitution && (c->flags & CONST_PERSISTENT) && !(CG(compiler_options) & ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION) && Z_TYPE(c->value) != IS_CONSTANT && Z_TYPE(c->value) != IS_CONSTANT_ARRAY) { return c; } return NULL; } /* }}} */ static int zend_constant_ct_subst(znode *result, zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = zend_get_ct_const(const_name, all_internal_constants_substitution TSRMLS_CC); if (c) { zval_dtor(const_name); result->op_type = IS_CONST; result->u.constant = c->value; zval_copy_ctor(&result->u.constant); INIT_PZVAL(&result->u.constant); return 1; } return 0; } /* }}} */ void zend_do_fetch_constant(znode *result, znode *constant_container, znode *constant_name, int mode, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; zend_op *opline; int type; char *compound; ulong fetch_type = 0; if (constant_container) { switch (mode) { case ZEND_CT: /* this is a class constant */ type = zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant)); if (ZEND_FETCH_CLASS_STATIC == type) { zend_error(E_ERROR, "\"static::\" is not allowed in compile-time constants"); } else if (ZEND_FETCH_CLASS_DEFAULT == type) { zend_resolve_class_name(constant_container, &fetch_type, 1 TSRMLS_CC); } zend_do_build_full_name(NULL, constant_container, constant_name, 1 TSRMLS_CC); *result = *constant_container; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: if (constant_container->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant))) { zend_resolve_class_name(constant_container, &fetch_type, 1 TSRMLS_CC); } else { zend_do_fetch_class(&tmp, constant_container TSRMLS_CC); constant_container = &tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); if (constant_container->op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &constant_container->u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, constant_container); } SET_NODE(opline->op2, constant_name); CALCULATE_LITERAL_HASH(opline->op2.constant); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } GET_NODE(result, opline->result); break; } return; } /* namespace constant */ /* only one that did not contain \ from the start can be converted to string if unknown */ switch (mode) { case ZEND_CT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); /* this is a namespace constant, or an unprefixed constant */ if (zend_constant_ct_subst(result, &constant_name->u.constant, 0 TSRMLS_CC)) { break; } zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(!compound) { fetch_type |= IS_CONSTANT_UNQUALIFIED; } *result = *constant_name; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(zend_constant_ct_subst(result, &constant_name->u.constant, 1 TSRMLS_CC)) { break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; if (compound) { /* the name is unambiguous */ opline->extended_value = 0; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } else { opline->extended_value = IS_CONSTANT_UNQUALIFIED; if (CG(current_namespace)) { opline->extended_value |= IS_CONSTANT_IN_NAMESPACE; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 1 TSRMLS_CC); } else { opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } } GET_CACHE_SLOT(opline->op2.constant); break; } } /* }}} */ void zend_do_shell_exec(znode *result, const znode *cmd TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); switch (cmd->op_type) { case IS_CONST: case IS_TMP_VAR: opline->opcode = ZEND_SEND_VAL; break; default: opline->opcode = ZEND_SEND_VAR; break; } SET_NODE(opline->op1, cmd); opline->op2.opline_num = 0; opline->extended_value = ZEND_DO_FCALL; SET_UNUSED(opline->op2); /* FIXME: exception support not added to this op2 */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DO_FCALL; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; LITERAL_STRINGL(opline->op1, estrndup("shell_exec", sizeof("shell_exec")-1), sizeof("shell_exec")-1, 0); CALCULATE_LITERAL_HASH(opline->op1.constant); opline->op1_type = IS_CONST; GET_CACHE_SLOT(opline->op1.constant); opline->extended_value = 1; SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_init_array(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_ARRAY; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; GET_NODE(result, opline->result); if (expr) { SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } } else { SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_array_element(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_ARRAY_ELEMENT; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_static_array_element(znode *result, znode *offset, const znode *expr) /* {{{ */ { zval *element; ALLOC_ZVAL(element); *element = expr->u.constant; if (offset) { switch (offset->u.constant.type & IS_CONSTANT_TYPE_MASK) { case IS_CONSTANT: /* Ugly hack to denote that this value has a constant index */ Z_TYPE_P(element) |= IS_CONSTANT_INDEX; Z_STRVAL(offset->u.constant) = erealloc(Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+1] = Z_TYPE(offset->u.constant); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+2] = 0; zend_symtable_update(result->u.constant.value.ht, Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_STRING: zend_symtable_update(result->u.constant.value.ht, offset->u.constant.value.str.val, offset->u.constant.value.str.len+1, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_NULL: zend_symtable_update(Z_ARRVAL(result->u.constant), "", 1, &element, sizeof(zval *), NULL); break; case IS_LONG: case IS_BOOL: zend_hash_index_update(Z_ARRVAL(result->u.constant), Z_LVAL(offset->u.constant), &element, sizeof(zval *), NULL); break; case IS_DOUBLE: zend_hash_index_update(Z_ARRVAL(result->u.constant), zend_dval_to_lval(Z_DVAL(offset->u.constant)), &element, sizeof(zval *), NULL); break; case IS_CONSTANT_ARRAY: zend_error(E_ERROR, "Illegal offset type"); break; } } else { zend_hash_next_index_insert(Z_ARRVAL(result->u.constant), &element, sizeof(zval *), NULL); } } /* }}} */ void zend_do_add_list_element(const znode *element TSRMLS_DC) /* {{{ */ { list_llist_element lle; if (element) { zend_check_writable_variable(element); lle.var = *element; zend_llist_copy(&lle.dimensions, &CG(dimension_llist)); zend_llist_prepend_element(&CG(list_llist), &lle); } (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_new_list_begin(TSRMLS_D) /* {{{ */ { int current_dimension = 0; zend_llist_add_element(&CG(dimension_llist), &current_dimension); } /* }}} */ void zend_do_new_list_end(TSRMLS_D) /* {{{ */ { zend_llist_remove_tail(&CG(dimension_llist)); (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_list_init(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(list_stack), &CG(list_llist), sizeof(zend_llist)); zend_stack_push(&CG(list_stack), &CG(dimension_llist), sizeof(zend_llist)); zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_do_new_list_begin(TSRMLS_C); } /* }}} */ void zend_do_list_end(znode *result, znode *expr TSRMLS_DC) /* {{{ */ { zend_llist_element *le; zend_llist_element *dimension; zend_op *opline; znode last_container; le = CG(list_llist).head; while (le) { zend_llist *tmp_dimension_llist = &((list_llist_element *)le->data)->dimensions; dimension = tmp_dimension_llist->head; while (dimension) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (dimension == tmp_dimension_llist->head) { /* first */ last_container = *expr; switch (expr->op_type) { case IS_VAR: case IS_CV: opline->opcode = ZEND_FETCH_DIM_R; break; case IS_TMP_VAR: opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; case IS_CONST: /* fetch_dim_tmp_var will handle this bogus fetch */ zval_copy_ctor(&expr->u.constant); opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; } opline->extended_value |= ZEND_FETCH_ADD_LOCK; } else { opline->opcode = ZEND_FETCH_DIM_R; } opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, &last_container); opline->op2_type = IS_CONST; LITERAL_LONG(opline->op2, *((int *) dimension->data)); GET_NODE(&last_container, opline->result); dimension = dimension->next; } ((list_llist_element *) le->data)->value = last_container; zend_llist_destroy(&((list_llist_element *) le->data)->dimensions); zend_do_assign(result, &((list_llist_element *) le->data)->var, &((list_llist_element *) le->data)->value TSRMLS_CC); zend_do_free(result TSRMLS_CC); le = le->next; } zend_llist_destroy(&CG(dimension_llist)); zend_llist_destroy(&CG(list_llist)); *result = *expr; { zend_llist *p; /* restore previous lists */ zend_stack_top(&CG(list_stack), (void **) &p); CG(dimension_llist) = *p; zend_stack_del_top(&CG(list_stack)); zend_stack_top(&CG(list_stack), (void **) &p); CG(list_llist) = *p; zend_stack_del_top(&CG(list_stack)); } } /* }}} */ void zend_init_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = emalloc(sizeof(void*) * 2); list[0] = item; list[1] = NULL; *(void**)result = list; } /* }}} */ void zend_add_to_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = *(void**)result; size_t n = 0; while (list && list[n]) { n++; } list = erealloc(list, sizeof(void*) * (n+2)); list[n] = item; list[n+1] = NULL; *(void**)result = list; } /* }}} */ void zend_do_fetch_static_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zval *tmp; zend_op *opline; znode lval; znode result; ALLOC_ZVAL(tmp); if (static_assignment) { *tmp = static_assignment->u.constant; } else { INIT_ZVAL(*tmp); } if (!CG(active_op_array)->static_variables) { if (CG(active_op_array)->scope) { CG(active_op_array)->scope->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } ALLOC_HASHTABLE(CG(active_op_array)->static_variables); zend_hash_init(CG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } zend_hash_update(CG(active_op_array)->static_variables, varname->u.constant.value.str.val, varname->u.constant.value.str.len+1, &tmp, sizeof(zval *), NULL); if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (fetch_type == ZEND_FETCH_LEXICAL) ? ZEND_FETCH_R : ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_STATIC; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ if (fetch_type == ZEND_FETCH_LEXICAL) { znode dummy; zend_do_begin_variable_parse(TSRMLS_C); zend_do_assign(&dummy, &lval, &result TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } else { zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); } CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_fetch_lexical_variable(znode *varname, zend_bool is_ref TSRMLS_DC) /* {{{ */ { znode value; if (Z_STRLEN(varname->u.constant) == sizeof("this") - 1 && memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this") - 1) == 0) { zend_error(E_COMPILE_ERROR, "Cannot use $this as lexical variable"); return; } value.op_type = IS_CONST; ZVAL_NULL(&value.u.constant); Z_TYPE(value.u.constant) |= is_ref ? IS_LEXICAL_REF : IS_LEXICAL_VAR; Z_SET_REFCOUNT_P(&value.u.constant, 1); Z_UNSET_ISREF_P(&value.u.constant); zend_do_fetch_static_variable(varname, &value, is_ref ? ZEND_FETCH_STATIC : ZEND_FETCH_LEXICAL TSRMLS_CC); } /* }}} */ void zend_do_fetch_global_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zend_op *opline; znode lval; znode result; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = fetch_type; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_cast(znode *result, const znode *expr, int type TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CAST; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } /* }}} */ void zend_do_include_or_eval(int type, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_do_extended_fcall_begin(TSRMLS_C); { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INCLUDE_OR_EVAL; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } zend_do_extended_fcall_end(TSRMLS_C); } /* }}} */ void zend_do_indirect_references(znode *result, const znode *num_references, znode *variable TSRMLS_DC) /* {{{ */ { int i; zend_do_end_variable_parse(variable, BP_VAR_R, 0 TSRMLS_CC); for (i=1; i<num_references->u.constant.value.lval; i++) { fetch_simple_variable_ex(result, variable, 0, ZEND_FETCH_R TSRMLS_CC); *variable = *result; } zend_do_begin_variable_parse(TSRMLS_C); fetch_simple_variable(result, variable, 1 TSRMLS_CC); /* there is a chance someone is accessing $this */ if (CG(active_op_array)->scope && CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1 TSRMLS_CC); } } /* }}} */ void zend_do_unset(const znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_UNSET_VAR; SET_NODE(opline->op1, variable); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); opline->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_UNSET: last_op->opcode = ZEND_UNSET_VAR; SET_UNUSED(last_op->result); break; case ZEND_FETCH_DIM_UNSET: last_op->opcode = ZEND_UNSET_DIM; SET_UNUSED(last_op->result); break; case ZEND_FETCH_OBJ_UNSET: last_op->opcode = ZEND_UNSET_OBJ; SET_UNUSED(last_op->result); break; } } } /* }}} */ void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_do_end_variable_parse(variable, BP_VAR_IS, 0 TSRMLS_CC); zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { last_op = get_next_op(CG(active_op_array) TSRMLS_CC); last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; SET_NODE(last_op->op1, variable); SET_UNUSED(last_op->op2); last_op->result.var = get_temporary_variable(CG(active_op_array)); last_op->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; break; case ZEND_FETCH_DIM_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_DIM_OBJ; break; case ZEND_FETCH_OBJ_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_PROP_OBJ; break; } } last_op->result_type = IS_TMP_VAR; last_op->extended_value |= type; GET_NODE(result, last_op->result); } /* }}} */ void zend_do_instanceof(znode *result, const znode *expr, const znode *class_znode, int type TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline->opcode == ZEND_FETCH_CLASS) { opline->extended_value |= ZEND_FETCH_CLASS_NO_AUTOLOAD; } } if (expr->op_type == IS_CONST) { zend_error(E_COMPILE_ERROR, "instanceof expects an object instance, constant given"); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INSTANCEOF; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_NODE(opline->op2, class_znode); GET_NODE(result, opline->result); } /* }}} */ void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_bool is_variable; zend_bool push_container = 0; zend_op dummy_opline; if (variable) { if (zend_is_function_or_method_call(array)) { is_variable = 0; } else { is_variable = 1; } /* save the location of FETCH_W instruction(s) */ open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); zend_do_end_variable_parse(array, BP_VAR_W, 0 TSRMLS_CC); if (CG(active_op_array)->last > 0 && CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) { /* Only lock the container if we are fetching from a real container and not $this */ if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1_type == IS_VAR) { CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK; push_container = 1; } } } else { is_variable = 0; open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* save the location of FE_RESET */ foreach_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* Preform array reset */ opline->opcode = ZEND_FE_RESET; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, array); SET_UNUSED(opline->op2); opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0; COPY_NODE(dummy_opline.result, opline->result); if (push_container) { COPY_NODE(dummy_opline.op1, CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1); } else { dummy_opline.op1_type = IS_UNUSED; } zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); /* save the location of FE_FETCH */ as_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FE_FETCH; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); COPY_NODE(opline->op1, dummy_opline.result); opline->extended_value = 0; SET_UNUSED(opline->op2); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_OP_DATA; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); } /* }}} */ void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC) /* {{{ */ { zend_op *opline; znode dummy, value_node; zend_bool assign_by_ref=0; opline = &CG(active_op_array)->opcodes[as_token->u.op. opline_num]; if (key->op_type != IS_UNUSED) { znode *tmp; /* switch between the key and value... */ tmp = key; key = value; value = tmp; /* Mark extended_value in case both key and value are being used */ opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; } if ((key->op_type != IS_UNUSED) && (key->EA & ZEND_PARSED_REFERENCE_VARIABLE)) { zend_error(E_COMPILE_ERROR, "Key element cannot be a reference"); } if (value->EA & ZEND_PARSED_REFERENCE_VARIABLE) { assign_by_ref = 1; if (!(opline-1)->extended_value) { zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression"); } /* Mark extended_value for assign-by-reference */ opline->extended_value |= ZEND_FE_FETCH_BYREF; CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; } else { zend_op *foreach_copy; zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.op.opline_num]; zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.op.opline_num]; /* Change "write context" into "read context" */ fetch->extended_value = 0; /* reset ZEND_FE_RESET_VARIABLE */ while (fetch != end) { --fetch; if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } if (fetch->opcode == ZEND_SEPARATE) { MAKE_NOP(fetch); } else { fetch->opcode -= 3; /* FETCH_W -> FETCH_R */ } } /* prevent double SWITCH_FREE */ zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy); foreach_copy->op1_type = IS_UNUSED; } GET_NODE(&value_node, opline->result); if (assign_by_ref) { zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); /* Mark FE_FETCH as IS_VAR as it holds the data directly as a value */ zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC); } else { zend_do_assign(&dummy, value, &value_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } if (key->op_type != IS_UNUSED) { znode key_node; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num+1]; opline->result_type = IS_TMP_VAR; opline->result.opline_num = get_temporary_variable(CG(active_op_array)); GET_NODE(&key_node, opline->result); zend_do_assign(&dummy, key, &key_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_foreach_end(const znode *foreach_token, const znode *as_token TSRMLS_DC) /* {{{ */ { zend_op *container_ptr; zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = as_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_RESET */ CG(active_op_array)->opcodes[as_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_FETCH */ do_end_loop(as_token->u.op.opline_num, 1 TSRMLS_CC); zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr); generate_free_foreach_copy(container_ptr TSRMLS_CC); zend_stack_del_top(&CG(foreach_copy_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_declare_begin(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(declare_stack), &CG(declarables), sizeof(zend_declarables)); } /* }}} */ void zend_do_declare_stmt(znode *var, znode *val TSRMLS_DC) /* {{{ */ { if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "ticks", sizeof("ticks")-1)) { convert_to_long(&val->u.constant); CG(declarables).ticks = val->u.constant; } else if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "encoding", sizeof("encoding")-1)) { if ((Z_TYPE(val->u.constant) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Cannot use constants as encoding"); } /* * Check that the pragma comes before any opcodes. If the compilation * got as far as this, the previous portion of the script must have been * parseable according to the .ini script_encoding setting. We still * want to tell them to put declare() at the top. */ { int num = CG(active_op_array)->last; /* ignore ZEND_EXT_STMT and ZEND_TICKS */ while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Encoding declaration pragma must be the very first statement in the script"); } } if (CG(multibyte)) { zend_encoding *new_encoding, *old_encoding; zend_encoding_filter old_input_filter; CG(encoding_declared) = 1; convert_to_string(&val->u.constant); new_encoding = zend_multibyte_fetch_encoding(val->u.constant.value.str.val TSRMLS_CC); if (!new_encoding) { zend_error(E_COMPILE_WARNING, "Unsupported encoding [%s]", val->u.constant.value.str.val); } else { old_input_filter = LANG_SCNG(input_filter); old_encoding = LANG_SCNG(script_encoding); zend_multibyte_set_filter(new_encoding TSRMLS_CC); /* need to re-scan if input filter changed */ if (old_input_filter != LANG_SCNG(input_filter) || (old_input_filter && new_encoding != old_encoding)) { zend_multibyte_yyinput_again(old_input_filter, old_encoding TSRMLS_CC); } } } else { zend_error(E_COMPILE_WARNING, "declare(encoding=...) ignored because Zend multibyte feature is turned off by settings"); } zval_dtor(&val->u.constant); } else { zend_error(E_COMPILE_WARNING, "Unsupported declare '%s'", var->u.constant.value.str.val); zval_dtor(&val->u.constant); } zval_dtor(&var->u.constant); } /* }}} */ void zend_do_declare_end(const znode *declare_token TSRMLS_DC) /* {{{ */ { zend_declarables *declarables; zend_stack_top(&CG(declare_stack), (void **) &declarables); /* We should restore if there was more than (current - start) - (ticks?1:0) opcodes */ if ((get_next_op_number(CG(active_op_array)) - declare_token->u.op.opline_num) - ((Z_LVAL(CG(declarables).ticks))?1:0)) { CG(declarables) = *declarables; } } /* }}} */ void zend_do_exit(znode *result, const znode *message TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXIT; SET_NODE(opline->op1, message); SET_UNUSED(opline->op2); result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_BOOL; Z_LVAL(result->u.constant) = 1; } /* }}} */ void zend_do_begin_silence(znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BEGIN_SILENCE; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); GET_NODE(strudel_token, opline->result); } /* }}} */ void zend_do_end_silence(const znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_END_SILENCE; SET_NODE(opline->op1, strudel_token); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_jmp_set(const znode *value, znode *jmp_token, znode *colon_token TSRMLS_DC) /* {{{ */ { int op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP_SET; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, value); SET_UNUSED(opline->op2); GET_NODE(colon_token, opline->result); jmp_token->u.op .opline_num = op_number; INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_jmp_set_else(znode *result, const znode *false_value, const znode *jmp_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_QM_ASSIGN; opline->extended_value = 0; SET_NODE(opline->result, colon_token); SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_qm_op(const znode *cond, znode *qm_token TSRMLS_DC) /* {{{ */ { int jmpz_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); SET_UNUSED(opline->op2); opline->op2.opline_num = jmpz_op_number; GET_NODE(qm_token, opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_qm_true(const znode *true_value, znode *qm_token, znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->opcodes[qm_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array))+1; /* jmp over the ZEND_JMP */ opline->opcode = ZEND_QM_ASSIGN; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, true_value); SET_UNUSED(opline->op2); GET_NODE(qm_token, opline->result); colon_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_qm_false(znode *result, const znode *false_value, const znode *qm_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_QM_ASSIGN; SET_NODE(opline->result, qm_token); SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[colon_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, opline->result); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_extended_info(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_STMT; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_begin(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_BEGIN; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_end(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_END; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_ticks(TSRMLS_D) /* {{{ */ { if (Z_LVAL(CG(declarables).ticks)) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_TICKS; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->extended_value = Z_LVAL(CG(declarables).ticks); } } /* }}} */ zend_bool zend_is_auto_global(const char *name, uint name_len TSRMLS_DC) /* {{{ */ { zend_auto_global *auto_global; if (zend_hash_find(CG(auto_globals), name, name_len+1, (void **) &auto_global)==SUCCESS) { if (auto_global->armed) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } return 1; } return 0; } /* }}} */ int zend_register_auto_global(const char *name, uint name_len, zend_bool jit, zend_auto_global_callback auto_global_callback TSRMLS_DC) /* {{{ */ { zend_auto_global auto_global; auto_global.name = zend_new_interned_string((char*)name, name_len + 1, 0 TSRMLS_CC); auto_global.name_len = name_len; auto_global.auto_global_callback = auto_global_callback; auto_global.jit = jit; return zend_hash_add(CG(auto_globals), name, name_len+1, &auto_global, sizeof(zend_auto_global), NULL); } /* }}} */ static int zend_auto_global_init(zend_auto_global *auto_global TSRMLS_DC) /* {{{ */ { if (auto_global->jit) { auto_global->armed = 1; } else if (auto_global->auto_global_callback) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } else { auto_global->armed = 0; } return 0; } /* }}} */ ZEND_API void zend_activate_auto_globals(TSRMLS_D) /* {{{ */ { zend_hash_apply(CG(auto_globals), (apply_func_t) zend_auto_global_init TSRMLS_CC); } /* }}} */ int zendlex(znode *zendlval TSRMLS_DC) /* {{{ */ { int retval; if (CG(increment_lineno)) { CG(zend_lineno)++; CG(increment_lineno) = 0; } again: Z_TYPE(zendlval->u.constant) = IS_LONG; retval = lex_scan(&zendlval->u.constant TSRMLS_CC); switch (retval) { case T_COMMENT: case T_DOC_COMMENT: case T_OPEN_TAG: case T_WHITESPACE: goto again; case T_CLOSE_TAG: if (LANG_SCNG(yy_text)[LANG_SCNG(yy_leng)-1] != '>') { CG(increment_lineno) = 1; } if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { goto again; } retval = ';'; /* implicit ; */ break; case T_OPEN_TAG_WITH_ECHO: retval = T_ECHO; break; case T_END_HEREDOC: efree(Z_STRVAL(zendlval->u.constant)); break; } INIT_PZVAL(&zendlval->u.constant); zendlval->op_type = IS_CONST; return retval; } /* }}} */ ZEND_API void zend_initialize_class_data(zend_class_entry *ce, zend_bool nullify_handlers TSRMLS_DC) /* {{{ */ { zend_bool persistent_hashes = (ce->type == ZEND_INTERNAL_CLASS) ? 1 : 0; dtor_func_t zval_ptr_dtor_func = ((persistent_hashes) ? ZVAL_INTERNAL_PTR_DTOR : ZVAL_PTR_DTOR); ce->refcount = 1; ce->ce_flags = 0; ce->default_properties_table = NULL; ce->default_static_members_table = NULL; zend_hash_init_ex(&ce->properties_info, 0, NULL, (dtor_func_t) (persistent_hashes ? zend_destroy_property_info_internal : zend_destroy_property_info), persistent_hashes, 0); zend_hash_init_ex(&ce->constants_table, 0, NULL, zval_ptr_dtor_func, persistent_hashes, 0); zend_hash_init_ex(&ce->function_table, 0, NULL, ZEND_FUNCTION_DTOR, persistent_hashes, 0); if (ce->type == ZEND_INTERNAL_CLASS) { #ifdef ZTS int n = zend_hash_num_elements(CG(class_table)); if (CG(static_members_table) && n >= CG(last_static_member)) { /* Support for run-time declaration: dl() */ CG(last_static_member) = n+1; CG(static_members_table) = realloc(CG(static_members_table), (n+1)*sizeof(zval**)); CG(static_members_table)[n] = NULL; } ce->static_members_table = (zval**)(zend_intptr_t)n; #else ce->static_members_table = NULL; #endif } else { ce->static_members_table = ce->default_static_members_table; ce->info.user.doc_comment = NULL; ce->info.user.doc_comment_len = 0; } ce->default_properties_count = 0; ce->default_static_members_count = 0; if (nullify_handlers) { ce->constructor = NULL; ce->destructor = NULL; ce->clone = NULL; ce->__get = NULL; ce->__set = NULL; ce->__unset = NULL; ce->__isset = NULL; ce->__call = NULL; ce->__callstatic = NULL; ce->__tostring = NULL; ce->create_object = NULL; ce->get_iterator = NULL; ce->iterator_funcs.funcs = NULL; ce->interface_gets_implemented = NULL; ce->get_static_method = NULL; ce->parent = NULL; ce->num_interfaces = 0; ce->interfaces = NULL; ce->num_traits = 0; ce->traits = NULL; ce->trait_aliases = NULL; ce->trait_precedences = NULL; ce->serialize = NULL; ce->unserialize = NULL; ce->serialize_func = NULL; ce->unserialize_func = NULL; if (ce->type == ZEND_INTERNAL_CLASS) { ce->info.internal.module = NULL; ce->info.internal.builtin_functions = NULL; } } } /* }}} */ int zend_get_class_fetch_type(const char *class_name, uint class_name_len) /* {{{ */ { if ((class_name_len == sizeof("self")-1) && !memcmp(class_name, "self", sizeof("self")-1)) { return ZEND_FETCH_CLASS_SELF; } else if ((class_name_len == sizeof("parent")-1) && !memcmp(class_name, "parent", sizeof("parent")-1)) { return ZEND_FETCH_CLASS_PARENT; } else if ((class_name_len == sizeof("static")-1) && !memcmp(class_name, "static", sizeof("static")-1)) { return ZEND_FETCH_CLASS_STATIC; } else { return ZEND_FETCH_CLASS_DEFAULT; } } /* }}} */ ZEND_API char* zend_get_compiled_variable_name(const zend_op_array *op_array, zend_uint var, int* name_len) /* {{{ */ { if (name_len) { *name_len = op_array->vars[var].name_len; } return op_array->vars[var].name; } /* }}} */ void zend_do_build_namespace_name(znode *result, znode *prefix, znode *name TSRMLS_DC) /* {{{ */ { if (prefix) { *result = *prefix; if (Z_TYPE(result->u.constant) == IS_STRING && Z_STRLEN(result->u.constant) == 0) { /* namespace\ */ if (CG(current_namespace)) { znode tmp; zval_dtor(&result->u.constant); tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(result, NULL, &tmp TSRMLS_CC); } } } else { result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_STRING; Z_STRVAL(result->u.constant) = NULL; Z_STRLEN(result->u.constant) = 0; } /* prefix = result */ zend_do_build_full_name(NULL, result, name, 0 TSRMLS_CC); } /* }}} */ void zend_do_begin_namespace(const znode *name, zend_bool with_bracket TSRMLS_DC) /* {{{ */ { char *lcname; /* handle mixed syntax declaration or nested namespaces */ if (!CG(has_bracketed_namespaces)) { if (CG(current_namespace)) { /* previous namespace declarations were unbracketed */ if (with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } } } else { /* previous namespace declarations were bracketed */ if (!with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } else if (CG(current_namespace) || CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "Namespace declarations cannot be nested"); } } if (((!with_bracket && !CG(current_namespace)) || (with_bracket && !CG(has_bracketed_namespaces))) && CG(active_op_array)->last > 0) { /* ignore ZEND_EXT_STMT and ZEND_TICKS */ int num = CG(active_op_array)->last; while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Namespace declaration statement has to be the very first statement in the script"); } } CG(in_namespace) = 1; if (with_bracket) { CG(has_bracketed_namespaces) = 1; } if (name) { lcname = zend_str_tolower_dup(Z_STRVAL(name->u.constant), Z_STRLEN(name->u.constant)); if (((Z_STRLEN(name->u.constant) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN(name->u.constant) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as namespace name", Z_STRVAL(name->u.constant)); } efree(lcname); if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); } else { ALLOC_ZVAL(CG(current_namespace)); } *CG(current_namespace) = name->u.constant; } else { if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_use(znode *ns_name, znode *new_name, int is_global TSRMLS_DC) /* {{{ */ { char *lcname; zval *name, *ns, tmp; zend_bool warn = 0; zend_class_entry **pce; if (!CG(current_import)) { CG(current_import) = emalloc(sizeof(HashTable)); zend_hash_init(CG(current_import), 0, NULL, ZVAL_PTR_DTOR, 0); } ALLOC_ZVAL(ns); *ns = ns_name->u.constant; if (new_name) { name = &new_name->u.constant; } else { char *p; /* The form "use A\B" is eqivalent to "use A\B as B". So we extract the last part of compound name to use as a new_name */ name = &tmp; p = zend_memrchr(Z_STRVAL_P(ns), '\\', Z_STRLEN_P(ns)); if (p) { ZVAL_STRING(name, p+1, 1); } else { *name = *ns; zval_copy_ctor(name); warn = !is_global && !CG(current_namespace); } } lcname = zend_str_tolower_dup(Z_STRVAL_P(name), Z_STRLEN_P(name)); if (((Z_STRLEN_P(name) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN_P(name) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because '%s' is a special class name", Z_STRVAL_P(ns), Z_STRVAL_P(name), Z_STRVAL_P(name)); } if (CG(current_namespace)) { /* Prefix import name with current namespace name to avoid conflicts with classes */ char *c_ns_name = emalloc(Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) + 1); zend_str_tolower_copy(c_ns_name, Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); c_ns_name[Z_STRLEN_P(CG(current_namespace))] = '\\'; memcpy(c_ns_name+Z_STRLEN_P(CG(current_namespace))+1, lcname, Z_STRLEN_P(name)+1); if (zend_hash_exists(CG(class_table), c_ns_name, Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name)+1)) { char *tmp2 = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) || memcmp(tmp2, c_ns_name, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(tmp2); } efree(c_ns_name); } else if (zend_hash_find(CG(class_table), lcname, Z_STRLEN_P(name)+1, (void**)&pce) == SUCCESS && (*pce)->type == ZEND_USER_CLASS && (*pce)->info.user.filename == CG(compiled_filename)) { char *c_tmp = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(name) || memcmp(c_tmp, lcname, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(c_tmp); } if (zend_hash_add(CG(current_import), lcname, Z_STRLEN_P(name)+1, &ns, sizeof(zval*), NULL) != SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } if (warn) { zend_error(E_WARNING, "The use statement with non-compound name '%s' has no effect", Z_STRVAL_P(name)); } efree(lcname); zval_dtor(name); } /* }}} */ void zend_do_declare_constant(znode *name, znode *value TSRMLS_DC) /* {{{ */ { zend_op *opline; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed as constants"); } if (zend_get_ct_const(&name->u.constant, 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare constant '%s'", Z_STRVAL(name->u.constant)); } if (CG(current_namespace)) { /* Prefix constant name with name of current namespace, lowercased */ znode tmp; tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); Z_STRVAL(tmp.u.constant) = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), Z_STRLEN(tmp.u.constant)); zend_do_build_namespace_name(&tmp, &tmp, name TSRMLS_CC); *name = tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DECLARE_CONST; SET_UNUSED(opline->result); SET_NODE(opline->op1, name); SET_NODE(opline->op2, value); } /* }}} */ void zend_verify_namespace(TSRMLS_D) /* {{{ */ { if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "No code may exist outside of namespace {}"); } } /* }}} */ void zend_do_end_namespace(TSRMLS_D) /* {{{ */ { CG(in_namespace) = 0; if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_end_compilation(TSRMLS_D) /* {{{ */ { CG(has_bracketed_namespaces) = 0; zend_do_end_namespace(TSRMLS_C); } /* }}} */ /* {{{ zend_dirname Returns directory name component of path */ ZEND_API size_t zend_dirname(char *path, size_t len) { register char *end = path + len - 1; unsigned int len_adjust = 0; #ifdef PHP_WIN32 /* Note that on Win32 CWD is per drive (heritage from CP/M). * This means dirname("c:foo") maps to "c:." or "c:" - which means CWD on C: drive. */ if ((2 <= len) && isalpha((int)((unsigned char *)path)[0]) && (':' == path[1])) { /* Skip over the drive spec (if any) so as not to change */ path += 2; len_adjust += 2; if (2 == len) { /* Return "c:" on Win32 for dirname("c:"). * It would be more consistent to return "c:." * but that would require making the string *longer*. */ return len; } } #elif defined(NETWARE) /* * Find the first occurence of : from the left * move the path pointer to the position just after : * increment the len_adjust to the length of path till colon character(inclusive) * If there is no character beyond : simple return len */ char *colonpos = NULL; colonpos = strchr(path, ':'); if (colonpos != NULL) { len_adjust = ((colonpos - path) + 1); path += len_adjust; if (len_adjust == len) { return len; } } #endif if (len == 0) { /* Illegal use of this function */ return 0; } /* Strip trailing slashes */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { /* The path only contained slashes */ path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } /* Strip filename */ while (end >= path && !IS_SLASH_P(end)) { end--; } if (end < path) { /* No slash found, therefore return '.' */ #ifdef NETWARE if (len_adjust == 0) { path[0] = '.'; path[1] = '\0'; return 1; /* only one character */ } else { path[0] = '\0'; return len_adjust; } #else path[0] = '.'; path[1] = '\0'; return 1 + len_adjust; #endif } /* Strip slashes which came before the file name */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } *(end+1) = '\0'; return (size_t)(end + 1 - path) + len_adjust; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-05-13-db0c957f02-8ba00176f1.c
manybugs_data_54
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2012 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | Andrei Zmievski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "zend.h" #include "zend_execute.h" #include "zend_API.h" #include "zend_modules.h" #include "zend_constants.h" #include "zend_exceptions.h" #include "zend_closures.h" #ifdef HAVE_STDARG_H #include <stdarg.h> #endif /* these variables are true statics/globals, and have to be mutex'ed on every access */ static int module_count=0; ZEND_API HashTable module_registry; static zend_module_entry **module_request_startup_handlers; static zend_module_entry **module_request_shutdown_handlers; static zend_module_entry **module_post_deactivate_handlers; static zend_class_entry **class_cleanup_handlers; /* this function doesn't check for too many parameters */ ZEND_API int zend_get_parameters(int ht, int param_count, ...) /* {{{ */ { void **p; int arg_count; va_list ptr; zval **param, *param_ptr; TSRMLS_FETCH(); p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } va_start(ptr, param_count); while (param_count-->0) { param = va_arg(ptr, zval **); param_ptr = *(p-arg_count); if (!PZVAL_IS_REF(param_ptr) && Z_REFCOUNT_P(param_ptr) > 1) { zval *new_tmp; ALLOC_ZVAL(new_tmp); *new_tmp = *param_ptr; zval_copy_ctor(new_tmp); INIT_PZVAL(new_tmp); param_ptr = new_tmp; Z_DELREF_P((zval *) *(p-arg_count)); *(p-arg_count) = param_ptr; } *param = param_ptr; arg_count--; } va_end(ptr); return SUCCESS; } /* }}} */ ZEND_API int _zend_get_parameters_array(int ht, int param_count, zval **argument_array TSRMLS_DC) /* {{{ */ { void **p; int arg_count; zval *param_ptr; p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } while (param_count-->0) { param_ptr = *(p-arg_count); if (!PZVAL_IS_REF(param_ptr) && Z_REFCOUNT_P(param_ptr) > 1) { zval *new_tmp; ALLOC_ZVAL(new_tmp); *new_tmp = *param_ptr; zval_copy_ctor(new_tmp); INIT_PZVAL(new_tmp); param_ptr = new_tmp; Z_DELREF_P((zval *) *(p-arg_count)); *(p-arg_count) = param_ptr; } *(argument_array++) = param_ptr; arg_count--; } return SUCCESS; } /* }}} */ /* Zend-optimized Extended functions */ /* this function doesn't check for too many parameters */ ZEND_API int zend_get_parameters_ex(int param_count, ...) /* {{{ */ { void **p; int arg_count; va_list ptr; zval ***param; TSRMLS_FETCH(); p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } va_start(ptr, param_count); while (param_count-->0) { param = va_arg(ptr, zval ***); *param = (zval **) p-(arg_count--); } va_end(ptr); return SUCCESS; } /* }}} */ ZEND_API int _zend_get_parameters_array_ex(int param_count, zval ***argument_array TSRMLS_DC) /* {{{ */ { void **p; int arg_count; p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } while (param_count-->0) { zval **value = (zval**)(p-arg_count); *(argument_array++) = value; arg_count--; } return SUCCESS; } /* }}} */ ZEND_API int zend_copy_parameters_array(int param_count, zval *argument_array TSRMLS_DC) /* {{{ */ { void **p; int arg_count; p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } while (param_count-->0) { zval **param = (zval **) p-(arg_count--); zval_add_ref(param); add_next_index_zval(argument_array, *param); } return SUCCESS; } /* }}} */ ZEND_API void zend_wrong_param_count(TSRMLS_D) /* {{{ */ { const char *space; const char *class_name = get_active_class_name(&space TSRMLS_CC); zend_error(E_WARNING, "Wrong parameter count for %s%s%s()", class_name, space, get_active_function_name(TSRMLS_C)); } /* }}} */ /* Argument parsing API -- andrei */ ZEND_API char *zend_get_type_by_const(int type) /* {{{ */ { switch(type) { case IS_BOOL: return "boolean"; case IS_LONG: return "integer"; case IS_DOUBLE: return "double"; case IS_STRING: return "string"; case IS_OBJECT: return "object"; case IS_RESOURCE: return "resource"; case IS_NULL: return "null"; case IS_CALLABLE: return "callable"; case IS_ARRAY: return "array"; default: return "unknown"; } } /* }}} */ ZEND_API char *zend_zval_type_name(const zval *arg) /* {{{ */ { return zend_get_type_by_const(Z_TYPE_P(arg)); } /* }}} */ ZEND_API zend_class_entry *zend_get_class_entry(const zval *zobject TSRMLS_DC) /* {{{ */ { if (Z_OBJ_HT_P(zobject)->get_class_entry) { return Z_OBJ_HT_P(zobject)->get_class_entry(zobject TSRMLS_CC); } else { zend_error(E_ERROR, "Class entry requested for an object without PHP class"); return NULL; } } /* }}} */ /* returns 1 if you need to copy result, 0 if it's already a copy */ ZEND_API int zend_get_object_classname(const zval *object, const char **class_name, zend_uint *class_name_len TSRMLS_DC) /* {{{ */ { if (Z_OBJ_HT_P(object)->get_class_name == NULL || Z_OBJ_HT_P(object)->get_class_name(object, class_name, class_name_len, 0 TSRMLS_CC) != SUCCESS) { zend_class_entry *ce = Z_OBJCE_P(object); *class_name = ce->name; *class_name_len = ce->name_length; return 1; } return 0; } /* }}} */ static int parse_arg_object_to_string(zval **arg, char **p, int *pl, int type TSRMLS_DC) /* {{{ */ { if (Z_OBJ_HANDLER_PP(arg, cast_object)) { SEPARATE_ZVAL_IF_NOT_REF(arg); if (Z_OBJ_HANDLER_PP(arg, cast_object)(*arg, *arg, type TSRMLS_CC) == SUCCESS) { *pl = Z_STRLEN_PP(arg); *p = Z_STRVAL_PP(arg); return SUCCESS; } } /* Standard PHP objects */ if (Z_OBJ_HT_PP(arg) == &std_object_handlers || !Z_OBJ_HANDLER_PP(arg, cast_object)) { SEPARATE_ZVAL_IF_NOT_REF(arg); if (zend_std_cast_object_tostring(*arg, *arg, type TSRMLS_CC) == SUCCESS) { *pl = Z_STRLEN_PP(arg); *p = Z_STRVAL_PP(arg); return SUCCESS; } } if (!Z_OBJ_HANDLER_PP(arg, cast_object) && Z_OBJ_HANDLER_PP(arg, get)) { int use_copy; zval *z = Z_OBJ_HANDLER_PP(arg, get)(*arg TSRMLS_CC); Z_ADDREF_P(z); if(Z_TYPE_P(z) != IS_OBJECT) { zval_dtor(*arg); Z_TYPE_P(*arg) = IS_NULL; zend_make_printable_zval(z, *arg, &use_copy); if (!use_copy) { ZVAL_ZVAL(*arg, z, 1, 1); } *pl = Z_STRLEN_PP(arg); *p = Z_STRVAL_PP(arg); return SUCCESS; } zval_ptr_dtor(&z); } return FAILURE; } /* }}} */ static const char *zend_parse_arg_impl(int arg_num, zval **arg, va_list *va, const char **spec, char **error, int *severity TSRMLS_DC) /* {{{ */ { const char *spec_walk = *spec; char c = *spec_walk++; int return_null = 0; /* scan through modifiers */ while (1) { if (*spec_walk == '/') { SEPARATE_ZVAL_IF_NOT_REF(arg); } else if (*spec_walk == '!') { if (Z_TYPE_PP(arg) == IS_NULL) { return_null = 1; } } else { break; } spec_walk++; } switch (c) { case 'l': case 'L': { long *p = va_arg(*va, long *); switch (Z_TYPE_PP(arg)) { case IS_STRING: { double d; int type; if ((type = is_numeric_string(Z_STRVAL_PP(arg), Z_STRLEN_PP(arg), p, &d, -1)) == 0) { return "long"; } else if (type == IS_DOUBLE) { if (c == 'L') { if (d > LONG_MAX) { *p = LONG_MAX; break; } else if (d < LONG_MIN) { *p = LONG_MIN; break; } } *p = zend_dval_to_lval(d); } } break; case IS_DOUBLE: if (c == 'L') { if (Z_DVAL_PP(arg) > LONG_MAX) { *p = LONG_MAX; break; } else if (Z_DVAL_PP(arg) < LONG_MIN) { *p = LONG_MIN; break; } } case IS_NULL: case IS_LONG: case IS_BOOL: convert_to_long_ex(arg); *p = Z_LVAL_PP(arg); break; case IS_ARRAY: case IS_OBJECT: case IS_RESOURCE: default: return "long"; } } break; case 'd': { double *p = va_arg(*va, double *); switch (Z_TYPE_PP(arg)) { case IS_STRING: { long l; int type; if ((type = is_numeric_string(Z_STRVAL_PP(arg), Z_STRLEN_PP(arg), &l, p, -1)) == 0) { return "double"; } else if (type == IS_LONG) { *p = (double) l; } } break; case IS_NULL: case IS_LONG: case IS_DOUBLE: case IS_BOOL: convert_to_double_ex(arg); *p = Z_DVAL_PP(arg); break; case IS_ARRAY: case IS_OBJECT: case IS_RESOURCE: default: return "double"; } } break; case 'p': case 's': { char **p = va_arg(*va, char **); int *pl = va_arg(*va, int *); switch (Z_TYPE_PP(arg)) { case IS_NULL: if (return_null) { *p = NULL; *pl = 0; break; } /* break omitted intentionally */ case IS_STRING: case IS_LONG: case IS_DOUBLE: case IS_BOOL: convert_to_string_ex(arg); if (UNEXPECTED(Z_ISREF_PP(arg) != 0)) { /* it's dangerous to return pointers to string buffer of referenced variable, because it can be clobbered throug magic callbacks */ SEPARATE_ZVAL(arg); } *p = Z_STRVAL_PP(arg); *pl = Z_STRLEN_PP(arg); if (c == 'p' && CHECK_ZVAL_NULL_PATH(*arg)) { return "a valid path"; } break; case IS_OBJECT: if (parse_arg_object_to_string(arg, p, pl, IS_STRING TSRMLS_CC) == SUCCESS) { if (c == 'p' && CHECK_ZVAL_NULL_PATH(*arg)) { return "a valid path"; } break; } case IS_ARRAY: case IS_RESOURCE: default: return c == 's' ? "string" : "a valid path"; } } break; case 'b': { zend_bool *p = va_arg(*va, zend_bool *); switch (Z_TYPE_PP(arg)) { case IS_NULL: case IS_STRING: case IS_LONG: case IS_DOUBLE: case IS_BOOL: convert_to_boolean_ex(arg); *p = Z_BVAL_PP(arg); break; case IS_ARRAY: case IS_OBJECT: case IS_RESOURCE: default: return "boolean"; } } break; case 'r': { zval **p = va_arg(*va, zval **); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_RESOURCE) { *p = *arg; } else { return "resource"; } } break; case 'A': case 'a': { zval **p = va_arg(*va, zval **); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_ARRAY || (c == 'A' && Z_TYPE_PP(arg) == IS_OBJECT)) { *p = *arg; } else { return "array"; } } break; case 'H': case 'h': { HashTable **p = va_arg(*va, HashTable **); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_ARRAY) { *p = Z_ARRVAL_PP(arg); } else if(c == 'H' && Z_TYPE_PP(arg) == IS_OBJECT) { *p = HASH_OF(*arg); if(*p == NULL) { return "array"; } } else { return "array"; } } break; case 'o': { zval **p = va_arg(*va, zval **); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_OBJECT) { *p = *arg; } else { return "object"; } } break; case 'O': { zval **p = va_arg(*va, zval **); zend_class_entry *ce = va_arg(*va, zend_class_entry *); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_OBJECT && (!ce || instanceof_function(Z_OBJCE_PP(arg), ce TSRMLS_CC))) { *p = *arg; } else { if (ce) { return ce->name; } else { return "object"; } } } break; case 'C': { zend_class_entry **lookup, **pce = va_arg(*va, zend_class_entry **); zend_class_entry *ce_base = *pce; if (return_null) { *pce = NULL; break; } convert_to_string_ex(arg); if (zend_lookup_class(Z_STRVAL_PP(arg), Z_STRLEN_PP(arg), &lookup TSRMLS_CC) == FAILURE) { *pce = NULL; } else { *pce = *lookup; } if (ce_base) { if ((!*pce || !instanceof_function(*pce, ce_base TSRMLS_CC))) { zend_spprintf(error, 0, "to be a class name derived from %s, '%s' given", ce_base->name, Z_STRVAL_PP(arg)); *pce = NULL; return ""; } } if (!*pce) { zend_spprintf(error, 0, "to be a valid class name, '%s' given", Z_STRVAL_PP(arg)); return ""; } break; } break; case 'f': { zend_fcall_info *fci = va_arg(*va, zend_fcall_info *); zend_fcall_info_cache *fcc = va_arg(*va, zend_fcall_info_cache *); char *is_callable_error = NULL; if (return_null) { fci->size = 0; fcc->initialized = 0; break; } if (zend_fcall_info_init(*arg, 0, fci, fcc, NULL, &is_callable_error TSRMLS_CC) == SUCCESS) { if (is_callable_error) { *severity = E_STRICT; zend_spprintf(error, 0, "to be a valid callback, %s", is_callable_error); efree(is_callable_error); *spec = spec_walk; return ""; } break; } else { if (is_callable_error) { *severity = E_WARNING; zend_spprintf(error, 0, "to be a valid callback, %s", is_callable_error); efree(is_callable_error); return ""; } else { return "valid callback"; } } } case 'z': { zval **p = va_arg(*va, zval **); if (return_null) { *p = NULL; } else { *p = *arg; } } break; case 'Z': { zval ***p = va_arg(*va, zval ***); if (return_null) { *p = NULL; } else { *p = arg; } } break; default: return "unknown"; } *spec = spec_walk; return NULL; } /* }}} */ static int zend_parse_arg(int arg_num, zval **arg, va_list *va, const char **spec, int quiet TSRMLS_DC) /* {{{ */ { const char *expected_type = NULL; char *error = NULL; int severity = E_WARNING; expected_type = zend_parse_arg_impl(arg_num, arg, va, spec, &error, &severity TSRMLS_CC); if (expected_type) { if (!quiet && (*expected_type || error)) { const char *space; const char *class_name = get_active_class_name(&space TSRMLS_CC); if (error) { zend_error(severity, "%s%s%s() expects parameter %d %s", class_name, space, get_active_function_name(TSRMLS_C), arg_num, error); efree(error); } else { zend_error(severity, "%s%s%s() expects parameter %d to be %s, %s given", class_name, space, get_active_function_name(TSRMLS_C), arg_num, expected_type, zend_zval_type_name(*arg)); } } if (severity != E_STRICT) { return FAILURE; } } return SUCCESS; } /* }}} */ static int zend_parse_va_args(int num_args, const char *type_spec, va_list *va, int flags TSRMLS_DC) /* {{{ */ { const char *spec_walk; int c, i; int min_num_args = -1; int max_num_args = 0; int post_varargs = 0; zval **arg; int arg_count; int quiet = flags & ZEND_PARSE_PARAMS_QUIET; zend_bool have_varargs = 0; zval ****varargs = NULL; int *n_varargs = NULL; for (spec_walk = type_spec; *spec_walk; spec_walk++) { c = *spec_walk; switch (c) { case 'l': case 'd': case 's': case 'b': case 'r': case 'a': case 'o': case 'O': case 'z': case 'Z': case 'C': case 'h': case 'f': case 'A': case 'H': case 'p': max_num_args++; break; case '|': min_num_args = max_num_args; break; case '/': case '!': /* Pass */ break; case '*': case '+': if (have_varargs) { if (!quiet) { zend_function *active_function = EG(current_execute_data)->function_state.function; const char *class_name = active_function->common.scope ? active_function->common.scope->name : ""; zend_error(E_WARNING, "%s%s%s(): only one varargs specifier (* or +) is permitted", class_name, class_name[0] ? "::" : "", active_function->common.function_name); } return FAILURE; } have_varargs = 1; /* we expect at least one parameter in varargs */ if (c == '+') { max_num_args++; } /* mark the beginning of varargs */ post_varargs = max_num_args; break; default: if (!quiet) { zend_function *active_function = EG(current_execute_data)->function_state.function; const char *class_name = active_function->common.scope ? active_function->common.scope->name : ""; zend_error(E_WARNING, "%s%s%s(): bad type specifier while parsing parameters", class_name, class_name[0] ? "::" : "", active_function->common.function_name); } return FAILURE; } } if (min_num_args < 0) { min_num_args = max_num_args; } if (have_varargs) { /* calculate how many required args are at the end of the specifier list */ post_varargs = max_num_args - post_varargs; max_num_args = -1; } if (num_args < min_num_args || (num_args > max_num_args && max_num_args > 0)) { if (!quiet) { zend_function *active_function = EG(current_execute_data)->function_state.function; const char *class_name = active_function->common.scope ? active_function->common.scope->name : ""; zend_error(E_WARNING, "%s%s%s() expects %s %d parameter%s, %d given", class_name, class_name[0] ? "::" : "", active_function->common.function_name, min_num_args == max_num_args ? "exactly" : num_args < min_num_args ? "at least" : "at most", num_args < min_num_args ? min_num_args : max_num_args, (num_args < min_num_args ? min_num_args : max_num_args) == 1 ? "" : "s", num_args); } return FAILURE; } arg_count = (int)(zend_uintptr_t) *(zend_vm_stack_top(TSRMLS_C) - 1); if (num_args > arg_count) { zend_error(E_WARNING, "%s(): could not obtain parameters for parsing", get_active_function_name(TSRMLS_C)); return FAILURE; } i = 0; while (num_args-- > 0) { if (*type_spec == '|') { type_spec++; } if (*type_spec == '*' || *type_spec == '+') { int num_varargs = num_args + 1 - post_varargs; /* eat up the passed in storage even if it won't be filled in with varargs */ varargs = va_arg(*va, zval ****); n_varargs = va_arg(*va, int *); type_spec++; if (num_varargs > 0) { int iv = 0; zval **p = (zval **) (zend_vm_stack_top(TSRMLS_C) - 1 - (arg_count - i)); *n_varargs = num_varargs; /* allocate space for array and store args */ *varargs = safe_emalloc(num_varargs, sizeof(zval **), 0); while (num_varargs-- > 0) { (*varargs)[iv++] = p++; } /* adjust how many args we have left and restart loop */ num_args = num_args + 1 - iv; i += iv; continue; } else { *varargs = NULL; *n_varargs = 0; } } arg = (zval **) (zend_vm_stack_top(TSRMLS_C) - 1 - (arg_count-i)); if (zend_parse_arg(i+1, arg, va, &type_spec, quiet TSRMLS_CC) == FAILURE) { /* clean up varargs array if it was used */ if (varargs && *varargs) { efree(*varargs); *varargs = NULL; } return FAILURE; } i++; } return SUCCESS; } /* }}} */ #define RETURN_IF_ZERO_ARGS(num_args, type_spec, quiet) { \ int __num_args = (num_args); \ \ if (0 == (type_spec)[0] && 0 != __num_args && !(quiet)) { \ const char *__space; \ const char * __class_name = get_active_class_name(&__space TSRMLS_CC); \ zend_error(E_WARNING, "%s%s%s() expects exactly 0 parameters, %d given", \ __class_name, __space, \ get_active_function_name(TSRMLS_C), __num_args); \ return FAILURE; \ }\ } ZEND_API int zend_parse_parameters_ex(int flags, int num_args TSRMLS_DC, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; RETURN_IF_ZERO_ARGS(num_args, type_spec, flags & ZEND_PARSE_PARAMS_QUIET); va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, flags TSRMLS_CC); va_end(va); return retval; } /* }}} */ ZEND_API int zend_parse_parameters(int num_args TSRMLS_DC, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; RETURN_IF_ZERO_ARGS(num_args, type_spec, 0); va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, 0 TSRMLS_CC); va_end(va); return retval; } /* }}} */ ZEND_API int zend_parse_method_parameters(int num_args TSRMLS_DC, zval *this_ptr, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; const char *p = type_spec; zval **object; zend_class_entry *ce; if (!this_ptr) { RETURN_IF_ZERO_ARGS(num_args, p, 0); va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, 0 TSRMLS_CC); va_end(va); } else { p++; RETURN_IF_ZERO_ARGS(num_args, p, 0); va_start(va, type_spec); object = va_arg(va, zval **); ce = va_arg(va, zend_class_entry *); *object = this_ptr; if (ce && !instanceof_function(Z_OBJCE_P(this_ptr), ce TSRMLS_CC)) { zend_error(E_CORE_ERROR, "%s::%s() must be derived from %s::%s", ce->name, get_active_function_name(TSRMLS_C), Z_OBJCE_P(this_ptr)->name, get_active_function_name(TSRMLS_C)); } retval = zend_parse_va_args(num_args, p, &va, 0 TSRMLS_CC); va_end(va); } return retval; } /* }}} */ ZEND_API int zend_parse_method_parameters_ex(int flags, int num_args TSRMLS_DC, zval *this_ptr, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; const char *p = type_spec; zval **object; zend_class_entry *ce; int quiet = flags & ZEND_PARSE_PARAMS_QUIET; if (!this_ptr) { RETURN_IF_ZERO_ARGS(num_args, p, quiet); va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, flags TSRMLS_CC); va_end(va); } else { p++; RETURN_IF_ZERO_ARGS(num_args, p, quiet); va_start(va, type_spec); object = va_arg(va, zval **); ce = va_arg(va, zend_class_entry *); *object = this_ptr; if (ce && !instanceof_function(Z_OBJCE_P(this_ptr), ce TSRMLS_CC)) { if (!quiet) { zend_error(E_CORE_ERROR, "%s::%s() must be derived from %s::%s", ce->name, get_active_function_name(TSRMLS_C), Z_OBJCE_P(this_ptr)->name, get_active_function_name(TSRMLS_C)); } va_end(va); return FAILURE; } retval = zend_parse_va_args(num_args, p, &va, flags TSRMLS_CC); va_end(va); } return retval; } /* }}} */ /* Argument parsing API -- andrei */ ZEND_API int _array_init(zval *arg, uint size ZEND_FILE_LINE_DC) /* {{{ */ { ALLOC_HASHTABLE_REL(Z_ARRVAL_P(arg)); _zend_hash_init(Z_ARRVAL_P(arg), size, NULL, ZVAL_PTR_DTOR, 0 ZEND_FILE_LINE_RELAY_CC); Z_TYPE_P(arg) = IS_ARRAY; return SUCCESS; } /* }}} */ static int zend_merge_property(zval **value TSRMLS_DC, int num_args, va_list args, const zend_hash_key *hash_key) /* {{{ */ { /* which name should a numeric property have ? */ if (hash_key->nKeyLength) { zval *obj = va_arg(args, zval *); zend_object_handlers *obj_ht = va_arg(args, zend_object_handlers *); zval *member; MAKE_STD_ZVAL(member); ZVAL_STRINGL(member, hash_key->arKey, hash_key->nKeyLength-1, 1); obj_ht->write_property(obj, member, *value, 0 TSRMLS_CC); zval_ptr_dtor(&member); } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* This function should be called after the constructor has been called * because it may call __set from the uninitialized object otherwise. */ ZEND_API void zend_merge_properties(zval *obj, HashTable *properties, int destroy_ht TSRMLS_DC) /* {{{ */ { const zend_object_handlers *obj_ht = Z_OBJ_HT_P(obj); zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE_P(obj); zend_hash_apply_with_arguments(properties TSRMLS_CC, (apply_func_args_t)zend_merge_property, 2, obj, obj_ht); EG(scope) = old_scope; if (destroy_ht) { zend_hash_destroy(properties); FREE_HASHTABLE(properties); } } /* }}} */ ZEND_API void zend_update_class_constants(zend_class_entry *class_type TSRMLS_DC) /* {{{ */ { if ((class_type->ce_flags & ZEND_ACC_CONSTANTS_UPDATED) == 0 || (!CE_STATIC_MEMBERS(class_type) && class_type->default_static_members_count)) { zend_class_entry **scope = EG(in_execution)?&EG(scope):&CG(active_class_entry); zend_class_entry *old_scope = *scope; int i; *scope = class_type; zend_hash_apply_with_argument(&class_type->constants_table, (apply_func_arg_t) zval_update_constant, (void*)1 TSRMLS_CC); for (i = 0; i < class_type->default_properties_count; i++) { if (class_type->default_properties_table[i]) { zval_update_constant(&class_type->default_properties_table[i], (void**)1 TSRMLS_CC); } } if (!CE_STATIC_MEMBERS(class_type) && class_type->default_static_members_count) { zval **p; if (class_type->parent) { zend_update_class_constants(class_type->parent TSRMLS_CC); } #if ZTS CG(static_members_table)[(zend_intptr_t)(class_type->static_members_table)] = emalloc(sizeof(zval*) * class_type->default_static_members_count); #else class_type->static_members_table = emalloc(sizeof(zval*) * class_type->default_static_members_count); #endif for (i = 0; i < class_type->default_static_members_count; i++) { p = &class_type->default_static_members_table[i]; if (Z_ISREF_PP(p) && class_type->parent && i < class_type->parent->default_static_members_count && *p == class_type->parent->default_static_members_table[i] && CE_STATIC_MEMBERS(class_type->parent)[i] ) { zval *q = CE_STATIC_MEMBERS(class_type->parent)[i]; Z_ADDREF_P(q); Z_SET_ISREF_P(q); CE_STATIC_MEMBERS(class_type)[i] = q; } else { zval *r; ALLOC_ZVAL(r); *r = **p; INIT_PZVAL(r); zval_copy_ctor(r); CE_STATIC_MEMBERS(class_type)[i] = r; } } } for (i = 0; i < class_type->default_static_members_count; i++) { zval_update_constant(&CE_STATIC_MEMBERS(class_type)[i], (void**)1 TSRMLS_CC); } *scope = old_scope; class_type->ce_flags |= ZEND_ACC_CONSTANTS_UPDATED; } } /* }}} */ ZEND_API void object_properties_init(zend_object *object, zend_class_entry *class_type) /* {{{ */ { int i; if (class_type->default_properties_count) { object->properties_table = emalloc(sizeof(zval*) * class_type->default_properties_count); for (i = 0; i < class_type->default_properties_count; i++) { object->properties_table[i] = class_type->default_properties_table[i]; if (class_type->default_properties_table[i]) { Z_ADDREF_P(object->properties_table[i]); } } object->properties = NULL; } } /* }}} */ /* This function requires 'properties' to contain all props declared in the * class and all props being public. If only a subset is given or the class * has protected members then you need to merge the properties seperately by * calling zend_merge_properties(). */ ZEND_API int _object_and_properties_init(zval *arg, zend_class_entry *class_type, HashTable *properties ZEND_FILE_LINE_DC TSRMLS_DC) /* {{{ */ { zend_object *object; if (class_type->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLICIT_ABSTRACT_CLASS|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) { char *what = (class_type->ce_flags & ZEND_ACC_INTERFACE) ? "interface" :((class_type->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) ? "trait" : "abstract class"; zend_error(E_ERROR, "Cannot instantiate %s %s", what, class_type->name); } zend_update_class_constants(class_type TSRMLS_CC); Z_TYPE_P(arg) = IS_OBJECT; if (class_type->create_object == NULL) { Z_OBJVAL_P(arg) = zend_objects_new(&object, class_type TSRMLS_CC); if (properties) { object->properties = properties; object->properties_table = NULL; } else { object_properties_init(object, class_type); } } else { Z_OBJVAL_P(arg) = class_type->create_object(class_type TSRMLS_CC); } return SUCCESS; } /* }}} */ ZEND_API int _object_init_ex(zval *arg, zend_class_entry *class_type ZEND_FILE_LINE_DC TSRMLS_DC) /* {{{ */ { return _object_and_properties_init(arg, class_type, 0 ZEND_FILE_LINE_RELAY_CC TSRMLS_CC); } /* }}} */ ZEND_API int _object_init(zval *arg ZEND_FILE_LINE_DC TSRMLS_DC) /* {{{ */ { return _object_init_ex(arg, zend_standard_class_def ZEND_FILE_LINE_RELAY_CC TSRMLS_CC); } /* }}} */ ZEND_API int add_assoc_function(zval *arg, const char *key, void (*function_ptr)(INTERNAL_FUNCTION_PARAMETERS)) /* {{{ */ { zend_error(E_WARNING, "add_assoc_function() is no longer supported"); return FAILURE; } /* }}} */ ZEND_API int add_assoc_long_ex(zval *arg, const char *key, uint key_len, long n) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, n); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_null_ex(zval *arg, const char *key, uint key_len) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_NULL(tmp); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_bool_ex(zval *arg, const char *key, uint key_len, int b) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_BOOL(tmp, b); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_resource_ex(zval *arg, const char *key, uint key_len, int r) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_RESOURCE(tmp, r); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_double_ex(zval *arg, const char *key, uint key_len, double d) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_string_ex(zval *arg, const char *key, uint key_len, char *str, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_stringl_ex(zval *arg, const char *key, uint key_len, char *str, uint length, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_zval_ex(zval *arg, const char *key, uint key_len, zval *value) /* {{{ */ { return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &value, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_long(zval *arg, ulong index, long n) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, n); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_null(zval *arg, ulong index) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_NULL(tmp); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_bool(zval *arg, ulong index, int b) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_BOOL(tmp, b); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_resource(zval *arg, ulong index, int r) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_RESOURCE(tmp, r); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_double(zval *arg, ulong index, double d) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_string(zval *arg, ulong index, const char *str, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_stringl(zval *arg, ulong index, const char *str, uint length, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_zval(zval *arg, ulong index, zval *value) /* {{{ */ { return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &value, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_long(zval *arg, long n) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, n); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_null(zval *arg) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_NULL(tmp); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_bool(zval *arg, int b) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_BOOL(tmp, b); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_resource(zval *arg, int r) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_RESOURCE(tmp, r); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_double(zval *arg, double d) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_string(zval *arg, const char *str, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_stringl(zval *arg, const char *str, uint length, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_zval(zval *arg, zval *value) /* {{{ */ { return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &value, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_get_assoc_string_ex(zval *arg, const char *key, uint key_len, const char *str, void **dest, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_assoc_stringl_ex(zval *arg, const char *key, uint key_len, const char *str, uint length, void **dest, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_index_long(zval *arg, ulong index, long l, void **dest) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, l); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_index_double(zval *arg, ulong index, double d, void **dest) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_index_string(zval *arg, ulong index, const char *str, void **dest, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_index_stringl(zval *arg, ulong index, const char *str, uint length, void **dest, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_property_long_ex(zval *arg, const char *key, uint key_len, long n TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, n); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_bool_ex(zval *arg, const char *key, uint key_len, int b TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_BOOL(tmp, b); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_null_ex(zval *arg, const char *key, uint key_len TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_NULL(tmp); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_resource_ex(zval *arg, const char *key, uint key_len, long n TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_RESOURCE(tmp, n); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_double_ex(zval *arg, const char *key, uint key_len, double d TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_string_ex(zval *arg, const char *key, uint key_len, const char *str, int duplicate TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_stringl_ex(zval *arg, const char *key, uint key_len, const char *str, uint length, int duplicate TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_zval_ex(zval *arg, const char *key, uint key_len, zval *value TSRMLS_DC) /* {{{ */ { zval *z_key; MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, value, 0 TSRMLS_CC); zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int zend_startup_module_ex(zend_module_entry *module TSRMLS_DC) /* {{{ */ { int name_len; char *lcname; if (module->module_started) { return SUCCESS; } module->module_started = 1; /* Check module dependencies */ if (module->deps) { const zend_module_dep *dep = module->deps; while (dep->name) { if (dep->type == MODULE_DEP_REQUIRED) { zend_module_entry *req_mod; name_len = strlen(dep->name); lcname = zend_str_tolower_dup(dep->name, name_len); if (zend_hash_find(&module_registry, lcname, name_len+1, (void**)&req_mod) == FAILURE || !req_mod->module_started) { efree(lcname); /* TODO: Check version relationship */ zend_error(E_CORE_WARNING, "Cannot load module '%s' because required module '%s' is not loaded", module->name, dep->name); module->module_started = 0; return FAILURE; } efree(lcname); } ++dep; } } /* Initialize module globals */ if (module->globals_size) { #ifdef ZTS ts_allocate_id(module->globals_id_ptr, module->globals_size, (ts_allocate_ctor) module->globals_ctor, (ts_allocate_dtor) module->globals_dtor); #else if (module->globals_ctor) { module->globals_ctor(module->globals_ptr TSRMLS_CC); } #endif } if (module->module_startup_func) { EG(current_module) = module; if (module->module_startup_func(module->type, module->module_number TSRMLS_CC)==FAILURE) { zend_error(E_CORE_ERROR,"Unable to start %s module", module->name); EG(current_module) = NULL; return FAILURE; } EG(current_module) = NULL; } return SUCCESS; } /* }}} */ static void zend_sort_modules(void *base, size_t count, size_t siz, compare_func_t compare TSRMLS_DC) /* {{{ */ { Bucket **b1 = base; Bucket **b2; Bucket **end = b1 + count; Bucket *tmp; zend_module_entry *m, *r; while (b1 < end) { try_again: m = (zend_module_entry*)(*b1)->pData; if (!m->module_started && m->deps) { const zend_module_dep *dep = m->deps; while (dep->name) { if (dep->type == MODULE_DEP_REQUIRED || dep->type == MODULE_DEP_OPTIONAL) { b2 = b1 + 1; while (b2 < end) { r = (zend_module_entry*)(*b2)->pData; if (strcasecmp(dep->name, r->name) == 0) { tmp = *b1; *b1 = *b2; *b2 = tmp; goto try_again; } b2++; } } dep++; } } b1++; } } /* }}} */ ZEND_API void zend_collect_module_handlers(TSRMLS_D) /* {{{ */ { HashPosition pos; zend_module_entry *module; int startup_count = 0; int shutdown_count = 0; int post_deactivate_count = 0; zend_class_entry **pce; int class_count = 0; /* Collect extensions with request startup/shutdown handlers */ for (zend_hash_internal_pointer_reset_ex(&module_registry, &pos); zend_hash_get_current_data_ex(&module_registry, (void *) &module, &pos) == SUCCESS; zend_hash_move_forward_ex(&module_registry, &pos)) { if (module->request_startup_func) { startup_count++; } if (module->request_shutdown_func) { shutdown_count++; } if (module->post_deactivate_func) { post_deactivate_count++; } } module_request_startup_handlers = (zend_module_entry**)malloc( sizeof(zend_module_entry*) * (startup_count + 1 + shutdown_count + 1 + post_deactivate_count + 1)); module_request_startup_handlers[startup_count] = NULL; module_request_shutdown_handlers = module_request_startup_handlers + startup_count + 1; module_request_shutdown_handlers[shutdown_count] = NULL; module_post_deactivate_handlers = module_request_shutdown_handlers + shutdown_count + 1; module_post_deactivate_handlers[post_deactivate_count] = NULL; startup_count = 0; for (zend_hash_internal_pointer_reset_ex(&module_registry, &pos); zend_hash_get_current_data_ex(&module_registry, (void *) &module, &pos) == SUCCESS; zend_hash_move_forward_ex(&module_registry, &pos)) { if (module->request_startup_func) { module_request_startup_handlers[startup_count++] = module; } if (module->request_shutdown_func) { module_request_shutdown_handlers[--shutdown_count] = module; } if (module->post_deactivate_func) { module_post_deactivate_handlers[--post_deactivate_count] = module; } } /* Collect internal classes with static members */ for (zend_hash_internal_pointer_reset_ex(CG(class_table), &pos); zend_hash_get_current_data_ex(CG(class_table), (void *) &pce, &pos) == SUCCESS; zend_hash_move_forward_ex(CG(class_table), &pos)) { if ((*pce)->type == ZEND_INTERNAL_CLASS && (*pce)->default_static_members_count > 0) { class_count++; } } class_cleanup_handlers = (zend_class_entry**)malloc( sizeof(zend_class_entry*) * (class_count + 1)); class_cleanup_handlers[class_count] = NULL; if (class_count) { for (zend_hash_internal_pointer_reset_ex(CG(class_table), &pos); zend_hash_get_current_data_ex(CG(class_table), (void *) &pce, &pos) == SUCCESS; zend_hash_move_forward_ex(CG(class_table), &pos)) { if ((*pce)->type == ZEND_INTERNAL_CLASS && (*pce)->default_static_members_count > 0) { class_cleanup_handlers[--class_count] = *pce; } } } } /* }}} */ ZEND_API int zend_startup_modules(TSRMLS_D) /* {{{ */ { zend_hash_sort(&module_registry, zend_sort_modules, NULL, 0 TSRMLS_CC); zend_hash_apply(&module_registry, (apply_func_t)zend_startup_module_ex TSRMLS_CC); return SUCCESS; } /* }}} */ ZEND_API void zend_destroy_modules(void) /* {{{ */ { free(class_cleanup_handlers); free(module_request_startup_handlers); zend_hash_graceful_reverse_destroy(&module_registry); } /* }}} */ ZEND_API zend_module_entry* zend_register_module_ex(zend_module_entry *module TSRMLS_DC) /* {{{ */ { int name_len; char *lcname; zend_module_entry *module_ptr; if (!module) { return NULL; } #if 0 zend_printf("%s: Registering module %d\n", module->name, module->module_number); #endif /* Check module dependencies */ if (module->deps) { const zend_module_dep *dep = module->deps; while (dep->name) { if (dep->type == MODULE_DEP_CONFLICTS) { name_len = strlen(dep->name); lcname = zend_str_tolower_dup(dep->name, name_len); if (zend_hash_exists(&module_registry, lcname, name_len+1)) { efree(lcname); /* TODO: Check version relationship */ zend_error(E_CORE_WARNING, "Cannot load module '%s' because conflicting module '%s' is already loaded", module->name, dep->name); return NULL; } efree(lcname); } ++dep; } } name_len = strlen(module->name); lcname = zend_str_tolower_dup(module->name, name_len); if (zend_hash_add(&module_registry, lcname, name_len+1, (void *)module, sizeof(zend_module_entry), (void**)&module_ptr)==FAILURE) { zend_error(E_CORE_WARNING, "Module '%s' already loaded", module->name); efree(lcname); return NULL; } efree(lcname); module = module_ptr; EG(current_module) = module; if (module->functions && zend_register_functions(NULL, module->functions, NULL, module->type TSRMLS_CC)==FAILURE) { EG(current_module) = NULL; zend_error(E_CORE_WARNING,"%s: Unable to register functions, unable to load", module->name); return NULL; } EG(current_module) = NULL; return module; } /* }}} */ ZEND_API zend_module_entry* zend_register_internal_module(zend_module_entry *module TSRMLS_DC) /* {{{ */ { module->module_number = zend_next_free_module(); module->type = MODULE_PERSISTENT; return zend_register_module_ex(module TSRMLS_CC); } /* }}} */ ZEND_API void zend_check_magic_method_implementation(const zend_class_entry *ce, const zend_function *fptr, int error_type TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(fptr->common.function_name); zend_str_tolower_copy(lcname, fptr->common.function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)) && fptr->common.num_args != 0) { zend_error(error_type, "Destructor %s::%s() cannot take arguments", ce->name, ZEND_DESTRUCTOR_FUNC_NAME); } else if (name_len == sizeof(ZEND_CLONE_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)) && fptr->common.num_args != 0) { zend_error(error_type, "Method %s::%s() cannot accept any arguments", ce->name, ZEND_CLONE_FUNC_NAME); } else if (name_len == sizeof(ZEND_GET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME))) { if (fptr->common.num_args != 1) { zend_error(error_type, "Method %s::%s() must take exactly 1 argument", ce->name, ZEND_GET_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_GET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_SET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME))) { if (fptr->common.num_args != 2) { zend_error(error_type, "Method %s::%s() must take exactly 2 arguments", ce->name, ZEND_SET_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1) || ARG_SHOULD_BE_SENT_BY_REF(fptr, 2)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_SET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_UNSET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME))) { if (fptr->common.num_args != 1) { zend_error(error_type, "Method %s::%s() must take exactly 1 argument", ce->name, ZEND_UNSET_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_UNSET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_ISSET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME))) { if (fptr->common.num_args != 1) { zend_error(error_type, "Method %s::%s() must take exactly 1 argument", ce->name, ZEND_ISSET_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_ISSET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_CALL_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME))) { if (fptr->common.num_args != 2) { zend_error(error_type, "Method %s::%s() must take exactly 2 arguments", ce->name, ZEND_CALL_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1) || ARG_SHOULD_BE_SENT_BY_REF(fptr, 2)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_CALL_FUNC_NAME); } } else if (name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) ) { if (fptr->common.num_args != 2) { zend_error(error_type, "Method %s::%s() must take exactly 2 arguments", ce->name, ZEND_CALLSTATIC_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1) || ARG_SHOULD_BE_SENT_BY_REF(fptr, 2)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_CALLSTATIC_FUNC_NAME); } } else if (name_len == sizeof(ZEND_TOSTRING_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && fptr->common.num_args != 0 ) { zend_error(error_type, "Method %s::%s() cannot take arguments", ce->name, ZEND_TOSTRING_FUNC_NAME); } } /* }}} */ /* registers all functions in *library_functions in the function hash */ ZEND_API int zend_register_functions(zend_class_entry *scope, const zend_function_entry *functions, HashTable *function_table, int type TSRMLS_DC) /* {{{ */ { const zend_function_entry *ptr = functions; zend_function function, *reg_function; zend_internal_function *internal_function = (zend_internal_function *)&function; int count=0, unload=0, result=0; HashTable *target_function_table = function_table; int error_type; zend_function *ctor = NULL, *dtor = NULL, *clone = NULL, *__get = NULL, *__set = NULL, *__unset = NULL, *__isset = NULL, *__call = NULL, *__callstatic = NULL, *__tostring = NULL; const char *lowercase_name; int fname_len; const char *lc_class_name = NULL; int class_name_len = 0; if (type==MODULE_PERSISTENT) { error_type = E_CORE_WARNING; } else { error_type = E_WARNING; } if (!target_function_table) { target_function_table = CG(function_table); } internal_function->type = ZEND_INTERNAL_FUNCTION; internal_function->module = EG(current_module); if (scope) { class_name_len = strlen(scope->name); if ((lc_class_name = zend_memrchr(scope->name, '\\', class_name_len))) { ++lc_class_name; class_name_len -= (lc_class_name - scope->name); lc_class_name = zend_str_tolower_dup(lc_class_name, class_name_len); } else { lc_class_name = zend_str_tolower_dup(scope->name, class_name_len); } } while (ptr->fname) { internal_function->handler = ptr->handler; internal_function->function_name = (char*)ptr->fname; internal_function->scope = scope; internal_function->prototype = NULL; if (ptr->flags) { if (!(ptr->flags & ZEND_ACC_PPP_MASK)) { if (ptr->flags != ZEND_ACC_DEPRECATED || scope) { zend_error(error_type, "Invalid access level for %s%s%s() - access must be exactly one of public, protected or private", scope ? scope->name : "", scope ? "::" : "", ptr->fname); } internal_function->fn_flags = ZEND_ACC_PUBLIC | ptr->flags; } else { internal_function->fn_flags = ptr->flags; } } else { internal_function->fn_flags = ZEND_ACC_PUBLIC; } if (ptr->arg_info) { zend_internal_function_info *info = (zend_internal_function_info*)ptr->arg_info; internal_function->arg_info = (zend_arg_info*)ptr->arg_info+1; internal_function->num_args = ptr->num_args; /* Currently you cannot denote that the function can accept less arguments than num_args */ if (info->required_num_args == -1) { internal_function->required_num_args = ptr->num_args; } else { internal_function->required_num_args = info->required_num_args; } if (info->pass_rest_by_reference) { if (info->pass_rest_by_reference == ZEND_SEND_PREFER_REF) { internal_function->fn_flags |= ZEND_ACC_PASS_REST_PREFER_REF; } else { internal_function->fn_flags |= ZEND_ACC_PASS_REST_BY_REFERENCE; } } if (info->return_reference) { internal_function->fn_flags |= ZEND_ACC_RETURN_REFERENCE; } } else { internal_function->arg_info = NULL; internal_function->num_args = 0; internal_function->required_num_args = 0; } if (ptr->flags & ZEND_ACC_ABSTRACT) { if (scope) { /* This is a class that must be abstract itself. Here we set the check info. */ scope->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; if (!(scope->ce_flags & ZEND_ACC_INTERFACE)) { /* Since the class is not an interface it needs to be declared as a abstract class. */ /* Since here we are handling internal functions only we can add the keyword flag. */ /* This time we set the flag for the keyword 'abstract'. */ scope->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } } if (ptr->flags & ZEND_ACC_STATIC && (!scope || !(scope->ce_flags & ZEND_ACC_INTERFACE))) { zend_error(error_type, "Static function %s%s%s() cannot be abstract", scope ? scope->name : "", scope ? "::" : "", ptr->fname); } } else { if (scope && (scope->ce_flags & ZEND_ACC_INTERFACE)) { efree((char*)lc_class_name); zend_error(error_type, "Interface %s cannot contain non abstract method %s()", scope->name, ptr->fname); return FAILURE; } if (!internal_function->handler) { if (scope) { efree((char*)lc_class_name); } zend_error(error_type, "Method %s%s%s() cannot be a NULL function", scope ? scope->name : "", scope ? "::" : "", ptr->fname); zend_unregister_functions(functions, count, target_function_table TSRMLS_CC); return FAILURE; } } fname_len = strlen(ptr->fname); lowercase_name = zend_new_interned_string(zend_str_tolower_dup(ptr->fname, fname_len), fname_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lowercase_name)) { result = zend_hash_quick_add(target_function_table, lowercase_name, fname_len+1, INTERNED_HASH(lowercase_name), &function, sizeof(zend_function), (void**)&reg_function); } else { result = zend_hash_add(target_function_table, lowercase_name, fname_len+1, &function, sizeof(zend_function), (void**)&reg_function); } if (result == FAILURE) { unload=1; str_efree(lowercase_name); break; } if (scope) { /* Look for ctor, dtor, clone * If it's an old-style constructor, store it only if we don't have * a constructor already. */ if ((fname_len == class_name_len) && !ctor && !memcmp(lowercase_name, lc_class_name, class_name_len+1)) { ctor = reg_function; } else if ((fname_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME))) { ctor = reg_function; } else if ((fname_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME))) { dtor = reg_function; if (internal_function->num_args) { zend_error(error_type, "Destructor %s::%s() cannot take arguments", scope->name, ptr->fname); } } else if ((fname_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME))) { clone = reg_function; } else if ((fname_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME))) { __call = reg_function; } else if ((fname_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME))) { __callstatic = reg_function; } else if ((fname_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME))) { __tostring = reg_function; } else if ((fname_len == sizeof(ZEND_GET_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME))) { __get = reg_function; } else if ((fname_len == sizeof(ZEND_SET_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME))) { __set = reg_function; } else if ((fname_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME))) { __unset = reg_function; } else if ((fname_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME))) { __isset = reg_function; } else { reg_function = NULL; } if (reg_function) { zend_check_magic_method_implementation(scope, reg_function, error_type TSRMLS_CC); } } ptr++; count++; str_efree(lowercase_name); } if (unload) { /* before unloading, display all remaining bad function in the module */ if (scope) { efree((char*)lc_class_name); } while (ptr->fname) { fname_len = strlen(ptr->fname); lowercase_name = zend_str_tolower_dup(ptr->fname, fname_len); if (zend_hash_exists(target_function_table, lowercase_name, fname_len+1)) { zend_error(error_type, "Function registration failed - duplicate name - %s%s%s", scope ? scope->name : "", scope ? "::" : "", ptr->fname); } efree((char*)lowercase_name); ptr++; } zend_unregister_functions(functions, count, target_function_table TSRMLS_CC); return FAILURE; } if (scope) { scope->constructor = ctor; scope->destructor = dtor; scope->clone = clone; scope->__call = __call; scope->__callstatic = __callstatic; scope->__tostring = __tostring; scope->__get = __get; scope->__set = __set; scope->__unset = __unset; scope->__isset = __isset; if (ctor) { ctor->common.fn_flags |= ZEND_ACC_CTOR; if (ctor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Constructor %s::%s() cannot be static", scope->name, ctor->common.function_name); } ctor->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (dtor) { dtor->common.fn_flags |= ZEND_ACC_DTOR; if (dtor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Destructor %s::%s() cannot be static", scope->name, dtor->common.function_name); } dtor->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (clone) { clone->common.fn_flags |= ZEND_ACC_CLONE; if (clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Constructor %s::%s() cannot be static", scope->name, clone->common.function_name); } clone->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__call) { if (__call->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __call->common.function_name); } __call->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__callstatic) { if (!(__callstatic->common.fn_flags & ZEND_ACC_STATIC)) { zend_error(error_type, "Method %s::%s() must be static", scope->name, __callstatic->common.function_name); } __callstatic->common.fn_flags |= ZEND_ACC_STATIC; } if (__tostring) { if (__tostring->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __tostring->common.function_name); } __tostring->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__get) { if (__get->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __get->common.function_name); } __get->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__set) { if (__set->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __set->common.function_name); } __set->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__unset) { if (__unset->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __unset->common.function_name); } __unset->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__isset) { if (__isset->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __isset->common.function_name); } __isset->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } efree((char*)lc_class_name); } return SUCCESS; } /* }}} */ /* count=-1 means erase all functions, otherwise, * erase the first count functions */ ZEND_API void zend_unregister_functions(const zend_function_entry *functions, int count, HashTable *function_table TSRMLS_DC) /* {{{ */ { const zend_function_entry *ptr = functions; int i=0; HashTable *target_function_table = function_table; if (!target_function_table) { target_function_table = CG(function_table); } while (ptr->fname) { if (count!=-1 && i>=count) { break; } #if 0 zend_printf("Unregistering %s()\n", ptr->fname); #endif zend_hash_del(target_function_table, ptr->fname, strlen(ptr->fname)+1); ptr++; i++; } } /* }}} */ ZEND_API int zend_startup_module(zend_module_entry *module) /* {{{ */ { TSRMLS_FETCH(); if ((module = zend_register_internal_module(module TSRMLS_CC)) != NULL && zend_startup_module_ex(module TSRMLS_CC) == SUCCESS) { return SUCCESS; } return FAILURE; } /* }}} */ ZEND_API int zend_get_module_started(const char *module_name) /* {{{ */ { zend_module_entry *module; return (zend_hash_find(&module_registry, module_name, strlen(module_name)+1, (void**)&module) == SUCCESS && module->module_started) ? SUCCESS : FAILURE; } /* }}} */ static int clean_module_class(const zend_class_entry **ce, int *module_number TSRMLS_DC) /* {{{ */ { if ((*ce)->type == ZEND_INTERNAL_CLASS && (*ce)->info.internal.module->module_number == *module_number) { return ZEND_HASH_APPLY_REMOVE; } else { return ZEND_HASH_APPLY_KEEP; } } /* }}} */ static void clean_module_classes(int module_number TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_argument(EG(class_table), (apply_func_arg_t) clean_module_class, (void *) &module_number TSRMLS_CC); } /* }}} */ void module_destructor(zend_module_entry *module) /* {{{ */ { TSRMLS_FETCH(); if (module->type == MODULE_TEMPORARY) { zend_clean_module_rsrc_dtors(module->module_number TSRMLS_CC); clean_module_constants(module->module_number TSRMLS_CC); clean_module_classes(module->module_number TSRMLS_CC); } if (module->module_started && module->module_shutdown_func) { #if 0 zend_printf("%s: Module shutdown\n", module->name); #endif module->module_shutdown_func(module->type, module->module_number TSRMLS_CC); } /* Deinitilaise module globals */ if (module->globals_size) { #ifdef ZTS ts_free_id(*module->globals_id_ptr); #else if (module->globals_dtor) { module->globals_dtor(module->globals_ptr TSRMLS_CC); } #endif } module->module_started=0; if (module->functions) { zend_unregister_functions(module->functions, -1, NULL TSRMLS_CC); } #if HAVE_LIBDL #if !(defined(NETWARE) && defined(APACHE_1_BUILD)) if (module->handle && !getenv("ZEND_DONT_UNLOAD_MODULES")) { DL_UNLOAD(module->handle); } #endif #endif } /* }}} */ void zend_activate_modules(TSRMLS_D) /* {{{ */ { zend_module_entry **p = module_request_startup_handlers; while (*p) { zend_module_entry *module = *p; if (module->request_startup_func(module->type, module->module_number TSRMLS_CC)==FAILURE) { zend_error(E_WARNING, "request_startup() for %s module failed", module->name); exit(1); } p++; } } /* }}} */ /* call request shutdown for all modules */ int module_registry_cleanup(zend_module_entry *module TSRMLS_DC) /* {{{ */ { if (module->request_shutdown_func) { #if 0 zend_printf("%s: Request shutdown\n", module->name); #endif module->request_shutdown_func(module->type, module->module_number TSRMLS_CC); } return 0; } /* }}} */ void zend_deactivate_modules(TSRMLS_D) /* {{{ */ { EG(opline_ptr) = NULL; /* we're no longer executing anything */ zend_try { if (EG(full_tables_cleanup)) { zend_hash_reverse_apply(&module_registry, (apply_func_t) module_registry_cleanup TSRMLS_CC); } else { zend_module_entry **p = module_request_shutdown_handlers; while (*p) { zend_module_entry *module = *p; module->request_shutdown_func(module->type, module->module_number TSRMLS_CC); p++; } } } zend_end_try(); } /* }}} */ ZEND_API void zend_cleanup_internal_classes(TSRMLS_D) /* {{{ */ { zend_class_entry **p = class_cleanup_handlers; while (*p) { zend_cleanup_internal_class_data(*p TSRMLS_CC); p++; } } /* }}} */ int module_registry_unload_temp(const zend_module_entry *module TSRMLS_DC) /* {{{ */ { return (module->type == MODULE_TEMPORARY) ? ZEND_HASH_APPLY_REMOVE : ZEND_HASH_APPLY_STOP; } /* }}} */ static int exec_done_cb(zend_module_entry *module TSRMLS_DC) /* {{{ */ { if (module->post_deactivate_func) { module->post_deactivate_func(); } return 0; } /* }}} */ void zend_post_deactivate_modules(TSRMLS_D) /* {{{ */ { if (EG(full_tables_cleanup)) { zend_hash_apply(&module_registry, (apply_func_t) exec_done_cb TSRMLS_CC); zend_hash_reverse_apply(&module_registry, (apply_func_t) module_registry_unload_temp TSRMLS_CC); } else { zend_module_entry **p = module_post_deactivate_handlers; while (*p) { zend_module_entry *module = *p; module->post_deactivate_func(); p++; } } } /* }}} */ /* return the next free module number */ int zend_next_free_module(void) /* {{{ */ { return ++module_count; } /* }}} */ static zend_class_entry *do_register_internal_class(zend_class_entry *orig_class_entry, zend_uint ce_flags TSRMLS_DC) /* {{{ */ { zend_class_entry *class_entry = malloc(sizeof(zend_class_entry)); char *lowercase_name = emalloc(orig_class_entry->name_length + 1); *class_entry = *orig_class_entry; class_entry->type = ZEND_INTERNAL_CLASS; zend_initialize_class_data(class_entry, 0 TSRMLS_CC); class_entry->ce_flags = ce_flags; class_entry->info.internal.module = EG(current_module); if (class_entry->info.internal.builtin_functions) { zend_register_functions(class_entry, class_entry->info.internal.builtin_functions, &class_entry->function_table, MODULE_PERSISTENT TSRMLS_CC); } zend_str_tolower_copy(lowercase_name, orig_class_entry->name, class_entry->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, class_entry->name_length + 1, 1 TSRMLS_CC); if (IS_INTERNED(lowercase_name)) { zend_hash_quick_update(CG(class_table), lowercase_name, class_entry->name_length+1, INTERNED_HASH(lowercase_name), &class_entry, sizeof(zend_class_entry *), NULL); } else { zend_hash_update(CG(class_table), lowercase_name, class_entry->name_length+1, &class_entry, sizeof(zend_class_entry *), NULL); } str_efree(lowercase_name); return class_entry; } /* }}} */ /* If parent_ce is not NULL then it inherits from parent_ce * If parent_ce is NULL and parent_name isn't then it looks for the parent and inherits from it * If both parent_ce and parent_name are NULL it does a regular class registration * If parent_name is specified but not found NULL is returned */ ZEND_API zend_class_entry *zend_register_internal_class_ex(zend_class_entry *class_entry, zend_class_entry *parent_ce, char *parent_name TSRMLS_DC) /* {{{ */ { zend_class_entry *register_class; if (!parent_ce && parent_name) { zend_class_entry **pce; if (zend_hash_find(CG(class_table), parent_name, strlen(parent_name)+1, (void **) &pce)==FAILURE) { return NULL; } else { parent_ce = *pce; } } register_class = zend_register_internal_class(class_entry TSRMLS_CC); if (parent_ce) { zend_do_inheritance(register_class, parent_ce TSRMLS_CC); } return register_class; } /* }}} */ ZEND_API void zend_class_implements(zend_class_entry *class_entry TSRMLS_DC, int num_interfaces, ...) /* {{{ */ { zend_class_entry *interface_entry; va_list interface_list; va_start(interface_list, num_interfaces); while (num_interfaces--) { interface_entry = va_arg(interface_list, zend_class_entry *); zend_do_implement_interface(class_entry, interface_entry TSRMLS_CC); } va_end(interface_list); } /* }}} */ /* A class that contains at least one abstract method automatically becomes an abstract class. */ ZEND_API zend_class_entry *zend_register_internal_class(zend_class_entry *orig_class_entry TSRMLS_DC) /* {{{ */ { return do_register_internal_class(orig_class_entry, 0 TSRMLS_CC); } /* }}} */ ZEND_API zend_class_entry *zend_register_internal_interface(zend_class_entry *orig_class_entry TSRMLS_DC) /* {{{ */ { return do_register_internal_class(orig_class_entry, ZEND_ACC_INTERFACE TSRMLS_CC); } /* }}} */ ZEND_API int zend_register_class_alias_ex(const char *name, int name_len, zend_class_entry *ce TSRMLS_DC) /* {{{ */ { char *lcname = zend_str_tolower_dup(name, name_len); int ret; ret = zend_hash_add(CG(class_table), lcname, name_len+1, &ce, sizeof(zend_class_entry *), NULL); efree(lcname); if (ret == SUCCESS) { ce->refcount++; } return ret; } /* }}} */ ZEND_API int zend_set_hash_symbol(zval *symbol, const char *name, int name_length, zend_bool is_ref, int num_symbol_tables, ...) /* {{{ */ { HashTable *symbol_table; va_list symbol_table_list; if (num_symbol_tables <= 0) return FAILURE; Z_SET_ISREF_TO_P(symbol, is_ref); va_start(symbol_table_list, num_symbol_tables); while (num_symbol_tables-- > 0) { symbol_table = va_arg(symbol_table_list, HashTable *); zend_hash_update(symbol_table, name, name_length + 1, &symbol, sizeof(zval *), NULL); zval_add_ref(&symbol); } va_end(symbol_table_list); return SUCCESS; } /* }}} */ /* Disabled functions support */ /* {{{ proto void display_disabled_function(void) Dummy function which displays an error when a disabled function is called. */ ZEND_API ZEND_FUNCTION(display_disabled_function) { zend_error(E_WARNING, "%s() has been disabled for security reasons", get_active_function_name(TSRMLS_C)); } /* }}} */ static zend_function_entry disabled_function[] = { ZEND_FE(display_disabled_function, NULL) ZEND_FE_END }; ZEND_API int zend_disable_function(char *function_name, uint function_name_length TSRMLS_DC) /* {{{ */ { if (zend_hash_del(CG(function_table), function_name, function_name_length+1)==FAILURE) { return FAILURE; } disabled_function[0].fname = function_name; return zend_register_functions(NULL, disabled_function, CG(function_table), MODULE_PERSISTENT TSRMLS_CC); } /* }}} */ static zend_object_value display_disabled_class(zend_class_entry *class_type TSRMLS_DC) /* {{{ */ { zend_object_value retval; zend_object *intern; retval = zend_objects_new(&intern, class_type TSRMLS_CC); zend_error(E_WARNING, "%s() has been disabled for security reasons", class_type->name); return retval; } /* }}} */ static const zend_function_entry disabled_class_new[] = { ZEND_FE_END }; ZEND_API int zend_disable_class(char *class_name, uint class_name_length TSRMLS_DC) /* {{{ */ { zend_class_entry disabled_class; zend_str_tolower(class_name, class_name_length); if (zend_hash_del(CG(class_table), class_name, class_name_length+1)==FAILURE) { return FAILURE; } INIT_OVERLOADED_CLASS_ENTRY_EX(disabled_class, class_name, class_name_length, disabled_class_new, NULL, NULL, NULL, NULL, NULL); disabled_class.create_object = display_disabled_class; disabled_class.name_length = class_name_length; zend_register_internal_class(&disabled_class TSRMLS_CC); return SUCCESS; } /* }}} */ static int zend_is_callable_check_class(const char *name, int name_len, zend_fcall_info_cache *fcc, int *strict_class, char **error TSRMLS_DC) /* {{{ */ { int ret = 0; zend_class_entry **pce; char *lcname = zend_str_tolower_dup(name, name_len); *strict_class = 0; if (name_len == sizeof("self") - 1 && !memcmp(lcname, "self", sizeof("self") - 1)) { if (!EG(scope)) { if (error) *error = estrdup("cannot access self:: when no class scope is active"); } else { fcc->called_scope = EG(called_scope); fcc->calling_scope = EG(scope); if (!fcc->object_ptr) { fcc->object_ptr = EG(This); } ret = 1; } } else if (name_len == sizeof("parent") - 1 && !memcmp(lcname, "parent", sizeof("parent") - 1)) { if (!EG(scope)) { if (error) *error = estrdup("cannot access parent:: when no class scope is active"); } else if (!EG(scope)->parent) { if (error) *error = estrdup("cannot access parent:: when current class scope has no parent"); } else { fcc->called_scope = EG(called_scope); fcc->calling_scope = EG(scope)->parent; if (!fcc->object_ptr) { fcc->object_ptr = EG(This); } *strict_class = 1; ret = 1; } } else if (name_len == sizeof("static") - 1 && !memcmp(lcname, "static", sizeof("static") - 1)) { if (!EG(called_scope)) { if (error) *error = estrdup("cannot access static:: when no class scope is active"); } else { fcc->called_scope = EG(called_scope); fcc->calling_scope = EG(called_scope); if (!fcc->object_ptr) { fcc->object_ptr = EG(This); } *strict_class = 1; ret = 1; } } else if (zend_lookup_class_ex(name, name_len, NULL, 1, &pce TSRMLS_CC) == SUCCESS) { zend_class_entry *scope = EG(active_op_array) ? EG(active_op_array)->scope : NULL; fcc->calling_scope = *pce; if (scope && !fcc->object_ptr && EG(This) && instanceof_function(Z_OBJCE_P(EG(This)), scope TSRMLS_CC) && instanceof_function(scope, fcc->calling_scope TSRMLS_CC)) { fcc->object_ptr = EG(This); fcc->called_scope = Z_OBJCE_P(fcc->object_ptr); } else { fcc->called_scope = fcc->object_ptr ? Z_OBJCE_P(fcc->object_ptr) : fcc->calling_scope; } *strict_class = 1; ret = 1; } else { if (error) zend_spprintf(error, 0, "class '%.*s' not found", name_len, name); } efree(lcname); return ret; } /* }}} */ static int zend_is_callable_check_func(int check_flags, zval *callable, zend_fcall_info_cache *fcc, int strict_class, char **error TSRMLS_DC) /* {{{ */ { zend_class_entry *ce_org = fcc->calling_scope; int retval = 0; char *mname, *lmname; const char *colon; int clen, mlen; zend_class_entry *last_scope; HashTable *ftable; int call_via_handler = 0; if (error) { *error = NULL; } fcc->calling_scope = NULL; fcc->function_handler = NULL; if (!ce_org) { /* Skip leading \ */ if (Z_STRVAL_P(callable)[0] == '\\') { mlen = Z_STRLEN_P(callable) - 1; mname = Z_STRVAL_P(callable) + 1; lmname = zend_str_tolower_dup(Z_STRVAL_P(callable) + 1, mlen); } else { mlen = Z_STRLEN_P(callable); mname = Z_STRVAL_P(callable); lmname = zend_str_tolower_dup(Z_STRVAL_P(callable), mlen); } /* Check if function with given name exists. * This may be a compound name that includes namespace name */ if (zend_hash_find(EG(function_table), lmname, mlen+1, (void**)&fcc->function_handler) == SUCCESS) { efree(lmname); return 1; } efree(lmname); } /* Split name into class/namespace and method/function names */ if ((colon = zend_memrchr(Z_STRVAL_P(callable), ':', Z_STRLEN_P(callable))) != NULL && colon > Z_STRVAL_P(callable) && *(colon-1) == ':' ) { colon--; clen = colon - Z_STRVAL_P(callable); mlen = Z_STRLEN_P(callable) - clen - 2; if (colon == Z_STRVAL_P(callable)) { if (error) zend_spprintf(error, 0, "invalid function name"); return 0; } /* This is a compound name. * Try to fetch class and then find static method. */ last_scope = EG(scope); if (ce_org) { EG(scope) = ce_org; } if (!zend_is_callable_check_class(Z_STRVAL_P(callable), clen, fcc, &strict_class, error TSRMLS_CC)) { EG(scope) = last_scope; return 0; } EG(scope) = last_scope; ftable = &fcc->calling_scope->function_table; if (ce_org && !instanceof_function(ce_org, fcc->calling_scope TSRMLS_CC)) { if (error) zend_spprintf(error, 0, "class '%s' is not a subclass of '%s'", ce_org->name, fcc->calling_scope->name); return 0; } mname = Z_STRVAL_P(callable) + clen + 2; } else if (ce_org) { /* Try to fetch find static method of given class. */ mlen = Z_STRLEN_P(callable); mname = Z_STRVAL_P(callable); ftable = &ce_org->function_table; fcc->calling_scope = ce_org; } else { /* We already checked for plain function before. */ if (error && !(check_flags & IS_CALLABLE_CHECK_SILENT)) { zend_spprintf(error, 0, "function '%s' not found or invalid function name", Z_STRVAL_P(callable)); } return 0; } lmname = zend_str_tolower_dup(mname, mlen); if (strict_class && fcc->calling_scope && mlen == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1 && !memcmp(lmname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME))) { fcc->function_handler = fcc->calling_scope->constructor; if (fcc->function_handler) { retval = 1; } } else if (zend_hash_find(ftable, lmname, mlen+1, (void**)&fcc->function_handler) == SUCCESS) { retval = 1; if ((fcc->function_handler->op_array.fn_flags & ZEND_ACC_CHANGED) && EG(scope) && instanceof_function(fcc->function_handler->common.scope, EG(scope) TSRMLS_CC)) { zend_function *priv_fbc; if (zend_hash_find(&EG(scope)->function_table, lmname, mlen+1, (void **) &priv_fbc)==SUCCESS && priv_fbc->common.fn_flags & ZEND_ACC_PRIVATE && priv_fbc->common.scope == EG(scope)) { fcc->function_handler = priv_fbc; } } if ((check_flags & IS_CALLABLE_CHECK_NO_ACCESS) == 0 && (fcc->calling_scope && (fcc->calling_scope->__call || fcc->calling_scope->__callstatic))) { if (fcc->function_handler->op_array.fn_flags & ZEND_ACC_PRIVATE) { if (!zend_check_private(fcc->function_handler, fcc->object_ptr ? Z_OBJCE_P(fcc->object_ptr) : EG(scope), lmname, mlen TSRMLS_CC)) { retval = 0; fcc->function_handler = NULL; goto get_function_via_handler; } } else if (fcc->function_handler->common.fn_flags & ZEND_ACC_PROTECTED) { if (!zend_check_protected(fcc->function_handler->common.scope, EG(scope))) { retval = 0; fcc->function_handler = NULL; goto get_function_via_handler; } } } } else { get_function_via_handler: if (fcc->object_ptr && fcc->calling_scope == ce_org) { if (strict_class && ce_org->__call) { fcc->function_handler = emalloc(sizeof(zend_internal_function)); fcc->function_handler->internal_function.type = ZEND_INTERNAL_FUNCTION; fcc->function_handler->internal_function.module = (ce_org->type == ZEND_INTERNAL_CLASS) ? ce_org->info.internal.module : NULL; fcc->function_handler->internal_function.handler = zend_std_call_user_call; fcc->function_handler->internal_function.arg_info = NULL; fcc->function_handler->internal_function.num_args = 0; fcc->function_handler->internal_function.scope = ce_org; fcc->function_handler->internal_function.fn_flags = ZEND_ACC_CALL_VIA_HANDLER; fcc->function_handler->internal_function.function_name = estrndup(mname, mlen); call_via_handler = 1; retval = 1; } else if (Z_OBJ_HT_P(fcc->object_ptr)->get_method) { fcc->function_handler = Z_OBJ_HT_P(fcc->object_ptr)->get_method(&fcc->object_ptr, mname, mlen, NULL TSRMLS_CC); if (fcc->function_handler) { if (strict_class && (!fcc->function_handler->common.scope || !instanceof_function(ce_org, fcc->function_handler->common.scope TSRMLS_CC))) { if ((fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) != 0) { if (fcc->function_handler->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fcc->function_handler->common.function_name); } efree(fcc->function_handler); } } else { retval = 1; call_via_handler = (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) != 0; } } } } else if (fcc->calling_scope) { if (fcc->calling_scope->get_static_method) { fcc->function_handler = fcc->calling_scope->get_static_method(fcc->calling_scope, mname, mlen TSRMLS_CC); } else { fcc->function_handler = zend_std_get_static_method(fcc->calling_scope, mname, mlen, NULL TSRMLS_CC); } if (fcc->function_handler) { retval = 1; call_via_handler = (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) != 0; if (call_via_handler && !fcc->object_ptr && EG(This) && Z_OBJ_HT_P(EG(This))->get_class_entry && instanceof_function(Z_OBJCE_P(EG(This)), fcc->calling_scope TSRMLS_CC)) { fcc->object_ptr = EG(This); } } } } if (retval) { if (fcc->calling_scope && !call_via_handler) { if (!fcc->object_ptr && !(fcc->function_handler->common.fn_flags & ZEND_ACC_STATIC)) { int severity; char *verb; if (fcc->function_handler->common.fn_flags & ZEND_ACC_ALLOW_STATIC) { severity = E_STRICT; verb = "should not"; } else { /* An internal function assumes $this is present and won't check that. So PHP would crash by allowing the call. */ severity = E_ERROR; verb = "cannot"; } if ((check_flags & IS_CALLABLE_CHECK_IS_STATIC) != 0) { retval = 0; } if (EG(This) && instanceof_function(Z_OBJCE_P(EG(This)), fcc->calling_scope TSRMLS_CC)) { fcc->object_ptr = EG(This); if (error) { zend_spprintf(error, 0, "non-static method %s::%s() %s be called statically, assuming $this from compatible context %s", fcc->calling_scope->name, fcc->function_handler->common.function_name, verb, Z_OBJCE_P(EG(This))->name); if (severity == E_ERROR) { retval = 0; } } else if (retval) { zend_error(severity, "Non-static method %s::%s() %s be called statically, assuming $this from compatible context %s", fcc->calling_scope->name, fcc->function_handler->common.function_name, verb, Z_OBJCE_P(EG(This))->name); } } else { if (error) { zend_spprintf(error, 0, "non-static method %s::%s() %s be called statically", fcc->calling_scope->name, fcc->function_handler->common.function_name, verb); if (severity == E_ERROR) { retval = 0; } } else if (retval) { zend_error(severity, "Non-static method %s::%s() %s be called statically", fcc->calling_scope->name, fcc->function_handler->common.function_name, verb); } } } if (retval && (check_flags & IS_CALLABLE_CHECK_NO_ACCESS) == 0) { if (fcc->function_handler->op_array.fn_flags & ZEND_ACC_PRIVATE) { if (!zend_check_private(fcc->function_handler, fcc->object_ptr ? Z_OBJCE_P(fcc->object_ptr) : EG(scope), lmname, mlen TSRMLS_CC)) { if (error) { if (*error) { efree(*error); } zend_spprintf(error, 0, "cannot access private method %s::%s()", fcc->calling_scope->name, fcc->function_handler->common.function_name); } retval = 0; } } else if ((fcc->function_handler->common.fn_flags & ZEND_ACC_PROTECTED)) { if (!zend_check_protected(fcc->function_handler->common.scope, EG(scope))) { if (error) { if (*error) { efree(*error); } zend_spprintf(error, 0, "cannot access protected method %s::%s()", fcc->calling_scope->name, fcc->function_handler->common.function_name); } retval = 0; } } } } } else if (error && !(check_flags & IS_CALLABLE_CHECK_SILENT)) { if (fcc->calling_scope) { if (error) zend_spprintf(error, 0, "class '%s' does not have a method '%s'", fcc->calling_scope->name, mname); } else { if (error) zend_spprintf(error, 0, "function '%s' does not exist", mname); } } efree(lmname); if (fcc->object_ptr) { fcc->called_scope = Z_OBJCE_P(fcc->object_ptr); } if (retval) { fcc->initialized = 1; } return retval; } /* }}} */ ZEND_API zend_bool zend_is_callable_ex(zval *callable, zval *object_ptr, uint check_flags, char **callable_name, int *callable_name_len, zend_fcall_info_cache *fcc, char **error TSRMLS_DC) /* {{{ */ { zend_bool ret; int callable_name_len_local; zend_fcall_info_cache fcc_local; if (callable_name) { *callable_name = NULL; } if (callable_name_len == NULL) { callable_name_len = &callable_name_len_local; } if (fcc == NULL) { fcc = &fcc_local; } if (error) { *error = NULL; } fcc->initialized = 0; fcc->calling_scope = NULL; fcc->called_scope = NULL; fcc->function_handler = NULL; fcc->calling_scope = NULL; fcc->object_ptr = NULL; if (object_ptr && Z_TYPE_P(object_ptr) != IS_OBJECT) { object_ptr = NULL; } if (object_ptr && (!EG(objects_store).object_buckets || !EG(objects_store).object_buckets[Z_OBJ_HANDLE_P(object_ptr)].valid)) { return 0; } switch (Z_TYPE_P(callable)) { case IS_STRING: if (object_ptr) { fcc->object_ptr = object_ptr; fcc->calling_scope = Z_OBJCE_P(object_ptr); if (callable_name) { char *ptr; *callable_name_len = fcc->calling_scope->name_length + Z_STRLEN_P(callable) + sizeof("::") - 1; ptr = *callable_name = emalloc(*callable_name_len + 1); memcpy(ptr, fcc->calling_scope->name, fcc->calling_scope->name_length); ptr += fcc->calling_scope->name_length; memcpy(ptr, "::", sizeof("::") - 1); ptr += sizeof("::") - 1; memcpy(ptr, Z_STRVAL_P(callable), Z_STRLEN_P(callable) + 1); } } else if (callable_name) { *callable_name = estrndup(Z_STRVAL_P(callable), Z_STRLEN_P(callable)); *callable_name_len = Z_STRLEN_P(callable); } if (check_flags & IS_CALLABLE_CHECK_SYNTAX_ONLY) { fcc->called_scope = fcc->calling_scope; return 1; } ret = zend_is_callable_check_func(check_flags, callable, fcc, 0, error TSRMLS_CC); if (fcc == &fcc_local && fcc->function_handler && ((fcc->function_handler->type == ZEND_INTERNAL_FUNCTION && (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER)) || fcc->function_handler->type == ZEND_OVERLOADED_FUNCTION_TEMPORARY || fcc->function_handler->type == ZEND_OVERLOADED_FUNCTION)) { if (fcc->function_handler->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fcc->function_handler->common.function_name); } efree(fcc->function_handler); } return ret; case IS_ARRAY: { zval **method = NULL; zval **obj = NULL; int strict_class = 0; if (zend_hash_num_elements(Z_ARRVAL_P(callable)) == 2) { zend_hash_index_find(Z_ARRVAL_P(callable), 0, (void **) &obj); zend_hash_index_find(Z_ARRVAL_P(callable), 1, (void **) &method); } if (obj && method && (Z_TYPE_PP(obj) == IS_OBJECT || Z_TYPE_PP(obj) == IS_STRING) && Z_TYPE_PP(method) == IS_STRING) { if (Z_TYPE_PP(obj) == IS_STRING) { if (callable_name) { char *ptr; *callable_name_len = Z_STRLEN_PP(obj) + Z_STRLEN_PP(method) + sizeof("::") - 1; ptr = *callable_name = emalloc(*callable_name_len + 1); memcpy(ptr, Z_STRVAL_PP(obj), Z_STRLEN_PP(obj)); ptr += Z_STRLEN_PP(obj); memcpy(ptr, "::", sizeof("::") - 1); ptr += sizeof("::") - 1; memcpy(ptr, Z_STRVAL_PP(method), Z_STRLEN_PP(method) + 1); } if (check_flags & IS_CALLABLE_CHECK_SYNTAX_ONLY) { return 1; } if (!zend_is_callable_check_class(Z_STRVAL_PP(obj), Z_STRLEN_PP(obj), fcc, &strict_class, error TSRMLS_CC)) { return 0; } } else { if (!EG(objects_store).object_buckets || !EG(objects_store).object_buckets[Z_OBJ_HANDLE_PP(obj)].valid) { return 0; } fcc->calling_scope = Z_OBJCE_PP(obj); /* TBFixed: what if it's overloaded? */ fcc->object_ptr = *obj; if (callable_name) { char *ptr; *callable_name_len = fcc->calling_scope->name_length + Z_STRLEN_PP(method) + sizeof("::") - 1; ptr = *callable_name = emalloc(*callable_name_len + 1); memcpy(ptr, fcc->calling_scope->name, fcc->calling_scope->name_length); ptr += fcc->calling_scope->name_length; memcpy(ptr, "::", sizeof("::") - 1); ptr += sizeof("::") - 1; memcpy(ptr, Z_STRVAL_PP(method), Z_STRLEN_PP(method) + 1); } if (check_flags & IS_CALLABLE_CHECK_SYNTAX_ONLY) { fcc->called_scope = fcc->calling_scope; return 1; } } ret = zend_is_callable_check_func(check_flags, *method, fcc, strict_class, error TSRMLS_CC); if (fcc == &fcc_local && fcc->function_handler && ((fcc->function_handler->type == ZEND_INTERNAL_FUNCTION && (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER)) || fcc->function_handler->type == ZEND_OVERLOADED_FUNCTION_TEMPORARY || fcc->function_handler->type == ZEND_OVERLOADED_FUNCTION)) { if (fcc->function_handler->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fcc->function_handler->common.function_name); } efree(fcc->function_handler); } return ret; } else { if (zend_hash_num_elements(Z_ARRVAL_P(callable)) == 2) { if (!obj || (Z_TYPE_PP(obj) != IS_STRING && Z_TYPE_PP(obj) != IS_OBJECT)) { if (error) zend_spprintf(error, 0, "first array member is not a valid class name or object"); } else { if (error) zend_spprintf(error, 0, "second array member is not a valid method"); } } else { if (error) zend_spprintf(error, 0, "array must have exactly two members"); } if (callable_name) { *callable_name = estrndup("Array", sizeof("Array")-1); *callable_name_len = sizeof("Array") - 1; } } } return 0; case IS_OBJECT: if (Z_OBJ_HANDLER_P(callable, get_closure) && Z_OBJ_HANDLER_P(callable, get_closure)(callable, &fcc->calling_scope, &fcc->function_handler, &fcc->object_ptr TSRMLS_CC) == SUCCESS) { fcc->called_scope = fcc->calling_scope; if (callable_name) { zend_class_entry *ce = Z_OBJCE_P(callable); /* TBFixed: what if it's overloaded? */ *callable_name_len = ce->name_length + sizeof("::__invoke") - 1; *callable_name = emalloc(*callable_name_len + 1); memcpy(*callable_name, ce->name, ce->name_length); memcpy((*callable_name) + ce->name_length, "::__invoke", sizeof("::__invoke")); } return 1; } /* break missing intentionally */ default: if (callable_name) { zval expr_copy; int use_copy; zend_make_printable_zval(callable, &expr_copy, &use_copy); *callable_name = estrndup(Z_STRVAL(expr_copy), Z_STRLEN(expr_copy)); *callable_name_len = Z_STRLEN(expr_copy); zval_dtor(&expr_copy); } if (error) zend_spprintf(error, 0, "no array or string given"); return 0; } } /* }}} */ ZEND_API zend_bool zend_is_callable(zval *callable, uint check_flags, char **callable_name TSRMLS_DC) /* {{{ */ { return zend_is_callable_ex(callable, NULL, check_flags, callable_name, NULL, NULL, NULL TSRMLS_CC); } /* }}} */ ZEND_API zend_bool zend_make_callable(zval *callable, char **callable_name TSRMLS_DC) /* {{{ */ { zend_fcall_info_cache fcc; if (zend_is_callable_ex(callable, NULL, IS_CALLABLE_STRICT, callable_name, NULL, &fcc, NULL TSRMLS_CC)) { if (Z_TYPE_P(callable) == IS_STRING && fcc.calling_scope) { zval_dtor(callable); array_init(callable); add_next_index_string(callable, fcc.calling_scope->name, 1); add_next_index_string(callable, fcc.function_handler->common.function_name, 1); } if (fcc.function_handler && ((fcc.function_handler->type == ZEND_INTERNAL_FUNCTION && (fcc.function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER)) || fcc.function_handler->type == ZEND_OVERLOADED_FUNCTION_TEMPORARY || fcc.function_handler->type == ZEND_OVERLOADED_FUNCTION)) { if (fcc.function_handler->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fcc.function_handler->common.function_name); } efree(fcc.function_handler); } return 1; } return 0; } /* }}} */ ZEND_API int zend_fcall_info_init(zval *callable, uint check_flags, zend_fcall_info *fci, zend_fcall_info_cache *fcc, char **callable_name, char **error TSRMLS_DC) /* {{{ */ { if (!zend_is_callable_ex(callable, NULL, check_flags, callable_name, NULL, fcc, error TSRMLS_CC)) { return FAILURE; } fci->size = sizeof(*fci); fci->function_table = fcc->calling_scope ? &fcc->calling_scope->function_table : EG(function_table); fci->object_ptr = fcc->object_ptr; fci->function_name = callable; fci->retval_ptr_ptr = NULL; fci->param_count = 0; fci->params = NULL; fci->no_separation = 1; fci->symbol_table = NULL; return SUCCESS; } /* }}} */ ZEND_API void zend_fcall_info_args_clear(zend_fcall_info *fci, int free_mem) /* {{{ */ { if (fci->params) { if (free_mem) { efree(fci->params); fci->params = NULL; } } fci->param_count = 0; } /* }}} */ ZEND_API void zend_fcall_info_args_save(zend_fcall_info *fci, int *param_count, zval ****params) /* {{{ */ { *param_count = fci->param_count; *params = fci->params; fci->param_count = 0; fci->params = NULL; } /* }}} */ ZEND_API void zend_fcall_info_args_restore(zend_fcall_info *fci, int param_count, zval ***params) /* {{{ */ { zend_fcall_info_args_clear(fci, 1); fci->param_count = param_count; fci->params = params; } /* }}} */ ZEND_API int zend_fcall_info_args(zend_fcall_info *fci, zval *args TSRMLS_DC) /* {{{ */ { HashPosition pos; zval **arg, ***params; zend_fcall_info_args_clear(fci, !args); if (!args) { return SUCCESS; } if (Z_TYPE_P(args) != IS_ARRAY) { return FAILURE; } fci->param_count = zend_hash_num_elements(Z_ARRVAL_P(args)); fci->params = params = (zval ***) erealloc(fci->params, fci->param_count * sizeof(zval **)); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(args), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(args), (void *) &arg, &pos) == SUCCESS) { *params++ = arg; zend_hash_move_forward_ex(Z_ARRVAL_P(args), &pos); } return SUCCESS; } /* }}} */ ZEND_API int zend_fcall_info_argp(zend_fcall_info *fci TSRMLS_DC, int argc, zval ***argv) /* {{{ */ { int i; if (argc < 0) { return FAILURE; } zend_fcall_info_args_clear(fci, !argc); if (argc) { fci->param_count = argc; fci->params = (zval ***) erealloc(fci->params, fci->param_count * sizeof(zval **)); for (i = 0; i < argc; ++i) { fci->params[i] = argv[i]; } } return SUCCESS; } /* }}} */ ZEND_API int zend_fcall_info_argv(zend_fcall_info *fci TSRMLS_DC, int argc, va_list *argv) /* {{{ */ { int i; zval **arg; if (argc < 0) { return FAILURE; } zend_fcall_info_args_clear(fci, !argc); if (argc) { fci->param_count = argc; fci->params = (zval ***) erealloc(fci->params, fci->param_count * sizeof(zval **)); for (i = 0; i < argc; ++i) { arg = va_arg(*argv, zval **); fci->params[i] = arg; } } return SUCCESS; } /* }}} */ ZEND_API int zend_fcall_info_argn(zend_fcall_info *fci TSRMLS_DC, int argc, ...) /* {{{ */ { int ret; va_list argv; va_start(argv, argc); ret = zend_fcall_info_argv(fci TSRMLS_CC, argc, &argv); va_end(argv); return ret; } /* }}} */ ZEND_API int zend_fcall_info_call(zend_fcall_info *fci, zend_fcall_info_cache *fcc, zval **retval_ptr_ptr, zval *args TSRMLS_DC) /* {{{ */ { zval *retval, ***org_params = NULL; int result, org_count = 0; fci->retval_ptr_ptr = retval_ptr_ptr ? retval_ptr_ptr : &retval; if (args) { zend_fcall_info_args_save(fci, &org_count, &org_params); zend_fcall_info_args(fci, args TSRMLS_CC); } result = zend_call_function(fci, fcc TSRMLS_CC); if (!retval_ptr_ptr && retval) { zval_ptr_dtor(&retval); } if (args) { zend_fcall_info_args_restore(fci, org_count, org_params); } return result; } /* }}} */ ZEND_API const char *zend_get_module_version(const char *module_name) /* {{{ */ { char *lname; int name_len = strlen(module_name); zend_module_entry *module; lname = zend_str_tolower_dup(module_name, name_len); if (zend_hash_find(&module_registry, lname, name_len + 1, (void**)&module) == FAILURE) { efree(lname); return NULL; } efree(lname); return module->version; } /* }}} */ ZEND_API int zend_declare_property_ex(zend_class_entry *ce, const char *name, int name_length, zval *property, int access_type, const char *doc_comment, int doc_comment_len TSRMLS_DC) /* {{{ */ { zend_property_info property_info, *property_info_ptr; const char *interned_name; ulong h = zend_get_hash_value(name, name_length+1); if (!(access_type & ZEND_ACC_PPP_MASK)) { access_type |= ZEND_ACC_PUBLIC; } if (access_type & ZEND_ACC_STATIC) { if (zend_hash_quick_find(&ce->properties_info, name, name_length + 1, h, (void**)&property_info_ptr) == SUCCESS && (property_info_ptr->flags & ZEND_ACC_STATIC) != 0) { property_info.offset = property_info_ptr->offset; zval_ptr_dtor(&ce->default_static_members_table[property_info.offset]); zend_hash_quick_del(&ce->properties_info, name, name_length + 1, h); } else { property_info.offset = ce->default_static_members_count++; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(zval*) * ce->default_static_members_count, ce->type == ZEND_INTERNAL_CLASS); } ce->default_static_members_table[property_info.offset] = property; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } else { if (zend_hash_quick_find(&ce->properties_info, name, name_length + 1, h, (void**)&property_info_ptr) == SUCCESS && (property_info_ptr->flags & ZEND_ACC_STATIC) == 0) { property_info.offset = property_info_ptr->offset; zval_ptr_dtor(&ce->default_properties_table[property_info.offset]); zend_hash_quick_del(&ce->properties_info, name, name_length + 1, h); } else { property_info.offset = ce->default_properties_count++; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(zval*) * ce->default_properties_count, ce->type == ZEND_INTERNAL_CLASS); } ce->default_properties_table[property_info.offset] = property; } if (ce->type & ZEND_INTERNAL_CLASS) { switch(Z_TYPE_P(property)) { case IS_ARRAY: case IS_CONSTANT_ARRAY: case IS_OBJECT: case IS_RESOURCE: zend_error(E_CORE_ERROR, "Internal zval's can't be arrays, objects or resources"); break; default: break; } } switch (access_type & ZEND_ACC_PPP_MASK) { case ZEND_ACC_PRIVATE: { char *priv_name; int priv_name_length; zend_mangle_property_name(&priv_name, &priv_name_length, ce->name, ce->name_length, name, name_length, ce->type & ZEND_INTERNAL_CLASS); property_info.name = priv_name; property_info.name_length = priv_name_length; } break; case ZEND_ACC_PROTECTED: { char *prot_name; int prot_name_length; zend_mangle_property_name(&prot_name, &prot_name_length, "*", 1, name, name_length, ce->type & ZEND_INTERNAL_CLASS); property_info.name = prot_name; property_info.name_length = prot_name_length; } break; case ZEND_ACC_PUBLIC: if (IS_INTERNED(name)) { property_info.name = (char*)name; } else { property_info.name = ce->type & ZEND_INTERNAL_CLASS ? zend_strndup(name, name_length) : estrndup(name, name_length); } property_info.name_length = name_length; break; } interned_name = zend_new_interned_string(property_info.name, property_info.name_length+1, 0 TSRMLS_CC); if (interned_name != property_info.name) { if (ce->type == ZEND_USER_CLASS) { efree((char*)property_info.name); } else { free((char*)property_info.name); } property_info.name = interned_name; } property_info.flags = access_type; property_info.h = (access_type & ZEND_ACC_PUBLIC) ? h : zend_get_hash_value(property_info.name, property_info.name_length+1); property_info.doc_comment = doc_comment; property_info.doc_comment_len = doc_comment_len; property_info.ce = ce; zend_hash_quick_update(&ce->properties_info, name, name_length+1, h, &property_info, sizeof(zend_property_info), NULL); return SUCCESS; } /* }}} */ ZEND_API int zend_declare_property(zend_class_entry *ce, const char *name, int name_length, zval *property, int access_type TSRMLS_DC) /* {{{ */ { return zend_declare_property_ex(ce, name, name_length, property, access_type, NULL, 0 TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_null(zend_class_entry *ce, const char *name, int name_length, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); } else { ALLOC_ZVAL(property); } INIT_ZVAL(*property); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_bool(zend_class_entry *ce, const char *name, int name_length, long value, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); } else { ALLOC_ZVAL(property); } INIT_PZVAL(property); ZVAL_BOOL(property, value); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_long(zend_class_entry *ce, const char *name, int name_length, long value, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); } else { ALLOC_ZVAL(property); } INIT_PZVAL(property); ZVAL_LONG(property, value); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_double(zend_class_entry *ce, const char *name, int name_length, double value, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); } else { ALLOC_ZVAL(property); } INIT_PZVAL(property); ZVAL_DOUBLE(property, value); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_string(zend_class_entry *ce, const char *name, int name_length, const char *value, int access_type TSRMLS_DC) /* {{{ */ { zval *property; int len = strlen(value); if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); ZVAL_STRINGL(property, zend_strndup(value, len), len, 0); } else { ALLOC_ZVAL(property); ZVAL_STRINGL(property, value, len, 1); } INIT_PZVAL(property); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_stringl(zend_class_entry *ce, const char *name, int name_length, const char *value, int value_len, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); ZVAL_STRINGL(property, zend_strndup(value, value_len), value_len, 0); } else { ALLOC_ZVAL(property); ZVAL_STRINGL(property, value, value_len, 1); } INIT_PZVAL(property); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant(zend_class_entry *ce, const char *name, size_t name_length, zval *value TSRMLS_DC) /* {{{ */ { return zend_hash_update(&ce->constants_table, name, name_length+1, &value, sizeof(zval *), NULL); } /* }}} */ ZEND_API int zend_declare_class_constant_null(zend_class_entry *ce, const char *name, size_t name_length TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); } else { ALLOC_ZVAL(constant); } ZVAL_NULL(constant); INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_long(zend_class_entry *ce, const char *name, size_t name_length, long value TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); } else { ALLOC_ZVAL(constant); } ZVAL_LONG(constant, value); INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_bool(zend_class_entry *ce, const char *name, size_t name_length, zend_bool value TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); } else { ALLOC_ZVAL(constant); } ZVAL_BOOL(constant, value); INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_double(zend_class_entry *ce, const char *name, size_t name_length, double value TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); } else { ALLOC_ZVAL(constant); } ZVAL_DOUBLE(constant, value); INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_stringl(zend_class_entry *ce, const char *name, size_t name_length, const char *value, size_t value_length TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); ZVAL_STRINGL(constant, zend_strndup(value, value_length), value_length, 0); } else { ALLOC_ZVAL(constant); ZVAL_STRINGL(constant, value, value_length, 1); } INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_string(zend_class_entry *ce, const char *name, size_t name_length, const char *value TSRMLS_DC) /* {{{ */ { return zend_declare_class_constant_stringl(ce, name, name_length, value, strlen(value) TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property(zend_class_entry *scope, zval *object, const char *name, int name_length, zval *value TSRMLS_DC) /* {{{ */ { zval *property; zend_class_entry *old_scope = EG(scope); EG(scope) = scope; if (!Z_OBJ_HT_P(object)->write_property) { const char *class_name; zend_uint class_name_len; zend_get_object_classname(object, &class_name, &class_name_len TSRMLS_CC); zend_error(E_CORE_ERROR, "Property %s of class %s cannot be updated", name, class_name); } MAKE_STD_ZVAL(property); ZVAL_STRINGL(property, name, name_length, 1); Z_OBJ_HT_P(object)->write_property(object, property, value, 0 TSRMLS_CC); zval_ptr_dtor(&property); EG(scope) = old_scope; } /* }}} */ ZEND_API void zend_update_property_null(zend_class_entry *scope, zval *object, const char *name, int name_length TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_NULL(tmp); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_bool(zend_class_entry *scope, zval *object, const char *name, int name_length, long value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_BOOL(tmp, value); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_long(zend_class_entry *scope, zval *object, const char *name, int name_length, long value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_LONG(tmp, value); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_double(zend_class_entry *scope, zval *object, const char *name, int name_length, double value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_DOUBLE(tmp, value); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_string(zend_class_entry *scope, zval *object, const char *name, int name_length, const char *value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_STRING(tmp, value, 1); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_stringl(zend_class_entry *scope, zval *object, const char *name, int name_length, const char *value, int value_len TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_STRINGL(tmp, value, value_len, 1); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property(zend_class_entry *scope, const char *name, int name_length, zval *value TSRMLS_DC) /* {{{ */ { zval **property; zend_class_entry *old_scope = EG(scope); EG(scope) = scope; property = zend_std_get_static_property(scope, name, name_length, 0, NULL TSRMLS_CC); EG(scope) = old_scope; if (!property) { return FAILURE; } else { if (*property != value) { if (PZVAL_IS_REF(*property)) { zval_dtor(*property); Z_TYPE_PP(property) = Z_TYPE_P(value); (*property)->value = value->value; if (Z_REFCOUNT_P(value) > 0) { zval_copy_ctor(*property); } } else { zval *garbage = *property; Z_ADDREF_P(value); if (PZVAL_IS_REF(value)) { SEPARATE_ZVAL(&value); } *property = value; zval_ptr_dtor(&garbage); } } return SUCCESS; } } /* }}} */ ZEND_API int zend_update_static_property_null(zend_class_entry *scope, const char *name, int name_length TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_NULL(tmp); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_bool(zend_class_entry *scope, const char *name, int name_length, long value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_BOOL(tmp, value); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_long(zend_class_entry *scope, const char *name, int name_length, long value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_LONG(tmp, value); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_double(zend_class_entry *scope, const char *name, int name_length, double value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_DOUBLE(tmp, value); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_string(zend_class_entry *scope, const char *name, int name_length, const char *value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_STRING(tmp, value, 1); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_stringl(zend_class_entry *scope, const char *name, int name_length, const char *value, int value_len TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_STRINGL(tmp, value, value_len, 1); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API zval *zend_read_property(zend_class_entry *scope, zval *object, const char *name, int name_length, zend_bool silent TSRMLS_DC) /* {{{ */ { zval *property, *value; zend_class_entry *old_scope = EG(scope); EG(scope) = scope; if (!Z_OBJ_HT_P(object)->read_property) { const char *class_name; zend_uint class_name_len; zend_get_object_classname(object, &class_name, &class_name_len TSRMLS_CC); zend_error(E_CORE_ERROR, "Property %s of class %s cannot be read", name, class_name); } MAKE_STD_ZVAL(property); ZVAL_STRINGL(property, name, name_length, 1); value = Z_OBJ_HT_P(object)->read_property(object, property, silent?BP_VAR_IS:BP_VAR_R, 0 TSRMLS_CC); zval_ptr_dtor(&property); EG(scope) = old_scope; return value; } /* }}} */ ZEND_API zval *zend_read_static_property(zend_class_entry *scope, const char *name, int name_length, zend_bool silent TSRMLS_DC) /* {{{ */ { zval **property; zend_class_entry *old_scope = EG(scope); EG(scope) = scope; property = zend_std_get_static_property(scope, name, name_length, silent, NULL TSRMLS_CC); EG(scope) = old_scope; return property?*property:NULL; } /* }}} */ ZEND_API void zend_save_error_handling(zend_error_handling *current TSRMLS_DC) /* {{{ */ { current->handling = EG(error_handling); current->exception = EG(exception_class); current->user_handler = EG(user_error_handler); if (current->user_handler) { Z_ADDREF_P(current->user_handler); } } /* }}} */ ZEND_API void zend_replace_error_handling(zend_error_handling_t error_handling, zend_class_entry *exception_class, zend_error_handling *current TSRMLS_DC) /* {{{ */ { if (current) { zend_save_error_handling(current TSRMLS_CC); if (error_handling != EH_NORMAL && EG(user_error_handler)) { zval_ptr_dtor(&EG(user_error_handler)); EG(user_error_handler) = NULL; } } EG(error_handling) = error_handling; EG(exception_class) = error_handling == EH_THROW ? exception_class : NULL; } /* }}} */ ZEND_API void zend_restore_error_handling(zend_error_handling *saved TSRMLS_DC) /* {{{ */ { EG(error_handling) = saved->handling; EG(exception_class) = saved->handling == EH_THROW ? saved->exception : NULL; if (saved->user_handler && saved->user_handler != EG(user_error_handler)) { if (EG(user_error_handler)) { zval_ptr_dtor(&EG(user_error_handler)); } EG(user_error_handler) = saved->user_handler; } else if (saved->user_handler) { zval_ptr_dtor(&saved->user_handler); } saved->user_handler = NULL; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */ /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2012 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | Andrei Zmievski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "zend.h" #include "zend_execute.h" #include "zend_API.h" #include "zend_modules.h" #include "zend_constants.h" #include "zend_exceptions.h" #include "zend_closures.h" #ifdef HAVE_STDARG_H #include <stdarg.h> #endif /* these variables are true statics/globals, and have to be mutex'ed on every access */ static int module_count=0; ZEND_API HashTable module_registry; static zend_module_entry **module_request_startup_handlers; static zend_module_entry **module_request_shutdown_handlers; static zend_module_entry **module_post_deactivate_handlers; static zend_class_entry **class_cleanup_handlers; /* this function doesn't check for too many parameters */ ZEND_API int zend_get_parameters(int ht, int param_count, ...) /* {{{ */ { void **p; int arg_count; va_list ptr; zval **param, *param_ptr; TSRMLS_FETCH(); p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } va_start(ptr, param_count); while (param_count-->0) { param = va_arg(ptr, zval **); param_ptr = *(p-arg_count); if (!PZVAL_IS_REF(param_ptr) && Z_REFCOUNT_P(param_ptr) > 1) { zval *new_tmp; ALLOC_ZVAL(new_tmp); *new_tmp = *param_ptr; zval_copy_ctor(new_tmp); INIT_PZVAL(new_tmp); param_ptr = new_tmp; Z_DELREF_P((zval *) *(p-arg_count)); *(p-arg_count) = param_ptr; } *param = param_ptr; arg_count--; } va_end(ptr); return SUCCESS; } /* }}} */ ZEND_API int _zend_get_parameters_array(int ht, int param_count, zval **argument_array TSRMLS_DC) /* {{{ */ { void **p; int arg_count; zval *param_ptr; p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } while (param_count-->0) { param_ptr = *(p-arg_count); if (!PZVAL_IS_REF(param_ptr) && Z_REFCOUNT_P(param_ptr) > 1) { zval *new_tmp; ALLOC_ZVAL(new_tmp); *new_tmp = *param_ptr; zval_copy_ctor(new_tmp); INIT_PZVAL(new_tmp); param_ptr = new_tmp; Z_DELREF_P((zval *) *(p-arg_count)); *(p-arg_count) = param_ptr; } *(argument_array++) = param_ptr; arg_count--; } return SUCCESS; } /* }}} */ /* Zend-optimized Extended functions */ /* this function doesn't check for too many parameters */ ZEND_API int zend_get_parameters_ex(int param_count, ...) /* {{{ */ { void **p; int arg_count; va_list ptr; zval ***param; TSRMLS_FETCH(); p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } va_start(ptr, param_count); while (param_count-->0) { param = va_arg(ptr, zval ***); *param = (zval **) p-(arg_count--); } va_end(ptr); return SUCCESS; } /* }}} */ ZEND_API int _zend_get_parameters_array_ex(int param_count, zval ***argument_array TSRMLS_DC) /* {{{ */ { void **p; int arg_count; p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } while (param_count-->0) { zval **value = (zval**)(p-arg_count); *(argument_array++) = value; arg_count--; } return SUCCESS; } /* }}} */ ZEND_API int zend_copy_parameters_array(int param_count, zval *argument_array TSRMLS_DC) /* {{{ */ { void **p; int arg_count; p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } while (param_count-->0) { zval **param = (zval **) p-(arg_count--); zval_add_ref(param); add_next_index_zval(argument_array, *param); } return SUCCESS; } /* }}} */ ZEND_API void zend_wrong_param_count(TSRMLS_D) /* {{{ */ { const char *space; const char *class_name = get_active_class_name(&space TSRMLS_CC); zend_error(E_WARNING, "Wrong parameter count for %s%s%s()", class_name, space, get_active_function_name(TSRMLS_C)); } /* }}} */ /* Argument parsing API -- andrei */ ZEND_API char *zend_get_type_by_const(int type) /* {{{ */ { switch(type) { case IS_BOOL: return "boolean"; case IS_LONG: return "integer"; case IS_DOUBLE: return "double"; case IS_STRING: return "string"; case IS_OBJECT: return "object"; case IS_RESOURCE: return "resource"; case IS_NULL: return "null"; case IS_CALLABLE: return "callable"; case IS_ARRAY: return "array"; default: return "unknown"; } } /* }}} */ ZEND_API char *zend_zval_type_name(const zval *arg) /* {{{ */ { return zend_get_type_by_const(Z_TYPE_P(arg)); } /* }}} */ ZEND_API zend_class_entry *zend_get_class_entry(const zval *zobject TSRMLS_DC) /* {{{ */ { if (Z_OBJ_HT_P(zobject)->get_class_entry) { return Z_OBJ_HT_P(zobject)->get_class_entry(zobject TSRMLS_CC); } else { zend_error(E_ERROR, "Class entry requested for an object without PHP class"); return NULL; } } /* }}} */ /* returns 1 if you need to copy result, 0 if it's already a copy */ ZEND_API int zend_get_object_classname(const zval *object, const char **class_name, zend_uint *class_name_len TSRMLS_DC) /* {{{ */ { if (Z_OBJ_HT_P(object)->get_class_name == NULL || Z_OBJ_HT_P(object)->get_class_name(object, class_name, class_name_len, 0 TSRMLS_CC) != SUCCESS) { zend_class_entry *ce = Z_OBJCE_P(object); *class_name = ce->name; *class_name_len = ce->name_length; return 1; } return 0; } /* }}} */ static int parse_arg_object_to_string(zval **arg, char **p, int *pl, int type TSRMLS_DC) /* {{{ */ { if (Z_OBJ_HANDLER_PP(arg, cast_object)) { zval *obj; ALLOC_ZVAL(obj); MAKE_COPY_ZVAL(arg, obj); if (Z_OBJ_HANDLER_P(*arg, cast_object)(*arg, obj, type TSRMLS_CC) == SUCCESS) { zval_ptr_dtor(arg); *arg = obj; *pl = Z_STRLEN_PP(arg); *p = Z_STRVAL_PP(arg); return SUCCESS; } zval_ptr_dtor(&obj); } /* Standard PHP objects */ if (Z_OBJ_HT_PP(arg) == &std_object_handlers || !Z_OBJ_HANDLER_PP(arg, cast_object)) { SEPARATE_ZVAL_IF_NOT_REF(arg); if (zend_std_cast_object_tostring(*arg, *arg, type TSRMLS_CC) == SUCCESS) { *pl = Z_STRLEN_PP(arg); *p = Z_STRVAL_PP(arg); return SUCCESS; } } if (!Z_OBJ_HANDLER_PP(arg, cast_object) && Z_OBJ_HANDLER_PP(arg, get)) { int use_copy; zval *z = Z_OBJ_HANDLER_PP(arg, get)(*arg TSRMLS_CC); Z_ADDREF_P(z); if(Z_TYPE_P(z) != IS_OBJECT) { zval_dtor(*arg); Z_TYPE_P(*arg) = IS_NULL; zend_make_printable_zval(z, *arg, &use_copy); if (!use_copy) { ZVAL_ZVAL(*arg, z, 1, 1); } *pl = Z_STRLEN_PP(arg); *p = Z_STRVAL_PP(arg); return SUCCESS; } zval_ptr_dtor(&z); } return FAILURE; } /* }}} */ static const char *zend_parse_arg_impl(int arg_num, zval **arg, va_list *va, const char **spec, char **error, int *severity TSRMLS_DC) /* {{{ */ { const char *spec_walk = *spec; char c = *spec_walk++; int return_null = 0; /* scan through modifiers */ while (1) { if (*spec_walk == '/') { SEPARATE_ZVAL_IF_NOT_REF(arg); } else if (*spec_walk == '!') { if (Z_TYPE_PP(arg) == IS_NULL) { return_null = 1; } } else { break; } spec_walk++; } switch (c) { case 'l': case 'L': { long *p = va_arg(*va, long *); switch (Z_TYPE_PP(arg)) { case IS_STRING: { double d; int type; if ((type = is_numeric_string(Z_STRVAL_PP(arg), Z_STRLEN_PP(arg), p, &d, -1)) == 0) { return "long"; } else if (type == IS_DOUBLE) { if (c == 'L') { if (d > LONG_MAX) { *p = LONG_MAX; break; } else if (d < LONG_MIN) { *p = LONG_MIN; break; } } *p = zend_dval_to_lval(d); } } break; case IS_DOUBLE: if (c == 'L') { if (Z_DVAL_PP(arg) > LONG_MAX) { *p = LONG_MAX; break; } else if (Z_DVAL_PP(arg) < LONG_MIN) { *p = LONG_MIN; break; } } case IS_NULL: case IS_LONG: case IS_BOOL: convert_to_long_ex(arg); *p = Z_LVAL_PP(arg); break; case IS_ARRAY: case IS_OBJECT: case IS_RESOURCE: default: return "long"; } } break; case 'd': { double *p = va_arg(*va, double *); switch (Z_TYPE_PP(arg)) { case IS_STRING: { long l; int type; if ((type = is_numeric_string(Z_STRVAL_PP(arg), Z_STRLEN_PP(arg), &l, p, -1)) == 0) { return "double"; } else if (type == IS_LONG) { *p = (double) l; } } break; case IS_NULL: case IS_LONG: case IS_DOUBLE: case IS_BOOL: convert_to_double_ex(arg); *p = Z_DVAL_PP(arg); break; case IS_ARRAY: case IS_OBJECT: case IS_RESOURCE: default: return "double"; } } break; case 'p': case 's': { char **p = va_arg(*va, char **); int *pl = va_arg(*va, int *); switch (Z_TYPE_PP(arg)) { case IS_NULL: if (return_null) { *p = NULL; *pl = 0; break; } /* break omitted intentionally */ case IS_STRING: case IS_LONG: case IS_DOUBLE: case IS_BOOL: convert_to_string_ex(arg); if (UNEXPECTED(Z_ISREF_PP(arg) != 0)) { /* it's dangerous to return pointers to string buffer of referenced variable, because it can be clobbered throug magic callbacks */ SEPARATE_ZVAL(arg); } *p = Z_STRVAL_PP(arg); *pl = Z_STRLEN_PP(arg); if (c == 'p' && CHECK_ZVAL_NULL_PATH(*arg)) { return "a valid path"; } break; case IS_OBJECT: if (parse_arg_object_to_string(arg, p, pl, IS_STRING TSRMLS_CC) == SUCCESS) { if (c == 'p' && CHECK_ZVAL_NULL_PATH(*arg)) { return "a valid path"; } break; } case IS_ARRAY: case IS_RESOURCE: default: return c == 's' ? "string" : "a valid path"; } } break; case 'b': { zend_bool *p = va_arg(*va, zend_bool *); switch (Z_TYPE_PP(arg)) { case IS_NULL: case IS_STRING: case IS_LONG: case IS_DOUBLE: case IS_BOOL: convert_to_boolean_ex(arg); *p = Z_BVAL_PP(arg); break; case IS_ARRAY: case IS_OBJECT: case IS_RESOURCE: default: return "boolean"; } } break; case 'r': { zval **p = va_arg(*va, zval **); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_RESOURCE) { *p = *arg; } else { return "resource"; } } break; case 'A': case 'a': { zval **p = va_arg(*va, zval **); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_ARRAY || (c == 'A' && Z_TYPE_PP(arg) == IS_OBJECT)) { *p = *arg; } else { return "array"; } } break; case 'H': case 'h': { HashTable **p = va_arg(*va, HashTable **); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_ARRAY) { *p = Z_ARRVAL_PP(arg); } else if(c == 'H' && Z_TYPE_PP(arg) == IS_OBJECT) { *p = HASH_OF(*arg); if(*p == NULL) { return "array"; } } else { return "array"; } } break; case 'o': { zval **p = va_arg(*va, zval **); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_OBJECT) { *p = *arg; } else { return "object"; } } break; case 'O': { zval **p = va_arg(*va, zval **); zend_class_entry *ce = va_arg(*va, zend_class_entry *); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_OBJECT && (!ce || instanceof_function(Z_OBJCE_PP(arg), ce TSRMLS_CC))) { *p = *arg; } else { if (ce) { return ce->name; } else { return "object"; } } } break; case 'C': { zend_class_entry **lookup, **pce = va_arg(*va, zend_class_entry **); zend_class_entry *ce_base = *pce; if (return_null) { *pce = NULL; break; } convert_to_string_ex(arg); if (zend_lookup_class(Z_STRVAL_PP(arg), Z_STRLEN_PP(arg), &lookup TSRMLS_CC) == FAILURE) { *pce = NULL; } else { *pce = *lookup; } if (ce_base) { if ((!*pce || !instanceof_function(*pce, ce_base TSRMLS_CC))) { zend_spprintf(error, 0, "to be a class name derived from %s, '%s' given", ce_base->name, Z_STRVAL_PP(arg)); *pce = NULL; return ""; } } if (!*pce) { zend_spprintf(error, 0, "to be a valid class name, '%s' given", Z_STRVAL_PP(arg)); return ""; } break; } break; case 'f': { zend_fcall_info *fci = va_arg(*va, zend_fcall_info *); zend_fcall_info_cache *fcc = va_arg(*va, zend_fcall_info_cache *); char *is_callable_error = NULL; if (return_null) { fci->size = 0; fcc->initialized = 0; break; } if (zend_fcall_info_init(*arg, 0, fci, fcc, NULL, &is_callable_error TSRMLS_CC) == SUCCESS) { if (is_callable_error) { *severity = E_STRICT; zend_spprintf(error, 0, "to be a valid callback, %s", is_callable_error); efree(is_callable_error); *spec = spec_walk; return ""; } break; } else { if (is_callable_error) { *severity = E_WARNING; zend_spprintf(error, 0, "to be a valid callback, %s", is_callable_error); efree(is_callable_error); return ""; } else { return "valid callback"; } } } case 'z': { zval **p = va_arg(*va, zval **); if (return_null) { *p = NULL; } else { *p = *arg; } } break; case 'Z': { zval ***p = va_arg(*va, zval ***); if (return_null) { *p = NULL; } else { *p = arg; } } break; default: return "unknown"; } *spec = spec_walk; return NULL; } /* }}} */ static int zend_parse_arg(int arg_num, zval **arg, va_list *va, const char **spec, int quiet TSRMLS_DC) /* {{{ */ { const char *expected_type = NULL; char *error = NULL; int severity = E_WARNING; expected_type = zend_parse_arg_impl(arg_num, arg, va, spec, &error, &severity TSRMLS_CC); if (expected_type) { if (!quiet && (*expected_type || error)) { const char *space; const char *class_name = get_active_class_name(&space TSRMLS_CC); if (error) { zend_error(severity, "%s%s%s() expects parameter %d %s", class_name, space, get_active_function_name(TSRMLS_C), arg_num, error); efree(error); } else { zend_error(severity, "%s%s%s() expects parameter %d to be %s, %s given", class_name, space, get_active_function_name(TSRMLS_C), arg_num, expected_type, zend_zval_type_name(*arg)); } } if (severity != E_STRICT) { return FAILURE; } } return SUCCESS; } /* }}} */ static int zend_parse_va_args(int num_args, const char *type_spec, va_list *va, int flags TSRMLS_DC) /* {{{ */ { const char *spec_walk; int c, i; int min_num_args = -1; int max_num_args = 0; int post_varargs = 0; zval **arg; int arg_count; int quiet = flags & ZEND_PARSE_PARAMS_QUIET; zend_bool have_varargs = 0; zval ****varargs = NULL; int *n_varargs = NULL; for (spec_walk = type_spec; *spec_walk; spec_walk++) { c = *spec_walk; switch (c) { case 'l': case 'd': case 's': case 'b': case 'r': case 'a': case 'o': case 'O': case 'z': case 'Z': case 'C': case 'h': case 'f': case 'A': case 'H': case 'p': max_num_args++; break; case '|': min_num_args = max_num_args; break; case '/': case '!': /* Pass */ break; case '*': case '+': if (have_varargs) { if (!quiet) { zend_function *active_function = EG(current_execute_data)->function_state.function; const char *class_name = active_function->common.scope ? active_function->common.scope->name : ""; zend_error(E_WARNING, "%s%s%s(): only one varargs specifier (* or +) is permitted", class_name, class_name[0] ? "::" : "", active_function->common.function_name); } return FAILURE; } have_varargs = 1; /* we expect at least one parameter in varargs */ if (c == '+') { max_num_args++; } /* mark the beginning of varargs */ post_varargs = max_num_args; break; default: if (!quiet) { zend_function *active_function = EG(current_execute_data)->function_state.function; const char *class_name = active_function->common.scope ? active_function->common.scope->name : ""; zend_error(E_WARNING, "%s%s%s(): bad type specifier while parsing parameters", class_name, class_name[0] ? "::" : "", active_function->common.function_name); } return FAILURE; } } if (min_num_args < 0) { min_num_args = max_num_args; } if (have_varargs) { /* calculate how many required args are at the end of the specifier list */ post_varargs = max_num_args - post_varargs; max_num_args = -1; } if (num_args < min_num_args || (num_args > max_num_args && max_num_args > 0)) { if (!quiet) { zend_function *active_function = EG(current_execute_data)->function_state.function; const char *class_name = active_function->common.scope ? active_function->common.scope->name : ""; zend_error(E_WARNING, "%s%s%s() expects %s %d parameter%s, %d given", class_name, class_name[0] ? "::" : "", active_function->common.function_name, min_num_args == max_num_args ? "exactly" : num_args < min_num_args ? "at least" : "at most", num_args < min_num_args ? min_num_args : max_num_args, (num_args < min_num_args ? min_num_args : max_num_args) == 1 ? "" : "s", num_args); } return FAILURE; } arg_count = (int)(zend_uintptr_t) *(zend_vm_stack_top(TSRMLS_C) - 1); if (num_args > arg_count) { zend_error(E_WARNING, "%s(): could not obtain parameters for parsing", get_active_function_name(TSRMLS_C)); return FAILURE; } i = 0; while (num_args-- > 0) { if (*type_spec == '|') { type_spec++; } if (*type_spec == '*' || *type_spec == '+') { int num_varargs = num_args + 1 - post_varargs; /* eat up the passed in storage even if it won't be filled in with varargs */ varargs = va_arg(*va, zval ****); n_varargs = va_arg(*va, int *); type_spec++; if (num_varargs > 0) { int iv = 0; zval **p = (zval **) (zend_vm_stack_top(TSRMLS_C) - 1 - (arg_count - i)); *n_varargs = num_varargs; /* allocate space for array and store args */ *varargs = safe_emalloc(num_varargs, sizeof(zval **), 0); while (num_varargs-- > 0) { (*varargs)[iv++] = p++; } /* adjust how many args we have left and restart loop */ num_args = num_args + 1 - iv; i += iv; continue; } else { *varargs = NULL; *n_varargs = 0; } } arg = (zval **) (zend_vm_stack_top(TSRMLS_C) - 1 - (arg_count-i)); if (zend_parse_arg(i+1, arg, va, &type_spec, quiet TSRMLS_CC) == FAILURE) { /* clean up varargs array if it was used */ if (varargs && *varargs) { efree(*varargs); *varargs = NULL; } return FAILURE; } i++; } return SUCCESS; } /* }}} */ #define RETURN_IF_ZERO_ARGS(num_args, type_spec, quiet) { \ int __num_args = (num_args); \ \ if (0 == (type_spec)[0] && 0 != __num_args && !(quiet)) { \ const char *__space; \ const char * __class_name = get_active_class_name(&__space TSRMLS_CC); \ zend_error(E_WARNING, "%s%s%s() expects exactly 0 parameters, %d given", \ __class_name, __space, \ get_active_function_name(TSRMLS_C), __num_args); \ return FAILURE; \ }\ } ZEND_API int zend_parse_parameters_ex(int flags, int num_args TSRMLS_DC, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; RETURN_IF_ZERO_ARGS(num_args, type_spec, flags & ZEND_PARSE_PARAMS_QUIET); va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, flags TSRMLS_CC); va_end(va); return retval; } /* }}} */ ZEND_API int zend_parse_parameters(int num_args TSRMLS_DC, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; RETURN_IF_ZERO_ARGS(num_args, type_spec, 0); va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, 0 TSRMLS_CC); va_end(va); return retval; } /* }}} */ ZEND_API int zend_parse_method_parameters(int num_args TSRMLS_DC, zval *this_ptr, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; const char *p = type_spec; zval **object; zend_class_entry *ce; if (!this_ptr) { RETURN_IF_ZERO_ARGS(num_args, p, 0); va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, 0 TSRMLS_CC); va_end(va); } else { p++; RETURN_IF_ZERO_ARGS(num_args, p, 0); va_start(va, type_spec); object = va_arg(va, zval **); ce = va_arg(va, zend_class_entry *); *object = this_ptr; if (ce && !instanceof_function(Z_OBJCE_P(this_ptr), ce TSRMLS_CC)) { zend_error(E_CORE_ERROR, "%s::%s() must be derived from %s::%s", ce->name, get_active_function_name(TSRMLS_C), Z_OBJCE_P(this_ptr)->name, get_active_function_name(TSRMLS_C)); } retval = zend_parse_va_args(num_args, p, &va, 0 TSRMLS_CC); va_end(va); } return retval; } /* }}} */ ZEND_API int zend_parse_method_parameters_ex(int flags, int num_args TSRMLS_DC, zval *this_ptr, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; const char *p = type_spec; zval **object; zend_class_entry *ce; int quiet = flags & ZEND_PARSE_PARAMS_QUIET; if (!this_ptr) { RETURN_IF_ZERO_ARGS(num_args, p, quiet); va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, flags TSRMLS_CC); va_end(va); } else { p++; RETURN_IF_ZERO_ARGS(num_args, p, quiet); va_start(va, type_spec); object = va_arg(va, zval **); ce = va_arg(va, zend_class_entry *); *object = this_ptr; if (ce && !instanceof_function(Z_OBJCE_P(this_ptr), ce TSRMLS_CC)) { if (!quiet) { zend_error(E_CORE_ERROR, "%s::%s() must be derived from %s::%s", ce->name, get_active_function_name(TSRMLS_C), Z_OBJCE_P(this_ptr)->name, get_active_function_name(TSRMLS_C)); } va_end(va); return FAILURE; } retval = zend_parse_va_args(num_args, p, &va, flags TSRMLS_CC); va_end(va); } return retval; } /* }}} */ /* Argument parsing API -- andrei */ ZEND_API int _array_init(zval *arg, uint size ZEND_FILE_LINE_DC) /* {{{ */ { ALLOC_HASHTABLE_REL(Z_ARRVAL_P(arg)); _zend_hash_init(Z_ARRVAL_P(arg), size, NULL, ZVAL_PTR_DTOR, 0 ZEND_FILE_LINE_RELAY_CC); Z_TYPE_P(arg) = IS_ARRAY; return SUCCESS; } /* }}} */ static int zend_merge_property(zval **value TSRMLS_DC, int num_args, va_list args, const zend_hash_key *hash_key) /* {{{ */ { /* which name should a numeric property have ? */ if (hash_key->nKeyLength) { zval *obj = va_arg(args, zval *); zend_object_handlers *obj_ht = va_arg(args, zend_object_handlers *); zval *member; MAKE_STD_ZVAL(member); ZVAL_STRINGL(member, hash_key->arKey, hash_key->nKeyLength-1, 1); obj_ht->write_property(obj, member, *value, 0 TSRMLS_CC); zval_ptr_dtor(&member); } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* This function should be called after the constructor has been called * because it may call __set from the uninitialized object otherwise. */ ZEND_API void zend_merge_properties(zval *obj, HashTable *properties, int destroy_ht TSRMLS_DC) /* {{{ */ { const zend_object_handlers *obj_ht = Z_OBJ_HT_P(obj); zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE_P(obj); zend_hash_apply_with_arguments(properties TSRMLS_CC, (apply_func_args_t)zend_merge_property, 2, obj, obj_ht); EG(scope) = old_scope; if (destroy_ht) { zend_hash_destroy(properties); FREE_HASHTABLE(properties); } } /* }}} */ ZEND_API void zend_update_class_constants(zend_class_entry *class_type TSRMLS_DC) /* {{{ */ { if ((class_type->ce_flags & ZEND_ACC_CONSTANTS_UPDATED) == 0 || (!CE_STATIC_MEMBERS(class_type) && class_type->default_static_members_count)) { zend_class_entry **scope = EG(in_execution)?&EG(scope):&CG(active_class_entry); zend_class_entry *old_scope = *scope; int i; *scope = class_type; zend_hash_apply_with_argument(&class_type->constants_table, (apply_func_arg_t) zval_update_constant, (void*)1 TSRMLS_CC); for (i = 0; i < class_type->default_properties_count; i++) { if (class_type->default_properties_table[i]) { zval_update_constant(&class_type->default_properties_table[i], (void**)1 TSRMLS_CC); } } if (!CE_STATIC_MEMBERS(class_type) && class_type->default_static_members_count) { zval **p; if (class_type->parent) { zend_update_class_constants(class_type->parent TSRMLS_CC); } #if ZTS CG(static_members_table)[(zend_intptr_t)(class_type->static_members_table)] = emalloc(sizeof(zval*) * class_type->default_static_members_count); #else class_type->static_members_table = emalloc(sizeof(zval*) * class_type->default_static_members_count); #endif for (i = 0; i < class_type->default_static_members_count; i++) { p = &class_type->default_static_members_table[i]; if (Z_ISREF_PP(p) && class_type->parent && i < class_type->parent->default_static_members_count && *p == class_type->parent->default_static_members_table[i] && CE_STATIC_MEMBERS(class_type->parent)[i] ) { zval *q = CE_STATIC_MEMBERS(class_type->parent)[i]; Z_ADDREF_P(q); Z_SET_ISREF_P(q); CE_STATIC_MEMBERS(class_type)[i] = q; } else { zval *r; ALLOC_ZVAL(r); *r = **p; INIT_PZVAL(r); zval_copy_ctor(r); CE_STATIC_MEMBERS(class_type)[i] = r; } } } for (i = 0; i < class_type->default_static_members_count; i++) { zval_update_constant(&CE_STATIC_MEMBERS(class_type)[i], (void**)1 TSRMLS_CC); } *scope = old_scope; class_type->ce_flags |= ZEND_ACC_CONSTANTS_UPDATED; } } /* }}} */ ZEND_API void object_properties_init(zend_object *object, zend_class_entry *class_type) /* {{{ */ { int i; if (class_type->default_properties_count) { object->properties_table = emalloc(sizeof(zval*) * class_type->default_properties_count); for (i = 0; i < class_type->default_properties_count; i++) { object->properties_table[i] = class_type->default_properties_table[i]; if (class_type->default_properties_table[i]) { Z_ADDREF_P(object->properties_table[i]); } } object->properties = NULL; } } /* }}} */ /* This function requires 'properties' to contain all props declared in the * class and all props being public. If only a subset is given or the class * has protected members then you need to merge the properties seperately by * calling zend_merge_properties(). */ ZEND_API int _object_and_properties_init(zval *arg, zend_class_entry *class_type, HashTable *properties ZEND_FILE_LINE_DC TSRMLS_DC) /* {{{ */ { zend_object *object; if (class_type->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLICIT_ABSTRACT_CLASS|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) { char *what = (class_type->ce_flags & ZEND_ACC_INTERFACE) ? "interface" :((class_type->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) ? "trait" : "abstract class"; zend_error(E_ERROR, "Cannot instantiate %s %s", what, class_type->name); } zend_update_class_constants(class_type TSRMLS_CC); Z_TYPE_P(arg) = IS_OBJECT; if (class_type->create_object == NULL) { Z_OBJVAL_P(arg) = zend_objects_new(&object, class_type TSRMLS_CC); if (properties) { object->properties = properties; object->properties_table = NULL; } else { object_properties_init(object, class_type); } } else { Z_OBJVAL_P(arg) = class_type->create_object(class_type TSRMLS_CC); } return SUCCESS; } /* }}} */ ZEND_API int _object_init_ex(zval *arg, zend_class_entry *class_type ZEND_FILE_LINE_DC TSRMLS_DC) /* {{{ */ { return _object_and_properties_init(arg, class_type, 0 ZEND_FILE_LINE_RELAY_CC TSRMLS_CC); } /* }}} */ ZEND_API int _object_init(zval *arg ZEND_FILE_LINE_DC TSRMLS_DC) /* {{{ */ { return _object_init_ex(arg, zend_standard_class_def ZEND_FILE_LINE_RELAY_CC TSRMLS_CC); } /* }}} */ ZEND_API int add_assoc_function(zval *arg, const char *key, void (*function_ptr)(INTERNAL_FUNCTION_PARAMETERS)) /* {{{ */ { zend_error(E_WARNING, "add_assoc_function() is no longer supported"); return FAILURE; } /* }}} */ ZEND_API int add_assoc_long_ex(zval *arg, const char *key, uint key_len, long n) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, n); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_null_ex(zval *arg, const char *key, uint key_len) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_NULL(tmp); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_bool_ex(zval *arg, const char *key, uint key_len, int b) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_BOOL(tmp, b); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_resource_ex(zval *arg, const char *key, uint key_len, int r) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_RESOURCE(tmp, r); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_double_ex(zval *arg, const char *key, uint key_len, double d) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_string_ex(zval *arg, const char *key, uint key_len, char *str, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_stringl_ex(zval *arg, const char *key, uint key_len, char *str, uint length, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_zval_ex(zval *arg, const char *key, uint key_len, zval *value) /* {{{ */ { return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &value, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_long(zval *arg, ulong index, long n) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, n); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_null(zval *arg, ulong index) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_NULL(tmp); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_bool(zval *arg, ulong index, int b) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_BOOL(tmp, b); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_resource(zval *arg, ulong index, int r) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_RESOURCE(tmp, r); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_double(zval *arg, ulong index, double d) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_string(zval *arg, ulong index, const char *str, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_stringl(zval *arg, ulong index, const char *str, uint length, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_zval(zval *arg, ulong index, zval *value) /* {{{ */ { return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &value, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_long(zval *arg, long n) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, n); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_null(zval *arg) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_NULL(tmp); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_bool(zval *arg, int b) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_BOOL(tmp, b); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_resource(zval *arg, int r) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_RESOURCE(tmp, r); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_double(zval *arg, double d) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_string(zval *arg, const char *str, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_stringl(zval *arg, const char *str, uint length, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_zval(zval *arg, zval *value) /* {{{ */ { return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &value, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_get_assoc_string_ex(zval *arg, const char *key, uint key_len, const char *str, void **dest, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_assoc_stringl_ex(zval *arg, const char *key, uint key_len, const char *str, uint length, void **dest, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_index_long(zval *arg, ulong index, long l, void **dest) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, l); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_index_double(zval *arg, ulong index, double d, void **dest) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_index_string(zval *arg, ulong index, const char *str, void **dest, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_index_stringl(zval *arg, ulong index, const char *str, uint length, void **dest, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_property_long_ex(zval *arg, const char *key, uint key_len, long n TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, n); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_bool_ex(zval *arg, const char *key, uint key_len, int b TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_BOOL(tmp, b); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_null_ex(zval *arg, const char *key, uint key_len TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_NULL(tmp); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_resource_ex(zval *arg, const char *key, uint key_len, long n TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_RESOURCE(tmp, n); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_double_ex(zval *arg, const char *key, uint key_len, double d TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_string_ex(zval *arg, const char *key, uint key_len, const char *str, int duplicate TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_stringl_ex(zval *arg, const char *key, uint key_len, const char *str, uint length, int duplicate TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_zval_ex(zval *arg, const char *key, uint key_len, zval *value TSRMLS_DC) /* {{{ */ { zval *z_key; MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, value, 0 TSRMLS_CC); zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int zend_startup_module_ex(zend_module_entry *module TSRMLS_DC) /* {{{ */ { int name_len; char *lcname; if (module->module_started) { return SUCCESS; } module->module_started = 1; /* Check module dependencies */ if (module->deps) { const zend_module_dep *dep = module->deps; while (dep->name) { if (dep->type == MODULE_DEP_REQUIRED) { zend_module_entry *req_mod; name_len = strlen(dep->name); lcname = zend_str_tolower_dup(dep->name, name_len); if (zend_hash_find(&module_registry, lcname, name_len+1, (void**)&req_mod) == FAILURE || !req_mod->module_started) { efree(lcname); /* TODO: Check version relationship */ zend_error(E_CORE_WARNING, "Cannot load module '%s' because required module '%s' is not loaded", module->name, dep->name); module->module_started = 0; return FAILURE; } efree(lcname); } ++dep; } } /* Initialize module globals */ if (module->globals_size) { #ifdef ZTS ts_allocate_id(module->globals_id_ptr, module->globals_size, (ts_allocate_ctor) module->globals_ctor, (ts_allocate_dtor) module->globals_dtor); #else if (module->globals_ctor) { module->globals_ctor(module->globals_ptr TSRMLS_CC); } #endif } if (module->module_startup_func) { EG(current_module) = module; if (module->module_startup_func(module->type, module->module_number TSRMLS_CC)==FAILURE) { zend_error(E_CORE_ERROR,"Unable to start %s module", module->name); EG(current_module) = NULL; return FAILURE; } EG(current_module) = NULL; } return SUCCESS; } /* }}} */ static void zend_sort_modules(void *base, size_t count, size_t siz, compare_func_t compare TSRMLS_DC) /* {{{ */ { Bucket **b1 = base; Bucket **b2; Bucket **end = b1 + count; Bucket *tmp; zend_module_entry *m, *r; while (b1 < end) { try_again: m = (zend_module_entry*)(*b1)->pData; if (!m->module_started && m->deps) { const zend_module_dep *dep = m->deps; while (dep->name) { if (dep->type == MODULE_DEP_REQUIRED || dep->type == MODULE_DEP_OPTIONAL) { b2 = b1 + 1; while (b2 < end) { r = (zend_module_entry*)(*b2)->pData; if (strcasecmp(dep->name, r->name) == 0) { tmp = *b1; *b1 = *b2; *b2 = tmp; goto try_again; } b2++; } } dep++; } } b1++; } } /* }}} */ ZEND_API void zend_collect_module_handlers(TSRMLS_D) /* {{{ */ { HashPosition pos; zend_module_entry *module; int startup_count = 0; int shutdown_count = 0; int post_deactivate_count = 0; zend_class_entry **pce; int class_count = 0; /* Collect extensions with request startup/shutdown handlers */ for (zend_hash_internal_pointer_reset_ex(&module_registry, &pos); zend_hash_get_current_data_ex(&module_registry, (void *) &module, &pos) == SUCCESS; zend_hash_move_forward_ex(&module_registry, &pos)) { if (module->request_startup_func) { startup_count++; } if (module->request_shutdown_func) { shutdown_count++; } if (module->post_deactivate_func) { post_deactivate_count++; } } module_request_startup_handlers = (zend_module_entry**)malloc( sizeof(zend_module_entry*) * (startup_count + 1 + shutdown_count + 1 + post_deactivate_count + 1)); module_request_startup_handlers[startup_count] = NULL; module_request_shutdown_handlers = module_request_startup_handlers + startup_count + 1; module_request_shutdown_handlers[shutdown_count] = NULL; module_post_deactivate_handlers = module_request_shutdown_handlers + shutdown_count + 1; module_post_deactivate_handlers[post_deactivate_count] = NULL; startup_count = 0; for (zend_hash_internal_pointer_reset_ex(&module_registry, &pos); zend_hash_get_current_data_ex(&module_registry, (void *) &module, &pos) == SUCCESS; zend_hash_move_forward_ex(&module_registry, &pos)) { if (module->request_startup_func) { module_request_startup_handlers[startup_count++] = module; } if (module->request_shutdown_func) { module_request_shutdown_handlers[--shutdown_count] = module; } if (module->post_deactivate_func) { module_post_deactivate_handlers[--post_deactivate_count] = module; } } /* Collect internal classes with static members */ for (zend_hash_internal_pointer_reset_ex(CG(class_table), &pos); zend_hash_get_current_data_ex(CG(class_table), (void *) &pce, &pos) == SUCCESS; zend_hash_move_forward_ex(CG(class_table), &pos)) { if ((*pce)->type == ZEND_INTERNAL_CLASS && (*pce)->default_static_members_count > 0) { class_count++; } } class_cleanup_handlers = (zend_class_entry**)malloc( sizeof(zend_class_entry*) * (class_count + 1)); class_cleanup_handlers[class_count] = NULL; if (class_count) { for (zend_hash_internal_pointer_reset_ex(CG(class_table), &pos); zend_hash_get_current_data_ex(CG(class_table), (void *) &pce, &pos) == SUCCESS; zend_hash_move_forward_ex(CG(class_table), &pos)) { if ((*pce)->type == ZEND_INTERNAL_CLASS && (*pce)->default_static_members_count > 0) { class_cleanup_handlers[--class_count] = *pce; } } } } /* }}} */ ZEND_API int zend_startup_modules(TSRMLS_D) /* {{{ */ { zend_hash_sort(&module_registry, zend_sort_modules, NULL, 0 TSRMLS_CC); zend_hash_apply(&module_registry, (apply_func_t)zend_startup_module_ex TSRMLS_CC); return SUCCESS; } /* }}} */ ZEND_API void zend_destroy_modules(void) /* {{{ */ { free(class_cleanup_handlers); free(module_request_startup_handlers); zend_hash_graceful_reverse_destroy(&module_registry); } /* }}} */ ZEND_API zend_module_entry* zend_register_module_ex(zend_module_entry *module TSRMLS_DC) /* {{{ */ { int name_len; char *lcname; zend_module_entry *module_ptr; if (!module) { return NULL; } #if 0 zend_printf("%s: Registering module %d\n", module->name, module->module_number); #endif /* Check module dependencies */ if (module->deps) { const zend_module_dep *dep = module->deps; while (dep->name) { if (dep->type == MODULE_DEP_CONFLICTS) { name_len = strlen(dep->name); lcname = zend_str_tolower_dup(dep->name, name_len); if (zend_hash_exists(&module_registry, lcname, name_len+1)) { efree(lcname); /* TODO: Check version relationship */ zend_error(E_CORE_WARNING, "Cannot load module '%s' because conflicting module '%s' is already loaded", module->name, dep->name); return NULL; } efree(lcname); } ++dep; } } name_len = strlen(module->name); lcname = zend_str_tolower_dup(module->name, name_len); if (zend_hash_add(&module_registry, lcname, name_len+1, (void *)module, sizeof(zend_module_entry), (void**)&module_ptr)==FAILURE) { zend_error(E_CORE_WARNING, "Module '%s' already loaded", module->name); efree(lcname); return NULL; } efree(lcname); module = module_ptr; EG(current_module) = module; if (module->functions && zend_register_functions(NULL, module->functions, NULL, module->type TSRMLS_CC)==FAILURE) { EG(current_module) = NULL; zend_error(E_CORE_WARNING,"%s: Unable to register functions, unable to load", module->name); return NULL; } EG(current_module) = NULL; return module; } /* }}} */ ZEND_API zend_module_entry* zend_register_internal_module(zend_module_entry *module TSRMLS_DC) /* {{{ */ { module->module_number = zend_next_free_module(); module->type = MODULE_PERSISTENT; return zend_register_module_ex(module TSRMLS_CC); } /* }}} */ ZEND_API void zend_check_magic_method_implementation(const zend_class_entry *ce, const zend_function *fptr, int error_type TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(fptr->common.function_name); zend_str_tolower_copy(lcname, fptr->common.function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)) && fptr->common.num_args != 0) { zend_error(error_type, "Destructor %s::%s() cannot take arguments", ce->name, ZEND_DESTRUCTOR_FUNC_NAME); } else if (name_len == sizeof(ZEND_CLONE_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)) && fptr->common.num_args != 0) { zend_error(error_type, "Method %s::%s() cannot accept any arguments", ce->name, ZEND_CLONE_FUNC_NAME); } else if (name_len == sizeof(ZEND_GET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME))) { if (fptr->common.num_args != 1) { zend_error(error_type, "Method %s::%s() must take exactly 1 argument", ce->name, ZEND_GET_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_GET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_SET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME))) { if (fptr->common.num_args != 2) { zend_error(error_type, "Method %s::%s() must take exactly 2 arguments", ce->name, ZEND_SET_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1) || ARG_SHOULD_BE_SENT_BY_REF(fptr, 2)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_SET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_UNSET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME))) { if (fptr->common.num_args != 1) { zend_error(error_type, "Method %s::%s() must take exactly 1 argument", ce->name, ZEND_UNSET_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_UNSET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_ISSET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME))) { if (fptr->common.num_args != 1) { zend_error(error_type, "Method %s::%s() must take exactly 1 argument", ce->name, ZEND_ISSET_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_ISSET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_CALL_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME))) { if (fptr->common.num_args != 2) { zend_error(error_type, "Method %s::%s() must take exactly 2 arguments", ce->name, ZEND_CALL_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1) || ARG_SHOULD_BE_SENT_BY_REF(fptr, 2)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_CALL_FUNC_NAME); } } else if (name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) ) { if (fptr->common.num_args != 2) { zend_error(error_type, "Method %s::%s() must take exactly 2 arguments", ce->name, ZEND_CALLSTATIC_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1) || ARG_SHOULD_BE_SENT_BY_REF(fptr, 2)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_CALLSTATIC_FUNC_NAME); } } else if (name_len == sizeof(ZEND_TOSTRING_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && fptr->common.num_args != 0 ) { zend_error(error_type, "Method %s::%s() cannot take arguments", ce->name, ZEND_TOSTRING_FUNC_NAME); } } /* }}} */ /* registers all functions in *library_functions in the function hash */ ZEND_API int zend_register_functions(zend_class_entry *scope, const zend_function_entry *functions, HashTable *function_table, int type TSRMLS_DC) /* {{{ */ { const zend_function_entry *ptr = functions; zend_function function, *reg_function; zend_internal_function *internal_function = (zend_internal_function *)&function; int count=0, unload=0, result=0; HashTable *target_function_table = function_table; int error_type; zend_function *ctor = NULL, *dtor = NULL, *clone = NULL, *__get = NULL, *__set = NULL, *__unset = NULL, *__isset = NULL, *__call = NULL, *__callstatic = NULL, *__tostring = NULL; const char *lowercase_name; int fname_len; const char *lc_class_name = NULL; int class_name_len = 0; if (type==MODULE_PERSISTENT) { error_type = E_CORE_WARNING; } else { error_type = E_WARNING; } if (!target_function_table) { target_function_table = CG(function_table); } internal_function->type = ZEND_INTERNAL_FUNCTION; internal_function->module = EG(current_module); if (scope) { class_name_len = strlen(scope->name); if ((lc_class_name = zend_memrchr(scope->name, '\\', class_name_len))) { ++lc_class_name; class_name_len -= (lc_class_name - scope->name); lc_class_name = zend_str_tolower_dup(lc_class_name, class_name_len); } else { lc_class_name = zend_str_tolower_dup(scope->name, class_name_len); } } while (ptr->fname) { internal_function->handler = ptr->handler; internal_function->function_name = (char*)ptr->fname; internal_function->scope = scope; internal_function->prototype = NULL; if (ptr->flags) { if (!(ptr->flags & ZEND_ACC_PPP_MASK)) { if (ptr->flags != ZEND_ACC_DEPRECATED || scope) { zend_error(error_type, "Invalid access level for %s%s%s() - access must be exactly one of public, protected or private", scope ? scope->name : "", scope ? "::" : "", ptr->fname); } internal_function->fn_flags = ZEND_ACC_PUBLIC | ptr->flags; } else { internal_function->fn_flags = ptr->flags; } } else { internal_function->fn_flags = ZEND_ACC_PUBLIC; } if (ptr->arg_info) { zend_internal_function_info *info = (zend_internal_function_info*)ptr->arg_info; internal_function->arg_info = (zend_arg_info*)ptr->arg_info+1; internal_function->num_args = ptr->num_args; /* Currently you cannot denote that the function can accept less arguments than num_args */ if (info->required_num_args == -1) { internal_function->required_num_args = ptr->num_args; } else { internal_function->required_num_args = info->required_num_args; } if (info->pass_rest_by_reference) { if (info->pass_rest_by_reference == ZEND_SEND_PREFER_REF) { internal_function->fn_flags |= ZEND_ACC_PASS_REST_PREFER_REF; } else { internal_function->fn_flags |= ZEND_ACC_PASS_REST_BY_REFERENCE; } } if (info->return_reference) { internal_function->fn_flags |= ZEND_ACC_RETURN_REFERENCE; } } else { internal_function->arg_info = NULL; internal_function->num_args = 0; internal_function->required_num_args = 0; } if (ptr->flags & ZEND_ACC_ABSTRACT) { if (scope) { /* This is a class that must be abstract itself. Here we set the check info. */ scope->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; if (!(scope->ce_flags & ZEND_ACC_INTERFACE)) { /* Since the class is not an interface it needs to be declared as a abstract class. */ /* Since here we are handling internal functions only we can add the keyword flag. */ /* This time we set the flag for the keyword 'abstract'. */ scope->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } } if (ptr->flags & ZEND_ACC_STATIC && (!scope || !(scope->ce_flags & ZEND_ACC_INTERFACE))) { zend_error(error_type, "Static function %s%s%s() cannot be abstract", scope ? scope->name : "", scope ? "::" : "", ptr->fname); } } else { if (scope && (scope->ce_flags & ZEND_ACC_INTERFACE)) { efree((char*)lc_class_name); zend_error(error_type, "Interface %s cannot contain non abstract method %s()", scope->name, ptr->fname); return FAILURE; } if (!internal_function->handler) { if (scope) { efree((char*)lc_class_name); } zend_error(error_type, "Method %s%s%s() cannot be a NULL function", scope ? scope->name : "", scope ? "::" : "", ptr->fname); zend_unregister_functions(functions, count, target_function_table TSRMLS_CC); return FAILURE; } } fname_len = strlen(ptr->fname); lowercase_name = zend_new_interned_string(zend_str_tolower_dup(ptr->fname, fname_len), fname_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lowercase_name)) { result = zend_hash_quick_add(target_function_table, lowercase_name, fname_len+1, INTERNED_HASH(lowercase_name), &function, sizeof(zend_function), (void**)&reg_function); } else { result = zend_hash_add(target_function_table, lowercase_name, fname_len+1, &function, sizeof(zend_function), (void**)&reg_function); } if (result == FAILURE) { unload=1; str_efree(lowercase_name); break; } if (scope) { /* Look for ctor, dtor, clone * If it's an old-style constructor, store it only if we don't have * a constructor already. */ if ((fname_len == class_name_len) && !ctor && !memcmp(lowercase_name, lc_class_name, class_name_len+1)) { ctor = reg_function; } else if ((fname_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME))) { ctor = reg_function; } else if ((fname_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME))) { dtor = reg_function; if (internal_function->num_args) { zend_error(error_type, "Destructor %s::%s() cannot take arguments", scope->name, ptr->fname); } } else if ((fname_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME))) { clone = reg_function; } else if ((fname_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME))) { __call = reg_function; } else if ((fname_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME))) { __callstatic = reg_function; } else if ((fname_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME))) { __tostring = reg_function; } else if ((fname_len == sizeof(ZEND_GET_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME))) { __get = reg_function; } else if ((fname_len == sizeof(ZEND_SET_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME))) { __set = reg_function; } else if ((fname_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME))) { __unset = reg_function; } else if ((fname_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME))) { __isset = reg_function; } else { reg_function = NULL; } if (reg_function) { zend_check_magic_method_implementation(scope, reg_function, error_type TSRMLS_CC); } } ptr++; count++; str_efree(lowercase_name); } if (unload) { /* before unloading, display all remaining bad function in the module */ if (scope) { efree((char*)lc_class_name); } while (ptr->fname) { fname_len = strlen(ptr->fname); lowercase_name = zend_str_tolower_dup(ptr->fname, fname_len); if (zend_hash_exists(target_function_table, lowercase_name, fname_len+1)) { zend_error(error_type, "Function registration failed - duplicate name - %s%s%s", scope ? scope->name : "", scope ? "::" : "", ptr->fname); } efree((char*)lowercase_name); ptr++; } zend_unregister_functions(functions, count, target_function_table TSRMLS_CC); return FAILURE; } if (scope) { scope->constructor = ctor; scope->destructor = dtor; scope->clone = clone; scope->__call = __call; scope->__callstatic = __callstatic; scope->__tostring = __tostring; scope->__get = __get; scope->__set = __set; scope->__unset = __unset; scope->__isset = __isset; if (ctor) { ctor->common.fn_flags |= ZEND_ACC_CTOR; if (ctor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Constructor %s::%s() cannot be static", scope->name, ctor->common.function_name); } ctor->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (dtor) { dtor->common.fn_flags |= ZEND_ACC_DTOR; if (dtor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Destructor %s::%s() cannot be static", scope->name, dtor->common.function_name); } dtor->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (clone) { clone->common.fn_flags |= ZEND_ACC_CLONE; if (clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Constructor %s::%s() cannot be static", scope->name, clone->common.function_name); } clone->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__call) { if (__call->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __call->common.function_name); } __call->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__callstatic) { if (!(__callstatic->common.fn_flags & ZEND_ACC_STATIC)) { zend_error(error_type, "Method %s::%s() must be static", scope->name, __callstatic->common.function_name); } __callstatic->common.fn_flags |= ZEND_ACC_STATIC; } if (__tostring) { if (__tostring->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __tostring->common.function_name); } __tostring->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__get) { if (__get->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __get->common.function_name); } __get->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__set) { if (__set->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __set->common.function_name); } __set->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__unset) { if (__unset->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __unset->common.function_name); } __unset->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__isset) { if (__isset->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __isset->common.function_name); } __isset->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } efree((char*)lc_class_name); } return SUCCESS; } /* }}} */ /* count=-1 means erase all functions, otherwise, * erase the first count functions */ ZEND_API void zend_unregister_functions(const zend_function_entry *functions, int count, HashTable *function_table TSRMLS_DC) /* {{{ */ { const zend_function_entry *ptr = functions; int i=0; HashTable *target_function_table = function_table; if (!target_function_table) { target_function_table = CG(function_table); } while (ptr->fname) { if (count!=-1 && i>=count) { break; } #if 0 zend_printf("Unregistering %s()\n", ptr->fname); #endif zend_hash_del(target_function_table, ptr->fname, strlen(ptr->fname)+1); ptr++; i++; } } /* }}} */ ZEND_API int zend_startup_module(zend_module_entry *module) /* {{{ */ { TSRMLS_FETCH(); if ((module = zend_register_internal_module(module TSRMLS_CC)) != NULL && zend_startup_module_ex(module TSRMLS_CC) == SUCCESS) { return SUCCESS; } return FAILURE; } /* }}} */ ZEND_API int zend_get_module_started(const char *module_name) /* {{{ */ { zend_module_entry *module; return (zend_hash_find(&module_registry, module_name, strlen(module_name)+1, (void**)&module) == SUCCESS && module->module_started) ? SUCCESS : FAILURE; } /* }}} */ static int clean_module_class(const zend_class_entry **ce, int *module_number TSRMLS_DC) /* {{{ */ { if ((*ce)->type == ZEND_INTERNAL_CLASS && (*ce)->info.internal.module->module_number == *module_number) { return ZEND_HASH_APPLY_REMOVE; } else { return ZEND_HASH_APPLY_KEEP; } } /* }}} */ static void clean_module_classes(int module_number TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_argument(EG(class_table), (apply_func_arg_t) clean_module_class, (void *) &module_number TSRMLS_CC); } /* }}} */ void module_destructor(zend_module_entry *module) /* {{{ */ { TSRMLS_FETCH(); if (module->type == MODULE_TEMPORARY) { zend_clean_module_rsrc_dtors(module->module_number TSRMLS_CC); clean_module_constants(module->module_number TSRMLS_CC); clean_module_classes(module->module_number TSRMLS_CC); } if (module->module_started && module->module_shutdown_func) { #if 0 zend_printf("%s: Module shutdown\n", module->name); #endif module->module_shutdown_func(module->type, module->module_number TSRMLS_CC); } /* Deinitilaise module globals */ if (module->globals_size) { #ifdef ZTS ts_free_id(*module->globals_id_ptr); #else if (module->globals_dtor) { module->globals_dtor(module->globals_ptr TSRMLS_CC); } #endif } module->module_started=0; if (module->functions) { zend_unregister_functions(module->functions, -1, NULL TSRMLS_CC); } #if HAVE_LIBDL #if !(defined(NETWARE) && defined(APACHE_1_BUILD)) if (module->handle && !getenv("ZEND_DONT_UNLOAD_MODULES")) { DL_UNLOAD(module->handle); } #endif #endif } /* }}} */ void zend_activate_modules(TSRMLS_D) /* {{{ */ { zend_module_entry **p = module_request_startup_handlers; while (*p) { zend_module_entry *module = *p; if (module->request_startup_func(module->type, module->module_number TSRMLS_CC)==FAILURE) { zend_error(E_WARNING, "request_startup() for %s module failed", module->name); exit(1); } p++; } } /* }}} */ /* call request shutdown for all modules */ int module_registry_cleanup(zend_module_entry *module TSRMLS_DC) /* {{{ */ { if (module->request_shutdown_func) { #if 0 zend_printf("%s: Request shutdown\n", module->name); #endif module->request_shutdown_func(module->type, module->module_number TSRMLS_CC); } return 0; } /* }}} */ void zend_deactivate_modules(TSRMLS_D) /* {{{ */ { EG(opline_ptr) = NULL; /* we're no longer executing anything */ zend_try { if (EG(full_tables_cleanup)) { zend_hash_reverse_apply(&module_registry, (apply_func_t) module_registry_cleanup TSRMLS_CC); } else { zend_module_entry **p = module_request_shutdown_handlers; while (*p) { zend_module_entry *module = *p; module->request_shutdown_func(module->type, module->module_number TSRMLS_CC); p++; } } } zend_end_try(); } /* }}} */ ZEND_API void zend_cleanup_internal_classes(TSRMLS_D) /* {{{ */ { zend_class_entry **p = class_cleanup_handlers; while (*p) { zend_cleanup_internal_class_data(*p TSRMLS_CC); p++; } } /* }}} */ int module_registry_unload_temp(const zend_module_entry *module TSRMLS_DC) /* {{{ */ { return (module->type == MODULE_TEMPORARY) ? ZEND_HASH_APPLY_REMOVE : ZEND_HASH_APPLY_STOP; } /* }}} */ static int exec_done_cb(zend_module_entry *module TSRMLS_DC) /* {{{ */ { if (module->post_deactivate_func) { module->post_deactivate_func(); } return 0; } /* }}} */ void zend_post_deactivate_modules(TSRMLS_D) /* {{{ */ { if (EG(full_tables_cleanup)) { zend_hash_apply(&module_registry, (apply_func_t) exec_done_cb TSRMLS_CC); zend_hash_reverse_apply(&module_registry, (apply_func_t) module_registry_unload_temp TSRMLS_CC); } else { zend_module_entry **p = module_post_deactivate_handlers; while (*p) { zend_module_entry *module = *p; module->post_deactivate_func(); p++; } } } /* }}} */ /* return the next free module number */ int zend_next_free_module(void) /* {{{ */ { return ++module_count; } /* }}} */ static zend_class_entry *do_register_internal_class(zend_class_entry *orig_class_entry, zend_uint ce_flags TSRMLS_DC) /* {{{ */ { zend_class_entry *class_entry = malloc(sizeof(zend_class_entry)); char *lowercase_name = emalloc(orig_class_entry->name_length + 1); *class_entry = *orig_class_entry; class_entry->type = ZEND_INTERNAL_CLASS; zend_initialize_class_data(class_entry, 0 TSRMLS_CC); class_entry->ce_flags = ce_flags; class_entry->info.internal.module = EG(current_module); if (class_entry->info.internal.builtin_functions) { zend_register_functions(class_entry, class_entry->info.internal.builtin_functions, &class_entry->function_table, MODULE_PERSISTENT TSRMLS_CC); } zend_str_tolower_copy(lowercase_name, orig_class_entry->name, class_entry->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, class_entry->name_length + 1, 1 TSRMLS_CC); if (IS_INTERNED(lowercase_name)) { zend_hash_quick_update(CG(class_table), lowercase_name, class_entry->name_length+1, INTERNED_HASH(lowercase_name), &class_entry, sizeof(zend_class_entry *), NULL); } else { zend_hash_update(CG(class_table), lowercase_name, class_entry->name_length+1, &class_entry, sizeof(zend_class_entry *), NULL); } str_efree(lowercase_name); return class_entry; } /* }}} */ /* If parent_ce is not NULL then it inherits from parent_ce * If parent_ce is NULL and parent_name isn't then it looks for the parent and inherits from it * If both parent_ce and parent_name are NULL it does a regular class registration * If parent_name is specified but not found NULL is returned */ ZEND_API zend_class_entry *zend_register_internal_class_ex(zend_class_entry *class_entry, zend_class_entry *parent_ce, char *parent_name TSRMLS_DC) /* {{{ */ { zend_class_entry *register_class; if (!parent_ce && parent_name) { zend_class_entry **pce; if (zend_hash_find(CG(class_table), parent_name, strlen(parent_name)+1, (void **) &pce)==FAILURE) { return NULL; } else { parent_ce = *pce; } } register_class = zend_register_internal_class(class_entry TSRMLS_CC); if (parent_ce) { zend_do_inheritance(register_class, parent_ce TSRMLS_CC); } return register_class; } /* }}} */ ZEND_API void zend_class_implements(zend_class_entry *class_entry TSRMLS_DC, int num_interfaces, ...) /* {{{ */ { zend_class_entry *interface_entry; va_list interface_list; va_start(interface_list, num_interfaces); while (num_interfaces--) { interface_entry = va_arg(interface_list, zend_class_entry *); zend_do_implement_interface(class_entry, interface_entry TSRMLS_CC); } va_end(interface_list); } /* }}} */ /* A class that contains at least one abstract method automatically becomes an abstract class. */ ZEND_API zend_class_entry *zend_register_internal_class(zend_class_entry *orig_class_entry TSRMLS_DC) /* {{{ */ { return do_register_internal_class(orig_class_entry, 0 TSRMLS_CC); } /* }}} */ ZEND_API zend_class_entry *zend_register_internal_interface(zend_class_entry *orig_class_entry TSRMLS_DC) /* {{{ */ { return do_register_internal_class(orig_class_entry, ZEND_ACC_INTERFACE TSRMLS_CC); } /* }}} */ ZEND_API int zend_register_class_alias_ex(const char *name, int name_len, zend_class_entry *ce TSRMLS_DC) /* {{{ */ { char *lcname = zend_str_tolower_dup(name, name_len); int ret; ret = zend_hash_add(CG(class_table), lcname, name_len+1, &ce, sizeof(zend_class_entry *), NULL); efree(lcname); if (ret == SUCCESS) { ce->refcount++; } return ret; } /* }}} */ ZEND_API int zend_set_hash_symbol(zval *symbol, const char *name, int name_length, zend_bool is_ref, int num_symbol_tables, ...) /* {{{ */ { HashTable *symbol_table; va_list symbol_table_list; if (num_symbol_tables <= 0) return FAILURE; Z_SET_ISREF_TO_P(symbol, is_ref); va_start(symbol_table_list, num_symbol_tables); while (num_symbol_tables-- > 0) { symbol_table = va_arg(symbol_table_list, HashTable *); zend_hash_update(symbol_table, name, name_length + 1, &symbol, sizeof(zval *), NULL); zval_add_ref(&symbol); } va_end(symbol_table_list); return SUCCESS; } /* }}} */ /* Disabled functions support */ /* {{{ proto void display_disabled_function(void) Dummy function which displays an error when a disabled function is called. */ ZEND_API ZEND_FUNCTION(display_disabled_function) { zend_error(E_WARNING, "%s() has been disabled for security reasons", get_active_function_name(TSRMLS_C)); } /* }}} */ static zend_function_entry disabled_function[] = { ZEND_FE(display_disabled_function, NULL) ZEND_FE_END }; ZEND_API int zend_disable_function(char *function_name, uint function_name_length TSRMLS_DC) /* {{{ */ { if (zend_hash_del(CG(function_table), function_name, function_name_length+1)==FAILURE) { return FAILURE; } disabled_function[0].fname = function_name; return zend_register_functions(NULL, disabled_function, CG(function_table), MODULE_PERSISTENT TSRMLS_CC); } /* }}} */ static zend_object_value display_disabled_class(zend_class_entry *class_type TSRMLS_DC) /* {{{ */ { zend_object_value retval; zend_object *intern; retval = zend_objects_new(&intern, class_type TSRMLS_CC); zend_error(E_WARNING, "%s() has been disabled for security reasons", class_type->name); return retval; } /* }}} */ static const zend_function_entry disabled_class_new[] = { ZEND_FE_END }; ZEND_API int zend_disable_class(char *class_name, uint class_name_length TSRMLS_DC) /* {{{ */ { zend_class_entry disabled_class; zend_str_tolower(class_name, class_name_length); if (zend_hash_del(CG(class_table), class_name, class_name_length+1)==FAILURE) { return FAILURE; } INIT_OVERLOADED_CLASS_ENTRY_EX(disabled_class, class_name, class_name_length, disabled_class_new, NULL, NULL, NULL, NULL, NULL); disabled_class.create_object = display_disabled_class; disabled_class.name_length = class_name_length; zend_register_internal_class(&disabled_class TSRMLS_CC); return SUCCESS; } /* }}} */ static int zend_is_callable_check_class(const char *name, int name_len, zend_fcall_info_cache *fcc, int *strict_class, char **error TSRMLS_DC) /* {{{ */ { int ret = 0; zend_class_entry **pce; char *lcname = zend_str_tolower_dup(name, name_len); *strict_class = 0; if (name_len == sizeof("self") - 1 && !memcmp(lcname, "self", sizeof("self") - 1)) { if (!EG(scope)) { if (error) *error = estrdup("cannot access self:: when no class scope is active"); } else { fcc->called_scope = EG(called_scope); fcc->calling_scope = EG(scope); if (!fcc->object_ptr) { fcc->object_ptr = EG(This); } ret = 1; } } else if (name_len == sizeof("parent") - 1 && !memcmp(lcname, "parent", sizeof("parent") - 1)) { if (!EG(scope)) { if (error) *error = estrdup("cannot access parent:: when no class scope is active"); } else if (!EG(scope)->parent) { if (error) *error = estrdup("cannot access parent:: when current class scope has no parent"); } else { fcc->called_scope = EG(called_scope); fcc->calling_scope = EG(scope)->parent; if (!fcc->object_ptr) { fcc->object_ptr = EG(This); } *strict_class = 1; ret = 1; } } else if (name_len == sizeof("static") - 1 && !memcmp(lcname, "static", sizeof("static") - 1)) { if (!EG(called_scope)) { if (error) *error = estrdup("cannot access static:: when no class scope is active"); } else { fcc->called_scope = EG(called_scope); fcc->calling_scope = EG(called_scope); if (!fcc->object_ptr) { fcc->object_ptr = EG(This); } *strict_class = 1; ret = 1; } } else if (zend_lookup_class_ex(name, name_len, NULL, 1, &pce TSRMLS_CC) == SUCCESS) { zend_class_entry *scope = EG(active_op_array) ? EG(active_op_array)->scope : NULL; fcc->calling_scope = *pce; if (scope && !fcc->object_ptr && EG(This) && instanceof_function(Z_OBJCE_P(EG(This)), scope TSRMLS_CC) && instanceof_function(scope, fcc->calling_scope TSRMLS_CC)) { fcc->object_ptr = EG(This); fcc->called_scope = Z_OBJCE_P(fcc->object_ptr); } else { fcc->called_scope = fcc->object_ptr ? Z_OBJCE_P(fcc->object_ptr) : fcc->calling_scope; } *strict_class = 1; ret = 1; } else { if (error) zend_spprintf(error, 0, "class '%.*s' not found", name_len, name); } efree(lcname); return ret; } /* }}} */ static int zend_is_callable_check_func(int check_flags, zval *callable, zend_fcall_info_cache *fcc, int strict_class, char **error TSRMLS_DC) /* {{{ */ { zend_class_entry *ce_org = fcc->calling_scope; int retval = 0; char *mname, *lmname; const char *colon; int clen, mlen; zend_class_entry *last_scope; HashTable *ftable; int call_via_handler = 0; if (error) { *error = NULL; } fcc->calling_scope = NULL; fcc->function_handler = NULL; if (!ce_org) { /* Skip leading \ */ if (Z_STRVAL_P(callable)[0] == '\\') { mlen = Z_STRLEN_P(callable) - 1; mname = Z_STRVAL_P(callable) + 1; lmname = zend_str_tolower_dup(Z_STRVAL_P(callable) + 1, mlen); } else { mlen = Z_STRLEN_P(callable); mname = Z_STRVAL_P(callable); lmname = zend_str_tolower_dup(Z_STRVAL_P(callable), mlen); } /* Check if function with given name exists. * This may be a compound name that includes namespace name */ if (zend_hash_find(EG(function_table), lmname, mlen+1, (void**)&fcc->function_handler) == SUCCESS) { efree(lmname); return 1; } efree(lmname); } /* Split name into class/namespace and method/function names */ if ((colon = zend_memrchr(Z_STRVAL_P(callable), ':', Z_STRLEN_P(callable))) != NULL && colon > Z_STRVAL_P(callable) && *(colon-1) == ':' ) { colon--; clen = colon - Z_STRVAL_P(callable); mlen = Z_STRLEN_P(callable) - clen - 2; if (colon == Z_STRVAL_P(callable)) { if (error) zend_spprintf(error, 0, "invalid function name"); return 0; } /* This is a compound name. * Try to fetch class and then find static method. */ last_scope = EG(scope); if (ce_org) { EG(scope) = ce_org; } if (!zend_is_callable_check_class(Z_STRVAL_P(callable), clen, fcc, &strict_class, error TSRMLS_CC)) { EG(scope) = last_scope; return 0; } EG(scope) = last_scope; ftable = &fcc->calling_scope->function_table; if (ce_org && !instanceof_function(ce_org, fcc->calling_scope TSRMLS_CC)) { if (error) zend_spprintf(error, 0, "class '%s' is not a subclass of '%s'", ce_org->name, fcc->calling_scope->name); return 0; } mname = Z_STRVAL_P(callable) + clen + 2; } else if (ce_org) { /* Try to fetch find static method of given class. */ mlen = Z_STRLEN_P(callable); mname = Z_STRVAL_P(callable); ftable = &ce_org->function_table; fcc->calling_scope = ce_org; } else { /* We already checked for plain function before. */ if (error && !(check_flags & IS_CALLABLE_CHECK_SILENT)) { zend_spprintf(error, 0, "function '%s' not found or invalid function name", Z_STRVAL_P(callable)); } return 0; } lmname = zend_str_tolower_dup(mname, mlen); if (strict_class && fcc->calling_scope && mlen == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1 && !memcmp(lmname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME))) { fcc->function_handler = fcc->calling_scope->constructor; if (fcc->function_handler) { retval = 1; } } else if (zend_hash_find(ftable, lmname, mlen+1, (void**)&fcc->function_handler) == SUCCESS) { retval = 1; if ((fcc->function_handler->op_array.fn_flags & ZEND_ACC_CHANGED) && EG(scope) && instanceof_function(fcc->function_handler->common.scope, EG(scope) TSRMLS_CC)) { zend_function *priv_fbc; if (zend_hash_find(&EG(scope)->function_table, lmname, mlen+1, (void **) &priv_fbc)==SUCCESS && priv_fbc->common.fn_flags & ZEND_ACC_PRIVATE && priv_fbc->common.scope == EG(scope)) { fcc->function_handler = priv_fbc; } } if ((check_flags & IS_CALLABLE_CHECK_NO_ACCESS) == 0 && (fcc->calling_scope && (fcc->calling_scope->__call || fcc->calling_scope->__callstatic))) { if (fcc->function_handler->op_array.fn_flags & ZEND_ACC_PRIVATE) { if (!zend_check_private(fcc->function_handler, fcc->object_ptr ? Z_OBJCE_P(fcc->object_ptr) : EG(scope), lmname, mlen TSRMLS_CC)) { retval = 0; fcc->function_handler = NULL; goto get_function_via_handler; } } else if (fcc->function_handler->common.fn_flags & ZEND_ACC_PROTECTED) { if (!zend_check_protected(fcc->function_handler->common.scope, EG(scope))) { retval = 0; fcc->function_handler = NULL; goto get_function_via_handler; } } } } else { get_function_via_handler: if (fcc->object_ptr && fcc->calling_scope == ce_org) { if (strict_class && ce_org->__call) { fcc->function_handler = emalloc(sizeof(zend_internal_function)); fcc->function_handler->internal_function.type = ZEND_INTERNAL_FUNCTION; fcc->function_handler->internal_function.module = (ce_org->type == ZEND_INTERNAL_CLASS) ? ce_org->info.internal.module : NULL; fcc->function_handler->internal_function.handler = zend_std_call_user_call; fcc->function_handler->internal_function.arg_info = NULL; fcc->function_handler->internal_function.num_args = 0; fcc->function_handler->internal_function.scope = ce_org; fcc->function_handler->internal_function.fn_flags = ZEND_ACC_CALL_VIA_HANDLER; fcc->function_handler->internal_function.function_name = estrndup(mname, mlen); call_via_handler = 1; retval = 1; } else if (Z_OBJ_HT_P(fcc->object_ptr)->get_method) { fcc->function_handler = Z_OBJ_HT_P(fcc->object_ptr)->get_method(&fcc->object_ptr, mname, mlen, NULL TSRMLS_CC); if (fcc->function_handler) { if (strict_class && (!fcc->function_handler->common.scope || !instanceof_function(ce_org, fcc->function_handler->common.scope TSRMLS_CC))) { if ((fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) != 0) { if (fcc->function_handler->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fcc->function_handler->common.function_name); } efree(fcc->function_handler); } } else { retval = 1; call_via_handler = (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) != 0; } } } } else if (fcc->calling_scope) { if (fcc->calling_scope->get_static_method) { fcc->function_handler = fcc->calling_scope->get_static_method(fcc->calling_scope, mname, mlen TSRMLS_CC); } else { fcc->function_handler = zend_std_get_static_method(fcc->calling_scope, mname, mlen, NULL TSRMLS_CC); } if (fcc->function_handler) { retval = 1; call_via_handler = (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) != 0; if (call_via_handler && !fcc->object_ptr && EG(This) && Z_OBJ_HT_P(EG(This))->get_class_entry && instanceof_function(Z_OBJCE_P(EG(This)), fcc->calling_scope TSRMLS_CC)) { fcc->object_ptr = EG(This); } } } } if (retval) { if (fcc->calling_scope && !call_via_handler) { if (!fcc->object_ptr && !(fcc->function_handler->common.fn_flags & ZEND_ACC_STATIC)) { int severity; char *verb; if (fcc->function_handler->common.fn_flags & ZEND_ACC_ALLOW_STATIC) { severity = E_STRICT; verb = "should not"; } else { /* An internal function assumes $this is present and won't check that. So PHP would crash by allowing the call. */ severity = E_ERROR; verb = "cannot"; } if ((check_flags & IS_CALLABLE_CHECK_IS_STATIC) != 0) { retval = 0; } if (EG(This) && instanceof_function(Z_OBJCE_P(EG(This)), fcc->calling_scope TSRMLS_CC)) { fcc->object_ptr = EG(This); if (error) { zend_spprintf(error, 0, "non-static method %s::%s() %s be called statically, assuming $this from compatible context %s", fcc->calling_scope->name, fcc->function_handler->common.function_name, verb, Z_OBJCE_P(EG(This))->name); if (severity == E_ERROR) { retval = 0; } } else if (retval) { zend_error(severity, "Non-static method %s::%s() %s be called statically, assuming $this from compatible context %s", fcc->calling_scope->name, fcc->function_handler->common.function_name, verb, Z_OBJCE_P(EG(This))->name); } } else { if (error) { zend_spprintf(error, 0, "non-static method %s::%s() %s be called statically", fcc->calling_scope->name, fcc->function_handler->common.function_name, verb); if (severity == E_ERROR) { retval = 0; } } else if (retval) { zend_error(severity, "Non-static method %s::%s() %s be called statically", fcc->calling_scope->name, fcc->function_handler->common.function_name, verb); } } } if (retval && (check_flags & IS_CALLABLE_CHECK_NO_ACCESS) == 0) { if (fcc->function_handler->op_array.fn_flags & ZEND_ACC_PRIVATE) { if (!zend_check_private(fcc->function_handler, fcc->object_ptr ? Z_OBJCE_P(fcc->object_ptr) : EG(scope), lmname, mlen TSRMLS_CC)) { if (error) { if (*error) { efree(*error); } zend_spprintf(error, 0, "cannot access private method %s::%s()", fcc->calling_scope->name, fcc->function_handler->common.function_name); } retval = 0; } } else if ((fcc->function_handler->common.fn_flags & ZEND_ACC_PROTECTED)) { if (!zend_check_protected(fcc->function_handler->common.scope, EG(scope))) { if (error) { if (*error) { efree(*error); } zend_spprintf(error, 0, "cannot access protected method %s::%s()", fcc->calling_scope->name, fcc->function_handler->common.function_name); } retval = 0; } } } } } else if (error && !(check_flags & IS_CALLABLE_CHECK_SILENT)) { if (fcc->calling_scope) { if (error) zend_spprintf(error, 0, "class '%s' does not have a method '%s'", fcc->calling_scope->name, mname); } else { if (error) zend_spprintf(error, 0, "function '%s' does not exist", mname); } } efree(lmname); if (fcc->object_ptr) { fcc->called_scope = Z_OBJCE_P(fcc->object_ptr); } if (retval) { fcc->initialized = 1; } return retval; } /* }}} */ ZEND_API zend_bool zend_is_callable_ex(zval *callable, zval *object_ptr, uint check_flags, char **callable_name, int *callable_name_len, zend_fcall_info_cache *fcc, char **error TSRMLS_DC) /* {{{ */ { zend_bool ret; int callable_name_len_local; zend_fcall_info_cache fcc_local; if (callable_name) { *callable_name = NULL; } if (callable_name_len == NULL) { callable_name_len = &callable_name_len_local; } if (fcc == NULL) { fcc = &fcc_local; } if (error) { *error = NULL; } fcc->initialized = 0; fcc->calling_scope = NULL; fcc->called_scope = NULL; fcc->function_handler = NULL; fcc->calling_scope = NULL; fcc->object_ptr = NULL; if (object_ptr && Z_TYPE_P(object_ptr) != IS_OBJECT) { object_ptr = NULL; } if (object_ptr && (!EG(objects_store).object_buckets || !EG(objects_store).object_buckets[Z_OBJ_HANDLE_P(object_ptr)].valid)) { return 0; } switch (Z_TYPE_P(callable)) { case IS_STRING: if (object_ptr) { fcc->object_ptr = object_ptr; fcc->calling_scope = Z_OBJCE_P(object_ptr); if (callable_name) { char *ptr; *callable_name_len = fcc->calling_scope->name_length + Z_STRLEN_P(callable) + sizeof("::") - 1; ptr = *callable_name = emalloc(*callable_name_len + 1); memcpy(ptr, fcc->calling_scope->name, fcc->calling_scope->name_length); ptr += fcc->calling_scope->name_length; memcpy(ptr, "::", sizeof("::") - 1); ptr += sizeof("::") - 1; memcpy(ptr, Z_STRVAL_P(callable), Z_STRLEN_P(callable) + 1); } } else if (callable_name) { *callable_name = estrndup(Z_STRVAL_P(callable), Z_STRLEN_P(callable)); *callable_name_len = Z_STRLEN_P(callable); } if (check_flags & IS_CALLABLE_CHECK_SYNTAX_ONLY) { fcc->called_scope = fcc->calling_scope; return 1; } ret = zend_is_callable_check_func(check_flags, callable, fcc, 0, error TSRMLS_CC); if (fcc == &fcc_local && fcc->function_handler && ((fcc->function_handler->type == ZEND_INTERNAL_FUNCTION && (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER)) || fcc->function_handler->type == ZEND_OVERLOADED_FUNCTION_TEMPORARY || fcc->function_handler->type == ZEND_OVERLOADED_FUNCTION)) { if (fcc->function_handler->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fcc->function_handler->common.function_name); } efree(fcc->function_handler); } return ret; case IS_ARRAY: { zval **method = NULL; zval **obj = NULL; int strict_class = 0; if (zend_hash_num_elements(Z_ARRVAL_P(callable)) == 2) { zend_hash_index_find(Z_ARRVAL_P(callable), 0, (void **) &obj); zend_hash_index_find(Z_ARRVAL_P(callable), 1, (void **) &method); } if (obj && method && (Z_TYPE_PP(obj) == IS_OBJECT || Z_TYPE_PP(obj) == IS_STRING) && Z_TYPE_PP(method) == IS_STRING) { if (Z_TYPE_PP(obj) == IS_STRING) { if (callable_name) { char *ptr; *callable_name_len = Z_STRLEN_PP(obj) + Z_STRLEN_PP(method) + sizeof("::") - 1; ptr = *callable_name = emalloc(*callable_name_len + 1); memcpy(ptr, Z_STRVAL_PP(obj), Z_STRLEN_PP(obj)); ptr += Z_STRLEN_PP(obj); memcpy(ptr, "::", sizeof("::") - 1); ptr += sizeof("::") - 1; memcpy(ptr, Z_STRVAL_PP(method), Z_STRLEN_PP(method) + 1); } if (check_flags & IS_CALLABLE_CHECK_SYNTAX_ONLY) { return 1; } if (!zend_is_callable_check_class(Z_STRVAL_PP(obj), Z_STRLEN_PP(obj), fcc, &strict_class, error TSRMLS_CC)) { return 0; } } else { if (!EG(objects_store).object_buckets || !EG(objects_store).object_buckets[Z_OBJ_HANDLE_PP(obj)].valid) { return 0; } fcc->calling_scope = Z_OBJCE_PP(obj); /* TBFixed: what if it's overloaded? */ fcc->object_ptr = *obj; if (callable_name) { char *ptr; *callable_name_len = fcc->calling_scope->name_length + Z_STRLEN_PP(method) + sizeof("::") - 1; ptr = *callable_name = emalloc(*callable_name_len + 1); memcpy(ptr, fcc->calling_scope->name, fcc->calling_scope->name_length); ptr += fcc->calling_scope->name_length; memcpy(ptr, "::", sizeof("::") - 1); ptr += sizeof("::") - 1; memcpy(ptr, Z_STRVAL_PP(method), Z_STRLEN_PP(method) + 1); } if (check_flags & IS_CALLABLE_CHECK_SYNTAX_ONLY) { fcc->called_scope = fcc->calling_scope; return 1; } } ret = zend_is_callable_check_func(check_flags, *method, fcc, strict_class, error TSRMLS_CC); if (fcc == &fcc_local && fcc->function_handler && ((fcc->function_handler->type == ZEND_INTERNAL_FUNCTION && (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER)) || fcc->function_handler->type == ZEND_OVERLOADED_FUNCTION_TEMPORARY || fcc->function_handler->type == ZEND_OVERLOADED_FUNCTION)) { if (fcc->function_handler->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fcc->function_handler->common.function_name); } efree(fcc->function_handler); } return ret; } else { if (zend_hash_num_elements(Z_ARRVAL_P(callable)) == 2) { if (!obj || (Z_TYPE_PP(obj) != IS_STRING && Z_TYPE_PP(obj) != IS_OBJECT)) { if (error) zend_spprintf(error, 0, "first array member is not a valid class name or object"); } else { if (error) zend_spprintf(error, 0, "second array member is not a valid method"); } } else { if (error) zend_spprintf(error, 0, "array must have exactly two members"); } if (callable_name) { *callable_name = estrndup("Array", sizeof("Array")-1); *callable_name_len = sizeof("Array") - 1; } } } return 0; case IS_OBJECT: if (Z_OBJ_HANDLER_P(callable, get_closure) && Z_OBJ_HANDLER_P(callable, get_closure)(callable, &fcc->calling_scope, &fcc->function_handler, &fcc->object_ptr TSRMLS_CC) == SUCCESS) { fcc->called_scope = fcc->calling_scope; if (callable_name) { zend_class_entry *ce = Z_OBJCE_P(callable); /* TBFixed: what if it's overloaded? */ *callable_name_len = ce->name_length + sizeof("::__invoke") - 1; *callable_name = emalloc(*callable_name_len + 1); memcpy(*callable_name, ce->name, ce->name_length); memcpy((*callable_name) + ce->name_length, "::__invoke", sizeof("::__invoke")); } return 1; } /* break missing intentionally */ default: if (callable_name) { zval expr_copy; int use_copy; zend_make_printable_zval(callable, &expr_copy, &use_copy); *callable_name = estrndup(Z_STRVAL(expr_copy), Z_STRLEN(expr_copy)); *callable_name_len = Z_STRLEN(expr_copy); zval_dtor(&expr_copy); } if (error) zend_spprintf(error, 0, "no array or string given"); return 0; } } /* }}} */ ZEND_API zend_bool zend_is_callable(zval *callable, uint check_flags, char **callable_name TSRMLS_DC) /* {{{ */ { return zend_is_callable_ex(callable, NULL, check_flags, callable_name, NULL, NULL, NULL TSRMLS_CC); } /* }}} */ ZEND_API zend_bool zend_make_callable(zval *callable, char **callable_name TSRMLS_DC) /* {{{ */ { zend_fcall_info_cache fcc; if (zend_is_callable_ex(callable, NULL, IS_CALLABLE_STRICT, callable_name, NULL, &fcc, NULL TSRMLS_CC)) { if (Z_TYPE_P(callable) == IS_STRING && fcc.calling_scope) { zval_dtor(callable); array_init(callable); add_next_index_string(callable, fcc.calling_scope->name, 1); add_next_index_string(callable, fcc.function_handler->common.function_name, 1); } if (fcc.function_handler && ((fcc.function_handler->type == ZEND_INTERNAL_FUNCTION && (fcc.function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER)) || fcc.function_handler->type == ZEND_OVERLOADED_FUNCTION_TEMPORARY || fcc.function_handler->type == ZEND_OVERLOADED_FUNCTION)) { if (fcc.function_handler->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fcc.function_handler->common.function_name); } efree(fcc.function_handler); } return 1; } return 0; } /* }}} */ ZEND_API int zend_fcall_info_init(zval *callable, uint check_flags, zend_fcall_info *fci, zend_fcall_info_cache *fcc, char **callable_name, char **error TSRMLS_DC) /* {{{ */ { if (!zend_is_callable_ex(callable, NULL, check_flags, callable_name, NULL, fcc, error TSRMLS_CC)) { return FAILURE; } fci->size = sizeof(*fci); fci->function_table = fcc->calling_scope ? &fcc->calling_scope->function_table : EG(function_table); fci->object_ptr = fcc->object_ptr; fci->function_name = callable; fci->retval_ptr_ptr = NULL; fci->param_count = 0; fci->params = NULL; fci->no_separation = 1; fci->symbol_table = NULL; return SUCCESS; } /* }}} */ ZEND_API void zend_fcall_info_args_clear(zend_fcall_info *fci, int free_mem) /* {{{ */ { if (fci->params) { if (free_mem) { efree(fci->params); fci->params = NULL; } } fci->param_count = 0; } /* }}} */ ZEND_API void zend_fcall_info_args_save(zend_fcall_info *fci, int *param_count, zval ****params) /* {{{ */ { *param_count = fci->param_count; *params = fci->params; fci->param_count = 0; fci->params = NULL; } /* }}} */ ZEND_API void zend_fcall_info_args_restore(zend_fcall_info *fci, int param_count, zval ***params) /* {{{ */ { zend_fcall_info_args_clear(fci, 1); fci->param_count = param_count; fci->params = params; } /* }}} */ ZEND_API int zend_fcall_info_args(zend_fcall_info *fci, zval *args TSRMLS_DC) /* {{{ */ { HashPosition pos; zval **arg, ***params; zend_fcall_info_args_clear(fci, !args); if (!args) { return SUCCESS; } if (Z_TYPE_P(args) != IS_ARRAY) { return FAILURE; } fci->param_count = zend_hash_num_elements(Z_ARRVAL_P(args)); fci->params = params = (zval ***) erealloc(fci->params, fci->param_count * sizeof(zval **)); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(args), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(args), (void *) &arg, &pos) == SUCCESS) { *params++ = arg; zend_hash_move_forward_ex(Z_ARRVAL_P(args), &pos); } return SUCCESS; } /* }}} */ ZEND_API int zend_fcall_info_argp(zend_fcall_info *fci TSRMLS_DC, int argc, zval ***argv) /* {{{ */ { int i; if (argc < 0) { return FAILURE; } zend_fcall_info_args_clear(fci, !argc); if (argc) { fci->param_count = argc; fci->params = (zval ***) erealloc(fci->params, fci->param_count * sizeof(zval **)); for (i = 0; i < argc; ++i) { fci->params[i] = argv[i]; } } return SUCCESS; } /* }}} */ ZEND_API int zend_fcall_info_argv(zend_fcall_info *fci TSRMLS_DC, int argc, va_list *argv) /* {{{ */ { int i; zval **arg; if (argc < 0) { return FAILURE; } zend_fcall_info_args_clear(fci, !argc); if (argc) { fci->param_count = argc; fci->params = (zval ***) erealloc(fci->params, fci->param_count * sizeof(zval **)); for (i = 0; i < argc; ++i) { arg = va_arg(*argv, zval **); fci->params[i] = arg; } } return SUCCESS; } /* }}} */ ZEND_API int zend_fcall_info_argn(zend_fcall_info *fci TSRMLS_DC, int argc, ...) /* {{{ */ { int ret; va_list argv; va_start(argv, argc); ret = zend_fcall_info_argv(fci TSRMLS_CC, argc, &argv); va_end(argv); return ret; } /* }}} */ ZEND_API int zend_fcall_info_call(zend_fcall_info *fci, zend_fcall_info_cache *fcc, zval **retval_ptr_ptr, zval *args TSRMLS_DC) /* {{{ */ { zval *retval, ***org_params = NULL; int result, org_count = 0; fci->retval_ptr_ptr = retval_ptr_ptr ? retval_ptr_ptr : &retval; if (args) { zend_fcall_info_args_save(fci, &org_count, &org_params); zend_fcall_info_args(fci, args TSRMLS_CC); } result = zend_call_function(fci, fcc TSRMLS_CC); if (!retval_ptr_ptr && retval) { zval_ptr_dtor(&retval); } if (args) { zend_fcall_info_args_restore(fci, org_count, org_params); } return result; } /* }}} */ ZEND_API const char *zend_get_module_version(const char *module_name) /* {{{ */ { char *lname; int name_len = strlen(module_name); zend_module_entry *module; lname = zend_str_tolower_dup(module_name, name_len); if (zend_hash_find(&module_registry, lname, name_len + 1, (void**)&module) == FAILURE) { efree(lname); return NULL; } efree(lname); return module->version; } /* }}} */ ZEND_API int zend_declare_property_ex(zend_class_entry *ce, const char *name, int name_length, zval *property, int access_type, const char *doc_comment, int doc_comment_len TSRMLS_DC) /* {{{ */ { zend_property_info property_info, *property_info_ptr; const char *interned_name; ulong h = zend_get_hash_value(name, name_length+1); if (!(access_type & ZEND_ACC_PPP_MASK)) { access_type |= ZEND_ACC_PUBLIC; } if (access_type & ZEND_ACC_STATIC) { if (zend_hash_quick_find(&ce->properties_info, name, name_length + 1, h, (void**)&property_info_ptr) == SUCCESS && (property_info_ptr->flags & ZEND_ACC_STATIC) != 0) { property_info.offset = property_info_ptr->offset; zval_ptr_dtor(&ce->default_static_members_table[property_info.offset]); zend_hash_quick_del(&ce->properties_info, name, name_length + 1, h); } else { property_info.offset = ce->default_static_members_count++; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(zval*) * ce->default_static_members_count, ce->type == ZEND_INTERNAL_CLASS); } ce->default_static_members_table[property_info.offset] = property; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } else { if (zend_hash_quick_find(&ce->properties_info, name, name_length + 1, h, (void**)&property_info_ptr) == SUCCESS && (property_info_ptr->flags & ZEND_ACC_STATIC) == 0) { property_info.offset = property_info_ptr->offset; zval_ptr_dtor(&ce->default_properties_table[property_info.offset]); zend_hash_quick_del(&ce->properties_info, name, name_length + 1, h); } else { property_info.offset = ce->default_properties_count++; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(zval*) * ce->default_properties_count, ce->type == ZEND_INTERNAL_CLASS); } ce->default_properties_table[property_info.offset] = property; } if (ce->type & ZEND_INTERNAL_CLASS) { switch(Z_TYPE_P(property)) { case IS_ARRAY: case IS_CONSTANT_ARRAY: case IS_OBJECT: case IS_RESOURCE: zend_error(E_CORE_ERROR, "Internal zval's can't be arrays, objects or resources"); break; default: break; } } switch (access_type & ZEND_ACC_PPP_MASK) { case ZEND_ACC_PRIVATE: { char *priv_name; int priv_name_length; zend_mangle_property_name(&priv_name, &priv_name_length, ce->name, ce->name_length, name, name_length, ce->type & ZEND_INTERNAL_CLASS); property_info.name = priv_name; property_info.name_length = priv_name_length; } break; case ZEND_ACC_PROTECTED: { char *prot_name; int prot_name_length; zend_mangle_property_name(&prot_name, &prot_name_length, "*", 1, name, name_length, ce->type & ZEND_INTERNAL_CLASS); property_info.name = prot_name; property_info.name_length = prot_name_length; } break; case ZEND_ACC_PUBLIC: if (IS_INTERNED(name)) { property_info.name = (char*)name; } else { property_info.name = ce->type & ZEND_INTERNAL_CLASS ? zend_strndup(name, name_length) : estrndup(name, name_length); } property_info.name_length = name_length; break; } interned_name = zend_new_interned_string(property_info.name, property_info.name_length+1, 0 TSRMLS_CC); if (interned_name != property_info.name) { if (ce->type == ZEND_USER_CLASS) { efree((char*)property_info.name); } else { free((char*)property_info.name); } property_info.name = interned_name; } property_info.flags = access_type; property_info.h = (access_type & ZEND_ACC_PUBLIC) ? h : zend_get_hash_value(property_info.name, property_info.name_length+1); property_info.doc_comment = doc_comment; property_info.doc_comment_len = doc_comment_len; property_info.ce = ce; zend_hash_quick_update(&ce->properties_info, name, name_length+1, h, &property_info, sizeof(zend_property_info), NULL); return SUCCESS; } /* }}} */ ZEND_API int zend_declare_property(zend_class_entry *ce, const char *name, int name_length, zval *property, int access_type TSRMLS_DC) /* {{{ */ { return zend_declare_property_ex(ce, name, name_length, property, access_type, NULL, 0 TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_null(zend_class_entry *ce, const char *name, int name_length, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); } else { ALLOC_ZVAL(property); } INIT_ZVAL(*property); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_bool(zend_class_entry *ce, const char *name, int name_length, long value, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); } else { ALLOC_ZVAL(property); } INIT_PZVAL(property); ZVAL_BOOL(property, value); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_long(zend_class_entry *ce, const char *name, int name_length, long value, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); } else { ALLOC_ZVAL(property); } INIT_PZVAL(property); ZVAL_LONG(property, value); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_double(zend_class_entry *ce, const char *name, int name_length, double value, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); } else { ALLOC_ZVAL(property); } INIT_PZVAL(property); ZVAL_DOUBLE(property, value); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_string(zend_class_entry *ce, const char *name, int name_length, const char *value, int access_type TSRMLS_DC) /* {{{ */ { zval *property; int len = strlen(value); if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); ZVAL_STRINGL(property, zend_strndup(value, len), len, 0); } else { ALLOC_ZVAL(property); ZVAL_STRINGL(property, value, len, 1); } INIT_PZVAL(property); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_stringl(zend_class_entry *ce, const char *name, int name_length, const char *value, int value_len, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); ZVAL_STRINGL(property, zend_strndup(value, value_len), value_len, 0); } else { ALLOC_ZVAL(property); ZVAL_STRINGL(property, value, value_len, 1); } INIT_PZVAL(property); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant(zend_class_entry *ce, const char *name, size_t name_length, zval *value TSRMLS_DC) /* {{{ */ { return zend_hash_update(&ce->constants_table, name, name_length+1, &value, sizeof(zval *), NULL); } /* }}} */ ZEND_API int zend_declare_class_constant_null(zend_class_entry *ce, const char *name, size_t name_length TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); } else { ALLOC_ZVAL(constant); } ZVAL_NULL(constant); INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_long(zend_class_entry *ce, const char *name, size_t name_length, long value TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); } else { ALLOC_ZVAL(constant); } ZVAL_LONG(constant, value); INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_bool(zend_class_entry *ce, const char *name, size_t name_length, zend_bool value TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); } else { ALLOC_ZVAL(constant); } ZVAL_BOOL(constant, value); INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_double(zend_class_entry *ce, const char *name, size_t name_length, double value TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); } else { ALLOC_ZVAL(constant); } ZVAL_DOUBLE(constant, value); INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_stringl(zend_class_entry *ce, const char *name, size_t name_length, const char *value, size_t value_length TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); ZVAL_STRINGL(constant, zend_strndup(value, value_length), value_length, 0); } else { ALLOC_ZVAL(constant); ZVAL_STRINGL(constant, value, value_length, 1); } INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_string(zend_class_entry *ce, const char *name, size_t name_length, const char *value TSRMLS_DC) /* {{{ */ { return zend_declare_class_constant_stringl(ce, name, name_length, value, strlen(value) TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property(zend_class_entry *scope, zval *object, const char *name, int name_length, zval *value TSRMLS_DC) /* {{{ */ { zval *property; zend_class_entry *old_scope = EG(scope); EG(scope) = scope; if (!Z_OBJ_HT_P(object)->write_property) { const char *class_name; zend_uint class_name_len; zend_get_object_classname(object, &class_name, &class_name_len TSRMLS_CC); zend_error(E_CORE_ERROR, "Property %s of class %s cannot be updated", name, class_name); } MAKE_STD_ZVAL(property); ZVAL_STRINGL(property, name, name_length, 1); Z_OBJ_HT_P(object)->write_property(object, property, value, 0 TSRMLS_CC); zval_ptr_dtor(&property); EG(scope) = old_scope; } /* }}} */ ZEND_API void zend_update_property_null(zend_class_entry *scope, zval *object, const char *name, int name_length TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_NULL(tmp); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_bool(zend_class_entry *scope, zval *object, const char *name, int name_length, long value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_BOOL(tmp, value); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_long(zend_class_entry *scope, zval *object, const char *name, int name_length, long value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_LONG(tmp, value); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_double(zend_class_entry *scope, zval *object, const char *name, int name_length, double value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_DOUBLE(tmp, value); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_string(zend_class_entry *scope, zval *object, const char *name, int name_length, const char *value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_STRING(tmp, value, 1); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_stringl(zend_class_entry *scope, zval *object, const char *name, int name_length, const char *value, int value_len TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_STRINGL(tmp, value, value_len, 1); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property(zend_class_entry *scope, const char *name, int name_length, zval *value TSRMLS_DC) /* {{{ */ { zval **property; zend_class_entry *old_scope = EG(scope); EG(scope) = scope; property = zend_std_get_static_property(scope, name, name_length, 0, NULL TSRMLS_CC); EG(scope) = old_scope; if (!property) { return FAILURE; } else { if (*property != value) { if (PZVAL_IS_REF(*property)) { zval_dtor(*property); Z_TYPE_PP(property) = Z_TYPE_P(value); (*property)->value = value->value; if (Z_REFCOUNT_P(value) > 0) { zval_copy_ctor(*property); } } else { zval *garbage = *property; Z_ADDREF_P(value); if (PZVAL_IS_REF(value)) { SEPARATE_ZVAL(&value); } *property = value; zval_ptr_dtor(&garbage); } } return SUCCESS; } } /* }}} */ ZEND_API int zend_update_static_property_null(zend_class_entry *scope, const char *name, int name_length TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_NULL(tmp); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_bool(zend_class_entry *scope, const char *name, int name_length, long value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_BOOL(tmp, value); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_long(zend_class_entry *scope, const char *name, int name_length, long value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_LONG(tmp, value); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_double(zend_class_entry *scope, const char *name, int name_length, double value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_DOUBLE(tmp, value); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_string(zend_class_entry *scope, const char *name, int name_length, const char *value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_STRING(tmp, value, 1); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_stringl(zend_class_entry *scope, const char *name, int name_length, const char *value, int value_len TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_STRINGL(tmp, value, value_len, 1); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API zval *zend_read_property(zend_class_entry *scope, zval *object, const char *name, int name_length, zend_bool silent TSRMLS_DC) /* {{{ */ { zval *property, *value; zend_class_entry *old_scope = EG(scope); EG(scope) = scope; if (!Z_OBJ_HT_P(object)->read_property) { const char *class_name; zend_uint class_name_len; zend_get_object_classname(object, &class_name, &class_name_len TSRMLS_CC); zend_error(E_CORE_ERROR, "Property %s of class %s cannot be read", name, class_name); } MAKE_STD_ZVAL(property); ZVAL_STRINGL(property, name, name_length, 1); value = Z_OBJ_HT_P(object)->read_property(object, property, silent?BP_VAR_IS:BP_VAR_R, 0 TSRMLS_CC); zval_ptr_dtor(&property); EG(scope) = old_scope; return value; } /* }}} */ ZEND_API zval *zend_read_static_property(zend_class_entry *scope, const char *name, int name_length, zend_bool silent TSRMLS_DC) /* {{{ */ { zval **property; zend_class_entry *old_scope = EG(scope); EG(scope) = scope; property = zend_std_get_static_property(scope, name, name_length, silent, NULL TSRMLS_CC); EG(scope) = old_scope; return property?*property:NULL; } /* }}} */ ZEND_API void zend_save_error_handling(zend_error_handling *current TSRMLS_DC) /* {{{ */ { current->handling = EG(error_handling); current->exception = EG(exception_class); current->user_handler = EG(user_error_handler); if (current->user_handler) { Z_ADDREF_P(current->user_handler); } } /* }}} */ ZEND_API void zend_replace_error_handling(zend_error_handling_t error_handling, zend_class_entry *exception_class, zend_error_handling *current TSRMLS_DC) /* {{{ */ { if (current) { zend_save_error_handling(current TSRMLS_CC); if (error_handling != EH_NORMAL && EG(user_error_handler)) { zval_ptr_dtor(&EG(user_error_handler)); EG(user_error_handler) = NULL; } } EG(error_handling) = error_handling; EG(exception_class) = error_handling == EH_THROW ? exception_class : NULL; } /* }}} */ ZEND_API void zend_restore_error_handling(zend_error_handling *saved TSRMLS_DC) /* {{{ */ { EG(error_handling) = saved->handling; EG(exception_class) = saved->handling == EH_THROW ? saved->exception : NULL; if (saved->user_handler && saved->user_handler != EG(user_error_handler)) { if (EG(user_error_handler)) { zval_ptr_dtor(&EG(user_error_handler)); } EG(user_error_handler) = saved->user_handler; } else if (saved->user_handler) { zval_ptr_dtor(&saved->user_handler); } saved->user_handler = NULL; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2012-02-25-c1322d2505-cfa9c90b20.c
manybugs_data_55
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2012 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Wez Furlong <[email protected]> | | Borrowed code from: | | Rasmus Lerdorf <[email protected]> | | Jim Winstead <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #define _GNU_SOURCE #include "php.h" #include "php_globals.h" #include "php_network.h" #include "php_open_temporary_file.h" #include "ext/standard/file.h" #include "ext/standard/basic_functions.h" /* for BG(mmap_file) (not strictly required) */ #include "ext/standard/php_string.h" /* for php_memnstr, used by php_stream_get_record() */ #include <stddef.h> #include <fcntl.h> #include "php_streams_int.h" /* {{{ resource and registration code */ /* Global wrapper hash, copied to FG(stream_wrappers) on registration of volatile wrapper */ static HashTable url_stream_wrappers_hash; static int le_stream = FAILURE; /* true global */ static int le_pstream = FAILURE; /* true global */ static int le_stream_filter = FAILURE; /* true global */ PHPAPI int php_file_le_stream(void) { return le_stream; } PHPAPI int php_file_le_pstream(void) { return le_pstream; } PHPAPI int php_file_le_stream_filter(void) { return le_stream_filter; } PHPAPI HashTable *_php_stream_get_url_stream_wrappers_hash(TSRMLS_D) { return (FG(stream_wrappers) ? FG(stream_wrappers) : &url_stream_wrappers_hash); } PHPAPI HashTable *php_stream_get_url_stream_wrappers_hash_global(void) { return &url_stream_wrappers_hash; } static int _php_stream_release_context(zend_rsrc_list_entry *le, void *pContext TSRMLS_DC) { if (le->ptr == pContext) { return --le->refcount == 0; } return 0; } static int forget_persistent_resource_id_numbers(zend_rsrc_list_entry *rsrc TSRMLS_DC) { php_stream *stream; if (Z_TYPE_P(rsrc) != le_pstream) { return 0; } stream = (php_stream*)rsrc->ptr; #if STREAM_DEBUG fprintf(stderr, "forget_persistent: %s:%p\n", stream->ops->label, stream); #endif stream->rsrc_id = FAILURE; if (stream->context) { zend_hash_apply_with_argument(&EG(regular_list), (apply_func_arg_t) _php_stream_release_context, stream->context TSRMLS_CC); stream->context = NULL; } return 0; } PHP_RSHUTDOWN_FUNCTION(streams) { zend_hash_apply(&EG(persistent_list), (apply_func_t)forget_persistent_resource_id_numbers TSRMLS_CC); return SUCCESS; } PHPAPI php_stream *php_stream_encloses(php_stream *enclosing, php_stream *enclosed) { php_stream *orig = enclosed->enclosing_stream; php_stream_auto_cleanup(enclosed); enclosed->enclosing_stream = enclosing; return orig; } PHPAPI int php_stream_from_persistent_id(const char *persistent_id, php_stream **stream TSRMLS_DC) { zend_rsrc_list_entry *le; if (zend_hash_find(&EG(persistent_list), (char*)persistent_id, strlen(persistent_id)+1, (void*) &le) == SUCCESS) { if (Z_TYPE_P(le) == le_pstream) { if (stream) { HashPosition pos; zend_rsrc_list_entry *regentry; ulong index = -1; /* intentional */ /* see if this persistent resource already has been loaded to the * regular list; allowing the same resource in several entries in the * regular list causes trouble (see bug #54623) */ zend_hash_internal_pointer_reset_ex(&EG(regular_list), &pos); while (zend_hash_get_current_data_ex(&EG(regular_list), (void **)&regentry, &pos) == SUCCESS) { if (regentry->ptr == le->ptr) { zend_hash_get_current_key_ex(&EG(regular_list), NULL, NULL, &index, 0, &pos); break; } zend_hash_move_forward_ex(&EG(regular_list), &pos); } *stream = (php_stream*)le->ptr; if (index == -1) { /* not found in regular list */ le->refcount++; (*stream)->rsrc_id = ZEND_REGISTER_RESOURCE(NULL, *stream, le_pstream); } else { regentry->refcount++; (*stream)->rsrc_id = index; } } return PHP_STREAM_PERSISTENT_SUCCESS; } return PHP_STREAM_PERSISTENT_FAILURE; } return PHP_STREAM_PERSISTENT_NOT_EXIST; } /* }}} */ static zend_llist *php_get_wrapper_errors_list(php_stream_wrapper *wrapper TSRMLS_DC) { zend_llist *list = NULL; if (!FG(wrapper_errors)) { return NULL; } else { zend_hash_find(FG(wrapper_errors), (const char*)&wrapper, sizeof wrapper, (void**)&list); return list; } } /* {{{ wrapper error reporting */ void php_stream_display_wrapper_errors(php_stream_wrapper *wrapper, const char *path, const char *caption TSRMLS_DC) { char *tmp = estrdup(path); char *msg; int free_msg = 0; if (wrapper) { zend_llist *err_list = php_get_wrapper_errors_list(wrapper TSRMLS_CC); if (err_list) { size_t l = 0; int brlen; int i; int count = zend_llist_count(err_list); const char *br; const char **err_buf_p; zend_llist_position pos; if (PG(html_errors)) { brlen = 7; br = "<br />\n"; } else { brlen = 1; br = "\n"; } for (err_buf_p = zend_llist_get_first_ex(err_list, &pos), i = 0; err_buf_p; err_buf_p = zend_llist_get_next_ex(err_list, &pos), i++) { l += strlen(*err_buf_p); if (i < count - 1) { l += brlen; } } msg = emalloc(l + 1); msg[0] = '\0'; for (err_buf_p = zend_llist_get_first_ex(err_list, &pos), i = 0; err_buf_p; err_buf_p = zend_llist_get_next_ex(err_list, &pos), i++) { strcat(msg, *err_buf_p); if (i < count - 1) { l += brlen; } } free_msg = 1; } else { if (wrapper == &php_plain_files_wrapper) { msg = strerror(errno); /* TODO: not ts on linux */ } else { msg = "operation failed"; } } } else { msg = "no suitable wrapper could be found"; } php_strip_url_passwd(tmp); php_error_docref1(NULL TSRMLS_CC, tmp, E_WARNING, "%s: %s", caption, msg); efree(tmp); if (free_msg) { efree(msg); } } void php_stream_tidy_wrapper_error_log(php_stream_wrapper *wrapper TSRMLS_DC) { if (wrapper && FG(wrapper_errors)) { zend_hash_del(FG(wrapper_errors), (const char*)&wrapper, sizeof wrapper); } } static void wrapper_error_dtor(void *error) { efree(*(char**)error); } PHPAPI void php_stream_wrapper_log_error(php_stream_wrapper *wrapper, int options TSRMLS_DC, const char *fmt, ...) { va_list args; char *buffer = NULL; va_start(args, fmt); vspprintf(&buffer, 0, fmt, args); va_end(args); if (options & REPORT_ERRORS || wrapper == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", buffer); efree(buffer); } else { zend_llist *list = NULL; if (!FG(wrapper_errors)) { ALLOC_HASHTABLE(FG(wrapper_errors)); zend_hash_init(FG(wrapper_errors), 8, NULL, (dtor_func_t)zend_llist_destroy, 0); } else { zend_hash_find(FG(wrapper_errors), (const char*)&wrapper, sizeof wrapper, (void**)&list); } if (!list) { zend_llist new_list; zend_llist_init(&new_list, sizeof buffer, wrapper_error_dtor, 0); zend_hash_update(FG(wrapper_errors), (const char*)&wrapper, sizeof wrapper, &new_list, sizeof new_list, (void**)&list); } /* append to linked list */ zend_llist_add_element(list, &buffer); } } /* }}} */ /* allocate a new stream for a particular ops */ PHPAPI php_stream *_php_stream_alloc(php_stream_ops *ops, void *abstract, const char *persistent_id, const char *mode STREAMS_DC TSRMLS_DC) /* {{{ */ { php_stream *ret; ret = (php_stream*) pemalloc_rel_orig(sizeof(php_stream), persistent_id ? 1 : 0); memset(ret, 0, sizeof(php_stream)); ret->readfilters.stream = ret; ret->writefilters.stream = ret; #if STREAM_DEBUG fprintf(stderr, "stream_alloc: %s:%p persistent=%s\n", ops->label, ret, persistent_id); #endif ret->ops = ops; ret->abstract = abstract; ret->is_persistent = persistent_id ? 1 : 0; ret->chunk_size = FG(def_chunk_size); #if ZEND_DEBUG ret->open_filename = __zend_orig_filename ? __zend_orig_filename : __zend_filename; ret->open_lineno = __zend_orig_lineno ? __zend_orig_lineno : __zend_lineno; #endif if (FG(auto_detect_line_endings)) { ret->flags |= PHP_STREAM_FLAG_DETECT_EOL; } if (persistent_id) { zend_rsrc_list_entry le; Z_TYPE(le) = le_pstream; le.ptr = ret; le.refcount = 0; if (FAILURE == zend_hash_update(&EG(persistent_list), (char *)persistent_id, strlen(persistent_id) + 1, (void *)&le, sizeof(le), NULL)) { pefree(ret, 1); return NULL; } } ret->rsrc_id = ZEND_REGISTER_RESOURCE(NULL, ret, persistent_id ? le_pstream : le_stream); strlcpy(ret->mode, mode, sizeof(ret->mode)); ret->wrapper = NULL; ret->wrapperthis = NULL; ret->wrapperdata = NULL; ret->stdiocast = NULL; ret->orig_path = NULL; ret->context = NULL; ret->readbuf = NULL; ret->enclosing_stream = NULL; return ret; } /* }}} */ PHPAPI int _php_stream_free_enclosed(php_stream *stream_enclosed, int close_options TSRMLS_DC) /* {{{ */ { return _php_stream_free(stream_enclosed, close_options | PHP_STREAM_FREE_IGNORE_ENCLOSING TSRMLS_CC); } /* }}} */ #if STREAM_DEBUG static const char *_php_stream_pretty_free_options(int close_options, char *out) { if (close_options & PHP_STREAM_FREE_CALL_DTOR) strcat(out, "CALL_DTOR, "); if (close_options & PHP_STREAM_FREE_RELEASE_STREAM) strcat(out, "RELEASE_STREAM, "); if (close_options & PHP_STREAM_FREE_PRESERVE_HANDLE) strcat(out, "PREVERSE_HANDLE, "); if (close_options & PHP_STREAM_FREE_RSRC_DTOR) strcat(out, "RSRC_DTOR, "); if (close_options & PHP_STREAM_FREE_PERSISTENT) strcat(out, "PERSISTENT, "); if (close_options & PHP_STREAM_FREE_IGNORE_ENCLOSING) strcat(out, "IGNORE_ENCLOSING, "); if (out[0] != '\0') out[strlen(out) - 2] = '\0'; return out; } #endif static int _php_stream_free_persistent(zend_rsrc_list_entry *le, void *pStream TSRMLS_DC) { return le->ptr == pStream; } PHPAPI int _php_stream_free(php_stream *stream, int close_options TSRMLS_DC) /* {{{ */ { int ret = 1; int preserve_handle = close_options & PHP_STREAM_FREE_PRESERVE_HANDLE ? 1 : 0; int release_cast = 1; php_stream_context *context = NULL; /* on an resource list destruction, the context, another resource, may have * already been freed (if it was created after the stream resource), so * don't reference it */ if (!(close_options & PHP_STREAM_FREE_RSRC_DTOR)) { context = stream->context; } if (stream->flags & PHP_STREAM_FLAG_NO_CLOSE) { preserve_handle = 1; } #if STREAM_DEBUG { char out[200] = ""; fprintf(stderr, "stream_free: %s:%p[%s] in_free=%d opts=%s\n", stream->ops->label, stream, stream->orig_path, stream->in_free, _php_stream_pretty_free_options(close_options, out)); } #endif if (stream->in_free) { /* hopefully called recursively from the enclosing stream; the pointer was NULLed below */ if ((stream->in_free == 1) && (close_options & PHP_STREAM_FREE_IGNORE_ENCLOSING) && (stream->enclosing_stream == NULL)) { close_options |= PHP_STREAM_FREE_RSRC_DTOR; /* restore flag */ } else { return 1; /* recursion protection */ } } stream->in_free++; /* force correct order on enclosing/enclosed stream destruction (only from resource * destructor as in when reverse destroying the resource list) */ if ((close_options & PHP_STREAM_FREE_RSRC_DTOR) && !(close_options & PHP_STREAM_FREE_IGNORE_ENCLOSING) && (close_options & (PHP_STREAM_FREE_CALL_DTOR | PHP_STREAM_FREE_RELEASE_STREAM)) && /* always? */ (stream->enclosing_stream != NULL)) { php_stream *enclosing_stream = stream->enclosing_stream; stream->enclosing_stream = NULL; /* we force PHP_STREAM_CALL_DTOR because that's from where the * enclosing stream can free this stream. We remove rsrc_dtor because * we want the enclosing stream to be deleted from the resource list */ return _php_stream_free(enclosing_stream, (close_options | PHP_STREAM_FREE_CALL_DTOR) & ~PHP_STREAM_FREE_RSRC_DTOR TSRMLS_CC); } /* if we are releasing the stream only (and preserving the underlying handle), * we need to do things a little differently. * We are only ever called like this when the stream is cast to a FILE* * for include (or other similar) purposes. * */ if (preserve_handle) { if (stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FOPENCOOKIE) { /* If the stream was fopencookied, we must NOT touch anything * here, as the cookied stream relies on it all. * Instead, mark the stream as OK to auto-clean */ php_stream_auto_cleanup(stream); stream->in_free--; return 0; } /* otherwise, make sure that we don't close the FILE* from a cast */ release_cast = 0; } #if STREAM_DEBUG fprintf(stderr, "stream_free: %s:%p[%s] preserve_handle=%d release_cast=%d remove_rsrc=%d\n", stream->ops->label, stream, stream->orig_path, preserve_handle, release_cast, (close_options & PHP_STREAM_FREE_RSRC_DTOR) == 0); #endif /* make sure everything is saved */ _php_stream_flush(stream, 1 TSRMLS_CC); /* If not called from the resource dtor, remove the stream from the resource list. */ if ((close_options & PHP_STREAM_FREE_RSRC_DTOR) == 0) { /* zend_list_delete actually only decreases the refcount; if we're * releasing the stream, we want to actually delete the resource from * the resource list, otherwise the resource will point to invalid memory. * In any case, let's always completely delete it from the resource list, * not only when PHP_STREAM_FREE_RELEASE_STREAM is set */ while (zend_list_delete(stream->rsrc_id) == SUCCESS) {} } if (close_options & PHP_STREAM_FREE_CALL_DTOR) { if (release_cast && stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FOPENCOOKIE) { /* calling fclose on an fopencookied stream will ultimately call this very same function. If we were called via fclose, the cookie_closer unsets the fclose_stdiocast flags, so we can be sure that we only reach here when PHP code calls php_stream_free. Lets let the cookie code clean it all up. */ stream->in_free = 0; return fclose(stream->stdiocast); } ret = stream->ops->close(stream, preserve_handle ? 0 : 1 TSRMLS_CC); stream->abstract = NULL; /* tidy up any FILE* that might have been fdopened */ if (release_cast && stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FDOPEN && stream->stdiocast) { fclose(stream->stdiocast); stream->stdiocast = NULL; stream->fclose_stdiocast = PHP_STREAM_FCLOSE_NONE; } } if (close_options & PHP_STREAM_FREE_RELEASE_STREAM) { while (stream->readfilters.head) { php_stream_filter_remove(stream->readfilters.head, 1 TSRMLS_CC); } while (stream->writefilters.head) { php_stream_filter_remove(stream->writefilters.head, 1 TSRMLS_CC); } if (stream->wrapper && stream->wrapper->wops && stream->wrapper->wops->stream_closer) { stream->wrapper->wops->stream_closer(stream->wrapper, stream TSRMLS_CC); stream->wrapper = NULL; } if (stream->wrapperdata) { zval_ptr_dtor(&stream->wrapperdata); stream->wrapperdata = NULL; } if (stream->readbuf) { pefree(stream->readbuf, stream->is_persistent); stream->readbuf = NULL; } if (stream->is_persistent && (close_options & PHP_STREAM_FREE_PERSISTENT)) { /* we don't work with *stream but need its value for comparison */ zend_hash_apply_with_argument(&EG(persistent_list), (apply_func_arg_t) _php_stream_free_persistent, stream TSRMLS_CC); } #if ZEND_DEBUG if ((close_options & PHP_STREAM_FREE_RSRC_DTOR) && (stream->__exposed == 0) && (EG(error_reporting) & E_WARNING)) { /* it leaked: Lets deliberately NOT pefree it so that the memory manager shows it * as leaked; it will log a warning, but lets help it out and display what kind * of stream it was. */ char *leakinfo; spprintf(&leakinfo, 0, __FILE__ "(%d) : Stream of type '%s' %p (path:%s) was not closed\n", __LINE__, stream->ops->label, stream, stream->orig_path); if (stream->orig_path) { pefree(stream->orig_path, stream->is_persistent); stream->orig_path = NULL; } # if defined(PHP_WIN32) OutputDebugString(leakinfo); # else fprintf(stderr, "%s", leakinfo); # endif efree(leakinfo); } else { if (stream->orig_path) { pefree(stream->orig_path, stream->is_persistent); stream->orig_path = NULL; } pefree(stream, stream->is_persistent); } #else if (stream->orig_path) { pefree(stream->orig_path, stream->is_persistent); stream->orig_path = NULL; } pefree(stream, stream->is_persistent); #endif } if (context) { zend_list_delete(context->rsrc_id); } return ret; } /* }}} */ /* {{{ generic stream operations */ static void php_stream_fill_read_buffer(php_stream *stream, size_t size TSRMLS_DC) { /* allocate/fill the buffer */ if (stream->readfilters.head) { char *chunk_buf; int err_flag = 0; php_stream_bucket_brigade brig_in = { NULL, NULL }, brig_out = { NULL, NULL }; php_stream_bucket_brigade *brig_inp = &brig_in, *brig_outp = &brig_out, *brig_swap; /* Invalidate the existing cache, otherwise reads can fail, see note in main/streams/filter.c::_php_stream_filter_append */ stream->writepos = stream->readpos = 0; /* allocate a buffer for reading chunks */ chunk_buf = emalloc(stream->chunk_size); while (!stream->eof && !err_flag && (stream->writepos - stream->readpos < (off_t)size)) { size_t justread = 0; int flags; php_stream_bucket *bucket; php_stream_filter_status_t status = PSFS_ERR_FATAL; php_stream_filter *filter; /* read a chunk into a bucket */ justread = stream->ops->read(stream, chunk_buf, stream->chunk_size TSRMLS_CC); if (justread && justread != (size_t)-1) { bucket = php_stream_bucket_new(stream, chunk_buf, justread, 0, 0 TSRMLS_CC); /* after this call, bucket is owned by the brigade */ php_stream_bucket_append(brig_inp, bucket TSRMLS_CC); flags = PSFS_FLAG_NORMAL; } else { flags = stream->eof ? PSFS_FLAG_FLUSH_CLOSE : PSFS_FLAG_FLUSH_INC; } /* wind the handle... */ for (filter = stream->readfilters.head; filter; filter = filter->next) { status = filter->fops->filter(stream, filter, brig_inp, brig_outp, NULL, flags TSRMLS_CC); if (status != PSFS_PASS_ON) { break; } /* brig_out becomes brig_in. * brig_in will always be empty here, as the filter MUST attach any un-consumed buckets * to its own brigade */ brig_swap = brig_inp; brig_inp = brig_outp; brig_outp = brig_swap; memset(brig_outp, 0, sizeof(*brig_outp)); } switch (status) { case PSFS_PASS_ON: /* we get here when the last filter in the chain has data to pass on. * in this situation, we are passing the brig_in brigade into the * stream read buffer */ while (brig_inp->head) { bucket = brig_inp->head; /* grow buffer to hold this bucket * TODO: this can fail for persistent streams */ if (stream->readbuflen - stream->writepos < bucket->buflen) { stream->readbuflen += bucket->buflen; stream->readbuf = perealloc(stream->readbuf, stream->readbuflen, stream->is_persistent); } memcpy(stream->readbuf + stream->writepos, bucket->buf, bucket->buflen); stream->writepos += bucket->buflen; php_stream_bucket_unlink(bucket TSRMLS_CC); php_stream_bucket_delref(bucket TSRMLS_CC); } break; case PSFS_FEED_ME: /* when a filter needs feeding, there is no brig_out to deal with. * we simply continue the loop; if the caller needs more data, * we will read again, otherwise out job is done here */ if (justread == 0) { /* there is no data */ err_flag = 1; break; } continue; case PSFS_ERR_FATAL: /* some fatal error. Theoretically, the stream is borked, so all * further reads should fail. */ err_flag = 1; break; } if (justread == 0 || justread == (size_t)-1) { break; } } efree(chunk_buf); } else { /* is there enough data in the buffer ? */ if (stream->writepos - stream->readpos < (off_t)size) { size_t justread = 0; /* reduce buffer memory consumption if possible, to avoid a realloc */ if (stream->readbuf && stream->readbuflen - stream->writepos < stream->chunk_size) { memmove(stream->readbuf, stream->readbuf + stream->readpos, stream->readbuflen - stream->readpos); stream->writepos -= stream->readpos; stream->readpos = 0; } /* grow the buffer if required * TODO: this can fail for persistent streams */ if (stream->readbuflen - stream->writepos < stream->chunk_size) { stream->readbuflen += stream->chunk_size; stream->readbuf = perealloc(stream->readbuf, stream->readbuflen, stream->is_persistent); } justread = stream->ops->read(stream, stream->readbuf + stream->writepos, stream->readbuflen - stream->writepos TSRMLS_CC); if (justread != (size_t)-1) { stream->writepos += justread; } } } } PHPAPI size_t _php_stream_read(php_stream *stream, char *buf, size_t size TSRMLS_DC) { size_t toread = 0, didread = 0; while (size > 0) { /* take from the read buffer first. * It is possible that a buffered stream was switched to non-buffered, so we * drain the remainder of the buffer before using the "raw" read mode for * the excess */ if (stream->writepos > stream->readpos) { toread = stream->writepos - stream->readpos; if (toread > size) { toread = size; } memcpy(buf, stream->readbuf + stream->readpos, toread); stream->readpos += toread; size -= toread; buf += toread; didread += toread; } /* ignore eof here; the underlying state might have changed */ if (size == 0) { break; } if (!stream->readfilters.head && (stream->flags & PHP_STREAM_FLAG_NO_BUFFER || stream->chunk_size == 1)) { toread = stream->ops->read(stream, buf, size TSRMLS_CC); } else { php_stream_fill_read_buffer(stream, size TSRMLS_CC); toread = stream->writepos - stream->readpos; if (toread > size) { toread = size; } if (toread > 0) { memcpy(buf, stream->readbuf + stream->readpos, toread); stream->readpos += toread; } } if (toread > 0) { didread += toread; buf += toread; size -= toread; } else { /* EOF, or temporary end of data (for non-blocking mode). */ break; } /* just break anyway, to avoid greedy read */ if (stream->wrapper != &php_plain_files_wrapper) { break; } } if (didread > 0) { stream->position += didread; } return didread; } PHPAPI int _php_stream_eof(php_stream *stream TSRMLS_DC) { /* if there is data in the buffer, it's not EOF */ if (stream->writepos - stream->readpos > 0) { return 0; } /* use the configured timeout when checking eof */ if (!stream->eof && PHP_STREAM_OPTION_RETURN_ERR == php_stream_set_option(stream, PHP_STREAM_OPTION_CHECK_LIVENESS, 0, NULL)) { stream->eof = 1; } return stream->eof; } PHPAPI int _php_stream_putc(php_stream *stream, int c TSRMLS_DC) { unsigned char buf = c; if (php_stream_write(stream, &buf, 1) > 0) { return 1; } return EOF; } PHPAPI int _php_stream_getc(php_stream *stream TSRMLS_DC) { char buf; if (php_stream_read(stream, &buf, 1) > 0) { return buf & 0xff; } return EOF; } PHPAPI int _php_stream_puts(php_stream *stream, char *buf TSRMLS_DC) { int len; char newline[2] = "\n"; /* is this OK for Win? */ len = strlen(buf); if (len > 0 && php_stream_write(stream, buf, len) && php_stream_write(stream, newline, 1)) { return 1; } return 0; } PHPAPI int _php_stream_stat(php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC) { memset(ssb, 0, sizeof(*ssb)); /* if the stream was wrapped, allow the wrapper to stat it */ if (stream->wrapper && stream->wrapper->wops->stream_stat != NULL) { return stream->wrapper->wops->stream_stat(stream->wrapper, stream, ssb TSRMLS_CC); } /* if the stream doesn't directly support stat-ing, return with failure. * We could try and emulate this by casting to a FD and fstat-ing it, * but since the fd might not represent the actual underlying content * this would give bogus results. */ if (stream->ops->stat == NULL) { return -1; } return (stream->ops->stat)(stream, ssb TSRMLS_CC); } PHPAPI char *php_stream_locate_eol(php_stream *stream, char *buf, size_t buf_len TSRMLS_DC) { size_t avail; char *cr, *lf, *eol = NULL; char *readptr; if (!buf) { readptr = stream->readbuf + stream->readpos; avail = stream->writepos - stream->readpos; } else { readptr = buf; avail = buf_len; } /* Look for EOL */ if (stream->flags & PHP_STREAM_FLAG_DETECT_EOL) { cr = memchr(readptr, '\r', avail); lf = memchr(readptr, '\n', avail); if (cr && lf != cr + 1 && !(lf && lf < cr)) { /* mac */ stream->flags ^= PHP_STREAM_FLAG_DETECT_EOL; stream->flags |= PHP_STREAM_FLAG_EOL_MAC; eol = cr; } else if ((cr && lf && cr == lf - 1) || (lf)) { /* dos or unix endings */ stream->flags ^= PHP_STREAM_FLAG_DETECT_EOL; eol = lf; } } else if (stream->flags & PHP_STREAM_FLAG_EOL_MAC) { eol = memchr(readptr, '\r', avail); } else { /* unix (and dos) line endings */ eol = memchr(readptr, '\n', avail); } return eol; } /* If buf == NULL, the buffer will be allocated automatically and will be of an * appropriate length to hold the line, regardless of the line length, memory * permitting */ PHPAPI char *_php_stream_get_line(php_stream *stream, char *buf, size_t maxlen, size_t *returned_len TSRMLS_DC) { size_t avail = 0; size_t current_buf_size = 0; size_t total_copied = 0; int grow_mode = 0; char *bufstart = buf; if (buf == NULL) { grow_mode = 1; } else if (maxlen == 0) { return NULL; } /* * If the underlying stream operations block when no new data is readable, * we need to take extra precautions. * * If there is buffered data available, we check for a EOL. If it exists, * we pass the data immediately back to the caller. This saves a call * to the read implementation and will not block where blocking * is not necessary at all. * * If the stream buffer contains more data than the caller requested, * we can also avoid that costly step and simply return that data. */ for (;;) { avail = stream->writepos - stream->readpos; if (avail > 0) { size_t cpysz = 0; char *readptr; char *eol; int done = 0; readptr = stream->readbuf + stream->readpos; eol = php_stream_locate_eol(stream, NULL, 0 TSRMLS_CC); if (eol) { cpysz = eol - readptr + 1; done = 1; } else { cpysz = avail; } if (grow_mode) { /* allow room for a NUL. If this realloc is really a realloc * (ie: second time around), we get an extra byte. In most * cases, with the default chunk size of 8K, we will only * incur that overhead once. When people have lines longer * than 8K, we waste 1 byte per additional 8K or so. * That seems acceptable to me, to avoid making this code * hard to follow */ bufstart = erealloc(bufstart, current_buf_size + cpysz + 1); current_buf_size += cpysz + 1; buf = bufstart + total_copied; } else { if (cpysz >= maxlen - 1) { cpysz = maxlen - 1; done = 1; } } memcpy(buf, readptr, cpysz); stream->position += cpysz; stream->readpos += cpysz; buf += cpysz; maxlen -= cpysz; total_copied += cpysz; if (done) { break; } } else if (stream->eof) { break; } else { /* XXX: Should be fine to always read chunk_size */ size_t toread; if (grow_mode) { toread = stream->chunk_size; } else { toread = maxlen - 1; if (toread > stream->chunk_size) { toread = stream->chunk_size; } } php_stream_fill_read_buffer(stream, toread TSRMLS_CC); if (stream->writepos - stream->readpos == 0) { break; } } } if (total_copied == 0) { if (grow_mode) { assert(bufstart == NULL); } return NULL; } buf[0] = '\0'; if (returned_len) { *returned_len = total_copied; } return bufstart; } #define STREAM_BUFFERED_AMOUNT(stream) \ ((size_t)(((stream)->writepos) - (stream)->readpos)) static char *_php_stream_search_delim(php_stream *stream, size_t maxlen, size_t skiplen, char *delim, /* non-empty! */ size_t delim_len TSRMLS_DC) { size_t seek_len; /* set the maximum number of bytes we're allowed to read from buffer */ seek_len = MIN(STREAM_BUFFERED_AMOUNT(stream), maxlen); if (seek_len <= skiplen) { return NULL; } if (delim_len == 1) { return memchr(&stream->readbuf[stream->readpos + skiplen], delim[0], seek_len - skiplen); } else { return php_memnstr((char*)&stream->readbuf[stream->readpos + skiplen], delim, delim_len, (char*)&stream->readbuf[stream->readpos + seek_len]); } } PHPAPI char *php_stream_get_record(php_stream *stream, size_t maxlen, size_t *returned_len, char *delim, size_t delim_len TSRMLS_DC) { char *ret_buf, /* returned buffer */ *found_delim = NULL; size_t buffered_len, tent_ret_len; /* tentative returned length*/ int has_delim = delim_len > 0 && delim[0] != '\0'; if (maxlen == 0) { return NULL; } if (has_delim) { found_delim = _php_stream_search_delim( stream, maxlen, 0, delim, delim_len TSRMLS_CC); } buffered_len = STREAM_BUFFERED_AMOUNT(stream); /* try to read up to maxlen length bytes while we don't find the delim */ while (!found_delim && buffered_len < maxlen) { size_t just_read, to_read_now; to_read_now = MIN(maxlen - buffered_len, stream->chunk_size); php_stream_fill_read_buffer(stream, buffered_len + to_read_now TSRMLS_CC); just_read = STREAM_BUFFERED_AMOUNT(stream) - buffered_len; /* Assume the stream is temporarily or permanently out of data */ if (just_read == 0) { break; } if (has_delim) { /* search for delimiter, but skip buffered_len (the number of bytes * buffered before this loop iteration), as they have already been * searched for the delimiter */ found_delim = _php_stream_search_delim( stream, maxlen, buffered_len, delim, delim_len TSRMLS_CC); if (found_delim) { break; } } buffered_len += just_read; } if (has_delim && found_delim) { tent_ret_len = found_delim - (char*)&stream->readbuf[stream->readpos]; } else if (!has_delim && STREAM_BUFFERED_AMOUNT(stream) >= maxlen) { tent_ret_len = maxlen; } else { /* return with error if the delimiter string (if any) was not found, we * could not completely fill the read buffer with maxlen bytes and we * don't know we've reached end of file. Added with non-blocking streams * in mind, where this situation is frequent */ if (STREAM_BUFFERED_AMOUNT(stream) < maxlen && !stream->eof) { return NULL; } else if (STREAM_BUFFERED_AMOUNT(stream) == 0 && stream->eof) { /* refuse to return an empty string just because by accident * we knew of EOF in a read that returned no data */ return NULL; } else { tent_ret_len = MIN(STREAM_BUFFERED_AMOUNT(stream), maxlen); } } ret_buf = emalloc(tent_ret_len + 1); /* php_stream_read will not call ops->read here because the necessary * data is guaranteedly buffered */ *returned_len = php_stream_read(stream, ret_buf, tent_ret_len); if (found_delim) { stream->readpos += delim_len; stream->position += delim_len; } ret_buf[*returned_len] = '\0'; return ret_buf; } /* Writes a buffer directly to a stream, using multiple of the chunk size */ static size_t _php_stream_write_buffer(php_stream *stream, const char *buf, size_t count TSRMLS_DC) { size_t didwrite = 0, towrite, justwrote; /* if we have a seekable stream we need to ensure that data is written at the * current stream->position. This means invalidating the read buffer and then * performing a low-level seek */ if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0 && stream->readpos != stream->writepos) { stream->readpos = stream->writepos = 0; stream->ops->seek(stream, stream->position, SEEK_SET, &stream->position TSRMLS_CC); } while (count > 0) { towrite = count; if (towrite > stream->chunk_size) towrite = stream->chunk_size; justwrote = stream->ops->write(stream, buf, towrite TSRMLS_CC); /* convert justwrote to an integer, since normally it is unsigned */ if ((int)justwrote > 0) { buf += justwrote; count -= justwrote; didwrite += justwrote; /* Only screw with the buffer if we can seek, otherwise we lose data * buffered from fifos and sockets */ if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) { stream->position += justwrote; } } else { break; } } return didwrite; } /* push some data through the write filter chain. * buf may be NULL, if flags are set to indicate a flush. * This may trigger a real write to the stream. * Returns the number of bytes consumed from buf by the first filter in the chain. * */ static size_t _php_stream_write_filtered(php_stream *stream, const char *buf, size_t count, int flags TSRMLS_DC) { size_t consumed = 0; php_stream_bucket *bucket; php_stream_bucket_brigade brig_in = { NULL, NULL }, brig_out = { NULL, NULL }; php_stream_bucket_brigade *brig_inp = &brig_in, *brig_outp = &brig_out, *brig_swap; php_stream_filter_status_t status = PSFS_ERR_FATAL; php_stream_filter *filter; if (buf) { bucket = php_stream_bucket_new(stream, (char *)buf, count, 0, 0 TSRMLS_CC); php_stream_bucket_append(&brig_in, bucket TSRMLS_CC); } for (filter = stream->writefilters.head; filter; filter = filter->next) { /* for our return value, we are interested in the number of bytes consumed from * the first filter in the chain */ status = filter->fops->filter(stream, filter, brig_inp, brig_outp, filter == stream->writefilters.head ? &consumed : NULL, flags TSRMLS_CC); if (status != PSFS_PASS_ON) { break; } /* brig_out becomes brig_in. * brig_in will always be empty here, as the filter MUST attach any un-consumed buckets * to its own brigade */ brig_swap = brig_inp; brig_inp = brig_outp; brig_outp = brig_swap; memset(brig_outp, 0, sizeof(*brig_outp)); } switch (status) { case PSFS_PASS_ON: /* filter chain generated some output; push it through to the * underlying stream */ while (brig_inp->head) { bucket = brig_inp->head; _php_stream_write_buffer(stream, bucket->buf, bucket->buflen TSRMLS_CC); /* Potential error situation - eg: no space on device. Perhaps we should keep this brigade * hanging around and try to write it later. * At the moment, we just drop it on the floor * */ php_stream_bucket_unlink(bucket TSRMLS_CC); php_stream_bucket_delref(bucket TSRMLS_CC); } break; case PSFS_FEED_ME: /* need more data before we can push data through to the stream */ break; case PSFS_ERR_FATAL: /* some fatal error. Theoretically, the stream is borked, so all * further writes should fail. */ break; } return consumed; } PHPAPI int _php_stream_flush(php_stream *stream, int closing TSRMLS_DC) { int ret = 0; if (stream->writefilters.head) { _php_stream_write_filtered(stream, NULL, 0, closing ? PSFS_FLAG_FLUSH_CLOSE : PSFS_FLAG_FLUSH_INC TSRMLS_CC); } if (stream->ops->flush) { ret = stream->ops->flush(stream TSRMLS_CC); } return ret; } PHPAPI size_t _php_stream_write(php_stream *stream, const char *buf, size_t count TSRMLS_DC) { if (buf == NULL || count == 0 || stream->ops->write == NULL) { return 0; } if (stream->writefilters.head) { return _php_stream_write_filtered(stream, buf, count, PSFS_FLAG_NORMAL TSRMLS_CC); } else { return _php_stream_write_buffer(stream, buf, count TSRMLS_CC); } } PHPAPI size_t _php_stream_printf(php_stream *stream TSRMLS_DC, const char *fmt, ...) { size_t count; char *buf; va_list ap; va_start(ap, fmt); count = vspprintf(&buf, 0, fmt, ap); va_end(ap); if (!buf) { return 0; /* error condition */ } count = php_stream_write(stream, buf, count); efree(buf); return count; } PHPAPI off_t _php_stream_tell(php_stream *stream TSRMLS_DC) { return stream->position; } PHPAPI int _php_stream_seek(php_stream *stream, off_t offset, int whence TSRMLS_DC) { if (stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FOPENCOOKIE) { /* flush to commit data written to the fopencookie FILE* */ fflush(stream->stdiocast); } /* handle the case where we are in the buffer */ if ((stream->flags & PHP_STREAM_FLAG_NO_BUFFER) == 0) { switch(whence) { case SEEK_CUR: if (offset > 0 && offset <= stream->writepos - stream->readpos) { stream->readpos += offset; /* if offset = ..., then readpos = writepos */ stream->position += offset; stream->eof = 0; return 0; } break; case SEEK_SET: if (offset > stream->position && offset <= stream->position + stream->writepos - stream->readpos) { stream->readpos += offset - stream->position; stream->position = offset; stream->eof = 0; return 0; } break; } } if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) { int ret; if (stream->writefilters.head) { _php_stream_flush(stream, 0 TSRMLS_CC); } switch(whence) { case SEEK_CUR: offset = stream->position + offset; whence = SEEK_SET; break; } ret = stream->ops->seek(stream, offset, whence, &stream->position TSRMLS_CC); if (((stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) || ret == 0) { if (ret == 0) { stream->eof = 0; } /* invalidate the buffer contents */ stream->readpos = stream->writepos = 0; return ret; } /* else the stream has decided that it can't support seeking after all; * fall through to attempt emulation */ } /* emulate forward moving seeks with reads */ if (whence == SEEK_CUR && offset >= 0) { char tmp[1024]; size_t didread; while(offset > 0) { if ((didread = php_stream_read(stream, tmp, MIN(offset, sizeof(tmp)))) == 0) { return -1; } offset -= didread; } stream->eof = 0; return 0; } php_error_docref(NULL TSRMLS_CC, E_WARNING, "stream does not support seeking"); return -1; } PHPAPI int _php_stream_set_option(php_stream *stream, int option, int value, void *ptrparam TSRMLS_DC) { int ret = PHP_STREAM_OPTION_RETURN_NOTIMPL; if (stream->ops->set_option) { ret = stream->ops->set_option(stream, option, value, ptrparam TSRMLS_CC); } if (ret == PHP_STREAM_OPTION_RETURN_NOTIMPL) { switch(option) { case PHP_STREAM_OPTION_SET_CHUNK_SIZE: ret = stream->chunk_size; stream->chunk_size = value; return ret; case PHP_STREAM_OPTION_READ_BUFFER: /* try to match the buffer mode as best we can */ if (value == PHP_STREAM_BUFFER_NONE) { stream->flags |= PHP_STREAM_FLAG_NO_BUFFER; } else if (stream->flags & PHP_STREAM_FLAG_NO_BUFFER) { stream->flags ^= PHP_STREAM_FLAG_NO_BUFFER; } ret = PHP_STREAM_OPTION_RETURN_OK; break; default: ; } } return ret; } PHPAPI int _php_stream_truncate_set_size(php_stream *stream, size_t newsize TSRMLS_DC) { return php_stream_set_option(stream, PHP_STREAM_OPTION_TRUNCATE_API, PHP_STREAM_TRUNCATE_SET_SIZE, &newsize); } PHPAPI size_t _php_stream_passthru(php_stream * stream STREAMS_DC TSRMLS_DC) { size_t bcount = 0; char buf[8192]; int b; if (php_stream_mmap_possible(stream)) { char *p; size_t mapped; p = php_stream_mmap_range(stream, php_stream_tell(stream), PHP_STREAM_MMAP_ALL, PHP_STREAM_MAP_MODE_SHARED_READONLY, &mapped); if (p) { PHPWRITE(p, mapped); php_stream_mmap_unmap_ex(stream, mapped); return mapped; } } while ((b = php_stream_read(stream, buf, sizeof(buf))) > 0) { PHPWRITE(buf, b); bcount += b; } return bcount; } PHPAPI size_t _php_stream_copy_to_mem(php_stream *src, char **buf, size_t maxlen, int persistent STREAMS_DC TSRMLS_DC) { size_t ret = 0; char *ptr; size_t len = 0, max_len; int step = CHUNK_SIZE; int min_room = CHUNK_SIZE / 4; php_stream_statbuf ssbuf; if (maxlen == 0) { return 0; } if (maxlen == PHP_STREAM_COPY_ALL) { maxlen = 0; } if (maxlen > 0) { ptr = *buf = pemalloc_rel_orig(maxlen + 1, persistent); while ((len < maxlen) && !php_stream_eof(src)) { ret = php_stream_read(src, ptr, maxlen - len); if (!ret) { break; } len += ret; ptr += ret; } *ptr = '\0'; return len; } /* avoid many reallocs by allocating a good sized chunk to begin with, if * we can. Note that the stream may be filtered, in which case the stat * result may be inaccurate, as the filter may inflate or deflate the * number of bytes that we can read. In order to avoid an upsize followed * by a downsize of the buffer, overestimate by the step size (which is * 2K). */ if (php_stream_stat(src, &ssbuf) == 0 && ssbuf.sb.st_size > 0) { max_len = ssbuf.sb.st_size + step; } else { max_len = step; } ptr = *buf = pemalloc_rel_orig(max_len, persistent); while((ret = php_stream_read(src, ptr, max_len - len))) { len += ret; if (len + min_room >= max_len) { *buf = perealloc_rel_orig(*buf, max_len + step, persistent); max_len += step; ptr = *buf + len; } else { ptr += ret; } } if (len) { *buf = perealloc_rel_orig(*buf, len + 1, persistent); (*buf)[len] = '\0'; } else { pefree(*buf, persistent); *buf = NULL; } return len; } /* Returns SUCCESS/FAILURE and sets *len to the number of bytes moved */ PHPAPI int _php_stream_copy_to_stream_ex(php_stream *src, php_stream *dest, size_t maxlen, size_t *len STREAMS_DC TSRMLS_DC) { char buf[CHUNK_SIZE]; size_t readchunk; size_t haveread = 0; size_t didread; size_t dummy; php_stream_statbuf ssbuf; if (!len) { len = &dummy; } if (maxlen == 0) { *len = 0; return SUCCESS; } if (maxlen == PHP_STREAM_COPY_ALL) { maxlen = 0; } if (php_stream_stat(src, &ssbuf) == 0) { if (ssbuf.sb.st_size == 0 #ifdef S_ISREG && S_ISREG(ssbuf.sb.st_mode) #endif ) { *len = 0; return SUCCESS; } } if (php_stream_mmap_possible(src)) { char *p; size_t mapped; p = php_stream_mmap_range(src, php_stream_tell(src), maxlen, PHP_STREAM_MAP_MODE_SHARED_READONLY, &mapped); if (p) { mapped = php_stream_write(dest, p, mapped); php_stream_mmap_unmap_ex(src, mapped); *len = mapped; /* we've got at least 1 byte to read. * less than 1 is an error */ if (mapped > 0) { return SUCCESS; } return FAILURE; } } while(1) { readchunk = sizeof(buf); if (maxlen && (maxlen - haveread) < readchunk) { readchunk = maxlen - haveread; } didread = php_stream_read(src, buf, readchunk); if (didread) { /* extra paranoid */ size_t didwrite, towrite; char *writeptr; towrite = didread; writeptr = buf; haveread += didread; while(towrite) { didwrite = php_stream_write(dest, writeptr, towrite); if (didwrite == 0) { *len = haveread - (didread - towrite); return FAILURE; } towrite -= didwrite; writeptr += didwrite; } } else { break; } if (maxlen - haveread == 0) { break; } } *len = haveread; /* we've got at least 1 byte to read. * less than 1 is an error */ if (haveread > 0 || src->eof) { return SUCCESS; } return FAILURE; } /* Returns the number of bytes moved. * Returns 1 when source len is 0. * Deprecated in favor of php_stream_copy_to_stream_ex() */ ZEND_ATTRIBUTE_DEPRECATED PHPAPI size_t _php_stream_copy_to_stream(php_stream *src, php_stream *dest, size_t maxlen STREAMS_DC TSRMLS_DC) { size_t len; int ret = _php_stream_copy_to_stream_ex(src, dest, maxlen, &len STREAMS_REL_CC TSRMLS_CC); if (ret == SUCCESS && len == 0 && maxlen != 0) { return 1; } return len; } /* }}} */ /* {{{ wrapper init and registration */ static void stream_resource_regular_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC) { php_stream *stream = (php_stream*)rsrc->ptr; /* set the return value for pclose */ FG(pclose_ret) = php_stream_free(stream, PHP_STREAM_FREE_CLOSE | PHP_STREAM_FREE_RSRC_DTOR); } static void stream_resource_persistent_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC) { php_stream *stream = (php_stream*)rsrc->ptr; FG(pclose_ret) = php_stream_free(stream, PHP_STREAM_FREE_CLOSE | PHP_STREAM_FREE_RSRC_DTOR); } void php_shutdown_stream_hashes(TSRMLS_D) { if (FG(stream_wrappers)) { zend_hash_destroy(FG(stream_wrappers)); efree(FG(stream_wrappers)); FG(stream_wrappers) = NULL; } if (FG(stream_filters)) { zend_hash_destroy(FG(stream_filters)); efree(FG(stream_filters)); FG(stream_filters) = NULL; } if (FG(wrapper_errors)) { zend_hash_destroy(FG(wrapper_errors)); efree(FG(wrapper_errors)); FG(wrapper_errors) = NULL; } } int php_init_stream_wrappers(int module_number TSRMLS_DC) { le_stream = zend_register_list_destructors_ex(stream_resource_regular_dtor, NULL, "stream", module_number); le_pstream = zend_register_list_destructors_ex(NULL, stream_resource_persistent_dtor, "persistent stream", module_number); /* Filters are cleaned up by the streams they're attached to */ le_stream_filter = zend_register_list_destructors_ex(NULL, NULL, "stream filter", module_number); return ( zend_hash_init(&url_stream_wrappers_hash, 0, NULL, NULL, 1) == SUCCESS && zend_hash_init(php_get_stream_filters_hash_global(), 0, NULL, NULL, 1) == SUCCESS && zend_hash_init(php_stream_xport_get_hash(), 0, NULL, NULL, 1) == SUCCESS && php_stream_xport_register("tcp", php_stream_generic_socket_factory TSRMLS_CC) == SUCCESS && php_stream_xport_register("udp", php_stream_generic_socket_factory TSRMLS_CC) == SUCCESS #if defined(AF_UNIX) && !(defined(PHP_WIN32) || defined(__riscos__) || defined(NETWARE)) && php_stream_xport_register("unix", php_stream_generic_socket_factory TSRMLS_CC) == SUCCESS && php_stream_xport_register("udg", php_stream_generic_socket_factory TSRMLS_CC) == SUCCESS #endif ) ? SUCCESS : FAILURE; } int php_shutdown_stream_wrappers(int module_number TSRMLS_DC) { zend_hash_destroy(&url_stream_wrappers_hash); zend_hash_destroy(php_get_stream_filters_hash_global()); zend_hash_destroy(php_stream_xport_get_hash()); return SUCCESS; } /* Validate protocol scheme names during registration * Must conform to /^[a-zA-Z0-9+.-]+$/ */ static inline int php_stream_wrapper_scheme_validate(char *protocol, int protocol_len) { int i; for(i = 0; i < protocol_len; i++) { if (!isalnum((int)protocol[i]) && protocol[i] != '+' && protocol[i] != '-' && protocol[i] != '.') { return FAILURE; } } return SUCCESS; } /* API for registering GLOBAL wrappers */ PHPAPI int php_register_url_stream_wrapper(char *protocol, php_stream_wrapper *wrapper TSRMLS_DC) { int protocol_len = strlen(protocol); if (php_stream_wrapper_scheme_validate(protocol, protocol_len) == FAILURE) { return FAILURE; } return zend_hash_add(&url_stream_wrappers_hash, protocol, protocol_len + 1, &wrapper, sizeof(wrapper), NULL); } PHPAPI int php_unregister_url_stream_wrapper(char *protocol TSRMLS_DC) { return zend_hash_del(&url_stream_wrappers_hash, protocol, strlen(protocol) + 1); } static void clone_wrapper_hash(TSRMLS_D) { php_stream_wrapper *tmp; ALLOC_HASHTABLE(FG(stream_wrappers)); zend_hash_init(FG(stream_wrappers), zend_hash_num_elements(&url_stream_wrappers_hash), NULL, NULL, 1); zend_hash_copy(FG(stream_wrappers), &url_stream_wrappers_hash, NULL, &tmp, sizeof(tmp)); } /* API for registering VOLATILE wrappers */ PHPAPI int php_register_url_stream_wrapper_volatile(char *protocol, php_stream_wrapper *wrapper TSRMLS_DC) { int protocol_len = strlen(protocol); if (php_stream_wrapper_scheme_validate(protocol, protocol_len) == FAILURE) { return FAILURE; } if (!FG(stream_wrappers)) { clone_wrapper_hash(TSRMLS_C); } return zend_hash_add(FG(stream_wrappers), protocol, protocol_len + 1, &wrapper, sizeof(wrapper), NULL); } PHPAPI int php_unregister_url_stream_wrapper_volatile(char *protocol TSRMLS_DC) { if (!FG(stream_wrappers)) { clone_wrapper_hash(TSRMLS_C); } return zend_hash_del(FG(stream_wrappers), protocol, strlen(protocol) + 1); } /* }}} */ /* {{{ php_stream_locate_url_wrapper */ PHPAPI php_stream_wrapper *php_stream_locate_url_wrapper(const char *path, char **path_for_open, int options TSRMLS_DC) { HashTable *wrapper_hash = (FG(stream_wrappers) ? FG(stream_wrappers) : &url_stream_wrappers_hash); php_stream_wrapper **wrapperpp = NULL; const char *p, *protocol = NULL; int n = 0; if (path_for_open) { *path_for_open = (char*)path; } if (options & IGNORE_URL) { return (options & STREAM_LOCATE_WRAPPERS_ONLY) ? NULL : &php_plain_files_wrapper; } for (p = path; isalnum((int)*p) || *p == '+' || *p == '-' || *p == '.'; p++) { n++; } if ((*p == ':') && (n > 1) && (!strncmp("//", p+1, 2) || (n == 4 && !memcmp("data:", path, 5)))) { protocol = path; } else if (n == 5 && strncasecmp(path, "zlib:", 5) == 0) { /* BC with older php scripts and zlib wrapper */ protocol = "compress.zlib"; n = 13; php_error_docref(NULL TSRMLS_CC, E_WARNING, "Use of \"zlib:\" wrapper is deprecated; please use \"compress.zlib://\" instead"); } if (protocol) { char *tmp = estrndup(protocol, n); if (FAILURE == zend_hash_find(wrapper_hash, (char*)tmp, n + 1, (void**)&wrapperpp)) { php_strtolower(tmp, n); if (FAILURE == zend_hash_find(wrapper_hash, (char*)tmp, n + 1, (void**)&wrapperpp)) { char wrapper_name[32]; if (n >= sizeof(wrapper_name)) { n = sizeof(wrapper_name) - 1; } PHP_STRLCPY(wrapper_name, protocol, sizeof(wrapper_name), n); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to find the wrapper \"%s\" - did you forget to enable it when you configured PHP?", wrapper_name); wrapperpp = NULL; protocol = NULL; } } efree(tmp); } /* TODO: curl based streams probably support file:// properly */ if (!protocol || !strncasecmp(protocol, "file", n)) { /* fall back on regular file access */ php_stream_wrapper *plain_files_wrapper = &php_plain_files_wrapper; if (protocol) { int localhost = 0; if (!strncasecmp(path, "file://localhost/", 17)) { localhost = 1; } #ifdef PHP_WIN32 if (localhost == 0 && path[n+3] != '\0' && path[n+3] != '/' && path[n+4] != ':') { #else if (localhost == 0 && path[n+3] != '\0' && path[n+3] != '/') { #endif if (options & REPORT_ERRORS) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "remote host file access not supported, %s", path); } return NULL; } if (path_for_open) { /* skip past protocol and :/, but handle windows correctly */ *path_for_open = (char*)path + n + 1; if (localhost == 1) { (*path_for_open) += 11; } while (*(++*path_for_open)=='/'); #ifdef PHP_WIN32 if (*(*path_for_open + 1) != ':') #endif (*path_for_open)--; } } if (options & STREAM_LOCATE_WRAPPERS_ONLY) { return NULL; } if (FG(stream_wrappers)) { /* The file:// wrapper may have been disabled/overridden */ if (wrapperpp) { /* It was found so go ahead and provide it */ return *wrapperpp; } /* Check again, the original check might have not known the protocol name */ if (zend_hash_find(wrapper_hash, "file", sizeof("file"), (void**)&wrapperpp) == SUCCESS) { return *wrapperpp; } if (options & REPORT_ERRORS) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "file:// wrapper is disabled in the server configuration"); } return NULL; } return plain_files_wrapper; } if (wrapperpp && (*wrapperpp)->is_url && (options & STREAM_DISABLE_URL_PROTECTION) == 0 && (!PG(allow_url_fopen) || (((options & STREAM_OPEN_FOR_INCLUDE) || PG(in_user_include)) && !PG(allow_url_include)))) { if (options & REPORT_ERRORS) { /* protocol[n] probably isn't '\0' */ char *protocol_dup = estrndup(protocol, n); if (!PG(allow_url_fopen)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s:// wrapper is disabled in the server configuration by allow_url_fopen=0", protocol_dup); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s:// wrapper is disabled in the server configuration by allow_url_include=0", protocol_dup); } efree(protocol_dup); } return NULL; } return *wrapperpp; } /* }}} */ /* {{{ _php_stream_mkdir */ PHPAPI int _php_stream_mkdir(char *path, int mode, int options, php_stream_context *context TSRMLS_DC) { php_stream_wrapper *wrapper = NULL; wrapper = php_stream_locate_url_wrapper(path, NULL, 0 TSRMLS_CC); if (!wrapper || !wrapper->wops || !wrapper->wops->stream_mkdir) { return 0; } return wrapper->wops->stream_mkdir(wrapper, path, mode, options, context TSRMLS_CC); } /* }}} */ /* {{{ _php_stream_rmdir */ PHPAPI int _php_stream_rmdir(char *path, int options, php_stream_context *context TSRMLS_DC) { php_stream_wrapper *wrapper = NULL; wrapper = php_stream_locate_url_wrapper(path, NULL, 0 TSRMLS_CC); if (!wrapper || !wrapper->wops || !wrapper->wops->stream_rmdir) { return 0; } return wrapper->wops->stream_rmdir(wrapper, path, options, context TSRMLS_CC); } /* }}} */ /* {{{ _php_stream_stat_path */ PHPAPI int _php_stream_stat_path(char *path, int flags, php_stream_statbuf *ssb, php_stream_context *context TSRMLS_DC) { php_stream_wrapper *wrapper = NULL; char *path_to_open = path; int ret; /* Try to hit the cache first */ if (flags & PHP_STREAM_URL_STAT_LINK) { if (BG(CurrentLStatFile) && strcmp(path, BG(CurrentLStatFile)) == 0) { memcpy(ssb, &BG(lssb), sizeof(php_stream_statbuf)); return 0; } } else { if (BG(CurrentStatFile) && strcmp(path, BG(CurrentStatFile)) == 0) { memcpy(ssb, &BG(ssb), sizeof(php_stream_statbuf)); return 0; } } wrapper = php_stream_locate_url_wrapper(path, &path_to_open, 0 TSRMLS_CC); if (wrapper && wrapper->wops->url_stat) { ret = wrapper->wops->url_stat(wrapper, path_to_open, flags, ssb, context TSRMLS_CC); if (ret == 0) { /* Drop into cache */ if (flags & PHP_STREAM_URL_STAT_LINK) { if (BG(CurrentLStatFile)) { efree(BG(CurrentLStatFile)); } BG(CurrentLStatFile) = estrdup(path); memcpy(&BG(lssb), ssb, sizeof(php_stream_statbuf)); } else { if (BG(CurrentStatFile)) { efree(BG(CurrentStatFile)); } BG(CurrentStatFile) = estrdup(path); memcpy(&BG(ssb), ssb, sizeof(php_stream_statbuf)); } } return ret; } return -1; } /* }}} */ /* {{{ php_stream_opendir */ PHPAPI php_stream *_php_stream_opendir(char *path, int options, php_stream_context *context STREAMS_DC TSRMLS_DC) { php_stream *stream = NULL; php_stream_wrapper *wrapper = NULL; char *path_to_open; if (!path || !*path) { return NULL; } path_to_open = path; wrapper = php_stream_locate_url_wrapper(path, &path_to_open, options TSRMLS_CC); if (wrapper && wrapper->wops->dir_opener) { stream = wrapper->wops->dir_opener(wrapper, path_to_open, "r", options ^ REPORT_ERRORS, NULL, context STREAMS_REL_CC TSRMLS_CC); if (stream) { stream->wrapper = wrapper; stream->flags |= PHP_STREAM_FLAG_NO_BUFFER | PHP_STREAM_FLAG_IS_DIR; } } else if (wrapper) { php_stream_wrapper_log_error(wrapper, options ^ REPORT_ERRORS TSRMLS_CC, "not implemented"); } if (stream == NULL && (options & REPORT_ERRORS)) { php_stream_display_wrapper_errors(wrapper, path, "failed to open dir" TSRMLS_CC); } php_stream_tidy_wrapper_error_log(wrapper TSRMLS_CC); return stream; } /* }}} */ /* {{{ _php_stream_readdir */ PHPAPI php_stream_dirent *_php_stream_readdir(php_stream *dirstream, php_stream_dirent *ent TSRMLS_DC) { if (sizeof(php_stream_dirent) == php_stream_read(dirstream, (char*)ent, sizeof(php_stream_dirent))) { return ent; } return NULL; } /* }}} */ /* {{{ php_stream_open_wrapper_ex */ PHPAPI php_stream *_php_stream_open_wrapper_ex(char *path, char *mode, int options, char **opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC) { php_stream *stream = NULL; php_stream_wrapper *wrapper = NULL; char *path_to_open; int persistent = options & STREAM_OPEN_PERSISTENT; char *resolved_path = NULL; char *copy_of_path = NULL; if (opened_path) { *opened_path = NULL; } if (!path || !*path) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Filename cannot be empty"); return NULL; } if (options & USE_PATH) { resolved_path = zend_resolve_path(path, strlen(path) TSRMLS_CC); if (resolved_path) { path = resolved_path; /* we've found this file, don't re-check include_path or run realpath */ options |= STREAM_ASSUME_REALPATH; options &= ~USE_PATH; } } path_to_open = path; wrapper = php_stream_locate_url_wrapper(path, &path_to_open, options TSRMLS_CC); if (options & STREAM_USE_URL && (!wrapper || !wrapper->is_url)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "This function may only be used against URLs"); if (resolved_path) { efree(resolved_path); } return NULL; } if (wrapper) { if (!wrapper->wops->stream_opener) { php_stream_wrapper_log_error(wrapper, options ^ REPORT_ERRORS TSRMLS_CC, "wrapper does not support stream open"); } else { stream = wrapper->wops->stream_opener(wrapper, path_to_open, mode, options ^ REPORT_ERRORS, opened_path, context STREAMS_REL_CC TSRMLS_CC); } /* if the caller asked for a persistent stream but the wrapper did not * return one, force an error here */ if (stream && (options & STREAM_OPEN_PERSISTENT) && !stream->is_persistent) { php_stream_wrapper_log_error(wrapper, options ^ REPORT_ERRORS TSRMLS_CC, "wrapper does not support persistent streams"); php_stream_close(stream); stream = NULL; } if (stream) { stream->wrapper = wrapper; } } if (stream) { if (opened_path && !*opened_path && resolved_path) { *opened_path = resolved_path; resolved_path = NULL; } if (stream->orig_path) { pefree(stream->orig_path, persistent); } copy_of_path = pestrdup(path, persistent); stream->orig_path = copy_of_path; #if ZEND_DEBUG stream->open_filename = __zend_orig_filename ? __zend_orig_filename : __zend_filename; stream->open_lineno = __zend_orig_lineno ? __zend_orig_lineno : __zend_lineno; #endif } if (stream != NULL && (options & STREAM_MUST_SEEK)) { php_stream *newstream; switch(php_stream_make_seekable_rel(stream, &newstream, (options & STREAM_WILL_CAST) ? PHP_STREAM_PREFER_STDIO : PHP_STREAM_NO_PREFERENCE)) { case PHP_STREAM_UNCHANGED: if (resolved_path) { efree(resolved_path); } return stream; case PHP_STREAM_RELEASED: if (newstream->orig_path) { pefree(newstream->orig_path, persistent); } newstream->orig_path = pestrdup(path, persistent); if (resolved_path) { efree(resolved_path); } return newstream; default: php_stream_close(stream); stream = NULL; if (options & REPORT_ERRORS) { char *tmp = estrdup(path); php_strip_url_passwd(tmp); php_error_docref1(NULL TSRMLS_CC, tmp, E_WARNING, "could not make seekable - %s", tmp); efree(tmp); options ^= REPORT_ERRORS; } } } if (stream && stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0 && strchr(mode, 'a') && stream->position == 0) { off_t newpos = 0; /* if opened for append, we need to revise our idea of the initial file position */ if (0 == stream->ops->seek(stream, 0, SEEK_CUR, &newpos TSRMLS_CC)) { stream->position = newpos; } } if (stream == NULL && (options & REPORT_ERRORS)) { php_stream_display_wrapper_errors(wrapper, path, "failed to open stream" TSRMLS_CC); if (opened_path && *opened_path) { efree(*opened_path); *opened_path = NULL; } } php_stream_tidy_wrapper_error_log(wrapper TSRMLS_CC); #if ZEND_DEBUG if (stream == NULL && copy_of_path != NULL) { pefree(copy_of_path, persistent); } #endif if (resolved_path) { efree(resolved_path); } return stream; } /* }}} */ /* {{{ context API */ PHPAPI php_stream_context *php_stream_context_set(php_stream *stream, php_stream_context *context) { php_stream_context *oldcontext = stream->context; TSRMLS_FETCH(); stream->context = context; if (context) { zend_list_addref(context->rsrc_id); } if (oldcontext) { zend_list_delete(oldcontext->rsrc_id); } return oldcontext; } PHPAPI void php_stream_notification_notify(php_stream_context *context, int notifycode, int severity, char *xmsg, int xcode, size_t bytes_sofar, size_t bytes_max, void * ptr TSRMLS_DC) { if (context && context->notifier) context->notifier->func(context, notifycode, severity, xmsg, xcode, bytes_sofar, bytes_max, ptr TSRMLS_CC); } PHPAPI void php_stream_context_free(php_stream_context *context) { if (context->options) { zval_ptr_dtor(&context->options); context->options = NULL; } if (context->notifier) { php_stream_notification_free(context->notifier); context->notifier = NULL; } efree(context); } PHPAPI php_stream_context *php_stream_context_alloc(TSRMLS_D) { php_stream_context *context; context = ecalloc(1, sizeof(php_stream_context)); context->notifier = NULL; MAKE_STD_ZVAL(context->options); array_init(context->options); context->rsrc_id = ZEND_REGISTER_RESOURCE(NULL, context, php_le_stream_context(TSRMLS_C)); return context; } PHPAPI php_stream_notifier *php_stream_notification_alloc(void) { return ecalloc(1, sizeof(php_stream_notifier)); } PHPAPI void php_stream_notification_free(php_stream_notifier *notifier) { if (notifier->dtor) { notifier->dtor(notifier); } efree(notifier); } PHPAPI int php_stream_context_get_option(php_stream_context *context, const char *wrappername, const char *optionname, zval ***optionvalue) { zval **wrapperhash; if (FAILURE == zend_hash_find(Z_ARRVAL_P(context->options), (char*)wrappername, strlen(wrappername)+1, (void**)&wrapperhash)) { return FAILURE; } return zend_hash_find(Z_ARRVAL_PP(wrapperhash), (char*)optionname, strlen(optionname)+1, (void**)optionvalue); } PHPAPI int php_stream_context_set_option(php_stream_context *context, const char *wrappername, const char *optionname, zval *optionvalue) { zval **wrapperhash; zval *category, *copied_val; ALLOC_INIT_ZVAL(copied_val); *copied_val = *optionvalue; zval_copy_ctor(copied_val); INIT_PZVAL(copied_val); if (FAILURE == zend_hash_find(Z_ARRVAL_P(context->options), (char*)wrappername, strlen(wrappername)+1, (void**)&wrapperhash)) { MAKE_STD_ZVAL(category); array_init(category); if (FAILURE == zend_hash_update(Z_ARRVAL_P(context->options), (char*)wrappername, strlen(wrappername)+1, (void**)&category, sizeof(zval *), NULL)) { return FAILURE; } wrapperhash = &category; } return zend_hash_update(Z_ARRVAL_PP(wrapperhash), (char*)optionname, strlen(optionname)+1, (void**)&copied_val, sizeof(zval *), NULL); } /* }}} */ /* {{{ php_stream_dirent_alphasort */ PHPAPI int php_stream_dirent_alphasort(const char **a, const char **b) { return strcoll(*a, *b); } /* }}} */ /* {{{ php_stream_dirent_alphasortr */ PHPAPI int php_stream_dirent_alphasortr(const char **a, const char **b) { return strcoll(*b, *a); } /* }}} */ /* {{{ php_stream_scandir */ PHPAPI int _php_stream_scandir(char *dirname, char **namelist[], int flags, php_stream_context *context, int (*compare) (const char **a, const char **b) TSRMLS_DC) { php_stream *stream; php_stream_dirent sdp; char **vector = NULL; int vector_size = 0; int nfiles = 0; if (!namelist) { return FAILURE; } stream = php_stream_opendir(dirname, REPORT_ERRORS, context); if (!stream) { return FAILURE; } while (php_stream_readdir(stream, &sdp)) { if (nfiles == vector_size) { if (vector_size == 0) { vector_size = 10; } else { vector_size *= 2; } vector = (char **) erealloc(vector, vector_size * sizeof(char *)); } vector[nfiles] = estrdup(sdp.d_name); nfiles++; } php_stream_closedir(stream); *namelist = vector; if (compare) { qsort(*namelist, nfiles, sizeof(char *), (int(*)(const void *, const void *))compare); } return nfiles; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2012 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Wez Furlong <[email protected]> | | Borrowed code from: | | Rasmus Lerdorf <[email protected]> | | Jim Winstead <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #define _GNU_SOURCE #include "php.h" #include "php_globals.h" #include "php_network.h" #include "php_open_temporary_file.h" #include "ext/standard/file.h" #include "ext/standard/basic_functions.h" /* for BG(mmap_file) (not strictly required) */ #include "ext/standard/php_string.h" /* for php_memnstr, used by php_stream_get_record() */ #include <stddef.h> #include <fcntl.h> #include "php_streams_int.h" /* {{{ resource and registration code */ /* Global wrapper hash, copied to FG(stream_wrappers) on registration of volatile wrapper */ static HashTable url_stream_wrappers_hash; static int le_stream = FAILURE; /* true global */ static int le_pstream = FAILURE; /* true global */ static int le_stream_filter = FAILURE; /* true global */ PHPAPI int php_file_le_stream(void) { return le_stream; } PHPAPI int php_file_le_pstream(void) { return le_pstream; } PHPAPI int php_file_le_stream_filter(void) { return le_stream_filter; } PHPAPI HashTable *_php_stream_get_url_stream_wrappers_hash(TSRMLS_D) { return (FG(stream_wrappers) ? FG(stream_wrappers) : &url_stream_wrappers_hash); } PHPAPI HashTable *php_stream_get_url_stream_wrappers_hash_global(void) { return &url_stream_wrappers_hash; } static int _php_stream_release_context(zend_rsrc_list_entry *le, void *pContext TSRMLS_DC) { if (le->ptr == pContext) { return --le->refcount == 0; } return 0; } static int forget_persistent_resource_id_numbers(zend_rsrc_list_entry *rsrc TSRMLS_DC) { php_stream *stream; if (Z_TYPE_P(rsrc) != le_pstream) { return 0; } stream = (php_stream*)rsrc->ptr; #if STREAM_DEBUG fprintf(stderr, "forget_persistent: %s:%p\n", stream->ops->label, stream); #endif stream->rsrc_id = FAILURE; if (stream->context) { zend_hash_apply_with_argument(&EG(regular_list), (apply_func_arg_t) _php_stream_release_context, stream->context TSRMLS_CC); stream->context = NULL; } return 0; } PHP_RSHUTDOWN_FUNCTION(streams) { zend_hash_apply(&EG(persistent_list), (apply_func_t)forget_persistent_resource_id_numbers TSRMLS_CC); return SUCCESS; } PHPAPI php_stream *php_stream_encloses(php_stream *enclosing, php_stream *enclosed) { php_stream *orig = enclosed->enclosing_stream; php_stream_auto_cleanup(enclosed); enclosed->enclosing_stream = enclosing; return orig; } PHPAPI int php_stream_from_persistent_id(const char *persistent_id, php_stream **stream TSRMLS_DC) { zend_rsrc_list_entry *le; if (zend_hash_find(&EG(persistent_list), (char*)persistent_id, strlen(persistent_id)+1, (void*) &le) == SUCCESS) { if (Z_TYPE_P(le) == le_pstream) { if (stream) { HashPosition pos; zend_rsrc_list_entry *regentry; ulong index = -1; /* intentional */ /* see if this persistent resource already has been loaded to the * regular list; allowing the same resource in several entries in the * regular list causes trouble (see bug #54623) */ zend_hash_internal_pointer_reset_ex(&EG(regular_list), &pos); while (zend_hash_get_current_data_ex(&EG(regular_list), (void **)&regentry, &pos) == SUCCESS) { if (regentry->ptr == le->ptr) { zend_hash_get_current_key_ex(&EG(regular_list), NULL, NULL, &index, 0, &pos); break; } zend_hash_move_forward_ex(&EG(regular_list), &pos); } *stream = (php_stream*)le->ptr; if (index == -1) { /* not found in regular list */ le->refcount++; (*stream)->rsrc_id = ZEND_REGISTER_RESOURCE(NULL, *stream, le_pstream); } else { regentry->refcount++; (*stream)->rsrc_id = index; } } return PHP_STREAM_PERSISTENT_SUCCESS; } return PHP_STREAM_PERSISTENT_FAILURE; } return PHP_STREAM_PERSISTENT_NOT_EXIST; } /* }}} */ static zend_llist *php_get_wrapper_errors_list(php_stream_wrapper *wrapper TSRMLS_DC) { zend_llist *list = NULL; if (!FG(wrapper_errors)) { return NULL; } else { zend_hash_find(FG(wrapper_errors), (const char*)&wrapper, sizeof wrapper, (void**)&list); return list; } } /* {{{ wrapper error reporting */ void php_stream_display_wrapper_errors(php_stream_wrapper *wrapper, const char *path, const char *caption TSRMLS_DC) { char *tmp = estrdup(path); char *msg; int free_msg = 0; if (wrapper) { zend_llist *err_list = php_get_wrapper_errors_list(wrapper TSRMLS_CC); if (err_list) { size_t l = 0; int brlen; int i; int count = zend_llist_count(err_list); const char *br; const char **err_buf_p; zend_llist_position pos; if (PG(html_errors)) { brlen = 7; br = "<br />\n"; } else { brlen = 1; br = "\n"; } for (err_buf_p = zend_llist_get_first_ex(err_list, &pos), i = 0; err_buf_p; err_buf_p = zend_llist_get_next_ex(err_list, &pos), i++) { l += strlen(*err_buf_p); if (i < count - 1) { l += brlen; } } msg = emalloc(l + 1); msg[0] = '\0'; for (err_buf_p = zend_llist_get_first_ex(err_list, &pos), i = 0; err_buf_p; err_buf_p = zend_llist_get_next_ex(err_list, &pos), i++) { strcat(msg, *err_buf_p); if (i < count - 1) { strcat(msg, br); } } free_msg = 1; } else { if (wrapper == &php_plain_files_wrapper) { msg = strerror(errno); /* TODO: not ts on linux */ } else { msg = "operation failed"; } } } else { msg = "no suitable wrapper could be found"; } php_strip_url_passwd(tmp); php_error_docref1(NULL TSRMLS_CC, tmp, E_WARNING, "%s: %s", caption, msg); efree(tmp); if (free_msg) { efree(msg); } } void php_stream_tidy_wrapper_error_log(php_stream_wrapper *wrapper TSRMLS_DC) { if (wrapper && FG(wrapper_errors)) { zend_hash_del(FG(wrapper_errors), (const char*)&wrapper, sizeof wrapper); } } static void wrapper_error_dtor(void *error) { efree(*(char**)error); } PHPAPI void php_stream_wrapper_log_error(php_stream_wrapper *wrapper, int options TSRMLS_DC, const char *fmt, ...) { va_list args; char *buffer = NULL; va_start(args, fmt); vspprintf(&buffer, 0, fmt, args); va_end(args); if (options & REPORT_ERRORS || wrapper == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", buffer); efree(buffer); } else { zend_llist *list = NULL; if (!FG(wrapper_errors)) { ALLOC_HASHTABLE(FG(wrapper_errors)); zend_hash_init(FG(wrapper_errors), 8, NULL, (dtor_func_t)zend_llist_destroy, 0); } else { zend_hash_find(FG(wrapper_errors), (const char*)&wrapper, sizeof wrapper, (void**)&list); } if (!list) { zend_llist new_list; zend_llist_init(&new_list, sizeof buffer, wrapper_error_dtor, 0); zend_hash_update(FG(wrapper_errors), (const char*)&wrapper, sizeof wrapper, &new_list, sizeof new_list, (void**)&list); } /* append to linked list */ zend_llist_add_element(list, &buffer); } } /* }}} */ /* allocate a new stream for a particular ops */ PHPAPI php_stream *_php_stream_alloc(php_stream_ops *ops, void *abstract, const char *persistent_id, const char *mode STREAMS_DC TSRMLS_DC) /* {{{ */ { php_stream *ret; ret = (php_stream*) pemalloc_rel_orig(sizeof(php_stream), persistent_id ? 1 : 0); memset(ret, 0, sizeof(php_stream)); ret->readfilters.stream = ret; ret->writefilters.stream = ret; #if STREAM_DEBUG fprintf(stderr, "stream_alloc: %s:%p persistent=%s\n", ops->label, ret, persistent_id); #endif ret->ops = ops; ret->abstract = abstract; ret->is_persistent = persistent_id ? 1 : 0; ret->chunk_size = FG(def_chunk_size); #if ZEND_DEBUG ret->open_filename = __zend_orig_filename ? __zend_orig_filename : __zend_filename; ret->open_lineno = __zend_orig_lineno ? __zend_orig_lineno : __zend_lineno; #endif if (FG(auto_detect_line_endings)) { ret->flags |= PHP_STREAM_FLAG_DETECT_EOL; } if (persistent_id) { zend_rsrc_list_entry le; Z_TYPE(le) = le_pstream; le.ptr = ret; le.refcount = 0; if (FAILURE == zend_hash_update(&EG(persistent_list), (char *)persistent_id, strlen(persistent_id) + 1, (void *)&le, sizeof(le), NULL)) { pefree(ret, 1); return NULL; } } ret->rsrc_id = ZEND_REGISTER_RESOURCE(NULL, ret, persistent_id ? le_pstream : le_stream); strlcpy(ret->mode, mode, sizeof(ret->mode)); ret->wrapper = NULL; ret->wrapperthis = NULL; ret->wrapperdata = NULL; ret->stdiocast = NULL; ret->orig_path = NULL; ret->context = NULL; ret->readbuf = NULL; ret->enclosing_stream = NULL; return ret; } /* }}} */ PHPAPI int _php_stream_free_enclosed(php_stream *stream_enclosed, int close_options TSRMLS_DC) /* {{{ */ { return _php_stream_free(stream_enclosed, close_options | PHP_STREAM_FREE_IGNORE_ENCLOSING TSRMLS_CC); } /* }}} */ #if STREAM_DEBUG static const char *_php_stream_pretty_free_options(int close_options, char *out) { if (close_options & PHP_STREAM_FREE_CALL_DTOR) strcat(out, "CALL_DTOR, "); if (close_options & PHP_STREAM_FREE_RELEASE_STREAM) strcat(out, "RELEASE_STREAM, "); if (close_options & PHP_STREAM_FREE_PRESERVE_HANDLE) strcat(out, "PREVERSE_HANDLE, "); if (close_options & PHP_STREAM_FREE_RSRC_DTOR) strcat(out, "RSRC_DTOR, "); if (close_options & PHP_STREAM_FREE_PERSISTENT) strcat(out, "PERSISTENT, "); if (close_options & PHP_STREAM_FREE_IGNORE_ENCLOSING) strcat(out, "IGNORE_ENCLOSING, "); if (out[0] != '\0') out[strlen(out) - 2] = '\0'; return out; } #endif static int _php_stream_free_persistent(zend_rsrc_list_entry *le, void *pStream TSRMLS_DC) { return le->ptr == pStream; } PHPAPI int _php_stream_free(php_stream *stream, int close_options TSRMLS_DC) /* {{{ */ { int ret = 1; int preserve_handle = close_options & PHP_STREAM_FREE_PRESERVE_HANDLE ? 1 : 0; int release_cast = 1; php_stream_context *context = NULL; /* on an resource list destruction, the context, another resource, may have * already been freed (if it was created after the stream resource), so * don't reference it */ if (!(close_options & PHP_STREAM_FREE_RSRC_DTOR)) { context = stream->context; } if (stream->flags & PHP_STREAM_FLAG_NO_CLOSE) { preserve_handle = 1; } #if STREAM_DEBUG { char out[200] = ""; fprintf(stderr, "stream_free: %s:%p[%s] in_free=%d opts=%s\n", stream->ops->label, stream, stream->orig_path, stream->in_free, _php_stream_pretty_free_options(close_options, out)); } #endif if (stream->in_free) { /* hopefully called recursively from the enclosing stream; the pointer was NULLed below */ if ((stream->in_free == 1) && (close_options & PHP_STREAM_FREE_IGNORE_ENCLOSING) && (stream->enclosing_stream == NULL)) { close_options |= PHP_STREAM_FREE_RSRC_DTOR; /* restore flag */ } else { return 1; /* recursion protection */ } } stream->in_free++; /* force correct order on enclosing/enclosed stream destruction (only from resource * destructor as in when reverse destroying the resource list) */ if ((close_options & PHP_STREAM_FREE_RSRC_DTOR) && !(close_options & PHP_STREAM_FREE_IGNORE_ENCLOSING) && (close_options & (PHP_STREAM_FREE_CALL_DTOR | PHP_STREAM_FREE_RELEASE_STREAM)) && /* always? */ (stream->enclosing_stream != NULL)) { php_stream *enclosing_stream = stream->enclosing_stream; stream->enclosing_stream = NULL; /* we force PHP_STREAM_CALL_DTOR because that's from where the * enclosing stream can free this stream. We remove rsrc_dtor because * we want the enclosing stream to be deleted from the resource list */ return _php_stream_free(enclosing_stream, (close_options | PHP_STREAM_FREE_CALL_DTOR) & ~PHP_STREAM_FREE_RSRC_DTOR TSRMLS_CC); } /* if we are releasing the stream only (and preserving the underlying handle), * we need to do things a little differently. * We are only ever called like this when the stream is cast to a FILE* * for include (or other similar) purposes. * */ if (preserve_handle) { if (stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FOPENCOOKIE) { /* If the stream was fopencookied, we must NOT touch anything * here, as the cookied stream relies on it all. * Instead, mark the stream as OK to auto-clean */ php_stream_auto_cleanup(stream); stream->in_free--; return 0; } /* otherwise, make sure that we don't close the FILE* from a cast */ release_cast = 0; } #if STREAM_DEBUG fprintf(stderr, "stream_free: %s:%p[%s] preserve_handle=%d release_cast=%d remove_rsrc=%d\n", stream->ops->label, stream, stream->orig_path, preserve_handle, release_cast, (close_options & PHP_STREAM_FREE_RSRC_DTOR) == 0); #endif /* make sure everything is saved */ _php_stream_flush(stream, 1 TSRMLS_CC); /* If not called from the resource dtor, remove the stream from the resource list. */ if ((close_options & PHP_STREAM_FREE_RSRC_DTOR) == 0) { /* zend_list_delete actually only decreases the refcount; if we're * releasing the stream, we want to actually delete the resource from * the resource list, otherwise the resource will point to invalid memory. * In any case, let's always completely delete it from the resource list, * not only when PHP_STREAM_FREE_RELEASE_STREAM is set */ while (zend_list_delete(stream->rsrc_id) == SUCCESS) {} } if (close_options & PHP_STREAM_FREE_CALL_DTOR) { if (release_cast && stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FOPENCOOKIE) { /* calling fclose on an fopencookied stream will ultimately call this very same function. If we were called via fclose, the cookie_closer unsets the fclose_stdiocast flags, so we can be sure that we only reach here when PHP code calls php_stream_free. Lets let the cookie code clean it all up. */ stream->in_free = 0; return fclose(stream->stdiocast); } ret = stream->ops->close(stream, preserve_handle ? 0 : 1 TSRMLS_CC); stream->abstract = NULL; /* tidy up any FILE* that might have been fdopened */ if (release_cast && stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FDOPEN && stream->stdiocast) { fclose(stream->stdiocast); stream->stdiocast = NULL; stream->fclose_stdiocast = PHP_STREAM_FCLOSE_NONE; } } if (close_options & PHP_STREAM_FREE_RELEASE_STREAM) { while (stream->readfilters.head) { php_stream_filter_remove(stream->readfilters.head, 1 TSRMLS_CC); } while (stream->writefilters.head) { php_stream_filter_remove(stream->writefilters.head, 1 TSRMLS_CC); } if (stream->wrapper && stream->wrapper->wops && stream->wrapper->wops->stream_closer) { stream->wrapper->wops->stream_closer(stream->wrapper, stream TSRMLS_CC); stream->wrapper = NULL; } if (stream->wrapperdata) { zval_ptr_dtor(&stream->wrapperdata); stream->wrapperdata = NULL; } if (stream->readbuf) { pefree(stream->readbuf, stream->is_persistent); stream->readbuf = NULL; } if (stream->is_persistent && (close_options & PHP_STREAM_FREE_PERSISTENT)) { /* we don't work with *stream but need its value for comparison */ zend_hash_apply_with_argument(&EG(persistent_list), (apply_func_arg_t) _php_stream_free_persistent, stream TSRMLS_CC); } #if ZEND_DEBUG if ((close_options & PHP_STREAM_FREE_RSRC_DTOR) && (stream->__exposed == 0) && (EG(error_reporting) & E_WARNING)) { /* it leaked: Lets deliberately NOT pefree it so that the memory manager shows it * as leaked; it will log a warning, but lets help it out and display what kind * of stream it was. */ char *leakinfo; spprintf(&leakinfo, 0, __FILE__ "(%d) : Stream of type '%s' %p (path:%s) was not closed\n", __LINE__, stream->ops->label, stream, stream->orig_path); if (stream->orig_path) { pefree(stream->orig_path, stream->is_persistent); stream->orig_path = NULL; } # if defined(PHP_WIN32) OutputDebugString(leakinfo); # else fprintf(stderr, "%s", leakinfo); # endif efree(leakinfo); } else { if (stream->orig_path) { pefree(stream->orig_path, stream->is_persistent); stream->orig_path = NULL; } pefree(stream, stream->is_persistent); } #else if (stream->orig_path) { pefree(stream->orig_path, stream->is_persistent); stream->orig_path = NULL; } pefree(stream, stream->is_persistent); #endif } if (context) { zend_list_delete(context->rsrc_id); } return ret; } /* }}} */ /* {{{ generic stream operations */ static void php_stream_fill_read_buffer(php_stream *stream, size_t size TSRMLS_DC) { /* allocate/fill the buffer */ if (stream->readfilters.head) { char *chunk_buf; int err_flag = 0; php_stream_bucket_brigade brig_in = { NULL, NULL }, brig_out = { NULL, NULL }; php_stream_bucket_brigade *brig_inp = &brig_in, *brig_outp = &brig_out, *brig_swap; /* Invalidate the existing cache, otherwise reads can fail, see note in main/streams/filter.c::_php_stream_filter_append */ stream->writepos = stream->readpos = 0; /* allocate a buffer for reading chunks */ chunk_buf = emalloc(stream->chunk_size); while (!stream->eof && !err_flag && (stream->writepos - stream->readpos < (off_t)size)) { size_t justread = 0; int flags; php_stream_bucket *bucket; php_stream_filter_status_t status = PSFS_ERR_FATAL; php_stream_filter *filter; /* read a chunk into a bucket */ justread = stream->ops->read(stream, chunk_buf, stream->chunk_size TSRMLS_CC); if (justread && justread != (size_t)-1) { bucket = php_stream_bucket_new(stream, chunk_buf, justread, 0, 0 TSRMLS_CC); /* after this call, bucket is owned by the brigade */ php_stream_bucket_append(brig_inp, bucket TSRMLS_CC); flags = PSFS_FLAG_NORMAL; } else { flags = stream->eof ? PSFS_FLAG_FLUSH_CLOSE : PSFS_FLAG_FLUSH_INC; } /* wind the handle... */ for (filter = stream->readfilters.head; filter; filter = filter->next) { status = filter->fops->filter(stream, filter, brig_inp, brig_outp, NULL, flags TSRMLS_CC); if (status != PSFS_PASS_ON) { break; } /* brig_out becomes brig_in. * brig_in will always be empty here, as the filter MUST attach any un-consumed buckets * to its own brigade */ brig_swap = brig_inp; brig_inp = brig_outp; brig_outp = brig_swap; memset(brig_outp, 0, sizeof(*brig_outp)); } switch (status) { case PSFS_PASS_ON: /* we get here when the last filter in the chain has data to pass on. * in this situation, we are passing the brig_in brigade into the * stream read buffer */ while (brig_inp->head) { bucket = brig_inp->head; /* grow buffer to hold this bucket * TODO: this can fail for persistent streams */ if (stream->readbuflen - stream->writepos < bucket->buflen) { stream->readbuflen += bucket->buflen; stream->readbuf = perealloc(stream->readbuf, stream->readbuflen, stream->is_persistent); } memcpy(stream->readbuf + stream->writepos, bucket->buf, bucket->buflen); stream->writepos += bucket->buflen; php_stream_bucket_unlink(bucket TSRMLS_CC); php_stream_bucket_delref(bucket TSRMLS_CC); } break; case PSFS_FEED_ME: /* when a filter needs feeding, there is no brig_out to deal with. * we simply continue the loop; if the caller needs more data, * we will read again, otherwise out job is done here */ if (justread == 0) { /* there is no data */ err_flag = 1; break; } continue; case PSFS_ERR_FATAL: /* some fatal error. Theoretically, the stream is borked, so all * further reads should fail. */ err_flag = 1; break; } if (justread == 0 || justread == (size_t)-1) { break; } } efree(chunk_buf); } else { /* is there enough data in the buffer ? */ if (stream->writepos - stream->readpos < (off_t)size) { size_t justread = 0; /* reduce buffer memory consumption if possible, to avoid a realloc */ if (stream->readbuf && stream->readbuflen - stream->writepos < stream->chunk_size) { memmove(stream->readbuf, stream->readbuf + stream->readpos, stream->readbuflen - stream->readpos); stream->writepos -= stream->readpos; stream->readpos = 0; } /* grow the buffer if required * TODO: this can fail for persistent streams */ if (stream->readbuflen - stream->writepos < stream->chunk_size) { stream->readbuflen += stream->chunk_size; stream->readbuf = perealloc(stream->readbuf, stream->readbuflen, stream->is_persistent); } justread = stream->ops->read(stream, stream->readbuf + stream->writepos, stream->readbuflen - stream->writepos TSRMLS_CC); if (justread != (size_t)-1) { stream->writepos += justread; } } } } PHPAPI size_t _php_stream_read(php_stream *stream, char *buf, size_t size TSRMLS_DC) { size_t toread = 0, didread = 0; while (size > 0) { /* take from the read buffer first. * It is possible that a buffered stream was switched to non-buffered, so we * drain the remainder of the buffer before using the "raw" read mode for * the excess */ if (stream->writepos > stream->readpos) { toread = stream->writepos - stream->readpos; if (toread > size) { toread = size; } memcpy(buf, stream->readbuf + stream->readpos, toread); stream->readpos += toread; size -= toread; buf += toread; didread += toread; } /* ignore eof here; the underlying state might have changed */ if (size == 0) { break; } if (!stream->readfilters.head && (stream->flags & PHP_STREAM_FLAG_NO_BUFFER || stream->chunk_size == 1)) { toread = stream->ops->read(stream, buf, size TSRMLS_CC); } else { php_stream_fill_read_buffer(stream, size TSRMLS_CC); toread = stream->writepos - stream->readpos; if (toread > size) { toread = size; } if (toread > 0) { memcpy(buf, stream->readbuf + stream->readpos, toread); stream->readpos += toread; } } if (toread > 0) { didread += toread; buf += toread; size -= toread; } else { /* EOF, or temporary end of data (for non-blocking mode). */ break; } /* just break anyway, to avoid greedy read */ if (stream->wrapper != &php_plain_files_wrapper) { break; } } if (didread > 0) { stream->position += didread; } return didread; } PHPAPI int _php_stream_eof(php_stream *stream TSRMLS_DC) { /* if there is data in the buffer, it's not EOF */ if (stream->writepos - stream->readpos > 0) { return 0; } /* use the configured timeout when checking eof */ if (!stream->eof && PHP_STREAM_OPTION_RETURN_ERR == php_stream_set_option(stream, PHP_STREAM_OPTION_CHECK_LIVENESS, 0, NULL)) { stream->eof = 1; } return stream->eof; } PHPAPI int _php_stream_putc(php_stream *stream, int c TSRMLS_DC) { unsigned char buf = c; if (php_stream_write(stream, &buf, 1) > 0) { return 1; } return EOF; } PHPAPI int _php_stream_getc(php_stream *stream TSRMLS_DC) { char buf; if (php_stream_read(stream, &buf, 1) > 0) { return buf & 0xff; } return EOF; } PHPAPI int _php_stream_puts(php_stream *stream, char *buf TSRMLS_DC) { int len; char newline[2] = "\n"; /* is this OK for Win? */ len = strlen(buf); if (len > 0 && php_stream_write(stream, buf, len) && php_stream_write(stream, newline, 1)) { return 1; } return 0; } PHPAPI int _php_stream_stat(php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC) { memset(ssb, 0, sizeof(*ssb)); /* if the stream was wrapped, allow the wrapper to stat it */ if (stream->wrapper && stream->wrapper->wops->stream_stat != NULL) { return stream->wrapper->wops->stream_stat(stream->wrapper, stream, ssb TSRMLS_CC); } /* if the stream doesn't directly support stat-ing, return with failure. * We could try and emulate this by casting to a FD and fstat-ing it, * but since the fd might not represent the actual underlying content * this would give bogus results. */ if (stream->ops->stat == NULL) { return -1; } return (stream->ops->stat)(stream, ssb TSRMLS_CC); } PHPAPI char *php_stream_locate_eol(php_stream *stream, char *buf, size_t buf_len TSRMLS_DC) { size_t avail; char *cr, *lf, *eol = NULL; char *readptr; if (!buf) { readptr = stream->readbuf + stream->readpos; avail = stream->writepos - stream->readpos; } else { readptr = buf; avail = buf_len; } /* Look for EOL */ if (stream->flags & PHP_STREAM_FLAG_DETECT_EOL) { cr = memchr(readptr, '\r', avail); lf = memchr(readptr, '\n', avail); if (cr && lf != cr + 1 && !(lf && lf < cr)) { /* mac */ stream->flags ^= PHP_STREAM_FLAG_DETECT_EOL; stream->flags |= PHP_STREAM_FLAG_EOL_MAC; eol = cr; } else if ((cr && lf && cr == lf - 1) || (lf)) { /* dos or unix endings */ stream->flags ^= PHP_STREAM_FLAG_DETECT_EOL; eol = lf; } } else if (stream->flags & PHP_STREAM_FLAG_EOL_MAC) { eol = memchr(readptr, '\r', avail); } else { /* unix (and dos) line endings */ eol = memchr(readptr, '\n', avail); } return eol; } /* If buf == NULL, the buffer will be allocated automatically and will be of an * appropriate length to hold the line, regardless of the line length, memory * permitting */ PHPAPI char *_php_stream_get_line(php_stream *stream, char *buf, size_t maxlen, size_t *returned_len TSRMLS_DC) { size_t avail = 0; size_t current_buf_size = 0; size_t total_copied = 0; int grow_mode = 0; char *bufstart = buf; if (buf == NULL) { grow_mode = 1; } else if (maxlen == 0) { return NULL; } /* * If the underlying stream operations block when no new data is readable, * we need to take extra precautions. * * If there is buffered data available, we check for a EOL. If it exists, * we pass the data immediately back to the caller. This saves a call * to the read implementation and will not block where blocking * is not necessary at all. * * If the stream buffer contains more data than the caller requested, * we can also avoid that costly step and simply return that data. */ for (;;) { avail = stream->writepos - stream->readpos; if (avail > 0) { size_t cpysz = 0; char *readptr; char *eol; int done = 0; readptr = stream->readbuf + stream->readpos; eol = php_stream_locate_eol(stream, NULL, 0 TSRMLS_CC); if (eol) { cpysz = eol - readptr + 1; done = 1; } else { cpysz = avail; } if (grow_mode) { /* allow room for a NUL. If this realloc is really a realloc * (ie: second time around), we get an extra byte. In most * cases, with the default chunk size of 8K, we will only * incur that overhead once. When people have lines longer * than 8K, we waste 1 byte per additional 8K or so. * That seems acceptable to me, to avoid making this code * hard to follow */ bufstart = erealloc(bufstart, current_buf_size + cpysz + 1); current_buf_size += cpysz + 1; buf = bufstart + total_copied; } else { if (cpysz >= maxlen - 1) { cpysz = maxlen - 1; done = 1; } } memcpy(buf, readptr, cpysz); stream->position += cpysz; stream->readpos += cpysz; buf += cpysz; maxlen -= cpysz; total_copied += cpysz; if (done) { break; } } else if (stream->eof) { break; } else { /* XXX: Should be fine to always read chunk_size */ size_t toread; if (grow_mode) { toread = stream->chunk_size; } else { toread = maxlen - 1; if (toread > stream->chunk_size) { toread = stream->chunk_size; } } php_stream_fill_read_buffer(stream, toread TSRMLS_CC); if (stream->writepos - stream->readpos == 0) { break; } } } if (total_copied == 0) { if (grow_mode) { assert(bufstart == NULL); } return NULL; } buf[0] = '\0'; if (returned_len) { *returned_len = total_copied; } return bufstart; } #define STREAM_BUFFERED_AMOUNT(stream) \ ((size_t)(((stream)->writepos) - (stream)->readpos)) static char *_php_stream_search_delim(php_stream *stream, size_t maxlen, size_t skiplen, char *delim, /* non-empty! */ size_t delim_len TSRMLS_DC) { size_t seek_len; /* set the maximum number of bytes we're allowed to read from buffer */ seek_len = MIN(STREAM_BUFFERED_AMOUNT(stream), maxlen); if (seek_len <= skiplen) { return NULL; } if (delim_len == 1) { return memchr(&stream->readbuf[stream->readpos + skiplen], delim[0], seek_len - skiplen); } else { return php_memnstr((char*)&stream->readbuf[stream->readpos + skiplen], delim, delim_len, (char*)&stream->readbuf[stream->readpos + seek_len]); } } PHPAPI char *php_stream_get_record(php_stream *stream, size_t maxlen, size_t *returned_len, char *delim, size_t delim_len TSRMLS_DC) { char *ret_buf, /* returned buffer */ *found_delim = NULL; size_t buffered_len, tent_ret_len; /* tentative returned length*/ int has_delim = delim_len > 0 && delim[0] != '\0'; if (maxlen == 0) { return NULL; } if (has_delim) { found_delim = _php_stream_search_delim( stream, maxlen, 0, delim, delim_len TSRMLS_CC); } buffered_len = STREAM_BUFFERED_AMOUNT(stream); /* try to read up to maxlen length bytes while we don't find the delim */ while (!found_delim && buffered_len < maxlen) { size_t just_read, to_read_now; to_read_now = MIN(maxlen - buffered_len, stream->chunk_size); php_stream_fill_read_buffer(stream, buffered_len + to_read_now TSRMLS_CC); just_read = STREAM_BUFFERED_AMOUNT(stream) - buffered_len; /* Assume the stream is temporarily or permanently out of data */ if (just_read == 0) { break; } if (has_delim) { /* search for delimiter, but skip buffered_len (the number of bytes * buffered before this loop iteration), as they have already been * searched for the delimiter */ found_delim = _php_stream_search_delim( stream, maxlen, buffered_len, delim, delim_len TSRMLS_CC); if (found_delim) { break; } } buffered_len += just_read; } if (has_delim && found_delim) { tent_ret_len = found_delim - (char*)&stream->readbuf[stream->readpos]; } else if (!has_delim && STREAM_BUFFERED_AMOUNT(stream) >= maxlen) { tent_ret_len = maxlen; } else { /* return with error if the delimiter string (if any) was not found, we * could not completely fill the read buffer with maxlen bytes and we * don't know we've reached end of file. Added with non-blocking streams * in mind, where this situation is frequent */ if (STREAM_BUFFERED_AMOUNT(stream) < maxlen && !stream->eof) { return NULL; } else if (STREAM_BUFFERED_AMOUNT(stream) == 0 && stream->eof) { /* refuse to return an empty string just because by accident * we knew of EOF in a read that returned no data */ return NULL; } else { tent_ret_len = MIN(STREAM_BUFFERED_AMOUNT(stream), maxlen); } } ret_buf = emalloc(tent_ret_len + 1); /* php_stream_read will not call ops->read here because the necessary * data is guaranteedly buffered */ *returned_len = php_stream_read(stream, ret_buf, tent_ret_len); if (found_delim) { stream->readpos += delim_len; stream->position += delim_len; } ret_buf[*returned_len] = '\0'; return ret_buf; } /* Writes a buffer directly to a stream, using multiple of the chunk size */ static size_t _php_stream_write_buffer(php_stream *stream, const char *buf, size_t count TSRMLS_DC) { size_t didwrite = 0, towrite, justwrote; /* if we have a seekable stream we need to ensure that data is written at the * current stream->position. This means invalidating the read buffer and then * performing a low-level seek */ if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0 && stream->readpos != stream->writepos) { stream->readpos = stream->writepos = 0; stream->ops->seek(stream, stream->position, SEEK_SET, &stream->position TSRMLS_CC); } while (count > 0) { towrite = count; if (towrite > stream->chunk_size) towrite = stream->chunk_size; justwrote = stream->ops->write(stream, buf, towrite TSRMLS_CC); /* convert justwrote to an integer, since normally it is unsigned */ if ((int)justwrote > 0) { buf += justwrote; count -= justwrote; didwrite += justwrote; /* Only screw with the buffer if we can seek, otherwise we lose data * buffered from fifos and sockets */ if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) { stream->position += justwrote; } } else { break; } } return didwrite; } /* push some data through the write filter chain. * buf may be NULL, if flags are set to indicate a flush. * This may trigger a real write to the stream. * Returns the number of bytes consumed from buf by the first filter in the chain. * */ static size_t _php_stream_write_filtered(php_stream *stream, const char *buf, size_t count, int flags TSRMLS_DC) { size_t consumed = 0; php_stream_bucket *bucket; php_stream_bucket_brigade brig_in = { NULL, NULL }, brig_out = { NULL, NULL }; php_stream_bucket_brigade *brig_inp = &brig_in, *brig_outp = &brig_out, *brig_swap; php_stream_filter_status_t status = PSFS_ERR_FATAL; php_stream_filter *filter; if (buf) { bucket = php_stream_bucket_new(stream, (char *)buf, count, 0, 0 TSRMLS_CC); php_stream_bucket_append(&brig_in, bucket TSRMLS_CC); } for (filter = stream->writefilters.head; filter; filter = filter->next) { /* for our return value, we are interested in the number of bytes consumed from * the first filter in the chain */ status = filter->fops->filter(stream, filter, brig_inp, brig_outp, filter == stream->writefilters.head ? &consumed : NULL, flags TSRMLS_CC); if (status != PSFS_PASS_ON) { break; } /* brig_out becomes brig_in. * brig_in will always be empty here, as the filter MUST attach any un-consumed buckets * to its own brigade */ brig_swap = brig_inp; brig_inp = brig_outp; brig_outp = brig_swap; memset(brig_outp, 0, sizeof(*brig_outp)); } switch (status) { case PSFS_PASS_ON: /* filter chain generated some output; push it through to the * underlying stream */ while (brig_inp->head) { bucket = brig_inp->head; _php_stream_write_buffer(stream, bucket->buf, bucket->buflen TSRMLS_CC); /* Potential error situation - eg: no space on device. Perhaps we should keep this brigade * hanging around and try to write it later. * At the moment, we just drop it on the floor * */ php_stream_bucket_unlink(bucket TSRMLS_CC); php_stream_bucket_delref(bucket TSRMLS_CC); } break; case PSFS_FEED_ME: /* need more data before we can push data through to the stream */ break; case PSFS_ERR_FATAL: /* some fatal error. Theoretically, the stream is borked, so all * further writes should fail. */ break; } return consumed; } PHPAPI int _php_stream_flush(php_stream *stream, int closing TSRMLS_DC) { int ret = 0; if (stream->writefilters.head) { _php_stream_write_filtered(stream, NULL, 0, closing ? PSFS_FLAG_FLUSH_CLOSE : PSFS_FLAG_FLUSH_INC TSRMLS_CC); } if (stream->ops->flush) { ret = stream->ops->flush(stream TSRMLS_CC); } return ret; } PHPAPI size_t _php_stream_write(php_stream *stream, const char *buf, size_t count TSRMLS_DC) { if (buf == NULL || count == 0 || stream->ops->write == NULL) { return 0; } if (stream->writefilters.head) { return _php_stream_write_filtered(stream, buf, count, PSFS_FLAG_NORMAL TSRMLS_CC); } else { return _php_stream_write_buffer(stream, buf, count TSRMLS_CC); } } PHPAPI size_t _php_stream_printf(php_stream *stream TSRMLS_DC, const char *fmt, ...) { size_t count; char *buf; va_list ap; va_start(ap, fmt); count = vspprintf(&buf, 0, fmt, ap); va_end(ap); if (!buf) { return 0; /* error condition */ } count = php_stream_write(stream, buf, count); efree(buf); return count; } PHPAPI off_t _php_stream_tell(php_stream *stream TSRMLS_DC) { return stream->position; } PHPAPI int _php_stream_seek(php_stream *stream, off_t offset, int whence TSRMLS_DC) { if (stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FOPENCOOKIE) { /* flush to commit data written to the fopencookie FILE* */ fflush(stream->stdiocast); } /* handle the case where we are in the buffer */ if ((stream->flags & PHP_STREAM_FLAG_NO_BUFFER) == 0) { switch(whence) { case SEEK_CUR: if (offset > 0 && offset <= stream->writepos - stream->readpos) { stream->readpos += offset; /* if offset = ..., then readpos = writepos */ stream->position += offset; stream->eof = 0; return 0; } break; case SEEK_SET: if (offset > stream->position && offset <= stream->position + stream->writepos - stream->readpos) { stream->readpos += offset - stream->position; stream->position = offset; stream->eof = 0; return 0; } break; } } if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) { int ret; if (stream->writefilters.head) { _php_stream_flush(stream, 0 TSRMLS_CC); } switch(whence) { case SEEK_CUR: offset = stream->position + offset; whence = SEEK_SET; break; } ret = stream->ops->seek(stream, offset, whence, &stream->position TSRMLS_CC); if (((stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) || ret == 0) { if (ret == 0) { stream->eof = 0; } /* invalidate the buffer contents */ stream->readpos = stream->writepos = 0; return ret; } /* else the stream has decided that it can't support seeking after all; * fall through to attempt emulation */ } /* emulate forward moving seeks with reads */ if (whence == SEEK_CUR && offset >= 0) { char tmp[1024]; size_t didread; while(offset > 0) { if ((didread = php_stream_read(stream, tmp, MIN(offset, sizeof(tmp)))) == 0) { return -1; } offset -= didread; } stream->eof = 0; return 0; } php_error_docref(NULL TSRMLS_CC, E_WARNING, "stream does not support seeking"); return -1; } PHPAPI int _php_stream_set_option(php_stream *stream, int option, int value, void *ptrparam TSRMLS_DC) { int ret = PHP_STREAM_OPTION_RETURN_NOTIMPL; if (stream->ops->set_option) { ret = stream->ops->set_option(stream, option, value, ptrparam TSRMLS_CC); } if (ret == PHP_STREAM_OPTION_RETURN_NOTIMPL) { switch(option) { case PHP_STREAM_OPTION_SET_CHUNK_SIZE: ret = stream->chunk_size; stream->chunk_size = value; return ret; case PHP_STREAM_OPTION_READ_BUFFER: /* try to match the buffer mode as best we can */ if (value == PHP_STREAM_BUFFER_NONE) { stream->flags |= PHP_STREAM_FLAG_NO_BUFFER; } else if (stream->flags & PHP_STREAM_FLAG_NO_BUFFER) { stream->flags ^= PHP_STREAM_FLAG_NO_BUFFER; } ret = PHP_STREAM_OPTION_RETURN_OK; break; default: ; } } return ret; } PHPAPI int _php_stream_truncate_set_size(php_stream *stream, size_t newsize TSRMLS_DC) { return php_stream_set_option(stream, PHP_STREAM_OPTION_TRUNCATE_API, PHP_STREAM_TRUNCATE_SET_SIZE, &newsize); } PHPAPI size_t _php_stream_passthru(php_stream * stream STREAMS_DC TSRMLS_DC) { size_t bcount = 0; char buf[8192]; int b; if (php_stream_mmap_possible(stream)) { char *p; size_t mapped; p = php_stream_mmap_range(stream, php_stream_tell(stream), PHP_STREAM_MMAP_ALL, PHP_STREAM_MAP_MODE_SHARED_READONLY, &mapped); if (p) { PHPWRITE(p, mapped); php_stream_mmap_unmap_ex(stream, mapped); return mapped; } } while ((b = php_stream_read(stream, buf, sizeof(buf))) > 0) { PHPWRITE(buf, b); bcount += b; } return bcount; } PHPAPI size_t _php_stream_copy_to_mem(php_stream *src, char **buf, size_t maxlen, int persistent STREAMS_DC TSRMLS_DC) { size_t ret = 0; char *ptr; size_t len = 0, max_len; int step = CHUNK_SIZE; int min_room = CHUNK_SIZE / 4; php_stream_statbuf ssbuf; if (maxlen == 0) { return 0; } if (maxlen == PHP_STREAM_COPY_ALL) { maxlen = 0; } if (maxlen > 0) { ptr = *buf = pemalloc_rel_orig(maxlen + 1, persistent); while ((len < maxlen) && !php_stream_eof(src)) { ret = php_stream_read(src, ptr, maxlen - len); if (!ret) { break; } len += ret; ptr += ret; } *ptr = '\0'; return len; } /* avoid many reallocs by allocating a good sized chunk to begin with, if * we can. Note that the stream may be filtered, in which case the stat * result may be inaccurate, as the filter may inflate or deflate the * number of bytes that we can read. In order to avoid an upsize followed * by a downsize of the buffer, overestimate by the step size (which is * 2K). */ if (php_stream_stat(src, &ssbuf) == 0 && ssbuf.sb.st_size > 0) { max_len = ssbuf.sb.st_size + step; } else { max_len = step; } ptr = *buf = pemalloc_rel_orig(max_len, persistent); while((ret = php_stream_read(src, ptr, max_len - len))) { len += ret; if (len + min_room >= max_len) { *buf = perealloc_rel_orig(*buf, max_len + step, persistent); max_len += step; ptr = *buf + len; } else { ptr += ret; } } if (len) { *buf = perealloc_rel_orig(*buf, len + 1, persistent); (*buf)[len] = '\0'; } else { pefree(*buf, persistent); *buf = NULL; } return len; } /* Returns SUCCESS/FAILURE and sets *len to the number of bytes moved */ PHPAPI int _php_stream_copy_to_stream_ex(php_stream *src, php_stream *dest, size_t maxlen, size_t *len STREAMS_DC TSRMLS_DC) { char buf[CHUNK_SIZE]; size_t readchunk; size_t haveread = 0; size_t didread; size_t dummy; php_stream_statbuf ssbuf; if (!len) { len = &dummy; } if (maxlen == 0) { *len = 0; return SUCCESS; } if (maxlen == PHP_STREAM_COPY_ALL) { maxlen = 0; } if (php_stream_stat(src, &ssbuf) == 0) { if (ssbuf.sb.st_size == 0 #ifdef S_ISREG && S_ISREG(ssbuf.sb.st_mode) #endif ) { *len = 0; return SUCCESS; } } if (php_stream_mmap_possible(src)) { char *p; size_t mapped; p = php_stream_mmap_range(src, php_stream_tell(src), maxlen, PHP_STREAM_MAP_MODE_SHARED_READONLY, &mapped); if (p) { mapped = php_stream_write(dest, p, mapped); php_stream_mmap_unmap_ex(src, mapped); *len = mapped; /* we've got at least 1 byte to read. * less than 1 is an error */ if (mapped > 0) { return SUCCESS; } return FAILURE; } } while(1) { readchunk = sizeof(buf); if (maxlen && (maxlen - haveread) < readchunk) { readchunk = maxlen - haveread; } didread = php_stream_read(src, buf, readchunk); if (didread) { /* extra paranoid */ size_t didwrite, towrite; char *writeptr; towrite = didread; writeptr = buf; haveread += didread; while(towrite) { didwrite = php_stream_write(dest, writeptr, towrite); if (didwrite == 0) { *len = haveread - (didread - towrite); return FAILURE; } towrite -= didwrite; writeptr += didwrite; } } else { break; } if (maxlen - haveread == 0) { break; } } *len = haveread; /* we've got at least 1 byte to read. * less than 1 is an error */ if (haveread > 0 || src->eof) { return SUCCESS; } return FAILURE; } /* Returns the number of bytes moved. * Returns 1 when source len is 0. * Deprecated in favor of php_stream_copy_to_stream_ex() */ ZEND_ATTRIBUTE_DEPRECATED PHPAPI size_t _php_stream_copy_to_stream(php_stream *src, php_stream *dest, size_t maxlen STREAMS_DC TSRMLS_DC) { size_t len; int ret = _php_stream_copy_to_stream_ex(src, dest, maxlen, &len STREAMS_REL_CC TSRMLS_CC); if (ret == SUCCESS && len == 0 && maxlen != 0) { return 1; } return len; } /* }}} */ /* {{{ wrapper init and registration */ static void stream_resource_regular_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC) { php_stream *stream = (php_stream*)rsrc->ptr; /* set the return value for pclose */ FG(pclose_ret) = php_stream_free(stream, PHP_STREAM_FREE_CLOSE | PHP_STREAM_FREE_RSRC_DTOR); } static void stream_resource_persistent_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC) { php_stream *stream = (php_stream*)rsrc->ptr; FG(pclose_ret) = php_stream_free(stream, PHP_STREAM_FREE_CLOSE | PHP_STREAM_FREE_RSRC_DTOR); } void php_shutdown_stream_hashes(TSRMLS_D) { if (FG(stream_wrappers)) { zend_hash_destroy(FG(stream_wrappers)); efree(FG(stream_wrappers)); FG(stream_wrappers) = NULL; } if (FG(stream_filters)) { zend_hash_destroy(FG(stream_filters)); efree(FG(stream_filters)); FG(stream_filters) = NULL; } if (FG(wrapper_errors)) { zend_hash_destroy(FG(wrapper_errors)); efree(FG(wrapper_errors)); FG(wrapper_errors) = NULL; } } int php_init_stream_wrappers(int module_number TSRMLS_DC) { le_stream = zend_register_list_destructors_ex(stream_resource_regular_dtor, NULL, "stream", module_number); le_pstream = zend_register_list_destructors_ex(NULL, stream_resource_persistent_dtor, "persistent stream", module_number); /* Filters are cleaned up by the streams they're attached to */ le_stream_filter = zend_register_list_destructors_ex(NULL, NULL, "stream filter", module_number); return ( zend_hash_init(&url_stream_wrappers_hash, 0, NULL, NULL, 1) == SUCCESS && zend_hash_init(php_get_stream_filters_hash_global(), 0, NULL, NULL, 1) == SUCCESS && zend_hash_init(php_stream_xport_get_hash(), 0, NULL, NULL, 1) == SUCCESS && php_stream_xport_register("tcp", php_stream_generic_socket_factory TSRMLS_CC) == SUCCESS && php_stream_xport_register("udp", php_stream_generic_socket_factory TSRMLS_CC) == SUCCESS #if defined(AF_UNIX) && !(defined(PHP_WIN32) || defined(__riscos__) || defined(NETWARE)) && php_stream_xport_register("unix", php_stream_generic_socket_factory TSRMLS_CC) == SUCCESS && php_stream_xport_register("udg", php_stream_generic_socket_factory TSRMLS_CC) == SUCCESS #endif ) ? SUCCESS : FAILURE; } int php_shutdown_stream_wrappers(int module_number TSRMLS_DC) { zend_hash_destroy(&url_stream_wrappers_hash); zend_hash_destroy(php_get_stream_filters_hash_global()); zend_hash_destroy(php_stream_xport_get_hash()); return SUCCESS; } /* Validate protocol scheme names during registration * Must conform to /^[a-zA-Z0-9+.-]+$/ */ static inline int php_stream_wrapper_scheme_validate(char *protocol, int protocol_len) { int i; for(i = 0; i < protocol_len; i++) { if (!isalnum((int)protocol[i]) && protocol[i] != '+' && protocol[i] != '-' && protocol[i] != '.') { return FAILURE; } } return SUCCESS; } /* API for registering GLOBAL wrappers */ PHPAPI int php_register_url_stream_wrapper(char *protocol, php_stream_wrapper *wrapper TSRMLS_DC) { int protocol_len = strlen(protocol); if (php_stream_wrapper_scheme_validate(protocol, protocol_len) == FAILURE) { return FAILURE; } return zend_hash_add(&url_stream_wrappers_hash, protocol, protocol_len + 1, &wrapper, sizeof(wrapper), NULL); } PHPAPI int php_unregister_url_stream_wrapper(char *protocol TSRMLS_DC) { return zend_hash_del(&url_stream_wrappers_hash, protocol, strlen(protocol) + 1); } static void clone_wrapper_hash(TSRMLS_D) { php_stream_wrapper *tmp; ALLOC_HASHTABLE(FG(stream_wrappers)); zend_hash_init(FG(stream_wrappers), zend_hash_num_elements(&url_stream_wrappers_hash), NULL, NULL, 1); zend_hash_copy(FG(stream_wrappers), &url_stream_wrappers_hash, NULL, &tmp, sizeof(tmp)); } /* API for registering VOLATILE wrappers */ PHPAPI int php_register_url_stream_wrapper_volatile(char *protocol, php_stream_wrapper *wrapper TSRMLS_DC) { int protocol_len = strlen(protocol); if (php_stream_wrapper_scheme_validate(protocol, protocol_len) == FAILURE) { return FAILURE; } if (!FG(stream_wrappers)) { clone_wrapper_hash(TSRMLS_C); } return zend_hash_add(FG(stream_wrappers), protocol, protocol_len + 1, &wrapper, sizeof(wrapper), NULL); } PHPAPI int php_unregister_url_stream_wrapper_volatile(char *protocol TSRMLS_DC) { if (!FG(stream_wrappers)) { clone_wrapper_hash(TSRMLS_C); } return zend_hash_del(FG(stream_wrappers), protocol, strlen(protocol) + 1); } /* }}} */ /* {{{ php_stream_locate_url_wrapper */ PHPAPI php_stream_wrapper *php_stream_locate_url_wrapper(const char *path, char **path_for_open, int options TSRMLS_DC) { HashTable *wrapper_hash = (FG(stream_wrappers) ? FG(stream_wrappers) : &url_stream_wrappers_hash); php_stream_wrapper **wrapperpp = NULL; const char *p, *protocol = NULL; int n = 0; if (path_for_open) { *path_for_open = (char*)path; } if (options & IGNORE_URL) { return (options & STREAM_LOCATE_WRAPPERS_ONLY) ? NULL : &php_plain_files_wrapper; } for (p = path; isalnum((int)*p) || *p == '+' || *p == '-' || *p == '.'; p++) { n++; } if ((*p == ':') && (n > 1) && (!strncmp("//", p+1, 2) || (n == 4 && !memcmp("data:", path, 5)))) { protocol = path; } else if (n == 5 && strncasecmp(path, "zlib:", 5) == 0) { /* BC with older php scripts and zlib wrapper */ protocol = "compress.zlib"; n = 13; php_error_docref(NULL TSRMLS_CC, E_WARNING, "Use of \"zlib:\" wrapper is deprecated; please use \"compress.zlib://\" instead"); } if (protocol) { char *tmp = estrndup(protocol, n); if (FAILURE == zend_hash_find(wrapper_hash, (char*)tmp, n + 1, (void**)&wrapperpp)) { php_strtolower(tmp, n); if (FAILURE == zend_hash_find(wrapper_hash, (char*)tmp, n + 1, (void**)&wrapperpp)) { char wrapper_name[32]; if (n >= sizeof(wrapper_name)) { n = sizeof(wrapper_name) - 1; } PHP_STRLCPY(wrapper_name, protocol, sizeof(wrapper_name), n); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to find the wrapper \"%s\" - did you forget to enable it when you configured PHP?", wrapper_name); wrapperpp = NULL; protocol = NULL; } } efree(tmp); } /* TODO: curl based streams probably support file:// properly */ if (!protocol || !strncasecmp(protocol, "file", n)) { /* fall back on regular file access */ php_stream_wrapper *plain_files_wrapper = &php_plain_files_wrapper; if (protocol) { int localhost = 0; if (!strncasecmp(path, "file://localhost/", 17)) { localhost = 1; } #ifdef PHP_WIN32 if (localhost == 0 && path[n+3] != '\0' && path[n+3] != '/' && path[n+4] != ':') { #else if (localhost == 0 && path[n+3] != '\0' && path[n+3] != '/') { #endif if (options & REPORT_ERRORS) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "remote host file access not supported, %s", path); } return NULL; } if (path_for_open) { /* skip past protocol and :/, but handle windows correctly */ *path_for_open = (char*)path + n + 1; if (localhost == 1) { (*path_for_open) += 11; } while (*(++*path_for_open)=='/'); #ifdef PHP_WIN32 if (*(*path_for_open + 1) != ':') #endif (*path_for_open)--; } } if (options & STREAM_LOCATE_WRAPPERS_ONLY) { return NULL; } if (FG(stream_wrappers)) { /* The file:// wrapper may have been disabled/overridden */ if (wrapperpp) { /* It was found so go ahead and provide it */ return *wrapperpp; } /* Check again, the original check might have not known the protocol name */ if (zend_hash_find(wrapper_hash, "file", sizeof("file"), (void**)&wrapperpp) == SUCCESS) { return *wrapperpp; } if (options & REPORT_ERRORS) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "file:// wrapper is disabled in the server configuration"); } return NULL; } return plain_files_wrapper; } if (wrapperpp && (*wrapperpp)->is_url && (options & STREAM_DISABLE_URL_PROTECTION) == 0 && (!PG(allow_url_fopen) || (((options & STREAM_OPEN_FOR_INCLUDE) || PG(in_user_include)) && !PG(allow_url_include)))) { if (options & REPORT_ERRORS) { /* protocol[n] probably isn't '\0' */ char *protocol_dup = estrndup(protocol, n); if (!PG(allow_url_fopen)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s:// wrapper is disabled in the server configuration by allow_url_fopen=0", protocol_dup); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s:// wrapper is disabled in the server configuration by allow_url_include=0", protocol_dup); } efree(protocol_dup); } return NULL; } return *wrapperpp; } /* }}} */ /* {{{ _php_stream_mkdir */ PHPAPI int _php_stream_mkdir(char *path, int mode, int options, php_stream_context *context TSRMLS_DC) { php_stream_wrapper *wrapper = NULL; wrapper = php_stream_locate_url_wrapper(path, NULL, 0 TSRMLS_CC); if (!wrapper || !wrapper->wops || !wrapper->wops->stream_mkdir) { return 0; } return wrapper->wops->stream_mkdir(wrapper, path, mode, options, context TSRMLS_CC); } /* }}} */ /* {{{ _php_stream_rmdir */ PHPAPI int _php_stream_rmdir(char *path, int options, php_stream_context *context TSRMLS_DC) { php_stream_wrapper *wrapper = NULL; wrapper = php_stream_locate_url_wrapper(path, NULL, 0 TSRMLS_CC); if (!wrapper || !wrapper->wops || !wrapper->wops->stream_rmdir) { return 0; } return wrapper->wops->stream_rmdir(wrapper, path, options, context TSRMLS_CC); } /* }}} */ /* {{{ _php_stream_stat_path */ PHPAPI int _php_stream_stat_path(char *path, int flags, php_stream_statbuf *ssb, php_stream_context *context TSRMLS_DC) { php_stream_wrapper *wrapper = NULL; char *path_to_open = path; int ret; /* Try to hit the cache first */ if (flags & PHP_STREAM_URL_STAT_LINK) { if (BG(CurrentLStatFile) && strcmp(path, BG(CurrentLStatFile)) == 0) { memcpy(ssb, &BG(lssb), sizeof(php_stream_statbuf)); return 0; } } else { if (BG(CurrentStatFile) && strcmp(path, BG(CurrentStatFile)) == 0) { memcpy(ssb, &BG(ssb), sizeof(php_stream_statbuf)); return 0; } } wrapper = php_stream_locate_url_wrapper(path, &path_to_open, 0 TSRMLS_CC); if (wrapper && wrapper->wops->url_stat) { ret = wrapper->wops->url_stat(wrapper, path_to_open, flags, ssb, context TSRMLS_CC); if (ret == 0) { /* Drop into cache */ if (flags & PHP_STREAM_URL_STAT_LINK) { if (BG(CurrentLStatFile)) { efree(BG(CurrentLStatFile)); } BG(CurrentLStatFile) = estrdup(path); memcpy(&BG(lssb), ssb, sizeof(php_stream_statbuf)); } else { if (BG(CurrentStatFile)) { efree(BG(CurrentStatFile)); } BG(CurrentStatFile) = estrdup(path); memcpy(&BG(ssb), ssb, sizeof(php_stream_statbuf)); } } return ret; } return -1; } /* }}} */ /* {{{ php_stream_opendir */ PHPAPI php_stream *_php_stream_opendir(char *path, int options, php_stream_context *context STREAMS_DC TSRMLS_DC) { php_stream *stream = NULL; php_stream_wrapper *wrapper = NULL; char *path_to_open; if (!path || !*path) { return NULL; } path_to_open = path; wrapper = php_stream_locate_url_wrapper(path, &path_to_open, options TSRMLS_CC); if (wrapper && wrapper->wops->dir_opener) { stream = wrapper->wops->dir_opener(wrapper, path_to_open, "r", options ^ REPORT_ERRORS, NULL, context STREAMS_REL_CC TSRMLS_CC); if (stream) { stream->wrapper = wrapper; stream->flags |= PHP_STREAM_FLAG_NO_BUFFER | PHP_STREAM_FLAG_IS_DIR; } } else if (wrapper) { php_stream_wrapper_log_error(wrapper, options ^ REPORT_ERRORS TSRMLS_CC, "not implemented"); } if (stream == NULL && (options & REPORT_ERRORS)) { php_stream_display_wrapper_errors(wrapper, path, "failed to open dir" TSRMLS_CC); } php_stream_tidy_wrapper_error_log(wrapper TSRMLS_CC); return stream; } /* }}} */ /* {{{ _php_stream_readdir */ PHPAPI php_stream_dirent *_php_stream_readdir(php_stream *dirstream, php_stream_dirent *ent TSRMLS_DC) { if (sizeof(php_stream_dirent) == php_stream_read(dirstream, (char*)ent, sizeof(php_stream_dirent))) { return ent; } return NULL; } /* }}} */ /* {{{ php_stream_open_wrapper_ex */ PHPAPI php_stream *_php_stream_open_wrapper_ex(char *path, char *mode, int options, char **opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC) { php_stream *stream = NULL; php_stream_wrapper *wrapper = NULL; char *path_to_open; int persistent = options & STREAM_OPEN_PERSISTENT; char *resolved_path = NULL; char *copy_of_path = NULL; if (opened_path) { *opened_path = NULL; } if (!path || !*path) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Filename cannot be empty"); return NULL; } if (options & USE_PATH) { resolved_path = zend_resolve_path(path, strlen(path) TSRMLS_CC); if (resolved_path) { path = resolved_path; /* we've found this file, don't re-check include_path or run realpath */ options |= STREAM_ASSUME_REALPATH; options &= ~USE_PATH; } } path_to_open = path; wrapper = php_stream_locate_url_wrapper(path, &path_to_open, options TSRMLS_CC); if (options & STREAM_USE_URL && (!wrapper || !wrapper->is_url)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "This function may only be used against URLs"); if (resolved_path) { efree(resolved_path); } return NULL; } if (wrapper) { if (!wrapper->wops->stream_opener) { php_stream_wrapper_log_error(wrapper, options ^ REPORT_ERRORS TSRMLS_CC, "wrapper does not support stream open"); } else { stream = wrapper->wops->stream_opener(wrapper, path_to_open, mode, options ^ REPORT_ERRORS, opened_path, context STREAMS_REL_CC TSRMLS_CC); } /* if the caller asked for a persistent stream but the wrapper did not * return one, force an error here */ if (stream && (options & STREAM_OPEN_PERSISTENT) && !stream->is_persistent) { php_stream_wrapper_log_error(wrapper, options ^ REPORT_ERRORS TSRMLS_CC, "wrapper does not support persistent streams"); php_stream_close(stream); stream = NULL; } if (stream) { stream->wrapper = wrapper; } } if (stream) { if (opened_path && !*opened_path && resolved_path) { *opened_path = resolved_path; resolved_path = NULL; } if (stream->orig_path) { pefree(stream->orig_path, persistent); } copy_of_path = pestrdup(path, persistent); stream->orig_path = copy_of_path; #if ZEND_DEBUG stream->open_filename = __zend_orig_filename ? __zend_orig_filename : __zend_filename; stream->open_lineno = __zend_orig_lineno ? __zend_orig_lineno : __zend_lineno; #endif } if (stream != NULL && (options & STREAM_MUST_SEEK)) { php_stream *newstream; switch(php_stream_make_seekable_rel(stream, &newstream, (options & STREAM_WILL_CAST) ? PHP_STREAM_PREFER_STDIO : PHP_STREAM_NO_PREFERENCE)) { case PHP_STREAM_UNCHANGED: if (resolved_path) { efree(resolved_path); } return stream; case PHP_STREAM_RELEASED: if (newstream->orig_path) { pefree(newstream->orig_path, persistent); } newstream->orig_path = pestrdup(path, persistent); if (resolved_path) { efree(resolved_path); } return newstream; default: php_stream_close(stream); stream = NULL; if (options & REPORT_ERRORS) { char *tmp = estrdup(path); php_strip_url_passwd(tmp); php_error_docref1(NULL TSRMLS_CC, tmp, E_WARNING, "could not make seekable - %s", tmp); efree(tmp); options ^= REPORT_ERRORS; } } } if (stream && stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0 && strchr(mode, 'a') && stream->position == 0) { off_t newpos = 0; /* if opened for append, we need to revise our idea of the initial file position */ if (0 == stream->ops->seek(stream, 0, SEEK_CUR, &newpos TSRMLS_CC)) { stream->position = newpos; } } if (stream == NULL && (options & REPORT_ERRORS)) { php_stream_display_wrapper_errors(wrapper, path, "failed to open stream" TSRMLS_CC); if (opened_path && *opened_path) { efree(*opened_path); *opened_path = NULL; } } php_stream_tidy_wrapper_error_log(wrapper TSRMLS_CC); #if ZEND_DEBUG if (stream == NULL && copy_of_path != NULL) { pefree(copy_of_path, persistent); } #endif if (resolved_path) { efree(resolved_path); } return stream; } /* }}} */ /* {{{ context API */ PHPAPI php_stream_context *php_stream_context_set(php_stream *stream, php_stream_context *context) { php_stream_context *oldcontext = stream->context; TSRMLS_FETCH(); stream->context = context; if (context) { zend_list_addref(context->rsrc_id); } if (oldcontext) { zend_list_delete(oldcontext->rsrc_id); } return oldcontext; } PHPAPI void php_stream_notification_notify(php_stream_context *context, int notifycode, int severity, char *xmsg, int xcode, size_t bytes_sofar, size_t bytes_max, void * ptr TSRMLS_DC) { if (context && context->notifier) context->notifier->func(context, notifycode, severity, xmsg, xcode, bytes_sofar, bytes_max, ptr TSRMLS_CC); } PHPAPI void php_stream_context_free(php_stream_context *context) { if (context->options) { zval_ptr_dtor(&context->options); context->options = NULL; } if (context->notifier) { php_stream_notification_free(context->notifier); context->notifier = NULL; } efree(context); } PHPAPI php_stream_context *php_stream_context_alloc(TSRMLS_D) { php_stream_context *context; context = ecalloc(1, sizeof(php_stream_context)); context->notifier = NULL; MAKE_STD_ZVAL(context->options); array_init(context->options); context->rsrc_id = ZEND_REGISTER_RESOURCE(NULL, context, php_le_stream_context(TSRMLS_C)); return context; } PHPAPI php_stream_notifier *php_stream_notification_alloc(void) { return ecalloc(1, sizeof(php_stream_notifier)); } PHPAPI void php_stream_notification_free(php_stream_notifier *notifier) { if (notifier->dtor) { notifier->dtor(notifier); } efree(notifier); } PHPAPI int php_stream_context_get_option(php_stream_context *context, const char *wrappername, const char *optionname, zval ***optionvalue) { zval **wrapperhash; if (FAILURE == zend_hash_find(Z_ARRVAL_P(context->options), (char*)wrappername, strlen(wrappername)+1, (void**)&wrapperhash)) { return FAILURE; } return zend_hash_find(Z_ARRVAL_PP(wrapperhash), (char*)optionname, strlen(optionname)+1, (void**)optionvalue); } PHPAPI int php_stream_context_set_option(php_stream_context *context, const char *wrappername, const char *optionname, zval *optionvalue) { zval **wrapperhash; zval *category, *copied_val; ALLOC_INIT_ZVAL(copied_val); *copied_val = *optionvalue; zval_copy_ctor(copied_val); INIT_PZVAL(copied_val); if (FAILURE == zend_hash_find(Z_ARRVAL_P(context->options), (char*)wrappername, strlen(wrappername)+1, (void**)&wrapperhash)) { MAKE_STD_ZVAL(category); array_init(category); if (FAILURE == zend_hash_update(Z_ARRVAL_P(context->options), (char*)wrappername, strlen(wrappername)+1, (void**)&category, sizeof(zval *), NULL)) { return FAILURE; } wrapperhash = &category; } return zend_hash_update(Z_ARRVAL_PP(wrapperhash), (char*)optionname, strlen(optionname)+1, (void**)&copied_val, sizeof(zval *), NULL); } /* }}} */ /* {{{ php_stream_dirent_alphasort */ PHPAPI int php_stream_dirent_alphasort(const char **a, const char **b) { return strcoll(*a, *b); } /* }}} */ /* {{{ php_stream_dirent_alphasortr */ PHPAPI int php_stream_dirent_alphasortr(const char **a, const char **b) { return strcoll(*b, *a); } /* }}} */ /* {{{ php_stream_scandir */ PHPAPI int _php_stream_scandir(char *dirname, char **namelist[], int flags, php_stream_context *context, int (*compare) (const char **a, const char **b) TSRMLS_DC) { php_stream *stream; php_stream_dirent sdp; char **vector = NULL; int vector_size = 0; int nfiles = 0; if (!namelist) { return FAILURE; } stream = php_stream_opendir(dirname, REPORT_ERRORS, context); if (!stream) { return FAILURE; } while (php_stream_readdir(stream, &sdp)) { if (nfiles == vector_size) { if (vector_size == 0) { vector_size = 10; } else { vector_size *= 2; } vector = (char **) erealloc(vector, vector_size * sizeof(char *)); } vector[nfiles] = estrdup(sdp.d_name); nfiles++; } php_stream_closedir(stream); *namelist = vector; if (compare) { qsort(*namelist, nfiles, sizeof(char *), (int(*)(const void *, const void *))compare); } return nfiles; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2012-03-08-0169020e49-cdc512afb3.c
manybugs_data_56
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #define ZEND_INTENSIVE_DEBUGGING 0 #include <stdio.h> #include <signal.h> #include "zend.h" #include "zend_compile.h" #include "zend_execute.h" #include "zend_API.h" #include "zend_ptr_stack.h" #include "zend_constants.h" #include "zend_extensions.h" #include "zend_ini.h" #include "zend_exceptions.h" #include "zend_interfaces.h" #include "zend_closures.h" #include "zend_vm.h" #include "zend_dtrace.h" /* Virtual current working directory support */ #include "tsrm_virtual_cwd.h" #define _CONST_CODE 0 #define _TMP_CODE 1 #define _VAR_CODE 2 #define _UNUSED_CODE 3 #define _CV_CODE 4 typedef int (*incdec_t)(zval *); #define get_zval_ptr(op_type, node, Ts, should_free, type) _get_zval_ptr(op_type, node, Ts, should_free, type TSRMLS_CC) #define get_zval_ptr_ptr(op_type, node, Ts, should_free, type) _get_zval_ptr_ptr(op_type, node, Ts, should_free, type TSRMLS_CC) #define get_obj_zval_ptr(op_type, node, Ts, should_free, type) _get_obj_zval_ptr(op_type, node, Ts, should_free, type TSRMLS_CC) #define get_obj_zval_ptr_ptr(op_type, node, Ts, should_free, type) _get_obj_zval_ptr_ptr(op_type, node, Ts, should_free, type TSRMLS_CC) /* Prototypes */ static void zend_extension_statement_handler(const zend_extension *extension, zend_op_array *op_array TSRMLS_DC); static void zend_extension_fcall_begin_handler(const zend_extension *extension, zend_op_array *op_array TSRMLS_DC); static void zend_extension_fcall_end_handler(const zend_extension *extension, zend_op_array *op_array TSRMLS_DC); #define RETURN_VALUE_USED(opline) (!((opline)->result_type & EXT_TYPE_UNUSED)) #define T(offset) (*(temp_variable *)((char *) Ts + offset)) #define CV(var) CVs[var] #define TEMP_VAR_STACK_LIMIT 2000 static zend_always_inline void zend_pzval_unlock_func(zval *z, zend_free_op *should_free, int unref TSRMLS_DC) { if (!Z_DELREF_P(z)) { Z_SET_REFCOUNT_P(z, 1); Z_UNSET_ISREF_P(z); should_free->var = z; /* should_free->is_var = 1; */ } else { should_free->var = 0; if (unref && Z_ISREF_P(z) && Z_REFCOUNT_P(z) == 1) { Z_UNSET_ISREF_P(z); } GC_ZVAL_CHECK_POSSIBLE_ROOT(z); } } static zend_always_inline void zend_pzval_unlock_free_func(zval *z TSRMLS_DC) { if (!Z_DELREF_P(z)) { if (z != &EG(uninitialized_zval)) { GC_REMOVE_ZVAL_FROM_BUFFER(z); zval_dtor(z); efree(z); } } } #undef zval_ptr_dtor #define zval_ptr_dtor(pzv) i_zval_ptr_dtor(*(pzv) ZEND_FILE_LINE_CC) #define PZVAL_UNLOCK(z, f) zend_pzval_unlock_func(z, f, 1 TSRMLS_CC) #define PZVAL_UNLOCK_EX(z, f, u) zend_pzval_unlock_func(z, f, u TSRMLS_CC) #define PZVAL_UNLOCK_FREE(z) zend_pzval_unlock_free_func(z TSRMLS_CC) #define PZVAL_LOCK(z) Z_ADDREF_P((z)) #define SELECTIVE_PZVAL_LOCK(pzv, opline) if (RETURN_VALUE_USED(opline)) { PZVAL_LOCK(pzv); } #define EXTRACT_ZVAL_PTR(t) do { \ temp_variable *__t = (t); \ if (__t->var.ptr_ptr) { \ __t->var.ptr = *__t->var.ptr_ptr; \ __t->var.ptr_ptr = &__t->var.ptr; \ if (!PZVAL_IS_REF(__t->var.ptr) && \ Z_REFCOUNT_P(__t->var.ptr) > 2) { \ SEPARATE_ZVAL(__t->var.ptr_ptr); \ } \ } \ } while (0) #define AI_SET_PTR(t, val) do { \ temp_variable *__t = (t); \ __t->var.ptr = (val); \ __t->var.ptr_ptr = &__t->var.ptr; \ } while (0) #define FREE_OP(should_free) \ if (should_free.var) { \ if ((zend_uintptr_t)should_free.var & 1L) { \ zval_dtor((zval*)((zend_uintptr_t)should_free.var & ~1L)); \ } else { \ zval_ptr_dtor(&should_free.var); \ } \ } #define FREE_OP_IF_VAR(should_free) \ if (should_free.var != NULL && (((zend_uintptr_t)should_free.var & 1L) == 0)) { \ zval_ptr_dtor(&should_free.var); \ } #define FREE_OP_VAR_PTR(should_free) \ if (should_free.var) { \ zval_ptr_dtor(&should_free.var); \ } #define TMP_FREE(z) (zval*)(((zend_uintptr_t)(z)) | 1L) #define IS_TMP_FREE(should_free) ((zend_uintptr_t)should_free.var & 1L) #define MAKE_REAL_ZVAL_PTR(val) \ do { \ zval *_tmp; \ ALLOC_ZVAL(_tmp); \ INIT_PZVAL_COPY(_tmp, (val)); \ (val) = _tmp; \ } while (0) /* End of zend_execute_locks.h */ #define CV_OF(i) (EG(current_execute_data)->CVs[i]) #define CV_DEF_OF(i) (EG(active_op_array)->vars[i]) #define CTOR_CALL_BIT 0x1 #define CTOR_USED_BIT 0x2 #define IS_CTOR_CALL(ce) (((zend_uintptr_t)(ce)) & CTOR_CALL_BIT) #define IS_CTOR_USED(ce) (((zend_uintptr_t)(ce)) & CTOR_USED_BIT) #define ENCODE_CTOR(ce, used) \ ((zend_class_entry*)(((zend_uintptr_t)(ce)) | CTOR_CALL_BIT | ((used) ? CTOR_USED_BIT : 0))) #define DECODE_CTOR(ce) \ ((zend_class_entry*)(((zend_uintptr_t)(ce)) & ~(CTOR_CALL_BIT|CTOR_USED_BIT))) ZEND_API zval** zend_get_compiled_variable_value(const zend_execute_data *execute_data_ptr, zend_uint var) { return execute_data_ptr->CVs[var]; } static zend_always_inline zval *_get_zval_ptr_tmp(zend_uint var, const temp_variable *Ts, zend_free_op *should_free TSRMLS_DC) { return should_free->var = &T(var).tmp_var; } static zend_always_inline zval *_get_zval_ptr_var(zend_uint var, const temp_variable *Ts, zend_free_op *should_free TSRMLS_DC) { zval *ptr = T(var).var.ptr; PZVAL_UNLOCK(ptr, should_free); return ptr; } static zend_never_inline zval **_get_zval_cv_lookup(zval ***ptr, zend_uint var, int type TSRMLS_DC) { zend_compiled_variable *cv = &CV_DEF_OF(var); if (!EG(active_symbol_table) || zend_hash_quick_find(EG(active_symbol_table), cv->name, cv->name_len+1, cv->hash_value, (void **)ptr)==FAILURE) { switch (type) { case BP_VAR_R: case BP_VAR_UNSET: zend_error(E_NOTICE, "Undefined variable: %s", cv->name); /* break missing intentionally */ case BP_VAR_IS: return &EG(uninitialized_zval_ptr); break; case BP_VAR_RW: zend_error(E_NOTICE, "Undefined variable: %s", cv->name); /* break missing intentionally */ case BP_VAR_W: Z_ADDREF(EG(uninitialized_zval)); if (!EG(active_symbol_table)) { *ptr = (zval**)EG(current_execute_data)->CVs + (EG(active_op_array)->last_var + var); **ptr = &EG(uninitialized_zval); } else { zend_hash_quick_update(EG(active_symbol_table), cv->name, cv->name_len+1, cv->hash_value, &EG(uninitialized_zval_ptr), sizeof(zval *), (void **)ptr); } break; } } return *ptr; } static zend_never_inline zval **_get_zval_cv_lookup_BP_VAR_R(zval ***ptr, zend_uint var TSRMLS_DC) { zend_compiled_variable *cv = &CV_DEF_OF(var); if (!EG(active_symbol_table) || zend_hash_quick_find(EG(active_symbol_table), cv->name, cv->name_len+1, cv->hash_value, (void **)ptr)==FAILURE) { zend_error(E_NOTICE, "Undefined variable: %s", cv->name); return &EG(uninitialized_zval_ptr); } return *ptr; } static zend_never_inline zval **_get_zval_cv_lookup_BP_VAR_UNSET(zval ***ptr, zend_uint var TSRMLS_DC) { zend_compiled_variable *cv = &CV_DEF_OF(var); if (!EG(active_symbol_table) || zend_hash_quick_find(EG(active_symbol_table), cv->name, cv->name_len+1, cv->hash_value, (void **)ptr)==FAILURE) { zend_error(E_NOTICE, "Undefined variable: %s", cv->name); return &EG(uninitialized_zval_ptr); } return *ptr; } static zend_never_inline zval **_get_zval_cv_lookup_BP_VAR_IS(zval ***ptr, zend_uint var TSRMLS_DC) { zend_compiled_variable *cv = &CV_DEF_OF(var); if (!EG(active_symbol_table) || zend_hash_quick_find(EG(active_symbol_table), cv->name, cv->name_len+1, cv->hash_value, (void **)ptr)==FAILURE) { return &EG(uninitialized_zval_ptr); } return *ptr; } static zend_never_inline zval **_get_zval_cv_lookup_BP_VAR_RW(zval ***ptr, zend_uint var TSRMLS_DC) { zend_compiled_variable *cv = &CV_DEF_OF(var); if (!EG(active_symbol_table)) { Z_ADDREF(EG(uninitialized_zval)); *ptr = (zval**)EG(current_execute_data)->CVs + (EG(active_op_array)->last_var + var); **ptr = &EG(uninitialized_zval); zend_error(E_NOTICE, "Undefined variable: %s", cv->name); } else if (zend_hash_quick_find(EG(active_symbol_table), cv->name, cv->name_len+1, cv->hash_value, (void **)ptr)==FAILURE) { Z_ADDREF(EG(uninitialized_zval)); zend_hash_quick_update(EG(active_symbol_table), cv->name, cv->name_len+1, cv->hash_value, &EG(uninitialized_zval_ptr), sizeof(zval *), (void **)ptr); zend_error(E_NOTICE, "Undefined variable: %s", cv->name); } return *ptr; } static zend_never_inline zval **_get_zval_cv_lookup_BP_VAR_W(zval ***ptr, zend_uint var TSRMLS_DC) { zend_compiled_variable *cv = &CV_DEF_OF(var); if (!EG(active_symbol_table)) { Z_ADDREF(EG(uninitialized_zval)); *ptr = (zval**)EG(current_execute_data)->CVs + (EG(active_op_array)->last_var + var); **ptr = &EG(uninitialized_zval); } else if (zend_hash_quick_find(EG(active_symbol_table), cv->name, cv->name_len+1, cv->hash_value, (void **)ptr)==FAILURE) { Z_ADDREF(EG(uninitialized_zval)); zend_hash_quick_update(EG(active_symbol_table), cv->name, cv->name_len+1, cv->hash_value, &EG(uninitialized_zval_ptr), sizeof(zval *), (void **)ptr); } return *ptr; } static zend_always_inline zval *_get_zval_ptr_cv(zend_uint var, int type TSRMLS_DC) { zval ***ptr = &CV_OF(var); if (UNEXPECTED(*ptr == NULL)) { return *_get_zval_cv_lookup(ptr, var, type TSRMLS_CC); } return **ptr; } static zend_always_inline zval *_get_zval_ptr_cv_BP_VAR_R(zval ***CVs, zend_uint var TSRMLS_DC) { zval ***ptr = &CV(var); if (UNEXPECTED(*ptr == NULL)) { return *_get_zval_cv_lookup_BP_VAR_R(ptr, var TSRMLS_CC); } return **ptr; } static zend_always_inline zval *_get_zval_ptr_cv_BP_VAR_UNSET(zval ***CVs, zend_uint var TSRMLS_DC) { zval ***ptr = &CV(var); if (UNEXPECTED(*ptr == NULL)) { return *_get_zval_cv_lookup_BP_VAR_UNSET(ptr, var TSRMLS_CC); } return **ptr; } static zend_always_inline zval *_get_zval_ptr_cv_BP_VAR_IS(zval ***CVs, zend_uint var TSRMLS_DC) { zval ***ptr = &CV(var); if (UNEXPECTED(*ptr == NULL)) { return *_get_zval_cv_lookup_BP_VAR_IS(ptr, var TSRMLS_CC); } return **ptr; } static zend_always_inline zval *_get_zval_ptr_cv_BP_VAR_RW(zval ***CVs, zend_uint var TSRMLS_DC) { zval ***ptr = &CV(var); if (UNEXPECTED(*ptr == NULL)) { return *_get_zval_cv_lookup_BP_VAR_RW(ptr, var TSRMLS_CC); } return **ptr; } static zend_always_inline zval *_get_zval_ptr_cv_BP_VAR_W(zval ***CVs, zend_uint var TSRMLS_DC) { zval ***ptr = &CV(var); if (UNEXPECTED(*ptr == NULL)) { return *_get_zval_cv_lookup_BP_VAR_W(ptr, var TSRMLS_CC); } return **ptr; } static inline zval *_get_zval_ptr(int op_type, const znode_op *node, const temp_variable *Ts, zend_free_op *should_free, int type TSRMLS_DC) { /* should_free->is_var = 0; */ switch (op_type) { case IS_CONST: should_free->var = 0; return node->zv; break; case IS_TMP_VAR: should_free->var = TMP_FREE(&T(node->var).tmp_var); return &T(node->var).tmp_var; break; case IS_VAR: return _get_zval_ptr_var(node->var, Ts, should_free TSRMLS_CC); break; case IS_UNUSED: should_free->var = 0; return NULL; break; case IS_CV: should_free->var = 0; return _get_zval_ptr_cv(node->var, type TSRMLS_CC); break; EMPTY_SWITCH_DEFAULT_CASE() } return NULL; } static zend_always_inline zval **_get_zval_ptr_ptr_var(zend_uint var, const temp_variable *Ts, zend_free_op *should_free TSRMLS_DC) { zval** ptr_ptr = T(var).var.ptr_ptr; if (EXPECTED(ptr_ptr != NULL)) { PZVAL_UNLOCK(*ptr_ptr, should_free); } else { /* string offset */ PZVAL_UNLOCK(T(var).str_offset.str, should_free); } return ptr_ptr; } static zend_always_inline zval **_get_zval_ptr_ptr_cv(zend_uint var, int type TSRMLS_DC) { zval ***ptr = &CV_OF(var); if (UNEXPECTED(*ptr == NULL)) { return _get_zval_cv_lookup(ptr, var, type TSRMLS_CC); } return *ptr; } static zend_always_inline zval **_get_zval_ptr_ptr_cv_BP_VAR_R(zval ***CVs, zend_uint var TSRMLS_DC) { zval ***ptr = &CV(var); if (UNEXPECTED(*ptr == NULL)) { return _get_zval_cv_lookup_BP_VAR_R(ptr, var TSRMLS_CC); } return *ptr; } static zend_always_inline zval **_get_zval_ptr_ptr_cv_BP_VAR_UNSET(zval ***CVs, zend_uint var TSRMLS_DC) { zval ***ptr = &CV(var); if (UNEXPECTED(*ptr == NULL)) { return _get_zval_cv_lookup_BP_VAR_UNSET(ptr, var TSRMLS_CC); } return *ptr; } static zend_always_inline zval **_get_zval_ptr_ptr_cv_BP_VAR_IS(zval ***CVs, zend_uint var TSRMLS_DC) { zval ***ptr = &CV(var); if (UNEXPECTED(*ptr == NULL)) { return _get_zval_cv_lookup_BP_VAR_IS(ptr, var TSRMLS_CC); } return *ptr; } static zend_always_inline zval **_get_zval_ptr_ptr_cv_BP_VAR_RW(zval ***CVs, zend_uint var TSRMLS_DC) { zval ***ptr = &CV(var); if (UNEXPECTED(*ptr == NULL)) { return _get_zval_cv_lookup_BP_VAR_RW(ptr, var TSRMLS_CC); } return *ptr; } static zend_always_inline zval **_get_zval_ptr_ptr_cv_BP_VAR_W(zval ***CVs, zend_uint var TSRMLS_DC) { zval ***ptr = &CV(var); if (UNEXPECTED(*ptr == NULL)) { return _get_zval_cv_lookup_BP_VAR_W(ptr, var TSRMLS_CC); } return *ptr; } static inline zval **_get_zval_ptr_ptr(int op_type, const znode_op *node, const temp_variable *Ts, zend_free_op *should_free, int type TSRMLS_DC) { if (op_type == IS_CV) { should_free->var = 0; return _get_zval_ptr_ptr_cv(node->var, type TSRMLS_CC); } else if (op_type == IS_VAR) { return _get_zval_ptr_ptr_var(node->var, Ts, should_free TSRMLS_CC); } else { should_free->var = 0; return NULL; } } static zend_always_inline zval *_get_obj_zval_ptr_unused(TSRMLS_D) { if (EXPECTED(EG(This) != NULL)) { return EG(This); } else { zend_error_noreturn(E_ERROR, "Using $this when not in object context"); return NULL; } } static inline zval **_get_obj_zval_ptr_ptr(int op_type, const znode_op *op, const temp_variable *Ts, zend_free_op *should_free, int type TSRMLS_DC) { if (op_type == IS_UNUSED) { if (EXPECTED(EG(This) != NULL)) { /* this should actually never be modified, _ptr_ptr is modified only when the object is empty */ should_free->var = 0; return &EG(This); } else { zend_error_noreturn(E_ERROR, "Using $this when not in object context"); } } return get_zval_ptr_ptr(op_type, op, Ts, should_free, type); } static zend_always_inline zval **_get_obj_zval_ptr_ptr_unused(TSRMLS_D) { if (EXPECTED(EG(This) != NULL)) { return &EG(This); } else { zend_error_noreturn(E_ERROR, "Using $this when not in object context"); return NULL; } } static inline zval *_get_obj_zval_ptr(int op_type, znode_op *op, const temp_variable *Ts, zend_free_op *should_free, int type TSRMLS_DC) { if (op_type == IS_UNUSED) { if (EXPECTED(EG(This) != NULL)) { should_free->var = 0; return EG(This); } else { zend_error_noreturn(E_ERROR, "Using $this when not in object context"); } } return get_zval_ptr(op_type, op, Ts, should_free, type); } static void zend_assign_to_variable_reference(zval **variable_ptr_ptr, zval **value_ptr_ptr TSRMLS_DC) { zval *variable_ptr = *variable_ptr_ptr; zval *value_ptr = *value_ptr_ptr; if (variable_ptr == &EG(error_zval) || value_ptr == &EG(error_zval)) { variable_ptr_ptr = &EG(uninitialized_zval_ptr); } else if (variable_ptr != value_ptr) { if (!PZVAL_IS_REF(value_ptr)) { /* break it away */ Z_DELREF_P(value_ptr); if (Z_REFCOUNT_P(value_ptr)>0) { ALLOC_ZVAL(*value_ptr_ptr); ZVAL_COPY_VALUE(*value_ptr_ptr, value_ptr); value_ptr = *value_ptr_ptr; zendi_zval_copy_ctor(*value_ptr); } Z_SET_REFCOUNT_P(value_ptr, 1); Z_SET_ISREF_P(value_ptr); } *variable_ptr_ptr = value_ptr; Z_ADDREF_P(value_ptr); zval_ptr_dtor(&variable_ptr); } else if (!Z_ISREF_P(variable_ptr)) { if (variable_ptr_ptr == value_ptr_ptr) { SEPARATE_ZVAL(variable_ptr_ptr); } else if (variable_ptr==&EG(uninitialized_zval) || Z_REFCOUNT_P(variable_ptr)>2) { /* we need to separate */ Z_SET_REFCOUNT_P(variable_ptr, Z_REFCOUNT_P(variable_ptr) - 2); ALLOC_ZVAL(*variable_ptr_ptr); ZVAL_COPY_VALUE(*variable_ptr_ptr, variable_ptr); zval_copy_ctor(*variable_ptr_ptr); *value_ptr_ptr = *variable_ptr_ptr; Z_SET_REFCOUNT_PP(variable_ptr_ptr, 2); } Z_SET_ISREF_PP(variable_ptr_ptr); } } /* this should modify object only if it's empty */ static inline void make_real_object(zval **object_ptr TSRMLS_DC) { if (Z_TYPE_PP(object_ptr) == IS_NULL || (Z_TYPE_PP(object_ptr) == IS_BOOL && Z_LVAL_PP(object_ptr) == 0) || (Z_TYPE_PP(object_ptr) == IS_STRING && Z_STRLEN_PP(object_ptr) == 0) ) { zend_error(E_WARNING, "Creating default object from empty value"); SEPARATE_ZVAL_IF_NOT_REF(object_ptr); zval_dtor(*object_ptr); object_init(*object_ptr); } } ZEND_API char * zend_verify_arg_class_kind(const zend_arg_info *cur_arg_info, ulong fetch_type, const char **class_name, zend_class_entry **pce TSRMLS_DC) { *pce = zend_fetch_class(cur_arg_info->class_name, cur_arg_info->class_name_len, (fetch_type | ZEND_FETCH_CLASS_AUTO | ZEND_FETCH_CLASS_NO_AUTOLOAD) TSRMLS_CC); *class_name = (*pce) ? (*pce)->name: cur_arg_info->class_name; if (*pce && (*pce)->ce_flags & ZEND_ACC_INTERFACE) { return "implement interface "; } else { return "be an instance of "; } } ZEND_API int zend_verify_arg_error(int error_type, const zend_function *zf, zend_uint arg_num, const char *need_msg, const char *need_kind, const char *given_msg, char *given_kind TSRMLS_DC) { zend_execute_data *ptr = EG(current_execute_data)->prev_execute_data; char *fname = zf->common.function_name; char *fsep; const char *fclass; if (zf->common.scope) { fsep = "::"; fclass = zf->common.scope->name; } else { fsep = ""; fclass = ""; } if (ptr && ptr->op_array) { zend_error(error_type, "Argument %d passed to %s%s%s() must %s%s, %s%s given, called in %s on line %d and defined", arg_num, fclass, fsep, fname, need_msg, need_kind, given_msg, given_kind, ptr->op_array->filename, ptr->opline->lineno); } else { zend_error(error_type, "Argument %d passed to %s%s%s() must %s%s, %s%s given", arg_num, fclass, fsep, fname, need_msg, need_kind, given_msg, given_kind); } return 0; } static inline int zend_verify_arg_type(zend_function *zf, zend_uint arg_num, zval *arg, ulong fetch_type TSRMLS_DC) { zend_arg_info *cur_arg_info; char *need_msg; zend_class_entry *ce; if (!zf->common.arg_info || arg_num>zf->common.num_args) { return 1; } cur_arg_info = &zf->common.arg_info[arg_num-1]; if (cur_arg_info->class_name) { const char *class_name; if (!arg) { need_msg = zend_verify_arg_class_kind(cur_arg_info, fetch_type, &class_name, &ce TSRMLS_CC); return zend_verify_arg_error(E_RECOVERABLE_ERROR, zf, arg_num, need_msg, class_name, "none", "" TSRMLS_CC); } if (Z_TYPE_P(arg) == IS_OBJECT) { need_msg = zend_verify_arg_class_kind(cur_arg_info, fetch_type, &class_name, &ce TSRMLS_CC); if (!ce || !instanceof_function(Z_OBJCE_P(arg), ce TSRMLS_CC)) { return zend_verify_arg_error(E_RECOVERABLE_ERROR, zf, arg_num, need_msg, class_name, "instance of ", Z_OBJCE_P(arg)->name TSRMLS_CC); } } else if (Z_TYPE_P(arg) != IS_NULL || !cur_arg_info->allow_null) { need_msg = zend_verify_arg_class_kind(cur_arg_info, fetch_type, &class_name, &ce TSRMLS_CC); return zend_verify_arg_error(E_RECOVERABLE_ERROR, zf, arg_num, need_msg, class_name, zend_zval_type_name(arg), "" TSRMLS_CC); } } else if (cur_arg_info->type_hint && cur_arg_info->type_hint == IS_ARRAY) { if (!arg) { return zend_verify_arg_error(E_RECOVERABLE_ERROR, zf, arg_num, "be of the type array", "", "none", "" TSRMLS_CC); } if (Z_TYPE_P(arg) != IS_ARRAY && (Z_TYPE_P(arg) != IS_NULL || !cur_arg_info->allow_null)) { return zend_verify_arg_error(E_RECOVERABLE_ERROR, zf, arg_num, "be of the type array", "", zend_zval_type_name(arg), "" TSRMLS_CC); } } return 1; } static inline void zend_assign_to_object(zval **retval, zval **object_ptr, zval *property_name, int value_type, znode_op *value_op, const temp_variable *Ts, int opcode, const zend_literal *key TSRMLS_DC) { zval *object = *object_ptr; zend_free_op free_value; zval *value = get_zval_ptr(value_type, value_op, Ts, &free_value, BP_VAR_R); if (Z_TYPE_P(object) != IS_OBJECT) { if (object == &EG(error_zval)) { if (retval) { *retval = &EG(uninitialized_zval); PZVAL_LOCK(*retval); } FREE_OP(free_value); return; } if (Z_TYPE_P(object) == IS_NULL || (Z_TYPE_P(object) == IS_BOOL && Z_LVAL_P(object) == 0) || (Z_TYPE_P(object) == IS_STRING && Z_STRLEN_P(object) == 0)) { SEPARATE_ZVAL_IF_NOT_REF(object_ptr); zval_dtor(*object_ptr); object_init(*object_ptr); object = *object_ptr; zend_error(E_WARNING, "Creating default object from empty value"); } else { zend_error(E_WARNING, "Attempt to assign property of non-object"); if (retval) { *retval = &EG(uninitialized_zval); PZVAL_LOCK(*retval); } FREE_OP(free_value); return; } } /* separate our value if necessary */ if (value_type == IS_TMP_VAR) { zval *orig_value = value; ALLOC_ZVAL(value); ZVAL_COPY_VALUE(value, orig_value); Z_UNSET_ISREF_P(value); Z_SET_REFCOUNT_P(value, 0); } else if (value_type == IS_CONST) { zval *orig_value = value; ALLOC_ZVAL(value); ZVAL_COPY_VALUE(value, orig_value); Z_UNSET_ISREF_P(value); Z_SET_REFCOUNT_P(value, 0); zval_copy_ctor(value); } Z_ADDREF_P(value); if (opcode == ZEND_ASSIGN_OBJ) { if (!Z_OBJ_HT_P(object)->write_property) { zend_error(E_WARNING, "Attempt to assign property of non-object"); if (retval) { *retval = &EG(uninitialized_zval); PZVAL_LOCK(&EG(uninitialized_zval)); } if (value_type == IS_TMP_VAR) { FREE_ZVAL(value); } else if (value_type == IS_CONST) { zval_ptr_dtor(&value); } FREE_OP(free_value); return; } Z_OBJ_HT_P(object)->write_property(object, property_name, value, key TSRMLS_CC); } else { /* Note: property_name in this case is really the array index! */ if (!Z_OBJ_HT_P(object)->write_dimension) { zend_error_noreturn(E_ERROR, "Cannot use object as array"); } Z_OBJ_HT_P(object)->write_dimension(object, property_name, value TSRMLS_CC); } if (retval && !EG(exception)) { *retval = value; PZVAL_LOCK(value); } zval_ptr_dtor(&value); FREE_OP_IF_VAR(free_value); } static inline int zend_assign_to_string_offset(const temp_variable *T, const zval *value, int value_type TSRMLS_DC) { if (Z_TYPE_P(T->str_offset.str) == IS_STRING) { if (((int)T->str_offset.offset < 0)) { zend_error(E_WARNING, "Illegal string offset: %d", T->str_offset.offset); return 0; } if (T->str_offset.offset >= Z_STRLEN_P(T->str_offset.str)) { if (IS_INTERNED(Z_STRVAL_P(T->str_offset.str))) { char *tmp = (char *) emalloc(T->str_offset.offset+1+1); memcpy(tmp, Z_STRVAL_P(T->str_offset.str), T->str_offset.offset+1+1); Z_STRVAL_P(T->str_offset.str) = tmp; } else { Z_STRVAL_P(T->str_offset.str) = (char *) erealloc(Z_STRVAL_P(T->str_offset.str), T->str_offset.offset+1+1); } memset(Z_STRVAL_P(T->str_offset.str) + Z_STRLEN_P(T->str_offset.str), ' ', T->str_offset.offset - Z_STRLEN_P(T->str_offset.str)); Z_STRVAL_P(T->str_offset.str)[T->str_offset.offset+1] = 0; Z_STRLEN_P(T->str_offset.str) = T->str_offset.offset+1; } else if (IS_INTERNED(Z_STRVAL_P(T->str_offset.str))) { char *tmp = (char *) emalloc(Z_STRLEN_P(T->str_offset.str) + 1); memcpy(tmp, Z_STRVAL_P(T->str_offset.str), Z_STRLEN_P(T->str_offset.str) + 1); Z_STRVAL_P(T->str_offset.str) = tmp; } if (Z_TYPE_P(value) != IS_STRING) { zval tmp; ZVAL_COPY_VALUE(&tmp, value); if (value_type != IS_TMP_VAR) { zval_copy_ctor(&tmp); } convert_to_string(&tmp); Z_STRVAL_P(T->str_offset.str)[T->str_offset.offset] = Z_STRVAL(tmp)[0]; STR_FREE(Z_STRVAL(tmp)); } else { Z_STRVAL_P(T->str_offset.str)[T->str_offset.offset] = Z_STRVAL_P(value)[0]; if (value_type == IS_TMP_VAR) { /* we can safely free final_value here * because separation is done only * in case value_type == IS_VAR */ STR_FREE(Z_STRVAL_P(value)); } } /* * the value of an assignment to a string offset is undefined T(result->u.var).var = &T->str_offset.str; */ } return 1; } static inline zval* zend_assign_tmp_to_variable(zval **variable_ptr_ptr, zval *value TSRMLS_DC) { zval *variable_ptr = *variable_ptr_ptr; zval garbage; if (Z_TYPE_P(variable_ptr) == IS_OBJECT && UNEXPECTED(Z_OBJ_HANDLER_P(variable_ptr, set) != NULL)) { Z_OBJ_HANDLER_P(variable_ptr, set)(variable_ptr_ptr, value TSRMLS_CC); return variable_ptr; } if (UNEXPECTED(Z_REFCOUNT_P(variable_ptr) > 1) && EXPECTED(!PZVAL_IS_REF(variable_ptr))) { /* we need to split */ Z_DELREF_P(variable_ptr); GC_ZVAL_CHECK_POSSIBLE_ROOT(variable_ptr); ALLOC_ZVAL(variable_ptr); INIT_PZVAL_COPY(variable_ptr, value); *variable_ptr_ptr = variable_ptr; return variable_ptr; } else { if (EXPECTED(Z_TYPE_P(variable_ptr) <= IS_BOOL)) { /* nothing to destroy */ ZVAL_COPY_VALUE(variable_ptr, value); } else { ZVAL_COPY_VALUE(&garbage, variable_ptr); ZVAL_COPY_VALUE(variable_ptr, value); _zval_dtor_func(&garbage ZEND_FILE_LINE_CC); } return variable_ptr; } } static inline zval* zend_assign_const_to_variable(zval **variable_ptr_ptr, zval *value TSRMLS_DC) { zval *variable_ptr = *variable_ptr_ptr; zval garbage; if (Z_TYPE_P(variable_ptr) == IS_OBJECT && UNEXPECTED(Z_OBJ_HANDLER_P(variable_ptr, set) != NULL)) { Z_OBJ_HANDLER_P(variable_ptr, set)(variable_ptr_ptr, value TSRMLS_CC); return variable_ptr; } if (UNEXPECTED(Z_REFCOUNT_P(variable_ptr) > 1) && EXPECTED(!PZVAL_IS_REF(variable_ptr))) { /* we need to split */ Z_DELREF_P(variable_ptr); GC_ZVAL_CHECK_POSSIBLE_ROOT(variable_ptr); ALLOC_ZVAL(variable_ptr); INIT_PZVAL_COPY(variable_ptr, value); zval_copy_ctor(variable_ptr); *variable_ptr_ptr = variable_ptr; return variable_ptr; } else { if (EXPECTED(Z_TYPE_P(variable_ptr) <= IS_BOOL)) { /* nothing to destroy */ ZVAL_COPY_VALUE(variable_ptr, value); zendi_zval_copy_ctor(*variable_ptr); } else { ZVAL_COPY_VALUE(&garbage, variable_ptr); ZVAL_COPY_VALUE(variable_ptr, value); zendi_zval_copy_ctor(*variable_ptr); _zval_dtor_func(&garbage ZEND_FILE_LINE_CC); } return variable_ptr; } } static inline zval* zend_assign_to_variable(zval **variable_ptr_ptr, zval *value TSRMLS_DC) { zval *variable_ptr = *variable_ptr_ptr; zval garbage; if (Z_TYPE_P(variable_ptr) == IS_OBJECT && UNEXPECTED(Z_OBJ_HANDLER_P(variable_ptr, set) != NULL)) { Z_OBJ_HANDLER_P(variable_ptr, set)(variable_ptr_ptr, value TSRMLS_CC); return variable_ptr; } if (EXPECTED(!PZVAL_IS_REF(variable_ptr))) { if (Z_REFCOUNT_P(variable_ptr)==1) { if (UNEXPECTED(variable_ptr == value)) { return variable_ptr; } else if (EXPECTED(!PZVAL_IS_REF(value))) { Z_ADDREF_P(value); *variable_ptr_ptr = value; if (EXPECTED(variable_ptr != &EG(uninitialized_zval))) { GC_REMOVE_ZVAL_FROM_BUFFER(variable_ptr); zval_dtor(variable_ptr); efree(variable_ptr); } else { Z_DELREF_P(variable_ptr); } return value; } else { goto copy_value; } } else { /* we need to split */ Z_DELREF_P(variable_ptr); GC_ZVAL_CHECK_POSSIBLE_ROOT(variable_ptr); if (PZVAL_IS_REF(value) && Z_REFCOUNT_P(value) > 0) { ALLOC_ZVAL(variable_ptr); *variable_ptr_ptr = variable_ptr; INIT_PZVAL_COPY(variable_ptr, value); zval_copy_ctor(variable_ptr); return variable_ptr; } else { *variable_ptr_ptr = value; Z_ADDREF_P(value); Z_UNSET_ISREF_P(value); return value; } } } else { if (EXPECTED(variable_ptr != value)) { copy_value: if (EXPECTED(Z_TYPE_P(variable_ptr) <= IS_BOOL)) { /* nothing to destroy */ ZVAL_COPY_VALUE(variable_ptr, value); zendi_zval_copy_ctor(*variable_ptr); } else { ZVAL_COPY_VALUE(&garbage, variable_ptr); ZVAL_COPY_VALUE(variable_ptr, value); zendi_zval_copy_ctor(*variable_ptr); _zval_dtor_func(&garbage ZEND_FILE_LINE_CC); } } return variable_ptr; } } /* Utility Functions for Extensions */ static void zend_extension_statement_handler(const zend_extension *extension, zend_op_array *op_array TSRMLS_DC) { if (extension->statement_handler) { extension->statement_handler(op_array); } } static void zend_extension_fcall_begin_handler(const zend_extension *extension, zend_op_array *op_array TSRMLS_DC) { if (extension->fcall_begin_handler) { extension->fcall_begin_handler(op_array); } } static void zend_extension_fcall_end_handler(const zend_extension *extension, zend_op_array *op_array TSRMLS_DC) { if (extension->fcall_end_handler) { extension->fcall_end_handler(op_array); } } static inline HashTable *zend_get_target_symbol_table(int fetch_type TSRMLS_DC) { switch (fetch_type) { case ZEND_FETCH_LOCAL: if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } return EG(active_symbol_table); break; case ZEND_FETCH_GLOBAL: case ZEND_FETCH_GLOBAL_LOCK: return &EG(symbol_table); break; case ZEND_FETCH_STATIC: if (!EG(active_op_array)->static_variables) { ALLOC_HASHTABLE(EG(active_op_array)->static_variables); zend_hash_init(EG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } return EG(active_op_array)->static_variables; break; EMPTY_SWITCH_DEFAULT_CASE() } return NULL; } static inline zval **zend_fetch_dimension_address_inner(HashTable *ht, const zval *dim, int dim_type, int type TSRMLS_DC) { zval **retval; char *offset_key; int offset_key_length; ulong hval; switch (dim->type) { case IS_NULL: offset_key = ""; offset_key_length = 0; hval = zend_inline_hash_func("", 1); goto fetch_string_dim; case IS_STRING: offset_key = dim->value.str.val; offset_key_length = dim->value.str.len; if (dim_type == IS_CONST) { hval = Z_HASH_P(dim); } else { ZEND_HANDLE_NUMERIC_EX(offset_key, offset_key_length+1, hval, goto num_index); if (IS_INTERNED(offset_key)) { hval = INTERNED_HASH(offset_key); } else { hval = zend_hash_func(offset_key, offset_key_length+1); } } fetch_string_dim: if (zend_hash_quick_find(ht, offset_key, offset_key_length+1, hval, (void **) &retval) == FAILURE) { switch (type) { case BP_VAR_R: zend_error(E_NOTICE, "Undefined index: %s", offset_key); /* break missing intentionally */ case BP_VAR_UNSET: case BP_VAR_IS: retval = &EG(uninitialized_zval_ptr); break; case BP_VAR_RW: zend_error(E_NOTICE,"Undefined index: %s", offset_key); /* break missing intentionally */ case BP_VAR_W: { zval *new_zval = &EG(uninitialized_zval); Z_ADDREF_P(new_zval); zend_hash_quick_update(ht, offset_key, offset_key_length+1, hval, &new_zval, sizeof(zval *), (void **) &retval); } break; } } break; case IS_DOUBLE: hval = zend_dval_to_lval(Z_DVAL_P(dim)); goto num_index; case IS_RESOURCE: zend_error(E_STRICT, "Resource ID#%ld used as offset, casting to integer (%ld)", Z_LVAL_P(dim), Z_LVAL_P(dim)); /* Fall Through */ case IS_BOOL: case IS_LONG: hval = Z_LVAL_P(dim); num_index: if (zend_hash_index_find(ht, hval, (void **) &retval) == FAILURE) { switch (type) { case BP_VAR_R: zend_error(E_NOTICE,"Undefined offset: %ld", hval); /* break missing intentionally */ case BP_VAR_UNSET: case BP_VAR_IS: retval = &EG(uninitialized_zval_ptr); break; case BP_VAR_RW: zend_error(E_NOTICE,"Undefined offset: %ld", hval); /* break missing intentionally */ case BP_VAR_W: { zval *new_zval = &EG(uninitialized_zval); Z_ADDREF_P(new_zval); zend_hash_index_update(ht, hval, &new_zval, sizeof(zval *), (void **) &retval); } break; } } break; default: zend_error(E_WARNING, "Illegal offset type"); return (type == BP_VAR_W || type == BP_VAR_RW) ? &EG(error_zval_ptr) : &EG(uninitialized_zval_ptr); } return retval; } static void zend_fetch_dimension_address(temp_variable *result, zval **container_ptr, zval *dim, int dim_type, int type TSRMLS_DC) { zval *container = *container_ptr; zval **retval; switch (Z_TYPE_P(container)) { case IS_ARRAY: if (type != BP_VAR_UNSET && Z_REFCOUNT_P(container)>1 && !PZVAL_IS_REF(container)) { SEPARATE_ZVAL(container_ptr); container = *container_ptr; } fetch_from_array: if (dim == NULL) { zval *new_zval = &EG(uninitialized_zval); Z_ADDREF_P(new_zval); if (zend_hash_next_index_insert(Z_ARRVAL_P(container), &new_zval, sizeof(zval *), (void **) &retval) == FAILURE) { zend_error(E_WARNING, "Cannot add element to the array as the next element is already occupied"); retval = &EG(error_zval_ptr); Z_DELREF_P(new_zval); } } else { retval = zend_fetch_dimension_address_inner(Z_ARRVAL_P(container), dim, dim_type, type TSRMLS_CC); } result->var.ptr_ptr = retval; PZVAL_LOCK(*retval); return; break; case IS_NULL: if (container == &EG(error_zval)) { result->var.ptr_ptr = &EG(error_zval_ptr); PZVAL_LOCK(EG(error_zval_ptr)); } else if (type != BP_VAR_UNSET) { convert_to_array: if (!PZVAL_IS_REF(container)) { SEPARATE_ZVAL(container_ptr); container = *container_ptr; } zval_dtor(container); array_init(container); goto fetch_from_array; } else { /* for read-mode only */ result->var.ptr_ptr = &EG(uninitialized_zval_ptr); PZVAL_LOCK(EG(uninitialized_zval_ptr)); } return; break; case IS_STRING: { zval tmp; if (type != BP_VAR_UNSET && Z_STRLEN_P(container)==0) { goto convert_to_array; } if (dim == NULL) { zend_error_noreturn(E_ERROR, "[] operator not supported for strings"); } if (Z_TYPE_P(dim) != IS_LONG) { switch(Z_TYPE_P(dim)) { /* case IS_LONG: */ case IS_STRING: case IS_DOUBLE: case IS_NULL: case IS_BOOL: /* do nothing */ break; default: zend_error(E_WARNING, "Illegal offset type"); break; } tmp = *dim; zval_copy_ctor(&tmp); convert_to_long(&tmp); dim = &tmp; } if (type != BP_VAR_UNSET) { SEPARATE_ZVAL_IF_NOT_REF(container_ptr); } container = *container_ptr; result->str_offset.str = container; PZVAL_LOCK(container); result->str_offset.offset = Z_LVAL_P(dim); result->str_offset.ptr_ptr = NULL; return; } break; case IS_OBJECT: if (!Z_OBJ_HT_P(container)->read_dimension) { zend_error_noreturn(E_ERROR, "Cannot use object as array"); } else { zval *overloaded_result; if (dim_type == IS_TMP_VAR) { zval *orig = dim; MAKE_REAL_ZVAL_PTR(dim); ZVAL_NULL(orig); } overloaded_result = Z_OBJ_HT_P(container)->read_dimension(container, dim, type TSRMLS_CC); if (overloaded_result) { if (!Z_ISREF_P(overloaded_result)) { if (Z_REFCOUNT_P(overloaded_result) > 0) { zval *tmp = overloaded_result; ALLOC_ZVAL(overloaded_result); ZVAL_COPY_VALUE(overloaded_result, tmp); zval_copy_ctor(overloaded_result); Z_UNSET_ISREF_P(overloaded_result); Z_SET_REFCOUNT_P(overloaded_result, 0); } if (Z_TYPE_P(overloaded_result) != IS_OBJECT) { zend_class_entry *ce = Z_OBJCE_P(container); zend_error(E_NOTICE, "Indirect modification of overloaded element of %s has no effect", ce->name); } } retval = &overloaded_result; } else { retval = &EG(error_zval_ptr); } AI_SET_PTR(result, *retval); PZVAL_LOCK(*retval); if (dim_type == IS_TMP_VAR) { zval_ptr_dtor(&dim); } } return; break; case IS_BOOL: if (type != BP_VAR_UNSET && Z_LVAL_P(container)==0) { goto convert_to_array; } /* break missing intentionally */ default: if (type == BP_VAR_UNSET) { zend_error(E_WARNING, "Cannot unset offset in a non-array variable"); AI_SET_PTR(result, &EG(uninitialized_zval)); PZVAL_LOCK(&EG(uninitialized_zval)); } else { zend_error(E_WARNING, "Cannot use a scalar value as an array"); result->var.ptr_ptr = &EG(error_zval_ptr); PZVAL_LOCK(EG(error_zval_ptr)); } break; } } static void zend_fetch_dimension_address_read(temp_variable *result, zval **container_ptr, zval *dim, int dim_type, int type TSRMLS_DC) { zval *container = *container_ptr; zval **retval; switch (Z_TYPE_P(container)) { case IS_ARRAY: retval = zend_fetch_dimension_address_inner(Z_ARRVAL_P(container), dim, dim_type, type TSRMLS_CC); AI_SET_PTR(result, *retval); PZVAL_LOCK(*retval); return; case IS_NULL: AI_SET_PTR(result, &EG(uninitialized_zval)); PZVAL_LOCK(&EG(uninitialized_zval)); return; case IS_STRING: { zval tmp; zval *ptr; if (Z_TYPE_P(dim) != IS_LONG) { switch(Z_TYPE_P(dim)) { /* case IS_LONG: */ case IS_STRING: case IS_DOUBLE: case IS_NULL: case IS_BOOL: /* do nothing */ break; default: zend_error(E_WARNING, "Illegal offset type"); break; } ZVAL_COPY_VALUE(&tmp, dim); zval_copy_ctor(&tmp); convert_to_long(&tmp); dim = &tmp; } ALLOC_ZVAL(ptr); INIT_PZVAL(ptr); Z_TYPE_P(ptr) = IS_STRING; if (Z_LVAL_P(dim) < 0 || Z_STRLEN_P(container) <= Z_LVAL_P(dim)) { zend_error(E_NOTICE, "Uninitialized string offset: %ld", Z_LVAL_P(dim)); Z_STRVAL_P(ptr) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ptr) = 0; } else { Z_STRVAL_P(ptr) = (char*)emalloc(2); Z_STRVAL_P(ptr)[0] = Z_STRVAL_P(container)[Z_LVAL_P(dim)]; Z_STRVAL_P(ptr)[1] = 0; Z_STRLEN_P(ptr) = 1; } AI_SET_PTR(result, ptr); return; } break; case IS_OBJECT: if (!Z_OBJ_HT_P(container)->read_dimension) { zend_error_noreturn(E_ERROR, "Cannot use object as array"); } else { zval *overloaded_result; if (dim_type == IS_TMP_VAR) { zval *orig = dim; MAKE_REAL_ZVAL_PTR(dim); ZVAL_NULL(orig); } overloaded_result = Z_OBJ_HT_P(container)->read_dimension(container, dim, type TSRMLS_CC); if (overloaded_result) { AI_SET_PTR(result, overloaded_result); PZVAL_LOCK(overloaded_result); } else if (result) { AI_SET_PTR(result, &EG(uninitialized_zval)); PZVAL_LOCK(&EG(uninitialized_zval)); } if (dim_type == IS_TMP_VAR) { zval_ptr_dtor(&dim); } } return; default: AI_SET_PTR(result, &EG(uninitialized_zval)); PZVAL_LOCK(&EG(uninitialized_zval)); return; } } static void zend_fetch_property_address(temp_variable *result, zval **container_ptr, zval *prop_ptr, const zend_literal *key, int type TSRMLS_DC) { zval *container = *container_ptr;; if (Z_TYPE_P(container) != IS_OBJECT) { if (container == &EG(error_zval)) { result->var.ptr_ptr = &EG(error_zval_ptr); PZVAL_LOCK(EG(error_zval_ptr)); return; } /* this should modify object only if it's empty */ if (type != BP_VAR_UNSET && ((Z_TYPE_P(container) == IS_NULL || (Z_TYPE_P(container) == IS_BOOL && Z_LVAL_P(container)==0) || (Z_TYPE_P(container) == IS_STRING && Z_STRLEN_P(container)==0)))) { if (!PZVAL_IS_REF(container)) { SEPARATE_ZVAL(container_ptr); container = *container_ptr; } object_init(container); } else { zend_error(E_WARNING, "Attempt to modify property of non-object"); result->var.ptr_ptr = &EG(error_zval_ptr); PZVAL_LOCK(EG(error_zval_ptr)); return; } } if (Z_OBJ_HT_P(container)->get_property_ptr_ptr) { zval **ptr_ptr = Z_OBJ_HT_P(container)->get_property_ptr_ptr(container, prop_ptr, key TSRMLS_CC); if (NULL == ptr_ptr) { zval *ptr; if (Z_OBJ_HT_P(container)->read_property && (ptr = Z_OBJ_HT_P(container)->read_property(container, prop_ptr, type, key TSRMLS_CC)) != NULL) { AI_SET_PTR(result, ptr); PZVAL_LOCK(ptr); } else { zend_error_noreturn(E_ERROR, "Cannot access undefined property for object with overloaded property access"); } } else { result->var.ptr_ptr = ptr_ptr; PZVAL_LOCK(*ptr_ptr); } } else if (Z_OBJ_HT_P(container)->read_property) { zval *ptr = Z_OBJ_HT_P(container)->read_property(container, prop_ptr, type, key TSRMLS_CC); AI_SET_PTR(result, ptr); PZVAL_LOCK(ptr); } else { zend_error(E_WARNING, "This object doesn't support property references"); result->var.ptr_ptr = &EG(error_zval_ptr); PZVAL_LOCK(EG(error_zval_ptr)); } } static inline zend_brk_cont_element* zend_brk_cont(int nest_levels, int array_offset, const zend_op_array *op_array, const temp_variable *Ts TSRMLS_DC) { int original_nest_levels = nest_levels; zend_brk_cont_element *jmp_to; do { if (array_offset==-1) { zend_error_noreturn(E_ERROR, "Cannot break/continue %d level%s", original_nest_levels, (original_nest_levels == 1) ? "" : "s"); } jmp_to = &op_array->brk_cont_array[array_offset]; if (nest_levels>1) { zend_op *brk_opline = &op_array->opcodes[jmp_to->brk]; switch (brk_opline->opcode) { case ZEND_SWITCH_FREE: if (!(brk_opline->extended_value & EXT_TYPE_FREE_ON_RETURN)) { zval_ptr_dtor(&T(brk_opline->op1.var).var.ptr); } break; case ZEND_FREE: if (!(brk_opline->extended_value & EXT_TYPE_FREE_ON_RETURN)) { zendi_zval_dtor(T(brk_opline->op1.var).tmp_var); } break; } } array_offset = jmp_to->parent; } while (--nest_levels > 0); return jmp_to; } #if ZEND_INTENSIVE_DEBUGGING #define CHECK_SYMBOL_TABLES() \ zend_hash_apply(&EG(symbol_table), (apply_func_t) zend_check_symbol TSRMLS_CC); \ if (&EG(symbol_table)!=EG(active_symbol_table)) { \ zend_hash_apply(EG(active_symbol_table), (apply_func_t) zend_check_symbol TSRMLS_CC); \ } static int zend_check_symbol(zval **pz TSRMLS_DC) { if (Z_TYPE_PP(pz) > 9) { fprintf(stderr, "Warning! %x has invalid type!\n", *pz); /* See http://support.microsoft.com/kb/190351 */ #ifdef PHP_WIN32 fflush(stderr); #endif } else if (Z_TYPE_PP(pz) == IS_ARRAY) { zend_hash_apply(Z_ARRVAL_PP(pz), (apply_func_t) zend_check_symbol TSRMLS_CC); } else if (Z_TYPE_PP(pz) == IS_OBJECT) { /* OBJ-TBI - doesn't support new object model! */ zend_hash_apply(Z_OBJPROP_PP(pz), (apply_func_t) zend_check_symbol TSRMLS_CC); } return 0; } #else #define CHECK_SYMBOL_TABLES() #endif ZEND_API opcode_handler_t *zend_opcode_handlers; ZEND_API void execute_internal(zend_execute_data *execute_data_ptr, int return_value_used TSRMLS_DC) { zval **return_value_ptr = &(*(temp_variable *)((char *) execute_data_ptr->Ts + execute_data_ptr->opline->result.var)).var.ptr; ((zend_internal_function *) execute_data_ptr->function_state.function)->handler(execute_data_ptr->opline->extended_value, *return_value_ptr, (execute_data_ptr->function_state.function->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)?return_value_ptr:NULL, execute_data_ptr->object, return_value_used TSRMLS_CC); } #define ZEND_VM_NEXT_OPCODE() \ CHECK_SYMBOL_TABLES() \ ZEND_VM_INC_OPCODE(); \ ZEND_VM_CONTINUE() #define ZEND_VM_SET_OPCODE(new_op) \ CHECK_SYMBOL_TABLES() \ OPLINE = new_op #define ZEND_VM_JMP(new_op) \ if (EXPECTED(!EG(exception))) { \ ZEND_VM_SET_OPCODE(new_op); \ } else { \ LOAD_OPLINE(); \ } \ ZEND_VM_CONTINUE() #define ZEND_VM_INC_OPCODE() \ OPLINE++ #ifdef __GNUC__ # define ZEND_VM_GUARD(name) __asm__("#" #name) #else # define ZEND_VM_GUARD(name) #endif #include "zend_vm_execute.h" ZEND_API int zend_set_user_opcode_handler(zend_uchar opcode, user_opcode_handler_t handler) { if (opcode != ZEND_USER_OPCODE) { zend_user_opcodes[opcode] = ZEND_USER_OPCODE; zend_user_opcode_handlers[opcode] = handler; return SUCCESS; } return FAILURE; } ZEND_API user_opcode_handler_t zend_get_user_opcode_handler(zend_uchar opcode) { return zend_user_opcode_handlers[opcode]; } ZEND_API zval *zend_get_zval_ptr(int op_type, const znode_op *node, const temp_variable *Ts, zend_free_op *should_free, int type TSRMLS_DC) { return get_zval_ptr(op_type, node, Ts, should_free, type); } ZEND_API zval **zend_get_zval_ptr_ptr(int op_type, const znode_op *node, const temp_variable *Ts, zend_free_op *should_free, int type TSRMLS_DC) { return get_zval_ptr_ptr(op_type, node, Ts, should_free, type); } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */ /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #define ZEND_INTENSIVE_DEBUGGING 0 #include <stdio.h> #include <signal.h> #include "zend.h" #include "zend_compile.h" #include "zend_execute.h" #include "zend_API.h" #include "zend_ptr_stack.h" #include "zend_constants.h" #include "zend_extensions.h" #include "zend_ini.h" #include "zend_exceptions.h" #include "zend_interfaces.h" #include "zend_closures.h" #include "zend_vm.h" #include "zend_dtrace.h" /* Virtual current working directory support */ #include "tsrm_virtual_cwd.h" #define _CONST_CODE 0 #define _TMP_CODE 1 #define _VAR_CODE 2 #define _UNUSED_CODE 3 #define _CV_CODE 4 typedef int (*incdec_t)(zval *); #define get_zval_ptr(op_type, node, Ts, should_free, type) _get_zval_ptr(op_type, node, Ts, should_free, type TSRMLS_CC) #define get_zval_ptr_ptr(op_type, node, Ts, should_free, type) _get_zval_ptr_ptr(op_type, node, Ts, should_free, type TSRMLS_CC) #define get_obj_zval_ptr(op_type, node, Ts, should_free, type) _get_obj_zval_ptr(op_type, node, Ts, should_free, type TSRMLS_CC) #define get_obj_zval_ptr_ptr(op_type, node, Ts, should_free, type) _get_obj_zval_ptr_ptr(op_type, node, Ts, should_free, type TSRMLS_CC) /* Prototypes */ static void zend_extension_statement_handler(const zend_extension *extension, zend_op_array *op_array TSRMLS_DC); static void zend_extension_fcall_begin_handler(const zend_extension *extension, zend_op_array *op_array TSRMLS_DC); static void zend_extension_fcall_end_handler(const zend_extension *extension, zend_op_array *op_array TSRMLS_DC); #define RETURN_VALUE_USED(opline) (!((opline)->result_type & EXT_TYPE_UNUSED)) #define T(offset) (*(temp_variable *)((char *) Ts + offset)) #define CV(var) CVs[var] #define TEMP_VAR_STACK_LIMIT 2000 static zend_always_inline void zend_pzval_unlock_func(zval *z, zend_free_op *should_free, int unref TSRMLS_DC) { if (!Z_DELREF_P(z)) { Z_SET_REFCOUNT_P(z, 1); Z_UNSET_ISREF_P(z); should_free->var = z; /* should_free->is_var = 1; */ } else { should_free->var = 0; if (unref && Z_ISREF_P(z) && Z_REFCOUNT_P(z) == 1) { Z_UNSET_ISREF_P(z); } GC_ZVAL_CHECK_POSSIBLE_ROOT(z); } } static zend_always_inline void zend_pzval_unlock_free_func(zval *z TSRMLS_DC) { if (!Z_DELREF_P(z)) { if (z != &EG(uninitialized_zval)) { GC_REMOVE_ZVAL_FROM_BUFFER(z); zval_dtor(z); efree(z); } } } #undef zval_ptr_dtor #define zval_ptr_dtor(pzv) i_zval_ptr_dtor(*(pzv) ZEND_FILE_LINE_CC) #define PZVAL_UNLOCK(z, f) zend_pzval_unlock_func(z, f, 1 TSRMLS_CC) #define PZVAL_UNLOCK_EX(z, f, u) zend_pzval_unlock_func(z, f, u TSRMLS_CC) #define PZVAL_UNLOCK_FREE(z) zend_pzval_unlock_free_func(z TSRMLS_CC) #define PZVAL_LOCK(z) Z_ADDREF_P((z)) #define SELECTIVE_PZVAL_LOCK(pzv, opline) if (RETURN_VALUE_USED(opline)) { PZVAL_LOCK(pzv); } #define EXTRACT_ZVAL_PTR(t) do { \ temp_variable *__t = (t); \ if (__t->var.ptr_ptr) { \ __t->var.ptr = *__t->var.ptr_ptr; \ __t->var.ptr_ptr = &__t->var.ptr; \ if (!PZVAL_IS_REF(__t->var.ptr) && \ Z_REFCOUNT_P(__t->var.ptr) > 2) { \ SEPARATE_ZVAL(__t->var.ptr_ptr); \ } \ } \ } while (0) #define AI_SET_PTR(t, val) do { \ temp_variable *__t = (t); \ __t->var.ptr = (val); \ __t->var.ptr_ptr = &__t->var.ptr; \ } while (0) #define FREE_OP(should_free) \ if (should_free.var) { \ if ((zend_uintptr_t)should_free.var & 1L) { \ zval_dtor((zval*)((zend_uintptr_t)should_free.var & ~1L)); \ } else { \ zval_ptr_dtor(&should_free.var); \ } \ } #define FREE_OP_IF_VAR(should_free) \ if (should_free.var != NULL && (((zend_uintptr_t)should_free.var & 1L) == 0)) { \ zval_ptr_dtor(&should_free.var); \ } #define FREE_OP_VAR_PTR(should_free) \ if (should_free.var) { \ zval_ptr_dtor(&should_free.var); \ } #define TMP_FREE(z) (zval*)(((zend_uintptr_t)(z)) | 1L) #define IS_TMP_FREE(should_free) ((zend_uintptr_t)should_free.var & 1L) #define MAKE_REAL_ZVAL_PTR(val) \ do { \ zval *_tmp; \ ALLOC_ZVAL(_tmp); \ INIT_PZVAL_COPY(_tmp, (val)); \ (val) = _tmp; \ } while (0) /* End of zend_execute_locks.h */ #define CV_OF(i) (EG(current_execute_data)->CVs[i]) #define CV_DEF_OF(i) (EG(active_op_array)->vars[i]) #define CTOR_CALL_BIT 0x1 #define CTOR_USED_BIT 0x2 #define IS_CTOR_CALL(ce) (((zend_uintptr_t)(ce)) & CTOR_CALL_BIT) #define IS_CTOR_USED(ce) (((zend_uintptr_t)(ce)) & CTOR_USED_BIT) #define ENCODE_CTOR(ce, used) \ ((zend_class_entry*)(((zend_uintptr_t)(ce)) | CTOR_CALL_BIT | ((used) ? CTOR_USED_BIT : 0))) #define DECODE_CTOR(ce) \ ((zend_class_entry*)(((zend_uintptr_t)(ce)) & ~(CTOR_CALL_BIT|CTOR_USED_BIT))) ZEND_API zval** zend_get_compiled_variable_value(const zend_execute_data *execute_data_ptr, zend_uint var) { return execute_data_ptr->CVs[var]; } static zend_always_inline zval *_get_zval_ptr_tmp(zend_uint var, const temp_variable *Ts, zend_free_op *should_free TSRMLS_DC) { return should_free->var = &T(var).tmp_var; } static zend_always_inline zval *_get_zval_ptr_var(zend_uint var, const temp_variable *Ts, zend_free_op *should_free TSRMLS_DC) { zval *ptr = T(var).var.ptr; PZVAL_UNLOCK(ptr, should_free); return ptr; } static zend_never_inline zval **_get_zval_cv_lookup(zval ***ptr, zend_uint var, int type TSRMLS_DC) { zend_compiled_variable *cv = &CV_DEF_OF(var); if (!EG(active_symbol_table) || zend_hash_quick_find(EG(active_symbol_table), cv->name, cv->name_len+1, cv->hash_value, (void **)ptr)==FAILURE) { switch (type) { case BP_VAR_R: case BP_VAR_UNSET: zend_error(E_NOTICE, "Undefined variable: %s", cv->name); /* break missing intentionally */ case BP_VAR_IS: return &EG(uninitialized_zval_ptr); break; case BP_VAR_RW: zend_error(E_NOTICE, "Undefined variable: %s", cv->name); /* break missing intentionally */ case BP_VAR_W: Z_ADDREF(EG(uninitialized_zval)); if (!EG(active_symbol_table)) { *ptr = (zval**)EG(current_execute_data)->CVs + (EG(active_op_array)->last_var + var); **ptr = &EG(uninitialized_zval); } else { zend_hash_quick_update(EG(active_symbol_table), cv->name, cv->name_len+1, cv->hash_value, &EG(uninitialized_zval_ptr), sizeof(zval *), (void **)ptr); } break; } } return *ptr; } static zend_never_inline zval **_get_zval_cv_lookup_BP_VAR_R(zval ***ptr, zend_uint var TSRMLS_DC) { zend_compiled_variable *cv = &CV_DEF_OF(var); if (!EG(active_symbol_table) || zend_hash_quick_find(EG(active_symbol_table), cv->name, cv->name_len+1, cv->hash_value, (void **)ptr)==FAILURE) { zend_error(E_NOTICE, "Undefined variable: %s", cv->name); return &EG(uninitialized_zval_ptr); } return *ptr; } static zend_never_inline zval **_get_zval_cv_lookup_BP_VAR_UNSET(zval ***ptr, zend_uint var TSRMLS_DC) { zend_compiled_variable *cv = &CV_DEF_OF(var); if (!EG(active_symbol_table) || zend_hash_quick_find(EG(active_symbol_table), cv->name, cv->name_len+1, cv->hash_value, (void **)ptr)==FAILURE) { zend_error(E_NOTICE, "Undefined variable: %s", cv->name); return &EG(uninitialized_zval_ptr); } return *ptr; } static zend_never_inline zval **_get_zval_cv_lookup_BP_VAR_IS(zval ***ptr, zend_uint var TSRMLS_DC) { zend_compiled_variable *cv = &CV_DEF_OF(var); if (!EG(active_symbol_table) || zend_hash_quick_find(EG(active_symbol_table), cv->name, cv->name_len+1, cv->hash_value, (void **)ptr)==FAILURE) { return &EG(uninitialized_zval_ptr); } return *ptr; } static zend_never_inline zval **_get_zval_cv_lookup_BP_VAR_RW(zval ***ptr, zend_uint var TSRMLS_DC) { zend_compiled_variable *cv = &CV_DEF_OF(var); if (!EG(active_symbol_table)) { Z_ADDREF(EG(uninitialized_zval)); *ptr = (zval**)EG(current_execute_data)->CVs + (EG(active_op_array)->last_var + var); **ptr = &EG(uninitialized_zval); zend_error(E_NOTICE, "Undefined variable: %s", cv->name); } else if (zend_hash_quick_find(EG(active_symbol_table), cv->name, cv->name_len+1, cv->hash_value, (void **)ptr)==FAILURE) { Z_ADDREF(EG(uninitialized_zval)); zend_hash_quick_update(EG(active_symbol_table), cv->name, cv->name_len+1, cv->hash_value, &EG(uninitialized_zval_ptr), sizeof(zval *), (void **)ptr); zend_error(E_NOTICE, "Undefined variable: %s", cv->name); } return *ptr; } static zend_never_inline zval **_get_zval_cv_lookup_BP_VAR_W(zval ***ptr, zend_uint var TSRMLS_DC) { zend_compiled_variable *cv = &CV_DEF_OF(var); if (!EG(active_symbol_table)) { Z_ADDREF(EG(uninitialized_zval)); *ptr = (zval**)EG(current_execute_data)->CVs + (EG(active_op_array)->last_var + var); **ptr = &EG(uninitialized_zval); } else if (zend_hash_quick_find(EG(active_symbol_table), cv->name, cv->name_len+1, cv->hash_value, (void **)ptr)==FAILURE) { Z_ADDREF(EG(uninitialized_zval)); zend_hash_quick_update(EG(active_symbol_table), cv->name, cv->name_len+1, cv->hash_value, &EG(uninitialized_zval_ptr), sizeof(zval *), (void **)ptr); } return *ptr; } static zend_always_inline zval *_get_zval_ptr_cv(zend_uint var, int type TSRMLS_DC) { zval ***ptr = &CV_OF(var); if (UNEXPECTED(*ptr == NULL)) { return *_get_zval_cv_lookup(ptr, var, type TSRMLS_CC); } return **ptr; } static zend_always_inline zval *_get_zval_ptr_cv_BP_VAR_R(zval ***CVs, zend_uint var TSRMLS_DC) { zval ***ptr = &CV(var); if (UNEXPECTED(*ptr == NULL)) { return *_get_zval_cv_lookup_BP_VAR_R(ptr, var TSRMLS_CC); } return **ptr; } static zend_always_inline zval *_get_zval_ptr_cv_BP_VAR_UNSET(zval ***CVs, zend_uint var TSRMLS_DC) { zval ***ptr = &CV(var); if (UNEXPECTED(*ptr == NULL)) { return *_get_zval_cv_lookup_BP_VAR_UNSET(ptr, var TSRMLS_CC); } return **ptr; } static zend_always_inline zval *_get_zval_ptr_cv_BP_VAR_IS(zval ***CVs, zend_uint var TSRMLS_DC) { zval ***ptr = &CV(var); if (UNEXPECTED(*ptr == NULL)) { return *_get_zval_cv_lookup_BP_VAR_IS(ptr, var TSRMLS_CC); } return **ptr; } static zend_always_inline zval *_get_zval_ptr_cv_BP_VAR_RW(zval ***CVs, zend_uint var TSRMLS_DC) { zval ***ptr = &CV(var); if (UNEXPECTED(*ptr == NULL)) { return *_get_zval_cv_lookup_BP_VAR_RW(ptr, var TSRMLS_CC); } return **ptr; } static zend_always_inline zval *_get_zval_ptr_cv_BP_VAR_W(zval ***CVs, zend_uint var TSRMLS_DC) { zval ***ptr = &CV(var); if (UNEXPECTED(*ptr == NULL)) { return *_get_zval_cv_lookup_BP_VAR_W(ptr, var TSRMLS_CC); } return **ptr; } static inline zval *_get_zval_ptr(int op_type, const znode_op *node, const temp_variable *Ts, zend_free_op *should_free, int type TSRMLS_DC) { /* should_free->is_var = 0; */ switch (op_type) { case IS_CONST: should_free->var = 0; return node->zv; break; case IS_TMP_VAR: should_free->var = TMP_FREE(&T(node->var).tmp_var); return &T(node->var).tmp_var; break; case IS_VAR: return _get_zval_ptr_var(node->var, Ts, should_free TSRMLS_CC); break; case IS_UNUSED: should_free->var = 0; return NULL; break; case IS_CV: should_free->var = 0; return _get_zval_ptr_cv(node->var, type TSRMLS_CC); break; EMPTY_SWITCH_DEFAULT_CASE() } return NULL; } static zend_always_inline zval **_get_zval_ptr_ptr_var(zend_uint var, const temp_variable *Ts, zend_free_op *should_free TSRMLS_DC) { zval** ptr_ptr = T(var).var.ptr_ptr; if (EXPECTED(ptr_ptr != NULL)) { PZVAL_UNLOCK(*ptr_ptr, should_free); } else { /* string offset */ PZVAL_UNLOCK(T(var).str_offset.str, should_free); } return ptr_ptr; } static zend_always_inline zval **_get_zval_ptr_ptr_cv(zend_uint var, int type TSRMLS_DC) { zval ***ptr = &CV_OF(var); if (UNEXPECTED(*ptr == NULL)) { return _get_zval_cv_lookup(ptr, var, type TSRMLS_CC); } return *ptr; } static zend_always_inline zval **_get_zval_ptr_ptr_cv_BP_VAR_R(zval ***CVs, zend_uint var TSRMLS_DC) { zval ***ptr = &CV(var); if (UNEXPECTED(*ptr == NULL)) { return _get_zval_cv_lookup_BP_VAR_R(ptr, var TSRMLS_CC); } return *ptr; } static zend_always_inline zval **_get_zval_ptr_ptr_cv_BP_VAR_UNSET(zval ***CVs, zend_uint var TSRMLS_DC) { zval ***ptr = &CV(var); if (UNEXPECTED(*ptr == NULL)) { return _get_zval_cv_lookup_BP_VAR_UNSET(ptr, var TSRMLS_CC); } return *ptr; } static zend_always_inline zval **_get_zval_ptr_ptr_cv_BP_VAR_IS(zval ***CVs, zend_uint var TSRMLS_DC) { zval ***ptr = &CV(var); if (UNEXPECTED(*ptr == NULL)) { return _get_zval_cv_lookup_BP_VAR_IS(ptr, var TSRMLS_CC); } return *ptr; } static zend_always_inline zval **_get_zval_ptr_ptr_cv_BP_VAR_RW(zval ***CVs, zend_uint var TSRMLS_DC) { zval ***ptr = &CV(var); if (UNEXPECTED(*ptr == NULL)) { return _get_zval_cv_lookup_BP_VAR_RW(ptr, var TSRMLS_CC); } return *ptr; } static zend_always_inline zval **_get_zval_ptr_ptr_cv_BP_VAR_W(zval ***CVs, zend_uint var TSRMLS_DC) { zval ***ptr = &CV(var); if (UNEXPECTED(*ptr == NULL)) { return _get_zval_cv_lookup_BP_VAR_W(ptr, var TSRMLS_CC); } return *ptr; } static inline zval **_get_zval_ptr_ptr(int op_type, const znode_op *node, const temp_variable *Ts, zend_free_op *should_free, int type TSRMLS_DC) { if (op_type == IS_CV) { should_free->var = 0; return _get_zval_ptr_ptr_cv(node->var, type TSRMLS_CC); } else if (op_type == IS_VAR) { return _get_zval_ptr_ptr_var(node->var, Ts, should_free TSRMLS_CC); } else { should_free->var = 0; return NULL; } } static zend_always_inline zval *_get_obj_zval_ptr_unused(TSRMLS_D) { if (EXPECTED(EG(This) != NULL)) { return EG(This); } else { zend_error_noreturn(E_ERROR, "Using $this when not in object context"); return NULL; } } static inline zval **_get_obj_zval_ptr_ptr(int op_type, const znode_op *op, const temp_variable *Ts, zend_free_op *should_free, int type TSRMLS_DC) { if (op_type == IS_UNUSED) { if (EXPECTED(EG(This) != NULL)) { /* this should actually never be modified, _ptr_ptr is modified only when the object is empty */ should_free->var = 0; return &EG(This); } else { zend_error_noreturn(E_ERROR, "Using $this when not in object context"); } } return get_zval_ptr_ptr(op_type, op, Ts, should_free, type); } static zend_always_inline zval **_get_obj_zval_ptr_ptr_unused(TSRMLS_D) { if (EXPECTED(EG(This) != NULL)) { return &EG(This); } else { zend_error_noreturn(E_ERROR, "Using $this when not in object context"); return NULL; } } static inline zval *_get_obj_zval_ptr(int op_type, znode_op *op, const temp_variable *Ts, zend_free_op *should_free, int type TSRMLS_DC) { if (op_type == IS_UNUSED) { if (EXPECTED(EG(This) != NULL)) { should_free->var = 0; return EG(This); } else { zend_error_noreturn(E_ERROR, "Using $this when not in object context"); } } return get_zval_ptr(op_type, op, Ts, should_free, type); } static void zend_assign_to_variable_reference(zval **variable_ptr_ptr, zval **value_ptr_ptr TSRMLS_DC) { zval *variable_ptr = *variable_ptr_ptr; zval *value_ptr = *value_ptr_ptr; if (variable_ptr == &EG(error_zval) || value_ptr == &EG(error_zval)) { variable_ptr_ptr = &EG(uninitialized_zval_ptr); } else if (variable_ptr != value_ptr) { if (!PZVAL_IS_REF(value_ptr)) { /* break it away */ Z_DELREF_P(value_ptr); if (Z_REFCOUNT_P(value_ptr)>0) { ALLOC_ZVAL(*value_ptr_ptr); ZVAL_COPY_VALUE(*value_ptr_ptr, value_ptr); value_ptr = *value_ptr_ptr; zendi_zval_copy_ctor(*value_ptr); } Z_SET_REFCOUNT_P(value_ptr, 1); Z_SET_ISREF_P(value_ptr); } *variable_ptr_ptr = value_ptr; Z_ADDREF_P(value_ptr); zval_ptr_dtor(&variable_ptr); } else if (!Z_ISREF_P(variable_ptr)) { if (variable_ptr_ptr == value_ptr_ptr) { SEPARATE_ZVAL(variable_ptr_ptr); } else if (variable_ptr==&EG(uninitialized_zval) || Z_REFCOUNT_P(variable_ptr)>2) { /* we need to separate */ Z_SET_REFCOUNT_P(variable_ptr, Z_REFCOUNT_P(variable_ptr) - 2); ALLOC_ZVAL(*variable_ptr_ptr); ZVAL_COPY_VALUE(*variable_ptr_ptr, variable_ptr); zval_copy_ctor(*variable_ptr_ptr); *value_ptr_ptr = *variable_ptr_ptr; Z_SET_REFCOUNT_PP(variable_ptr_ptr, 2); } Z_SET_ISREF_PP(variable_ptr_ptr); } } /* this should modify object only if it's empty */ static inline void make_real_object(zval **object_ptr TSRMLS_DC) { if (Z_TYPE_PP(object_ptr) == IS_NULL || (Z_TYPE_PP(object_ptr) == IS_BOOL && Z_LVAL_PP(object_ptr) == 0) || (Z_TYPE_PP(object_ptr) == IS_STRING && Z_STRLEN_PP(object_ptr) == 0) ) { zend_error(E_WARNING, "Creating default object from empty value"); SEPARATE_ZVAL_IF_NOT_REF(object_ptr); zval_dtor(*object_ptr); object_init(*object_ptr); } } ZEND_API char * zend_verify_arg_class_kind(const zend_arg_info *cur_arg_info, ulong fetch_type, const char **class_name, zend_class_entry **pce TSRMLS_DC) { *pce = zend_fetch_class(cur_arg_info->class_name, cur_arg_info->class_name_len, (fetch_type | ZEND_FETCH_CLASS_AUTO | ZEND_FETCH_CLASS_NO_AUTOLOAD) TSRMLS_CC); *class_name = (*pce) ? (*pce)->name: cur_arg_info->class_name; if (*pce && (*pce)->ce_flags & ZEND_ACC_INTERFACE) { return "implement interface "; } else { return "be an instance of "; } } ZEND_API int zend_verify_arg_error(int error_type, const zend_function *zf, zend_uint arg_num, const char *need_msg, const char *need_kind, const char *given_msg, char *given_kind TSRMLS_DC) { zend_execute_data *ptr = EG(current_execute_data)->prev_execute_data; char *fname = zf->common.function_name; char *fsep; const char *fclass; if (zf->common.scope) { fsep = "::"; fclass = zf->common.scope->name; } else { fsep = ""; fclass = ""; } if (ptr && ptr->op_array) { zend_error(error_type, "Argument %d passed to %s%s%s() must %s%s, %s%s given, called in %s on line %d and defined", arg_num, fclass, fsep, fname, need_msg, need_kind, given_msg, given_kind, ptr->op_array->filename, ptr->opline->lineno); } else { zend_error(error_type, "Argument %d passed to %s%s%s() must %s%s, %s%s given", arg_num, fclass, fsep, fname, need_msg, need_kind, given_msg, given_kind); } return 0; } static inline int zend_verify_arg_type(zend_function *zf, zend_uint arg_num, zval *arg, ulong fetch_type TSRMLS_DC) { zend_arg_info *cur_arg_info; char *need_msg; zend_class_entry *ce; if (!zf->common.arg_info || arg_num>zf->common.num_args) { return 1; } cur_arg_info = &zf->common.arg_info[arg_num-1]; if (cur_arg_info->class_name) { const char *class_name; if (!arg) { need_msg = zend_verify_arg_class_kind(cur_arg_info, fetch_type, &class_name, &ce TSRMLS_CC); return zend_verify_arg_error(E_RECOVERABLE_ERROR, zf, arg_num, need_msg, class_name, "none", "" TSRMLS_CC); } if (Z_TYPE_P(arg) == IS_OBJECT) { need_msg = zend_verify_arg_class_kind(cur_arg_info, fetch_type, &class_name, &ce TSRMLS_CC); if (!ce || !instanceof_function(Z_OBJCE_P(arg), ce TSRMLS_CC)) { return zend_verify_arg_error(E_RECOVERABLE_ERROR, zf, arg_num, need_msg, class_name, "instance of ", Z_OBJCE_P(arg)->name TSRMLS_CC); } } else if (Z_TYPE_P(arg) != IS_NULL || !cur_arg_info->allow_null) { need_msg = zend_verify_arg_class_kind(cur_arg_info, fetch_type, &class_name, &ce TSRMLS_CC); return zend_verify_arg_error(E_RECOVERABLE_ERROR, zf, arg_num, need_msg, class_name, zend_zval_type_name(arg), "" TSRMLS_CC); } } else if (cur_arg_info->type_hint && cur_arg_info->type_hint == IS_ARRAY) { if (!arg) { return zend_verify_arg_error(E_RECOVERABLE_ERROR, zf, arg_num, "be of the type array", "", "none", "" TSRMLS_CC); } if (Z_TYPE_P(arg) != IS_ARRAY && (Z_TYPE_P(arg) != IS_NULL || !cur_arg_info->allow_null)) { return zend_verify_arg_error(E_RECOVERABLE_ERROR, zf, arg_num, "be of the type array", "", zend_zval_type_name(arg), "" TSRMLS_CC); } } return 1; } static inline void zend_assign_to_object(zval **retval, zval **object_ptr, zval *property_name, int value_type, znode_op *value_op, const temp_variable *Ts, int opcode, const zend_literal *key TSRMLS_DC) { zval *object = *object_ptr; zend_free_op free_value; zval *value = get_zval_ptr(value_type, value_op, Ts, &free_value, BP_VAR_R); if (Z_TYPE_P(object) != IS_OBJECT) { if (object == &EG(error_zval)) { if (retval) { *retval = &EG(uninitialized_zval); PZVAL_LOCK(*retval); } FREE_OP(free_value); return; } if (Z_TYPE_P(object) == IS_NULL || (Z_TYPE_P(object) == IS_BOOL && Z_LVAL_P(object) == 0) || (Z_TYPE_P(object) == IS_STRING && Z_STRLEN_P(object) == 0)) { SEPARATE_ZVAL_IF_NOT_REF(object_ptr); zval_dtor(*object_ptr); object_init(*object_ptr); object = *object_ptr; zend_error(E_WARNING, "Creating default object from empty value"); } else { zend_error(E_WARNING, "Attempt to assign property of non-object"); if (retval) { *retval = &EG(uninitialized_zval); PZVAL_LOCK(*retval); } FREE_OP(free_value); return; } } /* separate our value if necessary */ if (value_type == IS_TMP_VAR) { zval *orig_value = value; ALLOC_ZVAL(value); ZVAL_COPY_VALUE(value, orig_value); Z_UNSET_ISREF_P(value); Z_SET_REFCOUNT_P(value, 0); } else if (value_type == IS_CONST) { zval *orig_value = value; ALLOC_ZVAL(value); ZVAL_COPY_VALUE(value, orig_value); Z_UNSET_ISREF_P(value); Z_SET_REFCOUNT_P(value, 0); zval_copy_ctor(value); } Z_ADDREF_P(value); if (opcode == ZEND_ASSIGN_OBJ) { if (!Z_OBJ_HT_P(object)->write_property) { zend_error(E_WARNING, "Attempt to assign property of non-object"); if (retval) { *retval = &EG(uninitialized_zval); PZVAL_LOCK(&EG(uninitialized_zval)); } if (value_type == IS_TMP_VAR) { FREE_ZVAL(value); } else if (value_type == IS_CONST) { zval_ptr_dtor(&value); } FREE_OP(free_value); return; } Z_OBJ_HT_P(object)->write_property(object, property_name, value, key TSRMLS_CC); } else { /* Note: property_name in this case is really the array index! */ if (!Z_OBJ_HT_P(object)->write_dimension) { zend_error_noreturn(E_ERROR, "Cannot use object as array"); } Z_OBJ_HT_P(object)->write_dimension(object, property_name, value TSRMLS_CC); } if (retval && !EG(exception)) { *retval = value; PZVAL_LOCK(value); } zval_ptr_dtor(&value); FREE_OP_IF_VAR(free_value); } static inline int zend_assign_to_string_offset(const temp_variable *T, const zval *value, int value_type TSRMLS_DC) { if (Z_TYPE_P(T->str_offset.str) == IS_STRING) { if (((int)T->str_offset.offset < 0)) { zend_error(E_WARNING, "Illegal string offset: %d", T->str_offset.offset); return 0; } if (T->str_offset.offset >= Z_STRLEN_P(T->str_offset.str)) { if (IS_INTERNED(Z_STRVAL_P(T->str_offset.str))) { char *tmp = (char *) emalloc(T->str_offset.offset+1+1); memcpy(tmp, Z_STRVAL_P(T->str_offset.str), T->str_offset.offset+1+1); Z_STRVAL_P(T->str_offset.str) = tmp; } else { Z_STRVAL_P(T->str_offset.str) = (char *) erealloc(Z_STRVAL_P(T->str_offset.str), T->str_offset.offset+1+1); } memset(Z_STRVAL_P(T->str_offset.str) + Z_STRLEN_P(T->str_offset.str), ' ', T->str_offset.offset - Z_STRLEN_P(T->str_offset.str)); Z_STRVAL_P(T->str_offset.str)[T->str_offset.offset+1] = 0; Z_STRLEN_P(T->str_offset.str) = T->str_offset.offset+1; } else if (IS_INTERNED(Z_STRVAL_P(T->str_offset.str))) { char *tmp = (char *) emalloc(Z_STRLEN_P(T->str_offset.str) + 1); memcpy(tmp, Z_STRVAL_P(T->str_offset.str), Z_STRLEN_P(T->str_offset.str) + 1); Z_STRVAL_P(T->str_offset.str) = tmp; } if (Z_TYPE_P(value) != IS_STRING) { zval tmp; ZVAL_COPY_VALUE(&tmp, value); if (value_type != IS_TMP_VAR) { zval_copy_ctor(&tmp); } convert_to_string(&tmp); Z_STRVAL_P(T->str_offset.str)[T->str_offset.offset] = Z_STRVAL(tmp)[0]; STR_FREE(Z_STRVAL(tmp)); } else { Z_STRVAL_P(T->str_offset.str)[T->str_offset.offset] = Z_STRVAL_P(value)[0]; if (value_type == IS_TMP_VAR) { /* we can safely free final_value here * because separation is done only * in case value_type == IS_VAR */ STR_FREE(Z_STRVAL_P(value)); } } /* * the value of an assignment to a string offset is undefined T(result->u.var).var = &T->str_offset.str; */ } return 1; } static inline zval* zend_assign_tmp_to_variable(zval **variable_ptr_ptr, zval *value TSRMLS_DC) { zval *variable_ptr = *variable_ptr_ptr; zval garbage; if (Z_TYPE_P(variable_ptr) == IS_OBJECT && UNEXPECTED(Z_OBJ_HANDLER_P(variable_ptr, set) != NULL)) { Z_OBJ_HANDLER_P(variable_ptr, set)(variable_ptr_ptr, value TSRMLS_CC); return variable_ptr; } if (UNEXPECTED(Z_REFCOUNT_P(variable_ptr) > 1) && EXPECTED(!PZVAL_IS_REF(variable_ptr))) { /* we need to split */ Z_DELREF_P(variable_ptr); GC_ZVAL_CHECK_POSSIBLE_ROOT(variable_ptr); ALLOC_ZVAL(variable_ptr); INIT_PZVAL_COPY(variable_ptr, value); *variable_ptr_ptr = variable_ptr; return variable_ptr; } else { if (EXPECTED(Z_TYPE_P(variable_ptr) <= IS_BOOL)) { /* nothing to destroy */ ZVAL_COPY_VALUE(variable_ptr, value); } else { ZVAL_COPY_VALUE(&garbage, variable_ptr); ZVAL_COPY_VALUE(variable_ptr, value); _zval_dtor_func(&garbage ZEND_FILE_LINE_CC); } return variable_ptr; } } static inline zval* zend_assign_const_to_variable(zval **variable_ptr_ptr, zval *value TSRMLS_DC) { zval *variable_ptr = *variable_ptr_ptr; zval garbage; if (Z_TYPE_P(variable_ptr) == IS_OBJECT && UNEXPECTED(Z_OBJ_HANDLER_P(variable_ptr, set) != NULL)) { Z_OBJ_HANDLER_P(variable_ptr, set)(variable_ptr_ptr, value TSRMLS_CC); return variable_ptr; } if (UNEXPECTED(Z_REFCOUNT_P(variable_ptr) > 1) && EXPECTED(!PZVAL_IS_REF(variable_ptr))) { /* we need to split */ Z_DELREF_P(variable_ptr); GC_ZVAL_CHECK_POSSIBLE_ROOT(variable_ptr); ALLOC_ZVAL(variable_ptr); INIT_PZVAL_COPY(variable_ptr, value); zval_copy_ctor(variable_ptr); *variable_ptr_ptr = variable_ptr; return variable_ptr; } else { if (EXPECTED(Z_TYPE_P(variable_ptr) <= IS_BOOL)) { /* nothing to destroy */ ZVAL_COPY_VALUE(variable_ptr, value); zendi_zval_copy_ctor(*variable_ptr); } else { ZVAL_COPY_VALUE(&garbage, variable_ptr); ZVAL_COPY_VALUE(variable_ptr, value); zendi_zval_copy_ctor(*variable_ptr); _zval_dtor_func(&garbage ZEND_FILE_LINE_CC); } return variable_ptr; } } static inline zval* zend_assign_to_variable(zval **variable_ptr_ptr, zval *value TSRMLS_DC) { zval *variable_ptr = *variable_ptr_ptr; zval garbage; if (Z_TYPE_P(variable_ptr) == IS_OBJECT && UNEXPECTED(Z_OBJ_HANDLER_P(variable_ptr, set) != NULL)) { Z_OBJ_HANDLER_P(variable_ptr, set)(variable_ptr_ptr, value TSRMLS_CC); return variable_ptr; } if (EXPECTED(!PZVAL_IS_REF(variable_ptr))) { if (Z_REFCOUNT_P(variable_ptr)==1) { if (UNEXPECTED(variable_ptr == value)) { return variable_ptr; } else if (EXPECTED(!PZVAL_IS_REF(value))) { Z_ADDREF_P(value); *variable_ptr_ptr = value; if (EXPECTED(variable_ptr != &EG(uninitialized_zval))) { GC_REMOVE_ZVAL_FROM_BUFFER(variable_ptr); zval_dtor(variable_ptr); efree(variable_ptr); } else { Z_DELREF_P(variable_ptr); } return value; } else { goto copy_value; } } else { /* we need to split */ Z_DELREF_P(variable_ptr); GC_ZVAL_CHECK_POSSIBLE_ROOT(variable_ptr); if (PZVAL_IS_REF(value) && Z_REFCOUNT_P(value) > 0) { ALLOC_ZVAL(variable_ptr); *variable_ptr_ptr = variable_ptr; INIT_PZVAL_COPY(variable_ptr, value); zval_copy_ctor(variable_ptr); return variable_ptr; } else { *variable_ptr_ptr = value; Z_ADDREF_P(value); Z_UNSET_ISREF_P(value); return value; } } } else { if (EXPECTED(variable_ptr != value)) { copy_value: if (EXPECTED(Z_TYPE_P(variable_ptr) <= IS_BOOL)) { /* nothing to destroy */ ZVAL_COPY_VALUE(variable_ptr, value); zendi_zval_copy_ctor(*variable_ptr); } else { ZVAL_COPY_VALUE(&garbage, variable_ptr); ZVAL_COPY_VALUE(variable_ptr, value); zendi_zval_copy_ctor(*variable_ptr); _zval_dtor_func(&garbage ZEND_FILE_LINE_CC); } } return variable_ptr; } } /* Utility Functions for Extensions */ static void zend_extension_statement_handler(const zend_extension *extension, zend_op_array *op_array TSRMLS_DC) { if (extension->statement_handler) { extension->statement_handler(op_array); } } static void zend_extension_fcall_begin_handler(const zend_extension *extension, zend_op_array *op_array TSRMLS_DC) { if (extension->fcall_begin_handler) { extension->fcall_begin_handler(op_array); } } static void zend_extension_fcall_end_handler(const zend_extension *extension, zend_op_array *op_array TSRMLS_DC) { if (extension->fcall_end_handler) { extension->fcall_end_handler(op_array); } } static inline HashTable *zend_get_target_symbol_table(int fetch_type TSRMLS_DC) { switch (fetch_type) { case ZEND_FETCH_LOCAL: if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } return EG(active_symbol_table); break; case ZEND_FETCH_GLOBAL: case ZEND_FETCH_GLOBAL_LOCK: return &EG(symbol_table); break; case ZEND_FETCH_STATIC: if (!EG(active_op_array)->static_variables) { ALLOC_HASHTABLE(EG(active_op_array)->static_variables); zend_hash_init(EG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } return EG(active_op_array)->static_variables; break; EMPTY_SWITCH_DEFAULT_CASE() } return NULL; } static inline zval **zend_fetch_dimension_address_inner(HashTable *ht, const zval *dim, int dim_type, int type TSRMLS_DC) { zval **retval; char *offset_key; int offset_key_length; ulong hval; switch (dim->type) { case IS_NULL: offset_key = ""; offset_key_length = 0; hval = zend_inline_hash_func("", 1); goto fetch_string_dim; case IS_STRING: offset_key = dim->value.str.val; offset_key_length = dim->value.str.len; if (dim_type == IS_CONST) { hval = Z_HASH_P(dim); } else { ZEND_HANDLE_NUMERIC_EX(offset_key, offset_key_length+1, hval, goto num_index); if (IS_INTERNED(offset_key)) { hval = INTERNED_HASH(offset_key); } else { hval = zend_hash_func(offset_key, offset_key_length+1); } } fetch_string_dim: if (zend_hash_quick_find(ht, offset_key, offset_key_length+1, hval, (void **) &retval) == FAILURE) { switch (type) { case BP_VAR_R: zend_error(E_NOTICE, "Undefined index: %s", offset_key); /* break missing intentionally */ case BP_VAR_UNSET: case BP_VAR_IS: retval = &EG(uninitialized_zval_ptr); break; case BP_VAR_RW: zend_error(E_NOTICE,"Undefined index: %s", offset_key); /* break missing intentionally */ case BP_VAR_W: { zval *new_zval = &EG(uninitialized_zval); Z_ADDREF_P(new_zval); zend_hash_quick_update(ht, offset_key, offset_key_length+1, hval, &new_zval, sizeof(zval *), (void **) &retval); } break; } } break; case IS_DOUBLE: hval = zend_dval_to_lval(Z_DVAL_P(dim)); goto num_index; case IS_RESOURCE: zend_error(E_STRICT, "Resource ID#%ld used as offset, casting to integer (%ld)", Z_LVAL_P(dim), Z_LVAL_P(dim)); /* Fall Through */ case IS_BOOL: case IS_LONG: hval = Z_LVAL_P(dim); num_index: if (zend_hash_index_find(ht, hval, (void **) &retval) == FAILURE) { switch (type) { case BP_VAR_R: zend_error(E_NOTICE,"Undefined offset: %ld", hval); /* break missing intentionally */ case BP_VAR_UNSET: case BP_VAR_IS: retval = &EG(uninitialized_zval_ptr); break; case BP_VAR_RW: zend_error(E_NOTICE,"Undefined offset: %ld", hval); /* break missing intentionally */ case BP_VAR_W: { zval *new_zval = &EG(uninitialized_zval); Z_ADDREF_P(new_zval); zend_hash_index_update(ht, hval, &new_zval, sizeof(zval *), (void **) &retval); } break; } } break; default: zend_error(E_WARNING, "Illegal offset type"); return (type == BP_VAR_W || type == BP_VAR_RW) ? &EG(error_zval_ptr) : &EG(uninitialized_zval_ptr); } return retval; } static void zend_fetch_dimension_address(temp_variable *result, zval **container_ptr, zval *dim, int dim_type, int type TSRMLS_DC) { zval *container = *container_ptr; zval **retval; switch (Z_TYPE_P(container)) { case IS_ARRAY: if (type != BP_VAR_UNSET && Z_REFCOUNT_P(container)>1 && !PZVAL_IS_REF(container)) { SEPARATE_ZVAL(container_ptr); container = *container_ptr; } fetch_from_array: if (dim == NULL) { zval *new_zval = &EG(uninitialized_zval); Z_ADDREF_P(new_zval); if (zend_hash_next_index_insert(Z_ARRVAL_P(container), &new_zval, sizeof(zval *), (void **) &retval) == FAILURE) { zend_error(E_WARNING, "Cannot add element to the array as the next element is already occupied"); retval = &EG(error_zval_ptr); Z_DELREF_P(new_zval); } } else { retval = zend_fetch_dimension_address_inner(Z_ARRVAL_P(container), dim, dim_type, type TSRMLS_CC); } result->var.ptr_ptr = retval; PZVAL_LOCK(*retval); return; break; case IS_NULL: if (container == &EG(error_zval)) { result->var.ptr_ptr = &EG(error_zval_ptr); PZVAL_LOCK(EG(error_zval_ptr)); } else if (type != BP_VAR_UNSET) { convert_to_array: if (!PZVAL_IS_REF(container)) { SEPARATE_ZVAL(container_ptr); container = *container_ptr; } zval_dtor(container); array_init(container); goto fetch_from_array; } else { /* for read-mode only */ result->var.ptr_ptr = &EG(uninitialized_zval_ptr); PZVAL_LOCK(EG(uninitialized_zval_ptr)); } return; break; case IS_STRING: { zval tmp; if (type != BP_VAR_UNSET && Z_STRLEN_P(container)==0) { goto convert_to_array; } if (dim == NULL) { zend_error_noreturn(E_ERROR, "[] operator not supported for strings"); } if (Z_TYPE_P(dim) != IS_LONG) { switch(Z_TYPE_P(dim)) { /* case IS_LONG: */ case IS_STRING: case IS_DOUBLE: case IS_NULL: case IS_BOOL: /* do nothing */ break; default: zend_error(E_WARNING, "Illegal offset type"); break; } tmp = *dim; zval_copy_ctor(&tmp); convert_to_long(&tmp); dim = &tmp; } if (type != BP_VAR_UNSET) { SEPARATE_ZVAL_IF_NOT_REF(container_ptr); } container = *container_ptr; result->str_offset.str = container; PZVAL_LOCK(container); result->str_offset.offset = Z_LVAL_P(dim); result->str_offset.ptr_ptr = NULL; return; } break; case IS_OBJECT: if (!Z_OBJ_HT_P(container)->read_dimension) { zend_error_noreturn(E_ERROR, "Cannot use object as array"); } else { zval *overloaded_result; if (dim_type == IS_TMP_VAR) { zval *orig = dim; MAKE_REAL_ZVAL_PTR(dim); ZVAL_NULL(orig); } overloaded_result = Z_OBJ_HT_P(container)->read_dimension(container, dim, type TSRMLS_CC); if (overloaded_result) { if (!Z_ISREF_P(overloaded_result)) { if (Z_REFCOUNT_P(overloaded_result) > 0) { zval *tmp = overloaded_result; ALLOC_ZVAL(overloaded_result); ZVAL_COPY_VALUE(overloaded_result, tmp); zval_copy_ctor(overloaded_result); Z_UNSET_ISREF_P(overloaded_result); Z_SET_REFCOUNT_P(overloaded_result, 0); } if (Z_TYPE_P(overloaded_result) != IS_OBJECT) { zend_class_entry *ce = Z_OBJCE_P(container); zend_error(E_NOTICE, "Indirect modification of overloaded element of %s has no effect", ce->name); } } retval = &overloaded_result; } else { retval = &EG(error_zval_ptr); } AI_SET_PTR(result, *retval); PZVAL_LOCK(*retval); if (dim_type == IS_TMP_VAR) { zval_ptr_dtor(&dim); } } return; break; case IS_BOOL: if (type != BP_VAR_UNSET && Z_LVAL_P(container)==0) { goto convert_to_array; } /* break missing intentionally */ default: if (type == BP_VAR_UNSET) { zend_error(E_WARNING, "Cannot unset offset in a non-array variable"); AI_SET_PTR(result, &EG(uninitialized_zval)); PZVAL_LOCK(&EG(uninitialized_zval)); } else { zend_error(E_WARNING, "Cannot use a scalar value as an array"); result->var.ptr_ptr = &EG(error_zval_ptr); PZVAL_LOCK(EG(error_zval_ptr)); } break; } } static void zend_fetch_dimension_address_read(temp_variable *result, zval **container_ptr, zval *dim, int dim_type, int type TSRMLS_DC) { zval *container = *container_ptr; zval **retval; switch (Z_TYPE_P(container)) { case IS_ARRAY: retval = zend_fetch_dimension_address_inner(Z_ARRVAL_P(container), dim, dim_type, type TSRMLS_CC); AI_SET_PTR(result, *retval); PZVAL_LOCK(*retval); return; case IS_NULL: AI_SET_PTR(result, &EG(uninitialized_zval)); PZVAL_LOCK(&EG(uninitialized_zval)); return; case IS_STRING: { zval tmp; zval *ptr; if (Z_TYPE_P(dim) != IS_LONG) { switch(Z_TYPE_P(dim)) { /* case IS_LONG: */ case IS_STRING: case IS_DOUBLE: case IS_NULL: case IS_BOOL: /* do nothing */ break; default: zend_error(E_WARNING, "Illegal offset type"); break; } ZVAL_COPY_VALUE(&tmp, dim); zval_copy_ctor(&tmp); convert_to_long(&tmp); dim = &tmp; } ALLOC_ZVAL(ptr); INIT_PZVAL(ptr); Z_TYPE_P(ptr) = IS_STRING; if (Z_LVAL_P(dim) < 0 || Z_STRLEN_P(container) <= Z_LVAL_P(dim)) { if (type != BP_VAR_IS) { zend_error(E_NOTICE, "Uninitialized string offset: %ld", Z_LVAL_P(dim)); } Z_STRVAL_P(ptr) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ptr) = 0; } else { Z_STRVAL_P(ptr) = (char*)emalloc(2); Z_STRVAL_P(ptr)[0] = Z_STRVAL_P(container)[Z_LVAL_P(dim)]; Z_STRVAL_P(ptr)[1] = 0; Z_STRLEN_P(ptr) = 1; } AI_SET_PTR(result, ptr); return; } break; case IS_OBJECT: if (!Z_OBJ_HT_P(container)->read_dimension) { zend_error_noreturn(E_ERROR, "Cannot use object as array"); } else { zval *overloaded_result; if (dim_type == IS_TMP_VAR) { zval *orig = dim; MAKE_REAL_ZVAL_PTR(dim); ZVAL_NULL(orig); } overloaded_result = Z_OBJ_HT_P(container)->read_dimension(container, dim, type TSRMLS_CC); if (overloaded_result) { AI_SET_PTR(result, overloaded_result); PZVAL_LOCK(overloaded_result); } else if (result) { AI_SET_PTR(result, &EG(uninitialized_zval)); PZVAL_LOCK(&EG(uninitialized_zval)); } if (dim_type == IS_TMP_VAR) { zval_ptr_dtor(&dim); } } return; default: AI_SET_PTR(result, &EG(uninitialized_zval)); PZVAL_LOCK(&EG(uninitialized_zval)); return; } } static void zend_fetch_property_address(temp_variable *result, zval **container_ptr, zval *prop_ptr, const zend_literal *key, int type TSRMLS_DC) { zval *container = *container_ptr;; if (Z_TYPE_P(container) != IS_OBJECT) { if (container == &EG(error_zval)) { result->var.ptr_ptr = &EG(error_zval_ptr); PZVAL_LOCK(EG(error_zval_ptr)); return; } /* this should modify object only if it's empty */ if (type != BP_VAR_UNSET && ((Z_TYPE_P(container) == IS_NULL || (Z_TYPE_P(container) == IS_BOOL && Z_LVAL_P(container)==0) || (Z_TYPE_P(container) == IS_STRING && Z_STRLEN_P(container)==0)))) { if (!PZVAL_IS_REF(container)) { SEPARATE_ZVAL(container_ptr); container = *container_ptr; } object_init(container); } else { zend_error(E_WARNING, "Attempt to modify property of non-object"); result->var.ptr_ptr = &EG(error_zval_ptr); PZVAL_LOCK(EG(error_zval_ptr)); return; } } if (Z_OBJ_HT_P(container)->get_property_ptr_ptr) { zval **ptr_ptr = Z_OBJ_HT_P(container)->get_property_ptr_ptr(container, prop_ptr, key TSRMLS_CC); if (NULL == ptr_ptr) { zval *ptr; if (Z_OBJ_HT_P(container)->read_property && (ptr = Z_OBJ_HT_P(container)->read_property(container, prop_ptr, type, key TSRMLS_CC)) != NULL) { AI_SET_PTR(result, ptr); PZVAL_LOCK(ptr); } else { zend_error_noreturn(E_ERROR, "Cannot access undefined property for object with overloaded property access"); } } else { result->var.ptr_ptr = ptr_ptr; PZVAL_LOCK(*ptr_ptr); } } else if (Z_OBJ_HT_P(container)->read_property) { zval *ptr = Z_OBJ_HT_P(container)->read_property(container, prop_ptr, type, key TSRMLS_CC); AI_SET_PTR(result, ptr); PZVAL_LOCK(ptr); } else { zend_error(E_WARNING, "This object doesn't support property references"); result->var.ptr_ptr = &EG(error_zval_ptr); PZVAL_LOCK(EG(error_zval_ptr)); } } static inline zend_brk_cont_element* zend_brk_cont(int nest_levels, int array_offset, const zend_op_array *op_array, const temp_variable *Ts TSRMLS_DC) { int original_nest_levels = nest_levels; zend_brk_cont_element *jmp_to; do { if (array_offset==-1) { zend_error_noreturn(E_ERROR, "Cannot break/continue %d level%s", original_nest_levels, (original_nest_levels == 1) ? "" : "s"); } jmp_to = &op_array->brk_cont_array[array_offset]; if (nest_levels>1) { zend_op *brk_opline = &op_array->opcodes[jmp_to->brk]; switch (brk_opline->opcode) { case ZEND_SWITCH_FREE: if (!(brk_opline->extended_value & EXT_TYPE_FREE_ON_RETURN)) { zval_ptr_dtor(&T(brk_opline->op1.var).var.ptr); } break; case ZEND_FREE: if (!(brk_opline->extended_value & EXT_TYPE_FREE_ON_RETURN)) { zendi_zval_dtor(T(brk_opline->op1.var).tmp_var); } break; } } array_offset = jmp_to->parent; } while (--nest_levels > 0); return jmp_to; } #if ZEND_INTENSIVE_DEBUGGING #define CHECK_SYMBOL_TABLES() \ zend_hash_apply(&EG(symbol_table), (apply_func_t) zend_check_symbol TSRMLS_CC); \ if (&EG(symbol_table)!=EG(active_symbol_table)) { \ zend_hash_apply(EG(active_symbol_table), (apply_func_t) zend_check_symbol TSRMLS_CC); \ } static int zend_check_symbol(zval **pz TSRMLS_DC) { if (Z_TYPE_PP(pz) > 9) { fprintf(stderr, "Warning! %x has invalid type!\n", *pz); /* See http://support.microsoft.com/kb/190351 */ #ifdef PHP_WIN32 fflush(stderr); #endif } else if (Z_TYPE_PP(pz) == IS_ARRAY) { zend_hash_apply(Z_ARRVAL_PP(pz), (apply_func_t) zend_check_symbol TSRMLS_CC); } else if (Z_TYPE_PP(pz) == IS_OBJECT) { /* OBJ-TBI - doesn't support new object model! */ zend_hash_apply(Z_OBJPROP_PP(pz), (apply_func_t) zend_check_symbol TSRMLS_CC); } return 0; } #else #define CHECK_SYMBOL_TABLES() #endif ZEND_API opcode_handler_t *zend_opcode_handlers; ZEND_API void execute_internal(zend_execute_data *execute_data_ptr, int return_value_used TSRMLS_DC) { zval **return_value_ptr = &(*(temp_variable *)((char *) execute_data_ptr->Ts + execute_data_ptr->opline->result.var)).var.ptr; ((zend_internal_function *) execute_data_ptr->function_state.function)->handler(execute_data_ptr->opline->extended_value, *return_value_ptr, (execute_data_ptr->function_state.function->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)?return_value_ptr:NULL, execute_data_ptr->object, return_value_used TSRMLS_CC); } #define ZEND_VM_NEXT_OPCODE() \ CHECK_SYMBOL_TABLES() \ ZEND_VM_INC_OPCODE(); \ ZEND_VM_CONTINUE() #define ZEND_VM_SET_OPCODE(new_op) \ CHECK_SYMBOL_TABLES() \ OPLINE = new_op #define ZEND_VM_JMP(new_op) \ if (EXPECTED(!EG(exception))) { \ ZEND_VM_SET_OPCODE(new_op); \ } else { \ LOAD_OPLINE(); \ } \ ZEND_VM_CONTINUE() #define ZEND_VM_INC_OPCODE() \ OPLINE++ #ifdef __GNUC__ # define ZEND_VM_GUARD(name) __asm__("#" #name) #else # define ZEND_VM_GUARD(name) #endif #include "zend_vm_execute.h" ZEND_API int zend_set_user_opcode_handler(zend_uchar opcode, user_opcode_handler_t handler) { if (opcode != ZEND_USER_OPCODE) { zend_user_opcodes[opcode] = ZEND_USER_OPCODE; zend_user_opcode_handlers[opcode] = handler; return SUCCESS; } return FAILURE; } ZEND_API user_opcode_handler_t zend_get_user_opcode_handler(zend_uchar opcode) { return zend_user_opcode_handlers[opcode]; } ZEND_API zval *zend_get_zval_ptr(int op_type, const znode_op *node, const temp_variable *Ts, zend_free_op *should_free, int type TSRMLS_DC) { return get_zval_ptr(op_type, node, Ts, should_free, type); } ZEND_API zval **zend_get_zval_ptr_ptr(int op_type, const znode_op *node, const temp_variable *Ts, zend_free_op *should_free, int type TSRMLS_DC) { return get_zval_ptr_ptr(op_type, node, Ts, should_free, type); } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-02-11-f912a2d087-b84967d3e2.c
manybugs_data_57
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <zend_language_parser.h> #include "zend.h" #include "zend_compile.h" #include "zend_constants.h" #include "zend_llist.h" #include "zend_API.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "zend_multibyte.h" #include "zend_language_scanner.h" #define CONSTANT_EX(op_array, op) \ (op_array)->literals[op].constant #define CONSTANT(op) \ CONSTANT_EX(CG(active_op_array), op) #define SET_NODE(target, src) do { \ target ## _type = (src)->op_type; \ if ((src)->op_type == IS_CONST) { \ target.constant = zend_add_literal(CG(active_op_array), &(src)->u.constant TSRMLS_CC); \ } else { \ target = (src)->u.op; \ } \ } while (0) #define GET_NODE(target, src) do { \ (target)->op_type = src ## _type; \ if ((target)->op_type == IS_CONST) { \ (target)->u.constant = CONSTANT(src.constant); \ } else { \ (target)->u.op = src; \ (target)->EA = 0; \ } \ } while (0) #define COPY_NODE(target, src) do { \ target ## _type = src ## _type; \ target = src; \ } while (0) #define CALCULATE_LITERAL_HASH(num) do { \ if (IS_INTERNED(Z_STRVAL(CONSTANT(num)))) { \ Z_HASH_P(&CONSTANT(num)) = INTERNED_HASH(Z_STRVAL(CONSTANT(num))); \ } else { \ Z_HASH_P(&CONSTANT(num)) = zend_hash_func(Z_STRVAL(CONSTANT(num)), Z_STRLEN(CONSTANT(num))+1); \ } \ } while (0) #define GET_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot++; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ } \ } while (0) #define POLYMORPHIC_CACHE_SLOT_SIZE 2 #define GET_POLYMORPHIC_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot; \ CG(active_op_array)->last_cache_slot += POLYMORPHIC_CACHE_SLOT_SIZE; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 2] = NULL; \ } \ } while (0) #define FREE_POLYMORPHIC_CACHE_SLOT(literal) do { \ if (CG(active_op_array)->literals[literal].cache_slot == \ CG(active_op_array)->last_cache_slot - POLYMORPHIC_CACHE_SLOT_SIZE) { \ CG(active_op_array)->literals[literal].cache_slot = -1; \ CG(active_op_array)->last_cache_slot -= POLYMORPHIC_CACHE_SLOT_SIZE; \ } \ } while (0) ZEND_API zend_op_array *(*zend_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); ZEND_API zend_op_array *(*zend_compile_string)(zval *source_string, char *filename TSRMLS_DC); #ifndef ZTS ZEND_API zend_compiler_globals compiler_globals; ZEND_API zend_executor_globals executor_globals; #endif static void zend_duplicate_property_info(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = estrndup(property_info->name, property_info->name_length); } if (property_info->doc_comment) { property_info->doc_comment = estrndup(property_info->doc_comment, property_info->doc_comment_len); } } /* }}} */ static void zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = zend_strndup(property_info->name, property_info->name_length); } } /* }}} */ static void zend_destroy_property_info(zend_property_info *property_info) /* {{{ */ { str_efree(property_info->name); if (property_info->doc_comment) { efree((char*)property_info->doc_comment); } } /* }}} */ static void zend_destroy_property_info_internal(zend_property_info *property_info) /* {{{ */ { str_free((char*)property_info->name); } /* }}} */ static void build_runtime_defined_function_key(zval *result, const char *name, int name_length TSRMLS_DC) /* {{{ */ { char char_pos_buf[32]; uint char_pos_len; const char *filename; char_pos_len = zend_sprintf(char_pos_buf, "%p", LANG_SCNG(yy_text)); if (CG(active_op_array)->filename) { filename = CG(active_op_array)->filename; } else { filename = "-"; } /* NULL, name length, filename length, last accepting char position length */ result->value.str.len = 1+name_length+strlen(filename)+char_pos_len; /* must be binary safe */ result->value.str.val = (char *) safe_emalloc(result->value.str.len, 1, 1); result->value.str.val[0] = '\0'; sprintf(result->value.str.val+1, "%s%s%s", name, filename, char_pos_buf); result->type = IS_STRING; Z_SET_REFCOUNT_P(result, 1); } /* }}} */ static void init_compiler_declarables(TSRMLS_D) /* {{{ */ { Z_TYPE(CG(declarables).ticks) = IS_LONG; Z_LVAL(CG(declarables).ticks) = 0; } /* }}} */ void zend_init_compiler_context(TSRMLS_D) /* {{{ */ { CG(context).opcodes_size = (CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) ? INITIAL_INTERACTIVE_OP_ARRAY_SIZE : INITIAL_OP_ARRAY_SIZE; CG(context).vars_size = 0; CG(context).literals_size = 0; CG(context).current_brk_cont = -1; CG(context).backpatch_count = 0; CG(context).labels = NULL; } /* }}} */ void zend_init_compiler_data_structures(TSRMLS_D) /* {{{ */ { zend_stack_init(&CG(bp_stack)); zend_stack_init(&CG(function_call_stack)); zend_stack_init(&CG(switch_cond_stack)); zend_stack_init(&CG(foreach_copy_stack)); zend_stack_init(&CG(object_stack)); zend_stack_init(&CG(declare_stack)); CG(active_class_entry) = NULL; zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_stack_init(&CG(list_stack)); CG(in_compilation) = 0; CG(start_lineno) = 0; CG(current_namespace) = NULL; CG(in_namespace) = 0; CG(has_bracketed_namespaces) = 0; CG(current_import) = NULL; init_compiler_declarables(TSRMLS_C); zend_stack_init(&CG(context_stack)); CG(encoding_declared) = 0; } /* }}} */ ZEND_API void file_handle_dtor(zend_file_handle *fh) /* {{{ */ { TSRMLS_FETCH(); zend_file_handle_dtor(fh TSRMLS_CC); } /* }}} */ void init_compiler(TSRMLS_D) /* {{{ */ { CG(active_op_array) = NULL; zend_init_compiler_data_structures(TSRMLS_C); zend_init_rsrc_list(TSRMLS_C); zend_hash_init(&CG(filenames_table), 5, NULL, (dtor_func_t) free_estring, 0); zend_llist_init(&CG(open_files), sizeof(zend_file_handle), (void (*)(void *)) file_handle_dtor, 0); CG(unclean_shutdown) = 0; } /* }}} */ void shutdown_compiler(TSRMLS_D) /* {{{ */ { zend_stack_destroy(&CG(bp_stack)); zend_stack_destroy(&CG(function_call_stack)); zend_stack_destroy(&CG(switch_cond_stack)); zend_stack_destroy(&CG(foreach_copy_stack)); zend_stack_destroy(&CG(object_stack)); zend_stack_destroy(&CG(declare_stack)); zend_stack_destroy(&CG(list_stack)); zend_hash_destroy(&CG(filenames_table)); zend_llist_destroy(&CG(open_files)); zend_stack_destroy(&CG(context_stack)); } /* }}} */ ZEND_API char *zend_set_compiled_filename(const char *new_compiled_filename TSRMLS_DC) /* {{{ */ { char **pp, *p; int length = strlen(new_compiled_filename); if (zend_hash_find(&CG(filenames_table), new_compiled_filename, length+1, (void **) &pp) == SUCCESS) { CG(compiled_filename) = *pp; return *pp; } p = estrndup(new_compiled_filename, length); zend_hash_update(&CG(filenames_table), new_compiled_filename, length+1, &p, sizeof(char *), (void **) &pp); CG(compiled_filename) = p; return p; } /* }}} */ ZEND_API void zend_restore_compiled_filename(char *original_compiled_filename TSRMLS_DC) /* {{{ */ { CG(compiled_filename) = original_compiled_filename; } /* }}} */ ZEND_API char *zend_get_compiled_filename(TSRMLS_D) /* {{{ */ { return CG(compiled_filename); } /* }}} */ ZEND_API int zend_get_compiled_lineno(TSRMLS_D) /* {{{ */ { return CG(zend_lineno); } /* }}} */ ZEND_API zend_bool zend_is_compiling(TSRMLS_D) /* {{{ */ { return CG(in_compilation); } /* }}} */ static zend_uint get_temporary_variable(zend_op_array *op_array) /* {{{ */ { return (op_array->T)++ * ZEND_MM_ALIGNED_SIZE(sizeof(temp_variable)); } /* }}} */ static int lookup_cv(zend_op_array *op_array, char* name, int name_len, ulong hash TSRMLS_DC) /* {{{ */ { int i = 0; ulong hash_value = hash ? hash : zend_inline_hash_func(name, name_len+1); while (i < op_array->last_var) { if (op_array->vars[i].name == name || (op_array->vars[i].hash_value == hash_value && op_array->vars[i].name_len == name_len && memcmp(op_array->vars[i].name, name, name_len) == 0)) { str_efree(name); return i; } i++; } i = op_array->last_var; op_array->last_var++; if (op_array->last_var > CG(context).vars_size) { CG(context).vars_size += 16; /* FIXME */ op_array->vars = erealloc(op_array->vars, CG(context).vars_size * sizeof(zend_compiled_variable)); } op_array->vars[i].name = zend_new_interned_string(name, name_len + 1, 1 TSRMLS_CC); op_array->vars[i].name_len = name_len; op_array->vars[i].hash_value = hash_value; return i; } /* }}} */ void zend_del_literal(zend_op_array *op_array, int n) /* {{{ */ { zval_dtor(&CONSTANT_EX(op_array, n)); if (n + 1 == op_array->last_literal) { op_array->last_literal--; } else { Z_TYPE(CONSTANT_EX(op_array, n)) = IS_NULL; } } /* }}} */ /* Common part of zend_add_literal and zend_append_individual_literal */ static inline void zend_insert_literal(zend_op_array *op_array, const zval *zv, int literal_position TSRMLS_DC) /* {{{ */ { if (Z_TYPE_P(zv) == IS_STRING || Z_TYPE_P(zv) == IS_CONSTANT) { zval *z = (zval*)zv; Z_STRVAL_P(z) = (char*)zend_new_interned_string(Z_STRVAL_P(zv), Z_STRLEN_P(zv) + 1, 1 TSRMLS_CC); } CONSTANT_EX(op_array, literal_position) = *zv; Z_SET_REFCOUNT(CONSTANT_EX(op_array, literal_position), 2); Z_SET_ISREF(CONSTANT_EX(op_array, literal_position)); op_array->literals[literal_position].hash_value = 0; op_array->literals[literal_position].cache_slot = -1; } /* }}} */ /* Is used while compiling a function, using the context to keep track of an approximate size to avoid to relocate to often. Literals are truncated to actual size in the second compiler pass (pass_two()). */ int zend_add_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; if (i >= CG(context).literals_size) { while (i >= CG(context).literals_size) { CG(context).literals_size += 16; /* FIXME */ } op_array->literals = (zend_literal*)erealloc(op_array->literals, CG(context).literals_size * sizeof(zend_literal)); } zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ /* Is used after normal compilation to append an additional literal. Allocation is done precisely here. */ int zend_append_individual_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; op_array->literals = (zend_literal*)erealloc(op_array->literals, (i + 1) * sizeof(zend_literal)); zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ int zend_add_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_ns_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; const char *ns_separator; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); ns_separator = (const char*)zend_memrchr(Z_STRVAL_P(zv), '\\', Z_STRLEN_P(zv)) + 1; lc_len = Z_STRLEN_P(zv) - (ns_separator - Z_STRVAL_P(zv)); lc_name = zend_str_tolower_dup(ns_separator, lc_len); ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_class_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } if (Z_STRVAL_P(zv)[0] == '\\') { lc_len = Z_STRLEN_P(zv) - 1; lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv) + 1, lc_len); } else { lc_len = Z_STRLEN_P(zv); lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), lc_len); } ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); GET_CACHE_SLOT(ret); return ret; } /* }}} */ int zend_add_const_name_literal(zend_op_array *op_array, const zval *zv, int unqualified TSRMLS_DC) /* {{{ */ { int ret, tmp_literal; char *name, *tmp_name; const char *ns_separator; int name_len, ns_len; zval c; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } /* skip leading '\\' */ if (Z_STRVAL_P(zv)[0] == '\\') { name_len = Z_STRLEN_P(zv) - 1; name = Z_STRVAL_P(zv) + 1; } else { name_len = Z_STRLEN_P(zv); name = Z_STRVAL_P(zv); } ns_separator = zend_memrchr(name, '\\', name_len); if (ns_separator) { ns_len = ns_separator - name; } else { ns_len = 0; } if (ns_len) { /* lowercased namespace name & original constant name */ tmp_name = estrndup(name, name_len); zend_str_tolower(tmp_name, ns_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased namespace name & lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); } if (ns_len) { if (!unqualified) { return ret; } ns_len++; name += ns_len; name_len -= ns_len; } /* original constant name */ tmp_name = estrndup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); return ret; } /* }}} */ #define LITERAL_STRINGL(op, str, len, copy) do { \ zval _c; \ ZVAL_STRINGL(&_c, str, len, copy); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG(op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG_EX(op_array, op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(op_array, &_c TSRMLS_CC); \ } while (0) #define LITERAL_NULL(op) do { \ zval _c; \ INIT_ZVAL( _c); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) static inline zend_bool zend_is_function_or_method_call(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; return ((type & ZEND_PARSED_METHOD_CALL) || (type == ZEND_PARSED_FUNCTION_CALL)); } /* }}} */ void zend_do_binary_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_unary_op(zend_uchar op, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); GET_NODE(result, opline->result); SET_UNUSED(opline->op2); } /* }}} */ #define MAKE_NOP(opline) { opline->opcode = ZEND_NOP; memset(&opline->result,0,sizeof(opline->result)); memset(&opline->op1,0,sizeof(opline->op1)); memset(&opline->op2,0,sizeof(opline->op2)); opline->result_type=opline->op1_type=opline->op2_type=IS_UNUSED; } static void zend_do_op_data(zend_op *data_op, const znode *value TSRMLS_DC) /* {{{ */ { data_op->opcode = ZEND_OP_DATA; SET_NODE(data_op->op1, value); SET_UNUSED(data_op->op2); } /* }}} */ void zend_do_binary_assign_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; switch (last_op->opcode) { case ZEND_FETCH_OBJ_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, op2 TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; case ZEND_FETCH_DIM_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_DIM; zend_do_op_data(opline, op2 TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result,last_op->result); return; default: break; } } opline->opcode = op; SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void fetch_simple_variable_ex(znode *result, znode *varname, int bp, zend_uchar op TSRMLS_DC) /* {{{ */ { zend_op opline; zend_op *opline_ptr; zend_llist *fetch_list_ptr; if (varname->op_type == IS_CONST) { ulong hash = 0; if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } else if (IS_INTERNED(Z_STRVAL(varname->u.constant))) { hash = INTERNED_HASH(Z_STRVAL(varname->u.constant)); } if (!zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC) && !(varname->u.constant.value.str.len == (sizeof("this")-1) && !memcmp(varname->u.constant.value.str.val, "this", sizeof("this"))) && (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE)) { result->op_type = IS_CV; result->u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC); varname->u.constant.value.str.val = (char*)CG(active_op_array)->vars[result->u.op.var].name; result->EA = 0; return; } } if (bp) { opline_ptr = &opline; init_op(opline_ptr TSRMLS_CC); } else { opline_ptr = get_next_op(CG(active_op_array) TSRMLS_CC); } opline_ptr->opcode = op; opline_ptr->result_type = IS_VAR; opline_ptr->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline_ptr->op1, varname); GET_NODE(result, opline_ptr->result); SET_UNUSED(opline_ptr->op2); opline_ptr->extended_value = ZEND_FETCH_LOCAL; if (varname->op_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline_ptr->op1.constant); if (zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC)) { opline_ptr->extended_value = ZEND_FETCH_GLOBAL; } } if (bp) { zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); zend_llist_add_element(fetch_list_ptr, opline_ptr); } } /* }}} */ void fetch_simple_variable(znode *result, znode *varname, int bp TSRMLS_DC) /* {{{ */ { /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ fetch_simple_variable_ex(result, varname, bp, ZEND_FETCH_W TSRMLS_CC); } /* }}} */ void zend_do_fetch_static_member(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { znode class_node; zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline_ptr; zend_op opline; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); } zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (result->op_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[result->u.op.var].name), CG(active_op_array)->vars[result->u.op.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } GET_NODE(result,opline.result); opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; opline_ptr = &opline; zend_llist_add_element(fetch_list_ptr, &opline); } else { le = fetch_list_ptr->head; opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode != ZEND_FETCH_W && opline_ptr->op1_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[opline_ptr->op1.var].name), CG(active_op_array)->vars[opline_ptr->op1.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; COPY_NODE(opline_ptr->op1, opline.result); zend_llist_prepend_element(fetch_list_ptr, &opline); } else { if (opline_ptr->op1_type == IS_CONST) { GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op1.constant); } if (class_node.op_type == IS_CONST) { opline_ptr->op2_type = IS_CONST; opline_ptr->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline_ptr->op2, &class_node); } opline_ptr->extended_value |= ZEND_FETCH_STATIC_MEMBER; } } } /* }}} */ void fetch_array_begin(znode *result, znode *varname, znode *first_dim TSRMLS_DC) /* {{{ */ { fetch_simple_variable(result, varname, 1 TSRMLS_CC); fetch_array_dim(result, result, first_dim TSRMLS_CC); } /* }}} */ void fetch_array_dim(znode *result, const znode *parent, const znode *dim TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (zend_is_function_or_method_call(parent)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, parent); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_DIM_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, parent); SET_NODE(opline.op2, dim); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline.op2.constant)), Z_STRLEN(CONSTANT(opline.op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline.op2.constant)); ZVAL_LONG(&CONSTANT(opline.op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline.op2.constant); } } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void fetch_string_offset(znode *result, const znode *parent, const znode *offset TSRMLS_DC) /* {{{ */ { fetch_array_dim(result, parent, offset TSRMLS_CC); } /* }}} */ void zend_do_print(znode *result, const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->opcode = ZEND_PRINT; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_echo(const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ECHO; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_abstract_method(const znode *function_name, znode *modifiers, const znode *body TSRMLS_DC) /* {{{ */ { char *method_type; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { Z_LVAL(modifiers->u.constant) |= ZEND_ACC_ABSTRACT; method_type = "Interface"; } else { method_type = "Abstract"; } if (modifiers->u.constant.value.lval & ZEND_ACC_ABSTRACT) { if(modifiers->u.constant.value.lval & ZEND_ACC_PRIVATE) { zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot be declared private", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } if (Z_LVAL(body->u.constant) == ZEND_ACC_ABSTRACT) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_RAISE_ABSTRACT_ERROR; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } else { /* we had code in the function body */ zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot contain body", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } else { if (body->u.constant.value.lval == ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Non-abstract method %s::%s() must contain body", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } } /* }}} */ static zend_bool opline_is_fetch_this(const zend_op *opline TSRMLS_DC) /* {{{ */ { if ((opline->opcode == ZEND_FETCH_W) && (opline->op1_type == IS_CONST) && (Z_TYPE(CONSTANT(opline->op1.constant)) == IS_STRING) && (Z_HASH_P(&CONSTANT(opline->op1.constant)) == THIS_HASHVAL) && (Z_STRLEN(CONSTANT(opline->op1.constant)) == (sizeof("this")-1)) && !memcmp(Z_STRVAL(CONSTANT(opline->op1.constant)), "this", sizeof("this"))) { return 1; } else { return 0; } } /* }}} */ void zend_do_assign(znode *result, znode *variable, znode *value TSRMLS_DC) /* {{{ */ { int last_op_number; zend_op *opline; if (value->op_type == IS_CV) { zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (fetch_list_ptr && fetch_list_ptr->head) { opline = (zend_op *)fetch_list_ptr->head->data; if (opline->opcode == ZEND_FETCH_DIM_W && opline->op1_type == IS_CV && opline->op1.var == value->u.op.var) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_R; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->op1_type = IS_CONST; LITERAL_STRINGL(opline->op1, CG(active_op_array)->vars[value->u.op.var].name, CG(active_op_array)->vars[value->u.op.var].name_len, 1); CALCULATE_LITERAL_HASH(opline->op1.constant); SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_LOCAL; GET_NODE(value, opline->result); } } } zend_do_end_variable_parse(variable, BP_VAR_W, 0 TSRMLS_CC); last_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (variable->op_type == IS_CV) { if (variable->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (variable->op_type == IS_VAR) { int n = 0; while (last_op_number - n > 0) { zend_op *last_op; last_op = &CG(active_op_array)->opcodes[last_op_number-n-1]; if (last_op->result_type == IS_VAR && last_op->result.var == variable->u.op.var) { if (last_op->opcode == ZEND_FETCH_OBJ_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, value TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (last_op->opcode == ZEND_FETCH_DIM_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ /* TBFixed: this can realloc opcodes, leaving last_op pointing wrong */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_DIM; zend_do_op_data(opline, value TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (opline_is_fetch_this(last_op TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } else { break; } } n++; } } opline->opcode = ZEND_ASSIGN; SET_NODE(opline->op1, variable); SET_NODE(opline->op2, value); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_assign_ref(znode *result, const znode *lvar, const znode *rvar TSRMLS_DC) /* {{{ */ { zend_op *opline; if (lvar->op_type == IS_CV) { if (lvar->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (lvar->op_type == IS_VAR) { int last_op_number = get_next_op_number(CG(active_op_array)); if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline_is_fetch_this(opline TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ASSIGN_REF; if (zend_is_function_or_method_call(rvar)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } else if (rvar->EA & ZEND_PARSED_NEW) { opline->extended_value = ZEND_RETURNS_NEW; } else { opline->extended_value = 0; } if (result) { opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } else { opline->result_type = IS_UNUSED | EXT_TYPE_UNUSED; } SET_NODE(opline->op1, lvar); SET_NODE(opline->op2, rvar); } /* }}} */ static inline void do_begin_loop(TSRMLS_D) /* {{{ */ { zend_brk_cont_element *brk_cont_element; int parent; parent = CG(context).current_brk_cont; CG(context).current_brk_cont = CG(active_op_array)->last_brk_cont; brk_cont_element = get_next_brk_cont_element(CG(active_op_array)); brk_cont_element->start = get_next_op_number(CG(active_op_array)); brk_cont_element->parent = parent; } /* }}} */ static inline void do_end_loop(int cont_addr, int has_loop_var TSRMLS_DC) /* {{{ */ { if (!has_loop_var) { /* The start fileld is used to free temporary variables in case of exceptions. * We won't try to free something of we don't have loop variable. */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].start = -1; } CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = cont_addr; CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; } /* }}} */ void zend_do_while_cond(const znode *expr, znode *close_bracket_token TSRMLS_DC) /* {{{ */ { int while_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, expr); close_bracket_token->u.op.opline_num = while_cond_op_number; SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_while_end(const znode *while_token, const znode *close_bracket_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* add unconditional jump */ opline->opcode = ZEND_JMP; opline->op1.opline_num = while_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* update while's conditional jmp */ CG(active_op_array)->opcodes[close_bracket_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); do_end_loop(while_token->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_cond(const znode *expr, znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { int for_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZNZ; SET_NODE(opline->op1, expr); /* the conditional expression */ second_semicolon_token->u.op.opline_num = for_cond_op_number; SET_UNUSED(opline->op2); } /* }}} */ void zend_do_for_before_statement(const znode *cond_start, const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = cond_start->u.op.opline_num; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_end(const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = second_semicolon_token->u.op.opline_num+1; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_end_loop(second_semicolon_token->u.op.opline_num+1, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_pre_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_PRE_INC)?ZEND_PRE_INC_OBJ:ZEND_PRE_DEC_OBJ; last_op->result_type = IS_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_post_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_POST_INC)?ZEND_POST_INC_OBJ:ZEND_POST_DEC_OBJ; last_op->result_type = IS_TMP_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_if_cond(const znode *cond, znode *closing_bracket_token TSRMLS_DC) /* {{{ */ { int if_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); closing_bracket_token->u.op.opline_num = if_cond_op_number; SET_UNUSED(opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_if_after_statement(const znode *closing_bracket_token, unsigned char initialize TSRMLS_DC) /* {{{ */ { int if_end_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; /* save for backpatching */ if (initialize) { zend_llist jmp_list; zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); } zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &if_end_op_number); CG(active_op_array)->opcodes[closing_bracket_token->u.op.opline_num].op2.opline_num = if_end_op_number+1; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_if_end(TSRMLS_D) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_llist *jmp_list_ptr; zend_llist_element *le; zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); for (le=jmp_list_ptr->head; le; le = le->next) { CG(active_op_array)->opcodes[*((int *) le->data)].op1.opline_num = next_op_number; } zend_llist_destroy(jmp_list_ptr); zend_stack_del_top(&CG(bp_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_check_writable_variable(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; if (type & ZEND_PARSED_METHOD_CALL) { zend_error(E_COMPILE_ERROR, "Can't use method return value in write context"); } if (type == ZEND_PARSED_FUNCTION_CALL) { zend_error(E_COMPILE_ERROR, "Can't use function return value in write context"); } } /* }}} */ void zend_do_begin_variable_parse(TSRMLS_D) /* {{{ */ { zend_llist fetch_list; zend_llist_init(&fetch_list, sizeof(zend_op), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &fetch_list, sizeof(zend_llist)); } /* }}} */ void zend_do_end_variable_parse(znode *variable, int type, int arg_offset TSRMLS_DC) /* {{{ */ { zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline = NULL; zend_op *opline_ptr; zend_uint this_var = -1; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); le = fetch_list_ptr->head; /* TODO: $foo->x->y->z = 1 should fetch "x" and "y" for R or RW, not just W */ if (le) { opline_ptr = (zend_op *)le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { /* convert to FETCH_?(this) into IS_CV */ if (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE) { this_var = opline_ptr->result.var; if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), Z_STRVAL(CONSTANT(opline_ptr->op1.constant)), Z_STRLEN(CONSTANT(opline_ptr->op1.constant)), Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC); Z_TYPE(CONSTANT(opline_ptr->op1.constant)) = IS_NULL; } else { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); } le = le->next; if (variable->op_type == IS_VAR && variable->u.op.var == this_var) { variable->op_type = IS_CV; variable->u.op.var = CG(active_op_array)->this_var; } } else if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } while (le) { opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode == ZEND_SEPARATE) { if (type != BP_VAR_R && type != BP_VAR_IS) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); } le = le->next; continue; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); if (opline->op1_type == IS_VAR && opline->op1.var == this_var) { opline->op1_type = IS_CV; opline->op1.var = CG(active_op_array)->this_var; } switch (type) { case BP_VAR_R: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode -= 3; break; case BP_VAR_W: break; case BP_VAR_RW: opline->opcode += 3; break; case BP_VAR_IS: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode += 6; /* 3+3 */ break; case BP_VAR_FUNC_ARG: opline->opcode += 9; /* 3+3+3 */ opline->extended_value |= arg_offset; break; case BP_VAR_UNSET: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for unsetting"); } opline->opcode += 12; /* 3+3+3+3 */ break; } le = le->next; } if (opline && type == BP_VAR_W && arg_offset) { opline->extended_value |= ZEND_FETCH_MAKE_REF; } } zend_llist_destroy(fetch_list_ptr); zend_stack_del_top(&CG(bp_stack)); } /* }}} */ void zend_do_add_string(znode *result, const znode *op1, znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline; if (Z_STRLEN(op2->u.constant) > 1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_STRING; } else if (Z_STRLEN(op2->u.constant) == 1) { int ch = *Z_STRVAL(op2->u.constant); /* Free memory and use ZEND_ADD_CHAR in case of 1 character strings */ efree(Z_STRVAL(op2->u.constant)); ZVAL_LONG(&op2->u.constant, ch); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_CHAR; } else { /* String can be empty after a variable at the end of a heredoc */ efree(Z_STRVAL(op2->u.constant)); return; } if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_add_variable(znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_VAR; if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_free(znode *op1 TSRMLS_DC) /* {{{ */ { if (op1->op_type==IS_TMP_VAR) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else if (op1->op_type==IS_VAR) { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; while (opline->opcode == ZEND_END_SILENCE || opline->opcode == ZEND_EXT_FCALL_END || opline->opcode == ZEND_OP_DATA) { opline--; } if (opline->result_type == IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_FETCH_R || opline->opcode == ZEND_FETCH_DIM_R || opline->opcode == ZEND_FETCH_OBJ_R || opline->opcode == ZEND_QM_ASSIGN_VAR) { /* It's very rare and useless case. It's better to use additional FREE opcode and simplify the FETCH handlers their selves */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else { opline->result_type |= EXT_TYPE_UNUSED; } } else { while (opline>CG(active_op_array)->opcodes) { if (opline->opcode == ZEND_FETCH_DIM_R && opline->op1_type == IS_VAR && opline->op1.var == op1->u.op.var) { /* This should the end of a list() construct * Mark its result as unused */ opline->extended_value = ZEND_FETCH_STANDARD; break; } else if (opline->result_type==IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_NEW) { opline->result_type |= EXT_TYPE_UNUSED; } break; } opline--; } } } else if (op1->op_type == IS_CONST) { zval_dtor(&op1->u.constant); } } /* }}} */ int zend_do_verify_access_types(const znode *current_access_type, const znode *new_modifier) /* {{{ */ { if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_PPP_MASK) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Multiple access type modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_ABSTRACT) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Multiple abstract modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_STATIC) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Multiple static modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_FINAL) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Multiple final modifiers are not allowed"); } if (((Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)) & (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) == (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Cannot use the final modifier on an abstract class member"); } return (Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)); } /* }}} */ void zend_do_begin_function_declaration(znode *function_token, znode *function_name, int is_method, int return_reference, znode *fn_flags_znode TSRMLS_DC) /* {{{ */ { zend_op_array op_array; char *name = function_name->u.constant.value.str.val; int name_len = function_name->u.constant.value.str.len; int function_begin_line = function_token->u.op.opline_num; zend_uint fn_flags; const char *lcname; zend_bool orig_interactive; ALLOCA_FLAG(use_heap) if (is_method) { if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((Z_LVAL(fn_flags_znode->u.constant) & ~(ZEND_ACC_STATIC|ZEND_ACC_PUBLIC))) { zend_error(E_COMPILE_ERROR, "Access type for interface method %s::%s() must be omitted", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } Z_LVAL(fn_flags_znode->u.constant) |= ZEND_ACC_ABSTRACT; /* propagates to the rest of the parser */ } fn_flags = Z_LVAL(fn_flags_znode->u.constant); /* must be done *after* the above check */ } else { fn_flags = 0; } if ((fn_flags & ZEND_ACC_STATIC) && (fn_flags & ZEND_ACC_ABSTRACT) && !(CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_STRICT, "Static function %s%s%s() should not be abstract", is_method ? CG(active_class_entry)->name : "", is_method ? "::" : "", Z_STRVAL(function_name->u.constant)); } function_token->u.op_array = CG(active_op_array); orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(&op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; op_array.function_name = name; if (return_reference) { op_array.fn_flags |= ZEND_ACC_RETURN_REFERENCE; } op_array.fn_flags |= fn_flags; op_array.scope = is_method?CG(active_class_entry):NULL; op_array.prototype = NULL; op_array.line_start = zend_get_compiled_lineno(TSRMLS_C); if (is_method) { int result; lcname = zend_new_interned_string(zend_str_tolower_dup(name, name_len), name_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lcname)) { result = zend_hash_quick_add(&CG(active_class_entry)->function_table, lcname, name_len+1, INTERNED_HASH(lcname), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } else { result = zend_hash_add(&CG(active_class_entry)->function_table, lcname, name_len+1, &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } if (result == FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::%s()", CG(active_class_entry)->name, name); } zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); if (fn_flags & ZEND_ACC_ABSTRACT) { CG(active_class_entry)->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (!(fn_flags & ZEND_ACC_PPP_MASK)) { fn_flags |= ZEND_ACC_PUBLIC; } if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } } } else { char *class_lcname; class_lcname = do_alloca(CG(active_class_entry)->name_length + 1, use_heap); zend_str_tolower_copy(class_lcname, CG(active_class_entry)->name, CG(active_class_entry)->name_length); /* Improve after RC: cache the lowercase class name */ if ((CG(active_class_entry)->name_length == name_len) && ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT) && (!memcmp(class_lcname, lcname, name_len))) { if (!CG(active_class_entry)->constructor) { CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } } else if ((name_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)))) { if (CG(active_class_entry)->constructor) { zend_error(E_STRICT, "Redefining already defined constructor for class %s", CG(active_class_entry)->name); } CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1))) { CG(active_class_entry)->destructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1))) { CG(active_class_entry)->clone = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } CG(active_class_entry)->__call = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } CG(active_class_entry)->__callstatic = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } CG(active_class_entry)->__get = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } CG(active_class_entry)->__set = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } CG(active_class_entry)->__unset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } CG(active_class_entry)->__isset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } CG(active_class_entry)->__tostring = (zend_function *) CG(active_op_array); } else if (!(fn_flags & ZEND_ACC_STATIC)) { CG(active_op_array)->fn_flags |= ZEND_ACC_ALLOW_STATIC; } free_alloca(class_lcname, use_heap); } str_efree(lcname); } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zval key; if (CG(current_namespace)) { /* Prefix function name with current namespcae name */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, function_name TSRMLS_CC); op_array.function_name = Z_STRVAL(tmp.u.constant); name_len = Z_STRLEN(tmp.u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), name_len); } else { lcname = zend_str_tolower_dup(name, name_len); } opline->opcode = ZEND_DECLARE_FUNCTION; opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, name_len TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; LITERAL_STRINGL(opline->op2, lcname, name_len, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); opline->extended_value = ZEND_DECLARE_FUNCTION; zend_hash_quick_update(CG(function_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); } if (CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_NOP; opline->lineno = function_begin_line; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } { /* Push a seperator to the switch and foreach stacks */ zend_switch_entry switch_entry; switch_entry.cond.op_type = IS_UNUSED; switch_entry.default_case = 0; switch_entry.control_var = 0; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); { /* Foreach stack separator */ zend_op dummy_opline; dummy_opline.result_type = IS_UNUSED; dummy_opline.op1_type = IS_UNUSED; zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); } } if (CG(doc_comment)) { CG(active_op_array)->doc_comment = CG(doc_comment); CG(active_op_array)->doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_begin_lambda_function_declaration(znode *result, znode *function_token, int return_reference, int is_static TSRMLS_DC) /* {{{ */ { znode function_name; zend_op_array *current_op_array = CG(active_op_array); int current_op_number = get_next_op_number(CG(active_op_array)); zend_op *current_op; function_name.op_type = IS_CONST; ZVAL_STRINGL(&function_name.u.constant, "{closure}", sizeof("{closure}")-1, 1); zend_do_begin_function_declaration(function_token, &function_name, 0, return_reference, NULL TSRMLS_CC); result->op_type = IS_TMP_VAR; result->u.op.var = get_temporary_variable(current_op_array); current_op = &current_op_array->opcodes[current_op_number]; current_op->opcode = ZEND_DECLARE_LAMBDA_FUNCTION; zend_del_literal(current_op_array, current_op->op2.constant); SET_UNUSED(current_op->op2); SET_NODE(current_op->result, result); if (is_static) { CG(active_op_array)->fn_flags |= ZEND_ACC_STATIC; } CG(active_op_array)->fn_flags |= ZEND_ACC_CLOSURE; } /* }}} */ void zend_do_handle_exception(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_HANDLE_EXCEPTION; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_function_declaration(const znode *function_token TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; zend_do_extended_info(TSRMLS_C); zend_do_return(NULL, 0 TSRMLS_CC); pass_two(CG(active_op_array) TSRMLS_CC); zend_release_labels(TSRMLS_C); if (CG(active_class_entry)) { zend_check_magic_method_implementation(CG(active_class_entry), (zend_function*)CG(active_op_array), E_COMPILE_ERROR TSRMLS_CC); } else { /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(CG(active_op_array)->function_name); zend_str_tolower_copy(lcname, CG(active_op_array)->function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME)) && CG(active_op_array)->num_args != 1) { zend_error(E_COMPILE_ERROR, "%s() must take exactly 1 argument", ZEND_AUTOLOAD_FUNC_NAME); } } CG(active_op_array)->line_end = zend_get_compiled_lineno(TSRMLS_C); CG(active_op_array) = function_token->u.op_array; /* Pop the switch and foreach seperators */ zend_stack_del_top(&CG(switch_cond_stack)); zend_stack_del_top(&CG(foreach_copy_stack)); } /* }}} */ void zend_do_receive_arg(zend_uchar op, znode *varname, const znode *offset, const znode *initialization, znode *class_type, zend_uchar pass_by_reference TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_arg_info *cur_arg_info; znode var; if (class_type->op_type == IS_CONST && Z_TYPE(class_type->u.constant) == IS_STRING && Z_STRLEN(class_type->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_type->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } if (zend_is_auto_global_quick(Z_STRVAL(varname->u.constant), Z_STRLEN(varname->u.constant), 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign auto-global variable %s", Z_STRVAL(varname->u.constant)); } else { var.op_type = IS_CV; var.u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(varname->u.constant) = (char*)CG(active_op_array)->vars[var.u.op.var].name; var.EA = 0; if (CG(active_op_array)->vars[var.u.op.var].hash_value == THIS_HASHVAL && Z_STRLEN(varname->u.constant) == sizeof("this")-1 && !memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this")-1)) { if (CG(active_op_array)->scope && (CG(active_op_array)->fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } CG(active_op_array)->this_var = var.u.op.var; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->num_args++; opline->opcode = op; SET_NODE(opline->result, &var); SET_NODE(opline->op1, offset); if (op == ZEND_RECV_INIT) { SET_NODE(opline->op2, initialization); } else { CG(active_op_array)->required_num_args = CG(active_op_array)->num_args; SET_UNUSED(opline->op2); } CG(active_op_array)->arg_info = erealloc(CG(active_op_array)->arg_info, sizeof(zend_arg_info)*(CG(active_op_array)->num_args)); cur_arg_info = &CG(active_op_array)->arg_info[CG(active_op_array)->num_args-1]; cur_arg_info->name = zend_new_interned_string(estrndup(varname->u.constant.value.str.val, varname->u.constant.value.str.len), varname->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->name_len = varname->u.constant.value.str.len; cur_arg_info->type_hint = 0; cur_arg_info->allow_null = 1; cur_arg_info->pass_by_reference = pass_by_reference; cur_arg_info->class_name = NULL; cur_arg_info->class_name_len = 0; if (class_type->op_type != IS_UNUSED) { cur_arg_info->allow_null = 0; if (class_type->u.constant.type != IS_NULL) { if (class_type->u.constant.type == IS_ARRAY) { cur_arg_info->type_hint = IS_ARRAY; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else if (Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Default value for parameters with array type hint can only be an array or NULL"); } } } else if (class_type->u.constant.type == IS_CALLABLE) { cur_arg_info->type_hint = IS_CALLABLE; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with callable type hint can only be NULL"); } } } else { cur_arg_info->type_hint = IS_OBJECT; if (ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_type->u.constant), Z_STRLEN(class_type->u.constant))) { zend_resolve_class_name(class_type, opline->extended_value, 1 TSRMLS_CC); } Z_STRVAL(class_type->u.constant) = (char*)zend_new_interned_string(class_type->u.constant.value.str.val, class_type->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->class_name = class_type->u.constant.value.str.val; cur_arg_info->class_name_len = class_type->u.constant.value.str.len; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with a class type hint can only be NULL"); } } } } } } /* }}} */ int zend_do_begin_function_call(znode *function_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { zend_function *function; char *lcname; char *is_compound = memchr(Z_STRVAL(function_name->u.constant), '\\', Z_STRLEN(function_name->u.constant)); zend_resolve_non_class_name(function_name, check_namespace TSRMLS_CC); if (check_namespace && CG(current_namespace) && !is_compound) { /* We assume we call function from the current namespace if it is not prefixed. */ /* In run-time PHP will check for function with full name and internal function with short name */ zend_do_begin_dynamic_function_call(function_name, 1 TSRMLS_CC); return 1; } lcname = zend_str_tolower_dup(function_name->u.constant.value.str.val, function_name->u.constant.value.str.len); if ((zend_hash_find(CG(function_table), lcname, function_name->u.constant.value.str.len+1, (void **) &function)==FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_FUNCTIONS) && (function->type == ZEND_INTERNAL_FUNCTION))) { zend_do_begin_dynamic_function_call(function_name, 0 TSRMLS_CC); efree(lcname); return 1; /* Dynamic */ } efree(function_name->u.constant.value.str.val); function_name->u.constant.value.str.val = lcname; zend_stack_push(&CG(function_call_stack), (void *) &function, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 0; } /* }}} */ void zend_do_begin_method_call(znode *left_bracket TSRMLS_DC) /* {{{ */ { zend_op *last_op; int last_op_number; unsigned char *ptr = NULL; zend_do_end_variable_parse(left_bracket, BP_VAR_R, 0 TSRMLS_CC); zend_do_begin_variable_parse(TSRMLS_C); last_op_number = get_next_op_number(CG(active_op_array))-1; last_op = &CG(active_op_array)->opcodes[last_op_number]; if ((last_op->op2_type == IS_CONST) && (Z_TYPE(CONSTANT(last_op->op2.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(last_op->op2.constant)) == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !zend_binary_strcasecmp(Z_STRVAL(CONSTANT(last_op->op2.constant)), Z_STRLEN(CONSTANT(last_op->op2.constant)), ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1)) { zend_error(E_COMPILE_ERROR, "Cannot call __clone() method on objects - use 'clone $obj' instead"); } if (last_op->opcode == ZEND_FETCH_OBJ_R) { if (last_op->op2_type == IS_CONST) { zval name; name = CONSTANT(last_op->op2.constant); if (!IS_INTERNED(Z_STRVAL(name))) { Z_STRVAL(name) = estrndup(Z_STRVAL(name), Z_STRLEN(name)); } FREE_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); last_op->op2.constant = zend_add_func_name_literal(CG(active_op_array), &name TSRMLS_CC); GET_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); } last_op->opcode = ZEND_INIT_METHOD_CALL; SET_UNUSED(last_op->result); Z_LVAL(left_bracket->u.constant) = ZEND_INIT_FCALL_BY_NAME; } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (left_bracket->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &left_bracket->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, left_bracket); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_do_clone(znode *result, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CLONE; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_begin_dynamic_function_call(znode *function_name, int ns_call TSRMLS_DC) /* {{{ */ { unsigned char *ptr = NULL; zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (ns_call) { /* In run-time PHP will check for function with full name and internal function with short name */ opline->opcode = ZEND_INIT_NS_FCALL_BY_NAME; SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_ns_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (function_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, function_name); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_resolve_non_class_name(znode *element_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; int len; zval **ns; char *lcname, *compound = memchr(Z_STRVAL(element_name->u.constant), '\\', Z_STRLEN(element_name->u.constant)); if (Z_STRVAL(element_name->u.constant)[0] == '\\') { /* name starts with \ so it is known and unambiguos, nothing to do here but shorten it */ memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+1, Z_STRLEN(element_name->u.constant)); --Z_STRLEN(element_name->u.constant); return; } if(!check_namespace) { return; } if (compound && CG(current_import)) { len = compound - Z_STRVAL(element_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(element_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(element_name->u.constant) -= len; memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+len, Z_STRLEN(element_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, element_name TSRMLS_CC); *element_name = tmp; efree(lcname); return; } efree(lcname); } if (CG(current_namespace)) { tmp = *element_name; Z_STRLEN(tmp.u.constant) = sizeof("\\")-1 + Z_STRLEN(element_name->u.constant) + Z_STRLEN_P(CG(current_namespace)); Z_STRVAL(tmp.u.constant) = (char *) emalloc(Z_STRLEN(tmp.u.constant)+1); memcpy(Z_STRVAL(tmp.u.constant), Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace))]), "\\", sizeof("\\")-1); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace)) + sizeof("\\")-1]), Z_STRVAL(element_name->u.constant), Z_STRLEN(element_name->u.constant)+1); STR_FREE(Z_STRVAL(element_name->u.constant)); *element_name = tmp; } } /* }}} */ void zend_resolve_class_name(znode *class_name, ulong fetch_type, int check_ns_name TSRMLS_DC) /* {{{ */ { char *compound; char *lcname; zval **ns; znode tmp; int len; compound = memchr(Z_STRVAL(class_name->u.constant), '\\', Z_STRLEN(class_name->u.constant)); if (compound) { /* This is a compound class name that contains namespace prefix */ if (Z_STRVAL(class_name->u.constant)[0] == '\\') { /* The STRING name has "\" prefix */ Z_STRLEN(class_name->u.constant) -= 1; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+1, Z_STRLEN(class_name->u.constant)+1); Z_STRVAL(class_name->u.constant) = erealloc( Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1); if (ZEND_FETCH_CLASS_DEFAULT != zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "'\\%s' is an invalid class name", Z_STRVAL(class_name->u.constant)); } } else { if (CG(current_import)) { len = compound - Z_STRVAL(class_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(class_name->u.constant) -= len; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+len, Z_STRLEN(class_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; efree(lcname); return; } efree(lcname); } /* Here name is not prefixed with \ and not imported */ if (CG(current_namespace)) { tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } } } else if (CG(current_import) || CG(current_namespace)) { /* this is a plain name (without \) */ lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns) == SUCCESS) { /* The given name is an import name. Substitute it. */ zval_dtor(&class_name->u.constant); class_name->u.constant = **ns; zval_copy_ctor(&class_name->u.constant); } else if (CG(current_namespace)) { /* plain name, no import - prepend current namespace to it */ tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } efree(lcname); } } /* }}} */ void zend_do_fetch_class(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { long fetch_class_op_number; zend_op *opline; if (class_name->op_type == IS_CONST && Z_TYPE(class_name->u.constant) == IS_STRING && Z_STRLEN(class_name->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_name->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } fetch_class_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CLASS; SET_UNUSED(opline->op1); opline->extended_value = ZEND_FETCH_CLASS_GLOBAL; CG(catch_begin) = fetch_class_op_number; if (class_name->op_type == IS_CONST) { int fetch_type; fetch_type = zend_get_class_fetch_type(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); switch (fetch_type) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: SET_UNUSED(opline->op2); opline->extended_value = fetch_type; zval_dtor(&class_name->u.constant); break; default: zend_resolve_class_name(class_name, opline->extended_value, 0 TSRMLS_CC); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_name->u.constant TSRMLS_CC); break; } } else { SET_NODE(opline->op2, class_name); } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; /* FIXME: Hack so that INIT_FCALL_BY_NAME still knows this is a class */ GET_NODE(result, opline->result); result->EA = opline->extended_value; } /* }}} */ void zend_do_label(znode *label TSRMLS_DC) /* {{{ */ { zend_label dest; if (!CG(context).labels) { ALLOC_HASHTABLE(CG(context).labels); zend_hash_init(CG(context).labels, 4, NULL, NULL, 0); } dest.brk_cont = CG(context).current_brk_cont; dest.opline_num = get_next_op_number(CG(active_op_array)); if (zend_hash_add(CG(context).labels, Z_STRVAL(label->u.constant), Z_STRLEN(label->u.constant) + 1, (void**)&dest, sizeof(zend_label), NULL) == FAILURE) { zend_error(E_COMPILE_ERROR, "Label '%s' already defined", Z_STRVAL(label->u.constant)); } /* Done with label now */ zval_dtor(&label->u.constant); } /* }}} */ void zend_resolve_goto_label(zend_op_array *op_array, zend_op *opline, int pass2 TSRMLS_DC) /* {{{ */ { zend_label *dest; long current, distance; zval *label; if (pass2) { label = opline->op2.zv; } else { label = &CONSTANT_EX(op_array, opline->op2.constant); } if (CG(context).labels == NULL || zend_hash_find(CG(context).labels, Z_STRVAL_P(label), Z_STRLEN_P(label)+1, (void**)&dest) == FAILURE) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; zend_error(E_COMPILE_ERROR, "'goto' to undefined label '%s'", Z_STRVAL_P(label)); } else { /* Label is not defined. Delay to pass 2. */ INC_BPC(op_array); return; } } opline->op1.opline_num = dest->opline_num; zval_dtor(label); Z_TYPE_P(label) = IS_NULL; /* Check that we are not moving into loop or switch */ current = opline->extended_value; for (distance = 0; current != dest->brk_cont; distance++) { if (current == -1) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; } zend_error(E_COMPILE_ERROR, "'goto' into loop or switch statement is disallowed"); } current = op_array->brk_cont_array[current].parent; } if (distance == 0) { /* Nothing to break out of, optimize to ZEND_JMP */ opline->opcode = ZEND_JMP; opline->extended_value = 0; SET_UNUSED(opline->op2); } else { /* Set real break distance */ ZVAL_LONG(label, distance); } if (pass2) { DEC_BPC(op_array); } } /* }}} */ void zend_do_goto(const znode *label TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_GOTO; opline->extended_value = CG(context).current_brk_cont; SET_UNUSED(opline->op1); SET_NODE(opline->op2, label); zend_resolve_goto_label(CG(active_op_array), opline, 0 TSRMLS_CC); } /* }}} */ void zend_release_labels(TSRMLS_D) /* {{{ */ { if (CG(context).labels) { zend_hash_destroy(CG(context).labels); FREE_HASHTABLE(CG(context).labels); } if (!zend_stack_is_empty(&CG(context_stack))) { zend_compiler_context *ctx; zend_stack_top(&CG(context_stack), (void**)&ctx); CG(context) = *ctx; zend_stack_del_top(&CG(context_stack)); } } /* }}} */ void zend_do_build_full_name(znode *result, znode *prefix, znode *name, int is_class_member TSRMLS_DC) /* {{{ */ { zend_uint length; if (!result) { result = prefix; } else { *result = *prefix; } if (is_class_member) { length = sizeof("::")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "::", sizeof("::")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("::")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } else { length = sizeof("\\")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "\\", sizeof("\\")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("\\")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } } /* }}} */ int zend_do_begin_class_member_function_call(znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { znode class_node; unsigned char *ptr = NULL; zend_op *opline; if (method_name->op_type == IS_CONST) { char *lcname = zend_str_tolower_dup(Z_STRVAL(method_name->u.constant), Z_STRLEN(method_name->u.constant)); if ((sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == Z_STRLEN(method_name->u.constant) && memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == 0) { zval_dtor(&method_name->u.constant); method_name->op_type = IS_UNUSED; } efree(lcname); } if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; opline = get_next_op(CG(active_op_array) TSRMLS_CC); } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->extended_value = class_node.EA ; } opline->opcode = ZEND_INIT_STATIC_METHOD_CALL; if (class_node.op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, &class_node); } if (method_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &method_name->u.constant TSRMLS_CC); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } } else { SET_NODE(opline->op2, method_name); } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 1; /* Dynamic */ } /* }}} */ void zend_do_end_function_call(znode *function_name, znode *result, const znode *argument_list, int is_method, int is_dynamic_fcall TSRMLS_DC) /* {{{ */ { zend_op *opline; if (is_method && function_name && function_name->op_type == IS_UNUSED) { /* clone */ if (Z_LVAL(argument_list->u.constant) != 0) { zend_error(E_WARNING, "Clone method does not require arguments"); } opline = &CG(active_op_array)->opcodes[Z_LVAL(function_name->u.constant)]; } else { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (!is_method && !is_dynamic_fcall && function_name->op_type==IS_CONST) { opline->opcode = ZEND_DO_FCALL; SET_NODE(opline->op1, function_name); CALCULATE_LITERAL_HASH(opline->op1.constant); GET_CACHE_SLOT(opline->op1.constant); } else { opline->opcode = ZEND_DO_FCALL_BY_NAME; SET_UNUSED(opline->op1); } } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(result, opline->result) ; SET_UNUSED(opline->op2); zend_stack_del_top(&CG(function_call_stack)); opline->extended_value = Z_LVAL(argument_list->u.constant); } /* }}} */ void zend_do_pass_param(znode *param, zend_uchar op, int offset TSRMLS_DC) /* {{{ */ { zend_op *opline; int original_op=op; zend_function **function_ptr_ptr, *function_ptr; int send_by_reference; int send_function = 0; zend_stack_top(&CG(function_call_stack), (void **) &function_ptr_ptr); function_ptr = *function_ptr_ptr; if (original_op == ZEND_SEND_REF) { if (function_ptr && function_ptr->common.function_name && function_ptr->common.type == ZEND_USER_FUNCTION && !ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed; " "If you would like to pass argument by reference, modify the declaration of %s().", function_ptr->common.function_name); } else { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed"); } return; } if (function_ptr) { if (ARG_MAY_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { if (param->op_type & (IS_VAR|IS_CV) && original_op != ZEND_SEND_VAL) { send_by_reference = 1; if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION | ZEND_ARG_SEND_SILENT; } } else { op = ZEND_SEND_VAL; send_by_reference = 0; } } else { send_by_reference = ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset) ? ZEND_ARG_SEND_BY_REF : 0; } } else { send_by_reference = 0; } if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION; } else if (op == ZEND_SEND_VAL && (param->op_type & (IS_VAR|IS_CV))) { op = ZEND_SEND_VAR_NO_REF; } if (op!=ZEND_SEND_VAR_NO_REF && send_by_reference==ZEND_ARG_SEND_BY_REF) { /* change to passing by reference */ switch (param->op_type) { case IS_VAR: case IS_CV: op = ZEND_SEND_REF; break; default: zend_error(E_COMPILE_ERROR, "Only variables can be passed by reference"); break; } } if (original_op == ZEND_SEND_VAR) { switch (op) { case ZEND_SEND_VAR_NO_REF: zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); break; case ZEND_SEND_VAR: if (function_ptr) { zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(param, BP_VAR_FUNC_ARG, offset TSRMLS_CC); } break; case ZEND_SEND_REF: zend_do_end_variable_parse(param, BP_VAR_W, 0 TSRMLS_CC); break; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (op == ZEND_SEND_VAR_NO_REF) { if (function_ptr) { opline->extended_value = ZEND_ARG_COMPILE_TIME_BOUND | send_by_reference | send_function; } else { opline->extended_value = send_function; } } else { if (function_ptr) { opline->extended_value = ZEND_DO_FCALL; } else { opline->extended_value = ZEND_DO_FCALL_BY_NAME; } } opline->opcode = op; SET_NODE(opline->op1, param); opline->op2.opline_num = offset; SET_UNUSED(opline->op2); } /* }}} */ static int generate_free_switch_expr(const zend_switch_entry *switch_entry TSRMLS_DC) /* {{{ */ { zend_op *opline; if (switch_entry->cond.op_type != IS_VAR && switch_entry->cond.op_type != IS_TMP_VAR) { return (switch_entry->cond.op_type == IS_UNUSED); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry->cond); SET_UNUSED(opline->op2); opline->extended_value = 0; return 0; } /* }}} */ static int generate_free_foreach_copy(const zend_op *foreach_copy TSRMLS_DC) /* {{{ */ { zend_op *opline; /* If we reach the seperator then stop applying the stack */ if (foreach_copy->result_type == IS_UNUSED && foreach_copy->op1_type == IS_UNUSED) { return 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->result_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->result); SET_UNUSED(opline->op2); opline->extended_value = 1; if (foreach_copy->op1_type != IS_UNUSED) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->op1_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->op1); SET_UNUSED(opline->op2); opline->extended_value = 0; } return 0; } /* }}} */ void zend_do_return(znode *expr, int do_end_vparse TSRMLS_DC) /* {{{ */ { zend_op *opline; int start_op_number, end_op_number; if (do_end_vparse) { if ((CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) && !zend_is_function_or_method_call(expr)) { zend_do_end_variable_parse(expr, BP_VAR_W, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(expr, BP_VAR_R, 0 TSRMLS_CC); } } start_op_number = get_next_op_number(CG(active_op_array)); #ifdef ZTS zend_stack_apply_with_argument(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_switch_expr TSRMLS_CC); zend_stack_apply_with_argument(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_foreach_copy TSRMLS_CC); #else zend_stack_apply(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_switch_expr); zend_stack_apply(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_foreach_copy); #endif end_op_number = get_next_op_number(CG(active_op_array)); while (start_op_number < end_op_number) { CG(active_op_array)->opcodes[start_op_number].extended_value |= EXT_TYPE_FREE_ON_RETURN; start_op_number++; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) ? ZEND_RETURN_BY_REF : ZEND_RETURN; if (expr) { SET_NODE(opline->op1, expr); if (do_end_vparse && zend_is_function_or_method_call(expr)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } } else { opline->op1_type = IS_CONST; LITERAL_NULL(opline->op1); } SET_UNUSED(opline->op2); } /* }}} */ static int zend_add_try_element(zend_uint try_op TSRMLS_DC) /* {{{ */ { int try_catch_offset = CG(active_op_array)->last_try_catch++; CG(active_op_array)->try_catch_array = erealloc(CG(active_op_array)->try_catch_array, sizeof(zend_try_catch_element)*CG(active_op_array)->last_try_catch); CG(active_op_array)->try_catch_array[try_catch_offset].try_op = try_op; return try_catch_offset; } /* }}} */ static void zend_add_catch_element(int offset, zend_uint catch_op TSRMLS_DC) /* {{{ */ { CG(active_op_array)->try_catch_array[offset].catch_op = catch_op; } /* }}} */ void zend_do_first_catch(znode *open_parentheses TSRMLS_DC) /* {{{ */ { open_parentheses->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_initialize_try_catch_element(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist jmp_list; zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); zend_add_catch_element(try_token->u.op.opline_num, get_next_op_number(CG(active_op_array)) TSRMLS_CC); } /* }}} */ void zend_do_mark_last_catch(const znode *first_catch, const znode *last_additional_catch TSRMLS_DC) /* {{{ */ { CG(active_op_array)->last--; zend_do_if_end(TSRMLS_C); if (last_additional_catch->u.op.opline_num == -1) { CG(active_op_array)->opcodes[first_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[first_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } else { CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_try(znode *try_token TSRMLS_DC) /* {{{ */ { try_token->u.op.opline_num = zend_add_try_element(get_next_op_number(CG(active_op_array)) TSRMLS_CC); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_catch(znode *try_token, znode *class_name, znode *catch_var, znode *first_catch TSRMLS_DC) /* {{{ */ { long catch_op_number; zend_op *opline; znode catch_class; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); catch_class = *class_name; } else { zend_error(E_COMPILE_ERROR, "Bad class name in the catch statement"); } catch_op_number = get_next_op_number(CG(active_op_array)); if (first_catch) { first_catch->u.op.opline_num = catch_op_number; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CATCH; opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &catch_class.u.constant TSRMLS_CC); opline->op2_type = IS_CV; opline->op2.var = lookup_cv(CG(active_op_array), catch_var->u.constant.value.str.val, catch_var->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(catch_var->u.constant) = (char*)CG(active_op_array)->vars[opline->op2.var].name; opline->result.num = 0; /* 1 means it's the last catch in the block */ try_token->u.op.opline_num = catch_op_number; } /* }}} */ void zend_do_end_catch(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); CG(active_op_array)->opcodes[try_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_throw(const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_THROW; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); } /* }}} */ ZEND_API void function_add_ref(zend_function *function) /* {{{ */ { if (function->type == ZEND_USER_FUNCTION) { zend_op_array *op_array = &function->op_array; (*op_array->refcount)++; if (op_array->static_variables) { HashTable *static_variables = op_array->static_variables; zval *tmp_zval; ALLOC_HASHTABLE(op_array->static_variables); zend_hash_init(op_array->static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(op_array->static_variables, static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_zval, sizeof(zval *)); } op_array->run_time_cache = NULL; } } /* }}} */ static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */ { zend_function *function; if (!ce->parent) { return; } /* You cannot change create_object */ ce->create_object = ce->parent->create_object; /* Inherit special functions if needed */ if (!ce->get_iterator) { ce->get_iterator = ce->parent->get_iterator; } if (!ce->iterator_funcs.funcs) { ce->iterator_funcs.funcs = ce->parent->iterator_funcs.funcs; } if (!ce->__get) { ce->__get = ce->parent->__get; } if (!ce->__set) { ce->__set = ce->parent->__set; } if (!ce->__unset) { ce->__unset = ce->parent->__unset; } if (!ce->__isset) { ce->__isset = ce->parent->__isset; } if (!ce->__call) { ce->__call = ce->parent->__call; } if (!ce->__callstatic) { ce->__callstatic = ce->parent->__callstatic; } if (!ce->__tostring) { ce->__tostring = ce->parent->__tostring; } if (!ce->clone) { ce->clone = ce->parent->clone; } if(!ce->serialize) { ce->serialize = ce->parent->serialize; } if(!ce->unserialize) { ce->unserialize = ce->parent->unserialize; } if (!ce->destructor) { ce->destructor = ce->parent->destructor; } if (ce->constructor) { if (ce->parent->constructor && ce->parent->constructor->common.fn_flags & ZEND_ACC_FINAL) { zend_error(E_ERROR, "Cannot override final %s::%s() with %s::%s()", ce->parent->name, ce->parent->constructor->common.function_name, ce->name, ce->constructor->common.function_name ); } return; } if (zend_hash_find(&ce->parent->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), (void **)&function)==SUCCESS) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), function, sizeof(zend_function), NULL); function_add_ref(function); } else { /* Don't inherit the old style constructor if we already have the new style constructor */ char *lc_class_name; char *lc_parent_class_name; lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); if (!zend_hash_exists(&ce->function_table, lc_class_name, ce->name_length+1)) { lc_parent_class_name = zend_str_tolower_dup(ce->parent->name, ce->parent->name_length); if (!zend_hash_exists(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1) && zend_hash_find(&ce->parent->function_table, lc_parent_class_name, ce->parent->name_length+1, (void **)&function)==SUCCESS) { if (function->common.fn_flags & ZEND_ACC_CTOR) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1, function, sizeof(zend_function), NULL); function_add_ref(function); } } efree(lc_parent_class_name); } efree(lc_class_name); } ce->constructor = ce->parent->constructor; } /* }}} */ char *zend_visibility_string(zend_uint fn_flags) /* {{{ */ { if (fn_flags & ZEND_ACC_PRIVATE) { return "private"; } if (fn_flags & ZEND_ACC_PROTECTED) { return "protected"; } if (fn_flags & ZEND_ACC_PUBLIC) { return "public"; } return ""; } /* }}} */ static void do_inherit_method(zend_function *function) /* {{{ */ { /* The class entry of the derived function intentionally remains the same * as that of the parent class. That allows us to know in which context * we're running, and handle private method calls properly. */ function_add_ref(function); } /* }}} */ static zend_bool zend_do_perform_implementation_check(const zend_function *fe, const zend_function *proto TSRMLS_DC) /* {{{ */ { zend_uint i; /* If it's a user function then arg_info == NULL means we don't have any parameters but * we still need to do the arg number checks. We are only willing to ignore this for internal * functions because extensions don't always define arg_info. */ if (!proto || (!proto->common.arg_info && proto->common.type != ZEND_USER_FUNCTION)) { return 1; } /* Checks for constructors only if they are declared in an interface, * or explicitly marked as abstract */ if ((fe->common.fn_flags & ZEND_ACC_CTOR) && ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)) { return 1; } /* check number of arguments */ if (proto->common.required_num_args < fe->common.required_num_args || proto->common.num_args > fe->common.num_args) { return 0; } if (fe->common.type != ZEND_USER_FUNCTION && (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) != 0 && (fe->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) == 0) { return 0; } /* by-ref constraints on return values are covariant */ if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) { return 0; } for (i=0; i < proto->common.num_args; i++) { if (ZEND_LOG_XOR(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)) { /* Only one has a type hint and the other one doesn't */ return 0; } if (fe->common.arg_info[i].class_name && strcasecmp(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)!=0) { const char *colon; if (fe->common.type != ZEND_USER_FUNCTION) { return 0; } else if (strchr(proto->common.arg_info[i].class_name, '\\') != NULL || (colon = zend_memrchr(fe->common.arg_info[i].class_name, '\\', fe->common.arg_info[i].class_name_len)) == NULL || strcasecmp(colon+1, proto->common.arg_info[i].class_name) != 0) { zend_class_entry **fe_ce, **proto_ce; int found, found2; found = zend_lookup_class(fe->common.arg_info[i].class_name, fe->common.arg_info[i].class_name_len, &fe_ce TSRMLS_CC); found2 = zend_lookup_class(proto->common.arg_info[i].class_name, proto->common.arg_info[i].class_name_len, &proto_ce TSRMLS_CC); /* Check for class alias */ if (found != SUCCESS || found2 != SUCCESS || (*fe_ce)->type == ZEND_INTERNAL_CLASS || (*proto_ce)->type == ZEND_INTERNAL_CLASS || *fe_ce != *proto_ce) { return 0; } } } if (fe->common.arg_info[i].type_hint != proto->common.arg_info[i].type_hint) { /* Incompatible type hint */ return 0; } /* by-ref constraints on arguments are invariant */ if (fe->common.arg_info[i].pass_by_reference != proto->common.arg_info[i].pass_by_reference) { return 0; } } if (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) { for (i=proto->common.num_args; i < fe->common.num_args; i++) { if (!fe->common.arg_info[i].pass_by_reference) { return 0; } } } return 1; } /* }}} */ #define REALLOC_BUF_IF_EXCEED(buf, offset, length, size) \ if (UNEXPECTED(offset - buf + size >= length)) { \ length += size + 1; \ buf = erealloc(buf, length); \ } static char * zend_get_function_declaration(zend_function *fptr TSRMLS_DC) /* {{{ */ { char *offset, *buf; zend_uint length = 1024; offset = buf = (char *)emalloc(length * sizeof(char)); if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { *(offset++) = '&'; *(offset++) = ' '; } if (fptr->common.scope) { memcpy(offset, fptr->common.scope->name, fptr->common.scope->name_length); offset += fptr->common.scope->name_length; *(offset++) = ':'; *(offset++) = ':'; } { size_t name_len = strlen(fptr->common.function_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, name_len); memcpy(offset, fptr->common.function_name, name_len); offset += name_len; } *(offset++) = '('; if (fptr->common.arg_info) { zend_uint i, required; zend_arg_info *arg_info = fptr->common.arg_info; required = fptr->common.required_num_args; for (i = 0; i < fptr->common.num_args;) { if (arg_info->class_name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->class_name_len); memcpy(offset, arg_info->class_name, arg_info->class_name_len); offset += arg_info->class_name_len; *(offset++) = ' '; } else if (arg_info->type_hint) { zend_uint type_name_len; char *type_name = zend_get_type_by_const(arg_info->type_hint); type_name_len = strlen(type_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, type_name_len); memcpy(offset, type_name, type_name_len); offset += type_name_len; *(offset++) = ' '; } if (arg_info->pass_by_reference) { *(offset++) = '&'; } *(offset++) = '$'; if (arg_info->name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->name_len); memcpy(offset, arg_info->name, arg_info->name_len); offset += arg_info->name_len; } else { zend_uint idx = i; memcpy(offset, "param", 5); offset += 5; do { *(offset++) = (char) (idx % 10) + '0'; idx /= 10; } while (idx > 0); } if (i >= required) { *(offset++) = ' '; *(offset++) = '='; *(offset++) = ' '; if (fptr->type == ZEND_USER_FUNCTION) { zend_op *precv = NULL; { zend_uint idx = i; zend_op *op = ((zend_op_array *)fptr)->opcodes; zend_op *end = op + ((zend_op_array *)fptr)->last; ++idx; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT) && op->op1.num == (long)idx) { precv = op; } ++op; } } if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) { zval *zv, zv_copy; int use_copy; ALLOC_ZVAL(zv); *zv = *precv->op2.zv; zval_copy_ctor(zv); INIT_PZVAL(zv); zval_update_constant_ex(&zv, (void*)1, fptr->common.scope TSRMLS_CC); if (Z_TYPE_P(zv) == IS_BOOL) { if (Z_LVAL_P(zv)) { memcpy(offset, "true", 4); offset += 4; } else { memcpy(offset, "false", 5); offset += 5; } } else if (Z_TYPE_P(zv) == IS_NULL) { memcpy(offset, "NULL", 4); offset += 4; } else if (Z_TYPE_P(zv) == IS_STRING) { *(offset++) = '\''; REALLOC_BUF_IF_EXCEED(buf, offset, length, MIN(Z_STRLEN_P(zv), 10)); memcpy(offset, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 10)); offset += MIN(Z_STRLEN_P(zv), 10); if (Z_STRLEN_P(zv) > 10) { *(offset++) = '.'; *(offset++) = '.'; *(offset++) = '.'; } *(offset++) = '\''; } else if (Z_TYPE_P(zv) == IS_ARRAY) { memcpy(offset, "Array", 5); offset += 5; } else { zend_make_printable_zval(zv, &zv_copy, &use_copy); REALLOC_BUF_IF_EXCEED(buf, offset, length, Z_STRLEN(zv_copy)); memcpy(offset, Z_STRVAL(zv_copy), Z_STRLEN(zv_copy)); offset += Z_STRLEN(zv_copy); if (use_copy) { zval_dtor(&zv_copy); } } zval_ptr_dtor(&zv); } } else { memcpy(offset, "NULL", 4); offset += 4; } } if (++i < fptr->common.num_args) { *(offset++) = ','; *(offset++) = ' '; } arg_info++; REALLOC_BUF_IF_EXCEED(buf, offset, length, 32); } } *(offset++) = ')'; *offset = '\0'; return buf; } /* }}} */ static void do_inheritance_check_on_method(zend_function *child, zend_function *parent TSRMLS_DC) /* {{{ */ { zend_uint child_flags; zend_uint parent_flags = parent->common.fn_flags; if (parent->common.fn_flags & ZEND_ACC_ABSTRACT && parent->common.scope != (child->common.prototype ? child->common.prototype->common.scope : child->common.scope) && child->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_IMPLEMENTED_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Can't inherit abstract function %s::%s() (previously declared abstract in %s)", parent->common.scope->name, child->common.function_name, child->common.prototype ? child->common.prototype->common.scope->name : child->common.scope->name); } if (parent_flags & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot override final method %s::%s()", ZEND_FN_SCOPE_NAME(parent), child->common.function_name); } child_flags = child->common.fn_flags; /* You cannot change from static to non static and vice versa. */ if ((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC)) { if (child->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot make non static method %s::%s() static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } else { zend_error(E_COMPILE_ERROR, "Cannot make static method %s::%s() non static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } } /* Disallow making an inherited method abstract. */ if ((child_flags & ZEND_ACC_ABSTRACT) && !(parent_flags & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Cannot make non abstract method %s::%s() abstract in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } if (parent_flags & ZEND_ACC_CHANGED) { child->common.fn_flags |= ZEND_ACC_CHANGED; } else { /* Prevent derived classes from restricting access that was available in parent classes */ if ((child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::%s() must be %s (as in class %s)%s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if (((child_flags & ZEND_ACC_PPP_MASK) < (parent_flags & ZEND_ACC_PPP_MASK)) && ((parent_flags & ZEND_ACC_PPP_MASK) & ZEND_ACC_PRIVATE)) { child->common.fn_flags |= ZEND_ACC_CHANGED; } } if (parent_flags & ZEND_ACC_PRIVATE) { child->common.prototype = NULL; } else if (parent_flags & ZEND_ACC_ABSTRACT) { child->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; child->common.prototype = parent; } else if (!(parent->common.fn_flags & ZEND_ACC_CTOR) || (parent->common.prototype && (parent->common.prototype->common.scope->ce_flags & ZEND_ACC_INTERFACE))) { /* ctors only have a prototype if it comes from an interface */ child->common.prototype = parent->common.prototype ? parent->common.prototype : parent; } if (child->common.prototype && (child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { if (!zend_do_perform_implementation_check(child, child->common.prototype TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s::%s() must be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_get_function_declaration(child->common.prototype TSRMLS_CC)); } } else if (EG(error_reporting) & E_STRICT || EG(user_error_handler)) { /* Check E_STRICT (or custom error handler) before the check so that we save some time */ if (!zend_do_perform_implementation_check(child, parent TSRMLS_CC)) { char *method_prototype = zend_get_function_declaration(child->common.prototype TSRMLS_CC); zend_error(E_STRICT, "Declaration of %s::%s() should be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, method_prototype); efree(method_prototype); } } } /* }}} */ static zend_bool do_inherit_method_check(HashTable *child_function_table, zend_function *parent, const zend_hash_key *hash_key, zend_class_entry *child_ce) /* {{{ */ { zend_uint parent_flags = parent->common.fn_flags; zend_function *child; TSRMLS_FETCH(); if (zend_hash_quick_find(child_function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child)==FAILURE) { if (parent_flags & (ZEND_ACC_ABSTRACT)) { child_ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } return 1; /* method doesn't exist in child, copy from parent */ } do_inheritance_check_on_method(child, parent TSRMLS_CC); return 0; } /* }}} */ static zend_bool do_inherit_property_access_check(HashTable *target_ht, zend_property_info *parent_info, const zend_hash_key *hash_key, zend_class_entry *ce) /* {{{ */ { zend_property_info *child_info; zend_class_entry *parent_ce = ce->parent; if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW)) { if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { child_info->flags |= ZEND_ACC_CHANGED; } else { zend_hash_quick_update(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, parent_info, sizeof(zend_property_info), (void **) &child_info); if(ce->type & ZEND_INTERNAL_CLASS) { zend_duplicate_property_info_internal(child_info); } else { zend_duplicate_property_info(child_info); } child_info->flags &= ~ZEND_ACC_PRIVATE; /* it's not private anymore */ child_info->flags |= ZEND_ACC_SHADOW; /* but it's a shadow of private */ } return 0; /* don't copy access information to child */ } if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { if ((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s", (parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", parent_ce->name, hash_key->arKey, (child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ce->name, hash_key->arKey); } if(parent_info->flags & ZEND_ACC_CHANGED) { child_info->flags |= ZEND_ACC_CHANGED; } if ((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ce->name, hash_key->arKey, zend_visibility_string(parent_info->flags), parent_ce->name, (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if ((child_info->flags & ZEND_ACC_STATIC) == 0) { Z_DELREF_P(ce->default_properties_table[parent_info->offset]); ce->default_properties_table[parent_info->offset] = ce->default_properties_table[child_info->offset]; ce->default_properties_table[child_info->offset] = NULL; child_info->offset = parent_info->offset; } return 0; /* Don't copy from parent */ } else { return 1; /* Copy from parent */ } } /* }}} */ static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce TSRMLS_CC) == FAILURE) { zend_error(E_CORE_ERROR, "Class %s could not implement interface %s", ce->name, iface->name); } if (ce == iface) { zend_error(E_ERROR, "Interface %s cannot implement itself", ce->name); } } /* }}} */ ZEND_API void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface TSRMLS_DC) /* {{{ */ { /* expects interface to be contained in ce's interface list already */ zend_uint i, ce_num, if_num = iface->num_interfaces; zend_class_entry *entry; if (if_num==0) { return; } ce_num = ce->num_interfaces; if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } /* Inherit the interfaces, only if they're not already inherited by the class */ while (if_num--) { entry = iface->interfaces[if_num]; for (i = 0; i < ce_num; i++) { if (ce->interfaces[i] == entry) { break; } } if (i == ce_num) { ce->interfaces[ce->num_interfaces++] = entry; } } /* and now call the implementing handlers */ while (ce_num < ce->num_interfaces) { do_implement_interface(ce, ce->interfaces[ce_num++] TSRMLS_CC); } } /* }}} */ #ifdef ZTS static void zval_internal_ctor(zval **p) /* {{{ */ { zval *orig_ptr = *p; ALLOC_ZVAL(*p); MAKE_COPY_ZVAL(&orig_ptr, *p); } /* }}} */ # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) (((parent_ce)->type != (ce)->type) ? zval_internal_ctor : zval_add_ref)) #else # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) zval_add_ref) #endif ZEND_API void zend_do_inheritance(zend_class_entry *ce, zend_class_entry *parent_ce TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; if ((ce->ce_flags & ZEND_ACC_INTERFACE) && !(parent_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ce->name, parent_ce->name); } if (parent_ce->ce_flags & ZEND_ACC_FINAL_CLASS) { zend_error(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ce->name, parent_ce->name); } ce->parent = parent_ce; /* Copy serialize/unserialize callbacks */ if (!ce->serialize) { ce->serialize = parent_ce->serialize; } if (!ce->unserialize) { ce->unserialize = parent_ce->unserialize; } /* Inherit interfaces */ zend_do_inherit_interfaces(ce, parent_ce TSRMLS_CC); /* Inherit properties */ if (parent_ce->default_properties_count) { int i = ce->default_properties_count + parent_ce->default_properties_count; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_properties_count) { while (i-- > parent_ce->default_properties_count) { ce->default_properties_table[i] = ce->default_properties_table[i - parent_ce->default_properties_count]; } } for (i = 0; i < parent_ce->default_properties_count; i++) { ce->default_properties_table[i] = parent_ce->default_properties_table[i]; if (ce->default_properties_table[i]) { #ifdef ZTS if (parent_ce->type != ce->type) { zval *p; ALLOC_ZVAL(p); MAKE_COPY_ZVAL(&ce->default_properties_table[i], p); ce->default_properties_table[i] = p; } else { Z_ADDREF_P(ce->default_properties_table[i]); } #else Z_ADDREF_P(ce->default_properties_table[i]); #endif } } ce->default_properties_count += parent_ce->default_properties_count; } if (parent_ce->type != ce->type) { /* User class extends internal class */ zend_update_class_constants(parent_ce TSRMLS_CC); if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = erealloc(ce->default_static_members_table, sizeof(void*) * i); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&CE_STATIC_MEMBERS(parent_ce)[i]); ce->default_static_members_table[i] = CE_STATIC_MEMBERS(parent_ce)[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; ce->static_members_table = ce->default_static_members_table; } } else { if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&parent_ce->default_static_members_table[i]); ce->default_static_members_table[i] = parent_ce->default_static_members_table[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } } for (zend_hash_internal_pointer_reset(&ce->properties_info); zend_hash_get_current_data(&ce->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->properties_info)) { if (property_info->ce == ce) { if (property_info->flags & ZEND_ACC_STATIC) { property_info->offset += parent_ce->default_static_members_count; } else { property_info->offset += parent_ce->default_properties_count; } } } zend_hash_merge_ex(&ce->properties_info, &parent_ce->properties_info, (copy_ctor_func_t) (ce->type & ZEND_INTERNAL_CLASS ? zend_duplicate_property_info_internal : zend_duplicate_property_info), sizeof(zend_property_info), (merge_checker_func_t) do_inherit_property_access_check, ce); zend_hash_merge(&ce->constants_table, &parent_ce->constants_table, zval_property_ctor(parent_ce, ce), NULL, sizeof(zval *), 0); zend_hash_merge_ex(&ce->function_table, &parent_ce->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_inherit_parent_constructor(ce); if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS && ce->type == ZEND_INTERNAL_CLASS) { ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } else if (!(ce->ce_flags & ZEND_ACC_IMPLEMENT_INTERFACES) && !(ce->ce_flags & ZEND_ACC_IMPLEMENT_TRAITS)) { /* The verification will be done in runtime by ZEND_VERIFY_ABSTRACT_CLASS */ zend_verify_abstract_class(ce TSRMLS_CC); } ce->ce_flags |= parent_ce->ce_flags & ZEND_HAS_STATIC_IN_METHODS; } /* }}} */ static zend_bool do_inherit_constant_check(HashTable *child_constants_table, const zval **parent_constant, const zend_hash_key *hash_key, const zend_class_entry *iface) /* {{{ */ { zval **old_constant; if (zend_hash_quick_find(child_constants_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**)&old_constant) == SUCCESS) { if (*old_constant != *parent_constant) { zend_error(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", hash_key->arKey, iface->name); } return 0; } return 1; } /* }}} */ static int do_interface_constant_check(zval **val TSRMLS_DC, int num_args, va_list args, const zend_hash_key *key) /* {{{ */ { zend_class_entry **iface = va_arg(args, zend_class_entry**); do_inherit_constant_check(&(*iface)->constants_table, (const zval **) val, key, *iface); return ZEND_HASH_APPLY_KEEP; } /* }}} */ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_iface_num = ce->num_interfaces; zend_uint parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0; for (i = 0; i < ce->num_interfaces; i++) { if (ce->interfaces[i] == NULL) { memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i)); i--; } else if (ce->interfaces[i] == iface) { if (i < parent_iface_num) { ignore = 1; } else { zend_error(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ce->name, iface->name); } } } if (ignore) { /* Check for attempt to redeclare interface constants */ zend_hash_apply_with_arguments(&ce->constants_table TSRMLS_CC, (apply_func_args_t) do_interface_constant_check, 1, &iface); } else { if (ce->num_interfaces >= current_iface_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } } ce->interfaces[ce->num_interfaces++] = iface; zend_hash_merge_ex(&ce->constants_table, &iface->constants_table, (copy_ctor_func_t) zval_add_ref, sizeof(zval *), (merge_checker_func_t) do_inherit_constant_check, iface); zend_hash_merge_ex(&ce->function_table, &iface->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_implement_interface(ce, iface TSRMLS_CC); zend_do_inherit_interfaces(ce, iface TSRMLS_CC); } } /* }}} */ ZEND_API void zend_do_implement_trait(zend_class_entry *ce, zend_class_entry *trait TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_trait_num = ce->num_traits; zend_uint parent_trait_num = ce->parent ? ce->parent->num_traits : 0; for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == NULL) { memmove(ce->traits + i, ce->traits + i + 1, sizeof(zend_class_entry*) * (--ce->num_traits - i)); i--; } else if (ce->traits[i] == trait) { if (i < parent_trait_num) { ignore = 1; } } } if (!ignore) { if (ce->num_traits >= current_trait_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->traits = (zend_class_entry **) realloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } else { ce->traits = (zend_class_entry **) erealloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } } ce->traits[ce->num_traits++] = trait; } } /* }}} */ static int zend_traits_merge_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { size_t current; size_t i; size_t count; HashTable* resulting_table; HashTable** function_tables; zend_class_entry *ce; size_t collision = 0; size_t abstract_solved = 0; zend_function* other_trait_fn; current = va_arg(args, size_t); /* index of current trait */ count = va_arg(args, size_t); resulting_table = va_arg(args, HashTable*); function_tables = va_arg(args, HashTable**); ce = va_arg(args, zend_class_entry*); for (i = 0; i < count; i++) { if (i == current) { continue; /* just skip this, cause its the table this function is applied on */ } if (zend_hash_quick_find(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&other_trait_fn) == SUCCESS) { /* if it is an abstract method, there is no collision */ if (other_trait_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* we can savely free and remove it from other table */ zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } else { /* if it is not an abstract method, there is still no collision */ /* if fn is an abstract method */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* just mark as solved, will be added if its own trait is processed */ abstract_solved = 1; } else { /* but else, we have a collision of non-abstract methods */ collision++; zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } } } if (collision) { zend_function* class_fn; /* make sure method is not already overridden in class */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&class_fn) == FAILURE || class_fn->common.scope != ce) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because there are collisions with other trait methods on %s", fn->common.function_name, ce->name); } zend_function_dtor(fn); } else if (abstract_solved) { zend_function_dtor(fn); } else { /* Add it to result function table */ if (zend_hash_quick_add(resulting_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, fn, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating resulting trait method table", fn->common.function_name); } } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ /* {{{ Originates from php_runkit_function_copy_ctor Duplicate structures in an op_array where necessary to make an outright duplicate */ static void zend_traits_duplicate_function(zend_function *fe, zend_class_entry *target_ce, char *newname TSRMLS_DC) { zend_literal *literals_copy; zend_compiled_variable *dupvars; zend_op *opcode_copy; zval class_name_zv; int class_name_literal; int i; int number_of_literals; if (fe->op_array.static_variables) { HashTable *tmpHash; ALLOC_HASHTABLE(tmpHash); zend_hash_init(tmpHash, zend_hash_num_elements(fe->op_array.static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_apply_with_arguments(fe->op_array.static_variables TSRMLS_CC, (apply_func_args_t)zval_copy_static_var, 1, tmpHash); fe->op_array.static_variables = tmpHash; } number_of_literals = fe->op_array.last_literal; literals_copy = (zend_literal*)emalloc(number_of_literals * sizeof(zend_literal)); for (i = 0; i < number_of_literals; i++) { literals_copy[i] = fe->op_array.literals[i]; zval_copy_ctor(&literals_copy[i].constant); } fe->op_array.literals = literals_copy; fe->op_array.refcount = emalloc(sizeof(zend_uint)); *(fe->op_array.refcount) = 1; if (fe->op_array.vars) { i = fe->op_array.last_var; dupvars = safe_emalloc(fe->op_array.last_var, sizeof(zend_compiled_variable), 0); while (i > 0) { i--; dupvars[i].name = estrndup(fe->op_array.vars[i].name, fe->op_array.vars[i].name_len); dupvars[i].name_len = fe->op_array.vars[i].name_len; dupvars[i].hash_value = fe->op_array.vars[i].hash_value; } fe->op_array.vars = dupvars; } else { fe->op_array.vars = NULL; } opcode_copy = safe_emalloc(sizeof(zend_op), fe->op_array.last, 0); for(i = 0; i < fe->op_array.last; i++) { opcode_copy[i] = fe->op_array.opcodes[i]; if (opcode_copy[i].op1_type != IS_CONST) { if (opcode_copy[i].op1.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op1.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op1.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op1.jmp_addr - fe->op_array.opcodes); } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op1.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op1.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op1.zv = &fe->op_array.literals[class_name_literal].constant; } } if (opcode_copy[i].op2_type != IS_CONST) { if (opcode_copy[i].op2.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op2.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op2.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op2.jmp_addr - fe->op_array.opcodes); } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op2.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op2.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op2.zv = &fe->op_array.literals[class_name_literal].constant; } } } fe->op_array.opcodes = opcode_copy; fe->op_array.function_name = newname; /* was setting it to fe which does not work since fe is stack allocated and not a stable address */ /* fe->op_array.prototype = fe->op_array.prototype; */ if (fe->op_array.arg_info) { zend_arg_info *tmpArginfo; tmpArginfo = safe_emalloc(sizeof(zend_arg_info), fe->op_array.num_args, 0); for(i = 0; i < fe->op_array.num_args; i++) { tmpArginfo[i] = fe->op_array.arg_info[i]; tmpArginfo[i].name = estrndup(tmpArginfo[i].name, tmpArginfo[i].name_len); if (tmpArginfo[i].class_name) { tmpArginfo[i].class_name = estrndup(tmpArginfo[i].class_name, tmpArginfo[i].class_name_len); } } fe->op_array.arg_info = tmpArginfo; } fe->op_array.doc_comment = estrndup(fe->op_array.doc_comment, fe->op_array.doc_comment_len); fe->op_array.try_catch_array = (zend_try_catch_element*)estrndup((char*)fe->op_array.try_catch_array, sizeof(zend_try_catch_element) * fe->op_array.last_try_catch); fe->op_array.brk_cont_array = (zend_brk_cont_element*)estrndup((char*)fe->op_array.brk_cont_array, sizeof(zend_brk_cont_element) * fe->op_array.last_brk_cont); } /* }}} */ static void zend_add_magic_methods(zend_class_entry* ce, const char* mname, uint mname_len, zend_function* fe TSRMLS_DC) { if ( !strncmp(mname, ZEND_CLONE_FUNC_NAME, mname_len)) { ce->clone = fe; fe->common.fn_flags |= ZEND_ACC_CLONE; } else if (!strncmp(mname, ZEND_CONSTRUCTOR_FUNC_NAME, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } else if (!strncmp(mname, ZEND_DESTRUCTOR_FUNC_NAME, mname_len)) { ce->destructor = fe; fe->common.fn_flags |= ZEND_ACC_DTOR; } else if (!strncmp(mname, ZEND_GET_FUNC_NAME, mname_len)) ce->__get = fe; else if (!strncmp(mname, ZEND_SET_FUNC_NAME, mname_len)) ce->__set = fe; else if (!strncmp(mname, ZEND_CALL_FUNC_NAME, mname_len)) ce->__call = fe; else if (!strncmp(mname, ZEND_UNSET_FUNC_NAME, mname_len)) ce->__unset = fe; else if (!strncmp(mname, ZEND_ISSET_FUNC_NAME, mname_len)) ce->__isset = fe; else if (!strncmp(mname, ZEND_CALLSTATIC_FUNC_NAME, mname_len)) ce->__callstatic= fe; else if (!strncmp(mname, ZEND_TOSTRING_FUNC_NAME, mname_len)) ce->__tostring = fe; else if (ce->name_length + 1 == mname_len) { char *lowercase_name = emalloc(ce->name_length + 1); zend_str_tolower_copy(lowercase_name, ce->name, ce->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, ce->name_length + 1, 1 TSRMLS_CC); if (!memcmp(mname, lowercase_name, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } str_efree(lowercase_name); } } static int zend_traits_merge_functions_to_class(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zend_class_entry *ce = va_arg(args, zend_class_entry*); int add = 0; zend_function* existing_fn; zend_function fn_copy, *fn_copy_p; zend_function* prototype = NULL; /* is used to determine the prototype according to the inheritance chain */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &existing_fn) == FAILURE) { add = 1; /* not found */ } else if (existing_fn->common.scope != ce) { add = 1; /* or inherited from other class or interface */ /* it is just a reference which was added to the subclass while doing the inheritance */ /* so we can deleted now, and will add the overriding method afterwards */ /* except, if we try to add an abstract function, then we should not delete the inherited one */ /* delete inherited fn if the function to be added is not abstract */ if ((fn->common.fn_flags & ZEND_ACC_ABSTRACT) == 0) { zend_hash_quick_del(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } if (add) { zend_function* parent_function; if (ce->parent && zend_hash_quick_find(&ce->parent->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &parent_function) != FAILURE) { prototype = parent_function; /* ->common.fn_flags |= ZEND_ACC_ABSTRACT; */ /* we got that method in the parent class, and are going to override it, except, if the trait is just asking to have an abstract method implemented. */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* then we clean up an skip this method */ zend_function_dtor(fn); return ZEND_HASH_APPLY_REMOVE; } } fn->common.scope = ce; fn->common.prototype = prototype; if (prototype && (prototype->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT || prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { fn->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; } else if (fn->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT) { /* remove ZEND_ACC_IMPLEMENTED_ABSTRACT flag, think it shouldn't be copied to class */ fn->common.fn_flags = fn->common.fn_flags - ZEND_ACC_IMPLEMENTED_ABSTRACT; } /* check whether the trait method fullfills the inheritance requirements */ if (prototype) { do_inheritance_check_on_method(fn, prototype TSRMLS_CC); } if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (fn->op_array.static_variables) { ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, ce, estrdup(fn->common.function_name) TSRMLS_CC); if (zend_hash_quick_update(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, &fn_copy, sizeof(zend_function), (void**)&fn_copy_p)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating class method table", hash_key->arKey); } zend_add_magic_methods(ce, hash_key->arKey, hash_key->nKeyLength, fn_copy_p TSRMLS_CC); zend_function_dtor(fn); } else { zend_function_dtor(fn); } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ static int zend_traits_copy_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { HashTable* target; zend_class_entry *target_ce; zend_trait_alias** aliases; HashTable* exclude_table; char* lcname; unsigned int fnname_len; zend_function fn_copy; void* dummy; size_t i = 0; target = va_arg(args, HashTable*); target_ce = va_arg(args, zend_class_entry*); aliases = va_arg(args, zend_trait_alias**); exclude_table = va_arg(args, HashTable*); fnname_len = strlen(fn->common.function_name); /* apply aliases which are qualified with a class name, there should not be any ambiguity */ if (aliases) { while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias != NULL && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && aliases[i]->trait_method->mname_len == fnname_len && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(aliases[i]->alias, aliases[i]->alias_len) TSRMLS_CC); /* if it is 0, no modifieres has been changed */ if (aliases[i]->modifiers) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } lcname = zend_str_tolower_dup(aliases[i]->alias, aliases[i]->alias_len); if (zend_hash_add(target, lcname, aliases[i]->alias_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add aliased trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } efree(lcname); } i++; } } lcname = zend_str_tolower_dup(fn->common.function_name, fnname_len); if (exclude_table == NULL || zend_hash_find(exclude_table, lcname, fnname_len, &dummy) == FAILURE) { /* is not in hashtable, thus, function is not to be excluded */ fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(fn->common.function_name, fnname_len) TSRMLS_CC); /* apply aliases which are not qualified by a class name, or which have not * alias name, just setting visibility */ if (aliases) { i = 0; while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias == NULL && aliases[i]->modifiers != 0 && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && (aliases[i]->trait_method->mname_len == fnname_len) && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } i++; } } if (zend_hash_add(target, lcname, fnname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } } efree(lcname); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* Copies function table entries to target function table with applied aliasing */ static void zend_traits_copy_trait_function_table(HashTable *target, zend_class_entry *target_ce, HashTable *source, zend_trait_alias** aliases, HashTable* exclude_table TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_arguments(source TSRMLS_CC, (apply_func_args_t)zend_traits_copy_functions, 4, target, target_ce, aliases, exclude_table); } /* }}} */ static void zend_traits_init_trait_structures(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i, j = 0; zend_trait_precedence *cur_precedence; zend_trait_method_reference *cur_method_ref; /* resolve class references */ if (ce->trait_precedences) { i = 0; while ((cur_precedence = ce->trait_precedences[i])) { if (cur_precedence->exclude_from_classes) { cur_precedence->trait_method->ce = zend_fetch_class(cur_precedence->trait_method->class_name, cur_precedence->trait_method->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); j = 0; while (cur_precedence->exclude_from_classes[j]) { char* class_name = (char*)cur_precedence->exclude_from_classes[j]; zend_uint name_length = strlen(class_name); cur_precedence->exclude_from_classes[j] = zend_fetch_class(class_name, name_length, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); efree(class_name); j++; } } i++; } } if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { if (ce->trait_aliases[i]->trait_method->class_name) { cur_method_ref = ce->trait_aliases[i]->trait_method; cur_method_ref->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); } i++; } } } /* }}} */ static void zend_traits_compile_exclude_table(HashTable* exclude_table, zend_trait_precedence **precedences, zend_class_entry *trait) /* {{{ */ { size_t i = 0, j; if (!precedences) { return; } while (precedences[i]) { if (precedences[i]->exclude_from_classes) { j = 0; while (precedences[i]->exclude_from_classes[j]) { if (precedences[i]->exclude_from_classes[j] == trait) { zend_uint lcname_len = precedences[i]->trait_method->mname_len; char *lcname = zend_str_tolower_dup(precedences[i]->trait_method->method_name, lcname_len); if (zend_hash_add(exclude_table, lcname, lcname_len, NULL, 0, NULL) == FAILURE) { efree(lcname); zend_error(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", precedences[i]->trait_method->method_name, trait->name); } efree(lcname); } ++j; } } ++i; } } /* }}} */ static void zend_do_traits_method_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { HashTable** function_tables; HashTable* resulting_table; HashTable exclude_table; size_t i; /* prepare copies of trait function tables for combination */ function_tables = malloc(sizeof(HashTable*) * ce->num_traits); resulting_table = (HashTable *) malloc(sizeof(HashTable)); /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(resulting_table, 10, NULL, NULL, 1, 0); for (i = 0; i < ce->num_traits; i++) { function_tables[i] = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(function_tables[i], ce->traits[i]->function_table.nNumOfElements, NULL, NULL, 1, 0); if (ce->trait_precedences) { /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(&exclude_table, 2, NULL, NULL, 0, 0); zend_traits_compile_exclude_table(&exclude_table, ce->trait_precedences, ce->traits[i]); /* copies functions, applies defined aliasing, and excludes unused trait methods */ zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, &exclude_table TSRMLS_CC); zend_hash_graceful_destroy(&exclude_table); } else { zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, NULL TSRMLS_CC); } } /* now merge trait methods */ for (i = 0; i < ce->num_traits; i++) { zend_hash_apply_with_arguments(function_tables[i] TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions, 5, i, ce->num_traits, resulting_table, function_tables, ce); } /* Now the resulting_table contains all trait methods we would have to * add to the class in the following step the methods are inserted into the method table * if there is already a method with the same name it is replaced iff ce != fn.scope * --> all inherited methods are overridden, methods defined in the class are left untouched */ zend_hash_apply_with_arguments(resulting_table TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions_to_class, 1, ce); /* free temporary function tables */ for (i = 0; i < ce->num_traits; i++) { /* zend_hash_destroy(function_tables[i]); */ zend_hash_graceful_destroy(function_tables[i]); free(function_tables[i]); } free(function_tables); /* free temporary resulting table */ /* zend_hash_destroy(resulting_table); */ zend_hash_graceful_destroy(resulting_table); free(resulting_table); } /* }}} */ static zend_class_entry* find_first_definition(zend_class_entry *ce, size_t current_trait, const char* prop_name, int prop_name_length, ulong prop_hash, zend_class_entry *coliding_ce) /* {{{ */ { size_t i; zend_property_info *coliding_prop; for (i = 0; (i < current_trait) && (i < ce->num_traits); i++) { if (zend_hash_quick_find(&ce->traits[i]->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS) { return ce->traits[i]; } } return coliding_ce; } /* }}} */ static void zend_do_traits_property_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i; zend_property_info *property_info; zend_property_info *coliding_prop; zval compare_result; const char* prop_name; int prop_name_length; ulong prop_hash; const char* class_name_unused; zend_bool prop_found; zend_bool not_compatible; zval* prop_value; /* In the following steps the properties are inserted into the property table * for that, a very strict approach is applied: * - check for compatibility, if not compatible with any property in class -> fatal * - if compatible, then strict notice */ for (i = 0; i < ce->num_traits; i++) { for (zend_hash_internal_pointer_reset(&ce->traits[i]->properties_info); zend_hash_get_current_data(&ce->traits[i]->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->traits[i]->properties_info)) { /* first get the unmangeld name if necessary, * then check whether the property is already there */ if ((property_info->flags & ZEND_ACC_PPP_MASK) == ZEND_ACC_PUBLIC) { prop_hash = property_info->h; prop_name = property_info->name; prop_name_length = property_info->name_length; prop_found = zend_hash_quick_find(&ce->properties_info, property_info->name, property_info->name_length+1, property_info->h, (void **) &coliding_prop) == SUCCESS; } else { /* for private and protected we need to unmangle the names */ zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name_unused, &prop_name); prop_name_length = strlen(prop_name); prop_hash = zend_get_hash_value(prop_name, prop_name_length + 1); prop_found = zend_hash_quick_find(&ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS; } /* next: check for conflicts with current class */ if (prop_found) { if (coliding_prop->flags & ZEND_ACC_SHADOW) { /* this one is inherited, lets look it up in its own class */ zend_hash_quick_find(&coliding_prop->ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop); } if ((coliding_prop->flags & ZEND_ACC_PPP_MASK) == (property_info->flags & ZEND_ACC_PPP_MASK)) { /* flags are identical, now the value needs to be checked */ if (property_info->flags & ZEND_ACC_STATIC) { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_static_members_table[coliding_prop->offset], ce->traits[i]->default_static_members_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } else { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_properties_table[coliding_prop->offset], ce->traits[i]->default_properties_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } } else { /* the flags are not identical, thus, we assume properties are not compatible */ not_compatible = 1; } if (not_compatible) { zend_error(E_COMPILE_ERROR, "%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } else { zend_error(E_STRICT, "%s and %s define the same property ($%s) in the composition of %s. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } } /* property not found, so lets add it */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); zend_declare_property_ex(ce, prop_name, prop_name_length, prop_value, property_info->flags, property_info->doc_comment, property_info->doc_comment_len TSRMLS_CC); } } } /* }}} */ ZEND_API void zend_do_bind_traits(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { if (ce->num_traits <= 0) { return; } /* complete initialization of trait strutures in ce */ zend_traits_init_trait_structures(ce TSRMLS_CC); /* first care about all methods to be flattened into the class */ zend_do_traits_method_binding(ce TSRMLS_CC); /* then flatten the properties into it, to, mostly to notfiy developer about problems */ zend_do_traits_property_binding(ce TSRMLS_CC); /* verify that all abstract methods from traits have been implemented */ zend_verify_abstract_class(ce TSRMLS_CC); /* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */ if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { ce->ce_flags -= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } } /* }}} */ ZEND_API int do_bind_function(const zend_op_array *op_array, zend_op *opline, HashTable *function_table, zend_bool compile_time) /* {{{ */ { zend_function *function; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } zend_hash_quick_find(function_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void *) &function); if (zend_hash_quick_add(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), function, sizeof(zend_function), NULL)==FAILURE) { int error_level = compile_time ? E_COMPILE_ERROR : E_ERROR; zend_function *old_function; if (zend_hash_quick_find(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), (void *) &old_function)==SUCCESS && old_function->type == ZEND_USER_FUNCTION && old_function->op_array.last > 0) { zend_error(error_level, "Cannot redeclare %s() (previously declared in %s:%d)", function->common.function_name, old_function->op_array.filename, old_function->op_array.opcodes[0].lineno); } else { zend_error(error_level, "Cannot redeclare %s()", function->common.function_name); } return FAILURE; } else { (*function->op_array.refcount)++; function->op_array.static_variables = NULL; /* NULL out the unbound function */ return SUCCESS; } } /* }}} */ void zend_add_trait_precedence(znode *precedence_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_precedences, precedence_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_add_trait_alias(znode *alias_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_aliases, alias_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_prepare_reference(znode *result, znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { zend_trait_method_reference *method_ref = emalloc(sizeof(zend_trait_method_reference)); method_ref->ce = NULL; /* REM: There should not be a need for copying, zend_do_begin_class_declaration is also just using that string */ if (class_name) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); method_ref->class_name = Z_STRVAL(class_name->u.constant); method_ref->cname_len = Z_STRLEN(class_name->u.constant); } else { method_ref->class_name = NULL; method_ref->cname_len = 0; } method_ref->method_name = Z_STRVAL(method_name->u.constant); method_ref->mname_len = Z_STRLEN(method_name->u.constant); result->u.op.ptr = method_ref; result->op_type = IS_TMP_VAR; } /* }}} */ void zend_prepare_trait_alias(znode *result, znode *method_reference, znode *modifiers, znode *alias TSRMLS_DC) /* {{{ */ { zend_trait_alias *trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_alias->modifiers = Z_LVAL(modifiers->u.constant); if (Z_LVAL(modifiers->u.constant) == ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot use 'static' as method modifier"); return; } if (alias) { trait_alias->alias = Z_STRVAL(alias->u.constant); trait_alias->alias_len = Z_STRLEN(alias->u.constant); } else { trait_alias->alias = NULL; } trait_alias->function = NULL; result->u.op.ptr = trait_alias; } /* }}} */ void zend_prepare_trait_precedence(znode *result, znode *method_reference, znode *trait_list TSRMLS_DC) /* {{{ */ { zend_trait_precedence *trait_precedence = emalloc(sizeof(zend_trait_precedence)); trait_precedence->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_precedence->exclude_from_classes = (zend_class_entry**) trait_list->u.op.ptr; trait_precedence->function = NULL; result->u.op.ptr = trait_precedence; } /* }}} */ ZEND_API zend_class_entry *do_bind_class(const zend_op_array* op_array, const zend_op *opline, HashTable *class_table, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } if (zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce)==FAILURE) { zend_error(E_COMPILE_ERROR, "Internal Zend error - Missing class information for %s", Z_STRVAL_P(op1)); return NULL; } else { ce = *pce; } ce->refcount++; if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), &ce, sizeof(zend_class_entry *), NULL)==FAILURE) { ce->refcount--; if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return NULL; } else { if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLEMENT_INTERFACES))) { zend_verify_abstract_class(ce TSRMLS_CC); } return ce; } } /* }}} */ ZEND_API zend_class_entry *do_bind_inherited_class(const zend_op_array *op_array, const zend_op *opline, HashTable *class_table, zend_class_entry *parent_ce, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; int found_ce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } found_ce = zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce); if (found_ce == FAILURE) { if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", Z_STRVAL_P(op2)); } return NULL; } else { ce = *pce; } if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ce->name, parent_ce->name); } else if ((parent_ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ce->name, parent_ce->name); } zend_do_inheritance(ce, parent_ce TSRMLS_CC); ce->refcount++; /* Register the derived class */ if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), pce, sizeof(zend_class_entry *), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return ce; } /* }}} */ void zend_do_early_binding(TSRMLS_D) /* {{{ */ { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; HashTable *table; while (opline->opcode == ZEND_TICKS && opline > CG(active_op_array)->opcodes) { opline--; } switch (opline->opcode) { case ZEND_DECLARE_FUNCTION: if (do_bind_function(CG(active_op_array), opline, CG(function_table), 1) == FAILURE) { return; } table = CG(function_table); break; case ZEND_DECLARE_CLASS: if (do_bind_class(CG(active_op_array), opline, CG(class_table), 1 TSRMLS_CC) == NULL) { return; } table = CG(class_table); break; case ZEND_DECLARE_INHERITED_CLASS: { zend_op *fetch_class_opline = opline-1; zval *parent_name; zend_class_entry **pce; parent_name = &CONSTANT(fetch_class_opline->op2.constant); if ((zend_lookup_class(Z_STRVAL_P(parent_name), Z_STRLEN_P(parent_name), &pce TSRMLS_CC) == FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_CLASSES) && ((*pce)->type == ZEND_INTERNAL_CLASS))) { if (CG(compiler_options) & ZEND_COMPILE_DELAYED_BINDING) { zend_uint *opline_num = &CG(active_op_array)->early_binding; while (*opline_num != -1) { opline_num = &CG(active_op_array)->opcodes[*opline_num].result.opline_num; } *opline_num = opline - CG(active_op_array)->opcodes; opline->opcode = ZEND_DECLARE_INHERITED_CLASS_DELAYED; opline->result_type = IS_UNUSED; opline->result.opline_num = -1; } return; } if (do_bind_inherited_class(CG(active_op_array), opline, CG(class_table), *pce, 1 TSRMLS_CC) == NULL) { return; } /* clear unnecessary ZEND_FETCH_CLASS opcode */ zend_del_literal(CG(active_op_array), fetch_class_opline->op2.constant); MAKE_NOP(fetch_class_opline); table = CG(class_table); break; } case ZEND_VERIFY_ABSTRACT_CLASS: case ZEND_ADD_INTERFACE: case ZEND_ADD_TRAIT: case ZEND_BIND_TRAITS: /* We currently don't early-bind classes that implement interfaces */ /* Classes with traits are handled exactly the same, no early-bind here */ return; default: zend_error(E_COMPILE_ERROR, "Invalid binding type"); return; } zend_hash_quick_del(table, Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant)), Z_HASH_P(&CONSTANT(opline->op1.constant))); zend_del_literal(CG(active_op_array), opline->op1.constant); zend_del_literal(CG(active_op_array), opline->op2.constant); MAKE_NOP(opline); } /* }}} */ ZEND_API void zend_do_delayed_early_binding(const zend_op_array *op_array TSRMLS_DC) /* {{{ */ { if (op_array->early_binding != -1) { zend_bool orig_in_compilation = CG(in_compilation); zend_uint opline_num = op_array->early_binding; zend_class_entry **pce; CG(in_compilation) = 1; while (opline_num != -1) { if (zend_lookup_class(Z_STRVAL_P(op_array->opcodes[opline_num-1].op2.zv), Z_STRLEN_P(op_array->opcodes[opline_num-1].op2.zv), &pce TSRMLS_CC) == SUCCESS) { do_bind_inherited_class(op_array, &op_array->opcodes[opline_num], EG(class_table), *pce, 0 TSRMLS_CC); } opline_num = op_array->opcodes[opline_num].result.opline_num; } CG(in_compilation) = orig_in_compilation; } } /* }}} */ void zend_do_boolean_or_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_or_end(znode *result, const znode *expr1, const znode *expr2, znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_boolean_and_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_and_end(znode *result, const znode *expr1, const znode *expr2, const znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_do_while_begin(TSRMLS_D) /* {{{ */ { do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_do_while_end(const znode *do_token, const znode *expr_open_bracket, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ; SET_NODE(opline->op1, expr); opline->op2.opline_num = do_token->u.op.opline_num; SET_UNUSED(opline->op2); do_end_loop(expr_open_bracket->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_brk_cont(zend_uchar op, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->op1.opline_num = CG(context).current_brk_cont; SET_UNUSED(opline->op1); if (expr) { if (expr->op_type != IS_CONST) { zend_error(E_COMPILE_ERROR, "'%s' operator with non-constant operand is no longer supported", op == ZEND_BRK ? "break" : "continue"); } else if (Z_TYPE(expr->u.constant) != IS_LONG || Z_LVAL(expr->u.constant) < 1) { zend_error(E_COMPILE_ERROR, "'%s' operator accepts only positive numbers", op == ZEND_BRK ? "break" : "continue"); } SET_NODE(opline->op2, expr); } else { LITERAL_LONG(opline->op2, 1); opline->op2_type = IS_CONST; } } /* }}} */ void zend_do_switch_cond(const znode *cond TSRMLS_DC) /* {{{ */ { zend_switch_entry switch_entry; switch_entry.cond = *cond; switch_entry.default_case = -1; switch_entry.control_var = -1; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_switch_end(const znode *case_list TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); /* add code to jmp to default case */ if (switch_entry_ptr->default_case != -1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->op1.opline_num = switch_entry_ptr->default_case; } if (case_list->op_type != IS_UNUSED) { /* non-empty switch */ int next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* remember break/continue loop information */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; if (switch_entry_ptr->cond.op_type==IS_VAR || switch_entry_ptr->cond.op_type==IS_TMP_VAR) { /* emit free for the switch condition*/ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry_ptr->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_UNUSED(opline->op2); } if (switch_entry_ptr->cond.op_type == IS_CONST) { zval_dtor(&switch_entry_ptr->cond.u.constant); } zend_stack_del_top(&CG(switch_cond_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_case_before_statement(const znode *case_list, znode *case_token, const znode *case_expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); int next_op_number; zend_switch_entry *switch_entry_ptr; znode result; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); if (switch_entry_ptr->control_var == -1) { switch_entry_ptr->control_var = get_temporary_variable(CG(active_op_array)); } opline->opcode = ZEND_CASE; opline->result.var = switch_entry_ptr->control_var; opline->result_type = IS_TMP_VAR; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_NODE(opline->op2, case_expr); if (opline->op1_type == IS_CONST) { zval_copy_ctor(&CONSTANT(opline->op1.constant)); } GET_NODE(&result, opline->result); next_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, &result); SET_UNUSED(opline->op2); case_token->u.op.opline_num = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_case_after_statement(znode *result, const znode *case_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); result->u.op.opline_num = next_op_number; switch (CG(active_op_array)->opcodes[case_token->u.op.opline_num].opcode) { case ZEND_JMP: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); break; case ZEND_JMPZ: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); break; } } /* }}} */ void zend_do_default_before_statement(const znode *case_list, znode *default_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); default_token->u.op.opline_num = next_op_number; next_op_number = get_next_op_number(CG(active_op_array)); switch_entry_ptr->default_case = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_begin_class_declaration(const znode *class_token, znode *class_name, const znode *parent_class_name TSRMLS_DC) /* {{{ */ { zend_op *opline; int doing_inheritance = 0; zend_class_entry *new_class_entry; char *lcname; int error = 0; zval **ns_name, key; if (CG(active_class_entry)) { zend_error(E_COMPILE_ERROR, "Class declarations may not be nested"); return; } lcname = zend_str_tolower_dup(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); if (!(strcmp(lcname, "self") && strcmp(lcname, "parent"))) { efree(lcname); zend_error(E_COMPILE_ERROR, "Cannot use '%s' as class name as it is reserved", Z_STRVAL(class_name->u.constant)); } /* Class name must not conflict with import names */ if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns_name) == SUCCESS) { error = 1; } if (CG(current_namespace)) { /* Prefix class name with name of current namespace */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); class_name = &tmp; efree(lcname); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); } if (error) { char *tmp = zend_str_tolower_dup(Z_STRVAL_PP(ns_name), Z_STRLEN_PP(ns_name)); if (Z_STRLEN_PP(ns_name) != Z_STRLEN(class_name->u.constant) || memcmp(tmp, lcname, Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "Cannot declare class %s because the name is already in use", Z_STRVAL(class_name->u.constant)); } efree(tmp); } new_class_entry = emalloc(sizeof(zend_class_entry)); new_class_entry->type = ZEND_USER_CLASS; new_class_entry->name = zend_new_interned_string(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1, 1 TSRMLS_CC); new_class_entry->name_length = Z_STRLEN(class_name->u.constant); zend_initialize_class_data(new_class_entry, 1 TSRMLS_CC); new_class_entry->info.user.filename = zend_get_compiled_filename(TSRMLS_C); new_class_entry->info.user.line_start = class_token->u.op.opline_num; new_class_entry->ce_flags |= class_token->EA; if (parent_class_name && parent_class_name->op_type != IS_UNUSED) { switch (parent_class_name->EA) { case ZEND_FETCH_CLASS_SELF: zend_error(E_COMPILE_ERROR, "Cannot use 'self' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_PARENT: zend_error(E_COMPILE_ERROR, "Cannot use 'parent' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use 'static' as class name as it is reserved"); break; default: break; } doing_inheritance = 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, new_class_entry->name_length TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; if (doing_inheritance) { /* Make sure a trait does not try to extend a class */ if ((new_class_entry->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "A trait (%s) cannot extend a class", new_class_entry->name); } opline->extended_value = parent_class_name->u.op.var; opline->opcode = ZEND_DECLARE_INHERITED_CLASS; } else { opline->opcode = ZEND_DECLARE_CLASS; } LITERAL_STRINGL(opline->op2, lcname, new_class_entry->name_length, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); zend_hash_quick_update(CG(class_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &new_class_entry, sizeof(zend_class_entry *), NULL); CG(active_class_entry) = new_class_entry; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(&CG(implementing_class), opline->result); if (CG(doc_comment)) { CG(active_class_entry)->info.user.doc_comment = CG(doc_comment); CG(active_class_entry)->info.user.doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ static void do_verify_abstract_class(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_VERIFY_ABSTRACT_CLASS; SET_NODE(opline->op1, &CG(implementing_class)); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_class_declaration(const znode *class_token, const znode *parent_token TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); if (ce->constructor) { ce->constructor->common.fn_flags |= ZEND_ACC_CTOR; if (ce->constructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Constructor %s::%s() cannot be static", ce->name, ce->constructor->common.function_name); } } if (ce->destructor) { ce->destructor->common.fn_flags |= ZEND_ACC_DTOR; if (ce->destructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Destructor %s::%s() cannot be static", ce->name, ce->destructor->common.function_name); } } if (ce->clone) { ce->clone->common.fn_flags |= ZEND_ACC_CLONE; if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static", ce->name, ce->clone->common.function_name); } } ce->info.user.line_end = zend_get_compiled_lineno(TSRMLS_C); /* Check for traits and proceed like with interfaces. * The only difference will be a combined handling of them in the end. * Thus, we need another opcode here. */ if (ce->num_traits > 0) { zend_op *opline; ce->traits = NULL; ce->num_traits = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_TRAITS; /* opcode generation: */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BIND_TRAITS; SET_NODE(opline->op1, &CG(implementing_class)); } if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) && ((parent_token->op_type != IS_UNUSED) || (ce->num_interfaces > 0))) { zend_verify_abstract_class(ce TSRMLS_CC); if (ce->num_interfaces) { do_verify_abstract_class(TSRMLS_C); } } /* Inherit interfaces; reset number to zero, we need it for above check and * will restore it during actual implementation. * The ZEND_ACC_IMPLEMENT_INTERFACES flag disables double call to * zend_verify_abstract_class() */ if (ce->num_interfaces > 0) { ce->interfaces = NULL; ce->num_interfaces = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_INTERFACES; } CG(active_class_entry) = NULL; } /* }}} */ void zend_do_implements_interface(znode *interface_name TSRMLS_DC) /* {{{ */ { zend_op *opline; /* Traits can not implement interfaces */ if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface on '%s' since it is a Trait", Z_STRVAL(interface_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(interface_name->u.constant), Z_STRLEN(interface_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface name as it is reserved", Z_STRVAL(interface_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_INTERFACE; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(interface_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = (opline->extended_value & ~ZEND_FETCH_CLASS_MASK) | ZEND_FETCH_CLASS_INTERFACE; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &interface_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_interfaces++; } /* }}} */ void zend_do_implements_trait(znode *trait_name TSRMLS_DC) /* {{{ */ { zend_op *opline; if ((CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Cannot use traits inside of interfaces. %s is used in %s", Z_STRVAL(trait_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(trait_name->u.constant), Z_STRLEN(trait_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as trait name as it is reserved", Z_STRVAL(trait_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_TRAIT; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(trait_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = ZEND_FETCH_CLASS_TRAIT; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &trait_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_traits++; } /* }}} */ ZEND_API void zend_mangle_property_name(char **dest, int *dest_length, const char *src1, int src1_length, const char *src2, int src2_length, int internal) /* {{{ */ { char *prop_name; int prop_name_length; prop_name_length = 1 + src1_length + 1 + src2_length; prop_name = pemalloc(prop_name_length + 1, internal); prop_name[0] = '\0'; memcpy(prop_name + 1, src1, src1_length+1); memcpy(prop_name + 1 + src1_length + 1, src2, src2_length+1); *dest = prop_name; *dest_length = prop_name_length; } /* }}} */ static int zend_strnlen(const char* s, int maxlen) /* {{{ */ { int len = 0; while (*s++ && maxlen--) len++; return len; } /* }}} */ ZEND_API int zend_unmangle_property_name(const char *mangled_property, int len, const char **class_name, const char **prop_name) /* {{{ */ { int class_name_len; *class_name = NULL; if (mangled_property[0]!=0) { *prop_name = mangled_property; return SUCCESS; } if (len < 3 || mangled_property[1]==0) { zend_error(E_NOTICE, "Illegal member variable name"); *prop_name = mangled_property; return FAILURE; } class_name_len = zend_strnlen(mangled_property+1, --len - 1) + 1; if (class_name_len >= len || mangled_property[class_name_len]!=0) { zend_error(E_NOTICE, "Corrupt member variable name"); *prop_name = mangled_property; return FAILURE; } *class_name = mangled_property+1; *prop_name = (*class_name)+class_name_len; return SUCCESS; } /* }}} */ void zend_do_declare_property(const znode *var_name, const znode *value, zend_uint access_type TSRMLS_DC) /* {{{ */ { zval *property; zend_property_info *existing_property_info; char *comment = NULL; int comment_len = 0; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Interfaces may not include member variables"); } if (access_type & ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Properties cannot be declared abstract"); } if (access_type & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot declare property %s::$%s final, the final modifier is allowed only for methods and classes", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } if (zend_hash_find(&CG(active_class_entry)->properties_info, var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, (void **) &existing_property_info)==SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::$%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } ALLOC_ZVAL(property); if (value) { *property = value->u.constant; } else { INIT_PZVAL(property); Z_TYPE_P(property) = IS_NULL; } if (CG(doc_comment)) { comment = CG(doc_comment); comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } zend_declare_property_ex(CG(active_class_entry), zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len + 1, 0 TSRMLS_CC), var_name->u.constant.value.str.len, property, access_type, comment, comment_len TSRMLS_CC); efree(var_name->u.constant.value.str.val); } /* }}} */ void zend_do_declare_class_constant(znode *var_name, const znode *value TSRMLS_DC) /* {{{ */ { zval *property; const char *cname = NULL; int result; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed in class constants"); return; } if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Traits cannot have constants"); return; } ALLOC_ZVAL(property); *property = value->u.constant; cname = zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, 0 TSRMLS_CC); if (IS_INTERNED(cname)) { result = zend_hash_quick_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, INTERNED_HASH(cname), &property, sizeof(zval *), NULL); } else { result = zend_hash_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, &property, sizeof(zval *), NULL); } if (result == FAILURE) { FREE_ZVAL(property); zend_error(E_COMPILE_ERROR, "Cannot redefine class constant %s::%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } FREE_PNODE(var_name); if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_fetch_property(znode *result, znode *object, const znode *property TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (object->op_type == IS_CV) { if (object->u.op.var == CG(active_op_array)->this_var) { object->op_type = IS_UNUSED; /* this means $this for objects */ } } else if (fetch_list_ptr->count == 1) { zend_llist_element *le = fetch_list_ptr->head; zend_op *opline_ptr = (zend_op *) le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); SET_UNUSED(opline_ptr->op1); /* this means $this for objects */ SET_NODE(opline_ptr->op2, property); /* if it was usual fetch, we change it to object fetch */ switch (opline_ptr->opcode) { case ZEND_FETCH_W: opline_ptr->opcode = ZEND_FETCH_OBJ_W; break; case ZEND_FETCH_R: opline_ptr->opcode = ZEND_FETCH_OBJ_R; break; case ZEND_FETCH_RW: opline_ptr->opcode = ZEND_FETCH_OBJ_RW; break; case ZEND_FETCH_IS: opline_ptr->opcode = ZEND_FETCH_OBJ_IS; break; case ZEND_FETCH_UNSET: opline_ptr->opcode = ZEND_FETCH_OBJ_UNSET; break; case ZEND_FETCH_FUNC_ARG: opline_ptr->opcode = ZEND_FETCH_OBJ_FUNC_ARG; break; } if (opline_ptr->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline_ptr->op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline_ptr->op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op2.constant); } GET_NODE(result, opline_ptr->result); return; } } if (zend_is_function_or_method_call(object)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, object); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_OBJ_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, object); SET_NODE(opline.op2, property); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline.op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op2.constant); } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void zend_do_halt_compiler_register(TSRMLS_D) /* {{{ */ { char *name, *cfilename; char haltoff[] = "__COMPILER_HALT_OFFSET__"; int len, clen; cfilename = zend_get_compiled_filename(TSRMLS_C); clen = strlen(cfilename); zend_mangle_property_name(&name, &len, haltoff, sizeof(haltoff) - 1, cfilename, clen, 0); zend_register_long_constant(name, len+1, zend_get_scanned_file_offset(TSRMLS_C), CONST_CS, 0 TSRMLS_CC); pefree(name, 0); if (CG(in_namespace)) { zend_do_end_namespace(TSRMLS_C); } } /* }}} */ void zend_do_push_object(const znode *object TSRMLS_DC) /* {{{ */ { zend_stack_push(&CG(object_stack), object, sizeof(znode)); } /* }}} */ void zend_do_pop_object(znode *object TSRMLS_DC) /* {{{ */ { if (object) { znode *tmp; zend_stack_top(&CG(object_stack), (void **) &tmp); *object = *tmp; } zend_stack_del_top(&CG(object_stack)); } /* }}} */ void zend_do_begin_new_object(znode *new_token, znode *class_type TSRMLS_DC) /* {{{ */ { zend_op *opline; unsigned char *ptr = NULL; new_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_NEW; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, class_type); SET_UNUSED(opline->op2); zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(unsigned char *)); } /* }}} */ void zend_do_end_new_object(znode *result, const znode *new_token, const znode *argument_list TSRMLS_DC) /* {{{ */ { znode ctor_result; zend_do_end_function_call(NULL, &ctor_result, argument_list, 1, 0 TSRMLS_CC); zend_do_free(&ctor_result TSRMLS_CC); CG(active_op_array)->opcodes[new_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, CG(active_op_array)->opcodes[new_token->u.op.opline_num].result); } /* }}} */ static zend_constant* zend_get_ct_const(const zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = NULL; if (Z_STRVAL_P(const_name)[0] == '\\') { if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name), (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name)-1); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name), (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } } else if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)+1, (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name)+1, (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } if (c->flags & CONST_CT_SUBST) { return c; } if (all_internal_constants_substitution && (c->flags & CONST_PERSISTENT) && !(CG(compiler_options) & ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION) && Z_TYPE(c->value) != IS_CONSTANT && Z_TYPE(c->value) != IS_CONSTANT_ARRAY) { return c; } return NULL; } /* }}} */ static int zend_constant_ct_subst(znode *result, zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = zend_get_ct_const(const_name, all_internal_constants_substitution TSRMLS_CC); if (c) { zval_dtor(const_name); result->op_type = IS_CONST; result->u.constant = c->value; zval_copy_ctor(&result->u.constant); INIT_PZVAL(&result->u.constant); return 1; } return 0; } /* }}} */ void zend_do_fetch_constant(znode *result, znode *constant_container, znode *constant_name, int mode, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; zend_op *opline; int type; char *compound; ulong fetch_type = 0; if (constant_container) { switch (mode) { case ZEND_CT: /* this is a class constant */ type = zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant)); if (ZEND_FETCH_CLASS_STATIC == type) { zend_error(E_ERROR, "\"static::\" is not allowed in compile-time constants"); } else if (ZEND_FETCH_CLASS_DEFAULT == type) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } zend_do_build_full_name(NULL, constant_container, constant_name, 1 TSRMLS_CC); *result = *constant_container; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: if (constant_container->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant))) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } else { zend_do_fetch_class(&tmp, constant_container TSRMLS_CC); constant_container = &tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); if (constant_container->op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &constant_container->u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, constant_container); } SET_NODE(opline->op2, constant_name); CALCULATE_LITERAL_HASH(opline->op2.constant); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } GET_NODE(result, opline->result); break; } return; } /* namespace constant */ /* only one that did not contain \ from the start can be converted to string if unknown */ switch (mode) { case ZEND_CT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); /* this is a namespace constant, or an unprefixed constant */ if (zend_constant_ct_subst(result, &constant_name->u.constant, 0 TSRMLS_CC)) { break; } zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(!compound) { fetch_type |= IS_CONSTANT_UNQUALIFIED; } *result = *constant_name; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(zend_constant_ct_subst(result, &constant_name->u.constant, 1 TSRMLS_CC)) { break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; if (compound) { /* the name is unambiguous */ opline->extended_value = 0; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } else { opline->extended_value = IS_CONSTANT_UNQUALIFIED; if (CG(current_namespace)) { opline->extended_value |= IS_CONSTANT_IN_NAMESPACE; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 1 TSRMLS_CC); } else { opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } } GET_CACHE_SLOT(opline->op2.constant); break; } } /* }}} */ void zend_do_shell_exec(znode *result, const znode *cmd TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); switch (cmd->op_type) { case IS_CONST: case IS_TMP_VAR: opline->opcode = ZEND_SEND_VAL; break; default: opline->opcode = ZEND_SEND_VAR; break; } SET_NODE(opline->op1, cmd); opline->op2.opline_num = 0; opline->extended_value = ZEND_DO_FCALL; SET_UNUSED(opline->op2); /* FIXME: exception support not added to this op2 */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DO_FCALL; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; LITERAL_STRINGL(opline->op1, estrndup("shell_exec", sizeof("shell_exec")-1), sizeof("shell_exec")-1, 0); CALCULATE_LITERAL_HASH(opline->op1.constant); opline->op1_type = IS_CONST; GET_CACHE_SLOT(opline->op1.constant); opline->extended_value = 1; SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_init_array(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_ARRAY; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; GET_NODE(result, opline->result); if (expr) { SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } } else { SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_array_element(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_ARRAY_ELEMENT; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_static_array_element(znode *result, znode *offset, const znode *expr) /* {{{ */ { zval *element; ALLOC_ZVAL(element); *element = expr->u.constant; if (offset) { switch (offset->u.constant.type & IS_CONSTANT_TYPE_MASK) { case IS_CONSTANT: /* Ugly hack to denote that this value has a constant index */ Z_TYPE_P(element) |= IS_CONSTANT_INDEX; Z_STRVAL(offset->u.constant) = erealloc(Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+1] = Z_TYPE(offset->u.constant); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+2] = 0; zend_symtable_update(result->u.constant.value.ht, Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_STRING: zend_symtable_update(result->u.constant.value.ht, offset->u.constant.value.str.val, offset->u.constant.value.str.len+1, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_NULL: zend_symtable_update(Z_ARRVAL(result->u.constant), "", 1, &element, sizeof(zval *), NULL); break; case IS_LONG: case IS_BOOL: zend_hash_index_update(Z_ARRVAL(result->u.constant), Z_LVAL(offset->u.constant), &element, sizeof(zval *), NULL); break; case IS_DOUBLE: zend_hash_index_update(Z_ARRVAL(result->u.constant), zend_dval_to_lval(Z_DVAL(offset->u.constant)), &element, sizeof(zval *), NULL); break; case IS_CONSTANT_ARRAY: zend_error(E_ERROR, "Illegal offset type"); break; } } else { zend_hash_next_index_insert(Z_ARRVAL(result->u.constant), &element, sizeof(zval *), NULL); } } /* }}} */ void zend_do_add_list_element(const znode *element TSRMLS_DC) /* {{{ */ { list_llist_element lle; if (element) { zend_check_writable_variable(element); lle.var = *element; zend_llist_copy(&lle.dimensions, &CG(dimension_llist)); zend_llist_prepend_element(&CG(list_llist), &lle); } (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_new_list_begin(TSRMLS_D) /* {{{ */ { int current_dimension = 0; zend_llist_add_element(&CG(dimension_llist), &current_dimension); } /* }}} */ void zend_do_new_list_end(TSRMLS_D) /* {{{ */ { zend_llist_remove_tail(&CG(dimension_llist)); (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_list_init(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(list_stack), &CG(list_llist), sizeof(zend_llist)); zend_stack_push(&CG(list_stack), &CG(dimension_llist), sizeof(zend_llist)); zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_do_new_list_begin(TSRMLS_C); } /* }}} */ void zend_do_list_end(znode *result, znode *expr TSRMLS_DC) /* {{{ */ { zend_llist_element *le; zend_llist_element *dimension; zend_op *opline; znode last_container; le = CG(list_llist).head; while (le) { zend_llist *tmp_dimension_llist = &((list_llist_element *)le->data)->dimensions; dimension = tmp_dimension_llist->head; while (dimension) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (dimension == tmp_dimension_llist->head) { /* first */ last_container = *expr; switch (expr->op_type) { case IS_VAR: case IS_CV: opline->opcode = ZEND_FETCH_DIM_R; break; case IS_TMP_VAR: opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; case IS_CONST: /* fetch_dim_tmp_var will handle this bogus fetch */ zval_copy_ctor(&expr->u.constant); opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; } opline->extended_value |= ZEND_FETCH_ADD_LOCK; } else { opline->opcode = ZEND_FETCH_DIM_R; } opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, &last_container); opline->op2_type = IS_CONST; LITERAL_LONG(opline->op2, *((int *) dimension->data)); GET_NODE(&last_container, opline->result); dimension = dimension->next; } ((list_llist_element *) le->data)->value = last_container; zend_llist_destroy(&((list_llist_element *) le->data)->dimensions); zend_do_assign(result, &((list_llist_element *) le->data)->var, &((list_llist_element *) le->data)->value TSRMLS_CC); zend_do_free(result TSRMLS_CC); le = le->next; } zend_llist_destroy(&CG(dimension_llist)); zend_llist_destroy(&CG(list_llist)); *result = *expr; { zend_llist *p; /* restore previous lists */ zend_stack_top(&CG(list_stack), (void **) &p); CG(dimension_llist) = *p; zend_stack_del_top(&CG(list_stack)); zend_stack_top(&CG(list_stack), (void **) &p); CG(list_llist) = *p; zend_stack_del_top(&CG(list_stack)); } } /* }}} */ void zend_init_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = emalloc(sizeof(void*) * 2); list[0] = item; list[1] = NULL; *(void**)result = list; } /* }}} */ void zend_add_to_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = *(void**)result; size_t n = 0; while (list && list[n]) { n++; } list = erealloc(list, sizeof(void*) * (n+2)); list[n] = item; list[n+1] = NULL; *(void**)result = list; } /* }}} */ void zend_do_fetch_static_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zval *tmp; zend_op *opline; znode lval; znode result; ALLOC_ZVAL(tmp); if (static_assignment) { *tmp = static_assignment->u.constant; } else { INIT_ZVAL(*tmp); } if (!CG(active_op_array)->static_variables) { if (CG(active_op_array)->scope) { CG(active_op_array)->scope->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } ALLOC_HASHTABLE(CG(active_op_array)->static_variables); zend_hash_init(CG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } zend_hash_update(CG(active_op_array)->static_variables, varname->u.constant.value.str.val, varname->u.constant.value.str.len+1, &tmp, sizeof(zval *), NULL); if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (fetch_type == ZEND_FETCH_LEXICAL) ? ZEND_FETCH_R : ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_STATIC; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ if (fetch_type == ZEND_FETCH_LEXICAL) { znode dummy; zend_do_begin_variable_parse(TSRMLS_C); zend_do_assign(&dummy, &lval, &result TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } else { zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); } CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_fetch_lexical_variable(znode *varname, zend_bool is_ref TSRMLS_DC) /* {{{ */ { znode value; if (Z_STRLEN(varname->u.constant) == sizeof("this") - 1 && memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this") - 1) == 0) { zend_error(E_COMPILE_ERROR, "Cannot use $this as lexical variable"); return; } value.op_type = IS_CONST; ZVAL_NULL(&value.u.constant); Z_TYPE(value.u.constant) |= is_ref ? IS_LEXICAL_REF : IS_LEXICAL_VAR; Z_SET_REFCOUNT_P(&value.u.constant, 1); Z_UNSET_ISREF_P(&value.u.constant); zend_do_fetch_static_variable(varname, &value, is_ref ? ZEND_FETCH_STATIC : ZEND_FETCH_LEXICAL TSRMLS_CC); } /* }}} */ void zend_do_fetch_global_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zend_op *opline; znode lval; znode result; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = fetch_type; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_cast(znode *result, const znode *expr, int type TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CAST; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } /* }}} */ void zend_do_include_or_eval(int type, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_do_extended_fcall_begin(TSRMLS_C); { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INCLUDE_OR_EVAL; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } zend_do_extended_fcall_end(TSRMLS_C); } /* }}} */ void zend_do_indirect_references(znode *result, const znode *num_references, znode *variable TSRMLS_DC) /* {{{ */ { int i; zend_do_end_variable_parse(variable, BP_VAR_R, 0 TSRMLS_CC); for (i=1; i<num_references->u.constant.value.lval; i++) { fetch_simple_variable_ex(result, variable, 0, ZEND_FETCH_R TSRMLS_CC); *variable = *result; } zend_do_begin_variable_parse(TSRMLS_C); fetch_simple_variable(result, variable, 1 TSRMLS_CC); /* there is a chance someone is accessing $this */ if (CG(active_op_array)->scope && CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } /* }}} */ void zend_do_unset(const znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_UNSET_VAR; SET_NODE(opline->op1, variable); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); opline->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_UNSET: last_op->opcode = ZEND_UNSET_VAR; SET_UNUSED(last_op->result); break; case ZEND_FETCH_DIM_UNSET: last_op->opcode = ZEND_UNSET_DIM; SET_UNUSED(last_op->result); break; case ZEND_FETCH_OBJ_UNSET: last_op->opcode = ZEND_UNSET_OBJ; SET_UNUSED(last_op->result); break; } } } /* }}} */ void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_do_end_variable_parse(variable, BP_VAR_IS, 0 TSRMLS_CC); zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { last_op = get_next_op(CG(active_op_array) TSRMLS_CC); last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; SET_NODE(last_op->op1, variable); SET_UNUSED(last_op->op2); last_op->result.var = get_temporary_variable(CG(active_op_array)); last_op->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; break; case ZEND_FETCH_DIM_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_DIM_OBJ; break; case ZEND_FETCH_OBJ_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_PROP_OBJ; break; } } last_op->result_type = IS_TMP_VAR; last_op->extended_value |= type; GET_NODE(result, last_op->result); } /* }}} */ void zend_do_instanceof(znode *result, const znode *expr, const znode *class_znode, int type TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline->opcode == ZEND_FETCH_CLASS) { opline->extended_value |= ZEND_FETCH_CLASS_NO_AUTOLOAD; } } if (expr->op_type == IS_CONST) { zend_error(E_COMPILE_ERROR, "instanceof expects an object instance, constant given"); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INSTANCEOF; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_NODE(opline->op2, class_znode); GET_NODE(result, opline->result); } /* }}} */ void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_bool is_variable; zend_bool push_container = 0; zend_op dummy_opline; if (variable) { if (zend_is_function_or_method_call(array)) { is_variable = 0; } else { is_variable = 1; } /* save the location of FETCH_W instruction(s) */ open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); zend_do_end_variable_parse(array, BP_VAR_W, 0 TSRMLS_CC); if (CG(active_op_array)->last > 0 && CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) { /* Only lock the container if we are fetching from a real container and not $this */ if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1_type == IS_VAR) { CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK; push_container = 1; } } } else { is_variable = 0; open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* save the location of FE_RESET */ foreach_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* Preform array reset */ opline->opcode = ZEND_FE_RESET; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, array); SET_UNUSED(opline->op2); opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0; COPY_NODE(dummy_opline.result, opline->result); if (push_container) { COPY_NODE(dummy_opline.op1, CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1); } else { dummy_opline.op1_type = IS_UNUSED; } zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); /* save the location of FE_FETCH */ as_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FE_FETCH; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); COPY_NODE(opline->op1, dummy_opline.result); opline->extended_value = 0; SET_UNUSED(opline->op2); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_OP_DATA; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); } /* }}} */ void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC) /* {{{ */ { zend_op *opline; znode dummy, value_node; zend_bool assign_by_ref=0; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num]; if (key->op_type != IS_UNUSED) { znode *tmp; /* switch between the key and value... */ tmp = key; key = value; value = tmp; /* Mark extended_value in case both key and value are being used */ opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; } if ((key->op_type != IS_UNUSED) && (key->EA & ZEND_PARSED_REFERENCE_VARIABLE)) { zend_error(E_COMPILE_ERROR, "Key element cannot be a reference"); } if (value->EA & ZEND_PARSED_REFERENCE_VARIABLE) { assign_by_ref = 1; if (!(opline-1)->extended_value) { zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression"); } /* Mark extended_value for assign-by-reference */ opline->extended_value |= ZEND_FE_FETCH_BYREF; CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; } else { zend_op *foreach_copy; zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.op.opline_num]; zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.op.opline_num]; /* Change "write context" into "read context" */ fetch->extended_value = 0; /* reset ZEND_FE_RESET_VARIABLE */ while (fetch != end) { --fetch; if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } if (fetch->opcode == ZEND_SEPARATE) { MAKE_NOP(fetch); } else { fetch->opcode -= 3; /* FETCH_W -> FETCH_R */ } } /* prevent double SWITCH_FREE */ zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy); foreach_copy->op1_type = IS_UNUSED; } GET_NODE(&value_node, opline->result); if (assign_by_ref) { zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); /* Mark FE_FETCH as IS_VAR as it holds the data directly as a value */ zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC); } else { zend_do_assign(&dummy, value, &value_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } if (key->op_type != IS_UNUSED) { znode key_node; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num+1]; opline->result_type = IS_TMP_VAR; opline->result.opline_num = get_temporary_variable(CG(active_op_array)); GET_NODE(&key_node, opline->result); zend_do_assign(&dummy, key, &key_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_foreach_end(const znode *foreach_token, const znode *as_token TSRMLS_DC) /* {{{ */ { zend_op *container_ptr; zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = as_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_RESET */ CG(active_op_array)->opcodes[as_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_FETCH */ do_end_loop(as_token->u.op.opline_num, 1 TSRMLS_CC); zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr); generate_free_foreach_copy(container_ptr TSRMLS_CC); zend_stack_del_top(&CG(foreach_copy_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_declare_begin(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(declare_stack), &CG(declarables), sizeof(zend_declarables)); } /* }}} */ void zend_do_declare_stmt(znode *var, znode *val TSRMLS_DC) /* {{{ */ { if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "ticks", sizeof("ticks")-1)) { convert_to_long(&val->u.constant); CG(declarables).ticks = val->u.constant; } else if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "encoding", sizeof("encoding")-1)) { if ((Z_TYPE(val->u.constant) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Cannot use constants as encoding"); } /* * Check that the pragma comes before any opcodes. If the compilation * got as far as this, the previous portion of the script must have been * parseable according to the .ini script_encoding setting. We still * want to tell them to put declare() at the top. */ { int num = CG(active_op_array)->last; /* ignore ZEND_EXT_STMT and ZEND_TICKS */ while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Encoding declaration pragma must be the very first statement in the script"); } } if (CG(multibyte)) { const zend_encoding *new_encoding, *old_encoding; zend_encoding_filter old_input_filter; CG(encoding_declared) = 1; convert_to_string(&val->u.constant); new_encoding = zend_multibyte_fetch_encoding(val->u.constant.value.str.val TSRMLS_CC); if (!new_encoding) { zend_error(E_COMPILE_WARNING, "Unsupported encoding [%s]", val->u.constant.value.str.val); } else { old_input_filter = LANG_SCNG(input_filter); old_encoding = LANG_SCNG(script_encoding); zend_multibyte_set_filter(new_encoding TSRMLS_CC); /* need to re-scan if input filter changed */ if (old_input_filter != LANG_SCNG(input_filter) || (old_input_filter && new_encoding != old_encoding)) { zend_multibyte_yyinput_again(old_input_filter, old_encoding TSRMLS_CC); } } } else { zend_error(E_COMPILE_WARNING, "declare(encoding=...) ignored because Zend multibyte feature is turned off by settings"); } zval_dtor(&val->u.constant); } else { zend_error(E_COMPILE_WARNING, "Unsupported declare '%s'", var->u.constant.value.str.val); zval_dtor(&val->u.constant); } zval_dtor(&var->u.constant); } /* }}} */ void zend_do_declare_end(const znode *declare_token TSRMLS_DC) /* {{{ */ { zend_declarables *declarables; zend_stack_top(&CG(declare_stack), (void **) &declarables); /* We should restore if there was more than (current - start) - (ticks?1:0) opcodes */ if ((get_next_op_number(CG(active_op_array)) - declare_token->u.op.opline_num) - ((Z_LVAL(CG(declarables).ticks))?1:0)) { CG(declarables) = *declarables; } } /* }}} */ void zend_do_exit(znode *result, const znode *message TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXIT; SET_NODE(opline->op1, message); SET_UNUSED(opline->op2); result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_BOOL; Z_LVAL(result->u.constant) = 1; } /* }}} */ void zend_do_begin_silence(znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BEGIN_SILENCE; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); GET_NODE(strudel_token, opline->result); } /* }}} */ void zend_do_end_silence(const znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_END_SILENCE; SET_NODE(opline->op1, strudel_token); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_jmp_set(const znode *value, znode *jmp_token, znode *colon_token TSRMLS_DC) /* {{{ */ { int op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (value->op_type == IS_VAR || value->op_type == IS_CV) { opline->opcode = ZEND_JMP_SET_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_JMP_SET; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, value); SET_UNUSED(opline->op2); GET_NODE(colon_token, opline->result); jmp_token->u.op .opline_num = op_number; INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_jmp_set_else(znode *result, const znode *false_value, const znode *jmp_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, colon_token); if (colon_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].opcode = ZEND_JMP_SET_VAR; CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } opline->extended_value = 0; SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_qm_op(const znode *cond, znode *qm_token TSRMLS_DC) /* {{{ */ { int jmpz_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); SET_UNUSED(opline->op2); opline->op2.opline_num = jmpz_op_number; GET_NODE(qm_token, opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_qm_true(const znode *true_value, znode *qm_token, znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->opcodes[qm_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array))+1; /* jmp over the ZEND_JMP */ if (true_value->op_type == IS_VAR || true_value->op_type == IS_CV) { opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, true_value); SET_UNUSED(opline->op2); GET_NODE(qm_token, opline->result); colon_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_qm_false(znode *result, const znode *false_value, const znode *qm_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, qm_token); if (qm_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].opcode = ZEND_QM_ASSIGN_VAR; CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[colon_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, opline->result); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_extended_info(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_STMT; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_begin(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_BEGIN; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_end(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_END; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_ticks(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_TICKS; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->extended_value = Z_LVAL(CG(declarables).ticks); } /* }}} */ zend_bool zend_is_auto_global_quick(const char *name, uint name_len, ulong hashval TSRMLS_DC) /* {{{ */ { zend_auto_global *auto_global; ulong hash = hashval ? hashval : zend_hash_func(name, name_len+1); if (zend_hash_quick_find(CG(auto_globals), name, name_len+1, hash, (void **) &auto_global)==SUCCESS) { if (auto_global->armed) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } return 1; } return 0; } /* }}} */ zend_bool zend_is_auto_global(const char *name, uint name_len TSRMLS_DC) /* {{{ */ { return zend_is_auto_global_quick(name, name_len, 0 TSRMLS_CC); } /* }}} */ int zend_register_auto_global(const char *name, uint name_len, zend_bool jit, zend_auto_global_callback auto_global_callback TSRMLS_DC) /* {{{ */ { zend_auto_global auto_global; auto_global.name = zend_new_interned_string((char*)name, name_len + 1, 0 TSRMLS_CC); auto_global.name_len = name_len; auto_global.auto_global_callback = auto_global_callback; auto_global.jit = jit; return zend_hash_add(CG(auto_globals), name, name_len+1, &auto_global, sizeof(zend_auto_global), NULL); } /* }}} */ static int zend_auto_global_init(zend_auto_global *auto_global TSRMLS_DC) /* {{{ */ { if (auto_global->jit) { auto_global->armed = 1; } else if (auto_global->auto_global_callback) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } else { auto_global->armed = 0; } return 0; } /* }}} */ ZEND_API void zend_activate_auto_globals(TSRMLS_D) /* {{{ */ { zend_hash_apply(CG(auto_globals), (apply_func_t) zend_auto_global_init TSRMLS_CC); } /* }}} */ int zendlex(znode *zendlval TSRMLS_DC) /* {{{ */ { int retval; if (CG(increment_lineno)) { CG(zend_lineno)++; CG(increment_lineno) = 0; } again: Z_TYPE(zendlval->u.constant) = IS_LONG; retval = lex_scan(&zendlval->u.constant TSRMLS_CC); switch (retval) { case T_COMMENT: case T_DOC_COMMENT: case T_OPEN_TAG: case T_WHITESPACE: goto again; case T_CLOSE_TAG: if (LANG_SCNG(yy_text)[LANG_SCNG(yy_leng)-1] != '>') { CG(increment_lineno) = 1; } if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { goto again; } retval = ';'; /* implicit ; */ break; case T_OPEN_TAG_WITH_ECHO: retval = T_ECHO; break; case T_END_HEREDOC: efree(Z_STRVAL(zendlval->u.constant)); break; } INIT_PZVAL(&zendlval->u.constant); zendlval->op_type = IS_CONST; return retval; } /* }}} */ ZEND_API void zend_initialize_class_data(zend_class_entry *ce, zend_bool nullify_handlers TSRMLS_DC) /* {{{ */ { zend_bool persistent_hashes = (ce->type == ZEND_INTERNAL_CLASS) ? 1 : 0; dtor_func_t zval_ptr_dtor_func = ((persistent_hashes) ? ZVAL_INTERNAL_PTR_DTOR : ZVAL_PTR_DTOR); ce->refcount = 1; ce->ce_flags = 0; ce->default_properties_table = NULL; ce->default_static_members_table = NULL; zend_hash_init_ex(&ce->properties_info, 0, NULL, (dtor_func_t) (persistent_hashes ? zend_destroy_property_info_internal : zend_destroy_property_info), persistent_hashes, 0); zend_hash_init_ex(&ce->constants_table, 0, NULL, zval_ptr_dtor_func, persistent_hashes, 0); zend_hash_init_ex(&ce->function_table, 0, NULL, ZEND_FUNCTION_DTOR, persistent_hashes, 0); if (ce->type == ZEND_INTERNAL_CLASS) { #ifdef ZTS int n = zend_hash_num_elements(CG(class_table)); if (CG(static_members_table) && n >= CG(last_static_member)) { /* Support for run-time declaration: dl() */ CG(last_static_member) = n+1; CG(static_members_table) = realloc(CG(static_members_table), (n+1)*sizeof(zval**)); CG(static_members_table)[n] = NULL; } ce->static_members_table = (zval**)(zend_intptr_t)n; #else ce->static_members_table = NULL; #endif } else { ce->static_members_table = ce->default_static_members_table; ce->info.user.doc_comment = NULL; ce->info.user.doc_comment_len = 0; } ce->default_properties_count = 0; ce->default_static_members_count = 0; if (nullify_handlers) { ce->constructor = NULL; ce->destructor = NULL; ce->clone = NULL; ce->__get = NULL; ce->__set = NULL; ce->__unset = NULL; ce->__isset = NULL; ce->__call = NULL; ce->__callstatic = NULL; ce->__tostring = NULL; ce->create_object = NULL; ce->get_iterator = NULL; ce->iterator_funcs.funcs = NULL; ce->interface_gets_implemented = NULL; ce->get_static_method = NULL; ce->parent = NULL; ce->num_interfaces = 0; ce->interfaces = NULL; ce->num_traits = 0; ce->traits = NULL; ce->trait_aliases = NULL; ce->trait_precedences = NULL; ce->serialize = NULL; ce->unserialize = NULL; ce->serialize_func = NULL; ce->unserialize_func = NULL; if (ce->type == ZEND_INTERNAL_CLASS) { ce->info.internal.module = NULL; ce->info.internal.builtin_functions = NULL; } } } /* }}} */ int zend_get_class_fetch_type(const char *class_name, uint class_name_len) /* {{{ */ { if ((class_name_len == sizeof("self")-1) && !memcmp(class_name, "self", sizeof("self")-1)) { return ZEND_FETCH_CLASS_SELF; } else if ((class_name_len == sizeof("parent")-1) && !memcmp(class_name, "parent", sizeof("parent")-1)) { return ZEND_FETCH_CLASS_PARENT; } else if ((class_name_len == sizeof("static")-1) && !memcmp(class_name, "static", sizeof("static")-1)) { return ZEND_FETCH_CLASS_STATIC; } else { return ZEND_FETCH_CLASS_DEFAULT; } } /* }}} */ ZEND_API const char* zend_get_compiled_variable_name(const zend_op_array *op_array, zend_uint var, int* name_len) /* {{{ */ { if (name_len) { *name_len = op_array->vars[var].name_len; } return op_array->vars[var].name; } /* }}} */ void zend_do_build_namespace_name(znode *result, znode *prefix, znode *name TSRMLS_DC) /* {{{ */ { if (prefix) { *result = *prefix; if (Z_TYPE(result->u.constant) == IS_STRING && Z_STRLEN(result->u.constant) == 0) { /* namespace\ */ if (CG(current_namespace)) { znode tmp; zval_dtor(&result->u.constant); tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(result, NULL, &tmp TSRMLS_CC); } } } else { result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_STRING; Z_STRVAL(result->u.constant) = NULL; Z_STRLEN(result->u.constant) = 0; } /* prefix = result */ zend_do_build_full_name(NULL, result, name, 0 TSRMLS_CC); } /* }}} */ void zend_do_begin_namespace(const znode *name, zend_bool with_bracket TSRMLS_DC) /* {{{ */ { char *lcname; /* handle mixed syntax declaration or nested namespaces */ if (!CG(has_bracketed_namespaces)) { if (CG(current_namespace)) { /* previous namespace declarations were unbracketed */ if (with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } } } else { /* previous namespace declarations were bracketed */ if (!with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } else if (CG(current_namespace) || CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "Namespace declarations cannot be nested"); } } if (((!with_bracket && !CG(current_namespace)) || (with_bracket && !CG(has_bracketed_namespaces))) && CG(active_op_array)->last > 0) { /* ignore ZEND_EXT_STMT and ZEND_TICKS */ int num = CG(active_op_array)->last; while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Namespace declaration statement has to be the very first statement in the script"); } } CG(in_namespace) = 1; if (with_bracket) { CG(has_bracketed_namespaces) = 1; } if (name) { lcname = zend_str_tolower_dup(Z_STRVAL(name->u.constant), Z_STRLEN(name->u.constant)); if (((Z_STRLEN(name->u.constant) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN(name->u.constant) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as namespace name", Z_STRVAL(name->u.constant)); } efree(lcname); if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); } else { ALLOC_ZVAL(CG(current_namespace)); } *CG(current_namespace) = name->u.constant; } else { if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_use(znode *ns_name, znode *new_name, int is_global TSRMLS_DC) /* {{{ */ { char *lcname; zval *name, *ns, tmp; zend_bool warn = 0; zend_class_entry **pce; if (!CG(current_import)) { CG(current_import) = emalloc(sizeof(HashTable)); zend_hash_init(CG(current_import), 0, NULL, ZVAL_PTR_DTOR, 0); } ALLOC_ZVAL(ns); *ns = ns_name->u.constant; if (new_name) { name = &new_name->u.constant; } else { const char *p; /* The form "use A\B" is eqivalent to "use A\B as B". So we extract the last part of compound name to use as a new_name */ name = &tmp; p = zend_memrchr(Z_STRVAL_P(ns), '\\', Z_STRLEN_P(ns)); if (p) { ZVAL_STRING(name, p+1, 1); } else { *name = *ns; zval_copy_ctor(name); warn = !is_global && !CG(current_namespace); } } lcname = zend_str_tolower_dup(Z_STRVAL_P(name), Z_STRLEN_P(name)); if (((Z_STRLEN_P(name) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN_P(name) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because '%s' is a special class name", Z_STRVAL_P(ns), Z_STRVAL_P(name), Z_STRVAL_P(name)); } if (CG(current_namespace)) { /* Prefix import name with current namespace name to avoid conflicts with classes */ char *c_ns_name = emalloc(Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) + 1); zend_str_tolower_copy(c_ns_name, Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); c_ns_name[Z_STRLEN_P(CG(current_namespace))] = '\\'; memcpy(c_ns_name+Z_STRLEN_P(CG(current_namespace))+1, lcname, Z_STRLEN_P(name)+1); if (zend_hash_exists(CG(class_table), c_ns_name, Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name)+1)) { char *tmp2 = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) || memcmp(tmp2, c_ns_name, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(tmp2); } efree(c_ns_name); } else if (zend_hash_find(CG(class_table), lcname, Z_STRLEN_P(name)+1, (void**)&pce) == SUCCESS && (*pce)->type == ZEND_USER_CLASS && (*pce)->info.user.filename == CG(compiled_filename)) { char *c_tmp = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(name) || memcmp(c_tmp, lcname, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(c_tmp); } if (zend_hash_add(CG(current_import), lcname, Z_STRLEN_P(name)+1, &ns, sizeof(zval*), NULL) != SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } if (warn) { if (!strcmp(Z_STRVAL_P(name), "strict")) { zend_error(E_COMPILE_ERROR, "You seem to be trying to use a different language..."); } zend_error(E_WARNING, "The use statement with non-compound name '%s' has no effect", Z_STRVAL_P(name)); } efree(lcname); zval_dtor(name); } /* }}} */ void zend_do_declare_constant(znode *name, znode *value TSRMLS_DC) /* {{{ */ { zend_op *opline; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed as constants"); } if (zend_get_ct_const(&name->u.constant, 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare constant '%s'", Z_STRVAL(name->u.constant)); } if (CG(current_namespace)) { /* Prefix constant name with name of current namespace, lowercased */ znode tmp; tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); Z_STRVAL(tmp.u.constant) = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), Z_STRLEN(tmp.u.constant)); zend_do_build_namespace_name(&tmp, &tmp, name TSRMLS_CC); *name = tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DECLARE_CONST; SET_UNUSED(opline->result); SET_NODE(opline->op1, name); SET_NODE(opline->op2, value); } /* }}} */ void zend_verify_namespace(TSRMLS_D) /* {{{ */ { if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "No code may exist outside of namespace {}"); } } /* }}} */ void zend_do_end_namespace(TSRMLS_D) /* {{{ */ { CG(in_namespace) = 0; if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_end_compilation(TSRMLS_D) /* {{{ */ { CG(has_bracketed_namespaces) = 0; zend_do_end_namespace(TSRMLS_C); } /* }}} */ /* {{{ zend_dirname Returns directory name component of path */ ZEND_API size_t zend_dirname(char *path, size_t len) { register char *end = path + len - 1; unsigned int len_adjust = 0; #ifdef PHP_WIN32 /* Note that on Win32 CWD is per drive (heritage from CP/M). * This means dirname("c:foo") maps to "c:." or "c:" - which means CWD on C: drive. */ if ((2 <= len) && isalpha((int)((unsigned char *)path)[0]) && (':' == path[1])) { /* Skip over the drive spec (if any) so as not to change */ path += 2; len_adjust += 2; if (2 == len) { /* Return "c:" on Win32 for dirname("c:"). * It would be more consistent to return "c:." * but that would require making the string *longer*. */ return len; } } #elif defined(NETWARE) /* * Find the first occurence of : from the left * move the path pointer to the position just after : * increment the len_adjust to the length of path till colon character(inclusive) * If there is no character beyond : simple return len */ char *colonpos = NULL; colonpos = strchr(path, ':'); if (colonpos != NULL) { len_adjust = ((colonpos - path) + 1); path += len_adjust; if (len_adjust == len) { return len; } } #endif if (len == 0) { /* Illegal use of this function */ return 0; } /* Strip trailing slashes */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { /* The path only contained slashes */ path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } /* Strip filename */ while (end >= path && !IS_SLASH_P(end)) { end--; } if (end < path) { /* No slash found, therefore return '.' */ #ifdef NETWARE if (len_adjust == 0) { path[0] = '.'; path[1] = '\0'; return 1; /* only one character */ } else { path[0] = '\0'; return len_adjust; } #else path[0] = '.'; path[1] = '\0'; return 1 + len_adjust; #endif } /* Strip slashes which came before the file name */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } *(end+1) = '\0'; return (size_t)(end + 1 - path) + len_adjust; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */ /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <zend_language_parser.h> #include "zend.h" #include "zend_compile.h" #include "zend_constants.h" #include "zend_llist.h" #include "zend_API.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "zend_multibyte.h" #include "zend_language_scanner.h" #define CONSTANT_EX(op_array, op) \ (op_array)->literals[op].constant #define CONSTANT(op) \ CONSTANT_EX(CG(active_op_array), op) #define SET_NODE(target, src) do { \ target ## _type = (src)->op_type; \ if ((src)->op_type == IS_CONST) { \ target.constant = zend_add_literal(CG(active_op_array), &(src)->u.constant TSRMLS_CC); \ } else { \ target = (src)->u.op; \ } \ } while (0) #define GET_NODE(target, src) do { \ (target)->op_type = src ## _type; \ if ((target)->op_type == IS_CONST) { \ (target)->u.constant = CONSTANT(src.constant); \ } else { \ (target)->u.op = src; \ (target)->EA = 0; \ } \ } while (0) #define COPY_NODE(target, src) do { \ target ## _type = src ## _type; \ target = src; \ } while (0) #define CALCULATE_LITERAL_HASH(num) do { \ if (IS_INTERNED(Z_STRVAL(CONSTANT(num)))) { \ Z_HASH_P(&CONSTANT(num)) = INTERNED_HASH(Z_STRVAL(CONSTANT(num))); \ } else { \ Z_HASH_P(&CONSTANT(num)) = zend_hash_func(Z_STRVAL(CONSTANT(num)), Z_STRLEN(CONSTANT(num))+1); \ } \ } while (0) #define GET_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot++; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ } \ } while (0) #define POLYMORPHIC_CACHE_SLOT_SIZE 2 #define GET_POLYMORPHIC_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot; \ CG(active_op_array)->last_cache_slot += POLYMORPHIC_CACHE_SLOT_SIZE; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 2] = NULL; \ } \ } while (0) #define FREE_POLYMORPHIC_CACHE_SLOT(literal) do { \ if (CG(active_op_array)->literals[literal].cache_slot == \ CG(active_op_array)->last_cache_slot - POLYMORPHIC_CACHE_SLOT_SIZE) { \ CG(active_op_array)->literals[literal].cache_slot = -1; \ CG(active_op_array)->last_cache_slot -= POLYMORPHIC_CACHE_SLOT_SIZE; \ } \ } while (0) ZEND_API zend_op_array *(*zend_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); ZEND_API zend_op_array *(*zend_compile_string)(zval *source_string, char *filename TSRMLS_DC); #ifndef ZTS ZEND_API zend_compiler_globals compiler_globals; ZEND_API zend_executor_globals executor_globals; #endif static void zend_duplicate_property_info(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = estrndup(property_info->name, property_info->name_length); } if (property_info->doc_comment) { property_info->doc_comment = estrndup(property_info->doc_comment, property_info->doc_comment_len); } } /* }}} */ static void zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = zend_strndup(property_info->name, property_info->name_length); } } /* }}} */ static void zend_destroy_property_info(zend_property_info *property_info) /* {{{ */ { str_efree(property_info->name); if (property_info->doc_comment) { efree((char*)property_info->doc_comment); } } /* }}} */ static void zend_destroy_property_info_internal(zend_property_info *property_info) /* {{{ */ { str_free((char*)property_info->name); } /* }}} */ static void build_runtime_defined_function_key(zval *result, const char *name, int name_length TSRMLS_DC) /* {{{ */ { char char_pos_buf[32]; uint char_pos_len; const char *filename; char_pos_len = zend_sprintf(char_pos_buf, "%p", LANG_SCNG(yy_text)); if (CG(active_op_array)->filename) { filename = CG(active_op_array)->filename; } else { filename = "-"; } /* NULL, name length, filename length, last accepting char position length */ result->value.str.len = 1+name_length+strlen(filename)+char_pos_len; /* must be binary safe */ result->value.str.val = (char *) safe_emalloc(result->value.str.len, 1, 1); result->value.str.val[0] = '\0'; sprintf(result->value.str.val+1, "%s%s%s", name, filename, char_pos_buf); result->type = IS_STRING; Z_SET_REFCOUNT_P(result, 1); } /* }}} */ static void init_compiler_declarables(TSRMLS_D) /* {{{ */ { Z_TYPE(CG(declarables).ticks) = IS_LONG; Z_LVAL(CG(declarables).ticks) = 0; } /* }}} */ void zend_init_compiler_context(TSRMLS_D) /* {{{ */ { CG(context).opcodes_size = (CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) ? INITIAL_INTERACTIVE_OP_ARRAY_SIZE : INITIAL_OP_ARRAY_SIZE; CG(context).vars_size = 0; CG(context).literals_size = 0; CG(context).current_brk_cont = -1; CG(context).backpatch_count = 0; CG(context).labels = NULL; } /* }}} */ void zend_init_compiler_data_structures(TSRMLS_D) /* {{{ */ { zend_stack_init(&CG(bp_stack)); zend_stack_init(&CG(function_call_stack)); zend_stack_init(&CG(switch_cond_stack)); zend_stack_init(&CG(foreach_copy_stack)); zend_stack_init(&CG(object_stack)); zend_stack_init(&CG(declare_stack)); CG(active_class_entry) = NULL; zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_stack_init(&CG(list_stack)); CG(in_compilation) = 0; CG(start_lineno) = 0; CG(current_namespace) = NULL; CG(in_namespace) = 0; CG(has_bracketed_namespaces) = 0; CG(current_import) = NULL; init_compiler_declarables(TSRMLS_C); zend_stack_init(&CG(context_stack)); CG(encoding_declared) = 0; } /* }}} */ ZEND_API void file_handle_dtor(zend_file_handle *fh) /* {{{ */ { TSRMLS_FETCH(); zend_file_handle_dtor(fh TSRMLS_CC); } /* }}} */ void init_compiler(TSRMLS_D) /* {{{ */ { CG(active_op_array) = NULL; zend_init_compiler_data_structures(TSRMLS_C); zend_init_rsrc_list(TSRMLS_C); zend_hash_init(&CG(filenames_table), 5, NULL, (dtor_func_t) free_estring, 0); zend_llist_init(&CG(open_files), sizeof(zend_file_handle), (void (*)(void *)) file_handle_dtor, 0); CG(unclean_shutdown) = 0; } /* }}} */ void shutdown_compiler(TSRMLS_D) /* {{{ */ { zend_stack_destroy(&CG(bp_stack)); zend_stack_destroy(&CG(function_call_stack)); zend_stack_destroy(&CG(switch_cond_stack)); zend_stack_destroy(&CG(foreach_copy_stack)); zend_stack_destroy(&CG(object_stack)); zend_stack_destroy(&CG(declare_stack)); zend_stack_destroy(&CG(list_stack)); zend_hash_destroy(&CG(filenames_table)); zend_llist_destroy(&CG(open_files)); zend_stack_destroy(&CG(context_stack)); } /* }}} */ ZEND_API char *zend_set_compiled_filename(const char *new_compiled_filename TSRMLS_DC) /* {{{ */ { char **pp, *p; int length = strlen(new_compiled_filename); if (zend_hash_find(&CG(filenames_table), new_compiled_filename, length+1, (void **) &pp) == SUCCESS) { CG(compiled_filename) = *pp; return *pp; } p = estrndup(new_compiled_filename, length); zend_hash_update(&CG(filenames_table), new_compiled_filename, length+1, &p, sizeof(char *), (void **) &pp); CG(compiled_filename) = p; return p; } /* }}} */ ZEND_API void zend_restore_compiled_filename(char *original_compiled_filename TSRMLS_DC) /* {{{ */ { CG(compiled_filename) = original_compiled_filename; } /* }}} */ ZEND_API char *zend_get_compiled_filename(TSRMLS_D) /* {{{ */ { return CG(compiled_filename); } /* }}} */ ZEND_API int zend_get_compiled_lineno(TSRMLS_D) /* {{{ */ { return CG(zend_lineno); } /* }}} */ ZEND_API zend_bool zend_is_compiling(TSRMLS_D) /* {{{ */ { return CG(in_compilation); } /* }}} */ static zend_uint get_temporary_variable(zend_op_array *op_array) /* {{{ */ { return (op_array->T)++ * ZEND_MM_ALIGNED_SIZE(sizeof(temp_variable)); } /* }}} */ static int lookup_cv(zend_op_array *op_array, char* name, int name_len, ulong hash TSRMLS_DC) /* {{{ */ { int i = 0; ulong hash_value = hash ? hash : zend_inline_hash_func(name, name_len+1); while (i < op_array->last_var) { if (op_array->vars[i].name == name || (op_array->vars[i].hash_value == hash_value && op_array->vars[i].name_len == name_len && memcmp(op_array->vars[i].name, name, name_len) == 0)) { str_efree(name); return i; } i++; } i = op_array->last_var; op_array->last_var++; if (op_array->last_var > CG(context).vars_size) { CG(context).vars_size += 16; /* FIXME */ op_array->vars = erealloc(op_array->vars, CG(context).vars_size * sizeof(zend_compiled_variable)); } op_array->vars[i].name = zend_new_interned_string(name, name_len + 1, 1 TSRMLS_CC); op_array->vars[i].name_len = name_len; op_array->vars[i].hash_value = hash_value; return i; } /* }}} */ void zend_del_literal(zend_op_array *op_array, int n) /* {{{ */ { zval_dtor(&CONSTANT_EX(op_array, n)); if (n + 1 == op_array->last_literal) { op_array->last_literal--; } else { Z_TYPE(CONSTANT_EX(op_array, n)) = IS_NULL; } } /* }}} */ /* Common part of zend_add_literal and zend_append_individual_literal */ static inline void zend_insert_literal(zend_op_array *op_array, const zval *zv, int literal_position TSRMLS_DC) /* {{{ */ { if (Z_TYPE_P(zv) == IS_STRING || Z_TYPE_P(zv) == IS_CONSTANT) { zval *z = (zval*)zv; Z_STRVAL_P(z) = (char*)zend_new_interned_string(Z_STRVAL_P(zv), Z_STRLEN_P(zv) + 1, 1 TSRMLS_CC); } CONSTANT_EX(op_array, literal_position) = *zv; Z_SET_REFCOUNT(CONSTANT_EX(op_array, literal_position), 2); Z_SET_ISREF(CONSTANT_EX(op_array, literal_position)); op_array->literals[literal_position].hash_value = 0; op_array->literals[literal_position].cache_slot = -1; } /* }}} */ /* Is used while compiling a function, using the context to keep track of an approximate size to avoid to relocate to often. Literals are truncated to actual size in the second compiler pass (pass_two()). */ int zend_add_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; if (i >= CG(context).literals_size) { while (i >= CG(context).literals_size) { CG(context).literals_size += 16; /* FIXME */ } op_array->literals = (zend_literal*)erealloc(op_array->literals, CG(context).literals_size * sizeof(zend_literal)); } zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ /* Is used after normal compilation to append an additional literal. Allocation is done precisely here. */ int zend_append_individual_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; op_array->literals = (zend_literal*)erealloc(op_array->literals, (i + 1) * sizeof(zend_literal)); zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ int zend_add_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_ns_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; const char *ns_separator; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); ns_separator = (const char*)zend_memrchr(Z_STRVAL_P(zv), '\\', Z_STRLEN_P(zv)) + 1; lc_len = Z_STRLEN_P(zv) - (ns_separator - Z_STRVAL_P(zv)); lc_name = zend_str_tolower_dup(ns_separator, lc_len); ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_class_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } if (Z_STRVAL_P(zv)[0] == '\\') { lc_len = Z_STRLEN_P(zv) - 1; lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv) + 1, lc_len); } else { lc_len = Z_STRLEN_P(zv); lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), lc_len); } ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); GET_CACHE_SLOT(ret); return ret; } /* }}} */ int zend_add_const_name_literal(zend_op_array *op_array, const zval *zv, int unqualified TSRMLS_DC) /* {{{ */ { int ret, tmp_literal; char *name, *tmp_name; const char *ns_separator; int name_len, ns_len; zval c; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } /* skip leading '\\' */ if (Z_STRVAL_P(zv)[0] == '\\') { name_len = Z_STRLEN_P(zv) - 1; name = Z_STRVAL_P(zv) + 1; } else { name_len = Z_STRLEN_P(zv); name = Z_STRVAL_P(zv); } ns_separator = zend_memrchr(name, '\\', name_len); if (ns_separator) { ns_len = ns_separator - name; } else { ns_len = 0; } if (ns_len) { /* lowercased namespace name & original constant name */ tmp_name = estrndup(name, name_len); zend_str_tolower(tmp_name, ns_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased namespace name & lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); } if (ns_len) { if (!unqualified) { return ret; } ns_len++; name += ns_len; name_len -= ns_len; } /* original constant name */ tmp_name = estrndup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); return ret; } /* }}} */ #define LITERAL_STRINGL(op, str, len, copy) do { \ zval _c; \ ZVAL_STRINGL(&_c, str, len, copy); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG(op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG_EX(op_array, op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(op_array, &_c TSRMLS_CC); \ } while (0) #define LITERAL_NULL(op) do { \ zval _c; \ INIT_ZVAL( _c); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) static inline zend_bool zend_is_function_or_method_call(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; return ((type & ZEND_PARSED_METHOD_CALL) || (type == ZEND_PARSED_FUNCTION_CALL)); } /* }}} */ void zend_do_binary_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_unary_op(zend_uchar op, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); GET_NODE(result, opline->result); SET_UNUSED(opline->op2); } /* }}} */ #define MAKE_NOP(opline) { opline->opcode = ZEND_NOP; memset(&opline->result,0,sizeof(opline->result)); memset(&opline->op1,0,sizeof(opline->op1)); memset(&opline->op2,0,sizeof(opline->op2)); opline->result_type=opline->op1_type=opline->op2_type=IS_UNUSED; } static void zend_do_op_data(zend_op *data_op, const znode *value TSRMLS_DC) /* {{{ */ { data_op->opcode = ZEND_OP_DATA; SET_NODE(data_op->op1, value); SET_UNUSED(data_op->op2); } /* }}} */ void zend_do_binary_assign_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; switch (last_op->opcode) { case ZEND_FETCH_OBJ_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, op2 TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; case ZEND_FETCH_DIM_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_DIM; zend_do_op_data(opline, op2 TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result,last_op->result); return; default: break; } } opline->opcode = op; SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void fetch_simple_variable_ex(znode *result, znode *varname, int bp, zend_uchar op TSRMLS_DC) /* {{{ */ { zend_op opline; zend_op *opline_ptr; zend_llist *fetch_list_ptr; if (varname->op_type == IS_CONST) { ulong hash = 0; if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } else if (IS_INTERNED(Z_STRVAL(varname->u.constant))) { hash = INTERNED_HASH(Z_STRVAL(varname->u.constant)); } if (!zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC) && !(varname->u.constant.value.str.len == (sizeof("this")-1) && !memcmp(varname->u.constant.value.str.val, "this", sizeof("this"))) && (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE)) { result->op_type = IS_CV; result->u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC); varname->u.constant.value.str.val = (char*)CG(active_op_array)->vars[result->u.op.var].name; result->EA = 0; return; } } if (bp) { opline_ptr = &opline; init_op(opline_ptr TSRMLS_CC); } else { opline_ptr = get_next_op(CG(active_op_array) TSRMLS_CC); } opline_ptr->opcode = op; opline_ptr->result_type = IS_VAR; opline_ptr->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline_ptr->op1, varname); GET_NODE(result, opline_ptr->result); SET_UNUSED(opline_ptr->op2); opline_ptr->extended_value = ZEND_FETCH_LOCAL; if (varname->op_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline_ptr->op1.constant); if (zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC)) { opline_ptr->extended_value = ZEND_FETCH_GLOBAL; } } if (bp) { zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); zend_llist_add_element(fetch_list_ptr, opline_ptr); } } /* }}} */ void fetch_simple_variable(znode *result, znode *varname, int bp TSRMLS_DC) /* {{{ */ { /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ fetch_simple_variable_ex(result, varname, bp, ZEND_FETCH_W TSRMLS_CC); } /* }}} */ void zend_do_fetch_static_member(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { znode class_node; zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline_ptr; zend_op opline; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); } zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (result->op_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[result->u.op.var].name), CG(active_op_array)->vars[result->u.op.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } GET_NODE(result,opline.result); opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; opline_ptr = &opline; zend_llist_add_element(fetch_list_ptr, &opline); } else { le = fetch_list_ptr->head; opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode != ZEND_FETCH_W && opline_ptr->op1_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[opline_ptr->op1.var].name), CG(active_op_array)->vars[opline_ptr->op1.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; COPY_NODE(opline_ptr->op1, opline.result); zend_llist_prepend_element(fetch_list_ptr, &opline); } else { if (opline_ptr->op1_type == IS_CONST) { GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op1.constant); } if (class_node.op_type == IS_CONST) { opline_ptr->op2_type = IS_CONST; opline_ptr->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline_ptr->op2, &class_node); } opline_ptr->extended_value |= ZEND_FETCH_STATIC_MEMBER; } } } /* }}} */ void fetch_array_begin(znode *result, znode *varname, znode *first_dim TSRMLS_DC) /* {{{ */ { fetch_simple_variable(result, varname, 1 TSRMLS_CC); fetch_array_dim(result, result, first_dim TSRMLS_CC); } /* }}} */ void fetch_array_dim(znode *result, const znode *parent, const znode *dim TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (zend_is_function_or_method_call(parent)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, parent); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_DIM_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, parent); SET_NODE(opline.op2, dim); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline.op2.constant)), Z_STRLEN(CONSTANT(opline.op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline.op2.constant)); ZVAL_LONG(&CONSTANT(opline.op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline.op2.constant); } } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void fetch_string_offset(znode *result, const znode *parent, const znode *offset TSRMLS_DC) /* {{{ */ { fetch_array_dim(result, parent, offset TSRMLS_CC); } /* }}} */ void zend_do_print(znode *result, const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->opcode = ZEND_PRINT; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_echo(const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ECHO; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_abstract_method(const znode *function_name, znode *modifiers, const znode *body TSRMLS_DC) /* {{{ */ { char *method_type; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { Z_LVAL(modifiers->u.constant) |= ZEND_ACC_ABSTRACT; method_type = "Interface"; } else { method_type = "Abstract"; } if (modifiers->u.constant.value.lval & ZEND_ACC_ABSTRACT) { if(modifiers->u.constant.value.lval & ZEND_ACC_PRIVATE) { zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot be declared private", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } if (Z_LVAL(body->u.constant) == ZEND_ACC_ABSTRACT) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_RAISE_ABSTRACT_ERROR; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } else { /* we had code in the function body */ zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot contain body", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } else { if (body->u.constant.value.lval == ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Non-abstract method %s::%s() must contain body", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } } /* }}} */ static zend_bool opline_is_fetch_this(const zend_op *opline TSRMLS_DC) /* {{{ */ { if ((opline->opcode == ZEND_FETCH_W) && (opline->op1_type == IS_CONST) && (Z_TYPE(CONSTANT(opline->op1.constant)) == IS_STRING) && (Z_HASH_P(&CONSTANT(opline->op1.constant)) == THIS_HASHVAL) && (Z_STRLEN(CONSTANT(opline->op1.constant)) == (sizeof("this")-1)) && !memcmp(Z_STRVAL(CONSTANT(opline->op1.constant)), "this", sizeof("this"))) { return 1; } else { return 0; } } /* }}} */ void zend_do_assign(znode *result, znode *variable, znode *value TSRMLS_DC) /* {{{ */ { int last_op_number; zend_op *opline; if (value->op_type == IS_CV) { zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (fetch_list_ptr && fetch_list_ptr->head) { opline = (zend_op *)fetch_list_ptr->head->data; if (opline->opcode == ZEND_FETCH_DIM_W && opline->op1_type == IS_CV && opline->op1.var == value->u.op.var) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_R; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->op1_type = IS_CONST; LITERAL_STRINGL(opline->op1, CG(active_op_array)->vars[value->u.op.var].name, CG(active_op_array)->vars[value->u.op.var].name_len, 1); CALCULATE_LITERAL_HASH(opline->op1.constant); SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_LOCAL; GET_NODE(value, opline->result); } } } zend_do_end_variable_parse(variable, BP_VAR_W, 0 TSRMLS_CC); last_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (variable->op_type == IS_CV) { if (variable->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (variable->op_type == IS_VAR) { int n = 0; while (last_op_number - n > 0) { zend_op *last_op; last_op = &CG(active_op_array)->opcodes[last_op_number-n-1]; if (last_op->result_type == IS_VAR && last_op->result.var == variable->u.op.var) { if (last_op->opcode == ZEND_FETCH_OBJ_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, value TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (last_op->opcode == ZEND_FETCH_DIM_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ /* TBFixed: this can realloc opcodes, leaving last_op pointing wrong */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_DIM; zend_do_op_data(opline, value TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (opline_is_fetch_this(last_op TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } else { break; } } n++; } } opline->opcode = ZEND_ASSIGN; SET_NODE(opline->op1, variable); SET_NODE(opline->op2, value); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_assign_ref(znode *result, const znode *lvar, const znode *rvar TSRMLS_DC) /* {{{ */ { zend_op *opline; if (lvar->op_type == IS_CV) { if (lvar->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (lvar->op_type == IS_VAR) { int last_op_number = get_next_op_number(CG(active_op_array)); if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline_is_fetch_this(opline TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ASSIGN_REF; if (zend_is_function_or_method_call(rvar)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } else if (rvar->EA & ZEND_PARSED_NEW) { opline->extended_value = ZEND_RETURNS_NEW; } else { opline->extended_value = 0; } if (result) { opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } else { opline->result_type = IS_UNUSED | EXT_TYPE_UNUSED; } SET_NODE(opline->op1, lvar); SET_NODE(opline->op2, rvar); } /* }}} */ static inline void do_begin_loop(TSRMLS_D) /* {{{ */ { zend_brk_cont_element *brk_cont_element; int parent; parent = CG(context).current_brk_cont; CG(context).current_brk_cont = CG(active_op_array)->last_brk_cont; brk_cont_element = get_next_brk_cont_element(CG(active_op_array)); brk_cont_element->start = get_next_op_number(CG(active_op_array)); brk_cont_element->parent = parent; } /* }}} */ static inline void do_end_loop(int cont_addr, int has_loop_var TSRMLS_DC) /* {{{ */ { if (!has_loop_var) { /* The start fileld is used to free temporary variables in case of exceptions. * We won't try to free something of we don't have loop variable. */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].start = -1; } CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = cont_addr; CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; } /* }}} */ void zend_do_while_cond(const znode *expr, znode *close_bracket_token TSRMLS_DC) /* {{{ */ { int while_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, expr); close_bracket_token->u.op.opline_num = while_cond_op_number; SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_while_end(const znode *while_token, const znode *close_bracket_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* add unconditional jump */ opline->opcode = ZEND_JMP; opline->op1.opline_num = while_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* update while's conditional jmp */ CG(active_op_array)->opcodes[close_bracket_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); do_end_loop(while_token->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_cond(const znode *expr, znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { int for_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZNZ; SET_NODE(opline->op1, expr); /* the conditional expression */ second_semicolon_token->u.op.opline_num = for_cond_op_number; SET_UNUSED(opline->op2); } /* }}} */ void zend_do_for_before_statement(const znode *cond_start, const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = cond_start->u.op.opline_num; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_end(const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = second_semicolon_token->u.op.opline_num+1; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_end_loop(second_semicolon_token->u.op.opline_num+1, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_pre_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_PRE_INC)?ZEND_PRE_INC_OBJ:ZEND_PRE_DEC_OBJ; last_op->result_type = IS_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_post_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_POST_INC)?ZEND_POST_INC_OBJ:ZEND_POST_DEC_OBJ; last_op->result_type = IS_TMP_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_if_cond(const znode *cond, znode *closing_bracket_token TSRMLS_DC) /* {{{ */ { int if_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); closing_bracket_token->u.op.opline_num = if_cond_op_number; SET_UNUSED(opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_if_after_statement(const znode *closing_bracket_token, unsigned char initialize TSRMLS_DC) /* {{{ */ { int if_end_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; /* save for backpatching */ if (initialize) { zend_llist jmp_list; zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); } zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &if_end_op_number); CG(active_op_array)->opcodes[closing_bracket_token->u.op.opline_num].op2.opline_num = if_end_op_number+1; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_if_end(TSRMLS_D) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_llist *jmp_list_ptr; zend_llist_element *le; zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); for (le=jmp_list_ptr->head; le; le = le->next) { CG(active_op_array)->opcodes[*((int *) le->data)].op1.opline_num = next_op_number; } zend_llist_destroy(jmp_list_ptr); zend_stack_del_top(&CG(bp_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_check_writable_variable(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; if (type & ZEND_PARSED_METHOD_CALL) { zend_error(E_COMPILE_ERROR, "Can't use method return value in write context"); } if (type == ZEND_PARSED_FUNCTION_CALL) { zend_error(E_COMPILE_ERROR, "Can't use function return value in write context"); } } /* }}} */ void zend_do_begin_variable_parse(TSRMLS_D) /* {{{ */ { zend_llist fetch_list; zend_llist_init(&fetch_list, sizeof(zend_op), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &fetch_list, sizeof(zend_llist)); } /* }}} */ void zend_do_end_variable_parse(znode *variable, int type, int arg_offset TSRMLS_DC) /* {{{ */ { zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline = NULL; zend_op *opline_ptr; zend_uint this_var = -1; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); le = fetch_list_ptr->head; /* TODO: $foo->x->y->z = 1 should fetch "x" and "y" for R or RW, not just W */ if (le) { opline_ptr = (zend_op *)le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { /* convert to FETCH_?(this) into IS_CV */ if (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE) { this_var = opline_ptr->result.var; if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), Z_STRVAL(CONSTANT(opline_ptr->op1.constant)), Z_STRLEN(CONSTANT(opline_ptr->op1.constant)), Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC); Z_TYPE(CONSTANT(opline_ptr->op1.constant)) = IS_NULL; } else { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); } le = le->next; if (variable->op_type == IS_VAR && variable->u.op.var == this_var) { variable->op_type = IS_CV; variable->u.op.var = CG(active_op_array)->this_var; } } else if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } while (le) { opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode == ZEND_SEPARATE) { if (type != BP_VAR_R && type != BP_VAR_IS) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); } le = le->next; continue; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); if (opline->op1_type == IS_VAR && opline->op1.var == this_var) { opline->op1_type = IS_CV; opline->op1.var = CG(active_op_array)->this_var; } switch (type) { case BP_VAR_R: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode -= 3; break; case BP_VAR_W: break; case BP_VAR_RW: opline->opcode += 3; break; case BP_VAR_IS: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode += 6; /* 3+3 */ break; case BP_VAR_FUNC_ARG: opline->opcode += 9; /* 3+3+3 */ opline->extended_value |= arg_offset; break; case BP_VAR_UNSET: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for unsetting"); } opline->opcode += 12; /* 3+3+3+3 */ break; } le = le->next; } if (opline && type == BP_VAR_W && arg_offset) { opline->extended_value |= ZEND_FETCH_MAKE_REF; } } zend_llist_destroy(fetch_list_ptr); zend_stack_del_top(&CG(bp_stack)); } /* }}} */ void zend_do_add_string(znode *result, const znode *op1, znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline; if (Z_STRLEN(op2->u.constant) > 1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_STRING; } else if (Z_STRLEN(op2->u.constant) == 1) { int ch = *Z_STRVAL(op2->u.constant); /* Free memory and use ZEND_ADD_CHAR in case of 1 character strings */ efree(Z_STRVAL(op2->u.constant)); ZVAL_LONG(&op2->u.constant, ch); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_CHAR; } else { /* String can be empty after a variable at the end of a heredoc */ efree(Z_STRVAL(op2->u.constant)); return; } if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_add_variable(znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_VAR; if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_free(znode *op1 TSRMLS_DC) /* {{{ */ { if (op1->op_type==IS_TMP_VAR) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else if (op1->op_type==IS_VAR) { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; while (opline->opcode == ZEND_END_SILENCE || opline->opcode == ZEND_EXT_FCALL_END || opline->opcode == ZEND_OP_DATA) { opline--; } if (opline->result_type == IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_FETCH_R || opline->opcode == ZEND_FETCH_DIM_R || opline->opcode == ZEND_FETCH_OBJ_R || opline->opcode == ZEND_QM_ASSIGN_VAR) { /* It's very rare and useless case. It's better to use additional FREE opcode and simplify the FETCH handlers their selves */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else { opline->result_type |= EXT_TYPE_UNUSED; } } else { while (opline>CG(active_op_array)->opcodes) { if (opline->opcode == ZEND_FETCH_DIM_R && opline->op1_type == IS_VAR && opline->op1.var == op1->u.op.var) { /* This should the end of a list() construct * Mark its result as unused */ opline->extended_value = ZEND_FETCH_STANDARD; break; } else if (opline->result_type==IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_NEW) { opline->result_type |= EXT_TYPE_UNUSED; } break; } opline--; } } } else if (op1->op_type == IS_CONST) { zval_dtor(&op1->u.constant); } } /* }}} */ int zend_do_verify_access_types(const znode *current_access_type, const znode *new_modifier) /* {{{ */ { if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_PPP_MASK) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Multiple access type modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_ABSTRACT) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Multiple abstract modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_STATIC) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Multiple static modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_FINAL) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Multiple final modifiers are not allowed"); } if (((Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)) & (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) == (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Cannot use the final modifier on an abstract class member"); } return (Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)); } /* }}} */ void zend_do_begin_function_declaration(znode *function_token, znode *function_name, int is_method, int return_reference, znode *fn_flags_znode TSRMLS_DC) /* {{{ */ { zend_op_array op_array; char *name = function_name->u.constant.value.str.val; int name_len = function_name->u.constant.value.str.len; int function_begin_line = function_token->u.op.opline_num; zend_uint fn_flags; const char *lcname; zend_bool orig_interactive; ALLOCA_FLAG(use_heap) if (is_method) { if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((Z_LVAL(fn_flags_znode->u.constant) & ~(ZEND_ACC_STATIC|ZEND_ACC_PUBLIC))) { zend_error(E_COMPILE_ERROR, "Access type for interface method %s::%s() must be omitted", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } Z_LVAL(fn_flags_znode->u.constant) |= ZEND_ACC_ABSTRACT; /* propagates to the rest of the parser */ } fn_flags = Z_LVAL(fn_flags_znode->u.constant); /* must be done *after* the above check */ } else { fn_flags = 0; } if ((fn_flags & ZEND_ACC_STATIC) && (fn_flags & ZEND_ACC_ABSTRACT) && !(CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_STRICT, "Static function %s%s%s() should not be abstract", is_method ? CG(active_class_entry)->name : "", is_method ? "::" : "", Z_STRVAL(function_name->u.constant)); } function_token->u.op_array = CG(active_op_array); orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(&op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; op_array.function_name = name; if (return_reference) { op_array.fn_flags |= ZEND_ACC_RETURN_REFERENCE; } op_array.fn_flags |= fn_flags; op_array.scope = is_method?CG(active_class_entry):NULL; op_array.prototype = NULL; op_array.line_start = zend_get_compiled_lineno(TSRMLS_C); if (is_method) { int result; lcname = zend_new_interned_string(zend_str_tolower_dup(name, name_len), name_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lcname)) { result = zend_hash_quick_add(&CG(active_class_entry)->function_table, lcname, name_len+1, INTERNED_HASH(lcname), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } else { result = zend_hash_add(&CG(active_class_entry)->function_table, lcname, name_len+1, &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } if (result == FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::%s()", CG(active_class_entry)->name, name); } zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); if (fn_flags & ZEND_ACC_ABSTRACT) { CG(active_class_entry)->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (!(fn_flags & ZEND_ACC_PPP_MASK)) { fn_flags |= ZEND_ACC_PUBLIC; } if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } } } else { char *class_lcname; class_lcname = do_alloca(CG(active_class_entry)->name_length + 1, use_heap); zend_str_tolower_copy(class_lcname, CG(active_class_entry)->name, CG(active_class_entry)->name_length); /* Improve after RC: cache the lowercase class name */ if ((CG(active_class_entry)->name_length == name_len) && ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT) && (!memcmp(class_lcname, lcname, name_len))) { if (!CG(active_class_entry)->constructor) { CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } } else if ((name_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)))) { if (CG(active_class_entry)->constructor) { zend_error(E_STRICT, "Redefining already defined constructor for class %s", CG(active_class_entry)->name); } CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1))) { CG(active_class_entry)->destructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1))) { CG(active_class_entry)->clone = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } CG(active_class_entry)->__call = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } CG(active_class_entry)->__callstatic = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } CG(active_class_entry)->__get = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } CG(active_class_entry)->__set = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } CG(active_class_entry)->__unset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } CG(active_class_entry)->__isset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } CG(active_class_entry)->__tostring = (zend_function *) CG(active_op_array); } else if (!(fn_flags & ZEND_ACC_STATIC)) { CG(active_op_array)->fn_flags |= ZEND_ACC_ALLOW_STATIC; } free_alloca(class_lcname, use_heap); } str_efree(lcname); } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zval key; if (CG(current_namespace)) { /* Prefix function name with current namespcae name */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, function_name TSRMLS_CC); op_array.function_name = Z_STRVAL(tmp.u.constant); name_len = Z_STRLEN(tmp.u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), name_len); } else { lcname = zend_str_tolower_dup(name, name_len); } opline->opcode = ZEND_DECLARE_FUNCTION; opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, name_len TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; LITERAL_STRINGL(opline->op2, lcname, name_len, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); opline->extended_value = ZEND_DECLARE_FUNCTION; zend_hash_quick_update(CG(function_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); } if (CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_NOP; opline->lineno = function_begin_line; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } { /* Push a seperator to the switch and foreach stacks */ zend_switch_entry switch_entry; switch_entry.cond.op_type = IS_UNUSED; switch_entry.default_case = 0; switch_entry.control_var = 0; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); { /* Foreach stack separator */ zend_op dummy_opline; dummy_opline.result_type = IS_UNUSED; dummy_opline.op1_type = IS_UNUSED; zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); } } if (CG(doc_comment)) { CG(active_op_array)->doc_comment = CG(doc_comment); CG(active_op_array)->doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_begin_lambda_function_declaration(znode *result, znode *function_token, int return_reference, int is_static TSRMLS_DC) /* {{{ */ { znode function_name; zend_op_array *current_op_array = CG(active_op_array); int current_op_number = get_next_op_number(CG(active_op_array)); zend_op *current_op; function_name.op_type = IS_CONST; ZVAL_STRINGL(&function_name.u.constant, "{closure}", sizeof("{closure}")-1, 1); zend_do_begin_function_declaration(function_token, &function_name, 0, return_reference, NULL TSRMLS_CC); result->op_type = IS_TMP_VAR; result->u.op.var = get_temporary_variable(current_op_array); current_op = &current_op_array->opcodes[current_op_number]; current_op->opcode = ZEND_DECLARE_LAMBDA_FUNCTION; zend_del_literal(current_op_array, current_op->op2.constant); SET_UNUSED(current_op->op2); SET_NODE(current_op->result, result); if (is_static) { CG(active_op_array)->fn_flags |= ZEND_ACC_STATIC; } CG(active_op_array)->fn_flags |= ZEND_ACC_CLOSURE; } /* }}} */ void zend_do_handle_exception(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_HANDLE_EXCEPTION; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_function_declaration(const znode *function_token TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; zend_do_extended_info(TSRMLS_C); zend_do_return(NULL, 0 TSRMLS_CC); pass_two(CG(active_op_array) TSRMLS_CC); zend_release_labels(TSRMLS_C); if (CG(active_class_entry)) { zend_check_magic_method_implementation(CG(active_class_entry), (zend_function*)CG(active_op_array), E_COMPILE_ERROR TSRMLS_CC); } else { /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(CG(active_op_array)->function_name); zend_str_tolower_copy(lcname, CG(active_op_array)->function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME)) && CG(active_op_array)->num_args != 1) { zend_error(E_COMPILE_ERROR, "%s() must take exactly 1 argument", ZEND_AUTOLOAD_FUNC_NAME); } } CG(active_op_array)->line_end = zend_get_compiled_lineno(TSRMLS_C); CG(active_op_array) = function_token->u.op_array; /* Pop the switch and foreach seperators */ zend_stack_del_top(&CG(switch_cond_stack)); zend_stack_del_top(&CG(foreach_copy_stack)); } /* }}} */ void zend_do_receive_arg(zend_uchar op, znode *varname, const znode *offset, const znode *initialization, znode *class_type, zend_uchar pass_by_reference TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_arg_info *cur_arg_info; znode var; if (class_type->op_type == IS_CONST && Z_TYPE(class_type->u.constant) == IS_STRING && Z_STRLEN(class_type->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_type->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } if (zend_is_auto_global_quick(Z_STRVAL(varname->u.constant), Z_STRLEN(varname->u.constant), 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign auto-global variable %s", Z_STRVAL(varname->u.constant)); } else { var.op_type = IS_CV; var.u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(varname->u.constant) = (char*)CG(active_op_array)->vars[var.u.op.var].name; var.EA = 0; if (CG(active_op_array)->vars[var.u.op.var].hash_value == THIS_HASHVAL && Z_STRLEN(varname->u.constant) == sizeof("this")-1 && !memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this")-1)) { if (CG(active_op_array)->scope && (CG(active_op_array)->fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } CG(active_op_array)->this_var = var.u.op.var; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->num_args++; opline->opcode = op; SET_NODE(opline->result, &var); SET_NODE(opline->op1, offset); if (op == ZEND_RECV_INIT) { SET_NODE(opline->op2, initialization); } else { CG(active_op_array)->required_num_args = CG(active_op_array)->num_args; SET_UNUSED(opline->op2); } CG(active_op_array)->arg_info = erealloc(CG(active_op_array)->arg_info, sizeof(zend_arg_info)*(CG(active_op_array)->num_args)); cur_arg_info = &CG(active_op_array)->arg_info[CG(active_op_array)->num_args-1]; cur_arg_info->name = zend_new_interned_string(estrndup(varname->u.constant.value.str.val, varname->u.constant.value.str.len), varname->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->name_len = varname->u.constant.value.str.len; cur_arg_info->type_hint = 0; cur_arg_info->allow_null = 1; cur_arg_info->pass_by_reference = pass_by_reference; cur_arg_info->class_name = NULL; cur_arg_info->class_name_len = 0; if (class_type->op_type != IS_UNUSED) { cur_arg_info->allow_null = 0; if (class_type->u.constant.type != IS_NULL) { if (class_type->u.constant.type == IS_ARRAY) { cur_arg_info->type_hint = IS_ARRAY; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else if (Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Default value for parameters with array type hint can only be an array or NULL"); } } } else if (class_type->u.constant.type == IS_CALLABLE) { cur_arg_info->type_hint = IS_CALLABLE; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with callable type hint can only be NULL"); } } } else { cur_arg_info->type_hint = IS_OBJECT; if (ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_type->u.constant), Z_STRLEN(class_type->u.constant))) { zend_resolve_class_name(class_type, opline->extended_value, 1 TSRMLS_CC); } Z_STRVAL(class_type->u.constant) = (char*)zend_new_interned_string(class_type->u.constant.value.str.val, class_type->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->class_name = class_type->u.constant.value.str.val; cur_arg_info->class_name_len = class_type->u.constant.value.str.len; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with a class type hint can only be NULL"); } } } } } } /* }}} */ int zend_do_begin_function_call(znode *function_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { zend_function *function; char *lcname; char *is_compound = memchr(Z_STRVAL(function_name->u.constant), '\\', Z_STRLEN(function_name->u.constant)); zend_resolve_non_class_name(function_name, check_namespace TSRMLS_CC); if (check_namespace && CG(current_namespace) && !is_compound) { /* We assume we call function from the current namespace if it is not prefixed. */ /* In run-time PHP will check for function with full name and internal function with short name */ zend_do_begin_dynamic_function_call(function_name, 1 TSRMLS_CC); return 1; } lcname = zend_str_tolower_dup(function_name->u.constant.value.str.val, function_name->u.constant.value.str.len); if ((zend_hash_find(CG(function_table), lcname, function_name->u.constant.value.str.len+1, (void **) &function)==FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_FUNCTIONS) && (function->type == ZEND_INTERNAL_FUNCTION))) { zend_do_begin_dynamic_function_call(function_name, 0 TSRMLS_CC); efree(lcname); return 1; /* Dynamic */ } efree(function_name->u.constant.value.str.val); function_name->u.constant.value.str.val = lcname; zend_stack_push(&CG(function_call_stack), (void *) &function, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 0; } /* }}} */ void zend_do_begin_method_call(znode *left_bracket TSRMLS_DC) /* {{{ */ { zend_op *last_op; int last_op_number; unsigned char *ptr = NULL; zend_do_end_variable_parse(left_bracket, BP_VAR_R, 0 TSRMLS_CC); zend_do_begin_variable_parse(TSRMLS_C); last_op_number = get_next_op_number(CG(active_op_array))-1; last_op = &CG(active_op_array)->opcodes[last_op_number]; if ((last_op->op2_type == IS_CONST) && (Z_TYPE(CONSTANT(last_op->op2.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(last_op->op2.constant)) == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !zend_binary_strcasecmp(Z_STRVAL(CONSTANT(last_op->op2.constant)), Z_STRLEN(CONSTANT(last_op->op2.constant)), ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1)) { zend_error(E_COMPILE_ERROR, "Cannot call __clone() method on objects - use 'clone $obj' instead"); } if (last_op->opcode == ZEND_FETCH_OBJ_R) { if (last_op->op2_type == IS_CONST) { zval name; name = CONSTANT(last_op->op2.constant); if (!IS_INTERNED(Z_STRVAL(name))) { Z_STRVAL(name) = estrndup(Z_STRVAL(name), Z_STRLEN(name)); } FREE_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); last_op->op2.constant = zend_add_func_name_literal(CG(active_op_array), &name TSRMLS_CC); GET_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); } last_op->opcode = ZEND_INIT_METHOD_CALL; SET_UNUSED(last_op->result); Z_LVAL(left_bracket->u.constant) = ZEND_INIT_FCALL_BY_NAME; } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (left_bracket->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &left_bracket->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, left_bracket); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_do_clone(znode *result, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CLONE; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_begin_dynamic_function_call(znode *function_name, int ns_call TSRMLS_DC) /* {{{ */ { unsigned char *ptr = NULL; zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (ns_call) { /* In run-time PHP will check for function with full name and internal function with short name */ opline->opcode = ZEND_INIT_NS_FCALL_BY_NAME; SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_ns_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (function_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, function_name); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_resolve_non_class_name(znode *element_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; int len; zval **ns; char *lcname, *compound = memchr(Z_STRVAL(element_name->u.constant), '\\', Z_STRLEN(element_name->u.constant)); if (Z_STRVAL(element_name->u.constant)[0] == '\\') { /* name starts with \ so it is known and unambiguos, nothing to do here but shorten it */ memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+1, Z_STRLEN(element_name->u.constant)); --Z_STRLEN(element_name->u.constant); return; } if(!check_namespace) { return; } if (compound && CG(current_import)) { len = compound - Z_STRVAL(element_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(element_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(element_name->u.constant) -= len; memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+len, Z_STRLEN(element_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, element_name TSRMLS_CC); *element_name = tmp; efree(lcname); return; } efree(lcname); } if (CG(current_namespace)) { tmp = *element_name; Z_STRLEN(tmp.u.constant) = sizeof("\\")-1 + Z_STRLEN(element_name->u.constant) + Z_STRLEN_P(CG(current_namespace)); Z_STRVAL(tmp.u.constant) = (char *) emalloc(Z_STRLEN(tmp.u.constant)+1); memcpy(Z_STRVAL(tmp.u.constant), Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace))]), "\\", sizeof("\\")-1); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace)) + sizeof("\\")-1]), Z_STRVAL(element_name->u.constant), Z_STRLEN(element_name->u.constant)+1); STR_FREE(Z_STRVAL(element_name->u.constant)); *element_name = tmp; } } /* }}} */ void zend_resolve_class_name(znode *class_name, ulong fetch_type, int check_ns_name TSRMLS_DC) /* {{{ */ { char *compound; char *lcname; zval **ns; znode tmp; int len; compound = memchr(Z_STRVAL(class_name->u.constant), '\\', Z_STRLEN(class_name->u.constant)); if (compound) { /* This is a compound class name that contains namespace prefix */ if (Z_STRVAL(class_name->u.constant)[0] == '\\') { /* The STRING name has "\" prefix */ Z_STRLEN(class_name->u.constant) -= 1; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+1, Z_STRLEN(class_name->u.constant)+1); Z_STRVAL(class_name->u.constant) = erealloc( Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1); if (ZEND_FETCH_CLASS_DEFAULT != zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "'\\%s' is an invalid class name", Z_STRVAL(class_name->u.constant)); } } else { if (CG(current_import)) { len = compound - Z_STRVAL(class_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(class_name->u.constant) -= len; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+len, Z_STRLEN(class_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; efree(lcname); return; } efree(lcname); } /* Here name is not prefixed with \ and not imported */ if (CG(current_namespace)) { tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } } } else if (CG(current_import) || CG(current_namespace)) { /* this is a plain name (without \) */ lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns) == SUCCESS) { /* The given name is an import name. Substitute it. */ zval_dtor(&class_name->u.constant); class_name->u.constant = **ns; zval_copy_ctor(&class_name->u.constant); } else if (CG(current_namespace)) { /* plain name, no import - prepend current namespace to it */ tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } efree(lcname); } } /* }}} */ void zend_do_fetch_class(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { long fetch_class_op_number; zend_op *opline; if (class_name->op_type == IS_CONST && Z_TYPE(class_name->u.constant) == IS_STRING && Z_STRLEN(class_name->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_name->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } fetch_class_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CLASS; SET_UNUSED(opline->op1); opline->extended_value = ZEND_FETCH_CLASS_GLOBAL; CG(catch_begin) = fetch_class_op_number; if (class_name->op_type == IS_CONST) { int fetch_type; fetch_type = zend_get_class_fetch_type(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); switch (fetch_type) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: SET_UNUSED(opline->op2); opline->extended_value = fetch_type; zval_dtor(&class_name->u.constant); break; default: zend_resolve_class_name(class_name, opline->extended_value, 0 TSRMLS_CC); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_name->u.constant TSRMLS_CC); break; } } else { SET_NODE(opline->op2, class_name); } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; /* FIXME: Hack so that INIT_FCALL_BY_NAME still knows this is a class */ GET_NODE(result, opline->result); result->EA = opline->extended_value; } /* }}} */ void zend_do_label(znode *label TSRMLS_DC) /* {{{ */ { zend_label dest; if (!CG(context).labels) { ALLOC_HASHTABLE(CG(context).labels); zend_hash_init(CG(context).labels, 4, NULL, NULL, 0); } dest.brk_cont = CG(context).current_brk_cont; dest.opline_num = get_next_op_number(CG(active_op_array)); if (zend_hash_add(CG(context).labels, Z_STRVAL(label->u.constant), Z_STRLEN(label->u.constant) + 1, (void**)&dest, sizeof(zend_label), NULL) == FAILURE) { zend_error(E_COMPILE_ERROR, "Label '%s' already defined", Z_STRVAL(label->u.constant)); } /* Done with label now */ zval_dtor(&label->u.constant); } /* }}} */ void zend_resolve_goto_label(zend_op_array *op_array, zend_op *opline, int pass2 TSRMLS_DC) /* {{{ */ { zend_label *dest; long current, distance; zval *label; if (pass2) { label = opline->op2.zv; } else { label = &CONSTANT_EX(op_array, opline->op2.constant); } if (CG(context).labels == NULL || zend_hash_find(CG(context).labels, Z_STRVAL_P(label), Z_STRLEN_P(label)+1, (void**)&dest) == FAILURE) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; zend_error(E_COMPILE_ERROR, "'goto' to undefined label '%s'", Z_STRVAL_P(label)); } else { /* Label is not defined. Delay to pass 2. */ INC_BPC(op_array); return; } } opline->op1.opline_num = dest->opline_num; zval_dtor(label); Z_TYPE_P(label) = IS_NULL; /* Check that we are not moving into loop or switch */ current = opline->extended_value; for (distance = 0; current != dest->brk_cont; distance++) { if (current == -1) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; } zend_error(E_COMPILE_ERROR, "'goto' into loop or switch statement is disallowed"); } current = op_array->brk_cont_array[current].parent; } if (distance == 0) { /* Nothing to break out of, optimize to ZEND_JMP */ opline->opcode = ZEND_JMP; opline->extended_value = 0; SET_UNUSED(opline->op2); } else { /* Set real break distance */ ZVAL_LONG(label, distance); } if (pass2) { DEC_BPC(op_array); } } /* }}} */ void zend_do_goto(const znode *label TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_GOTO; opline->extended_value = CG(context).current_brk_cont; SET_UNUSED(opline->op1); SET_NODE(opline->op2, label); zend_resolve_goto_label(CG(active_op_array), opline, 0 TSRMLS_CC); } /* }}} */ void zend_release_labels(TSRMLS_D) /* {{{ */ { if (CG(context).labels) { zend_hash_destroy(CG(context).labels); FREE_HASHTABLE(CG(context).labels); } if (!zend_stack_is_empty(&CG(context_stack))) { zend_compiler_context *ctx; zend_stack_top(&CG(context_stack), (void**)&ctx); CG(context) = *ctx; zend_stack_del_top(&CG(context_stack)); } } /* }}} */ void zend_do_build_full_name(znode *result, znode *prefix, znode *name, int is_class_member TSRMLS_DC) /* {{{ */ { zend_uint length; if (!result) { result = prefix; } else { *result = *prefix; } if (is_class_member) { length = sizeof("::")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "::", sizeof("::")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("::")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } else { length = sizeof("\\")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "\\", sizeof("\\")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("\\")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } } /* }}} */ int zend_do_begin_class_member_function_call(znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { znode class_node; unsigned char *ptr = NULL; zend_op *opline; if (method_name->op_type == IS_CONST) { char *lcname = zend_str_tolower_dup(Z_STRVAL(method_name->u.constant), Z_STRLEN(method_name->u.constant)); if ((sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == Z_STRLEN(method_name->u.constant) && memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == 0) { zval_dtor(&method_name->u.constant); method_name->op_type = IS_UNUSED; } efree(lcname); } if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; opline = get_next_op(CG(active_op_array) TSRMLS_CC); } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->extended_value = class_node.EA ; } opline->opcode = ZEND_INIT_STATIC_METHOD_CALL; if (class_node.op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, &class_node); } if (method_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &method_name->u.constant TSRMLS_CC); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } } else { SET_NODE(opline->op2, method_name); } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 1; /* Dynamic */ } /* }}} */ void zend_do_end_function_call(znode *function_name, znode *result, const znode *argument_list, int is_method, int is_dynamic_fcall TSRMLS_DC) /* {{{ */ { zend_op *opline; if (is_method && function_name && function_name->op_type == IS_UNUSED) { /* clone */ if (Z_LVAL(argument_list->u.constant) != 0) { zend_error(E_WARNING, "Clone method does not require arguments"); } opline = &CG(active_op_array)->opcodes[Z_LVAL(function_name->u.constant)]; } else { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (!is_method && !is_dynamic_fcall && function_name->op_type==IS_CONST) { opline->opcode = ZEND_DO_FCALL; SET_NODE(opline->op1, function_name); CALCULATE_LITERAL_HASH(opline->op1.constant); GET_CACHE_SLOT(opline->op1.constant); } else { opline->opcode = ZEND_DO_FCALL_BY_NAME; SET_UNUSED(opline->op1); } } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(result, opline->result) ; SET_UNUSED(opline->op2); zend_stack_del_top(&CG(function_call_stack)); opline->extended_value = Z_LVAL(argument_list->u.constant); } /* }}} */ void zend_do_pass_param(znode *param, zend_uchar op, int offset TSRMLS_DC) /* {{{ */ { zend_op *opline; int original_op=op; zend_function **function_ptr_ptr, *function_ptr; int send_by_reference; int send_function = 0; zend_stack_top(&CG(function_call_stack), (void **) &function_ptr_ptr); function_ptr = *function_ptr_ptr; if (original_op == ZEND_SEND_REF) { if (function_ptr && function_ptr->common.function_name && function_ptr->common.type == ZEND_USER_FUNCTION && !ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed; " "If you would like to pass argument by reference, modify the declaration of %s().", function_ptr->common.function_name); } else { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed"); } return; } if (function_ptr) { if (ARG_MAY_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { if (param->op_type & (IS_VAR|IS_CV) && original_op != ZEND_SEND_VAL) { send_by_reference = 1; if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION | ZEND_ARG_SEND_SILENT; } } else { op = ZEND_SEND_VAL; send_by_reference = 0; } } else { send_by_reference = ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset) ? ZEND_ARG_SEND_BY_REF : 0; } } else { send_by_reference = 0; } if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION; } else if (op == ZEND_SEND_VAL && (param->op_type & (IS_VAR|IS_CV))) { op = ZEND_SEND_VAR_NO_REF; } if (op!=ZEND_SEND_VAR_NO_REF && send_by_reference==ZEND_ARG_SEND_BY_REF) { /* change to passing by reference */ switch (param->op_type) { case IS_VAR: case IS_CV: op = ZEND_SEND_REF; break; default: zend_error(E_COMPILE_ERROR, "Only variables can be passed by reference"); break; } } if (original_op == ZEND_SEND_VAR) { switch (op) { case ZEND_SEND_VAR_NO_REF: zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); break; case ZEND_SEND_VAR: if (function_ptr) { zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(param, BP_VAR_FUNC_ARG, offset TSRMLS_CC); } break; case ZEND_SEND_REF: zend_do_end_variable_parse(param, BP_VAR_W, 0 TSRMLS_CC); break; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (op == ZEND_SEND_VAR_NO_REF) { if (function_ptr) { opline->extended_value = ZEND_ARG_COMPILE_TIME_BOUND | send_by_reference | send_function; } else { opline->extended_value = send_function; } } else { if (function_ptr) { opline->extended_value = ZEND_DO_FCALL; } else { opline->extended_value = ZEND_DO_FCALL_BY_NAME; } } opline->opcode = op; SET_NODE(opline->op1, param); opline->op2.opline_num = offset; SET_UNUSED(opline->op2); } /* }}} */ static int generate_free_switch_expr(const zend_switch_entry *switch_entry TSRMLS_DC) /* {{{ */ { zend_op *opline; if (switch_entry->cond.op_type != IS_VAR && switch_entry->cond.op_type != IS_TMP_VAR) { return (switch_entry->cond.op_type == IS_UNUSED); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry->cond); SET_UNUSED(opline->op2); opline->extended_value = 0; return 0; } /* }}} */ static int generate_free_foreach_copy(const zend_op *foreach_copy TSRMLS_DC) /* {{{ */ { zend_op *opline; /* If we reach the seperator then stop applying the stack */ if (foreach_copy->result_type == IS_UNUSED && foreach_copy->op1_type == IS_UNUSED) { return 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->result_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->result); SET_UNUSED(opline->op2); opline->extended_value = 1; if (foreach_copy->op1_type != IS_UNUSED) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->op1_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->op1); SET_UNUSED(opline->op2); opline->extended_value = 0; } return 0; } /* }}} */ void zend_do_return(znode *expr, int do_end_vparse TSRMLS_DC) /* {{{ */ { zend_op *opline; int start_op_number, end_op_number; if (do_end_vparse) { if ((CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) && !zend_is_function_or_method_call(expr)) { zend_do_end_variable_parse(expr, BP_VAR_W, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(expr, BP_VAR_R, 0 TSRMLS_CC); } } start_op_number = get_next_op_number(CG(active_op_array)); #ifdef ZTS zend_stack_apply_with_argument(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_switch_expr TSRMLS_CC); zend_stack_apply_with_argument(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_foreach_copy TSRMLS_CC); #else zend_stack_apply(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_switch_expr); zend_stack_apply(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_foreach_copy); #endif end_op_number = get_next_op_number(CG(active_op_array)); while (start_op_number < end_op_number) { CG(active_op_array)->opcodes[start_op_number].extended_value |= EXT_TYPE_FREE_ON_RETURN; start_op_number++; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) ? ZEND_RETURN_BY_REF : ZEND_RETURN; if (expr) { SET_NODE(opline->op1, expr); if (do_end_vparse && zend_is_function_or_method_call(expr)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } } else { opline->op1_type = IS_CONST; LITERAL_NULL(opline->op1); } SET_UNUSED(opline->op2); } /* }}} */ static int zend_add_try_element(zend_uint try_op TSRMLS_DC) /* {{{ */ { int try_catch_offset = CG(active_op_array)->last_try_catch++; CG(active_op_array)->try_catch_array = erealloc(CG(active_op_array)->try_catch_array, sizeof(zend_try_catch_element)*CG(active_op_array)->last_try_catch); CG(active_op_array)->try_catch_array[try_catch_offset].try_op = try_op; return try_catch_offset; } /* }}} */ static void zend_add_catch_element(int offset, zend_uint catch_op TSRMLS_DC) /* {{{ */ { CG(active_op_array)->try_catch_array[offset].catch_op = catch_op; } /* }}} */ void zend_do_first_catch(znode *open_parentheses TSRMLS_DC) /* {{{ */ { open_parentheses->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_initialize_try_catch_element(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist jmp_list; zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); zend_add_catch_element(try_token->u.op.opline_num, get_next_op_number(CG(active_op_array)) TSRMLS_CC); } /* }}} */ void zend_do_mark_last_catch(const znode *first_catch, const znode *last_additional_catch TSRMLS_DC) /* {{{ */ { CG(active_op_array)->last--; zend_do_if_end(TSRMLS_C); if (last_additional_catch->u.op.opline_num == -1) { CG(active_op_array)->opcodes[first_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[first_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } else { CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_try(znode *try_token TSRMLS_DC) /* {{{ */ { try_token->u.op.opline_num = zend_add_try_element(get_next_op_number(CG(active_op_array)) TSRMLS_CC); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_catch(znode *try_token, znode *class_name, znode *catch_var, znode *first_catch TSRMLS_DC) /* {{{ */ { long catch_op_number; zend_op *opline; znode catch_class; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); catch_class = *class_name; } else { zend_error(E_COMPILE_ERROR, "Bad class name in the catch statement"); } catch_op_number = get_next_op_number(CG(active_op_array)); if (first_catch) { first_catch->u.op.opline_num = catch_op_number; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CATCH; opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &catch_class.u.constant TSRMLS_CC); opline->op2_type = IS_CV; opline->op2.var = lookup_cv(CG(active_op_array), catch_var->u.constant.value.str.val, catch_var->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(catch_var->u.constant) = (char*)CG(active_op_array)->vars[opline->op2.var].name; opline->result.num = 0; /* 1 means it's the last catch in the block */ try_token->u.op.opline_num = catch_op_number; } /* }}} */ void zend_do_end_catch(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); CG(active_op_array)->opcodes[try_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_throw(const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_THROW; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); } /* }}} */ ZEND_API void function_add_ref(zend_function *function) /* {{{ */ { if (function->type == ZEND_USER_FUNCTION) { zend_op_array *op_array = &function->op_array; (*op_array->refcount)++; if (op_array->static_variables) { HashTable *static_variables = op_array->static_variables; zval *tmp_zval; ALLOC_HASHTABLE(op_array->static_variables); zend_hash_init(op_array->static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(op_array->static_variables, static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_zval, sizeof(zval *)); } op_array->run_time_cache = NULL; } } /* }}} */ static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */ { zend_function *function; if (!ce->parent) { return; } /* You cannot change create_object */ ce->create_object = ce->parent->create_object; /* Inherit special functions if needed */ if (!ce->get_iterator) { ce->get_iterator = ce->parent->get_iterator; } if (!ce->iterator_funcs.funcs) { ce->iterator_funcs.funcs = ce->parent->iterator_funcs.funcs; } if (!ce->__get) { ce->__get = ce->parent->__get; } if (!ce->__set) { ce->__set = ce->parent->__set; } if (!ce->__unset) { ce->__unset = ce->parent->__unset; } if (!ce->__isset) { ce->__isset = ce->parent->__isset; } if (!ce->__call) { ce->__call = ce->parent->__call; } if (!ce->__callstatic) { ce->__callstatic = ce->parent->__callstatic; } if (!ce->__tostring) { ce->__tostring = ce->parent->__tostring; } if (!ce->clone) { ce->clone = ce->parent->clone; } if(!ce->serialize) { ce->serialize = ce->parent->serialize; } if(!ce->unserialize) { ce->unserialize = ce->parent->unserialize; } if (!ce->destructor) { ce->destructor = ce->parent->destructor; } if (ce->constructor) { if (ce->parent->constructor && ce->parent->constructor->common.fn_flags & ZEND_ACC_FINAL) { zend_error(E_ERROR, "Cannot override final %s::%s() with %s::%s()", ce->parent->name, ce->parent->constructor->common.function_name, ce->name, ce->constructor->common.function_name ); } return; } if (zend_hash_find(&ce->parent->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), (void **)&function)==SUCCESS) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), function, sizeof(zend_function), NULL); function_add_ref(function); } else { /* Don't inherit the old style constructor if we already have the new style constructor */ char *lc_class_name; char *lc_parent_class_name; lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); if (!zend_hash_exists(&ce->function_table, lc_class_name, ce->name_length+1)) { lc_parent_class_name = zend_str_tolower_dup(ce->parent->name, ce->parent->name_length); if (!zend_hash_exists(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1) && zend_hash_find(&ce->parent->function_table, lc_parent_class_name, ce->parent->name_length+1, (void **)&function)==SUCCESS) { if (function->common.fn_flags & ZEND_ACC_CTOR) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1, function, sizeof(zend_function), NULL); function_add_ref(function); } } efree(lc_parent_class_name); } efree(lc_class_name); } ce->constructor = ce->parent->constructor; } /* }}} */ char *zend_visibility_string(zend_uint fn_flags) /* {{{ */ { if (fn_flags & ZEND_ACC_PRIVATE) { return "private"; } if (fn_flags & ZEND_ACC_PROTECTED) { return "protected"; } if (fn_flags & ZEND_ACC_PUBLIC) { return "public"; } return ""; } /* }}} */ static void do_inherit_method(zend_function *function) /* {{{ */ { /* The class entry of the derived function intentionally remains the same * as that of the parent class. That allows us to know in which context * we're running, and handle private method calls properly. */ function_add_ref(function); } /* }}} */ static zend_bool zend_do_perform_implementation_check(const zend_function *fe, const zend_function *proto TSRMLS_DC) /* {{{ */ { zend_uint i; /* If it's a user function then arg_info == NULL means we don't have any parameters but * we still need to do the arg number checks. We are only willing to ignore this for internal * functions because extensions don't always define arg_info. */ if (!proto || (!proto->common.arg_info && proto->common.type != ZEND_USER_FUNCTION)) { return 1; } /* Checks for constructors only if they are declared in an interface, * or explicitly marked as abstract */ if ((fe->common.fn_flags & ZEND_ACC_CTOR) && ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)) { return 1; } /* check number of arguments */ if (proto->common.required_num_args < fe->common.required_num_args || proto->common.num_args > fe->common.num_args) { return 0; } if (fe->common.type != ZEND_USER_FUNCTION && (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) != 0 && (fe->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) == 0) { return 0; } /* by-ref constraints on return values are covariant */ if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) { return 0; } for (i=0; i < proto->common.num_args; i++) { if (ZEND_LOG_XOR(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)) { /* Only one has a type hint and the other one doesn't */ return 0; } if (fe->common.arg_info[i].class_name && strcasecmp(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)!=0) { const char *colon; if (fe->common.type != ZEND_USER_FUNCTION) { return 0; } else if (strchr(proto->common.arg_info[i].class_name, '\\') != NULL || (colon = zend_memrchr(fe->common.arg_info[i].class_name, '\\', fe->common.arg_info[i].class_name_len)) == NULL || strcasecmp(colon+1, proto->common.arg_info[i].class_name) != 0) { zend_class_entry **fe_ce, **proto_ce; int found, found2; found = zend_lookup_class(fe->common.arg_info[i].class_name, fe->common.arg_info[i].class_name_len, &fe_ce TSRMLS_CC); found2 = zend_lookup_class(proto->common.arg_info[i].class_name, proto->common.arg_info[i].class_name_len, &proto_ce TSRMLS_CC); /* Check for class alias */ if (found != SUCCESS || found2 != SUCCESS || (*fe_ce)->type == ZEND_INTERNAL_CLASS || (*proto_ce)->type == ZEND_INTERNAL_CLASS || *fe_ce != *proto_ce) { return 0; } } } if (fe->common.arg_info[i].type_hint != proto->common.arg_info[i].type_hint) { /* Incompatible type hint */ return 0; } /* by-ref constraints on arguments are invariant */ if (fe->common.arg_info[i].pass_by_reference != proto->common.arg_info[i].pass_by_reference) { return 0; } } if (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) { for (i=proto->common.num_args; i < fe->common.num_args; i++) { if (!fe->common.arg_info[i].pass_by_reference) { return 0; } } } return 1; } /* }}} */ #define REALLOC_BUF_IF_EXCEED(buf, offset, length, size) \ if (UNEXPECTED(offset - buf + size >= length)) { \ length += size + 1; \ buf = erealloc(buf, length); \ } static char * zend_get_function_declaration(zend_function *fptr TSRMLS_DC) /* {{{ */ { char *offset, *buf; zend_uint length = 1024; offset = buf = (char *)emalloc(length * sizeof(char)); if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { *(offset++) = '&'; *(offset++) = ' '; } if (fptr->common.scope) { memcpy(offset, fptr->common.scope->name, fptr->common.scope->name_length); offset += fptr->common.scope->name_length; *(offset++) = ':'; *(offset++) = ':'; } { size_t name_len = strlen(fptr->common.function_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, name_len); memcpy(offset, fptr->common.function_name, name_len); offset += name_len; } *(offset++) = '('; if (fptr->common.arg_info) { zend_uint i, required; zend_arg_info *arg_info = fptr->common.arg_info; required = fptr->common.required_num_args; for (i = 0; i < fptr->common.num_args;) { if (arg_info->class_name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->class_name_len); memcpy(offset, arg_info->class_name, arg_info->class_name_len); offset += arg_info->class_name_len; *(offset++) = ' '; } else if (arg_info->type_hint) { zend_uint type_name_len; char *type_name = zend_get_type_by_const(arg_info->type_hint); type_name_len = strlen(type_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, type_name_len); memcpy(offset, type_name, type_name_len); offset += type_name_len; *(offset++) = ' '; } if (arg_info->pass_by_reference) { *(offset++) = '&'; } *(offset++) = '$'; if (arg_info->name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->name_len); memcpy(offset, arg_info->name, arg_info->name_len); offset += arg_info->name_len; } else { zend_uint idx = i; memcpy(offset, "param", 5); offset += 5; do { *(offset++) = (char) (idx % 10) + '0'; idx /= 10; } while (idx > 0); } if (i >= required) { *(offset++) = ' '; *(offset++) = '='; *(offset++) = ' '; if (fptr->type == ZEND_USER_FUNCTION) { zend_op *precv = NULL; { zend_uint idx = i; zend_op *op = ((zend_op_array *)fptr)->opcodes; zend_op *end = op + ((zend_op_array *)fptr)->last; ++idx; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT) && op->op1.num == (long)idx) { precv = op; } ++op; } } if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) { zval *zv, zv_copy; int use_copy; ALLOC_ZVAL(zv); *zv = *precv->op2.zv; zval_copy_ctor(zv); INIT_PZVAL(zv); zval_update_constant_ex(&zv, (void*)1, fptr->common.scope TSRMLS_CC); if (Z_TYPE_P(zv) == IS_BOOL) { if (Z_LVAL_P(zv)) { memcpy(offset, "true", 4); offset += 4; } else { memcpy(offset, "false", 5); offset += 5; } } else if (Z_TYPE_P(zv) == IS_NULL) { memcpy(offset, "NULL", 4); offset += 4; } else if (Z_TYPE_P(zv) == IS_STRING) { *(offset++) = '\''; REALLOC_BUF_IF_EXCEED(buf, offset, length, MIN(Z_STRLEN_P(zv), 10)); memcpy(offset, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 10)); offset += MIN(Z_STRLEN_P(zv), 10); if (Z_STRLEN_P(zv) > 10) { *(offset++) = '.'; *(offset++) = '.'; *(offset++) = '.'; } *(offset++) = '\''; } else if (Z_TYPE_P(zv) == IS_ARRAY) { memcpy(offset, "Array", 5); offset += 5; } else { zend_make_printable_zval(zv, &zv_copy, &use_copy); REALLOC_BUF_IF_EXCEED(buf, offset, length, Z_STRLEN(zv_copy)); memcpy(offset, Z_STRVAL(zv_copy), Z_STRLEN(zv_copy)); offset += Z_STRLEN(zv_copy); if (use_copy) { zval_dtor(&zv_copy); } } zval_ptr_dtor(&zv); } } else { memcpy(offset, "NULL", 4); offset += 4; } } if (++i < fptr->common.num_args) { *(offset++) = ','; *(offset++) = ' '; } arg_info++; REALLOC_BUF_IF_EXCEED(buf, offset, length, 32); } } *(offset++) = ')'; *offset = '\0'; return buf; } /* }}} */ static void do_inheritance_check_on_method(zend_function *child, zend_function *parent TSRMLS_DC) /* {{{ */ { zend_uint child_flags; zend_uint parent_flags = parent->common.fn_flags; if (parent->common.fn_flags & ZEND_ACC_ABSTRACT && parent->common.scope != (child->common.prototype ? child->common.prototype->common.scope : child->common.scope) && child->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_IMPLEMENTED_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Can't inherit abstract function %s::%s() (previously declared abstract in %s)", parent->common.scope->name, child->common.function_name, child->common.prototype ? child->common.prototype->common.scope->name : child->common.scope->name); } if (parent_flags & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot override final method %s::%s()", ZEND_FN_SCOPE_NAME(parent), child->common.function_name); } child_flags = child->common.fn_flags; /* You cannot change from static to non static and vice versa. */ if ((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC)) { if (child->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot make non static method %s::%s() static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } else { zend_error(E_COMPILE_ERROR, "Cannot make static method %s::%s() non static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } } /* Disallow making an inherited method abstract. */ if ((child_flags & ZEND_ACC_ABSTRACT) && !(parent_flags & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Cannot make non abstract method %s::%s() abstract in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } if (parent_flags & ZEND_ACC_CHANGED) { child->common.fn_flags |= ZEND_ACC_CHANGED; } else { /* Prevent derived classes from restricting access that was available in parent classes */ if ((child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::%s() must be %s (as in class %s)%s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if (((child_flags & ZEND_ACC_PPP_MASK) < (parent_flags & ZEND_ACC_PPP_MASK)) && ((parent_flags & ZEND_ACC_PPP_MASK) & ZEND_ACC_PRIVATE)) { child->common.fn_flags |= ZEND_ACC_CHANGED; } } if (parent_flags & ZEND_ACC_PRIVATE) { child->common.prototype = NULL; } else if (parent_flags & ZEND_ACC_ABSTRACT) { child->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; child->common.prototype = parent; } else if (!(parent->common.fn_flags & ZEND_ACC_CTOR) || (parent->common.prototype && (parent->common.prototype->common.scope->ce_flags & ZEND_ACC_INTERFACE))) { /* ctors only have a prototype if it comes from an interface */ child->common.prototype = parent->common.prototype ? parent->common.prototype : parent; } if (child->common.prototype && (child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { if (!zend_do_perform_implementation_check(child, child->common.prototype TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s::%s() must be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_get_function_declaration(child->common.prototype TSRMLS_CC)); } } else if (EG(error_reporting) & E_STRICT || EG(user_error_handler)) { /* Check E_STRICT (or custom error handler) before the check so that we save some time */ if (!zend_do_perform_implementation_check(child, parent TSRMLS_CC)) { char *method_prototype = zend_get_function_declaration(child->common.prototype TSRMLS_CC); zend_error(E_STRICT, "Declaration of %s::%s() should be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, method_prototype); efree(method_prototype); } } } /* }}} */ static zend_bool do_inherit_method_check(HashTable *child_function_table, zend_function *parent, const zend_hash_key *hash_key, zend_class_entry *child_ce) /* {{{ */ { zend_uint parent_flags = parent->common.fn_flags; zend_function *child; TSRMLS_FETCH(); if (zend_hash_quick_find(child_function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child)==FAILURE) { if (parent_flags & (ZEND_ACC_ABSTRACT)) { child_ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } return 1; /* method doesn't exist in child, copy from parent */ } do_inheritance_check_on_method(child, parent TSRMLS_CC); return 0; } /* }}} */ static zend_bool do_inherit_property_access_check(HashTable *target_ht, zend_property_info *parent_info, const zend_hash_key *hash_key, zend_class_entry *ce) /* {{{ */ { zend_property_info *child_info; zend_class_entry *parent_ce = ce->parent; if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW)) { if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { child_info->flags |= ZEND_ACC_CHANGED; } else { zend_hash_quick_update(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, parent_info, sizeof(zend_property_info), (void **) &child_info); if(ce->type & ZEND_INTERNAL_CLASS) { zend_duplicate_property_info_internal(child_info); } else { zend_duplicate_property_info(child_info); } child_info->flags &= ~ZEND_ACC_PRIVATE; /* it's not private anymore */ child_info->flags |= ZEND_ACC_SHADOW; /* but it's a shadow of private */ } return 0; /* don't copy access information to child */ } if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { if ((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s", (parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", parent_ce->name, hash_key->arKey, (child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ce->name, hash_key->arKey); } if(parent_info->flags & ZEND_ACC_CHANGED) { child_info->flags |= ZEND_ACC_CHANGED; } if ((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ce->name, hash_key->arKey, zend_visibility_string(parent_info->flags), parent_ce->name, (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if ((child_info->flags & ZEND_ACC_STATIC) == 0) { Z_DELREF_P(ce->default_properties_table[parent_info->offset]); ce->default_properties_table[parent_info->offset] = ce->default_properties_table[child_info->offset]; ce->default_properties_table[child_info->offset] = NULL; child_info->offset = parent_info->offset; } return 0; /* Don't copy from parent */ } else { return 1; /* Copy from parent */ } } /* }}} */ static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce TSRMLS_CC) == FAILURE) { zend_error(E_CORE_ERROR, "Class %s could not implement interface %s", ce->name, iface->name); } if (ce == iface) { zend_error(E_ERROR, "Interface %s cannot implement itself", ce->name); } } /* }}} */ ZEND_API void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface TSRMLS_DC) /* {{{ */ { /* expects interface to be contained in ce's interface list already */ zend_uint i, ce_num, if_num = iface->num_interfaces; zend_class_entry *entry; if (if_num==0) { return; } ce_num = ce->num_interfaces; if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } /* Inherit the interfaces, only if they're not already inherited by the class */ while (if_num--) { entry = iface->interfaces[if_num]; for (i = 0; i < ce_num; i++) { if (ce->interfaces[i] == entry) { break; } } if (i == ce_num) { ce->interfaces[ce->num_interfaces++] = entry; } } /* and now call the implementing handlers */ while (ce_num < ce->num_interfaces) { do_implement_interface(ce, ce->interfaces[ce_num++] TSRMLS_CC); } } /* }}} */ #ifdef ZTS static void zval_internal_ctor(zval **p) /* {{{ */ { zval *orig_ptr = *p; ALLOC_ZVAL(*p); MAKE_COPY_ZVAL(&orig_ptr, *p); } /* }}} */ # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) (((parent_ce)->type != (ce)->type) ? zval_internal_ctor : zval_add_ref)) #else # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) zval_add_ref) #endif ZEND_API void zend_do_inheritance(zend_class_entry *ce, zend_class_entry *parent_ce TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; if ((ce->ce_flags & ZEND_ACC_INTERFACE) && !(parent_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ce->name, parent_ce->name); } if (parent_ce->ce_flags & ZEND_ACC_FINAL_CLASS) { zend_error(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ce->name, parent_ce->name); } ce->parent = parent_ce; /* Copy serialize/unserialize callbacks */ if (!ce->serialize) { ce->serialize = parent_ce->serialize; } if (!ce->unserialize) { ce->unserialize = parent_ce->unserialize; } /* Inherit interfaces */ zend_do_inherit_interfaces(ce, parent_ce TSRMLS_CC); /* Inherit properties */ if (parent_ce->default_properties_count) { int i = ce->default_properties_count + parent_ce->default_properties_count; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_properties_count) { while (i-- > parent_ce->default_properties_count) { ce->default_properties_table[i] = ce->default_properties_table[i - parent_ce->default_properties_count]; } } for (i = 0; i < parent_ce->default_properties_count; i++) { ce->default_properties_table[i] = parent_ce->default_properties_table[i]; if (ce->default_properties_table[i]) { #ifdef ZTS if (parent_ce->type != ce->type) { zval *p; ALLOC_ZVAL(p); MAKE_COPY_ZVAL(&ce->default_properties_table[i], p); ce->default_properties_table[i] = p; } else { Z_ADDREF_P(ce->default_properties_table[i]); } #else Z_ADDREF_P(ce->default_properties_table[i]); #endif } } ce->default_properties_count += parent_ce->default_properties_count; } if (parent_ce->type != ce->type) { /* User class extends internal class */ zend_update_class_constants(parent_ce TSRMLS_CC); if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = erealloc(ce->default_static_members_table, sizeof(void*) * i); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&CE_STATIC_MEMBERS(parent_ce)[i]); ce->default_static_members_table[i] = CE_STATIC_MEMBERS(parent_ce)[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; ce->static_members_table = ce->default_static_members_table; } } else { if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&parent_ce->default_static_members_table[i]); ce->default_static_members_table[i] = parent_ce->default_static_members_table[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } } for (zend_hash_internal_pointer_reset(&ce->properties_info); zend_hash_get_current_data(&ce->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->properties_info)) { if (property_info->ce == ce) { if (property_info->flags & ZEND_ACC_STATIC) { property_info->offset += parent_ce->default_static_members_count; } else { property_info->offset += parent_ce->default_properties_count; } } } zend_hash_merge_ex(&ce->properties_info, &parent_ce->properties_info, (copy_ctor_func_t) (ce->type & ZEND_INTERNAL_CLASS ? zend_duplicate_property_info_internal : zend_duplicate_property_info), sizeof(zend_property_info), (merge_checker_func_t) do_inherit_property_access_check, ce); zend_hash_merge(&ce->constants_table, &parent_ce->constants_table, zval_property_ctor(parent_ce, ce), NULL, sizeof(zval *), 0); zend_hash_merge_ex(&ce->function_table, &parent_ce->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_inherit_parent_constructor(ce); if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS && ce->type == ZEND_INTERNAL_CLASS) { ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } else if (!(ce->ce_flags & ZEND_ACC_IMPLEMENT_INTERFACES) && !(ce->ce_flags & ZEND_ACC_IMPLEMENT_TRAITS)) { /* The verification will be done in runtime by ZEND_VERIFY_ABSTRACT_CLASS */ zend_verify_abstract_class(ce TSRMLS_CC); } ce->ce_flags |= parent_ce->ce_flags & ZEND_HAS_STATIC_IN_METHODS; } /* }}} */ static zend_bool do_inherit_constant_check(HashTable *child_constants_table, const zval **parent_constant, const zend_hash_key *hash_key, const zend_class_entry *iface) /* {{{ */ { zval **old_constant; if (zend_hash_quick_find(child_constants_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**)&old_constant) == SUCCESS) { if (*old_constant != *parent_constant) { zend_error(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", hash_key->arKey, iface->name); } return 0; } return 1; } /* }}} */ static int do_interface_constant_check(zval **val TSRMLS_DC, int num_args, va_list args, const zend_hash_key *key) /* {{{ */ { zend_class_entry **iface = va_arg(args, zend_class_entry**); do_inherit_constant_check(&(*iface)->constants_table, (const zval **) val, key, *iface); return ZEND_HASH_APPLY_KEEP; } /* }}} */ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_iface_num = ce->num_interfaces; zend_uint parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0; for (i = 0; i < ce->num_interfaces; i++) { if (ce->interfaces[i] == NULL) { memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i)); i--; } else if (ce->interfaces[i] == iface) { if (i < parent_iface_num) { ignore = 1; } else { zend_error(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ce->name, iface->name); } } } if (ignore) { /* Check for attempt to redeclare interface constants */ zend_hash_apply_with_arguments(&ce->constants_table TSRMLS_CC, (apply_func_args_t) do_interface_constant_check, 1, &iface); } else { if (ce->num_interfaces >= current_iface_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } } ce->interfaces[ce->num_interfaces++] = iface; zend_hash_merge_ex(&ce->constants_table, &iface->constants_table, (copy_ctor_func_t) zval_add_ref, sizeof(zval *), (merge_checker_func_t) do_inherit_constant_check, iface); zend_hash_merge_ex(&ce->function_table, &iface->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_implement_interface(ce, iface TSRMLS_CC); zend_do_inherit_interfaces(ce, iface TSRMLS_CC); } } /* }}} */ ZEND_API void zend_do_implement_trait(zend_class_entry *ce, zend_class_entry *trait TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_trait_num = ce->num_traits; zend_uint parent_trait_num = ce->parent ? ce->parent->num_traits : 0; for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == NULL) { memmove(ce->traits + i, ce->traits + i + 1, sizeof(zend_class_entry*) * (--ce->num_traits - i)); i--; } else if (ce->traits[i] == trait) { if (i < parent_trait_num) { ignore = 1; } } } if (!ignore) { if (ce->num_traits >= current_trait_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->traits = (zend_class_entry **) realloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } else { ce->traits = (zend_class_entry **) erealloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } } ce->traits[ce->num_traits++] = trait; } } /* }}} */ static int zend_traits_merge_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { size_t current; size_t i; size_t count; HashTable* resulting_table; HashTable** function_tables; zend_class_entry *ce; size_t collision = 0; size_t abstract_solved = 0; zend_function* other_trait_fn; current = va_arg(args, size_t); /* index of current trait */ count = va_arg(args, size_t); resulting_table = va_arg(args, HashTable*); function_tables = va_arg(args, HashTable**); ce = va_arg(args, zend_class_entry*); for (i = 0; i < count; i++) { if (i == current) { continue; /* just skip this, cause its the table this function is applied on */ } if (zend_hash_quick_find(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&other_trait_fn) == SUCCESS) { /* if it is an abstract method, there is no collision */ if (other_trait_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible */ do_inheritance_check_on_method(fn, other_trait_fn TSRMLS_CC); /* we can savely free and remove it from other table */ zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } else { /* if it is not an abstract method, there is still no collision */ /* if fn is an abstract method */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible */ do_inheritance_check_on_method(other_trait_fn, fn TSRMLS_CC); /* just mark as solved, will be added if its own trait is processed */ abstract_solved = 1; } else { /* but else, we have a collision of non-abstract methods */ collision++; zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } } } if (collision) { zend_function* class_fn; /* make sure method is not already overridden in class */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&class_fn) == FAILURE || class_fn->common.scope != ce) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because there are collisions with other trait methods on %s", fn->common.function_name, ce->name); } zend_function_dtor(fn); } else if (abstract_solved) { zend_function_dtor(fn); } else { /* Add it to result function table */ if (zend_hash_quick_add(resulting_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, fn, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating resulting trait method table", fn->common.function_name); } } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ /* {{{ Originates from php_runkit_function_copy_ctor Duplicate structures in an op_array where necessary to make an outright duplicate */ static void zend_traits_duplicate_function(zend_function *fe, zend_class_entry *target_ce, char *newname TSRMLS_DC) { zend_literal *literals_copy; zend_compiled_variable *dupvars; zend_op *opcode_copy; zval class_name_zv; int class_name_literal; int i; int number_of_literals; if (fe->op_array.static_variables) { HashTable *tmpHash; ALLOC_HASHTABLE(tmpHash); zend_hash_init(tmpHash, zend_hash_num_elements(fe->op_array.static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_apply_with_arguments(fe->op_array.static_variables TSRMLS_CC, (apply_func_args_t)zval_copy_static_var, 1, tmpHash); fe->op_array.static_variables = tmpHash; } number_of_literals = fe->op_array.last_literal; literals_copy = (zend_literal*)emalloc(number_of_literals * sizeof(zend_literal)); for (i = 0; i < number_of_literals; i++) { literals_copy[i] = fe->op_array.literals[i]; zval_copy_ctor(&literals_copy[i].constant); } fe->op_array.literals = literals_copy; fe->op_array.refcount = emalloc(sizeof(zend_uint)); *(fe->op_array.refcount) = 1; if (fe->op_array.vars) { i = fe->op_array.last_var; dupvars = safe_emalloc(fe->op_array.last_var, sizeof(zend_compiled_variable), 0); while (i > 0) { i--; dupvars[i].name = estrndup(fe->op_array.vars[i].name, fe->op_array.vars[i].name_len); dupvars[i].name_len = fe->op_array.vars[i].name_len; dupvars[i].hash_value = fe->op_array.vars[i].hash_value; } fe->op_array.vars = dupvars; } else { fe->op_array.vars = NULL; } opcode_copy = safe_emalloc(sizeof(zend_op), fe->op_array.last, 0); for(i = 0; i < fe->op_array.last; i++) { opcode_copy[i] = fe->op_array.opcodes[i]; if (opcode_copy[i].op1_type != IS_CONST) { if (opcode_copy[i].op1.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op1.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op1.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op1.jmp_addr - fe->op_array.opcodes); } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op1.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op1.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op1.zv = &fe->op_array.literals[class_name_literal].constant; } } if (opcode_copy[i].op2_type != IS_CONST) { if (opcode_copy[i].op2.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op2.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op2.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op2.jmp_addr - fe->op_array.opcodes); } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op2.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op2.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op2.zv = &fe->op_array.literals[class_name_literal].constant; } } } fe->op_array.opcodes = opcode_copy; fe->op_array.function_name = newname; /* was setting it to fe which does not work since fe is stack allocated and not a stable address */ /* fe->op_array.prototype = fe->op_array.prototype; */ if (fe->op_array.arg_info) { zend_arg_info *tmpArginfo; tmpArginfo = safe_emalloc(sizeof(zend_arg_info), fe->op_array.num_args, 0); for(i = 0; i < fe->op_array.num_args; i++) { tmpArginfo[i] = fe->op_array.arg_info[i]; tmpArginfo[i].name = estrndup(tmpArginfo[i].name, tmpArginfo[i].name_len); if (tmpArginfo[i].class_name) { tmpArginfo[i].class_name = estrndup(tmpArginfo[i].class_name, tmpArginfo[i].class_name_len); } } fe->op_array.arg_info = tmpArginfo; } fe->op_array.doc_comment = estrndup(fe->op_array.doc_comment, fe->op_array.doc_comment_len); fe->op_array.try_catch_array = (zend_try_catch_element*)estrndup((char*)fe->op_array.try_catch_array, sizeof(zend_try_catch_element) * fe->op_array.last_try_catch); fe->op_array.brk_cont_array = (zend_brk_cont_element*)estrndup((char*)fe->op_array.brk_cont_array, sizeof(zend_brk_cont_element) * fe->op_array.last_brk_cont); } /* }}} */ static void zend_add_magic_methods(zend_class_entry* ce, const char* mname, uint mname_len, zend_function* fe TSRMLS_DC) { if ( !strncmp(mname, ZEND_CLONE_FUNC_NAME, mname_len)) { ce->clone = fe; fe->common.fn_flags |= ZEND_ACC_CLONE; } else if (!strncmp(mname, ZEND_CONSTRUCTOR_FUNC_NAME, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } else if (!strncmp(mname, ZEND_DESTRUCTOR_FUNC_NAME, mname_len)) { ce->destructor = fe; fe->common.fn_flags |= ZEND_ACC_DTOR; } else if (!strncmp(mname, ZEND_GET_FUNC_NAME, mname_len)) ce->__get = fe; else if (!strncmp(mname, ZEND_SET_FUNC_NAME, mname_len)) ce->__set = fe; else if (!strncmp(mname, ZEND_CALL_FUNC_NAME, mname_len)) ce->__call = fe; else if (!strncmp(mname, ZEND_UNSET_FUNC_NAME, mname_len)) ce->__unset = fe; else if (!strncmp(mname, ZEND_ISSET_FUNC_NAME, mname_len)) ce->__isset = fe; else if (!strncmp(mname, ZEND_CALLSTATIC_FUNC_NAME, mname_len)) ce->__callstatic= fe; else if (!strncmp(mname, ZEND_TOSTRING_FUNC_NAME, mname_len)) ce->__tostring = fe; else if (ce->name_length + 1 == mname_len) { char *lowercase_name = emalloc(ce->name_length + 1); zend_str_tolower_copy(lowercase_name, ce->name, ce->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, ce->name_length + 1, 1 TSRMLS_CC); if (!memcmp(mname, lowercase_name, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } str_efree(lowercase_name); } } static int zend_traits_merge_functions_to_class(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zend_class_entry *ce = va_arg(args, zend_class_entry*); int add = 0; zend_function* existing_fn; zend_function fn_copy, *fn_copy_p; zend_function* prototype = NULL; /* is used to determine the prototype according to the inheritance chain */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &existing_fn) == FAILURE) { add = 1; /* not found */ } else if (existing_fn->common.scope != ce) { add = 1; /* or inherited from other class or interface */ /* it is just a reference which was added to the subclass while doing the inheritance */ /* so we can deleted now, and will add the overriding method afterwards */ /* except, if we try to add an abstract function, then we should not delete the inherited one */ /* delete inherited fn if the function to be added is not abstract */ if ((fn->common.fn_flags & ZEND_ACC_ABSTRACT) == 0) { zend_hash_quick_del(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } if (add) { zend_function* parent_function; if (ce->parent && zend_hash_quick_find(&ce->parent->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &parent_function) != FAILURE) { prototype = parent_function; /* ->common.fn_flags |= ZEND_ACC_ABSTRACT; */ /* we got that method in the parent class, and are going to override it, except, if the trait is just asking to have an abstract method implemented. */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* then we clean up an skip this method */ zend_function_dtor(fn); return ZEND_HASH_APPLY_REMOVE; } } fn->common.scope = ce; fn->common.prototype = prototype; if (prototype && (prototype->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT || prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { fn->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; } else if (fn->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT) { /* remove ZEND_ACC_IMPLEMENTED_ABSTRACT flag, think it shouldn't be copied to class */ fn->common.fn_flags = fn->common.fn_flags - ZEND_ACC_IMPLEMENTED_ABSTRACT; } /* check whether the trait method fullfills the inheritance requirements */ if (prototype) { do_inheritance_check_on_method(fn, prototype TSRMLS_CC); } if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (fn->op_array.static_variables) { ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, ce, estrdup(fn->common.function_name) TSRMLS_CC); if (zend_hash_quick_update(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, &fn_copy, sizeof(zend_function), (void**)&fn_copy_p)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating class method table", hash_key->arKey); } zend_add_magic_methods(ce, hash_key->arKey, hash_key->nKeyLength, fn_copy_p TSRMLS_CC); zend_function_dtor(fn); } else { zend_function_dtor(fn); } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ static int zend_traits_copy_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { HashTable* target; zend_class_entry *target_ce; zend_trait_alias** aliases; HashTable* exclude_table; char* lcname; unsigned int fnname_len; zend_function fn_copy; void* dummy; size_t i = 0; target = va_arg(args, HashTable*); target_ce = va_arg(args, zend_class_entry*); aliases = va_arg(args, zend_trait_alias**); exclude_table = va_arg(args, HashTable*); fnname_len = strlen(fn->common.function_name); /* apply aliases which are qualified with a class name, there should not be any ambiguity */ if (aliases) { while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias != NULL && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && aliases[i]->trait_method->mname_len == fnname_len && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(aliases[i]->alias, aliases[i]->alias_len) TSRMLS_CC); /* if it is 0, no modifieres has been changed */ if (aliases[i]->modifiers) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } lcname = zend_str_tolower_dup(aliases[i]->alias, aliases[i]->alias_len); if (zend_hash_add(target, lcname, aliases[i]->alias_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add aliased trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } efree(lcname); } i++; } } lcname = zend_str_tolower_dup(fn->common.function_name, fnname_len); if (exclude_table == NULL || zend_hash_find(exclude_table, lcname, fnname_len, &dummy) == FAILURE) { /* is not in hashtable, thus, function is not to be excluded */ fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(fn->common.function_name, fnname_len) TSRMLS_CC); /* apply aliases which are not qualified by a class name, or which have not * alias name, just setting visibility */ if (aliases) { i = 0; while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias == NULL && aliases[i]->modifiers != 0 && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && (aliases[i]->trait_method->mname_len == fnname_len) && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } i++; } } if (zend_hash_add(target, lcname, fnname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } } efree(lcname); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* Copies function table entries to target function table with applied aliasing */ static void zend_traits_copy_trait_function_table(HashTable *target, zend_class_entry *target_ce, HashTable *source, zend_trait_alias** aliases, HashTable* exclude_table TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_arguments(source TSRMLS_CC, (apply_func_args_t)zend_traits_copy_functions, 4, target, target_ce, aliases, exclude_table); } /* }}} */ static void zend_traits_init_trait_structures(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i, j = 0; zend_trait_precedence *cur_precedence; zend_trait_method_reference *cur_method_ref; /* resolve class references */ if (ce->trait_precedences) { i = 0; while ((cur_precedence = ce->trait_precedences[i])) { if (cur_precedence->exclude_from_classes) { cur_precedence->trait_method->ce = zend_fetch_class(cur_precedence->trait_method->class_name, cur_precedence->trait_method->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); j = 0; while (cur_precedence->exclude_from_classes[j]) { char* class_name = (char*)cur_precedence->exclude_from_classes[j]; zend_uint name_length = strlen(class_name); cur_precedence->exclude_from_classes[j] = zend_fetch_class(class_name, name_length, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); efree(class_name); j++; } } i++; } } if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { if (ce->trait_aliases[i]->trait_method->class_name) { cur_method_ref = ce->trait_aliases[i]->trait_method; cur_method_ref->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); } i++; } } } /* }}} */ static void zend_traits_compile_exclude_table(HashTable* exclude_table, zend_trait_precedence **precedences, zend_class_entry *trait) /* {{{ */ { size_t i = 0, j; if (!precedences) { return; } while (precedences[i]) { if (precedences[i]->exclude_from_classes) { j = 0; while (precedences[i]->exclude_from_classes[j]) { if (precedences[i]->exclude_from_classes[j] == trait) { zend_uint lcname_len = precedences[i]->trait_method->mname_len; char *lcname = zend_str_tolower_dup(precedences[i]->trait_method->method_name, lcname_len); if (zend_hash_add(exclude_table, lcname, lcname_len, NULL, 0, NULL) == FAILURE) { efree(lcname); zend_error(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", precedences[i]->trait_method->method_name, trait->name); } efree(lcname); } ++j; } } ++i; } } /* }}} */ static void zend_do_traits_method_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { HashTable** function_tables; HashTable* resulting_table; HashTable exclude_table; size_t i; /* prepare copies of trait function tables for combination */ function_tables = malloc(sizeof(HashTable*) * ce->num_traits); resulting_table = (HashTable *) malloc(sizeof(HashTable)); /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(resulting_table, 10, NULL, NULL, 1, 0); for (i = 0; i < ce->num_traits; i++) { function_tables[i] = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(function_tables[i], ce->traits[i]->function_table.nNumOfElements, NULL, NULL, 1, 0); if (ce->trait_precedences) { /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(&exclude_table, 2, NULL, NULL, 0, 0); zend_traits_compile_exclude_table(&exclude_table, ce->trait_precedences, ce->traits[i]); /* copies functions, applies defined aliasing, and excludes unused trait methods */ zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, &exclude_table TSRMLS_CC); zend_hash_graceful_destroy(&exclude_table); } else { zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, NULL TSRMLS_CC); } } /* now merge trait methods */ for (i = 0; i < ce->num_traits; i++) { zend_hash_apply_with_arguments(function_tables[i] TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions, 5, i, ce->num_traits, resulting_table, function_tables, ce); } /* Now the resulting_table contains all trait methods we would have to * add to the class in the following step the methods are inserted into the method table * if there is already a method with the same name it is replaced iff ce != fn.scope * --> all inherited methods are overridden, methods defined in the class are left untouched */ zend_hash_apply_with_arguments(resulting_table TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions_to_class, 1, ce); /* free temporary function tables */ for (i = 0; i < ce->num_traits; i++) { /* zend_hash_destroy(function_tables[i]); */ zend_hash_graceful_destroy(function_tables[i]); free(function_tables[i]); } free(function_tables); /* free temporary resulting table */ /* zend_hash_destroy(resulting_table); */ zend_hash_graceful_destroy(resulting_table); free(resulting_table); } /* }}} */ static zend_class_entry* find_first_definition(zend_class_entry *ce, size_t current_trait, const char* prop_name, int prop_name_length, ulong prop_hash, zend_class_entry *coliding_ce) /* {{{ */ { size_t i; zend_property_info *coliding_prop; for (i = 0; (i < current_trait) && (i < ce->num_traits); i++) { if (zend_hash_quick_find(&ce->traits[i]->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS) { return ce->traits[i]; } } return coliding_ce; } /* }}} */ static void zend_do_traits_property_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i; zend_property_info *property_info; zend_property_info *coliding_prop; zval compare_result; const char* prop_name; int prop_name_length; ulong prop_hash; const char* class_name_unused; zend_bool prop_found; zend_bool not_compatible; zval* prop_value; /* In the following steps the properties are inserted into the property table * for that, a very strict approach is applied: * - check for compatibility, if not compatible with any property in class -> fatal * - if compatible, then strict notice */ for (i = 0; i < ce->num_traits; i++) { for (zend_hash_internal_pointer_reset(&ce->traits[i]->properties_info); zend_hash_get_current_data(&ce->traits[i]->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->traits[i]->properties_info)) { /* first get the unmangeld name if necessary, * then check whether the property is already there */ if ((property_info->flags & ZEND_ACC_PPP_MASK) == ZEND_ACC_PUBLIC) { prop_hash = property_info->h; prop_name = property_info->name; prop_name_length = property_info->name_length; prop_found = zend_hash_quick_find(&ce->properties_info, property_info->name, property_info->name_length+1, property_info->h, (void **) &coliding_prop) == SUCCESS; } else { /* for private and protected we need to unmangle the names */ zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name_unused, &prop_name); prop_name_length = strlen(prop_name); prop_hash = zend_get_hash_value(prop_name, prop_name_length + 1); prop_found = zend_hash_quick_find(&ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS; } /* next: check for conflicts with current class */ if (prop_found) { if (coliding_prop->flags & ZEND_ACC_SHADOW) { /* this one is inherited, lets look it up in its own class */ zend_hash_quick_find(&coliding_prop->ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop); } if ((coliding_prop->flags & ZEND_ACC_PPP_MASK) == (property_info->flags & ZEND_ACC_PPP_MASK)) { /* flags are identical, now the value needs to be checked */ if (property_info->flags & ZEND_ACC_STATIC) { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_static_members_table[coliding_prop->offset], ce->traits[i]->default_static_members_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } else { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_properties_table[coliding_prop->offset], ce->traits[i]->default_properties_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } } else { /* the flags are not identical, thus, we assume properties are not compatible */ not_compatible = 1; } if (not_compatible) { zend_error(E_COMPILE_ERROR, "%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } else { zend_error(E_STRICT, "%s and %s define the same property ($%s) in the composition of %s. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } } /* property not found, so lets add it */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); zend_declare_property_ex(ce, prop_name, prop_name_length, prop_value, property_info->flags, property_info->doc_comment, property_info->doc_comment_len TSRMLS_CC); } } } /* }}} */ ZEND_API void zend_do_bind_traits(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { if (ce->num_traits <= 0) { return; } /* complete initialization of trait strutures in ce */ zend_traits_init_trait_structures(ce TSRMLS_CC); /* first care about all methods to be flattened into the class */ zend_do_traits_method_binding(ce TSRMLS_CC); /* then flatten the properties into it, to, mostly to notfiy developer about problems */ zend_do_traits_property_binding(ce TSRMLS_CC); /* verify that all abstract methods from traits have been implemented */ zend_verify_abstract_class(ce TSRMLS_CC); /* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */ if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { ce->ce_flags -= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } } /* }}} */ ZEND_API int do_bind_function(const zend_op_array *op_array, zend_op *opline, HashTable *function_table, zend_bool compile_time) /* {{{ */ { zend_function *function; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } zend_hash_quick_find(function_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void *) &function); if (zend_hash_quick_add(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), function, sizeof(zend_function), NULL)==FAILURE) { int error_level = compile_time ? E_COMPILE_ERROR : E_ERROR; zend_function *old_function; if (zend_hash_quick_find(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), (void *) &old_function)==SUCCESS && old_function->type == ZEND_USER_FUNCTION && old_function->op_array.last > 0) { zend_error(error_level, "Cannot redeclare %s() (previously declared in %s:%d)", function->common.function_name, old_function->op_array.filename, old_function->op_array.opcodes[0].lineno); } else { zend_error(error_level, "Cannot redeclare %s()", function->common.function_name); } return FAILURE; } else { (*function->op_array.refcount)++; function->op_array.static_variables = NULL; /* NULL out the unbound function */ return SUCCESS; } } /* }}} */ void zend_add_trait_precedence(znode *precedence_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_precedences, precedence_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_add_trait_alias(znode *alias_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_aliases, alias_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_prepare_reference(znode *result, znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { zend_trait_method_reference *method_ref = emalloc(sizeof(zend_trait_method_reference)); method_ref->ce = NULL; /* REM: There should not be a need for copying, zend_do_begin_class_declaration is also just using that string */ if (class_name) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); method_ref->class_name = Z_STRVAL(class_name->u.constant); method_ref->cname_len = Z_STRLEN(class_name->u.constant); } else { method_ref->class_name = NULL; method_ref->cname_len = 0; } method_ref->method_name = Z_STRVAL(method_name->u.constant); method_ref->mname_len = Z_STRLEN(method_name->u.constant); result->u.op.ptr = method_ref; result->op_type = IS_TMP_VAR; } /* }}} */ void zend_prepare_trait_alias(znode *result, znode *method_reference, znode *modifiers, znode *alias TSRMLS_DC) /* {{{ */ { zend_trait_alias *trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_alias->modifiers = Z_LVAL(modifiers->u.constant); if (Z_LVAL(modifiers->u.constant) == ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot use 'static' as method modifier"); return; } if (alias) { trait_alias->alias = Z_STRVAL(alias->u.constant); trait_alias->alias_len = Z_STRLEN(alias->u.constant); } else { trait_alias->alias = NULL; } trait_alias->function = NULL; result->u.op.ptr = trait_alias; } /* }}} */ void zend_prepare_trait_precedence(znode *result, znode *method_reference, znode *trait_list TSRMLS_DC) /* {{{ */ { zend_trait_precedence *trait_precedence = emalloc(sizeof(zend_trait_precedence)); trait_precedence->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_precedence->exclude_from_classes = (zend_class_entry**) trait_list->u.op.ptr; trait_precedence->function = NULL; result->u.op.ptr = trait_precedence; } /* }}} */ ZEND_API zend_class_entry *do_bind_class(const zend_op_array* op_array, const zend_op *opline, HashTable *class_table, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } if (zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce)==FAILURE) { zend_error(E_COMPILE_ERROR, "Internal Zend error - Missing class information for %s", Z_STRVAL_P(op1)); return NULL; } else { ce = *pce; } ce->refcount++; if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), &ce, sizeof(zend_class_entry *), NULL)==FAILURE) { ce->refcount--; if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return NULL; } else { if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLEMENT_INTERFACES))) { zend_verify_abstract_class(ce TSRMLS_CC); } return ce; } } /* }}} */ ZEND_API zend_class_entry *do_bind_inherited_class(const zend_op_array *op_array, const zend_op *opline, HashTable *class_table, zend_class_entry *parent_ce, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; int found_ce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } found_ce = zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce); if (found_ce == FAILURE) { if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", Z_STRVAL_P(op2)); } return NULL; } else { ce = *pce; } if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ce->name, parent_ce->name); } else if ((parent_ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ce->name, parent_ce->name); } zend_do_inheritance(ce, parent_ce TSRMLS_CC); ce->refcount++; /* Register the derived class */ if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), pce, sizeof(zend_class_entry *), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return ce; } /* }}} */ void zend_do_early_binding(TSRMLS_D) /* {{{ */ { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; HashTable *table; while (opline->opcode == ZEND_TICKS && opline > CG(active_op_array)->opcodes) { opline--; } switch (opline->opcode) { case ZEND_DECLARE_FUNCTION: if (do_bind_function(CG(active_op_array), opline, CG(function_table), 1) == FAILURE) { return; } table = CG(function_table); break; case ZEND_DECLARE_CLASS: if (do_bind_class(CG(active_op_array), opline, CG(class_table), 1 TSRMLS_CC) == NULL) { return; } table = CG(class_table); break; case ZEND_DECLARE_INHERITED_CLASS: { zend_op *fetch_class_opline = opline-1; zval *parent_name; zend_class_entry **pce; parent_name = &CONSTANT(fetch_class_opline->op2.constant); if ((zend_lookup_class(Z_STRVAL_P(parent_name), Z_STRLEN_P(parent_name), &pce TSRMLS_CC) == FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_CLASSES) && ((*pce)->type == ZEND_INTERNAL_CLASS))) { if (CG(compiler_options) & ZEND_COMPILE_DELAYED_BINDING) { zend_uint *opline_num = &CG(active_op_array)->early_binding; while (*opline_num != -1) { opline_num = &CG(active_op_array)->opcodes[*opline_num].result.opline_num; } *opline_num = opline - CG(active_op_array)->opcodes; opline->opcode = ZEND_DECLARE_INHERITED_CLASS_DELAYED; opline->result_type = IS_UNUSED; opline->result.opline_num = -1; } return; } if (do_bind_inherited_class(CG(active_op_array), opline, CG(class_table), *pce, 1 TSRMLS_CC) == NULL) { return; } /* clear unnecessary ZEND_FETCH_CLASS opcode */ zend_del_literal(CG(active_op_array), fetch_class_opline->op2.constant); MAKE_NOP(fetch_class_opline); table = CG(class_table); break; } case ZEND_VERIFY_ABSTRACT_CLASS: case ZEND_ADD_INTERFACE: case ZEND_ADD_TRAIT: case ZEND_BIND_TRAITS: /* We currently don't early-bind classes that implement interfaces */ /* Classes with traits are handled exactly the same, no early-bind here */ return; default: zend_error(E_COMPILE_ERROR, "Invalid binding type"); return; } zend_hash_quick_del(table, Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant)), Z_HASH_P(&CONSTANT(opline->op1.constant))); zend_del_literal(CG(active_op_array), opline->op1.constant); zend_del_literal(CG(active_op_array), opline->op2.constant); MAKE_NOP(opline); } /* }}} */ ZEND_API void zend_do_delayed_early_binding(const zend_op_array *op_array TSRMLS_DC) /* {{{ */ { if (op_array->early_binding != -1) { zend_bool orig_in_compilation = CG(in_compilation); zend_uint opline_num = op_array->early_binding; zend_class_entry **pce; CG(in_compilation) = 1; while (opline_num != -1) { if (zend_lookup_class(Z_STRVAL_P(op_array->opcodes[opline_num-1].op2.zv), Z_STRLEN_P(op_array->opcodes[opline_num-1].op2.zv), &pce TSRMLS_CC) == SUCCESS) { do_bind_inherited_class(op_array, &op_array->opcodes[opline_num], EG(class_table), *pce, 0 TSRMLS_CC); } opline_num = op_array->opcodes[opline_num].result.opline_num; } CG(in_compilation) = orig_in_compilation; } } /* }}} */ void zend_do_boolean_or_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_or_end(znode *result, const znode *expr1, const znode *expr2, znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_boolean_and_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_and_end(znode *result, const znode *expr1, const znode *expr2, const znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_do_while_begin(TSRMLS_D) /* {{{ */ { do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_do_while_end(const znode *do_token, const znode *expr_open_bracket, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ; SET_NODE(opline->op1, expr); opline->op2.opline_num = do_token->u.op.opline_num; SET_UNUSED(opline->op2); do_end_loop(expr_open_bracket->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_brk_cont(zend_uchar op, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->op1.opline_num = CG(context).current_brk_cont; SET_UNUSED(opline->op1); if (expr) { if (expr->op_type != IS_CONST) { zend_error(E_COMPILE_ERROR, "'%s' operator with non-constant operand is no longer supported", op == ZEND_BRK ? "break" : "continue"); } else if (Z_TYPE(expr->u.constant) != IS_LONG || Z_LVAL(expr->u.constant) < 1) { zend_error(E_COMPILE_ERROR, "'%s' operator accepts only positive numbers", op == ZEND_BRK ? "break" : "continue"); } SET_NODE(opline->op2, expr); } else { LITERAL_LONG(opline->op2, 1); opline->op2_type = IS_CONST; } } /* }}} */ void zend_do_switch_cond(const znode *cond TSRMLS_DC) /* {{{ */ { zend_switch_entry switch_entry; switch_entry.cond = *cond; switch_entry.default_case = -1; switch_entry.control_var = -1; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_switch_end(const znode *case_list TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); /* add code to jmp to default case */ if (switch_entry_ptr->default_case != -1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->op1.opline_num = switch_entry_ptr->default_case; } if (case_list->op_type != IS_UNUSED) { /* non-empty switch */ int next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* remember break/continue loop information */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; if (switch_entry_ptr->cond.op_type==IS_VAR || switch_entry_ptr->cond.op_type==IS_TMP_VAR) { /* emit free for the switch condition*/ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry_ptr->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_UNUSED(opline->op2); } if (switch_entry_ptr->cond.op_type == IS_CONST) { zval_dtor(&switch_entry_ptr->cond.u.constant); } zend_stack_del_top(&CG(switch_cond_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_case_before_statement(const znode *case_list, znode *case_token, const znode *case_expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); int next_op_number; zend_switch_entry *switch_entry_ptr; znode result; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); if (switch_entry_ptr->control_var == -1) { switch_entry_ptr->control_var = get_temporary_variable(CG(active_op_array)); } opline->opcode = ZEND_CASE; opline->result.var = switch_entry_ptr->control_var; opline->result_type = IS_TMP_VAR; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_NODE(opline->op2, case_expr); if (opline->op1_type == IS_CONST) { zval_copy_ctor(&CONSTANT(opline->op1.constant)); } GET_NODE(&result, opline->result); next_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, &result); SET_UNUSED(opline->op2); case_token->u.op.opline_num = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_case_after_statement(znode *result, const znode *case_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); result->u.op.opline_num = next_op_number; switch (CG(active_op_array)->opcodes[case_token->u.op.opline_num].opcode) { case ZEND_JMP: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); break; case ZEND_JMPZ: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); break; } } /* }}} */ void zend_do_default_before_statement(const znode *case_list, znode *default_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); default_token->u.op.opline_num = next_op_number; next_op_number = get_next_op_number(CG(active_op_array)); switch_entry_ptr->default_case = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_begin_class_declaration(const znode *class_token, znode *class_name, const znode *parent_class_name TSRMLS_DC) /* {{{ */ { zend_op *opline; int doing_inheritance = 0; zend_class_entry *new_class_entry; char *lcname; int error = 0; zval **ns_name, key; if (CG(active_class_entry)) { zend_error(E_COMPILE_ERROR, "Class declarations may not be nested"); return; } lcname = zend_str_tolower_dup(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); if (!(strcmp(lcname, "self") && strcmp(lcname, "parent"))) { efree(lcname); zend_error(E_COMPILE_ERROR, "Cannot use '%s' as class name as it is reserved", Z_STRVAL(class_name->u.constant)); } /* Class name must not conflict with import names */ if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns_name) == SUCCESS) { error = 1; } if (CG(current_namespace)) { /* Prefix class name with name of current namespace */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); class_name = &tmp; efree(lcname); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); } if (error) { char *tmp = zend_str_tolower_dup(Z_STRVAL_PP(ns_name), Z_STRLEN_PP(ns_name)); if (Z_STRLEN_PP(ns_name) != Z_STRLEN(class_name->u.constant) || memcmp(tmp, lcname, Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "Cannot declare class %s because the name is already in use", Z_STRVAL(class_name->u.constant)); } efree(tmp); } new_class_entry = emalloc(sizeof(zend_class_entry)); new_class_entry->type = ZEND_USER_CLASS; new_class_entry->name = zend_new_interned_string(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1, 1 TSRMLS_CC); new_class_entry->name_length = Z_STRLEN(class_name->u.constant); zend_initialize_class_data(new_class_entry, 1 TSRMLS_CC); new_class_entry->info.user.filename = zend_get_compiled_filename(TSRMLS_C); new_class_entry->info.user.line_start = class_token->u.op.opline_num; new_class_entry->ce_flags |= class_token->EA; if (parent_class_name && parent_class_name->op_type != IS_UNUSED) { switch (parent_class_name->EA) { case ZEND_FETCH_CLASS_SELF: zend_error(E_COMPILE_ERROR, "Cannot use 'self' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_PARENT: zend_error(E_COMPILE_ERROR, "Cannot use 'parent' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use 'static' as class name as it is reserved"); break; default: break; } doing_inheritance = 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, new_class_entry->name_length TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; if (doing_inheritance) { /* Make sure a trait does not try to extend a class */ if ((new_class_entry->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "A trait (%s) cannot extend a class", new_class_entry->name); } opline->extended_value = parent_class_name->u.op.var; opline->opcode = ZEND_DECLARE_INHERITED_CLASS; } else { opline->opcode = ZEND_DECLARE_CLASS; } LITERAL_STRINGL(opline->op2, lcname, new_class_entry->name_length, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); zend_hash_quick_update(CG(class_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &new_class_entry, sizeof(zend_class_entry *), NULL); CG(active_class_entry) = new_class_entry; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(&CG(implementing_class), opline->result); if (CG(doc_comment)) { CG(active_class_entry)->info.user.doc_comment = CG(doc_comment); CG(active_class_entry)->info.user.doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ static void do_verify_abstract_class(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_VERIFY_ABSTRACT_CLASS; SET_NODE(opline->op1, &CG(implementing_class)); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_class_declaration(const znode *class_token, const znode *parent_token TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); if (ce->constructor) { ce->constructor->common.fn_flags |= ZEND_ACC_CTOR; if (ce->constructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Constructor %s::%s() cannot be static", ce->name, ce->constructor->common.function_name); } } if (ce->destructor) { ce->destructor->common.fn_flags |= ZEND_ACC_DTOR; if (ce->destructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Destructor %s::%s() cannot be static", ce->name, ce->destructor->common.function_name); } } if (ce->clone) { ce->clone->common.fn_flags |= ZEND_ACC_CLONE; if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static", ce->name, ce->clone->common.function_name); } } ce->info.user.line_end = zend_get_compiled_lineno(TSRMLS_C); /* Check for traits and proceed like with interfaces. * The only difference will be a combined handling of them in the end. * Thus, we need another opcode here. */ if (ce->num_traits > 0) { zend_op *opline; ce->traits = NULL; ce->num_traits = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_TRAITS; /* opcode generation: */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BIND_TRAITS; SET_NODE(opline->op1, &CG(implementing_class)); } if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) && ((parent_token->op_type != IS_UNUSED) || (ce->num_interfaces > 0))) { zend_verify_abstract_class(ce TSRMLS_CC); if (ce->num_interfaces) { do_verify_abstract_class(TSRMLS_C); } } /* Inherit interfaces; reset number to zero, we need it for above check and * will restore it during actual implementation. * The ZEND_ACC_IMPLEMENT_INTERFACES flag disables double call to * zend_verify_abstract_class() */ if (ce->num_interfaces > 0) { ce->interfaces = NULL; ce->num_interfaces = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_INTERFACES; } CG(active_class_entry) = NULL; } /* }}} */ void zend_do_implements_interface(znode *interface_name TSRMLS_DC) /* {{{ */ { zend_op *opline; /* Traits can not implement interfaces */ if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface on '%s' since it is a Trait", Z_STRVAL(interface_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(interface_name->u.constant), Z_STRLEN(interface_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface name as it is reserved", Z_STRVAL(interface_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_INTERFACE; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(interface_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = (opline->extended_value & ~ZEND_FETCH_CLASS_MASK) | ZEND_FETCH_CLASS_INTERFACE; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &interface_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_interfaces++; } /* }}} */ void zend_do_implements_trait(znode *trait_name TSRMLS_DC) /* {{{ */ { zend_op *opline; if ((CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Cannot use traits inside of interfaces. %s is used in %s", Z_STRVAL(trait_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(trait_name->u.constant), Z_STRLEN(trait_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as trait name as it is reserved", Z_STRVAL(trait_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_TRAIT; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(trait_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = ZEND_FETCH_CLASS_TRAIT; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &trait_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_traits++; } /* }}} */ ZEND_API void zend_mangle_property_name(char **dest, int *dest_length, const char *src1, int src1_length, const char *src2, int src2_length, int internal) /* {{{ */ { char *prop_name; int prop_name_length; prop_name_length = 1 + src1_length + 1 + src2_length; prop_name = pemalloc(prop_name_length + 1, internal); prop_name[0] = '\0'; memcpy(prop_name + 1, src1, src1_length+1); memcpy(prop_name + 1 + src1_length + 1, src2, src2_length+1); *dest = prop_name; *dest_length = prop_name_length; } /* }}} */ static int zend_strnlen(const char* s, int maxlen) /* {{{ */ { int len = 0; while (*s++ && maxlen--) len++; return len; } /* }}} */ ZEND_API int zend_unmangle_property_name(const char *mangled_property, int len, const char **class_name, const char **prop_name) /* {{{ */ { int class_name_len; *class_name = NULL; if (mangled_property[0]!=0) { *prop_name = mangled_property; return SUCCESS; } if (len < 3 || mangled_property[1]==0) { zend_error(E_NOTICE, "Illegal member variable name"); *prop_name = mangled_property; return FAILURE; } class_name_len = zend_strnlen(mangled_property+1, --len - 1) + 1; if (class_name_len >= len || mangled_property[class_name_len]!=0) { zend_error(E_NOTICE, "Corrupt member variable name"); *prop_name = mangled_property; return FAILURE; } *class_name = mangled_property+1; *prop_name = (*class_name)+class_name_len; return SUCCESS; } /* }}} */ void zend_do_declare_property(const znode *var_name, const znode *value, zend_uint access_type TSRMLS_DC) /* {{{ */ { zval *property; zend_property_info *existing_property_info; char *comment = NULL; int comment_len = 0; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Interfaces may not include member variables"); } if (access_type & ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Properties cannot be declared abstract"); } if (access_type & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot declare property %s::$%s final, the final modifier is allowed only for methods and classes", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } if (zend_hash_find(&CG(active_class_entry)->properties_info, var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, (void **) &existing_property_info)==SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::$%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } ALLOC_ZVAL(property); if (value) { *property = value->u.constant; } else { INIT_PZVAL(property); Z_TYPE_P(property) = IS_NULL; } if (CG(doc_comment)) { comment = CG(doc_comment); comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } zend_declare_property_ex(CG(active_class_entry), zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len + 1, 0 TSRMLS_CC), var_name->u.constant.value.str.len, property, access_type, comment, comment_len TSRMLS_CC); efree(var_name->u.constant.value.str.val); } /* }}} */ void zend_do_declare_class_constant(znode *var_name, const znode *value TSRMLS_DC) /* {{{ */ { zval *property; const char *cname = NULL; int result; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed in class constants"); return; } if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Traits cannot have constants"); return; } ALLOC_ZVAL(property); *property = value->u.constant; cname = zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, 0 TSRMLS_CC); if (IS_INTERNED(cname)) { result = zend_hash_quick_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, INTERNED_HASH(cname), &property, sizeof(zval *), NULL); } else { result = zend_hash_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, &property, sizeof(zval *), NULL); } if (result == FAILURE) { FREE_ZVAL(property); zend_error(E_COMPILE_ERROR, "Cannot redefine class constant %s::%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } FREE_PNODE(var_name); if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_fetch_property(znode *result, znode *object, const znode *property TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (object->op_type == IS_CV) { if (object->u.op.var == CG(active_op_array)->this_var) { object->op_type = IS_UNUSED; /* this means $this for objects */ } } else if (fetch_list_ptr->count == 1) { zend_llist_element *le = fetch_list_ptr->head; zend_op *opline_ptr = (zend_op *) le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); SET_UNUSED(opline_ptr->op1); /* this means $this for objects */ SET_NODE(opline_ptr->op2, property); /* if it was usual fetch, we change it to object fetch */ switch (opline_ptr->opcode) { case ZEND_FETCH_W: opline_ptr->opcode = ZEND_FETCH_OBJ_W; break; case ZEND_FETCH_R: opline_ptr->opcode = ZEND_FETCH_OBJ_R; break; case ZEND_FETCH_RW: opline_ptr->opcode = ZEND_FETCH_OBJ_RW; break; case ZEND_FETCH_IS: opline_ptr->opcode = ZEND_FETCH_OBJ_IS; break; case ZEND_FETCH_UNSET: opline_ptr->opcode = ZEND_FETCH_OBJ_UNSET; break; case ZEND_FETCH_FUNC_ARG: opline_ptr->opcode = ZEND_FETCH_OBJ_FUNC_ARG; break; } if (opline_ptr->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline_ptr->op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline_ptr->op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op2.constant); } GET_NODE(result, opline_ptr->result); return; } } if (zend_is_function_or_method_call(object)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, object); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_OBJ_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, object); SET_NODE(opline.op2, property); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline.op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op2.constant); } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void zend_do_halt_compiler_register(TSRMLS_D) /* {{{ */ { char *name, *cfilename; char haltoff[] = "__COMPILER_HALT_OFFSET__"; int len, clen; cfilename = zend_get_compiled_filename(TSRMLS_C); clen = strlen(cfilename); zend_mangle_property_name(&name, &len, haltoff, sizeof(haltoff) - 1, cfilename, clen, 0); zend_register_long_constant(name, len+1, zend_get_scanned_file_offset(TSRMLS_C), CONST_CS, 0 TSRMLS_CC); pefree(name, 0); if (CG(in_namespace)) { zend_do_end_namespace(TSRMLS_C); } } /* }}} */ void zend_do_push_object(const znode *object TSRMLS_DC) /* {{{ */ { zend_stack_push(&CG(object_stack), object, sizeof(znode)); } /* }}} */ void zend_do_pop_object(znode *object TSRMLS_DC) /* {{{ */ { if (object) { znode *tmp; zend_stack_top(&CG(object_stack), (void **) &tmp); *object = *tmp; } zend_stack_del_top(&CG(object_stack)); } /* }}} */ void zend_do_begin_new_object(znode *new_token, znode *class_type TSRMLS_DC) /* {{{ */ { zend_op *opline; unsigned char *ptr = NULL; new_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_NEW; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, class_type); SET_UNUSED(opline->op2); zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(unsigned char *)); } /* }}} */ void zend_do_end_new_object(znode *result, const znode *new_token, const znode *argument_list TSRMLS_DC) /* {{{ */ { znode ctor_result; zend_do_end_function_call(NULL, &ctor_result, argument_list, 1, 0 TSRMLS_CC); zend_do_free(&ctor_result TSRMLS_CC); CG(active_op_array)->opcodes[new_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, CG(active_op_array)->opcodes[new_token->u.op.opline_num].result); } /* }}} */ static zend_constant* zend_get_ct_const(const zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = NULL; if (Z_STRVAL_P(const_name)[0] == '\\') { if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name), (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name)-1); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name), (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } } else if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)+1, (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name)+1, (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } if (c->flags & CONST_CT_SUBST) { return c; } if (all_internal_constants_substitution && (c->flags & CONST_PERSISTENT) && !(CG(compiler_options) & ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION) && Z_TYPE(c->value) != IS_CONSTANT && Z_TYPE(c->value) != IS_CONSTANT_ARRAY) { return c; } return NULL; } /* }}} */ static int zend_constant_ct_subst(znode *result, zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = zend_get_ct_const(const_name, all_internal_constants_substitution TSRMLS_CC); if (c) { zval_dtor(const_name); result->op_type = IS_CONST; result->u.constant = c->value; zval_copy_ctor(&result->u.constant); INIT_PZVAL(&result->u.constant); return 1; } return 0; } /* }}} */ void zend_do_fetch_constant(znode *result, znode *constant_container, znode *constant_name, int mode, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; zend_op *opline; int type; char *compound; ulong fetch_type = 0; if (constant_container) { switch (mode) { case ZEND_CT: /* this is a class constant */ type = zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant)); if (ZEND_FETCH_CLASS_STATIC == type) { zend_error(E_ERROR, "\"static::\" is not allowed in compile-time constants"); } else if (ZEND_FETCH_CLASS_DEFAULT == type) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } zend_do_build_full_name(NULL, constant_container, constant_name, 1 TSRMLS_CC); *result = *constant_container; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: if (constant_container->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant))) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } else { zend_do_fetch_class(&tmp, constant_container TSRMLS_CC); constant_container = &tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); if (constant_container->op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &constant_container->u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, constant_container); } SET_NODE(opline->op2, constant_name); CALCULATE_LITERAL_HASH(opline->op2.constant); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } GET_NODE(result, opline->result); break; } return; } /* namespace constant */ /* only one that did not contain \ from the start can be converted to string if unknown */ switch (mode) { case ZEND_CT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); /* this is a namespace constant, or an unprefixed constant */ if (zend_constant_ct_subst(result, &constant_name->u.constant, 0 TSRMLS_CC)) { break; } zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(!compound) { fetch_type |= IS_CONSTANT_UNQUALIFIED; } *result = *constant_name; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(zend_constant_ct_subst(result, &constant_name->u.constant, 1 TSRMLS_CC)) { break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; if (compound) { /* the name is unambiguous */ opline->extended_value = 0; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } else { opline->extended_value = IS_CONSTANT_UNQUALIFIED; if (CG(current_namespace)) { opline->extended_value |= IS_CONSTANT_IN_NAMESPACE; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 1 TSRMLS_CC); } else { opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } } GET_CACHE_SLOT(opline->op2.constant); break; } } /* }}} */ void zend_do_shell_exec(znode *result, const znode *cmd TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); switch (cmd->op_type) { case IS_CONST: case IS_TMP_VAR: opline->opcode = ZEND_SEND_VAL; break; default: opline->opcode = ZEND_SEND_VAR; break; } SET_NODE(opline->op1, cmd); opline->op2.opline_num = 0; opline->extended_value = ZEND_DO_FCALL; SET_UNUSED(opline->op2); /* FIXME: exception support not added to this op2 */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DO_FCALL; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; LITERAL_STRINGL(opline->op1, estrndup("shell_exec", sizeof("shell_exec")-1), sizeof("shell_exec")-1, 0); CALCULATE_LITERAL_HASH(opline->op1.constant); opline->op1_type = IS_CONST; GET_CACHE_SLOT(opline->op1.constant); opline->extended_value = 1; SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_init_array(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_ARRAY; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; GET_NODE(result, opline->result); if (expr) { SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } } else { SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_array_element(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_ARRAY_ELEMENT; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_static_array_element(znode *result, znode *offset, const znode *expr) /* {{{ */ { zval *element; ALLOC_ZVAL(element); *element = expr->u.constant; if (offset) { switch (offset->u.constant.type & IS_CONSTANT_TYPE_MASK) { case IS_CONSTANT: /* Ugly hack to denote that this value has a constant index */ Z_TYPE_P(element) |= IS_CONSTANT_INDEX; Z_STRVAL(offset->u.constant) = erealloc(Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+1] = Z_TYPE(offset->u.constant); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+2] = 0; zend_symtable_update(result->u.constant.value.ht, Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_STRING: zend_symtable_update(result->u.constant.value.ht, offset->u.constant.value.str.val, offset->u.constant.value.str.len+1, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_NULL: zend_symtable_update(Z_ARRVAL(result->u.constant), "", 1, &element, sizeof(zval *), NULL); break; case IS_LONG: case IS_BOOL: zend_hash_index_update(Z_ARRVAL(result->u.constant), Z_LVAL(offset->u.constant), &element, sizeof(zval *), NULL); break; case IS_DOUBLE: zend_hash_index_update(Z_ARRVAL(result->u.constant), zend_dval_to_lval(Z_DVAL(offset->u.constant)), &element, sizeof(zval *), NULL); break; case IS_CONSTANT_ARRAY: zend_error(E_ERROR, "Illegal offset type"); break; } } else { zend_hash_next_index_insert(Z_ARRVAL(result->u.constant), &element, sizeof(zval *), NULL); } } /* }}} */ void zend_do_add_list_element(const znode *element TSRMLS_DC) /* {{{ */ { list_llist_element lle; if (element) { zend_check_writable_variable(element); lle.var = *element; zend_llist_copy(&lle.dimensions, &CG(dimension_llist)); zend_llist_prepend_element(&CG(list_llist), &lle); } (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_new_list_begin(TSRMLS_D) /* {{{ */ { int current_dimension = 0; zend_llist_add_element(&CG(dimension_llist), &current_dimension); } /* }}} */ void zend_do_new_list_end(TSRMLS_D) /* {{{ */ { zend_llist_remove_tail(&CG(dimension_llist)); (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_list_init(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(list_stack), &CG(list_llist), sizeof(zend_llist)); zend_stack_push(&CG(list_stack), &CG(dimension_llist), sizeof(zend_llist)); zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_do_new_list_begin(TSRMLS_C); } /* }}} */ void zend_do_list_end(znode *result, znode *expr TSRMLS_DC) /* {{{ */ { zend_llist_element *le; zend_llist_element *dimension; zend_op *opline; znode last_container; le = CG(list_llist).head; while (le) { zend_llist *tmp_dimension_llist = &((list_llist_element *)le->data)->dimensions; dimension = tmp_dimension_llist->head; while (dimension) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (dimension == tmp_dimension_llist->head) { /* first */ last_container = *expr; switch (expr->op_type) { case IS_VAR: case IS_CV: opline->opcode = ZEND_FETCH_DIM_R; break; case IS_TMP_VAR: opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; case IS_CONST: /* fetch_dim_tmp_var will handle this bogus fetch */ zval_copy_ctor(&expr->u.constant); opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; } opline->extended_value |= ZEND_FETCH_ADD_LOCK; } else { opline->opcode = ZEND_FETCH_DIM_R; } opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, &last_container); opline->op2_type = IS_CONST; LITERAL_LONG(opline->op2, *((int *) dimension->data)); GET_NODE(&last_container, opline->result); dimension = dimension->next; } ((list_llist_element *) le->data)->value = last_container; zend_llist_destroy(&((list_llist_element *) le->data)->dimensions); zend_do_assign(result, &((list_llist_element *) le->data)->var, &((list_llist_element *) le->data)->value TSRMLS_CC); zend_do_free(result TSRMLS_CC); le = le->next; } zend_llist_destroy(&CG(dimension_llist)); zend_llist_destroy(&CG(list_llist)); *result = *expr; { zend_llist *p; /* restore previous lists */ zend_stack_top(&CG(list_stack), (void **) &p); CG(dimension_llist) = *p; zend_stack_del_top(&CG(list_stack)); zend_stack_top(&CG(list_stack), (void **) &p); CG(list_llist) = *p; zend_stack_del_top(&CG(list_stack)); } } /* }}} */ void zend_init_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = emalloc(sizeof(void*) * 2); list[0] = item; list[1] = NULL; *(void**)result = list; } /* }}} */ void zend_add_to_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = *(void**)result; size_t n = 0; while (list && list[n]) { n++; } list = erealloc(list, sizeof(void*) * (n+2)); list[n] = item; list[n+1] = NULL; *(void**)result = list; } /* }}} */ void zend_do_fetch_static_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zval *tmp; zend_op *opline; znode lval; znode result; ALLOC_ZVAL(tmp); if (static_assignment) { *tmp = static_assignment->u.constant; } else { INIT_ZVAL(*tmp); } if (!CG(active_op_array)->static_variables) { if (CG(active_op_array)->scope) { CG(active_op_array)->scope->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } ALLOC_HASHTABLE(CG(active_op_array)->static_variables); zend_hash_init(CG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } zend_hash_update(CG(active_op_array)->static_variables, varname->u.constant.value.str.val, varname->u.constant.value.str.len+1, &tmp, sizeof(zval *), NULL); if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (fetch_type == ZEND_FETCH_LEXICAL) ? ZEND_FETCH_R : ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_STATIC; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ if (fetch_type == ZEND_FETCH_LEXICAL) { znode dummy; zend_do_begin_variable_parse(TSRMLS_C); zend_do_assign(&dummy, &lval, &result TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } else { zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); } CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_fetch_lexical_variable(znode *varname, zend_bool is_ref TSRMLS_DC) /* {{{ */ { znode value; if (Z_STRLEN(varname->u.constant) == sizeof("this") - 1 && memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this") - 1) == 0) { zend_error(E_COMPILE_ERROR, "Cannot use $this as lexical variable"); return; } value.op_type = IS_CONST; ZVAL_NULL(&value.u.constant); Z_TYPE(value.u.constant) |= is_ref ? IS_LEXICAL_REF : IS_LEXICAL_VAR; Z_SET_REFCOUNT_P(&value.u.constant, 1); Z_UNSET_ISREF_P(&value.u.constant); zend_do_fetch_static_variable(varname, &value, is_ref ? ZEND_FETCH_STATIC : ZEND_FETCH_LEXICAL TSRMLS_CC); } /* }}} */ void zend_do_fetch_global_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zend_op *opline; znode lval; znode result; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = fetch_type; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_cast(znode *result, const znode *expr, int type TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CAST; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } /* }}} */ void zend_do_include_or_eval(int type, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_do_extended_fcall_begin(TSRMLS_C); { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INCLUDE_OR_EVAL; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } zend_do_extended_fcall_end(TSRMLS_C); } /* }}} */ void zend_do_indirect_references(znode *result, const znode *num_references, znode *variable TSRMLS_DC) /* {{{ */ { int i; zend_do_end_variable_parse(variable, BP_VAR_R, 0 TSRMLS_CC); for (i=1; i<num_references->u.constant.value.lval; i++) { fetch_simple_variable_ex(result, variable, 0, ZEND_FETCH_R TSRMLS_CC); *variable = *result; } zend_do_begin_variable_parse(TSRMLS_C); fetch_simple_variable(result, variable, 1 TSRMLS_CC); /* there is a chance someone is accessing $this */ if (CG(active_op_array)->scope && CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } /* }}} */ void zend_do_unset(const znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_UNSET_VAR; SET_NODE(opline->op1, variable); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); opline->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_UNSET: last_op->opcode = ZEND_UNSET_VAR; SET_UNUSED(last_op->result); break; case ZEND_FETCH_DIM_UNSET: last_op->opcode = ZEND_UNSET_DIM; SET_UNUSED(last_op->result); break; case ZEND_FETCH_OBJ_UNSET: last_op->opcode = ZEND_UNSET_OBJ; SET_UNUSED(last_op->result); break; } } } /* }}} */ void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_do_end_variable_parse(variable, BP_VAR_IS, 0 TSRMLS_CC); zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { last_op = get_next_op(CG(active_op_array) TSRMLS_CC); last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; SET_NODE(last_op->op1, variable); SET_UNUSED(last_op->op2); last_op->result.var = get_temporary_variable(CG(active_op_array)); last_op->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; break; case ZEND_FETCH_DIM_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_DIM_OBJ; break; case ZEND_FETCH_OBJ_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_PROP_OBJ; break; } } last_op->result_type = IS_TMP_VAR; last_op->extended_value |= type; GET_NODE(result, last_op->result); } /* }}} */ void zend_do_instanceof(znode *result, const znode *expr, const znode *class_znode, int type TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline->opcode == ZEND_FETCH_CLASS) { opline->extended_value |= ZEND_FETCH_CLASS_NO_AUTOLOAD; } } if (expr->op_type == IS_CONST) { zend_error(E_COMPILE_ERROR, "instanceof expects an object instance, constant given"); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INSTANCEOF; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_NODE(opline->op2, class_znode); GET_NODE(result, opline->result); } /* }}} */ void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_bool is_variable; zend_bool push_container = 0; zend_op dummy_opline; if (variable) { if (zend_is_function_or_method_call(array)) { is_variable = 0; } else { is_variable = 1; } /* save the location of FETCH_W instruction(s) */ open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); zend_do_end_variable_parse(array, BP_VAR_W, 0 TSRMLS_CC); if (CG(active_op_array)->last > 0 && CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) { /* Only lock the container if we are fetching from a real container and not $this */ if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1_type == IS_VAR) { CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK; push_container = 1; } } } else { is_variable = 0; open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* save the location of FE_RESET */ foreach_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* Preform array reset */ opline->opcode = ZEND_FE_RESET; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, array); SET_UNUSED(opline->op2); opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0; COPY_NODE(dummy_opline.result, opline->result); if (push_container) { COPY_NODE(dummy_opline.op1, CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1); } else { dummy_opline.op1_type = IS_UNUSED; } zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); /* save the location of FE_FETCH */ as_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FE_FETCH; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); COPY_NODE(opline->op1, dummy_opline.result); opline->extended_value = 0; SET_UNUSED(opline->op2); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_OP_DATA; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); } /* }}} */ void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC) /* {{{ */ { zend_op *opline; znode dummy, value_node; zend_bool assign_by_ref=0; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num]; if (key->op_type != IS_UNUSED) { znode *tmp; /* switch between the key and value... */ tmp = key; key = value; value = tmp; /* Mark extended_value in case both key and value are being used */ opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; } if ((key->op_type != IS_UNUSED) && (key->EA & ZEND_PARSED_REFERENCE_VARIABLE)) { zend_error(E_COMPILE_ERROR, "Key element cannot be a reference"); } if (value->EA & ZEND_PARSED_REFERENCE_VARIABLE) { assign_by_ref = 1; if (!(opline-1)->extended_value) { zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression"); } /* Mark extended_value for assign-by-reference */ opline->extended_value |= ZEND_FE_FETCH_BYREF; CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; } else { zend_op *foreach_copy; zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.op.opline_num]; zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.op.opline_num]; /* Change "write context" into "read context" */ fetch->extended_value = 0; /* reset ZEND_FE_RESET_VARIABLE */ while (fetch != end) { --fetch; if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } if (fetch->opcode == ZEND_SEPARATE) { MAKE_NOP(fetch); } else { fetch->opcode -= 3; /* FETCH_W -> FETCH_R */ } } /* prevent double SWITCH_FREE */ zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy); foreach_copy->op1_type = IS_UNUSED; } GET_NODE(&value_node, opline->result); if (assign_by_ref) { zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); /* Mark FE_FETCH as IS_VAR as it holds the data directly as a value */ zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC); } else { zend_do_assign(&dummy, value, &value_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } if (key->op_type != IS_UNUSED) { znode key_node; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num+1]; opline->result_type = IS_TMP_VAR; opline->result.opline_num = get_temporary_variable(CG(active_op_array)); GET_NODE(&key_node, opline->result); zend_do_assign(&dummy, key, &key_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_foreach_end(const znode *foreach_token, const znode *as_token TSRMLS_DC) /* {{{ */ { zend_op *container_ptr; zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = as_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_RESET */ CG(active_op_array)->opcodes[as_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_FETCH */ do_end_loop(as_token->u.op.opline_num, 1 TSRMLS_CC); zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr); generate_free_foreach_copy(container_ptr TSRMLS_CC); zend_stack_del_top(&CG(foreach_copy_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_declare_begin(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(declare_stack), &CG(declarables), sizeof(zend_declarables)); } /* }}} */ void zend_do_declare_stmt(znode *var, znode *val TSRMLS_DC) /* {{{ */ { if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "ticks", sizeof("ticks")-1)) { convert_to_long(&val->u.constant); CG(declarables).ticks = val->u.constant; } else if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "encoding", sizeof("encoding")-1)) { if ((Z_TYPE(val->u.constant) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Cannot use constants as encoding"); } /* * Check that the pragma comes before any opcodes. If the compilation * got as far as this, the previous portion of the script must have been * parseable according to the .ini script_encoding setting. We still * want to tell them to put declare() at the top. */ { int num = CG(active_op_array)->last; /* ignore ZEND_EXT_STMT and ZEND_TICKS */ while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Encoding declaration pragma must be the very first statement in the script"); } } if (CG(multibyte)) { const zend_encoding *new_encoding, *old_encoding; zend_encoding_filter old_input_filter; CG(encoding_declared) = 1; convert_to_string(&val->u.constant); new_encoding = zend_multibyte_fetch_encoding(val->u.constant.value.str.val TSRMLS_CC); if (!new_encoding) { zend_error(E_COMPILE_WARNING, "Unsupported encoding [%s]", val->u.constant.value.str.val); } else { old_input_filter = LANG_SCNG(input_filter); old_encoding = LANG_SCNG(script_encoding); zend_multibyte_set_filter(new_encoding TSRMLS_CC); /* need to re-scan if input filter changed */ if (old_input_filter != LANG_SCNG(input_filter) || (old_input_filter && new_encoding != old_encoding)) { zend_multibyte_yyinput_again(old_input_filter, old_encoding TSRMLS_CC); } } } else { zend_error(E_COMPILE_WARNING, "declare(encoding=...) ignored because Zend multibyte feature is turned off by settings"); } zval_dtor(&val->u.constant); } else { zend_error(E_COMPILE_WARNING, "Unsupported declare '%s'", var->u.constant.value.str.val); zval_dtor(&val->u.constant); } zval_dtor(&var->u.constant); } /* }}} */ void zend_do_declare_end(const znode *declare_token TSRMLS_DC) /* {{{ */ { zend_declarables *declarables; zend_stack_top(&CG(declare_stack), (void **) &declarables); /* We should restore if there was more than (current - start) - (ticks?1:0) opcodes */ if ((get_next_op_number(CG(active_op_array)) - declare_token->u.op.opline_num) - ((Z_LVAL(CG(declarables).ticks))?1:0)) { CG(declarables) = *declarables; } } /* }}} */ void zend_do_exit(znode *result, const znode *message TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXIT; SET_NODE(opline->op1, message); SET_UNUSED(opline->op2); result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_BOOL; Z_LVAL(result->u.constant) = 1; } /* }}} */ void zend_do_begin_silence(znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BEGIN_SILENCE; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); GET_NODE(strudel_token, opline->result); } /* }}} */ void zend_do_end_silence(const znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_END_SILENCE; SET_NODE(opline->op1, strudel_token); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_jmp_set(const znode *value, znode *jmp_token, znode *colon_token TSRMLS_DC) /* {{{ */ { int op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (value->op_type == IS_VAR || value->op_type == IS_CV) { opline->opcode = ZEND_JMP_SET_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_JMP_SET; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, value); SET_UNUSED(opline->op2); GET_NODE(colon_token, opline->result); jmp_token->u.op .opline_num = op_number; INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_jmp_set_else(znode *result, const znode *false_value, const znode *jmp_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, colon_token); if (colon_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].opcode = ZEND_JMP_SET_VAR; CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } opline->extended_value = 0; SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_qm_op(const znode *cond, znode *qm_token TSRMLS_DC) /* {{{ */ { int jmpz_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); SET_UNUSED(opline->op2); opline->op2.opline_num = jmpz_op_number; GET_NODE(qm_token, opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_qm_true(const znode *true_value, znode *qm_token, znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->opcodes[qm_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array))+1; /* jmp over the ZEND_JMP */ if (true_value->op_type == IS_VAR || true_value->op_type == IS_CV) { opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, true_value); SET_UNUSED(opline->op2); GET_NODE(qm_token, opline->result); colon_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_qm_false(znode *result, const znode *false_value, const znode *qm_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, qm_token); if (qm_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].opcode = ZEND_QM_ASSIGN_VAR; CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[colon_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, opline->result); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_extended_info(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_STMT; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_begin(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_BEGIN; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_end(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_END; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_ticks(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_TICKS; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->extended_value = Z_LVAL(CG(declarables).ticks); } /* }}} */ zend_bool zend_is_auto_global_quick(const char *name, uint name_len, ulong hashval TSRMLS_DC) /* {{{ */ { zend_auto_global *auto_global; ulong hash = hashval ? hashval : zend_hash_func(name, name_len+1); if (zend_hash_quick_find(CG(auto_globals), name, name_len+1, hash, (void **) &auto_global)==SUCCESS) { if (auto_global->armed) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } return 1; } return 0; } /* }}} */ zend_bool zend_is_auto_global(const char *name, uint name_len TSRMLS_DC) /* {{{ */ { return zend_is_auto_global_quick(name, name_len, 0 TSRMLS_CC); } /* }}} */ int zend_register_auto_global(const char *name, uint name_len, zend_bool jit, zend_auto_global_callback auto_global_callback TSRMLS_DC) /* {{{ */ { zend_auto_global auto_global; auto_global.name = zend_new_interned_string((char*)name, name_len + 1, 0 TSRMLS_CC); auto_global.name_len = name_len; auto_global.auto_global_callback = auto_global_callback; auto_global.jit = jit; return zend_hash_add(CG(auto_globals), name, name_len+1, &auto_global, sizeof(zend_auto_global), NULL); } /* }}} */ static int zend_auto_global_init(zend_auto_global *auto_global TSRMLS_DC) /* {{{ */ { if (auto_global->jit) { auto_global->armed = 1; } else if (auto_global->auto_global_callback) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } else { auto_global->armed = 0; } return 0; } /* }}} */ ZEND_API void zend_activate_auto_globals(TSRMLS_D) /* {{{ */ { zend_hash_apply(CG(auto_globals), (apply_func_t) zend_auto_global_init TSRMLS_CC); } /* }}} */ int zendlex(znode *zendlval TSRMLS_DC) /* {{{ */ { int retval; if (CG(increment_lineno)) { CG(zend_lineno)++; CG(increment_lineno) = 0; } again: Z_TYPE(zendlval->u.constant) = IS_LONG; retval = lex_scan(&zendlval->u.constant TSRMLS_CC); switch (retval) { case T_COMMENT: case T_DOC_COMMENT: case T_OPEN_TAG: case T_WHITESPACE: goto again; case T_CLOSE_TAG: if (LANG_SCNG(yy_text)[LANG_SCNG(yy_leng)-1] != '>') { CG(increment_lineno) = 1; } if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { goto again; } retval = ';'; /* implicit ; */ break; case T_OPEN_TAG_WITH_ECHO: retval = T_ECHO; break; case T_END_HEREDOC: efree(Z_STRVAL(zendlval->u.constant)); break; } INIT_PZVAL(&zendlval->u.constant); zendlval->op_type = IS_CONST; return retval; } /* }}} */ ZEND_API void zend_initialize_class_data(zend_class_entry *ce, zend_bool nullify_handlers TSRMLS_DC) /* {{{ */ { zend_bool persistent_hashes = (ce->type == ZEND_INTERNAL_CLASS) ? 1 : 0; dtor_func_t zval_ptr_dtor_func = ((persistent_hashes) ? ZVAL_INTERNAL_PTR_DTOR : ZVAL_PTR_DTOR); ce->refcount = 1; ce->ce_flags = 0; ce->default_properties_table = NULL; ce->default_static_members_table = NULL; zend_hash_init_ex(&ce->properties_info, 0, NULL, (dtor_func_t) (persistent_hashes ? zend_destroy_property_info_internal : zend_destroy_property_info), persistent_hashes, 0); zend_hash_init_ex(&ce->constants_table, 0, NULL, zval_ptr_dtor_func, persistent_hashes, 0); zend_hash_init_ex(&ce->function_table, 0, NULL, ZEND_FUNCTION_DTOR, persistent_hashes, 0); if (ce->type == ZEND_INTERNAL_CLASS) { #ifdef ZTS int n = zend_hash_num_elements(CG(class_table)); if (CG(static_members_table) && n >= CG(last_static_member)) { /* Support for run-time declaration: dl() */ CG(last_static_member) = n+1; CG(static_members_table) = realloc(CG(static_members_table), (n+1)*sizeof(zval**)); CG(static_members_table)[n] = NULL; } ce->static_members_table = (zval**)(zend_intptr_t)n; #else ce->static_members_table = NULL; #endif } else { ce->static_members_table = ce->default_static_members_table; ce->info.user.doc_comment = NULL; ce->info.user.doc_comment_len = 0; } ce->default_properties_count = 0; ce->default_static_members_count = 0; if (nullify_handlers) { ce->constructor = NULL; ce->destructor = NULL; ce->clone = NULL; ce->__get = NULL; ce->__set = NULL; ce->__unset = NULL; ce->__isset = NULL; ce->__call = NULL; ce->__callstatic = NULL; ce->__tostring = NULL; ce->create_object = NULL; ce->get_iterator = NULL; ce->iterator_funcs.funcs = NULL; ce->interface_gets_implemented = NULL; ce->get_static_method = NULL; ce->parent = NULL; ce->num_interfaces = 0; ce->interfaces = NULL; ce->num_traits = 0; ce->traits = NULL; ce->trait_aliases = NULL; ce->trait_precedences = NULL; ce->serialize = NULL; ce->unserialize = NULL; ce->serialize_func = NULL; ce->unserialize_func = NULL; if (ce->type == ZEND_INTERNAL_CLASS) { ce->info.internal.module = NULL; ce->info.internal.builtin_functions = NULL; } } } /* }}} */ int zend_get_class_fetch_type(const char *class_name, uint class_name_len) /* {{{ */ { if ((class_name_len == sizeof("self")-1) && !memcmp(class_name, "self", sizeof("self")-1)) { return ZEND_FETCH_CLASS_SELF; } else if ((class_name_len == sizeof("parent")-1) && !memcmp(class_name, "parent", sizeof("parent")-1)) { return ZEND_FETCH_CLASS_PARENT; } else if ((class_name_len == sizeof("static")-1) && !memcmp(class_name, "static", sizeof("static")-1)) { return ZEND_FETCH_CLASS_STATIC; } else { return ZEND_FETCH_CLASS_DEFAULT; } } /* }}} */ ZEND_API const char* zend_get_compiled_variable_name(const zend_op_array *op_array, zend_uint var, int* name_len) /* {{{ */ { if (name_len) { *name_len = op_array->vars[var].name_len; } return op_array->vars[var].name; } /* }}} */ void zend_do_build_namespace_name(znode *result, znode *prefix, znode *name TSRMLS_DC) /* {{{ */ { if (prefix) { *result = *prefix; if (Z_TYPE(result->u.constant) == IS_STRING && Z_STRLEN(result->u.constant) == 0) { /* namespace\ */ if (CG(current_namespace)) { znode tmp; zval_dtor(&result->u.constant); tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(result, NULL, &tmp TSRMLS_CC); } } } else { result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_STRING; Z_STRVAL(result->u.constant) = NULL; Z_STRLEN(result->u.constant) = 0; } /* prefix = result */ zend_do_build_full_name(NULL, result, name, 0 TSRMLS_CC); } /* }}} */ void zend_do_begin_namespace(const znode *name, zend_bool with_bracket TSRMLS_DC) /* {{{ */ { char *lcname; /* handle mixed syntax declaration or nested namespaces */ if (!CG(has_bracketed_namespaces)) { if (CG(current_namespace)) { /* previous namespace declarations were unbracketed */ if (with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } } } else { /* previous namespace declarations were bracketed */ if (!with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } else if (CG(current_namespace) || CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "Namespace declarations cannot be nested"); } } if (((!with_bracket && !CG(current_namespace)) || (with_bracket && !CG(has_bracketed_namespaces))) && CG(active_op_array)->last > 0) { /* ignore ZEND_EXT_STMT and ZEND_TICKS */ int num = CG(active_op_array)->last; while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Namespace declaration statement has to be the very first statement in the script"); } } CG(in_namespace) = 1; if (with_bracket) { CG(has_bracketed_namespaces) = 1; } if (name) { lcname = zend_str_tolower_dup(Z_STRVAL(name->u.constant), Z_STRLEN(name->u.constant)); if (((Z_STRLEN(name->u.constant) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN(name->u.constant) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as namespace name", Z_STRVAL(name->u.constant)); } efree(lcname); if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); } else { ALLOC_ZVAL(CG(current_namespace)); } *CG(current_namespace) = name->u.constant; } else { if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_use(znode *ns_name, znode *new_name, int is_global TSRMLS_DC) /* {{{ */ { char *lcname; zval *name, *ns, tmp; zend_bool warn = 0; zend_class_entry **pce; if (!CG(current_import)) { CG(current_import) = emalloc(sizeof(HashTable)); zend_hash_init(CG(current_import), 0, NULL, ZVAL_PTR_DTOR, 0); } ALLOC_ZVAL(ns); *ns = ns_name->u.constant; if (new_name) { name = &new_name->u.constant; } else { const char *p; /* The form "use A\B" is eqivalent to "use A\B as B". So we extract the last part of compound name to use as a new_name */ name = &tmp; p = zend_memrchr(Z_STRVAL_P(ns), '\\', Z_STRLEN_P(ns)); if (p) { ZVAL_STRING(name, p+1, 1); } else { *name = *ns; zval_copy_ctor(name); warn = !is_global && !CG(current_namespace); } } lcname = zend_str_tolower_dup(Z_STRVAL_P(name), Z_STRLEN_P(name)); if (((Z_STRLEN_P(name) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN_P(name) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because '%s' is a special class name", Z_STRVAL_P(ns), Z_STRVAL_P(name), Z_STRVAL_P(name)); } if (CG(current_namespace)) { /* Prefix import name with current namespace name to avoid conflicts with classes */ char *c_ns_name = emalloc(Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) + 1); zend_str_tolower_copy(c_ns_name, Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); c_ns_name[Z_STRLEN_P(CG(current_namespace))] = '\\'; memcpy(c_ns_name+Z_STRLEN_P(CG(current_namespace))+1, lcname, Z_STRLEN_P(name)+1); if (zend_hash_exists(CG(class_table), c_ns_name, Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name)+1)) { char *tmp2 = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) || memcmp(tmp2, c_ns_name, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(tmp2); } efree(c_ns_name); } else if (zend_hash_find(CG(class_table), lcname, Z_STRLEN_P(name)+1, (void**)&pce) == SUCCESS && (*pce)->type == ZEND_USER_CLASS && (*pce)->info.user.filename == CG(compiled_filename)) { char *c_tmp = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(name) || memcmp(c_tmp, lcname, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(c_tmp); } if (zend_hash_add(CG(current_import), lcname, Z_STRLEN_P(name)+1, &ns, sizeof(zval*), NULL) != SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } if (warn) { if (!strcmp(Z_STRVAL_P(name), "strict")) { zend_error(E_COMPILE_ERROR, "You seem to be trying to use a different language..."); } zend_error(E_WARNING, "The use statement with non-compound name '%s' has no effect", Z_STRVAL_P(name)); } efree(lcname); zval_dtor(name); } /* }}} */ void zend_do_declare_constant(znode *name, znode *value TSRMLS_DC) /* {{{ */ { zend_op *opline; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed as constants"); } if (zend_get_ct_const(&name->u.constant, 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare constant '%s'", Z_STRVAL(name->u.constant)); } if (CG(current_namespace)) { /* Prefix constant name with name of current namespace, lowercased */ znode tmp; tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); Z_STRVAL(tmp.u.constant) = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), Z_STRLEN(tmp.u.constant)); zend_do_build_namespace_name(&tmp, &tmp, name TSRMLS_CC); *name = tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DECLARE_CONST; SET_UNUSED(opline->result); SET_NODE(opline->op1, name); SET_NODE(opline->op2, value); } /* }}} */ void zend_verify_namespace(TSRMLS_D) /* {{{ */ { if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "No code may exist outside of namespace {}"); } } /* }}} */ void zend_do_end_namespace(TSRMLS_D) /* {{{ */ { CG(in_namespace) = 0; if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_end_compilation(TSRMLS_D) /* {{{ */ { CG(has_bracketed_namespaces) = 0; zend_do_end_namespace(TSRMLS_C); } /* }}} */ /* {{{ zend_dirname Returns directory name component of path */ ZEND_API size_t zend_dirname(char *path, size_t len) { register char *end = path + len - 1; unsigned int len_adjust = 0; #ifdef PHP_WIN32 /* Note that on Win32 CWD is per drive (heritage from CP/M). * This means dirname("c:foo") maps to "c:." or "c:" - which means CWD on C: drive. */ if ((2 <= len) && isalpha((int)((unsigned char *)path)[0]) && (':' == path[1])) { /* Skip over the drive spec (if any) so as not to change */ path += 2; len_adjust += 2; if (2 == len) { /* Return "c:" on Win32 for dirname("c:"). * It would be more consistent to return "c:." * but that would require making the string *longer*. */ return len; } } #elif defined(NETWARE) /* * Find the first occurence of : from the left * move the path pointer to the position just after : * increment the len_adjust to the length of path till colon character(inclusive) * If there is no character beyond : simple return len */ char *colonpos = NULL; colonpos = strchr(path, ':'); if (colonpos != NULL) { len_adjust = ((colonpos - path) + 1); path += len_adjust; if (len_adjust == len) { return len; } } #endif if (len == 0) { /* Illegal use of this function */ return 0; } /* Strip trailing slashes */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { /* The path only contained slashes */ path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } /* Strip filename */ while (end >= path && !IS_SLASH_P(end)) { end--; } if (end < path) { /* No slash found, therefore return '.' */ #ifdef NETWARE if (len_adjust == 0) { path[0] = '.'; path[1] = '\0'; return 1; /* only one character */ } else { path[0] = '\0'; return len_adjust; } #else path[0] = '.'; path[1] = '\0'; return 1 + len_adjust; #endif } /* Strip slashes which came before the file name */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } *(end+1) = '\0'; return (size_t)(end + 1 - path) + len_adjust; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-11-01-ceac9dc490-9b0d73af1d.c
manybugs_data_58
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "zend.h" #include "zend_API.h" #include "zend_builtin_functions.h" #include "zend_constants.h" #include "zend_ini.h" #include "zend_exceptions.h" #include "zend_extensions.h" #include "zend_closures.h" #undef ZEND_TEST_EXCEPTIONS static ZEND_FUNCTION(zend_version); static ZEND_FUNCTION(func_num_args); static ZEND_FUNCTION(func_get_arg); static ZEND_FUNCTION(func_get_args); static ZEND_FUNCTION(strlen); static ZEND_FUNCTION(strcmp); static ZEND_FUNCTION(strncmp); static ZEND_FUNCTION(strcasecmp); static ZEND_FUNCTION(strncasecmp); static ZEND_FUNCTION(each); static ZEND_FUNCTION(error_reporting); static ZEND_FUNCTION(define); static ZEND_FUNCTION(defined); static ZEND_FUNCTION(get_class); static ZEND_FUNCTION(get_called_class); static ZEND_FUNCTION(get_parent_class); static ZEND_FUNCTION(method_exists); static ZEND_FUNCTION(property_exists); static ZEND_FUNCTION(class_exists); static ZEND_FUNCTION(interface_exists); static ZEND_FUNCTION(trait_exists); static ZEND_FUNCTION(function_exists); static ZEND_FUNCTION(class_alias); #if ZEND_DEBUG static ZEND_FUNCTION(leak); static ZEND_FUNCTION(leak_variable); #ifdef ZEND_TEST_EXCEPTIONS static ZEND_FUNCTION(crash); #endif #endif static ZEND_FUNCTION(get_included_files); static ZEND_FUNCTION(is_subclass_of); static ZEND_FUNCTION(is_a); static ZEND_FUNCTION(get_class_vars); static ZEND_FUNCTION(get_object_vars); static ZEND_FUNCTION(get_class_methods); static ZEND_FUNCTION(trigger_error); static ZEND_FUNCTION(set_error_handler); static ZEND_FUNCTION(restore_error_handler); static ZEND_FUNCTION(set_exception_handler); static ZEND_FUNCTION(restore_exception_handler); static ZEND_FUNCTION(get_declared_classes); static ZEND_FUNCTION(get_declared_traits); static ZEND_FUNCTION(get_declared_interfaces); static ZEND_FUNCTION(get_defined_functions); static ZEND_FUNCTION(get_defined_vars); static ZEND_FUNCTION(create_function); static ZEND_FUNCTION(get_resource_type); static ZEND_FUNCTION(get_loaded_extensions); static ZEND_FUNCTION(extension_loaded); static ZEND_FUNCTION(get_extension_funcs); static ZEND_FUNCTION(get_defined_constants); static ZEND_FUNCTION(debug_backtrace); static ZEND_FUNCTION(debug_print_backtrace); #if ZEND_DEBUG static ZEND_FUNCTION(zend_test_func); #ifdef ZTS static ZEND_FUNCTION(zend_thread_id); #endif #endif static ZEND_FUNCTION(gc_collect_cycles); static ZEND_FUNCTION(gc_enabled); static ZEND_FUNCTION(gc_enable); static ZEND_FUNCTION(gc_disable); /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO(arginfo_zend__void, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_func_get_arg, 0, 0, 1) ZEND_ARG_INFO(0, arg_num) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strlen, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strcmp, 0, 0, 2) ZEND_ARG_INFO(0, str1) ZEND_ARG_INFO(0, str2) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strncmp, 0, 0, 3) ZEND_ARG_INFO(0, str1) ZEND_ARG_INFO(0, str2) ZEND_ARG_INFO(0, len) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_each, 0, 0, 1) ZEND_ARG_INFO(1, arr) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_error_reporting, 0, 0, 0) ZEND_ARG_INFO(0, new_error_level) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_define, 0, 0, 3) ZEND_ARG_INFO(0, constant_name) ZEND_ARG_INFO(0, value) ZEND_ARG_INFO(0, case_insensitive) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_defined, 0, 0, 1) ZEND_ARG_INFO(0, constant_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_get_class, 0, 0, 0) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_is_subclass_of, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, class_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_get_class_vars, 0, 0, 1) ZEND_ARG_INFO(0, class_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_get_object_vars, 0, 0, 1) ZEND_ARG_INFO(0, obj) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_get_class_methods, 0, 0, 1) ZEND_ARG_INFO(0, class) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_method_exists, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, method) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_property_exists, 0, 0, 2) ZEND_ARG_INFO(0, object_or_class) ZEND_ARG_INFO(0, property_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_class_exists, 0, 0, 1) ZEND_ARG_INFO(0, classname) ZEND_ARG_INFO(0, autoload) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_trait_exists, 0, 0, 1) ZEND_ARG_INFO(0, traitname) ZEND_ARG_INFO(0, autoload) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_function_exists, 0, 0, 1) ZEND_ARG_INFO(0, function_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_class_alias, 0, 0, 2) ZEND_ARG_INFO(0, user_class_name) ZEND_ARG_INFO(0, alias_name) ZEND_ARG_INFO(0, autoload) ZEND_END_ARG_INFO() #if ZEND_DEBUG ZEND_BEGIN_ARG_INFO_EX(arginfo_leak_variable, 0, 0, 1) ZEND_ARG_INFO(0, variable) ZEND_ARG_INFO(0, leak_data) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_trigger_error, 0, 0, 1) ZEND_ARG_INFO(0, message) ZEND_ARG_INFO(0, error_type) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_set_error_handler, 0, 0, 1) ZEND_ARG_INFO(0, error_handler) ZEND_ARG_INFO(0, error_types) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_set_exception_handler, 0, 0, 1) ZEND_ARG_INFO(0, exception_handler) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_create_function, 0, 0, 2) ZEND_ARG_INFO(0, args) ZEND_ARG_INFO(0, code) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_get_resource_type, 0, 0, 1) ZEND_ARG_INFO(0, res) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_get_loaded_extensions, 0, 0, 0) ZEND_ARG_INFO(0, zend_extensions) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_get_defined_constants, 0, 0, 0) ZEND_ARG_INFO(0, categorize) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_debug_backtrace, 0, 0, 0) ZEND_ARG_INFO(0, options) ZEND_ARG_INFO(0, limit) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_debug_print_backtrace, 0, 0, 0) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_extension_loaded, 0, 0, 1) ZEND_ARG_INFO(0, extension_name) ZEND_END_ARG_INFO() /* }}} */ static const zend_function_entry builtin_functions[] = { /* {{{ */ ZEND_FE(zend_version, arginfo_zend__void) ZEND_FE(func_num_args, arginfo_zend__void) ZEND_FE(func_get_arg, arginfo_func_get_arg) ZEND_FE(func_get_args, arginfo_zend__void) ZEND_FE(strlen, arginfo_strlen) ZEND_FE(strcmp, arginfo_strcmp) ZEND_FE(strncmp, arginfo_strncmp) ZEND_FE(strcasecmp, arginfo_strcmp) ZEND_FE(strncasecmp, arginfo_strncmp) ZEND_FE(each, arginfo_each) ZEND_FE(error_reporting, arginfo_error_reporting) ZEND_FE(define, arginfo_define) ZEND_FE(defined, arginfo_defined) ZEND_FE(get_class, arginfo_get_class) ZEND_FE(get_called_class, arginfo_zend__void) ZEND_FE(get_parent_class, arginfo_get_class) ZEND_FE(method_exists, arginfo_method_exists) ZEND_FE(property_exists, arginfo_property_exists) ZEND_FE(class_exists, arginfo_class_exists) ZEND_FE(interface_exists, arginfo_class_exists) ZEND_FE(trait_exists, arginfo_trait_exists) ZEND_FE(function_exists, arginfo_function_exists) ZEND_FE(class_alias, arginfo_class_alias) #if ZEND_DEBUG ZEND_FE(leak, NULL) ZEND_FE(leak_variable, arginfo_leak_variable) #ifdef ZEND_TEST_EXCEPTIONS ZEND_FE(crash, NULL) #endif #endif ZEND_FE(get_included_files, arginfo_zend__void) ZEND_FALIAS(get_required_files, get_included_files, arginfo_zend__void) ZEND_FE(is_subclass_of, arginfo_is_subclass_of) ZEND_FE(is_a, arginfo_is_subclass_of) ZEND_FE(get_class_vars, arginfo_get_class_vars) ZEND_FE(get_object_vars, arginfo_get_object_vars) ZEND_FE(get_class_methods, arginfo_get_class_methods) ZEND_FE(trigger_error, arginfo_trigger_error) ZEND_FALIAS(user_error, trigger_error, arginfo_trigger_error) ZEND_FE(set_error_handler, arginfo_set_error_handler) ZEND_FE(restore_error_handler, arginfo_zend__void) ZEND_FE(set_exception_handler, arginfo_set_exception_handler) ZEND_FE(restore_exception_handler, arginfo_zend__void) ZEND_FE(get_declared_classes, arginfo_zend__void) ZEND_FE(get_declared_traits, arginfo_zend__void) ZEND_FE(get_declared_interfaces, arginfo_zend__void) ZEND_FE(get_defined_functions, arginfo_zend__void) ZEND_FE(get_defined_vars, arginfo_zend__void) ZEND_FE(create_function, arginfo_create_function) ZEND_FE(get_resource_type, arginfo_get_resource_type) ZEND_FE(get_loaded_extensions, arginfo_get_loaded_extensions) ZEND_FE(extension_loaded, arginfo_extension_loaded) ZEND_FE(get_extension_funcs, arginfo_extension_loaded) ZEND_FE(get_defined_constants, arginfo_get_defined_constants) ZEND_FE(debug_backtrace, arginfo_debug_backtrace) ZEND_FE(debug_print_backtrace, arginfo_debug_print_backtrace) #if ZEND_DEBUG ZEND_FE(zend_test_func, NULL) #ifdef ZTS ZEND_FE(zend_thread_id, NULL) #endif #endif ZEND_FE(gc_collect_cycles, arginfo_zend__void) ZEND_FE(gc_enabled, arginfo_zend__void) ZEND_FE(gc_enable, arginfo_zend__void) ZEND_FE(gc_disable, arginfo_zend__void) ZEND_FE_END }; /* }}} */ ZEND_MINIT_FUNCTION(core) { /* {{{ */ zend_class_entry class_entry; INIT_CLASS_ENTRY(class_entry, "stdClass", NULL); zend_standard_class_def = zend_register_internal_class(&class_entry TSRMLS_CC); zend_register_default_classes(TSRMLS_C); return SUCCESS; } /* }}} */ zend_module_entry zend_builtin_module = { /* {{{ */ STANDARD_MODULE_HEADER, "Core", builtin_functions, ZEND_MINIT(core), NULL, NULL, NULL, NULL, ZEND_VERSION, STANDARD_MODULE_PROPERTIES }; /* }}} */ int zend_startup_builtin_functions(TSRMLS_D) /* {{{ */ { zend_builtin_module.module_number = 0; zend_builtin_module.type = MODULE_PERSISTENT; return (EG(current_module) = zend_register_module_ex(&zend_builtin_module TSRMLS_CC)) == NULL ? FAILURE : SUCCESS; } /* }}} */ /* {{{ proto string zend_version(void) Get the version of the Zend Engine */ ZEND_FUNCTION(zend_version) { RETURN_STRINGL(ZEND_VERSION, sizeof(ZEND_VERSION)-1, 1); } /* }}} */ /* {{{ proto int gc_collect_cycles(void) Forces collection of any existing garbage cycles. Returns number of freed zvals */ ZEND_FUNCTION(gc_collect_cycles) { RETURN_LONG(gc_collect_cycles(TSRMLS_C)); } /* }}} */ /* {{{ proto void gc_enabled(void) Returns status of the circular reference collector */ ZEND_FUNCTION(gc_enabled) { RETURN_BOOL(GC_G(gc_enabled)); } /* }}} */ /* {{{ proto void gc_enable(void) Activates the circular reference collector */ ZEND_FUNCTION(gc_enable) { zend_alter_ini_entry("zend.enable_gc", sizeof("zend.enable_gc"), "1", sizeof("1")-1, ZEND_INI_USER, ZEND_INI_STAGE_RUNTIME); } /* }}} */ /* {{{ proto void gc_disable(void) Deactivates the circular reference collector */ ZEND_FUNCTION(gc_disable) { zend_alter_ini_entry("zend.enable_gc", sizeof("zend.enable_gc"), "0", sizeof("0")-1, ZEND_INI_USER, ZEND_INI_STAGE_RUNTIME); } /* }}} */ /* {{{ proto int func_num_args(void) Get the number of arguments that were passed to the function */ ZEND_FUNCTION(func_num_args) { zend_execute_data *ex = EG(current_execute_data)->prev_execute_data; if (ex && ex->function_state.arguments) { RETURN_LONG((long)(zend_uintptr_t)*(ex->function_state.arguments)); } else { zend_error(E_WARNING, "func_num_args(): Called from the global scope - no function context"); RETURN_LONG(-1); } } /* }}} */ /* {{{ proto mixed func_get_arg(int arg_num) Get the $arg_num'th argument that was passed to the function */ ZEND_FUNCTION(func_get_arg) { void **p; int arg_count; zval *arg; long requested_offset; zend_execute_data *ex = EG(current_execute_data)->prev_execute_data; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &requested_offset) == FAILURE) { return; } if (requested_offset < 0) { zend_error(E_WARNING, "func_get_arg(): The argument number should be >= 0"); RETURN_FALSE; } if (!ex || !ex->function_state.arguments) { zend_error(E_WARNING, "func_get_arg(): Called from the global scope - no function context"); RETURN_FALSE; } p = ex->function_state.arguments; arg_count = (int)(zend_uintptr_t) *p; /* this is the amount of arguments passed to func_get_arg(); */ if (requested_offset >= arg_count) { zend_error(E_WARNING, "func_get_arg(): Argument %ld not passed to function", requested_offset); RETURN_FALSE; } arg = *(p-(arg_count-requested_offset)); *return_value = *arg; zval_copy_ctor(return_value); INIT_PZVAL(return_value); } /* }}} */ /* {{{ proto array func_get_args() Get an array of the arguments that were passed to the function */ ZEND_FUNCTION(func_get_args) { void **p; int arg_count; int i; zend_execute_data *ex = EG(current_execute_data)->prev_execute_data; if (!ex || !ex->function_state.arguments) { zend_error(E_WARNING, "func_get_args(): Called from the global scope - no function context"); RETURN_FALSE; } p = ex->function_state.arguments; arg_count = (int)(zend_uintptr_t) *p; /* this is the amount of arguments passed to func_get_args(); */ array_init_size(return_value, arg_count); for (i=0; i<arg_count; i++) { zval *element; ALLOC_ZVAL(element); *element = **((zval **) (p-(arg_count-i))); zval_copy_ctor(element); INIT_PZVAL(element); zend_hash_next_index_insert(return_value->value.ht, &element, sizeof(zval *), NULL); } } /* }}} */ /* {{{ proto int strlen(string str) Get string length */ ZEND_FUNCTION(strlen) { char *s1; int s1_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &s1, &s1_len) == FAILURE) { return; } RETVAL_LONG(s1_len); } /* }}} */ /* {{{ proto int strcmp(string str1, string str2) Binary safe string comparison */ ZEND_FUNCTION(strcmp) { char *s1, *s2; int s1_len, s2_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &s1, &s1_len, &s2, &s2_len) == FAILURE) { return; } RETURN_LONG(zend_binary_strcmp(s1, s1_len, s2, s2_len)); } /* }}} */ /* {{{ proto int strncmp(string str1, string str2, int len) Binary safe string comparison */ ZEND_FUNCTION(strncmp) { char *s1, *s2; int s1_len, s2_len; long len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ssl", &s1, &s1_len, &s2, &s2_len, &len) == FAILURE) { return; } if (len < 0) { zend_error(E_WARNING, "Length must be greater than or equal to 0"); RETURN_FALSE; } RETURN_LONG(zend_binary_strncmp(s1, s1_len, s2, s2_len, len)); } /* }}} */ /* {{{ proto int strcasecmp(string str1, string str2) Binary safe case-insensitive string comparison */ ZEND_FUNCTION(strcasecmp) { char *s1, *s2; int s1_len, s2_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &s1, &s1_len, &s2, &s2_len) == FAILURE) { return; } RETURN_LONG(zend_binary_strcasecmp(s1, s1_len, s2, s2_len)); } /* }}} */ /* {{{ proto int strncasecmp(string str1, string str2, int len) Binary safe string comparison */ ZEND_FUNCTION(strncasecmp) { char *s1, *s2; int s1_len, s2_len; long len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ssl", &s1, &s1_len, &s2, &s2_len, &len) == FAILURE) { return; } if (len < 0) { zend_error(E_WARNING, "Length must be greater than or equal to 0"); RETURN_FALSE; } RETURN_LONG(zend_binary_strncasecmp(s1, s1_len, s2, s2_len, len)); } /* }}} */ /* {{{ proto array each(array arr) Return the currently pointed key..value pair in the passed array, and advance the pointer to the next element */ ZEND_FUNCTION(each) { zval *array, *entry, **entry_ptr, *tmp; char *string_key; uint string_key_len; ulong num_key; zval **inserted_pointer; HashTable *target_hash; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &array) == FAILURE) { return; } target_hash = HASH_OF(array); if (!target_hash) { zend_error(E_WARNING,"Variable passed to each() is not an array or object"); return; } if (zend_hash_get_current_data(target_hash, (void **) &entry_ptr)==FAILURE) { RETURN_FALSE; } array_init(return_value); entry = *entry_ptr; /* add value elements */ if (Z_ISREF_P(entry)) { ALLOC_ZVAL(tmp); *tmp = *entry; zval_copy_ctor(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); entry=tmp; } zend_hash_index_update(return_value->value.ht, 1, &entry, sizeof(zval *), NULL); Z_ADDREF_P(entry); zend_hash_update(return_value->value.ht, "value", sizeof("value"), &entry, sizeof(zval *), NULL); Z_ADDREF_P(entry); /* add the key elements */ switch (zend_hash_get_current_key_ex(target_hash, &string_key, &string_key_len, &num_key, 1, NULL)) { case HASH_KEY_IS_STRING: add_get_index_stringl(return_value, 0, string_key, string_key_len-1, (void **) &inserted_pointer, 0); break; case HASH_KEY_IS_LONG: add_get_index_long(return_value, 0, num_key, (void **) &inserted_pointer); break; } zend_hash_update(return_value->value.ht, "key", sizeof("key"), inserted_pointer, sizeof(zval *), NULL); Z_ADDREF_PP(inserted_pointer); zend_hash_move_forward(target_hash); } /* }}} */ /* {{{ proto int error_reporting([int new_error_level]) Return the current error_reporting level, and if an argument was passed - change to the new level */ ZEND_FUNCTION(error_reporting) { char *err; int err_len; int old_error_reporting; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &err, &err_len) == FAILURE) { return; } old_error_reporting = EG(error_reporting); if(ZEND_NUM_ARGS() != 0) { zend_alter_ini_entry("error_reporting", sizeof("error_reporting"), err, err_len, ZEND_INI_USER, ZEND_INI_STAGE_RUNTIME); } RETVAL_LONG(old_error_reporting); } /* }}} */ /* {{{ proto bool define(string constant_name, mixed value, boolean case_insensitive=false) Define a new constant */ ZEND_FUNCTION(define) { char *name; int name_len; zval *val; zval *val_free = NULL; zend_bool non_cs = 0; int case_sensitive = CONST_CS; zend_constant c; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz|b", &name, &name_len, &val, &non_cs) == FAILURE) { return; } if(non_cs) { case_sensitive = 0; } /* class constant, check if there is name and make sure class is valid & exists */ if (zend_memnstr(name, "::", sizeof("::") - 1, name + name_len)) { zend_error(E_WARNING, "Class constants cannot be defined or redefined"); RETURN_FALSE; } repeat: switch (Z_TYPE_P(val)) { case IS_LONG: case IS_DOUBLE: case IS_STRING: case IS_BOOL: case IS_RESOURCE: case IS_NULL: break; case IS_OBJECT: if (!val_free) { if (Z_OBJ_HT_P(val)->get) { val_free = val = Z_OBJ_HT_P(val)->get(val TSRMLS_CC); goto repeat; } else if (Z_OBJ_HT_P(val)->cast_object) { ALLOC_INIT_ZVAL(val_free); if (Z_OBJ_HT_P(val)->cast_object(val, val_free, IS_STRING TSRMLS_CC) == SUCCESS) { val = val_free; break; } } } /* no break */ default: zend_error(E_WARNING,"Constants may only evaluate to scalar values"); if (val_free) { zval_ptr_dtor(&val_free); } RETURN_FALSE; } c.value = *val; zval_copy_ctor(&c.value); if (val_free) { zval_ptr_dtor(&val_free); } c.flags = case_sensitive; /* non persistent */ c.name = IS_INTERNED(name) ? name : zend_strndup(name, name_len); c.name_len = name_len+1; c.module_number = PHP_USER_CONSTANT; if (zend_register_constant(&c TSRMLS_CC) == SUCCESS) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool defined(string constant_name) Check whether a constant exists */ ZEND_FUNCTION(defined) { char *name; int name_len; zval c; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) { return; } if (zend_get_constant_ex(name, name_len, &c, NULL, ZEND_FETCH_CLASS_SILENT TSRMLS_CC)) { zval_dtor(&c); RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto string get_class([object object]) Retrieves the class name */ ZEND_FUNCTION(get_class) { zval *obj = NULL; const char *name = ""; zend_uint name_len = 0; int dup; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|o!", &obj) == FAILURE) { RETURN_FALSE; } if (!obj) { if (EG(scope)) { RETURN_STRINGL(EG(scope)->name, EG(scope)->name_length, 1); } else { zend_error(E_WARNING, "get_class() called without object from outside a class"); RETURN_FALSE; } } dup = zend_get_object_classname(obj, &name, &name_len TSRMLS_CC); RETURN_STRINGL(name, name_len, dup); } /* }}} */ /* {{{ proto string get_called_class() Retrieves the "Late Static Binding" class name */ ZEND_FUNCTION(get_called_class) { if (zend_parse_parameters_none() == FAILURE) { return; } if (EG(called_scope)) { RETURN_STRINGL(EG(called_scope)->name, EG(called_scope)->name_length, 1); } else if (!EG(scope)) { zend_error(E_WARNING, "get_called_class() called from outside a class"); } RETURN_FALSE; } /* }}} */ /* {{{ proto string get_parent_class([mixed object]) Retrieves the parent class name for object or class or current scope. */ ZEND_FUNCTION(get_parent_class) { zval *arg; zend_class_entry *ce = NULL; const char *name; zend_uint name_length; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &arg) == FAILURE) { return; } if (!ZEND_NUM_ARGS()) { ce = EG(scope); if (ce && ce->parent) { RETURN_STRINGL(ce->parent->name, ce->parent->name_length, 1); } else { RETURN_FALSE; } } if (Z_TYPE_P(arg) == IS_OBJECT) { if (Z_OBJ_HT_P(arg)->get_class_name && Z_OBJ_HT_P(arg)->get_class_name(arg, &name, &name_length, 1 TSRMLS_CC) == SUCCESS) { RETURN_STRINGL(name, name_length, 0); } else { ce = zend_get_class_entry(arg TSRMLS_CC); } } else if (Z_TYPE_P(arg) == IS_STRING) { zend_class_entry **pce; if (zend_lookup_class(Z_STRVAL_P(arg), Z_STRLEN_P(arg), &pce TSRMLS_CC) == SUCCESS) { ce = *pce; } } if (ce && ce->parent) { RETURN_STRINGL(ce->parent->name, ce->parent->name_length, 1); } else { RETURN_FALSE; } } /* }}} */ static void is_a_impl(INTERNAL_FUNCTION_PARAMETERS, zend_bool only_subclass) { zval *obj; char *class_name; int class_name_len; zend_class_entry *instance_ce; zend_class_entry **ce; zend_bool retval; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zs", &obj, &class_name, &class_name_len) == FAILURE) { return; } if (Z_TYPE_P(obj) == IS_STRING) { zend_class_entry **the_ce; if (zend_lookup_class(Z_STRVAL_P(obj), Z_STRLEN_P(obj), &the_ce TSRMLS_CC) == FAILURE) { RETURN_FALSE; } instance_ce = *the_ce; } else if (Z_TYPE_P(obj) == IS_OBJECT && HAS_CLASS_ENTRY(*obj)) { instance_ce = Z_OBJCE_P(obj); } else { RETURN_FALSE; } if (zend_lookup_class_ex(class_name, class_name_len, NULL, 0, &ce TSRMLS_CC) == FAILURE) { retval = 0; } else { if (only_subclass && instance_ce == *ce) { retval = 0; } else { retval = instanceof_function(instance_ce, *ce TSRMLS_CC); } } RETURN_BOOL(retval); } /* {{{ proto bool is_subclass_of(mixed object, string class_name) Returns true if the object has this class as one of its parents */ ZEND_FUNCTION(is_subclass_of) { is_a_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto bool is_a(mixed object, string class_name) Returns true if the object is of this class or has this class as one of its parents */ ZEND_FUNCTION(is_a) { is_a_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ add_class_vars */ static void add_class_vars(zend_class_entry *ce, int statics, zval *return_value TSRMLS_DC) { HashPosition pos; zend_property_info *prop_info; zval *prop, *prop_copy; char *key; uint key_len; ulong num_index; zend_hash_internal_pointer_reset_ex(&ce->properties_info, &pos); while (zend_hash_get_current_data_ex(&ce->properties_info, (void **) &prop_info, &pos) == SUCCESS) { zend_hash_get_current_key_ex(&ce->properties_info, &key, &key_len, &num_index, 0, &pos); zend_hash_move_forward_ex(&ce->properties_info, &pos); if (((prop_info->flags & ZEND_ACC_SHADOW) && prop_info->ce != EG(scope)) || ((prop_info->flags & ZEND_ACC_PROTECTED) && !zend_check_protected(prop_info->ce, EG(scope))) || ((prop_info->flags & ZEND_ACC_PRIVATE) && ce != EG(scope) && prop_info->ce != EG(scope))) { continue; } prop = NULL; if (prop_info->offset >= 0) { if (statics && (prop_info->flags & ZEND_ACC_STATIC) != 0) { prop = ce->default_static_members_table[prop_info->offset]; } else if (!statics && (prop_info->flags & ZEND_ACC_STATIC) == 0) { prop = ce->default_properties_table[prop_info->offset]; } } if (!prop) { continue; } /* copy: enforce read only access */ ALLOC_ZVAL(prop_copy); *prop_copy = *prop; zval_copy_ctor(prop_copy); INIT_PZVAL(prop_copy); /* this is necessary to make it able to work with default array * properties, returned to user */ if (Z_TYPE_P(prop_copy) == IS_CONSTANT_ARRAY || (Z_TYPE_P(prop_copy) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zval_update_constant(&prop_copy, 0 TSRMLS_CC); } add_assoc_zval(return_value, key, prop_copy); } } /* }}} */ /* {{{ proto array get_class_vars(string class_name) Returns an array of default properties of the class. */ ZEND_FUNCTION(get_class_vars) { char *class_name; int class_name_len; zend_class_entry **pce; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &class_name, &class_name_len) == FAILURE) { return; } if (zend_lookup_class(class_name, class_name_len, &pce TSRMLS_CC) == FAILURE) { RETURN_FALSE; } else { array_init(return_value); zend_update_class_constants(*pce TSRMLS_CC); add_class_vars(*pce, 0, return_value TSRMLS_CC); add_class_vars(*pce, 1, return_value TSRMLS_CC); } } /* }}} */ /* {{{ proto array get_object_vars(object obj) Returns an array of object properties */ ZEND_FUNCTION(get_object_vars) { zval *obj; zval **value; HashTable *properties; HashPosition pos; char *key; const char *prop_name, *class_name; uint key_len; ulong num_index; zend_object *zobj; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "o", &obj) == FAILURE) { return; } if (Z_OBJ_HT_P(obj)->get_properties == NULL) { RETURN_FALSE; } properties = Z_OBJ_HT_P(obj)->get_properties(obj TSRMLS_CC); if (properties == NULL) { RETURN_FALSE; } zobj = zend_objects_get_address(obj TSRMLS_CC); array_init(return_value); zend_hash_internal_pointer_reset_ex(properties, &pos); while (zend_hash_get_current_data_ex(properties, (void **) &value, &pos) == SUCCESS) { if (zend_hash_get_current_key_ex(properties, &key, &key_len, &num_index, 0, &pos) == HASH_KEY_IS_STRING) { if (zend_check_property_access(zobj, key, key_len-1 TSRMLS_CC) == SUCCESS) { zend_unmangle_property_name(key, key_len-1, &class_name, &prop_name); /* Not separating references */ Z_ADDREF_PP(value); add_assoc_zval_ex(return_value, prop_name, strlen(prop_name)+1, *value); } } zend_hash_move_forward_ex(properties, &pos); } } /* }}} */ /* {{{ proto array get_class_methods(mixed class) Returns an array of method names for class or class instance. */ ZEND_FUNCTION(get_class_methods) { zval *klass; zval *method_name; zend_class_entry *ce = NULL, **pce; HashPosition pos; zend_function *mptr; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &klass) == FAILURE) { return; } if (Z_TYPE_P(klass) == IS_OBJECT) { /* TBI!! new object handlers */ if (!HAS_CLASS_ENTRY(*klass)) { RETURN_FALSE; } ce = Z_OBJCE_P(klass); } else if (Z_TYPE_P(klass) == IS_STRING) { if (zend_lookup_class(Z_STRVAL_P(klass), Z_STRLEN_P(klass), &pce TSRMLS_CC) == SUCCESS) { ce = *pce; } } if (!ce) { RETURN_NULL(); } array_init(return_value); zend_hash_internal_pointer_reset_ex(&ce->function_table, &pos); while (zend_hash_get_current_data_ex(&ce->function_table, (void **) &mptr, &pos) == SUCCESS) { if ((mptr->common.fn_flags & ZEND_ACC_PUBLIC) || (EG(scope) && (((mptr->common.fn_flags & ZEND_ACC_PROTECTED) && zend_check_protected(mptr->common.scope, EG(scope))) || ((mptr->common.fn_flags & ZEND_ACC_PRIVATE) && EG(scope) == mptr->common.scope)))) { char *key; uint key_len; ulong num_index; uint len = strlen(mptr->common.function_name); /* Do not display old-style inherited constructors */ if ((mptr->common.fn_flags & ZEND_ACC_CTOR) == 0 || mptr->common.scope == ce || zend_hash_get_current_key_ex(&ce->function_table, &key, &key_len, &num_index, 0, &pos) != HASH_KEY_IS_STRING || zend_binary_strcasecmp(key, key_len-1, mptr->common.function_name, len) == 0) { MAKE_STD_ZVAL(method_name); ZVAL_STRINGL(method_name, mptr->common.function_name, len, 1); zend_hash_next_index_insert(return_value->value.ht, &method_name, sizeof(zval *), NULL); } } zend_hash_move_forward_ex(&ce->function_table, &pos); } } /* }}} */ /* {{{ proto bool method_exists(object object, string method) Checks if the class method exists */ ZEND_FUNCTION(method_exists) { zval *klass; char *method_name; int method_len; char *lcname; zend_class_entry * ce, **pce; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zs", &klass, &method_name, &method_len) == FAILURE) { return; } if (Z_TYPE_P(klass) == IS_OBJECT) { ce = Z_OBJCE_P(klass); } else if (Z_TYPE_P(klass) == IS_STRING) { if (zend_lookup_class(Z_STRVAL_P(klass), Z_STRLEN_P(klass), &pce TSRMLS_CC) == FAILURE) { RETURN_FALSE; } ce = *pce; } else { RETURN_FALSE; } lcname = zend_str_tolower_dup(method_name, method_len); if (zend_hash_exists(&ce->function_table, lcname, method_len+1)) { efree(lcname); RETURN_TRUE; } else { union _zend_function *func = NULL; if (Z_TYPE_P(klass) == IS_OBJECT && Z_OBJ_HT_P(klass)->get_method != NULL && (func = Z_OBJ_HT_P(klass)->get_method(&klass, method_name, method_len, NULL TSRMLS_CC)) != NULL ) { if (func->type == ZEND_INTERNAL_FUNCTION && (func->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) != 0 ) { /* Returns true to the fake Closure's __invoke */ RETVAL_BOOL((func->common.scope == zend_ce_closure && (method_len == sizeof(ZEND_INVOKE_FUNC_NAME)-1) && memcmp(lcname, ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME)-1) == 0) ? 1 : 0); efree(lcname); efree((char*)((zend_internal_function*)func)->function_name); efree(func); return; } efree(lcname); RETURN_TRUE; } } efree(lcname); RETURN_FALSE; } /* }}} */ /* {{{ proto bool property_exists(mixed object_or_class, string property_name) Checks if the object or class has a property */ ZEND_FUNCTION(property_exists) { zval *object; char *property; int property_len; zend_class_entry *ce, **pce; zend_property_info *property_info; zval property_z; ulong h; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zs", &object, &property, &property_len) == FAILURE) { return; } if (property_len == 0) { RETURN_FALSE; } if (Z_TYPE_P(object) == IS_STRING) { if (zend_lookup_class(Z_STRVAL_P(object), Z_STRLEN_P(object), &pce TSRMLS_CC) == FAILURE) { RETURN_FALSE; } ce = *pce; } else if (Z_TYPE_P(object) == IS_OBJECT) { ce = Z_OBJCE_P(object); } else { zend_error(E_WARNING, "First parameter must either be an object or the name of an existing class"); RETURN_NULL(); } h = zend_get_hash_value(property, property_len+1); if (zend_hash_quick_find(&ce->properties_info, property, property_len+1, h, (void **) &property_info) == SUCCESS && (property_info->flags & ZEND_ACC_SHADOW) == 0) { RETURN_TRUE; } ZVAL_STRINGL(&property_z, property, property_len, 0); if (Z_TYPE_P(object) == IS_OBJECT && Z_OBJ_HANDLER_P(object, has_property) && Z_OBJ_HANDLER_P(object, has_property)(object, &property_z, 2, 0 TSRMLS_CC)) { RETURN_TRUE; } RETURN_FALSE; } /* }}} */ /* {{{ proto bool class_exists(string classname [, bool autoload]) Checks if the class exists */ ZEND_FUNCTION(class_exists) { char *class_name, *lc_name; zend_class_entry **ce; int class_name_len; int found; zend_bool autoload = 1; ALLOCA_FLAG(use_heap) if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|b", &class_name, &class_name_len, &autoload) == FAILURE) { return; } if (!autoload) { char *name; int len; lc_name = do_alloca(class_name_len + 1, use_heap); zend_str_tolower_copy(lc_name, class_name, class_name_len); /* Ignore leading "\" */ name = lc_name; len = class_name_len; if (lc_name[0] == '\\') { name = &lc_name[1]; len--; } found = zend_hash_find(EG(class_table), name, len+1, (void **) &ce); free_alloca(lc_name, use_heap); RETURN_BOOL(found == SUCCESS && !(((*ce)->ce_flags & (ZEND_ACC_INTERFACE | ZEND_ACC_TRAIT)) > ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)); } if (zend_lookup_class(class_name, class_name_len, &ce TSRMLS_CC) == SUCCESS) { RETURN_BOOL(((*ce)->ce_flags & (ZEND_ACC_INTERFACE | (ZEND_ACC_TRAIT - ZEND_ACC_EXPLICIT_ABSTRACT_CLASS))) == 0); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool interface_exists(string classname [, bool autoload]) Checks if the class exists */ ZEND_FUNCTION(interface_exists) { char *iface_name, *lc_name; zend_class_entry **ce; int iface_name_len; int found; zend_bool autoload = 1; ALLOCA_FLAG(use_heap) if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|b", &iface_name, &iface_name_len, &autoload) == FAILURE) { return; } if (!autoload) { char *name; int len; lc_name = do_alloca(iface_name_len + 1, use_heap); zend_str_tolower_copy(lc_name, iface_name, iface_name_len); /* Ignore leading "\" */ name = lc_name; len = iface_name_len; if (lc_name[0] == '\\') { name = &lc_name[1]; len--; } found = zend_hash_find(EG(class_table), name, len+1, (void **) &ce); free_alloca(lc_name, use_heap); RETURN_BOOL(found == SUCCESS && (*ce)->ce_flags & ZEND_ACC_INTERFACE); } if (zend_lookup_class(iface_name, iface_name_len, &ce TSRMLS_CC) == SUCCESS) { RETURN_BOOL(((*ce)->ce_flags & ZEND_ACC_INTERFACE) > 0); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool trait_exists(string traitname [, bool autoload]) Checks if the trait exists */ ZEND_FUNCTION(trait_exists) { char *trait_name, *lc_name; zend_class_entry **ce; int trait_name_len; int found; zend_bool autoload = 1; ALLOCA_FLAG(use_heap) if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|b", &trait_name, &trait_name_len, &autoload) == FAILURE) { return; } if (!autoload) { char *name; int len; lc_name = do_alloca(trait_name_len + 1, use_heap); zend_str_tolower_copy(lc_name, trait_name, trait_name_len); /* Ignore leading "\" */ name = lc_name; len = trait_name_len; if (lc_name[0] == '\\') { name = &lc_name[1]; len--; } found = zend_hash_find(EG(class_table), name, len+1, (void **) &ce); free_alloca(lc_name, use_heap); RETURN_BOOL(found == SUCCESS && (((*ce)->ce_flags & ZEND_ACC_TRAIT) > ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)); } if (zend_lookup_class(trait_name, trait_name_len, &ce TSRMLS_CC) == SUCCESS) { RETURN_BOOL(((*ce)->ce_flags & ZEND_ACC_TRAIT) > ZEND_ACC_EXPLICIT_ABSTRACT_CLASS); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool function_exists(string function_name) Checks if the function exists */ ZEND_FUNCTION(function_exists) { char *name; int name_len; zend_function *func; char *lcname; zend_bool retval; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) { return; } lcname = zend_str_tolower_dup(name, name_len); /* Ignore leading "\" */ name = lcname; if (lcname[0] == '\\') { name = &lcname[1]; name_len--; } retval = (zend_hash_find(EG(function_table), name, name_len+1, (void **)&func) == SUCCESS); efree(lcname); /* * A bit of a hack, but not a bad one: we see if the handler of the function * is actually one that displays "function is disabled" message. */ if (retval && func->type == ZEND_INTERNAL_FUNCTION && func->internal_function.handler == zif_display_disabled_function) { retval = 0; } RETURN_BOOL(retval); } /* }}} */ /* {{{ proto bool class_alias(string user_class_name , string alias_name [, bool autoload]) Creates an alias for user defined class */ ZEND_FUNCTION(class_alias) { char *class_name, *lc_name, *alias_name; zend_class_entry **ce; int class_name_len, alias_name_len; int found; zend_bool autoload = 1; ALLOCA_FLAG(use_heap) if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|b", &class_name, &class_name_len, &alias_name, &alias_name_len, &autoload) == FAILURE) { return; } if (!autoload) { lc_name = do_alloca(class_name_len + 1, use_heap); zend_str_tolower_copy(lc_name, class_name, class_name_len); found = zend_hash_find(EG(class_table), lc_name, class_name_len+1, (void **) &ce); free_alloca(lc_name, use_heap); } else { found = zend_lookup_class(class_name, class_name_len, &ce TSRMLS_CC); } if (found == SUCCESS) { if ((*ce)->type == ZEND_USER_CLASS) { if (zend_register_class_alias_ex(alias_name, alias_name_len, *ce TSRMLS_CC) == SUCCESS) { RETURN_TRUE; } else { zend_error(E_WARNING, "Cannot redeclare class %s", alias_name); RETURN_FALSE; } } else { zend_error(E_WARNING, "First argument of class_alias() must be a name of user defined class"); RETURN_FALSE; } } else { zend_error(E_WARNING, "Class '%s' not found", class_name); RETURN_FALSE; } } /* }}} */ #if ZEND_DEBUG /* {{{ proto void leak(int num_bytes=3) Cause an intentional memory leak, for testing/debugging purposes */ ZEND_FUNCTION(leak) { long leakbytes=3; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &leakbytes) == FAILURE) { return; } emalloc(leakbytes); } /* }}} */ /* {{{ proto leak_variable(mixed variable [, bool leak_data]) */ ZEND_FUNCTION(leak_variable) { zval *zv; zend_bool leak_data = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|b", &zv, &leak_data) == FAILURE) { return; } if (!leak_data) { zval_add_ref(&zv); } else if (Z_TYPE_P(zv) == IS_RESOURCE) { zend_list_addref(Z_RESVAL_P(zv)); } else if (Z_TYPE_P(zv) == IS_OBJECT) { Z_OBJ_HANDLER_P(zv, add_ref)(zv TSRMLS_CC); } else { zend_error(E_WARNING, "Leaking non-zval data is only applicable to resources and objects"); } } /* }}} */ #ifdef ZEND_TEST_EXCEPTIONS ZEND_FUNCTION(crash) { char *nowhere=NULL; memcpy(nowhere, "something", sizeof("something")); } #endif #endif /* ZEND_DEBUG */ /* {{{ proto array get_included_files(void) Returns an array with the file names that were include_once()'d */ ZEND_FUNCTION(get_included_files) { char *entry; if (zend_parse_parameters_none() == FAILURE) { return; } array_init(return_value); zend_hash_internal_pointer_reset(&EG(included_files)); while (zend_hash_get_current_key(&EG(included_files), &entry, NULL, 1) == HASH_KEY_IS_STRING) { add_next_index_string(return_value, entry, 0); zend_hash_move_forward(&EG(included_files)); } } /* }}} */ /* {{{ proto void trigger_error(string message [, int error_type]) Generates a user-level error/warning/notice message */ ZEND_FUNCTION(trigger_error) { long error_type = E_USER_NOTICE; char *message; int message_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &message, &message_len, &error_type) == FAILURE) { return; } switch (error_type) { case E_USER_ERROR: case E_USER_WARNING: case E_USER_NOTICE: case E_USER_DEPRECATED: break; default: zend_error(E_WARNING, "Invalid error type specified"); RETURN_FALSE; break; } zend_error((int)error_type, "%s", message); RETURN_TRUE; } /* }}} */ /* {{{ proto string set_error_handler(string error_handler [, int error_types]) Sets a user-defined error handler function. Returns the previously defined error handler, or false on error */ ZEND_FUNCTION(set_error_handler) { zval *error_handler; zend_bool had_orig_error_handler=0; char *error_handler_name = NULL; long error_type = E_ALL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|l", &error_handler, &error_type) == FAILURE) { return; } if (!zend_is_callable(error_handler, 0, &error_handler_name TSRMLS_CC)) { zend_error(E_WARNING, "%s() expects the argument (%s) to be a valid callback", get_active_function_name(TSRMLS_C), error_handler_name?error_handler_name:"unknown"); efree(error_handler_name); return; } efree(error_handler_name); if (EG(user_error_handler)) { had_orig_error_handler = 1; *return_value = *EG(user_error_handler); zval_copy_ctor(return_value); INIT_PZVAL(return_value); zend_stack_push(&EG(user_error_handlers_error_reporting), &EG(user_error_handler_error_reporting), sizeof(EG(user_error_handler_error_reporting))); zend_ptr_stack_push(&EG(user_error_handlers), EG(user_error_handler)); } ALLOC_ZVAL(EG(user_error_handler)); if (!zend_is_true(error_handler)) { /* unset user-defined handler */ FREE_ZVAL(EG(user_error_handler)); EG(user_error_handler) = NULL; RETURN_TRUE; } EG(user_error_handler_error_reporting) = (int)error_type; *EG(user_error_handler) = *error_handler; zval_copy_ctor(EG(user_error_handler)); INIT_PZVAL(EG(user_error_handler)); if (!had_orig_error_handler) { RETURN_NULL(); } } /* }}} */ /* {{{ proto void restore_error_handler(void) Restores the previously defined error handler function */ ZEND_FUNCTION(restore_error_handler) { if (EG(user_error_handler)) { zval *zeh = EG(user_error_handler); EG(user_error_handler) = NULL; zval_ptr_dtor(&zeh); } if (zend_ptr_stack_num_elements(&EG(user_error_handlers))==0) { EG(user_error_handler) = NULL; } else { EG(user_error_handler_error_reporting) = zend_stack_int_top(&EG(user_error_handlers_error_reporting)); zend_stack_del_top(&EG(user_error_handlers_error_reporting)); EG(user_error_handler) = zend_ptr_stack_pop(&EG(user_error_handlers)); } RETURN_TRUE; } /* }}} */ /* {{{ proto string set_exception_handler(callable exception_handler) Sets a user-defined exception handler function. Returns the previously defined exception handler, or false on error */ ZEND_FUNCTION(set_exception_handler) { zval *exception_handler; char *exception_handler_name = NULL; zend_bool had_orig_exception_handler=0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &exception_handler) == FAILURE) { return; } if (Z_TYPE_P(exception_handler) != IS_NULL) { /* NULL == unset */ if (!zend_is_callable(exception_handler, 0, &exception_handler_name TSRMLS_CC)) { zend_error(E_WARNING, "%s() expects the argument (%s) to be a valid callback", get_active_function_name(TSRMLS_C), exception_handler_name?exception_handler_name:"unknown"); efree(exception_handler_name); return; } efree(exception_handler_name); } if (EG(user_exception_handler)) { had_orig_exception_handler = 1; *return_value = *EG(user_exception_handler); zval_copy_ctor(return_value); zend_ptr_stack_push(&EG(user_exception_handlers), EG(user_exception_handler)); } ALLOC_ZVAL(EG(user_exception_handler)); if (Z_TYPE_P(exception_handler) == IS_NULL) { /* unset user-defined handler */ FREE_ZVAL(EG(user_exception_handler)); EG(user_exception_handler) = NULL; RETURN_TRUE; } *EG(user_exception_handler) = *exception_handler; zval_copy_ctor(EG(user_exception_handler)); if (!had_orig_exception_handler) { RETURN_NULL(); } } /* }}} */ /* {{{ proto void restore_exception_handler(void) Restores the previously defined exception handler function */ ZEND_FUNCTION(restore_exception_handler) { if (EG(user_exception_handler)) { zval_ptr_dtor(&EG(user_exception_handler)); } if (zend_ptr_stack_num_elements(&EG(user_exception_handlers))==0) { EG(user_exception_handler) = NULL; } else { EG(user_exception_handler) = zend_ptr_stack_pop(&EG(user_exception_handlers)); } RETURN_TRUE; } /* }}} */ static int copy_class_or_interface_name(zend_class_entry **pce TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) { zval *array = va_arg(args, zval *); zend_uint mask = va_arg(args, zend_uint); zend_uint comply = va_arg(args, zend_uint); zend_uint comply_mask = (comply)? mask:0; zend_class_entry *ce = *pce; if ((hash_key->nKeyLength==0 || hash_key->arKey[0]!=0) && (comply_mask == (ce->ce_flags & mask))) { add_next_index_stringl(array, ce->name, ce->name_length, 1); } return ZEND_HASH_APPLY_KEEP; } /* {{{ proto array get_declared_traits() Returns an array of all declared traits. */ ZEND_FUNCTION(get_declared_traits) { zend_uint mask = ZEND_ACC_TRAIT; zend_uint comply = 1; if (zend_parse_parameters_none() == FAILURE) { return; } array_init(return_value); zend_hash_apply_with_arguments(EG(class_table) TSRMLS_CC, (apply_func_args_t) copy_class_or_interface_name, 3, return_value, mask, comply); } /* }}} */ /* {{{ proto array get_declared_classes() Returns an array of all declared classes. */ ZEND_FUNCTION(get_declared_classes) { zend_uint mask = ZEND_ACC_INTERFACE | (ZEND_ACC_TRAIT & ~ZEND_ACC_EXPLICIT_ABSTRACT_CLASS); zend_uint comply = 0; if (zend_parse_parameters_none() == FAILURE) { return; } array_init(return_value); zend_hash_apply_with_arguments(EG(class_table) TSRMLS_CC, (apply_func_args_t) copy_class_or_interface_name, 3, return_value, mask, comply); } /* }}} */ /* {{{ proto array get_declared_interfaces() Returns an array of all declared interfaces. */ ZEND_FUNCTION(get_declared_interfaces) { zend_uint mask = ZEND_ACC_INTERFACE; zend_uint comply = 1; if (zend_parse_parameters_none() == FAILURE) { return; } array_init(return_value); zend_hash_apply_with_arguments(EG(class_table) TSRMLS_CC, (apply_func_args_t) copy_class_or_interface_name, 3, return_value, mask, comply); } /* }}} */ static int copy_function_name(zend_function *func TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) { zval *internal_ar = va_arg(args, zval *), *user_ar = va_arg(args, zval *); if (hash_key->nKeyLength == 0 || hash_key->arKey[0] == 0) { return 0; } if (func->type == ZEND_INTERNAL_FUNCTION) { add_next_index_stringl(internal_ar, hash_key->arKey, hash_key->nKeyLength-1, 1); } else if (func->type == ZEND_USER_FUNCTION) { add_next_index_stringl(user_ar, hash_key->arKey, hash_key->nKeyLength-1, 1); } return 0; } /* {{{ proto array get_defined_functions(void) Returns an array of all defined functions */ ZEND_FUNCTION(get_defined_functions) { zval *internal; zval *user; if (zend_parse_parameters_none() == FAILURE) { return; } MAKE_STD_ZVAL(internal); MAKE_STD_ZVAL(user); array_init(internal); array_init(user); array_init(return_value); zend_hash_apply_with_arguments(EG(function_table) TSRMLS_CC, (apply_func_args_t) copy_function_name, 2, internal, user); if (zend_hash_add(Z_ARRVAL_P(return_value), "internal", sizeof("internal"), (void **)&internal, sizeof(zval *), NULL) == FAILURE) { zval_ptr_dtor(&internal); zval_ptr_dtor(&user); zval_dtor(return_value); zend_error(E_WARNING, "Cannot add internal functions to return value from get_defined_functions()"); RETURN_FALSE; } if (zend_hash_add(Z_ARRVAL_P(return_value), "user", sizeof("user"), (void **)&user, sizeof(zval *), NULL) == FAILURE) { zval_ptr_dtor(&user); zval_dtor(return_value); zend_error(E_WARNING, "Cannot add user functions to return value from get_defined_functions()"); RETURN_FALSE; } } /* }}} */ /* {{{ proto array get_defined_vars(void) Returns an associative array of names and values of all currently defined variable names (variables in the current scope) */ ZEND_FUNCTION(get_defined_vars) { if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } array_init_size(return_value, zend_hash_num_elements(EG(active_symbol_table))); zend_hash_copy(Z_ARRVAL_P(return_value), EG(active_symbol_table), (copy_ctor_func_t)zval_add_ref, NULL, sizeof(zval *)); } /* }}} */ #define LAMBDA_TEMP_FUNCNAME "__lambda_func" /* {{{ proto string create_function(string args, string code) Creates an anonymous function, and returns its name (funny, eh?) */ ZEND_FUNCTION(create_function) { char *eval_code, *function_name, *function_args, *function_code; int eval_code_length, function_name_length, function_args_len, function_code_len; int retval; char *eval_name; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &function_args, &function_args_len, &function_code, &function_code_len) == FAILURE) { return; } eval_code = (char *) emalloc(sizeof("function " LAMBDA_TEMP_FUNCNAME) +function_args_len +2 /* for the args parentheses */ +2 /* for the curly braces */ +function_code_len); eval_code_length = sizeof("function " LAMBDA_TEMP_FUNCNAME "(") - 1; memcpy(eval_code, "function " LAMBDA_TEMP_FUNCNAME "(", eval_code_length); memcpy(eval_code + eval_code_length, function_args, function_args_len); eval_code_length += function_args_len; eval_code[eval_code_length++] = ')'; eval_code[eval_code_length++] = '{'; memcpy(eval_code + eval_code_length, function_code, function_code_len); eval_code_length += function_code_len; eval_code[eval_code_length++] = '}'; eval_code[eval_code_length] = '\0'; eval_name = zend_make_compiled_string_description("runtime-created function" TSRMLS_CC); retval = zend_eval_stringl(eval_code, eval_code_length, NULL, eval_name TSRMLS_CC); efree(eval_code); efree(eval_name); if (retval==SUCCESS) { zend_function new_function, *func; if (zend_hash_find(EG(function_table), LAMBDA_TEMP_FUNCNAME, sizeof(LAMBDA_TEMP_FUNCNAME), (void **) &func)==FAILURE) { zend_error(E_ERROR, "Unexpected inconsistency in create_function()"); RETURN_FALSE; } new_function = *func; function_add_ref(&new_function); function_name = (char *) emalloc(sizeof("0lambda_")+MAX_LENGTH_OF_LONG); function_name[0] = '\0'; do { function_name_length = 1 + snprintf(function_name + 1, sizeof("lambda_")+MAX_LENGTH_OF_LONG, "lambda_%d", ++EG(lambda_count)); } while (zend_hash_add(EG(function_table), function_name, function_name_length+1, &new_function, sizeof(zend_function), NULL)==FAILURE); zend_hash_del(EG(function_table), LAMBDA_TEMP_FUNCNAME, sizeof(LAMBDA_TEMP_FUNCNAME)); RETURN_STRINGL(function_name, function_name_length, 0); } else { zend_hash_del(EG(function_table), LAMBDA_TEMP_FUNCNAME, sizeof(LAMBDA_TEMP_FUNCNAME)); RETURN_FALSE; } } /* }}} */ #if ZEND_DEBUG ZEND_FUNCTION(zend_test_func) { zval *arg1, *arg2; zend_get_parameters(ht, 2, &arg1, &arg2); } #ifdef ZTS ZEND_FUNCTION(zend_thread_id) { RETURN_LONG((long)tsrm_thread_id()); } #endif #endif /* {{{ proto string get_resource_type(resource res) Get the resource type name for a given resource */ ZEND_FUNCTION(get_resource_type) { const char *resource_type; zval *z_resource_type; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &z_resource_type) == FAILURE) { return; } resource_type = zend_rsrc_list_get_rsrc_type(Z_LVAL_P(z_resource_type) TSRMLS_CC); if (resource_type) { RETURN_STRING(resource_type, 1); } else { RETURN_STRING("Unknown", 1); } } /* }}} */ static int add_extension_info(zend_module_entry *module, void *arg TSRMLS_DC) { zval *name_array = (zval *)arg; add_next_index_string(name_array, module->name, 1); return 0; } static int add_zendext_info(zend_extension *ext, void *arg TSRMLS_DC) { zval *name_array = (zval *)arg; add_next_index_string(name_array, ext->name, 1); return 0; } static int add_constant_info(zend_constant *constant, void *arg TSRMLS_DC) { zval *name_array = (zval *)arg; zval *const_val; MAKE_STD_ZVAL(const_val); *const_val = constant->value; zval_copy_ctor(const_val); INIT_PZVAL(const_val); add_assoc_zval_ex(name_array, constant->name, constant->name_len, const_val); return 0; } /* {{{ proto array get_loaded_extensions([bool zend_extensions]) U Return an array containing names of loaded extensions */ ZEND_FUNCTION(get_loaded_extensions) { zend_bool zendext = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &zendext) == FAILURE) { return; } array_init(return_value); if (zendext) { zend_llist_apply_with_argument(&zend_extensions, (llist_apply_with_arg_func_t) add_zendext_info, return_value TSRMLS_CC); } else { zend_hash_apply_with_argument(&module_registry, (apply_func_arg_t) add_extension_info, return_value TSRMLS_CC); } } /* }}} */ /* {{{ proto array get_defined_constants([bool categorize]) Return an array containing the names and values of all defined constants */ ZEND_FUNCTION(get_defined_constants) { zend_bool categorize = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &categorize) == FAILURE) { return; } array_init(return_value); if (categorize) { HashPosition pos; zend_constant *val; int module_number; zval **modules; char **module_names; zend_module_entry *module; int i = 1; modules = ecalloc(zend_hash_num_elements(&module_registry) + 2, sizeof(zval *)); module_names = emalloc((zend_hash_num_elements(&module_registry) + 2) * sizeof(char *)); module_names[0] = "internal"; zend_hash_internal_pointer_reset_ex(&module_registry, &pos); while (zend_hash_get_current_data_ex(&module_registry, (void *) &module, &pos) != FAILURE) { module_names[module->module_number] = (char *)module->name; i++; zend_hash_move_forward_ex(&module_registry, &pos); } module_names[i] = "user"; zend_hash_internal_pointer_reset_ex(EG(zend_constants), &pos); while (zend_hash_get_current_data_ex(EG(zend_constants), (void **) &val, &pos) != FAILURE) { zval *const_val; if (val->module_number == PHP_USER_CONSTANT) { module_number = i; } else if (val->module_number > i || val->module_number < 0) { /* should not happen */ goto bad_module_id; } else { module_number = val->module_number; } if (!modules[module_number]) { MAKE_STD_ZVAL(modules[module_number]); array_init(modules[module_number]); add_assoc_zval(return_value, module_names[module_number], modules[module_number]); } MAKE_STD_ZVAL(const_val); *const_val = val->value; zval_copy_ctor(const_val); INIT_PZVAL(const_val); add_assoc_zval_ex(modules[module_number], val->name, val->name_len, const_val); bad_module_id: zend_hash_move_forward_ex(EG(zend_constants), &pos); } efree(module_names); efree(modules); } else { zend_hash_apply_with_argument(EG(zend_constants), (apply_func_arg_t) add_constant_info, return_value TSRMLS_CC); } } /* }}} */ static zval *debug_backtrace_get_args(void **curpos TSRMLS_DC) { void **p = curpos; zval *arg_array, **arg; int arg_count = (int)(zend_uintptr_t) *p; MAKE_STD_ZVAL(arg_array); array_init_size(arg_array, arg_count); p -= arg_count; while (--arg_count >= 0) { arg = (zval **) p++; if (*arg) { if (Z_TYPE_PP(arg) != IS_OBJECT) { SEPARATE_ZVAL_TO_MAKE_IS_REF(arg); } Z_ADDREF_PP(arg); add_next_index_zval(arg_array, *arg); } else { add_next_index_null(arg_array); } } return arg_array; } void debug_print_backtrace_args(zval *arg_array TSRMLS_DC) { zval **tmp; HashPosition iterator; int i = 0; zend_hash_internal_pointer_reset_ex(arg_array->value.ht, &iterator); while (zend_hash_get_current_data_ex(arg_array->value.ht, (void **) &tmp, &iterator) == SUCCESS) { if (i++) { ZEND_PUTS(", "); } zend_print_flat_zval_r(*tmp TSRMLS_CC); zend_hash_move_forward_ex(arg_array->value.ht, &iterator); } } /* {{{ proto void debug_print_backtrace([int options[, int limit]]) */ ZEND_FUNCTION(debug_print_backtrace) { zend_execute_data *ptr, *skip; int lineno, frameno = 0; const char *function_name; const char *filename; const char *class_name = NULL; char *call_type; const char *include_filename = NULL; zval *arg_array = NULL; int indent = 0; long options = 0; long limit = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|ll", &options, &limit) == FAILURE) { return; } ptr = EG(current_execute_data); /* skip debug_backtrace() */ ptr = ptr->prev_execute_data; while (ptr && (limit == 0 || frameno < limit)) { const char *free_class_name = NULL; frameno++; class_name = call_type = NULL; arg_array = NULL; skip = ptr; /* skip internal handler */ if (!skip->op_array && skip->prev_execute_data && skip->prev_execute_data->opline && skip->prev_execute_data->opline->opcode != ZEND_DO_FCALL && skip->prev_execute_data->opline->opcode != ZEND_DO_FCALL_BY_NAME && skip->prev_execute_data->opline->opcode != ZEND_INCLUDE_OR_EVAL) { skip = skip->prev_execute_data; } if (skip->op_array) { filename = skip->op_array->filename; lineno = skip->opline->lineno; } else { filename = NULL; lineno = 0; } function_name = ptr->function_state.function->common.function_name; if (function_name) { if (ptr->object) { if (ptr->function_state.function->common.scope) { class_name = ptr->function_state.function->common.scope->name; } else { zend_uint class_name_len; int dup; dup = zend_get_object_classname(ptr->object, &class_name, &class_name_len TSRMLS_CC); if(!dup) { free_class_name = class_name; } } call_type = "->"; } else if (ptr->function_state.function->common.scope) { class_name = ptr->function_state.function->common.scope->name; call_type = "::"; } else { class_name = NULL; call_type = NULL; } if ((! ptr->opline) || ((ptr->opline->opcode == ZEND_DO_FCALL_BY_NAME) || (ptr->opline->opcode == ZEND_DO_FCALL))) { if (ptr->function_state.arguments && (options & DEBUG_BACKTRACE_IGNORE_ARGS) == 0) { arg_array = debug_backtrace_get_args(ptr->function_state.arguments TSRMLS_CC); } } } else { /* i know this is kinda ugly, but i'm trying to avoid extra cycles in the main execution loop */ zend_bool build_filename_arg = 1; if (!ptr->opline || ptr->opline->opcode != ZEND_INCLUDE_OR_EVAL) { /* can happen when calling eval from a custom sapi */ function_name = "unknown"; build_filename_arg = 0; } else switch (ptr->opline->extended_value) { case ZEND_EVAL: function_name = "eval"; build_filename_arg = 0; break; case ZEND_INCLUDE: function_name = "include"; break; case ZEND_REQUIRE: function_name = "require"; break; case ZEND_INCLUDE_ONCE: function_name = "include_once"; break; case ZEND_REQUIRE_ONCE: function_name = "require_once"; break; default: /* this can actually happen if you use debug_backtrace() in your error_handler and * you're in the top-scope */ function_name = "unknown"; build_filename_arg = 0; break; } if (build_filename_arg && include_filename) { MAKE_STD_ZVAL(arg_array); array_init(arg_array); add_next_index_string(arg_array, (char*)include_filename, 1); } call_type = NULL; } zend_printf("#%-2d ", indent); if (class_name) { ZEND_PUTS(class_name); ZEND_PUTS(call_type); } zend_printf("%s(", function_name); if (arg_array) { debug_print_backtrace_args(arg_array TSRMLS_CC); zval_ptr_dtor(&arg_array); } if (filename) { zend_printf(") called at [%s:%d]\n", filename, lineno); } else { zend_execute_data *prev = skip->prev_execute_data; while (prev) { if (prev->function_state.function && prev->function_state.function->common.type != ZEND_USER_FUNCTION) { prev = NULL; break; } if (prev->op_array) { zend_printf(") called at [%s:%d]\n", prev->op_array->filename, prev->opline->lineno); break; } prev = prev->prev_execute_data; } if (!prev) { ZEND_PUTS(")\n"); } } include_filename = filename; ptr = skip->prev_execute_data; ++indent; if (free_class_name) { efree((char*)free_class_name); } } } /* }}} */ ZEND_API void zend_fetch_debug_backtrace(zval *return_value, int skip_last, int options, int limit TSRMLS_DC) { zend_execute_data *ptr, *skip; int lineno, frameno = 0; const char *function_name; const char *filename; const char *class_name; const char *include_filename = NULL; zval *stack_frame; ptr = EG(current_execute_data); /* skip "new Exception()" */ if (ptr && (skip_last == 0) && ptr->opline && (ptr->opline->opcode == ZEND_NEW)) { ptr = ptr->prev_execute_data; } /* skip debug_backtrace() */ if (skip_last-- && ptr) { ptr = ptr->prev_execute_data; } array_init(return_value); while (ptr && (limit == 0 || frameno < limit)) { frameno++; MAKE_STD_ZVAL(stack_frame); array_init(stack_frame); skip = ptr; /* skip internal handler */ if (!skip->op_array && skip->prev_execute_data && skip->prev_execute_data->opline && skip->prev_execute_data->opline->opcode != ZEND_DO_FCALL && skip->prev_execute_data->opline->opcode != ZEND_DO_FCALL_BY_NAME && skip->prev_execute_data->opline->opcode != ZEND_INCLUDE_OR_EVAL) { skip = skip->prev_execute_data; } if (skip->op_array) { filename = skip->op_array->filename; lineno = skip->opline->lineno; add_assoc_string_ex(stack_frame, "file", sizeof("file"), (char*)filename, 1); add_assoc_long_ex(stack_frame, "line", sizeof("line"), lineno); /* try to fetch args only if an FCALL was just made - elsewise we're in the middle of a function * and debug_baktrace() might have been called by the error_handler. in this case we don't * want to pop anything of the argument-stack */ } else { zend_execute_data *prev = skip->prev_execute_data; while (prev) { if (prev->function_state.function && prev->function_state.function->common.type != ZEND_USER_FUNCTION && !(prev->function_state.function->common.type == ZEND_INTERNAL_FUNCTION && (prev->function_state.function->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER))) { break; } if (prev->op_array) { add_assoc_string_ex(stack_frame, "file", sizeof("file"), (char*)prev->op_array->filename, 1); add_assoc_long_ex(stack_frame, "line", sizeof("line"), prev->opline->lineno); break; } prev = prev->prev_execute_data; } filename = NULL; } function_name = ptr->function_state.function->common.function_name; if (function_name) { add_assoc_string_ex(stack_frame, "function", sizeof("function"), (char*)function_name, 1); if (ptr->object && Z_TYPE_P(ptr->object) == IS_OBJECT) { if (ptr->function_state.function->common.scope) { add_assoc_string_ex(stack_frame, "class", sizeof("class"), (char*)ptr->function_state.function->common.scope->name, 1); } else { zend_uint class_name_len; int dup; dup = zend_get_object_classname(ptr->object, &class_name, &class_name_len TSRMLS_CC); add_assoc_string_ex(stack_frame, "class", sizeof("class"), (char*)class_name, dup); } if ((options & DEBUG_BACKTRACE_PROVIDE_OBJECT) != 0) { add_assoc_zval_ex(stack_frame, "object", sizeof("object"), ptr->object); Z_ADDREF_P(ptr->object); } add_assoc_string_ex(stack_frame, "type", sizeof("type"), "->", 1); } else if (ptr->function_state.function->common.scope) { add_assoc_string_ex(stack_frame, "class", sizeof("class"), (char*)ptr->function_state.function->common.scope->name, 1); add_assoc_string_ex(stack_frame, "type", sizeof("type"), "::", 1); } if ((options & DEBUG_BACKTRACE_IGNORE_ARGS) == 0 && ((! ptr->opline) || ((ptr->opline->opcode == ZEND_DO_FCALL_BY_NAME) || (ptr->opline->opcode == ZEND_DO_FCALL)))) { if (ptr->function_state.arguments) { add_assoc_zval_ex(stack_frame, "args", sizeof("args"), debug_backtrace_get_args(ptr->function_state.arguments TSRMLS_CC)); } } } else { /* i know this is kinda ugly, but i'm trying to avoid extra cycles in the main execution loop */ zend_bool build_filename_arg = 1; if (!ptr->opline || ptr->opline->opcode != ZEND_INCLUDE_OR_EVAL) { /* can happen when calling eval from a custom sapi */ function_name = "unknown"; build_filename_arg = 0; } else switch (ptr->opline->extended_value) { case ZEND_EVAL: function_name = "eval"; build_filename_arg = 0; break; case ZEND_INCLUDE: function_name = "include"; break; case ZEND_REQUIRE: function_name = "require"; break; case ZEND_INCLUDE_ONCE: function_name = "include_once"; break; case ZEND_REQUIRE_ONCE: function_name = "require_once"; break; default: /* this can actually happen if you use debug_backtrace() in your error_handler and * you're in the top-scope */ function_name = "unknown"; build_filename_arg = 0; break; } if (build_filename_arg && include_filename) { zval *arg_array; MAKE_STD_ZVAL(arg_array); array_init(arg_array); /* include_filename always points to the last filename of the last last called-fuction. if we have called include in the frame above - this is the file we have included. */ add_next_index_string(arg_array, (char*)include_filename, 1); add_assoc_zval_ex(stack_frame, "args", sizeof("args"), arg_array); } add_assoc_string_ex(stack_frame, "function", sizeof("function"), (char*)function_name, 1); } add_next_index_zval(return_value, stack_frame); include_filename = filename; ptr = skip->prev_execute_data; } } /* }}} */ /* {{{ proto array debug_backtrace([int options[, int limit]]) Return backtrace as array */ ZEND_FUNCTION(debug_backtrace) { long options = DEBUG_BACKTRACE_PROVIDE_OBJECT; long limit = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|ll", &options, &limit) == FAILURE) { return; } zend_fetch_debug_backtrace(return_value, 1, options, limit TSRMLS_CC); } /* }}} */ /* {{{ proto bool extension_loaded(string extension_name) Returns true if the named extension is loaded */ ZEND_FUNCTION(extension_loaded) { char *extension_name; int extension_name_len; char *lcname; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &extension_name, &extension_name_len) == FAILURE) { return; } lcname = zend_str_tolower_dup(extension_name, extension_name_len); if (zend_hash_exists(&module_registry, lcname, extension_name_len+1)) { RETVAL_TRUE; } else { RETVAL_FALSE; } efree(lcname); } /* }}} */ /* {{{ proto array get_extension_funcs(string extension_name) Returns an array with the names of functions belonging to the named extension */ ZEND_FUNCTION(get_extension_funcs) { char *extension_name; int extension_name_len; zend_module_entry *module; const zend_function_entry *func; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &extension_name, &extension_name_len) == FAILURE) { return; } if (strncasecmp(extension_name, "zend", sizeof("zend"))) { char *lcname = zend_str_tolower_dup(extension_name, extension_name_len); if (zend_hash_find(&module_registry, lcname, extension_name_len+1, (void**)&module) == FAILURE) { efree(lcname); RETURN_FALSE; } efree(lcname); if (!(func = module->functions)) { RETURN_FALSE; } } else { func = builtin_functions; } array_init(return_value); while (func->fname) { add_next_index_string(return_value, func->fname, 1); func++; } } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */ /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "zend.h" #include "zend_API.h" #include "zend_builtin_functions.h" #include "zend_constants.h" #include "zend_ini.h" #include "zend_exceptions.h" #include "zend_extensions.h" #include "zend_closures.h" #undef ZEND_TEST_EXCEPTIONS static ZEND_FUNCTION(zend_version); static ZEND_FUNCTION(func_num_args); static ZEND_FUNCTION(func_get_arg); static ZEND_FUNCTION(func_get_args); static ZEND_FUNCTION(strlen); static ZEND_FUNCTION(strcmp); static ZEND_FUNCTION(strncmp); static ZEND_FUNCTION(strcasecmp); static ZEND_FUNCTION(strncasecmp); static ZEND_FUNCTION(each); static ZEND_FUNCTION(error_reporting); static ZEND_FUNCTION(define); static ZEND_FUNCTION(defined); static ZEND_FUNCTION(get_class); static ZEND_FUNCTION(get_called_class); static ZEND_FUNCTION(get_parent_class); static ZEND_FUNCTION(method_exists); static ZEND_FUNCTION(property_exists); static ZEND_FUNCTION(class_exists); static ZEND_FUNCTION(interface_exists); static ZEND_FUNCTION(trait_exists); static ZEND_FUNCTION(function_exists); static ZEND_FUNCTION(class_alias); #if ZEND_DEBUG static ZEND_FUNCTION(leak); static ZEND_FUNCTION(leak_variable); #ifdef ZEND_TEST_EXCEPTIONS static ZEND_FUNCTION(crash); #endif #endif static ZEND_FUNCTION(get_included_files); static ZEND_FUNCTION(is_subclass_of); static ZEND_FUNCTION(is_a); static ZEND_FUNCTION(get_class_vars); static ZEND_FUNCTION(get_object_vars); static ZEND_FUNCTION(get_class_methods); static ZEND_FUNCTION(trigger_error); static ZEND_FUNCTION(set_error_handler); static ZEND_FUNCTION(restore_error_handler); static ZEND_FUNCTION(set_exception_handler); static ZEND_FUNCTION(restore_exception_handler); static ZEND_FUNCTION(get_declared_classes); static ZEND_FUNCTION(get_declared_traits); static ZEND_FUNCTION(get_declared_interfaces); static ZEND_FUNCTION(get_defined_functions); static ZEND_FUNCTION(get_defined_vars); static ZEND_FUNCTION(create_function); static ZEND_FUNCTION(get_resource_type); static ZEND_FUNCTION(get_loaded_extensions); static ZEND_FUNCTION(extension_loaded); static ZEND_FUNCTION(get_extension_funcs); static ZEND_FUNCTION(get_defined_constants); static ZEND_FUNCTION(debug_backtrace); static ZEND_FUNCTION(debug_print_backtrace); #if ZEND_DEBUG static ZEND_FUNCTION(zend_test_func); #ifdef ZTS static ZEND_FUNCTION(zend_thread_id); #endif #endif static ZEND_FUNCTION(gc_collect_cycles); static ZEND_FUNCTION(gc_enabled); static ZEND_FUNCTION(gc_enable); static ZEND_FUNCTION(gc_disable); /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO(arginfo_zend__void, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_func_get_arg, 0, 0, 1) ZEND_ARG_INFO(0, arg_num) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strlen, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strcmp, 0, 0, 2) ZEND_ARG_INFO(0, str1) ZEND_ARG_INFO(0, str2) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strncmp, 0, 0, 3) ZEND_ARG_INFO(0, str1) ZEND_ARG_INFO(0, str2) ZEND_ARG_INFO(0, len) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_each, 0, 0, 1) ZEND_ARG_INFO(1, arr) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_error_reporting, 0, 0, 0) ZEND_ARG_INFO(0, new_error_level) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_define, 0, 0, 3) ZEND_ARG_INFO(0, constant_name) ZEND_ARG_INFO(0, value) ZEND_ARG_INFO(0, case_insensitive) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_defined, 0, 0, 1) ZEND_ARG_INFO(0, constant_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_get_class, 0, 0, 0) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_is_subclass_of, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, class_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_get_class_vars, 0, 0, 1) ZEND_ARG_INFO(0, class_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_get_object_vars, 0, 0, 1) ZEND_ARG_INFO(0, obj) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_get_class_methods, 0, 0, 1) ZEND_ARG_INFO(0, class) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_method_exists, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, method) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_property_exists, 0, 0, 2) ZEND_ARG_INFO(0, object_or_class) ZEND_ARG_INFO(0, property_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_class_exists, 0, 0, 1) ZEND_ARG_INFO(0, classname) ZEND_ARG_INFO(0, autoload) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_trait_exists, 0, 0, 1) ZEND_ARG_INFO(0, traitname) ZEND_ARG_INFO(0, autoload) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_function_exists, 0, 0, 1) ZEND_ARG_INFO(0, function_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_class_alias, 0, 0, 2) ZEND_ARG_INFO(0, user_class_name) ZEND_ARG_INFO(0, alias_name) ZEND_ARG_INFO(0, autoload) ZEND_END_ARG_INFO() #if ZEND_DEBUG ZEND_BEGIN_ARG_INFO_EX(arginfo_leak_variable, 0, 0, 1) ZEND_ARG_INFO(0, variable) ZEND_ARG_INFO(0, leak_data) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_trigger_error, 0, 0, 1) ZEND_ARG_INFO(0, message) ZEND_ARG_INFO(0, error_type) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_set_error_handler, 0, 0, 1) ZEND_ARG_INFO(0, error_handler) ZEND_ARG_INFO(0, error_types) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_set_exception_handler, 0, 0, 1) ZEND_ARG_INFO(0, exception_handler) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_create_function, 0, 0, 2) ZEND_ARG_INFO(0, args) ZEND_ARG_INFO(0, code) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_get_resource_type, 0, 0, 1) ZEND_ARG_INFO(0, res) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_get_loaded_extensions, 0, 0, 0) ZEND_ARG_INFO(0, zend_extensions) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_get_defined_constants, 0, 0, 0) ZEND_ARG_INFO(0, categorize) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_debug_backtrace, 0, 0, 0) ZEND_ARG_INFO(0, options) ZEND_ARG_INFO(0, limit) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_debug_print_backtrace, 0, 0, 0) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_extension_loaded, 0, 0, 1) ZEND_ARG_INFO(0, extension_name) ZEND_END_ARG_INFO() /* }}} */ static const zend_function_entry builtin_functions[] = { /* {{{ */ ZEND_FE(zend_version, arginfo_zend__void) ZEND_FE(func_num_args, arginfo_zend__void) ZEND_FE(func_get_arg, arginfo_func_get_arg) ZEND_FE(func_get_args, arginfo_zend__void) ZEND_FE(strlen, arginfo_strlen) ZEND_FE(strcmp, arginfo_strcmp) ZEND_FE(strncmp, arginfo_strncmp) ZEND_FE(strcasecmp, arginfo_strcmp) ZEND_FE(strncasecmp, arginfo_strncmp) ZEND_FE(each, arginfo_each) ZEND_FE(error_reporting, arginfo_error_reporting) ZEND_FE(define, arginfo_define) ZEND_FE(defined, arginfo_defined) ZEND_FE(get_class, arginfo_get_class) ZEND_FE(get_called_class, arginfo_zend__void) ZEND_FE(get_parent_class, arginfo_get_class) ZEND_FE(method_exists, arginfo_method_exists) ZEND_FE(property_exists, arginfo_property_exists) ZEND_FE(class_exists, arginfo_class_exists) ZEND_FE(interface_exists, arginfo_class_exists) ZEND_FE(trait_exists, arginfo_trait_exists) ZEND_FE(function_exists, arginfo_function_exists) ZEND_FE(class_alias, arginfo_class_alias) #if ZEND_DEBUG ZEND_FE(leak, NULL) ZEND_FE(leak_variable, arginfo_leak_variable) #ifdef ZEND_TEST_EXCEPTIONS ZEND_FE(crash, NULL) #endif #endif ZEND_FE(get_included_files, arginfo_zend__void) ZEND_FALIAS(get_required_files, get_included_files, arginfo_zend__void) ZEND_FE(is_subclass_of, arginfo_is_subclass_of) ZEND_FE(is_a, arginfo_is_subclass_of) ZEND_FE(get_class_vars, arginfo_get_class_vars) ZEND_FE(get_object_vars, arginfo_get_object_vars) ZEND_FE(get_class_methods, arginfo_get_class_methods) ZEND_FE(trigger_error, arginfo_trigger_error) ZEND_FALIAS(user_error, trigger_error, arginfo_trigger_error) ZEND_FE(set_error_handler, arginfo_set_error_handler) ZEND_FE(restore_error_handler, arginfo_zend__void) ZEND_FE(set_exception_handler, arginfo_set_exception_handler) ZEND_FE(restore_exception_handler, arginfo_zend__void) ZEND_FE(get_declared_classes, arginfo_zend__void) ZEND_FE(get_declared_traits, arginfo_zend__void) ZEND_FE(get_declared_interfaces, arginfo_zend__void) ZEND_FE(get_defined_functions, arginfo_zend__void) ZEND_FE(get_defined_vars, arginfo_zend__void) ZEND_FE(create_function, arginfo_create_function) ZEND_FE(get_resource_type, arginfo_get_resource_type) ZEND_FE(get_loaded_extensions, arginfo_get_loaded_extensions) ZEND_FE(extension_loaded, arginfo_extension_loaded) ZEND_FE(get_extension_funcs, arginfo_extension_loaded) ZEND_FE(get_defined_constants, arginfo_get_defined_constants) ZEND_FE(debug_backtrace, arginfo_debug_backtrace) ZEND_FE(debug_print_backtrace, arginfo_debug_print_backtrace) #if ZEND_DEBUG ZEND_FE(zend_test_func, NULL) #ifdef ZTS ZEND_FE(zend_thread_id, NULL) #endif #endif ZEND_FE(gc_collect_cycles, arginfo_zend__void) ZEND_FE(gc_enabled, arginfo_zend__void) ZEND_FE(gc_enable, arginfo_zend__void) ZEND_FE(gc_disable, arginfo_zend__void) ZEND_FE_END }; /* }}} */ ZEND_MINIT_FUNCTION(core) { /* {{{ */ zend_class_entry class_entry; INIT_CLASS_ENTRY(class_entry, "stdClass", NULL); zend_standard_class_def = zend_register_internal_class(&class_entry TSRMLS_CC); zend_register_default_classes(TSRMLS_C); return SUCCESS; } /* }}} */ zend_module_entry zend_builtin_module = { /* {{{ */ STANDARD_MODULE_HEADER, "Core", builtin_functions, ZEND_MINIT(core), NULL, NULL, NULL, NULL, ZEND_VERSION, STANDARD_MODULE_PROPERTIES }; /* }}} */ int zend_startup_builtin_functions(TSRMLS_D) /* {{{ */ { zend_builtin_module.module_number = 0; zend_builtin_module.type = MODULE_PERSISTENT; return (EG(current_module) = zend_register_module_ex(&zend_builtin_module TSRMLS_CC)) == NULL ? FAILURE : SUCCESS; } /* }}} */ /* {{{ proto string zend_version(void) Get the version of the Zend Engine */ ZEND_FUNCTION(zend_version) { RETURN_STRINGL(ZEND_VERSION, sizeof(ZEND_VERSION)-1, 1); } /* }}} */ /* {{{ proto int gc_collect_cycles(void) Forces collection of any existing garbage cycles. Returns number of freed zvals */ ZEND_FUNCTION(gc_collect_cycles) { RETURN_LONG(gc_collect_cycles(TSRMLS_C)); } /* }}} */ /* {{{ proto void gc_enabled(void) Returns status of the circular reference collector */ ZEND_FUNCTION(gc_enabled) { RETURN_BOOL(GC_G(gc_enabled)); } /* }}} */ /* {{{ proto void gc_enable(void) Activates the circular reference collector */ ZEND_FUNCTION(gc_enable) { zend_alter_ini_entry("zend.enable_gc", sizeof("zend.enable_gc"), "1", sizeof("1")-1, ZEND_INI_USER, ZEND_INI_STAGE_RUNTIME); } /* }}} */ /* {{{ proto void gc_disable(void) Deactivates the circular reference collector */ ZEND_FUNCTION(gc_disable) { zend_alter_ini_entry("zend.enable_gc", sizeof("zend.enable_gc"), "0", sizeof("0")-1, ZEND_INI_USER, ZEND_INI_STAGE_RUNTIME); } /* }}} */ /* {{{ proto int func_num_args(void) Get the number of arguments that were passed to the function */ ZEND_FUNCTION(func_num_args) { zend_execute_data *ex = EG(current_execute_data)->prev_execute_data; if (ex && ex->function_state.arguments) { RETURN_LONG((long)(zend_uintptr_t)*(ex->function_state.arguments)); } else { zend_error(E_WARNING, "func_num_args(): Called from the global scope - no function context"); RETURN_LONG(-1); } } /* }}} */ /* {{{ proto mixed func_get_arg(int arg_num) Get the $arg_num'th argument that was passed to the function */ ZEND_FUNCTION(func_get_arg) { void **p; int arg_count; zval *arg; long requested_offset; zend_execute_data *ex = EG(current_execute_data)->prev_execute_data; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &requested_offset) == FAILURE) { return; } if (requested_offset < 0) { zend_error(E_WARNING, "func_get_arg(): The argument number should be >= 0"); RETURN_FALSE; } if (!ex || !ex->function_state.arguments) { zend_error(E_WARNING, "func_get_arg(): Called from the global scope - no function context"); RETURN_FALSE; } p = ex->function_state.arguments; arg_count = (int)(zend_uintptr_t) *p; /* this is the amount of arguments passed to func_get_arg(); */ if (requested_offset >= arg_count) { zend_error(E_WARNING, "func_get_arg(): Argument %ld not passed to function", requested_offset); RETURN_FALSE; } arg = *(p-(arg_count-requested_offset)); *return_value = *arg; zval_copy_ctor(return_value); INIT_PZVAL(return_value); } /* }}} */ /* {{{ proto array func_get_args() Get an array of the arguments that were passed to the function */ ZEND_FUNCTION(func_get_args) { void **p; int arg_count; int i; zend_execute_data *ex = EG(current_execute_data)->prev_execute_data; if (!ex || !ex->function_state.arguments) { zend_error(E_WARNING, "func_get_args(): Called from the global scope - no function context"); RETURN_FALSE; } p = ex->function_state.arguments; arg_count = (int)(zend_uintptr_t) *p; /* this is the amount of arguments passed to func_get_args(); */ array_init_size(return_value, arg_count); for (i=0; i<arg_count; i++) { zval *element; ALLOC_ZVAL(element); *element = **((zval **) (p-(arg_count-i))); zval_copy_ctor(element); INIT_PZVAL(element); zend_hash_next_index_insert(return_value->value.ht, &element, sizeof(zval *), NULL); } } /* }}} */ /* {{{ proto int strlen(string str) Get string length */ ZEND_FUNCTION(strlen) { char *s1; int s1_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &s1, &s1_len) == FAILURE) { return; } RETVAL_LONG(s1_len); } /* }}} */ /* {{{ proto int strcmp(string str1, string str2) Binary safe string comparison */ ZEND_FUNCTION(strcmp) { char *s1, *s2; int s1_len, s2_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &s1, &s1_len, &s2, &s2_len) == FAILURE) { return; } RETURN_LONG(zend_binary_strcmp(s1, s1_len, s2, s2_len)); } /* }}} */ /* {{{ proto int strncmp(string str1, string str2, int len) Binary safe string comparison */ ZEND_FUNCTION(strncmp) { char *s1, *s2; int s1_len, s2_len; long len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ssl", &s1, &s1_len, &s2, &s2_len, &len) == FAILURE) { return; } if (len < 0) { zend_error(E_WARNING, "Length must be greater than or equal to 0"); RETURN_FALSE; } RETURN_LONG(zend_binary_strncmp(s1, s1_len, s2, s2_len, len)); } /* }}} */ /* {{{ proto int strcasecmp(string str1, string str2) Binary safe case-insensitive string comparison */ ZEND_FUNCTION(strcasecmp) { char *s1, *s2; int s1_len, s2_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &s1, &s1_len, &s2, &s2_len) == FAILURE) { return; } RETURN_LONG(zend_binary_strcasecmp(s1, s1_len, s2, s2_len)); } /* }}} */ /* {{{ proto int strncasecmp(string str1, string str2, int len) Binary safe string comparison */ ZEND_FUNCTION(strncasecmp) { char *s1, *s2; int s1_len, s2_len; long len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ssl", &s1, &s1_len, &s2, &s2_len, &len) == FAILURE) { return; } if (len < 0) { zend_error(E_WARNING, "Length must be greater than or equal to 0"); RETURN_FALSE; } RETURN_LONG(zend_binary_strncasecmp(s1, s1_len, s2, s2_len, len)); } /* }}} */ /* {{{ proto array each(array arr) Return the currently pointed key..value pair in the passed array, and advance the pointer to the next element */ ZEND_FUNCTION(each) { zval *array, *entry, **entry_ptr, *tmp; char *string_key; uint string_key_len; ulong num_key; zval **inserted_pointer; HashTable *target_hash; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &array) == FAILURE) { return; } target_hash = HASH_OF(array); if (!target_hash) { zend_error(E_WARNING,"Variable passed to each() is not an array or object"); return; } if (zend_hash_get_current_data(target_hash, (void **) &entry_ptr)==FAILURE) { RETURN_FALSE; } array_init(return_value); entry = *entry_ptr; /* add value elements */ if (Z_ISREF_P(entry)) { ALLOC_ZVAL(tmp); *tmp = *entry; zval_copy_ctor(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); entry=tmp; } zend_hash_index_update(return_value->value.ht, 1, &entry, sizeof(zval *), NULL); Z_ADDREF_P(entry); zend_hash_update(return_value->value.ht, "value", sizeof("value"), &entry, sizeof(zval *), NULL); Z_ADDREF_P(entry); /* add the key elements */ switch (zend_hash_get_current_key_ex(target_hash, &string_key, &string_key_len, &num_key, 1, NULL)) { case HASH_KEY_IS_STRING: add_get_index_stringl(return_value, 0, string_key, string_key_len-1, (void **) &inserted_pointer, 0); break; case HASH_KEY_IS_LONG: add_get_index_long(return_value, 0, num_key, (void **) &inserted_pointer); break; } zend_hash_update(return_value->value.ht, "key", sizeof("key"), inserted_pointer, sizeof(zval *), NULL); Z_ADDREF_PP(inserted_pointer); zend_hash_move_forward(target_hash); } /* }}} */ /* {{{ proto int error_reporting([int new_error_level]) Return the current error_reporting level, and if an argument was passed - change to the new level */ ZEND_FUNCTION(error_reporting) { char *err; int err_len; int old_error_reporting; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &err, &err_len) == FAILURE) { return; } old_error_reporting = EG(error_reporting); if(ZEND_NUM_ARGS() != 0) { zend_alter_ini_entry("error_reporting", sizeof("error_reporting"), err, err_len, ZEND_INI_USER, ZEND_INI_STAGE_RUNTIME); } RETVAL_LONG(old_error_reporting); } /* }}} */ /* {{{ proto bool define(string constant_name, mixed value, boolean case_insensitive=false) Define a new constant */ ZEND_FUNCTION(define) { char *name; int name_len; zval *val; zval *val_free = NULL; zend_bool non_cs = 0; int case_sensitive = CONST_CS; zend_constant c; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz|b", &name, &name_len, &val, &non_cs) == FAILURE) { return; } if(non_cs) { case_sensitive = 0; } /* class constant, check if there is name and make sure class is valid & exists */ if (zend_memnstr(name, "::", sizeof("::") - 1, name + name_len)) { zend_error(E_WARNING, "Class constants cannot be defined or redefined"); RETURN_FALSE; } repeat: switch (Z_TYPE_P(val)) { case IS_LONG: case IS_DOUBLE: case IS_STRING: case IS_BOOL: case IS_RESOURCE: case IS_NULL: break; case IS_OBJECT: if (!val_free) { if (Z_OBJ_HT_P(val)->get) { val_free = val = Z_OBJ_HT_P(val)->get(val TSRMLS_CC); goto repeat; } else if (Z_OBJ_HT_P(val)->cast_object) { ALLOC_INIT_ZVAL(val_free); if (Z_OBJ_HT_P(val)->cast_object(val, val_free, IS_STRING TSRMLS_CC) == SUCCESS) { val = val_free; break; } } } /* no break */ default: zend_error(E_WARNING,"Constants may only evaluate to scalar values"); if (val_free) { zval_ptr_dtor(&val_free); } RETURN_FALSE; } c.value = *val; zval_copy_ctor(&c.value); if (val_free) { zval_ptr_dtor(&val_free); } c.flags = case_sensitive; /* non persistent */ c.name = IS_INTERNED(name) ? name : zend_strndup(name, name_len); c.name_len = name_len+1; c.module_number = PHP_USER_CONSTANT; if (zend_register_constant(&c TSRMLS_CC) == SUCCESS) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool defined(string constant_name) Check whether a constant exists */ ZEND_FUNCTION(defined) { char *name; int name_len; zval c; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) { return; } if (zend_get_constant_ex(name, name_len, &c, NULL, ZEND_FETCH_CLASS_SILENT TSRMLS_CC)) { zval_dtor(&c); RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto string get_class([object object]) Retrieves the class name */ ZEND_FUNCTION(get_class) { zval *obj = NULL; const char *name = ""; zend_uint name_len = 0; int dup; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|o!", &obj) == FAILURE) { RETURN_FALSE; } if (!obj) { if (EG(scope)) { RETURN_STRINGL(EG(scope)->name, EG(scope)->name_length, 1); } else { zend_error(E_WARNING, "get_class() called without object from outside a class"); RETURN_FALSE; } } dup = zend_get_object_classname(obj, &name, &name_len TSRMLS_CC); RETURN_STRINGL(name, name_len, dup); } /* }}} */ /* {{{ proto string get_called_class() Retrieves the "Late Static Binding" class name */ ZEND_FUNCTION(get_called_class) { if (zend_parse_parameters_none() == FAILURE) { return; } if (EG(called_scope)) { RETURN_STRINGL(EG(called_scope)->name, EG(called_scope)->name_length, 1); } else if (!EG(scope)) { zend_error(E_WARNING, "get_called_class() called from outside a class"); } RETURN_FALSE; } /* }}} */ /* {{{ proto string get_parent_class([mixed object]) Retrieves the parent class name for object or class or current scope. */ ZEND_FUNCTION(get_parent_class) { zval *arg; zend_class_entry *ce = NULL; const char *name; zend_uint name_length; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &arg) == FAILURE) { return; } if (!ZEND_NUM_ARGS()) { ce = EG(scope); if (ce && ce->parent) { RETURN_STRINGL(ce->parent->name, ce->parent->name_length, 1); } else { RETURN_FALSE; } } if (Z_TYPE_P(arg) == IS_OBJECT) { if (Z_OBJ_HT_P(arg)->get_class_name && Z_OBJ_HT_P(arg)->get_class_name(arg, &name, &name_length, 1 TSRMLS_CC) == SUCCESS) { RETURN_STRINGL(name, name_length, 0); } else { ce = zend_get_class_entry(arg TSRMLS_CC); } } else if (Z_TYPE_P(arg) == IS_STRING) { zend_class_entry **pce; if (zend_lookup_class(Z_STRVAL_P(arg), Z_STRLEN_P(arg), &pce TSRMLS_CC) == SUCCESS) { ce = *pce; } } if (ce && ce->parent) { RETURN_STRINGL(ce->parent->name, ce->parent->name_length, 1); } else { RETURN_FALSE; } } /* }}} */ static void is_a_impl(INTERNAL_FUNCTION_PARAMETERS, zend_bool only_subclass) { zval *obj; char *class_name; int class_name_len; zend_class_entry *instance_ce; zend_class_entry **ce; zend_bool allow_string = only_subclass; zend_bool retval; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zs|b", &obj, &class_name, &class_name_len, &allow_string) == FAILURE) { return; } /* * allow_string - is_a default is no, is_subclass_of is yes. * if it's allowed, then the autoloader will be called if the class does not exist. * default behaviour is different, as 'is_a' used to be used to test mixed return values * and there is no easy way to deprecate this. */ if (allow_string && Z_TYPE_P(obj) == IS_STRING) { zend_class_entry **the_ce; if (zend_lookup_class(Z_STRVAL_P(obj), Z_STRLEN_P(obj), &the_ce TSRMLS_CC) == FAILURE) { RETURN_FALSE; } instance_ce = *the_ce; } else if (Z_TYPE_P(obj) == IS_OBJECT && HAS_CLASS_ENTRY(*obj)) { instance_ce = Z_OBJCE_P(obj); } else { RETURN_FALSE; } if (zend_lookup_class_ex(class_name, class_name_len, NULL, 0, &ce TSRMLS_CC) == FAILURE) { retval = 0; } else { if (only_subclass && instance_ce == *ce) { retval = 0; } else { retval = instanceof_function(instance_ce, *ce TSRMLS_CC); } } RETURN_BOOL(retval); } /* {{{ proto bool is_subclass_of(mixed object_or_string, string class_name [, bool allow_string=true]) Returns true if the object has this class as one of its parents */ ZEND_FUNCTION(is_subclass_of) { is_a_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto bool is_a(mixed object_or_string, string class_name [, bool allow_string=false]) Returns true if the first argument is an object and is this class or has this class as one of its parents, */ ZEND_FUNCTION(is_a) { is_a_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ add_class_vars */ static void add_class_vars(zend_class_entry *ce, int statics, zval *return_value TSRMLS_DC) { HashPosition pos; zend_property_info *prop_info; zval *prop, *prop_copy; char *key; uint key_len; ulong num_index; zend_hash_internal_pointer_reset_ex(&ce->properties_info, &pos); while (zend_hash_get_current_data_ex(&ce->properties_info, (void **) &prop_info, &pos) == SUCCESS) { zend_hash_get_current_key_ex(&ce->properties_info, &key, &key_len, &num_index, 0, &pos); zend_hash_move_forward_ex(&ce->properties_info, &pos); if (((prop_info->flags & ZEND_ACC_SHADOW) && prop_info->ce != EG(scope)) || ((prop_info->flags & ZEND_ACC_PROTECTED) && !zend_check_protected(prop_info->ce, EG(scope))) || ((prop_info->flags & ZEND_ACC_PRIVATE) && ce != EG(scope) && prop_info->ce != EG(scope))) { continue; } prop = NULL; if (prop_info->offset >= 0) { if (statics && (prop_info->flags & ZEND_ACC_STATIC) != 0) { prop = ce->default_static_members_table[prop_info->offset]; } else if (!statics && (prop_info->flags & ZEND_ACC_STATIC) == 0) { prop = ce->default_properties_table[prop_info->offset]; } } if (!prop) { continue; } /* copy: enforce read only access */ ALLOC_ZVAL(prop_copy); *prop_copy = *prop; zval_copy_ctor(prop_copy); INIT_PZVAL(prop_copy); /* this is necessary to make it able to work with default array * properties, returned to user */ if (Z_TYPE_P(prop_copy) == IS_CONSTANT_ARRAY || (Z_TYPE_P(prop_copy) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zval_update_constant(&prop_copy, 0 TSRMLS_CC); } add_assoc_zval(return_value, key, prop_copy); } } /* }}} */ /* {{{ proto array get_class_vars(string class_name) Returns an array of default properties of the class. */ ZEND_FUNCTION(get_class_vars) { char *class_name; int class_name_len; zend_class_entry **pce; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &class_name, &class_name_len) == FAILURE) { return; } if (zend_lookup_class(class_name, class_name_len, &pce TSRMLS_CC) == FAILURE) { RETURN_FALSE; } else { array_init(return_value); zend_update_class_constants(*pce TSRMLS_CC); add_class_vars(*pce, 0, return_value TSRMLS_CC); add_class_vars(*pce, 1, return_value TSRMLS_CC); } } /* }}} */ /* {{{ proto array get_object_vars(object obj) Returns an array of object properties */ ZEND_FUNCTION(get_object_vars) { zval *obj; zval **value; HashTable *properties; HashPosition pos; char *key; const char *prop_name, *class_name; uint key_len; ulong num_index; zend_object *zobj; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "o", &obj) == FAILURE) { return; } if (Z_OBJ_HT_P(obj)->get_properties == NULL) { RETURN_FALSE; } properties = Z_OBJ_HT_P(obj)->get_properties(obj TSRMLS_CC); if (properties == NULL) { RETURN_FALSE; } zobj = zend_objects_get_address(obj TSRMLS_CC); array_init(return_value); zend_hash_internal_pointer_reset_ex(properties, &pos); while (zend_hash_get_current_data_ex(properties, (void **) &value, &pos) == SUCCESS) { if (zend_hash_get_current_key_ex(properties, &key, &key_len, &num_index, 0, &pos) == HASH_KEY_IS_STRING) { if (zend_check_property_access(zobj, key, key_len-1 TSRMLS_CC) == SUCCESS) { zend_unmangle_property_name(key, key_len-1, &class_name, &prop_name); /* Not separating references */ Z_ADDREF_PP(value); add_assoc_zval_ex(return_value, prop_name, strlen(prop_name)+1, *value); } } zend_hash_move_forward_ex(properties, &pos); } } /* }}} */ /* {{{ proto array get_class_methods(mixed class) Returns an array of method names for class or class instance. */ ZEND_FUNCTION(get_class_methods) { zval *klass; zval *method_name; zend_class_entry *ce = NULL, **pce; HashPosition pos; zend_function *mptr; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &klass) == FAILURE) { return; } if (Z_TYPE_P(klass) == IS_OBJECT) { /* TBI!! new object handlers */ if (!HAS_CLASS_ENTRY(*klass)) { RETURN_FALSE; } ce = Z_OBJCE_P(klass); } else if (Z_TYPE_P(klass) == IS_STRING) { if (zend_lookup_class(Z_STRVAL_P(klass), Z_STRLEN_P(klass), &pce TSRMLS_CC) == SUCCESS) { ce = *pce; } } if (!ce) { RETURN_NULL(); } array_init(return_value); zend_hash_internal_pointer_reset_ex(&ce->function_table, &pos); while (zend_hash_get_current_data_ex(&ce->function_table, (void **) &mptr, &pos) == SUCCESS) { if ((mptr->common.fn_flags & ZEND_ACC_PUBLIC) || (EG(scope) && (((mptr->common.fn_flags & ZEND_ACC_PROTECTED) && zend_check_protected(mptr->common.scope, EG(scope))) || ((mptr->common.fn_flags & ZEND_ACC_PRIVATE) && EG(scope) == mptr->common.scope)))) { char *key; uint key_len; ulong num_index; uint len = strlen(mptr->common.function_name); /* Do not display old-style inherited constructors */ if ((mptr->common.fn_flags & ZEND_ACC_CTOR) == 0 || mptr->common.scope == ce || zend_hash_get_current_key_ex(&ce->function_table, &key, &key_len, &num_index, 0, &pos) != HASH_KEY_IS_STRING || zend_binary_strcasecmp(key, key_len-1, mptr->common.function_name, len) == 0) { MAKE_STD_ZVAL(method_name); ZVAL_STRINGL(method_name, mptr->common.function_name, len, 1); zend_hash_next_index_insert(return_value->value.ht, &method_name, sizeof(zval *), NULL); } } zend_hash_move_forward_ex(&ce->function_table, &pos); } } /* }}} */ /* {{{ proto bool method_exists(object object, string method) Checks if the class method exists */ ZEND_FUNCTION(method_exists) { zval *klass; char *method_name; int method_len; char *lcname; zend_class_entry * ce, **pce; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zs", &klass, &method_name, &method_len) == FAILURE) { return; } if (Z_TYPE_P(klass) == IS_OBJECT) { ce = Z_OBJCE_P(klass); } else if (Z_TYPE_P(klass) == IS_STRING) { if (zend_lookup_class(Z_STRVAL_P(klass), Z_STRLEN_P(klass), &pce TSRMLS_CC) == FAILURE) { RETURN_FALSE; } ce = *pce; } else { RETURN_FALSE; } lcname = zend_str_tolower_dup(method_name, method_len); if (zend_hash_exists(&ce->function_table, lcname, method_len+1)) { efree(lcname); RETURN_TRUE; } else { union _zend_function *func = NULL; if (Z_TYPE_P(klass) == IS_OBJECT && Z_OBJ_HT_P(klass)->get_method != NULL && (func = Z_OBJ_HT_P(klass)->get_method(&klass, method_name, method_len, NULL TSRMLS_CC)) != NULL ) { if (func->type == ZEND_INTERNAL_FUNCTION && (func->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) != 0 ) { /* Returns true to the fake Closure's __invoke */ RETVAL_BOOL((func->common.scope == zend_ce_closure && (method_len == sizeof(ZEND_INVOKE_FUNC_NAME)-1) && memcmp(lcname, ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME)-1) == 0) ? 1 : 0); efree(lcname); efree((char*)((zend_internal_function*)func)->function_name); efree(func); return; } efree(lcname); RETURN_TRUE; } } efree(lcname); RETURN_FALSE; } /* }}} */ /* {{{ proto bool property_exists(mixed object_or_class, string property_name) Checks if the object or class has a property */ ZEND_FUNCTION(property_exists) { zval *object; char *property; int property_len; zend_class_entry *ce, **pce; zend_property_info *property_info; zval property_z; ulong h; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zs", &object, &property, &property_len) == FAILURE) { return; } if (property_len == 0) { RETURN_FALSE; } if (Z_TYPE_P(object) == IS_STRING) { if (zend_lookup_class(Z_STRVAL_P(object), Z_STRLEN_P(object), &pce TSRMLS_CC) == FAILURE) { RETURN_FALSE; } ce = *pce; } else if (Z_TYPE_P(object) == IS_OBJECT) { ce = Z_OBJCE_P(object); } else { zend_error(E_WARNING, "First parameter must either be an object or the name of an existing class"); RETURN_NULL(); } h = zend_get_hash_value(property, property_len+1); if (zend_hash_quick_find(&ce->properties_info, property, property_len+1, h, (void **) &property_info) == SUCCESS && (property_info->flags & ZEND_ACC_SHADOW) == 0) { RETURN_TRUE; } ZVAL_STRINGL(&property_z, property, property_len, 0); if (Z_TYPE_P(object) == IS_OBJECT && Z_OBJ_HANDLER_P(object, has_property) && Z_OBJ_HANDLER_P(object, has_property)(object, &property_z, 2, 0 TSRMLS_CC)) { RETURN_TRUE; } RETURN_FALSE; } /* }}} */ /* {{{ proto bool class_exists(string classname [, bool autoload]) Checks if the class exists */ ZEND_FUNCTION(class_exists) { char *class_name, *lc_name; zend_class_entry **ce; int class_name_len; int found; zend_bool autoload = 1; ALLOCA_FLAG(use_heap) if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|b", &class_name, &class_name_len, &autoload) == FAILURE) { return; } if (!autoload) { char *name; int len; lc_name = do_alloca(class_name_len + 1, use_heap); zend_str_tolower_copy(lc_name, class_name, class_name_len); /* Ignore leading "\" */ name = lc_name; len = class_name_len; if (lc_name[0] == '\\') { name = &lc_name[1]; len--; } found = zend_hash_find(EG(class_table), name, len+1, (void **) &ce); free_alloca(lc_name, use_heap); RETURN_BOOL(found == SUCCESS && !(((*ce)->ce_flags & (ZEND_ACC_INTERFACE | ZEND_ACC_TRAIT)) > ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)); } if (zend_lookup_class(class_name, class_name_len, &ce TSRMLS_CC) == SUCCESS) { RETURN_BOOL(((*ce)->ce_flags & (ZEND_ACC_INTERFACE | (ZEND_ACC_TRAIT - ZEND_ACC_EXPLICIT_ABSTRACT_CLASS))) == 0); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool interface_exists(string classname [, bool autoload]) Checks if the class exists */ ZEND_FUNCTION(interface_exists) { char *iface_name, *lc_name; zend_class_entry **ce; int iface_name_len; int found; zend_bool autoload = 1; ALLOCA_FLAG(use_heap) if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|b", &iface_name, &iface_name_len, &autoload) == FAILURE) { return; } if (!autoload) { char *name; int len; lc_name = do_alloca(iface_name_len + 1, use_heap); zend_str_tolower_copy(lc_name, iface_name, iface_name_len); /* Ignore leading "\" */ name = lc_name; len = iface_name_len; if (lc_name[0] == '\\') { name = &lc_name[1]; len--; } found = zend_hash_find(EG(class_table), name, len+1, (void **) &ce); free_alloca(lc_name, use_heap); RETURN_BOOL(found == SUCCESS && (*ce)->ce_flags & ZEND_ACC_INTERFACE); } if (zend_lookup_class(iface_name, iface_name_len, &ce TSRMLS_CC) == SUCCESS) { RETURN_BOOL(((*ce)->ce_flags & ZEND_ACC_INTERFACE) > 0); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool trait_exists(string traitname [, bool autoload]) Checks if the trait exists */ ZEND_FUNCTION(trait_exists) { char *trait_name, *lc_name; zend_class_entry **ce; int trait_name_len; int found; zend_bool autoload = 1; ALLOCA_FLAG(use_heap) if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|b", &trait_name, &trait_name_len, &autoload) == FAILURE) { return; } if (!autoload) { char *name; int len; lc_name = do_alloca(trait_name_len + 1, use_heap); zend_str_tolower_copy(lc_name, trait_name, trait_name_len); /* Ignore leading "\" */ name = lc_name; len = trait_name_len; if (lc_name[0] == '\\') { name = &lc_name[1]; len--; } found = zend_hash_find(EG(class_table), name, len+1, (void **) &ce); free_alloca(lc_name, use_heap); RETURN_BOOL(found == SUCCESS && (((*ce)->ce_flags & ZEND_ACC_TRAIT) > ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)); } if (zend_lookup_class(trait_name, trait_name_len, &ce TSRMLS_CC) == SUCCESS) { RETURN_BOOL(((*ce)->ce_flags & ZEND_ACC_TRAIT) > ZEND_ACC_EXPLICIT_ABSTRACT_CLASS); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool function_exists(string function_name) Checks if the function exists */ ZEND_FUNCTION(function_exists) { char *name; int name_len; zend_function *func; char *lcname; zend_bool retval; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) { return; } lcname = zend_str_tolower_dup(name, name_len); /* Ignore leading "\" */ name = lcname; if (lcname[0] == '\\') { name = &lcname[1]; name_len--; } retval = (zend_hash_find(EG(function_table), name, name_len+1, (void **)&func) == SUCCESS); efree(lcname); /* * A bit of a hack, but not a bad one: we see if the handler of the function * is actually one that displays "function is disabled" message. */ if (retval && func->type == ZEND_INTERNAL_FUNCTION && func->internal_function.handler == zif_display_disabled_function) { retval = 0; } RETURN_BOOL(retval); } /* }}} */ /* {{{ proto bool class_alias(string user_class_name , string alias_name [, bool autoload]) Creates an alias for user defined class */ ZEND_FUNCTION(class_alias) { char *class_name, *lc_name, *alias_name; zend_class_entry **ce; int class_name_len, alias_name_len; int found; zend_bool autoload = 1; ALLOCA_FLAG(use_heap) if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|b", &class_name, &class_name_len, &alias_name, &alias_name_len, &autoload) == FAILURE) { return; } if (!autoload) { lc_name = do_alloca(class_name_len + 1, use_heap); zend_str_tolower_copy(lc_name, class_name, class_name_len); found = zend_hash_find(EG(class_table), lc_name, class_name_len+1, (void **) &ce); free_alloca(lc_name, use_heap); } else { found = zend_lookup_class(class_name, class_name_len, &ce TSRMLS_CC); } if (found == SUCCESS) { if ((*ce)->type == ZEND_USER_CLASS) { if (zend_register_class_alias_ex(alias_name, alias_name_len, *ce TSRMLS_CC) == SUCCESS) { RETURN_TRUE; } else { zend_error(E_WARNING, "Cannot redeclare class %s", alias_name); RETURN_FALSE; } } else { zend_error(E_WARNING, "First argument of class_alias() must be a name of user defined class"); RETURN_FALSE; } } else { zend_error(E_WARNING, "Class '%s' not found", class_name); RETURN_FALSE; } } /* }}} */ #if ZEND_DEBUG /* {{{ proto void leak(int num_bytes=3) Cause an intentional memory leak, for testing/debugging purposes */ ZEND_FUNCTION(leak) { long leakbytes=3; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &leakbytes) == FAILURE) { return; } emalloc(leakbytes); } /* }}} */ /* {{{ proto leak_variable(mixed variable [, bool leak_data]) */ ZEND_FUNCTION(leak_variable) { zval *zv; zend_bool leak_data = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|b", &zv, &leak_data) == FAILURE) { return; } if (!leak_data) { zval_add_ref(&zv); } else if (Z_TYPE_P(zv) == IS_RESOURCE) { zend_list_addref(Z_RESVAL_P(zv)); } else if (Z_TYPE_P(zv) == IS_OBJECT) { Z_OBJ_HANDLER_P(zv, add_ref)(zv TSRMLS_CC); } else { zend_error(E_WARNING, "Leaking non-zval data is only applicable to resources and objects"); } } /* }}} */ #ifdef ZEND_TEST_EXCEPTIONS ZEND_FUNCTION(crash) { char *nowhere=NULL; memcpy(nowhere, "something", sizeof("something")); } #endif #endif /* ZEND_DEBUG */ /* {{{ proto array get_included_files(void) Returns an array with the file names that were include_once()'d */ ZEND_FUNCTION(get_included_files) { char *entry; if (zend_parse_parameters_none() == FAILURE) { return; } array_init(return_value); zend_hash_internal_pointer_reset(&EG(included_files)); while (zend_hash_get_current_key(&EG(included_files), &entry, NULL, 1) == HASH_KEY_IS_STRING) { add_next_index_string(return_value, entry, 0); zend_hash_move_forward(&EG(included_files)); } } /* }}} */ /* {{{ proto void trigger_error(string message [, int error_type]) Generates a user-level error/warning/notice message */ ZEND_FUNCTION(trigger_error) { long error_type = E_USER_NOTICE; char *message; int message_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &message, &message_len, &error_type) == FAILURE) { return; } switch (error_type) { case E_USER_ERROR: case E_USER_WARNING: case E_USER_NOTICE: case E_USER_DEPRECATED: break; default: zend_error(E_WARNING, "Invalid error type specified"); RETURN_FALSE; break; } zend_error((int)error_type, "%s", message); RETURN_TRUE; } /* }}} */ /* {{{ proto string set_error_handler(string error_handler [, int error_types]) Sets a user-defined error handler function. Returns the previously defined error handler, or false on error */ ZEND_FUNCTION(set_error_handler) { zval *error_handler; zend_bool had_orig_error_handler=0; char *error_handler_name = NULL; long error_type = E_ALL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|l", &error_handler, &error_type) == FAILURE) { return; } if (!zend_is_callable(error_handler, 0, &error_handler_name TSRMLS_CC)) { zend_error(E_WARNING, "%s() expects the argument (%s) to be a valid callback", get_active_function_name(TSRMLS_C), error_handler_name?error_handler_name:"unknown"); efree(error_handler_name); return; } efree(error_handler_name); if (EG(user_error_handler)) { had_orig_error_handler = 1; *return_value = *EG(user_error_handler); zval_copy_ctor(return_value); INIT_PZVAL(return_value); zend_stack_push(&EG(user_error_handlers_error_reporting), &EG(user_error_handler_error_reporting), sizeof(EG(user_error_handler_error_reporting))); zend_ptr_stack_push(&EG(user_error_handlers), EG(user_error_handler)); } ALLOC_ZVAL(EG(user_error_handler)); if (!zend_is_true(error_handler)) { /* unset user-defined handler */ FREE_ZVAL(EG(user_error_handler)); EG(user_error_handler) = NULL; RETURN_TRUE; } EG(user_error_handler_error_reporting) = (int)error_type; *EG(user_error_handler) = *error_handler; zval_copy_ctor(EG(user_error_handler)); INIT_PZVAL(EG(user_error_handler)); if (!had_orig_error_handler) { RETURN_NULL(); } } /* }}} */ /* {{{ proto void restore_error_handler(void) Restores the previously defined error handler function */ ZEND_FUNCTION(restore_error_handler) { if (EG(user_error_handler)) { zval *zeh = EG(user_error_handler); EG(user_error_handler) = NULL; zval_ptr_dtor(&zeh); } if (zend_ptr_stack_num_elements(&EG(user_error_handlers))==0) { EG(user_error_handler) = NULL; } else { EG(user_error_handler_error_reporting) = zend_stack_int_top(&EG(user_error_handlers_error_reporting)); zend_stack_del_top(&EG(user_error_handlers_error_reporting)); EG(user_error_handler) = zend_ptr_stack_pop(&EG(user_error_handlers)); } RETURN_TRUE; } /* }}} */ /* {{{ proto string set_exception_handler(callable exception_handler) Sets a user-defined exception handler function. Returns the previously defined exception handler, or false on error */ ZEND_FUNCTION(set_exception_handler) { zval *exception_handler; char *exception_handler_name = NULL; zend_bool had_orig_exception_handler=0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &exception_handler) == FAILURE) { return; } if (Z_TYPE_P(exception_handler) != IS_NULL) { /* NULL == unset */ if (!zend_is_callable(exception_handler, 0, &exception_handler_name TSRMLS_CC)) { zend_error(E_WARNING, "%s() expects the argument (%s) to be a valid callback", get_active_function_name(TSRMLS_C), exception_handler_name?exception_handler_name:"unknown"); efree(exception_handler_name); return; } efree(exception_handler_name); } if (EG(user_exception_handler)) { had_orig_exception_handler = 1; *return_value = *EG(user_exception_handler); zval_copy_ctor(return_value); zend_ptr_stack_push(&EG(user_exception_handlers), EG(user_exception_handler)); } ALLOC_ZVAL(EG(user_exception_handler)); if (Z_TYPE_P(exception_handler) == IS_NULL) { /* unset user-defined handler */ FREE_ZVAL(EG(user_exception_handler)); EG(user_exception_handler) = NULL; RETURN_TRUE; } *EG(user_exception_handler) = *exception_handler; zval_copy_ctor(EG(user_exception_handler)); if (!had_orig_exception_handler) { RETURN_NULL(); } } /* }}} */ /* {{{ proto void restore_exception_handler(void) Restores the previously defined exception handler function */ ZEND_FUNCTION(restore_exception_handler) { if (EG(user_exception_handler)) { zval_ptr_dtor(&EG(user_exception_handler)); } if (zend_ptr_stack_num_elements(&EG(user_exception_handlers))==0) { EG(user_exception_handler) = NULL; } else { EG(user_exception_handler) = zend_ptr_stack_pop(&EG(user_exception_handlers)); } RETURN_TRUE; } /* }}} */ static int copy_class_or_interface_name(zend_class_entry **pce TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) { zval *array = va_arg(args, zval *); zend_uint mask = va_arg(args, zend_uint); zend_uint comply = va_arg(args, zend_uint); zend_uint comply_mask = (comply)? mask:0; zend_class_entry *ce = *pce; if ((hash_key->nKeyLength==0 || hash_key->arKey[0]!=0) && (comply_mask == (ce->ce_flags & mask))) { add_next_index_stringl(array, ce->name, ce->name_length, 1); } return ZEND_HASH_APPLY_KEEP; } /* {{{ proto array get_declared_traits() Returns an array of all declared traits. */ ZEND_FUNCTION(get_declared_traits) { zend_uint mask = ZEND_ACC_TRAIT; zend_uint comply = 1; if (zend_parse_parameters_none() == FAILURE) { return; } array_init(return_value); zend_hash_apply_with_arguments(EG(class_table) TSRMLS_CC, (apply_func_args_t) copy_class_or_interface_name, 3, return_value, mask, comply); } /* }}} */ /* {{{ proto array get_declared_classes() Returns an array of all declared classes. */ ZEND_FUNCTION(get_declared_classes) { zend_uint mask = ZEND_ACC_INTERFACE | (ZEND_ACC_TRAIT & ~ZEND_ACC_EXPLICIT_ABSTRACT_CLASS); zend_uint comply = 0; if (zend_parse_parameters_none() == FAILURE) { return; } array_init(return_value); zend_hash_apply_with_arguments(EG(class_table) TSRMLS_CC, (apply_func_args_t) copy_class_or_interface_name, 3, return_value, mask, comply); } /* }}} */ /* {{{ proto array get_declared_interfaces() Returns an array of all declared interfaces. */ ZEND_FUNCTION(get_declared_interfaces) { zend_uint mask = ZEND_ACC_INTERFACE; zend_uint comply = 1; if (zend_parse_parameters_none() == FAILURE) { return; } array_init(return_value); zend_hash_apply_with_arguments(EG(class_table) TSRMLS_CC, (apply_func_args_t) copy_class_or_interface_name, 3, return_value, mask, comply); } /* }}} */ static int copy_function_name(zend_function *func TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) { zval *internal_ar = va_arg(args, zval *), *user_ar = va_arg(args, zval *); if (hash_key->nKeyLength == 0 || hash_key->arKey[0] == 0) { return 0; } if (func->type == ZEND_INTERNAL_FUNCTION) { add_next_index_stringl(internal_ar, hash_key->arKey, hash_key->nKeyLength-1, 1); } else if (func->type == ZEND_USER_FUNCTION) { add_next_index_stringl(user_ar, hash_key->arKey, hash_key->nKeyLength-1, 1); } return 0; } /* {{{ proto array get_defined_functions(void) Returns an array of all defined functions */ ZEND_FUNCTION(get_defined_functions) { zval *internal; zval *user; if (zend_parse_parameters_none() == FAILURE) { return; } MAKE_STD_ZVAL(internal); MAKE_STD_ZVAL(user); array_init(internal); array_init(user); array_init(return_value); zend_hash_apply_with_arguments(EG(function_table) TSRMLS_CC, (apply_func_args_t) copy_function_name, 2, internal, user); if (zend_hash_add(Z_ARRVAL_P(return_value), "internal", sizeof("internal"), (void **)&internal, sizeof(zval *), NULL) == FAILURE) { zval_ptr_dtor(&internal); zval_ptr_dtor(&user); zval_dtor(return_value); zend_error(E_WARNING, "Cannot add internal functions to return value from get_defined_functions()"); RETURN_FALSE; } if (zend_hash_add(Z_ARRVAL_P(return_value), "user", sizeof("user"), (void **)&user, sizeof(zval *), NULL) == FAILURE) { zval_ptr_dtor(&user); zval_dtor(return_value); zend_error(E_WARNING, "Cannot add user functions to return value from get_defined_functions()"); RETURN_FALSE; } } /* }}} */ /* {{{ proto array get_defined_vars(void) Returns an associative array of names and values of all currently defined variable names (variables in the current scope) */ ZEND_FUNCTION(get_defined_vars) { if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } array_init_size(return_value, zend_hash_num_elements(EG(active_symbol_table))); zend_hash_copy(Z_ARRVAL_P(return_value), EG(active_symbol_table), (copy_ctor_func_t)zval_add_ref, NULL, sizeof(zval *)); } /* }}} */ #define LAMBDA_TEMP_FUNCNAME "__lambda_func" /* {{{ proto string create_function(string args, string code) Creates an anonymous function, and returns its name (funny, eh?) */ ZEND_FUNCTION(create_function) { char *eval_code, *function_name, *function_args, *function_code; int eval_code_length, function_name_length, function_args_len, function_code_len; int retval; char *eval_name; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &function_args, &function_args_len, &function_code, &function_code_len) == FAILURE) { return; } eval_code = (char *) emalloc(sizeof("function " LAMBDA_TEMP_FUNCNAME) +function_args_len +2 /* for the args parentheses */ +2 /* for the curly braces */ +function_code_len); eval_code_length = sizeof("function " LAMBDA_TEMP_FUNCNAME "(") - 1; memcpy(eval_code, "function " LAMBDA_TEMP_FUNCNAME "(", eval_code_length); memcpy(eval_code + eval_code_length, function_args, function_args_len); eval_code_length += function_args_len; eval_code[eval_code_length++] = ')'; eval_code[eval_code_length++] = '{'; memcpy(eval_code + eval_code_length, function_code, function_code_len); eval_code_length += function_code_len; eval_code[eval_code_length++] = '}'; eval_code[eval_code_length] = '\0'; eval_name = zend_make_compiled_string_description("runtime-created function" TSRMLS_CC); retval = zend_eval_stringl(eval_code, eval_code_length, NULL, eval_name TSRMLS_CC); efree(eval_code); efree(eval_name); if (retval==SUCCESS) { zend_function new_function, *func; if (zend_hash_find(EG(function_table), LAMBDA_TEMP_FUNCNAME, sizeof(LAMBDA_TEMP_FUNCNAME), (void **) &func)==FAILURE) { zend_error(E_ERROR, "Unexpected inconsistency in create_function()"); RETURN_FALSE; } new_function = *func; function_add_ref(&new_function); function_name = (char *) emalloc(sizeof("0lambda_")+MAX_LENGTH_OF_LONG); function_name[0] = '\0'; do { function_name_length = 1 + snprintf(function_name + 1, sizeof("lambda_")+MAX_LENGTH_OF_LONG, "lambda_%d", ++EG(lambda_count)); } while (zend_hash_add(EG(function_table), function_name, function_name_length+1, &new_function, sizeof(zend_function), NULL)==FAILURE); zend_hash_del(EG(function_table), LAMBDA_TEMP_FUNCNAME, sizeof(LAMBDA_TEMP_FUNCNAME)); RETURN_STRINGL(function_name, function_name_length, 0); } else { zend_hash_del(EG(function_table), LAMBDA_TEMP_FUNCNAME, sizeof(LAMBDA_TEMP_FUNCNAME)); RETURN_FALSE; } } /* }}} */ #if ZEND_DEBUG ZEND_FUNCTION(zend_test_func) { zval *arg1, *arg2; zend_get_parameters(ht, 2, &arg1, &arg2); } #ifdef ZTS ZEND_FUNCTION(zend_thread_id) { RETURN_LONG((long)tsrm_thread_id()); } #endif #endif /* {{{ proto string get_resource_type(resource res) Get the resource type name for a given resource */ ZEND_FUNCTION(get_resource_type) { const char *resource_type; zval *z_resource_type; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &z_resource_type) == FAILURE) { return; } resource_type = zend_rsrc_list_get_rsrc_type(Z_LVAL_P(z_resource_type) TSRMLS_CC); if (resource_type) { RETURN_STRING(resource_type, 1); } else { RETURN_STRING("Unknown", 1); } } /* }}} */ static int add_extension_info(zend_module_entry *module, void *arg TSRMLS_DC) { zval *name_array = (zval *)arg; add_next_index_string(name_array, module->name, 1); return 0; } static int add_zendext_info(zend_extension *ext, void *arg TSRMLS_DC) { zval *name_array = (zval *)arg; add_next_index_string(name_array, ext->name, 1); return 0; } static int add_constant_info(zend_constant *constant, void *arg TSRMLS_DC) { zval *name_array = (zval *)arg; zval *const_val; MAKE_STD_ZVAL(const_val); *const_val = constant->value; zval_copy_ctor(const_val); INIT_PZVAL(const_val); add_assoc_zval_ex(name_array, constant->name, constant->name_len, const_val); return 0; } /* {{{ proto array get_loaded_extensions([bool zend_extensions]) U Return an array containing names of loaded extensions */ ZEND_FUNCTION(get_loaded_extensions) { zend_bool zendext = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &zendext) == FAILURE) { return; } array_init(return_value); if (zendext) { zend_llist_apply_with_argument(&zend_extensions, (llist_apply_with_arg_func_t) add_zendext_info, return_value TSRMLS_CC); } else { zend_hash_apply_with_argument(&module_registry, (apply_func_arg_t) add_extension_info, return_value TSRMLS_CC); } } /* }}} */ /* {{{ proto array get_defined_constants([bool categorize]) Return an array containing the names and values of all defined constants */ ZEND_FUNCTION(get_defined_constants) { zend_bool categorize = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &categorize) == FAILURE) { return; } array_init(return_value); if (categorize) { HashPosition pos; zend_constant *val; int module_number; zval **modules; char **module_names; zend_module_entry *module; int i = 1; modules = ecalloc(zend_hash_num_elements(&module_registry) + 2, sizeof(zval *)); module_names = emalloc((zend_hash_num_elements(&module_registry) + 2) * sizeof(char *)); module_names[0] = "internal"; zend_hash_internal_pointer_reset_ex(&module_registry, &pos); while (zend_hash_get_current_data_ex(&module_registry, (void *) &module, &pos) != FAILURE) { module_names[module->module_number] = (char *)module->name; i++; zend_hash_move_forward_ex(&module_registry, &pos); } module_names[i] = "user"; zend_hash_internal_pointer_reset_ex(EG(zend_constants), &pos); while (zend_hash_get_current_data_ex(EG(zend_constants), (void **) &val, &pos) != FAILURE) { zval *const_val; if (val->module_number == PHP_USER_CONSTANT) { module_number = i; } else if (val->module_number > i || val->module_number < 0) { /* should not happen */ goto bad_module_id; } else { module_number = val->module_number; } if (!modules[module_number]) { MAKE_STD_ZVAL(modules[module_number]); array_init(modules[module_number]); add_assoc_zval(return_value, module_names[module_number], modules[module_number]); } MAKE_STD_ZVAL(const_val); *const_val = val->value; zval_copy_ctor(const_val); INIT_PZVAL(const_val); add_assoc_zval_ex(modules[module_number], val->name, val->name_len, const_val); bad_module_id: zend_hash_move_forward_ex(EG(zend_constants), &pos); } efree(module_names); efree(modules); } else { zend_hash_apply_with_argument(EG(zend_constants), (apply_func_arg_t) add_constant_info, return_value TSRMLS_CC); } } /* }}} */ static zval *debug_backtrace_get_args(void **curpos TSRMLS_DC) { void **p = curpos; zval *arg_array, **arg; int arg_count = (int)(zend_uintptr_t) *p; MAKE_STD_ZVAL(arg_array); array_init_size(arg_array, arg_count); p -= arg_count; while (--arg_count >= 0) { arg = (zval **) p++; if (*arg) { if (Z_TYPE_PP(arg) != IS_OBJECT) { SEPARATE_ZVAL_TO_MAKE_IS_REF(arg); } Z_ADDREF_PP(arg); add_next_index_zval(arg_array, *arg); } else { add_next_index_null(arg_array); } } return arg_array; } void debug_print_backtrace_args(zval *arg_array TSRMLS_DC) { zval **tmp; HashPosition iterator; int i = 0; zend_hash_internal_pointer_reset_ex(arg_array->value.ht, &iterator); while (zend_hash_get_current_data_ex(arg_array->value.ht, (void **) &tmp, &iterator) == SUCCESS) { if (i++) { ZEND_PUTS(", "); } zend_print_flat_zval_r(*tmp TSRMLS_CC); zend_hash_move_forward_ex(arg_array->value.ht, &iterator); } } /* {{{ proto void debug_print_backtrace([int options[, int limit]]) */ ZEND_FUNCTION(debug_print_backtrace) { zend_execute_data *ptr, *skip; int lineno, frameno = 0; const char *function_name; const char *filename; const char *class_name = NULL; char *call_type; const char *include_filename = NULL; zval *arg_array = NULL; int indent = 0; long options = 0; long limit = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|ll", &options, &limit) == FAILURE) { return; } ptr = EG(current_execute_data); /* skip debug_backtrace() */ ptr = ptr->prev_execute_data; while (ptr && (limit == 0 || frameno < limit)) { const char *free_class_name = NULL; frameno++; class_name = call_type = NULL; arg_array = NULL; skip = ptr; /* skip internal handler */ if (!skip->op_array && skip->prev_execute_data && skip->prev_execute_data->opline && skip->prev_execute_data->opline->opcode != ZEND_DO_FCALL && skip->prev_execute_data->opline->opcode != ZEND_DO_FCALL_BY_NAME && skip->prev_execute_data->opline->opcode != ZEND_INCLUDE_OR_EVAL) { skip = skip->prev_execute_data; } if (skip->op_array) { filename = skip->op_array->filename; lineno = skip->opline->lineno; } else { filename = NULL; lineno = 0; } function_name = ptr->function_state.function->common.function_name; if (function_name) { if (ptr->object) { if (ptr->function_state.function->common.scope) { class_name = ptr->function_state.function->common.scope->name; } else { zend_uint class_name_len; int dup; dup = zend_get_object_classname(ptr->object, &class_name, &class_name_len TSRMLS_CC); if(!dup) { free_class_name = class_name; } } call_type = "->"; } else if (ptr->function_state.function->common.scope) { class_name = ptr->function_state.function->common.scope->name; call_type = "::"; } else { class_name = NULL; call_type = NULL; } if ((! ptr->opline) || ((ptr->opline->opcode == ZEND_DO_FCALL_BY_NAME) || (ptr->opline->opcode == ZEND_DO_FCALL))) { if (ptr->function_state.arguments && (options & DEBUG_BACKTRACE_IGNORE_ARGS) == 0) { arg_array = debug_backtrace_get_args(ptr->function_state.arguments TSRMLS_CC); } } } else { /* i know this is kinda ugly, but i'm trying to avoid extra cycles in the main execution loop */ zend_bool build_filename_arg = 1; if (!ptr->opline || ptr->opline->opcode != ZEND_INCLUDE_OR_EVAL) { /* can happen when calling eval from a custom sapi */ function_name = "unknown"; build_filename_arg = 0; } else switch (ptr->opline->extended_value) { case ZEND_EVAL: function_name = "eval"; build_filename_arg = 0; break; case ZEND_INCLUDE: function_name = "include"; break; case ZEND_REQUIRE: function_name = "require"; break; case ZEND_INCLUDE_ONCE: function_name = "include_once"; break; case ZEND_REQUIRE_ONCE: function_name = "require_once"; break; default: /* this can actually happen if you use debug_backtrace() in your error_handler and * you're in the top-scope */ function_name = "unknown"; build_filename_arg = 0; break; } if (build_filename_arg && include_filename) { MAKE_STD_ZVAL(arg_array); array_init(arg_array); add_next_index_string(arg_array, (char*)include_filename, 1); } call_type = NULL; } zend_printf("#%-2d ", indent); if (class_name) { ZEND_PUTS(class_name); ZEND_PUTS(call_type); } zend_printf("%s(", function_name); if (arg_array) { debug_print_backtrace_args(arg_array TSRMLS_CC); zval_ptr_dtor(&arg_array); } if (filename) { zend_printf(") called at [%s:%d]\n", filename, lineno); } else { zend_execute_data *prev = skip->prev_execute_data; while (prev) { if (prev->function_state.function && prev->function_state.function->common.type != ZEND_USER_FUNCTION) { prev = NULL; break; } if (prev->op_array) { zend_printf(") called at [%s:%d]\n", prev->op_array->filename, prev->opline->lineno); break; } prev = prev->prev_execute_data; } if (!prev) { ZEND_PUTS(")\n"); } } include_filename = filename; ptr = skip->prev_execute_data; ++indent; if (free_class_name) { efree((char*)free_class_name); } } } /* }}} */ ZEND_API void zend_fetch_debug_backtrace(zval *return_value, int skip_last, int options, int limit TSRMLS_DC) { zend_execute_data *ptr, *skip; int lineno, frameno = 0; const char *function_name; const char *filename; const char *class_name; const char *include_filename = NULL; zval *stack_frame; ptr = EG(current_execute_data); /* skip "new Exception()" */ if (ptr && (skip_last == 0) && ptr->opline && (ptr->opline->opcode == ZEND_NEW)) { ptr = ptr->prev_execute_data; } /* skip debug_backtrace() */ if (skip_last-- && ptr) { ptr = ptr->prev_execute_data; } array_init(return_value); while (ptr && (limit == 0 || frameno < limit)) { frameno++; MAKE_STD_ZVAL(stack_frame); array_init(stack_frame); skip = ptr; /* skip internal handler */ if (!skip->op_array && skip->prev_execute_data && skip->prev_execute_data->opline && skip->prev_execute_data->opline->opcode != ZEND_DO_FCALL && skip->prev_execute_data->opline->opcode != ZEND_DO_FCALL_BY_NAME && skip->prev_execute_data->opline->opcode != ZEND_INCLUDE_OR_EVAL) { skip = skip->prev_execute_data; } if (skip->op_array) { filename = skip->op_array->filename; lineno = skip->opline->lineno; add_assoc_string_ex(stack_frame, "file", sizeof("file"), (char*)filename, 1); add_assoc_long_ex(stack_frame, "line", sizeof("line"), lineno); /* try to fetch args only if an FCALL was just made - elsewise we're in the middle of a function * and debug_baktrace() might have been called by the error_handler. in this case we don't * want to pop anything of the argument-stack */ } else { zend_execute_data *prev = skip->prev_execute_data; while (prev) { if (prev->function_state.function && prev->function_state.function->common.type != ZEND_USER_FUNCTION && !(prev->function_state.function->common.type == ZEND_INTERNAL_FUNCTION && (prev->function_state.function->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER))) { break; } if (prev->op_array) { add_assoc_string_ex(stack_frame, "file", sizeof("file"), (char*)prev->op_array->filename, 1); add_assoc_long_ex(stack_frame, "line", sizeof("line"), prev->opline->lineno); break; } prev = prev->prev_execute_data; } filename = NULL; } function_name = ptr->function_state.function->common.function_name; if (function_name) { add_assoc_string_ex(stack_frame, "function", sizeof("function"), (char*)function_name, 1); if (ptr->object && Z_TYPE_P(ptr->object) == IS_OBJECT) { if (ptr->function_state.function->common.scope) { add_assoc_string_ex(stack_frame, "class", sizeof("class"), (char*)ptr->function_state.function->common.scope->name, 1); } else { zend_uint class_name_len; int dup; dup = zend_get_object_classname(ptr->object, &class_name, &class_name_len TSRMLS_CC); add_assoc_string_ex(stack_frame, "class", sizeof("class"), (char*)class_name, dup); } if ((options & DEBUG_BACKTRACE_PROVIDE_OBJECT) != 0) { add_assoc_zval_ex(stack_frame, "object", sizeof("object"), ptr->object); Z_ADDREF_P(ptr->object); } add_assoc_string_ex(stack_frame, "type", sizeof("type"), "->", 1); } else if (ptr->function_state.function->common.scope) { add_assoc_string_ex(stack_frame, "class", sizeof("class"), (char*)ptr->function_state.function->common.scope->name, 1); add_assoc_string_ex(stack_frame, "type", sizeof("type"), "::", 1); } if ((options & DEBUG_BACKTRACE_IGNORE_ARGS) == 0 && ((! ptr->opline) || ((ptr->opline->opcode == ZEND_DO_FCALL_BY_NAME) || (ptr->opline->opcode == ZEND_DO_FCALL)))) { if (ptr->function_state.arguments) { add_assoc_zval_ex(stack_frame, "args", sizeof("args"), debug_backtrace_get_args(ptr->function_state.arguments TSRMLS_CC)); } } } else { /* i know this is kinda ugly, but i'm trying to avoid extra cycles in the main execution loop */ zend_bool build_filename_arg = 1; if (!ptr->opline || ptr->opline->opcode != ZEND_INCLUDE_OR_EVAL) { /* can happen when calling eval from a custom sapi */ function_name = "unknown"; build_filename_arg = 0; } else switch (ptr->opline->extended_value) { case ZEND_EVAL: function_name = "eval"; build_filename_arg = 0; break; case ZEND_INCLUDE: function_name = "include"; break; case ZEND_REQUIRE: function_name = "require"; break; case ZEND_INCLUDE_ONCE: function_name = "include_once"; break; case ZEND_REQUIRE_ONCE: function_name = "require_once"; break; default: /* this can actually happen if you use debug_backtrace() in your error_handler and * you're in the top-scope */ function_name = "unknown"; build_filename_arg = 0; break; } if (build_filename_arg && include_filename) { zval *arg_array; MAKE_STD_ZVAL(arg_array); array_init(arg_array); /* include_filename always points to the last filename of the last last called-fuction. if we have called include in the frame above - this is the file we have included. */ add_next_index_string(arg_array, (char*)include_filename, 1); add_assoc_zval_ex(stack_frame, "args", sizeof("args"), arg_array); } add_assoc_string_ex(stack_frame, "function", sizeof("function"), (char*)function_name, 1); } add_next_index_zval(return_value, stack_frame); include_filename = filename; ptr = skip->prev_execute_data; } } /* }}} */ /* {{{ proto array debug_backtrace([int options[, int limit]]) Return backtrace as array */ ZEND_FUNCTION(debug_backtrace) { long options = DEBUG_BACKTRACE_PROVIDE_OBJECT; long limit = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|ll", &options, &limit) == FAILURE) { return; } zend_fetch_debug_backtrace(return_value, 1, options, limit TSRMLS_CC); } /* }}} */ /* {{{ proto bool extension_loaded(string extension_name) Returns true if the named extension is loaded */ ZEND_FUNCTION(extension_loaded) { char *extension_name; int extension_name_len; char *lcname; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &extension_name, &extension_name_len) == FAILURE) { return; } lcname = zend_str_tolower_dup(extension_name, extension_name_len); if (zend_hash_exists(&module_registry, lcname, extension_name_len+1)) { RETVAL_TRUE; } else { RETVAL_FALSE; } efree(lcname); } /* }}} */ /* {{{ proto array get_extension_funcs(string extension_name) Returns an array with the names of functions belonging to the named extension */ ZEND_FUNCTION(get_extension_funcs) { char *extension_name; int extension_name_len; zend_module_entry *module; const zend_function_entry *func; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &extension_name, &extension_name_len) == FAILURE) { return; } if (strncasecmp(extension_name, "zend", sizeof("zend"))) { char *lcname = zend_str_tolower_dup(extension_name, extension_name_len); if (zend_hash_find(&module_registry, lcname, extension_name_len+1, (void**)&module) == FAILURE) { efree(lcname); RETURN_FALSE; } efree(lcname); if (!(func = module->functions)) { RETURN_FALSE; } } else { func = builtin_functions; } array_init(return_value); while (func->fname) { add_next_index_string(return_value, func->fname, 1); func++; } } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-11-08-c3e56a152c-3598185a74.c
manybugs_data_59
/* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library. * * Core Directory Tag Support. */ #include "tiffiop.h" #include <stdlib.h> /* * NOTE: THIS ARRAY IS ASSUMED TO BE SORTED BY TAG. * * NOTE: The second field (field_readcount) and third field (field_writecount) * sometimes use the values TIFF_VARIABLE (-1), TIFF_VARIABLE2 (-3) * and TIFFTAG_SPP (-2). The macros should be used but would throw off * the formatting of the code, so please interprete the -1, -2 and -3 * values accordingly. */ static const TIFFFieldArray tiffFieldArray; static const TIFFFieldArray exifFieldArray; static const TIFFField tiffFields[] = { { TIFFTAG_SUBFILETYPE, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_SUBFILETYPE, 1, 0, "SubfileType", NULL }, { TIFFTAG_OSUBFILETYPE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_SUBFILETYPE, 1, 0, "OldSubfileType", NULL }, { TIFFTAG_IMAGEWIDTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_IMAGEDIMENSIONS, 0, 0, "ImageWidth", NULL }, { TIFFTAG_IMAGELENGTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_IMAGEDIMENSIONS, 1, 0, "ImageLength", NULL }, { TIFFTAG_BITSPERSAMPLE, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_BITSPERSAMPLE, 0, 0, "BitsPerSample", NULL }, { TIFFTAG_COMPRESSION, -1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_COMPRESSION, 0, 0, "Compression", NULL }, { TIFFTAG_PHOTOMETRIC, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_PHOTOMETRIC, 0, 0, "PhotometricInterpretation", NULL }, { TIFFTAG_THRESHHOLDING, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_THRESHHOLDING, 1, 0, "Threshholding", NULL }, { TIFFTAG_CELLWIDTH, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 1, 0, "CellWidth", NULL }, { TIFFTAG_CELLLENGTH, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 1, 0, "CellLength", NULL }, { TIFFTAG_FILLORDER, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_FILLORDER, 0, 0, "FillOrder", NULL }, { TIFFTAG_DOCUMENTNAME, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "DocumentName", NULL }, { TIFFTAG_IMAGEDESCRIPTION, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ImageDescription", NULL }, { TIFFTAG_MAKE, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Make", NULL }, { TIFFTAG_MODEL, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Model", NULL }, { TIFFTAG_STRIPOFFSETS, -1, -1, TIFF_LONG8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_STRIPOFFSETS, 0, 0, "StripOffsets", NULL }, { TIFFTAG_ORIENTATION, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_ORIENTATION, 0, 0, "Orientation", NULL }, { TIFFTAG_SAMPLESPERPIXEL, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_SAMPLESPERPIXEL, 0, 0, "SamplesPerPixel", NULL }, { TIFFTAG_ROWSPERSTRIP, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_ROWSPERSTRIP, 0, 0, "RowsPerStrip", NULL }, { TIFFTAG_STRIPBYTECOUNTS, -1, -1, TIFF_LONG8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_STRIPBYTECOUNTS, 0, 0, "StripByteCounts", NULL }, { TIFFTAG_MINSAMPLEVALUE, -2, -1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_MINSAMPLEVALUE, 1, 0, "MinSampleValue", NULL }, { TIFFTAG_MAXSAMPLEVALUE, -2, -1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_MAXSAMPLEVALUE, 1, 0, "MaxSampleValue", NULL }, { TIFFTAG_XRESOLUTION, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_RESOLUTION, 1, 0, "XResolution", NULL }, { TIFFTAG_YRESOLUTION, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_RESOLUTION, 1, 0, "YResolution", NULL }, { TIFFTAG_PLANARCONFIG, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_PLANARCONFIG, 0, 0, "PlanarConfiguration", NULL }, { TIFFTAG_PAGENAME, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "PageName", NULL }, { TIFFTAG_XPOSITION, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_POSITION, 1, 0, "XPosition", NULL }, { TIFFTAG_YPOSITION, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_POSITION, 1, 0, "YPosition", NULL }, { TIFFTAG_FREEOFFSETS, -1, -1, TIFF_LONG8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 0, 0, "FreeOffsets", NULL }, { TIFFTAG_FREEBYTECOUNTS, -1, -1, TIFF_LONG8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 0, 0, "FreeByteCounts", NULL }, { TIFFTAG_GRAYRESPONSEUNIT, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 1, 0, "GrayResponseUnit", NULL }, { TIFFTAG_GRAYRESPONSECURVE, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 1, 0, "GrayResponseCurve", NULL }, { TIFFTAG_RESOLUTIONUNIT, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_RESOLUTIONUNIT, 1, 0, "ResolutionUnit", NULL }, { TIFFTAG_PAGENUMBER, 2, 2, TIFF_SHORT, 0, TIFF_SETGET_UINT16_PAIR, TIFF_SETGET_UNDEFINED, FIELD_PAGENUMBER, 1, 0, "PageNumber", NULL }, { TIFFTAG_COLORRESPONSEUNIT, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 1, 0, "ColorResponseUnit", NULL }, { TIFFTAG_TRANSFERFUNCTION, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_OTHER, TIFF_SETGET_UNDEFINED, FIELD_TRANSFERFUNCTION, 1, 0, "TransferFunction", NULL }, { TIFFTAG_SOFTWARE, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Software", NULL }, { TIFFTAG_DATETIME, 20, 20, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "DateTime", NULL }, { TIFFTAG_ARTIST, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Artist", NULL }, { TIFFTAG_HOSTCOMPUTER, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "HostComputer", NULL }, { TIFFTAG_WHITEPOINT, 2, 2, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "WhitePoint", NULL }, { TIFFTAG_PRIMARYCHROMATICITIES, 6, 6, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "PrimaryChromaticities", NULL }, { TIFFTAG_COLORMAP, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_OTHER, TIFF_SETGET_UNDEFINED, FIELD_COLORMAP, 1, 0, "ColorMap", NULL }, { TIFFTAG_HALFTONEHINTS, 2, 2, TIFF_SHORT, 0, TIFF_SETGET_UINT16_PAIR, TIFF_SETGET_UNDEFINED, FIELD_HALFTONEHINTS, 1, 0, "HalftoneHints", NULL }, { TIFFTAG_TILEWIDTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_TILEDIMENSIONS, 0, 0, "TileWidth", NULL }, { TIFFTAG_TILELENGTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_TILEDIMENSIONS, 0, 0, "TileLength", NULL }, { TIFFTAG_TILEOFFSETS, -1, 1, TIFF_LONG8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_STRIPOFFSETS, 0, 0, "TileOffsets", NULL }, { TIFFTAG_TILEBYTECOUNTS, -1, 1, TIFF_LONG8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_STRIPBYTECOUNTS, 0, 0, "TileByteCounts", NULL }, { TIFFTAG_SUBIFD, -1, -1, TIFF_IFD8, 0, TIFF_SETGET_C16_IFD8, TIFF_SETGET_UNDEFINED, FIELD_SUBIFD, 1, 1, "SubIFD", &tiffFieldArray }, { TIFFTAG_INKSET, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "InkSet", NULL }, { TIFFTAG_INKNAMES, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_C16_ASCII, TIFF_SETGET_UNDEFINED, FIELD_INKNAMES, 1, 1, "InkNames", NULL }, { TIFFTAG_NUMBEROFINKS, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "NumberOfInks", NULL }, { TIFFTAG_DOTRANGE, 2, 2, TIFF_SHORT, 0, TIFF_SETGET_UINT16_PAIR, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "DotRange", NULL }, { TIFFTAG_TARGETPRINTER, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "TargetPrinter", NULL }, { TIFFTAG_EXTRASAMPLES, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_C16_UINT16, TIFF_SETGET_UNDEFINED, FIELD_EXTRASAMPLES, 0, 1, "ExtraSamples", NULL }, { TIFFTAG_SAMPLEFORMAT, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_SAMPLEFORMAT, 0, 0, "SampleFormat", NULL }, { TIFFTAG_SMINSAMPLEVALUE, -2, -1, TIFF_ANY, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_SMINSAMPLEVALUE, 1, 0, "SMinSampleValue", NULL }, { TIFFTAG_SMAXSAMPLEVALUE, -2, -1, TIFF_ANY, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_SMAXSAMPLEVALUE, 1, 0, "SMaxSampleValue", NULL }, { TIFFTAG_CLIPPATH, -1, -3, TIFF_BYTE, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ClipPath", NULL }, { TIFFTAG_XCLIPPATHUNITS, 1, 1, TIFF_SLONG, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "XClipPathUnits", NULL }, { TIFFTAG_XCLIPPATHUNITS, 1, 1, TIFF_SBYTE, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "XClipPathUnits", NULL }, { TIFFTAG_YCLIPPATHUNITS, 1, 1, TIFF_SLONG, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "YClipPathUnits", NULL }, { TIFFTAG_YCBCRCOEFFICIENTS, 3, 3, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "YCbCrCoefficients", NULL }, { TIFFTAG_YCBCRSUBSAMPLING, 2, 2, TIFF_SHORT, 0, TIFF_SETGET_UINT16_PAIR, TIFF_SETGET_UNDEFINED, FIELD_YCBCRSUBSAMPLING, 0, 0, "YCbCrSubsampling", NULL }, { TIFFTAG_YCBCRPOSITIONING, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_YCBCRPOSITIONING, 0, 0, "YCbCrPositioning", NULL }, { TIFFTAG_REFERENCEBLACKWHITE, 6, 6, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ReferenceBlackWhite", NULL }, { TIFFTAG_XMLPACKET, -3, -3, TIFF_BYTE, 0, TIFF_SETGET_C32_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "XMLPacket", NULL }, /* begin SGI tags */ { TIFFTAG_MATTEING, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_EXTRASAMPLES, 0, 0, "Matteing", NULL }, { TIFFTAG_DATATYPE, -2, -1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_SAMPLEFORMAT, 0, 0, "DataType", NULL }, { TIFFTAG_IMAGEDEPTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_IMAGEDEPTH, 0, 0, "ImageDepth", NULL }, { TIFFTAG_TILEDEPTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_TILEDEPTH, 0, 0, "TileDepth", NULL }, /* end SGI tags */ /* begin Pixar tags */ { TIFFTAG_PIXAR_IMAGEFULLWIDTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ImageFullWidth", NULL }, { TIFFTAG_PIXAR_IMAGEFULLLENGTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ImageFullLength", NULL }, { TIFFTAG_PIXAR_TEXTUREFORMAT, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "TextureFormat", NULL }, { TIFFTAG_PIXAR_WRAPMODES, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "TextureWrapModes", NULL }, { TIFFTAG_PIXAR_FOVCOT, 1, 1, TIFF_FLOAT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FieldOfViewCotangent", NULL }, { TIFFTAG_PIXAR_MATRIX_WORLDTOSCREEN, 16, 16, TIFF_FLOAT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "MatrixWorldToScreen", NULL }, { TIFFTAG_PIXAR_MATRIX_WORLDTOCAMERA, 16, 16, TIFF_FLOAT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "MatrixWorldToCamera", NULL }, { TIFFTAG_COPYRIGHT, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Copyright", NULL }, /* end Pixar tags */ { TIFFTAG_RICHTIFFIPTC, -3, -3, TIFF_LONG, 0, TIFF_SETGET_C32_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "RichTIFFIPTC", NULL }, { TIFFTAG_PHOTOSHOP, -3, -3, TIFF_BYTE, 0, TIFF_SETGET_C32_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "Photoshop", NULL }, { TIFFTAG_EXIFIFD, 1, 1, TIFF_IFD8, 0, TIFF_SETGET_IFD8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "EXIFIFDOffset", &exifFieldArray }, { TIFFTAG_ICCPROFILE, -3, -3, TIFF_UNDEFINED, 0, TIFF_SETGET_C32_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ICC Profile", NULL }, { TIFFTAG_GPSIFD, 1, 1, TIFF_IFD8, 0, TIFF_SETGET_IFD8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "GPSIFDOffset", NULL }, { TIFFTAG_FAXRECVPARAMS, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UINT32, FIELD_CUSTOM, TRUE, FALSE, "FaxRecvParams", NULL }, { TIFFTAG_FAXSUBADDRESS, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_ASCII, FIELD_CUSTOM, TRUE, FALSE, "FaxSubAddress", NULL }, { TIFFTAG_FAXRECVTIME, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UINT32, FIELD_CUSTOM, TRUE, FALSE, "FaxRecvTime", NULL }, { TIFFTAG_FAXDCS, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_ASCII, FIELD_CUSTOM, TRUE, FALSE, "FaxDcs", NULL }, { TIFFTAG_STONITS, 1, 1, TIFF_DOUBLE, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "StoNits", NULL }, { TIFFTAG_INTEROPERABILITYIFD, 1, 1, TIFF_IFD8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "InteroperabilityIFDOffset", NULL }, /* begin DNG tags */ { TIFFTAG_DNGVERSION, 4, 4, TIFF_BYTE, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "DNGVersion", NULL }, { TIFFTAG_DNGBACKWARDVERSION, 4, 4, TIFF_BYTE, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "DNGBackwardVersion", NULL }, { TIFFTAG_UNIQUECAMERAMODEL, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "UniqueCameraModel", NULL }, { TIFFTAG_LOCALIZEDCAMERAMODEL, -1, -1, TIFF_BYTE, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "LocalizedCameraModel", NULL }, { TIFFTAG_CFAPLANECOLOR, -1, -1, TIFF_BYTE, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "CFAPlaneColor", NULL }, { TIFFTAG_CFALAYOUT, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "CFALayout", NULL }, { TIFFTAG_LINEARIZATIONTABLE, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_C16_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "LinearizationTable", NULL }, { TIFFTAG_BLACKLEVELREPEATDIM, 2, 2, TIFF_SHORT, 0, TIFF_SETGET_C0_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "BlackLevelRepeatDim", NULL }, { TIFFTAG_BLACKLEVEL, -1, -1, TIFF_RATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "BlackLevel", NULL }, { TIFFTAG_BLACKLEVELDELTAH, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "BlackLevelDeltaH", NULL }, { TIFFTAG_BLACKLEVELDELTAV, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "BlackLevelDeltaV", NULL }, { TIFFTAG_WHITELEVEL, -1, -1, TIFF_LONG, 0, TIFF_SETGET_C16_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "WhiteLevel", NULL }, { TIFFTAG_DEFAULTSCALE, 2, 2, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "DefaultScale", NULL }, { TIFFTAG_BESTQUALITYSCALE, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "BestQualityScale", NULL }, { TIFFTAG_DEFAULTCROPORIGIN, 2, 2, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "DefaultCropOrigin", NULL }, { TIFFTAG_DEFAULTCROPSIZE, 2, 2, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "DefaultCropSize", NULL }, { TIFFTAG_COLORMATRIX1, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ColorMatrix1", NULL }, { TIFFTAG_COLORMATRIX2, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ColorMatrix2", NULL }, { TIFFTAG_CAMERACALIBRATION1, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "CameraCalibration1", NULL }, { TIFFTAG_CAMERACALIBRATION2, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "CameraCalibration2", NULL }, { TIFFTAG_REDUCTIONMATRIX1, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ReductionMatrix1", NULL }, { TIFFTAG_REDUCTIONMATRIX2, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ReductionMatrix2", NULL }, { TIFFTAG_ANALOGBALANCE, -1, -1, TIFF_RATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "AnalogBalance", NULL }, { TIFFTAG_ASSHOTNEUTRAL, -1, -1, TIFF_RATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "AsShotNeutral", NULL }, { TIFFTAG_ASSHOTWHITEXY, 2, 2, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "AsShotWhiteXY", NULL }, { TIFFTAG_BASELINEEXPOSURE, 1, 1, TIFF_SRATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "BaselineExposure", NULL }, { TIFFTAG_BASELINENOISE, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "BaselineNoise", NULL }, { TIFFTAG_BASELINESHARPNESS, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "BaselineSharpness", NULL }, { TIFFTAG_BAYERGREENSPLIT, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "BayerGreenSplit", NULL }, { TIFFTAG_LINEARRESPONSELIMIT, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "LinearResponseLimit", NULL }, { TIFFTAG_CAMERASERIALNUMBER, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "CameraSerialNumber", NULL }, { TIFFTAG_LENSINFO, 4, 4, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "LensInfo", NULL }, { TIFFTAG_CHROMABLURRADIUS, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "ChromaBlurRadius", NULL }, { TIFFTAG_ANTIALIASSTRENGTH, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "AntiAliasStrength", NULL }, { TIFFTAG_SHADOWSCALE, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "ShadowScale", NULL }, { TIFFTAG_DNGPRIVATEDATA, -1, -1, TIFF_BYTE, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "DNGPrivateData", NULL }, { TIFFTAG_MAKERNOTESAFETY, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "MakerNoteSafety", NULL }, { TIFFTAG_CALIBRATIONILLUMINANT1, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "CalibrationIlluminant1", NULL }, { TIFFTAG_CALIBRATIONILLUMINANT2, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "CalibrationIlluminant2", NULL }, { TIFFTAG_RAWDATAUNIQUEID, 16, 16, TIFF_BYTE, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "RawDataUniqueID", NULL }, { TIFFTAG_ORIGINALRAWFILENAME, -1, -1, TIFF_BYTE, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "OriginalRawFileName", NULL }, { TIFFTAG_ORIGINALRAWFILEDATA, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "OriginalRawFileData", NULL }, { TIFFTAG_ACTIVEAREA, 4, 4, TIFF_LONG, 0, TIFF_SETGET_C0_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "ActiveArea", NULL }, { TIFFTAG_MASKEDAREAS, -1, -1, TIFF_LONG, 0, TIFF_SETGET_C16_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "MaskedAreas", NULL }, { TIFFTAG_ASSHOTICCPROFILE, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "AsShotICCProfile", NULL }, { TIFFTAG_ASSHOTPREPROFILEMATRIX, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "AsShotPreProfileMatrix", NULL }, { TIFFTAG_CURRENTICCPROFILE, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "CurrentICCProfile", NULL }, { TIFFTAG_CURRENTPREPROFILEMATRIX, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "CurrentPreProfileMatrix", NULL }, /* end DNG tags */ }; static const TIFFField exifFields[] = { { EXIFTAG_EXPOSURETIME, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ExposureTime", NULL }, { EXIFTAG_FNUMBER, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FNumber", NULL }, { EXIFTAG_EXPOSUREPROGRAM, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ExposureProgram", NULL }, { EXIFTAG_SPECTRALSENSITIVITY, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SpectralSensitivity", NULL }, { EXIFTAG_ISOSPEEDRATINGS, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_C16_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "ISOSpeedRatings", NULL }, { EXIFTAG_OECF, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "OptoelectricConversionFactor", NULL }, { EXIFTAG_EXIFVERSION, 4, 4, TIFF_UNDEFINED, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ExifVersion", NULL }, { EXIFTAG_DATETIMEORIGINAL, 20, 20, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "DateTimeOriginal", NULL }, { EXIFTAG_DATETIMEDIGITIZED, 20, 20, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "DateTimeDigitized", NULL }, { EXIFTAG_COMPONENTSCONFIGURATION, 4, 4, TIFF_UNDEFINED, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ComponentsConfiguration", NULL }, { EXIFTAG_COMPRESSEDBITSPERPIXEL, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "CompressedBitsPerPixel", NULL }, { EXIFTAG_SHUTTERSPEEDVALUE, 1, 1, TIFF_SRATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ShutterSpeedValue", NULL }, { EXIFTAG_APERTUREVALUE, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ApertureValue", NULL }, { EXIFTAG_BRIGHTNESSVALUE, 1, 1, TIFF_SRATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "BrightnessValue", NULL }, { EXIFTAG_EXPOSUREBIASVALUE, 1, 1, TIFF_SRATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ExposureBiasValue", NULL }, { EXIFTAG_MAXAPERTUREVALUE, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "MaxApertureValue", NULL }, { EXIFTAG_SUBJECTDISTANCE, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SubjectDistance", NULL }, { EXIFTAG_METERINGMODE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "MeteringMode", NULL }, { EXIFTAG_LIGHTSOURCE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "LightSource", NULL }, { EXIFTAG_FLASH, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Flash", NULL }, { EXIFTAG_FOCALLENGTH, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FocalLength", NULL }, { EXIFTAG_SUBJECTAREA, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_C16_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "SubjectArea", NULL }, { EXIFTAG_MAKERNOTE, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "MakerNote", NULL }, { EXIFTAG_USERCOMMENT, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "UserComment", NULL }, { EXIFTAG_SUBSECTIME, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SubSecTime", NULL }, { EXIFTAG_SUBSECTIMEORIGINAL, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SubSecTimeOriginal", NULL }, { EXIFTAG_SUBSECTIMEDIGITIZED, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SubSecTimeDigitized", NULL }, { EXIFTAG_FLASHPIXVERSION, 4, 4, TIFF_UNDEFINED, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FlashpixVersion", NULL }, { EXIFTAG_COLORSPACE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ColorSpace", NULL }, { EXIFTAG_PIXELXDIMENSION, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "PixelXDimension", NULL }, { EXIFTAG_PIXELYDIMENSION, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "PixelYDimension", NULL }, { EXIFTAG_RELATEDSOUNDFILE, 13, 13, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "RelatedSoundFile", NULL }, { EXIFTAG_FLASHENERGY, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FlashEnergy", NULL }, { EXIFTAG_SPATIALFREQUENCYRESPONSE, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "SpatialFrequencyResponse", NULL }, { EXIFTAG_FOCALPLANEXRESOLUTION, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FocalPlaneXResolution", NULL }, { EXIFTAG_FOCALPLANEYRESOLUTION, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FocalPlaneYResolution", NULL }, { EXIFTAG_FOCALPLANERESOLUTIONUNIT, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FocalPlaneResolutionUnit", NULL }, { EXIFTAG_SUBJECTLOCATION, 2, 2, TIFF_SHORT, 0, TIFF_SETGET_C0_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SubjectLocation", NULL }, { EXIFTAG_EXPOSUREINDEX, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ExposureIndex", NULL }, { EXIFTAG_SENSINGMETHOD, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SensingMethod", NULL }, { EXIFTAG_FILESOURCE, 1, 1, TIFF_UNDEFINED, 0, TIFF_SETGET_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FileSource", NULL }, { EXIFTAG_SCENETYPE, 1, 1, TIFF_UNDEFINED, 0, TIFF_SETGET_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SceneType", NULL }, { EXIFTAG_CFAPATTERN, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "CFAPattern", NULL }, { EXIFTAG_CUSTOMRENDERED, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "CustomRendered", NULL }, { EXIFTAG_EXPOSUREMODE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ExposureMode", NULL }, { EXIFTAG_WHITEBALANCE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "WhiteBalance", NULL }, { EXIFTAG_DIGITALZOOMRATIO, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "DigitalZoomRatio", NULL }, { EXIFTAG_FOCALLENGTHIN35MMFILM, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FocalLengthIn35mmFilm", NULL }, { EXIFTAG_SCENECAPTURETYPE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SceneCaptureType", NULL }, { EXIFTAG_GAINCONTROL, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "GainControl", NULL }, { EXIFTAG_CONTRAST, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Contrast", NULL }, { EXIFTAG_SATURATION, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Saturation", NULL }, { EXIFTAG_SHARPNESS, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Sharpness", NULL }, { EXIFTAG_DEVICESETTINGDESCRIPTION, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "DeviceSettingDescription", NULL }, { EXIFTAG_SUBJECTDISTANCERANGE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SubjectDistanceRange", NULL }, { EXIFTAG_IMAGEUNIQUEID, 33, 33, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ImageUniqueID", NULL } }; static const TIFFFieldArray tiffFieldArray = { tfiatImage, 0, TIFFArrayCount(tiffFields), tiffFields }; static const TIFFFieldArray exifFieldArray = { tfiatExif, 0, TIFFArrayCount(exifFields), exifFields }; const TIFFFieldArray* _TIFFGetFields(void) { return(&tiffFieldArray); } const TIFFFieldArray* _TIFFGetExifFields(void) { return(&exifFieldArray); } void _TIFFSetupFields(TIFF* tif, const TIFFFieldArray* fieldarray) { if (tif->tif_fields && tif->tif_nfields > 0) { uint32 i; for (i = 0; i < tif->tif_nfields; i++) { TIFFField *fld = tif->tif_fields[i]; if (fld->field_bit == FIELD_CUSTOM && strncmp("Tag ", fld->field_name, 4) == 0) { _TIFFfree(fld->field_name); _TIFFfree(fld); } } _TIFFfree(tif->tif_fields); tif->tif_fields = NULL; tif->tif_nfields = 0; } if (!_TIFFMergeFields(tif, fieldarray->fields, fieldarray->count)) { TIFFErrorExt(tif->tif_clientdata, "_TIFFSetupFields", "Setting up field info failed"); } } static int tagCompare(const void* a, const void* b) { const TIFFField* ta = *(const TIFFField**) a; const TIFFField* tb = *(const TIFFField**) b; /* NB: be careful of return values for 16-bit platforms */ if (ta->field_tag != tb->field_tag) return (int)ta->field_tag - (int)tb->field_tag; else return (ta->field_type == TIFF_ANY) ? 0 : ((int)tb->field_type - (int)ta->field_type); } static int tagNameCompare(const void* a, const void* b) { const TIFFField* ta = *(const TIFFField**) a; const TIFFField* tb = *(const TIFFField**) b; int ret = strcmp(ta->field_name, tb->field_name); if (ret) return ret; else return (ta->field_type == TIFF_ANY) ? 0 : ((int)tb->field_type - (int)ta->field_type); } int _TIFFMergeFields(TIFF* tif, const TIFFField info[], uint32 n) { const char module[] = "_TIFFMergeFields"; const char reason[] = "for fields array"; TIFFField** tp; uint32 i; for (i = 0; i < n; i++) { const TIFFField *fip = TIFFFindField(tif, info[i].field_tag, TIFF_ANY); if (fip) { TIFFErrorExt(tif->tif_clientdata, module, "Field with tag %lu is already registered as \"%s\"", (unsigned int) info[i].field_tag, fip->field_name); return 0; } } tif->tif_foundfield = NULL; if (tif->tif_fields && tif->tif_nfields > 0) { tif->tif_fields = (TIFFField**) _TIFFCheckRealloc(tif, tif->tif_fields, (tif->tif_nfields + n), sizeof(TIFFField *), reason); } else { tif->tif_fields = (TIFFField **) _TIFFCheckMalloc(tif, n, sizeof(TIFFField *), reason); } if (!tif->tif_fields) { TIFFErrorExt(tif->tif_clientdata, module, "Failed to allocate fields array"); return 0; } tp = tif->tif_fields + tif->tif_nfields; for (i = 0; i < n; i++) *tp++ = (TIFFField *) (info + i); /* XXX */ /* Sort the field info by tag number */ qsort(tif->tif_fields, tif->tif_nfields += n, sizeof(TIFFField *), tagCompare); return n; } void _TIFFPrintFieldInfo(TIFF* tif, FILE* fd) { uint32 i; fprintf(fd, "%s: \n", tif->tif_name); for (i = 0; i < tif->tif_nfields; i++) { const TIFFField* fip = tif->tif_fields[i]; fprintf(fd, "field[%2d] %5lu, %2d, %2d, %d, %2d, %5s, %5s, %s\n" , (int)i , (unsigned long) fip->field_tag , fip->field_readcount, fip->field_writecount , fip->field_type , fip->field_bit , fip->field_oktochange ? "TRUE" : "FALSE" , fip->field_passcount ? "TRUE" : "FALSE" , fip->field_name ); } } /* * Return size of TIFFDataType in bytes */ int TIFFDataWidth(TIFFDataType type) { switch(type) { case 0: /* nothing */ case TIFF_BYTE: case TIFF_ASCII: case TIFF_SBYTE: case TIFF_UNDEFINED: return 1; case TIFF_SHORT: case TIFF_SSHORT: return 2; case TIFF_LONG: case TIFF_SLONG: case TIFF_FLOAT: case TIFF_IFD: return 4; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_DOUBLE: case TIFF_LONG8: case TIFF_SLONG8: case TIFF_IFD8: return 8; default: return 0; /* will return 0 for unknown types */ } } /* * Return size of TIFFDataType in bytes. * * XXX: We need a separate function to determine the space needed * to store the value. For TIFF_RATIONAL values TIFFDataWidth() returns 8, * but we use 4-byte float to represent rationals. */ int _TIFFDataSize(TIFFDataType type) { switch (type) { case TIFF_BYTE: case TIFF_SBYTE: case TIFF_ASCII: case TIFF_UNDEFINED: return 1; case TIFF_SHORT: case TIFF_SSHORT: return 2; case TIFF_LONG: case TIFF_SLONG: case TIFF_FLOAT: case TIFF_IFD: case TIFF_RATIONAL: case TIFF_SRATIONAL: return 4; case TIFF_DOUBLE: case TIFF_LONG8: case TIFF_SLONG8: case TIFF_IFD8: return 8; default: return 0; } } const TIFFField* TIFFFindField(TIFF* tif, uint32 tag, TIFFDataType dt) { TIFFField key = {0, 0, 0, TIFF_NOTYPE, 0, 0, 0, 0, 0, 0, NULL, NULL}; TIFFField* pkey = &key; const TIFFField **ret; if (tif->tif_foundfield && tif->tif_foundfield->field_tag == tag && (dt == TIFF_ANY || dt == tif->tif_foundfield->field_type)) return tif->tif_foundfield; /* If we are invoked with no field information, then just return. */ if (!tif->tif_fields) return NULL; /* NB: use sorted search (e.g. binary search) */ key.field_tag = tag; key.field_type = dt; ret = (const TIFFField **) bsearch(&pkey, tif->tif_fields, tif->tif_nfields, sizeof(TIFFField *), tagCompare); return tif->tif_foundfield = (ret ? *ret : NULL); } const TIFFField* _TIFFFindFieldByName(TIFF* tif, const char *field_name, TIFFDataType dt) { TIFFField key = {0, 0, 0, TIFF_NOTYPE, 0, 0, 0, 0, 0, 0, NULL, NULL}; TIFFField* pkey = &key; const TIFFField **ret; if (tif->tif_foundfield && streq(tif->tif_foundfield->field_name, field_name) && (dt == TIFF_ANY || dt == tif->tif_foundfield->field_type)) return (tif->tif_foundfield); /* If we are invoked with no field information, then just return. */ if (!tif->tif_fields) return NULL; /* NB: use sorted search (e.g. binary search) */ key.field_name = (char *)field_name; key.field_type = dt; ret = (const TIFFField **) lfind(&pkey, tif->tif_fields, &tif->tif_nfields, sizeof(TIFFField *), tagNameCompare); return tif->tif_foundfield = (ret ? *ret : NULL); } const TIFFField* TIFFFieldWithTag(TIFF* tif, uint32 tag) { const TIFFField* fip = TIFFFindField(tif, tag, TIFF_ANY); if (!fip) { TIFFErrorExt(tif->tif_clientdata, "TIFFFieldWithTag", "Internal error, unknown tag 0x%x", (unsigned int) tag); assert(fip != NULL); /*NOTREACHED*/ } return (fip); } const TIFFField* TIFFFieldWithName(TIFF* tif, const char *field_name) { const TIFFField* fip = _TIFFFindFieldByName(tif, field_name, TIFF_ANY); if (!fip) { TIFFErrorExt(tif->tif_clientdata, "TIFFFieldWithName", "Internal error, unknown tag %s", field_name); assert(fip != NULL); /*NOTREACHED*/ } return (fip); } const TIFFField* _TIFFFindOrRegisterField(TIFF *tif, uint32 tag, TIFFDataType dt) { const TIFFField *fld; fld = TIFFFindField(tif, tag, dt); if (fld == NULL) { fld = _TIFFCreateAnonField(tif, tag, dt); if (!_TIFFMergeFields(tif, fld, 1)) return NULL; } return fld; } TIFFField* _TIFFCreateAnonField(TIFF *tif, uint32 tag, TIFFDataType field_type) { TIFFField *fld; (void) tif; fld = (TIFFField *) _TIFFmalloc(sizeof (TIFFField)); if (fld == NULL) return NULL; _TIFFmemset(fld, 0, sizeof(TIFFField)); fld->field_tag = tag; fld->field_readcount = TIFF_VARIABLE2; fld->field_writecount = TIFF_VARIABLE2; fld->field_type = field_type; fld->reserved = 0; switch (field_type) { case TIFF_BYTE: case TIFF_UNDEFINED: fld->set_field_type = TIFF_SETGET_C32_UINT8; fld->get_field_type = TIFF_SETGET_C32_UINT8; break; case TIFF_ASCII: fld->set_field_type = TIFF_SETGET_C32_ASCII; fld->get_field_type = TIFF_SETGET_C32_ASCII; break; case TIFF_SHORT: fld->set_field_type = TIFF_SETGET_C32_UINT16; fld->get_field_type = TIFF_SETGET_C32_UINT16; break; case TIFF_LONG: fld->set_field_type = TIFF_SETGET_C32_UINT32; fld->get_field_type = TIFF_SETGET_C32_UINT32; break; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: fld->set_field_type = TIFF_SETGET_C32_FLOAT; fld->get_field_type = TIFF_SETGET_C32_FLOAT; break; case TIFF_SBYTE: fld->set_field_type = TIFF_SETGET_C32_SINT8; fld->get_field_type = TIFF_SETGET_C32_SINT8; break; case TIFF_SSHORT: fld->set_field_type = TIFF_SETGET_C32_SINT16; fld->get_field_type = TIFF_SETGET_C32_SINT16; break; case TIFF_SLONG: fld->set_field_type = TIFF_SETGET_C32_SINT32; fld->get_field_type = TIFF_SETGET_C32_SINT32; break; case TIFF_DOUBLE: fld->set_field_type = TIFF_SETGET_C32_DOUBLE; fld->get_field_type = TIFF_SETGET_C32_DOUBLE; break; case TIFF_IFD: case TIFF_IFD8: fld->set_field_type = TIFF_SETGET_C32_IFD8; fld->get_field_type = TIFF_SETGET_C32_IFD8; break; case TIFF_LONG8: fld->set_field_type = TIFF_SETGET_C32_UINT64; fld->get_field_type = TIFF_SETGET_C32_UINT64; break; case TIFF_SLONG8: fld->set_field_type = TIFF_SETGET_C32_SINT64; fld->get_field_type = TIFF_SETGET_C32_SINT64; break; default: fld->set_field_type = TIFF_SETGET_UNDEFINED; fld->get_field_type = TIFF_SETGET_UNDEFINED; break; } fld->field_bit = FIELD_CUSTOM; fld->field_oktochange = TRUE; fld->field_passcount = TRUE; fld->field_name = (char *) _TIFFmalloc(32); if (fld->field_name == NULL) { _TIFFfree(fld); return NULL; } fld->field_subfields = NULL; /* * note that this name is a special sign to TIFFClose() and * _TIFFSetupFields() to free the field */ sprintf(fld->field_name, "Tag %d", (int) tag); return fld; } /**************************************************************************** * O B S O L E T E D I N T E R F A C E S * * Don't use this stuff in your applications, it may be removed in the future * libtiff versions. ****************************************************************************/ static TIFFSetGetFieldType _TIFFSetGetType(TIFFDataType type, short count, unsigned char passcount) { if (type == TIFF_ASCII && count == TIFF_VARIABLE && passcount == 0) return TIFF_SETGET_ASCII; else if (count == 1 && passcount == 0) { switch (type) { case TIFF_BYTE: case TIFF_UNDEFINED: return TIFF_SETGET_UINT8; case TIFF_ASCII: return TIFF_SETGET_ASCII; case TIFF_SHORT: return TIFF_SETGET_UINT16; case TIFF_LONG: return TIFF_SETGET_UINT32; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: return TIFF_SETGET_FLOAT; case TIFF_SBYTE: return TIFF_SETGET_SINT8; case TIFF_SSHORT: return TIFF_SETGET_SINT16; case TIFF_SLONG: return TIFF_SETGET_SINT32; case TIFF_DOUBLE: return TIFF_SETGET_DOUBLE; case TIFF_IFD: case TIFF_IFD8: return TIFF_SETGET_IFD8; case TIFF_LONG8: return TIFF_SETGET_UINT64; case TIFF_SLONG8: return TIFF_SETGET_SINT64; default: return TIFF_SETGET_UNDEFINED; } } else if (count >= 1 && passcount == 0) { switch (type) { case TIFF_BYTE: case TIFF_UNDEFINED: return TIFF_SETGET_C0_UINT8; case TIFF_ASCII: return TIFF_SETGET_C0_ASCII; case TIFF_SHORT: return TIFF_SETGET_C0_UINT16; case TIFF_LONG: return TIFF_SETGET_C0_UINT32; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: return TIFF_SETGET_C0_FLOAT; case TIFF_SBYTE: return TIFF_SETGET_C0_SINT8; case TIFF_SSHORT: return TIFF_SETGET_C0_SINT16; case TIFF_SLONG: return TIFF_SETGET_C0_SINT32; case TIFF_DOUBLE: return TIFF_SETGET_C0_DOUBLE; case TIFF_IFD: case TIFF_IFD8: return TIFF_SETGET_C0_IFD8; case TIFF_LONG8: return TIFF_SETGET_C0_UINT64; case TIFF_SLONG8: return TIFF_SETGET_C0_SINT64; default: return TIFF_SETGET_UNDEFINED; } } else if (count == TIFF_VARIABLE && passcount == 1) { switch (type) { case TIFF_BYTE: case TIFF_UNDEFINED: return TIFF_SETGET_C16_UINT8; case TIFF_ASCII: return TIFF_SETGET_C16_ASCII; case TIFF_SHORT: return TIFF_SETGET_C16_UINT16; case TIFF_LONG: return TIFF_SETGET_C16_UINT32; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: return TIFF_SETGET_C16_FLOAT; case TIFF_SBYTE: return TIFF_SETGET_C16_SINT8; case TIFF_SSHORT: return TIFF_SETGET_C16_SINT16; case TIFF_SLONG: return TIFF_SETGET_C16_SINT32; case TIFF_DOUBLE: return TIFF_SETGET_C16_DOUBLE; case TIFF_IFD: case TIFF_IFD8: return TIFF_SETGET_C16_IFD8; case TIFF_LONG8: return TIFF_SETGET_C16_UINT64; case TIFF_SLONG8: return TIFF_SETGET_C16_SINT64; default: return TIFF_SETGET_UNDEFINED; } } else if (count == TIFF_VARIABLE2 && passcount == 1) { switch (type) { case TIFF_BYTE: case TIFF_UNDEFINED: return TIFF_SETGET_C32_UINT8; case TIFF_ASCII: return TIFF_SETGET_C32_ASCII; case TIFF_SHORT: return TIFF_SETGET_C32_UINT16; case TIFF_LONG: return TIFF_SETGET_C32_UINT32; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: return TIFF_SETGET_C32_FLOAT; case TIFF_SBYTE: return TIFF_SETGET_C32_SINT8; case TIFF_SSHORT: return TIFF_SETGET_C32_SINT16; case TIFF_SLONG: return TIFF_SETGET_C32_SINT32; case TIFF_DOUBLE: return TIFF_SETGET_C32_DOUBLE; case TIFF_IFD: case TIFF_IFD8: return TIFF_SETGET_C32_IFD8; case TIFF_LONG8: return TIFF_SETGET_C32_UINT64; case TIFF_SLONG8: return TIFF_SETGET_C32_SINT64; default: return TIFF_SETGET_UNDEFINED; } } return TIFF_SETGET_UNDEFINED; } int TIFFMergeFieldInfo(TIFF* tif, const TIFFFieldInfo info[], uint32 n) { const char module[] = "TIFFMergeFieldInfo"; const char reason[] = "for fields array"; TIFFField *tp; uint32 i, nfields; if (tif->tif_nfieldscompat > 0) { tif->tif_fieldscompat = (TIFFFieldArray *) _TIFFCheckRealloc(tif, tif->tif_fieldscompat, tif->tif_nfieldscompat + 1, sizeof(TIFFFieldArray), reason); } else { tif->tif_fieldscompat = (TIFFFieldArray *) _TIFFCheckMalloc(tif, 1, sizeof(TIFFFieldArray), reason); } if (!tif->tif_fieldscompat) { TIFFErrorExt(tif->tif_clientdata, module, "Failed to allocate fields array"); return -1; } nfields = tif->tif_nfieldscompat++; tif->tif_fieldscompat[nfields].type = tfiatOther; tif->tif_fieldscompat[nfields].allocated_size = n; tif->tif_fieldscompat[nfields].count = n; tif->tif_fieldscompat[nfields].fields = (TIFFField *)_TIFFCheckMalloc(tif, n, sizeof(TIFFField), reason); if (!tif->tif_fieldscompat[nfields].fields) { TIFFErrorExt(tif->tif_clientdata, module, "Failed to allocate fields array"); return -1; } tp = tif->tif_fieldscompat[nfields].fields; for (i = 0; i < n; i++) { tp->field_tag = info[i].field_tag; tp->field_readcount = info[i].field_readcount; tp->field_writecount = info[i].field_writecount; tp->field_type = info[i].field_type; tp->reserved = 0; tp->set_field_type = _TIFFSetGetType(info[i].field_type, info[i].field_readcount, info[i].field_passcount); tp->get_field_type = _TIFFSetGetType(info[i].field_type, info[i].field_readcount, info[i].field_passcount); tp->field_bit = info[i].field_bit; tp->field_oktochange = info[i].field_oktochange; tp->field_passcount = info[i].field_passcount; tp->field_name = info[i].field_name; tp->field_subfields = NULL; tp++; } if (!_TIFFMergeFields(tif, tif->tif_fieldscompat[nfields].fields, n)) { TIFFErrorExt(tif->tif_clientdata, module, "Setting up field info failed"); return -1; } return 0; } const TIFFFieldInfo* TIFFFindFieldInfoByName(TIFF* tif, const char *field_name, TIFFDataType dt) { #if 0 TIFFFieldInfo key = {0, 0, 0, TIFF_NOTYPE, 0, 0, 0, 0, 0, 0, NULL, NULL}; TIFFFieldInfo* pkey = &key; const TIFFFieldInfo **ret; if (tif->tif_foundfield && streq(tif->tif_foundfield->field_name, field_name) && (dt == TIFF_ANY || dt == tif->tif_foundfield->field_type)) return (tif->tif_foundfield); /* If we are invoked with no field information, then just return. */ if ( !tif->tif_fields ) { return NULL; } /* NB: use sorted search (e.g. binary search) */ key.field_name = (char *)field_name; key.field_type = dt; ret = (const TIFFFieldInfo **) lfind(&pkey, tif->tif_fields, &tif->tif_nfields, sizeof(TIFFFieldInfo *), tagNameCompare); return tif->tif_foundfield = (ret ? *ret : NULL); #endif return NULL; } const TIFFFieldInfo* TIFFFindFieldInfo(TIFF* tif, uint32 tag, TIFFDataType dt) { #if 0 TIFFFieldInfo key = {0, 0, 0, TIFF_NOTYPE, 0, 0, 0, 0, 0, 0, NULL, NULL}; TIFFFieldInfo* pkey = &key; const TIFFFieldInfo **ret; if (tif->tif_foundfield && tif->tif_foundfield->field_tag == tag && (dt == TIFF_ANY || dt == tif->tif_foundfield->field_type)) return tif->tif_foundfield; /* If we are invoked with no field information, then just return. */ if ( !tif->tif_fields ) { return NULL; } /* NB: use sorted search (e.g. binary search) */ key.field_tag = tag; key.field_type = dt; ret = (const TIFFFieldInfo **) bsearch(&pkey, tif->tif_fields, tif->tif_nfields, sizeof(TIFFFieldInfo *), tagCompare); return tif->tif_foundfield = (ret ? *ret : NULL); #endif return NULL; } /* vim: set ts=8 sts=8 sw=8 noet: */ /* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library. * * Core Directory Tag Support. */ #include "tiffiop.h" #include <stdlib.h> /* * NOTE: THIS ARRAY IS ASSUMED TO BE SORTED BY TAG. * * NOTE: The second field (field_readcount) and third field (field_writecount) * sometimes use the values TIFF_VARIABLE (-1), TIFF_VARIABLE2 (-3) * and TIFFTAG_SPP (-2). The macros should be used but would throw off * the formatting of the code, so please interprete the -1, -2 and -3 * values accordingly. */ static const TIFFFieldArray tiffFieldArray; static const TIFFFieldArray exifFieldArray; static const TIFFField tiffFields[] = { { TIFFTAG_SUBFILETYPE, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_SUBFILETYPE, 1, 0, "SubfileType", NULL }, { TIFFTAG_OSUBFILETYPE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_SUBFILETYPE, 1, 0, "OldSubfileType", NULL }, { TIFFTAG_IMAGEWIDTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_IMAGEDIMENSIONS, 0, 0, "ImageWidth", NULL }, { TIFFTAG_IMAGELENGTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_IMAGEDIMENSIONS, 1, 0, "ImageLength", NULL }, { TIFFTAG_BITSPERSAMPLE, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_BITSPERSAMPLE, 0, 0, "BitsPerSample", NULL }, { TIFFTAG_COMPRESSION, -1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_COMPRESSION, 0, 0, "Compression", NULL }, { TIFFTAG_PHOTOMETRIC, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_PHOTOMETRIC, 0, 0, "PhotometricInterpretation", NULL }, { TIFFTAG_THRESHHOLDING, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_THRESHHOLDING, 1, 0, "Threshholding", NULL }, { TIFFTAG_CELLWIDTH, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 1, 0, "CellWidth", NULL }, { TIFFTAG_CELLLENGTH, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 1, 0, "CellLength", NULL }, { TIFFTAG_FILLORDER, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_FILLORDER, 0, 0, "FillOrder", NULL }, { TIFFTAG_DOCUMENTNAME, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "DocumentName", NULL }, { TIFFTAG_IMAGEDESCRIPTION, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ImageDescription", NULL }, { TIFFTAG_MAKE, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Make", NULL }, { TIFFTAG_MODEL, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Model", NULL }, { TIFFTAG_STRIPOFFSETS, -1, -1, TIFF_LONG8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_STRIPOFFSETS, 0, 0, "StripOffsets", NULL }, { TIFFTAG_ORIENTATION, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_ORIENTATION, 0, 0, "Orientation", NULL }, { TIFFTAG_SAMPLESPERPIXEL, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_SAMPLESPERPIXEL, 0, 0, "SamplesPerPixel", NULL }, { TIFFTAG_ROWSPERSTRIP, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_ROWSPERSTRIP, 0, 0, "RowsPerStrip", NULL }, { TIFFTAG_STRIPBYTECOUNTS, -1, -1, TIFF_LONG8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_STRIPBYTECOUNTS, 0, 0, "StripByteCounts", NULL }, { TIFFTAG_MINSAMPLEVALUE, -2, -1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_MINSAMPLEVALUE, 1, 0, "MinSampleValue", NULL }, { TIFFTAG_MAXSAMPLEVALUE, -2, -1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_MAXSAMPLEVALUE, 1, 0, "MaxSampleValue", NULL }, { TIFFTAG_XRESOLUTION, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_RESOLUTION, 1, 0, "XResolution", NULL }, { TIFFTAG_YRESOLUTION, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_RESOLUTION, 1, 0, "YResolution", NULL }, { TIFFTAG_PLANARCONFIG, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_PLANARCONFIG, 0, 0, "PlanarConfiguration", NULL }, { TIFFTAG_PAGENAME, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "PageName", NULL }, { TIFFTAG_XPOSITION, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_POSITION, 1, 0, "XPosition", NULL }, { TIFFTAG_YPOSITION, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_POSITION, 1, 0, "YPosition", NULL }, { TIFFTAG_FREEOFFSETS, -1, -1, TIFF_LONG8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 0, 0, "FreeOffsets", NULL }, { TIFFTAG_FREEBYTECOUNTS, -1, -1, TIFF_LONG8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 0, 0, "FreeByteCounts", NULL }, { TIFFTAG_GRAYRESPONSEUNIT, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 1, 0, "GrayResponseUnit", NULL }, { TIFFTAG_GRAYRESPONSECURVE, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 1, 0, "GrayResponseCurve", NULL }, { TIFFTAG_RESOLUTIONUNIT, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_RESOLUTIONUNIT, 1, 0, "ResolutionUnit", NULL }, { TIFFTAG_PAGENUMBER, 2, 2, TIFF_SHORT, 0, TIFF_SETGET_UINT16_PAIR, TIFF_SETGET_UNDEFINED, FIELD_PAGENUMBER, 1, 0, "PageNumber", NULL }, { TIFFTAG_COLORRESPONSEUNIT, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 1, 0, "ColorResponseUnit", NULL }, { TIFFTAG_TRANSFERFUNCTION, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_OTHER, TIFF_SETGET_UNDEFINED, FIELD_TRANSFERFUNCTION, 1, 0, "TransferFunction", NULL }, { TIFFTAG_SOFTWARE, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Software", NULL }, { TIFFTAG_DATETIME, 20, 20, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "DateTime", NULL }, { TIFFTAG_ARTIST, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Artist", NULL }, { TIFFTAG_HOSTCOMPUTER, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "HostComputer", NULL }, { TIFFTAG_WHITEPOINT, 2, 2, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "WhitePoint", NULL }, { TIFFTAG_PRIMARYCHROMATICITIES, 6, 6, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "PrimaryChromaticities", NULL }, { TIFFTAG_COLORMAP, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_OTHER, TIFF_SETGET_UNDEFINED, FIELD_COLORMAP, 1, 0, "ColorMap", NULL }, { TIFFTAG_HALFTONEHINTS, 2, 2, TIFF_SHORT, 0, TIFF_SETGET_UINT16_PAIR, TIFF_SETGET_UNDEFINED, FIELD_HALFTONEHINTS, 1, 0, "HalftoneHints", NULL }, { TIFFTAG_TILEWIDTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_TILEDIMENSIONS, 0, 0, "TileWidth", NULL }, { TIFFTAG_TILELENGTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_TILEDIMENSIONS, 0, 0, "TileLength", NULL }, { TIFFTAG_TILEOFFSETS, -1, 1, TIFF_LONG8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_STRIPOFFSETS, 0, 0, "TileOffsets", NULL }, { TIFFTAG_TILEBYTECOUNTS, -1, 1, TIFF_LONG8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_STRIPBYTECOUNTS, 0, 0, "TileByteCounts", NULL }, { TIFFTAG_SUBIFD, -1, -1, TIFF_IFD8, 0, TIFF_SETGET_C16_IFD8, TIFF_SETGET_UNDEFINED, FIELD_SUBIFD, 1, 1, "SubIFD", &tiffFieldArray }, { TIFFTAG_INKSET, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "InkSet", NULL }, { TIFFTAG_INKNAMES, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_C16_ASCII, TIFF_SETGET_UNDEFINED, FIELD_INKNAMES, 1, 1, "InkNames", NULL }, { TIFFTAG_NUMBEROFINKS, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "NumberOfInks", NULL }, { TIFFTAG_DOTRANGE, 2, 2, TIFF_SHORT, 0, TIFF_SETGET_UINT16_PAIR, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "DotRange", NULL }, { TIFFTAG_TARGETPRINTER, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "TargetPrinter", NULL }, { TIFFTAG_EXTRASAMPLES, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_C16_UINT16, TIFF_SETGET_UNDEFINED, FIELD_EXTRASAMPLES, 0, 1, "ExtraSamples", NULL }, { TIFFTAG_SAMPLEFORMAT, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_SAMPLEFORMAT, 0, 0, "SampleFormat", NULL }, { TIFFTAG_SMINSAMPLEVALUE, -2, -1, TIFF_ANY, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_SMINSAMPLEVALUE, 1, 0, "SMinSampleValue", NULL }, { TIFFTAG_SMAXSAMPLEVALUE, -2, -1, TIFF_ANY, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_SMAXSAMPLEVALUE, 1, 0, "SMaxSampleValue", NULL }, { TIFFTAG_CLIPPATH, -1, -3, TIFF_BYTE, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ClipPath", NULL }, { TIFFTAG_XCLIPPATHUNITS, 1, 1, TIFF_SLONG, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "XClipPathUnits", NULL }, { TIFFTAG_XCLIPPATHUNITS, 1, 1, TIFF_SBYTE, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "XClipPathUnits", NULL }, { TIFFTAG_YCLIPPATHUNITS, 1, 1, TIFF_SLONG, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "YClipPathUnits", NULL }, { TIFFTAG_YCBCRCOEFFICIENTS, 3, 3, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "YCbCrCoefficients", NULL }, { TIFFTAG_YCBCRSUBSAMPLING, 2, 2, TIFF_SHORT, 0, TIFF_SETGET_UINT16_PAIR, TIFF_SETGET_UNDEFINED, FIELD_YCBCRSUBSAMPLING, 0, 0, "YCbCrSubsampling", NULL }, { TIFFTAG_YCBCRPOSITIONING, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_YCBCRPOSITIONING, 0, 0, "YCbCrPositioning", NULL }, { TIFFTAG_REFERENCEBLACKWHITE, 6, 6, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ReferenceBlackWhite", NULL }, { TIFFTAG_XMLPACKET, -3, -3, TIFF_BYTE, 0, TIFF_SETGET_C32_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "XMLPacket", NULL }, /* begin SGI tags */ { TIFFTAG_MATTEING, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_EXTRASAMPLES, 0, 0, "Matteing", NULL }, { TIFFTAG_DATATYPE, -2, -1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_SAMPLEFORMAT, 0, 0, "DataType", NULL }, { TIFFTAG_IMAGEDEPTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_IMAGEDEPTH, 0, 0, "ImageDepth", NULL }, { TIFFTAG_TILEDEPTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_TILEDEPTH, 0, 0, "TileDepth", NULL }, /* end SGI tags */ /* begin Pixar tags */ { TIFFTAG_PIXAR_IMAGEFULLWIDTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ImageFullWidth", NULL }, { TIFFTAG_PIXAR_IMAGEFULLLENGTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ImageFullLength", NULL }, { TIFFTAG_PIXAR_TEXTUREFORMAT, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "TextureFormat", NULL }, { TIFFTAG_PIXAR_WRAPMODES, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "TextureWrapModes", NULL }, { TIFFTAG_PIXAR_FOVCOT, 1, 1, TIFF_FLOAT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FieldOfViewCotangent", NULL }, { TIFFTAG_PIXAR_MATRIX_WORLDTOSCREEN, 16, 16, TIFF_FLOAT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "MatrixWorldToScreen", NULL }, { TIFFTAG_PIXAR_MATRIX_WORLDTOCAMERA, 16, 16, TIFF_FLOAT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "MatrixWorldToCamera", NULL }, { TIFFTAG_COPYRIGHT, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Copyright", NULL }, /* end Pixar tags */ { TIFFTAG_RICHTIFFIPTC, -3, -3, TIFF_LONG, 0, TIFF_SETGET_C32_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "RichTIFFIPTC", NULL }, { TIFFTAG_PHOTOSHOP, -3, -3, TIFF_BYTE, 0, TIFF_SETGET_C32_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "Photoshop", NULL }, { TIFFTAG_EXIFIFD, 1, 1, TIFF_IFD8, 0, TIFF_SETGET_IFD8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "EXIFIFDOffset", &exifFieldArray }, { TIFFTAG_ICCPROFILE, -3, -3, TIFF_UNDEFINED, 0, TIFF_SETGET_C32_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ICC Profile", NULL }, { TIFFTAG_GPSIFD, 1, 1, TIFF_IFD8, 0, TIFF_SETGET_IFD8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "GPSIFDOffset", NULL }, { TIFFTAG_FAXRECVPARAMS, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UINT32, FIELD_CUSTOM, TRUE, FALSE, "FaxRecvParams", NULL }, { TIFFTAG_FAXSUBADDRESS, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_ASCII, FIELD_CUSTOM, TRUE, FALSE, "FaxSubAddress", NULL }, { TIFFTAG_FAXRECVTIME, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UINT32, FIELD_CUSTOM, TRUE, FALSE, "FaxRecvTime", NULL }, { TIFFTAG_FAXDCS, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_ASCII, FIELD_CUSTOM, TRUE, FALSE, "FaxDcs", NULL }, { TIFFTAG_STONITS, 1, 1, TIFF_DOUBLE, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "StoNits", NULL }, { TIFFTAG_INTEROPERABILITYIFD, 1, 1, TIFF_IFD8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "InteroperabilityIFDOffset", NULL }, /* begin DNG tags */ { TIFFTAG_DNGVERSION, 4, 4, TIFF_BYTE, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "DNGVersion", NULL }, { TIFFTAG_DNGBACKWARDVERSION, 4, 4, TIFF_BYTE, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "DNGBackwardVersion", NULL }, { TIFFTAG_UNIQUECAMERAMODEL, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "UniqueCameraModel", NULL }, { TIFFTAG_LOCALIZEDCAMERAMODEL, -1, -1, TIFF_BYTE, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "LocalizedCameraModel", NULL }, { TIFFTAG_CFAPLANECOLOR, -1, -1, TIFF_BYTE, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "CFAPlaneColor", NULL }, { TIFFTAG_CFALAYOUT, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "CFALayout", NULL }, { TIFFTAG_LINEARIZATIONTABLE, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_C16_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "LinearizationTable", NULL }, { TIFFTAG_BLACKLEVELREPEATDIM, 2, 2, TIFF_SHORT, 0, TIFF_SETGET_C0_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "BlackLevelRepeatDim", NULL }, { TIFFTAG_BLACKLEVEL, -1, -1, TIFF_RATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "BlackLevel", NULL }, { TIFFTAG_BLACKLEVELDELTAH, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "BlackLevelDeltaH", NULL }, { TIFFTAG_BLACKLEVELDELTAV, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "BlackLevelDeltaV", NULL }, { TIFFTAG_WHITELEVEL, -1, -1, TIFF_LONG, 0, TIFF_SETGET_C16_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "WhiteLevel", NULL }, { TIFFTAG_DEFAULTSCALE, 2, 2, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "DefaultScale", NULL }, { TIFFTAG_BESTQUALITYSCALE, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "BestQualityScale", NULL }, { TIFFTAG_DEFAULTCROPORIGIN, 2, 2, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "DefaultCropOrigin", NULL }, { TIFFTAG_DEFAULTCROPSIZE, 2, 2, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "DefaultCropSize", NULL }, { TIFFTAG_COLORMATRIX1, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ColorMatrix1", NULL }, { TIFFTAG_COLORMATRIX2, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ColorMatrix2", NULL }, { TIFFTAG_CAMERACALIBRATION1, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "CameraCalibration1", NULL }, { TIFFTAG_CAMERACALIBRATION2, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "CameraCalibration2", NULL }, { TIFFTAG_REDUCTIONMATRIX1, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ReductionMatrix1", NULL }, { TIFFTAG_REDUCTIONMATRIX2, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ReductionMatrix2", NULL }, { TIFFTAG_ANALOGBALANCE, -1, -1, TIFF_RATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "AnalogBalance", NULL }, { TIFFTAG_ASSHOTNEUTRAL, -1, -1, TIFF_RATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "AsShotNeutral", NULL }, { TIFFTAG_ASSHOTWHITEXY, 2, 2, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "AsShotWhiteXY", NULL }, { TIFFTAG_BASELINEEXPOSURE, 1, 1, TIFF_SRATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "BaselineExposure", NULL }, { TIFFTAG_BASELINENOISE, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "BaselineNoise", NULL }, { TIFFTAG_BASELINESHARPNESS, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "BaselineSharpness", NULL }, { TIFFTAG_BAYERGREENSPLIT, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "BayerGreenSplit", NULL }, { TIFFTAG_LINEARRESPONSELIMIT, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "LinearResponseLimit", NULL }, { TIFFTAG_CAMERASERIALNUMBER, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "CameraSerialNumber", NULL }, { TIFFTAG_LENSINFO, 4, 4, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "LensInfo", NULL }, { TIFFTAG_CHROMABLURRADIUS, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "ChromaBlurRadius", NULL }, { TIFFTAG_ANTIALIASSTRENGTH, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "AntiAliasStrength", NULL }, { TIFFTAG_SHADOWSCALE, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "ShadowScale", NULL }, { TIFFTAG_DNGPRIVATEDATA, -1, -1, TIFF_BYTE, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "DNGPrivateData", NULL }, { TIFFTAG_MAKERNOTESAFETY, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "MakerNoteSafety", NULL }, { TIFFTAG_CALIBRATIONILLUMINANT1, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "CalibrationIlluminant1", NULL }, { TIFFTAG_CALIBRATIONILLUMINANT2, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "CalibrationIlluminant2", NULL }, { TIFFTAG_RAWDATAUNIQUEID, 16, 16, TIFF_BYTE, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "RawDataUniqueID", NULL }, { TIFFTAG_ORIGINALRAWFILENAME, -1, -1, TIFF_BYTE, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "OriginalRawFileName", NULL }, { TIFFTAG_ORIGINALRAWFILEDATA, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "OriginalRawFileData", NULL }, { TIFFTAG_ACTIVEAREA, 4, 4, TIFF_LONG, 0, TIFF_SETGET_C0_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "ActiveArea", NULL }, { TIFFTAG_MASKEDAREAS, -1, -1, TIFF_LONG, 0, TIFF_SETGET_C16_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "MaskedAreas", NULL }, { TIFFTAG_ASSHOTICCPROFILE, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "AsShotICCProfile", NULL }, { TIFFTAG_ASSHOTPREPROFILEMATRIX, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "AsShotPreProfileMatrix", NULL }, { TIFFTAG_CURRENTICCPROFILE, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "CurrentICCProfile", NULL }, { TIFFTAG_CURRENTPREPROFILEMATRIX, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "CurrentPreProfileMatrix", NULL }, /* end DNG tags */ }; static const TIFFField exifFields[] = { { EXIFTAG_EXPOSURETIME, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ExposureTime", NULL }, { EXIFTAG_FNUMBER, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FNumber", NULL }, { EXIFTAG_EXPOSUREPROGRAM, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ExposureProgram", NULL }, { EXIFTAG_SPECTRALSENSITIVITY, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SpectralSensitivity", NULL }, { EXIFTAG_ISOSPEEDRATINGS, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_C16_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "ISOSpeedRatings", NULL }, { EXIFTAG_OECF, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "OptoelectricConversionFactor", NULL }, { EXIFTAG_EXIFVERSION, 4, 4, TIFF_UNDEFINED, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ExifVersion", NULL }, { EXIFTAG_DATETIMEORIGINAL, 20, 20, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "DateTimeOriginal", NULL }, { EXIFTAG_DATETIMEDIGITIZED, 20, 20, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "DateTimeDigitized", NULL }, { EXIFTAG_COMPONENTSCONFIGURATION, 4, 4, TIFF_UNDEFINED, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ComponentsConfiguration", NULL }, { EXIFTAG_COMPRESSEDBITSPERPIXEL, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "CompressedBitsPerPixel", NULL }, { EXIFTAG_SHUTTERSPEEDVALUE, 1, 1, TIFF_SRATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ShutterSpeedValue", NULL }, { EXIFTAG_APERTUREVALUE, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ApertureValue", NULL }, { EXIFTAG_BRIGHTNESSVALUE, 1, 1, TIFF_SRATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "BrightnessValue", NULL }, { EXIFTAG_EXPOSUREBIASVALUE, 1, 1, TIFF_SRATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ExposureBiasValue", NULL }, { EXIFTAG_MAXAPERTUREVALUE, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "MaxApertureValue", NULL }, { EXIFTAG_SUBJECTDISTANCE, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SubjectDistance", NULL }, { EXIFTAG_METERINGMODE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "MeteringMode", NULL }, { EXIFTAG_LIGHTSOURCE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "LightSource", NULL }, { EXIFTAG_FLASH, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Flash", NULL }, { EXIFTAG_FOCALLENGTH, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FocalLength", NULL }, { EXIFTAG_SUBJECTAREA, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_C16_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "SubjectArea", NULL }, { EXIFTAG_MAKERNOTE, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "MakerNote", NULL }, { EXIFTAG_USERCOMMENT, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "UserComment", NULL }, { EXIFTAG_SUBSECTIME, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SubSecTime", NULL }, { EXIFTAG_SUBSECTIMEORIGINAL, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SubSecTimeOriginal", NULL }, { EXIFTAG_SUBSECTIMEDIGITIZED, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SubSecTimeDigitized", NULL }, { EXIFTAG_FLASHPIXVERSION, 4, 4, TIFF_UNDEFINED, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FlashpixVersion", NULL }, { EXIFTAG_COLORSPACE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ColorSpace", NULL }, { EXIFTAG_PIXELXDIMENSION, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "PixelXDimension", NULL }, { EXIFTAG_PIXELYDIMENSION, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "PixelYDimension", NULL }, { EXIFTAG_RELATEDSOUNDFILE, 13, 13, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "RelatedSoundFile", NULL }, { EXIFTAG_FLASHENERGY, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FlashEnergy", NULL }, { EXIFTAG_SPATIALFREQUENCYRESPONSE, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "SpatialFrequencyResponse", NULL }, { EXIFTAG_FOCALPLANEXRESOLUTION, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FocalPlaneXResolution", NULL }, { EXIFTAG_FOCALPLANEYRESOLUTION, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FocalPlaneYResolution", NULL }, { EXIFTAG_FOCALPLANERESOLUTIONUNIT, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FocalPlaneResolutionUnit", NULL }, { EXIFTAG_SUBJECTLOCATION, 2, 2, TIFF_SHORT, 0, TIFF_SETGET_C0_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SubjectLocation", NULL }, { EXIFTAG_EXPOSUREINDEX, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ExposureIndex", NULL }, { EXIFTAG_SENSINGMETHOD, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SensingMethod", NULL }, { EXIFTAG_FILESOURCE, 1, 1, TIFF_UNDEFINED, 0, TIFF_SETGET_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FileSource", NULL }, { EXIFTAG_SCENETYPE, 1, 1, TIFF_UNDEFINED, 0, TIFF_SETGET_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SceneType", NULL }, { EXIFTAG_CFAPATTERN, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "CFAPattern", NULL }, { EXIFTAG_CUSTOMRENDERED, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "CustomRendered", NULL }, { EXIFTAG_EXPOSUREMODE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ExposureMode", NULL }, { EXIFTAG_WHITEBALANCE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "WhiteBalance", NULL }, { EXIFTAG_DIGITALZOOMRATIO, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "DigitalZoomRatio", NULL }, { EXIFTAG_FOCALLENGTHIN35MMFILM, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FocalLengthIn35mmFilm", NULL }, { EXIFTAG_SCENECAPTURETYPE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SceneCaptureType", NULL }, { EXIFTAG_GAINCONTROL, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "GainControl", NULL }, { EXIFTAG_CONTRAST, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Contrast", NULL }, { EXIFTAG_SATURATION, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Saturation", NULL }, { EXIFTAG_SHARPNESS, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Sharpness", NULL }, { EXIFTAG_DEVICESETTINGDESCRIPTION, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "DeviceSettingDescription", NULL }, { EXIFTAG_SUBJECTDISTANCERANGE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SubjectDistanceRange", NULL }, { EXIFTAG_IMAGEUNIQUEID, 33, 33, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ImageUniqueID", NULL } }; static const TIFFFieldArray tiffFieldArray = { tfiatImage, 0, TIFFArrayCount(tiffFields), tiffFields }; static const TIFFFieldArray exifFieldArray = { tfiatExif, 0, TIFFArrayCount(exifFields), exifFields }; const TIFFFieldArray* _TIFFGetFields(void) { return(&tiffFieldArray); } const TIFFFieldArray* _TIFFGetExifFields(void) { return(&exifFieldArray); } void _TIFFSetupFields(TIFF* tif, const TIFFFieldArray* fieldarray) { if (tif->tif_fields && tif->tif_nfields > 0) { uint32 i; for (i = 0; i < tif->tif_nfields; i++) { TIFFField *fld = tif->tif_fields[i]; if (fld->field_bit == FIELD_CUSTOM && strncmp("Tag ", fld->field_name, 4) == 0) { _TIFFfree(fld->field_name); _TIFFfree(fld); } } _TIFFfree(tif->tif_fields); tif->tif_fields = NULL; tif->tif_nfields = 0; } if (!_TIFFMergeFields(tif, fieldarray->fields, fieldarray->count)) { TIFFErrorExt(tif->tif_clientdata, "_TIFFSetupFields", "Setting up field info failed"); } } static int tagCompare(const void* a, const void* b) { const TIFFField* ta = *(const TIFFField**) a; const TIFFField* tb = *(const TIFFField**) b; /* NB: be careful of return values for 16-bit platforms */ if (ta->field_tag != tb->field_tag) return (int)ta->field_tag - (int)tb->field_tag; else return (ta->field_type == TIFF_ANY) ? 0 : ((int)tb->field_type - (int)ta->field_type); } static int tagNameCompare(const void* a, const void* b) { const TIFFField* ta = *(const TIFFField**) a; const TIFFField* tb = *(const TIFFField**) b; int ret = strcmp(ta->field_name, tb->field_name); if (ret) return ret; else return (ta->field_type == TIFF_ANY) ? 0 : ((int)tb->field_type - (int)ta->field_type); } int _TIFFMergeFields(TIFF* tif, const TIFFField info[], uint32 n) { const char module[] = "_TIFFMergeFields"; const char reason[] = "for fields array"; TIFFField** tp; uint32 i; tif->tif_foundfield = NULL; if (tif->tif_fields && tif->tif_nfields > 0) { tif->tif_fields = (TIFFField**) _TIFFCheckRealloc(tif, tif->tif_fields, (tif->tif_nfields + n), sizeof(TIFFField *), reason); } else { tif->tif_fields = (TIFFField **) _TIFFCheckMalloc(tif, n, sizeof(TIFFField *), reason); } if (!tif->tif_fields) { TIFFErrorExt(tif->tif_clientdata, module, "Failed to allocate fields array"); return 0; } tp = tif->tif_fields + tif->tif_nfields; for (i = 0; i < n; i++) { const TIFFField *fip = TIFFFindField(tif, info[i].field_tag, TIFF_ANY); /* only add definitions that aren't already present */ if (!fip) { tif->tif_fields[tif->tif_nfields] = (TIFFField *) (info+i); tif->tif_nfields++; } } /* Sort the field info by tag number */ qsort(tif->tif_fields, tif->tif_nfields, sizeof(TIFFField *), tagCompare); return n; } void _TIFFPrintFieldInfo(TIFF* tif, FILE* fd) { uint32 i; fprintf(fd, "%s: \n", tif->tif_name); for (i = 0; i < tif->tif_nfields; i++) { const TIFFField* fip = tif->tif_fields[i]; fprintf(fd, "field[%2d] %5lu, %2d, %2d, %d, %2d, %5s, %5s, %s\n" , (int)i , (unsigned long) fip->field_tag , fip->field_readcount, fip->field_writecount , fip->field_type , fip->field_bit , fip->field_oktochange ? "TRUE" : "FALSE" , fip->field_passcount ? "TRUE" : "FALSE" , fip->field_name ); } } /* * Return size of TIFFDataType in bytes */ int TIFFDataWidth(TIFFDataType type) { switch(type) { case 0: /* nothing */ case TIFF_BYTE: case TIFF_ASCII: case TIFF_SBYTE: case TIFF_UNDEFINED: return 1; case TIFF_SHORT: case TIFF_SSHORT: return 2; case TIFF_LONG: case TIFF_SLONG: case TIFF_FLOAT: case TIFF_IFD: return 4; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_DOUBLE: case TIFF_LONG8: case TIFF_SLONG8: case TIFF_IFD8: return 8; default: return 0; /* will return 0 for unknown types */ } } /* * Return size of TIFFDataType in bytes. * * XXX: We need a separate function to determine the space needed * to store the value. For TIFF_RATIONAL values TIFFDataWidth() returns 8, * but we use 4-byte float to represent rationals. */ int _TIFFDataSize(TIFFDataType type) { switch (type) { case TIFF_BYTE: case TIFF_SBYTE: case TIFF_ASCII: case TIFF_UNDEFINED: return 1; case TIFF_SHORT: case TIFF_SSHORT: return 2; case TIFF_LONG: case TIFF_SLONG: case TIFF_FLOAT: case TIFF_IFD: case TIFF_RATIONAL: case TIFF_SRATIONAL: return 4; case TIFF_DOUBLE: case TIFF_LONG8: case TIFF_SLONG8: case TIFF_IFD8: return 8; default: return 0; } } const TIFFField* TIFFFindField(TIFF* tif, uint32 tag, TIFFDataType dt) { TIFFField key = {0, 0, 0, TIFF_NOTYPE, 0, 0, 0, 0, 0, 0, NULL, NULL}; TIFFField* pkey = &key; const TIFFField **ret; if (tif->tif_foundfield && tif->tif_foundfield->field_tag == tag && (dt == TIFF_ANY || dt == tif->tif_foundfield->field_type)) return tif->tif_foundfield; /* If we are invoked with no field information, then just return. */ if (!tif->tif_fields) return NULL; /* NB: use sorted search (e.g. binary search) */ key.field_tag = tag; key.field_type = dt; ret = (const TIFFField **) bsearch(&pkey, tif->tif_fields, tif->tif_nfields, sizeof(TIFFField *), tagCompare); return tif->tif_foundfield = (ret ? *ret : NULL); } const TIFFField* _TIFFFindFieldByName(TIFF* tif, const char *field_name, TIFFDataType dt) { TIFFField key = {0, 0, 0, TIFF_NOTYPE, 0, 0, 0, 0, 0, 0, NULL, NULL}; TIFFField* pkey = &key; const TIFFField **ret; if (tif->tif_foundfield && streq(tif->tif_foundfield->field_name, field_name) && (dt == TIFF_ANY || dt == tif->tif_foundfield->field_type)) return (tif->tif_foundfield); /* If we are invoked with no field information, then just return. */ if (!tif->tif_fields) return NULL; /* NB: use sorted search (e.g. binary search) */ key.field_name = (char *)field_name; key.field_type = dt; ret = (const TIFFField **) lfind(&pkey, tif->tif_fields, &tif->tif_nfields, sizeof(TIFFField *), tagNameCompare); return tif->tif_foundfield = (ret ? *ret : NULL); } const TIFFField* TIFFFieldWithTag(TIFF* tif, uint32 tag) { const TIFFField* fip = TIFFFindField(tif, tag, TIFF_ANY); if (!fip) { TIFFErrorExt(tif->tif_clientdata, "TIFFFieldWithTag", "Internal error, unknown tag 0x%x", (unsigned int) tag); assert(fip != NULL); /*NOTREACHED*/ } return (fip); } const TIFFField* TIFFFieldWithName(TIFF* tif, const char *field_name) { const TIFFField* fip = _TIFFFindFieldByName(tif, field_name, TIFF_ANY); if (!fip) { TIFFErrorExt(tif->tif_clientdata, "TIFFFieldWithName", "Internal error, unknown tag %s", field_name); assert(fip != NULL); /*NOTREACHED*/ } return (fip); } const TIFFField* _TIFFFindOrRegisterField(TIFF *tif, uint32 tag, TIFFDataType dt) { const TIFFField *fld; fld = TIFFFindField(tif, tag, dt); if (fld == NULL) { fld = _TIFFCreateAnonField(tif, tag, dt); if (!_TIFFMergeFields(tif, fld, 1)) return NULL; } return fld; } TIFFField* _TIFFCreateAnonField(TIFF *tif, uint32 tag, TIFFDataType field_type) { TIFFField *fld; (void) tif; fld = (TIFFField *) _TIFFmalloc(sizeof (TIFFField)); if (fld == NULL) return NULL; _TIFFmemset(fld, 0, sizeof(TIFFField)); fld->field_tag = tag; fld->field_readcount = TIFF_VARIABLE2; fld->field_writecount = TIFF_VARIABLE2; fld->field_type = field_type; fld->reserved = 0; switch (field_type) { case TIFF_BYTE: case TIFF_UNDEFINED: fld->set_field_type = TIFF_SETGET_C32_UINT8; fld->get_field_type = TIFF_SETGET_C32_UINT8; break; case TIFF_ASCII: fld->set_field_type = TIFF_SETGET_C32_ASCII; fld->get_field_type = TIFF_SETGET_C32_ASCII; break; case TIFF_SHORT: fld->set_field_type = TIFF_SETGET_C32_UINT16; fld->get_field_type = TIFF_SETGET_C32_UINT16; break; case TIFF_LONG: fld->set_field_type = TIFF_SETGET_C32_UINT32; fld->get_field_type = TIFF_SETGET_C32_UINT32; break; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: fld->set_field_type = TIFF_SETGET_C32_FLOAT; fld->get_field_type = TIFF_SETGET_C32_FLOAT; break; case TIFF_SBYTE: fld->set_field_type = TIFF_SETGET_C32_SINT8; fld->get_field_type = TIFF_SETGET_C32_SINT8; break; case TIFF_SSHORT: fld->set_field_type = TIFF_SETGET_C32_SINT16; fld->get_field_type = TIFF_SETGET_C32_SINT16; break; case TIFF_SLONG: fld->set_field_type = TIFF_SETGET_C32_SINT32; fld->get_field_type = TIFF_SETGET_C32_SINT32; break; case TIFF_DOUBLE: fld->set_field_type = TIFF_SETGET_C32_DOUBLE; fld->get_field_type = TIFF_SETGET_C32_DOUBLE; break; case TIFF_IFD: case TIFF_IFD8: fld->set_field_type = TIFF_SETGET_C32_IFD8; fld->get_field_type = TIFF_SETGET_C32_IFD8; break; case TIFF_LONG8: fld->set_field_type = TIFF_SETGET_C32_UINT64; fld->get_field_type = TIFF_SETGET_C32_UINT64; break; case TIFF_SLONG8: fld->set_field_type = TIFF_SETGET_C32_SINT64; fld->get_field_type = TIFF_SETGET_C32_SINT64; break; default: fld->set_field_type = TIFF_SETGET_UNDEFINED; fld->get_field_type = TIFF_SETGET_UNDEFINED; break; } fld->field_bit = FIELD_CUSTOM; fld->field_oktochange = TRUE; fld->field_passcount = TRUE; fld->field_name = (char *) _TIFFmalloc(32); if (fld->field_name == NULL) { _TIFFfree(fld); return NULL; } fld->field_subfields = NULL; /* * note that this name is a special sign to TIFFClose() and * _TIFFSetupFields() to free the field */ sprintf(fld->field_name, "Tag %d", (int) tag); return fld; } /**************************************************************************** * O B S O L E T E D I N T E R F A C E S * * Don't use this stuff in your applications, it may be removed in the future * libtiff versions. ****************************************************************************/ static TIFFSetGetFieldType _TIFFSetGetType(TIFFDataType type, short count, unsigned char passcount) { if (type == TIFF_ASCII && count == TIFF_VARIABLE && passcount == 0) return TIFF_SETGET_ASCII; else if (count == 1 && passcount == 0) { switch (type) { case TIFF_BYTE: case TIFF_UNDEFINED: return TIFF_SETGET_UINT8; case TIFF_ASCII: return TIFF_SETGET_ASCII; case TIFF_SHORT: return TIFF_SETGET_UINT16; case TIFF_LONG: return TIFF_SETGET_UINT32; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: return TIFF_SETGET_FLOAT; case TIFF_SBYTE: return TIFF_SETGET_SINT8; case TIFF_SSHORT: return TIFF_SETGET_SINT16; case TIFF_SLONG: return TIFF_SETGET_SINT32; case TIFF_DOUBLE: return TIFF_SETGET_DOUBLE; case TIFF_IFD: case TIFF_IFD8: return TIFF_SETGET_IFD8; case TIFF_LONG8: return TIFF_SETGET_UINT64; case TIFF_SLONG8: return TIFF_SETGET_SINT64; default: return TIFF_SETGET_UNDEFINED; } } else if (count >= 1 && passcount == 0) { switch (type) { case TIFF_BYTE: case TIFF_UNDEFINED: return TIFF_SETGET_C0_UINT8; case TIFF_ASCII: return TIFF_SETGET_C0_ASCII; case TIFF_SHORT: return TIFF_SETGET_C0_UINT16; case TIFF_LONG: return TIFF_SETGET_C0_UINT32; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: return TIFF_SETGET_C0_FLOAT; case TIFF_SBYTE: return TIFF_SETGET_C0_SINT8; case TIFF_SSHORT: return TIFF_SETGET_C0_SINT16; case TIFF_SLONG: return TIFF_SETGET_C0_SINT32; case TIFF_DOUBLE: return TIFF_SETGET_C0_DOUBLE; case TIFF_IFD: case TIFF_IFD8: return TIFF_SETGET_C0_IFD8; case TIFF_LONG8: return TIFF_SETGET_C0_UINT64; case TIFF_SLONG8: return TIFF_SETGET_C0_SINT64; default: return TIFF_SETGET_UNDEFINED; } } else if (count == TIFF_VARIABLE && passcount == 1) { switch (type) { case TIFF_BYTE: case TIFF_UNDEFINED: return TIFF_SETGET_C16_UINT8; case TIFF_ASCII: return TIFF_SETGET_C16_ASCII; case TIFF_SHORT: return TIFF_SETGET_C16_UINT16; case TIFF_LONG: return TIFF_SETGET_C16_UINT32; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: return TIFF_SETGET_C16_FLOAT; case TIFF_SBYTE: return TIFF_SETGET_C16_SINT8; case TIFF_SSHORT: return TIFF_SETGET_C16_SINT16; case TIFF_SLONG: return TIFF_SETGET_C16_SINT32; case TIFF_DOUBLE: return TIFF_SETGET_C16_DOUBLE; case TIFF_IFD: case TIFF_IFD8: return TIFF_SETGET_C16_IFD8; case TIFF_LONG8: return TIFF_SETGET_C16_UINT64; case TIFF_SLONG8: return TIFF_SETGET_C16_SINT64; default: return TIFF_SETGET_UNDEFINED; } } else if (count == TIFF_VARIABLE2 && passcount == 1) { switch (type) { case TIFF_BYTE: case TIFF_UNDEFINED: return TIFF_SETGET_C32_UINT8; case TIFF_ASCII: return TIFF_SETGET_C32_ASCII; case TIFF_SHORT: return TIFF_SETGET_C32_UINT16; case TIFF_LONG: return TIFF_SETGET_C32_UINT32; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: return TIFF_SETGET_C32_FLOAT; case TIFF_SBYTE: return TIFF_SETGET_C32_SINT8; case TIFF_SSHORT: return TIFF_SETGET_C32_SINT16; case TIFF_SLONG: return TIFF_SETGET_C32_SINT32; case TIFF_DOUBLE: return TIFF_SETGET_C32_DOUBLE; case TIFF_IFD: case TIFF_IFD8: return TIFF_SETGET_C32_IFD8; case TIFF_LONG8: return TIFF_SETGET_C32_UINT64; case TIFF_SLONG8: return TIFF_SETGET_C32_SINT64; default: return TIFF_SETGET_UNDEFINED; } } return TIFF_SETGET_UNDEFINED; } int TIFFMergeFieldInfo(TIFF* tif, const TIFFFieldInfo info[], uint32 n) { const char module[] = "TIFFMergeFieldInfo"; const char reason[] = "for fields array"; TIFFField *tp; uint32 i, nfields; if (tif->tif_nfieldscompat > 0) { tif->tif_fieldscompat = (TIFFFieldArray *) _TIFFCheckRealloc(tif, tif->tif_fieldscompat, tif->tif_nfieldscompat + 1, sizeof(TIFFFieldArray), reason); } else { tif->tif_fieldscompat = (TIFFFieldArray *) _TIFFCheckMalloc(tif, 1, sizeof(TIFFFieldArray), reason); } if (!tif->tif_fieldscompat) { TIFFErrorExt(tif->tif_clientdata, module, "Failed to allocate fields array"); return -1; } nfields = tif->tif_nfieldscompat++; tif->tif_fieldscompat[nfields].type = tfiatOther; tif->tif_fieldscompat[nfields].allocated_size = n; tif->tif_fieldscompat[nfields].count = n; tif->tif_fieldscompat[nfields].fields = (TIFFField *)_TIFFCheckMalloc(tif, n, sizeof(TIFFField), reason); if (!tif->tif_fieldscompat[nfields].fields) { TIFFErrorExt(tif->tif_clientdata, module, "Failed to allocate fields array"); return -1; } tp = tif->tif_fieldscompat[nfields].fields; for (i = 0; i < n; i++) { tp->field_tag = info[i].field_tag; tp->field_readcount = info[i].field_readcount; tp->field_writecount = info[i].field_writecount; tp->field_type = info[i].field_type; tp->reserved = 0; tp->set_field_type = _TIFFSetGetType(info[i].field_type, info[i].field_readcount, info[i].field_passcount); tp->get_field_type = _TIFFSetGetType(info[i].field_type, info[i].field_readcount, info[i].field_passcount); tp->field_bit = info[i].field_bit; tp->field_oktochange = info[i].field_oktochange; tp->field_passcount = info[i].field_passcount; tp->field_name = info[i].field_name; tp->field_subfields = NULL; tp++; } if (!_TIFFMergeFields(tif, tif->tif_fieldscompat[nfields].fields, n)) { TIFFErrorExt(tif->tif_clientdata, module, "Setting up field info failed"); return -1; } return 0; } const TIFFFieldInfo* TIFFFindFieldInfoByName(TIFF* tif, const char *field_name, TIFFDataType dt) { #if 0 TIFFFieldInfo key = {0, 0, 0, TIFF_NOTYPE, 0, 0, 0, 0, 0, 0, NULL, NULL}; TIFFFieldInfo* pkey = &key; const TIFFFieldInfo **ret; if (tif->tif_foundfield && streq(tif->tif_foundfield->field_name, field_name) && (dt == TIFF_ANY || dt == tif->tif_foundfield->field_type)) return (tif->tif_foundfield); /* If we are invoked with no field information, then just return. */ if ( !tif->tif_fields ) { return NULL; } /* NB: use sorted search (e.g. binary search) */ key.field_name = (char *)field_name; key.field_type = dt; ret = (const TIFFFieldInfo **) lfind(&pkey, tif->tif_fields, &tif->tif_nfields, sizeof(TIFFFieldInfo *), tagNameCompare); return tif->tif_foundfield = (ret ? *ret : NULL); #endif return NULL; } const TIFFFieldInfo* TIFFFindFieldInfo(TIFF* tif, uint32 tag, TIFFDataType dt) { #if 0 TIFFFieldInfo key = {0, 0, 0, TIFF_NOTYPE, 0, 0, 0, 0, 0, 0, NULL, NULL}; TIFFFieldInfo* pkey = &key; const TIFFFieldInfo **ret; if (tif->tif_foundfield && tif->tif_foundfield->field_tag == tag && (dt == TIFF_ANY || dt == tif->tif_foundfield->field_type)) return tif->tif_foundfield; /* If we are invoked with no field information, then just return. */ if ( !tif->tif_fields ) { return NULL; } /* NB: use sorted search (e.g. binary search) */ key.field_tag = tag; key.field_type = dt; ret = (const TIFFFieldInfo **) bsearch(&pkey, tif->tif_fields, tif->tif_nfields, sizeof(TIFFFieldInfo *), tagCompare); return tif->tif_foundfield = (ret ? *ret : NULL); #endif return NULL; } /* vim: set ts=8 sts=8 sw=8 noet: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/libtiff_2007-08-24-827b6bc-22da1d6.c
manybugs_data_60
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Marcus Boerger <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" #include "ext/standard/php_var.h" #include "ext/standard/php_smart_str.h" #include "zend_interfaces.h" #include "zend_exceptions.h" #include "php_spl.h" #include "spl_functions.h" #include "spl_engine.h" #include "spl_iterators.h" #include "spl_array.h" #include "spl_exceptions.h" zend_object_handlers spl_handler_ArrayObject; PHPAPI zend_class_entry *spl_ce_ArrayObject; zend_object_handlers spl_handler_ArrayIterator; PHPAPI zend_class_entry *spl_ce_ArrayIterator; PHPAPI zend_class_entry *spl_ce_RecursiveArrayIterator; #define SPL_ARRAY_STD_PROP_LIST 0x00000001 #define SPL_ARRAY_ARRAY_AS_PROPS 0x00000002 #define SPL_ARRAY_CHILD_ARRAYS_ONLY 0x00000004 #define SPL_ARRAY_OVERLOADED_REWIND 0x00010000 #define SPL_ARRAY_OVERLOADED_VALID 0x00020000 #define SPL_ARRAY_OVERLOADED_KEY 0x00040000 #define SPL_ARRAY_OVERLOADED_CURRENT 0x00080000 #define SPL_ARRAY_OVERLOADED_NEXT 0x00100000 #define SPL_ARRAY_IS_REF 0x01000000 #define SPL_ARRAY_IS_SELF 0x02000000 #define SPL_ARRAY_USE_OTHER 0x04000000 #define SPL_ARRAY_INT_MASK 0xFFFF0000 #define SPL_ARRAY_CLONE_MASK 0x0300FFFF typedef struct _spl_array_object { zend_object std; zval *array; zval *retval; HashPosition pos; ulong pos_h; int ar_flags; int is_self; zend_function *fptr_offset_get; zend_function *fptr_offset_set; zend_function *fptr_offset_has; zend_function *fptr_offset_del; zend_function *fptr_count; zend_class_entry* ce_get_iterator; HashTable *debug_info; } spl_array_object; static inline HashTable *spl_array_get_hash_table(spl_array_object* intern, int check_std_props TSRMLS_DC) { /* {{{ */ if ((intern->ar_flags & SPL_ARRAY_IS_SELF) != 0) { if (!intern->std.properties) { rebuild_object_properties(&intern->std); } return intern->std.properties; } else if ((intern->ar_flags & SPL_ARRAY_USE_OTHER) && (check_std_props == 0 || (intern->ar_flags & SPL_ARRAY_STD_PROP_LIST) == 0) && Z_TYPE_P(intern->array) == IS_OBJECT) { spl_array_object *other = (spl_array_object*)zend_object_store_get_object(intern->array TSRMLS_CC); return spl_array_get_hash_table(other, check_std_props TSRMLS_CC); } else if ((intern->ar_flags & ((check_std_props ? SPL_ARRAY_STD_PROP_LIST : 0) | SPL_ARRAY_IS_SELF)) != 0) { if (!intern->std.properties) { rebuild_object_properties(&intern->std); } return intern->std.properties; } else { return HASH_OF(intern->array); } } /* }}} */ static void spl_array_rewind(spl_array_object *intern TSRMLS_DC); static void spl_array_update_pos(spl_array_object* intern) /* {{{ */ { Bucket *pos = intern->pos; if (pos != NULL) { intern->pos_h = pos->h; } } /* }}} */ static void spl_array_set_pos(spl_array_object* intern, HashPosition pos) /* {{{ */ { intern->pos = pos; spl_array_update_pos(intern); } /* }}} */ SPL_API int spl_hash_verify_pos_ex(spl_array_object * intern, HashTable * ht TSRMLS_DC) /* {{{ */ { Bucket *p; /* IS_CONSISTENT(ht);*/ /* HASH_PROTECT_RECURSION(ht);*/ p = ht->arBuckets[intern->pos_h & ht->nTableMask]; while (p != NULL) { if (p == intern->pos) { return SUCCESS; } p = p->pNext; } /* HASH_UNPROTECT_RECURSION(ht); */ spl_array_rewind(intern TSRMLS_CC); return FAILURE; } /* }}} */ SPL_API int spl_hash_verify_pos(spl_array_object * intern TSRMLS_DC) /* {{{ */ { HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); return spl_hash_verify_pos_ex(intern, ht TSRMLS_CC); } /* }}} */ /* {{{ spl_array_object_free_storage */ static void spl_array_object_free_storage(void *object TSRMLS_DC) { spl_array_object *intern = (spl_array_object *)object; zend_object_std_dtor(&intern->std TSRMLS_CC); zval_ptr_dtor(&intern->array); zval_ptr_dtor(&intern->retval); if (intern->debug_info != NULL) { zend_hash_destroy(intern->debug_info); efree(intern->debug_info); } efree(object); } /* }}} */ zend_object_iterator *spl_array_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC); /* {{{ spl_array_object_new_ex */ static zend_object_value spl_array_object_new_ex(zend_class_entry *class_type, spl_array_object **obj, zval *orig, int clone_orig TSRMLS_DC) { zend_object_value retval; spl_array_object *intern; zval *tmp; zend_class_entry * parent = class_type; int inherited = 0; intern = emalloc(sizeof(spl_array_object)); memset(intern, 0, sizeof(spl_array_object)); *obj = intern; ALLOC_INIT_ZVAL(intern->retval); zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); intern->ar_flags = 0; intern->debug_info = NULL; intern->ce_get_iterator = spl_ce_ArrayIterator; if (orig) { spl_array_object *other = (spl_array_object*)zend_object_store_get_object(orig TSRMLS_CC); intern->ar_flags &= ~ SPL_ARRAY_CLONE_MASK; intern->ar_flags |= (other->ar_flags & SPL_ARRAY_CLONE_MASK); intern->ce_get_iterator = other->ce_get_iterator; if (clone_orig) { intern->array = other->array; if (Z_OBJ_HT_P(orig) == &spl_handler_ArrayObject) { MAKE_STD_ZVAL(intern->array); array_init(intern->array); zend_hash_copy(HASH_OF(intern->array), HASH_OF(other->array), (copy_ctor_func_t) zval_add_ref, &tmp, sizeof(zval*)); } if (Z_OBJ_HT_P(orig) == &spl_handler_ArrayIterator) { Z_ADDREF_P(other->array); } } else { intern->array = orig; Z_ADDREF_P(intern->array); intern->ar_flags |= SPL_ARRAY_IS_REF | SPL_ARRAY_USE_OTHER; } } else { MAKE_STD_ZVAL(intern->array); array_init(intern->array); intern->ar_flags &= ~SPL_ARRAY_IS_REF; } retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) spl_array_object_free_storage, NULL TSRMLS_CC); while (parent) { if (parent == spl_ce_ArrayIterator || parent == spl_ce_RecursiveArrayIterator) { retval.handlers = &spl_handler_ArrayIterator; class_type->get_iterator = spl_array_get_iterator; break; } else if (parent == spl_ce_ArrayObject) { retval.handlers = &spl_handler_ArrayObject; break; } parent = parent->parent; inherited = 1; } if (!parent) { /* this must never happen */ php_error_docref(NULL TSRMLS_CC, E_COMPILE_ERROR, "Internal compiler error, Class is not child of ArrayObject or ArrayIterator"); } if (inherited) { zend_hash_find(&class_type->function_table, "offsetget", sizeof("offsetget"), (void **) &intern->fptr_offset_get); if (intern->fptr_offset_get->common.scope == parent) { intern->fptr_offset_get = NULL; } zend_hash_find(&class_type->function_table, "offsetset", sizeof("offsetset"), (void **) &intern->fptr_offset_set); if (intern->fptr_offset_set->common.scope == parent) { intern->fptr_offset_set = NULL; } zend_hash_find(&class_type->function_table, "offsetexists", sizeof("offsetexists"), (void **) &intern->fptr_offset_has); if (intern->fptr_offset_has->common.scope == parent) { intern->fptr_offset_has = NULL; } zend_hash_find(&class_type->function_table, "offsetunset", sizeof("offsetunset"), (void **) &intern->fptr_offset_del); if (intern->fptr_offset_del->common.scope == parent) { intern->fptr_offset_del = NULL; } zend_hash_find(&class_type->function_table, "count", sizeof("count"), (void **) &intern->fptr_count); if (intern->fptr_count->common.scope == parent) { intern->fptr_count = NULL; } } /* Cache iterator functions if ArrayIterator or derived. Check current's */ /* cache since only current is always required */ if (retval.handlers == &spl_handler_ArrayIterator) { if (!class_type->iterator_funcs.zf_current) { zend_hash_find(&class_type->function_table, "rewind", sizeof("rewind"), (void **) &class_type->iterator_funcs.zf_rewind); zend_hash_find(&class_type->function_table, "valid", sizeof("valid"), (void **) &class_type->iterator_funcs.zf_valid); zend_hash_find(&class_type->function_table, "key", sizeof("key"), (void **) &class_type->iterator_funcs.zf_key); zend_hash_find(&class_type->function_table, "current", sizeof("current"), (void **) &class_type->iterator_funcs.zf_current); zend_hash_find(&class_type->function_table, "next", sizeof("next"), (void **) &class_type->iterator_funcs.zf_next); } if (inherited) { if (class_type->iterator_funcs.zf_rewind->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_REWIND; if (class_type->iterator_funcs.zf_valid->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_VALID; if (class_type->iterator_funcs.zf_key->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_KEY; if (class_type->iterator_funcs.zf_current->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_CURRENT; if (class_type->iterator_funcs.zf_next->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_NEXT; } } spl_array_rewind(intern TSRMLS_CC); return retval; } /* }}} */ /* {{{ spl_array_object_new */ static zend_object_value spl_array_object_new(zend_class_entry *class_type TSRMLS_DC) { spl_array_object *tmp; return spl_array_object_new_ex(class_type, &tmp, NULL, 0 TSRMLS_CC); } /* }}} */ /* {{{ spl_array_object_clone */ static zend_object_value spl_array_object_clone(zval *zobject TSRMLS_DC) { zend_object_value new_obj_val; zend_object *old_object; zend_object *new_object; zend_object_handle handle = Z_OBJ_HANDLE_P(zobject); spl_array_object *intern; old_object = zend_objects_get_address(zobject TSRMLS_CC); new_obj_val = spl_array_object_new_ex(old_object->ce, &intern, zobject, 1 TSRMLS_CC); new_object = &intern->std; zend_objects_clone_members(new_object, new_obj_val, old_object, handle TSRMLS_CC); return new_obj_val; } /* }}} */ static zval **spl_array_get_dimension_ptr_ptr(int check_inherited, zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); zval **retval; long index; HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); /* We cannot get the pointer pointer so we don't allow it here for now if (check_inherited && intern->fptr_offset_get) { return zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_get, "offsetGet", NULL, offset); }*/ if (!offset) { return &EG(uninitialized_zval_ptr); } if ((type == BP_VAR_W || type == BP_VAR_RW) && (ht->nApplyCount > 0)) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return &EG(uninitialized_zval_ptr);; } switch(Z_TYPE_P(offset)) { case IS_STRING: if (zend_symtable_find(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void **) &retval) == FAILURE) { if (type == BP_VAR_W || type == BP_VAR_RW) { zval *value; ALLOC_INIT_ZVAL(value); zend_symtable_update(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void**)&value, sizeof(void*), NULL); zend_symtable_find(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void **) &retval); return retval; } else { zend_error(E_NOTICE, "Undefined index: %s", Z_STRVAL_P(offset)); return &EG(uninitialized_zval_ptr); } } else { return retval; } case IS_DOUBLE: case IS_RESOURCE: case IS_BOOL: case IS_LONG: if (offset->type == IS_DOUBLE) { index = (long)Z_DVAL_P(offset); } else { index = Z_LVAL_P(offset); } if (zend_hash_index_find(ht, index, (void **) &retval) == FAILURE) { if (type == BP_VAR_W || type == BP_VAR_RW) { zval *value; ALLOC_INIT_ZVAL(value); zend_hash_index_update(ht, index, (void**)&value, sizeof(void*), NULL); zend_hash_index_find(ht, index, (void **) &retval); return retval; } else { zend_error(E_NOTICE, "Undefined offset: %ld", index); return &EG(uninitialized_zval_ptr); } } else { return retval; } break; default: zend_error(E_WARNING, "Illegal offset type"); return &EG(uninitialized_zval_ptr); } } /* }}} */ static zval *spl_array_read_dimension_ex(int check_inherited, zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */ { zval **ret; if (check_inherited) { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (intern->fptr_offset_get) { zval *rv; SEPARATE_ARG_IF_REF(offset); zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_get, "offsetGet", &rv, offset); zval_ptr_dtor(&offset); if (rv) { zval_ptr_dtor(&intern->retval); MAKE_STD_ZVAL(intern->retval); ZVAL_ZVAL(intern->retval, rv, 1, 1); return intern->retval; } return EG(uninitialized_zval_ptr); } } ret = spl_array_get_dimension_ptr_ptr(check_inherited, object, offset, type TSRMLS_CC); /* When in a write context, * ZE has to be fooled into thinking this is in a reference set * by separating (if necessary) and returning as an is_ref=1 zval (even if refcount == 1) */ if ((type == BP_VAR_W || type == BP_VAR_RW) && !Z_ISREF_PP(ret)) { if (Z_REFCOUNT_PP(ret) > 1) { zval *newval; /* Separate */ MAKE_STD_ZVAL(newval); *newval = **ret; zval_copy_ctor(newval); Z_SET_REFCOUNT_P(newval, 1); /* Replace */ Z_DELREF_PP(ret); *ret = newval; } Z_SET_ISREF_PP(ret); } return *ret; } /* }}} */ static zval *spl_array_read_dimension(zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */ { return spl_array_read_dimension_ex(1, object, offset, type TSRMLS_CC); } /* }}} */ static void spl_array_write_dimension_ex(int check_inherited, zval *object, zval *offset, zval *value TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); long index; HashTable *ht; if (check_inherited && intern->fptr_offset_set) { if (!offset) { ALLOC_INIT_ZVAL(offset); } else { SEPARATE_ARG_IF_REF(offset); } zend_call_method_with_2_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_set, "offsetSet", NULL, offset, value); zval_ptr_dtor(&offset); return; } if (!offset) { ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (ht->nApplyCount > 0) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return; } Z_ADDREF_P(value); zend_hash_next_index_insert(ht, (void**)&value, sizeof(void*), NULL); return; } switch(Z_TYPE_P(offset)) { case IS_STRING: ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (ht->nApplyCount > 0) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return; } Z_ADDREF_P(value); zend_symtable_update(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void**)&value, sizeof(void*), NULL); return; case IS_DOUBLE: case IS_RESOURCE: case IS_BOOL: case IS_LONG: ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (ht->nApplyCount > 0) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return; } if (offset->type == IS_DOUBLE) { index = (long)Z_DVAL_P(offset); } else { index = Z_LVAL_P(offset); } Z_ADDREF_P(value); zend_hash_index_update(ht, index, (void**)&value, sizeof(void*), NULL); return; case IS_NULL: ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (ht->nApplyCount > 0) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return; } Z_ADDREF_P(value); zend_hash_next_index_insert(ht, (void**)&value, sizeof(void*), NULL); return; default: zend_error(E_WARNING, "Illegal offset type"); return; } } /* }}} */ static void spl_array_write_dimension(zval *object, zval *offset, zval *value TSRMLS_DC) /* {{{ */ { spl_array_write_dimension_ex(1, object, offset, value TSRMLS_CC); } /* }}} */ static void spl_array_unset_dimension_ex(int check_inherited, zval *object, zval *offset TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); long index; HashTable *ht; if (check_inherited && intern->fptr_offset_del) { SEPARATE_ARG_IF_REF(offset); zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_del, "offsetUnset", NULL, offset); zval_ptr_dtor(&offset); return; } switch(Z_TYPE_P(offset)) { case IS_STRING: ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (ht->nApplyCount > 0) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return; } if (ht == &EG(symbol_table)) { if (zend_delete_global_variable(Z_STRVAL_P(offset), Z_STRLEN_P(offset) TSRMLS_CC)) { zend_error(E_NOTICE,"Undefined index: %s", Z_STRVAL_P(offset)); } } else { if (zend_symtable_del(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1) == FAILURE) { zend_error(E_NOTICE,"Undefined index: %s", Z_STRVAL_P(offset)); } } break; case IS_DOUBLE: case IS_RESOURCE: case IS_BOOL: case IS_LONG: if (offset->type == IS_DOUBLE) { index = (long)Z_DVAL_P(offset); } else { index = Z_LVAL_P(offset); } ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (ht->nApplyCount > 0) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return; } if (zend_hash_index_del(ht, index) == FAILURE) { zend_error(E_NOTICE,"Undefined offset: %ld", Z_LVAL_P(offset)); } break; default: zend_error(E_WARNING, "Illegal offset type"); return; } spl_hash_verify_pos(intern TSRMLS_CC); /* call rewind on FAILURE */ } /* }}} */ static void spl_array_unset_dimension(zval *object, zval *offset TSRMLS_DC) /* {{{ */ { spl_array_unset_dimension_ex(1, object, offset TSRMLS_CC); } /* }}} */ static int spl_array_has_dimension_ex(int check_inherited, zval *object, zval *offset, int check_empty TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); long index; zval *rv, **tmp; if (check_inherited && intern->fptr_offset_has) { SEPARATE_ARG_IF_REF(offset); zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_has, "offsetExists", &rv, offset); zval_ptr_dtor(&offset); if (rv && zend_is_true(rv)) { zval_ptr_dtor(&rv); return 1; } if (rv) { zval_ptr_dtor(&rv); } return 0; } switch(Z_TYPE_P(offset)) { case IS_STRING: if (check_empty) { if (zend_symtable_find(spl_array_get_hash_table(intern, 0 TSRMLS_CC), Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void **) &tmp) != FAILURE) { switch (check_empty) { case 0: return Z_TYPE_PP(tmp) != IS_NULL; case 2: return 1; default: return zend_is_true(*tmp); } } return 0; } else { return zend_symtable_exists(spl_array_get_hash_table(intern, 0 TSRMLS_CC), Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1); } case IS_DOUBLE: case IS_RESOURCE: case IS_BOOL: case IS_LONG: if (offset->type == IS_DOUBLE) { index = (long)Z_DVAL_P(offset); } else { index = Z_LVAL_P(offset); } if (check_empty) { HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_hash_index_find(ht, index, (void **)&tmp) != FAILURE) { switch (check_empty) { case 0: return Z_TYPE_PP(tmp) != IS_NULL; case 2: return 1; default: return zend_is_true(*tmp); } } return 0; } else { return zend_hash_index_exists(spl_array_get_hash_table(intern, 0 TSRMLS_CC), index); } default: zend_error(E_WARNING, "Illegal offset type"); } return 0; } /* }}} */ static int spl_array_has_dimension(zval *object, zval *offset, int check_empty TSRMLS_DC) /* {{{ */ { return spl_array_has_dimension_ex(1, object, offset, check_empty TSRMLS_CC); } /* }}} */ /* {{{ proto bool ArrayObject::offsetExists(mixed $index) proto bool ArrayIterator::offsetExists(mixed $index) Returns whether the requested $index exists. */ SPL_METHOD(Array, offsetExists) { zval *index; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &index) == FAILURE) { return; } RETURN_BOOL(spl_array_has_dimension_ex(0, getThis(), index, 0 TSRMLS_CC)); } /* }}} */ /* {{{ proto mixed ArrayObject::offsetGet(mixed $index) proto mixed ArrayIterator::offsetGet(mixed $index) Returns the value at the specified $index. */ SPL_METHOD(Array, offsetGet) { zval *index, *value; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &index) == FAILURE) { return; } value = spl_array_read_dimension_ex(0, getThis(), index, BP_VAR_R TSRMLS_CC); RETURN_ZVAL(value, 1, 0); } /* }}} */ /* {{{ proto void ArrayObject::offsetSet(mixed $index, mixed $newval) proto void ArrayIterator::offsetSet(mixed $index, mixed $newval) Sets the value at the specified $index to $newval. */ SPL_METHOD(Array, offsetSet) { zval *index, *value; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &index, &value) == FAILURE) { return; } spl_array_write_dimension_ex(0, getThis(), index, value TSRMLS_CC); } /* }}} */ void spl_array_iterator_append(zval *object, zval *append_value TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } if (Z_TYPE_P(intern->array) == IS_OBJECT) { php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "Cannot append properties to objects, use %s::offsetSet() instead", Z_OBJCE_P(object)->name); return; } spl_array_write_dimension(object, NULL, append_value TSRMLS_CC); if (!intern->pos) { spl_array_set_pos(intern, aht->pListTail); } } /* }}} */ /* {{{ proto void ArrayObject::append(mixed $newval) proto void ArrayIterator::append(mixed $newval) Appends the value (cannot be called for objects). */ SPL_METHOD(Array, append) { zval *value; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &value) == FAILURE) { return; } spl_array_iterator_append(getThis(), value TSRMLS_CC); } /* }}} */ /* {{{ proto void ArrayObject::offsetUnset(mixed $index) proto void ArrayIterator::offsetUnset(mixed $index) Unsets the value at the specified $index. */ SPL_METHOD(Array, offsetUnset) { zval *index; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &index) == FAILURE) { return; } spl_array_unset_dimension_ex(0, getThis(), index TSRMLS_CC); } /* }}} */ /* {{{ proto array ArrayObject::getArrayCopy() proto array ArrayIterator::getArrayCopy() Return a copy of the contained array */ SPL_METHOD(Array, getArrayCopy) { zval *object = getThis(), *tmp; spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); array_init(return_value); zend_hash_copy(HASH_OF(return_value), spl_array_get_hash_table(intern, 0 TSRMLS_CC), (copy_ctor_func_t) zval_add_ref, &tmp, sizeof(zval*)); } /* }}} */ static HashTable *spl_array_get_properties(zval *object TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); return spl_array_get_hash_table(intern, 1 TSRMLS_CC); } /* }}} */ static HashTable* spl_array_get_debug_info(zval *obj, int *is_temp TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(obj TSRMLS_CC); zval *tmp, *storage; int name_len; char *zname; zend_class_entry *base; *is_temp = 0; if (!intern->std.properties) { rebuild_object_properties(&intern->std); } if (HASH_OF(intern->array) == intern->std.properties) { return intern->std.properties; } else { if (intern->debug_info == NULL) { ALLOC_HASHTABLE(intern->debug_info); ZEND_INIT_SYMTABLE_EX(intern->debug_info, zend_hash_num_elements(intern->std.properties) + 1, 0); } if (intern->debug_info->nApplyCount == 0) { zend_hash_clean(intern->debug_info); zend_hash_copy(intern->debug_info, intern->std.properties, (copy_ctor_func_t) zval_add_ref, (void *) &tmp, sizeof(zval *)); storage = intern->array; zval_add_ref(&storage); base = (Z_OBJ_HT_P(obj) == &spl_handler_ArrayIterator) ? spl_ce_ArrayIterator : spl_ce_ArrayObject; zname = spl_gen_private_prop_name(base, "storage", sizeof("storage")-1, &name_len TSRMLS_CC); zend_symtable_update(intern->debug_info, zname, name_len+1, &storage, sizeof(zval *), NULL); efree(zname); } return intern->debug_info; } } /* }}} */ static zval *spl_array_read_property(zval *object, zval *member, int type, const zend_literal *key TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0 && !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) { return spl_array_read_dimension(object, member, type TSRMLS_CC); } return std_object_handlers.read_property(object, member, type, key TSRMLS_CC); } /* }}} */ static void spl_array_write_property(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0 && !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) { spl_array_write_dimension(object, member, value TSRMLS_CC); return; } std_object_handlers.write_property(object, member, value, key TSRMLS_CC); } /* }}} */ static zval **spl_array_get_property_ptr_ptr(zval *object, zval *member, const zend_literal *key TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0 && !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) { return spl_array_get_dimension_ptr_ptr(1, object, member, BP_VAR_RW TSRMLS_CC); } return std_object_handlers.get_property_ptr_ptr(object, member, key TSRMLS_CC); } /* }}} */ static int spl_array_has_property(zval *object, zval *member, int has_set_exists, const zend_literal *key TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0 && !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) { return spl_array_has_dimension(object, member, has_set_exists TSRMLS_CC); } return std_object_handlers.has_property(object, member, has_set_exists, key TSRMLS_CC); } /* }}} */ static void spl_array_unset_property(zval *object, zval *member, const zend_literal *key TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0 && !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) { spl_array_unset_dimension(object, member TSRMLS_CC); spl_array_rewind(intern TSRMLS_CC); /* because deletion might invalidate position */ return; } std_object_handlers.unset_property(object, member, key TSRMLS_CC); } /* }}} */ static int spl_array_skip_protected(spl_array_object *intern, HashTable *aht TSRMLS_DC) /* {{{ */ { char *string_key; uint string_length; ulong num_key; if (Z_TYPE_P(intern->array) == IS_OBJECT) { do { if (zend_hash_get_current_key_ex(aht, &string_key, &string_length, &num_key, 0, &intern->pos) == HASH_KEY_IS_STRING) { if (!string_length || string_key[0]) { return SUCCESS; } } else { return SUCCESS; } if (zend_hash_has_more_elements_ex(aht, &intern->pos) != SUCCESS) { return FAILURE; } zend_hash_move_forward_ex(aht, &intern->pos); spl_array_update_pos(intern); } while (1); } return FAILURE; } /* }}} */ static int spl_array_next_no_verify(spl_array_object *intern, HashTable *aht TSRMLS_DC) /* {{{ */ { zend_hash_move_forward_ex(aht, &intern->pos); spl_array_update_pos(intern); if (Z_TYPE_P(intern->array) == IS_OBJECT) { return spl_array_skip_protected(intern, aht TSRMLS_CC); } else { return zend_hash_has_more_elements_ex(aht, &intern->pos); } } /* }}} */ static int spl_array_next_ex(spl_array_object *intern, HashTable *aht TSRMLS_DC) /* {{{ */ { if ((intern->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(intern, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and internal position is no longer valid"); return FAILURE; } return spl_array_next_no_verify(intern, aht TSRMLS_CC); } /* }}} */ static int spl_array_next(spl_array_object *intern TSRMLS_DC) /* {{{ */ { HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); return spl_array_next_ex(intern, aht TSRMLS_CC); } /* }}} */ /* define an overloaded iterator structure */ typedef struct { zend_user_iterator intern; spl_array_object *object; } spl_array_it; static void spl_array_it_dtor(zend_object_iterator *iter TSRMLS_DC) /* {{{ */ { spl_array_it *iterator = (spl_array_it *)iter; zend_user_it_invalidate_current(iter TSRMLS_CC); zval_ptr_dtor((zval**)&iterator->intern.it.data); efree(iterator); } /* }}} */ static int spl_array_it_valid(zend_object_iterator *iter TSRMLS_DC) /* {{{ */ { spl_array_it *iterator = (spl_array_it *)iter; spl_array_object *object = iterator->object; HashTable *aht = spl_array_get_hash_table(object, 0 TSRMLS_CC); if (object->ar_flags & SPL_ARRAY_OVERLOADED_VALID) { return zend_user_it_valid(iter TSRMLS_CC); } else { if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::valid(): Array was modified outside object and is no longer an array"); return FAILURE; } if (object->pos && (object->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(object, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::valid(): Array was modified outside object and internal position is no longer valid"); return FAILURE; } else { return zend_hash_has_more_elements_ex(aht, &object->pos); } } } /* }}} */ static void spl_array_it_get_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC) /* {{{ */ { spl_array_it *iterator = (spl_array_it *)iter; spl_array_object *object = iterator->object; HashTable *aht = spl_array_get_hash_table(object, 0 TSRMLS_CC); if (object->ar_flags & SPL_ARRAY_OVERLOADED_CURRENT) { zend_user_it_get_current_data(iter, data TSRMLS_CC); } else { if (zend_hash_get_current_data_ex(aht, (void**)data, &object->pos) == FAILURE) { *data = NULL; } } } /* }}} */ static int spl_array_it_get_current_key(zend_object_iterator *iter, char **str_key, uint *str_key_len, ulong *int_key TSRMLS_DC) /* {{{ */ { spl_array_it *iterator = (spl_array_it *)iter; spl_array_object *object = iterator->object; HashTable *aht = spl_array_get_hash_table(object, 0 TSRMLS_CC); if (object->ar_flags & SPL_ARRAY_OVERLOADED_KEY) { return zend_user_it_get_current_key(iter, str_key, str_key_len, int_key TSRMLS_CC); } else { if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::current(): Array was modified outside object and is no longer an array"); return HASH_KEY_NON_EXISTANT; } if ((object->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(object, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::current(): Array was modified outside object and internal position is no longer valid"); return HASH_KEY_NON_EXISTANT; } return zend_hash_get_current_key_ex(aht, str_key, str_key_len, int_key, 1, &object->pos); } } /* }}} */ static void spl_array_it_move_forward(zend_object_iterator *iter TSRMLS_DC) /* {{{ */ { spl_array_it *iterator = (spl_array_it *)iter; spl_array_object *object = iterator->object; HashTable *aht = spl_array_get_hash_table(object, 0 TSRMLS_CC); if (object->ar_flags & SPL_ARRAY_OVERLOADED_NEXT) { zend_user_it_move_forward(iter TSRMLS_CC); } else { zend_user_it_invalidate_current(iter TSRMLS_CC); if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::current(): Array was modified outside object and is no longer an array"); return; } if ((object->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(object, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::next(): Array was modified outside object and internal position is no longer valid"); } else { spl_array_next_no_verify(object, aht TSRMLS_CC); } } } /* }}} */ static void spl_array_rewind_ex(spl_array_object *intern, HashTable *aht TSRMLS_DC) /* {{{ */ { zend_hash_internal_pointer_reset_ex(aht, &intern->pos); spl_array_update_pos(intern); spl_array_skip_protected(intern, aht TSRMLS_CC); } /* }}} */ static void spl_array_rewind(spl_array_object *intern TSRMLS_DC) /* {{{ */ { HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::rewind(): Array was modified outside object and is no longer an array"); return; } spl_array_rewind_ex(intern, aht TSRMLS_CC); } /* }}} */ static void spl_array_it_rewind(zend_object_iterator *iter TSRMLS_DC) /* {{{ */ { spl_array_it *iterator = (spl_array_it *)iter; spl_array_object *object = iterator->object; if (object->ar_flags & SPL_ARRAY_OVERLOADED_REWIND) { zend_user_it_rewind(iter TSRMLS_CC); } else { zend_user_it_invalidate_current(iter TSRMLS_CC); spl_array_rewind(object TSRMLS_CC); } } /* }}} */ /* {{{ spl_array_set_array */ static void spl_array_set_array(zval *object, spl_array_object *intern, zval **array, long ar_flags, int just_array TSRMLS_DC) { if (Z_TYPE_PP(array) == IS_ARRAY) { SEPARATE_ZVAL_IF_NOT_REF(array); } if (Z_TYPE_PP(array) == IS_OBJECT && (Z_OBJ_HT_PP(array) == &spl_handler_ArrayObject || Z_OBJ_HT_PP(array) == &spl_handler_ArrayIterator)) { zval_ptr_dtor(&intern->array); if (just_array) { spl_array_object *other = (spl_array_object*)zend_object_store_get_object(*array TSRMLS_CC); ar_flags = other->ar_flags & ~SPL_ARRAY_INT_MASK; } ar_flags |= SPL_ARRAY_USE_OTHER; intern->array = *array; } else { if (Z_TYPE_PP(array) != IS_OBJECT && Z_TYPE_PP(array) != IS_ARRAY) { zend_throw_exception(spl_ce_InvalidArgumentException, "Passed variable is not an array or object, using empty array instead", 0 TSRMLS_CC); return; } zval_ptr_dtor(&intern->array); intern->array = *array; } if (object == *array) { intern->ar_flags |= SPL_ARRAY_IS_SELF; intern->ar_flags &= ~SPL_ARRAY_USE_OTHER; } else { intern->ar_flags &= ~SPL_ARRAY_IS_SELF; } intern->ar_flags |= ar_flags; Z_ADDREF_P(intern->array); if (Z_TYPE_PP(array) == IS_OBJECT) { zend_object_get_properties_t handler = Z_OBJ_HANDLER_PP(array, get_properties); if ((handler != std_object_handlers.get_properties && handler != spl_array_get_properties) || !spl_array_get_hash_table(intern, 0 TSRMLS_CC)) { zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0 TSRMLS_CC, "Overloaded object of type %s is not compatible with %s", Z_OBJCE_PP(array)->name, intern->std.ce->name); } } spl_array_rewind(intern TSRMLS_CC); } /* }}} */ /* iterator handler table */ zend_object_iterator_funcs spl_array_it_funcs = { spl_array_it_dtor, spl_array_it_valid, spl_array_it_get_current_data, spl_array_it_get_current_key, spl_array_it_move_forward, spl_array_it_rewind }; zend_object_iterator *spl_array_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) /* {{{ */ { spl_array_it *iterator; spl_array_object *array_object = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (by_ref && (array_object->ar_flags & SPL_ARRAY_OVERLOADED_CURRENT)) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } iterator = emalloc(sizeof(spl_array_it)); Z_ADDREF_P(object); iterator->intern.it.data = (void*)object; iterator->intern.it.funcs = &spl_array_it_funcs; iterator->intern.ce = ce; iterator->intern.value = NULL; iterator->object = array_object; return (zend_object_iterator*)iterator; } /* }}} */ /* {{{ proto void ArrayObject::__construct(array|object ar = array() [, int flags = 0 [, string iterator_class = "ArrayIterator"]]) proto void ArrayIterator::__construct(array|object ar = array() [, int flags = 0]) Constructs a new array iterator from a path. */ SPL_METHOD(Array, __construct) { zval *object = getThis(); spl_array_object *intern; zval **array; long ar_flags = 0; zend_class_entry *ce_get_iterator = spl_ce_Iterator; zend_error_handling error_handling; if (ZEND_NUM_ARGS() == 0) { return; /* nothing to do */ } zend_replace_error_handling(EH_THROW, spl_ce_InvalidArgumentException, &error_handling TSRMLS_CC); intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z|lC", &array, &ar_flags, &ce_get_iterator) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (ZEND_NUM_ARGS() > 2) { intern->ce_get_iterator = ce_get_iterator; } ar_flags &= ~SPL_ARRAY_INT_MASK; spl_array_set_array(object, intern, array, ar_flags, ZEND_NUM_ARGS() == 1 TSRMLS_CC); zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void ArrayObject::setIteratorClass(string iterator_class) Set the class used in getIterator. */ SPL_METHOD(Array, setIteratorClass) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); zend_class_entry * ce_get_iterator = spl_ce_Iterator; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "C", &ce_get_iterator) == FAILURE) { return; } intern->ce_get_iterator = ce_get_iterator; } /* }}} */ /* {{{ proto string ArrayObject::getIteratorClass() Get the class used in getIterator. */ SPL_METHOD(Array, getIteratorClass) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_STRING(intern->ce_get_iterator->name, 1); } /* }}} */ /* {{{ proto int ArrayObject::getFlags() Get flags */ SPL_METHOD(Array, getFlags) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(intern->ar_flags & ~SPL_ARRAY_INT_MASK); } /* }}} */ /* {{{ proto void ArrayObject::setFlags(int flags) Set flags */ SPL_METHOD(Array, setFlags) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); long ar_flags = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &ar_flags) == FAILURE) { return; } intern->ar_flags = (intern->ar_flags & SPL_ARRAY_INT_MASK) | (ar_flags & ~SPL_ARRAY_INT_MASK); } /* }}} */ /* {{{ proto Array|Object ArrayObject::exchangeArray(Array|Object ar = array()) Replace the referenced array or object with a new one and return the old one (right now copy - to be changed) */ SPL_METHOD(Array, exchangeArray) { zval *object = getThis(), *tmp, **array; spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); array_init(return_value); zend_hash_copy(HASH_OF(return_value), spl_array_get_hash_table(intern, 0 TSRMLS_CC), (copy_ctor_func_t) zval_add_ref, &tmp, sizeof(zval*)); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z", &array) == FAILURE) { return; } spl_array_set_array(object, intern, array, 0L, 1 TSRMLS_CC); } /* }}} */ /* {{{ proto ArrayIterator ArrayObject::getIterator() Create a new iterator from a ArrayObject instance */ SPL_METHOD(Array, getIterator) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); spl_array_object *iterator; HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } return_value->type = IS_OBJECT; return_value->value.obj = spl_array_object_new_ex(intern->ce_get_iterator, &iterator, object, 0 TSRMLS_CC); Z_SET_REFCOUNT_P(return_value, 1); Z_SET_ISREF_P(return_value); } /* }}} */ /* {{{ proto void ArrayIterator::rewind() Rewind array back to the start */ SPL_METHOD(Array, rewind) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } spl_array_rewind(intern TSRMLS_CC); } /* }}} */ /* {{{ proto void ArrayIterator::seek(int $position) Seek to position. */ SPL_METHOD(Array, seek) { long opos, position; zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); int result; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &position) == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } opos = position; if (position >= 0) { /* negative values are not supported */ spl_array_rewind(intern TSRMLS_CC); result = SUCCESS; while (position-- > 0 && (result = spl_array_next(intern TSRMLS_CC)) == SUCCESS); if (result == SUCCESS && zend_hash_has_more_elements_ex(aht, &intern->pos) == SUCCESS) { return; /* ok */ } } zend_throw_exception_ex(spl_ce_OutOfBoundsException, 0 TSRMLS_CC, "Seek position %ld is out of range", opos); } /* }}} */ int static spl_array_object_count_elements_helper(spl_array_object *intern, long *count TSRMLS_DC) /* {{{ */ { HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); HashPosition pos; if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); *count = 0; return FAILURE; } if (Z_TYPE_P(intern->array) == IS_OBJECT) { /* We need to store the 'pos' since we'll modify it in the functions * we're going to call and which do not support 'pos' as parameter. */ pos = intern->pos; *count = 0; spl_array_rewind(intern TSRMLS_CC); while(intern->pos && spl_array_next(intern TSRMLS_CC) == SUCCESS) { (*count)++; } spl_array_set_pos(intern, pos); return SUCCESS; } else { *count = zend_hash_num_elements(aht); return SUCCESS; } } /* }}} */ int spl_array_object_count_elements(zval *object, long *count TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (intern->fptr_count) { zval *rv; zend_call_method_with_0_params(&object, intern->std.ce, &intern->fptr_count, "count", &rv); if (rv) { zval_ptr_dtor(&intern->retval); MAKE_STD_ZVAL(intern->retval); ZVAL_ZVAL(intern->retval, rv, 1, 1); convert_to_long(intern->retval); *count = (long) Z_LVAL_P(intern->retval); return SUCCESS; } *count = 0; return FAILURE; } return spl_array_object_count_elements_helper(intern, count TSRMLS_CC); } /* }}} */ /* {{{ proto int ArrayObject::count() proto int ArrayIterator::count() Return the number of elements in the Iterator. */ SPL_METHOD(Array, count) { long count; spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } spl_array_object_count_elements_helper(intern, &count TSRMLS_CC); RETURN_LONG(count); } /* }}} */ static void spl_array_method(INTERNAL_FUNCTION_PARAMETERS, char *fname, int fname_len, int use_arg) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(getThis() TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); zval *tmp, *arg; zval *retval_ptr = NULL; MAKE_STD_ZVAL(tmp); Z_TYPE_P(tmp) = IS_ARRAY; Z_ARRVAL_P(tmp) = aht; if (use_arg) { if (ZEND_NUM_ARGS() != 1 || zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "z", &arg) == FAILURE) { Z_TYPE_P(tmp) = IS_NULL; zval_ptr_dtor(&tmp); zend_throw_exception(spl_ce_BadMethodCallException, "Function expects exactly one argument", 0 TSRMLS_CC); return; } aht->nApplyCount++; zend_call_method(NULL, NULL, NULL, fname, fname_len, &retval_ptr, 2, tmp, arg TSRMLS_CC); aht->nApplyCount--; } else { aht->nApplyCount++; zend_call_method(NULL, NULL, NULL, fname, fname_len, &retval_ptr, 1, tmp, NULL TSRMLS_CC); aht->nApplyCount--; } Z_TYPE_P(tmp) = IS_NULL; /* we want to destroy the zval, not the hashtable */ zval_ptr_dtor(&tmp); if (retval_ptr) { COPY_PZVAL_TO_ZVAL(*return_value, retval_ptr); } } /* }}} */ #define SPL_ARRAY_METHOD(cname, fname, use_arg) \ SPL_METHOD(cname, fname) \ { \ spl_array_method(INTERNAL_FUNCTION_PARAM_PASSTHRU, #fname, sizeof(#fname)-1, use_arg); \ } /* {{{ proto int ArrayObject::asort() proto int ArrayIterator::asort() Sort the entries by values. */ SPL_ARRAY_METHOD(Array, asort, 0) /* }}} */ /* {{{ proto int ArrayObject::ksort() proto int ArrayIterator::ksort() Sort the entries by key. */ SPL_ARRAY_METHOD(Array, ksort, 0) /* }}} */ /* {{{ proto int ArrayObject::uasort(callback cmp_function) proto int ArrayIterator::uasort(callback cmp_function) Sort the entries by values user defined function. */ SPL_ARRAY_METHOD(Array, uasort, 1) /* }}} */ /* {{{ proto int ArrayObject::uksort(callback cmp_function) proto int ArrayIterator::uksort(callback cmp_function) Sort the entries by key using user defined function. */ SPL_ARRAY_METHOD(Array, uksort, 1) /* }}} */ /* {{{ proto int ArrayObject::natsort() proto int ArrayIterator::natsort() Sort the entries by values using "natural order" algorithm. */ SPL_ARRAY_METHOD(Array, natsort, 0) /* }}} */ /* {{{ proto int ArrayObject::natcasesort() proto int ArrayIterator::natcasesort() Sort the entries by key using case insensitive "natural order" algorithm. */ SPL_ARRAY_METHOD(Array, natcasesort, 0) /* }}} */ /* {{{ proto mixed|NULL ArrayIterator::current() Return current array entry */ SPL_METHOD(Array, current) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); zval **entry; HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } if ((intern->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(intern, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and internal position is no longer valid"); return; } if (zend_hash_get_current_data_ex(aht, (void **) &entry, &intern->pos) == FAILURE) { return; } RETVAL_ZVAL(*entry, 1, 0); } /* }}} */ /* {{{ proto mixed|NULL ArrayIterator::key() Return current array key */ SPL_METHOD(Array, key) { if (zend_parse_parameters_none() == FAILURE) { return; } spl_array_iterator_key(getThis(), return_value TSRMLS_CC); } /* }}} */ void spl_array_iterator_key(zval *object, zval *return_value TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); char *string_key; uint string_length; ulong num_key; HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } if ((intern->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(intern, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and internal position is no longer valid"); return; } switch (zend_hash_get_current_key_ex(aht, &string_key, &string_length, &num_key, 1, &intern->pos)) { case HASH_KEY_IS_STRING: RETVAL_STRINGL(string_key, string_length - 1, 0); break; case HASH_KEY_IS_LONG: RETVAL_LONG(num_key); break; case HASH_KEY_NON_EXISTANT: return; } } /* }}} */ /* {{{ proto void ArrayIterator::next() Move to next entry */ SPL_METHOD(Array, next) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } spl_array_next_ex(intern, aht TSRMLS_CC); } /* }}} */ /* {{{ proto bool ArrayIterator::valid() Check whether array contains more entries */ SPL_METHOD(Array, valid) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } if (intern->pos && (intern->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(intern, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and internal position is no longer valid"); RETURN_FALSE; } else { RETURN_BOOL(zend_hash_has_more_elements_ex(aht, &intern->pos) == SUCCESS); } } /* }}} */ /* {{{ proto bool RecursiveArrayIterator::hasChildren() Check whether current element has children (e.g. is an array) */ SPL_METHOD(Array, hasChildren) { zval *object = getThis(), **entry; spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); RETURN_FALSE; } if ((intern->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(intern, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and internal position is no longer valid"); RETURN_FALSE; } if (zend_hash_get_current_data_ex(aht, (void **) &entry, &intern->pos) == FAILURE) { RETURN_FALSE; } RETURN_BOOL(Z_TYPE_PP(entry) == IS_ARRAY || (Z_TYPE_PP(entry) == IS_OBJECT && (intern->ar_flags & SPL_ARRAY_CHILD_ARRAYS_ONLY) == 0)); } /* }}} */ /* {{{ proto object RecursiveArrayIterator::getChildren() Create a sub iterator for the current element (same class as $this) */ SPL_METHOD(Array, getChildren) { zval *object = getThis(), **entry, *flags; spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } if ((intern->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(intern, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and internal position is no longer valid"); return; } if (zend_hash_get_current_data_ex(aht, (void **) &entry, &intern->pos) == FAILURE) { return; } if (Z_TYPE_PP(entry) == IS_OBJECT) { if ((intern->ar_flags & SPL_ARRAY_CHILD_ARRAYS_ONLY) != 0) { return; } if (instanceof_function(Z_OBJCE_PP(entry), Z_OBJCE_P(getThis()) TSRMLS_CC)) { RETURN_ZVAL(*entry, 0, 0); } } MAKE_STD_ZVAL(flags); ZVAL_LONG(flags, SPL_ARRAY_USE_OTHER | intern->ar_flags); spl_instantiate_arg_ex2(Z_OBJCE_P(getThis()), &return_value, 0, *entry, flags TSRMLS_CC); zval_ptr_dtor(&flags); } /* }}} */ /* {{{ proto string ArrayObject::serialize() Serialize the object */ SPL_METHOD(Array, serialize) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); zval members, *pmembers; php_serialize_data_t var_hash; smart_str buf = {0}; zval *flags; if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } PHP_VAR_SERIALIZE_INIT(var_hash); MAKE_STD_ZVAL(flags); ZVAL_LONG(flags, (intern->ar_flags & SPL_ARRAY_CLONE_MASK)); /* storage */ smart_str_appendl(&buf, "x:", 2); php_var_serialize(&buf, &flags, &var_hash TSRMLS_CC); zval_ptr_dtor(&flags); if (!(intern->ar_flags & SPL_ARRAY_IS_SELF)) { php_var_serialize(&buf, &intern->array, &var_hash TSRMLS_CC); smart_str_appendc(&buf, ';'); } /* members */ smart_str_appendl(&buf, "m:", 2); INIT_PZVAL(&members); if (!intern->std.properties) { rebuild_object_properties(&intern->std); } Z_ARRVAL(members) = intern->std.properties; Z_TYPE(members) = IS_ARRAY; pmembers = &members; php_var_serialize(&buf, &pmembers, &var_hash TSRMLS_CC); /* finishes the string */ /* done */ PHP_VAR_SERIALIZE_DESTROY(var_hash); if (buf.c) { RETURN_STRINGL(buf.c, buf.len, 0); } RETURN_NULL(); } /* }}} */ /* {{{ proto void ArrayObject::unserialize(string serialized) * unserialize the object */ SPL_METHOD(Array, unserialize) { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *buf; int buf_len; const unsigned char *p, *s; php_unserialize_data_t var_hash; zval *pmembers, *pflags = NULL; long flags; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &buf, &buf_len) == FAILURE) { return; } if (buf_len == 0) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Empty serialized string cannot be empty"); return; } /* storage */ s = p = (const unsigned char*)buf; PHP_VAR_UNSERIALIZE_INIT(var_hash); if (*p!= 'x' || *++p != ':') { goto outexcept; } ++p; ALLOC_INIT_ZVAL(pflags); if (!php_var_unserialize(&pflags, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pflags) != IS_LONG) { zval_ptr_dtor(&pflags); goto outexcept; } --p; /* for ';' */ flags = Z_LVAL_P(pflags); zval_ptr_dtor(&pflags); /* flags needs to be verified and we also need to verify whether the next * thing we get is ';'. After that we require an 'm' or somethign else * where 'm' stands for members and anything else should be an array. If * neither 'a' or 'm' follows we have an error. */ if (*p != ';') { goto outexcept; } ++p; if (*p!='m') { if (*p!='a' && *p!='O' && *p!='C') { goto outexcept; } intern->ar_flags &= ~SPL_ARRAY_CLONE_MASK; intern->ar_flags |= flags & SPL_ARRAY_CLONE_MASK; zval_ptr_dtor(&intern->array); ALLOC_INIT_ZVAL(intern->array); if (!php_var_unserialize(&intern->array, &p, s + buf_len, &var_hash TSRMLS_CC)) { goto outexcept; } } if (*p != ';') { goto outexcept; } ++p; /* members */ if (*p!= 'm' || *++p != ':') { goto outexcept; } ++p; ALLOC_INIT_ZVAL(pmembers); if (!php_var_unserialize(&pmembers, &p, s + buf_len, &var_hash TSRMLS_CC)) { zval_ptr_dtor(&pmembers); goto outexcept; } /* copy members */ if (!intern->std.properties) { rebuild_object_properties(&intern->std); } zend_hash_copy(intern->std.properties, Z_ARRVAL_P(pmembers), (copy_ctor_func_t) zval_add_ref, (void *) NULL, sizeof(zval *)); zval_ptr_dtor(&pmembers); /* done reading $serialized */ PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return; outexcept: PHP_VAR_UNSERIALIZE_DESTROY(var_hash); zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Error at offset %ld of %d bytes", (long)((char*)p - buf), buf_len); return; } /* }}} */ /* {{{ arginfo and function tbale */ ZEND_BEGIN_ARG_INFO(arginfo_array___construct, 0) ZEND_ARG_INFO(0, array) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_offsetGet, 0, 0, 1) ZEND_ARG_INFO(0, index) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_offsetSet, 0, 0, 2) ZEND_ARG_INFO(0, index) ZEND_ARG_INFO(0, newval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_append, 0) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_seek, 0) ZEND_ARG_INFO(0, position) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_exchangeArray, 0) ZEND_ARG_INFO(0, array) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_setFlags, 0) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_setIteratorClass, 0) ZEND_ARG_INFO(0, iteratorClass) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_uXsort, 0) ZEND_ARG_INFO(0, cmp_function) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO(arginfo_array_unserialize, 0) ZEND_ARG_INFO(0, serialized) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO(arginfo_array_void, 0) ZEND_END_ARG_INFO() static const zend_function_entry spl_funcs_ArrayObject[] = { SPL_ME(Array, __construct, arginfo_array___construct, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetExists, arginfo_array_offsetGet, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetGet, arginfo_array_offsetGet, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetSet, arginfo_array_offsetSet, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetUnset, arginfo_array_offsetGet, ZEND_ACC_PUBLIC) SPL_ME(Array, append, arginfo_array_append, ZEND_ACC_PUBLIC) SPL_ME(Array, getArrayCopy, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, count, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, getFlags, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, setFlags, arginfo_array_setFlags, ZEND_ACC_PUBLIC) SPL_ME(Array, asort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, ksort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, uasort, arginfo_array_uXsort, ZEND_ACC_PUBLIC) SPL_ME(Array, uksort, arginfo_array_uXsort, ZEND_ACC_PUBLIC) SPL_ME(Array, natsort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, natcasesort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, unserialize, arginfo_array_unserialize, ZEND_ACC_PUBLIC) SPL_ME(Array, serialize, arginfo_array_void, ZEND_ACC_PUBLIC) /* ArrayObject specific */ SPL_ME(Array, getIterator, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, exchangeArray, arginfo_array_exchangeArray, ZEND_ACC_PUBLIC) SPL_ME(Array, setIteratorClass, arginfo_array_setIteratorClass, ZEND_ACC_PUBLIC) SPL_ME(Array, getIteratorClass, arginfo_array_void, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; static const zend_function_entry spl_funcs_ArrayIterator[] = { SPL_ME(Array, __construct, arginfo_array___construct, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetExists, arginfo_array_offsetGet, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetGet, arginfo_array_offsetGet, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetSet, arginfo_array_offsetSet, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetUnset, arginfo_array_offsetGet, ZEND_ACC_PUBLIC) SPL_ME(Array, append, arginfo_array_append, ZEND_ACC_PUBLIC) SPL_ME(Array, getArrayCopy, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, count, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, getFlags, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, setFlags, arginfo_array_setFlags, ZEND_ACC_PUBLIC) SPL_ME(Array, asort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, ksort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, uasort, arginfo_array_uXsort, ZEND_ACC_PUBLIC) SPL_ME(Array, uksort, arginfo_array_uXsort, ZEND_ACC_PUBLIC) SPL_ME(Array, natsort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, natcasesort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, unserialize, arginfo_array_unserialize, ZEND_ACC_PUBLIC) SPL_ME(Array, serialize, arginfo_array_void, ZEND_ACC_PUBLIC) /* ArrayIterator specific */ SPL_ME(Array, rewind, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, current, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, key, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, next, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, valid, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, seek, arginfo_array_seek, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; static const zend_function_entry spl_funcs_RecursiveArrayIterator[] = { SPL_ME(Array, hasChildren, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, getChildren, arginfo_array_void, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; /* }}} */ /* {{{ PHP_MINIT_FUNCTION(spl_array) */ PHP_MINIT_FUNCTION(spl_array) { REGISTER_SPL_STD_CLASS_EX(ArrayObject, spl_array_object_new, spl_funcs_ArrayObject); REGISTER_SPL_IMPLEMENTS(ArrayObject, Aggregate); REGISTER_SPL_IMPLEMENTS(ArrayObject, ArrayAccess); REGISTER_SPL_IMPLEMENTS(ArrayObject, Serializable); memcpy(&spl_handler_ArrayObject, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); spl_handler_ArrayObject.clone_obj = spl_array_object_clone; spl_handler_ArrayObject.read_dimension = spl_array_read_dimension; spl_handler_ArrayObject.write_dimension = spl_array_write_dimension; spl_handler_ArrayObject.unset_dimension = spl_array_unset_dimension; spl_handler_ArrayObject.has_dimension = spl_array_has_dimension; spl_handler_ArrayObject.count_elements = spl_array_object_count_elements; spl_handler_ArrayObject.get_properties = spl_array_get_properties; spl_handler_ArrayObject.get_debug_info = spl_array_get_debug_info; spl_handler_ArrayObject.read_property = spl_array_read_property; spl_handler_ArrayObject.write_property = spl_array_write_property; spl_handler_ArrayObject.get_property_ptr_ptr = spl_array_get_property_ptr_ptr; spl_handler_ArrayObject.has_property = spl_array_has_property; spl_handler_ArrayObject.unset_property = spl_array_unset_property; REGISTER_SPL_STD_CLASS_EX(ArrayIterator, spl_array_object_new, spl_funcs_ArrayIterator); REGISTER_SPL_IMPLEMENTS(ArrayIterator, Iterator); REGISTER_SPL_IMPLEMENTS(ArrayIterator, ArrayAccess); REGISTER_SPL_IMPLEMENTS(ArrayIterator, SeekableIterator); REGISTER_SPL_IMPLEMENTS(ArrayIterator, Serializable); memcpy(&spl_handler_ArrayIterator, &spl_handler_ArrayObject, sizeof(zend_object_handlers)); spl_ce_ArrayIterator->get_iterator = spl_array_get_iterator; REGISTER_SPL_SUB_CLASS_EX(RecursiveArrayIterator, ArrayIterator, spl_array_object_new, spl_funcs_RecursiveArrayIterator); REGISTER_SPL_IMPLEMENTS(RecursiveArrayIterator, RecursiveIterator); spl_ce_RecursiveArrayIterator->get_iterator = spl_array_get_iterator; REGISTER_SPL_IMPLEMENTS(ArrayObject, Countable); REGISTER_SPL_IMPLEMENTS(ArrayIterator, Countable); REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, "STD_PROP_LIST", SPL_ARRAY_STD_PROP_LIST); REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, "ARRAY_AS_PROPS", SPL_ARRAY_ARRAY_AS_PROPS); REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "STD_PROP_LIST", SPL_ARRAY_STD_PROP_LIST); REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "ARRAY_AS_PROPS", SPL_ARRAY_ARRAY_AS_PROPS); REGISTER_SPL_CLASS_CONST_LONG(RecursiveArrayIterator, "CHILD_ARRAYS_ONLY", SPL_ARRAY_CHILD_ARRAYS_ONLY); return SUCCESS; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: fdm=marker * vim: noet sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Marcus Boerger <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" #include "ext/standard/php_var.h" #include "ext/standard/php_smart_str.h" #include "zend_interfaces.h" #include "zend_exceptions.h" #include "php_spl.h" #include "spl_functions.h" #include "spl_engine.h" #include "spl_iterators.h" #include "spl_array.h" #include "spl_exceptions.h" zend_object_handlers spl_handler_ArrayObject; PHPAPI zend_class_entry *spl_ce_ArrayObject; zend_object_handlers spl_handler_ArrayIterator; PHPAPI zend_class_entry *spl_ce_ArrayIterator; PHPAPI zend_class_entry *spl_ce_RecursiveArrayIterator; #define SPL_ARRAY_STD_PROP_LIST 0x00000001 #define SPL_ARRAY_ARRAY_AS_PROPS 0x00000002 #define SPL_ARRAY_CHILD_ARRAYS_ONLY 0x00000004 #define SPL_ARRAY_OVERLOADED_REWIND 0x00010000 #define SPL_ARRAY_OVERLOADED_VALID 0x00020000 #define SPL_ARRAY_OVERLOADED_KEY 0x00040000 #define SPL_ARRAY_OVERLOADED_CURRENT 0x00080000 #define SPL_ARRAY_OVERLOADED_NEXT 0x00100000 #define SPL_ARRAY_IS_REF 0x01000000 #define SPL_ARRAY_IS_SELF 0x02000000 #define SPL_ARRAY_USE_OTHER 0x04000000 #define SPL_ARRAY_INT_MASK 0xFFFF0000 #define SPL_ARRAY_CLONE_MASK 0x0300FFFF typedef struct _spl_array_object { zend_object std; zval *array; zval *retval; HashPosition pos; ulong pos_h; int ar_flags; int is_self; zend_function *fptr_offset_get; zend_function *fptr_offset_set; zend_function *fptr_offset_has; zend_function *fptr_offset_del; zend_function *fptr_count; zend_class_entry* ce_get_iterator; HashTable *debug_info; } spl_array_object; static inline HashTable *spl_array_get_hash_table(spl_array_object* intern, int check_std_props TSRMLS_DC) { /* {{{ */ if ((intern->ar_flags & SPL_ARRAY_IS_SELF) != 0) { if (!intern->std.properties) { rebuild_object_properties(&intern->std); } return intern->std.properties; } else if ((intern->ar_flags & SPL_ARRAY_USE_OTHER) && (check_std_props == 0 || (intern->ar_flags & SPL_ARRAY_STD_PROP_LIST) == 0) && Z_TYPE_P(intern->array) == IS_OBJECT) { spl_array_object *other = (spl_array_object*)zend_object_store_get_object(intern->array TSRMLS_CC); return spl_array_get_hash_table(other, check_std_props TSRMLS_CC); } else if ((intern->ar_flags & ((check_std_props ? SPL_ARRAY_STD_PROP_LIST : 0) | SPL_ARRAY_IS_SELF)) != 0) { if (!intern->std.properties) { rebuild_object_properties(&intern->std); } return intern->std.properties; } else { return HASH_OF(intern->array); } } /* }}} */ static void spl_array_rewind(spl_array_object *intern TSRMLS_DC); static void spl_array_update_pos(spl_array_object* intern) /* {{{ */ { Bucket *pos = intern->pos; if (pos != NULL) { intern->pos_h = pos->h; } } /* }}} */ static void spl_array_set_pos(spl_array_object* intern, HashPosition pos) /* {{{ */ { intern->pos = pos; spl_array_update_pos(intern); } /* }}} */ SPL_API int spl_hash_verify_pos_ex(spl_array_object * intern, HashTable * ht TSRMLS_DC) /* {{{ */ { Bucket *p; /* IS_CONSISTENT(ht);*/ /* HASH_PROTECT_RECURSION(ht);*/ p = ht->arBuckets[intern->pos_h & ht->nTableMask]; while (p != NULL) { if (p == intern->pos) { return SUCCESS; } p = p->pNext; } /* HASH_UNPROTECT_RECURSION(ht); */ spl_array_rewind(intern TSRMLS_CC); return FAILURE; } /* }}} */ SPL_API int spl_hash_verify_pos(spl_array_object * intern TSRMLS_DC) /* {{{ */ { HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); return spl_hash_verify_pos_ex(intern, ht TSRMLS_CC); } /* }}} */ /* {{{ spl_array_object_free_storage */ static void spl_array_object_free_storage(void *object TSRMLS_DC) { spl_array_object *intern = (spl_array_object *)object; zend_object_std_dtor(&intern->std TSRMLS_CC); zval_ptr_dtor(&intern->array); zval_ptr_dtor(&intern->retval); if (intern->debug_info != NULL) { zend_hash_destroy(intern->debug_info); efree(intern->debug_info); } efree(object); } /* }}} */ zend_object_iterator *spl_array_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC); /* {{{ spl_array_object_new_ex */ static zend_object_value spl_array_object_new_ex(zend_class_entry *class_type, spl_array_object **obj, zval *orig, int clone_orig TSRMLS_DC) { zend_object_value retval; spl_array_object *intern; zval *tmp; zend_class_entry * parent = class_type; int inherited = 0; intern = emalloc(sizeof(spl_array_object)); memset(intern, 0, sizeof(spl_array_object)); *obj = intern; ALLOC_INIT_ZVAL(intern->retval); zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); intern->ar_flags = 0; intern->debug_info = NULL; intern->ce_get_iterator = spl_ce_ArrayIterator; if (orig) { spl_array_object *other = (spl_array_object*)zend_object_store_get_object(orig TSRMLS_CC); intern->ar_flags &= ~ SPL_ARRAY_CLONE_MASK; intern->ar_flags |= (other->ar_flags & SPL_ARRAY_CLONE_MASK); intern->ce_get_iterator = other->ce_get_iterator; if (clone_orig) { intern->array = other->array; if (Z_OBJ_HT_P(orig) == &spl_handler_ArrayObject) { MAKE_STD_ZVAL(intern->array); array_init(intern->array); zend_hash_copy(HASH_OF(intern->array), HASH_OF(other->array), (copy_ctor_func_t) zval_add_ref, &tmp, sizeof(zval*)); } if (Z_OBJ_HT_P(orig) == &spl_handler_ArrayIterator) { Z_ADDREF_P(other->array); } } else { intern->array = orig; Z_ADDREF_P(intern->array); intern->ar_flags |= SPL_ARRAY_IS_REF | SPL_ARRAY_USE_OTHER; } } else { MAKE_STD_ZVAL(intern->array); array_init(intern->array); intern->ar_flags &= ~SPL_ARRAY_IS_REF; } retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) spl_array_object_free_storage, NULL TSRMLS_CC); while (parent) { if (parent == spl_ce_ArrayIterator || parent == spl_ce_RecursiveArrayIterator) { retval.handlers = &spl_handler_ArrayIterator; class_type->get_iterator = spl_array_get_iterator; break; } else if (parent == spl_ce_ArrayObject) { retval.handlers = &spl_handler_ArrayObject; break; } parent = parent->parent; inherited = 1; } if (!parent) { /* this must never happen */ php_error_docref(NULL TSRMLS_CC, E_COMPILE_ERROR, "Internal compiler error, Class is not child of ArrayObject or ArrayIterator"); } if (inherited) { zend_hash_find(&class_type->function_table, "offsetget", sizeof("offsetget"), (void **) &intern->fptr_offset_get); if (intern->fptr_offset_get->common.scope == parent) { intern->fptr_offset_get = NULL; } zend_hash_find(&class_type->function_table, "offsetset", sizeof("offsetset"), (void **) &intern->fptr_offset_set); if (intern->fptr_offset_set->common.scope == parent) { intern->fptr_offset_set = NULL; } zend_hash_find(&class_type->function_table, "offsetexists", sizeof("offsetexists"), (void **) &intern->fptr_offset_has); if (intern->fptr_offset_has->common.scope == parent) { intern->fptr_offset_has = NULL; } zend_hash_find(&class_type->function_table, "offsetunset", sizeof("offsetunset"), (void **) &intern->fptr_offset_del); if (intern->fptr_offset_del->common.scope == parent) { intern->fptr_offset_del = NULL; } zend_hash_find(&class_type->function_table, "count", sizeof("count"), (void **) &intern->fptr_count); if (intern->fptr_count->common.scope == parent) { intern->fptr_count = NULL; } } /* Cache iterator functions if ArrayIterator or derived. Check current's */ /* cache since only current is always required */ if (retval.handlers == &spl_handler_ArrayIterator) { if (!class_type->iterator_funcs.zf_current) { zend_hash_find(&class_type->function_table, "rewind", sizeof("rewind"), (void **) &class_type->iterator_funcs.zf_rewind); zend_hash_find(&class_type->function_table, "valid", sizeof("valid"), (void **) &class_type->iterator_funcs.zf_valid); zend_hash_find(&class_type->function_table, "key", sizeof("key"), (void **) &class_type->iterator_funcs.zf_key); zend_hash_find(&class_type->function_table, "current", sizeof("current"), (void **) &class_type->iterator_funcs.zf_current); zend_hash_find(&class_type->function_table, "next", sizeof("next"), (void **) &class_type->iterator_funcs.zf_next); } if (inherited) { if (class_type->iterator_funcs.zf_rewind->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_REWIND; if (class_type->iterator_funcs.zf_valid->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_VALID; if (class_type->iterator_funcs.zf_key->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_KEY; if (class_type->iterator_funcs.zf_current->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_CURRENT; if (class_type->iterator_funcs.zf_next->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_NEXT; } } spl_array_rewind(intern TSRMLS_CC); return retval; } /* }}} */ /* {{{ spl_array_object_new */ static zend_object_value spl_array_object_new(zend_class_entry *class_type TSRMLS_DC) { spl_array_object *tmp; return spl_array_object_new_ex(class_type, &tmp, NULL, 0 TSRMLS_CC); } /* }}} */ /* {{{ spl_array_object_clone */ static zend_object_value spl_array_object_clone(zval *zobject TSRMLS_DC) { zend_object_value new_obj_val; zend_object *old_object; zend_object *new_object; zend_object_handle handle = Z_OBJ_HANDLE_P(zobject); spl_array_object *intern; old_object = zend_objects_get_address(zobject TSRMLS_CC); new_obj_val = spl_array_object_new_ex(old_object->ce, &intern, zobject, 1 TSRMLS_CC); new_object = &intern->std; zend_objects_clone_members(new_object, new_obj_val, old_object, handle TSRMLS_CC); return new_obj_val; } /* }}} */ static zval **spl_array_get_dimension_ptr_ptr(int check_inherited, zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); zval **retval; long index; HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); /* We cannot get the pointer pointer so we don't allow it here for now if (check_inherited && intern->fptr_offset_get) { return zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_get, "offsetGet", NULL, offset); }*/ if (!offset) { return &EG(uninitialized_zval_ptr); } if ((type == BP_VAR_W || type == BP_VAR_RW) && (ht->nApplyCount > 0)) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return &EG(uninitialized_zval_ptr);; } switch(Z_TYPE_P(offset)) { case IS_STRING: if (zend_symtable_find(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void **) &retval) == FAILURE) { if (type == BP_VAR_W || type == BP_VAR_RW) { zval *value; ALLOC_INIT_ZVAL(value); zend_symtable_update(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void**)&value, sizeof(void*), NULL); zend_symtable_find(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void **) &retval); return retval; } else { zend_error(E_NOTICE, "Undefined index: %s", Z_STRVAL_P(offset)); return &EG(uninitialized_zval_ptr); } } else { return retval; } case IS_DOUBLE: case IS_RESOURCE: case IS_BOOL: case IS_LONG: if (offset->type == IS_DOUBLE) { index = (long)Z_DVAL_P(offset); } else { index = Z_LVAL_P(offset); } if (zend_hash_index_find(ht, index, (void **) &retval) == FAILURE) { if (type == BP_VAR_W || type == BP_VAR_RW) { zval *value; ALLOC_INIT_ZVAL(value); zend_hash_index_update(ht, index, (void**)&value, sizeof(void*), NULL); zend_hash_index_find(ht, index, (void **) &retval); return retval; } else { zend_error(E_NOTICE, "Undefined offset: %ld", index); return &EG(uninitialized_zval_ptr); } } else { return retval; } break; default: zend_error(E_WARNING, "Illegal offset type"); return &EG(uninitialized_zval_ptr); } } /* }}} */ static zval *spl_array_read_dimension_ex(int check_inherited, zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */ { zval **ret; if (check_inherited) { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (intern->fptr_offset_get) { zval *rv; SEPARATE_ARG_IF_REF(offset); zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_get, "offsetGet", &rv, offset); zval_ptr_dtor(&offset); if (rv) { zval_ptr_dtor(&intern->retval); MAKE_STD_ZVAL(intern->retval); ZVAL_ZVAL(intern->retval, rv, 1, 1); return intern->retval; } return EG(uninitialized_zval_ptr); } } ret = spl_array_get_dimension_ptr_ptr(check_inherited, object, offset, type TSRMLS_CC); /* When in a write context, * ZE has to be fooled into thinking this is in a reference set * by separating (if necessary) and returning as an is_ref=1 zval (even if refcount == 1) */ if ((type == BP_VAR_W || type == BP_VAR_RW) && !Z_ISREF_PP(ret)) { if (Z_REFCOUNT_PP(ret) > 1) { zval *newval; /* Separate */ MAKE_STD_ZVAL(newval); *newval = **ret; zval_copy_ctor(newval); Z_SET_REFCOUNT_P(newval, 1); /* Replace */ Z_DELREF_PP(ret); *ret = newval; } Z_SET_ISREF_PP(ret); } return *ret; } /* }}} */ static zval *spl_array_read_dimension(zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */ { return spl_array_read_dimension_ex(1, object, offset, type TSRMLS_CC); } /* }}} */ static void spl_array_write_dimension_ex(int check_inherited, zval *object, zval *offset, zval *value TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); long index; HashTable *ht; if (check_inherited && intern->fptr_offset_set) { if (!offset) { ALLOC_INIT_ZVAL(offset); } else { SEPARATE_ARG_IF_REF(offset); } zend_call_method_with_2_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_set, "offsetSet", NULL, offset, value); zval_ptr_dtor(&offset); return; } if (!offset) { ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (ht->nApplyCount > 0) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return; } Z_ADDREF_P(value); zend_hash_next_index_insert(ht, (void**)&value, sizeof(void*), NULL); return; } switch(Z_TYPE_P(offset)) { case IS_STRING: ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (ht->nApplyCount > 0) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return; } Z_ADDREF_P(value); zend_symtable_update(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void**)&value, sizeof(void*), NULL); return; case IS_DOUBLE: case IS_RESOURCE: case IS_BOOL: case IS_LONG: ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (ht->nApplyCount > 0) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return; } if (offset->type == IS_DOUBLE) { index = (long)Z_DVAL_P(offset); } else { index = Z_LVAL_P(offset); } Z_ADDREF_P(value); zend_hash_index_update(ht, index, (void**)&value, sizeof(void*), NULL); return; case IS_NULL: ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (ht->nApplyCount > 0) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return; } Z_ADDREF_P(value); zend_hash_next_index_insert(ht, (void**)&value, sizeof(void*), NULL); return; default: zend_error(E_WARNING, "Illegal offset type"); return; } } /* }}} */ static void spl_array_write_dimension(zval *object, zval *offset, zval *value TSRMLS_DC) /* {{{ */ { spl_array_write_dimension_ex(1, object, offset, value TSRMLS_CC); } /* }}} */ static void spl_array_unset_dimension_ex(int check_inherited, zval *object, zval *offset TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); long index; HashTable *ht; if (check_inherited && intern->fptr_offset_del) { SEPARATE_ARG_IF_REF(offset); zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_del, "offsetUnset", NULL, offset); zval_ptr_dtor(&offset); return; } switch(Z_TYPE_P(offset)) { case IS_STRING: ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (ht->nApplyCount > 0) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return; } if (ht == &EG(symbol_table)) { if (zend_delete_global_variable(Z_STRVAL_P(offset), Z_STRLEN_P(offset) TSRMLS_CC)) { zend_error(E_NOTICE,"Undefined index: %s", Z_STRVAL_P(offset)); } } else { if (zend_symtable_del(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1) == FAILURE) { zend_error(E_NOTICE,"Undefined index: %s", Z_STRVAL_P(offset)); } else { spl_array_object *obj = intern; while (1) { if ((obj->ar_flags & SPL_ARRAY_IS_SELF) != 0) { break; } else if (Z_TYPE_P(obj->array) == IS_OBJECT) { if ((obj->ar_flags & SPL_ARRAY_USE_OTHER) == 0) { obj = (spl_array_object*)zend_object_store_get_object(obj->array TSRMLS_CC); break; } else { obj = (spl_array_object*)zend_object_store_get_object(obj->array TSRMLS_CC); } } else { obj = NULL; break; } } if (obj) { zend_property_info *property_info = zend_get_property_info(obj->std.ce, offset, 1 TSRMLS_CC); if (property_info && (property_info->flags & ZEND_ACC_STATIC) == 0 && property_info->offset >= 0) { obj->std.properties_table[property_info->offset] = NULL; } } } } break; case IS_DOUBLE: case IS_RESOURCE: case IS_BOOL: case IS_LONG: if (offset->type == IS_DOUBLE) { index = (long)Z_DVAL_P(offset); } else { index = Z_LVAL_P(offset); } ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (ht->nApplyCount > 0) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return; } if (zend_hash_index_del(ht, index) == FAILURE) { zend_error(E_NOTICE,"Undefined offset: %ld", Z_LVAL_P(offset)); } break; default: zend_error(E_WARNING, "Illegal offset type"); return; } spl_hash_verify_pos(intern TSRMLS_CC); /* call rewind on FAILURE */ } /* }}} */ static void spl_array_unset_dimension(zval *object, zval *offset TSRMLS_DC) /* {{{ */ { spl_array_unset_dimension_ex(1, object, offset TSRMLS_CC); } /* }}} */ static int spl_array_has_dimension_ex(int check_inherited, zval *object, zval *offset, int check_empty TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); long index; zval *rv, **tmp; if (check_inherited && intern->fptr_offset_has) { SEPARATE_ARG_IF_REF(offset); zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_has, "offsetExists", &rv, offset); zval_ptr_dtor(&offset); if (rv && zend_is_true(rv)) { zval_ptr_dtor(&rv); return 1; } if (rv) { zval_ptr_dtor(&rv); } return 0; } switch(Z_TYPE_P(offset)) { case IS_STRING: if (check_empty) { if (zend_symtable_find(spl_array_get_hash_table(intern, 0 TSRMLS_CC), Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void **) &tmp) != FAILURE) { switch (check_empty) { case 0: return Z_TYPE_PP(tmp) != IS_NULL; case 2: return 1; default: return zend_is_true(*tmp); } } return 0; } else { return zend_symtable_exists(spl_array_get_hash_table(intern, 0 TSRMLS_CC), Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1); } case IS_DOUBLE: case IS_RESOURCE: case IS_BOOL: case IS_LONG: if (offset->type == IS_DOUBLE) { index = (long)Z_DVAL_P(offset); } else { index = Z_LVAL_P(offset); } if (check_empty) { HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_hash_index_find(ht, index, (void **)&tmp) != FAILURE) { switch (check_empty) { case 0: return Z_TYPE_PP(tmp) != IS_NULL; case 2: return 1; default: return zend_is_true(*tmp); } } return 0; } else { return zend_hash_index_exists(spl_array_get_hash_table(intern, 0 TSRMLS_CC), index); } default: zend_error(E_WARNING, "Illegal offset type"); } return 0; } /* }}} */ static int spl_array_has_dimension(zval *object, zval *offset, int check_empty TSRMLS_DC) /* {{{ */ { return spl_array_has_dimension_ex(1, object, offset, check_empty TSRMLS_CC); } /* }}} */ /* {{{ proto bool ArrayObject::offsetExists(mixed $index) proto bool ArrayIterator::offsetExists(mixed $index) Returns whether the requested $index exists. */ SPL_METHOD(Array, offsetExists) { zval *index; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &index) == FAILURE) { return; } RETURN_BOOL(spl_array_has_dimension_ex(0, getThis(), index, 0 TSRMLS_CC)); } /* }}} */ /* {{{ proto mixed ArrayObject::offsetGet(mixed $index) proto mixed ArrayIterator::offsetGet(mixed $index) Returns the value at the specified $index. */ SPL_METHOD(Array, offsetGet) { zval *index, *value; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &index) == FAILURE) { return; } value = spl_array_read_dimension_ex(0, getThis(), index, BP_VAR_R TSRMLS_CC); RETURN_ZVAL(value, 1, 0); } /* }}} */ /* {{{ proto void ArrayObject::offsetSet(mixed $index, mixed $newval) proto void ArrayIterator::offsetSet(mixed $index, mixed $newval) Sets the value at the specified $index to $newval. */ SPL_METHOD(Array, offsetSet) { zval *index, *value; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &index, &value) == FAILURE) { return; } spl_array_write_dimension_ex(0, getThis(), index, value TSRMLS_CC); } /* }}} */ void spl_array_iterator_append(zval *object, zval *append_value TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } if (Z_TYPE_P(intern->array) == IS_OBJECT) { php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "Cannot append properties to objects, use %s::offsetSet() instead", Z_OBJCE_P(object)->name); return; } spl_array_write_dimension(object, NULL, append_value TSRMLS_CC); if (!intern->pos) { spl_array_set_pos(intern, aht->pListTail); } } /* }}} */ /* {{{ proto void ArrayObject::append(mixed $newval) proto void ArrayIterator::append(mixed $newval) Appends the value (cannot be called for objects). */ SPL_METHOD(Array, append) { zval *value; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &value) == FAILURE) { return; } spl_array_iterator_append(getThis(), value TSRMLS_CC); } /* }}} */ /* {{{ proto void ArrayObject::offsetUnset(mixed $index) proto void ArrayIterator::offsetUnset(mixed $index) Unsets the value at the specified $index. */ SPL_METHOD(Array, offsetUnset) { zval *index; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &index) == FAILURE) { return; } spl_array_unset_dimension_ex(0, getThis(), index TSRMLS_CC); } /* }}} */ /* {{{ proto array ArrayObject::getArrayCopy() proto array ArrayIterator::getArrayCopy() Return a copy of the contained array */ SPL_METHOD(Array, getArrayCopy) { zval *object = getThis(), *tmp; spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); array_init(return_value); zend_hash_copy(HASH_OF(return_value), spl_array_get_hash_table(intern, 0 TSRMLS_CC), (copy_ctor_func_t) zval_add_ref, &tmp, sizeof(zval*)); } /* }}} */ static HashTable *spl_array_get_properties(zval *object TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); return spl_array_get_hash_table(intern, 1 TSRMLS_CC); } /* }}} */ static HashTable* spl_array_get_debug_info(zval *obj, int *is_temp TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(obj TSRMLS_CC); zval *tmp, *storage; int name_len; char *zname; zend_class_entry *base; *is_temp = 0; if (!intern->std.properties) { rebuild_object_properties(&intern->std); } if (HASH_OF(intern->array) == intern->std.properties) { return intern->std.properties; } else { if (intern->debug_info == NULL) { ALLOC_HASHTABLE(intern->debug_info); ZEND_INIT_SYMTABLE_EX(intern->debug_info, zend_hash_num_elements(intern->std.properties) + 1, 0); } if (intern->debug_info->nApplyCount == 0) { zend_hash_clean(intern->debug_info); zend_hash_copy(intern->debug_info, intern->std.properties, (copy_ctor_func_t) zval_add_ref, (void *) &tmp, sizeof(zval *)); storage = intern->array; zval_add_ref(&storage); base = (Z_OBJ_HT_P(obj) == &spl_handler_ArrayIterator) ? spl_ce_ArrayIterator : spl_ce_ArrayObject; zname = spl_gen_private_prop_name(base, "storage", sizeof("storage")-1, &name_len TSRMLS_CC); zend_symtable_update(intern->debug_info, zname, name_len+1, &storage, sizeof(zval *), NULL); efree(zname); } return intern->debug_info; } } /* }}} */ static zval *spl_array_read_property(zval *object, zval *member, int type, const zend_literal *key TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0 && !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) { return spl_array_read_dimension(object, member, type TSRMLS_CC); } return std_object_handlers.read_property(object, member, type, key TSRMLS_CC); } /* }}} */ static void spl_array_write_property(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0 && !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) { spl_array_write_dimension(object, member, value TSRMLS_CC); return; } std_object_handlers.write_property(object, member, value, key TSRMLS_CC); } /* }}} */ static zval **spl_array_get_property_ptr_ptr(zval *object, zval *member, const zend_literal *key TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0 && !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) { return spl_array_get_dimension_ptr_ptr(1, object, member, BP_VAR_RW TSRMLS_CC); } return std_object_handlers.get_property_ptr_ptr(object, member, key TSRMLS_CC); } /* }}} */ static int spl_array_has_property(zval *object, zval *member, int has_set_exists, const zend_literal *key TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0 && !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) { return spl_array_has_dimension(object, member, has_set_exists TSRMLS_CC); } return std_object_handlers.has_property(object, member, has_set_exists, key TSRMLS_CC); } /* }}} */ static void spl_array_unset_property(zval *object, zval *member, const zend_literal *key TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0 && !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) { spl_array_unset_dimension(object, member TSRMLS_CC); spl_array_rewind(intern TSRMLS_CC); /* because deletion might invalidate position */ return; } std_object_handlers.unset_property(object, member, key TSRMLS_CC); } /* }}} */ static int spl_array_skip_protected(spl_array_object *intern, HashTable *aht TSRMLS_DC) /* {{{ */ { char *string_key; uint string_length; ulong num_key; if (Z_TYPE_P(intern->array) == IS_OBJECT) { do { if (zend_hash_get_current_key_ex(aht, &string_key, &string_length, &num_key, 0, &intern->pos) == HASH_KEY_IS_STRING) { if (!string_length || string_key[0]) { return SUCCESS; } } else { return SUCCESS; } if (zend_hash_has_more_elements_ex(aht, &intern->pos) != SUCCESS) { return FAILURE; } zend_hash_move_forward_ex(aht, &intern->pos); spl_array_update_pos(intern); } while (1); } return FAILURE; } /* }}} */ static int spl_array_next_no_verify(spl_array_object *intern, HashTable *aht TSRMLS_DC) /* {{{ */ { zend_hash_move_forward_ex(aht, &intern->pos); spl_array_update_pos(intern); if (Z_TYPE_P(intern->array) == IS_OBJECT) { return spl_array_skip_protected(intern, aht TSRMLS_CC); } else { return zend_hash_has_more_elements_ex(aht, &intern->pos); } } /* }}} */ static int spl_array_next_ex(spl_array_object *intern, HashTable *aht TSRMLS_DC) /* {{{ */ { if ((intern->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(intern, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and internal position is no longer valid"); return FAILURE; } return spl_array_next_no_verify(intern, aht TSRMLS_CC); } /* }}} */ static int spl_array_next(spl_array_object *intern TSRMLS_DC) /* {{{ */ { HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); return spl_array_next_ex(intern, aht TSRMLS_CC); } /* }}} */ /* define an overloaded iterator structure */ typedef struct { zend_user_iterator intern; spl_array_object *object; } spl_array_it; static void spl_array_it_dtor(zend_object_iterator *iter TSRMLS_DC) /* {{{ */ { spl_array_it *iterator = (spl_array_it *)iter; zend_user_it_invalidate_current(iter TSRMLS_CC); zval_ptr_dtor((zval**)&iterator->intern.it.data); efree(iterator); } /* }}} */ static int spl_array_it_valid(zend_object_iterator *iter TSRMLS_DC) /* {{{ */ { spl_array_it *iterator = (spl_array_it *)iter; spl_array_object *object = iterator->object; HashTable *aht = spl_array_get_hash_table(object, 0 TSRMLS_CC); if (object->ar_flags & SPL_ARRAY_OVERLOADED_VALID) { return zend_user_it_valid(iter TSRMLS_CC); } else { if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::valid(): Array was modified outside object and is no longer an array"); return FAILURE; } if (object->pos && (object->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(object, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::valid(): Array was modified outside object and internal position is no longer valid"); return FAILURE; } else { return zend_hash_has_more_elements_ex(aht, &object->pos); } } } /* }}} */ static void spl_array_it_get_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC) /* {{{ */ { spl_array_it *iterator = (spl_array_it *)iter; spl_array_object *object = iterator->object; HashTable *aht = spl_array_get_hash_table(object, 0 TSRMLS_CC); if (object->ar_flags & SPL_ARRAY_OVERLOADED_CURRENT) { zend_user_it_get_current_data(iter, data TSRMLS_CC); } else { if (zend_hash_get_current_data_ex(aht, (void**)data, &object->pos) == FAILURE) { *data = NULL; } } } /* }}} */ static int spl_array_it_get_current_key(zend_object_iterator *iter, char **str_key, uint *str_key_len, ulong *int_key TSRMLS_DC) /* {{{ */ { spl_array_it *iterator = (spl_array_it *)iter; spl_array_object *object = iterator->object; HashTable *aht = spl_array_get_hash_table(object, 0 TSRMLS_CC); if (object->ar_flags & SPL_ARRAY_OVERLOADED_KEY) { return zend_user_it_get_current_key(iter, str_key, str_key_len, int_key TSRMLS_CC); } else { if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::current(): Array was modified outside object and is no longer an array"); return HASH_KEY_NON_EXISTANT; } if ((object->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(object, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::current(): Array was modified outside object and internal position is no longer valid"); return HASH_KEY_NON_EXISTANT; } return zend_hash_get_current_key_ex(aht, str_key, str_key_len, int_key, 1, &object->pos); } } /* }}} */ static void spl_array_it_move_forward(zend_object_iterator *iter TSRMLS_DC) /* {{{ */ { spl_array_it *iterator = (spl_array_it *)iter; spl_array_object *object = iterator->object; HashTable *aht = spl_array_get_hash_table(object, 0 TSRMLS_CC); if (object->ar_flags & SPL_ARRAY_OVERLOADED_NEXT) { zend_user_it_move_forward(iter TSRMLS_CC); } else { zend_user_it_invalidate_current(iter TSRMLS_CC); if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::current(): Array was modified outside object and is no longer an array"); return; } if ((object->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(object, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::next(): Array was modified outside object and internal position is no longer valid"); } else { spl_array_next_no_verify(object, aht TSRMLS_CC); } } } /* }}} */ static void spl_array_rewind_ex(spl_array_object *intern, HashTable *aht TSRMLS_DC) /* {{{ */ { zend_hash_internal_pointer_reset_ex(aht, &intern->pos); spl_array_update_pos(intern); spl_array_skip_protected(intern, aht TSRMLS_CC); } /* }}} */ static void spl_array_rewind(spl_array_object *intern TSRMLS_DC) /* {{{ */ { HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::rewind(): Array was modified outside object and is no longer an array"); return; } spl_array_rewind_ex(intern, aht TSRMLS_CC); } /* }}} */ static void spl_array_it_rewind(zend_object_iterator *iter TSRMLS_DC) /* {{{ */ { spl_array_it *iterator = (spl_array_it *)iter; spl_array_object *object = iterator->object; if (object->ar_flags & SPL_ARRAY_OVERLOADED_REWIND) { zend_user_it_rewind(iter TSRMLS_CC); } else { zend_user_it_invalidate_current(iter TSRMLS_CC); spl_array_rewind(object TSRMLS_CC); } } /* }}} */ /* {{{ spl_array_set_array */ static void spl_array_set_array(zval *object, spl_array_object *intern, zval **array, long ar_flags, int just_array TSRMLS_DC) { if (Z_TYPE_PP(array) == IS_ARRAY) { SEPARATE_ZVAL_IF_NOT_REF(array); } if (Z_TYPE_PP(array) == IS_OBJECT && (Z_OBJ_HT_PP(array) == &spl_handler_ArrayObject || Z_OBJ_HT_PP(array) == &spl_handler_ArrayIterator)) { zval_ptr_dtor(&intern->array); if (just_array) { spl_array_object *other = (spl_array_object*)zend_object_store_get_object(*array TSRMLS_CC); ar_flags = other->ar_flags & ~SPL_ARRAY_INT_MASK; } ar_flags |= SPL_ARRAY_USE_OTHER; intern->array = *array; } else { if (Z_TYPE_PP(array) != IS_OBJECT && Z_TYPE_PP(array) != IS_ARRAY) { zend_throw_exception(spl_ce_InvalidArgumentException, "Passed variable is not an array or object, using empty array instead", 0 TSRMLS_CC); return; } zval_ptr_dtor(&intern->array); intern->array = *array; } if (object == *array) { intern->ar_flags |= SPL_ARRAY_IS_SELF; intern->ar_flags &= ~SPL_ARRAY_USE_OTHER; } else { intern->ar_flags &= ~SPL_ARRAY_IS_SELF; } intern->ar_flags |= ar_flags; Z_ADDREF_P(intern->array); if (Z_TYPE_PP(array) == IS_OBJECT) { zend_object_get_properties_t handler = Z_OBJ_HANDLER_PP(array, get_properties); if ((handler != std_object_handlers.get_properties && handler != spl_array_get_properties) || !spl_array_get_hash_table(intern, 0 TSRMLS_CC)) { zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0 TSRMLS_CC, "Overloaded object of type %s is not compatible with %s", Z_OBJCE_PP(array)->name, intern->std.ce->name); } } spl_array_rewind(intern TSRMLS_CC); } /* }}} */ /* iterator handler table */ zend_object_iterator_funcs spl_array_it_funcs = { spl_array_it_dtor, spl_array_it_valid, spl_array_it_get_current_data, spl_array_it_get_current_key, spl_array_it_move_forward, spl_array_it_rewind }; zend_object_iterator *spl_array_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) /* {{{ */ { spl_array_it *iterator; spl_array_object *array_object = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (by_ref && (array_object->ar_flags & SPL_ARRAY_OVERLOADED_CURRENT)) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } iterator = emalloc(sizeof(spl_array_it)); Z_ADDREF_P(object); iterator->intern.it.data = (void*)object; iterator->intern.it.funcs = &spl_array_it_funcs; iterator->intern.ce = ce; iterator->intern.value = NULL; iterator->object = array_object; return (zend_object_iterator*)iterator; } /* }}} */ /* {{{ proto void ArrayObject::__construct(array|object ar = array() [, int flags = 0 [, string iterator_class = "ArrayIterator"]]) proto void ArrayIterator::__construct(array|object ar = array() [, int flags = 0]) Constructs a new array iterator from a path. */ SPL_METHOD(Array, __construct) { zval *object = getThis(); spl_array_object *intern; zval **array; long ar_flags = 0; zend_class_entry *ce_get_iterator = spl_ce_Iterator; zend_error_handling error_handling; if (ZEND_NUM_ARGS() == 0) { return; /* nothing to do */ } zend_replace_error_handling(EH_THROW, spl_ce_InvalidArgumentException, &error_handling TSRMLS_CC); intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z|lC", &array, &ar_flags, &ce_get_iterator) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (ZEND_NUM_ARGS() > 2) { intern->ce_get_iterator = ce_get_iterator; } ar_flags &= ~SPL_ARRAY_INT_MASK; spl_array_set_array(object, intern, array, ar_flags, ZEND_NUM_ARGS() == 1 TSRMLS_CC); zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void ArrayObject::setIteratorClass(string iterator_class) Set the class used in getIterator. */ SPL_METHOD(Array, setIteratorClass) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); zend_class_entry * ce_get_iterator = spl_ce_Iterator; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "C", &ce_get_iterator) == FAILURE) { return; } intern->ce_get_iterator = ce_get_iterator; } /* }}} */ /* {{{ proto string ArrayObject::getIteratorClass() Get the class used in getIterator. */ SPL_METHOD(Array, getIteratorClass) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_STRING(intern->ce_get_iterator->name, 1); } /* }}} */ /* {{{ proto int ArrayObject::getFlags() Get flags */ SPL_METHOD(Array, getFlags) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(intern->ar_flags & ~SPL_ARRAY_INT_MASK); } /* }}} */ /* {{{ proto void ArrayObject::setFlags(int flags) Set flags */ SPL_METHOD(Array, setFlags) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); long ar_flags = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &ar_flags) == FAILURE) { return; } intern->ar_flags = (intern->ar_flags & SPL_ARRAY_INT_MASK) | (ar_flags & ~SPL_ARRAY_INT_MASK); } /* }}} */ /* {{{ proto Array|Object ArrayObject::exchangeArray(Array|Object ar = array()) Replace the referenced array or object with a new one and return the old one (right now copy - to be changed) */ SPL_METHOD(Array, exchangeArray) { zval *object = getThis(), *tmp, **array; spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); array_init(return_value); zend_hash_copy(HASH_OF(return_value), spl_array_get_hash_table(intern, 0 TSRMLS_CC), (copy_ctor_func_t) zval_add_ref, &tmp, sizeof(zval*)); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z", &array) == FAILURE) { return; } spl_array_set_array(object, intern, array, 0L, 1 TSRMLS_CC); } /* }}} */ /* {{{ proto ArrayIterator ArrayObject::getIterator() Create a new iterator from a ArrayObject instance */ SPL_METHOD(Array, getIterator) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); spl_array_object *iterator; HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } return_value->type = IS_OBJECT; return_value->value.obj = spl_array_object_new_ex(intern->ce_get_iterator, &iterator, object, 0 TSRMLS_CC); Z_SET_REFCOUNT_P(return_value, 1); Z_SET_ISREF_P(return_value); } /* }}} */ /* {{{ proto void ArrayIterator::rewind() Rewind array back to the start */ SPL_METHOD(Array, rewind) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } spl_array_rewind(intern TSRMLS_CC); } /* }}} */ /* {{{ proto void ArrayIterator::seek(int $position) Seek to position. */ SPL_METHOD(Array, seek) { long opos, position; zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); int result; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &position) == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } opos = position; if (position >= 0) { /* negative values are not supported */ spl_array_rewind(intern TSRMLS_CC); result = SUCCESS; while (position-- > 0 && (result = spl_array_next(intern TSRMLS_CC)) == SUCCESS); if (result == SUCCESS && zend_hash_has_more_elements_ex(aht, &intern->pos) == SUCCESS) { return; /* ok */ } } zend_throw_exception_ex(spl_ce_OutOfBoundsException, 0 TSRMLS_CC, "Seek position %ld is out of range", opos); } /* }}} */ int static spl_array_object_count_elements_helper(spl_array_object *intern, long *count TSRMLS_DC) /* {{{ */ { HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); HashPosition pos; if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); *count = 0; return FAILURE; } if (Z_TYPE_P(intern->array) == IS_OBJECT) { /* We need to store the 'pos' since we'll modify it in the functions * we're going to call and which do not support 'pos' as parameter. */ pos = intern->pos; *count = 0; spl_array_rewind(intern TSRMLS_CC); while(intern->pos && spl_array_next(intern TSRMLS_CC) == SUCCESS) { (*count)++; } spl_array_set_pos(intern, pos); return SUCCESS; } else { *count = zend_hash_num_elements(aht); return SUCCESS; } } /* }}} */ int spl_array_object_count_elements(zval *object, long *count TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (intern->fptr_count) { zval *rv; zend_call_method_with_0_params(&object, intern->std.ce, &intern->fptr_count, "count", &rv); if (rv) { zval_ptr_dtor(&intern->retval); MAKE_STD_ZVAL(intern->retval); ZVAL_ZVAL(intern->retval, rv, 1, 1); convert_to_long(intern->retval); *count = (long) Z_LVAL_P(intern->retval); return SUCCESS; } *count = 0; return FAILURE; } return spl_array_object_count_elements_helper(intern, count TSRMLS_CC); } /* }}} */ /* {{{ proto int ArrayObject::count() proto int ArrayIterator::count() Return the number of elements in the Iterator. */ SPL_METHOD(Array, count) { long count; spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } spl_array_object_count_elements_helper(intern, &count TSRMLS_CC); RETURN_LONG(count); } /* }}} */ static void spl_array_method(INTERNAL_FUNCTION_PARAMETERS, char *fname, int fname_len, int use_arg) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(getThis() TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); zval *tmp, *arg; zval *retval_ptr = NULL; MAKE_STD_ZVAL(tmp); Z_TYPE_P(tmp) = IS_ARRAY; Z_ARRVAL_P(tmp) = aht; if (use_arg) { if (ZEND_NUM_ARGS() != 1 || zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "z", &arg) == FAILURE) { Z_TYPE_P(tmp) = IS_NULL; zval_ptr_dtor(&tmp); zend_throw_exception(spl_ce_BadMethodCallException, "Function expects exactly one argument", 0 TSRMLS_CC); return; } aht->nApplyCount++; zend_call_method(NULL, NULL, NULL, fname, fname_len, &retval_ptr, 2, tmp, arg TSRMLS_CC); aht->nApplyCount--; } else { aht->nApplyCount++; zend_call_method(NULL, NULL, NULL, fname, fname_len, &retval_ptr, 1, tmp, NULL TSRMLS_CC); aht->nApplyCount--; } Z_TYPE_P(tmp) = IS_NULL; /* we want to destroy the zval, not the hashtable */ zval_ptr_dtor(&tmp); if (retval_ptr) { COPY_PZVAL_TO_ZVAL(*return_value, retval_ptr); } } /* }}} */ #define SPL_ARRAY_METHOD(cname, fname, use_arg) \ SPL_METHOD(cname, fname) \ { \ spl_array_method(INTERNAL_FUNCTION_PARAM_PASSTHRU, #fname, sizeof(#fname)-1, use_arg); \ } /* {{{ proto int ArrayObject::asort() proto int ArrayIterator::asort() Sort the entries by values. */ SPL_ARRAY_METHOD(Array, asort, 0) /* }}} */ /* {{{ proto int ArrayObject::ksort() proto int ArrayIterator::ksort() Sort the entries by key. */ SPL_ARRAY_METHOD(Array, ksort, 0) /* }}} */ /* {{{ proto int ArrayObject::uasort(callback cmp_function) proto int ArrayIterator::uasort(callback cmp_function) Sort the entries by values user defined function. */ SPL_ARRAY_METHOD(Array, uasort, 1) /* }}} */ /* {{{ proto int ArrayObject::uksort(callback cmp_function) proto int ArrayIterator::uksort(callback cmp_function) Sort the entries by key using user defined function. */ SPL_ARRAY_METHOD(Array, uksort, 1) /* }}} */ /* {{{ proto int ArrayObject::natsort() proto int ArrayIterator::natsort() Sort the entries by values using "natural order" algorithm. */ SPL_ARRAY_METHOD(Array, natsort, 0) /* }}} */ /* {{{ proto int ArrayObject::natcasesort() proto int ArrayIterator::natcasesort() Sort the entries by key using case insensitive "natural order" algorithm. */ SPL_ARRAY_METHOD(Array, natcasesort, 0) /* }}} */ /* {{{ proto mixed|NULL ArrayIterator::current() Return current array entry */ SPL_METHOD(Array, current) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); zval **entry; HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } if ((intern->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(intern, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and internal position is no longer valid"); return; } if (zend_hash_get_current_data_ex(aht, (void **) &entry, &intern->pos) == FAILURE) { return; } RETVAL_ZVAL(*entry, 1, 0); } /* }}} */ /* {{{ proto mixed|NULL ArrayIterator::key() Return current array key */ SPL_METHOD(Array, key) { if (zend_parse_parameters_none() == FAILURE) { return; } spl_array_iterator_key(getThis(), return_value TSRMLS_CC); } /* }}} */ void spl_array_iterator_key(zval *object, zval *return_value TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); char *string_key; uint string_length; ulong num_key; HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } if ((intern->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(intern, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and internal position is no longer valid"); return; } switch (zend_hash_get_current_key_ex(aht, &string_key, &string_length, &num_key, 1, &intern->pos)) { case HASH_KEY_IS_STRING: RETVAL_STRINGL(string_key, string_length - 1, 0); break; case HASH_KEY_IS_LONG: RETVAL_LONG(num_key); break; case HASH_KEY_NON_EXISTANT: return; } } /* }}} */ /* {{{ proto void ArrayIterator::next() Move to next entry */ SPL_METHOD(Array, next) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } spl_array_next_ex(intern, aht TSRMLS_CC); } /* }}} */ /* {{{ proto bool ArrayIterator::valid() Check whether array contains more entries */ SPL_METHOD(Array, valid) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } if (intern->pos && (intern->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(intern, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and internal position is no longer valid"); RETURN_FALSE; } else { RETURN_BOOL(zend_hash_has_more_elements_ex(aht, &intern->pos) == SUCCESS); } } /* }}} */ /* {{{ proto bool RecursiveArrayIterator::hasChildren() Check whether current element has children (e.g. is an array) */ SPL_METHOD(Array, hasChildren) { zval *object = getThis(), **entry; spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); RETURN_FALSE; } if ((intern->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(intern, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and internal position is no longer valid"); RETURN_FALSE; } if (zend_hash_get_current_data_ex(aht, (void **) &entry, &intern->pos) == FAILURE) { RETURN_FALSE; } RETURN_BOOL(Z_TYPE_PP(entry) == IS_ARRAY || (Z_TYPE_PP(entry) == IS_OBJECT && (intern->ar_flags & SPL_ARRAY_CHILD_ARRAYS_ONLY) == 0)); } /* }}} */ /* {{{ proto object RecursiveArrayIterator::getChildren() Create a sub iterator for the current element (same class as $this) */ SPL_METHOD(Array, getChildren) { zval *object = getThis(), **entry, *flags; spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } if ((intern->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(intern, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and internal position is no longer valid"); return; } if (zend_hash_get_current_data_ex(aht, (void **) &entry, &intern->pos) == FAILURE) { return; } if (Z_TYPE_PP(entry) == IS_OBJECT) { if ((intern->ar_flags & SPL_ARRAY_CHILD_ARRAYS_ONLY) != 0) { return; } if (instanceof_function(Z_OBJCE_PP(entry), Z_OBJCE_P(getThis()) TSRMLS_CC)) { RETURN_ZVAL(*entry, 0, 0); } } MAKE_STD_ZVAL(flags); ZVAL_LONG(flags, SPL_ARRAY_USE_OTHER | intern->ar_flags); spl_instantiate_arg_ex2(Z_OBJCE_P(getThis()), &return_value, 0, *entry, flags TSRMLS_CC); zval_ptr_dtor(&flags); } /* }}} */ /* {{{ proto string ArrayObject::serialize() Serialize the object */ SPL_METHOD(Array, serialize) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); zval members, *pmembers; php_serialize_data_t var_hash; smart_str buf = {0}; zval *flags; if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } PHP_VAR_SERIALIZE_INIT(var_hash); MAKE_STD_ZVAL(flags); ZVAL_LONG(flags, (intern->ar_flags & SPL_ARRAY_CLONE_MASK)); /* storage */ smart_str_appendl(&buf, "x:", 2); php_var_serialize(&buf, &flags, &var_hash TSRMLS_CC); zval_ptr_dtor(&flags); if (!(intern->ar_flags & SPL_ARRAY_IS_SELF)) { php_var_serialize(&buf, &intern->array, &var_hash TSRMLS_CC); smart_str_appendc(&buf, ';'); } /* members */ smart_str_appendl(&buf, "m:", 2); INIT_PZVAL(&members); if (!intern->std.properties) { rebuild_object_properties(&intern->std); } Z_ARRVAL(members) = intern->std.properties; Z_TYPE(members) = IS_ARRAY; pmembers = &members; php_var_serialize(&buf, &pmembers, &var_hash TSRMLS_CC); /* finishes the string */ /* done */ PHP_VAR_SERIALIZE_DESTROY(var_hash); if (buf.c) { RETURN_STRINGL(buf.c, buf.len, 0); } RETURN_NULL(); } /* }}} */ /* {{{ proto void ArrayObject::unserialize(string serialized) * unserialize the object */ SPL_METHOD(Array, unserialize) { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *buf; int buf_len; const unsigned char *p, *s; php_unserialize_data_t var_hash; zval *pmembers, *pflags = NULL; long flags; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &buf, &buf_len) == FAILURE) { return; } if (buf_len == 0) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Empty serialized string cannot be empty"); return; } /* storage */ s = p = (const unsigned char*)buf; PHP_VAR_UNSERIALIZE_INIT(var_hash); if (*p!= 'x' || *++p != ':') { goto outexcept; } ++p; ALLOC_INIT_ZVAL(pflags); if (!php_var_unserialize(&pflags, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pflags) != IS_LONG) { zval_ptr_dtor(&pflags); goto outexcept; } --p; /* for ';' */ flags = Z_LVAL_P(pflags); zval_ptr_dtor(&pflags); /* flags needs to be verified and we also need to verify whether the next * thing we get is ';'. After that we require an 'm' or somethign else * where 'm' stands for members and anything else should be an array. If * neither 'a' or 'm' follows we have an error. */ if (*p != ';') { goto outexcept; } ++p; if (*p!='m') { if (*p!='a' && *p!='O' && *p!='C') { goto outexcept; } intern->ar_flags &= ~SPL_ARRAY_CLONE_MASK; intern->ar_flags |= flags & SPL_ARRAY_CLONE_MASK; zval_ptr_dtor(&intern->array); ALLOC_INIT_ZVAL(intern->array); if (!php_var_unserialize(&intern->array, &p, s + buf_len, &var_hash TSRMLS_CC)) { goto outexcept; } } if (*p != ';') { goto outexcept; } ++p; /* members */ if (*p!= 'm' || *++p != ':') { goto outexcept; } ++p; ALLOC_INIT_ZVAL(pmembers); if (!php_var_unserialize(&pmembers, &p, s + buf_len, &var_hash TSRMLS_CC)) { zval_ptr_dtor(&pmembers); goto outexcept; } /* copy members */ if (!intern->std.properties) { rebuild_object_properties(&intern->std); } zend_hash_copy(intern->std.properties, Z_ARRVAL_P(pmembers), (copy_ctor_func_t) zval_add_ref, (void *) NULL, sizeof(zval *)); zval_ptr_dtor(&pmembers); /* done reading $serialized */ PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return; outexcept: PHP_VAR_UNSERIALIZE_DESTROY(var_hash); zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Error at offset %ld of %d bytes", (long)((char*)p - buf), buf_len); return; } /* }}} */ /* {{{ arginfo and function tbale */ ZEND_BEGIN_ARG_INFO(arginfo_array___construct, 0) ZEND_ARG_INFO(0, array) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_offsetGet, 0, 0, 1) ZEND_ARG_INFO(0, index) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_offsetSet, 0, 0, 2) ZEND_ARG_INFO(0, index) ZEND_ARG_INFO(0, newval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_append, 0) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_seek, 0) ZEND_ARG_INFO(0, position) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_exchangeArray, 0) ZEND_ARG_INFO(0, array) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_setFlags, 0) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_setIteratorClass, 0) ZEND_ARG_INFO(0, iteratorClass) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_uXsort, 0) ZEND_ARG_INFO(0, cmp_function) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO(arginfo_array_unserialize, 0) ZEND_ARG_INFO(0, serialized) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO(arginfo_array_void, 0) ZEND_END_ARG_INFO() static const zend_function_entry spl_funcs_ArrayObject[] = { SPL_ME(Array, __construct, arginfo_array___construct, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetExists, arginfo_array_offsetGet, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetGet, arginfo_array_offsetGet, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetSet, arginfo_array_offsetSet, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetUnset, arginfo_array_offsetGet, ZEND_ACC_PUBLIC) SPL_ME(Array, append, arginfo_array_append, ZEND_ACC_PUBLIC) SPL_ME(Array, getArrayCopy, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, count, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, getFlags, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, setFlags, arginfo_array_setFlags, ZEND_ACC_PUBLIC) SPL_ME(Array, asort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, ksort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, uasort, arginfo_array_uXsort, ZEND_ACC_PUBLIC) SPL_ME(Array, uksort, arginfo_array_uXsort, ZEND_ACC_PUBLIC) SPL_ME(Array, natsort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, natcasesort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, unserialize, arginfo_array_unserialize, ZEND_ACC_PUBLIC) SPL_ME(Array, serialize, arginfo_array_void, ZEND_ACC_PUBLIC) /* ArrayObject specific */ SPL_ME(Array, getIterator, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, exchangeArray, arginfo_array_exchangeArray, ZEND_ACC_PUBLIC) SPL_ME(Array, setIteratorClass, arginfo_array_setIteratorClass, ZEND_ACC_PUBLIC) SPL_ME(Array, getIteratorClass, arginfo_array_void, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; static const zend_function_entry spl_funcs_ArrayIterator[] = { SPL_ME(Array, __construct, arginfo_array___construct, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetExists, arginfo_array_offsetGet, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetGet, arginfo_array_offsetGet, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetSet, arginfo_array_offsetSet, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetUnset, arginfo_array_offsetGet, ZEND_ACC_PUBLIC) SPL_ME(Array, append, arginfo_array_append, ZEND_ACC_PUBLIC) SPL_ME(Array, getArrayCopy, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, count, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, getFlags, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, setFlags, arginfo_array_setFlags, ZEND_ACC_PUBLIC) SPL_ME(Array, asort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, ksort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, uasort, arginfo_array_uXsort, ZEND_ACC_PUBLIC) SPL_ME(Array, uksort, arginfo_array_uXsort, ZEND_ACC_PUBLIC) SPL_ME(Array, natsort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, natcasesort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, unserialize, arginfo_array_unserialize, ZEND_ACC_PUBLIC) SPL_ME(Array, serialize, arginfo_array_void, ZEND_ACC_PUBLIC) /* ArrayIterator specific */ SPL_ME(Array, rewind, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, current, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, key, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, next, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, valid, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, seek, arginfo_array_seek, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; static const zend_function_entry spl_funcs_RecursiveArrayIterator[] = { SPL_ME(Array, hasChildren, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, getChildren, arginfo_array_void, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; /* }}} */ /* {{{ PHP_MINIT_FUNCTION(spl_array) */ PHP_MINIT_FUNCTION(spl_array) { REGISTER_SPL_STD_CLASS_EX(ArrayObject, spl_array_object_new, spl_funcs_ArrayObject); REGISTER_SPL_IMPLEMENTS(ArrayObject, Aggregate); REGISTER_SPL_IMPLEMENTS(ArrayObject, ArrayAccess); REGISTER_SPL_IMPLEMENTS(ArrayObject, Serializable); memcpy(&spl_handler_ArrayObject, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); spl_handler_ArrayObject.clone_obj = spl_array_object_clone; spl_handler_ArrayObject.read_dimension = spl_array_read_dimension; spl_handler_ArrayObject.write_dimension = spl_array_write_dimension; spl_handler_ArrayObject.unset_dimension = spl_array_unset_dimension; spl_handler_ArrayObject.has_dimension = spl_array_has_dimension; spl_handler_ArrayObject.count_elements = spl_array_object_count_elements; spl_handler_ArrayObject.get_properties = spl_array_get_properties; spl_handler_ArrayObject.get_debug_info = spl_array_get_debug_info; spl_handler_ArrayObject.read_property = spl_array_read_property; spl_handler_ArrayObject.write_property = spl_array_write_property; spl_handler_ArrayObject.get_property_ptr_ptr = spl_array_get_property_ptr_ptr; spl_handler_ArrayObject.has_property = spl_array_has_property; spl_handler_ArrayObject.unset_property = spl_array_unset_property; REGISTER_SPL_STD_CLASS_EX(ArrayIterator, spl_array_object_new, spl_funcs_ArrayIterator); REGISTER_SPL_IMPLEMENTS(ArrayIterator, Iterator); REGISTER_SPL_IMPLEMENTS(ArrayIterator, ArrayAccess); REGISTER_SPL_IMPLEMENTS(ArrayIterator, SeekableIterator); REGISTER_SPL_IMPLEMENTS(ArrayIterator, Serializable); memcpy(&spl_handler_ArrayIterator, &spl_handler_ArrayObject, sizeof(zend_object_handlers)); spl_ce_ArrayIterator->get_iterator = spl_array_get_iterator; REGISTER_SPL_SUB_CLASS_EX(RecursiveArrayIterator, ArrayIterator, spl_array_object_new, spl_funcs_RecursiveArrayIterator); REGISTER_SPL_IMPLEMENTS(RecursiveArrayIterator, RecursiveIterator); spl_ce_RecursiveArrayIterator->get_iterator = spl_array_get_iterator; REGISTER_SPL_IMPLEMENTS(ArrayObject, Countable); REGISTER_SPL_IMPLEMENTS(ArrayIterator, Countable); REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, "STD_PROP_LIST", SPL_ARRAY_STD_PROP_LIST); REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, "ARRAY_AS_PROPS", SPL_ARRAY_ARRAY_AS_PROPS); REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "STD_PROP_LIST", SPL_ARRAY_STD_PROP_LIST); REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "ARRAY_AS_PROPS", SPL_ARRAY_ARRAY_AS_PROPS); REGISTER_SPL_CLASS_CONST_LONG(RecursiveArrayIterator, "CHILD_ARRAYS_ONLY", SPL_ARRAY_CHILD_ARRAYS_ONLY); return SUCCESS; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: fdm=marker * vim: noet sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-04-07-d3274b7f20-77ed819430.c
manybugs_data_61
/* reassemble.c * Routines for {fragment,segment} reassembly * * $Id: reassemble.c 37112 2011-05-13 05:19:23Z etxrab $ * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <string.h> #include <epan/packet.h> #include <epan/reassemble.h> #include <epan/emem.h> #include <epan/dissectors/packet-dcerpc.h> typedef struct _fragment_key { address src; address dst; guint32 id; } fragment_key; typedef struct _dcerpc_fragment_key { address src; address dst; guint32 id; e_uuid_t act_id; } dcerpc_fragment_key; #if GLIB_CHECK_VERSION(2,10,0) #else static GMemChunk *fragment_key_chunk = NULL; static GMemChunk *fragment_data_chunk = NULL; static GMemChunk *dcerpc_fragment_key_chunk = NULL; static int fragment_init_count = 200; #endif static void LINK_FRAG(fragment_data *fd_head,fragment_data *fd) { fragment_data *fd_i; /* add fragment to list, keep list sorted */ for(fd_i= fd_head; fd_i->next;fd_i=fd_i->next) { if (fd->offset < fd_i->next->offset ) break; } fd->next=fd_i->next; fd_i->next=fd; } /* copy a fragment key to heap store to insert in the hash */ static void *fragment_key_copy(const void *k) { const fragment_key* key = (const fragment_key*) k; #if GLIB_CHECK_VERSION(2,10,0) fragment_key *new_key = g_slice_new(fragment_key); #else fragment_key *new_key = g_mem_chunk_alloc(fragment_key_chunk); #endif COPY_ADDRESS(&new_key->src, &key->src); COPY_ADDRESS(&new_key->dst, &key->dst); new_key->id = key->id; return new_key; } /* copy a dcerpc fragment key to heap store to insert in the hash */ static void *dcerpc_fragment_key_copy(const void *k) { const dcerpc_fragment_key* key = (const dcerpc_fragment_key*) k; #if GLIB_CHECK_VERSION(2,10,0) dcerpc_fragment_key *new_key = g_slice_new(dcerpc_fragment_key); #else dcerpc_fragment_key *new_key = g_mem_chunk_alloc(dcerpc_fragment_key_chunk); #endif COPY_ADDRESS(&new_key->src, &key->src); COPY_ADDRESS(&new_key->dst, &key->dst); new_key->id = key->id; new_key->act_id = key->act_id; return new_key; } static gint fragment_equal(gconstpointer k1, gconstpointer k2) { const fragment_key* key1 = (const fragment_key*) k1; const fragment_key* key2 = (const fragment_key*) k2; /*key.id is the first item to compare since item is most likely to differ between sessions, thus shortcircuiting the comparasion of addresses. */ return ( ( (key1->id == key2->id) && (ADDRESSES_EQUAL(&key1->src, &key2->src)) && (ADDRESSES_EQUAL(&key1->dst, &key2->dst)) ) ? TRUE : FALSE); } static guint fragment_hash(gconstpointer k) { const fragment_key* key = (const fragment_key*) k; guint hash_val; /* int i; */ hash_val = 0; /* More than likely: in most captures src and dst addresses are the same, and would hash the same. We only use id as the hash as an optimization. for (i = 0; i < key->src.len; i++) hash_val += key->src.data[i]; for (i = 0; i < key->dst.len; i++) hash_val += key->dst.data[i]; */ hash_val += key->id; return hash_val; } static gint dcerpc_fragment_equal(gconstpointer k1, gconstpointer k2) { const dcerpc_fragment_key* key1 = (const dcerpc_fragment_key*) k1; const dcerpc_fragment_key* key2 = (const dcerpc_fragment_key*) k2; /*key.id is the first item to compare since item is most likely to differ between sessions, thus shortcircuiting the comparison of addresses. */ return (((key1->id == key2->id) && (ADDRESSES_EQUAL(&key1->src, &key2->src)) && (ADDRESSES_EQUAL(&key1->dst, &key2->dst)) && (memcmp (&key1->act_id, &key2->act_id, sizeof (e_uuid_t)) == 0)) ? TRUE : FALSE); } static guint dcerpc_fragment_hash(gconstpointer k) { const dcerpc_fragment_key* key = (const dcerpc_fragment_key*) k; guint hash_val; hash_val = 0; hash_val += key->id; hash_val += key->act_id.Data1; hash_val += key->act_id.Data2 << 16; hash_val += key->act_id.Data3; return hash_val; } typedef struct _reassembled_key { guint32 id; guint32 frame; } reassembled_key; static gint reassembled_equal(gconstpointer k1, gconstpointer k2) { const reassembled_key* key1 = (const reassembled_key*) k1; const reassembled_key* key2 = (const reassembled_key*) k2; /* * We assume that the frame numbers are unlikely to be equal, * so we check them first. */ return key1->frame == key2->frame && key1->id == key2->id; } static guint reassembled_hash(gconstpointer k) { const reassembled_key* key = (const reassembled_key*) k; return key->frame; } /* * For a fragment hash table entry, free the associated fragments. * If slices are used (GLIB >= 2.10) the entry value (fd_chain) is * freed herein and the entry is freed when fragment_free_key() * [or dcerpc_fragment_free_key()] is called (as a consequence of * returning TRUE from this function). * If mem_chunks are used, free the address data to which the key * refers; the the actual key and value structures get freed * by "reassemble_cleanup()"). */ static gboolean free_all_fragments(gpointer key_arg _U_, gpointer value, gpointer user_data _U_) { fragment_data *fd_head, *tmp_fd; #if GLIB_CHECK_VERSION(2,10,0) /* If Glib version => 2.10 we do g_hash_table_new_full() and supply a function * to free the key and the addresses. */ #else fragment_key *key = key_arg; /* * Grr. I guess the theory here is that freeing * something sure as heck modifies it, so you * want to ban attempts to free it, but, alas, * if we make the "data" field of an "address" * structure not a "const", the compiler whines if * we try to make it point into the data for a packet, * as that's a "const" array (and should be, as dissectors * shouldn't trash it). * * So we cast the complaint into oblivion, and rely on * the fact that these addresses are known to have had * their data mallocated, i.e. they don't point into, * say, the middle of the data for a packet. */ g_free((gpointer)key->src.data); g_free((gpointer)key->dst.data); #endif for (fd_head = value; fd_head != NULL; fd_head = tmp_fd) { tmp_fd=fd_head->next; if(fd_head->data && !(fd_head->flags&FD_NOT_MALLOCED)) g_free(fd_head->data); #if GLIB_CHECK_VERSION(2,10,0) g_slice_free(fragment_data, fd_head); #endif } return TRUE; } /* ------------------------- */ static fragment_data *new_head(const guint32 flags) { fragment_data *fd_head; /* If head/first structure in list only holds no other data than * 'datalen' then we don't have to change the head of the list * even if we want to keep it sorted */ #if GLIB_CHECK_VERSION(2,10,0) fd_head=g_slice_new0(fragment_data); #else fd_head=g_mem_chunk_alloc0(fragment_data_chunk); #endif fd_head->flags=flags; return fd_head; } /* * For a reassembled-packet hash table entry, free the fragment data * to which the value refers. * (Pre glib 2.10:The actual value structures get freed by "reassemble_cleanup()".) * http://www.wireshark.org/lists/wireshark-dev/200910/msg00074.html */ static gboolean free_all_reassembled_fragments(gpointer key_arg, gpointer value, gpointer user_data _U_) { fragment_data *fd_head, *tmp_fd; reassembled_key *key = (reassembled_key *)key_arg; for (fd_head = value; fd_head != NULL; fd_head = tmp_fd) { tmp_fd=fd_head->next; if(fd_head->data && !(fd_head->flags&FD_NOT_MALLOCED)) { g_free(fd_head->data); /* * A reassembled packet is inserted into the * hash table once for every frame that made * up the reassembled packet; clear the data * pointer so that we only free the data the * first time we see it. */ fd_head->data = NULL; } #if GLIB_CHECK_VERSION(2,10,0) if(key->frame == fd_head->reassembled_in){ g_slice_free(fragment_data, fd_head); } #endif } return TRUE; } #if GLIB_CHECK_VERSION(2,10,0) static void fragment_free_key(void *ptr) { fragment_key *key = (fragment_key *)ptr; if(key){ /* * Free up the copies of the addresses from the old key. */ g_free((gpointer)key->src.data); g_free((gpointer)key->dst.data); g_slice_free(fragment_key, key); } } static void dcerpc_fragment_free_key(void *ptr) { dcerpc_fragment_key *key = (dcerpc_fragment_key *)ptr; if(key){ /* * Free up the copies of the addresses from the old key. */ g_free((gpointer)key->src.data); g_free((gpointer)key->dst.data); g_slice_free(dcerpc_fragment_key, key); } } #endif #if GLIB_CHECK_VERSION(2,10,0) static void reassembled_key_free(void *ptr) { reassembled_key *key = (reassembled_key *)ptr; g_slice_free(reassembled_key, key); } #endif /* * Initialize a fragment table. */ void fragment_table_init(GHashTable **fragment_table) { if (*fragment_table != NULL) { /* * The fragment hash table exists. * * Remove all entries and free fragment data for each entry. * * If slices are used (GLIB >= 2.10) * the keys are freed by calling fragment_free_key() * and the values are freed in free_all_fragments(). * * If mem_chunks are used, the key and value data * are freed by "reassemble_cleanup()". free_all_fragments() * will free the adrress data associated with the key */ g_hash_table_foreach_remove(*fragment_table, free_all_fragments, NULL); } else { #if GLIB_CHECK_VERSION(2,10,0) /* The fragment table does not exist. Create it */ *fragment_table = g_hash_table_new_full(fragment_hash, fragment_equal, fragment_free_key, NULL); #else /* The fragment table does not exist. Create it */ *fragment_table = g_hash_table_new(fragment_hash, fragment_equal); #endif } } void dcerpc_fragment_table_init(GHashTable **fragment_table) { if (*fragment_table != NULL) { /* * The fragment hash table exists. * * Remove all entries and free fragment data for each entry. * * If slices are used (GLIB >= 2.10) * the keys are freed by calling dcerpc_fragment_free_key() * and the values are freed in free_all_fragments(). * * If mem_chunks are used, the key and value data * are freed by "reassemble_cleanup()". free_all_fragments() * will free the adrress data associated with the key */ g_hash_table_foreach_remove(*fragment_table, free_all_fragments, NULL); } else { #if GLIB_CHECK_VERSION(2,10,0) /* The fragment table does not exist. Create it */ *fragment_table = g_hash_table_new_full(dcerpc_fragment_hash, dcerpc_fragment_equal, dcerpc_fragment_free_key, NULL); #else /* The fragment table does not exist. Create it */ *fragment_table = g_hash_table_new(dcerpc_fragment_hash, dcerpc_fragment_equal); #endif } } /* * Initialize a reassembled-packet table. */ void reassembled_table_init(GHashTable **reassembled_table) { if (*reassembled_table != NULL) { /* * The reassembled-packet hash table exists. * * Remove all entries and free reassembled packet * data for each entry. (The key data is freed * by "reassemble_cleanup()".) */ g_hash_table_foreach_remove(*reassembled_table, free_all_reassembled_fragments, NULL); } else { /* The fragment table does not exist. Create it */ #if GLIB_CHECK_VERSION(2,10,0) *reassembled_table = g_hash_table_new_full(reassembled_hash, reassembled_equal, reassembled_key_free, NULL); #else *reassembled_table = g_hash_table_new(reassembled_hash, reassembled_equal); #endif } } /* * Free up all space allocated for fragment keys and data and * reassembled keys. */ void reassemble_cleanup(void) { #if GLIB_CHECK_VERSION(2,10,0) #else if (fragment_key_chunk != NULL) g_mem_chunk_destroy(fragment_key_chunk); if (dcerpc_fragment_key_chunk != NULL) g_mem_chunk_destroy(dcerpc_fragment_key_chunk); if (fragment_data_chunk != NULL) g_mem_chunk_destroy(fragment_data_chunk); fragment_key_chunk = NULL; dcerpc_fragment_key_chunk = NULL; fragment_data_chunk = NULL; #endif } void reassemble_init(void) { #if GLIB_CHECK_VERSION(2,10,0) #else fragment_key_chunk = g_mem_chunk_new("fragment_key_chunk", sizeof(fragment_key), fragment_init_count * sizeof(fragment_key), G_ALLOC_AND_FREE); dcerpc_fragment_key_chunk = g_mem_chunk_new("dcerpc_fragment_key_chunk", sizeof(dcerpc_fragment_key), fragment_init_count * sizeof(dcerpc_fragment_key), G_ALLOC_AND_FREE); fragment_data_chunk = g_mem_chunk_new("fragment_data_chunk", sizeof(fragment_data), fragment_init_count * sizeof(fragment_data), G_ALLOC_ONLY); #endif } /* This function cleans up the stored state and removes the reassembly data and * (with one exception) all allocated memory for matching reassembly. * * The exception is : * If the PDU was already completely reassembled, then the buffer containing the * reassembled data WILL NOT be free()d, and the pointer to that buffer will be * returned. * Othervise the function will return NULL. * * So, if you call fragment_delete and it returns non-NULL, YOU are responsible to * g_free() that buffer. */ unsigned char * fragment_delete(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table) { fragment_data *fd_head, *fd; fragment_key key; unsigned char *data=NULL; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup(fragment_table, &key); if(fd_head==NULL){ /* We do not recognize this as a PDU we have seen before. return */ return NULL; } data=fd_head->data; /* loop over all partial fragments and free any buffers */ for(fd=fd_head->next;fd;){ fragment_data *tmp_fd; tmp_fd=fd->next; if( !(fd->flags&FD_NOT_MALLOCED) ) g_free(fd->data); #if GLIB_CHECK_VERSION(2,10,0) g_slice_free(fragment_data, fd); #else g_mem_chunk_free(fragment_data_chunk, fd); #endif fd=tmp_fd; } #if GLIB_CHECK_VERSION(2,10,0) g_slice_free(fragment_data, fd_head); #else g_mem_chunk_free(fragment_data_chunk, fd_head); #endif g_hash_table_remove(fragment_table, &key); return data; } /* This function is used to check if there is partial or completed reassembly state * matching this packet. I.e. Is there reassembly going on or not for this packet? */ fragment_data * fragment_get(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table) { fragment_data *fd_head; fragment_key key; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup(fragment_table, &key); return fd_head; } /* id *must* be the frame number for this to work! */ fragment_data * fragment_get_reassembled(const guint32 id, GHashTable *reassembled_table) { fragment_data *fd_head; reassembled_key key; /* create key to search hash with */ key.frame = id; key.id = id; fd_head = g_hash_table_lookup(reassembled_table, &key); return fd_head; } fragment_data * fragment_get_reassembled_id(const packet_info *pinfo, const guint32 id, GHashTable *reassembled_table) { fragment_data *fd_head; reassembled_key key; /* create key to search hash with */ key.frame = pinfo->fd->num; key.id = id; fd_head = g_hash_table_lookup(reassembled_table, &key); return fd_head; } /* This function can be used to explicitly set the total length (if known) * for reassembly of a PDU. * This is useful for reassembly of PDUs where one may have the total length specified * in the first fragment instead of as for, say, IPv4 where a flag indicates which * is the last fragment. * * Such protocols might fragment_add with a more_frags==TRUE for every fragment * and just tell the reassembly engine the expected total length of the reassembled data * using fragment_set_tot_len immediately after doing fragment_add for the first packet. * * Note that for FD_BLOCKSEQUENCE tot_len is the index for the tail fragment. * i.e. since the block numbers start at 0, if we specify tot_len==2, that * actually means we want to defragment 3 blocks, block 0, 1 and 2. */ void fragment_set_tot_len(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, const guint32 tot_len) { fragment_data *fd_head; fragment_key key; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup(fragment_table, &key); if(fd_head){ fd_head->datalen = tot_len; fd_head->flags |= FD_DATALEN_SET; } return; } guint32 fragment_get_tot_len(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table) { fragment_data *fd_head; fragment_key key; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup(fragment_table, &key); if(fd_head){ return fd_head->datalen; } return 0; } /* This function will set the partial reassembly flag for a fh. When this function is called, the fh MUST already exist, i.e. the fh MUST be created by the initial call to fragment_add() before this function is called. Also note that this function MUST be called to indicate a fh will be extended (increase the already stored data) */ void fragment_set_partial_reassembly(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table) { fragment_data *fd_head; fragment_key key; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup(fragment_table, &key); /* * XXX - why not do all the stuff done early in "fragment_add_work()", * turning off FD_DEFRAGMENTED and pointing the fragments' data * pointers to the appropriate part of the already-reassembled * data, and clearing the data length and "reassembled in" frame * number, here? We currently have a hack in the TCP dissector * not to set the "reassembled in" value if the "partial reassembly" * flag is set, so that in the first pass through the packets * we don't falsely set a packet as reassembled in that packet * if the dissector decided that even more reassembly was needed. */ if(fd_head){ fd_head->flags |= FD_PARTIAL_REASSEMBLY; } } /* * This function gets rid of an entry from a fragment table, given * a pointer to the key for that entry; it also frees up the key * and the addresses in it. * Note: If we use slices keys are freed by fragment_free_key() [or dcerpc_fragment_free_key()] being called * during g_hash_table_remove(). */ static void fragment_unhash(GHashTable *fragment_table, fragment_key *key) { /* * Remove the entry from the fragment table. */ g_hash_table_remove(fragment_table, key); /* * Free the key itself. */ #if GLIB_CHECK_VERSION(2,10,0) #else /* * Free up the copies of the addresses from the old key. */ g_free((gpointer)key->src.data); g_free((gpointer)key->dst.data); g_mem_chunk_free(fragment_key_chunk, key); #endif } /* * This function adds fragment_data structure to a reassembled-packet * hash table, using the frame numbers of each of the frames from * which it was reassembled as keys, and sets the "reassembled_in" * frame number. */ static void fragment_reassembled(fragment_data *fd_head, const packet_info *pinfo, GHashTable *reassembled_table, const guint32 id) { reassembled_key *new_key; fragment_data *fd; if (fd_head->next == NULL) { /* * This was not fragmented, so there's no fragment * table; just hash it using the current frame number. */ #if GLIB_CHECK_VERSION(2,10,0) new_key = g_slice_new(reassembled_key); #else new_key = se_alloc(sizeof(reassembled_key)); #endif new_key->frame = pinfo->fd->num; new_key->id = id; g_hash_table_insert(reassembled_table, new_key, fd_head); } else { /* * Hash it with the frame numbers for all the frames. */ for (fd = fd_head->next; fd != NULL; fd = fd->next){ #if GLIB_CHECK_VERSION(2,10,0) new_key = g_slice_new(reassembled_key); #else new_key = se_alloc(sizeof(reassembled_key)); #endif new_key->frame = fd->frame; new_key->id = id; g_hash_table_insert(reassembled_table, new_key, fd_head); } } fd_head->flags |= FD_DEFRAGMENTED; fd_head->reassembled_in = pinfo->fd->num; } /* * This function adds a new fragment to the fragment hash table. * If this is the first fragment seen for this datagram, a new entry * is created in the hash table, otherwise this fragment is just added * to the linked list of fragments for this packet. * The list of fragments for a specific datagram is kept sorted for * easier handling. * * Returns a pointer to the head of the fragment data list if we have all the * fragments, NULL otherwise. * * This function assumes frag_offset being a byte offset into the defragment * packet. * * 01-2002 * Once the fh is defragmented (= FD_DEFRAGMENTED set), it can be * extended using the FD_PARTIAL_REASSEMBLY flag. This flag should be set * using fragment_set_partial_reassembly() before calling fragment_add * with the new fragment. FD_TOOLONGFRAGMENT and FD_MULTIPLETAILS flags * are lowered when a new extension process is started. */ static gboolean fragment_add_work(fragment_data *fd_head, tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 frag_offset, const guint32 frag_data_len, const gboolean more_frags) { fragment_data *fd; fragment_data *fd_i; guint32 max, dfpos; unsigned char *old_data; /* create new fd describing this fragment */ #if GLIB_CHECK_VERSION(2,10,0) fd = g_slice_new(fragment_data); #else fd = g_mem_chunk_alloc(fragment_data_chunk); #endif fd->next = NULL; fd->flags = 0; fd->frame = pinfo->fd->num; if (fd->frame > fd_head->frame) fd_head->frame = fd->frame; fd->offset = frag_offset; fd->len = frag_data_len; fd->data = NULL; /* * If it was already defragmented and this new fragment goes beyond * data limits, set flag in already empty fds & point old fds to malloc'ed data. */ if(fd_head->flags & FD_DEFRAGMENTED && (frag_offset+frag_data_len) >= fd_head->datalen && fd_head->flags & FD_PARTIAL_REASSEMBLY){ for(fd_i=fd_head->next; fd_i; fd_i=fd_i->next){ if( !fd_i->data ) { fd_i->data = fd_head->data + fd_i->offset; fd_i->flags |= FD_NOT_MALLOCED; } fd_i->flags &= (~FD_TOOLONGFRAGMENT) & (~FD_MULTIPLETAILS); } fd_head->flags &= ~(FD_DEFRAGMENTED|FD_PARTIAL_REASSEMBLY|FD_DATALEN_SET); fd_head->flags &= (~FD_TOOLONGFRAGMENT) & (~FD_MULTIPLETAILS); fd_head->datalen=0; fd_head->reassembled_in=0; } if (!more_frags) { /* * This is the tail fragment in the sequence. */ if (fd_head->flags & FD_DATALEN_SET) { /* ok we have already seen other tails for this packet * it might be a duplicate. */ if (fd_head->datalen != (fd->offset + fd->len) ){ /* Oops, this tail indicates a different packet * len than the previous ones. Something's wrong. */ fd->flags |= FD_MULTIPLETAILS; fd_head->flags |= FD_MULTIPLETAILS; } } else { /* this was the first tail fragment, now we know the * length of the packet */ fd_head->datalen = fd->offset + fd->len; fd_head->flags |= FD_DATALEN_SET; } } /* If the packet is already defragmented, this MUST be an overlap. * The entire defragmented packet is in fd_head->data. * Even if we have previously defragmented this packet, we still * check it. Someone might play overlap and TTL games. */ if (fd_head->flags & FD_DEFRAGMENTED) { guint32 end_offset = fd->offset + fd->len; fd->flags |= FD_OVERLAP; fd_head->flags |= FD_OVERLAP; /* make sure it's not too long */ if (end_offset > fd_head->datalen || end_offset < fd->offset || end_offset < fd->len) { fd->flags |= FD_TOOLONGFRAGMENT; fd_head->flags |= FD_TOOLONGFRAGMENT; } /* make sure it doesn't conflict with previous data */ else if ( memcmp(fd_head->data+fd->offset, tvb_get_ptr(tvb,offset,fd->len),fd->len) ){ fd->flags |= FD_OVERLAPCONFLICT; fd_head->flags |= FD_OVERLAPCONFLICT; } /* it was just an overlap, link it and return */ LINK_FRAG(fd_head,fd); return TRUE; } /* If we have reached this point, the packet is not defragmented yet. * Save all payload in a buffer until we can defragment. * XXX - what if we didn't capture the entire fragment due * to a too-short snapshot length? */ fd->data = g_malloc(fd->len); tvb_memcpy(tvb, fd->data, offset, fd->len); LINK_FRAG(fd_head,fd); if( !(fd_head->flags & FD_DATALEN_SET) ){ /* if we dont know the datalen, there are still missing * packets. Cheaper than the check below. */ return FALSE; } /* * Check if we have received the entire fragment. * This is easy since the list is sorted and the head is faked. * * First, we compute the amount of contiguous data that's * available. (The check for fd_i->offset <= max rules out * fragments that don't start before or at the end of the * previous fragment, i.e. fragments that have a gap between * them and the previous fragment.) */ max = 0; for (fd_i=fd_head->next;fd_i;fd_i=fd_i->next) { if ( ((fd_i->offset)<=max) && ((fd_i->offset+fd_i->len)>max) ){ max = fd_i->offset+fd_i->len; } } if (max < (fd_head->datalen)) { /* * The amount of contiguous data we have is less than the * amount of data we're trying to reassemble, so we haven't * received all packets yet. */ return FALSE; } if (max > (fd_head->datalen)) { /*XXX not sure if current fd was the TOOLONG*/ /*XXX is it fair to flag current fd*/ /* oops, too long fragment detected */ fd->flags |= FD_TOOLONGFRAGMENT; fd_head->flags |= FD_TOOLONGFRAGMENT; } /* we have received an entire packet, defragment it and * free all fragments */ /* store old data just in case */ old_data=fd_head->data; fd_head->data = g_malloc(max); /* add all data fragments */ for (dfpos=0,fd_i=fd_head;fd_i;fd_i=fd_i->next) { if (fd_i->len) { /* dfpos is always >= than fd_i->offset */ /* No gaps can exist here, max_loop(above) does this */ /* XXX - true? Can we get fd_i->offset+fd-i->len */ /* overflowing, for example? */ /* Actually: there is at least one pathological case wherein there can be fragments * on the list which are for offsets greater than max (i.e.: following a gap after max). * (Apparently a "DESEGMENT_UNTIL_FIN" was involved wherein the FIN packet had an offset * less than the highest fragment offset seen. [Seen from a fuzz-test: bug #2470]). * Note that the "overlap" compare must only be done for fragments with (offset+len) <= max * and thus within the newly g_malloc'd buffer. */ if ( fd_i->offset+fd_i->len > dfpos ) { if (fd_i->offset+fd_i->len > max) g_warning("Reassemble error in frame %u: offset %u + len %u > max %u", pinfo->fd->num, fd_i->offset, fd_i->len, max); else if (dfpos < fd_i->offset) g_warning("Reassemble error in frame %u: dfpos %u < offset %u", pinfo->fd->num, dfpos, fd_i->offset); else if (dfpos-fd_i->offset > fd_i->len) g_warning("Reassemble error in frame %u: dfpos %u - offset %u > len %u", pinfo->fd->num, dfpos, fd_i->offset, fd_i->len); else if (!fd_head->data) g_warning("Reassemble error in frame %u: no data", pinfo->fd->num); else { if (fd_i->offset < dfpos) { fd_i->flags |= FD_OVERLAP; fd_head->flags |= FD_OVERLAP; if ( memcmp(fd_head->data+fd_i->offset, fd_i->data, MIN(fd_i->len,(dfpos-fd_i->offset)) ) ) { fd_i->flags |= FD_OVERLAPCONFLICT; fd_head->flags |= FD_OVERLAPCONFLICT; } } memcpy(fd_head->data+dfpos, fd_i->data+(dfpos-fd_i->offset), fd_i->len-(dfpos-fd_i->offset)); } } else { if (fd_i->offset + fd_i->len < fd_i->offset) /* Integer overflow? */ g_warning("Reassemble error in frame %u: offset %u + len %u < offset", pinfo->fd->num, fd_i->offset, fd_i->len); } if( fd_i->flags & FD_NOT_MALLOCED ) fd_i->flags &= ~FD_NOT_MALLOCED; else g_free(fd_i->data); fd_i->data=NULL; dfpos=MAX(dfpos,(fd_i->offset+fd_i->len)); } } g_free(old_data); /* mark this packet as defragmented. allows us to skip any trailing fragments */ fd_head->flags |= FD_DEFRAGMENTED; fd_head->reassembled_in=pinfo->fd->num; return TRUE; } static fragment_data * fragment_add_common(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, const guint32 frag_offset, const guint32 frag_data_len, const gboolean more_frags, const gboolean check_already_added) { fragment_key key, *new_key; fragment_data *fd_head; fragment_data *fd_item; gboolean already_added=pinfo->fd->flags.visited; /* dissector shouldn't give us garbage tvb info */ DISSECTOR_ASSERT(tvb_bytes_exist(tvb, offset, frag_data_len)); /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup(fragment_table, &key); #if 0 /* debug output of associated fragments. */ /* leave it here for future debugging sessions */ if(strcmp(pinfo->current_proto, "DCERPC") == 0) { printf("proto:%s num:%u id:%u offset:%u len:%u more:%u visited:%u\n", pinfo->current_proto, pinfo->fd->num, id, frag_offset, frag_data_len, more_frags, pinfo->fd->flags.visited); if(fd_head != NULL) { for(fd_item=fd_head->next;fd_item;fd_item=fd_item->next){ printf("fd_frame:%u fd_offset:%u len:%u datalen:%u\n", fd_item->frame, fd_item->offset, fd_item->len, fd_item->datalen); } } } #endif /* * "already_added" is true if "pinfo->fd->flags.visited" is true; * if "pinfo->fd->flags.visited", this isn't the first pass, so * we've already done all the reassembly and added all the * fragments. * * If it's not true, but "check_already_added" is true, just check * if we have seen this fragment before, i.e., if we have already * added it to reassembly. * That can be true even if "pinfo->fd->flags.visited" is false * since we sometimes might call a subdissector multiple times. * As an additional check, just make sure we have not already added * this frame to the reassembly list, if there is a reassembly list; * note that the first item in the reassembly list is not a * fragment, it's a data structure for the reassembled packet. * We don't check it because its "frame" member isn't initialized * to anything, and because it doesn't count in any case. * * And as another additional check, make sure the fragment offsets are * the same, as otherwise we get into trouble if multiple fragments * are in one PDU. */ if (!already_added && check_already_added && fd_head != NULL) { if (pinfo->fd->num <= fd_head->frame) { for(fd_item=fd_head->next;fd_item;fd_item=fd_item->next){ if(pinfo->fd->num==fd_item->frame && frag_offset==fd_item->offset){ already_added=TRUE; } } } } /* have we already added this frame ?*/ if (already_added) { if (fd_head != NULL && fd_head->flags & FD_DEFRAGMENTED) { return fd_head; } else { return NULL; } } if (fd_head==NULL){ /* not found, this must be the first snooped fragment for this * packet. Create list-head. */ fd_head = new_head(0); /* * We're going to use the key to insert the fragment, * so allocate a structure for it, and copy the * addresses, allocating new buffers for the address * data. */ #if GLIB_CHECK_VERSION(2,10,0) new_key = g_slice_new(fragment_key); #else new_key = g_mem_chunk_alloc(fragment_key_chunk); #endif COPY_ADDRESS(&new_key->src, &key.src); COPY_ADDRESS(&new_key->dst, &key.dst); new_key->id = key.id; g_hash_table_insert(fragment_table, new_key, fd_head); } if (fragment_add_work(fd_head, tvb, offset, pinfo, frag_offset, frag_data_len, more_frags)) { /* * Reassembly is complete. */ return fd_head; } else { /* * Reassembly isn't complete. */ return NULL; } } fragment_data * fragment_add(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, const guint32 frag_offset, const guint32 frag_data_len, const gboolean more_frags) { return fragment_add_common(tvb, offset, pinfo, id, fragment_table, frag_offset, frag_data_len, more_frags, TRUE); } /* * For use when you can have multiple fragments in the same frame added * to the same reassembled PDU, e.g. with ONC RPC-over-TCP. */ fragment_data * fragment_add_multiple_ok(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, const guint32 frag_offset, const guint32 frag_data_len, const gboolean more_frags) { return fragment_add_common(tvb, offset, pinfo, id, fragment_table, frag_offset, frag_data_len, more_frags, FALSE); } fragment_data * fragment_add_check(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, GHashTable *reassembled_table, const guint32 frag_offset, const guint32 frag_data_len, const gboolean more_frags) { reassembled_key reass_key; fragment_key key, *new_key, *old_key; gpointer orig_key, value; fragment_data *fd_head; /* * If this isn't the first pass, look for this frame in the table * of reassembled packets. */ if (pinfo->fd->flags.visited) { reass_key.frame = pinfo->fd->num; reass_key.id = id; return g_hash_table_lookup(reassembled_table, &reass_key); } /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; /* Looks up a key in the GHashTable, returning the original key and the associated value * and a gboolean which is TRUE if the key was found. This is useful if you need to free * the memory allocated for the original key, for example before calling g_hash_table_remove() */ if (!g_hash_table_lookup_extended(fragment_table, &key, &orig_key, &value)) { /* not found, this must be the first snooped fragment for this * packet. Create list-head. */ fd_head = new_head(0); /* * We're going to use the key to insert the fragment, * so allocate a structure for it, and copy the * addresses, allocating new buffers for the address * data. */ #if GLIB_CHECK_VERSION(2,10,0) new_key = g_slice_new(fragment_key); #else new_key = g_mem_chunk_alloc(fragment_key_chunk); #endif COPY_ADDRESS(&new_key->src, &key.src); COPY_ADDRESS(&new_key->dst, &key.dst); new_key->id = key.id; g_hash_table_insert(fragment_table, new_key, fd_head); orig_key = new_key; /* for unhashing it later */ } else { /* * We found it. */ fd_head = value; } /* * If this is a short frame, then we can't, and don't, do * reassembly on it. We just give up. */ if (tvb_reported_length(tvb) > tvb_length(tvb)) return NULL; if (fragment_add_work(fd_head, tvb, offset, pinfo, frag_offset, frag_data_len, more_frags)) { /* * Reassembly is complete. * Remove this from the table of in-progress * reassemblies, add it to the table of * reassembled packets, and return it. */ /* * Remove this from the table of in-progress reassemblies, * and free up any memory used for it in that table. */ old_key = orig_key; fragment_unhash(fragment_table, old_key); /* * Add this item to the table of reassembled packets. */ fragment_reassembled(fd_head, pinfo, reassembled_table, id); return fd_head; } else { /* * Reassembly isn't complete. */ return NULL; } } static void fragment_defragment_and_free (fragment_data *fd_head, const packet_info *pinfo) { fragment_data *fd_i = NULL; fragment_data *last_fd = NULL; guint32 dfpos = 0, size = 0; void *old_data = NULL; for(fd_i=fd_head->next;fd_i;fd_i=fd_i->next) { if(!last_fd || last_fd->offset!=fd_i->offset){ size+=fd_i->len; } last_fd=fd_i; } /* store old data in case the fd_i->data pointers refer to it */ old_data=fd_head->data; fd_head->data = g_malloc(size); fd_head->len = size; /* record size for caller */ /* add all data fragments */ last_fd=NULL; for (fd_i=fd_head->next; fd_i; fd_i=fd_i->next) { if (fd_i->len) { if(!last_fd || last_fd->offset != fd_i->offset) { /* First fragment or in-sequence fragment */ memcpy(fd_head->data+dfpos, fd_i->data, fd_i->len); dfpos += fd_i->len; } else { /* duplicate/retransmission/overlap */ fd_i->flags |= FD_OVERLAP; fd_head->flags |= FD_OVERLAP; if(last_fd->len != fd_i->len || memcmp(last_fd->data, fd_i->data, last_fd->len) ) { fd_i->flags |= FD_OVERLAPCONFLICT; fd_head->flags |= FD_OVERLAPCONFLICT; } } } last_fd=fd_i; } /* we have defragmented the pdu, now free all fragments*/ for (fd_i=fd_head->next;fd_i;fd_i=fd_i->next) { if( fd_i->flags & FD_NOT_MALLOCED ) fd_i->flags &= ~FD_NOT_MALLOCED; else g_free(fd_i->data); fd_i->data=NULL; } g_free(old_data); /* mark this packet as defragmented. * allows us to skip any trailing fragments. */ fd_head->flags |= FD_DEFRAGMENTED; fd_head->reassembled_in=pinfo->fd->num; } /* * This function adds a new fragment to the entry for a reassembly * operation. * * The list of fragments for a specific datagram is kept sorted for * easier handling. * * Returns TRUE if we have all the fragments, FALSE otherwise. * * This function assumes frag_number being a block sequence number. * The bsn for the first block is 0. */ static gboolean fragment_add_seq_work(fragment_data *fd_head, tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags, const guint32 flags _U_) { fragment_data *fd; fragment_data *fd_i; fragment_data *last_fd; guint32 max, dfpos; /* if the partial reassembly flag has been set, and we are extending * the pdu, un-reassemble the pdu. This means pointing old fds to malloc'ed data. */ if(fd_head->flags & FD_DEFRAGMENTED && frag_number >= fd_head->datalen && fd_head->flags & FD_PARTIAL_REASSEMBLY){ guint32 lastdfpos = 0; dfpos = 0; for(fd_i=fd_head->next; fd_i; fd_i=fd_i->next){ if( !fd_i->data ) { if( fd_i->flags & FD_OVERLAP ) { /* this is a duplicate of the previous * fragment. */ fd_i->data = fd_head->data + lastdfpos; } else { fd_i->data = fd_head->data + dfpos; lastdfpos = dfpos; dfpos += fd_i->len; } fd_i->flags |= FD_NOT_MALLOCED; } fd_i->flags &= (~FD_TOOLONGFRAGMENT) & (~FD_MULTIPLETAILS); } fd_head->flags &= ~(FD_DEFRAGMENTED|FD_PARTIAL_REASSEMBLY|FD_DATALEN_SET); fd_head->flags &= (~FD_TOOLONGFRAGMENT) & (~FD_MULTIPLETAILS); fd_head->datalen=0; fd_head->reassembled_in=0; } /* create new fd describing this fragment */ #if GLIB_CHECK_VERSION(2,10,0) fd = g_slice_new(fragment_data); #else fd = g_mem_chunk_alloc(fragment_data_chunk); #endif fd->next = NULL; fd->flags = 0; fd->frame = pinfo->fd->num; fd->offset = frag_number; fd->len = frag_data_len; fd->data = NULL; if (!more_frags) { /* * This is the tail fragment in the sequence. */ if (fd_head->flags&FD_DATALEN_SET) { /* ok we have already seen other tails for this packet * it might be a duplicate. */ if (fd_head->datalen != fd->offset ){ /* Oops, this tail indicates a different packet * len than the previous ones. Something's wrong. */ fd->flags |= FD_MULTIPLETAILS; fd_head->flags |= FD_MULTIPLETAILS; } } else { /* this was the first tail fragment, now we know the * sequence number of that fragment (which is NOT * the length of the packet!) */ fd_head->datalen = fd->offset; fd_head->flags |= FD_DATALEN_SET; } } /* If the packet is already defragmented, this MUST be an overlap. * The entire defragmented packet is in fd_head->data * Even if we have previously defragmented this packet, we still check * check it. Someone might play overlap and TTL games. */ if (fd_head->flags & FD_DEFRAGMENTED) { fd->flags |= FD_OVERLAP; fd_head->flags |= FD_OVERLAP; /* make sure it's not past the end */ if (fd->offset > fd_head->datalen) { /* new fragment comes after the end */ fd->flags |= FD_TOOLONGFRAGMENT; fd_head->flags |= FD_TOOLONGFRAGMENT; LINK_FRAG(fd_head,fd); return TRUE; } /* make sure it doesn't conflict with previous data */ dfpos=0; last_fd=NULL; for (fd_i=fd_head->next;fd_i && (fd_i->offset!=fd->offset);fd_i=fd_i->next) { if (!last_fd || last_fd->offset!=fd_i->offset){ dfpos += fd_i->len; } last_fd=fd_i; } if(fd_i){ /* new fragment overlaps existing fragment */ if(fd_i->len!=fd->len){ /* * They have different lengths; this * is definitely a conflict. */ fd->flags |= FD_OVERLAPCONFLICT; fd_head->flags |= FD_OVERLAPCONFLICT; LINK_FRAG(fd_head,fd); return TRUE; } DISSECTOR_ASSERT(fd_head->len >= dfpos + fd->len); if ( memcmp(fd_head->data+dfpos, tvb_get_ptr(tvb,offset,fd->len),fd->len) ){ /* * They have the same length, but the * data isn't the same. */ fd->flags |= FD_OVERLAPCONFLICT; fd_head->flags |= FD_OVERLAPCONFLICT; LINK_FRAG(fd_head,fd); return TRUE; } /* it was just an overlap, link it and return */ LINK_FRAG(fd_head,fd); return TRUE; } else { /* * New fragment doesn't overlap an existing * fragment - there was presumably a gap in * the sequence number space. * * XXX - what should we do here? Is it always * the case that there are no gaps, or are there * protcols using sequence numbers where there * can be gaps? * * If the former, the check below for having * received all the fragments should check for * holes in the sequence number space and for the * first sequence number being 0. If we do that, * the only way we can get here is if this fragment * is past the end of the sequence number space - * but the check for "fd->offset > fd_head->datalen" * would have caught that above, so it can't happen. * * If the latter, we don't have a good way of * knowing whether reassembly is complete if we * get packet out of order such that the "last" * fragment doesn't show up last - but, unless * in-order reliable delivery of fragments is * guaranteed, an implementation of the protocol * has no way of knowing whether reassembly is * complete, either. * * For now, we just link the fragment in and * return. */ LINK_FRAG(fd_head,fd); return TRUE; } } /* If we have reached this point, the packet is not defragmented yet. * Save all payload in a buffer until we can defragment. * XXX - what if we didn't capture the entire fragment due * to a too-short snapshot length? */ /* check len, there may be a fragment with 0 len, that is actually the tail */ if (fd->len) { fd->data = g_malloc(fd->len); tvb_memcpy(tvb, fd->data, offset, fd->len); } LINK_FRAG(fd_head,fd); if( !(fd_head->flags & FD_DATALEN_SET) ){ /* if we dont know the sequence number of the last fragment, * there are definitely still missing packets. Cheaper than * the check below. */ return FALSE; } /* check if we have received the entire fragment * this is easy since the list is sorted and the head is faked. * common case the whole list is scanned. */ max = 0; for(fd_i=fd_head->next;fd_i;fd_i=fd_i->next) { if ( fd_i->offset==max ){ max++; } } /* max will now be datalen+1 if all fragments have been seen */ if (max <= fd_head->datalen) { /* we have not received all packets yet */ return FALSE; } if (max > (fd_head->datalen+1)) { /* oops, too long fragment detected */ fd->flags |= FD_TOOLONGFRAGMENT; fd_head->flags |= FD_TOOLONGFRAGMENT; } /* we have received an entire packet, defragment it and * free all fragments */ fragment_defragment_and_free(fd_head, pinfo); return TRUE; } /* * This function adds a new fragment to the fragment hash table. * If this is the first fragment seen for this datagram, a new entry * is created in the hash table, otherwise this fragment is just added * to the linked list of fragments for this packet. * * Returns a pointer to the head of the fragment data list if we have all the * fragments, NULL otherwise. * * This function assumes frag_number being a block sequence number. * The bsn for the first block is 0. */ fragment_data * fragment_add_seq(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, const guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags) { fragment_key key; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; return fragment_add_seq_key(tvb, offset, pinfo, &key, fragment_key_copy, fragment_table, frag_number, frag_data_len, more_frags, 0); } fragment_data * fragment_add_dcerpc_dg(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, void *v_act_id, GHashTable *fragment_table, const guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags) { e_uuid_t *act_id = (e_uuid_t *)v_act_id; dcerpc_fragment_key key; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; key.act_id = *act_id; return fragment_add_seq_key(tvb, offset, pinfo, &key, dcerpc_fragment_key_copy, fragment_table, frag_number, frag_data_len, more_frags, 0); } fragment_data * fragment_add_seq_key(tvbuff_t *tvb, const int offset, const packet_info *pinfo, void *key, fragment_key_copier key_copier, GHashTable *fragment_table, guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags, const guint32 flags) { fragment_data *fd_head; fd_head = g_hash_table_lookup(fragment_table, key); /* have we already seen this frame ?*/ if (pinfo->fd->flags.visited) { if (fd_head != NULL && fd_head->flags & FD_DEFRAGMENTED) { return fd_head; } else { return NULL; } } if (fd_head==NULL){ /* not found, this must be the first snooped fragment for this * packet. Create list-head. */ fd_head= new_head(FD_BLOCKSEQUENCE); if((flags & (REASSEMBLE_FLAGS_NO_FRAG_NUMBER|REASSEMBLE_FLAGS_802_11_HACK)) && !more_frags) { /* * This is the last fragment for this packet, and * is the only one we've seen. * * Either we don't have sequence numbers, in which * case we assume this is the first fragment for * this packet, or we're doing special 802.11 * processing, in which case we assume it's one * of those reassembled packets with a non-zero * fragment number (see packet-80211.c); just * return a pointer to the head of the list; * fragment_add_seq_check will then add it to the table * of reassembled packets. */ fd_head->reassembled_in=pinfo->fd->num; return fd_head; } /* * We're going to use the key to insert the fragment, * so copy it to a long-term store. */ if(key_copier != NULL) key = key_copier(key); g_hash_table_insert(fragment_table, key, fd_head); /* * If we weren't given an initial fragment number, * make it 0. */ if (flags & REASSEMBLE_FLAGS_NO_FRAG_NUMBER) frag_number = 0; } else { if (flags & REASSEMBLE_FLAGS_NO_FRAG_NUMBER) { fragment_data *fd; /* * If we weren't given an initial fragment number, * use the next expected fragment number as the fragment * number for this fragment. */ for (fd = fd_head; fd != NULL; fd = fd->next) { if (fd->next == NULL) frag_number = fd->offset + 1; } } } /* * XXX I've copied this over from the old separate * fragment_add_seq_check_work, but I'm not convinced it's doing the * right thing -- rav * * If we don't have all the data that is in this fragment, * then we can't, and don't, do reassembly on it. * * If it's the first frame, handle it as an unfragmented packet. * Otherwise, just handle it as a fragment. * * If "more_frags" isn't set, we get rid of the entry in the * hash table for this reassembly, as we don't need it any more. */ if ((flags & REASSEMBLE_FLAGS_CHECK_DATA_PRESENT) && !tvb_bytes_exist(tvb, offset, frag_data_len)) { if (!more_frags) { gpointer orig_key; /* * Remove this from the table of in-progress * reassemblies, and free up any memory used for * it in that table. */ if (g_hash_table_lookup_extended(fragment_table, key, &orig_key, NULL)) { fragment_unhash(fragment_table, (fragment_key *)orig_key); } } fd_head -> flags |= FD_DATA_NOT_PRESENT; return frag_number == 0 ? fd_head : NULL; } if (fragment_add_seq_work(fd_head, tvb, offset, pinfo, frag_number, frag_data_len, more_frags, flags)) { /* * Reassembly is complete. */ return fd_head; } else { /* * Reassembly isn't complete. */ return NULL; } } /* * This does the work for "fragment_add_seq_check()" and * "fragment_add_seq_next()". * * This function assumes frag_number being a block sequence number. * The bsn for the first block is 0. * * If "no_frag_number" is TRUE, it uses the next expected fragment number * as the fragment number if there is a reassembly in progress, otherwise * it uses 0. * * If "no_frag_number" is FALSE, it uses the "frag_number" argument as * the fragment number. * * If this is the first fragment seen for this datagram, a new * "fragment_data" structure is allocated to refer to the reassembled * packet. * * This fragment is added to the linked list of fragments for this packet. * * If "more_frags" is false and REASSEMBLE_FLAGS_802_11_HACK (as the name * implies, a special hack for 802.11) or REASSEMBLE_FLAGS_NO_FRAG_NUMBER * (implying messages must be in order since there's no sequence number) are * set in "flags", then this (one element) list is returned. * * If, after processing this fragment, we have all the fragments, * "fragment_add_seq_check_work()" removes that from the fragment hash * table if necessary and adds it to the table of reassembled fragments, * and returns a pointer to the head of the fragment list. * * Otherwise, it returns NULL. * * XXX - Should we simply return NULL for zero-length fragments? */ static fragment_data * fragment_add_seq_check_work(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, GHashTable *reassembled_table, const guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags, const guint32 flags) { reassembled_key reass_key; fragment_key key; fragment_data *fd_head; /* * Have we already seen this frame? * If so, look for it in the table of reassembled packets. */ if (pinfo->fd->flags.visited) { reass_key.frame = pinfo->fd->num; reass_key.id = id; return g_hash_table_lookup(reassembled_table, &reass_key); } /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = fragment_add_seq_key(tvb, offset, pinfo, &key, fragment_key_copy, fragment_table, frag_number, frag_data_len, more_frags, flags|REASSEMBLE_FLAGS_CHECK_DATA_PRESENT); if (fd_head) { gpointer orig_key; if(fd_head->flags & FD_DATA_NOT_PRESENT) { /* this is the first fragment of a datagram with * truncated fragments. Don't move it to the * reassembled table. */ return fd_head; } /* * Reassembly is complete. * Remove this from the table of in-progress * reassemblies, add it to the table of * reassembled packets, and return it. */ if (g_hash_table_lookup_extended(fragment_table, &key, &orig_key, NULL)) { /* * Remove this from the table of in-progress reassemblies, * and free up any memory used for it in that table. */ fragment_unhash(fragment_table, (fragment_key *)orig_key); } /* * Add this item to the table of reassembled packets. */ fragment_reassembled(fd_head, pinfo, reassembled_table, id); return fd_head; } else { /* * Reassembly isn't complete. */ return NULL; } } fragment_data * fragment_add_seq_check(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, GHashTable *reassembled_table, const guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags) { return fragment_add_seq_check_work(tvb, offset, pinfo, id, fragment_table, reassembled_table, frag_number, frag_data_len, more_frags, 0); } fragment_data * fragment_add_seq_802_11(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, GHashTable *reassembled_table, const guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags) { return fragment_add_seq_check_work(tvb, offset, pinfo, id, fragment_table, reassembled_table, frag_number, frag_data_len, more_frags, REASSEMBLE_FLAGS_802_11_HACK); } fragment_data * fragment_add_seq_next(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, GHashTable *reassembled_table, const guint32 frag_data_len, const gboolean more_frags) { return fragment_add_seq_check_work(tvb, offset, pinfo, id, fragment_table, reassembled_table, 0, frag_data_len, more_frags, REASSEMBLE_FLAGS_NO_FRAG_NUMBER); } void fragment_start_seq_check(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, const guint32 tot_len) { fragment_key key, *new_key; fragment_data *fd_head; /* Have we already seen this frame ?*/ if (pinfo->fd->flags.visited) { return; } /* Create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; /* Check if fragment data exist for this key */ fd_head = g_hash_table_lookup(fragment_table, &key); if (fd_head == NULL) { /* Create list-head. */ #if GLIB_CHECK_VERSION(2,10,0) fd_head = g_slice_new(fragment_data); #else fd_head = g_mem_chunk_alloc(fragment_data_chunk); #endif fd_head->next = NULL; fd_head->datalen = tot_len; fd_head->offset = 0; fd_head->len = 0; fd_head->flags = FD_BLOCKSEQUENCE|FD_DATALEN_SET; fd_head->data = NULL; fd_head->reassembled_in = 0; /* * We're going to use the key to insert the fragment, * so copy it to a long-term store. */ new_key = fragment_key_copy(&key); g_hash_table_insert(fragment_table, new_key, fd_head); } } fragment_data * fragment_end_seq_next(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, GHashTable *reassembled_table) { reassembled_key reass_key; reassembled_key *new_key; fragment_key key; fragment_data *fd_head; /* * Have we already seen this frame? * If so, look for it in the table of reassembled packets. */ if (pinfo->fd->flags.visited) { reass_key.frame = pinfo->fd->num; reass_key.id = id; return g_hash_table_lookup(reassembled_table, &reass_key); } /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup (fragment_table, &key); if (fd_head) { gpointer orig_key; if (fd_head->flags & FD_DATA_NOT_PRESENT) { /* No data added */ return NULL; } fd_head->datalen = fd_head->offset; fd_head->flags |= FD_DATALEN_SET; fragment_defragment_and_free (fd_head, pinfo); /* * Remove this from the table of in-progress * reassemblies, add it to the table of * reassembled packets, and return it. */ if (g_hash_table_lookup_extended(fragment_table, &key, &orig_key, NULL)) { /* * Remove this from the table of in-progress reassemblies, * and free up any memory used for it in that table. */ fragment_unhash(fragment_table, (fragment_key *)orig_key); } /* * Add this item to the table of reassembled packets. */ fragment_reassembled(fd_head, pinfo, reassembled_table, id); if (fd_head->next != NULL) { #if GLIB_CHECK_VERSION(2,10,0) new_key = g_slice_new(reassembled_key); #else new_key = se_alloc(sizeof(reassembled_key)); #endif new_key->frame = pinfo->fd->num; new_key->id = id; g_hash_table_insert(reassembled_table, new_key, fd_head); } return fd_head; } else { /* * Fragment data not found. */ return NULL; } } /* * Process reassembled data; if we're on the frame in which the data * was reassembled, put the fragment information into the protocol * tree, and construct a tvbuff with the reassembled data, otherwise * just put a "reassembled in" item into the protocol tree. */ tvbuff_t * process_reassembled_data(tvbuff_t *tvb, const int offset, packet_info *pinfo, const char *name, fragment_data *fd_head, const fragment_items *fit, gboolean *update_col_infop, proto_tree *tree) { tvbuff_t *next_tvb; gboolean update_col_info; proto_item *frag_tree_item; if (fd_head != NULL && pinfo->fd->num == fd_head->reassembled_in) { /* * OK, we've reassembled this. * Is this something that's been reassembled from more * than one fragment? */ if (fd_head->next != NULL) { /* * Yes. * Allocate a new tvbuff, referring to the * reassembled payload. */ if (fd_head->flags & FD_BLOCKSEQUENCE) { next_tvb = tvb_new_real_data(fd_head->data, fd_head->len, fd_head->len); } else { next_tvb = tvb_new_real_data(fd_head->data, fd_head->datalen, fd_head->datalen); } /* * Add the tvbuff to the list of tvbuffs to which * the tvbuff we were handed refers, so it'll get * cleaned up when that tvbuff is cleaned up. */ tvb_set_child_real_data_tvbuff(tvb, next_tvb); /* Add the defragmented data to the data source list. */ add_new_data_source(pinfo, next_tvb, name); /* show all fragments */ if (fd_head->flags & FD_BLOCKSEQUENCE) { update_col_info = !show_fragment_seq_tree( fd_head, fit, tree, pinfo, next_tvb, &frag_tree_item); } else { update_col_info = !show_fragment_tree(fd_head, fit, tree, pinfo, next_tvb, &frag_tree_item); } } else { /* * No. * Return a tvbuff with the payload. */ next_tvb = tvb_new_subset_remaining(tvb, offset); pinfo->fragmented = FALSE; /* one-fragment packet */ update_col_info = TRUE; } if (update_col_infop != NULL) *update_col_infop = update_col_info; } else { /* * We don't have the complete reassembled payload, or this * isn't the final frame of that payload. */ next_tvb = NULL; /* * If we know what frame this was reassembled in, * and if there's a field to use for the number of * the frame in which the packet was reassembled, * add it to the protocol tree. */ if (fd_head != NULL && fit->hf_reassembled_in != NULL) { proto_tree_add_uint(tree, *(fit->hf_reassembled_in), tvb, 0, 0, fd_head->reassembled_in); } } return next_tvb; } /* * Show a single fragment in a fragment subtree, and put information about * it in the top-level item for that subtree. */ static void show_fragment(fragment_data *fd, const int offset, const fragment_items *fit, proto_tree *ft, proto_item *fi, const gboolean first_frag, const guint32 count, tvbuff_t *tvb) { proto_item *fei=NULL; int hf; if (first_frag) { gchar *name; if (count == 1) { name = g_strdup(proto_registrar_get_name(*(fit->hf_fragment))); } else { name = g_strdup(proto_registrar_get_name(*(fit->hf_fragments))); } proto_item_set_text(fi, "%u %s (%u byte%s): ", count, name, tvb_length(tvb), plurality(tvb_length(tvb), "", "s")); g_free(name); } else { proto_item_append_text(fi, ", "); } proto_item_append_text(fi, "#%u(%u)", fd->frame, fd->len); if (fd->flags & (FD_OVERLAPCONFLICT |FD_MULTIPLETAILS|FD_TOOLONGFRAGMENT) ) { hf = *(fit->hf_fragment_error); } else { hf = *(fit->hf_fragment); } if (fd->len == 0) { fei = proto_tree_add_uint_format(ft, hf, tvb, offset, fd->len, fd->frame, "Frame: %u (no data)", fd->frame); } else { fei = proto_tree_add_uint_format(ft, hf, tvb, offset, fd->len, fd->frame, "Frame: %u, payload: %u-%u (%u byte%s)", fd->frame, offset, offset+fd->len-1, fd->len, plurality(fd->len, "", "s")); } PROTO_ITEM_SET_GENERATED(fei); if (fd->flags & (FD_OVERLAP|FD_OVERLAPCONFLICT |FD_MULTIPLETAILS|FD_TOOLONGFRAGMENT) ) { /* this fragment has some flags set, create a subtree * for it and display the flags. */ proto_tree *fet=NULL; fet = proto_item_add_subtree(fei, *(fit->ett_fragment)); if (fd->flags&FD_OVERLAP) { fei=proto_tree_add_boolean(fet, *(fit->hf_fragment_overlap), tvb, 0, 0, TRUE); PROTO_ITEM_SET_GENERATED(fei); } if (fd->flags&FD_OVERLAPCONFLICT) { fei=proto_tree_add_boolean(fet, *(fit->hf_fragment_overlap_conflict), tvb, 0, 0, TRUE); PROTO_ITEM_SET_GENERATED(fei); } if (fd->flags&FD_MULTIPLETAILS) { fei=proto_tree_add_boolean(fet, *(fit->hf_fragment_multiple_tails), tvb, 0, 0, TRUE); PROTO_ITEM_SET_GENERATED(fei); } if (fd->flags&FD_TOOLONGFRAGMENT) { fei=proto_tree_add_boolean(fet, *(fit->hf_fragment_too_long_fragment), tvb, 0, 0, TRUE); PROTO_ITEM_SET_GENERATED(fei); } } } static gboolean show_fragment_errs_in_col(fragment_data *fd_head, const fragment_items *fit, packet_info *pinfo) { if (fd_head->flags & (FD_OVERLAPCONFLICT |FD_MULTIPLETAILS|FD_TOOLONGFRAGMENT) ) { if (check_col(pinfo->cinfo, COL_INFO)) { col_add_fstr(pinfo->cinfo, COL_INFO, "[Illegal %s]", fit->tag); return TRUE; } } return FALSE; } /* This function will build the fragment subtree; it's for fragments reassembled with "fragment_add()". It will return TRUE if there were fragmentation errors or FALSE if fragmentation was ok. */ gboolean show_fragment_tree(fragment_data *fd_head, const fragment_items *fit, proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, proto_item **fi) { fragment_data *fd; proto_tree *ft; gboolean first_frag; guint32 count = 0; /* It's not fragmented. */ pinfo->fragmented = FALSE; *fi = proto_tree_add_item(tree, *(fit->hf_fragments), tvb, 0, -1, FALSE); PROTO_ITEM_SET_GENERATED(*fi); ft = proto_item_add_subtree(*fi, *(fit->ett_fragments)); first_frag = TRUE; for (fd = fd_head->next; fd != NULL; fd = fd->next) { count++; } for (fd = fd_head->next; fd != NULL; fd = fd->next) { show_fragment(fd, fd->offset, fit, ft, *fi, first_frag, count, tvb); first_frag = FALSE; } if (fit->hf_fragment_count) { proto_item *fli = proto_tree_add_uint(ft, *(fit->hf_fragment_count), tvb, 0, 0, count); PROTO_ITEM_SET_GENERATED(fli); } if (fit->hf_reassembled_length) { proto_item *fli = proto_tree_add_uint(ft, *(fit->hf_reassembled_length), tvb, 0, 0, tvb_length (tvb)); PROTO_ITEM_SET_GENERATED(fli); } return show_fragment_errs_in_col(fd_head, fit, pinfo); } /* This function will build the fragment subtree; it's for fragments reassembled with "fragment_add_seq()" or "fragment_add_seq_check()". It will return TRUE if there were fragmentation errors or FALSE if fragmentation was ok. */ gboolean show_fragment_seq_tree(fragment_data *fd_head, const fragment_items *fit, proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, proto_item **fi) { guint32 offset, next_offset, count = 0; fragment_data *fd, *last_fd; proto_tree *ft; gboolean first_frag; /* It's not fragmented. */ pinfo->fragmented = FALSE; *fi = proto_tree_add_item(tree, *(fit->hf_fragments), tvb, 0, -1, FALSE); PROTO_ITEM_SET_GENERATED(*fi); ft = proto_item_add_subtree(*fi, *(fit->ett_fragments)); offset = 0; next_offset = 0; last_fd = NULL; first_frag = TRUE; for (fd = fd_head->next; fd != NULL; fd = fd->next){ count++; } for (fd = fd_head->next; fd != NULL; fd = fd->next){ if (last_fd == NULL || last_fd->offset != fd->offset) { offset = next_offset; next_offset += fd->len; } last_fd = fd; show_fragment(fd, offset, fit, ft, *fi, first_frag, count, tvb); first_frag = FALSE; } if (fit->hf_fragment_count) { proto_item *fli = proto_tree_add_uint(ft, *(fit->hf_fragment_count), tvb, 0, 0, count); PROTO_ITEM_SET_GENERATED(fli); } if (fit->hf_reassembled_length) { proto_item *fli = proto_tree_add_uint(ft, *(fit->hf_reassembled_length), tvb, 0, 0, tvb_length (tvb)); PROTO_ITEM_SET_GENERATED(fli); } return show_fragment_errs_in_col(fd_head, fit, pinfo); } /* * Local Variables: * c-basic-offset: 8 * indent-tabs-mode: t * tab-width: 8 * End: */ /* reassemble.c * Routines for {fragment,segment} reassembly * * $Id: reassemble.c 37123 2011-05-13 14:21:58Z morriss $ * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <string.h> #include <epan/packet.h> #include <epan/reassemble.h> #include <epan/emem.h> #include <epan/dissectors/packet-dcerpc.h> typedef struct _fragment_key { address src; address dst; guint32 id; } fragment_key; typedef struct _dcerpc_fragment_key { address src; address dst; guint32 id; e_uuid_t act_id; } dcerpc_fragment_key; #if GLIB_CHECK_VERSION(2,10,0) #else static GMemChunk *fragment_key_chunk = NULL; static GMemChunk *fragment_data_chunk = NULL; static GMemChunk *dcerpc_fragment_key_chunk = NULL; static int fragment_init_count = 200; #endif static void LINK_FRAG(fragment_data *fd_head,fragment_data *fd) { fragment_data *fd_i; /* add fragment to list, keep list sorted */ for(fd_i= fd_head; fd_i->next;fd_i=fd_i->next) { if (fd->offset < fd_i->next->offset ) break; } fd->next=fd_i->next; fd_i->next=fd; } /* copy a fragment key to heap store to insert in the hash */ static void *fragment_key_copy(const void *k) { const fragment_key* key = (const fragment_key*) k; #if GLIB_CHECK_VERSION(2,10,0) fragment_key *new_key = g_slice_new(fragment_key); #else fragment_key *new_key = g_mem_chunk_alloc(fragment_key_chunk); #endif COPY_ADDRESS(&new_key->src, &key->src); COPY_ADDRESS(&new_key->dst, &key->dst); new_key->id = key->id; return new_key; } /* copy a dcerpc fragment key to heap store to insert in the hash */ static void *dcerpc_fragment_key_copy(const void *k) { const dcerpc_fragment_key* key = (const dcerpc_fragment_key*) k; #if GLIB_CHECK_VERSION(2,10,0) dcerpc_fragment_key *new_key = g_slice_new(dcerpc_fragment_key); #else dcerpc_fragment_key *new_key = g_mem_chunk_alloc(dcerpc_fragment_key_chunk); #endif COPY_ADDRESS(&new_key->src, &key->src); COPY_ADDRESS(&new_key->dst, &key->dst); new_key->id = key->id; new_key->act_id = key->act_id; return new_key; } static gint fragment_equal(gconstpointer k1, gconstpointer k2) { const fragment_key* key1 = (const fragment_key*) k1; const fragment_key* key2 = (const fragment_key*) k2; /*key.id is the first item to compare since item is most likely to differ between sessions, thus shortcircuiting the comparasion of addresses. */ return ( ( (key1->id == key2->id) && (ADDRESSES_EQUAL(&key1->src, &key2->src)) && (ADDRESSES_EQUAL(&key1->dst, &key2->dst)) ) ? TRUE : FALSE); } static guint fragment_hash(gconstpointer k) { const fragment_key* key = (const fragment_key*) k; guint hash_val; /* int i; */ hash_val = 0; /* More than likely: in most captures src and dst addresses are the same, and would hash the same. We only use id as the hash as an optimization. for (i = 0; i < key->src.len; i++) hash_val += key->src.data[i]; for (i = 0; i < key->dst.len; i++) hash_val += key->dst.data[i]; */ hash_val += key->id; return hash_val; } static gint dcerpc_fragment_equal(gconstpointer k1, gconstpointer k2) { const dcerpc_fragment_key* key1 = (const dcerpc_fragment_key*) k1; const dcerpc_fragment_key* key2 = (const dcerpc_fragment_key*) k2; /*key.id is the first item to compare since item is most likely to differ between sessions, thus shortcircuiting the comparison of addresses. */ return (((key1->id == key2->id) && (ADDRESSES_EQUAL(&key1->src, &key2->src)) && (ADDRESSES_EQUAL(&key1->dst, &key2->dst)) && (memcmp (&key1->act_id, &key2->act_id, sizeof (e_uuid_t)) == 0)) ? TRUE : FALSE); } static guint dcerpc_fragment_hash(gconstpointer k) { const dcerpc_fragment_key* key = (const dcerpc_fragment_key*) k; guint hash_val; hash_val = 0; hash_val += key->id; hash_val += key->act_id.Data1; hash_val += key->act_id.Data2 << 16; hash_val += key->act_id.Data3; return hash_val; } typedef struct _reassembled_key { guint32 id; guint32 frame; } reassembled_key; static gint reassembled_equal(gconstpointer k1, gconstpointer k2) { const reassembled_key* key1 = (const reassembled_key*) k1; const reassembled_key* key2 = (const reassembled_key*) k2; /* * We assume that the frame numbers are unlikely to be equal, * so we check them first. */ return key1->frame == key2->frame && key1->id == key2->id; } static guint reassembled_hash(gconstpointer k) { const reassembled_key* key = (const reassembled_key*) k; return key->frame; } /* * For a fragment hash table entry, free the associated fragments. * If slices are used (GLIB >= 2.10) the entry value (fd_chain) is * freed herein and the entry is freed when fragment_free_key() * [or dcerpc_fragment_free_key()] is called (as a consequence of * returning TRUE from this function). * If mem_chunks are used, free the address data to which the key * refers; the the actual key and value structures get freed * by "reassemble_cleanup()"). */ static gboolean free_all_fragments(gpointer key_arg _U_, gpointer value, gpointer user_data _U_) { fragment_data *fd_head, *tmp_fd; #if GLIB_CHECK_VERSION(2,10,0) /* If Glib version => 2.10 we do g_hash_table_new_full() and supply a function * to free the key and the addresses. */ #else fragment_key *key = key_arg; /* * Grr. I guess the theory here is that freeing * something sure as heck modifies it, so you * want to ban attempts to free it, but, alas, * if we make the "data" field of an "address" * structure not a "const", the compiler whines if * we try to make it point into the data for a packet, * as that's a "const" array (and should be, as dissectors * shouldn't trash it). * * So we cast the complaint into oblivion, and rely on * the fact that these addresses are known to have had * their data mallocated, i.e. they don't point into, * say, the middle of the data for a packet. */ g_free((gpointer)key->src.data); g_free((gpointer)key->dst.data); #endif for (fd_head = value; fd_head != NULL; fd_head = tmp_fd) { tmp_fd=fd_head->next; if(fd_head->data && !(fd_head->flags&FD_NOT_MALLOCED)) g_free(fd_head->data); #if GLIB_CHECK_VERSION(2,10,0) g_slice_free(fragment_data, fd_head); #endif } return TRUE; } /* ------------------------- */ static fragment_data *new_head(const guint32 flags) { fragment_data *fd_head; /* If head/first structure in list only holds no other data than * 'datalen' then we don't have to change the head of the list * even if we want to keep it sorted */ #if GLIB_CHECK_VERSION(2,10,0) fd_head=g_slice_new0(fragment_data); #else fd_head=g_mem_chunk_alloc0(fragment_data_chunk); #endif fd_head->flags=flags; return fd_head; } /* * For a reassembled-packet hash table entry, free the fragment data * to which the value refers. * (The actual value structures get freed by "reassemble_cleanup()".) */ static gboolean free_all_reassembled_fragments(gpointer key_arg _U_, gpointer value, gpointer user_data _U_) { fragment_data *fd_head; for (fd_head = value; fd_head != NULL; fd_head = fd_head->next) { if(fd_head->data && !(fd_head->flags&FD_NOT_MALLOCED)) { g_free(fd_head->data); /* * A reassembled packet is inserted into the * hash table once for every frame that made * up the reassembled packet; clear the data * pointer so that we only free the data the * first time we see it. */ fd_head->data = NULL; } } return TRUE; } #if GLIB_CHECK_VERSION(2,10,0) static void fragment_free_key(void *ptr) { fragment_key *key = (fragment_key *)ptr; if(key){ /* * Free up the copies of the addresses from the old key. */ g_free((gpointer)key->src.data); g_free((gpointer)key->dst.data); g_slice_free(fragment_key, key); } } static void dcerpc_fragment_free_key(void *ptr) { dcerpc_fragment_key *key = (dcerpc_fragment_key *)ptr; if(key){ /* * Free up the copies of the addresses from the old key. */ g_free((gpointer)key->src.data); g_free((gpointer)key->dst.data); g_slice_free(dcerpc_fragment_key, key); } } #endif /* * Initialize a fragment table. */ void fragment_table_init(GHashTable **fragment_table) { if (*fragment_table != NULL) { /* * The fragment hash table exists. * * Remove all entries and free fragment data for each entry. * * If slices are used (GLIB >= 2.10) * the keys are freed by calling fragment_free_key() * and the values are freed in free_all_fragments(). * * If mem_chunks are used, the key and value data * are freed by "reassemble_cleanup()". free_all_fragments() * will free the adrress data associated with the key */ g_hash_table_foreach_remove(*fragment_table, free_all_fragments, NULL); } else { #if GLIB_CHECK_VERSION(2,10,0) /* The fragment table does not exist. Create it */ *fragment_table = g_hash_table_new_full(fragment_hash, fragment_equal, fragment_free_key, NULL); #else /* The fragment table does not exist. Create it */ *fragment_table = g_hash_table_new(fragment_hash, fragment_equal); #endif } } void dcerpc_fragment_table_init(GHashTable **fragment_table) { if (*fragment_table != NULL) { /* * The fragment hash table exists. * * Remove all entries and free fragment data for each entry. * * If slices are used (GLIB >= 2.10) * the keys are freed by calling dcerpc_fragment_free_key() * and the values are freed in free_all_fragments(). * * If mem_chunks are used, the key and value data * are freed by "reassemble_cleanup()". free_all_fragments() * will free the adrress data associated with the key */ g_hash_table_foreach_remove(*fragment_table, free_all_fragments, NULL); } else { #if GLIB_CHECK_VERSION(2,10,0) /* The fragment table does not exist. Create it */ *fragment_table = g_hash_table_new_full(dcerpc_fragment_hash, dcerpc_fragment_equal, dcerpc_fragment_free_key, NULL); #else /* The fragment table does not exist. Create it */ *fragment_table = g_hash_table_new(dcerpc_fragment_hash, dcerpc_fragment_equal); #endif } } /* * Initialize a reassembled-packet table. */ void reassembled_table_init(GHashTable **reassembled_table) { if (*reassembled_table != NULL) { /* * The reassembled-packet hash table exists. * * Remove all entries and free reassembled packet * data for each entry. (The key data is freed * by "reassemble_cleanup()".) */ g_hash_table_foreach_remove(*reassembled_table, free_all_reassembled_fragments, NULL); } else { /* The fragment table does not exist. Create it */ *reassembled_table = g_hash_table_new(reassembled_hash, reassembled_equal); } } /* * Free up all space allocated for fragment keys and data and * reassembled keys. */ void reassemble_cleanup(void) { #if GLIB_CHECK_VERSION(2,10,0) #else if (fragment_key_chunk != NULL) g_mem_chunk_destroy(fragment_key_chunk); if (dcerpc_fragment_key_chunk != NULL) g_mem_chunk_destroy(dcerpc_fragment_key_chunk); if (fragment_data_chunk != NULL) g_mem_chunk_destroy(fragment_data_chunk); fragment_key_chunk = NULL; dcerpc_fragment_key_chunk = NULL; fragment_data_chunk = NULL; #endif } void reassemble_init(void) { #if GLIB_CHECK_VERSION(2,10,0) #else fragment_key_chunk = g_mem_chunk_new("fragment_key_chunk", sizeof(fragment_key), fragment_init_count * sizeof(fragment_key), G_ALLOC_AND_FREE); dcerpc_fragment_key_chunk = g_mem_chunk_new("dcerpc_fragment_key_chunk", sizeof(dcerpc_fragment_key), fragment_init_count * sizeof(dcerpc_fragment_key), G_ALLOC_AND_FREE); fragment_data_chunk = g_mem_chunk_new("fragment_data_chunk", sizeof(fragment_data), fragment_init_count * sizeof(fragment_data), G_ALLOC_ONLY); #endif } /* This function cleans up the stored state and removes the reassembly data and * (with one exception) all allocated memory for matching reassembly. * * The exception is : * If the PDU was already completely reassembled, then the buffer containing the * reassembled data WILL NOT be free()d, and the pointer to that buffer will be * returned. * Othervise the function will return NULL. * * So, if you call fragment_delete and it returns non-NULL, YOU are responsible to * g_free() that buffer. */ unsigned char * fragment_delete(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table) { fragment_data *fd_head, *fd; fragment_key key; unsigned char *data=NULL; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup(fragment_table, &key); if(fd_head==NULL){ /* We do not recognize this as a PDU we have seen before. return */ return NULL; } data=fd_head->data; /* loop over all partial fragments and free any buffers */ for(fd=fd_head->next;fd;){ fragment_data *tmp_fd; tmp_fd=fd->next; if( !(fd->flags&FD_NOT_MALLOCED) ) g_free(fd->data); #if GLIB_CHECK_VERSION(2,10,0) g_slice_free(fragment_data, fd); #else g_mem_chunk_free(fragment_data_chunk, fd); #endif fd=tmp_fd; } #if GLIB_CHECK_VERSION(2,10,0) g_slice_free(fragment_data, fd_head); #else g_mem_chunk_free(fragment_data_chunk, fd_head); #endif g_hash_table_remove(fragment_table, &key); return data; } /* This function is used to check if there is partial or completed reassembly state * matching this packet. I.e. Is there reassembly going on or not for this packet? */ fragment_data * fragment_get(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table) { fragment_data *fd_head; fragment_key key; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup(fragment_table, &key); return fd_head; } /* id *must* be the frame number for this to work! */ fragment_data * fragment_get_reassembled(const guint32 id, GHashTable *reassembled_table) { fragment_data *fd_head; reassembled_key key; /* create key to search hash with */ key.frame = id; key.id = id; fd_head = g_hash_table_lookup(reassembled_table, &key); return fd_head; } fragment_data * fragment_get_reassembled_id(const packet_info *pinfo, const guint32 id, GHashTable *reassembled_table) { fragment_data *fd_head; reassembled_key key; /* create key to search hash with */ key.frame = pinfo->fd->num; key.id = id; fd_head = g_hash_table_lookup(reassembled_table, &key); return fd_head; } /* This function can be used to explicitly set the total length (if known) * for reassembly of a PDU. * This is useful for reassembly of PDUs where one may have the total length specified * in the first fragment instead of as for, say, IPv4 where a flag indicates which * is the last fragment. * * Such protocols might fragment_add with a more_frags==TRUE for every fragment * and just tell the reassembly engine the expected total length of the reassembled data * using fragment_set_tot_len immediately after doing fragment_add for the first packet. * * Note that for FD_BLOCKSEQUENCE tot_len is the index for the tail fragment. * i.e. since the block numbers start at 0, if we specify tot_len==2, that * actually means we want to defragment 3 blocks, block 0, 1 and 2. */ void fragment_set_tot_len(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, const guint32 tot_len) { fragment_data *fd_head; fragment_key key; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup(fragment_table, &key); if(fd_head){ fd_head->datalen = tot_len; fd_head->flags |= FD_DATALEN_SET; } return; } guint32 fragment_get_tot_len(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table) { fragment_data *fd_head; fragment_key key; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup(fragment_table, &key); if(fd_head){ return fd_head->datalen; } return 0; } /* This function will set the partial reassembly flag for a fh. When this function is called, the fh MUST already exist, i.e. the fh MUST be created by the initial call to fragment_add() before this function is called. Also note that this function MUST be called to indicate a fh will be extended (increase the already stored data) */ void fragment_set_partial_reassembly(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table) { fragment_data *fd_head; fragment_key key; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup(fragment_table, &key); /* * XXX - why not do all the stuff done early in "fragment_add_work()", * turning off FD_DEFRAGMENTED and pointing the fragments' data * pointers to the appropriate part of the already-reassembled * data, and clearing the data length and "reassembled in" frame * number, here? We currently have a hack in the TCP dissector * not to set the "reassembled in" value if the "partial reassembly" * flag is set, so that in the first pass through the packets * we don't falsely set a packet as reassembled in that packet * if the dissector decided that even more reassembly was needed. */ if(fd_head){ fd_head->flags |= FD_PARTIAL_REASSEMBLY; } } /* * This function gets rid of an entry from a fragment table, given * a pointer to the key for that entry; it also frees up the key * and the addresses in it. * Note: If we use slices keys are freed by fragment_free_key() [or dcerpc_fragment_free_key()] being called * during g_hash_table_remove(). */ static void fragment_unhash(GHashTable *fragment_table, fragment_key *key) { /* * Remove the entry from the fragment table. */ g_hash_table_remove(fragment_table, key); /* * Free the key itself. */ #if GLIB_CHECK_VERSION(2,10,0) #else /* * Free up the copies of the addresses from the old key. */ g_free((gpointer)key->src.data); g_free((gpointer)key->dst.data); g_mem_chunk_free(fragment_key_chunk, key); #endif } /* * This function adds fragment_data structure to a reassembled-packet * hash table, using the frame numbers of each of the frames from * which it was reassembled as keys, and sets the "reassembled_in" * frame number. */ static void fragment_reassembled(fragment_data *fd_head, const packet_info *pinfo, GHashTable *reassembled_table, const guint32 id) { reassembled_key *new_key; fragment_data *fd; if (fd_head->next == NULL) { /* * This was not fragmented, so there's no fragment * table; just hash it using the current frame number. */ new_key = se_alloc(sizeof(reassembled_key)); new_key->frame = pinfo->fd->num; new_key->id = id; g_hash_table_insert(reassembled_table, new_key, fd_head); } else { /* * Hash it with the frame numbers for all the frames. */ for (fd = fd_head->next; fd != NULL; fd = fd->next){ new_key = se_alloc(sizeof(reassembled_key)); new_key->frame = fd->frame; new_key->id = id; g_hash_table_insert(reassembled_table, new_key, fd_head); } } fd_head->flags |= FD_DEFRAGMENTED; fd_head->reassembled_in = pinfo->fd->num; } /* * This function adds a new fragment to the fragment hash table. * If this is the first fragment seen for this datagram, a new entry * is created in the hash table, otherwise this fragment is just added * to the linked list of fragments for this packet. * The list of fragments for a specific datagram is kept sorted for * easier handling. * * Returns a pointer to the head of the fragment data list if we have all the * fragments, NULL otherwise. * * This function assumes frag_offset being a byte offset into the defragment * packet. * * 01-2002 * Once the fh is defragmented (= FD_DEFRAGMENTED set), it can be * extended using the FD_PARTIAL_REASSEMBLY flag. This flag should be set * using fragment_set_partial_reassembly() before calling fragment_add * with the new fragment. FD_TOOLONGFRAGMENT and FD_MULTIPLETAILS flags * are lowered when a new extension process is started. */ static gboolean fragment_add_work(fragment_data *fd_head, tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 frag_offset, const guint32 frag_data_len, const gboolean more_frags) { fragment_data *fd; fragment_data *fd_i; guint32 max, dfpos; unsigned char *old_data; /* create new fd describing this fragment */ #if GLIB_CHECK_VERSION(2,10,0) fd = g_slice_new(fragment_data); #else fd = g_mem_chunk_alloc(fragment_data_chunk); #endif fd->next = NULL; fd->flags = 0; fd->frame = pinfo->fd->num; if (fd->frame > fd_head->frame) fd_head->frame = fd->frame; fd->offset = frag_offset; fd->len = frag_data_len; fd->data = NULL; /* * If it was already defragmented and this new fragment goes beyond * data limits, set flag in already empty fds & point old fds to malloc'ed data. */ if(fd_head->flags & FD_DEFRAGMENTED && (frag_offset+frag_data_len) >= fd_head->datalen && fd_head->flags & FD_PARTIAL_REASSEMBLY){ for(fd_i=fd_head->next; fd_i; fd_i=fd_i->next){ if( !fd_i->data ) { fd_i->data = fd_head->data + fd_i->offset; fd_i->flags |= FD_NOT_MALLOCED; } fd_i->flags &= (~FD_TOOLONGFRAGMENT) & (~FD_MULTIPLETAILS); } fd_head->flags &= ~(FD_DEFRAGMENTED|FD_PARTIAL_REASSEMBLY|FD_DATALEN_SET); fd_head->flags &= (~FD_TOOLONGFRAGMENT) & (~FD_MULTIPLETAILS); fd_head->datalen=0; fd_head->reassembled_in=0; } if (!more_frags) { /* * This is the tail fragment in the sequence. */ if (fd_head->flags & FD_DATALEN_SET) { /* ok we have already seen other tails for this packet * it might be a duplicate. */ if (fd_head->datalen != (fd->offset + fd->len) ){ /* Oops, this tail indicates a different packet * len than the previous ones. Something's wrong. */ fd->flags |= FD_MULTIPLETAILS; fd_head->flags |= FD_MULTIPLETAILS; } } else { /* this was the first tail fragment, now we know the * length of the packet */ fd_head->datalen = fd->offset + fd->len; fd_head->flags |= FD_DATALEN_SET; } } /* If the packet is already defragmented, this MUST be an overlap. * The entire defragmented packet is in fd_head->data. * Even if we have previously defragmented this packet, we still * check it. Someone might play overlap and TTL games. */ if (fd_head->flags & FD_DEFRAGMENTED) { guint32 end_offset = fd->offset + fd->len; fd->flags |= FD_OVERLAP; fd_head->flags |= FD_OVERLAP; /* make sure it's not too long */ if (end_offset > fd_head->datalen || end_offset < fd->offset || end_offset < fd->len) { fd->flags |= FD_TOOLONGFRAGMENT; fd_head->flags |= FD_TOOLONGFRAGMENT; } /* make sure it doesn't conflict with previous data */ else if ( memcmp(fd_head->data+fd->offset, tvb_get_ptr(tvb,offset,fd->len),fd->len) ){ fd->flags |= FD_OVERLAPCONFLICT; fd_head->flags |= FD_OVERLAPCONFLICT; } /* it was just an overlap, link it and return */ LINK_FRAG(fd_head,fd); return TRUE; } /* If we have reached this point, the packet is not defragmented yet. * Save all payload in a buffer until we can defragment. * XXX - what if we didn't capture the entire fragment due * to a too-short snapshot length? */ fd->data = g_malloc(fd->len); tvb_memcpy(tvb, fd->data, offset, fd->len); LINK_FRAG(fd_head,fd); if( !(fd_head->flags & FD_DATALEN_SET) ){ /* if we dont know the datalen, there are still missing * packets. Cheaper than the check below. */ return FALSE; } /* * Check if we have received the entire fragment. * This is easy since the list is sorted and the head is faked. * * First, we compute the amount of contiguous data that's * available. (The check for fd_i->offset <= max rules out * fragments that don't start before or at the end of the * previous fragment, i.e. fragments that have a gap between * them and the previous fragment.) */ max = 0; for (fd_i=fd_head->next;fd_i;fd_i=fd_i->next) { if ( ((fd_i->offset)<=max) && ((fd_i->offset+fd_i->len)>max) ){ max = fd_i->offset+fd_i->len; } } if (max < (fd_head->datalen)) { /* * The amount of contiguous data we have is less than the * amount of data we're trying to reassemble, so we haven't * received all packets yet. */ return FALSE; } if (max > (fd_head->datalen)) { /*XXX not sure if current fd was the TOOLONG*/ /*XXX is it fair to flag current fd*/ /* oops, too long fragment detected */ fd->flags |= FD_TOOLONGFRAGMENT; fd_head->flags |= FD_TOOLONGFRAGMENT; } /* we have received an entire packet, defragment it and * free all fragments */ /* store old data just in case */ old_data=fd_head->data; fd_head->data = g_malloc(max); /* add all data fragments */ for (dfpos=0,fd_i=fd_head;fd_i;fd_i=fd_i->next) { if (fd_i->len) { /* dfpos is always >= than fd_i->offset */ /* No gaps can exist here, max_loop(above) does this */ /* XXX - true? Can we get fd_i->offset+fd-i->len */ /* overflowing, for example? */ /* Actually: there is at least one pathological case wherein there can be fragments * on the list which are for offsets greater than max (i.e.: following a gap after max). * (Apparently a "DESEGMENT_UNTIL_FIN" was involved wherein the FIN packet had an offset * less than the highest fragment offset seen. [Seen from a fuzz-test: bug #2470]). * Note that the "overlap" compare must only be done for fragments with (offset+len) <= max * and thus within the newly g_malloc'd buffer. */ if ( fd_i->offset+fd_i->len > dfpos ) { if (fd_i->offset+fd_i->len > max) g_warning("Reassemble error in frame %u: offset %u + len %u > max %u", pinfo->fd->num, fd_i->offset, fd_i->len, max); else if (dfpos < fd_i->offset) g_warning("Reassemble error in frame %u: dfpos %u < offset %u", pinfo->fd->num, dfpos, fd_i->offset); else if (dfpos-fd_i->offset > fd_i->len) g_warning("Reassemble error in frame %u: dfpos %u - offset %u > len %u", pinfo->fd->num, dfpos, fd_i->offset, fd_i->len); else if (!fd_head->data) g_warning("Reassemble error in frame %u: no data", pinfo->fd->num); else { if (fd_i->offset < dfpos) { fd_i->flags |= FD_OVERLAP; fd_head->flags |= FD_OVERLAP; if ( memcmp(fd_head->data+fd_i->offset, fd_i->data, MIN(fd_i->len,(dfpos-fd_i->offset)) ) ) { fd_i->flags |= FD_OVERLAPCONFLICT; fd_head->flags |= FD_OVERLAPCONFLICT; } } memcpy(fd_head->data+dfpos, fd_i->data+(dfpos-fd_i->offset), fd_i->len-(dfpos-fd_i->offset)); } } else { if (fd_i->offset + fd_i->len < fd_i->offset) /* Integer overflow? */ g_warning("Reassemble error in frame %u: offset %u + len %u < offset", pinfo->fd->num, fd_i->offset, fd_i->len); } if( fd_i->flags & FD_NOT_MALLOCED ) fd_i->flags &= ~FD_NOT_MALLOCED; else g_free(fd_i->data); fd_i->data=NULL; dfpos=MAX(dfpos,(fd_i->offset+fd_i->len)); } } g_free(old_data); /* mark this packet as defragmented. allows us to skip any trailing fragments */ fd_head->flags |= FD_DEFRAGMENTED; fd_head->reassembled_in=pinfo->fd->num; return TRUE; } static fragment_data * fragment_add_common(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, const guint32 frag_offset, const guint32 frag_data_len, const gboolean more_frags, const gboolean check_already_added) { fragment_key key, *new_key; fragment_data *fd_head; fragment_data *fd_item; gboolean already_added=pinfo->fd->flags.visited; /* dissector shouldn't give us garbage tvb info */ DISSECTOR_ASSERT(tvb_bytes_exist(tvb, offset, frag_data_len)); /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup(fragment_table, &key); #if 0 /* debug output of associated fragments. */ /* leave it here for future debugging sessions */ if(strcmp(pinfo->current_proto, "DCERPC") == 0) { printf("proto:%s num:%u id:%u offset:%u len:%u more:%u visited:%u\n", pinfo->current_proto, pinfo->fd->num, id, frag_offset, frag_data_len, more_frags, pinfo->fd->flags.visited); if(fd_head != NULL) { for(fd_item=fd_head->next;fd_item;fd_item=fd_item->next){ printf("fd_frame:%u fd_offset:%u len:%u datalen:%u\n", fd_item->frame, fd_item->offset, fd_item->len, fd_item->datalen); } } } #endif /* * "already_added" is true if "pinfo->fd->flags.visited" is true; * if "pinfo->fd->flags.visited", this isn't the first pass, so * we've already done all the reassembly and added all the * fragments. * * If it's not true, but "check_already_added" is true, just check * if we have seen this fragment before, i.e., if we have already * added it to reassembly. * That can be true even if "pinfo->fd->flags.visited" is false * since we sometimes might call a subdissector multiple times. * As an additional check, just make sure we have not already added * this frame to the reassembly list, if there is a reassembly list; * note that the first item in the reassembly list is not a * fragment, it's a data structure for the reassembled packet. * We don't check it because its "frame" member isn't initialized * to anything, and because it doesn't count in any case. * * And as another additional check, make sure the fragment offsets are * the same, as otherwise we get into trouble if multiple fragments * are in one PDU. */ if (!already_added && check_already_added && fd_head != NULL) { if (pinfo->fd->num <= fd_head->frame) { for(fd_item=fd_head->next;fd_item;fd_item=fd_item->next){ if(pinfo->fd->num==fd_item->frame && frag_offset==fd_item->offset){ already_added=TRUE; } } } } /* have we already added this frame ?*/ if (already_added) { if (fd_head != NULL && fd_head->flags & FD_DEFRAGMENTED) { return fd_head; } else { return NULL; } } if (fd_head==NULL){ /* not found, this must be the first snooped fragment for this * packet. Create list-head. */ fd_head = new_head(0); /* * We're going to use the key to insert the fragment, * so allocate a structure for it, and copy the * addresses, allocating new buffers for the address * data. */ #if GLIB_CHECK_VERSION(2,10,0) new_key = g_slice_new(fragment_key); #else new_key = g_mem_chunk_alloc(fragment_key_chunk); #endif COPY_ADDRESS(&new_key->src, &key.src); COPY_ADDRESS(&new_key->dst, &key.dst); new_key->id = key.id; g_hash_table_insert(fragment_table, new_key, fd_head); } if (fragment_add_work(fd_head, tvb, offset, pinfo, frag_offset, frag_data_len, more_frags)) { /* * Reassembly is complete. */ return fd_head; } else { /* * Reassembly isn't complete. */ return NULL; } } fragment_data * fragment_add(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, const guint32 frag_offset, const guint32 frag_data_len, const gboolean more_frags) { return fragment_add_common(tvb, offset, pinfo, id, fragment_table, frag_offset, frag_data_len, more_frags, TRUE); } /* * For use when you can have multiple fragments in the same frame added * to the same reassembled PDU, e.g. with ONC RPC-over-TCP. */ fragment_data * fragment_add_multiple_ok(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, const guint32 frag_offset, const guint32 frag_data_len, const gboolean more_frags) { return fragment_add_common(tvb, offset, pinfo, id, fragment_table, frag_offset, frag_data_len, more_frags, FALSE); } fragment_data * fragment_add_check(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, GHashTable *reassembled_table, const guint32 frag_offset, const guint32 frag_data_len, const gboolean more_frags) { reassembled_key reass_key; fragment_key key, *new_key, *old_key; gpointer orig_key, value; fragment_data *fd_head; /* * If this isn't the first pass, look for this frame in the table * of reassembled packets. */ if (pinfo->fd->flags.visited) { reass_key.frame = pinfo->fd->num; reass_key.id = id; return g_hash_table_lookup(reassembled_table, &reass_key); } /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; /* Looks up a key in the GHashTable, returning the original key and the associated value * and a gboolean which is TRUE if the key was found. This is useful if you need to free * the memory allocated for the original key, for example before calling g_hash_table_remove() */ if (!g_hash_table_lookup_extended(fragment_table, &key, &orig_key, &value)) { /* not found, this must be the first snooped fragment for this * packet. Create list-head. */ fd_head = new_head(0); /* * We're going to use the key to insert the fragment, * so allocate a structure for it, and copy the * addresses, allocating new buffers for the address * data. */ #if GLIB_CHECK_VERSION(2,10,0) new_key = g_slice_new(fragment_key); #else new_key = g_mem_chunk_alloc(fragment_key_chunk); #endif COPY_ADDRESS(&new_key->src, &key.src); COPY_ADDRESS(&new_key->dst, &key.dst); new_key->id = key.id; g_hash_table_insert(fragment_table, new_key, fd_head); orig_key = new_key; /* for unhashing it later */ } else { /* * We found it. */ fd_head = value; } /* * If this is a short frame, then we can't, and don't, do * reassembly on it. We just give up. */ if (tvb_reported_length(tvb) > tvb_length(tvb)) return NULL; if (fragment_add_work(fd_head, tvb, offset, pinfo, frag_offset, frag_data_len, more_frags)) { /* * Reassembly is complete. * Remove this from the table of in-progress * reassemblies, add it to the table of * reassembled packets, and return it. */ /* * Remove this from the table of in-progress reassemblies, * and free up any memory used for it in that table. */ old_key = orig_key; fragment_unhash(fragment_table, old_key); /* * Add this item to the table of reassembled packets. */ fragment_reassembled(fd_head, pinfo, reassembled_table, id); return fd_head; } else { /* * Reassembly isn't complete. */ return NULL; } } static void fragment_defragment_and_free (fragment_data *fd_head, const packet_info *pinfo) { fragment_data *fd_i = NULL; fragment_data *last_fd = NULL; guint32 dfpos = 0, size = 0; void *old_data = NULL; for(fd_i=fd_head->next;fd_i;fd_i=fd_i->next) { if(!last_fd || last_fd->offset!=fd_i->offset){ size+=fd_i->len; } last_fd=fd_i; } /* store old data in case the fd_i->data pointers refer to it */ old_data=fd_head->data; fd_head->data = g_malloc(size); fd_head->len = size; /* record size for caller */ /* add all data fragments */ last_fd=NULL; for (fd_i=fd_head->next; fd_i; fd_i=fd_i->next) { if (fd_i->len) { if(!last_fd || last_fd->offset != fd_i->offset) { /* First fragment or in-sequence fragment */ memcpy(fd_head->data+dfpos, fd_i->data, fd_i->len); dfpos += fd_i->len; } else { /* duplicate/retransmission/overlap */ fd_i->flags |= FD_OVERLAP; fd_head->flags |= FD_OVERLAP; if(last_fd->len != fd_i->len || memcmp(last_fd->data, fd_i->data, last_fd->len) ) { fd_i->flags |= FD_OVERLAPCONFLICT; fd_head->flags |= FD_OVERLAPCONFLICT; } } } last_fd=fd_i; } /* we have defragmented the pdu, now free all fragments*/ for (fd_i=fd_head->next;fd_i;fd_i=fd_i->next) { if( fd_i->flags & FD_NOT_MALLOCED ) fd_i->flags &= ~FD_NOT_MALLOCED; else g_free(fd_i->data); fd_i->data=NULL; } g_free(old_data); /* mark this packet as defragmented. * allows us to skip any trailing fragments. */ fd_head->flags |= FD_DEFRAGMENTED; fd_head->reassembled_in=pinfo->fd->num; } /* * This function adds a new fragment to the entry for a reassembly * operation. * * The list of fragments for a specific datagram is kept sorted for * easier handling. * * Returns TRUE if we have all the fragments, FALSE otherwise. * * This function assumes frag_number being a block sequence number. * The bsn for the first block is 0. */ static gboolean fragment_add_seq_work(fragment_data *fd_head, tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags, const guint32 flags _U_) { fragment_data *fd; fragment_data *fd_i; fragment_data *last_fd; guint32 max, dfpos; /* if the partial reassembly flag has been set, and we are extending * the pdu, un-reassemble the pdu. This means pointing old fds to malloc'ed data. */ if(fd_head->flags & FD_DEFRAGMENTED && frag_number >= fd_head->datalen && fd_head->flags & FD_PARTIAL_REASSEMBLY){ guint32 lastdfpos = 0; dfpos = 0; for(fd_i=fd_head->next; fd_i; fd_i=fd_i->next){ if( !fd_i->data ) { if( fd_i->flags & FD_OVERLAP ) { /* this is a duplicate of the previous * fragment. */ fd_i->data = fd_head->data + lastdfpos; } else { fd_i->data = fd_head->data + dfpos; lastdfpos = dfpos; dfpos += fd_i->len; } fd_i->flags |= FD_NOT_MALLOCED; } fd_i->flags &= (~FD_TOOLONGFRAGMENT) & (~FD_MULTIPLETAILS); } fd_head->flags &= ~(FD_DEFRAGMENTED|FD_PARTIAL_REASSEMBLY|FD_DATALEN_SET); fd_head->flags &= (~FD_TOOLONGFRAGMENT) & (~FD_MULTIPLETAILS); fd_head->datalen=0; fd_head->reassembled_in=0; } /* create new fd describing this fragment */ #if GLIB_CHECK_VERSION(2,10,0) fd = g_slice_new(fragment_data); #else fd = g_mem_chunk_alloc(fragment_data_chunk); #endif fd->next = NULL; fd->flags = 0; fd->frame = pinfo->fd->num; fd->offset = frag_number; fd->len = frag_data_len; fd->data = NULL; if (!more_frags) { /* * This is the tail fragment in the sequence. */ if (fd_head->flags&FD_DATALEN_SET) { /* ok we have already seen other tails for this packet * it might be a duplicate. */ if (fd_head->datalen != fd->offset ){ /* Oops, this tail indicates a different packet * len than the previous ones. Something's wrong. */ fd->flags |= FD_MULTIPLETAILS; fd_head->flags |= FD_MULTIPLETAILS; } } else { /* this was the first tail fragment, now we know the * sequence number of that fragment (which is NOT * the length of the packet!) */ fd_head->datalen = fd->offset; fd_head->flags |= FD_DATALEN_SET; } } /* If the packet is already defragmented, this MUST be an overlap. * The entire defragmented packet is in fd_head->data * Even if we have previously defragmented this packet, we still check * check it. Someone might play overlap and TTL games. */ if (fd_head->flags & FD_DEFRAGMENTED) { fd->flags |= FD_OVERLAP; fd_head->flags |= FD_OVERLAP; /* make sure it's not past the end */ if (fd->offset > fd_head->datalen) { /* new fragment comes after the end */ fd->flags |= FD_TOOLONGFRAGMENT; fd_head->flags |= FD_TOOLONGFRAGMENT; LINK_FRAG(fd_head,fd); return TRUE; } /* make sure it doesn't conflict with previous data */ dfpos=0; last_fd=NULL; for (fd_i=fd_head->next;fd_i && (fd_i->offset!=fd->offset);fd_i=fd_i->next) { if (!last_fd || last_fd->offset!=fd_i->offset){ dfpos += fd_i->len; } last_fd=fd_i; } if(fd_i){ /* new fragment overlaps existing fragment */ if(fd_i->len!=fd->len){ /* * They have different lengths; this * is definitely a conflict. */ fd->flags |= FD_OVERLAPCONFLICT; fd_head->flags |= FD_OVERLAPCONFLICT; LINK_FRAG(fd_head,fd); return TRUE; } DISSECTOR_ASSERT(fd_head->len >= dfpos + fd->len); if ( memcmp(fd_head->data+dfpos, tvb_get_ptr(tvb,offset,fd->len),fd->len) ){ /* * They have the same length, but the * data isn't the same. */ fd->flags |= FD_OVERLAPCONFLICT; fd_head->flags |= FD_OVERLAPCONFLICT; LINK_FRAG(fd_head,fd); return TRUE; } /* it was just an overlap, link it and return */ LINK_FRAG(fd_head,fd); return TRUE; } else { /* * New fragment doesn't overlap an existing * fragment - there was presumably a gap in * the sequence number space. * * XXX - what should we do here? Is it always * the case that there are no gaps, or are there * protcols using sequence numbers where there * can be gaps? * * If the former, the check below for having * received all the fragments should check for * holes in the sequence number space and for the * first sequence number being 0. If we do that, * the only way we can get here is if this fragment * is past the end of the sequence number space - * but the check for "fd->offset > fd_head->datalen" * would have caught that above, so it can't happen. * * If the latter, we don't have a good way of * knowing whether reassembly is complete if we * get packet out of order such that the "last" * fragment doesn't show up last - but, unless * in-order reliable delivery of fragments is * guaranteed, an implementation of the protocol * has no way of knowing whether reassembly is * complete, either. * * For now, we just link the fragment in and * return. */ LINK_FRAG(fd_head,fd); return TRUE; } } /* If we have reached this point, the packet is not defragmented yet. * Save all payload in a buffer until we can defragment. * XXX - what if we didn't capture the entire fragment due * to a too-short snapshot length? */ /* check len, there may be a fragment with 0 len, that is actually the tail */ if (fd->len) { fd->data = g_malloc(fd->len); tvb_memcpy(tvb, fd->data, offset, fd->len); } LINK_FRAG(fd_head,fd); if( !(fd_head->flags & FD_DATALEN_SET) ){ /* if we dont know the sequence number of the last fragment, * there are definitely still missing packets. Cheaper than * the check below. */ return FALSE; } /* check if we have received the entire fragment * this is easy since the list is sorted and the head is faked. * common case the whole list is scanned. */ max = 0; for(fd_i=fd_head->next;fd_i;fd_i=fd_i->next) { if ( fd_i->offset==max ){ max++; } } /* max will now be datalen+1 if all fragments have been seen */ if (max <= fd_head->datalen) { /* we have not received all packets yet */ return FALSE; } if (max > (fd_head->datalen+1)) { /* oops, too long fragment detected */ fd->flags |= FD_TOOLONGFRAGMENT; fd_head->flags |= FD_TOOLONGFRAGMENT; } /* we have received an entire packet, defragment it and * free all fragments */ fragment_defragment_and_free(fd_head, pinfo); return TRUE; } /* * This function adds a new fragment to the fragment hash table. * If this is the first fragment seen for this datagram, a new entry * is created in the hash table, otherwise this fragment is just added * to the linked list of fragments for this packet. * * Returns a pointer to the head of the fragment data list if we have all the * fragments, NULL otherwise. * * This function assumes frag_number being a block sequence number. * The bsn for the first block is 0. */ fragment_data * fragment_add_seq(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, const guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags) { fragment_key key; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; return fragment_add_seq_key(tvb, offset, pinfo, &key, fragment_key_copy, fragment_table, frag_number, frag_data_len, more_frags, 0); } fragment_data * fragment_add_dcerpc_dg(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, void *v_act_id, GHashTable *fragment_table, const guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags) { e_uuid_t *act_id = (e_uuid_t *)v_act_id; dcerpc_fragment_key key; /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; key.act_id = *act_id; return fragment_add_seq_key(tvb, offset, pinfo, &key, dcerpc_fragment_key_copy, fragment_table, frag_number, frag_data_len, more_frags, 0); } fragment_data * fragment_add_seq_key(tvbuff_t *tvb, const int offset, const packet_info *pinfo, void *key, fragment_key_copier key_copier, GHashTable *fragment_table, guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags, const guint32 flags) { fragment_data *fd_head; fd_head = g_hash_table_lookup(fragment_table, key); /* have we already seen this frame ?*/ if (pinfo->fd->flags.visited) { if (fd_head != NULL && fd_head->flags & FD_DEFRAGMENTED) { return fd_head; } else { return NULL; } } if (fd_head==NULL){ /* not found, this must be the first snooped fragment for this * packet. Create list-head. */ fd_head= new_head(FD_BLOCKSEQUENCE); if((flags & (REASSEMBLE_FLAGS_NO_FRAG_NUMBER|REASSEMBLE_FLAGS_802_11_HACK)) && !more_frags) { /* * This is the last fragment for this packet, and * is the only one we've seen. * * Either we don't have sequence numbers, in which * case we assume this is the first fragment for * this packet, or we're doing special 802.11 * processing, in which case we assume it's one * of those reassembled packets with a non-zero * fragment number (see packet-80211.c); just * return a pointer to the head of the list; * fragment_add_seq_check will then add it to the table * of reassembled packets. */ fd_head->reassembled_in=pinfo->fd->num; return fd_head; } /* * We're going to use the key to insert the fragment, * so copy it to a long-term store. */ if(key_copier != NULL) key = key_copier(key); g_hash_table_insert(fragment_table, key, fd_head); /* * If we weren't given an initial fragment number, * make it 0. */ if (flags & REASSEMBLE_FLAGS_NO_FRAG_NUMBER) frag_number = 0; } else { if (flags & REASSEMBLE_FLAGS_NO_FRAG_NUMBER) { fragment_data *fd; /* * If we weren't given an initial fragment number, * use the next expected fragment number as the fragment * number for this fragment. */ for (fd = fd_head; fd != NULL; fd = fd->next) { if (fd->next == NULL) frag_number = fd->offset + 1; } } } /* * XXX I've copied this over from the old separate * fragment_add_seq_check_work, but I'm not convinced it's doing the * right thing -- rav * * If we don't have all the data that is in this fragment, * then we can't, and don't, do reassembly on it. * * If it's the first frame, handle it as an unfragmented packet. * Otherwise, just handle it as a fragment. * * If "more_frags" isn't set, we get rid of the entry in the * hash table for this reassembly, as we don't need it any more. */ if ((flags & REASSEMBLE_FLAGS_CHECK_DATA_PRESENT) && !tvb_bytes_exist(tvb, offset, frag_data_len)) { if (!more_frags) { gpointer orig_key; /* * Remove this from the table of in-progress * reassemblies, and free up any memory used for * it in that table. */ if (g_hash_table_lookup_extended(fragment_table, key, &orig_key, NULL)) { fragment_unhash(fragment_table, (fragment_key *)orig_key); } } fd_head -> flags |= FD_DATA_NOT_PRESENT; return frag_number == 0 ? fd_head : NULL; } if (fragment_add_seq_work(fd_head, tvb, offset, pinfo, frag_number, frag_data_len, more_frags, flags)) { /* * Reassembly is complete. */ return fd_head; } else { /* * Reassembly isn't complete. */ return NULL; } } /* * This does the work for "fragment_add_seq_check()" and * "fragment_add_seq_next()". * * This function assumes frag_number being a block sequence number. * The bsn for the first block is 0. * * If "no_frag_number" is TRUE, it uses the next expected fragment number * as the fragment number if there is a reassembly in progress, otherwise * it uses 0. * * If "no_frag_number" is FALSE, it uses the "frag_number" argument as * the fragment number. * * If this is the first fragment seen for this datagram, a new * "fragment_data" structure is allocated to refer to the reassembled * packet. * * This fragment is added to the linked list of fragments for this packet. * * If "more_frags" is false and REASSEMBLE_FLAGS_802_11_HACK (as the name * implies, a special hack for 802.11) or REASSEMBLE_FLAGS_NO_FRAG_NUMBER * (implying messages must be in order since there's no sequence number) are * set in "flags", then this (one element) list is returned. * * If, after processing this fragment, we have all the fragments, * "fragment_add_seq_check_work()" removes that from the fragment hash * table if necessary and adds it to the table of reassembled fragments, * and returns a pointer to the head of the fragment list. * * Otherwise, it returns NULL. * * XXX - Should we simply return NULL for zero-length fragments? */ static fragment_data * fragment_add_seq_check_work(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, GHashTable *reassembled_table, const guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags, const guint32 flags) { reassembled_key reass_key; fragment_key key; fragment_data *fd_head; /* * Have we already seen this frame? * If so, look for it in the table of reassembled packets. */ if (pinfo->fd->flags.visited) { reass_key.frame = pinfo->fd->num; reass_key.id = id; return g_hash_table_lookup(reassembled_table, &reass_key); } /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = fragment_add_seq_key(tvb, offset, pinfo, &key, fragment_key_copy, fragment_table, frag_number, frag_data_len, more_frags, flags|REASSEMBLE_FLAGS_CHECK_DATA_PRESENT); if (fd_head) { gpointer orig_key; if(fd_head->flags & FD_DATA_NOT_PRESENT) { /* this is the first fragment of a datagram with * truncated fragments. Don't move it to the * reassembled table. */ return fd_head; } /* * Reassembly is complete. * Remove this from the table of in-progress * reassemblies, add it to the table of * reassembled packets, and return it. */ if (g_hash_table_lookup_extended(fragment_table, &key, &orig_key, NULL)) { /* * Remove this from the table of in-progress reassemblies, * and free up any memory used for it in that table. */ fragment_unhash(fragment_table, (fragment_key *)orig_key); } /* * Add this item to the table of reassembled packets. */ fragment_reassembled(fd_head, pinfo, reassembled_table, id); return fd_head; } else { /* * Reassembly isn't complete. */ return NULL; } } fragment_data * fragment_add_seq_check(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, GHashTable *reassembled_table, const guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags) { return fragment_add_seq_check_work(tvb, offset, pinfo, id, fragment_table, reassembled_table, frag_number, frag_data_len, more_frags, 0); } fragment_data * fragment_add_seq_802_11(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, GHashTable *reassembled_table, const guint32 frag_number, const guint32 frag_data_len, const gboolean more_frags) { return fragment_add_seq_check_work(tvb, offset, pinfo, id, fragment_table, reassembled_table, frag_number, frag_data_len, more_frags, REASSEMBLE_FLAGS_802_11_HACK); } fragment_data * fragment_add_seq_next(tvbuff_t *tvb, const int offset, const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, GHashTable *reassembled_table, const guint32 frag_data_len, const gboolean more_frags) { return fragment_add_seq_check_work(tvb, offset, pinfo, id, fragment_table, reassembled_table, 0, frag_data_len, more_frags, REASSEMBLE_FLAGS_NO_FRAG_NUMBER); } void fragment_start_seq_check(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, const guint32 tot_len) { fragment_key key, *new_key; fragment_data *fd_head; /* Have we already seen this frame ?*/ if (pinfo->fd->flags.visited) { return; } /* Create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; /* Check if fragment data exist for this key */ fd_head = g_hash_table_lookup(fragment_table, &key); if (fd_head == NULL) { /* Create list-head. */ #if GLIB_CHECK_VERSION(2,10,0) fd_head = g_slice_new(fragment_data); #else fd_head = g_mem_chunk_alloc(fragment_data_chunk); #endif fd_head->next = NULL; fd_head->datalen = tot_len; fd_head->offset = 0; fd_head->len = 0; fd_head->flags = FD_BLOCKSEQUENCE|FD_DATALEN_SET; fd_head->data = NULL; fd_head->reassembled_in = 0; /* * We're going to use the key to insert the fragment, * so copy it to a long-term store. */ new_key = fragment_key_copy(&key); g_hash_table_insert(fragment_table, new_key, fd_head); } } fragment_data * fragment_end_seq_next(const packet_info *pinfo, const guint32 id, GHashTable *fragment_table, GHashTable *reassembled_table) { reassembled_key reass_key; reassembled_key *new_key; fragment_key key; fragment_data *fd_head; /* * Have we already seen this frame? * If so, look for it in the table of reassembled packets. */ if (pinfo->fd->flags.visited) { reass_key.frame = pinfo->fd->num; reass_key.id = id; return g_hash_table_lookup(reassembled_table, &reass_key); } /* create key to search hash with */ key.src = pinfo->src; key.dst = pinfo->dst; key.id = id; fd_head = g_hash_table_lookup (fragment_table, &key); if (fd_head) { gpointer orig_key; if (fd_head->flags & FD_DATA_NOT_PRESENT) { /* No data added */ return NULL; } fd_head->datalen = fd_head->offset; fd_head->flags |= FD_DATALEN_SET; fragment_defragment_and_free (fd_head, pinfo); /* * Remove this from the table of in-progress * reassemblies, add it to the table of * reassembled packets, and return it. */ if (g_hash_table_lookup_extended(fragment_table, &key, &orig_key, NULL)) { /* * Remove this from the table of in-progress reassemblies, * and free up any memory used for it in that table. */ fragment_unhash(fragment_table, (fragment_key *)orig_key); } /* * Add this item to the table of reassembled packets. */ fragment_reassembled(fd_head, pinfo, reassembled_table, id); if (fd_head->next != NULL) { new_key = se_alloc(sizeof(reassembled_key)); new_key->frame = pinfo->fd->num; new_key->id = id; g_hash_table_insert(reassembled_table, new_key, fd_head); } return fd_head; } else { /* * Fragment data not found. */ return NULL; } } /* * Process reassembled data; if we're on the frame in which the data * was reassembled, put the fragment information into the protocol * tree, and construct a tvbuff with the reassembled data, otherwise * just put a "reassembled in" item into the protocol tree. */ tvbuff_t * process_reassembled_data(tvbuff_t *tvb, const int offset, packet_info *pinfo, const char *name, fragment_data *fd_head, const fragment_items *fit, gboolean *update_col_infop, proto_tree *tree) { tvbuff_t *next_tvb; gboolean update_col_info; proto_item *frag_tree_item; if (fd_head != NULL && pinfo->fd->num == fd_head->reassembled_in) { /* * OK, we've reassembled this. * Is this something that's been reassembled from more * than one fragment? */ if (fd_head->next != NULL) { /* * Yes. * Allocate a new tvbuff, referring to the * reassembled payload. */ if (fd_head->flags & FD_BLOCKSEQUENCE) { next_tvb = tvb_new_real_data(fd_head->data, fd_head->len, fd_head->len); } else { next_tvb = tvb_new_real_data(fd_head->data, fd_head->datalen, fd_head->datalen); } /* * Add the tvbuff to the list of tvbuffs to which * the tvbuff we were handed refers, so it'll get * cleaned up when that tvbuff is cleaned up. */ tvb_set_child_real_data_tvbuff(tvb, next_tvb); /* Add the defragmented data to the data source list. */ add_new_data_source(pinfo, next_tvb, name); /* show all fragments */ if (fd_head->flags & FD_BLOCKSEQUENCE) { update_col_info = !show_fragment_seq_tree( fd_head, fit, tree, pinfo, next_tvb, &frag_tree_item); } else { update_col_info = !show_fragment_tree(fd_head, fit, tree, pinfo, next_tvb, &frag_tree_item); } } else { /* * No. * Return a tvbuff with the payload. */ next_tvb = tvb_new_subset_remaining(tvb, offset); pinfo->fragmented = FALSE; /* one-fragment packet */ update_col_info = TRUE; } if (update_col_infop != NULL) *update_col_infop = update_col_info; } else { /* * We don't have the complete reassembled payload, or this * isn't the final frame of that payload. */ next_tvb = NULL; /* * If we know what frame this was reassembled in, * and if there's a field to use for the number of * the frame in which the packet was reassembled, * add it to the protocol tree. */ if (fd_head != NULL && fit->hf_reassembled_in != NULL) { proto_tree_add_uint(tree, *(fit->hf_reassembled_in), tvb, 0, 0, fd_head->reassembled_in); } } return next_tvb; } /* * Show a single fragment in a fragment subtree, and put information about * it in the top-level item for that subtree. */ static void show_fragment(fragment_data *fd, const int offset, const fragment_items *fit, proto_tree *ft, proto_item *fi, const gboolean first_frag, const guint32 count, tvbuff_t *tvb) { proto_item *fei=NULL; int hf; if (first_frag) { gchar *name; if (count == 1) { name = g_strdup(proto_registrar_get_name(*(fit->hf_fragment))); } else { name = g_strdup(proto_registrar_get_name(*(fit->hf_fragments))); } proto_item_set_text(fi, "%u %s (%u byte%s): ", count, name, tvb_length(tvb), plurality(tvb_length(tvb), "", "s")); g_free(name); } else { proto_item_append_text(fi, ", "); } proto_item_append_text(fi, "#%u(%u)", fd->frame, fd->len); if (fd->flags & (FD_OVERLAPCONFLICT |FD_MULTIPLETAILS|FD_TOOLONGFRAGMENT) ) { hf = *(fit->hf_fragment_error); } else { hf = *(fit->hf_fragment); } if (fd->len == 0) { fei = proto_tree_add_uint_format(ft, hf, tvb, offset, fd->len, fd->frame, "Frame: %u (no data)", fd->frame); } else { fei = proto_tree_add_uint_format(ft, hf, tvb, offset, fd->len, fd->frame, "Frame: %u, payload: %u-%u (%u byte%s)", fd->frame, offset, offset+fd->len-1, fd->len, plurality(fd->len, "", "s")); } PROTO_ITEM_SET_GENERATED(fei); if (fd->flags & (FD_OVERLAP|FD_OVERLAPCONFLICT |FD_MULTIPLETAILS|FD_TOOLONGFRAGMENT) ) { /* this fragment has some flags set, create a subtree * for it and display the flags. */ proto_tree *fet=NULL; fet = proto_item_add_subtree(fei, *(fit->ett_fragment)); if (fd->flags&FD_OVERLAP) { fei=proto_tree_add_boolean(fet, *(fit->hf_fragment_overlap), tvb, 0, 0, TRUE); PROTO_ITEM_SET_GENERATED(fei); } if (fd->flags&FD_OVERLAPCONFLICT) { fei=proto_tree_add_boolean(fet, *(fit->hf_fragment_overlap_conflict), tvb, 0, 0, TRUE); PROTO_ITEM_SET_GENERATED(fei); } if (fd->flags&FD_MULTIPLETAILS) { fei=proto_tree_add_boolean(fet, *(fit->hf_fragment_multiple_tails), tvb, 0, 0, TRUE); PROTO_ITEM_SET_GENERATED(fei); } if (fd->flags&FD_TOOLONGFRAGMENT) { fei=proto_tree_add_boolean(fet, *(fit->hf_fragment_too_long_fragment), tvb, 0, 0, TRUE); PROTO_ITEM_SET_GENERATED(fei); } } } static gboolean show_fragment_errs_in_col(fragment_data *fd_head, const fragment_items *fit, packet_info *pinfo) { if (fd_head->flags & (FD_OVERLAPCONFLICT |FD_MULTIPLETAILS|FD_TOOLONGFRAGMENT) ) { if (check_col(pinfo->cinfo, COL_INFO)) { col_add_fstr(pinfo->cinfo, COL_INFO, "[Illegal %s]", fit->tag); return TRUE; } } return FALSE; } /* This function will build the fragment subtree; it's for fragments reassembled with "fragment_add()". It will return TRUE if there were fragmentation errors or FALSE if fragmentation was ok. */ gboolean show_fragment_tree(fragment_data *fd_head, const fragment_items *fit, proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, proto_item **fi) { fragment_data *fd; proto_tree *ft; gboolean first_frag; guint32 count = 0; /* It's not fragmented. */ pinfo->fragmented = FALSE; *fi = proto_tree_add_item(tree, *(fit->hf_fragments), tvb, 0, -1, FALSE); PROTO_ITEM_SET_GENERATED(*fi); ft = proto_item_add_subtree(*fi, *(fit->ett_fragments)); first_frag = TRUE; for (fd = fd_head->next; fd != NULL; fd = fd->next) { count++; } for (fd = fd_head->next; fd != NULL; fd = fd->next) { show_fragment(fd, fd->offset, fit, ft, *fi, first_frag, count, tvb); first_frag = FALSE; } if (fit->hf_fragment_count) { proto_item *fli = proto_tree_add_uint(ft, *(fit->hf_fragment_count), tvb, 0, 0, count); PROTO_ITEM_SET_GENERATED(fli); } if (fit->hf_reassembled_length) { proto_item *fli = proto_tree_add_uint(ft, *(fit->hf_reassembled_length), tvb, 0, 0, tvb_length (tvb)); PROTO_ITEM_SET_GENERATED(fli); } return show_fragment_errs_in_col(fd_head, fit, pinfo); } /* This function will build the fragment subtree; it's for fragments reassembled with "fragment_add_seq()" or "fragment_add_seq_check()". It will return TRUE if there were fragmentation errors or FALSE if fragmentation was ok. */ gboolean show_fragment_seq_tree(fragment_data *fd_head, const fragment_items *fit, proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, proto_item **fi) { guint32 offset, next_offset, count = 0; fragment_data *fd, *last_fd; proto_tree *ft; gboolean first_frag; /* It's not fragmented. */ pinfo->fragmented = FALSE; *fi = proto_tree_add_item(tree, *(fit->hf_fragments), tvb, 0, -1, FALSE); PROTO_ITEM_SET_GENERATED(*fi); ft = proto_item_add_subtree(*fi, *(fit->ett_fragments)); offset = 0; next_offset = 0; last_fd = NULL; first_frag = TRUE; for (fd = fd_head->next; fd != NULL; fd = fd->next){ count++; } for (fd = fd_head->next; fd != NULL; fd = fd->next){ if (last_fd == NULL || last_fd->offset != fd->offset) { offset = next_offset; next_offset += fd->len; } last_fd = fd; show_fragment(fd, offset, fit, ft, *fi, first_frag, count, tvb); first_frag = FALSE; } if (fit->hf_fragment_count) { proto_item *fli = proto_tree_add_uint(ft, *(fit->hf_fragment_count), tvb, 0, 0, count); PROTO_ITEM_SET_GENERATED(fli); } if (fit->hf_reassembled_length) { proto_item *fli = proto_tree_add_uint(ft, *(fit->hf_reassembled_length), tvb, 0, 0, tvb_length (tvb)); PROTO_ITEM_SET_GENERATED(fli); } return show_fragment_errs_in_col(fd_head, fit, pinfo); } /* * Local Variables: * c-basic-offset: 8 * indent-tabs-mode: t * tab-width: 8 * End: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/wireshark_37122-37123.c
manybugs_data_62
/* +----------------------------------------------------------------------+ | phar php single-file executable PHP extension | +----------------------------------------------------------------------+ | Copyright (c) 2005-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Gregory Beaver <[email protected]> | | Marcus Boerger <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "phar_internal.h" #include "func_interceptors.h" static zend_class_entry *phar_ce_archive; static zend_class_entry *phar_ce_data; static zend_class_entry *phar_ce_PharException; #if HAVE_SPL static zend_class_entry *phar_ce_entry; #endif #if PHP_MAJOR_VERSION > 5 || ((PHP_MAJOR_VERSION == 5) && (PHP_MINOR_VERSION >= 3)) # define PHAR_ARG_INFO #else # define PHAR_ARG_INFO static #endif static int phar_file_type(HashTable *mimes, char *file, char **mime_type TSRMLS_DC) /* {{{ */ { char *ext; phar_mime_type *mime; ext = strrchr(file, '.'); if (!ext) { *mime_type = "text/plain"; /* no file extension = assume text/plain */ return PHAR_MIME_OTHER; } ++ext; if (SUCCESS != zend_hash_find(mimes, ext, strlen(ext), (void **) &mime)) { *mime_type = "application/octet-stream"; return PHAR_MIME_OTHER; } *mime_type = mime->mime; return mime->type; } /* }}} */ static void phar_mung_server_vars(char *fname, char *entry, int entry_len, char *basename, int request_uri_len TSRMLS_DC) /* {{{ */ { #if PHP_MAJOR_VERSION >= 6 int is_unicode = 0; #endif HashTable *_SERVER; zval **stuff; char *path_info; int basename_len = strlen(basename); int code; zval *temp; /* "tweak" $_SERVER variables requested in earlier call to Phar::mungServer() */ if (!PG(http_globals)[TRACK_VARS_SERVER]) { return; } _SERVER = Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]); /* PATH_INFO and PATH_TRANSLATED should always be munged */ #if PHP_MAJOR_VERSION >= 6 if (phar_find_key(_SERVER, "PATH_INFO", sizeof("PATH_INFO"), (void **) &stuff TSRMLS_CC)) { if (Z_TYPE_PP(stuff) == IS_UNICODE) { is_unicode = 1; zval_unicode_to_string(*stuff TSRMLS_CC); } else { is_unicode = 0; } #else if (SUCCESS == zend_hash_find(_SERVER, "PATH_INFO", sizeof("PATH_INFO"), (void **) &stuff)) { #endif path_info = Z_STRVAL_PP(stuff); code = Z_STRLEN_PP(stuff); if (Z_STRLEN_PP(stuff) > entry_len && !memcmp(Z_STRVAL_PP(stuff), entry, entry_len)) { ZVAL_STRINGL(*stuff, Z_STRVAL_PP(stuff) + entry_len, request_uri_len, 1); MAKE_STD_ZVAL(temp); ZVAL_STRINGL(temp, path_info, code, 0); #if PHP_MAJOR_VERSION >= 6 if (is_unicode) { zval_string_to_unicode(*stuff TSRMLS_CC); } #endif zend_hash_update(_SERVER, "PHAR_PATH_INFO", sizeof("PHAR_PATH_INFO"), &temp, sizeof(zval **), NULL); } } #if PHP_MAJOR_VERSION >= 6 if (phar_find_key(_SERVER, "PATH_TRANSLATED", sizeof("PATH_TRANSLATED"), (void **) &stuff TSRMLS_CC)) { if (Z_TYPE_PP(stuff) == IS_UNICODE) { is_unicode = 1; zval_unicode_to_string(*stuff TSRMLS_CC); } else { is_unicode = 0; } #else if (SUCCESS == zend_hash_find(_SERVER, "PATH_TRANSLATED", sizeof("PATH_TRANSLATED"), (void **) &stuff)) { #endif path_info = Z_STRVAL_PP(stuff); code = Z_STRLEN_PP(stuff); Z_STRLEN_PP(stuff) = spprintf(&(Z_STRVAL_PP(stuff)), 4096, "phar://%s%s", fname, entry); MAKE_STD_ZVAL(temp); ZVAL_STRINGL(temp, path_info, code, 0); #if PHP_MAJOR_VERSION >= 6 if (is_unicode) { zval_string_to_unicode(*stuff TSRMLS_CC); } #endif zend_hash_update(_SERVER, "PHAR_PATH_TRANSLATED", sizeof("PHAR_PATH_TRANSLATED"), (void *) &temp, sizeof(zval **), NULL); } if (!PHAR_GLOBALS->phar_SERVER_mung_list) { return; } if (PHAR_GLOBALS->phar_SERVER_mung_list & PHAR_MUNG_REQUEST_URI) { #if PHP_MAJOR_VERSION >= 6 if (phar_find_key(_SERVER, "REQUEST_URI", sizeof("REQUEST_URI"), (void **) &stuff TSRMLS_CC)) { if (Z_TYPE_PP(stuff) == IS_UNICODE) { is_unicode = 1; zval_unicode_to_string(*stuff TSRMLS_CC); } else { is_unicode = 0; } #else if (SUCCESS == zend_hash_find(_SERVER, "REQUEST_URI", sizeof("REQUEST_URI"), (void **) &stuff)) { #endif path_info = Z_STRVAL_PP(stuff); code = Z_STRLEN_PP(stuff); if (Z_STRLEN_PP(stuff) > basename_len && !memcmp(Z_STRVAL_PP(stuff), basename, basename_len)) { ZVAL_STRINGL(*stuff, Z_STRVAL_PP(stuff) + basename_len, Z_STRLEN_PP(stuff) - basename_len, 1); MAKE_STD_ZVAL(temp); ZVAL_STRINGL(temp, path_info, code, 0); #if PHP_MAJOR_VERSION >= 6 if (is_unicode) { zval_string_to_unicode(*stuff TSRMLS_CC); } #endif zend_hash_update(_SERVER, "PHAR_REQUEST_URI", sizeof("PHAR_REQUEST_URI"), (void *) &temp, sizeof(zval **), NULL); } } } if (PHAR_GLOBALS->phar_SERVER_mung_list & PHAR_MUNG_PHP_SELF) { #if PHP_MAJOR_VERSION >= 6 if (phar_find_key(_SERVER, "PHP_SELF", sizeof("PHP_SELF"), (void **) &stuff TSRMLS_CC)) { if (Z_TYPE_PP(stuff) == IS_UNICODE) { is_unicode = 1; zval_unicode_to_string(*stuff TSRMLS_CC); } else { is_unicode = 0; } #else if (SUCCESS == zend_hash_find(_SERVER, "PHP_SELF", sizeof("PHP_SELF"), (void **) &stuff)) { #endif path_info = Z_STRVAL_PP(stuff); code = Z_STRLEN_PP(stuff); if (Z_STRLEN_PP(stuff) > basename_len && !memcmp(Z_STRVAL_PP(stuff), basename, basename_len)) { ZVAL_STRINGL(*stuff, Z_STRVAL_PP(stuff) + basename_len, Z_STRLEN_PP(stuff) - basename_len, 1); MAKE_STD_ZVAL(temp); ZVAL_STRINGL(temp, path_info, code, 0); #if PHP_MAJOR_VERSION >= 6 if (is_unicode) { zval_string_to_unicode(*stuff TSRMLS_CC); } #endif zend_hash_update(_SERVER, "PHAR_PHP_SELF", sizeof("PHAR_PHP_SELF"), (void *) &temp, sizeof(zval **), NULL); } } } if (PHAR_GLOBALS->phar_SERVER_mung_list & PHAR_MUNG_SCRIPT_NAME) { #if PHP_MAJOR_VERSION >= 6 if (phar_find_key(_SERVER, "SCRIPT_NAME", sizeof("SCRIPT_NAME"), (void **) &stuff TSRMLS_CC)) { if (Z_TYPE_PP(stuff) == IS_UNICODE) { is_unicode = 1; zval_unicode_to_string(*stuff TSRMLS_CC); } else { is_unicode = 0; } #else if (SUCCESS == zend_hash_find(_SERVER, "SCRIPT_NAME", sizeof("SCRIPT_NAME"), (void **) &stuff)) { #endif path_info = Z_STRVAL_PP(stuff); code = Z_STRLEN_PP(stuff); ZVAL_STRINGL(*stuff, entry, entry_len, 1); MAKE_STD_ZVAL(temp); ZVAL_STRINGL(temp, path_info, code, 0); #if PHP_MAJOR_VERSION >= 6 if (is_unicode) { zval_string_to_unicode(*stuff TSRMLS_CC); } #endif zend_hash_update(_SERVER, "PHAR_SCRIPT_NAME", sizeof("PHAR_SCRIPT_NAME"), (void *) &temp, sizeof(zval **), NULL); } } if (PHAR_GLOBALS->phar_SERVER_mung_list & PHAR_MUNG_SCRIPT_FILENAME) { #if PHP_MAJOR_VERSION >= 6 if (phar_find_key(_SERVER, "SCRIPT_FILENAME", sizeof("SCRIPT_FILENAME"), (void **) &stuff TSRMLS_CC)) { if (Z_TYPE_PP(stuff) == IS_UNICODE) { is_unicode = 1; zval_unicode_to_string(*stuff TSRMLS_CC); } else { is_unicode = 0; } #else if (SUCCESS == zend_hash_find(_SERVER, "SCRIPT_FILENAME", sizeof("SCRIPT_FILENAME"), (void **) &stuff)) { #endif path_info = Z_STRVAL_PP(stuff); code = Z_STRLEN_PP(stuff); Z_STRLEN_PP(stuff) = spprintf(&(Z_STRVAL_PP(stuff)), 4096, "phar://%s%s", fname, entry); MAKE_STD_ZVAL(temp); ZVAL_STRINGL(temp, path_info, code, 0); #if PHP_MAJOR_VERSION >= 6 if (is_unicode) { zval_string_to_unicode(*stuff TSRMLS_CC); } #endif zend_hash_update(_SERVER, "PHAR_SCRIPT_FILENAME", sizeof("PHAR_SCRIPT_FILENAME"), (void *) &temp, sizeof(zval **), NULL); } } } /* }}} */ static int phar_file_action(phar_archive_data *phar, phar_entry_info *info, char *mime_type, int code, char *entry, int entry_len, char *arch, char *basename, char *ru, int ru_len TSRMLS_DC) /* {{{ */ { char *name = NULL, buf[8192]; const char *cwd; zend_syntax_highlighter_ini syntax_highlighter_ini; sapi_header_line ctr = {0}; size_t got; int dummy = 1, name_len; zend_file_handle file_handle; zend_op_array *new_op_array; zval *result = NULL; php_stream *fp; off_t position; switch (code) { case PHAR_MIME_PHPS: efree(basename); /* highlight source */ if (entry[0] == '/') { name_len = spprintf(&name, 4096, "phar://%s%s", arch, entry); } else { name_len = spprintf(&name, 4096, "phar://%s/%s", arch, entry); } php_get_highlight_struct(&syntax_highlighter_ini); highlight_file(name, &syntax_highlighter_ini TSRMLS_CC); efree(name); #ifdef PHP_WIN32 efree(arch); #endif zend_bailout(); case PHAR_MIME_OTHER: /* send headers, output file contents */ efree(basename); ctr.line_len = spprintf(&(ctr.line), 0, "Content-type: %s", mime_type); sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC); efree(ctr.line); ctr.line_len = spprintf(&(ctr.line), 0, "Content-length: %u", info->uncompressed_filesize); sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC); efree(ctr.line); if (FAILURE == sapi_send_headers(TSRMLS_C)) { zend_bailout(); } /* prepare to output */ fp = phar_get_efp(info, 1 TSRMLS_CC); if (!fp) { char *error; if (!phar_open_jit(phar, info, &error TSRMLS_CC)) { if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } return -1; } fp = phar_get_efp(info, 1 TSRMLS_CC); } position = 0; phar_seek_efp(info, 0, SEEK_SET, 0, 1 TSRMLS_CC); do { got = php_stream_read(fp, buf, MIN(8192, info->uncompressed_filesize - position)); if (got > 0) { PHPWRITE(buf, got); position += got; if (position == (off_t) info->uncompressed_filesize) { break; } } } while (1); zend_bailout(); case PHAR_MIME_PHP: if (basename) { phar_mung_server_vars(arch, entry, entry_len, basename, ru_len TSRMLS_CC); efree(basename); } if (entry[0] == '/') { name_len = spprintf(&name, 4096, "phar://%s%s", arch, entry); } else { name_len = spprintf(&name, 4096, "phar://%s/%s", arch, entry); } file_handle.type = ZEND_HANDLE_FILENAME; file_handle.handle.fd = 0; file_handle.filename = name; file_handle.opened_path = NULL; file_handle.free_filename = 0; PHAR_G(cwd) = NULL; PHAR_G(cwd_len) = 0; if (zend_hash_add(&EG(included_files), name, name_len+1, (void *)&dummy, sizeof(int), NULL) == SUCCESS) { if ((cwd = zend_memrchr(entry, '/', entry_len))) { PHAR_G(cwd_init) = 1; if (entry == cwd) { /* root directory */ PHAR_G(cwd_len) = 0; PHAR_G(cwd) = NULL; } else if (entry[0] == '/') { PHAR_G(cwd_len) = cwd - (entry + 1); PHAR_G(cwd) = estrndup(entry + 1, PHAR_G(cwd_len)); } else { PHAR_G(cwd_len) = cwd - entry; PHAR_G(cwd) = estrndup(entry, PHAR_G(cwd_len)); } } new_op_array = zend_compile_file(&file_handle, ZEND_REQUIRE TSRMLS_CC); if (!new_op_array) { zend_hash_del(&EG(included_files), name, name_len+1); } zend_destroy_file_handle(&file_handle TSRMLS_CC); } else { efree(name); new_op_array = NULL; } #ifdef PHP_WIN32 efree(arch); #endif if (new_op_array) { EG(return_value_ptr_ptr) = &result; EG(active_op_array) = new_op_array; zend_try { zend_execute(new_op_array TSRMLS_CC); if (PHAR_G(cwd)) { efree(PHAR_G(cwd)); PHAR_G(cwd) = NULL; PHAR_G(cwd_len) = 0; } PHAR_G(cwd_init) = 0; efree(name); destroy_op_array(new_op_array TSRMLS_CC); efree(new_op_array); if (EG(return_value_ptr_ptr) && *EG(return_value_ptr_ptr)) { zval_ptr_dtor(EG(return_value_ptr_ptr)); } } zend_catch { if (PHAR_G(cwd)) { efree(PHAR_G(cwd)); PHAR_G(cwd) = NULL; PHAR_G(cwd_len) = 0; } PHAR_G(cwd_init) = 0; efree(name); } zend_end_try(); zend_bailout(); } return PHAR_MIME_PHP; } return -1; } /* }}} */ static void phar_do_403(char *entry, int entry_len TSRMLS_DC) /* {{{ */ { sapi_header_line ctr = {0}; ctr.response_code = 403; ctr.line_len = sizeof("HTTP/1.0 403 Access Denied"); ctr.line = "HTTP/1.0 403 Access Denied"; sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC); sapi_send_headers(TSRMLS_C); PHPWRITE("<html>\n <head>\n <title>Access Denied</title>\n </head>\n <body>\n <h1>403 - File ", sizeof("<html>\n <head>\n <title>Access Denied</title>\n </head>\n <body>\n <h1>403 - File ") - 1); PHPWRITE(entry, entry_len); PHPWRITE(" Access Denied</h1>\n </body>\n</html>", sizeof(" Access Denied</h1>\n </body>\n</html>") - 1); } /* }}} */ static void phar_do_404(phar_archive_data *phar, char *fname, int fname_len, char *f404, int f404_len, char *entry, int entry_len TSRMLS_DC) /* {{{ */ { sapi_header_line ctr = {0}; phar_entry_info *info; if (phar && f404_len) { info = phar_get_entry_info(phar, f404, f404_len, NULL, 1 TSRMLS_CC); if (info) { phar_file_action(phar, info, "text/html", PHAR_MIME_PHP, f404, f404_len, fname, NULL, NULL, 0 TSRMLS_CC); return; } } ctr.response_code = 404; ctr.line_len = sizeof("HTTP/1.0 404 Not Found")+1; ctr.line = "HTTP/1.0 404 Not Found"; sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC); sapi_send_headers(TSRMLS_C); PHPWRITE("<html>\n <head>\n <title>File Not Found</title>\n </head>\n <body>\n <h1>404 - File ", sizeof("<html>\n <head>\n <title>File Not Found</title>\n </head>\n <body>\n <h1>404 - File ") - 1); PHPWRITE(entry, entry_len); PHPWRITE(" Not Found</h1>\n </body>\n</html>", sizeof(" Not Found</h1>\n </body>\n</html>") - 1); } /* }}} */ /* post-process REQUEST_URI and retrieve the actual request URI. This is for cases like http://localhost/blah.phar/path/to/file.php/extra/stuff which calls "blah.phar" file "path/to/file.php" with PATH_INFO "/extra/stuff" */ static void phar_postprocess_ru_web(char *fname, int fname_len, char **entry, int *entry_len, char **ru, int *ru_len TSRMLS_DC) /* {{{ */ { char *e = *entry + 1, *u = NULL, *u1 = NULL, *saveu = NULL; int e_len = *entry_len - 1, u_len = 0; phar_archive_data **pphar = NULL; /* we already know we can retrieve the phar if we reach here */ zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), fname, fname_len, (void **) &pphar); if (!pphar && PHAR_G(manifest_cached)) { zend_hash_find(&cached_phars, fname, fname_len, (void **) &pphar); } do { if (zend_hash_exists(&((*pphar)->manifest), e, e_len)) { if (u) { u[0] = '/'; *ru = estrndup(u, u_len+1); ++u_len; u[0] = '\0'; } else { *ru = NULL; } *ru_len = u_len; *entry_len = e_len + 1; return; } if (u) { u1 = strrchr(e, '/'); u[0] = '/'; saveu = u; e_len += u_len + 1; u = u1; if (!u) { return; } } else { u = strrchr(e, '/'); if (!u) { if (saveu) { saveu[0] = '/'; } return; } } u[0] = '\0'; u_len = strlen(u + 1); e_len -= u_len + 1; if (e_len < 0) { if (saveu) { saveu[0] = '/'; } return; } } while (1); } /* }}} */ /* {{{ proto void Phar::running([bool retphar = true]) * return the name of the currently running phar archive. If the optional parameter * is set to true, return the phar:// URL to the currently running phar */ PHP_METHOD(Phar, running) { char *fname, *arch, *entry; int fname_len, arch_len, entry_len; zend_bool retphar = 1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &retphar) == FAILURE) { return; } fname = zend_get_executed_filename(TSRMLS_C); fname_len = strlen(fname); if (fname_len > 7 && !memcmp(fname, "phar://", 7) && SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0 TSRMLS_CC)) { efree(entry); if (retphar) { RETVAL_STRINGL(fname, arch_len + 7, 1); efree(arch); return; } else { RETURN_STRINGL(arch, arch_len, 0); } } RETURN_STRINGL("", 0, 1); } /* }}} */ /* {{{ proto void Phar::mount(string pharpath, string externalfile) * mount an external file or path to a location within the phar. This maps * an external file or directory to a location within the phar archive, allowing * reference to an external location as if it were within the phar archive. This * is useful for writable temp files like databases */ PHP_METHOD(Phar, mount) { char *fname, *arch = NULL, *entry = NULL, *path, *actual; int fname_len, arch_len, entry_len, path_len, actual_len; phar_archive_data **pphar; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &path, &path_len, &actual, &actual_len) == FAILURE) { return; } fname = zend_get_executed_filename(TSRMLS_C); fname_len = strlen(fname); #ifdef PHP_WIN32 phar_unixify_path_separators(fname, fname_len); #endif if (fname_len > 7 && !memcmp(fname, "phar://", 7) && SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0 TSRMLS_CC)) { efree(entry); entry = NULL; if (path_len > 7 && !memcmp(path, "phar://", 7)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Can only mount internal paths within a phar archive, use a relative path instead of \"%s\"", path); efree(arch); return; } carry_on2: if (SUCCESS != zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), arch, arch_len, (void **)&pphar)) { if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, arch, arch_len, (void **)&pphar)) { if (SUCCESS == phar_copy_on_write(pphar TSRMLS_CC)) { goto carry_on; } } zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s is not a phar archive, cannot mount", arch); if (arch) { efree(arch); } return; } carry_on: if (SUCCESS != phar_mount_entry(*pphar, actual, actual_len, path, path_len TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Mounting of %s to %s within phar %s failed", path, actual, arch); if (path && path == entry) { efree(entry); } if (arch) { efree(arch); } return; } if (entry && path && path == entry) { efree(entry); } if (arch) { efree(arch); } return; } else if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), fname, fname_len, (void **)&pphar)) { goto carry_on; } else if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, fname, fname_len, (void **)&pphar)) { if (SUCCESS == phar_copy_on_write(pphar TSRMLS_CC)) { goto carry_on; } goto carry_on; } else if (SUCCESS == phar_split_fname(path, path_len, &arch, &arch_len, &entry, &entry_len, 2, 0 TSRMLS_CC)) { path = entry; path_len = entry_len; goto carry_on2; } zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Mounting of %s to %s failed", path, actual); } /* }}} */ /* {{{ proto void Phar::webPhar([string alias, [string index, [string f404, [array mimetypes, [callback rewrites]]]]]) * mapPhar for web-based phars. Reads the currently executed file (a phar) * and registers its manifest. When executed in the CLI or CGI command-line sapi, * this works exactly like mapPhar(). When executed by a web-based sapi, this * reads $_SERVER['REQUEST_URI'] (the actual original value) and parses out the * intended internal file. */ PHP_METHOD(Phar, webPhar) { zval *mimeoverride = NULL, *rewrite = NULL; char *alias = NULL, *error, *index_php = NULL, *f404 = NULL, *ru = NULL; int alias_len = 0, ret, f404_len = 0, free_pathinfo = 0, ru_len = 0; char *fname, *path_info, *mime_type = NULL, *entry, *pt; const char *basename; int fname_len, entry_len, code, index_php_len = 0, not_cgi; phar_archive_data *phar = NULL; phar_entry_info *info; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!s!saz", &alias, &alias_len, &index_php, &index_php_len, &f404, &f404_len, &mimeoverride, &rewrite) == FAILURE) { return; } phar_request_initialize(TSRMLS_C); fname = zend_get_executed_filename(TSRMLS_C); fname_len = strlen(fname); if (phar_open_executed_filename(alias, alias_len, &error TSRMLS_CC) != SUCCESS) { if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } return; } /* retrieve requested file within phar */ if (!(SG(request_info).request_method && SG(request_info).request_uri && (!strcmp(SG(request_info).request_method, "GET") || !strcmp(SG(request_info).request_method, "POST")))) { return; } #ifdef PHP_WIN32 fname = estrndup(fname, fname_len); phar_unixify_path_separators(fname, fname_len); #endif basename = zend_memrchr(fname, '/', fname_len); if (!basename) { basename = fname; } else { ++basename; } if ((strlen(sapi_module.name) == sizeof("cgi-fcgi")-1 && !strncmp(sapi_module.name, "cgi-fcgi", sizeof("cgi-fcgi")-1)) || (strlen(sapi_module.name) == sizeof("cgi")-1 && !strncmp(sapi_module.name, "cgi", sizeof("cgi")-1))) { if (PG(http_globals)[TRACK_VARS_SERVER]) { HashTable *_server = Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]); zval **z_script_name, **z_path_info; if (SUCCESS != zend_hash_find(_server, "SCRIPT_NAME", sizeof("SCRIPT_NAME"), (void**)&z_script_name) || IS_STRING != Z_TYPE_PP(z_script_name) || !strstr(Z_STRVAL_PP(z_script_name), basename)) { return; } if (SUCCESS == zend_hash_find(_server, "PATH_INFO", sizeof("PATH_INFO"), (void**)&z_path_info) && IS_STRING == Z_TYPE_PP(z_path_info)) { entry_len = Z_STRLEN_PP(z_path_info); entry = estrndup(Z_STRVAL_PP(z_path_info), entry_len); path_info = emalloc(Z_STRLEN_PP(z_script_name) + entry_len + 1); memcpy(path_info, Z_STRVAL_PP(z_script_name), Z_STRLEN_PP(z_script_name)); memcpy(path_info + Z_STRLEN_PP(z_script_name), entry, entry_len + 1); free_pathinfo = 1; } else { entry_len = 0; entry = estrndup("", 0); path_info = Z_STRVAL_PP(z_script_name); } pt = estrndup(Z_STRVAL_PP(z_script_name), Z_STRLEN_PP(z_script_name)); } else { char *testit; testit = sapi_getenv("SCRIPT_NAME", sizeof("SCRIPT_NAME")-1 TSRMLS_CC); if (!(pt = strstr(testit, basename))) { efree(testit); return; } path_info = sapi_getenv("PATH_INFO", sizeof("PATH_INFO")-1 TSRMLS_CC); if (path_info) { entry = path_info; entry_len = strlen(entry); spprintf(&path_info, 0, "%s%s", testit, path_info); free_pathinfo = 1; } else { path_info = testit; free_pathinfo = 1; entry = estrndup("", 0); entry_len = 0; } pt = estrndup(testit, (pt - testit) + (fname_len - (basename - fname))); } not_cgi = 0; } else { path_info = SG(request_info).request_uri; if (!(pt = strstr(path_info, basename))) { /* this can happen with rewrite rules - and we have no idea what to do then, so return */ return; } entry_len = strlen(path_info); entry_len -= (pt - path_info) + (fname_len - (basename - fname)); entry = estrndup(pt + (fname_len - (basename - fname)), entry_len); pt = estrndup(path_info, (pt - path_info) + (fname_len - (basename - fname))); not_cgi = 1; } if (rewrite) { zend_fcall_info fci; zend_fcall_info_cache fcc; zval *params, *retval_ptr, **zp[1]; MAKE_STD_ZVAL(params); ZVAL_STRINGL(params, entry, entry_len, 1); zp[0] = &params; #if PHP_VERSION_ID < 50300 if (FAILURE == zend_fcall_info_init(rewrite, &fci, &fcc TSRMLS_CC)) { #else if (FAILURE == zend_fcall_info_init(rewrite, 0, &fci, &fcc, NULL, NULL TSRMLS_CC)) { #endif zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: invalid rewrite callback"); if (free_pathinfo) { efree(path_info); } return; } fci.param_count = 1; fci.params = zp; #if PHP_VERSION_ID < 50300 ++(params->refcount); #else Z_ADDREF_P(params); #endif fci.retval_ptr_ptr = &retval_ptr; if (FAILURE == zend_call_function(&fci, &fcc TSRMLS_CC)) { if (!EG(exception)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: failed to call rewrite callback"); } if (free_pathinfo) { efree(path_info); } return; } if (!fci.retval_ptr_ptr || !retval_ptr) { if (free_pathinfo) { efree(path_info); } zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: rewrite callback must return a string or false"); return; } switch (Z_TYPE_P(retval_ptr)) { #if PHP_VERSION_ID >= 60000 case IS_UNICODE: zval_unicode_to_string(retval_ptr TSRMLS_CC); /* break intentionally omitted */ #endif case IS_STRING: efree(entry); if (fci.retval_ptr_ptr != &retval_ptr) { entry = estrndup(Z_STRVAL_PP(fci.retval_ptr_ptr), Z_STRLEN_PP(fci.retval_ptr_ptr)); entry_len = Z_STRLEN_PP(fci.retval_ptr_ptr); } else { entry = Z_STRVAL_P(retval_ptr); entry_len = Z_STRLEN_P(retval_ptr); } break; case IS_BOOL: phar_do_403(entry, entry_len TSRMLS_CC); if (free_pathinfo) { efree(path_info); } zend_bailout(); return; default: efree(retval_ptr); if (free_pathinfo) { efree(path_info); } zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: rewrite callback must return a string or false"); return; } } if (entry_len) { phar_postprocess_ru_web(fname, fname_len, &entry, &entry_len, &ru, &ru_len TSRMLS_CC); } if (!entry_len || (entry_len == 1 && entry[0] == '/')) { efree(entry); /* direct request */ if (index_php_len) { entry = index_php; entry_len = index_php_len; if (entry[0] != '/') { spprintf(&entry, 0, "/%s", index_php); ++entry_len; } } else { /* assume "index.php" is starting point */ entry = estrndup("/index.php", sizeof("/index.php")); entry_len = sizeof("/index.php")-1; } if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL TSRMLS_CC) || (info = phar_get_entry_info(phar, entry, entry_len, NULL, 0 TSRMLS_CC)) == NULL) { phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len TSRMLS_CC); if (free_pathinfo) { efree(path_info); } zend_bailout(); } else { char *tmp, sa; sapi_header_line ctr = {0}; ctr.response_code = 301; ctr.line_len = sizeof("HTTP/1.1 301 Moved Permanently")+1; ctr.line = "HTTP/1.1 301 Moved Permanently"; sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC); if (not_cgi) { tmp = strstr(path_info, basename) + fname_len; sa = *tmp; *tmp = '\0'; } ctr.response_code = 0; if (path_info[strlen(path_info)-1] == '/') { ctr.line_len = spprintf(&(ctr.line), 4096, "Location: %s%s", path_info, entry + 1); } else { ctr.line_len = spprintf(&(ctr.line), 4096, "Location: %s%s", path_info, entry); } if (not_cgi) { *tmp = sa; } if (free_pathinfo) { efree(path_info); } sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC); sapi_send_headers(TSRMLS_C); efree(ctr.line); zend_bailout(); } } if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL TSRMLS_CC) || (info = phar_get_entry_info(phar, entry, entry_len, NULL, 0 TSRMLS_CC)) == NULL) { phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len TSRMLS_CC); #ifdef PHP_WIN32 efree(fname); #endif zend_bailout(); } if (mimeoverride && zend_hash_num_elements(Z_ARRVAL_P(mimeoverride))) { const char *ext = zend_memrchr(entry, '.', entry_len); zval **val; if (ext) { ++ext; #if PHP_MAJOR_VERSION >= 6 if (phar_find_key(Z_ARRVAL_P(mimeoverride), ext, strlen(ext)+1, (void **) &val TSRMLS_CC)) { #else if (SUCCESS == zend_hash_find(Z_ARRVAL_P(mimeoverride), ext, strlen(ext)+1, (void **) &val)) { #endif switch (Z_TYPE_PP(val)) { case IS_LONG: if (Z_LVAL_PP(val) == PHAR_MIME_PHP || Z_LVAL_PP(val) == PHAR_MIME_PHPS) { mime_type = ""; code = Z_LVAL_PP(val); } else { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown mime type specifier used, only Phar::PHP, Phar::PHPS and a mime type string are allowed"); #ifdef PHP_WIN32 efree(fname); #endif RETURN_FALSE; } break; #if PHP_MAJOR_VERSION >= 6 case IS_UNICODE: zval_unicode_to_string(*(val) TSRMLS_CC); /* break intentionally omitted */ #endif case IS_STRING: mime_type = Z_STRVAL_PP(val); code = PHAR_MIME_OTHER; break; default: zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown mime type specifier used (not a string or int), only Phar::PHP, Phar::PHPS and a mime type string are allowed"); #ifdef PHP_WIN32 efree(fname); #endif RETURN_FALSE; } } } } if (!mime_type) { code = phar_file_type(&PHAR_G(mime_types), entry, &mime_type TSRMLS_CC); } ret = phar_file_action(phar, info, mime_type, code, entry, entry_len, fname, pt, ru, ru_len TSRMLS_CC); } /* }}} */ /* {{{ proto void Phar::mungServer(array munglist) * Defines a list of up to 4 $_SERVER variables that should be modified for execution * to mask the presence of the phar archive. This should be used in conjunction with * Phar::webPhar(), and has no effect otherwise * SCRIPT_NAME, PHP_SELF, REQUEST_URI and SCRIPT_FILENAME */ PHP_METHOD(Phar, mungServer) { zval *mungvalues; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &mungvalues) == FAILURE) { return; } if (!zend_hash_num_elements(Z_ARRVAL_P(mungvalues))) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "No values passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME"); return; } if (zend_hash_num_elements(Z_ARRVAL_P(mungvalues)) > 4) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Too many values passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME"); return; } phar_request_initialize(TSRMLS_C); for (zend_hash_internal_pointer_reset(Z_ARRVAL_P(mungvalues)); SUCCESS == zend_hash_has_more_elements(Z_ARRVAL_P(mungvalues)); zend_hash_move_forward(Z_ARRVAL_P(mungvalues))) { zval **data = NULL; #if PHP_MAJOR_VERSION >= 6 zval *unicopy = NULL; #endif if (SUCCESS != zend_hash_get_current_data(Z_ARRVAL_P(mungvalues), (void **) &data)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "unable to retrieve array value in Phar::mungServer()"); return; } #if PHP_MAJOR_VERSION >= 6 if (Z_TYPE_PP(data) == IS_UNICODE) { MAKE_STD_ZVAL(unicopy); *unicopy = **data; zval_copy_ctor(unicopy); INIT_PZVAL(unicopy); zval_unicode_to_string(unicopy TSRMLS_CC); data = &unicopy; } #endif if (Z_TYPE_PP(data) != IS_STRING) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Non-string value passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME"); return; } if (Z_STRLEN_PP(data) == sizeof("PHP_SELF")-1 && !strncmp(Z_STRVAL_PP(data), "PHP_SELF", sizeof("PHP_SELF")-1)) { PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_PHP_SELF; } if (Z_STRLEN_PP(data) == sizeof("REQUEST_URI")-1) { if (!strncmp(Z_STRVAL_PP(data), "REQUEST_URI", sizeof("REQUEST_URI")-1)) { PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_REQUEST_URI; } if (!strncmp(Z_STRVAL_PP(data), "SCRIPT_NAME", sizeof("SCRIPT_NAME")-1)) { PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_SCRIPT_NAME; } } if (Z_STRLEN_PP(data) == sizeof("SCRIPT_FILENAME")-1 && !strncmp(Z_STRVAL_PP(data), "SCRIPT_FILENAME", sizeof("SCRIPT_FILENAME")-1)) { PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_SCRIPT_FILENAME; } #if PHP_MAJOR_VERSION >= 6 if (unicopy) { zval_ptr_dtor(&unicopy); } #endif } } /* }}} */ /* {{{ proto void Phar::interceptFileFuncs() * instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions * and return stat on files within the phar for relative paths * * Once called, this cannot be reversed, and continue until the end of the request. * * This allows legacy scripts to be pharred unmodified */ PHP_METHOD(Phar, interceptFileFuncs) { phar_intercept_functions(TSRMLS_C); } /* }}} */ /* {{{ proto array Phar::createDefaultStub([string indexfile[, string webindexfile]]) * Return a stub that can be used to run a phar-based archive without the phar extension * indexfile is the CLI startup filename, which defaults to "index.php", webindexfile * is the web startup filename, and also defaults to "index.php" */ PHP_METHOD(Phar, createDefaultStub) { char *index = NULL, *webindex = NULL, *stub, *error; int index_len = 0, webindex_len = 0; size_t stub_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|ss", &index, &index_len, &webindex, &webindex_len) == FAILURE) { return; } stub = phar_create_default_stub(index, webindex, &stub_len, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); return; } RETURN_STRINGL(stub, stub_len, 0); } /* }}} */ /* {{{ proto mixed Phar::mapPhar([string alias, [int dataoffset]]) * Reads the currently executed file (a phar) and registers its manifest */ PHP_METHOD(Phar, mapPhar) { char *alias = NULL, *error; int alias_len = 0; long dataoffset = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!l", &alias, &alias_len, &dataoffset) == FAILURE) { return; } phar_request_initialize(TSRMLS_C); RETVAL_BOOL(phar_open_executed_filename(alias, alias_len, &error TSRMLS_CC) == SUCCESS); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } } /* }}} */ /* {{{ proto mixed Phar::loadPhar(string filename [, string alias]) * Loads any phar archive with an alias */ PHP_METHOD(Phar, loadPhar) { char *fname, *alias = NULL, *error; int fname_len, alias_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s!", &fname, &fname_len, &alias, &alias_len) == FAILURE) { return; } phar_request_initialize(TSRMLS_C); RETVAL_BOOL(phar_open_from_filename(fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, &error TSRMLS_CC) == SUCCESS); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } } /* }}} */ /* {{{ proto string Phar::apiVersion() * Returns the api version */ PHP_METHOD(Phar, apiVersion) { RETURN_STRINGL(PHP_PHAR_API_VERSION, sizeof(PHP_PHAR_API_VERSION)-1, 1); } /* }}}*/ /* {{{ proto bool Phar::canCompress([int method]) * Returns whether phar extension supports compression using zlib/bzip2 */ PHP_METHOD(Phar, canCompress) { long method = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &method) == FAILURE) { return; } phar_request_initialize(TSRMLS_C); switch (method) { case PHAR_ENT_COMPRESSED_GZ: if (PHAR_G(has_zlib)) { RETURN_TRUE; } else { RETURN_FALSE; } case PHAR_ENT_COMPRESSED_BZ2: if (PHAR_G(has_bz2)) { RETURN_TRUE; } else { RETURN_FALSE; } default: if (PHAR_G(has_zlib) || PHAR_G(has_bz2)) { RETURN_TRUE; } else { RETURN_FALSE; } } } /* }}} */ /* {{{ proto bool Phar::canWrite() * Returns whether phar extension supports writing and creating phars */ PHP_METHOD(Phar, canWrite) { RETURN_BOOL(!PHAR_G(readonly)); } /* }}} */ /* {{{ proto bool Phar::isValidPharFilename(string filename[, bool executable = true]) * Returns whether the given filename is a valid phar filename */ PHP_METHOD(Phar, isValidPharFilename) { char *fname; const char *ext_str; int fname_len, ext_len, is_executable; zend_bool executable = 1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|b", &fname, &fname_len, &executable) == FAILURE) { return; } is_executable = executable; RETVAL_BOOL(phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, is_executable, 2, 1 TSRMLS_CC) == SUCCESS); } /* }}} */ #if HAVE_SPL /** * from spl_directory */ static void phar_spl_foreign_dtor(spl_filesystem_object *object TSRMLS_DC) /* {{{ */ { phar_archive_data *phar = (phar_archive_data *) object->oth; if (!phar->is_persistent) { phar_archive_delref(phar TSRMLS_CC); } object->oth = NULL; } /* }}} */ /** * from spl_directory */ static void phar_spl_foreign_clone(spl_filesystem_object *src, spl_filesystem_object *dst TSRMLS_DC) /* {{{ */ { phar_archive_data *phar_data = (phar_archive_data *) dst->oth; if (!phar_data->is_persistent) { ++(phar_data->refcount); } } /* }}} */ static spl_other_handler phar_spl_foreign_handler = { phar_spl_foreign_dtor, phar_spl_foreign_clone }; #endif /* HAVE_SPL */ /* {{{ proto void Phar::__construct(string fname [, int flags [, string alias]]) * Construct a Phar archive object * * proto void PharData::__construct(string fname [[, int flags [, string alias]], int file format = Phar::TAR]) * Construct a PharData archive object * * This function is used as the constructor for both the Phar and PharData * classes, hence the two prototypes above. */ PHP_METHOD(Phar, __construct) { #if !HAVE_SPL zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Cannot instantiate Phar object without SPL extension"); #else char *fname, *alias = NULL, *error, *arch = NULL, *entry = NULL, *save_fname; int fname_len, alias_len = 0, arch_len, entry_len, is_data; #if PHP_VERSION_ID < 50300 long flags = 0; #else long flags = SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS; #endif long format = 0; phar_archive_object *phar_obj; phar_archive_data *phar_data; zval *zobj = getThis(), arg1, arg2; phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC); is_data = instanceof_function(Z_OBJCE_P(zobj), phar_ce_data TSRMLS_CC); if (is_data) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!l", &fname, &fname_len, &flags, &alias, &alias_len, &format) == FAILURE) { return; } } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!", &fname, &fname_len, &flags, &alias, &alias_len) == FAILURE) { return; } } if (phar_obj->arc.archive) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot call constructor twice"); return; } save_fname = fname; if (SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, !is_data, 2 TSRMLS_CC)) { /* use arch (the basename for the archive) for fname instead of fname */ /* this allows support for RecursiveDirectoryIterator of subdirectories */ #ifdef PHP_WIN32 phar_unixify_path_separators(arch, arch_len); #endif fname = arch; fname_len = arch_len; #ifdef PHP_WIN32 } else { arch = estrndup(fname, fname_len); arch_len = fname_len; fname = arch; phar_unixify_path_separators(arch, arch_len); #endif } if (phar_open_or_create_filename(fname, fname_len, alias, alias_len, is_data, REPORT_ERRORS, &phar_data, &error TSRMLS_CC) == FAILURE) { if (fname == arch && fname != save_fname) { efree(arch); fname = save_fname; } if (entry) { efree(entry); } if (error) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "%s", error); efree(error); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Phar creation or opening failed"); } return; } if (is_data && phar_data->is_tar && phar_data->is_brandnew && format == PHAR_FORMAT_ZIP) { phar_data->is_zip = 1; phar_data->is_tar = 0; } if (fname == arch) { efree(arch); fname = save_fname; } if ((is_data && !phar_data->is_data) || (!is_data && phar_data->is_data)) { if (is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "PharData class can only be used for non-executable tar and zip archives"); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Phar class can only be used for executable tar and zip archives"); } efree(entry); return; } is_data = phar_data->is_data; if (!phar_data->is_persistent) { ++(phar_data->refcount); } phar_obj->arc.archive = phar_data; phar_obj->spl.oth_handler = &phar_spl_foreign_handler; if (entry) { fname_len = spprintf(&fname, 0, "phar://%s%s", phar_data->fname, entry); efree(entry); } else { fname_len = spprintf(&fname, 0, "phar://%s", phar_data->fname); } INIT_PZVAL(&arg1); ZVAL_STRINGL(&arg1, fname, fname_len, 0); INIT_PZVAL(&arg2); ZVAL_LONG(&arg2, flags); zend_call_method_with_2_params(&zobj, Z_OBJCE_P(zobj), &spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg1, &arg2); if (!phar_data->is_persistent) { phar_obj->arc.archive->is_data = is_data; } else if (!EG(exception)) { /* register this guy so we can modify if necessary */ zend_hash_add(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive), (void *) &phar_obj, sizeof(phar_archive_object **), NULL); } phar_obj->spl.info_class = phar_ce_entry; efree(fname); #endif /* HAVE_SPL */ } /* }}} */ /* {{{ proto array Phar::getSupportedSignatures() * Return array of supported signature types */ PHP_METHOD(Phar, getSupportedSignatures) { array_init(return_value); add_next_index_stringl(return_value, "MD5", 3, 1); add_next_index_stringl(return_value, "SHA-1", 5, 1); #ifdef PHAR_HASH_OK add_next_index_stringl(return_value, "SHA-256", 7, 1); add_next_index_stringl(return_value, "SHA-512", 7, 1); #endif #if PHAR_HAVE_OPENSSL add_next_index_stringl(return_value, "OpenSSL", 7, 1); #else if (zend_hash_exists(&module_registry, "openssl", sizeof("openssl"))) { add_next_index_stringl(return_value, "OpenSSL", 7, 1); } #endif } /* }}} */ /* {{{ proto array Phar::getSupportedCompression() * Return array of supported comparession algorithms */ PHP_METHOD(Phar, getSupportedCompression) { array_init(return_value); phar_request_initialize(TSRMLS_C); if (PHAR_G(has_zlib)) { add_next_index_stringl(return_value, "GZ", 2, 1); } if (PHAR_G(has_bz2)) { add_next_index_stringl(return_value, "BZIP2", 5, 1); } } /* }}} */ /* {{{ proto array Phar::unlinkArchive(string archive) * Completely remove a phar archive from memory and disk */ PHP_METHOD(Phar, unlinkArchive) { char *fname, *error, *zname, *arch, *entry; int fname_len, zname_len, arch_len, entry_len; phar_archive_data *phar; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &fname, &fname_len) == FAILURE) { RETURN_FALSE; } if (!fname_len) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown phar archive \"\""); return; } if (FAILURE == phar_open_from_filename(fname, fname_len, NULL, 0, REPORT_ERRORS, &phar, &error TSRMLS_CC)) { if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown phar archive \"%s\": %s", fname, error); efree(error); } else { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown phar archive \"%s\"", fname); } return; } zname = zend_get_executed_filename(TSRMLS_C); zname_len = strlen(zname); if (zname_len > 7 && !memcmp(zname, "phar://", 7) && SUCCESS == phar_split_fname(zname, zname_len, &arch, &arch_len, &entry, &entry_len, 2, 0 TSRMLS_CC)) { if (arch_len == fname_len && !memcmp(arch, fname, arch_len)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar archive \"%s\" cannot be unlinked from within itself", fname); efree(arch); efree(entry); return; } efree(arch); efree(entry); } if (phar->is_persistent) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar archive \"%s\" is in phar.cache_list, cannot unlinkArchive()", fname); return; } if (phar->refcount) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar archive \"%s\" has open file handles or objects. fclose() all file handles, and unset() all objects prior to calling unlinkArchive()", fname); return; } fname = estrndup(phar->fname, phar->fname_len); /* invalidate phar cache */ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; phar_archive_delref(phar TSRMLS_CC); unlink(fname); efree(fname); RETURN_TRUE; } /* }}} */ #if HAVE_SPL #define PHAR_ARCHIVE_OBJECT() \ phar_archive_object *phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC); \ if (!phar_obj->arc.archive) { \ zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \ "Cannot call method on an uninitialized Phar object"); \ return; \ } /* {{{ proto void Phar::__destruct() * if persistent, remove from the cache */ PHP_METHOD(Phar, __destruct) { phar_archive_object *phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (phar_obj->arc.archive && phar_obj->arc.archive->is_persistent) { zend_hash_del(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive)); } } /* }}} */ struct _phar_t { phar_archive_object *p; zend_class_entry *c; char *b; uint l; zval *ret; int count; php_stream *fp; }; static int phar_build(zend_object_iterator *iter, void *puser TSRMLS_DC) /* {{{ */ { zval **value; zend_uchar key_type; zend_bool close_fp = 1; ulong int_key; struct _phar_t *p_obj = (struct _phar_t*) puser; uint str_key_len, base_len = p_obj->l, fname_len; phar_entry_data *data; php_stream *fp; size_t contents_len; char *fname, *error = NULL, *base = p_obj->b, *opened, *save = NULL, *temp = NULL; phar_zstr key; char *str_key; zend_class_entry *ce = p_obj->c; phar_archive_object *phar_obj = p_obj->p; char *str = "[stream]"; iter->funcs->get_current_data(iter, &value TSRMLS_CC); if (EG(exception)) { return ZEND_HASH_APPLY_STOP; } if (!value) { /* failure in get_current_data */ zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned no value", ce->name); return ZEND_HASH_APPLY_STOP; } switch (Z_TYPE_PP(value)) { #if PHP_VERSION_ID >= 60000 case IS_UNICODE: zval_unicode_to_string(*(value) TSRMLS_CC); /* break intentionally omitted */ #endif case IS_STRING: break; case IS_RESOURCE: php_stream_from_zval_no_verify(fp, value); if (!fp) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Iterator %v returned an invalid stream handle", ce->name); return ZEND_HASH_APPLY_STOP; } if (iter->funcs->get_current_key) { key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC); if (EG(exception)) { return ZEND_HASH_APPLY_STOP; } if (key_type == HASH_KEY_IS_LONG) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name); return ZEND_HASH_APPLY_STOP; } if (key_type > 9) { /* IS_UNICODE == 10 */ #if PHP_VERSION_ID < 60000 /* this can never happen, but fixes a compile warning */ spprintf(&str_key, 0, "%s", key); #else spprintf(&str_key, 0, "%v", key); ezfree(key); #endif } else { PHAR_STR(key, str_key); } save = str_key; if (str_key[str_key_len - 1] == '\0') { str_key_len--; } } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name); return ZEND_HASH_APPLY_STOP; } close_fp = 0; opened = (char *) estrndup(str, sizeof("[stream]") + 1); goto after_open_fp; case IS_OBJECT: if (instanceof_function(Z_OBJCE_PP(value), spl_ce_SplFileInfo TSRMLS_CC)) { char *test = NULL; zval dummy; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(*value TSRMLS_CC); if (!base_len) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Iterator %v returns an SplFileInfo object, so base directory must be specified", ce->name); return ZEND_HASH_APPLY_STOP; } switch (intern->type) { case SPL_FS_DIR: #if PHP_VERSION_ID >= 60000 test = spl_filesystem_object_get_path(intern, NULL, NULL TSRMLS_CC).s; #elif PHP_VERSION_ID >= 50300 test = spl_filesystem_object_get_path(intern, NULL TSRMLS_CC); #else test = intern->path; #endif fname_len = spprintf(&fname, 0, "%s%c%s", test, DEFAULT_SLASH, intern->u.dir.entry.d_name); php_stat(fname, fname_len, FS_IS_DIR, &dummy TSRMLS_CC); if (Z_BVAL(dummy)) { /* ignore directories */ efree(fname); return ZEND_HASH_APPLY_KEEP; } test = expand_filepath(fname, NULL TSRMLS_CC); if (test) { efree(fname); fname = test; fname_len = strlen(fname); } save = fname; goto phar_spl_fileinfo; case SPL_FS_INFO: case SPL_FS_FILE: #if PHP_VERSION_ID >= 60000 if (intern->file_name_type == IS_UNICODE) { zval zv; INIT_ZVAL(zv); Z_UNIVAL(zv) = intern->file_name; Z_UNILEN(zv) = intern->file_name_len; Z_TYPE(zv) = IS_UNICODE; zval_copy_ctor(&zv); zval_unicode_to_string(&zv TSRMLS_CC); fname = expand_filepath(Z_STRVAL(zv), NULL TSRMLS_CC); ezfree(Z_UNIVAL(zv)); } else { fname = expand_filepath(intern->file_name.s, NULL TSRMLS_CC); } #else fname = expand_filepath(intern->file_name, NULL TSRMLS_CC); #endif fname_len = strlen(fname); save = fname; goto phar_spl_fileinfo; } } /* fall-through */ default: zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid value (must return a string)", ce->name); return ZEND_HASH_APPLY_STOP; } fname = Z_STRVAL_PP(value); fname_len = Z_STRLEN_PP(value); phar_spl_fileinfo: if (base_len) { temp = expand_filepath(base, NULL TSRMLS_CC); base = temp; base_len = strlen(base); if (strstr(fname, base)) { str_key_len = fname_len - base_len; if (str_key_len <= 0) { if (save) { efree(save); efree(temp); } return ZEND_HASH_APPLY_KEEP; } str_key = fname + base_len; if (*str_key == '/' || *str_key == '\\') { str_key++; str_key_len--; } } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that is not in the base directory \"%s\"", ce->name, fname, base); if (save) { efree(save); efree(temp); } return ZEND_HASH_APPLY_STOP; } } else { if (iter->funcs->get_current_key) { key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC); if (EG(exception)) { return ZEND_HASH_APPLY_STOP; } if (key_type == HASH_KEY_IS_LONG) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name); return ZEND_HASH_APPLY_STOP; } if (key_type > 9) { /* IS_UNICODE == 10 */ #if PHP_VERSION_ID < 60000 /* this can never happen, but fixes a compile warning */ spprintf(&str_key, 0, "%s", key); #else spprintf(&str_key, 0, "%v", key); ezfree(key); #endif } else { PHAR_STR(key, str_key); } save = str_key; if (str_key[str_key_len - 1] == '\0') str_key_len--; } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name); return ZEND_HASH_APPLY_STOP; } } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that safe mode prevents opening", ce->name, fname); if (save) { efree(save); } if (temp) { efree(temp); } return ZEND_HASH_APPLY_STOP; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that open_basedir prevents opening", ce->name, fname); if (save) { efree(save); } if (temp) { efree(temp); } return ZEND_HASH_APPLY_STOP; } /* try to open source file, then create internal phar file and copy contents */ fp = php_stream_open_wrapper(fname, "rb", STREAM_MUST_SEEK|0, &opened); if (!fp) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a file that could not be opened \"%s\"", ce->name, fname); if (save) { efree(save); } if (temp) { efree(temp); } return ZEND_HASH_APPLY_STOP; } after_open_fp: if (str_key_len >= sizeof(".phar")-1 && !memcmp(str_key, ".phar", sizeof(".phar")-1)) { /* silently skip any files that would be added to the magic .phar directory */ if (save) { efree(save); } if (temp) { efree(temp); } if (opened) { efree(opened); } if (close_fp) { php_stream_close(fp); } return ZEND_HASH_APPLY_KEEP; } if (!(data = phar_get_or_create_entry_data(phar_obj->arc.archive->fname, phar_obj->arc.archive->fname_len, str_key, str_key_len, "w+b", 0, &error, 1 TSRMLS_CC))) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s cannot be created: %s", str_key, error); efree(error); if (save) { efree(save); } if (opened) { efree(opened); } if (temp) { efree(temp); } if (close_fp) { php_stream_close(fp); } return ZEND_HASH_APPLY_STOP; } else { if (error) { efree(error); } /* convert to PHAR_UFP */ if (data->internal_file->fp_type == PHAR_MOD) { php_stream_close(data->internal_file->fp); } data->internal_file->fp = NULL; data->internal_file->fp_type = PHAR_UFP; data->internal_file->offset_abs = data->internal_file->offset = php_stream_tell(p_obj->fp); data->fp = NULL; phar_stream_copy_to_stream(fp, p_obj->fp, PHP_STREAM_COPY_ALL, &contents_len); data->internal_file->uncompressed_filesize = data->internal_file->compressed_filesize = php_stream_tell(p_obj->fp) - data->internal_file->offset; } if (close_fp) { php_stream_close(fp); } add_assoc_string(p_obj->ret, str_key, opened, 0); if (save) { efree(save); } if (temp) { efree(temp); } data->internal_file->compressed_filesize = data->internal_file->uncompressed_filesize = contents_len; phar_entry_delref(data TSRMLS_CC); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* {{{ proto array Phar::buildFromDirectory(string base_dir[, string regex]) * Construct a phar archive from an existing directory, recursively. * Optional second parameter is a regular expression for filtering directory contents. * * Return value is an array mapping phar index to actual files added. */ PHP_METHOD(Phar, buildFromDirectory) { char *dir, *error, *regex = NULL; int dir_len, regex_len = 0; zend_bool apply_reg = 0; zval arg, arg2, *iter, *iteriter, *regexiter = NULL; struct _phar_t pass; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot write to archive - write operations restricted by INI setting"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &dir, &dir_len, &regex, &regex_len) == FAILURE) { RETURN_FALSE; } MAKE_STD_ZVAL(iter); if (SUCCESS != object_init_ex(iter, spl_ce_RecursiveDirectoryIterator)) { zval_ptr_dtor(&iter); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname); RETURN_FALSE; } INIT_PZVAL(&arg); ZVAL_STRINGL(&arg, dir, dir_len, 0); INIT_PZVAL(&arg2); #if PHP_VERSION_ID < 50300 ZVAL_LONG(&arg2, 0); #else ZVAL_LONG(&arg2, SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS); #endif zend_call_method_with_2_params(&iter, spl_ce_RecursiveDirectoryIterator, &spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg, &arg2); if (EG(exception)) { zval_ptr_dtor(&iter); RETURN_FALSE; } MAKE_STD_ZVAL(iteriter); if (SUCCESS != object_init_ex(iteriter, spl_ce_RecursiveIteratorIterator)) { zval_ptr_dtor(&iter); zval_ptr_dtor(&iteriter); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname); RETURN_FALSE; } zend_call_method_with_1_params(&iteriter, spl_ce_RecursiveIteratorIterator, &spl_ce_RecursiveIteratorIterator->constructor, "__construct", NULL, iter); if (EG(exception)) { zval_ptr_dtor(&iter); zval_ptr_dtor(&iteriter); RETURN_FALSE; } zval_ptr_dtor(&iter); if (regex_len > 0) { apply_reg = 1; MAKE_STD_ZVAL(regexiter); if (SUCCESS != object_init_ex(regexiter, spl_ce_RegexIterator)) { zval_ptr_dtor(&iteriter); zval_dtor(regexiter); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate regex iterator for %s", phar_obj->arc.archive->fname); RETURN_FALSE; } INIT_PZVAL(&arg2); ZVAL_STRINGL(&arg2, regex, regex_len, 0); zend_call_method_with_2_params(&regexiter, spl_ce_RegexIterator, &spl_ce_RegexIterator->constructor, "__construct", NULL, iteriter, &arg2); } array_init(return_value); pass.c = apply_reg ? Z_OBJCE_P(regexiter) : Z_OBJCE_P(iteriter); pass.p = phar_obj; pass.b = dir; pass.l = dir_len; pass.count = 0; pass.ret = return_value; pass.fp = php_stream_fopen_tmpfile(); if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zval_ptr_dtor(&iteriter); if (apply_reg) { zval_ptr_dtor(&regexiter); } php_stream_close(pass.fp); zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } if (SUCCESS == spl_iterator_apply((apply_reg ? regexiter : iteriter), (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) { zval_ptr_dtor(&iteriter); if (apply_reg) { zval_ptr_dtor(&regexiter); } phar_obj->arc.archive->ufp = pass.fp; phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } } else { zval_ptr_dtor(&iteriter); if (apply_reg) { zval_ptr_dtor(&regexiter); } php_stream_close(pass.fp); } } /* }}} */ /* {{{ proto array Phar::buildFromIterator(Iterator iter[, string base_directory]) * Construct a phar archive from an iterator. The iterator must return a series of strings * that are full paths to files that should be added to the phar. The iterator key should * be the path that the file will have within the phar archive. * * If base directory is specified, then the key will be ignored, and instead the portion of * the current value minus the base directory will be used * * Returned is an array mapping phar index to actual file added */ PHP_METHOD(Phar, buildFromIterator) { zval *obj; char *error; uint base_len = 0; char *base = NULL; struct _phar_t pass; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot write out phar archive, phar is read-only"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|s", &obj, zend_ce_traversable, &base, &base_len) == FAILURE) { RETURN_FALSE; } if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } array_init(return_value); pass.c = Z_OBJCE_P(obj); pass.p = phar_obj; pass.b = base; pass.l = base_len; pass.ret = return_value; pass.count = 0; pass.fp = php_stream_fopen_tmpfile(); if (SUCCESS == spl_iterator_apply(obj, (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) { phar_obj->arc.archive->ufp = pass.fp; phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } } else { php_stream_close(pass.fp); } } /* }}} */ /* {{{ proto int Phar::count() * Returns the number of entries in the Phar archive */ PHP_METHOD(Phar, count) { PHAR_ARCHIVE_OBJECT(); RETURN_LONG(zend_hash_num_elements(&phar_obj->arc.archive->manifest)); } /* }}} */ /* {{{ proto bool Phar::isFileFormat(int format) * Returns true if the phar archive is based on the tar/zip/phar file format depending * on whether Phar::TAR, Phar::ZIP or Phar::PHAR was passed in */ PHP_METHOD(Phar, isFileFormat) { long type; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &type) == FAILURE) { RETURN_FALSE; } switch (type) { case PHAR_FORMAT_TAR: RETURN_BOOL(phar_obj->arc.archive->is_tar); case PHAR_FORMAT_ZIP: RETURN_BOOL(phar_obj->arc.archive->is_zip); case PHAR_FORMAT_PHAR: RETURN_BOOL(!phar_obj->arc.archive->is_tar && !phar_obj->arc.archive->is_zip); default: zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown file format specified"); } } /* }}} */ static int phar_copy_file_contents(phar_entry_info *entry, php_stream *fp TSRMLS_DC) /* {{{ */ { char *error; off_t offset; phar_entry_info *link; if (FAILURE == phar_open_entry_fp(entry, &error, 1 TSRMLS_CC)) { if (error) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot convert phar archive \"%s\", unable to open entry \"%s\" contents: %s", entry->phar->fname, entry->filename, error); efree(error); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot convert phar archive \"%s\", unable to open entry \"%s\" contents", entry->phar->fname, entry->filename); } return FAILURE; } /* copy old contents in entirety */ phar_seek_efp(entry, 0, SEEK_SET, 0, 1 TSRMLS_CC); offset = php_stream_tell(fp); link = phar_get_link_source(entry TSRMLS_CC); if (!link) { link = entry; } if (SUCCESS != phar_stream_copy_to_stream(phar_get_efp(link, 0 TSRMLS_CC), fp, link->uncompressed_filesize, NULL)) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot convert phar archive \"%s\", unable to copy entry \"%s\" contents", entry->phar->fname, entry->filename); return FAILURE; } if (entry->fp_type == PHAR_MOD) { /* save for potential restore on error */ entry->cfp = entry->fp; entry->fp = NULL; } /* set new location of file contents */ entry->fp_type = PHAR_FP; entry->offset = offset; return SUCCESS; } /* }}} */ static zval *phar_rename_archive(phar_archive_data *phar, char *ext, zend_bool compress TSRMLS_DC) /* {{{ */ { const char *oldname = NULL; char *oldpath = NULL; char *basename = NULL, *basepath = NULL; char *newname = NULL, *newpath = NULL; zval *ret, arg1; zend_class_entry *ce; char *error; const char *pcr_error; int ext_len = ext ? strlen(ext) : 0; int oldname_len; phar_archive_data **pphar = NULL; php_stream_statbuf ssb; if (!ext) { if (phar->is_zip) { if (phar->is_data) { ext = "zip"; } else { ext = "phar.zip"; } } else if (phar->is_tar) { switch (phar->flags) { case PHAR_FILE_COMPRESSED_GZ: if (phar->is_data) { ext = "tar.gz"; } else { ext = "phar.tar.gz"; } break; case PHAR_FILE_COMPRESSED_BZ2: if (phar->is_data) { ext = "tar.bz2"; } else { ext = "phar.tar.bz2"; } break; default: if (phar->is_data) { ext = "tar"; } else { ext = "phar.tar"; } } } else { switch (phar->flags) { case PHAR_FILE_COMPRESSED_GZ: ext = "phar.gz"; break; case PHAR_FILE_COMPRESSED_BZ2: ext = "phar.bz2"; break; default: ext = "phar"; } } } else if (phar_path_check(&ext, &ext_len, &pcr_error) > pcr_is_ok) { if (phar->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "data phar converted from \"%s\" has invalid extension %s", phar->fname, ext); } else { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar converted from \"%s\" has invalid extension %s", phar->fname, ext); } return NULL; } if (ext[0] == '.') { ++ext; } oldpath = estrndup(phar->fname, phar->fname_len); oldname = zend_memrchr(phar->fname, '/', phar->fname_len); ++oldname; oldname_len = strlen(oldname); basename = estrndup(oldname, oldname_len); spprintf(&newname, 0, "%s.%s", strtok(basename, "."), ext); efree(basename); basepath = estrndup(oldpath, (strlen(oldpath) - oldname_len)); phar->fname_len = spprintf(&newpath, 0, "%s%s", basepath, newname); phar->fname = newpath; phar->ext = newpath + phar->fname_len - strlen(ext) - 1; efree(basepath); efree(newname); if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, newpath, phar->fname_len, (void **) &pphar)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars, new phar name is in phar.cache_list", phar->fname); return NULL; } if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void **) &pphar)) { if ((*pphar)->fname_len == phar->fname_len && !memcmp((*pphar)->fname, phar->fname, phar->fname_len)) { if (!zend_hash_num_elements(&phar->manifest)) { (*pphar)->is_tar = phar->is_tar; (*pphar)->is_zip = phar->is_zip; (*pphar)->is_data = phar->is_data; (*pphar)->flags = phar->flags; (*pphar)->fp = phar->fp; phar->fp = NULL; phar_destroy_phar_data(phar TSRMLS_CC); phar = *pphar; phar->refcount++; newpath = oldpath; goto its_ok; } } efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars, a phar with that name already exists", phar->fname); return NULL; } its_ok: if (SUCCESS == php_stream_stat_path(newpath, &ssb)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar \"%s\" exists and must be unlinked prior to conversion", newpath); return NULL; } if (!phar->is_data) { if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 1, 1, 1 TSRMLS_CC)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar \"%s\" has invalid extension %s", phar->fname, ext); return NULL; } if (phar->alias) { if (phar->is_temporary_alias) { phar->alias = NULL; phar->alias_len = 0; } else { phar->alias = estrndup(newpath, strlen(newpath)); phar->alias_len = strlen(newpath); phar->is_temporary_alias = 1; zend_hash_update(&(PHAR_GLOBALS->phar_alias_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL); } } } else { if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 0, 1, 1 TSRMLS_CC)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "data phar \"%s\" has invalid extension %s", phar->fname, ext); return NULL; } phar->alias = NULL; phar->alias_len = 0; } if ((!pphar || phar == *pphar) && SUCCESS != zend_hash_update(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars", phar->fname); return NULL; } phar_flush(phar, 0, 0, 1, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "%s", error); efree(error); efree(oldpath); return NULL; } efree(oldpath); if (phar->is_data) { ce = phar_ce_data; } else { ce = phar_ce_archive; } MAKE_STD_ZVAL(ret); if (SUCCESS != object_init_ex(ret, ce)) { zval_dtor(ret); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate phar object when converting archive \"%s\"", phar->fname); return NULL; } INIT_PZVAL(&arg1); ZVAL_STRINGL(&arg1, phar->fname, phar->fname_len, 0); zend_call_method_with_1_params(&ret, ce, &ce->constructor, "__construct", NULL, &arg1); return ret; } /* }}} */ static zval *phar_convert_to_other(phar_archive_data *source, int convert, char *ext, php_uint32 flags TSRMLS_DC) /* {{{ */ { phar_archive_data *phar; phar_entry_info *entry, newentry; zval *ret; /* invalidate phar cache */ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; phar = (phar_archive_data *) ecalloc(1, sizeof(phar_archive_data)); /* set whole-archive compression and type from parameter */ phar->flags = flags; phar->is_data = source->is_data; switch (convert) { case PHAR_FORMAT_TAR: phar->is_tar = 1; break; case PHAR_FORMAT_ZIP: phar->is_zip = 1; break; default: phar->is_data = 0; break; } zend_hash_init(&(phar->manifest), sizeof(phar_entry_info), zend_get_hash_value, destroy_phar_manifest_entry, 0); zend_hash_init(&phar->mounted_dirs, sizeof(char *), zend_get_hash_value, NULL, 0); zend_hash_init(&phar->virtual_dirs, sizeof(char *), zend_get_hash_value, NULL, 0); phar->fp = php_stream_fopen_tmpfile(); phar->fname = source->fname; phar->fname_len = source->fname_len; phar->is_temporary_alias = source->is_temporary_alias; phar->alias = source->alias; if (source->metadata) { zval *t; t = source->metadata; ALLOC_ZVAL(phar->metadata); *phar->metadata = *t; zval_copy_ctor(phar->metadata); #if PHP_VERSION_ID < 50300 phar->metadata->refcount = 1; #else Z_SET_REFCOUNT_P(phar->metadata, 1); #endif phar->metadata_len = 0; } /* first copy each file's uncompressed contents to a temporary file and set per-file flags */ for (zend_hash_internal_pointer_reset(&source->manifest); SUCCESS == zend_hash_has_more_elements(&source->manifest); zend_hash_move_forward(&source->manifest)) { if (FAILURE == zend_hash_get_current_data(&source->manifest, (void **) &entry)) { zend_hash_destroy(&(phar->manifest)); php_stream_close(phar->fp); efree(phar); zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot convert phar archive \"%s\"", source->fname); return NULL; } newentry = *entry; if (newentry.link) { newentry.link = estrdup(newentry.link); goto no_copy; } if (newentry.tmp) { newentry.tmp = estrdup(newentry.tmp); goto no_copy; } newentry.metadata_str.c = 0; if (FAILURE == phar_copy_file_contents(&newentry, phar->fp TSRMLS_CC)) { zend_hash_destroy(&(phar->manifest)); php_stream_close(phar->fp); efree(phar); /* exception already thrown */ return NULL; } no_copy: newentry.filename = estrndup(newentry.filename, newentry.filename_len); if (newentry.metadata) { zval *t; t = newentry.metadata; ALLOC_ZVAL(newentry.metadata); *newentry.metadata = *t; zval_copy_ctor(newentry.metadata); #if PHP_VERSION_ID < 50300 newentry.metadata->refcount = 1; #else Z_SET_REFCOUNT_P(newentry.metadata, 1); #endif newentry.metadata_str.c = NULL; newentry.metadata_str.len = 0; } newentry.is_zip = phar->is_zip; newentry.is_tar = phar->is_tar; if (newentry.is_tar) { newentry.tar_type = (entry->is_dir ? TAR_DIR : TAR_FILE); } newentry.is_modified = 1; newentry.phar = phar; newentry.old_flags = newentry.flags & ~PHAR_ENT_COMPRESSION_MASK; /* remove compression from old_flags */ phar_set_inode(&newentry TSRMLS_CC); zend_hash_add(&(phar->manifest), newentry.filename, newentry.filename_len, (void*)&newentry, sizeof(phar_entry_info), NULL); phar_add_virtual_dirs(phar, newentry.filename, newentry.filename_len TSRMLS_CC); } if ((ret = phar_rename_archive(phar, ext, 0 TSRMLS_CC))) { return ret; } else { zend_hash_destroy(&(phar->manifest)); zend_hash_destroy(&(phar->mounted_dirs)); zend_hash_destroy(&(phar->virtual_dirs)); php_stream_close(phar->fp); efree(phar->fname); efree(phar); return NULL; } } /* }}} */ /* {{{ proto object Phar::convertToExecutable([int format[, int compression [, string file_ext]]]) * Convert a phar.tar or phar.zip archive to the phar file format. The * optional parameter allows the user to determine the new * filename extension (default is phar). */ PHP_METHOD(Phar, convertToExecutable) { char *ext = NULL; int is_data, ext_len = 0; php_uint32 flags; zval *ret; /* a number that is not 0, 1 or 2 (Which is also Greg's birthday, so there) */ long format = 9021976, method = 9021976; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lls", &format, &method, &ext, &ext_len) == FAILURE) { return; } if (PHAR_G(readonly)) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot write out executable phar archive, phar is read-only"); return; } switch (format) { case 9021976: case PHAR_FORMAT_SAME: /* null is converted to 0 */ /* by default, use the existing format */ if (phar_obj->arc.archive->is_tar) { format = PHAR_FORMAT_TAR; } else if (phar_obj->arc.archive->is_zip) { format = PHAR_FORMAT_ZIP; } else { format = PHAR_FORMAT_PHAR; } break; case PHAR_FORMAT_PHAR: case PHAR_FORMAT_TAR: case PHAR_FORMAT_ZIP: break; default: zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unknown file format specified, please pass one of Phar::PHAR, Phar::TAR or Phar::ZIP"); return; } switch (method) { case 9021976: flags = phar_obj->arc.archive->flags & PHAR_FILE_COMPRESSION_MASK; break; case 0: flags = PHAR_FILE_COMPRESSED_NONE; break; case PHAR_ENT_COMPRESSED_GZ: if (format == PHAR_FORMAT_ZIP) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress entire archive with gzip, zip archives do not support whole-archive compression"); return; } if (!PHAR_G(has_zlib)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress entire archive with gzip, enable ext/zlib in php.ini"); return; } flags = PHAR_FILE_COMPRESSED_GZ; break; case PHAR_ENT_COMPRESSED_BZ2: if (format == PHAR_FORMAT_ZIP) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress entire archive with bz2, zip archives do not support whole-archive compression"); return; } if (!PHAR_G(has_bz2)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress entire archive with bz2, enable ext/bz2 in php.ini"); return; } flags = PHAR_FILE_COMPRESSED_BZ2; break; default: zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unknown compression specified, please pass one of Phar::GZ or Phar::BZ2"); return; } is_data = phar_obj->arc.archive->is_data; phar_obj->arc.archive->is_data = 0; ret = phar_convert_to_other(phar_obj->arc.archive, format, ext, flags TSRMLS_CC); phar_obj->arc.archive->is_data = is_data; if (ret) { RETURN_ZVAL(ret, 1, 1); } else { RETURN_NULL(); } } /* }}} */ /* {{{ proto object Phar::convertToData([int format[, int compression [, string file_ext]]]) * Convert an archive to a non-executable .tar or .zip. * The optional parameter allows the user to determine the new * filename extension (default is .zip or .tar). */ PHP_METHOD(Phar, convertToData) { char *ext = NULL; int is_data, ext_len = 0; php_uint32 flags; zval *ret; /* a number that is not 0, 1 or 2 (Which is also Greg's birthday so there) */ long format = 9021976, method = 9021976; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lls", &format, &method, &ext, &ext_len) == FAILURE) { return; } switch (format) { case 9021976: case PHAR_FORMAT_SAME: /* null is converted to 0 */ /* by default, use the existing format */ if (phar_obj->arc.archive->is_tar) { format = PHAR_FORMAT_TAR; } else if (phar_obj->arc.archive->is_zip) { format = PHAR_FORMAT_ZIP; } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot write out data phar archive, use Phar::TAR or Phar::ZIP"); return; } break; case PHAR_FORMAT_PHAR: zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot write out data phar archive, use Phar::TAR or Phar::ZIP"); return; case PHAR_FORMAT_TAR: case PHAR_FORMAT_ZIP: break; default: zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unknown file format specified, please pass one of Phar::TAR or Phar::ZIP"); return; } switch (method) { case 9021976: flags = phar_obj->arc.archive->flags & PHAR_FILE_COMPRESSION_MASK; break; case 0: flags = PHAR_FILE_COMPRESSED_NONE; break; case PHAR_ENT_COMPRESSED_GZ: if (format == PHAR_FORMAT_ZIP) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress entire archive with gzip, zip archives do not support whole-archive compression"); return; } if (!PHAR_G(has_zlib)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress entire archive with gzip, enable ext/zlib in php.ini"); return; } flags = PHAR_FILE_COMPRESSED_GZ; break; case PHAR_ENT_COMPRESSED_BZ2: if (format == PHAR_FORMAT_ZIP) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress entire archive with bz2, zip archives do not support whole-archive compression"); return; } if (!PHAR_G(has_bz2)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress entire archive with bz2, enable ext/bz2 in php.ini"); return; } flags = PHAR_FILE_COMPRESSED_BZ2; break; default: zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unknown compression specified, please pass one of Phar::GZ or Phar::BZ2"); return; } is_data = phar_obj->arc.archive->is_data; phar_obj->arc.archive->is_data = 1; ret = phar_convert_to_other(phar_obj->arc.archive, format, ext, flags TSRMLS_CC); phar_obj->arc.archive->is_data = is_data; if (ret) { RETURN_ZVAL(ret, 1, 1); } else { RETURN_NULL(); } } /* }}} */ /* {{{ proto int|false Phar::isCompressed() * Returns Phar::GZ or PHAR::BZ2 if the entire archive is compressed * (.tar.gz/tar.bz2 and so on), or FALSE otherwise. */ PHP_METHOD(Phar, isCompressed) { PHAR_ARCHIVE_OBJECT(); if (phar_obj->arc.archive->flags & PHAR_FILE_COMPRESSED_GZ) { RETURN_LONG(PHAR_ENT_COMPRESSED_GZ); } if (phar_obj->arc.archive->flags & PHAR_FILE_COMPRESSED_BZ2) { RETURN_LONG(PHAR_ENT_COMPRESSED_BZ2); } RETURN_FALSE; } /* }}} */ /* {{{ proto bool Phar::isWritable() * Returns true if phar.readonly=0 or phar is a PharData AND the actual file is writable. */ PHP_METHOD(Phar, isWritable) { php_stream_statbuf ssb; PHAR_ARCHIVE_OBJECT(); if (!phar_obj->arc.archive->is_writeable) { RETURN_FALSE; } if (SUCCESS != php_stream_stat_path(phar_obj->arc.archive->fname, &ssb)) { if (phar_obj->arc.archive->is_brandnew) { /* assume it works if the file doesn't exist yet */ RETURN_TRUE; } RETURN_FALSE; } RETURN_BOOL((ssb.sb.st_mode & (S_IWOTH | S_IWGRP | S_IWUSR)) != 0); } /* }}} */ /* {{{ proto bool Phar::delete(string entry) * Deletes a named file within the archive. */ PHP_METHOD(Phar, delete) { char *fname; int fname_len; char *error; phar_entry_info *entry; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot write out phar archive, phar is read-only"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &fname, &fname_len) == FAILURE) { RETURN_FALSE; } if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } if (zend_hash_exists(&phar_obj->arc.archive->manifest, fname, (uint) fname_len)) { if (SUCCESS == zend_hash_find(&phar_obj->arc.archive->manifest, fname, (uint) fname_len, (void**)&entry)) { if (entry->is_deleted) { /* entry is deleted, but has not been flushed to disk yet */ RETURN_TRUE; } else { entry->is_deleted = 1; entry->is_modified = 1; phar_obj->arc.archive->is_modified = 1; } } } else { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s does not exist and cannot be deleted", fname); RETURN_FALSE; } phar_flush(phar_obj->arc.archive, NULL, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } RETURN_TRUE; } /* }}} */ /* {{{ proto int Phar::getAlias() * Returns the alias for the Phar or NULL. */ PHP_METHOD(Phar, getAlias) { PHAR_ARCHIVE_OBJECT(); if (phar_obj->arc.archive->alias && phar_obj->arc.archive->alias != phar_obj->arc.archive->fname) { RETURN_STRINGL(phar_obj->arc.archive->alias, phar_obj->arc.archive->alias_len, 1); } } /* }}} */ /* {{{ proto int Phar::getPath() * Returns the real path to the phar archive on disk */ PHP_METHOD(Phar, getPath) { PHAR_ARCHIVE_OBJECT(); RETURN_STRINGL(phar_obj->arc.archive->fname, phar_obj->arc.archive->fname_len, 1); } /* }}} */ /* {{{ proto bool Phar::setAlias(string alias) * Sets the alias for a Phar archive. The default value is the full path * to the archive. */ PHP_METHOD(Phar, setAlias) { char *alias, *error, *oldalias; phar_archive_data **fd_ptr; int alias_len, oldalias_len, old_temp, readd = 0; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot write out phar archive, phar is read-only"); RETURN_FALSE; } /* invalidate phar cache */ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; if (phar_obj->arc.archive->is_data) { if (phar_obj->arc.archive->is_tar) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "A Phar alias cannot be set in a plain tar archive"); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "A Phar alias cannot be set in a plain zip archive"); } RETURN_FALSE; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &alias, &alias_len) == SUCCESS) { if (alias_len == phar_obj->arc.archive->alias_len && memcmp(phar_obj->arc.archive->alias, alias, alias_len) == 0) { RETURN_TRUE; } if (alias_len && SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void**)&fd_ptr)) { spprintf(&error, 0, "alias \"%s\" is already used for archive \"%s\" and cannot be used for other archives", alias, (*fd_ptr)->fname); if (SUCCESS == phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) { efree(error); goto valid_alias; } zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); RETURN_FALSE; } if (!phar_validate_alias(alias, alias_len)) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Invalid alias \"%s\" specified for phar \"%s\"", alias, phar_obj->arc.archive->fname); RETURN_FALSE; } valid_alias: if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } if (phar_obj->arc.archive->alias_len && SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), phar_obj->arc.archive->alias, phar_obj->arc.archive->alias_len, (void**)&fd_ptr)) { zend_hash_del(&(PHAR_GLOBALS->phar_alias_map), phar_obj->arc.archive->alias, phar_obj->arc.archive->alias_len); readd = 1; } oldalias = phar_obj->arc.archive->alias; oldalias_len = phar_obj->arc.archive->alias_len; old_temp = phar_obj->arc.archive->is_temporary_alias; if (alias_len) { phar_obj->arc.archive->alias = estrndup(alias, alias_len); } else { phar_obj->arc.archive->alias = NULL; } phar_obj->arc.archive->alias_len = alias_len; phar_obj->arc.archive->is_temporary_alias = 0; phar_flush(phar_obj->arc.archive, NULL, 0, 0, &error TSRMLS_CC); if (error) { phar_obj->arc.archive->alias = oldalias; phar_obj->arc.archive->alias_len = oldalias_len; phar_obj->arc.archive->is_temporary_alias = old_temp; zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); if (readd) { zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), oldalias, oldalias_len, (void*)&(phar_obj->arc.archive), sizeof(phar_archive_data*), NULL); } efree(error); RETURN_FALSE; } zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&(phar_obj->arc.archive), sizeof(phar_archive_data*), NULL); if (oldalias) { efree(oldalias); } RETURN_TRUE; } RETURN_FALSE; } /* }}} */ /* {{{ proto string Phar::getVersion() * Return version info of Phar archive */ PHP_METHOD(Phar, getVersion) { PHAR_ARCHIVE_OBJECT(); RETURN_STRING(phar_obj->arc.archive->version, 1); } /* }}} */ /* {{{ proto void Phar::startBuffering() * Do not flush a writeable phar (save its contents) until explicitly requested */ PHP_METHOD(Phar, startBuffering) { PHAR_ARCHIVE_OBJECT(); phar_obj->arc.archive->donotflush = 1; } /* }}} */ /* {{{ proto bool Phar::isBuffering() * Returns whether write operations are flushing to disk immediately. */ PHP_METHOD(Phar, isBuffering) { PHAR_ARCHIVE_OBJECT(); RETURN_BOOL(phar_obj->arc.archive->donotflush); } /* }}} */ /* {{{ proto bool Phar::stopBuffering() * Saves the contents of a modified archive to disk. */ PHP_METHOD(Phar, stopBuffering) { char *error; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot write out phar archive, phar is read-only"); return; } phar_obj->arc.archive->donotflush = 0; phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } } /* }}} */ /* {{{ proto bool Phar::setStub(string|stream stub [, int len]) * Change the stub in a phar, phar.tar or phar.zip archive to something other * than the default. The stub *must* end with a call to __HALT_COMPILER(). */ PHP_METHOD(Phar, setStub) { zval *zstub; char *stub, *error; int stub_len; long len = -1; php_stream *stream; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot change stub, phar is read-only"); return; } if (phar_obj->arc.archive->is_data) { if (phar_obj->arc.archive->is_tar) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "A Phar stub cannot be set in a plain tar archive"); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "A Phar stub cannot be set in a plain zip archive"); } return; } if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r|l", &zstub, &len) == SUCCESS) { if ((php_stream_from_zval_no_verify(stream, &zstub)) != NULL) { if (len > 0) { len = -len; } else { len = -1; } if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } phar_flush(phar_obj->arc.archive, (char *) &zstub, len, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } RETURN_TRUE; } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot change stub, unable to read from input stream"); } } else if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &stub, &stub_len) == SUCCESS) { if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } phar_flush(phar_obj->arc.archive, stub, stub_len, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } RETURN_TRUE; } RETURN_FALSE; } /* }}} */ /* {{{ proto bool Phar::setDefaultStub([string index[, string webindex]]) * In a pure phar archive, sets a stub that can be used to run the archive * regardless of whether the phar extension is available. The first parameter * is the CLI startup filename, which defaults to "index.php". The second * parameter is the web startup filename and also defaults to "index.php" * (falling back to CLI behaviour). * Both parameters are optional. * In a phar.zip or phar.tar archive, the default stub is used only to * identify the archive to the extension as a Phar object. This allows the * extension to treat phar.zip and phar.tar types as honorary phars. Since * files cannot be loaded via this kind of stub, no parameters are accepted * when the Phar object is zip- or tar-based. */ PHP_METHOD(Phar, setDefaultStub) { char *index = NULL, *webindex = NULL, *error = NULL, *stub = NULL; int index_len = 0, webindex_len = 0, created_stub = 0; size_t stub_len = 0; PHAR_ARCHIVE_OBJECT(); if (phar_obj->arc.archive->is_data) { if (phar_obj->arc.archive->is_tar) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "A Phar stub cannot be set in a plain tar archive"); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "A Phar stub cannot be set in a plain zip archive"); } return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!s", &index, &index_len, &webindex, &webindex_len) == FAILURE) { RETURN_FALSE; } if (ZEND_NUM_ARGS() > 0 && (phar_obj->arc.archive->is_tar || phar_obj->arc.archive->is_zip)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "method accepts no arguments for a tar- or zip-based phar stub, %d given", ZEND_NUM_ARGS()); RETURN_FALSE; } if (PHAR_G(readonly)) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot change stub: phar.readonly=1"); RETURN_FALSE; } if (!phar_obj->arc.archive->is_tar && !phar_obj->arc.archive->is_zip) { stub = phar_create_default_stub(index, webindex, &stub_len, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "%s", error); efree(error); if (stub) { efree(stub); } RETURN_FALSE; } created_stub = 1; } if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } phar_flush(phar_obj->arc.archive, stub, stub_len, 1, &error TSRMLS_CC); if (created_stub) { efree(stub); } if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto array Phar::setSignatureAlgorithm(int sigtype[, string privatekey]) * Sets the signature algorithm for a phar and applies it. The signature * algorithm must be one of Phar::MD5, Phar::SHA1, Phar::SHA256, * Phar::SHA512, or Phar::OPENSSL. Note that zip- based phar archives * cannot support signatures. */ PHP_METHOD(Phar, setSignatureAlgorithm) { long algo; char *error, *key = NULL; int key_len = 0; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot set signature algorithm, phar is read-only"); return; } if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "l|s", &algo, &key, &key_len) != SUCCESS) { return; } switch (algo) { case PHAR_SIG_SHA256: case PHAR_SIG_SHA512: #ifndef PHAR_HASH_OK zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "SHA-256 and SHA-512 signatures are only supported if the hash extension is enabled and built non-shared"); return; #endif case PHAR_SIG_MD5: case PHAR_SIG_SHA1: case PHAR_SIG_OPENSSL: if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } phar_obj->arc.archive->sig_flags = algo; phar_obj->arc.archive->is_modified = 1; PHAR_G(openssl_privatekey) = key; PHAR_G(openssl_privatekey_len) = key_len; phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } break; default: zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Unknown signature algorithm specified"); } } /* }}} */ /* {{{ proto array|false Phar::getSignature() * Returns a hash signature, or FALSE if the archive is unsigned. */ PHP_METHOD(Phar, getSignature) { PHAR_ARCHIVE_OBJECT(); if (phar_obj->arc.archive->signature) { char *unknown; int unknown_len; array_init(return_value); add_assoc_stringl(return_value, "hash", phar_obj->arc.archive->signature, phar_obj->arc.archive->sig_len, 1); switch(phar_obj->arc.archive->sig_flags) { case PHAR_SIG_MD5: add_assoc_stringl(return_value, "hash_type", "MD5", 3, 1); break; case PHAR_SIG_SHA1: add_assoc_stringl(return_value, "hash_type", "SHA-1", 5, 1); break; case PHAR_SIG_SHA256: add_assoc_stringl(return_value, "hash_type", "SHA-256", 7, 1); break; case PHAR_SIG_SHA512: add_assoc_stringl(return_value, "hash_type", "SHA-512", 7, 1); break; case PHAR_SIG_OPENSSL: add_assoc_stringl(return_value, "hash_type", "OpenSSL", 7, 1); break; default: unknown_len = spprintf(&unknown, 0, "Unknown (%u)", phar_obj->arc.archive->sig_flags); add_assoc_stringl(return_value, "hash_type", unknown, unknown_len, 0); break; } } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool Phar::getModified() * Return whether phar was modified */ PHP_METHOD(Phar, getModified) { PHAR_ARCHIVE_OBJECT(); RETURN_BOOL(phar_obj->arc.archive->is_modified); } /* }}} */ static int phar_set_compression(void *pDest, void *argument TSRMLS_DC) /* {{{ */ { phar_entry_info *entry = (phar_entry_info *)pDest; php_uint32 compress = *(php_uint32 *)argument; if (entry->is_deleted) { return ZEND_HASH_APPLY_KEEP; } entry->old_flags = entry->flags; entry->flags &= ~PHAR_ENT_COMPRESSION_MASK; entry->flags |= compress; entry->is_modified = 1; return ZEND_HASH_APPLY_KEEP; } /* }}} */ static int phar_test_compression(void *pDest, void *argument TSRMLS_DC) /* {{{ */ { phar_entry_info *entry = (phar_entry_info *)pDest; if (entry->is_deleted) { return ZEND_HASH_APPLY_KEEP; } if (!PHAR_G(has_bz2)) { if (entry->flags & PHAR_ENT_COMPRESSED_BZ2) { *(int *) argument = 0; } } if (!PHAR_G(has_zlib)) { if (entry->flags & PHAR_ENT_COMPRESSED_GZ) { *(int *) argument = 0; } } return ZEND_HASH_APPLY_KEEP; } /* }}} */ static void pharobj_set_compression(HashTable *manifest, php_uint32 compress TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_argument(manifest, phar_set_compression, &compress TSRMLS_CC); } /* }}} */ static int pharobj_cancompress(HashTable *manifest TSRMLS_DC) /* {{{ */ { int test; test = 1; zend_hash_apply_with_argument(manifest, phar_test_compression, &test TSRMLS_CC); return test; } /* }}} */ /* {{{ proto object Phar::compress(int method[, string extension]) * Compress a .tar, or .phar.tar with whole-file compression * The parameter can be one of Phar::GZ or Phar::BZ2 to specify * the kind of compression desired */ PHP_METHOD(Phar, compress) { long method; char *ext = NULL; int ext_len = 0; php_uint32 flags; zval *ret; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|s", &method, &ext, &ext_len) == FAILURE) { return; } if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot compress phar archive, phar is read-only"); return; } if (phar_obj->arc.archive->is_zip) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot compress zip-based archives with whole-archive compression"); return; } switch (method) { case 0: flags = PHAR_FILE_COMPRESSED_NONE; break; case PHAR_ENT_COMPRESSED_GZ: if (!PHAR_G(has_zlib)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress entire archive with gzip, enable ext/zlib in php.ini"); return; } flags = PHAR_FILE_COMPRESSED_GZ; break; case PHAR_ENT_COMPRESSED_BZ2: if (!PHAR_G(has_bz2)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress entire archive with bz2, enable ext/bz2 in php.ini"); return; } flags = PHAR_FILE_COMPRESSED_BZ2; break; default: zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unknown compression specified, please pass one of Phar::GZ or Phar::BZ2"); return; } if (phar_obj->arc.archive->is_tar) { ret = phar_convert_to_other(phar_obj->arc.archive, PHAR_FORMAT_TAR, ext, flags TSRMLS_CC); } else { ret = phar_convert_to_other(phar_obj->arc.archive, PHAR_FORMAT_PHAR, ext, flags TSRMLS_CC); } if (ret) { RETURN_ZVAL(ret, 1, 1); } else { RETURN_NULL(); } } /* }}} */ /* {{{ proto object Phar::decompress([string extension]) * Decompress a .tar, or .phar.tar with whole-file compression */ PHP_METHOD(Phar, decompress) { char *ext = NULL; int ext_len = 0; zval *ret; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &ext, &ext_len) == FAILURE) { return; } if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot decompress phar archive, phar is read-only"); return; } if (phar_obj->arc.archive->is_zip) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot decompress zip-based archives with whole-archive compression"); return; } if (phar_obj->arc.archive->is_tar) { ret = phar_convert_to_other(phar_obj->arc.archive, PHAR_FORMAT_TAR, ext, PHAR_FILE_COMPRESSED_NONE TSRMLS_CC); } else { ret = phar_convert_to_other(phar_obj->arc.archive, PHAR_FORMAT_PHAR, ext, PHAR_FILE_COMPRESSED_NONE TSRMLS_CC); } if (ret) { RETURN_ZVAL(ret, 1, 1); } else { RETURN_NULL(); } } /* }}} */ /* {{{ proto object Phar::compressFiles(int method) * Compress all files within a phar or zip archive using the specified compression * The parameter can be one of Phar::GZ or Phar::BZ2 to specify * the kind of compression desired */ PHP_METHOD(Phar, compressFiles) { char *error; php_uint32 flags; long method; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &method) == FAILURE) { return; } if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Phar is readonly, cannot change compression"); return; } switch (method) { case PHAR_ENT_COMPRESSED_GZ: if (!PHAR_G(has_zlib)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress files within archive with gzip, enable ext/zlib in php.ini"); return; } flags = PHAR_ENT_COMPRESSED_GZ; break; case PHAR_ENT_COMPRESSED_BZ2: if (!PHAR_G(has_bz2)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress files within archive with bz2, enable ext/bz2 in php.ini"); return; } flags = PHAR_ENT_COMPRESSED_BZ2; break; default: zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unknown compression specified, please pass one of Phar::GZ or Phar::BZ2"); return; } if (phar_obj->arc.archive->is_tar) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress with Gzip compression, tar archives cannot compress individual files, use compress() to compress the whole archive"); return; } if (!pharobj_cancompress(&phar_obj->arc.archive->manifest TSRMLS_CC)) { if (flags == PHAR_FILE_COMPRESSED_GZ) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress all files as Gzip, some are compressed as bzip2 and cannot be decompressed"); } else { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress all files as Bzip2, some are compressed as gzip and cannot be decompressed"); } return; } if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } pharobj_set_compression(&phar_obj->arc.archive->manifest, flags TSRMLS_CC); phar_obj->arc.archive->is_modified = 1; phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "%s", error); efree(error); } } /* }}} */ /* {{{ proto bool Phar::decompressFiles() * decompress every file */ PHP_METHOD(Phar, decompressFiles) { char *error; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Phar is readonly, cannot change compression"); return; } if (!pharobj_cancompress(&phar_obj->arc.archive->manifest TSRMLS_CC)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot decompress all files, some are compressed as bzip2 or gzip and cannot be decompressed"); return; } if (phar_obj->arc.archive->is_tar) { RETURN_TRUE; } else { if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } pharobj_set_compression(&phar_obj->arc.archive->manifest, PHAR_ENT_COMPRESSED_NONE TSRMLS_CC); } phar_obj->arc.archive->is_modified = 1; phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "%s", error); efree(error); } RETURN_TRUE; } /* }}} */ /* {{{ proto bool Phar::copy(string oldfile, string newfile) * copy a file internal to the phar archive to another new file within the phar */ PHP_METHOD(Phar, copy) { char *oldfile, *newfile, *error; const char *pcr_error; int oldfile_len, newfile_len; phar_entry_info *oldentry, newentry = {0}, *temp; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &oldfile, &oldfile_len, &newfile, &newfile_len) == FAILURE) { return; } if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot copy \"%s\" to \"%s\", phar is read-only", oldfile, newfile); RETURN_FALSE; } if (oldfile_len >= sizeof(".phar")-1 && !memcmp(oldfile, ".phar", sizeof(".phar")-1)) { /* can't copy a meta file */ zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "file \"%s\" cannot be copied to file \"%s\", cannot copy Phar meta-file in %s", oldfile, newfile, phar_obj->arc.archive->fname); RETURN_FALSE; } if (newfile_len >= sizeof(".phar")-1 && !memcmp(newfile, ".phar", sizeof(".phar")-1)) { /* can't copy a meta file */ zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "file \"%s\" cannot be copied to file \"%s\", cannot copy to Phar meta-file in %s", oldfile, newfile, phar_obj->arc.archive->fname); RETURN_FALSE; } if (!zend_hash_exists(&phar_obj->arc.archive->manifest, oldfile, (uint) oldfile_len) || SUCCESS != zend_hash_find(&phar_obj->arc.archive->manifest, oldfile, (uint) oldfile_len, (void**)&oldentry) || oldentry->is_deleted) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "file \"%s\" cannot be copied to file \"%s\", file does not exist in %s", oldfile, newfile, phar_obj->arc.archive->fname); RETURN_FALSE; } if (zend_hash_exists(&phar_obj->arc.archive->manifest, newfile, (uint) newfile_len)) { if (SUCCESS == zend_hash_find(&phar_obj->arc.archive->manifest, newfile, (uint) newfile_len, (void**)&temp) || !temp->is_deleted) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "file \"%s\" cannot be copied to file \"%s\", file must not already exist in phar %s", oldfile, newfile, phar_obj->arc.archive->fname); RETURN_FALSE; } } if (phar_path_check(&newfile, &newfile_len, &pcr_error) > pcr_is_ok) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "file \"%s\" contains invalid characters %s, cannot be copied from \"%s\" in phar %s", newfile, pcr_error, oldfile, phar_obj->arc.archive->fname); RETURN_FALSE; } if (phar_obj->arc.archive->is_persistent) { if (FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } /* re-populate with copied-on-write entry */ zend_hash_find(&phar_obj->arc.archive->manifest, oldfile, (uint) oldfile_len, (void**)&oldentry); } memcpy((void *) &newentry, oldentry, sizeof(phar_entry_info)); if (newentry.metadata) { zval *t; t = newentry.metadata; ALLOC_ZVAL(newentry.metadata); *newentry.metadata = *t; zval_copy_ctor(newentry.metadata); #if PHP_VERSION_ID < 50300 newentry.metadata->refcount = 1; #else Z_SET_REFCOUNT_P(newentry.metadata, 1); #endif newentry.metadata_str.c = NULL; newentry.metadata_str.len = 0; } newentry.filename = estrndup(newfile, newfile_len); newentry.filename_len = newfile_len; newentry.fp_refcount = 0; if (oldentry->fp_type != PHAR_FP) { if (FAILURE == phar_copy_entry_fp(oldentry, &newentry, &error TSRMLS_CC)) { efree(newentry.filename); php_stream_close(newentry.fp); zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); return; } } zend_hash_add(&oldentry->phar->manifest, newfile, newfile_len, (void*)&newentry, sizeof(phar_entry_info), NULL); phar_obj->arc.archive->is_modified = 1; phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } RETURN_TRUE; } /* }}} */ /* {{{ proto int Phar::offsetExists(string entry) * determines whether a file exists in the phar */ PHP_METHOD(Phar, offsetExists) { char *fname; int fname_len; phar_entry_info *entry; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &fname, &fname_len) == FAILURE) { return; } if (zend_hash_exists(&phar_obj->arc.archive->manifest, fname, (uint) fname_len)) { if (SUCCESS == zend_hash_find(&phar_obj->arc.archive->manifest, fname, (uint) fname_len, (void**)&entry)) { if (entry->is_deleted) { /* entry is deleted, but has not been flushed to disk yet */ RETURN_FALSE; } } if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) { /* none of these are real files, so they don't exist */ RETURN_FALSE; } RETURN_TRUE; } else { if (zend_hash_exists(&phar_obj->arc.archive->virtual_dirs, fname, (uint) fname_len)) { RETURN_TRUE; } RETURN_FALSE; } } /* }}} */ /* {{{ proto int Phar::offsetGet(string entry) * get a PharFileInfo object for a specific file */ PHP_METHOD(Phar, offsetGet) { char *fname, *error; int fname_len; zval *zfname; phar_entry_info *entry; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &fname, &fname_len) == FAILURE) { return; } /* security is 0 here so that we can get a better error message than "entry doesn't exist" */ if (!(entry = phar_get_entry_info_dir(phar_obj->arc.archive, fname, fname_len, 1, &error, 0 TSRMLS_CC))) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s does not exist%s%s", fname, error?", ":"", error?error:""); } else { if (fname_len == sizeof(".phar/stub.php")-1 && !memcmp(fname, ".phar/stub.php", sizeof(".phar/stub.php")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot get stub \".phar/stub.php\" directly in phar \"%s\", use getStub", phar_obj->arc.archive->fname); return; } if (fname_len == sizeof(".phar/alias.txt")-1 && !memcmp(fname, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot get alias \".phar/alias.txt\" directly in phar \"%s\", use getAlias", phar_obj->arc.archive->fname); return; } if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot directly get any files or directories in magic \".phar\" directory", phar_obj->arc.archive->fname); return; } if (entry->is_temp_dir) { efree(entry->filename); efree(entry); } fname_len = spprintf(&fname, 0, "phar://%s/%s", phar_obj->arc.archive->fname, fname); MAKE_STD_ZVAL(zfname); ZVAL_STRINGL(zfname, fname, fname_len, 0); spl_instantiate_arg_ex1(phar_obj->spl.info_class, &return_value, 0, zfname TSRMLS_CC); zval_ptr_dtor(&zfname); } } /* }}} */ /* {{{ add a file within the phar archive from a string or resource */ static void phar_add_file(phar_archive_data **pphar, char *filename, int filename_len, char *cont_str, int cont_len, zval *zresource TSRMLS_DC) { char *error; size_t contents_len; phar_entry_data *data; php_stream *contents_file; if (filename_len >= sizeof(".phar")-1 && !memcmp(filename, ".phar", sizeof(".phar")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot create any files in magic \".phar\" directory", (*pphar)->fname); return; } if (!(data = phar_get_or_create_entry_data((*pphar)->fname, (*pphar)->fname_len, filename, filename_len, "w+b", 0, &error, 1 TSRMLS_CC))) { if (error) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s does not exist and cannot be created: %s", filename, error); efree(error); } else { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s does not exist and cannot be created", filename); } return; } else { if (error) { efree(error); } if (!data->internal_file->is_dir) { if (cont_str) { contents_len = php_stream_write(data->fp, cont_str, cont_len); if (contents_len != cont_len) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s could not be written to", filename); return; } } else { if (!(php_stream_from_zval_no_verify(contents_file, &zresource))) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s could not be written to", filename); return; } phar_stream_copy_to_stream(contents_file, data->fp, PHP_STREAM_COPY_ALL, &contents_len); } data->internal_file->compressed_filesize = data->internal_file->uncompressed_filesize = contents_len; } /* check for copy-on-write */ if (pphar[0] != data->phar) { *pphar = data->phar; } phar_entry_delref(data TSRMLS_CC); phar_flush(*pphar, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } } } /* }}} */ /* {{{ create a directory within the phar archive */ static void phar_mkdir(phar_archive_data **pphar, char *dirname, int dirname_len TSRMLS_DC) { char *error; phar_entry_data *data; if (!(data = phar_get_or_create_entry_data((*pphar)->fname, (*pphar)->fname_len, dirname, dirname_len, "w+b", 2, &error, 1 TSRMLS_CC))) { if (error) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Directory %s does not exist and cannot be created: %s", dirname, error); efree(error); } else { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Directory %s does not exist and cannot be created", dirname); } return; } else { if (error) { efree(error); } /* check for copy on write */ if (data->phar != *pphar) { *pphar = data->phar; } phar_entry_delref(data TSRMLS_CC); phar_flush(*pphar, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } } } /* }}} */ /* {{{ proto int Phar::offsetSet(string entry, string value) * set the contents of an internal file to those of an external file */ PHP_METHOD(Phar, offsetSet) { char *fname, *cont_str = NULL; int fname_len, cont_len; zval *zresource; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Write operations disabled by the php.ini setting phar.readonly"); return; } if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "sr", &fname, &fname_len, &zresource) == FAILURE && zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &fname, &fname_len, &cont_str, &cont_len) == FAILURE) { return; } if (fname_len == sizeof(".phar/stub.php")-1 && !memcmp(fname, ".phar/stub.php", sizeof(".phar/stub.php")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot set stub \".phar/stub.php\" directly in phar \"%s\", use setStub", phar_obj->arc.archive->fname); return; } if (fname_len == sizeof(".phar/alias.txt")-1 && !memcmp(fname, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot set alias \".phar/alias.txt\" directly in phar \"%s\", use setAlias", phar_obj->arc.archive->fname); return; } if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot set any files or directories in magic \".phar\" directory", phar_obj->arc.archive->fname); return; } phar_add_file(&(phar_obj->arc.archive), fname, fname_len, cont_str, cont_len, zresource TSRMLS_CC); } /* }}} */ /* {{{ proto int Phar::offsetUnset(string entry) * remove a file from a phar */ PHP_METHOD(Phar, offsetUnset) { char *fname, *error; int fname_len; phar_entry_info *entry; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Write operations disabled by the php.ini setting phar.readonly"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &fname, &fname_len) == FAILURE) { return; } if (zend_hash_exists(&phar_obj->arc.archive->manifest, fname, (uint) fname_len)) { if (SUCCESS == zend_hash_find(&phar_obj->arc.archive->manifest, fname, (uint) fname_len, (void**)&entry)) { if (entry->is_deleted) { /* entry is deleted, but has not been flushed to disk yet */ return; } if (phar_obj->arc.archive->is_persistent) { if (FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } /* re-populate entry after copy on write */ zend_hash_find(&phar_obj->arc.archive->manifest, fname, (uint) fname_len, (void **)&entry); } entry->is_modified = 0; entry->is_deleted = 1; /* we need to "flush" the stream to save the newly deleted file on disk */ phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } RETURN_TRUE; } } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto string Phar::addEmptyDir(string dirname) * Adds an empty directory to the phar archive */ PHP_METHOD(Phar, addEmptyDir) { char *dirname; int dirname_len; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &dirname, &dirname_len) == FAILURE) { return; } if (dirname_len >= sizeof(".phar")-1 && !memcmp(dirname, ".phar", sizeof(".phar")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot create a directory in magic \".phar\" directory"); return; } phar_mkdir(&phar_obj->arc.archive, dirname, dirname_len TSRMLS_CC); } /* }}} */ /* {{{ proto string Phar::addFile(string filename[, string localname]) * Adds a file to the archive using the filename, or the second parameter as the name within the archive */ PHP_METHOD(Phar, addFile) { char *fname, *localname = NULL; int fname_len, localname_len = 0; php_stream *resource; zval *zresource; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &fname, &fname_len, &localname, &localname_len) == FAILURE) { return; } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "phar error: unable to open file \"%s\" to add to phar archive, safe_mode restrictions prevent this", fname); return; } #endif if (!strstr(fname, "://") && php_check_open_basedir(fname TSRMLS_CC)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "phar error: unable to open file \"%s\" to add to phar archive, open_basedir restrictions prevent this", fname); return; } if (!(resource = php_stream_open_wrapper(fname, "rb", 0, NULL))) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "phar error: unable to open file \"%s\" to add to phar archive", fname); return; } if (localname) { fname = localname; fname_len = localname_len; } MAKE_STD_ZVAL(zresource); php_stream_to_zval(resource, zresource); phar_add_file(&(phar_obj->arc.archive), fname, fname_len, NULL, 0, zresource TSRMLS_CC); efree(zresource); php_stream_close(resource); } /* }}} */ /* {{{ proto string Phar::addFromString(string localname, string contents) * Adds a file to the archive using its contents as a string */ PHP_METHOD(Phar, addFromString) { char *localname, *cont_str; int localname_len, cont_len; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &localname, &localname_len, &cont_str, &cont_len) == FAILURE) { return; } phar_add_file(&(phar_obj->arc.archive), localname, localname_len, cont_str, cont_len, NULL TSRMLS_CC); } /* }}} */ /* {{{ proto string Phar::getStub() * Returns the stub at the head of a phar archive as a string. */ PHP_METHOD(Phar, getStub) { size_t len; char *buf; php_stream *fp; php_stream_filter *filter = NULL; phar_entry_info *stub; PHAR_ARCHIVE_OBJECT(); if (phar_obj->arc.archive->is_tar || phar_obj->arc.archive->is_zip) { if (SUCCESS == zend_hash_find(&(phar_obj->arc.archive->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1, (void **)&stub)) { if (phar_obj->arc.archive->fp && !phar_obj->arc.archive->is_brandnew && !(stub->flags & PHAR_ENT_COMPRESSION_MASK)) { fp = phar_obj->arc.archive->fp; } else { fp = php_stream_open_wrapper(phar_obj->arc.archive->fname, "rb", 0, NULL); if (stub->flags & PHAR_ENT_COMPRESSION_MASK) { char *filter_name; if ((filter_name = phar_decompress_filter(stub, 0)) != NULL) { filter = php_stream_filter_create(filter_name, NULL, php_stream_is_persistent(fp) TSRMLS_CC); } else { filter = NULL; } if (!filter) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "phar error: unable to read stub of phar \"%s\" (cannot create %s filter)", phar_obj->arc.archive->fname, phar_decompress_filter(stub, 1)); return; } php_stream_filter_append(&fp->readfilters, filter); } } if (!fp) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Unable to read stub"); return; } php_stream_seek(fp, stub->offset_abs, SEEK_SET); len = stub->uncompressed_filesize; goto carry_on; } else { RETURN_STRINGL("", 0, 1); } } len = phar_obj->arc.archive->halt_offset; if (phar_obj->arc.archive->fp && !phar_obj->arc.archive->is_brandnew) { fp = phar_obj->arc.archive->fp; } else { fp = php_stream_open_wrapper(phar_obj->arc.archive->fname, "rb", 0, NULL); } if (!fp) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Unable to read stub"); return; } php_stream_rewind(fp); carry_on: buf = safe_emalloc(len, 1, 1); if (len != php_stream_read(fp, buf, len)) { if (fp != phar_obj->arc.archive->fp) { php_stream_close(fp); } zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Unable to read stub"); efree(buf); return; } if (filter) { php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); } if (fp != phar_obj->arc.archive->fp) { php_stream_close(fp); } buf[len] = '\0'; RETURN_STRINGL(buf, len, 0); } /* }}}*/ /* {{{ proto int Phar::hasMetaData() * Returns TRUE if the phar has global metadata, FALSE otherwise. */ PHP_METHOD(Phar, hasMetadata) { PHAR_ARCHIVE_OBJECT(); RETURN_BOOL(phar_obj->arc.archive->metadata != NULL); } /* }}} */ /* {{{ proto int Phar::getMetaData() * Returns the global metadata of the phar */ PHP_METHOD(Phar, getMetadata) { PHAR_ARCHIVE_OBJECT(); if (phar_obj->arc.archive->metadata) { if (phar_obj->arc.archive->is_persistent) { zval *ret; char *buf = estrndup((char *) phar_obj->arc.archive->metadata, phar_obj->arc.archive->metadata_len); /* assume success, we would have failed before */ phar_parse_metadata(&buf, &ret, phar_obj->arc.archive->metadata_len TSRMLS_CC); efree(buf); RETURN_ZVAL(ret, 0, 1); } RETURN_ZVAL(phar_obj->arc.archive->metadata, 1, 0); } } /* }}} */ /* {{{ proto int Phar::setMetaData(mixed $metadata) * Sets the global metadata of the phar */ PHP_METHOD(Phar, setMetadata) { char *error; zval *metadata; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Write operations disabled by the php.ini setting phar.readonly"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &metadata) == FAILURE) { return; } if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } if (phar_obj->arc.archive->metadata) { zval_ptr_dtor(&phar_obj->arc.archive->metadata); phar_obj->arc.archive->metadata = NULL; } MAKE_STD_ZVAL(phar_obj->arc.archive->metadata); ZVAL_ZVAL(phar_obj->arc.archive->metadata, metadata, 1, 0); phar_obj->arc.archive->is_modified = 1; phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } } /* }}} */ /* {{{ proto int Phar::delMetadata() * Deletes the global metadata of the phar */ PHP_METHOD(Phar, delMetadata) { char *error; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Write operations disabled by the php.ini setting phar.readonly"); return; } if (phar_obj->arc.archive->metadata) { zval_ptr_dtor(&phar_obj->arc.archive->metadata); phar_obj->arc.archive->metadata = NULL; phar_obj->arc.archive->is_modified = 1; phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); RETURN_FALSE; } else { RETURN_TRUE; } } else { RETURN_TRUE; } } /* }}} */ #if PHP_API_VERSION < 20100412 #define PHAR_OPENBASEDIR_CHECKPATH(filename) \ (PG(safe_mode) && (!php_checkuid(filename, NULL, CHECKUID_CHECK_FILE_AND_DIR))) || php_check_open_basedir(filename TSRMLS_CC) #else #define PHAR_OPENBASEDIR_CHECKPATH(filename) \ php_check_open_basedir(filename TSRMLS_CC) #endif static int phar_extract_file(zend_bool overwrite, phar_entry_info *entry, char *dest, int dest_len, char **error TSRMLS_DC) /* {{{ */ { php_stream_statbuf ssb; int len; php_stream *fp; char *fullpath; const char *slash; mode_t mode; if (entry->is_mounted) { /* silently ignore mounted entries */ return SUCCESS; } if (entry->filename_len >= sizeof(".phar")-1 && !memcmp(entry->filename, ".phar", sizeof(".phar")-1)) { return SUCCESS; } len = spprintf(&fullpath, 0, "%s/%s", dest, entry->filename); if (len >= MAXPATHLEN) { char *tmp; /* truncate for error message */ fullpath[50] = '\0'; if (entry->filename_len > 50) { tmp = estrndup(entry->filename, 50); spprintf(error, 4096, "Cannot extract \"%s...\" to \"%s...\", extracted filename is too long for filesystem", tmp, fullpath); efree(tmp); } else { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s...\", extracted filename is too long for filesystem", entry->filename, fullpath); } efree(fullpath); return FAILURE; } if (!len) { spprintf(error, 4096, "Cannot extract \"%s\", internal error", entry->filename); efree(fullpath); return FAILURE; } if (PHAR_OPENBASEDIR_CHECKPATH(fullpath)) { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", openbasedir/safe mode restrictions in effect", entry->filename, fullpath); efree(fullpath); return FAILURE; } /* let see if the path already exists */ if (!overwrite && SUCCESS == php_stream_stat_path(fullpath, &ssb)) { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", path already exists", entry->filename, fullpath); efree(fullpath); return FAILURE; } /* perform dirname */ slash = zend_memrchr(entry->filename, '/', entry->filename_len); if (slash) { fullpath[dest_len + (slash - entry->filename) + 1] = '\0'; } else { fullpath[dest_len] = '\0'; } if (FAILURE == php_stream_stat_path(fullpath, &ssb)) { if (entry->is_dir) { if (!php_stream_mkdir(fullpath, entry->flags & PHAR_ENT_PERM_MASK, PHP_STREAM_MKDIR_RECURSIVE, NULL)) { spprintf(error, 4096, "Cannot extract \"%s\", could not create directory \"%s\"", entry->filename, fullpath); efree(fullpath); return FAILURE; } } else { if (!php_stream_mkdir(fullpath, 0777, PHP_STREAM_MKDIR_RECURSIVE, NULL)) { spprintf(error, 4096, "Cannot extract \"%s\", could not create directory \"%s\"", entry->filename, fullpath); efree(fullpath); return FAILURE; } } } if (slash) { fullpath[dest_len + (slash - entry->filename) + 1] = '/'; } else { fullpath[dest_len] = '/'; } /* it is a standalone directory, job done */ if (entry->is_dir) { efree(fullpath); return SUCCESS; } #if PHP_API_VERSION < 20100412 fp = php_stream_open_wrapper(fullpath, "w+b", REPORT_ERRORS|ENFORCE_SAFE_MODE, NULL); #else fp = php_stream_open_wrapper(fullpath, "w+b", REPORT_ERRORS, NULL); #endif if (!fp) { spprintf(error, 4096, "Cannot extract \"%s\", could not open for writing \"%s\"", entry->filename, fullpath); efree(fullpath); return FAILURE; } if (!phar_get_efp(entry, 0 TSRMLS_CC)) { if (FAILURE == phar_open_entry_fp(entry, error, 1 TSRMLS_CC)) { if (error) { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", unable to open internal file pointer: %s", entry->filename, fullpath, *error); } else { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", unable to open internal file pointer", entry->filename, fullpath); } efree(fullpath); php_stream_close(fp); return FAILURE; } } if (FAILURE == phar_seek_efp(entry, 0, SEEK_SET, 0, 0 TSRMLS_CC)) { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", unable to seek internal file pointer", entry->filename, fullpath); efree(fullpath); php_stream_close(fp); return FAILURE; } if (SUCCESS != phar_stream_copy_to_stream(phar_get_efp(entry, 0 TSRMLS_CC), fp, entry->uncompressed_filesize, NULL)) { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", copying contents failed", entry->filename, fullpath); efree(fullpath); php_stream_close(fp); return FAILURE; } php_stream_close(fp); mode = (mode_t) entry->flags & PHAR_ENT_PERM_MASK; if (FAILURE == VCWD_CHMOD(fullpath, mode)) { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", setting file permissions failed", entry->filename, fullpath); efree(fullpath); return FAILURE; } efree(fullpath); return SUCCESS; } /* }}} */ /* {{{ proto bool Phar::extractTo(string pathto[[, mixed files], bool overwrite]) * Extract one or more file from a phar archive, optionally overwriting existing files */ PHP_METHOD(Phar, extractTo) { char *error = NULL; php_stream *fp; php_stream_statbuf ssb; phar_entry_info *entry; char *pathto, *filename, *actual; int pathto_len, filename_len; int ret, i; int nelems; zval *zval_files = NULL; zend_bool overwrite = 0; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|z!b", &pathto, &pathto_len, &zval_files, &overwrite) == FAILURE) { return; } fp = php_stream_open_wrapper(phar_obj->arc.archive->fname, "rb", IGNORE_URL|STREAM_MUST_SEEK, &actual); if (!fp) { zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0 TSRMLS_CC, "Invalid argument, %s cannot be found", phar_obj->arc.archive->fname); return; } efree(actual); php_stream_close(fp); if (pathto_len < 1) { zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0 TSRMLS_CC, "Invalid argument, extraction path must be non-zero length"); return; } if (pathto_len >= MAXPATHLEN) { char *tmp = estrndup(pathto, 50); /* truncate for error message */ zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0 TSRMLS_CC, "Cannot extract to \"%s...\", destination directory is too long for filesystem", tmp); efree(tmp); return; } if (php_stream_stat_path(pathto, &ssb) < 0) { ret = php_stream_mkdir(pathto, 0777, PHP_STREAM_MKDIR_RECURSIVE, NULL); if (!ret) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Unable to create path \"%s\" for extraction", pathto); return; } } else if (!(ssb.sb.st_mode & S_IFDIR)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Unable to use path \"%s\" for extraction, it is a file, must be a directory", pathto); return; } if (zval_files) { switch (Z_TYPE_P(zval_files)) { case IS_NULL: goto all_files; #if PHP_VERSION_ID >= 60000 case IS_UNICODE: zval_unicode_to_string(zval_files TSRMLS_CC); /* break intentionally omitted */ #endif case IS_STRING: filename = Z_STRVAL_P(zval_files); filename_len = Z_STRLEN_P(zval_files); break; case IS_ARRAY: nelems = zend_hash_num_elements(Z_ARRVAL_P(zval_files)); if (nelems == 0 ) { RETURN_FALSE; } for (i = 0; i < nelems; i++) { zval **zval_file; if (zend_hash_index_find(Z_ARRVAL_P(zval_files), i, (void **) &zval_file) == SUCCESS) { switch (Z_TYPE_PP(zval_file)) { #if PHP_VERSION_ID >= 60000 case IS_UNICODE: zval_unicode_to_string(*(zval_file) TSRMLS_CC); /* break intentionally omitted */ #endif case IS_STRING: break; default: zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0 TSRMLS_CC, "Invalid argument, array of filenames to extract contains non-string value"); return; } if (FAILURE == zend_hash_find(&phar_obj->arc.archive->manifest, Z_STRVAL_PP(zval_file), Z_STRLEN_PP(zval_file), (void **)&entry)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Phar Error: attempted to extract non-existent file \"%s\" from phar \"%s\"", Z_STRVAL_PP(zval_file), phar_obj->arc.archive->fname); } if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, &error TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Extraction from phar \"%s\" failed: %s", phar_obj->arc.archive->fname, error); efree(error); return; } } } RETURN_TRUE; default: zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0 TSRMLS_CC, "Invalid argument, expected a filename (string) or array of filenames"); return; } if (FAILURE == zend_hash_find(&phar_obj->arc.archive->manifest, filename, filename_len, (void **)&entry)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Phar Error: attempted to extract non-existent file \"%s\" from phar \"%s\"", filename, phar_obj->arc.archive->fname); return; } if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, &error TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Extraction from phar \"%s\" failed: %s", phar_obj->arc.archive->fname, error); efree(error); return; } } else { phar_archive_data *phar; all_files: phar = phar_obj->arc.archive; /* Extract all files */ if (!zend_hash_num_elements(&(phar->manifest))) { RETURN_TRUE; } for (zend_hash_internal_pointer_reset(&phar->manifest); zend_hash_has_more_elements(&phar->manifest) == SUCCESS; zend_hash_move_forward(&phar->manifest)) { if (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) { continue; } if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, &error TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Extraction from phar \"%s\" failed: %s", phar->fname, error); efree(error); return; } } } RETURN_TRUE; } /* }}} */ /* {{{ proto void PharFileInfo::__construct(string entry) * Construct a Phar entry object */ PHP_METHOD(PharFileInfo, __construct) { char *fname, *arch, *entry, *error; int fname_len, arch_len, entry_len; phar_entry_object *entry_obj; phar_entry_info *entry_info; phar_archive_data *phar_data; zval *zobj = getThis(), arg1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &fname, &fname_len) == FAILURE) { return; } entry_obj = (phar_entry_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (entry_obj->ent.entry) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot call constructor twice"); return; } if (fname_len < 7 || memcmp(fname, "phar://", 7) || phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0 TSRMLS_CC) == FAILURE) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "'%s' is not a valid phar archive URL (must have at least phar://filename.phar)", fname); return; } if (phar_open_from_filename(arch, arch_len, NULL, 0, REPORT_ERRORS, &phar_data, &error TSRMLS_CC) == FAILURE) { efree(arch); efree(entry); if (error) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot open phar file '%s': %s", fname, error); efree(error); } else { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot open phar file '%s'", fname); } return; } if ((entry_info = phar_get_entry_info_dir(phar_data, entry, entry_len, 1, &error, 1 TSRMLS_CC)) == NULL) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot access phar file entry '%s' in archive '%s'%s%s", entry, arch, error ? ", " : "", error ? error : ""); efree(arch); efree(entry); return; } efree(arch); efree(entry); entry_obj->ent.entry = entry_info; INIT_PZVAL(&arg1); ZVAL_STRINGL(&arg1, fname, fname_len, 0); zend_call_method_with_1_params(&zobj, Z_OBJCE_P(zobj), &spl_ce_SplFileInfo->constructor, "__construct", NULL, &arg1); } /* }}} */ #define PHAR_ENTRY_OBJECT() \ phar_entry_object *entry_obj = (phar_entry_object*)zend_object_store_get_object(getThis() TSRMLS_CC); \ if (!entry_obj->ent.entry) { \ zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \ "Cannot call method on an uninitialized PharFileInfo object"); \ return; \ } /* {{{ proto void PharFileInfo::__destruct() * clean up directory-based entry objects */ PHP_METHOD(PharFileInfo, __destruct) { phar_entry_object *entry_obj = (phar_entry_object*)zend_object_store_get_object(getThis() TSRMLS_CC); \ if (entry_obj->ent.entry && entry_obj->ent.entry->is_temp_dir) { if (entry_obj->ent.entry->filename) { efree(entry_obj->ent.entry->filename); entry_obj->ent.entry->filename = NULL; } efree(entry_obj->ent.entry); entry_obj->ent.entry = NULL; } } /* }}} */ /* {{{ proto int PharFileInfo::getCompressedSize() * Returns the compressed size */ PHP_METHOD(PharFileInfo, getCompressedSize) { PHAR_ENTRY_OBJECT(); RETURN_LONG(entry_obj->ent.entry->compressed_filesize); } /* }}} */ /* {{{ proto bool PharFileInfo::isCompressed([int compression_type]) * Returns whether the entry is compressed, and whether it is compressed with Phar::GZ or Phar::BZ2 if specified */ PHP_METHOD(PharFileInfo, isCompressed) { /* a number that is not Phar::GZ or Phar::BZ2 */ long method = 9021976; PHAR_ENTRY_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &method) == FAILURE) { return; } switch (method) { case 9021976: RETURN_BOOL(entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSION_MASK); case PHAR_ENT_COMPRESSED_GZ: RETURN_BOOL(entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSED_GZ); case PHAR_ENT_COMPRESSED_BZ2: RETURN_BOOL(entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSED_BZ2); default: zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \ "Unknown compression type specified"); \ } } /* }}} */ /* {{{ proto int PharFileInfo::getCRC32() * Returns CRC32 code or throws an exception if not CRC checked */ PHP_METHOD(PharFileInfo, getCRC32) { PHAR_ENTRY_OBJECT(); if (entry_obj->ent.entry->is_dir) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \ "Phar entry is a directory, does not have a CRC"); \ return; } if (entry_obj->ent.entry->is_crc_checked) { RETURN_LONG(entry_obj->ent.entry->crc32); } else { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \ "Phar entry was not CRC checked"); \ } } /* }}} */ /* {{{ proto int PharFileInfo::isCRCChecked() * Returns whether file entry is CRC checked */ PHP_METHOD(PharFileInfo, isCRCChecked) { PHAR_ENTRY_OBJECT(); RETURN_BOOL(entry_obj->ent.entry->is_crc_checked); } /* }}} */ /* {{{ proto int PharFileInfo::getPharFlags() * Returns the Phar file entry flags */ PHP_METHOD(PharFileInfo, getPharFlags) { PHAR_ENTRY_OBJECT(); RETURN_LONG(entry_obj->ent.entry->flags & ~(PHAR_ENT_PERM_MASK|PHAR_ENT_COMPRESSION_MASK)); } /* }}} */ /* {{{ proto int PharFileInfo::chmod() * set the file permissions for the Phar. This only allows setting execution bit, read/write */ PHP_METHOD(PharFileInfo, chmod) { char *error; long perms; PHAR_ENTRY_OBJECT(); if (entry_obj->ent.entry->is_temp_dir) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \ "Phar entry \"%s\" is a temporary directory (not an actual entry in the archive), cannot chmod", entry_obj->ent.entry->filename); \ return; } if (PHAR_G(readonly) && !entry_obj->ent.entry->phar->is_data) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Cannot modify permissions for file \"%s\" in phar \"%s\", write operations are prohibited", entry_obj->ent.entry->filename, entry_obj->ent.entry->phar->fname); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &perms) == FAILURE) { return; } if (entry_obj->ent.entry->is_persistent) { phar_archive_data *phar = entry_obj->ent.entry->phar; if (FAILURE == phar_copy_on_write(&phar TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar->fname); return; } /* re-populate after copy-on-write */ zend_hash_find(&phar->manifest, entry_obj->ent.entry->filename, entry_obj->ent.entry->filename_len, (void **)&entry_obj->ent.entry); } /* clear permissions */ entry_obj->ent.entry->flags &= ~PHAR_ENT_PERM_MASK; perms &= 0777; entry_obj->ent.entry->flags |= perms; entry_obj->ent.entry->old_flags = entry_obj->ent.entry->flags; entry_obj->ent.entry->phar->is_modified = 1; entry_obj->ent.entry->is_modified = 1; /* hackish cache in php_stat needs to be cleared */ /* if this code fails to work, check main/streams/streams.c, _php_stream_stat_path */ if (BG(CurrentLStatFile)) { efree(BG(CurrentLStatFile)); } if (BG(CurrentStatFile)) { efree(BG(CurrentStatFile)); } BG(CurrentLStatFile) = NULL; BG(CurrentStatFile) = NULL; phar_flush(entry_obj->ent.entry->phar, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } } /* }}} */ /* {{{ proto int PharFileInfo::hasMetaData() * Returns the metadata of the entry */ PHP_METHOD(PharFileInfo, hasMetadata) { PHAR_ENTRY_OBJECT(); RETURN_BOOL(entry_obj->ent.entry->metadata != NULL); } /* }}} */ /* {{{ proto int PharFileInfo::getMetaData() * Returns the metadata of the entry */ PHP_METHOD(PharFileInfo, getMetadata) { PHAR_ENTRY_OBJECT(); if (entry_obj->ent.entry->metadata) { if (entry_obj->ent.entry->is_persistent) { zval *ret; char *buf = estrndup((char *) entry_obj->ent.entry->metadata, entry_obj->ent.entry->metadata_len); /* assume success, we would have failed before */ phar_parse_metadata(&buf, &ret, entry_obj->ent.entry->metadata_len TSRMLS_CC); efree(buf); RETURN_ZVAL(ret, 0, 1); } RETURN_ZVAL(entry_obj->ent.entry->metadata, 1, 0); } } /* }}} */ /* {{{ proto int PharFileInfo::setMetaData(mixed $metadata) * Sets the metadata of the entry */ PHP_METHOD(PharFileInfo, setMetadata) { char *error; zval *metadata; PHAR_ENTRY_OBJECT(); if (PHAR_G(readonly) && !entry_obj->ent.entry->phar->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Write operations disabled by the php.ini setting phar.readonly"); return; } if (entry_obj->ent.entry->is_temp_dir) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \ "Phar entry is a temporary directory (not an actual entry in the archive), cannot set metadata"); \ return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &metadata) == FAILURE) { return; } if (entry_obj->ent.entry->is_persistent) { phar_archive_data *phar = entry_obj->ent.entry->phar; if (FAILURE == phar_copy_on_write(&phar TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar->fname); return; } /* re-populate after copy-on-write */ zend_hash_find(&phar->manifest, entry_obj->ent.entry->filename, entry_obj->ent.entry->filename_len, (void **)&entry_obj->ent.entry); } if (entry_obj->ent.entry->metadata) { zval_ptr_dtor(&entry_obj->ent.entry->metadata); entry_obj->ent.entry->metadata = NULL; } MAKE_STD_ZVAL(entry_obj->ent.entry->metadata); ZVAL_ZVAL(entry_obj->ent.entry->metadata, metadata, 1, 0); entry_obj->ent.entry->is_modified = 1; entry_obj->ent.entry->phar->is_modified = 1; phar_flush(entry_obj->ent.entry->phar, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } } /* }}} */ /* {{{ proto bool PharFileInfo::delMetaData() * Deletes the metadata of the entry */ PHP_METHOD(PharFileInfo, delMetadata) { char *error; PHAR_ENTRY_OBJECT(); if (PHAR_G(readonly) && !entry_obj->ent.entry->phar->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Write operations disabled by the php.ini setting phar.readonly"); return; } if (entry_obj->ent.entry->is_temp_dir) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \ "Phar entry is a temporary directory (not an actual entry in the archive), cannot delete metadata"); \ return; } if (entry_obj->ent.entry->metadata) { if (entry_obj->ent.entry->is_persistent) { phar_archive_data *phar = entry_obj->ent.entry->phar; if (FAILURE == phar_copy_on_write(&phar TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar->fname); return; } /* re-populate after copy-on-write */ zend_hash_find(&phar->manifest, entry_obj->ent.entry->filename, entry_obj->ent.entry->filename_len, (void **)&entry_obj->ent.entry); } zval_ptr_dtor(&entry_obj->ent.entry->metadata); entry_obj->ent.entry->metadata = NULL; entry_obj->ent.entry->is_modified = 1; entry_obj->ent.entry->phar->is_modified = 1; phar_flush(entry_obj->ent.entry->phar, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); RETURN_FALSE; } else { RETURN_TRUE; } } else { RETURN_TRUE; } } /* }}} */ /* {{{ proto string PharFileInfo::getContent() * return the complete file contents of the entry (like file_get_contents) */ PHP_METHOD(PharFileInfo, getContent) { char *error; php_stream *fp; phar_entry_info *link; PHAR_ENTRY_OBJECT(); if (entry_obj->ent.entry->is_dir) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Phar error: Cannot retrieve contents, \"%s\" in phar \"%s\" is a directory", entry_obj->ent.entry->filename, entry_obj->ent.entry->phar->fname); return; } link = phar_get_link_source(entry_obj->ent.entry TSRMLS_CC); if (!link) { link = entry_obj->ent.entry; } if (SUCCESS != phar_open_entry_fp(link, &error, 0 TSRMLS_CC)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Phar error: Cannot retrieve contents, \"%s\" in phar \"%s\": %s", entry_obj->ent.entry->filename, entry_obj->ent.entry->phar->fname, error); efree(error); return; } if (!(fp = phar_get_efp(link, 0 TSRMLS_CC))) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Phar error: Cannot retrieve contents of \"%s\" in phar \"%s\"", entry_obj->ent.entry->filename, entry_obj->ent.entry->phar->fname); return; } phar_seek_efp(link, 0, SEEK_SET, 0, 0 TSRMLS_CC); Z_TYPE_P(return_value) = IS_STRING; #if PHP_MAJOR_VERSION >= 6 Z_STRLEN_P(return_value) = php_stream_copy_to_mem(fp, (void **) &(Z_STRVAL_P(return_value)), link->uncompressed_filesize, 0); #else Z_STRLEN_P(return_value) = php_stream_copy_to_mem(fp, &(Z_STRVAL_P(return_value)), link->uncompressed_filesize, 0); #endif if (!Z_STRVAL_P(return_value)) { Z_STRVAL_P(return_value) = estrndup("", 0); } } /* }}} */ /* {{{ proto int PharFileInfo::compress(int compression_type) * Instructs the Phar class to compress the current file using zlib or bzip2 compression */ PHP_METHOD(PharFileInfo, compress) { long method; char *error; PHAR_ENTRY_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &method) == FAILURE) { return; } if (entry_obj->ent.entry->is_tar) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress with Gzip compression, not possible with tar-based phar archives"); return; } if (entry_obj->ent.entry->is_dir) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \ "Phar entry is a directory, cannot set compression"); \ return; } if (PHAR_G(readonly) && !entry_obj->ent.entry->phar->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Phar is readonly, cannot change compression"); return; } if (entry_obj->ent.entry->is_deleted) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress deleted file"); return; } if (entry_obj->ent.entry->is_persistent) { phar_archive_data *phar = entry_obj->ent.entry->phar; if (FAILURE == phar_copy_on_write(&phar TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar->fname); return; } /* re-populate after copy-on-write */ zend_hash_find(&phar->manifest, entry_obj->ent.entry->filename, entry_obj->ent.entry->filename_len, (void **)&entry_obj->ent.entry); } switch (method) { case PHAR_ENT_COMPRESSED_GZ: if (entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSED_GZ) { RETURN_TRUE; } if ((entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSED_BZ2) != 0) { if (!PHAR_G(has_bz2)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress with gzip compression, file is already compressed with bzip2 compression and bz2 extension is not enabled, cannot decompress"); return; } /* decompress this file indirectly */ if (SUCCESS != phar_open_entry_fp(entry_obj->ent.entry, &error, 1 TSRMLS_CC)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Phar error: Cannot decompress bzip2-compressed file \"%s\" in phar \"%s\" in order to compress with gzip: %s", entry_obj->ent.entry->filename, entry_obj->ent.entry->phar->fname, error); efree(error); return; } } if (!PHAR_G(has_zlib)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress with gzip compression, zlib extension is not enabled"); return; } entry_obj->ent.entry->old_flags = entry_obj->ent.entry->flags; entry_obj->ent.entry->flags &= ~PHAR_ENT_COMPRESSION_MASK; entry_obj->ent.entry->flags |= PHAR_ENT_COMPRESSED_GZ; break; case PHAR_ENT_COMPRESSED_BZ2: if (entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSED_BZ2) { RETURN_TRUE; } if ((entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSED_GZ) != 0) { if (!PHAR_G(has_zlib)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress with bzip2 compression, file is already compressed with gzip compression and zlib extension is not enabled, cannot decompress"); return; } /* decompress this file indirectly */ if (SUCCESS != phar_open_entry_fp(entry_obj->ent.entry, &error, 1 TSRMLS_CC)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Phar error: Cannot decompress gzip-compressed file \"%s\" in phar \"%s\" in order to compress with bzip2: %s", entry_obj->ent.entry->filename, entry_obj->ent.entry->phar->fname, error); efree(error); return; } } if (!PHAR_G(has_bz2)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress with bzip2 compression, bz2 extension is not enabled"); return; } entry_obj->ent.entry->old_flags = entry_obj->ent.entry->flags; entry_obj->ent.entry->flags &= ~PHAR_ENT_COMPRESSION_MASK; entry_obj->ent.entry->flags |= PHAR_ENT_COMPRESSED_BZ2; break; default: zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \ "Unknown compression type specified"); \ } entry_obj->ent.entry->phar->is_modified = 1; entry_obj->ent.entry->is_modified = 1; phar_flush(entry_obj->ent.entry->phar, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } RETURN_TRUE; } /* }}} */ /* {{{ proto int PharFileInfo::decompress() * Instructs the Phar class to decompress the current file */ PHP_METHOD(PharFileInfo, decompress) { char *error; PHAR_ENTRY_OBJECT(); if (entry_obj->ent.entry->is_dir) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \ "Phar entry is a directory, cannot set compression"); \ return; } if ((entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSION_MASK) == 0) { RETURN_TRUE; } if (PHAR_G(readonly) && !entry_obj->ent.entry->phar->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Phar is readonly, cannot decompress"); return; } if (entry_obj->ent.entry->is_deleted) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress deleted file"); return; } if ((entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSED_GZ) != 0 && !PHAR_G(has_zlib)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot decompress Gzip-compressed file, zlib extension is not enabled"); return; } if ((entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSED_BZ2) != 0 && !PHAR_G(has_bz2)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot decompress Bzip2-compressed file, bz2 extension is not enabled"); return; } if (entry_obj->ent.entry->is_persistent) { phar_archive_data *phar = entry_obj->ent.entry->phar; if (FAILURE == phar_copy_on_write(&phar TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar->fname); return; } /* re-populate after copy-on-write */ zend_hash_find(&phar->manifest, entry_obj->ent.entry->filename, entry_obj->ent.entry->filename_len, (void **)&entry_obj->ent.entry); } if (!entry_obj->ent.entry->fp) { if (FAILURE == phar_open_archive_fp(entry_obj->ent.entry->phar TSRMLS_CC)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot decompress entry \"%s\", phar error: Cannot open phar archive \"%s\" for reading", entry_obj->ent.entry->filename, entry_obj->ent.entry->phar->fname); return; } entry_obj->ent.entry->fp_type = PHAR_FP; } entry_obj->ent.entry->old_flags = entry_obj->ent.entry->flags; entry_obj->ent.entry->flags &= ~PHAR_ENT_COMPRESSION_MASK; entry_obj->ent.entry->phar->is_modified = 1; entry_obj->ent.entry->is_modified = 1; phar_flush(entry_obj->ent.entry->phar, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } RETURN_TRUE; } /* }}} */ #endif /* HAVE_SPL */ /* {{{ phar methods */ PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar___construct, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, flags) ZEND_ARG_INFO(0, alias) ZEND_ARG_INFO(0, fileformat) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_createDS, 0, 0, 0) ZEND_ARG_INFO(0, index) ZEND_ARG_INFO(0, webindex) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_loadPhar, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, alias) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_mapPhar, 0, 0, 0) ZEND_ARG_INFO(0, alias) ZEND_ARG_INFO(0, offset) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_mount, 0, 0, 2) ZEND_ARG_INFO(0, inphar) ZEND_ARG_INFO(0, externalfile) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_mungServer, 0, 0, 1) ZEND_ARG_INFO(0, munglist) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_webPhar, 0, 0, 0) ZEND_ARG_INFO(0, alias) ZEND_ARG_INFO(0, index) ZEND_ARG_INFO(0, f404) ZEND_ARG_INFO(0, mimetypes) ZEND_ARG_INFO(0, rewrites) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_running, 0, 0, 1) ZEND_ARG_INFO(0, retphar) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_ua, 0, 0, 1) ZEND_ARG_INFO(0, archive) ZEND_END_ARG_INFO() #if HAVE_SPL PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_build, 0, 0, 1) ZEND_ARG_INFO(0, iterator) ZEND_ARG_INFO(0, base_directory) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_conv, 0, 0, 0) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, compression_type) ZEND_ARG_INFO(0, file_ext) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_comps, 0, 0, 1) ZEND_ARG_INFO(0, compression_type) ZEND_ARG_INFO(0, file_ext) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_decomp, 0, 0, 0) ZEND_ARG_INFO(0, file_ext) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_comp, 0, 0, 1) ZEND_ARG_INFO(0, compression_type) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_compo, 0, 0, 0) ZEND_ARG_INFO(0, compression_type) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_copy, 0, 0, 2) ZEND_ARG_INFO(0, newfile) ZEND_ARG_INFO(0, oldfile) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_delete, 0, 0, 1) ZEND_ARG_INFO(0, entry) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_fromdir, 0, 0, 1) ZEND_ARG_INFO(0, base_dir) ZEND_ARG_INFO(0, regex) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_offsetExists, 0, 0, 1) ZEND_ARG_INFO(0, entry) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_offsetSet, 0, 0, 2) ZEND_ARG_INFO(0, entry) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_setAlias, 0, 0, 1) ZEND_ARG_INFO(0, alias) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_setMetadata, 0, 0, 1) ZEND_ARG_INFO(0, metadata) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_setSigAlgo, 0, 0, 1) ZEND_ARG_INFO(0, algorithm) ZEND_ARG_INFO(0, privatekey) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_setStub, 0, 0, 1) ZEND_ARG_INFO(0, newstub) ZEND_ARG_INFO(0, maxlen) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_emptydir, 0, 0, 0) ZEND_ARG_INFO(0, dirname) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_extract, 0, 0, 1) ZEND_ARG_INFO(0, pathto) ZEND_ARG_INFO(0, files) ZEND_ARG_INFO(0, overwrite) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_addfile, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, localname) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_fromstring, 0, 0, 1) ZEND_ARG_INFO(0, localname) ZEND_ARG_INFO(0, contents) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_isff, 0, 0, 1) ZEND_ARG_INFO(0, fileformat) ZEND_END_ARG_INFO() #endif /* HAVE_SPL */ zend_function_entry php_archive_methods[] = { #if !HAVE_SPL PHP_ME(Phar, __construct, arginfo_phar___construct, ZEND_ACC_PRIVATE) #else PHP_ME(Phar, __construct, arginfo_phar___construct, ZEND_ACC_PUBLIC) PHP_ME(Phar, __destruct, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, addEmptyDir, arginfo_phar_emptydir, ZEND_ACC_PUBLIC) PHP_ME(Phar, addFile, arginfo_phar_addfile, ZEND_ACC_PUBLIC) PHP_ME(Phar, addFromString, arginfo_phar_fromstring, ZEND_ACC_PUBLIC) PHP_ME(Phar, buildFromDirectory, arginfo_phar_fromdir, ZEND_ACC_PUBLIC) PHP_ME(Phar, buildFromIterator, arginfo_phar_build, ZEND_ACC_PUBLIC) PHP_ME(Phar, compressFiles, arginfo_phar_comp, ZEND_ACC_PUBLIC) PHP_ME(Phar, decompressFiles, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, compress, arginfo_phar_comps, ZEND_ACC_PUBLIC) PHP_ME(Phar, decompress, arginfo_phar_decomp, ZEND_ACC_PUBLIC) PHP_ME(Phar, convertToExecutable, arginfo_phar_conv, ZEND_ACC_PUBLIC) PHP_ME(Phar, convertToData, arginfo_phar_conv, ZEND_ACC_PUBLIC) PHP_ME(Phar, copy, arginfo_phar_copy, ZEND_ACC_PUBLIC) PHP_ME(Phar, count, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, delete, arginfo_phar_delete, ZEND_ACC_PUBLIC) PHP_ME(Phar, delMetadata, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, extractTo, arginfo_phar_extract, ZEND_ACC_PUBLIC) PHP_ME(Phar, getAlias, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, getPath, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, getMetadata, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, getModified, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, getSignature, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, getStub, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, getVersion, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, hasMetadata, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, isBuffering, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, isCompressed, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, isFileFormat, arginfo_phar_isff, ZEND_ACC_PUBLIC) PHP_ME(Phar, isWritable, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, offsetExists, arginfo_phar_offsetExists, ZEND_ACC_PUBLIC) PHP_ME(Phar, offsetGet, arginfo_phar_offsetExists, ZEND_ACC_PUBLIC) PHP_ME(Phar, offsetSet, arginfo_phar_offsetSet, ZEND_ACC_PUBLIC) PHP_ME(Phar, offsetUnset, arginfo_phar_offsetExists, ZEND_ACC_PUBLIC) PHP_ME(Phar, setAlias, arginfo_phar_setAlias, ZEND_ACC_PUBLIC) PHP_ME(Phar, setDefaultStub, arginfo_phar_createDS, ZEND_ACC_PUBLIC) PHP_ME(Phar, setMetadata, arginfo_phar_setMetadata, ZEND_ACC_PUBLIC) PHP_ME(Phar, setSignatureAlgorithm, arginfo_phar_setSigAlgo, ZEND_ACC_PUBLIC) PHP_ME(Phar, setStub, arginfo_phar_setStub, ZEND_ACC_PUBLIC) PHP_ME(Phar, startBuffering, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, stopBuffering, NULL, ZEND_ACC_PUBLIC) #endif /* static member functions */ PHP_ME(Phar, apiVersion, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, canCompress, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, canWrite, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, createDefaultStub, arginfo_phar_createDS, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, getSupportedCompression,NULL, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, getSupportedSignatures,NULL, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, interceptFileFuncs, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, isValidPharFilename, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, loadPhar, arginfo_phar_loadPhar, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, mapPhar, arginfo_phar_mapPhar, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, running, arginfo_phar_running, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, mount, arginfo_phar_mount, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, mungServer, arginfo_phar_mungServer, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, unlinkArchive, arginfo_phar_ua, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, webPhar, arginfo_phar_webPhar, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) {NULL, NULL, NULL} }; #if HAVE_SPL PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_entry___construct, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_entry_chmod, 0, 0, 1) ZEND_ARG_INFO(0, perms) ZEND_END_ARG_INFO() zend_function_entry php_entry_methods[] = { PHP_ME(PharFileInfo, __construct, arginfo_entry___construct, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, __destruct, NULL, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, chmod, arginfo_entry_chmod, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, compress, arginfo_phar_comp, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, decompress, NULL, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, delMetadata, NULL, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, getCompressedSize, NULL, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, getCRC32, NULL, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, getContent, NULL, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, getMetadata, NULL, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, getPharFlags, NULL, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, hasMetadata, NULL, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, isCompressed, arginfo_phar_compo, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, isCRCChecked, NULL, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, setMetadata, arginfo_phar_setMetadata, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; #endif /* HAVE_SPL */ zend_function_entry phar_exception_methods[] = { {NULL, NULL, NULL} }; /* }}} */ #define REGISTER_PHAR_CLASS_CONST_LONG(class_name, const_name, value) \ zend_declare_class_constant_long(class_name, const_name, sizeof(const_name)-1, (long)value TSRMLS_CC); #if PHP_VERSION_ID < 50200 # define phar_exception_get_default() zend_exception_get_default() #else # define phar_exception_get_default() zend_exception_get_default(TSRMLS_C) #endif void phar_object_init(TSRMLS_D) /* {{{ */ { zend_class_entry ce; INIT_CLASS_ENTRY(ce, "PharException", phar_exception_methods); phar_ce_PharException = zend_register_internal_class_ex(&ce, phar_exception_get_default(), NULL TSRMLS_CC); #if HAVE_SPL INIT_CLASS_ENTRY(ce, "Phar", php_archive_methods); phar_ce_archive = zend_register_internal_class_ex(&ce, spl_ce_RecursiveDirectoryIterator, NULL TSRMLS_CC); zend_class_implements(phar_ce_archive TSRMLS_CC, 2, spl_ce_Countable, zend_ce_arrayaccess); INIT_CLASS_ENTRY(ce, "PharData", php_archive_methods); phar_ce_data = zend_register_internal_class_ex(&ce, spl_ce_RecursiveDirectoryIterator, NULL TSRMLS_CC); zend_class_implements(phar_ce_data TSRMLS_CC, 2, spl_ce_Countable, zend_ce_arrayaccess); INIT_CLASS_ENTRY(ce, "PharFileInfo", php_entry_methods); phar_ce_entry = zend_register_internal_class_ex(&ce, spl_ce_SplFileInfo, NULL TSRMLS_CC); #else INIT_CLASS_ENTRY(ce, "Phar", php_archive_methods); phar_ce_archive = zend_register_internal_class(&ce TSRMLS_CC); phar_ce_archive->ce_flags |= ZEND_ACC_FINAL_CLASS; INIT_CLASS_ENTRY(ce, "PharData", php_archive_methods); phar_ce_data = zend_register_internal_class(&ce TSRMLS_CC); phar_ce_data->ce_flags |= ZEND_ACC_FINAL_CLASS; #endif REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "BZ2", PHAR_ENT_COMPRESSED_BZ2) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "GZ", PHAR_ENT_COMPRESSED_GZ) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "NONE", PHAR_ENT_COMPRESSED_NONE) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "PHAR", PHAR_FORMAT_PHAR) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "TAR", PHAR_FORMAT_TAR) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "ZIP", PHAR_FORMAT_ZIP) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "COMPRESSED", PHAR_ENT_COMPRESSION_MASK) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "PHP", PHAR_MIME_PHP) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "PHPS", PHAR_MIME_PHPS) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "MD5", PHAR_SIG_MD5) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "OPENSSL", PHAR_SIG_OPENSSL) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "SHA1", PHAR_SIG_SHA1) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "SHA256", PHAR_SIG_SHA256) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "SHA512", PHAR_SIG_SHA512) } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | phar php single-file executable PHP extension | +----------------------------------------------------------------------+ | Copyright (c) 2005-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Gregory Beaver <[email protected]> | | Marcus Boerger <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "phar_internal.h" #include "func_interceptors.h" static zend_class_entry *phar_ce_archive; static zend_class_entry *phar_ce_data; static zend_class_entry *phar_ce_PharException; #if HAVE_SPL static zend_class_entry *phar_ce_entry; #endif #if PHP_MAJOR_VERSION > 5 || ((PHP_MAJOR_VERSION == 5) && (PHP_MINOR_VERSION >= 3)) # define PHAR_ARG_INFO #else # define PHAR_ARG_INFO static #endif static int phar_file_type(HashTable *mimes, char *file, char **mime_type TSRMLS_DC) /* {{{ */ { char *ext; phar_mime_type *mime; ext = strrchr(file, '.'); if (!ext) { *mime_type = "text/plain"; /* no file extension = assume text/plain */ return PHAR_MIME_OTHER; } ++ext; if (SUCCESS != zend_hash_find(mimes, ext, strlen(ext), (void **) &mime)) { *mime_type = "application/octet-stream"; return PHAR_MIME_OTHER; } *mime_type = mime->mime; return mime->type; } /* }}} */ static void phar_mung_server_vars(char *fname, char *entry, int entry_len, char *basename, int request_uri_len TSRMLS_DC) /* {{{ */ { #if PHP_MAJOR_VERSION >= 6 int is_unicode = 0; #endif HashTable *_SERVER; zval **stuff; char *path_info; int basename_len = strlen(basename); int code; zval *temp; /* "tweak" $_SERVER variables requested in earlier call to Phar::mungServer() */ if (!PG(http_globals)[TRACK_VARS_SERVER]) { return; } _SERVER = Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]); /* PATH_INFO and PATH_TRANSLATED should always be munged */ #if PHP_MAJOR_VERSION >= 6 if (phar_find_key(_SERVER, "PATH_INFO", sizeof("PATH_INFO"), (void **) &stuff TSRMLS_CC)) { if (Z_TYPE_PP(stuff) == IS_UNICODE) { is_unicode = 1; zval_unicode_to_string(*stuff TSRMLS_CC); } else { is_unicode = 0; } #else if (SUCCESS == zend_hash_find(_SERVER, "PATH_INFO", sizeof("PATH_INFO"), (void **) &stuff)) { #endif path_info = Z_STRVAL_PP(stuff); code = Z_STRLEN_PP(stuff); if (Z_STRLEN_PP(stuff) > entry_len && !memcmp(Z_STRVAL_PP(stuff), entry, entry_len)) { ZVAL_STRINGL(*stuff, Z_STRVAL_PP(stuff) + entry_len, request_uri_len, 1); MAKE_STD_ZVAL(temp); ZVAL_STRINGL(temp, path_info, code, 0); #if PHP_MAJOR_VERSION >= 6 if (is_unicode) { zval_string_to_unicode(*stuff TSRMLS_CC); } #endif zend_hash_update(_SERVER, "PHAR_PATH_INFO", sizeof("PHAR_PATH_INFO"), &temp, sizeof(zval **), NULL); } } #if PHP_MAJOR_VERSION >= 6 if (phar_find_key(_SERVER, "PATH_TRANSLATED", sizeof("PATH_TRANSLATED"), (void **) &stuff TSRMLS_CC)) { if (Z_TYPE_PP(stuff) == IS_UNICODE) { is_unicode = 1; zval_unicode_to_string(*stuff TSRMLS_CC); } else { is_unicode = 0; } #else if (SUCCESS == zend_hash_find(_SERVER, "PATH_TRANSLATED", sizeof("PATH_TRANSLATED"), (void **) &stuff)) { #endif path_info = Z_STRVAL_PP(stuff); code = Z_STRLEN_PP(stuff); Z_STRLEN_PP(stuff) = spprintf(&(Z_STRVAL_PP(stuff)), 4096, "phar://%s%s", fname, entry); MAKE_STD_ZVAL(temp); ZVAL_STRINGL(temp, path_info, code, 0); #if PHP_MAJOR_VERSION >= 6 if (is_unicode) { zval_string_to_unicode(*stuff TSRMLS_CC); } #endif zend_hash_update(_SERVER, "PHAR_PATH_TRANSLATED", sizeof("PHAR_PATH_TRANSLATED"), (void *) &temp, sizeof(zval **), NULL); } if (!PHAR_GLOBALS->phar_SERVER_mung_list) { return; } if (PHAR_GLOBALS->phar_SERVER_mung_list & PHAR_MUNG_REQUEST_URI) { #if PHP_MAJOR_VERSION >= 6 if (phar_find_key(_SERVER, "REQUEST_URI", sizeof("REQUEST_URI"), (void **) &stuff TSRMLS_CC)) { if (Z_TYPE_PP(stuff) == IS_UNICODE) { is_unicode = 1; zval_unicode_to_string(*stuff TSRMLS_CC); } else { is_unicode = 0; } #else if (SUCCESS == zend_hash_find(_SERVER, "REQUEST_URI", sizeof("REQUEST_URI"), (void **) &stuff)) { #endif path_info = Z_STRVAL_PP(stuff); code = Z_STRLEN_PP(stuff); if (Z_STRLEN_PP(stuff) > basename_len && !memcmp(Z_STRVAL_PP(stuff), basename, basename_len)) { ZVAL_STRINGL(*stuff, Z_STRVAL_PP(stuff) + basename_len, Z_STRLEN_PP(stuff) - basename_len, 1); MAKE_STD_ZVAL(temp); ZVAL_STRINGL(temp, path_info, code, 0); #if PHP_MAJOR_VERSION >= 6 if (is_unicode) { zval_string_to_unicode(*stuff TSRMLS_CC); } #endif zend_hash_update(_SERVER, "PHAR_REQUEST_URI", sizeof("PHAR_REQUEST_URI"), (void *) &temp, sizeof(zval **), NULL); } } } if (PHAR_GLOBALS->phar_SERVER_mung_list & PHAR_MUNG_PHP_SELF) { #if PHP_MAJOR_VERSION >= 6 if (phar_find_key(_SERVER, "PHP_SELF", sizeof("PHP_SELF"), (void **) &stuff TSRMLS_CC)) { if (Z_TYPE_PP(stuff) == IS_UNICODE) { is_unicode = 1; zval_unicode_to_string(*stuff TSRMLS_CC); } else { is_unicode = 0; } #else if (SUCCESS == zend_hash_find(_SERVER, "PHP_SELF", sizeof("PHP_SELF"), (void **) &stuff)) { #endif path_info = Z_STRVAL_PP(stuff); code = Z_STRLEN_PP(stuff); if (Z_STRLEN_PP(stuff) > basename_len && !memcmp(Z_STRVAL_PP(stuff), basename, basename_len)) { ZVAL_STRINGL(*stuff, Z_STRVAL_PP(stuff) + basename_len, Z_STRLEN_PP(stuff) - basename_len, 1); MAKE_STD_ZVAL(temp); ZVAL_STRINGL(temp, path_info, code, 0); #if PHP_MAJOR_VERSION >= 6 if (is_unicode) { zval_string_to_unicode(*stuff TSRMLS_CC); } #endif zend_hash_update(_SERVER, "PHAR_PHP_SELF", sizeof("PHAR_PHP_SELF"), (void *) &temp, sizeof(zval **), NULL); } } } if (PHAR_GLOBALS->phar_SERVER_mung_list & PHAR_MUNG_SCRIPT_NAME) { #if PHP_MAJOR_VERSION >= 6 if (phar_find_key(_SERVER, "SCRIPT_NAME", sizeof("SCRIPT_NAME"), (void **) &stuff TSRMLS_CC)) { if (Z_TYPE_PP(stuff) == IS_UNICODE) { is_unicode = 1; zval_unicode_to_string(*stuff TSRMLS_CC); } else { is_unicode = 0; } #else if (SUCCESS == zend_hash_find(_SERVER, "SCRIPT_NAME", sizeof("SCRIPT_NAME"), (void **) &stuff)) { #endif path_info = Z_STRVAL_PP(stuff); code = Z_STRLEN_PP(stuff); ZVAL_STRINGL(*stuff, entry, entry_len, 1); MAKE_STD_ZVAL(temp); ZVAL_STRINGL(temp, path_info, code, 0); #if PHP_MAJOR_VERSION >= 6 if (is_unicode) { zval_string_to_unicode(*stuff TSRMLS_CC); } #endif zend_hash_update(_SERVER, "PHAR_SCRIPT_NAME", sizeof("PHAR_SCRIPT_NAME"), (void *) &temp, sizeof(zval **), NULL); } } if (PHAR_GLOBALS->phar_SERVER_mung_list & PHAR_MUNG_SCRIPT_FILENAME) { #if PHP_MAJOR_VERSION >= 6 if (phar_find_key(_SERVER, "SCRIPT_FILENAME", sizeof("SCRIPT_FILENAME"), (void **) &stuff TSRMLS_CC)) { if (Z_TYPE_PP(stuff) == IS_UNICODE) { is_unicode = 1; zval_unicode_to_string(*stuff TSRMLS_CC); } else { is_unicode = 0; } #else if (SUCCESS == zend_hash_find(_SERVER, "SCRIPT_FILENAME", sizeof("SCRIPT_FILENAME"), (void **) &stuff)) { #endif path_info = Z_STRVAL_PP(stuff); code = Z_STRLEN_PP(stuff); Z_STRLEN_PP(stuff) = spprintf(&(Z_STRVAL_PP(stuff)), 4096, "phar://%s%s", fname, entry); MAKE_STD_ZVAL(temp); ZVAL_STRINGL(temp, path_info, code, 0); #if PHP_MAJOR_VERSION >= 6 if (is_unicode) { zval_string_to_unicode(*stuff TSRMLS_CC); } #endif zend_hash_update(_SERVER, "PHAR_SCRIPT_FILENAME", sizeof("PHAR_SCRIPT_FILENAME"), (void *) &temp, sizeof(zval **), NULL); } } } /* }}} */ static int phar_file_action(phar_archive_data *phar, phar_entry_info *info, char *mime_type, int code, char *entry, int entry_len, char *arch, char *basename, char *ru, int ru_len TSRMLS_DC) /* {{{ */ { char *name = NULL, buf[8192]; const char *cwd; zend_syntax_highlighter_ini syntax_highlighter_ini; sapi_header_line ctr = {0}; size_t got; int dummy = 1, name_len; zend_file_handle file_handle; zend_op_array *new_op_array; zval *result = NULL; php_stream *fp; off_t position; switch (code) { case PHAR_MIME_PHPS: efree(basename); /* highlight source */ if (entry[0] == '/') { name_len = spprintf(&name, 4096, "phar://%s%s", arch, entry); } else { name_len = spprintf(&name, 4096, "phar://%s/%s", arch, entry); } php_get_highlight_struct(&syntax_highlighter_ini); highlight_file(name, &syntax_highlighter_ini TSRMLS_CC); efree(name); #ifdef PHP_WIN32 efree(arch); #endif zend_bailout(); case PHAR_MIME_OTHER: /* send headers, output file contents */ efree(basename); ctr.line_len = spprintf(&(ctr.line), 0, "Content-type: %s", mime_type); sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC); efree(ctr.line); ctr.line_len = spprintf(&(ctr.line), 0, "Content-length: %u", info->uncompressed_filesize); sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC); efree(ctr.line); if (FAILURE == sapi_send_headers(TSRMLS_C)) { zend_bailout(); } /* prepare to output */ fp = phar_get_efp(info, 1 TSRMLS_CC); if (!fp) { char *error; if (!phar_open_jit(phar, info, &error TSRMLS_CC)) { if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } return -1; } fp = phar_get_efp(info, 1 TSRMLS_CC); } position = 0; phar_seek_efp(info, 0, SEEK_SET, 0, 1 TSRMLS_CC); do { got = php_stream_read(fp, buf, MIN(8192, info->uncompressed_filesize - position)); if (got > 0) { PHPWRITE(buf, got); position += got; if (position == (off_t) info->uncompressed_filesize) { break; } } } while (1); zend_bailout(); case PHAR_MIME_PHP: if (basename) { phar_mung_server_vars(arch, entry, entry_len, basename, ru_len TSRMLS_CC); efree(basename); } if (entry[0] == '/') { name_len = spprintf(&name, 4096, "phar://%s%s", arch, entry); } else { name_len = spprintf(&name, 4096, "phar://%s/%s", arch, entry); } file_handle.type = ZEND_HANDLE_FILENAME; file_handle.handle.fd = 0; file_handle.filename = name; file_handle.opened_path = NULL; file_handle.free_filename = 0; PHAR_G(cwd) = NULL; PHAR_G(cwd_len) = 0; if (zend_hash_add(&EG(included_files), name, name_len+1, (void *)&dummy, sizeof(int), NULL) == SUCCESS) { if ((cwd = zend_memrchr(entry, '/', entry_len))) { PHAR_G(cwd_init) = 1; if (entry == cwd) { /* root directory */ PHAR_G(cwd_len) = 0; PHAR_G(cwd) = NULL; } else if (entry[0] == '/') { PHAR_G(cwd_len) = cwd - (entry + 1); PHAR_G(cwd) = estrndup(entry + 1, PHAR_G(cwd_len)); } else { PHAR_G(cwd_len) = cwd - entry; PHAR_G(cwd) = estrndup(entry, PHAR_G(cwd_len)); } } new_op_array = zend_compile_file(&file_handle, ZEND_REQUIRE TSRMLS_CC); if (!new_op_array) { zend_hash_del(&EG(included_files), name, name_len+1); } zend_destroy_file_handle(&file_handle TSRMLS_CC); } else { efree(name); new_op_array = NULL; } #ifdef PHP_WIN32 efree(arch); #endif if (new_op_array) { EG(return_value_ptr_ptr) = &result; EG(active_op_array) = new_op_array; zend_try { zend_execute(new_op_array TSRMLS_CC); if (PHAR_G(cwd)) { efree(PHAR_G(cwd)); PHAR_G(cwd) = NULL; PHAR_G(cwd_len) = 0; } PHAR_G(cwd_init) = 0; efree(name); destroy_op_array(new_op_array TSRMLS_CC); efree(new_op_array); if (EG(return_value_ptr_ptr) && *EG(return_value_ptr_ptr)) { zval_ptr_dtor(EG(return_value_ptr_ptr)); } } zend_catch { if (PHAR_G(cwd)) { efree(PHAR_G(cwd)); PHAR_G(cwd) = NULL; PHAR_G(cwd_len) = 0; } PHAR_G(cwd_init) = 0; efree(name); } zend_end_try(); zend_bailout(); } return PHAR_MIME_PHP; } return -1; } /* }}} */ static void phar_do_403(char *entry, int entry_len TSRMLS_DC) /* {{{ */ { sapi_header_line ctr = {0}; ctr.response_code = 403; ctr.line_len = sizeof("HTTP/1.0 403 Access Denied"); ctr.line = "HTTP/1.0 403 Access Denied"; sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC); sapi_send_headers(TSRMLS_C); PHPWRITE("<html>\n <head>\n <title>Access Denied</title>\n </head>\n <body>\n <h1>403 - File ", sizeof("<html>\n <head>\n <title>Access Denied</title>\n </head>\n <body>\n <h1>403 - File ") - 1); PHPWRITE(entry, entry_len); PHPWRITE(" Access Denied</h1>\n </body>\n</html>", sizeof(" Access Denied</h1>\n </body>\n</html>") - 1); } /* }}} */ static void phar_do_404(phar_archive_data *phar, char *fname, int fname_len, char *f404, int f404_len, char *entry, int entry_len TSRMLS_DC) /* {{{ */ { sapi_header_line ctr = {0}; phar_entry_info *info; if (phar && f404_len) { info = phar_get_entry_info(phar, f404, f404_len, NULL, 1 TSRMLS_CC); if (info) { phar_file_action(phar, info, "text/html", PHAR_MIME_PHP, f404, f404_len, fname, NULL, NULL, 0 TSRMLS_CC); return; } } ctr.response_code = 404; ctr.line_len = sizeof("HTTP/1.0 404 Not Found")+1; ctr.line = "HTTP/1.0 404 Not Found"; sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC); sapi_send_headers(TSRMLS_C); PHPWRITE("<html>\n <head>\n <title>File Not Found</title>\n </head>\n <body>\n <h1>404 - File ", sizeof("<html>\n <head>\n <title>File Not Found</title>\n </head>\n <body>\n <h1>404 - File ") - 1); PHPWRITE(entry, entry_len); PHPWRITE(" Not Found</h1>\n </body>\n</html>", sizeof(" Not Found</h1>\n </body>\n</html>") - 1); } /* }}} */ /* post-process REQUEST_URI and retrieve the actual request URI. This is for cases like http://localhost/blah.phar/path/to/file.php/extra/stuff which calls "blah.phar" file "path/to/file.php" with PATH_INFO "/extra/stuff" */ static void phar_postprocess_ru_web(char *fname, int fname_len, char **entry, int *entry_len, char **ru, int *ru_len TSRMLS_DC) /* {{{ */ { char *e = *entry + 1, *u = NULL, *u1 = NULL, *saveu = NULL; int e_len = *entry_len - 1, u_len = 0; phar_archive_data **pphar = NULL; /* we already know we can retrieve the phar if we reach here */ zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), fname, fname_len, (void **) &pphar); if (!pphar && PHAR_G(manifest_cached)) { zend_hash_find(&cached_phars, fname, fname_len, (void **) &pphar); } do { if (zend_hash_exists(&((*pphar)->manifest), e, e_len)) { if (u) { u[0] = '/'; *ru = estrndup(u, u_len+1); ++u_len; u[0] = '\0'; } else { *ru = NULL; } *ru_len = u_len; *entry_len = e_len + 1; return; } if (u) { u1 = strrchr(e, '/'); u[0] = '/'; saveu = u; e_len += u_len + 1; u = u1; if (!u) { return; } } else { u = strrchr(e, '/'); if (!u) { if (saveu) { saveu[0] = '/'; } return; } } u[0] = '\0'; u_len = strlen(u + 1); e_len -= u_len + 1; if (e_len < 0) { if (saveu) { saveu[0] = '/'; } return; } } while (1); } /* }}} */ /* {{{ proto void Phar::running([bool retphar = true]) * return the name of the currently running phar archive. If the optional parameter * is set to true, return the phar:// URL to the currently running phar */ PHP_METHOD(Phar, running) { char *fname, *arch, *entry; int fname_len, arch_len, entry_len; zend_bool retphar = 1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &retphar) == FAILURE) { return; } fname = zend_get_executed_filename(TSRMLS_C); fname_len = strlen(fname); if (fname_len > 7 && !memcmp(fname, "phar://", 7) && SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0 TSRMLS_CC)) { efree(entry); if (retphar) { RETVAL_STRINGL(fname, arch_len + 7, 1); efree(arch); return; } else { RETURN_STRINGL(arch, arch_len, 0); } } RETURN_STRINGL("", 0, 1); } /* }}} */ /* {{{ proto void Phar::mount(string pharpath, string externalfile) * mount an external file or path to a location within the phar. This maps * an external file or directory to a location within the phar archive, allowing * reference to an external location as if it were within the phar archive. This * is useful for writable temp files like databases */ PHP_METHOD(Phar, mount) { char *fname, *arch = NULL, *entry = NULL, *path, *actual; int fname_len, arch_len, entry_len, path_len, actual_len; phar_archive_data **pphar; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &path, &path_len, &actual, &actual_len) == FAILURE) { return; } fname = zend_get_executed_filename(TSRMLS_C); fname_len = strlen(fname); #ifdef PHP_WIN32 phar_unixify_path_separators(fname, fname_len); #endif if (fname_len > 7 && !memcmp(fname, "phar://", 7) && SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0 TSRMLS_CC)) { efree(entry); entry = NULL; if (path_len > 7 && !memcmp(path, "phar://", 7)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Can only mount internal paths within a phar archive, use a relative path instead of \"%s\"", path); efree(arch); return; } carry_on2: if (SUCCESS != zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), arch, arch_len, (void **)&pphar)) { if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, arch, arch_len, (void **)&pphar)) { if (SUCCESS == phar_copy_on_write(pphar TSRMLS_CC)) { goto carry_on; } } zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s is not a phar archive, cannot mount", arch); if (arch) { efree(arch); } return; } carry_on: if (SUCCESS != phar_mount_entry(*pphar, actual, actual_len, path, path_len TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Mounting of %s to %s within phar %s failed", path, actual, arch); if (path && path == entry) { efree(entry); } if (arch) { efree(arch); } return; } if (entry && path && path == entry) { efree(entry); } if (arch) { efree(arch); } return; } else if (PHAR_GLOBALS->phar_fname_map.arBuckets && SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), fname, fname_len, (void **)&pphar)) { goto carry_on; } else if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, fname, fname_len, (void **)&pphar)) { if (SUCCESS == phar_copy_on_write(pphar TSRMLS_CC)) { goto carry_on; } goto carry_on; } else if (SUCCESS == phar_split_fname(path, path_len, &arch, &arch_len, &entry, &entry_len, 2, 0 TSRMLS_CC)) { path = entry; path_len = entry_len; goto carry_on2; } zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Mounting of %s to %s failed", path, actual); } /* }}} */ /* {{{ proto void Phar::webPhar([string alias, [string index, [string f404, [array mimetypes, [callback rewrites]]]]]) * mapPhar for web-based phars. Reads the currently executed file (a phar) * and registers its manifest. When executed in the CLI or CGI command-line sapi, * this works exactly like mapPhar(). When executed by a web-based sapi, this * reads $_SERVER['REQUEST_URI'] (the actual original value) and parses out the * intended internal file. */ PHP_METHOD(Phar, webPhar) { zval *mimeoverride = NULL, *rewrite = NULL; char *alias = NULL, *error, *index_php = NULL, *f404 = NULL, *ru = NULL; int alias_len = 0, ret, f404_len = 0, free_pathinfo = 0, ru_len = 0; char *fname, *path_info, *mime_type = NULL, *entry, *pt; const char *basename; int fname_len, entry_len, code, index_php_len = 0, not_cgi; phar_archive_data *phar = NULL; phar_entry_info *info; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!s!saz", &alias, &alias_len, &index_php, &index_php_len, &f404, &f404_len, &mimeoverride, &rewrite) == FAILURE) { return; } phar_request_initialize(TSRMLS_C); fname = zend_get_executed_filename(TSRMLS_C); fname_len = strlen(fname); if (phar_open_executed_filename(alias, alias_len, &error TSRMLS_CC) != SUCCESS) { if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } return; } /* retrieve requested file within phar */ if (!(SG(request_info).request_method && SG(request_info).request_uri && (!strcmp(SG(request_info).request_method, "GET") || !strcmp(SG(request_info).request_method, "POST")))) { return; } #ifdef PHP_WIN32 fname = estrndup(fname, fname_len); phar_unixify_path_separators(fname, fname_len); #endif basename = zend_memrchr(fname, '/', fname_len); if (!basename) { basename = fname; } else { ++basename; } if ((strlen(sapi_module.name) == sizeof("cgi-fcgi")-1 && !strncmp(sapi_module.name, "cgi-fcgi", sizeof("cgi-fcgi")-1)) || (strlen(sapi_module.name) == sizeof("cgi")-1 && !strncmp(sapi_module.name, "cgi", sizeof("cgi")-1))) { if (PG(http_globals)[TRACK_VARS_SERVER]) { HashTable *_server = Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]); zval **z_script_name, **z_path_info; if (SUCCESS != zend_hash_find(_server, "SCRIPT_NAME", sizeof("SCRIPT_NAME"), (void**)&z_script_name) || IS_STRING != Z_TYPE_PP(z_script_name) || !strstr(Z_STRVAL_PP(z_script_name), basename)) { return; } if (SUCCESS == zend_hash_find(_server, "PATH_INFO", sizeof("PATH_INFO"), (void**)&z_path_info) && IS_STRING == Z_TYPE_PP(z_path_info)) { entry_len = Z_STRLEN_PP(z_path_info); entry = estrndup(Z_STRVAL_PP(z_path_info), entry_len); path_info = emalloc(Z_STRLEN_PP(z_script_name) + entry_len + 1); memcpy(path_info, Z_STRVAL_PP(z_script_name), Z_STRLEN_PP(z_script_name)); memcpy(path_info + Z_STRLEN_PP(z_script_name), entry, entry_len + 1); free_pathinfo = 1; } else { entry_len = 0; entry = estrndup("", 0); path_info = Z_STRVAL_PP(z_script_name); } pt = estrndup(Z_STRVAL_PP(z_script_name), Z_STRLEN_PP(z_script_name)); } else { char *testit; testit = sapi_getenv("SCRIPT_NAME", sizeof("SCRIPT_NAME")-1 TSRMLS_CC); if (!(pt = strstr(testit, basename))) { efree(testit); return; } path_info = sapi_getenv("PATH_INFO", sizeof("PATH_INFO")-1 TSRMLS_CC); if (path_info) { entry = path_info; entry_len = strlen(entry); spprintf(&path_info, 0, "%s%s", testit, path_info); free_pathinfo = 1; } else { path_info = testit; free_pathinfo = 1; entry = estrndup("", 0); entry_len = 0; } pt = estrndup(testit, (pt - testit) + (fname_len - (basename - fname))); } not_cgi = 0; } else { path_info = SG(request_info).request_uri; if (!(pt = strstr(path_info, basename))) { /* this can happen with rewrite rules - and we have no idea what to do then, so return */ return; } entry_len = strlen(path_info); entry_len -= (pt - path_info) + (fname_len - (basename - fname)); entry = estrndup(pt + (fname_len - (basename - fname)), entry_len); pt = estrndup(path_info, (pt - path_info) + (fname_len - (basename - fname))); not_cgi = 1; } if (rewrite) { zend_fcall_info fci; zend_fcall_info_cache fcc; zval *params, *retval_ptr, **zp[1]; MAKE_STD_ZVAL(params); ZVAL_STRINGL(params, entry, entry_len, 1); zp[0] = &params; #if PHP_VERSION_ID < 50300 if (FAILURE == zend_fcall_info_init(rewrite, &fci, &fcc TSRMLS_CC)) { #else if (FAILURE == zend_fcall_info_init(rewrite, 0, &fci, &fcc, NULL, NULL TSRMLS_CC)) { #endif zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: invalid rewrite callback"); if (free_pathinfo) { efree(path_info); } return; } fci.param_count = 1; fci.params = zp; #if PHP_VERSION_ID < 50300 ++(params->refcount); #else Z_ADDREF_P(params); #endif fci.retval_ptr_ptr = &retval_ptr; if (FAILURE == zend_call_function(&fci, &fcc TSRMLS_CC)) { if (!EG(exception)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: failed to call rewrite callback"); } if (free_pathinfo) { efree(path_info); } return; } if (!fci.retval_ptr_ptr || !retval_ptr) { if (free_pathinfo) { efree(path_info); } zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: rewrite callback must return a string or false"); return; } switch (Z_TYPE_P(retval_ptr)) { #if PHP_VERSION_ID >= 60000 case IS_UNICODE: zval_unicode_to_string(retval_ptr TSRMLS_CC); /* break intentionally omitted */ #endif case IS_STRING: efree(entry); if (fci.retval_ptr_ptr != &retval_ptr) { entry = estrndup(Z_STRVAL_PP(fci.retval_ptr_ptr), Z_STRLEN_PP(fci.retval_ptr_ptr)); entry_len = Z_STRLEN_PP(fci.retval_ptr_ptr); } else { entry = Z_STRVAL_P(retval_ptr); entry_len = Z_STRLEN_P(retval_ptr); } break; case IS_BOOL: phar_do_403(entry, entry_len TSRMLS_CC); if (free_pathinfo) { efree(path_info); } zend_bailout(); return; default: efree(retval_ptr); if (free_pathinfo) { efree(path_info); } zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: rewrite callback must return a string or false"); return; } } if (entry_len) { phar_postprocess_ru_web(fname, fname_len, &entry, &entry_len, &ru, &ru_len TSRMLS_CC); } if (!entry_len || (entry_len == 1 && entry[0] == '/')) { efree(entry); /* direct request */ if (index_php_len) { entry = index_php; entry_len = index_php_len; if (entry[0] != '/') { spprintf(&entry, 0, "/%s", index_php); ++entry_len; } } else { /* assume "index.php" is starting point */ entry = estrndup("/index.php", sizeof("/index.php")); entry_len = sizeof("/index.php")-1; } if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL TSRMLS_CC) || (info = phar_get_entry_info(phar, entry, entry_len, NULL, 0 TSRMLS_CC)) == NULL) { phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len TSRMLS_CC); if (free_pathinfo) { efree(path_info); } zend_bailout(); } else { char *tmp, sa; sapi_header_line ctr = {0}; ctr.response_code = 301; ctr.line_len = sizeof("HTTP/1.1 301 Moved Permanently")+1; ctr.line = "HTTP/1.1 301 Moved Permanently"; sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC); if (not_cgi) { tmp = strstr(path_info, basename) + fname_len; sa = *tmp; *tmp = '\0'; } ctr.response_code = 0; if (path_info[strlen(path_info)-1] == '/') { ctr.line_len = spprintf(&(ctr.line), 4096, "Location: %s%s", path_info, entry + 1); } else { ctr.line_len = spprintf(&(ctr.line), 4096, "Location: %s%s", path_info, entry); } if (not_cgi) { *tmp = sa; } if (free_pathinfo) { efree(path_info); } sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC); sapi_send_headers(TSRMLS_C); efree(ctr.line); zend_bailout(); } } if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL TSRMLS_CC) || (info = phar_get_entry_info(phar, entry, entry_len, NULL, 0 TSRMLS_CC)) == NULL) { phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len TSRMLS_CC); #ifdef PHP_WIN32 efree(fname); #endif zend_bailout(); } if (mimeoverride && zend_hash_num_elements(Z_ARRVAL_P(mimeoverride))) { const char *ext = zend_memrchr(entry, '.', entry_len); zval **val; if (ext) { ++ext; #if PHP_MAJOR_VERSION >= 6 if (phar_find_key(Z_ARRVAL_P(mimeoverride), ext, strlen(ext)+1, (void **) &val TSRMLS_CC)) { #else if (SUCCESS == zend_hash_find(Z_ARRVAL_P(mimeoverride), ext, strlen(ext)+1, (void **) &val)) { #endif switch (Z_TYPE_PP(val)) { case IS_LONG: if (Z_LVAL_PP(val) == PHAR_MIME_PHP || Z_LVAL_PP(val) == PHAR_MIME_PHPS) { mime_type = ""; code = Z_LVAL_PP(val); } else { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown mime type specifier used, only Phar::PHP, Phar::PHPS and a mime type string are allowed"); #ifdef PHP_WIN32 efree(fname); #endif RETURN_FALSE; } break; #if PHP_MAJOR_VERSION >= 6 case IS_UNICODE: zval_unicode_to_string(*(val) TSRMLS_CC); /* break intentionally omitted */ #endif case IS_STRING: mime_type = Z_STRVAL_PP(val); code = PHAR_MIME_OTHER; break; default: zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown mime type specifier used (not a string or int), only Phar::PHP, Phar::PHPS and a mime type string are allowed"); #ifdef PHP_WIN32 efree(fname); #endif RETURN_FALSE; } } } } if (!mime_type) { code = phar_file_type(&PHAR_G(mime_types), entry, &mime_type TSRMLS_CC); } ret = phar_file_action(phar, info, mime_type, code, entry, entry_len, fname, pt, ru, ru_len TSRMLS_CC); } /* }}} */ /* {{{ proto void Phar::mungServer(array munglist) * Defines a list of up to 4 $_SERVER variables that should be modified for execution * to mask the presence of the phar archive. This should be used in conjunction with * Phar::webPhar(), and has no effect otherwise * SCRIPT_NAME, PHP_SELF, REQUEST_URI and SCRIPT_FILENAME */ PHP_METHOD(Phar, mungServer) { zval *mungvalues; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &mungvalues) == FAILURE) { return; } if (!zend_hash_num_elements(Z_ARRVAL_P(mungvalues))) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "No values passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME"); return; } if (zend_hash_num_elements(Z_ARRVAL_P(mungvalues)) > 4) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Too many values passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME"); return; } phar_request_initialize(TSRMLS_C); for (zend_hash_internal_pointer_reset(Z_ARRVAL_P(mungvalues)); SUCCESS == zend_hash_has_more_elements(Z_ARRVAL_P(mungvalues)); zend_hash_move_forward(Z_ARRVAL_P(mungvalues))) { zval **data = NULL; #if PHP_MAJOR_VERSION >= 6 zval *unicopy = NULL; #endif if (SUCCESS != zend_hash_get_current_data(Z_ARRVAL_P(mungvalues), (void **) &data)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "unable to retrieve array value in Phar::mungServer()"); return; } #if PHP_MAJOR_VERSION >= 6 if (Z_TYPE_PP(data) == IS_UNICODE) { MAKE_STD_ZVAL(unicopy); *unicopy = **data; zval_copy_ctor(unicopy); INIT_PZVAL(unicopy); zval_unicode_to_string(unicopy TSRMLS_CC); data = &unicopy; } #endif if (Z_TYPE_PP(data) != IS_STRING) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Non-string value passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME"); return; } if (Z_STRLEN_PP(data) == sizeof("PHP_SELF")-1 && !strncmp(Z_STRVAL_PP(data), "PHP_SELF", sizeof("PHP_SELF")-1)) { PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_PHP_SELF; } if (Z_STRLEN_PP(data) == sizeof("REQUEST_URI")-1) { if (!strncmp(Z_STRVAL_PP(data), "REQUEST_URI", sizeof("REQUEST_URI")-1)) { PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_REQUEST_URI; } if (!strncmp(Z_STRVAL_PP(data), "SCRIPT_NAME", sizeof("SCRIPT_NAME")-1)) { PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_SCRIPT_NAME; } } if (Z_STRLEN_PP(data) == sizeof("SCRIPT_FILENAME")-1 && !strncmp(Z_STRVAL_PP(data), "SCRIPT_FILENAME", sizeof("SCRIPT_FILENAME")-1)) { PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_SCRIPT_FILENAME; } #if PHP_MAJOR_VERSION >= 6 if (unicopy) { zval_ptr_dtor(&unicopy); } #endif } } /* }}} */ /* {{{ proto void Phar::interceptFileFuncs() * instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions * and return stat on files within the phar for relative paths * * Once called, this cannot be reversed, and continue until the end of the request. * * This allows legacy scripts to be pharred unmodified */ PHP_METHOD(Phar, interceptFileFuncs) { phar_intercept_functions(TSRMLS_C); } /* }}} */ /* {{{ proto array Phar::createDefaultStub([string indexfile[, string webindexfile]]) * Return a stub that can be used to run a phar-based archive without the phar extension * indexfile is the CLI startup filename, which defaults to "index.php", webindexfile * is the web startup filename, and also defaults to "index.php" */ PHP_METHOD(Phar, createDefaultStub) { char *index = NULL, *webindex = NULL, *stub, *error; int index_len = 0, webindex_len = 0; size_t stub_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|ss", &index, &index_len, &webindex, &webindex_len) == FAILURE) { return; } stub = phar_create_default_stub(index, webindex, &stub_len, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); return; } RETURN_STRINGL(stub, stub_len, 0); } /* }}} */ /* {{{ proto mixed Phar::mapPhar([string alias, [int dataoffset]]) * Reads the currently executed file (a phar) and registers its manifest */ PHP_METHOD(Phar, mapPhar) { char *alias = NULL, *error; int alias_len = 0; long dataoffset = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!l", &alias, &alias_len, &dataoffset) == FAILURE) { return; } phar_request_initialize(TSRMLS_C); RETVAL_BOOL(phar_open_executed_filename(alias, alias_len, &error TSRMLS_CC) == SUCCESS); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } } /* }}} */ /* {{{ proto mixed Phar::loadPhar(string filename [, string alias]) * Loads any phar archive with an alias */ PHP_METHOD(Phar, loadPhar) { char *fname, *alias = NULL, *error; int fname_len, alias_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s!", &fname, &fname_len, &alias, &alias_len) == FAILURE) { return; } phar_request_initialize(TSRMLS_C); RETVAL_BOOL(phar_open_from_filename(fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, &error TSRMLS_CC) == SUCCESS); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } } /* }}} */ /* {{{ proto string Phar::apiVersion() * Returns the api version */ PHP_METHOD(Phar, apiVersion) { RETURN_STRINGL(PHP_PHAR_API_VERSION, sizeof(PHP_PHAR_API_VERSION)-1, 1); } /* }}}*/ /* {{{ proto bool Phar::canCompress([int method]) * Returns whether phar extension supports compression using zlib/bzip2 */ PHP_METHOD(Phar, canCompress) { long method = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &method) == FAILURE) { return; } phar_request_initialize(TSRMLS_C); switch (method) { case PHAR_ENT_COMPRESSED_GZ: if (PHAR_G(has_zlib)) { RETURN_TRUE; } else { RETURN_FALSE; } case PHAR_ENT_COMPRESSED_BZ2: if (PHAR_G(has_bz2)) { RETURN_TRUE; } else { RETURN_FALSE; } default: if (PHAR_G(has_zlib) || PHAR_G(has_bz2)) { RETURN_TRUE; } else { RETURN_FALSE; } } } /* }}} */ /* {{{ proto bool Phar::canWrite() * Returns whether phar extension supports writing and creating phars */ PHP_METHOD(Phar, canWrite) { RETURN_BOOL(!PHAR_G(readonly)); } /* }}} */ /* {{{ proto bool Phar::isValidPharFilename(string filename[, bool executable = true]) * Returns whether the given filename is a valid phar filename */ PHP_METHOD(Phar, isValidPharFilename) { char *fname; const char *ext_str; int fname_len, ext_len, is_executable; zend_bool executable = 1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|b", &fname, &fname_len, &executable) == FAILURE) { return; } is_executable = executable; RETVAL_BOOL(phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, is_executable, 2, 1 TSRMLS_CC) == SUCCESS); } /* }}} */ #if HAVE_SPL /** * from spl_directory */ static void phar_spl_foreign_dtor(spl_filesystem_object *object TSRMLS_DC) /* {{{ */ { phar_archive_data *phar = (phar_archive_data *) object->oth; if (!phar->is_persistent) { phar_archive_delref(phar TSRMLS_CC); } object->oth = NULL; } /* }}} */ /** * from spl_directory */ static void phar_spl_foreign_clone(spl_filesystem_object *src, spl_filesystem_object *dst TSRMLS_DC) /* {{{ */ { phar_archive_data *phar_data = (phar_archive_data *) dst->oth; if (!phar_data->is_persistent) { ++(phar_data->refcount); } } /* }}} */ static spl_other_handler phar_spl_foreign_handler = { phar_spl_foreign_dtor, phar_spl_foreign_clone }; #endif /* HAVE_SPL */ /* {{{ proto void Phar::__construct(string fname [, int flags [, string alias]]) * Construct a Phar archive object * * proto void PharData::__construct(string fname [[, int flags [, string alias]], int file format = Phar::TAR]) * Construct a PharData archive object * * This function is used as the constructor for both the Phar and PharData * classes, hence the two prototypes above. */ PHP_METHOD(Phar, __construct) { #if !HAVE_SPL zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Cannot instantiate Phar object without SPL extension"); #else char *fname, *alias = NULL, *error, *arch = NULL, *entry = NULL, *save_fname; int fname_len, alias_len = 0, arch_len, entry_len, is_data; #if PHP_VERSION_ID < 50300 long flags = 0; #else long flags = SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS; #endif long format = 0; phar_archive_object *phar_obj; phar_archive_data *phar_data; zval *zobj = getThis(), arg1, arg2; phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC); is_data = instanceof_function(Z_OBJCE_P(zobj), phar_ce_data TSRMLS_CC); if (is_data) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!l", &fname, &fname_len, &flags, &alias, &alias_len, &format) == FAILURE) { return; } } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!", &fname, &fname_len, &flags, &alias, &alias_len) == FAILURE) { return; } } if (phar_obj->arc.archive) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot call constructor twice"); return; } save_fname = fname; if (SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, !is_data, 2 TSRMLS_CC)) { /* use arch (the basename for the archive) for fname instead of fname */ /* this allows support for RecursiveDirectoryIterator of subdirectories */ #ifdef PHP_WIN32 phar_unixify_path_separators(arch, arch_len); #endif fname = arch; fname_len = arch_len; #ifdef PHP_WIN32 } else { arch = estrndup(fname, fname_len); arch_len = fname_len; fname = arch; phar_unixify_path_separators(arch, arch_len); #endif } if (phar_open_or_create_filename(fname, fname_len, alias, alias_len, is_data, REPORT_ERRORS, &phar_data, &error TSRMLS_CC) == FAILURE) { if (fname == arch && fname != save_fname) { efree(arch); fname = save_fname; } if (entry) { efree(entry); } if (error) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "%s", error); efree(error); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Phar creation or opening failed"); } return; } if (is_data && phar_data->is_tar && phar_data->is_brandnew && format == PHAR_FORMAT_ZIP) { phar_data->is_zip = 1; phar_data->is_tar = 0; } if (fname == arch) { efree(arch); fname = save_fname; } if ((is_data && !phar_data->is_data) || (!is_data && phar_data->is_data)) { if (is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "PharData class can only be used for non-executable tar and zip archives"); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Phar class can only be used for executable tar and zip archives"); } efree(entry); return; } is_data = phar_data->is_data; if (!phar_data->is_persistent) { ++(phar_data->refcount); } phar_obj->arc.archive = phar_data; phar_obj->spl.oth_handler = &phar_spl_foreign_handler; if (entry) { fname_len = spprintf(&fname, 0, "phar://%s%s", phar_data->fname, entry); efree(entry); } else { fname_len = spprintf(&fname, 0, "phar://%s", phar_data->fname); } INIT_PZVAL(&arg1); ZVAL_STRINGL(&arg1, fname, fname_len, 0); INIT_PZVAL(&arg2); ZVAL_LONG(&arg2, flags); zend_call_method_with_2_params(&zobj, Z_OBJCE_P(zobj), &spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg1, &arg2); if (!phar_data->is_persistent) { phar_obj->arc.archive->is_data = is_data; } else if (!EG(exception)) { /* register this guy so we can modify if necessary */ zend_hash_add(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive), (void *) &phar_obj, sizeof(phar_archive_object **), NULL); } phar_obj->spl.info_class = phar_ce_entry; efree(fname); #endif /* HAVE_SPL */ } /* }}} */ /* {{{ proto array Phar::getSupportedSignatures() * Return array of supported signature types */ PHP_METHOD(Phar, getSupportedSignatures) { array_init(return_value); add_next_index_stringl(return_value, "MD5", 3, 1); add_next_index_stringl(return_value, "SHA-1", 5, 1); #ifdef PHAR_HASH_OK add_next_index_stringl(return_value, "SHA-256", 7, 1); add_next_index_stringl(return_value, "SHA-512", 7, 1); #endif #if PHAR_HAVE_OPENSSL add_next_index_stringl(return_value, "OpenSSL", 7, 1); #else if (zend_hash_exists(&module_registry, "openssl", sizeof("openssl"))) { add_next_index_stringl(return_value, "OpenSSL", 7, 1); } #endif } /* }}} */ /* {{{ proto array Phar::getSupportedCompression() * Return array of supported comparession algorithms */ PHP_METHOD(Phar, getSupportedCompression) { array_init(return_value); phar_request_initialize(TSRMLS_C); if (PHAR_G(has_zlib)) { add_next_index_stringl(return_value, "GZ", 2, 1); } if (PHAR_G(has_bz2)) { add_next_index_stringl(return_value, "BZIP2", 5, 1); } } /* }}} */ /* {{{ proto array Phar::unlinkArchive(string archive) * Completely remove a phar archive from memory and disk */ PHP_METHOD(Phar, unlinkArchive) { char *fname, *error, *zname, *arch, *entry; int fname_len, zname_len, arch_len, entry_len; phar_archive_data *phar; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &fname, &fname_len) == FAILURE) { RETURN_FALSE; } if (!fname_len) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown phar archive \"\""); return; } if (FAILURE == phar_open_from_filename(fname, fname_len, NULL, 0, REPORT_ERRORS, &phar, &error TSRMLS_CC)) { if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown phar archive \"%s\": %s", fname, error); efree(error); } else { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown phar archive \"%s\"", fname); } return; } zname = zend_get_executed_filename(TSRMLS_C); zname_len = strlen(zname); if (zname_len > 7 && !memcmp(zname, "phar://", 7) && SUCCESS == phar_split_fname(zname, zname_len, &arch, &arch_len, &entry, &entry_len, 2, 0 TSRMLS_CC)) { if (arch_len == fname_len && !memcmp(arch, fname, arch_len)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar archive \"%s\" cannot be unlinked from within itself", fname); efree(arch); efree(entry); return; } efree(arch); efree(entry); } if (phar->is_persistent) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar archive \"%s\" is in phar.cache_list, cannot unlinkArchive()", fname); return; } if (phar->refcount) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar archive \"%s\" has open file handles or objects. fclose() all file handles, and unset() all objects prior to calling unlinkArchive()", fname); return; } fname = estrndup(phar->fname, phar->fname_len); /* invalidate phar cache */ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; phar_archive_delref(phar TSRMLS_CC); unlink(fname); efree(fname); RETURN_TRUE; } /* }}} */ #if HAVE_SPL #define PHAR_ARCHIVE_OBJECT() \ phar_archive_object *phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC); \ if (!phar_obj->arc.archive) { \ zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \ "Cannot call method on an uninitialized Phar object"); \ return; \ } /* {{{ proto void Phar::__destruct() * if persistent, remove from the cache */ PHP_METHOD(Phar, __destruct) { phar_archive_object *phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (phar_obj->arc.archive && phar_obj->arc.archive->is_persistent) { zend_hash_del(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive)); } } /* }}} */ struct _phar_t { phar_archive_object *p; zend_class_entry *c; char *b; uint l; zval *ret; int count; php_stream *fp; }; static int phar_build(zend_object_iterator *iter, void *puser TSRMLS_DC) /* {{{ */ { zval **value; zend_uchar key_type; zend_bool close_fp = 1; ulong int_key; struct _phar_t *p_obj = (struct _phar_t*) puser; uint str_key_len, base_len = p_obj->l, fname_len; phar_entry_data *data; php_stream *fp; size_t contents_len; char *fname, *error = NULL, *base = p_obj->b, *opened, *save = NULL, *temp = NULL; phar_zstr key; char *str_key; zend_class_entry *ce = p_obj->c; phar_archive_object *phar_obj = p_obj->p; char *str = "[stream]"; iter->funcs->get_current_data(iter, &value TSRMLS_CC); if (EG(exception)) { return ZEND_HASH_APPLY_STOP; } if (!value) { /* failure in get_current_data */ zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned no value", ce->name); return ZEND_HASH_APPLY_STOP; } switch (Z_TYPE_PP(value)) { #if PHP_VERSION_ID >= 60000 case IS_UNICODE: zval_unicode_to_string(*(value) TSRMLS_CC); /* break intentionally omitted */ #endif case IS_STRING: break; case IS_RESOURCE: php_stream_from_zval_no_verify(fp, value); if (!fp) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Iterator %v returned an invalid stream handle", ce->name); return ZEND_HASH_APPLY_STOP; } if (iter->funcs->get_current_key) { key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC); if (EG(exception)) { return ZEND_HASH_APPLY_STOP; } if (key_type == HASH_KEY_IS_LONG) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name); return ZEND_HASH_APPLY_STOP; } if (key_type > 9) { /* IS_UNICODE == 10 */ #if PHP_VERSION_ID < 60000 /* this can never happen, but fixes a compile warning */ spprintf(&str_key, 0, "%s", key); #else spprintf(&str_key, 0, "%v", key); ezfree(key); #endif } else { PHAR_STR(key, str_key); } save = str_key; if (str_key[str_key_len - 1] == '\0') { str_key_len--; } } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name); return ZEND_HASH_APPLY_STOP; } close_fp = 0; opened = (char *) estrndup(str, sizeof("[stream]") + 1); goto after_open_fp; case IS_OBJECT: if (instanceof_function(Z_OBJCE_PP(value), spl_ce_SplFileInfo TSRMLS_CC)) { char *test = NULL; zval dummy; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(*value TSRMLS_CC); if (!base_len) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Iterator %v returns an SplFileInfo object, so base directory must be specified", ce->name); return ZEND_HASH_APPLY_STOP; } switch (intern->type) { case SPL_FS_DIR: #if PHP_VERSION_ID >= 60000 test = spl_filesystem_object_get_path(intern, NULL, NULL TSRMLS_CC).s; #elif PHP_VERSION_ID >= 50300 test = spl_filesystem_object_get_path(intern, NULL TSRMLS_CC); #else test = intern->path; #endif fname_len = spprintf(&fname, 0, "%s%c%s", test, DEFAULT_SLASH, intern->u.dir.entry.d_name); php_stat(fname, fname_len, FS_IS_DIR, &dummy TSRMLS_CC); if (Z_BVAL(dummy)) { /* ignore directories */ efree(fname); return ZEND_HASH_APPLY_KEEP; } test = expand_filepath(fname, NULL TSRMLS_CC); if (test) { efree(fname); fname = test; fname_len = strlen(fname); } save = fname; goto phar_spl_fileinfo; case SPL_FS_INFO: case SPL_FS_FILE: #if PHP_VERSION_ID >= 60000 if (intern->file_name_type == IS_UNICODE) { zval zv; INIT_ZVAL(zv); Z_UNIVAL(zv) = intern->file_name; Z_UNILEN(zv) = intern->file_name_len; Z_TYPE(zv) = IS_UNICODE; zval_copy_ctor(&zv); zval_unicode_to_string(&zv TSRMLS_CC); fname = expand_filepath(Z_STRVAL(zv), NULL TSRMLS_CC); ezfree(Z_UNIVAL(zv)); } else { fname = expand_filepath(intern->file_name.s, NULL TSRMLS_CC); } #else fname = expand_filepath(intern->file_name, NULL TSRMLS_CC); #endif fname_len = strlen(fname); save = fname; goto phar_spl_fileinfo; } } /* fall-through */ default: zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid value (must return a string)", ce->name); return ZEND_HASH_APPLY_STOP; } fname = Z_STRVAL_PP(value); fname_len = Z_STRLEN_PP(value); phar_spl_fileinfo: if (base_len) { temp = expand_filepath(base, NULL TSRMLS_CC); base = temp; base_len = strlen(base); if (strstr(fname, base)) { str_key_len = fname_len - base_len; if (str_key_len <= 0) { if (save) { efree(save); efree(temp); } return ZEND_HASH_APPLY_KEEP; } str_key = fname + base_len; if (*str_key == '/' || *str_key == '\\') { str_key++; str_key_len--; } } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that is not in the base directory \"%s\"", ce->name, fname, base); if (save) { efree(save); efree(temp); } return ZEND_HASH_APPLY_STOP; } } else { if (iter->funcs->get_current_key) { key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC); if (EG(exception)) { return ZEND_HASH_APPLY_STOP; } if (key_type == HASH_KEY_IS_LONG) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name); return ZEND_HASH_APPLY_STOP; } if (key_type > 9) { /* IS_UNICODE == 10 */ #if PHP_VERSION_ID < 60000 /* this can never happen, but fixes a compile warning */ spprintf(&str_key, 0, "%s", key); #else spprintf(&str_key, 0, "%v", key); ezfree(key); #endif } else { PHAR_STR(key, str_key); } save = str_key; if (str_key[str_key_len - 1] == '\0') str_key_len--; } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name); return ZEND_HASH_APPLY_STOP; } } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that safe mode prevents opening", ce->name, fname); if (save) { efree(save); } if (temp) { efree(temp); } return ZEND_HASH_APPLY_STOP; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that open_basedir prevents opening", ce->name, fname); if (save) { efree(save); } if (temp) { efree(temp); } return ZEND_HASH_APPLY_STOP; } /* try to open source file, then create internal phar file and copy contents */ fp = php_stream_open_wrapper(fname, "rb", STREAM_MUST_SEEK|0, &opened); if (!fp) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a file that could not be opened \"%s\"", ce->name, fname); if (save) { efree(save); } if (temp) { efree(temp); } return ZEND_HASH_APPLY_STOP; } after_open_fp: if (str_key_len >= sizeof(".phar")-1 && !memcmp(str_key, ".phar", sizeof(".phar")-1)) { /* silently skip any files that would be added to the magic .phar directory */ if (save) { efree(save); } if (temp) { efree(temp); } if (opened) { efree(opened); } if (close_fp) { php_stream_close(fp); } return ZEND_HASH_APPLY_KEEP; } if (!(data = phar_get_or_create_entry_data(phar_obj->arc.archive->fname, phar_obj->arc.archive->fname_len, str_key, str_key_len, "w+b", 0, &error, 1 TSRMLS_CC))) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s cannot be created: %s", str_key, error); efree(error); if (save) { efree(save); } if (opened) { efree(opened); } if (temp) { efree(temp); } if (close_fp) { php_stream_close(fp); } return ZEND_HASH_APPLY_STOP; } else { if (error) { efree(error); } /* convert to PHAR_UFP */ if (data->internal_file->fp_type == PHAR_MOD) { php_stream_close(data->internal_file->fp); } data->internal_file->fp = NULL; data->internal_file->fp_type = PHAR_UFP; data->internal_file->offset_abs = data->internal_file->offset = php_stream_tell(p_obj->fp); data->fp = NULL; phar_stream_copy_to_stream(fp, p_obj->fp, PHP_STREAM_COPY_ALL, &contents_len); data->internal_file->uncompressed_filesize = data->internal_file->compressed_filesize = php_stream_tell(p_obj->fp) - data->internal_file->offset; } if (close_fp) { php_stream_close(fp); } add_assoc_string(p_obj->ret, str_key, opened, 0); if (save) { efree(save); } if (temp) { efree(temp); } data->internal_file->compressed_filesize = data->internal_file->uncompressed_filesize = contents_len; phar_entry_delref(data TSRMLS_CC); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* {{{ proto array Phar::buildFromDirectory(string base_dir[, string regex]) * Construct a phar archive from an existing directory, recursively. * Optional second parameter is a regular expression for filtering directory contents. * * Return value is an array mapping phar index to actual files added. */ PHP_METHOD(Phar, buildFromDirectory) { char *dir, *error, *regex = NULL; int dir_len, regex_len = 0; zend_bool apply_reg = 0; zval arg, arg2, *iter, *iteriter, *regexiter = NULL; struct _phar_t pass; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot write to archive - write operations restricted by INI setting"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &dir, &dir_len, &regex, &regex_len) == FAILURE) { RETURN_FALSE; } MAKE_STD_ZVAL(iter); if (SUCCESS != object_init_ex(iter, spl_ce_RecursiveDirectoryIterator)) { zval_ptr_dtor(&iter); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname); RETURN_FALSE; } INIT_PZVAL(&arg); ZVAL_STRINGL(&arg, dir, dir_len, 0); INIT_PZVAL(&arg2); #if PHP_VERSION_ID < 50300 ZVAL_LONG(&arg2, 0); #else ZVAL_LONG(&arg2, SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS); #endif zend_call_method_with_2_params(&iter, spl_ce_RecursiveDirectoryIterator, &spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg, &arg2); if (EG(exception)) { zval_ptr_dtor(&iter); RETURN_FALSE; } MAKE_STD_ZVAL(iteriter); if (SUCCESS != object_init_ex(iteriter, spl_ce_RecursiveIteratorIterator)) { zval_ptr_dtor(&iter); zval_ptr_dtor(&iteriter); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname); RETURN_FALSE; } zend_call_method_with_1_params(&iteriter, spl_ce_RecursiveIteratorIterator, &spl_ce_RecursiveIteratorIterator->constructor, "__construct", NULL, iter); if (EG(exception)) { zval_ptr_dtor(&iter); zval_ptr_dtor(&iteriter); RETURN_FALSE; } zval_ptr_dtor(&iter); if (regex_len > 0) { apply_reg = 1; MAKE_STD_ZVAL(regexiter); if (SUCCESS != object_init_ex(regexiter, spl_ce_RegexIterator)) { zval_ptr_dtor(&iteriter); zval_dtor(regexiter); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate regex iterator for %s", phar_obj->arc.archive->fname); RETURN_FALSE; } INIT_PZVAL(&arg2); ZVAL_STRINGL(&arg2, regex, regex_len, 0); zend_call_method_with_2_params(&regexiter, spl_ce_RegexIterator, &spl_ce_RegexIterator->constructor, "__construct", NULL, iteriter, &arg2); } array_init(return_value); pass.c = apply_reg ? Z_OBJCE_P(regexiter) : Z_OBJCE_P(iteriter); pass.p = phar_obj; pass.b = dir; pass.l = dir_len; pass.count = 0; pass.ret = return_value; pass.fp = php_stream_fopen_tmpfile(); if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zval_ptr_dtor(&iteriter); if (apply_reg) { zval_ptr_dtor(&regexiter); } php_stream_close(pass.fp); zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } if (SUCCESS == spl_iterator_apply((apply_reg ? regexiter : iteriter), (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) { zval_ptr_dtor(&iteriter); if (apply_reg) { zval_ptr_dtor(&regexiter); } phar_obj->arc.archive->ufp = pass.fp; phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } } else { zval_ptr_dtor(&iteriter); if (apply_reg) { zval_ptr_dtor(&regexiter); } php_stream_close(pass.fp); } } /* }}} */ /* {{{ proto array Phar::buildFromIterator(Iterator iter[, string base_directory]) * Construct a phar archive from an iterator. The iterator must return a series of strings * that are full paths to files that should be added to the phar. The iterator key should * be the path that the file will have within the phar archive. * * If base directory is specified, then the key will be ignored, and instead the portion of * the current value minus the base directory will be used * * Returned is an array mapping phar index to actual file added */ PHP_METHOD(Phar, buildFromIterator) { zval *obj; char *error; uint base_len = 0; char *base = NULL; struct _phar_t pass; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot write out phar archive, phar is read-only"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|s", &obj, zend_ce_traversable, &base, &base_len) == FAILURE) { RETURN_FALSE; } if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } array_init(return_value); pass.c = Z_OBJCE_P(obj); pass.p = phar_obj; pass.b = base; pass.l = base_len; pass.ret = return_value; pass.count = 0; pass.fp = php_stream_fopen_tmpfile(); if (SUCCESS == spl_iterator_apply(obj, (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) { phar_obj->arc.archive->ufp = pass.fp; phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } } else { php_stream_close(pass.fp); } } /* }}} */ /* {{{ proto int Phar::count() * Returns the number of entries in the Phar archive */ PHP_METHOD(Phar, count) { PHAR_ARCHIVE_OBJECT(); RETURN_LONG(zend_hash_num_elements(&phar_obj->arc.archive->manifest)); } /* }}} */ /* {{{ proto bool Phar::isFileFormat(int format) * Returns true if the phar archive is based on the tar/zip/phar file format depending * on whether Phar::TAR, Phar::ZIP or Phar::PHAR was passed in */ PHP_METHOD(Phar, isFileFormat) { long type; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &type) == FAILURE) { RETURN_FALSE; } switch (type) { case PHAR_FORMAT_TAR: RETURN_BOOL(phar_obj->arc.archive->is_tar); case PHAR_FORMAT_ZIP: RETURN_BOOL(phar_obj->arc.archive->is_zip); case PHAR_FORMAT_PHAR: RETURN_BOOL(!phar_obj->arc.archive->is_tar && !phar_obj->arc.archive->is_zip); default: zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown file format specified"); } } /* }}} */ static int phar_copy_file_contents(phar_entry_info *entry, php_stream *fp TSRMLS_DC) /* {{{ */ { char *error; off_t offset; phar_entry_info *link; if (FAILURE == phar_open_entry_fp(entry, &error, 1 TSRMLS_CC)) { if (error) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot convert phar archive \"%s\", unable to open entry \"%s\" contents: %s", entry->phar->fname, entry->filename, error); efree(error); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot convert phar archive \"%s\", unable to open entry \"%s\" contents", entry->phar->fname, entry->filename); } return FAILURE; } /* copy old contents in entirety */ phar_seek_efp(entry, 0, SEEK_SET, 0, 1 TSRMLS_CC); offset = php_stream_tell(fp); link = phar_get_link_source(entry TSRMLS_CC); if (!link) { link = entry; } if (SUCCESS != phar_stream_copy_to_stream(phar_get_efp(link, 0 TSRMLS_CC), fp, link->uncompressed_filesize, NULL)) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot convert phar archive \"%s\", unable to copy entry \"%s\" contents", entry->phar->fname, entry->filename); return FAILURE; } if (entry->fp_type == PHAR_MOD) { /* save for potential restore on error */ entry->cfp = entry->fp; entry->fp = NULL; } /* set new location of file contents */ entry->fp_type = PHAR_FP; entry->offset = offset; return SUCCESS; } /* }}} */ static zval *phar_rename_archive(phar_archive_data *phar, char *ext, zend_bool compress TSRMLS_DC) /* {{{ */ { const char *oldname = NULL; char *oldpath = NULL; char *basename = NULL, *basepath = NULL; char *newname = NULL, *newpath = NULL; zval *ret, arg1; zend_class_entry *ce; char *error; const char *pcr_error; int ext_len = ext ? strlen(ext) : 0; int oldname_len; phar_archive_data **pphar = NULL; php_stream_statbuf ssb; if (!ext) { if (phar->is_zip) { if (phar->is_data) { ext = "zip"; } else { ext = "phar.zip"; } } else if (phar->is_tar) { switch (phar->flags) { case PHAR_FILE_COMPRESSED_GZ: if (phar->is_data) { ext = "tar.gz"; } else { ext = "phar.tar.gz"; } break; case PHAR_FILE_COMPRESSED_BZ2: if (phar->is_data) { ext = "tar.bz2"; } else { ext = "phar.tar.bz2"; } break; default: if (phar->is_data) { ext = "tar"; } else { ext = "phar.tar"; } } } else { switch (phar->flags) { case PHAR_FILE_COMPRESSED_GZ: ext = "phar.gz"; break; case PHAR_FILE_COMPRESSED_BZ2: ext = "phar.bz2"; break; default: ext = "phar"; } } } else if (phar_path_check(&ext, &ext_len, &pcr_error) > pcr_is_ok) { if (phar->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "data phar converted from \"%s\" has invalid extension %s", phar->fname, ext); } else { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar converted from \"%s\" has invalid extension %s", phar->fname, ext); } return NULL; } if (ext[0] == '.') { ++ext; } oldpath = estrndup(phar->fname, phar->fname_len); oldname = zend_memrchr(phar->fname, '/', phar->fname_len); ++oldname; oldname_len = strlen(oldname); basename = estrndup(oldname, oldname_len); spprintf(&newname, 0, "%s.%s", strtok(basename, "."), ext); efree(basename); basepath = estrndup(oldpath, (strlen(oldpath) - oldname_len)); phar->fname_len = spprintf(&newpath, 0, "%s%s", basepath, newname); phar->fname = newpath; phar->ext = newpath + phar->fname_len - strlen(ext) - 1; efree(basepath); efree(newname); if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, newpath, phar->fname_len, (void **) &pphar)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars, new phar name is in phar.cache_list", phar->fname); return NULL; } if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void **) &pphar)) { if ((*pphar)->fname_len == phar->fname_len && !memcmp((*pphar)->fname, phar->fname, phar->fname_len)) { if (!zend_hash_num_elements(&phar->manifest)) { (*pphar)->is_tar = phar->is_tar; (*pphar)->is_zip = phar->is_zip; (*pphar)->is_data = phar->is_data; (*pphar)->flags = phar->flags; (*pphar)->fp = phar->fp; phar->fp = NULL; phar_destroy_phar_data(phar TSRMLS_CC); phar = *pphar; phar->refcount++; newpath = oldpath; goto its_ok; } } efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars, a phar with that name already exists", phar->fname); return NULL; } its_ok: if (SUCCESS == php_stream_stat_path(newpath, &ssb)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar \"%s\" exists and must be unlinked prior to conversion", newpath); return NULL; } if (!phar->is_data) { if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 1, 1, 1 TSRMLS_CC)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar \"%s\" has invalid extension %s", phar->fname, ext); return NULL; } if (phar->alias) { if (phar->is_temporary_alias) { phar->alias = NULL; phar->alias_len = 0; } else { phar->alias = estrndup(newpath, strlen(newpath)); phar->alias_len = strlen(newpath); phar->is_temporary_alias = 1; zend_hash_update(&(PHAR_GLOBALS->phar_alias_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL); } } } else { if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 0, 1, 1 TSRMLS_CC)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "data phar \"%s\" has invalid extension %s", phar->fname, ext); return NULL; } phar->alias = NULL; phar->alias_len = 0; } if ((!pphar || phar == *pphar) && SUCCESS != zend_hash_update(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars", phar->fname); return NULL; } phar_flush(phar, 0, 0, 1, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "%s", error); efree(error); efree(oldpath); return NULL; } efree(oldpath); if (phar->is_data) { ce = phar_ce_data; } else { ce = phar_ce_archive; } MAKE_STD_ZVAL(ret); if (SUCCESS != object_init_ex(ret, ce)) { zval_dtor(ret); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate phar object when converting archive \"%s\"", phar->fname); return NULL; } INIT_PZVAL(&arg1); ZVAL_STRINGL(&arg1, phar->fname, phar->fname_len, 0); zend_call_method_with_1_params(&ret, ce, &ce->constructor, "__construct", NULL, &arg1); return ret; } /* }}} */ static zval *phar_convert_to_other(phar_archive_data *source, int convert, char *ext, php_uint32 flags TSRMLS_DC) /* {{{ */ { phar_archive_data *phar; phar_entry_info *entry, newentry; zval *ret; /* invalidate phar cache */ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; phar = (phar_archive_data *) ecalloc(1, sizeof(phar_archive_data)); /* set whole-archive compression and type from parameter */ phar->flags = flags; phar->is_data = source->is_data; switch (convert) { case PHAR_FORMAT_TAR: phar->is_tar = 1; break; case PHAR_FORMAT_ZIP: phar->is_zip = 1; break; default: phar->is_data = 0; break; } zend_hash_init(&(phar->manifest), sizeof(phar_entry_info), zend_get_hash_value, destroy_phar_manifest_entry, 0); zend_hash_init(&phar->mounted_dirs, sizeof(char *), zend_get_hash_value, NULL, 0); zend_hash_init(&phar->virtual_dirs, sizeof(char *), zend_get_hash_value, NULL, 0); phar->fp = php_stream_fopen_tmpfile(); phar->fname = source->fname; phar->fname_len = source->fname_len; phar->is_temporary_alias = source->is_temporary_alias; phar->alias = source->alias; if (source->metadata) { zval *t; t = source->metadata; ALLOC_ZVAL(phar->metadata); *phar->metadata = *t; zval_copy_ctor(phar->metadata); #if PHP_VERSION_ID < 50300 phar->metadata->refcount = 1; #else Z_SET_REFCOUNT_P(phar->metadata, 1); #endif phar->metadata_len = 0; } /* first copy each file's uncompressed contents to a temporary file and set per-file flags */ for (zend_hash_internal_pointer_reset(&source->manifest); SUCCESS == zend_hash_has_more_elements(&source->manifest); zend_hash_move_forward(&source->manifest)) { if (FAILURE == zend_hash_get_current_data(&source->manifest, (void **) &entry)) { zend_hash_destroy(&(phar->manifest)); php_stream_close(phar->fp); efree(phar); zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot convert phar archive \"%s\"", source->fname); return NULL; } newentry = *entry; if (newentry.link) { newentry.link = estrdup(newentry.link); goto no_copy; } if (newentry.tmp) { newentry.tmp = estrdup(newentry.tmp); goto no_copy; } newentry.metadata_str.c = 0; if (FAILURE == phar_copy_file_contents(&newentry, phar->fp TSRMLS_CC)) { zend_hash_destroy(&(phar->manifest)); php_stream_close(phar->fp); efree(phar); /* exception already thrown */ return NULL; } no_copy: newentry.filename = estrndup(newentry.filename, newentry.filename_len); if (newentry.metadata) { zval *t; t = newentry.metadata; ALLOC_ZVAL(newentry.metadata); *newentry.metadata = *t; zval_copy_ctor(newentry.metadata); #if PHP_VERSION_ID < 50300 newentry.metadata->refcount = 1; #else Z_SET_REFCOUNT_P(newentry.metadata, 1); #endif newentry.metadata_str.c = NULL; newentry.metadata_str.len = 0; } newentry.is_zip = phar->is_zip; newentry.is_tar = phar->is_tar; if (newentry.is_tar) { newentry.tar_type = (entry->is_dir ? TAR_DIR : TAR_FILE); } newentry.is_modified = 1; newentry.phar = phar; newentry.old_flags = newentry.flags & ~PHAR_ENT_COMPRESSION_MASK; /* remove compression from old_flags */ phar_set_inode(&newentry TSRMLS_CC); zend_hash_add(&(phar->manifest), newentry.filename, newentry.filename_len, (void*)&newentry, sizeof(phar_entry_info), NULL); phar_add_virtual_dirs(phar, newentry.filename, newentry.filename_len TSRMLS_CC); } if ((ret = phar_rename_archive(phar, ext, 0 TSRMLS_CC))) { return ret; } else { zend_hash_destroy(&(phar->manifest)); zend_hash_destroy(&(phar->mounted_dirs)); zend_hash_destroy(&(phar->virtual_dirs)); php_stream_close(phar->fp); efree(phar->fname); efree(phar); return NULL; } } /* }}} */ /* {{{ proto object Phar::convertToExecutable([int format[, int compression [, string file_ext]]]) * Convert a phar.tar or phar.zip archive to the phar file format. The * optional parameter allows the user to determine the new * filename extension (default is phar). */ PHP_METHOD(Phar, convertToExecutable) { char *ext = NULL; int is_data, ext_len = 0; php_uint32 flags; zval *ret; /* a number that is not 0, 1 or 2 (Which is also Greg's birthday, so there) */ long format = 9021976, method = 9021976; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lls", &format, &method, &ext, &ext_len) == FAILURE) { return; } if (PHAR_G(readonly)) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot write out executable phar archive, phar is read-only"); return; } switch (format) { case 9021976: case PHAR_FORMAT_SAME: /* null is converted to 0 */ /* by default, use the existing format */ if (phar_obj->arc.archive->is_tar) { format = PHAR_FORMAT_TAR; } else if (phar_obj->arc.archive->is_zip) { format = PHAR_FORMAT_ZIP; } else { format = PHAR_FORMAT_PHAR; } break; case PHAR_FORMAT_PHAR: case PHAR_FORMAT_TAR: case PHAR_FORMAT_ZIP: break; default: zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unknown file format specified, please pass one of Phar::PHAR, Phar::TAR or Phar::ZIP"); return; } switch (method) { case 9021976: flags = phar_obj->arc.archive->flags & PHAR_FILE_COMPRESSION_MASK; break; case 0: flags = PHAR_FILE_COMPRESSED_NONE; break; case PHAR_ENT_COMPRESSED_GZ: if (format == PHAR_FORMAT_ZIP) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress entire archive with gzip, zip archives do not support whole-archive compression"); return; } if (!PHAR_G(has_zlib)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress entire archive with gzip, enable ext/zlib in php.ini"); return; } flags = PHAR_FILE_COMPRESSED_GZ; break; case PHAR_ENT_COMPRESSED_BZ2: if (format == PHAR_FORMAT_ZIP) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress entire archive with bz2, zip archives do not support whole-archive compression"); return; } if (!PHAR_G(has_bz2)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress entire archive with bz2, enable ext/bz2 in php.ini"); return; } flags = PHAR_FILE_COMPRESSED_BZ2; break; default: zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unknown compression specified, please pass one of Phar::GZ or Phar::BZ2"); return; } is_data = phar_obj->arc.archive->is_data; phar_obj->arc.archive->is_data = 0; ret = phar_convert_to_other(phar_obj->arc.archive, format, ext, flags TSRMLS_CC); phar_obj->arc.archive->is_data = is_data; if (ret) { RETURN_ZVAL(ret, 1, 1); } else { RETURN_NULL(); } } /* }}} */ /* {{{ proto object Phar::convertToData([int format[, int compression [, string file_ext]]]) * Convert an archive to a non-executable .tar or .zip. * The optional parameter allows the user to determine the new * filename extension (default is .zip or .tar). */ PHP_METHOD(Phar, convertToData) { char *ext = NULL; int is_data, ext_len = 0; php_uint32 flags; zval *ret; /* a number that is not 0, 1 or 2 (Which is also Greg's birthday so there) */ long format = 9021976, method = 9021976; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lls", &format, &method, &ext, &ext_len) == FAILURE) { return; } switch (format) { case 9021976: case PHAR_FORMAT_SAME: /* null is converted to 0 */ /* by default, use the existing format */ if (phar_obj->arc.archive->is_tar) { format = PHAR_FORMAT_TAR; } else if (phar_obj->arc.archive->is_zip) { format = PHAR_FORMAT_ZIP; } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot write out data phar archive, use Phar::TAR or Phar::ZIP"); return; } break; case PHAR_FORMAT_PHAR: zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot write out data phar archive, use Phar::TAR or Phar::ZIP"); return; case PHAR_FORMAT_TAR: case PHAR_FORMAT_ZIP: break; default: zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unknown file format specified, please pass one of Phar::TAR or Phar::ZIP"); return; } switch (method) { case 9021976: flags = phar_obj->arc.archive->flags & PHAR_FILE_COMPRESSION_MASK; break; case 0: flags = PHAR_FILE_COMPRESSED_NONE; break; case PHAR_ENT_COMPRESSED_GZ: if (format == PHAR_FORMAT_ZIP) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress entire archive with gzip, zip archives do not support whole-archive compression"); return; } if (!PHAR_G(has_zlib)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress entire archive with gzip, enable ext/zlib in php.ini"); return; } flags = PHAR_FILE_COMPRESSED_GZ; break; case PHAR_ENT_COMPRESSED_BZ2: if (format == PHAR_FORMAT_ZIP) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress entire archive with bz2, zip archives do not support whole-archive compression"); return; } if (!PHAR_G(has_bz2)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress entire archive with bz2, enable ext/bz2 in php.ini"); return; } flags = PHAR_FILE_COMPRESSED_BZ2; break; default: zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unknown compression specified, please pass one of Phar::GZ or Phar::BZ2"); return; } is_data = phar_obj->arc.archive->is_data; phar_obj->arc.archive->is_data = 1; ret = phar_convert_to_other(phar_obj->arc.archive, format, ext, flags TSRMLS_CC); phar_obj->arc.archive->is_data = is_data; if (ret) { RETURN_ZVAL(ret, 1, 1); } else { RETURN_NULL(); } } /* }}} */ /* {{{ proto int|false Phar::isCompressed() * Returns Phar::GZ or PHAR::BZ2 if the entire archive is compressed * (.tar.gz/tar.bz2 and so on), or FALSE otherwise. */ PHP_METHOD(Phar, isCompressed) { PHAR_ARCHIVE_OBJECT(); if (phar_obj->arc.archive->flags & PHAR_FILE_COMPRESSED_GZ) { RETURN_LONG(PHAR_ENT_COMPRESSED_GZ); } if (phar_obj->arc.archive->flags & PHAR_FILE_COMPRESSED_BZ2) { RETURN_LONG(PHAR_ENT_COMPRESSED_BZ2); } RETURN_FALSE; } /* }}} */ /* {{{ proto bool Phar::isWritable() * Returns true if phar.readonly=0 or phar is a PharData AND the actual file is writable. */ PHP_METHOD(Phar, isWritable) { php_stream_statbuf ssb; PHAR_ARCHIVE_OBJECT(); if (!phar_obj->arc.archive->is_writeable) { RETURN_FALSE; } if (SUCCESS != php_stream_stat_path(phar_obj->arc.archive->fname, &ssb)) { if (phar_obj->arc.archive->is_brandnew) { /* assume it works if the file doesn't exist yet */ RETURN_TRUE; } RETURN_FALSE; } RETURN_BOOL((ssb.sb.st_mode & (S_IWOTH | S_IWGRP | S_IWUSR)) != 0); } /* }}} */ /* {{{ proto bool Phar::delete(string entry) * Deletes a named file within the archive. */ PHP_METHOD(Phar, delete) { char *fname; int fname_len; char *error; phar_entry_info *entry; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot write out phar archive, phar is read-only"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &fname, &fname_len) == FAILURE) { RETURN_FALSE; } if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } if (zend_hash_exists(&phar_obj->arc.archive->manifest, fname, (uint) fname_len)) { if (SUCCESS == zend_hash_find(&phar_obj->arc.archive->manifest, fname, (uint) fname_len, (void**)&entry)) { if (entry->is_deleted) { /* entry is deleted, but has not been flushed to disk yet */ RETURN_TRUE; } else { entry->is_deleted = 1; entry->is_modified = 1; phar_obj->arc.archive->is_modified = 1; } } } else { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s does not exist and cannot be deleted", fname); RETURN_FALSE; } phar_flush(phar_obj->arc.archive, NULL, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } RETURN_TRUE; } /* }}} */ /* {{{ proto int Phar::getAlias() * Returns the alias for the Phar or NULL. */ PHP_METHOD(Phar, getAlias) { PHAR_ARCHIVE_OBJECT(); if (phar_obj->arc.archive->alias && phar_obj->arc.archive->alias != phar_obj->arc.archive->fname) { RETURN_STRINGL(phar_obj->arc.archive->alias, phar_obj->arc.archive->alias_len, 1); } } /* }}} */ /* {{{ proto int Phar::getPath() * Returns the real path to the phar archive on disk */ PHP_METHOD(Phar, getPath) { PHAR_ARCHIVE_OBJECT(); RETURN_STRINGL(phar_obj->arc.archive->fname, phar_obj->arc.archive->fname_len, 1); } /* }}} */ /* {{{ proto bool Phar::setAlias(string alias) * Sets the alias for a Phar archive. The default value is the full path * to the archive. */ PHP_METHOD(Phar, setAlias) { char *alias, *error, *oldalias; phar_archive_data **fd_ptr; int alias_len, oldalias_len, old_temp, readd = 0; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot write out phar archive, phar is read-only"); RETURN_FALSE; } /* invalidate phar cache */ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; if (phar_obj->arc.archive->is_data) { if (phar_obj->arc.archive->is_tar) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "A Phar alias cannot be set in a plain tar archive"); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "A Phar alias cannot be set in a plain zip archive"); } RETURN_FALSE; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &alias, &alias_len) == SUCCESS) { if (alias_len == phar_obj->arc.archive->alias_len && memcmp(phar_obj->arc.archive->alias, alias, alias_len) == 0) { RETURN_TRUE; } if (alias_len && SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void**)&fd_ptr)) { spprintf(&error, 0, "alias \"%s\" is already used for archive \"%s\" and cannot be used for other archives", alias, (*fd_ptr)->fname); if (SUCCESS == phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) { efree(error); goto valid_alias; } zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); RETURN_FALSE; } if (!phar_validate_alias(alias, alias_len)) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Invalid alias \"%s\" specified for phar \"%s\"", alias, phar_obj->arc.archive->fname); RETURN_FALSE; } valid_alias: if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } if (phar_obj->arc.archive->alias_len && SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), phar_obj->arc.archive->alias, phar_obj->arc.archive->alias_len, (void**)&fd_ptr)) { zend_hash_del(&(PHAR_GLOBALS->phar_alias_map), phar_obj->arc.archive->alias, phar_obj->arc.archive->alias_len); readd = 1; } oldalias = phar_obj->arc.archive->alias; oldalias_len = phar_obj->arc.archive->alias_len; old_temp = phar_obj->arc.archive->is_temporary_alias; if (alias_len) { phar_obj->arc.archive->alias = estrndup(alias, alias_len); } else { phar_obj->arc.archive->alias = NULL; } phar_obj->arc.archive->alias_len = alias_len; phar_obj->arc.archive->is_temporary_alias = 0; phar_flush(phar_obj->arc.archive, NULL, 0, 0, &error TSRMLS_CC); if (error) { phar_obj->arc.archive->alias = oldalias; phar_obj->arc.archive->alias_len = oldalias_len; phar_obj->arc.archive->is_temporary_alias = old_temp; zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); if (readd) { zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), oldalias, oldalias_len, (void*)&(phar_obj->arc.archive), sizeof(phar_archive_data*), NULL); } efree(error); RETURN_FALSE; } zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&(phar_obj->arc.archive), sizeof(phar_archive_data*), NULL); if (oldalias) { efree(oldalias); } RETURN_TRUE; } RETURN_FALSE; } /* }}} */ /* {{{ proto string Phar::getVersion() * Return version info of Phar archive */ PHP_METHOD(Phar, getVersion) { PHAR_ARCHIVE_OBJECT(); RETURN_STRING(phar_obj->arc.archive->version, 1); } /* }}} */ /* {{{ proto void Phar::startBuffering() * Do not flush a writeable phar (save its contents) until explicitly requested */ PHP_METHOD(Phar, startBuffering) { PHAR_ARCHIVE_OBJECT(); phar_obj->arc.archive->donotflush = 1; } /* }}} */ /* {{{ proto bool Phar::isBuffering() * Returns whether write operations are flushing to disk immediately. */ PHP_METHOD(Phar, isBuffering) { PHAR_ARCHIVE_OBJECT(); RETURN_BOOL(phar_obj->arc.archive->donotflush); } /* }}} */ /* {{{ proto bool Phar::stopBuffering() * Saves the contents of a modified archive to disk. */ PHP_METHOD(Phar, stopBuffering) { char *error; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot write out phar archive, phar is read-only"); return; } phar_obj->arc.archive->donotflush = 0; phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } } /* }}} */ /* {{{ proto bool Phar::setStub(string|stream stub [, int len]) * Change the stub in a phar, phar.tar or phar.zip archive to something other * than the default. The stub *must* end with a call to __HALT_COMPILER(). */ PHP_METHOD(Phar, setStub) { zval *zstub; char *stub, *error; int stub_len; long len = -1; php_stream *stream; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot change stub, phar is read-only"); return; } if (phar_obj->arc.archive->is_data) { if (phar_obj->arc.archive->is_tar) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "A Phar stub cannot be set in a plain tar archive"); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "A Phar stub cannot be set in a plain zip archive"); } return; } if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r|l", &zstub, &len) == SUCCESS) { if ((php_stream_from_zval_no_verify(stream, &zstub)) != NULL) { if (len > 0) { len = -len; } else { len = -1; } if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } phar_flush(phar_obj->arc.archive, (char *) &zstub, len, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } RETURN_TRUE; } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot change stub, unable to read from input stream"); } } else if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &stub, &stub_len) == SUCCESS) { if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } phar_flush(phar_obj->arc.archive, stub, stub_len, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } RETURN_TRUE; } RETURN_FALSE; } /* }}} */ /* {{{ proto bool Phar::setDefaultStub([string index[, string webindex]]) * In a pure phar archive, sets a stub that can be used to run the archive * regardless of whether the phar extension is available. The first parameter * is the CLI startup filename, which defaults to "index.php". The second * parameter is the web startup filename and also defaults to "index.php" * (falling back to CLI behaviour). * Both parameters are optional. * In a phar.zip or phar.tar archive, the default stub is used only to * identify the archive to the extension as a Phar object. This allows the * extension to treat phar.zip and phar.tar types as honorary phars. Since * files cannot be loaded via this kind of stub, no parameters are accepted * when the Phar object is zip- or tar-based. */ PHP_METHOD(Phar, setDefaultStub) { char *index = NULL, *webindex = NULL, *error = NULL, *stub = NULL; int index_len = 0, webindex_len = 0, created_stub = 0; size_t stub_len = 0; PHAR_ARCHIVE_OBJECT(); if (phar_obj->arc.archive->is_data) { if (phar_obj->arc.archive->is_tar) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "A Phar stub cannot be set in a plain tar archive"); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "A Phar stub cannot be set in a plain zip archive"); } return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!s", &index, &index_len, &webindex, &webindex_len) == FAILURE) { RETURN_FALSE; } if (ZEND_NUM_ARGS() > 0 && (phar_obj->arc.archive->is_tar || phar_obj->arc.archive->is_zip)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "method accepts no arguments for a tar- or zip-based phar stub, %d given", ZEND_NUM_ARGS()); RETURN_FALSE; } if (PHAR_G(readonly)) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot change stub: phar.readonly=1"); RETURN_FALSE; } if (!phar_obj->arc.archive->is_tar && !phar_obj->arc.archive->is_zip) { stub = phar_create_default_stub(index, webindex, &stub_len, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "%s", error); efree(error); if (stub) { efree(stub); } RETURN_FALSE; } created_stub = 1; } if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } phar_flush(phar_obj->arc.archive, stub, stub_len, 1, &error TSRMLS_CC); if (created_stub) { efree(stub); } if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto array Phar::setSignatureAlgorithm(int sigtype[, string privatekey]) * Sets the signature algorithm for a phar and applies it. The signature * algorithm must be one of Phar::MD5, Phar::SHA1, Phar::SHA256, * Phar::SHA512, or Phar::OPENSSL. Note that zip- based phar archives * cannot support signatures. */ PHP_METHOD(Phar, setSignatureAlgorithm) { long algo; char *error, *key = NULL; int key_len = 0; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot set signature algorithm, phar is read-only"); return; } if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "l|s", &algo, &key, &key_len) != SUCCESS) { return; } switch (algo) { case PHAR_SIG_SHA256: case PHAR_SIG_SHA512: #ifndef PHAR_HASH_OK zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "SHA-256 and SHA-512 signatures are only supported if the hash extension is enabled and built non-shared"); return; #endif case PHAR_SIG_MD5: case PHAR_SIG_SHA1: case PHAR_SIG_OPENSSL: if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } phar_obj->arc.archive->sig_flags = algo; phar_obj->arc.archive->is_modified = 1; PHAR_G(openssl_privatekey) = key; PHAR_G(openssl_privatekey_len) = key_len; phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } break; default: zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Unknown signature algorithm specified"); } } /* }}} */ /* {{{ proto array|false Phar::getSignature() * Returns a hash signature, or FALSE if the archive is unsigned. */ PHP_METHOD(Phar, getSignature) { PHAR_ARCHIVE_OBJECT(); if (phar_obj->arc.archive->signature) { char *unknown; int unknown_len; array_init(return_value); add_assoc_stringl(return_value, "hash", phar_obj->arc.archive->signature, phar_obj->arc.archive->sig_len, 1); switch(phar_obj->arc.archive->sig_flags) { case PHAR_SIG_MD5: add_assoc_stringl(return_value, "hash_type", "MD5", 3, 1); break; case PHAR_SIG_SHA1: add_assoc_stringl(return_value, "hash_type", "SHA-1", 5, 1); break; case PHAR_SIG_SHA256: add_assoc_stringl(return_value, "hash_type", "SHA-256", 7, 1); break; case PHAR_SIG_SHA512: add_assoc_stringl(return_value, "hash_type", "SHA-512", 7, 1); break; case PHAR_SIG_OPENSSL: add_assoc_stringl(return_value, "hash_type", "OpenSSL", 7, 1); break; default: unknown_len = spprintf(&unknown, 0, "Unknown (%u)", phar_obj->arc.archive->sig_flags); add_assoc_stringl(return_value, "hash_type", unknown, unknown_len, 0); break; } } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool Phar::getModified() * Return whether phar was modified */ PHP_METHOD(Phar, getModified) { PHAR_ARCHIVE_OBJECT(); RETURN_BOOL(phar_obj->arc.archive->is_modified); } /* }}} */ static int phar_set_compression(void *pDest, void *argument TSRMLS_DC) /* {{{ */ { phar_entry_info *entry = (phar_entry_info *)pDest; php_uint32 compress = *(php_uint32 *)argument; if (entry->is_deleted) { return ZEND_HASH_APPLY_KEEP; } entry->old_flags = entry->flags; entry->flags &= ~PHAR_ENT_COMPRESSION_MASK; entry->flags |= compress; entry->is_modified = 1; return ZEND_HASH_APPLY_KEEP; } /* }}} */ static int phar_test_compression(void *pDest, void *argument TSRMLS_DC) /* {{{ */ { phar_entry_info *entry = (phar_entry_info *)pDest; if (entry->is_deleted) { return ZEND_HASH_APPLY_KEEP; } if (!PHAR_G(has_bz2)) { if (entry->flags & PHAR_ENT_COMPRESSED_BZ2) { *(int *) argument = 0; } } if (!PHAR_G(has_zlib)) { if (entry->flags & PHAR_ENT_COMPRESSED_GZ) { *(int *) argument = 0; } } return ZEND_HASH_APPLY_KEEP; } /* }}} */ static void pharobj_set_compression(HashTable *manifest, php_uint32 compress TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_argument(manifest, phar_set_compression, &compress TSRMLS_CC); } /* }}} */ static int pharobj_cancompress(HashTable *manifest TSRMLS_DC) /* {{{ */ { int test; test = 1; zend_hash_apply_with_argument(manifest, phar_test_compression, &test TSRMLS_CC); return test; } /* }}} */ /* {{{ proto object Phar::compress(int method[, string extension]) * Compress a .tar, or .phar.tar with whole-file compression * The parameter can be one of Phar::GZ or Phar::BZ2 to specify * the kind of compression desired */ PHP_METHOD(Phar, compress) { long method; char *ext = NULL; int ext_len = 0; php_uint32 flags; zval *ret; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|s", &method, &ext, &ext_len) == FAILURE) { return; } if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot compress phar archive, phar is read-only"); return; } if (phar_obj->arc.archive->is_zip) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot compress zip-based archives with whole-archive compression"); return; } switch (method) { case 0: flags = PHAR_FILE_COMPRESSED_NONE; break; case PHAR_ENT_COMPRESSED_GZ: if (!PHAR_G(has_zlib)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress entire archive with gzip, enable ext/zlib in php.ini"); return; } flags = PHAR_FILE_COMPRESSED_GZ; break; case PHAR_ENT_COMPRESSED_BZ2: if (!PHAR_G(has_bz2)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress entire archive with bz2, enable ext/bz2 in php.ini"); return; } flags = PHAR_FILE_COMPRESSED_BZ2; break; default: zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unknown compression specified, please pass one of Phar::GZ or Phar::BZ2"); return; } if (phar_obj->arc.archive->is_tar) { ret = phar_convert_to_other(phar_obj->arc.archive, PHAR_FORMAT_TAR, ext, flags TSRMLS_CC); } else { ret = phar_convert_to_other(phar_obj->arc.archive, PHAR_FORMAT_PHAR, ext, flags TSRMLS_CC); } if (ret) { RETURN_ZVAL(ret, 1, 1); } else { RETURN_NULL(); } } /* }}} */ /* {{{ proto object Phar::decompress([string extension]) * Decompress a .tar, or .phar.tar with whole-file compression */ PHP_METHOD(Phar, decompress) { char *ext = NULL; int ext_len = 0; zval *ret; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &ext, &ext_len) == FAILURE) { return; } if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot decompress phar archive, phar is read-only"); return; } if (phar_obj->arc.archive->is_zip) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot decompress zip-based archives with whole-archive compression"); return; } if (phar_obj->arc.archive->is_tar) { ret = phar_convert_to_other(phar_obj->arc.archive, PHAR_FORMAT_TAR, ext, PHAR_FILE_COMPRESSED_NONE TSRMLS_CC); } else { ret = phar_convert_to_other(phar_obj->arc.archive, PHAR_FORMAT_PHAR, ext, PHAR_FILE_COMPRESSED_NONE TSRMLS_CC); } if (ret) { RETURN_ZVAL(ret, 1, 1); } else { RETURN_NULL(); } } /* }}} */ /* {{{ proto object Phar::compressFiles(int method) * Compress all files within a phar or zip archive using the specified compression * The parameter can be one of Phar::GZ or Phar::BZ2 to specify * the kind of compression desired */ PHP_METHOD(Phar, compressFiles) { char *error; php_uint32 flags; long method; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &method) == FAILURE) { return; } if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Phar is readonly, cannot change compression"); return; } switch (method) { case PHAR_ENT_COMPRESSED_GZ: if (!PHAR_G(has_zlib)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress files within archive with gzip, enable ext/zlib in php.ini"); return; } flags = PHAR_ENT_COMPRESSED_GZ; break; case PHAR_ENT_COMPRESSED_BZ2: if (!PHAR_G(has_bz2)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress files within archive with bz2, enable ext/bz2 in php.ini"); return; } flags = PHAR_ENT_COMPRESSED_BZ2; break; default: zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unknown compression specified, please pass one of Phar::GZ or Phar::BZ2"); return; } if (phar_obj->arc.archive->is_tar) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress with Gzip compression, tar archives cannot compress individual files, use compress() to compress the whole archive"); return; } if (!pharobj_cancompress(&phar_obj->arc.archive->manifest TSRMLS_CC)) { if (flags == PHAR_FILE_COMPRESSED_GZ) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress all files as Gzip, some are compressed as bzip2 and cannot be decompressed"); } else { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress all files as Bzip2, some are compressed as gzip and cannot be decompressed"); } return; } if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } pharobj_set_compression(&phar_obj->arc.archive->manifest, flags TSRMLS_CC); phar_obj->arc.archive->is_modified = 1; phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "%s", error); efree(error); } } /* }}} */ /* {{{ proto bool Phar::decompressFiles() * decompress every file */ PHP_METHOD(Phar, decompressFiles) { char *error; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Phar is readonly, cannot change compression"); return; } if (!pharobj_cancompress(&phar_obj->arc.archive->manifest TSRMLS_CC)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot decompress all files, some are compressed as bzip2 or gzip and cannot be decompressed"); return; } if (phar_obj->arc.archive->is_tar) { RETURN_TRUE; } else { if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } pharobj_set_compression(&phar_obj->arc.archive->manifest, PHAR_ENT_COMPRESSED_NONE TSRMLS_CC); } phar_obj->arc.archive->is_modified = 1; phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "%s", error); efree(error); } RETURN_TRUE; } /* }}} */ /* {{{ proto bool Phar::copy(string oldfile, string newfile) * copy a file internal to the phar archive to another new file within the phar */ PHP_METHOD(Phar, copy) { char *oldfile, *newfile, *error; const char *pcr_error; int oldfile_len, newfile_len; phar_entry_info *oldentry, newentry = {0}, *temp; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &oldfile, &oldfile_len, &newfile, &newfile_len) == FAILURE) { return; } if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot copy \"%s\" to \"%s\", phar is read-only", oldfile, newfile); RETURN_FALSE; } if (oldfile_len >= sizeof(".phar")-1 && !memcmp(oldfile, ".phar", sizeof(".phar")-1)) { /* can't copy a meta file */ zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "file \"%s\" cannot be copied to file \"%s\", cannot copy Phar meta-file in %s", oldfile, newfile, phar_obj->arc.archive->fname); RETURN_FALSE; } if (newfile_len >= sizeof(".phar")-1 && !memcmp(newfile, ".phar", sizeof(".phar")-1)) { /* can't copy a meta file */ zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "file \"%s\" cannot be copied to file \"%s\", cannot copy to Phar meta-file in %s", oldfile, newfile, phar_obj->arc.archive->fname); RETURN_FALSE; } if (!zend_hash_exists(&phar_obj->arc.archive->manifest, oldfile, (uint) oldfile_len) || SUCCESS != zend_hash_find(&phar_obj->arc.archive->manifest, oldfile, (uint) oldfile_len, (void**)&oldentry) || oldentry->is_deleted) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "file \"%s\" cannot be copied to file \"%s\", file does not exist in %s", oldfile, newfile, phar_obj->arc.archive->fname); RETURN_FALSE; } if (zend_hash_exists(&phar_obj->arc.archive->manifest, newfile, (uint) newfile_len)) { if (SUCCESS == zend_hash_find(&phar_obj->arc.archive->manifest, newfile, (uint) newfile_len, (void**)&temp) || !temp->is_deleted) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "file \"%s\" cannot be copied to file \"%s\", file must not already exist in phar %s", oldfile, newfile, phar_obj->arc.archive->fname); RETURN_FALSE; } } if (phar_path_check(&newfile, &newfile_len, &pcr_error) > pcr_is_ok) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "file \"%s\" contains invalid characters %s, cannot be copied from \"%s\" in phar %s", newfile, pcr_error, oldfile, phar_obj->arc.archive->fname); RETURN_FALSE; } if (phar_obj->arc.archive->is_persistent) { if (FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } /* re-populate with copied-on-write entry */ zend_hash_find(&phar_obj->arc.archive->manifest, oldfile, (uint) oldfile_len, (void**)&oldentry); } memcpy((void *) &newentry, oldentry, sizeof(phar_entry_info)); if (newentry.metadata) { zval *t; t = newentry.metadata; ALLOC_ZVAL(newentry.metadata); *newentry.metadata = *t; zval_copy_ctor(newentry.metadata); #if PHP_VERSION_ID < 50300 newentry.metadata->refcount = 1; #else Z_SET_REFCOUNT_P(newentry.metadata, 1); #endif newentry.metadata_str.c = NULL; newentry.metadata_str.len = 0; } newentry.filename = estrndup(newfile, newfile_len); newentry.filename_len = newfile_len; newentry.fp_refcount = 0; if (oldentry->fp_type != PHAR_FP) { if (FAILURE == phar_copy_entry_fp(oldentry, &newentry, &error TSRMLS_CC)) { efree(newentry.filename); php_stream_close(newentry.fp); zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); return; } } zend_hash_add(&oldentry->phar->manifest, newfile, newfile_len, (void*)&newentry, sizeof(phar_entry_info), NULL); phar_obj->arc.archive->is_modified = 1; phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } RETURN_TRUE; } /* }}} */ /* {{{ proto int Phar::offsetExists(string entry) * determines whether a file exists in the phar */ PHP_METHOD(Phar, offsetExists) { char *fname; int fname_len; phar_entry_info *entry; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &fname, &fname_len) == FAILURE) { return; } if (zend_hash_exists(&phar_obj->arc.archive->manifest, fname, (uint) fname_len)) { if (SUCCESS == zend_hash_find(&phar_obj->arc.archive->manifest, fname, (uint) fname_len, (void**)&entry)) { if (entry->is_deleted) { /* entry is deleted, but has not been flushed to disk yet */ RETURN_FALSE; } } if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) { /* none of these are real files, so they don't exist */ RETURN_FALSE; } RETURN_TRUE; } else { if (zend_hash_exists(&phar_obj->arc.archive->virtual_dirs, fname, (uint) fname_len)) { RETURN_TRUE; } RETURN_FALSE; } } /* }}} */ /* {{{ proto int Phar::offsetGet(string entry) * get a PharFileInfo object for a specific file */ PHP_METHOD(Phar, offsetGet) { char *fname, *error; int fname_len; zval *zfname; phar_entry_info *entry; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &fname, &fname_len) == FAILURE) { return; } /* security is 0 here so that we can get a better error message than "entry doesn't exist" */ if (!(entry = phar_get_entry_info_dir(phar_obj->arc.archive, fname, fname_len, 1, &error, 0 TSRMLS_CC))) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s does not exist%s%s", fname, error?", ":"", error?error:""); } else { if (fname_len == sizeof(".phar/stub.php")-1 && !memcmp(fname, ".phar/stub.php", sizeof(".phar/stub.php")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot get stub \".phar/stub.php\" directly in phar \"%s\", use getStub", phar_obj->arc.archive->fname); return; } if (fname_len == sizeof(".phar/alias.txt")-1 && !memcmp(fname, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot get alias \".phar/alias.txt\" directly in phar \"%s\", use getAlias", phar_obj->arc.archive->fname); return; } if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot directly get any files or directories in magic \".phar\" directory", phar_obj->arc.archive->fname); return; } if (entry->is_temp_dir) { efree(entry->filename); efree(entry); } fname_len = spprintf(&fname, 0, "phar://%s/%s", phar_obj->arc.archive->fname, fname); MAKE_STD_ZVAL(zfname); ZVAL_STRINGL(zfname, fname, fname_len, 0); spl_instantiate_arg_ex1(phar_obj->spl.info_class, &return_value, 0, zfname TSRMLS_CC); zval_ptr_dtor(&zfname); } } /* }}} */ /* {{{ add a file within the phar archive from a string or resource */ static void phar_add_file(phar_archive_data **pphar, char *filename, int filename_len, char *cont_str, int cont_len, zval *zresource TSRMLS_DC) { char *error; size_t contents_len; phar_entry_data *data; php_stream *contents_file; if (filename_len >= sizeof(".phar")-1 && !memcmp(filename, ".phar", sizeof(".phar")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot create any files in magic \".phar\" directory", (*pphar)->fname); return; } if (!(data = phar_get_or_create_entry_data((*pphar)->fname, (*pphar)->fname_len, filename, filename_len, "w+b", 0, &error, 1 TSRMLS_CC))) { if (error) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s does not exist and cannot be created: %s", filename, error); efree(error); } else { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s does not exist and cannot be created", filename); } return; } else { if (error) { efree(error); } if (!data->internal_file->is_dir) { if (cont_str) { contents_len = php_stream_write(data->fp, cont_str, cont_len); if (contents_len != cont_len) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s could not be written to", filename); return; } } else { if (!(php_stream_from_zval_no_verify(contents_file, &zresource))) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s could not be written to", filename); return; } phar_stream_copy_to_stream(contents_file, data->fp, PHP_STREAM_COPY_ALL, &contents_len); } data->internal_file->compressed_filesize = data->internal_file->uncompressed_filesize = contents_len; } /* check for copy-on-write */ if (pphar[0] != data->phar) { *pphar = data->phar; } phar_entry_delref(data TSRMLS_CC); phar_flush(*pphar, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } } } /* }}} */ /* {{{ create a directory within the phar archive */ static void phar_mkdir(phar_archive_data **pphar, char *dirname, int dirname_len TSRMLS_DC) { char *error; phar_entry_data *data; if (!(data = phar_get_or_create_entry_data((*pphar)->fname, (*pphar)->fname_len, dirname, dirname_len, "w+b", 2, &error, 1 TSRMLS_CC))) { if (error) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Directory %s does not exist and cannot be created: %s", dirname, error); efree(error); } else { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Directory %s does not exist and cannot be created", dirname); } return; } else { if (error) { efree(error); } /* check for copy on write */ if (data->phar != *pphar) { *pphar = data->phar; } phar_entry_delref(data TSRMLS_CC); phar_flush(*pphar, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } } } /* }}} */ /* {{{ proto int Phar::offsetSet(string entry, string value) * set the contents of an internal file to those of an external file */ PHP_METHOD(Phar, offsetSet) { char *fname, *cont_str = NULL; int fname_len, cont_len; zval *zresource; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Write operations disabled by the php.ini setting phar.readonly"); return; } if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "sr", &fname, &fname_len, &zresource) == FAILURE && zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &fname, &fname_len, &cont_str, &cont_len) == FAILURE) { return; } if (fname_len == sizeof(".phar/stub.php")-1 && !memcmp(fname, ".phar/stub.php", sizeof(".phar/stub.php")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot set stub \".phar/stub.php\" directly in phar \"%s\", use setStub", phar_obj->arc.archive->fname); return; } if (fname_len == sizeof(".phar/alias.txt")-1 && !memcmp(fname, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot set alias \".phar/alias.txt\" directly in phar \"%s\", use setAlias", phar_obj->arc.archive->fname); return; } if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot set any files or directories in magic \".phar\" directory", phar_obj->arc.archive->fname); return; } phar_add_file(&(phar_obj->arc.archive), fname, fname_len, cont_str, cont_len, zresource TSRMLS_CC); } /* }}} */ /* {{{ proto int Phar::offsetUnset(string entry) * remove a file from a phar */ PHP_METHOD(Phar, offsetUnset) { char *fname, *error; int fname_len; phar_entry_info *entry; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Write operations disabled by the php.ini setting phar.readonly"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &fname, &fname_len) == FAILURE) { return; } if (zend_hash_exists(&phar_obj->arc.archive->manifest, fname, (uint) fname_len)) { if (SUCCESS == zend_hash_find(&phar_obj->arc.archive->manifest, fname, (uint) fname_len, (void**)&entry)) { if (entry->is_deleted) { /* entry is deleted, but has not been flushed to disk yet */ return; } if (phar_obj->arc.archive->is_persistent) { if (FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } /* re-populate entry after copy on write */ zend_hash_find(&phar_obj->arc.archive->manifest, fname, (uint) fname_len, (void **)&entry); } entry->is_modified = 0; entry->is_deleted = 1; /* we need to "flush" the stream to save the newly deleted file on disk */ phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } RETURN_TRUE; } } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto string Phar::addEmptyDir(string dirname) * Adds an empty directory to the phar archive */ PHP_METHOD(Phar, addEmptyDir) { char *dirname; int dirname_len; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &dirname, &dirname_len) == FAILURE) { return; } if (dirname_len >= sizeof(".phar")-1 && !memcmp(dirname, ".phar", sizeof(".phar")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot create a directory in magic \".phar\" directory"); return; } phar_mkdir(&phar_obj->arc.archive, dirname, dirname_len TSRMLS_CC); } /* }}} */ /* {{{ proto string Phar::addFile(string filename[, string localname]) * Adds a file to the archive using the filename, or the second parameter as the name within the archive */ PHP_METHOD(Phar, addFile) { char *fname, *localname = NULL; int fname_len, localname_len = 0; php_stream *resource; zval *zresource; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &fname, &fname_len, &localname, &localname_len) == FAILURE) { return; } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "phar error: unable to open file \"%s\" to add to phar archive, safe_mode restrictions prevent this", fname); return; } #endif if (!strstr(fname, "://") && php_check_open_basedir(fname TSRMLS_CC)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "phar error: unable to open file \"%s\" to add to phar archive, open_basedir restrictions prevent this", fname); return; } if (!(resource = php_stream_open_wrapper(fname, "rb", 0, NULL))) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "phar error: unable to open file \"%s\" to add to phar archive", fname); return; } if (localname) { fname = localname; fname_len = localname_len; } MAKE_STD_ZVAL(zresource); php_stream_to_zval(resource, zresource); phar_add_file(&(phar_obj->arc.archive), fname, fname_len, NULL, 0, zresource TSRMLS_CC); efree(zresource); php_stream_close(resource); } /* }}} */ /* {{{ proto string Phar::addFromString(string localname, string contents) * Adds a file to the archive using its contents as a string */ PHP_METHOD(Phar, addFromString) { char *localname, *cont_str; int localname_len, cont_len; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &localname, &localname_len, &cont_str, &cont_len) == FAILURE) { return; } phar_add_file(&(phar_obj->arc.archive), localname, localname_len, cont_str, cont_len, NULL TSRMLS_CC); } /* }}} */ /* {{{ proto string Phar::getStub() * Returns the stub at the head of a phar archive as a string. */ PHP_METHOD(Phar, getStub) { size_t len; char *buf; php_stream *fp; php_stream_filter *filter = NULL; phar_entry_info *stub; PHAR_ARCHIVE_OBJECT(); if (phar_obj->arc.archive->is_tar || phar_obj->arc.archive->is_zip) { if (SUCCESS == zend_hash_find(&(phar_obj->arc.archive->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1, (void **)&stub)) { if (phar_obj->arc.archive->fp && !phar_obj->arc.archive->is_brandnew && !(stub->flags & PHAR_ENT_COMPRESSION_MASK)) { fp = phar_obj->arc.archive->fp; } else { fp = php_stream_open_wrapper(phar_obj->arc.archive->fname, "rb", 0, NULL); if (stub->flags & PHAR_ENT_COMPRESSION_MASK) { char *filter_name; if ((filter_name = phar_decompress_filter(stub, 0)) != NULL) { filter = php_stream_filter_create(filter_name, NULL, php_stream_is_persistent(fp) TSRMLS_CC); } else { filter = NULL; } if (!filter) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "phar error: unable to read stub of phar \"%s\" (cannot create %s filter)", phar_obj->arc.archive->fname, phar_decompress_filter(stub, 1)); return; } php_stream_filter_append(&fp->readfilters, filter); } } if (!fp) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Unable to read stub"); return; } php_stream_seek(fp, stub->offset_abs, SEEK_SET); len = stub->uncompressed_filesize; goto carry_on; } else { RETURN_STRINGL("", 0, 1); } } len = phar_obj->arc.archive->halt_offset; if (phar_obj->arc.archive->fp && !phar_obj->arc.archive->is_brandnew) { fp = phar_obj->arc.archive->fp; } else { fp = php_stream_open_wrapper(phar_obj->arc.archive->fname, "rb", 0, NULL); } if (!fp) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Unable to read stub"); return; } php_stream_rewind(fp); carry_on: buf = safe_emalloc(len, 1, 1); if (len != php_stream_read(fp, buf, len)) { if (fp != phar_obj->arc.archive->fp) { php_stream_close(fp); } zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Unable to read stub"); efree(buf); return; } if (filter) { php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); } if (fp != phar_obj->arc.archive->fp) { php_stream_close(fp); } buf[len] = '\0'; RETURN_STRINGL(buf, len, 0); } /* }}}*/ /* {{{ proto int Phar::hasMetaData() * Returns TRUE if the phar has global metadata, FALSE otherwise. */ PHP_METHOD(Phar, hasMetadata) { PHAR_ARCHIVE_OBJECT(); RETURN_BOOL(phar_obj->arc.archive->metadata != NULL); } /* }}} */ /* {{{ proto int Phar::getMetaData() * Returns the global metadata of the phar */ PHP_METHOD(Phar, getMetadata) { PHAR_ARCHIVE_OBJECT(); if (phar_obj->arc.archive->metadata) { if (phar_obj->arc.archive->is_persistent) { zval *ret; char *buf = estrndup((char *) phar_obj->arc.archive->metadata, phar_obj->arc.archive->metadata_len); /* assume success, we would have failed before */ phar_parse_metadata(&buf, &ret, phar_obj->arc.archive->metadata_len TSRMLS_CC); efree(buf); RETURN_ZVAL(ret, 0, 1); } RETURN_ZVAL(phar_obj->arc.archive->metadata, 1, 0); } } /* }}} */ /* {{{ proto int Phar::setMetaData(mixed $metadata) * Sets the global metadata of the phar */ PHP_METHOD(Phar, setMetadata) { char *error; zval *metadata; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Write operations disabled by the php.ini setting phar.readonly"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &metadata) == FAILURE) { return; } if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } if (phar_obj->arc.archive->metadata) { zval_ptr_dtor(&phar_obj->arc.archive->metadata); phar_obj->arc.archive->metadata = NULL; } MAKE_STD_ZVAL(phar_obj->arc.archive->metadata); ZVAL_ZVAL(phar_obj->arc.archive->metadata, metadata, 1, 0); phar_obj->arc.archive->is_modified = 1; phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } } /* }}} */ /* {{{ proto int Phar::delMetadata() * Deletes the global metadata of the phar */ PHP_METHOD(Phar, delMetadata) { char *error; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Write operations disabled by the php.ini setting phar.readonly"); return; } if (phar_obj->arc.archive->metadata) { zval_ptr_dtor(&phar_obj->arc.archive->metadata); phar_obj->arc.archive->metadata = NULL; phar_obj->arc.archive->is_modified = 1; phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); RETURN_FALSE; } else { RETURN_TRUE; } } else { RETURN_TRUE; } } /* }}} */ #if PHP_API_VERSION < 20100412 #define PHAR_OPENBASEDIR_CHECKPATH(filename) \ (PG(safe_mode) && (!php_checkuid(filename, NULL, CHECKUID_CHECK_FILE_AND_DIR))) || php_check_open_basedir(filename TSRMLS_CC) #else #define PHAR_OPENBASEDIR_CHECKPATH(filename) \ php_check_open_basedir(filename TSRMLS_CC) #endif static int phar_extract_file(zend_bool overwrite, phar_entry_info *entry, char *dest, int dest_len, char **error TSRMLS_DC) /* {{{ */ { php_stream_statbuf ssb; int len; php_stream *fp; char *fullpath; const char *slash; mode_t mode; if (entry->is_mounted) { /* silently ignore mounted entries */ return SUCCESS; } if (entry->filename_len >= sizeof(".phar")-1 && !memcmp(entry->filename, ".phar", sizeof(".phar")-1)) { return SUCCESS; } len = spprintf(&fullpath, 0, "%s/%s", dest, entry->filename); if (len >= MAXPATHLEN) { char *tmp; /* truncate for error message */ fullpath[50] = '\0'; if (entry->filename_len > 50) { tmp = estrndup(entry->filename, 50); spprintf(error, 4096, "Cannot extract \"%s...\" to \"%s...\", extracted filename is too long for filesystem", tmp, fullpath); efree(tmp); } else { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s...\", extracted filename is too long for filesystem", entry->filename, fullpath); } efree(fullpath); return FAILURE; } if (!len) { spprintf(error, 4096, "Cannot extract \"%s\", internal error", entry->filename); efree(fullpath); return FAILURE; } if (PHAR_OPENBASEDIR_CHECKPATH(fullpath)) { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", openbasedir/safe mode restrictions in effect", entry->filename, fullpath); efree(fullpath); return FAILURE; } /* let see if the path already exists */ if (!overwrite && SUCCESS == php_stream_stat_path(fullpath, &ssb)) { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", path already exists", entry->filename, fullpath); efree(fullpath); return FAILURE; } /* perform dirname */ slash = zend_memrchr(entry->filename, '/', entry->filename_len); if (slash) { fullpath[dest_len + (slash - entry->filename) + 1] = '\0'; } else { fullpath[dest_len] = '\0'; } if (FAILURE == php_stream_stat_path(fullpath, &ssb)) { if (entry->is_dir) { if (!php_stream_mkdir(fullpath, entry->flags & PHAR_ENT_PERM_MASK, PHP_STREAM_MKDIR_RECURSIVE, NULL)) { spprintf(error, 4096, "Cannot extract \"%s\", could not create directory \"%s\"", entry->filename, fullpath); efree(fullpath); return FAILURE; } } else { if (!php_stream_mkdir(fullpath, 0777, PHP_STREAM_MKDIR_RECURSIVE, NULL)) { spprintf(error, 4096, "Cannot extract \"%s\", could not create directory \"%s\"", entry->filename, fullpath); efree(fullpath); return FAILURE; } } } if (slash) { fullpath[dest_len + (slash - entry->filename) + 1] = '/'; } else { fullpath[dest_len] = '/'; } /* it is a standalone directory, job done */ if (entry->is_dir) { efree(fullpath); return SUCCESS; } #if PHP_API_VERSION < 20100412 fp = php_stream_open_wrapper(fullpath, "w+b", REPORT_ERRORS|ENFORCE_SAFE_MODE, NULL); #else fp = php_stream_open_wrapper(fullpath, "w+b", REPORT_ERRORS, NULL); #endif if (!fp) { spprintf(error, 4096, "Cannot extract \"%s\", could not open for writing \"%s\"", entry->filename, fullpath); efree(fullpath); return FAILURE; } if (!phar_get_efp(entry, 0 TSRMLS_CC)) { if (FAILURE == phar_open_entry_fp(entry, error, 1 TSRMLS_CC)) { if (error) { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", unable to open internal file pointer: %s", entry->filename, fullpath, *error); } else { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", unable to open internal file pointer", entry->filename, fullpath); } efree(fullpath); php_stream_close(fp); return FAILURE; } } if (FAILURE == phar_seek_efp(entry, 0, SEEK_SET, 0, 0 TSRMLS_CC)) { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", unable to seek internal file pointer", entry->filename, fullpath); efree(fullpath); php_stream_close(fp); return FAILURE; } if (SUCCESS != phar_stream_copy_to_stream(phar_get_efp(entry, 0 TSRMLS_CC), fp, entry->uncompressed_filesize, NULL)) { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", copying contents failed", entry->filename, fullpath); efree(fullpath); php_stream_close(fp); return FAILURE; } php_stream_close(fp); mode = (mode_t) entry->flags & PHAR_ENT_PERM_MASK; if (FAILURE == VCWD_CHMOD(fullpath, mode)) { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", setting file permissions failed", entry->filename, fullpath); efree(fullpath); return FAILURE; } efree(fullpath); return SUCCESS; } /* }}} */ /* {{{ proto bool Phar::extractTo(string pathto[[, mixed files], bool overwrite]) * Extract one or more file from a phar archive, optionally overwriting existing files */ PHP_METHOD(Phar, extractTo) { char *error = NULL; php_stream *fp; php_stream_statbuf ssb; phar_entry_info *entry; char *pathto, *filename, *actual; int pathto_len, filename_len; int ret, i; int nelems; zval *zval_files = NULL; zend_bool overwrite = 0; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|z!b", &pathto, &pathto_len, &zval_files, &overwrite) == FAILURE) { return; } fp = php_stream_open_wrapper(phar_obj->arc.archive->fname, "rb", IGNORE_URL|STREAM_MUST_SEEK, &actual); if (!fp) { zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0 TSRMLS_CC, "Invalid argument, %s cannot be found", phar_obj->arc.archive->fname); return; } efree(actual); php_stream_close(fp); if (pathto_len < 1) { zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0 TSRMLS_CC, "Invalid argument, extraction path must be non-zero length"); return; } if (pathto_len >= MAXPATHLEN) { char *tmp = estrndup(pathto, 50); /* truncate for error message */ zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0 TSRMLS_CC, "Cannot extract to \"%s...\", destination directory is too long for filesystem", tmp); efree(tmp); return; } if (php_stream_stat_path(pathto, &ssb) < 0) { ret = php_stream_mkdir(pathto, 0777, PHP_STREAM_MKDIR_RECURSIVE, NULL); if (!ret) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Unable to create path \"%s\" for extraction", pathto); return; } } else if (!(ssb.sb.st_mode & S_IFDIR)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Unable to use path \"%s\" for extraction, it is a file, must be a directory", pathto); return; } if (zval_files) { switch (Z_TYPE_P(zval_files)) { case IS_NULL: goto all_files; #if PHP_VERSION_ID >= 60000 case IS_UNICODE: zval_unicode_to_string(zval_files TSRMLS_CC); /* break intentionally omitted */ #endif case IS_STRING: filename = Z_STRVAL_P(zval_files); filename_len = Z_STRLEN_P(zval_files); break; case IS_ARRAY: nelems = zend_hash_num_elements(Z_ARRVAL_P(zval_files)); if (nelems == 0 ) { RETURN_FALSE; } for (i = 0; i < nelems; i++) { zval **zval_file; if (zend_hash_index_find(Z_ARRVAL_P(zval_files), i, (void **) &zval_file) == SUCCESS) { switch (Z_TYPE_PP(zval_file)) { #if PHP_VERSION_ID >= 60000 case IS_UNICODE: zval_unicode_to_string(*(zval_file) TSRMLS_CC); /* break intentionally omitted */ #endif case IS_STRING: break; default: zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0 TSRMLS_CC, "Invalid argument, array of filenames to extract contains non-string value"); return; } if (FAILURE == zend_hash_find(&phar_obj->arc.archive->manifest, Z_STRVAL_PP(zval_file), Z_STRLEN_PP(zval_file), (void **)&entry)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Phar Error: attempted to extract non-existent file \"%s\" from phar \"%s\"", Z_STRVAL_PP(zval_file), phar_obj->arc.archive->fname); } if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, &error TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Extraction from phar \"%s\" failed: %s", phar_obj->arc.archive->fname, error); efree(error); return; } } } RETURN_TRUE; default: zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0 TSRMLS_CC, "Invalid argument, expected a filename (string) or array of filenames"); return; } if (FAILURE == zend_hash_find(&phar_obj->arc.archive->manifest, filename, filename_len, (void **)&entry)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Phar Error: attempted to extract non-existent file \"%s\" from phar \"%s\"", filename, phar_obj->arc.archive->fname); return; } if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, &error TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Extraction from phar \"%s\" failed: %s", phar_obj->arc.archive->fname, error); efree(error); return; } } else { phar_archive_data *phar; all_files: phar = phar_obj->arc.archive; /* Extract all files */ if (!zend_hash_num_elements(&(phar->manifest))) { RETURN_TRUE; } for (zend_hash_internal_pointer_reset(&phar->manifest); zend_hash_has_more_elements(&phar->manifest) == SUCCESS; zend_hash_move_forward(&phar->manifest)) { if (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) { continue; } if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, &error TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Extraction from phar \"%s\" failed: %s", phar->fname, error); efree(error); return; } } } RETURN_TRUE; } /* }}} */ /* {{{ proto void PharFileInfo::__construct(string entry) * Construct a Phar entry object */ PHP_METHOD(PharFileInfo, __construct) { char *fname, *arch, *entry, *error; int fname_len, arch_len, entry_len; phar_entry_object *entry_obj; phar_entry_info *entry_info; phar_archive_data *phar_data; zval *zobj = getThis(), arg1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &fname, &fname_len) == FAILURE) { return; } entry_obj = (phar_entry_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (entry_obj->ent.entry) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot call constructor twice"); return; } if (fname_len < 7 || memcmp(fname, "phar://", 7) || phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0 TSRMLS_CC) == FAILURE) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "'%s' is not a valid phar archive URL (must have at least phar://filename.phar)", fname); return; } if (phar_open_from_filename(arch, arch_len, NULL, 0, REPORT_ERRORS, &phar_data, &error TSRMLS_CC) == FAILURE) { efree(arch); efree(entry); if (error) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot open phar file '%s': %s", fname, error); efree(error); } else { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot open phar file '%s'", fname); } return; } if ((entry_info = phar_get_entry_info_dir(phar_data, entry, entry_len, 1, &error, 1 TSRMLS_CC)) == NULL) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot access phar file entry '%s' in archive '%s'%s%s", entry, arch, error ? ", " : "", error ? error : ""); efree(arch); efree(entry); return; } efree(arch); efree(entry); entry_obj->ent.entry = entry_info; INIT_PZVAL(&arg1); ZVAL_STRINGL(&arg1, fname, fname_len, 0); zend_call_method_with_1_params(&zobj, Z_OBJCE_P(zobj), &spl_ce_SplFileInfo->constructor, "__construct", NULL, &arg1); } /* }}} */ #define PHAR_ENTRY_OBJECT() \ phar_entry_object *entry_obj = (phar_entry_object*)zend_object_store_get_object(getThis() TSRMLS_CC); \ if (!entry_obj->ent.entry) { \ zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \ "Cannot call method on an uninitialized PharFileInfo object"); \ return; \ } /* {{{ proto void PharFileInfo::__destruct() * clean up directory-based entry objects */ PHP_METHOD(PharFileInfo, __destruct) { phar_entry_object *entry_obj = (phar_entry_object*)zend_object_store_get_object(getThis() TSRMLS_CC); \ if (entry_obj->ent.entry && entry_obj->ent.entry->is_temp_dir) { if (entry_obj->ent.entry->filename) { efree(entry_obj->ent.entry->filename); entry_obj->ent.entry->filename = NULL; } efree(entry_obj->ent.entry); entry_obj->ent.entry = NULL; } } /* }}} */ /* {{{ proto int PharFileInfo::getCompressedSize() * Returns the compressed size */ PHP_METHOD(PharFileInfo, getCompressedSize) { PHAR_ENTRY_OBJECT(); RETURN_LONG(entry_obj->ent.entry->compressed_filesize); } /* }}} */ /* {{{ proto bool PharFileInfo::isCompressed([int compression_type]) * Returns whether the entry is compressed, and whether it is compressed with Phar::GZ or Phar::BZ2 if specified */ PHP_METHOD(PharFileInfo, isCompressed) { /* a number that is not Phar::GZ or Phar::BZ2 */ long method = 9021976; PHAR_ENTRY_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &method) == FAILURE) { return; } switch (method) { case 9021976: RETURN_BOOL(entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSION_MASK); case PHAR_ENT_COMPRESSED_GZ: RETURN_BOOL(entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSED_GZ); case PHAR_ENT_COMPRESSED_BZ2: RETURN_BOOL(entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSED_BZ2); default: zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \ "Unknown compression type specified"); \ } } /* }}} */ /* {{{ proto int PharFileInfo::getCRC32() * Returns CRC32 code or throws an exception if not CRC checked */ PHP_METHOD(PharFileInfo, getCRC32) { PHAR_ENTRY_OBJECT(); if (entry_obj->ent.entry->is_dir) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \ "Phar entry is a directory, does not have a CRC"); \ return; } if (entry_obj->ent.entry->is_crc_checked) { RETURN_LONG(entry_obj->ent.entry->crc32); } else { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \ "Phar entry was not CRC checked"); \ } } /* }}} */ /* {{{ proto int PharFileInfo::isCRCChecked() * Returns whether file entry is CRC checked */ PHP_METHOD(PharFileInfo, isCRCChecked) { PHAR_ENTRY_OBJECT(); RETURN_BOOL(entry_obj->ent.entry->is_crc_checked); } /* }}} */ /* {{{ proto int PharFileInfo::getPharFlags() * Returns the Phar file entry flags */ PHP_METHOD(PharFileInfo, getPharFlags) { PHAR_ENTRY_OBJECT(); RETURN_LONG(entry_obj->ent.entry->flags & ~(PHAR_ENT_PERM_MASK|PHAR_ENT_COMPRESSION_MASK)); } /* }}} */ /* {{{ proto int PharFileInfo::chmod() * set the file permissions for the Phar. This only allows setting execution bit, read/write */ PHP_METHOD(PharFileInfo, chmod) { char *error; long perms; PHAR_ENTRY_OBJECT(); if (entry_obj->ent.entry->is_temp_dir) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \ "Phar entry \"%s\" is a temporary directory (not an actual entry in the archive), cannot chmod", entry_obj->ent.entry->filename); \ return; } if (PHAR_G(readonly) && !entry_obj->ent.entry->phar->is_data) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Cannot modify permissions for file \"%s\" in phar \"%s\", write operations are prohibited", entry_obj->ent.entry->filename, entry_obj->ent.entry->phar->fname); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &perms) == FAILURE) { return; } if (entry_obj->ent.entry->is_persistent) { phar_archive_data *phar = entry_obj->ent.entry->phar; if (FAILURE == phar_copy_on_write(&phar TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar->fname); return; } /* re-populate after copy-on-write */ zend_hash_find(&phar->manifest, entry_obj->ent.entry->filename, entry_obj->ent.entry->filename_len, (void **)&entry_obj->ent.entry); } /* clear permissions */ entry_obj->ent.entry->flags &= ~PHAR_ENT_PERM_MASK; perms &= 0777; entry_obj->ent.entry->flags |= perms; entry_obj->ent.entry->old_flags = entry_obj->ent.entry->flags; entry_obj->ent.entry->phar->is_modified = 1; entry_obj->ent.entry->is_modified = 1; /* hackish cache in php_stat needs to be cleared */ /* if this code fails to work, check main/streams/streams.c, _php_stream_stat_path */ if (BG(CurrentLStatFile)) { efree(BG(CurrentLStatFile)); } if (BG(CurrentStatFile)) { efree(BG(CurrentStatFile)); } BG(CurrentLStatFile) = NULL; BG(CurrentStatFile) = NULL; phar_flush(entry_obj->ent.entry->phar, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } } /* }}} */ /* {{{ proto int PharFileInfo::hasMetaData() * Returns the metadata of the entry */ PHP_METHOD(PharFileInfo, hasMetadata) { PHAR_ENTRY_OBJECT(); RETURN_BOOL(entry_obj->ent.entry->metadata != NULL); } /* }}} */ /* {{{ proto int PharFileInfo::getMetaData() * Returns the metadata of the entry */ PHP_METHOD(PharFileInfo, getMetadata) { PHAR_ENTRY_OBJECT(); if (entry_obj->ent.entry->metadata) { if (entry_obj->ent.entry->is_persistent) { zval *ret; char *buf = estrndup((char *) entry_obj->ent.entry->metadata, entry_obj->ent.entry->metadata_len); /* assume success, we would have failed before */ phar_parse_metadata(&buf, &ret, entry_obj->ent.entry->metadata_len TSRMLS_CC); efree(buf); RETURN_ZVAL(ret, 0, 1); } RETURN_ZVAL(entry_obj->ent.entry->metadata, 1, 0); } } /* }}} */ /* {{{ proto int PharFileInfo::setMetaData(mixed $metadata) * Sets the metadata of the entry */ PHP_METHOD(PharFileInfo, setMetadata) { char *error; zval *metadata; PHAR_ENTRY_OBJECT(); if (PHAR_G(readonly) && !entry_obj->ent.entry->phar->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Write operations disabled by the php.ini setting phar.readonly"); return; } if (entry_obj->ent.entry->is_temp_dir) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \ "Phar entry is a temporary directory (not an actual entry in the archive), cannot set metadata"); \ return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &metadata) == FAILURE) { return; } if (entry_obj->ent.entry->is_persistent) { phar_archive_data *phar = entry_obj->ent.entry->phar; if (FAILURE == phar_copy_on_write(&phar TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar->fname); return; } /* re-populate after copy-on-write */ zend_hash_find(&phar->manifest, entry_obj->ent.entry->filename, entry_obj->ent.entry->filename_len, (void **)&entry_obj->ent.entry); } if (entry_obj->ent.entry->metadata) { zval_ptr_dtor(&entry_obj->ent.entry->metadata); entry_obj->ent.entry->metadata = NULL; } MAKE_STD_ZVAL(entry_obj->ent.entry->metadata); ZVAL_ZVAL(entry_obj->ent.entry->metadata, metadata, 1, 0); entry_obj->ent.entry->is_modified = 1; entry_obj->ent.entry->phar->is_modified = 1; phar_flush(entry_obj->ent.entry->phar, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } } /* }}} */ /* {{{ proto bool PharFileInfo::delMetaData() * Deletes the metadata of the entry */ PHP_METHOD(PharFileInfo, delMetadata) { char *error; PHAR_ENTRY_OBJECT(); if (PHAR_G(readonly) && !entry_obj->ent.entry->phar->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Write operations disabled by the php.ini setting phar.readonly"); return; } if (entry_obj->ent.entry->is_temp_dir) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \ "Phar entry is a temporary directory (not an actual entry in the archive), cannot delete metadata"); \ return; } if (entry_obj->ent.entry->metadata) { if (entry_obj->ent.entry->is_persistent) { phar_archive_data *phar = entry_obj->ent.entry->phar; if (FAILURE == phar_copy_on_write(&phar TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar->fname); return; } /* re-populate after copy-on-write */ zend_hash_find(&phar->manifest, entry_obj->ent.entry->filename, entry_obj->ent.entry->filename_len, (void **)&entry_obj->ent.entry); } zval_ptr_dtor(&entry_obj->ent.entry->metadata); entry_obj->ent.entry->metadata = NULL; entry_obj->ent.entry->is_modified = 1; entry_obj->ent.entry->phar->is_modified = 1; phar_flush(entry_obj->ent.entry->phar, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); RETURN_FALSE; } else { RETURN_TRUE; } } else { RETURN_TRUE; } } /* }}} */ /* {{{ proto string PharFileInfo::getContent() * return the complete file contents of the entry (like file_get_contents) */ PHP_METHOD(PharFileInfo, getContent) { char *error; php_stream *fp; phar_entry_info *link; PHAR_ENTRY_OBJECT(); if (entry_obj->ent.entry->is_dir) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Phar error: Cannot retrieve contents, \"%s\" in phar \"%s\" is a directory", entry_obj->ent.entry->filename, entry_obj->ent.entry->phar->fname); return; } link = phar_get_link_source(entry_obj->ent.entry TSRMLS_CC); if (!link) { link = entry_obj->ent.entry; } if (SUCCESS != phar_open_entry_fp(link, &error, 0 TSRMLS_CC)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Phar error: Cannot retrieve contents, \"%s\" in phar \"%s\": %s", entry_obj->ent.entry->filename, entry_obj->ent.entry->phar->fname, error); efree(error); return; } if (!(fp = phar_get_efp(link, 0 TSRMLS_CC))) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Phar error: Cannot retrieve contents of \"%s\" in phar \"%s\"", entry_obj->ent.entry->filename, entry_obj->ent.entry->phar->fname); return; } phar_seek_efp(link, 0, SEEK_SET, 0, 0 TSRMLS_CC); Z_TYPE_P(return_value) = IS_STRING; #if PHP_MAJOR_VERSION >= 6 Z_STRLEN_P(return_value) = php_stream_copy_to_mem(fp, (void **) &(Z_STRVAL_P(return_value)), link->uncompressed_filesize, 0); #else Z_STRLEN_P(return_value) = php_stream_copy_to_mem(fp, &(Z_STRVAL_P(return_value)), link->uncompressed_filesize, 0); #endif if (!Z_STRVAL_P(return_value)) { Z_STRVAL_P(return_value) = estrndup("", 0); } } /* }}} */ /* {{{ proto int PharFileInfo::compress(int compression_type) * Instructs the Phar class to compress the current file using zlib or bzip2 compression */ PHP_METHOD(PharFileInfo, compress) { long method; char *error; PHAR_ENTRY_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &method) == FAILURE) { return; } if (entry_obj->ent.entry->is_tar) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress with Gzip compression, not possible with tar-based phar archives"); return; } if (entry_obj->ent.entry->is_dir) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \ "Phar entry is a directory, cannot set compression"); \ return; } if (PHAR_G(readonly) && !entry_obj->ent.entry->phar->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Phar is readonly, cannot change compression"); return; } if (entry_obj->ent.entry->is_deleted) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress deleted file"); return; } if (entry_obj->ent.entry->is_persistent) { phar_archive_data *phar = entry_obj->ent.entry->phar; if (FAILURE == phar_copy_on_write(&phar TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar->fname); return; } /* re-populate after copy-on-write */ zend_hash_find(&phar->manifest, entry_obj->ent.entry->filename, entry_obj->ent.entry->filename_len, (void **)&entry_obj->ent.entry); } switch (method) { case PHAR_ENT_COMPRESSED_GZ: if (entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSED_GZ) { RETURN_TRUE; } if ((entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSED_BZ2) != 0) { if (!PHAR_G(has_bz2)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress with gzip compression, file is already compressed with bzip2 compression and bz2 extension is not enabled, cannot decompress"); return; } /* decompress this file indirectly */ if (SUCCESS != phar_open_entry_fp(entry_obj->ent.entry, &error, 1 TSRMLS_CC)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Phar error: Cannot decompress bzip2-compressed file \"%s\" in phar \"%s\" in order to compress with gzip: %s", entry_obj->ent.entry->filename, entry_obj->ent.entry->phar->fname, error); efree(error); return; } } if (!PHAR_G(has_zlib)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress with gzip compression, zlib extension is not enabled"); return; } entry_obj->ent.entry->old_flags = entry_obj->ent.entry->flags; entry_obj->ent.entry->flags &= ~PHAR_ENT_COMPRESSION_MASK; entry_obj->ent.entry->flags |= PHAR_ENT_COMPRESSED_GZ; break; case PHAR_ENT_COMPRESSED_BZ2: if (entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSED_BZ2) { RETURN_TRUE; } if ((entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSED_GZ) != 0) { if (!PHAR_G(has_zlib)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress with bzip2 compression, file is already compressed with gzip compression and zlib extension is not enabled, cannot decompress"); return; } /* decompress this file indirectly */ if (SUCCESS != phar_open_entry_fp(entry_obj->ent.entry, &error, 1 TSRMLS_CC)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Phar error: Cannot decompress gzip-compressed file \"%s\" in phar \"%s\" in order to compress with bzip2: %s", entry_obj->ent.entry->filename, entry_obj->ent.entry->phar->fname, error); efree(error); return; } } if (!PHAR_G(has_bz2)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress with bzip2 compression, bz2 extension is not enabled"); return; } entry_obj->ent.entry->old_flags = entry_obj->ent.entry->flags; entry_obj->ent.entry->flags &= ~PHAR_ENT_COMPRESSION_MASK; entry_obj->ent.entry->flags |= PHAR_ENT_COMPRESSED_BZ2; break; default: zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \ "Unknown compression type specified"); \ } entry_obj->ent.entry->phar->is_modified = 1; entry_obj->ent.entry->is_modified = 1; phar_flush(entry_obj->ent.entry->phar, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } RETURN_TRUE; } /* }}} */ /* {{{ proto int PharFileInfo::decompress() * Instructs the Phar class to decompress the current file */ PHP_METHOD(PharFileInfo, decompress) { char *error; PHAR_ENTRY_OBJECT(); if (entry_obj->ent.entry->is_dir) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \ "Phar entry is a directory, cannot set compression"); \ return; } if ((entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSION_MASK) == 0) { RETURN_TRUE; } if (PHAR_G(readonly) && !entry_obj->ent.entry->phar->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Phar is readonly, cannot decompress"); return; } if (entry_obj->ent.entry->is_deleted) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot compress deleted file"); return; } if ((entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSED_GZ) != 0 && !PHAR_G(has_zlib)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot decompress Gzip-compressed file, zlib extension is not enabled"); return; } if ((entry_obj->ent.entry->flags & PHAR_ENT_COMPRESSED_BZ2) != 0 && !PHAR_G(has_bz2)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot decompress Bzip2-compressed file, bz2 extension is not enabled"); return; } if (entry_obj->ent.entry->is_persistent) { phar_archive_data *phar = entry_obj->ent.entry->phar; if (FAILURE == phar_copy_on_write(&phar TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar->fname); return; } /* re-populate after copy-on-write */ zend_hash_find(&phar->manifest, entry_obj->ent.entry->filename, entry_obj->ent.entry->filename_len, (void **)&entry_obj->ent.entry); } if (!entry_obj->ent.entry->fp) { if (FAILURE == phar_open_archive_fp(entry_obj->ent.entry->phar TSRMLS_CC)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot decompress entry \"%s\", phar error: Cannot open phar archive \"%s\" for reading", entry_obj->ent.entry->filename, entry_obj->ent.entry->phar->fname); return; } entry_obj->ent.entry->fp_type = PHAR_FP; } entry_obj->ent.entry->old_flags = entry_obj->ent.entry->flags; entry_obj->ent.entry->flags &= ~PHAR_ENT_COMPRESSION_MASK; entry_obj->ent.entry->phar->is_modified = 1; entry_obj->ent.entry->is_modified = 1; phar_flush(entry_obj->ent.entry->phar, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } RETURN_TRUE; } /* }}} */ #endif /* HAVE_SPL */ /* {{{ phar methods */ PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar___construct, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, flags) ZEND_ARG_INFO(0, alias) ZEND_ARG_INFO(0, fileformat) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_createDS, 0, 0, 0) ZEND_ARG_INFO(0, index) ZEND_ARG_INFO(0, webindex) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_loadPhar, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, alias) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_mapPhar, 0, 0, 0) ZEND_ARG_INFO(0, alias) ZEND_ARG_INFO(0, offset) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_mount, 0, 0, 2) ZEND_ARG_INFO(0, inphar) ZEND_ARG_INFO(0, externalfile) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_mungServer, 0, 0, 1) ZEND_ARG_INFO(0, munglist) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_webPhar, 0, 0, 0) ZEND_ARG_INFO(0, alias) ZEND_ARG_INFO(0, index) ZEND_ARG_INFO(0, f404) ZEND_ARG_INFO(0, mimetypes) ZEND_ARG_INFO(0, rewrites) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_running, 0, 0, 1) ZEND_ARG_INFO(0, retphar) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_ua, 0, 0, 1) ZEND_ARG_INFO(0, archive) ZEND_END_ARG_INFO() #if HAVE_SPL PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_build, 0, 0, 1) ZEND_ARG_INFO(0, iterator) ZEND_ARG_INFO(0, base_directory) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_conv, 0, 0, 0) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, compression_type) ZEND_ARG_INFO(0, file_ext) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_comps, 0, 0, 1) ZEND_ARG_INFO(0, compression_type) ZEND_ARG_INFO(0, file_ext) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_decomp, 0, 0, 0) ZEND_ARG_INFO(0, file_ext) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_comp, 0, 0, 1) ZEND_ARG_INFO(0, compression_type) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_compo, 0, 0, 0) ZEND_ARG_INFO(0, compression_type) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_copy, 0, 0, 2) ZEND_ARG_INFO(0, newfile) ZEND_ARG_INFO(0, oldfile) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_delete, 0, 0, 1) ZEND_ARG_INFO(0, entry) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_fromdir, 0, 0, 1) ZEND_ARG_INFO(0, base_dir) ZEND_ARG_INFO(0, regex) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_offsetExists, 0, 0, 1) ZEND_ARG_INFO(0, entry) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_offsetSet, 0, 0, 2) ZEND_ARG_INFO(0, entry) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_setAlias, 0, 0, 1) ZEND_ARG_INFO(0, alias) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_setMetadata, 0, 0, 1) ZEND_ARG_INFO(0, metadata) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_setSigAlgo, 0, 0, 1) ZEND_ARG_INFO(0, algorithm) ZEND_ARG_INFO(0, privatekey) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_setStub, 0, 0, 1) ZEND_ARG_INFO(0, newstub) ZEND_ARG_INFO(0, maxlen) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_emptydir, 0, 0, 0) ZEND_ARG_INFO(0, dirname) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_extract, 0, 0, 1) ZEND_ARG_INFO(0, pathto) ZEND_ARG_INFO(0, files) ZEND_ARG_INFO(0, overwrite) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_addfile, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, localname) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_fromstring, 0, 0, 1) ZEND_ARG_INFO(0, localname) ZEND_ARG_INFO(0, contents) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_isff, 0, 0, 1) ZEND_ARG_INFO(0, fileformat) ZEND_END_ARG_INFO() #endif /* HAVE_SPL */ zend_function_entry php_archive_methods[] = { #if !HAVE_SPL PHP_ME(Phar, __construct, arginfo_phar___construct, ZEND_ACC_PRIVATE) #else PHP_ME(Phar, __construct, arginfo_phar___construct, ZEND_ACC_PUBLIC) PHP_ME(Phar, __destruct, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, addEmptyDir, arginfo_phar_emptydir, ZEND_ACC_PUBLIC) PHP_ME(Phar, addFile, arginfo_phar_addfile, ZEND_ACC_PUBLIC) PHP_ME(Phar, addFromString, arginfo_phar_fromstring, ZEND_ACC_PUBLIC) PHP_ME(Phar, buildFromDirectory, arginfo_phar_fromdir, ZEND_ACC_PUBLIC) PHP_ME(Phar, buildFromIterator, arginfo_phar_build, ZEND_ACC_PUBLIC) PHP_ME(Phar, compressFiles, arginfo_phar_comp, ZEND_ACC_PUBLIC) PHP_ME(Phar, decompressFiles, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, compress, arginfo_phar_comps, ZEND_ACC_PUBLIC) PHP_ME(Phar, decompress, arginfo_phar_decomp, ZEND_ACC_PUBLIC) PHP_ME(Phar, convertToExecutable, arginfo_phar_conv, ZEND_ACC_PUBLIC) PHP_ME(Phar, convertToData, arginfo_phar_conv, ZEND_ACC_PUBLIC) PHP_ME(Phar, copy, arginfo_phar_copy, ZEND_ACC_PUBLIC) PHP_ME(Phar, count, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, delete, arginfo_phar_delete, ZEND_ACC_PUBLIC) PHP_ME(Phar, delMetadata, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, extractTo, arginfo_phar_extract, ZEND_ACC_PUBLIC) PHP_ME(Phar, getAlias, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, getPath, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, getMetadata, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, getModified, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, getSignature, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, getStub, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, getVersion, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, hasMetadata, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, isBuffering, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, isCompressed, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, isFileFormat, arginfo_phar_isff, ZEND_ACC_PUBLIC) PHP_ME(Phar, isWritable, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, offsetExists, arginfo_phar_offsetExists, ZEND_ACC_PUBLIC) PHP_ME(Phar, offsetGet, arginfo_phar_offsetExists, ZEND_ACC_PUBLIC) PHP_ME(Phar, offsetSet, arginfo_phar_offsetSet, ZEND_ACC_PUBLIC) PHP_ME(Phar, offsetUnset, arginfo_phar_offsetExists, ZEND_ACC_PUBLIC) PHP_ME(Phar, setAlias, arginfo_phar_setAlias, ZEND_ACC_PUBLIC) PHP_ME(Phar, setDefaultStub, arginfo_phar_createDS, ZEND_ACC_PUBLIC) PHP_ME(Phar, setMetadata, arginfo_phar_setMetadata, ZEND_ACC_PUBLIC) PHP_ME(Phar, setSignatureAlgorithm, arginfo_phar_setSigAlgo, ZEND_ACC_PUBLIC) PHP_ME(Phar, setStub, arginfo_phar_setStub, ZEND_ACC_PUBLIC) PHP_ME(Phar, startBuffering, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phar, stopBuffering, NULL, ZEND_ACC_PUBLIC) #endif /* static member functions */ PHP_ME(Phar, apiVersion, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, canCompress, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, canWrite, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, createDefaultStub, arginfo_phar_createDS, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, getSupportedCompression,NULL, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, getSupportedSignatures,NULL, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, interceptFileFuncs, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, isValidPharFilename, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, loadPhar, arginfo_phar_loadPhar, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, mapPhar, arginfo_phar_mapPhar, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, running, arginfo_phar_running, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, mount, arginfo_phar_mount, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, mungServer, arginfo_phar_mungServer, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, unlinkArchive, arginfo_phar_ua, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) PHP_ME(Phar, webPhar, arginfo_phar_webPhar, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL) {NULL, NULL, NULL} }; #if HAVE_SPL PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_entry___construct, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() PHAR_ARG_INFO ZEND_BEGIN_ARG_INFO_EX(arginfo_entry_chmod, 0, 0, 1) ZEND_ARG_INFO(0, perms) ZEND_END_ARG_INFO() zend_function_entry php_entry_methods[] = { PHP_ME(PharFileInfo, __construct, arginfo_entry___construct, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, __destruct, NULL, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, chmod, arginfo_entry_chmod, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, compress, arginfo_phar_comp, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, decompress, NULL, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, delMetadata, NULL, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, getCompressedSize, NULL, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, getCRC32, NULL, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, getContent, NULL, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, getMetadata, NULL, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, getPharFlags, NULL, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, hasMetadata, NULL, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, isCompressed, arginfo_phar_compo, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, isCRCChecked, NULL, ZEND_ACC_PUBLIC) PHP_ME(PharFileInfo, setMetadata, arginfo_phar_setMetadata, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; #endif /* HAVE_SPL */ zend_function_entry phar_exception_methods[] = { {NULL, NULL, NULL} }; /* }}} */ #define REGISTER_PHAR_CLASS_CONST_LONG(class_name, const_name, value) \ zend_declare_class_constant_long(class_name, const_name, sizeof(const_name)-1, (long)value TSRMLS_CC); #if PHP_VERSION_ID < 50200 # define phar_exception_get_default() zend_exception_get_default() #else # define phar_exception_get_default() zend_exception_get_default(TSRMLS_C) #endif void phar_object_init(TSRMLS_D) /* {{{ */ { zend_class_entry ce; INIT_CLASS_ENTRY(ce, "PharException", phar_exception_methods); phar_ce_PharException = zend_register_internal_class_ex(&ce, phar_exception_get_default(), NULL TSRMLS_CC); #if HAVE_SPL INIT_CLASS_ENTRY(ce, "Phar", php_archive_methods); phar_ce_archive = zend_register_internal_class_ex(&ce, spl_ce_RecursiveDirectoryIterator, NULL TSRMLS_CC); zend_class_implements(phar_ce_archive TSRMLS_CC, 2, spl_ce_Countable, zend_ce_arrayaccess); INIT_CLASS_ENTRY(ce, "PharData", php_archive_methods); phar_ce_data = zend_register_internal_class_ex(&ce, spl_ce_RecursiveDirectoryIterator, NULL TSRMLS_CC); zend_class_implements(phar_ce_data TSRMLS_CC, 2, spl_ce_Countable, zend_ce_arrayaccess); INIT_CLASS_ENTRY(ce, "PharFileInfo", php_entry_methods); phar_ce_entry = zend_register_internal_class_ex(&ce, spl_ce_SplFileInfo, NULL TSRMLS_CC); #else INIT_CLASS_ENTRY(ce, "Phar", php_archive_methods); phar_ce_archive = zend_register_internal_class(&ce TSRMLS_CC); phar_ce_archive->ce_flags |= ZEND_ACC_FINAL_CLASS; INIT_CLASS_ENTRY(ce, "PharData", php_archive_methods); phar_ce_data = zend_register_internal_class(&ce TSRMLS_CC); phar_ce_data->ce_flags |= ZEND_ACC_FINAL_CLASS; #endif REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "BZ2", PHAR_ENT_COMPRESSED_BZ2) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "GZ", PHAR_ENT_COMPRESSED_GZ) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "NONE", PHAR_ENT_COMPRESSED_NONE) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "PHAR", PHAR_FORMAT_PHAR) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "TAR", PHAR_FORMAT_TAR) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "ZIP", PHAR_FORMAT_ZIP) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "COMPRESSED", PHAR_ENT_COMPRESSION_MASK) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "PHP", PHAR_MIME_PHP) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "PHPS", PHAR_MIME_PHPS) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "MD5", PHAR_SIG_MD5) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "OPENSSL", PHAR_SIG_OPENSSL) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "SHA1", PHAR_SIG_SHA1) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "SHA256", PHAR_SIG_SHA256) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "SHA512", PHAR_SIG_SHA512) } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-03-25-8138f7de40-3acdca4703.c
manybugs_data_63
/* zlibmodule.c -- gzip-compatible data compression */ /* See http://www.gzip.org/zlib/ */ /* Windows users: read Python's PCbuild\readme.txt */ #include "Python.h" #include "structmember.h" #include "zlib.h" #ifdef WITH_THREAD #include "pythread.h" #define ENTER_ZLIB(obj) \ Py_BEGIN_ALLOW_THREADS; \ PyThread_acquire_lock((obj)->lock, 1); \ Py_END_ALLOW_THREADS; #define LEAVE_ZLIB(obj) PyThread_release_lock((obj)->lock); #else #define ENTER_ZLIB(obj) #define LEAVE_ZLIB(obj) #endif /* The following parameters are copied from zutil.h, version 0.95 */ #define DEFLATED 8 #if MAX_MEM_LEVEL >= 8 # define DEF_MEM_LEVEL 8 #else # define DEF_MEM_LEVEL MAX_MEM_LEVEL #endif #define DEF_WBITS MAX_WBITS /* The output buffer will be increased in chunks of DEFAULTALLOC bytes. */ #define DEFAULTALLOC (16*1024) static PyTypeObject Comptype; static PyTypeObject Decomptype; static PyObject *ZlibError; typedef struct { PyObject_HEAD z_stream zst; PyObject *unused_data; PyObject *unconsumed_tail; int is_initialised; #ifdef WITH_THREAD PyThread_type_lock lock; #endif } compobject; static void zlib_error(z_stream zst, int err, char *msg) { const char *zmsg = zst.msg; if (zmsg == Z_NULL) { switch (err) { case Z_BUF_ERROR: zmsg = "incomplete or truncated stream"; break; case Z_STREAM_ERROR: zmsg = "inconsistent stream state"; break; case Z_DATA_ERROR: zmsg = "invalid input data"; break; } } if (zmsg == Z_NULL) PyErr_Format(ZlibError, "Error %d %s", err, msg); else PyErr_Format(ZlibError, "Error %d %s: %.200s", err, msg, zmsg); } PyDoc_STRVAR(compressobj__doc__, "compressobj([level]) -- Return a compressor object.\n" "\n" "Optional arg level is the compression level, in 1-9."); PyDoc_STRVAR(decompressobj__doc__, "decompressobj([wbits]) -- Return a decompressor object.\n" "\n" "Optional arg wbits is the window buffer size."); static compobject * newcompobject(PyTypeObject *type) { compobject *self; self = PyObject_New(compobject, type); if (self == NULL) return NULL; self->is_initialised = 0; self->unused_data = PyBytes_FromStringAndSize("", 0); if (self->unused_data == NULL) { Py_DECREF(self); return NULL; } self->unconsumed_tail = PyBytes_FromStringAndSize("", 0); if (self->unconsumed_tail == NULL) { Py_DECREF(self); return NULL; } #ifdef WITH_THREAD self->lock = PyThread_allocate_lock(); #endif return self; } PyDoc_STRVAR(compress__doc__, "compress(string[, level]) -- Returned compressed string.\n" "\n" "Optional arg level is the compression level, in 1-9."); static PyObject * PyZlib_compress(PyObject *self, PyObject *args) { PyObject *ReturnVal = NULL; Py_buffer pinput; Byte *input, *output; unsigned int length; int level=Z_DEFAULT_COMPRESSION, err; z_stream zst; /* require Python string object, optional 'level' arg */ if (!PyArg_ParseTuple(args, "y*|i:compress", &pinput, &level)) return NULL; if (pinput.len > UINT_MAX) { PyErr_SetString(PyExc_OverflowError, "size does not fit in an unsigned int"); return NULL; } length = pinput.len; input = pinput.buf; zst.avail_out = length + length/1000 + 12 + 1; output = (Byte*)malloc(zst.avail_out); if (output == NULL) { PyBuffer_Release(&pinput); PyErr_SetString(PyExc_MemoryError, "Can't allocate memory to compress data"); return NULL; } /* Past the point of no return. From here on out, we need to make sure we clean up mallocs & INCREFs. */ zst.zalloc = (alloc_func)NULL; zst.zfree = (free_func)Z_NULL; zst.next_out = (Byte *)output; zst.next_in = (Byte *)input; zst.avail_in = length; err = deflateInit(&zst, level); switch(err) { case(Z_OK): break; case(Z_MEM_ERROR): PyErr_SetString(PyExc_MemoryError, "Out of memory while compressing data"); goto error; case(Z_STREAM_ERROR): PyErr_SetString(ZlibError, "Bad compression level"); goto error; default: deflateEnd(&zst); zlib_error(zst, err, "while compressing data"); goto error; } Py_BEGIN_ALLOW_THREADS; err = deflate(&zst, Z_FINISH); Py_END_ALLOW_THREADS; if (err != Z_STREAM_END) { zlib_error(zst, err, "while compressing data"); deflateEnd(&zst); goto error; } err=deflateEnd(&zst); if (err == Z_OK) ReturnVal = PyBytes_FromStringAndSize((char *)output, zst.total_out); else zlib_error(zst, err, "while finishing compression"); error: PyBuffer_Release(&pinput); free(output); return ReturnVal; } PyDoc_STRVAR(decompress__doc__, "decompress(string[, wbits[, bufsize]]) -- Return decompressed string.\n" "\n" "Optional arg wbits is the window buffer size. Optional arg bufsize is\n" "the initial output buffer size."); static PyObject * PyZlib_decompress(PyObject *self, PyObject *args) { PyObject *result_str; Py_buffer pinput; Byte *input; unsigned int length; int err; int wsize=DEF_WBITS; Py_ssize_t r_strlen=DEFAULTALLOC; z_stream zst; if (!PyArg_ParseTuple(args, "y*|in:decompress", &pinput, &wsize, &r_strlen)) return NULL; if (pinput.len > UINT_MAX) { PyErr_SetString(PyExc_OverflowError, "size does not fit in an unsigned int"); return NULL; } length = pinput.len; input = pinput.buf; if (r_strlen <= 0) r_strlen = 1; zst.avail_in = length; zst.avail_out = r_strlen; if (!(result_str = PyBytes_FromStringAndSize(NULL, r_strlen))) { PyBuffer_Release(&pinput); return NULL; } zst.zalloc = (alloc_func)NULL; zst.zfree = (free_func)Z_NULL; zst.next_out = (Byte *)PyBytes_AS_STRING(result_str); zst.next_in = (Byte *)input; err = inflateInit2(&zst, wsize); switch(err) { case(Z_OK): break; case(Z_MEM_ERROR): PyErr_SetString(PyExc_MemoryError, "Out of memory while decompressing data"); goto error; default: inflateEnd(&zst); zlib_error(zst, err, "while preparing to decompress data"); goto error; } do { Py_BEGIN_ALLOW_THREADS err=inflate(&zst, Z_FINISH); Py_END_ALLOW_THREADS switch(err) { case(Z_STREAM_END): break; case(Z_BUF_ERROR): /* * If there is at least 1 byte of room according to zst.avail_out * and we get this error, assume that it means zlib cannot * process the inflate call() due to an error in the data. */ if (zst.avail_out > 0) { zlib_error(zst, err, "while decompressing data"); inflateEnd(&zst); goto error; } /* fall through */ case(Z_OK): /* need more memory */ if (_PyBytes_Resize(&result_str, r_strlen << 1) < 0) { inflateEnd(&zst); goto error; } zst.next_out = (unsigned char *)PyBytes_AS_STRING(result_str) + r_strlen; zst.avail_out = r_strlen; r_strlen = r_strlen << 1; break; default: inflateEnd(&zst); zlib_error(zst, err, "while decompressing data"); goto error; } } while (err != Z_STREAM_END); err = inflateEnd(&zst); if (err != Z_OK) { zlib_error(zst, err, "while finishing data decompression"); goto error; } if (_PyBytes_Resize(&result_str, zst.total_out) < 0) goto error; PyBuffer_Release(&pinput); return result_str; error: PyBuffer_Release(&pinput); Py_XDECREF(result_str); return NULL; } static PyObject * PyZlib_compressobj(PyObject *selfptr, PyObject *args) { compobject *self; int level=Z_DEFAULT_COMPRESSION, method=DEFLATED; int wbits=MAX_WBITS, memLevel=DEF_MEM_LEVEL, strategy=0, err; if (!PyArg_ParseTuple(args, "|iiiii:compressobj", &level, &method, &wbits, &memLevel, &strategy)) return NULL; self = newcompobject(&Comptype); if (self==NULL) return(NULL); self->zst.zalloc = (alloc_func)NULL; self->zst.zfree = (free_func)Z_NULL; self->zst.next_in = NULL; self->zst.avail_in = 0; err = deflateInit2(&self->zst, level, method, wbits, memLevel, strategy); switch(err) { case (Z_OK): self->is_initialised = 1; return (PyObject*)self; case (Z_MEM_ERROR): Py_DECREF(self); PyErr_SetString(PyExc_MemoryError, "Can't allocate memory for compression object"); return NULL; case(Z_STREAM_ERROR): Py_DECREF(self); PyErr_SetString(PyExc_ValueError, "Invalid initialization option"); return NULL; default: zlib_error(self->zst, err, "while creating compression object"); Py_DECREF(self); return NULL; } } static PyObject * PyZlib_decompressobj(PyObject *selfptr, PyObject *args) { int wbits=DEF_WBITS, err; compobject *self; if (!PyArg_ParseTuple(args, "|i:decompressobj", &wbits)) return NULL; self = newcompobject(&Decomptype); if (self == NULL) return(NULL); self->zst.zalloc = (alloc_func)NULL; self->zst.zfree = (free_func)Z_NULL; self->zst.next_in = NULL; self->zst.avail_in = 0; err = inflateInit2(&self->zst, wbits); switch(err) { case (Z_OK): self->is_initialised = 1; return (PyObject*)self; case(Z_STREAM_ERROR): Py_DECREF(self); PyErr_SetString(PyExc_ValueError, "Invalid initialization option"); return NULL; case (Z_MEM_ERROR): Py_DECREF(self); PyErr_SetString(PyExc_MemoryError, "Can't allocate memory for decompression object"); return NULL; default: zlib_error(self->zst, err, "while creating decompression object"); Py_DECREF(self); return NULL; } } static void Dealloc(compobject *self) { #ifdef WITH_THREAD PyThread_free_lock(self->lock); #endif Py_XDECREF(self->unused_data); Py_XDECREF(self->unconsumed_tail); PyObject_Del(self); } static void Comp_dealloc(compobject *self) { if (self->is_initialised) deflateEnd(&self->zst); Dealloc(self); } static void Decomp_dealloc(compobject *self) { if (self->is_initialised) inflateEnd(&self->zst); Dealloc(self); } PyDoc_STRVAR(comp_compress__doc__, "compress(data) -- Return a string containing data compressed.\n" "\n" "After calling this function, some of the input data may still\n" "be stored in internal buffers for later processing.\n" "Call the flush() method to clear these buffers."); static PyObject * PyZlib_objcompress(compobject *self, PyObject *args) { int err, inplen; Py_ssize_t length = DEFAULTALLOC; PyObject *RetVal; Py_buffer pinput; Byte *input; unsigned long start_total_out; if (!PyArg_ParseTuple(args, "y*:compress", &pinput)) return NULL; input = pinput.buf; inplen = pinput.len; if (!(RetVal = PyBytes_FromStringAndSize(NULL, length))) { PyBuffer_Release(&pinput); return NULL; } ENTER_ZLIB(self); start_total_out = self->zst.total_out; self->zst.avail_in = inplen; self->zst.next_in = input; self->zst.avail_out = length; self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal); Py_BEGIN_ALLOW_THREADS err = deflate(&(self->zst), Z_NO_FLUSH); Py_END_ALLOW_THREADS /* while Z_OK and the output buffer is full, there might be more output, so extend the output buffer and try again */ while (err == Z_OK && self->zst.avail_out == 0) { if (_PyBytes_Resize(&RetVal, length << 1) < 0) { Py_DECREF(RetVal); RetVal = NULL; goto error; } self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal) + length; self->zst.avail_out = length; length = length << 1; Py_BEGIN_ALLOW_THREADS err = deflate(&(self->zst), Z_NO_FLUSH); Py_END_ALLOW_THREADS } /* We will only get Z_BUF_ERROR if the output buffer was full but there wasn't more output when we tried again, so it is not an error condition. */ if (err != Z_OK && err != Z_BUF_ERROR) { zlib_error(self->zst, err, "while compressing"); Py_DECREF(RetVal); RetVal = NULL; goto error; } if (_PyBytes_Resize(&RetVal, self->zst.total_out - start_total_out) < 0) { Py_DECREF(RetVal); RetVal = NULL; } error: LEAVE_ZLIB(self); PyBuffer_Release(&pinput); return RetVal; } PyDoc_STRVAR(decomp_decompress__doc__, "decompress(data, max_length) -- Return a string containing the decompressed\n" "version of the data.\n" "\n" "After calling this function, some of the input data may still be stored in\n" "internal buffers for later processing.\n" "Call the flush() method to clear these buffers.\n" "If the max_length parameter is specified then the return value will be\n" "no longer than max_length. Unconsumed input data will be stored in\n" "the unconsumed_tail attribute."); static PyObject * PyZlib_objdecompress(compobject *self, PyObject *args) { int err, inplen, max_length = 0; Py_ssize_t old_length, length = DEFAULTALLOC; PyObject *RetVal; Py_buffer pinput; Byte *input; unsigned long start_total_out; if (!PyArg_ParseTuple(args, "y*|i:decompress", &pinput, &max_length)) return NULL; input = pinput.buf; inplen = pinput.len; if (max_length < 0) { PyBuffer_Release(&pinput); PyErr_SetString(PyExc_ValueError, "max_length must be greater than zero"); return NULL; } /* limit amount of data allocated to max_length */ if (max_length && length > max_length) length = max_length; if (!(RetVal = PyBytes_FromStringAndSize(NULL, length))) { PyBuffer_Release(&pinput); return NULL; } ENTER_ZLIB(self); start_total_out = self->zst.total_out; self->zst.avail_in = inplen; self->zst.next_in = input; self->zst.avail_out = length; self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal); Py_BEGIN_ALLOW_THREADS err = inflate(&(self->zst), Z_SYNC_FLUSH); Py_END_ALLOW_THREADS /* While Z_OK and the output buffer is full, there might be more output. So extend the output buffer and try again. */ while (err == Z_OK && self->zst.avail_out == 0) { /* If max_length set, don't continue decompressing if we've already reached the limit. */ if (max_length && length >= max_length) break; /* otherwise, ... */ old_length = length; length = length << 1; if (max_length && length > max_length) length = max_length; if (_PyBytes_Resize(&RetVal, length) < 0) { Py_DECREF(RetVal); RetVal = NULL; goto error; } self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal) + old_length; self->zst.avail_out = length - old_length; Py_BEGIN_ALLOW_THREADS err = inflate(&(self->zst), Z_SYNC_FLUSH); Py_END_ALLOW_THREADS } /* Not all of the compressed data could be accommodated in the output buffer of specified size. Return the unconsumed tail in an attribute.*/ if(max_length) { Py_DECREF(self->unconsumed_tail); self->unconsumed_tail = PyBytes_FromStringAndSize((char *)self->zst.next_in, self->zst.avail_in); if(!self->unconsumed_tail) { Py_DECREF(RetVal); RetVal = NULL; goto error; } } /* The end of the compressed data has been reached, so set the unused_data attribute to a string containing the remainder of the data in the string. Note that this is also a logical place to call inflateEnd, but the old behaviour of only calling it on flush() is preserved. */ if (err == Z_STREAM_END) { Py_XDECREF(self->unused_data); /* Free original empty string */ self->unused_data = PyBytes_FromStringAndSize( (char *)self->zst.next_in, self->zst.avail_in); if (self->unused_data == NULL) { Py_DECREF(RetVal); goto error; } /* We will only get Z_BUF_ERROR if the output buffer was full but there wasn't more output when we tried again, so it is not an error condition. */ } else if (err != Z_OK && err != Z_BUF_ERROR) { zlib_error(self->zst, err, "while decompressing"); Py_DECREF(RetVal); RetVal = NULL; goto error; } if (_PyBytes_Resize(&RetVal, self->zst.total_out - start_total_out) < 0) { Py_DECREF(RetVal); RetVal = NULL; } error: LEAVE_ZLIB(self); PyBuffer_Release(&pinput); return RetVal; } PyDoc_STRVAR(comp_flush__doc__, "flush( [mode] ) -- Return a string containing any remaining compressed data.\n" "\n" "mode can be one of the constants Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH; the\n" "default value used when mode is not specified is Z_FINISH.\n" "If mode == Z_FINISH, the compressor object can no longer be used after\n" "calling the flush() method. Otherwise, more data can still be compressed."); static PyObject * PyZlib_flush(compobject *self, PyObject *args) { int err, length = DEFAULTALLOC; PyObject *RetVal; int flushmode = Z_FINISH; unsigned long start_total_out; if (!PyArg_ParseTuple(args, "|i:flush", &flushmode)) return NULL; /* Flushing with Z_NO_FLUSH is a no-op, so there's no point in doing any work at all; just return an empty string. */ if (flushmode == Z_NO_FLUSH) { return PyBytes_FromStringAndSize(NULL, 0); } if (!(RetVal = PyBytes_FromStringAndSize(NULL, length))) return NULL; ENTER_ZLIB(self); start_total_out = self->zst.total_out; self->zst.avail_in = 0; self->zst.avail_out = length; self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal); Py_BEGIN_ALLOW_THREADS err = deflate(&(self->zst), flushmode); Py_END_ALLOW_THREADS /* while Z_OK and the output buffer is full, there might be more output, so extend the output buffer and try again */ while (err == Z_OK && self->zst.avail_out == 0) { if (_PyBytes_Resize(&RetVal, length << 1) < 0) { Py_DECREF(RetVal); RetVal = NULL; goto error; } self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal) + length; self->zst.avail_out = length; length = length << 1; Py_BEGIN_ALLOW_THREADS err = deflate(&(self->zst), flushmode); Py_END_ALLOW_THREADS } /* If flushmode is Z_FINISH, we also have to call deflateEnd() to free various data structures. Note we should only get Z_STREAM_END when flushmode is Z_FINISH, but checking both for safety*/ if (err == Z_STREAM_END && flushmode == Z_FINISH) { err = deflateEnd(&(self->zst)); if (err != Z_OK) { zlib_error(self->zst, err, "from deflateEnd()"); Py_DECREF(RetVal); RetVal = NULL; goto error; } else self->is_initialised = 0; /* We will only get Z_BUF_ERROR if the output buffer was full but there wasn't more output when we tried again, so it is not an error condition. */ } else if (err!=Z_OK && err!=Z_BUF_ERROR) { zlib_error(self->zst, err, "while flushing"); Py_DECREF(RetVal); RetVal = NULL; goto error; } if (_PyBytes_Resize(&RetVal, self->zst.total_out - start_total_out) < 0) { Py_DECREF(RetVal); RetVal = NULL; } error: LEAVE_ZLIB(self); return RetVal; } #ifdef HAVE_ZLIB_COPY PyDoc_STRVAR(comp_copy__doc__, "copy() -- Return a copy of the compression object."); static PyObject * PyZlib_copy(compobject *self) { compobject *retval = NULL; int err; retval = newcompobject(&Comptype); if (!retval) return NULL; /* Copy the zstream state * We use ENTER_ZLIB / LEAVE_ZLIB to make this thread-safe */ ENTER_ZLIB(self); err = deflateCopy(&retval->zst, &self->zst); switch(err) { case(Z_OK): break; case(Z_STREAM_ERROR): PyErr_SetString(PyExc_ValueError, "Inconsistent stream state"); goto error; case(Z_MEM_ERROR): PyErr_SetString(PyExc_MemoryError, "Can't allocate memory for compression object"); goto error; default: zlib_error(self->zst, err, "while copying compression object"); goto error; } Py_INCREF(self->unused_data); Py_INCREF(self->unconsumed_tail); Py_XDECREF(retval->unused_data); Py_XDECREF(retval->unconsumed_tail); retval->unused_data = self->unused_data; retval->unconsumed_tail = self->unconsumed_tail; /* Mark it as being initialized */ retval->is_initialised = 1; LEAVE_ZLIB(self); return (PyObject *)retval; error: LEAVE_ZLIB(self); Py_XDECREF(retval); return NULL; } PyDoc_STRVAR(decomp_copy__doc__, "copy() -- Return a copy of the decompression object."); static PyObject * PyZlib_uncopy(compobject *self) { compobject *retval = NULL; int err; retval = newcompobject(&Decomptype); if (!retval) return NULL; /* Copy the zstream state * We use ENTER_ZLIB / LEAVE_ZLIB to make this thread-safe */ ENTER_ZLIB(self); err = inflateCopy(&retval->zst, &self->zst); switch(err) { case(Z_OK): break; case(Z_STREAM_ERROR): PyErr_SetString(PyExc_ValueError, "Inconsistent stream state"); goto error; case(Z_MEM_ERROR): PyErr_SetString(PyExc_MemoryError, "Can't allocate memory for decompression object"); goto error; default: zlib_error(self->zst, err, "while copying decompression object"); goto error; } Py_INCREF(self->unused_data); Py_INCREF(self->unconsumed_tail); Py_XDECREF(retval->unused_data); Py_XDECREF(retval->unconsumed_tail); retval->unused_data = self->unused_data; retval->unconsumed_tail = self->unconsumed_tail; /* Mark it as being initialized */ retval->is_initialised = 1; LEAVE_ZLIB(self); return (PyObject *)retval; error: LEAVE_ZLIB(self); Py_XDECREF(retval); return NULL; } #endif PyDoc_STRVAR(decomp_flush__doc__, "flush( [length] ) -- Return a string containing any remaining\n" "decompressed data. length, if given, is the initial size of the\n" "output buffer.\n" "\n" "The decompressor object can no longer be used after this call."); static PyObject * PyZlib_unflush(compobject *self, PyObject *args) { int err, length = DEFAULTALLOC; PyObject * retval = NULL; unsigned long start_total_out; if (!PyArg_ParseTuple(args, "|i:flush", &length)) return NULL; if (length <= 0) { PyErr_SetString(PyExc_ValueError, "length must be greater than zero"); return NULL; } if (!(retval = PyBytes_FromStringAndSize(NULL, length))) return NULL; ENTER_ZLIB(self); start_total_out = self->zst.total_out; self->zst.avail_out = length; self->zst.next_out = (Byte *)PyBytes_AS_STRING(retval); Py_BEGIN_ALLOW_THREADS err = inflate(&(self->zst), Z_FINISH); Py_END_ALLOW_THREADS /* while Z_OK and the output buffer is full, there might be more output, so extend the output buffer and try again */ while ((err == Z_OK || err == Z_BUF_ERROR) && self->zst.avail_out == 0) { if (_PyBytes_Resize(&retval, length << 1) < 0) { Py_DECREF(retval); retval = NULL; goto error; } self->zst.next_out = (Byte *)PyBytes_AS_STRING(retval) + length; self->zst.avail_out = length; length = length << 1; Py_BEGIN_ALLOW_THREADS err = inflate(&(self->zst), Z_FINISH); Py_END_ALLOW_THREADS } /* If flushmode is Z_FINISH, we also have to call deflateEnd() to free various data structures. Note we should only get Z_STREAM_END when flushmode is Z_FINISH */ if (err == Z_STREAM_END) { err = inflateEnd(&(self->zst)); self->is_initialised = 0; if (err != Z_OK) { zlib_error(self->zst, err, "from inflateEnd()"); Py_DECREF(retval); retval = NULL; goto error; } } if (_PyBytes_Resize(&retval, self->zst.total_out - start_total_out) < 0) { Py_DECREF(retval); retval = NULL; } error: LEAVE_ZLIB(self); return retval; } static PyMethodDef comp_methods[] = { {"compress", (binaryfunc)PyZlib_objcompress, METH_VARARGS, comp_compress__doc__}, {"flush", (binaryfunc)PyZlib_flush, METH_VARARGS, comp_flush__doc__}, #ifdef HAVE_ZLIB_COPY {"copy", (PyCFunction)PyZlib_copy, METH_NOARGS, comp_copy__doc__}, #endif {NULL, NULL} }; static PyMethodDef Decomp_methods[] = { {"decompress", (binaryfunc)PyZlib_objdecompress, METH_VARARGS, decomp_decompress__doc__}, {"flush", (binaryfunc)PyZlib_unflush, METH_VARARGS, decomp_flush__doc__}, #ifdef HAVE_ZLIB_COPY {"copy", (PyCFunction)PyZlib_uncopy, METH_NOARGS, decomp_copy__doc__}, #endif {NULL, NULL} }; #define COMP_OFF(x) offsetof(compobject, x) static PyMemberDef Decomp_members[] = { {"unused_data", T_OBJECT, COMP_OFF(unused_data), READONLY}, {"unconsumed_tail", T_OBJECT, COMP_OFF(unconsumed_tail), READONLY}, {NULL}, }; PyDoc_STRVAR(adler32__doc__, "adler32(string[, start]) -- Compute an Adler-32 checksum of string.\n" "\n" "An optional starting value can be specified. The returned checksum is\n" "an integer."); static PyObject * PyZlib_adler32(PyObject *self, PyObject *args) { unsigned int adler32val = 1; /* adler32(0L, Z_NULL, 0) */ Py_buffer pbuf; if (!PyArg_ParseTuple(args, "y*|I:adler32", &pbuf, &adler32val)) return NULL; /* Releasing the GIL for very small buffers is inefficient and may lower performance */ if (pbuf.len > 1024*5) { unsigned char *buf = pbuf.buf; Py_ssize_t len = pbuf.len; Py_BEGIN_ALLOW_THREADS /* Avoid truncation of length for very large buffers. adler32() takes length as an unsigned int, which may be narrower than Py_ssize_t. */ while (len > (size_t) UINT_MAX) { adler32val = adler32(adler32val, buf, UINT_MAX); buf += (size_t) UINT_MAX; len -= (size_t) UINT_MAX; } adler32val = adler32(adler32val, buf, len); Py_END_ALLOW_THREADS } else { adler32val = adler32(adler32val, pbuf.buf, pbuf.len); } PyBuffer_Release(&pbuf); return PyLong_FromUnsignedLong(adler32val & 0xffffffffU); } PyDoc_STRVAR(crc32__doc__, "crc32(string[, start]) -- Compute a CRC-32 checksum of string.\n" "\n" "An optional starting value can be specified. The returned checksum is\n" "an integer."); static PyObject * PyZlib_crc32(PyObject *self, PyObject *args) { unsigned int crc32val = 0; /* crc32(0L, Z_NULL, 0) */ Py_buffer pbuf; int signed_val; if (!PyArg_ParseTuple(args, "y*|I:crc32", &pbuf, &crc32val)) return NULL; /* Releasing the GIL for very small buffers is inefficient and may lower performance */ if (pbuf.len > 1024*5) { unsigned char *buf = pbuf.buf; Py_ssize_t len = pbuf.len; Py_BEGIN_ALLOW_THREADS /* Avoid truncation of length for very large buffers. crc32() takes length as an unsigned int, which may be narrower than Py_ssize_t. */ while (len > (size_t) UINT_MAX) { crc32val = crc32(crc32val, buf, UINT_MAX); buf += (size_t) UINT_MAX; len -= (size_t) UINT_MAX; } signed_val = crc32(crc32val, buf, len); Py_END_ALLOW_THREADS } else { signed_val = crc32(crc32val, pbuf.buf, pbuf.len); } PyBuffer_Release(&pbuf); return PyLong_FromUnsignedLong(signed_val & 0xffffffffU); } static PyMethodDef zlib_methods[] = { {"adler32", (PyCFunction)PyZlib_adler32, METH_VARARGS, adler32__doc__}, {"compress", (PyCFunction)PyZlib_compress, METH_VARARGS, compress__doc__}, {"compressobj", (PyCFunction)PyZlib_compressobj, METH_VARARGS, compressobj__doc__}, {"crc32", (PyCFunction)PyZlib_crc32, METH_VARARGS, crc32__doc__}, {"decompress", (PyCFunction)PyZlib_decompress, METH_VARARGS, decompress__doc__}, {"decompressobj", (PyCFunction)PyZlib_decompressobj, METH_VARARGS, decompressobj__doc__}, {NULL, NULL} }; static PyTypeObject Comptype = { PyVarObject_HEAD_INIT(0, 0) "zlib.Compress", sizeof(compobject), 0, (destructor)Comp_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ comp_methods, /*tp_methods*/ }; static PyTypeObject Decomptype = { PyVarObject_HEAD_INIT(0, 0) "zlib.Decompress", sizeof(compobject), 0, (destructor)Decomp_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ Decomp_methods, /*tp_methods*/ Decomp_members, /*tp_members*/ }; PyDoc_STRVAR(zlib_module_documentation, "The functions in this module allow compression and decompression using the\n" "zlib library, which is based on GNU zip.\n" "\n" "adler32(string[, start]) -- Compute an Adler-32 checksum.\n" "compress(string[, level]) -- Compress string, with compression level in 1-9.\n" "compressobj([level]) -- Return a compressor object.\n" "crc32(string[, start]) -- Compute a CRC-32 checksum.\n" "decompress(string,[wbits],[bufsize]) -- Decompresses a compressed string.\n" "decompressobj([wbits]) -- Return a decompressor object.\n" "\n" "'wbits' is window buffer size.\n" "Compressor objects support compress() and flush() methods; decompressor\n" "objects support decompress() and flush()."); static struct PyModuleDef zlibmodule = { PyModuleDef_HEAD_INIT, "zlib", zlib_module_documentation, -1, zlib_methods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_zlib(void) { PyObject *m, *ver; if (PyType_Ready(&Comptype) < 0) return NULL; if (PyType_Ready(&Decomptype) < 0) return NULL; m = PyModule_Create(&zlibmodule); if (m == NULL) return NULL; ZlibError = PyErr_NewException("zlib.error", NULL, NULL); if (ZlibError != NULL) { Py_INCREF(ZlibError); PyModule_AddObject(m, "error", ZlibError); } PyModule_AddIntConstant(m, "MAX_WBITS", MAX_WBITS); PyModule_AddIntConstant(m, "DEFLATED", DEFLATED); PyModule_AddIntConstant(m, "DEF_MEM_LEVEL", DEF_MEM_LEVEL); PyModule_AddIntConstant(m, "Z_BEST_SPEED", Z_BEST_SPEED); PyModule_AddIntConstant(m, "Z_BEST_COMPRESSION", Z_BEST_COMPRESSION); PyModule_AddIntConstant(m, "Z_DEFAULT_COMPRESSION", Z_DEFAULT_COMPRESSION); PyModule_AddIntConstant(m, "Z_FILTERED", Z_FILTERED); PyModule_AddIntConstant(m, "Z_HUFFMAN_ONLY", Z_HUFFMAN_ONLY); PyModule_AddIntConstant(m, "Z_DEFAULT_STRATEGY", Z_DEFAULT_STRATEGY); PyModule_AddIntConstant(m, "Z_FINISH", Z_FINISH); PyModule_AddIntConstant(m, "Z_NO_FLUSH", Z_NO_FLUSH); PyModule_AddIntConstant(m, "Z_SYNC_FLUSH", Z_SYNC_FLUSH); PyModule_AddIntConstant(m, "Z_FULL_FLUSH", Z_FULL_FLUSH); ver = PyUnicode_FromString(ZLIB_VERSION); if (ver != NULL) PyModule_AddObject(m, "ZLIB_VERSION", ver); PyModule_AddStringConstant(m, "__version__", "1.0"); return m; } /* zlibmodule.c -- gzip-compatible data compression */ /* See http://www.gzip.org/zlib/ */ /* Windows users: read Python's PCbuild\readme.txt */ #include "Python.h" #include "structmember.h" #include "zlib.h" #ifdef WITH_THREAD #include "pythread.h" #define ENTER_ZLIB(obj) \ Py_BEGIN_ALLOW_THREADS; \ PyThread_acquire_lock((obj)->lock, 1); \ Py_END_ALLOW_THREADS; #define LEAVE_ZLIB(obj) PyThread_release_lock((obj)->lock); #else #define ENTER_ZLIB(obj) #define LEAVE_ZLIB(obj) #endif /* The following parameters are copied from zutil.h, version 0.95 */ #define DEFLATED 8 #if MAX_MEM_LEVEL >= 8 # define DEF_MEM_LEVEL 8 #else # define DEF_MEM_LEVEL MAX_MEM_LEVEL #endif #define DEF_WBITS MAX_WBITS /* The output buffer will be increased in chunks of DEFAULTALLOC bytes. */ #define DEFAULTALLOC (16*1024) static PyTypeObject Comptype; static PyTypeObject Decomptype; static PyObject *ZlibError; typedef struct { PyObject_HEAD z_stream zst; PyObject *unused_data; PyObject *unconsumed_tail; int is_initialised; #ifdef WITH_THREAD PyThread_type_lock lock; #endif } compobject; static void zlib_error(z_stream zst, int err, char *msg) { const char *zmsg = zst.msg; if (zmsg == Z_NULL) { switch (err) { case Z_BUF_ERROR: zmsg = "incomplete or truncated stream"; break; case Z_STREAM_ERROR: zmsg = "inconsistent stream state"; break; case Z_DATA_ERROR: zmsg = "invalid input data"; break; } } if (zmsg == Z_NULL) PyErr_Format(ZlibError, "Error %d %s", err, msg); else PyErr_Format(ZlibError, "Error %d %s: %.200s", err, msg, zmsg); } PyDoc_STRVAR(compressobj__doc__, "compressobj([level]) -- Return a compressor object.\n" "\n" "Optional arg level is the compression level, in 1-9."); PyDoc_STRVAR(decompressobj__doc__, "decompressobj([wbits]) -- Return a decompressor object.\n" "\n" "Optional arg wbits is the window buffer size."); static compobject * newcompobject(PyTypeObject *type) { compobject *self; self = PyObject_New(compobject, type); if (self == NULL) return NULL; self->is_initialised = 0; self->unused_data = PyBytes_FromStringAndSize("", 0); if (self->unused_data == NULL) { Py_DECREF(self); return NULL; } self->unconsumed_tail = PyBytes_FromStringAndSize("", 0); if (self->unconsumed_tail == NULL) { Py_DECREF(self); return NULL; } #ifdef WITH_THREAD self->lock = PyThread_allocate_lock(); #endif return self; } PyDoc_STRVAR(compress__doc__, "compress(string[, level]) -- Returned compressed string.\n" "\n" "Optional arg level is the compression level, in 1-9."); static PyObject * PyZlib_compress(PyObject *self, PyObject *args) { PyObject *ReturnVal = NULL; Py_buffer pinput; Byte *input, *output; unsigned int length; int level=Z_DEFAULT_COMPRESSION, err; z_stream zst; /* require Python string object, optional 'level' arg */ if (!PyArg_ParseTuple(args, "y*|i:compress", &pinput, &level)) return NULL; if (pinput.len > UINT_MAX) { PyErr_SetString(PyExc_OverflowError, "size does not fit in an unsigned int"); return NULL; } length = pinput.len; input = pinput.buf; zst.avail_out = length + length/1000 + 12 + 1; output = (Byte*)malloc(zst.avail_out); if (output == NULL) { PyBuffer_Release(&pinput); PyErr_SetString(PyExc_MemoryError, "Can't allocate memory to compress data"); return NULL; } /* Past the point of no return. From here on out, we need to make sure we clean up mallocs & INCREFs. */ zst.zalloc = (alloc_func)NULL; zst.zfree = (free_func)Z_NULL; zst.next_out = (Byte *)output; zst.next_in = (Byte *)input; zst.avail_in = length; err = deflateInit(&zst, level); switch(err) { case(Z_OK): break; case(Z_MEM_ERROR): PyErr_SetString(PyExc_MemoryError, "Out of memory while compressing data"); goto error; case(Z_STREAM_ERROR): PyErr_SetString(ZlibError, "Bad compression level"); goto error; default: deflateEnd(&zst); zlib_error(zst, err, "while compressing data"); goto error; } Py_BEGIN_ALLOW_THREADS; err = deflate(&zst, Z_FINISH); Py_END_ALLOW_THREADS; if (err != Z_STREAM_END) { zlib_error(zst, err, "while compressing data"); deflateEnd(&zst); goto error; } err=deflateEnd(&zst); if (err == Z_OK) ReturnVal = PyBytes_FromStringAndSize((char *)output, zst.total_out); else zlib_error(zst, err, "while finishing compression"); error: PyBuffer_Release(&pinput); free(output); return ReturnVal; } PyDoc_STRVAR(decompress__doc__, "decompress(string[, wbits[, bufsize]]) -- Return decompressed string.\n" "\n" "Optional arg wbits is the window buffer size. Optional arg bufsize is\n" "the initial output buffer size."); static PyObject * PyZlib_decompress(PyObject *self, PyObject *args) { PyObject *result_str; Py_buffer pinput; Byte *input; unsigned int length; int err; int wsize=DEF_WBITS; Py_ssize_t r_strlen=DEFAULTALLOC; z_stream zst; if (!PyArg_ParseTuple(args, "y*|in:decompress", &pinput, &wsize, &r_strlen)) return NULL; if (pinput.len > UINT_MAX) { PyErr_SetString(PyExc_OverflowError, "size does not fit in an unsigned int"); return NULL; } length = pinput.len; input = pinput.buf; if (r_strlen <= 0) r_strlen = 1; zst.avail_in = length; zst.avail_out = r_strlen; if (!(result_str = PyBytes_FromStringAndSize(NULL, r_strlen))) { PyBuffer_Release(&pinput); return NULL; } zst.zalloc = (alloc_func)NULL; zst.zfree = (free_func)Z_NULL; zst.next_out = (Byte *)PyBytes_AS_STRING(result_str); zst.next_in = (Byte *)input; err = inflateInit2(&zst, wsize); switch(err) { case(Z_OK): break; case(Z_MEM_ERROR): PyErr_SetString(PyExc_MemoryError, "Out of memory while decompressing data"); goto error; default: inflateEnd(&zst); zlib_error(zst, err, "while preparing to decompress data"); goto error; } do { Py_BEGIN_ALLOW_THREADS err=inflate(&zst, Z_FINISH); Py_END_ALLOW_THREADS switch(err) { case(Z_STREAM_END): break; case(Z_BUF_ERROR): /* * If there is at least 1 byte of room according to zst.avail_out * and we get this error, assume that it means zlib cannot * process the inflate call() due to an error in the data. */ if (zst.avail_out > 0) { zlib_error(zst, err, "while decompressing data"); inflateEnd(&zst); goto error; } /* fall through */ case(Z_OK): /* need more memory */ if (_PyBytes_Resize(&result_str, r_strlen << 1) < 0) { inflateEnd(&zst); goto error; } zst.next_out = (unsigned char *)PyBytes_AS_STRING(result_str) + r_strlen; zst.avail_out = r_strlen; r_strlen = r_strlen << 1; break; default: inflateEnd(&zst); zlib_error(zst, err, "while decompressing data"); goto error; } } while (err != Z_STREAM_END); err = inflateEnd(&zst); if (err != Z_OK) { zlib_error(zst, err, "while finishing data decompression"); goto error; } if (_PyBytes_Resize(&result_str, zst.total_out) < 0) goto error; PyBuffer_Release(&pinput); return result_str; error: PyBuffer_Release(&pinput); Py_XDECREF(result_str); return NULL; } static PyObject * PyZlib_compressobj(PyObject *selfptr, PyObject *args) { compobject *self; int level=Z_DEFAULT_COMPRESSION, method=DEFLATED; int wbits=MAX_WBITS, memLevel=DEF_MEM_LEVEL, strategy=0, err; if (!PyArg_ParseTuple(args, "|iiiii:compressobj", &level, &method, &wbits, &memLevel, &strategy)) return NULL; self = newcompobject(&Comptype); if (self==NULL) return(NULL); self->zst.zalloc = (alloc_func)NULL; self->zst.zfree = (free_func)Z_NULL; self->zst.next_in = NULL; self->zst.avail_in = 0; err = deflateInit2(&self->zst, level, method, wbits, memLevel, strategy); switch(err) { case (Z_OK): self->is_initialised = 1; return (PyObject*)self; case (Z_MEM_ERROR): Py_DECREF(self); PyErr_SetString(PyExc_MemoryError, "Can't allocate memory for compression object"); return NULL; case(Z_STREAM_ERROR): Py_DECREF(self); PyErr_SetString(PyExc_ValueError, "Invalid initialization option"); return NULL; default: zlib_error(self->zst, err, "while creating compression object"); Py_DECREF(self); return NULL; } } static PyObject * PyZlib_decompressobj(PyObject *selfptr, PyObject *args) { int wbits=DEF_WBITS, err; compobject *self; if (!PyArg_ParseTuple(args, "|i:decompressobj", &wbits)) return NULL; self = newcompobject(&Decomptype); if (self == NULL) return(NULL); self->zst.zalloc = (alloc_func)NULL; self->zst.zfree = (free_func)Z_NULL; self->zst.next_in = NULL; self->zst.avail_in = 0; err = inflateInit2(&self->zst, wbits); switch(err) { case (Z_OK): self->is_initialised = 1; return (PyObject*)self; case(Z_STREAM_ERROR): Py_DECREF(self); PyErr_SetString(PyExc_ValueError, "Invalid initialization option"); return NULL; case (Z_MEM_ERROR): Py_DECREF(self); PyErr_SetString(PyExc_MemoryError, "Can't allocate memory for decompression object"); return NULL; default: zlib_error(self->zst, err, "while creating decompression object"); Py_DECREF(self); return NULL; } } static void Dealloc(compobject *self) { #ifdef WITH_THREAD PyThread_free_lock(self->lock); #endif Py_XDECREF(self->unused_data); Py_XDECREF(self->unconsumed_tail); PyObject_Del(self); } static void Comp_dealloc(compobject *self) { if (self->is_initialised) deflateEnd(&self->zst); Dealloc(self); } static void Decomp_dealloc(compobject *self) { if (self->is_initialised) inflateEnd(&self->zst); Dealloc(self); } PyDoc_STRVAR(comp_compress__doc__, "compress(data) -- Return a string containing data compressed.\n" "\n" "After calling this function, some of the input data may still\n" "be stored in internal buffers for later processing.\n" "Call the flush() method to clear these buffers."); static PyObject * PyZlib_objcompress(compobject *self, PyObject *args) { int err, inplen; Py_ssize_t length = DEFAULTALLOC; PyObject *RetVal; Py_buffer pinput; Byte *input; unsigned long start_total_out; if (!PyArg_ParseTuple(args, "y*:compress", &pinput)) return NULL; input = pinput.buf; inplen = pinput.len; if (!(RetVal = PyBytes_FromStringAndSize(NULL, length))) { PyBuffer_Release(&pinput); return NULL; } ENTER_ZLIB(self); start_total_out = self->zst.total_out; self->zst.avail_in = inplen; self->zst.next_in = input; self->zst.avail_out = length; self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal); Py_BEGIN_ALLOW_THREADS err = deflate(&(self->zst), Z_NO_FLUSH); Py_END_ALLOW_THREADS /* while Z_OK and the output buffer is full, there might be more output, so extend the output buffer and try again */ while (err == Z_OK && self->zst.avail_out == 0) { if (_PyBytes_Resize(&RetVal, length << 1) < 0) { Py_DECREF(RetVal); RetVal = NULL; goto error; } self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal) + length; self->zst.avail_out = length; length = length << 1; Py_BEGIN_ALLOW_THREADS err = deflate(&(self->zst), Z_NO_FLUSH); Py_END_ALLOW_THREADS } /* We will only get Z_BUF_ERROR if the output buffer was full but there wasn't more output when we tried again, so it is not an error condition. */ if (err != Z_OK && err != Z_BUF_ERROR) { zlib_error(self->zst, err, "while compressing"); Py_DECREF(RetVal); RetVal = NULL; goto error; } if (_PyBytes_Resize(&RetVal, self->zst.total_out - start_total_out) < 0) { Py_DECREF(RetVal); RetVal = NULL; } error: LEAVE_ZLIB(self); PyBuffer_Release(&pinput); return RetVal; } PyDoc_STRVAR(decomp_decompress__doc__, "decompress(data, max_length) -- Return a string containing the decompressed\n" "version of the data.\n" "\n" "After calling this function, some of the input data may still be stored in\n" "internal buffers for later processing.\n" "Call the flush() method to clear these buffers.\n" "If the max_length parameter is specified then the return value will be\n" "no longer than max_length. Unconsumed input data will be stored in\n" "the unconsumed_tail attribute."); static PyObject * PyZlib_objdecompress(compobject *self, PyObject *args) { int err, inplen, max_length = 0; Py_ssize_t old_length, length = DEFAULTALLOC; PyObject *RetVal; Py_buffer pinput; Byte *input; unsigned long start_total_out; if (!PyArg_ParseTuple(args, "y*|i:decompress", &pinput, &max_length)) return NULL; input = pinput.buf; inplen = pinput.len; if (max_length < 0) { PyBuffer_Release(&pinput); PyErr_SetString(PyExc_ValueError, "max_length must be greater than zero"); return NULL; } /* limit amount of data allocated to max_length */ if (max_length && length > max_length) length = max_length; if (!(RetVal = PyBytes_FromStringAndSize(NULL, length))) { PyBuffer_Release(&pinput); return NULL; } ENTER_ZLIB(self); start_total_out = self->zst.total_out; self->zst.avail_in = inplen; self->zst.next_in = input; self->zst.avail_out = length; self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal); Py_BEGIN_ALLOW_THREADS err = inflate(&(self->zst), Z_SYNC_FLUSH); Py_END_ALLOW_THREADS /* While Z_OK and the output buffer is full, there might be more output. So extend the output buffer and try again. */ while (err == Z_OK && self->zst.avail_out == 0) { /* If max_length set, don't continue decompressing if we've already reached the limit. */ if (max_length && length >= max_length) break; /* otherwise, ... */ old_length = length; length = length << 1; if (max_length && length > max_length) length = max_length; if (_PyBytes_Resize(&RetVal, length) < 0) { Py_DECREF(RetVal); RetVal = NULL; goto error; } self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal) + old_length; self->zst.avail_out = length - old_length; Py_BEGIN_ALLOW_THREADS err = inflate(&(self->zst), Z_SYNC_FLUSH); Py_END_ALLOW_THREADS } if(max_length) { /* Not all of the compressed data could be accommodated in a buffer of the specified size. Return the unconsumed tail in an attribute. */ Py_DECREF(self->unconsumed_tail); self->unconsumed_tail = PyBytes_FromStringAndSize((char *)self->zst.next_in, self->zst.avail_in); } else if (PyBytes_GET_SIZE(self->unconsumed_tail) > 0) { /* All of the compressed data was consumed. Clear unconsumed_tail. */ Py_DECREF(self->unconsumed_tail); self->unconsumed_tail = PyBytes_FromStringAndSize("", 0); } if (self->unconsumed_tail == NULL) { Py_DECREF(RetVal); RetVal = NULL; goto error; } /* The end of the compressed data has been reached, so set the unused_data attribute to a string containing the remainder of the data in the string. Note that this is also a logical place to call inflateEnd, but the old behaviour of only calling it on flush() is preserved. */ if (err == Z_STREAM_END) { Py_XDECREF(self->unused_data); /* Free original empty string */ self->unused_data = PyBytes_FromStringAndSize( (char *)self->zst.next_in, self->zst.avail_in); if (self->unused_data == NULL) { Py_DECREF(RetVal); goto error; } /* We will only get Z_BUF_ERROR if the output buffer was full but there wasn't more output when we tried again, so it is not an error condition. */ } else if (err != Z_OK && err != Z_BUF_ERROR) { zlib_error(self->zst, err, "while decompressing"); Py_DECREF(RetVal); RetVal = NULL; goto error; } if (_PyBytes_Resize(&RetVal, self->zst.total_out - start_total_out) < 0) { Py_DECREF(RetVal); RetVal = NULL; } error: LEAVE_ZLIB(self); PyBuffer_Release(&pinput); return RetVal; } PyDoc_STRVAR(comp_flush__doc__, "flush( [mode] ) -- Return a string containing any remaining compressed data.\n" "\n" "mode can be one of the constants Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH; the\n" "default value used when mode is not specified is Z_FINISH.\n" "If mode == Z_FINISH, the compressor object can no longer be used after\n" "calling the flush() method. Otherwise, more data can still be compressed."); static PyObject * PyZlib_flush(compobject *self, PyObject *args) { int err, length = DEFAULTALLOC; PyObject *RetVal; int flushmode = Z_FINISH; unsigned long start_total_out; if (!PyArg_ParseTuple(args, "|i:flush", &flushmode)) return NULL; /* Flushing with Z_NO_FLUSH is a no-op, so there's no point in doing any work at all; just return an empty string. */ if (flushmode == Z_NO_FLUSH) { return PyBytes_FromStringAndSize(NULL, 0); } if (!(RetVal = PyBytes_FromStringAndSize(NULL, length))) return NULL; ENTER_ZLIB(self); start_total_out = self->zst.total_out; self->zst.avail_in = 0; self->zst.avail_out = length; self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal); Py_BEGIN_ALLOW_THREADS err = deflate(&(self->zst), flushmode); Py_END_ALLOW_THREADS /* while Z_OK and the output buffer is full, there might be more output, so extend the output buffer and try again */ while (err == Z_OK && self->zst.avail_out == 0) { if (_PyBytes_Resize(&RetVal, length << 1) < 0) { Py_DECREF(RetVal); RetVal = NULL; goto error; } self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal) + length; self->zst.avail_out = length; length = length << 1; Py_BEGIN_ALLOW_THREADS err = deflate(&(self->zst), flushmode); Py_END_ALLOW_THREADS } /* If flushmode is Z_FINISH, we also have to call deflateEnd() to free various data structures. Note we should only get Z_STREAM_END when flushmode is Z_FINISH, but checking both for safety*/ if (err == Z_STREAM_END && flushmode == Z_FINISH) { err = deflateEnd(&(self->zst)); if (err != Z_OK) { zlib_error(self->zst, err, "from deflateEnd()"); Py_DECREF(RetVal); RetVal = NULL; goto error; } else self->is_initialised = 0; /* We will only get Z_BUF_ERROR if the output buffer was full but there wasn't more output when we tried again, so it is not an error condition. */ } else if (err!=Z_OK && err!=Z_BUF_ERROR) { zlib_error(self->zst, err, "while flushing"); Py_DECREF(RetVal); RetVal = NULL; goto error; } if (_PyBytes_Resize(&RetVal, self->zst.total_out - start_total_out) < 0) { Py_DECREF(RetVal); RetVal = NULL; } error: LEAVE_ZLIB(self); return RetVal; } #ifdef HAVE_ZLIB_COPY PyDoc_STRVAR(comp_copy__doc__, "copy() -- Return a copy of the compression object."); static PyObject * PyZlib_copy(compobject *self) { compobject *retval = NULL; int err; retval = newcompobject(&Comptype); if (!retval) return NULL; /* Copy the zstream state * We use ENTER_ZLIB / LEAVE_ZLIB to make this thread-safe */ ENTER_ZLIB(self); err = deflateCopy(&retval->zst, &self->zst); switch(err) { case(Z_OK): break; case(Z_STREAM_ERROR): PyErr_SetString(PyExc_ValueError, "Inconsistent stream state"); goto error; case(Z_MEM_ERROR): PyErr_SetString(PyExc_MemoryError, "Can't allocate memory for compression object"); goto error; default: zlib_error(self->zst, err, "while copying compression object"); goto error; } Py_INCREF(self->unused_data); Py_INCREF(self->unconsumed_tail); Py_XDECREF(retval->unused_data); Py_XDECREF(retval->unconsumed_tail); retval->unused_data = self->unused_data; retval->unconsumed_tail = self->unconsumed_tail; /* Mark it as being initialized */ retval->is_initialised = 1; LEAVE_ZLIB(self); return (PyObject *)retval; error: LEAVE_ZLIB(self); Py_XDECREF(retval); return NULL; } PyDoc_STRVAR(decomp_copy__doc__, "copy() -- Return a copy of the decompression object."); static PyObject * PyZlib_uncopy(compobject *self) { compobject *retval = NULL; int err; retval = newcompobject(&Decomptype); if (!retval) return NULL; /* Copy the zstream state * We use ENTER_ZLIB / LEAVE_ZLIB to make this thread-safe */ ENTER_ZLIB(self); err = inflateCopy(&retval->zst, &self->zst); switch(err) { case(Z_OK): break; case(Z_STREAM_ERROR): PyErr_SetString(PyExc_ValueError, "Inconsistent stream state"); goto error; case(Z_MEM_ERROR): PyErr_SetString(PyExc_MemoryError, "Can't allocate memory for decompression object"); goto error; default: zlib_error(self->zst, err, "while copying decompression object"); goto error; } Py_INCREF(self->unused_data); Py_INCREF(self->unconsumed_tail); Py_XDECREF(retval->unused_data); Py_XDECREF(retval->unconsumed_tail); retval->unused_data = self->unused_data; retval->unconsumed_tail = self->unconsumed_tail; /* Mark it as being initialized */ retval->is_initialised = 1; LEAVE_ZLIB(self); return (PyObject *)retval; error: LEAVE_ZLIB(self); Py_XDECREF(retval); return NULL; } #endif PyDoc_STRVAR(decomp_flush__doc__, "flush( [length] ) -- Return a string containing any remaining\n" "decompressed data. length, if given, is the initial size of the\n" "output buffer.\n" "\n" "The decompressor object can no longer be used after this call."); static PyObject * PyZlib_unflush(compobject *self, PyObject *args) { int err, length = DEFAULTALLOC; PyObject * retval = NULL; unsigned long start_total_out; if (!PyArg_ParseTuple(args, "|i:flush", &length)) return NULL; if (length <= 0) { PyErr_SetString(PyExc_ValueError, "length must be greater than zero"); return NULL; } if (!(retval = PyBytes_FromStringAndSize(NULL, length))) return NULL; ENTER_ZLIB(self); start_total_out = self->zst.total_out; self->zst.avail_out = length; self->zst.next_out = (Byte *)PyBytes_AS_STRING(retval); Py_BEGIN_ALLOW_THREADS err = inflate(&(self->zst), Z_FINISH); Py_END_ALLOW_THREADS /* while Z_OK and the output buffer is full, there might be more output, so extend the output buffer and try again */ while ((err == Z_OK || err == Z_BUF_ERROR) && self->zst.avail_out == 0) { if (_PyBytes_Resize(&retval, length << 1) < 0) { Py_DECREF(retval); retval = NULL; goto error; } self->zst.next_out = (Byte *)PyBytes_AS_STRING(retval) + length; self->zst.avail_out = length; length = length << 1; Py_BEGIN_ALLOW_THREADS err = inflate(&(self->zst), Z_FINISH); Py_END_ALLOW_THREADS } /* If flushmode is Z_FINISH, we also have to call deflateEnd() to free various data structures. Note we should only get Z_STREAM_END when flushmode is Z_FINISH */ if (err == Z_STREAM_END) { err = inflateEnd(&(self->zst)); self->is_initialised = 0; if (err != Z_OK) { zlib_error(self->zst, err, "from inflateEnd()"); Py_DECREF(retval); retval = NULL; goto error; } } if (_PyBytes_Resize(&retval, self->zst.total_out - start_total_out) < 0) { Py_DECREF(retval); retval = NULL; } error: LEAVE_ZLIB(self); return retval; } static PyMethodDef comp_methods[] = { {"compress", (binaryfunc)PyZlib_objcompress, METH_VARARGS, comp_compress__doc__}, {"flush", (binaryfunc)PyZlib_flush, METH_VARARGS, comp_flush__doc__}, #ifdef HAVE_ZLIB_COPY {"copy", (PyCFunction)PyZlib_copy, METH_NOARGS, comp_copy__doc__}, #endif {NULL, NULL} }; static PyMethodDef Decomp_methods[] = { {"decompress", (binaryfunc)PyZlib_objdecompress, METH_VARARGS, decomp_decompress__doc__}, {"flush", (binaryfunc)PyZlib_unflush, METH_VARARGS, decomp_flush__doc__}, #ifdef HAVE_ZLIB_COPY {"copy", (PyCFunction)PyZlib_uncopy, METH_NOARGS, decomp_copy__doc__}, #endif {NULL, NULL} }; #define COMP_OFF(x) offsetof(compobject, x) static PyMemberDef Decomp_members[] = { {"unused_data", T_OBJECT, COMP_OFF(unused_data), READONLY}, {"unconsumed_tail", T_OBJECT, COMP_OFF(unconsumed_tail), READONLY}, {NULL}, }; PyDoc_STRVAR(adler32__doc__, "adler32(string[, start]) -- Compute an Adler-32 checksum of string.\n" "\n" "An optional starting value can be specified. The returned checksum is\n" "an integer."); static PyObject * PyZlib_adler32(PyObject *self, PyObject *args) { unsigned int adler32val = 1; /* adler32(0L, Z_NULL, 0) */ Py_buffer pbuf; if (!PyArg_ParseTuple(args, "y*|I:adler32", &pbuf, &adler32val)) return NULL; /* Releasing the GIL for very small buffers is inefficient and may lower performance */ if (pbuf.len > 1024*5) { unsigned char *buf = pbuf.buf; Py_ssize_t len = pbuf.len; Py_BEGIN_ALLOW_THREADS /* Avoid truncation of length for very large buffers. adler32() takes length as an unsigned int, which may be narrower than Py_ssize_t. */ while (len > (size_t) UINT_MAX) { adler32val = adler32(adler32val, buf, UINT_MAX); buf += (size_t) UINT_MAX; len -= (size_t) UINT_MAX; } adler32val = adler32(adler32val, buf, len); Py_END_ALLOW_THREADS } else { adler32val = adler32(adler32val, pbuf.buf, pbuf.len); } PyBuffer_Release(&pbuf); return PyLong_FromUnsignedLong(adler32val & 0xffffffffU); } PyDoc_STRVAR(crc32__doc__, "crc32(string[, start]) -- Compute a CRC-32 checksum of string.\n" "\n" "An optional starting value can be specified. The returned checksum is\n" "an integer."); static PyObject * PyZlib_crc32(PyObject *self, PyObject *args) { unsigned int crc32val = 0; /* crc32(0L, Z_NULL, 0) */ Py_buffer pbuf; int signed_val; if (!PyArg_ParseTuple(args, "y*|I:crc32", &pbuf, &crc32val)) return NULL; /* Releasing the GIL for very small buffers is inefficient and may lower performance */ if (pbuf.len > 1024*5) { unsigned char *buf = pbuf.buf; Py_ssize_t len = pbuf.len; Py_BEGIN_ALLOW_THREADS /* Avoid truncation of length for very large buffers. crc32() takes length as an unsigned int, which may be narrower than Py_ssize_t. */ while (len > (size_t) UINT_MAX) { crc32val = crc32(crc32val, buf, UINT_MAX); buf += (size_t) UINT_MAX; len -= (size_t) UINT_MAX; } signed_val = crc32(crc32val, buf, len); Py_END_ALLOW_THREADS } else { signed_val = crc32(crc32val, pbuf.buf, pbuf.len); } PyBuffer_Release(&pbuf); return PyLong_FromUnsignedLong(signed_val & 0xffffffffU); } static PyMethodDef zlib_methods[] = { {"adler32", (PyCFunction)PyZlib_adler32, METH_VARARGS, adler32__doc__}, {"compress", (PyCFunction)PyZlib_compress, METH_VARARGS, compress__doc__}, {"compressobj", (PyCFunction)PyZlib_compressobj, METH_VARARGS, compressobj__doc__}, {"crc32", (PyCFunction)PyZlib_crc32, METH_VARARGS, crc32__doc__}, {"decompress", (PyCFunction)PyZlib_decompress, METH_VARARGS, decompress__doc__}, {"decompressobj", (PyCFunction)PyZlib_decompressobj, METH_VARARGS, decompressobj__doc__}, {NULL, NULL} }; static PyTypeObject Comptype = { PyVarObject_HEAD_INIT(0, 0) "zlib.Compress", sizeof(compobject), 0, (destructor)Comp_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ comp_methods, /*tp_methods*/ }; static PyTypeObject Decomptype = { PyVarObject_HEAD_INIT(0, 0) "zlib.Decompress", sizeof(compobject), 0, (destructor)Decomp_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ Decomp_methods, /*tp_methods*/ Decomp_members, /*tp_members*/ }; PyDoc_STRVAR(zlib_module_documentation, "The functions in this module allow compression and decompression using the\n" "zlib library, which is based on GNU zip.\n" "\n" "adler32(string[, start]) -- Compute an Adler-32 checksum.\n" "compress(string[, level]) -- Compress string, with compression level in 1-9.\n" "compressobj([level]) -- Return a compressor object.\n" "crc32(string[, start]) -- Compute a CRC-32 checksum.\n" "decompress(string,[wbits],[bufsize]) -- Decompresses a compressed string.\n" "decompressobj([wbits]) -- Return a decompressor object.\n" "\n" "'wbits' is window buffer size.\n" "Compressor objects support compress() and flush() methods; decompressor\n" "objects support decompress() and flush()."); static struct PyModuleDef zlibmodule = { PyModuleDef_HEAD_INIT, "zlib", zlib_module_documentation, -1, zlib_methods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_zlib(void) { PyObject *m, *ver; if (PyType_Ready(&Comptype) < 0) return NULL; if (PyType_Ready(&Decomptype) < 0) return NULL; m = PyModule_Create(&zlibmodule); if (m == NULL) return NULL; ZlibError = PyErr_NewException("zlib.error", NULL, NULL); if (ZlibError != NULL) { Py_INCREF(ZlibError); PyModule_AddObject(m, "error", ZlibError); } PyModule_AddIntConstant(m, "MAX_WBITS", MAX_WBITS); PyModule_AddIntConstant(m, "DEFLATED", DEFLATED); PyModule_AddIntConstant(m, "DEF_MEM_LEVEL", DEF_MEM_LEVEL); PyModule_AddIntConstant(m, "Z_BEST_SPEED", Z_BEST_SPEED); PyModule_AddIntConstant(m, "Z_BEST_COMPRESSION", Z_BEST_COMPRESSION); PyModule_AddIntConstant(m, "Z_DEFAULT_COMPRESSION", Z_DEFAULT_COMPRESSION); PyModule_AddIntConstant(m, "Z_FILTERED", Z_FILTERED); PyModule_AddIntConstant(m, "Z_HUFFMAN_ONLY", Z_HUFFMAN_ONLY); PyModule_AddIntConstant(m, "Z_DEFAULT_STRATEGY", Z_DEFAULT_STRATEGY); PyModule_AddIntConstant(m, "Z_FINISH", Z_FINISH); PyModule_AddIntConstant(m, "Z_NO_FLUSH", Z_NO_FLUSH); PyModule_AddIntConstant(m, "Z_SYNC_FLUSH", Z_SYNC_FLUSH); PyModule_AddIntConstant(m, "Z_FULL_FLUSH", Z_FULL_FLUSH); ver = PyUnicode_FromString(ZLIB_VERSION); if (ver != NULL) PyModule_AddObject(m, "ZLIB_VERSION", ver); PyModule_AddStringConstant(m, "__version__", "1.0"); return m; }
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/python_70098-70101.c
manybugs_data_64
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Jim Winstead <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <stdlib.h> #include <string.h> #include <ctype.h> #include <sys/types.h> #include "php.h" #include "url.h" #include "file.h" #ifdef _OSD_POSIX #ifndef APACHE #error On this EBCDIC platform, PHP is only supported as an Apache module. #else /*APACHE*/ #ifndef CHARSET_EBCDIC #define CHARSET_EBCDIC /* this machine uses EBCDIC, not ASCII! */ #endif #include "ebcdic.h" #endif /*APACHE*/ #endif /*_OSD_POSIX*/ /* {{{ free_url */ PHPAPI void php_url_free(php_url *theurl) { if (theurl->scheme) efree(theurl->scheme); if (theurl->user) efree(theurl->user); if (theurl->pass) efree(theurl->pass); if (theurl->host) efree(theurl->host); if (theurl->path) efree(theurl->path); if (theurl->query) efree(theurl->query); if (theurl->fragment) efree(theurl->fragment); efree(theurl); } /* }}} */ /* {{{ php_replace_controlchars */ PHPAPI char *php_replace_controlchars_ex(char *str, int len) { unsigned char *s = (unsigned char *)str; unsigned char *e = (unsigned char *)str + len; if (!str) { return (NULL); } while (s < e) { if (iscntrl(*s)) { *s='_'; } s++; } return (str); } /* }}} */ PHPAPI char *php_replace_controlchars(char *str) { return php_replace_controlchars_ex(str, strlen(str)); } PHPAPI php_url *php_url_parse(char const *str) { return php_url_parse_ex(str, strlen(str)); } /* {{{ php_url_parse */ PHPAPI php_url *php_url_parse_ex(char const *str, int length) { char port_buf[6]; php_url *ret = ecalloc(1, sizeof(php_url)); char const *s, *e, *p, *pp, *ue; s = str; ue = s + length; /* parse scheme */ if ((e = memchr(s, ':', length)) && (e - s)) { /* validate scheme */ p = s; while (p < e) { /* scheme = 1*[ lowalpha | digit | "+" | "-" | "." ] */ if (!isalpha(*p) && !isdigit(*p) && *p != '+' && *p != '.' && *p != '-') { if (e + 1 < ue) { goto parse_port; } else { goto just_path; } } p++; } if (*(e + 1) == '\0') { /* only scheme is available */ ret->scheme = estrndup(s, (e - s)); php_replace_controlchars_ex(ret->scheme, (e - s)); goto end; } /* * certain schemas like mailto: and zlib: may not have any / after them * this check ensures we support those. */ if (*(e+1) != '/') { /* check if the data we get is a port this allows us to * correctly parse things like a.com:80 */ p = e + 1; while (isdigit(*p)) { p++; } if ((*p == '\0' || *p == '/') && (p - e) < 7) { goto parse_port; } ret->scheme = estrndup(s, (e-s)); php_replace_controlchars_ex(ret->scheme, (e - s)); length -= ++e - s; s = e; goto just_path; } else { ret->scheme = estrndup(s, (e-s)); php_replace_controlchars_ex(ret->scheme, (e - s)); if (*(e+2) == '/') { s = e + 3; if (!strncasecmp("file", ret->scheme, sizeof("file"))) { if (*(e + 3) == '/') { /* support windows drive letters as in: file:///c:/somedir/file.txt */ if (*(e + 5) == ':') { s = e + 4; } goto nohost; } } } else { if (!strncasecmp("file", ret->scheme, sizeof("file"))) { s = e + 1; goto nohost; } else { length -= ++e - s; s = e; goto just_path; } } } } else if (e) { /* no scheme, look for port */ parse_port: p = e + 1; pp = p; while (pp-p < 6 && isdigit(*pp)) { pp++; } if (pp-p < 6 && (*pp == '/' || *pp == '\0')) { memcpy(port_buf, p, (pp-p)); port_buf[pp-p] = '\0'; ret->port = atoi(port_buf); if (!ret->port && (pp - p) > 0) { STR_FREE(ret->scheme); efree(ret); return NULL; } } else { goto just_path; } } else { just_path: ue = s + length; goto nohost; } e = ue; if (!(p = memchr(s, '/', (ue - s)))) { char *query, *fragment; query = memchr(s, '?', (ue - s)); fragment = memchr(s, '#', (ue - s)); if (query && fragment) { if (query > fragment) { p = e = fragment; } else { p = e = query; } } else if (query) { p = e = query; } else if (fragment) { p = e = fragment; } } else { e = p; } /* check for login and password */ if ((p = zend_memrchr(s, '@', (e-s)))) { if ((pp = memchr(s, ':', (p-s)))) { if ((pp-s) > 0) { ret->user = estrndup(s, (pp-s)); php_replace_controlchars_ex(ret->user, (pp - s)); } pp++; if (p-pp > 0) { ret->pass = estrndup(pp, (p-pp)); php_replace_controlchars_ex(ret->pass, (p-pp)); } } else { ret->user = estrndup(s, (p-s)); php_replace_controlchars_ex(ret->user, (p-s)); } s = p + 1; } /* check for port */ if (*s == '[' && *(e-1) == ']') { /* Short circuit portscan, we're dealing with an IPv6 embedded address */ p = s; } else { /* memrchr is a GNU specific extension Emulate for wide compatability */ for(p = e; *p != ':' && p >= s; p--); } if (p >= s && *p == ':') { if (!ret->port) { p++; if (e-p > 5) { /* port cannot be longer then 5 characters */ STR_FREE(ret->scheme); STR_FREE(ret->user); STR_FREE(ret->pass); efree(ret); return NULL; } else if (e - p > 0) { memcpy(port_buf, p, (e-p)); port_buf[e-p] = '\0'; ret->port = atoi(port_buf); if (!ret->port && (e - p)) { STR_FREE(ret->scheme); STR_FREE(ret->user); STR_FREE(ret->pass); efree(ret); return NULL; } } p--; } } else { p = e; } /* check if we have a valid host, if we don't reject the string as url */ if ((p-s) < 1) { STR_FREE(ret->scheme); STR_FREE(ret->user); STR_FREE(ret->pass); efree(ret); return NULL; } ret->host = estrndup(s, (p-s)); php_replace_controlchars_ex(ret->host, (p - s)); if (e == ue) { return ret; } s = e; nohost: if ((p = memchr(s, '?', (ue - s)))) { pp = strchr(s, '#'); if (pp && pp < p) { p = pp; goto label_parse; } if (p - s) { ret->path = estrndup(s, (p-s)); php_replace_controlchars_ex(ret->path, (p - s)); } if (pp) { if (pp - ++p) { ret->query = estrndup(p, (pp-p)); php_replace_controlchars_ex(ret->query, (pp - p)); } p = pp; goto label_parse; } else if (++p - ue) { ret->query = estrndup(p, (ue-p)); php_replace_controlchars_ex(ret->query, (ue - p)); } } else if ((p = memchr(s, '#', (ue - s)))) { if (p - s) { ret->path = estrndup(s, (p-s)); php_replace_controlchars_ex(ret->path, (p - s)); } label_parse: p++; if (ue - p) { ret->fragment = estrndup(p, (ue-p)); php_replace_controlchars_ex(ret->fragment, (ue - p)); } } else { ret->path = estrndup(s, (ue-s)); php_replace_controlchars_ex(ret->path, (ue - s)); } end: return ret; } /* }}} */ /* {{{ proto mixed parse_url(string url, [int url_component]) Parse a URL and return its components */ PHP_FUNCTION(parse_url) { char *str; int str_len; php_url *resource; long key = -1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &str, &str_len, &key) == FAILURE) { return; } resource = php_url_parse_ex(str, str_len); if (resource == NULL) { /* @todo Find a method to determine why php_url_parse_ex() failed */ RETURN_FALSE; } if (key > -1) { switch (key) { case PHP_URL_SCHEME: if (resource->scheme != NULL) RETVAL_STRING(resource->scheme, 1); break; case PHP_URL_HOST: if (resource->host != NULL) RETVAL_STRING(resource->host, 1); break; case PHP_URL_PORT: if (resource->port != 0) RETVAL_LONG(resource->port); break; case PHP_URL_USER: if (resource->user != NULL) RETVAL_STRING(resource->user, 1); break; case PHP_URL_PASS: if (resource->pass != NULL) RETVAL_STRING(resource->pass, 1); break; case PHP_URL_PATH: if (resource->path != NULL) RETVAL_STRING(resource->path, 1); break; case PHP_URL_QUERY: if (resource->query != NULL) RETVAL_STRING(resource->query, 1); break; case PHP_URL_FRAGMENT: if (resource->fragment != NULL) RETVAL_STRING(resource->fragment, 1); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid URL component identifier %ld", key); RETVAL_FALSE; } goto done; } /* allocate an array for return */ array_init(return_value); /* add the various elements to the array */ if (resource->scheme != NULL) add_assoc_string(return_value, "scheme", resource->scheme, 1); if (resource->host != NULL) add_assoc_string(return_value, "host", resource->host, 1); if (resource->port != 0) add_assoc_long(return_value, "port", resource->port); if (resource->user != NULL) add_assoc_string(return_value, "user", resource->user, 1); if (resource->pass != NULL) add_assoc_string(return_value, "pass", resource->pass, 1); if (resource->path != NULL) add_assoc_string(return_value, "path", resource->path, 1); if (resource->query != NULL) add_assoc_string(return_value, "query", resource->query, 1); if (resource->fragment != NULL) add_assoc_string(return_value, "fragment", resource->fragment, 1); done: php_url_free(resource); } /* }}} */ /* {{{ php_htoi */ static int php_htoi(char *s) { int value; int c; c = ((unsigned char *)s)[0]; if (isupper(c)) c = tolower(c); value = (c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10) * 16; c = ((unsigned char *)s)[1]; if (isupper(c)) c = tolower(c); value += c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10; return (value); } /* }}} */ /* rfc1738: ...The characters ";", "/", "?", ":", "@", "=" and "&" are the characters which may be reserved for special meaning within a scheme... ...Thus, only alphanumerics, the special characters "$-_.+!*'(),", and reserved characters used for their reserved purposes may be used unencoded within a URL... For added safety, we only leave -_. unencoded. */ static unsigned char hexchars[] = "0123456789ABCDEF"; /* {{{ php_url_encode */ PHPAPI char *php_url_encode(char const *s, int len, int *new_length) { register unsigned char c; unsigned char *to, *start; unsigned char const *from, *end; from = (unsigned char *)s; end = (unsigned char *)s + len; start = to = (unsigned char *) safe_emalloc(3, len, 1); while (from < end) { c = *from++; if (c == ' ') { *to++ = '+'; #ifndef CHARSET_EBCDIC } else if ((c < '0' && c != '-' && c != '.') || (c < 'A' && c > '9') || (c > 'Z' && c < 'a' && c != '_') || (c > 'z')) { to[0] = '%'; to[1] = hexchars[c >> 4]; to[2] = hexchars[c & 15]; to += 3; #else /*CHARSET_EBCDIC*/ } else if (!isalnum(c) && strchr("_-.", c) == NULL) { /* Allow only alphanumeric chars and '_', '-', '.'; escape the rest */ to[0] = '%'; to[1] = hexchars[os_toascii[c] >> 4]; to[2] = hexchars[os_toascii[c] & 15]; to += 3; #endif /*CHARSET_EBCDIC*/ } else { *to++ = c; } } *to = 0; if (new_length) { *new_length = to - start; } return (char *) start; } /* }}} */ /* {{{ proto string urlencode(string str) URL-encodes string */ PHP_FUNCTION(urlencode) { char *in_str, *out_str; int in_str_len, out_str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str, &in_str_len) == FAILURE) { return; } out_str = php_url_encode(in_str, in_str_len, &out_str_len); RETURN_STRINGL(out_str, out_str_len, 0); } /* }}} */ /* {{{ proto string urldecode(string str) Decodes URL-encoded string */ PHP_FUNCTION(urldecode) { char *in_str, *out_str; int in_str_len, out_str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str, &in_str_len) == FAILURE) { return; } out_str = estrndup(in_str, in_str_len); out_str_len = php_url_decode(out_str, in_str_len); RETURN_STRINGL(out_str, out_str_len, 0); } /* }}} */ /* {{{ php_url_decode */ PHPAPI int php_url_decode(char *str, int len) { char *dest = str; char *data = str; while (len--) { if (*data == '+') { *dest = ' '; } else if (*data == '%' && len >= 2 && isxdigit((int) *(data + 1)) && isxdigit((int) *(data + 2))) { #ifndef CHARSET_EBCDIC *dest = (char) php_htoi(data + 1); #else *dest = os_toebcdic[(char) php_htoi(data + 1)]; #endif data += 2; len -= 2; } else { *dest = *data; } data++; dest++; } *dest = '\0'; return dest - str; } /* }}} */ /* {{{ php_raw_url_encode */ PHPAPI char *php_raw_url_encode(char const *s, int len, int *new_length) { register int x, y; unsigned char *str; str = (unsigned char *) safe_emalloc(3, len, 1); for (x = 0, y = 0; len--; x++, y++) { str[y] = (unsigned char) s[x]; #ifndef CHARSET_EBCDIC if ((str[y] < '0' && str[y] != '-' && str[y] != '.') || (str[y] < 'A' && str[y] > '9') || (str[y] > 'Z' && str[y] < 'a' && str[y] != '_') || (str[y] > 'z' && str[y] != '~')) { str[y++] = '%'; str[y++] = hexchars[(unsigned char) s[x] >> 4]; str[y] = hexchars[(unsigned char) s[x] & 15]; #else /*CHARSET_EBCDIC*/ if (!isalnum(str[y]) && strchr("_-.~", str[y]) != NULL) { str[y++] = '%'; str[y++] = hexchars[os_toascii[(unsigned char) s[x]] >> 4]; str[y] = hexchars[os_toascii[(unsigned char) s[x]] & 15]; #endif /*CHARSET_EBCDIC*/ } } str[y] = '\0'; if (new_length) { *new_length = y; } return ((char *) str); } /* }}} */ /* {{{ proto string rawurlencode(string str) URL-encodes string */ PHP_FUNCTION(rawurlencode) { char *in_str, *out_str; int in_str_len, out_str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str, &in_str_len) == FAILURE) { return; } out_str = php_raw_url_encode(in_str, in_str_len, &out_str_len); RETURN_STRINGL(out_str, out_str_len, 0); } /* }}} */ /* {{{ proto string rawurldecode(string str) Decodes URL-encodes string */ PHP_FUNCTION(rawurldecode) { char *in_str, *out_str; int in_str_len, out_str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str, &in_str_len) == FAILURE) { return; } out_str = estrndup(in_str, in_str_len); out_str_len = php_raw_url_decode(out_str, in_str_len); RETURN_STRINGL(out_str, out_str_len, 0); } /* }}} */ /* {{{ php_raw_url_decode */ PHPAPI int php_raw_url_decode(char *str, int len) { char *dest = str; char *data = str; while (len--) { if (*data == '%' && len >= 2 && isxdigit((int) *(data + 1)) && isxdigit((int) *(data + 2))) { #ifndef CHARSET_EBCDIC *dest = (char) php_htoi(data + 1); #else *dest = os_toebcdic[(char) php_htoi(data + 1)]; #endif data += 2; len -= 2; } else { *dest = *data; } data++; dest++; } *dest = '\0'; return dest - str; } /* }}} */ /* {{{ proto array get_headers(string url[, int format]) fetches all the headers sent by the server in response to a HTTP request */ PHP_FUNCTION(get_headers) { char *url; int url_len; php_stream_context *context; php_stream *stream; zval **prev_val, **hdr = NULL, **h; HashPosition pos; HashTable *hashT; long format = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &url, &url_len, &format) == FAILURE) { return; } context = FG(default_context) ? FG(default_context) : (FG(default_context) = php_stream_context_alloc(TSRMLS_C)); if (!(stream = php_stream_open_wrapper_ex(url, "r", REPORT_ERRORS | STREAM_USE_URL | STREAM_ONLY_GET_HEADERS, NULL, context))) { RETURN_FALSE; } if (!stream->wrapperdata || Z_TYPE_P(stream->wrapperdata) != IS_ARRAY) { php_stream_close(stream); RETURN_FALSE; } array_init(return_value); /* check for curl-wrappers that provide headers via a special "headers" element */ if (zend_hash_find(HASH_OF(stream->wrapperdata), "headers", sizeof("headers"), (void **)&h) != FAILURE && Z_TYPE_PP(h) == IS_ARRAY) { /* curl-wrappers don't load data until the 1st read */ if (!Z_ARRVAL_PP(h)->nNumOfElements) { php_stream_getc(stream); } zend_hash_find(HASH_OF(stream->wrapperdata), "headers", sizeof("headers"), (void **)&h); hashT = Z_ARRVAL_PP(h); } else { hashT = HASH_OF(stream->wrapperdata); } zend_hash_internal_pointer_reset_ex(hashT, &pos); while (zend_hash_get_current_data_ex(hashT, (void**)&hdr, &pos) != FAILURE) { if (!hdr || Z_TYPE_PP(hdr) != IS_STRING) { zend_hash_move_forward_ex(hashT, &pos); continue; } if (!format) { no_name_header: add_next_index_stringl(return_value, Z_STRVAL_PP(hdr), Z_STRLEN_PP(hdr), 1); } else { char c; char *s, *p; if ((p = strchr(Z_STRVAL_PP(hdr), ':'))) { c = *p; *p = '\0'; s = p + 1; while (isspace((int)*(unsigned char *)s)) { s++; } if (zend_hash_find(HASH_OF(return_value), Z_STRVAL_PP(hdr), (p - Z_STRVAL_PP(hdr) + 1), (void **) &prev_val) == FAILURE) { add_assoc_stringl_ex(return_value, Z_STRVAL_PP(hdr), (p - Z_STRVAL_PP(hdr) + 1), s, (Z_STRLEN_PP(hdr) - (s - Z_STRVAL_PP(hdr))), 1); } else { /* some headers may occur more then once, therefor we need to remake the string into an array */ convert_to_array(*prev_val); add_next_index_stringl(*prev_val, s, (Z_STRLEN_PP(hdr) - (s - Z_STRVAL_PP(hdr))), 1); } *p = c; } else { goto no_name_header; } } zend_hash_move_forward_ex(hashT, &pos); } php_stream_close(stream); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Jim Winstead <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <stdlib.h> #include <string.h> #include <ctype.h> #include <sys/types.h> #include "php.h" #include "url.h" #include "file.h" #ifdef _OSD_POSIX #ifndef APACHE #error On this EBCDIC platform, PHP is only supported as an Apache module. #else /*APACHE*/ #ifndef CHARSET_EBCDIC #define CHARSET_EBCDIC /* this machine uses EBCDIC, not ASCII! */ #endif #include "ebcdic.h" #endif /*APACHE*/ #endif /*_OSD_POSIX*/ /* {{{ free_url */ PHPAPI void php_url_free(php_url *theurl) { if (theurl->scheme) efree(theurl->scheme); if (theurl->user) efree(theurl->user); if (theurl->pass) efree(theurl->pass); if (theurl->host) efree(theurl->host); if (theurl->path) efree(theurl->path); if (theurl->query) efree(theurl->query); if (theurl->fragment) efree(theurl->fragment); efree(theurl); } /* }}} */ /* {{{ php_replace_controlchars */ PHPAPI char *php_replace_controlchars_ex(char *str, int len) { unsigned char *s = (unsigned char *)str; unsigned char *e = (unsigned char *)str + len; if (!str) { return (NULL); } while (s < e) { if (iscntrl(*s)) { *s='_'; } s++; } return (str); } /* }}} */ PHPAPI char *php_replace_controlchars(char *str) { return php_replace_controlchars_ex(str, strlen(str)); } PHPAPI php_url *php_url_parse(char const *str) { return php_url_parse_ex(str, strlen(str)); } /* {{{ php_url_parse */ PHPAPI php_url *php_url_parse_ex(char const *str, int length) { char port_buf[6]; php_url *ret = ecalloc(1, sizeof(php_url)); char const *s, *e, *p, *pp, *ue; s = str; ue = s + length; /* parse scheme */ if ((e = memchr(s, ':', length)) && (e - s)) { /* validate scheme */ p = s; while (p < e) { /* scheme = 1*[ lowalpha | digit | "+" | "-" | "." ] */ if (!isalpha(*p) && !isdigit(*p) && *p != '+' && *p != '.' && *p != '-') { if (e + 1 < ue) { goto parse_port; } else { goto just_path; } } p++; } if (*(e + 1) == '\0') { /* only scheme is available */ ret->scheme = estrndup(s, (e - s)); php_replace_controlchars_ex(ret->scheme, (e - s)); goto end; } /* * certain schemas like mailto: and zlib: may not have any / after them * this check ensures we support those. */ if (*(e+1) != '/') { /* check if the data we get is a port this allows us to * correctly parse things like a.com:80 */ p = e + 1; while (isdigit(*p)) { p++; } if ((*p == '\0' || *p == '/') && (p - e) < 7) { goto parse_port; } ret->scheme = estrndup(s, (e-s)); php_replace_controlchars_ex(ret->scheme, (e - s)); length -= ++e - s; s = e; goto just_path; } else { ret->scheme = estrndup(s, (e-s)); php_replace_controlchars_ex(ret->scheme, (e - s)); if (*(e+2) == '/') { s = e + 3; if (!strncasecmp("file", ret->scheme, sizeof("file"))) { if (*(e + 3) == '/') { /* support windows drive letters as in: file:///c:/somedir/file.txt */ if (*(e + 5) == ':') { s = e + 4; } goto nohost; } } } else { if (!strncasecmp("file", ret->scheme, sizeof("file"))) { s = e + 1; goto nohost; } else { length -= ++e - s; s = e; goto just_path; } } } } else if (e) { /* no scheme; starts with colon: look for port */ parse_port: p = e + 1; pp = p; while (pp-p < 6 && isdigit(*pp)) { pp++; } if (pp - p > 0 && pp - p < 6 && (*pp == '/' || *pp == '\0')) { long port; memcpy(port_buf, p, (pp - p)); port_buf[pp - p] = '\0'; port = strtol(port_buf, NULL, 10); if (port > 0 && port <= 65535) { ret->port = (unsigned short) port; } else { STR_FREE(ret->scheme); efree(ret); return NULL; } } else { goto just_path; } } else { just_path: ue = s + length; goto nohost; } e = ue; if (!(p = memchr(s, '/', (ue - s)))) { char *query, *fragment; query = memchr(s, '?', (ue - s)); fragment = memchr(s, '#', (ue - s)); if (query && fragment) { if (query > fragment) { p = e = fragment; } else { p = e = query; } } else if (query) { p = e = query; } else if (fragment) { p = e = fragment; } } else { e = p; } /* check for login and password */ if ((p = zend_memrchr(s, '@', (e-s)))) { if ((pp = memchr(s, ':', (p-s)))) { if ((pp-s) > 0) { ret->user = estrndup(s, (pp-s)); php_replace_controlchars_ex(ret->user, (pp - s)); } pp++; if (p-pp > 0) { ret->pass = estrndup(pp, (p-pp)); php_replace_controlchars_ex(ret->pass, (p-pp)); } } else { ret->user = estrndup(s, (p-s)); php_replace_controlchars_ex(ret->user, (p-s)); } s = p + 1; } /* check for port */ if (*s == '[' && *(e-1) == ']') { /* Short circuit portscan, we're dealing with an IPv6 embedded address */ p = s; } else { /* memrchr is a GNU specific extension Emulate for wide compatability */ for(p = e; *p != ':' && p >= s; p--); } if (p >= s && *p == ':') { if (!ret->port) { p++; if (e-p > 5) { /* port cannot be longer then 5 characters */ STR_FREE(ret->scheme); STR_FREE(ret->user); STR_FREE(ret->pass); efree(ret); return NULL; } else if (e - p > 0) { long port; memcpy(port_buf, p, (e - p)); port_buf[e - p] = '\0'; port = strtol(port_buf, NULL, 10); if (port > 0 && port <= 65535) { ret->port = (unsigned short)port; } else { STR_FREE(ret->scheme); STR_FREE(ret->user); STR_FREE(ret->pass); efree(ret); return NULL; } } p--; } } else { p = e; } /* check if we have a valid host, if we don't reject the string as url */ if ((p-s) < 1) { STR_FREE(ret->scheme); STR_FREE(ret->user); STR_FREE(ret->pass); efree(ret); return NULL; } ret->host = estrndup(s, (p-s)); php_replace_controlchars_ex(ret->host, (p - s)); if (e == ue) { return ret; } s = e; nohost: if ((p = memchr(s, '?', (ue - s)))) { pp = strchr(s, '#'); if (pp && pp < p) { p = pp; goto label_parse; } if (p - s) { ret->path = estrndup(s, (p-s)); php_replace_controlchars_ex(ret->path, (p - s)); } if (pp) { if (pp - ++p) { ret->query = estrndup(p, (pp-p)); php_replace_controlchars_ex(ret->query, (pp - p)); } p = pp; goto label_parse; } else if (++p - ue) { ret->query = estrndup(p, (ue-p)); php_replace_controlchars_ex(ret->query, (ue - p)); } } else if ((p = memchr(s, '#', (ue - s)))) { if (p - s) { ret->path = estrndup(s, (p-s)); php_replace_controlchars_ex(ret->path, (p - s)); } label_parse: p++; if (ue - p) { ret->fragment = estrndup(p, (ue-p)); php_replace_controlchars_ex(ret->fragment, (ue - p)); } } else { ret->path = estrndup(s, (ue-s)); php_replace_controlchars_ex(ret->path, (ue - s)); } end: return ret; } /* }}} */ /* {{{ proto mixed parse_url(string url, [int url_component]) Parse a URL and return its components */ PHP_FUNCTION(parse_url) { char *str; int str_len; php_url *resource; long key = -1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &str, &str_len, &key) == FAILURE) { return; } resource = php_url_parse_ex(str, str_len); if (resource == NULL) { /* @todo Find a method to determine why php_url_parse_ex() failed */ RETURN_FALSE; } if (key > -1) { switch (key) { case PHP_URL_SCHEME: if (resource->scheme != NULL) RETVAL_STRING(resource->scheme, 1); break; case PHP_URL_HOST: if (resource->host != NULL) RETVAL_STRING(resource->host, 1); break; case PHP_URL_PORT: if (resource->port != 0) RETVAL_LONG(resource->port); break; case PHP_URL_USER: if (resource->user != NULL) RETVAL_STRING(resource->user, 1); break; case PHP_URL_PASS: if (resource->pass != NULL) RETVAL_STRING(resource->pass, 1); break; case PHP_URL_PATH: if (resource->path != NULL) RETVAL_STRING(resource->path, 1); break; case PHP_URL_QUERY: if (resource->query != NULL) RETVAL_STRING(resource->query, 1); break; case PHP_URL_FRAGMENT: if (resource->fragment != NULL) RETVAL_STRING(resource->fragment, 1); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid URL component identifier %ld", key); RETVAL_FALSE; } goto done; } /* allocate an array for return */ array_init(return_value); /* add the various elements to the array */ if (resource->scheme != NULL) add_assoc_string(return_value, "scheme", resource->scheme, 1); if (resource->host != NULL) add_assoc_string(return_value, "host", resource->host, 1); if (resource->port != 0) add_assoc_long(return_value, "port", resource->port); if (resource->user != NULL) add_assoc_string(return_value, "user", resource->user, 1); if (resource->pass != NULL) add_assoc_string(return_value, "pass", resource->pass, 1); if (resource->path != NULL) add_assoc_string(return_value, "path", resource->path, 1); if (resource->query != NULL) add_assoc_string(return_value, "query", resource->query, 1); if (resource->fragment != NULL) add_assoc_string(return_value, "fragment", resource->fragment, 1); done: php_url_free(resource); } /* }}} */ /* {{{ php_htoi */ static int php_htoi(char *s) { int value; int c; c = ((unsigned char *)s)[0]; if (isupper(c)) c = tolower(c); value = (c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10) * 16; c = ((unsigned char *)s)[1]; if (isupper(c)) c = tolower(c); value += c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10; return (value); } /* }}} */ /* rfc1738: ...The characters ";", "/", "?", ":", "@", "=" and "&" are the characters which may be reserved for special meaning within a scheme... ...Thus, only alphanumerics, the special characters "$-_.+!*'(),", and reserved characters used for their reserved purposes may be used unencoded within a URL... For added safety, we only leave -_. unencoded. */ static unsigned char hexchars[] = "0123456789ABCDEF"; /* {{{ php_url_encode */ PHPAPI char *php_url_encode(char const *s, int len, int *new_length) { register unsigned char c; unsigned char *to, *start; unsigned char const *from, *end; from = (unsigned char *)s; end = (unsigned char *)s + len; start = to = (unsigned char *) safe_emalloc(3, len, 1); while (from < end) { c = *from++; if (c == ' ') { *to++ = '+'; #ifndef CHARSET_EBCDIC } else if ((c < '0' && c != '-' && c != '.') || (c < 'A' && c > '9') || (c > 'Z' && c < 'a' && c != '_') || (c > 'z')) { to[0] = '%'; to[1] = hexchars[c >> 4]; to[2] = hexchars[c & 15]; to += 3; #else /*CHARSET_EBCDIC*/ } else if (!isalnum(c) && strchr("_-.", c) == NULL) { /* Allow only alphanumeric chars and '_', '-', '.'; escape the rest */ to[0] = '%'; to[1] = hexchars[os_toascii[c] >> 4]; to[2] = hexchars[os_toascii[c] & 15]; to += 3; #endif /*CHARSET_EBCDIC*/ } else { *to++ = c; } } *to = 0; if (new_length) { *new_length = to - start; } return (char *) start; } /* }}} */ /* {{{ proto string urlencode(string str) URL-encodes string */ PHP_FUNCTION(urlencode) { char *in_str, *out_str; int in_str_len, out_str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str, &in_str_len) == FAILURE) { return; } out_str = php_url_encode(in_str, in_str_len, &out_str_len); RETURN_STRINGL(out_str, out_str_len, 0); } /* }}} */ /* {{{ proto string urldecode(string str) Decodes URL-encoded string */ PHP_FUNCTION(urldecode) { char *in_str, *out_str; int in_str_len, out_str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str, &in_str_len) == FAILURE) { return; } out_str = estrndup(in_str, in_str_len); out_str_len = php_url_decode(out_str, in_str_len); RETURN_STRINGL(out_str, out_str_len, 0); } /* }}} */ /* {{{ php_url_decode */ PHPAPI int php_url_decode(char *str, int len) { char *dest = str; char *data = str; while (len--) { if (*data == '+') { *dest = ' '; } else if (*data == '%' && len >= 2 && isxdigit((int) *(data + 1)) && isxdigit((int) *(data + 2))) { #ifndef CHARSET_EBCDIC *dest = (char) php_htoi(data + 1); #else *dest = os_toebcdic[(char) php_htoi(data + 1)]; #endif data += 2; len -= 2; } else { *dest = *data; } data++; dest++; } *dest = '\0'; return dest - str; } /* }}} */ /* {{{ php_raw_url_encode */ PHPAPI char *php_raw_url_encode(char const *s, int len, int *new_length) { register int x, y; unsigned char *str; str = (unsigned char *) safe_emalloc(3, len, 1); for (x = 0, y = 0; len--; x++, y++) { str[y] = (unsigned char) s[x]; #ifndef CHARSET_EBCDIC if ((str[y] < '0' && str[y] != '-' && str[y] != '.') || (str[y] < 'A' && str[y] > '9') || (str[y] > 'Z' && str[y] < 'a' && str[y] != '_') || (str[y] > 'z' && str[y] != '~')) { str[y++] = '%'; str[y++] = hexchars[(unsigned char) s[x] >> 4]; str[y] = hexchars[(unsigned char) s[x] & 15]; #else /*CHARSET_EBCDIC*/ if (!isalnum(str[y]) && strchr("_-.~", str[y]) != NULL) { str[y++] = '%'; str[y++] = hexchars[os_toascii[(unsigned char) s[x]] >> 4]; str[y] = hexchars[os_toascii[(unsigned char) s[x]] & 15]; #endif /*CHARSET_EBCDIC*/ } } str[y] = '\0'; if (new_length) { *new_length = y; } return ((char *) str); } /* }}} */ /* {{{ proto string rawurlencode(string str) URL-encodes string */ PHP_FUNCTION(rawurlencode) { char *in_str, *out_str; int in_str_len, out_str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str, &in_str_len) == FAILURE) { return; } out_str = php_raw_url_encode(in_str, in_str_len, &out_str_len); RETURN_STRINGL(out_str, out_str_len, 0); } /* }}} */ /* {{{ proto string rawurldecode(string str) Decodes URL-encodes string */ PHP_FUNCTION(rawurldecode) { char *in_str, *out_str; int in_str_len, out_str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in_str, &in_str_len) == FAILURE) { return; } out_str = estrndup(in_str, in_str_len); out_str_len = php_raw_url_decode(out_str, in_str_len); RETURN_STRINGL(out_str, out_str_len, 0); } /* }}} */ /* {{{ php_raw_url_decode */ PHPAPI int php_raw_url_decode(char *str, int len) { char *dest = str; char *data = str; while (len--) { if (*data == '%' && len >= 2 && isxdigit((int) *(data + 1)) && isxdigit((int) *(data + 2))) { #ifndef CHARSET_EBCDIC *dest = (char) php_htoi(data + 1); #else *dest = os_toebcdic[(char) php_htoi(data + 1)]; #endif data += 2; len -= 2; } else { *dest = *data; } data++; dest++; } *dest = '\0'; return dest - str; } /* }}} */ /* {{{ proto array get_headers(string url[, int format]) fetches all the headers sent by the server in response to a HTTP request */ PHP_FUNCTION(get_headers) { char *url; int url_len; php_stream_context *context; php_stream *stream; zval **prev_val, **hdr = NULL, **h; HashPosition pos; HashTable *hashT; long format = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &url, &url_len, &format) == FAILURE) { return; } context = FG(default_context) ? FG(default_context) : (FG(default_context) = php_stream_context_alloc(TSRMLS_C)); if (!(stream = php_stream_open_wrapper_ex(url, "r", REPORT_ERRORS | STREAM_USE_URL | STREAM_ONLY_GET_HEADERS, NULL, context))) { RETURN_FALSE; } if (!stream->wrapperdata || Z_TYPE_P(stream->wrapperdata) != IS_ARRAY) { php_stream_close(stream); RETURN_FALSE; } array_init(return_value); /* check for curl-wrappers that provide headers via a special "headers" element */ if (zend_hash_find(HASH_OF(stream->wrapperdata), "headers", sizeof("headers"), (void **)&h) != FAILURE && Z_TYPE_PP(h) == IS_ARRAY) { /* curl-wrappers don't load data until the 1st read */ if (!Z_ARRVAL_PP(h)->nNumOfElements) { php_stream_getc(stream); } zend_hash_find(HASH_OF(stream->wrapperdata), "headers", sizeof("headers"), (void **)&h); hashT = Z_ARRVAL_PP(h); } else { hashT = HASH_OF(stream->wrapperdata); } zend_hash_internal_pointer_reset_ex(hashT, &pos); while (zend_hash_get_current_data_ex(hashT, (void**)&hdr, &pos) != FAILURE) { if (!hdr || Z_TYPE_PP(hdr) != IS_STRING) { zend_hash_move_forward_ex(hashT, &pos); continue; } if (!format) { no_name_header: add_next_index_stringl(return_value, Z_STRVAL_PP(hdr), Z_STRLEN_PP(hdr), 1); } else { char c; char *s, *p; if ((p = strchr(Z_STRVAL_PP(hdr), ':'))) { c = *p; *p = '\0'; s = p + 1; while (isspace((int)*(unsigned char *)s)) { s++; } if (zend_hash_find(HASH_OF(return_value), Z_STRVAL_PP(hdr), (p - Z_STRVAL_PP(hdr) + 1), (void **) &prev_val) == FAILURE) { add_assoc_stringl_ex(return_value, Z_STRVAL_PP(hdr), (p - Z_STRVAL_PP(hdr) + 1), s, (Z_STRLEN_PP(hdr) - (s - Z_STRVAL_PP(hdr))), 1); } else { /* some headers may occur more then once, therefor we need to remake the string into an array */ convert_to_array(*prev_val); add_next_index_stringl(*prev_val, s, (Z_STRLEN_PP(hdr) - (s - Z_STRVAL_PP(hdr))), 1); } *p = c; } else { goto no_name_header; } } zend_hash_move_forward_ex(hashT, &pos); } php_stream_close(stream); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-02-05-c50b3d7add-426f31e790.c
manybugs_data_65
/* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library. * * Directory Write Support Routines. */ #include "tiffiop.h" #ifdef HAVE_IEEEFP #define TIFFCvtNativeToIEEEFloat(tif, n, fp) #define TIFFCvtNativeToIEEEDouble(tif, n, dp) #else extern void TIFFCvtNativeToIEEEFloat(TIFF* tif, uint32 n, float* fp); extern void TIFFCvtNativeToIEEEDouble(TIFF* tif, uint32 n, double* dp); #endif static int TIFFWriteDirectorySec(TIFF* tif, int isimage, int imagedone, uint64* pdiroff); static int TIFFWriteDirectoryTagSampleformatPerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, double value); static int TIFFWriteDirectoryTagAscii(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, char* value); static int TIFFWriteDirectoryTagUndefinedArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint8* value); static int TIFFWriteDirectoryTagByte(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint8 value); static int TIFFWriteDirectoryTagByteArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint8* value); static int TIFFWriteDirectoryTagBytePerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint8 value); static int TIFFWriteDirectoryTagSbyte(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int8 value); static int TIFFWriteDirectoryTagSbyteArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int8* value); static int TIFFWriteDirectoryTagSbytePerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int8 value); static int TIFFWriteDirectoryTagShort(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint16 value); static int TIFFWriteDirectoryTagShortArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint16* value); static int TIFFWriteDirectoryTagShortPerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint16 value); static int TIFFWriteDirectoryTagSshort(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int16 value); static int TIFFWriteDirectoryTagSshortArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int16* value); static int TIFFWriteDirectoryTagSshortPerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int16 value); static int TIFFWriteDirectoryTagLong(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 value); static int TIFFWriteDirectoryTagLongArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint32* value); static int TIFFWriteDirectoryTagLongPerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 value); static int TIFFWriteDirectoryTagSlong(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int32 value); static int TIFFWriteDirectoryTagSlongArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int32* value); static int TIFFWriteDirectoryTagSlongPerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int32 value); static int TIFFWriteDirectoryTagLong8(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint64 value); static int TIFFWriteDirectoryTagLong8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint64* value); static int TIFFWriteDirectoryTagSlong8(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int64 value); static int TIFFWriteDirectoryTagSlong8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int64* value); static int TIFFWriteDirectoryTagRational(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, double value); static int TIFFWriteDirectoryTagRationalArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, float* value); static int TIFFWriteDirectoryTagSrationalArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, float* value); static int TIFFWriteDirectoryTagFloat(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, float value); static int TIFFWriteDirectoryTagFloatArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, float* value); static int TIFFWriteDirectoryTagFloatPerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, float value); static int TIFFWriteDirectoryTagDouble(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, double value); static int TIFFWriteDirectoryTagDoubleArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, double* value); static int TIFFWriteDirectoryTagDoublePerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, double value); static int TIFFWriteDirectoryTagIfdArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint32* value); static int TIFFWriteDirectoryTagIfd8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint64* value); static int TIFFWriteDirectoryTagShortLong(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 value); static int TIFFWriteDirectoryTagLongLong8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint64* value); static int TIFFWriteDirectoryTagShortLongLong8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint64* value); static int TIFFWriteDirectoryTagColormap(TIFF* tif, uint32* ndir, TIFFDirEntry* dir); static int TIFFWriteDirectoryTagTransferfunction(TIFF* tif, uint32* ndir, TIFFDirEntry* dir); static int TIFFWriteDirectoryTagSubifd(TIFF* tif, uint32* ndir, TIFFDirEntry* dir); static int TIFFWriteDirectoryTagCheckedAscii(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, char* value); static int TIFFWriteDirectoryTagCheckedUndefinedArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint8* value); static int TIFFWriteDirectoryTagCheckedByte(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint8 value); static int TIFFWriteDirectoryTagCheckedByteArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint8* value); static int TIFFWriteDirectoryTagCheckedSbyte(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int8 value); static int TIFFWriteDirectoryTagCheckedSbyteArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int8* value); static int TIFFWriteDirectoryTagCheckedShort(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint16 value); static int TIFFWriteDirectoryTagCheckedShortArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint16* value); static int TIFFWriteDirectoryTagCheckedSshort(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int16 value); static int TIFFWriteDirectoryTagCheckedSshortArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int16* value); static int TIFFWriteDirectoryTagCheckedLong(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 value); static int TIFFWriteDirectoryTagCheckedLongArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint32* value); static int TIFFWriteDirectoryTagCheckedSlong(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int32 value); static int TIFFWriteDirectoryTagCheckedSlongArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int32* value); static int TIFFWriteDirectoryTagCheckedLong8(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint64 value); static int TIFFWriteDirectoryTagCheckedLong8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint64* value); static int TIFFWriteDirectoryTagCheckedSlong8(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int64 value); static int TIFFWriteDirectoryTagCheckedSlong8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int64* value); static int TIFFWriteDirectoryTagCheckedRational(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, double value); static int TIFFWriteDirectoryTagCheckedRationalArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, float* value); static int TIFFWriteDirectoryTagCheckedSrationalArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, float* value); static int TIFFWriteDirectoryTagCheckedFloat(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, float value); static int TIFFWriteDirectoryTagCheckedFloatArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, float* value); static int TIFFWriteDirectoryTagCheckedDouble(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, double value); static int TIFFWriteDirectoryTagCheckedDoubleArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, double* value); static int TIFFWriteDirectoryTagCheckedIfdArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint32* value); static int TIFFWriteDirectoryTagCheckedIfd8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint64* value); static int TIFFWriteDirectoryTagData(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint16 datatype, uint32 count, uint32 datalength, void* data); static int TIFFLinkDirectory(TIFF*); /* * Write the contents of the current directory * to the specified file. This routine doesn't * handle overwriting a directory with auxiliary * storage that's been changed. */ int TIFFWriteDirectory(TIFF* tif) { return TIFFWriteDirectorySec(tif,TRUE,TRUE,NULL); } /* * Similar to TIFFWriteDirectory(), writes the directory out * but leaves all data structures in memory so that it can be * written again. This will make a partially written TIFF file * readable before it is successfully completed/closed. */ int TIFFCheckpointDirectory(TIFF* tif) { int rc; /* Setup the strips arrays, if they haven't already been. */ if (tif->tif_dir.td_stripoffset == NULL) (void) TIFFSetupStrips(tif); rc = TIFFWriteDirectorySec(tif,TRUE,FALSE,NULL); (void) TIFFSetWriteOffset(tif, TIFFSeekFile(tif, 0, SEEK_END)); return rc; } int TIFFWriteCustomDirectory(TIFF* tif, uint64* pdiroff) { return TIFFWriteDirectorySec(tif,FALSE,FALSE,pdiroff); } /* * Similar to TIFFWriteDirectory(), but if the directory has already * been written once, it is relocated to the end of the file, in case it * has changed in size. Note that this will result in the loss of the * previously used directory space. */ int TIFFRewriteDirectory( TIFF *tif ) { static const char module[] = "TIFFRewriteDirectory"; /* We don't need to do anything special if it hasn't been written. */ if( tif->tif_diroff == 0 ) return TIFFWriteDirectory( tif ); /* * Find and zero the pointer to this directory, so that TIFFLinkDirectory * will cause it to be added after this directories current pre-link. */ if (!(tif->tif_flags&TIFF_BIGTIFF)) { if (tif->tif_header.classic.tiff_diroff == tif->tif_diroff) { tif->tif_header.classic.tiff_diroff = 0; tif->tif_diroff = 0; TIFFSeekFile(tif,4,SEEK_SET); if (!WriteOK(tif, &(tif->tif_header.classic.tiff_diroff),4)) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error updating TIFF header"); return (0); } } else { uint32 nextdir; nextdir = tif->tif_header.classic.tiff_diroff; while(1) { uint16 dircount; uint32 nextnextdir; if (!SeekOK(tif, nextdir) || !ReadOK(tif, &dircount, 2)) { TIFFErrorExt(tif->tif_clientdata, module, "Error fetching directory count"); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); (void) TIFFSeekFile(tif, nextdir+2+dircount*12, SEEK_SET); if (!ReadOK(tif, &nextnextdir, 4)) { TIFFErrorExt(tif->tif_clientdata, module, "Error fetching directory link"); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong(&nextnextdir); if (nextnextdir==tif->tif_diroff) { uint32 m; m=0; (void) TIFFSeekFile(tif, nextdir+2+dircount*12, SEEK_SET); if (!WriteOK(tif, &m, 4)) { TIFFErrorExt(tif->tif_clientdata, module, "Error writing directory link"); return (0); } tif->tif_diroff=0; break; } nextdir=nextnextdir; } } } else { if (tif->tif_header.big.tiff_diroff == tif->tif_diroff) { tif->tif_header.big.tiff_diroff = 0; tif->tif_diroff = 0; TIFFSeekFile(tif,8,SEEK_SET); if (!WriteOK(tif, &(tif->tif_header.big.tiff_diroff),8)) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error updating TIFF header"); return (0); } } else { uint64 nextdir; nextdir = tif->tif_header.big.tiff_diroff; while(1) { uint64 dircount64; uint16 dircount; uint64 nextnextdir; if (!SeekOK(tif, nextdir) || !ReadOK(tif, &dircount64, 8)) { TIFFErrorExt(tif->tif_clientdata, module, "Error fetching directory count"); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong8(&dircount64); if (dircount64>0xFFFF) { TIFFErrorExt(tif->tif_clientdata, module, "Sanity check on tag count failed, likely corrupt TIFF"); return (0); } dircount=(uint16)dircount64; (void) TIFFSeekFile(tif, nextdir+8+dircount*20, SEEK_SET); if (!ReadOK(tif, &nextnextdir, 8)) { TIFFErrorExt(tif->tif_clientdata, module, "Error fetching directory link"); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong8(&nextnextdir); if (nextnextdir==tif->tif_diroff) { uint64 m; m=0; (void) TIFFSeekFile(tif, nextdir+8+dircount*20, SEEK_SET); if (!WriteOK(tif, &m, 8)) { TIFFErrorExt(tif->tif_clientdata, module, "Error writing directory link"); return (0); } tif->tif_diroff=0; break; } nextdir=nextnextdir; } } } /* * Now use TIFFWriteDirectory() normally. */ return TIFFWriteDirectory( tif ); } static int TIFFWriteDirectorySec(TIFF* tif, int isimage, int imagedone, uint64* pdiroff) { static const char module[] = "TIFFWriteDirectorySec"; uint32 ndir; TIFFDirEntry* dir; uint32 dirsize; void* dirmem; uint32 m; if (tif->tif_mode == O_RDONLY) return (1); /* * Clear write state so that subsequent images with * different characteristics get the right buffers * setup for them. */ if (imagedone) { tmsize_t orig_rawcc = tif->tif_rawcc; if (tif->tif_flags & TIFF_POSTENCODE) { tif->tif_flags &= ~TIFF_POSTENCODE; if (!(*tif->tif_postencode)(tif)) { TIFFErrorExt(tif->tif_clientdata,module, "Error post-encoding before directory write"); return (0); } } (*tif->tif_close)(tif); /* shutdown encoder */ /* * Flush any data that might have been written * by the compression close+cleanup routines. But * be careful not to write stuff if we didn't add data * in the previous steps as the "rawcc" data may well be * a previously read tile/strip in mixed read/write mode. */ if (tif->tif_rawcc > 0 && tif->tif_rawcc != orig_rawcc && (tif->tif_flags & TIFF_BEENWRITING) != 0 && !TIFFFlushData1(tif)) { TIFFErrorExt(tif->tif_clientdata, module, "Error flushing data before directory write"); return (0); } if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata) { _TIFFfree(tif->tif_rawdata); tif->tif_rawdata = NULL; tif->tif_rawcc = 0; tif->tif_rawdatasize = 0; } tif->tif_flags &= ~(TIFF_BEENWRITING|TIFF_BUFFERSETUP); } dir=NULL; dirmem=NULL; dirsize=0; while (1) { ndir=0; if (isimage) { if (TIFFFieldSet(tif,FIELD_IMAGEDIMENSIONS)) { if (!TIFFWriteDirectoryTagShortLong(tif,&ndir,dir,TIFFTAG_IMAGEWIDTH,tif->tif_dir.td_imagewidth)) goto bad; if (!TIFFWriteDirectoryTagShortLong(tif,&ndir,dir,TIFFTAG_IMAGELENGTH,tif->tif_dir.td_imagelength)) goto bad; } if (TIFFFieldSet(tif,FIELD_TILEDIMENSIONS)) { if (!TIFFWriteDirectoryTagShortLong(tif,&ndir,dir,TIFFTAG_TILEWIDTH,tif->tif_dir.td_tilewidth)) goto bad; if (!TIFFWriteDirectoryTagShortLong(tif,&ndir,dir,TIFFTAG_TILELENGTH,tif->tif_dir.td_tilelength)) goto bad; } if (TIFFFieldSet(tif,FIELD_RESOLUTION)) { if (!TIFFWriteDirectoryTagRational(tif,&ndir,dir,TIFFTAG_XRESOLUTION,tif->tif_dir.td_xresolution)) goto bad; if (!TIFFWriteDirectoryTagRational(tif,&ndir,dir,TIFFTAG_YRESOLUTION,tif->tif_dir.td_yresolution)) goto bad; } if (TIFFFieldSet(tif,FIELD_POSITION)) { if (!TIFFWriteDirectoryTagRational(tif,&ndir,dir,TIFFTAG_XPOSITION,tif->tif_dir.td_xposition)) goto bad; if (!TIFFWriteDirectoryTagRational(tif,&ndir,dir,TIFFTAG_YPOSITION,tif->tif_dir.td_yposition)) goto bad; } if (TIFFFieldSet(tif,FIELD_SUBFILETYPE)) { if (!TIFFWriteDirectoryTagLong(tif,&ndir,dir,TIFFTAG_SUBFILETYPE,tif->tif_dir.td_subfiletype)) goto bad; } if (TIFFFieldSet(tif,FIELD_BITSPERSAMPLE)) { if (!TIFFWriteDirectoryTagShortPerSample(tif,&ndir,dir,TIFFTAG_BITSPERSAMPLE,tif->tif_dir.td_bitspersample)) goto bad; } if (TIFFFieldSet(tif,FIELD_COMPRESSION)) { if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_COMPRESSION,tif->tif_dir.td_compression)) goto bad; } if (TIFFFieldSet(tif,FIELD_PHOTOMETRIC)) { if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_PHOTOMETRIC,tif->tif_dir.td_photometric)) goto bad; } if (TIFFFieldSet(tif,FIELD_THRESHHOLDING)) { if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_THRESHHOLDING,tif->tif_dir.td_threshholding)) goto bad; } if (TIFFFieldSet(tif,FIELD_FILLORDER)) { if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_FILLORDER,tif->tif_dir.td_fillorder)) goto bad; } if (TIFFFieldSet(tif,FIELD_ORIENTATION)) { if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_ORIENTATION,tif->tif_dir.td_orientation)) goto bad; } if (TIFFFieldSet(tif,FIELD_SAMPLESPERPIXEL)) { if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_SAMPLESPERPIXEL,tif->tif_dir.td_samplesperpixel)) goto bad; } if (TIFFFieldSet(tif,FIELD_ROWSPERSTRIP)) { if (!TIFFWriteDirectoryTagShortLong(tif,&ndir,dir,TIFFTAG_ROWSPERSTRIP,tif->tif_dir.td_rowsperstrip)) goto bad; } if (TIFFFieldSet(tif,FIELD_MINSAMPLEVALUE)) { if (!TIFFWriteDirectoryTagShortPerSample(tif,&ndir,dir,TIFFTAG_MINSAMPLEVALUE,tif->tif_dir.td_minsamplevalue)) goto bad; } if (TIFFFieldSet(tif,FIELD_MAXSAMPLEVALUE)) { if (!TIFFWriteDirectoryTagShortPerSample(tif,&ndir,dir,TIFFTAG_MAXSAMPLEVALUE,tif->tif_dir.td_maxsamplevalue)) goto bad; } if (TIFFFieldSet(tif,FIELD_PLANARCONFIG)) { if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_PLANARCONFIG,tif->tif_dir.td_planarconfig)) goto bad; } if (TIFFFieldSet(tif,FIELD_RESOLUTIONUNIT)) { if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_RESOLUTIONUNIT,tif->tif_dir.td_resolutionunit)) goto bad; } if (TIFFFieldSet(tif,FIELD_PAGENUMBER)) { if (!TIFFWriteDirectoryTagShortArray(tif,&ndir,dir,TIFFTAG_PAGENUMBER,2,&tif->tif_dir.td_pagenumber[0])) goto bad; } if (TIFFFieldSet(tif,FIELD_STRIPBYTECOUNTS)) { if (!isTiled(tif)) { if (!TIFFWriteDirectoryTagLongLong8Array(tif,&ndir,dir,TIFFTAG_STRIPBYTECOUNTS,tif->tif_dir.td_nstrips,tif->tif_dir.td_stripbytecount)) goto bad; } else { if (!TIFFWriteDirectoryTagLongLong8Array(tif,&ndir,dir,TIFFTAG_TILEBYTECOUNTS,tif->tif_dir.td_nstrips,tif->tif_dir.td_stripbytecount)) goto bad; } } if (TIFFFieldSet(tif,FIELD_STRIPOFFSETS)) { if (!isTiled(tif)) { if (!TIFFWriteDirectoryTagLongLong8Array(tif,&ndir,dir,TIFFTAG_STRIPOFFSETS,tif->tif_dir.td_nstrips,tif->tif_dir.td_stripoffset)) goto bad; } else { if (!TIFFWriteDirectoryTagLongLong8Array(tif,&ndir,dir,TIFFTAG_TILEOFFSETS,tif->tif_dir.td_nstrips,tif->tif_dir.td_stripoffset)) goto bad; } } if (TIFFFieldSet(tif,FIELD_COLORMAP)) { if (!TIFFWriteDirectoryTagColormap(tif,&ndir,dir)) goto bad; } if (TIFFFieldSet(tif,FIELD_EXTRASAMPLES)) { if (tif->tif_dir.td_extrasamples) { uint16 na; uint16* nb; TIFFGetFieldDefaulted(tif,TIFFTAG_EXTRASAMPLES,&na,&nb); if (!TIFFWriteDirectoryTagShortArray(tif,&ndir,dir,TIFFTAG_EXTRASAMPLES,na,nb)) goto bad; } } if (TIFFFieldSet(tif,FIELD_SAMPLEFORMAT)) { if (!TIFFWriteDirectoryTagShortPerSample(tif,&ndir,dir,TIFFTAG_SAMPLEFORMAT,tif->tif_dir.td_sampleformat)) goto bad; } if (TIFFFieldSet(tif,FIELD_SMINSAMPLEVALUE)) { if (!TIFFWriteDirectoryTagSampleformatPerSample(tif,&ndir,dir,TIFFTAG_SMINSAMPLEVALUE,tif->tif_dir.td_sminsamplevalue)) goto bad; } if (TIFFFieldSet(tif,FIELD_SMAXSAMPLEVALUE)) { if (!TIFFWriteDirectoryTagSampleformatPerSample(tif,&ndir,dir,TIFFTAG_SMAXSAMPLEVALUE,tif->tif_dir.td_smaxsamplevalue)) goto bad; } if (TIFFFieldSet(tif,FIELD_IMAGEDEPTH)) { if (!TIFFWriteDirectoryTagLong(tif,&ndir,dir,TIFFTAG_IMAGEDEPTH,tif->tif_dir.td_imagedepth)) goto bad; } if (TIFFFieldSet(tif,FIELD_TILEDEPTH)) { if (!TIFFWriteDirectoryTagLong(tif,&ndir,dir,TIFFTAG_TILEDEPTH,tif->tif_dir.td_tiledepth)) goto bad; } if (TIFFFieldSet(tif,FIELD_HALFTONEHINTS)) { if (!TIFFWriteDirectoryTagShortArray(tif,&ndir,dir,TIFFTAG_HALFTONEHINTS,2,&tif->tif_dir.td_halftonehints[0])) goto bad; } if (TIFFFieldSet(tif,FIELD_YCBCRSUBSAMPLING)) { if (!TIFFWriteDirectoryTagShortArray(tif,&ndir,dir,TIFFTAG_YCBCRSUBSAMPLING,2,&tif->tif_dir.td_ycbcrsubsampling[0])) goto bad; } if (TIFFFieldSet(tif,FIELD_YCBCRPOSITIONING)) { if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_YCBCRPOSITIONING,tif->tif_dir.td_ycbcrpositioning)) goto bad; } if (TIFFFieldSet(tif,FIELD_TRANSFERFUNCTION)) { if (!TIFFWriteDirectoryTagTransferfunction(tif,&ndir,dir)) goto bad; } if (TIFFFieldSet(tif,FIELD_INKNAMES)) { if (!TIFFWriteDirectoryTagAscii(tif,&ndir,dir,TIFFTAG_INKNAMES,tif->tif_dir.td_inknameslen,tif->tif_dir.td_inknames)) goto bad; } if (TIFFFieldSet(tif,FIELD_SUBIFD)) { if (!TIFFWriteDirectoryTagSubifd(tif,&ndir,dir)) goto bad; } { uint32 n; for (n=0; n<tif->tif_nfields; n++) { const TIFFField* o; o = tif->tif_fields[n]; if ((o->field_bit>=FIELD_CODEC)&&(TIFFFieldSet(tif,o->field_bit))) { switch (o->get_field_type) { case TIFF_SETGET_ASCII: { uint32 pa; char* pb; assert(o->field_type==TIFF_ASCII); assert(o->field_readcount==TIFF_VARIABLE); assert(o->field_passcount==0); TIFFGetField(tif,o->field_tag,&pb); pa=(uint32)(strlen(pb)); if (!TIFFWriteDirectoryTagAscii(tif,&ndir,dir,o->field_tag,pa,pb)) goto bad; } break; case TIFF_SETGET_UINT16: { uint16 p; assert(o->field_type==TIFF_SHORT); assert(o->field_readcount==1); assert(o->field_passcount==0); TIFFGetField(tif,o->field_tag,&p); if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,o->field_tag,p)) goto bad; } break; case TIFF_SETGET_UINT32: { uint32 p; assert(o->field_type==TIFF_LONG); assert(o->field_readcount==1); assert(o->field_passcount==0); TIFFGetField(tif,o->field_tag,&p); if (!TIFFWriteDirectoryTagLong(tif,&ndir,dir,o->field_tag,p)) goto bad; } break; case TIFF_SETGET_C32_UINT8: { uint32 pa; void* pb; assert(o->field_type==TIFF_UNDEFINED); assert(o->field_readcount==TIFF_VARIABLE2); assert(o->field_passcount==1); TIFFGetField(tif,o->field_tag,&pa,&pb); if (!TIFFWriteDirectoryTagUndefinedArray(tif,&ndir,dir,o->field_tag,pa,pb)) goto bad; } break; default: assert(0); /* we should never get here */ break; } } } } } for (m=0; m<(uint32)(tif->tif_dir.td_customValueCount); m++) { switch (tif->tif_dir.td_customValues[m].info->field_type) { case TIFF_ASCII: if (!TIFFWriteDirectoryTagAscii(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_UNDEFINED: if (!TIFFWriteDirectoryTagUndefinedArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_BYTE: if (!TIFFWriteDirectoryTagByteArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_SBYTE: if (!TIFFWriteDirectoryTagSbyteArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_SHORT: if (!TIFFWriteDirectoryTagShortArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_SSHORT: if (!TIFFWriteDirectoryTagSshortArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_LONG: if (!TIFFWriteDirectoryTagLongArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_SLONG: if (!TIFFWriteDirectoryTagSlongArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_LONG8: if (!TIFFWriteDirectoryTagLong8Array(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_SLONG8: if (!TIFFWriteDirectoryTagSlong8Array(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_RATIONAL: if (!TIFFWriteDirectoryTagRationalArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_SRATIONAL: if (!TIFFWriteDirectoryTagSrationalArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_FLOAT: if (!TIFFWriteDirectoryTagFloatArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_DOUBLE: if (!TIFFWriteDirectoryTagDoubleArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_IFD: if (!TIFFWriteDirectoryTagIfdArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_IFD8: if (!TIFFWriteDirectoryTagIfd8Array(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; default: assert(0); /* we should never get here */ break; } } if (dir!=NULL) break; dir=_TIFFmalloc(ndir*sizeof(TIFFDirEntry)); if (dir==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); goto bad; } if (isimage) { if ((tif->tif_diroff==0)&&(!TIFFLinkDirectory(tif))) goto bad; } else tif->tif_diroff=(TIFFSeekFile(tif,0,SEEK_END)+1)&(~1); if (pdiroff!=NULL) *pdiroff=tif->tif_diroff; if (!(tif->tif_flags&TIFF_BIGTIFF)) dirsize=2+ndir*12+4; else dirsize=8+ndir*20+8; tif->tif_dataoff=tif->tif_diroff+dirsize; if (!(tif->tif_flags&TIFF_BIGTIFF)) tif->tif_dataoff=(uint32)tif->tif_dataoff; if ((tif->tif_dataoff<tif->tif_diroff)||(tif->tif_dataoff<(uint64)dirsize)) { TIFFErrorExt(tif->tif_clientdata,module,"Maximum TIFF file size exceeded"); goto bad; } if (tif->tif_dataoff&1) tif->tif_dataoff++; if (isimage) tif->tif_curdir++; } if (isimage) { if (TIFFFieldSet(tif,FIELD_SUBIFD)&&(tif->tif_subifdoff==0)) { uint32 na; TIFFDirEntry* nb; for (na=0, nb=dir; ; na++, nb++) { assert(na<ndir); if (nb->tdir_tag==TIFFTAG_SUBIFD) break; } if (!(tif->tif_flags&TIFF_BIGTIFF)) tif->tif_subifdoff=tif->tif_diroff+2+na*12+8; else tif->tif_subifdoff=tif->tif_diroff+8+na*20+12; } } dirmem=_TIFFmalloc(dirsize); if (dirmem==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); goto bad; } if (!(tif->tif_flags&TIFF_BIGTIFF)) { uint8* n; TIFFDirEntry* o; n=dirmem; *(uint16*)n=ndir; if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)n); n+=2; o=dir; for (m=0; m<ndir; m++) { *(uint16*)n=o->tdir_tag; if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)n); n+=2; *(uint16*)n=o->tdir_type; if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)n); n+=2; *(uint32*)n=(uint32)o->tdir_count; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong((uint32*)n); n+=4; _TIFFmemcpy(n,&o->tdir_offset,4); n+=4; o++; } *(uint32*)n = (uint32)tif->tif_nextdiroff; } else { uint8* n; TIFFDirEntry* o; n=dirmem; *(uint64*)n=ndir; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8((uint64*)n); n+=8; o=dir; for (m=0; m<ndir; m++) { *(uint16*)n=o->tdir_tag; if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)n); n+=2; *(uint16*)n=o->tdir_type; if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)n); n+=2; *(uint64*)n=o->tdir_count; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8((uint64*)n); n+=8; _TIFFmemcpy(n,&o->tdir_offset,8); n+=8; o++; } *(uint64*)n = tif->tif_nextdiroff; } _TIFFfree(dir); dir=NULL; if (!SeekOK(tif,tif->tif_diroff)) { TIFFErrorExt(tif->tif_clientdata,module,"IO error writing directory"); goto bad; } if (!WriteOK(tif,dirmem,(tmsize_t)dirsize)) { TIFFErrorExt(tif->tif_clientdata,module,"IO error writing directory"); goto bad; } _TIFFfree(dirmem); if (imagedone) { TIFFFreeDirectory(tif); tif->tif_flags&=~TIFF_DIRTYDIRECT; (*tif->tif_cleanup)(tif); /* * Reset directory-related state for subsequent * directories. */ TIFFCreateDirectory(tif); } return(1); bad: if (dir!=NULL) _TIFFfree(dir); if (dirmem!=NULL) _TIFFfree(dirmem); return(0); } static int TIFFWriteDirectoryTagSampleformatPerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, double value) { switch (tif->tif_dir.td_sampleformat) { case SAMPLEFORMAT_IEEEFP: if (tif->tif_dir.td_bitspersample<=32) return(TIFFWriteDirectoryTagFloatPerSample(tif,ndir,dir,tag,(float)value)); else return(TIFFWriteDirectoryTagDoublePerSample(tif,ndir,dir,tag,value)); case SAMPLEFORMAT_INT: if (tif->tif_dir.td_bitspersample<=8) return(TIFFWriteDirectoryTagSbytePerSample(tif,ndir,dir,tag,(int8)value)); else if (tif->tif_dir.td_bitspersample<=16) return(TIFFWriteDirectoryTagSshortPerSample(tif,ndir,dir,tag,(int16)value)); else return(TIFFWriteDirectoryTagSlongPerSample(tif,ndir,dir,tag,(int32)value)); case SAMPLEFORMAT_UINT: if (tif->tif_dir.td_bitspersample<=8) return(TIFFWriteDirectoryTagBytePerSample(tif,ndir,dir,tag,(uint8)value)); else if (tif->tif_dir.td_bitspersample<=16) return(TIFFWriteDirectoryTagShortPerSample(tif,ndir,dir,tag,(uint16)value)); else return(TIFFWriteDirectoryTagLongPerSample(tif,ndir,dir,tag,(uint32)value)); default: return(1); } } static int TIFFWriteDirectoryTagAscii(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, char* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedAscii(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagUndefinedArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint8* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedUndefinedArray(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagByte(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint8 value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedByte(tif,ndir,dir,tag,value)); } static int TIFFWriteDirectoryTagByteArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint8* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedByteArray(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagBytePerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint8 value) { static const char module[] = "TIFFWriteDirectoryTagBytePerSample"; uint8* m; uint8* na; uint16 nb; int o; if (dir==NULL) { (*ndir)++; return(1); } m=_TIFFmalloc(tif->tif_dir.td_samplesperpixel*sizeof(uint8)); if (m==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } for (na=m, nb=0; nb<tif->tif_dir.td_samplesperpixel; na++, nb++) *na=value; o=TIFFWriteDirectoryTagCheckedByteArray(tif,ndir,dir,tag,tif->tif_dir.td_samplesperpixel,m); _TIFFfree(m); return(o); } static int TIFFWriteDirectoryTagSbyte(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int8 value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedSbyte(tif,ndir,dir,tag,value)); } static int TIFFWriteDirectoryTagSbyteArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int8* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedSbyteArray(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagSbytePerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int8 value) { static const char module[] = "TIFFWriteDirectoryTagSbytePerSample"; int8* m; int8* na; uint16 nb; int o; if (dir==NULL) { (*ndir)++; return(1); } m=_TIFFmalloc(tif->tif_dir.td_samplesperpixel*sizeof(int8)); if (m==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } for (na=m, nb=0; nb<tif->tif_dir.td_samplesperpixel; na++, nb++) *na=value; o=TIFFWriteDirectoryTagCheckedSbyteArray(tif,ndir,dir,tag,tif->tif_dir.td_samplesperpixel,m); _TIFFfree(m); return(o); } static int TIFFWriteDirectoryTagShort(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint16 value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedShort(tif,ndir,dir,tag,value)); } static int TIFFWriteDirectoryTagShortArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint16* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedShortArray(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagShortPerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint16 value) { static const char module[] = "TIFFWriteDirectoryTagShortPerSample"; uint16* m; uint16* na; uint16 nb; int o; if (dir==NULL) { (*ndir)++; return(1); } m=_TIFFmalloc(tif->tif_dir.td_samplesperpixel*sizeof(uint16)); if (m==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } for (na=m, nb=0; nb<tif->tif_dir.td_samplesperpixel; na++, nb++) *na=value; o=TIFFWriteDirectoryTagCheckedShortArray(tif,ndir,dir,tag,tif->tif_dir.td_samplesperpixel,m); _TIFFfree(m); return(o); } static int TIFFWriteDirectoryTagSshort(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int16 value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedSshort(tif,ndir,dir,tag,value)); } static int TIFFWriteDirectoryTagSshortArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int16* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedSshortArray(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagSshortPerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int16 value) { static const char module[] = "TIFFWriteDirectoryTagSshortPerSample"; int16* m; int16* na; uint16 nb; int o; if (dir==NULL) { (*ndir)++; return(1); } m=_TIFFmalloc(tif->tif_dir.td_samplesperpixel*sizeof(int16)); if (m==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } for (na=m, nb=0; nb<tif->tif_dir.td_samplesperpixel; na++, nb++) *na=value; o=TIFFWriteDirectoryTagCheckedSshortArray(tif,ndir,dir,tag,tif->tif_dir.td_samplesperpixel,m); _TIFFfree(m); return(o); } static int TIFFWriteDirectoryTagLong(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedLong(tif,ndir,dir,tag,value)); } static int TIFFWriteDirectoryTagLongArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint32* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedLongArray(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagLongPerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 value) { static const char module[] = "TIFFWriteDirectoryTagLongPerSample"; uint32* m; uint32* na; uint16 nb; int o; if (dir==NULL) { (*ndir)++; return(1); } m=_TIFFmalloc(tif->tif_dir.td_samplesperpixel*sizeof(uint32)); if (m==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } for (na=m, nb=0; nb<tif->tif_dir.td_samplesperpixel; na++, nb++) *na=value; o=TIFFWriteDirectoryTagCheckedLongArray(tif,ndir,dir,tag,tif->tif_dir.td_samplesperpixel,m); _TIFFfree(m); return(o); } static int TIFFWriteDirectoryTagSlong(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int32 value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedSlong(tif,ndir,dir,tag,value)); } static int TIFFWriteDirectoryTagSlongArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int32* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedSlongArray(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagSlongPerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int32 value) { static const char module[] = "TIFFWriteDirectoryTagSlongPerSample"; int32* m; int32* na; uint16 nb; int o; if (dir==NULL) { (*ndir)++; return(1); } m=_TIFFmalloc(tif->tif_dir.td_samplesperpixel*sizeof(int32)); if (m==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } for (na=m, nb=0; nb<tif->tif_dir.td_samplesperpixel; na++, nb++) *na=value; o=TIFFWriteDirectoryTagCheckedSlongArray(tif,ndir,dir,tag,tif->tif_dir.td_samplesperpixel,m); _TIFFfree(m); return(o); } static int TIFFWriteDirectoryTagLong8(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint64 value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedLong8(tif,ndir,dir,tag,value)); } static int TIFFWriteDirectoryTagLong8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint64* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedLong8Array(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagSlong8(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int64 value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedSlong8(tif,ndir,dir,tag,value)); } static int TIFFWriteDirectoryTagSlong8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int64* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedSlong8Array(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagRational(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, double value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedRational(tif,ndir,dir,tag,value)); } static int TIFFWriteDirectoryTagRationalArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, float* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedRationalArray(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagSrationalArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, float* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedSrationalArray(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagFloat(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, float value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedFloat(tif,ndir,dir,tag,value)); } static int TIFFWriteDirectoryTagFloatArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, float* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedFloatArray(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagFloatPerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, float value) { static const char module[] = "TIFFWriteDirectoryTagFloatPerSample"; float* m; float* na; uint16 nb; int o; if (dir==NULL) { (*ndir)++; return(1); } m=_TIFFmalloc(tif->tif_dir.td_samplesperpixel*sizeof(float)); if (m==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } for (na=m, nb=0; nb<tif->tif_dir.td_samplesperpixel; na++, nb++) *na=value; o=TIFFWriteDirectoryTagCheckedFloatArray(tif,ndir,dir,tag,tif->tif_dir.td_samplesperpixel,m); _TIFFfree(m); return(o); } static int TIFFWriteDirectoryTagDouble(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, double value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedDouble(tif,ndir,dir,tag,value)); } static int TIFFWriteDirectoryTagDoubleArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, double* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedDoubleArray(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagDoublePerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, double value) { static const char module[] = "TIFFWriteDirectoryTagDoublePerSample"; double* m; double* na; uint16 nb; int o; if (dir==NULL) { (*ndir)++; return(1); } m=_TIFFmalloc(tif->tif_dir.td_samplesperpixel*sizeof(double)); if (m==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } for (na=m, nb=0; nb<tif->tif_dir.td_samplesperpixel; na++, nb++) *na=value; o=TIFFWriteDirectoryTagCheckedDoubleArray(tif,ndir,dir,tag,tif->tif_dir.td_samplesperpixel,m); _TIFFfree(m); return(o); } static int TIFFWriteDirectoryTagIfdArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint32* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedIfdArray(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagIfd8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint64* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedIfd8Array(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagShortLong(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 value) { if (dir==NULL) { (*ndir)++; return(1); } if (value<=0xFFFF) return(TIFFWriteDirectoryTagCheckedShort(tif,ndir,dir,tag,(uint16)value)); else return(TIFFWriteDirectoryTagCheckedLong(tif,ndir,dir,tag,value)); } /************************************************************************/ /* TIFFWriteDirectoryTagLongLong8Array() */ /* */ /* Write out LONG8 array as LONG8 for BigTIFF or LONG for */ /* Classic TIFF with some checking. */ /************************************************************************/ static int TIFFWriteDirectoryTagLongLong8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint64* value) { static const char module[] = "TIFFWriteDirectoryTagLongLong8Array"; uint64* ma; uint32 mb; uint32* p; uint32* q; int o; /* is this just a counting pass? */ if (dir==NULL) { (*ndir)++; return(1); } /* We always write LONG8 for BigTIFF, no checking needed. */ if( tif->tif_flags&TIFF_BIGTIFF ) return TIFFWriteDirectoryTagCheckedLong8Array(tif,ndir,dir, tag,count,value); /* ** For classic tiff we want to verify everything is in range for LONG ** and convert to long format. */ p = _TIFFmalloc(count*sizeof(uint32)); if (p==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } for (q=p, ma=value, mb=0; mb<count; ma++, mb++, q++) { if (*ma>0xFFFFFFFF) { TIFFErrorExt(tif->tif_clientdata,module, "Attempt to write value larger than 0xFFFFFFFF in Classic TIFF file."); _TIFFfree(p); return(0); } *q= (uint32)(*ma); } o=TIFFWriteDirectoryTagCheckedLongArray(tif,ndir,dir,tag,count,p); _TIFFfree(p); return(o); } static int TIFFWriteDirectoryTagShortLongLong8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint64* value) { static const char module[] = "TIFFWriteDirectoryTagShortLongLong8Array"; uint64* ma; uint32 mb; uint8 n; int o; if (dir==NULL) { (*ndir)++; return(1); } n=0; for (ma=value, mb=0; mb<count; ma++, mb++) { if ((n==0)&&(*ma>0xFFFF)) n=1; if ((n==1)&&(*ma>0xFFFFFFFF)) { n=2; break; } } if (n==0) { uint16* p; uint16* q; p=_TIFFmalloc(count*sizeof(uint16)); if (p==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } for (ma=value, mb=0, q=p; mb<count; ma++, mb++, q++) *q=(uint16)(*ma); o=TIFFWriteDirectoryTagCheckedShortArray(tif,ndir,dir,tag,count,p); _TIFFfree(p); } else if (n==1) { uint32* p; uint32* q; p=_TIFFmalloc(count*sizeof(uint32)); if (p==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } for (ma=value, mb=0, q=p; mb<count; ma++, mb++, q++) *q=(uint32)(*ma); o=TIFFWriteDirectoryTagCheckedLongArray(tif,ndir,dir,tag,count,p); _TIFFfree(p); } else { assert(n==2); o=TIFFWriteDirectoryTagCheckedLong8Array(tif,ndir,dir,tag,count,value); } return(o); } static int TIFFWriteDirectoryTagColormap(TIFF* tif, uint32* ndir, TIFFDirEntry* dir) { static const char module[] = "TIFFWriteDirectoryTagColormap"; uint32 m; uint16* n; int o; if (dir==NULL) { (*ndir)++; return(1); } m=(1<<tif->tif_dir.td_bitspersample); n=_TIFFmalloc(3*m*sizeof(uint16)); if (n==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } _TIFFmemcpy(&n[0],tif->tif_dir.td_colormap[0],m*sizeof(uint16)); _TIFFmemcpy(&n[m],tif->tif_dir.td_colormap[1],m*sizeof(uint16)); _TIFFmemcpy(&n[2*m],tif->tif_dir.td_colormap[2],m*sizeof(uint16)); o=TIFFWriteDirectoryTagCheckedShortArray(tif,ndir,dir,TIFFTAG_COLORMAP,3*m,n); _TIFFfree(n); return(o); } static int TIFFWriteDirectoryTagTransferfunction(TIFF* tif, uint32* ndir, TIFFDirEntry* dir) { static const char module[] = "TIFFWriteDirectoryTagTransferfunction"; uint32 m; uint16 n; uint16* o; int p; if (dir==NULL) { (*ndir)++; return(1); } m=(1<<tif->tif_dir.td_bitspersample); n=tif->tif_dir.td_samplesperpixel-tif->tif_dir.td_extrasamples; /* * Check if the table can be written as a single column, * or if it must be written as 3 columns. Note that we * write a 3-column tag if there are 2 samples/pixel and * a single column of data won't suffice--hmm. */ if (n>3) n=3; if (n==3) { if (!_TIFFmemcmp(tif->tif_dir.td_transferfunction[0],tif->tif_dir.td_transferfunction[2],m*sizeof(uint16))) n=2; } if (n==2) { if (!_TIFFmemcmp(tif->tif_dir.td_transferfunction[0],tif->tif_dir.td_transferfunction[1],m*sizeof(uint16))) n=1; } if (n==0) n=1; o=_TIFFmalloc(n*m*sizeof(uint16)); if (o==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } _TIFFmemcpy(&o[0],tif->tif_dir.td_transferfunction[0],m*sizeof(uint16)); if (n>1) _TIFFmemcpy(&o[m],tif->tif_dir.td_transferfunction[1],m*sizeof(uint16)); if (n>2) _TIFFmemcpy(&o[2*m],tif->tif_dir.td_transferfunction[2],m*sizeof(uint16)); p=TIFFWriteDirectoryTagCheckedShortArray(tif,ndir,dir,TIFFTAG_TRANSFERFUNCTION,n*m,o); _TIFFfree(o); return(p); } static int TIFFWriteDirectoryTagSubifd(TIFF* tif, uint32* ndir, TIFFDirEntry* dir) { static const char module[] = "TIFFWriteDirectoryTagSubifd"; uint64 m; int n; if (tif->tif_dir.td_nsubifd==0) return(1); if (dir==NULL) { (*ndir)++; return(1); } m=tif->tif_dataoff; if (!(tif->tif_flags&TIFF_BIGTIFF)) { uint32* o; uint64* pa; uint32* pb; uint16 p; o=_TIFFmalloc(tif->tif_dir.td_nsubifd*sizeof(uint32)); if (o==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } pa=tif->tif_dir.td_subifd; pb=o; for (p=0; p<tif->tif_dir.td_nsubifd; p++) { assert(*pa<=0xFFFFFFFFUL); *pb++=(uint32)(*pa++); } n=TIFFWriteDirectoryTagCheckedIfdArray(tif,ndir,dir,TIFFTAG_SUBIFD,tif->tif_dir.td_nsubifd,o); _TIFFfree(o); } else n=TIFFWriteDirectoryTagCheckedIfd8Array(tif,ndir,dir,TIFFTAG_SUBIFD,tif->tif_dir.td_nsubifd,tif->tif_dir.td_subifd); if (!n) return(0); /* * Total hack: if this directory includes a SubIFD * tag then force the next <n> directories to be * written as ``sub directories'' of this one. This * is used to write things like thumbnails and * image masks that one wants to keep out of the * normal directory linkage access mechanism. */ tif->tif_flags|=TIFF_INSUBIFD; tif->tif_nsubifd=tif->tif_dir.td_nsubifd; if (tif->tif_dir.td_nsubifd==1) tif->tif_subifdoff=0; else tif->tif_subifdoff=m; return(1); } static int TIFFWriteDirectoryTagCheckedAscii(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, char* value) { assert(sizeof(char)==1); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_ASCII,count,count,value)); } static int TIFFWriteDirectoryTagCheckedUndefinedArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint8* value) { assert(sizeof(uint8)==1); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_UNDEFINED,count,count,value)); } static int TIFFWriteDirectoryTagCheckedByte(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint8 value) { assert(sizeof(uint8)==1); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_BYTE,1,1,&value)); } static int TIFFWriteDirectoryTagCheckedByteArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint8* value) { assert(sizeof(uint8)==1); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_BYTE,count,count,value)); } static int TIFFWriteDirectoryTagCheckedSbyte(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int8 value) { assert(sizeof(int8)==1); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_SBYTE,1,1,&value)); } static int TIFFWriteDirectoryTagCheckedSbyteArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int8* value) { assert(sizeof(int8)==1); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_SBYTE,count,count,value)); } static int TIFFWriteDirectoryTagCheckedShort(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint16 value) { uint16 m; assert(sizeof(uint16)==2); m=value; if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort(&m); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_SHORT,1,2,&m)); } static int TIFFWriteDirectoryTagCheckedShortArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint16* value) { assert(count<0x80000000); assert(sizeof(uint16)==2); if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfShort(value,count); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_SHORT,count,count*2,value)); } static int TIFFWriteDirectoryTagCheckedSshort(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int16 value) { int16 m; assert(sizeof(int16)==2); m=value; if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)(&m)); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_SSHORT,1,2,&m)); } static int TIFFWriteDirectoryTagCheckedSshortArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int16* value) { assert(count<0x80000000); assert(sizeof(int16)==2); if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfShort((uint16*)value,count); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_SSHORT,count,count*2,value)); } static int TIFFWriteDirectoryTagCheckedLong(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 value) { uint32 m; assert(sizeof(uint32)==4); m=value; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(&m); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_LONG,1,4,&m)); } static int TIFFWriteDirectoryTagCheckedLongArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint32* value) { assert(count<0x40000000); assert(sizeof(uint32)==4); if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong(value,count); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_LONG,count,count*4,value)); } static int TIFFWriteDirectoryTagCheckedSlong(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int32 value) { int32 m; assert(sizeof(int32)==4); m=value; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong((uint32*)(&m)); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_SLONG,1,4,&m)); } static int TIFFWriteDirectoryTagCheckedSlongArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int32* value) { assert(count<0x40000000); assert(sizeof(int32)==4); if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong((uint32*)value,count); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_SLONG,count,count*4,value)); } static int TIFFWriteDirectoryTagCheckedLong8(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint64 value) { uint64 m; assert(sizeof(uint64)==8); assert(tif->tif_flags&TIFF_BIGTIFF); m=value; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8(&m); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_LONG8,1,8,&m)); } static int TIFFWriteDirectoryTagCheckedLong8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint64* value) { assert(count<0x20000000); assert(sizeof(uint64)==8); assert(tif->tif_flags&TIFF_BIGTIFF); if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong8(value,count); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_LONG8,count,count*8,value)); } static int TIFFWriteDirectoryTagCheckedSlong8(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int64 value) { int64 m; assert(sizeof(int64)==8); assert(tif->tif_flags&TIFF_BIGTIFF); m=value; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8((uint64*)(&m)); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_SLONG8,1,8,&m)); } static int TIFFWriteDirectoryTagCheckedSlong8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int64* value) { assert(count<0x20000000); assert(sizeof(int64)==8); assert(tif->tif_flags&TIFF_BIGTIFF); if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong8((uint64*)value,count); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_SLONG8,count,count*8,value)); } static int TIFFWriteDirectoryTagCheckedRational(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, double value) { uint32 m[2]; assert(value>=0.0); assert(sizeof(uint32)==4); if (value<=0.0) { m[0]=0; m[1]=1; } else if (value==(double)(uint32)value) { m[0]=(uint32)value; m[1]=1; } else if (value<1.0) { m[0]=(uint32)(value*0xFFFFFFFF); m[1]=0xFFFFFFFF; } else { m[0]=0xFFFFFFFF; m[1]=(uint32)(0xFFFFFFFF/value); } if (tif->tif_flags&TIFF_SWAB) { TIFFSwabLong(&m[0]); TIFFSwabLong(&m[1]); } return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_RATIONAL,1,8,&m[0])); } static int TIFFWriteDirectoryTagCheckedRationalArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, float* value) { static const char module[] = "TIFFWriteDirectoryTagCheckedRationalArray"; uint32* m; float* na; uint32* nb; uint32 nc; int o; assert(sizeof(uint32)==4); m=_TIFFmalloc(count*2*sizeof(uint32)); if (m==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } for (na=value, nb=m, nc=0; nc<count; na++, nb+=2, nc++) { if (*na<=0.0) { nb[0]=0; nb[1]=1; } else if (*na==(float)(uint32)(*na)) { nb[0]=(uint32)(*na); nb[1]=1; } else if (*na<1.0) { nb[0]=(uint32)((*na)*0xFFFFFFFF); nb[1]=0xFFFFFFFF; } else { nb[0]=0xFFFFFFFF; nb[1]=(uint32)(0xFFFFFFFF/(*na)); } } if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong(m,count*2); o=TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_RATIONAL,count,count*8,&m[0]); _TIFFfree(m); return(o); } static int TIFFWriteDirectoryTagCheckedSrationalArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, float* value) { static const char module[] = "TIFFWriteDirectoryTagCheckedSrationalArray"; int32* m; float* na; int32* nb; uint32 nc; int o; assert(sizeof(int32)==4); m=_TIFFmalloc(count*2*sizeof(int32)); if (m==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } for (na=value, nb=m, nc=0; nc<count; na++, nb+=2, nc++) { if (*na<0.0) { if (*na==(int32)(*na)) { nb[0]=(int32)(*na); nb[1]=1; } else if (*na>-1.0) { nb[0]=-(int32)((-*na)*0x7FFFFFFF); nb[1]=0x7FFFFFFF; } else { nb[0]=-0x7FFFFFFF; nb[1]=(int32)(0x7FFFFFFF/(-*na)); } } else { if (*na==(int32)(*na)) { nb[0]=(int32)(*na); nb[1]=1; } else if (*na<1.0) { nb[0]=(int32)((*na)*0x7FFFFFFF); nb[1]=0x7FFFFFFF; } else { nb[0]=0x7FFFFFFF; nb[1]=(int32)(0x7FFFFFFF/(*na)); } } } if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong((uint32*)m,count*2); o=TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_SRATIONAL,count,count*8,&m[0]); _TIFFfree(m); return(o); } static int TIFFWriteDirectoryTagCheckedFloat(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, float value) { float m; assert(sizeof(float)==4); m=value; TIFFCvtNativeToIEEEFloat(tif,1,&m); if (tif->tif_flags&TIFF_SWAB) TIFFSwabFloat(&m); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_FLOAT,1,4,&m)); } static int TIFFWriteDirectoryTagCheckedFloatArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, float* value) { assert(count<0x40000000); assert(sizeof(float)==4); TIFFCvtNativeToIEEEFloat(tif,count,&value); if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfFloat(value,count); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_FLOAT,count,count*4,value)); } static int TIFFWriteDirectoryTagCheckedDouble(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, double value) { double m; assert(sizeof(double)==8); m=value; TIFFCvtNativeToIEEEDouble(tif,1,&m); if (tif->tif_flags&TIFF_SWAB) TIFFSwabDouble(&m); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_DOUBLE,1,8,&m)); } static int TIFFWriteDirectoryTagCheckedDoubleArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, double* value) { assert(count<0x20000000); assert(sizeof(double)==8); TIFFCvtNativeToIEEEDouble(tif,count,&value); if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfDouble(value,count); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_DOUBLE,count,count*8,value)); } static int TIFFWriteDirectoryTagCheckedIfdArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint32* value) { assert(count<0x40000000); assert(sizeof(uint32)==4); if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong(value,count); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_IFD,count,count*4,value)); } static int TIFFWriteDirectoryTagCheckedIfd8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint64* value) { assert(count<0x20000000); assert(sizeof(uint64)==8); assert(tif->tif_flags&TIFF_BIGTIFF); if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong8(value,count); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_IFD8,count,count*8,value)); } static int TIFFWriteDirectoryTagData(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint16 datatype, uint32 count, uint32 datalength, void* data) { static const char module[] = "TIFFWriteDirectoryTagData"; uint32 m; m=0; while (m<(*ndir)) { assert(dir[m].tdir_tag!=tag); if (dir[m].tdir_tag>tag) break; m++; } if (m<(*ndir)) { uint32 n; for (n=*ndir; n>m; n--) dir[n]=dir[n-1]; } dir[m].tdir_tag=tag; dir[m].tdir_type=datatype; dir[m].tdir_count=count; dir[m].tdir_offset=0; if (datalength<=((tif->tif_flags&TIFF_BIGTIFF)?0x8U:0x4U)) _TIFFmemcpy(&dir[m].tdir_offset,data,datalength); else { uint64 na,nb; na=tif->tif_dataoff; nb=na+datalength; if (!(tif->tif_flags&TIFF_BIGTIFF)) nb=(uint32)nb; if ((nb<na)||(nb<datalength)) { TIFFErrorExt(tif->tif_clientdata,module,"Maximum TIFF file size exceeded"); return(0); } if (!SeekOK(tif,na)) { TIFFErrorExt(tif->tif_clientdata,module,"IO error writing tag data"); return(0); } assert(datalength<0x80000000UL); if (!WriteOK(tif,data,(tmsize_t)datalength)) { TIFFErrorExt(tif->tif_clientdata,module,"IO error writing tag data"); return(0); } tif->tif_dataoff=nb; if (tif->tif_dataoff&1) tif->tif_dataoff++; if (!(tif->tif_flags&TIFF_BIGTIFF)) { uint32 o; o=(uint32)na; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(&o); _TIFFmemcpy(&dir[m].tdir_offset,&o,4); } else { dir[m].tdir_offset=na; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8(&dir[m].tdir_offset); } } (*ndir)++; return(1); } /* * Link the current directory into the directory chain for the file. */ static int TIFFLinkDirectory(TIFF* tif) { static const char module[] = "TIFFLinkDirectory"; tif->tif_diroff = (TIFFSeekFile(tif,0,SEEK_END)+1) &~ 1; /* * Handle SubIFDs */ if (tif->tif_flags & TIFF_INSUBIFD) { if (!(tif->tif_flags&TIFF_BIGTIFF)) { uint32 m; m = (uint32)tif->tif_diroff; if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong(&m); (void) TIFFSeekFile(tif, tif->tif_subifdoff, SEEK_SET); if (!WriteOK(tif, &m, 4)) { TIFFErrorExt(tif->tif_clientdata, module, "Error writing SubIFD directory link"); return (0); } /* * Advance to the next SubIFD or, if this is * the last one configured, revert back to the * normal directory linkage. */ if (--tif->tif_nsubifd) tif->tif_subifdoff += 4; else tif->tif_flags &= ~TIFF_INSUBIFD; return (1); } else { uint64 m; m = tif->tif_diroff; if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong8(&m); (void) TIFFSeekFile(tif, tif->tif_subifdoff, SEEK_SET); if (!WriteOK(tif, &m, 8)) { TIFFErrorExt(tif->tif_clientdata, module, "Error writing SubIFD directory link"); return (0); } /* * Advance to the next SubIFD or, if this is * the last one configured, revert back to the * normal directory linkage. */ if (--tif->tif_nsubifd) tif->tif_subifdoff += 8; else tif->tif_flags &= ~TIFF_INSUBIFD; return (1); } } if (!(tif->tif_flags&TIFF_BIGTIFF)) { uint32 m; uint32 nextdir; m = (uint32)(tif->tif_diroff); if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong(&m); if (tif->tif_header.classic.tiff_diroff == 0) { /* * First directory, overwrite offset in header. */ tif->tif_header.classic.tiff_diroff = (uint32) tif->tif_diroff; (void) TIFFSeekFile(tif,4, SEEK_SET); if (!WriteOK(tif, &m, 4)) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error writing TIFF header"); return (0); } return (1); } /* * Not the first directory, search to the last and append. */ nextdir = tif->tif_header.classic.tiff_diroff; while(1) { uint16 dircount; uint32 nextnextdir; if (!SeekOK(tif, nextdir) || !ReadOK(tif, &dircount, 2)) { TIFFErrorExt(tif->tif_clientdata, module, "Error fetching directory count"); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); (void) TIFFSeekFile(tif, nextdir+2+dircount*12, SEEK_SET); if (!ReadOK(tif, &nextnextdir, 4)) { TIFFErrorExt(tif->tif_clientdata, module, "Error fetching directory link"); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong(&nextnextdir); if (nextnextdir==0) { (void) TIFFSeekFile(tif, nextdir+2+dircount*12, SEEK_SET); if (!WriteOK(tif, &m, 4)) { TIFFErrorExt(tif->tif_clientdata, module, "Error writing directory link"); return (0); } break; } nextdir=nextnextdir; } } else { uint64 m; uint64 nextdir; m = tif->tif_diroff; if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong8(&m); if (tif->tif_header.big.tiff_diroff == 0) { /* * First directory, overwrite offset in header. */ tif->tif_header.big.tiff_diroff = tif->tif_diroff; (void) TIFFSeekFile(tif,8, SEEK_SET); if (!WriteOK(tif, &m, 8)) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error writing TIFF header"); return (0); } return (1); } /* * Not the first directory, search to the last and append. */ nextdir = tif->tif_header.big.tiff_diroff; while(1) { uint64 dircount64; uint16 dircount; uint64 nextnextdir; if (!SeekOK(tif, nextdir) || !ReadOK(tif, &dircount64, 8)) { TIFFErrorExt(tif->tif_clientdata, module, "Error fetching directory count"); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong8(&dircount64); if (dircount64>0xFFFF) { TIFFErrorExt(tif->tif_clientdata, module, "Sanity check on tag count failed, likely corrupt TIFF"); return (0); } dircount=(uint16)dircount64; (void) TIFFSeekFile(tif, nextdir+8+dircount*20, SEEK_SET); if (!ReadOK(tif, &nextnextdir, 8)) { TIFFErrorExt(tif->tif_clientdata, module, "Error fetching directory link"); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong8(&nextnextdir); if (nextnextdir==0) { (void) TIFFSeekFile(tif, nextdir+8+dircount*20, SEEK_SET); if (!WriteOK(tif, &m, 8)) { TIFFErrorExt(tif->tif_clientdata, module, "Error writing directory link"); return (0); } break; } nextdir=nextnextdir; } } return (1); } /* vim: set ts=8 sts=8 sw=8 noet: */ /* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library. * * Directory Write Support Routines. */ #include "tiffiop.h" #ifdef HAVE_IEEEFP #define TIFFCvtNativeToIEEEFloat(tif, n, fp) #define TIFFCvtNativeToIEEEDouble(tif, n, dp) #else extern void TIFFCvtNativeToIEEEFloat(TIFF* tif, uint32 n, float* fp); extern void TIFFCvtNativeToIEEEDouble(TIFF* tif, uint32 n, double* dp); #endif static int TIFFWriteDirectorySec(TIFF* tif, int isimage, int imagedone, uint64* pdiroff); static int TIFFWriteDirectoryTagSampleformatPerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, double value); static int TIFFWriteDirectoryTagAscii(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, char* value); static int TIFFWriteDirectoryTagUndefinedArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint8* value); static int TIFFWriteDirectoryTagByte(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint8 value); static int TIFFWriteDirectoryTagByteArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint8* value); static int TIFFWriteDirectoryTagBytePerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint8 value); static int TIFFWriteDirectoryTagSbyte(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int8 value); static int TIFFWriteDirectoryTagSbyteArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int8* value); static int TIFFWriteDirectoryTagSbytePerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int8 value); static int TIFFWriteDirectoryTagShort(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint16 value); static int TIFFWriteDirectoryTagShortArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint16* value); static int TIFFWriteDirectoryTagShortPerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint16 value); static int TIFFWriteDirectoryTagSshort(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int16 value); static int TIFFWriteDirectoryTagSshortArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int16* value); static int TIFFWriteDirectoryTagSshortPerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int16 value); static int TIFFWriteDirectoryTagLong(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 value); static int TIFFWriteDirectoryTagLongArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint32* value); static int TIFFWriteDirectoryTagLongPerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 value); static int TIFFWriteDirectoryTagSlong(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int32 value); static int TIFFWriteDirectoryTagSlongArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int32* value); static int TIFFWriteDirectoryTagSlongPerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int32 value); static int TIFFWriteDirectoryTagLong8(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint64 value); static int TIFFWriteDirectoryTagLong8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint64* value); static int TIFFWriteDirectoryTagSlong8(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int64 value); static int TIFFWriteDirectoryTagSlong8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int64* value); static int TIFFWriteDirectoryTagRational(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, double value); static int TIFFWriteDirectoryTagRationalArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, float* value); static int TIFFWriteDirectoryTagSrationalArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, float* value); static int TIFFWriteDirectoryTagFloat(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, float value); static int TIFFWriteDirectoryTagFloatArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, float* value); static int TIFFWriteDirectoryTagFloatPerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, float value); static int TIFFWriteDirectoryTagDouble(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, double value); static int TIFFWriteDirectoryTagDoubleArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, double* value); static int TIFFWriteDirectoryTagDoublePerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, double value); static int TIFFWriteDirectoryTagIfdArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint32* value); static int TIFFWriteDirectoryTagIfd8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint64* value); static int TIFFWriteDirectoryTagShortLong(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 value); static int TIFFWriteDirectoryTagLongLong8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint64* value); static int TIFFWriteDirectoryTagShortLongLong8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint64* value); static int TIFFWriteDirectoryTagColormap(TIFF* tif, uint32* ndir, TIFFDirEntry* dir); static int TIFFWriteDirectoryTagTransferfunction(TIFF* tif, uint32* ndir, TIFFDirEntry* dir); static int TIFFWriteDirectoryTagSubifd(TIFF* tif, uint32* ndir, TIFFDirEntry* dir); static int TIFFWriteDirectoryTagCheckedAscii(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, char* value); static int TIFFWriteDirectoryTagCheckedUndefinedArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint8* value); static int TIFFWriteDirectoryTagCheckedByte(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint8 value); static int TIFFWriteDirectoryTagCheckedByteArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint8* value); static int TIFFWriteDirectoryTagCheckedSbyte(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int8 value); static int TIFFWriteDirectoryTagCheckedSbyteArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int8* value); static int TIFFWriteDirectoryTagCheckedShort(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint16 value); static int TIFFWriteDirectoryTagCheckedShortArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint16* value); static int TIFFWriteDirectoryTagCheckedSshort(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int16 value); static int TIFFWriteDirectoryTagCheckedSshortArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int16* value); static int TIFFWriteDirectoryTagCheckedLong(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 value); static int TIFFWriteDirectoryTagCheckedLongArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint32* value); static int TIFFWriteDirectoryTagCheckedSlong(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int32 value); static int TIFFWriteDirectoryTagCheckedSlongArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int32* value); static int TIFFWriteDirectoryTagCheckedLong8(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint64 value); static int TIFFWriteDirectoryTagCheckedLong8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint64* value); static int TIFFWriteDirectoryTagCheckedSlong8(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int64 value); static int TIFFWriteDirectoryTagCheckedSlong8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int64* value); static int TIFFWriteDirectoryTagCheckedRational(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, double value); static int TIFFWriteDirectoryTagCheckedRationalArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, float* value); static int TIFFWriteDirectoryTagCheckedSrationalArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, float* value); static int TIFFWriteDirectoryTagCheckedFloat(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, float value); static int TIFFWriteDirectoryTagCheckedFloatArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, float* value); static int TIFFWriteDirectoryTagCheckedDouble(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, double value); static int TIFFWriteDirectoryTagCheckedDoubleArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, double* value); static int TIFFWriteDirectoryTagCheckedIfdArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint32* value); static int TIFFWriteDirectoryTagCheckedIfd8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint64* value); static int TIFFWriteDirectoryTagData(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint16 datatype, uint32 count, uint32 datalength, void* data); static int TIFFLinkDirectory(TIFF*); /* * Write the contents of the current directory * to the specified file. This routine doesn't * handle overwriting a directory with auxiliary * storage that's been changed. */ int TIFFWriteDirectory(TIFF* tif) { return TIFFWriteDirectorySec(tif,TRUE,TRUE,NULL); } /* * Similar to TIFFWriteDirectory(), writes the directory out * but leaves all data structures in memory so that it can be * written again. This will make a partially written TIFF file * readable before it is successfully completed/closed. */ int TIFFCheckpointDirectory(TIFF* tif) { int rc; /* Setup the strips arrays, if they haven't already been. */ if (tif->tif_dir.td_stripoffset == NULL) (void) TIFFSetupStrips(tif); rc = TIFFWriteDirectorySec(tif,TRUE,FALSE,NULL); (void) TIFFSetWriteOffset(tif, TIFFSeekFile(tif, 0, SEEK_END)); return rc; } int TIFFWriteCustomDirectory(TIFF* tif, uint64* pdiroff) { return TIFFWriteDirectorySec(tif,FALSE,FALSE,pdiroff); } /* * Similar to TIFFWriteDirectory(), but if the directory has already * been written once, it is relocated to the end of the file, in case it * has changed in size. Note that this will result in the loss of the * previously used directory space. */ int TIFFRewriteDirectory( TIFF *tif ) { static const char module[] = "TIFFRewriteDirectory"; /* We don't need to do anything special if it hasn't been written. */ if( tif->tif_diroff == 0 ) return TIFFWriteDirectory( tif ); /* * Find and zero the pointer to this directory, so that TIFFLinkDirectory * will cause it to be added after this directories current pre-link. */ if (!(tif->tif_flags&TIFF_BIGTIFF)) { if (tif->tif_header.classic.tiff_diroff == tif->tif_diroff) { tif->tif_header.classic.tiff_diroff = 0; tif->tif_diroff = 0; TIFFSeekFile(tif,4,SEEK_SET); if (!WriteOK(tif, &(tif->tif_header.classic.tiff_diroff),4)) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error updating TIFF header"); return (0); } } else { uint32 nextdir; nextdir = tif->tif_header.classic.tiff_diroff; while(1) { uint16 dircount; uint32 nextnextdir; if (!SeekOK(tif, nextdir) || !ReadOK(tif, &dircount, 2)) { TIFFErrorExt(tif->tif_clientdata, module, "Error fetching directory count"); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); (void) TIFFSeekFile(tif, nextdir+2+dircount*12, SEEK_SET); if (!ReadOK(tif, &nextnextdir, 4)) { TIFFErrorExt(tif->tif_clientdata, module, "Error fetching directory link"); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong(&nextnextdir); if (nextnextdir==tif->tif_diroff) { uint32 m; m=0; (void) TIFFSeekFile(tif, nextdir+2+dircount*12, SEEK_SET); if (!WriteOK(tif, &m, 4)) { TIFFErrorExt(tif->tif_clientdata, module, "Error writing directory link"); return (0); } tif->tif_diroff=0; break; } nextdir=nextnextdir; } } } else { if (tif->tif_header.big.tiff_diroff == tif->tif_diroff) { tif->tif_header.big.tiff_diroff = 0; tif->tif_diroff = 0; TIFFSeekFile(tif,8,SEEK_SET); if (!WriteOK(tif, &(tif->tif_header.big.tiff_diroff),8)) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error updating TIFF header"); return (0); } } else { uint64 nextdir; nextdir = tif->tif_header.big.tiff_diroff; while(1) { uint64 dircount64; uint16 dircount; uint64 nextnextdir; if (!SeekOK(tif, nextdir) || !ReadOK(tif, &dircount64, 8)) { TIFFErrorExt(tif->tif_clientdata, module, "Error fetching directory count"); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong8(&dircount64); if (dircount64>0xFFFF) { TIFFErrorExt(tif->tif_clientdata, module, "Sanity check on tag count failed, likely corrupt TIFF"); return (0); } dircount=(uint16)dircount64; (void) TIFFSeekFile(tif, nextdir+8+dircount*20, SEEK_SET); if (!ReadOK(tif, &nextnextdir, 8)) { TIFFErrorExt(tif->tif_clientdata, module, "Error fetching directory link"); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong8(&nextnextdir); if (nextnextdir==tif->tif_diroff) { uint64 m; m=0; (void) TIFFSeekFile(tif, nextdir+8+dircount*20, SEEK_SET); if (!WriteOK(tif, &m, 8)) { TIFFErrorExt(tif->tif_clientdata, module, "Error writing directory link"); return (0); } tif->tif_diroff=0; break; } nextdir=nextnextdir; } } } /* * Now use TIFFWriteDirectory() normally. */ return TIFFWriteDirectory( tif ); } static int TIFFWriteDirectorySec(TIFF* tif, int isimage, int imagedone, uint64* pdiroff) { static const char module[] = "TIFFWriteDirectorySec"; uint32 ndir; TIFFDirEntry* dir; uint32 dirsize; void* dirmem; uint32 m; if (tif->tif_mode == O_RDONLY) return (1); /* * Clear write state so that subsequent images with * different characteristics get the right buffers * setup for them. */ if (imagedone) { if (tif->tif_flags & TIFF_POSTENCODE) { tif->tif_flags &= ~TIFF_POSTENCODE; if (!(*tif->tif_postencode)(tif)) { TIFFErrorExt(tif->tif_clientdata,module, "Error post-encoding before directory write"); return (0); } } (*tif->tif_close)(tif); /* shutdown encoder */ /* * Flush any data that might have been written * by the compression close+cleanup routines. */ if (tif->tif_rawcc > 0 && (tif->tif_flags & TIFF_BEENWRITING) != 0 && !TIFFFlushData1(tif)) { TIFFErrorExt(tif->tif_clientdata, module, "Error flushing data before directory write"); return (0); } if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata) { _TIFFfree(tif->tif_rawdata); tif->tif_rawdata = NULL; tif->tif_rawcc = 0; tif->tif_rawdatasize = 0; } tif->tif_flags &= ~(TIFF_BEENWRITING|TIFF_BUFFERSETUP); } dir=NULL; dirmem=NULL; dirsize=0; while (1) { ndir=0; if (isimage) { if (TIFFFieldSet(tif,FIELD_IMAGEDIMENSIONS)) { if (!TIFFWriteDirectoryTagShortLong(tif,&ndir,dir,TIFFTAG_IMAGEWIDTH,tif->tif_dir.td_imagewidth)) goto bad; if (!TIFFWriteDirectoryTagShortLong(tif,&ndir,dir,TIFFTAG_IMAGELENGTH,tif->tif_dir.td_imagelength)) goto bad; } if (TIFFFieldSet(tif,FIELD_TILEDIMENSIONS)) { if (!TIFFWriteDirectoryTagShortLong(tif,&ndir,dir,TIFFTAG_TILEWIDTH,tif->tif_dir.td_tilewidth)) goto bad; if (!TIFFWriteDirectoryTagShortLong(tif,&ndir,dir,TIFFTAG_TILELENGTH,tif->tif_dir.td_tilelength)) goto bad; } if (TIFFFieldSet(tif,FIELD_RESOLUTION)) { if (!TIFFWriteDirectoryTagRational(tif,&ndir,dir,TIFFTAG_XRESOLUTION,tif->tif_dir.td_xresolution)) goto bad; if (!TIFFWriteDirectoryTagRational(tif,&ndir,dir,TIFFTAG_YRESOLUTION,tif->tif_dir.td_yresolution)) goto bad; } if (TIFFFieldSet(tif,FIELD_POSITION)) { if (!TIFFWriteDirectoryTagRational(tif,&ndir,dir,TIFFTAG_XPOSITION,tif->tif_dir.td_xposition)) goto bad; if (!TIFFWriteDirectoryTagRational(tif,&ndir,dir,TIFFTAG_YPOSITION,tif->tif_dir.td_yposition)) goto bad; } if (TIFFFieldSet(tif,FIELD_SUBFILETYPE)) { if (!TIFFWriteDirectoryTagLong(tif,&ndir,dir,TIFFTAG_SUBFILETYPE,tif->tif_dir.td_subfiletype)) goto bad; } if (TIFFFieldSet(tif,FIELD_BITSPERSAMPLE)) { if (!TIFFWriteDirectoryTagShortPerSample(tif,&ndir,dir,TIFFTAG_BITSPERSAMPLE,tif->tif_dir.td_bitspersample)) goto bad; } if (TIFFFieldSet(tif,FIELD_COMPRESSION)) { if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_COMPRESSION,tif->tif_dir.td_compression)) goto bad; } if (TIFFFieldSet(tif,FIELD_PHOTOMETRIC)) { if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_PHOTOMETRIC,tif->tif_dir.td_photometric)) goto bad; } if (TIFFFieldSet(tif,FIELD_THRESHHOLDING)) { if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_THRESHHOLDING,tif->tif_dir.td_threshholding)) goto bad; } if (TIFFFieldSet(tif,FIELD_FILLORDER)) { if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_FILLORDER,tif->tif_dir.td_fillorder)) goto bad; } if (TIFFFieldSet(tif,FIELD_ORIENTATION)) { if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_ORIENTATION,tif->tif_dir.td_orientation)) goto bad; } if (TIFFFieldSet(tif,FIELD_SAMPLESPERPIXEL)) { if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_SAMPLESPERPIXEL,tif->tif_dir.td_samplesperpixel)) goto bad; } if (TIFFFieldSet(tif,FIELD_ROWSPERSTRIP)) { if (!TIFFWriteDirectoryTagShortLong(tif,&ndir,dir,TIFFTAG_ROWSPERSTRIP,tif->tif_dir.td_rowsperstrip)) goto bad; } if (TIFFFieldSet(tif,FIELD_MINSAMPLEVALUE)) { if (!TIFFWriteDirectoryTagShortPerSample(tif,&ndir,dir,TIFFTAG_MINSAMPLEVALUE,tif->tif_dir.td_minsamplevalue)) goto bad; } if (TIFFFieldSet(tif,FIELD_MAXSAMPLEVALUE)) { if (!TIFFWriteDirectoryTagShortPerSample(tif,&ndir,dir,TIFFTAG_MAXSAMPLEVALUE,tif->tif_dir.td_maxsamplevalue)) goto bad; } if (TIFFFieldSet(tif,FIELD_PLANARCONFIG)) { if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_PLANARCONFIG,tif->tif_dir.td_planarconfig)) goto bad; } if (TIFFFieldSet(tif,FIELD_RESOLUTIONUNIT)) { if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_RESOLUTIONUNIT,tif->tif_dir.td_resolutionunit)) goto bad; } if (TIFFFieldSet(tif,FIELD_PAGENUMBER)) { if (!TIFFWriteDirectoryTagShortArray(tif,&ndir,dir,TIFFTAG_PAGENUMBER,2,&tif->tif_dir.td_pagenumber[0])) goto bad; } if (TIFFFieldSet(tif,FIELD_STRIPBYTECOUNTS)) { if (!isTiled(tif)) { if (!TIFFWriteDirectoryTagLongLong8Array(tif,&ndir,dir,TIFFTAG_STRIPBYTECOUNTS,tif->tif_dir.td_nstrips,tif->tif_dir.td_stripbytecount)) goto bad; } else { if (!TIFFWriteDirectoryTagLongLong8Array(tif,&ndir,dir,TIFFTAG_TILEBYTECOUNTS,tif->tif_dir.td_nstrips,tif->tif_dir.td_stripbytecount)) goto bad; } } if (TIFFFieldSet(tif,FIELD_STRIPOFFSETS)) { if (!isTiled(tif)) { if (!TIFFWriteDirectoryTagLongLong8Array(tif,&ndir,dir,TIFFTAG_STRIPOFFSETS,tif->tif_dir.td_nstrips,tif->tif_dir.td_stripoffset)) goto bad; } else { if (!TIFFWriteDirectoryTagLongLong8Array(tif,&ndir,dir,TIFFTAG_TILEOFFSETS,tif->tif_dir.td_nstrips,tif->tif_dir.td_stripoffset)) goto bad; } } if (TIFFFieldSet(tif,FIELD_COLORMAP)) { if (!TIFFWriteDirectoryTagColormap(tif,&ndir,dir)) goto bad; } if (TIFFFieldSet(tif,FIELD_EXTRASAMPLES)) { if (tif->tif_dir.td_extrasamples) { uint16 na; uint16* nb; TIFFGetFieldDefaulted(tif,TIFFTAG_EXTRASAMPLES,&na,&nb); if (!TIFFWriteDirectoryTagShortArray(tif,&ndir,dir,TIFFTAG_EXTRASAMPLES,na,nb)) goto bad; } } if (TIFFFieldSet(tif,FIELD_SAMPLEFORMAT)) { if (!TIFFWriteDirectoryTagShortPerSample(tif,&ndir,dir,TIFFTAG_SAMPLEFORMAT,tif->tif_dir.td_sampleformat)) goto bad; } if (TIFFFieldSet(tif,FIELD_SMINSAMPLEVALUE)) { if (!TIFFWriteDirectoryTagSampleformatPerSample(tif,&ndir,dir,TIFFTAG_SMINSAMPLEVALUE,tif->tif_dir.td_sminsamplevalue)) goto bad; } if (TIFFFieldSet(tif,FIELD_SMAXSAMPLEVALUE)) { if (!TIFFWriteDirectoryTagSampleformatPerSample(tif,&ndir,dir,TIFFTAG_SMAXSAMPLEVALUE,tif->tif_dir.td_smaxsamplevalue)) goto bad; } if (TIFFFieldSet(tif,FIELD_IMAGEDEPTH)) { if (!TIFFWriteDirectoryTagLong(tif,&ndir,dir,TIFFTAG_IMAGEDEPTH,tif->tif_dir.td_imagedepth)) goto bad; } if (TIFFFieldSet(tif,FIELD_TILEDEPTH)) { if (!TIFFWriteDirectoryTagLong(tif,&ndir,dir,TIFFTAG_TILEDEPTH,tif->tif_dir.td_tiledepth)) goto bad; } if (TIFFFieldSet(tif,FIELD_HALFTONEHINTS)) { if (!TIFFWriteDirectoryTagShortArray(tif,&ndir,dir,TIFFTAG_HALFTONEHINTS,2,&tif->tif_dir.td_halftonehints[0])) goto bad; } if (TIFFFieldSet(tif,FIELD_YCBCRSUBSAMPLING)) { if (!TIFFWriteDirectoryTagShortArray(tif,&ndir,dir,TIFFTAG_YCBCRSUBSAMPLING,2,&tif->tif_dir.td_ycbcrsubsampling[0])) goto bad; } if (TIFFFieldSet(tif,FIELD_YCBCRPOSITIONING)) { if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,TIFFTAG_YCBCRPOSITIONING,tif->tif_dir.td_ycbcrpositioning)) goto bad; } if (TIFFFieldSet(tif,FIELD_TRANSFERFUNCTION)) { if (!TIFFWriteDirectoryTagTransferfunction(tif,&ndir,dir)) goto bad; } if (TIFFFieldSet(tif,FIELD_INKNAMES)) { if (!TIFFWriteDirectoryTagAscii(tif,&ndir,dir,TIFFTAG_INKNAMES,tif->tif_dir.td_inknameslen,tif->tif_dir.td_inknames)) goto bad; } if (TIFFFieldSet(tif,FIELD_SUBIFD)) { if (!TIFFWriteDirectoryTagSubifd(tif,&ndir,dir)) goto bad; } { uint32 n; for (n=0; n<tif->tif_nfields; n++) { const TIFFField* o; o = tif->tif_fields[n]; if ((o->field_bit>=FIELD_CODEC)&&(TIFFFieldSet(tif,o->field_bit))) { switch (o->get_field_type) { case TIFF_SETGET_ASCII: { uint32 pa; char* pb; assert(o->field_type==TIFF_ASCII); assert(o->field_readcount==TIFF_VARIABLE); assert(o->field_passcount==0); TIFFGetField(tif,o->field_tag,&pb); pa=(uint32)(strlen(pb)); if (!TIFFWriteDirectoryTagAscii(tif,&ndir,dir,o->field_tag,pa,pb)) goto bad; } break; case TIFF_SETGET_UINT16: { uint16 p; assert(o->field_type==TIFF_SHORT); assert(o->field_readcount==1); assert(o->field_passcount==0); TIFFGetField(tif,o->field_tag,&p); if (!TIFFWriteDirectoryTagShort(tif,&ndir,dir,o->field_tag,p)) goto bad; } break; case TIFF_SETGET_UINT32: { uint32 p; assert(o->field_type==TIFF_LONG); assert(o->field_readcount==1); assert(o->field_passcount==0); TIFFGetField(tif,o->field_tag,&p); if (!TIFFWriteDirectoryTagLong(tif,&ndir,dir,o->field_tag,p)) goto bad; } break; case TIFF_SETGET_C32_UINT8: { uint32 pa; void* pb; assert(o->field_type==TIFF_UNDEFINED); assert(o->field_readcount==TIFF_VARIABLE2); assert(o->field_passcount==1); TIFFGetField(tif,o->field_tag,&pa,&pb); if (!TIFFWriteDirectoryTagUndefinedArray(tif,&ndir,dir,o->field_tag,pa,pb)) goto bad; } break; default: assert(0); /* we should never get here */ break; } } } } } for (m=0; m<(uint32)(tif->tif_dir.td_customValueCount); m++) { switch (tif->tif_dir.td_customValues[m].info->field_type) { case TIFF_ASCII: if (!TIFFWriteDirectoryTagAscii(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_UNDEFINED: if (!TIFFWriteDirectoryTagUndefinedArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_BYTE: if (!TIFFWriteDirectoryTagByteArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_SBYTE: if (!TIFFWriteDirectoryTagSbyteArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_SHORT: if (!TIFFWriteDirectoryTagShortArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_SSHORT: if (!TIFFWriteDirectoryTagSshortArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_LONG: if (!TIFFWriteDirectoryTagLongArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_SLONG: if (!TIFFWriteDirectoryTagSlongArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_LONG8: if (!TIFFWriteDirectoryTagLong8Array(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_SLONG8: if (!TIFFWriteDirectoryTagSlong8Array(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_RATIONAL: if (!TIFFWriteDirectoryTagRationalArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_SRATIONAL: if (!TIFFWriteDirectoryTagSrationalArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_FLOAT: if (!TIFFWriteDirectoryTagFloatArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_DOUBLE: if (!TIFFWriteDirectoryTagDoubleArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_IFD: if (!TIFFWriteDirectoryTagIfdArray(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; case TIFF_IFD8: if (!TIFFWriteDirectoryTagIfd8Array(tif,&ndir,dir,tif->tif_dir.td_customValues[m].info->field_tag,tif->tif_dir.td_customValues[m].count,tif->tif_dir.td_customValues[m].value)) goto bad; break; default: assert(0); /* we should never get here */ break; } } if (dir!=NULL) break; dir=_TIFFmalloc(ndir*sizeof(TIFFDirEntry)); if (dir==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); goto bad; } if (isimage) { if ((tif->tif_diroff==0)&&(!TIFFLinkDirectory(tif))) goto bad; } else tif->tif_diroff=(TIFFSeekFile(tif,0,SEEK_END)+1)&(~1); if (pdiroff!=NULL) *pdiroff=tif->tif_diroff; if (!(tif->tif_flags&TIFF_BIGTIFF)) dirsize=2+ndir*12+4; else dirsize=8+ndir*20+8; tif->tif_dataoff=tif->tif_diroff+dirsize; if (!(tif->tif_flags&TIFF_BIGTIFF)) tif->tif_dataoff=(uint32)tif->tif_dataoff; if ((tif->tif_dataoff<tif->tif_diroff)||(tif->tif_dataoff<(uint64)dirsize)) { TIFFErrorExt(tif->tif_clientdata,module,"Maximum TIFF file size exceeded"); goto bad; } if (tif->tif_dataoff&1) tif->tif_dataoff++; if (isimage) tif->tif_curdir++; } if (isimage) { if (TIFFFieldSet(tif,FIELD_SUBIFD)&&(tif->tif_subifdoff==0)) { uint32 na; TIFFDirEntry* nb; for (na=0, nb=dir; ; na++, nb++) { assert(na<ndir); if (nb->tdir_tag==TIFFTAG_SUBIFD) break; } if (!(tif->tif_flags&TIFF_BIGTIFF)) tif->tif_subifdoff=tif->tif_diroff+2+na*12+8; else tif->tif_subifdoff=tif->tif_diroff+8+na*20+12; } } dirmem=_TIFFmalloc(dirsize); if (dirmem==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); goto bad; } if (!(tif->tif_flags&TIFF_BIGTIFF)) { uint8* n; TIFFDirEntry* o; n=dirmem; *(uint16*)n=ndir; if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)n); n+=2; o=dir; for (m=0; m<ndir; m++) { *(uint16*)n=o->tdir_tag; if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)n); n+=2; *(uint16*)n=o->tdir_type; if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)n); n+=2; *(uint32*)n=(uint32)o->tdir_count; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong((uint32*)n); n+=4; _TIFFmemcpy(n,&o->tdir_offset,4); n+=4; o++; } *(uint32*)n = (uint32)tif->tif_nextdiroff; } else { uint8* n; TIFFDirEntry* o; n=dirmem; *(uint64*)n=ndir; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8((uint64*)n); n+=8; o=dir; for (m=0; m<ndir; m++) { *(uint16*)n=o->tdir_tag; if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)n); n+=2; *(uint16*)n=o->tdir_type; if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)n); n+=2; *(uint64*)n=o->tdir_count; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8((uint64*)n); n+=8; _TIFFmemcpy(n,&o->tdir_offset,8); n+=8; o++; } *(uint64*)n = tif->tif_nextdiroff; } _TIFFfree(dir); dir=NULL; if (!SeekOK(tif,tif->tif_diroff)) { TIFFErrorExt(tif->tif_clientdata,module,"IO error writing directory"); goto bad; } if (!WriteOK(tif,dirmem,(tmsize_t)dirsize)) { TIFFErrorExt(tif->tif_clientdata,module,"IO error writing directory"); goto bad; } _TIFFfree(dirmem); if (imagedone) { TIFFFreeDirectory(tif); tif->tif_flags&=~TIFF_DIRTYDIRECT; (*tif->tif_cleanup)(tif); /* * Reset directory-related state for subsequent * directories. */ TIFFCreateDirectory(tif); } return(1); bad: if (dir!=NULL) _TIFFfree(dir); if (dirmem!=NULL) _TIFFfree(dirmem); return(0); } static int TIFFWriteDirectoryTagSampleformatPerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, double value) { switch (tif->tif_dir.td_sampleformat) { case SAMPLEFORMAT_IEEEFP: if (tif->tif_dir.td_bitspersample<=32) return(TIFFWriteDirectoryTagFloatPerSample(tif,ndir,dir,tag,(float)value)); else return(TIFFWriteDirectoryTagDoublePerSample(tif,ndir,dir,tag,value)); case SAMPLEFORMAT_INT: if (tif->tif_dir.td_bitspersample<=8) return(TIFFWriteDirectoryTagSbytePerSample(tif,ndir,dir,tag,(int8)value)); else if (tif->tif_dir.td_bitspersample<=16) return(TIFFWriteDirectoryTagSshortPerSample(tif,ndir,dir,tag,(int16)value)); else return(TIFFWriteDirectoryTagSlongPerSample(tif,ndir,dir,tag,(int32)value)); case SAMPLEFORMAT_UINT: if (tif->tif_dir.td_bitspersample<=8) return(TIFFWriteDirectoryTagBytePerSample(tif,ndir,dir,tag,(uint8)value)); else if (tif->tif_dir.td_bitspersample<=16) return(TIFFWriteDirectoryTagShortPerSample(tif,ndir,dir,tag,(uint16)value)); else return(TIFFWriteDirectoryTagLongPerSample(tif,ndir,dir,tag,(uint32)value)); default: return(1); } } static int TIFFWriteDirectoryTagAscii(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, char* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedAscii(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagUndefinedArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint8* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedUndefinedArray(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagByte(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint8 value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedByte(tif,ndir,dir,tag,value)); } static int TIFFWriteDirectoryTagByteArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint8* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedByteArray(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagBytePerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint8 value) { static const char module[] = "TIFFWriteDirectoryTagBytePerSample"; uint8* m; uint8* na; uint16 nb; int o; if (dir==NULL) { (*ndir)++; return(1); } m=_TIFFmalloc(tif->tif_dir.td_samplesperpixel*sizeof(uint8)); if (m==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } for (na=m, nb=0; nb<tif->tif_dir.td_samplesperpixel; na++, nb++) *na=value; o=TIFFWriteDirectoryTagCheckedByteArray(tif,ndir,dir,tag,tif->tif_dir.td_samplesperpixel,m); _TIFFfree(m); return(o); } static int TIFFWriteDirectoryTagSbyte(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int8 value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedSbyte(tif,ndir,dir,tag,value)); } static int TIFFWriteDirectoryTagSbyteArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int8* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedSbyteArray(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagSbytePerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int8 value) { static const char module[] = "TIFFWriteDirectoryTagSbytePerSample"; int8* m; int8* na; uint16 nb; int o; if (dir==NULL) { (*ndir)++; return(1); } m=_TIFFmalloc(tif->tif_dir.td_samplesperpixel*sizeof(int8)); if (m==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } for (na=m, nb=0; nb<tif->tif_dir.td_samplesperpixel; na++, nb++) *na=value; o=TIFFWriteDirectoryTagCheckedSbyteArray(tif,ndir,dir,tag,tif->tif_dir.td_samplesperpixel,m); _TIFFfree(m); return(o); } static int TIFFWriteDirectoryTagShort(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint16 value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedShort(tif,ndir,dir,tag,value)); } static int TIFFWriteDirectoryTagShortArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint16* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedShortArray(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagShortPerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint16 value) { static const char module[] = "TIFFWriteDirectoryTagShortPerSample"; uint16* m; uint16* na; uint16 nb; int o; if (dir==NULL) { (*ndir)++; return(1); } m=_TIFFmalloc(tif->tif_dir.td_samplesperpixel*sizeof(uint16)); if (m==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } for (na=m, nb=0; nb<tif->tif_dir.td_samplesperpixel; na++, nb++) *na=value; o=TIFFWriteDirectoryTagCheckedShortArray(tif,ndir,dir,tag,tif->tif_dir.td_samplesperpixel,m); _TIFFfree(m); return(o); } static int TIFFWriteDirectoryTagSshort(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int16 value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedSshort(tif,ndir,dir,tag,value)); } static int TIFFWriteDirectoryTagSshortArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int16* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedSshortArray(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagSshortPerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int16 value) { static const char module[] = "TIFFWriteDirectoryTagSshortPerSample"; int16* m; int16* na; uint16 nb; int o; if (dir==NULL) { (*ndir)++; return(1); } m=_TIFFmalloc(tif->tif_dir.td_samplesperpixel*sizeof(int16)); if (m==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } for (na=m, nb=0; nb<tif->tif_dir.td_samplesperpixel; na++, nb++) *na=value; o=TIFFWriteDirectoryTagCheckedSshortArray(tif,ndir,dir,tag,tif->tif_dir.td_samplesperpixel,m); _TIFFfree(m); return(o); } static int TIFFWriteDirectoryTagLong(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedLong(tif,ndir,dir,tag,value)); } static int TIFFWriteDirectoryTagLongArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint32* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedLongArray(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagLongPerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 value) { static const char module[] = "TIFFWriteDirectoryTagLongPerSample"; uint32* m; uint32* na; uint16 nb; int o; if (dir==NULL) { (*ndir)++; return(1); } m=_TIFFmalloc(tif->tif_dir.td_samplesperpixel*sizeof(uint32)); if (m==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } for (na=m, nb=0; nb<tif->tif_dir.td_samplesperpixel; na++, nb++) *na=value; o=TIFFWriteDirectoryTagCheckedLongArray(tif,ndir,dir,tag,tif->tif_dir.td_samplesperpixel,m); _TIFFfree(m); return(o); } static int TIFFWriteDirectoryTagSlong(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int32 value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedSlong(tif,ndir,dir,tag,value)); } static int TIFFWriteDirectoryTagSlongArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int32* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedSlongArray(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagSlongPerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int32 value) { static const char module[] = "TIFFWriteDirectoryTagSlongPerSample"; int32* m; int32* na; uint16 nb; int o; if (dir==NULL) { (*ndir)++; return(1); } m=_TIFFmalloc(tif->tif_dir.td_samplesperpixel*sizeof(int32)); if (m==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } for (na=m, nb=0; nb<tif->tif_dir.td_samplesperpixel; na++, nb++) *na=value; o=TIFFWriteDirectoryTagCheckedSlongArray(tif,ndir,dir,tag,tif->tif_dir.td_samplesperpixel,m); _TIFFfree(m); return(o); } static int TIFFWriteDirectoryTagLong8(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint64 value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedLong8(tif,ndir,dir,tag,value)); } static int TIFFWriteDirectoryTagLong8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint64* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedLong8Array(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagSlong8(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int64 value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedSlong8(tif,ndir,dir,tag,value)); } static int TIFFWriteDirectoryTagSlong8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int64* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedSlong8Array(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagRational(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, double value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedRational(tif,ndir,dir,tag,value)); } static int TIFFWriteDirectoryTagRationalArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, float* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedRationalArray(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagSrationalArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, float* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedSrationalArray(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagFloat(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, float value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedFloat(tif,ndir,dir,tag,value)); } static int TIFFWriteDirectoryTagFloatArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, float* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedFloatArray(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagFloatPerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, float value) { static const char module[] = "TIFFWriteDirectoryTagFloatPerSample"; float* m; float* na; uint16 nb; int o; if (dir==NULL) { (*ndir)++; return(1); } m=_TIFFmalloc(tif->tif_dir.td_samplesperpixel*sizeof(float)); if (m==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } for (na=m, nb=0; nb<tif->tif_dir.td_samplesperpixel; na++, nb++) *na=value; o=TIFFWriteDirectoryTagCheckedFloatArray(tif,ndir,dir,tag,tif->tif_dir.td_samplesperpixel,m); _TIFFfree(m); return(o); } static int TIFFWriteDirectoryTagDouble(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, double value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedDouble(tif,ndir,dir,tag,value)); } static int TIFFWriteDirectoryTagDoubleArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, double* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedDoubleArray(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagDoublePerSample(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, double value) { static const char module[] = "TIFFWriteDirectoryTagDoublePerSample"; double* m; double* na; uint16 nb; int o; if (dir==NULL) { (*ndir)++; return(1); } m=_TIFFmalloc(tif->tif_dir.td_samplesperpixel*sizeof(double)); if (m==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } for (na=m, nb=0; nb<tif->tif_dir.td_samplesperpixel; na++, nb++) *na=value; o=TIFFWriteDirectoryTagCheckedDoubleArray(tif,ndir,dir,tag,tif->tif_dir.td_samplesperpixel,m); _TIFFfree(m); return(o); } static int TIFFWriteDirectoryTagIfdArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint32* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedIfdArray(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagIfd8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint64* value) { if (dir==NULL) { (*ndir)++; return(1); } return(TIFFWriteDirectoryTagCheckedIfd8Array(tif,ndir,dir,tag,count,value)); } static int TIFFWriteDirectoryTagShortLong(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 value) { if (dir==NULL) { (*ndir)++; return(1); } if (value<=0xFFFF) return(TIFFWriteDirectoryTagCheckedShort(tif,ndir,dir,tag,(uint16)value)); else return(TIFFWriteDirectoryTagCheckedLong(tif,ndir,dir,tag,value)); } /************************************************************************/ /* TIFFWriteDirectoryTagLongLong8Array() */ /* */ /* Write out LONG8 array as LONG8 for BigTIFF or LONG for */ /* Classic TIFF with some checking. */ /************************************************************************/ static int TIFFWriteDirectoryTagLongLong8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint64* value) { static const char module[] = "TIFFWriteDirectoryTagLongLong8Array"; uint64* ma; uint32 mb; uint32* p; uint32* q; int o; /* is this just a counting pass? */ if (dir==NULL) { (*ndir)++; return(1); } /* We always write LONG8 for BigTIFF, no checking needed. */ if( tif->tif_flags&TIFF_BIGTIFF ) return TIFFWriteDirectoryTagCheckedLong8Array(tif,ndir,dir, tag,count,value); /* ** For classic tiff we want to verify everything is in range for LONG ** and convert to long format. */ p = _TIFFmalloc(count*sizeof(uint32)); if (p==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } for (q=p, ma=value, mb=0; mb<count; ma++, mb++, q++) { if (*ma>0xFFFFFFFF) { TIFFErrorExt(tif->tif_clientdata,module, "Attempt to write value larger than 0xFFFFFFFF in Classic TIFF file."); _TIFFfree(p); return(0); } *q= (uint32)(*ma); } o=TIFFWriteDirectoryTagCheckedLongArray(tif,ndir,dir,tag,count,p); _TIFFfree(p); return(o); } static int TIFFWriteDirectoryTagShortLongLong8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint64* value) { static const char module[] = "TIFFWriteDirectoryTagShortLongLong8Array"; uint64* ma; uint32 mb; uint8 n; int o; if (dir==NULL) { (*ndir)++; return(1); } n=0; for (ma=value, mb=0; mb<count; ma++, mb++) { if ((n==0)&&(*ma>0xFFFF)) n=1; if ((n==1)&&(*ma>0xFFFFFFFF)) { n=2; break; } } if (n==0) { uint16* p; uint16* q; p=_TIFFmalloc(count*sizeof(uint16)); if (p==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } for (ma=value, mb=0, q=p; mb<count; ma++, mb++, q++) *q=(uint16)(*ma); o=TIFFWriteDirectoryTagCheckedShortArray(tif,ndir,dir,tag,count,p); _TIFFfree(p); } else if (n==1) { uint32* p; uint32* q; p=_TIFFmalloc(count*sizeof(uint32)); if (p==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } for (ma=value, mb=0, q=p; mb<count; ma++, mb++, q++) *q=(uint32)(*ma); o=TIFFWriteDirectoryTagCheckedLongArray(tif,ndir,dir,tag,count,p); _TIFFfree(p); } else { assert(n==2); o=TIFFWriteDirectoryTagCheckedLong8Array(tif,ndir,dir,tag,count,value); } return(o); } static int TIFFWriteDirectoryTagColormap(TIFF* tif, uint32* ndir, TIFFDirEntry* dir) { static const char module[] = "TIFFWriteDirectoryTagColormap"; uint32 m; uint16* n; int o; if (dir==NULL) { (*ndir)++; return(1); } m=(1<<tif->tif_dir.td_bitspersample); n=_TIFFmalloc(3*m*sizeof(uint16)); if (n==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } _TIFFmemcpy(&n[0],tif->tif_dir.td_colormap[0],m*sizeof(uint16)); _TIFFmemcpy(&n[m],tif->tif_dir.td_colormap[1],m*sizeof(uint16)); _TIFFmemcpy(&n[2*m],tif->tif_dir.td_colormap[2],m*sizeof(uint16)); o=TIFFWriteDirectoryTagCheckedShortArray(tif,ndir,dir,TIFFTAG_COLORMAP,3*m,n); _TIFFfree(n); return(o); } static int TIFFWriteDirectoryTagTransferfunction(TIFF* tif, uint32* ndir, TIFFDirEntry* dir) { static const char module[] = "TIFFWriteDirectoryTagTransferfunction"; uint32 m; uint16 n; uint16* o; int p; if (dir==NULL) { (*ndir)++; return(1); } m=(1<<tif->tif_dir.td_bitspersample); n=tif->tif_dir.td_samplesperpixel-tif->tif_dir.td_extrasamples; /* * Check if the table can be written as a single column, * or if it must be written as 3 columns. Note that we * write a 3-column tag if there are 2 samples/pixel and * a single column of data won't suffice--hmm. */ if (n>3) n=3; if (n==3) { if (!_TIFFmemcmp(tif->tif_dir.td_transferfunction[0],tif->tif_dir.td_transferfunction[2],m*sizeof(uint16))) n=2; } if (n==2) { if (!_TIFFmemcmp(tif->tif_dir.td_transferfunction[0],tif->tif_dir.td_transferfunction[1],m*sizeof(uint16))) n=1; } if (n==0) n=1; o=_TIFFmalloc(n*m*sizeof(uint16)); if (o==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } _TIFFmemcpy(&o[0],tif->tif_dir.td_transferfunction[0],m*sizeof(uint16)); if (n>1) _TIFFmemcpy(&o[m],tif->tif_dir.td_transferfunction[1],m*sizeof(uint16)); if (n>2) _TIFFmemcpy(&o[2*m],tif->tif_dir.td_transferfunction[2],m*sizeof(uint16)); p=TIFFWriteDirectoryTagCheckedShortArray(tif,ndir,dir,TIFFTAG_TRANSFERFUNCTION,n*m,o); _TIFFfree(o); return(p); } static int TIFFWriteDirectoryTagSubifd(TIFF* tif, uint32* ndir, TIFFDirEntry* dir) { static const char module[] = "TIFFWriteDirectoryTagSubifd"; uint64 m; int n; if (tif->tif_dir.td_nsubifd==0) return(1); if (dir==NULL) { (*ndir)++; return(1); } m=tif->tif_dataoff; if (!(tif->tif_flags&TIFF_BIGTIFF)) { uint32* o; uint64* pa; uint32* pb; uint16 p; o=_TIFFmalloc(tif->tif_dir.td_nsubifd*sizeof(uint32)); if (o==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } pa=tif->tif_dir.td_subifd; pb=o; for (p=0; p<tif->tif_dir.td_nsubifd; p++) { assert(*pa<=0xFFFFFFFFUL); *pb++=(uint32)(*pa++); } n=TIFFWriteDirectoryTagCheckedIfdArray(tif,ndir,dir,TIFFTAG_SUBIFD,tif->tif_dir.td_nsubifd,o); _TIFFfree(o); } else n=TIFFWriteDirectoryTagCheckedIfd8Array(tif,ndir,dir,TIFFTAG_SUBIFD,tif->tif_dir.td_nsubifd,tif->tif_dir.td_subifd); if (!n) return(0); /* * Total hack: if this directory includes a SubIFD * tag then force the next <n> directories to be * written as ``sub directories'' of this one. This * is used to write things like thumbnails and * image masks that one wants to keep out of the * normal directory linkage access mechanism. */ tif->tif_flags|=TIFF_INSUBIFD; tif->tif_nsubifd=tif->tif_dir.td_nsubifd; if (tif->tif_dir.td_nsubifd==1) tif->tif_subifdoff=0; else tif->tif_subifdoff=m; return(1); } static int TIFFWriteDirectoryTagCheckedAscii(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, char* value) { assert(sizeof(char)==1); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_ASCII,count,count,value)); } static int TIFFWriteDirectoryTagCheckedUndefinedArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint8* value) { assert(sizeof(uint8)==1); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_UNDEFINED,count,count,value)); } static int TIFFWriteDirectoryTagCheckedByte(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint8 value) { assert(sizeof(uint8)==1); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_BYTE,1,1,&value)); } static int TIFFWriteDirectoryTagCheckedByteArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint8* value) { assert(sizeof(uint8)==1); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_BYTE,count,count,value)); } static int TIFFWriteDirectoryTagCheckedSbyte(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int8 value) { assert(sizeof(int8)==1); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_SBYTE,1,1,&value)); } static int TIFFWriteDirectoryTagCheckedSbyteArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int8* value) { assert(sizeof(int8)==1); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_SBYTE,count,count,value)); } static int TIFFWriteDirectoryTagCheckedShort(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint16 value) { uint16 m; assert(sizeof(uint16)==2); m=value; if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort(&m); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_SHORT,1,2,&m)); } static int TIFFWriteDirectoryTagCheckedShortArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint16* value) { assert(count<0x80000000); assert(sizeof(uint16)==2); if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfShort(value,count); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_SHORT,count,count*2,value)); } static int TIFFWriteDirectoryTagCheckedSshort(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int16 value) { int16 m; assert(sizeof(int16)==2); m=value; if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)(&m)); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_SSHORT,1,2,&m)); } static int TIFFWriteDirectoryTagCheckedSshortArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int16* value) { assert(count<0x80000000); assert(sizeof(int16)==2); if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfShort((uint16*)value,count); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_SSHORT,count,count*2,value)); } static int TIFFWriteDirectoryTagCheckedLong(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 value) { uint32 m; assert(sizeof(uint32)==4); m=value; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(&m); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_LONG,1,4,&m)); } static int TIFFWriteDirectoryTagCheckedLongArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint32* value) { assert(count<0x40000000); assert(sizeof(uint32)==4); if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong(value,count); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_LONG,count,count*4,value)); } static int TIFFWriteDirectoryTagCheckedSlong(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int32 value) { int32 m; assert(sizeof(int32)==4); m=value; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong((uint32*)(&m)); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_SLONG,1,4,&m)); } static int TIFFWriteDirectoryTagCheckedSlongArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int32* value) { assert(count<0x40000000); assert(sizeof(int32)==4); if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong((uint32*)value,count); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_SLONG,count,count*4,value)); } static int TIFFWriteDirectoryTagCheckedLong8(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint64 value) { uint64 m; assert(sizeof(uint64)==8); assert(tif->tif_flags&TIFF_BIGTIFF); m=value; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8(&m); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_LONG8,1,8,&m)); } static int TIFFWriteDirectoryTagCheckedLong8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint64* value) { assert(count<0x20000000); assert(sizeof(uint64)==8); assert(tif->tif_flags&TIFF_BIGTIFF); if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong8(value,count); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_LONG8,count,count*8,value)); } static int TIFFWriteDirectoryTagCheckedSlong8(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, int64 value) { int64 m; assert(sizeof(int64)==8); assert(tif->tif_flags&TIFF_BIGTIFF); m=value; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8((uint64*)(&m)); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_SLONG8,1,8,&m)); } static int TIFFWriteDirectoryTagCheckedSlong8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, int64* value) { assert(count<0x20000000); assert(sizeof(int64)==8); assert(tif->tif_flags&TIFF_BIGTIFF); if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong8((uint64*)value,count); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_SLONG8,count,count*8,value)); } static int TIFFWriteDirectoryTagCheckedRational(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, double value) { uint32 m[2]; assert(value>=0.0); assert(sizeof(uint32)==4); if (value<=0.0) { m[0]=0; m[1]=1; } else if (value==(double)(uint32)value) { m[0]=(uint32)value; m[1]=1; } else if (value<1.0) { m[0]=(uint32)(value*0xFFFFFFFF); m[1]=0xFFFFFFFF; } else { m[0]=0xFFFFFFFF; m[1]=(uint32)(0xFFFFFFFF/value); } if (tif->tif_flags&TIFF_SWAB) { TIFFSwabLong(&m[0]); TIFFSwabLong(&m[1]); } return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_RATIONAL,1,8,&m[0])); } static int TIFFWriteDirectoryTagCheckedRationalArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, float* value) { static const char module[] = "TIFFWriteDirectoryTagCheckedRationalArray"; uint32* m; float* na; uint32* nb; uint32 nc; int o; assert(sizeof(uint32)==4); m=_TIFFmalloc(count*2*sizeof(uint32)); if (m==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } for (na=value, nb=m, nc=0; nc<count; na++, nb+=2, nc++) { if (*na<=0.0) { nb[0]=0; nb[1]=1; } else if (*na==(float)(uint32)(*na)) { nb[0]=(uint32)(*na); nb[1]=1; } else if (*na<1.0) { nb[0]=(uint32)((*na)*0xFFFFFFFF); nb[1]=0xFFFFFFFF; } else { nb[0]=0xFFFFFFFF; nb[1]=(uint32)(0xFFFFFFFF/(*na)); } } if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong(m,count*2); o=TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_RATIONAL,count,count*8,&m[0]); _TIFFfree(m); return(o); } static int TIFFWriteDirectoryTagCheckedSrationalArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, float* value) { static const char module[] = "TIFFWriteDirectoryTagCheckedSrationalArray"; int32* m; float* na; int32* nb; uint32 nc; int o; assert(sizeof(int32)==4); m=_TIFFmalloc(count*2*sizeof(int32)); if (m==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } for (na=value, nb=m, nc=0; nc<count; na++, nb+=2, nc++) { if (*na<0.0) { if (*na==(int32)(*na)) { nb[0]=(int32)(*na); nb[1]=1; } else if (*na>-1.0) { nb[0]=-(int32)((-*na)*0x7FFFFFFF); nb[1]=0x7FFFFFFF; } else { nb[0]=-0x7FFFFFFF; nb[1]=(int32)(0x7FFFFFFF/(-*na)); } } else { if (*na==(int32)(*na)) { nb[0]=(int32)(*na); nb[1]=1; } else if (*na<1.0) { nb[0]=(int32)((*na)*0x7FFFFFFF); nb[1]=0x7FFFFFFF; } else { nb[0]=0x7FFFFFFF; nb[1]=(int32)(0x7FFFFFFF/(*na)); } } } if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong((uint32*)m,count*2); o=TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_SRATIONAL,count,count*8,&m[0]); _TIFFfree(m); return(o); } static int TIFFWriteDirectoryTagCheckedFloat(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, float value) { float m; assert(sizeof(float)==4); m=value; TIFFCvtNativeToIEEEFloat(tif,1,&m); if (tif->tif_flags&TIFF_SWAB) TIFFSwabFloat(&m); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_FLOAT,1,4,&m)); } static int TIFFWriteDirectoryTagCheckedFloatArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, float* value) { assert(count<0x40000000); assert(sizeof(float)==4); TIFFCvtNativeToIEEEFloat(tif,count,&value); if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfFloat(value,count); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_FLOAT,count,count*4,value)); } static int TIFFWriteDirectoryTagCheckedDouble(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, double value) { double m; assert(sizeof(double)==8); m=value; TIFFCvtNativeToIEEEDouble(tif,1,&m); if (tif->tif_flags&TIFF_SWAB) TIFFSwabDouble(&m); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_DOUBLE,1,8,&m)); } static int TIFFWriteDirectoryTagCheckedDoubleArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, double* value) { assert(count<0x20000000); assert(sizeof(double)==8); TIFFCvtNativeToIEEEDouble(tif,count,&value); if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfDouble(value,count); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_DOUBLE,count,count*8,value)); } static int TIFFWriteDirectoryTagCheckedIfdArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint32* value) { assert(count<0x40000000); assert(sizeof(uint32)==4); if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong(value,count); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_IFD,count,count*4,value)); } static int TIFFWriteDirectoryTagCheckedIfd8Array(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, uint64* value) { assert(count<0x20000000); assert(sizeof(uint64)==8); assert(tif->tif_flags&TIFF_BIGTIFF); if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong8(value,count); return(TIFFWriteDirectoryTagData(tif,ndir,dir,tag,TIFF_IFD8,count,count*8,value)); } static int TIFFWriteDirectoryTagData(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint16 datatype, uint32 count, uint32 datalength, void* data) { static const char module[] = "TIFFWriteDirectoryTagData"; uint32 m; m=0; while (m<(*ndir)) { assert(dir[m].tdir_tag!=tag); if (dir[m].tdir_tag>tag) break; m++; } if (m<(*ndir)) { uint32 n; for (n=*ndir; n>m; n--) dir[n]=dir[n-1]; } dir[m].tdir_tag=tag; dir[m].tdir_type=datatype; dir[m].tdir_count=count; dir[m].tdir_offset=0; if (datalength<=((tif->tif_flags&TIFF_BIGTIFF)?0x8U:0x4U)) _TIFFmemcpy(&dir[m].tdir_offset,data,datalength); else { uint64 na,nb; na=tif->tif_dataoff; nb=na+datalength; if (!(tif->tif_flags&TIFF_BIGTIFF)) nb=(uint32)nb; if ((nb<na)||(nb<datalength)) { TIFFErrorExt(tif->tif_clientdata,module,"Maximum TIFF file size exceeded"); return(0); } if (!SeekOK(tif,na)) { TIFFErrorExt(tif->tif_clientdata,module,"IO error writing tag data"); return(0); } assert(datalength<0x80000000UL); if (!WriteOK(tif,data,(tmsize_t)datalength)) { TIFFErrorExt(tif->tif_clientdata,module,"IO error writing tag data"); return(0); } tif->tif_dataoff=nb; if (tif->tif_dataoff&1) tif->tif_dataoff++; if (!(tif->tif_flags&TIFF_BIGTIFF)) { uint32 o; o=(uint32)na; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(&o); _TIFFmemcpy(&dir[m].tdir_offset,&o,4); } else { dir[m].tdir_offset=na; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8(&dir[m].tdir_offset); } } (*ndir)++; return(1); } /* * Link the current directory into the directory chain for the file. */ static int TIFFLinkDirectory(TIFF* tif) { static const char module[] = "TIFFLinkDirectory"; tif->tif_diroff = (TIFFSeekFile(tif,0,SEEK_END)+1) &~ 1; /* * Handle SubIFDs */ if (tif->tif_flags & TIFF_INSUBIFD) { if (!(tif->tif_flags&TIFF_BIGTIFF)) { uint32 m; m = (uint32)tif->tif_diroff; if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong(&m); (void) TIFFSeekFile(tif, tif->tif_subifdoff, SEEK_SET); if (!WriteOK(tif, &m, 4)) { TIFFErrorExt(tif->tif_clientdata, module, "Error writing SubIFD directory link"); return (0); } /* * Advance to the next SubIFD or, if this is * the last one configured, revert back to the * normal directory linkage. */ if (--tif->tif_nsubifd) tif->tif_subifdoff += 4; else tif->tif_flags &= ~TIFF_INSUBIFD; return (1); } else { uint64 m; m = tif->tif_diroff; if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong8(&m); (void) TIFFSeekFile(tif, tif->tif_subifdoff, SEEK_SET); if (!WriteOK(tif, &m, 8)) { TIFFErrorExt(tif->tif_clientdata, module, "Error writing SubIFD directory link"); return (0); } /* * Advance to the next SubIFD or, if this is * the last one configured, revert back to the * normal directory linkage. */ if (--tif->tif_nsubifd) tif->tif_subifdoff += 8; else tif->tif_flags &= ~TIFF_INSUBIFD; return (1); } } if (!(tif->tif_flags&TIFF_BIGTIFF)) { uint32 m; uint32 nextdir; m = (uint32)(tif->tif_diroff); if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong(&m); if (tif->tif_header.classic.tiff_diroff == 0) { /* * First directory, overwrite offset in header. */ tif->tif_header.classic.tiff_diroff = (uint32) tif->tif_diroff; (void) TIFFSeekFile(tif,4, SEEK_SET); if (!WriteOK(tif, &m, 4)) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error writing TIFF header"); return (0); } return (1); } /* * Not the first directory, search to the last and append. */ nextdir = tif->tif_header.classic.tiff_diroff; while(1) { uint16 dircount; uint32 nextnextdir; if (!SeekOK(tif, nextdir) || !ReadOK(tif, &dircount, 2)) { TIFFErrorExt(tif->tif_clientdata, module, "Error fetching directory count"); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); (void) TIFFSeekFile(tif, nextdir+2+dircount*12, SEEK_SET); if (!ReadOK(tif, &nextnextdir, 4)) { TIFFErrorExt(tif->tif_clientdata, module, "Error fetching directory link"); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong(&nextnextdir); if (nextnextdir==0) { (void) TIFFSeekFile(tif, nextdir+2+dircount*12, SEEK_SET); if (!WriteOK(tif, &m, 4)) { TIFFErrorExt(tif->tif_clientdata, module, "Error writing directory link"); return (0); } break; } nextdir=nextnextdir; } } else { uint64 m; uint64 nextdir; m = tif->tif_diroff; if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong8(&m); if (tif->tif_header.big.tiff_diroff == 0) { /* * First directory, overwrite offset in header. */ tif->tif_header.big.tiff_diroff = tif->tif_diroff; (void) TIFFSeekFile(tif,8, SEEK_SET); if (!WriteOK(tif, &m, 8)) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error writing TIFF header"); return (0); } return (1); } /* * Not the first directory, search to the last and append. */ nextdir = tif->tif_header.big.tiff_diroff; while(1) { uint64 dircount64; uint16 dircount; uint64 nextnextdir; if (!SeekOK(tif, nextdir) || !ReadOK(tif, &dircount64, 8)) { TIFFErrorExt(tif->tif_clientdata, module, "Error fetching directory count"); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong8(&dircount64); if (dircount64>0xFFFF) { TIFFErrorExt(tif->tif_clientdata, module, "Sanity check on tag count failed, likely corrupt TIFF"); return (0); } dircount=(uint16)dircount64; (void) TIFFSeekFile(tif, nextdir+8+dircount*20, SEEK_SET); if (!ReadOK(tif, &nextnextdir, 8)) { TIFFErrorExt(tif->tif_clientdata, module, "Error fetching directory link"); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong8(&nextnextdir); if (nextnextdir==0) { (void) TIFFSeekFile(tif, nextdir+8+dircount*20, SEEK_SET); if (!WriteOK(tif, &m, 8)) { TIFFErrorExt(tif->tif_clientdata, module, "Error writing directory link"); return (0); } break; } nextdir=nextnextdir; } } return (1); } /* vim: set ts=8 sts=8 sw=8 noet: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/libtiff_2007-11-02-371336d-865f7b2.c
manybugs_data_66
#include <sys/stat.h> #include <limits.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <ctype.h> #include <errno.h> #include "request.h" #include "keyvalue.h" #include "log.h" #include "http_req.h" #include "sys-strings.h" static int request_check_hostname(buffer *host) { enum { DOMAINLABEL, TOPLABEL } stage = TOPLABEL; size_t i; int label_len = 0; size_t host_len; char *colon; int is_ip = -1; /* -1 don't know yet, 0 no, 1 yes */ int level = 0; /* * hostport = host [ ":" port ] * host = hostname | IPv4address | IPv6address * hostname = *( domainlabel "." ) toplabel [ "." ] * domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum * toplabel = alpha | alpha *( alphanum | "-" ) alphanum * IPv4address = 1*digit "." 1*digit "." 1*digit "." 1*digit * IPv6address = "[" ... "]" * port = *digit */ /* no Host: */ if (buffer_is_empty(host)) return 0; if (host->used < 1) return 0; host_len = host->used - 1; /* IPv6 adress */ if (host->ptr[0] == '[') { char *c = host->ptr + 1; int colon_cnt = 0; /* check portnumber */ for (; *c && *c != ']'; c++) { if (*c == ':') { if (++colon_cnt > 7) { return -1; } } else if (!light_isxdigit(*c)) { return -1; } } /* missing ] */ if (!*c) { return -1; } /* check port */ if (*(c+1) == ':') { for (c += 2; *c; c++) { if (!light_isdigit(*c)) { return -1; } } } return 0; } if (NULL != (colon = memchr(host->ptr, ':', host_len))) { char *c = colon + 1; /* check portnumber */ for (; *c; c++) { if (!light_isdigit(*c)) return -1; } /* remove the port from the host-len */ host_len = colon - host->ptr; } /* Host is empty */ if (host_len == 0) return -1; /* if the hostname ends in a "." strip it */ if (host->ptr[host_len-1] == '.') { /* shift port info one left */ if (NULL != colon) memmove(colon-1, colon, host->used - host_len); else host->ptr[host_len-1] = '\0'; host_len -= 1; host->used -= 1; } if (host_len == 0) return -1; /* scan from the right and skip the \0 */ for (i = host_len; i-- > 0; ) { const char c = host->ptr[i]; switch (stage) { case TOPLABEL: if (c == '.') { /* only switch stage, if this is not the last character */ if (i != host_len - 1) { if (label_len == 0) { return -1; } /* check the first character at right of the dot */ if (is_ip == 0) { if (!light_isalnum(host->ptr[i+1])) { return -1; } } else if (!light_isdigit(host->ptr[i+1])) { is_ip = 0; } else if ('-' == host->ptr[i+1]) { return -1; } else { /* just digits */ is_ip = 1; } stage = DOMAINLABEL; label_len = 0; level++; } else if (i == 0) { /* just a dot and nothing else is evil */ return -1; } } else if (i == 0) { /* the first character of the hostname */ if (!light_isalnum(c)) { return -1; } label_len++; } else { if (c != '-' && !light_isalnum(c)) { return -1; } if (is_ip == -1) { if (!light_isdigit(c)) is_ip = 0; } label_len++; } break; case DOMAINLABEL: if (is_ip == 1) { if (c == '.') { if (label_len == 0) { return -1; } label_len = 0; level++; } else if (!light_isdigit(c)) { return -1; } else { label_len++; } } else { if (c == '.') { if (label_len == 0) { return -1; } /* c is either - or alphanum here */ if ('-' == host->ptr[i+1]) { return -1; } label_len = 0; level++; } else if (i == 0) { if (!light_isalnum(c)) { return -1; } label_len++; } else { if (c != '-' && !light_isalnum(c)) { return -1; } label_len++; } } break; } } /* a IP has to consist of 4 parts */ if (is_ip == 1 && level != 3) { return -1; } if (label_len == 0) { return -1; } return 0; } #if 0 #define DUMP_HEADER #endif static int http_request_split_value(array *vals, buffer *b) { char *s; size_t i; int state = 0; /* * parse * * val1, val2, val3, val4 * * into a array (more or less a explode() incl. striping of whitespaces */ if (b->used == 0) return 0; s = b->ptr; for (i =0; i < b->used - 1; ) { char *start = NULL, *end = NULL; data_string *ds; switch (state) { case 0: /* ws */ /* skip ws */ for (; (*s == ' ' || *s == '\t') && i < b->used - 1; i++, s++); state = 1; break; case 1: /* value */ start = s; for (; *s != ',' && i < b->used - 1; i++, s++); end = s - 1; for (; (*end == ' ' || *end == '\t') && end > start; end--); if (NULL == (ds = (data_string *)array_get_unused_element(vals, TYPE_STRING))) { ds = data_string_init(); } buffer_copy_string_len(ds->value, start, end-start+1); array_insert_unique(vals, (data_unset *)ds); if (*s == ',') { state = 0; i++; s++; } else { /* end of string */ state = 2; } break; default: i++; break; } } return 0; } int http_request_parse(server *srv, connection *con, http_req *req) { size_t i; enum { HTTP_CONNECTION_UNSET, HTTP_CONNECTION_CLOSE, HTTP_CONNECTION_KEEPALIVE } keep_alive_set = HTTP_CONNECTION_UNSET; if (req->protocol == HTTP_VERSION_UNSET) { con->http_status = 505; /* Version not Supported */ return 0; } if (req->method == HTTP_METHOD_UNSET) { con->http_status = 405; /* Method not allowed */ return 0; } if (buffer_is_empty(req->uri_raw)) { con->http_status = 400; return 0; } /* strip absolute URLs * */ buffer_copy_string_buffer(con->request.orig_uri, req->uri_raw); if (req->uri_raw->ptr[0] == '/') { buffer_copy_string_buffer(con->request.uri, req->uri_raw); } else if (req->uri_raw->ptr[0] == '*') { if (req->method != HTTP_METHOD_OPTIONS) { con->http_status = 400; return 0; } buffer_copy_string_buffer(con->request.uri, req->uri_raw); } else { /* GET http://www.example.org/foobar */ char *sl; if (0 != strncmp(BUF_STR(req->uri_raw), "http://", 7)) { con->http_status = 400; return 0; } if (NULL == (sl = strchr(BUF_STR(req->uri_raw) + 7, '/'))) { con->http_status = 400; return 0; } buffer_copy_string(con->request.uri, sl); buffer_copy_string_len(con->request.http_host, BUF_STR(req->uri_raw) + 7, sl - BUF_STR(req->uri_raw) - 7); if (request_check_hostname(con->request.http_host)) { if (srv->srvconf.log_request_header_on_error) { TRACE("Host header is invalid (Status: 400), was %s", SAFE_BUF_STR(con->request.http_host)); } con->http_status = 400; con->keep_alive = 0; buffer_reset(con->request.http_host); return 0; } } con->request.http_method = req->method; con->request.http_version = req->protocol; for (i = 0; i < req->headers->used; i++) { data_string *ds = (data_string *)req->headers->data[i]; data_string *hdr; int cmp; /* this list is sorted */ if (0 == (cmp = buffer_caseless_compare(CONST_BUF_LEN(ds->key), CONST_STR_LEN("Connection")))) { array *vals; size_t vi; /* Connection: Keep-Alive, ... */ vals = srv->split_vals; array_reset(vals); http_request_split_value(vals, ds->value); for (vi = 0; vi < vals->used; vi++) { data_string *dsv = (data_string *)vals->data[vi]; if (0 == buffer_caseless_compare(CONST_BUF_LEN(dsv->value), CONST_STR_LEN("keep-alive"))) { keep_alive_set = HTTP_CONNECTION_KEEPALIVE; break; } else if (0 == buffer_caseless_compare(CONST_BUF_LEN(dsv->value), CONST_STR_LEN("close"))) { keep_alive_set = HTTP_CONNECTION_CLOSE; break; } } } else if (cmp > 0 && 0 == (cmp = buffer_caseless_compare(CONST_BUF_LEN(ds->key), CONST_STR_LEN("Content-Length")))) { char *err; off_t r; /* ignore the header, if it is a duplicate */ if (con->request.content_length != -1) continue; r = str_to_off_t(ds->value->ptr, &err, 10); if (*err != '\0') { TRACE("content-length is not a number: %s (Status: 400)", err); con->http_status = 400; return 0; } /** * check if we had a over- or underrun in the string conversion */ if (r == STR_OFF_T_MIN || r == STR_OFF_T_MAX) { if (errno == ERANGE) { con->http_status = 413; return 0; } } /** * negative content-length is not supported * and is a bad request */ if (r < 0) { con->http_status = 400; return 0; } /* don't handle more the SSIZE_MAX bytes in content-length */ if (r > SSIZE_MAX) { con->http_status = 413; ERROR("request-size too long: %s (Status: 413)", SAFE_BUF_STR(ds->value)); return 0; } con->request.content_length = r; } else if (cmp > 0 && 0 == (cmp = buffer_caseless_compare(CONST_BUF_LEN(ds->key), CONST_STR_LEN("Expect")))) { /* HTTP 2616 8.2.3 * Expect: 100-continue * * -> (10.1.1) 100 (read content, process request, send final status-code) * -> (10.4.18) 417 (close) * * */ if (0 != buffer_caseless_compare(CONST_BUF_LEN(ds->value), CONST_STR_LEN("100-continue"))) { /* we only support 100-continue */ con->http_status = 417; return 0; } if (con->request.http_version != HTTP_VERSION_1_1) { /* only HTTP/1.1 clients can send us this header */ con->http_status = 417; return 0; } } else if (cmp > 0 && 0 == (cmp = buffer_caseless_compare(CONST_BUF_LEN(ds->key), CONST_STR_LEN("Host")))) { if (request_check_hostname(ds->value)) { TRACE("Host header is invalid (Status: 400), was %s", SAFE_BUF_STR(ds->value)); con->http_status = 400; con->keep_alive = 0; return 0; } if (!buffer_is_empty(con->request.http_host) && !buffer_is_equal(con->request.http_host, ds->value)) { TRACE("%s", "Host header is duplicate (Status: 400)"); con->http_status = 400; return 0; } buffer_copy_string_buffer(con->request.http_host, ds->value); } else if (cmp > 0 && 0 == (cmp = buffer_caseless_compare(CONST_BUF_LEN(ds->key), CONST_STR_LEN("If-Modified-Since")))) { data_string *old; if (NULL != (old = (data_string *)array_get_element(con->request.headers, CONST_STR_LEN("If-Modified-Since")))) { if (0 != buffer_caseless_compare(CONST_BUF_LEN(old->value), CONST_BUF_LEN(ds->value))) { /* duplicate header and different timestamps */ con->http_status = 400; TRACE("%s", "If-Modified-Since is duplicate (Status: 400)"); return 0; } } } else if (cmp > 0 && 0 == (cmp = buffer_caseless_compare(CONST_BUF_LEN(ds->key), CONST_STR_LEN("If-None-Match")))) { data_string *old; /* if dup, only the first one will survive */ if (NULL != (old = (data_string *)array_get_element(con->request.headers, CONST_STR_LEN("If-None-Match")))) { continue; } } else if (cmp > 0 && 0 == (cmp = buffer_caseless_compare(CONST_BUF_LEN(ds->key), CONST_STR_LEN("Range")))) { if (NULL != array_get_element(con->request.headers, CONST_STR_LEN("Range"))) { /* duplicate Range header */ TRACE("%s", "Range: header is duplicate (Status: 400)"); con->http_status = 400; con->keep_alive = 0; return 0; } } if (NULL == (hdr = (data_string *)array_get_unused_element(con->request.headers, TYPE_STRING))) { hdr = data_string_init(); } buffer_copy_string_buffer(hdr->key, ds->key); buffer_copy_string_buffer(hdr->value, ds->value); array_insert_unique(con->request.headers, (data_unset *)hdr); } con->header_len = i; /* do some post-processing */ if (con->request.http_version == HTTP_VERSION_1_1) { if (keep_alive_set != HTTP_CONNECTION_CLOSE) { /* no Connection-Header sent */ /* HTTP/1.1 -> keep-alive default TRUE */ con->keep_alive = 1; } else { con->keep_alive = 0; } /* RFC 2616, 14.23 */ if (buffer_is_empty(con->request.http_host)) { con->http_status = 400; con->response.keep_alive = 0; con->keep_alive = 0; if (srv->srvconf.log_request_header_on_error) { log_error_write(srv, __FILE__, __LINE__, "s", "HTTP/1.1 but Host missing -> 400"); log_error_write(srv, __FILE__, __LINE__, "Sb", "request-header:\n", con->request.request); } return 0; } } else { if (keep_alive_set == HTTP_CONNECTION_KEEPALIVE) { /* no Connection-Header sent */ /* HTTP/1.0 -> keep-alive default FALSE */ con->keep_alive = 1; } else { con->keep_alive = 0; } } switch(con->request.http_method) { case HTTP_METHOD_GET: case HTTP_METHOD_HEAD: /* content-length is forbidden for those */ if (con->request.content_length != -1) { /* content-length is missing */ if (srv->srvconf.log_request_header_on_error) { ERROR("GET/HEAD with content-length: %d", 400); } con->keep_alive = 0; con->http_status = 400; return 0; } break; case HTTP_METHOD_POST: /* content-length is required for them */ if (con->request.content_length == -1) { /* content-length is missing */ if (srv->srvconf.log_request_header_on_error) { log_error_write(srv, __FILE__, __LINE__, "s", "POST-request, but content-length missing -> 411"); } con->keep_alive = 0; con->http_status = 411; return 0; } break; default: /* the may have a content-length */ break; } /* check if we have read post data */ if (con->request.content_length != -1) { /* divide by 1024 as srvconf.max_request_size is in kBytes */ if (srv->srvconf.max_request_size != 0 && ((size_t)(con->request.content_length >> 10)) > srv->srvconf.max_request_size) { /* the request body itself is larger then * our our max_request_size */ con->http_status = 413; con->keep_alive = 0; log_error_write(srv, __FILE__, __LINE__, "sos", "request-size too long:", con->request.content_length, "-> 413"); return 0; } } return 0; } #include <sys/stat.h> #include <limits.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <ctype.h> #include <errno.h> #include "request.h" #include "keyvalue.h" #include "log.h" #include "http_req.h" #include "sys-strings.h" static int request_check_hostname(buffer *host) { enum { DOMAINLABEL, TOPLABEL } stage = TOPLABEL; size_t i; int label_len = 0; size_t host_len; char *colon; int is_ip = -1; /* -1 don't know yet, 0 no, 1 yes */ int level = 0; /* * hostport = host [ ":" port ] * host = hostname | IPv4address | IPv6address * hostname = *( domainlabel "." ) toplabel [ "." ] * domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum * toplabel = alpha | alpha *( alphanum | "-" ) alphanum * IPv4address = 1*digit "." 1*digit "." 1*digit "." 1*digit * IPv6address = "[" ... "]" * port = *digit */ /* no Host: */ if (buffer_is_empty(host)) return 0; if (host->used < 1) return 0; host_len = host->used - 1; /* IPv6 adress */ if (host->ptr[0] == '[') { char *c = host->ptr + 1; int colon_cnt = 0; /* check portnumber */ for (; *c && *c != ']'; c++) { if (*c == ':') { if (++colon_cnt > 7) { return -1; } } else if (!light_isxdigit(*c)) { return -1; } } /* missing ] */ if (!*c) { return -1; } /* check port */ if (*(c+1) == ':') { for (c += 2; *c; c++) { if (!light_isdigit(*c)) { return -1; } } } return 0; } if (NULL != (colon = memchr(host->ptr, ':', host_len))) { char *c = colon + 1; /* check portnumber */ for (; *c; c++) { if (!light_isdigit(*c)) return -1; } /* remove the port from the host-len */ host_len = colon - host->ptr; } /* Host is empty */ if (host_len == 0) return -1; /* if the hostname ends in a "." strip it */ if (host->ptr[host_len-1] == '.') { /* shift port info one left */ if (NULL != colon) memmove(colon-1, colon, host->used - host_len); else host->ptr[host_len-1] = '\0'; host_len -= 1; host->used -= 1; } if (host_len == 0) return -1; /* scan from the right and skip the \0 */ for (i = host_len; i-- > 0; ) { const char c = host->ptr[i]; switch (stage) { case TOPLABEL: if (c == '.') { /* only switch stage, if this is not the last character */ if (i != host_len - 1) { if (label_len == 0) { return -1; } /* check the first character at right of the dot */ if (is_ip == 0) { if (!light_isalnum(host->ptr[i+1])) { return -1; } } else if (!light_isdigit(host->ptr[i+1])) { is_ip = 0; } else if ('-' == host->ptr[i+1]) { return -1; } else { /* just digits */ is_ip = 1; } stage = DOMAINLABEL; label_len = 0; level++; } else if (i == 0) { /* just a dot and nothing else is evil */ return -1; } } else if (i == 0) { /* the first character of the hostname */ if (!light_isalnum(c)) { return -1; } label_len++; } else { if (c != '-' && !light_isalnum(c)) { return -1; } if (is_ip == -1) { if (!light_isdigit(c)) is_ip = 0; } label_len++; } break; case DOMAINLABEL: if (is_ip == 1) { if (c == '.') { if (label_len == 0) { return -1; } label_len = 0; level++; } else if (!light_isdigit(c)) { return -1; } else { label_len++; } } else { if (c == '.') { if (label_len == 0) { return -1; } /* c is either - or alphanum here */ if ('-' == host->ptr[i+1]) { return -1; } label_len = 0; level++; } else if (i == 0) { if (!light_isalnum(c)) { return -1; } label_len++; } else { if (c != '-' && !light_isalnum(c)) { return -1; } label_len++; } } break; } } /* a IP has to consist of 4 parts */ if (is_ip == 1 && level != 3) { return -1; } if (label_len == 0) { return -1; } return 0; } #if 0 #define DUMP_HEADER #endif static int http_request_split_value(array *vals, buffer *b) { char *s; size_t i; int state = 0; /* * parse * * val1, val2, val3, val4 * * into a array (more or less a explode() incl. striping of whitespaces */ if (b->used == 0) return 0; s = b->ptr; for (i =0; i < b->used - 1; ) { char *start = NULL, *end = NULL; data_string *ds; switch (state) { case 0: /* ws */ /* skip ws */ for (; (*s == ' ' || *s == '\t') && i < b->used - 1; i++, s++); state = 1; break; case 1: /* value */ start = s; for (; *s != ',' && i < b->used - 1; i++, s++); end = s - 1; for (; (*end == ' ' || *end == '\t') && end > start; end--); if (NULL == (ds = (data_string *)array_get_unused_element(vals, TYPE_STRING))) { ds = data_string_init(); } buffer_copy_string_len(ds->value, start, end-start+1); array_insert_unique(vals, (data_unset *)ds); if (*s == ',') { state = 0; i++; s++; } else { /* end of string */ state = 2; } break; default: i++; break; } } return 0; } int http_request_parse(server *srv, connection *con, http_req *req) { size_t i; enum { HTTP_CONNECTION_UNSET, HTTP_CONNECTION_CLOSE, HTTP_CONNECTION_KEEPALIVE } keep_alive_set = HTTP_CONNECTION_UNSET; if (req->protocol == HTTP_VERSION_UNSET) { con->http_status = 505; /* Version not Supported */ return 0; } if (req->method == HTTP_METHOD_UNSET) { con->http_status = 405; /* Method not allowed */ return 0; } if (buffer_is_empty(req->uri_raw)) { con->http_status = 400; return 0; } /* strip absolute URLs * */ buffer_copy_string_buffer(con->request.orig_uri, req->uri_raw); if (req->uri_raw->ptr[0] == '/') { buffer_copy_string_buffer(con->request.uri, req->uri_raw); } else if (req->uri_raw->ptr[0] == '*') { if (req->method != HTTP_METHOD_OPTIONS) { con->http_status = 400; return 0; } buffer_copy_string_buffer(con->request.uri, req->uri_raw); } else { /* GET http://www.example.org/foobar */ char *sl; int l; if (0 == strncmp(BUF_STR(req->uri_raw), "https://", 8)) { l = 8; } else if (0 == strncmp(BUF_STR(req->uri_raw), "http://", 7)) { l = 7; } else { con->http_status = 400; return 0; } if (NULL == (sl = strchr(BUF_STR(req->uri_raw) + l, '/'))) { con->http_status = 400; return 0; } buffer_copy_string(con->request.uri, sl); buffer_copy_string_len(con->request.http_host, BUF_STR(req->uri_raw) + l, sl - BUF_STR(req->uri_raw) - l); if (request_check_hostname(con->request.http_host)) { if (srv->srvconf.log_request_header_on_error) { TRACE("Host header is invalid (Status: 400), was %s", SAFE_BUF_STR(con->request.http_host)); } con->http_status = 400; con->keep_alive = 0; buffer_reset(con->request.http_host); return 0; } } con->request.http_method = req->method; con->request.http_version = req->protocol; for (i = 0; i < req->headers->used; i++) { data_string *ds = (data_string *)req->headers->data[i]; data_string *hdr; int cmp; /* this list is sorted */ if (0 == (cmp = buffer_caseless_compare(CONST_BUF_LEN(ds->key), CONST_STR_LEN("Connection")))) { array *vals; size_t vi; /* Connection: Keep-Alive, ... */ vals = srv->split_vals; array_reset(vals); http_request_split_value(vals, ds->value); for (vi = 0; vi < vals->used; vi++) { data_string *dsv = (data_string *)vals->data[vi]; if (0 == buffer_caseless_compare(CONST_BUF_LEN(dsv->value), CONST_STR_LEN("keep-alive"))) { keep_alive_set = HTTP_CONNECTION_KEEPALIVE; break; } else if (0 == buffer_caseless_compare(CONST_BUF_LEN(dsv->value), CONST_STR_LEN("close"))) { keep_alive_set = HTTP_CONNECTION_CLOSE; break; } } } else if (cmp > 0 && 0 == (cmp = buffer_caseless_compare(CONST_BUF_LEN(ds->key), CONST_STR_LEN("Content-Length")))) { char *err; off_t r; /* ignore the header, if it is a duplicate */ if (con->request.content_length != -1) continue; r = str_to_off_t(ds->value->ptr, &err, 10); if (*err != '\0') { TRACE("content-length is not a number: %s (Status: 400)", err); con->http_status = 400; return 0; } /** * check if we had a over- or underrun in the string conversion */ if (r == STR_OFF_T_MIN || r == STR_OFF_T_MAX) { if (errno == ERANGE) { con->http_status = 413; return 0; } } /** * negative content-length is not supported * and is a bad request */ if (r < 0) { con->http_status = 400; return 0; } /* don't handle more the SSIZE_MAX bytes in content-length */ if (r > SSIZE_MAX) { con->http_status = 413; ERROR("request-size too long: %s (Status: 413)", SAFE_BUF_STR(ds->value)); return 0; } con->request.content_length = r; } else if (cmp > 0 && 0 == (cmp = buffer_caseless_compare(CONST_BUF_LEN(ds->key), CONST_STR_LEN("Expect")))) { /* HTTP 2616 8.2.3 * Expect: 100-continue * * -> (10.1.1) 100 (read content, process request, send final status-code) * -> (10.4.18) 417 (close) * * */ if (0 != buffer_caseless_compare(CONST_BUF_LEN(ds->value), CONST_STR_LEN("100-continue"))) { /* we only support 100-continue */ con->http_status = 417; return 0; } if (con->request.http_version != HTTP_VERSION_1_1) { /* only HTTP/1.1 clients can send us this header */ con->http_status = 417; return 0; } } else if (cmp > 0 && 0 == (cmp = buffer_caseless_compare(CONST_BUF_LEN(ds->key), CONST_STR_LEN("Host")))) { if (request_check_hostname(ds->value)) { TRACE("Host header is invalid (Status: 400), was %s", SAFE_BUF_STR(ds->value)); con->http_status = 400; con->keep_alive = 0; return 0; } if (!buffer_is_empty(con->request.http_host) && !buffer_is_equal(con->request.http_host, ds->value)) { TRACE("%s", "Host header is duplicate (Status: 400)"); con->http_status = 400; return 0; } buffer_copy_string_buffer(con->request.http_host, ds->value); } else if (cmp > 0 && 0 == (cmp = buffer_caseless_compare(CONST_BUF_LEN(ds->key), CONST_STR_LEN("If-Modified-Since")))) { data_string *old; if (NULL != (old = (data_string *)array_get_element(con->request.headers, CONST_STR_LEN("If-Modified-Since")))) { if (0 != buffer_caseless_compare(CONST_BUF_LEN(old->value), CONST_BUF_LEN(ds->value))) { /* duplicate header and different timestamps */ con->http_status = 400; TRACE("%s", "If-Modified-Since is duplicate (Status: 400)"); return 0; } } } else if (cmp > 0 && 0 == (cmp = buffer_caseless_compare(CONST_BUF_LEN(ds->key), CONST_STR_LEN("If-None-Match")))) { data_string *old; /* if dup, only the first one will survive */ if (NULL != (old = (data_string *)array_get_element(con->request.headers, CONST_STR_LEN("If-None-Match")))) { continue; } } else if (cmp > 0 && 0 == (cmp = buffer_caseless_compare(CONST_BUF_LEN(ds->key), CONST_STR_LEN("Range")))) { if (NULL != array_get_element(con->request.headers, CONST_STR_LEN("Range"))) { /* duplicate Range header */ TRACE("%s", "Range: header is duplicate (Status: 400)"); con->http_status = 400; con->keep_alive = 0; return 0; } } if (NULL == (hdr = (data_string *)array_get_unused_element(con->request.headers, TYPE_STRING))) { hdr = data_string_init(); } buffer_copy_string_buffer(hdr->key, ds->key); buffer_copy_string_buffer(hdr->value, ds->value); array_insert_unique(con->request.headers, (data_unset *)hdr); } con->header_len = i; /* do some post-processing */ if (con->request.http_version == HTTP_VERSION_1_1) { if (keep_alive_set != HTTP_CONNECTION_CLOSE) { /* no Connection-Header sent */ /* HTTP/1.1 -> keep-alive default TRUE */ con->keep_alive = 1; } else { con->keep_alive = 0; } /* RFC 2616, 14.23 */ if (buffer_is_empty(con->request.http_host)) { con->http_status = 400; con->response.keep_alive = 0; con->keep_alive = 0; if (srv->srvconf.log_request_header_on_error) { log_error_write(srv, __FILE__, __LINE__, "s", "HTTP/1.1 but Host missing -> 400"); log_error_write(srv, __FILE__, __LINE__, "Sb", "request-header:\n", con->request.request); } return 0; } } else { if (keep_alive_set == HTTP_CONNECTION_KEEPALIVE) { /* no Connection-Header sent */ /* HTTP/1.0 -> keep-alive default FALSE */ con->keep_alive = 1; } else { con->keep_alive = 0; } } switch(con->request.http_method) { case HTTP_METHOD_GET: case HTTP_METHOD_HEAD: /* content-length is forbidden for those */ if (con->request.content_length != -1) { /* content-length is missing */ if (srv->srvconf.log_request_header_on_error) { ERROR("GET/HEAD with content-length: %d", 400); } con->keep_alive = 0; con->http_status = 400; return 0; } break; case HTTP_METHOD_POST: /* content-length is required for them */ if (con->request.content_length == -1) { /* content-length is missing */ if (srv->srvconf.log_request_header_on_error) { log_error_write(srv, __FILE__, __LINE__, "s", "POST-request, but content-length missing -> 411"); } con->keep_alive = 0; con->http_status = 411; return 0; } break; default: /* the may have a content-length */ break; } /* check if we have read post data */ if (con->request.content_length != -1) { /* divide by 1024 as srvconf.max_request_size is in kBytes */ if (srv->srvconf.max_request_size != 0 && ((size_t)(con->request.content_length >> 10)) > srv->srvconf.max_request_size) { /* the request body itself is larger then * our our max_request_size */ con->http_status = 413; con->keep_alive = 0; log_error_write(srv, __FILE__, __LINE__, "sos", "request-size too long:", con->request.content_length, "-> 413"); return 0; } } return 0; }
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/lighttpd_2785-2786.c
manybugs_data_67
/* Generated by re2c 0.13.5 on Sun Jan 1 17:47:27 2012 */ #line 1 "Zend/zend_language_scanner.l" /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2012 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Marcus Boerger <[email protected]> | | Nuno Lopes <[email protected]> | | Scott MacVicar <[email protected]> | | Flex version authors: | | Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #if 0 # define YYDEBUG(s, c) printf("state: %d char: %c\n", s, c) #else # define YYDEBUG(s, c) #endif #include "zend_language_scanner_defs.h" #include <errno.h> #include "zend.h" #include "zend_alloc.h" #include <zend_language_parser.h> #include "zend_compile.h" #include "zend_language_scanner.h" #include "zend_highlight.h" #include "zend_constants.h" #include "zend_variables.h" #include "zend_operators.h" #include "zend_API.h" #include "zend_strtod.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "tsrm_config_common.h" #define YYCTYPE unsigned char #define YYFILL(n) { if ((YYCURSOR + n) >= (YYLIMIT + ZEND_MMAP_AHEAD)) { return 0; } } #define YYCURSOR SCNG(yy_cursor) #define YYLIMIT SCNG(yy_limit) #define YYMARKER SCNG(yy_marker) #define YYGETCONDITION() SCNG(yy_state) #define YYSETCONDITION(s) SCNG(yy_state) = s #define STATE(name) yyc##name /* emulate flex constructs */ #define BEGIN(state) YYSETCONDITION(STATE(state)) #define YYSTATE YYGETCONDITION() #define yytext ((char*)SCNG(yy_text)) #define yyleng SCNG(yy_leng) #define yyless(x) do { YYCURSOR = (unsigned char*)yytext + x; \ yyleng = (unsigned int)x; } while(0) #define yymore() goto yymore_restart /* perform sanity check. If this message is triggered you should increase the ZEND_MMAP_AHEAD value in the zend_streams.h file */ #define YYMAXFILL 16 #if ZEND_MMAP_AHEAD < YYMAXFILL # error ZEND_MMAP_AHEAD should be greater than or equal to YYMAXFILL #endif #ifdef HAVE_STDARG_H # include <stdarg.h> #endif #ifdef HAVE_UNISTD_H # include <unistd.h> #endif /* Globals Macros */ #define SCNG LANG_SCNG #ifdef ZTS ZEND_API ts_rsrc_id language_scanner_globals_id; #else ZEND_API zend_php_scanner_globals language_scanner_globals; #endif #define HANDLE_NEWLINES(s, l) \ do { \ char *p = (s), *boundary = p+(l); \ \ while (p<boundary) { \ if (*p == '\n' || (*p == '\r' && (*(p+1) != '\n'))) { \ CG(zend_lineno)++; \ } \ p++; \ } \ } while (0) #define HANDLE_NEWLINE(c) \ { \ if (c == '\n' || c == '\r') { \ CG(zend_lineno)++; \ } \ } /* To save initial string length after scanning to first variable, CG(doc_comment_len) can be reused */ #define SET_DOUBLE_QUOTES_SCANNED_LENGTH(len) CG(doc_comment_len) = (len) #define GET_DOUBLE_QUOTES_SCANNED_LENGTH() CG(doc_comment_len) #define IS_LABEL_START(c) (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z') || (c) == '_' || (c) >= 0x7F) #define ZEND_IS_OCT(c) ((c)>='0' && (c)<='7') #define ZEND_IS_HEX(c) (((c)>='0' && (c)<='9') || ((c)>='a' && (c)<='f') || ((c)>='A' && (c)<='F')) BEGIN_EXTERN_C() static size_t encoding_filter_script_to_internal(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) { const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding(TSRMLS_C); assert(internal_encoding && zend_multibyte_check_lexer_compatibility(internal_encoding)); return zend_multibyte_encoding_converter(to, to_length, from, from_length, internal_encoding, LANG_SCNG(script_encoding) TSRMLS_CC); } static size_t encoding_filter_script_to_intermediate(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) { return zend_multibyte_encoding_converter(to, to_length, from, from_length, zend_multibyte_encoding_utf8, LANG_SCNG(script_encoding) TSRMLS_CC); } static size_t encoding_filter_intermediate_to_script(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) { return zend_multibyte_encoding_converter(to, to_length, from, from_length, LANG_SCNG(script_encoding), zend_multibyte_encoding_utf8 TSRMLS_CC); } static size_t encoding_filter_intermediate_to_internal(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) { const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding(TSRMLS_C); assert(internal_encoding && zend_multibyte_check_lexer_compatibility(internal_encoding)); return zend_multibyte_encoding_converter(to, to_length, from, from_length, internal_encoding, zend_multibyte_encoding_utf8 TSRMLS_CC); } static void _yy_push_state(int new_state TSRMLS_DC) { zend_stack_push(&SCNG(state_stack), (void *) &YYGETCONDITION(), sizeof(int)); YYSETCONDITION(new_state); } #define yy_push_state(state_and_tsrm) _yy_push_state(yyc##state_and_tsrm) static void yy_pop_state(TSRMLS_D) { int *stack_state; zend_stack_top(&SCNG(state_stack), (void **) &stack_state); YYSETCONDITION(*stack_state); zend_stack_del_top(&SCNG(state_stack)); } static void yy_scan_buffer(char *str, unsigned int len TSRMLS_DC) { YYCURSOR = (YYCTYPE*)str; YYLIMIT = YYCURSOR + len; if (!SCNG(yy_start)) { SCNG(yy_start) = YYCURSOR; } } void startup_scanner(TSRMLS_D) { CG(parse_error) = 0; CG(heredoc) = NULL; CG(heredoc_len) = 0; CG(doc_comment) = NULL; CG(doc_comment_len) = 0; zend_stack_init(&SCNG(state_stack)); } void shutdown_scanner(TSRMLS_D) { if (CG(heredoc)) { efree(CG(heredoc)); CG(heredoc_len)=0; } CG(parse_error) = 0; zend_stack_destroy(&SCNG(state_stack)); RESET_DOC_COMMENT(); } ZEND_API void zend_save_lexical_state(zend_lex_state *lex_state TSRMLS_DC) { lex_state->yy_leng = SCNG(yy_leng); lex_state->yy_start = SCNG(yy_start); lex_state->yy_text = SCNG(yy_text); lex_state->yy_cursor = SCNG(yy_cursor); lex_state->yy_marker = SCNG(yy_marker); lex_state->yy_limit = SCNG(yy_limit); lex_state->state_stack = SCNG(state_stack); zend_stack_init(&SCNG(state_stack)); lex_state->in = SCNG(yy_in); lex_state->yy_state = YYSTATE; lex_state->filename = zend_get_compiled_filename(TSRMLS_C); lex_state->lineno = CG(zend_lineno); lex_state->script_org = SCNG(script_org); lex_state->script_org_size = SCNG(script_org_size); lex_state->script_filtered = SCNG(script_filtered); lex_state->script_filtered_size = SCNG(script_filtered_size); lex_state->input_filter = SCNG(input_filter); lex_state->output_filter = SCNG(output_filter); lex_state->script_encoding = SCNG(script_encoding); } ZEND_API void zend_restore_lexical_state(zend_lex_state *lex_state TSRMLS_DC) { SCNG(yy_leng) = lex_state->yy_leng; SCNG(yy_start) = lex_state->yy_start; SCNG(yy_text) = lex_state->yy_text; SCNG(yy_cursor) = lex_state->yy_cursor; SCNG(yy_marker) = lex_state->yy_marker; SCNG(yy_limit) = lex_state->yy_limit; zend_stack_destroy(&SCNG(state_stack)); SCNG(state_stack) = lex_state->state_stack; SCNG(yy_in) = lex_state->in; YYSETCONDITION(lex_state->yy_state); CG(zend_lineno) = lex_state->lineno; zend_restore_compiled_filename(lex_state->filename TSRMLS_CC); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } SCNG(script_org) = lex_state->script_org; SCNG(script_org_size) = lex_state->script_org_size; SCNG(script_filtered) = lex_state->script_filtered; SCNG(script_filtered_size) = lex_state->script_filtered_size; SCNG(input_filter) = lex_state->input_filter; SCNG(output_filter) = lex_state->output_filter; SCNG(script_encoding) = lex_state->script_encoding; if (CG(heredoc)) { efree(CG(heredoc)); CG(heredoc) = NULL; CG(heredoc_len) = 0; } } ZEND_API void zend_destroy_file_handle(zend_file_handle *file_handle TSRMLS_DC) { zend_llist_del_element(&CG(open_files), file_handle, (int (*)(void *, void *)) zend_compare_file_handles); /* zend_file_handle_dtor() operates on the copy, so we have to NULLify the original here */ file_handle->opened_path = NULL; if (file_handle->free_filename) { file_handle->filename = NULL; } } #define BOM_UTF32_BE "\x00\x00\xfe\xff" #define BOM_UTF32_LE "\xff\xfe\x00\x00" #define BOM_UTF16_BE "\xfe\xff" #define BOM_UTF16_LE "\xff\xfe" #define BOM_UTF8 "\xef\xbb\xbf" static const zend_encoding *zend_multibyte_detect_utf_encoding(const unsigned char *script, size_t script_size TSRMLS_DC) { const unsigned char *p; int wchar_size = 2; int le = 0; /* utf-16 or utf-32? */ p = script; while ((p-script) < script_size) { p = memchr(p, 0, script_size-(p-script)-2); if (!p) { break; } if (*(p+1) == '\0' && *(p+2) == '\0') { wchar_size = 4; break; } /* searching for UTF-32 specific byte orders, so this will do */ p += 4; } /* BE or LE? */ p = script; while ((p-script) < script_size) { if (*p == '\0' && *(p+wchar_size-1) != '\0') { /* BE */ le = 0; break; } else if (*p != '\0' && *(p+wchar_size-1) == '\0') { /* LE* */ le = 1; break; } p += wchar_size; } if (wchar_size == 2) { return le ? zend_multibyte_encoding_utf16le : zend_multibyte_encoding_utf16be; } else { return le ? zend_multibyte_encoding_utf32le : zend_multibyte_encoding_utf32be; } return NULL; } static const zend_encoding* zend_multibyte_detect_unicode(TSRMLS_D) { const zend_encoding *script_encoding = NULL; int bom_size; unsigned char *pos1, *pos2; if (LANG_SCNG(script_org_size) < sizeof(BOM_UTF32_LE)-1) { return NULL; } /* check out BOM */ if (!memcmp(LANG_SCNG(script_org), BOM_UTF32_BE, sizeof(BOM_UTF32_BE)-1)) { script_encoding = zend_multibyte_encoding_utf32be; bom_size = sizeof(BOM_UTF32_BE)-1; } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF32_LE, sizeof(BOM_UTF32_LE)-1)) { script_encoding = zend_multibyte_encoding_utf32le; bom_size = sizeof(BOM_UTF32_LE)-1; } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF16_BE, sizeof(BOM_UTF16_BE)-1)) { script_encoding = zend_multibyte_encoding_utf16be; bom_size = sizeof(BOM_UTF16_BE)-1; } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF16_LE, sizeof(BOM_UTF16_LE)-1)) { script_encoding = zend_multibyte_encoding_utf16le; bom_size = sizeof(BOM_UTF16_LE)-1; } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF8, sizeof(BOM_UTF8)-1)) { script_encoding = zend_multibyte_encoding_utf8; bom_size = sizeof(BOM_UTF8)-1; } if (script_encoding) { /* remove BOM */ LANG_SCNG(script_org) += bom_size; LANG_SCNG(script_org_size) -= bom_size; return script_encoding; } /* script contains NULL bytes -> auto-detection */ if ((pos1 = memchr(LANG_SCNG(script_org), 0, LANG_SCNG(script_org_size)))) { /* check if the NULL byte is after the __HALT_COMPILER(); */ pos2 = LANG_SCNG(script_org); while (pos1 - pos2 >= sizeof("__HALT_COMPILER();")-1) { pos2 = memchr(pos2, '_', pos1 - pos2); if (!pos2) break; pos2++; if (strncasecmp((char*)pos2, "_HALT_COMPILER", sizeof("_HALT_COMPILER")-1) == 0) { pos2 += sizeof("_HALT_COMPILER")-1; while (*pos2 == ' ' || *pos2 == '\t' || *pos2 == '\r' || *pos2 == '\n') { pos2++; } if (*pos2 == '(') { pos2++; while (*pos2 == ' ' || *pos2 == '\t' || *pos2 == '\r' || *pos2 == '\n') { pos2++; } if (*pos2 == ')') { pos2++; while (*pos2 == ' ' || *pos2 == '\t' || *pos2 == '\r' || *pos2 == '\n') { pos2++; } if (*pos2 == ';') { return NULL; } } } } } /* make best effort if BOM is missing */ return zend_multibyte_detect_utf_encoding(LANG_SCNG(script_org), LANG_SCNG(script_org_size) TSRMLS_CC); } return NULL; } static const zend_encoding* zend_multibyte_find_script_encoding(TSRMLS_D) { const zend_encoding *script_encoding; if (CG(detect_unicode)) { /* check out bom(byte order mark) and see if containing wchars */ script_encoding = zend_multibyte_detect_unicode(TSRMLS_C); if (script_encoding != NULL) { /* bom or wchar detection is prior to 'script_encoding' option */ return script_encoding; } } /* if no script_encoding specified, just leave alone */ if (!CG(script_encoding_list) || !CG(script_encoding_list_size)) { return NULL; } /* if multiple encodings specified, detect automagically */ if (CG(script_encoding_list_size) > 1) { return zend_multibyte_encoding_detector(LANG_SCNG(script_org), LANG_SCNG(script_org_size), CG(script_encoding_list), CG(script_encoding_list_size) TSRMLS_CC); } return CG(script_encoding_list)[0]; } ZEND_API int zend_multibyte_set_filter(const zend_encoding *onetime_encoding TSRMLS_DC) { const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding(TSRMLS_C); const zend_encoding *script_encoding = onetime_encoding ? onetime_encoding: zend_multibyte_find_script_encoding(TSRMLS_C); if (!script_encoding) { return FAILURE; } /* judge input/output filter */ LANG_SCNG(script_encoding) = script_encoding; LANG_SCNG(input_filter) = NULL; LANG_SCNG(output_filter) = NULL; if (!internal_encoding || LANG_SCNG(script_encoding) == internal_encoding) { if (!zend_multibyte_check_lexer_compatibility(LANG_SCNG(script_encoding))) { /* and if not, work around w/ script_encoding -> utf-8 -> script_encoding conversion */ LANG_SCNG(input_filter) = encoding_filter_script_to_intermediate; LANG_SCNG(output_filter) = encoding_filter_intermediate_to_script; } else { LANG_SCNG(input_filter) = NULL; LANG_SCNG(output_filter) = NULL; } return SUCCESS; } if (zend_multibyte_check_lexer_compatibility(internal_encoding)) { LANG_SCNG(input_filter) = encoding_filter_script_to_internal; LANG_SCNG(output_filter) = NULL; } else if (zend_multibyte_check_lexer_compatibility(LANG_SCNG(script_encoding))) { LANG_SCNG(input_filter) = NULL; LANG_SCNG(output_filter) = encoding_filter_script_to_internal; } else { /* both script and internal encodings are incompatible w/ flex */ LANG_SCNG(input_filter) = encoding_filter_script_to_intermediate; LANG_SCNG(output_filter) = encoding_filter_intermediate_to_internal; } return 0; } ZEND_API int open_file_for_scanning(zend_file_handle *file_handle TSRMLS_DC) { const char *file_path = NULL; char *buf; size_t size, offset = 0; /* The shebang line was read, get the current position to obtain the buffer start */ if (CG(start_lineno) == 2 && file_handle->type == ZEND_HANDLE_FP && file_handle->handle.fp) { if ((offset = ftell(file_handle->handle.fp)) == -1) { offset = 0; } } if (zend_stream_fixup(file_handle, &buf, &size TSRMLS_CC) == FAILURE) { return FAILURE; } zend_llist_add_element(&CG(open_files), file_handle); if (file_handle->handle.stream.handle >= (void*)file_handle && file_handle->handle.stream.handle <= (void*)(file_handle+1)) { zend_file_handle *fh = (zend_file_handle*)zend_llist_get_last(&CG(open_files)); size_t diff = (char*)file_handle->handle.stream.handle - (char*)file_handle; fh->handle.stream.handle = (void*)(((char*)fh) + diff); file_handle->handle.stream.handle = fh->handle.stream.handle; } /* Reset the scanner for scanning the new file */ SCNG(yy_in) = file_handle; SCNG(yy_start) = NULL; if (size != -1) { if (CG(multibyte)) { SCNG(script_org) = (unsigned char*)buf; SCNG(script_org_size) = size; SCNG(script_filtered) = NULL; zend_multibyte_set_filter(NULL TSRMLS_CC); if (SCNG(input_filter)) { if ((size_t)-1 == SCNG(input_filter)(&SCNG(script_filtered), &SCNG(script_filtered_size), SCNG(script_org), SCNG(script_org_size) TSRMLS_CC)) { zend_error_noreturn(E_COMPILE_ERROR, "Could not convert the script from the detected " "encoding \"%s\" to a compatible encoding", zend_multibyte_get_encoding_name(LANG_SCNG(script_encoding))); } buf = (char*)SCNG(script_filtered); size = SCNG(script_filtered_size); } } SCNG(yy_start) = (unsigned char *)buf - offset; yy_scan_buffer(buf, size TSRMLS_CC); } else { zend_error_noreturn(E_COMPILE_ERROR, "zend_stream_mmap() failed"); } BEGIN(INITIAL); if (file_handle->opened_path) { file_path = file_handle->opened_path; } else { file_path = file_handle->filename; } zend_set_compiled_filename(file_path TSRMLS_CC); if (CG(start_lineno)) { CG(zend_lineno) = CG(start_lineno); CG(start_lineno) = 0; } else { CG(zend_lineno) = 1; } CG(increment_lineno) = 0; return SUCCESS; } END_EXTERN_C() ZEND_API zend_op_array *compile_file(zend_file_handle *file_handle, int type TSRMLS_DC) { zend_lex_state original_lex_state; zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array)); zend_op_array *original_active_op_array = CG(active_op_array); zend_op_array *retval=NULL; int compiler_result; zend_bool compilation_successful=0; znode retval_znode; zend_bool original_in_compilation = CG(in_compilation); retval_znode.op_type = IS_CONST; retval_znode.u.constant.type = IS_LONG; retval_znode.u.constant.value.lval = 1; Z_UNSET_ISREF(retval_znode.u.constant); Z_SET_REFCOUNT(retval_znode.u.constant, 1); zend_save_lexical_state(&original_lex_state TSRMLS_CC); retval = op_array; /* success oriented */ if (open_file_for_scanning(file_handle TSRMLS_CC)==FAILURE) { if (type==ZEND_REQUIRE) { zend_message_dispatcher(ZMSG_FAILED_REQUIRE_FOPEN, file_handle->filename TSRMLS_CC); zend_bailout(); } else { zend_message_dispatcher(ZMSG_FAILED_INCLUDE_FOPEN, file_handle->filename TSRMLS_CC); } compilation_successful=0; } else { init_op_array(op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(in_compilation) = 1; CG(active_op_array) = op_array; zend_init_compiler_context(TSRMLS_C); compiler_result = zendparse(TSRMLS_C); zend_do_return(&retval_znode, 0 TSRMLS_CC); CG(in_compilation) = original_in_compilation; if (compiler_result==1) { /* parser error */ zend_bailout(); } compilation_successful=1; } if (retval) { CG(active_op_array) = original_active_op_array; if (compilation_successful) { pass_two(op_array TSRMLS_CC); zend_release_labels(TSRMLS_C); } else { efree(op_array); retval = NULL; } } zend_restore_lexical_state(&original_lex_state TSRMLS_CC); return retval; } zend_op_array *compile_filename(int type, zval *filename TSRMLS_DC) { zend_file_handle file_handle; zval tmp; zend_op_array *retval; char *opened_path = NULL; if (filename->type != IS_STRING) { tmp = *filename; zval_copy_ctor(&tmp); convert_to_string(&tmp); filename = &tmp; } file_handle.filename = filename->value.str.val; file_handle.free_filename = 0; file_handle.type = ZEND_HANDLE_FILENAME; file_handle.opened_path = NULL; file_handle.handle.fp = NULL; retval = zend_compile_file(&file_handle, type TSRMLS_CC); if (retval && file_handle.handle.stream.handle) { int dummy = 1; if (!file_handle.opened_path) { file_handle.opened_path = opened_path = estrndup(filename->value.str.val, filename->value.str.len); } zend_hash_add(&EG(included_files), file_handle.opened_path, strlen(file_handle.opened_path)+1, (void *)&dummy, sizeof(int), NULL); if (opened_path) { efree(opened_path); } } zend_destroy_file_handle(&file_handle TSRMLS_CC); if (filename==&tmp) { zval_dtor(&tmp); } return retval; } ZEND_API int zend_prepare_string_for_scanning(zval *str, char *filename TSRMLS_DC) { char *buf; size_t size; /* enforce two trailing NULLs for flex... */ if (IS_INTERNED(str->value.str.val)) { char *tmp = safe_emalloc(1, str->value.str.len, ZEND_MMAP_AHEAD); memcpy(tmp, str->value.str.val, str->value.str.len + ZEND_MMAP_AHEAD); str->value.str.val = tmp; } else { str->value.str.val = safe_erealloc(str->value.str.val, 1, str->value.str.len, ZEND_MMAP_AHEAD); } memset(str->value.str.val + str->value.str.len, 0, ZEND_MMAP_AHEAD); SCNG(yy_in) = NULL; SCNG(yy_start) = NULL; buf = str->value.str.val; size = str->value.str.len; if (CG(multibyte)) { SCNG(script_org) = (unsigned char*)buf; SCNG(script_org_size) = size; SCNG(script_filtered) = NULL; zend_multibyte_set_filter(zend_multibyte_get_internal_encoding(TSRMLS_C) TSRMLS_CC); if (SCNG(input_filter)) { if ((size_t)-1 == SCNG(input_filter)(&SCNG(script_filtered), &SCNG(script_filtered_size), SCNG(script_org), SCNG(script_org_size) TSRMLS_CC)) { zend_error_noreturn(E_COMPILE_ERROR, "Could not convert the script from the detected " "encoding \"%s\" to a compatible encoding", zend_multibyte_get_encoding_name(LANG_SCNG(script_encoding))); } buf = (char*)SCNG(script_filtered); size = SCNG(script_filtered_size); } } yy_scan_buffer(buf, size TSRMLS_CC); zend_set_compiled_filename(filename TSRMLS_CC); CG(zend_lineno) = 1; CG(increment_lineno) = 0; return SUCCESS; } ZEND_API size_t zend_get_scanned_file_offset(TSRMLS_D) { size_t offset = SCNG(yy_cursor) - SCNG(yy_start); if (SCNG(input_filter)) { size_t original_offset = offset, length = 0; do { unsigned char *p = NULL; if ((size_t)-1 == SCNG(input_filter)(&p, &length, SCNG(script_org), offset TSRMLS_CC)) { return (size_t)-1; } efree(p); if (length > original_offset) { offset--; } else if (length < original_offset) { offset++; } } while (original_offset != length); } return offset; } zend_op_array *compile_string(zval *source_string, char *filename TSRMLS_DC) { zend_lex_state original_lex_state; zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array)); zend_op_array *original_active_op_array = CG(active_op_array); zend_op_array *retval; zval tmp; int compiler_result; zend_bool original_in_compilation = CG(in_compilation); if (source_string->value.str.len==0) { efree(op_array); return NULL; } CG(in_compilation) = 1; tmp = *source_string; zval_copy_ctor(&tmp); convert_to_string(&tmp); source_string = &tmp; zend_save_lexical_state(&original_lex_state TSRMLS_CC); if (zend_prepare_string_for_scanning(source_string, filename TSRMLS_CC)==FAILURE) { efree(op_array); retval = NULL; } else { zend_bool orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(op_array, ZEND_EVAL_CODE, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; CG(active_op_array) = op_array; zend_init_compiler_context(TSRMLS_C); BEGIN(ST_IN_SCRIPTING); compiler_result = zendparse(TSRMLS_C); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } if (compiler_result==1) { CG(active_op_array) = original_active_op_array; CG(unclean_shutdown)=1; destroy_op_array(op_array TSRMLS_CC); efree(op_array); retval = NULL; } else { zend_do_return(NULL, 0 TSRMLS_CC); CG(active_op_array) = original_active_op_array; pass_two(op_array TSRMLS_CC); zend_release_labels(TSRMLS_C); retval = op_array; } } zend_restore_lexical_state(&original_lex_state TSRMLS_CC); zval_dtor(&tmp); CG(in_compilation) = original_in_compilation; return retval; } BEGIN_EXTERN_C() int highlight_file(char *filename, zend_syntax_highlighter_ini *syntax_highlighter_ini TSRMLS_DC) { zend_lex_state original_lex_state; zend_file_handle file_handle; file_handle.type = ZEND_HANDLE_FILENAME; file_handle.filename = filename; file_handle.free_filename = 0; file_handle.opened_path = NULL; zend_save_lexical_state(&original_lex_state TSRMLS_CC); if (open_file_for_scanning(&file_handle TSRMLS_CC)==FAILURE) { zend_message_dispatcher(ZMSG_FAILED_HIGHLIGHT_FOPEN, filename TSRMLS_CC); zend_restore_lexical_state(&original_lex_state TSRMLS_CC); return FAILURE; } zend_highlight(syntax_highlighter_ini TSRMLS_CC); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } zend_destroy_file_handle(&file_handle TSRMLS_CC); zend_restore_lexical_state(&original_lex_state TSRMLS_CC); return SUCCESS; } int highlight_string(zval *str, zend_syntax_highlighter_ini *syntax_highlighter_ini, char *str_name TSRMLS_DC) { zend_lex_state original_lex_state; zval tmp = *str; str = &tmp; zval_copy_ctor(str); zend_save_lexical_state(&original_lex_state TSRMLS_CC); if (zend_prepare_string_for_scanning(str, str_name TSRMLS_CC)==FAILURE) { zend_restore_lexical_state(&original_lex_state TSRMLS_CC); return FAILURE; } BEGIN(INITIAL); zend_highlight(syntax_highlighter_ini TSRMLS_CC); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } zend_restore_lexical_state(&original_lex_state TSRMLS_CC); zval_dtor(str); return SUCCESS; } ZEND_API void zend_multibyte_yyinput_again(zend_encoding_filter old_input_filter, const zend_encoding *old_encoding TSRMLS_DC) { size_t length; unsigned char *new_yy_start; /* convert and set */ if (!SCNG(input_filter)) { if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } SCNG(script_filtered_size) = 0; length = SCNG(script_org_size); new_yy_start = SCNG(script_org); } else { if ((size_t)-1 == SCNG(input_filter)(&new_yy_start, &length, SCNG(script_org), SCNG(script_org_size) TSRMLS_CC)) { zend_error_noreturn(E_COMPILE_ERROR, "Could not convert the script from the detected " "encoding \"%s\" to a compatible encoding", zend_multibyte_get_encoding_name(LANG_SCNG(script_encoding))); } SCNG(script_filtered) = new_yy_start; SCNG(script_filtered_size) = length; } SCNG(yy_cursor) = new_yy_start + (SCNG(yy_cursor) - SCNG(yy_start)); SCNG(yy_marker) = new_yy_start + (SCNG(yy_marker) - SCNG(yy_start)); SCNG(yy_text) = new_yy_start + (SCNG(yy_text) - SCNG(yy_start)); SCNG(yy_limit) = new_yy_start + (SCNG(yy_limit) - SCNG(yy_start)); SCNG(yy_start) = new_yy_start; } # define zend_copy_value(zendlval, yytext, yyleng) \ if (SCNG(output_filter)) { \ size_t sz = 0; \ SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)yytext, (size_t)yyleng TSRMLS_CC); \ zendlval->value.str.len = sz; \ } else { \ zendlval->value.str.val = (char *) estrndup(yytext, yyleng); \ zendlval->value.str.len = yyleng; \ } static void zend_scan_escape_string(zval *zendlval, char *str, int len, char quote_type TSRMLS_DC) { register char *s, *t; char *end; ZVAL_STRINGL(zendlval, str, len, 1); /* convert escape sequences */ s = t = zendlval->value.str.val; end = s+zendlval->value.str.len; while (s<end) { if (*s=='\\') { s++; if (s >= end) { *t++ = '\\'; break; } switch(*s) { case 'n': *t++ = '\n'; zendlval->value.str.len--; break; case 'r': *t++ = '\r'; zendlval->value.str.len--; break; case 't': *t++ = '\t'; zendlval->value.str.len--; break; case 'f': *t++ = '\f'; zendlval->value.str.len--; break; case 'v': *t++ = '\v'; zendlval->value.str.len--; break; case 'e': *t++ = '\e'; zendlval->value.str.len--; break; case '"': case '`': if (*s != quote_type) { *t++ = '\\'; *t++ = *s; break; } case '\\': case '$': *t++ = *s; zendlval->value.str.len--; break; case 'x': case 'X': if (ZEND_IS_HEX(*(s+1))) { char hex_buf[3] = { 0, 0, 0 }; zendlval->value.str.len--; /* for the 'x' */ hex_buf[0] = *(++s); zendlval->value.str.len--; if (ZEND_IS_HEX(*(s+1))) { hex_buf[1] = *(++s); zendlval->value.str.len--; } *t++ = (char) strtol(hex_buf, NULL, 16); } else { *t++ = '\\'; *t++ = *s; } break; default: /* check for an octal */ if (ZEND_IS_OCT(*s)) { char octal_buf[4] = { 0, 0, 0, 0 }; octal_buf[0] = *s; zendlval->value.str.len--; if (ZEND_IS_OCT(*(s+1))) { octal_buf[1] = *(++s); zendlval->value.str.len--; if (ZEND_IS_OCT(*(s+1))) { octal_buf[2] = *(++s); zendlval->value.str.len--; } } *t++ = (char) strtol(octal_buf, NULL, 8); } else { *t++ = '\\'; *t++ = *s; } break; } } else { *t++ = *s; } if (*s == '\n' || (*s == '\r' && (*(s+1) != '\n'))) { CG(zend_lineno)++; } s++; } *t = 0; if (SCNG(output_filter)) { size_t sz = 0; s = zendlval->value.str.val; SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)s, (size_t)zendlval->value.str.len TSRMLS_CC); zendlval->value.str.len = sz; efree(s); } } int lex_scan(zval *zendlval TSRMLS_DC) { restart: SCNG(yy_text) = YYCURSOR; yymore_restart: #line 995 "Zend/zend_language_scanner.c" { YYCTYPE yych; unsigned int yyaccept = 0; if (YYGETCONDITION() < 5) { if (YYGETCONDITION() < 2) { if (YYGETCONDITION() < 1) { goto yyc_ST_IN_SCRIPTING; } else { goto yyc_ST_LOOKING_FOR_PROPERTY; } } else { if (YYGETCONDITION() < 3) { goto yyc_ST_BACKQUOTE; } else { if (YYGETCONDITION() < 4) { goto yyc_ST_DOUBLE_QUOTES; } else { goto yyc_ST_HEREDOC; } } } } else { if (YYGETCONDITION() < 7) { if (YYGETCONDITION() < 6) { goto yyc_ST_LOOKING_FOR_VARNAME; } else { goto yyc_ST_VAR_OFFSET; } } else { if (YYGETCONDITION() < 8) { goto yyc_INITIAL; } else { if (YYGETCONDITION() < 9) { goto yyc_ST_END_HEREDOC; } else { goto yyc_ST_NOWDOC; } } } } /* *********************************** */ yyc_INITIAL: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; YYDEBUG(0, *YYCURSOR); YYFILL(8); yych = *YYCURSOR; if (yych != '<') goto yy4; YYDEBUG(2, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '?') { if (yych == '%') goto yy7; if (yych >= '?') goto yy5; } else { if (yych <= 'S') { if (yych >= 'S') goto yy9; } else { if (yych == 's') goto yy9; } } yy3: YYDEBUG(3, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1775 "Zend/zend_language_scanner.l" { if (YYCURSOR > YYLIMIT) { return 0; } inline_char_handler: while (1) { YYCTYPE *ptr = memchr(YYCURSOR, '<', YYLIMIT - YYCURSOR); YYCURSOR = ptr ? ptr + 1 : YYLIMIT; if (YYCURSOR < YYLIMIT) { switch (*YYCURSOR) { case '?': if (CG(short_tags) || !strncasecmp((char*)YYCURSOR + 1, "php", 3) || (*(YYCURSOR + 1) == '=')) { /* Assume [ \t\n\r] follows "php" */ break; } continue; case '%': if (CG(asp_tags)) { break; } continue; case 's': case 'S': /* Probably NOT an opening PHP <script> tag, so don't end the HTML chunk yet * If it is, the PHP <script> tag rule checks for any HTML scanned before it */ YYCURSOR--; yymore(); default: continue; } YYCURSOR--; } break; } inline_html: yyleng = YYCURSOR - SCNG(yy_text); if (SCNG(output_filter)) { int readsize; size_t sz = 0; readsize = SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)yytext, (size_t)yyleng TSRMLS_CC); zendlval->value.str.len = sz; if (readsize < yyleng) { yyless(readsize); } } else { zendlval->value.str.val = (char *) estrndup(yytext, yyleng); zendlval->value.str.len = yyleng; } zendlval->type = IS_STRING; HANDLE_NEWLINES(yytext, yyleng); return T_INLINE_HTML; } #line 1154 "Zend/zend_language_scanner.c" yy4: YYDEBUG(4, *YYCURSOR); yych = *++YYCURSOR; goto yy3; yy5: YYDEBUG(5, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'O') { if (yych == '=') goto yy45; } else { if (yych <= 'P') goto yy47; if (yych == 'p') goto yy47; } yy6: YYDEBUG(6, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1763 "Zend/zend_language_scanner.l" { if (CG(short_tags)) { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG; } else { goto inline_char_handler; } } #line 1184 "Zend/zend_language_scanner.c" yy7: YYDEBUG(7, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '=') goto yy43; YYDEBUG(8, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1740 "Zend/zend_language_scanner.l" { if (CG(asp_tags)) { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG; } else { goto inline_char_handler; } } #line 1203 "Zend/zend_language_scanner.c" yy9: YYDEBUG(9, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy11; if (yych == 'c') goto yy11; yy10: YYDEBUG(10, *YYCURSOR); YYCURSOR = YYMARKER; if (yyaccept <= 0) { goto yy3; } else { goto yy6; } yy11: YYDEBUG(11, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy12; if (yych != 'r') goto yy10; yy12: YYDEBUG(12, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy13; if (yych != 'i') goto yy10; yy13: YYDEBUG(13, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy14; if (yych != 'p') goto yy10; yy14: YYDEBUG(14, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy15; if (yych != 't') goto yy10; yy15: YYDEBUG(15, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy10; if (yych == 'l') goto yy10; goto yy17; yy16: YYDEBUG(16, *YYCURSOR); ++YYCURSOR; YYFILL(8); yych = *YYCURSOR; yy17: YYDEBUG(17, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy16; } if (yych == 'L') goto yy18; if (yych != 'l') goto yy10; yy18: YYDEBUG(18, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy19; if (yych != 'a') goto yy10; yy19: YYDEBUG(19, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy20; if (yych != 'n') goto yy10; yy20: YYDEBUG(20, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy21; if (yych != 'g') goto yy10; yy21: YYDEBUG(21, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy22; if (yych != 'u') goto yy10; yy22: YYDEBUG(22, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy23; if (yych != 'a') goto yy10; yy23: YYDEBUG(23, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy24; if (yych != 'g') goto yy10; yy24: YYDEBUG(24, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy25; if (yych != 'e') goto yy10; yy25: YYDEBUG(25, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(26, *YYCURSOR); if (yych <= '\r') { if (yych <= 0x08) goto yy10; if (yych <= '\n') goto yy25; if (yych <= '\f') goto yy10; goto yy25; } else { if (yych <= ' ') { if (yych <= 0x1F) goto yy10; goto yy25; } else { if (yych != '=') goto yy10; } } yy27: YYDEBUG(27, *YYCURSOR); ++YYCURSOR; YYFILL(5); yych = *YYCURSOR; YYDEBUG(28, *YYCURSOR); if (yych <= '!') { if (yych <= '\f') { if (yych <= 0x08) goto yy10; if (yych <= '\n') goto yy27; goto yy10; } else { if (yych <= '\r') goto yy27; if (yych == ' ') goto yy27; goto yy10; } } else { if (yych <= 'O') { if (yych <= '"') goto yy30; if (yych == '\'') goto yy31; goto yy10; } else { if (yych <= 'P') goto yy29; if (yych != 'p') goto yy10; } } yy29: YYDEBUG(29, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy42; if (yych == 'h') goto yy42; goto yy10; yy30: YYDEBUG(30, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy39; if (yych == 'p') goto yy39; goto yy10; yy31: YYDEBUG(31, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy32; if (yych != 'p') goto yy10; yy32: YYDEBUG(32, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy33; if (yych != 'h') goto yy10; yy33: YYDEBUG(33, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy34; if (yych != 'p') goto yy10; yy34: YYDEBUG(34, *YYCURSOR); yych = *++YYCURSOR; if (yych != '\'') goto yy10; yy35: YYDEBUG(35, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(36, *YYCURSOR); if (yych <= '\r') { if (yych <= 0x08) goto yy10; if (yych <= '\n') goto yy35; if (yych <= '\f') goto yy10; goto yy35; } else { if (yych <= ' ') { if (yych <= 0x1F) goto yy10; goto yy35; } else { if (yych != '>') goto yy10; } } YYDEBUG(37, *YYCURSOR); ++YYCURSOR; YYDEBUG(38, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1700 "Zend/zend_language_scanner.l" { YYCTYPE *bracket = (YYCTYPE*)zend_memrchr(yytext, '<', yyleng - (sizeof("script language=php>") - 1)); if (bracket != SCNG(yy_text)) { /* Handle previously scanned HTML, as possible <script> tags found are assumed to not be PHP's */ YYCURSOR = bracket; goto inline_html; } HANDLE_NEWLINES(yytext, yyleng); zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG; } #line 1406 "Zend/zend_language_scanner.c" yy39: YYDEBUG(39, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy40; if (yych != 'h') goto yy10; yy40: YYDEBUG(40, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy41; if (yych != 'p') goto yy10; yy41: YYDEBUG(41, *YYCURSOR); yych = *++YYCURSOR; if (yych == '"') goto yy35; goto yy10; yy42: YYDEBUG(42, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy35; if (yych == 'p') goto yy35; goto yy10; yy43: YYDEBUG(43, *YYCURSOR); ++YYCURSOR; YYDEBUG(44, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1718 "Zend/zend_language_scanner.l" { if (CG(asp_tags)) { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG_WITH_ECHO; } else { goto inline_char_handler; } } #line 1445 "Zend/zend_language_scanner.c" yy45: YYDEBUG(45, *YYCURSOR); ++YYCURSOR; YYDEBUG(46, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1731 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG_WITH_ECHO; } #line 1459 "Zend/zend_language_scanner.c" yy47: YYDEBUG(47, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy48; if (yych != 'h') goto yy10; yy48: YYDEBUG(48, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy49; if (yych != 'p') goto yy10; yy49: YYDEBUG(49, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '\f') { if (yych <= 0x08) goto yy10; if (yych >= '\v') goto yy10; } else { if (yych <= '\r') goto yy52; if (yych != ' ') goto yy10; } yy50: YYDEBUG(50, *YYCURSOR); ++YYCURSOR; yy51: YYDEBUG(51, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1753 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; HANDLE_NEWLINE(yytext[yyleng-1]); BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG; } #line 1495 "Zend/zend_language_scanner.c" yy52: YYDEBUG(52, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '\n') goto yy50; goto yy51; } /* *********************************** */ yyc_ST_BACKQUOTE: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; YYDEBUG(53, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych <= '_') { if (yych != '$') goto yy60; } else { if (yych <= '`') goto yy58; if (yych == '{') goto yy57; goto yy60; } YYDEBUG(55, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '_') { if (yych <= '@') goto yy56; if (yych <= 'Z') goto yy63; if (yych >= '_') goto yy63; } else { if (yych <= 'z') { if (yych >= 'a') goto yy63; } else { if (yych <= '{') goto yy66; if (yych >= 0x7F) goto yy63; } } yy56: YYDEBUG(56, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2226 "Zend/zend_language_scanner.l" { if (YYCURSOR > YYLIMIT) { return 0; } if (yytext[0] == '\\' && YYCURSOR < YYLIMIT) { YYCURSOR++; } while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '`': break; case '$': if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { break; } continue; case '{': if (*YYCURSOR == '$') { break; } continue; case '\\': if (YYCURSOR < YYLIMIT) { YYCURSOR++; } /* fall through */ default: continue; } YYCURSOR--; break; } yyleng = YYCURSOR - SCNG(yy_text); zend_scan_escape_string(zendlval, yytext, yyleng, '`' TSRMLS_CC); return T_ENCAPSED_AND_WHITESPACE; } #line 1607 "Zend/zend_language_scanner.c" yy57: YYDEBUG(57, *YYCURSOR); yych = *++YYCURSOR; if (yych == '$') goto yy61; goto yy56; yy58: YYDEBUG(58, *YYCURSOR); ++YYCURSOR; YYDEBUG(59, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2170 "Zend/zend_language_scanner.l" { BEGIN(ST_IN_SCRIPTING); return '`'; } #line 1623 "Zend/zend_language_scanner.c" yy60: YYDEBUG(60, *YYCURSOR); yych = *++YYCURSOR; goto yy56; yy61: YYDEBUG(61, *YYCURSOR); ++YYCURSOR; YYDEBUG(62, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2157 "Zend/zend_language_scanner.l" { zendlval->value.lval = (long) '{'; yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); yyless(1); return T_CURLY_OPEN; } #line 1640 "Zend/zend_language_scanner.c" yy63: YYDEBUG(63, *YYCURSOR); yyaccept = 0; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(64, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy63; } if (yych == '-') goto yy68; if (yych == '[') goto yy70; yy65: YYDEBUG(65, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1857 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1662 "Zend/zend_language_scanner.c" yy66: YYDEBUG(66, *YYCURSOR); ++YYCURSOR; YYDEBUG(67, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1442 "Zend/zend_language_scanner.l" { yy_push_state(ST_LOOKING_FOR_VARNAME TSRMLS_CC); return T_DOLLAR_OPEN_CURLY_BRACES; } #line 1673 "Zend/zend_language_scanner.c" yy68: YYDEBUG(68, *YYCURSOR); yych = *++YYCURSOR; if (yych == '>') goto yy72; yy69: YYDEBUG(69, *YYCURSOR); YYCURSOR = YYMARKER; goto yy65; yy70: YYDEBUG(70, *YYCURSOR); ++YYCURSOR; YYDEBUG(71, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1849 "Zend/zend_language_scanner.l" { yyless(yyleng - 1); yy_push_state(ST_VAR_OFFSET TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1695 "Zend/zend_language_scanner.c" yy72: YYDEBUG(72, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy69; if (yych <= 'Z') goto yy73; if (yych <= '^') goto yy69; } else { if (yych <= '`') goto yy69; if (yych <= 'z') goto yy73; if (yych <= '~') goto yy69; } yy73: YYDEBUG(73, *YYCURSOR); ++YYCURSOR; YYDEBUG(74, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1839 "Zend/zend_language_scanner.l" { yyless(yyleng - 3); yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1721 "Zend/zend_language_scanner.c" } /* *********************************** */ yyc_ST_DOUBLE_QUOTES: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; YYDEBUG(75, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych <= '#') { if (yych == '"') goto yy80; goto yy82; } else { if (yych <= '$') goto yy77; if (yych == '{') goto yy79; goto yy82; } yy77: YYDEBUG(77, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '_') { if (yych <= '@') goto yy78; if (yych <= 'Z') goto yy85; if (yych >= '_') goto yy85; } else { if (yych <= 'z') { if (yych >= 'a') goto yy85; } else { if (yych <= '{') goto yy88; if (yych >= 0x7F) goto yy85; } } yy78: YYDEBUG(78, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2176 "Zend/zend_language_scanner.l" { if (GET_DOUBLE_QUOTES_SCANNED_LENGTH()) { YYCURSOR += GET_DOUBLE_QUOTES_SCANNED_LENGTH() - 1; SET_DOUBLE_QUOTES_SCANNED_LENGTH(0); goto double_quotes_scan_done; } if (YYCURSOR > YYLIMIT) { return 0; } if (yytext[0] == '\\' && YYCURSOR < YYLIMIT) { YYCURSOR++; } while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '"': break; case '$': if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { break; } continue; case '{': if (*YYCURSOR == '$') { break; } continue; case '\\': if (YYCURSOR < YYLIMIT) { YYCURSOR++; } /* fall through */ default: continue; } YYCURSOR--; break; } double_quotes_scan_done: yyleng = YYCURSOR - SCNG(yy_text); zend_scan_escape_string(zendlval, yytext, yyleng, '"' TSRMLS_CC); return T_ENCAPSED_AND_WHITESPACE; } #line 1838 "Zend/zend_language_scanner.c" yy79: YYDEBUG(79, *YYCURSOR); yych = *++YYCURSOR; if (yych == '$') goto yy83; goto yy78; yy80: YYDEBUG(80, *YYCURSOR); ++YYCURSOR; YYDEBUG(81, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2165 "Zend/zend_language_scanner.l" { BEGIN(ST_IN_SCRIPTING); return '"'; } #line 1854 "Zend/zend_language_scanner.c" yy82: YYDEBUG(82, *YYCURSOR); yych = *++YYCURSOR; goto yy78; yy83: YYDEBUG(83, *YYCURSOR); ++YYCURSOR; YYDEBUG(84, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2157 "Zend/zend_language_scanner.l" { zendlval->value.lval = (long) '{'; yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); yyless(1); return T_CURLY_OPEN; } #line 1871 "Zend/zend_language_scanner.c" yy85: YYDEBUG(85, *YYCURSOR); yyaccept = 0; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(86, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy85; } if (yych == '-') goto yy90; if (yych == '[') goto yy92; yy87: YYDEBUG(87, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1857 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1893 "Zend/zend_language_scanner.c" yy88: YYDEBUG(88, *YYCURSOR); ++YYCURSOR; YYDEBUG(89, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1442 "Zend/zend_language_scanner.l" { yy_push_state(ST_LOOKING_FOR_VARNAME TSRMLS_CC); return T_DOLLAR_OPEN_CURLY_BRACES; } #line 1904 "Zend/zend_language_scanner.c" yy90: YYDEBUG(90, *YYCURSOR); yych = *++YYCURSOR; if (yych == '>') goto yy94; yy91: YYDEBUG(91, *YYCURSOR); YYCURSOR = YYMARKER; goto yy87; yy92: YYDEBUG(92, *YYCURSOR); ++YYCURSOR; YYDEBUG(93, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1849 "Zend/zend_language_scanner.l" { yyless(yyleng - 1); yy_push_state(ST_VAR_OFFSET TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1926 "Zend/zend_language_scanner.c" yy94: YYDEBUG(94, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy91; if (yych <= 'Z') goto yy95; if (yych <= '^') goto yy91; } else { if (yych <= '`') goto yy91; if (yych <= 'z') goto yy95; if (yych <= '~') goto yy91; } yy95: YYDEBUG(95, *YYCURSOR); ++YYCURSOR; YYDEBUG(96, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1839 "Zend/zend_language_scanner.l" { yyless(yyleng - 3); yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1952 "Zend/zend_language_scanner.c" } /* *********************************** */ yyc_ST_END_HEREDOC: YYDEBUG(97, *YYCURSOR); YYFILL(1); yych = *YYCURSOR; YYDEBUG(99, *YYCURSOR); ++YYCURSOR; YYDEBUG(100, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2144 "Zend/zend_language_scanner.l" { YYCURSOR += CG(heredoc_len) - 1; yyleng = CG(heredoc_len); Z_STRVAL_P(zendlval) = CG(heredoc); Z_STRLEN_P(zendlval) = CG(heredoc_len); CG(heredoc) = NULL; CG(heredoc_len) = 0; BEGIN(ST_IN_SCRIPTING); return T_END_HEREDOC; } #line 1975 "Zend/zend_language_scanner.c" /* *********************************** */ yyc_ST_HEREDOC: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; YYDEBUG(101, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych == '$') goto yy103; if (yych == '{') goto yy105; goto yy106; yy103: YYDEBUG(103, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '_') { if (yych <= '@') goto yy104; if (yych <= 'Z') goto yy109; if (yych >= '_') goto yy109; } else { if (yych <= 'z') { if (yych >= 'a') goto yy109; } else { if (yych <= '{') goto yy112; if (yych >= 0x7F) goto yy109; } } yy104: YYDEBUG(104, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2268 "Zend/zend_language_scanner.l" { int newline = 0; if (YYCURSOR > YYLIMIT) { return 0; } YYCURSOR--; while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '\r': if (*YYCURSOR == '\n') { YYCURSOR++; } /* fall through */ case '\n': /* Check for ending label on the next line */ if (IS_LABEL_START(*YYCURSOR) && CG(heredoc_len) < YYLIMIT - YYCURSOR && !memcmp(YYCURSOR, CG(heredoc), CG(heredoc_len))) { YYCTYPE *end = YYCURSOR + CG(heredoc_len); if (*end == ';') { end++; } if (*end == '\n' || *end == '\r') { /* newline before label will be subtracted from returned text, but * yyleng/yytext will include it, for zend_highlight/strip, tokenizer, etc. */ if (YYCURSOR[-2] == '\r' && YYCURSOR[-1] == '\n') { newline = 2; /* Windows newline */ } else { newline = 1; } CG(increment_lineno) = 1; /* For newline before label */ BEGIN(ST_END_HEREDOC); goto heredoc_scan_done; } } continue; case '$': if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { break; } continue; case '{': if (*YYCURSOR == '$') { break; } continue; case '\\': if (YYCURSOR < YYLIMIT && *YYCURSOR != '\n' && *YYCURSOR != '\r') { YYCURSOR++; } /* fall through */ default: continue; } YYCURSOR--; break; } heredoc_scan_done: yyleng = YYCURSOR - SCNG(yy_text); zend_scan_escape_string(zendlval, yytext, yyleng - newline, 0 TSRMLS_CC); return T_ENCAPSED_AND_WHITESPACE; } #line 2108 "Zend/zend_language_scanner.c" yy105: YYDEBUG(105, *YYCURSOR); yych = *++YYCURSOR; if (yych == '$') goto yy107; goto yy104; yy106: YYDEBUG(106, *YYCURSOR); yych = *++YYCURSOR; goto yy104; yy107: YYDEBUG(107, *YYCURSOR); ++YYCURSOR; YYDEBUG(108, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2157 "Zend/zend_language_scanner.l" { zendlval->value.lval = (long) '{'; yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); yyless(1); return T_CURLY_OPEN; } #line 2130 "Zend/zend_language_scanner.c" yy109: YYDEBUG(109, *YYCURSOR); yyaccept = 0; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(110, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy109; } if (yych == '-') goto yy114; if (yych == '[') goto yy116; yy111: YYDEBUG(111, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1857 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 2152 "Zend/zend_language_scanner.c" yy112: YYDEBUG(112, *YYCURSOR); ++YYCURSOR; YYDEBUG(113, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1442 "Zend/zend_language_scanner.l" { yy_push_state(ST_LOOKING_FOR_VARNAME TSRMLS_CC); return T_DOLLAR_OPEN_CURLY_BRACES; } #line 2163 "Zend/zend_language_scanner.c" yy114: YYDEBUG(114, *YYCURSOR); yych = *++YYCURSOR; if (yych == '>') goto yy118; yy115: YYDEBUG(115, *YYCURSOR); YYCURSOR = YYMARKER; goto yy111; yy116: YYDEBUG(116, *YYCURSOR); ++YYCURSOR; YYDEBUG(117, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1849 "Zend/zend_language_scanner.l" { yyless(yyleng - 1); yy_push_state(ST_VAR_OFFSET TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 2185 "Zend/zend_language_scanner.c" yy118: YYDEBUG(118, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy115; if (yych <= 'Z') goto yy119; if (yych <= '^') goto yy115; } else { if (yych <= '`') goto yy115; if (yych <= 'z') goto yy119; if (yych <= '~') goto yy115; } yy119: YYDEBUG(119, *YYCURSOR); ++YYCURSOR; YYDEBUG(120, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1839 "Zend/zend_language_scanner.l" { yyless(yyleng - 3); yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 2211 "Zend/zend_language_scanner.c" } /* *********************************** */ yyc_ST_IN_SCRIPTING: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 64, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 60, 60, 44, 44, 44, 44, 44, 44, 44, 44, 0, 0, 0, 0, 0, 0, 0, 36, 36, 36, 36, 36, 36, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 4, 0, 36, 36, 36, 36, 36, 36, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, }; YYDEBUG(121, *YYCURSOR); YYFILL(16); yych = *YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case '\v': case '\f': case 0x0E: case 0x0F: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1A: case 0x1B: case 0x1C: case 0x1D: case 0x1E: case 0x1F: goto yy183; case '\t': case '\n': case '\r': case ' ': goto yy139; case '!': goto yy152; case '"': goto yy179; case '#': goto yy175; case '$': goto yy164; case '%': goto yy158; case '&': goto yy159; case '\'': goto yy177; case '(': goto yy146; case ')': case ',': case ';': case '@': case '[': case ']': case '~': goto yy165; case '*': goto yy155; case '+': goto yy151; case '-': goto yy137; case '.': goto yy157; case '/': goto yy156; case '0': goto yy171; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy173; case ':': goto yy141; case '<': goto yy153; case '=': goto yy149; case '>': goto yy154; case '?': goto yy166; case 'A': case 'a': goto yy132; case 'B': case 'b': goto yy134; case 'C': case 'c': goto yy127; case 'D': case 'd': goto yy125; case 'E': case 'e': goto yy123; case 'F': case 'f': goto yy126; case 'G': case 'g': goto yy135; case 'I': case 'i': goto yy130; case 'L': case 'l': goto yy150; case 'N': case 'n': goto yy144; case 'O': case 'o': goto yy162; case 'P': case 'p': goto yy136; case 'R': case 'r': goto yy128; case 'S': case 's': goto yy133; case 'T': case 't': goto yy129; case 'U': case 'u': goto yy147; case 'V': case 'v': goto yy145; case 'W': case 'w': goto yy131; case 'X': case 'x': goto yy163; case '\\': goto yy142; case '^': goto yy161; case '_': goto yy148; case '`': goto yy181; case '{': goto yy167; case '|': goto yy160; case '}': goto yy169; default: goto yy174; } yy123: YYDEBUG(123, *YYCURSOR); ++YYCURSOR; YYDEBUG(-1, yych); switch ((yych = *YYCURSOR)) { case 'C': case 'c': goto yy726; case 'L': case 'l': goto yy727; case 'M': case 'm': goto yy728; case 'N': case 'n': goto yy729; case 'V': case 'v': goto yy730; case 'X': case 'x': goto yy731; default: goto yy186; } yy124: YYDEBUG(124, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1880 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, yytext, yyleng); zendlval->type = IS_STRING; return T_STRING; } #line 2398 "Zend/zend_language_scanner.c" yy125: YYDEBUG(125, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= 'H') { if (yych == 'E') goto yy708; goto yy186; } else { if (yych <= 'I') goto yy709; if (yych <= 'N') goto yy186; goto yy710; } } else { if (yych <= 'h') { if (yych == 'e') goto yy708; goto yy186; } else { if (yych <= 'i') goto yy709; if (yych == 'o') goto yy710; goto yy186; } } yy126: YYDEBUG(126, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= 'N') { if (yych == 'I') goto yy687; goto yy186; } else { if (yych <= 'O') goto yy688; if (yych <= 'T') goto yy186; goto yy689; } } else { if (yych <= 'n') { if (yych == 'i') goto yy687; goto yy186; } else { if (yych <= 'o') goto yy688; if (yych == 'u') goto yy689; goto yy186; } } yy127: YYDEBUG(127, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= 'K') { if (yych == 'A') goto yy652; goto yy186; } else { if (yych <= 'L') goto yy653; if (yych <= 'N') goto yy186; goto yy654; } } else { if (yych <= 'k') { if (yych == 'a') goto yy652; goto yy186; } else { if (yych <= 'l') goto yy653; if (yych == 'o') goto yy654; goto yy186; } } yy128: YYDEBUG(128, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy634; if (yych == 'e') goto yy634; goto yy186; yy129: YYDEBUG(129, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych == 'H') goto yy622; if (yych <= 'Q') goto yy186; goto yy623; } else { if (yych <= 'h') { if (yych <= 'g') goto yy186; goto yy622; } else { if (yych == 'r') goto yy623; goto yy186; } } yy130: YYDEBUG(130, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= 'L') { if (yych == 'F') goto yy569; goto yy186; } else { if (yych <= 'M') goto yy571; if (yych <= 'N') goto yy572; if (yych <= 'R') goto yy186; goto yy573; } } else { if (yych <= 'm') { if (yych == 'f') goto yy569; if (yych <= 'l') goto yy186; goto yy571; } else { if (yych <= 'n') goto yy572; if (yych == 's') goto yy573; goto yy186; } } yy131: YYDEBUG(131, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy564; if (yych == 'h') goto yy564; goto yy186; yy132: YYDEBUG(132, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= 'M') { if (yych == 'B') goto yy546; goto yy186; } else { if (yych <= 'N') goto yy547; if (yych <= 'Q') goto yy186; if (yych <= 'R') goto yy548; goto yy549; } } else { if (yych <= 'n') { if (yych == 'b') goto yy546; if (yych <= 'm') goto yy186; goto yy547; } else { if (yych <= 'q') goto yy186; if (yych <= 'r') goto yy548; if (yych <= 's') goto yy549; goto yy186; } } yy133: YYDEBUG(133, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'W') { if (yych == 'T') goto yy534; if (yych <= 'V') goto yy186; goto yy535; } else { if (yych <= 't') { if (yych <= 's') goto yy186; goto yy534; } else { if (yych == 'w') goto yy535; goto yy186; } } yy134: YYDEBUG(134, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ';') { if (yych <= '"') { if (yych <= '!') goto yy186; goto yy526; } else { if (yych == '\'') goto yy527; goto yy186; } } else { if (yych <= 'R') { if (yych <= '<') goto yy525; if (yych <= 'Q') goto yy186; goto yy528; } else { if (yych == 'r') goto yy528; goto yy186; } } yy135: YYDEBUG(135, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'L') goto yy515; if (yych <= 'N') goto yy186; goto yy516; } else { if (yych <= 'l') { if (yych <= 'k') goto yy186; goto yy515; } else { if (yych == 'o') goto yy516; goto yy186; } } yy136: YYDEBUG(136, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'R') goto yy491; if (yych <= 'T') goto yy186; goto yy492; } else { if (yych <= 'r') { if (yych <= 'q') goto yy186; goto yy491; } else { if (yych == 'u') goto yy492; goto yy186; } } yy137: YYDEBUG(137, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '<') { if (yych == '-') goto yy487; } else { if (yych <= '=') goto yy485; if (yych <= '>') goto yy489; } yy138: YYDEBUG(138, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1431 "Zend/zend_language_scanner.l" { return yytext[0]; } #line 2628 "Zend/zend_language_scanner.c" yy139: YYDEBUG(139, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy484; yy140: YYDEBUG(140, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1162 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; HANDLE_NEWLINES(yytext, yyleng); return T_WHITESPACE; } #line 2645 "Zend/zend_language_scanner.c" yy141: YYDEBUG(141, *YYCURSOR); yych = *++YYCURSOR; if (yych == ':') goto yy481; goto yy138; yy142: YYDEBUG(142, *YYCURSOR); ++YYCURSOR; YYDEBUG(143, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1191 "Zend/zend_language_scanner.l" { return T_NS_SEPARATOR; } #line 2660 "Zend/zend_language_scanner.c" yy144: YYDEBUG(144, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych == 'A') goto yy469; if (yych <= 'D') goto yy186; goto yy470; } else { if (yych <= 'a') { if (yych <= '`') goto yy186; goto yy469; } else { if (yych == 'e') goto yy470; goto yy186; } } yy145: YYDEBUG(145, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy466; if (yych == 'a') goto yy466; goto yy186; yy146: YYDEBUG(146, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy391; if (yych <= 0x1F) goto yy138; goto yy391; } else { if (yych <= '@') goto yy138; if (yych == 'C') goto yy138; goto yy391; } } else { if (yych <= 'I') { if (yych == 'F') goto yy391; if (yych <= 'H') goto yy138; goto yy391; } else { if (yych == 'O') goto yy391; if (yych <= 'Q') goto yy138; goto yy391; } } } else { if (yych <= 'f') { if (yych <= 'b') { if (yych == 'U') goto yy391; if (yych <= '`') goto yy138; goto yy391; } else { if (yych == 'd') goto yy391; if (yych <= 'e') goto yy138; goto yy391; } } else { if (yych <= 'o') { if (yych == 'i') goto yy391; if (yych <= 'n') goto yy138; goto yy391; } else { if (yych <= 's') { if (yych <= 'q') goto yy138; goto yy391; } else { if (yych == 'u') goto yy391; goto yy138; } } } } yy147: YYDEBUG(147, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych == 'N') goto yy382; if (yych <= 'R') goto yy186; goto yy383; } else { if (yych <= 'n') { if (yych <= 'm') goto yy186; goto yy382; } else { if (yych == 's') goto yy383; goto yy186; } } yy148: YYDEBUG(148, *YYCURSOR); yych = *++YYCURSOR; if (yych == '_') goto yy300; goto yy186; yy149: YYDEBUG(149, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '<') goto yy138; if (yych <= '=') goto yy294; if (yych <= '>') goto yy296; goto yy138; yy150: YYDEBUG(150, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy290; if (yych == 'i') goto yy290; goto yy186; yy151: YYDEBUG(151, *YYCURSOR); yych = *++YYCURSOR; if (yych == '+') goto yy288; if (yych == '=') goto yy286; goto yy138; yy152: YYDEBUG(152, *YYCURSOR); yych = *++YYCURSOR; if (yych == '=') goto yy283; goto yy138; yy153: YYDEBUG(153, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ';') { if (yych == '/') goto yy255; goto yy138; } else { if (yych <= '<') goto yy253; if (yych <= '=') goto yy256; if (yych <= '>') goto yy258; goto yy138; } yy154: YYDEBUG(154, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '<') goto yy138; if (yych <= '=') goto yy249; if (yych <= '>') goto yy247; goto yy138; yy155: YYDEBUG(155, *YYCURSOR); yych = *++YYCURSOR; if (yych == '=') goto yy245; goto yy138; yy156: YYDEBUG(156, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '.') { if (yych == '*') goto yy237; goto yy138; } else { if (yych <= '/') goto yy239; if (yych == '=') goto yy240; goto yy138; } yy157: YYDEBUG(157, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy138; if (yych <= '9') goto yy233; if (yych == '=') goto yy235; goto yy138; yy158: YYDEBUG(158, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '<') goto yy138; if (yych <= '=') goto yy229; if (yych <= '>') goto yy227; goto yy138; yy159: YYDEBUG(159, *YYCURSOR); yych = *++YYCURSOR; if (yych == '&') goto yy223; if (yych == '=') goto yy225; goto yy138; yy160: YYDEBUG(160, *YYCURSOR); yych = *++YYCURSOR; if (yych == '=') goto yy221; if (yych == '|') goto yy219; goto yy138; yy161: YYDEBUG(161, *YYCURSOR); yych = *++YYCURSOR; if (yych == '=') goto yy217; goto yy138; yy162: YYDEBUG(162, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy215; if (yych == 'r') goto yy215; goto yy186; yy163: YYDEBUG(163, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy212; if (yych == 'o') goto yy212; goto yy186; yy164: YYDEBUG(164, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy138; if (yych <= 'Z') goto yy209; if (yych <= '^') goto yy138; goto yy209; } else { if (yych <= '`') goto yy138; if (yych <= 'z') goto yy209; if (yych <= '~') goto yy138; goto yy209; } yy165: YYDEBUG(165, *YYCURSOR); yych = *++YYCURSOR; goto yy138; yy166: YYDEBUG(166, *YYCURSOR); yych = *++YYCURSOR; if (yych == '>') goto yy205; goto yy138; yy167: YYDEBUG(167, *YYCURSOR); ++YYCURSOR; YYDEBUG(168, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1436 "Zend/zend_language_scanner.l" { yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); return '{'; } #line 2893 "Zend/zend_language_scanner.c" yy169: YYDEBUG(169, *YYCURSOR); ++YYCURSOR; YYDEBUG(170, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1448 "Zend/zend_language_scanner.l" { RESET_DOC_COMMENT(); if (!zend_stack_is_empty(&SCNG(state_stack))) { yy_pop_state(TSRMLS_C); } return '}'; } #line 2907 "Zend/zend_language_scanner.c" yy171: YYDEBUG(171, *YYCURSOR); yyaccept = 2; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'E') { if (yych <= '9') { if (yych == '.') goto yy187; if (yych >= '0') goto yy190; } else { if (yych == 'B') goto yy198; if (yych >= 'E') goto yy192; } } else { if (yych <= 'b') { if (yych == 'X') goto yy197; if (yych >= 'b') goto yy198; } else { if (yych <= 'e') { if (yych >= 'e') goto yy192; } else { if (yych == 'x') goto yy197; } } } yy172: YYDEBUG(172, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1494 "Zend/zend_language_scanner.l" { if (yyleng < MAX_LENGTH_OF_LONG - 1) { /* Won't overflow */ zendlval->value.lval = strtol(yytext, NULL, 0); } else { errno = 0; zendlval->value.lval = strtol(yytext, NULL, 0); if (errno == ERANGE) { /* Overflow */ if (yytext[0] == '0') { /* octal overflow */ zendlval->value.dval = zend_oct_strtod(yytext, NULL); } else { zendlval->value.dval = zend_strtod(yytext, NULL); } zendlval->type = IS_DOUBLE; return T_DNUMBER; } } zendlval->type = IS_LONG; return T_LNUMBER; } #line 2956 "Zend/zend_language_scanner.c" yy173: YYDEBUG(173, *YYCURSOR); yyaccept = 2; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych == '.') goto yy187; if (yych <= '/') goto yy172; goto yy190; } else { if (yych <= 'E') { if (yych <= 'D') goto yy172; goto yy192; } else { if (yych == 'e') goto yy192; goto yy172; } } yy174: YYDEBUG(174, *YYCURSOR); yych = *++YYCURSOR; goto yy186; yy175: YYDEBUG(175, *YYCURSOR); ++YYCURSOR; yy176: YYDEBUG(176, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1887 "Zend/zend_language_scanner.l" { while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '\r': if (*YYCURSOR == '\n') { YYCURSOR++; } /* fall through */ case '\n': CG(zend_lineno)++; break; case '%': if (!CG(asp_tags)) { continue; } /* fall through */ case '?': if (*YYCURSOR == '>') { YYCURSOR--; break; } /* fall through */ default: continue; } break; } yyleng = YYCURSOR - SCNG(yy_text); return T_COMMENT; } #line 3018 "Zend/zend_language_scanner.c" yy177: YYDEBUG(177, *YYCURSOR); ++YYCURSOR; yy178: YYDEBUG(178, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1978 "Zend/zend_language_scanner.l" { register char *s, *t; char *end; int bprefix = (yytext[0] != '\'') ? 1 : 0; while (1) { if (YYCURSOR < YYLIMIT) { if (*YYCURSOR == '\'') { YYCURSOR++; yyleng = YYCURSOR - SCNG(yy_text); break; } else if (*YYCURSOR++ == '\\' && YYCURSOR < YYLIMIT) { YYCURSOR++; } } else { yyleng = YYLIMIT - SCNG(yy_text); /* Unclosed single quotes; treat similar to double quotes, but without a separate token * for ' (unrecognized by parser), instead of old flex fallback to "Unexpected character..." * rule, which continued in ST_IN_SCRIPTING state after the quote */ return T_ENCAPSED_AND_WHITESPACE; } } zendlval->value.str.val = estrndup(yytext+bprefix+1, yyleng-bprefix-2); zendlval->value.str.len = yyleng-bprefix-2; zendlval->type = IS_STRING; /* convert escape sequences */ s = t = zendlval->value.str.val; end = s+zendlval->value.str.len; while (s<end) { if (*s=='\\') { s++; switch(*s) { case '\\': case '\'': *t++ = *s; zendlval->value.str.len--; break; default: *t++ = '\\'; *t++ = *s; break; } } else { *t++ = *s; } if (*s == '\n' || (*s == '\r' && (*(s+1) != '\n'))) { CG(zend_lineno)++; } s++; } *t = 0; if (SCNG(output_filter)) { size_t sz = 0; s = zendlval->value.str.val; SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)s, (size_t)zendlval->value.str.len TSRMLS_CC); zendlval->value.str.len = sz; efree(s); } return T_CONSTANT_ENCAPSED_STRING; } #line 3093 "Zend/zend_language_scanner.c" yy179: YYDEBUG(179, *YYCURSOR); ++YYCURSOR; yy180: YYDEBUG(180, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2047 "Zend/zend_language_scanner.l" { int bprefix = (yytext[0] != '"') ? 1 : 0; while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '"': yyleng = YYCURSOR - SCNG(yy_text); zend_scan_escape_string(zendlval, yytext+bprefix+1, yyleng-bprefix-2, '"' TSRMLS_CC); return T_CONSTANT_ENCAPSED_STRING; case '$': if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { break; } continue; case '{': if (*YYCURSOR == '$') { break; } continue; case '\\': if (YYCURSOR < YYLIMIT) { YYCURSOR++; } /* fall through */ default: continue; } YYCURSOR--; break; } /* Remember how much was scanned to save rescanning */ SET_DOUBLE_QUOTES_SCANNED_LENGTH(YYCURSOR - SCNG(yy_text) - yyleng); YYCURSOR = SCNG(yy_text) + yyleng; BEGIN(ST_DOUBLE_QUOTES); return '"'; } #line 3141 "Zend/zend_language_scanner.c" yy181: YYDEBUG(181, *YYCURSOR); ++YYCURSOR; YYDEBUG(182, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2138 "Zend/zend_language_scanner.l" { BEGIN(ST_BACKQUOTE); return '`'; } #line 3152 "Zend/zend_language_scanner.c" yy183: YYDEBUG(183, *YYCURSOR); ++YYCURSOR; YYDEBUG(184, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2396 "Zend/zend_language_scanner.l" { if (YYCURSOR > YYLIMIT) { return 0; } zend_error(E_COMPILE_WARNING,"Unexpected character in input: '%c' (ASCII=%d) state=%d", yytext[0], yytext[0], YYSTATE); goto restart; } #line 3167 "Zend/zend_language_scanner.c" yy185: YYDEBUG(185, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy186: YYDEBUG(186, *YYCURSOR); if (yybm[0+yych] & 4) { goto yy185; } goto yy124; yy187: YYDEBUG(187, *YYCURSOR); yyaccept = 3; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(188, *YYCURSOR); if (yybm[0+yych] & 8) { goto yy187; } if (yych == 'E') goto yy192; if (yych == 'e') goto yy192; yy189: YYDEBUG(189, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1555 "Zend/zend_language_scanner.l" { zendlval->value.dval = zend_strtod(yytext, NULL); zendlval->type = IS_DOUBLE; return T_DNUMBER; } #line 3200 "Zend/zend_language_scanner.c" yy190: YYDEBUG(190, *YYCURSOR); yyaccept = 2; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(191, *YYCURSOR); if (yych <= '9') { if (yych == '.') goto yy187; if (yych <= '/') goto yy172; goto yy190; } else { if (yych <= 'E') { if (yych <= 'D') goto yy172; } else { if (yych != 'e') goto yy172; } } yy192: YYDEBUG(192, *YYCURSOR); yych = *++YYCURSOR; if (yych <= ',') { if (yych == '+') goto yy194; } else { if (yych <= '-') goto yy194; if (yych <= '/') goto yy193; if (yych <= '9') goto yy195; } yy193: YYDEBUG(193, *YYCURSOR); YYCURSOR = YYMARKER; if (yyaccept <= 2) { if (yyaccept <= 1) { if (yyaccept <= 0) { goto yy124; } else { goto yy138; } } else { goto yy172; } } else { if (yyaccept <= 4) { if (yyaccept <= 3) { goto yy189; } else { goto yy238; } } else { goto yy254; } } yy194: YYDEBUG(194, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy193; if (yych >= ':') goto yy193; yy195: YYDEBUG(195, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(196, *YYCURSOR); if (yych <= '/') goto yy189; if (yych <= '9') goto yy195; goto yy189; yy197: YYDEBUG(197, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 32) { goto yy202; } goto yy193; yy198: YYDEBUG(198, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 16) { goto yy199; } goto yy193; yy199: YYDEBUG(199, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(200, *YYCURSOR); if (yybm[0+yych] & 16) { goto yy199; } YYDEBUG(201, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1473 "Zend/zend_language_scanner.l" { char *bin = yytext + 2; /* Skip "0b" */ int len = yyleng - 2; /* Skip any leading 0s */ while (*bin == '0') { ++bin; --len; } if (len < SIZEOF_LONG * 8) { zendlval->value.lval = strtol(bin, NULL, 2); zendlval->type = IS_LONG; return T_LNUMBER; } else { zendlval->value.dval = zend_bin_strtod(bin, NULL); zendlval->type = IS_DOUBLE; return T_DNUMBER; } } #line 3313 "Zend/zend_language_scanner.c" yy202: YYDEBUG(202, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(203, *YYCURSOR); if (yybm[0+yych] & 32) { goto yy202; } YYDEBUG(204, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1515 "Zend/zend_language_scanner.l" { char *hex = yytext + 2; /* Skip "0x" */ int len = yyleng - 2; /* Skip any leading 0s */ while (*hex == '0') { hex++; len--; } if (len < SIZEOF_LONG * 2 || (len == SIZEOF_LONG * 2 && *hex <= '7')) { zendlval->value.lval = strtol(hex, NULL, 16); zendlval->type = IS_LONG; return T_LNUMBER; } else { zendlval->value.dval = zend_hex_strtod(hex, NULL); zendlval->type = IS_DOUBLE; return T_DNUMBER; } } #line 3346 "Zend/zend_language_scanner.c" yy205: YYDEBUG(205, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '\n') goto yy207; if (yych == '\r') goto yy208; yy206: YYDEBUG(206, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1955 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(INITIAL); return T_CLOSE_TAG; /* implicit ';' at php-end tag */ } #line 3363 "Zend/zend_language_scanner.c" yy207: YYDEBUG(207, *YYCURSOR); yych = *++YYCURSOR; goto yy206; yy208: YYDEBUG(208, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\n') goto yy207; goto yy206; yy209: YYDEBUG(209, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(210, *YYCURSOR); if (yych <= '^') { if (yych <= '9') { if (yych >= '0') goto yy209; } else { if (yych <= '@') goto yy211; if (yych <= 'Z') goto yy209; } } else { if (yych <= '`') { if (yych <= '_') goto yy209; } else { if (yych <= 'z') goto yy209; if (yych >= 0x7F) goto yy209; } } yy211: YYDEBUG(211, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1857 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 3403 "Zend/zend_language_scanner.c" yy212: YYDEBUG(212, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy213; if (yych != 'r') goto yy186; yy213: YYDEBUG(213, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(214, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1419 "Zend/zend_language_scanner.l" { return T_LOGICAL_XOR; } #line 3421 "Zend/zend_language_scanner.c" yy215: YYDEBUG(215, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(216, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1411 "Zend/zend_language_scanner.l" { return T_LOGICAL_OR; } #line 3434 "Zend/zend_language_scanner.c" yy217: YYDEBUG(217, *YYCURSOR); ++YYCURSOR; YYDEBUG(218, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1399 "Zend/zend_language_scanner.l" { return T_XOR_EQUAL; } #line 3444 "Zend/zend_language_scanner.c" yy219: YYDEBUG(219, *YYCURSOR); ++YYCURSOR; YYDEBUG(220, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1403 "Zend/zend_language_scanner.l" { return T_BOOLEAN_OR; } #line 3454 "Zend/zend_language_scanner.c" yy221: YYDEBUG(221, *YYCURSOR); ++YYCURSOR; YYDEBUG(222, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1395 "Zend/zend_language_scanner.l" { return T_OR_EQUAL; } #line 3464 "Zend/zend_language_scanner.c" yy223: YYDEBUG(223, *YYCURSOR); ++YYCURSOR; YYDEBUG(224, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1407 "Zend/zend_language_scanner.l" { return T_BOOLEAN_AND; } #line 3474 "Zend/zend_language_scanner.c" yy225: YYDEBUG(225, *YYCURSOR); ++YYCURSOR; YYDEBUG(226, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1391 "Zend/zend_language_scanner.l" { return T_AND_EQUAL; } #line 3484 "Zend/zend_language_scanner.c" yy227: YYDEBUG(227, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '\n') goto yy231; if (yych == '\r') goto yy232; yy228: YYDEBUG(228, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1964 "Zend/zend_language_scanner.l" { if (CG(asp_tags)) { BEGIN(INITIAL); zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; zendlval->value.str.val = yytext; /* no copying - intentional */ return T_CLOSE_TAG; /* implicit ';' at php-end tag */ } else { yyless(1); return yytext[0]; } } #line 3506 "Zend/zend_language_scanner.c" yy229: YYDEBUG(229, *YYCURSOR); ++YYCURSOR; YYDEBUG(230, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1379 "Zend/zend_language_scanner.l" { return T_MOD_EQUAL; } #line 3516 "Zend/zend_language_scanner.c" yy231: YYDEBUG(231, *YYCURSOR); yych = *++YYCURSOR; goto yy228; yy232: YYDEBUG(232, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\n') goto yy231; goto yy228; yy233: YYDEBUG(233, *YYCURSOR); yyaccept = 3; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(234, *YYCURSOR); if (yych <= 'D') { if (yych <= '/') goto yy189; if (yych <= '9') goto yy233; goto yy189; } else { if (yych <= 'E') goto yy192; if (yych == 'e') goto yy192; goto yy189; } yy235: YYDEBUG(235, *YYCURSOR); ++YYCURSOR; YYDEBUG(236, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1375 "Zend/zend_language_scanner.l" { return T_CONCAT_EQUAL; } #line 3551 "Zend/zend_language_scanner.c" yy237: YYDEBUG(237, *YYCURSOR); yyaccept = 4; yych = *(YYMARKER = ++YYCURSOR); if (yych == '*') goto yy242; yy238: YYDEBUG(238, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1921 "Zend/zend_language_scanner.l" { int doc_com; if (yyleng > 2) { doc_com = 1; RESET_DOC_COMMENT(); } else { doc_com = 0; } while (YYCURSOR < YYLIMIT) { if (*YYCURSOR++ == '*' && *YYCURSOR == '/') { break; } } if (YYCURSOR < YYLIMIT) { YYCURSOR++; } else { zend_error(E_COMPILE_WARNING, "Unterminated comment starting line %d", CG(zend_lineno)); } yyleng = YYCURSOR - SCNG(yy_text); HANDLE_NEWLINES(yytext, yyleng); if (doc_com) { CG(doc_comment) = estrndup(yytext, yyleng); CG(doc_comment_len) = yyleng; return T_DOC_COMMENT; } return T_COMMENT; } #line 3594 "Zend/zend_language_scanner.c" yy239: YYDEBUG(239, *YYCURSOR); yych = *++YYCURSOR; goto yy176; yy240: YYDEBUG(240, *YYCURSOR); ++YYCURSOR; YYDEBUG(241, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1371 "Zend/zend_language_scanner.l" { return T_DIV_EQUAL; } #line 3608 "Zend/zend_language_scanner.c" yy242: YYDEBUG(242, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 64) { goto yy243; } goto yy193; yy243: YYDEBUG(243, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(244, *YYCURSOR); if (yybm[0+yych] & 64) { goto yy243; } goto yy238; yy245: YYDEBUG(245, *YYCURSOR); ++YYCURSOR; YYDEBUG(246, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1367 "Zend/zend_language_scanner.l" { return T_MUL_EQUAL; } #line 3635 "Zend/zend_language_scanner.c" yy247: YYDEBUG(247, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '=') goto yy251; YYDEBUG(248, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1427 "Zend/zend_language_scanner.l" { return T_SR; } #line 3646 "Zend/zend_language_scanner.c" yy249: YYDEBUG(249, *YYCURSOR); ++YYCURSOR; YYDEBUG(250, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1355 "Zend/zend_language_scanner.l" { return T_IS_GREATER_OR_EQUAL; } #line 3656 "Zend/zend_language_scanner.c" yy251: YYDEBUG(251, *YYCURSOR); ++YYCURSOR; YYDEBUG(252, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1387 "Zend/zend_language_scanner.l" { return T_SR_EQUAL; } #line 3666 "Zend/zend_language_scanner.c" yy253: YYDEBUG(253, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ';') goto yy254; if (yych <= '<') goto yy269; if (yych <= '=') goto yy267; yy254: YYDEBUG(254, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1423 "Zend/zend_language_scanner.l" { return T_SL; } #line 3681 "Zend/zend_language_scanner.c" yy255: YYDEBUG(255, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy260; if (yych == 's') goto yy260; goto yy193; yy256: YYDEBUG(256, *YYCURSOR); ++YYCURSOR; YYDEBUG(257, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1351 "Zend/zend_language_scanner.l" { return T_IS_SMALLER_OR_EQUAL; } #line 3697 "Zend/zend_language_scanner.c" yy258: YYDEBUG(258, *YYCURSOR); ++YYCURSOR; yy259: YYDEBUG(259, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1347 "Zend/zend_language_scanner.l" { return T_IS_NOT_EQUAL; } #line 3708 "Zend/zend_language_scanner.c" yy260: YYDEBUG(260, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy261; if (yych != 'c') goto yy193; yy261: YYDEBUG(261, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy262; if (yych != 'r') goto yy193; yy262: YYDEBUG(262, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy263; if (yych != 'i') goto yy193; yy263: YYDEBUG(263, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy264; if (yych != 'p') goto yy193; yy264: YYDEBUG(264, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy265; if (yych != 't') goto yy193; yy265: YYDEBUG(265, *YYCURSOR); ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(266, *YYCURSOR); if (yych <= '\r') { if (yych <= 0x08) goto yy193; if (yych <= '\n') goto yy265; if (yych <= '\f') goto yy193; goto yy265; } else { if (yych <= ' ') { if (yych <= 0x1F) goto yy193; goto yy265; } else { if (yych == '>') goto yy205; goto yy193; } } yy267: YYDEBUG(267, *YYCURSOR); ++YYCURSOR; YYDEBUG(268, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1383 "Zend/zend_language_scanner.l" { return T_SL_EQUAL; } #line 3763 "Zend/zend_language_scanner.c" yy269: YYDEBUG(269, *YYCURSOR); ++YYCURSOR; YYFILL(2); yych = *YYCURSOR; YYDEBUG(270, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy269; } if (yych <= 'Z') { if (yych <= '&') { if (yych == '"') goto yy274; goto yy193; } else { if (yych <= '\'') goto yy273; if (yych <= '@') goto yy193; } } else { if (yych <= '`') { if (yych != '_') goto yy193; } else { if (yych <= 'z') goto yy271; if (yych <= '~') goto yy193; } } yy271: YYDEBUG(271, *YYCURSOR); ++YYCURSOR; YYFILL(2); yych = *YYCURSOR; YYDEBUG(272, *YYCURSOR); if (yych <= '@') { if (yych <= '\f') { if (yych == '\n') goto yy278; goto yy193; } else { if (yych <= '\r') goto yy280; if (yych <= '/') goto yy193; if (yych <= '9') goto yy271; goto yy193; } } else { if (yych <= '_') { if (yych <= 'Z') goto yy271; if (yych <= '^') goto yy193; goto yy271; } else { if (yych <= '`') goto yy193; if (yych <= 'z') goto yy271; if (yych <= '~') goto yy193; goto yy271; } } yy273: YYDEBUG(273, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\'') goto yy193; if (yych <= '/') goto yy282; if (yych <= '9') goto yy193; goto yy282; yy274: YYDEBUG(274, *YYCURSOR); yych = *++YYCURSOR; if (yych == '"') goto yy193; if (yych <= '/') goto yy276; if (yych <= '9') goto yy193; goto yy276; yy275: YYDEBUG(275, *YYCURSOR); ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; yy276: YYDEBUG(276, *YYCURSOR); if (yych <= 'Z') { if (yych <= '/') { if (yych != '"') goto yy193; } else { if (yych <= '9') goto yy275; if (yych <= '@') goto yy193; goto yy275; } } else { if (yych <= '`') { if (yych == '_') goto yy275; goto yy193; } else { if (yych <= 'z') goto yy275; if (yych <= '~') goto yy193; goto yy275; } } yy277: YYDEBUG(277, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\n') goto yy278; if (yych == '\r') goto yy280; goto yy193; yy278: YYDEBUG(278, *YYCURSOR); ++YYCURSOR; yy279: YYDEBUG(279, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2089 "Zend/zend_language_scanner.l" { char *s; int bprefix = (yytext[0] != '<') ? 1 : 0; /* save old heredoc label */ Z_STRVAL_P(zendlval) = CG(heredoc); Z_STRLEN_P(zendlval) = CG(heredoc_len); CG(zend_lineno)++; CG(heredoc_len) = yyleng-bprefix-3-1-(yytext[yyleng-2]=='\r'?1:0); s = yytext+bprefix+3; while ((*s == ' ') || (*s == '\t')) { s++; CG(heredoc_len)--; } if (*s == '\'') { s++; CG(heredoc_len) -= 2; BEGIN(ST_NOWDOC); } else { if (*s == '"') { s++; CG(heredoc_len) -= 2; } BEGIN(ST_HEREDOC); } CG(heredoc) = estrndup(s, CG(heredoc_len)); /* Check for ending label on the next line */ if (CG(heredoc_len) < YYLIMIT - YYCURSOR && !memcmp(YYCURSOR, s, CG(heredoc_len))) { YYCTYPE *end = YYCURSOR + CG(heredoc_len); if (*end == ';') { end++; } if (*end == '\n' || *end == '\r') { BEGIN(ST_END_HEREDOC); } } return T_START_HEREDOC; } #line 3916 "Zend/zend_language_scanner.c" yy280: YYDEBUG(280, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\n') goto yy278; goto yy279; yy281: YYDEBUG(281, *YYCURSOR); ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; yy282: YYDEBUG(282, *YYCURSOR); if (yych <= 'Z') { if (yych <= '/') { if (yych == '\'') goto yy277; goto yy193; } else { if (yych <= '9') goto yy281; if (yych <= '@') goto yy193; goto yy281; } } else { if (yych <= '`') { if (yych == '_') goto yy281; goto yy193; } else { if (yych <= 'z') goto yy281; if (yych <= '~') goto yy193; goto yy281; } } yy283: YYDEBUG(283, *YYCURSOR); yych = *++YYCURSOR; if (yych != '=') goto yy259; YYDEBUG(284, *YYCURSOR); ++YYCURSOR; YYDEBUG(285, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1339 "Zend/zend_language_scanner.l" { return T_IS_NOT_IDENTICAL; } #line 3960 "Zend/zend_language_scanner.c" yy286: YYDEBUG(286, *YYCURSOR); ++YYCURSOR; YYDEBUG(287, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1359 "Zend/zend_language_scanner.l" { return T_PLUS_EQUAL; } #line 3970 "Zend/zend_language_scanner.c" yy288: YYDEBUG(288, *YYCURSOR); ++YYCURSOR; YYDEBUG(289, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1327 "Zend/zend_language_scanner.l" { return T_INC; } #line 3980 "Zend/zend_language_scanner.c" yy290: YYDEBUG(290, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy291; if (yych != 's') goto yy186; yy291: YYDEBUG(291, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy292; if (yych != 't') goto yy186; yy292: YYDEBUG(292, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(293, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1315 "Zend/zend_language_scanner.l" { return T_LIST; } #line 4003 "Zend/zend_language_scanner.c" yy294: YYDEBUG(294, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '=') goto yy298; YYDEBUG(295, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1343 "Zend/zend_language_scanner.l" { return T_IS_EQUAL; } #line 4014 "Zend/zend_language_scanner.c" yy296: YYDEBUG(296, *YYCURSOR); ++YYCURSOR; YYDEBUG(297, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1311 "Zend/zend_language_scanner.l" { return T_DOUBLE_ARROW; } #line 4024 "Zend/zend_language_scanner.c" yy298: YYDEBUG(298, *YYCURSOR); ++YYCURSOR; YYDEBUG(299, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1335 "Zend/zend_language_scanner.l" { return T_IS_IDENTICAL; } #line 4034 "Zend/zend_language_scanner.c" yy300: YYDEBUG(300, *YYCURSOR); yych = *++YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case 'C': case 'c': goto yy302; case 'D': case 'd': goto yy307; case 'F': case 'f': goto yy304; case 'H': case 'h': goto yy301; case 'L': case 'l': goto yy306; case 'M': case 'm': goto yy305; case 'N': case 'n': goto yy308; case 'T': case 't': goto yy303; default: goto yy186; } yy301: YYDEBUG(301, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy369; if (yych == 'a') goto yy369; goto yy186; yy302: YYDEBUG(302, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy362; if (yych == 'l') goto yy362; goto yy186; yy303: YYDEBUG(303, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy355; if (yych == 'r') goto yy355; goto yy186; yy304: YYDEBUG(304, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'I') goto yy339; if (yych <= 'T') goto yy186; goto yy340; } else { if (yych <= 'i') { if (yych <= 'h') goto yy186; goto yy339; } else { if (yych == 'u') goto yy340; goto yy186; } } yy305: YYDEBUG(305, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy331; if (yych == 'e') goto yy331; goto yy186; yy306: YYDEBUG(306, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy325; if (yych == 'i') goto yy325; goto yy186; yy307: YYDEBUG(307, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy320; if (yych == 'i') goto yy320; goto yy186; yy308: YYDEBUG(308, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy309; if (yych != 'a') goto yy186; yy309: YYDEBUG(309, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy310; if (yych != 'm') goto yy186; yy310: YYDEBUG(310, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy311; if (yych != 'e') goto yy186; yy311: YYDEBUG(311, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy312; if (yych != 's') goto yy186; yy312: YYDEBUG(312, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy313; if (yych != 'p') goto yy186; yy313: YYDEBUG(313, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy314; if (yych != 'a') goto yy186; yy314: YYDEBUG(314, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy315; if (yych != 'c') goto yy186; yy315: YYDEBUG(315, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy316; if (yych != 'e') goto yy186; yy316: YYDEBUG(316, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(317, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(318, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(319, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1690 "Zend/zend_language_scanner.l" { if (CG(current_namespace)) { *zendlval = *CG(current_namespace); zval_copy_ctor(zendlval); } else { ZVAL_EMPTY_STRING(zendlval); } return T_NS_C; } #line 4174 "Zend/zend_language_scanner.c" yy320: YYDEBUG(320, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy321; if (yych != 'r') goto yy186; yy321: YYDEBUG(321, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(322, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(323, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(324, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1663 "Zend/zend_language_scanner.l" { char *filename = zend_get_compiled_filename(TSRMLS_C); const size_t filename_len = strlen(filename); char *dirname; if (!filename) { filename = ""; } dirname = estrndup(filename, filename_len); zend_dirname(dirname, filename_len); if (strcmp(dirname, ".") == 0) { dirname = erealloc(dirname, MAXPATHLEN); #if HAVE_GETCWD VCWD_GETCWD(dirname, MAXPATHLEN); #elif HAVE_GETWD VCWD_GETWD(dirname); #endif } zendlval->value.str.len = strlen(dirname); zendlval->value.str.val = dirname; zendlval->type = IS_STRING; return T_DIR; } #line 4221 "Zend/zend_language_scanner.c" yy325: YYDEBUG(325, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy326; if (yych != 'n') goto yy186; yy326: YYDEBUG(326, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy327; if (yych != 'e') goto yy186; yy327: YYDEBUG(327, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(328, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(329, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(330, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1645 "Zend/zend_language_scanner.l" { zendlval->value.lval = CG(zend_lineno); zendlval->type = IS_LONG; return T_LINE; } #line 4252 "Zend/zend_language_scanner.c" yy331: YYDEBUG(331, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy332; if (yych != 't') goto yy186; yy332: YYDEBUG(332, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy333; if (yych != 'h') goto yy186; yy333: YYDEBUG(333, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy334; if (yych != 'o') goto yy186; yy334: YYDEBUG(334, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy335; if (yych != 'd') goto yy186; yy335: YYDEBUG(335, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(336, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(337, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(338, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1624 "Zend/zend_language_scanner.l" { const char *class_name = CG(active_class_entry) ? CG(active_class_entry)->name : NULL; const char *func_name = CG(active_op_array)? CG(active_op_array)->function_name : NULL; size_t len = 0; if (class_name) { len += strlen(class_name) + 2; } if (func_name) { len += strlen(func_name); } zendlval->value.str.len = zend_spprintf(&zendlval->value.str.val, 0, "%s%s%s", class_name ? class_name : "", class_name && func_name ? "::" : "", func_name ? func_name : "" ); zendlval->type = IS_STRING; return T_METHOD_C; } #line 4308 "Zend/zend_language_scanner.c" yy339: YYDEBUG(339, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy350; if (yych == 'l') goto yy350; goto yy186; yy340: YYDEBUG(340, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy341; if (yych != 'n') goto yy186; yy341: YYDEBUG(341, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy342; if (yych != 'c') goto yy186; yy342: YYDEBUG(342, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy343; if (yych != 't') goto yy186; yy343: YYDEBUG(343, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy344; if (yych != 'i') goto yy186; yy344: YYDEBUG(344, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy345; if (yych != 'o') goto yy186; yy345: YYDEBUG(345, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy346; if (yych != 'n') goto yy186; yy346: YYDEBUG(346, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(347, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(348, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(349, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1608 "Zend/zend_language_scanner.l" { const char *func_name = NULL; if (CG(active_op_array)) { func_name = CG(active_op_array)->function_name; } if (!func_name) { func_name = ""; } zendlval->value.str.len = strlen(func_name); zendlval->value.str.val = estrndup(func_name, zendlval->value.str.len); zendlval->type = IS_STRING; return T_FUNC_C; } #line 4375 "Zend/zend_language_scanner.c" yy350: YYDEBUG(350, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy351; if (yych != 'e') goto yy186; yy351: YYDEBUG(351, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(352, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(353, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(354, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1651 "Zend/zend_language_scanner.l" { char *filename = zend_get_compiled_filename(TSRMLS_C); if (!filename) { filename = ""; } zendlval->value.str.len = strlen(filename); zendlval->value.str.val = estrndup(filename, zendlval->value.str.len); zendlval->type = IS_STRING; return T_FILE; } #line 4407 "Zend/zend_language_scanner.c" yy355: YYDEBUG(355, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy356; if (yych != 'a') goto yy186; yy356: YYDEBUG(356, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy357; if (yych != 'i') goto yy186; yy357: YYDEBUG(357, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy358; if (yych != 't') goto yy186; yy358: YYDEBUG(358, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(359, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(360, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(361, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1588 "Zend/zend_language_scanner.l" { const char *trait_name = NULL; if (CG(active_class_entry) && (ZEND_ACC_TRAIT == (CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT))) { trait_name = CG(active_class_entry)->name; } if (!trait_name) { trait_name = ""; } zendlval->value.str.len = strlen(trait_name); zendlval->value.str.val = estrndup(trait_name, zendlval->value.str.len); zendlval->type = IS_STRING; return T_TRAIT_C; } #line 4457 "Zend/zend_language_scanner.c" yy362: YYDEBUG(362, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy363; if (yych != 'a') goto yy186; yy363: YYDEBUG(363, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy364; if (yych != 's') goto yy186; yy364: YYDEBUG(364, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy365; if (yych != 's') goto yy186; yy365: YYDEBUG(365, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(366, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(367, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(368, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1561 "Zend/zend_language_scanner.l" { const char *class_name = NULL; if (CG(active_class_entry) && (ZEND_ACC_TRAIT == (CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT))) { // This is a hack, we abuse IS_NULL to indicate an invalid value // if __CLASS__ is encountered in a trait, however, we also not that we // should fix it up when we copy the method into an actual class zendlval->value.lval = ZEND_ACC_TRAIT; zendlval->type = IS_NULL; } else { if (CG(active_class_entry)) { class_name = CG(active_class_entry)->name; } if (!class_name) { class_name = ""; } zendlval->value.str.len = strlen(class_name); zendlval->value.str.val = estrndup(class_name, zendlval->value.str.len); zendlval->type = IS_STRING; } return T_CLASS_C; } #line 4514 "Zend/zend_language_scanner.c" yy369: YYDEBUG(369, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy370; if (yych != 'l') goto yy186; yy370: YYDEBUG(370, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy371; if (yych != 't') goto yy186; yy371: YYDEBUG(371, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(372, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy373; if (yych != 'c') goto yy186; yy373: YYDEBUG(373, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy374; if (yych != 'o') goto yy186; yy374: YYDEBUG(374, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy375; if (yych != 'm') goto yy186; yy375: YYDEBUG(375, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy376; if (yych != 'p') goto yy186; yy376: YYDEBUG(376, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy377; if (yych != 'i') goto yy186; yy377: YYDEBUG(377, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy378; if (yych != 'l') goto yy186; yy378: YYDEBUG(378, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy379; if (yych != 'e') goto yy186; yy379: YYDEBUG(379, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy380; if (yych != 'r') goto yy186; yy380: YYDEBUG(380, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(381, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1279 "Zend/zend_language_scanner.l" { return T_HALT_COMPILER; } #line 4580 "Zend/zend_language_scanner.c" yy382: YYDEBUG(382, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy386; if (yych == 's') goto yy386; goto yy186; yy383: YYDEBUG(383, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy384; if (yych != 'e') goto yy186; yy384: YYDEBUG(384, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(385, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1259 "Zend/zend_language_scanner.l" { return T_USE; } #line 4604 "Zend/zend_language_scanner.c" yy386: YYDEBUG(386, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy387; if (yych != 'e') goto yy186; yy387: YYDEBUG(387, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy388; if (yych != 't') goto yy186; yy388: YYDEBUG(388, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(389, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1307 "Zend/zend_language_scanner.l" { return T_UNSET; } #line 4627 "Zend/zend_language_scanner.c" yy390: YYDEBUG(390, *YYCURSOR); ++YYCURSOR; YYFILL(7); yych = *YYCURSOR; yy391: YYDEBUG(391, *YYCURSOR); if (yych <= 'S') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy390; if (yych <= 0x1F) goto yy193; goto yy390; } else { if (yych <= 'A') { if (yych <= '@') goto yy193; goto yy395; } else { if (yych <= 'B') goto yy393; if (yych <= 'C') goto yy193; goto yy398; } } } else { if (yych <= 'I') { if (yych == 'F') goto yy399; if (yych <= 'H') goto yy193; goto yy400; } else { if (yych <= 'O') { if (yych <= 'N') goto yy193; goto yy394; } else { if (yych <= 'Q') goto yy193; if (yych <= 'R') goto yy397; goto yy396; } } } } else { if (yych <= 'f') { if (yych <= 'a') { if (yych == 'U') goto yy392; if (yych <= '`') goto yy193; goto yy395; } else { if (yych <= 'c') { if (yych <= 'b') goto yy393; goto yy193; } else { if (yych <= 'd') goto yy398; if (yych <= 'e') goto yy193; goto yy399; } } } else { if (yych <= 'q') { if (yych <= 'i') { if (yych <= 'h') goto yy193; goto yy400; } else { if (yych == 'o') goto yy394; goto yy193; } } else { if (yych <= 's') { if (yych <= 'r') goto yy397; goto yy396; } else { if (yych != 'u') goto yy193; } } } } yy392: YYDEBUG(392, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy459; if (yych == 'n') goto yy459; goto yy193; yy393: YYDEBUG(393, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'I') goto yy446; if (yych <= 'N') goto yy193; goto yy447; } else { if (yych <= 'i') { if (yych <= 'h') goto yy193; goto yy446; } else { if (yych == 'o') goto yy447; goto yy193; } } yy394: YYDEBUG(394, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy438; if (yych == 'b') goto yy438; goto yy193; yy395: YYDEBUG(395, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy431; if (yych == 'r') goto yy431; goto yy193; yy396: YYDEBUG(396, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy423; if (yych == 't') goto yy423; goto yy193; yy397: YYDEBUG(397, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy421; if (yych == 'e') goto yy421; goto yy193; yy398: YYDEBUG(398, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy417; if (yych == 'o') goto yy417; goto yy193; yy399: YYDEBUG(399, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy410; if (yych == 'l') goto yy410; goto yy193; yy400: YYDEBUG(400, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy401; if (yych != 'n') goto yy193; yy401: YYDEBUG(401, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy402; if (yych != 't') goto yy193; yy402: YYDEBUG(402, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy403; if (yych != 'e') goto yy405; yy403: YYDEBUG(403, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy408; if (yych == 'g') goto yy408; goto yy193; yy404: YYDEBUG(404, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy405: YYDEBUG(405, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy404; goto yy193; } else { if (yych <= ' ') goto yy404; if (yych != ')') goto yy193; } YYDEBUG(406, *YYCURSOR); ++YYCURSOR; YYDEBUG(407, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1207 "Zend/zend_language_scanner.l" { return T_INT_CAST; } #line 4803 "Zend/zend_language_scanner.c" yy408: YYDEBUG(408, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy409; if (yych != 'e') goto yy193; yy409: YYDEBUG(409, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy404; if (yych == 'r') goto yy404; goto yy193; yy410: YYDEBUG(410, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy411; if (yych != 'o') goto yy193; yy411: YYDEBUG(411, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy412; if (yych != 'a') goto yy193; yy412: YYDEBUG(412, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy413; if (yych != 't') goto yy193; yy413: YYDEBUG(413, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(414, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy413; goto yy193; } else { if (yych <= ' ') goto yy413; if (yych != ')') goto yy193; } YYDEBUG(415, *YYCURSOR); ++YYCURSOR; YYDEBUG(416, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1211 "Zend/zend_language_scanner.l" { return T_DOUBLE_CAST; } #line 4851 "Zend/zend_language_scanner.c" yy417: YYDEBUG(417, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy418; if (yych != 'u') goto yy193; yy418: YYDEBUG(418, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy419; if (yych != 'b') goto yy193; yy419: YYDEBUG(419, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy420; if (yych != 'l') goto yy193; yy420: YYDEBUG(420, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy413; if (yych == 'e') goto yy413; goto yy193; yy421: YYDEBUG(421, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy422; if (yych != 'a') goto yy193; yy422: YYDEBUG(422, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy413; if (yych == 'l') goto yy413; goto yy193; yy423: YYDEBUG(423, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy424; if (yych != 'r') goto yy193; yy424: YYDEBUG(424, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy425; if (yych != 'i') goto yy193; yy425: YYDEBUG(425, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy426; if (yych != 'n') goto yy193; yy426: YYDEBUG(426, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy427; if (yych != 'g') goto yy193; yy427: YYDEBUG(427, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(428, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy427; goto yy193; } else { if (yych <= ' ') goto yy427; if (yych != ')') goto yy193; } YYDEBUG(429, *YYCURSOR); ++YYCURSOR; YYDEBUG(430, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1215 "Zend/zend_language_scanner.l" { return T_STRING_CAST; } #line 4925 "Zend/zend_language_scanner.c" yy431: YYDEBUG(431, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy432; if (yych != 'r') goto yy193; yy432: YYDEBUG(432, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy433; if (yych != 'a') goto yy193; yy433: YYDEBUG(433, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy434; if (yych != 'y') goto yy193; yy434: YYDEBUG(434, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(435, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy434; goto yy193; } else { if (yych <= ' ') goto yy434; if (yych != ')') goto yy193; } YYDEBUG(436, *YYCURSOR); ++YYCURSOR; YYDEBUG(437, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1219 "Zend/zend_language_scanner.l" { return T_ARRAY_CAST; } #line 4962 "Zend/zend_language_scanner.c" yy438: YYDEBUG(438, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'J') goto yy439; if (yych != 'j') goto yy193; yy439: YYDEBUG(439, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy440; if (yych != 'e') goto yy193; yy440: YYDEBUG(440, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy441; if (yych != 'c') goto yy193; yy441: YYDEBUG(441, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy442; if (yych != 't') goto yy193; yy442: YYDEBUG(442, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(443, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy442; goto yy193; } else { if (yych <= ' ') goto yy442; if (yych != ')') goto yy193; } YYDEBUG(444, *YYCURSOR); ++YYCURSOR; YYDEBUG(445, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1223 "Zend/zend_language_scanner.l" { return T_OBJECT_CAST; } #line 5004 "Zend/zend_language_scanner.c" yy446: YYDEBUG(446, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy456; if (yych == 'n') goto yy456; goto yy193; yy447: YYDEBUG(447, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy448; if (yych != 'o') goto yy193; yy448: YYDEBUG(448, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy449; if (yych != 'l') goto yy193; yy449: YYDEBUG(449, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy454; if (yych == 'e') goto yy454; goto yy451; yy450: YYDEBUG(450, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy451: YYDEBUG(451, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy450; goto yy193; } else { if (yych <= ' ') goto yy450; if (yych != ')') goto yy193; } YYDEBUG(452, *YYCURSOR); ++YYCURSOR; YYDEBUG(453, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1227 "Zend/zend_language_scanner.l" { return T_BOOL_CAST; } #line 5049 "Zend/zend_language_scanner.c" yy454: YYDEBUG(454, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy455; if (yych != 'a') goto yy193; yy455: YYDEBUG(455, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy450; if (yych == 'n') goto yy450; goto yy193; yy456: YYDEBUG(456, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy457; if (yych != 'a') goto yy193; yy457: YYDEBUG(457, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy458; if (yych != 'r') goto yy193; yy458: YYDEBUG(458, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy427; if (yych == 'y') goto yy427; goto yy193; yy459: YYDEBUG(459, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy460; if (yych != 's') goto yy193; yy460: YYDEBUG(460, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy461; if (yych != 'e') goto yy193; yy461: YYDEBUG(461, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy462; if (yych != 't') goto yy193; yy462: YYDEBUG(462, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(463, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy462; goto yy193; } else { if (yych <= ' ') goto yy462; if (yych != ')') goto yy193; } YYDEBUG(464, *YYCURSOR); ++YYCURSOR; YYDEBUG(465, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1231 "Zend/zend_language_scanner.l" { return T_UNSET_CAST; } #line 5113 "Zend/zend_language_scanner.c" yy466: YYDEBUG(466, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy467; if (yych != 'r') goto yy186; yy467: YYDEBUG(467, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(468, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1203 "Zend/zend_language_scanner.l" { return T_VAR; } #line 5131 "Zend/zend_language_scanner.c" yy469: YYDEBUG(469, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy473; if (yych == 'm') goto yy473; goto yy186; yy470: YYDEBUG(470, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'W') goto yy471; if (yych != 'w') goto yy186; yy471: YYDEBUG(471, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(472, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1195 "Zend/zend_language_scanner.l" { return T_NEW; } #line 5155 "Zend/zend_language_scanner.c" yy473: YYDEBUG(473, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy474; if (yych != 'e') goto yy186; yy474: YYDEBUG(474, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy475; if (yych != 's') goto yy186; yy475: YYDEBUG(475, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy476; if (yych != 'p') goto yy186; yy476: YYDEBUG(476, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy477; if (yych != 'a') goto yy186; yy477: YYDEBUG(477, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy478; if (yych != 'c') goto yy186; yy478: YYDEBUG(478, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy479; if (yych != 'e') goto yy186; yy479: YYDEBUG(479, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(480, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1255 "Zend/zend_language_scanner.l" { return T_NAMESPACE; } #line 5198 "Zend/zend_language_scanner.c" yy481: YYDEBUG(481, *YYCURSOR); ++YYCURSOR; YYDEBUG(482, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1187 "Zend/zend_language_scanner.l" { return T_PAAMAYIM_NEKUDOTAYIM; } #line 5208 "Zend/zend_language_scanner.c" yy483: YYDEBUG(483, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy484: YYDEBUG(484, *YYCURSOR); if (yych <= '\f') { if (yych <= 0x08) goto yy140; if (yych <= '\n') goto yy483; goto yy140; } else { if (yych <= '\r') goto yy483; if (yych == ' ') goto yy483; goto yy140; } yy485: YYDEBUG(485, *YYCURSOR); ++YYCURSOR; YYDEBUG(486, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1363 "Zend/zend_language_scanner.l" { return T_MINUS_EQUAL; } #line 5234 "Zend/zend_language_scanner.c" yy487: YYDEBUG(487, *YYCURSOR); ++YYCURSOR; YYDEBUG(488, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1331 "Zend/zend_language_scanner.l" { return T_DEC; } #line 5244 "Zend/zend_language_scanner.c" yy489: YYDEBUG(489, *YYCURSOR); ++YYCURSOR; YYDEBUG(490, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1157 "Zend/zend_language_scanner.l" { yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC); return T_OBJECT_OPERATOR; } #line 5255 "Zend/zend_language_scanner.c" yy491: YYDEBUG(491, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'I') goto yy498; if (yych <= 'N') goto yy186; goto yy499; } else { if (yych <= 'i') { if (yych <= 'h') goto yy186; goto yy498; } else { if (yych == 'o') goto yy499; goto yy186; } } yy492: YYDEBUG(492, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy493; if (yych != 'b') goto yy186; yy493: YYDEBUG(493, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy494; if (yych != 'l') goto yy186; yy494: YYDEBUG(494, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy495; if (yych != 'i') goto yy186; yy495: YYDEBUG(495, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy496; if (yych != 'c') goto yy186; yy496: YYDEBUG(496, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(497, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1303 "Zend/zend_language_scanner.l" { return T_PUBLIC; } #line 5304 "Zend/zend_language_scanner.c" yy498: YYDEBUG(498, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'V') { if (yych == 'N') goto yy507; if (yych <= 'U') goto yy186; goto yy508; } else { if (yych <= 'n') { if (yych <= 'm') goto yy186; goto yy507; } else { if (yych == 'v') goto yy508; goto yy186; } } yy499: YYDEBUG(499, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy500; if (yych != 't') goto yy186; yy500: YYDEBUG(500, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy501; if (yych != 'e') goto yy186; yy501: YYDEBUG(501, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy502; if (yych != 'c') goto yy186; yy502: YYDEBUG(502, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy503; if (yych != 't') goto yy186; yy503: YYDEBUG(503, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy504; if (yych != 'e') goto yy186; yy504: YYDEBUG(504, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy505; if (yych != 'd') goto yy186; yy505: YYDEBUG(505, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(506, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1299 "Zend/zend_language_scanner.l" { return T_PROTECTED; } #line 5363 "Zend/zend_language_scanner.c" yy507: YYDEBUG(507, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy513; if (yych == 't') goto yy513; goto yy186; yy508: YYDEBUG(508, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy509; if (yych != 'a') goto yy186; yy509: YYDEBUG(509, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy510; if (yych != 't') goto yy186; yy510: YYDEBUG(510, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy511; if (yych != 'e') goto yy186; yy511: YYDEBUG(511, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(512, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1295 "Zend/zend_language_scanner.l" { return T_PRIVATE; } #line 5397 "Zend/zend_language_scanner.c" yy513: YYDEBUG(513, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(514, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1133 "Zend/zend_language_scanner.l" { return T_PRINT; } #line 5410 "Zend/zend_language_scanner.c" yy515: YYDEBUG(515, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy520; if (yych == 'o') goto yy520; goto yy186; yy516: YYDEBUG(516, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy517; if (yych != 't') goto yy186; yy517: YYDEBUG(517, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy518; if (yych != 'o') goto yy186; yy518: YYDEBUG(518, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(519, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1125 "Zend/zend_language_scanner.l" { return T_GOTO; } #line 5439 "Zend/zend_language_scanner.c" yy520: YYDEBUG(520, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy521; if (yych != 'b') goto yy186; yy521: YYDEBUG(521, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy522; if (yych != 'a') goto yy186; yy522: YYDEBUG(522, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy523; if (yych != 'l') goto yy186; yy523: YYDEBUG(523, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(524, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1267 "Zend/zend_language_scanner.l" { return T_GLOBAL; } #line 5467 "Zend/zend_language_scanner.c" yy525: YYDEBUG(525, *YYCURSOR); yych = *++YYCURSOR; if (yych == '<') goto yy533; goto yy193; yy526: YYDEBUG(526, *YYCURSOR); yych = *++YYCURSOR; goto yy180; yy527: YYDEBUG(527, *YYCURSOR); yych = *++YYCURSOR; goto yy178; yy528: YYDEBUG(528, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy529; if (yych != 'e') goto yy186; yy529: YYDEBUG(529, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy530; if (yych != 'a') goto yy186; yy530: YYDEBUG(530, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'K') goto yy531; if (yych != 'k') goto yy186; yy531: YYDEBUG(531, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(532, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1117 "Zend/zend_language_scanner.l" { return T_BREAK; } #line 5508 "Zend/zend_language_scanner.c" yy533: YYDEBUG(533, *YYCURSOR); yych = *++YYCURSOR; if (yych == '<') goto yy269; goto yy193; yy534: YYDEBUG(534, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy541; if (yych == 'a') goto yy541; goto yy186; yy535: YYDEBUG(535, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy536; if (yych != 'i') goto yy186; yy536: YYDEBUG(536, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy537; if (yych != 't') goto yy186; yy537: YYDEBUG(537, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy538; if (yych != 'c') goto yy186; yy538: YYDEBUG(538, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy539; if (yych != 'h') goto yy186; yy539: YYDEBUG(539, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(540, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1101 "Zend/zend_language_scanner.l" { return T_SWITCH; } #line 5552 "Zend/zend_language_scanner.c" yy541: YYDEBUG(541, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy542; if (yych != 't') goto yy186; yy542: YYDEBUG(542, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy543; if (yych != 'i') goto yy186; yy543: YYDEBUG(543, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy544; if (yych != 'c') goto yy186; yy544: YYDEBUG(544, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(545, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1283 "Zend/zend_language_scanner.l" { return T_STATIC; } #line 5580 "Zend/zend_language_scanner.c" yy546: YYDEBUG(546, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy557; if (yych == 's') goto yy557; goto yy186; yy547: YYDEBUG(547, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy555; if (yych == 'd') goto yy555; goto yy186; yy548: YYDEBUG(548, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy551; if (yych == 'r') goto yy551; goto yy186; yy549: YYDEBUG(549, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(550, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1097 "Zend/zend_language_scanner.l" { return T_AS; } #line 5611 "Zend/zend_language_scanner.c" yy551: YYDEBUG(551, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy552; if (yych != 'a') goto yy186; yy552: YYDEBUG(552, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy553; if (yych != 'y') goto yy186; yy553: YYDEBUG(553, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(554, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1319 "Zend/zend_language_scanner.l" { return T_ARRAY; } #line 5634 "Zend/zend_language_scanner.c" yy555: YYDEBUG(555, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(556, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1415 "Zend/zend_language_scanner.l" { return T_LOGICAL_AND; } #line 5647 "Zend/zend_language_scanner.c" yy557: YYDEBUG(557, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy558; if (yych != 't') goto yy186; yy558: YYDEBUG(558, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy559; if (yych != 'r') goto yy186; yy559: YYDEBUG(559, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy560; if (yych != 'a') goto yy186; yy560: YYDEBUG(560, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy561; if (yych != 'c') goto yy186; yy561: YYDEBUG(561, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy562; if (yych != 't') goto yy186; yy562: YYDEBUG(562, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(563, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1287 "Zend/zend_language_scanner.l" { return T_ABSTRACT; } #line 5685 "Zend/zend_language_scanner.c" yy564: YYDEBUG(564, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy565; if (yych != 'i') goto yy186; yy565: YYDEBUG(565, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy566; if (yych != 'l') goto yy186; yy566: YYDEBUG(566, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy567; if (yych != 'e') goto yy186; yy567: YYDEBUG(567, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(568, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1057 "Zend/zend_language_scanner.l" { return T_WHILE; } #line 5713 "Zend/zend_language_scanner.c" yy569: YYDEBUG(569, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(570, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1041 "Zend/zend_language_scanner.l" { return T_IF; } #line 5726 "Zend/zend_language_scanner.c" yy571: YYDEBUG(571, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy613; if (yych == 'p') goto yy613; goto yy186; yy572: YYDEBUG(572, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= 'C') { if (yych <= 'B') goto yy186; goto yy580; } else { if (yych <= 'R') goto yy186; if (yych <= 'S') goto yy578; goto yy579; } } else { if (yych <= 'r') { if (yych == 'c') goto yy580; goto yy186; } else { if (yych <= 's') goto yy578; if (yych <= 't') goto yy579; goto yy186; } } yy573: YYDEBUG(573, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy574; if (yych != 's') goto yy186; yy574: YYDEBUG(574, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy575; if (yych != 'e') goto yy186; yy575: YYDEBUG(575, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy576; if (yych != 't') goto yy186; yy576: YYDEBUG(576, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(577, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1271 "Zend/zend_language_scanner.l" { return T_ISSET; } #line 5782 "Zend/zend_language_scanner.c" yy578: YYDEBUG(578, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy599; if (yych == 't') goto yy599; goto yy186; yy579: YYDEBUG(579, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy592; if (yych == 'e') goto yy592; goto yy186; yy580: YYDEBUG(580, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy581; if (yych != 'l') goto yy186; yy581: YYDEBUG(581, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy582; if (yych != 'u') goto yy186; yy582: YYDEBUG(582, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy583; if (yych != 'd') goto yy186; yy583: YYDEBUG(583, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy584; if (yych != 'e') goto yy186; yy584: YYDEBUG(584, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '9') { if (yych >= '0') goto yy185; } else { if (yych <= '@') goto yy585; if (yych <= 'Z') goto yy185; } } else { if (yych <= '`') { if (yych <= '_') goto yy586; } else { if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy585: YYDEBUG(585, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1239 "Zend/zend_language_scanner.l" { return T_INCLUDE; } #line 5840 "Zend/zend_language_scanner.c" yy586: YYDEBUG(586, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy587; if (yych != 'o') goto yy186; yy587: YYDEBUG(587, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy588; if (yych != 'n') goto yy186; yy588: YYDEBUG(588, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy589; if (yych != 'c') goto yy186; yy589: YYDEBUG(589, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy590; if (yych != 'e') goto yy186; yy590: YYDEBUG(590, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(591, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1243 "Zend/zend_language_scanner.l" { return T_INCLUDE_ONCE; } #line 5873 "Zend/zend_language_scanner.c" yy592: YYDEBUG(592, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy593; if (yych != 'r') goto yy186; yy593: YYDEBUG(593, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy594; if (yych != 'f') goto yy186; yy594: YYDEBUG(594, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy595; if (yych != 'a') goto yy186; yy595: YYDEBUG(595, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy596; if (yych != 'c') goto yy186; yy596: YYDEBUG(596, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy597; if (yych != 'e') goto yy186; yy597: YYDEBUG(597, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(598, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1141 "Zend/zend_language_scanner.l" { return T_INTERFACE; } #line 5911 "Zend/zend_language_scanner.c" yy599: YYDEBUG(599, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych == 'A') goto yy600; if (yych <= 'D') goto yy186; goto yy601; } else { if (yych <= 'a') { if (yych <= '`') goto yy186; } else { if (yych == 'e') goto yy601; goto yy186; } } yy600: YYDEBUG(600, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy607; if (yych == 'n') goto yy607; goto yy186; yy601: YYDEBUG(601, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy602; if (yych != 'a') goto yy186; yy602: YYDEBUG(602, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy603; if (yych != 'd') goto yy186; yy603: YYDEBUG(603, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy604; if (yych != 'o') goto yy186; yy604: YYDEBUG(604, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy605; if (yych != 'f') goto yy186; yy605: YYDEBUG(605, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(606, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1263 "Zend/zend_language_scanner.l" { return T_INSTEADOF; } #line 5965 "Zend/zend_language_scanner.c" yy607: YYDEBUG(607, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy608; if (yych != 'c') goto yy186; yy608: YYDEBUG(608, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy609; if (yych != 'e') goto yy186; yy609: YYDEBUG(609, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy610; if (yych != 'o') goto yy186; yy610: YYDEBUG(610, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy611; if (yych != 'f') goto yy186; yy611: YYDEBUG(611, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(612, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1093 "Zend/zend_language_scanner.l" { return T_INSTANCEOF; } #line 5998 "Zend/zend_language_scanner.c" yy613: YYDEBUG(613, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy614; if (yych != 'l') goto yy186; yy614: YYDEBUG(614, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy615; if (yych != 'e') goto yy186; yy615: YYDEBUG(615, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy616; if (yych != 'm') goto yy186; yy616: YYDEBUG(616, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy617; if (yych != 'e') goto yy186; yy617: YYDEBUG(617, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy618; if (yych != 'n') goto yy186; yy618: YYDEBUG(618, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy619; if (yych != 't') goto yy186; yy619: YYDEBUG(619, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy620; if (yych != 's') goto yy186; yy620: YYDEBUG(620, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(621, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1153 "Zend/zend_language_scanner.l" { return T_IMPLEMENTS; } #line 6046 "Zend/zend_language_scanner.c" yy622: YYDEBUG(622, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy630; if (yych == 'r') goto yy630; goto yy186; yy623: YYDEBUG(623, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych == 'A') goto yy626; if (yych <= 'X') goto yy186; } else { if (yych <= 'a') { if (yych <= '`') goto yy186; goto yy626; } else { if (yych != 'y') goto yy186; } } YYDEBUG(624, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(625, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1029 "Zend/zend_language_scanner.l" { return T_TRY; } #line 6078 "Zend/zend_language_scanner.c" yy626: YYDEBUG(626, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy627; if (yych != 'i') goto yy186; yy627: YYDEBUG(627, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy628; if (yych != 't') goto yy186; yy628: YYDEBUG(628, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(629, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1145 "Zend/zend_language_scanner.l" { return T_TRAIT; } #line 6101 "Zend/zend_language_scanner.c" yy630: YYDEBUG(630, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy631; if (yych != 'o') goto yy186; yy631: YYDEBUG(631, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'W') goto yy632; if (yych != 'w') goto yy186; yy632: YYDEBUG(632, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(633, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1037 "Zend/zend_language_scanner.l" { return T_THROW; } #line 6124 "Zend/zend_language_scanner.c" yy634: YYDEBUG(634, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych == 'Q') goto yy636; if (yych <= 'S') goto yy186; } else { if (yych <= 'q') { if (yych <= 'p') goto yy186; goto yy636; } else { if (yych != 't') goto yy186; } } YYDEBUG(635, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy648; if (yych == 'u') goto yy648; goto yy186; yy636: YYDEBUG(636, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy637; if (yych != 'u') goto yy186; yy637: YYDEBUG(637, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy638; if (yych != 'i') goto yy186; yy638: YYDEBUG(638, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy639; if (yych != 'r') goto yy186; yy639: YYDEBUG(639, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy640; if (yych != 'e') goto yy186; yy640: YYDEBUG(640, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '9') { if (yych >= '0') goto yy185; } else { if (yych <= '@') goto yy641; if (yych <= 'Z') goto yy185; } } else { if (yych <= '`') { if (yych <= '_') goto yy642; } else { if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy641: YYDEBUG(641, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1247 "Zend/zend_language_scanner.l" { return T_REQUIRE; } #line 6189 "Zend/zend_language_scanner.c" yy642: YYDEBUG(642, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy643; if (yych != 'o') goto yy186; yy643: YYDEBUG(643, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy644; if (yych != 'n') goto yy186; yy644: YYDEBUG(644, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy645; if (yych != 'c') goto yy186; yy645: YYDEBUG(645, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy646; if (yych != 'e') goto yy186; yy646: YYDEBUG(646, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(647, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1251 "Zend/zend_language_scanner.l" { return T_REQUIRE_ONCE; } #line 6222 "Zend/zend_language_scanner.c" yy648: YYDEBUG(648, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy649; if (yych != 'r') goto yy186; yy649: YYDEBUG(649, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy650; if (yych != 'n') goto yy186; yy650: YYDEBUG(650, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(651, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1025 "Zend/zend_language_scanner.l" { return T_RETURN; } #line 6245 "Zend/zend_language_scanner.c" yy652: YYDEBUG(652, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= 'L') { if (yych <= 'K') goto yy186; goto yy675; } else { if (yych <= 'R') goto yy186; if (yych <= 'S') goto yy674; goto yy673; } } else { if (yych <= 'r') { if (yych == 'l') goto yy675; goto yy186; } else { if (yych <= 's') goto yy674; if (yych <= 't') goto yy673; goto yy186; } } yy653: YYDEBUG(653, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'A') goto yy665; if (yych <= 'N') goto yy186; goto yy666; } else { if (yych <= 'a') { if (yych <= '`') goto yy186; goto yy665; } else { if (yych == 'o') goto yy666; goto yy186; } } yy654: YYDEBUG(654, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy655; if (yych != 'n') goto yy186; yy655: YYDEBUG(655, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= 'R') goto yy186; if (yych >= 'T') goto yy657; } else { if (yych <= 'r') goto yy186; if (yych <= 's') goto yy656; if (yych <= 't') goto yy657; goto yy186; } yy656: YYDEBUG(656, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy663; if (yych == 't') goto yy663; goto yy186; yy657: YYDEBUG(657, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy658; if (yych != 'i') goto yy186; yy658: YYDEBUG(658, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy659; if (yych != 'n') goto yy186; yy659: YYDEBUG(659, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy660; if (yych != 'u') goto yy186; yy660: YYDEBUG(660, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy661; if (yych != 'e') goto yy186; yy661: YYDEBUG(661, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(662, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1121 "Zend/zend_language_scanner.l" { return T_CONTINUE; } #line 6339 "Zend/zend_language_scanner.c" yy663: YYDEBUG(663, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(664, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1021 "Zend/zend_language_scanner.l" { return T_CONST; } #line 6352 "Zend/zend_language_scanner.c" yy665: YYDEBUG(665, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy670; if (yych == 's') goto yy670; goto yy186; yy666: YYDEBUG(666, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy667; if (yych != 'n') goto yy186; yy667: YYDEBUG(667, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy668; if (yych != 'e') goto yy186; yy668: YYDEBUG(668, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(669, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1199 "Zend/zend_language_scanner.l" { return T_CLONE; } #line 6381 "Zend/zend_language_scanner.c" yy670: YYDEBUG(670, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy671; if (yych != 's') goto yy186; yy671: YYDEBUG(671, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(672, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1137 "Zend/zend_language_scanner.l" { return T_CLASS; } #line 6399 "Zend/zend_language_scanner.c" yy673: YYDEBUG(673, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy684; if (yych == 'c') goto yy684; goto yy186; yy674: YYDEBUG(674, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy682; if (yych == 'e') goto yy682; goto yy186; yy675: YYDEBUG(675, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy676; if (yych != 'l') goto yy186; yy676: YYDEBUG(676, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy677; if (yych != 'a') goto yy186; yy677: YYDEBUG(677, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy678; if (yych != 'b') goto yy186; yy678: YYDEBUG(678, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy679; if (yych != 'l') goto yy186; yy679: YYDEBUG(679, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy680; if (yych != 'e') goto yy186; yy680: YYDEBUG(680, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(681, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1323 "Zend/zend_language_scanner.l" { return T_CALLABLE; } #line 6449 "Zend/zend_language_scanner.c" yy682: YYDEBUG(682, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(683, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1109 "Zend/zend_language_scanner.l" { return T_CASE; } #line 6462 "Zend/zend_language_scanner.c" yy684: YYDEBUG(684, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy685; if (yych != 'h') goto yy186; yy685: YYDEBUG(685, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(686, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1033 "Zend/zend_language_scanner.l" { return T_CATCH; } #line 6480 "Zend/zend_language_scanner.c" yy687: YYDEBUG(687, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy704; if (yych == 'n') goto yy704; goto yy186; yy688: YYDEBUG(688, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy697; if (yych == 'r') goto yy697; goto yy186; yy689: YYDEBUG(689, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy690; if (yych != 'n') goto yy186; yy690: YYDEBUG(690, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy691; if (yych != 'c') goto yy186; yy691: YYDEBUG(691, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy692; if (yych != 't') goto yy186; yy692: YYDEBUG(692, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy693; if (yych != 'i') goto yy186; yy693: YYDEBUG(693, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy694; if (yych != 'o') goto yy186; yy694: YYDEBUG(694, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy695; if (yych != 'n') goto yy186; yy695: YYDEBUG(695, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(696, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1017 "Zend/zend_language_scanner.l" { return T_FUNCTION; } #line 6535 "Zend/zend_language_scanner.c" yy697: YYDEBUG(697, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '@') { if (yych <= '/') goto yy698; if (yych <= '9') goto yy185; } else { if (yych == 'E') goto yy699; if (yych <= 'Z') goto yy185; } } else { if (yych <= 'd') { if (yych != '`') goto yy185; } else { if (yych <= 'e') goto yy699; if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy698: YYDEBUG(698, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1069 "Zend/zend_language_scanner.l" { return T_FOR; } #line 6563 "Zend/zend_language_scanner.c" yy699: YYDEBUG(699, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy700; if (yych != 'a') goto yy186; yy700: YYDEBUG(700, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy701; if (yych != 'c') goto yy186; yy701: YYDEBUG(701, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy702; if (yych != 'h') goto yy186; yy702: YYDEBUG(702, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(703, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1077 "Zend/zend_language_scanner.l" { return T_FOREACH; } #line 6591 "Zend/zend_language_scanner.c" yy704: YYDEBUG(704, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy705; if (yych != 'a') goto yy186; yy705: YYDEBUG(705, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy706; if (yych != 'l') goto yy186; yy706: YYDEBUG(706, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(707, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1291 "Zend/zend_language_scanner.l" { return T_FINAL; } #line 6614 "Zend/zend_language_scanner.c" yy708: YYDEBUG(708, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'F') { if (yych == 'C') goto yy714; if (yych <= 'E') goto yy186; goto yy715; } else { if (yych <= 'c') { if (yych <= 'b') goto yy186; goto yy714; } else { if (yych == 'f') goto yy715; goto yy186; } } yy709: YYDEBUG(709, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy712; if (yych == 'e') goto yy712; goto yy186; yy710: YYDEBUG(710, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(711, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1065 "Zend/zend_language_scanner.l" { return T_DO; } #line 6649 "Zend/zend_language_scanner.c" yy712: YYDEBUG(712, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(713, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1013 "Zend/zend_language_scanner.l" { return T_EXIT; } #line 6662 "Zend/zend_language_scanner.c" yy714: YYDEBUG(714, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy721; if (yych == 'l') goto yy721; goto yy186; yy715: YYDEBUG(715, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy716; if (yych != 'a') goto yy186; yy716: YYDEBUG(716, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy717; if (yych != 'u') goto yy186; yy717: YYDEBUG(717, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy718; if (yych != 'l') goto yy186; yy718: YYDEBUG(718, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy719; if (yych != 't') goto yy186; yy719: YYDEBUG(719, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(720, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1113 "Zend/zend_language_scanner.l" { return T_DEFAULT; } #line 6701 "Zend/zend_language_scanner.c" yy721: YYDEBUG(721, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy722; if (yych != 'a') goto yy186; yy722: YYDEBUG(722, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy723; if (yych != 'r') goto yy186; yy723: YYDEBUG(723, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy724; if (yych != 'e') goto yy186; yy724: YYDEBUG(724, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(725, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1085 "Zend/zend_language_scanner.l" { return T_DECLARE; } #line 6729 "Zend/zend_language_scanner.c" yy726: YYDEBUG(726, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy788; if (yych == 'h') goto yy788; goto yy186; yy727: YYDEBUG(727, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy782; if (yych == 's') goto yy782; goto yy186; yy728: YYDEBUG(728, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy778; if (yych == 'p') goto yy778; goto yy186; yy729: YYDEBUG(729, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy744; if (yych == 'd') goto yy744; goto yy186; yy730: YYDEBUG(730, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy741; if (yych == 'a') goto yy741; goto yy186; yy731: YYDEBUG(731, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych == 'I') goto yy732; if (yych <= 'S') goto yy186; goto yy733; } else { if (yych <= 'i') { if (yych <= 'h') goto yy186; } else { if (yych == 't') goto yy733; goto yy186; } } yy732: YYDEBUG(732, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy739; if (yych == 't') goto yy739; goto yy186; yy733: YYDEBUG(733, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy734; if (yych != 'e') goto yy186; yy734: YYDEBUG(734, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy735; if (yych != 'n') goto yy186; yy735: YYDEBUG(735, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy736; if (yych != 'd') goto yy186; yy736: YYDEBUG(736, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy737; if (yych != 's') goto yy186; yy737: YYDEBUG(737, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(738, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1149 "Zend/zend_language_scanner.l" { return T_EXTENDS; } #line 6813 "Zend/zend_language_scanner.c" yy739: YYDEBUG(739, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(740, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1009 "Zend/zend_language_scanner.l" { return T_EXIT; } #line 6826 "Zend/zend_language_scanner.c" yy741: YYDEBUG(741, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy742; if (yych != 'l') goto yy186; yy742: YYDEBUG(742, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(743, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1235 "Zend/zend_language_scanner.l" { return T_EVAL; } #line 6844 "Zend/zend_language_scanner.c" yy744: YYDEBUG(744, *YYCURSOR); yych = *++YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case 'D': case 'd': goto yy745; case 'F': case 'f': goto yy746; case 'I': case 'i': goto yy747; case 'S': case 's': goto yy748; case 'W': case 'w': goto yy749; default: goto yy186; } yy745: YYDEBUG(745, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy771; if (yych == 'e') goto yy771; goto yy186; yy746: YYDEBUG(746, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy763; if (yych == 'o') goto yy763; goto yy186; yy747: YYDEBUG(747, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy761; if (yych == 'f') goto yy761; goto yy186; yy748: YYDEBUG(748, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'W') goto yy755; if (yych == 'w') goto yy755; goto yy186; yy749: YYDEBUG(749, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy750; if (yych != 'h') goto yy186; yy750: YYDEBUG(750, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy751; if (yych != 'i') goto yy186; yy751: YYDEBUG(751, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy752; if (yych != 'l') goto yy186; yy752: YYDEBUG(752, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy753; if (yych != 'e') goto yy186; yy753: YYDEBUG(753, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(754, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1061 "Zend/zend_language_scanner.l" { return T_ENDWHILE; } #line 6918 "Zend/zend_language_scanner.c" yy755: YYDEBUG(755, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy756; if (yych != 'i') goto yy186; yy756: YYDEBUG(756, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy757; if (yych != 't') goto yy186; yy757: YYDEBUG(757, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy758; if (yych != 'c') goto yy186; yy758: YYDEBUG(758, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy759; if (yych != 'h') goto yy186; yy759: YYDEBUG(759, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(760, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1105 "Zend/zend_language_scanner.l" { return T_ENDSWITCH; } #line 6951 "Zend/zend_language_scanner.c" yy761: YYDEBUG(761, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(762, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1049 "Zend/zend_language_scanner.l" { return T_ENDIF; } #line 6964 "Zend/zend_language_scanner.c" yy763: YYDEBUG(763, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy764; if (yych != 'r') goto yy186; yy764: YYDEBUG(764, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '@') { if (yych <= '/') goto yy765; if (yych <= '9') goto yy185; } else { if (yych == 'E') goto yy766; if (yych <= 'Z') goto yy185; } } else { if (yych <= 'd') { if (yych != '`') goto yy185; } else { if (yych <= 'e') goto yy766; if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy765: YYDEBUG(765, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1073 "Zend/zend_language_scanner.l" { return T_ENDFOR; } #line 6997 "Zend/zend_language_scanner.c" yy766: YYDEBUG(766, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy767; if (yych != 'a') goto yy186; yy767: YYDEBUG(767, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy768; if (yych != 'c') goto yy186; yy768: YYDEBUG(768, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy769; if (yych != 'h') goto yy186; yy769: YYDEBUG(769, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(770, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1081 "Zend/zend_language_scanner.l" { return T_ENDFOREACH; } #line 7025 "Zend/zend_language_scanner.c" yy771: YYDEBUG(771, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy772; if (yych != 'c') goto yy186; yy772: YYDEBUG(772, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy773; if (yych != 'l') goto yy186; yy773: YYDEBUG(773, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy774; if (yych != 'a') goto yy186; yy774: YYDEBUG(774, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy775; if (yych != 'r') goto yy186; yy775: YYDEBUG(775, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy776; if (yych != 'e') goto yy186; yy776: YYDEBUG(776, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(777, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1089 "Zend/zend_language_scanner.l" { return T_ENDDECLARE; } #line 7063 "Zend/zend_language_scanner.c" yy778: YYDEBUG(778, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy779; if (yych != 't') goto yy186; yy779: YYDEBUG(779, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy780; if (yych != 'y') goto yy186; yy780: YYDEBUG(780, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(781, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1275 "Zend/zend_language_scanner.l" { return T_EMPTY; } #line 7086 "Zend/zend_language_scanner.c" yy782: YYDEBUG(782, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy783; if (yych != 'e') goto yy186; yy783: YYDEBUG(783, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '@') { if (yych <= '/') goto yy784; if (yych <= '9') goto yy185; } else { if (yych == 'I') goto yy785; if (yych <= 'Z') goto yy185; } } else { if (yych <= 'h') { if (yych != '`') goto yy185; } else { if (yych <= 'i') goto yy785; if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy784: YYDEBUG(784, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1053 "Zend/zend_language_scanner.l" { return T_ELSE; } #line 7119 "Zend/zend_language_scanner.c" yy785: YYDEBUG(785, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy786; if (yych != 'f') goto yy186; yy786: YYDEBUG(786, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(787, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1045 "Zend/zend_language_scanner.l" { return T_ELSEIF; } #line 7137 "Zend/zend_language_scanner.c" yy788: YYDEBUG(788, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy789; if (yych != 'o') goto yy186; yy789: YYDEBUG(789, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(790, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1129 "Zend/zend_language_scanner.l" { return T_ECHO; } #line 7155 "Zend/zend_language_scanner.c" } /* *********************************** */ yyc_ST_LOOKING_FOR_PROPERTY: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 0, 0, 0, 0, 0, 0, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 0, 0, 0, 0, 64, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 0, 0, 0, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, }; YYDEBUG(791, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych <= '-') { if (yych <= '\r') { if (yych <= 0x08) goto yy799; if (yych <= '\n') goto yy793; if (yych <= '\f') goto yy799; } else { if (yych == ' ') goto yy793; if (yych <= ',') goto yy799; goto yy795; } } else { if (yych <= '_') { if (yych <= '@') goto yy799; if (yych <= 'Z') goto yy797; if (yych <= '^') goto yy799; goto yy797; } else { if (yych <= '`') goto yy799; if (yych <= 'z') goto yy797; if (yych <= '~') goto yy799; goto yy797; } } yy793: YYDEBUG(793, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy805; yy794: YYDEBUG(794, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1162 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; HANDLE_NEWLINES(yytext, yyleng); return T_WHITESPACE; } #line 7236 "Zend/zend_language_scanner.c" yy795: YYDEBUG(795, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '>') goto yy802; yy796: YYDEBUG(796, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1181 "Zend/zend_language_scanner.l" { yyless(0); yy_pop_state(TSRMLS_C); goto restart; } #line 7250 "Zend/zend_language_scanner.c" yy797: YYDEBUG(797, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy801; yy798: YYDEBUG(798, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1174 "Zend/zend_language_scanner.l" { yy_pop_state(TSRMLS_C); zend_copy_value(zendlval, yytext, yyleng); zendlval->type = IS_STRING; return T_STRING; } #line 7266 "Zend/zend_language_scanner.c" yy799: YYDEBUG(799, *YYCURSOR); yych = *++YYCURSOR; goto yy796; yy800: YYDEBUG(800, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy801: YYDEBUG(801, *YYCURSOR); if (yybm[0+yych] & 64) { goto yy800; } goto yy798; yy802: YYDEBUG(802, *YYCURSOR); ++YYCURSOR; YYDEBUG(803, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1170 "Zend/zend_language_scanner.l" { return T_OBJECT_OPERATOR; } #line 7291 "Zend/zend_language_scanner.c" yy804: YYDEBUG(804, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy805: YYDEBUG(805, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy804; } goto yy794; } /* *********************************** */ yyc_ST_LOOKING_FOR_VARNAME: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; YYDEBUG(806, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy810; if (yych <= 'Z') goto yy808; if (yych <= '^') goto yy810; } else { if (yych <= '`') goto yy810; if (yych <= 'z') goto yy808; if (yych <= '~') goto yy810; } yy808: YYDEBUG(808, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy813; yy809: YYDEBUG(809, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1457 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, yytext, yyleng); zendlval->type = IS_STRING; yy_pop_state(TSRMLS_C); yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); return T_STRING_VARNAME; } #line 7369 "Zend/zend_language_scanner.c" yy810: YYDEBUG(810, *YYCURSOR); ++YYCURSOR; YYDEBUG(811, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1466 "Zend/zend_language_scanner.l" { yyless(0); yy_pop_state(TSRMLS_C); yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); goto restart; } #line 7382 "Zend/zend_language_scanner.c" yy812: YYDEBUG(812, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy813: YYDEBUG(813, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy812; } goto yy809; } /* *********************************** */ yyc_ST_NOWDOC: YYDEBUG(814, *YYCURSOR); YYFILL(1); yych = *YYCURSOR; YYDEBUG(816, *YYCURSOR); ++YYCURSOR; YYDEBUG(817, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2340 "Zend/zend_language_scanner.l" { int newline = 0; if (YYCURSOR > YYLIMIT) { return 0; } YYCURSOR--; while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '\r': if (*YYCURSOR == '\n') { YYCURSOR++; } /* fall through */ case '\n': /* Check for ending label on the next line */ if (IS_LABEL_START(*YYCURSOR) && CG(heredoc_len) < YYLIMIT - YYCURSOR && !memcmp(YYCURSOR, CG(heredoc), CG(heredoc_len))) { YYCTYPE *end = YYCURSOR + CG(heredoc_len); if (*end == ';') { end++; } if (*end == '\n' || *end == '\r') { /* newline before label will be subtracted from returned text, but * yyleng/yytext will include it, for zend_highlight/strip, tokenizer, etc. */ if (YYCURSOR[-2] == '\r' && YYCURSOR[-1] == '\n') { newline = 2; /* Windows newline */ } else { newline = 1; } CG(increment_lineno) = 1; /* For newline before label */ BEGIN(ST_END_HEREDOC); goto nowdoc_scan_done; } } /* fall through */ default: continue; } } nowdoc_scan_done: yyleng = YYCURSOR - SCNG(yy_text); zend_copy_value(zendlval, yytext, yyleng - newline); zendlval->type = IS_STRING; HANDLE_NEWLINES(yytext, yyleng - newline); return T_ENCAPSED_AND_WHITESPACE; } #line 7459 "Zend/zend_language_scanner.c" /* *********************************** */ yyc_ST_VAR_OFFSET: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 240, 240, 112, 112, 112, 112, 112, 112, 112, 112, 0, 0, 0, 0, 0, 0, 0, 80, 80, 80, 80, 80, 80, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 16, 0, 80, 80, 80, 80, 80, 80, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, }; YYDEBUG(818, *YYCURSOR); YYFILL(3); yych = *YYCURSOR; if (yych <= '/') { if (yych <= ' ') { if (yych <= '\f') { if (yych <= 0x08) goto yy832; if (yych <= '\n') goto yy828; goto yy832; } else { if (yych <= '\r') goto yy828; if (yych <= 0x1F) goto yy832; goto yy828; } } else { if (yych <= '$') { if (yych <= '"') goto yy827; if (yych <= '#') goto yy828; goto yy823; } else { if (yych == '\'') goto yy828; goto yy827; } } } else { if (yych <= '\\') { if (yych <= '@') { if (yych <= '0') goto yy820; if (yych <= '9') goto yy822; goto yy827; } else { if (yych <= 'Z') goto yy830; if (yych <= '[') goto yy827; goto yy828; } } else { if (yych <= '_') { if (yych <= ']') goto yy825; if (yych <= '^') goto yy827; goto yy830; } else { if (yych <= '`') goto yy827; if (yych <= 'z') goto yy830; if (yych <= '~') goto yy827; goto yy830; } } } yy820: YYDEBUG(820, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'W') { if (yych <= '9') { if (yych >= '0') goto yy844; } else { if (yych == 'B') goto yy841; } } else { if (yych <= 'b') { if (yych <= 'X') goto yy843; if (yych >= 'b') goto yy841; } else { if (yych == 'x') goto yy843; } } yy821: YYDEBUG(821, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1536 "Zend/zend_language_scanner.l" { /* Offset could be treated as a long */ if (yyleng < MAX_LENGTH_OF_LONG - 1 || (yyleng == MAX_LENGTH_OF_LONG - 1 && strcmp(yytext, long_min_digits) < 0)) { zendlval->value.lval = strtol(yytext, NULL, 10); zendlval->type = IS_LONG; } else { zendlval->value.str.val = (char *)estrndup(yytext, yyleng); zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; } return T_NUM_STRING; } #line 7578 "Zend/zend_language_scanner.c" yy822: YYDEBUG(822, *YYCURSOR); yych = *++YYCURSOR; goto yy840; yy823: YYDEBUG(823, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '_') { if (yych <= '@') goto yy824; if (yych <= 'Z') goto yy836; if (yych >= '_') goto yy836; } else { if (yych <= '`') goto yy824; if (yych <= 'z') goto yy836; if (yych >= 0x7F) goto yy836; } yy824: YYDEBUG(824, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1868 "Zend/zend_language_scanner.l" { /* Only '[' can be valid, but returning other tokens will allow a more explicit parse error */ return yytext[0]; } #line 7603 "Zend/zend_language_scanner.c" yy825: YYDEBUG(825, *YYCURSOR); ++YYCURSOR; YYDEBUG(826, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1863 "Zend/zend_language_scanner.l" { yy_pop_state(TSRMLS_C); return ']'; } #line 7614 "Zend/zend_language_scanner.c" yy827: YYDEBUG(827, *YYCURSOR); yych = *++YYCURSOR; goto yy824; yy828: YYDEBUG(828, *YYCURSOR); ++YYCURSOR; YYDEBUG(829, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1873 "Zend/zend_language_scanner.l" { /* Invalid rule to return a more explicit parse error with proper line number */ yyless(0); yy_pop_state(TSRMLS_C); return T_ENCAPSED_AND_WHITESPACE; } #line 7631 "Zend/zend_language_scanner.c" yy830: YYDEBUG(830, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy835; yy831: YYDEBUG(831, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1880 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, yytext, yyleng); zendlval->type = IS_STRING; return T_STRING; } #line 7646 "Zend/zend_language_scanner.c" yy832: YYDEBUG(832, *YYCURSOR); ++YYCURSOR; YYDEBUG(833, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2396 "Zend/zend_language_scanner.l" { if (YYCURSOR > YYLIMIT) { return 0; } zend_error(E_COMPILE_WARNING,"Unexpected character in input: '%c' (ASCII=%d) state=%d", yytext[0], yytext[0], YYSTATE); goto restart; } #line 7661 "Zend/zend_language_scanner.c" yy834: YYDEBUG(834, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy835: YYDEBUG(835, *YYCURSOR); if (yybm[0+yych] & 16) { goto yy834; } goto yy831; yy836: YYDEBUG(836, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(837, *YYCURSOR); if (yych <= '^') { if (yych <= '9') { if (yych >= '0') goto yy836; } else { if (yych <= '@') goto yy838; if (yych <= 'Z') goto yy836; } } else { if (yych <= '`') { if (yych <= '_') goto yy836; } else { if (yych <= 'z') goto yy836; if (yych >= 0x7F) goto yy836; } } yy838: YYDEBUG(838, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1857 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 7703 "Zend/zend_language_scanner.c" yy839: YYDEBUG(839, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy840: YYDEBUG(840, *YYCURSOR); if (yybm[0+yych] & 32) { goto yy839; } goto yy821; yy841: YYDEBUG(841, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 128) { goto yy849; } yy842: YYDEBUG(842, *YYCURSOR); YYCURSOR = YYMARKER; goto yy821; yy843: YYDEBUG(843, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 64) { goto yy847; } goto yy842; yy844: YYDEBUG(844, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(845, *YYCURSOR); if (yych <= '/') goto yy846; if (yych <= '9') goto yy844; yy846: YYDEBUG(846, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1548 "Zend/zend_language_scanner.l" { /* Offset must be treated as a string */ zendlval->value.str.val = (char *)estrndup(yytext, yyleng); zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; return T_NUM_STRING; } #line 7750 "Zend/zend_language_scanner.c" yy847: YYDEBUG(847, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(848, *YYCURSOR); if (yybm[0+yych] & 64) { goto yy847; } goto yy846; yy849: YYDEBUG(849, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(850, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy849; } goto yy846; } } #line 2405 "Zend/zend_language_scanner.l" } /* Generated by re2c 0.13.5 on Tue Jan 17 11:54:12 2012 */ #line 1 "Zend/zend_language_scanner.l" /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2012 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Marcus Boerger <[email protected]> | | Nuno Lopes <[email protected]> | | Scott MacVicar <[email protected]> | | Flex version authors: | | Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #if 0 # define YYDEBUG(s, c) printf("state: %d char: %c\n", s, c) #else # define YYDEBUG(s, c) #endif #include "zend_language_scanner_defs.h" #include <errno.h> #include "zend.h" #include "zend_alloc.h" #include <zend_language_parser.h> #include "zend_compile.h" #include "zend_language_scanner.h" #include "zend_highlight.h" #include "zend_constants.h" #include "zend_variables.h" #include "zend_operators.h" #include "zend_API.h" #include "zend_strtod.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "tsrm_config_common.h" #define YYCTYPE unsigned char #define YYFILL(n) { if ((YYCURSOR + n) >= (YYLIMIT + ZEND_MMAP_AHEAD)) { return 0; } } #define YYCURSOR SCNG(yy_cursor) #define YYLIMIT SCNG(yy_limit) #define YYMARKER SCNG(yy_marker) #define YYGETCONDITION() SCNG(yy_state) #define YYSETCONDITION(s) SCNG(yy_state) = s #define STATE(name) yyc##name /* emulate flex constructs */ #define BEGIN(state) YYSETCONDITION(STATE(state)) #define YYSTATE YYGETCONDITION() #define yytext ((char*)SCNG(yy_text)) #define yyleng SCNG(yy_leng) #define yyless(x) do { YYCURSOR = (unsigned char*)yytext + x; \ yyleng = (unsigned int)x; } while(0) #define yymore() goto yymore_restart /* perform sanity check. If this message is triggered you should increase the ZEND_MMAP_AHEAD value in the zend_streams.h file */ #define YYMAXFILL 16 #if ZEND_MMAP_AHEAD < YYMAXFILL # error ZEND_MMAP_AHEAD should be greater than or equal to YYMAXFILL #endif #ifdef HAVE_STDARG_H # include <stdarg.h> #endif #ifdef HAVE_UNISTD_H # include <unistd.h> #endif /* Globals Macros */ #define SCNG LANG_SCNG #ifdef ZTS ZEND_API ts_rsrc_id language_scanner_globals_id; #else ZEND_API zend_php_scanner_globals language_scanner_globals; #endif #define HANDLE_NEWLINES(s, l) \ do { \ char *p = (s), *boundary = p+(l); \ \ while (p<boundary) { \ if (*p == '\n' || (*p == '\r' && (*(p+1) != '\n'))) { \ CG(zend_lineno)++; \ } \ p++; \ } \ } while (0) #define HANDLE_NEWLINE(c) \ { \ if (c == '\n' || c == '\r') { \ CG(zend_lineno)++; \ } \ } /* To save initial string length after scanning to first variable, CG(doc_comment_len) can be reused */ #define SET_DOUBLE_QUOTES_SCANNED_LENGTH(len) CG(doc_comment_len) = (len) #define GET_DOUBLE_QUOTES_SCANNED_LENGTH() CG(doc_comment_len) #define IS_LABEL_START(c) (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z') || (c) == '_' || (c) >= 0x7F) #define ZEND_IS_OCT(c) ((c)>='0' && (c)<='7') #define ZEND_IS_HEX(c) (((c)>='0' && (c)<='9') || ((c)>='a' && (c)<='f') || ((c)>='A' && (c)<='F')) BEGIN_EXTERN_C() static size_t encoding_filter_script_to_internal(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) { const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding(TSRMLS_C); assert(internal_encoding && zend_multibyte_check_lexer_compatibility(internal_encoding)); return zend_multibyte_encoding_converter(to, to_length, from, from_length, internal_encoding, LANG_SCNG(script_encoding) TSRMLS_CC); } static size_t encoding_filter_script_to_intermediate(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) { return zend_multibyte_encoding_converter(to, to_length, from, from_length, zend_multibyte_encoding_utf8, LANG_SCNG(script_encoding) TSRMLS_CC); } static size_t encoding_filter_intermediate_to_script(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) { return zend_multibyte_encoding_converter(to, to_length, from, from_length, LANG_SCNG(script_encoding), zend_multibyte_encoding_utf8 TSRMLS_CC); } static size_t encoding_filter_intermediate_to_internal(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) { const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding(TSRMLS_C); assert(internal_encoding && zend_multibyte_check_lexer_compatibility(internal_encoding)); return zend_multibyte_encoding_converter(to, to_length, from, from_length, internal_encoding, zend_multibyte_encoding_utf8 TSRMLS_CC); } static void _yy_push_state(int new_state TSRMLS_DC) { zend_stack_push(&SCNG(state_stack), (void *) &YYGETCONDITION(), sizeof(int)); YYSETCONDITION(new_state); } #define yy_push_state(state_and_tsrm) _yy_push_state(yyc##state_and_tsrm) static void yy_pop_state(TSRMLS_D) { int *stack_state; zend_stack_top(&SCNG(state_stack), (void **) &stack_state); YYSETCONDITION(*stack_state); zend_stack_del_top(&SCNG(state_stack)); } static void yy_scan_buffer(char *str, unsigned int len TSRMLS_DC) { YYCURSOR = (YYCTYPE*)str; YYLIMIT = YYCURSOR + len; if (!SCNG(yy_start)) { SCNG(yy_start) = YYCURSOR; } } void startup_scanner(TSRMLS_D) { CG(parse_error) = 0; CG(heredoc) = NULL; CG(heredoc_len) = 0; CG(doc_comment) = NULL; CG(doc_comment_len) = 0; zend_stack_init(&SCNG(state_stack)); } void shutdown_scanner(TSRMLS_D) { if (CG(heredoc)) { efree(CG(heredoc)); CG(heredoc_len)=0; } CG(parse_error) = 0; zend_stack_destroy(&SCNG(state_stack)); RESET_DOC_COMMENT(); } ZEND_API void zend_save_lexical_state(zend_lex_state *lex_state TSRMLS_DC) { lex_state->yy_leng = SCNG(yy_leng); lex_state->yy_start = SCNG(yy_start); lex_state->yy_text = SCNG(yy_text); lex_state->yy_cursor = SCNG(yy_cursor); lex_state->yy_marker = SCNG(yy_marker); lex_state->yy_limit = SCNG(yy_limit); lex_state->state_stack = SCNG(state_stack); zend_stack_init(&SCNG(state_stack)); lex_state->in = SCNG(yy_in); lex_state->yy_state = YYSTATE; lex_state->filename = zend_get_compiled_filename(TSRMLS_C); lex_state->lineno = CG(zend_lineno); lex_state->script_org = SCNG(script_org); lex_state->script_org_size = SCNG(script_org_size); lex_state->script_filtered = SCNG(script_filtered); lex_state->script_filtered_size = SCNG(script_filtered_size); lex_state->input_filter = SCNG(input_filter); lex_state->output_filter = SCNG(output_filter); lex_state->script_encoding = SCNG(script_encoding); } ZEND_API void zend_restore_lexical_state(zend_lex_state *lex_state TSRMLS_DC) { SCNG(yy_leng) = lex_state->yy_leng; SCNG(yy_start) = lex_state->yy_start; SCNG(yy_text) = lex_state->yy_text; SCNG(yy_cursor) = lex_state->yy_cursor; SCNG(yy_marker) = lex_state->yy_marker; SCNG(yy_limit) = lex_state->yy_limit; zend_stack_destroy(&SCNG(state_stack)); SCNG(state_stack) = lex_state->state_stack; SCNG(yy_in) = lex_state->in; YYSETCONDITION(lex_state->yy_state); CG(zend_lineno) = lex_state->lineno; zend_restore_compiled_filename(lex_state->filename TSRMLS_CC); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } SCNG(script_org) = lex_state->script_org; SCNG(script_org_size) = lex_state->script_org_size; SCNG(script_filtered) = lex_state->script_filtered; SCNG(script_filtered_size) = lex_state->script_filtered_size; SCNG(input_filter) = lex_state->input_filter; SCNG(output_filter) = lex_state->output_filter; SCNG(script_encoding) = lex_state->script_encoding; if (CG(heredoc)) { efree(CG(heredoc)); CG(heredoc) = NULL; CG(heredoc_len) = 0; } } ZEND_API void zend_destroy_file_handle(zend_file_handle *file_handle TSRMLS_DC) { zend_llist_del_element(&CG(open_files), file_handle, (int (*)(void *, void *)) zend_compare_file_handles); /* zend_file_handle_dtor() operates on the copy, so we have to NULLify the original here */ file_handle->opened_path = NULL; if (file_handle->free_filename) { file_handle->filename = NULL; } } #define BOM_UTF32_BE "\x00\x00\xfe\xff" #define BOM_UTF32_LE "\xff\xfe\x00\x00" #define BOM_UTF16_BE "\xfe\xff" #define BOM_UTF16_LE "\xff\xfe" #define BOM_UTF8 "\xef\xbb\xbf" static const zend_encoding *zend_multibyte_detect_utf_encoding(const unsigned char *script, size_t script_size TSRMLS_DC) { const unsigned char *p; int wchar_size = 2; int le = 0; /* utf-16 or utf-32? */ p = script; while ((p-script) < script_size) { p = memchr(p, 0, script_size-(p-script)-2); if (!p) { break; } if (*(p+1) == '\0' && *(p+2) == '\0') { wchar_size = 4; break; } /* searching for UTF-32 specific byte orders, so this will do */ p += 4; } /* BE or LE? */ p = script; while ((p-script) < script_size) { if (*p == '\0' && *(p+wchar_size-1) != '\0') { /* BE */ le = 0; break; } else if (*p != '\0' && *(p+wchar_size-1) == '\0') { /* LE* */ le = 1; break; } p += wchar_size; } if (wchar_size == 2) { return le ? zend_multibyte_encoding_utf16le : zend_multibyte_encoding_utf16be; } else { return le ? zend_multibyte_encoding_utf32le : zend_multibyte_encoding_utf32be; } return NULL; } static const zend_encoding* zend_multibyte_detect_unicode(TSRMLS_D) { const zend_encoding *script_encoding = NULL; int bom_size; unsigned char *pos1, *pos2; if (LANG_SCNG(script_org_size) < sizeof(BOM_UTF32_LE)-1) { return NULL; } /* check out BOM */ if (!memcmp(LANG_SCNG(script_org), BOM_UTF32_BE, sizeof(BOM_UTF32_BE)-1)) { script_encoding = zend_multibyte_encoding_utf32be; bom_size = sizeof(BOM_UTF32_BE)-1; } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF32_LE, sizeof(BOM_UTF32_LE)-1)) { script_encoding = zend_multibyte_encoding_utf32le; bom_size = sizeof(BOM_UTF32_LE)-1; } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF16_BE, sizeof(BOM_UTF16_BE)-1)) { script_encoding = zend_multibyte_encoding_utf16be; bom_size = sizeof(BOM_UTF16_BE)-1; } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF16_LE, sizeof(BOM_UTF16_LE)-1)) { script_encoding = zend_multibyte_encoding_utf16le; bom_size = sizeof(BOM_UTF16_LE)-1; } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF8, sizeof(BOM_UTF8)-1)) { script_encoding = zend_multibyte_encoding_utf8; bom_size = sizeof(BOM_UTF8)-1; } if (script_encoding) { /* remove BOM */ LANG_SCNG(script_org) += bom_size; LANG_SCNG(script_org_size) -= bom_size; return script_encoding; } /* script contains NULL bytes -> auto-detection */ if ((pos1 = memchr(LANG_SCNG(script_org), 0, LANG_SCNG(script_org_size)))) { /* check if the NULL byte is after the __HALT_COMPILER(); */ pos2 = LANG_SCNG(script_org); while (pos1 - pos2 >= sizeof("__HALT_COMPILER();")-1) { pos2 = memchr(pos2, '_', pos1 - pos2); if (!pos2) break; pos2++; if (strncasecmp((char*)pos2, "_HALT_COMPILER", sizeof("_HALT_COMPILER")-1) == 0) { pos2 += sizeof("_HALT_COMPILER")-1; while (*pos2 == ' ' || *pos2 == '\t' || *pos2 == '\r' || *pos2 == '\n') { pos2++; } if (*pos2 == '(') { pos2++; while (*pos2 == ' ' || *pos2 == '\t' || *pos2 == '\r' || *pos2 == '\n') { pos2++; } if (*pos2 == ')') { pos2++; while (*pos2 == ' ' || *pos2 == '\t' || *pos2 == '\r' || *pos2 == '\n') { pos2++; } if (*pos2 == ';') { return NULL; } } } } } /* make best effort if BOM is missing */ return zend_multibyte_detect_utf_encoding(LANG_SCNG(script_org), LANG_SCNG(script_org_size) TSRMLS_CC); } return NULL; } static const zend_encoding* zend_multibyte_find_script_encoding(TSRMLS_D) { const zend_encoding *script_encoding; if (CG(detect_unicode)) { /* check out bom(byte order mark) and see if containing wchars */ script_encoding = zend_multibyte_detect_unicode(TSRMLS_C); if (script_encoding != NULL) { /* bom or wchar detection is prior to 'script_encoding' option */ return script_encoding; } } /* if no script_encoding specified, just leave alone */ if (!CG(script_encoding_list) || !CG(script_encoding_list_size)) { return NULL; } /* if multiple encodings specified, detect automagically */ if (CG(script_encoding_list_size) > 1) { return zend_multibyte_encoding_detector(LANG_SCNG(script_org), LANG_SCNG(script_org_size), CG(script_encoding_list), CG(script_encoding_list_size) TSRMLS_CC); } return CG(script_encoding_list)[0]; } ZEND_API int zend_multibyte_set_filter(const zend_encoding *onetime_encoding TSRMLS_DC) { const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding(TSRMLS_C); const zend_encoding *script_encoding = onetime_encoding ? onetime_encoding: zend_multibyte_find_script_encoding(TSRMLS_C); if (!script_encoding) { return FAILURE; } /* judge input/output filter */ LANG_SCNG(script_encoding) = script_encoding; LANG_SCNG(input_filter) = NULL; LANG_SCNG(output_filter) = NULL; if (!internal_encoding || LANG_SCNG(script_encoding) == internal_encoding) { if (!zend_multibyte_check_lexer_compatibility(LANG_SCNG(script_encoding))) { /* and if not, work around w/ script_encoding -> utf-8 -> script_encoding conversion */ LANG_SCNG(input_filter) = encoding_filter_script_to_intermediate; LANG_SCNG(output_filter) = encoding_filter_intermediate_to_script; } else { LANG_SCNG(input_filter) = NULL; LANG_SCNG(output_filter) = NULL; } return SUCCESS; } if (zend_multibyte_check_lexer_compatibility(internal_encoding)) { LANG_SCNG(input_filter) = encoding_filter_script_to_internal; LANG_SCNG(output_filter) = NULL; } else if (zend_multibyte_check_lexer_compatibility(LANG_SCNG(script_encoding))) { LANG_SCNG(input_filter) = NULL; LANG_SCNG(output_filter) = encoding_filter_script_to_internal; } else { /* both script and internal encodings are incompatible w/ flex */ LANG_SCNG(input_filter) = encoding_filter_script_to_intermediate; LANG_SCNG(output_filter) = encoding_filter_intermediate_to_internal; } return 0; } ZEND_API int open_file_for_scanning(zend_file_handle *file_handle TSRMLS_DC) { const char *file_path = NULL; char *buf; size_t size, offset = 0; /* The shebang line was read, get the current position to obtain the buffer start */ if (CG(start_lineno) == 2 && file_handle->type == ZEND_HANDLE_FP && file_handle->handle.fp) { if ((offset = ftell(file_handle->handle.fp)) == -1) { offset = 0; } } if (zend_stream_fixup(file_handle, &buf, &size TSRMLS_CC) == FAILURE) { return FAILURE; } zend_llist_add_element(&CG(open_files), file_handle); if (file_handle->handle.stream.handle >= (void*)file_handle && file_handle->handle.stream.handle <= (void*)(file_handle+1)) { zend_file_handle *fh = (zend_file_handle*)zend_llist_get_last(&CG(open_files)); size_t diff = (char*)file_handle->handle.stream.handle - (char*)file_handle; fh->handle.stream.handle = (void*)(((char*)fh) + diff); file_handle->handle.stream.handle = fh->handle.stream.handle; } /* Reset the scanner for scanning the new file */ SCNG(yy_in) = file_handle; SCNG(yy_start) = NULL; if (size != -1) { if (CG(multibyte)) { SCNG(script_org) = (unsigned char*)buf; SCNG(script_org_size) = size; SCNG(script_filtered) = NULL; zend_multibyte_set_filter(NULL TSRMLS_CC); if (SCNG(input_filter)) { if ((size_t)-1 == SCNG(input_filter)(&SCNG(script_filtered), &SCNG(script_filtered_size), SCNG(script_org), SCNG(script_org_size) TSRMLS_CC)) { zend_error_noreturn(E_COMPILE_ERROR, "Could not convert the script from the detected " "encoding \"%s\" to a compatible encoding", zend_multibyte_get_encoding_name(LANG_SCNG(script_encoding))); } buf = (char*)SCNG(script_filtered); size = SCNG(script_filtered_size); } } SCNG(yy_start) = (unsigned char *)buf - offset; yy_scan_buffer(buf, size TSRMLS_CC); } else { zend_error_noreturn(E_COMPILE_ERROR, "zend_stream_mmap() failed"); } BEGIN(INITIAL); if (file_handle->opened_path) { file_path = file_handle->opened_path; } else { file_path = file_handle->filename; } zend_set_compiled_filename(file_path TSRMLS_CC); if (CG(start_lineno)) { CG(zend_lineno) = CG(start_lineno); CG(start_lineno) = 0; } else { CG(zend_lineno) = 1; } CG(increment_lineno) = 0; return SUCCESS; } END_EXTERN_C() ZEND_API zend_op_array *compile_file(zend_file_handle *file_handle, int type TSRMLS_DC) { zend_lex_state original_lex_state; zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array)); zend_op_array *original_active_op_array = CG(active_op_array); zend_op_array *retval=NULL; int compiler_result; zend_bool compilation_successful=0; znode retval_znode; zend_bool original_in_compilation = CG(in_compilation); retval_znode.op_type = IS_CONST; retval_znode.u.constant.type = IS_LONG; retval_znode.u.constant.value.lval = 1; Z_UNSET_ISREF(retval_znode.u.constant); Z_SET_REFCOUNT(retval_znode.u.constant, 1); zend_save_lexical_state(&original_lex_state TSRMLS_CC); retval = op_array; /* success oriented */ if (open_file_for_scanning(file_handle TSRMLS_CC)==FAILURE) { if (type==ZEND_REQUIRE) { zend_message_dispatcher(ZMSG_FAILED_REQUIRE_FOPEN, file_handle->filename TSRMLS_CC); zend_bailout(); } else { zend_message_dispatcher(ZMSG_FAILED_INCLUDE_FOPEN, file_handle->filename TSRMLS_CC); } compilation_successful=0; } else { init_op_array(op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(in_compilation) = 1; CG(active_op_array) = op_array; zend_init_compiler_context(TSRMLS_C); compiler_result = zendparse(TSRMLS_C); zend_do_return(&retval_znode, 0 TSRMLS_CC); CG(in_compilation) = original_in_compilation; if (compiler_result==1) { /* parser error */ zend_bailout(); } compilation_successful=1; } if (retval) { CG(active_op_array) = original_active_op_array; if (compilation_successful) { pass_two(op_array TSRMLS_CC); zend_release_labels(TSRMLS_C); } else { efree(op_array); retval = NULL; } } zend_restore_lexical_state(&original_lex_state TSRMLS_CC); return retval; } zend_op_array *compile_filename(int type, zval *filename TSRMLS_DC) { zend_file_handle file_handle; zval tmp; zend_op_array *retval; char *opened_path = NULL; if (filename->type != IS_STRING) { tmp = *filename; zval_copy_ctor(&tmp); convert_to_string(&tmp); filename = &tmp; } file_handle.filename = filename->value.str.val; file_handle.free_filename = 0; file_handle.type = ZEND_HANDLE_FILENAME; file_handle.opened_path = NULL; file_handle.handle.fp = NULL; retval = zend_compile_file(&file_handle, type TSRMLS_CC); if (retval && file_handle.handle.stream.handle) { int dummy = 1; if (!file_handle.opened_path) { file_handle.opened_path = opened_path = estrndup(filename->value.str.val, filename->value.str.len); } zend_hash_add(&EG(included_files), file_handle.opened_path, strlen(file_handle.opened_path)+1, (void *)&dummy, sizeof(int), NULL); if (opened_path) { efree(opened_path); } } zend_destroy_file_handle(&file_handle TSRMLS_CC); if (filename==&tmp) { zval_dtor(&tmp); } return retval; } ZEND_API int zend_prepare_string_for_scanning(zval *str, char *filename TSRMLS_DC) { char *buf; size_t size; /* enforce two trailing NULLs for flex... */ if (IS_INTERNED(str->value.str.val)) { char *tmp = safe_emalloc(1, str->value.str.len, ZEND_MMAP_AHEAD); memcpy(tmp, str->value.str.val, str->value.str.len + ZEND_MMAP_AHEAD); str->value.str.val = tmp; } else { str->value.str.val = safe_erealloc(str->value.str.val, 1, str->value.str.len, ZEND_MMAP_AHEAD); } memset(str->value.str.val + str->value.str.len, 0, ZEND_MMAP_AHEAD); SCNG(yy_in) = NULL; SCNG(yy_start) = NULL; buf = str->value.str.val; size = str->value.str.len; if (CG(multibyte)) { SCNG(script_org) = (unsigned char*)buf; SCNG(script_org_size) = size; SCNG(script_filtered) = NULL; zend_multibyte_set_filter(zend_multibyte_get_internal_encoding(TSRMLS_C) TSRMLS_CC); if (SCNG(input_filter)) { if ((size_t)-1 == SCNG(input_filter)(&SCNG(script_filtered), &SCNG(script_filtered_size), SCNG(script_org), SCNG(script_org_size) TSRMLS_CC)) { zend_error_noreturn(E_COMPILE_ERROR, "Could not convert the script from the detected " "encoding \"%s\" to a compatible encoding", zend_multibyte_get_encoding_name(LANG_SCNG(script_encoding))); } buf = (char*)SCNG(script_filtered); size = SCNG(script_filtered_size); } } yy_scan_buffer(buf, size TSRMLS_CC); zend_set_compiled_filename(filename TSRMLS_CC); CG(zend_lineno) = 1; CG(increment_lineno) = 0; return SUCCESS; } ZEND_API size_t zend_get_scanned_file_offset(TSRMLS_D) { size_t offset = SCNG(yy_cursor) - SCNG(yy_start); if (SCNG(input_filter)) { size_t original_offset = offset, length = 0; do { unsigned char *p = NULL; if ((size_t)-1 == SCNG(input_filter)(&p, &length, SCNG(script_org), offset TSRMLS_CC)) { return (size_t)-1; } efree(p); if (length > original_offset) { offset--; } else if (length < original_offset) { offset++; } } while (original_offset != length); } return offset; } zend_op_array *compile_string(zval *source_string, char *filename TSRMLS_DC) { zend_lex_state original_lex_state; zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array)); zend_op_array *original_active_op_array = CG(active_op_array); zend_op_array *retval; zval tmp; int compiler_result; zend_bool original_in_compilation = CG(in_compilation); if (source_string->value.str.len==0) { efree(op_array); return NULL; } CG(in_compilation) = 1; tmp = *source_string; zval_copy_ctor(&tmp); convert_to_string(&tmp); source_string = &tmp; zend_save_lexical_state(&original_lex_state TSRMLS_CC); if (zend_prepare_string_for_scanning(source_string, filename TSRMLS_CC)==FAILURE) { efree(op_array); retval = NULL; } else { zend_bool orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(op_array, ZEND_EVAL_CODE, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; CG(active_op_array) = op_array; zend_init_compiler_context(TSRMLS_C); BEGIN(ST_IN_SCRIPTING); compiler_result = zendparse(TSRMLS_C); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } if (compiler_result==1) { CG(active_op_array) = original_active_op_array; CG(unclean_shutdown)=1; destroy_op_array(op_array TSRMLS_CC); efree(op_array); retval = NULL; } else { zend_do_return(NULL, 0 TSRMLS_CC); CG(active_op_array) = original_active_op_array; pass_two(op_array TSRMLS_CC); zend_release_labels(TSRMLS_C); retval = op_array; } } zend_restore_lexical_state(&original_lex_state TSRMLS_CC); zval_dtor(&tmp); CG(in_compilation) = original_in_compilation; return retval; } BEGIN_EXTERN_C() int highlight_file(char *filename, zend_syntax_highlighter_ini *syntax_highlighter_ini TSRMLS_DC) { zend_lex_state original_lex_state; zend_file_handle file_handle; file_handle.type = ZEND_HANDLE_FILENAME; file_handle.filename = filename; file_handle.free_filename = 0; file_handle.opened_path = NULL; zend_save_lexical_state(&original_lex_state TSRMLS_CC); if (open_file_for_scanning(&file_handle TSRMLS_CC)==FAILURE) { zend_message_dispatcher(ZMSG_FAILED_HIGHLIGHT_FOPEN, filename TSRMLS_CC); zend_restore_lexical_state(&original_lex_state TSRMLS_CC); return FAILURE; } zend_highlight(syntax_highlighter_ini TSRMLS_CC); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } zend_destroy_file_handle(&file_handle TSRMLS_CC); zend_restore_lexical_state(&original_lex_state TSRMLS_CC); return SUCCESS; } int highlight_string(zval *str, zend_syntax_highlighter_ini *syntax_highlighter_ini, char *str_name TSRMLS_DC) { zend_lex_state original_lex_state; zval tmp = *str; str = &tmp; zval_copy_ctor(str); zend_save_lexical_state(&original_lex_state TSRMLS_CC); if (zend_prepare_string_for_scanning(str, str_name TSRMLS_CC)==FAILURE) { zend_restore_lexical_state(&original_lex_state TSRMLS_CC); return FAILURE; } BEGIN(INITIAL); zend_highlight(syntax_highlighter_ini TSRMLS_CC); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } zend_restore_lexical_state(&original_lex_state TSRMLS_CC); zval_dtor(str); return SUCCESS; } ZEND_API void zend_multibyte_yyinput_again(zend_encoding_filter old_input_filter, const zend_encoding *old_encoding TSRMLS_DC) { size_t length; unsigned char *new_yy_start; /* convert and set */ if (!SCNG(input_filter)) { if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } SCNG(script_filtered_size) = 0; length = SCNG(script_org_size); new_yy_start = SCNG(script_org); } else { if ((size_t)-1 == SCNG(input_filter)(&new_yy_start, &length, SCNG(script_org), SCNG(script_org_size) TSRMLS_CC)) { zend_error_noreturn(E_COMPILE_ERROR, "Could not convert the script from the detected " "encoding \"%s\" to a compatible encoding", zend_multibyte_get_encoding_name(LANG_SCNG(script_encoding))); } SCNG(script_filtered) = new_yy_start; SCNG(script_filtered_size) = length; } SCNG(yy_cursor) = new_yy_start + (SCNG(yy_cursor) - SCNG(yy_start)); SCNG(yy_marker) = new_yy_start + (SCNG(yy_marker) - SCNG(yy_start)); SCNG(yy_text) = new_yy_start + (SCNG(yy_text) - SCNG(yy_start)); SCNG(yy_limit) = new_yy_start + (SCNG(yy_limit) - SCNG(yy_start)); SCNG(yy_start) = new_yy_start; } # define zend_copy_value(zendlval, yytext, yyleng) \ if (SCNG(output_filter)) { \ size_t sz = 0; \ SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)yytext, (size_t)yyleng TSRMLS_CC); \ zendlval->value.str.len = sz; \ } else { \ zendlval->value.str.val = (char *) estrndup(yytext, yyleng); \ zendlval->value.str.len = yyleng; \ } static void zend_scan_escape_string(zval *zendlval, char *str, int len, char quote_type TSRMLS_DC) { register char *s, *t; char *end; ZVAL_STRINGL(zendlval, str, len, 1); /* convert escape sequences */ s = t = zendlval->value.str.val; end = s+zendlval->value.str.len; while (s<end) { if (*s=='\\') { s++; if (s >= end) { *t++ = '\\'; break; } switch(*s) { case 'n': *t++ = '\n'; zendlval->value.str.len--; break; case 'r': *t++ = '\r'; zendlval->value.str.len--; break; case 't': *t++ = '\t'; zendlval->value.str.len--; break; case 'f': *t++ = '\f'; zendlval->value.str.len--; break; case 'v': *t++ = '\v'; zendlval->value.str.len--; break; case 'e': *t++ = '\e'; zendlval->value.str.len--; break; case '"': case '`': if (*s != quote_type) { *t++ = '\\'; *t++ = *s; break; } case '\\': case '$': *t++ = *s; zendlval->value.str.len--; break; case 'x': case 'X': if (ZEND_IS_HEX(*(s+1))) { char hex_buf[3] = { 0, 0, 0 }; zendlval->value.str.len--; /* for the 'x' */ hex_buf[0] = *(++s); zendlval->value.str.len--; if (ZEND_IS_HEX(*(s+1))) { hex_buf[1] = *(++s); zendlval->value.str.len--; } *t++ = (char) strtol(hex_buf, NULL, 16); } else { *t++ = '\\'; *t++ = *s; } break; default: /* check for an octal */ if (ZEND_IS_OCT(*s)) { char octal_buf[4] = { 0, 0, 0, 0 }; octal_buf[0] = *s; zendlval->value.str.len--; if (ZEND_IS_OCT(*(s+1))) { octal_buf[1] = *(++s); zendlval->value.str.len--; if (ZEND_IS_OCT(*(s+1))) { octal_buf[2] = *(++s); zendlval->value.str.len--; } } *t++ = (char) strtol(octal_buf, NULL, 8); } else { *t++ = '\\'; *t++ = *s; } break; } } else { *t++ = *s; } if (*s == '\n' || (*s == '\r' && (*(s+1) != '\n'))) { CG(zend_lineno)++; } s++; } *t = 0; if (SCNG(output_filter)) { size_t sz = 0; s = zendlval->value.str.val; SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)s, (size_t)zendlval->value.str.len TSRMLS_CC); zendlval->value.str.len = sz; efree(s); } } int lex_scan(zval *zendlval TSRMLS_DC) { restart: SCNG(yy_text) = YYCURSOR; yymore_restart: #line 995 "Zend/zend_language_scanner.c" { YYCTYPE yych; unsigned int yyaccept = 0; if (YYGETCONDITION() < 5) { if (YYGETCONDITION() < 2) { if (YYGETCONDITION() < 1) { goto yyc_ST_IN_SCRIPTING; } else { goto yyc_ST_LOOKING_FOR_PROPERTY; } } else { if (YYGETCONDITION() < 3) { goto yyc_ST_BACKQUOTE; } else { if (YYGETCONDITION() < 4) { goto yyc_ST_DOUBLE_QUOTES; } else { goto yyc_ST_HEREDOC; } } } } else { if (YYGETCONDITION() < 7) { if (YYGETCONDITION() < 6) { goto yyc_ST_LOOKING_FOR_VARNAME; } else { goto yyc_ST_VAR_OFFSET; } } else { if (YYGETCONDITION() < 8) { goto yyc_INITIAL; } else { if (YYGETCONDITION() < 9) { goto yyc_ST_END_HEREDOC; } else { goto yyc_ST_NOWDOC; } } } } /* *********************************** */ yyc_INITIAL: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; YYDEBUG(0, *YYCURSOR); YYFILL(8); yych = *YYCURSOR; if (yych != '<') goto yy4; YYDEBUG(2, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '?') { if (yych == '%') goto yy7; if (yych >= '?') goto yy5; } else { if (yych <= 'S') { if (yych >= 'S') goto yy9; } else { if (yych == 's') goto yy9; } } yy3: YYDEBUG(3, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1775 "Zend/zend_language_scanner.l" { if (YYCURSOR > YYLIMIT) { return 0; } inline_char_handler: while (1) { YYCTYPE *ptr = memchr(YYCURSOR, '<', YYLIMIT - YYCURSOR); YYCURSOR = ptr ? ptr + 1 : YYLIMIT; if (YYCURSOR < YYLIMIT) { switch (*YYCURSOR) { case '?': if (CG(short_tags) || !strncasecmp((char*)YYCURSOR + 1, "php", 3) || (*(YYCURSOR + 1) == '=')) { /* Assume [ \t\n\r] follows "php" */ break; } continue; case '%': if (CG(asp_tags)) { break; } continue; case 's': case 'S': /* Probably NOT an opening PHP <script> tag, so don't end the HTML chunk yet * If it is, the PHP <script> tag rule checks for any HTML scanned before it */ YYCURSOR--; yymore(); default: continue; } YYCURSOR--; } break; } inline_html: yyleng = YYCURSOR - SCNG(yy_text); if (SCNG(output_filter)) { int readsize; size_t sz = 0; readsize = SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)yytext, (size_t)yyleng TSRMLS_CC); zendlval->value.str.len = sz; if (readsize < yyleng) { yyless(readsize); } } else { zendlval->value.str.val = (char *) estrndup(yytext, yyleng); zendlval->value.str.len = yyleng; } zendlval->type = IS_STRING; HANDLE_NEWLINES(yytext, yyleng); return T_INLINE_HTML; } #line 1154 "Zend/zend_language_scanner.c" yy4: YYDEBUG(4, *YYCURSOR); yych = *++YYCURSOR; goto yy3; yy5: YYDEBUG(5, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'O') { if (yych == '=') goto yy45; } else { if (yych <= 'P') goto yy47; if (yych == 'p') goto yy47; } yy6: YYDEBUG(6, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1763 "Zend/zend_language_scanner.l" { if (CG(short_tags)) { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG; } else { goto inline_char_handler; } } #line 1184 "Zend/zend_language_scanner.c" yy7: YYDEBUG(7, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '=') goto yy43; YYDEBUG(8, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1740 "Zend/zend_language_scanner.l" { if (CG(asp_tags)) { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG; } else { goto inline_char_handler; } } #line 1203 "Zend/zend_language_scanner.c" yy9: YYDEBUG(9, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy11; if (yych == 'c') goto yy11; yy10: YYDEBUG(10, *YYCURSOR); YYCURSOR = YYMARKER; if (yyaccept <= 0) { goto yy3; } else { goto yy6; } yy11: YYDEBUG(11, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy12; if (yych != 'r') goto yy10; yy12: YYDEBUG(12, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy13; if (yych != 'i') goto yy10; yy13: YYDEBUG(13, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy14; if (yych != 'p') goto yy10; yy14: YYDEBUG(14, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy15; if (yych != 't') goto yy10; yy15: YYDEBUG(15, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy10; if (yych == 'l') goto yy10; goto yy17; yy16: YYDEBUG(16, *YYCURSOR); ++YYCURSOR; YYFILL(8); yych = *YYCURSOR; yy17: YYDEBUG(17, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy16; } if (yych == 'L') goto yy18; if (yych != 'l') goto yy10; yy18: YYDEBUG(18, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy19; if (yych != 'a') goto yy10; yy19: YYDEBUG(19, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy20; if (yych != 'n') goto yy10; yy20: YYDEBUG(20, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy21; if (yych != 'g') goto yy10; yy21: YYDEBUG(21, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy22; if (yych != 'u') goto yy10; yy22: YYDEBUG(22, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy23; if (yych != 'a') goto yy10; yy23: YYDEBUG(23, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy24; if (yych != 'g') goto yy10; yy24: YYDEBUG(24, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy25; if (yych != 'e') goto yy10; yy25: YYDEBUG(25, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(26, *YYCURSOR); if (yych <= '\r') { if (yych <= 0x08) goto yy10; if (yych <= '\n') goto yy25; if (yych <= '\f') goto yy10; goto yy25; } else { if (yych <= ' ') { if (yych <= 0x1F) goto yy10; goto yy25; } else { if (yych != '=') goto yy10; } } yy27: YYDEBUG(27, *YYCURSOR); ++YYCURSOR; YYFILL(5); yych = *YYCURSOR; YYDEBUG(28, *YYCURSOR); if (yych <= '!') { if (yych <= '\f') { if (yych <= 0x08) goto yy10; if (yych <= '\n') goto yy27; goto yy10; } else { if (yych <= '\r') goto yy27; if (yych == ' ') goto yy27; goto yy10; } } else { if (yych <= 'O') { if (yych <= '"') goto yy30; if (yych == '\'') goto yy31; goto yy10; } else { if (yych <= 'P') goto yy29; if (yych != 'p') goto yy10; } } yy29: YYDEBUG(29, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy42; if (yych == 'h') goto yy42; goto yy10; yy30: YYDEBUG(30, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy39; if (yych == 'p') goto yy39; goto yy10; yy31: YYDEBUG(31, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy32; if (yych != 'p') goto yy10; yy32: YYDEBUG(32, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy33; if (yych != 'h') goto yy10; yy33: YYDEBUG(33, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy34; if (yych != 'p') goto yy10; yy34: YYDEBUG(34, *YYCURSOR); yych = *++YYCURSOR; if (yych != '\'') goto yy10; yy35: YYDEBUG(35, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(36, *YYCURSOR); if (yych <= '\r') { if (yych <= 0x08) goto yy10; if (yych <= '\n') goto yy35; if (yych <= '\f') goto yy10; goto yy35; } else { if (yych <= ' ') { if (yych <= 0x1F) goto yy10; goto yy35; } else { if (yych != '>') goto yy10; } } YYDEBUG(37, *YYCURSOR); ++YYCURSOR; YYDEBUG(38, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1700 "Zend/zend_language_scanner.l" { YYCTYPE *bracket = (YYCTYPE*)zend_memrchr(yytext, '<', yyleng - (sizeof("script language=php>") - 1)); if (bracket != SCNG(yy_text)) { /* Handle previously scanned HTML, as possible <script> tags found are assumed to not be PHP's */ YYCURSOR = bracket; goto inline_html; } HANDLE_NEWLINES(yytext, yyleng); zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG; } #line 1406 "Zend/zend_language_scanner.c" yy39: YYDEBUG(39, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy40; if (yych != 'h') goto yy10; yy40: YYDEBUG(40, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy41; if (yych != 'p') goto yy10; yy41: YYDEBUG(41, *YYCURSOR); yych = *++YYCURSOR; if (yych == '"') goto yy35; goto yy10; yy42: YYDEBUG(42, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy35; if (yych == 'p') goto yy35; goto yy10; yy43: YYDEBUG(43, *YYCURSOR); ++YYCURSOR; YYDEBUG(44, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1718 "Zend/zend_language_scanner.l" { if (CG(asp_tags)) { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG_WITH_ECHO; } else { goto inline_char_handler; } } #line 1445 "Zend/zend_language_scanner.c" yy45: YYDEBUG(45, *YYCURSOR); ++YYCURSOR; YYDEBUG(46, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1731 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG_WITH_ECHO; } #line 1459 "Zend/zend_language_scanner.c" yy47: YYDEBUG(47, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy48; if (yych != 'h') goto yy10; yy48: YYDEBUG(48, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy49; if (yych != 'p') goto yy10; yy49: YYDEBUG(49, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '\f') { if (yych <= 0x08) goto yy10; if (yych >= '\v') goto yy10; } else { if (yych <= '\r') goto yy52; if (yych != ' ') goto yy10; } yy50: YYDEBUG(50, *YYCURSOR); ++YYCURSOR; yy51: YYDEBUG(51, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1753 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; HANDLE_NEWLINE(yytext[yyleng-1]); BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG; } #line 1495 "Zend/zend_language_scanner.c" yy52: YYDEBUG(52, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '\n') goto yy50; goto yy51; } /* *********************************** */ yyc_ST_BACKQUOTE: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; YYDEBUG(53, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych <= '_') { if (yych != '$') goto yy60; } else { if (yych <= '`') goto yy58; if (yych == '{') goto yy57; goto yy60; } YYDEBUG(55, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '_') { if (yych <= '@') goto yy56; if (yych <= 'Z') goto yy63; if (yych >= '_') goto yy63; } else { if (yych <= 'z') { if (yych >= 'a') goto yy63; } else { if (yych <= '{') goto yy66; if (yych >= 0x7F) goto yy63; } } yy56: YYDEBUG(56, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2226 "Zend/zend_language_scanner.l" { if (YYCURSOR > YYLIMIT) { return 0; } if (yytext[0] == '\\' && YYCURSOR < YYLIMIT) { YYCURSOR++; } while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '`': break; case '$': if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { break; } continue; case '{': if (*YYCURSOR == '$') { break; } continue; case '\\': if (YYCURSOR < YYLIMIT) { YYCURSOR++; } /* fall through */ default: continue; } YYCURSOR--; break; } yyleng = YYCURSOR - SCNG(yy_text); zend_scan_escape_string(zendlval, yytext, yyleng, '`' TSRMLS_CC); return T_ENCAPSED_AND_WHITESPACE; } #line 1607 "Zend/zend_language_scanner.c" yy57: YYDEBUG(57, *YYCURSOR); yych = *++YYCURSOR; if (yych == '$') goto yy61; goto yy56; yy58: YYDEBUG(58, *YYCURSOR); ++YYCURSOR; YYDEBUG(59, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2170 "Zend/zend_language_scanner.l" { BEGIN(ST_IN_SCRIPTING); return '`'; } #line 1623 "Zend/zend_language_scanner.c" yy60: YYDEBUG(60, *YYCURSOR); yych = *++YYCURSOR; goto yy56; yy61: YYDEBUG(61, *YYCURSOR); ++YYCURSOR; YYDEBUG(62, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2157 "Zend/zend_language_scanner.l" { zendlval->value.lval = (long) '{'; yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); yyless(1); return T_CURLY_OPEN; } #line 1640 "Zend/zend_language_scanner.c" yy63: YYDEBUG(63, *YYCURSOR); yyaccept = 0; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(64, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy63; } if (yych == '-') goto yy68; if (yych == '[') goto yy70; yy65: YYDEBUG(65, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1857 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1662 "Zend/zend_language_scanner.c" yy66: YYDEBUG(66, *YYCURSOR); ++YYCURSOR; YYDEBUG(67, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1442 "Zend/zend_language_scanner.l" { yy_push_state(ST_LOOKING_FOR_VARNAME TSRMLS_CC); return T_DOLLAR_OPEN_CURLY_BRACES; } #line 1673 "Zend/zend_language_scanner.c" yy68: YYDEBUG(68, *YYCURSOR); yych = *++YYCURSOR; if (yych == '>') goto yy72; yy69: YYDEBUG(69, *YYCURSOR); YYCURSOR = YYMARKER; goto yy65; yy70: YYDEBUG(70, *YYCURSOR); ++YYCURSOR; YYDEBUG(71, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1849 "Zend/zend_language_scanner.l" { yyless(yyleng - 1); yy_push_state(ST_VAR_OFFSET TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1695 "Zend/zend_language_scanner.c" yy72: YYDEBUG(72, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy69; if (yych <= 'Z') goto yy73; if (yych <= '^') goto yy69; } else { if (yych <= '`') goto yy69; if (yych <= 'z') goto yy73; if (yych <= '~') goto yy69; } yy73: YYDEBUG(73, *YYCURSOR); ++YYCURSOR; YYDEBUG(74, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1839 "Zend/zend_language_scanner.l" { yyless(yyleng - 3); yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1721 "Zend/zend_language_scanner.c" } /* *********************************** */ yyc_ST_DOUBLE_QUOTES: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; YYDEBUG(75, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych <= '#') { if (yych == '"') goto yy80; goto yy82; } else { if (yych <= '$') goto yy77; if (yych == '{') goto yy79; goto yy82; } yy77: YYDEBUG(77, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '_') { if (yych <= '@') goto yy78; if (yych <= 'Z') goto yy85; if (yych >= '_') goto yy85; } else { if (yych <= 'z') { if (yych >= 'a') goto yy85; } else { if (yych <= '{') goto yy88; if (yych >= 0x7F) goto yy85; } } yy78: YYDEBUG(78, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2176 "Zend/zend_language_scanner.l" { if (GET_DOUBLE_QUOTES_SCANNED_LENGTH()) { YYCURSOR += GET_DOUBLE_QUOTES_SCANNED_LENGTH() - 1; SET_DOUBLE_QUOTES_SCANNED_LENGTH(0); goto double_quotes_scan_done; } if (YYCURSOR > YYLIMIT) { return 0; } if (yytext[0] == '\\' && YYCURSOR < YYLIMIT) { YYCURSOR++; } while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '"': break; case '$': if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { break; } continue; case '{': if (*YYCURSOR == '$') { break; } continue; case '\\': if (YYCURSOR < YYLIMIT) { YYCURSOR++; } /* fall through */ default: continue; } YYCURSOR--; break; } double_quotes_scan_done: yyleng = YYCURSOR - SCNG(yy_text); zend_scan_escape_string(zendlval, yytext, yyleng, '"' TSRMLS_CC); return T_ENCAPSED_AND_WHITESPACE; } #line 1838 "Zend/zend_language_scanner.c" yy79: YYDEBUG(79, *YYCURSOR); yych = *++YYCURSOR; if (yych == '$') goto yy83; goto yy78; yy80: YYDEBUG(80, *YYCURSOR); ++YYCURSOR; YYDEBUG(81, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2165 "Zend/zend_language_scanner.l" { BEGIN(ST_IN_SCRIPTING); return '"'; } #line 1854 "Zend/zend_language_scanner.c" yy82: YYDEBUG(82, *YYCURSOR); yych = *++YYCURSOR; goto yy78; yy83: YYDEBUG(83, *YYCURSOR); ++YYCURSOR; YYDEBUG(84, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2157 "Zend/zend_language_scanner.l" { zendlval->value.lval = (long) '{'; yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); yyless(1); return T_CURLY_OPEN; } #line 1871 "Zend/zend_language_scanner.c" yy85: YYDEBUG(85, *YYCURSOR); yyaccept = 0; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(86, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy85; } if (yych == '-') goto yy90; if (yych == '[') goto yy92; yy87: YYDEBUG(87, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1857 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1893 "Zend/zend_language_scanner.c" yy88: YYDEBUG(88, *YYCURSOR); ++YYCURSOR; YYDEBUG(89, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1442 "Zend/zend_language_scanner.l" { yy_push_state(ST_LOOKING_FOR_VARNAME TSRMLS_CC); return T_DOLLAR_OPEN_CURLY_BRACES; } #line 1904 "Zend/zend_language_scanner.c" yy90: YYDEBUG(90, *YYCURSOR); yych = *++YYCURSOR; if (yych == '>') goto yy94; yy91: YYDEBUG(91, *YYCURSOR); YYCURSOR = YYMARKER; goto yy87; yy92: YYDEBUG(92, *YYCURSOR); ++YYCURSOR; YYDEBUG(93, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1849 "Zend/zend_language_scanner.l" { yyless(yyleng - 1); yy_push_state(ST_VAR_OFFSET TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1926 "Zend/zend_language_scanner.c" yy94: YYDEBUG(94, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy91; if (yych <= 'Z') goto yy95; if (yych <= '^') goto yy91; } else { if (yych <= '`') goto yy91; if (yych <= 'z') goto yy95; if (yych <= '~') goto yy91; } yy95: YYDEBUG(95, *YYCURSOR); ++YYCURSOR; YYDEBUG(96, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1839 "Zend/zend_language_scanner.l" { yyless(yyleng - 3); yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1952 "Zend/zend_language_scanner.c" } /* *********************************** */ yyc_ST_END_HEREDOC: YYDEBUG(97, *YYCURSOR); YYFILL(1); yych = *YYCURSOR; YYDEBUG(99, *YYCURSOR); ++YYCURSOR; YYDEBUG(100, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2144 "Zend/zend_language_scanner.l" { YYCURSOR += CG(heredoc_len) - 1; yyleng = CG(heredoc_len); Z_STRVAL_P(zendlval) = CG(heredoc); Z_STRLEN_P(zendlval) = CG(heredoc_len); CG(heredoc) = NULL; CG(heredoc_len) = 0; BEGIN(ST_IN_SCRIPTING); return T_END_HEREDOC; } #line 1975 "Zend/zend_language_scanner.c" /* *********************************** */ yyc_ST_HEREDOC: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; YYDEBUG(101, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych == '$') goto yy103; if (yych == '{') goto yy105; goto yy106; yy103: YYDEBUG(103, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '_') { if (yych <= '@') goto yy104; if (yych <= 'Z') goto yy109; if (yych >= '_') goto yy109; } else { if (yych <= 'z') { if (yych >= 'a') goto yy109; } else { if (yych <= '{') goto yy112; if (yych >= 0x7F) goto yy109; } } yy104: YYDEBUG(104, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2268 "Zend/zend_language_scanner.l" { int newline = 0; if (YYCURSOR > YYLIMIT) { return 0; } YYCURSOR--; while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '\r': if (*YYCURSOR == '\n') { YYCURSOR++; } /* fall through */ case '\n': /* Check for ending label on the next line */ if (IS_LABEL_START(*YYCURSOR) && CG(heredoc_len) < YYLIMIT - YYCURSOR && !memcmp(YYCURSOR, CG(heredoc), CG(heredoc_len))) { YYCTYPE *end = YYCURSOR + CG(heredoc_len); if (*end == ';') { end++; } if (*end == '\n' || *end == '\r') { /* newline before label will be subtracted from returned text, but * yyleng/yytext will include it, for zend_highlight/strip, tokenizer, etc. */ if (YYCURSOR[-2] == '\r' && YYCURSOR[-1] == '\n') { newline = 2; /* Windows newline */ } else { newline = 1; } CG(increment_lineno) = 1; /* For newline before label */ BEGIN(ST_END_HEREDOC); goto heredoc_scan_done; } } continue; case '$': if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { break; } continue; case '{': if (*YYCURSOR == '$') { break; } continue; case '\\': if (YYCURSOR < YYLIMIT && *YYCURSOR != '\n' && *YYCURSOR != '\r') { YYCURSOR++; } /* fall through */ default: continue; } YYCURSOR--; break; } heredoc_scan_done: yyleng = YYCURSOR - SCNG(yy_text); zend_scan_escape_string(zendlval, yytext, yyleng - newline, 0 TSRMLS_CC); return T_ENCAPSED_AND_WHITESPACE; } #line 2108 "Zend/zend_language_scanner.c" yy105: YYDEBUG(105, *YYCURSOR); yych = *++YYCURSOR; if (yych == '$') goto yy107; goto yy104; yy106: YYDEBUG(106, *YYCURSOR); yych = *++YYCURSOR; goto yy104; yy107: YYDEBUG(107, *YYCURSOR); ++YYCURSOR; YYDEBUG(108, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2157 "Zend/zend_language_scanner.l" { zendlval->value.lval = (long) '{'; yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); yyless(1); return T_CURLY_OPEN; } #line 2130 "Zend/zend_language_scanner.c" yy109: YYDEBUG(109, *YYCURSOR); yyaccept = 0; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(110, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy109; } if (yych == '-') goto yy114; if (yych == '[') goto yy116; yy111: YYDEBUG(111, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1857 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 2152 "Zend/zend_language_scanner.c" yy112: YYDEBUG(112, *YYCURSOR); ++YYCURSOR; YYDEBUG(113, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1442 "Zend/zend_language_scanner.l" { yy_push_state(ST_LOOKING_FOR_VARNAME TSRMLS_CC); return T_DOLLAR_OPEN_CURLY_BRACES; } #line 2163 "Zend/zend_language_scanner.c" yy114: YYDEBUG(114, *YYCURSOR); yych = *++YYCURSOR; if (yych == '>') goto yy118; yy115: YYDEBUG(115, *YYCURSOR); YYCURSOR = YYMARKER; goto yy111; yy116: YYDEBUG(116, *YYCURSOR); ++YYCURSOR; YYDEBUG(117, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1849 "Zend/zend_language_scanner.l" { yyless(yyleng - 1); yy_push_state(ST_VAR_OFFSET TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 2185 "Zend/zend_language_scanner.c" yy118: YYDEBUG(118, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy115; if (yych <= 'Z') goto yy119; if (yych <= '^') goto yy115; } else { if (yych <= '`') goto yy115; if (yych <= 'z') goto yy119; if (yych <= '~') goto yy115; } yy119: YYDEBUG(119, *YYCURSOR); ++YYCURSOR; YYDEBUG(120, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1839 "Zend/zend_language_scanner.l" { yyless(yyleng - 3); yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 2211 "Zend/zend_language_scanner.c" } /* *********************************** */ yyc_ST_IN_SCRIPTING: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 64, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 60, 60, 44, 44, 44, 44, 44, 44, 44, 44, 0, 0, 0, 0, 0, 0, 0, 36, 36, 36, 36, 36, 36, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 4, 0, 36, 36, 36, 36, 36, 36, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, }; YYDEBUG(121, *YYCURSOR); YYFILL(16); yych = *YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case '\v': case '\f': case 0x0E: case 0x0F: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1A: case 0x1B: case 0x1C: case 0x1D: case 0x1E: case 0x1F: goto yy183; case '\t': case '\n': case '\r': case ' ': goto yy139; case '!': goto yy152; case '"': goto yy179; case '#': goto yy175; case '$': goto yy164; case '%': goto yy158; case '&': goto yy159; case '\'': goto yy177; case '(': goto yy146; case ')': case ',': case ';': case '@': case '[': case ']': case '~': goto yy165; case '*': goto yy155; case '+': goto yy151; case '-': goto yy137; case '.': goto yy157; case '/': goto yy156; case '0': goto yy171; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy173; case ':': goto yy141; case '<': goto yy153; case '=': goto yy149; case '>': goto yy154; case '?': goto yy166; case 'A': case 'a': goto yy132; case 'B': case 'b': goto yy134; case 'C': case 'c': goto yy127; case 'D': case 'd': goto yy125; case 'E': case 'e': goto yy123; case 'F': case 'f': goto yy126; case 'G': case 'g': goto yy135; case 'I': case 'i': goto yy130; case 'L': case 'l': goto yy150; case 'N': case 'n': goto yy144; case 'O': case 'o': goto yy162; case 'P': case 'p': goto yy136; case 'R': case 'r': goto yy128; case 'S': case 's': goto yy133; case 'T': case 't': goto yy129; case 'U': case 'u': goto yy147; case 'V': case 'v': goto yy145; case 'W': case 'w': goto yy131; case 'X': case 'x': goto yy163; case '\\': goto yy142; case '^': goto yy161; case '_': goto yy148; case '`': goto yy181; case '{': goto yy167; case '|': goto yy160; case '}': goto yy169; default: goto yy174; } yy123: YYDEBUG(123, *YYCURSOR); ++YYCURSOR; YYDEBUG(-1, yych); switch ((yych = *YYCURSOR)) { case 'C': case 'c': goto yy726; case 'L': case 'l': goto yy727; case 'M': case 'm': goto yy728; case 'N': case 'n': goto yy729; case 'V': case 'v': goto yy730; case 'X': case 'x': goto yy731; default: goto yy186; } yy124: YYDEBUG(124, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1880 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, yytext, yyleng); zendlval->type = IS_STRING; return T_STRING; } #line 2398 "Zend/zend_language_scanner.c" yy125: YYDEBUG(125, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= 'H') { if (yych == 'E') goto yy708; goto yy186; } else { if (yych <= 'I') goto yy709; if (yych <= 'N') goto yy186; goto yy710; } } else { if (yych <= 'h') { if (yych == 'e') goto yy708; goto yy186; } else { if (yych <= 'i') goto yy709; if (yych == 'o') goto yy710; goto yy186; } } yy126: YYDEBUG(126, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= 'N') { if (yych == 'I') goto yy687; goto yy186; } else { if (yych <= 'O') goto yy688; if (yych <= 'T') goto yy186; goto yy689; } } else { if (yych <= 'n') { if (yych == 'i') goto yy687; goto yy186; } else { if (yych <= 'o') goto yy688; if (yych == 'u') goto yy689; goto yy186; } } yy127: YYDEBUG(127, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= 'K') { if (yych == 'A') goto yy652; goto yy186; } else { if (yych <= 'L') goto yy653; if (yych <= 'N') goto yy186; goto yy654; } } else { if (yych <= 'k') { if (yych == 'a') goto yy652; goto yy186; } else { if (yych <= 'l') goto yy653; if (yych == 'o') goto yy654; goto yy186; } } yy128: YYDEBUG(128, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy634; if (yych == 'e') goto yy634; goto yy186; yy129: YYDEBUG(129, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych == 'H') goto yy622; if (yych <= 'Q') goto yy186; goto yy623; } else { if (yych <= 'h') { if (yych <= 'g') goto yy186; goto yy622; } else { if (yych == 'r') goto yy623; goto yy186; } } yy130: YYDEBUG(130, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= 'L') { if (yych == 'F') goto yy569; goto yy186; } else { if (yych <= 'M') goto yy571; if (yych <= 'N') goto yy572; if (yych <= 'R') goto yy186; goto yy573; } } else { if (yych <= 'm') { if (yych == 'f') goto yy569; if (yych <= 'l') goto yy186; goto yy571; } else { if (yych <= 'n') goto yy572; if (yych == 's') goto yy573; goto yy186; } } yy131: YYDEBUG(131, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy564; if (yych == 'h') goto yy564; goto yy186; yy132: YYDEBUG(132, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= 'M') { if (yych == 'B') goto yy546; goto yy186; } else { if (yych <= 'N') goto yy547; if (yych <= 'Q') goto yy186; if (yych <= 'R') goto yy548; goto yy549; } } else { if (yych <= 'n') { if (yych == 'b') goto yy546; if (yych <= 'm') goto yy186; goto yy547; } else { if (yych <= 'q') goto yy186; if (yych <= 'r') goto yy548; if (yych <= 's') goto yy549; goto yy186; } } yy133: YYDEBUG(133, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'W') { if (yych == 'T') goto yy534; if (yych <= 'V') goto yy186; goto yy535; } else { if (yych <= 't') { if (yych <= 's') goto yy186; goto yy534; } else { if (yych == 'w') goto yy535; goto yy186; } } yy134: YYDEBUG(134, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ';') { if (yych <= '"') { if (yych <= '!') goto yy186; goto yy526; } else { if (yych == '\'') goto yy527; goto yy186; } } else { if (yych <= 'R') { if (yych <= '<') goto yy525; if (yych <= 'Q') goto yy186; goto yy528; } else { if (yych == 'r') goto yy528; goto yy186; } } yy135: YYDEBUG(135, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'L') goto yy515; if (yych <= 'N') goto yy186; goto yy516; } else { if (yych <= 'l') { if (yych <= 'k') goto yy186; goto yy515; } else { if (yych == 'o') goto yy516; goto yy186; } } yy136: YYDEBUG(136, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'R') goto yy491; if (yych <= 'T') goto yy186; goto yy492; } else { if (yych <= 'r') { if (yych <= 'q') goto yy186; goto yy491; } else { if (yych == 'u') goto yy492; goto yy186; } } yy137: YYDEBUG(137, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '<') { if (yych == '-') goto yy487; } else { if (yych <= '=') goto yy485; if (yych <= '>') goto yy489; } yy138: YYDEBUG(138, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1431 "Zend/zend_language_scanner.l" { return yytext[0]; } #line 2628 "Zend/zend_language_scanner.c" yy139: YYDEBUG(139, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy484; yy140: YYDEBUG(140, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1162 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; HANDLE_NEWLINES(yytext, yyleng); return T_WHITESPACE; } #line 2645 "Zend/zend_language_scanner.c" yy141: YYDEBUG(141, *YYCURSOR); yych = *++YYCURSOR; if (yych == ':') goto yy481; goto yy138; yy142: YYDEBUG(142, *YYCURSOR); ++YYCURSOR; YYDEBUG(143, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1191 "Zend/zend_language_scanner.l" { return T_NS_SEPARATOR; } #line 2660 "Zend/zend_language_scanner.c" yy144: YYDEBUG(144, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych == 'A') goto yy469; if (yych <= 'D') goto yy186; goto yy470; } else { if (yych <= 'a') { if (yych <= '`') goto yy186; goto yy469; } else { if (yych == 'e') goto yy470; goto yy186; } } yy145: YYDEBUG(145, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy466; if (yych == 'a') goto yy466; goto yy186; yy146: YYDEBUG(146, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy391; if (yych <= 0x1F) goto yy138; goto yy391; } else { if (yych <= '@') goto yy138; if (yych == 'C') goto yy138; goto yy391; } } else { if (yych <= 'I') { if (yych == 'F') goto yy391; if (yych <= 'H') goto yy138; goto yy391; } else { if (yych == 'O') goto yy391; if (yych <= 'Q') goto yy138; goto yy391; } } } else { if (yych <= 'f') { if (yych <= 'b') { if (yych == 'U') goto yy391; if (yych <= '`') goto yy138; goto yy391; } else { if (yych == 'd') goto yy391; if (yych <= 'e') goto yy138; goto yy391; } } else { if (yych <= 'o') { if (yych == 'i') goto yy391; if (yych <= 'n') goto yy138; goto yy391; } else { if (yych <= 's') { if (yych <= 'q') goto yy138; goto yy391; } else { if (yych == 'u') goto yy391; goto yy138; } } } } yy147: YYDEBUG(147, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych == 'N') goto yy382; if (yych <= 'R') goto yy186; goto yy383; } else { if (yych <= 'n') { if (yych <= 'm') goto yy186; goto yy382; } else { if (yych == 's') goto yy383; goto yy186; } } yy148: YYDEBUG(148, *YYCURSOR); yych = *++YYCURSOR; if (yych == '_') goto yy300; goto yy186; yy149: YYDEBUG(149, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '<') goto yy138; if (yych <= '=') goto yy294; if (yych <= '>') goto yy296; goto yy138; yy150: YYDEBUG(150, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy290; if (yych == 'i') goto yy290; goto yy186; yy151: YYDEBUG(151, *YYCURSOR); yych = *++YYCURSOR; if (yych == '+') goto yy288; if (yych == '=') goto yy286; goto yy138; yy152: YYDEBUG(152, *YYCURSOR); yych = *++YYCURSOR; if (yych == '=') goto yy283; goto yy138; yy153: YYDEBUG(153, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ';') { if (yych == '/') goto yy255; goto yy138; } else { if (yych <= '<') goto yy253; if (yych <= '=') goto yy256; if (yych <= '>') goto yy258; goto yy138; } yy154: YYDEBUG(154, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '<') goto yy138; if (yych <= '=') goto yy249; if (yych <= '>') goto yy247; goto yy138; yy155: YYDEBUG(155, *YYCURSOR); yych = *++YYCURSOR; if (yych == '=') goto yy245; goto yy138; yy156: YYDEBUG(156, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '.') { if (yych == '*') goto yy237; goto yy138; } else { if (yych <= '/') goto yy239; if (yych == '=') goto yy240; goto yy138; } yy157: YYDEBUG(157, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy138; if (yych <= '9') goto yy233; if (yych == '=') goto yy235; goto yy138; yy158: YYDEBUG(158, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '<') goto yy138; if (yych <= '=') goto yy229; if (yych <= '>') goto yy227; goto yy138; yy159: YYDEBUG(159, *YYCURSOR); yych = *++YYCURSOR; if (yych == '&') goto yy223; if (yych == '=') goto yy225; goto yy138; yy160: YYDEBUG(160, *YYCURSOR); yych = *++YYCURSOR; if (yych == '=') goto yy221; if (yych == '|') goto yy219; goto yy138; yy161: YYDEBUG(161, *YYCURSOR); yych = *++YYCURSOR; if (yych == '=') goto yy217; goto yy138; yy162: YYDEBUG(162, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy215; if (yych == 'r') goto yy215; goto yy186; yy163: YYDEBUG(163, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy212; if (yych == 'o') goto yy212; goto yy186; yy164: YYDEBUG(164, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy138; if (yych <= 'Z') goto yy209; if (yych <= '^') goto yy138; goto yy209; } else { if (yych <= '`') goto yy138; if (yych <= 'z') goto yy209; if (yych <= '~') goto yy138; goto yy209; } yy165: YYDEBUG(165, *YYCURSOR); yych = *++YYCURSOR; goto yy138; yy166: YYDEBUG(166, *YYCURSOR); yych = *++YYCURSOR; if (yych == '>') goto yy205; goto yy138; yy167: YYDEBUG(167, *YYCURSOR); ++YYCURSOR; YYDEBUG(168, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1436 "Zend/zend_language_scanner.l" { yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); return '{'; } #line 2893 "Zend/zend_language_scanner.c" yy169: YYDEBUG(169, *YYCURSOR); ++YYCURSOR; YYDEBUG(170, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1448 "Zend/zend_language_scanner.l" { RESET_DOC_COMMENT(); if (!zend_stack_is_empty(&SCNG(state_stack))) { yy_pop_state(TSRMLS_C); } return '}'; } #line 2907 "Zend/zend_language_scanner.c" yy171: YYDEBUG(171, *YYCURSOR); yyaccept = 2; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'E') { if (yych <= '9') { if (yych == '.') goto yy187; if (yych >= '0') goto yy190; } else { if (yych == 'B') goto yy198; if (yych >= 'E') goto yy192; } } else { if (yych <= 'b') { if (yych == 'X') goto yy197; if (yych >= 'b') goto yy198; } else { if (yych <= 'e') { if (yych >= 'e') goto yy192; } else { if (yych == 'x') goto yy197; } } } yy172: YYDEBUG(172, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1494 "Zend/zend_language_scanner.l" { if (yyleng < MAX_LENGTH_OF_LONG - 1) { /* Won't overflow */ zendlval->value.lval = strtol(yytext, NULL, 0); } else { errno = 0; zendlval->value.lval = strtol(yytext, NULL, 0); if (errno == ERANGE) { /* Overflow */ if (yytext[0] == '0') { /* octal overflow */ zendlval->value.dval = zend_oct_strtod(yytext, NULL); } else { zendlval->value.dval = zend_strtod(yytext, NULL); } zendlval->type = IS_DOUBLE; return T_DNUMBER; } } zendlval->type = IS_LONG; return T_LNUMBER; } #line 2956 "Zend/zend_language_scanner.c" yy173: YYDEBUG(173, *YYCURSOR); yyaccept = 2; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych == '.') goto yy187; if (yych <= '/') goto yy172; goto yy190; } else { if (yych <= 'E') { if (yych <= 'D') goto yy172; goto yy192; } else { if (yych == 'e') goto yy192; goto yy172; } } yy174: YYDEBUG(174, *YYCURSOR); yych = *++YYCURSOR; goto yy186; yy175: YYDEBUG(175, *YYCURSOR); ++YYCURSOR; yy176: YYDEBUG(176, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1887 "Zend/zend_language_scanner.l" { while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '\r': if (*YYCURSOR == '\n') { YYCURSOR++; } /* fall through */ case '\n': CG(zend_lineno)++; break; case '%': if (!CG(asp_tags)) { continue; } /* fall through */ case '?': if (*YYCURSOR == '>') { YYCURSOR--; break; } /* fall through */ default: continue; } break; } yyleng = YYCURSOR - SCNG(yy_text); return T_COMMENT; } #line 3018 "Zend/zend_language_scanner.c" yy177: YYDEBUG(177, *YYCURSOR); ++YYCURSOR; yy178: YYDEBUG(178, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1978 "Zend/zend_language_scanner.l" { register char *s, *t; char *end; int bprefix = (yytext[0] != '\'') ? 1 : 0; while (1) { if (YYCURSOR < YYLIMIT) { if (*YYCURSOR == '\'') { YYCURSOR++; yyleng = YYCURSOR - SCNG(yy_text); break; } else if (*YYCURSOR++ == '\\' && YYCURSOR < YYLIMIT) { YYCURSOR++; } } else { yyleng = YYLIMIT - SCNG(yy_text); /* Unclosed single quotes; treat similar to double quotes, but without a separate token * for ' (unrecognized by parser), instead of old flex fallback to "Unexpected character..." * rule, which continued in ST_IN_SCRIPTING state after the quote */ return T_ENCAPSED_AND_WHITESPACE; } } zendlval->value.str.val = estrndup(yytext+bprefix+1, yyleng-bprefix-2); zendlval->value.str.len = yyleng-bprefix-2; zendlval->type = IS_STRING; /* convert escape sequences */ s = t = zendlval->value.str.val; end = s+zendlval->value.str.len; while (s<end) { if (*s=='\\') { s++; switch(*s) { case '\\': case '\'': *t++ = *s; zendlval->value.str.len--; break; default: *t++ = '\\'; *t++ = *s; break; } } else { *t++ = *s; } if (*s == '\n' || (*s == '\r' && (*(s+1) != '\n'))) { CG(zend_lineno)++; } s++; } *t = 0; if (SCNG(output_filter)) { size_t sz = 0; s = zendlval->value.str.val; SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)s, (size_t)zendlval->value.str.len TSRMLS_CC); zendlval->value.str.len = sz; efree(s); } return T_CONSTANT_ENCAPSED_STRING; } #line 3093 "Zend/zend_language_scanner.c" yy179: YYDEBUG(179, *YYCURSOR); ++YYCURSOR; yy180: YYDEBUG(180, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2047 "Zend/zend_language_scanner.l" { int bprefix = (yytext[0] != '"') ? 1 : 0; while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '"': yyleng = YYCURSOR - SCNG(yy_text); zend_scan_escape_string(zendlval, yytext+bprefix+1, yyleng-bprefix-2, '"' TSRMLS_CC); return T_CONSTANT_ENCAPSED_STRING; case '$': if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { break; } continue; case '{': if (*YYCURSOR == '$') { break; } continue; case '\\': if (YYCURSOR < YYLIMIT) { YYCURSOR++; } /* fall through */ default: continue; } YYCURSOR--; break; } /* Remember how much was scanned to save rescanning */ SET_DOUBLE_QUOTES_SCANNED_LENGTH(YYCURSOR - SCNG(yy_text) - yyleng); YYCURSOR = SCNG(yy_text) + yyleng; BEGIN(ST_DOUBLE_QUOTES); return '"'; } #line 3141 "Zend/zend_language_scanner.c" yy181: YYDEBUG(181, *YYCURSOR); ++YYCURSOR; YYDEBUG(182, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2138 "Zend/zend_language_scanner.l" { BEGIN(ST_BACKQUOTE); return '`'; } #line 3152 "Zend/zend_language_scanner.c" yy183: YYDEBUG(183, *YYCURSOR); ++YYCURSOR; YYDEBUG(184, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2396 "Zend/zend_language_scanner.l" { if (YYCURSOR > YYLIMIT) { return 0; } zend_error(E_COMPILE_WARNING,"Unexpected character in input: '%c' (ASCII=%d) state=%d", yytext[0], yytext[0], YYSTATE); goto restart; } #line 3167 "Zend/zend_language_scanner.c" yy185: YYDEBUG(185, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy186: YYDEBUG(186, *YYCURSOR); if (yybm[0+yych] & 4) { goto yy185; } goto yy124; yy187: YYDEBUG(187, *YYCURSOR); yyaccept = 3; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(188, *YYCURSOR); if (yybm[0+yych] & 8) { goto yy187; } if (yych == 'E') goto yy192; if (yych == 'e') goto yy192; yy189: YYDEBUG(189, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1555 "Zend/zend_language_scanner.l" { zendlval->value.dval = zend_strtod(yytext, NULL); zendlval->type = IS_DOUBLE; return T_DNUMBER; } #line 3200 "Zend/zend_language_scanner.c" yy190: YYDEBUG(190, *YYCURSOR); yyaccept = 2; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(191, *YYCURSOR); if (yych <= '9') { if (yych == '.') goto yy187; if (yych <= '/') goto yy172; goto yy190; } else { if (yych <= 'E') { if (yych <= 'D') goto yy172; } else { if (yych != 'e') goto yy172; } } yy192: YYDEBUG(192, *YYCURSOR); yych = *++YYCURSOR; if (yych <= ',') { if (yych == '+') goto yy194; } else { if (yych <= '-') goto yy194; if (yych <= '/') goto yy193; if (yych <= '9') goto yy195; } yy193: YYDEBUG(193, *YYCURSOR); YYCURSOR = YYMARKER; if (yyaccept <= 2) { if (yyaccept <= 1) { if (yyaccept <= 0) { goto yy124; } else { goto yy138; } } else { goto yy172; } } else { if (yyaccept <= 4) { if (yyaccept <= 3) { goto yy189; } else { goto yy238; } } else { goto yy254; } } yy194: YYDEBUG(194, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy193; if (yych >= ':') goto yy193; yy195: YYDEBUG(195, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(196, *YYCURSOR); if (yych <= '/') goto yy189; if (yych <= '9') goto yy195; goto yy189; yy197: YYDEBUG(197, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 32) { goto yy202; } goto yy193; yy198: YYDEBUG(198, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 16) { goto yy199; } goto yy193; yy199: YYDEBUG(199, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(200, *YYCURSOR); if (yybm[0+yych] & 16) { goto yy199; } YYDEBUG(201, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1473 "Zend/zend_language_scanner.l" { char *bin = yytext + 2; /* Skip "0b" */ int len = yyleng - 2; /* Skip any leading 0s */ while (*bin == '0') { ++bin; --len; } if (len < SIZEOF_LONG * 8) { zendlval->value.lval = strtol(bin, NULL, 2); zendlval->type = IS_LONG; return T_LNUMBER; } else { zendlval->value.dval = zend_bin_strtod(bin, NULL); zendlval->type = IS_DOUBLE; return T_DNUMBER; } } #line 3313 "Zend/zend_language_scanner.c" yy202: YYDEBUG(202, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(203, *YYCURSOR); if (yybm[0+yych] & 32) { goto yy202; } YYDEBUG(204, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1515 "Zend/zend_language_scanner.l" { char *hex = yytext + 2; /* Skip "0x" */ int len = yyleng - 2; /* Skip any leading 0s */ while (*hex == '0') { hex++; len--; } if (len < SIZEOF_LONG * 2 || (len == SIZEOF_LONG * 2 && *hex <= '7')) { zendlval->value.lval = strtol(hex, NULL, 16); zendlval->type = IS_LONG; return T_LNUMBER; } else { zendlval->value.dval = zend_hex_strtod(hex, NULL); zendlval->type = IS_DOUBLE; return T_DNUMBER; } } #line 3346 "Zend/zend_language_scanner.c" yy205: YYDEBUG(205, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '\n') goto yy207; if (yych == '\r') goto yy208; yy206: YYDEBUG(206, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1955 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(INITIAL); return T_CLOSE_TAG; /* implicit ';' at php-end tag */ } #line 3363 "Zend/zend_language_scanner.c" yy207: YYDEBUG(207, *YYCURSOR); yych = *++YYCURSOR; goto yy206; yy208: YYDEBUG(208, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\n') goto yy207; goto yy206; yy209: YYDEBUG(209, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(210, *YYCURSOR); if (yych <= '^') { if (yych <= '9') { if (yych >= '0') goto yy209; } else { if (yych <= '@') goto yy211; if (yych <= 'Z') goto yy209; } } else { if (yych <= '`') { if (yych <= '_') goto yy209; } else { if (yych <= 'z') goto yy209; if (yych >= 0x7F) goto yy209; } } yy211: YYDEBUG(211, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1857 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 3403 "Zend/zend_language_scanner.c" yy212: YYDEBUG(212, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy213; if (yych != 'r') goto yy186; yy213: YYDEBUG(213, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(214, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1419 "Zend/zend_language_scanner.l" { return T_LOGICAL_XOR; } #line 3421 "Zend/zend_language_scanner.c" yy215: YYDEBUG(215, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(216, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1411 "Zend/zend_language_scanner.l" { return T_LOGICAL_OR; } #line 3434 "Zend/zend_language_scanner.c" yy217: YYDEBUG(217, *YYCURSOR); ++YYCURSOR; YYDEBUG(218, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1399 "Zend/zend_language_scanner.l" { return T_XOR_EQUAL; } #line 3444 "Zend/zend_language_scanner.c" yy219: YYDEBUG(219, *YYCURSOR); ++YYCURSOR; YYDEBUG(220, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1403 "Zend/zend_language_scanner.l" { return T_BOOLEAN_OR; } #line 3454 "Zend/zend_language_scanner.c" yy221: YYDEBUG(221, *YYCURSOR); ++YYCURSOR; YYDEBUG(222, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1395 "Zend/zend_language_scanner.l" { return T_OR_EQUAL; } #line 3464 "Zend/zend_language_scanner.c" yy223: YYDEBUG(223, *YYCURSOR); ++YYCURSOR; YYDEBUG(224, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1407 "Zend/zend_language_scanner.l" { return T_BOOLEAN_AND; } #line 3474 "Zend/zend_language_scanner.c" yy225: YYDEBUG(225, *YYCURSOR); ++YYCURSOR; YYDEBUG(226, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1391 "Zend/zend_language_scanner.l" { return T_AND_EQUAL; } #line 3484 "Zend/zend_language_scanner.c" yy227: YYDEBUG(227, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '\n') goto yy231; if (yych == '\r') goto yy232; yy228: YYDEBUG(228, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1964 "Zend/zend_language_scanner.l" { if (CG(asp_tags)) { BEGIN(INITIAL); zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; zendlval->value.str.val = yytext; /* no copying - intentional */ return T_CLOSE_TAG; /* implicit ';' at php-end tag */ } else { yyless(1); return yytext[0]; } } #line 3506 "Zend/zend_language_scanner.c" yy229: YYDEBUG(229, *YYCURSOR); ++YYCURSOR; YYDEBUG(230, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1379 "Zend/zend_language_scanner.l" { return T_MOD_EQUAL; } #line 3516 "Zend/zend_language_scanner.c" yy231: YYDEBUG(231, *YYCURSOR); yych = *++YYCURSOR; goto yy228; yy232: YYDEBUG(232, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\n') goto yy231; goto yy228; yy233: YYDEBUG(233, *YYCURSOR); yyaccept = 3; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(234, *YYCURSOR); if (yych <= 'D') { if (yych <= '/') goto yy189; if (yych <= '9') goto yy233; goto yy189; } else { if (yych <= 'E') goto yy192; if (yych == 'e') goto yy192; goto yy189; } yy235: YYDEBUG(235, *YYCURSOR); ++YYCURSOR; YYDEBUG(236, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1375 "Zend/zend_language_scanner.l" { return T_CONCAT_EQUAL; } #line 3551 "Zend/zend_language_scanner.c" yy237: YYDEBUG(237, *YYCURSOR); yyaccept = 4; yych = *(YYMARKER = ++YYCURSOR); if (yych == '*') goto yy242; yy238: YYDEBUG(238, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1921 "Zend/zend_language_scanner.l" { int doc_com; if (yyleng > 2) { doc_com = 1; RESET_DOC_COMMENT(); } else { doc_com = 0; } while (YYCURSOR < YYLIMIT) { if (*YYCURSOR++ == '*' && *YYCURSOR == '/') { break; } } if (YYCURSOR < YYLIMIT) { YYCURSOR++; } else { zend_error(E_COMPILE_WARNING, "Unterminated comment starting line %d", CG(zend_lineno)); } yyleng = YYCURSOR - SCNG(yy_text); HANDLE_NEWLINES(yytext, yyleng); if (doc_com) { CG(doc_comment) = estrndup(yytext, yyleng); CG(doc_comment_len) = yyleng; return T_DOC_COMMENT; } return T_COMMENT; } #line 3594 "Zend/zend_language_scanner.c" yy239: YYDEBUG(239, *YYCURSOR); yych = *++YYCURSOR; goto yy176; yy240: YYDEBUG(240, *YYCURSOR); ++YYCURSOR; YYDEBUG(241, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1371 "Zend/zend_language_scanner.l" { return T_DIV_EQUAL; } #line 3608 "Zend/zend_language_scanner.c" yy242: YYDEBUG(242, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 64) { goto yy243; } goto yy193; yy243: YYDEBUG(243, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(244, *YYCURSOR); if (yybm[0+yych] & 64) { goto yy243; } goto yy238; yy245: YYDEBUG(245, *YYCURSOR); ++YYCURSOR; YYDEBUG(246, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1367 "Zend/zend_language_scanner.l" { return T_MUL_EQUAL; } #line 3635 "Zend/zend_language_scanner.c" yy247: YYDEBUG(247, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '=') goto yy251; YYDEBUG(248, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1427 "Zend/zend_language_scanner.l" { return T_SR; } #line 3646 "Zend/zend_language_scanner.c" yy249: YYDEBUG(249, *YYCURSOR); ++YYCURSOR; YYDEBUG(250, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1355 "Zend/zend_language_scanner.l" { return T_IS_GREATER_OR_EQUAL; } #line 3656 "Zend/zend_language_scanner.c" yy251: YYDEBUG(251, *YYCURSOR); ++YYCURSOR; YYDEBUG(252, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1387 "Zend/zend_language_scanner.l" { return T_SR_EQUAL; } #line 3666 "Zend/zend_language_scanner.c" yy253: YYDEBUG(253, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ';') goto yy254; if (yych <= '<') goto yy269; if (yych <= '=') goto yy267; yy254: YYDEBUG(254, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1423 "Zend/zend_language_scanner.l" { return T_SL; } #line 3681 "Zend/zend_language_scanner.c" yy255: YYDEBUG(255, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy260; if (yych == 's') goto yy260; goto yy193; yy256: YYDEBUG(256, *YYCURSOR); ++YYCURSOR; YYDEBUG(257, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1351 "Zend/zend_language_scanner.l" { return T_IS_SMALLER_OR_EQUAL; } #line 3697 "Zend/zend_language_scanner.c" yy258: YYDEBUG(258, *YYCURSOR); ++YYCURSOR; yy259: YYDEBUG(259, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1347 "Zend/zend_language_scanner.l" { return T_IS_NOT_EQUAL; } #line 3708 "Zend/zend_language_scanner.c" yy260: YYDEBUG(260, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy261; if (yych != 'c') goto yy193; yy261: YYDEBUG(261, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy262; if (yych != 'r') goto yy193; yy262: YYDEBUG(262, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy263; if (yych != 'i') goto yy193; yy263: YYDEBUG(263, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy264; if (yych != 'p') goto yy193; yy264: YYDEBUG(264, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy265; if (yych != 't') goto yy193; yy265: YYDEBUG(265, *YYCURSOR); ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(266, *YYCURSOR); if (yych <= '\r') { if (yych <= 0x08) goto yy193; if (yych <= '\n') goto yy265; if (yych <= '\f') goto yy193; goto yy265; } else { if (yych <= ' ') { if (yych <= 0x1F) goto yy193; goto yy265; } else { if (yych == '>') goto yy205; goto yy193; } } yy267: YYDEBUG(267, *YYCURSOR); ++YYCURSOR; YYDEBUG(268, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1383 "Zend/zend_language_scanner.l" { return T_SL_EQUAL; } #line 3763 "Zend/zend_language_scanner.c" yy269: YYDEBUG(269, *YYCURSOR); ++YYCURSOR; YYFILL(2); yych = *YYCURSOR; YYDEBUG(270, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy269; } if (yych <= 'Z') { if (yych <= '&') { if (yych == '"') goto yy274; goto yy193; } else { if (yych <= '\'') goto yy273; if (yych <= '@') goto yy193; } } else { if (yych <= '`') { if (yych != '_') goto yy193; } else { if (yych <= 'z') goto yy271; if (yych <= '~') goto yy193; } } yy271: YYDEBUG(271, *YYCURSOR); ++YYCURSOR; YYFILL(2); yych = *YYCURSOR; YYDEBUG(272, *YYCURSOR); if (yych <= '@') { if (yych <= '\f') { if (yych == '\n') goto yy278; goto yy193; } else { if (yych <= '\r') goto yy280; if (yych <= '/') goto yy193; if (yych <= '9') goto yy271; goto yy193; } } else { if (yych <= '_') { if (yych <= 'Z') goto yy271; if (yych <= '^') goto yy193; goto yy271; } else { if (yych <= '`') goto yy193; if (yych <= 'z') goto yy271; if (yych <= '~') goto yy193; goto yy271; } } yy273: YYDEBUG(273, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\'') goto yy193; if (yych <= '/') goto yy282; if (yych <= '9') goto yy193; goto yy282; yy274: YYDEBUG(274, *YYCURSOR); yych = *++YYCURSOR; if (yych == '"') goto yy193; if (yych <= '/') goto yy276; if (yych <= '9') goto yy193; goto yy276; yy275: YYDEBUG(275, *YYCURSOR); ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; yy276: YYDEBUG(276, *YYCURSOR); if (yych <= 'Z') { if (yych <= '/') { if (yych != '"') goto yy193; } else { if (yych <= '9') goto yy275; if (yych <= '@') goto yy193; goto yy275; } } else { if (yych <= '`') { if (yych == '_') goto yy275; goto yy193; } else { if (yych <= 'z') goto yy275; if (yych <= '~') goto yy193; goto yy275; } } yy277: YYDEBUG(277, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\n') goto yy278; if (yych == '\r') goto yy280; goto yy193; yy278: YYDEBUG(278, *YYCURSOR); ++YYCURSOR; yy279: YYDEBUG(279, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2089 "Zend/zend_language_scanner.l" { char *s; int bprefix = (yytext[0] != '<') ? 1 : 0; /* save old heredoc label */ Z_STRVAL_P(zendlval) = CG(heredoc); Z_STRLEN_P(zendlval) = CG(heredoc_len); CG(zend_lineno)++; CG(heredoc_len) = yyleng-bprefix-3-1-(yytext[yyleng-2]=='\r'?1:0); s = yytext+bprefix+3; while ((*s == ' ') || (*s == '\t')) { s++; CG(heredoc_len)--; } if (*s == '\'') { s++; CG(heredoc_len) -= 2; BEGIN(ST_NOWDOC); } else { if (*s == '"') { s++; CG(heredoc_len) -= 2; } BEGIN(ST_HEREDOC); } CG(heredoc) = estrndup(s, CG(heredoc_len)); /* Check for ending label on the next line */ if (CG(heredoc_len) < YYLIMIT - YYCURSOR && !memcmp(YYCURSOR, s, CG(heredoc_len))) { YYCTYPE *end = YYCURSOR + CG(heredoc_len); if (*end == ';') { end++; } if (*end == '\n' || *end == '\r') { BEGIN(ST_END_HEREDOC); } } return T_START_HEREDOC; } #line 3916 "Zend/zend_language_scanner.c" yy280: YYDEBUG(280, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\n') goto yy278; goto yy279; yy281: YYDEBUG(281, *YYCURSOR); ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; yy282: YYDEBUG(282, *YYCURSOR); if (yych <= 'Z') { if (yych <= '/') { if (yych == '\'') goto yy277; goto yy193; } else { if (yych <= '9') goto yy281; if (yych <= '@') goto yy193; goto yy281; } } else { if (yych <= '`') { if (yych == '_') goto yy281; goto yy193; } else { if (yych <= 'z') goto yy281; if (yych <= '~') goto yy193; goto yy281; } } yy283: YYDEBUG(283, *YYCURSOR); yych = *++YYCURSOR; if (yych != '=') goto yy259; YYDEBUG(284, *YYCURSOR); ++YYCURSOR; YYDEBUG(285, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1339 "Zend/zend_language_scanner.l" { return T_IS_NOT_IDENTICAL; } #line 3960 "Zend/zend_language_scanner.c" yy286: YYDEBUG(286, *YYCURSOR); ++YYCURSOR; YYDEBUG(287, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1359 "Zend/zend_language_scanner.l" { return T_PLUS_EQUAL; } #line 3970 "Zend/zend_language_scanner.c" yy288: YYDEBUG(288, *YYCURSOR); ++YYCURSOR; YYDEBUG(289, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1327 "Zend/zend_language_scanner.l" { return T_INC; } #line 3980 "Zend/zend_language_scanner.c" yy290: YYDEBUG(290, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy291; if (yych != 's') goto yy186; yy291: YYDEBUG(291, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy292; if (yych != 't') goto yy186; yy292: YYDEBUG(292, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(293, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1315 "Zend/zend_language_scanner.l" { return T_LIST; } #line 4003 "Zend/zend_language_scanner.c" yy294: YYDEBUG(294, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '=') goto yy298; YYDEBUG(295, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1343 "Zend/zend_language_scanner.l" { return T_IS_EQUAL; } #line 4014 "Zend/zend_language_scanner.c" yy296: YYDEBUG(296, *YYCURSOR); ++YYCURSOR; YYDEBUG(297, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1311 "Zend/zend_language_scanner.l" { return T_DOUBLE_ARROW; } #line 4024 "Zend/zend_language_scanner.c" yy298: YYDEBUG(298, *YYCURSOR); ++YYCURSOR; YYDEBUG(299, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1335 "Zend/zend_language_scanner.l" { return T_IS_IDENTICAL; } #line 4034 "Zend/zend_language_scanner.c" yy300: YYDEBUG(300, *YYCURSOR); yych = *++YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case 'C': case 'c': goto yy302; case 'D': case 'd': goto yy307; case 'F': case 'f': goto yy304; case 'H': case 'h': goto yy301; case 'L': case 'l': goto yy306; case 'M': case 'm': goto yy305; case 'N': case 'n': goto yy308; case 'T': case 't': goto yy303; default: goto yy186; } yy301: YYDEBUG(301, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy369; if (yych == 'a') goto yy369; goto yy186; yy302: YYDEBUG(302, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy362; if (yych == 'l') goto yy362; goto yy186; yy303: YYDEBUG(303, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy355; if (yych == 'r') goto yy355; goto yy186; yy304: YYDEBUG(304, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'I') goto yy339; if (yych <= 'T') goto yy186; goto yy340; } else { if (yych <= 'i') { if (yych <= 'h') goto yy186; goto yy339; } else { if (yych == 'u') goto yy340; goto yy186; } } yy305: YYDEBUG(305, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy331; if (yych == 'e') goto yy331; goto yy186; yy306: YYDEBUG(306, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy325; if (yych == 'i') goto yy325; goto yy186; yy307: YYDEBUG(307, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy320; if (yych == 'i') goto yy320; goto yy186; yy308: YYDEBUG(308, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy309; if (yych != 'a') goto yy186; yy309: YYDEBUG(309, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy310; if (yych != 'm') goto yy186; yy310: YYDEBUG(310, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy311; if (yych != 'e') goto yy186; yy311: YYDEBUG(311, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy312; if (yych != 's') goto yy186; yy312: YYDEBUG(312, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy313; if (yych != 'p') goto yy186; yy313: YYDEBUG(313, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy314; if (yych != 'a') goto yy186; yy314: YYDEBUG(314, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy315; if (yych != 'c') goto yy186; yy315: YYDEBUG(315, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy316; if (yych != 'e') goto yy186; yy316: YYDEBUG(316, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(317, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(318, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(319, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1690 "Zend/zend_language_scanner.l" { if (CG(current_namespace)) { *zendlval = *CG(current_namespace); zval_copy_ctor(zendlval); } else { ZVAL_EMPTY_STRING(zendlval); } return T_NS_C; } #line 4174 "Zend/zend_language_scanner.c" yy320: YYDEBUG(320, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy321; if (yych != 'r') goto yy186; yy321: YYDEBUG(321, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(322, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(323, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(324, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1663 "Zend/zend_language_scanner.l" { char *filename = zend_get_compiled_filename(TSRMLS_C); const size_t filename_len = strlen(filename); char *dirname; if (!filename) { filename = ""; } dirname = estrndup(filename, filename_len); zend_dirname(dirname, filename_len); if (strcmp(dirname, ".") == 0) { dirname = erealloc(dirname, MAXPATHLEN); #if HAVE_GETCWD VCWD_GETCWD(dirname, MAXPATHLEN); #elif HAVE_GETWD VCWD_GETWD(dirname); #endif } zendlval->value.str.len = strlen(dirname); zendlval->value.str.val = dirname; zendlval->type = IS_STRING; return T_DIR; } #line 4221 "Zend/zend_language_scanner.c" yy325: YYDEBUG(325, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy326; if (yych != 'n') goto yy186; yy326: YYDEBUG(326, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy327; if (yych != 'e') goto yy186; yy327: YYDEBUG(327, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(328, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(329, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(330, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1645 "Zend/zend_language_scanner.l" { zendlval->value.lval = CG(zend_lineno); zendlval->type = IS_LONG; return T_LINE; } #line 4252 "Zend/zend_language_scanner.c" yy331: YYDEBUG(331, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy332; if (yych != 't') goto yy186; yy332: YYDEBUG(332, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy333; if (yych != 'h') goto yy186; yy333: YYDEBUG(333, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy334; if (yych != 'o') goto yy186; yy334: YYDEBUG(334, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy335; if (yych != 'd') goto yy186; yy335: YYDEBUG(335, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(336, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(337, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(338, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1624 "Zend/zend_language_scanner.l" { const char *class_name = CG(active_class_entry) ? CG(active_class_entry)->name : NULL; const char *func_name = CG(active_op_array)? CG(active_op_array)->function_name : NULL; size_t len = 0; if (class_name) { len += strlen(class_name) + 2; } if (func_name) { len += strlen(func_name); } zendlval->value.str.len = zend_spprintf(&zendlval->value.str.val, 0, "%s%s%s", class_name ? class_name : "", class_name && func_name ? "::" : "", func_name ? func_name : "" ); zendlval->type = IS_STRING; return T_METHOD_C; } #line 4308 "Zend/zend_language_scanner.c" yy339: YYDEBUG(339, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy350; if (yych == 'l') goto yy350; goto yy186; yy340: YYDEBUG(340, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy341; if (yych != 'n') goto yy186; yy341: YYDEBUG(341, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy342; if (yych != 'c') goto yy186; yy342: YYDEBUG(342, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy343; if (yych != 't') goto yy186; yy343: YYDEBUG(343, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy344; if (yych != 'i') goto yy186; yy344: YYDEBUG(344, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy345; if (yych != 'o') goto yy186; yy345: YYDEBUG(345, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy346; if (yych != 'n') goto yy186; yy346: YYDEBUG(346, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(347, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(348, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(349, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1608 "Zend/zend_language_scanner.l" { const char *func_name = NULL; if (CG(active_op_array)) { func_name = CG(active_op_array)->function_name; } if (!func_name) { func_name = ""; } zendlval->value.str.len = strlen(func_name); zendlval->value.str.val = estrndup(func_name, zendlval->value.str.len); zendlval->type = IS_STRING; return T_FUNC_C; } #line 4375 "Zend/zend_language_scanner.c" yy350: YYDEBUG(350, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy351; if (yych != 'e') goto yy186; yy351: YYDEBUG(351, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(352, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(353, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(354, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1651 "Zend/zend_language_scanner.l" { char *filename = zend_get_compiled_filename(TSRMLS_C); if (!filename) { filename = ""; } zendlval->value.str.len = strlen(filename); zendlval->value.str.val = estrndup(filename, zendlval->value.str.len); zendlval->type = IS_STRING; return T_FILE; } #line 4407 "Zend/zend_language_scanner.c" yy355: YYDEBUG(355, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy356; if (yych != 'a') goto yy186; yy356: YYDEBUG(356, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy357; if (yych != 'i') goto yy186; yy357: YYDEBUG(357, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy358; if (yych != 't') goto yy186; yy358: YYDEBUG(358, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(359, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(360, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(361, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1588 "Zend/zend_language_scanner.l" { const char *trait_name = NULL; if (CG(active_class_entry) && (ZEND_ACC_TRAIT == (CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT))) { trait_name = CG(active_class_entry)->name; } if (!trait_name) { trait_name = ""; } zendlval->value.str.len = strlen(trait_name); zendlval->value.str.val = estrndup(trait_name, zendlval->value.str.len); zendlval->type = IS_STRING; return T_TRAIT_C; } #line 4457 "Zend/zend_language_scanner.c" yy362: YYDEBUG(362, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy363; if (yych != 'a') goto yy186; yy363: YYDEBUG(363, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy364; if (yych != 's') goto yy186; yy364: YYDEBUG(364, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy365; if (yych != 's') goto yy186; yy365: YYDEBUG(365, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(366, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(367, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(368, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1561 "Zend/zend_language_scanner.l" { const char *class_name = NULL; if (CG(active_class_entry) && (ZEND_ACC_TRAIT == (CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT))) { /* We create a special __CLASS__ constant that is going to be resolved at run-time */ zendlval->value.str.len = sizeof("__CLASS__")-1; zendlval->value.str.val = estrndup("__CLASS__", zendlval->value.str.len); zendlval->type = IS_CONSTANT; } else { if (CG(active_class_entry)) { class_name = CG(active_class_entry)->name; } if (!class_name) { class_name = ""; } zendlval->value.str.len = strlen(class_name); zendlval->value.str.val = estrndup(class_name, zendlval->value.str.len); zendlval->type = IS_STRING; } return T_CLASS_C; } #line 4514 "Zend/zend_language_scanner.c" yy369: YYDEBUG(369, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy370; if (yych != 'l') goto yy186; yy370: YYDEBUG(370, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy371; if (yych != 't') goto yy186; yy371: YYDEBUG(371, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(372, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy373; if (yych != 'c') goto yy186; yy373: YYDEBUG(373, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy374; if (yych != 'o') goto yy186; yy374: YYDEBUG(374, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy375; if (yych != 'm') goto yy186; yy375: YYDEBUG(375, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy376; if (yych != 'p') goto yy186; yy376: YYDEBUG(376, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy377; if (yych != 'i') goto yy186; yy377: YYDEBUG(377, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy378; if (yych != 'l') goto yy186; yy378: YYDEBUG(378, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy379; if (yych != 'e') goto yy186; yy379: YYDEBUG(379, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy380; if (yych != 'r') goto yy186; yy380: YYDEBUG(380, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(381, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1279 "Zend/zend_language_scanner.l" { return T_HALT_COMPILER; } #line 4580 "Zend/zend_language_scanner.c" yy382: YYDEBUG(382, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy386; if (yych == 's') goto yy386; goto yy186; yy383: YYDEBUG(383, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy384; if (yych != 'e') goto yy186; yy384: YYDEBUG(384, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(385, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1259 "Zend/zend_language_scanner.l" { return T_USE; } #line 4604 "Zend/zend_language_scanner.c" yy386: YYDEBUG(386, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy387; if (yych != 'e') goto yy186; yy387: YYDEBUG(387, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy388; if (yych != 't') goto yy186; yy388: YYDEBUG(388, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(389, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1307 "Zend/zend_language_scanner.l" { return T_UNSET; } #line 4627 "Zend/zend_language_scanner.c" yy390: YYDEBUG(390, *YYCURSOR); ++YYCURSOR; YYFILL(7); yych = *YYCURSOR; yy391: YYDEBUG(391, *YYCURSOR); if (yych <= 'S') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy390; if (yych <= 0x1F) goto yy193; goto yy390; } else { if (yych <= 'A') { if (yych <= '@') goto yy193; goto yy395; } else { if (yych <= 'B') goto yy393; if (yych <= 'C') goto yy193; goto yy398; } } } else { if (yych <= 'I') { if (yych == 'F') goto yy399; if (yych <= 'H') goto yy193; goto yy400; } else { if (yych <= 'O') { if (yych <= 'N') goto yy193; goto yy394; } else { if (yych <= 'Q') goto yy193; if (yych <= 'R') goto yy397; goto yy396; } } } } else { if (yych <= 'f') { if (yych <= 'a') { if (yych == 'U') goto yy392; if (yych <= '`') goto yy193; goto yy395; } else { if (yych <= 'c') { if (yych <= 'b') goto yy393; goto yy193; } else { if (yych <= 'd') goto yy398; if (yych <= 'e') goto yy193; goto yy399; } } } else { if (yych <= 'q') { if (yych <= 'i') { if (yych <= 'h') goto yy193; goto yy400; } else { if (yych == 'o') goto yy394; goto yy193; } } else { if (yych <= 's') { if (yych <= 'r') goto yy397; goto yy396; } else { if (yych != 'u') goto yy193; } } } } yy392: YYDEBUG(392, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy459; if (yych == 'n') goto yy459; goto yy193; yy393: YYDEBUG(393, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'I') goto yy446; if (yych <= 'N') goto yy193; goto yy447; } else { if (yych <= 'i') { if (yych <= 'h') goto yy193; goto yy446; } else { if (yych == 'o') goto yy447; goto yy193; } } yy394: YYDEBUG(394, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy438; if (yych == 'b') goto yy438; goto yy193; yy395: YYDEBUG(395, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy431; if (yych == 'r') goto yy431; goto yy193; yy396: YYDEBUG(396, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy423; if (yych == 't') goto yy423; goto yy193; yy397: YYDEBUG(397, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy421; if (yych == 'e') goto yy421; goto yy193; yy398: YYDEBUG(398, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy417; if (yych == 'o') goto yy417; goto yy193; yy399: YYDEBUG(399, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy410; if (yych == 'l') goto yy410; goto yy193; yy400: YYDEBUG(400, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy401; if (yych != 'n') goto yy193; yy401: YYDEBUG(401, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy402; if (yych != 't') goto yy193; yy402: YYDEBUG(402, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy403; if (yych != 'e') goto yy405; yy403: YYDEBUG(403, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy408; if (yych == 'g') goto yy408; goto yy193; yy404: YYDEBUG(404, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy405: YYDEBUG(405, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy404; goto yy193; } else { if (yych <= ' ') goto yy404; if (yych != ')') goto yy193; } YYDEBUG(406, *YYCURSOR); ++YYCURSOR; YYDEBUG(407, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1207 "Zend/zend_language_scanner.l" { return T_INT_CAST; } #line 4803 "Zend/zend_language_scanner.c" yy408: YYDEBUG(408, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy409; if (yych != 'e') goto yy193; yy409: YYDEBUG(409, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy404; if (yych == 'r') goto yy404; goto yy193; yy410: YYDEBUG(410, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy411; if (yych != 'o') goto yy193; yy411: YYDEBUG(411, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy412; if (yych != 'a') goto yy193; yy412: YYDEBUG(412, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy413; if (yych != 't') goto yy193; yy413: YYDEBUG(413, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(414, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy413; goto yy193; } else { if (yych <= ' ') goto yy413; if (yych != ')') goto yy193; } YYDEBUG(415, *YYCURSOR); ++YYCURSOR; YYDEBUG(416, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1211 "Zend/zend_language_scanner.l" { return T_DOUBLE_CAST; } #line 4851 "Zend/zend_language_scanner.c" yy417: YYDEBUG(417, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy418; if (yych != 'u') goto yy193; yy418: YYDEBUG(418, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy419; if (yych != 'b') goto yy193; yy419: YYDEBUG(419, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy420; if (yych != 'l') goto yy193; yy420: YYDEBUG(420, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy413; if (yych == 'e') goto yy413; goto yy193; yy421: YYDEBUG(421, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy422; if (yych != 'a') goto yy193; yy422: YYDEBUG(422, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy413; if (yych == 'l') goto yy413; goto yy193; yy423: YYDEBUG(423, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy424; if (yych != 'r') goto yy193; yy424: YYDEBUG(424, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy425; if (yych != 'i') goto yy193; yy425: YYDEBUG(425, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy426; if (yych != 'n') goto yy193; yy426: YYDEBUG(426, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy427; if (yych != 'g') goto yy193; yy427: YYDEBUG(427, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(428, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy427; goto yy193; } else { if (yych <= ' ') goto yy427; if (yych != ')') goto yy193; } YYDEBUG(429, *YYCURSOR); ++YYCURSOR; YYDEBUG(430, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1215 "Zend/zend_language_scanner.l" { return T_STRING_CAST; } #line 4925 "Zend/zend_language_scanner.c" yy431: YYDEBUG(431, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy432; if (yych != 'r') goto yy193; yy432: YYDEBUG(432, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy433; if (yych != 'a') goto yy193; yy433: YYDEBUG(433, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy434; if (yych != 'y') goto yy193; yy434: YYDEBUG(434, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(435, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy434; goto yy193; } else { if (yych <= ' ') goto yy434; if (yych != ')') goto yy193; } YYDEBUG(436, *YYCURSOR); ++YYCURSOR; YYDEBUG(437, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1219 "Zend/zend_language_scanner.l" { return T_ARRAY_CAST; } #line 4962 "Zend/zend_language_scanner.c" yy438: YYDEBUG(438, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'J') goto yy439; if (yych != 'j') goto yy193; yy439: YYDEBUG(439, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy440; if (yych != 'e') goto yy193; yy440: YYDEBUG(440, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy441; if (yych != 'c') goto yy193; yy441: YYDEBUG(441, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy442; if (yych != 't') goto yy193; yy442: YYDEBUG(442, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(443, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy442; goto yy193; } else { if (yych <= ' ') goto yy442; if (yych != ')') goto yy193; } YYDEBUG(444, *YYCURSOR); ++YYCURSOR; YYDEBUG(445, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1223 "Zend/zend_language_scanner.l" { return T_OBJECT_CAST; } #line 5004 "Zend/zend_language_scanner.c" yy446: YYDEBUG(446, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy456; if (yych == 'n') goto yy456; goto yy193; yy447: YYDEBUG(447, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy448; if (yych != 'o') goto yy193; yy448: YYDEBUG(448, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy449; if (yych != 'l') goto yy193; yy449: YYDEBUG(449, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy454; if (yych == 'e') goto yy454; goto yy451; yy450: YYDEBUG(450, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy451: YYDEBUG(451, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy450; goto yy193; } else { if (yych <= ' ') goto yy450; if (yych != ')') goto yy193; } YYDEBUG(452, *YYCURSOR); ++YYCURSOR; YYDEBUG(453, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1227 "Zend/zend_language_scanner.l" { return T_BOOL_CAST; } #line 5049 "Zend/zend_language_scanner.c" yy454: YYDEBUG(454, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy455; if (yych != 'a') goto yy193; yy455: YYDEBUG(455, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy450; if (yych == 'n') goto yy450; goto yy193; yy456: YYDEBUG(456, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy457; if (yych != 'a') goto yy193; yy457: YYDEBUG(457, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy458; if (yych != 'r') goto yy193; yy458: YYDEBUG(458, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy427; if (yych == 'y') goto yy427; goto yy193; yy459: YYDEBUG(459, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy460; if (yych != 's') goto yy193; yy460: YYDEBUG(460, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy461; if (yych != 'e') goto yy193; yy461: YYDEBUG(461, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy462; if (yych != 't') goto yy193; yy462: YYDEBUG(462, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(463, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy462; goto yy193; } else { if (yych <= ' ') goto yy462; if (yych != ')') goto yy193; } YYDEBUG(464, *YYCURSOR); ++YYCURSOR; YYDEBUG(465, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1231 "Zend/zend_language_scanner.l" { return T_UNSET_CAST; } #line 5113 "Zend/zend_language_scanner.c" yy466: YYDEBUG(466, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy467; if (yych != 'r') goto yy186; yy467: YYDEBUG(467, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(468, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1203 "Zend/zend_language_scanner.l" { return T_VAR; } #line 5131 "Zend/zend_language_scanner.c" yy469: YYDEBUG(469, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy473; if (yych == 'm') goto yy473; goto yy186; yy470: YYDEBUG(470, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'W') goto yy471; if (yych != 'w') goto yy186; yy471: YYDEBUG(471, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(472, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1195 "Zend/zend_language_scanner.l" { return T_NEW; } #line 5155 "Zend/zend_language_scanner.c" yy473: YYDEBUG(473, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy474; if (yych != 'e') goto yy186; yy474: YYDEBUG(474, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy475; if (yych != 's') goto yy186; yy475: YYDEBUG(475, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy476; if (yych != 'p') goto yy186; yy476: YYDEBUG(476, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy477; if (yych != 'a') goto yy186; yy477: YYDEBUG(477, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy478; if (yych != 'c') goto yy186; yy478: YYDEBUG(478, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy479; if (yych != 'e') goto yy186; yy479: YYDEBUG(479, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(480, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1255 "Zend/zend_language_scanner.l" { return T_NAMESPACE; } #line 5198 "Zend/zend_language_scanner.c" yy481: YYDEBUG(481, *YYCURSOR); ++YYCURSOR; YYDEBUG(482, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1187 "Zend/zend_language_scanner.l" { return T_PAAMAYIM_NEKUDOTAYIM; } #line 5208 "Zend/zend_language_scanner.c" yy483: YYDEBUG(483, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy484: YYDEBUG(484, *YYCURSOR); if (yych <= '\f') { if (yych <= 0x08) goto yy140; if (yych <= '\n') goto yy483; goto yy140; } else { if (yych <= '\r') goto yy483; if (yych == ' ') goto yy483; goto yy140; } yy485: YYDEBUG(485, *YYCURSOR); ++YYCURSOR; YYDEBUG(486, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1363 "Zend/zend_language_scanner.l" { return T_MINUS_EQUAL; } #line 5234 "Zend/zend_language_scanner.c" yy487: YYDEBUG(487, *YYCURSOR); ++YYCURSOR; YYDEBUG(488, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1331 "Zend/zend_language_scanner.l" { return T_DEC; } #line 5244 "Zend/zend_language_scanner.c" yy489: YYDEBUG(489, *YYCURSOR); ++YYCURSOR; YYDEBUG(490, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1157 "Zend/zend_language_scanner.l" { yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC); return T_OBJECT_OPERATOR; } #line 5255 "Zend/zend_language_scanner.c" yy491: YYDEBUG(491, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'I') goto yy498; if (yych <= 'N') goto yy186; goto yy499; } else { if (yych <= 'i') { if (yych <= 'h') goto yy186; goto yy498; } else { if (yych == 'o') goto yy499; goto yy186; } } yy492: YYDEBUG(492, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy493; if (yych != 'b') goto yy186; yy493: YYDEBUG(493, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy494; if (yych != 'l') goto yy186; yy494: YYDEBUG(494, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy495; if (yych != 'i') goto yy186; yy495: YYDEBUG(495, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy496; if (yych != 'c') goto yy186; yy496: YYDEBUG(496, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(497, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1303 "Zend/zend_language_scanner.l" { return T_PUBLIC; } #line 5304 "Zend/zend_language_scanner.c" yy498: YYDEBUG(498, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'V') { if (yych == 'N') goto yy507; if (yych <= 'U') goto yy186; goto yy508; } else { if (yych <= 'n') { if (yych <= 'm') goto yy186; goto yy507; } else { if (yych == 'v') goto yy508; goto yy186; } } yy499: YYDEBUG(499, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy500; if (yych != 't') goto yy186; yy500: YYDEBUG(500, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy501; if (yych != 'e') goto yy186; yy501: YYDEBUG(501, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy502; if (yych != 'c') goto yy186; yy502: YYDEBUG(502, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy503; if (yych != 't') goto yy186; yy503: YYDEBUG(503, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy504; if (yych != 'e') goto yy186; yy504: YYDEBUG(504, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy505; if (yych != 'd') goto yy186; yy505: YYDEBUG(505, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(506, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1299 "Zend/zend_language_scanner.l" { return T_PROTECTED; } #line 5363 "Zend/zend_language_scanner.c" yy507: YYDEBUG(507, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy513; if (yych == 't') goto yy513; goto yy186; yy508: YYDEBUG(508, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy509; if (yych != 'a') goto yy186; yy509: YYDEBUG(509, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy510; if (yych != 't') goto yy186; yy510: YYDEBUG(510, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy511; if (yych != 'e') goto yy186; yy511: YYDEBUG(511, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(512, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1295 "Zend/zend_language_scanner.l" { return T_PRIVATE; } #line 5397 "Zend/zend_language_scanner.c" yy513: YYDEBUG(513, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(514, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1133 "Zend/zend_language_scanner.l" { return T_PRINT; } #line 5410 "Zend/zend_language_scanner.c" yy515: YYDEBUG(515, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy520; if (yych == 'o') goto yy520; goto yy186; yy516: YYDEBUG(516, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy517; if (yych != 't') goto yy186; yy517: YYDEBUG(517, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy518; if (yych != 'o') goto yy186; yy518: YYDEBUG(518, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(519, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1125 "Zend/zend_language_scanner.l" { return T_GOTO; } #line 5439 "Zend/zend_language_scanner.c" yy520: YYDEBUG(520, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy521; if (yych != 'b') goto yy186; yy521: YYDEBUG(521, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy522; if (yych != 'a') goto yy186; yy522: YYDEBUG(522, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy523; if (yych != 'l') goto yy186; yy523: YYDEBUG(523, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(524, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1267 "Zend/zend_language_scanner.l" { return T_GLOBAL; } #line 5467 "Zend/zend_language_scanner.c" yy525: YYDEBUG(525, *YYCURSOR); yych = *++YYCURSOR; if (yych == '<') goto yy533; goto yy193; yy526: YYDEBUG(526, *YYCURSOR); yych = *++YYCURSOR; goto yy180; yy527: YYDEBUG(527, *YYCURSOR); yych = *++YYCURSOR; goto yy178; yy528: YYDEBUG(528, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy529; if (yych != 'e') goto yy186; yy529: YYDEBUG(529, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy530; if (yych != 'a') goto yy186; yy530: YYDEBUG(530, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'K') goto yy531; if (yych != 'k') goto yy186; yy531: YYDEBUG(531, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(532, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1117 "Zend/zend_language_scanner.l" { return T_BREAK; } #line 5508 "Zend/zend_language_scanner.c" yy533: YYDEBUG(533, *YYCURSOR); yych = *++YYCURSOR; if (yych == '<') goto yy269; goto yy193; yy534: YYDEBUG(534, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy541; if (yych == 'a') goto yy541; goto yy186; yy535: YYDEBUG(535, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy536; if (yych != 'i') goto yy186; yy536: YYDEBUG(536, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy537; if (yych != 't') goto yy186; yy537: YYDEBUG(537, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy538; if (yych != 'c') goto yy186; yy538: YYDEBUG(538, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy539; if (yych != 'h') goto yy186; yy539: YYDEBUG(539, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(540, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1101 "Zend/zend_language_scanner.l" { return T_SWITCH; } #line 5552 "Zend/zend_language_scanner.c" yy541: YYDEBUG(541, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy542; if (yych != 't') goto yy186; yy542: YYDEBUG(542, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy543; if (yych != 'i') goto yy186; yy543: YYDEBUG(543, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy544; if (yych != 'c') goto yy186; yy544: YYDEBUG(544, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(545, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1283 "Zend/zend_language_scanner.l" { return T_STATIC; } #line 5580 "Zend/zend_language_scanner.c" yy546: YYDEBUG(546, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy557; if (yych == 's') goto yy557; goto yy186; yy547: YYDEBUG(547, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy555; if (yych == 'd') goto yy555; goto yy186; yy548: YYDEBUG(548, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy551; if (yych == 'r') goto yy551; goto yy186; yy549: YYDEBUG(549, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(550, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1097 "Zend/zend_language_scanner.l" { return T_AS; } #line 5611 "Zend/zend_language_scanner.c" yy551: YYDEBUG(551, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy552; if (yych != 'a') goto yy186; yy552: YYDEBUG(552, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy553; if (yych != 'y') goto yy186; yy553: YYDEBUG(553, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(554, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1319 "Zend/zend_language_scanner.l" { return T_ARRAY; } #line 5634 "Zend/zend_language_scanner.c" yy555: YYDEBUG(555, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(556, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1415 "Zend/zend_language_scanner.l" { return T_LOGICAL_AND; } #line 5647 "Zend/zend_language_scanner.c" yy557: YYDEBUG(557, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy558; if (yych != 't') goto yy186; yy558: YYDEBUG(558, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy559; if (yych != 'r') goto yy186; yy559: YYDEBUG(559, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy560; if (yych != 'a') goto yy186; yy560: YYDEBUG(560, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy561; if (yych != 'c') goto yy186; yy561: YYDEBUG(561, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy562; if (yych != 't') goto yy186; yy562: YYDEBUG(562, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(563, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1287 "Zend/zend_language_scanner.l" { return T_ABSTRACT; } #line 5685 "Zend/zend_language_scanner.c" yy564: YYDEBUG(564, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy565; if (yych != 'i') goto yy186; yy565: YYDEBUG(565, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy566; if (yych != 'l') goto yy186; yy566: YYDEBUG(566, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy567; if (yych != 'e') goto yy186; yy567: YYDEBUG(567, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(568, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1057 "Zend/zend_language_scanner.l" { return T_WHILE; } #line 5713 "Zend/zend_language_scanner.c" yy569: YYDEBUG(569, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(570, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1041 "Zend/zend_language_scanner.l" { return T_IF; } #line 5726 "Zend/zend_language_scanner.c" yy571: YYDEBUG(571, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy613; if (yych == 'p') goto yy613; goto yy186; yy572: YYDEBUG(572, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= 'C') { if (yych <= 'B') goto yy186; goto yy580; } else { if (yych <= 'R') goto yy186; if (yych <= 'S') goto yy578; goto yy579; } } else { if (yych <= 'r') { if (yych == 'c') goto yy580; goto yy186; } else { if (yych <= 's') goto yy578; if (yych <= 't') goto yy579; goto yy186; } } yy573: YYDEBUG(573, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy574; if (yych != 's') goto yy186; yy574: YYDEBUG(574, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy575; if (yych != 'e') goto yy186; yy575: YYDEBUG(575, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy576; if (yych != 't') goto yy186; yy576: YYDEBUG(576, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(577, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1271 "Zend/zend_language_scanner.l" { return T_ISSET; } #line 5782 "Zend/zend_language_scanner.c" yy578: YYDEBUG(578, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy599; if (yych == 't') goto yy599; goto yy186; yy579: YYDEBUG(579, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy592; if (yych == 'e') goto yy592; goto yy186; yy580: YYDEBUG(580, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy581; if (yych != 'l') goto yy186; yy581: YYDEBUG(581, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy582; if (yych != 'u') goto yy186; yy582: YYDEBUG(582, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy583; if (yych != 'd') goto yy186; yy583: YYDEBUG(583, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy584; if (yych != 'e') goto yy186; yy584: YYDEBUG(584, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '9') { if (yych >= '0') goto yy185; } else { if (yych <= '@') goto yy585; if (yych <= 'Z') goto yy185; } } else { if (yych <= '`') { if (yych <= '_') goto yy586; } else { if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy585: YYDEBUG(585, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1239 "Zend/zend_language_scanner.l" { return T_INCLUDE; } #line 5840 "Zend/zend_language_scanner.c" yy586: YYDEBUG(586, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy587; if (yych != 'o') goto yy186; yy587: YYDEBUG(587, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy588; if (yych != 'n') goto yy186; yy588: YYDEBUG(588, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy589; if (yych != 'c') goto yy186; yy589: YYDEBUG(589, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy590; if (yych != 'e') goto yy186; yy590: YYDEBUG(590, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(591, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1243 "Zend/zend_language_scanner.l" { return T_INCLUDE_ONCE; } #line 5873 "Zend/zend_language_scanner.c" yy592: YYDEBUG(592, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy593; if (yych != 'r') goto yy186; yy593: YYDEBUG(593, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy594; if (yych != 'f') goto yy186; yy594: YYDEBUG(594, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy595; if (yych != 'a') goto yy186; yy595: YYDEBUG(595, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy596; if (yych != 'c') goto yy186; yy596: YYDEBUG(596, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy597; if (yych != 'e') goto yy186; yy597: YYDEBUG(597, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(598, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1141 "Zend/zend_language_scanner.l" { return T_INTERFACE; } #line 5911 "Zend/zend_language_scanner.c" yy599: YYDEBUG(599, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych == 'A') goto yy600; if (yych <= 'D') goto yy186; goto yy601; } else { if (yych <= 'a') { if (yych <= '`') goto yy186; } else { if (yych == 'e') goto yy601; goto yy186; } } yy600: YYDEBUG(600, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy607; if (yych == 'n') goto yy607; goto yy186; yy601: YYDEBUG(601, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy602; if (yych != 'a') goto yy186; yy602: YYDEBUG(602, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy603; if (yych != 'd') goto yy186; yy603: YYDEBUG(603, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy604; if (yych != 'o') goto yy186; yy604: YYDEBUG(604, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy605; if (yych != 'f') goto yy186; yy605: YYDEBUG(605, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(606, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1263 "Zend/zend_language_scanner.l" { return T_INSTEADOF; } #line 5965 "Zend/zend_language_scanner.c" yy607: YYDEBUG(607, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy608; if (yych != 'c') goto yy186; yy608: YYDEBUG(608, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy609; if (yych != 'e') goto yy186; yy609: YYDEBUG(609, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy610; if (yych != 'o') goto yy186; yy610: YYDEBUG(610, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy611; if (yych != 'f') goto yy186; yy611: YYDEBUG(611, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(612, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1093 "Zend/zend_language_scanner.l" { return T_INSTANCEOF; } #line 5998 "Zend/zend_language_scanner.c" yy613: YYDEBUG(613, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy614; if (yych != 'l') goto yy186; yy614: YYDEBUG(614, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy615; if (yych != 'e') goto yy186; yy615: YYDEBUG(615, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy616; if (yych != 'm') goto yy186; yy616: YYDEBUG(616, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy617; if (yych != 'e') goto yy186; yy617: YYDEBUG(617, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy618; if (yych != 'n') goto yy186; yy618: YYDEBUG(618, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy619; if (yych != 't') goto yy186; yy619: YYDEBUG(619, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy620; if (yych != 's') goto yy186; yy620: YYDEBUG(620, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(621, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1153 "Zend/zend_language_scanner.l" { return T_IMPLEMENTS; } #line 6046 "Zend/zend_language_scanner.c" yy622: YYDEBUG(622, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy630; if (yych == 'r') goto yy630; goto yy186; yy623: YYDEBUG(623, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych == 'A') goto yy626; if (yych <= 'X') goto yy186; } else { if (yych <= 'a') { if (yych <= '`') goto yy186; goto yy626; } else { if (yych != 'y') goto yy186; } } YYDEBUG(624, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(625, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1029 "Zend/zend_language_scanner.l" { return T_TRY; } #line 6078 "Zend/zend_language_scanner.c" yy626: YYDEBUG(626, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy627; if (yych != 'i') goto yy186; yy627: YYDEBUG(627, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy628; if (yych != 't') goto yy186; yy628: YYDEBUG(628, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(629, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1145 "Zend/zend_language_scanner.l" { return T_TRAIT; } #line 6101 "Zend/zend_language_scanner.c" yy630: YYDEBUG(630, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy631; if (yych != 'o') goto yy186; yy631: YYDEBUG(631, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'W') goto yy632; if (yych != 'w') goto yy186; yy632: YYDEBUG(632, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(633, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1037 "Zend/zend_language_scanner.l" { return T_THROW; } #line 6124 "Zend/zend_language_scanner.c" yy634: YYDEBUG(634, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych == 'Q') goto yy636; if (yych <= 'S') goto yy186; } else { if (yych <= 'q') { if (yych <= 'p') goto yy186; goto yy636; } else { if (yych != 't') goto yy186; } } YYDEBUG(635, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy648; if (yych == 'u') goto yy648; goto yy186; yy636: YYDEBUG(636, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy637; if (yych != 'u') goto yy186; yy637: YYDEBUG(637, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy638; if (yych != 'i') goto yy186; yy638: YYDEBUG(638, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy639; if (yych != 'r') goto yy186; yy639: YYDEBUG(639, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy640; if (yych != 'e') goto yy186; yy640: YYDEBUG(640, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '9') { if (yych >= '0') goto yy185; } else { if (yych <= '@') goto yy641; if (yych <= 'Z') goto yy185; } } else { if (yych <= '`') { if (yych <= '_') goto yy642; } else { if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy641: YYDEBUG(641, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1247 "Zend/zend_language_scanner.l" { return T_REQUIRE; } #line 6189 "Zend/zend_language_scanner.c" yy642: YYDEBUG(642, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy643; if (yych != 'o') goto yy186; yy643: YYDEBUG(643, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy644; if (yych != 'n') goto yy186; yy644: YYDEBUG(644, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy645; if (yych != 'c') goto yy186; yy645: YYDEBUG(645, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy646; if (yych != 'e') goto yy186; yy646: YYDEBUG(646, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(647, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1251 "Zend/zend_language_scanner.l" { return T_REQUIRE_ONCE; } #line 6222 "Zend/zend_language_scanner.c" yy648: YYDEBUG(648, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy649; if (yych != 'r') goto yy186; yy649: YYDEBUG(649, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy650; if (yych != 'n') goto yy186; yy650: YYDEBUG(650, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(651, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1025 "Zend/zend_language_scanner.l" { return T_RETURN; } #line 6245 "Zend/zend_language_scanner.c" yy652: YYDEBUG(652, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= 'L') { if (yych <= 'K') goto yy186; goto yy675; } else { if (yych <= 'R') goto yy186; if (yych <= 'S') goto yy674; goto yy673; } } else { if (yych <= 'r') { if (yych == 'l') goto yy675; goto yy186; } else { if (yych <= 's') goto yy674; if (yych <= 't') goto yy673; goto yy186; } } yy653: YYDEBUG(653, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'A') goto yy665; if (yych <= 'N') goto yy186; goto yy666; } else { if (yych <= 'a') { if (yych <= '`') goto yy186; goto yy665; } else { if (yych == 'o') goto yy666; goto yy186; } } yy654: YYDEBUG(654, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy655; if (yych != 'n') goto yy186; yy655: YYDEBUG(655, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= 'R') goto yy186; if (yych >= 'T') goto yy657; } else { if (yych <= 'r') goto yy186; if (yych <= 's') goto yy656; if (yych <= 't') goto yy657; goto yy186; } yy656: YYDEBUG(656, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy663; if (yych == 't') goto yy663; goto yy186; yy657: YYDEBUG(657, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy658; if (yych != 'i') goto yy186; yy658: YYDEBUG(658, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy659; if (yych != 'n') goto yy186; yy659: YYDEBUG(659, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy660; if (yych != 'u') goto yy186; yy660: YYDEBUG(660, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy661; if (yych != 'e') goto yy186; yy661: YYDEBUG(661, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(662, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1121 "Zend/zend_language_scanner.l" { return T_CONTINUE; } #line 6339 "Zend/zend_language_scanner.c" yy663: YYDEBUG(663, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(664, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1021 "Zend/zend_language_scanner.l" { return T_CONST; } #line 6352 "Zend/zend_language_scanner.c" yy665: YYDEBUG(665, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy670; if (yych == 's') goto yy670; goto yy186; yy666: YYDEBUG(666, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy667; if (yych != 'n') goto yy186; yy667: YYDEBUG(667, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy668; if (yych != 'e') goto yy186; yy668: YYDEBUG(668, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(669, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1199 "Zend/zend_language_scanner.l" { return T_CLONE; } #line 6381 "Zend/zend_language_scanner.c" yy670: YYDEBUG(670, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy671; if (yych != 's') goto yy186; yy671: YYDEBUG(671, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(672, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1137 "Zend/zend_language_scanner.l" { return T_CLASS; } #line 6399 "Zend/zend_language_scanner.c" yy673: YYDEBUG(673, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy684; if (yych == 'c') goto yy684; goto yy186; yy674: YYDEBUG(674, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy682; if (yych == 'e') goto yy682; goto yy186; yy675: YYDEBUG(675, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy676; if (yych != 'l') goto yy186; yy676: YYDEBUG(676, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy677; if (yych != 'a') goto yy186; yy677: YYDEBUG(677, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy678; if (yych != 'b') goto yy186; yy678: YYDEBUG(678, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy679; if (yych != 'l') goto yy186; yy679: YYDEBUG(679, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy680; if (yych != 'e') goto yy186; yy680: YYDEBUG(680, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(681, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1323 "Zend/zend_language_scanner.l" { return T_CALLABLE; } #line 6449 "Zend/zend_language_scanner.c" yy682: YYDEBUG(682, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(683, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1109 "Zend/zend_language_scanner.l" { return T_CASE; } #line 6462 "Zend/zend_language_scanner.c" yy684: YYDEBUG(684, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy685; if (yych != 'h') goto yy186; yy685: YYDEBUG(685, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(686, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1033 "Zend/zend_language_scanner.l" { return T_CATCH; } #line 6480 "Zend/zend_language_scanner.c" yy687: YYDEBUG(687, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy704; if (yych == 'n') goto yy704; goto yy186; yy688: YYDEBUG(688, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy697; if (yych == 'r') goto yy697; goto yy186; yy689: YYDEBUG(689, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy690; if (yych != 'n') goto yy186; yy690: YYDEBUG(690, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy691; if (yych != 'c') goto yy186; yy691: YYDEBUG(691, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy692; if (yych != 't') goto yy186; yy692: YYDEBUG(692, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy693; if (yych != 'i') goto yy186; yy693: YYDEBUG(693, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy694; if (yych != 'o') goto yy186; yy694: YYDEBUG(694, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy695; if (yych != 'n') goto yy186; yy695: YYDEBUG(695, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(696, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1017 "Zend/zend_language_scanner.l" { return T_FUNCTION; } #line 6535 "Zend/zend_language_scanner.c" yy697: YYDEBUG(697, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '@') { if (yych <= '/') goto yy698; if (yych <= '9') goto yy185; } else { if (yych == 'E') goto yy699; if (yych <= 'Z') goto yy185; } } else { if (yych <= 'd') { if (yych != '`') goto yy185; } else { if (yych <= 'e') goto yy699; if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy698: YYDEBUG(698, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1069 "Zend/zend_language_scanner.l" { return T_FOR; } #line 6563 "Zend/zend_language_scanner.c" yy699: YYDEBUG(699, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy700; if (yych != 'a') goto yy186; yy700: YYDEBUG(700, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy701; if (yych != 'c') goto yy186; yy701: YYDEBUG(701, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy702; if (yych != 'h') goto yy186; yy702: YYDEBUG(702, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(703, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1077 "Zend/zend_language_scanner.l" { return T_FOREACH; } #line 6591 "Zend/zend_language_scanner.c" yy704: YYDEBUG(704, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy705; if (yych != 'a') goto yy186; yy705: YYDEBUG(705, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy706; if (yych != 'l') goto yy186; yy706: YYDEBUG(706, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(707, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1291 "Zend/zend_language_scanner.l" { return T_FINAL; } #line 6614 "Zend/zend_language_scanner.c" yy708: YYDEBUG(708, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'F') { if (yych == 'C') goto yy714; if (yych <= 'E') goto yy186; goto yy715; } else { if (yych <= 'c') { if (yych <= 'b') goto yy186; goto yy714; } else { if (yych == 'f') goto yy715; goto yy186; } } yy709: YYDEBUG(709, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy712; if (yych == 'e') goto yy712; goto yy186; yy710: YYDEBUG(710, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(711, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1065 "Zend/zend_language_scanner.l" { return T_DO; } #line 6649 "Zend/zend_language_scanner.c" yy712: YYDEBUG(712, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(713, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1013 "Zend/zend_language_scanner.l" { return T_EXIT; } #line 6662 "Zend/zend_language_scanner.c" yy714: YYDEBUG(714, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy721; if (yych == 'l') goto yy721; goto yy186; yy715: YYDEBUG(715, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy716; if (yych != 'a') goto yy186; yy716: YYDEBUG(716, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy717; if (yych != 'u') goto yy186; yy717: YYDEBUG(717, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy718; if (yych != 'l') goto yy186; yy718: YYDEBUG(718, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy719; if (yych != 't') goto yy186; yy719: YYDEBUG(719, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(720, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1113 "Zend/zend_language_scanner.l" { return T_DEFAULT; } #line 6701 "Zend/zend_language_scanner.c" yy721: YYDEBUG(721, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy722; if (yych != 'a') goto yy186; yy722: YYDEBUG(722, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy723; if (yych != 'r') goto yy186; yy723: YYDEBUG(723, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy724; if (yych != 'e') goto yy186; yy724: YYDEBUG(724, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(725, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1085 "Zend/zend_language_scanner.l" { return T_DECLARE; } #line 6729 "Zend/zend_language_scanner.c" yy726: YYDEBUG(726, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy788; if (yych == 'h') goto yy788; goto yy186; yy727: YYDEBUG(727, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy782; if (yych == 's') goto yy782; goto yy186; yy728: YYDEBUG(728, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy778; if (yych == 'p') goto yy778; goto yy186; yy729: YYDEBUG(729, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy744; if (yych == 'd') goto yy744; goto yy186; yy730: YYDEBUG(730, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy741; if (yych == 'a') goto yy741; goto yy186; yy731: YYDEBUG(731, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych == 'I') goto yy732; if (yych <= 'S') goto yy186; goto yy733; } else { if (yych <= 'i') { if (yych <= 'h') goto yy186; } else { if (yych == 't') goto yy733; goto yy186; } } yy732: YYDEBUG(732, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy739; if (yych == 't') goto yy739; goto yy186; yy733: YYDEBUG(733, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy734; if (yych != 'e') goto yy186; yy734: YYDEBUG(734, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy735; if (yych != 'n') goto yy186; yy735: YYDEBUG(735, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy736; if (yych != 'd') goto yy186; yy736: YYDEBUG(736, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy737; if (yych != 's') goto yy186; yy737: YYDEBUG(737, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(738, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1149 "Zend/zend_language_scanner.l" { return T_EXTENDS; } #line 6813 "Zend/zend_language_scanner.c" yy739: YYDEBUG(739, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(740, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1009 "Zend/zend_language_scanner.l" { return T_EXIT; } #line 6826 "Zend/zend_language_scanner.c" yy741: YYDEBUG(741, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy742; if (yych != 'l') goto yy186; yy742: YYDEBUG(742, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(743, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1235 "Zend/zend_language_scanner.l" { return T_EVAL; } #line 6844 "Zend/zend_language_scanner.c" yy744: YYDEBUG(744, *YYCURSOR); yych = *++YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case 'D': case 'd': goto yy745; case 'F': case 'f': goto yy746; case 'I': case 'i': goto yy747; case 'S': case 's': goto yy748; case 'W': case 'w': goto yy749; default: goto yy186; } yy745: YYDEBUG(745, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy771; if (yych == 'e') goto yy771; goto yy186; yy746: YYDEBUG(746, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy763; if (yych == 'o') goto yy763; goto yy186; yy747: YYDEBUG(747, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy761; if (yych == 'f') goto yy761; goto yy186; yy748: YYDEBUG(748, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'W') goto yy755; if (yych == 'w') goto yy755; goto yy186; yy749: YYDEBUG(749, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy750; if (yych != 'h') goto yy186; yy750: YYDEBUG(750, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy751; if (yych != 'i') goto yy186; yy751: YYDEBUG(751, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy752; if (yych != 'l') goto yy186; yy752: YYDEBUG(752, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy753; if (yych != 'e') goto yy186; yy753: YYDEBUG(753, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(754, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1061 "Zend/zend_language_scanner.l" { return T_ENDWHILE; } #line 6918 "Zend/zend_language_scanner.c" yy755: YYDEBUG(755, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy756; if (yych != 'i') goto yy186; yy756: YYDEBUG(756, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy757; if (yych != 't') goto yy186; yy757: YYDEBUG(757, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy758; if (yych != 'c') goto yy186; yy758: YYDEBUG(758, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy759; if (yych != 'h') goto yy186; yy759: YYDEBUG(759, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(760, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1105 "Zend/zend_language_scanner.l" { return T_ENDSWITCH; } #line 6951 "Zend/zend_language_scanner.c" yy761: YYDEBUG(761, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(762, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1049 "Zend/zend_language_scanner.l" { return T_ENDIF; } #line 6964 "Zend/zend_language_scanner.c" yy763: YYDEBUG(763, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy764; if (yych != 'r') goto yy186; yy764: YYDEBUG(764, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '@') { if (yych <= '/') goto yy765; if (yych <= '9') goto yy185; } else { if (yych == 'E') goto yy766; if (yych <= 'Z') goto yy185; } } else { if (yych <= 'd') { if (yych != '`') goto yy185; } else { if (yych <= 'e') goto yy766; if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy765: YYDEBUG(765, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1073 "Zend/zend_language_scanner.l" { return T_ENDFOR; } #line 6997 "Zend/zend_language_scanner.c" yy766: YYDEBUG(766, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy767; if (yych != 'a') goto yy186; yy767: YYDEBUG(767, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy768; if (yych != 'c') goto yy186; yy768: YYDEBUG(768, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy769; if (yych != 'h') goto yy186; yy769: YYDEBUG(769, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(770, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1081 "Zend/zend_language_scanner.l" { return T_ENDFOREACH; } #line 7025 "Zend/zend_language_scanner.c" yy771: YYDEBUG(771, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy772; if (yych != 'c') goto yy186; yy772: YYDEBUG(772, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy773; if (yych != 'l') goto yy186; yy773: YYDEBUG(773, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy774; if (yych != 'a') goto yy186; yy774: YYDEBUG(774, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy775; if (yych != 'r') goto yy186; yy775: YYDEBUG(775, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy776; if (yych != 'e') goto yy186; yy776: YYDEBUG(776, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(777, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1089 "Zend/zend_language_scanner.l" { return T_ENDDECLARE; } #line 7063 "Zend/zend_language_scanner.c" yy778: YYDEBUG(778, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy779; if (yych != 't') goto yy186; yy779: YYDEBUG(779, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy780; if (yych != 'y') goto yy186; yy780: YYDEBUG(780, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(781, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1275 "Zend/zend_language_scanner.l" { return T_EMPTY; } #line 7086 "Zend/zend_language_scanner.c" yy782: YYDEBUG(782, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy783; if (yych != 'e') goto yy186; yy783: YYDEBUG(783, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '@') { if (yych <= '/') goto yy784; if (yych <= '9') goto yy185; } else { if (yych == 'I') goto yy785; if (yych <= 'Z') goto yy185; } } else { if (yych <= 'h') { if (yych != '`') goto yy185; } else { if (yych <= 'i') goto yy785; if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy784: YYDEBUG(784, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1053 "Zend/zend_language_scanner.l" { return T_ELSE; } #line 7119 "Zend/zend_language_scanner.c" yy785: YYDEBUG(785, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy786; if (yych != 'f') goto yy186; yy786: YYDEBUG(786, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(787, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1045 "Zend/zend_language_scanner.l" { return T_ELSEIF; } #line 7137 "Zend/zend_language_scanner.c" yy788: YYDEBUG(788, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy789; if (yych != 'o') goto yy186; yy789: YYDEBUG(789, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(790, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1129 "Zend/zend_language_scanner.l" { return T_ECHO; } #line 7155 "Zend/zend_language_scanner.c" } /* *********************************** */ yyc_ST_LOOKING_FOR_PROPERTY: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 0, 0, 0, 0, 0, 0, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 0, 0, 0, 0, 64, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 0, 0, 0, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, }; YYDEBUG(791, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych <= '-') { if (yych <= '\r') { if (yych <= 0x08) goto yy799; if (yych <= '\n') goto yy793; if (yych <= '\f') goto yy799; } else { if (yych == ' ') goto yy793; if (yych <= ',') goto yy799; goto yy795; } } else { if (yych <= '_') { if (yych <= '@') goto yy799; if (yych <= 'Z') goto yy797; if (yych <= '^') goto yy799; goto yy797; } else { if (yych <= '`') goto yy799; if (yych <= 'z') goto yy797; if (yych <= '~') goto yy799; goto yy797; } } yy793: YYDEBUG(793, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy805; yy794: YYDEBUG(794, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1162 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; HANDLE_NEWLINES(yytext, yyleng); return T_WHITESPACE; } #line 7236 "Zend/zend_language_scanner.c" yy795: YYDEBUG(795, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '>') goto yy802; yy796: YYDEBUG(796, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1181 "Zend/zend_language_scanner.l" { yyless(0); yy_pop_state(TSRMLS_C); goto restart; } #line 7250 "Zend/zend_language_scanner.c" yy797: YYDEBUG(797, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy801; yy798: YYDEBUG(798, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1174 "Zend/zend_language_scanner.l" { yy_pop_state(TSRMLS_C); zend_copy_value(zendlval, yytext, yyleng); zendlval->type = IS_STRING; return T_STRING; } #line 7266 "Zend/zend_language_scanner.c" yy799: YYDEBUG(799, *YYCURSOR); yych = *++YYCURSOR; goto yy796; yy800: YYDEBUG(800, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy801: YYDEBUG(801, *YYCURSOR); if (yybm[0+yych] & 64) { goto yy800; } goto yy798; yy802: YYDEBUG(802, *YYCURSOR); ++YYCURSOR; YYDEBUG(803, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1170 "Zend/zend_language_scanner.l" { return T_OBJECT_OPERATOR; } #line 7291 "Zend/zend_language_scanner.c" yy804: YYDEBUG(804, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy805: YYDEBUG(805, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy804; } goto yy794; } /* *********************************** */ yyc_ST_LOOKING_FOR_VARNAME: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; YYDEBUG(806, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy810; if (yych <= 'Z') goto yy808; if (yych <= '^') goto yy810; } else { if (yych <= '`') goto yy810; if (yych <= 'z') goto yy808; if (yych <= '~') goto yy810; } yy808: YYDEBUG(808, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy813; yy809: YYDEBUG(809, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1457 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, yytext, yyleng); zendlval->type = IS_STRING; yy_pop_state(TSRMLS_C); yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); return T_STRING_VARNAME; } #line 7369 "Zend/zend_language_scanner.c" yy810: YYDEBUG(810, *YYCURSOR); ++YYCURSOR; YYDEBUG(811, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1466 "Zend/zend_language_scanner.l" { yyless(0); yy_pop_state(TSRMLS_C); yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); goto restart; } #line 7382 "Zend/zend_language_scanner.c" yy812: YYDEBUG(812, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy813: YYDEBUG(813, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy812; } goto yy809; } /* *********************************** */ yyc_ST_NOWDOC: YYDEBUG(814, *YYCURSOR); YYFILL(1); yych = *YYCURSOR; YYDEBUG(816, *YYCURSOR); ++YYCURSOR; YYDEBUG(817, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2340 "Zend/zend_language_scanner.l" { int newline = 0; if (YYCURSOR > YYLIMIT) { return 0; } YYCURSOR--; while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '\r': if (*YYCURSOR == '\n') { YYCURSOR++; } /* fall through */ case '\n': /* Check for ending label on the next line */ if (IS_LABEL_START(*YYCURSOR) && CG(heredoc_len) < YYLIMIT - YYCURSOR && !memcmp(YYCURSOR, CG(heredoc), CG(heredoc_len))) { YYCTYPE *end = YYCURSOR + CG(heredoc_len); if (*end == ';') { end++; } if (*end == '\n' || *end == '\r') { /* newline before label will be subtracted from returned text, but * yyleng/yytext will include it, for zend_highlight/strip, tokenizer, etc. */ if (YYCURSOR[-2] == '\r' && YYCURSOR[-1] == '\n') { newline = 2; /* Windows newline */ } else { newline = 1; } CG(increment_lineno) = 1; /* For newline before label */ BEGIN(ST_END_HEREDOC); goto nowdoc_scan_done; } } /* fall through */ default: continue; } } nowdoc_scan_done: yyleng = YYCURSOR - SCNG(yy_text); zend_copy_value(zendlval, yytext, yyleng - newline); zendlval->type = IS_STRING; HANDLE_NEWLINES(yytext, yyleng - newline); return T_ENCAPSED_AND_WHITESPACE; } #line 7459 "Zend/zend_language_scanner.c" /* *********************************** */ yyc_ST_VAR_OFFSET: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 240, 240, 112, 112, 112, 112, 112, 112, 112, 112, 0, 0, 0, 0, 0, 0, 0, 80, 80, 80, 80, 80, 80, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 16, 0, 80, 80, 80, 80, 80, 80, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, }; YYDEBUG(818, *YYCURSOR); YYFILL(3); yych = *YYCURSOR; if (yych <= '/') { if (yych <= ' ') { if (yych <= '\f') { if (yych <= 0x08) goto yy832; if (yych <= '\n') goto yy828; goto yy832; } else { if (yych <= '\r') goto yy828; if (yych <= 0x1F) goto yy832; goto yy828; } } else { if (yych <= '$') { if (yych <= '"') goto yy827; if (yych <= '#') goto yy828; goto yy823; } else { if (yych == '\'') goto yy828; goto yy827; } } } else { if (yych <= '\\') { if (yych <= '@') { if (yych <= '0') goto yy820; if (yych <= '9') goto yy822; goto yy827; } else { if (yych <= 'Z') goto yy830; if (yych <= '[') goto yy827; goto yy828; } } else { if (yych <= '_') { if (yych <= ']') goto yy825; if (yych <= '^') goto yy827; goto yy830; } else { if (yych <= '`') goto yy827; if (yych <= 'z') goto yy830; if (yych <= '~') goto yy827; goto yy830; } } } yy820: YYDEBUG(820, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'W') { if (yych <= '9') { if (yych >= '0') goto yy844; } else { if (yych == 'B') goto yy841; } } else { if (yych <= 'b') { if (yych <= 'X') goto yy843; if (yych >= 'b') goto yy841; } else { if (yych == 'x') goto yy843; } } yy821: YYDEBUG(821, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1536 "Zend/zend_language_scanner.l" { /* Offset could be treated as a long */ if (yyleng < MAX_LENGTH_OF_LONG - 1 || (yyleng == MAX_LENGTH_OF_LONG - 1 && strcmp(yytext, long_min_digits) < 0)) { zendlval->value.lval = strtol(yytext, NULL, 10); zendlval->type = IS_LONG; } else { zendlval->value.str.val = (char *)estrndup(yytext, yyleng); zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; } return T_NUM_STRING; } #line 7578 "Zend/zend_language_scanner.c" yy822: YYDEBUG(822, *YYCURSOR); yych = *++YYCURSOR; goto yy840; yy823: YYDEBUG(823, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '_') { if (yych <= '@') goto yy824; if (yych <= 'Z') goto yy836; if (yych >= '_') goto yy836; } else { if (yych <= '`') goto yy824; if (yych <= 'z') goto yy836; if (yych >= 0x7F) goto yy836; } yy824: YYDEBUG(824, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1868 "Zend/zend_language_scanner.l" { /* Only '[' can be valid, but returning other tokens will allow a more explicit parse error */ return yytext[0]; } #line 7603 "Zend/zend_language_scanner.c" yy825: YYDEBUG(825, *YYCURSOR); ++YYCURSOR; YYDEBUG(826, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1863 "Zend/zend_language_scanner.l" { yy_pop_state(TSRMLS_C); return ']'; } #line 7614 "Zend/zend_language_scanner.c" yy827: YYDEBUG(827, *YYCURSOR); yych = *++YYCURSOR; goto yy824; yy828: YYDEBUG(828, *YYCURSOR); ++YYCURSOR; YYDEBUG(829, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1873 "Zend/zend_language_scanner.l" { /* Invalid rule to return a more explicit parse error with proper line number */ yyless(0); yy_pop_state(TSRMLS_C); return T_ENCAPSED_AND_WHITESPACE; } #line 7631 "Zend/zend_language_scanner.c" yy830: YYDEBUG(830, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy835; yy831: YYDEBUG(831, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1880 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, yytext, yyleng); zendlval->type = IS_STRING; return T_STRING; } #line 7646 "Zend/zend_language_scanner.c" yy832: YYDEBUG(832, *YYCURSOR); ++YYCURSOR; YYDEBUG(833, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2396 "Zend/zend_language_scanner.l" { if (YYCURSOR > YYLIMIT) { return 0; } zend_error(E_COMPILE_WARNING,"Unexpected character in input: '%c' (ASCII=%d) state=%d", yytext[0], yytext[0], YYSTATE); goto restart; } #line 7661 "Zend/zend_language_scanner.c" yy834: YYDEBUG(834, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy835: YYDEBUG(835, *YYCURSOR); if (yybm[0+yych] & 16) { goto yy834; } goto yy831; yy836: YYDEBUG(836, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(837, *YYCURSOR); if (yych <= '^') { if (yych <= '9') { if (yych >= '0') goto yy836; } else { if (yych <= '@') goto yy838; if (yych <= 'Z') goto yy836; } } else { if (yych <= '`') { if (yych <= '_') goto yy836; } else { if (yych <= 'z') goto yy836; if (yych >= 0x7F) goto yy836; } } yy838: YYDEBUG(838, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1857 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 7703 "Zend/zend_language_scanner.c" yy839: YYDEBUG(839, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy840: YYDEBUG(840, *YYCURSOR); if (yybm[0+yych] & 32) { goto yy839; } goto yy821; yy841: YYDEBUG(841, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 128) { goto yy849; } yy842: YYDEBUG(842, *YYCURSOR); YYCURSOR = YYMARKER; goto yy821; yy843: YYDEBUG(843, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 64) { goto yy847; } goto yy842; yy844: YYDEBUG(844, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(845, *YYCURSOR); if (yych <= '/') goto yy846; if (yych <= '9') goto yy844; yy846: YYDEBUG(846, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1548 "Zend/zend_language_scanner.l" { /* Offset must be treated as a string */ zendlval->value.str.val = (char *)estrndup(yytext, yyleng); zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; return T_NUM_STRING; } #line 7750 "Zend/zend_language_scanner.c" yy847: YYDEBUG(847, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(848, *YYCURSOR); if (yybm[0+yych] & 64) { goto yy847; } goto yy846; yy849: YYDEBUG(849, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(850, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy849; } goto yy846; } } #line 2405 "Zend/zend_language_scanner.l" }
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2012-01-17-032d140fd6-877f97cde1.c
manybugs_data_68
/*--------------------------------------------------------------------*/ /*--- Helgrind: a Valgrind tool for detecting errors ---*/ /*--- in threaded programs. hg_main.c ---*/ /*--------------------------------------------------------------------*/ /* This file is part of Helgrind, a Valgrind tool for detecting errors in threaded programs. Copyright (C) 2007-2010 OpenWorks LLP [email protected] Copyright (C) 2007-2010 Apple, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. The GNU General Public License is contained in the file COPYING. Neither the names of the U.S. Department of Energy nor the University of California nor the names of its contributors may be used to endorse or promote products derived from this software without prior written permission. */ #include "pub_tool_basics.h" #include "pub_tool_libcassert.h" #include "pub_tool_libcbase.h" #include "pub_tool_libcprint.h" #include "pub_tool_threadstate.h" #include "pub_tool_tooliface.h" #include "pub_tool_hashtable.h" #include "pub_tool_replacemalloc.h" #include "pub_tool_machine.h" #include "pub_tool_options.h" #include "pub_tool_xarray.h" #include "pub_tool_stacktrace.h" #include "pub_tool_wordfm.h" #include "pub_tool_debuginfo.h" // VG_(find_seginfo), VG_(seginfo_soname) #include "pub_tool_redir.h" // sonames for the dynamic linkers #include "pub_tool_vki.h" // VKI_PAGE_SIZE #include "pub_tool_libcproc.h" // VG_(atfork) #include "pub_tool_aspacemgr.h" // VG_(am_is_valid_for_client) #include "hg_basics.h" #include "hg_wordset.h" #include "hg_lock_n_thread.h" #include "hg_errors.h" #include "libhb.h" #include "helgrind.h" // FIXME: new_mem_w_tid ignores the supplied tid. (wtf?!) // FIXME: when client destroys a lock or a CV, remove these // from our mappings, so that the associated SO can be freed up /*----------------------------------------------------------------*/ /*--- ---*/ /*----------------------------------------------------------------*/ /* Note this needs to be compiled with -fno-strict-aliasing, since it contains a whole bunch of calls to lookupFM etc which cast between Word and pointer types. gcc rightly complains this breaks ANSI C strict aliasing rules, at -O2. No complaints at -O, but -O2 gives worthwhile performance benefits over -O. */ // FIXME what is supposed to happen to locks in memory which // is relocated as a result of client realloc? // FIXME put referencing ThreadId into Thread and get // rid of the slow reverse mapping function. // FIXME accesses to NoAccess areas: change state to Excl? // FIXME report errors for accesses of NoAccess memory? // FIXME pth_cond_wait/timedwait wrappers. Even if these fail, // the thread still holds the lock. /* ------------ Debug/trace options ------------ */ // 0 for silent, 1 for some stuff, 2 for lots of stuff #define SHOW_EVENTS 0 static void all__sanity_check ( Char* who ); /* fwds */ #define HG_CLI__MALLOC_REDZONE_SZB 16 /* let's say */ // 0 for none, 1 for dump at end of run #define SHOW_DATA_STRUCTURES 0 /* ------------ Misc comments ------------ */ // FIXME: don't hardwire initial entries for root thread. // Instead, let the pre_thread_ll_create handler do this. /*----------------------------------------------------------------*/ /*--- Primary data structures ---*/ /*----------------------------------------------------------------*/ /* Admin linked list of Threads */ static Thread* admin_threads = NULL; /* Admin double linked list of Locks */ /* We need a double linked list to properly and efficiently handle del_LockN. */ static Lock* admin_locks = NULL; /* Mapping table for core ThreadIds to Thread* */ static Thread** map_threads = NULL; /* Array[VG_N_THREADS] of Thread* */ /* Mapping table for lock guest addresses to Lock* */ static WordFM* map_locks = NULL; /* WordFM LockAddr Lock* */ /* The word-set universes for lock sets. */ static WordSetU* univ_lsets = NULL; /* sets of Lock* */ static WordSetU* univ_laog = NULL; /* sets of Lock*, for LAOG */ /*----------------------------------------------------------------*/ /*--- Simple helpers for the data structures ---*/ /*----------------------------------------------------------------*/ static UWord stats__lockN_acquires = 0; static UWord stats__lockN_releases = 0; static ThreadId map_threads_maybe_reverse_lookup_SLOW ( Thread* thr ); /*fwds*/ /* --------- Constructors --------- */ static Thread* mk_Thread ( Thr* hbthr ) { static Int indx = 1; Thread* thread = HG_(zalloc)( "hg.mk_Thread.1", sizeof(Thread) ); thread->locksetA = HG_(emptyWS)( univ_lsets ); thread->locksetW = HG_(emptyWS)( univ_lsets ); thread->magic = Thread_MAGIC; thread->hbthr = hbthr; thread->coretid = VG_INVALID_THREADID; thread->created_at = NULL; thread->announced = False; thread->errmsg_index = indx++; thread->admin = admin_threads; admin_threads = thread; return thread; } // Make a new lock which is unlocked (hence ownerless) // and insert the new lock in admin_locks double linked list. static Lock* mk_LockN ( LockKind kind, Addr guestaddr ) { static ULong unique = 0; Lock* lock = HG_(zalloc)( "hg.mk_Lock.1", sizeof(Lock) ); /* begin: add to double linked list */ if (admin_locks) admin_locks->admin_prev = lock; lock->admin_next = admin_locks; lock->admin_prev = NULL; admin_locks = lock; /* end: add */ lock->unique = unique++; lock->magic = LockN_MAGIC; lock->appeared_at = NULL; lock->acquired_at = NULL; lock->hbso = libhb_so_alloc(); lock->guestaddr = guestaddr; lock->kind = kind; lock->heldW = False; lock->heldBy = NULL; tl_assert(HG_(is_sane_LockN)(lock)); return lock; } /* Release storage for a Lock. Also release storage in .heldBy, if any. Removes from admin_locks double linked list. */ static void del_LockN ( Lock* lk ) { tl_assert(HG_(is_sane_LockN)(lk)); tl_assert(lk->hbso); libhb_so_dealloc(lk->hbso); if (lk->heldBy) VG_(deleteBag)( lk->heldBy ); /* begin: del lock from double linked list */ if (lk == admin_locks) { tl_assert(lk->admin_prev == NULL); if (lk->admin_next) lk->admin_next->admin_prev = NULL; admin_locks = lk->admin_next; } else { tl_assert(lk->admin_prev != NULL); lk->admin_prev->admin_next = lk->admin_next; if (lk->admin_next) lk->admin_next->admin_prev = lk->admin_prev; } /* end: del */ VG_(memset)(lk, 0xAA, sizeof(*lk)); HG_(free)(lk); } /* Update 'lk' to reflect that 'thr' now has a write-acquisition of it. This is done strictly: only combinations resulting from correct program and libpthread behaviour are allowed. */ static void lockN_acquire_writer ( Lock* lk, Thread* thr ) { tl_assert(HG_(is_sane_LockN)(lk)); tl_assert(HG_(is_sane_Thread)(thr)); stats__lockN_acquires++; /* EXPOSITION only */ /* We need to keep recording snapshots of where the lock was acquired, so as to produce better lock-order error messages. */ if (lk->acquired_at == NULL) { ThreadId tid; tl_assert(lk->heldBy == NULL); tid = map_threads_maybe_reverse_lookup_SLOW(thr); lk->acquired_at = VG_(record_ExeContext)(tid, 0/*first_ip_delta*/); } else { tl_assert(lk->heldBy != NULL); } /* end EXPOSITION only */ switch (lk->kind) { case LK_nonRec: case_LK_nonRec: tl_assert(lk->heldBy == NULL); /* can't w-lock recursively */ tl_assert(!lk->heldW); lk->heldW = True; lk->heldBy = VG_(newBag)( HG_(zalloc), "hg.lNaw.1", HG_(free) ); VG_(addToBag)( lk->heldBy, (Word)thr ); break; case LK_mbRec: if (lk->heldBy == NULL) goto case_LK_nonRec; /* 2nd and subsequent locking of a lock by its owner */ tl_assert(lk->heldW); /* assert: lk is only held by one thread .. */ tl_assert(VG_(sizeUniqueBag(lk->heldBy)) == 1); /* assert: .. and that thread is 'thr'. */ tl_assert(VG_(elemBag)(lk->heldBy, (Word)thr) == VG_(sizeTotalBag)(lk->heldBy)); VG_(addToBag)(lk->heldBy, (Word)thr); break; case LK_rdwr: tl_assert(lk->heldBy == NULL && !lk->heldW); /* must be unheld */ goto case_LK_nonRec; default: tl_assert(0); } tl_assert(HG_(is_sane_LockN)(lk)); } static void lockN_acquire_reader ( Lock* lk, Thread* thr ) { tl_assert(HG_(is_sane_LockN)(lk)); tl_assert(HG_(is_sane_Thread)(thr)); /* can only add reader to a reader-writer lock. */ tl_assert(lk->kind == LK_rdwr); /* lk must be free or already r-held. */ tl_assert(lk->heldBy == NULL || (lk->heldBy != NULL && !lk->heldW)); stats__lockN_acquires++; /* EXPOSITION only */ /* We need to keep recording snapshots of where the lock was acquired, so as to produce better lock-order error messages. */ if (lk->acquired_at == NULL) { ThreadId tid; tl_assert(lk->heldBy == NULL); tid = map_threads_maybe_reverse_lookup_SLOW(thr); lk->acquired_at = VG_(record_ExeContext)(tid, 0/*first_ip_delta*/); } else { tl_assert(lk->heldBy != NULL); } /* end EXPOSITION only */ if (lk->heldBy) { VG_(addToBag)(lk->heldBy, (Word)thr); } else { lk->heldW = False; lk->heldBy = VG_(newBag)( HG_(zalloc), "hg.lNar.1", HG_(free) ); VG_(addToBag)( lk->heldBy, (Word)thr ); } tl_assert(!lk->heldW); tl_assert(HG_(is_sane_LockN)(lk)); } /* Update 'lk' to reflect a release of it by 'thr'. This is done strictly: only combinations resulting from correct program and libpthread behaviour are allowed. */ static void lockN_release ( Lock* lk, Thread* thr ) { Bool b; tl_assert(HG_(is_sane_LockN)(lk)); tl_assert(HG_(is_sane_Thread)(thr)); /* lock must be held by someone */ tl_assert(lk->heldBy); stats__lockN_releases++; /* Remove it from the holder set */ b = VG_(delFromBag)(lk->heldBy, (Word)thr); /* thr must actually have been a holder of lk */ tl_assert(b); /* normalise */ tl_assert(lk->acquired_at); if (VG_(isEmptyBag)(lk->heldBy)) { VG_(deleteBag)(lk->heldBy); lk->heldBy = NULL; lk->heldW = False; lk->acquired_at = NULL; } tl_assert(HG_(is_sane_LockN)(lk)); } static void remove_Lock_from_locksets_of_all_owning_Threads( Lock* lk ) { Thread* thr; if (!lk->heldBy) { tl_assert(!lk->heldW); return; } /* for each thread that holds this lock do ... */ VG_(initIterBag)( lk->heldBy ); while (VG_(nextIterBag)( lk->heldBy, (Word*)&thr, NULL )) { tl_assert(HG_(is_sane_Thread)(thr)); tl_assert(HG_(elemWS)( univ_lsets, thr->locksetA, (Word)lk )); thr->locksetA = HG_(delFromWS)( univ_lsets, thr->locksetA, (Word)lk ); if (lk->heldW) { tl_assert(HG_(elemWS)( univ_lsets, thr->locksetW, (Word)lk )); thr->locksetW = HG_(delFromWS)( univ_lsets, thr->locksetW, (Word)lk ); } } VG_(doneIterBag)( lk->heldBy ); } /*----------------------------------------------------------------*/ /*--- Print out the primary data structures ---*/ /*----------------------------------------------------------------*/ #define PP_THREADS (1<<1) #define PP_LOCKS (1<<2) #define PP_ALL (PP_THREADS | PP_LOCKS) static const Int sHOW_ADMIN = 0; static void space ( Int n ) { Int i; Char spaces[128+1]; tl_assert(n >= 0 && n < 128); if (n == 0) return; for (i = 0; i < n; i++) spaces[i] = ' '; spaces[i] = 0; tl_assert(i < 128+1); VG_(printf)("%s", spaces); } static void pp_Thread ( Int d, Thread* t ) { space(d+0); VG_(printf)("Thread %p {\n", t); if (sHOW_ADMIN) { space(d+3); VG_(printf)("admin %p\n", t->admin); space(d+3); VG_(printf)("magic 0x%x\n", (UInt)t->magic); } space(d+3); VG_(printf)("locksetA %d\n", (Int)t->locksetA); space(d+3); VG_(printf)("locksetW %d\n", (Int)t->locksetW); space(d+0); VG_(printf)("}\n"); } static void pp_admin_threads ( Int d ) { Int i, n; Thread* t; for (n = 0, t = admin_threads; t; n++, t = t->admin) { /* nothing */ } space(d); VG_(printf)("admin_threads (%d records) {\n", n); for (i = 0, t = admin_threads; t; i++, t = t->admin) { if (0) { space(n); VG_(printf)("admin_threads record %d of %d:\n", i, n); } pp_Thread(d+3, t); } space(d); VG_(printf)("}\n"); } static void pp_map_threads ( Int d ) { Int i, n = 0; space(d); VG_(printf)("map_threads "); for (i = 0; i < VG_N_THREADS; i++) { if (map_threads[i] != NULL) n++; } VG_(printf)("(%d entries) {\n", n); for (i = 0; i < VG_N_THREADS; i++) { if (map_threads[i] == NULL) continue; space(d+3); VG_(printf)("coretid %d -> Thread %p\n", i, map_threads[i]); } space(d); VG_(printf)("}\n"); } static const HChar* show_LockKind ( LockKind lkk ) { switch (lkk) { case LK_mbRec: return "mbRec"; case LK_nonRec: return "nonRec"; case LK_rdwr: return "rdwr"; default: tl_assert(0); } } static void pp_Lock ( Int d, Lock* lk ) { space(d+0); VG_(printf)("Lock %p (ga %#lx) {\n", lk, lk->guestaddr); if (sHOW_ADMIN) { space(d+3); VG_(printf)("admin_n %p\n", lk->admin_next); space(d+3); VG_(printf)("admin_p %p\n", lk->admin_prev); space(d+3); VG_(printf)("magic 0x%x\n", (UInt)lk->magic); } space(d+3); VG_(printf)("unique %llu\n", lk->unique); space(d+3); VG_(printf)("kind %s\n", show_LockKind(lk->kind)); space(d+3); VG_(printf)("heldW %s\n", lk->heldW ? "yes" : "no"); space(d+3); VG_(printf)("heldBy %p", lk->heldBy); if (lk->heldBy) { Thread* thr; Word count; VG_(printf)(" { "); VG_(initIterBag)( lk->heldBy ); while (VG_(nextIterBag)( lk->heldBy, (Word*)&thr, &count )) VG_(printf)("%lu:%p ", count, thr); VG_(doneIterBag)( lk->heldBy ); VG_(printf)("}"); } VG_(printf)("\n"); space(d+0); VG_(printf)("}\n"); } static void pp_admin_locks ( Int d ) { Int i, n; Lock* lk; for (n = 0, lk = admin_locks; lk; n++, lk = lk->admin_next) { /* nothing */ } space(d); VG_(printf)("admin_locks (%d records) {\n", n); for (i = 0, lk = admin_locks; lk; i++, lk = lk->admin_next) { if (0) { space(n); VG_(printf)("admin_locks record %d of %d:\n", i, n); } pp_Lock(d+3, lk); } space(d); VG_(printf)("}\n"); } static void pp_map_locks ( Int d ) { void* gla; Lock* lk; space(d); VG_(printf)("map_locks (%d entries) {\n", (Int)VG_(sizeFM)( map_locks )); VG_(initIterFM)( map_locks ); while (VG_(nextIterFM)( map_locks, (Word*)&gla, (Word*)&lk )) { space(d+3); VG_(printf)("guest %p -> Lock %p\n", gla, lk); } VG_(doneIterFM)( map_locks ); space(d); VG_(printf)("}\n"); } static void pp_everything ( Int flags, Char* caller ) { Int d = 0; VG_(printf)("\n"); VG_(printf)("All_Data_Structures (caller = \"%s\") {\n", caller); if (flags & PP_THREADS) { VG_(printf)("\n"); pp_admin_threads(d+3); VG_(printf)("\n"); pp_map_threads(d+3); } if (flags & PP_LOCKS) { VG_(printf)("\n"); pp_admin_locks(d+3); VG_(printf)("\n"); pp_map_locks(d+3); } VG_(printf)("\n"); VG_(printf)("}\n"); VG_(printf)("\n"); } #undef SHOW_ADMIN /*----------------------------------------------------------------*/ /*--- Initialise the primary data structures ---*/ /*----------------------------------------------------------------*/ static void initialise_data_structures ( Thr* hbthr_root ) { Thread* thr; /* Get everything initialised and zeroed. */ tl_assert(admin_threads == NULL); tl_assert(admin_locks == NULL); tl_assert(sizeof(Addr) == sizeof(Word)); tl_assert(map_threads == NULL); map_threads = HG_(zalloc)( "hg.ids.1", VG_N_THREADS * sizeof(Thread*) ); tl_assert(map_threads != NULL); tl_assert(sizeof(Addr) == sizeof(Word)); tl_assert(map_locks == NULL); map_locks = VG_(newFM)( HG_(zalloc), "hg.ids.2", HG_(free), NULL/*unboxed Word cmp*/); tl_assert(map_locks != NULL); tl_assert(univ_lsets == NULL); univ_lsets = HG_(newWordSetU)( HG_(zalloc), "hg.ids.4", HG_(free), 8/*cacheSize*/ ); tl_assert(univ_lsets != NULL); tl_assert(univ_laog == NULL); if (HG_(clo_track_lockorders)) { univ_laog = HG_(newWordSetU)( HG_(zalloc), "hg.ids.5 (univ_laog)", HG_(free), 24/*cacheSize*/ ); tl_assert(univ_laog != NULL); } /* Set up entries for the root thread */ // FIXME: this assumes that the first real ThreadId is 1 /* a Thread for the new thread ... */ thr = mk_Thread(hbthr_root); thr->coretid = 1; /* FIXME: hardwires an assumption about the identity of the root thread. */ tl_assert( libhb_get_Thr_hgthread(hbthr_root) == NULL ); libhb_set_Thr_hgthread(hbthr_root, thr); /* and bind it in the thread-map table. */ tl_assert(HG_(is_sane_ThreadId)(thr->coretid)); tl_assert(thr->coretid != VG_INVALID_THREADID); map_threads[thr->coretid] = thr; tl_assert(VG_INVALID_THREADID == 0); all__sanity_check("initialise_data_structures"); } /*----------------------------------------------------------------*/ /*--- map_threads :: array[core-ThreadId] of Thread* ---*/ /*----------------------------------------------------------------*/ /* Doesn't assert if the relevant map_threads entry is NULL. */ static Thread* map_threads_maybe_lookup ( ThreadId coretid ) { Thread* thr; tl_assert( HG_(is_sane_ThreadId)(coretid) ); thr = map_threads[coretid]; return thr; } /* Asserts if the relevant map_threads entry is NULL. */ static inline Thread* map_threads_lookup ( ThreadId coretid ) { Thread* thr; tl_assert( HG_(is_sane_ThreadId)(coretid) ); thr = map_threads[coretid]; tl_assert(thr); return thr; } /* Do a reverse lookup. Does not assert if 'thr' is not found in map_threads. */ static ThreadId map_threads_maybe_reverse_lookup_SLOW ( Thread* thr ) { ThreadId tid; tl_assert(HG_(is_sane_Thread)(thr)); /* Check nobody used the invalid-threadid slot */ tl_assert(VG_INVALID_THREADID >= 0 && VG_INVALID_THREADID < VG_N_THREADS); tl_assert(map_threads[VG_INVALID_THREADID] == NULL); tid = thr->coretid; tl_assert(HG_(is_sane_ThreadId)(tid)); return tid; } /* Do a reverse lookup. Warning: POTENTIALLY SLOW. Asserts if 'thr' is not found in map_threads. */ static ThreadId map_threads_reverse_lookup_SLOW ( Thread* thr ) { ThreadId tid = map_threads_maybe_reverse_lookup_SLOW( thr ); tl_assert(tid != VG_INVALID_THREADID); tl_assert(map_threads[tid]); tl_assert(map_threads[tid]->coretid == tid); return tid; } static void map_threads_delete ( ThreadId coretid ) { Thread* thr; tl_assert(coretid != 0); tl_assert( HG_(is_sane_ThreadId)(coretid) ); thr = map_threads[coretid]; tl_assert(thr); map_threads[coretid] = NULL; } /*----------------------------------------------------------------*/ /*--- map_locks :: WordFM guest-Addr-of-lock Lock* ---*/ /*----------------------------------------------------------------*/ /* Make sure there is a lock table entry for the given (lock) guest address. If not, create one of the stated 'kind' in unheld state. In any case, return the address of the existing or new Lock. */ static Lock* map_locks_lookup_or_create ( LockKind lkk, Addr ga, ThreadId tid ) { Bool found; Lock* oldlock = NULL; tl_assert(HG_(is_sane_ThreadId)(tid)); found = VG_(lookupFM)( map_locks, NULL, (Word*)&oldlock, (Word)ga ); if (!found) { Lock* lock = mk_LockN(lkk, ga); lock->appeared_at = VG_(record_ExeContext)( tid, 0 ); tl_assert(HG_(is_sane_LockN)(lock)); VG_(addToFM)( map_locks, (Word)ga, (Word)lock ); tl_assert(oldlock == NULL); return lock; } else { tl_assert(oldlock != NULL); tl_assert(HG_(is_sane_LockN)(oldlock)); tl_assert(oldlock->guestaddr == ga); return oldlock; } } static Lock* map_locks_maybe_lookup ( Addr ga ) { Bool found; Lock* lk = NULL; found = VG_(lookupFM)( map_locks, NULL, (Word*)&lk, (Word)ga ); tl_assert(found ? lk != NULL : lk == NULL); return lk; } static void map_locks_delete ( Addr ga ) { Addr ga2 = 0; Lock* lk = NULL; VG_(delFromFM)( map_locks, (Word*)&ga2, (Word*)&lk, (Word)ga ); /* delFromFM produces the val which is being deleted, if it is found. So assert it is non-null; that in effect asserts that we are deleting a (ga, Lock) pair which actually exists. */ tl_assert(lk != NULL); tl_assert(ga2 == ga); } /*----------------------------------------------------------------*/ /*--- Sanity checking the data structures ---*/ /*----------------------------------------------------------------*/ static UWord stats__sanity_checks = 0; static void laog__sanity_check ( Char* who ); /* fwds */ /* REQUIRED INVARIANTS: Thread vs Segment/Lock/SecMaps for each t in Threads { // Thread.lockset: each element is really a valid Lock // Thread.lockset: each Lock in set is actually held by that thread for lk in Thread.lockset lk == LockedBy(t) // Thread.csegid is a valid SegmentID // and the associated Segment has .thr == t } all thread Locksets are pairwise empty under intersection (that is, no lock is claimed to be held by more than one thread) -- this is guaranteed if all locks in locksets point back to their owner threads Lock vs Thread/Segment/SecMaps for each entry (gla, la) in map_locks gla == la->guest_addr for each lk in Locks { lk->tag is valid lk->guest_addr does not have shadow state NoAccess if lk == LockedBy(t), then t->lockset contains lk if lk == UnlockedBy(segid) then segid is valid SegmentID and can be mapped to a valid Segment(seg) and seg->thr->lockset does not contain lk if lk == UnlockedNew then (no lockset contains lk) secmaps for lk has .mbHasLocks == True } Segment vs Thread/Lock/SecMaps the Segment graph is a dag (no cycles) all of the Segment graph must be reachable from the segids mentioned in the Threads for seg in Segments { seg->thr is a sane Thread } SecMaps vs Segment/Thread/Lock for sm in SecMaps { sm properly aligned if any shadow word is ShR or ShM then .mbHasShared == True for each Excl(segid) state map_segments_lookup maps to a sane Segment(seg) for each ShM/ShR(tsetid,lsetid) state each lk in lset is a valid Lock each thr in tset is a valid thread, which is non-dead } */ /* Return True iff 'thr' holds 'lk' in some mode. */ static Bool thread_is_a_holder_of_Lock ( Thread* thr, Lock* lk ) { if (lk->heldBy) return VG_(elemBag)( lk->heldBy, (Word)thr ) > 0; else return False; } /* Sanity check Threads, as far as possible */ __attribute__((noinline)) static void threads__sanity_check ( Char* who ) { #define BAD(_str) do { how = (_str); goto bad; } while (0) Char* how = "no error"; Thread* thr; WordSetID wsA, wsW; UWord* ls_words; Word ls_size, i; Lock* lk; for (thr = admin_threads; thr; thr = thr->admin) { if (!HG_(is_sane_Thread)(thr)) BAD("1"); wsA = thr->locksetA; wsW = thr->locksetW; // locks held in W mode are a subset of all locks held if (!HG_(isSubsetOf)( univ_lsets, wsW, wsA )) BAD("7"); HG_(getPayloadWS)( &ls_words, &ls_size, univ_lsets, wsA ); for (i = 0; i < ls_size; i++) { lk = (Lock*)ls_words[i]; // Thread.lockset: each element is really a valid Lock if (!HG_(is_sane_LockN)(lk)) BAD("2"); // Thread.lockset: each Lock in set is actually held by that // thread if (!thread_is_a_holder_of_Lock(thr,lk)) BAD("3"); } } return; bad: VG_(printf)("threads__sanity_check: who=\"%s\", bad=\"%s\"\n", who, how); tl_assert(0); #undef BAD } /* Sanity check Locks, as far as possible */ __attribute__((noinline)) static void locks__sanity_check ( Char* who ) { #define BAD(_str) do { how = (_str); goto bad; } while (0) Char* how = "no error"; Addr gla; Lock* lk; Int i; // # entries in admin_locks == # entries in map_locks for (i = 0, lk = admin_locks; lk; i++, lk = lk->admin_next) ; if (i != VG_(sizeFM)(map_locks)) BAD("1"); // for each entry (gla, lk) in map_locks // gla == lk->guest_addr VG_(initIterFM)( map_locks ); while (VG_(nextIterFM)( map_locks, (Word*)&gla, (Word*)&lk )) { if (lk->guestaddr != gla) BAD("2"); } VG_(doneIterFM)( map_locks ); // scan through admin_locks ... for (lk = admin_locks; lk; lk = lk->admin_next) { // lock is sane. Quite comprehensive, also checks that // referenced (holder) threads are sane. if (!HG_(is_sane_LockN)(lk)) BAD("3"); // map_locks binds guest address back to this lock if (lk != map_locks_maybe_lookup(lk->guestaddr)) BAD("4"); // look at all threads mentioned as holders of this lock. Ensure // this lock is mentioned in their locksets. if (lk->heldBy) { Thread* thr; Word count; VG_(initIterBag)( lk->heldBy ); while (VG_(nextIterBag)( lk->heldBy, (Word*)&thr, &count )) { // HG_(is_sane_LockN) above ensures these tl_assert(count >= 1); tl_assert(HG_(is_sane_Thread)(thr)); if (!HG_(elemWS)(univ_lsets, thr->locksetA, (Word)lk)) BAD("6"); // also check the w-only lockset if (lk->heldW && !HG_(elemWS)(univ_lsets, thr->locksetW, (Word)lk)) BAD("7"); if ((!lk->heldW) && HG_(elemWS)(univ_lsets, thr->locksetW, (Word)lk)) BAD("8"); } VG_(doneIterBag)( lk->heldBy ); } else { /* lock not held by anybody */ if (lk->heldW) BAD("9"); /* should be False if !heldBy */ // since lk is unheld, then (no lockset contains lk) // hmm, this is really too expensive to check. Hmm. } } return; bad: VG_(printf)("locks__sanity_check: who=\"%s\", bad=\"%s\"\n", who, how); tl_assert(0); #undef BAD } static void all_except_Locks__sanity_check ( Char* who ) { stats__sanity_checks++; if (0) VG_(printf)("all_except_Locks__sanity_check(%s)\n", who); threads__sanity_check(who); if (HG_(clo_track_lockorders)) laog__sanity_check(who); } static void all__sanity_check ( Char* who ) { all_except_Locks__sanity_check(who); locks__sanity_check(who); } /*----------------------------------------------------------------*/ /*--- Shadow value and address range handlers ---*/ /*----------------------------------------------------------------*/ static void laog__pre_thread_acquires_lock ( Thread*, Lock* ); /* fwds */ //static void laog__handle_lock_deletions ( WordSetID ); /* fwds */ static inline Thread* get_current_Thread ( void ); /* fwds */ __attribute__((noinline)) static void laog__handle_one_lock_deletion ( Lock* lk ); /* fwds */ /* Block-copy states (needed for implementing realloc()). */ /* FIXME this copies shadow memory; it doesn't apply the MSM to it. Is that a problem? (hence 'scopy' rather than 'ccopy') */ static void shadow_mem_scopy_range ( Thread* thr, Addr src, Addr dst, SizeT len ) { Thr* hbthr = thr->hbthr; tl_assert(hbthr); libhb_copy_shadow_state( hbthr, src, dst, len ); } static void shadow_mem_cread_range ( Thread* thr, Addr a, SizeT len ) { Thr* hbthr = thr->hbthr; tl_assert(hbthr); LIBHB_CREAD_N(hbthr, a, len); } static void shadow_mem_cwrite_range ( Thread* thr, Addr a, SizeT len ) { Thr* hbthr = thr->hbthr; tl_assert(hbthr); LIBHB_CWRITE_N(hbthr, a, len); } static void shadow_mem_make_New ( Thread* thr, Addr a, SizeT len ) { libhb_srange_new( thr->hbthr, a, len ); } static void shadow_mem_make_NoAccess ( Thread* thr, Addr aIN, SizeT len ) { if (0 && len > 500) VG_(printf)("make NoAccess ( %#lx, %ld )\n", aIN, len ); libhb_srange_noaccess( thr->hbthr, aIN, len ); } static void shadow_mem_make_Untracked ( Thread* thr, Addr aIN, SizeT len ) { if (0 && len > 500) VG_(printf)("make Untracked ( %#lx, %ld )\n", aIN, len ); libhb_srange_untrack( thr->hbthr, aIN, len ); } /*----------------------------------------------------------------*/ /*--- Event handlers (evh__* functions) ---*/ /*--- plus helpers (evhH__* functions) ---*/ /*----------------------------------------------------------------*/ /*--------- Event handler helpers (evhH__* functions) ---------*/ /* Create a new segment for 'thr', making it depend (.prev) on its existing segment, bind together the SegmentID and Segment, and return both of them. Also update 'thr' so it references the new Segment. */ //zz static //zz void evhH__start_new_segment_for_thread ( /*OUT*/SegmentID* new_segidP, //zz /*OUT*/Segment** new_segP, //zz Thread* thr ) //zz { //zz Segment* cur_seg; //zz tl_assert(new_segP); //zz tl_assert(new_segidP); //zz tl_assert(HG_(is_sane_Thread)(thr)); //zz cur_seg = map_segments_lookup( thr->csegid ); //zz tl_assert(cur_seg); //zz tl_assert(cur_seg->thr == thr); /* all sane segs should point back //zz at their owner thread. */ //zz *new_segP = mk_Segment( thr, cur_seg, NULL/*other*/ ); //zz *new_segidP = alloc_SegmentID(); //zz map_segments_add( *new_segidP, *new_segP ); //zz thr->csegid = *new_segidP; //zz } /* The lock at 'lock_ga' has acquired a writer. Make all necessary updates, and also do all possible error checks. */ static void evhH__post_thread_w_acquires_lock ( Thread* thr, LockKind lkk, Addr lock_ga ) { Lock* lk; /* Basically what we need to do is call lockN_acquire_writer. However, that will barf if any 'invalid' lock states would result. Therefore check before calling. Side effect is that 'HG_(is_sane_LockN)(lk)' is both a pre- and post-condition of this routine. Because this routine is only called after successful lock acquisition, we should not be asked to move the lock into any invalid states. Requests to do so are bugs in libpthread, since that should have rejected any such requests. */ tl_assert(HG_(is_sane_Thread)(thr)); /* Try to find the lock. If we can't, then create a new one with kind 'lkk'. */ lk = map_locks_lookup_or_create( lkk, lock_ga, map_threads_reverse_lookup_SLOW(thr) ); tl_assert( HG_(is_sane_LockN)(lk) ); /* check libhb level entities exist */ tl_assert(thr->hbthr); tl_assert(lk->hbso); if (lk->heldBy == NULL) { /* the lock isn't held. Simple. */ tl_assert(!lk->heldW); lockN_acquire_writer( lk, thr ); /* acquire a dependency from the lock's VCs */ libhb_so_recv( thr->hbthr, lk->hbso, True/*strong_recv*/ ); goto noerror; } /* So the lock is already held. If held as a r-lock then libpthread must be buggy. */ tl_assert(lk->heldBy); if (!lk->heldW) { HG_(record_error_Misc)( thr, "Bug in libpthread: write lock " "granted on rwlock which is currently rd-held"); goto error; } /* So the lock is held in w-mode. If it's held by some other thread, then libpthread must be buggy. */ tl_assert(VG_(sizeUniqueBag)(lk->heldBy) == 1); /* from precondition */ if (thr != (Thread*)VG_(anyElementOfBag)(lk->heldBy)) { HG_(record_error_Misc)( thr, "Bug in libpthread: write lock " "granted on mutex/rwlock which is currently " "wr-held by a different thread"); goto error; } /* So the lock is already held in w-mode by 'thr'. That means this is an attempt to lock it recursively, which is only allowable for LK_mbRec kinded locks. Since this routine is called only once the lock has been acquired, this must also be a libpthread bug. */ if (lk->kind != LK_mbRec) { HG_(record_error_Misc)( thr, "Bug in libpthread: recursive write lock " "granted on mutex/wrlock which does not " "support recursion"); goto error; } /* So we are recursively re-locking a lock we already w-hold. */ lockN_acquire_writer( lk, thr ); /* acquire a dependency from the lock's VC. Probably pointless, but also harmless. */ libhb_so_recv( thr->hbthr, lk->hbso, True/*strong_recv*/ ); goto noerror; noerror: if (HG_(clo_track_lockorders)) { /* check lock order acquisition graph, and update. This has to happen before the lock is added to the thread's locksetA/W. */ laog__pre_thread_acquires_lock( thr, lk ); } /* update the thread's held-locks set */ thr->locksetA = HG_(addToWS)( univ_lsets, thr->locksetA, (Word)lk ); thr->locksetW = HG_(addToWS)( univ_lsets, thr->locksetW, (Word)lk ); /* fall through */ error: tl_assert(HG_(is_sane_LockN)(lk)); } /* The lock at 'lock_ga' has acquired a reader. Make all necessary updates, and also do all possible error checks. */ static void evhH__post_thread_r_acquires_lock ( Thread* thr, LockKind lkk, Addr lock_ga ) { Lock* lk; /* Basically what we need to do is call lockN_acquire_reader. However, that will barf if any 'invalid' lock states would result. Therefore check before calling. Side effect is that 'HG_(is_sane_LockN)(lk)' is both a pre- and post-condition of this routine. Because this routine is only called after successful lock acquisition, we should not be asked to move the lock into any invalid states. Requests to do so are bugs in libpthread, since that should have rejected any such requests. */ tl_assert(HG_(is_sane_Thread)(thr)); /* Try to find the lock. If we can't, then create a new one with kind 'lkk'. Only a reader-writer lock can be read-locked, hence the first assertion. */ tl_assert(lkk == LK_rdwr); lk = map_locks_lookup_or_create( lkk, lock_ga, map_threads_reverse_lookup_SLOW(thr) ); tl_assert( HG_(is_sane_LockN)(lk) ); /* check libhb level entities exist */ tl_assert(thr->hbthr); tl_assert(lk->hbso); if (lk->heldBy == NULL) { /* the lock isn't held. Simple. */ tl_assert(!lk->heldW); lockN_acquire_reader( lk, thr ); /* acquire a dependency from the lock's VC */ libhb_so_recv( thr->hbthr, lk->hbso, False/*!strong_recv*/ ); goto noerror; } /* So the lock is already held. If held as a w-lock then libpthread must be buggy. */ tl_assert(lk->heldBy); if (lk->heldW) { HG_(record_error_Misc)( thr, "Bug in libpthread: read lock " "granted on rwlock which is " "currently wr-held"); goto error; } /* Easy enough. In short anybody can get a read-lock on a rwlock provided it is either unlocked or already in rd-held. */ lockN_acquire_reader( lk, thr ); /* acquire a dependency from the lock's VC. Probably pointless, but also harmless. */ libhb_so_recv( thr->hbthr, lk->hbso, False/*!strong_recv*/ ); goto noerror; noerror: if (HG_(clo_track_lockorders)) { /* check lock order acquisition graph, and update. This has to happen before the lock is added to the thread's locksetA/W. */ laog__pre_thread_acquires_lock( thr, lk ); } /* update the thread's held-locks set */ thr->locksetA = HG_(addToWS)( univ_lsets, thr->locksetA, (Word)lk ); /* but don't update thr->locksetW, since lk is only rd-held */ /* fall through */ error: tl_assert(HG_(is_sane_LockN)(lk)); } /* The lock at 'lock_ga' is just about to be unlocked. Make all necessary updates, and also do all possible error checks. */ static void evhH__pre_thread_releases_lock ( Thread* thr, Addr lock_ga, Bool isRDWR ) { Lock* lock; Word n; Bool was_heldW; /* This routine is called prior to a lock release, before libpthread has had a chance to validate the call. Hence we need to detect and reject any attempts to move the lock into an invalid state. Such attempts are bugs in the client. isRDWR is True if we know from the wrapper context that lock_ga should refer to a reader-writer lock, and is False if [ditto] lock_ga should refer to a standard mutex. */ tl_assert(HG_(is_sane_Thread)(thr)); lock = map_locks_maybe_lookup( lock_ga ); if (!lock) { /* We know nothing about a lock at 'lock_ga'. Nevertheless the client is trying to unlock it. So complain, then ignore the attempt. */ HG_(record_error_UnlockBogus)( thr, lock_ga ); return; } tl_assert(lock->guestaddr == lock_ga); tl_assert(HG_(is_sane_LockN)(lock)); if (isRDWR && lock->kind != LK_rdwr) { HG_(record_error_Misc)( thr, "pthread_rwlock_unlock with a " "pthread_mutex_t* argument " ); } if ((!isRDWR) && lock->kind == LK_rdwr) { HG_(record_error_Misc)( thr, "pthread_mutex_unlock with a " "pthread_rwlock_t* argument " ); } if (!lock->heldBy) { /* The lock is not held. This indicates a serious bug in the client. */ tl_assert(!lock->heldW); HG_(record_error_UnlockUnlocked)( thr, lock ); tl_assert(!HG_(elemWS)( univ_lsets, thr->locksetA, (Word)lock )); tl_assert(!HG_(elemWS)( univ_lsets, thr->locksetW, (Word)lock )); goto error; } /* test just above dominates */ tl_assert(lock->heldBy); was_heldW = lock->heldW; /* The lock is held. Is this thread one of the holders? If not, report a bug in the client. */ n = VG_(elemBag)( lock->heldBy, (Word)thr ); tl_assert(n >= 0); if (n == 0) { /* We are not a current holder of the lock. This is a bug in the guest, and (per POSIX pthread rules) the unlock attempt will fail. So just complain and do nothing else. */ Thread* realOwner = (Thread*)VG_(anyElementOfBag)( lock->heldBy ); tl_assert(HG_(is_sane_Thread)(realOwner)); tl_assert(realOwner != thr); tl_assert(!HG_(elemWS)( univ_lsets, thr->locksetA, (Word)lock )); tl_assert(!HG_(elemWS)( univ_lsets, thr->locksetW, (Word)lock )); HG_(record_error_UnlockForeign)( thr, realOwner, lock ); goto error; } /* Ok, we hold the lock 'n' times. */ tl_assert(n >= 1); lockN_release( lock, thr ); n--; tl_assert(n >= 0); if (n > 0) { tl_assert(lock->heldBy); tl_assert(n == VG_(elemBag)( lock->heldBy, (Word)thr )); /* We still hold the lock. So either it's a recursive lock or a rwlock which is currently r-held. */ tl_assert(lock->kind == LK_mbRec || (lock->kind == LK_rdwr && !lock->heldW)); tl_assert(HG_(elemWS)( univ_lsets, thr->locksetA, (Word)lock )); if (lock->heldW) tl_assert(HG_(elemWS)( univ_lsets, thr->locksetW, (Word)lock )); else tl_assert(!HG_(elemWS)( univ_lsets, thr->locksetW, (Word)lock )); } else { /* n is zero. This means we don't hold the lock any more. But if it's a rwlock held in r-mode, someone else could still hold it. Just do whatever sanity checks we can. */ if (lock->kind == LK_rdwr && lock->heldBy) { /* It's a rwlock. We no longer hold it but we used to; nevertheless it still appears to be held by someone else. The implication is that, prior to this release, it must have been shared by us and and whoever else is holding it; which in turn implies it must be r-held, since a lock can't be w-held by more than one thread. */ /* The lock is now R-held by somebody else: */ tl_assert(lock->heldW == False); } else { /* Normal case. It's either not a rwlock, or it's a rwlock that we used to hold in w-mode (which is pretty much the same thing as a non-rwlock.) Since this transaction is atomic (V does not allow multiple threads to run simultaneously), it must mean the lock is now not held by anybody. Hence assert for it. */ /* The lock is now not held by anybody: */ tl_assert(!lock->heldBy); tl_assert(lock->heldW == False); } //if (lock->heldBy) { // tl_assert(0 == VG_(elemBag)( lock->heldBy, (Word)thr )); //} /* update this thread's lockset accordingly. */ thr->locksetA = HG_(delFromWS)( univ_lsets, thr->locksetA, (Word)lock ); thr->locksetW = HG_(delFromWS)( univ_lsets, thr->locksetW, (Word)lock ); /* push our VC into the lock */ tl_assert(thr->hbthr); tl_assert(lock->hbso); /* If the lock was previously W-held, then we want to do a strong send, and if previously R-held, then a weak send. */ libhb_so_send( thr->hbthr, lock->hbso, was_heldW ); } /* fall through */ error: tl_assert(HG_(is_sane_LockN)(lock)); } /* ---------------------------------------------------------- */ /* -------- Event handlers proper (evh__* functions) -------- */ /* ---------------------------------------------------------- */ /* What is the Thread* for the currently running thread? This is absolutely performance critical. We receive notifications from the core for client code starts/stops, and cache the looked-up result in 'current_Thread'. Hence, for the vast majority of requests, finding the current thread reduces to a read of a global variable, provided get_current_Thread_in_C_C is inlined. Outside of client code, current_Thread is NULL, and presumably any uses of it will cause a segfault. Hence: - for uses definitely within client code, use get_current_Thread_in_C_C. - for all other uses, use get_current_Thread. */ static Thread *current_Thread = NULL, *current_Thread_prev = NULL; static void evh__start_client_code ( ThreadId tid, ULong nDisp ) { if (0) VG_(printf)("start %d %llu\n", (Int)tid, nDisp); tl_assert(current_Thread == NULL); current_Thread = map_threads_lookup( tid ); tl_assert(current_Thread != NULL); if (current_Thread != current_Thread_prev) { libhb_Thr_resumes( current_Thread->hbthr ); current_Thread_prev = current_Thread; } } static void evh__stop_client_code ( ThreadId tid, ULong nDisp ) { if (0) VG_(printf)(" stop %d %llu\n", (Int)tid, nDisp); tl_assert(current_Thread != NULL); current_Thread = NULL; libhb_maybe_GC(); } static inline Thread* get_current_Thread_in_C_C ( void ) { return current_Thread; } static inline Thread* get_current_Thread ( void ) { ThreadId coretid; Thread* thr; thr = get_current_Thread_in_C_C(); if (LIKELY(thr)) return thr; /* evidently not in client code. Do it the slow way. */ coretid = VG_(get_running_tid)(); /* FIXME: get rid of the following kludge. It exists because evh__new_mem is called during initialisation (as notification of initial memory layout) and VG_(get_running_tid)() returns VG_INVALID_THREADID at that point. */ if (coretid == VG_INVALID_THREADID) coretid = 1; /* KLUDGE */ thr = map_threads_lookup( coretid ); return thr; } static void evh__new_mem ( Addr a, SizeT len ) { if (SHOW_EVENTS >= 2) VG_(printf)("evh__new_mem(%p, %lu)\n", (void*)a, len ); shadow_mem_make_New( get_current_Thread(), a, len ); if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE)) all__sanity_check("evh__new_mem-post"); } static void evh__new_mem_stack ( Addr a, SizeT len ) { if (SHOW_EVENTS >= 2) VG_(printf)("evh__new_mem_stack(%p, %lu)\n", (void*)a, len ); shadow_mem_make_New( get_current_Thread(), -VG_STACK_REDZONE_SZB + a, len ); if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE)) all__sanity_check("evh__new_mem_stack-post"); } static void evh__new_mem_w_tid ( Addr a, SizeT len, ThreadId tid ) { if (SHOW_EVENTS >= 2) VG_(printf)("evh__new_mem_w_tid(%p, %lu)\n", (void*)a, len ); shadow_mem_make_New( get_current_Thread(), a, len ); if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE)) all__sanity_check("evh__new_mem_w_tid-post"); } static void evh__new_mem_w_perms ( Addr a, SizeT len, Bool rr, Bool ww, Bool xx, ULong di_handle ) { if (SHOW_EVENTS >= 1) VG_(printf)("evh__new_mem_w_perms(%p, %lu, %d,%d,%d)\n", (void*)a, len, (Int)rr, (Int)ww, (Int)xx ); if (rr || ww || xx) shadow_mem_make_New( get_current_Thread(), a, len ); if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE)) all__sanity_check("evh__new_mem_w_perms-post"); } static void evh__set_perms ( Addr a, SizeT len, Bool rr, Bool ww, Bool xx ) { if (SHOW_EVENTS >= 1) VG_(printf)("evh__set_perms(%p, %lu, %d,%d,%d)\n", (void*)a, len, (Int)rr, (Int)ww, (Int)xx ); /* Hmm. What should we do here, that actually makes any sense? Let's say: if neither readable nor writable, then declare it NoAccess, else leave it alone. */ if (!(rr || ww)) shadow_mem_make_NoAccess( get_current_Thread(), a, len ); if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE)) all__sanity_check("evh__set_perms-post"); } static void evh__die_mem ( Addr a, SizeT len ) { // urr, libhb ignores this. if (SHOW_EVENTS >= 2) VG_(printf)("evh__die_mem(%p, %lu)\n", (void*)a, len ); shadow_mem_make_NoAccess( get_current_Thread(), a, len ); if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE)) all__sanity_check("evh__die_mem-post"); } static void evh__untrack_mem ( Addr a, SizeT len ) { // whereas it doesn't ignore this if (SHOW_EVENTS >= 2) VG_(printf)("evh__untrack_mem(%p, %lu)\n", (void*)a, len ); shadow_mem_make_Untracked( get_current_Thread(), a, len ); if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE)) all__sanity_check("evh__untrack_mem-post"); } static void evh__copy_mem ( Addr src, Addr dst, SizeT len ) { if (SHOW_EVENTS >= 2) VG_(printf)("evh__copy_mem(%p, %p, %lu)\n", (void*)src, (void*)dst, len ); shadow_mem_scopy_range( get_current_Thread(), src, dst, len ); if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE)) all__sanity_check("evh__copy_mem-post"); } static void evh__pre_thread_ll_create ( ThreadId parent, ThreadId child ) { if (SHOW_EVENTS >= 1) VG_(printf)("evh__pre_thread_ll_create(p=%d, c=%d)\n", (Int)parent, (Int)child ); if (parent != VG_INVALID_THREADID) { Thread* thr_p; Thread* thr_c; Thr* hbthr_p; Thr* hbthr_c; tl_assert(HG_(is_sane_ThreadId)(parent)); tl_assert(HG_(is_sane_ThreadId)(child)); tl_assert(parent != child); thr_p = map_threads_maybe_lookup( parent ); thr_c = map_threads_maybe_lookup( child ); tl_assert(thr_p != NULL); tl_assert(thr_c == NULL); hbthr_p = thr_p->hbthr; tl_assert(hbthr_p != NULL); tl_assert( libhb_get_Thr_hgthread(hbthr_p) == thr_p ); hbthr_c = libhb_create ( hbthr_p ); /* Create a new thread record for the child. */ /* a Thread for the new thread ... */ thr_c = mk_Thread( hbthr_c ); tl_assert( libhb_get_Thr_hgthread(hbthr_c) == NULL ); libhb_set_Thr_hgthread(hbthr_c, thr_c); /* and bind it in the thread-map table */ map_threads[child] = thr_c; tl_assert(thr_c->coretid == VG_INVALID_THREADID); thr_c->coretid = child; /* Record where the parent is so we can later refer to this in error messages. On amd64-linux, this entails a nasty glibc-2.5 specific hack. The stack snapshot is taken immediately after the parent has returned from its sys_clone call. Unfortunately there is no unwind info for the insn following "syscall" - reading the glibc sources confirms this. So we ask for a snapshot to be taken as if RIP was 3 bytes earlier, in a place where there is unwind info. Sigh. */ { Word first_ip_delta = 0; # if defined(VGP_amd64_linux) first_ip_delta = -3; # endif thr_c->created_at = VG_(record_ExeContext)(parent, first_ip_delta); } } if (HG_(clo_sanity_flags) & SCE_THREADS) all__sanity_check("evh__pre_thread_create-post"); } static void evh__pre_thread_ll_exit ( ThreadId quit_tid ) { Int nHeld; Thread* thr_q; if (SHOW_EVENTS >= 1) VG_(printf)("evh__pre_thread_ll_exit(thr=%d)\n", (Int)quit_tid ); /* quit_tid has disappeared without joining to any other thread. Therefore there is no synchronisation event associated with its exit and so we have to pretty much treat it as if it was still alive but mysteriously making no progress. That is because, if we don't know when it really exited, then we can never say there is a point in time when we're sure the thread really has finished, and so we need to consider the possibility that it lingers indefinitely and continues to interact with other threads. */ /* However, it might have rendezvous'd with a thread that called pthread_join with this one as arg, prior to this point (that's how NPTL works). In which case there has already been a prior sync event. So in any case, just let the thread exit. On NPTL, all thread exits go through here. */ tl_assert(HG_(is_sane_ThreadId)(quit_tid)); thr_q = map_threads_maybe_lookup( quit_tid ); tl_assert(thr_q != NULL); /* Complain if this thread holds any locks. */ nHeld = HG_(cardinalityWS)( univ_lsets, thr_q->locksetA ); tl_assert(nHeld >= 0); if (nHeld > 0) { HChar buf[80]; VG_(sprintf)(buf, "Exiting thread still holds %d lock%s", nHeld, nHeld > 1 ? "s" : ""); HG_(record_error_Misc)( thr_q, buf ); } /* Not much to do here: - tell libhb the thread is gone - clear the map_threads entry, in order that the Valgrind core can re-use it. */ /* Cleanup actions (next 5 lines) copied in evh__atfork_child; keep in sync. */ tl_assert(thr_q->hbthr); libhb_async_exit(thr_q->hbthr); tl_assert(thr_q->coretid == quit_tid); thr_q->coretid = VG_INVALID_THREADID; map_threads_delete( quit_tid ); if (HG_(clo_sanity_flags) & SCE_THREADS) all__sanity_check("evh__pre_thread_ll_exit-post"); } /* This is called immediately after fork, for the child only. 'tid' is the only surviving thread (as per POSIX rules on fork() in threaded programs), so we have to clean up map_threads to remove entries for any other threads. */ static void evh__atfork_child ( ThreadId tid ) { UInt i; Thread* thr; /* Slot 0 should never be used. */ thr = map_threads_maybe_lookup( 0/*INVALID*/ ); tl_assert(!thr); /* Clean up all other slots except 'tid'. */ for (i = 1; i < VG_N_THREADS; i++) { if (i == tid) continue; thr = map_threads_maybe_lookup(i); if (!thr) continue; /* Cleanup actions (next 5 lines) copied from end of evh__pre_thread_ll_exit; keep in sync. */ tl_assert(thr->hbthr); libhb_async_exit(thr->hbthr); tl_assert(thr->coretid == i); thr->coretid = VG_INVALID_THREADID; map_threads_delete(i); } } static void evh__HG_PTHREAD_JOIN_POST ( ThreadId stay_tid, Thread* quit_thr ) { Thread* thr_s; Thread* thr_q; Thr* hbthr_s; Thr* hbthr_q; SO* so; if (SHOW_EVENTS >= 1) VG_(printf)("evh__post_thread_join(stayer=%d, quitter=%p)\n", (Int)stay_tid, quit_thr ); tl_assert(HG_(is_sane_ThreadId)(stay_tid)); thr_s = map_threads_maybe_lookup( stay_tid ); thr_q = quit_thr; tl_assert(thr_s != NULL); tl_assert(thr_q != NULL); tl_assert(thr_s != thr_q); hbthr_s = thr_s->hbthr; hbthr_q = thr_q->hbthr; tl_assert(hbthr_s != hbthr_q); tl_assert( libhb_get_Thr_hgthread(hbthr_s) == thr_s ); tl_assert( libhb_get_Thr_hgthread(hbthr_q) == thr_q ); /* Allocate a temporary synchronisation object and use it to send an imaginary message from the quitter to the stayer, the purpose being to generate a dependence from the quitter to the stayer. */ so = libhb_so_alloc(); tl_assert(so); /* Send last arg of _so_send as False, since the sending thread doesn't actually exist any more, so we don't want _so_send to try taking stack snapshots of it. */ libhb_so_send(hbthr_q, so, True/*strong_send*/); libhb_so_recv(hbthr_s, so, True/*strong_recv*/); libhb_so_dealloc(so); /* evh__pre_thread_ll_exit issues an error message if the exiting thread holds any locks. No need to check here. */ /* This holds because, at least when using NPTL as the thread library, we should be notified the low level thread exit before we hear of any join event on it. The low level exit notification feeds through into evh__pre_thread_ll_exit, which should clear the map_threads entry for it. Hence we expect there to be no map_threads entry at this point. */ tl_assert( map_threads_maybe_reverse_lookup_SLOW(thr_q) == VG_INVALID_THREADID); if (HG_(clo_sanity_flags) & SCE_THREADS) all__sanity_check("evh__post_thread_join-post"); } static void evh__pre_mem_read ( CorePart part, ThreadId tid, Char* s, Addr a, SizeT size) { if (SHOW_EVENTS >= 2 || (SHOW_EVENTS >= 1 && size != 1)) VG_(printf)("evh__pre_mem_read(ctid=%d, \"%s\", %p, %lu)\n", (Int)tid, s, (void*)a, size ); shadow_mem_cread_range( map_threads_lookup(tid), a, size); if (size >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE)) all__sanity_check("evh__pre_mem_read-post"); } static void evh__pre_mem_read_asciiz ( CorePart part, ThreadId tid, Char* s, Addr a ) { Int len; if (SHOW_EVENTS >= 1) VG_(printf)("evh__pre_mem_asciiz(ctid=%d, \"%s\", %p)\n", (Int)tid, s, (void*)a ); // Don't segfault if the string starts in an obviously stupid // place. Actually we should check the whole string, not just // the start address, but that's too much trouble. At least // checking the first byte is better than nothing. See #255009. if (!VG_(am_is_valid_for_client) (a, 1, VKI_PROT_READ)) return; len = VG_(strlen)( (Char*) a ); shadow_mem_cread_range( map_threads_lookup(tid), a, len+1 ); if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE)) all__sanity_check("evh__pre_mem_read_asciiz-post"); } static void evh__pre_mem_write ( CorePart part, ThreadId tid, Char* s, Addr a, SizeT size ) { if (SHOW_EVENTS >= 1) VG_(printf)("evh__pre_mem_write(ctid=%d, \"%s\", %p, %lu)\n", (Int)tid, s, (void*)a, size ); shadow_mem_cwrite_range( map_threads_lookup(tid), a, size); if (size >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE)) all__sanity_check("evh__pre_mem_write-post"); } static void evh__new_mem_heap ( Addr a, SizeT len, Bool is_inited ) { if (SHOW_EVENTS >= 1) VG_(printf)("evh__new_mem_heap(%p, %lu, inited=%d)\n", (void*)a, len, (Int)is_inited ); // FIXME: this is kinda stupid if (is_inited) { shadow_mem_make_New(get_current_Thread(), a, len); } else { shadow_mem_make_New(get_current_Thread(), a, len); } if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE)) all__sanity_check("evh__pre_mem_read-post"); } static void evh__die_mem_heap ( Addr a, SizeT len ) { if (SHOW_EVENTS >= 1) VG_(printf)("evh__die_mem_heap(%p, %lu)\n", (void*)a, len ); shadow_mem_make_NoAccess( get_current_Thread(), a, len ); if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE)) all__sanity_check("evh__pre_mem_read-post"); } /* --- Event handlers called from generated code --- */ static VG_REGPARM(1) void evh__mem_help_cread_1(Addr a) { Thread* thr = get_current_Thread_in_C_C(); Thr* hbthr = thr->hbthr; LIBHB_CREAD_1(hbthr, a); } static VG_REGPARM(1) void evh__mem_help_cread_2(Addr a) { Thread* thr = get_current_Thread_in_C_C(); Thr* hbthr = thr->hbthr; LIBHB_CREAD_2(hbthr, a); } static VG_REGPARM(1) void evh__mem_help_cread_4(Addr a) { Thread* thr = get_current_Thread_in_C_C(); Thr* hbthr = thr->hbthr; LIBHB_CREAD_4(hbthr, a); } static VG_REGPARM(1) void evh__mem_help_cread_8(Addr a) { Thread* thr = get_current_Thread_in_C_C(); Thr* hbthr = thr->hbthr; LIBHB_CREAD_8(hbthr, a); } static VG_REGPARM(2) void evh__mem_help_cread_N(Addr a, SizeT size) { Thread* thr = get_current_Thread_in_C_C(); Thr* hbthr = thr->hbthr; LIBHB_CREAD_N(hbthr, a, size); } static VG_REGPARM(1) void evh__mem_help_cwrite_1(Addr a) { Thread* thr = get_current_Thread_in_C_C(); Thr* hbthr = thr->hbthr; LIBHB_CWRITE_1(hbthr, a); } static VG_REGPARM(1) void evh__mem_help_cwrite_2(Addr a) { Thread* thr = get_current_Thread_in_C_C(); Thr* hbthr = thr->hbthr; LIBHB_CWRITE_2(hbthr, a); } static VG_REGPARM(1) void evh__mem_help_cwrite_4(Addr a) { Thread* thr = get_current_Thread_in_C_C(); Thr* hbthr = thr->hbthr; LIBHB_CWRITE_4(hbthr, a); } static VG_REGPARM(1) void evh__mem_help_cwrite_8(Addr a) { Thread* thr = get_current_Thread_in_C_C(); Thr* hbthr = thr->hbthr; LIBHB_CWRITE_8(hbthr, a); } static VG_REGPARM(2) void evh__mem_help_cwrite_N(Addr a, SizeT size) { Thread* thr = get_current_Thread_in_C_C(); Thr* hbthr = thr->hbthr; LIBHB_CWRITE_N(hbthr, a, size); } /* ------------------------------------------------------- */ /* -------------- events to do with mutexes -------------- */ /* ------------------------------------------------------- */ /* EXPOSITION only: by intercepting lock init events we can show the user where the lock was initialised, rather than only being able to show where it was first locked. Intercepting lock initialisations is not necessary for the basic operation of the race checker. */ static void evh__HG_PTHREAD_MUTEX_INIT_POST( ThreadId tid, void* mutex, Word mbRec ) { if (SHOW_EVENTS >= 1) VG_(printf)("evh__hg_PTHREAD_MUTEX_INIT_POST(ctid=%d, mbRec=%ld, %p)\n", (Int)tid, mbRec, (void*)mutex ); tl_assert(mbRec == 0 || mbRec == 1); map_locks_lookup_or_create( mbRec ? LK_mbRec : LK_nonRec, (Addr)mutex, tid ); if (HG_(clo_sanity_flags) & SCE_LOCKS) all__sanity_check("evh__hg_PTHREAD_MUTEX_INIT_POST"); } static void evh__HG_PTHREAD_MUTEX_DESTROY_PRE( ThreadId tid, void* mutex ) { Thread* thr; Lock* lk; if (SHOW_EVENTS >= 1) VG_(printf)("evh__hg_PTHREAD_MUTEX_DESTROY_PRE(ctid=%d, %p)\n", (Int)tid, (void*)mutex ); thr = map_threads_maybe_lookup( tid ); /* cannot fail - Thread* must already exist */ tl_assert( HG_(is_sane_Thread)(thr) ); lk = map_locks_maybe_lookup( (Addr)mutex ); if (lk == NULL || (lk->kind != LK_nonRec && lk->kind != LK_mbRec)) { HG_(record_error_Misc)( thr, "pthread_mutex_destroy with invalid argument" ); } if (lk) { tl_assert( HG_(is_sane_LockN)(lk) ); tl_assert( lk->guestaddr == (Addr)mutex ); if (lk->heldBy) { /* Basically act like we unlocked the lock */ HG_(record_error_Misc)( thr, "pthread_mutex_destroy of a locked mutex" ); /* remove lock from locksets of all owning threads */ remove_Lock_from_locksets_of_all_owning_Threads( lk ); VG_(deleteBag)( lk->heldBy ); lk->heldBy = NULL; lk->heldW = False; lk->acquired_at = NULL; } tl_assert( !lk->heldBy ); tl_assert( HG_(is_sane_LockN)(lk) ); if (HG_(clo_track_lockorders)) laog__handle_one_lock_deletion(lk); map_locks_delete( lk->guestaddr ); del_LockN( lk ); } if (HG_(clo_sanity_flags) & SCE_LOCKS) all__sanity_check("evh__hg_PTHREAD_MUTEX_DESTROY_PRE"); } static void evh__HG_PTHREAD_MUTEX_LOCK_PRE ( ThreadId tid, void* mutex, Word isTryLock ) { /* Just check the mutex is sane; nothing else to do. */ // 'mutex' may be invalid - not checked by wrapper Thread* thr; Lock* lk; if (SHOW_EVENTS >= 1) VG_(printf)("evh__hg_PTHREAD_MUTEX_LOCK_PRE(ctid=%d, mutex=%p)\n", (Int)tid, (void*)mutex ); tl_assert(isTryLock == 0 || isTryLock == 1); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ lk = map_locks_maybe_lookup( (Addr)mutex ); if (lk && (lk->kind == LK_rdwr)) { HG_(record_error_Misc)( thr, "pthread_mutex_lock with a " "pthread_rwlock_t* argument " ); } if ( lk && isTryLock == 0 && (lk->kind == LK_nonRec || lk->kind == LK_rdwr) && lk->heldBy && lk->heldW && VG_(elemBag)( lk->heldBy, (Word)thr ) > 0 ) { /* uh, it's a non-recursive lock and we already w-hold it, and this is a real lock operation (not a speculative "tryLock" kind of thing). Duh. Deadlock coming up; but at least produce an error message. */ HChar* errstr = "Attempt to re-lock a " "non-recursive lock I already hold"; HChar* auxstr = "Lock was previously acquired"; if (lk->acquired_at) { HG_(record_error_Misc_w_aux)( thr, errstr, auxstr, lk->acquired_at ); } else { HG_(record_error_Misc)( thr, errstr ); } } } static void evh__HG_PTHREAD_MUTEX_LOCK_POST ( ThreadId tid, void* mutex ) { // only called if the real library call succeeded - so mutex is sane Thread* thr; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_PTHREAD_MUTEX_LOCK_POST(ctid=%d, mutex=%p)\n", (Int)tid, (void*)mutex ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ evhH__post_thread_w_acquires_lock( thr, LK_mbRec, /* if not known, create new lock with this LockKind */ (Addr)mutex ); } static void evh__HG_PTHREAD_MUTEX_UNLOCK_PRE ( ThreadId tid, void* mutex ) { // 'mutex' may be invalid - not checked by wrapper Thread* thr; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_PTHREAD_MUTEX_UNLOCK_PRE(ctid=%d, mutex=%p)\n", (Int)tid, (void*)mutex ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ evhH__pre_thread_releases_lock( thr, (Addr)mutex, False/*!isRDWR*/ ); } static void evh__HG_PTHREAD_MUTEX_UNLOCK_POST ( ThreadId tid, void* mutex ) { // only called if the real library call succeeded - so mutex is sane Thread* thr; if (SHOW_EVENTS >= 1) VG_(printf)("evh__hg_PTHREAD_MUTEX_UNLOCK_POST(ctid=%d, mutex=%p)\n", (Int)tid, (void*)mutex ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ // anything we should do here? } /* ------------------------------------------------------- */ /* -------------- events to do with spinlocks ------------ */ /* ------------------------------------------------------- */ /* All a bit of a kludge. Pretend we're really dealing with ordinary pthread_mutex_t's instead, for the most part. */ static void evh__HG_PTHREAD_SPIN_INIT_OR_UNLOCK_PRE( ThreadId tid, void* slock ) { Thread* thr; Lock* lk; /* In glibc's kludgey world, we're either initialising or unlocking it. Since this is the pre-routine, if it is locked, unlock it and take a dependence edge. Otherwise, do nothing. */ if (SHOW_EVENTS >= 1) VG_(printf)("evh__hg_PTHREAD_SPIN_INIT_OR_UNLOCK_PRE" "(ctid=%d, slock=%p)\n", (Int)tid, (void*)slock ); thr = map_threads_maybe_lookup( tid ); /* cannot fail - Thread* must already exist */; tl_assert( HG_(is_sane_Thread)(thr) ); lk = map_locks_maybe_lookup( (Addr)slock ); if (lk && lk->heldBy) { /* it's held. So do the normal pre-unlock actions, as copied from evh__HG_PTHREAD_MUTEX_UNLOCK_PRE. This stupidly duplicates the map_locks_maybe_lookup. */ evhH__pre_thread_releases_lock( thr, (Addr)slock, False/*!isRDWR*/ ); } } static void evh__HG_PTHREAD_SPIN_INIT_OR_UNLOCK_POST( ThreadId tid, void* slock ) { Lock* lk; /* More kludgery. If the lock has never been seen before, do actions as per evh__HG_PTHREAD_MUTEX_INIT_POST. Else do nothing. */ if (SHOW_EVENTS >= 1) VG_(printf)("evh__hg_PTHREAD_SPIN_INIT_OR_UNLOCK_POST" "(ctid=%d, slock=%p)\n", (Int)tid, (void*)slock ); lk = map_locks_maybe_lookup( (Addr)slock ); if (!lk) { map_locks_lookup_or_create( LK_nonRec, (Addr)slock, tid ); } } static void evh__HG_PTHREAD_SPIN_LOCK_PRE( ThreadId tid, void* slock, Word isTryLock ) { evh__HG_PTHREAD_MUTEX_LOCK_PRE( tid, slock, isTryLock ); } static void evh__HG_PTHREAD_SPIN_LOCK_POST( ThreadId tid, void* slock ) { evh__HG_PTHREAD_MUTEX_LOCK_POST( tid, slock ); } static void evh__HG_PTHREAD_SPIN_DESTROY_PRE( ThreadId tid, void* slock ) { evh__HG_PTHREAD_MUTEX_DESTROY_PRE( tid, slock ); } /* ----------------------------------------------------- */ /* --------------- events to do with CVs --------------- */ /* ----------------------------------------------------- */ /* A mapping from CV to (the SO associated with it, plus some auxiliary data for error checking). When the CV is signalled/broadcasted upon, we do a 'send' into the SO, and when a wait on it completes, we do a 'recv' from the SO. This is believed to give the correct happens-before events arising from CV signallings/broadcasts. */ /* .so is the SO for this CV. .mx_ga is the associated mutex, when .nWaiters > 0 POSIX says effectively that the first pthread_cond_{timed}wait call causes a dynamic binding between the CV and the mutex, and that lasts until such time as the waiter count falls to zero. Hence need to keep track of the number of waiters in order to do consistency tracking. */ typedef struct { SO* so; /* libhb-allocated SO */ void* mx_ga; /* addr of associated mutex, if any */ UWord nWaiters; /* # threads waiting on the CV */ } CVInfo; /* pthread_cond_t* -> CVInfo* */ static WordFM* map_cond_to_CVInfo = NULL; static void map_cond_to_CVInfo_INIT ( void ) { if (UNLIKELY(map_cond_to_CVInfo == NULL)) { map_cond_to_CVInfo = VG_(newFM)( HG_(zalloc), "hg.mctCI.1", HG_(free), NULL ); tl_assert(map_cond_to_CVInfo != NULL); } } static CVInfo* map_cond_to_CVInfo_lookup_or_alloc ( void* cond ) { UWord key, val; map_cond_to_CVInfo_INIT(); if (VG_(lookupFM)( map_cond_to_CVInfo, &key, &val, (UWord)cond )) { tl_assert(key == (UWord)cond); return (CVInfo*)val; } else { SO* so = libhb_so_alloc(); CVInfo* cvi = HG_(zalloc)("hg.mctCloa.1", sizeof(CVInfo)); cvi->so = so; cvi->mx_ga = 0; VG_(addToFM)( map_cond_to_CVInfo, (UWord)cond, (UWord)cvi ); return cvi; } } static void map_cond_to_CVInfo_delete ( void* cond ) { UWord keyW, valW; map_cond_to_CVInfo_INIT(); if (VG_(delFromFM)( map_cond_to_CVInfo, &keyW, &valW, (UWord)cond )) { CVInfo* cvi = (CVInfo*)valW; tl_assert(keyW == (UWord)cond); tl_assert(cvi); tl_assert(cvi->so); libhb_so_dealloc(cvi->so); cvi->mx_ga = 0; HG_(free)(cvi); } } static void evh__HG_PTHREAD_COND_SIGNAL_PRE ( ThreadId tid, void* cond ) { /* 'tid' has signalled on 'cond'. As per the comment above, bind cond to a SO if it is not already so bound, and 'send' on the SO. This is later used by other thread(s) which successfully exit from a pthread_cond_wait on the same cv; then they 'recv' from the SO, thereby acquiring a dependency on this signalling event. */ Thread* thr; CVInfo* cvi; //Lock* lk; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_PTHREAD_COND_SIGNAL_PRE(ctid=%d, cond=%p)\n", (Int)tid, (void*)cond ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ cvi = map_cond_to_CVInfo_lookup_or_alloc( cond ); tl_assert(cvi); tl_assert(cvi->so); // error-if: mutex is bogus // error-if: mutex is not locked // Hmm. POSIX doesn't actually say that it's an error to call // pthread_cond_signal with the associated mutex being unlocked. // Although it does say that it should be "if consistent scheduling // is desired." // // For the moment, disable these checks. //lk = map_locks_maybe_lookup(cvi->mx_ga); //if (lk == NULL || cvi->mx_ga == 0) { // HG_(record_error_Misc)( thr, // "pthread_cond_{signal,broadcast}: " // "no or invalid mutex associated with cond"); //} ///* note: lk could be NULL. Be careful. */ //if (lk) { // if (lk->kind == LK_rdwr) { // HG_(record_error_Misc)(thr, // "pthread_cond_{signal,broadcast}: associated lock is a rwlock"); // } // if (lk->heldBy == NULL) { // HG_(record_error_Misc)(thr, // "pthread_cond_{signal,broadcast}: " // "associated lock is not held by any thread"); // } // if (lk->heldBy != NULL && 0 == VG_(elemBag)(lk->heldBy, (Word)thr)) { // HG_(record_error_Misc)(thr, // "pthread_cond_{signal,broadcast}: " // "associated lock is not held by calling thread"); // } //} libhb_so_send( thr->hbthr, cvi->so, True/*strong_send*/ ); } /* returns True if it reckons 'mutex' is valid and held by this thread, else False */ static Bool evh__HG_PTHREAD_COND_WAIT_PRE ( ThreadId tid, void* cond, void* mutex ) { Thread* thr; Lock* lk; Bool lk_valid = True; CVInfo* cvi; if (SHOW_EVENTS >= 1) VG_(printf)("evh__hg_PTHREAD_COND_WAIT_PRE" "(ctid=%d, cond=%p, mutex=%p)\n", (Int)tid, (void*)cond, (void*)mutex ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ lk = map_locks_maybe_lookup( (Addr)mutex ); /* Check for stupid mutex arguments. There are various ways to be a bozo. Only complain once, though, even if more than one thing is wrong. */ if (lk == NULL) { lk_valid = False; HG_(record_error_Misc)( thr, "pthread_cond_{timed}wait called with invalid mutex" ); } else { tl_assert( HG_(is_sane_LockN)(lk) ); if (lk->kind == LK_rdwr) { lk_valid = False; HG_(record_error_Misc)( thr, "pthread_cond_{timed}wait called with mutex " "of type pthread_rwlock_t*" ); } else if (lk->heldBy == NULL) { lk_valid = False; HG_(record_error_Misc)( thr, "pthread_cond_{timed}wait called with un-held mutex"); } else if (lk->heldBy != NULL && VG_(elemBag)( lk->heldBy, (Word)thr ) == 0) { lk_valid = False; HG_(record_error_Misc)( thr, "pthread_cond_{timed}wait called with mutex " "held by a different thread" ); } } // error-if: cond is also associated with a different mutex cvi = map_cond_to_CVInfo_lookup_or_alloc(cond); tl_assert(cvi); tl_assert(cvi->so); if (cvi->nWaiters == 0) { /* form initial (CV,MX) binding */ cvi->mx_ga = mutex; } else /* check existing (CV,MX) binding */ if (cvi->mx_ga != mutex) { HG_(record_error_Misc)( thr, "pthread_cond_{timed}wait: cond is associated " "with a different mutex"); } cvi->nWaiters++; return lk_valid; } static void evh__HG_PTHREAD_COND_WAIT_POST ( ThreadId tid, void* cond, void* mutex ) { /* A pthread_cond_wait(cond, mutex) completed successfully. Find the SO for this cond, and 'recv' from it so as to acquire a dependency edge back to the signaller/broadcaster. */ Thread* thr; CVInfo* cvi; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_PTHREAD_COND_WAIT_POST" "(ctid=%d, cond=%p, mutex=%p)\n", (Int)tid, (void*)cond, (void*)mutex ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ // error-if: cond is also associated with a different mutex cvi = map_cond_to_CVInfo_lookup_or_alloc( cond ); tl_assert(cvi); tl_assert(cvi->so); tl_assert(cvi->nWaiters > 0); if (!libhb_so_everSent(cvi->so)) { /* Hmm. How can a wait on 'cond' succeed if nobody signalled it? If this happened it would surely be a bug in the threads library. Or one of those fabled "spurious wakeups". */ HG_(record_error_Misc)( thr, "Bug in libpthread: pthread_cond_wait " "succeeded on" " without prior pthread_cond_post"); } /* anyway, acquire a dependency on it. */ libhb_so_recv( thr->hbthr, cvi->so, True/*strong_recv*/ ); cvi->nWaiters--; } static void evh__HG_PTHREAD_COND_DESTROY_PRE ( ThreadId tid, void* cond ) { /* Deal with destroy events. The only purpose is to free storage associated with the CV, so as to avoid any possible resource leaks. */ if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_PTHREAD_COND_DESTROY_PRE" "(ctid=%d, cond=%p)\n", (Int)tid, (void*)cond ); map_cond_to_CVInfo_delete( cond ); } /* ------------------------------------------------------- */ /* -------------- events to do with rwlocks -------------- */ /* ------------------------------------------------------- */ /* EXPOSITION only */ static void evh__HG_PTHREAD_RWLOCK_INIT_POST( ThreadId tid, void* rwl ) { if (SHOW_EVENTS >= 1) VG_(printf)("evh__hg_PTHREAD_RWLOCK_INIT_POST(ctid=%d, %p)\n", (Int)tid, (void*)rwl ); map_locks_lookup_or_create( LK_rdwr, (Addr)rwl, tid ); if (HG_(clo_sanity_flags) & SCE_LOCKS) all__sanity_check("evh__hg_PTHREAD_RWLOCK_INIT_POST"); } static void evh__HG_PTHREAD_RWLOCK_DESTROY_PRE( ThreadId tid, void* rwl ) { Thread* thr; Lock* lk; if (SHOW_EVENTS >= 1) VG_(printf)("evh__hg_PTHREAD_RWLOCK_DESTROY_PRE(ctid=%d, %p)\n", (Int)tid, (void*)rwl ); thr = map_threads_maybe_lookup( tid ); /* cannot fail - Thread* must already exist */ tl_assert( HG_(is_sane_Thread)(thr) ); lk = map_locks_maybe_lookup( (Addr)rwl ); if (lk == NULL || lk->kind != LK_rdwr) { HG_(record_error_Misc)( thr, "pthread_rwlock_destroy with invalid argument" ); } if (lk) { tl_assert( HG_(is_sane_LockN)(lk) ); tl_assert( lk->guestaddr == (Addr)rwl ); if (lk->heldBy) { /* Basically act like we unlocked the lock */ HG_(record_error_Misc)( thr, "pthread_rwlock_destroy of a locked mutex" ); /* remove lock from locksets of all owning threads */ remove_Lock_from_locksets_of_all_owning_Threads( lk ); VG_(deleteBag)( lk->heldBy ); lk->heldBy = NULL; lk->heldW = False; lk->acquired_at = NULL; } tl_assert( !lk->heldBy ); tl_assert( HG_(is_sane_LockN)(lk) ); if (HG_(clo_track_lockorders)) laog__handle_one_lock_deletion(lk); map_locks_delete( lk->guestaddr ); del_LockN( lk ); } if (HG_(clo_sanity_flags) & SCE_LOCKS) all__sanity_check("evh__hg_PTHREAD_RWLOCK_DESTROY_PRE"); } static void evh__HG_PTHREAD_RWLOCK_LOCK_PRE ( ThreadId tid, void* rwl, Word isW, Word isTryLock ) { /* Just check the rwl is sane; nothing else to do. */ // 'rwl' may be invalid - not checked by wrapper Thread* thr; Lock* lk; if (SHOW_EVENTS >= 1) VG_(printf)("evh__hg_PTHREAD_RWLOCK_LOCK_PRE(ctid=%d, isW=%d, %p)\n", (Int)tid, (Int)isW, (void*)rwl ); tl_assert(isW == 0 || isW == 1); /* assured us by wrapper */ tl_assert(isTryLock == 0 || isTryLock == 1); /* assured us by wrapper */ thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ lk = map_locks_maybe_lookup( (Addr)rwl ); if ( lk && (lk->kind == LK_nonRec || lk->kind == LK_mbRec) ) { /* Wrong kind of lock. Duh. */ HG_(record_error_Misc)( thr, "pthread_rwlock_{rd,rw}lock with a " "pthread_mutex_t* argument " ); } } static void evh__HG_PTHREAD_RWLOCK_LOCK_POST ( ThreadId tid, void* rwl, Word isW ) { // only called if the real library call succeeded - so mutex is sane Thread* thr; if (SHOW_EVENTS >= 1) VG_(printf)("evh__hg_PTHREAD_RWLOCK_LOCK_POST(ctid=%d, isW=%d, %p)\n", (Int)tid, (Int)isW, (void*)rwl ); tl_assert(isW == 0 || isW == 1); /* assured us by wrapper */ thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ (isW ? evhH__post_thread_w_acquires_lock : evhH__post_thread_r_acquires_lock)( thr, LK_rdwr, /* if not known, create new lock with this LockKind */ (Addr)rwl ); } static void evh__HG_PTHREAD_RWLOCK_UNLOCK_PRE ( ThreadId tid, void* rwl ) { // 'rwl' may be invalid - not checked by wrapper Thread* thr; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_PTHREAD_RWLOCK_UNLOCK_PRE(ctid=%d, rwl=%p)\n", (Int)tid, (void*)rwl ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ evhH__pre_thread_releases_lock( thr, (Addr)rwl, True/*isRDWR*/ ); } static void evh__HG_PTHREAD_RWLOCK_UNLOCK_POST ( ThreadId tid, void* rwl ) { // only called if the real library call succeeded - so mutex is sane Thread* thr; if (SHOW_EVENTS >= 1) VG_(printf)("evh__hg_PTHREAD_RWLOCK_UNLOCK_POST(ctid=%d, rwl=%p)\n", (Int)tid, (void*)rwl ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ // anything we should do here? } /* ---------------------------------------------------------- */ /* -------------- events to do with semaphores -------------- */ /* ---------------------------------------------------------- */ /* This is similar to but not identical to the handling for condition variables. */ /* For each semaphore, we maintain a stack of SOs. When a 'post' operation is done on a semaphore (unlocking, essentially), a new SO is created for the posting thread, the posting thread does a strong send to it (which merely installs the posting thread's VC in the SO), and the SO is pushed on the semaphore's stack. Later, when a (probably different) thread completes 'wait' on the semaphore, we pop a SO off the semaphore's stack (which should be nonempty), and do a strong recv from it. This mechanism creates dependencies between posters and waiters of the semaphore. It may not be necessary to use a stack - perhaps a bag of SOs would do. But we do need to keep track of how many unused-up posts have happened for the semaphore. Imagine T1 and T2 both post once on a semaphore S, and T3 waits twice on S. T3 cannot complete its waits without both T1 and T2 posting. The above mechanism will ensure that T3 acquires dependencies on both T1 and T2. When a semaphore is initialised with value N, we do as if we'd posted N times on the semaphore: basically create N SOs and do a strong send to all of then. This allows up to N waits on the semaphore to acquire a dependency on the initialisation point, which AFAICS is the correct behaviour. We don't emit an error for DESTROY_PRE on a semaphore we don't know about. We should. */ /* sem_t* -> XArray* SO* */ static WordFM* map_sem_to_SO_stack = NULL; static void map_sem_to_SO_stack_INIT ( void ) { if (map_sem_to_SO_stack == NULL) { map_sem_to_SO_stack = VG_(newFM)( HG_(zalloc), "hg.mstSs.1", HG_(free), NULL ); tl_assert(map_sem_to_SO_stack != NULL); } } static void push_SO_for_sem ( void* sem, SO* so ) { UWord keyW; XArray* xa; tl_assert(so); map_sem_to_SO_stack_INIT(); if (VG_(lookupFM)( map_sem_to_SO_stack, &keyW, (UWord*)&xa, (UWord)sem )) { tl_assert(keyW == (UWord)sem); tl_assert(xa); VG_(addToXA)( xa, &so ); } else { xa = VG_(newXA)( HG_(zalloc), "hg.pSfs.1", HG_(free), sizeof(SO*) ); VG_(addToXA)( xa, &so ); VG_(addToFM)( map_sem_to_SO_stack, (Word)sem, (Word)xa ); } } static SO* mb_pop_SO_for_sem ( void* sem ) { UWord keyW; XArray* xa; SO* so; map_sem_to_SO_stack_INIT(); if (VG_(lookupFM)( map_sem_to_SO_stack, &keyW, (UWord*)&xa, (UWord)sem )) { /* xa is the stack for this semaphore. */ Word sz; tl_assert(keyW == (UWord)sem); sz = VG_(sizeXA)( xa ); tl_assert(sz >= 0); if (sz == 0) return NULL; /* odd, the stack is empty */ so = *(SO**)VG_(indexXA)( xa, sz-1 ); tl_assert(so); VG_(dropTailXA)( xa, 1 ); return so; } else { /* hmm, that's odd. No stack for this semaphore. */ return NULL; } } static void evh__HG_POSIX_SEM_DESTROY_PRE ( ThreadId tid, void* sem ) { UWord keyW, valW; SO* so; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_POSIX_SEM_DESTROY_PRE(ctid=%d, sem=%p)\n", (Int)tid, (void*)sem ); map_sem_to_SO_stack_INIT(); /* Empty out the semaphore's SO stack. This way of doing it is stupid, but at least it's easy. */ while (1) { so = mb_pop_SO_for_sem( sem ); if (!so) break; libhb_so_dealloc(so); } if (VG_(delFromFM)( map_sem_to_SO_stack, &keyW, &valW, (UWord)sem )) { XArray* xa = (XArray*)valW; tl_assert(keyW == (UWord)sem); tl_assert(xa); tl_assert(VG_(sizeXA)(xa) == 0); /* preceding loop just emptied it */ VG_(deleteXA)(xa); } } static void evh__HG_POSIX_SEM_INIT_POST ( ThreadId tid, void* sem, UWord value ) { SO* so; Thread* thr; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_POSIX_SEM_INIT_POST(ctid=%d, sem=%p, value=%lu)\n", (Int)tid, (void*)sem, value ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ /* Empty out the semaphore's SO stack. This way of doing it is stupid, but at least it's easy. */ while (1) { so = mb_pop_SO_for_sem( sem ); if (!so) break; libhb_so_dealloc(so); } /* If we don't do this check, the following while loop runs us out of memory for stupid initial values of 'value'. */ if (value > 10000) { HG_(record_error_Misc)( thr, "sem_init: initial value exceeds 10000; using 10000" ); value = 10000; } /* Now create 'valid' new SOs for the thread, do a strong send to each of them, and push them all on the stack. */ for (; value > 0; value--) { Thr* hbthr = thr->hbthr; tl_assert(hbthr); so = libhb_so_alloc(); libhb_so_send( hbthr, so, True/*strong send*/ ); push_SO_for_sem( sem, so ); } } static void evh__HG_POSIX_SEM_POST_PRE ( ThreadId tid, void* sem ) { /* 'tid' has posted on 'sem'. Create a new SO, do a strong send to it (iow, write our VC into it, then tick ours), and push the SO on on a stack of SOs associated with 'sem'. This is later used by other thread(s) which successfully exit from a sem_wait on the same sem; by doing a strong recv from SOs popped of the stack, they acquire dependencies on the posting thread segment(s). */ Thread* thr; SO* so; Thr* hbthr; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_POSIX_SEM_POST_PRE(ctid=%d, sem=%p)\n", (Int)tid, (void*)sem ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ // error-if: sem is bogus hbthr = thr->hbthr; tl_assert(hbthr); so = libhb_so_alloc(); libhb_so_send( hbthr, so, True/*strong send*/ ); push_SO_for_sem( sem, so ); } static void evh__HG_POSIX_SEM_WAIT_POST ( ThreadId tid, void* sem ) { /* A sem_wait(sem) completed successfully. Pop the posting-SO for the 'sem' from this semaphore's SO-stack, and do a strong recv from it. This creates a dependency back to one of the post-ers for the semaphore. */ Thread* thr; SO* so; Thr* hbthr; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_POSIX_SEM_WAIT_POST(ctid=%d, sem=%p)\n", (Int)tid, (void*)sem ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ // error-if: sem is bogus so = mb_pop_SO_for_sem( sem ); if (so) { hbthr = thr->hbthr; tl_assert(hbthr); libhb_so_recv( hbthr, so, True/*strong recv*/ ); libhb_so_dealloc(so); } else { /* Hmm. How can a wait on 'sem' succeed if nobody posted to it? If this happened it would surely be a bug in the threads library. */ HG_(record_error_Misc)( thr, "Bug in libpthread: sem_wait succeeded on" " semaphore without prior sem_post"); } } /* -------------------------------------------------------- */ /* -------------- events to do with barriers -------------- */ /* -------------------------------------------------------- */ typedef struct { Bool initted; /* has it yet been initted by guest? */ Bool resizable; /* is resizing allowed? */ UWord size; /* declared size */ XArray* waiting; /* XA of Thread*. # present is 0 .. .size */ } Bar; static Bar* new_Bar ( void ) { Bar* bar = HG_(zalloc)( "hg.nB.1 (new_Bar)", sizeof(Bar) ); tl_assert(bar); /* all fields are zero */ tl_assert(bar->initted == False); return bar; } static void delete_Bar ( Bar* bar ) { tl_assert(bar); if (bar->waiting) VG_(deleteXA)(bar->waiting); HG_(free)(bar); } /* A mapping which stores auxiliary data for barriers. */ /* pthread_barrier_t* -> Bar* */ static WordFM* map_barrier_to_Bar = NULL; static void map_barrier_to_Bar_INIT ( void ) { if (UNLIKELY(map_barrier_to_Bar == NULL)) { map_barrier_to_Bar = VG_(newFM)( HG_(zalloc), "hg.mbtBI.1", HG_(free), NULL ); tl_assert(map_barrier_to_Bar != NULL); } } static Bar* map_barrier_to_Bar_lookup_or_alloc ( void* barrier ) { UWord key, val; map_barrier_to_Bar_INIT(); if (VG_(lookupFM)( map_barrier_to_Bar, &key, &val, (UWord)barrier )) { tl_assert(key == (UWord)barrier); return (Bar*)val; } else { Bar* bar = new_Bar(); VG_(addToFM)( map_barrier_to_Bar, (UWord)barrier, (UWord)bar ); return bar; } } static void map_barrier_to_Bar_delete ( void* barrier ) { UWord keyW, valW; map_barrier_to_Bar_INIT(); if (VG_(delFromFM)( map_barrier_to_Bar, &keyW, &valW, (UWord)barrier )) { Bar* bar = (Bar*)valW; tl_assert(keyW == (UWord)barrier); delete_Bar(bar); } } static void evh__HG_PTHREAD_BARRIER_INIT_PRE ( ThreadId tid, void* barrier, UWord count, UWord resizable ) { Thread* thr; Bar* bar; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_PTHREAD_BARRIER_INIT_PRE" "(tid=%d, barrier=%p, count=%lu, resizable=%lu)\n", (Int)tid, (void*)barrier, count, resizable ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ if (count == 0) { HG_(record_error_Misc)( thr, "pthread_barrier_init: 'count' argument is zero" ); } if (resizable != 0 && resizable != 1) { HG_(record_error_Misc)( thr, "pthread_barrier_init: invalid 'resizable' argument" ); } bar = map_barrier_to_Bar_lookup_or_alloc(barrier); tl_assert(bar); if (bar->initted) { HG_(record_error_Misc)( thr, "pthread_barrier_init: barrier is already initialised" ); } if (bar->waiting && VG_(sizeXA)(bar->waiting) > 0) { tl_assert(bar->initted); HG_(record_error_Misc)( thr, "pthread_barrier_init: threads are waiting at barrier" ); VG_(dropTailXA)(bar->waiting, VG_(sizeXA)(bar->waiting)); } if (!bar->waiting) { bar->waiting = VG_(newXA)( HG_(zalloc), "hg.eHPBIP.1", HG_(free), sizeof(Thread*) ); } tl_assert(bar->waiting); tl_assert(VG_(sizeXA)(bar->waiting) == 0); bar->initted = True; bar->resizable = resizable == 1 ? True : False; bar->size = count; } static void evh__HG_PTHREAD_BARRIER_DESTROY_PRE ( ThreadId tid, void* barrier ) { Thread* thr; Bar* bar; /* Deal with destroy events. The only purpose is to free storage associated with the barrier, so as to avoid any possible resource leaks. */ if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_PTHREAD_BARRIER_DESTROY_PRE" "(tid=%d, barrier=%p)\n", (Int)tid, (void*)barrier ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ bar = map_barrier_to_Bar_lookup_or_alloc(barrier); tl_assert(bar); if (!bar->initted) { HG_(record_error_Misc)( thr, "pthread_barrier_destroy: barrier was never initialised" ); } if (bar->initted && bar->waiting && VG_(sizeXA)(bar->waiting) > 0) { HG_(record_error_Misc)( thr, "pthread_barrier_destroy: threads are waiting at barrier" ); } /* Maybe we shouldn't do this; just let it persist, so that when it is reinitialised we don't need to do any dynamic memory allocation? The downside is a potentially unlimited space leak, if the client creates (in turn) a large number of barriers all at different locations. Note that if we do later move to the don't-delete-it scheme, we need to mark the barrier as uninitialised again since otherwise a later _init call will elicit a duplicate-init error. */ map_barrier_to_Bar_delete( barrier ); } /* All the threads have arrived. Now do the Interesting Bit. Get a new synchronisation object and do a weak send to it from all the participating threads. This makes its vector clocks be the join of all the individual threads' vector clocks. Then do a strong receive from it back to all threads, so that their VCs are a copy of it (hence are all equal to the join of their original VCs.) */ static void do_barrier_cross_sync_and_empty ( Bar* bar ) { /* XXX check bar->waiting has no duplicates */ UWord i; SO* so = libhb_so_alloc(); tl_assert(bar->waiting); tl_assert(VG_(sizeXA)(bar->waiting) == bar->size); /* compute the join ... */ for (i = 0; i < bar->size; i++) { Thread* t = *(Thread**)VG_(indexXA)(bar->waiting, i); Thr* hbthr = t->hbthr; libhb_so_send( hbthr, so, False/*weak send*/ ); } /* ... and distribute to all threads */ for (i = 0; i < bar->size; i++) { Thread* t = *(Thread**)VG_(indexXA)(bar->waiting, i); Thr* hbthr = t->hbthr; libhb_so_recv( hbthr, so, True/*strong recv*/ ); } /* finally, we must empty out the waiting vector */ VG_(dropTailXA)(bar->waiting, VG_(sizeXA)(bar->waiting)); /* and we don't need this any more. Perhaps a stack-allocated SO would be better? */ libhb_so_dealloc(so); } static void evh__HG_PTHREAD_BARRIER_WAIT_PRE ( ThreadId tid, void* barrier ) { /* This function gets called after a client thread calls pthread_barrier_wait but before it arrives at the real pthread_barrier_wait. Why is the following correct? It's a bit subtle. If this is not the last thread arriving at the barrier, we simply note its presence and return. Because valgrind (at least as of Nov 08) is single threaded, we are guaranteed safe from any race conditions when in this function -- no other client threads are running. If this is the last thread, then we are again the only running thread. All the other threads will have either arrived at the real pthread_barrier_wait or are on their way to it, but in any case are guaranteed not to be able to move past it, because this thread is currently in this function and so has not yet arrived at the real pthread_barrier_wait. That means that: 1. While we are in this function, none of the other threads waiting at the barrier can move past it. 2. When this function returns (and simulated execution resumes), this thread and all other waiting threads will be able to move past the real barrier. Because of this, it is now safe to update the vector clocks of all threads, to represent the fact that they all arrived at the barrier and have all moved on. There is no danger of any complications to do with some threads leaving the barrier and racing back round to the front, whilst others are still leaving (which is the primary source of complication in correct handling/ implementation of barriers). That can't happen because we update here our data structures so as to indicate that the threads have passed the barrier, even though, as per (2) above, they are guaranteed not to pass the barrier until we return. This relies crucially on Valgrind being single threaded. If that changes, this will need to be reconsidered. */ Thread* thr; Bar* bar; UWord present; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_PTHREAD_BARRIER_WAIT_PRE" "(tid=%d, barrier=%p)\n", (Int)tid, (void*)barrier ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ bar = map_barrier_to_Bar_lookup_or_alloc(barrier); tl_assert(bar); if (!bar->initted) { HG_(record_error_Misc)( thr, "pthread_barrier_wait: barrier is uninitialised" ); return; /* client is broken .. avoid assertions below */ } /* guaranteed by _INIT_PRE above */ tl_assert(bar->size > 0); tl_assert(bar->waiting); VG_(addToXA)( bar->waiting, &thr ); /* guaranteed by this function */ present = VG_(sizeXA)(bar->waiting); tl_assert(present > 0 && present <= bar->size); if (present < bar->size) return; do_barrier_cross_sync_and_empty(bar); } static void evh__HG_PTHREAD_BARRIER_RESIZE_PRE ( ThreadId tid, void* barrier, UWord newcount ) { Thread* thr; Bar* bar; UWord present; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_PTHREAD_BARRIER_RESIZE_PRE" "(tid=%d, barrier=%p, newcount=%lu)\n", (Int)tid, (void*)barrier, newcount ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ bar = map_barrier_to_Bar_lookup_or_alloc(barrier); tl_assert(bar); if (!bar->initted) { HG_(record_error_Misc)( thr, "pthread_barrier_resize: barrier is uninitialised" ); return; /* client is broken .. avoid assertions below */ } if (!bar->resizable) { HG_(record_error_Misc)( thr, "pthread_barrier_resize: barrier is may not be resized" ); return; /* client is broken .. avoid assertions below */ } if (newcount == 0) { HG_(record_error_Misc)( thr, "pthread_barrier_resize: 'newcount' argument is zero" ); return; /* client is broken .. avoid assertions below */ } /* guaranteed by _INIT_PRE above */ tl_assert(bar->size > 0); tl_assert(bar->waiting); /* Guaranteed by this fn */ tl_assert(newcount > 0); if (newcount >= bar->size) { /* Increasing the capacity. There's no possibility of threads moving on from the barrier in this situation, so just note the fact and do nothing more. */ bar->size = newcount; } else { /* Decreasing the capacity. If we decrease it to be equal or below the number of waiting threads, they will now move past the barrier, so need to mess with dep edges in the same way as if the barrier had filled up normally. */ present = VG_(sizeXA)(bar->waiting); tl_assert(present >= 0 && present <= bar->size); if (newcount <= present) { bar->size = present; /* keep the cross_sync call happy */ do_barrier_cross_sync_and_empty(bar); } bar->size = newcount; } } /* ----------------------------------------------------- */ /* ----- events to do with user-specified HB edges ----- */ /* ----------------------------------------------------- */ /* A mapping from arbitrary UWord tag to the SO associated with it. The UWord tags are meaningless to us, interpreted only by the user. */ /* UWord -> SO* */ static WordFM* map_usertag_to_SO = NULL; static void map_usertag_to_SO_INIT ( void ) { if (UNLIKELY(map_usertag_to_SO == NULL)) { map_usertag_to_SO = VG_(newFM)( HG_(zalloc), "hg.mutS.1", HG_(free), NULL ); tl_assert(map_usertag_to_SO != NULL); } } static SO* map_usertag_to_SO_lookup_or_alloc ( UWord usertag ) { UWord key, val; map_usertag_to_SO_INIT(); if (VG_(lookupFM)( map_usertag_to_SO, &key, &val, usertag )) { tl_assert(key == (UWord)usertag); return (SO*)val; } else { SO* so = libhb_so_alloc(); VG_(addToFM)( map_usertag_to_SO, usertag, (UWord)so ); return so; } } // If it's ever needed (XXX check before use) //static void map_usertag_to_SO_delete ( UWord usertag ) { // UWord keyW, valW; // map_usertag_to_SO_INIT(); // if (VG_(delFromFM)( map_usertag_to_SO, &keyW, &valW, usertag )) { // SO* so = (SO*)valW; // tl_assert(keyW == usertag); // tl_assert(so); // libhb_so_dealloc(so); // } //} static void evh__HG_USERSO_SEND_PRE ( ThreadId tid, UWord usertag ) { /* TID is just about to notionally sent a message on a notional abstract synchronisation object whose identity is given by USERTAG. Bind USERTAG to a real SO if it is not already so bound, and do a 'strong send' on the SO. This is later used by other thread(s) which successfully 'receive' from the SO, thereby acquiring a dependency on this signalling event. */ Thread* thr; SO* so; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_USERSO_SEND_PRE(ctid=%d, usertag=%#lx)\n", (Int)tid, usertag ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ so = map_usertag_to_SO_lookup_or_alloc( usertag ); tl_assert(so); libhb_so_send( thr->hbthr, so, True/*strong_send*/ ); } static void evh__HG_USERSO_RECV_POST ( ThreadId tid, UWord usertag ) { /* TID has just notionally received a message from a notional abstract synchronisation object whose identity is given by USERTAG. Bind USERTAG to a real SO if it is not already so bound. If the SO has at some point in the past been 'sent' on, to a 'strong receive' on it, thereby acquiring a dependency on the sender. */ Thread* thr; SO* so; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_USERSO_RECV_POST(ctid=%d, usertag=%#lx)\n", (Int)tid, usertag ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ so = map_usertag_to_SO_lookup_or_alloc( usertag ); tl_assert(so); /* Acquire a dependency on it. If the SO has never so far been sent on, then libhb_so_recv will do nothing. So we're safe regardless of SO's history. */ libhb_so_recv( thr->hbthr, so, True/*strong_recv*/ ); } /*--------------------------------------------------------------*/ /*--- Lock acquisition order monitoring ---*/ /*--------------------------------------------------------------*/ /* FIXME: here are some optimisations still to do in laog__pre_thread_acquires_lock. The graph is structured so that if L1 --*--> L2 then L1 must be acquired before L2. The common case is that some thread T holds (eg) L1 L2 and L3 and is repeatedly acquiring and releasing Ln, and there is no ordering error in what it is doing. Hence it repeatly: (1) searches laog to see if Ln --*--> {L1,L2,L3}, which always produces the answer No (because there is no error). (2) adds edges {L1,L2,L3} --> Ln to laog, which are already present (because they already got added the first time T acquired Ln). Hence cache these two events: (1) Cache result of the query from last time. Invalidate the cache any time any edges are added to or deleted from laog. (2) Cache these add-edge requests and ignore them if said edges have already been added to laog. Invalidate the cache any time any edges are deleted from laog. */ typedef struct { WordSetID inns; /* in univ_laog */ WordSetID outs; /* in univ_laog */ } LAOGLinks; /* lock order acquisition graph */ static WordFM* laog = NULL; /* WordFM Lock* LAOGLinks* */ /* EXPOSITION ONLY: for each edge in 'laog', record the two places where that edge was created, so that we can show the user later if we need to. */ typedef struct { Addr src_ga; /* Lock guest addresses for */ Addr dst_ga; /* src/dst of the edge */ ExeContext* src_ec; /* And corresponding places where that */ ExeContext* dst_ec; /* ordering was established */ } LAOGLinkExposition; static Word cmp_LAOGLinkExposition ( UWord llx1W, UWord llx2W ) { /* Compare LAOGLinkExposition*s by (src_ga,dst_ga) field pair. */ LAOGLinkExposition* llx1 = (LAOGLinkExposition*)llx1W; LAOGLinkExposition* llx2 = (LAOGLinkExposition*)llx2W; if (llx1->src_ga < llx2->src_ga) return -1; if (llx1->src_ga > llx2->src_ga) return 1; if (llx1->dst_ga < llx2->dst_ga) return -1; if (llx1->dst_ga > llx2->dst_ga) return 1; return 0; } static WordFM* laog_exposition = NULL; /* WordFM LAOGLinkExposition* NULL */ /* end EXPOSITION ONLY */ __attribute__((noinline)) static void laog__init ( void ) { tl_assert(!laog); tl_assert(!laog_exposition); tl_assert(HG_(clo_track_lockorders)); laog = VG_(newFM)( HG_(zalloc), "hg.laog__init.1", HG_(free), NULL/*unboxedcmp*/ ); laog_exposition = VG_(newFM)( HG_(zalloc), "hg.laog__init.2", HG_(free), cmp_LAOGLinkExposition ); tl_assert(laog); tl_assert(laog_exposition); } static void laog__show ( Char* who ) { Word i, ws_size; UWord* ws_words; Lock* me; LAOGLinks* links; VG_(printf)("laog (requested by %s) {\n", who); VG_(initIterFM)( laog ); me = NULL; links = NULL; while (VG_(nextIterFM)( laog, (Word*)&me, (Word*)&links )) { tl_assert(me); tl_assert(links); VG_(printf)(" node %p:\n", me); HG_(getPayloadWS)( &ws_words, &ws_size, univ_laog, links->inns ); for (i = 0; i < ws_size; i++) VG_(printf)(" inn %#lx\n", ws_words[i] ); HG_(getPayloadWS)( &ws_words, &ws_size, univ_laog, links->outs ); for (i = 0; i < ws_size; i++) VG_(printf)(" out %#lx\n", ws_words[i] ); me = NULL; links = NULL; } VG_(doneIterFM)( laog ); VG_(printf)("}\n"); } __attribute__((noinline)) static void laog__add_edge ( Lock* src, Lock* dst ) { Word keyW; LAOGLinks* links; Bool presentF, presentR; if (0) VG_(printf)("laog__add_edge %p %p\n", src, dst); /* Take the opportunity to sanity check the graph. Record in presentF if there is already a src->dst mapping in this node's forwards links, and presentR if there is already a src->dst mapping in this node's backwards links. They should agree! Also, we need to know whether the edge was already present so as to decide whether or not to update the link details mapping. We can compute presentF and presentR essentially for free, so may as well do this always. */ presentF = presentR = False; /* Update the out edges for src */ keyW = 0; links = NULL; if (VG_(lookupFM)( laog, &keyW, (Word*)&links, (Word)src )) { WordSetID outs_new; tl_assert(links); tl_assert(keyW == (Word)src); outs_new = HG_(addToWS)( univ_laog, links->outs, (Word)dst ); presentF = outs_new == links->outs; links->outs = outs_new; } else { links = HG_(zalloc)("hg.lae.1", sizeof(LAOGLinks)); links->inns = HG_(emptyWS)( univ_laog ); links->outs = HG_(singletonWS)( univ_laog, (Word)dst ); VG_(addToFM)( laog, (Word)src, (Word)links ); } /* Update the in edges for dst */ keyW = 0; links = NULL; if (VG_(lookupFM)( laog, &keyW, (Word*)&links, (Word)dst )) { WordSetID inns_new; tl_assert(links); tl_assert(keyW == (Word)dst); inns_new = HG_(addToWS)( univ_laog, links->inns, (Word)src ); presentR = inns_new == links->inns; links->inns = inns_new; } else { links = HG_(zalloc)("hg.lae.2", sizeof(LAOGLinks)); links->inns = HG_(singletonWS)( univ_laog, (Word)src ); links->outs = HG_(emptyWS)( univ_laog ); VG_(addToFM)( laog, (Word)dst, (Word)links ); } tl_assert( (presentF && presentR) || (!presentF && !presentR) ); if (!presentF && src->acquired_at && dst->acquired_at) { LAOGLinkExposition expo; /* If this edge is entering the graph, and we have acquired_at information for both src and dst, record those acquisition points. Hence, if there is later a violation of this ordering, we can show the user the two places in which the required src-dst ordering was previously established. */ if (0) VG_(printf)("acquire edge %#lx %#lx\n", src->guestaddr, dst->guestaddr); expo.src_ga = src->guestaddr; expo.dst_ga = dst->guestaddr; expo.src_ec = NULL; expo.dst_ec = NULL; tl_assert(laog_exposition); if (VG_(lookupFM)( laog_exposition, NULL, NULL, (Word)&expo )) { /* we already have it; do nothing */ } else { LAOGLinkExposition* expo2 = HG_(zalloc)("hg.lae.3", sizeof(LAOGLinkExposition)); expo2->src_ga = src->guestaddr; expo2->dst_ga = dst->guestaddr; expo2->src_ec = src->acquired_at; expo2->dst_ec = dst->acquired_at; VG_(addToFM)( laog_exposition, (Word)expo2, (Word)NULL ); } } } __attribute__((noinline)) static void laog__del_edge ( Lock* src, Lock* dst ) { Word keyW; LAOGLinks* links; if (0) VG_(printf)("laog__del_edge %p %p\n", src, dst); /* Update the out edges for src */ keyW = 0; links = NULL; if (VG_(lookupFM)( laog, &keyW, (Word*)&links, (Word)src )) { tl_assert(links); tl_assert(keyW == (Word)src); links->outs = HG_(delFromWS)( univ_laog, links->outs, (Word)dst ); } /* Update the in edges for dst */ keyW = 0; links = NULL; if (VG_(lookupFM)( laog, &keyW, (Word*)&links, (Word)dst )) { tl_assert(links); tl_assert(keyW == (Word)dst); links->inns = HG_(delFromWS)( univ_laog, links->inns, (Word)src ); } } __attribute__((noinline)) static WordSetID /* in univ_laog */ laog__succs ( Lock* lk ) { Word keyW; LAOGLinks* links; keyW = 0; links = NULL; if (VG_(lookupFM)( laog, &keyW, (Word*)&links, (Word)lk )) { tl_assert(links); tl_assert(keyW == (Word)lk); return links->outs; } else { return HG_(emptyWS)( univ_laog ); } } __attribute__((noinline)) static WordSetID /* in univ_laog */ laog__preds ( Lock* lk ) { Word keyW; LAOGLinks* links; keyW = 0; links = NULL; if (VG_(lookupFM)( laog, &keyW, (Word*)&links, (Word)lk )) { tl_assert(links); tl_assert(keyW == (Word)lk); return links->inns; } else { return HG_(emptyWS)( univ_laog ); } } __attribute__((noinline)) static void laog__sanity_check ( Char* who ) { Word i, ws_size; UWord* ws_words; Lock* me; LAOGLinks* links; VG_(initIterFM)( laog ); me = NULL; links = NULL; if (0) VG_(printf)("laog sanity check\n"); while (VG_(nextIterFM)( laog, (Word*)&me, (Word*)&links )) { tl_assert(me); tl_assert(links); HG_(getPayloadWS)( &ws_words, &ws_size, univ_laog, links->inns ); for (i = 0; i < ws_size; i++) { if ( ! HG_(elemWS)( univ_laog, laog__succs( (Lock*)ws_words[i] ), (Word)me )) goto bad; } HG_(getPayloadWS)( &ws_words, &ws_size, univ_laog, links->outs ); for (i = 0; i < ws_size; i++) { if ( ! HG_(elemWS)( univ_laog, laog__preds( (Lock*)ws_words[i] ), (Word)me )) goto bad; } me = NULL; links = NULL; } VG_(doneIterFM)( laog ); return; bad: VG_(printf)("laog__sanity_check(%s) FAILED\n", who); laog__show(who); tl_assert(0); } /* If there is a path in laog from 'src' to any of the elements in 'dst', return an arbitrarily chosen element of 'dst' reachable from 'src'. If no path exist from 'src' to any element in 'dst', return NULL. */ __attribute__((noinline)) static Lock* laog__do_dfs_from_to ( Lock* src, WordSetID dsts /* univ_lsets */ ) { Lock* ret; Word i, ssz; XArray* stack; /* of Lock* */ WordFM* visited; /* Lock* -> void, iow, Set(Lock*) */ Lock* here; WordSetID succs; Word succs_size; UWord* succs_words; //laog__sanity_check(); /* If the destination set is empty, we can never get there from 'src' :-), so don't bother to try */ if (HG_(isEmptyWS)( univ_lsets, dsts )) return NULL; ret = NULL; stack = VG_(newXA)( HG_(zalloc), "hg.lddft.1", HG_(free), sizeof(Lock*) ); visited = VG_(newFM)( HG_(zalloc), "hg.lddft.2", HG_(free), NULL/*unboxedcmp*/ ); (void) VG_(addToXA)( stack, &src ); while (True) { ssz = VG_(sizeXA)( stack ); if (ssz == 0) { ret = NULL; break; } here = *(Lock**) VG_(indexXA)( stack, ssz-1 ); VG_(dropTailXA)( stack, 1 ); if (HG_(elemWS)( univ_lsets, dsts, (Word)here )) { ret = here; break; } if (VG_(lookupFM)( visited, NULL, NULL, (Word)here )) continue; VG_(addToFM)( visited, (Word)here, 0 ); succs = laog__succs( here ); HG_(getPayloadWS)( &succs_words, &succs_size, univ_laog, succs ); for (i = 0; i < succs_size; i++) (void) VG_(addToXA)( stack, &succs_words[i] ); } VG_(deleteFM)( visited, NULL, NULL ); VG_(deleteXA)( stack ); return ret; } /* Thread 'thr' is acquiring 'lk'. Check for inconsistent ordering between 'lk' and the locks already held by 'thr' and issue a complaint if so. Also, update the ordering graph appropriately. */ __attribute__((noinline)) static void laog__pre_thread_acquires_lock ( Thread* thr, /* NB: BEFORE lock is added */ Lock* lk ) { UWord* ls_words; Word ls_size, i; Lock* other; /* It may be that 'thr' already holds 'lk' and is recursively relocking in. In this case we just ignore the call. */ /* NB: univ_lsets really is correct here */ if (HG_(elemWS)( univ_lsets, thr->locksetA, (Word)lk )) return; /* First, the check. Complain if there is any path in laog from lk to any of the locks already held by thr, since if any such path existed, it would mean that previously lk was acquired before (rather than after, as we are doing here) at least one of those locks. */ other = laog__do_dfs_from_to(lk, thr->locksetA); if (other) { LAOGLinkExposition key, *found; /* So we managed to find a path lk --*--> other in the graph, which implies that 'lk' should have been acquired before 'other' but is in fact being acquired afterwards. We present the lk/other arguments to record_error_LockOrder in the order in which they should have been acquired. */ /* Go look in the laog_exposition mapping, to find the allocation points for this edge, so we can show the user. */ key.src_ga = lk->guestaddr; key.dst_ga = other->guestaddr; key.src_ec = NULL; key.dst_ec = NULL; found = NULL; if (VG_(lookupFM)( laog_exposition, (Word*)&found, NULL, (Word)&key )) { tl_assert(found != &key); tl_assert(found->src_ga == key.src_ga); tl_assert(found->dst_ga == key.dst_ga); tl_assert(found->src_ec); tl_assert(found->dst_ec); HG_(record_error_LockOrder)( thr, lk->guestaddr, other->guestaddr, found->src_ec, found->dst_ec ); } else { /* Hmm. This can't happen (can it?) */ HG_(record_error_LockOrder)( thr, lk->guestaddr, other->guestaddr, NULL, NULL ); } } /* Second, add to laog the pairs (old, lk) | old <- locks already held by thr Since both old and lk are currently held by thr, their acquired_at fields must be non-NULL. */ tl_assert(lk->acquired_at); HG_(getPayloadWS)( &ls_words, &ls_size, univ_lsets, thr->locksetA ); for (i = 0; i < ls_size; i++) { Lock* old = (Lock*)ls_words[i]; tl_assert(old->acquired_at); laog__add_edge( old, lk ); } /* Why "except_Locks" ? We're here because a lock is being acquired by a thread, and we're in an inconsistent state here. See the call points in evhH__post_thread_{r,w}_acquires_lock. When called in this inconsistent state, locks__sanity_check duly barfs. */ if (HG_(clo_sanity_flags) & SCE_LAOG) all_except_Locks__sanity_check("laog__pre_thread_acquires_lock-post"); } /* Delete from 'laog' any pair mentioning a lock in locksToDelete */ __attribute__((noinline)) static void laog__handle_one_lock_deletion ( Lock* lk ) { WordSetID preds, succs; Word preds_size, succs_size, i, j; UWord *preds_words, *succs_words; preds = laog__preds( lk ); succs = laog__succs( lk ); HG_(getPayloadWS)( &preds_words, &preds_size, univ_laog, preds ); for (i = 0; i < preds_size; i++) laog__del_edge( (Lock*)preds_words[i], lk ); HG_(getPayloadWS)( &succs_words, &succs_size, univ_laog, succs ); for (j = 0; j < succs_size; j++) laog__del_edge( lk, (Lock*)succs_words[j] ); for (i = 0; i < preds_size; i++) { for (j = 0; j < succs_size; j++) { if (preds_words[i] != succs_words[j]) { /* This can pass unlocked locks to laog__add_edge, since we're deleting stuff. So their acquired_at fields may be NULL. */ laog__add_edge( (Lock*)preds_words[i], (Lock*)succs_words[j] ); } } } } //__attribute__((noinline)) //static void laog__handle_lock_deletions ( // WordSetID /* in univ_laog */ locksToDelete // ) //{ // Word i, ws_size; // UWord* ws_words; // // // HG_(getPayloadWS)( &ws_words, &ws_size, univ_lsets, locksToDelete ); // for (i = 0; i < ws_size; i++) // laog__handle_one_lock_deletion( (Lock*)ws_words[i] ); // // if (HG_(clo_sanity_flags) & SCE_LAOG) // all__sanity_check("laog__handle_lock_deletions-post"); //} /*--------------------------------------------------------------*/ /*--- Malloc/free replacements ---*/ /*--------------------------------------------------------------*/ typedef struct { void* next; /* required by m_hashtable */ Addr payload; /* ptr to actual block */ SizeT szB; /* size requested */ ExeContext* where; /* where it was allocated */ Thread* thr; /* allocating thread */ } MallocMeta; /* A hash table of MallocMetas, used to track malloc'd blocks (obviously). */ static VgHashTable hg_mallocmeta_table = NULL; static MallocMeta* new_MallocMeta ( void ) { MallocMeta* md = HG_(zalloc)( "hg.new_MallocMeta.1", sizeof(MallocMeta) ); tl_assert(md); return md; } static void delete_MallocMeta ( MallocMeta* md ) { HG_(free)(md); } /* Allocate a client block and set up the metadata for it. */ static void* handle_alloc ( ThreadId tid, SizeT szB, SizeT alignB, Bool is_zeroed ) { Addr p; MallocMeta* md; tl_assert( ((SSizeT)szB) >= 0 ); p = (Addr)VG_(cli_malloc)(alignB, szB); if (!p) { return NULL; } if (is_zeroed) VG_(memset)((void*)p, 0, szB); /* Note that map_threads_lookup must succeed (cannot assert), since memory can only be allocated by currently alive threads, hence they must have an entry in map_threads. */ md = new_MallocMeta(); md->payload = p; md->szB = szB; md->where = VG_(record_ExeContext)( tid, 0 ); md->thr = map_threads_lookup( tid ); VG_(HT_add_node)( hg_mallocmeta_table, (VgHashNode*)md ); /* Tell the lower level memory wranglers. */ evh__new_mem_heap( p, szB, is_zeroed ); return (void*)p; } /* Re the checks for less-than-zero (also in hg_cli__realloc below): Cast to a signed type to catch any unexpectedly negative args. We're assuming here that the size asked for is not greater than 2^31 bytes (for 32-bit platforms) or 2^63 bytes (for 64-bit platforms). */ static void* hg_cli__malloc ( ThreadId tid, SizeT n ) { if (((SSizeT)n) < 0) return NULL; return handle_alloc ( tid, n, VG_(clo_alignment), /*is_zeroed*/False ); } static void* hg_cli____builtin_new ( ThreadId tid, SizeT n ) { if (((SSizeT)n) < 0) return NULL; return handle_alloc ( tid, n, VG_(clo_alignment), /*is_zeroed*/False ); } static void* hg_cli____builtin_vec_new ( ThreadId tid, SizeT n ) { if (((SSizeT)n) < 0) return NULL; return handle_alloc ( tid, n, VG_(clo_alignment), /*is_zeroed*/False ); } static void* hg_cli__memalign ( ThreadId tid, SizeT align, SizeT n ) { if (((SSizeT)n) < 0) return NULL; return handle_alloc ( tid, n, align, /*is_zeroed*/False ); } static void* hg_cli__calloc ( ThreadId tid, SizeT nmemb, SizeT size1 ) { if ( ((SSizeT)nmemb) < 0 || ((SSizeT)size1) < 0 ) return NULL; return handle_alloc ( tid, nmemb*size1, VG_(clo_alignment), /*is_zeroed*/True ); } /* Free a client block, including getting rid of the relevant metadata. */ static void handle_free ( ThreadId tid, void* p ) { MallocMeta *md, *old_md; SizeT szB; /* First see if we can find the metadata for 'p'. */ md = (MallocMeta*) VG_(HT_lookup)( hg_mallocmeta_table, (UWord)p ); if (!md) return; /* apparently freeing a bogus address. Oh well. */ tl_assert(md->payload == (Addr)p); szB = md->szB; /* Nuke the metadata block */ old_md = (MallocMeta*) VG_(HT_remove)( hg_mallocmeta_table, (UWord)p ); tl_assert(old_md); /* it must be present - we just found it */ tl_assert(old_md == md); tl_assert(old_md->payload == (Addr)p); VG_(cli_free)((void*)old_md->payload); delete_MallocMeta(old_md); /* Tell the lower level memory wranglers. */ evh__die_mem_heap( (Addr)p, szB ); } static void hg_cli__free ( ThreadId tid, void* p ) { handle_free(tid, p); } static void hg_cli____builtin_delete ( ThreadId tid, void* p ) { handle_free(tid, p); } static void hg_cli____builtin_vec_delete ( ThreadId tid, void* p ) { handle_free(tid, p); } static void* hg_cli__realloc ( ThreadId tid, void* payloadV, SizeT new_size ) { MallocMeta *md, *md_new, *md_tmp; SizeT i; Addr payload = (Addr)payloadV; if (((SSizeT)new_size) < 0) return NULL; md = (MallocMeta*) VG_(HT_lookup)( hg_mallocmeta_table, (UWord)payload ); if (!md) return NULL; /* apparently realloc-ing a bogus address. Oh well. */ tl_assert(md->payload == payload); if (md->szB == new_size) { /* size unchanged */ md->where = VG_(record_ExeContext)(tid, 0); return payloadV; } if (md->szB > new_size) { /* new size is smaller */ md->szB = new_size; md->where = VG_(record_ExeContext)(tid, 0); evh__die_mem_heap( md->payload + new_size, md->szB - new_size ); return payloadV; } /* else */ { /* new size is bigger */ Addr p_new = (Addr)VG_(cli_malloc)(VG_(clo_alignment), new_size); /* First half kept and copied, second half new */ // FIXME: shouldn't we use a copier which implements the // memory state machine? evh__copy_mem( payload, p_new, md->szB ); evh__new_mem_heap ( p_new + md->szB, new_size - md->szB, /*inited*/False ); /* FIXME: can anything funny happen here? specifically, if the old range contained a lock, then die_mem_heap will complain. Is that the correct behaviour? Not sure. */ evh__die_mem_heap( payload, md->szB ); /* Copy from old to new */ for (i = 0; i < md->szB; i++) ((UChar*)p_new)[i] = ((UChar*)payload)[i]; /* Because the metadata hash table is index by payload address, we have to get rid of the old hash table entry and make a new one. We can't just modify the existing metadata in place, because then it would (almost certainly) be in the wrong hash chain. */ md_new = new_MallocMeta(); *md_new = *md; md_tmp = VG_(HT_remove)( hg_mallocmeta_table, payload ); tl_assert(md_tmp); tl_assert(md_tmp == md); VG_(cli_free)((void*)md->payload); delete_MallocMeta(md); /* Update fields */ md_new->where = VG_(record_ExeContext)( tid, 0 ); md_new->szB = new_size; md_new->payload = p_new; md_new->thr = map_threads_lookup( tid ); /* and add */ VG_(HT_add_node)( hg_mallocmeta_table, (VgHashNode*)md_new ); return (void*)p_new; } } static SizeT hg_cli_malloc_usable_size ( ThreadId tid, void* p ) { MallocMeta *md = VG_(HT_lookup)( hg_mallocmeta_table, (UWord)p ); // There may be slop, but pretend there isn't because only the asked-for // area will have been shadowed properly. return ( md ? md->szB : 0 ); } /* For error creation: map 'data_addr' to a malloc'd chunk, if any. Slow linear search. With a bit of hash table help if 'data_addr' is either the start of a block or up to 15 word-sized steps along from the start of a block. */ static inline Bool addr_is_in_MM_Chunk( MallocMeta* mm, Addr a ) { /* Accept 'a' as within 'mm' if 'mm's size is zero and 'a' points right at it. */ if (UNLIKELY(mm->szB == 0 && a == mm->payload)) return True; /* else normal interval rules apply */ if (LIKELY(a < mm->payload)) return False; if (LIKELY(a >= mm->payload + mm->szB)) return False; return True; } Bool HG_(mm_find_containing_block)( /*OUT*/ExeContext** where, /*OUT*/Addr* payload, /*OUT*/SizeT* szB, Addr data_addr ) { MallocMeta* mm; Int i; const Int n_fast_check_words = 16; /* First, do a few fast searches on the basis that data_addr might be exactly the start of a block or up to 15 words inside. This can happen commonly via the creq _VG_USERREQ__HG_CLEAN_MEMORY_HEAPBLOCK. */ for (i = 0; i < n_fast_check_words; i++) { mm = VG_(HT_lookup)( hg_mallocmeta_table, data_addr - (UWord)(UInt)i * sizeof(UWord) ); if (UNLIKELY(mm && addr_is_in_MM_Chunk(mm, data_addr))) goto found; } /* Well, this totally sucks. But without using an interval tree or some such, it's hard to see how to do better. We have to check every block in the entire table. */ VG_(HT_ResetIter)(hg_mallocmeta_table); while ( (mm = VG_(HT_Next)(hg_mallocmeta_table)) ) { if (UNLIKELY(addr_is_in_MM_Chunk(mm, data_addr))) goto found; } /* Not found. Bah. */ return False; /*NOTREACHED*/ found: tl_assert(mm); tl_assert(addr_is_in_MM_Chunk(mm, data_addr)); if (where) *where = mm->where; if (payload) *payload = mm->payload; if (szB) *szB = mm->szB; return True; } /*--------------------------------------------------------------*/ /*--- Instrumentation ---*/ /*--------------------------------------------------------------*/ static void instrument_mem_access ( IRSB* bbOut, IRExpr* addr, Int szB, Bool isStore, Int hWordTy_szB ) { IRType tyAddr = Ity_INVALID; HChar* hName = NULL; void* hAddr = NULL; Int regparms = 0; IRExpr** argv = NULL; IRDirty* di = NULL; tl_assert(isIRAtom(addr)); tl_assert(hWordTy_szB == 4 || hWordTy_szB == 8); tyAddr = typeOfIRExpr( bbOut->tyenv, addr ); tl_assert(tyAddr == Ity_I32 || tyAddr == Ity_I64); /* So the effective address is in 'addr' now. */ regparms = 1; // unless stated otherwise if (isStore) { switch (szB) { case 1: hName = "evh__mem_help_cwrite_1"; hAddr = &evh__mem_help_cwrite_1; argv = mkIRExprVec_1( addr ); break; case 2: hName = "evh__mem_help_cwrite_2"; hAddr = &evh__mem_help_cwrite_2; argv = mkIRExprVec_1( addr ); break; case 4: hName = "evh__mem_help_cwrite_4"; hAddr = &evh__mem_help_cwrite_4; argv = mkIRExprVec_1( addr ); break; case 8: hName = "evh__mem_help_cwrite_8"; hAddr = &evh__mem_help_cwrite_8; argv = mkIRExprVec_1( addr ); break; default: tl_assert(szB > 8 && szB <= 512); /* stay sane */ regparms = 2; hName = "evh__mem_help_cwrite_N"; hAddr = &evh__mem_help_cwrite_N; argv = mkIRExprVec_2( addr, mkIRExpr_HWord( szB )); break; } } else { switch (szB) { case 1: hName = "evh__mem_help_cread_1"; hAddr = &evh__mem_help_cread_1; argv = mkIRExprVec_1( addr ); break; case 2: hName = "evh__mem_help_cread_2"; hAddr = &evh__mem_help_cread_2; argv = mkIRExprVec_1( addr ); break; case 4: hName = "evh__mem_help_cread_4"; hAddr = &evh__mem_help_cread_4; argv = mkIRExprVec_1( addr ); break; case 8: hName = "evh__mem_help_cread_8"; hAddr = &evh__mem_help_cread_8; argv = mkIRExprVec_1( addr ); break; default: tl_assert(szB > 8 && szB <= 512); /* stay sane */ regparms = 2; hName = "evh__mem_help_cread_N"; hAddr = &evh__mem_help_cread_N; argv = mkIRExprVec_2( addr, mkIRExpr_HWord( szB )); break; } } /* Add the helper. */ tl_assert(hName); tl_assert(hAddr); tl_assert(argv); di = unsafeIRDirty_0_N( regparms, hName, VG_(fnptr_to_fnentry)( hAddr ), argv ); addStmtToIRSB( bbOut, IRStmt_Dirty(di) ); } /* Figure out if GA is a guest code address in the dynamic linker, and if so return True. Otherwise (and in case of any doubt) return False. (sidedly safe w/ False as the safe value) */ static Bool is_in_dynamic_linker_shared_object( Addr64 ga ) { DebugInfo* dinfo; const UChar* soname; if (0) return False; dinfo = VG_(find_DebugInfo)( (Addr)ga ); if (!dinfo) return False; soname = VG_(DebugInfo_get_soname)(dinfo); tl_assert(soname); if (0) VG_(printf)("%s\n", soname); # if defined(VGO_linux) if (VG_STREQ(soname, VG_U_LD_LINUX_SO_3)) return True; if (VG_STREQ(soname, VG_U_LD_LINUX_SO_2)) return True; if (VG_STREQ(soname, VG_U_LD_LINUX_X86_64_SO_2)) return True; if (VG_STREQ(soname, VG_U_LD64_SO_1)) return True; if (VG_STREQ(soname, VG_U_LD_SO_1)) return True; # elif defined(VGO_darwin) if (VG_STREQ(soname, VG_U_DYLD)) return True; # else # error "Unsupported OS" # endif return False; } static IRSB* hg_instrument ( VgCallbackClosure* closure, IRSB* bbIn, VexGuestLayout* layout, VexGuestExtents* vge, IRType gWordTy, IRType hWordTy ) { Int i; IRSB* bbOut; Addr64 cia; /* address of current insn */ IRStmt* st; Bool inLDSO = False; Addr64 inLDSOmask4K = 1; /* mismatches on first check */ if (gWordTy != hWordTy) { /* We don't currently support this case. */ VG_(tool_panic)("host/guest word size mismatch"); } if (VKI_PAGE_SIZE < 4096 || VG_(log2)(VKI_PAGE_SIZE) == -1) { VG_(tool_panic)("implausible or too-small VKI_PAGE_SIZE"); } /* Set up BB */ bbOut = emptyIRSB(); bbOut->tyenv = deepCopyIRTypeEnv(bbIn->tyenv); bbOut->next = deepCopyIRExpr(bbIn->next); bbOut->jumpkind = bbIn->jumpkind; // Copy verbatim any IR preamble preceding the first IMark i = 0; while (i < bbIn->stmts_used && bbIn->stmts[i]->tag != Ist_IMark) { addStmtToIRSB( bbOut, bbIn->stmts[i] ); i++; } // Get the first statement, and initial cia from it tl_assert(bbIn->stmts_used > 0); tl_assert(i < bbIn->stmts_used); st = bbIn->stmts[i]; tl_assert(Ist_IMark == st->tag); cia = st->Ist.IMark.addr; st = NULL; for (/*use current i*/; i < bbIn->stmts_used; i++) { st = bbIn->stmts[i]; tl_assert(st); tl_assert(isFlatIRStmt(st)); switch (st->tag) { case Ist_NoOp: case Ist_AbiHint: case Ist_Put: case Ist_PutI: case Ist_Exit: /* None of these can contain any memory references. */ break; case Ist_IMark: /* no mem refs, but note the insn address. */ cia = st->Ist.IMark.addr; /* Don't instrument the dynamic linker. It generates a lot of races which we just expensively suppress, so it's pointless. Avoid flooding is_in_dynamic_linker_shared_object with requests by only checking at transitions between 4K pages. */ if ((cia & ~(Addr64)0xFFF) != inLDSOmask4K) { if (0) VG_(printf)("NEW %#lx\n", (Addr)cia); inLDSOmask4K = cia & ~(Addr64)0xFFF; inLDSO = is_in_dynamic_linker_shared_object(cia); } else { if (0) VG_(printf)("old %#lx\n", (Addr)cia); } break; case Ist_MBE: switch (st->Ist.MBE.event) { case Imbe_Fence: break; /* not interesting */ default: goto unhandled; } break; case Ist_CAS: { /* Atomic read-modify-write cycle. Just pretend it's a read. */ IRCAS* cas = st->Ist.CAS.details; Bool isDCAS = cas->oldHi != IRTemp_INVALID; if (isDCAS) { tl_assert(cas->expdHi); tl_assert(cas->dataHi); } else { tl_assert(!cas->expdHi); tl_assert(!cas->dataHi); } /* Just be boring about it. */ if (!inLDSO) { instrument_mem_access( bbOut, cas->addr, (isDCAS ? 2 : 1) * sizeofIRType(typeOfIRExpr(bbIn->tyenv, cas->dataLo)), False/*!isStore*/, sizeofIRType(hWordTy) ); } break; } case Ist_LLSC: { /* We pretend store-conditionals don't exist, viz, ignore them. Whereas load-linked's are treated the same as normal loads. */ IRType dataTy; if (st->Ist.LLSC.storedata == NULL) { /* LL */ dataTy = typeOfIRTemp(bbIn->tyenv, st->Ist.LLSC.result); if (!inLDSO) { instrument_mem_access( bbOut, st->Ist.LLSC.addr, sizeofIRType(dataTy), False/*!isStore*/, sizeofIRType(hWordTy) ); } } else { /* SC */ /*ignore */ } break; } case Ist_Store: /* It seems we pretend that store-conditionals don't exist, viz, just ignore them ... */ if (!inLDSO) { instrument_mem_access( bbOut, st->Ist.Store.addr, sizeofIRType(typeOfIRExpr(bbIn->tyenv, st->Ist.Store.data)), True/*isStore*/, sizeofIRType(hWordTy) ); } break; case Ist_WrTmp: { /* ... whereas here we don't care whether a load is a vanilla one or a load-linked. */ IRExpr* data = st->Ist.WrTmp.data; if (data->tag == Iex_Load) { if (!inLDSO) { instrument_mem_access( bbOut, data->Iex.Load.addr, sizeofIRType(data->Iex.Load.ty), False/*!isStore*/, sizeofIRType(hWordTy) ); } } break; } case Ist_Dirty: { Int dataSize; IRDirty* d = st->Ist.Dirty.details; if (d->mFx != Ifx_None) { /* This dirty helper accesses memory. Collect the details. */ tl_assert(d->mAddr != NULL); tl_assert(d->mSize != 0); dataSize = d->mSize; if (d->mFx == Ifx_Read || d->mFx == Ifx_Modify) { if (!inLDSO) { instrument_mem_access( bbOut, d->mAddr, dataSize, False/*!isStore*/, sizeofIRType(hWordTy) ); } } if (d->mFx == Ifx_Write || d->mFx == Ifx_Modify) { if (!inLDSO) { instrument_mem_access( bbOut, d->mAddr, dataSize, True/*isStore*/, sizeofIRType(hWordTy) ); } } } else { tl_assert(d->mAddr == NULL); tl_assert(d->mSize == 0); } break; } default: unhandled: ppIRStmt(st); tl_assert(0); } /* switch (st->tag) */ addStmtToIRSB( bbOut, st ); } /* iterate over bbIn->stmts */ return bbOut; } /*----------------------------------------------------------------*/ /*--- Client requests ---*/ /*----------------------------------------------------------------*/ /* Sheesh. Yet another goddam finite map. */ static WordFM* map_pthread_t_to_Thread = NULL; /* pthread_t -> Thread* */ static void map_pthread_t_to_Thread_INIT ( void ) { if (UNLIKELY(map_pthread_t_to_Thread == NULL)) { map_pthread_t_to_Thread = VG_(newFM)( HG_(zalloc), "hg.mpttT.1", HG_(free), NULL ); tl_assert(map_pthread_t_to_Thread != NULL); } } static Bool hg_handle_client_request ( ThreadId tid, UWord* args, UWord* ret) { if (!VG_IS_TOOL_USERREQ('H','G',args[0])) return False; /* Anything that gets past the above check is one of ours, so we should be able to handle it. */ /* default, meaningless return value, unless otherwise set */ *ret = 0; switch (args[0]) { /* --- --- User-visible client requests --- --- */ case VG_USERREQ__HG_CLEAN_MEMORY: if (0) VG_(printf)("VG_USERREQ__HG_CLEAN_MEMORY(%#lx,%ld)\n", args[1], args[2]); /* Call die_mem to (expensively) tidy up properly, if there are any held locks etc in the area. Calling evh__die_mem and then evh__new_mem is a bit inefficient; probably just the latter would do. */ if (args[2] > 0) { /* length */ evh__die_mem(args[1], args[2]); /* and then set it to New */ evh__new_mem(args[1], args[2]); } break; case _VG_USERREQ__HG_CLEAN_MEMORY_HEAPBLOCK: { Addr payload = 0; SizeT pszB = 0; if (0) VG_(printf)("VG_USERREQ__HG_CLEAN_MEMORY_HEAPBLOCK(%#lx)\n", args[1]); if (HG_(mm_find_containing_block)(NULL, &payload, &pszB, args[1])) { if (pszB > 0) { evh__die_mem(payload, pszB); evh__new_mem(payload, pszB); } *ret = pszB; } else { *ret = (UWord)-1; } break; } case _VG_USERREQ__HG_ARANGE_MAKE_UNTRACKED: if (0) VG_(printf)("HG_ARANGE_MAKE_UNTRACKED(%#lx,%ld)\n", args[1], args[2]); if (args[2] > 0) { /* length */ evh__untrack_mem(args[1], args[2]); } break; case _VG_USERREQ__HG_ARANGE_MAKE_TRACKED: if (0) VG_(printf)("HG_ARANGE_MAKE_TRACKED(%#lx,%ld)\n", args[1], args[2]); if (args[2] > 0) { /* length */ evh__new_mem(args[1], args[2]); } break; /* --- --- Client requests for Helgrind's use only --- --- */ /* Some thread is telling us its pthread_t value. Record the binding between that and the associated Thread*, so we can later find the Thread* again when notified of a join by the thread. */ case _VG_USERREQ__HG_SET_MY_PTHREAD_T: { Thread* my_thr = NULL; if (0) VG_(printf)("SET_MY_PTHREAD_T (tid %d): pthread_t = %p\n", (Int)tid, (void*)args[1]); map_pthread_t_to_Thread_INIT(); my_thr = map_threads_maybe_lookup( tid ); /* This assertion should hold because the map_threads (tid to Thread*) binding should have been made at the point of low-level creation of this thread, which should have happened prior to us getting this client request for it. That's because this client request is sent from client-world from the 'thread_wrapper' function, which only runs once the thread has been low-level created. */ tl_assert(my_thr != NULL); /* So now we know that (pthread_t)args[1] is associated with (Thread*)my_thr. Note that down. */ if (0) VG_(printf)("XXXX: bind pthread_t %p to Thread* %p\n", (void*)args[1], (void*)my_thr ); VG_(addToFM)( map_pthread_t_to_Thread, (Word)args[1], (Word)my_thr ); break; } case _VG_USERREQ__HG_PTH_API_ERROR: { Thread* my_thr = NULL; map_pthread_t_to_Thread_INIT(); my_thr = map_threads_maybe_lookup( tid ); tl_assert(my_thr); /* See justification above in SET_MY_PTHREAD_T */ HG_(record_error_PthAPIerror)( my_thr, (HChar*)args[1], (Word)args[2], (HChar*)args[3] ); break; } /* This thread (tid) has completed a join with the quitting thread whose pthread_t is in args[1]. */ case _VG_USERREQ__HG_PTHREAD_JOIN_POST: { Thread* thr_q = NULL; /* quitter Thread* */ Bool found = False; if (0) VG_(printf)("NOTIFY_JOIN_COMPLETE (tid %d): quitter = %p\n", (Int)tid, (void*)args[1]); map_pthread_t_to_Thread_INIT(); found = VG_(lookupFM)( map_pthread_t_to_Thread, NULL, (Word*)&thr_q, (Word)args[1] ); /* Can this fail? It would mean that our pthread_join wrapper observed a successful join on args[1] yet that thread never existed (or at least, it never lodged an entry in the mapping (via SET_MY_PTHREAD_T)). Which sounds like a bug in the threads library. */ // FIXME: get rid of this assertion; handle properly tl_assert(found); if (found) { if (0) VG_(printf)(".................... quitter Thread* = %p\n", thr_q); evh__HG_PTHREAD_JOIN_POST( tid, thr_q ); } break; } /* EXPOSITION only: by intercepting lock init events we can show the user where the lock was initialised, rather than only being able to show where it was first locked. Intercepting lock initialisations is not necessary for the basic operation of the race checker. */ case _VG_USERREQ__HG_PTHREAD_MUTEX_INIT_POST: evh__HG_PTHREAD_MUTEX_INIT_POST( tid, (void*)args[1], args[2] ); break; case _VG_USERREQ__HG_PTHREAD_MUTEX_DESTROY_PRE: evh__HG_PTHREAD_MUTEX_DESTROY_PRE( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_PTHREAD_MUTEX_UNLOCK_PRE: // pth_mx_t* evh__HG_PTHREAD_MUTEX_UNLOCK_PRE( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_PTHREAD_MUTEX_UNLOCK_POST: // pth_mx_t* evh__HG_PTHREAD_MUTEX_UNLOCK_POST( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_PTHREAD_MUTEX_LOCK_PRE: // pth_mx_t*, Word evh__HG_PTHREAD_MUTEX_LOCK_PRE( tid, (void*)args[1], args[2] ); break; case _VG_USERREQ__HG_PTHREAD_MUTEX_LOCK_POST: // pth_mx_t* evh__HG_PTHREAD_MUTEX_LOCK_POST( tid, (void*)args[1] ); break; /* This thread is about to do pthread_cond_signal on the pthread_cond_t* in arg[1]. Ditto pthread_cond_broadcast. */ case _VG_USERREQ__HG_PTHREAD_COND_SIGNAL_PRE: case _VG_USERREQ__HG_PTHREAD_COND_BROADCAST_PRE: evh__HG_PTHREAD_COND_SIGNAL_PRE( tid, (void*)args[1] ); break; /* Entry into pthread_cond_wait, cond=arg[1], mutex=arg[2]. Returns a flag indicating whether or not the mutex is believed to be valid for this operation. */ case _VG_USERREQ__HG_PTHREAD_COND_WAIT_PRE: { Bool mutex_is_valid = evh__HG_PTHREAD_COND_WAIT_PRE( tid, (void*)args[1], (void*)args[2] ); *ret = mutex_is_valid ? 1 : 0; break; } /* cond=arg[1] */ case _VG_USERREQ__HG_PTHREAD_COND_DESTROY_PRE: evh__HG_PTHREAD_COND_DESTROY_PRE( tid, (void*)args[1] ); break; /* Thread successfully completed pthread_cond_wait, cond=arg[1], mutex=arg[2] */ case _VG_USERREQ__HG_PTHREAD_COND_WAIT_POST: evh__HG_PTHREAD_COND_WAIT_POST( tid, (void*)args[1], (void*)args[2] ); break; case _VG_USERREQ__HG_PTHREAD_RWLOCK_INIT_POST: evh__HG_PTHREAD_RWLOCK_INIT_POST( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_PTHREAD_RWLOCK_DESTROY_PRE: evh__HG_PTHREAD_RWLOCK_DESTROY_PRE( tid, (void*)args[1] ); break; /* rwlock=arg[1], isW=arg[2], isTryLock=arg[3] */ case _VG_USERREQ__HG_PTHREAD_RWLOCK_LOCK_PRE: evh__HG_PTHREAD_RWLOCK_LOCK_PRE( tid, (void*)args[1], args[2], args[3] ); break; /* rwlock=arg[1], isW=arg[2] */ case _VG_USERREQ__HG_PTHREAD_RWLOCK_LOCK_POST: evh__HG_PTHREAD_RWLOCK_LOCK_POST( tid, (void*)args[1], args[2] ); break; case _VG_USERREQ__HG_PTHREAD_RWLOCK_UNLOCK_PRE: evh__HG_PTHREAD_RWLOCK_UNLOCK_PRE( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_PTHREAD_RWLOCK_UNLOCK_POST: evh__HG_PTHREAD_RWLOCK_UNLOCK_POST( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_POSIX_SEM_INIT_POST: /* sem_t*, unsigned long */ evh__HG_POSIX_SEM_INIT_POST( tid, (void*)args[1], args[2] ); break; case _VG_USERREQ__HG_POSIX_SEM_DESTROY_PRE: /* sem_t* */ evh__HG_POSIX_SEM_DESTROY_PRE( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_POSIX_SEM_POST_PRE: /* sem_t* */ evh__HG_POSIX_SEM_POST_PRE( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_POSIX_SEM_WAIT_POST: /* sem_t* */ evh__HG_POSIX_SEM_WAIT_POST( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_PTHREAD_BARRIER_INIT_PRE: /* pth_bar_t*, ulong count, ulong resizable */ evh__HG_PTHREAD_BARRIER_INIT_PRE( tid, (void*)args[1], args[2], args[3] ); break; case _VG_USERREQ__HG_PTHREAD_BARRIER_RESIZE_PRE: /* pth_bar_t*, ulong newcount */ evh__HG_PTHREAD_BARRIER_RESIZE_PRE ( tid, (void*)args[1], args[2] ); break; case _VG_USERREQ__HG_PTHREAD_BARRIER_WAIT_PRE: /* pth_bar_t* */ evh__HG_PTHREAD_BARRIER_WAIT_PRE( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_PTHREAD_BARRIER_DESTROY_PRE: /* pth_bar_t* */ evh__HG_PTHREAD_BARRIER_DESTROY_PRE( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_PTHREAD_SPIN_INIT_OR_UNLOCK_PRE: /* pth_spinlock_t* */ evh__HG_PTHREAD_SPIN_INIT_OR_UNLOCK_PRE( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_PTHREAD_SPIN_INIT_OR_UNLOCK_POST: /* pth_spinlock_t* */ evh__HG_PTHREAD_SPIN_INIT_OR_UNLOCK_POST( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_PTHREAD_SPIN_LOCK_PRE: /* pth_spinlock_t*, Word */ evh__HG_PTHREAD_SPIN_LOCK_PRE( tid, (void*)args[1], args[2] ); break; case _VG_USERREQ__HG_PTHREAD_SPIN_LOCK_POST: /* pth_spinlock_t* */ evh__HG_PTHREAD_SPIN_LOCK_POST( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_PTHREAD_SPIN_DESTROY_PRE: /* pth_spinlock_t* */ evh__HG_PTHREAD_SPIN_DESTROY_PRE( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_CLIENTREQ_UNIMP: { /* char* who */ HChar* who = (HChar*)args[1]; HChar buf[50 + 50]; Thread* thr = map_threads_maybe_lookup( tid ); tl_assert( thr ); /* I must be mapped */ tl_assert( who ); tl_assert( VG_(strlen)(who) <= 50 ); VG_(sprintf)(buf, "Unimplemented client request macro \"%s\"", who ); /* record_error_Misc strdup's buf, so this is safe: */ HG_(record_error_Misc)( thr, buf ); break; } case _VG_USERREQ__HG_USERSO_SEND_PRE: /* UWord arbitrary-SO-tag */ evh__HG_USERSO_SEND_PRE( tid, args[1] ); break; case _VG_USERREQ__HG_USERSO_RECV_POST: /* UWord arbitrary-SO-tag */ evh__HG_USERSO_RECV_POST( tid, args[1] ); break; default: /* Unhandled Helgrind client request! */ tl_assert2(0, "unhandled Helgrind client request 0x%lx", args[0]); } return True; } /*----------------------------------------------------------------*/ /*--- Setup ---*/ /*----------------------------------------------------------------*/ static Bool hg_process_cmd_line_option ( Char* arg ) { Char* tmp_str; if VG_BOOL_CLO(arg, "--track-lockorders", HG_(clo_track_lockorders)) {} else if VG_BOOL_CLO(arg, "--cmp-race-err-addrs", HG_(clo_cmp_race_err_addrs)) {} else if VG_XACT_CLO(arg, "--history-level=none", HG_(clo_history_level), 0); else if VG_XACT_CLO(arg, "--history-level=approx", HG_(clo_history_level), 1); else if VG_XACT_CLO(arg, "--history-level=full", HG_(clo_history_level), 2); /* If you change the 10k/30mill limits, remember to also change them in assertions at the top of event_map_maybe_GC. */ else if VG_BINT_CLO(arg, "--conflict-cache-size", HG_(clo_conflict_cache_size), 10*1000, 30*1000*1000) {} /* "stuvwx" --> stuvwx (binary) */ else if VG_STR_CLO(arg, "--hg-sanity-flags", tmp_str) { Int j; if (6 != VG_(strlen)(tmp_str)) { VG_(message)(Vg_UserMsg, "--hg-sanity-flags argument must have 6 digits\n"); return False; } for (j = 0; j < 6; j++) { if ('0' == tmp_str[j]) { /* do nothing */ } else if ('1' == tmp_str[j]) HG_(clo_sanity_flags) |= (1 << (6-1-j)); else { VG_(message)(Vg_UserMsg, "--hg-sanity-flags argument can " "only contain 0s and 1s\n"); return False; } } if (0) VG_(printf)("XXX sanity flags: 0x%lx\n", HG_(clo_sanity_flags)); } else return VG_(replacement_malloc_process_cmd_line_option)(arg); return True; } static void hg_print_usage ( void ) { VG_(printf)( " --track-lockorders=no|yes show lock ordering errors? [yes]\n" " --history-level=none|approx|full [full]\n" " full: show both stack traces for a data race (can be very slow)\n" " approx: full trace for one thread, approx for the other (faster)\n" " none: only show trace for one thread in a race (fastest)\n" " --conflict-cache-size=N size of 'full' history cache [1000000]\n" ); } static void hg_print_debug_usage ( void ) { VG_(printf)(" --cmp-race-err-addrs=no|yes are data addresses in " "race errors significant? [no]\n"); VG_(printf)(" --hg-sanity-flags=<XXXXXX> sanity check " " at events (X = 0|1) [000000]\n"); VG_(printf)(" --hg-sanity-flags values:\n"); VG_(printf)(" 010000 after changes to " "lock-order-acquisition-graph\n"); VG_(printf)(" 001000 at memory accesses (NB: not currently used)\n"); VG_(printf)(" 000100 at mem permission setting for " "ranges >= %d bytes\n", SCE_BIGRANGE_T); VG_(printf)(" 000010 at lock/unlock events\n"); VG_(printf)(" 000001 at thread create/join events\n"); } static void hg_fini ( Int exitcode ) { if (VG_(clo_verbosity) == 1 && !VG_(clo_xml)) { VG_(message)(Vg_UserMsg, "For counts of detected and suppressed errors, " "rerun with: -v\n"); } if (VG_(clo_verbosity) == 1 && !VG_(clo_xml) && HG_(clo_history_level) >= 2) { VG_(umsg)( "Use --history-level=approx or =none to gain increased speed, at\n" ); VG_(umsg)( "the cost of reduced accuracy of conflicting-access information\n"); } if (SHOW_DATA_STRUCTURES) pp_everything( PP_ALL, "SK_(fini)" ); if (HG_(clo_sanity_flags)) all__sanity_check("SK_(fini)"); if (VG_(clo_stats)) { if (1) { VG_(printf)("\n"); HG_(ppWSUstats)( univ_lsets, "univ_lsets" ); if (HG_(clo_track_lockorders)) { VG_(printf)("\n"); HG_(ppWSUstats)( univ_laog, "univ_laog" ); } } //zz VG_(printf)("\n"); //zz VG_(printf)(" hbefore: %'10lu queries\n", stats__hbefore_queries); //zz VG_(printf)(" hbefore: %'10lu cache 0 hits\n", stats__hbefore_cache0s); //zz VG_(printf)(" hbefore: %'10lu cache > 0 hits\n", stats__hbefore_cacheNs); //zz VG_(printf)(" hbefore: %'10lu graph searches\n", stats__hbefore_gsearches); //zz VG_(printf)(" hbefore: %'10lu of which slow\n", //zz stats__hbefore_gsearches - stats__hbefore_gsearchFs); //zz VG_(printf)(" hbefore: %'10lu stack high water mark\n", //zz stats__hbefore_stk_hwm); //zz VG_(printf)(" hbefore: %'10lu cache invals\n", stats__hbefore_invals); //zz VG_(printf)(" hbefore: %'10lu probes\n", stats__hbefore_probes); VG_(printf)("\n"); VG_(printf)(" locksets: %'8d unique lock sets\n", (Int)HG_(cardinalityWSU)( univ_lsets )); if (HG_(clo_track_lockorders)) { VG_(printf)(" univ_laog: %'8d unique lock sets\n", (Int)HG_(cardinalityWSU)( univ_laog )); } //VG_(printf)("L(ast)L(ock) map: %'8lu inserts (%d map size)\n", // stats__ga_LL_adds, // (Int)(ga_to_lastlock ? VG_(sizeFM)( ga_to_lastlock ) : 0) ); VG_(printf)(" LockN-to-P map: %'8llu queries (%llu map size)\n", HG_(stats__LockN_to_P_queries), HG_(stats__LockN_to_P_get_map_size)() ); VG_(printf)("string table map: %'8llu queries (%llu map size)\n", HG_(stats__string_table_queries), HG_(stats__string_table_get_map_size)() ); if (HG_(clo_track_lockorders)) { VG_(printf)(" LAOG: %'8d map size\n", (Int)(laog ? VG_(sizeFM)( laog ) : 0)); VG_(printf)(" LAOG exposition: %'8d map size\n", (Int)(laog_exposition ? VG_(sizeFM)( laog_exposition ) : 0)); } VG_(printf)(" locks: %'8lu acquires, " "%'lu releases\n", stats__lockN_acquires, stats__lockN_releases ); VG_(printf)(" sanity checks: %'8lu\n", stats__sanity_checks); VG_(printf)("\n"); libhb_shutdown(True); } } /* FIXME: move these somewhere sane */ static void for_libhb__get_stacktrace ( Thr* hbt, Addr* frames, UWord nRequest ) { Thread* thr; ThreadId tid; UWord nActual; tl_assert(hbt); thr = libhb_get_Thr_hgthread( hbt ); tl_assert(thr); tid = map_threads_maybe_reverse_lookup_SLOW(thr); nActual = (UWord)VG_(get_StackTrace)( tid, frames, (UInt)nRequest, NULL, NULL, 0 ); tl_assert(nActual <= nRequest); for (; nActual < nRequest; nActual++) frames[nActual] = 0; } static ExeContext* for_libhb__get_EC ( Thr* hbt ) { Thread* thr; ThreadId tid; ExeContext* ec; tl_assert(hbt); thr = libhb_get_Thr_hgthread( hbt ); tl_assert(thr); tid = map_threads_maybe_reverse_lookup_SLOW(thr); /* this will assert if tid is invalid */ ec = VG_(record_ExeContext)( tid, 0 ); return ec; } static void hg_post_clo_init ( void ) { Thr* hbthr_root; ///////////////////////////////////////////// hbthr_root = libhb_init( for_libhb__get_stacktrace, for_libhb__get_EC ); ///////////////////////////////////////////// if (HG_(clo_track_lockorders)) laog__init(); initialise_data_structures(hbthr_root); } static void hg_pre_clo_init ( void ) { VG_(details_name) ("Helgrind"); VG_(details_version) (NULL); VG_(details_description) ("a thread error detector"); VG_(details_copyright_author)( "Copyright (C) 2007-2010, and GNU GPL'd, by OpenWorks LLP et al."); VG_(details_bug_reports_to) (VG_BUGS_TO); VG_(details_avg_translation_sizeB) ( 320 ); VG_(basic_tool_funcs) (hg_post_clo_init, hg_instrument, hg_fini); VG_(needs_core_errors) (); VG_(needs_tool_errors) (HG_(eq_Error), HG_(before_pp_Error), HG_(pp_Error), False,/*show TIDs for errors*/ HG_(update_extra), HG_(recognised_suppression), HG_(read_extra_suppression_info), HG_(error_matches_suppression), HG_(get_error_name), HG_(get_extra_suppression_info)); VG_(needs_xml_output) (); VG_(needs_command_line_options)(hg_process_cmd_line_option, hg_print_usage, hg_print_debug_usage); VG_(needs_client_requests) (hg_handle_client_request); // FIXME? //VG_(needs_sanity_checks) (hg_cheap_sanity_check, // hg_expensive_sanity_check); VG_(needs_malloc_replacement) (hg_cli__malloc, hg_cli____builtin_new, hg_cli____builtin_vec_new, hg_cli__memalign, hg_cli__calloc, hg_cli__free, hg_cli____builtin_delete, hg_cli____builtin_vec_delete, hg_cli__realloc, hg_cli_malloc_usable_size, HG_CLI__MALLOC_REDZONE_SZB ); /* 21 Dec 08: disabled this; it mostly causes H to start more slowly and use significantly more memory, without very often providing useful results. The user can request to load this information manually with --read-var-info=yes. */ if (0) VG_(needs_var_info)(); /* optional */ VG_(track_new_mem_startup) ( evh__new_mem_w_perms ); VG_(track_new_mem_stack_signal)( evh__new_mem_w_tid ); VG_(track_new_mem_brk) ( evh__new_mem_w_tid ); VG_(track_new_mem_mmap) ( evh__new_mem_w_perms ); VG_(track_new_mem_stack) ( evh__new_mem_stack ); // FIXME: surely this isn't thread-aware VG_(track_copy_mem_remap) ( evh__copy_mem ); VG_(track_change_mem_mprotect) ( evh__set_perms ); VG_(track_die_mem_stack_signal)( evh__die_mem ); VG_(track_die_mem_brk) ( evh__die_mem ); VG_(track_die_mem_munmap) ( evh__die_mem ); VG_(track_die_mem_stack) ( evh__die_mem ); // FIXME: what is this for? VG_(track_ban_mem_stack) (NULL); VG_(track_pre_mem_read) ( evh__pre_mem_read ); VG_(track_pre_mem_read_asciiz) ( evh__pre_mem_read_asciiz ); VG_(track_pre_mem_write) ( evh__pre_mem_write ); VG_(track_post_mem_write) (NULL); ///////////////// VG_(track_pre_thread_ll_create)( evh__pre_thread_ll_create ); VG_(track_pre_thread_ll_exit) ( evh__pre_thread_ll_exit ); VG_(track_start_client_code)( evh__start_client_code ); VG_(track_stop_client_code)( evh__stop_client_code ); /* Ensure that requirements for "dodgy C-as-C++ style inheritance" as described in comments at the top of pub_tool_hashtable.h, are met. Blargh. */ tl_assert( sizeof(void*) == sizeof(struct _MallocMeta*) ); tl_assert( sizeof(UWord) == sizeof(Addr) ); hg_mallocmeta_table = VG_(HT_construct)( "hg_malloc_metadata_table" ); // add a callback to clean up on (threaded) fork. VG_(atfork)(NULL/*pre*/, NULL/*parent*/, evh__atfork_child/*child*/); } VG_DETERMINE_INTERFACE_VERSION(hg_pre_clo_init) /*--------------------------------------------------------------------*/ /*--- end hg_main.c ---*/ /*--------------------------------------------------------------------*/ /*--------------------------------------------------------------------*/ /*--- Helgrind: a Valgrind tool for detecting errors ---*/ /*--- in threaded programs. hg_main.c ---*/ /*--------------------------------------------------------------------*/ /* This file is part of Helgrind, a Valgrind tool for detecting errors in threaded programs. Copyright (C) 2007-2010 OpenWorks LLP [email protected] Copyright (C) 2007-2010 Apple, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. The GNU General Public License is contained in the file COPYING. Neither the names of the U.S. Department of Energy nor the University of California nor the names of its contributors may be used to endorse or promote products derived from this software without prior written permission. */ #include "pub_tool_basics.h" #include "pub_tool_libcassert.h" #include "pub_tool_libcbase.h" #include "pub_tool_libcprint.h" #include "pub_tool_threadstate.h" #include "pub_tool_tooliface.h" #include "pub_tool_hashtable.h" #include "pub_tool_replacemalloc.h" #include "pub_tool_machine.h" #include "pub_tool_options.h" #include "pub_tool_xarray.h" #include "pub_tool_stacktrace.h" #include "pub_tool_wordfm.h" #include "pub_tool_debuginfo.h" // VG_(find_seginfo), VG_(seginfo_soname) #include "pub_tool_redir.h" // sonames for the dynamic linkers #include "pub_tool_vki.h" // VKI_PAGE_SIZE #include "pub_tool_libcproc.h" // VG_(atfork) #include "pub_tool_aspacemgr.h" // VG_(am_is_valid_for_client) #include "hg_basics.h" #include "hg_wordset.h" #include "hg_lock_n_thread.h" #include "hg_errors.h" #include "libhb.h" #include "helgrind.h" // FIXME: new_mem_w_tid ignores the supplied tid. (wtf?!) // FIXME: when client destroys a lock or a CV, remove these // from our mappings, so that the associated SO can be freed up /*----------------------------------------------------------------*/ /*--- ---*/ /*----------------------------------------------------------------*/ /* Note this needs to be compiled with -fno-strict-aliasing, since it contains a whole bunch of calls to lookupFM etc which cast between Word and pointer types. gcc rightly complains this breaks ANSI C strict aliasing rules, at -O2. No complaints at -O, but -O2 gives worthwhile performance benefits over -O. */ // FIXME what is supposed to happen to locks in memory which // is relocated as a result of client realloc? // FIXME put referencing ThreadId into Thread and get // rid of the slow reverse mapping function. // FIXME accesses to NoAccess areas: change state to Excl? // FIXME report errors for accesses of NoAccess memory? // FIXME pth_cond_wait/timedwait wrappers. Even if these fail, // the thread still holds the lock. /* ------------ Debug/trace options ------------ */ // 0 for silent, 1 for some stuff, 2 for lots of stuff #define SHOW_EVENTS 0 static void all__sanity_check ( Char* who ); /* fwds */ #define HG_CLI__MALLOC_REDZONE_SZB 16 /* let's say */ // 0 for none, 1 for dump at end of run #define SHOW_DATA_STRUCTURES 0 /* ------------ Misc comments ------------ */ // FIXME: don't hardwire initial entries for root thread. // Instead, let the pre_thread_ll_create handler do this. /*----------------------------------------------------------------*/ /*--- Primary data structures ---*/ /*----------------------------------------------------------------*/ /* Admin linked list of Threads */ static Thread* admin_threads = NULL; /* Admin double linked list of Locks */ /* We need a double linked list to properly and efficiently handle del_LockN. */ static Lock* admin_locks = NULL; /* Mapping table for core ThreadIds to Thread* */ static Thread** map_threads = NULL; /* Array[VG_N_THREADS] of Thread* */ /* Mapping table for lock guest addresses to Lock* */ static WordFM* map_locks = NULL; /* WordFM LockAddr Lock* */ /* The word-set universes for lock sets. */ static WordSetU* univ_lsets = NULL; /* sets of Lock* */ static WordSetU* univ_laog = NULL; /* sets of Lock*, for LAOG */ /*----------------------------------------------------------------*/ /*--- Simple helpers for the data structures ---*/ /*----------------------------------------------------------------*/ static UWord stats__lockN_acquires = 0; static UWord stats__lockN_releases = 0; static ThreadId map_threads_maybe_reverse_lookup_SLOW ( Thread* thr ); /*fwds*/ /* --------- Constructors --------- */ static Thread* mk_Thread ( Thr* hbthr ) { static Int indx = 1; Thread* thread = HG_(zalloc)( "hg.mk_Thread.1", sizeof(Thread) ); thread->locksetA = HG_(emptyWS)( univ_lsets ); thread->locksetW = HG_(emptyWS)( univ_lsets ); thread->magic = Thread_MAGIC; thread->hbthr = hbthr; thread->coretid = VG_INVALID_THREADID; thread->created_at = NULL; thread->announced = False; thread->errmsg_index = indx++; thread->admin = admin_threads; admin_threads = thread; return thread; } // Make a new lock which is unlocked (hence ownerless) // and insert the new lock in admin_locks double linked list. static Lock* mk_LockN ( LockKind kind, Addr guestaddr ) { static ULong unique = 0; Lock* lock = HG_(zalloc)( "hg.mk_Lock.1", sizeof(Lock) ); /* begin: add to double linked list */ if (admin_locks) admin_locks->admin_prev = lock; lock->admin_next = admin_locks; lock->admin_prev = NULL; admin_locks = lock; /* end: add */ lock->unique = unique++; lock->magic = LockN_MAGIC; lock->appeared_at = NULL; lock->acquired_at = NULL; lock->hbso = libhb_so_alloc(); lock->guestaddr = guestaddr; lock->kind = kind; lock->heldW = False; lock->heldBy = NULL; tl_assert(HG_(is_sane_LockN)(lock)); return lock; } /* Release storage for a Lock. Also release storage in .heldBy, if any. Removes from admin_locks double linked list. */ static void del_LockN ( Lock* lk ) { tl_assert(HG_(is_sane_LockN)(lk)); tl_assert(lk->hbso); libhb_so_dealloc(lk->hbso); if (lk->heldBy) VG_(deleteBag)( lk->heldBy ); /* begin: del lock from double linked list */ if (lk == admin_locks) { tl_assert(lk->admin_prev == NULL); if (lk->admin_next) lk->admin_next->admin_prev = NULL; admin_locks = lk->admin_next; } else { tl_assert(lk->admin_prev != NULL); lk->admin_prev->admin_next = lk->admin_next; if (lk->admin_next) lk->admin_next->admin_prev = lk->admin_prev; } /* end: del */ VG_(memset)(lk, 0xAA, sizeof(*lk)); HG_(free)(lk); } /* Update 'lk' to reflect that 'thr' now has a write-acquisition of it. This is done strictly: only combinations resulting from correct program and libpthread behaviour are allowed. */ static void lockN_acquire_writer ( Lock* lk, Thread* thr ) { tl_assert(HG_(is_sane_LockN)(lk)); tl_assert(HG_(is_sane_Thread)(thr)); stats__lockN_acquires++; /* EXPOSITION only */ /* We need to keep recording snapshots of where the lock was acquired, so as to produce better lock-order error messages. */ if (lk->acquired_at == NULL) { ThreadId tid; tl_assert(lk->heldBy == NULL); tid = map_threads_maybe_reverse_lookup_SLOW(thr); lk->acquired_at = VG_(record_ExeContext)(tid, 0/*first_ip_delta*/); } else { tl_assert(lk->heldBy != NULL); } /* end EXPOSITION only */ switch (lk->kind) { case LK_nonRec: case_LK_nonRec: tl_assert(lk->heldBy == NULL); /* can't w-lock recursively */ tl_assert(!lk->heldW); lk->heldW = True; lk->heldBy = VG_(newBag)( HG_(zalloc), "hg.lNaw.1", HG_(free) ); VG_(addToBag)( lk->heldBy, (Word)thr ); break; case LK_mbRec: if (lk->heldBy == NULL) goto case_LK_nonRec; /* 2nd and subsequent locking of a lock by its owner */ tl_assert(lk->heldW); /* assert: lk is only held by one thread .. */ tl_assert(VG_(sizeUniqueBag(lk->heldBy)) == 1); /* assert: .. and that thread is 'thr'. */ tl_assert(VG_(elemBag)(lk->heldBy, (Word)thr) == VG_(sizeTotalBag)(lk->heldBy)); VG_(addToBag)(lk->heldBy, (Word)thr); break; case LK_rdwr: tl_assert(lk->heldBy == NULL && !lk->heldW); /* must be unheld */ goto case_LK_nonRec; default: tl_assert(0); } tl_assert(HG_(is_sane_LockN)(lk)); } static void lockN_acquire_reader ( Lock* lk, Thread* thr ) { tl_assert(HG_(is_sane_LockN)(lk)); tl_assert(HG_(is_sane_Thread)(thr)); /* can only add reader to a reader-writer lock. */ tl_assert(lk->kind == LK_rdwr); /* lk must be free or already r-held. */ tl_assert(lk->heldBy == NULL || (lk->heldBy != NULL && !lk->heldW)); stats__lockN_acquires++; /* EXPOSITION only */ /* We need to keep recording snapshots of where the lock was acquired, so as to produce better lock-order error messages. */ if (lk->acquired_at == NULL) { ThreadId tid; tl_assert(lk->heldBy == NULL); tid = map_threads_maybe_reverse_lookup_SLOW(thr); lk->acquired_at = VG_(record_ExeContext)(tid, 0/*first_ip_delta*/); } else { tl_assert(lk->heldBy != NULL); } /* end EXPOSITION only */ if (lk->heldBy) { VG_(addToBag)(lk->heldBy, (Word)thr); } else { lk->heldW = False; lk->heldBy = VG_(newBag)( HG_(zalloc), "hg.lNar.1", HG_(free) ); VG_(addToBag)( lk->heldBy, (Word)thr ); } tl_assert(!lk->heldW); tl_assert(HG_(is_sane_LockN)(lk)); } /* Update 'lk' to reflect a release of it by 'thr'. This is done strictly: only combinations resulting from correct program and libpthread behaviour are allowed. */ static void lockN_release ( Lock* lk, Thread* thr ) { Bool b; tl_assert(HG_(is_sane_LockN)(lk)); tl_assert(HG_(is_sane_Thread)(thr)); /* lock must be held by someone */ tl_assert(lk->heldBy); stats__lockN_releases++; /* Remove it from the holder set */ b = VG_(delFromBag)(lk->heldBy, (Word)thr); /* thr must actually have been a holder of lk */ tl_assert(b); /* normalise */ tl_assert(lk->acquired_at); if (VG_(isEmptyBag)(lk->heldBy)) { VG_(deleteBag)(lk->heldBy); lk->heldBy = NULL; lk->heldW = False; lk->acquired_at = NULL; } tl_assert(HG_(is_sane_LockN)(lk)); } static void remove_Lock_from_locksets_of_all_owning_Threads( Lock* lk ) { Thread* thr; if (!lk->heldBy) { tl_assert(!lk->heldW); return; } /* for each thread that holds this lock do ... */ VG_(initIterBag)( lk->heldBy ); while (VG_(nextIterBag)( lk->heldBy, (Word*)&thr, NULL )) { tl_assert(HG_(is_sane_Thread)(thr)); tl_assert(HG_(elemWS)( univ_lsets, thr->locksetA, (Word)lk )); thr->locksetA = HG_(delFromWS)( univ_lsets, thr->locksetA, (Word)lk ); if (lk->heldW) { tl_assert(HG_(elemWS)( univ_lsets, thr->locksetW, (Word)lk )); thr->locksetW = HG_(delFromWS)( univ_lsets, thr->locksetW, (Word)lk ); } } VG_(doneIterBag)( lk->heldBy ); } /*----------------------------------------------------------------*/ /*--- Print out the primary data structures ---*/ /*----------------------------------------------------------------*/ #define PP_THREADS (1<<1) #define PP_LOCKS (1<<2) #define PP_ALL (PP_THREADS | PP_LOCKS) static const Int sHOW_ADMIN = 0; static void space ( Int n ) { Int i; Char spaces[128+1]; tl_assert(n >= 0 && n < 128); if (n == 0) return; for (i = 0; i < n; i++) spaces[i] = ' '; spaces[i] = 0; tl_assert(i < 128+1); VG_(printf)("%s", spaces); } static void pp_Thread ( Int d, Thread* t ) { space(d+0); VG_(printf)("Thread %p {\n", t); if (sHOW_ADMIN) { space(d+3); VG_(printf)("admin %p\n", t->admin); space(d+3); VG_(printf)("magic 0x%x\n", (UInt)t->magic); } space(d+3); VG_(printf)("locksetA %d\n", (Int)t->locksetA); space(d+3); VG_(printf)("locksetW %d\n", (Int)t->locksetW); space(d+0); VG_(printf)("}\n"); } static void pp_admin_threads ( Int d ) { Int i, n; Thread* t; for (n = 0, t = admin_threads; t; n++, t = t->admin) { /* nothing */ } space(d); VG_(printf)("admin_threads (%d records) {\n", n); for (i = 0, t = admin_threads; t; i++, t = t->admin) { if (0) { space(n); VG_(printf)("admin_threads record %d of %d:\n", i, n); } pp_Thread(d+3, t); } space(d); VG_(printf)("}\n"); } static void pp_map_threads ( Int d ) { Int i, n = 0; space(d); VG_(printf)("map_threads "); for (i = 0; i < VG_N_THREADS; i++) { if (map_threads[i] != NULL) n++; } VG_(printf)("(%d entries) {\n", n); for (i = 0; i < VG_N_THREADS; i++) { if (map_threads[i] == NULL) continue; space(d+3); VG_(printf)("coretid %d -> Thread %p\n", i, map_threads[i]); } space(d); VG_(printf)("}\n"); } static const HChar* show_LockKind ( LockKind lkk ) { switch (lkk) { case LK_mbRec: return "mbRec"; case LK_nonRec: return "nonRec"; case LK_rdwr: return "rdwr"; default: tl_assert(0); } } static void pp_Lock ( Int d, Lock* lk ) { space(d+0); VG_(printf)("Lock %p (ga %#lx) {\n", lk, lk->guestaddr); if (sHOW_ADMIN) { space(d+3); VG_(printf)("admin_n %p\n", lk->admin_next); space(d+3); VG_(printf)("admin_p %p\n", lk->admin_prev); space(d+3); VG_(printf)("magic 0x%x\n", (UInt)lk->magic); } space(d+3); VG_(printf)("unique %llu\n", lk->unique); space(d+3); VG_(printf)("kind %s\n", show_LockKind(lk->kind)); space(d+3); VG_(printf)("heldW %s\n", lk->heldW ? "yes" : "no"); space(d+3); VG_(printf)("heldBy %p", lk->heldBy); if (lk->heldBy) { Thread* thr; Word count; VG_(printf)(" { "); VG_(initIterBag)( lk->heldBy ); while (VG_(nextIterBag)( lk->heldBy, (Word*)&thr, &count )) VG_(printf)("%lu:%p ", count, thr); VG_(doneIterBag)( lk->heldBy ); VG_(printf)("}"); } VG_(printf)("\n"); space(d+0); VG_(printf)("}\n"); } static void pp_admin_locks ( Int d ) { Int i, n; Lock* lk; for (n = 0, lk = admin_locks; lk; n++, lk = lk->admin_next) { /* nothing */ } space(d); VG_(printf)("admin_locks (%d records) {\n", n); for (i = 0, lk = admin_locks; lk; i++, lk = lk->admin_next) { if (0) { space(n); VG_(printf)("admin_locks record %d of %d:\n", i, n); } pp_Lock(d+3, lk); } space(d); VG_(printf)("}\n"); } static void pp_map_locks ( Int d ) { void* gla; Lock* lk; space(d); VG_(printf)("map_locks (%d entries) {\n", (Int)VG_(sizeFM)( map_locks )); VG_(initIterFM)( map_locks ); while (VG_(nextIterFM)( map_locks, (Word*)&gla, (Word*)&lk )) { space(d+3); VG_(printf)("guest %p -> Lock %p\n", gla, lk); } VG_(doneIterFM)( map_locks ); space(d); VG_(printf)("}\n"); } static void pp_everything ( Int flags, Char* caller ) { Int d = 0; VG_(printf)("\n"); VG_(printf)("All_Data_Structures (caller = \"%s\") {\n", caller); if (flags & PP_THREADS) { VG_(printf)("\n"); pp_admin_threads(d+3); VG_(printf)("\n"); pp_map_threads(d+3); } if (flags & PP_LOCKS) { VG_(printf)("\n"); pp_admin_locks(d+3); VG_(printf)("\n"); pp_map_locks(d+3); } VG_(printf)("\n"); VG_(printf)("}\n"); VG_(printf)("\n"); } #undef SHOW_ADMIN /*----------------------------------------------------------------*/ /*--- Initialise the primary data structures ---*/ /*----------------------------------------------------------------*/ static void initialise_data_structures ( Thr* hbthr_root ) { Thread* thr; /* Get everything initialised and zeroed. */ tl_assert(admin_threads == NULL); tl_assert(admin_locks == NULL); tl_assert(sizeof(Addr) == sizeof(Word)); tl_assert(map_threads == NULL); map_threads = HG_(zalloc)( "hg.ids.1", VG_N_THREADS * sizeof(Thread*) ); tl_assert(map_threads != NULL); tl_assert(sizeof(Addr) == sizeof(Word)); tl_assert(map_locks == NULL); map_locks = VG_(newFM)( HG_(zalloc), "hg.ids.2", HG_(free), NULL/*unboxed Word cmp*/); tl_assert(map_locks != NULL); tl_assert(univ_lsets == NULL); univ_lsets = HG_(newWordSetU)( HG_(zalloc), "hg.ids.4", HG_(free), 8/*cacheSize*/ ); tl_assert(univ_lsets != NULL); tl_assert(univ_laog == NULL); if (HG_(clo_track_lockorders)) { univ_laog = HG_(newWordSetU)( HG_(zalloc), "hg.ids.5 (univ_laog)", HG_(free), 24/*cacheSize*/ ); tl_assert(univ_laog != NULL); } /* Set up entries for the root thread */ // FIXME: this assumes that the first real ThreadId is 1 /* a Thread for the new thread ... */ thr = mk_Thread(hbthr_root); thr->coretid = 1; /* FIXME: hardwires an assumption about the identity of the root thread. */ tl_assert( libhb_get_Thr_hgthread(hbthr_root) == NULL ); libhb_set_Thr_hgthread(hbthr_root, thr); /* and bind it in the thread-map table. */ tl_assert(HG_(is_sane_ThreadId)(thr->coretid)); tl_assert(thr->coretid != VG_INVALID_THREADID); map_threads[thr->coretid] = thr; tl_assert(VG_INVALID_THREADID == 0); all__sanity_check("initialise_data_structures"); } /*----------------------------------------------------------------*/ /*--- map_threads :: array[core-ThreadId] of Thread* ---*/ /*----------------------------------------------------------------*/ /* Doesn't assert if the relevant map_threads entry is NULL. */ static Thread* map_threads_maybe_lookup ( ThreadId coretid ) { Thread* thr; tl_assert( HG_(is_sane_ThreadId)(coretid) ); thr = map_threads[coretid]; return thr; } /* Asserts if the relevant map_threads entry is NULL. */ static inline Thread* map_threads_lookup ( ThreadId coretid ) { Thread* thr; tl_assert( HG_(is_sane_ThreadId)(coretid) ); thr = map_threads[coretid]; tl_assert(thr); return thr; } /* Do a reverse lookup. Does not assert if 'thr' is not found in map_threads. */ static ThreadId map_threads_maybe_reverse_lookup_SLOW ( Thread* thr ) { ThreadId tid; tl_assert(HG_(is_sane_Thread)(thr)); /* Check nobody used the invalid-threadid slot */ tl_assert(VG_INVALID_THREADID >= 0 && VG_INVALID_THREADID < VG_N_THREADS); tl_assert(map_threads[VG_INVALID_THREADID] == NULL); tid = thr->coretid; tl_assert(HG_(is_sane_ThreadId)(tid)); return tid; } /* Do a reverse lookup. Warning: POTENTIALLY SLOW. Asserts if 'thr' is not found in map_threads. */ static ThreadId map_threads_reverse_lookup_SLOW ( Thread* thr ) { ThreadId tid = map_threads_maybe_reverse_lookup_SLOW( thr ); tl_assert(tid != VG_INVALID_THREADID); tl_assert(map_threads[tid]); tl_assert(map_threads[tid]->coretid == tid); return tid; } static void map_threads_delete ( ThreadId coretid ) { Thread* thr; tl_assert(coretid != 0); tl_assert( HG_(is_sane_ThreadId)(coretid) ); thr = map_threads[coretid]; tl_assert(thr); map_threads[coretid] = NULL; } /*----------------------------------------------------------------*/ /*--- map_locks :: WordFM guest-Addr-of-lock Lock* ---*/ /*----------------------------------------------------------------*/ /* Make sure there is a lock table entry for the given (lock) guest address. If not, create one of the stated 'kind' in unheld state. In any case, return the address of the existing or new Lock. */ static Lock* map_locks_lookup_or_create ( LockKind lkk, Addr ga, ThreadId tid ) { Bool found; Lock* oldlock = NULL; tl_assert(HG_(is_sane_ThreadId)(tid)); found = VG_(lookupFM)( map_locks, NULL, (Word*)&oldlock, (Word)ga ); if (!found) { Lock* lock = mk_LockN(lkk, ga); lock->appeared_at = VG_(record_ExeContext)( tid, 0 ); tl_assert(HG_(is_sane_LockN)(lock)); VG_(addToFM)( map_locks, (Word)ga, (Word)lock ); tl_assert(oldlock == NULL); return lock; } else { tl_assert(oldlock != NULL); tl_assert(HG_(is_sane_LockN)(oldlock)); tl_assert(oldlock->guestaddr == ga); return oldlock; } } static Lock* map_locks_maybe_lookup ( Addr ga ) { Bool found; Lock* lk = NULL; found = VG_(lookupFM)( map_locks, NULL, (Word*)&lk, (Word)ga ); tl_assert(found ? lk != NULL : lk == NULL); return lk; } static void map_locks_delete ( Addr ga ) { Addr ga2 = 0; Lock* lk = NULL; VG_(delFromFM)( map_locks, (Word*)&ga2, (Word*)&lk, (Word)ga ); /* delFromFM produces the val which is being deleted, if it is found. So assert it is non-null; that in effect asserts that we are deleting a (ga, Lock) pair which actually exists. */ tl_assert(lk != NULL); tl_assert(ga2 == ga); } /*----------------------------------------------------------------*/ /*--- Sanity checking the data structures ---*/ /*----------------------------------------------------------------*/ static UWord stats__sanity_checks = 0; static void laog__sanity_check ( Char* who ); /* fwds */ /* REQUIRED INVARIANTS: Thread vs Segment/Lock/SecMaps for each t in Threads { // Thread.lockset: each element is really a valid Lock // Thread.lockset: each Lock in set is actually held by that thread for lk in Thread.lockset lk == LockedBy(t) // Thread.csegid is a valid SegmentID // and the associated Segment has .thr == t } all thread Locksets are pairwise empty under intersection (that is, no lock is claimed to be held by more than one thread) -- this is guaranteed if all locks in locksets point back to their owner threads Lock vs Thread/Segment/SecMaps for each entry (gla, la) in map_locks gla == la->guest_addr for each lk in Locks { lk->tag is valid lk->guest_addr does not have shadow state NoAccess if lk == LockedBy(t), then t->lockset contains lk if lk == UnlockedBy(segid) then segid is valid SegmentID and can be mapped to a valid Segment(seg) and seg->thr->lockset does not contain lk if lk == UnlockedNew then (no lockset contains lk) secmaps for lk has .mbHasLocks == True } Segment vs Thread/Lock/SecMaps the Segment graph is a dag (no cycles) all of the Segment graph must be reachable from the segids mentioned in the Threads for seg in Segments { seg->thr is a sane Thread } SecMaps vs Segment/Thread/Lock for sm in SecMaps { sm properly aligned if any shadow word is ShR or ShM then .mbHasShared == True for each Excl(segid) state map_segments_lookup maps to a sane Segment(seg) for each ShM/ShR(tsetid,lsetid) state each lk in lset is a valid Lock each thr in tset is a valid thread, which is non-dead } */ /* Return True iff 'thr' holds 'lk' in some mode. */ static Bool thread_is_a_holder_of_Lock ( Thread* thr, Lock* lk ) { if (lk->heldBy) return VG_(elemBag)( lk->heldBy, (Word)thr ) > 0; else return False; } /* Sanity check Threads, as far as possible */ __attribute__((noinline)) static void threads__sanity_check ( Char* who ) { #define BAD(_str) do { how = (_str); goto bad; } while (0) Char* how = "no error"; Thread* thr; WordSetID wsA, wsW; UWord* ls_words; Word ls_size, i; Lock* lk; for (thr = admin_threads; thr; thr = thr->admin) { if (!HG_(is_sane_Thread)(thr)) BAD("1"); wsA = thr->locksetA; wsW = thr->locksetW; // locks held in W mode are a subset of all locks held if (!HG_(isSubsetOf)( univ_lsets, wsW, wsA )) BAD("7"); HG_(getPayloadWS)( &ls_words, &ls_size, univ_lsets, wsA ); for (i = 0; i < ls_size; i++) { lk = (Lock*)ls_words[i]; // Thread.lockset: each element is really a valid Lock if (!HG_(is_sane_LockN)(lk)) BAD("2"); // Thread.lockset: each Lock in set is actually held by that // thread if (!thread_is_a_holder_of_Lock(thr,lk)) BAD("3"); } } return; bad: VG_(printf)("threads__sanity_check: who=\"%s\", bad=\"%s\"\n", who, how); tl_assert(0); #undef BAD } /* Sanity check Locks, as far as possible */ __attribute__((noinline)) static void locks__sanity_check ( Char* who ) { #define BAD(_str) do { how = (_str); goto bad; } while (0) Char* how = "no error"; Addr gla; Lock* lk; Int i; // # entries in admin_locks == # entries in map_locks for (i = 0, lk = admin_locks; lk; i++, lk = lk->admin_next) ; if (i != VG_(sizeFM)(map_locks)) BAD("1"); // for each entry (gla, lk) in map_locks // gla == lk->guest_addr VG_(initIterFM)( map_locks ); while (VG_(nextIterFM)( map_locks, (Word*)&gla, (Word*)&lk )) { if (lk->guestaddr != gla) BAD("2"); } VG_(doneIterFM)( map_locks ); // scan through admin_locks ... for (lk = admin_locks; lk; lk = lk->admin_next) { // lock is sane. Quite comprehensive, also checks that // referenced (holder) threads are sane. if (!HG_(is_sane_LockN)(lk)) BAD("3"); // map_locks binds guest address back to this lock if (lk != map_locks_maybe_lookup(lk->guestaddr)) BAD("4"); // look at all threads mentioned as holders of this lock. Ensure // this lock is mentioned in their locksets. if (lk->heldBy) { Thread* thr; Word count; VG_(initIterBag)( lk->heldBy ); while (VG_(nextIterBag)( lk->heldBy, (Word*)&thr, &count )) { // HG_(is_sane_LockN) above ensures these tl_assert(count >= 1); tl_assert(HG_(is_sane_Thread)(thr)); if (!HG_(elemWS)(univ_lsets, thr->locksetA, (Word)lk)) BAD("6"); // also check the w-only lockset if (lk->heldW && !HG_(elemWS)(univ_lsets, thr->locksetW, (Word)lk)) BAD("7"); if ((!lk->heldW) && HG_(elemWS)(univ_lsets, thr->locksetW, (Word)lk)) BAD("8"); } VG_(doneIterBag)( lk->heldBy ); } else { /* lock not held by anybody */ if (lk->heldW) BAD("9"); /* should be False if !heldBy */ // since lk is unheld, then (no lockset contains lk) // hmm, this is really too expensive to check. Hmm. } } return; bad: VG_(printf)("locks__sanity_check: who=\"%s\", bad=\"%s\"\n", who, how); tl_assert(0); #undef BAD } static void all_except_Locks__sanity_check ( Char* who ) { stats__sanity_checks++; if (0) VG_(printf)("all_except_Locks__sanity_check(%s)\n", who); threads__sanity_check(who); if (HG_(clo_track_lockorders)) laog__sanity_check(who); } static void all__sanity_check ( Char* who ) { all_except_Locks__sanity_check(who); locks__sanity_check(who); } /*----------------------------------------------------------------*/ /*--- Shadow value and address range handlers ---*/ /*----------------------------------------------------------------*/ static void laog__pre_thread_acquires_lock ( Thread*, Lock* ); /* fwds */ //static void laog__handle_lock_deletions ( WordSetID ); /* fwds */ static inline Thread* get_current_Thread ( void ); /* fwds */ __attribute__((noinline)) static void laog__handle_one_lock_deletion ( Lock* lk ); /* fwds */ /* Block-copy states (needed for implementing realloc()). */ /* FIXME this copies shadow memory; it doesn't apply the MSM to it. Is that a problem? (hence 'scopy' rather than 'ccopy') */ static void shadow_mem_scopy_range ( Thread* thr, Addr src, Addr dst, SizeT len ) { Thr* hbthr = thr->hbthr; tl_assert(hbthr); libhb_copy_shadow_state( hbthr, src, dst, len ); } static void shadow_mem_cread_range ( Thread* thr, Addr a, SizeT len ) { Thr* hbthr = thr->hbthr; tl_assert(hbthr); LIBHB_CREAD_N(hbthr, a, len); } static void shadow_mem_cwrite_range ( Thread* thr, Addr a, SizeT len ) { Thr* hbthr = thr->hbthr; tl_assert(hbthr); LIBHB_CWRITE_N(hbthr, a, len); } static void shadow_mem_make_New ( Thread* thr, Addr a, SizeT len ) { libhb_srange_new( thr->hbthr, a, len ); } static void shadow_mem_make_NoAccess ( Thread* thr, Addr aIN, SizeT len ) { if (0 && len > 500) VG_(printf)("make NoAccess ( %#lx, %ld )\n", aIN, len ); libhb_srange_noaccess( thr->hbthr, aIN, len ); } static void shadow_mem_make_Untracked ( Thread* thr, Addr aIN, SizeT len ) { if (0 && len > 500) VG_(printf)("make Untracked ( %#lx, %ld )\n", aIN, len ); libhb_srange_untrack( thr->hbthr, aIN, len ); } /*----------------------------------------------------------------*/ /*--- Event handlers (evh__* functions) ---*/ /*--- plus helpers (evhH__* functions) ---*/ /*----------------------------------------------------------------*/ /*--------- Event handler helpers (evhH__* functions) ---------*/ /* Create a new segment for 'thr', making it depend (.prev) on its existing segment, bind together the SegmentID and Segment, and return both of them. Also update 'thr' so it references the new Segment. */ //zz static //zz void evhH__start_new_segment_for_thread ( /*OUT*/SegmentID* new_segidP, //zz /*OUT*/Segment** new_segP, //zz Thread* thr ) //zz { //zz Segment* cur_seg; //zz tl_assert(new_segP); //zz tl_assert(new_segidP); //zz tl_assert(HG_(is_sane_Thread)(thr)); //zz cur_seg = map_segments_lookup( thr->csegid ); //zz tl_assert(cur_seg); //zz tl_assert(cur_seg->thr == thr); /* all sane segs should point back //zz at their owner thread. */ //zz *new_segP = mk_Segment( thr, cur_seg, NULL/*other*/ ); //zz *new_segidP = alloc_SegmentID(); //zz map_segments_add( *new_segidP, *new_segP ); //zz thr->csegid = *new_segidP; //zz } /* The lock at 'lock_ga' has acquired a writer. Make all necessary updates, and also do all possible error checks. */ static void evhH__post_thread_w_acquires_lock ( Thread* thr, LockKind lkk, Addr lock_ga ) { Lock* lk; /* Basically what we need to do is call lockN_acquire_writer. However, that will barf if any 'invalid' lock states would result. Therefore check before calling. Side effect is that 'HG_(is_sane_LockN)(lk)' is both a pre- and post-condition of this routine. Because this routine is only called after successful lock acquisition, we should not be asked to move the lock into any invalid states. Requests to do so are bugs in libpthread, since that should have rejected any such requests. */ tl_assert(HG_(is_sane_Thread)(thr)); /* Try to find the lock. If we can't, then create a new one with kind 'lkk'. */ lk = map_locks_lookup_or_create( lkk, lock_ga, map_threads_reverse_lookup_SLOW(thr) ); tl_assert( HG_(is_sane_LockN)(lk) ); /* check libhb level entities exist */ tl_assert(thr->hbthr); tl_assert(lk->hbso); if (lk->heldBy == NULL) { /* the lock isn't held. Simple. */ tl_assert(!lk->heldW); lockN_acquire_writer( lk, thr ); /* acquire a dependency from the lock's VCs */ libhb_so_recv( thr->hbthr, lk->hbso, True/*strong_recv*/ ); goto noerror; } /* So the lock is already held. If held as a r-lock then libpthread must be buggy. */ tl_assert(lk->heldBy); if (!lk->heldW) { HG_(record_error_Misc)( thr, "Bug in libpthread: write lock " "granted on rwlock which is currently rd-held"); goto error; } /* So the lock is held in w-mode. If it's held by some other thread, then libpthread must be buggy. */ tl_assert(VG_(sizeUniqueBag)(lk->heldBy) == 1); /* from precondition */ if (thr != (Thread*)VG_(anyElementOfBag)(lk->heldBy)) { HG_(record_error_Misc)( thr, "Bug in libpthread: write lock " "granted on mutex/rwlock which is currently " "wr-held by a different thread"); goto error; } /* So the lock is already held in w-mode by 'thr'. That means this is an attempt to lock it recursively, which is only allowable for LK_mbRec kinded locks. Since this routine is called only once the lock has been acquired, this must also be a libpthread bug. */ if (lk->kind != LK_mbRec) { HG_(record_error_Misc)( thr, "Bug in libpthread: recursive write lock " "granted on mutex/wrlock which does not " "support recursion"); goto error; } /* So we are recursively re-locking a lock we already w-hold. */ lockN_acquire_writer( lk, thr ); /* acquire a dependency from the lock's VC. Probably pointless, but also harmless. */ libhb_so_recv( thr->hbthr, lk->hbso, True/*strong_recv*/ ); goto noerror; noerror: if (HG_(clo_track_lockorders)) { /* check lock order acquisition graph, and update. This has to happen before the lock is added to the thread's locksetA/W. */ laog__pre_thread_acquires_lock( thr, lk ); } /* update the thread's held-locks set */ thr->locksetA = HG_(addToWS)( univ_lsets, thr->locksetA, (Word)lk ); thr->locksetW = HG_(addToWS)( univ_lsets, thr->locksetW, (Word)lk ); /* fall through */ error: tl_assert(HG_(is_sane_LockN)(lk)); } /* The lock at 'lock_ga' has acquired a reader. Make all necessary updates, and also do all possible error checks. */ static void evhH__post_thread_r_acquires_lock ( Thread* thr, LockKind lkk, Addr lock_ga ) { Lock* lk; /* Basically what we need to do is call lockN_acquire_reader. However, that will barf if any 'invalid' lock states would result. Therefore check before calling. Side effect is that 'HG_(is_sane_LockN)(lk)' is both a pre- and post-condition of this routine. Because this routine is only called after successful lock acquisition, we should not be asked to move the lock into any invalid states. Requests to do so are bugs in libpthread, since that should have rejected any such requests. */ tl_assert(HG_(is_sane_Thread)(thr)); /* Try to find the lock. If we can't, then create a new one with kind 'lkk'. Only a reader-writer lock can be read-locked, hence the first assertion. */ tl_assert(lkk == LK_rdwr); lk = map_locks_lookup_or_create( lkk, lock_ga, map_threads_reverse_lookup_SLOW(thr) ); tl_assert( HG_(is_sane_LockN)(lk) ); /* check libhb level entities exist */ tl_assert(thr->hbthr); tl_assert(lk->hbso); if (lk->heldBy == NULL) { /* the lock isn't held. Simple. */ tl_assert(!lk->heldW); lockN_acquire_reader( lk, thr ); /* acquire a dependency from the lock's VC */ libhb_so_recv( thr->hbthr, lk->hbso, False/*!strong_recv*/ ); goto noerror; } /* So the lock is already held. If held as a w-lock then libpthread must be buggy. */ tl_assert(lk->heldBy); if (lk->heldW) { HG_(record_error_Misc)( thr, "Bug in libpthread: read lock " "granted on rwlock which is " "currently wr-held"); goto error; } /* Easy enough. In short anybody can get a read-lock on a rwlock provided it is either unlocked or already in rd-held. */ lockN_acquire_reader( lk, thr ); /* acquire a dependency from the lock's VC. Probably pointless, but also harmless. */ libhb_so_recv( thr->hbthr, lk->hbso, False/*!strong_recv*/ ); goto noerror; noerror: if (HG_(clo_track_lockorders)) { /* check lock order acquisition graph, and update. This has to happen before the lock is added to the thread's locksetA/W. */ laog__pre_thread_acquires_lock( thr, lk ); } /* update the thread's held-locks set */ thr->locksetA = HG_(addToWS)( univ_lsets, thr->locksetA, (Word)lk ); /* but don't update thr->locksetW, since lk is only rd-held */ /* fall through */ error: tl_assert(HG_(is_sane_LockN)(lk)); } /* The lock at 'lock_ga' is just about to be unlocked. Make all necessary updates, and also do all possible error checks. */ static void evhH__pre_thread_releases_lock ( Thread* thr, Addr lock_ga, Bool isRDWR ) { Lock* lock; Word n; Bool was_heldW; /* This routine is called prior to a lock release, before libpthread has had a chance to validate the call. Hence we need to detect and reject any attempts to move the lock into an invalid state. Such attempts are bugs in the client. isRDWR is True if we know from the wrapper context that lock_ga should refer to a reader-writer lock, and is False if [ditto] lock_ga should refer to a standard mutex. */ tl_assert(HG_(is_sane_Thread)(thr)); lock = map_locks_maybe_lookup( lock_ga ); if (!lock) { /* We know nothing about a lock at 'lock_ga'. Nevertheless the client is trying to unlock it. So complain, then ignore the attempt. */ HG_(record_error_UnlockBogus)( thr, lock_ga ); return; } tl_assert(lock->guestaddr == lock_ga); tl_assert(HG_(is_sane_LockN)(lock)); if (isRDWR && lock->kind != LK_rdwr) { HG_(record_error_Misc)( thr, "pthread_rwlock_unlock with a " "pthread_mutex_t* argument " ); } if ((!isRDWR) && lock->kind == LK_rdwr) { HG_(record_error_Misc)( thr, "pthread_mutex_unlock with a " "pthread_rwlock_t* argument " ); } if (!lock->heldBy) { /* The lock is not held. This indicates a serious bug in the client. */ tl_assert(!lock->heldW); HG_(record_error_UnlockUnlocked)( thr, lock ); tl_assert(!HG_(elemWS)( univ_lsets, thr->locksetA, (Word)lock )); tl_assert(!HG_(elemWS)( univ_lsets, thr->locksetW, (Word)lock )); goto error; } /* test just above dominates */ tl_assert(lock->heldBy); was_heldW = lock->heldW; /* The lock is held. Is this thread one of the holders? If not, report a bug in the client. */ n = VG_(elemBag)( lock->heldBy, (Word)thr ); tl_assert(n >= 0); if (n == 0) { /* We are not a current holder of the lock. This is a bug in the guest, and (per POSIX pthread rules) the unlock attempt will fail. So just complain and do nothing else. */ Thread* realOwner = (Thread*)VG_(anyElementOfBag)( lock->heldBy ); tl_assert(HG_(is_sane_Thread)(realOwner)); tl_assert(realOwner != thr); tl_assert(!HG_(elemWS)( univ_lsets, thr->locksetA, (Word)lock )); tl_assert(!HG_(elemWS)( univ_lsets, thr->locksetW, (Word)lock )); HG_(record_error_UnlockForeign)( thr, realOwner, lock ); goto error; } /* Ok, we hold the lock 'n' times. */ tl_assert(n >= 1); lockN_release( lock, thr ); n--; tl_assert(n >= 0); if (n > 0) { tl_assert(lock->heldBy); tl_assert(n == VG_(elemBag)( lock->heldBy, (Word)thr )); /* We still hold the lock. So either it's a recursive lock or a rwlock which is currently r-held. */ tl_assert(lock->kind == LK_mbRec || (lock->kind == LK_rdwr && !lock->heldW)); tl_assert(HG_(elemWS)( univ_lsets, thr->locksetA, (Word)lock )); if (lock->heldW) tl_assert(HG_(elemWS)( univ_lsets, thr->locksetW, (Word)lock )); else tl_assert(!HG_(elemWS)( univ_lsets, thr->locksetW, (Word)lock )); } else { /* n is zero. This means we don't hold the lock any more. But if it's a rwlock held in r-mode, someone else could still hold it. Just do whatever sanity checks we can. */ if (lock->kind == LK_rdwr && lock->heldBy) { /* It's a rwlock. We no longer hold it but we used to; nevertheless it still appears to be held by someone else. The implication is that, prior to this release, it must have been shared by us and and whoever else is holding it; which in turn implies it must be r-held, since a lock can't be w-held by more than one thread. */ /* The lock is now R-held by somebody else: */ tl_assert(lock->heldW == False); } else { /* Normal case. It's either not a rwlock, or it's a rwlock that we used to hold in w-mode (which is pretty much the same thing as a non-rwlock.) Since this transaction is atomic (V does not allow multiple threads to run simultaneously), it must mean the lock is now not held by anybody. Hence assert for it. */ /* The lock is now not held by anybody: */ tl_assert(!lock->heldBy); tl_assert(lock->heldW == False); } //if (lock->heldBy) { // tl_assert(0 == VG_(elemBag)( lock->heldBy, (Word)thr )); //} /* update this thread's lockset accordingly. */ thr->locksetA = HG_(delFromWS)( univ_lsets, thr->locksetA, (Word)lock ); thr->locksetW = HG_(delFromWS)( univ_lsets, thr->locksetW, (Word)lock ); /* push our VC into the lock */ tl_assert(thr->hbthr); tl_assert(lock->hbso); /* If the lock was previously W-held, then we want to do a strong send, and if previously R-held, then a weak send. */ libhb_so_send( thr->hbthr, lock->hbso, was_heldW ); } /* fall through */ error: tl_assert(HG_(is_sane_LockN)(lock)); } /* ---------------------------------------------------------- */ /* -------- Event handlers proper (evh__* functions) -------- */ /* ---------------------------------------------------------- */ /* What is the Thread* for the currently running thread? This is absolutely performance critical. We receive notifications from the core for client code starts/stops, and cache the looked-up result in 'current_Thread'. Hence, for the vast majority of requests, finding the current thread reduces to a read of a global variable, provided get_current_Thread_in_C_C is inlined. Outside of client code, current_Thread is NULL, and presumably any uses of it will cause a segfault. Hence: - for uses definitely within client code, use get_current_Thread_in_C_C. - for all other uses, use get_current_Thread. */ static Thread *current_Thread = NULL, *current_Thread_prev = NULL; static void evh__start_client_code ( ThreadId tid, ULong nDisp ) { if (0) VG_(printf)("start %d %llu\n", (Int)tid, nDisp); tl_assert(current_Thread == NULL); current_Thread = map_threads_lookup( tid ); tl_assert(current_Thread != NULL); if (current_Thread != current_Thread_prev) { libhb_Thr_resumes( current_Thread->hbthr ); current_Thread_prev = current_Thread; } } static void evh__stop_client_code ( ThreadId tid, ULong nDisp ) { if (0) VG_(printf)(" stop %d %llu\n", (Int)tid, nDisp); tl_assert(current_Thread != NULL); current_Thread = NULL; libhb_maybe_GC(); } static inline Thread* get_current_Thread_in_C_C ( void ) { return current_Thread; } static inline Thread* get_current_Thread ( void ) { ThreadId coretid; Thread* thr; thr = get_current_Thread_in_C_C(); if (LIKELY(thr)) return thr; /* evidently not in client code. Do it the slow way. */ coretid = VG_(get_running_tid)(); /* FIXME: get rid of the following kludge. It exists because evh__new_mem is called during initialisation (as notification of initial memory layout) and VG_(get_running_tid)() returns VG_INVALID_THREADID at that point. */ if (coretid == VG_INVALID_THREADID) coretid = 1; /* KLUDGE */ thr = map_threads_lookup( coretid ); return thr; } static void evh__new_mem ( Addr a, SizeT len ) { if (SHOW_EVENTS >= 2) VG_(printf)("evh__new_mem(%p, %lu)\n", (void*)a, len ); shadow_mem_make_New( get_current_Thread(), a, len ); if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE)) all__sanity_check("evh__new_mem-post"); } static void evh__new_mem_stack ( Addr a, SizeT len ) { if (SHOW_EVENTS >= 2) VG_(printf)("evh__new_mem_stack(%p, %lu)\n", (void*)a, len ); shadow_mem_make_New( get_current_Thread(), -VG_STACK_REDZONE_SZB + a, len ); if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE)) all__sanity_check("evh__new_mem_stack-post"); } static void evh__new_mem_w_tid ( Addr a, SizeT len, ThreadId tid ) { if (SHOW_EVENTS >= 2) VG_(printf)("evh__new_mem_w_tid(%p, %lu)\n", (void*)a, len ); shadow_mem_make_New( get_current_Thread(), a, len ); if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE)) all__sanity_check("evh__new_mem_w_tid-post"); } static void evh__new_mem_w_perms ( Addr a, SizeT len, Bool rr, Bool ww, Bool xx, ULong di_handle ) { if (SHOW_EVENTS >= 1) VG_(printf)("evh__new_mem_w_perms(%p, %lu, %d,%d,%d)\n", (void*)a, len, (Int)rr, (Int)ww, (Int)xx ); if (rr || ww || xx) shadow_mem_make_New( get_current_Thread(), a, len ); if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE)) all__sanity_check("evh__new_mem_w_perms-post"); } static void evh__set_perms ( Addr a, SizeT len, Bool rr, Bool ww, Bool xx ) { if (SHOW_EVENTS >= 1) VG_(printf)("evh__set_perms(%p, %lu, %d,%d,%d)\n", (void*)a, len, (Int)rr, (Int)ww, (Int)xx ); /* Hmm. What should we do here, that actually makes any sense? Let's say: if neither readable nor writable, then declare it NoAccess, else leave it alone. */ if (!(rr || ww)) shadow_mem_make_NoAccess( get_current_Thread(), a, len ); if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE)) all__sanity_check("evh__set_perms-post"); } static void evh__die_mem ( Addr a, SizeT len ) { // urr, libhb ignores this. if (SHOW_EVENTS >= 2) VG_(printf)("evh__die_mem(%p, %lu)\n", (void*)a, len ); shadow_mem_make_NoAccess( get_current_Thread(), a, len ); if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE)) all__sanity_check("evh__die_mem-post"); } static void evh__untrack_mem ( Addr a, SizeT len ) { // whereas it doesn't ignore this if (SHOW_EVENTS >= 2) VG_(printf)("evh__untrack_mem(%p, %lu)\n", (void*)a, len ); shadow_mem_make_Untracked( get_current_Thread(), a, len ); if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE)) all__sanity_check("evh__untrack_mem-post"); } static void evh__copy_mem ( Addr src, Addr dst, SizeT len ) { if (SHOW_EVENTS >= 2) VG_(printf)("evh__copy_mem(%p, %p, %lu)\n", (void*)src, (void*)dst, len ); shadow_mem_scopy_range( get_current_Thread(), src, dst, len ); if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE)) all__sanity_check("evh__copy_mem-post"); } static void evh__pre_thread_ll_create ( ThreadId parent, ThreadId child ) { if (SHOW_EVENTS >= 1) VG_(printf)("evh__pre_thread_ll_create(p=%d, c=%d)\n", (Int)parent, (Int)child ); if (parent != VG_INVALID_THREADID) { Thread* thr_p; Thread* thr_c; Thr* hbthr_p; Thr* hbthr_c; tl_assert(HG_(is_sane_ThreadId)(parent)); tl_assert(HG_(is_sane_ThreadId)(child)); tl_assert(parent != child); thr_p = map_threads_maybe_lookup( parent ); thr_c = map_threads_maybe_lookup( child ); tl_assert(thr_p != NULL); tl_assert(thr_c == NULL); hbthr_p = thr_p->hbthr; tl_assert(hbthr_p != NULL); tl_assert( libhb_get_Thr_hgthread(hbthr_p) == thr_p ); hbthr_c = libhb_create ( hbthr_p ); /* Create a new thread record for the child. */ /* a Thread for the new thread ... */ thr_c = mk_Thread( hbthr_c ); tl_assert( libhb_get_Thr_hgthread(hbthr_c) == NULL ); libhb_set_Thr_hgthread(hbthr_c, thr_c); /* and bind it in the thread-map table */ map_threads[child] = thr_c; tl_assert(thr_c->coretid == VG_INVALID_THREADID); thr_c->coretid = child; /* Record where the parent is so we can later refer to this in error messages. On amd64-linux, this entails a nasty glibc-2.5 specific hack. The stack snapshot is taken immediately after the parent has returned from its sys_clone call. Unfortunately there is no unwind info for the insn following "syscall" - reading the glibc sources confirms this. So we ask for a snapshot to be taken as if RIP was 3 bytes earlier, in a place where there is unwind info. Sigh. */ { Word first_ip_delta = 0; # if defined(VGP_amd64_linux) first_ip_delta = -3; # endif thr_c->created_at = VG_(record_ExeContext)(parent, first_ip_delta); } } if (HG_(clo_sanity_flags) & SCE_THREADS) all__sanity_check("evh__pre_thread_create-post"); } static void evh__pre_thread_ll_exit ( ThreadId quit_tid ) { Int nHeld; Thread* thr_q; if (SHOW_EVENTS >= 1) VG_(printf)("evh__pre_thread_ll_exit(thr=%d)\n", (Int)quit_tid ); /* quit_tid has disappeared without joining to any other thread. Therefore there is no synchronisation event associated with its exit and so we have to pretty much treat it as if it was still alive but mysteriously making no progress. That is because, if we don't know when it really exited, then we can never say there is a point in time when we're sure the thread really has finished, and so we need to consider the possibility that it lingers indefinitely and continues to interact with other threads. */ /* However, it might have rendezvous'd with a thread that called pthread_join with this one as arg, prior to this point (that's how NPTL works). In which case there has already been a prior sync event. So in any case, just let the thread exit. On NPTL, all thread exits go through here. */ tl_assert(HG_(is_sane_ThreadId)(quit_tid)); thr_q = map_threads_maybe_lookup( quit_tid ); tl_assert(thr_q != NULL); /* Complain if this thread holds any locks. */ nHeld = HG_(cardinalityWS)( univ_lsets, thr_q->locksetA ); tl_assert(nHeld >= 0); if (nHeld > 0) { HChar buf[80]; VG_(sprintf)(buf, "Exiting thread still holds %d lock%s", nHeld, nHeld > 1 ? "s" : ""); HG_(record_error_Misc)( thr_q, buf ); } /* Not much to do here: - tell libhb the thread is gone - clear the map_threads entry, in order that the Valgrind core can re-use it. */ /* Cleanup actions (next 5 lines) copied in evh__atfork_child; keep in sync. */ tl_assert(thr_q->hbthr); libhb_async_exit(thr_q->hbthr); tl_assert(thr_q->coretid == quit_tid); thr_q->coretid = VG_INVALID_THREADID; map_threads_delete( quit_tid ); if (HG_(clo_sanity_flags) & SCE_THREADS) all__sanity_check("evh__pre_thread_ll_exit-post"); } /* This is called immediately after fork, for the child only. 'tid' is the only surviving thread (as per POSIX rules on fork() in threaded programs), so we have to clean up map_threads to remove entries for any other threads. */ static void evh__atfork_child ( ThreadId tid ) { UInt i; Thread* thr; /* Slot 0 should never be used. */ thr = map_threads_maybe_lookup( 0/*INVALID*/ ); tl_assert(!thr); /* Clean up all other slots except 'tid'. */ for (i = 1; i < VG_N_THREADS; i++) { if (i == tid) continue; thr = map_threads_maybe_lookup(i); if (!thr) continue; /* Cleanup actions (next 5 lines) copied from end of evh__pre_thread_ll_exit; keep in sync. */ tl_assert(thr->hbthr); libhb_async_exit(thr->hbthr); tl_assert(thr->coretid == i); thr->coretid = VG_INVALID_THREADID; map_threads_delete(i); } } static void evh__HG_PTHREAD_JOIN_POST ( ThreadId stay_tid, Thread* quit_thr ) { Thread* thr_s; Thread* thr_q; Thr* hbthr_s; Thr* hbthr_q; SO* so; if (SHOW_EVENTS >= 1) VG_(printf)("evh__post_thread_join(stayer=%d, quitter=%p)\n", (Int)stay_tid, quit_thr ); tl_assert(HG_(is_sane_ThreadId)(stay_tid)); thr_s = map_threads_maybe_lookup( stay_tid ); thr_q = quit_thr; tl_assert(thr_s != NULL); tl_assert(thr_q != NULL); tl_assert(thr_s != thr_q); hbthr_s = thr_s->hbthr; hbthr_q = thr_q->hbthr; tl_assert(hbthr_s != hbthr_q); tl_assert( libhb_get_Thr_hgthread(hbthr_s) == thr_s ); tl_assert( libhb_get_Thr_hgthread(hbthr_q) == thr_q ); /* Allocate a temporary synchronisation object and use it to send an imaginary message from the quitter to the stayer, the purpose being to generate a dependence from the quitter to the stayer. */ so = libhb_so_alloc(); tl_assert(so); /* Send last arg of _so_send as False, since the sending thread doesn't actually exist any more, so we don't want _so_send to try taking stack snapshots of it. */ libhb_so_send(hbthr_q, so, True/*strong_send*/); libhb_so_recv(hbthr_s, so, True/*strong_recv*/); libhb_so_dealloc(so); /* evh__pre_thread_ll_exit issues an error message if the exiting thread holds any locks. No need to check here. */ /* This holds because, at least when using NPTL as the thread library, we should be notified the low level thread exit before we hear of any join event on it. The low level exit notification feeds through into evh__pre_thread_ll_exit, which should clear the map_threads entry for it. Hence we expect there to be no map_threads entry at this point. */ tl_assert( map_threads_maybe_reverse_lookup_SLOW(thr_q) == VG_INVALID_THREADID); if (HG_(clo_sanity_flags) & SCE_THREADS) all__sanity_check("evh__post_thread_join-post"); } static void evh__pre_mem_read ( CorePart part, ThreadId tid, Char* s, Addr a, SizeT size) { if (SHOW_EVENTS >= 2 || (SHOW_EVENTS >= 1 && size != 1)) VG_(printf)("evh__pre_mem_read(ctid=%d, \"%s\", %p, %lu)\n", (Int)tid, s, (void*)a, size ); shadow_mem_cread_range( map_threads_lookup(tid), a, size); if (size >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE)) all__sanity_check("evh__pre_mem_read-post"); } static void evh__pre_mem_read_asciiz ( CorePart part, ThreadId tid, Char* s, Addr a ) { Int len; if (SHOW_EVENTS >= 1) VG_(printf)("evh__pre_mem_asciiz(ctid=%d, \"%s\", %p)\n", (Int)tid, s, (void*)a ); // Don't segfault if the string starts in an obviously stupid // place. Actually we should check the whole string, not just // the start address, but that's too much trouble. At least // checking the first byte is better than nothing. See #255009. if (!VG_(am_is_valid_for_client) (a, 1, VKI_PROT_READ)) return; len = VG_(strlen)( (Char*) a ); shadow_mem_cread_range( map_threads_lookup(tid), a, len+1 ); if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE)) all__sanity_check("evh__pre_mem_read_asciiz-post"); } static void evh__pre_mem_write ( CorePart part, ThreadId tid, Char* s, Addr a, SizeT size ) { if (SHOW_EVENTS >= 1) VG_(printf)("evh__pre_mem_write(ctid=%d, \"%s\", %p, %lu)\n", (Int)tid, s, (void*)a, size ); shadow_mem_cwrite_range( map_threads_lookup(tid), a, size); if (size >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE)) all__sanity_check("evh__pre_mem_write-post"); } static void evh__new_mem_heap ( Addr a, SizeT len, Bool is_inited ) { if (SHOW_EVENTS >= 1) VG_(printf)("evh__new_mem_heap(%p, %lu, inited=%d)\n", (void*)a, len, (Int)is_inited ); // FIXME: this is kinda stupid if (is_inited) { shadow_mem_make_New(get_current_Thread(), a, len); } else { shadow_mem_make_New(get_current_Thread(), a, len); } if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE)) all__sanity_check("evh__pre_mem_read-post"); } static void evh__die_mem_heap ( Addr a, SizeT len ) { if (SHOW_EVENTS >= 1) VG_(printf)("evh__die_mem_heap(%p, %lu)\n", (void*)a, len ); shadow_mem_make_NoAccess( get_current_Thread(), a, len ); if (len >= SCE_BIGRANGE_T && (HG_(clo_sanity_flags) & SCE_BIGRANGE)) all__sanity_check("evh__pre_mem_read-post"); } /* --- Event handlers called from generated code --- */ static VG_REGPARM(1) void evh__mem_help_cread_1(Addr a) { Thread* thr = get_current_Thread_in_C_C(); Thr* hbthr = thr->hbthr; LIBHB_CREAD_1(hbthr, a); } static VG_REGPARM(1) void evh__mem_help_cread_2(Addr a) { Thread* thr = get_current_Thread_in_C_C(); Thr* hbthr = thr->hbthr; LIBHB_CREAD_2(hbthr, a); } static VG_REGPARM(1) void evh__mem_help_cread_4(Addr a) { Thread* thr = get_current_Thread_in_C_C(); Thr* hbthr = thr->hbthr; LIBHB_CREAD_4(hbthr, a); } static VG_REGPARM(1) void evh__mem_help_cread_8(Addr a) { Thread* thr = get_current_Thread_in_C_C(); Thr* hbthr = thr->hbthr; LIBHB_CREAD_8(hbthr, a); } static VG_REGPARM(2) void evh__mem_help_cread_N(Addr a, SizeT size) { Thread* thr = get_current_Thread_in_C_C(); Thr* hbthr = thr->hbthr; LIBHB_CREAD_N(hbthr, a, size); } static VG_REGPARM(1) void evh__mem_help_cwrite_1(Addr a) { Thread* thr = get_current_Thread_in_C_C(); Thr* hbthr = thr->hbthr; LIBHB_CWRITE_1(hbthr, a); } static VG_REGPARM(1) void evh__mem_help_cwrite_2(Addr a) { Thread* thr = get_current_Thread_in_C_C(); Thr* hbthr = thr->hbthr; LIBHB_CWRITE_2(hbthr, a); } static VG_REGPARM(1) void evh__mem_help_cwrite_4(Addr a) { Thread* thr = get_current_Thread_in_C_C(); Thr* hbthr = thr->hbthr; LIBHB_CWRITE_4(hbthr, a); } static VG_REGPARM(1) void evh__mem_help_cwrite_8(Addr a) { Thread* thr = get_current_Thread_in_C_C(); Thr* hbthr = thr->hbthr; LIBHB_CWRITE_8(hbthr, a); } static VG_REGPARM(2) void evh__mem_help_cwrite_N(Addr a, SizeT size) { Thread* thr = get_current_Thread_in_C_C(); Thr* hbthr = thr->hbthr; LIBHB_CWRITE_N(hbthr, a, size); } /* ------------------------------------------------------- */ /* -------------- events to do with mutexes -------------- */ /* ------------------------------------------------------- */ /* EXPOSITION only: by intercepting lock init events we can show the user where the lock was initialised, rather than only being able to show where it was first locked. Intercepting lock initialisations is not necessary for the basic operation of the race checker. */ static void evh__HG_PTHREAD_MUTEX_INIT_POST( ThreadId tid, void* mutex, Word mbRec ) { if (SHOW_EVENTS >= 1) VG_(printf)("evh__hg_PTHREAD_MUTEX_INIT_POST(ctid=%d, mbRec=%ld, %p)\n", (Int)tid, mbRec, (void*)mutex ); tl_assert(mbRec == 0 || mbRec == 1); map_locks_lookup_or_create( mbRec ? LK_mbRec : LK_nonRec, (Addr)mutex, tid ); if (HG_(clo_sanity_flags) & SCE_LOCKS) all__sanity_check("evh__hg_PTHREAD_MUTEX_INIT_POST"); } static void evh__HG_PTHREAD_MUTEX_DESTROY_PRE( ThreadId tid, void* mutex ) { Thread* thr; Lock* lk; if (SHOW_EVENTS >= 1) VG_(printf)("evh__hg_PTHREAD_MUTEX_DESTROY_PRE(ctid=%d, %p)\n", (Int)tid, (void*)mutex ); thr = map_threads_maybe_lookup( tid ); /* cannot fail - Thread* must already exist */ tl_assert( HG_(is_sane_Thread)(thr) ); lk = map_locks_maybe_lookup( (Addr)mutex ); if (lk == NULL || (lk->kind != LK_nonRec && lk->kind != LK_mbRec)) { HG_(record_error_Misc)( thr, "pthread_mutex_destroy with invalid argument" ); } if (lk) { tl_assert( HG_(is_sane_LockN)(lk) ); tl_assert( lk->guestaddr == (Addr)mutex ); if (lk->heldBy) { /* Basically act like we unlocked the lock */ HG_(record_error_Misc)( thr, "pthread_mutex_destroy of a locked mutex" ); /* remove lock from locksets of all owning threads */ remove_Lock_from_locksets_of_all_owning_Threads( lk ); VG_(deleteBag)( lk->heldBy ); lk->heldBy = NULL; lk->heldW = False; lk->acquired_at = NULL; } tl_assert( !lk->heldBy ); tl_assert( HG_(is_sane_LockN)(lk) ); if (HG_(clo_track_lockorders)) laog__handle_one_lock_deletion(lk); map_locks_delete( lk->guestaddr ); del_LockN( lk ); } if (HG_(clo_sanity_flags) & SCE_LOCKS) all__sanity_check("evh__hg_PTHREAD_MUTEX_DESTROY_PRE"); } static void evh__HG_PTHREAD_MUTEX_LOCK_PRE ( ThreadId tid, void* mutex, Word isTryLock ) { /* Just check the mutex is sane; nothing else to do. */ // 'mutex' may be invalid - not checked by wrapper Thread* thr; Lock* lk; if (SHOW_EVENTS >= 1) VG_(printf)("evh__hg_PTHREAD_MUTEX_LOCK_PRE(ctid=%d, mutex=%p)\n", (Int)tid, (void*)mutex ); tl_assert(isTryLock == 0 || isTryLock == 1); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ lk = map_locks_maybe_lookup( (Addr)mutex ); if (lk && (lk->kind == LK_rdwr)) { HG_(record_error_Misc)( thr, "pthread_mutex_lock with a " "pthread_rwlock_t* argument " ); } if ( lk && isTryLock == 0 && (lk->kind == LK_nonRec || lk->kind == LK_rdwr) && lk->heldBy && lk->heldW && VG_(elemBag)( lk->heldBy, (Word)thr ) > 0 ) { /* uh, it's a non-recursive lock and we already w-hold it, and this is a real lock operation (not a speculative "tryLock" kind of thing). Duh. Deadlock coming up; but at least produce an error message. */ HChar* errstr = "Attempt to re-lock a " "non-recursive lock I already hold"; HChar* auxstr = "Lock was previously acquired"; if (lk->acquired_at) { HG_(record_error_Misc_w_aux)( thr, errstr, auxstr, lk->acquired_at ); } else { HG_(record_error_Misc)( thr, errstr ); } } } static void evh__HG_PTHREAD_MUTEX_LOCK_POST ( ThreadId tid, void* mutex ) { // only called if the real library call succeeded - so mutex is sane Thread* thr; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_PTHREAD_MUTEX_LOCK_POST(ctid=%d, mutex=%p)\n", (Int)tid, (void*)mutex ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ evhH__post_thread_w_acquires_lock( thr, LK_mbRec, /* if not known, create new lock with this LockKind */ (Addr)mutex ); } static void evh__HG_PTHREAD_MUTEX_UNLOCK_PRE ( ThreadId tid, void* mutex ) { // 'mutex' may be invalid - not checked by wrapper Thread* thr; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_PTHREAD_MUTEX_UNLOCK_PRE(ctid=%d, mutex=%p)\n", (Int)tid, (void*)mutex ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ evhH__pre_thread_releases_lock( thr, (Addr)mutex, False/*!isRDWR*/ ); } static void evh__HG_PTHREAD_MUTEX_UNLOCK_POST ( ThreadId tid, void* mutex ) { // only called if the real library call succeeded - so mutex is sane Thread* thr; if (SHOW_EVENTS >= 1) VG_(printf)("evh__hg_PTHREAD_MUTEX_UNLOCK_POST(ctid=%d, mutex=%p)\n", (Int)tid, (void*)mutex ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ // anything we should do here? } /* ------------------------------------------------------- */ /* -------------- events to do with spinlocks ------------ */ /* ------------------------------------------------------- */ /* All a bit of a kludge. Pretend we're really dealing with ordinary pthread_mutex_t's instead, for the most part. */ static void evh__HG_PTHREAD_SPIN_INIT_OR_UNLOCK_PRE( ThreadId tid, void* slock ) { Thread* thr; Lock* lk; /* In glibc's kludgey world, we're either initialising or unlocking it. Since this is the pre-routine, if it is locked, unlock it and take a dependence edge. Otherwise, do nothing. */ if (SHOW_EVENTS >= 1) VG_(printf)("evh__hg_PTHREAD_SPIN_INIT_OR_UNLOCK_PRE" "(ctid=%d, slock=%p)\n", (Int)tid, (void*)slock ); thr = map_threads_maybe_lookup( tid ); /* cannot fail - Thread* must already exist */; tl_assert( HG_(is_sane_Thread)(thr) ); lk = map_locks_maybe_lookup( (Addr)slock ); if (lk && lk->heldBy) { /* it's held. So do the normal pre-unlock actions, as copied from evh__HG_PTHREAD_MUTEX_UNLOCK_PRE. This stupidly duplicates the map_locks_maybe_lookup. */ evhH__pre_thread_releases_lock( thr, (Addr)slock, False/*!isRDWR*/ ); } } static void evh__HG_PTHREAD_SPIN_INIT_OR_UNLOCK_POST( ThreadId tid, void* slock ) { Lock* lk; /* More kludgery. If the lock has never been seen before, do actions as per evh__HG_PTHREAD_MUTEX_INIT_POST. Else do nothing. */ if (SHOW_EVENTS >= 1) VG_(printf)("evh__hg_PTHREAD_SPIN_INIT_OR_UNLOCK_POST" "(ctid=%d, slock=%p)\n", (Int)tid, (void*)slock ); lk = map_locks_maybe_lookup( (Addr)slock ); if (!lk) { map_locks_lookup_or_create( LK_nonRec, (Addr)slock, tid ); } } static void evh__HG_PTHREAD_SPIN_LOCK_PRE( ThreadId tid, void* slock, Word isTryLock ) { evh__HG_PTHREAD_MUTEX_LOCK_PRE( tid, slock, isTryLock ); } static void evh__HG_PTHREAD_SPIN_LOCK_POST( ThreadId tid, void* slock ) { evh__HG_PTHREAD_MUTEX_LOCK_POST( tid, slock ); } static void evh__HG_PTHREAD_SPIN_DESTROY_PRE( ThreadId tid, void* slock ) { evh__HG_PTHREAD_MUTEX_DESTROY_PRE( tid, slock ); } /* ----------------------------------------------------- */ /* --------------- events to do with CVs --------------- */ /* ----------------------------------------------------- */ /* A mapping from CV to (the SO associated with it, plus some auxiliary data for error checking). When the CV is signalled/broadcasted upon, we do a 'send' into the SO, and when a wait on it completes, we do a 'recv' from the SO. This is believed to give the correct happens-before events arising from CV signallings/broadcasts. */ /* .so is the SO for this CV. .mx_ga is the associated mutex, when .nWaiters > 0 POSIX says effectively that the first pthread_cond_{timed}wait call causes a dynamic binding between the CV and the mutex, and that lasts until such time as the waiter count falls to zero. Hence need to keep track of the number of waiters in order to do consistency tracking. */ typedef struct { SO* so; /* libhb-allocated SO */ void* mx_ga; /* addr of associated mutex, if any */ UWord nWaiters; /* # threads waiting on the CV */ } CVInfo; /* pthread_cond_t* -> CVInfo* */ static WordFM* map_cond_to_CVInfo = NULL; static void map_cond_to_CVInfo_INIT ( void ) { if (UNLIKELY(map_cond_to_CVInfo == NULL)) { map_cond_to_CVInfo = VG_(newFM)( HG_(zalloc), "hg.mctCI.1", HG_(free), NULL ); tl_assert(map_cond_to_CVInfo != NULL); } } static CVInfo* map_cond_to_CVInfo_lookup_or_alloc ( void* cond ) { UWord key, val; map_cond_to_CVInfo_INIT(); if (VG_(lookupFM)( map_cond_to_CVInfo, &key, &val, (UWord)cond )) { tl_assert(key == (UWord)cond); return (CVInfo*)val; } else { SO* so = libhb_so_alloc(); CVInfo* cvi = HG_(zalloc)("hg.mctCloa.1", sizeof(CVInfo)); cvi->so = so; cvi->mx_ga = 0; VG_(addToFM)( map_cond_to_CVInfo, (UWord)cond, (UWord)cvi ); return cvi; } } static void map_cond_to_CVInfo_delete ( void* cond ) { UWord keyW, valW; map_cond_to_CVInfo_INIT(); if (VG_(delFromFM)( map_cond_to_CVInfo, &keyW, &valW, (UWord)cond )) { CVInfo* cvi = (CVInfo*)valW; tl_assert(keyW == (UWord)cond); tl_assert(cvi); tl_assert(cvi->so); libhb_so_dealloc(cvi->so); cvi->mx_ga = 0; HG_(free)(cvi); } } static void evh__HG_PTHREAD_COND_SIGNAL_PRE ( ThreadId tid, void* cond ) { /* 'tid' has signalled on 'cond'. As per the comment above, bind cond to a SO if it is not already so bound, and 'send' on the SO. This is later used by other thread(s) which successfully exit from a pthread_cond_wait on the same cv; then they 'recv' from the SO, thereby acquiring a dependency on this signalling event. */ Thread* thr; CVInfo* cvi; //Lock* lk; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_PTHREAD_COND_SIGNAL_PRE(ctid=%d, cond=%p)\n", (Int)tid, (void*)cond ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ cvi = map_cond_to_CVInfo_lookup_or_alloc( cond ); tl_assert(cvi); tl_assert(cvi->so); // error-if: mutex is bogus // error-if: mutex is not locked // Hmm. POSIX doesn't actually say that it's an error to call // pthread_cond_signal with the associated mutex being unlocked. // Although it does say that it should be "if consistent scheduling // is desired." // // For the moment, disable these checks. //lk = map_locks_maybe_lookup(cvi->mx_ga); //if (lk == NULL || cvi->mx_ga == 0) { // HG_(record_error_Misc)( thr, // "pthread_cond_{signal,broadcast}: " // "no or invalid mutex associated with cond"); //} ///* note: lk could be NULL. Be careful. */ //if (lk) { // if (lk->kind == LK_rdwr) { // HG_(record_error_Misc)(thr, // "pthread_cond_{signal,broadcast}: associated lock is a rwlock"); // } // if (lk->heldBy == NULL) { // HG_(record_error_Misc)(thr, // "pthread_cond_{signal,broadcast}: " // "associated lock is not held by any thread"); // } // if (lk->heldBy != NULL && 0 == VG_(elemBag)(lk->heldBy, (Word)thr)) { // HG_(record_error_Misc)(thr, // "pthread_cond_{signal,broadcast}: " // "associated lock is not held by calling thread"); // } //} libhb_so_send( thr->hbthr, cvi->so, True/*strong_send*/ ); } /* returns True if it reckons 'mutex' is valid and held by this thread, else False */ static Bool evh__HG_PTHREAD_COND_WAIT_PRE ( ThreadId tid, void* cond, void* mutex ) { Thread* thr; Lock* lk; Bool lk_valid = True; CVInfo* cvi; if (SHOW_EVENTS >= 1) VG_(printf)("evh__hg_PTHREAD_COND_WAIT_PRE" "(ctid=%d, cond=%p, mutex=%p)\n", (Int)tid, (void*)cond, (void*)mutex ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ lk = map_locks_maybe_lookup( (Addr)mutex ); /* Check for stupid mutex arguments. There are various ways to be a bozo. Only complain once, though, even if more than one thing is wrong. */ if (lk == NULL) { lk_valid = False; HG_(record_error_Misc)( thr, "pthread_cond_{timed}wait called with invalid mutex" ); } else { tl_assert( HG_(is_sane_LockN)(lk) ); if (lk->kind == LK_rdwr) { lk_valid = False; HG_(record_error_Misc)( thr, "pthread_cond_{timed}wait called with mutex " "of type pthread_rwlock_t*" ); } else if (lk->heldBy == NULL) { lk_valid = False; HG_(record_error_Misc)( thr, "pthread_cond_{timed}wait called with un-held mutex"); } else if (lk->heldBy != NULL && VG_(elemBag)( lk->heldBy, (Word)thr ) == 0) { lk_valid = False; HG_(record_error_Misc)( thr, "pthread_cond_{timed}wait called with mutex " "held by a different thread" ); } } // error-if: cond is also associated with a different mutex cvi = map_cond_to_CVInfo_lookup_or_alloc(cond); tl_assert(cvi); tl_assert(cvi->so); if (cvi->nWaiters == 0) { /* form initial (CV,MX) binding */ cvi->mx_ga = mutex; } else /* check existing (CV,MX) binding */ if (cvi->mx_ga != mutex) { HG_(record_error_Misc)( thr, "pthread_cond_{timed}wait: cond is associated " "with a different mutex"); } cvi->nWaiters++; return lk_valid; } static void evh__HG_PTHREAD_COND_WAIT_POST ( ThreadId tid, void* cond, void* mutex ) { /* A pthread_cond_wait(cond, mutex) completed successfully. Find the SO for this cond, and 'recv' from it so as to acquire a dependency edge back to the signaller/broadcaster. */ Thread* thr; CVInfo* cvi; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_PTHREAD_COND_WAIT_POST" "(ctid=%d, cond=%p, mutex=%p)\n", (Int)tid, (void*)cond, (void*)mutex ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ // error-if: cond is also associated with a different mutex cvi = map_cond_to_CVInfo_lookup_or_alloc( cond ); tl_assert(cvi); tl_assert(cvi->so); tl_assert(cvi->nWaiters > 0); if (!libhb_so_everSent(cvi->so)) { /* Hmm. How can a wait on 'cond' succeed if nobody signalled it? If this happened it would surely be a bug in the threads library. Or one of those fabled "spurious wakeups". */ HG_(record_error_Misc)( thr, "Bug in libpthread: pthread_cond_wait " "succeeded on" " without prior pthread_cond_post"); } /* anyway, acquire a dependency on it. */ libhb_so_recv( thr->hbthr, cvi->so, True/*strong_recv*/ ); cvi->nWaiters--; } static void evh__HG_PTHREAD_COND_DESTROY_PRE ( ThreadId tid, void* cond ) { /* Deal with destroy events. The only purpose is to free storage associated with the CV, so as to avoid any possible resource leaks. */ if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_PTHREAD_COND_DESTROY_PRE" "(ctid=%d, cond=%p)\n", (Int)tid, (void*)cond ); map_cond_to_CVInfo_delete( cond ); } /* ------------------------------------------------------- */ /* -------------- events to do with rwlocks -------------- */ /* ------------------------------------------------------- */ /* EXPOSITION only */ static void evh__HG_PTHREAD_RWLOCK_INIT_POST( ThreadId tid, void* rwl ) { if (SHOW_EVENTS >= 1) VG_(printf)("evh__hg_PTHREAD_RWLOCK_INIT_POST(ctid=%d, %p)\n", (Int)tid, (void*)rwl ); map_locks_lookup_or_create( LK_rdwr, (Addr)rwl, tid ); if (HG_(clo_sanity_flags) & SCE_LOCKS) all__sanity_check("evh__hg_PTHREAD_RWLOCK_INIT_POST"); } static void evh__HG_PTHREAD_RWLOCK_DESTROY_PRE( ThreadId tid, void* rwl ) { Thread* thr; Lock* lk; if (SHOW_EVENTS >= 1) VG_(printf)("evh__hg_PTHREAD_RWLOCK_DESTROY_PRE(ctid=%d, %p)\n", (Int)tid, (void*)rwl ); thr = map_threads_maybe_lookup( tid ); /* cannot fail - Thread* must already exist */ tl_assert( HG_(is_sane_Thread)(thr) ); lk = map_locks_maybe_lookup( (Addr)rwl ); if (lk == NULL || lk->kind != LK_rdwr) { HG_(record_error_Misc)( thr, "pthread_rwlock_destroy with invalid argument" ); } if (lk) { tl_assert( HG_(is_sane_LockN)(lk) ); tl_assert( lk->guestaddr == (Addr)rwl ); if (lk->heldBy) { /* Basically act like we unlocked the lock */ HG_(record_error_Misc)( thr, "pthread_rwlock_destroy of a locked mutex" ); /* remove lock from locksets of all owning threads */ remove_Lock_from_locksets_of_all_owning_Threads( lk ); VG_(deleteBag)( lk->heldBy ); lk->heldBy = NULL; lk->heldW = False; lk->acquired_at = NULL; } tl_assert( !lk->heldBy ); tl_assert( HG_(is_sane_LockN)(lk) ); if (HG_(clo_track_lockorders)) laog__handle_one_lock_deletion(lk); map_locks_delete( lk->guestaddr ); del_LockN( lk ); } if (HG_(clo_sanity_flags) & SCE_LOCKS) all__sanity_check("evh__hg_PTHREAD_RWLOCK_DESTROY_PRE"); } static void evh__HG_PTHREAD_RWLOCK_LOCK_PRE ( ThreadId tid, void* rwl, Word isW, Word isTryLock ) { /* Just check the rwl is sane; nothing else to do. */ // 'rwl' may be invalid - not checked by wrapper Thread* thr; Lock* lk; if (SHOW_EVENTS >= 1) VG_(printf)("evh__hg_PTHREAD_RWLOCK_LOCK_PRE(ctid=%d, isW=%d, %p)\n", (Int)tid, (Int)isW, (void*)rwl ); tl_assert(isW == 0 || isW == 1); /* assured us by wrapper */ tl_assert(isTryLock == 0 || isTryLock == 1); /* assured us by wrapper */ thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ lk = map_locks_maybe_lookup( (Addr)rwl ); if ( lk && (lk->kind == LK_nonRec || lk->kind == LK_mbRec) ) { /* Wrong kind of lock. Duh. */ HG_(record_error_Misc)( thr, "pthread_rwlock_{rd,rw}lock with a " "pthread_mutex_t* argument " ); } } static void evh__HG_PTHREAD_RWLOCK_LOCK_POST ( ThreadId tid, void* rwl, Word isW ) { // only called if the real library call succeeded - so mutex is sane Thread* thr; if (SHOW_EVENTS >= 1) VG_(printf)("evh__hg_PTHREAD_RWLOCK_LOCK_POST(ctid=%d, isW=%d, %p)\n", (Int)tid, (Int)isW, (void*)rwl ); tl_assert(isW == 0 || isW == 1); /* assured us by wrapper */ thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ (isW ? evhH__post_thread_w_acquires_lock : evhH__post_thread_r_acquires_lock)( thr, LK_rdwr, /* if not known, create new lock with this LockKind */ (Addr)rwl ); } static void evh__HG_PTHREAD_RWLOCK_UNLOCK_PRE ( ThreadId tid, void* rwl ) { // 'rwl' may be invalid - not checked by wrapper Thread* thr; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_PTHREAD_RWLOCK_UNLOCK_PRE(ctid=%d, rwl=%p)\n", (Int)tid, (void*)rwl ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ evhH__pre_thread_releases_lock( thr, (Addr)rwl, True/*isRDWR*/ ); } static void evh__HG_PTHREAD_RWLOCK_UNLOCK_POST ( ThreadId tid, void* rwl ) { // only called if the real library call succeeded - so mutex is sane Thread* thr; if (SHOW_EVENTS >= 1) VG_(printf)("evh__hg_PTHREAD_RWLOCK_UNLOCK_POST(ctid=%d, rwl=%p)\n", (Int)tid, (void*)rwl ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ // anything we should do here? } /* ---------------------------------------------------------- */ /* -------------- events to do with semaphores -------------- */ /* ---------------------------------------------------------- */ /* This is similar to but not identical to the handling for condition variables. */ /* For each semaphore, we maintain a stack of SOs. When a 'post' operation is done on a semaphore (unlocking, essentially), a new SO is created for the posting thread, the posting thread does a strong send to it (which merely installs the posting thread's VC in the SO), and the SO is pushed on the semaphore's stack. Later, when a (probably different) thread completes 'wait' on the semaphore, we pop a SO off the semaphore's stack (which should be nonempty), and do a strong recv from it. This mechanism creates dependencies between posters and waiters of the semaphore. It may not be necessary to use a stack - perhaps a bag of SOs would do. But we do need to keep track of how many unused-up posts have happened for the semaphore. Imagine T1 and T2 both post once on a semaphore S, and T3 waits twice on S. T3 cannot complete its waits without both T1 and T2 posting. The above mechanism will ensure that T3 acquires dependencies on both T1 and T2. When a semaphore is initialised with value N, we do as if we'd posted N times on the semaphore: basically create N SOs and do a strong send to all of then. This allows up to N waits on the semaphore to acquire a dependency on the initialisation point, which AFAICS is the correct behaviour. We don't emit an error for DESTROY_PRE on a semaphore we don't know about. We should. */ /* sem_t* -> XArray* SO* */ static WordFM* map_sem_to_SO_stack = NULL; static void map_sem_to_SO_stack_INIT ( void ) { if (map_sem_to_SO_stack == NULL) { map_sem_to_SO_stack = VG_(newFM)( HG_(zalloc), "hg.mstSs.1", HG_(free), NULL ); tl_assert(map_sem_to_SO_stack != NULL); } } static void push_SO_for_sem ( void* sem, SO* so ) { UWord keyW; XArray* xa; tl_assert(so); map_sem_to_SO_stack_INIT(); if (VG_(lookupFM)( map_sem_to_SO_stack, &keyW, (UWord*)&xa, (UWord)sem )) { tl_assert(keyW == (UWord)sem); tl_assert(xa); VG_(addToXA)( xa, &so ); } else { xa = VG_(newXA)( HG_(zalloc), "hg.pSfs.1", HG_(free), sizeof(SO*) ); VG_(addToXA)( xa, &so ); VG_(addToFM)( map_sem_to_SO_stack, (Word)sem, (Word)xa ); } } static SO* mb_pop_SO_for_sem ( void* sem ) { UWord keyW; XArray* xa; SO* so; map_sem_to_SO_stack_INIT(); if (VG_(lookupFM)( map_sem_to_SO_stack, &keyW, (UWord*)&xa, (UWord)sem )) { /* xa is the stack for this semaphore. */ Word sz; tl_assert(keyW == (UWord)sem); sz = VG_(sizeXA)( xa ); tl_assert(sz >= 0); if (sz == 0) return NULL; /* odd, the stack is empty */ so = *(SO**)VG_(indexXA)( xa, sz-1 ); tl_assert(so); VG_(dropTailXA)( xa, 1 ); return so; } else { /* hmm, that's odd. No stack for this semaphore. */ return NULL; } } static void evh__HG_POSIX_SEM_DESTROY_PRE ( ThreadId tid, void* sem ) { UWord keyW, valW; SO* so; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_POSIX_SEM_DESTROY_PRE(ctid=%d, sem=%p)\n", (Int)tid, (void*)sem ); map_sem_to_SO_stack_INIT(); /* Empty out the semaphore's SO stack. This way of doing it is stupid, but at least it's easy. */ while (1) { so = mb_pop_SO_for_sem( sem ); if (!so) break; libhb_so_dealloc(so); } if (VG_(delFromFM)( map_sem_to_SO_stack, &keyW, &valW, (UWord)sem )) { XArray* xa = (XArray*)valW; tl_assert(keyW == (UWord)sem); tl_assert(xa); tl_assert(VG_(sizeXA)(xa) == 0); /* preceding loop just emptied it */ VG_(deleteXA)(xa); } } static void evh__HG_POSIX_SEM_INIT_POST ( ThreadId tid, void* sem, UWord value ) { SO* so; Thread* thr; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_POSIX_SEM_INIT_POST(ctid=%d, sem=%p, value=%lu)\n", (Int)tid, (void*)sem, value ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ /* Empty out the semaphore's SO stack. This way of doing it is stupid, but at least it's easy. */ while (1) { so = mb_pop_SO_for_sem( sem ); if (!so) break; libhb_so_dealloc(so); } /* If we don't do this check, the following while loop runs us out of memory for stupid initial values of 'value'. */ if (value > 10000) { HG_(record_error_Misc)( thr, "sem_init: initial value exceeds 10000; using 10000" ); value = 10000; } /* Now create 'valid' new SOs for the thread, do a strong send to each of them, and push them all on the stack. */ for (; value > 0; value--) { Thr* hbthr = thr->hbthr; tl_assert(hbthr); so = libhb_so_alloc(); libhb_so_send( hbthr, so, True/*strong send*/ ); push_SO_for_sem( sem, so ); } } static void evh__HG_POSIX_SEM_POST_PRE ( ThreadId tid, void* sem ) { /* 'tid' has posted on 'sem'. Create a new SO, do a strong send to it (iow, write our VC into it, then tick ours), and push the SO on on a stack of SOs associated with 'sem'. This is later used by other thread(s) which successfully exit from a sem_wait on the same sem; by doing a strong recv from SOs popped of the stack, they acquire dependencies on the posting thread segment(s). */ Thread* thr; SO* so; Thr* hbthr; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_POSIX_SEM_POST_PRE(ctid=%d, sem=%p)\n", (Int)tid, (void*)sem ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ // error-if: sem is bogus hbthr = thr->hbthr; tl_assert(hbthr); so = libhb_so_alloc(); libhb_so_send( hbthr, so, True/*strong send*/ ); push_SO_for_sem( sem, so ); } static void evh__HG_POSIX_SEM_WAIT_POST ( ThreadId tid, void* sem ) { /* A sem_wait(sem) completed successfully. Pop the posting-SO for the 'sem' from this semaphore's SO-stack, and do a strong recv from it. This creates a dependency back to one of the post-ers for the semaphore. */ Thread* thr; SO* so; Thr* hbthr; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_POSIX_SEM_WAIT_POST(ctid=%d, sem=%p)\n", (Int)tid, (void*)sem ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ // error-if: sem is bogus so = mb_pop_SO_for_sem( sem ); if (so) { hbthr = thr->hbthr; tl_assert(hbthr); libhb_so_recv( hbthr, so, True/*strong recv*/ ); libhb_so_dealloc(so); } else { /* Hmm. How can a wait on 'sem' succeed if nobody posted to it? If this happened it would surely be a bug in the threads library. */ HG_(record_error_Misc)( thr, "Bug in libpthread: sem_wait succeeded on" " semaphore without prior sem_post"); } } /* -------------------------------------------------------- */ /* -------------- events to do with barriers -------------- */ /* -------------------------------------------------------- */ typedef struct { Bool initted; /* has it yet been initted by guest? */ Bool resizable; /* is resizing allowed? */ UWord size; /* declared size */ XArray* waiting; /* XA of Thread*. # present is 0 .. .size */ } Bar; static Bar* new_Bar ( void ) { Bar* bar = HG_(zalloc)( "hg.nB.1 (new_Bar)", sizeof(Bar) ); tl_assert(bar); /* all fields are zero */ tl_assert(bar->initted == False); return bar; } static void delete_Bar ( Bar* bar ) { tl_assert(bar); if (bar->waiting) VG_(deleteXA)(bar->waiting); HG_(free)(bar); } /* A mapping which stores auxiliary data for barriers. */ /* pthread_barrier_t* -> Bar* */ static WordFM* map_barrier_to_Bar = NULL; static void map_barrier_to_Bar_INIT ( void ) { if (UNLIKELY(map_barrier_to_Bar == NULL)) { map_barrier_to_Bar = VG_(newFM)( HG_(zalloc), "hg.mbtBI.1", HG_(free), NULL ); tl_assert(map_barrier_to_Bar != NULL); } } static Bar* map_barrier_to_Bar_lookup_or_alloc ( void* barrier ) { UWord key, val; map_barrier_to_Bar_INIT(); if (VG_(lookupFM)( map_barrier_to_Bar, &key, &val, (UWord)barrier )) { tl_assert(key == (UWord)barrier); return (Bar*)val; } else { Bar* bar = new_Bar(); VG_(addToFM)( map_barrier_to_Bar, (UWord)barrier, (UWord)bar ); return bar; } } static void map_barrier_to_Bar_delete ( void* barrier ) { UWord keyW, valW; map_barrier_to_Bar_INIT(); if (VG_(delFromFM)( map_barrier_to_Bar, &keyW, &valW, (UWord)barrier )) { Bar* bar = (Bar*)valW; tl_assert(keyW == (UWord)barrier); delete_Bar(bar); } } static void evh__HG_PTHREAD_BARRIER_INIT_PRE ( ThreadId tid, void* barrier, UWord count, UWord resizable ) { Thread* thr; Bar* bar; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_PTHREAD_BARRIER_INIT_PRE" "(tid=%d, barrier=%p, count=%lu, resizable=%lu)\n", (Int)tid, (void*)barrier, count, resizable ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ if (count == 0) { HG_(record_error_Misc)( thr, "pthread_barrier_init: 'count' argument is zero" ); } if (resizable != 0 && resizable != 1) { HG_(record_error_Misc)( thr, "pthread_barrier_init: invalid 'resizable' argument" ); } bar = map_barrier_to_Bar_lookup_or_alloc(barrier); tl_assert(bar); if (bar->initted) { HG_(record_error_Misc)( thr, "pthread_barrier_init: barrier is already initialised" ); } if (bar->waiting && VG_(sizeXA)(bar->waiting) > 0) { tl_assert(bar->initted); HG_(record_error_Misc)( thr, "pthread_barrier_init: threads are waiting at barrier" ); VG_(dropTailXA)(bar->waiting, VG_(sizeXA)(bar->waiting)); } if (!bar->waiting) { bar->waiting = VG_(newXA)( HG_(zalloc), "hg.eHPBIP.1", HG_(free), sizeof(Thread*) ); } tl_assert(bar->waiting); tl_assert(VG_(sizeXA)(bar->waiting) == 0); bar->initted = True; bar->resizable = resizable == 1 ? True : False; bar->size = count; } static void evh__HG_PTHREAD_BARRIER_DESTROY_PRE ( ThreadId tid, void* barrier ) { Thread* thr; Bar* bar; /* Deal with destroy events. The only purpose is to free storage associated with the barrier, so as to avoid any possible resource leaks. */ if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_PTHREAD_BARRIER_DESTROY_PRE" "(tid=%d, barrier=%p)\n", (Int)tid, (void*)barrier ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ bar = map_barrier_to_Bar_lookup_or_alloc(barrier); tl_assert(bar); if (!bar->initted) { HG_(record_error_Misc)( thr, "pthread_barrier_destroy: barrier was never initialised" ); } if (bar->initted && bar->waiting && VG_(sizeXA)(bar->waiting) > 0) { HG_(record_error_Misc)( thr, "pthread_barrier_destroy: threads are waiting at barrier" ); } /* Maybe we shouldn't do this; just let it persist, so that when it is reinitialised we don't need to do any dynamic memory allocation? The downside is a potentially unlimited space leak, if the client creates (in turn) a large number of barriers all at different locations. Note that if we do later move to the don't-delete-it scheme, we need to mark the barrier as uninitialised again since otherwise a later _init call will elicit a duplicate-init error. */ map_barrier_to_Bar_delete( barrier ); } /* All the threads have arrived. Now do the Interesting Bit. Get a new synchronisation object and do a weak send to it from all the participating threads. This makes its vector clocks be the join of all the individual threads' vector clocks. Then do a strong receive from it back to all threads, so that their VCs are a copy of it (hence are all equal to the join of their original VCs.) */ static void do_barrier_cross_sync_and_empty ( Bar* bar ) { /* XXX check bar->waiting has no duplicates */ UWord i; SO* so = libhb_so_alloc(); tl_assert(bar->waiting); tl_assert(VG_(sizeXA)(bar->waiting) == bar->size); /* compute the join ... */ for (i = 0; i < bar->size; i++) { Thread* t = *(Thread**)VG_(indexXA)(bar->waiting, i); Thr* hbthr = t->hbthr; libhb_so_send( hbthr, so, False/*weak send*/ ); } /* ... and distribute to all threads */ for (i = 0; i < bar->size; i++) { Thread* t = *(Thread**)VG_(indexXA)(bar->waiting, i); Thr* hbthr = t->hbthr; libhb_so_recv( hbthr, so, True/*strong recv*/ ); } /* finally, we must empty out the waiting vector */ VG_(dropTailXA)(bar->waiting, VG_(sizeXA)(bar->waiting)); /* and we don't need this any more. Perhaps a stack-allocated SO would be better? */ libhb_so_dealloc(so); } static void evh__HG_PTHREAD_BARRIER_WAIT_PRE ( ThreadId tid, void* barrier ) { /* This function gets called after a client thread calls pthread_barrier_wait but before it arrives at the real pthread_barrier_wait. Why is the following correct? It's a bit subtle. If this is not the last thread arriving at the barrier, we simply note its presence and return. Because valgrind (at least as of Nov 08) is single threaded, we are guaranteed safe from any race conditions when in this function -- no other client threads are running. If this is the last thread, then we are again the only running thread. All the other threads will have either arrived at the real pthread_barrier_wait or are on their way to it, but in any case are guaranteed not to be able to move past it, because this thread is currently in this function and so has not yet arrived at the real pthread_barrier_wait. That means that: 1. While we are in this function, none of the other threads waiting at the barrier can move past it. 2. When this function returns (and simulated execution resumes), this thread and all other waiting threads will be able to move past the real barrier. Because of this, it is now safe to update the vector clocks of all threads, to represent the fact that they all arrived at the barrier and have all moved on. There is no danger of any complications to do with some threads leaving the barrier and racing back round to the front, whilst others are still leaving (which is the primary source of complication in correct handling/ implementation of barriers). That can't happen because we update here our data structures so as to indicate that the threads have passed the barrier, even though, as per (2) above, they are guaranteed not to pass the barrier until we return. This relies crucially on Valgrind being single threaded. If that changes, this will need to be reconsidered. */ Thread* thr; Bar* bar; UWord present; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_PTHREAD_BARRIER_WAIT_PRE" "(tid=%d, barrier=%p)\n", (Int)tid, (void*)barrier ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ bar = map_barrier_to_Bar_lookup_or_alloc(barrier); tl_assert(bar); if (!bar->initted) { HG_(record_error_Misc)( thr, "pthread_barrier_wait: barrier is uninitialised" ); return; /* client is broken .. avoid assertions below */ } /* guaranteed by _INIT_PRE above */ tl_assert(bar->size > 0); tl_assert(bar->waiting); VG_(addToXA)( bar->waiting, &thr ); /* guaranteed by this function */ present = VG_(sizeXA)(bar->waiting); tl_assert(present > 0 && present <= bar->size); if (present < bar->size) return; do_barrier_cross_sync_and_empty(bar); } static void evh__HG_PTHREAD_BARRIER_RESIZE_PRE ( ThreadId tid, void* barrier, UWord newcount ) { Thread* thr; Bar* bar; UWord present; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_PTHREAD_BARRIER_RESIZE_PRE" "(tid=%d, barrier=%p, newcount=%lu)\n", (Int)tid, (void*)barrier, newcount ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ bar = map_barrier_to_Bar_lookup_or_alloc(barrier); tl_assert(bar); if (!bar->initted) { HG_(record_error_Misc)( thr, "pthread_barrier_resize: barrier is uninitialised" ); return; /* client is broken .. avoid assertions below */ } if (!bar->resizable) { HG_(record_error_Misc)( thr, "pthread_barrier_resize: barrier is may not be resized" ); return; /* client is broken .. avoid assertions below */ } if (newcount == 0) { HG_(record_error_Misc)( thr, "pthread_barrier_resize: 'newcount' argument is zero" ); return; /* client is broken .. avoid assertions below */ } /* guaranteed by _INIT_PRE above */ tl_assert(bar->size > 0); tl_assert(bar->waiting); /* Guaranteed by this fn */ tl_assert(newcount > 0); if (newcount >= bar->size) { /* Increasing the capacity. There's no possibility of threads moving on from the barrier in this situation, so just note the fact and do nothing more. */ bar->size = newcount; } else { /* Decreasing the capacity. If we decrease it to be equal or below the number of waiting threads, they will now move past the barrier, so need to mess with dep edges in the same way as if the barrier had filled up normally. */ present = VG_(sizeXA)(bar->waiting); tl_assert(present >= 0 && present <= bar->size); if (newcount <= present) { bar->size = present; /* keep the cross_sync call happy */ do_barrier_cross_sync_and_empty(bar); } bar->size = newcount; } } /* ----------------------------------------------------- */ /* ----- events to do with user-specified HB edges ----- */ /* ----------------------------------------------------- */ /* A mapping from arbitrary UWord tag to the SO associated with it. The UWord tags are meaningless to us, interpreted only by the user. */ /* UWord -> SO* */ static WordFM* map_usertag_to_SO = NULL; static void map_usertag_to_SO_INIT ( void ) { if (UNLIKELY(map_usertag_to_SO == NULL)) { map_usertag_to_SO = VG_(newFM)( HG_(zalloc), "hg.mutS.1", HG_(free), NULL ); tl_assert(map_usertag_to_SO != NULL); } } static SO* map_usertag_to_SO_lookup_or_alloc ( UWord usertag ) { UWord key, val; map_usertag_to_SO_INIT(); if (VG_(lookupFM)( map_usertag_to_SO, &key, &val, usertag )) { tl_assert(key == (UWord)usertag); return (SO*)val; } else { SO* so = libhb_so_alloc(); VG_(addToFM)( map_usertag_to_SO, usertag, (UWord)so ); return so; } } // If it's ever needed (XXX check before use) //static void map_usertag_to_SO_delete ( UWord usertag ) { // UWord keyW, valW; // map_usertag_to_SO_INIT(); // if (VG_(delFromFM)( map_usertag_to_SO, &keyW, &valW, usertag )) { // SO* so = (SO*)valW; // tl_assert(keyW == usertag); // tl_assert(so); // libhb_so_dealloc(so); // } //} static void evh__HG_USERSO_SEND_PRE ( ThreadId tid, UWord usertag ) { /* TID is just about to notionally sent a message on a notional abstract synchronisation object whose identity is given by USERTAG. Bind USERTAG to a real SO if it is not already so bound, and do a 'weak send' on the SO. This joins the vector clocks from this thread into any vector clocks already present in the SO. The resulting SO vector clocks are later used by other thread(s) which successfully 'receive' from the SO, thereby acquiring a dependency on all the events that have previously signalled on this SO. */ Thread* thr; SO* so; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_USERSO_SEND_PRE(ctid=%d, usertag=%#lx)\n", (Int)tid, usertag ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ so = map_usertag_to_SO_lookup_or_alloc( usertag ); tl_assert(so); libhb_so_send( thr->hbthr, so, False/*!strong_send*/ ); } static void evh__HG_USERSO_RECV_POST ( ThreadId tid, UWord usertag ) { /* TID has just notionally received a message from a notional abstract synchronisation object whose identity is given by USERTAG. Bind USERTAG to a real SO if it is not already so bound. If the SO has at some point in the past been 'sent' on, to a 'strong receive' on it, thereby acquiring a dependency on the sender. */ Thread* thr; SO* so; if (SHOW_EVENTS >= 1) VG_(printf)("evh__HG_USERSO_RECV_POST(ctid=%d, usertag=%#lx)\n", (Int)tid, usertag ); thr = map_threads_maybe_lookup( tid ); tl_assert(thr); /* cannot fail - Thread* must already exist */ so = map_usertag_to_SO_lookup_or_alloc( usertag ); tl_assert(so); /* Acquire a dependency on it. If the SO has never so far been sent on, then libhb_so_recv will do nothing. So we're safe regardless of SO's history. */ libhb_so_recv( thr->hbthr, so, True/*strong_recv*/ ); } /*--------------------------------------------------------------*/ /*--- Lock acquisition order monitoring ---*/ /*--------------------------------------------------------------*/ /* FIXME: here are some optimisations still to do in laog__pre_thread_acquires_lock. The graph is structured so that if L1 --*--> L2 then L1 must be acquired before L2. The common case is that some thread T holds (eg) L1 L2 and L3 and is repeatedly acquiring and releasing Ln, and there is no ordering error in what it is doing. Hence it repeatly: (1) searches laog to see if Ln --*--> {L1,L2,L3}, which always produces the answer No (because there is no error). (2) adds edges {L1,L2,L3} --> Ln to laog, which are already present (because they already got added the first time T acquired Ln). Hence cache these two events: (1) Cache result of the query from last time. Invalidate the cache any time any edges are added to or deleted from laog. (2) Cache these add-edge requests and ignore them if said edges have already been added to laog. Invalidate the cache any time any edges are deleted from laog. */ typedef struct { WordSetID inns; /* in univ_laog */ WordSetID outs; /* in univ_laog */ } LAOGLinks; /* lock order acquisition graph */ static WordFM* laog = NULL; /* WordFM Lock* LAOGLinks* */ /* EXPOSITION ONLY: for each edge in 'laog', record the two places where that edge was created, so that we can show the user later if we need to. */ typedef struct { Addr src_ga; /* Lock guest addresses for */ Addr dst_ga; /* src/dst of the edge */ ExeContext* src_ec; /* And corresponding places where that */ ExeContext* dst_ec; /* ordering was established */ } LAOGLinkExposition; static Word cmp_LAOGLinkExposition ( UWord llx1W, UWord llx2W ) { /* Compare LAOGLinkExposition*s by (src_ga,dst_ga) field pair. */ LAOGLinkExposition* llx1 = (LAOGLinkExposition*)llx1W; LAOGLinkExposition* llx2 = (LAOGLinkExposition*)llx2W; if (llx1->src_ga < llx2->src_ga) return -1; if (llx1->src_ga > llx2->src_ga) return 1; if (llx1->dst_ga < llx2->dst_ga) return -1; if (llx1->dst_ga > llx2->dst_ga) return 1; return 0; } static WordFM* laog_exposition = NULL; /* WordFM LAOGLinkExposition* NULL */ /* end EXPOSITION ONLY */ __attribute__((noinline)) static void laog__init ( void ) { tl_assert(!laog); tl_assert(!laog_exposition); tl_assert(HG_(clo_track_lockorders)); laog = VG_(newFM)( HG_(zalloc), "hg.laog__init.1", HG_(free), NULL/*unboxedcmp*/ ); laog_exposition = VG_(newFM)( HG_(zalloc), "hg.laog__init.2", HG_(free), cmp_LAOGLinkExposition ); tl_assert(laog); tl_assert(laog_exposition); } static void laog__show ( Char* who ) { Word i, ws_size; UWord* ws_words; Lock* me; LAOGLinks* links; VG_(printf)("laog (requested by %s) {\n", who); VG_(initIterFM)( laog ); me = NULL; links = NULL; while (VG_(nextIterFM)( laog, (Word*)&me, (Word*)&links )) { tl_assert(me); tl_assert(links); VG_(printf)(" node %p:\n", me); HG_(getPayloadWS)( &ws_words, &ws_size, univ_laog, links->inns ); for (i = 0; i < ws_size; i++) VG_(printf)(" inn %#lx\n", ws_words[i] ); HG_(getPayloadWS)( &ws_words, &ws_size, univ_laog, links->outs ); for (i = 0; i < ws_size; i++) VG_(printf)(" out %#lx\n", ws_words[i] ); me = NULL; links = NULL; } VG_(doneIterFM)( laog ); VG_(printf)("}\n"); } __attribute__((noinline)) static void laog__add_edge ( Lock* src, Lock* dst ) { Word keyW; LAOGLinks* links; Bool presentF, presentR; if (0) VG_(printf)("laog__add_edge %p %p\n", src, dst); /* Take the opportunity to sanity check the graph. Record in presentF if there is already a src->dst mapping in this node's forwards links, and presentR if there is already a src->dst mapping in this node's backwards links. They should agree! Also, we need to know whether the edge was already present so as to decide whether or not to update the link details mapping. We can compute presentF and presentR essentially for free, so may as well do this always. */ presentF = presentR = False; /* Update the out edges for src */ keyW = 0; links = NULL; if (VG_(lookupFM)( laog, &keyW, (Word*)&links, (Word)src )) { WordSetID outs_new; tl_assert(links); tl_assert(keyW == (Word)src); outs_new = HG_(addToWS)( univ_laog, links->outs, (Word)dst ); presentF = outs_new == links->outs; links->outs = outs_new; } else { links = HG_(zalloc)("hg.lae.1", sizeof(LAOGLinks)); links->inns = HG_(emptyWS)( univ_laog ); links->outs = HG_(singletonWS)( univ_laog, (Word)dst ); VG_(addToFM)( laog, (Word)src, (Word)links ); } /* Update the in edges for dst */ keyW = 0; links = NULL; if (VG_(lookupFM)( laog, &keyW, (Word*)&links, (Word)dst )) { WordSetID inns_new; tl_assert(links); tl_assert(keyW == (Word)dst); inns_new = HG_(addToWS)( univ_laog, links->inns, (Word)src ); presentR = inns_new == links->inns; links->inns = inns_new; } else { links = HG_(zalloc)("hg.lae.2", sizeof(LAOGLinks)); links->inns = HG_(singletonWS)( univ_laog, (Word)src ); links->outs = HG_(emptyWS)( univ_laog ); VG_(addToFM)( laog, (Word)dst, (Word)links ); } tl_assert( (presentF && presentR) || (!presentF && !presentR) ); if (!presentF && src->acquired_at && dst->acquired_at) { LAOGLinkExposition expo; /* If this edge is entering the graph, and we have acquired_at information for both src and dst, record those acquisition points. Hence, if there is later a violation of this ordering, we can show the user the two places in which the required src-dst ordering was previously established. */ if (0) VG_(printf)("acquire edge %#lx %#lx\n", src->guestaddr, dst->guestaddr); expo.src_ga = src->guestaddr; expo.dst_ga = dst->guestaddr; expo.src_ec = NULL; expo.dst_ec = NULL; tl_assert(laog_exposition); if (VG_(lookupFM)( laog_exposition, NULL, NULL, (Word)&expo )) { /* we already have it; do nothing */ } else { LAOGLinkExposition* expo2 = HG_(zalloc)("hg.lae.3", sizeof(LAOGLinkExposition)); expo2->src_ga = src->guestaddr; expo2->dst_ga = dst->guestaddr; expo2->src_ec = src->acquired_at; expo2->dst_ec = dst->acquired_at; VG_(addToFM)( laog_exposition, (Word)expo2, (Word)NULL ); } } } __attribute__((noinline)) static void laog__del_edge ( Lock* src, Lock* dst ) { Word keyW; LAOGLinks* links; if (0) VG_(printf)("laog__del_edge %p %p\n", src, dst); /* Update the out edges for src */ keyW = 0; links = NULL; if (VG_(lookupFM)( laog, &keyW, (Word*)&links, (Word)src )) { tl_assert(links); tl_assert(keyW == (Word)src); links->outs = HG_(delFromWS)( univ_laog, links->outs, (Word)dst ); } /* Update the in edges for dst */ keyW = 0; links = NULL; if (VG_(lookupFM)( laog, &keyW, (Word*)&links, (Word)dst )) { tl_assert(links); tl_assert(keyW == (Word)dst); links->inns = HG_(delFromWS)( univ_laog, links->inns, (Word)src ); } } __attribute__((noinline)) static WordSetID /* in univ_laog */ laog__succs ( Lock* lk ) { Word keyW; LAOGLinks* links; keyW = 0; links = NULL; if (VG_(lookupFM)( laog, &keyW, (Word*)&links, (Word)lk )) { tl_assert(links); tl_assert(keyW == (Word)lk); return links->outs; } else { return HG_(emptyWS)( univ_laog ); } } __attribute__((noinline)) static WordSetID /* in univ_laog */ laog__preds ( Lock* lk ) { Word keyW; LAOGLinks* links; keyW = 0; links = NULL; if (VG_(lookupFM)( laog, &keyW, (Word*)&links, (Word)lk )) { tl_assert(links); tl_assert(keyW == (Word)lk); return links->inns; } else { return HG_(emptyWS)( univ_laog ); } } __attribute__((noinline)) static void laog__sanity_check ( Char* who ) { Word i, ws_size; UWord* ws_words; Lock* me; LAOGLinks* links; VG_(initIterFM)( laog ); me = NULL; links = NULL; if (0) VG_(printf)("laog sanity check\n"); while (VG_(nextIterFM)( laog, (Word*)&me, (Word*)&links )) { tl_assert(me); tl_assert(links); HG_(getPayloadWS)( &ws_words, &ws_size, univ_laog, links->inns ); for (i = 0; i < ws_size; i++) { if ( ! HG_(elemWS)( univ_laog, laog__succs( (Lock*)ws_words[i] ), (Word)me )) goto bad; } HG_(getPayloadWS)( &ws_words, &ws_size, univ_laog, links->outs ); for (i = 0; i < ws_size; i++) { if ( ! HG_(elemWS)( univ_laog, laog__preds( (Lock*)ws_words[i] ), (Word)me )) goto bad; } me = NULL; links = NULL; } VG_(doneIterFM)( laog ); return; bad: VG_(printf)("laog__sanity_check(%s) FAILED\n", who); laog__show(who); tl_assert(0); } /* If there is a path in laog from 'src' to any of the elements in 'dst', return an arbitrarily chosen element of 'dst' reachable from 'src'. If no path exist from 'src' to any element in 'dst', return NULL. */ __attribute__((noinline)) static Lock* laog__do_dfs_from_to ( Lock* src, WordSetID dsts /* univ_lsets */ ) { Lock* ret; Word i, ssz; XArray* stack; /* of Lock* */ WordFM* visited; /* Lock* -> void, iow, Set(Lock*) */ Lock* here; WordSetID succs; Word succs_size; UWord* succs_words; //laog__sanity_check(); /* If the destination set is empty, we can never get there from 'src' :-), so don't bother to try */ if (HG_(isEmptyWS)( univ_lsets, dsts )) return NULL; ret = NULL; stack = VG_(newXA)( HG_(zalloc), "hg.lddft.1", HG_(free), sizeof(Lock*) ); visited = VG_(newFM)( HG_(zalloc), "hg.lddft.2", HG_(free), NULL/*unboxedcmp*/ ); (void) VG_(addToXA)( stack, &src ); while (True) { ssz = VG_(sizeXA)( stack ); if (ssz == 0) { ret = NULL; break; } here = *(Lock**) VG_(indexXA)( stack, ssz-1 ); VG_(dropTailXA)( stack, 1 ); if (HG_(elemWS)( univ_lsets, dsts, (Word)here )) { ret = here; break; } if (VG_(lookupFM)( visited, NULL, NULL, (Word)here )) continue; VG_(addToFM)( visited, (Word)here, 0 ); succs = laog__succs( here ); HG_(getPayloadWS)( &succs_words, &succs_size, univ_laog, succs ); for (i = 0; i < succs_size; i++) (void) VG_(addToXA)( stack, &succs_words[i] ); } VG_(deleteFM)( visited, NULL, NULL ); VG_(deleteXA)( stack ); return ret; } /* Thread 'thr' is acquiring 'lk'. Check for inconsistent ordering between 'lk' and the locks already held by 'thr' and issue a complaint if so. Also, update the ordering graph appropriately. */ __attribute__((noinline)) static void laog__pre_thread_acquires_lock ( Thread* thr, /* NB: BEFORE lock is added */ Lock* lk ) { UWord* ls_words; Word ls_size, i; Lock* other; /* It may be that 'thr' already holds 'lk' and is recursively relocking in. In this case we just ignore the call. */ /* NB: univ_lsets really is correct here */ if (HG_(elemWS)( univ_lsets, thr->locksetA, (Word)lk )) return; /* First, the check. Complain if there is any path in laog from lk to any of the locks already held by thr, since if any such path existed, it would mean that previously lk was acquired before (rather than after, as we are doing here) at least one of those locks. */ other = laog__do_dfs_from_to(lk, thr->locksetA); if (other) { LAOGLinkExposition key, *found; /* So we managed to find a path lk --*--> other in the graph, which implies that 'lk' should have been acquired before 'other' but is in fact being acquired afterwards. We present the lk/other arguments to record_error_LockOrder in the order in which they should have been acquired. */ /* Go look in the laog_exposition mapping, to find the allocation points for this edge, so we can show the user. */ key.src_ga = lk->guestaddr; key.dst_ga = other->guestaddr; key.src_ec = NULL; key.dst_ec = NULL; found = NULL; if (VG_(lookupFM)( laog_exposition, (Word*)&found, NULL, (Word)&key )) { tl_assert(found != &key); tl_assert(found->src_ga == key.src_ga); tl_assert(found->dst_ga == key.dst_ga); tl_assert(found->src_ec); tl_assert(found->dst_ec); HG_(record_error_LockOrder)( thr, lk->guestaddr, other->guestaddr, found->src_ec, found->dst_ec ); } else { /* Hmm. This can't happen (can it?) */ HG_(record_error_LockOrder)( thr, lk->guestaddr, other->guestaddr, NULL, NULL ); } } /* Second, add to laog the pairs (old, lk) | old <- locks already held by thr Since both old and lk are currently held by thr, their acquired_at fields must be non-NULL. */ tl_assert(lk->acquired_at); HG_(getPayloadWS)( &ls_words, &ls_size, univ_lsets, thr->locksetA ); for (i = 0; i < ls_size; i++) { Lock* old = (Lock*)ls_words[i]; tl_assert(old->acquired_at); laog__add_edge( old, lk ); } /* Why "except_Locks" ? We're here because a lock is being acquired by a thread, and we're in an inconsistent state here. See the call points in evhH__post_thread_{r,w}_acquires_lock. When called in this inconsistent state, locks__sanity_check duly barfs. */ if (HG_(clo_sanity_flags) & SCE_LAOG) all_except_Locks__sanity_check("laog__pre_thread_acquires_lock-post"); } /* Delete from 'laog' any pair mentioning a lock in locksToDelete */ __attribute__((noinline)) static void laog__handle_one_lock_deletion ( Lock* lk ) { WordSetID preds, succs; Word preds_size, succs_size, i, j; UWord *preds_words, *succs_words; preds = laog__preds( lk ); succs = laog__succs( lk ); HG_(getPayloadWS)( &preds_words, &preds_size, univ_laog, preds ); for (i = 0; i < preds_size; i++) laog__del_edge( (Lock*)preds_words[i], lk ); HG_(getPayloadWS)( &succs_words, &succs_size, univ_laog, succs ); for (j = 0; j < succs_size; j++) laog__del_edge( lk, (Lock*)succs_words[j] ); for (i = 0; i < preds_size; i++) { for (j = 0; j < succs_size; j++) { if (preds_words[i] != succs_words[j]) { /* This can pass unlocked locks to laog__add_edge, since we're deleting stuff. So their acquired_at fields may be NULL. */ laog__add_edge( (Lock*)preds_words[i], (Lock*)succs_words[j] ); } } } } //__attribute__((noinline)) //static void laog__handle_lock_deletions ( // WordSetID /* in univ_laog */ locksToDelete // ) //{ // Word i, ws_size; // UWord* ws_words; // // // HG_(getPayloadWS)( &ws_words, &ws_size, univ_lsets, locksToDelete ); // for (i = 0; i < ws_size; i++) // laog__handle_one_lock_deletion( (Lock*)ws_words[i] ); // // if (HG_(clo_sanity_flags) & SCE_LAOG) // all__sanity_check("laog__handle_lock_deletions-post"); //} /*--------------------------------------------------------------*/ /*--- Malloc/free replacements ---*/ /*--------------------------------------------------------------*/ typedef struct { void* next; /* required by m_hashtable */ Addr payload; /* ptr to actual block */ SizeT szB; /* size requested */ ExeContext* where; /* where it was allocated */ Thread* thr; /* allocating thread */ } MallocMeta; /* A hash table of MallocMetas, used to track malloc'd blocks (obviously). */ static VgHashTable hg_mallocmeta_table = NULL; static MallocMeta* new_MallocMeta ( void ) { MallocMeta* md = HG_(zalloc)( "hg.new_MallocMeta.1", sizeof(MallocMeta) ); tl_assert(md); return md; } static void delete_MallocMeta ( MallocMeta* md ) { HG_(free)(md); } /* Allocate a client block and set up the metadata for it. */ static void* handle_alloc ( ThreadId tid, SizeT szB, SizeT alignB, Bool is_zeroed ) { Addr p; MallocMeta* md; tl_assert( ((SSizeT)szB) >= 0 ); p = (Addr)VG_(cli_malloc)(alignB, szB); if (!p) { return NULL; } if (is_zeroed) VG_(memset)((void*)p, 0, szB); /* Note that map_threads_lookup must succeed (cannot assert), since memory can only be allocated by currently alive threads, hence they must have an entry in map_threads. */ md = new_MallocMeta(); md->payload = p; md->szB = szB; md->where = VG_(record_ExeContext)( tid, 0 ); md->thr = map_threads_lookup( tid ); VG_(HT_add_node)( hg_mallocmeta_table, (VgHashNode*)md ); /* Tell the lower level memory wranglers. */ evh__new_mem_heap( p, szB, is_zeroed ); return (void*)p; } /* Re the checks for less-than-zero (also in hg_cli__realloc below): Cast to a signed type to catch any unexpectedly negative args. We're assuming here that the size asked for is not greater than 2^31 bytes (for 32-bit platforms) or 2^63 bytes (for 64-bit platforms). */ static void* hg_cli__malloc ( ThreadId tid, SizeT n ) { if (((SSizeT)n) < 0) return NULL; return handle_alloc ( tid, n, VG_(clo_alignment), /*is_zeroed*/False ); } static void* hg_cli____builtin_new ( ThreadId tid, SizeT n ) { if (((SSizeT)n) < 0) return NULL; return handle_alloc ( tid, n, VG_(clo_alignment), /*is_zeroed*/False ); } static void* hg_cli____builtin_vec_new ( ThreadId tid, SizeT n ) { if (((SSizeT)n) < 0) return NULL; return handle_alloc ( tid, n, VG_(clo_alignment), /*is_zeroed*/False ); } static void* hg_cli__memalign ( ThreadId tid, SizeT align, SizeT n ) { if (((SSizeT)n) < 0) return NULL; return handle_alloc ( tid, n, align, /*is_zeroed*/False ); } static void* hg_cli__calloc ( ThreadId tid, SizeT nmemb, SizeT size1 ) { if ( ((SSizeT)nmemb) < 0 || ((SSizeT)size1) < 0 ) return NULL; return handle_alloc ( tid, nmemb*size1, VG_(clo_alignment), /*is_zeroed*/True ); } /* Free a client block, including getting rid of the relevant metadata. */ static void handle_free ( ThreadId tid, void* p ) { MallocMeta *md, *old_md; SizeT szB; /* First see if we can find the metadata for 'p'. */ md = (MallocMeta*) VG_(HT_lookup)( hg_mallocmeta_table, (UWord)p ); if (!md) return; /* apparently freeing a bogus address. Oh well. */ tl_assert(md->payload == (Addr)p); szB = md->szB; /* Nuke the metadata block */ old_md = (MallocMeta*) VG_(HT_remove)( hg_mallocmeta_table, (UWord)p ); tl_assert(old_md); /* it must be present - we just found it */ tl_assert(old_md == md); tl_assert(old_md->payload == (Addr)p); VG_(cli_free)((void*)old_md->payload); delete_MallocMeta(old_md); /* Tell the lower level memory wranglers. */ evh__die_mem_heap( (Addr)p, szB ); } static void hg_cli__free ( ThreadId tid, void* p ) { handle_free(tid, p); } static void hg_cli____builtin_delete ( ThreadId tid, void* p ) { handle_free(tid, p); } static void hg_cli____builtin_vec_delete ( ThreadId tid, void* p ) { handle_free(tid, p); } static void* hg_cli__realloc ( ThreadId tid, void* payloadV, SizeT new_size ) { MallocMeta *md, *md_new, *md_tmp; SizeT i; Addr payload = (Addr)payloadV; if (((SSizeT)new_size) < 0) return NULL; md = (MallocMeta*) VG_(HT_lookup)( hg_mallocmeta_table, (UWord)payload ); if (!md) return NULL; /* apparently realloc-ing a bogus address. Oh well. */ tl_assert(md->payload == payload); if (md->szB == new_size) { /* size unchanged */ md->where = VG_(record_ExeContext)(tid, 0); return payloadV; } if (md->szB > new_size) { /* new size is smaller */ md->szB = new_size; md->where = VG_(record_ExeContext)(tid, 0); evh__die_mem_heap( md->payload + new_size, md->szB - new_size ); return payloadV; } /* else */ { /* new size is bigger */ Addr p_new = (Addr)VG_(cli_malloc)(VG_(clo_alignment), new_size); /* First half kept and copied, second half new */ // FIXME: shouldn't we use a copier which implements the // memory state machine? evh__copy_mem( payload, p_new, md->szB ); evh__new_mem_heap ( p_new + md->szB, new_size - md->szB, /*inited*/False ); /* FIXME: can anything funny happen here? specifically, if the old range contained a lock, then die_mem_heap will complain. Is that the correct behaviour? Not sure. */ evh__die_mem_heap( payload, md->szB ); /* Copy from old to new */ for (i = 0; i < md->szB; i++) ((UChar*)p_new)[i] = ((UChar*)payload)[i]; /* Because the metadata hash table is index by payload address, we have to get rid of the old hash table entry and make a new one. We can't just modify the existing metadata in place, because then it would (almost certainly) be in the wrong hash chain. */ md_new = new_MallocMeta(); *md_new = *md; md_tmp = VG_(HT_remove)( hg_mallocmeta_table, payload ); tl_assert(md_tmp); tl_assert(md_tmp == md); VG_(cli_free)((void*)md->payload); delete_MallocMeta(md); /* Update fields */ md_new->where = VG_(record_ExeContext)( tid, 0 ); md_new->szB = new_size; md_new->payload = p_new; md_new->thr = map_threads_lookup( tid ); /* and add */ VG_(HT_add_node)( hg_mallocmeta_table, (VgHashNode*)md_new ); return (void*)p_new; } } static SizeT hg_cli_malloc_usable_size ( ThreadId tid, void* p ) { MallocMeta *md = VG_(HT_lookup)( hg_mallocmeta_table, (UWord)p ); // There may be slop, but pretend there isn't because only the asked-for // area will have been shadowed properly. return ( md ? md->szB : 0 ); } /* For error creation: map 'data_addr' to a malloc'd chunk, if any. Slow linear search. With a bit of hash table help if 'data_addr' is either the start of a block or up to 15 word-sized steps along from the start of a block. */ static inline Bool addr_is_in_MM_Chunk( MallocMeta* mm, Addr a ) { /* Accept 'a' as within 'mm' if 'mm's size is zero and 'a' points right at it. */ if (UNLIKELY(mm->szB == 0 && a == mm->payload)) return True; /* else normal interval rules apply */ if (LIKELY(a < mm->payload)) return False; if (LIKELY(a >= mm->payload + mm->szB)) return False; return True; } Bool HG_(mm_find_containing_block)( /*OUT*/ExeContext** where, /*OUT*/Addr* payload, /*OUT*/SizeT* szB, Addr data_addr ) { MallocMeta* mm; Int i; const Int n_fast_check_words = 16; /* First, do a few fast searches on the basis that data_addr might be exactly the start of a block or up to 15 words inside. This can happen commonly via the creq _VG_USERREQ__HG_CLEAN_MEMORY_HEAPBLOCK. */ for (i = 0; i < n_fast_check_words; i++) { mm = VG_(HT_lookup)( hg_mallocmeta_table, data_addr - (UWord)(UInt)i * sizeof(UWord) ); if (UNLIKELY(mm && addr_is_in_MM_Chunk(mm, data_addr))) goto found; } /* Well, this totally sucks. But without using an interval tree or some such, it's hard to see how to do better. We have to check every block in the entire table. */ VG_(HT_ResetIter)(hg_mallocmeta_table); while ( (mm = VG_(HT_Next)(hg_mallocmeta_table)) ) { if (UNLIKELY(addr_is_in_MM_Chunk(mm, data_addr))) goto found; } /* Not found. Bah. */ return False; /*NOTREACHED*/ found: tl_assert(mm); tl_assert(addr_is_in_MM_Chunk(mm, data_addr)); if (where) *where = mm->where; if (payload) *payload = mm->payload; if (szB) *szB = mm->szB; return True; } /*--------------------------------------------------------------*/ /*--- Instrumentation ---*/ /*--------------------------------------------------------------*/ static void instrument_mem_access ( IRSB* bbOut, IRExpr* addr, Int szB, Bool isStore, Int hWordTy_szB ) { IRType tyAddr = Ity_INVALID; HChar* hName = NULL; void* hAddr = NULL; Int regparms = 0; IRExpr** argv = NULL; IRDirty* di = NULL; tl_assert(isIRAtom(addr)); tl_assert(hWordTy_szB == 4 || hWordTy_szB == 8); tyAddr = typeOfIRExpr( bbOut->tyenv, addr ); tl_assert(tyAddr == Ity_I32 || tyAddr == Ity_I64); /* So the effective address is in 'addr' now. */ regparms = 1; // unless stated otherwise if (isStore) { switch (szB) { case 1: hName = "evh__mem_help_cwrite_1"; hAddr = &evh__mem_help_cwrite_1; argv = mkIRExprVec_1( addr ); break; case 2: hName = "evh__mem_help_cwrite_2"; hAddr = &evh__mem_help_cwrite_2; argv = mkIRExprVec_1( addr ); break; case 4: hName = "evh__mem_help_cwrite_4"; hAddr = &evh__mem_help_cwrite_4; argv = mkIRExprVec_1( addr ); break; case 8: hName = "evh__mem_help_cwrite_8"; hAddr = &evh__mem_help_cwrite_8; argv = mkIRExprVec_1( addr ); break; default: tl_assert(szB > 8 && szB <= 512); /* stay sane */ regparms = 2; hName = "evh__mem_help_cwrite_N"; hAddr = &evh__mem_help_cwrite_N; argv = mkIRExprVec_2( addr, mkIRExpr_HWord( szB )); break; } } else { switch (szB) { case 1: hName = "evh__mem_help_cread_1"; hAddr = &evh__mem_help_cread_1; argv = mkIRExprVec_1( addr ); break; case 2: hName = "evh__mem_help_cread_2"; hAddr = &evh__mem_help_cread_2; argv = mkIRExprVec_1( addr ); break; case 4: hName = "evh__mem_help_cread_4"; hAddr = &evh__mem_help_cread_4; argv = mkIRExprVec_1( addr ); break; case 8: hName = "evh__mem_help_cread_8"; hAddr = &evh__mem_help_cread_8; argv = mkIRExprVec_1( addr ); break; default: tl_assert(szB > 8 && szB <= 512); /* stay sane */ regparms = 2; hName = "evh__mem_help_cread_N"; hAddr = &evh__mem_help_cread_N; argv = mkIRExprVec_2( addr, mkIRExpr_HWord( szB )); break; } } /* Add the helper. */ tl_assert(hName); tl_assert(hAddr); tl_assert(argv); di = unsafeIRDirty_0_N( regparms, hName, VG_(fnptr_to_fnentry)( hAddr ), argv ); addStmtToIRSB( bbOut, IRStmt_Dirty(di) ); } /* Figure out if GA is a guest code address in the dynamic linker, and if so return True. Otherwise (and in case of any doubt) return False. (sidedly safe w/ False as the safe value) */ static Bool is_in_dynamic_linker_shared_object( Addr64 ga ) { DebugInfo* dinfo; const UChar* soname; if (0) return False; dinfo = VG_(find_DebugInfo)( (Addr)ga ); if (!dinfo) return False; soname = VG_(DebugInfo_get_soname)(dinfo); tl_assert(soname); if (0) VG_(printf)("%s\n", soname); # if defined(VGO_linux) if (VG_STREQ(soname, VG_U_LD_LINUX_SO_3)) return True; if (VG_STREQ(soname, VG_U_LD_LINUX_SO_2)) return True; if (VG_STREQ(soname, VG_U_LD_LINUX_X86_64_SO_2)) return True; if (VG_STREQ(soname, VG_U_LD64_SO_1)) return True; if (VG_STREQ(soname, VG_U_LD_SO_1)) return True; # elif defined(VGO_darwin) if (VG_STREQ(soname, VG_U_DYLD)) return True; # else # error "Unsupported OS" # endif return False; } static IRSB* hg_instrument ( VgCallbackClosure* closure, IRSB* bbIn, VexGuestLayout* layout, VexGuestExtents* vge, IRType gWordTy, IRType hWordTy ) { Int i; IRSB* bbOut; Addr64 cia; /* address of current insn */ IRStmt* st; Bool inLDSO = False; Addr64 inLDSOmask4K = 1; /* mismatches on first check */ if (gWordTy != hWordTy) { /* We don't currently support this case. */ VG_(tool_panic)("host/guest word size mismatch"); } if (VKI_PAGE_SIZE < 4096 || VG_(log2)(VKI_PAGE_SIZE) == -1) { VG_(tool_panic)("implausible or too-small VKI_PAGE_SIZE"); } /* Set up BB */ bbOut = emptyIRSB(); bbOut->tyenv = deepCopyIRTypeEnv(bbIn->tyenv); bbOut->next = deepCopyIRExpr(bbIn->next); bbOut->jumpkind = bbIn->jumpkind; // Copy verbatim any IR preamble preceding the first IMark i = 0; while (i < bbIn->stmts_used && bbIn->stmts[i]->tag != Ist_IMark) { addStmtToIRSB( bbOut, bbIn->stmts[i] ); i++; } // Get the first statement, and initial cia from it tl_assert(bbIn->stmts_used > 0); tl_assert(i < bbIn->stmts_used); st = bbIn->stmts[i]; tl_assert(Ist_IMark == st->tag); cia = st->Ist.IMark.addr; st = NULL; for (/*use current i*/; i < bbIn->stmts_used; i++) { st = bbIn->stmts[i]; tl_assert(st); tl_assert(isFlatIRStmt(st)); switch (st->tag) { case Ist_NoOp: case Ist_AbiHint: case Ist_Put: case Ist_PutI: case Ist_Exit: /* None of these can contain any memory references. */ break; case Ist_IMark: /* no mem refs, but note the insn address. */ cia = st->Ist.IMark.addr; /* Don't instrument the dynamic linker. It generates a lot of races which we just expensively suppress, so it's pointless. Avoid flooding is_in_dynamic_linker_shared_object with requests by only checking at transitions between 4K pages. */ if ((cia & ~(Addr64)0xFFF) != inLDSOmask4K) { if (0) VG_(printf)("NEW %#lx\n", (Addr)cia); inLDSOmask4K = cia & ~(Addr64)0xFFF; inLDSO = is_in_dynamic_linker_shared_object(cia); } else { if (0) VG_(printf)("old %#lx\n", (Addr)cia); } break; case Ist_MBE: switch (st->Ist.MBE.event) { case Imbe_Fence: break; /* not interesting */ default: goto unhandled; } break; case Ist_CAS: { /* Atomic read-modify-write cycle. Just pretend it's a read. */ IRCAS* cas = st->Ist.CAS.details; Bool isDCAS = cas->oldHi != IRTemp_INVALID; if (isDCAS) { tl_assert(cas->expdHi); tl_assert(cas->dataHi); } else { tl_assert(!cas->expdHi); tl_assert(!cas->dataHi); } /* Just be boring about it. */ if (!inLDSO) { instrument_mem_access( bbOut, cas->addr, (isDCAS ? 2 : 1) * sizeofIRType(typeOfIRExpr(bbIn->tyenv, cas->dataLo)), False/*!isStore*/, sizeofIRType(hWordTy) ); } break; } case Ist_LLSC: { /* We pretend store-conditionals don't exist, viz, ignore them. Whereas load-linked's are treated the same as normal loads. */ IRType dataTy; if (st->Ist.LLSC.storedata == NULL) { /* LL */ dataTy = typeOfIRTemp(bbIn->tyenv, st->Ist.LLSC.result); if (!inLDSO) { instrument_mem_access( bbOut, st->Ist.LLSC.addr, sizeofIRType(dataTy), False/*!isStore*/, sizeofIRType(hWordTy) ); } } else { /* SC */ /*ignore */ } break; } case Ist_Store: /* It seems we pretend that store-conditionals don't exist, viz, just ignore them ... */ if (!inLDSO) { instrument_mem_access( bbOut, st->Ist.Store.addr, sizeofIRType(typeOfIRExpr(bbIn->tyenv, st->Ist.Store.data)), True/*isStore*/, sizeofIRType(hWordTy) ); } break; case Ist_WrTmp: { /* ... whereas here we don't care whether a load is a vanilla one or a load-linked. */ IRExpr* data = st->Ist.WrTmp.data; if (data->tag == Iex_Load) { if (!inLDSO) { instrument_mem_access( bbOut, data->Iex.Load.addr, sizeofIRType(data->Iex.Load.ty), False/*!isStore*/, sizeofIRType(hWordTy) ); } } break; } case Ist_Dirty: { Int dataSize; IRDirty* d = st->Ist.Dirty.details; if (d->mFx != Ifx_None) { /* This dirty helper accesses memory. Collect the details. */ tl_assert(d->mAddr != NULL); tl_assert(d->mSize != 0); dataSize = d->mSize; if (d->mFx == Ifx_Read || d->mFx == Ifx_Modify) { if (!inLDSO) { instrument_mem_access( bbOut, d->mAddr, dataSize, False/*!isStore*/, sizeofIRType(hWordTy) ); } } if (d->mFx == Ifx_Write || d->mFx == Ifx_Modify) { if (!inLDSO) { instrument_mem_access( bbOut, d->mAddr, dataSize, True/*isStore*/, sizeofIRType(hWordTy) ); } } } else { tl_assert(d->mAddr == NULL); tl_assert(d->mSize == 0); } break; } default: unhandled: ppIRStmt(st); tl_assert(0); } /* switch (st->tag) */ addStmtToIRSB( bbOut, st ); } /* iterate over bbIn->stmts */ return bbOut; } /*----------------------------------------------------------------*/ /*--- Client requests ---*/ /*----------------------------------------------------------------*/ /* Sheesh. Yet another goddam finite map. */ static WordFM* map_pthread_t_to_Thread = NULL; /* pthread_t -> Thread* */ static void map_pthread_t_to_Thread_INIT ( void ) { if (UNLIKELY(map_pthread_t_to_Thread == NULL)) { map_pthread_t_to_Thread = VG_(newFM)( HG_(zalloc), "hg.mpttT.1", HG_(free), NULL ); tl_assert(map_pthread_t_to_Thread != NULL); } } static Bool hg_handle_client_request ( ThreadId tid, UWord* args, UWord* ret) { if (!VG_IS_TOOL_USERREQ('H','G',args[0])) return False; /* Anything that gets past the above check is one of ours, so we should be able to handle it. */ /* default, meaningless return value, unless otherwise set */ *ret = 0; switch (args[0]) { /* --- --- User-visible client requests --- --- */ case VG_USERREQ__HG_CLEAN_MEMORY: if (0) VG_(printf)("VG_USERREQ__HG_CLEAN_MEMORY(%#lx,%ld)\n", args[1], args[2]); /* Call die_mem to (expensively) tidy up properly, if there are any held locks etc in the area. Calling evh__die_mem and then evh__new_mem is a bit inefficient; probably just the latter would do. */ if (args[2] > 0) { /* length */ evh__die_mem(args[1], args[2]); /* and then set it to New */ evh__new_mem(args[1], args[2]); } break; case _VG_USERREQ__HG_CLEAN_MEMORY_HEAPBLOCK: { Addr payload = 0; SizeT pszB = 0; if (0) VG_(printf)("VG_USERREQ__HG_CLEAN_MEMORY_HEAPBLOCK(%#lx)\n", args[1]); if (HG_(mm_find_containing_block)(NULL, &payload, &pszB, args[1])) { if (pszB > 0) { evh__die_mem(payload, pszB); evh__new_mem(payload, pszB); } *ret = pszB; } else { *ret = (UWord)-1; } break; } case _VG_USERREQ__HG_ARANGE_MAKE_UNTRACKED: if (0) VG_(printf)("HG_ARANGE_MAKE_UNTRACKED(%#lx,%ld)\n", args[1], args[2]); if (args[2] > 0) { /* length */ evh__untrack_mem(args[1], args[2]); } break; case _VG_USERREQ__HG_ARANGE_MAKE_TRACKED: if (0) VG_(printf)("HG_ARANGE_MAKE_TRACKED(%#lx,%ld)\n", args[1], args[2]); if (args[2] > 0) { /* length */ evh__new_mem(args[1], args[2]); } break; /* --- --- Client requests for Helgrind's use only --- --- */ /* Some thread is telling us its pthread_t value. Record the binding between that and the associated Thread*, so we can later find the Thread* again when notified of a join by the thread. */ case _VG_USERREQ__HG_SET_MY_PTHREAD_T: { Thread* my_thr = NULL; if (0) VG_(printf)("SET_MY_PTHREAD_T (tid %d): pthread_t = %p\n", (Int)tid, (void*)args[1]); map_pthread_t_to_Thread_INIT(); my_thr = map_threads_maybe_lookup( tid ); /* This assertion should hold because the map_threads (tid to Thread*) binding should have been made at the point of low-level creation of this thread, which should have happened prior to us getting this client request for it. That's because this client request is sent from client-world from the 'thread_wrapper' function, which only runs once the thread has been low-level created. */ tl_assert(my_thr != NULL); /* So now we know that (pthread_t)args[1] is associated with (Thread*)my_thr. Note that down. */ if (0) VG_(printf)("XXXX: bind pthread_t %p to Thread* %p\n", (void*)args[1], (void*)my_thr ); VG_(addToFM)( map_pthread_t_to_Thread, (Word)args[1], (Word)my_thr ); break; } case _VG_USERREQ__HG_PTH_API_ERROR: { Thread* my_thr = NULL; map_pthread_t_to_Thread_INIT(); my_thr = map_threads_maybe_lookup( tid ); tl_assert(my_thr); /* See justification above in SET_MY_PTHREAD_T */ HG_(record_error_PthAPIerror)( my_thr, (HChar*)args[1], (Word)args[2], (HChar*)args[3] ); break; } /* This thread (tid) has completed a join with the quitting thread whose pthread_t is in args[1]. */ case _VG_USERREQ__HG_PTHREAD_JOIN_POST: { Thread* thr_q = NULL; /* quitter Thread* */ Bool found = False; if (0) VG_(printf)("NOTIFY_JOIN_COMPLETE (tid %d): quitter = %p\n", (Int)tid, (void*)args[1]); map_pthread_t_to_Thread_INIT(); found = VG_(lookupFM)( map_pthread_t_to_Thread, NULL, (Word*)&thr_q, (Word)args[1] ); /* Can this fail? It would mean that our pthread_join wrapper observed a successful join on args[1] yet that thread never existed (or at least, it never lodged an entry in the mapping (via SET_MY_PTHREAD_T)). Which sounds like a bug in the threads library. */ // FIXME: get rid of this assertion; handle properly tl_assert(found); if (found) { if (0) VG_(printf)(".................... quitter Thread* = %p\n", thr_q); evh__HG_PTHREAD_JOIN_POST( tid, thr_q ); } break; } /* EXPOSITION only: by intercepting lock init events we can show the user where the lock was initialised, rather than only being able to show where it was first locked. Intercepting lock initialisations is not necessary for the basic operation of the race checker. */ case _VG_USERREQ__HG_PTHREAD_MUTEX_INIT_POST: evh__HG_PTHREAD_MUTEX_INIT_POST( tid, (void*)args[1], args[2] ); break; case _VG_USERREQ__HG_PTHREAD_MUTEX_DESTROY_PRE: evh__HG_PTHREAD_MUTEX_DESTROY_PRE( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_PTHREAD_MUTEX_UNLOCK_PRE: // pth_mx_t* evh__HG_PTHREAD_MUTEX_UNLOCK_PRE( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_PTHREAD_MUTEX_UNLOCK_POST: // pth_mx_t* evh__HG_PTHREAD_MUTEX_UNLOCK_POST( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_PTHREAD_MUTEX_LOCK_PRE: // pth_mx_t*, Word evh__HG_PTHREAD_MUTEX_LOCK_PRE( tid, (void*)args[1], args[2] ); break; case _VG_USERREQ__HG_PTHREAD_MUTEX_LOCK_POST: // pth_mx_t* evh__HG_PTHREAD_MUTEX_LOCK_POST( tid, (void*)args[1] ); break; /* This thread is about to do pthread_cond_signal on the pthread_cond_t* in arg[1]. Ditto pthread_cond_broadcast. */ case _VG_USERREQ__HG_PTHREAD_COND_SIGNAL_PRE: case _VG_USERREQ__HG_PTHREAD_COND_BROADCAST_PRE: evh__HG_PTHREAD_COND_SIGNAL_PRE( tid, (void*)args[1] ); break; /* Entry into pthread_cond_wait, cond=arg[1], mutex=arg[2]. Returns a flag indicating whether or not the mutex is believed to be valid for this operation. */ case _VG_USERREQ__HG_PTHREAD_COND_WAIT_PRE: { Bool mutex_is_valid = evh__HG_PTHREAD_COND_WAIT_PRE( tid, (void*)args[1], (void*)args[2] ); *ret = mutex_is_valid ? 1 : 0; break; } /* cond=arg[1] */ case _VG_USERREQ__HG_PTHREAD_COND_DESTROY_PRE: evh__HG_PTHREAD_COND_DESTROY_PRE( tid, (void*)args[1] ); break; /* Thread successfully completed pthread_cond_wait, cond=arg[1], mutex=arg[2] */ case _VG_USERREQ__HG_PTHREAD_COND_WAIT_POST: evh__HG_PTHREAD_COND_WAIT_POST( tid, (void*)args[1], (void*)args[2] ); break; case _VG_USERREQ__HG_PTHREAD_RWLOCK_INIT_POST: evh__HG_PTHREAD_RWLOCK_INIT_POST( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_PTHREAD_RWLOCK_DESTROY_PRE: evh__HG_PTHREAD_RWLOCK_DESTROY_PRE( tid, (void*)args[1] ); break; /* rwlock=arg[1], isW=arg[2], isTryLock=arg[3] */ case _VG_USERREQ__HG_PTHREAD_RWLOCK_LOCK_PRE: evh__HG_PTHREAD_RWLOCK_LOCK_PRE( tid, (void*)args[1], args[2], args[3] ); break; /* rwlock=arg[1], isW=arg[2] */ case _VG_USERREQ__HG_PTHREAD_RWLOCK_LOCK_POST: evh__HG_PTHREAD_RWLOCK_LOCK_POST( tid, (void*)args[1], args[2] ); break; case _VG_USERREQ__HG_PTHREAD_RWLOCK_UNLOCK_PRE: evh__HG_PTHREAD_RWLOCK_UNLOCK_PRE( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_PTHREAD_RWLOCK_UNLOCK_POST: evh__HG_PTHREAD_RWLOCK_UNLOCK_POST( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_POSIX_SEM_INIT_POST: /* sem_t*, unsigned long */ evh__HG_POSIX_SEM_INIT_POST( tid, (void*)args[1], args[2] ); break; case _VG_USERREQ__HG_POSIX_SEM_DESTROY_PRE: /* sem_t* */ evh__HG_POSIX_SEM_DESTROY_PRE( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_POSIX_SEM_POST_PRE: /* sem_t* */ evh__HG_POSIX_SEM_POST_PRE( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_POSIX_SEM_WAIT_POST: /* sem_t* */ evh__HG_POSIX_SEM_WAIT_POST( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_PTHREAD_BARRIER_INIT_PRE: /* pth_bar_t*, ulong count, ulong resizable */ evh__HG_PTHREAD_BARRIER_INIT_PRE( tid, (void*)args[1], args[2], args[3] ); break; case _VG_USERREQ__HG_PTHREAD_BARRIER_RESIZE_PRE: /* pth_bar_t*, ulong newcount */ evh__HG_PTHREAD_BARRIER_RESIZE_PRE ( tid, (void*)args[1], args[2] ); break; case _VG_USERREQ__HG_PTHREAD_BARRIER_WAIT_PRE: /* pth_bar_t* */ evh__HG_PTHREAD_BARRIER_WAIT_PRE( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_PTHREAD_BARRIER_DESTROY_PRE: /* pth_bar_t* */ evh__HG_PTHREAD_BARRIER_DESTROY_PRE( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_PTHREAD_SPIN_INIT_OR_UNLOCK_PRE: /* pth_spinlock_t* */ evh__HG_PTHREAD_SPIN_INIT_OR_UNLOCK_PRE( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_PTHREAD_SPIN_INIT_OR_UNLOCK_POST: /* pth_spinlock_t* */ evh__HG_PTHREAD_SPIN_INIT_OR_UNLOCK_POST( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_PTHREAD_SPIN_LOCK_PRE: /* pth_spinlock_t*, Word */ evh__HG_PTHREAD_SPIN_LOCK_PRE( tid, (void*)args[1], args[2] ); break; case _VG_USERREQ__HG_PTHREAD_SPIN_LOCK_POST: /* pth_spinlock_t* */ evh__HG_PTHREAD_SPIN_LOCK_POST( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_PTHREAD_SPIN_DESTROY_PRE: /* pth_spinlock_t* */ evh__HG_PTHREAD_SPIN_DESTROY_PRE( tid, (void*)args[1] ); break; case _VG_USERREQ__HG_CLIENTREQ_UNIMP: { /* char* who */ HChar* who = (HChar*)args[1]; HChar buf[50 + 50]; Thread* thr = map_threads_maybe_lookup( tid ); tl_assert( thr ); /* I must be mapped */ tl_assert( who ); tl_assert( VG_(strlen)(who) <= 50 ); VG_(sprintf)(buf, "Unimplemented client request macro \"%s\"", who ); /* record_error_Misc strdup's buf, so this is safe: */ HG_(record_error_Misc)( thr, buf ); break; } case _VG_USERREQ__HG_USERSO_SEND_PRE: /* UWord arbitrary-SO-tag */ evh__HG_USERSO_SEND_PRE( tid, args[1] ); break; case _VG_USERREQ__HG_USERSO_RECV_POST: /* UWord arbitrary-SO-tag */ evh__HG_USERSO_RECV_POST( tid, args[1] ); break; default: /* Unhandled Helgrind client request! */ tl_assert2(0, "unhandled Helgrind client request 0x%lx", args[0]); } return True; } /*----------------------------------------------------------------*/ /*--- Setup ---*/ /*----------------------------------------------------------------*/ static Bool hg_process_cmd_line_option ( Char* arg ) { Char* tmp_str; if VG_BOOL_CLO(arg, "--track-lockorders", HG_(clo_track_lockorders)) {} else if VG_BOOL_CLO(arg, "--cmp-race-err-addrs", HG_(clo_cmp_race_err_addrs)) {} else if VG_XACT_CLO(arg, "--history-level=none", HG_(clo_history_level), 0); else if VG_XACT_CLO(arg, "--history-level=approx", HG_(clo_history_level), 1); else if VG_XACT_CLO(arg, "--history-level=full", HG_(clo_history_level), 2); /* If you change the 10k/30mill limits, remember to also change them in assertions at the top of event_map_maybe_GC. */ else if VG_BINT_CLO(arg, "--conflict-cache-size", HG_(clo_conflict_cache_size), 10*1000, 30*1000*1000) {} /* "stuvwx" --> stuvwx (binary) */ else if VG_STR_CLO(arg, "--hg-sanity-flags", tmp_str) { Int j; if (6 != VG_(strlen)(tmp_str)) { VG_(message)(Vg_UserMsg, "--hg-sanity-flags argument must have 6 digits\n"); return False; } for (j = 0; j < 6; j++) { if ('0' == tmp_str[j]) { /* do nothing */ } else if ('1' == tmp_str[j]) HG_(clo_sanity_flags) |= (1 << (6-1-j)); else { VG_(message)(Vg_UserMsg, "--hg-sanity-flags argument can " "only contain 0s and 1s\n"); return False; } } if (0) VG_(printf)("XXX sanity flags: 0x%lx\n", HG_(clo_sanity_flags)); } else return VG_(replacement_malloc_process_cmd_line_option)(arg); return True; } static void hg_print_usage ( void ) { VG_(printf)( " --track-lockorders=no|yes show lock ordering errors? [yes]\n" " --history-level=none|approx|full [full]\n" " full: show both stack traces for a data race (can be very slow)\n" " approx: full trace for one thread, approx for the other (faster)\n" " none: only show trace for one thread in a race (fastest)\n" " --conflict-cache-size=N size of 'full' history cache [1000000]\n" ); } static void hg_print_debug_usage ( void ) { VG_(printf)(" --cmp-race-err-addrs=no|yes are data addresses in " "race errors significant? [no]\n"); VG_(printf)(" --hg-sanity-flags=<XXXXXX> sanity check " " at events (X = 0|1) [000000]\n"); VG_(printf)(" --hg-sanity-flags values:\n"); VG_(printf)(" 010000 after changes to " "lock-order-acquisition-graph\n"); VG_(printf)(" 001000 at memory accesses (NB: not currently used)\n"); VG_(printf)(" 000100 at mem permission setting for " "ranges >= %d bytes\n", SCE_BIGRANGE_T); VG_(printf)(" 000010 at lock/unlock events\n"); VG_(printf)(" 000001 at thread create/join events\n"); } static void hg_fini ( Int exitcode ) { if (VG_(clo_verbosity) == 1 && !VG_(clo_xml)) { VG_(message)(Vg_UserMsg, "For counts of detected and suppressed errors, " "rerun with: -v\n"); } if (VG_(clo_verbosity) == 1 && !VG_(clo_xml) && HG_(clo_history_level) >= 2) { VG_(umsg)( "Use --history-level=approx or =none to gain increased speed, at\n" ); VG_(umsg)( "the cost of reduced accuracy of conflicting-access information\n"); } if (SHOW_DATA_STRUCTURES) pp_everything( PP_ALL, "SK_(fini)" ); if (HG_(clo_sanity_flags)) all__sanity_check("SK_(fini)"); if (VG_(clo_stats)) { if (1) { VG_(printf)("\n"); HG_(ppWSUstats)( univ_lsets, "univ_lsets" ); if (HG_(clo_track_lockorders)) { VG_(printf)("\n"); HG_(ppWSUstats)( univ_laog, "univ_laog" ); } } //zz VG_(printf)("\n"); //zz VG_(printf)(" hbefore: %'10lu queries\n", stats__hbefore_queries); //zz VG_(printf)(" hbefore: %'10lu cache 0 hits\n", stats__hbefore_cache0s); //zz VG_(printf)(" hbefore: %'10lu cache > 0 hits\n", stats__hbefore_cacheNs); //zz VG_(printf)(" hbefore: %'10lu graph searches\n", stats__hbefore_gsearches); //zz VG_(printf)(" hbefore: %'10lu of which slow\n", //zz stats__hbefore_gsearches - stats__hbefore_gsearchFs); //zz VG_(printf)(" hbefore: %'10lu stack high water mark\n", //zz stats__hbefore_stk_hwm); //zz VG_(printf)(" hbefore: %'10lu cache invals\n", stats__hbefore_invals); //zz VG_(printf)(" hbefore: %'10lu probes\n", stats__hbefore_probes); VG_(printf)("\n"); VG_(printf)(" locksets: %'8d unique lock sets\n", (Int)HG_(cardinalityWSU)( univ_lsets )); if (HG_(clo_track_lockorders)) { VG_(printf)(" univ_laog: %'8d unique lock sets\n", (Int)HG_(cardinalityWSU)( univ_laog )); } //VG_(printf)("L(ast)L(ock) map: %'8lu inserts (%d map size)\n", // stats__ga_LL_adds, // (Int)(ga_to_lastlock ? VG_(sizeFM)( ga_to_lastlock ) : 0) ); VG_(printf)(" LockN-to-P map: %'8llu queries (%llu map size)\n", HG_(stats__LockN_to_P_queries), HG_(stats__LockN_to_P_get_map_size)() ); VG_(printf)("string table map: %'8llu queries (%llu map size)\n", HG_(stats__string_table_queries), HG_(stats__string_table_get_map_size)() ); if (HG_(clo_track_lockorders)) { VG_(printf)(" LAOG: %'8d map size\n", (Int)(laog ? VG_(sizeFM)( laog ) : 0)); VG_(printf)(" LAOG exposition: %'8d map size\n", (Int)(laog_exposition ? VG_(sizeFM)( laog_exposition ) : 0)); } VG_(printf)(" locks: %'8lu acquires, " "%'lu releases\n", stats__lockN_acquires, stats__lockN_releases ); VG_(printf)(" sanity checks: %'8lu\n", stats__sanity_checks); VG_(printf)("\n"); libhb_shutdown(True); } } /* FIXME: move these somewhere sane */ static void for_libhb__get_stacktrace ( Thr* hbt, Addr* frames, UWord nRequest ) { Thread* thr; ThreadId tid; UWord nActual; tl_assert(hbt); thr = libhb_get_Thr_hgthread( hbt ); tl_assert(thr); tid = map_threads_maybe_reverse_lookup_SLOW(thr); nActual = (UWord)VG_(get_StackTrace)( tid, frames, (UInt)nRequest, NULL, NULL, 0 ); tl_assert(nActual <= nRequest); for (; nActual < nRequest; nActual++) frames[nActual] = 0; } static ExeContext* for_libhb__get_EC ( Thr* hbt ) { Thread* thr; ThreadId tid; ExeContext* ec; tl_assert(hbt); thr = libhb_get_Thr_hgthread( hbt ); tl_assert(thr); tid = map_threads_maybe_reverse_lookup_SLOW(thr); /* this will assert if tid is invalid */ ec = VG_(record_ExeContext)( tid, 0 ); return ec; } static void hg_post_clo_init ( void ) { Thr* hbthr_root; ///////////////////////////////////////////// hbthr_root = libhb_init( for_libhb__get_stacktrace, for_libhb__get_EC ); ///////////////////////////////////////////// if (HG_(clo_track_lockorders)) laog__init(); initialise_data_structures(hbthr_root); } static void hg_pre_clo_init ( void ) { VG_(details_name) ("Helgrind"); VG_(details_version) (NULL); VG_(details_description) ("a thread error detector"); VG_(details_copyright_author)( "Copyright (C) 2007-2010, and GNU GPL'd, by OpenWorks LLP et al."); VG_(details_bug_reports_to) (VG_BUGS_TO); VG_(details_avg_translation_sizeB) ( 320 ); VG_(basic_tool_funcs) (hg_post_clo_init, hg_instrument, hg_fini); VG_(needs_core_errors) (); VG_(needs_tool_errors) (HG_(eq_Error), HG_(before_pp_Error), HG_(pp_Error), False,/*show TIDs for errors*/ HG_(update_extra), HG_(recognised_suppression), HG_(read_extra_suppression_info), HG_(error_matches_suppression), HG_(get_error_name), HG_(get_extra_suppression_info)); VG_(needs_xml_output) (); VG_(needs_command_line_options)(hg_process_cmd_line_option, hg_print_usage, hg_print_debug_usage); VG_(needs_client_requests) (hg_handle_client_request); // FIXME? //VG_(needs_sanity_checks) (hg_cheap_sanity_check, // hg_expensive_sanity_check); VG_(needs_malloc_replacement) (hg_cli__malloc, hg_cli____builtin_new, hg_cli____builtin_vec_new, hg_cli__memalign, hg_cli__calloc, hg_cli__free, hg_cli____builtin_delete, hg_cli____builtin_vec_delete, hg_cli__realloc, hg_cli_malloc_usable_size, HG_CLI__MALLOC_REDZONE_SZB ); /* 21 Dec 08: disabled this; it mostly causes H to start more slowly and use significantly more memory, without very often providing useful results. The user can request to load this information manually with --read-var-info=yes. */ if (0) VG_(needs_var_info)(); /* optional */ VG_(track_new_mem_startup) ( evh__new_mem_w_perms ); VG_(track_new_mem_stack_signal)( evh__new_mem_w_tid ); VG_(track_new_mem_brk) ( evh__new_mem_w_tid ); VG_(track_new_mem_mmap) ( evh__new_mem_w_perms ); VG_(track_new_mem_stack) ( evh__new_mem_stack ); // FIXME: surely this isn't thread-aware VG_(track_copy_mem_remap) ( evh__copy_mem ); VG_(track_change_mem_mprotect) ( evh__set_perms ); VG_(track_die_mem_stack_signal)( evh__die_mem ); VG_(track_die_mem_brk) ( evh__die_mem ); VG_(track_die_mem_munmap) ( evh__die_mem ); VG_(track_die_mem_stack) ( evh__die_mem ); // FIXME: what is this for? VG_(track_ban_mem_stack) (NULL); VG_(track_pre_mem_read) ( evh__pre_mem_read ); VG_(track_pre_mem_read_asciiz) ( evh__pre_mem_read_asciiz ); VG_(track_pre_mem_write) ( evh__pre_mem_write ); VG_(track_post_mem_write) (NULL); ///////////////// VG_(track_pre_thread_ll_create)( evh__pre_thread_ll_create ); VG_(track_pre_thread_ll_exit) ( evh__pre_thread_ll_exit ); VG_(track_start_client_code)( evh__start_client_code ); VG_(track_stop_client_code)( evh__stop_client_code ); /* Ensure that requirements for "dodgy C-as-C++ style inheritance" as described in comments at the top of pub_tool_hashtable.h, are met. Blargh. */ tl_assert( sizeof(void*) == sizeof(struct _MallocMeta*) ); tl_assert( sizeof(UWord) == sizeof(Addr) ); hg_mallocmeta_table = VG_(HT_construct)( "hg_malloc_metadata_table" ); // add a callback to clean up on (threaded) fork. VG_(atfork)(NULL/*pre*/, NULL/*parent*/, evh__atfork_child/*child*/); } VG_DETERMINE_INTERFACE_VERSION(hg_pre_clo_init) /*--------------------------------------------------------------------*/ /*--- end hg_main.c ---*/ /*--------------------------------------------------------------------*/
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/valgrind_11623-11624.c
manybugs_data_69
/* An implementation of Buffered I/O as defined by PEP 3116 - "New I/O" Classes defined here: BufferedIOBase, BufferedReader, BufferedWriter, BufferedRandom. Written by Amaury Forgeot d'Arc and Antoine Pitrou */ #define PY_SSIZE_T_CLEAN #include "Python.h" #include "structmember.h" #include "pythread.h" #include "_iomodule.h" /* * BufferedIOBase class, inherits from IOBase. */ PyDoc_STRVAR(bufferediobase_doc, "Base class for buffered IO objects.\n" "\n" "The main difference with RawIOBase is that the read() method\n" "supports omitting the size argument, and does not have a default\n" "implementation that defers to readinto().\n" "\n" "In addition, read(), readinto() and write() may raise\n" "BlockingIOError if the underlying raw stream is in non-blocking\n" "mode and not ready; unlike their raw counterparts, they will never\n" "return None.\n" "\n" "A typical implementation should not inherit from a RawIOBase\n" "implementation, but wrap one.\n" ); static PyObject * bufferediobase_readinto(PyObject *self, PyObject *args) { Py_buffer buf; Py_ssize_t len; PyObject *data; if (!PyArg_ParseTuple(args, "w*:readinto", &buf)) { return NULL; } data = PyObject_CallMethod(self, "read", "n", buf.len); if (data == NULL) goto error; if (!PyBytes_Check(data)) { Py_DECREF(data); PyErr_SetString(PyExc_TypeError, "read() should return bytes"); goto error; } len = Py_SIZE(data); memcpy(buf.buf, PyBytes_AS_STRING(data), len); PyBuffer_Release(&buf); Py_DECREF(data); return PyLong_FromSsize_t(len); error: PyBuffer_Release(&buf); return NULL; } static PyObject * bufferediobase_unsupported(const char *message) { PyErr_SetString(IO_STATE->unsupported_operation, message); return NULL; } PyDoc_STRVAR(bufferediobase_detach_doc, "Disconnect this buffer from its underlying raw stream and return it.\n" "\n" "After the raw stream has been detached, the buffer is in an unusable\n" "state.\n"); static PyObject * bufferediobase_detach(PyObject *self) { return bufferediobase_unsupported("detach"); } PyDoc_STRVAR(bufferediobase_read_doc, "Read and return up to n bytes.\n" "\n" "If the argument is omitted, None, or negative, reads and\n" "returns all data until EOF.\n" "\n" "If the argument is positive, and the underlying raw stream is\n" "not 'interactive', multiple raw reads may be issued to satisfy\n" "the byte count (unless EOF is reached first). But for\n" "interactive raw streams (as well as sockets and pipes), at most\n" "one raw read will be issued, and a short result does not imply\n" "that EOF is imminent.\n" "\n" "Returns an empty bytes object on EOF.\n" "\n" "Returns None if the underlying raw stream was open in non-blocking\n" "mode and no data is available at the moment.\n"); static PyObject * bufferediobase_read(PyObject *self, PyObject *args) { return bufferediobase_unsupported("read"); } PyDoc_STRVAR(bufferediobase_read1_doc, "Read and return up to n bytes, with at most one read() call\n" "to the underlying raw stream. A short result does not imply\n" "that EOF is imminent.\n" "\n" "Returns an empty bytes object on EOF.\n"); static PyObject * bufferediobase_read1(PyObject *self, PyObject *args) { return bufferediobase_unsupported("read1"); } PyDoc_STRVAR(bufferediobase_write_doc, "Write the given buffer to the IO stream.\n" "\n" "Returns the number of bytes written, which is never less than\n" "len(b).\n" "\n" "Raises BlockingIOError if the buffer is full and the\n" "underlying raw stream cannot accept more data at the moment.\n"); static PyObject * bufferediobase_write(PyObject *self, PyObject *args) { return bufferediobase_unsupported("write"); } static PyMethodDef bufferediobase_methods[] = { {"detach", (PyCFunction)bufferediobase_detach, METH_NOARGS, bufferediobase_detach_doc}, {"read", bufferediobase_read, METH_VARARGS, bufferediobase_read_doc}, {"read1", bufferediobase_read1, METH_VARARGS, bufferediobase_read1_doc}, {"readinto", bufferediobase_readinto, METH_VARARGS, NULL}, {"write", bufferediobase_write, METH_VARARGS, bufferediobase_write_doc}, {NULL, NULL} }; PyTypeObject PyBufferedIOBase_Type = { PyVarObject_HEAD_INIT(NULL, 0) "_io._BufferedIOBase", /*tp_name*/ 0, /*tp_basicsize*/ 0, /*tp_itemsize*/ 0, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare */ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ bufferediobase_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ bufferediobase_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ &PyIOBase_Type, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; typedef struct { PyObject_HEAD PyObject *raw; int ok; /* Initialized? */ int detached; int readable; int writable; int deallocating; /* True if this is a vanilla Buffered object (rather than a user derived class) *and* the raw stream is a vanilla FileIO object. */ int fast_closed_checks; /* Absolute position inside the raw stream (-1 if unknown). */ Py_off_t abs_pos; /* A static buffer of size `buffer_size` */ char *buffer; /* Current logical position in the buffer. */ Py_off_t pos; /* Position of the raw stream in the buffer. */ Py_off_t raw_pos; /* Just after the last buffered byte in the buffer, or -1 if the buffer isn't ready for reading. */ Py_off_t read_end; /* Just after the last byte actually written */ Py_off_t write_pos; /* Just after the last byte waiting to be written, or -1 if the buffer isn't ready for writing. */ Py_off_t write_end; #ifdef WITH_THREAD PyThread_type_lock lock; volatile long owner; #endif Py_ssize_t buffer_size; Py_ssize_t buffer_mask; PyObject *dict; PyObject *weakreflist; } buffered; /* Implementation notes: * BufferedReader, BufferedWriter and BufferedRandom try to share most methods (this is helped by the members `readable` and `writable`, which are initialized in the respective constructors) * They also share a single buffer for reading and writing. This enables interleaved reads and writes without flushing. It also makes the logic a bit trickier to get right. * The absolute position of the raw stream is cached, if possible, in the `abs_pos` member. It must be updated every time an operation is done on the raw stream. If not sure, it can be reinitialized by calling _buffered_raw_tell(), which queries the raw stream (_buffered_raw_seek() also does it). To read it, use RAW_TELL(). * Three helpers, _bufferedreader_raw_read, _bufferedwriter_raw_write and _bufferedwriter_flush_unlocked do a lot of useful housekeeping. NOTE: we should try to maintain block alignment of reads and writes to the raw stream (according to the buffer size), but for now it is only done in read() and friends. */ /* These macros protect the buffered object against concurrent operations. */ #ifdef WITH_THREAD static int _enter_buffered_busy(buffered *self) { if (self->owner == PyThread_get_thread_ident()) { PyErr_Format(PyExc_RuntimeError, "reentrant call inside %R", self); return 0; } Py_BEGIN_ALLOW_THREADS PyThread_acquire_lock(self->lock, 1); Py_END_ALLOW_THREADS return 1; } #define ENTER_BUFFERED(self) \ ( (PyThread_acquire_lock(self->lock, 0) ? \ 1 : _enter_buffered_busy(self)) \ && (self->owner = PyThread_get_thread_ident(), 1) ) #define LEAVE_BUFFERED(self) \ do { \ self->owner = 0; \ PyThread_release_lock(self->lock); \ } while(0); #else #define ENTER_BUFFERED(self) 1 #define LEAVE_BUFFERED(self) #endif #define CHECK_INITIALIZED(self) \ if (self->ok <= 0) { \ if (self->detached) { \ PyErr_SetString(PyExc_ValueError, \ "raw stream has been detached"); \ } else { \ PyErr_SetString(PyExc_ValueError, \ "I/O operation on uninitialized object"); \ } \ return NULL; \ } #define CHECK_INITIALIZED_INT(self) \ if (self->ok <= 0) { \ if (self->detached) { \ PyErr_SetString(PyExc_ValueError, \ "raw stream has been detached"); \ } else { \ PyErr_SetString(PyExc_ValueError, \ "I/O operation on uninitialized object"); \ } \ return -1; \ } #define IS_CLOSED(self) \ (self->fast_closed_checks \ ? _PyFileIO_closed(self->raw) \ : buffered_closed(self)) #define CHECK_CLOSED(self, error_msg) \ if (IS_CLOSED(self)) { \ PyErr_SetString(PyExc_ValueError, error_msg); \ return NULL; \ } #define VALID_READ_BUFFER(self) \ (self->readable && self->read_end != -1) #define VALID_WRITE_BUFFER(self) \ (self->writable && self->write_end != -1) #define ADJUST_POSITION(self, _new_pos) \ do { \ self->pos = _new_pos; \ if (VALID_READ_BUFFER(self) && self->read_end < self->pos) \ self->read_end = self->pos; \ } while(0) #define READAHEAD(self) \ ((self->readable && VALID_READ_BUFFER(self)) \ ? (self->read_end - self->pos) : 0) #define RAW_OFFSET(self) \ (((VALID_READ_BUFFER(self) || VALID_WRITE_BUFFER(self)) \ && self->raw_pos >= 0) ? self->raw_pos - self->pos : 0) #define RAW_TELL(self) \ (self->abs_pos != -1 ? self->abs_pos : _buffered_raw_tell(self)) #define MINUS_LAST_BLOCK(self, size) \ (self->buffer_mask ? \ (size & ~self->buffer_mask) : \ (self->buffer_size * (size / self->buffer_size))) static void buffered_dealloc(buffered *self) { self->deallocating = 1; if (self->ok && _PyIOBase_finalize((PyObject *) self) < 0) return; _PyObject_GC_UNTRACK(self); self->ok = 0; if (self->weakreflist != NULL) PyObject_ClearWeakRefs((PyObject *)self); Py_CLEAR(self->raw); if (self->buffer) { PyMem_Free(self->buffer); self->buffer = NULL; } #ifdef WITH_THREAD if (self->lock) { PyThread_free_lock(self->lock); self->lock = NULL; } #endif Py_CLEAR(self->dict); Py_TYPE(self)->tp_free((PyObject *)self); } static int buffered_traverse(buffered *self, visitproc visit, void *arg) { Py_VISIT(self->raw); Py_VISIT(self->dict); return 0; } static int buffered_clear(buffered *self) { if (self->ok && _PyIOBase_finalize((PyObject *) self) < 0) return -1; self->ok = 0; Py_CLEAR(self->raw); Py_CLEAR(self->dict); return 0; } /* Because this can call arbitrary code, it shouldn't be called when the refcount is 0 (that is, not directly from tp_dealloc unless the refcount has been temporarily re-incremented). */ static PyObject * buffered_dealloc_warn(buffered *self, PyObject *source) { if (self->ok && self->raw) { PyObject *r; r = PyObject_CallMethod(self->raw, "_dealloc_warn", "O", source); if (r) Py_DECREF(r); else PyErr_Clear(); } Py_RETURN_NONE; } /* * _BufferedIOMixin methods * This is not a class, just a collection of methods that will be reused * by BufferedReader and BufferedWriter */ /* Flush and close */ static PyObject * buffered_simple_flush(buffered *self, PyObject *args) { CHECK_INITIALIZED(self) return PyObject_CallMethodObjArgs(self->raw, _PyIO_str_flush, NULL); } static int buffered_closed(buffered *self) { int closed; PyObject *res; CHECK_INITIALIZED_INT(self) res = PyObject_GetAttr(self->raw, _PyIO_str_closed); if (res == NULL) return -1; closed = PyObject_IsTrue(res); Py_DECREF(res); return closed; } static PyObject * buffered_closed_get(buffered *self, void *context) { CHECK_INITIALIZED(self) return PyObject_GetAttr(self->raw, _PyIO_str_closed); } static PyObject * buffered_close(buffered *self, PyObject *args) { PyObject *res = NULL; int r; CHECK_INITIALIZED(self) if (!ENTER_BUFFERED(self)) return NULL; r = buffered_closed(self); if (r < 0) goto end; if (r > 0) { res = Py_None; Py_INCREF(res); goto end; } if (self->deallocating) { PyObject *r = buffered_dealloc_warn(self, (PyObject *) self); if (r) Py_DECREF(r); else PyErr_Clear(); } /* flush() will most probably re-take the lock, so drop it first */ LEAVE_BUFFERED(self) res = PyObject_CallMethodObjArgs((PyObject *)self, _PyIO_str_flush, NULL); if (!ENTER_BUFFERED(self)) return NULL; if (res == NULL) { goto end; } Py_XDECREF(res); res = PyObject_CallMethodObjArgs(self->raw, _PyIO_str_close, NULL); end: LEAVE_BUFFERED(self) return res; } /* detach */ static PyObject * buffered_detach(buffered *self, PyObject *args) { PyObject *raw, *res; CHECK_INITIALIZED(self) res = PyObject_CallMethodObjArgs((PyObject *)self, _PyIO_str_flush, NULL); if (res == NULL) return NULL; Py_DECREF(res); raw = self->raw; self->raw = NULL; self->detached = 1; self->ok = 0; return raw; } /* Inquiries */ static PyObject * buffered_seekable(buffered *self, PyObject *args) { CHECK_INITIALIZED(self) return PyObject_CallMethodObjArgs(self->raw, _PyIO_str_seekable, NULL); } static PyObject * buffered_readable(buffered *self, PyObject *args) { CHECK_INITIALIZED(self) return PyObject_CallMethodObjArgs(self->raw, _PyIO_str_readable, NULL); } static PyObject * buffered_writable(buffered *self, PyObject *args) { CHECK_INITIALIZED(self) return PyObject_CallMethodObjArgs(self->raw, _PyIO_str_writable, NULL); } static PyObject * buffered_name_get(buffered *self, void *context) { CHECK_INITIALIZED(self) return PyObject_GetAttrString(self->raw, "name"); } static PyObject * buffered_mode_get(buffered *self, void *context) { CHECK_INITIALIZED(self) return PyObject_GetAttrString(self->raw, "mode"); } /* Lower-level APIs */ static PyObject * buffered_fileno(buffered *self, PyObject *args) { CHECK_INITIALIZED(self) return PyObject_CallMethodObjArgs(self->raw, _PyIO_str_fileno, NULL); } static PyObject * buffered_isatty(buffered *self, PyObject *args) { CHECK_INITIALIZED(self) return PyObject_CallMethodObjArgs(self->raw, _PyIO_str_isatty, NULL); } /* Serialization */ static PyObject * buffered_getstate(buffered *self, PyObject *args) { PyErr_Format(PyExc_TypeError, "cannot serialize '%s' object", Py_TYPE(self)->tp_name); return NULL; } /* Forward decls */ static PyObject * _bufferedwriter_flush_unlocked(buffered *, int); static Py_ssize_t _bufferedreader_fill_buffer(buffered *self); static void _bufferedreader_reset_buf(buffered *self); static void _bufferedwriter_reset_buf(buffered *self); static PyObject * _bufferedreader_peek_unlocked(buffered *self, Py_ssize_t); static PyObject * _bufferedreader_read_all(buffered *self); static PyObject * _bufferedreader_read_fast(buffered *self, Py_ssize_t); static PyObject * _bufferedreader_read_generic(buffered *self, Py_ssize_t); static Py_ssize_t _bufferedreader_raw_read(buffered *self, char *start, Py_ssize_t len); /* * Helpers */ /* Returns the address of the `written` member if a BlockingIOError was raised, NULL otherwise. The error is always re-raised. */ static Py_ssize_t * _buffered_check_blocking_error(void) { PyObject *t, *v, *tb; PyBlockingIOErrorObject *err; PyErr_Fetch(&t, &v, &tb); if (v == NULL || !PyErr_GivenExceptionMatches(v, PyExc_BlockingIOError)) { PyErr_Restore(t, v, tb); return NULL; } err = (PyBlockingIOErrorObject *) v; /* TODO: sanity check (err->written >= 0) */ PyErr_Restore(t, v, tb); return &err->written; } static Py_off_t _buffered_raw_tell(buffered *self) { Py_off_t n; PyObject *res; res = PyObject_CallMethodObjArgs(self->raw, _PyIO_str_tell, NULL); if (res == NULL) return -1; n = PyNumber_AsOff_t(res, PyExc_ValueError); Py_DECREF(res); if (n < 0) { if (!PyErr_Occurred()) PyErr_Format(PyExc_IOError, "Raw stream returned invalid position %" PY_PRIdOFF, (PY_OFF_T_COMPAT)n); return -1; } self->abs_pos = n; return n; } static Py_off_t _buffered_raw_seek(buffered *self, Py_off_t target, int whence) { PyObject *res, *posobj, *whenceobj; Py_off_t n; posobj = PyLong_FromOff_t(target); if (posobj == NULL) return -1; whenceobj = PyLong_FromLong(whence); if (whenceobj == NULL) { Py_DECREF(posobj); return -1; } res = PyObject_CallMethodObjArgs(self->raw, _PyIO_str_seek, posobj, whenceobj, NULL); Py_DECREF(posobj); Py_DECREF(whenceobj); if (res == NULL) return -1; n = PyNumber_AsOff_t(res, PyExc_ValueError); Py_DECREF(res); if (n < 0) { if (!PyErr_Occurred()) PyErr_Format(PyExc_IOError, "Raw stream returned invalid position %" PY_PRIdOFF, (PY_OFF_T_COMPAT)n); return -1; } self->abs_pos = n; return n; } static int _buffered_init(buffered *self) { Py_ssize_t n; if (self->buffer_size <= 0) { PyErr_SetString(PyExc_ValueError, "buffer size must be strictly positive"); return -1; } if (self->buffer) PyMem_Free(self->buffer); self->buffer = PyMem_Malloc(self->buffer_size); if (self->buffer == NULL) { PyErr_NoMemory(); return -1; } #ifdef WITH_THREAD if (self->lock) PyThread_free_lock(self->lock); self->lock = PyThread_allocate_lock(); if (self->lock == NULL) { PyErr_SetString(PyExc_RuntimeError, "can't allocate read lock"); return -1; } self->owner = 0; #endif /* Find out whether buffer_size is a power of 2 */ /* XXX is this optimization useful? */ for (n = self->buffer_size - 1; n & 1; n >>= 1) ; if (n == 0) self->buffer_mask = self->buffer_size - 1; else self->buffer_mask = 0; if (_buffered_raw_tell(self) == -1) PyErr_Clear(); return 0; } /* Return 1 if an EnvironmentError with errno == EINTR is set (and then clears the error indicator), 0 otherwise. Should only be called when PyErr_Occurred() is true. */ static int _trap_eintr(void) { static PyObject *eintr_int = NULL; PyObject *typ, *val, *tb; PyEnvironmentErrorObject *env_err; if (eintr_int == NULL) { eintr_int = PyLong_FromLong(EINTR); assert(eintr_int != NULL); } if (!PyErr_ExceptionMatches(PyExc_EnvironmentError)) return 0; PyErr_Fetch(&typ, &val, &tb); PyErr_NormalizeException(&typ, &val, &tb); env_err = (PyEnvironmentErrorObject *) val; assert(env_err != NULL); if (env_err->myerrno != NULL && PyObject_RichCompareBool(env_err->myerrno, eintr_int, Py_EQ) > 0) { Py_DECREF(typ); Py_DECREF(val); Py_XDECREF(tb); return 1; } /* This silences any error set by PyObject_RichCompareBool() */ PyErr_Restore(typ, val, tb); return 0; } /* * Shared methods and wrappers */ static PyObject * buffered_flush(buffered *self, PyObject *args) { PyObject *res; CHECK_INITIALIZED(self) CHECK_CLOSED(self, "flush of closed file") if (!ENTER_BUFFERED(self)) return NULL; res = _bufferedwriter_flush_unlocked(self, 0); if (res != NULL && self->readable) { /* Rewind the raw stream so that its position corresponds to the current logical position. */ Py_off_t n; n = _buffered_raw_seek(self, -RAW_OFFSET(self), 1); if (n == -1) Py_CLEAR(res); _bufferedreader_reset_buf(self); } LEAVE_BUFFERED(self) return res; } static PyObject * buffered_peek(buffered *self, PyObject *args) { Py_ssize_t n = 0; PyObject *res = NULL; CHECK_INITIALIZED(self) if (!PyArg_ParseTuple(args, "|n:peek", &n)) { return NULL; } if (!ENTER_BUFFERED(self)) return NULL; if (self->writable) { res = _bufferedwriter_flush_unlocked(self, 1); if (res == NULL) goto end; Py_CLEAR(res); } res = _bufferedreader_peek_unlocked(self, n); end: LEAVE_BUFFERED(self) return res; } static PyObject * buffered_read(buffered *self, PyObject *args) { Py_ssize_t n = -1; PyObject *res; CHECK_INITIALIZED(self) if (!PyArg_ParseTuple(args, "|O&:read", &_PyIO_ConvertSsize_t, &n)) { return NULL; } if (n < -1) { PyErr_SetString(PyExc_ValueError, "read length must be positive or -1"); return NULL; } CHECK_CLOSED(self, "read of closed file") if (n == -1) { /* The number of bytes is unspecified, read until the end of stream */ if (!ENTER_BUFFERED(self)) return NULL; res = _bufferedreader_read_all(self); LEAVE_BUFFERED(self) } else { res = _bufferedreader_read_fast(self, n); if (res == Py_None) { Py_DECREF(res); if (!ENTER_BUFFERED(self)) return NULL; res = _bufferedreader_read_generic(self, n); LEAVE_BUFFERED(self) } } return res; } static PyObject * buffered_read1(buffered *self, PyObject *args) { Py_ssize_t n, have, r; PyObject *res = NULL; CHECK_INITIALIZED(self) if (!PyArg_ParseTuple(args, "n:read1", &n)) { return NULL; } if (n < 0) { PyErr_SetString(PyExc_ValueError, "read length must be positive"); return NULL; } if (n == 0) return PyBytes_FromStringAndSize(NULL, 0); if (!ENTER_BUFFERED(self)) return NULL; if (self->writable) { res = _bufferedwriter_flush_unlocked(self, 1); if (res == NULL) goto end; Py_CLEAR(res); } /* Return up to n bytes. If at least one byte is buffered, we only return buffered bytes. Otherwise, we do one raw read. */ /* XXX: this mimicks the io.py implementation but is probably wrong. If we need to read from the raw stream, then we could actually read all `n` bytes asked by the caller (and possibly more, so as to fill our buffer for the next reads). */ have = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t); if (have > 0) { if (n > have) n = have; res = PyBytes_FromStringAndSize(self->buffer + self->pos, n); if (res == NULL) goto end; self->pos += n; goto end; } /* Fill the buffer from the raw stream, and copy it to the result. */ _bufferedreader_reset_buf(self); r = _bufferedreader_fill_buffer(self); if (r == -1) goto end; if (r == -2) r = 0; if (n > r) n = r; res = PyBytes_FromStringAndSize(self->buffer, n); if (res == NULL) goto end; self->pos = n; end: LEAVE_BUFFERED(self) return res; } static PyObject * buffered_readinto(buffered *self, PyObject *args) { Py_buffer buf; Py_ssize_t n, written = 0, remaining; PyObject *res = NULL; CHECK_INITIALIZED(self) if (!PyArg_ParseTuple(args, "w*:readinto", &buf)) return NULL; n = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t); if (n > 0) { if (n >= buf.len) { memcpy(buf.buf, self->buffer + self->pos, buf.len); self->pos += buf.len; res = PyLong_FromSsize_t(buf.len); goto end_unlocked; } memcpy(buf.buf, self->buffer + self->pos, n); self->pos += n; written = n; } if (!ENTER_BUFFERED(self)) goto end_unlocked; if (self->writable) { res = _bufferedwriter_flush_unlocked(self, 0); if (res == NULL) goto end; Py_CLEAR(res); } _bufferedreader_reset_buf(self); self->pos = 0; for (remaining = buf.len - written; remaining > 0; written += n, remaining -= n) { /* If remaining bytes is larger than internal buffer size, copy * directly into caller's buffer. */ if (remaining > self->buffer_size) { n = _bufferedreader_raw_read(self, (char *) buf.buf + written, remaining); } else { n = _bufferedreader_fill_buffer(self); if (n > 0) { if (n > remaining) n = remaining; memcpy((char *) buf.buf + written, self->buffer + self->pos, n); self->pos += n; continue; /* short circuit */ } } if (n == 0 || (n == -2 && written > 0)) break; if (n < 0) { if (n == -2) { Py_INCREF(Py_None); res = Py_None; } goto end; } } res = PyLong_FromSsize_t(written); end: LEAVE_BUFFERED(self); end_unlocked: PyBuffer_Release(&buf); return res; } static PyObject * _buffered_readline(buffered *self, Py_ssize_t limit) { PyObject *res = NULL; PyObject *chunks = NULL; Py_ssize_t n, written = 0; const char *start, *s, *end; CHECK_CLOSED(self, "readline of closed file") /* First, try to find a line in the buffer. This can run unlocked because the calls to the C API are simple enough that they can't trigger any thread switch. */ n = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t); if (limit >= 0 && n > limit) n = limit; start = self->buffer + self->pos; s = memchr(start, '\n', n); if (s != NULL) { res = PyBytes_FromStringAndSize(start, s - start + 1); if (res != NULL) self->pos += s - start + 1; goto end_unlocked; } if (n == limit) { res = PyBytes_FromStringAndSize(start, n); if (res != NULL) self->pos += n; goto end_unlocked; } if (!ENTER_BUFFERED(self)) goto end_unlocked; /* Now we try to get some more from the raw stream */ if (self->writable) { res = _bufferedwriter_flush_unlocked(self, 1); if (res == NULL) goto end; Py_CLEAR(res); } chunks = PyList_New(0); if (chunks == NULL) goto end; if (n > 0) { res = PyBytes_FromStringAndSize(start, n); if (res == NULL) goto end; if (PyList_Append(chunks, res) < 0) { Py_CLEAR(res); goto end; } Py_CLEAR(res); written += n; if (limit >= 0) limit -= n; } for (;;) { _bufferedreader_reset_buf(self); n = _bufferedreader_fill_buffer(self); if (n == -1) goto end; if (n <= 0) break; if (limit >= 0 && n > limit) n = limit; start = self->buffer; end = start + n; s = start; while (s < end) { if (*s++ == '\n') { res = PyBytes_FromStringAndSize(start, s - start); if (res == NULL) goto end; self->pos = s - start; goto found; } } res = PyBytes_FromStringAndSize(start, n); if (res == NULL) goto end; if (n == limit) { self->pos = n; break; } if (PyList_Append(chunks, res) < 0) { Py_CLEAR(res); goto end; } Py_CLEAR(res); written += n; if (limit >= 0) limit -= n; } found: if (res != NULL && PyList_Append(chunks, res) < 0) { Py_CLEAR(res); goto end; } Py_CLEAR(res); res = _PyBytes_Join(_PyIO_empty_bytes, chunks); end: LEAVE_BUFFERED(self) end_unlocked: Py_XDECREF(chunks); return res; } static PyObject * buffered_readline(buffered *self, PyObject *args) { Py_ssize_t limit = -1; CHECK_INITIALIZED(self) if (!PyArg_ParseTuple(args, "|O&:readline", &_PyIO_ConvertSsize_t, &limit)) return NULL; return _buffered_readline(self, limit); } static PyObject * buffered_tell(buffered *self, PyObject *args) { Py_off_t pos; CHECK_INITIALIZED(self) pos = _buffered_raw_tell(self); if (pos == -1) return NULL; pos -= RAW_OFFSET(self); /* TODO: sanity check (pos >= 0) */ return PyLong_FromOff_t(pos); } static PyObject * buffered_seek(buffered *self, PyObject *args) { Py_off_t target, n; int whence = 0; PyObject *targetobj, *res = NULL; CHECK_INITIALIZED(self) if (!PyArg_ParseTuple(args, "O|i:seek", &targetobj, &whence)) { return NULL; } if (whence < 0 || whence > 2) { PyErr_Format(PyExc_ValueError, "whence must be between 0 and 2, not %d", whence); return NULL; } CHECK_CLOSED(self, "seek of closed file") target = PyNumber_AsOff_t(targetobj, PyExc_ValueError); if (target == -1 && PyErr_Occurred()) return NULL; if (whence != 2 && self->readable) { Py_off_t current, avail; /* Check if seeking leaves us inside the current buffer, so as to return quickly if possible. Also, we needn't take the lock in this fast path. Don't know how to do that when whence == 2, though. */ /* NOTE: RAW_TELL() can release the GIL but the object is in a stable state at this point. */ current = RAW_TELL(self); avail = READAHEAD(self); if (avail > 0) { Py_off_t offset; if (whence == 0) offset = target - (current - RAW_OFFSET(self)); else offset = target; if (offset >= -self->pos && offset <= avail) { self->pos += offset; return PyLong_FromOff_t(current - avail + offset); } } } if (!ENTER_BUFFERED(self)) return NULL; /* Fallback: invoke raw seek() method and clear buffer */ if (self->writable) { res = _bufferedwriter_flush_unlocked(self, 0); if (res == NULL) goto end; Py_CLEAR(res); _bufferedwriter_reset_buf(self); } /* TODO: align on block boundary and read buffer if needed? */ if (whence == 1) target -= RAW_OFFSET(self); n = _buffered_raw_seek(self, target, whence); if (n == -1) goto end; self->raw_pos = -1; res = PyLong_FromOff_t(n); if (res != NULL && self->readable) _bufferedreader_reset_buf(self); end: LEAVE_BUFFERED(self) return res; } static PyObject * buffered_truncate(buffered *self, PyObject *args) { PyObject *pos = Py_None; PyObject *res = NULL; CHECK_INITIALIZED(self) if (!PyArg_ParseTuple(args, "|O:truncate", &pos)) { return NULL; } if (!ENTER_BUFFERED(self)) return NULL; if (self->writable) { res = _bufferedwriter_flush_unlocked(self, 0); if (res == NULL) goto end; Py_CLEAR(res); } if (self->readable) { if (pos == Py_None) { /* Rewind the raw stream so that its position corresponds to the current logical position. */ if (_buffered_raw_seek(self, -RAW_OFFSET(self), 1) == -1) goto end; } _bufferedreader_reset_buf(self); } res = PyObject_CallMethodObjArgs(self->raw, _PyIO_str_truncate, pos, NULL); if (res == NULL) goto end; /* Reset cached position */ if (_buffered_raw_tell(self) == -1) PyErr_Clear(); end: LEAVE_BUFFERED(self) return res; } static PyObject * buffered_iternext(buffered *self) { PyObject *line; PyTypeObject *tp; CHECK_INITIALIZED(self); tp = Py_TYPE(self); if (tp == &PyBufferedReader_Type || tp == &PyBufferedRandom_Type) { /* Skip method call overhead for speed */ line = _buffered_readline(self, -1); } else { line = PyObject_CallMethodObjArgs((PyObject *)self, _PyIO_str_readline, NULL); if (line && !PyBytes_Check(line)) { PyErr_Format(PyExc_IOError, "readline() should have returned a bytes object, " "not '%.200s'", Py_TYPE(line)->tp_name); Py_DECREF(line); return NULL; } } if (line == NULL) return NULL; if (PyBytes_GET_SIZE(line) == 0) { /* Reached EOF or would have blocked */ Py_DECREF(line); return NULL; } return line; } static PyObject * buffered_repr(buffered *self) { PyObject *nameobj, *res; nameobj = PyObject_GetAttrString((PyObject *) self, "name"); if (nameobj == NULL) { if (PyErr_ExceptionMatches(PyExc_AttributeError)) PyErr_Clear(); else return NULL; res = PyUnicode_FromFormat("<%s>", Py_TYPE(self)->tp_name); } else { res = PyUnicode_FromFormat("<%s name=%R>", Py_TYPE(self)->tp_name, nameobj); Py_DECREF(nameobj); } return res; } /* * class BufferedReader */ PyDoc_STRVAR(bufferedreader_doc, "Create a new buffered reader using the given readable raw IO object."); static void _bufferedreader_reset_buf(buffered *self) { self->read_end = -1; } static int bufferedreader_init(buffered *self, PyObject *args, PyObject *kwds) { char *kwlist[] = {"raw", "buffer_size", NULL}; Py_ssize_t buffer_size = DEFAULT_BUFFER_SIZE; PyObject *raw; self->ok = 0; self->detached = 0; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|n:BufferedReader", kwlist, &raw, &buffer_size)) { return -1; } if (_PyIOBase_check_readable(raw, Py_True) == NULL) return -1; Py_CLEAR(self->raw); Py_INCREF(raw); self->raw = raw; self->buffer_size = buffer_size; self->readable = 1; self->writable = 0; if (_buffered_init(self) < 0) return -1; _bufferedreader_reset_buf(self); self->fast_closed_checks = (Py_TYPE(self) == &PyBufferedReader_Type && Py_TYPE(raw) == &PyFileIO_Type); self->ok = 1; return 0; } static Py_ssize_t _bufferedreader_raw_read(buffered *self, char *start, Py_ssize_t len) { Py_buffer buf; PyObject *memobj, *res; Py_ssize_t n; /* NOTE: the buffer needn't be released as its object is NULL. */ if (PyBuffer_FillInfo(&buf, NULL, start, len, 0, PyBUF_CONTIG) == -1) return -1; memobj = PyMemoryView_FromBuffer(&buf); if (memobj == NULL) return -1; /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals() when EINTR occurs so we needn't do it ourselves. We then retry reading, ignoring the signal if no handler has raised (see issue #10956). */ do { res = PyObject_CallMethodObjArgs(self->raw, _PyIO_str_readinto, memobj, NULL); } while (res == NULL && _trap_eintr()); Py_DECREF(memobj); if (res == NULL) return -1; if (res == Py_None) { /* Non-blocking stream would have blocked. Special return code! */ Py_DECREF(res); return -2; } n = PyNumber_AsSsize_t(res, PyExc_ValueError); Py_DECREF(res); if (n < 0 || n > len) { PyErr_Format(PyExc_IOError, "raw readinto() returned invalid length %zd " "(should have been between 0 and %zd)", n, len); return -1; } if (n > 0 && self->abs_pos != -1) self->abs_pos += n; return n; } static Py_ssize_t _bufferedreader_fill_buffer(buffered *self) { Py_ssize_t start, len, n; if (VALID_READ_BUFFER(self)) start = Py_SAFE_DOWNCAST(self->read_end, Py_off_t, Py_ssize_t); else start = 0; len = self->buffer_size - start; n = _bufferedreader_raw_read(self, self->buffer + start, len); if (n <= 0) return n; self->read_end = start + n; self->raw_pos = start + n; return n; } static PyObject * _bufferedreader_read_all(buffered *self) { Py_ssize_t current_size; PyObject *res, *data = NULL; PyObject *chunks = PyList_New(0); if (chunks == NULL) return NULL; /* First copy what we have in the current buffer. */ current_size = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t); if (current_size) { data = PyBytes_FromStringAndSize( self->buffer + self->pos, current_size); if (data == NULL) { Py_DECREF(chunks); return NULL; } } _bufferedreader_reset_buf(self); /* We're going past the buffer's bounds, flush it */ if (self->writable) { res = _bufferedwriter_flush_unlocked(self, 1); if (res == NULL) { Py_DECREF(chunks); return NULL; } Py_CLEAR(res); } while (1) { if (data) { if (PyList_Append(chunks, data) < 0) { Py_DECREF(data); Py_DECREF(chunks); return NULL; } Py_DECREF(data); } /* Read until EOF or until read() would block. */ data = PyObject_CallMethodObjArgs(self->raw, _PyIO_str_read, NULL); if (data == NULL) { Py_DECREF(chunks); return NULL; } if (data != Py_None && !PyBytes_Check(data)) { Py_DECREF(data); Py_DECREF(chunks); PyErr_SetString(PyExc_TypeError, "read() should return bytes"); return NULL; } if (data == Py_None || PyBytes_GET_SIZE(data) == 0) { if (current_size == 0) { Py_DECREF(chunks); return data; } else { res = _PyBytes_Join(_PyIO_empty_bytes, chunks); Py_DECREF(data); Py_DECREF(chunks); return res; } } current_size += PyBytes_GET_SIZE(data); if (self->abs_pos != -1) self->abs_pos += PyBytes_GET_SIZE(data); } } /* Read n bytes from the buffer if it can, otherwise return None. This function is simple enough that it can run unlocked. */ static PyObject * _bufferedreader_read_fast(buffered *self, Py_ssize_t n) { Py_ssize_t current_size; current_size = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t); if (n <= current_size) { /* Fast path: the data to read is fully buffered. */ PyObject *res = PyBytes_FromStringAndSize(self->buffer + self->pos, n); if (res != NULL) self->pos += n; return res; } Py_RETURN_NONE; } /* Generic read function: read from the stream until enough bytes are read, * or until an EOF occurs or until read() would block. */ static PyObject * _bufferedreader_read_generic(buffered *self, Py_ssize_t n) { PyObject *res = NULL; Py_ssize_t current_size, remaining, written; char *out; current_size = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t); if (n <= current_size) return _bufferedreader_read_fast(self, n); res = PyBytes_FromStringAndSize(NULL, n); if (res == NULL) goto error; out = PyBytes_AS_STRING(res); remaining = n; written = 0; if (current_size > 0) { memcpy(out, self->buffer + self->pos, current_size); remaining -= current_size; written += current_size; } _bufferedreader_reset_buf(self); while (remaining > 0) { /* We want to read a whole block at the end into buffer. If we had readv() we could do this in one pass. */ Py_ssize_t r = MINUS_LAST_BLOCK(self, remaining); if (r == 0) break; r = _bufferedreader_raw_read(self, out + written, r); if (r == -1) goto error; if (r == 0 || r == -2) { /* EOF occurred or read() would block. */ if (r == 0 || written > 0) { if (_PyBytes_Resize(&res, written)) goto error; return res; } Py_DECREF(res); Py_INCREF(Py_None); return Py_None; } remaining -= r; written += r; } assert(remaining <= self->buffer_size); self->pos = 0; self->raw_pos = 0; self->read_end = 0; /* NOTE: when the read is satisfied, we avoid issuing any additional reads, which could block indefinitely (e.g. on a socket). See issue #9550. */ while (remaining > 0 && self->read_end < self->buffer_size) { Py_ssize_t r = _bufferedreader_fill_buffer(self); if (r == -1) goto error; if (r == 0 || r == -2) { /* EOF occurred or read() would block. */ if (r == 0 || written > 0) { if (_PyBytes_Resize(&res, written)) goto error; return res; } Py_DECREF(res); Py_INCREF(Py_None); return Py_None; } if (remaining > r) { memcpy(out + written, self->buffer + self->pos, r); written += r; self->pos += r; remaining -= r; } else if (remaining > 0) { memcpy(out + written, self->buffer + self->pos, remaining); written += remaining; self->pos += remaining; remaining = 0; } if (remaining == 0) break; } return res; error: Py_XDECREF(res); return NULL; } static PyObject * _bufferedreader_peek_unlocked(buffered *self, Py_ssize_t n) { Py_ssize_t have, r; have = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t); /* Constraints: 1. we don't want to advance the file position. 2. we don't want to lose block alignment, so we can't shift the buffer to make some place. Therefore, we either return `have` bytes (if > 0), or a full buffer. */ if (have > 0) { return PyBytes_FromStringAndSize(self->buffer + self->pos, have); } /* Fill the buffer from the raw stream, and copy it to the result. */ _bufferedreader_reset_buf(self); r = _bufferedreader_fill_buffer(self); if (r == -1) return NULL; if (r == -2) r = 0; self->pos = 0; return PyBytes_FromStringAndSize(self->buffer, r); } static PyMethodDef bufferedreader_methods[] = { /* BufferedIOMixin methods */ {"detach", (PyCFunction)buffered_detach, METH_NOARGS}, {"flush", (PyCFunction)buffered_simple_flush, METH_NOARGS}, {"close", (PyCFunction)buffered_close, METH_NOARGS}, {"seekable", (PyCFunction)buffered_seekable, METH_NOARGS}, {"readable", (PyCFunction)buffered_readable, METH_NOARGS}, {"writable", (PyCFunction)buffered_writable, METH_NOARGS}, {"fileno", (PyCFunction)buffered_fileno, METH_NOARGS}, {"isatty", (PyCFunction)buffered_isatty, METH_NOARGS}, {"_dealloc_warn", (PyCFunction)buffered_dealloc_warn, METH_O}, {"__getstate__", (PyCFunction)buffered_getstate, METH_NOARGS}, {"read", (PyCFunction)buffered_read, METH_VARARGS}, {"peek", (PyCFunction)buffered_peek, METH_VARARGS}, {"read1", (PyCFunction)buffered_read1, METH_VARARGS}, {"readinto", (PyCFunction)buffered_readinto, METH_VARARGS}, {"readline", (PyCFunction)buffered_readline, METH_VARARGS}, {"seek", (PyCFunction)buffered_seek, METH_VARARGS}, {"tell", (PyCFunction)buffered_tell, METH_NOARGS}, {"truncate", (PyCFunction)buffered_truncate, METH_VARARGS}, {NULL, NULL} }; static PyMemberDef bufferedreader_members[] = { {"raw", T_OBJECT, offsetof(buffered, raw), READONLY}, {NULL} }; static PyGetSetDef bufferedreader_getset[] = { {"closed", (getter)buffered_closed_get, NULL, NULL}, {"name", (getter)buffered_name_get, NULL, NULL}, {"mode", (getter)buffered_mode_get, NULL, NULL}, {NULL} }; PyTypeObject PyBufferedReader_Type = { PyVarObject_HEAD_INIT(NULL, 0) "_io.BufferedReader", /*tp_name*/ sizeof(buffered), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)buffered_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare */ (reprfunc)buffered_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/ bufferedreader_doc, /* tp_doc */ (traverseproc)buffered_traverse, /* tp_traverse */ (inquiry)buffered_clear, /* tp_clear */ 0, /* tp_richcompare */ offsetof(buffered, weakreflist), /*tp_weaklistoffset*/ 0, /* tp_iter */ (iternextfunc)buffered_iternext, /* tp_iternext */ bufferedreader_methods, /* tp_methods */ bufferedreader_members, /* tp_members */ bufferedreader_getset, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(buffered, dict), /* tp_dictoffset */ (initproc)bufferedreader_init, /* tp_init */ 0, /* tp_alloc */ PyType_GenericNew, /* tp_new */ }; static int complain_about_max_buffer_size(void) { if (PyErr_WarnEx(PyExc_DeprecationWarning, "max_buffer_size is deprecated", 1) < 0) return 0; return 1; } /* * class BufferedWriter */ PyDoc_STRVAR(bufferedwriter_doc, "A buffer for a writeable sequential RawIO object.\n" "\n" "The constructor creates a BufferedWriter for the given writeable raw\n" "stream. If the buffer_size is not given, it defaults to\n" "DEFAULT_BUFFER_SIZE. max_buffer_size isn't used anymore.\n" ); static void _bufferedwriter_reset_buf(buffered *self) { self->write_pos = 0; self->write_end = -1; } static int bufferedwriter_init(buffered *self, PyObject *args, PyObject *kwds) { /* TODO: properly deprecate max_buffer_size */ char *kwlist[] = {"raw", "buffer_size", "max_buffer_size", NULL}; Py_ssize_t buffer_size = DEFAULT_BUFFER_SIZE; Py_ssize_t max_buffer_size = -234; PyObject *raw; self->ok = 0; self->detached = 0; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|nn:BufferedReader", kwlist, &raw, &buffer_size, &max_buffer_size)) { return -1; } if (max_buffer_size != -234 && !complain_about_max_buffer_size()) return -1; if (_PyIOBase_check_writable(raw, Py_True) == NULL) return -1; Py_CLEAR(self->raw); Py_INCREF(raw); self->raw = raw; self->readable = 0; self->writable = 1; self->buffer_size = buffer_size; if (_buffered_init(self) < 0) return -1; _bufferedwriter_reset_buf(self); self->pos = 0; self->fast_closed_checks = (Py_TYPE(self) == &PyBufferedWriter_Type && Py_TYPE(raw) == &PyFileIO_Type); self->ok = 1; return 0; } static Py_ssize_t _bufferedwriter_raw_write(buffered *self, char *start, Py_ssize_t len) { Py_buffer buf; PyObject *memobj, *res; Py_ssize_t n; /* NOTE: the buffer needn't be released as its object is NULL. */ if (PyBuffer_FillInfo(&buf, NULL, start, len, 1, PyBUF_CONTIG_RO) == -1) return -1; memobj = PyMemoryView_FromBuffer(&buf); if (memobj == NULL) return -1; /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals() when EINTR occurs so we needn't do it ourselves. We then retry writing, ignoring the signal if no handler has raised (see issue #10956). */ do { res = PyObject_CallMethodObjArgs(self->raw, _PyIO_str_write, memobj, NULL); } while (res == NULL && _trap_eintr()); Py_DECREF(memobj); if (res == NULL) return -1; n = PyNumber_AsSsize_t(res, PyExc_ValueError); Py_DECREF(res); if (n < 0 || n > len) { PyErr_Format(PyExc_IOError, "raw write() returned invalid length %zd " "(should have been between 0 and %zd)", n, len); return -1; } if (n > 0 && self->abs_pos != -1) self->abs_pos += n; return n; } /* `restore_pos` is 1 if we need to restore the raw stream position at the end, 0 otherwise. */ static PyObject * _bufferedwriter_flush_unlocked(buffered *self, int restore_pos) { Py_ssize_t written = 0; Py_off_t n, rewind; if (!VALID_WRITE_BUFFER(self) || self->write_pos == self->write_end) goto end; /* First, rewind */ rewind = RAW_OFFSET(self) + (self->pos - self->write_pos); if (rewind != 0) { n = _buffered_raw_seek(self, -rewind, 1); if (n < 0) { goto error; } self->raw_pos -= rewind; } while (self->write_pos < self->write_end) { n = _bufferedwriter_raw_write(self, self->buffer + self->write_pos, Py_SAFE_DOWNCAST(self->write_end - self->write_pos, Py_off_t, Py_ssize_t)); if (n == -1) { Py_ssize_t *w = _buffered_check_blocking_error(); if (w == NULL) goto error; self->write_pos += *w; self->raw_pos = self->write_pos; written += *w; *w = written; /* Already re-raised */ goto error; } self->write_pos += n; self->raw_pos = self->write_pos; written += Py_SAFE_DOWNCAST(n, Py_off_t, Py_ssize_t); /* Partial writes can return successfully when interrupted by a signal (see write(2)). We must run signal handlers before blocking another time, possibly indefinitely. */ if (PyErr_CheckSignals() < 0) goto error; } if (restore_pos) { Py_off_t forward = rewind - written; if (forward != 0) { n = _buffered_raw_seek(self, forward, 1); if (n < 0) { goto error; } self->raw_pos += forward; } } _bufferedwriter_reset_buf(self); end: Py_RETURN_NONE; error: return NULL; } static PyObject * bufferedwriter_write(buffered *self, PyObject *args) { PyObject *res = NULL; Py_buffer buf; Py_ssize_t written, avail, remaining; Py_off_t offset; CHECK_INITIALIZED(self) if (!PyArg_ParseTuple(args, "y*:write", &buf)) { return NULL; } if (IS_CLOSED(self)) { PyErr_SetString(PyExc_ValueError, "write to closed file"); PyBuffer_Release(&buf); return NULL; } if (!ENTER_BUFFERED(self)) { PyBuffer_Release(&buf); return NULL; } /* Fast path: the data to write can be fully buffered. */ if (!VALID_READ_BUFFER(self) && !VALID_WRITE_BUFFER(self)) { self->pos = 0; self->raw_pos = 0; } avail = Py_SAFE_DOWNCAST(self->buffer_size - self->pos, Py_off_t, Py_ssize_t); if (buf.len <= avail) { memcpy(self->buffer + self->pos, buf.buf, buf.len); if (!VALID_WRITE_BUFFER(self)) { self->write_pos = self->pos; } ADJUST_POSITION(self, self->pos + buf.len); if (self->pos > self->write_end) self->write_end = self->pos; written = buf.len; goto end; } /* First write the current buffer */ res = _bufferedwriter_flush_unlocked(self, 0); if (res == NULL) { Py_ssize_t *w = _buffered_check_blocking_error(); if (w == NULL) goto error; if (self->readable) _bufferedreader_reset_buf(self); /* Make some place by shifting the buffer. */ assert(VALID_WRITE_BUFFER(self)); memmove(self->buffer, self->buffer + self->write_pos, Py_SAFE_DOWNCAST(self->write_end - self->write_pos, Py_off_t, Py_ssize_t)); self->write_end -= self->write_pos; self->raw_pos -= self->write_pos; self->pos -= self->write_pos; self->write_pos = 0; avail = Py_SAFE_DOWNCAST(self->buffer_size - self->write_end, Py_off_t, Py_ssize_t); if (buf.len <= avail) { /* Everything can be buffered */ PyErr_Clear(); memcpy(self->buffer + self->write_end, buf.buf, buf.len); self->write_end += buf.len; written = buf.len; goto end; } /* Buffer as much as possible. */ memcpy(self->buffer + self->write_end, buf.buf, avail); self->write_end += avail; /* Already re-raised */ *w = avail; goto error; } Py_CLEAR(res); /* Adjust the raw stream position if it is away from the logical stream position. This happens if the read buffer has been filled but not modified (and therefore _bufferedwriter_flush_unlocked() didn't rewind the raw stream by itself). Fixes issue #6629. */ offset = RAW_OFFSET(self); if (offset != 0) { if (_buffered_raw_seek(self, -offset, 1) < 0) goto error; self->raw_pos -= offset; } /* Then write buf itself. At this point the buffer has been emptied. */ remaining = buf.len; written = 0; while (remaining > self->buffer_size) { Py_ssize_t n = _bufferedwriter_raw_write( self, (char *) buf.buf + written, buf.len - written); if (n == -1) { Py_ssize_t *w = _buffered_check_blocking_error(); if (w == NULL) goto error; written += *w; remaining -= *w; if (remaining > self->buffer_size) { /* Can't buffer everything, still buffer as much as possible */ memcpy(self->buffer, (char *) buf.buf + written, self->buffer_size); self->raw_pos = 0; ADJUST_POSITION(self, self->buffer_size); self->write_end = self->buffer_size; *w = written + self->buffer_size; /* Already re-raised */ goto error; } PyErr_Clear(); break; } written += n; remaining -= n; /* Partial writes can return successfully when interrupted by a signal (see write(2)). We must run signal handlers before blocking another time, possibly indefinitely. */ if (PyErr_CheckSignals() < 0) goto error; } if (self->readable) _bufferedreader_reset_buf(self); if (remaining > 0) { memcpy(self->buffer, (char *) buf.buf + written, remaining); written += remaining; } self->write_pos = 0; /* TODO: sanity check (remaining >= 0) */ self->write_end = remaining; ADJUST_POSITION(self, remaining); self->raw_pos = 0; end: res = PyLong_FromSsize_t(written); error: LEAVE_BUFFERED(self) PyBuffer_Release(&buf); return res; } static PyMethodDef bufferedwriter_methods[] = { /* BufferedIOMixin methods */ {"close", (PyCFunction)buffered_close, METH_NOARGS}, {"detach", (PyCFunction)buffered_detach, METH_NOARGS}, {"seekable", (PyCFunction)buffered_seekable, METH_NOARGS}, {"readable", (PyCFunction)buffered_readable, METH_NOARGS}, {"writable", (PyCFunction)buffered_writable, METH_NOARGS}, {"fileno", (PyCFunction)buffered_fileno, METH_NOARGS}, {"isatty", (PyCFunction)buffered_isatty, METH_NOARGS}, {"_dealloc_warn", (PyCFunction)buffered_dealloc_warn, METH_O}, {"__getstate__", (PyCFunction)buffered_getstate, METH_NOARGS}, {"write", (PyCFunction)bufferedwriter_write, METH_VARARGS}, {"truncate", (PyCFunction)buffered_truncate, METH_VARARGS}, {"flush", (PyCFunction)buffered_flush, METH_NOARGS}, {"seek", (PyCFunction)buffered_seek, METH_VARARGS}, {"tell", (PyCFunction)buffered_tell, METH_NOARGS}, {NULL, NULL} }; static PyMemberDef bufferedwriter_members[] = { {"raw", T_OBJECT, offsetof(buffered, raw), READONLY}, {NULL} }; static PyGetSetDef bufferedwriter_getset[] = { {"closed", (getter)buffered_closed_get, NULL, NULL}, {"name", (getter)buffered_name_get, NULL, NULL}, {"mode", (getter)buffered_mode_get, NULL, NULL}, {NULL} }; PyTypeObject PyBufferedWriter_Type = { PyVarObject_HEAD_INIT(NULL, 0) "_io.BufferedWriter", /*tp_name*/ sizeof(buffered), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)buffered_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare */ (reprfunc)buffered_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/ bufferedwriter_doc, /* tp_doc */ (traverseproc)buffered_traverse, /* tp_traverse */ (inquiry)buffered_clear, /* tp_clear */ 0, /* tp_richcompare */ offsetof(buffered, weakreflist), /*tp_weaklistoffset*/ 0, /* tp_iter */ 0, /* tp_iternext */ bufferedwriter_methods, /* tp_methods */ bufferedwriter_members, /* tp_members */ bufferedwriter_getset, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(buffered, dict), /* tp_dictoffset */ (initproc)bufferedwriter_init, /* tp_init */ 0, /* tp_alloc */ PyType_GenericNew, /* tp_new */ }; /* * BufferedRWPair */ PyDoc_STRVAR(bufferedrwpair_doc, "A buffered reader and writer object together.\n" "\n" "A buffered reader object and buffered writer object put together to\n" "form a sequential IO object that can read and write. This is typically\n" "used with a socket or two-way pipe.\n" "\n" "reader and writer are RawIOBase objects that are readable and\n" "writeable respectively. If the buffer_size is omitted it defaults to\n" "DEFAULT_BUFFER_SIZE.\n" ); /* XXX The usefulness of this (compared to having two separate IO objects) is * questionable. */ typedef struct { PyObject_HEAD buffered *reader; buffered *writer; PyObject *dict; PyObject *weakreflist; } rwpair; static int bufferedrwpair_init(rwpair *self, PyObject *args, PyObject *kwds) { PyObject *reader, *writer; Py_ssize_t buffer_size = DEFAULT_BUFFER_SIZE; Py_ssize_t max_buffer_size = -234; if (!PyArg_ParseTuple(args, "OO|nn:BufferedRWPair", &reader, &writer, &buffer_size, &max_buffer_size)) { return -1; } if (max_buffer_size != -234 && !complain_about_max_buffer_size()) return -1; if (_PyIOBase_check_readable(reader, Py_True) == NULL) return -1; if (_PyIOBase_check_writable(writer, Py_True) == NULL) return -1; self->reader = (buffered *) PyObject_CallFunction( (PyObject *) &PyBufferedReader_Type, "On", reader, buffer_size); if (self->reader == NULL) return -1; self->writer = (buffered *) PyObject_CallFunction( (PyObject *) &PyBufferedWriter_Type, "On", writer, buffer_size); if (self->writer == NULL) { Py_CLEAR(self->reader); return -1; } return 0; } static int bufferedrwpair_traverse(rwpair *self, visitproc visit, void *arg) { Py_VISIT(self->dict); return 0; } static int bufferedrwpair_clear(rwpair *self) { Py_CLEAR(self->reader); Py_CLEAR(self->writer); Py_CLEAR(self->dict); return 0; } static void bufferedrwpair_dealloc(rwpair *self) { _PyObject_GC_UNTRACK(self); Py_CLEAR(self->reader); Py_CLEAR(self->writer); Py_CLEAR(self->dict); Py_TYPE(self)->tp_free((PyObject *) self); } static PyObject * _forward_call(buffered *self, const char *name, PyObject *args) { PyObject *func = PyObject_GetAttrString((PyObject *)self, name); PyObject *ret; if (func == NULL) { PyErr_SetString(PyExc_AttributeError, name); return NULL; } ret = PyObject_CallObject(func, args); Py_DECREF(func); return ret; } static PyObject * bufferedrwpair_read(rwpair *self, PyObject *args) { return _forward_call(self->reader, "read", args); } static PyObject * bufferedrwpair_peek(rwpair *self, PyObject *args) { return _forward_call(self->reader, "peek", args); } static PyObject * bufferedrwpair_read1(rwpair *self, PyObject *args) { return _forward_call(self->reader, "read1", args); } static PyObject * bufferedrwpair_readinto(rwpair *self, PyObject *args) { return _forward_call(self->reader, "readinto", args); } static PyObject * bufferedrwpair_write(rwpair *self, PyObject *args) { return _forward_call(self->writer, "write", args); } static PyObject * bufferedrwpair_flush(rwpair *self, PyObject *args) { return _forward_call(self->writer, "flush", args); } static PyObject * bufferedrwpair_readable(rwpair *self, PyObject *args) { return _forward_call(self->reader, "readable", args); } static PyObject * bufferedrwpair_writable(rwpair *self, PyObject *args) { return _forward_call(self->writer, "writable", args); } static PyObject * bufferedrwpair_close(rwpair *self, PyObject *args) { PyObject *ret = _forward_call(self->writer, "close", args); if (ret == NULL) return NULL; Py_DECREF(ret); return _forward_call(self->reader, "close", args); } static PyObject * bufferedrwpair_isatty(rwpair *self, PyObject *args) { PyObject *ret = _forward_call(self->writer, "isatty", args); if (ret != Py_False) { /* either True or exception */ return ret; } Py_DECREF(ret); return _forward_call(self->reader, "isatty", args); } static PyObject * bufferedrwpair_closed_get(rwpair *self, void *context) { return PyObject_GetAttr((PyObject *) self->writer, _PyIO_str_closed); } static PyMethodDef bufferedrwpair_methods[] = { {"read", (PyCFunction)bufferedrwpair_read, METH_VARARGS}, {"peek", (PyCFunction)bufferedrwpair_peek, METH_VARARGS}, {"read1", (PyCFunction)bufferedrwpair_read1, METH_VARARGS}, {"readinto", (PyCFunction)bufferedrwpair_readinto, METH_VARARGS}, {"write", (PyCFunction)bufferedrwpair_write, METH_VARARGS}, {"flush", (PyCFunction)bufferedrwpair_flush, METH_NOARGS}, {"readable", (PyCFunction)bufferedrwpair_readable, METH_NOARGS}, {"writable", (PyCFunction)bufferedrwpair_writable, METH_NOARGS}, {"close", (PyCFunction)bufferedrwpair_close, METH_NOARGS}, {"isatty", (PyCFunction)bufferedrwpair_isatty, METH_NOARGS}, {"__getstate__", (PyCFunction)buffered_getstate, METH_NOARGS}, {NULL, NULL} }; static PyGetSetDef bufferedrwpair_getset[] = { {"closed", (getter)bufferedrwpair_closed_get, NULL, NULL}, {NULL} }; PyTypeObject PyBufferedRWPair_Type = { PyVarObject_HEAD_INIT(NULL, 0) "_io.BufferedRWPair", /*tp_name*/ sizeof(rwpair), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)bufferedrwpair_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare */ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ bufferedrwpair_doc, /* tp_doc */ (traverseproc)bufferedrwpair_traverse, /* tp_traverse */ (inquiry)bufferedrwpair_clear, /* tp_clear */ 0, /* tp_richcompare */ offsetof(rwpair, weakreflist), /*tp_weaklistoffset*/ 0, /* tp_iter */ 0, /* tp_iternext */ bufferedrwpair_methods, /* tp_methods */ 0, /* tp_members */ bufferedrwpair_getset, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(rwpair, dict), /* tp_dictoffset */ (initproc)bufferedrwpair_init, /* tp_init */ 0, /* tp_alloc */ PyType_GenericNew, /* tp_new */ }; /* * BufferedRandom */ PyDoc_STRVAR(bufferedrandom_doc, "A buffered interface to random access streams.\n" "\n" "The constructor creates a reader and writer for a seekable stream,\n" "raw, given in the first argument. If the buffer_size is omitted it\n" "defaults to DEFAULT_BUFFER_SIZE. max_buffer_size isn't used anymore.\n" ); static int bufferedrandom_init(buffered *self, PyObject *args, PyObject *kwds) { char *kwlist[] = {"raw", "buffer_size", "max_buffer_size", NULL}; Py_ssize_t buffer_size = DEFAULT_BUFFER_SIZE; Py_ssize_t max_buffer_size = -234; PyObject *raw; self->ok = 0; self->detached = 0; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|nn:BufferedReader", kwlist, &raw, &buffer_size, &max_buffer_size)) { return -1; } if (max_buffer_size != -234 && !complain_about_max_buffer_size()) return -1; if (_PyIOBase_check_seekable(raw, Py_True) == NULL) return -1; if (_PyIOBase_check_readable(raw, Py_True) == NULL) return -1; if (_PyIOBase_check_writable(raw, Py_True) == NULL) return -1; Py_CLEAR(self->raw); Py_INCREF(raw); self->raw = raw; self->buffer_size = buffer_size; self->readable = 1; self->writable = 1; if (_buffered_init(self) < 0) return -1; _bufferedreader_reset_buf(self); _bufferedwriter_reset_buf(self); self->pos = 0; self->fast_closed_checks = (Py_TYPE(self) == &PyBufferedRandom_Type && Py_TYPE(raw) == &PyFileIO_Type); self->ok = 1; return 0; } static PyMethodDef bufferedrandom_methods[] = { /* BufferedIOMixin methods */ {"close", (PyCFunction)buffered_close, METH_NOARGS}, {"detach", (PyCFunction)buffered_detach, METH_NOARGS}, {"seekable", (PyCFunction)buffered_seekable, METH_NOARGS}, {"readable", (PyCFunction)buffered_readable, METH_NOARGS}, {"writable", (PyCFunction)buffered_writable, METH_NOARGS}, {"fileno", (PyCFunction)buffered_fileno, METH_NOARGS}, {"isatty", (PyCFunction)buffered_isatty, METH_NOARGS}, {"_dealloc_warn", (PyCFunction)buffered_dealloc_warn, METH_O}, {"__getstate__", (PyCFunction)buffered_getstate, METH_NOARGS}, {"flush", (PyCFunction)buffered_flush, METH_NOARGS}, {"seek", (PyCFunction)buffered_seek, METH_VARARGS}, {"tell", (PyCFunction)buffered_tell, METH_NOARGS}, {"truncate", (PyCFunction)buffered_truncate, METH_VARARGS}, {"read", (PyCFunction)buffered_read, METH_VARARGS}, {"read1", (PyCFunction)buffered_read1, METH_VARARGS}, {"readinto", (PyCFunction)buffered_readinto, METH_VARARGS}, {"readline", (PyCFunction)buffered_readline, METH_VARARGS}, {"peek", (PyCFunction)buffered_peek, METH_VARARGS}, {"write", (PyCFunction)bufferedwriter_write, METH_VARARGS}, {NULL, NULL} }; static PyMemberDef bufferedrandom_members[] = { {"raw", T_OBJECT, offsetof(buffered, raw), READONLY}, {NULL} }; static PyGetSetDef bufferedrandom_getset[] = { {"closed", (getter)buffered_closed_get, NULL, NULL}, {"name", (getter)buffered_name_get, NULL, NULL}, {"mode", (getter)buffered_mode_get, NULL, NULL}, {NULL} }; PyTypeObject PyBufferedRandom_Type = { PyVarObject_HEAD_INIT(NULL, 0) "_io.BufferedRandom", /*tp_name*/ sizeof(buffered), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)buffered_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare */ (reprfunc)buffered_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/ bufferedrandom_doc, /* tp_doc */ (traverseproc)buffered_traverse, /* tp_traverse */ (inquiry)buffered_clear, /* tp_clear */ 0, /* tp_richcompare */ offsetof(buffered, weakreflist), /*tp_weaklistoffset*/ 0, /* tp_iter */ (iternextfunc)buffered_iternext, /* tp_iternext */ bufferedrandom_methods, /* tp_methods */ bufferedrandom_members, /* tp_members */ bufferedrandom_getset, /* tp_getset */ 0, /* tp_base */ 0, /*tp_dict*/ 0, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(buffered, dict), /*tp_dictoffset*/ (initproc)bufferedrandom_init, /* tp_init */ 0, /* tp_alloc */ PyType_GenericNew, /* tp_new */ }; /* An implementation of Buffered I/O as defined by PEP 3116 - "New I/O" Classes defined here: BufferedIOBase, BufferedReader, BufferedWriter, BufferedRandom. Written by Amaury Forgeot d'Arc and Antoine Pitrou */ #define PY_SSIZE_T_CLEAN #include "Python.h" #include "structmember.h" #include "pythread.h" #include "_iomodule.h" /* * BufferedIOBase class, inherits from IOBase. */ PyDoc_STRVAR(bufferediobase_doc, "Base class for buffered IO objects.\n" "\n" "The main difference with RawIOBase is that the read() method\n" "supports omitting the size argument, and does not have a default\n" "implementation that defers to readinto().\n" "\n" "In addition, read(), readinto() and write() may raise\n" "BlockingIOError if the underlying raw stream is in non-blocking\n" "mode and not ready; unlike their raw counterparts, they will never\n" "return None.\n" "\n" "A typical implementation should not inherit from a RawIOBase\n" "implementation, but wrap one.\n" ); static PyObject * bufferediobase_readinto(PyObject *self, PyObject *args) { Py_buffer buf; Py_ssize_t len; PyObject *data; if (!PyArg_ParseTuple(args, "w*:readinto", &buf)) { return NULL; } data = PyObject_CallMethod(self, "read", "n", buf.len); if (data == NULL) goto error; if (!PyBytes_Check(data)) { Py_DECREF(data); PyErr_SetString(PyExc_TypeError, "read() should return bytes"); goto error; } len = Py_SIZE(data); memcpy(buf.buf, PyBytes_AS_STRING(data), len); PyBuffer_Release(&buf); Py_DECREF(data); return PyLong_FromSsize_t(len); error: PyBuffer_Release(&buf); return NULL; } static PyObject * bufferediobase_unsupported(const char *message) { PyErr_SetString(IO_STATE->unsupported_operation, message); return NULL; } PyDoc_STRVAR(bufferediobase_detach_doc, "Disconnect this buffer from its underlying raw stream and return it.\n" "\n" "After the raw stream has been detached, the buffer is in an unusable\n" "state.\n"); static PyObject * bufferediobase_detach(PyObject *self) { return bufferediobase_unsupported("detach"); } PyDoc_STRVAR(bufferediobase_read_doc, "Read and return up to n bytes.\n" "\n" "If the argument is omitted, None, or negative, reads and\n" "returns all data until EOF.\n" "\n" "If the argument is positive, and the underlying raw stream is\n" "not 'interactive', multiple raw reads may be issued to satisfy\n" "the byte count (unless EOF is reached first). But for\n" "interactive raw streams (as well as sockets and pipes), at most\n" "one raw read will be issued, and a short result does not imply\n" "that EOF is imminent.\n" "\n" "Returns an empty bytes object on EOF.\n" "\n" "Returns None if the underlying raw stream was open in non-blocking\n" "mode and no data is available at the moment.\n"); static PyObject * bufferediobase_read(PyObject *self, PyObject *args) { return bufferediobase_unsupported("read"); } PyDoc_STRVAR(bufferediobase_read1_doc, "Read and return up to n bytes, with at most one read() call\n" "to the underlying raw stream. A short result does not imply\n" "that EOF is imminent.\n" "\n" "Returns an empty bytes object on EOF.\n"); static PyObject * bufferediobase_read1(PyObject *self, PyObject *args) { return bufferediobase_unsupported("read1"); } PyDoc_STRVAR(bufferediobase_write_doc, "Write the given buffer to the IO stream.\n" "\n" "Returns the number of bytes written, which is never less than\n" "len(b).\n" "\n" "Raises BlockingIOError if the buffer is full and the\n" "underlying raw stream cannot accept more data at the moment.\n"); static PyObject * bufferediobase_write(PyObject *self, PyObject *args) { return bufferediobase_unsupported("write"); } static PyMethodDef bufferediobase_methods[] = { {"detach", (PyCFunction)bufferediobase_detach, METH_NOARGS, bufferediobase_detach_doc}, {"read", bufferediobase_read, METH_VARARGS, bufferediobase_read_doc}, {"read1", bufferediobase_read1, METH_VARARGS, bufferediobase_read1_doc}, {"readinto", bufferediobase_readinto, METH_VARARGS, NULL}, {"write", bufferediobase_write, METH_VARARGS, bufferediobase_write_doc}, {NULL, NULL} }; PyTypeObject PyBufferedIOBase_Type = { PyVarObject_HEAD_INIT(NULL, 0) "_io._BufferedIOBase", /*tp_name*/ 0, /*tp_basicsize*/ 0, /*tp_itemsize*/ 0, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare */ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ bufferediobase_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ bufferediobase_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ &PyIOBase_Type, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; typedef struct { PyObject_HEAD PyObject *raw; int ok; /* Initialized? */ int detached; int readable; int writable; int deallocating; /* True if this is a vanilla Buffered object (rather than a user derived class) *and* the raw stream is a vanilla FileIO object. */ int fast_closed_checks; /* Absolute position inside the raw stream (-1 if unknown). */ Py_off_t abs_pos; /* A static buffer of size `buffer_size` */ char *buffer; /* Current logical position in the buffer. */ Py_off_t pos; /* Position of the raw stream in the buffer. */ Py_off_t raw_pos; /* Just after the last buffered byte in the buffer, or -1 if the buffer isn't ready for reading. */ Py_off_t read_end; /* Just after the last byte actually written */ Py_off_t write_pos; /* Just after the last byte waiting to be written, or -1 if the buffer isn't ready for writing. */ Py_off_t write_end; #ifdef WITH_THREAD PyThread_type_lock lock; volatile long owner; #endif Py_ssize_t buffer_size; Py_ssize_t buffer_mask; PyObject *dict; PyObject *weakreflist; } buffered; /* Implementation notes: * BufferedReader, BufferedWriter and BufferedRandom try to share most methods (this is helped by the members `readable` and `writable`, which are initialized in the respective constructors) * They also share a single buffer for reading and writing. This enables interleaved reads and writes without flushing. It also makes the logic a bit trickier to get right. * The absolute position of the raw stream is cached, if possible, in the `abs_pos` member. It must be updated every time an operation is done on the raw stream. If not sure, it can be reinitialized by calling _buffered_raw_tell(), which queries the raw stream (_buffered_raw_seek() also does it). To read it, use RAW_TELL(). * Three helpers, _bufferedreader_raw_read, _bufferedwriter_raw_write and _bufferedwriter_flush_unlocked do a lot of useful housekeeping. NOTE: we should try to maintain block alignment of reads and writes to the raw stream (according to the buffer size), but for now it is only done in read() and friends. */ /* These macros protect the buffered object against concurrent operations. */ #ifdef WITH_THREAD static int _enter_buffered_busy(buffered *self) { if (self->owner == PyThread_get_thread_ident()) { PyErr_Format(PyExc_RuntimeError, "reentrant call inside %R", self); return 0; } Py_BEGIN_ALLOW_THREADS PyThread_acquire_lock(self->lock, 1); Py_END_ALLOW_THREADS return 1; } #define ENTER_BUFFERED(self) \ ( (PyThread_acquire_lock(self->lock, 0) ? \ 1 : _enter_buffered_busy(self)) \ && (self->owner = PyThread_get_thread_ident(), 1) ) #define LEAVE_BUFFERED(self) \ do { \ self->owner = 0; \ PyThread_release_lock(self->lock); \ } while(0); #else #define ENTER_BUFFERED(self) 1 #define LEAVE_BUFFERED(self) #endif #define CHECK_INITIALIZED(self) \ if (self->ok <= 0) { \ if (self->detached) { \ PyErr_SetString(PyExc_ValueError, \ "raw stream has been detached"); \ } else { \ PyErr_SetString(PyExc_ValueError, \ "I/O operation on uninitialized object"); \ } \ return NULL; \ } #define CHECK_INITIALIZED_INT(self) \ if (self->ok <= 0) { \ if (self->detached) { \ PyErr_SetString(PyExc_ValueError, \ "raw stream has been detached"); \ } else { \ PyErr_SetString(PyExc_ValueError, \ "I/O operation on uninitialized object"); \ } \ return -1; \ } #define IS_CLOSED(self) \ (self->fast_closed_checks \ ? _PyFileIO_closed(self->raw) \ : buffered_closed(self)) #define CHECK_CLOSED(self, error_msg) \ if (IS_CLOSED(self)) { \ PyErr_SetString(PyExc_ValueError, error_msg); \ return NULL; \ } #define VALID_READ_BUFFER(self) \ (self->readable && self->read_end != -1) #define VALID_WRITE_BUFFER(self) \ (self->writable && self->write_end != -1) #define ADJUST_POSITION(self, _new_pos) \ do { \ self->pos = _new_pos; \ if (VALID_READ_BUFFER(self) && self->read_end < self->pos) \ self->read_end = self->pos; \ } while(0) #define READAHEAD(self) \ ((self->readable && VALID_READ_BUFFER(self)) \ ? (self->read_end - self->pos) : 0) #define RAW_OFFSET(self) \ (((VALID_READ_BUFFER(self) || VALID_WRITE_BUFFER(self)) \ && self->raw_pos >= 0) ? self->raw_pos - self->pos : 0) #define RAW_TELL(self) \ (self->abs_pos != -1 ? self->abs_pos : _buffered_raw_tell(self)) #define MINUS_LAST_BLOCK(self, size) \ (self->buffer_mask ? \ (size & ~self->buffer_mask) : \ (self->buffer_size * (size / self->buffer_size))) static void buffered_dealloc(buffered *self) { self->deallocating = 1; if (self->ok && _PyIOBase_finalize((PyObject *) self) < 0) return; _PyObject_GC_UNTRACK(self); self->ok = 0; if (self->weakreflist != NULL) PyObject_ClearWeakRefs((PyObject *)self); Py_CLEAR(self->raw); if (self->buffer) { PyMem_Free(self->buffer); self->buffer = NULL; } #ifdef WITH_THREAD if (self->lock) { PyThread_free_lock(self->lock); self->lock = NULL; } #endif Py_CLEAR(self->dict); Py_TYPE(self)->tp_free((PyObject *)self); } static int buffered_traverse(buffered *self, visitproc visit, void *arg) { Py_VISIT(self->raw); Py_VISIT(self->dict); return 0; } static int buffered_clear(buffered *self) { if (self->ok && _PyIOBase_finalize((PyObject *) self) < 0) return -1; self->ok = 0; Py_CLEAR(self->raw); Py_CLEAR(self->dict); return 0; } /* Because this can call arbitrary code, it shouldn't be called when the refcount is 0 (that is, not directly from tp_dealloc unless the refcount has been temporarily re-incremented). */ static PyObject * buffered_dealloc_warn(buffered *self, PyObject *source) { if (self->ok && self->raw) { PyObject *r; r = PyObject_CallMethod(self->raw, "_dealloc_warn", "O", source); if (r) Py_DECREF(r); else PyErr_Clear(); } Py_RETURN_NONE; } /* * _BufferedIOMixin methods * This is not a class, just a collection of methods that will be reused * by BufferedReader and BufferedWriter */ /* Flush and close */ static PyObject * buffered_simple_flush(buffered *self, PyObject *args) { CHECK_INITIALIZED(self) return PyObject_CallMethodObjArgs(self->raw, _PyIO_str_flush, NULL); } static int buffered_closed(buffered *self) { int closed; PyObject *res; CHECK_INITIALIZED_INT(self) res = PyObject_GetAttr(self->raw, _PyIO_str_closed); if (res == NULL) return -1; closed = PyObject_IsTrue(res); Py_DECREF(res); return closed; } static PyObject * buffered_closed_get(buffered *self, void *context) { CHECK_INITIALIZED(self) return PyObject_GetAttr(self->raw, _PyIO_str_closed); } static PyObject * buffered_close(buffered *self, PyObject *args) { PyObject *res = NULL; int r; CHECK_INITIALIZED(self) if (!ENTER_BUFFERED(self)) return NULL; r = buffered_closed(self); if (r < 0) goto end; if (r > 0) { res = Py_None; Py_INCREF(res); goto end; } if (self->deallocating) { PyObject *r = buffered_dealloc_warn(self, (PyObject *) self); if (r) Py_DECREF(r); else PyErr_Clear(); } /* flush() will most probably re-take the lock, so drop it first */ LEAVE_BUFFERED(self) res = PyObject_CallMethodObjArgs((PyObject *)self, _PyIO_str_flush, NULL); if (!ENTER_BUFFERED(self)) return NULL; if (res == NULL) { goto end; } Py_XDECREF(res); res = PyObject_CallMethodObjArgs(self->raw, _PyIO_str_close, NULL); end: LEAVE_BUFFERED(self) return res; } /* detach */ static PyObject * buffered_detach(buffered *self, PyObject *args) { PyObject *raw, *res; CHECK_INITIALIZED(self) res = PyObject_CallMethodObjArgs((PyObject *)self, _PyIO_str_flush, NULL); if (res == NULL) return NULL; Py_DECREF(res); raw = self->raw; self->raw = NULL; self->detached = 1; self->ok = 0; return raw; } /* Inquiries */ static PyObject * buffered_seekable(buffered *self, PyObject *args) { CHECK_INITIALIZED(self) return PyObject_CallMethodObjArgs(self->raw, _PyIO_str_seekable, NULL); } static PyObject * buffered_readable(buffered *self, PyObject *args) { CHECK_INITIALIZED(self) return PyObject_CallMethodObjArgs(self->raw, _PyIO_str_readable, NULL); } static PyObject * buffered_writable(buffered *self, PyObject *args) { CHECK_INITIALIZED(self) return PyObject_CallMethodObjArgs(self->raw, _PyIO_str_writable, NULL); } static PyObject * buffered_name_get(buffered *self, void *context) { CHECK_INITIALIZED(self) return PyObject_GetAttrString(self->raw, "name"); } static PyObject * buffered_mode_get(buffered *self, void *context) { CHECK_INITIALIZED(self) return PyObject_GetAttrString(self->raw, "mode"); } /* Lower-level APIs */ static PyObject * buffered_fileno(buffered *self, PyObject *args) { CHECK_INITIALIZED(self) return PyObject_CallMethodObjArgs(self->raw, _PyIO_str_fileno, NULL); } static PyObject * buffered_isatty(buffered *self, PyObject *args) { CHECK_INITIALIZED(self) return PyObject_CallMethodObjArgs(self->raw, _PyIO_str_isatty, NULL); } /* Serialization */ static PyObject * buffered_getstate(buffered *self, PyObject *args) { PyErr_Format(PyExc_TypeError, "cannot serialize '%s' object", Py_TYPE(self)->tp_name); return NULL; } /* Forward decls */ static PyObject * _bufferedwriter_flush_unlocked(buffered *, int); static Py_ssize_t _bufferedreader_fill_buffer(buffered *self); static void _bufferedreader_reset_buf(buffered *self); static void _bufferedwriter_reset_buf(buffered *self); static PyObject * _bufferedreader_peek_unlocked(buffered *self, Py_ssize_t); static PyObject * _bufferedreader_read_all(buffered *self); static PyObject * _bufferedreader_read_fast(buffered *self, Py_ssize_t); static PyObject * _bufferedreader_read_generic(buffered *self, Py_ssize_t); static Py_ssize_t _bufferedreader_raw_read(buffered *self, char *start, Py_ssize_t len); /* * Helpers */ /* Returns the address of the `written` member if a BlockingIOError was raised, NULL otherwise. The error is always re-raised. */ static Py_ssize_t * _buffered_check_blocking_error(void) { PyObject *t, *v, *tb; PyBlockingIOErrorObject *err; PyErr_Fetch(&t, &v, &tb); if (v == NULL || !PyErr_GivenExceptionMatches(v, PyExc_BlockingIOError)) { PyErr_Restore(t, v, tb); return NULL; } err = (PyBlockingIOErrorObject *) v; /* TODO: sanity check (err->written >= 0) */ PyErr_Restore(t, v, tb); return &err->written; } static Py_off_t _buffered_raw_tell(buffered *self) { Py_off_t n; PyObject *res; res = PyObject_CallMethodObjArgs(self->raw, _PyIO_str_tell, NULL); if (res == NULL) return -1; n = PyNumber_AsOff_t(res, PyExc_ValueError); Py_DECREF(res); if (n < 0) { if (!PyErr_Occurred()) PyErr_Format(PyExc_IOError, "Raw stream returned invalid position %" PY_PRIdOFF, (PY_OFF_T_COMPAT)n); return -1; } self->abs_pos = n; return n; } static Py_off_t _buffered_raw_seek(buffered *self, Py_off_t target, int whence) { PyObject *res, *posobj, *whenceobj; Py_off_t n; posobj = PyLong_FromOff_t(target); if (posobj == NULL) return -1; whenceobj = PyLong_FromLong(whence); if (whenceobj == NULL) { Py_DECREF(posobj); return -1; } res = PyObject_CallMethodObjArgs(self->raw, _PyIO_str_seek, posobj, whenceobj, NULL); Py_DECREF(posobj); Py_DECREF(whenceobj); if (res == NULL) return -1; n = PyNumber_AsOff_t(res, PyExc_ValueError); Py_DECREF(res); if (n < 0) { if (!PyErr_Occurred()) PyErr_Format(PyExc_IOError, "Raw stream returned invalid position %" PY_PRIdOFF, (PY_OFF_T_COMPAT)n); return -1; } self->abs_pos = n; return n; } static int _buffered_init(buffered *self) { Py_ssize_t n; if (self->buffer_size <= 0) { PyErr_SetString(PyExc_ValueError, "buffer size must be strictly positive"); return -1; } if (self->buffer) PyMem_Free(self->buffer); self->buffer = PyMem_Malloc(self->buffer_size); if (self->buffer == NULL) { PyErr_NoMemory(); return -1; } #ifdef WITH_THREAD if (self->lock) PyThread_free_lock(self->lock); self->lock = PyThread_allocate_lock(); if (self->lock == NULL) { PyErr_SetString(PyExc_RuntimeError, "can't allocate read lock"); return -1; } self->owner = 0; #endif /* Find out whether buffer_size is a power of 2 */ /* XXX is this optimization useful? */ for (n = self->buffer_size - 1; n & 1; n >>= 1) ; if (n == 0) self->buffer_mask = self->buffer_size - 1; else self->buffer_mask = 0; if (_buffered_raw_tell(self) == -1) PyErr_Clear(); return 0; } /* Return 1 if an EnvironmentError with errno == EINTR is set (and then clears the error indicator), 0 otherwise. Should only be called when PyErr_Occurred() is true. */ static int _trap_eintr(void) { static PyObject *eintr_int = NULL; PyObject *typ, *val, *tb; PyEnvironmentErrorObject *env_err; if (eintr_int == NULL) { eintr_int = PyLong_FromLong(EINTR); assert(eintr_int != NULL); } if (!PyErr_ExceptionMatches(PyExc_EnvironmentError)) return 0; PyErr_Fetch(&typ, &val, &tb); PyErr_NormalizeException(&typ, &val, &tb); env_err = (PyEnvironmentErrorObject *) val; assert(env_err != NULL); if (env_err->myerrno != NULL && PyObject_RichCompareBool(env_err->myerrno, eintr_int, Py_EQ) > 0) { Py_DECREF(typ); Py_DECREF(val); Py_XDECREF(tb); return 1; } /* This silences any error set by PyObject_RichCompareBool() */ PyErr_Restore(typ, val, tb); return 0; } /* * Shared methods and wrappers */ static PyObject * buffered_flush(buffered *self, PyObject *args) { PyObject *res; CHECK_INITIALIZED(self) CHECK_CLOSED(self, "flush of closed file") if (!ENTER_BUFFERED(self)) return NULL; res = _bufferedwriter_flush_unlocked(self, 0); if (res != NULL && self->readable) { /* Rewind the raw stream so that its position corresponds to the current logical position. */ Py_off_t n; n = _buffered_raw_seek(self, -RAW_OFFSET(self), 1); if (n == -1) Py_CLEAR(res); _bufferedreader_reset_buf(self); } LEAVE_BUFFERED(self) return res; } static PyObject * buffered_peek(buffered *self, PyObject *args) { Py_ssize_t n = 0; PyObject *res = NULL; CHECK_INITIALIZED(self) if (!PyArg_ParseTuple(args, "|n:peek", &n)) { return NULL; } if (!ENTER_BUFFERED(self)) return NULL; if (self->writable) { res = _bufferedwriter_flush_unlocked(self, 1); if (res == NULL) goto end; Py_CLEAR(res); } res = _bufferedreader_peek_unlocked(self, n); end: LEAVE_BUFFERED(self) return res; } static PyObject * buffered_read(buffered *self, PyObject *args) { Py_ssize_t n = -1; PyObject *res; CHECK_INITIALIZED(self) if (!PyArg_ParseTuple(args, "|O&:read", &_PyIO_ConvertSsize_t, &n)) { return NULL; } if (n < -1) { PyErr_SetString(PyExc_ValueError, "read length must be positive or -1"); return NULL; } CHECK_CLOSED(self, "read of closed file") if (n == -1) { /* The number of bytes is unspecified, read until the end of stream */ if (!ENTER_BUFFERED(self)) return NULL; res = _bufferedreader_read_all(self); LEAVE_BUFFERED(self) } else { res = _bufferedreader_read_fast(self, n); if (res == Py_None) { Py_DECREF(res); if (!ENTER_BUFFERED(self)) return NULL; res = _bufferedreader_read_generic(self, n); LEAVE_BUFFERED(self) } } return res; } static PyObject * buffered_read1(buffered *self, PyObject *args) { Py_ssize_t n, have, r; PyObject *res = NULL; CHECK_INITIALIZED(self) if (!PyArg_ParseTuple(args, "n:read1", &n)) { return NULL; } if (n < 0) { PyErr_SetString(PyExc_ValueError, "read length must be positive"); return NULL; } if (n == 0) return PyBytes_FromStringAndSize(NULL, 0); if (!ENTER_BUFFERED(self)) return NULL; if (self->writable) { res = _bufferedwriter_flush_unlocked(self, 1); if (res == NULL) goto end; Py_CLEAR(res); } /* Return up to n bytes. If at least one byte is buffered, we only return buffered bytes. Otherwise, we do one raw read. */ /* XXX: this mimicks the io.py implementation but is probably wrong. If we need to read from the raw stream, then we could actually read all `n` bytes asked by the caller (and possibly more, so as to fill our buffer for the next reads). */ have = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t); if (have > 0) { if (n > have) n = have; res = PyBytes_FromStringAndSize(self->buffer + self->pos, n); if (res == NULL) goto end; self->pos += n; goto end; } /* Fill the buffer from the raw stream, and copy it to the result. */ _bufferedreader_reset_buf(self); r = _bufferedreader_fill_buffer(self); if (r == -1) goto end; if (r == -2) r = 0; if (n > r) n = r; res = PyBytes_FromStringAndSize(self->buffer, n); if (res == NULL) goto end; self->pos = n; end: LEAVE_BUFFERED(self) return res; } static PyObject * buffered_readinto(buffered *self, PyObject *args) { Py_buffer buf; Py_ssize_t n, written = 0, remaining; PyObject *res = NULL; CHECK_INITIALIZED(self) if (!PyArg_ParseTuple(args, "w*:readinto", &buf)) return NULL; n = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t); if (n > 0) { if (n >= buf.len) { memcpy(buf.buf, self->buffer + self->pos, buf.len); self->pos += buf.len; res = PyLong_FromSsize_t(buf.len); goto end_unlocked; } memcpy(buf.buf, self->buffer + self->pos, n); self->pos += n; written = n; } if (!ENTER_BUFFERED(self)) goto end_unlocked; if (self->writable) { res = _bufferedwriter_flush_unlocked(self, 0); if (res == NULL) goto end; Py_CLEAR(res); } _bufferedreader_reset_buf(self); self->pos = 0; for (remaining = buf.len - written; remaining > 0; written += n, remaining -= n) { /* If remaining bytes is larger than internal buffer size, copy * directly into caller's buffer. */ if (remaining > self->buffer_size) { n = _bufferedreader_raw_read(self, (char *) buf.buf + written, remaining); } else { n = _bufferedreader_fill_buffer(self); if (n > 0) { if (n > remaining) n = remaining; memcpy((char *) buf.buf + written, self->buffer + self->pos, n); self->pos += n; continue; /* short circuit */ } } if (n == 0 || (n == -2 && written > 0)) break; if (n < 0) { if (n == -2) { Py_INCREF(Py_None); res = Py_None; } goto end; } } res = PyLong_FromSsize_t(written); end: LEAVE_BUFFERED(self); end_unlocked: PyBuffer_Release(&buf); return res; } static PyObject * _buffered_readline(buffered *self, Py_ssize_t limit) { PyObject *res = NULL; PyObject *chunks = NULL; Py_ssize_t n, written = 0; const char *start, *s, *end; CHECK_CLOSED(self, "readline of closed file") /* First, try to find a line in the buffer. This can run unlocked because the calls to the C API are simple enough that they can't trigger any thread switch. */ n = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t); if (limit >= 0 && n > limit) n = limit; start = self->buffer + self->pos; s = memchr(start, '\n', n); if (s != NULL) { res = PyBytes_FromStringAndSize(start, s - start + 1); if (res != NULL) self->pos += s - start + 1; goto end_unlocked; } if (n == limit) { res = PyBytes_FromStringAndSize(start, n); if (res != NULL) self->pos += n; goto end_unlocked; } if (!ENTER_BUFFERED(self)) goto end_unlocked; /* Now we try to get some more from the raw stream */ if (self->writable) { res = _bufferedwriter_flush_unlocked(self, 1); if (res == NULL) goto end; Py_CLEAR(res); } chunks = PyList_New(0); if (chunks == NULL) goto end; if (n > 0) { res = PyBytes_FromStringAndSize(start, n); if (res == NULL) goto end; if (PyList_Append(chunks, res) < 0) { Py_CLEAR(res); goto end; } Py_CLEAR(res); written += n; if (limit >= 0) limit -= n; } for (;;) { _bufferedreader_reset_buf(self); n = _bufferedreader_fill_buffer(self); if (n == -1) goto end; if (n <= 0) break; if (limit >= 0 && n > limit) n = limit; start = self->buffer; end = start + n; s = start; while (s < end) { if (*s++ == '\n') { res = PyBytes_FromStringAndSize(start, s - start); if (res == NULL) goto end; self->pos = s - start; goto found; } } res = PyBytes_FromStringAndSize(start, n); if (res == NULL) goto end; if (n == limit) { self->pos = n; break; } if (PyList_Append(chunks, res) < 0) { Py_CLEAR(res); goto end; } Py_CLEAR(res); written += n; if (limit >= 0) limit -= n; } found: if (res != NULL && PyList_Append(chunks, res) < 0) { Py_CLEAR(res); goto end; } Py_CLEAR(res); res = _PyBytes_Join(_PyIO_empty_bytes, chunks); end: LEAVE_BUFFERED(self) end_unlocked: Py_XDECREF(chunks); return res; } static PyObject * buffered_readline(buffered *self, PyObject *args) { Py_ssize_t limit = -1; CHECK_INITIALIZED(self) if (!PyArg_ParseTuple(args, "|O&:readline", &_PyIO_ConvertSsize_t, &limit)) return NULL; return _buffered_readline(self, limit); } static PyObject * buffered_tell(buffered *self, PyObject *args) { Py_off_t pos; CHECK_INITIALIZED(self) pos = _buffered_raw_tell(self); if (pos == -1) return NULL; pos -= RAW_OFFSET(self); /* TODO: sanity check (pos >= 0) */ return PyLong_FromOff_t(pos); } static PyObject * buffered_seek(buffered *self, PyObject *args) { Py_off_t target, n; int whence = 0; PyObject *targetobj, *res = NULL; CHECK_INITIALIZED(self) if (!PyArg_ParseTuple(args, "O|i:seek", &targetobj, &whence)) { return NULL; } if (whence < 0 || whence > 2) { PyErr_Format(PyExc_ValueError, "whence must be between 0 and 2, not %d", whence); return NULL; } CHECK_CLOSED(self, "seek of closed file") target = PyNumber_AsOff_t(targetobj, PyExc_ValueError); if (target == -1 && PyErr_Occurred()) return NULL; if (whence != 2 && self->readable) { Py_off_t current, avail; /* Check if seeking leaves us inside the current buffer, so as to return quickly if possible. Also, we needn't take the lock in this fast path. Don't know how to do that when whence == 2, though. */ /* NOTE: RAW_TELL() can release the GIL but the object is in a stable state at this point. */ current = RAW_TELL(self); avail = READAHEAD(self); if (avail > 0) { Py_off_t offset; if (whence == 0) offset = target - (current - RAW_OFFSET(self)); else offset = target; if (offset >= -self->pos && offset <= avail) { self->pos += offset; return PyLong_FromOff_t(current - avail + offset); } } } if (!ENTER_BUFFERED(self)) return NULL; /* Fallback: invoke raw seek() method and clear buffer */ if (self->writable) { res = _bufferedwriter_flush_unlocked(self, 0); if (res == NULL) goto end; Py_CLEAR(res); _bufferedwriter_reset_buf(self); } /* TODO: align on block boundary and read buffer if needed? */ if (whence == 1) target -= RAW_OFFSET(self); n = _buffered_raw_seek(self, target, whence); if (n == -1) goto end; self->raw_pos = -1; res = PyLong_FromOff_t(n); if (res != NULL && self->readable) _bufferedreader_reset_buf(self); end: LEAVE_BUFFERED(self) return res; } static PyObject * buffered_truncate(buffered *self, PyObject *args) { PyObject *pos = Py_None; PyObject *res = NULL; CHECK_INITIALIZED(self) if (!PyArg_ParseTuple(args, "|O:truncate", &pos)) { return NULL; } if (!ENTER_BUFFERED(self)) return NULL; if (self->writable) { res = _bufferedwriter_flush_unlocked(self, 0); if (res == NULL) goto end; Py_CLEAR(res); } if (self->readable) { if (pos == Py_None) { /* Rewind the raw stream so that its position corresponds to the current logical position. */ if (_buffered_raw_seek(self, -RAW_OFFSET(self), 1) == -1) goto end; } _bufferedreader_reset_buf(self); } res = PyObject_CallMethodObjArgs(self->raw, _PyIO_str_truncate, pos, NULL); if (res == NULL) goto end; /* Reset cached position */ if (_buffered_raw_tell(self) == -1) PyErr_Clear(); end: LEAVE_BUFFERED(self) return res; } static PyObject * buffered_iternext(buffered *self) { PyObject *line; PyTypeObject *tp; CHECK_INITIALIZED(self); tp = Py_TYPE(self); if (tp == &PyBufferedReader_Type || tp == &PyBufferedRandom_Type) { /* Skip method call overhead for speed */ line = _buffered_readline(self, -1); } else { line = PyObject_CallMethodObjArgs((PyObject *)self, _PyIO_str_readline, NULL); if (line && !PyBytes_Check(line)) { PyErr_Format(PyExc_IOError, "readline() should have returned a bytes object, " "not '%.200s'", Py_TYPE(line)->tp_name); Py_DECREF(line); return NULL; } } if (line == NULL) return NULL; if (PyBytes_GET_SIZE(line) == 0) { /* Reached EOF or would have blocked */ Py_DECREF(line); return NULL; } return line; } static PyObject * buffered_repr(buffered *self) { PyObject *nameobj, *res; nameobj = PyObject_GetAttrString((PyObject *) self, "name"); if (nameobj == NULL) { if (PyErr_ExceptionMatches(PyExc_AttributeError)) PyErr_Clear(); else return NULL; res = PyUnicode_FromFormat("<%s>", Py_TYPE(self)->tp_name); } else { res = PyUnicode_FromFormat("<%s name=%R>", Py_TYPE(self)->tp_name, nameobj); Py_DECREF(nameobj); } return res; } /* * class BufferedReader */ PyDoc_STRVAR(bufferedreader_doc, "Create a new buffered reader using the given readable raw IO object."); static void _bufferedreader_reset_buf(buffered *self) { self->read_end = -1; } static int bufferedreader_init(buffered *self, PyObject *args, PyObject *kwds) { char *kwlist[] = {"raw", "buffer_size", NULL}; Py_ssize_t buffer_size = DEFAULT_BUFFER_SIZE; PyObject *raw; self->ok = 0; self->detached = 0; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|n:BufferedReader", kwlist, &raw, &buffer_size)) { return -1; } if (_PyIOBase_check_readable(raw, Py_True) == NULL) return -1; Py_CLEAR(self->raw); Py_INCREF(raw); self->raw = raw; self->buffer_size = buffer_size; self->readable = 1; self->writable = 0; if (_buffered_init(self) < 0) return -1; _bufferedreader_reset_buf(self); self->fast_closed_checks = (Py_TYPE(self) == &PyBufferedReader_Type && Py_TYPE(raw) == &PyFileIO_Type); self->ok = 1; return 0; } static Py_ssize_t _bufferedreader_raw_read(buffered *self, char *start, Py_ssize_t len) { Py_buffer buf; PyObject *memobj, *res; Py_ssize_t n; /* NOTE: the buffer needn't be released as its object is NULL. */ if (PyBuffer_FillInfo(&buf, NULL, start, len, 0, PyBUF_CONTIG) == -1) return -1; memobj = PyMemoryView_FromBuffer(&buf); if (memobj == NULL) return -1; /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals() when EINTR occurs so we needn't do it ourselves. We then retry reading, ignoring the signal if no handler has raised (see issue #10956). */ do { res = PyObject_CallMethodObjArgs(self->raw, _PyIO_str_readinto, memobj, NULL); } while (res == NULL && _trap_eintr()); Py_DECREF(memobj); if (res == NULL) return -1; if (res == Py_None) { /* Non-blocking stream would have blocked. Special return code! */ Py_DECREF(res); return -2; } n = PyNumber_AsSsize_t(res, PyExc_ValueError); Py_DECREF(res); if (n < 0 || n > len) { PyErr_Format(PyExc_IOError, "raw readinto() returned invalid length %zd " "(should have been between 0 and %zd)", n, len); return -1; } if (n > 0 && self->abs_pos != -1) self->abs_pos += n; return n; } static Py_ssize_t _bufferedreader_fill_buffer(buffered *self) { Py_ssize_t start, len, n; if (VALID_READ_BUFFER(self)) start = Py_SAFE_DOWNCAST(self->read_end, Py_off_t, Py_ssize_t); else start = 0; len = self->buffer_size - start; n = _bufferedreader_raw_read(self, self->buffer + start, len); if (n <= 0) return n; self->read_end = start + n; self->raw_pos = start + n; return n; } static PyObject * _bufferedreader_read_all(buffered *self) { Py_ssize_t current_size; PyObject *res, *data = NULL; PyObject *chunks = PyList_New(0); if (chunks == NULL) return NULL; /* First copy what we have in the current buffer. */ current_size = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t); if (current_size) { data = PyBytes_FromStringAndSize( self->buffer + self->pos, current_size); if (data == NULL) { Py_DECREF(chunks); return NULL; } } _bufferedreader_reset_buf(self); /* We're going past the buffer's bounds, flush it */ if (self->writable) { res = _bufferedwriter_flush_unlocked(self, 1); if (res == NULL) { Py_DECREF(chunks); return NULL; } Py_CLEAR(res); } while (1) { if (data) { if (PyList_Append(chunks, data) < 0) { Py_DECREF(data); Py_DECREF(chunks); return NULL; } Py_DECREF(data); } /* Read until EOF or until read() would block. */ data = PyObject_CallMethodObjArgs(self->raw, _PyIO_str_read, NULL); if (data == NULL) { Py_DECREF(chunks); return NULL; } if (data != Py_None && !PyBytes_Check(data)) { Py_DECREF(data); Py_DECREF(chunks); PyErr_SetString(PyExc_TypeError, "read() should return bytes"); return NULL; } if (data == Py_None || PyBytes_GET_SIZE(data) == 0) { if (current_size == 0) { Py_DECREF(chunks); return data; } else { res = _PyBytes_Join(_PyIO_empty_bytes, chunks); Py_DECREF(data); Py_DECREF(chunks); return res; } } current_size += PyBytes_GET_SIZE(data); if (self->abs_pos != -1) self->abs_pos += PyBytes_GET_SIZE(data); } } /* Read n bytes from the buffer if it can, otherwise return None. This function is simple enough that it can run unlocked. */ static PyObject * _bufferedreader_read_fast(buffered *self, Py_ssize_t n) { Py_ssize_t current_size; current_size = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t); if (n <= current_size) { /* Fast path: the data to read is fully buffered. */ PyObject *res = PyBytes_FromStringAndSize(self->buffer + self->pos, n); if (res != NULL) self->pos += n; return res; } Py_RETURN_NONE; } /* Generic read function: read from the stream until enough bytes are read, * or until an EOF occurs or until read() would block. */ static PyObject * _bufferedreader_read_generic(buffered *self, Py_ssize_t n) { PyObject *res = NULL; Py_ssize_t current_size, remaining, written; char *out; current_size = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t); if (n <= current_size) return _bufferedreader_read_fast(self, n); res = PyBytes_FromStringAndSize(NULL, n); if (res == NULL) goto error; out = PyBytes_AS_STRING(res); remaining = n; written = 0; if (current_size > 0) { memcpy(out, self->buffer + self->pos, current_size); remaining -= current_size; written += current_size; } _bufferedreader_reset_buf(self); while (remaining > 0) { /* We want to read a whole block at the end into buffer. If we had readv() we could do this in one pass. */ Py_ssize_t r = MINUS_LAST_BLOCK(self, remaining); if (r == 0) break; r = _bufferedreader_raw_read(self, out + written, r); if (r == -1) goto error; if (r == 0 || r == -2) { /* EOF occurred or read() would block. */ if (r == 0 || written > 0) { if (_PyBytes_Resize(&res, written)) goto error; return res; } Py_DECREF(res); Py_INCREF(Py_None); return Py_None; } remaining -= r; written += r; } assert(remaining <= self->buffer_size); self->pos = 0; self->raw_pos = 0; self->read_end = 0; /* NOTE: when the read is satisfied, we avoid issuing any additional reads, which could block indefinitely (e.g. on a socket). See issue #9550. */ while (remaining > 0 && self->read_end < self->buffer_size) { Py_ssize_t r = _bufferedreader_fill_buffer(self); if (r == -1) goto error; if (r == 0 || r == -2) { /* EOF occurred or read() would block. */ if (r == 0 || written > 0) { if (_PyBytes_Resize(&res, written)) goto error; return res; } Py_DECREF(res); Py_INCREF(Py_None); return Py_None; } if (remaining > r) { memcpy(out + written, self->buffer + self->pos, r); written += r; self->pos += r; remaining -= r; } else if (remaining > 0) { memcpy(out + written, self->buffer + self->pos, remaining); written += remaining; self->pos += remaining; remaining = 0; } if (remaining == 0) break; } return res; error: Py_XDECREF(res); return NULL; } static PyObject * _bufferedreader_peek_unlocked(buffered *self, Py_ssize_t n) { Py_ssize_t have, r; have = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t); /* Constraints: 1. we don't want to advance the file position. 2. we don't want to lose block alignment, so we can't shift the buffer to make some place. Therefore, we either return `have` bytes (if > 0), or a full buffer. */ if (have > 0) { return PyBytes_FromStringAndSize(self->buffer + self->pos, have); } /* Fill the buffer from the raw stream, and copy it to the result. */ _bufferedreader_reset_buf(self); r = _bufferedreader_fill_buffer(self); if (r == -1) return NULL; if (r == -2) r = 0; self->pos = 0; return PyBytes_FromStringAndSize(self->buffer, r); } static PyMethodDef bufferedreader_methods[] = { /* BufferedIOMixin methods */ {"detach", (PyCFunction)buffered_detach, METH_NOARGS}, {"flush", (PyCFunction)buffered_simple_flush, METH_NOARGS}, {"close", (PyCFunction)buffered_close, METH_NOARGS}, {"seekable", (PyCFunction)buffered_seekable, METH_NOARGS}, {"readable", (PyCFunction)buffered_readable, METH_NOARGS}, {"writable", (PyCFunction)buffered_writable, METH_NOARGS}, {"fileno", (PyCFunction)buffered_fileno, METH_NOARGS}, {"isatty", (PyCFunction)buffered_isatty, METH_NOARGS}, {"_dealloc_warn", (PyCFunction)buffered_dealloc_warn, METH_O}, {"__getstate__", (PyCFunction)buffered_getstate, METH_NOARGS}, {"read", (PyCFunction)buffered_read, METH_VARARGS}, {"peek", (PyCFunction)buffered_peek, METH_VARARGS}, {"read1", (PyCFunction)buffered_read1, METH_VARARGS}, {"readinto", (PyCFunction)buffered_readinto, METH_VARARGS}, {"readline", (PyCFunction)buffered_readline, METH_VARARGS}, {"seek", (PyCFunction)buffered_seek, METH_VARARGS}, {"tell", (PyCFunction)buffered_tell, METH_NOARGS}, {"truncate", (PyCFunction)buffered_truncate, METH_VARARGS}, {NULL, NULL} }; static PyMemberDef bufferedreader_members[] = { {"raw", T_OBJECT, offsetof(buffered, raw), READONLY}, {NULL} }; static PyGetSetDef bufferedreader_getset[] = { {"closed", (getter)buffered_closed_get, NULL, NULL}, {"name", (getter)buffered_name_get, NULL, NULL}, {"mode", (getter)buffered_mode_get, NULL, NULL}, {NULL} }; PyTypeObject PyBufferedReader_Type = { PyVarObject_HEAD_INIT(NULL, 0) "_io.BufferedReader", /*tp_name*/ sizeof(buffered), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)buffered_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare */ (reprfunc)buffered_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/ bufferedreader_doc, /* tp_doc */ (traverseproc)buffered_traverse, /* tp_traverse */ (inquiry)buffered_clear, /* tp_clear */ 0, /* tp_richcompare */ offsetof(buffered, weakreflist), /*tp_weaklistoffset*/ 0, /* tp_iter */ (iternextfunc)buffered_iternext, /* tp_iternext */ bufferedreader_methods, /* tp_methods */ bufferedreader_members, /* tp_members */ bufferedreader_getset, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(buffered, dict), /* tp_dictoffset */ (initproc)bufferedreader_init, /* tp_init */ 0, /* tp_alloc */ PyType_GenericNew, /* tp_new */ }; static int complain_about_max_buffer_size(void) { if (PyErr_WarnEx(PyExc_DeprecationWarning, "max_buffer_size is deprecated", 1) < 0) return 0; return 1; } /* * class BufferedWriter */ PyDoc_STRVAR(bufferedwriter_doc, "A buffer for a writeable sequential RawIO object.\n" "\n" "The constructor creates a BufferedWriter for the given writeable raw\n" "stream. If the buffer_size is not given, it defaults to\n" "DEFAULT_BUFFER_SIZE. max_buffer_size isn't used anymore.\n" ); static void _bufferedwriter_reset_buf(buffered *self) { self->write_pos = 0; self->write_end = -1; } static int bufferedwriter_init(buffered *self, PyObject *args, PyObject *kwds) { /* TODO: properly deprecate max_buffer_size */ char *kwlist[] = {"raw", "buffer_size", "max_buffer_size", NULL}; Py_ssize_t buffer_size = DEFAULT_BUFFER_SIZE; Py_ssize_t max_buffer_size = -234; PyObject *raw; self->ok = 0; self->detached = 0; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|nn:BufferedReader", kwlist, &raw, &buffer_size, &max_buffer_size)) { return -1; } if (max_buffer_size != -234 && !complain_about_max_buffer_size()) return -1; if (_PyIOBase_check_writable(raw, Py_True) == NULL) return -1; Py_CLEAR(self->raw); Py_INCREF(raw); self->raw = raw; self->readable = 0; self->writable = 1; self->buffer_size = buffer_size; if (_buffered_init(self) < 0) return -1; _bufferedwriter_reset_buf(self); self->pos = 0; self->fast_closed_checks = (Py_TYPE(self) == &PyBufferedWriter_Type && Py_TYPE(raw) == &PyFileIO_Type); self->ok = 1; return 0; } static Py_ssize_t _bufferedwriter_raw_write(buffered *self, char *start, Py_ssize_t len) { Py_buffer buf; PyObject *memobj, *res; Py_ssize_t n; /* NOTE: the buffer needn't be released as its object is NULL. */ if (PyBuffer_FillInfo(&buf, NULL, start, len, 1, PyBUF_CONTIG_RO) == -1) return -1; memobj = PyMemoryView_FromBuffer(&buf); if (memobj == NULL) return -1; /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals() when EINTR occurs so we needn't do it ourselves. We then retry writing, ignoring the signal if no handler has raised (see issue #10956). */ do { res = PyObject_CallMethodObjArgs(self->raw, _PyIO_str_write, memobj, NULL); } while (res == NULL && _trap_eintr()); Py_DECREF(memobj); if (res == NULL) return -1; n = PyNumber_AsSsize_t(res, PyExc_ValueError); Py_DECREF(res); if (n < 0 || n > len) { PyErr_Format(PyExc_IOError, "raw write() returned invalid length %zd " "(should have been between 0 and %zd)", n, len); return -1; } if (n > 0 && self->abs_pos != -1) self->abs_pos += n; return n; } /* `restore_pos` is 1 if we need to restore the raw stream position at the end, 0 otherwise. */ static PyObject * _bufferedwriter_flush_unlocked(buffered *self, int restore_pos) { Py_ssize_t written = 0; Py_off_t n, rewind; if (!VALID_WRITE_BUFFER(self) || self->write_pos == self->write_end) goto end; /* First, rewind */ rewind = RAW_OFFSET(self) + (self->pos - self->write_pos); if (rewind != 0) { n = _buffered_raw_seek(self, -rewind, 1); if (n < 0) { goto error; } self->raw_pos -= rewind; } while (self->write_pos < self->write_end) { n = _bufferedwriter_raw_write(self, self->buffer + self->write_pos, Py_SAFE_DOWNCAST(self->write_end - self->write_pos, Py_off_t, Py_ssize_t)); if (n == -1) { Py_ssize_t *w = _buffered_check_blocking_error(); if (w == NULL) goto error; self->write_pos += *w; self->raw_pos = self->write_pos; written += *w; *w = written; /* Already re-raised */ goto error; } self->write_pos += n; self->raw_pos = self->write_pos; written += Py_SAFE_DOWNCAST(n, Py_off_t, Py_ssize_t); /* Partial writes can return successfully when interrupted by a signal (see write(2)). We must run signal handlers before blocking another time, possibly indefinitely. */ if (PyErr_CheckSignals() < 0) goto error; } if (restore_pos) { Py_off_t forward = rewind - written; if (forward != 0) { n = _buffered_raw_seek(self, forward, 1); if (n < 0) { goto error; } self->raw_pos += forward; } } _bufferedwriter_reset_buf(self); end: Py_RETURN_NONE; error: return NULL; } static PyObject * bufferedwriter_write(buffered *self, PyObject *args) { PyObject *res = NULL; Py_buffer buf; Py_ssize_t written, avail, remaining; Py_off_t offset; CHECK_INITIALIZED(self) if (!PyArg_ParseTuple(args, "y*:write", &buf)) { return NULL; } if (IS_CLOSED(self)) { PyErr_SetString(PyExc_ValueError, "write to closed file"); PyBuffer_Release(&buf); return NULL; } if (!ENTER_BUFFERED(self)) { PyBuffer_Release(&buf); return NULL; } /* Fast path: the data to write can be fully buffered. */ if (!VALID_READ_BUFFER(self) && !VALID_WRITE_BUFFER(self)) { self->pos = 0; self->raw_pos = 0; } avail = Py_SAFE_DOWNCAST(self->buffer_size - self->pos, Py_off_t, Py_ssize_t); if (buf.len <= avail) { memcpy(self->buffer + self->pos, buf.buf, buf.len); if (!VALID_WRITE_BUFFER(self) || self->write_pos > self->pos) { self->write_pos = self->pos; } ADJUST_POSITION(self, self->pos + buf.len); if (self->pos > self->write_end) self->write_end = self->pos; written = buf.len; goto end; } /* First write the current buffer */ res = _bufferedwriter_flush_unlocked(self, 0); if (res == NULL) { Py_ssize_t *w = _buffered_check_blocking_error(); if (w == NULL) goto error; if (self->readable) _bufferedreader_reset_buf(self); /* Make some place by shifting the buffer. */ assert(VALID_WRITE_BUFFER(self)); memmove(self->buffer, self->buffer + self->write_pos, Py_SAFE_DOWNCAST(self->write_end - self->write_pos, Py_off_t, Py_ssize_t)); self->write_end -= self->write_pos; self->raw_pos -= self->write_pos; self->pos -= self->write_pos; self->write_pos = 0; avail = Py_SAFE_DOWNCAST(self->buffer_size - self->write_end, Py_off_t, Py_ssize_t); if (buf.len <= avail) { /* Everything can be buffered */ PyErr_Clear(); memcpy(self->buffer + self->write_end, buf.buf, buf.len); self->write_end += buf.len; written = buf.len; goto end; } /* Buffer as much as possible. */ memcpy(self->buffer + self->write_end, buf.buf, avail); self->write_end += avail; /* Already re-raised */ *w = avail; goto error; } Py_CLEAR(res); /* Adjust the raw stream position if it is away from the logical stream position. This happens if the read buffer has been filled but not modified (and therefore _bufferedwriter_flush_unlocked() didn't rewind the raw stream by itself). Fixes issue #6629. */ offset = RAW_OFFSET(self); if (offset != 0) { if (_buffered_raw_seek(self, -offset, 1) < 0) goto error; self->raw_pos -= offset; } /* Then write buf itself. At this point the buffer has been emptied. */ remaining = buf.len; written = 0; while (remaining > self->buffer_size) { Py_ssize_t n = _bufferedwriter_raw_write( self, (char *) buf.buf + written, buf.len - written); if (n == -1) { Py_ssize_t *w = _buffered_check_blocking_error(); if (w == NULL) goto error; written += *w; remaining -= *w; if (remaining > self->buffer_size) { /* Can't buffer everything, still buffer as much as possible */ memcpy(self->buffer, (char *) buf.buf + written, self->buffer_size); self->raw_pos = 0; ADJUST_POSITION(self, self->buffer_size); self->write_end = self->buffer_size; *w = written + self->buffer_size; /* Already re-raised */ goto error; } PyErr_Clear(); break; } written += n; remaining -= n; /* Partial writes can return successfully when interrupted by a signal (see write(2)). We must run signal handlers before blocking another time, possibly indefinitely. */ if (PyErr_CheckSignals() < 0) goto error; } if (self->readable) _bufferedreader_reset_buf(self); if (remaining > 0) { memcpy(self->buffer, (char *) buf.buf + written, remaining); written += remaining; } self->write_pos = 0; /* TODO: sanity check (remaining >= 0) */ self->write_end = remaining; ADJUST_POSITION(self, remaining); self->raw_pos = 0; end: res = PyLong_FromSsize_t(written); error: LEAVE_BUFFERED(self) PyBuffer_Release(&buf); return res; } static PyMethodDef bufferedwriter_methods[] = { /* BufferedIOMixin methods */ {"close", (PyCFunction)buffered_close, METH_NOARGS}, {"detach", (PyCFunction)buffered_detach, METH_NOARGS}, {"seekable", (PyCFunction)buffered_seekable, METH_NOARGS}, {"readable", (PyCFunction)buffered_readable, METH_NOARGS}, {"writable", (PyCFunction)buffered_writable, METH_NOARGS}, {"fileno", (PyCFunction)buffered_fileno, METH_NOARGS}, {"isatty", (PyCFunction)buffered_isatty, METH_NOARGS}, {"_dealloc_warn", (PyCFunction)buffered_dealloc_warn, METH_O}, {"__getstate__", (PyCFunction)buffered_getstate, METH_NOARGS}, {"write", (PyCFunction)bufferedwriter_write, METH_VARARGS}, {"truncate", (PyCFunction)buffered_truncate, METH_VARARGS}, {"flush", (PyCFunction)buffered_flush, METH_NOARGS}, {"seek", (PyCFunction)buffered_seek, METH_VARARGS}, {"tell", (PyCFunction)buffered_tell, METH_NOARGS}, {NULL, NULL} }; static PyMemberDef bufferedwriter_members[] = { {"raw", T_OBJECT, offsetof(buffered, raw), READONLY}, {NULL} }; static PyGetSetDef bufferedwriter_getset[] = { {"closed", (getter)buffered_closed_get, NULL, NULL}, {"name", (getter)buffered_name_get, NULL, NULL}, {"mode", (getter)buffered_mode_get, NULL, NULL}, {NULL} }; PyTypeObject PyBufferedWriter_Type = { PyVarObject_HEAD_INIT(NULL, 0) "_io.BufferedWriter", /*tp_name*/ sizeof(buffered), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)buffered_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare */ (reprfunc)buffered_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/ bufferedwriter_doc, /* tp_doc */ (traverseproc)buffered_traverse, /* tp_traverse */ (inquiry)buffered_clear, /* tp_clear */ 0, /* tp_richcompare */ offsetof(buffered, weakreflist), /*tp_weaklistoffset*/ 0, /* tp_iter */ 0, /* tp_iternext */ bufferedwriter_methods, /* tp_methods */ bufferedwriter_members, /* tp_members */ bufferedwriter_getset, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(buffered, dict), /* tp_dictoffset */ (initproc)bufferedwriter_init, /* tp_init */ 0, /* tp_alloc */ PyType_GenericNew, /* tp_new */ }; /* * BufferedRWPair */ PyDoc_STRVAR(bufferedrwpair_doc, "A buffered reader and writer object together.\n" "\n" "A buffered reader object and buffered writer object put together to\n" "form a sequential IO object that can read and write. This is typically\n" "used with a socket or two-way pipe.\n" "\n" "reader and writer are RawIOBase objects that are readable and\n" "writeable respectively. If the buffer_size is omitted it defaults to\n" "DEFAULT_BUFFER_SIZE.\n" ); /* XXX The usefulness of this (compared to having two separate IO objects) is * questionable. */ typedef struct { PyObject_HEAD buffered *reader; buffered *writer; PyObject *dict; PyObject *weakreflist; } rwpair; static int bufferedrwpair_init(rwpair *self, PyObject *args, PyObject *kwds) { PyObject *reader, *writer; Py_ssize_t buffer_size = DEFAULT_BUFFER_SIZE; Py_ssize_t max_buffer_size = -234; if (!PyArg_ParseTuple(args, "OO|nn:BufferedRWPair", &reader, &writer, &buffer_size, &max_buffer_size)) { return -1; } if (max_buffer_size != -234 && !complain_about_max_buffer_size()) return -1; if (_PyIOBase_check_readable(reader, Py_True) == NULL) return -1; if (_PyIOBase_check_writable(writer, Py_True) == NULL) return -1; self->reader = (buffered *) PyObject_CallFunction( (PyObject *) &PyBufferedReader_Type, "On", reader, buffer_size); if (self->reader == NULL) return -1; self->writer = (buffered *) PyObject_CallFunction( (PyObject *) &PyBufferedWriter_Type, "On", writer, buffer_size); if (self->writer == NULL) { Py_CLEAR(self->reader); return -1; } return 0; } static int bufferedrwpair_traverse(rwpair *self, visitproc visit, void *arg) { Py_VISIT(self->dict); return 0; } static int bufferedrwpair_clear(rwpair *self) { Py_CLEAR(self->reader); Py_CLEAR(self->writer); Py_CLEAR(self->dict); return 0; } static void bufferedrwpair_dealloc(rwpair *self) { _PyObject_GC_UNTRACK(self); Py_CLEAR(self->reader); Py_CLEAR(self->writer); Py_CLEAR(self->dict); Py_TYPE(self)->tp_free((PyObject *) self); } static PyObject * _forward_call(buffered *self, const char *name, PyObject *args) { PyObject *func = PyObject_GetAttrString((PyObject *)self, name); PyObject *ret; if (func == NULL) { PyErr_SetString(PyExc_AttributeError, name); return NULL; } ret = PyObject_CallObject(func, args); Py_DECREF(func); return ret; } static PyObject * bufferedrwpair_read(rwpair *self, PyObject *args) { return _forward_call(self->reader, "read", args); } static PyObject * bufferedrwpair_peek(rwpair *self, PyObject *args) { return _forward_call(self->reader, "peek", args); } static PyObject * bufferedrwpair_read1(rwpair *self, PyObject *args) { return _forward_call(self->reader, "read1", args); } static PyObject * bufferedrwpair_readinto(rwpair *self, PyObject *args) { return _forward_call(self->reader, "readinto", args); } static PyObject * bufferedrwpair_write(rwpair *self, PyObject *args) { return _forward_call(self->writer, "write", args); } static PyObject * bufferedrwpair_flush(rwpair *self, PyObject *args) { return _forward_call(self->writer, "flush", args); } static PyObject * bufferedrwpair_readable(rwpair *self, PyObject *args) { return _forward_call(self->reader, "readable", args); } static PyObject * bufferedrwpair_writable(rwpair *self, PyObject *args) { return _forward_call(self->writer, "writable", args); } static PyObject * bufferedrwpair_close(rwpair *self, PyObject *args) { PyObject *ret = _forward_call(self->writer, "close", args); if (ret == NULL) return NULL; Py_DECREF(ret); return _forward_call(self->reader, "close", args); } static PyObject * bufferedrwpair_isatty(rwpair *self, PyObject *args) { PyObject *ret = _forward_call(self->writer, "isatty", args); if (ret != Py_False) { /* either True or exception */ return ret; } Py_DECREF(ret); return _forward_call(self->reader, "isatty", args); } static PyObject * bufferedrwpair_closed_get(rwpair *self, void *context) { return PyObject_GetAttr((PyObject *) self->writer, _PyIO_str_closed); } static PyMethodDef bufferedrwpair_methods[] = { {"read", (PyCFunction)bufferedrwpair_read, METH_VARARGS}, {"peek", (PyCFunction)bufferedrwpair_peek, METH_VARARGS}, {"read1", (PyCFunction)bufferedrwpair_read1, METH_VARARGS}, {"readinto", (PyCFunction)bufferedrwpair_readinto, METH_VARARGS}, {"write", (PyCFunction)bufferedrwpair_write, METH_VARARGS}, {"flush", (PyCFunction)bufferedrwpair_flush, METH_NOARGS}, {"readable", (PyCFunction)bufferedrwpair_readable, METH_NOARGS}, {"writable", (PyCFunction)bufferedrwpair_writable, METH_NOARGS}, {"close", (PyCFunction)bufferedrwpair_close, METH_NOARGS}, {"isatty", (PyCFunction)bufferedrwpair_isatty, METH_NOARGS}, {"__getstate__", (PyCFunction)buffered_getstate, METH_NOARGS}, {NULL, NULL} }; static PyGetSetDef bufferedrwpair_getset[] = { {"closed", (getter)bufferedrwpair_closed_get, NULL, NULL}, {NULL} }; PyTypeObject PyBufferedRWPair_Type = { PyVarObject_HEAD_INIT(NULL, 0) "_io.BufferedRWPair", /*tp_name*/ sizeof(rwpair), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)bufferedrwpair_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare */ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ bufferedrwpair_doc, /* tp_doc */ (traverseproc)bufferedrwpair_traverse, /* tp_traverse */ (inquiry)bufferedrwpair_clear, /* tp_clear */ 0, /* tp_richcompare */ offsetof(rwpair, weakreflist), /*tp_weaklistoffset*/ 0, /* tp_iter */ 0, /* tp_iternext */ bufferedrwpair_methods, /* tp_methods */ 0, /* tp_members */ bufferedrwpair_getset, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(rwpair, dict), /* tp_dictoffset */ (initproc)bufferedrwpair_init, /* tp_init */ 0, /* tp_alloc */ PyType_GenericNew, /* tp_new */ }; /* * BufferedRandom */ PyDoc_STRVAR(bufferedrandom_doc, "A buffered interface to random access streams.\n" "\n" "The constructor creates a reader and writer for a seekable stream,\n" "raw, given in the first argument. If the buffer_size is omitted it\n" "defaults to DEFAULT_BUFFER_SIZE. max_buffer_size isn't used anymore.\n" ); static int bufferedrandom_init(buffered *self, PyObject *args, PyObject *kwds) { char *kwlist[] = {"raw", "buffer_size", "max_buffer_size", NULL}; Py_ssize_t buffer_size = DEFAULT_BUFFER_SIZE; Py_ssize_t max_buffer_size = -234; PyObject *raw; self->ok = 0; self->detached = 0; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|nn:BufferedReader", kwlist, &raw, &buffer_size, &max_buffer_size)) { return -1; } if (max_buffer_size != -234 && !complain_about_max_buffer_size()) return -1; if (_PyIOBase_check_seekable(raw, Py_True) == NULL) return -1; if (_PyIOBase_check_readable(raw, Py_True) == NULL) return -1; if (_PyIOBase_check_writable(raw, Py_True) == NULL) return -1; Py_CLEAR(self->raw); Py_INCREF(raw); self->raw = raw; self->buffer_size = buffer_size; self->readable = 1; self->writable = 1; if (_buffered_init(self) < 0) return -1; _bufferedreader_reset_buf(self); _bufferedwriter_reset_buf(self); self->pos = 0; self->fast_closed_checks = (Py_TYPE(self) == &PyBufferedRandom_Type && Py_TYPE(raw) == &PyFileIO_Type); self->ok = 1; return 0; } static PyMethodDef bufferedrandom_methods[] = { /* BufferedIOMixin methods */ {"close", (PyCFunction)buffered_close, METH_NOARGS}, {"detach", (PyCFunction)buffered_detach, METH_NOARGS}, {"seekable", (PyCFunction)buffered_seekable, METH_NOARGS}, {"readable", (PyCFunction)buffered_readable, METH_NOARGS}, {"writable", (PyCFunction)buffered_writable, METH_NOARGS}, {"fileno", (PyCFunction)buffered_fileno, METH_NOARGS}, {"isatty", (PyCFunction)buffered_isatty, METH_NOARGS}, {"_dealloc_warn", (PyCFunction)buffered_dealloc_warn, METH_O}, {"__getstate__", (PyCFunction)buffered_getstate, METH_NOARGS}, {"flush", (PyCFunction)buffered_flush, METH_NOARGS}, {"seek", (PyCFunction)buffered_seek, METH_VARARGS}, {"tell", (PyCFunction)buffered_tell, METH_NOARGS}, {"truncate", (PyCFunction)buffered_truncate, METH_VARARGS}, {"read", (PyCFunction)buffered_read, METH_VARARGS}, {"read1", (PyCFunction)buffered_read1, METH_VARARGS}, {"readinto", (PyCFunction)buffered_readinto, METH_VARARGS}, {"readline", (PyCFunction)buffered_readline, METH_VARARGS}, {"peek", (PyCFunction)buffered_peek, METH_VARARGS}, {"write", (PyCFunction)bufferedwriter_write, METH_VARARGS}, {NULL, NULL} }; static PyMemberDef bufferedrandom_members[] = { {"raw", T_OBJECT, offsetof(buffered, raw), READONLY}, {NULL} }; static PyGetSetDef bufferedrandom_getset[] = { {"closed", (getter)buffered_closed_get, NULL, NULL}, {"name", (getter)buffered_name_get, NULL, NULL}, {"mode", (getter)buffered_mode_get, NULL, NULL}, {NULL} }; PyTypeObject PyBufferedRandom_Type = { PyVarObject_HEAD_INIT(NULL, 0) "_io.BufferedRandom", /*tp_name*/ sizeof(buffered), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)buffered_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare */ (reprfunc)buffered_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/ bufferedrandom_doc, /* tp_doc */ (traverseproc)buffered_traverse, /* tp_traverse */ (inquiry)buffered_clear, /* tp_clear */ 0, /* tp_richcompare */ offsetof(buffered, weakreflist), /*tp_weaklistoffset*/ 0, /* tp_iter */ (iternextfunc)buffered_iternext, /* tp_iternext */ bufferedrandom_methods, /* tp_methods */ bufferedrandom_members, /* tp_members */ bufferedrandom_getset, /* tp_getset */ 0, /* tp_base */ 0, /*tp_dict*/ 0, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(buffered, dict), /*tp_dictoffset*/ (initproc)bufferedrandom_init, /* tp_init */ 0, /* tp_alloc */ PyType_GenericNew, /* tp_new */ };
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/python_70056-70059.c
manybugs_data_70
/*--------------------------------------------------------------------*/ /*--- Startup: the real stuff m_main.c ---*/ /*--------------------------------------------------------------------*/ /* This file is part of Valgrind, a dynamic binary instrumentation framework. Copyright (C) 2000-2012 Julian Seward [email protected] This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. The GNU General Public License is contained in the file COPYING. */ #include "pub_core_basics.h" #include "pub_core_vki.h" #include "pub_core_vkiscnums.h" #include "pub_core_libcsetjmp.h" // to keep _threadstate.h happy #include "pub_core_threadstate.h" #include "pub_core_xarray.h" #include "pub_core_clientstate.h" #include "pub_core_aspacemgr.h" #include "pub_core_aspacehl.h" #include "pub_core_commandline.h" #include "pub_core_debuglog.h" #include "pub_core_errormgr.h" #include "pub_core_execontext.h" #include "pub_core_gdbserver.h" #include "pub_core_initimg.h" #include "pub_core_libcbase.h" #include "pub_core_libcassert.h" #include "pub_core_libcfile.h" #include "pub_core_libcprint.h" #include "pub_core_libcproc.h" #include "pub_core_libcsignal.h" #include "pub_core_syscall.h" // VG_(strerror) #include "pub_core_mach.h" #include "pub_core_machine.h" #include "pub_core_mallocfree.h" #include "pub_core_options.h" #include "pub_core_debuginfo.h" #include "pub_core_redir.h" #include "pub_core_scheduler.h" #include "pub_core_seqmatch.h" // For VG_(string_match) #include "pub_core_signals.h" #include "pub_core_stacks.h" // For VG_(register_stack) #include "pub_core_syswrap.h" #include "pub_core_tooliface.h" #include "pub_core_translate.h" // For VG_(translate) #include "pub_core_trampoline.h" #include "pub_core_transtab.h" #include "pub_tool_inner.h" #if defined(ENABLE_INNER_CLIENT_REQUEST) #include "valgrind.h" #endif /*====================================================================*/ /*=== Counters, for profiling purposes only ===*/ /*====================================================================*/ static void print_all_stats ( void ) { VG_(print_translation_stats)(); VG_(print_tt_tc_stats)(); VG_(print_scheduler_stats)(); VG_(print_ExeContext_stats)(); VG_(print_errormgr_stats)(); // Memory stats if (VG_(clo_verbosity) > 2) { VG_(message)(Vg_DebugMsg, "\n"); VG_(message)(Vg_DebugMsg, "------ Valgrind's internal memory use stats follow ------\n" ); VG_(sanity_check_malloc_all)(); VG_(message)(Vg_DebugMsg, "------\n" ); VG_(print_all_arena_stats)(); VG_(message)(Vg_DebugMsg, "\n"); } } /*====================================================================*/ /*=== Command-line: variables, processing, etc ===*/ /*====================================================================*/ // See pub_{core,tool}_options.h for explanations of all these. static void usage_NORETURN ( Bool debug_help ) { /* 'usage1' contains a %s - for the name of the GDB executable - for the name of vgdb's path prefix which must be supplied when they are VG_(printf)'d. */ Char* usage1 = "usage: valgrind [options] prog-and-args\n" "\n" " tool-selection option, with default in [ ]:\n" " --tool=<name> use the Valgrind tool named <name> [memcheck]\n" "\n" " basic user options for all Valgrind tools, with defaults in [ ]:\n" " -h --help show this message\n" " --help-debug show this message, plus debugging options\n" " --version show version\n" " -q --quiet run silently; only print error msgs\n" " -v --verbose be more verbose -- show misc extra info\n" " --trace-children=no|yes Valgrind-ise child processes (follow execve)? [no]\n" " --trace-children-skip=patt1,patt2,... specifies a list of executables\n" " that --trace-children=yes should not trace into\n" " --trace-children-skip-by-arg=patt1,patt2,... same as --trace-children-skip=\n" " but check the argv[] entries for children, rather\n" " than the exe name, to make a follow/no-follow decision\n" " --child-silent-after-fork=no|yes omit child output between fork & exec? [no]\n" " --vgdb=no|yes|full activate gdbserver? [yes]\n" " full is slower but provides precise watchpoint/step\n" " --vgdb-error=<number> invoke gdbserver after <number> errors [%d]\n" " to get started quickly, use --vgdb-error=0\n" " and follow the on-screen directions\n" " --track-fds=no|yes track open file descriptors? [no]\n" " --time-stamp=no|yes add timestamps to log messages? [no]\n" " --log-fd=<number> log messages to file descriptor [2=stderr]\n" " --log-file=<file> log messages to <file>\n" " --log-socket=ipaddr:port log messages to socket ipaddr:port\n" "\n" " user options for Valgrind tools that report errors:\n" " --xml=yes emit error output in XML (some tools only)\n" " --xml-fd=<number> XML output to file descriptor\n" " --xml-file=<file> XML output to <file>\n" " --xml-socket=ipaddr:port XML output to socket ipaddr:port\n" " --xml-user-comment=STR copy STR verbatim into XML output\n" " --demangle=no|yes automatically demangle C++ names? [yes]\n" " --num-callers=<number> show <number> callers in stack traces [12]\n" " --error-limit=no|yes stop showing new errors if too many? [yes]\n" " --error-exitcode=<number> exit code to return if errors found [0=disable]\n" " --show-below-main=no|yes continue stack traces below main() [no]\n" " --suppressions=<filename> suppress errors described in <filename>\n" " --gen-suppressions=no|yes|all print suppressions for errors? [no]\n" " --db-attach=no|yes start debugger when errors detected? [no]\n" " --db-command=<command> command to start debugger [%s -nw %%f %%p]\n" " --input-fd=<number> file descriptor for input [0=stdin]\n" " --dsymutil=no|yes run dsymutil on Mac OS X when helpful? [no]\n" " --max-stackframe=<number> assume stack switch for SP changes larger\n" " than <number> bytes [2000000]\n" " --main-stacksize=<number> set size of main thread's stack (in bytes)\n" " [use current 'ulimit' value]\n" "\n" " user options for Valgrind tools that replace malloc:\n" " --alignment=<number> set minimum alignment of heap allocations [%s]\n" " --redzone-size=<number> set minimum size of redzones added before/after\n" " heap blocks (in bytes). [%s]\n" "\n" " uncommon user options for all Valgrind tools:\n" " --fullpath-after= (with nothing after the '=')\n" " show full source paths in call stacks\n" " --fullpath-after=string like --fullpath-after=, but only show the\n" " part of the path after 'string'. Allows removal\n" " of path prefixes. Use this flag multiple times\n" " to specify a set of prefixes to remove.\n" " --smc-check=none|stack|all|all-non-file [stack]\n" " checks for self-modifying code: none, only for\n" " code found in stacks, for all code, or for all\n" " code except that from file-backed mappings\n" " --read-var-info=yes|no read debug info on stack and global variables\n" " and use it to print better error messages in\n" " tools that make use of it (Memcheck, Helgrind,\n" " DRD) [no]\n" " --vgdb-poll=<number> gdbserver poll max every <number> basic blocks [%d] \n" " --vgdb-shadow-registers=no|yes let gdb see the shadow registers [no]\n" " --vgdb-prefix=<prefix> prefix for vgdb FIFOs [%s]\n" " --run-libc-freeres=no|yes free up glibc memory at exit on Linux? [yes]\n" " --sim-hints=hint1,hint2,... known hints:\n" " lax-ioctls, enable-outer, fuse-compatible [none]\n" " --fair-sched=no|yes|try schedule threads fairly on multicore systems [no]\n" " --kernel-variant=variant1,variant2,... known variants: bproc [none]\n" " handle non-standard kernel variants\n" " --show-emwarns=no|yes show warnings about emulation limits? [no]\n" " --require-text-symbol=:sonamepattern:symbolpattern abort run if the\n" " stated shared object doesn't have the stated\n" " text symbol. Patterns can contain ? and *.\n" " --soname-synonyms=syn1=pattern1,syn2=pattern2,... synonym soname\n" " patterns for some Valgrind wrapping\n" " or replacement (such as malloc replacement)\n" "\n"; Char* usage2 = "\n" " debugging options for all Valgrind tools:\n" " -d show verbose debugging output\n" " --stats=no|yes show tool and core statistics [no]\n" " --sanity-level=<number> level of sanity checking to do [1]\n" " --trace-flags=<XXXXXXXX> show generated code? (X = 0|1) [00000000]\n" " --profile-flags=<XXXXXXXX> ditto, but for profiling (X = 0|1) [00000000]\n" " --trace-notbelow=<number> only show BBs above <number> [999999999]\n" " --trace-notabove=<number> only show BBs below <number> [0]\n" " --trace-syscalls=no|yes show all system calls? [no]\n" " --trace-signals=no|yes show signal handling details? [no]\n" " --trace-symtab=no|yes show symbol table details? [no]\n" " --trace-symtab-patt=<patt> limit debuginfo tracing to obj name <patt>\n" " --trace-cfi=no|yes show call-frame-info details? [no]\n" " --debug-dump=syms mimic /usr/bin/readelf --syms\n" " --debug-dump=line mimic /usr/bin/readelf --debug-dump=line\n" " --debug-dump=frames mimic /usr/bin/readelf --debug-dump=frames\n" " --trace-redir=no|yes show redirection details? [no]\n" " --trace-sched=no|yes show thread scheduler details? [no]\n" " --profile-heap=no|yes profile Valgrind's own space use\n" " --core-redzone=<number> set minimum size of redzones added before/after\n" " heap blocks allocated for Valgrind internal use (in bytes) [4]\n" " --wait-for-gdb=yes|no pause on startup to wait for gdb attach\n" " --sym-offsets=yes|no show syms in form 'name+offset' ? [no]\n" " --command-line-only=no|yes only use command line options [no]\n" "\n" " Vex options for all Valgrind tools:\n" " --vex-iropt-verbosity=<0..9> [0]\n" " --vex-iropt-level=<0..2> [2]\n" " --vex-iropt-register-updates=unwindregs-at-mem-access\n" " |allregs-at-mem-access\n" " |allregs-at-each-insn [unwindregs-at-mem-access]\n" " --vex-iropt-unroll-thresh=<0..400> [120]\n" " --vex-guest-max-insns=<1..100> [50]\n" " --vex-guest-chase-thresh=<0..99> [10]\n" " --vex-guest-chase-cond=no|yes [no]\n" " --trace-flags and --profile-flags values (omit the middle space):\n" " 1000 0000 show conversion into IR\n" " 0100 0000 show after initial opt\n" " 0010 0000 show after instrumentation\n" " 0001 0000 show after second opt\n" " 0000 1000 show after tree building\n" " 0000 0100 show selecting insns\n" " 0000 0010 show after reg-alloc\n" " 0000 0001 show final assembly\n" " (Nb: you need --trace-notbelow and/or --trace-notabove with --trace-flags for full details)\n" "\n" " debugging options for Valgrind tools that report errors\n" " --dump-error=<number> show translation for basic block associated\n" " with <number>'th error context [0=show none]\n" "\n" " debugging options for Valgrind tools that replace malloc:\n" " --trace-malloc=no|yes show client malloc details? [no]\n" "\n"; Char* usage3 = "\n" " Extra options read from ~/.valgrindrc, $VALGRIND_OPTS, ./.valgrindrc\n" "\n" " %s is %s\n" " Valgrind is Copyright (C) 2000-2012, and GNU GPL'd, by Julian Seward et al.\n" " LibVEX is Copyright (C) 2004-2012, and GNU GPL'd, by OpenWorks LLP et al.\n" "\n" " Bug reports, feedback, admiration, abuse, etc, to: %s.\n" "\n"; Char* gdb_path = GDB_PATH; Char default_alignment[30]; Char default_redzone_size[30]; // Ensure the message goes to stdout VG_(log_output_sink).fd = 1; VG_(log_output_sink).is_socket = False; if (VG_(needs).malloc_replacement) { VG_(sprintf)(default_alignment, "%d", VG_MIN_MALLOC_SZB); VG_(sprintf)(default_redzone_size, "%lu", VG_(tdict).tool_client_redzone_szB); } else { VG_(strcpy)(default_alignment, "not used by this tool"); VG_(strcpy)(default_redzone_size, "not used by this tool"); } /* 'usage1' a type as described after each arg. */ VG_(printf)(usage1, VG_(clo_vgdb_error) /* int */, gdb_path /* char* */, default_alignment /* char* */, default_redzone_size /* char* */, VG_(clo_vgdb_poll) /* int */, VG_(vgdb_prefix_default)() /* char* */ ); if (VG_(details).name) { VG_(printf)(" user options for %s:\n", VG_(details).name); if (VG_(needs).command_line_options) VG_TDICT_CALL(tool_print_usage); else VG_(printf)(" (none)\n"); } if (debug_help) { VG_(printf)("%s", usage2); if (VG_(details).name) { VG_(printf)(" debugging options for %s:\n", VG_(details).name); if (VG_(needs).command_line_options) VG_TDICT_CALL(tool_print_debug_usage); else VG_(printf)(" (none)\n"); } } VG_(printf)(usage3, VG_(details).name, VG_(details).copyright_author, VG_BUGS_TO); VG_(exit)(0); } /* Peer at previously set up VG_(args_for_valgrind) and do some minimal command line processing that must happen early on: - show the version string, if requested (-v) - extract any request for help (--help, -h, --help-debug) - get the toolname (--tool=) - set VG_(clo_max_stackframe) (--max-stackframe=) - set VG_(clo_main_stacksize) (--main-stacksize=) - set VG_(clo_sim_hints) (--sim-hints=) That's all it does. The main command line processing is done below by main_process_cmd_line_options. Note that main_process_cmd_line_options has to handle but ignore the ones we have handled here. */ static void early_process_cmd_line_options ( /*OUT*/Int* need_help, /*OUT*/HChar** tool ) { UInt i; HChar* str; vg_assert( VG_(args_for_valgrind) ); /* parse the options we have (only the options we care about now) */ for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) { str = * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i ); vg_assert(str); // Nb: the version string goes to stdout. if VG_XACT_CLO(str, "--version", VG_(log_output_sink).fd, 1) { VG_(log_output_sink).is_socket = False; VG_(printf)("valgrind-" VERSION "\n"); VG_(exit)(0); } else if VG_XACT_CLO(str, "--help", *need_help, *need_help+1) {} else if VG_XACT_CLO(str, "-h", *need_help, *need_help+1) {} else if VG_XACT_CLO(str, "--help-debug", *need_help, *need_help+2) {} // The tool has already been determined, but we need to know the name // here. else if VG_STR_CLO(str, "--tool", *tool) {} // Set up VG_(clo_max_stackframe) and VG_(clo_main_stacksize). // These are needed by VG_(ii_create_image), which happens // before main_process_cmd_line_options(). else if VG_INT_CLO(str, "--max-stackframe", VG_(clo_max_stackframe)) {} else if VG_INT_CLO(str, "--main-stacksize", VG_(clo_main_stacksize)) {} // Set up VG_(clo_sim_hints). This is needed a.o. for an inner // running in an outer, to have "no-inner-prefix" enabled // as early as possible. else if VG_STR_CLO (str, "--sim-hints", VG_(clo_sim_hints)) {} } } /* The main processing for command line options. See comments above on early_process_cmd_line_options. Comments on how the logging options are handled: User can specify: --log-fd= for a fd to write to (default setting, fd = 2) --log-file= for a file name to write to --log-socket= for a socket to write to As a result of examining these and doing relevant socket/file opening, a final fd is established. This is stored in VG_(log_output_sink) in m_libcprint. Also, if --log-file=STR was specified, then STR, after expansion of %p and %q templates within it, is stored in VG_(clo_log_fname_expanded), in m_options, just in case anybody wants to know what it is. When printing, VG_(log_output_sink) is consulted to find the fd to send output to. Exactly analogous actions are undertaken for the XML output channel, with the one difference that the default fd is -1, meaning the channel is disabled by default. */ static void main_process_cmd_line_options ( /*OUT*/Bool* logging_to_fd, /*OUT*/Char** xml_fname_unexpanded, const HChar* toolname ) { // VG_(clo_log_fd) is used by all the messaging. It starts as 2 (stderr) // and we cannot change it until we know what we are changing it to is // ok. So we have tmp_log_fd to hold the tmp fd prior to that point. SysRes sres; Int i, tmp_log_fd, tmp_xml_fd; Int toolname_len = VG_(strlen)(toolname); Char* tmp_str; // Used in a couple of places. enum { VgLogTo_Fd, VgLogTo_File, VgLogTo_Socket } log_to = VgLogTo_Fd, // Where is logging output to be sent? xml_to = VgLogTo_Fd; // Where is XML output to be sent? /* Temporarily holds the string STR specified with --{log,xml}-{name,socket}=STR. 'fs' stands for file-or-socket. */ Char* log_fsname_unexpanded = NULL; Char* xml_fsname_unexpanded = NULL; /* Log to stderr by default, but usage message goes to stdout. XML output is initially disabled. */ tmp_log_fd = 2; tmp_xml_fd = -1; /* Check for sane path in ./configure --prefix=... */ if (VG_LIBDIR[0] != '/') VG_(err_config_error)("Please use absolute paths in " "./configure --prefix=... or --libdir=...\n"); vg_assert( VG_(args_for_valgrind) ); /* BEGIN command-line processing loop */ for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) { HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i ); HChar* colon = arg; // Look for a colon in the option name. while (*colon && *colon != ':' && *colon != '=') colon++; // Does it have the form "--toolname:foo"? We have to do it at the start // in case someone has combined a prefix with a core-specific option, // eg. "--memcheck:verbose". if (*colon == ':') { if (VG_STREQN(2, arg, "--") && VG_STREQN(toolname_len, arg+2, toolname) && VG_STREQN(1, arg+2+toolname_len, ":")) { // Prefix matches, convert "--toolname:foo" to "--foo". // Two things to note: // - We cannot modify the option in-place. If we did, and then // a child was spawned with --trace-children=yes, the // now-non-prefixed option would be passed and could screw up // the child. // - We create copies, and never free them. Why? Non-prefixed // options hang around forever, so tools need not make copies // of strings within them. We need to have the same behaviour // for prefixed options. The pointer to the copy will be lost // once we leave this function (although a tool may keep a // pointer into it), but the space wasted is insignificant. // (In bug #142197, the copies were being freed, which caused // problems for tools that reasonably assumed that arguments // wouldn't disappear on them.) if (0) VG_(printf)("tool-specific arg: %s\n", arg); arg = VG_(strdup)("main.mpclo.1", arg + toolname_len + 1); arg[0] = '-'; arg[1] = '-'; } else { // prefix doesn't match, skip to next arg continue; } } /* Ignore these options - they've already been handled */ if VG_STREQN( 7, arg, "--tool=") {} else if VG_STREQN(20, arg, "--command-line-only=") {} else if VG_STREQ( arg, "--") {} else if VG_STREQ( arg, "-d") {} else if VG_STREQN(16, arg, "--max-stackframe") {} else if VG_STREQN(16, arg, "--main-stacksize") {} else if VG_STREQN(11, arg, "--sim-hints") {} else if VG_STREQN(14, arg, "--profile-heap") {} else if VG_STREQN(14, arg, "--core-redzone-size") {} else if VG_STREQN(14, arg, "--redzone-size") {} /* Obsolete options. Report an error and exit */ else if VG_STREQN(34, arg, "--vex-iropt-precise-memory-exns=no") { VG_(fmsg_bad_option) (arg, "--vex-iropt-precise-memory-exns is obsolete\n" "Use --vex-iropt-register-updates=unwindregs-at-mem-access instead\n"); } else if VG_STREQN(35, arg, "--vex-iropt-precise-memory-exns=yes") { VG_(fmsg_bad_option) (arg, "--vex-iropt-precise-memory-exns is obsolete\n" "Use --vex-iropt-register-updates=allregs-at-mem-access instead\n" " (or --vex-iropt-register-updates=allregs-at-each-insn)\n"); } // These options are new. else if (VG_STREQ(arg, "-v") || VG_STREQ(arg, "--verbose")) VG_(clo_verbosity)++; else if (VG_STREQ(arg, "-q") || VG_STREQ(arg, "--quiet")) VG_(clo_verbosity)--; else if VG_BOOL_CLO(arg, "--stats", VG_(clo_stats)) {} else if VG_BOOL_CLO(arg, "--xml", VG_(clo_xml)) VG_(debugLog_setXml)(VG_(clo_xml)); else if VG_XACT_CLO(arg, "--vgdb=no", VG_(clo_vgdb), Vg_VgdbNo) {} else if VG_XACT_CLO(arg, "--vgdb=yes", VG_(clo_vgdb), Vg_VgdbYes) {} else if VG_XACT_CLO(arg, "--vgdb=full", VG_(clo_vgdb), Vg_VgdbFull) { /* automatically updates register values at each insn with --vgdb=full */ VG_(clo_vex_control).iropt_register_updates = VexRegUpdAllregsAtEachInsn; } else if VG_INT_CLO (arg, "--vgdb-poll", VG_(clo_vgdb_poll)) {} else if VG_INT_CLO (arg, "--vgdb-error", VG_(clo_vgdb_error)) {} else if VG_STR_CLO (arg, "--vgdb-prefix", VG_(clo_vgdb_prefix)) {} else if VG_BOOL_CLO(arg, "--vgdb-shadow-registers", VG_(clo_vgdb_shadow_registers)) {} else if VG_BOOL_CLO(arg, "--db-attach", VG_(clo_db_attach)) {} else if VG_BOOL_CLO(arg, "--demangle", VG_(clo_demangle)) {} else if VG_STR_CLO (arg, "--soname-synonyms",VG_(clo_soname_synonyms)) {} else if VG_BOOL_CLO(arg, "--error-limit", VG_(clo_error_limit)) {} else if VG_INT_CLO (arg, "--error-exitcode", VG_(clo_error_exitcode)) {} else if VG_BOOL_CLO(arg, "--show-emwarns", VG_(clo_show_emwarns)) {} else if VG_BOOL_CLO(arg, "--run-libc-freeres", VG_(clo_run_libc_freeres)) {} else if VG_BOOL_CLO(arg, "--show-below-main", VG_(clo_show_below_main)) {} else if VG_BOOL_CLO(arg, "--time-stamp", VG_(clo_time_stamp)) {} else if VG_BOOL_CLO(arg, "--track-fds", VG_(clo_track_fds)) {} else if VG_BOOL_CLO(arg, "--trace-children", VG_(clo_trace_children)) {} else if VG_BOOL_CLO(arg, "--child-silent-after-fork", VG_(clo_child_silent_after_fork)) {} else if VG_STR_CLO(arg, "--fair-sched", tmp_str) { if (VG_(strcmp)(tmp_str, "yes") == 0) VG_(clo_fair_sched) = enable_fair_sched; else if (VG_(strcmp)(tmp_str, "try") == 0) VG_(clo_fair_sched) = try_fair_sched; else if (VG_(strcmp)(tmp_str, "no") == 0) VG_(clo_fair_sched) = disable_fair_sched; else VG_(fmsg_bad_option)(arg, ""); } else if VG_BOOL_CLO(arg, "--trace-sched", VG_(clo_trace_sched)) {} else if VG_BOOL_CLO(arg, "--trace-signals", VG_(clo_trace_signals)) {} else if VG_BOOL_CLO(arg, "--trace-symtab", VG_(clo_trace_symtab)) {} else if VG_STR_CLO (arg, "--trace-symtab-patt", VG_(clo_trace_symtab_patt)) {} else if VG_BOOL_CLO(arg, "--trace-cfi", VG_(clo_trace_cfi)) {} else if VG_XACT_CLO(arg, "--debug-dump=syms", VG_(clo_debug_dump_syms), True) {} else if VG_XACT_CLO(arg, "--debug-dump=line", VG_(clo_debug_dump_line), True) {} else if VG_XACT_CLO(arg, "--debug-dump=frames", VG_(clo_debug_dump_frames), True) {} else if VG_BOOL_CLO(arg, "--trace-redir", VG_(clo_trace_redir)) {} else if VG_BOOL_CLO(arg, "--trace-syscalls", VG_(clo_trace_syscalls)) {} else if VG_BOOL_CLO(arg, "--wait-for-gdb", VG_(clo_wait_for_gdb)) {} else if VG_STR_CLO (arg, "--db-command", VG_(clo_db_command)) {} else if VG_BOOL_CLO(arg, "--sym-offsets", VG_(clo_sym_offsets)) {} else if VG_BOOL_CLO(arg, "--read-var-info", VG_(clo_read_var_info)) {} else if VG_INT_CLO (arg, "--dump-error", VG_(clo_dump_error)) {} else if VG_INT_CLO (arg, "--input-fd", VG_(clo_input_fd)) {} else if VG_INT_CLO (arg, "--sanity-level", VG_(clo_sanity_level)) {} else if VG_BINT_CLO(arg, "--num-callers", VG_(clo_backtrace_size), 1, VG_DEEPEST_BACKTRACE) {} else if VG_XACT_CLO(arg, "--smc-check=none", VG_(clo_smc_check), Vg_SmcNone); else if VG_XACT_CLO(arg, "--smc-check=stack", VG_(clo_smc_check), Vg_SmcStack); else if VG_XACT_CLO(arg, "--smc-check=all", VG_(clo_smc_check), Vg_SmcAll); else if VG_XACT_CLO(arg, "--smc-check=all-non-file", VG_(clo_smc_check), Vg_SmcAllNonFile); else if VG_STR_CLO (arg, "--kernel-variant", VG_(clo_kernel_variant)) {} else if VG_BOOL_CLO(arg, "--dsymutil", VG_(clo_dsymutil)) {} else if VG_STR_CLO (arg, "--trace-children-skip", VG_(clo_trace_children_skip)) {} else if VG_STR_CLO (arg, "--trace-children-skip-by-arg", VG_(clo_trace_children_skip_by_arg)) {} else if VG_BINT_CLO(arg, "--vex-iropt-verbosity", VG_(clo_vex_control).iropt_verbosity, 0, 10) {} else if VG_BINT_CLO(arg, "--vex-iropt-level", VG_(clo_vex_control).iropt_level, 0, 2) {} else if VG_XACT_CLO(arg, "--vex-iropt-register-updates=unwindregs-at-mem-access", VG_(clo_vex_control).iropt_register_updates, VexRegUpdUnwindregsAtMemAccess); else if VG_XACT_CLO(arg, "--vex-iropt-register-updates=allregs-at-mem-access", VG_(clo_vex_control).iropt_register_updates, VexRegUpdAllregsAtMemAccess); else if VG_XACT_CLO(arg, "--vex-iropt-register-updates=allregs-at-each-insn", VG_(clo_vex_control).iropt_register_updates, VexRegUpdAllregsAtEachInsn); else if VG_BINT_CLO(arg, "--vex-iropt-unroll-thresh", VG_(clo_vex_control).iropt_unroll_thresh, 0, 400) {} else if VG_BINT_CLO(arg, "--vex-guest-max-insns", VG_(clo_vex_control).guest_max_insns, 1, 100) {} else if VG_BINT_CLO(arg, "--vex-guest-chase-thresh", VG_(clo_vex_control).guest_chase_thresh, 0, 99) {} else if VG_BOOL_CLO(arg, "--vex-guest-chase-cond", VG_(clo_vex_control).guest_chase_cond) {} else if VG_INT_CLO(arg, "--log-fd", tmp_log_fd) { log_to = VgLogTo_Fd; log_fsname_unexpanded = NULL; } else if VG_INT_CLO(arg, "--xml-fd", tmp_xml_fd) { xml_to = VgLogTo_Fd; xml_fsname_unexpanded = NULL; } else if VG_STR_CLO(arg, "--log-file", log_fsname_unexpanded) { log_to = VgLogTo_File; } else if VG_STR_CLO(arg, "--xml-file", xml_fsname_unexpanded) { xml_to = VgLogTo_File; } else if VG_STR_CLO(arg, "--log-socket", log_fsname_unexpanded) { log_to = VgLogTo_Socket; } else if VG_STR_CLO(arg, "--xml-socket", xml_fsname_unexpanded) { xml_to = VgLogTo_Socket; } else if VG_STR_CLO(arg, "--xml-user-comment", VG_(clo_xml_user_comment)) {} else if VG_STR_CLO(arg, "--suppressions", tmp_str) { if (VG_(clo_n_suppressions) >= VG_CLO_MAX_SFILES) { VG_(fmsg_bad_option)(arg, "Too many suppression files specified.\n" "Increase VG_CLO_MAX_SFILES and recompile.\n"); } VG_(clo_suppressions)[VG_(clo_n_suppressions)] = tmp_str; VG_(clo_n_suppressions)++; } else if VG_STR_CLO (arg, "--fullpath-after", tmp_str) { if (VG_(clo_n_fullpath_after) >= VG_CLO_MAX_FULLPATH_AFTER) { VG_(fmsg_bad_option)(arg, "Too many --fullpath-after= specifications.\n" "Increase VG_CLO_MAX_FULLPATH_AFTER and recompile.\n"); } VG_(clo_fullpath_after)[VG_(clo_n_fullpath_after)] = tmp_str; VG_(clo_n_fullpath_after)++; } else if VG_STR_CLO(arg, "--require-text-symbol", tmp_str) { if (VG_(clo_n_req_tsyms) >= VG_CLO_MAX_REQ_TSYMS) { VG_(fmsg_bad_option)(arg, "Too many --require-text-symbol= specifications.\n" "Increase VG_CLO_MAX_REQ_TSYMS and recompile.\n"); } /* String needs to be of the form C?*C?*, where C is any character, but is the same both times. Having it in this form facilitates finding the boundary between the sopatt and the fnpatt just by looking for the second occurrence of C, without hardwiring any assumption about what C is. */ Char patt[7]; Bool ok = True; ok = tmp_str && VG_(strlen)(tmp_str) > 0; if (ok) { patt[0] = patt[3] = tmp_str[0]; patt[1] = patt[4] = '?'; patt[2] = patt[5] = '*'; patt[6] = 0; ok = VG_(string_match)(patt, tmp_str); } if (!ok) { VG_(fmsg_bad_option)(arg, "Invalid --require-text-symbol= specification.\n"); } VG_(clo_req_tsyms)[VG_(clo_n_req_tsyms)] = tmp_str; VG_(clo_n_req_tsyms)++; } /* "stuvwxyz" --> stuvwxyz (binary) */ else if VG_STR_CLO(arg, "--trace-flags", tmp_str) { Int j; if (8 != VG_(strlen)(tmp_str)) { VG_(fmsg_bad_option)(arg, "--trace-flags argument must have 8 digits\n"); } for (j = 0; j < 8; j++) { if ('0' == tmp_str[j]) { /* do nothing */ } else if ('1' == tmp_str[j]) VG_(clo_trace_flags) |= (1 << (7-j)); else { VG_(fmsg_bad_option)(arg, "--trace-flags argument can only contain 0s and 1s\n"); } } } /* "stuvwxyz" --> stuvwxyz (binary) */ else if VG_STR_CLO(arg, "--profile-flags", tmp_str) { Int j; if (8 != VG_(strlen)(tmp_str)) { VG_(fmsg_bad_option)(arg, "--profile-flags argument must have 8 digits\n"); } for (j = 0; j < 8; j++) { if ('0' == tmp_str[j]) { /* do nothing */ } else if ('1' == tmp_str[j]) VG_(clo_profile_flags) |= (1 << (7-j)); else { VG_(fmsg_bad_option)(arg, "--profile-flags argument can only contain 0s and 1s\n"); } } } else if VG_INT_CLO (arg, "--trace-notbelow", VG_(clo_trace_notbelow)) {} else if VG_INT_CLO (arg, "--trace-notabove", VG_(clo_trace_notabove)) {} else if VG_XACT_CLO(arg, "--gen-suppressions=no", VG_(clo_gen_suppressions), 0) {} else if VG_XACT_CLO(arg, "--gen-suppressions=yes", VG_(clo_gen_suppressions), 1) {} else if VG_XACT_CLO(arg, "--gen-suppressions=all", VG_(clo_gen_suppressions), 2) {} else if ( ! VG_(needs).command_line_options || ! VG_TDICT_CALL(tool_process_cmd_line_option, arg) ) { VG_(fmsg_bad_option)(arg, ""); } } /* END command-line processing loop */ /* Determine the path prefix for vgdb */ if (VG_(clo_vgdb_prefix) == NULL) VG_(clo_vgdb_prefix) = VG_(vgdb_prefix_default)(); /* Make VEX control parameters sane */ if (VG_(clo_vex_control).guest_chase_thresh >= VG_(clo_vex_control).guest_max_insns) VG_(clo_vex_control).guest_chase_thresh = VG_(clo_vex_control).guest_max_insns - 1; if (VG_(clo_vex_control).guest_chase_thresh < 0) VG_(clo_vex_control).guest_chase_thresh = 0; /* Check various option values */ if (VG_(clo_verbosity) < 0) VG_(clo_verbosity) = 0; if (VG_(clo_trace_notbelow) == -1) { if (VG_(clo_trace_notabove) == -1) { /* [] */ VG_(clo_trace_notbelow) = 2147483647; VG_(clo_trace_notabove) = 0; } else { /* [0 .. notabove] */ VG_(clo_trace_notbelow) = 0; } } else { if (VG_(clo_trace_notabove) == -1) { /* [notbelow .. ] */ VG_(clo_trace_notabove) = 2147483647; } else { /* [notbelow .. notabove] */ } } VG_(dyn_vgdb_error) = VG_(clo_vgdb_error); if (VG_(clo_gen_suppressions) > 0 && !VG_(needs).core_errors && !VG_(needs).tool_errors) { VG_(fmsg_bad_option)("--gen-suppressions=yes", "Can't use --gen-suppressions= with %s\n" "because it doesn't generate errors.\n", VG_(details).name); } /* If XML output is requested, check that the tool actually supports it. */ if (VG_(clo_xml) && !VG_(needs).xml_output) { VG_(clo_xml) = False; VG_(fmsg_bad_option)("--xml=yes", "%s does not support XML output.\n", VG_(details).name); /*NOTREACHED*/ } vg_assert( VG_(clo_gen_suppressions) >= 0 ); vg_assert( VG_(clo_gen_suppressions) <= 2 ); /* If we've been asked to emit XML, mash around various other options so as to constrain the output somewhat, and to remove any need for user input during the run. */ if (VG_(clo_xml)) { /* We can't allow --gen-suppressions=yes, since that requires us to print the error and then ask the user if she wants a suppression for it, but in XML mode we won't print it until we know whether we also need to print a suppression. Hence a circular dependency. So disallow this. (--gen-suppressions=all is still OK since we don't need any user interaction in this case.) */ if (VG_(clo_gen_suppressions) == 1) { VG_(fmsg_bad_option)( "--xml=yes together with --gen-suppressions=yes", "When --xml=yes is specified, --gen-suppressions=no\n" "or --gen-suppressions=all is allowed, but not " "--gen-suppressions=yes.\n"); } /* We can't allow DB attaching (or we maybe could, but results could be chaotic ..) since it requires user input. Hence disallow. */ if (VG_(clo_db_attach)) { VG_(fmsg_bad_option)( "--xml=yes together with --db-attach=yes", "--db-attach=yes is not allowed with --xml=yes\n" "because it would require user input.\n"); } /* Disallow dump_error in XML mode; sounds like a recipe for chaos. No big deal; dump_error is a flag for debugging V itself. */ if (VG_(clo_dump_error) > 0) { VG_(fmsg_bad_option)("--xml=yes together with --dump-error", ""); } /* Disable error limits (this might be a bad idea!) */ VG_(clo_error_limit) = False; /* Disable emulation warnings */ /* Also, we want to set options for the leak checker, but that will have to be done in Memcheck's flag-handling code, not here. */ } /* All non-logging-related options have been checked. If the logging option specified is ok, we can switch to it, as we know we won't have to generate any other command-line-related error messages. (So far we should be still attached to stderr, so we can show on the terminal any problems to do with processing command line opts.) So set up logging now. After this is done, VG_(log_output_sink) and (if relevant) VG_(xml_output_sink) should be connected to whatever sink has been selected, and we indiscriminately chuck stuff into it without worrying what the nature of it is. Oh the wonder of Unix streams. */ vg_assert(VG_(log_output_sink).fd == 2 /* stderr */); vg_assert(VG_(log_output_sink).is_socket == False); vg_assert(VG_(clo_log_fname_expanded) == NULL); vg_assert(VG_(xml_output_sink).fd == -1 /* disabled */); vg_assert(VG_(xml_output_sink).is_socket == False); vg_assert(VG_(clo_xml_fname_expanded) == NULL); /* --- set up the normal text output channel --- */ switch (log_to) { case VgLogTo_Fd: vg_assert(log_fsname_unexpanded == NULL); break; case VgLogTo_File: { Char* logfilename; vg_assert(log_fsname_unexpanded != NULL); vg_assert(VG_(strlen)(log_fsname_unexpanded) <= 900); /* paranoia */ // Nb: we overwrite an existing file of this name without asking // any questions. logfilename = VG_(expand_file_name)("--log-file", log_fsname_unexpanded); sres = VG_(open)(logfilename, VKI_O_CREAT|VKI_O_WRONLY|VKI_O_TRUNC, VKI_S_IRUSR|VKI_S_IWUSR); if (!sr_isError(sres)) { tmp_log_fd = sr_Res(sres); VG_(clo_log_fname_expanded) = logfilename; } else { VG_(fmsg)("can't create log file '%s': %s\n", logfilename, VG_(strerror)(sr_Err(sres))); VG_(exit)(1); /*NOTREACHED*/ } break; } case VgLogTo_Socket: { vg_assert(log_fsname_unexpanded != NULL); vg_assert(VG_(strlen)(log_fsname_unexpanded) <= 900); /* paranoia */ tmp_log_fd = VG_(connect_via_socket)( log_fsname_unexpanded ); if (tmp_log_fd == -1) { VG_(fmsg)("Invalid --log-socket spec of '%s'\n", log_fsname_unexpanded); VG_(exit)(1); /*NOTREACHED*/ } if (tmp_log_fd == -2) { VG_(umsg)("failed to connect to logging server '%s'.\n" "Log messages will sent to stderr instead.\n", log_fsname_unexpanded ); /* We don't change anything here. */ vg_assert(VG_(log_output_sink).fd == 2); tmp_log_fd = 2; } else { vg_assert(tmp_log_fd > 0); VG_(log_output_sink).is_socket = True; } break; } } /* --- set up the XML output channel --- */ switch (xml_to) { case VgLogTo_Fd: vg_assert(xml_fsname_unexpanded == NULL); break; case VgLogTo_File: { Char* xmlfilename; vg_assert(xml_fsname_unexpanded != NULL); vg_assert(VG_(strlen)(xml_fsname_unexpanded) <= 900); /* paranoia */ // Nb: we overwrite an existing file of this name without asking // any questions. xmlfilename = VG_(expand_file_name)("--xml-file", xml_fsname_unexpanded); sres = VG_(open)(xmlfilename, VKI_O_CREAT|VKI_O_WRONLY|VKI_O_TRUNC, VKI_S_IRUSR|VKI_S_IWUSR); if (!sr_isError(sres)) { tmp_xml_fd = sr_Res(sres); VG_(clo_xml_fname_expanded) = xmlfilename; /* strdup here is probably paranoid overkill, but ... */ *xml_fname_unexpanded = VG_(strdup)( "main.mpclo.2", xml_fsname_unexpanded ); } else { VG_(fmsg)("can't create XML file '%s': %s\n", xmlfilename, VG_(strerror)(sr_Err(sres))); VG_(exit)(1); /*NOTREACHED*/ } break; } case VgLogTo_Socket: { vg_assert(xml_fsname_unexpanded != NULL); vg_assert(VG_(strlen)(xml_fsname_unexpanded) <= 900); /* paranoia */ tmp_xml_fd = VG_(connect_via_socket)( xml_fsname_unexpanded ); if (tmp_xml_fd == -1) { VG_(fmsg)("Invalid --xml-socket spec of '%s'\n", xml_fsname_unexpanded ); VG_(exit)(1); /*NOTREACHED*/ } if (tmp_xml_fd == -2) { VG_(umsg)("failed to connect to XML logging server '%s'.\n" "XML output will sent to stderr instead.\n", xml_fsname_unexpanded); /* We don't change anything here. */ vg_assert(VG_(xml_output_sink).fd == 2); tmp_xml_fd = 2; } else { vg_assert(tmp_xml_fd > 0); VG_(xml_output_sink).is_socket = True; } break; } } /* If we've got this far, and XML mode was requested, but no XML output channel appears to have been specified, just stop. We could continue, and XML output will simply vanish into nowhere, but that is likely to confuse the hell out of users, which is distinctly Ungood. */ if (VG_(clo_xml) && tmp_xml_fd == -1) { VG_(fmsg_bad_option)( "--xml=yes, but no XML destination specified", "--xml=yes has been specified, but there is no XML output\n" "destination. You must specify an XML output destination\n" "using --xml-fd, --xml-file or --xml-socket.\n" ); } // Finalise the output fds: the log fd .. if (tmp_log_fd >= 0) { // Move log_fd into the safe range, so it doesn't conflict with // any app fds. tmp_log_fd = VG_(fcntl)(tmp_log_fd, VKI_F_DUPFD, VG_(fd_hard_limit)); if (tmp_log_fd < 0) { VG_(message)(Vg_UserMsg, "valgrind: failed to move logfile fd " "into safe range, using stderr\n"); VG_(log_output_sink).fd = 2; // stderr VG_(log_output_sink).is_socket = False; } else { VG_(log_output_sink).fd = tmp_log_fd; VG_(fcntl)(VG_(log_output_sink).fd, VKI_F_SETFD, VKI_FD_CLOEXEC); } } else { // If they said --log-fd=-1, don't print anything. Plausible for use in // regression testing suites that use client requests to count errors. VG_(log_output_sink).fd = -1; VG_(log_output_sink).is_socket = False; } // Finalise the output fds: and the XML fd .. if (tmp_xml_fd >= 0) { // Move xml_fd into the safe range, so it doesn't conflict with // any app fds. tmp_xml_fd = VG_(fcntl)(tmp_xml_fd, VKI_F_DUPFD, VG_(fd_hard_limit)); if (tmp_xml_fd < 0) { VG_(message)(Vg_UserMsg, "valgrind: failed to move XML file fd " "into safe range, using stderr\n"); VG_(xml_output_sink).fd = 2; // stderr VG_(xml_output_sink).is_socket = False; } else { VG_(xml_output_sink).fd = tmp_xml_fd; VG_(fcntl)(VG_(xml_output_sink).fd, VKI_F_SETFD, VKI_FD_CLOEXEC); } } else { // If they said --xml-fd=-1, don't print anything. Plausible for use in // regression testing suites that use client requests to count errors. VG_(xml_output_sink).fd = -1; VG_(xml_output_sink).is_socket = False; } // Suppressions related stuff if (VG_(clo_n_suppressions) < VG_CLO_MAX_SFILES-1 && (VG_(needs).core_errors || VG_(needs).tool_errors)) { /* If we haven't reached the max number of suppressions, load the default one. */ static const Char default_supp[] = "default.supp"; Int len = VG_(strlen)(VG_(libdir)) + 1 + sizeof(default_supp); Char *buf = VG_(arena_malloc)(VG_AR_CORE, "main.mpclo.3", len); VG_(sprintf)(buf, "%s/%s", VG_(libdir), default_supp); VG_(clo_suppressions)[VG_(clo_n_suppressions)] = buf; VG_(clo_n_suppressions)++; } *logging_to_fd = log_to == VgLogTo_Fd || log_to == VgLogTo_Socket; } // Write the name and value of log file qualifiers to the xml file. static void print_file_vars(Char* format) { Int i = 0; while (format[i]) { if (format[i] == '%') { // We saw a '%'. What's next... i++; if ('q' == format[i]) { i++; if ('{' == format[i]) { // Get the env var name, print its contents. Char* qualname; Char* qual; i++; qualname = &format[i]; while (True) { if ('}' == format[i]) { // Temporarily replace the '}' with NUL to extract var // name. format[i] = 0; qual = VG_(getenv)(qualname); break; } i++; } VG_(printf_xml)( "<logfilequalifier> <var>%pS</var> " "<value>%pS</value> </logfilequalifier>\n", qualname,qual ); format[i] = '}'; i++; } } } else { i++; } } } /*====================================================================*/ /*=== Printing the preamble ===*/ /*====================================================================*/ // Print the argument, escaping any chars that require it. static void umsg_arg(const Char* arg) { SizeT len = VG_(strlen)(arg); Char* special = " \\<>"; Int i; for (i = 0; i < len; i++) { if (VG_(strchr)(special, arg[i])) { VG_(umsg)("\\"); // escape with a backslash if necessary } VG_(umsg)("%c", arg[i]); } } // Send output to the XML-stream and escape any XML meta-characters. static void xml_arg(const Char* arg) { VG_(printf_xml)("%pS", arg); } /* Ok, the logging sink is running now. Print a suitable preamble. If logging to file or a socket, write details of parent PID and command line args, to help people trying to interpret the results of a run which encompasses multiple processes. */ static void print_preamble ( Bool logging_to_fd, Char* xml_fname_unexpanded, const HChar* toolname ) { Int i; HChar* xpre = VG_(clo_xml) ? " <line>" : ""; HChar* xpost = VG_(clo_xml) ? "</line>" : ""; UInt (*umsg_or_xml)( const HChar*, ... ) = VG_(clo_xml) ? VG_(printf_xml) : VG_(umsg); void (*umsg_or_xml_arg)( const Char* ) = VG_(clo_xml) ? xml_arg : umsg_arg; vg_assert( VG_(args_for_client) ); vg_assert( VG_(args_for_valgrind) ); vg_assert( toolname ); if (VG_(clo_xml)) { VG_(printf_xml)("<?xml version=\"1.0\"?>\n"); VG_(printf_xml)("\n"); VG_(printf_xml)("<valgrindoutput>\n"); VG_(printf_xml)("\n"); VG_(printf_xml)("<protocolversion>4</protocolversion>\n"); VG_(printf_xml)("<protocoltool>%s</protocoltool>\n", toolname); VG_(printf_xml)("\n"); } if (VG_(clo_xml) || VG_(clo_verbosity > 0)) { if (VG_(clo_xml)) VG_(printf_xml)("<preamble>\n"); /* Tool details */ umsg_or_xml( VG_(clo_xml) ? "%s%pS%pS%pS, %pS%s\n" : "%s%s%s%s, %s%s\n", xpre, VG_(details).name, NULL == VG_(details).version ? "" : "-", NULL == VG_(details).version ? (Char*)"" : VG_(details).version, VG_(details).description, xpost ); if (VG_(strlen)(toolname) >= 4 && VG_STREQN(4, toolname, "exp-")) { umsg_or_xml( "%sNOTE: This is an Experimental-Class Valgrind Tool%s\n", xpre, xpost ); } umsg_or_xml( VG_(clo_xml) ? "%s%pS%s\n" : "%s%s%s\n", xpre, VG_(details).copyright_author, xpost ); /* Core details */ umsg_or_xml( "%sUsing Valgrind-%s and LibVEX; rerun with -h for copyright info%s\n", xpre, VERSION, xpost ); // Print the command line. At one point we wrapped at 80 chars and // printed a '\' as a line joiner, but that makes it hard to cut and // paste the command line (because of the "==pid==" prefixes), so we now // favour utility and simplicity over aesthetics. umsg_or_xml("%sCommand: ", xpre); if (VG_(args_the_exename)) umsg_or_xml_arg(VG_(args_the_exename)); for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) { HChar* s = *(HChar**)VG_(indexXA)( VG_(args_for_client), i ); umsg_or_xml(" "); umsg_or_xml_arg(s); } umsg_or_xml("%s\n", xpost); if (VG_(clo_xml)) VG_(printf_xml)("</preamble>\n"); } // Print the parent PID, and other stuff, if necessary. if (!VG_(clo_xml) && VG_(clo_verbosity) > 0 && !logging_to_fd) { VG_(umsg)("Parent PID: %d\n", VG_(getppid)()); } else if (VG_(clo_xml)) { VG_(printf_xml)("\n"); VG_(printf_xml)("<pid>%d</pid>\n", VG_(getpid)()); VG_(printf_xml)("<ppid>%d</ppid>\n", VG_(getppid)()); VG_(printf_xml)("<tool>%pS</tool>\n", toolname); if (xml_fname_unexpanded) print_file_vars(xml_fname_unexpanded); if (VG_(clo_xml_user_comment)) { /* Note: the user comment itself is XML and is therefore to be passed through verbatim (%s) rather than escaped (%pS). */ VG_(printf_xml)("<usercomment>%s</usercomment>\n", VG_(clo_xml_user_comment)); } VG_(printf_xml)("\n"); VG_(printf_xml)("<args>\n"); VG_(printf_xml)(" <vargv>\n"); if (VG_(name_of_launcher)) VG_(printf_xml)(" <exe>%pS</exe>\n", VG_(name_of_launcher)); else VG_(printf_xml)(" <exe>%pS</exe>\n", "(launcher name unknown)"); for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) { VG_(printf_xml)( " <arg>%pS</arg>\n", * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i ) ); } VG_(printf_xml)(" </vargv>\n"); VG_(printf_xml)(" <argv>\n"); if (VG_(args_the_exename)) VG_(printf_xml)(" <exe>%pS</exe>\n", VG_(args_the_exename)); for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) { VG_(printf_xml)( " <arg>%pS</arg>\n", * (HChar**) VG_(indexXA)( VG_(args_for_client), i ) ); } VG_(printf_xml)(" </argv>\n"); VG_(printf_xml)("</args>\n"); } // Last thing in the preamble is a blank line. if (VG_(clo_xml)) VG_(printf_xml)("\n"); else if (VG_(clo_verbosity) > 0) VG_(umsg)("\n"); # if defined(VGO_darwin) && DARWIN_VERS == DARWIN_10_8 /* Uh, this doesn't play nice with XML output. */ umsg_or_xml( "WARNING: Support on MacOS 10.8 is experimental and mostly broken.\n"); umsg_or_xml( "WARNING: Expect incorrect results, assertions and crashes.\n"); umsg_or_xml( "WARNING: In particular, Memcheck on 32-bit programs will fail to\n"); umsg_or_xml( "WARNING: detect any errors associated with heap-allocated data.\n"); umsg_or_xml( "\n" ); # endif if (VG_(clo_verbosity) > 1) { SysRes fd; VexArch vex_arch; VexArchInfo vex_archinfo; if (!logging_to_fd) VG_(message)(Vg_DebugMsg, "\n"); VG_(message)(Vg_DebugMsg, "Valgrind options:\n"); for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) { VG_(message)(Vg_DebugMsg, " %s\n", * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i )); } VG_(message)(Vg_DebugMsg, "Contents of /proc/version:\n"); fd = VG_(open) ( "/proc/version", VKI_O_RDONLY, 0 ); if (sr_isError(fd)) { VG_(message)(Vg_DebugMsg, " can't open /proc/version\n"); } else { # define BUF_LEN 256 Char version_buf[BUF_LEN]; Int n = VG_(read) ( sr_Res(fd), version_buf, BUF_LEN ); vg_assert(n <= BUF_LEN); if (n > 0) { version_buf[n-1] = '\0'; VG_(message)(Vg_DebugMsg, " %s\n", version_buf); } else { VG_(message)(Vg_DebugMsg, " (empty?)\n"); } VG_(close)(sr_Res(fd)); # undef BUF_LEN } VG_(machine_get_VexArchInfo)( &vex_arch, &vex_archinfo ); VG_(message)( Vg_DebugMsg, "Arch and hwcaps: %s, %s\n", LibVEX_ppVexArch ( vex_arch ), LibVEX_ppVexHwCaps ( vex_arch, vex_archinfo.hwcaps ) ); VG_(message)( Vg_DebugMsg, "Page sizes: currently %d, max supported %d\n", (Int)VKI_PAGE_SIZE, (Int)VKI_MAX_PAGE_SIZE ); VG_(message)(Vg_DebugMsg, "Valgrind library directory: %s\n", VG_(libdir)); } } /*====================================================================*/ /*=== File descriptor setup ===*/ /*====================================================================*/ /* Number of file descriptors that Valgrind tries to reserve for it's own use - just a small constant. */ #define N_RESERVED_FDS (10) static void setup_file_descriptors(void) { struct vki_rlimit rl; Bool show = False; /* Get the current file descriptor limits. */ if (VG_(getrlimit)(VKI_RLIMIT_NOFILE, &rl) < 0) { rl.rlim_cur = 1024; rl.rlim_max = 1024; } # if defined(VGO_darwin) /* Darwin lies. It reports file max as RLIM_INFINITY but silently disallows anything bigger than 10240. */ if (rl.rlim_cur >= 10240 && rl.rlim_max == 0x7fffffffffffffffULL) { rl.rlim_max = 10240; } # endif if (show) VG_(printf)("fd limits: host, before: cur %lu max %lu\n", (UWord)rl.rlim_cur, (UWord)rl.rlim_max); /* Work out where to move the soft limit to. */ if (rl.rlim_cur + N_RESERVED_FDS <= rl.rlim_max) { rl.rlim_cur = rl.rlim_cur + N_RESERVED_FDS; } else { rl.rlim_cur = rl.rlim_max; } /* Reserve some file descriptors for our use. */ VG_(fd_soft_limit) = rl.rlim_cur - N_RESERVED_FDS; VG_(fd_hard_limit) = rl.rlim_cur - N_RESERVED_FDS; /* Update the soft limit. */ VG_(setrlimit)(VKI_RLIMIT_NOFILE, &rl); if (show) { VG_(printf)("fd limits: host, after: cur %lu max %lu\n", (UWord)rl.rlim_cur, (UWord)rl.rlim_max); VG_(printf)("fd limits: guest : cur %u max %u\n", VG_(fd_soft_limit), VG_(fd_hard_limit)); } if (VG_(cl_exec_fd) != -1) VG_(cl_exec_fd) = VG_(safe_fd)( VG_(cl_exec_fd) ); } /*====================================================================*/ /*=== BB profiling ===*/ /*====================================================================*/ static void show_BB_profile ( BBProfEntry tops[], UInt n_tops, ULong score_total ) { ULong score_cumul, score_here; Char buf_cumul[10], buf_here[10]; Char name[64]; Int r; VG_(printf)("\n"); VG_(printf)("-----------------------------------------------------------\n"); VG_(printf)("--- BEGIN BB Profile (summary of scores) ---\n"); VG_(printf)("-----------------------------------------------------------\n"); VG_(printf)("\n"); VG_(printf)("Total score = %lld\n\n", score_total); score_cumul = 0; for (r = 0; r < n_tops; r++) { if (tops[r].addr == 0) continue; name[0] = 0; VG_(get_fnname_w_offset)(tops[r].addr, name, 64); name[63] = 0; score_here = tops[r].score; score_cumul += score_here; VG_(percentify)(score_cumul, score_total, 2, 6, buf_cumul); VG_(percentify)(score_here, score_total, 2, 6, buf_here); VG_(printf)("%3d: (%9lld %s) %9lld %s 0x%llx %s\n", r, score_cumul, buf_cumul, score_here, buf_here, tops[r].addr, name ); } VG_(printf)("\n"); VG_(printf)("-----------------------------------------------------------\n"); VG_(printf)("--- BB Profile (BB details) ---\n"); VG_(printf)("-----------------------------------------------------------\n"); VG_(printf)("\n"); score_cumul = 0; for (r = 0; r < n_tops; r++) { if (tops[r].addr == 0) continue; name[0] = 0; VG_(get_fnname_w_offset)(tops[r].addr, name, 64); name[63] = 0; score_here = tops[r].score; score_cumul += score_here; VG_(percentify)(score_cumul, score_total, 2, 6, buf_cumul); VG_(percentify)(score_here, score_total, 2, 6, buf_here); VG_(printf)("\n"); VG_(printf)("=-=-=-=-=-=-=-=-=-=-=-=-=-= begin BB rank %d " "=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n", r); VG_(printf)("%3d: (%9lld %s) %9lld %s 0x%llx %s\n", r, score_cumul, buf_cumul, score_here, buf_here, tops[r].addr, name ); VG_(printf)("\n"); VG_(discard_translations)(tops[r].addr, 1, "bb profile"); VG_(translate)(0, tops[r].addr, True, VG_(clo_profile_flags), 0, True); VG_(printf)("=-=-=-=-=-=-=-=-=-=-=-=-=-= end BB rank %d " "=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n", r); } VG_(printf)("\n"); VG_(printf)("-----------------------------------------------------------\n"); VG_(printf)("--- END BB Profile ---\n"); VG_(printf)("-----------------------------------------------------------\n"); VG_(printf)("\n"); } /*====================================================================*/ /*=== main() ===*/ /*====================================================================*/ /* When main() is entered, we should be on the following stack, not the one the kernel gave us. We will run on this stack until simulation of the root thread is started, at which point a transfer is made to a dynamically allocated stack. This is for the sake of uniform overflow detection for all Valgrind threads. This is marked global even though it isn't, because assembly code below needs to reference the name. */ /*static*/ VgStack VG_(interim_stack); /* These are the structures used to hold info for creating the initial client image. 'iicii' mostly holds important register state present at system startup (_start_valgrind). valgrind_main() then fills in the rest of it and passes it to VG_(ii_create_image)(). That produces 'iifii', which is later handed to VG_(ii_finalise_image). */ /* In all OS-instantiations, the_iicii has a field .sp_at_startup. This should get some address inside the stack on which we gained control (eg, it could be the SP at startup). It doesn't matter exactly where in the stack it is. This value is passed to the address space manager at startup. On Linux, aspacem then uses it to identify the initial stack segment and hence the upper end of the usable address space. */ static IICreateImageInfo the_iicii; static IIFinaliseImageInfo the_iifii; /* A simple pair structure, used for conveying debuginfo handles to calls to VG_TRACK(new_mem_startup, ...). */ typedef struct { Addr a; ULong ull; } Addr_n_ULong; /* --- Forwards decls to do with shutdown --- */ static void final_tidyup(ThreadId tid); /* Do everything which needs doing when the last thread exits */ static void shutdown_actions_NORETURN( ThreadId tid, VgSchedReturnCode tids_schedretcode ); /* --- end of Forwards decls to do with shutdown --- */ /* By the time we get to valgrind_main, the_iicii should already have been filled in with any important details as required by whatever OS we have been built for. */ static Int valgrind_main ( Int argc, HChar **argv, HChar **envp ) { HChar* toolname = "memcheck"; // default to Memcheck Int need_help = 0; // 0 = no, 1 = --help, 2 = --help-debug ThreadId tid_main = VG_INVALID_THREADID; Bool logging_to_fd = False; Char* xml_fname_unexpanded = NULL; Int loglevel, i; struct vki_rlimit zero = { 0, 0 }; XArray* addr2dihandle = NULL; // For an inner Valgrind, register the interim stack asap. // This is needed to allow the outer valgrind to do stacktraces during init. // Note that this stack is not unregistered when the main thread // is switching to the (real) stack. Unregistering this would imply // to save the stack id in a global variable, and have a "if" // in run_a_thread_NORETURN to do the unregistration only for the // main thread. This unregistration is not worth this complexity. INNER_REQUEST ((void) VALGRIND_STACK_REGISTER (&VG_(interim_stack).bytes[0], &VG_(interim_stack).bytes[0] + sizeof(VG_(interim_stack)))); //============================================================ // // Nb: startup is complex. Prerequisites are shown at every step. // *** Be very careful when messing with the order *** // // The first order of business is to get debug logging, the address // space manager and the dynamic memory manager up and running. // Once that's done, we can relax a bit. // //============================================================ /* This is needed to make VG_(getenv) usable early. */ VG_(client_envp) = (Char**)envp; //-------------------------------------------------------------- // Start up Mach kernel interface, if any // p: none //-------------------------------------------------------------- # if defined(VGO_darwin) VG_(mach_init)(); # endif //-------------------------------------------------------------- // Start up the logging mechanism // p: none //-------------------------------------------------------------- /* Start the debugging-log system ASAP. First find out how many "-d"s were specified. This is a pre-scan of the command line. Also get --profile-heap=yes, --core-redzone-size, --redzone-size which are needed by the time we start up dynamic memory management. */ loglevel = 0; for (i = 1; i < argc; i++) { if (argv[i][0] != '-') break; if VG_STREQ(argv[i], "--") break; if VG_STREQ(argv[i], "-d") loglevel++; if VG_BOOL_CLO(argv[i], "--profile-heap", VG_(clo_profile_heap)) {} if VG_BINT_CLO(argv[i], "--core-redzone-size", VG_(clo_core_redzone_size), 0, MAX_CLO_REDZONE_SZB) {} if VG_BINT_CLO(argv[i], "--redzone-size", VG_(clo_redzone_size), 0, MAX_CLO_REDZONE_SZB) {} } /* ... and start the debug logger. Now we can safely emit logging messages all through startup. */ VG_(debugLog_startup)(loglevel, "Stage 2 (main)"); VG_(debugLog)(1, "main", "Welcome to Valgrind version " VERSION " debug logging\n"); //-------------------------------------------------------------- // Ensure we're on a plausible stack. // p: logging //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Checking current stack is plausible\n"); { HChar* limLo = (HChar*)(&VG_(interim_stack).bytes[0]); HChar* limHi = limLo + sizeof(VG_(interim_stack)); HChar* aLocal = (HChar*)&limLo; /* any auto local will do */ /* "Apple clang version 4.0 (tags/Apple/clang-421.0.57) (based on LLVM 3.1svn)" appears to miscompile the following check, causing run to abort at this point (in 64-bit mode) even though aLocal is within limLo .. limHi. Try building with gcc instead. */ if (aLocal < limLo || aLocal >= limHi) { /* something's wrong. Stop. */ VG_(debugLog)(0, "main", "Root stack %p to %p, a local %p\n", limLo, limHi, aLocal ); VG_(debugLog)(0, "main", "Valgrind: FATAL: " "Initial stack switched failed.\n"); VG_(debugLog)(0, "main", " Cannot continue. Sorry.\n"); VG_(exit)(1); } } //-------------------------------------------------------------- // Ensure we have a plausible pointer to the stack on which // we gained control (not the current stack!) // p: logging //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Checking initial stack was noted\n"); if (the_iicii.sp_at_startup == 0) { VG_(debugLog)(0, "main", "Valgrind: FATAL: " "Initial stack was not noted.\n"); VG_(debugLog)(0, "main", " Cannot continue. Sorry.\n"); VG_(exit)(1); } //-------------------------------------------------------------- // Start up the address space manager, and determine the // approximate location of the client's stack // p: logging, plausible-stack //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Starting the address space manager\n"); vg_assert(VKI_PAGE_SIZE == 4096 || VKI_PAGE_SIZE == 65536 || VKI_PAGE_SIZE == 16384); vg_assert(VKI_MAX_PAGE_SIZE == 4096 || VKI_MAX_PAGE_SIZE == 65536 || VKI_MAX_PAGE_SIZE == 16384); vg_assert(VKI_PAGE_SIZE <= VKI_MAX_PAGE_SIZE); vg_assert(VKI_PAGE_SIZE == (1 << VKI_PAGE_SHIFT)); vg_assert(VKI_MAX_PAGE_SIZE == (1 << VKI_MAX_PAGE_SHIFT)); the_iicii.clstack_top = VG_(am_startup)( the_iicii.sp_at_startup ); VG_(debugLog)(1, "main", "Address space manager is running\n"); //-------------------------------------------------------------- // Start up the dynamic memory manager // p: address space management // p: getting --profile-heap,--core-redzone-size,--redzone-size // In fact m_mallocfree is self-initialising, so there's no // initialisation call to do. Instead, try a simple malloc/ // free pair right now to check that nothing is broken. //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Starting the dynamic memory manager\n"); { void* p = VG_(malloc)( "main.vm.1", 12345 ); if (p) VG_(free)( p ); } VG_(debugLog)(1, "main", "Dynamic memory manager is running\n"); //============================================================ // // Dynamic memory management is now available. // //============================================================ //-------------------------------------------------------------- // Initialise m_debuginfo // p: dynamic memory allocation VG_(debugLog)(1, "main", "Initialise m_debuginfo\n"); VG_(di_initialise)(); //-------------------------------------------------------------- // Look for alternative libdir { HChar *cp = VG_(getenv)(VALGRIND_LIB); if (cp != NULL) VG_(libdir) = cp; VG_(debugLog)(1, "main", "VG_(libdir) = %s\n", VG_(libdir)); } //-------------------------------------------------------------- // Extract the launcher name from the environment. VG_(debugLog)(1, "main", "Getting launcher's name ...\n"); VG_(name_of_launcher) = VG_(getenv)(VALGRIND_LAUNCHER); if (VG_(name_of_launcher) == NULL) { VG_(printf)("valgrind: You cannot run '%s' directly.\n", argv[0]); VG_(printf)("valgrind: You should use $prefix/bin/valgrind.\n"); VG_(exit)(1); } VG_(debugLog)(1, "main", "... %s\n", VG_(name_of_launcher)); //-------------------------------------------------------------- // Get the current process datasize rlimit, and set it to zero. // This prevents any internal uses of brk() from having any effect. // We remember the old value so we can restore it on exec, so that // child processes will have a reasonable brk value. VG_(getrlimit)(VKI_RLIMIT_DATA, &VG_(client_rlimit_data)); zero.rlim_max = VG_(client_rlimit_data).rlim_max; VG_(setrlimit)(VKI_RLIMIT_DATA, &zero); // Get the current process stack rlimit. VG_(getrlimit)(VKI_RLIMIT_STACK, &VG_(client_rlimit_stack)); //-------------------------------------------------------------- // Figure out what sort of CPU we're on, and whether it is // able to run V. VG_(debugLog)(1, "main", "Get hardware capabilities ...\n"); { VexArch vex_arch; VexArchInfo vex_archinfo; Bool ok = VG_(machine_get_hwcaps)(); if (!ok) { VG_(printf)("\n"); VG_(printf)("valgrind: fatal error: unsupported CPU.\n"); VG_(printf)(" Supported CPUs are:\n"); VG_(printf)(" * x86 (practically any; Pentium-I or above), " "AMD Athlon or above)\n"); VG_(printf)(" * AMD Athlon64/Opteron\n"); VG_(printf)(" * PowerPC (most; ppc405 and above)\n"); VG_(printf)(" * System z (64bit only - s390x; z900 and above)\n"); VG_(printf)("\n"); VG_(exit)(1); } VG_(machine_get_VexArchInfo)( &vex_arch, &vex_archinfo ); VG_(debugLog)( 1, "main", "... arch = %s, hwcaps = %s\n", LibVEX_ppVexArch ( vex_arch ), LibVEX_ppVexHwCaps ( vex_arch, vex_archinfo.hwcaps ) ); } //-------------------------------------------------------------- // Record the working directory at startup // p: none VG_(debugLog)(1, "main", "Getting the working directory at startup\n"); { Bool ok = VG_(record_startup_wd)(); if (!ok) VG_(err_config_error)( "Can't establish current working " "directory at startup\n"); } { Char buf[VKI_PATH_MAX+1]; Bool ok = VG_(get_startup_wd)( buf, sizeof(buf) ); vg_assert(ok); buf[VKI_PATH_MAX] = 0; VG_(debugLog)(1, "main", "... %s\n", buf ); } //============================================================ // Command line argument handling order: // * If --help/--help-debug are present, show usage message // (including the tool-specific usage) // * (If no --tool option given, default to Memcheck) // * Then, if client is missing, abort with error msg // * Then, if any cmdline args are bad, abort with error msg //============================================================ //-------------------------------------------------------------- // Split up argv into: C args, V args, V extra args, and exename. // p: dynamic memory allocation //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Split up command line\n"); VG_(split_up_argv)( argc, argv ); vg_assert( VG_(args_for_valgrind) ); vg_assert( VG_(args_for_client) ); if (0) { for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) VG_(printf)( "varg %s\n", * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i ) ); VG_(printf)(" exe %s\n", VG_(args_the_exename)); for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) VG_(printf)( "carg %s\n", * (HChar**) VG_(indexXA)( VG_(args_for_client), i ) ); } //-------------------------------------------------------------- // Extract tool name and whether help has been requested. // Note we can't print the help message yet, even if requested, // because the tool has not been initialised. // p: split_up_argv [for VG_(args_for_valgrind)] //-------------------------------------------------------------- VG_(debugLog)(1, "main", "(early_) Process Valgrind's command line options\n"); early_process_cmd_line_options(&need_help, &toolname); // Set default vex control params LibVEX_default_VexControl(& VG_(clo_vex_control)); //-------------------------------------------------------------- // Load client executable, finding in $PATH if necessary // p: early_process_cmd_line_options() [for 'exec', 'need_help', // clo_max_stackframe, // clo_main_stacksize] // p: layout_remaining_space [so there's space] // // Set up client's environment // p: set-libdir [for VG_(libdir)] // p: early_process_cmd_line_options [for toolname] // // Setup client stack, eip, and VG_(client_arg[cv]) // p: load_client() [for 'info'] // p: fix_environment() [for 'env'] // // Setup client data (brk) segment. Initially a 1-page segment // which abuts a shrinkable reservation. // p: load_client() [for 'info' and hence VG_(brk_base)] // // p: _start_in_C (for zeroing out the_iicii and putting some // initial values into it) //-------------------------------------------------------------- if (!need_help) { VG_(debugLog)(1, "main", "Create initial image\n"); # if defined(VGO_linux) || defined(VGO_darwin) the_iicii.argv = argv; the_iicii.envp = envp; the_iicii.toolname = toolname; # else # error "Unknown platform" # endif /* NOTE: this call reads VG_(clo_main_stacksize). */ the_iifii = VG_(ii_create_image)( the_iicii ); } //============================================================== // // Finished loading/setting up the client address space. // //============================================================== //-------------------------------------------------------------- // setup file descriptors // p: n/a //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Setup file descriptors\n"); setup_file_descriptors(); //-------------------------------------------------------------- // create the fake /proc/<pid>/cmdline file and then unlink it, // but hold onto the fd, so we can hand it out to the client // when it tries to open /proc/<pid>/cmdline for itself. // p: setup file descriptors //-------------------------------------------------------------- #if !defined(VGO_linux) // client shouldn't be using /proc! VG_(cl_cmdline_fd) = -1; #else if (!need_help) { HChar buf[50], buf2[50+64]; HChar nul[1]; Int fd, r; const HChar* exename; VG_(debugLog)(1, "main", "Create fake /proc/<pid>/cmdline\n"); VG_(sprintf)(buf, "proc_%d_cmdline", VG_(getpid)()); fd = VG_(mkstemp)( buf, buf2 ); if (fd == -1) VG_(err_config_error)("Can't create client cmdline file in %s\n", buf2); nul[0] = 0; exename = VG_(args_the_exename) ? VG_(args_the_exename) : "unknown_exename"; VG_(write)(fd, exename, VG_(strlen)( exename )); VG_(write)(fd, nul, 1); for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) { HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_client), i ); VG_(write)(fd, arg, VG_(strlen)( arg )); VG_(write)(fd, nul, 1); } /* Don't bother to seek the file back to the start; instead do it every time a copy of it is given out (by PRE(sys_open)). That is probably more robust across fork() etc. */ /* Now delete it, but hang on to the fd. */ r = VG_(unlink)( buf2 ); if (r) VG_(err_config_error)("Can't delete client cmdline file in %s\n", buf2); VG_(cl_cmdline_fd) = fd; } #endif //-------------------------------------------------------------- // Init tool part 1: pre_clo_init // p: setup_client_stack() [for 'VG_(client_arg[cv]'] // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)'] //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Initialise the tool part 1 (pre_clo_init)\n"); VG_(tl_pre_clo_init)(); //-------------------------------------------------------------- // If --tool and --help/--help-debug was given, now give the core+tool // help message // p: early_process_cmd_line_options() [for 'need_help'] // p: tl_pre_clo_init [for 'VG_(tdict).usage'] //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Print help and quit, if requested\n"); if (need_help) { usage_NORETURN(/*--help-debug?*/need_help >= 2); } //-------------------------------------------------------------- // Process command line options to Valgrind + tool // p: setup_client_stack() [for 'VG_(client_arg[cv]'] // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)'] //-------------------------------------------------------------- VG_(debugLog)(1, "main", "(main_) Process Valgrind's command line options, " "setup logging\n"); main_process_cmd_line_options ( &logging_to_fd, &xml_fname_unexpanded, toolname ); //-------------------------------------------------------------- // Zeroise the millisecond counter by doing a first read of it. // p: none //-------------------------------------------------------------- (void) VG_(read_millisecond_timer)(); //-------------------------------------------------------------- // Print the preamble // p: tl_pre_clo_init [for 'VG_(details).name' and friends] // p: main_process_cmd_line_options() // [for VG_(clo_verbosity), VG_(clo_xml), // logging_to_fd, xml_fname_unexpanded] //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Print the preamble...\n"); print_preamble(logging_to_fd, xml_fname_unexpanded, toolname); VG_(debugLog)(1, "main", "...finished the preamble\n"); //-------------------------------------------------------------- // Init tool part 2: post_clo_init // p: setup_client_stack() [for 'VG_(client_arg[cv]'] // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)'] // p: print_preamble() [so any warnings printed in post_clo_init // are shown after the preamble] //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Initialise the tool part 2 (post_clo_init)\n"); VG_TDICT_CALL(tool_post_clo_init); { /* The tool's "needs" will by now be finalised, since it has no further opportunity to specify them. So now sanity check them. */ Char* s; Bool ok; ok = VG_(sanity_check_needs)( &s ); if (!ok) { VG_(tool_panic)(s); } } //-------------------------------------------------------------- // Initialise translation table and translation cache // p: aspacem [??] // p: tl_pre_clo_init [for 'VG_(details).avg_translation_sizeB'] //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Initialise TT/TC\n"); VG_(init_tt_tc)(); //-------------------------------------------------------------- // Initialise the redirect table. // p: init_tt_tc [so it can call VG_(search_transtab) safely] // p: aspacem [so can change ownership of sysinfo pages] //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Initialise redirects\n"); VG_(redir_initialise)(); //-------------------------------------------------------------- // Allow GDB attach // p: main_process_cmd_line_options() [for VG_(clo_wait_for_gdb)] //-------------------------------------------------------------- /* Hook to delay things long enough so we can get the pid and attach GDB in another shell. */ if (VG_(clo_wait_for_gdb)) { ULong iters, q; VG_(debugLog)(1, "main", "Wait for GDB\n"); VG_(printf)("pid=%d, entering delay loop\n", VG_(getpid)()); # if defined(VGP_x86_linux) iters = 10; # elif defined(VGP_amd64_linux) || defined(VGP_ppc64_linux) iters = 10; # elif defined(VGP_ppc32_linux) iters = 5; # elif defined(VGP_arm_linux) iters = 5; # elif defined(VGP_s390x_linux) iters = 10; # elif defined(VGP_mips32_linux) iters = 10; # elif defined(VGO_darwin) iters = 3; # else # error "Unknown plat" # endif iters *= 1000ULL * 1000 * 1000; for (q = 0; q < iters; q++) __asm__ __volatile__("" ::: "memory","cc"); } //-------------------------------------------------------------- // Search for file descriptors that are inherited from our parent // p: main_process_cmd_line_options [for VG_(clo_track_fds)] //-------------------------------------------------------------- if (VG_(clo_track_fds)) { VG_(debugLog)(1, "main", "Init preopened fds\n"); VG_(init_preopened_fds)(); } //-------------------------------------------------------------- // Load debug info for the existing segments. // p: setup_code_redirect_table [so that redirs can be recorded] // p: mallocfree // p: probably: setup fds and process CLOs, so that logging works // p: initialise m_debuginfo // // While doing this, make a note of the debuginfo-handles that // come back from VG_(di_notify_mmap). // Later, in "Tell the tool about the initial client memory permissions" // (just below) we can then hand these handles off to the tool in // calls to VG_TRACK(new_mem_startup, ...). This gives the tool the // opportunity to make further queries to m_debuginfo before the // client is started, if it wants. We put this information into an // XArray, each handle along with the associated segment start address, // and search the XArray for the handles later, when calling // VG_TRACK(new_mem_startup, ...). //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Load initial debug info\n"); tl_assert(!addr2dihandle); addr2dihandle = VG_(newXA)( VG_(malloc), "main.vm.2", VG_(free), sizeof(Addr_n_ULong) ); tl_assert(addr2dihandle); # if defined(VGO_linux) { Addr* seg_starts; Int n_seg_starts; Addr_n_ULong anu; seg_starts = VG_(get_segment_starts)( &n_seg_starts ); vg_assert(seg_starts && n_seg_starts >= 0); /* show them all to the debug info reader. allow_SkFileV has to be True here so that we read info from the valgrind executable itself. */ for (i = 0; i < n_seg_starts; i++) { anu.ull = VG_(di_notify_mmap)( seg_starts[i], True/*allow_SkFileV*/, -1/*Don't use_fd*/); /* anu.ull holds the debuginfo handle returned by di_notify_mmap, if any. */ if (anu.ull > 0) { anu.a = seg_starts[i]; VG_(addToXA)( addr2dihandle, &anu ); } } VG_(free)( seg_starts ); } # elif defined(VGO_darwin) { Addr* seg_starts; Int n_seg_starts; seg_starts = VG_(get_segment_starts)( &n_seg_starts ); vg_assert(seg_starts && n_seg_starts >= 0); /* show them all to the debug info reader. Don't read from V segments (unlike Linux) */ // GrP fixme really? for (i = 0; i < n_seg_starts; i++) { VG_(di_notify_mmap)( seg_starts[i], False/*don't allow_SkFileV*/, -1/*don't use_fd*/); } VG_(free)( seg_starts ); } # else # error Unknown OS # endif //-------------------------------------------------------------- // Tell aspacem of ownership change of the asm helpers, so that // m_translate allows them to be translated. However, only do this // after the initial debug info read, since making a hole in the // address range for the stage2 binary confuses the debug info reader. // p: aspacem //-------------------------------------------------------------- { Bool change_ownership_v_c_OK; Addr co_start = VG_PGROUNDDN( (Addr)&VG_(trampoline_stuff_start) ); Addr co_endPlus = VG_PGROUNDUP( (Addr)&VG_(trampoline_stuff_end) ); VG_(debugLog)(1,"redir", "transfer ownership V -> C of 0x%llx .. 0x%llx\n", (ULong)co_start, (ULong)co_endPlus-1 ); change_ownership_v_c_OK = VG_(am_change_ownership_v_to_c)( co_start, co_endPlus - co_start ); vg_assert(change_ownership_v_c_OK); } if (VG_(clo_xml)) { HChar buf[50]; VG_(elapsed_wallclock_time)(buf); VG_(printf_xml)( "<status>\n" " <state>RUNNING</state>\n" " <time>%pS</time>\n" "</status>\n", buf ); VG_(printf_xml)( "\n" ); } VG_(init_Threads)(); //-------------------------------------------------------------- // Initialise the scheduler (phase 1) [generates tid_main] // p: none, afaics //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Initialise scheduler (phase 1)\n"); tid_main = VG_(scheduler_init_phase1)(); vg_assert(tid_main >= 0 && tid_main < VG_N_THREADS && tid_main != VG_INVALID_THREADID); /* Tell the tool about tid_main */ VG_TRACK( pre_thread_ll_create, VG_INVALID_THREADID, tid_main ); //-------------------------------------------------------------- // Tell the tool about the initial client memory permissions // p: aspacem // p: mallocfree // p: setup_client_stack // p: setup_client_dataseg // // For each segment we tell the client about, look up in // addr2dihandle as created above, to see if there's a debuginfo // handle associated with the segment, that we can hand along // to the tool, to be helpful. //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Tell tool about initial permissions\n"); { Addr* seg_starts; Int n_seg_starts; tl_assert(addr2dihandle); /* Mark the main thread as running while we tell the tool about the client memory so that the tool can associate that memory with the main thread. */ tl_assert(VG_(running_tid) == VG_INVALID_THREADID); VG_(running_tid) = tid_main; seg_starts = VG_(get_segment_starts)( &n_seg_starts ); vg_assert(seg_starts && n_seg_starts >= 0); /* show interesting ones to the tool */ for (i = 0; i < n_seg_starts; i++) { Word j, n; NSegment const* seg = VG_(am_find_nsegment)( seg_starts[i] ); vg_assert(seg); if (seg->kind == SkFileC || seg->kind == SkAnonC) { /* This next assertion is tricky. If it is placed immediately before this 'if', it very occasionally fails. Why? Because previous iterations of the loop may have caused tools (via the new_mem_startup calls) to do dynamic memory allocation, and that may affect the mapped segments; in particular it may cause segment merging to happen. Hence we cannot assume that seg_starts[i], which reflects the state of the world before we started this loop, is the same as seg->start, as the latter reflects the state of the world (viz, mappings) at this particular iteration of the loop. Why does moving it inside the 'if' make it safe? Because any dynamic memory allocation done by the tools will affect only the state of Valgrind-owned segments, not of Client-owned segments. And the 'if' guards against that -- we only get in here for Client-owned segments. In other words: the loop may change the state of Valgrind-owned segments as it proceeds. But it should not cause the Client-owned segments to change. */ vg_assert(seg->start == seg_starts[i]); VG_(debugLog)(2, "main", "tell tool about %010lx-%010lx %c%c%c\n", seg->start, seg->end, seg->hasR ? 'r' : '-', seg->hasW ? 'w' : '-', seg->hasX ? 'x' : '-' ); /* search addr2dihandle to see if we have an entry matching seg->start. */ n = VG_(sizeXA)( addr2dihandle ); for (j = 0; j < n; j++) { Addr_n_ULong* anl = VG_(indexXA)( addr2dihandle, j ); if (anl->a == seg->start) { tl_assert(anl->ull > 0); /* check it's a valid handle */ break; } } vg_assert(j >= 0 && j <= n); VG_TRACK( new_mem_startup, seg->start, seg->end+1-seg->start, seg->hasR, seg->hasW, seg->hasX, /* and the retrieved debuginfo handle, if any */ j < n ? ((Addr_n_ULong*)VG_(indexXA)( addr2dihandle, j ))->ull : 0 ); } } VG_(free)( seg_starts ); VG_(deleteXA)( addr2dihandle ); /* Also do the initial stack permissions. */ { SSizeT inaccessible_len; NSegment const* seg = VG_(am_find_nsegment)( the_iifii.initial_client_SP ); vg_assert(seg); vg_assert(seg->kind == SkAnonC); vg_assert(the_iifii.initial_client_SP >= seg->start); vg_assert(the_iifii.initial_client_SP <= seg->end); /* Stuff below the initial SP is unaddressable. Take into account any ABI-mandated space below the stack pointer that is required (VG_STACK_REDZONE_SZB). setup_client_stack() will have allocated an extra page if a red zone is required, to be on the safe side. */ inaccessible_len = the_iifii.initial_client_SP - VG_STACK_REDZONE_SZB - seg->start; vg_assert(inaccessible_len >= 0); if (inaccessible_len > 0) VG_TRACK( die_mem_stack, seg->start, inaccessible_len ); VG_(debugLog)(2, "main", "mark stack inaccessible %010lx-%010lx\n", seg->start, the_iifii.initial_client_SP-1 - VG_STACK_REDZONE_SZB); } /* Also the assembly helpers. */ VG_TRACK( new_mem_startup, (Addr)&VG_(trampoline_stuff_start), (Addr)&VG_(trampoline_stuff_end) - (Addr)&VG_(trampoline_stuff_start), False, /* readable? */ False, /* writable? */ True /* executable? */, 0 /* di_handle: no associated debug info */ ); /* Clear the running thread indicator */ VG_(running_tid) = VG_INVALID_THREADID; tl_assert(VG_(running_tid) == VG_INVALID_THREADID); } //-------------------------------------------------------------- // Initialise the scheduler (phase 2) // p: Initialise the scheduler (phase 1) [for tid_main] // p: setup_file_descriptors() [else VG_(safe_fd)() breaks] // p: setup_client_stack //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Initialise scheduler (phase 2)\n"); { NSegment const* seg = VG_(am_find_nsegment)( the_iifii.initial_client_SP ); vg_assert(seg); vg_assert(seg->kind == SkAnonC); vg_assert(the_iifii.initial_client_SP >= seg->start); vg_assert(the_iifii.initial_client_SP <= seg->end); VG_(scheduler_init_phase2)( tid_main, seg->end, the_iifii.clstack_max_size ); } //-------------------------------------------------------------- // Set up state for the root thread // p: ? // setup_scheduler() [for sched-specific thread 1 stuff] // VG_(ii_create_image) [for 'the_iicii' initial info] //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Finalise initial image\n"); VG_(ii_finalise_image)( the_iifii ); //-------------------------------------------------------------- // Initialise the signal handling subsystem // p: n/a //-------------------------------------------------------------- // Nb: temporarily parks the saved blocking-mask in saved_sigmask. VG_(debugLog)(1, "main", "Initialise signal management\n"); /* Check that the kernel-interface signal definitions look sane */ VG_(vki_do_initial_consistency_checks)(); /* .. and go on to use them. */ VG_(sigstartup_actions)(); //-------------------------------------------------------------- // Read suppression file // p: main_process_cmd_line_options() [for VG_(clo_suppressions)] //-------------------------------------------------------------- if (VG_(needs).core_errors || VG_(needs).tool_errors) { VG_(debugLog)(1, "main", "Load suppressions\n"); VG_(load_suppressions)(); } //-------------------------------------------------------------- // register client stack //-------------------------------------------------------------- VG_(clstk_id) = VG_(register_stack)(VG_(clstk_base), VG_(clstk_end)); //-------------------------------------------------------------- // Show the address space state so far //-------------------------------------------------------------- VG_(debugLog)(1, "main", "\n"); VG_(debugLog)(1, "main", "\n"); VG_(am_show_nsegments)(1,"Memory layout at client startup"); VG_(debugLog)(1, "main", "\n"); VG_(debugLog)(1, "main", "\n"); //-------------------------------------------------------------- // Run! //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Running thread 1\n"); /* As a result of the following call, the last thread standing eventually winds up running shutdown_actions_NORETURN just below. Unfortunately, simply exporting said function causes m_main to be part of a module cycle, which is pretty nonsensical. So instead of doing that, the address of said function is stored in a global variable 'owned' by m_syswrap, and it uses that function pointer to get back here when it needs to. */ /* Set continuation address. */ VG_(address_of_m_main_shutdown_actions_NORETURN) = & shutdown_actions_NORETURN; /* Run the first thread, eventually ending up at the continuation address. */ VG_(main_thread_wrapper_NORETURN)(1); /*NOTREACHED*/ vg_assert(0); } /* Do everything which needs doing when the last thread exits or when a thread exits requesting a complete process exit. We enter here holding The Lock. For the case VgSrc_ExitProcess we must never release it, because to do so would allow other threads to continue after the system is ostensibly shut down. So we must go to our grave, so to speak, holding the lock. In fact, there is never any point in releasing the lock at this point - we have it, we're shutting down the entire system, and for the case VgSrc_ExitProcess doing so positively causes trouble. So don't. The final_tidyup call makes a bit of a nonsense of the ExitProcess case, since it will run the libc_freeres function, thus allowing other lurking threads to run again. Hmm. */ static void shutdown_actions_NORETURN( ThreadId tid, VgSchedReturnCode tids_schedretcode ) { VG_(debugLog)(1, "main", "entering VG_(shutdown_actions_NORETURN)\n"); VG_(am_show_nsegments)(1,"Memory layout at client shutdown"); vg_assert(VG_(is_running_thread)(tid)); vg_assert(tids_schedretcode == VgSrc_ExitThread || tids_schedretcode == VgSrc_ExitProcess || tids_schedretcode == VgSrc_FatalSig ); if (tids_schedretcode == VgSrc_ExitThread) { // We are the last surviving thread. Right? vg_assert( VG_(count_living_threads)() == 1 ); // Wait for all other threads to exit. // jrs: Huh? but they surely are already gone VG_(reap_threads)(tid); // Clean the client up before the final report // this causes the libc_freeres function to run final_tidyup(tid); /* be paranoid */ vg_assert(VG_(is_running_thread)(tid)); vg_assert(VG_(count_living_threads)() == 1); } else { // We may not be the last surviving thread. However, we // want to shut down the entire process. We hold the lock // and we need to keep hold of it all the way out, in order // that none of the other threads ever run again. vg_assert( VG_(count_living_threads)() >= 1 ); // Clean the client up before the final report // this causes the libc_freeres function to run // perhaps this is unsafe, as per comment above final_tidyup(tid); /* be paranoid */ vg_assert(VG_(is_running_thread)(tid)); vg_assert(VG_(count_living_threads)() >= 1); } VG_(threads)[tid].status = VgTs_Empty; //-------------------------------------------------------------- // Finalisation: cleanup, messages, etc. Order not so important, only // affects what order the messages come. //-------------------------------------------------------------- // First thing in the post-amble is a blank line. if (VG_(clo_xml)) VG_(printf_xml)("\n"); else if (VG_(clo_verbosity) > 0) VG_(message)(Vg_UserMsg, "\n"); if (VG_(clo_xml)) { HChar buf[50]; VG_(elapsed_wallclock_time)(buf); VG_(printf_xml)( "<status>\n" " <state>FINISHED</state>\n" " <time>%pS</time>\n" "</status>\n" "\n", buf); } /* Print out file descriptor summary and stats. */ if (VG_(clo_track_fds)) VG_(show_open_fds)(); /* Call the tool's finalisation function. This makes Memcheck's leak checker run, and possibly chuck a bunch of leak errors into the error management machinery. */ VG_TDICT_CALL(tool_fini, 0/*exitcode*/); /* Show the error counts. */ if (VG_(clo_xml) && (VG_(needs).core_errors || VG_(needs).tool_errors)) { VG_(show_error_counts_as_XML)(); } /* In XML mode, this merely prints the used suppressions. */ if (VG_(needs).core_errors || VG_(needs).tool_errors) VG_(show_all_errors)(VG_(clo_verbosity), VG_(clo_xml)); if (VG_(clo_xml)) { VG_(printf_xml)("\n"); VG_(printf_xml)("</valgrindoutput>\n"); VG_(printf_xml)("\n"); } VG_(sanity_check_general)( True /*include expensive checks*/ ); if (VG_(clo_stats)) print_all_stats(); /* Show a profile of the heap(s) at shutdown. Optionally, first throw away all the debug info, as that makes it easy to spot leaks in the debuginfo reader. */ if (VG_(clo_profile_heap)) { if (0) VG_(di_discard_ALL_debuginfo)(); VG_(print_arena_cc_analysis)(); } if (VG_(clo_profile_flags) > 0) { #define N_MAX 200 BBProfEntry tops[N_MAX]; ULong score_total = VG_(get_BB_profile) (tops, N_MAX); show_BB_profile(tops, N_MAX, score_total); } /* Print Vex storage stats */ if (0) LibVEX_ShowAllocStats(); /* Flush any output cached by previous calls to VG_(message). */ VG_(message_flush)(); /* terminate gdbserver if ever it was started. We terminate it here so that it get the output above if output was redirected to gdb */ VG_(gdbserver) (0); /* Ok, finally exit in the os-specific way, according to the scheduler's return code. In short, if the (last) thread exited by calling sys_exit, do likewise; if the (last) thread stopped due to a fatal signal, terminate the entire system with that same fatal signal. */ VG_(debugLog)(1, "core_os", "VG_(terminate_NORETURN)(tid=%lld)\n", (ULong)tid); switch (tids_schedretcode) { case VgSrc_ExitThread: /* the normal way out (Linux) */ case VgSrc_ExitProcess: /* the normal way out (AIX) -- still needed? */ /* Change the application return code to user's return code, if an error was found */ if (VG_(clo_error_exitcode) > 0 && VG_(get_n_errs_found)() > 0) { VG_(exit)( VG_(clo_error_exitcode) ); } else { /* otherwise, return the client's exit code, in the normal way. */ VG_(exit)( VG_(threads)[tid].os_state.exitcode ); } /* NOT ALIVE HERE! */ VG_(core_panic)("entered the afterlife in main() -- ExitT/P"); break; /* what the hell :) */ case VgSrc_FatalSig: /* We were killed by a fatal signal, so replicate the effect */ vg_assert(VG_(threads)[tid].os_state.fatalsig != 0); VG_(kill_self)(VG_(threads)[tid].os_state.fatalsig); /* we shouldn't be alive at this point. But VG_(kill_self) sometimes fails with EPERM on Darwin, for unclear reasons. */ # if defined(VGO_darwin) VG_(debugLog)(0, "main", "VG_(kill_self) failed. Exiting normally.\n"); VG_(exit)(0); /* bogus, but we really need to exit now */ /* fall through .. */ # endif VG_(core_panic)("main(): signal was supposed to be fatal"); break; default: VG_(core_panic)("main(): unexpected scheduler return code"); } } /* -------------------- */ /* Final clean-up before terminating the process. Clean up the client by calling __libc_freeres() (if requested) This is Linux-specific? GrP fixme glibc-specific, anyway */ static void final_tidyup(ThreadId tid) { #if !defined(VGO_darwin) # if defined(VGP_ppc64_linux) Addr r2; # endif Addr __libc_freeres_wrapper = VG_(client___libc_freeres_wrapper); vg_assert(VG_(is_running_thread)(tid)); if ( !VG_(needs).libc_freeres || !VG_(clo_run_libc_freeres) || 0 == __libc_freeres_wrapper ) return; /* can't/won't do it */ # if defined(VGP_ppc64_linux) r2 = VG_(get_tocptr)( __libc_freeres_wrapper ); if (r2 == 0) { VG_(message)(Vg_UserMsg, "Caught __NR_exit, but can't run __libc_freeres()\n"); VG_(message)(Vg_UserMsg, " since cannot establish TOC pointer for it.\n"); return; } # endif if (VG_(clo_verbosity) > 2 || VG_(clo_trace_syscalls) || VG_(clo_trace_sched)) VG_(message)(Vg_DebugMsg, "Caught __NR_exit; running __libc_freeres()\n"); /* set thread context to point to libc_freeres_wrapper */ /* ppc64-linux note: __libc_freeres_wrapper gives us the real function entry point, not a fn descriptor, so can use it directly. However, we need to set R2 (the toc pointer) appropriately. */ VG_(set_IP)(tid, __libc_freeres_wrapper); # if defined(VGP_ppc64_linux) VG_(threads)[tid].arch.vex.guest_GPR2 = r2; # endif /* mips-linux note: we need to set t9 */ # if defined(VGP_mips32_linux) VG_(threads)[tid].arch.vex.guest_r25 = __libc_freeres_wrapper; # endif /* Block all blockable signals by copying the real block state into the thread's block state*/ VG_(sigprocmask)(VKI_SIG_BLOCK, NULL, &VG_(threads)[tid].sig_mask); VG_(threads)[tid].tmp_sig_mask = VG_(threads)[tid].sig_mask; /* and restore handlers to default */ VG_(set_default_handler)(VKI_SIGSEGV); VG_(set_default_handler)(VKI_SIGBUS); VG_(set_default_handler)(VKI_SIGILL); VG_(set_default_handler)(VKI_SIGFPE); // We were exiting, so assert that... vg_assert(VG_(is_exiting)(tid)); // ...but now we're not again VG_(threads)[tid].exitreason = VgSrc_None; // run until client thread exits - ideally with LIBC_FREERES_DONE, // but exit/exitgroup/signal will do VG_(scheduler)(tid); vg_assert(VG_(is_exiting)(tid)); #endif } /*====================================================================*/ /*=== Getting to main() alive: LINUX ===*/ /*====================================================================*/ #if defined(VGO_linux) /* If linking of the final executables is done with glibc present, then Valgrind starts at main() above as usual, and all of the following code is irrelevant. However, this is not the intended mode of use. The plan is to avoid linking against glibc, by giving gcc the flags -nodefaultlibs -lgcc -nostartfiles at startup. From this derive two requirements: 1. gcc may emit calls to memcpy and memset to deal with structure assignments etc. Since we have chosen to ignore all the "normal" supporting libraries, we have to provide our own implementations of them. No problem. 2. We have to provide a symbol "_start", to which the kernel hands control at startup. Hence the code below. */ /* ---------------- Requirement 1 ---------------- */ void* memcpy(void *dest, const void *src, SizeT n); void* memcpy(void *dest, const void *src, SizeT n) { return VG_(memcpy)(dest,src,n); } void* memset(void *s, int c, SizeT n); void* memset(void *s, int c, SizeT n) { return VG_(memset)(s,c,n); } /* BVA: abort() for those platforms that need it (PPC and ARM). */ void abort(void); void abort(void){ VG_(printf)("Something called raise().\n"); vg_assert(0); } /* EAZG: ARM's EABI will call floating point exception handlers in libgcc which boil down to an abort or raise, that's usually defined in libc. Instead, define them here. */ #if defined(VGP_arm_linux) void raise(void); void raise(void){ VG_(printf)("Something called raise().\n"); vg_assert(0); } void __aeabi_unwind_cpp_pr0(void); void __aeabi_unwind_cpp_pr0(void){ VG_(printf)("Something called __aeabi_unwind_cpp_pr0()\n"); vg_assert(0); } void __aeabi_unwind_cpp_pr1(void); void __aeabi_unwind_cpp_pr1(void){ VG_(printf)("Something called __aeabi_unwind_cpp_pr1()\n"); vg_assert(0); } #endif /* ---------------- Requirement 2 ---------------- */ /* Glibc's sysdeps/i386/elf/start.S has the following gem of a comment, which explains how the stack looks right at process start (when _start is jumped to). Hence _start passes %esp to _start_in_C_linux, which extracts argc/argv/envp and starts up correctly. */ /* This is the canonical entry point, usually the first thing in the text segment. The SVR4/i386 ABI (pages 3-31, 3-32) says that when the entry point runs, most registers' values are unspecified, except for: %edx Contains a function pointer to be registered with `atexit'. This is how the dynamic linker arranges to have DT_FINI functions called for shared libraries that have been loaded before this code runs. %esp The stack contains the arguments and environment: 0(%esp) argc 4(%esp) argv[0] ... (4*argc)(%esp) NULL (4*(argc+1))(%esp) envp[0] ... NULL */ /* The kernel hands control to _start, which extracts the initial stack pointer and calls onwards to _start_in_C_linux. This also switches the new stack. */ #if defined(VGP_x86_linux) asm("\n" ".text\n" "\t.globl _start\n" "\t.type _start,@function\n" "_start:\n" /* set up the new stack in %eax */ "\tmovl $vgPlain_interim_stack, %eax\n" "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n" "\taddl $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %eax\n" "\tsubl $16, %eax\n" "\tandl $~15, %eax\n" /* install it, and collect the original one */ "\txchgl %eax, %esp\n" /* call _start_in_C_linux, passing it the startup %esp */ "\tpushl %eax\n" "\tcall _start_in_C_linux\n" "\thlt\n" ".previous\n" ); #elif defined(VGP_amd64_linux) asm("\n" ".text\n" "\t.globl _start\n" "\t.type _start,@function\n" "_start:\n" /* set up the new stack in %rdi */ "\tmovq $vgPlain_interim_stack, %rdi\n" "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n" "\taddq $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %rdi\n" "\tandq $~15, %rdi\n" /* install it, and collect the original one */ "\txchgq %rdi, %rsp\n" /* call _start_in_C_linux, passing it the startup %rsp */ "\tcall _start_in_C_linux\n" "\thlt\n" ".previous\n" ); #elif defined(VGP_ppc32_linux) asm("\n" ".text\n" "\t.globl _start\n" "\t.type _start,@function\n" "_start:\n" /* set up the new stack in r16 */ "\tlis 16,vgPlain_interim_stack@ha\n" "\tla 16,vgPlain_interim_stack@l(16)\n" "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n" "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n" "\tlis 18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" >> 16)\n" "\tori 18,18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" & 0xFFFF)\n" "\tadd 16,17,16\n" "\tadd 16,18,16\n" "\trlwinm 16,16,0,0,27\n" /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB + VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte boundary. And r1 is the original SP. Set the SP to r16 and call _start_in_C_linux, passing it the initial SP. */ "\tmr 3,1\n" "\tmr 1,16\n" "\tbl _start_in_C_linux\n" "\ttrap\n" ".previous\n" ); #elif defined(VGP_ppc64_linux) asm("\n" /* PPC64 ELF ABI says '_start' points to a function descriptor. So we must have one, and that is what goes into the .opd section. */ "\t.align 2\n" "\t.global _start\n" "\t.section \".opd\",\"aw\"\n" "\t.align 3\n" "_start:\n" "\t.quad ._start,.TOC.@tocbase,0\n" "\t.previous\n" "\t.type ._start,@function\n" "\t.global ._start\n" "._start:\n" /* set up the new stack in r16 */ "\tlis 16, vgPlain_interim_stack@highest\n" "\tori 16,16,vgPlain_interim_stack@higher\n" "\tsldi 16,16,32\n" "\toris 16,16,vgPlain_interim_stack@h\n" "\tori 16,16,vgPlain_interim_stack@l\n" "\txor 17,17,17\n" "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n" "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n" "\txor 18,18,18\n" "\tlis 18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" >> 16)\n" "\tori 18,18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" & 0xFFFF)\n" "\tadd 16,17,16\n" "\tadd 16,18,16\n" "\trldicr 16,16,0,59\n" /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB + VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte boundary. And r1 is the original SP. Set the SP to r16 and call _start_in_C_linux, passing it the initial SP. */ "\tmr 3,1\n" "\tmr 1,16\n" "\tlis 14, _start_in_C_linux@highest\n" "\tori 14,14,_start_in_C_linux@higher\n" "\tsldi 14,14,32\n" "\toris 14,14,_start_in_C_linux@h\n" "\tori 14,14,_start_in_C_linux@l\n" "\tld 14,0(14)\n" "\tmtctr 14\n" "\tbctrl\n" "\tnop\n" "\ttrap\n" ); #elif defined(VGP_s390x_linux) /* This is the canonical entry point, usually the first thing in the text segment. Most registers' values are unspecified, except for: %r14 Contains a function pointer to be registered with `atexit'. This is how the dynamic linker arranges to have DT_FINI functions called for shared libraries that have been loaded before this code runs. %r15 The stack contains the arguments and environment: 0(%r15) argc 8(%r15) argv[0] ... (8*argc)(%r15) NULL (8*(argc+1))(%r15) envp[0] ... NULL */ asm("\n\t" ".text\n\t" ".globl _start\n\t" ".type _start,@function\n\t" "_start:\n\t" /* set up the new stack in %r1 */ "larl %r1, vgPlain_interim_stack\n\t" "larl %r5, 1f\n\t" "ag %r1, 0(%r5)\n\t" "ag %r1, 2f-1f(%r5)\n\t" "nill %r1, 0xFFF0\n\t" /* install it, and collect the original one */ "lgr %r2, %r15\n\t" "lgr %r15, %r1\n\t" /* call _start_in_C_linux, passing it the startup %r15 */ "brasl %r14, _start_in_C_linux\n\t" /* trigger execution of an invalid opcode -> halt machine */ "j .+2\n\t" "1: .quad "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n\t" "2: .quad "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n\t" ".previous\n" ); #elif defined(VGP_arm_linux) asm("\n" "\t.text\n" "\t.align 4\n" "\t.type _start,#function\n" "\t.global _start\n" "_start:\n" "\tldr r0, [pc, #36]\n" "\tldr r1, [pc, #36]\n" "\tadd r0, r1, r0\n" "\tldr r1, [pc, #32]\n" "\tadd r0, r1, r0\n" "\tmvn r1, #15\n" "\tand r0, r0, r1\n" "\tmov r1, sp\n" "\tmov sp, r0\n" "\tmov r0, r1\n" "\tb _start_in_C_linux\n" "\t.word vgPlain_interim_stack\n" "\t.word "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n" "\t.word "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n" ); #elif defined(VGP_mips32_linux) asm("\n" "\t.type _gp_disp,@object\n" ".text\n" "\t.globl __start\n" "\t.type __start,@function\n" "__start:\n" "\tbal 1f\n" "\tnop\n" "1:\n" "\tlui $28, %hi(_gp_disp)\n" "\taddiu $28, $28, %lo(_gp_disp)\n" "\taddu $28, $28, $31\n" /* t1/$9 <- Addr(interim_stack) */ "\tlui $9, %hi(vgPlain_interim_stack)\n" /* t1/$9 <- Addr(interim_stack) */ "\taddiu $9, %lo(vgPlain_interim_stack)\n" "\tli $10, "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n" "\tli $11, "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n" "\taddu $9, $9, $10\n" "\taddu $9, $9, $11\n" "\tli $12, 0xFFFFFFF0\n" "\tand $9, $9, $12\n" /* now t1/$9 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB + VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte boundary. And $29 is the original SP. Set the SP to t1 and call _start_in_C, passing it the initial SP. */ "\tmove $4, $29\n" // a0 <- $sp (_start_in_C first arg) "\tmove $29, $9\n" // $sp <- t1 (new sp) "\tlui $25, %hi(_start_in_C_linux)\n" "\taddiu $25, %lo(_start_in_C_linux)\n" "\tbal _start_in_C_linux\n" "\tbreak 0x7\n" ".previous\n" ); #else # error "Unknown linux platform" #endif /* --- !!! --- EXTERNAL HEADERS start --- !!! --- */ #define _GNU_SOURCE #define _FILE_OFFSET_BITS 64 /* This is in order to get AT_NULL and AT_PAGESIZE. */ #include <elf.h> /* --- !!! --- EXTERNAL HEADERS end --- !!! --- */ /* Avoid compiler warnings: this fn _is_ used, but labelling it 'static' causes gcc to complain it isn't. attribute 'used' also ensures the code is not eliminated at link time */ __attribute__ ((used)) void _start_in_C_linux ( UWord* pArgc ); __attribute__ ((used)) void _start_in_C_linux ( UWord* pArgc ) { Int r; Word argc = pArgc[0]; HChar** argv = (HChar**)&pArgc[1]; HChar** envp = (HChar**)&pArgc[1+argc+1]; VG_(memset)( &the_iicii, 0, sizeof(the_iicii) ); VG_(memset)( &the_iifii, 0, sizeof(the_iifii) ); the_iicii.sp_at_startup = (Addr)pArgc; # if defined(VGP_ppc32_linux) || defined(VGP_ppc64_linux) { /* ppc/ppc64 can be configured with different page sizes. Determine this early. This is an ugly hack and really should be moved into valgrind_main. */ UWord *sp = &pArgc[1+argc+1]; while (*sp++ != 0) ; for (; *sp != AT_NULL && *sp != AT_PAGESZ; sp += 2); if (*sp == AT_PAGESZ) { VKI_PAGE_SIZE = sp[1]; for (VKI_PAGE_SHIFT = 12; VKI_PAGE_SHIFT <= VKI_MAX_PAGE_SHIFT; VKI_PAGE_SHIFT++) if (VKI_PAGE_SIZE == (1UL << VKI_PAGE_SHIFT)) break; } } # endif r = valgrind_main( (Int)argc, argv, envp ); /* NOTREACHED */ VG_(exit)(r); } /*====================================================================*/ /*=== Getting to main() alive: darwin ===*/ /*====================================================================*/ #elif defined(VGO_darwin) /* Memory layout established by kernel: 0(%esp) argc 4(%esp) argv[0] ... argv[argc-1] NULL envp[0] ... envp[n] NULL executable name (presumably, a pointer to it) NULL Ditto in the 64-bit case, except all offsets from SP are obviously twice as large. */ /* The kernel hands control to _start, which extracts the initial stack pointer and calls onwards to _start_in_C_darwin. This also switches to the new stack. */ #if defined(VGP_x86_darwin) asm("\n" ".text\n" ".align 2,0x90\n" "\t.globl __start\n" "__start:\n" /* set up the new stack in %eax */ "\tmovl $_vgPlain_interim_stack, %eax\n" "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n" "\taddl $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %eax\n" "\tsubl $16, %eax\n" "\tandl $~15, %eax\n" /* install it, and collect the original one */ "\txchgl %eax, %esp\n" "\tsubl $12, %esp\n" // keep stack 16 aligned; see #295428 /* call _start_in_C_darwin, passing it the startup %esp */ "\tpushl %eax\n" "\tcall __start_in_C_darwin\n" "\tint $3\n" "\tint $3\n" ); #elif defined(VGP_amd64_darwin) asm("\n" ".text\n" "\t.globl __start\n" ".align 3,0x90\n" "__start:\n" /* set up the new stack in %rdi */ "\tmovabsq $_vgPlain_interim_stack, %rdi\n" "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n" "\taddq $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %rdi\n" "\tandq $~15, %rdi\n" /* install it, and collect the original one */ "\txchgq %rdi, %rsp\n" /* call _start_in_C_darwin, passing it the startup %rsp */ "\tcall __start_in_C_darwin\n" "\tint $3\n" "\tint $3\n" ); #endif void* __memcpy_chk(void *dest, const void *src, SizeT n, SizeT n2); void* __memcpy_chk(void *dest, const void *src, SizeT n, SizeT n2) { // skip check return VG_(memcpy)(dest,src,n); } void* __memset_chk(void *s, int c, SizeT n, SizeT n2); void* __memset_chk(void *s, int c, SizeT n, SizeT n2) { // skip check return VG_(memset)(s,c,n); } void bzero(void *s, SizeT n); void bzero(void *s, SizeT n) { VG_(memset)(s,0,n); } void* memcpy(void *dest, const void *src, SizeT n); void* memcpy(void *dest, const void *src, SizeT n) { return VG_(memcpy)(dest,src,n); } void* memset(void *s, int c, SizeT n); void* memset(void *s, int c, SizeT n) { return VG_(memset)(s,c,n); } /* Avoid compiler warnings: this fn _is_ used, but labelling it 'static' causes gcc to complain it isn't. */ void _start_in_C_darwin ( UWord* pArgc ); void _start_in_C_darwin ( UWord* pArgc ) { Int r; Int argc = *(Int *)pArgc; // not pArgc[0] on LP64 HChar** argv = (HChar**)&pArgc[1]; HChar** envp = (HChar**)&pArgc[1+argc+1]; VG_(memset)( &the_iicii, 0, sizeof(the_iicii) ); VG_(memset)( &the_iifii, 0, sizeof(the_iifii) ); the_iicii.sp_at_startup = (Addr)pArgc; r = valgrind_main( (Int)argc, argv, envp ); /* NOTREACHED */ VG_(exit)(r); } #else # error "Unknown OS" #endif /*====================================================================*/ /*=== {u,}{div,mod}di3 replacements ===*/ /*====================================================================*/ /* For static linking on x86-darwin, we need to supply our own 64-bit integer division code, else the link dies thusly: ld_classic: Undefined symbols: ___udivdi3 ___umoddi3 */ #if defined(VGP_x86_darwin) /* Routines for doing signed/unsigned 64 x 64 ==> 64 div and mod (udivdi3, umoddi3, divdi3, moddi3) using only 32 x 32 ==> 32 division. Cobbled together from http://www.hackersdelight.org/HDcode/divlu.c http://www.hackersdelight.org/HDcode/divls.c http://www.hackersdelight.org/HDcode/newCode/divDouble.c The code from those three files is covered by the following license, as it appears at: http://www.hackersdelight.org/permissions.htm You are free to use, copy, and distribute any of the code on this web site, whether modified by you or not. You need not give attribution. This includes the algorithms (some of which appear in Hacker's Delight), the Hacker's Assistant, and any code submitted by readers. Submitters implicitly agree to this. */ /* Long division, unsigned (64/32 ==> 32). This procedure performs unsigned "long division" i.e., division of a 64-bit unsigned dividend by a 32-bit unsigned divisor, producing a 32-bit quotient. In the overflow cases (divide by 0, or quotient exceeds 32 bits), it returns a remainder of 0xFFFFFFFF (an impossible value). The dividend is u1 and u0, with u1 being the most significant word. The divisor is parameter v. The value returned is the quotient. Max line length is 57, to fit in hacker.book. */ static Int nlz32(UInt x) { Int n; if (x == 0) return(32); n = 0; if (x <= 0x0000FFFF) {n = n +16; x = x <<16;} if (x <= 0x00FFFFFF) {n = n + 8; x = x << 8;} if (x <= 0x0FFFFFFF) {n = n + 4; x = x << 4;} if (x <= 0x3FFFFFFF) {n = n + 2; x = x << 2;} if (x <= 0x7FFFFFFF) {n = n + 1;} return n; } /* 64 x 32 ==> 32 unsigned division, using only 32 x 32 ==> 32 division as a primitive. */ static UInt divlu2(UInt u1, UInt u0, UInt v, UInt *r) { const UInt b = 65536; // Number base (16 bits). UInt un1, un0, // Norm. dividend LSD's. vn1, vn0, // Norm. divisor digits. q1, q0, // Quotient digits. un32, un21, un10, // Dividend digit pairs. rhat; // A remainder. Int s; // Shift amount for norm. if (u1 >= v) { // If overflow, set rem. if (r != NULL) // to an impossible value, *r = 0xFFFFFFFF; // and return the largest return 0xFFFFFFFF;} // possible quotient. s = nlz32(v); // 0 <= s <= 31. v = v << s; // Normalize divisor. vn1 = v >> 16; // Break divisor up into vn0 = v & 0xFFFF; // two 16-bit digits. un32 = (u1 << s) | ((u0 >> (32 - s)) & (-s >> 31)); un10 = u0 << s; // Shift dividend left. un1 = un10 >> 16; // Break right half of un0 = un10 & 0xFFFF; // dividend into two digits. q1 = un32/vn1; // Compute the first rhat = un32 - q1*vn1; // quotient digit, q1. again1: if (q1 >= b || q1*vn0 > b*rhat + un1) { q1 = q1 - 1; rhat = rhat + vn1; if (rhat < b) goto again1;} un21 = un32*b + un1 - q1*v; // Multiply and subtract. q0 = un21/vn1; // Compute the second rhat = un21 - q0*vn1; // quotient digit, q0. again2: if (q0 >= b || q0*vn0 > b*rhat + un0) { q0 = q0 - 1; rhat = rhat + vn1; if (rhat < b) goto again2;} if (r != NULL) // If remainder is wanted, *r = (un21*b + un0 - q0*v) >> s; // return it. return q1*b + q0; } /* 64 x 32 ==> 32 signed division, using only 32 x 32 ==> 32 division as a primitive. */ static Int divls(Int u1, UInt u0, Int v, Int *r) { Int q, uneg, vneg, diff, borrow; uneg = u1 >> 31; // -1 if u < 0. if (uneg) { // Compute the absolute u0 = -u0; // value of the dividend u. borrow = (u0 != 0); u1 = -u1 - borrow;} vneg = v >> 31; // -1 if v < 0. v = (v ^ vneg) - vneg; // Absolute value of v. if ((UInt)u1 >= (UInt)v) goto overflow; q = divlu2(u1, u0, v, (UInt *)r); diff = uneg ^ vneg; // Negate q if signs of q = (q ^ diff) - diff; // u and v differed. if (uneg && r != NULL) *r = -*r; if ((diff ^ q) < 0 && q != 0) { // If overflow, overflow: // set remainder if (r != NULL) // to an impossible value, *r = 0x80000000; // and return the largest q = 0x80000000;} // possible neg. quotient. return q; } /* This file contains a program for doing 64/64 ==> 64 division, on a machine that does not have that instruction but that does have instructions for "long division" (64/32 ==> 32). Code for unsigned division is given first, followed by a simple program for doing the signed version by using the unsigned version. These programs are useful in implementing "long long" (64-bit) arithmetic on a machine that has the long division instruction. It will work on 64- and 32-bit machines, provided the compiler implements long long's (64-bit integers). It is desirable that the machine have the Count Leading Zeros instruction. In the GNU world, these programs are known as __divdi3 and __udivdi3, and similar names are used here. This material is not in HD, but may be in a future edition. Max line length is 57, to fit in hacker.book. */ static Int nlz64(ULong x) { Int n; if (x == 0) return(64); n = 0; if (x <= 0x00000000FFFFFFFFULL) {n = n + 32; x = x << 32;} if (x <= 0x0000FFFFFFFFFFFFULL) {n = n + 16; x = x << 16;} if (x <= 0x00FFFFFFFFFFFFFFULL) {n = n + 8; x = x << 8;} if (x <= 0x0FFFFFFFFFFFFFFFULL) {n = n + 4; x = x << 4;} if (x <= 0x3FFFFFFFFFFFFFFFULL) {n = n + 2; x = x << 2;} if (x <= 0x7FFFFFFFFFFFFFFFULL) {n = n + 1;} return n; } // ---------------------------- udivdi3 -------------------------------- /* The variables u0, u1, etc. take on only 32-bit values, but they are declared long long to avoid some compiler warning messages and to avoid some unnecessary EXTRs that the compiler would put in, to convert long longs to ints. First the procedure takes care of the case in which the divisor is a 32-bit quantity. There are two subcases: (1) If the left half of the dividend is less than the divisor, one execution of DIVU is all that is required (overflow is not possible). (2) Otherwise it does two divisions, using the grade school method, with variables used as suggested below. q1 q0 ________ v) u1 u0 q1*v ____ k u0 */ /* These macros must be used with arguments of the appropriate type (unsigned long long for DIVU and long long for DIVS. They are simulations of the presumed machines ops. I.e., they look at only the low-order 32 bits of the divisor, they return garbage if the division overflows, and they return garbage in the high-order half of the quotient doubleword. In practice, these would be replaced with uses of the machine's DIVU and DIVS instructions (e.g., by using the GNU "asm" facility). */ static UInt DIVU ( ULong u, UInt v ) { UInt uHi = (UInt)(u >> 32); UInt uLo = (UInt)u; return divlu2(uHi, uLo, v, NULL); } static Int DIVS ( Long u, Int v ) { Int uHi = (Int)(u >> 32); UInt uLo = (UInt)u; return divls(uHi, uLo, v, NULL); } /* 64 x 64 ==> 64 unsigned division, using only 32 x 32 ==> 32 division as a primitive. */ static ULong udivdi3(ULong u, ULong v) { ULong u0, u1, v1, q0, q1, k, n; if (v >> 32 == 0) { // If v < 2**32: if (u >> 32 < v) // If u/v cannot overflow, return DIVU(u, v) // just do one division. & 0xFFFFFFFF; else { // If u/v would overflow: u1 = u >> 32; // Break u up into two u0 = u & 0xFFFFFFFF; // halves. q1 = DIVU(u1, v) // First quotient digit. & 0xFFFFFFFF; k = u1 - q1*v; // First remainder, < v. q0 = DIVU((k << 32) + u0, v) // 2nd quot. digit. & 0xFFFFFFFF; return (q1 << 32) + q0; } } // Here v >= 2**32. n = nlz64(v); // 0 <= n <= 31. v1 = (v << n) >> 32; // Normalize the divisor // so its MSB is 1. u1 = u >> 1; // To ensure no overflow. q1 = DIVU(u1, v1) // Get quotient from & 0xFFFFFFFF; // divide unsigned insn. q0 = (q1 << n) >> 31; // Undo normalization and // division of u by 2. if (q0 != 0) // Make q0 correct or q0 = q0 - 1; // too small by 1. if ((u - q0*v) >= v) q0 = q0 + 1; // Now q0 is correct. return q0; } // ----------------------------- divdi3 -------------------------------- /* This routine presumes that smallish cases (those which can be done in one execution of DIVS) are common. If this is not the case, the test for this case should be deleted. Note that the test for when DIVS can be used is not entirely accurate. For example, DIVS is not used if v = 0xFFFFFFFF8000000, whereas if could be (if u is sufficiently small in magnitude). */ // ------------------------------ cut ---------------------------------- static ULong my_llabs ( Long x ) { ULong t = x >> 63; return (x ^ t) - t; } /* 64 x 64 ==> 64 signed division, using only 32 x 32 ==> 32 division as a primitive. */ static Long divdi3(Long u, Long v) { ULong au, av; Long q, t; au = my_llabs(u); av = my_llabs(v); if (av >> 31 == 0) { // If |v| < 2**31 and // if (v << 32 >> 32 == v) { // If v is in range and if (au < av << 31) { // |u|/|v| cannot q = DIVS(u, v); // overflow, use DIVS. return (q << 32) >> 32; } } q = udivdi3(au,av); // Invoke udivdi3. t = (u ^ v) >> 63; // If u, v have different return (q ^ t) - t; // signs, negate q. } // ---------------------------- end cut -------------------------------- ULong __udivdi3 (ULong u, ULong v); ULong __udivdi3 (ULong u, ULong v) { return udivdi3(u,v); } Long __divdi3 (Long u, Long v); Long __divdi3 (Long u, Long v) { return divdi3(u,v); } ULong __umoddi3 (ULong u, ULong v); ULong __umoddi3 (ULong u, ULong v) { ULong q = __udivdi3(u, v); ULong r = u - q * v; return r; } Long __moddi3 (Long u, Long v); Long __moddi3 (Long u, Long v) { Long q = __divdi3(u, v); Long r = u - q * v; return r; } /* ------------------------------------------------ ld_classic: Undefined symbols: ___fixunsdfdi ------------------------------------------------ */ /* ===-- fixunsdfdi.c - Implement __fixunsdfdi -----------------------------=== * * The LLVM Compiler Infrastructure * * This file is dual licensed under the MIT and the University of Illinois Open * Source Licenses. See LICENSE.TXT for details. * * ===----------------------------------------------------------------------=== * * This file implements __fixunsdfdi for the compiler_rt library. * * ===----------------------------------------------------------------------=== */ /* As per http://www.gnu.org/licenses/license-list.html#GPLCompatibleLicenses, the "NCSA/University of Illinois Open Source License" is compatible with the GPL (both version 2 and 3). What is claimed to be compatible is this http://www.opensource.org/licenses/UoI-NCSA.php and the LLVM documentation at http://www.llvm.org/docs/DeveloperPolicy.html#license says all the code in LLVM is available under the University of Illinois/NCSA Open Source License, at this URL http://www.opensource.org/licenses/UoI-NCSA.php viz, the same one that the FSF pages claim is compatible. So I think it's OK to include it. */ /* Returns: convert a to a unsigned long long, rounding toward zero. * Negative values all become zero. */ /* Assumption: double is a IEEE 64 bit floating point type * du_int is a 64 bit integral type * value in double is representable in du_int or is negative * (no range checking performed) */ /* seee eeee eeee mmmm mmmm mmmm mmmm mmmm | mmmm mmmm mmmm mmmm mmmm mmmm mmmm mmmm */ typedef unsigned long long du_int; typedef unsigned su_int; typedef union { du_int all; struct { #if VG_LITTLEENDIAN su_int low; su_int high; #else su_int high; su_int low; #endif /* VG_LITTLEENDIAN */ }s; } udwords; typedef union { udwords u; double f; } double_bits; du_int __fixunsdfdi(double a); du_int __fixunsdfdi(double a) { double_bits fb; fb.f = a; int e = ((fb.u.s.high & 0x7FF00000) >> 20) - 1023; if (e < 0 || (fb.u.s.high & 0x80000000)) return 0; udwords r; r.s.high = (fb.u.s.high & 0x000FFFFF) | 0x00100000; r.s.low = fb.u.s.low; if (e > 52) r.all <<= (e - 52); else r.all >>= (52 - e); return r.all; } #endif /*--------------------------------------------------------------------*/ /*--- end ---*/ /*--------------------------------------------------------------------*/ /*--------------------------------------------------------------------*/ /*--- Startup: the real stuff m_main.c ---*/ /*--------------------------------------------------------------------*/ /* This file is part of Valgrind, a dynamic binary instrumentation framework. Copyright (C) 2000-2012 Julian Seward [email protected] This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. The GNU General Public License is contained in the file COPYING. */ #include "pub_core_basics.h" #include "pub_core_vki.h" #include "pub_core_vkiscnums.h" #include "pub_core_libcsetjmp.h" // to keep _threadstate.h happy #include "pub_core_threadstate.h" #include "pub_core_xarray.h" #include "pub_core_clientstate.h" #include "pub_core_aspacemgr.h" #include "pub_core_aspacehl.h" #include "pub_core_commandline.h" #include "pub_core_debuglog.h" #include "pub_core_errormgr.h" #include "pub_core_execontext.h" #include "pub_core_gdbserver.h" #include "pub_core_initimg.h" #include "pub_core_libcbase.h" #include "pub_core_libcassert.h" #include "pub_core_libcfile.h" #include "pub_core_libcprint.h" #include "pub_core_libcproc.h" #include "pub_core_libcsignal.h" #include "pub_core_syscall.h" // VG_(strerror) #include "pub_core_mach.h" #include "pub_core_machine.h" #include "pub_core_mallocfree.h" #include "pub_core_options.h" #include "pub_core_debuginfo.h" #include "pub_core_redir.h" #include "pub_core_scheduler.h" #include "pub_core_seqmatch.h" // For VG_(string_match) #include "pub_core_signals.h" #include "pub_core_stacks.h" // For VG_(register_stack) #include "pub_core_syswrap.h" #include "pub_core_tooliface.h" #include "pub_core_translate.h" // For VG_(translate) #include "pub_core_trampoline.h" #include "pub_core_transtab.h" #include "pub_tool_inner.h" #if defined(ENABLE_INNER_CLIENT_REQUEST) #include "valgrind.h" #endif /*====================================================================*/ /*=== Counters, for profiling purposes only ===*/ /*====================================================================*/ static void print_all_stats ( void ) { VG_(print_translation_stats)(); VG_(print_tt_tc_stats)(); VG_(print_scheduler_stats)(); VG_(print_ExeContext_stats)(); VG_(print_errormgr_stats)(); // Memory stats if (VG_(clo_verbosity) > 2) { VG_(message)(Vg_DebugMsg, "\n"); VG_(message)(Vg_DebugMsg, "------ Valgrind's internal memory use stats follow ------\n" ); VG_(sanity_check_malloc_all)(); VG_(message)(Vg_DebugMsg, "------\n" ); VG_(print_all_arena_stats)(); VG_(message)(Vg_DebugMsg, "\n"); } } /*====================================================================*/ /*=== Command-line: variables, processing, etc ===*/ /*====================================================================*/ // See pub_{core,tool}_options.h for explanations of all these. static void usage_NORETURN ( Bool debug_help ) { /* 'usage1' contains a %s - for the name of the GDB executable - for the name of vgdb's path prefix which must be supplied when they are VG_(printf)'d. */ Char* usage1 = "usage: valgrind [options] prog-and-args\n" "\n" " tool-selection option, with default in [ ]:\n" " --tool=<name> use the Valgrind tool named <name> [memcheck]\n" "\n" " basic user options for all Valgrind tools, with defaults in [ ]:\n" " -h --help show this message\n" " --help-debug show this message, plus debugging options\n" " --version show version\n" " -q --quiet run silently; only print error msgs\n" " -v --verbose be more verbose -- show misc extra info\n" " --trace-children=no|yes Valgrind-ise child processes (follow execve)? [no]\n" " --trace-children-skip=patt1,patt2,... specifies a list of executables\n" " that --trace-children=yes should not trace into\n" " --trace-children-skip-by-arg=patt1,patt2,... same as --trace-children-skip=\n" " but check the argv[] entries for children, rather\n" " than the exe name, to make a follow/no-follow decision\n" " --child-silent-after-fork=no|yes omit child output between fork & exec? [no]\n" " --vgdb=no|yes|full activate gdbserver? [yes]\n" " full is slower but provides precise watchpoint/step\n" " --vgdb-error=<number> invoke gdbserver after <number> errors [%d]\n" " to get started quickly, use --vgdb-error=0\n" " and follow the on-screen directions\n" " --track-fds=no|yes track open file descriptors? [no]\n" " --time-stamp=no|yes add timestamps to log messages? [no]\n" " --log-fd=<number> log messages to file descriptor [2=stderr]\n" " --log-file=<file> log messages to <file>\n" " --log-socket=ipaddr:port log messages to socket ipaddr:port\n" "\n" " user options for Valgrind tools that report errors:\n" " --xml=yes emit error output in XML (some tools only)\n" " --xml-fd=<number> XML output to file descriptor\n" " --xml-file=<file> XML output to <file>\n" " --xml-socket=ipaddr:port XML output to socket ipaddr:port\n" " --xml-user-comment=STR copy STR verbatim into XML output\n" " --demangle=no|yes automatically demangle C++ names? [yes]\n" " --num-callers=<number> show <number> callers in stack traces [12]\n" " --error-limit=no|yes stop showing new errors if too many? [yes]\n" " --error-exitcode=<number> exit code to return if errors found [0=disable]\n" " --show-below-main=no|yes continue stack traces below main() [no]\n" " --suppressions=<filename> suppress errors described in <filename>\n" " --gen-suppressions=no|yes|all print suppressions for errors? [no]\n" " --db-attach=no|yes start debugger when errors detected? [no]\n" " --db-command=<command> command to start debugger [%s -nw %%f %%p]\n" " --input-fd=<number> file descriptor for input [0=stdin]\n" " --dsymutil=no|yes run dsymutil on Mac OS X when helpful? [no]\n" " --max-stackframe=<number> assume stack switch for SP changes larger\n" " than <number> bytes [2000000]\n" " --main-stacksize=<number> set size of main thread's stack (in bytes)\n" " [use current 'ulimit' value]\n" "\n" " user options for Valgrind tools that replace malloc:\n" " --alignment=<number> set minimum alignment of heap allocations [%s]\n" " --redzone-size=<number> set minimum size of redzones added before/after\n" " heap blocks (in bytes). [%s]\n" "\n" " uncommon user options for all Valgrind tools:\n" " --fullpath-after= (with nothing after the '=')\n" " show full source paths in call stacks\n" " --fullpath-after=string like --fullpath-after=, but only show the\n" " part of the path after 'string'. Allows removal\n" " of path prefixes. Use this flag multiple times\n" " to specify a set of prefixes to remove.\n" " --smc-check=none|stack|all|all-non-file [stack]\n" " checks for self-modifying code: none, only for\n" " code found in stacks, for all code, or for all\n" " code except that from file-backed mappings\n" " --read-var-info=yes|no read debug info on stack and global variables\n" " and use it to print better error messages in\n" " tools that make use of it (Memcheck, Helgrind,\n" " DRD) [no]\n" " --vgdb-poll=<number> gdbserver poll max every <number> basic blocks [%d] \n" " --vgdb-shadow-registers=no|yes let gdb see the shadow registers [no]\n" " --vgdb-prefix=<prefix> prefix for vgdb FIFOs [%s]\n" " --run-libc-freeres=no|yes free up glibc memory at exit on Linux? [yes]\n" " --sim-hints=hint1,hint2,... known hints:\n" " lax-ioctls, enable-outer, fuse-compatible [none]\n" " --fair-sched=no|yes|try schedule threads fairly on multicore systems [no]\n" " --kernel-variant=variant1,variant2,... known variants: bproc [none]\n" " handle non-standard kernel variants\n" " --show-emwarns=no|yes show warnings about emulation limits? [no]\n" " --require-text-symbol=:sonamepattern:symbolpattern abort run if the\n" " stated shared object doesn't have the stated\n" " text symbol. Patterns can contain ? and *.\n" " --soname-synonyms=syn1=pattern1,syn2=pattern2,... synonym soname\n" " specify patterns for function wrapping or replacement.\n" " To use a non-libc malloc library that is\n" " in the main exe: --soname-synonyms=somalloc=NONE\n" " in libxyzzy.so: --soname-synonyms=somalloc=libxyzzy.so\n" "\n"; Char* usage2 = "\n" " debugging options for all Valgrind tools:\n" " -d show verbose debugging output\n" " --stats=no|yes show tool and core statistics [no]\n" " --sanity-level=<number> level of sanity checking to do [1]\n" " --trace-flags=<XXXXXXXX> show generated code? (X = 0|1) [00000000]\n" " --profile-flags=<XXXXXXXX> ditto, but for profiling (X = 0|1) [00000000]\n" " --trace-notbelow=<number> only show BBs above <number> [999999999]\n" " --trace-notabove=<number> only show BBs below <number> [0]\n" " --trace-syscalls=no|yes show all system calls? [no]\n" " --trace-signals=no|yes show signal handling details? [no]\n" " --trace-symtab=no|yes show symbol table details? [no]\n" " --trace-symtab-patt=<patt> limit debuginfo tracing to obj name <patt>\n" " --trace-cfi=no|yes show call-frame-info details? [no]\n" " --debug-dump=syms mimic /usr/bin/readelf --syms\n" " --debug-dump=line mimic /usr/bin/readelf --debug-dump=line\n" " --debug-dump=frames mimic /usr/bin/readelf --debug-dump=frames\n" " --trace-redir=no|yes show redirection details? [no]\n" " --trace-sched=no|yes show thread scheduler details? [no]\n" " --profile-heap=no|yes profile Valgrind's own space use\n" " --core-redzone=<number> set minimum size of redzones added before/after\n" " heap blocks allocated for Valgrind internal use (in bytes) [4]\n" " --wait-for-gdb=yes|no pause on startup to wait for gdb attach\n" " --sym-offsets=yes|no show syms in form 'name+offset' ? [no]\n" " --command-line-only=no|yes only use command line options [no]\n" "\n" " Vex options for all Valgrind tools:\n" " --vex-iropt-verbosity=<0..9> [0]\n" " --vex-iropt-level=<0..2> [2]\n" " --vex-iropt-register-updates=unwindregs-at-mem-access\n" " |allregs-at-mem-access\n" " |allregs-at-each-insn [unwindregs-at-mem-access]\n" " --vex-iropt-unroll-thresh=<0..400> [120]\n" " --vex-guest-max-insns=<1..100> [50]\n" " --vex-guest-chase-thresh=<0..99> [10]\n" " --vex-guest-chase-cond=no|yes [no]\n" " --trace-flags and --profile-flags values (omit the middle space):\n" " 1000 0000 show conversion into IR\n" " 0100 0000 show after initial opt\n" " 0010 0000 show after instrumentation\n" " 0001 0000 show after second opt\n" " 0000 1000 show after tree building\n" " 0000 0100 show selecting insns\n" " 0000 0010 show after reg-alloc\n" " 0000 0001 show final assembly\n" " (Nb: you need --trace-notbelow and/or --trace-notabove with --trace-flags for full details)\n" "\n" " debugging options for Valgrind tools that report errors\n" " --dump-error=<number> show translation for basic block associated\n" " with <number>'th error context [0=show none]\n" "\n" " debugging options for Valgrind tools that replace malloc:\n" " --trace-malloc=no|yes show client malloc details? [no]\n" "\n"; Char* usage3 = "\n" " Extra options read from ~/.valgrindrc, $VALGRIND_OPTS, ./.valgrindrc\n" "\n" " %s is %s\n" " Valgrind is Copyright (C) 2000-2012, and GNU GPL'd, by Julian Seward et al.\n" " LibVEX is Copyright (C) 2004-2012, and GNU GPL'd, by OpenWorks LLP et al.\n" "\n" " Bug reports, feedback, admiration, abuse, etc, to: %s.\n" "\n"; Char* gdb_path = GDB_PATH; Char default_alignment[30]; Char default_redzone_size[30]; // Ensure the message goes to stdout VG_(log_output_sink).fd = 1; VG_(log_output_sink).is_socket = False; if (VG_(needs).malloc_replacement) { VG_(sprintf)(default_alignment, "%d", VG_MIN_MALLOC_SZB); VG_(sprintf)(default_redzone_size, "%lu", VG_(tdict).tool_client_redzone_szB); } else { VG_(strcpy)(default_alignment, "not used by this tool"); VG_(strcpy)(default_redzone_size, "not used by this tool"); } /* 'usage1' a type as described after each arg. */ VG_(printf)(usage1, VG_(clo_vgdb_error) /* int */, gdb_path /* char* */, default_alignment /* char* */, default_redzone_size /* char* */, VG_(clo_vgdb_poll) /* int */, VG_(vgdb_prefix_default)() /* char* */ ); if (VG_(details).name) { VG_(printf)(" user options for %s:\n", VG_(details).name); if (VG_(needs).command_line_options) VG_TDICT_CALL(tool_print_usage); else VG_(printf)(" (none)\n"); } if (debug_help) { VG_(printf)("%s", usage2); if (VG_(details).name) { VG_(printf)(" debugging options for %s:\n", VG_(details).name); if (VG_(needs).command_line_options) VG_TDICT_CALL(tool_print_debug_usage); else VG_(printf)(" (none)\n"); } } VG_(printf)(usage3, VG_(details).name, VG_(details).copyright_author, VG_BUGS_TO); VG_(exit)(0); } /* Peer at previously set up VG_(args_for_valgrind) and do some minimal command line processing that must happen early on: - show the version string, if requested (-v) - extract any request for help (--help, -h, --help-debug) - get the toolname (--tool=) - set VG_(clo_max_stackframe) (--max-stackframe=) - set VG_(clo_main_stacksize) (--main-stacksize=) - set VG_(clo_sim_hints) (--sim-hints=) That's all it does. The main command line processing is done below by main_process_cmd_line_options. Note that main_process_cmd_line_options has to handle but ignore the ones we have handled here. */ static void early_process_cmd_line_options ( /*OUT*/Int* need_help, /*OUT*/HChar** tool ) { UInt i; HChar* str; vg_assert( VG_(args_for_valgrind) ); /* parse the options we have (only the options we care about now) */ for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) { str = * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i ); vg_assert(str); // Nb: the version string goes to stdout. if VG_XACT_CLO(str, "--version", VG_(log_output_sink).fd, 1) { VG_(log_output_sink).is_socket = False; VG_(printf)("valgrind-" VERSION "\n"); VG_(exit)(0); } else if VG_XACT_CLO(str, "--help", *need_help, *need_help+1) {} else if VG_XACT_CLO(str, "-h", *need_help, *need_help+1) {} else if VG_XACT_CLO(str, "--help-debug", *need_help, *need_help+2) {} // The tool has already been determined, but we need to know the name // here. else if VG_STR_CLO(str, "--tool", *tool) {} // Set up VG_(clo_max_stackframe) and VG_(clo_main_stacksize). // These are needed by VG_(ii_create_image), which happens // before main_process_cmd_line_options(). else if VG_INT_CLO(str, "--max-stackframe", VG_(clo_max_stackframe)) {} else if VG_INT_CLO(str, "--main-stacksize", VG_(clo_main_stacksize)) {} // Set up VG_(clo_sim_hints). This is needed a.o. for an inner // running in an outer, to have "no-inner-prefix" enabled // as early as possible. else if VG_STR_CLO (str, "--sim-hints", VG_(clo_sim_hints)) {} } } /* The main processing for command line options. See comments above on early_process_cmd_line_options. Comments on how the logging options are handled: User can specify: --log-fd= for a fd to write to (default setting, fd = 2) --log-file= for a file name to write to --log-socket= for a socket to write to As a result of examining these and doing relevant socket/file opening, a final fd is established. This is stored in VG_(log_output_sink) in m_libcprint. Also, if --log-file=STR was specified, then STR, after expansion of %p and %q templates within it, is stored in VG_(clo_log_fname_expanded), in m_options, just in case anybody wants to know what it is. When printing, VG_(log_output_sink) is consulted to find the fd to send output to. Exactly analogous actions are undertaken for the XML output channel, with the one difference that the default fd is -1, meaning the channel is disabled by default. */ static void main_process_cmd_line_options ( /*OUT*/Bool* logging_to_fd, /*OUT*/Char** xml_fname_unexpanded, const HChar* toolname ) { // VG_(clo_log_fd) is used by all the messaging. It starts as 2 (stderr) // and we cannot change it until we know what we are changing it to is // ok. So we have tmp_log_fd to hold the tmp fd prior to that point. SysRes sres; Int i, tmp_log_fd, tmp_xml_fd; Int toolname_len = VG_(strlen)(toolname); Char* tmp_str; // Used in a couple of places. enum { VgLogTo_Fd, VgLogTo_File, VgLogTo_Socket } log_to = VgLogTo_Fd, // Where is logging output to be sent? xml_to = VgLogTo_Fd; // Where is XML output to be sent? /* Temporarily holds the string STR specified with --{log,xml}-{name,socket}=STR. 'fs' stands for file-or-socket. */ Char* log_fsname_unexpanded = NULL; Char* xml_fsname_unexpanded = NULL; /* Log to stderr by default, but usage message goes to stdout. XML output is initially disabled. */ tmp_log_fd = 2; tmp_xml_fd = -1; /* Check for sane path in ./configure --prefix=... */ if (VG_LIBDIR[0] != '/') VG_(err_config_error)("Please use absolute paths in " "./configure --prefix=... or --libdir=...\n"); vg_assert( VG_(args_for_valgrind) ); /* BEGIN command-line processing loop */ for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) { HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i ); HChar* colon = arg; // Look for a colon in the option name. while (*colon && *colon != ':' && *colon != '=') colon++; // Does it have the form "--toolname:foo"? We have to do it at the start // in case someone has combined a prefix with a core-specific option, // eg. "--memcheck:verbose". if (*colon == ':') { if (VG_STREQN(2, arg, "--") && VG_STREQN(toolname_len, arg+2, toolname) && VG_STREQN(1, arg+2+toolname_len, ":")) { // Prefix matches, convert "--toolname:foo" to "--foo". // Two things to note: // - We cannot modify the option in-place. If we did, and then // a child was spawned with --trace-children=yes, the // now-non-prefixed option would be passed and could screw up // the child. // - We create copies, and never free them. Why? Non-prefixed // options hang around forever, so tools need not make copies // of strings within them. We need to have the same behaviour // for prefixed options. The pointer to the copy will be lost // once we leave this function (although a tool may keep a // pointer into it), but the space wasted is insignificant. // (In bug #142197, the copies were being freed, which caused // problems for tools that reasonably assumed that arguments // wouldn't disappear on them.) if (0) VG_(printf)("tool-specific arg: %s\n", arg); arg = VG_(strdup)("main.mpclo.1", arg + toolname_len + 1); arg[0] = '-'; arg[1] = '-'; } else { // prefix doesn't match, skip to next arg continue; } } /* Ignore these options - they've already been handled */ if VG_STREQN( 7, arg, "--tool=") {} else if VG_STREQN(20, arg, "--command-line-only=") {} else if VG_STREQ( arg, "--") {} else if VG_STREQ( arg, "-d") {} else if VG_STREQN(16, arg, "--max-stackframe") {} else if VG_STREQN(16, arg, "--main-stacksize") {} else if VG_STREQN(11, arg, "--sim-hints") {} else if VG_STREQN(14, arg, "--profile-heap") {} else if VG_STREQN(14, arg, "--core-redzone-size") {} else if VG_STREQN(14, arg, "--redzone-size") {} /* Obsolete options. Report an error and exit */ else if VG_STREQN(34, arg, "--vex-iropt-precise-memory-exns=no") { VG_(fmsg_bad_option) (arg, "--vex-iropt-precise-memory-exns is obsolete\n" "Use --vex-iropt-register-updates=unwindregs-at-mem-access instead\n"); } else if VG_STREQN(35, arg, "--vex-iropt-precise-memory-exns=yes") { VG_(fmsg_bad_option) (arg, "--vex-iropt-precise-memory-exns is obsolete\n" "Use --vex-iropt-register-updates=allregs-at-mem-access instead\n" " (or --vex-iropt-register-updates=allregs-at-each-insn)\n"); } // These options are new. else if (VG_STREQ(arg, "-v") || VG_STREQ(arg, "--verbose")) VG_(clo_verbosity)++; else if (VG_STREQ(arg, "-q") || VG_STREQ(arg, "--quiet")) VG_(clo_verbosity)--; else if VG_BOOL_CLO(arg, "--stats", VG_(clo_stats)) {} else if VG_BOOL_CLO(arg, "--xml", VG_(clo_xml)) VG_(debugLog_setXml)(VG_(clo_xml)); else if VG_XACT_CLO(arg, "--vgdb=no", VG_(clo_vgdb), Vg_VgdbNo) {} else if VG_XACT_CLO(arg, "--vgdb=yes", VG_(clo_vgdb), Vg_VgdbYes) {} else if VG_XACT_CLO(arg, "--vgdb=full", VG_(clo_vgdb), Vg_VgdbFull) { /* automatically updates register values at each insn with --vgdb=full */ VG_(clo_vex_control).iropt_register_updates = VexRegUpdAllregsAtEachInsn; } else if VG_INT_CLO (arg, "--vgdb-poll", VG_(clo_vgdb_poll)) {} else if VG_INT_CLO (arg, "--vgdb-error", VG_(clo_vgdb_error)) {} else if VG_STR_CLO (arg, "--vgdb-prefix", VG_(clo_vgdb_prefix)) {} else if VG_BOOL_CLO(arg, "--vgdb-shadow-registers", VG_(clo_vgdb_shadow_registers)) {} else if VG_BOOL_CLO(arg, "--db-attach", VG_(clo_db_attach)) {} else if VG_BOOL_CLO(arg, "--demangle", VG_(clo_demangle)) {} else if VG_STR_CLO (arg, "--soname-synonyms",VG_(clo_soname_synonyms)) {} else if VG_BOOL_CLO(arg, "--error-limit", VG_(clo_error_limit)) {} else if VG_INT_CLO (arg, "--error-exitcode", VG_(clo_error_exitcode)) {} else if VG_BOOL_CLO(arg, "--show-emwarns", VG_(clo_show_emwarns)) {} else if VG_BOOL_CLO(arg, "--run-libc-freeres", VG_(clo_run_libc_freeres)) {} else if VG_BOOL_CLO(arg, "--show-below-main", VG_(clo_show_below_main)) {} else if VG_BOOL_CLO(arg, "--time-stamp", VG_(clo_time_stamp)) {} else if VG_BOOL_CLO(arg, "--track-fds", VG_(clo_track_fds)) {} else if VG_BOOL_CLO(arg, "--trace-children", VG_(clo_trace_children)) {} else if VG_BOOL_CLO(arg, "--child-silent-after-fork", VG_(clo_child_silent_after_fork)) {} else if VG_STR_CLO(arg, "--fair-sched", tmp_str) { if (VG_(strcmp)(tmp_str, "yes") == 0) VG_(clo_fair_sched) = enable_fair_sched; else if (VG_(strcmp)(tmp_str, "try") == 0) VG_(clo_fair_sched) = try_fair_sched; else if (VG_(strcmp)(tmp_str, "no") == 0) VG_(clo_fair_sched) = disable_fair_sched; else VG_(fmsg_bad_option)(arg, ""); } else if VG_BOOL_CLO(arg, "--trace-sched", VG_(clo_trace_sched)) {} else if VG_BOOL_CLO(arg, "--trace-signals", VG_(clo_trace_signals)) {} else if VG_BOOL_CLO(arg, "--trace-symtab", VG_(clo_trace_symtab)) {} else if VG_STR_CLO (arg, "--trace-symtab-patt", VG_(clo_trace_symtab_patt)) {} else if VG_BOOL_CLO(arg, "--trace-cfi", VG_(clo_trace_cfi)) {} else if VG_XACT_CLO(arg, "--debug-dump=syms", VG_(clo_debug_dump_syms), True) {} else if VG_XACT_CLO(arg, "--debug-dump=line", VG_(clo_debug_dump_line), True) {} else if VG_XACT_CLO(arg, "--debug-dump=frames", VG_(clo_debug_dump_frames), True) {} else if VG_BOOL_CLO(arg, "--trace-redir", VG_(clo_trace_redir)) {} else if VG_BOOL_CLO(arg, "--trace-syscalls", VG_(clo_trace_syscalls)) {} else if VG_BOOL_CLO(arg, "--wait-for-gdb", VG_(clo_wait_for_gdb)) {} else if VG_STR_CLO (arg, "--db-command", VG_(clo_db_command)) {} else if VG_BOOL_CLO(arg, "--sym-offsets", VG_(clo_sym_offsets)) {} else if VG_BOOL_CLO(arg, "--read-var-info", VG_(clo_read_var_info)) {} else if VG_INT_CLO (arg, "--dump-error", VG_(clo_dump_error)) {} else if VG_INT_CLO (arg, "--input-fd", VG_(clo_input_fd)) {} else if VG_INT_CLO (arg, "--sanity-level", VG_(clo_sanity_level)) {} else if VG_BINT_CLO(arg, "--num-callers", VG_(clo_backtrace_size), 1, VG_DEEPEST_BACKTRACE) {} else if VG_XACT_CLO(arg, "--smc-check=none", VG_(clo_smc_check), Vg_SmcNone); else if VG_XACT_CLO(arg, "--smc-check=stack", VG_(clo_smc_check), Vg_SmcStack); else if VG_XACT_CLO(arg, "--smc-check=all", VG_(clo_smc_check), Vg_SmcAll); else if VG_XACT_CLO(arg, "--smc-check=all-non-file", VG_(clo_smc_check), Vg_SmcAllNonFile); else if VG_STR_CLO (arg, "--kernel-variant", VG_(clo_kernel_variant)) {} else if VG_BOOL_CLO(arg, "--dsymutil", VG_(clo_dsymutil)) {} else if VG_STR_CLO (arg, "--trace-children-skip", VG_(clo_trace_children_skip)) {} else if VG_STR_CLO (arg, "--trace-children-skip-by-arg", VG_(clo_trace_children_skip_by_arg)) {} else if VG_BINT_CLO(arg, "--vex-iropt-verbosity", VG_(clo_vex_control).iropt_verbosity, 0, 10) {} else if VG_BINT_CLO(arg, "--vex-iropt-level", VG_(clo_vex_control).iropt_level, 0, 2) {} else if VG_XACT_CLO(arg, "--vex-iropt-register-updates=unwindregs-at-mem-access", VG_(clo_vex_control).iropt_register_updates, VexRegUpdUnwindregsAtMemAccess); else if VG_XACT_CLO(arg, "--vex-iropt-register-updates=allregs-at-mem-access", VG_(clo_vex_control).iropt_register_updates, VexRegUpdAllregsAtMemAccess); else if VG_XACT_CLO(arg, "--vex-iropt-register-updates=allregs-at-each-insn", VG_(clo_vex_control).iropt_register_updates, VexRegUpdAllregsAtEachInsn); else if VG_BINT_CLO(arg, "--vex-iropt-unroll-thresh", VG_(clo_vex_control).iropt_unroll_thresh, 0, 400) {} else if VG_BINT_CLO(arg, "--vex-guest-max-insns", VG_(clo_vex_control).guest_max_insns, 1, 100) {} else if VG_BINT_CLO(arg, "--vex-guest-chase-thresh", VG_(clo_vex_control).guest_chase_thresh, 0, 99) {} else if VG_BOOL_CLO(arg, "--vex-guest-chase-cond", VG_(clo_vex_control).guest_chase_cond) {} else if VG_INT_CLO(arg, "--log-fd", tmp_log_fd) { log_to = VgLogTo_Fd; log_fsname_unexpanded = NULL; } else if VG_INT_CLO(arg, "--xml-fd", tmp_xml_fd) { xml_to = VgLogTo_Fd; xml_fsname_unexpanded = NULL; } else if VG_STR_CLO(arg, "--log-file", log_fsname_unexpanded) { log_to = VgLogTo_File; } else if VG_STR_CLO(arg, "--xml-file", xml_fsname_unexpanded) { xml_to = VgLogTo_File; } else if VG_STR_CLO(arg, "--log-socket", log_fsname_unexpanded) { log_to = VgLogTo_Socket; } else if VG_STR_CLO(arg, "--xml-socket", xml_fsname_unexpanded) { xml_to = VgLogTo_Socket; } else if VG_STR_CLO(arg, "--xml-user-comment", VG_(clo_xml_user_comment)) {} else if VG_STR_CLO(arg, "--suppressions", tmp_str) { if (VG_(clo_n_suppressions) >= VG_CLO_MAX_SFILES) { VG_(fmsg_bad_option)(arg, "Too many suppression files specified.\n" "Increase VG_CLO_MAX_SFILES and recompile.\n"); } VG_(clo_suppressions)[VG_(clo_n_suppressions)] = tmp_str; VG_(clo_n_suppressions)++; } else if VG_STR_CLO (arg, "--fullpath-after", tmp_str) { if (VG_(clo_n_fullpath_after) >= VG_CLO_MAX_FULLPATH_AFTER) { VG_(fmsg_bad_option)(arg, "Too many --fullpath-after= specifications.\n" "Increase VG_CLO_MAX_FULLPATH_AFTER and recompile.\n"); } VG_(clo_fullpath_after)[VG_(clo_n_fullpath_after)] = tmp_str; VG_(clo_n_fullpath_after)++; } else if VG_STR_CLO(arg, "--require-text-symbol", tmp_str) { if (VG_(clo_n_req_tsyms) >= VG_CLO_MAX_REQ_TSYMS) { VG_(fmsg_bad_option)(arg, "Too many --require-text-symbol= specifications.\n" "Increase VG_CLO_MAX_REQ_TSYMS and recompile.\n"); } /* String needs to be of the form C?*C?*, where C is any character, but is the same both times. Having it in this form facilitates finding the boundary between the sopatt and the fnpatt just by looking for the second occurrence of C, without hardwiring any assumption about what C is. */ Char patt[7]; Bool ok = True; ok = tmp_str && VG_(strlen)(tmp_str) > 0; if (ok) { patt[0] = patt[3] = tmp_str[0]; patt[1] = patt[4] = '?'; patt[2] = patt[5] = '*'; patt[6] = 0; ok = VG_(string_match)(patt, tmp_str); } if (!ok) { VG_(fmsg_bad_option)(arg, "Invalid --require-text-symbol= specification.\n"); } VG_(clo_req_tsyms)[VG_(clo_n_req_tsyms)] = tmp_str; VG_(clo_n_req_tsyms)++; } /* "stuvwxyz" --> stuvwxyz (binary) */ else if VG_STR_CLO(arg, "--trace-flags", tmp_str) { Int j; if (8 != VG_(strlen)(tmp_str)) { VG_(fmsg_bad_option)(arg, "--trace-flags argument must have 8 digits\n"); } for (j = 0; j < 8; j++) { if ('0' == tmp_str[j]) { /* do nothing */ } else if ('1' == tmp_str[j]) VG_(clo_trace_flags) |= (1 << (7-j)); else { VG_(fmsg_bad_option)(arg, "--trace-flags argument can only contain 0s and 1s\n"); } } } /* "stuvwxyz" --> stuvwxyz (binary) */ else if VG_STR_CLO(arg, "--profile-flags", tmp_str) { Int j; if (8 != VG_(strlen)(tmp_str)) { VG_(fmsg_bad_option)(arg, "--profile-flags argument must have 8 digits\n"); } for (j = 0; j < 8; j++) { if ('0' == tmp_str[j]) { /* do nothing */ } else if ('1' == tmp_str[j]) VG_(clo_profile_flags) |= (1 << (7-j)); else { VG_(fmsg_bad_option)(arg, "--profile-flags argument can only contain 0s and 1s\n"); } } } else if VG_INT_CLO (arg, "--trace-notbelow", VG_(clo_trace_notbelow)) {} else if VG_INT_CLO (arg, "--trace-notabove", VG_(clo_trace_notabove)) {} else if VG_XACT_CLO(arg, "--gen-suppressions=no", VG_(clo_gen_suppressions), 0) {} else if VG_XACT_CLO(arg, "--gen-suppressions=yes", VG_(clo_gen_suppressions), 1) {} else if VG_XACT_CLO(arg, "--gen-suppressions=all", VG_(clo_gen_suppressions), 2) {} else if ( ! VG_(needs).command_line_options || ! VG_TDICT_CALL(tool_process_cmd_line_option, arg) ) { VG_(fmsg_bad_option)(arg, ""); } } /* END command-line processing loop */ /* Determine the path prefix for vgdb */ if (VG_(clo_vgdb_prefix) == NULL) VG_(clo_vgdb_prefix) = VG_(vgdb_prefix_default)(); /* Make VEX control parameters sane */ if (VG_(clo_vex_control).guest_chase_thresh >= VG_(clo_vex_control).guest_max_insns) VG_(clo_vex_control).guest_chase_thresh = VG_(clo_vex_control).guest_max_insns - 1; if (VG_(clo_vex_control).guest_chase_thresh < 0) VG_(clo_vex_control).guest_chase_thresh = 0; /* Check various option values */ if (VG_(clo_verbosity) < 0) VG_(clo_verbosity) = 0; if (VG_(clo_trace_notbelow) == -1) { if (VG_(clo_trace_notabove) == -1) { /* [] */ VG_(clo_trace_notbelow) = 2147483647; VG_(clo_trace_notabove) = 0; } else { /* [0 .. notabove] */ VG_(clo_trace_notbelow) = 0; } } else { if (VG_(clo_trace_notabove) == -1) { /* [notbelow .. ] */ VG_(clo_trace_notabove) = 2147483647; } else { /* [notbelow .. notabove] */ } } VG_(dyn_vgdb_error) = VG_(clo_vgdb_error); if (VG_(clo_gen_suppressions) > 0 && !VG_(needs).core_errors && !VG_(needs).tool_errors) { VG_(fmsg_bad_option)("--gen-suppressions=yes", "Can't use --gen-suppressions= with %s\n" "because it doesn't generate errors.\n", VG_(details).name); } /* If XML output is requested, check that the tool actually supports it. */ if (VG_(clo_xml) && !VG_(needs).xml_output) { VG_(clo_xml) = False; VG_(fmsg_bad_option)("--xml=yes", "%s does not support XML output.\n", VG_(details).name); /*NOTREACHED*/ } vg_assert( VG_(clo_gen_suppressions) >= 0 ); vg_assert( VG_(clo_gen_suppressions) <= 2 ); /* If we've been asked to emit XML, mash around various other options so as to constrain the output somewhat, and to remove any need for user input during the run. */ if (VG_(clo_xml)) { /* We can't allow --gen-suppressions=yes, since that requires us to print the error and then ask the user if she wants a suppression for it, but in XML mode we won't print it until we know whether we also need to print a suppression. Hence a circular dependency. So disallow this. (--gen-suppressions=all is still OK since we don't need any user interaction in this case.) */ if (VG_(clo_gen_suppressions) == 1) { VG_(fmsg_bad_option)( "--xml=yes together with --gen-suppressions=yes", "When --xml=yes is specified, --gen-suppressions=no\n" "or --gen-suppressions=all is allowed, but not " "--gen-suppressions=yes.\n"); } /* We can't allow DB attaching (or we maybe could, but results could be chaotic ..) since it requires user input. Hence disallow. */ if (VG_(clo_db_attach)) { VG_(fmsg_bad_option)( "--xml=yes together with --db-attach=yes", "--db-attach=yes is not allowed with --xml=yes\n" "because it would require user input.\n"); } /* Disallow dump_error in XML mode; sounds like a recipe for chaos. No big deal; dump_error is a flag for debugging V itself. */ if (VG_(clo_dump_error) > 0) { VG_(fmsg_bad_option)("--xml=yes together with --dump-error", ""); } /* Disable error limits (this might be a bad idea!) */ VG_(clo_error_limit) = False; /* Disable emulation warnings */ /* Also, we want to set options for the leak checker, but that will have to be done in Memcheck's flag-handling code, not here. */ } /* All non-logging-related options have been checked. If the logging option specified is ok, we can switch to it, as we know we won't have to generate any other command-line-related error messages. (So far we should be still attached to stderr, so we can show on the terminal any problems to do with processing command line opts.) So set up logging now. After this is done, VG_(log_output_sink) and (if relevant) VG_(xml_output_sink) should be connected to whatever sink has been selected, and we indiscriminately chuck stuff into it without worrying what the nature of it is. Oh the wonder of Unix streams. */ vg_assert(VG_(log_output_sink).fd == 2 /* stderr */); vg_assert(VG_(log_output_sink).is_socket == False); vg_assert(VG_(clo_log_fname_expanded) == NULL); vg_assert(VG_(xml_output_sink).fd == -1 /* disabled */); vg_assert(VG_(xml_output_sink).is_socket == False); vg_assert(VG_(clo_xml_fname_expanded) == NULL); /* --- set up the normal text output channel --- */ switch (log_to) { case VgLogTo_Fd: vg_assert(log_fsname_unexpanded == NULL); break; case VgLogTo_File: { Char* logfilename; vg_assert(log_fsname_unexpanded != NULL); vg_assert(VG_(strlen)(log_fsname_unexpanded) <= 900); /* paranoia */ // Nb: we overwrite an existing file of this name without asking // any questions. logfilename = VG_(expand_file_name)("--log-file", log_fsname_unexpanded); sres = VG_(open)(logfilename, VKI_O_CREAT|VKI_O_WRONLY|VKI_O_TRUNC, VKI_S_IRUSR|VKI_S_IWUSR); if (!sr_isError(sres)) { tmp_log_fd = sr_Res(sres); VG_(clo_log_fname_expanded) = logfilename; } else { VG_(fmsg)("can't create log file '%s': %s\n", logfilename, VG_(strerror)(sr_Err(sres))); VG_(exit)(1); /*NOTREACHED*/ } break; } case VgLogTo_Socket: { vg_assert(log_fsname_unexpanded != NULL); vg_assert(VG_(strlen)(log_fsname_unexpanded) <= 900); /* paranoia */ tmp_log_fd = VG_(connect_via_socket)( log_fsname_unexpanded ); if (tmp_log_fd == -1) { VG_(fmsg)("Invalid --log-socket spec of '%s'\n", log_fsname_unexpanded); VG_(exit)(1); /*NOTREACHED*/ } if (tmp_log_fd == -2) { VG_(umsg)("failed to connect to logging server '%s'.\n" "Log messages will sent to stderr instead.\n", log_fsname_unexpanded ); /* We don't change anything here. */ vg_assert(VG_(log_output_sink).fd == 2); tmp_log_fd = 2; } else { vg_assert(tmp_log_fd > 0); VG_(log_output_sink).is_socket = True; } break; } } /* --- set up the XML output channel --- */ switch (xml_to) { case VgLogTo_Fd: vg_assert(xml_fsname_unexpanded == NULL); break; case VgLogTo_File: { Char* xmlfilename; vg_assert(xml_fsname_unexpanded != NULL); vg_assert(VG_(strlen)(xml_fsname_unexpanded) <= 900); /* paranoia */ // Nb: we overwrite an existing file of this name without asking // any questions. xmlfilename = VG_(expand_file_name)("--xml-file", xml_fsname_unexpanded); sres = VG_(open)(xmlfilename, VKI_O_CREAT|VKI_O_WRONLY|VKI_O_TRUNC, VKI_S_IRUSR|VKI_S_IWUSR); if (!sr_isError(sres)) { tmp_xml_fd = sr_Res(sres); VG_(clo_xml_fname_expanded) = xmlfilename; /* strdup here is probably paranoid overkill, but ... */ *xml_fname_unexpanded = VG_(strdup)( "main.mpclo.2", xml_fsname_unexpanded ); } else { VG_(fmsg)("can't create XML file '%s': %s\n", xmlfilename, VG_(strerror)(sr_Err(sres))); VG_(exit)(1); /*NOTREACHED*/ } break; } case VgLogTo_Socket: { vg_assert(xml_fsname_unexpanded != NULL); vg_assert(VG_(strlen)(xml_fsname_unexpanded) <= 900); /* paranoia */ tmp_xml_fd = VG_(connect_via_socket)( xml_fsname_unexpanded ); if (tmp_xml_fd == -1) { VG_(fmsg)("Invalid --xml-socket spec of '%s'\n", xml_fsname_unexpanded ); VG_(exit)(1); /*NOTREACHED*/ } if (tmp_xml_fd == -2) { VG_(umsg)("failed to connect to XML logging server '%s'.\n" "XML output will sent to stderr instead.\n", xml_fsname_unexpanded); /* We don't change anything here. */ vg_assert(VG_(xml_output_sink).fd == 2); tmp_xml_fd = 2; } else { vg_assert(tmp_xml_fd > 0); VG_(xml_output_sink).is_socket = True; } break; } } /* If we've got this far, and XML mode was requested, but no XML output channel appears to have been specified, just stop. We could continue, and XML output will simply vanish into nowhere, but that is likely to confuse the hell out of users, which is distinctly Ungood. */ if (VG_(clo_xml) && tmp_xml_fd == -1) { VG_(fmsg_bad_option)( "--xml=yes, but no XML destination specified", "--xml=yes has been specified, but there is no XML output\n" "destination. You must specify an XML output destination\n" "using --xml-fd, --xml-file or --xml-socket.\n" ); } // Finalise the output fds: the log fd .. if (tmp_log_fd >= 0) { // Move log_fd into the safe range, so it doesn't conflict with // any app fds. tmp_log_fd = VG_(fcntl)(tmp_log_fd, VKI_F_DUPFD, VG_(fd_hard_limit)); if (tmp_log_fd < 0) { VG_(message)(Vg_UserMsg, "valgrind: failed to move logfile fd " "into safe range, using stderr\n"); VG_(log_output_sink).fd = 2; // stderr VG_(log_output_sink).is_socket = False; } else { VG_(log_output_sink).fd = tmp_log_fd; VG_(fcntl)(VG_(log_output_sink).fd, VKI_F_SETFD, VKI_FD_CLOEXEC); } } else { // If they said --log-fd=-1, don't print anything. Plausible for use in // regression testing suites that use client requests to count errors. VG_(log_output_sink).fd = -1; VG_(log_output_sink).is_socket = False; } // Finalise the output fds: and the XML fd .. if (tmp_xml_fd >= 0) { // Move xml_fd into the safe range, so it doesn't conflict with // any app fds. tmp_xml_fd = VG_(fcntl)(tmp_xml_fd, VKI_F_DUPFD, VG_(fd_hard_limit)); if (tmp_xml_fd < 0) { VG_(message)(Vg_UserMsg, "valgrind: failed to move XML file fd " "into safe range, using stderr\n"); VG_(xml_output_sink).fd = 2; // stderr VG_(xml_output_sink).is_socket = False; } else { VG_(xml_output_sink).fd = tmp_xml_fd; VG_(fcntl)(VG_(xml_output_sink).fd, VKI_F_SETFD, VKI_FD_CLOEXEC); } } else { // If they said --xml-fd=-1, don't print anything. Plausible for use in // regression testing suites that use client requests to count errors. VG_(xml_output_sink).fd = -1; VG_(xml_output_sink).is_socket = False; } // Suppressions related stuff if (VG_(clo_n_suppressions) < VG_CLO_MAX_SFILES-1 && (VG_(needs).core_errors || VG_(needs).tool_errors)) { /* If we haven't reached the max number of suppressions, load the default one. */ static const Char default_supp[] = "default.supp"; Int len = VG_(strlen)(VG_(libdir)) + 1 + sizeof(default_supp); Char *buf = VG_(arena_malloc)(VG_AR_CORE, "main.mpclo.3", len); VG_(sprintf)(buf, "%s/%s", VG_(libdir), default_supp); VG_(clo_suppressions)[VG_(clo_n_suppressions)] = buf; VG_(clo_n_suppressions)++; } *logging_to_fd = log_to == VgLogTo_Fd || log_to == VgLogTo_Socket; } // Write the name and value of log file qualifiers to the xml file. static void print_file_vars(Char* format) { Int i = 0; while (format[i]) { if (format[i] == '%') { // We saw a '%'. What's next... i++; if ('q' == format[i]) { i++; if ('{' == format[i]) { // Get the env var name, print its contents. Char* qualname; Char* qual; i++; qualname = &format[i]; while (True) { if ('}' == format[i]) { // Temporarily replace the '}' with NUL to extract var // name. format[i] = 0; qual = VG_(getenv)(qualname); break; } i++; } VG_(printf_xml)( "<logfilequalifier> <var>%pS</var> " "<value>%pS</value> </logfilequalifier>\n", qualname,qual ); format[i] = '}'; i++; } } } else { i++; } } } /*====================================================================*/ /*=== Printing the preamble ===*/ /*====================================================================*/ // Print the argument, escaping any chars that require it. static void umsg_arg(const Char* arg) { SizeT len = VG_(strlen)(arg); Char* special = " \\<>"; Int i; for (i = 0; i < len; i++) { if (VG_(strchr)(special, arg[i])) { VG_(umsg)("\\"); // escape with a backslash if necessary } VG_(umsg)("%c", arg[i]); } } // Send output to the XML-stream and escape any XML meta-characters. static void xml_arg(const Char* arg) { VG_(printf_xml)("%pS", arg); } /* Ok, the logging sink is running now. Print a suitable preamble. If logging to file or a socket, write details of parent PID and command line args, to help people trying to interpret the results of a run which encompasses multiple processes. */ static void print_preamble ( Bool logging_to_fd, Char* xml_fname_unexpanded, const HChar* toolname ) { Int i; HChar* xpre = VG_(clo_xml) ? " <line>" : ""; HChar* xpost = VG_(clo_xml) ? "</line>" : ""; UInt (*umsg_or_xml)( const HChar*, ... ) = VG_(clo_xml) ? VG_(printf_xml) : VG_(umsg); void (*umsg_or_xml_arg)( const Char* ) = VG_(clo_xml) ? xml_arg : umsg_arg; vg_assert( VG_(args_for_client) ); vg_assert( VG_(args_for_valgrind) ); vg_assert( toolname ); if (VG_(clo_xml)) { VG_(printf_xml)("<?xml version=\"1.0\"?>\n"); VG_(printf_xml)("\n"); VG_(printf_xml)("<valgrindoutput>\n"); VG_(printf_xml)("\n"); VG_(printf_xml)("<protocolversion>4</protocolversion>\n"); VG_(printf_xml)("<protocoltool>%s</protocoltool>\n", toolname); VG_(printf_xml)("\n"); } if (VG_(clo_xml) || VG_(clo_verbosity > 0)) { if (VG_(clo_xml)) VG_(printf_xml)("<preamble>\n"); /* Tool details */ umsg_or_xml( VG_(clo_xml) ? "%s%pS%pS%pS, %pS%s\n" : "%s%s%s%s, %s%s\n", xpre, VG_(details).name, NULL == VG_(details).version ? "" : "-", NULL == VG_(details).version ? (Char*)"" : VG_(details).version, VG_(details).description, xpost ); if (VG_(strlen)(toolname) >= 4 && VG_STREQN(4, toolname, "exp-")) { umsg_or_xml( "%sNOTE: This is an Experimental-Class Valgrind Tool%s\n", xpre, xpost ); } umsg_or_xml( VG_(clo_xml) ? "%s%pS%s\n" : "%s%s%s\n", xpre, VG_(details).copyright_author, xpost ); /* Core details */ umsg_or_xml( "%sUsing Valgrind-%s and LibVEX; rerun with -h for copyright info%s\n", xpre, VERSION, xpost ); // Print the command line. At one point we wrapped at 80 chars and // printed a '\' as a line joiner, but that makes it hard to cut and // paste the command line (because of the "==pid==" prefixes), so we now // favour utility and simplicity over aesthetics. umsg_or_xml("%sCommand: ", xpre); if (VG_(args_the_exename)) umsg_or_xml_arg(VG_(args_the_exename)); for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) { HChar* s = *(HChar**)VG_(indexXA)( VG_(args_for_client), i ); umsg_or_xml(" "); umsg_or_xml_arg(s); } umsg_or_xml("%s\n", xpost); if (VG_(clo_xml)) VG_(printf_xml)("</preamble>\n"); } // Print the parent PID, and other stuff, if necessary. if (!VG_(clo_xml) && VG_(clo_verbosity) > 0 && !logging_to_fd) { VG_(umsg)("Parent PID: %d\n", VG_(getppid)()); } else if (VG_(clo_xml)) { VG_(printf_xml)("\n"); VG_(printf_xml)("<pid>%d</pid>\n", VG_(getpid)()); VG_(printf_xml)("<ppid>%d</ppid>\n", VG_(getppid)()); VG_(printf_xml)("<tool>%pS</tool>\n", toolname); if (xml_fname_unexpanded) print_file_vars(xml_fname_unexpanded); if (VG_(clo_xml_user_comment)) { /* Note: the user comment itself is XML and is therefore to be passed through verbatim (%s) rather than escaped (%pS). */ VG_(printf_xml)("<usercomment>%s</usercomment>\n", VG_(clo_xml_user_comment)); } VG_(printf_xml)("\n"); VG_(printf_xml)("<args>\n"); VG_(printf_xml)(" <vargv>\n"); if (VG_(name_of_launcher)) VG_(printf_xml)(" <exe>%pS</exe>\n", VG_(name_of_launcher)); else VG_(printf_xml)(" <exe>%pS</exe>\n", "(launcher name unknown)"); for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) { VG_(printf_xml)( " <arg>%pS</arg>\n", * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i ) ); } VG_(printf_xml)(" </vargv>\n"); VG_(printf_xml)(" <argv>\n"); if (VG_(args_the_exename)) VG_(printf_xml)(" <exe>%pS</exe>\n", VG_(args_the_exename)); for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) { VG_(printf_xml)( " <arg>%pS</arg>\n", * (HChar**) VG_(indexXA)( VG_(args_for_client), i ) ); } VG_(printf_xml)(" </argv>\n"); VG_(printf_xml)("</args>\n"); } // Last thing in the preamble is a blank line. if (VG_(clo_xml)) VG_(printf_xml)("\n"); else if (VG_(clo_verbosity) > 0) VG_(umsg)("\n"); # if defined(VGO_darwin) && DARWIN_VERS == DARWIN_10_8 /* Uh, this doesn't play nice with XML output. */ umsg_or_xml( "WARNING: Support on MacOS 10.8 is experimental and mostly broken.\n"); umsg_or_xml( "WARNING: Expect incorrect results, assertions and crashes.\n"); umsg_or_xml( "WARNING: In particular, Memcheck on 32-bit programs will fail to\n"); umsg_or_xml( "WARNING: detect any errors associated with heap-allocated data.\n"); umsg_or_xml( "\n" ); # endif if (VG_(clo_verbosity) > 1) { SysRes fd; VexArch vex_arch; VexArchInfo vex_archinfo; if (!logging_to_fd) VG_(message)(Vg_DebugMsg, "\n"); VG_(message)(Vg_DebugMsg, "Valgrind options:\n"); for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) { VG_(message)(Vg_DebugMsg, " %s\n", * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i )); } VG_(message)(Vg_DebugMsg, "Contents of /proc/version:\n"); fd = VG_(open) ( "/proc/version", VKI_O_RDONLY, 0 ); if (sr_isError(fd)) { VG_(message)(Vg_DebugMsg, " can't open /proc/version\n"); } else { # define BUF_LEN 256 Char version_buf[BUF_LEN]; Int n = VG_(read) ( sr_Res(fd), version_buf, BUF_LEN ); vg_assert(n <= BUF_LEN); if (n > 0) { version_buf[n-1] = '\0'; VG_(message)(Vg_DebugMsg, " %s\n", version_buf); } else { VG_(message)(Vg_DebugMsg, " (empty?)\n"); } VG_(close)(sr_Res(fd)); # undef BUF_LEN } VG_(machine_get_VexArchInfo)( &vex_arch, &vex_archinfo ); VG_(message)( Vg_DebugMsg, "Arch and hwcaps: %s, %s\n", LibVEX_ppVexArch ( vex_arch ), LibVEX_ppVexHwCaps ( vex_arch, vex_archinfo.hwcaps ) ); VG_(message)( Vg_DebugMsg, "Page sizes: currently %d, max supported %d\n", (Int)VKI_PAGE_SIZE, (Int)VKI_MAX_PAGE_SIZE ); VG_(message)(Vg_DebugMsg, "Valgrind library directory: %s\n", VG_(libdir)); } } /*====================================================================*/ /*=== File descriptor setup ===*/ /*====================================================================*/ /* Number of file descriptors that Valgrind tries to reserve for it's own use - just a small constant. */ #define N_RESERVED_FDS (10) static void setup_file_descriptors(void) { struct vki_rlimit rl; Bool show = False; /* Get the current file descriptor limits. */ if (VG_(getrlimit)(VKI_RLIMIT_NOFILE, &rl) < 0) { rl.rlim_cur = 1024; rl.rlim_max = 1024; } # if defined(VGO_darwin) /* Darwin lies. It reports file max as RLIM_INFINITY but silently disallows anything bigger than 10240. */ if (rl.rlim_cur >= 10240 && rl.rlim_max == 0x7fffffffffffffffULL) { rl.rlim_max = 10240; } # endif if (show) VG_(printf)("fd limits: host, before: cur %lu max %lu\n", (UWord)rl.rlim_cur, (UWord)rl.rlim_max); /* Work out where to move the soft limit to. */ if (rl.rlim_cur + N_RESERVED_FDS <= rl.rlim_max) { rl.rlim_cur = rl.rlim_cur + N_RESERVED_FDS; } else { rl.rlim_cur = rl.rlim_max; } /* Reserve some file descriptors for our use. */ VG_(fd_soft_limit) = rl.rlim_cur - N_RESERVED_FDS; VG_(fd_hard_limit) = rl.rlim_cur - N_RESERVED_FDS; /* Update the soft limit. */ VG_(setrlimit)(VKI_RLIMIT_NOFILE, &rl); if (show) { VG_(printf)("fd limits: host, after: cur %lu max %lu\n", (UWord)rl.rlim_cur, (UWord)rl.rlim_max); VG_(printf)("fd limits: guest : cur %u max %u\n", VG_(fd_soft_limit), VG_(fd_hard_limit)); } if (VG_(cl_exec_fd) != -1) VG_(cl_exec_fd) = VG_(safe_fd)( VG_(cl_exec_fd) ); } /*====================================================================*/ /*=== BB profiling ===*/ /*====================================================================*/ static void show_BB_profile ( BBProfEntry tops[], UInt n_tops, ULong score_total ) { ULong score_cumul, score_here; Char buf_cumul[10], buf_here[10]; Char name[64]; Int r; VG_(printf)("\n"); VG_(printf)("-----------------------------------------------------------\n"); VG_(printf)("--- BEGIN BB Profile (summary of scores) ---\n"); VG_(printf)("-----------------------------------------------------------\n"); VG_(printf)("\n"); VG_(printf)("Total score = %lld\n\n", score_total); score_cumul = 0; for (r = 0; r < n_tops; r++) { if (tops[r].addr == 0) continue; name[0] = 0; VG_(get_fnname_w_offset)(tops[r].addr, name, 64); name[63] = 0; score_here = tops[r].score; score_cumul += score_here; VG_(percentify)(score_cumul, score_total, 2, 6, buf_cumul); VG_(percentify)(score_here, score_total, 2, 6, buf_here); VG_(printf)("%3d: (%9lld %s) %9lld %s 0x%llx %s\n", r, score_cumul, buf_cumul, score_here, buf_here, tops[r].addr, name ); } VG_(printf)("\n"); VG_(printf)("-----------------------------------------------------------\n"); VG_(printf)("--- BB Profile (BB details) ---\n"); VG_(printf)("-----------------------------------------------------------\n"); VG_(printf)("\n"); score_cumul = 0; for (r = 0; r < n_tops; r++) { if (tops[r].addr == 0) continue; name[0] = 0; VG_(get_fnname_w_offset)(tops[r].addr, name, 64); name[63] = 0; score_here = tops[r].score; score_cumul += score_here; VG_(percentify)(score_cumul, score_total, 2, 6, buf_cumul); VG_(percentify)(score_here, score_total, 2, 6, buf_here); VG_(printf)("\n"); VG_(printf)("=-=-=-=-=-=-=-=-=-=-=-=-=-= begin BB rank %d " "=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n", r); VG_(printf)("%3d: (%9lld %s) %9lld %s 0x%llx %s\n", r, score_cumul, buf_cumul, score_here, buf_here, tops[r].addr, name ); VG_(printf)("\n"); VG_(discard_translations)(tops[r].addr, 1, "bb profile"); VG_(translate)(0, tops[r].addr, True, VG_(clo_profile_flags), 0, True); VG_(printf)("=-=-=-=-=-=-=-=-=-=-=-=-=-= end BB rank %d " "=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n", r); } VG_(printf)("\n"); VG_(printf)("-----------------------------------------------------------\n"); VG_(printf)("--- END BB Profile ---\n"); VG_(printf)("-----------------------------------------------------------\n"); VG_(printf)("\n"); } /*====================================================================*/ /*=== main() ===*/ /*====================================================================*/ /* When main() is entered, we should be on the following stack, not the one the kernel gave us. We will run on this stack until simulation of the root thread is started, at which point a transfer is made to a dynamically allocated stack. This is for the sake of uniform overflow detection for all Valgrind threads. This is marked global even though it isn't, because assembly code below needs to reference the name. */ /*static*/ VgStack VG_(interim_stack); /* These are the structures used to hold info for creating the initial client image. 'iicii' mostly holds important register state present at system startup (_start_valgrind). valgrind_main() then fills in the rest of it and passes it to VG_(ii_create_image)(). That produces 'iifii', which is later handed to VG_(ii_finalise_image). */ /* In all OS-instantiations, the_iicii has a field .sp_at_startup. This should get some address inside the stack on which we gained control (eg, it could be the SP at startup). It doesn't matter exactly where in the stack it is. This value is passed to the address space manager at startup. On Linux, aspacem then uses it to identify the initial stack segment and hence the upper end of the usable address space. */ static IICreateImageInfo the_iicii; static IIFinaliseImageInfo the_iifii; /* A simple pair structure, used for conveying debuginfo handles to calls to VG_TRACK(new_mem_startup, ...). */ typedef struct { Addr a; ULong ull; } Addr_n_ULong; /* --- Forwards decls to do with shutdown --- */ static void final_tidyup(ThreadId tid); /* Do everything which needs doing when the last thread exits */ static void shutdown_actions_NORETURN( ThreadId tid, VgSchedReturnCode tids_schedretcode ); /* --- end of Forwards decls to do with shutdown --- */ /* By the time we get to valgrind_main, the_iicii should already have been filled in with any important details as required by whatever OS we have been built for. */ static Int valgrind_main ( Int argc, HChar **argv, HChar **envp ) { HChar* toolname = "memcheck"; // default to Memcheck Int need_help = 0; // 0 = no, 1 = --help, 2 = --help-debug ThreadId tid_main = VG_INVALID_THREADID; Bool logging_to_fd = False; Char* xml_fname_unexpanded = NULL; Int loglevel, i; struct vki_rlimit zero = { 0, 0 }; XArray* addr2dihandle = NULL; // For an inner Valgrind, register the interim stack asap. // This is needed to allow the outer valgrind to do stacktraces during init. // Note that this stack is not unregistered when the main thread // is switching to the (real) stack. Unregistering this would imply // to save the stack id in a global variable, and have a "if" // in run_a_thread_NORETURN to do the unregistration only for the // main thread. This unregistration is not worth this complexity. INNER_REQUEST ((void) VALGRIND_STACK_REGISTER (&VG_(interim_stack).bytes[0], &VG_(interim_stack).bytes[0] + sizeof(VG_(interim_stack)))); //============================================================ // // Nb: startup is complex. Prerequisites are shown at every step. // *** Be very careful when messing with the order *** // // The first order of business is to get debug logging, the address // space manager and the dynamic memory manager up and running. // Once that's done, we can relax a bit. // //============================================================ /* This is needed to make VG_(getenv) usable early. */ VG_(client_envp) = (Char**)envp; //-------------------------------------------------------------- // Start up Mach kernel interface, if any // p: none //-------------------------------------------------------------- # if defined(VGO_darwin) VG_(mach_init)(); # endif //-------------------------------------------------------------- // Start up the logging mechanism // p: none //-------------------------------------------------------------- /* Start the debugging-log system ASAP. First find out how many "-d"s were specified. This is a pre-scan of the command line. Also get --profile-heap=yes, --core-redzone-size, --redzone-size which are needed by the time we start up dynamic memory management. */ loglevel = 0; for (i = 1; i < argc; i++) { if (argv[i][0] != '-') break; if VG_STREQ(argv[i], "--") break; if VG_STREQ(argv[i], "-d") loglevel++; if VG_BOOL_CLO(argv[i], "--profile-heap", VG_(clo_profile_heap)) {} if VG_BINT_CLO(argv[i], "--core-redzone-size", VG_(clo_core_redzone_size), 0, MAX_CLO_REDZONE_SZB) {} if VG_BINT_CLO(argv[i], "--redzone-size", VG_(clo_redzone_size), 0, MAX_CLO_REDZONE_SZB) {} } /* ... and start the debug logger. Now we can safely emit logging messages all through startup. */ VG_(debugLog_startup)(loglevel, "Stage 2 (main)"); VG_(debugLog)(1, "main", "Welcome to Valgrind version " VERSION " debug logging\n"); //-------------------------------------------------------------- // Ensure we're on a plausible stack. // p: logging //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Checking current stack is plausible\n"); { HChar* limLo = (HChar*)(&VG_(interim_stack).bytes[0]); HChar* limHi = limLo + sizeof(VG_(interim_stack)); HChar* aLocal = (HChar*)&limLo; /* any auto local will do */ /* "Apple clang version 4.0 (tags/Apple/clang-421.0.57) (based on LLVM 3.1svn)" appears to miscompile the following check, causing run to abort at this point (in 64-bit mode) even though aLocal is within limLo .. limHi. Try building with gcc instead. */ if (aLocal < limLo || aLocal >= limHi) { /* something's wrong. Stop. */ VG_(debugLog)(0, "main", "Root stack %p to %p, a local %p\n", limLo, limHi, aLocal ); VG_(debugLog)(0, "main", "Valgrind: FATAL: " "Initial stack switched failed.\n"); VG_(debugLog)(0, "main", " Cannot continue. Sorry.\n"); VG_(exit)(1); } } //-------------------------------------------------------------- // Ensure we have a plausible pointer to the stack on which // we gained control (not the current stack!) // p: logging //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Checking initial stack was noted\n"); if (the_iicii.sp_at_startup == 0) { VG_(debugLog)(0, "main", "Valgrind: FATAL: " "Initial stack was not noted.\n"); VG_(debugLog)(0, "main", " Cannot continue. Sorry.\n"); VG_(exit)(1); } //-------------------------------------------------------------- // Start up the address space manager, and determine the // approximate location of the client's stack // p: logging, plausible-stack //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Starting the address space manager\n"); vg_assert(VKI_PAGE_SIZE == 4096 || VKI_PAGE_SIZE == 65536 || VKI_PAGE_SIZE == 16384); vg_assert(VKI_MAX_PAGE_SIZE == 4096 || VKI_MAX_PAGE_SIZE == 65536 || VKI_MAX_PAGE_SIZE == 16384); vg_assert(VKI_PAGE_SIZE <= VKI_MAX_PAGE_SIZE); vg_assert(VKI_PAGE_SIZE == (1 << VKI_PAGE_SHIFT)); vg_assert(VKI_MAX_PAGE_SIZE == (1 << VKI_MAX_PAGE_SHIFT)); the_iicii.clstack_top = VG_(am_startup)( the_iicii.sp_at_startup ); VG_(debugLog)(1, "main", "Address space manager is running\n"); //-------------------------------------------------------------- // Start up the dynamic memory manager // p: address space management // p: getting --profile-heap,--core-redzone-size,--redzone-size // In fact m_mallocfree is self-initialising, so there's no // initialisation call to do. Instead, try a simple malloc/ // free pair right now to check that nothing is broken. //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Starting the dynamic memory manager\n"); { void* p = VG_(malloc)( "main.vm.1", 12345 ); if (p) VG_(free)( p ); } VG_(debugLog)(1, "main", "Dynamic memory manager is running\n"); //============================================================ // // Dynamic memory management is now available. // //============================================================ //-------------------------------------------------------------- // Initialise m_debuginfo // p: dynamic memory allocation VG_(debugLog)(1, "main", "Initialise m_debuginfo\n"); VG_(di_initialise)(); //-------------------------------------------------------------- // Look for alternative libdir { HChar *cp = VG_(getenv)(VALGRIND_LIB); if (cp != NULL) VG_(libdir) = cp; VG_(debugLog)(1, "main", "VG_(libdir) = %s\n", VG_(libdir)); } //-------------------------------------------------------------- // Extract the launcher name from the environment. VG_(debugLog)(1, "main", "Getting launcher's name ...\n"); VG_(name_of_launcher) = VG_(getenv)(VALGRIND_LAUNCHER); if (VG_(name_of_launcher) == NULL) { VG_(printf)("valgrind: You cannot run '%s' directly.\n", argv[0]); VG_(printf)("valgrind: You should use $prefix/bin/valgrind.\n"); VG_(exit)(1); } VG_(debugLog)(1, "main", "... %s\n", VG_(name_of_launcher)); //-------------------------------------------------------------- // Get the current process datasize rlimit, and set it to zero. // This prevents any internal uses of brk() from having any effect. // We remember the old value so we can restore it on exec, so that // child processes will have a reasonable brk value. VG_(getrlimit)(VKI_RLIMIT_DATA, &VG_(client_rlimit_data)); zero.rlim_max = VG_(client_rlimit_data).rlim_max; VG_(setrlimit)(VKI_RLIMIT_DATA, &zero); // Get the current process stack rlimit. VG_(getrlimit)(VKI_RLIMIT_STACK, &VG_(client_rlimit_stack)); //-------------------------------------------------------------- // Figure out what sort of CPU we're on, and whether it is // able to run V. VG_(debugLog)(1, "main", "Get hardware capabilities ...\n"); { VexArch vex_arch; VexArchInfo vex_archinfo; Bool ok = VG_(machine_get_hwcaps)(); if (!ok) { VG_(printf)("\n"); VG_(printf)("valgrind: fatal error: unsupported CPU.\n"); VG_(printf)(" Supported CPUs are:\n"); VG_(printf)(" * x86 (practically any; Pentium-I or above), " "AMD Athlon or above)\n"); VG_(printf)(" * AMD Athlon64/Opteron\n"); VG_(printf)(" * PowerPC (most; ppc405 and above)\n"); VG_(printf)(" * System z (64bit only - s390x; z900 and above)\n"); VG_(printf)("\n"); VG_(exit)(1); } VG_(machine_get_VexArchInfo)( &vex_arch, &vex_archinfo ); VG_(debugLog)( 1, "main", "... arch = %s, hwcaps = %s\n", LibVEX_ppVexArch ( vex_arch ), LibVEX_ppVexHwCaps ( vex_arch, vex_archinfo.hwcaps ) ); } //-------------------------------------------------------------- // Record the working directory at startup // p: none VG_(debugLog)(1, "main", "Getting the working directory at startup\n"); { Bool ok = VG_(record_startup_wd)(); if (!ok) VG_(err_config_error)( "Can't establish current working " "directory at startup\n"); } { Char buf[VKI_PATH_MAX+1]; Bool ok = VG_(get_startup_wd)( buf, sizeof(buf) ); vg_assert(ok); buf[VKI_PATH_MAX] = 0; VG_(debugLog)(1, "main", "... %s\n", buf ); } //============================================================ // Command line argument handling order: // * If --help/--help-debug are present, show usage message // (including the tool-specific usage) // * (If no --tool option given, default to Memcheck) // * Then, if client is missing, abort with error msg // * Then, if any cmdline args are bad, abort with error msg //============================================================ //-------------------------------------------------------------- // Split up argv into: C args, V args, V extra args, and exename. // p: dynamic memory allocation //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Split up command line\n"); VG_(split_up_argv)( argc, argv ); vg_assert( VG_(args_for_valgrind) ); vg_assert( VG_(args_for_client) ); if (0) { for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) VG_(printf)( "varg %s\n", * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i ) ); VG_(printf)(" exe %s\n", VG_(args_the_exename)); for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) VG_(printf)( "carg %s\n", * (HChar**) VG_(indexXA)( VG_(args_for_client), i ) ); } //-------------------------------------------------------------- // Extract tool name and whether help has been requested. // Note we can't print the help message yet, even if requested, // because the tool has not been initialised. // p: split_up_argv [for VG_(args_for_valgrind)] //-------------------------------------------------------------- VG_(debugLog)(1, "main", "(early_) Process Valgrind's command line options\n"); early_process_cmd_line_options(&need_help, &toolname); // Set default vex control params LibVEX_default_VexControl(& VG_(clo_vex_control)); //-------------------------------------------------------------- // Load client executable, finding in $PATH if necessary // p: early_process_cmd_line_options() [for 'exec', 'need_help', // clo_max_stackframe, // clo_main_stacksize] // p: layout_remaining_space [so there's space] // // Set up client's environment // p: set-libdir [for VG_(libdir)] // p: early_process_cmd_line_options [for toolname] // // Setup client stack, eip, and VG_(client_arg[cv]) // p: load_client() [for 'info'] // p: fix_environment() [for 'env'] // // Setup client data (brk) segment. Initially a 1-page segment // which abuts a shrinkable reservation. // p: load_client() [for 'info' and hence VG_(brk_base)] // // p: _start_in_C (for zeroing out the_iicii and putting some // initial values into it) //-------------------------------------------------------------- if (!need_help) { VG_(debugLog)(1, "main", "Create initial image\n"); # if defined(VGO_linux) || defined(VGO_darwin) the_iicii.argv = argv; the_iicii.envp = envp; the_iicii.toolname = toolname; # else # error "Unknown platform" # endif /* NOTE: this call reads VG_(clo_main_stacksize). */ the_iifii = VG_(ii_create_image)( the_iicii ); } //============================================================== // // Finished loading/setting up the client address space. // //============================================================== //-------------------------------------------------------------- // setup file descriptors // p: n/a //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Setup file descriptors\n"); setup_file_descriptors(); //-------------------------------------------------------------- // create the fake /proc/<pid>/cmdline file and then unlink it, // but hold onto the fd, so we can hand it out to the client // when it tries to open /proc/<pid>/cmdline for itself. // p: setup file descriptors //-------------------------------------------------------------- #if !defined(VGO_linux) // client shouldn't be using /proc! VG_(cl_cmdline_fd) = -1; #else if (!need_help) { HChar buf[50], buf2[50+64]; HChar nul[1]; Int fd, r; const HChar* exename; VG_(debugLog)(1, "main", "Create fake /proc/<pid>/cmdline\n"); VG_(sprintf)(buf, "proc_%d_cmdline", VG_(getpid)()); fd = VG_(mkstemp)( buf, buf2 ); if (fd == -1) VG_(err_config_error)("Can't create client cmdline file in %s\n", buf2); nul[0] = 0; exename = VG_(args_the_exename) ? VG_(args_the_exename) : "unknown_exename"; VG_(write)(fd, exename, VG_(strlen)( exename )); VG_(write)(fd, nul, 1); for (i = 0; i < VG_(sizeXA)( VG_(args_for_client) ); i++) { HChar* arg = * (HChar**) VG_(indexXA)( VG_(args_for_client), i ); VG_(write)(fd, arg, VG_(strlen)( arg )); VG_(write)(fd, nul, 1); } /* Don't bother to seek the file back to the start; instead do it every time a copy of it is given out (by PRE(sys_open)). That is probably more robust across fork() etc. */ /* Now delete it, but hang on to the fd. */ r = VG_(unlink)( buf2 ); if (r) VG_(err_config_error)("Can't delete client cmdline file in %s\n", buf2); VG_(cl_cmdline_fd) = fd; } #endif //-------------------------------------------------------------- // Init tool part 1: pre_clo_init // p: setup_client_stack() [for 'VG_(client_arg[cv]'] // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)'] //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Initialise the tool part 1 (pre_clo_init)\n"); VG_(tl_pre_clo_init)(); //-------------------------------------------------------------- // If --tool and --help/--help-debug was given, now give the core+tool // help message // p: early_process_cmd_line_options() [for 'need_help'] // p: tl_pre_clo_init [for 'VG_(tdict).usage'] //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Print help and quit, if requested\n"); if (need_help) { usage_NORETURN(/*--help-debug?*/need_help >= 2); } //-------------------------------------------------------------- // Process command line options to Valgrind + tool // p: setup_client_stack() [for 'VG_(client_arg[cv]'] // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)'] //-------------------------------------------------------------- VG_(debugLog)(1, "main", "(main_) Process Valgrind's command line options, " "setup logging\n"); main_process_cmd_line_options ( &logging_to_fd, &xml_fname_unexpanded, toolname ); //-------------------------------------------------------------- // Zeroise the millisecond counter by doing a first read of it. // p: none //-------------------------------------------------------------- (void) VG_(read_millisecond_timer)(); //-------------------------------------------------------------- // Print the preamble // p: tl_pre_clo_init [for 'VG_(details).name' and friends] // p: main_process_cmd_line_options() // [for VG_(clo_verbosity), VG_(clo_xml), // logging_to_fd, xml_fname_unexpanded] //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Print the preamble...\n"); print_preamble(logging_to_fd, xml_fname_unexpanded, toolname); VG_(debugLog)(1, "main", "...finished the preamble\n"); //-------------------------------------------------------------- // Init tool part 2: post_clo_init // p: setup_client_stack() [for 'VG_(client_arg[cv]'] // p: setup_file_descriptors() [for 'VG_(fd_xxx_limit)'] // p: print_preamble() [so any warnings printed in post_clo_init // are shown after the preamble] //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Initialise the tool part 2 (post_clo_init)\n"); VG_TDICT_CALL(tool_post_clo_init); { /* The tool's "needs" will by now be finalised, since it has no further opportunity to specify them. So now sanity check them. */ Char* s; Bool ok; ok = VG_(sanity_check_needs)( &s ); if (!ok) { VG_(tool_panic)(s); } } //-------------------------------------------------------------- // Initialise translation table and translation cache // p: aspacem [??] // p: tl_pre_clo_init [for 'VG_(details).avg_translation_sizeB'] //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Initialise TT/TC\n"); VG_(init_tt_tc)(); //-------------------------------------------------------------- // Initialise the redirect table. // p: init_tt_tc [so it can call VG_(search_transtab) safely] // p: aspacem [so can change ownership of sysinfo pages] //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Initialise redirects\n"); VG_(redir_initialise)(); //-------------------------------------------------------------- // Allow GDB attach // p: main_process_cmd_line_options() [for VG_(clo_wait_for_gdb)] //-------------------------------------------------------------- /* Hook to delay things long enough so we can get the pid and attach GDB in another shell. */ if (VG_(clo_wait_for_gdb)) { ULong iters, q; VG_(debugLog)(1, "main", "Wait for GDB\n"); VG_(printf)("pid=%d, entering delay loop\n", VG_(getpid)()); # if defined(VGP_x86_linux) iters = 10; # elif defined(VGP_amd64_linux) || defined(VGP_ppc64_linux) iters = 10; # elif defined(VGP_ppc32_linux) iters = 5; # elif defined(VGP_arm_linux) iters = 5; # elif defined(VGP_s390x_linux) iters = 10; # elif defined(VGP_mips32_linux) iters = 10; # elif defined(VGO_darwin) iters = 3; # else # error "Unknown plat" # endif iters *= 1000ULL * 1000 * 1000; for (q = 0; q < iters; q++) __asm__ __volatile__("" ::: "memory","cc"); } //-------------------------------------------------------------- // Search for file descriptors that are inherited from our parent // p: main_process_cmd_line_options [for VG_(clo_track_fds)] //-------------------------------------------------------------- if (VG_(clo_track_fds)) { VG_(debugLog)(1, "main", "Init preopened fds\n"); VG_(init_preopened_fds)(); } //-------------------------------------------------------------- // Load debug info for the existing segments. // p: setup_code_redirect_table [so that redirs can be recorded] // p: mallocfree // p: probably: setup fds and process CLOs, so that logging works // p: initialise m_debuginfo // // While doing this, make a note of the debuginfo-handles that // come back from VG_(di_notify_mmap). // Later, in "Tell the tool about the initial client memory permissions" // (just below) we can then hand these handles off to the tool in // calls to VG_TRACK(new_mem_startup, ...). This gives the tool the // opportunity to make further queries to m_debuginfo before the // client is started, if it wants. We put this information into an // XArray, each handle along with the associated segment start address, // and search the XArray for the handles later, when calling // VG_TRACK(new_mem_startup, ...). //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Load initial debug info\n"); tl_assert(!addr2dihandle); addr2dihandle = VG_(newXA)( VG_(malloc), "main.vm.2", VG_(free), sizeof(Addr_n_ULong) ); tl_assert(addr2dihandle); # if defined(VGO_linux) { Addr* seg_starts; Int n_seg_starts; Addr_n_ULong anu; seg_starts = VG_(get_segment_starts)( &n_seg_starts ); vg_assert(seg_starts && n_seg_starts >= 0); /* show them all to the debug info reader. allow_SkFileV has to be True here so that we read info from the valgrind executable itself. */ for (i = 0; i < n_seg_starts; i++) { anu.ull = VG_(di_notify_mmap)( seg_starts[i], True/*allow_SkFileV*/, -1/*Don't use_fd*/); /* anu.ull holds the debuginfo handle returned by di_notify_mmap, if any. */ if (anu.ull > 0) { anu.a = seg_starts[i]; VG_(addToXA)( addr2dihandle, &anu ); } } VG_(free)( seg_starts ); } # elif defined(VGO_darwin) { Addr* seg_starts; Int n_seg_starts; seg_starts = VG_(get_segment_starts)( &n_seg_starts ); vg_assert(seg_starts && n_seg_starts >= 0); /* show them all to the debug info reader. Don't read from V segments (unlike Linux) */ // GrP fixme really? for (i = 0; i < n_seg_starts; i++) { VG_(di_notify_mmap)( seg_starts[i], False/*don't allow_SkFileV*/, -1/*don't use_fd*/); } VG_(free)( seg_starts ); } # else # error Unknown OS # endif //-------------------------------------------------------------- // Tell aspacem of ownership change of the asm helpers, so that // m_translate allows them to be translated. However, only do this // after the initial debug info read, since making a hole in the // address range for the stage2 binary confuses the debug info reader. // p: aspacem //-------------------------------------------------------------- { Bool change_ownership_v_c_OK; Addr co_start = VG_PGROUNDDN( (Addr)&VG_(trampoline_stuff_start) ); Addr co_endPlus = VG_PGROUNDUP( (Addr)&VG_(trampoline_stuff_end) ); VG_(debugLog)(1,"redir", "transfer ownership V -> C of 0x%llx .. 0x%llx\n", (ULong)co_start, (ULong)co_endPlus-1 ); change_ownership_v_c_OK = VG_(am_change_ownership_v_to_c)( co_start, co_endPlus - co_start ); vg_assert(change_ownership_v_c_OK); } if (VG_(clo_xml)) { HChar buf[50]; VG_(elapsed_wallclock_time)(buf); VG_(printf_xml)( "<status>\n" " <state>RUNNING</state>\n" " <time>%pS</time>\n" "</status>\n", buf ); VG_(printf_xml)( "\n" ); } VG_(init_Threads)(); //-------------------------------------------------------------- // Initialise the scheduler (phase 1) [generates tid_main] // p: none, afaics //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Initialise scheduler (phase 1)\n"); tid_main = VG_(scheduler_init_phase1)(); vg_assert(tid_main >= 0 && tid_main < VG_N_THREADS && tid_main != VG_INVALID_THREADID); /* Tell the tool about tid_main */ VG_TRACK( pre_thread_ll_create, VG_INVALID_THREADID, tid_main ); //-------------------------------------------------------------- // Tell the tool about the initial client memory permissions // p: aspacem // p: mallocfree // p: setup_client_stack // p: setup_client_dataseg // // For each segment we tell the client about, look up in // addr2dihandle as created above, to see if there's a debuginfo // handle associated with the segment, that we can hand along // to the tool, to be helpful. //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Tell tool about initial permissions\n"); { Addr* seg_starts; Int n_seg_starts; tl_assert(addr2dihandle); /* Mark the main thread as running while we tell the tool about the client memory so that the tool can associate that memory with the main thread. */ tl_assert(VG_(running_tid) == VG_INVALID_THREADID); VG_(running_tid) = tid_main; seg_starts = VG_(get_segment_starts)( &n_seg_starts ); vg_assert(seg_starts && n_seg_starts >= 0); /* show interesting ones to the tool */ for (i = 0; i < n_seg_starts; i++) { Word j, n; NSegment const* seg = VG_(am_find_nsegment)( seg_starts[i] ); vg_assert(seg); if (seg->kind == SkFileC || seg->kind == SkAnonC) { /* This next assertion is tricky. If it is placed immediately before this 'if', it very occasionally fails. Why? Because previous iterations of the loop may have caused tools (via the new_mem_startup calls) to do dynamic memory allocation, and that may affect the mapped segments; in particular it may cause segment merging to happen. Hence we cannot assume that seg_starts[i], which reflects the state of the world before we started this loop, is the same as seg->start, as the latter reflects the state of the world (viz, mappings) at this particular iteration of the loop. Why does moving it inside the 'if' make it safe? Because any dynamic memory allocation done by the tools will affect only the state of Valgrind-owned segments, not of Client-owned segments. And the 'if' guards against that -- we only get in here for Client-owned segments. In other words: the loop may change the state of Valgrind-owned segments as it proceeds. But it should not cause the Client-owned segments to change. */ vg_assert(seg->start == seg_starts[i]); VG_(debugLog)(2, "main", "tell tool about %010lx-%010lx %c%c%c\n", seg->start, seg->end, seg->hasR ? 'r' : '-', seg->hasW ? 'w' : '-', seg->hasX ? 'x' : '-' ); /* search addr2dihandle to see if we have an entry matching seg->start. */ n = VG_(sizeXA)( addr2dihandle ); for (j = 0; j < n; j++) { Addr_n_ULong* anl = VG_(indexXA)( addr2dihandle, j ); if (anl->a == seg->start) { tl_assert(anl->ull > 0); /* check it's a valid handle */ break; } } vg_assert(j >= 0 && j <= n); VG_TRACK( new_mem_startup, seg->start, seg->end+1-seg->start, seg->hasR, seg->hasW, seg->hasX, /* and the retrieved debuginfo handle, if any */ j < n ? ((Addr_n_ULong*)VG_(indexXA)( addr2dihandle, j ))->ull : 0 ); } } VG_(free)( seg_starts ); VG_(deleteXA)( addr2dihandle ); /* Also do the initial stack permissions. */ { SSizeT inaccessible_len; NSegment const* seg = VG_(am_find_nsegment)( the_iifii.initial_client_SP ); vg_assert(seg); vg_assert(seg->kind == SkAnonC); vg_assert(the_iifii.initial_client_SP >= seg->start); vg_assert(the_iifii.initial_client_SP <= seg->end); /* Stuff below the initial SP is unaddressable. Take into account any ABI-mandated space below the stack pointer that is required (VG_STACK_REDZONE_SZB). setup_client_stack() will have allocated an extra page if a red zone is required, to be on the safe side. */ inaccessible_len = the_iifii.initial_client_SP - VG_STACK_REDZONE_SZB - seg->start; vg_assert(inaccessible_len >= 0); if (inaccessible_len > 0) VG_TRACK( die_mem_stack, seg->start, inaccessible_len ); VG_(debugLog)(2, "main", "mark stack inaccessible %010lx-%010lx\n", seg->start, the_iifii.initial_client_SP-1 - VG_STACK_REDZONE_SZB); } /* Also the assembly helpers. */ VG_TRACK( new_mem_startup, (Addr)&VG_(trampoline_stuff_start), (Addr)&VG_(trampoline_stuff_end) - (Addr)&VG_(trampoline_stuff_start), False, /* readable? */ False, /* writable? */ True /* executable? */, 0 /* di_handle: no associated debug info */ ); /* Clear the running thread indicator */ VG_(running_tid) = VG_INVALID_THREADID; tl_assert(VG_(running_tid) == VG_INVALID_THREADID); } //-------------------------------------------------------------- // Initialise the scheduler (phase 2) // p: Initialise the scheduler (phase 1) [for tid_main] // p: setup_file_descriptors() [else VG_(safe_fd)() breaks] // p: setup_client_stack //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Initialise scheduler (phase 2)\n"); { NSegment const* seg = VG_(am_find_nsegment)( the_iifii.initial_client_SP ); vg_assert(seg); vg_assert(seg->kind == SkAnonC); vg_assert(the_iifii.initial_client_SP >= seg->start); vg_assert(the_iifii.initial_client_SP <= seg->end); VG_(scheduler_init_phase2)( tid_main, seg->end, the_iifii.clstack_max_size ); } //-------------------------------------------------------------- // Set up state for the root thread // p: ? // setup_scheduler() [for sched-specific thread 1 stuff] // VG_(ii_create_image) [for 'the_iicii' initial info] //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Finalise initial image\n"); VG_(ii_finalise_image)( the_iifii ); //-------------------------------------------------------------- // Initialise the signal handling subsystem // p: n/a //-------------------------------------------------------------- // Nb: temporarily parks the saved blocking-mask in saved_sigmask. VG_(debugLog)(1, "main", "Initialise signal management\n"); /* Check that the kernel-interface signal definitions look sane */ VG_(vki_do_initial_consistency_checks)(); /* .. and go on to use them. */ VG_(sigstartup_actions)(); //-------------------------------------------------------------- // Read suppression file // p: main_process_cmd_line_options() [for VG_(clo_suppressions)] //-------------------------------------------------------------- if (VG_(needs).core_errors || VG_(needs).tool_errors) { VG_(debugLog)(1, "main", "Load suppressions\n"); VG_(load_suppressions)(); } //-------------------------------------------------------------- // register client stack //-------------------------------------------------------------- VG_(clstk_id) = VG_(register_stack)(VG_(clstk_base), VG_(clstk_end)); //-------------------------------------------------------------- // Show the address space state so far //-------------------------------------------------------------- VG_(debugLog)(1, "main", "\n"); VG_(debugLog)(1, "main", "\n"); VG_(am_show_nsegments)(1,"Memory layout at client startup"); VG_(debugLog)(1, "main", "\n"); VG_(debugLog)(1, "main", "\n"); //-------------------------------------------------------------- // Run! //-------------------------------------------------------------- VG_(debugLog)(1, "main", "Running thread 1\n"); /* As a result of the following call, the last thread standing eventually winds up running shutdown_actions_NORETURN just below. Unfortunately, simply exporting said function causes m_main to be part of a module cycle, which is pretty nonsensical. So instead of doing that, the address of said function is stored in a global variable 'owned' by m_syswrap, and it uses that function pointer to get back here when it needs to. */ /* Set continuation address. */ VG_(address_of_m_main_shutdown_actions_NORETURN) = & shutdown_actions_NORETURN; /* Run the first thread, eventually ending up at the continuation address. */ VG_(main_thread_wrapper_NORETURN)(1); /*NOTREACHED*/ vg_assert(0); } /* Do everything which needs doing when the last thread exits or when a thread exits requesting a complete process exit. We enter here holding The Lock. For the case VgSrc_ExitProcess we must never release it, because to do so would allow other threads to continue after the system is ostensibly shut down. So we must go to our grave, so to speak, holding the lock. In fact, there is never any point in releasing the lock at this point - we have it, we're shutting down the entire system, and for the case VgSrc_ExitProcess doing so positively causes trouble. So don't. The final_tidyup call makes a bit of a nonsense of the ExitProcess case, since it will run the libc_freeres function, thus allowing other lurking threads to run again. Hmm. */ static void shutdown_actions_NORETURN( ThreadId tid, VgSchedReturnCode tids_schedretcode ) { VG_(debugLog)(1, "main", "entering VG_(shutdown_actions_NORETURN)\n"); VG_(am_show_nsegments)(1,"Memory layout at client shutdown"); vg_assert(VG_(is_running_thread)(tid)); vg_assert(tids_schedretcode == VgSrc_ExitThread || tids_schedretcode == VgSrc_ExitProcess || tids_schedretcode == VgSrc_FatalSig ); if (tids_schedretcode == VgSrc_ExitThread) { // We are the last surviving thread. Right? vg_assert( VG_(count_living_threads)() == 1 ); // Wait for all other threads to exit. // jrs: Huh? but they surely are already gone VG_(reap_threads)(tid); // Clean the client up before the final report // this causes the libc_freeres function to run final_tidyup(tid); /* be paranoid */ vg_assert(VG_(is_running_thread)(tid)); vg_assert(VG_(count_living_threads)() == 1); } else { // We may not be the last surviving thread. However, we // want to shut down the entire process. We hold the lock // and we need to keep hold of it all the way out, in order // that none of the other threads ever run again. vg_assert( VG_(count_living_threads)() >= 1 ); // Clean the client up before the final report // this causes the libc_freeres function to run // perhaps this is unsafe, as per comment above final_tidyup(tid); /* be paranoid */ vg_assert(VG_(is_running_thread)(tid)); vg_assert(VG_(count_living_threads)() >= 1); } VG_(threads)[tid].status = VgTs_Empty; //-------------------------------------------------------------- // Finalisation: cleanup, messages, etc. Order not so important, only // affects what order the messages come. //-------------------------------------------------------------- // First thing in the post-amble is a blank line. if (VG_(clo_xml)) VG_(printf_xml)("\n"); else if (VG_(clo_verbosity) > 0) VG_(message)(Vg_UserMsg, "\n"); if (VG_(clo_xml)) { HChar buf[50]; VG_(elapsed_wallclock_time)(buf); VG_(printf_xml)( "<status>\n" " <state>FINISHED</state>\n" " <time>%pS</time>\n" "</status>\n" "\n", buf); } /* Print out file descriptor summary and stats. */ if (VG_(clo_track_fds)) VG_(show_open_fds)(); /* Call the tool's finalisation function. This makes Memcheck's leak checker run, and possibly chuck a bunch of leak errors into the error management machinery. */ VG_TDICT_CALL(tool_fini, 0/*exitcode*/); /* Show the error counts. */ if (VG_(clo_xml) && (VG_(needs).core_errors || VG_(needs).tool_errors)) { VG_(show_error_counts_as_XML)(); } /* In XML mode, this merely prints the used suppressions. */ if (VG_(needs).core_errors || VG_(needs).tool_errors) VG_(show_all_errors)(VG_(clo_verbosity), VG_(clo_xml)); if (VG_(clo_xml)) { VG_(printf_xml)("\n"); VG_(printf_xml)("</valgrindoutput>\n"); VG_(printf_xml)("\n"); } VG_(sanity_check_general)( True /*include expensive checks*/ ); if (VG_(clo_stats)) print_all_stats(); /* Show a profile of the heap(s) at shutdown. Optionally, first throw away all the debug info, as that makes it easy to spot leaks in the debuginfo reader. */ if (VG_(clo_profile_heap)) { if (0) VG_(di_discard_ALL_debuginfo)(); VG_(print_arena_cc_analysis)(); } if (VG_(clo_profile_flags) > 0) { #define N_MAX 200 BBProfEntry tops[N_MAX]; ULong score_total = VG_(get_BB_profile) (tops, N_MAX); show_BB_profile(tops, N_MAX, score_total); } /* Print Vex storage stats */ if (0) LibVEX_ShowAllocStats(); /* Flush any output cached by previous calls to VG_(message). */ VG_(message_flush)(); /* terminate gdbserver if ever it was started. We terminate it here so that it get the output above if output was redirected to gdb */ VG_(gdbserver) (0); /* Ok, finally exit in the os-specific way, according to the scheduler's return code. In short, if the (last) thread exited by calling sys_exit, do likewise; if the (last) thread stopped due to a fatal signal, terminate the entire system with that same fatal signal. */ VG_(debugLog)(1, "core_os", "VG_(terminate_NORETURN)(tid=%lld)\n", (ULong)tid); switch (tids_schedretcode) { case VgSrc_ExitThread: /* the normal way out (Linux) */ case VgSrc_ExitProcess: /* the normal way out (AIX) -- still needed? */ /* Change the application return code to user's return code, if an error was found */ if (VG_(clo_error_exitcode) > 0 && VG_(get_n_errs_found)() > 0) { VG_(exit)( VG_(clo_error_exitcode) ); } else { /* otherwise, return the client's exit code, in the normal way. */ VG_(exit)( VG_(threads)[tid].os_state.exitcode ); } /* NOT ALIVE HERE! */ VG_(core_panic)("entered the afterlife in main() -- ExitT/P"); break; /* what the hell :) */ case VgSrc_FatalSig: /* We were killed by a fatal signal, so replicate the effect */ vg_assert(VG_(threads)[tid].os_state.fatalsig != 0); VG_(kill_self)(VG_(threads)[tid].os_state.fatalsig); /* we shouldn't be alive at this point. But VG_(kill_self) sometimes fails with EPERM on Darwin, for unclear reasons. */ # if defined(VGO_darwin) VG_(debugLog)(0, "main", "VG_(kill_self) failed. Exiting normally.\n"); VG_(exit)(0); /* bogus, but we really need to exit now */ /* fall through .. */ # endif VG_(core_panic)("main(): signal was supposed to be fatal"); break; default: VG_(core_panic)("main(): unexpected scheduler return code"); } } /* -------------------- */ /* Final clean-up before terminating the process. Clean up the client by calling __libc_freeres() (if requested) This is Linux-specific? GrP fixme glibc-specific, anyway */ static void final_tidyup(ThreadId tid) { #if !defined(VGO_darwin) # if defined(VGP_ppc64_linux) Addr r2; # endif Addr __libc_freeres_wrapper = VG_(client___libc_freeres_wrapper); vg_assert(VG_(is_running_thread)(tid)); if ( !VG_(needs).libc_freeres || !VG_(clo_run_libc_freeres) || 0 == __libc_freeres_wrapper ) return; /* can't/won't do it */ # if defined(VGP_ppc64_linux) r2 = VG_(get_tocptr)( __libc_freeres_wrapper ); if (r2 == 0) { VG_(message)(Vg_UserMsg, "Caught __NR_exit, but can't run __libc_freeres()\n"); VG_(message)(Vg_UserMsg, " since cannot establish TOC pointer for it.\n"); return; } # endif if (VG_(clo_verbosity) > 2 || VG_(clo_trace_syscalls) || VG_(clo_trace_sched)) VG_(message)(Vg_DebugMsg, "Caught __NR_exit; running __libc_freeres()\n"); /* set thread context to point to libc_freeres_wrapper */ /* ppc64-linux note: __libc_freeres_wrapper gives us the real function entry point, not a fn descriptor, so can use it directly. However, we need to set R2 (the toc pointer) appropriately. */ VG_(set_IP)(tid, __libc_freeres_wrapper); # if defined(VGP_ppc64_linux) VG_(threads)[tid].arch.vex.guest_GPR2 = r2; # endif /* mips-linux note: we need to set t9 */ # if defined(VGP_mips32_linux) VG_(threads)[tid].arch.vex.guest_r25 = __libc_freeres_wrapper; # endif /* Block all blockable signals by copying the real block state into the thread's block state*/ VG_(sigprocmask)(VKI_SIG_BLOCK, NULL, &VG_(threads)[tid].sig_mask); VG_(threads)[tid].tmp_sig_mask = VG_(threads)[tid].sig_mask; /* and restore handlers to default */ VG_(set_default_handler)(VKI_SIGSEGV); VG_(set_default_handler)(VKI_SIGBUS); VG_(set_default_handler)(VKI_SIGILL); VG_(set_default_handler)(VKI_SIGFPE); // We were exiting, so assert that... vg_assert(VG_(is_exiting)(tid)); // ...but now we're not again VG_(threads)[tid].exitreason = VgSrc_None; // run until client thread exits - ideally with LIBC_FREERES_DONE, // but exit/exitgroup/signal will do VG_(scheduler)(tid); vg_assert(VG_(is_exiting)(tid)); #endif } /*====================================================================*/ /*=== Getting to main() alive: LINUX ===*/ /*====================================================================*/ #if defined(VGO_linux) /* If linking of the final executables is done with glibc present, then Valgrind starts at main() above as usual, and all of the following code is irrelevant. However, this is not the intended mode of use. The plan is to avoid linking against glibc, by giving gcc the flags -nodefaultlibs -lgcc -nostartfiles at startup. From this derive two requirements: 1. gcc may emit calls to memcpy and memset to deal with structure assignments etc. Since we have chosen to ignore all the "normal" supporting libraries, we have to provide our own implementations of them. No problem. 2. We have to provide a symbol "_start", to which the kernel hands control at startup. Hence the code below. */ /* ---------------- Requirement 1 ---------------- */ void* memcpy(void *dest, const void *src, SizeT n); void* memcpy(void *dest, const void *src, SizeT n) { return VG_(memcpy)(dest,src,n); } void* memset(void *s, int c, SizeT n); void* memset(void *s, int c, SizeT n) { return VG_(memset)(s,c,n); } /* BVA: abort() for those platforms that need it (PPC and ARM). */ void abort(void); void abort(void){ VG_(printf)("Something called raise().\n"); vg_assert(0); } /* EAZG: ARM's EABI will call floating point exception handlers in libgcc which boil down to an abort or raise, that's usually defined in libc. Instead, define them here. */ #if defined(VGP_arm_linux) void raise(void); void raise(void){ VG_(printf)("Something called raise().\n"); vg_assert(0); } void __aeabi_unwind_cpp_pr0(void); void __aeabi_unwind_cpp_pr0(void){ VG_(printf)("Something called __aeabi_unwind_cpp_pr0()\n"); vg_assert(0); } void __aeabi_unwind_cpp_pr1(void); void __aeabi_unwind_cpp_pr1(void){ VG_(printf)("Something called __aeabi_unwind_cpp_pr1()\n"); vg_assert(0); } #endif /* ---------------- Requirement 2 ---------------- */ /* Glibc's sysdeps/i386/elf/start.S has the following gem of a comment, which explains how the stack looks right at process start (when _start is jumped to). Hence _start passes %esp to _start_in_C_linux, which extracts argc/argv/envp and starts up correctly. */ /* This is the canonical entry point, usually the first thing in the text segment. The SVR4/i386 ABI (pages 3-31, 3-32) says that when the entry point runs, most registers' values are unspecified, except for: %edx Contains a function pointer to be registered with `atexit'. This is how the dynamic linker arranges to have DT_FINI functions called for shared libraries that have been loaded before this code runs. %esp The stack contains the arguments and environment: 0(%esp) argc 4(%esp) argv[0] ... (4*argc)(%esp) NULL (4*(argc+1))(%esp) envp[0] ... NULL */ /* The kernel hands control to _start, which extracts the initial stack pointer and calls onwards to _start_in_C_linux. This also switches the new stack. */ #if defined(VGP_x86_linux) asm("\n" ".text\n" "\t.globl _start\n" "\t.type _start,@function\n" "_start:\n" /* set up the new stack in %eax */ "\tmovl $vgPlain_interim_stack, %eax\n" "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n" "\taddl $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %eax\n" "\tsubl $16, %eax\n" "\tandl $~15, %eax\n" /* install it, and collect the original one */ "\txchgl %eax, %esp\n" /* call _start_in_C_linux, passing it the startup %esp */ "\tpushl %eax\n" "\tcall _start_in_C_linux\n" "\thlt\n" ".previous\n" ); #elif defined(VGP_amd64_linux) asm("\n" ".text\n" "\t.globl _start\n" "\t.type _start,@function\n" "_start:\n" /* set up the new stack in %rdi */ "\tmovq $vgPlain_interim_stack, %rdi\n" "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n" "\taddq $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %rdi\n" "\tandq $~15, %rdi\n" /* install it, and collect the original one */ "\txchgq %rdi, %rsp\n" /* call _start_in_C_linux, passing it the startup %rsp */ "\tcall _start_in_C_linux\n" "\thlt\n" ".previous\n" ); #elif defined(VGP_ppc32_linux) asm("\n" ".text\n" "\t.globl _start\n" "\t.type _start,@function\n" "_start:\n" /* set up the new stack in r16 */ "\tlis 16,vgPlain_interim_stack@ha\n" "\tla 16,vgPlain_interim_stack@l(16)\n" "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n" "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n" "\tlis 18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" >> 16)\n" "\tori 18,18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" & 0xFFFF)\n" "\tadd 16,17,16\n" "\tadd 16,18,16\n" "\trlwinm 16,16,0,0,27\n" /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB + VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte boundary. And r1 is the original SP. Set the SP to r16 and call _start_in_C_linux, passing it the initial SP. */ "\tmr 3,1\n" "\tmr 1,16\n" "\tbl _start_in_C_linux\n" "\ttrap\n" ".previous\n" ); #elif defined(VGP_ppc64_linux) asm("\n" /* PPC64 ELF ABI says '_start' points to a function descriptor. So we must have one, and that is what goes into the .opd section. */ "\t.align 2\n" "\t.global _start\n" "\t.section \".opd\",\"aw\"\n" "\t.align 3\n" "_start:\n" "\t.quad ._start,.TOC.@tocbase,0\n" "\t.previous\n" "\t.type ._start,@function\n" "\t.global ._start\n" "._start:\n" /* set up the new stack in r16 */ "\tlis 16, vgPlain_interim_stack@highest\n" "\tori 16,16,vgPlain_interim_stack@higher\n" "\tsldi 16,16,32\n" "\toris 16,16,vgPlain_interim_stack@h\n" "\tori 16,16,vgPlain_interim_stack@l\n" "\txor 17,17,17\n" "\tlis 17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" >> 16)\n" "\tori 17,17,("VG_STRINGIFY(VG_STACK_GUARD_SZB)" & 0xFFFF)\n" "\txor 18,18,18\n" "\tlis 18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" >> 16)\n" "\tori 18,18,("VG_STRINGIFY(VG_STACK_ACTIVE_SZB)" & 0xFFFF)\n" "\tadd 16,17,16\n" "\tadd 16,18,16\n" "\trldicr 16,16,0,59\n" /* now r16 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB + VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte boundary. And r1 is the original SP. Set the SP to r16 and call _start_in_C_linux, passing it the initial SP. */ "\tmr 3,1\n" "\tmr 1,16\n" "\tlis 14, _start_in_C_linux@highest\n" "\tori 14,14,_start_in_C_linux@higher\n" "\tsldi 14,14,32\n" "\toris 14,14,_start_in_C_linux@h\n" "\tori 14,14,_start_in_C_linux@l\n" "\tld 14,0(14)\n" "\tmtctr 14\n" "\tbctrl\n" "\tnop\n" "\ttrap\n" ); #elif defined(VGP_s390x_linux) /* This is the canonical entry point, usually the first thing in the text segment. Most registers' values are unspecified, except for: %r14 Contains a function pointer to be registered with `atexit'. This is how the dynamic linker arranges to have DT_FINI functions called for shared libraries that have been loaded before this code runs. %r15 The stack contains the arguments and environment: 0(%r15) argc 8(%r15) argv[0] ... (8*argc)(%r15) NULL (8*(argc+1))(%r15) envp[0] ... NULL */ asm("\n\t" ".text\n\t" ".globl _start\n\t" ".type _start,@function\n\t" "_start:\n\t" /* set up the new stack in %r1 */ "larl %r1, vgPlain_interim_stack\n\t" "larl %r5, 1f\n\t" "ag %r1, 0(%r5)\n\t" "ag %r1, 2f-1f(%r5)\n\t" "nill %r1, 0xFFF0\n\t" /* install it, and collect the original one */ "lgr %r2, %r15\n\t" "lgr %r15, %r1\n\t" /* call _start_in_C_linux, passing it the startup %r15 */ "brasl %r14, _start_in_C_linux\n\t" /* trigger execution of an invalid opcode -> halt machine */ "j .+2\n\t" "1: .quad "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n\t" "2: .quad "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n\t" ".previous\n" ); #elif defined(VGP_arm_linux) asm("\n" "\t.text\n" "\t.align 4\n" "\t.type _start,#function\n" "\t.global _start\n" "_start:\n" "\tldr r0, [pc, #36]\n" "\tldr r1, [pc, #36]\n" "\tadd r0, r1, r0\n" "\tldr r1, [pc, #32]\n" "\tadd r0, r1, r0\n" "\tmvn r1, #15\n" "\tand r0, r0, r1\n" "\tmov r1, sp\n" "\tmov sp, r0\n" "\tmov r0, r1\n" "\tb _start_in_C_linux\n" "\t.word vgPlain_interim_stack\n" "\t.word "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n" "\t.word "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n" ); #elif defined(VGP_mips32_linux) asm("\n" "\t.type _gp_disp,@object\n" ".text\n" "\t.globl __start\n" "\t.type __start,@function\n" "__start:\n" "\tbal 1f\n" "\tnop\n" "1:\n" "\tlui $28, %hi(_gp_disp)\n" "\taddiu $28, $28, %lo(_gp_disp)\n" "\taddu $28, $28, $31\n" /* t1/$9 <- Addr(interim_stack) */ "\tlui $9, %hi(vgPlain_interim_stack)\n" /* t1/$9 <- Addr(interim_stack) */ "\taddiu $9, %lo(vgPlain_interim_stack)\n" "\tli $10, "VG_STRINGIFY(VG_STACK_GUARD_SZB)"\n" "\tli $11, "VG_STRINGIFY(VG_STACK_ACTIVE_SZB)"\n" "\taddu $9, $9, $10\n" "\taddu $9, $9, $11\n" "\tli $12, 0xFFFFFFF0\n" "\tand $9, $9, $12\n" /* now t1/$9 = &vgPlain_interim_stack + VG_STACK_GUARD_SZB + VG_STACK_ACTIVE_SZB rounded down to the nearest 16-byte boundary. And $29 is the original SP. Set the SP to t1 and call _start_in_C, passing it the initial SP. */ "\tmove $4, $29\n" // a0 <- $sp (_start_in_C first arg) "\tmove $29, $9\n" // $sp <- t1 (new sp) "\tlui $25, %hi(_start_in_C_linux)\n" "\taddiu $25, %lo(_start_in_C_linux)\n" "\tbal _start_in_C_linux\n" "\tbreak 0x7\n" ".previous\n" ); #else # error "Unknown linux platform" #endif /* --- !!! --- EXTERNAL HEADERS start --- !!! --- */ #define _GNU_SOURCE #define _FILE_OFFSET_BITS 64 /* This is in order to get AT_NULL and AT_PAGESIZE. */ #include <elf.h> /* --- !!! --- EXTERNAL HEADERS end --- !!! --- */ /* Avoid compiler warnings: this fn _is_ used, but labelling it 'static' causes gcc to complain it isn't. attribute 'used' also ensures the code is not eliminated at link time */ __attribute__ ((used)) void _start_in_C_linux ( UWord* pArgc ); __attribute__ ((used)) void _start_in_C_linux ( UWord* pArgc ) { Int r; Word argc = pArgc[0]; HChar** argv = (HChar**)&pArgc[1]; HChar** envp = (HChar**)&pArgc[1+argc+1]; VG_(memset)( &the_iicii, 0, sizeof(the_iicii) ); VG_(memset)( &the_iifii, 0, sizeof(the_iifii) ); the_iicii.sp_at_startup = (Addr)pArgc; # if defined(VGP_ppc32_linux) || defined(VGP_ppc64_linux) { /* ppc/ppc64 can be configured with different page sizes. Determine this early. This is an ugly hack and really should be moved into valgrind_main. */ UWord *sp = &pArgc[1+argc+1]; while (*sp++ != 0) ; for (; *sp != AT_NULL && *sp != AT_PAGESZ; sp += 2); if (*sp == AT_PAGESZ) { VKI_PAGE_SIZE = sp[1]; for (VKI_PAGE_SHIFT = 12; VKI_PAGE_SHIFT <= VKI_MAX_PAGE_SHIFT; VKI_PAGE_SHIFT++) if (VKI_PAGE_SIZE == (1UL << VKI_PAGE_SHIFT)) break; } } # endif r = valgrind_main( (Int)argc, argv, envp ); /* NOTREACHED */ VG_(exit)(r); } /*====================================================================*/ /*=== Getting to main() alive: darwin ===*/ /*====================================================================*/ #elif defined(VGO_darwin) /* Memory layout established by kernel: 0(%esp) argc 4(%esp) argv[0] ... argv[argc-1] NULL envp[0] ... envp[n] NULL executable name (presumably, a pointer to it) NULL Ditto in the 64-bit case, except all offsets from SP are obviously twice as large. */ /* The kernel hands control to _start, which extracts the initial stack pointer and calls onwards to _start_in_C_darwin. This also switches to the new stack. */ #if defined(VGP_x86_darwin) asm("\n" ".text\n" ".align 2,0x90\n" "\t.globl __start\n" "__start:\n" /* set up the new stack in %eax */ "\tmovl $_vgPlain_interim_stack, %eax\n" "\taddl $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %eax\n" "\taddl $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %eax\n" "\tsubl $16, %eax\n" "\tandl $~15, %eax\n" /* install it, and collect the original one */ "\txchgl %eax, %esp\n" "\tsubl $12, %esp\n" // keep stack 16 aligned; see #295428 /* call _start_in_C_darwin, passing it the startup %esp */ "\tpushl %eax\n" "\tcall __start_in_C_darwin\n" "\tint $3\n" "\tint $3\n" ); #elif defined(VGP_amd64_darwin) asm("\n" ".text\n" "\t.globl __start\n" ".align 3,0x90\n" "__start:\n" /* set up the new stack in %rdi */ "\tmovabsq $_vgPlain_interim_stack, %rdi\n" "\taddq $"VG_STRINGIFY(VG_STACK_GUARD_SZB)", %rdi\n" "\taddq $"VG_STRINGIFY(VG_STACK_ACTIVE_SZB)", %rdi\n" "\tandq $~15, %rdi\n" /* install it, and collect the original one */ "\txchgq %rdi, %rsp\n" /* call _start_in_C_darwin, passing it the startup %rsp */ "\tcall __start_in_C_darwin\n" "\tint $3\n" "\tint $3\n" ); #endif void* __memcpy_chk(void *dest, const void *src, SizeT n, SizeT n2); void* __memcpy_chk(void *dest, const void *src, SizeT n, SizeT n2) { // skip check return VG_(memcpy)(dest,src,n); } void* __memset_chk(void *s, int c, SizeT n, SizeT n2); void* __memset_chk(void *s, int c, SizeT n, SizeT n2) { // skip check return VG_(memset)(s,c,n); } void bzero(void *s, SizeT n); void bzero(void *s, SizeT n) { VG_(memset)(s,0,n); } void* memcpy(void *dest, const void *src, SizeT n); void* memcpy(void *dest, const void *src, SizeT n) { return VG_(memcpy)(dest,src,n); } void* memset(void *s, int c, SizeT n); void* memset(void *s, int c, SizeT n) { return VG_(memset)(s,c,n); } /* Avoid compiler warnings: this fn _is_ used, but labelling it 'static' causes gcc to complain it isn't. */ void _start_in_C_darwin ( UWord* pArgc ); void _start_in_C_darwin ( UWord* pArgc ) { Int r; Int argc = *(Int *)pArgc; // not pArgc[0] on LP64 HChar** argv = (HChar**)&pArgc[1]; HChar** envp = (HChar**)&pArgc[1+argc+1]; VG_(memset)( &the_iicii, 0, sizeof(the_iicii) ); VG_(memset)( &the_iifii, 0, sizeof(the_iifii) ); the_iicii.sp_at_startup = (Addr)pArgc; r = valgrind_main( (Int)argc, argv, envp ); /* NOTREACHED */ VG_(exit)(r); } #else # error "Unknown OS" #endif /*====================================================================*/ /*=== {u,}{div,mod}di3 replacements ===*/ /*====================================================================*/ /* For static linking on x86-darwin, we need to supply our own 64-bit integer division code, else the link dies thusly: ld_classic: Undefined symbols: ___udivdi3 ___umoddi3 */ #if defined(VGP_x86_darwin) /* Routines for doing signed/unsigned 64 x 64 ==> 64 div and mod (udivdi3, umoddi3, divdi3, moddi3) using only 32 x 32 ==> 32 division. Cobbled together from http://www.hackersdelight.org/HDcode/divlu.c http://www.hackersdelight.org/HDcode/divls.c http://www.hackersdelight.org/HDcode/newCode/divDouble.c The code from those three files is covered by the following license, as it appears at: http://www.hackersdelight.org/permissions.htm You are free to use, copy, and distribute any of the code on this web site, whether modified by you or not. You need not give attribution. This includes the algorithms (some of which appear in Hacker's Delight), the Hacker's Assistant, and any code submitted by readers. Submitters implicitly agree to this. */ /* Long division, unsigned (64/32 ==> 32). This procedure performs unsigned "long division" i.e., division of a 64-bit unsigned dividend by a 32-bit unsigned divisor, producing a 32-bit quotient. In the overflow cases (divide by 0, or quotient exceeds 32 bits), it returns a remainder of 0xFFFFFFFF (an impossible value). The dividend is u1 and u0, with u1 being the most significant word. The divisor is parameter v. The value returned is the quotient. Max line length is 57, to fit in hacker.book. */ static Int nlz32(UInt x) { Int n; if (x == 0) return(32); n = 0; if (x <= 0x0000FFFF) {n = n +16; x = x <<16;} if (x <= 0x00FFFFFF) {n = n + 8; x = x << 8;} if (x <= 0x0FFFFFFF) {n = n + 4; x = x << 4;} if (x <= 0x3FFFFFFF) {n = n + 2; x = x << 2;} if (x <= 0x7FFFFFFF) {n = n + 1;} return n; } /* 64 x 32 ==> 32 unsigned division, using only 32 x 32 ==> 32 division as a primitive. */ static UInt divlu2(UInt u1, UInt u0, UInt v, UInt *r) { const UInt b = 65536; // Number base (16 bits). UInt un1, un0, // Norm. dividend LSD's. vn1, vn0, // Norm. divisor digits. q1, q0, // Quotient digits. un32, un21, un10, // Dividend digit pairs. rhat; // A remainder. Int s; // Shift amount for norm. if (u1 >= v) { // If overflow, set rem. if (r != NULL) // to an impossible value, *r = 0xFFFFFFFF; // and return the largest return 0xFFFFFFFF;} // possible quotient. s = nlz32(v); // 0 <= s <= 31. v = v << s; // Normalize divisor. vn1 = v >> 16; // Break divisor up into vn0 = v & 0xFFFF; // two 16-bit digits. un32 = (u1 << s) | ((u0 >> (32 - s)) & (-s >> 31)); un10 = u0 << s; // Shift dividend left. un1 = un10 >> 16; // Break right half of un0 = un10 & 0xFFFF; // dividend into two digits. q1 = un32/vn1; // Compute the first rhat = un32 - q1*vn1; // quotient digit, q1. again1: if (q1 >= b || q1*vn0 > b*rhat + un1) { q1 = q1 - 1; rhat = rhat + vn1; if (rhat < b) goto again1;} un21 = un32*b + un1 - q1*v; // Multiply and subtract. q0 = un21/vn1; // Compute the second rhat = un21 - q0*vn1; // quotient digit, q0. again2: if (q0 >= b || q0*vn0 > b*rhat + un0) { q0 = q0 - 1; rhat = rhat + vn1; if (rhat < b) goto again2;} if (r != NULL) // If remainder is wanted, *r = (un21*b + un0 - q0*v) >> s; // return it. return q1*b + q0; } /* 64 x 32 ==> 32 signed division, using only 32 x 32 ==> 32 division as a primitive. */ static Int divls(Int u1, UInt u0, Int v, Int *r) { Int q, uneg, vneg, diff, borrow; uneg = u1 >> 31; // -1 if u < 0. if (uneg) { // Compute the absolute u0 = -u0; // value of the dividend u. borrow = (u0 != 0); u1 = -u1 - borrow;} vneg = v >> 31; // -1 if v < 0. v = (v ^ vneg) - vneg; // Absolute value of v. if ((UInt)u1 >= (UInt)v) goto overflow; q = divlu2(u1, u0, v, (UInt *)r); diff = uneg ^ vneg; // Negate q if signs of q = (q ^ diff) - diff; // u and v differed. if (uneg && r != NULL) *r = -*r; if ((diff ^ q) < 0 && q != 0) { // If overflow, overflow: // set remainder if (r != NULL) // to an impossible value, *r = 0x80000000; // and return the largest q = 0x80000000;} // possible neg. quotient. return q; } /* This file contains a program for doing 64/64 ==> 64 division, on a machine that does not have that instruction but that does have instructions for "long division" (64/32 ==> 32). Code for unsigned division is given first, followed by a simple program for doing the signed version by using the unsigned version. These programs are useful in implementing "long long" (64-bit) arithmetic on a machine that has the long division instruction. It will work on 64- and 32-bit machines, provided the compiler implements long long's (64-bit integers). It is desirable that the machine have the Count Leading Zeros instruction. In the GNU world, these programs are known as __divdi3 and __udivdi3, and similar names are used here. This material is not in HD, but may be in a future edition. Max line length is 57, to fit in hacker.book. */ static Int nlz64(ULong x) { Int n; if (x == 0) return(64); n = 0; if (x <= 0x00000000FFFFFFFFULL) {n = n + 32; x = x << 32;} if (x <= 0x0000FFFFFFFFFFFFULL) {n = n + 16; x = x << 16;} if (x <= 0x00FFFFFFFFFFFFFFULL) {n = n + 8; x = x << 8;} if (x <= 0x0FFFFFFFFFFFFFFFULL) {n = n + 4; x = x << 4;} if (x <= 0x3FFFFFFFFFFFFFFFULL) {n = n + 2; x = x << 2;} if (x <= 0x7FFFFFFFFFFFFFFFULL) {n = n + 1;} return n; } // ---------------------------- udivdi3 -------------------------------- /* The variables u0, u1, etc. take on only 32-bit values, but they are declared long long to avoid some compiler warning messages and to avoid some unnecessary EXTRs that the compiler would put in, to convert long longs to ints. First the procedure takes care of the case in which the divisor is a 32-bit quantity. There are two subcases: (1) If the left half of the dividend is less than the divisor, one execution of DIVU is all that is required (overflow is not possible). (2) Otherwise it does two divisions, using the grade school method, with variables used as suggested below. q1 q0 ________ v) u1 u0 q1*v ____ k u0 */ /* These macros must be used with arguments of the appropriate type (unsigned long long for DIVU and long long for DIVS. They are simulations of the presumed machines ops. I.e., they look at only the low-order 32 bits of the divisor, they return garbage if the division overflows, and they return garbage in the high-order half of the quotient doubleword. In practice, these would be replaced with uses of the machine's DIVU and DIVS instructions (e.g., by using the GNU "asm" facility). */ static UInt DIVU ( ULong u, UInt v ) { UInt uHi = (UInt)(u >> 32); UInt uLo = (UInt)u; return divlu2(uHi, uLo, v, NULL); } static Int DIVS ( Long u, Int v ) { Int uHi = (Int)(u >> 32); UInt uLo = (UInt)u; return divls(uHi, uLo, v, NULL); } /* 64 x 64 ==> 64 unsigned division, using only 32 x 32 ==> 32 division as a primitive. */ static ULong udivdi3(ULong u, ULong v) { ULong u0, u1, v1, q0, q1, k, n; if (v >> 32 == 0) { // If v < 2**32: if (u >> 32 < v) // If u/v cannot overflow, return DIVU(u, v) // just do one division. & 0xFFFFFFFF; else { // If u/v would overflow: u1 = u >> 32; // Break u up into two u0 = u & 0xFFFFFFFF; // halves. q1 = DIVU(u1, v) // First quotient digit. & 0xFFFFFFFF; k = u1 - q1*v; // First remainder, < v. q0 = DIVU((k << 32) + u0, v) // 2nd quot. digit. & 0xFFFFFFFF; return (q1 << 32) + q0; } } // Here v >= 2**32. n = nlz64(v); // 0 <= n <= 31. v1 = (v << n) >> 32; // Normalize the divisor // so its MSB is 1. u1 = u >> 1; // To ensure no overflow. q1 = DIVU(u1, v1) // Get quotient from & 0xFFFFFFFF; // divide unsigned insn. q0 = (q1 << n) >> 31; // Undo normalization and // division of u by 2. if (q0 != 0) // Make q0 correct or q0 = q0 - 1; // too small by 1. if ((u - q0*v) >= v) q0 = q0 + 1; // Now q0 is correct. return q0; } // ----------------------------- divdi3 -------------------------------- /* This routine presumes that smallish cases (those which can be done in one execution of DIVS) are common. If this is not the case, the test for this case should be deleted. Note that the test for when DIVS can be used is not entirely accurate. For example, DIVS is not used if v = 0xFFFFFFFF8000000, whereas if could be (if u is sufficiently small in magnitude). */ // ------------------------------ cut ---------------------------------- static ULong my_llabs ( Long x ) { ULong t = x >> 63; return (x ^ t) - t; } /* 64 x 64 ==> 64 signed division, using only 32 x 32 ==> 32 division as a primitive. */ static Long divdi3(Long u, Long v) { ULong au, av; Long q, t; au = my_llabs(u); av = my_llabs(v); if (av >> 31 == 0) { // If |v| < 2**31 and // if (v << 32 >> 32 == v) { // If v is in range and if (au < av << 31) { // |u|/|v| cannot q = DIVS(u, v); // overflow, use DIVS. return (q << 32) >> 32; } } q = udivdi3(au,av); // Invoke udivdi3. t = (u ^ v) >> 63; // If u, v have different return (q ^ t) - t; // signs, negate q. } // ---------------------------- end cut -------------------------------- ULong __udivdi3 (ULong u, ULong v); ULong __udivdi3 (ULong u, ULong v) { return udivdi3(u,v); } Long __divdi3 (Long u, Long v); Long __divdi3 (Long u, Long v) { return divdi3(u,v); } ULong __umoddi3 (ULong u, ULong v); ULong __umoddi3 (ULong u, ULong v) { ULong q = __udivdi3(u, v); ULong r = u - q * v; return r; } Long __moddi3 (Long u, Long v); Long __moddi3 (Long u, Long v) { Long q = __divdi3(u, v); Long r = u - q * v; return r; } /* ------------------------------------------------ ld_classic: Undefined symbols: ___fixunsdfdi ------------------------------------------------ */ /* ===-- fixunsdfdi.c - Implement __fixunsdfdi -----------------------------=== * * The LLVM Compiler Infrastructure * * This file is dual licensed under the MIT and the University of Illinois Open * Source Licenses. See LICENSE.TXT for details. * * ===----------------------------------------------------------------------=== * * This file implements __fixunsdfdi for the compiler_rt library. * * ===----------------------------------------------------------------------=== */ /* As per http://www.gnu.org/licenses/license-list.html#GPLCompatibleLicenses, the "NCSA/University of Illinois Open Source License" is compatible with the GPL (both version 2 and 3). What is claimed to be compatible is this http://www.opensource.org/licenses/UoI-NCSA.php and the LLVM documentation at http://www.llvm.org/docs/DeveloperPolicy.html#license says all the code in LLVM is available under the University of Illinois/NCSA Open Source License, at this URL http://www.opensource.org/licenses/UoI-NCSA.php viz, the same one that the FSF pages claim is compatible. So I think it's OK to include it. */ /* Returns: convert a to a unsigned long long, rounding toward zero. * Negative values all become zero. */ /* Assumption: double is a IEEE 64 bit floating point type * du_int is a 64 bit integral type * value in double is representable in du_int or is negative * (no range checking performed) */ /* seee eeee eeee mmmm mmmm mmmm mmmm mmmm | mmmm mmmm mmmm mmmm mmmm mmmm mmmm mmmm */ typedef unsigned long long du_int; typedef unsigned su_int; typedef union { du_int all; struct { #if VG_LITTLEENDIAN su_int low; su_int high; #else su_int high; su_int low; #endif /* VG_LITTLEENDIAN */ }s; } udwords; typedef union { udwords u; double f; } double_bits; du_int __fixunsdfdi(double a); du_int __fixunsdfdi(double a) { double_bits fb; fb.f = a; int e = ((fb.u.s.high & 0x7FF00000) >> 20) - 1023; if (e < 0 || (fb.u.s.high & 0x80000000)) return 0; udwords r; r.s.high = (fb.u.s.high & 0x000FFFFF) | 0x00100000; r.s.low = fb.u.s.low; if (e > 52) r.all <<= (e - 52); else r.all >>= (52 - e); return r.all; } #endif /*--------------------------------------------------------------------*/ /*--- end ---*/ /*--------------------------------------------------------------------*/
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/valgrind_12854-12855.c
manybugs_data_71
/* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library. * * Directory Read Support Routines. */ #include "tiffiop.h" #define IGNORE 0 /* tag placeholder used below */ #ifdef HAVE_IEEEFP # define TIFFCvtIEEEFloatToNative(tif, n, fp) # define TIFFCvtIEEEDoubleToNative(tif, n, dp) #else extern void TIFFCvtIEEEFloatToNative(TIFF*, uint32, float*); extern void TIFFCvtIEEEDoubleToNative(TIFF*, uint32, double*); #endif static int EstimateStripByteCounts(TIFF*, TIFFDirEntry*, uint16); static void MissingRequired(TIFF*, const char*); static int CheckDirCount(TIFF*, TIFFDirEntry*, uint32); static tsize_t TIFFFetchData(TIFF*, TIFFDirEntry*, char*); static tsize_t TIFFFetchString(TIFF*, TIFFDirEntry*, char*); static float TIFFFetchRational(TIFF*, TIFFDirEntry*); static int TIFFFetchNormalTag(TIFF*, TIFFDirEntry*); static int TIFFFetchPerSampleShorts(TIFF*, TIFFDirEntry*, uint16*); static int TIFFFetchPerSampleLongs(TIFF*, TIFFDirEntry*, uint32*); static int TIFFFetchPerSampleAnys(TIFF*, TIFFDirEntry*, double*); static int TIFFFetchShortArray(TIFF*, TIFFDirEntry*, uint16*); static int TIFFFetchStripThing(TIFF*, TIFFDirEntry*, long, uint32**); static int TIFFFetchRefBlackWhite(TIFF*, TIFFDirEntry*); static float TIFFFetchFloat(TIFF*, TIFFDirEntry*); static int TIFFFetchFloatArray(TIFF*, TIFFDirEntry*, float*); static int TIFFFetchDoubleArray(TIFF*, TIFFDirEntry*, double*); static int TIFFFetchAnyArray(TIFF*, TIFFDirEntry*, double*); static int TIFFFetchShortPair(TIFF*, TIFFDirEntry*); static void ChopUpSingleUncompressedStrip(TIFF*); /* * Read the next TIFF directory from a file * and convert it to the internal format. * We read directories sequentially. */ int TIFFReadDirectory(TIFF* tif) { static const char module[] = "TIFFReadDirectory"; int n; TIFFDirectory* td; TIFFDirEntry *dp, *dir = NULL; uint16 iv; uint32 v; const TIFFFieldInfo* fip; size_t fix; uint16 dircount; toff_t nextdiroff; int diroutoforderwarning = 0; toff_t* new_dirlist; tif->tif_diroff = tif->tif_nextdiroff; if (tif->tif_diroff == 0) /* no more directories */ return (0); /* * XXX: Trick to prevent IFD looping. The one can create TIFF file * with looped directory pointers. We will maintain a list of already * seen directories and check every IFD offset against this list. */ for (n = 0; n < tif->tif_dirnumber; n++) { if (tif->tif_dirlist[n] == tif->tif_diroff) return (0); } tif->tif_dirnumber++; new_dirlist = (toff_t *)_TIFFrealloc(tif->tif_dirlist, tif->tif_dirnumber * sizeof(toff_t)); if (!new_dirlist) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Failed to allocate space for IFD list", tif->tif_name); return (0); } tif->tif_dirlist = new_dirlist; tif->tif_dirlist[tif->tif_dirnumber - 1] = tif->tif_diroff; /* * Cleanup any previous compression state. */ (*tif->tif_cleanup)(tif); tif->tif_curdir++; nextdiroff = 0; if (!isMapped(tif)) { if (!SeekOK(tif, tif->tif_diroff)) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Seek error accessing TIFF directory", tif->tif_name); return (0); } if (!ReadOK(tif, &dircount, sizeof (uint16))) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Can not read TIFF directory count", tif->tif_name); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); dir = (TIFFDirEntry *)_TIFFCheckMalloc(tif, dircount, sizeof (TIFFDirEntry), "to read TIFF directory"); if (dir == NULL) return (0); if (!ReadOK(tif, dir, dircount*sizeof (TIFFDirEntry))) { TIFFErrorExt(tif->tif_clientdata, module, "%.100s: Can not read TIFF directory", tif->tif_name); goto bad; } /* * Read offset to next directory for sequential scans. */ (void) ReadOK(tif, &nextdiroff, sizeof (uint32)); } else { toff_t off = tif->tif_diroff; if (off + sizeof (uint16) > tif->tif_size) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Can not read TIFF directory count", tif->tif_name); return (0); } else _TIFFmemcpy(&dircount, tif->tif_base + off, sizeof (uint16)); off += sizeof (uint16); if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); dir = (TIFFDirEntry *)_TIFFCheckMalloc(tif, dircount, sizeof (TIFFDirEntry), "to read TIFF directory"); if (dir == NULL) return (0); if (off + dircount*sizeof (TIFFDirEntry) > tif->tif_size) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Can not read TIFF directory", tif->tif_name); goto bad; } else { _TIFFmemcpy(dir, tif->tif_base + off, dircount*sizeof (TIFFDirEntry)); } off += dircount* sizeof (TIFFDirEntry); if (off + sizeof (uint32) <= tif->tif_size) _TIFFmemcpy(&nextdiroff, tif->tif_base+off, sizeof (uint32)); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong(&nextdiroff); tif->tif_nextdiroff = nextdiroff; tif->tif_flags &= ~TIFF_BEENWRITING; /* reset before new dir */ /* * Setup default value and then make a pass over * the fields to check type and tag information, * and to extract info required to size data * structures. A second pass is made afterwards * to read in everthing not taken in the first pass. */ td = &tif->tif_dir; /* free any old stuff and reinit */ TIFFFreeDirectory(tif); TIFFDefaultDirectory(tif); /* * Electronic Arts writes gray-scale TIFF files * without a PlanarConfiguration directory entry. * Thus we setup a default value here, even though * the TIFF spec says there is no default value. */ TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); /* * Sigh, we must make a separate pass through the * directory for the following reason: * * We must process the Compression tag in the first pass * in order to merge in codec-private tag definitions (otherwise * we may get complaints about unknown tags). However, the * Compression tag may be dependent on the SamplesPerPixel * tag value because older TIFF specs permited Compression * to be written as a SamplesPerPixel-count tag entry. * Thus if we don't first figure out the correct SamplesPerPixel * tag value then we may end up ignoring the Compression tag * value because it has an incorrect count value (if the * true value of SamplesPerPixel is not 1). * * It sure would have been nice if Aldus had really thought * this stuff through carefully. */ for (dp = dir, n = dircount; n > 0; n--, dp++) { if (tif->tif_flags & TIFF_SWAB) { TIFFSwabArrayOfShort(&dp->tdir_tag, 2); TIFFSwabArrayOfLong(&dp->tdir_count, 2); } if (dp->tdir_tag == TIFFTAG_SAMPLESPERPIXEL) { if (!TIFFFetchNormalTag(tif, dp)) goto bad; dp->tdir_tag = IGNORE; } } /* * First real pass over the directory. */ fix = 0; for (dp = dir, n = dircount; n > 0; n--, dp++) { if (fix >= tif->tif_nfields || dp->tdir_tag == IGNORE) continue; /* * Silicon Beach (at least) writes unordered * directory tags (violating the spec). Handle * it here, but be obnoxious (maybe they'll fix it?). */ if (dp->tdir_tag < tif->tif_fieldinfo[fix]->field_tag) { if (!diroutoforderwarning) { TIFFWarningExt(tif->tif_clientdata, module, "%s: invalid TIFF directory; tags are not sorted in ascending order", tif->tif_name); diroutoforderwarning = 1; } fix = 0; /* O(n^2) */ } while (fix < tif->tif_nfields && tif->tif_fieldinfo[fix]->field_tag < dp->tdir_tag) fix++; if (fix >= tif->tif_nfields || tif->tif_fieldinfo[fix]->field_tag != dp->tdir_tag) { TIFFWarningExt(tif->tif_clientdata, module, "%s: unknown field with tag %d (0x%x) encountered", tif->tif_name, dp->tdir_tag, dp->tdir_tag, dp->tdir_type); TIFFMergeFieldInfo( tif, _TIFFCreateAnonFieldInfo( tif, dp->tdir_tag, (TIFFDataType) dp->tdir_type ), 1 ); fix = 0; while (fix < tif->tif_nfields && tif->tif_fieldinfo[fix]->field_tag < dp->tdir_tag) fix++; } /* * Null out old tags that we ignore. */ if (tif->tif_fieldinfo[fix]->field_bit == FIELD_IGNORE) { ignore: dp->tdir_tag = IGNORE; continue; } /* * Check data type. */ fip = tif->tif_fieldinfo[fix]; while (dp->tdir_type != (unsigned short) fip->field_type && fix < tif->tif_nfields) { if (fip->field_type == TIFF_ANY) /* wildcard */ break; fip = tif->tif_fieldinfo[++fix]; if (fix >= tif->tif_nfields || fip->field_tag != dp->tdir_tag) { TIFFWarningExt(tif->tif_clientdata, module, "%s: wrong data type %d for \"%s\"; tag ignored", tif->tif_name, dp->tdir_type, tif->tif_fieldinfo[fix-1]->field_name); goto ignore; } } /* * Check count if known in advance. */ if (fip->field_readcount != TIFF_VARIABLE && fip->field_readcount != TIFF_VARIABLE2) { uint32 expected = (fip->field_readcount == TIFF_SPP) ? (uint32) td->td_samplesperpixel : (uint32) fip->field_readcount; if (!CheckDirCount(tif, dp, expected)) goto ignore; } switch (dp->tdir_tag) { case TIFFTAG_COMPRESSION: /* * The 5.0 spec says the Compression tag has * one value, while earlier specs say it has * one value per sample. Because of this, we * accept the tag if one value is supplied. */ if (dp->tdir_count == 1) { v = TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset); if (!TIFFSetField(tif, dp->tdir_tag, (uint16)v)) goto bad; break; /* XXX: workaround for broken TIFFs */ } else if (dp->tdir_type == TIFF_LONG) { if (!TIFFFetchPerSampleLongs(tif, dp, &v) || !TIFFSetField(tif, dp->tdir_tag, (uint16)v)) goto bad; } else { if (!TIFFFetchPerSampleShorts(tif, dp, &iv) || !TIFFSetField(tif, dp->tdir_tag, iv)) goto bad; } dp->tdir_tag = IGNORE; break; case TIFFTAG_STRIPOFFSETS: case TIFFTAG_STRIPBYTECOUNTS: case TIFFTAG_TILEOFFSETS: case TIFFTAG_TILEBYTECOUNTS: TIFFSetFieldBit(tif, fip->field_bit); break; case TIFFTAG_IMAGEWIDTH: case TIFFTAG_IMAGELENGTH: case TIFFTAG_IMAGEDEPTH: case TIFFTAG_TILELENGTH: case TIFFTAG_TILEWIDTH: case TIFFTAG_TILEDEPTH: case TIFFTAG_PLANARCONFIG: case TIFFTAG_ROWSPERSTRIP: case TIFFTAG_EXTRASAMPLES: if (!TIFFFetchNormalTag(tif, dp)) goto bad; dp->tdir_tag = IGNORE; break; } } /* * Allocate directory structure and setup defaults. */ if (!TIFFFieldSet(tif, FIELD_IMAGEDIMENSIONS)) { MissingRequired(tif, "ImageLength"); goto bad; } if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG)) { MissingRequired(tif, "PlanarConfiguration"); goto bad; } /* * Setup appropriate structures (by strip or by tile) */ if (!TIFFFieldSet(tif, FIELD_TILEDIMENSIONS)) { td->td_nstrips = TIFFNumberOfStrips(tif); td->td_tilewidth = td->td_imagewidth; td->td_tilelength = td->td_rowsperstrip; td->td_tiledepth = td->td_imagedepth; tif->tif_flags &= ~TIFF_ISTILED; } else { td->td_nstrips = TIFFNumberOfTiles(tif); tif->tif_flags |= TIFF_ISTILED; } if (!td->td_nstrips) { TIFFErrorExt(tif->tif_clientdata, module, "%s: cannot handle zero number of %s", tif->tif_name, isTiled(tif) ? "tiles" : "strips"); goto bad; } td->td_stripsperimage = td->td_nstrips; if (td->td_planarconfig == PLANARCONFIG_SEPARATE) td->td_stripsperimage /= td->td_samplesperpixel; if (!TIFFFieldSet(tif, FIELD_STRIPOFFSETS)) { MissingRequired(tif, isTiled(tif) ? "TileOffsets" : "StripOffsets"); goto bad; } /* * Second pass: extract other information. */ for (dp = dir, n = dircount; n > 0; n--, dp++) { if (dp->tdir_tag == IGNORE) continue; switch (dp->tdir_tag) { case TIFFTAG_MINSAMPLEVALUE: case TIFFTAG_MAXSAMPLEVALUE: case TIFFTAG_BITSPERSAMPLE: case TIFFTAG_DATATYPE: case TIFFTAG_SAMPLEFORMAT: /* * The 5.0 spec says the Compression tag has * one value, while earlier specs say it has * one value per sample. Because of this, we * accept the tag if one value is supplied. * * The MinSampleValue, MaxSampleValue, BitsPerSample * DataType and SampleFormat tags are supposed to be * written as one value/sample, but some vendors * incorrectly write one value only -- so we accept * that as well (yech). Other vendors write correct * value for NumberOfSamples, but incorrect one for * BitsPerSample and friends, and we will read this * too. */ if (dp->tdir_count == 1) { v = TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset); if (!TIFFSetField(tif, dp->tdir_tag, (uint16)v)) goto bad; /* XXX: workaround for broken TIFFs */ } else if (dp->tdir_tag == TIFFTAG_BITSPERSAMPLE && dp->tdir_type == TIFF_LONG) { if (!TIFFFetchPerSampleLongs(tif, dp, &v) || !TIFFSetField(tif, dp->tdir_tag, (uint16)v)) goto bad; } else { if (!TIFFFetchPerSampleShorts(tif, dp, &iv) || !TIFFSetField(tif, dp->tdir_tag, iv)) goto bad; } break; case TIFFTAG_SMINSAMPLEVALUE: case TIFFTAG_SMAXSAMPLEVALUE: { double dv = 0.0; if (!TIFFFetchPerSampleAnys(tif, dp, &dv) || !TIFFSetField(tif, dp->tdir_tag, dv)) goto bad; } break; case TIFFTAG_STRIPOFFSETS: case TIFFTAG_TILEOFFSETS: if (!TIFFFetchStripThing(tif, dp, td->td_nstrips, &td->td_stripoffset)) goto bad; break; case TIFFTAG_STRIPBYTECOUNTS: case TIFFTAG_TILEBYTECOUNTS: if (!TIFFFetchStripThing(tif, dp, td->td_nstrips, &td->td_stripbytecount)) goto bad; break; case TIFFTAG_COLORMAP: case TIFFTAG_TRANSFERFUNCTION: { char* cp; /* * TransferFunction can have either 1x or 3x * data values; Colormap can have only 3x * items. */ v = 1L<<td->td_bitspersample; if (dp->tdir_tag == TIFFTAG_COLORMAP || dp->tdir_count != v) { if (!CheckDirCount(tif, dp, 3 * v)) break; } v *= sizeof(uint16); cp = (char *)_TIFFCheckMalloc(tif, dp->tdir_count, sizeof (uint16), "to read \"TransferFunction\" tag"); if (cp != NULL) { if (TIFFFetchData(tif, dp, cp)) { /* * This deals with there being * only one array to apply to * all samples. */ uint32 c = 1L << td->td_bitspersample; if (dp->tdir_count == c) v = 0L; TIFFSetField(tif, dp->tdir_tag, cp, cp+v, cp+2*v); } _TIFFfree(cp); } break; } case TIFFTAG_PAGENUMBER: case TIFFTAG_HALFTONEHINTS: case TIFFTAG_YCBCRSUBSAMPLING: case TIFFTAG_DOTRANGE: (void) TIFFFetchShortPair(tif, dp); break; case TIFFTAG_REFERENCEBLACKWHITE: (void) TIFFFetchRefBlackWhite(tif, dp); break; /* BEGIN REV 4.0 COMPATIBILITY */ case TIFFTAG_OSUBFILETYPE: v = 0L; switch (TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset)) { case OFILETYPE_REDUCEDIMAGE: v = FILETYPE_REDUCEDIMAGE; break; case OFILETYPE_PAGE: v = FILETYPE_PAGE; break; } if (v) TIFFSetField(tif, TIFFTAG_SUBFILETYPE, v); break; /* END REV 4.0 COMPATIBILITY */ default: (void) TIFFFetchNormalTag(tif, dp); break; } } /* * Verify Palette image has a Colormap. */ if (td->td_photometric == PHOTOMETRIC_PALETTE && !TIFFFieldSet(tif, FIELD_COLORMAP)) { MissingRequired(tif, "Colormap"); goto bad; } /* * Attempt to deal with a missing StripByteCounts tag. */ if (!TIFFFieldSet(tif, FIELD_STRIPBYTECOUNTS)) { /* * Some manufacturers violate the spec by not giving * the size of the strips. In this case, assume there * is one uncompressed strip of data. */ if ((td->td_planarconfig == PLANARCONFIG_CONTIG && td->td_nstrips > 1) || (td->td_planarconfig == PLANARCONFIG_SEPARATE && td->td_nstrips != td->td_samplesperpixel)) { MissingRequired(tif, "StripByteCounts"); goto bad; } TIFFWarningExt(tif->tif_clientdata, module, "%s: TIFF directory is missing required " "\"%s\" field, calculating from imagelength", tif->tif_name, _TIFFFieldWithTag(tif,TIFFTAG_STRIPBYTECOUNTS)->field_name); if (EstimateStripByteCounts(tif, dir, dircount) < 0) goto bad; /* * Assume we have wrong StripByteCount value (in case of single strip) in * following cases: * - it is equal to zero along with StripOffset; * - it is larger than file itself (in case of uncompressed image); * - it is smaller than the size of the bytes per row multiplied on the * number of rows. The last case should not be checked in the case of * writing new image, because we may do not know the exact strip size * until the whole image will be written and directory dumped out. */ #define BYTECOUNTLOOKSBAD \ ( (td->td_stripbytecount[0] == 0 && td->td_stripoffset[0] != 0) || \ (td->td_compression == COMPRESSION_NONE && \ td->td_stripbytecount[0] > TIFFGetFileSize(tif) - td->td_stripoffset[0]) || \ (tif->tif_mode == O_RDONLY && \ td->td_compression == COMPRESSION_NONE && \ td->td_stripbytecount[0] < TIFFScanlineSize(tif) * td->td_imagelength) ) } else if (td->td_nstrips == 1 && td->td_stripoffset[0] != 0 && BYTECOUNTLOOKSBAD) { /* * XXX: Plexus (and others) sometimes give a value of zero for * a tag when they don't know what the correct value is! Try * and handle the simple case of estimating the size of a one * strip image. */ TIFFWarningExt(tif->tif_clientdata, module, "%s: Bogus \"%s\" field, ignoring and calculating from imagelength", tif->tif_name, _TIFFFieldWithTag(tif,TIFFTAG_STRIPBYTECOUNTS)->field_name); if(EstimateStripByteCounts(tif, dir, dircount) < 0) goto bad; } else if (td->td_planarconfig == PLANARCONFIG_CONTIG && td->td_nstrips > 2 && td->td_compression == COMPRESSION_NONE && td->td_stripbytecount[0] != td->td_stripbytecount[1]) { /* * XXX: Some vendors fill StripByteCount array with absolutely * wrong values (it can be equal to StripOffset array, for * example). Catch this case here. */ TIFFWarningExt(tif->tif_clientdata, module, "%s: Wrong \"%s\" field, ignoring and calculating from imagelength", tif->tif_name, _TIFFFieldWithTag(tif,TIFFTAG_STRIPBYTECOUNTS)->field_name); if (EstimateStripByteCounts(tif, dir, dircount) < 0) goto bad; } if (dir) { _TIFFfree((char *)dir); dir = NULL; } if (!TIFFFieldSet(tif, FIELD_MAXSAMPLEVALUE)) td->td_maxsamplevalue = (uint16)((1L<<td->td_bitspersample)-1); /* * Setup default compression scheme. */ /* * XXX: We can optimize checking for the strip bounds using the sorted * bytecounts array. See also comments for TIFFAppendToStrip() * function in tif_write.c. */ if (td->td_nstrips > 1) { tstrip_t strip; td->td_stripbytecountsorted = 1; for (strip = 1; strip < td->td_nstrips; strip++) { if (td->td_stripoffset[strip - 1] > td->td_stripoffset[strip]) { td->td_stripbytecountsorted = 0; break; } } } if (!TIFFFieldSet(tif, FIELD_COMPRESSION)) TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE); /* * Some manufacturers make life difficult by writing * large amounts of uncompressed data as a single strip. * This is contrary to the recommendations of the spec. * The following makes an attempt at breaking such images * into strips closer to the recommended 8k bytes. A * side effect, however, is that the RowsPerStrip tag * value may be changed. */ if (td->td_nstrips == 1 && td->td_compression == COMPRESSION_NONE && (tif->tif_flags & (TIFF_STRIPCHOP|TIFF_ISTILED)) == TIFF_STRIPCHOP) ChopUpSingleUncompressedStrip(tif); /* * Reinitialize i/o since we are starting on a new directory. */ tif->tif_row = (uint32) -1; tif->tif_curstrip = (tstrip_t) -1; tif->tif_col = (uint32) -1; tif->tif_curtile = (ttile_t) -1; tif->tif_tilesize = (tsize_t) -1; tif->tif_scanlinesize = TIFFScanlineSize(tif); if (!tif->tif_scanlinesize) { TIFFErrorExt(tif->tif_clientdata, module, "%s: cannot handle zero scanline size", tif->tif_name); return (0); } if (isTiled(tif)) { tif->tif_tilesize = TIFFTileSize(tif); if (!tif->tif_tilesize) { TIFFErrorExt(tif->tif_clientdata, module, "%s: cannot handle zero tile size", tif->tif_name); return (0); } } else { if (!TIFFStripSize(tif)) { TIFFErrorExt(tif->tif_clientdata, module, "%s: cannot handle zero strip size", tif->tif_name); return (0); } } return (1); bad: if (dir) _TIFFfree(dir); return (0); } /* * Read custom directory from the arbitarry offset. * The code is very similar to TIFFReadDirectory(). */ int TIFFReadCustomDirectory(TIFF* tif, toff_t diroff, const TIFFFieldInfo info[], size_t n) { static const char module[] = "TIFFReadCustomDirectory"; TIFFDirectory* td = &tif->tif_dir; TIFFDirEntry *dp, *dir = NULL; const TIFFFieldInfo* fip; size_t fix; uint16 i, dircount; _TIFFSetupFieldInfo(tif, info, n); tif->tif_diroff = diroff; if (!isMapped(tif)) { if (!SeekOK(tif, diroff)) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Seek error accessing TIFF directory", tif->tif_name); return (0); } if (!ReadOK(tif, &dircount, sizeof (uint16))) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Can not read TIFF directory count", tif->tif_name); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); dir = (TIFFDirEntry *)_TIFFCheckMalloc(tif, dircount, sizeof (TIFFDirEntry), "to read TIFF directory"); if (dir == NULL) return (0); if (!ReadOK(tif, dir, dircount * sizeof (TIFFDirEntry))) { TIFFErrorExt(tif->tif_clientdata, module, "%.100s: Can not read TIFF directory", tif->tif_name); goto bad; } } else { toff_t off = diroff; if (off + sizeof (uint16) > tif->tif_size) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Can not read TIFF directory count", tif->tif_name); return (0); } else _TIFFmemcpy(&dircount, tif->tif_base + off, sizeof (uint16)); off += sizeof (uint16); if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); dir = (TIFFDirEntry *)_TIFFCheckMalloc(tif, dircount, sizeof (TIFFDirEntry), "to read TIFF directory"); if (dir == NULL) return (0); if (off + dircount * sizeof (TIFFDirEntry) > tif->tif_size) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Can not read TIFF directory", tif->tif_name); goto bad; } else { _TIFFmemcpy(dir, tif->tif_base + off, dircount * sizeof (TIFFDirEntry)); } } TIFFFreeDirectory(tif); fix = 0; for (dp = dir, i = dircount; i > 0; i--, dp++) { if (tif->tif_flags & TIFF_SWAB) { TIFFSwabArrayOfShort(&dp->tdir_tag, 2); TIFFSwabArrayOfLong(&dp->tdir_count, 2); } if (fix >= tif->tif_nfields || dp->tdir_tag == IGNORE) continue; while (fix < tif->tif_nfields && tif->tif_fieldinfo[fix]->field_tag < dp->tdir_tag) fix++; if (fix >= tif->tif_nfields || tif->tif_fieldinfo[fix]->field_tag != dp->tdir_tag) { TIFFWarningExt(tif->tif_clientdata, module, "%s: unknown field with tag %d (0x%x) encountered", tif->tif_name, dp->tdir_tag, dp->tdir_tag, dp->tdir_type); TIFFMergeFieldInfo(tif, _TIFFCreateAnonFieldInfo(tif, dp->tdir_tag, (TIFFDataType)dp->tdir_type), 1); fix = 0; while (fix < tif->tif_nfields && tif->tif_fieldinfo[fix]->field_tag < dp->tdir_tag) fix++; } /* * Null out old tags that we ignore. */ if (tif->tif_fieldinfo[fix]->field_bit == FIELD_IGNORE) { ignore: dp->tdir_tag = IGNORE; continue; } /* * Check data type. */ fip = tif->tif_fieldinfo[fix]; while (dp->tdir_type != (unsigned short) fip->field_type && fix < tif->tif_nfields) { if (fip->field_type == TIFF_ANY) /* wildcard */ break; fip = tif->tif_fieldinfo[++fix]; if (fix >= tif->tif_nfields || fip->field_tag != dp->tdir_tag) { TIFFWarningExt(tif->tif_clientdata, module, "%s: wrong data type %d for \"%s\"; tag ignored", tif->tif_name, dp->tdir_type, tif->tif_fieldinfo[fix-1]->field_name); goto ignore; } } /* * Check count if known in advance. */ if (fip->field_readcount != TIFF_VARIABLE && fip->field_readcount != TIFF_VARIABLE2) { uint32 expected = (fip->field_readcount == TIFF_SPP) ? (uint32) td->td_samplesperpixel : (uint32) fip->field_readcount; if (!CheckDirCount(tif, dp, expected)) goto ignore; } (void) TIFFFetchNormalTag(tif, dp); } if (dir) _TIFFfree(dir); return 1; bad: if (dir) _TIFFfree(dir); return 0; } /* * EXIF is important special case of custom IFD, so we have a special * function to read it. */ int TIFFReadEXIFDirectory(TIFF* tif, toff_t diroff) { size_t exifFieldInfoCount; const TIFFFieldInfo *exifFieldInfo = _TIFFGetExifFieldInfo(&exifFieldInfoCount); return TIFFReadCustomDirectory(tif, diroff, exifFieldInfo, exifFieldInfoCount); } static int EstimateStripByteCounts(TIFF* tif, TIFFDirEntry* dir, uint16 dircount) { static const char module[] = "EstimateStripByteCounts"; register TIFFDirEntry *dp; register TIFFDirectory *td = &tif->tif_dir; uint16 i; if (td->td_stripbytecount) _TIFFfree(td->td_stripbytecount); td->td_stripbytecount = (uint32*) _TIFFCheckMalloc(tif, td->td_nstrips, sizeof (uint32), "for \"StripByteCounts\" array"); if (td->td_compression != COMPRESSION_NONE) { uint32 space = (uint32)(sizeof (TIFFHeader) + sizeof (uint16) + (dircount * sizeof (TIFFDirEntry)) + sizeof (uint32)); toff_t filesize = TIFFGetFileSize(tif); uint16 n; /* calculate amount of space used by indirect values */ for (dp = dir, n = dircount; n > 0; n--, dp++) { uint32 cc = TIFFDataWidth((TIFFDataType) dp->tdir_type); if (cc == 0) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Cannot determine size of unknown tag type %d", tif->tif_name, dp->tdir_type); return -1; } cc = cc * dp->tdir_count; if (cc > sizeof (uint32)) space += cc; } space = filesize - space; if (td->td_planarconfig == PLANARCONFIG_SEPARATE) space /= td->td_samplesperpixel; for (i = 0; i < td->td_nstrips; i++) td->td_stripbytecount[i] = space; /* * This gross hack handles the case were the offset to * the last strip is past the place where we think the strip * should begin. Since a strip of data must be contiguous, * it's safe to assume that we've overestimated the amount * of data in the strip and trim this number back accordingly. */ i--; if (((toff_t)(td->td_stripoffset[i]+td->td_stripbytecount[i])) > filesize) td->td_stripbytecount[i] = filesize - td->td_stripoffset[i]; } else { uint32 rowbytes = TIFFScanlineSize(tif); uint32 rowsperstrip = td->td_imagelength/td->td_stripsperimage; for (i = 0; i < td->td_nstrips; i++) td->td_stripbytecount[i] = rowbytes*rowsperstrip; } TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS); if (!TIFFFieldSet(tif, FIELD_ROWSPERSTRIP)) td->td_rowsperstrip = td->td_imagelength; return 1; } static void MissingRequired(TIFF* tif, const char* tagname) { static const char module[] = "MissingRequired"; TIFFErrorExt(tif->tif_clientdata, module, "%s: TIFF directory is missing required \"%s\" field", tif->tif_name, tagname); } /* * Check the count field of a directory * entry against a known value. The caller * is expected to skip/ignore the tag if * there is a mismatch. */ static int CheckDirCount(TIFF* tif, TIFFDirEntry* dir, uint32 count) { if (count > dir->tdir_count) { TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "incorrect count for field \"%s\" (%lu, expecting %lu); tag ignored", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name, dir->tdir_count, count); return (0); } else if (count < dir->tdir_count) { TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "incorrect count for field \"%s\" (%lu, expecting %lu); tag trimmed", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name, dir->tdir_count, count); return (1); } return (1); } /* * Fetch a contiguous directory item. */ static tsize_t TIFFFetchData(TIFF* tif, TIFFDirEntry* dir, char* cp) { int w = TIFFDataWidth((TIFFDataType) dir->tdir_type); tsize_t cc = dir->tdir_count * w; /* Check for overflow. */ if (!dir->tdir_count || !w || (tsize_t)dir->tdir_count / w != cc) goto bad; if (!isMapped(tif)) { if (!SeekOK(tif, dir->tdir_offset)) goto bad; if (!ReadOK(tif, cp, cc)) goto bad; } else { tsize_t offset = dir->tdir_offset + cc; /* Check for overflow. */ if ((tsize_t)dir->tdir_offset != offset - cc || offset > (tsize_t)tif->tif_size) goto bad; _TIFFmemcpy(cp, tif->tif_base + dir->tdir_offset, cc); } if (tif->tif_flags & TIFF_SWAB) { switch (dir->tdir_type) { case TIFF_SHORT: case TIFF_SSHORT: TIFFSwabArrayOfShort((uint16*) cp, dir->tdir_count); break; case TIFF_LONG: case TIFF_SLONG: case TIFF_FLOAT: TIFFSwabArrayOfLong((uint32*) cp, dir->tdir_count); break; case TIFF_RATIONAL: case TIFF_SRATIONAL: TIFFSwabArrayOfLong((uint32*) cp, 2*dir->tdir_count); break; case TIFF_DOUBLE: TIFFSwabArrayOfDouble((double*) cp, dir->tdir_count); break; } } return (cc); bad: TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error fetching data for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); return (tsize_t) 0; } /* * Fetch an ASCII item from the file. */ static tsize_t TIFFFetchString(TIFF* tif, TIFFDirEntry* dir, char* cp) { if (dir->tdir_count <= 4) { uint32 l = dir->tdir_offset; if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong(&l); _TIFFmemcpy(cp, &l, dir->tdir_count); return (1); } return (TIFFFetchData(tif, dir, cp)); } /* * Convert numerator+denominator to float. */ static int cvtRational(TIFF* tif, TIFFDirEntry* dir, uint32 num, uint32 denom, float* rv) { if (denom == 0) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "%s: Rational with zero denominator (num = %lu)", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name, num); return (0); } else { if (dir->tdir_type == TIFF_RATIONAL) *rv = ((float)num / (float)denom); else *rv = ((float)(int32)num / (float)(int32)denom); return (1); } } /* * Fetch a rational item from the file * at offset off and return the value * as a floating point number. */ static float TIFFFetchRational(TIFF* tif, TIFFDirEntry* dir) { uint32 l[2]; float v; return (!TIFFFetchData(tif, dir, (char *)l) || !cvtRational(tif, dir, l[0], l[1], &v) ? 1.0f : v); } /* * Fetch a single floating point value * from the offset field and return it * as a native float. */ static float TIFFFetchFloat(TIFF* tif, TIFFDirEntry* dir) { float v; int32 l = TIFFExtractData(tif, dir->tdir_type, dir->tdir_offset); _TIFFmemcpy(&v, &l, sizeof(float)); TIFFCvtIEEEFloatToNative(tif, 1, &v); return (v); } /* * Fetch an array of BYTE or SBYTE values. */ static int TIFFFetchByteArray(TIFF* tif, TIFFDirEntry* dir, uint8* v) { if (dir->tdir_count <= 4) { /* * Extract data from offset field. */ if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) { if (dir->tdir_type == TIFF_SBYTE) switch (dir->tdir_count) { case 4: v[3] = dir->tdir_offset & 0xff; case 3: v[2] = (dir->tdir_offset >> 8) & 0xff; case 2: v[1] = (dir->tdir_offset >> 16) & 0xff; case 1: v[0] = dir->tdir_offset >> 24; } else switch (dir->tdir_count) { case 4: v[3] = dir->tdir_offset & 0xff; case 3: v[2] = (dir->tdir_offset >> 8) & 0xff; case 2: v[1] = (dir->tdir_offset >> 16) & 0xff; case 1: v[0] = dir->tdir_offset >> 24; } } else { if (dir->tdir_type == TIFF_SBYTE) switch (dir->tdir_count) { case 4: v[3] = dir->tdir_offset >> 24; case 3: v[2] = (dir->tdir_offset >> 16) & 0xff; case 2: v[1] = (dir->tdir_offset >> 8) & 0xff; case 1: v[0] = dir->tdir_offset & 0xff; } else switch (dir->tdir_count) { case 4: v[3] = dir->tdir_offset >> 24; case 3: v[2] = (dir->tdir_offset >> 16) & 0xff; case 2: v[1] = (dir->tdir_offset >> 8) & 0xff; case 1: v[0] = dir->tdir_offset & 0xff; } } return (1); } else return (TIFFFetchData(tif, dir, (char*) v) != 0); /* XXX */ } /* * Fetch an array of SHORT or SSHORT values. */ static int TIFFFetchShortArray(TIFF* tif, TIFFDirEntry* dir, uint16* v) { if (dir->tdir_count <= 2) { if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) { switch (dir->tdir_count) { case 2: v[1] = (uint16) (dir->tdir_offset & 0xffff); case 1: v[0] = (uint16) (dir->tdir_offset >> 16); } } else { switch (dir->tdir_count) { case 2: v[1] = (uint16) (dir->tdir_offset >> 16); case 1: v[0] = (uint16) (dir->tdir_offset & 0xffff); } } return (1); } else return (TIFFFetchData(tif, dir, (char *)v) != 0); } /* * Fetch a pair of SHORT or BYTE values. Some tags may have either BYTE * or SHORT type and this function works with both ones. */ static int TIFFFetchShortPair(TIFF* tif, TIFFDirEntry* dir) { switch (dir->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: { uint8 v[4]; return TIFFFetchByteArray(tif, dir, v) && TIFFSetField(tif, dir->tdir_tag, v[0], v[1]); } case TIFF_SHORT: case TIFF_SSHORT: { uint16 v[2]; return TIFFFetchShortArray(tif, dir, v) && TIFFSetField(tif, dir->tdir_tag, v[0], v[1]); } default: return 0; } } /* * Fetch an array of LONG or SLONG values. */ static int TIFFFetchLongArray(TIFF* tif, TIFFDirEntry* dir, uint32* v) { if (dir->tdir_count == 1) { v[0] = dir->tdir_offset; return (1); } else return (TIFFFetchData(tif, dir, (char*) v) != 0); } /* * Fetch an array of RATIONAL or SRATIONAL values. */ static int TIFFFetchRationalArray(TIFF* tif, TIFFDirEntry* dir, float* v) { int ok = 0; uint32* l; l = (uint32*)_TIFFCheckMalloc(tif, dir->tdir_count, TIFFDataWidth((TIFFDataType) dir->tdir_type), "to fetch array of rationals"); if (l) { if (TIFFFetchData(tif, dir, (char *)l)) { uint32 i; for (i = 0; i < dir->tdir_count; i++) { ok = cvtRational(tif, dir, l[2*i+0], l[2*i+1], &v[i]); if (!ok) break; } } _TIFFfree((char *)l); } return (ok); } /* * Fetch an array of FLOAT values. */ static int TIFFFetchFloatArray(TIFF* tif, TIFFDirEntry* dir, float* v) { if (dir->tdir_count == 1) { v[0] = *(float*) &dir->tdir_offset; TIFFCvtIEEEFloatToNative(tif, dir->tdir_count, v); return (1); } else if (TIFFFetchData(tif, dir, (char*) v)) { TIFFCvtIEEEFloatToNative(tif, dir->tdir_count, v); return (1); } else return (0); } /* * Fetch an array of DOUBLE values. */ static int TIFFFetchDoubleArray(TIFF* tif, TIFFDirEntry* dir, double* v) { if (TIFFFetchData(tif, dir, (char*) v)) { TIFFCvtIEEEDoubleToNative(tif, dir->tdir_count, v); return (1); } else return (0); } /* * Fetch an array of ANY values. The actual values are * returned as doubles which should be able hold all the * types. Yes, there really should be an tany_t to avoid * this potential non-portability ... Note in particular * that we assume that the double return value vector is * large enough to read in any fundamental type. We use * that vector as a buffer to read in the base type vector * and then convert it in place to double (from end * to front of course). */ static int TIFFFetchAnyArray(TIFF* tif, TIFFDirEntry* dir, double* v) { int i; switch (dir->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: if (!TIFFFetchByteArray(tif, dir, (uint8*) v)) return (0); if (dir->tdir_type == TIFF_BYTE) { uint8* vp = (uint8*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } else { int8* vp = (int8*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_SHORT: case TIFF_SSHORT: if (!TIFFFetchShortArray(tif, dir, (uint16*) v)) return (0); if (dir->tdir_type == TIFF_SHORT) { uint16* vp = (uint16*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } else { int16* vp = (int16*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_LONG: case TIFF_SLONG: if (!TIFFFetchLongArray(tif, dir, (uint32*) v)) return (0); if (dir->tdir_type == TIFF_LONG) { uint32* vp = (uint32*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } else { int32* vp = (int32*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_RATIONAL: case TIFF_SRATIONAL: if (!TIFFFetchRationalArray(tif, dir, (float*) v)) return (0); { float* vp = (float*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_FLOAT: if (!TIFFFetchFloatArray(tif, dir, (float*) v)) return (0); { float* vp = (float*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_DOUBLE: return (TIFFFetchDoubleArray(tif, dir, (double*) v)); default: /* TIFF_NOTYPE */ /* TIFF_ASCII */ /* TIFF_UNDEFINED */ TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "cannot read TIFF_ANY type %d for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); return (0); } return (1); } /* * Fetch a tag that is not handled by special case code. */ static int TIFFFetchNormalTag(TIFF* tif, TIFFDirEntry* dp) { static const char mesg[] = "to fetch tag value"; int ok = 0; const TIFFFieldInfo* fip = _TIFFFieldWithTag(tif, dp->tdir_tag); if (dp->tdir_count > 1) { /* array of values */ char* cp = NULL; switch (dp->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: cp = (char *)_TIFFCheckMalloc(tif, dp->tdir_count, sizeof (uint8), mesg); ok = cp && TIFFFetchByteArray(tif, dp, (uint8*) cp); break; case TIFF_SHORT: case TIFF_SSHORT: cp = (char *)_TIFFCheckMalloc(tif, dp->tdir_count, sizeof (uint16), mesg); ok = cp && TIFFFetchShortArray(tif, dp, (uint16*) cp); break; case TIFF_LONG: case TIFF_SLONG: cp = (char *)_TIFFCheckMalloc(tif, dp->tdir_count, sizeof (uint32), mesg); ok = cp && TIFFFetchLongArray(tif, dp, (uint32*) cp); break; case TIFF_RATIONAL: case TIFF_SRATIONAL: cp = (char *)_TIFFCheckMalloc(tif, dp->tdir_count, sizeof (float), mesg); ok = cp && TIFFFetchRationalArray(tif, dp, (float*) cp); break; case TIFF_FLOAT: cp = (char *)_TIFFCheckMalloc(tif, dp->tdir_count, sizeof (float), mesg); ok = cp && TIFFFetchFloatArray(tif, dp, (float*) cp); break; case TIFF_DOUBLE: cp = (char *)_TIFFCheckMalloc(tif, dp->tdir_count, sizeof (double), mesg); ok = cp && TIFFFetchDoubleArray(tif, dp, (double*) cp); break; case TIFF_ASCII: case TIFF_UNDEFINED: /* bit of a cheat... */ /* * Some vendors write strings w/o the trailing * NULL byte, so always append one just in case. */ cp = (char *)_TIFFCheckMalloc(tif, dp->tdir_count + 1, 1, mesg); if( (ok = (cp && TIFFFetchString(tif, dp, cp))) != 0 ) cp[dp->tdir_count] = '\0'; /* XXX */ break; } if (ok) { ok = (fip->field_passcount ? TIFFSetField(tif, dp->tdir_tag, dp->tdir_count, cp) : TIFFSetField(tif, dp->tdir_tag, cp)); } if (cp != NULL) _TIFFfree(cp); } else if (CheckDirCount(tif, dp, 1)) { /* singleton value */ switch (dp->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: case TIFF_SHORT: case TIFF_SSHORT: /* * If the tag is also acceptable as a LONG or SLONG * then TIFFSetField will expect an uint32 parameter * passed to it (through varargs). Thus, for machines * where sizeof (int) != sizeof (uint32) we must do * a careful check here. It's hard to say if this * is worth optimizing. * * NB: We use TIFFFieldWithTag here knowing that * it returns us the first entry in the table * for the tag and that that entry is for the * widest potential data type the tag may have. */ { TIFFDataType type = fip->field_type; if (type != TIFF_LONG && type != TIFF_SLONG) { uint16 v = (uint16) TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset); ok = (fip->field_passcount ? TIFFSetField(tif, dp->tdir_tag, 1, &v) : TIFFSetField(tif, dp->tdir_tag, v)); break; } } /* fall thru... */ case TIFF_LONG: case TIFF_SLONG: { uint32 v32 = TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset); ok = (fip->field_passcount ? TIFFSetField(tif, dp->tdir_tag, 1, &v32) : TIFFSetField(tif, dp->tdir_tag, v32)); } break; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: { float v = (dp->tdir_type == TIFF_FLOAT ? TIFFFetchFloat(tif, dp) : TIFFFetchRational(tif, dp)); ok = (fip->field_passcount ? TIFFSetField(tif, dp->tdir_tag, 1, &v) : TIFFSetField(tif, dp->tdir_tag, v)); } break; case TIFF_DOUBLE: { double v; ok = (TIFFFetchDoubleArray(tif, dp, &v) && (fip->field_passcount ? TIFFSetField(tif, dp->tdir_tag, 1, &v) : TIFFSetField(tif, dp->tdir_tag, v)) ); } break; case TIFF_ASCII: case TIFF_UNDEFINED: /* bit of a cheat... */ { char c[2]; if( (ok = (TIFFFetchString(tif, dp, c) != 0)) != 0 ) { c[1] = '\0'; /* XXX paranoid */ ok = (fip->field_passcount ? TIFFSetField(tif, dp->tdir_tag, 1, c) : TIFFSetField(tif, dp->tdir_tag, c)); } } break; } } return (ok); } #define NITEMS(x) (sizeof (x) / sizeof (x[0])) /* * Fetch samples/pixel short values for * the specified tag and verify that * all values are the same. */ static int TIFFFetchPerSampleShorts(TIFF* tif, TIFFDirEntry* dir, uint16* pl) { uint16 samples = tif->tif_dir.td_samplesperpixel; int status = 0; if (CheckDirCount(tif, dir, (uint32) samples)) { uint16 buf[10]; uint16* v = buf; if (dir->tdir_count > NITEMS(buf)) v = (uint16*) _TIFFCheckMalloc(tif, dir->tdir_count, sizeof(uint16), "to fetch per-sample values"); if (v && TIFFFetchShortArray(tif, dir, v)) { uint16 i; int check_count = dir->tdir_count; if( samples < check_count ) check_count = samples; for (i = 1; i < check_count; i++) if (v[i] != v[0]) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Cannot handle different per-sample values for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); goto bad; } *pl = v[0]; status = 1; } bad: if (v && v != buf) _TIFFfree(v); } return (status); } /* * Fetch samples/pixel long values for * the specified tag and verify that * all values are the same. */ static int TIFFFetchPerSampleLongs(TIFF* tif, TIFFDirEntry* dir, uint32* pl) { uint16 samples = tif->tif_dir.td_samplesperpixel; int status = 0; if (CheckDirCount(tif, dir, (uint32) samples)) { uint32 buf[10]; uint32* v = buf; if (dir->tdir_count > NITEMS(buf)) v = (uint32*) _TIFFCheckMalloc(tif, dir->tdir_count, sizeof(uint32), "to fetch per-sample values"); if (v && TIFFFetchLongArray(tif, dir, v)) { uint16 i; int check_count = dir->tdir_count; if( samples < check_count ) check_count = samples; for (i = 1; i < check_count; i++) if (v[i] != v[0]) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Cannot handle different per-sample values for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); goto bad; } *pl = v[0]; status = 1; } bad: if (v && v != buf) _TIFFfree(v); } return (status); } /* * Fetch samples/pixel ANY values for the specified tag and verify that all * values are the same. */ static int TIFFFetchPerSampleAnys(TIFF* tif, TIFFDirEntry* dir, double* pl) { uint16 samples = tif->tif_dir.td_samplesperpixel; int status = 0; if (CheckDirCount(tif, dir, (uint32) samples)) { double buf[10]; double* v = buf; if (dir->tdir_count > NITEMS(buf)) v = (double*) _TIFFCheckMalloc(tif, dir->tdir_count, sizeof (double), "to fetch per-sample values"); if (v && TIFFFetchAnyArray(tif, dir, v)) { uint16 i; int check_count = dir->tdir_count; if( samples < check_count ) check_count = samples; for (i = 1; i < check_count; i++) if (v[i] != v[0]) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Cannot handle different per-sample values for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); goto bad; } *pl = v[0]; status = 1; } bad: if (v && v != buf) _TIFFfree(v); } return (status); } #undef NITEMS /* * Fetch a set of offsets or lengths. * While this routine says "strips", in fact it's also used for tiles. */ static int TIFFFetchStripThing(TIFF* tif, TIFFDirEntry* dir, long nstrips, uint32** lpp) { register uint32* lp; int status; CheckDirCount(tif, dir, (uint32) nstrips); /* * Allocate space for strip information. */ if (*lpp == NULL && (*lpp = (uint32 *)_TIFFCheckMalloc(tif, nstrips, sizeof (uint32), "for strip array")) == NULL) return (0); lp = *lpp; _TIFFmemset( lp, 0, sizeof(uint32) * nstrips ); if (dir->tdir_type == (int)TIFF_SHORT) { /* * Handle uint16->uint32 expansion. */ uint16* dp = (uint16*) _TIFFCheckMalloc(tif, dir->tdir_count, sizeof (uint16), "to fetch strip tag"); if (dp == NULL) return (0); if( (status = TIFFFetchShortArray(tif, dir, dp)) != 0 ) { int i; for( i = 0; i < nstrips && i < (int) dir->tdir_count; i++ ) { lp[i] = dp[i]; } } _TIFFfree((char*) dp); } else if( nstrips != (int) dir->tdir_count ) { /* Special case to correct length */ uint32* dp = (uint32*) _TIFFCheckMalloc(tif, dir->tdir_count, sizeof (uint32), "to fetch strip tag"); if (dp == NULL) return (0); status = TIFFFetchLongArray(tif, dir, dp); if( status != 0 ) { int i; for( i = 0; i < nstrips && i < (int) dir->tdir_count; i++ ) { lp[i] = dp[i]; } } _TIFFfree( (char *) dp ); } else status = TIFFFetchLongArray(tif, dir, lp); return (status); } /* * Fetch and set the RefBlackWhite tag. */ static int TIFFFetchRefBlackWhite(TIFF* tif, TIFFDirEntry* dir) { static const char mesg[] = "for \"ReferenceBlackWhite\" array"; char* cp; int ok; if (dir->tdir_type == TIFF_RATIONAL) return (TIFFFetchNormalTag(tif, dir)); /* * Handle LONG's for backward compatibility. */ cp = (char *)_TIFFCheckMalloc(tif, dir->tdir_count, sizeof (uint32), mesg); if( (ok = (cp && TIFFFetchLongArray(tif, dir, (uint32*) cp))) != 0) { float* fp = (float*) _TIFFCheckMalloc(tif, dir->tdir_count, sizeof (float), mesg); if( (ok = (fp != NULL)) != 0 ) { uint32 i; for (i = 0; i < dir->tdir_count; i++) fp[i] = (float)((uint32*) cp)[i]; ok = TIFFSetField(tif, dir->tdir_tag, fp); _TIFFfree((char*) fp); } } if (cp) _TIFFfree(cp); return (ok); } /* * Replace a single strip (tile) of uncompressed data by * multiple strips (tiles), each approximately 8Kbytes. * This is useful for dealing with large images or * for dealing with machines with a limited amount * memory. */ static void ChopUpSingleUncompressedStrip(TIFF* tif) { register TIFFDirectory *td = &tif->tif_dir; uint32 bytecount = td->td_stripbytecount[0]; uint32 offset = td->td_stripoffset[0]; tsize_t rowbytes = TIFFVTileSize(tif, 1), stripbytes; tstrip_t strip, nstrips, rowsperstrip; uint32* newcounts; uint32* newoffsets; /* * Make the rows hold at least one scanline, but fill specified amount * of data if possible. */ #ifndef STRIP_SIZE_DEFAULT # define STRIP_SIZE_DEFAULT 8192 #endif if (rowbytes > STRIP_SIZE_DEFAULT) { stripbytes = rowbytes; rowsperstrip = 1; } else if (rowbytes > 0 ) { rowsperstrip = STRIP_SIZE_DEFAULT / rowbytes; stripbytes = rowbytes * rowsperstrip; } else return; #undef STRIP_SIZE_DEFAULT /* * never increase the number of strips in an image */ if (rowsperstrip >= td->td_rowsperstrip) return; nstrips = (tstrip_t) TIFFhowmany(bytecount, stripbytes); if( nstrips == 0 ) /* something is wonky, do nothing. */ return; newcounts = (uint32*) _TIFFCheckMalloc(tif, nstrips, sizeof (uint32), "for chopped \"StripByteCounts\" array"); newoffsets = (uint32*) _TIFFCheckMalloc(tif, nstrips, sizeof (uint32), "for chopped \"StripOffsets\" array"); if (newcounts == NULL || newoffsets == NULL) { /* * Unable to allocate new strip information, give * up and use the original one strip information. */ if (newcounts != NULL) _TIFFfree(newcounts); if (newoffsets != NULL) _TIFFfree(newoffsets); return; } /* * Fill the strip information arrays with new bytecounts and offsets * that reflect the broken-up format. */ for (strip = 0; strip < nstrips; strip++) { if (stripbytes > (tsize_t) bytecount) stripbytes = bytecount; newcounts[strip] = stripbytes; newoffsets[strip] = offset; offset += stripbytes; bytecount -= stripbytes; } /* * Replace old single strip info with multi-strip info. */ td->td_stripsperimage = td->td_nstrips = nstrips; TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, rowsperstrip); _TIFFfree(td->td_stripbytecount); _TIFFfree(td->td_stripoffset); td->td_stripbytecount = newcounts; td->td_stripoffset = newoffsets; td->td_stripbytecountsorted = 1; } /* vim: set ts=8 sts=8 sw=8 noet: */ /* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library. * * Directory Read Support Routines. */ #include "tiffiop.h" #define IGNORE 0 /* tag placeholder used below */ #ifdef HAVE_IEEEFP # define TIFFCvtIEEEFloatToNative(tif, n, fp) # define TIFFCvtIEEEDoubleToNative(tif, n, dp) #else extern void TIFFCvtIEEEFloatToNative(TIFF*, uint32, float*); extern void TIFFCvtIEEEDoubleToNative(TIFF*, uint32, double*); #endif static int EstimateStripByteCounts(TIFF*, TIFFDirEntry*, uint16); static void MissingRequired(TIFF*, const char*); static int CheckDirCount(TIFF*, TIFFDirEntry*, uint32); static tsize_t TIFFFetchData(TIFF*, TIFFDirEntry*, char*); static tsize_t TIFFFetchString(TIFF*, TIFFDirEntry*, char*); static float TIFFFetchRational(TIFF*, TIFFDirEntry*); static int TIFFFetchNormalTag(TIFF*, TIFFDirEntry*); static int TIFFFetchPerSampleShorts(TIFF*, TIFFDirEntry*, uint16*); static int TIFFFetchPerSampleLongs(TIFF*, TIFFDirEntry*, uint32*); static int TIFFFetchPerSampleAnys(TIFF*, TIFFDirEntry*, double*); static int TIFFFetchShortArray(TIFF*, TIFFDirEntry*, uint16*); static int TIFFFetchStripThing(TIFF*, TIFFDirEntry*, long, uint32**); static int TIFFFetchRefBlackWhite(TIFF*, TIFFDirEntry*); static float TIFFFetchFloat(TIFF*, TIFFDirEntry*); static int TIFFFetchFloatArray(TIFF*, TIFFDirEntry*, float*); static int TIFFFetchDoubleArray(TIFF*, TIFFDirEntry*, double*); static int TIFFFetchAnyArray(TIFF*, TIFFDirEntry*, double*); static int TIFFFetchShortPair(TIFF*, TIFFDirEntry*); static void ChopUpSingleUncompressedStrip(TIFF*); /* * Read the next TIFF directory from a file * and convert it to the internal format. * We read directories sequentially. */ int TIFFReadDirectory(TIFF* tif) { static const char module[] = "TIFFReadDirectory"; int n; TIFFDirectory* td; TIFFDirEntry *dp, *dir = NULL; uint16 iv; uint32 v; const TIFFFieldInfo* fip; size_t fix; uint16 dircount; toff_t nextdiroff; int diroutoforderwarning = 0; toff_t* new_dirlist; tif->tif_diroff = tif->tif_nextdiroff; if (tif->tif_diroff == 0) /* no more directories */ return (0); /* * XXX: Trick to prevent IFD looping. The one can create TIFF file * with looped directory pointers. We will maintain a list of already * seen directories and check every IFD offset against this list. */ for (n = 0; n < tif->tif_dirnumber; n++) { if (tif->tif_dirlist[n] == tif->tif_diroff) return (0); } tif->tif_dirnumber++; new_dirlist = (toff_t *)_TIFFrealloc(tif->tif_dirlist, tif->tif_dirnumber * sizeof(toff_t)); if (!new_dirlist) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Failed to allocate space for IFD list", tif->tif_name); return (0); } tif->tif_dirlist = new_dirlist; tif->tif_dirlist[tif->tif_dirnumber - 1] = tif->tif_diroff; /* * Cleanup any previous compression state. */ (*tif->tif_cleanup)(tif); tif->tif_curdir++; nextdiroff = 0; if (!isMapped(tif)) { if (!SeekOK(tif, tif->tif_diroff)) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Seek error accessing TIFF directory", tif->tif_name); return (0); } if (!ReadOK(tif, &dircount, sizeof (uint16))) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Can not read TIFF directory count", tif->tif_name); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); dir = (TIFFDirEntry *)_TIFFCheckMalloc(tif, dircount, sizeof (TIFFDirEntry), "to read TIFF directory"); if (dir == NULL) return (0); if (!ReadOK(tif, dir, dircount*sizeof (TIFFDirEntry))) { TIFFErrorExt(tif->tif_clientdata, module, "%.100s: Can not read TIFF directory", tif->tif_name); goto bad; } /* * Read offset to next directory for sequential scans. */ (void) ReadOK(tif, &nextdiroff, sizeof (uint32)); } else { toff_t off = tif->tif_diroff; if (off + sizeof (uint16) > tif->tif_size) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Can not read TIFF directory count", tif->tif_name); return (0); } else _TIFFmemcpy(&dircount, tif->tif_base + off, sizeof (uint16)); off += sizeof (uint16); if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); dir = (TIFFDirEntry *)_TIFFCheckMalloc(tif, dircount, sizeof (TIFFDirEntry), "to read TIFF directory"); if (dir == NULL) return (0); if (off + dircount*sizeof (TIFFDirEntry) > tif->tif_size) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Can not read TIFF directory", tif->tif_name); goto bad; } else { _TIFFmemcpy(dir, tif->tif_base + off, dircount*sizeof (TIFFDirEntry)); } off += dircount* sizeof (TIFFDirEntry); if (off + sizeof (uint32) <= tif->tif_size) _TIFFmemcpy(&nextdiroff, tif->tif_base+off, sizeof (uint32)); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong(&nextdiroff); tif->tif_nextdiroff = nextdiroff; tif->tif_flags &= ~TIFF_BEENWRITING; /* reset before new dir */ /* * Setup default value and then make a pass over * the fields to check type and tag information, * and to extract info required to size data * structures. A second pass is made afterwards * to read in everthing not taken in the first pass. */ td = &tif->tif_dir; /* free any old stuff and reinit */ TIFFFreeDirectory(tif); TIFFDefaultDirectory(tif); /* * Electronic Arts writes gray-scale TIFF files * without a PlanarConfiguration directory entry. * Thus we setup a default value here, even though * the TIFF spec says there is no default value. */ TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); /* * Sigh, we must make a separate pass through the * directory for the following reason: * * We must process the Compression tag in the first pass * in order to merge in codec-private tag definitions (otherwise * we may get complaints about unknown tags). However, the * Compression tag may be dependent on the SamplesPerPixel * tag value because older TIFF specs permited Compression * to be written as a SamplesPerPixel-count tag entry. * Thus if we don't first figure out the correct SamplesPerPixel * tag value then we may end up ignoring the Compression tag * value because it has an incorrect count value (if the * true value of SamplesPerPixel is not 1). * * It sure would have been nice if Aldus had really thought * this stuff through carefully. */ for (dp = dir, n = dircount; n > 0; n--, dp++) { if (tif->tif_flags & TIFF_SWAB) { TIFFSwabArrayOfShort(&dp->tdir_tag, 2); TIFFSwabArrayOfLong(&dp->tdir_count, 2); } if (dp->tdir_tag == TIFFTAG_SAMPLESPERPIXEL) { if (!TIFFFetchNormalTag(tif, dp)) goto bad; dp->tdir_tag = IGNORE; } } /* * First real pass over the directory. */ fix = 0; for (dp = dir, n = dircount; n > 0; n--, dp++) { if (fix >= tif->tif_nfields || dp->tdir_tag == IGNORE) continue; /* * Silicon Beach (at least) writes unordered * directory tags (violating the spec). Handle * it here, but be obnoxious (maybe they'll fix it?). */ if (dp->tdir_tag < tif->tif_fieldinfo[fix]->field_tag) { if (!diroutoforderwarning) { TIFFWarningExt(tif->tif_clientdata, module, "%s: invalid TIFF directory; tags are not sorted in ascending order", tif->tif_name); diroutoforderwarning = 1; } fix = 0; /* O(n^2) */ } while (fix < tif->tif_nfields && tif->tif_fieldinfo[fix]->field_tag < dp->tdir_tag) fix++; if (fix >= tif->tif_nfields || tif->tif_fieldinfo[fix]->field_tag != dp->tdir_tag) { TIFFWarningExt(tif->tif_clientdata, module, "%s: unknown field with tag %d (0x%x) encountered", tif->tif_name, dp->tdir_tag, dp->tdir_tag, dp->tdir_type); TIFFMergeFieldInfo( tif, _TIFFCreateAnonFieldInfo( tif, dp->tdir_tag, (TIFFDataType) dp->tdir_type ), 1 ); fix = 0; while (fix < tif->tif_nfields && tif->tif_fieldinfo[fix]->field_tag < dp->tdir_tag) fix++; } /* * Null out old tags that we ignore. */ if (tif->tif_fieldinfo[fix]->field_bit == FIELD_IGNORE) { ignore: dp->tdir_tag = IGNORE; continue; } /* * Check data type. */ fip = tif->tif_fieldinfo[fix]; while (dp->tdir_type != (unsigned short) fip->field_type && fix < tif->tif_nfields) { if (fip->field_type == TIFF_ANY) /* wildcard */ break; fip = tif->tif_fieldinfo[++fix]; if (fix >= tif->tif_nfields || fip->field_tag != dp->tdir_tag) { TIFFWarningExt(tif->tif_clientdata, module, "%s: wrong data type %d for \"%s\"; tag ignored", tif->tif_name, dp->tdir_type, tif->tif_fieldinfo[fix-1]->field_name); goto ignore; } } /* * Check count if known in advance. */ if (fip->field_readcount != TIFF_VARIABLE && fip->field_readcount != TIFF_VARIABLE2) { uint32 expected = (fip->field_readcount == TIFF_SPP) ? (uint32) td->td_samplesperpixel : (uint32) fip->field_readcount; if (!CheckDirCount(tif, dp, expected)) goto ignore; } switch (dp->tdir_tag) { case TIFFTAG_COMPRESSION: /* * The 5.0 spec says the Compression tag has * one value, while earlier specs say it has * one value per sample. Because of this, we * accept the tag if one value is supplied. */ if (dp->tdir_count == 1) { v = TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset); if (!TIFFSetField(tif, dp->tdir_tag, (uint16)v)) goto bad; break; /* XXX: workaround for broken TIFFs */ } else if (dp->tdir_type == TIFF_LONG) { if (!TIFFFetchPerSampleLongs(tif, dp, &v) || !TIFFSetField(tif, dp->tdir_tag, (uint16)v)) goto bad; } else { if (!TIFFFetchPerSampleShorts(tif, dp, &iv) || !TIFFSetField(tif, dp->tdir_tag, iv)) goto bad; } dp->tdir_tag = IGNORE; break; case TIFFTAG_STRIPOFFSETS: case TIFFTAG_STRIPBYTECOUNTS: case TIFFTAG_TILEOFFSETS: case TIFFTAG_TILEBYTECOUNTS: TIFFSetFieldBit(tif, fip->field_bit); break; case TIFFTAG_IMAGEWIDTH: case TIFFTAG_IMAGELENGTH: case TIFFTAG_IMAGEDEPTH: case TIFFTAG_TILELENGTH: case TIFFTAG_TILEWIDTH: case TIFFTAG_TILEDEPTH: case TIFFTAG_PLANARCONFIG: case TIFFTAG_ROWSPERSTRIP: case TIFFTAG_EXTRASAMPLES: if (!TIFFFetchNormalTag(tif, dp)) goto bad; dp->tdir_tag = IGNORE; break; } } /* * Allocate directory structure and setup defaults. */ if (!TIFFFieldSet(tif, FIELD_IMAGEDIMENSIONS)) { MissingRequired(tif, "ImageLength"); goto bad; } if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG)) { MissingRequired(tif, "PlanarConfiguration"); goto bad; } /* * Setup appropriate structures (by strip or by tile) */ if (!TIFFFieldSet(tif, FIELD_TILEDIMENSIONS)) { td->td_nstrips = TIFFNumberOfStrips(tif); td->td_tilewidth = td->td_imagewidth; td->td_tilelength = td->td_rowsperstrip; td->td_tiledepth = td->td_imagedepth; tif->tif_flags &= ~TIFF_ISTILED; } else { td->td_nstrips = TIFFNumberOfTiles(tif); tif->tif_flags |= TIFF_ISTILED; } if (!td->td_nstrips) { TIFFErrorExt(tif->tif_clientdata, module, "%s: cannot handle zero number of %s", tif->tif_name, isTiled(tif) ? "tiles" : "strips"); goto bad; } td->td_stripsperimage = td->td_nstrips; if (td->td_planarconfig == PLANARCONFIG_SEPARATE) td->td_stripsperimage /= td->td_samplesperpixel; if (!TIFFFieldSet(tif, FIELD_STRIPOFFSETS)) { MissingRequired(tif, isTiled(tif) ? "TileOffsets" : "StripOffsets"); goto bad; } /* * Second pass: extract other information. */ for (dp = dir, n = dircount; n > 0; n--, dp++) { if (dp->tdir_tag == IGNORE) continue; switch (dp->tdir_tag) { case TIFFTAG_MINSAMPLEVALUE: case TIFFTAG_MAXSAMPLEVALUE: case TIFFTAG_BITSPERSAMPLE: case TIFFTAG_DATATYPE: case TIFFTAG_SAMPLEFORMAT: /* * The 5.0 spec says the Compression tag has * one value, while earlier specs say it has * one value per sample. Because of this, we * accept the tag if one value is supplied. * * The MinSampleValue, MaxSampleValue, BitsPerSample * DataType and SampleFormat tags are supposed to be * written as one value/sample, but some vendors * incorrectly write one value only -- so we accept * that as well (yech). Other vendors write correct * value for NumberOfSamples, but incorrect one for * BitsPerSample and friends, and we will read this * too. */ if (dp->tdir_count == 1) { v = TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset); if (!TIFFSetField(tif, dp->tdir_tag, (uint16)v)) goto bad; /* XXX: workaround for broken TIFFs */ } else if (dp->tdir_tag == TIFFTAG_BITSPERSAMPLE && dp->tdir_type == TIFF_LONG) { if (!TIFFFetchPerSampleLongs(tif, dp, &v) || !TIFFSetField(tif, dp->tdir_tag, (uint16)v)) goto bad; } else { if (!TIFFFetchPerSampleShorts(tif, dp, &iv) || !TIFFSetField(tif, dp->tdir_tag, iv)) goto bad; } break; case TIFFTAG_SMINSAMPLEVALUE: case TIFFTAG_SMAXSAMPLEVALUE: { double dv = 0.0; if (!TIFFFetchPerSampleAnys(tif, dp, &dv) || !TIFFSetField(tif, dp->tdir_tag, dv)) goto bad; } break; case TIFFTAG_STRIPOFFSETS: case TIFFTAG_TILEOFFSETS: if (!TIFFFetchStripThing(tif, dp, td->td_nstrips, &td->td_stripoffset)) goto bad; break; case TIFFTAG_STRIPBYTECOUNTS: case TIFFTAG_TILEBYTECOUNTS: if (!TIFFFetchStripThing(tif, dp, td->td_nstrips, &td->td_stripbytecount)) goto bad; break; case TIFFTAG_COLORMAP: case TIFFTAG_TRANSFERFUNCTION: { char* cp; /* * TransferFunction can have either 1x or 3x * data values; Colormap can have only 3x * items. */ v = 1L<<td->td_bitspersample; if (dp->tdir_tag == TIFFTAG_COLORMAP || dp->tdir_count != v) { if (!CheckDirCount(tif, dp, 3 * v)) break; } v *= sizeof(uint16); cp = (char *)_TIFFCheckMalloc(tif, dp->tdir_count, sizeof (uint16), "to read \"TransferFunction\" tag"); if (cp != NULL) { if (TIFFFetchData(tif, dp, cp)) { /* * This deals with there being * only one array to apply to * all samples. */ uint32 c = 1L << td->td_bitspersample; if (dp->tdir_count == c) v = 0L; TIFFSetField(tif, dp->tdir_tag, cp, cp+v, cp+2*v); } _TIFFfree(cp); } break; } case TIFFTAG_PAGENUMBER: case TIFFTAG_HALFTONEHINTS: case TIFFTAG_YCBCRSUBSAMPLING: case TIFFTAG_DOTRANGE: (void) TIFFFetchShortPair(tif, dp); break; case TIFFTAG_REFERENCEBLACKWHITE: (void) TIFFFetchRefBlackWhite(tif, dp); break; /* BEGIN REV 4.0 COMPATIBILITY */ case TIFFTAG_OSUBFILETYPE: v = 0L; switch (TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset)) { case OFILETYPE_REDUCEDIMAGE: v = FILETYPE_REDUCEDIMAGE; break; case OFILETYPE_PAGE: v = FILETYPE_PAGE; break; } if (v) TIFFSetField(tif, TIFFTAG_SUBFILETYPE, v); break; /* END REV 4.0 COMPATIBILITY */ default: (void) TIFFFetchNormalTag(tif, dp); break; } } /* * Verify Palette image has a Colormap. */ if (td->td_photometric == PHOTOMETRIC_PALETTE && !TIFFFieldSet(tif, FIELD_COLORMAP)) { MissingRequired(tif, "Colormap"); goto bad; } /* * Attempt to deal with a missing StripByteCounts tag. */ if (!TIFFFieldSet(tif, FIELD_STRIPBYTECOUNTS)) { /* * Some manufacturers violate the spec by not giving * the size of the strips. In this case, assume there * is one uncompressed strip of data. */ if ((td->td_planarconfig == PLANARCONFIG_CONTIG && td->td_nstrips > 1) || (td->td_planarconfig == PLANARCONFIG_SEPARATE && td->td_nstrips != td->td_samplesperpixel)) { MissingRequired(tif, "StripByteCounts"); goto bad; } TIFFWarningExt(tif->tif_clientdata, module, "%s: TIFF directory is missing required " "\"%s\" field, calculating from imagelength", tif->tif_name, _TIFFFieldWithTag(tif,TIFFTAG_STRIPBYTECOUNTS)->field_name); if (EstimateStripByteCounts(tif, dir, dircount) < 0) goto bad; /* * Assume we have wrong StripByteCount value (in case of single strip) in * following cases: * - it is equal to zero along with StripOffset; * - it is larger than file itself (in case of uncompressed image); * - it is smaller than the size of the bytes per row multiplied on the * number of rows. The last case should not be checked in the case of * writing new image, because we may do not know the exact strip size * until the whole image will be written and directory dumped out. */ #define BYTECOUNTLOOKSBAD \ ( (td->td_stripbytecount[0] == 0 && td->td_stripoffset[0] != 0) || \ (td->td_compression == COMPRESSION_NONE && \ td->td_stripbytecount[0] > TIFFGetFileSize(tif) - td->td_stripoffset[0]) || \ (tif->tif_mode == O_RDONLY && \ td->td_compression == COMPRESSION_NONE && \ td->td_stripbytecount[0] < TIFFScanlineSize(tif) * td->td_imagelength) ) } else if (td->td_nstrips == 1 && td->td_stripoffset[0] != 0 && BYTECOUNTLOOKSBAD) { /* * XXX: Plexus (and others) sometimes give a value of zero for * a tag when they don't know what the correct value is! Try * and handle the simple case of estimating the size of a one * strip image. */ TIFFWarningExt(tif->tif_clientdata, module, "%s: Bogus \"%s\" field, ignoring and calculating from imagelength", tif->tif_name, _TIFFFieldWithTag(tif,TIFFTAG_STRIPBYTECOUNTS)->field_name); if(EstimateStripByteCounts(tif, dir, dircount) < 0) goto bad; } else if (td->td_planarconfig == PLANARCONFIG_CONTIG && td->td_nstrips > 2 && td->td_compression == COMPRESSION_NONE && td->td_stripbytecount[0] != td->td_stripbytecount[1]) { /* * XXX: Some vendors fill StripByteCount array with absolutely * wrong values (it can be equal to StripOffset array, for * example). Catch this case here. */ TIFFWarningExt(tif->tif_clientdata, module, "%s: Wrong \"%s\" field, ignoring and calculating from imagelength", tif->tif_name, _TIFFFieldWithTag(tif,TIFFTAG_STRIPBYTECOUNTS)->field_name); if (EstimateStripByteCounts(tif, dir, dircount) < 0) goto bad; } if (dir) { _TIFFfree((char *)dir); dir = NULL; } if (!TIFFFieldSet(tif, FIELD_MAXSAMPLEVALUE)) td->td_maxsamplevalue = (uint16)((1L<<td->td_bitspersample)-1); /* * Setup default compression scheme. */ /* * XXX: We can optimize checking for the strip bounds using the sorted * bytecounts array. See also comments for TIFFAppendToStrip() * function in tif_write.c. */ if (td->td_nstrips > 1) { tstrip_t strip; td->td_stripbytecountsorted = 1; for (strip = 1; strip < td->td_nstrips; strip++) { if (td->td_stripoffset[strip - 1] > td->td_stripoffset[strip]) { td->td_stripbytecountsorted = 0; break; } } } if (!TIFFFieldSet(tif, FIELD_COMPRESSION)) TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE); /* * Some manufacturers make life difficult by writing * large amounts of uncompressed data as a single strip. * This is contrary to the recommendations of the spec. * The following makes an attempt at breaking such images * into strips closer to the recommended 8k bytes. A * side effect, however, is that the RowsPerStrip tag * value may be changed. */ if (td->td_nstrips == 1 && td->td_compression == COMPRESSION_NONE && (tif->tif_flags & (TIFF_STRIPCHOP|TIFF_ISTILED)) == TIFF_STRIPCHOP) ChopUpSingleUncompressedStrip(tif); /* * Reinitialize i/o since we are starting on a new directory. */ tif->tif_row = (uint32) -1; tif->tif_curstrip = (tstrip_t) -1; tif->tif_col = (uint32) -1; tif->tif_curtile = (ttile_t) -1; tif->tif_tilesize = (tsize_t) -1; tif->tif_scanlinesize = TIFFScanlineSize(tif); if (!tif->tif_scanlinesize) { TIFFErrorExt(tif->tif_clientdata, module, "%s: cannot handle zero scanline size", tif->tif_name); return (0); } if (isTiled(tif)) { tif->tif_tilesize = TIFFTileSize(tif); if (!tif->tif_tilesize) { TIFFErrorExt(tif->tif_clientdata, module, "%s: cannot handle zero tile size", tif->tif_name); return (0); } } else { if (!TIFFStripSize(tif)) { TIFFErrorExt(tif->tif_clientdata, module, "%s: cannot handle zero strip size", tif->tif_name); return (0); } } return (1); bad: if (dir) _TIFFfree(dir); return (0); } /* * Read custom directory from the arbitarry offset. * The code is very similar to TIFFReadDirectory(). */ int TIFFReadCustomDirectory(TIFF* tif, toff_t diroff, const TIFFFieldInfo info[], size_t n) { static const char module[] = "TIFFReadCustomDirectory"; TIFFDirectory* td = &tif->tif_dir; TIFFDirEntry *dp, *dir = NULL; const TIFFFieldInfo* fip; size_t fix; uint16 i, dircount; _TIFFSetupFieldInfo(tif, info, n); tif->tif_diroff = diroff; if (!isMapped(tif)) { if (!SeekOK(tif, diroff)) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Seek error accessing TIFF directory", tif->tif_name); return (0); } if (!ReadOK(tif, &dircount, sizeof (uint16))) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Can not read TIFF directory count", tif->tif_name); return (0); } if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); dir = (TIFFDirEntry *)_TIFFCheckMalloc(tif, dircount, sizeof (TIFFDirEntry), "to read TIFF directory"); if (dir == NULL) return (0); if (!ReadOK(tif, dir, dircount * sizeof (TIFFDirEntry))) { TIFFErrorExt(tif->tif_clientdata, module, "%.100s: Can not read TIFF directory", tif->tif_name); goto bad; } } else { toff_t off = diroff; if (off + sizeof (uint16) > tif->tif_size) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Can not read TIFF directory count", tif->tif_name); return (0); } else _TIFFmemcpy(&dircount, tif->tif_base + off, sizeof (uint16)); off += sizeof (uint16); if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount); dir = (TIFFDirEntry *)_TIFFCheckMalloc(tif, dircount, sizeof (TIFFDirEntry), "to read TIFF directory"); if (dir == NULL) return (0); if (off + dircount * sizeof (TIFFDirEntry) > tif->tif_size) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Can not read TIFF directory", tif->tif_name); goto bad; } else { _TIFFmemcpy(dir, tif->tif_base + off, dircount * sizeof (TIFFDirEntry)); } } TIFFFreeDirectory(tif); fix = 0; for (dp = dir, i = dircount; i > 0; i--, dp++) { if (tif->tif_flags & TIFF_SWAB) { TIFFSwabArrayOfShort(&dp->tdir_tag, 2); TIFFSwabArrayOfLong(&dp->tdir_count, 2); } if (fix >= tif->tif_nfields || dp->tdir_tag == IGNORE) continue; while (fix < tif->tif_nfields && tif->tif_fieldinfo[fix]->field_tag < dp->tdir_tag) fix++; if (fix >= tif->tif_nfields || tif->tif_fieldinfo[fix]->field_tag != dp->tdir_tag) { TIFFWarningExt(tif->tif_clientdata, module, "%s: unknown field with tag %d (0x%x) encountered", tif->tif_name, dp->tdir_tag, dp->tdir_tag, dp->tdir_type); TIFFMergeFieldInfo(tif, _TIFFCreateAnonFieldInfo(tif, dp->tdir_tag, (TIFFDataType)dp->tdir_type), 1); fix = 0; while (fix < tif->tif_nfields && tif->tif_fieldinfo[fix]->field_tag < dp->tdir_tag) fix++; } /* * Null out old tags that we ignore. */ if (tif->tif_fieldinfo[fix]->field_bit == FIELD_IGNORE) { ignore: dp->tdir_tag = IGNORE; continue; } /* * Check data type. */ fip = tif->tif_fieldinfo[fix]; while (dp->tdir_type != (unsigned short) fip->field_type && fix < tif->tif_nfields) { if (fip->field_type == TIFF_ANY) /* wildcard */ break; fip = tif->tif_fieldinfo[++fix]; if (fix >= tif->tif_nfields || fip->field_tag != dp->tdir_tag) { TIFFWarningExt(tif->tif_clientdata, module, "%s: wrong data type %d for \"%s\"; tag ignored", tif->tif_name, dp->tdir_type, tif->tif_fieldinfo[fix-1]->field_name); goto ignore; } } /* * Check count if known in advance. */ if (fip->field_readcount != TIFF_VARIABLE && fip->field_readcount != TIFF_VARIABLE2) { uint32 expected = (fip->field_readcount == TIFF_SPP) ? (uint32) td->td_samplesperpixel : (uint32) fip->field_readcount; if (!CheckDirCount(tif, dp, expected)) goto ignore; } (void) TIFFFetchNormalTag(tif, dp); } if (dir) _TIFFfree(dir); return 1; bad: if (dir) _TIFFfree(dir); return 0; } /* * EXIF is important special case of custom IFD, so we have a special * function to read it. */ int TIFFReadEXIFDirectory(TIFF* tif, toff_t diroff) { size_t exifFieldInfoCount; const TIFFFieldInfo *exifFieldInfo = _TIFFGetExifFieldInfo(&exifFieldInfoCount); return TIFFReadCustomDirectory(tif, diroff, exifFieldInfo, exifFieldInfoCount); } static int EstimateStripByteCounts(TIFF* tif, TIFFDirEntry* dir, uint16 dircount) { static const char module[] = "EstimateStripByteCounts"; register TIFFDirEntry *dp; register TIFFDirectory *td = &tif->tif_dir; uint16 i; if (td->td_stripbytecount) _TIFFfree(td->td_stripbytecount); td->td_stripbytecount = (uint32*) _TIFFCheckMalloc(tif, td->td_nstrips, sizeof (uint32), "for \"StripByteCounts\" array"); if (td->td_compression != COMPRESSION_NONE) { uint32 space = (uint32)(sizeof (TIFFHeader) + sizeof (uint16) + (dircount * sizeof (TIFFDirEntry)) + sizeof (uint32)); toff_t filesize = TIFFGetFileSize(tif); uint16 n; /* calculate amount of space used by indirect values */ for (dp = dir, n = dircount; n > 0; n--, dp++) { uint32 cc = TIFFDataWidth((TIFFDataType) dp->tdir_type); if (cc == 0) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Cannot determine size of unknown tag type %d", tif->tif_name, dp->tdir_type); return -1; } cc = cc * dp->tdir_count; if (cc > sizeof (uint32)) space += cc; } space = filesize - space; if (td->td_planarconfig == PLANARCONFIG_SEPARATE) space /= td->td_samplesperpixel; for (i = 0; i < td->td_nstrips; i++) td->td_stripbytecount[i] = space; /* * This gross hack handles the case were the offset to * the last strip is past the place where we think the strip * should begin. Since a strip of data must be contiguous, * it's safe to assume that we've overestimated the amount * of data in the strip and trim this number back accordingly. */ i--; if (((toff_t)(td->td_stripoffset[i]+td->td_stripbytecount[i])) > filesize) td->td_stripbytecount[i] = filesize - td->td_stripoffset[i]; } else { uint32 rowbytes = TIFFScanlineSize(tif); uint32 rowsperstrip = td->td_imagelength/td->td_stripsperimage; for (i = 0; i < td->td_nstrips; i++) td->td_stripbytecount[i] = rowbytes*rowsperstrip; } TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS); if (!TIFFFieldSet(tif, FIELD_ROWSPERSTRIP)) td->td_rowsperstrip = td->td_imagelength; return 1; } static void MissingRequired(TIFF* tif, const char* tagname) { static const char module[] = "MissingRequired"; TIFFErrorExt(tif->tif_clientdata, module, "%s: TIFF directory is missing required \"%s\" field", tif->tif_name, tagname); } /* * Check the count field of a directory * entry against a known value. The caller * is expected to skip/ignore the tag if * there is a mismatch. */ static int CheckDirCount(TIFF* tif, TIFFDirEntry* dir, uint32 count) { if (count > dir->tdir_count) { TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "incorrect count for field \"%s\" (%lu, expecting %lu); tag ignored", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name, dir->tdir_count, count); return (0); } else if (count < dir->tdir_count) { TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "incorrect count for field \"%s\" (%lu, expecting %lu); tag trimmed", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name, dir->tdir_count, count); return (1); } return (1); } /* * Fetch a contiguous directory item. */ static tsize_t TIFFFetchData(TIFF* tif, TIFFDirEntry* dir, char* cp) { int w = TIFFDataWidth((TIFFDataType) dir->tdir_type); tsize_t cc = dir->tdir_count * w; /* Check for overflow. */ if (!dir->tdir_count || !w || cc / w != (tsize_t)dir->tdir_count) goto bad; if (!isMapped(tif)) { if (!SeekOK(tif, dir->tdir_offset)) goto bad; if (!ReadOK(tif, cp, cc)) goto bad; } else { tsize_t offset = dir->tdir_offset + cc; /* Check for overflow. */ if ((tsize_t)dir->tdir_offset != offset - cc || offset > (tsize_t)tif->tif_size) goto bad; _TIFFmemcpy(cp, tif->tif_base + dir->tdir_offset, cc); } if (tif->tif_flags & TIFF_SWAB) { switch (dir->tdir_type) { case TIFF_SHORT: case TIFF_SSHORT: TIFFSwabArrayOfShort((uint16*) cp, dir->tdir_count); break; case TIFF_LONG: case TIFF_SLONG: case TIFF_FLOAT: TIFFSwabArrayOfLong((uint32*) cp, dir->tdir_count); break; case TIFF_RATIONAL: case TIFF_SRATIONAL: TIFFSwabArrayOfLong((uint32*) cp, 2*dir->tdir_count); break; case TIFF_DOUBLE: TIFFSwabArrayOfDouble((double*) cp, dir->tdir_count); break; } } return (cc); bad: TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Error fetching data for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); return (tsize_t) 0; } /* * Fetch an ASCII item from the file. */ static tsize_t TIFFFetchString(TIFF* tif, TIFFDirEntry* dir, char* cp) { if (dir->tdir_count <= 4) { uint32 l = dir->tdir_offset; if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong(&l); _TIFFmemcpy(cp, &l, dir->tdir_count); return (1); } return (TIFFFetchData(tif, dir, cp)); } /* * Convert numerator+denominator to float. */ static int cvtRational(TIFF* tif, TIFFDirEntry* dir, uint32 num, uint32 denom, float* rv) { if (denom == 0) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "%s: Rational with zero denominator (num = %lu)", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name, num); return (0); } else { if (dir->tdir_type == TIFF_RATIONAL) *rv = ((float)num / (float)denom); else *rv = ((float)(int32)num / (float)(int32)denom); return (1); } } /* * Fetch a rational item from the file * at offset off and return the value * as a floating point number. */ static float TIFFFetchRational(TIFF* tif, TIFFDirEntry* dir) { uint32 l[2]; float v; return (!TIFFFetchData(tif, dir, (char *)l) || !cvtRational(tif, dir, l[0], l[1], &v) ? 1.0f : v); } /* * Fetch a single floating point value * from the offset field and return it * as a native float. */ static float TIFFFetchFloat(TIFF* tif, TIFFDirEntry* dir) { float v; int32 l = TIFFExtractData(tif, dir->tdir_type, dir->tdir_offset); _TIFFmemcpy(&v, &l, sizeof(float)); TIFFCvtIEEEFloatToNative(tif, 1, &v); return (v); } /* * Fetch an array of BYTE or SBYTE values. */ static int TIFFFetchByteArray(TIFF* tif, TIFFDirEntry* dir, uint8* v) { if (dir->tdir_count <= 4) { /* * Extract data from offset field. */ if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) { if (dir->tdir_type == TIFF_SBYTE) switch (dir->tdir_count) { case 4: v[3] = dir->tdir_offset & 0xff; case 3: v[2] = (dir->tdir_offset >> 8) & 0xff; case 2: v[1] = (dir->tdir_offset >> 16) & 0xff; case 1: v[0] = dir->tdir_offset >> 24; } else switch (dir->tdir_count) { case 4: v[3] = dir->tdir_offset & 0xff; case 3: v[2] = (dir->tdir_offset >> 8) & 0xff; case 2: v[1] = (dir->tdir_offset >> 16) & 0xff; case 1: v[0] = dir->tdir_offset >> 24; } } else { if (dir->tdir_type == TIFF_SBYTE) switch (dir->tdir_count) { case 4: v[3] = dir->tdir_offset >> 24; case 3: v[2] = (dir->tdir_offset >> 16) & 0xff; case 2: v[1] = (dir->tdir_offset >> 8) & 0xff; case 1: v[0] = dir->tdir_offset & 0xff; } else switch (dir->tdir_count) { case 4: v[3] = dir->tdir_offset >> 24; case 3: v[2] = (dir->tdir_offset >> 16) & 0xff; case 2: v[1] = (dir->tdir_offset >> 8) & 0xff; case 1: v[0] = dir->tdir_offset & 0xff; } } return (1); } else return (TIFFFetchData(tif, dir, (char*) v) != 0); /* XXX */ } /* * Fetch an array of SHORT or SSHORT values. */ static int TIFFFetchShortArray(TIFF* tif, TIFFDirEntry* dir, uint16* v) { if (dir->tdir_count <= 2) { if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) { switch (dir->tdir_count) { case 2: v[1] = (uint16) (dir->tdir_offset & 0xffff); case 1: v[0] = (uint16) (dir->tdir_offset >> 16); } } else { switch (dir->tdir_count) { case 2: v[1] = (uint16) (dir->tdir_offset >> 16); case 1: v[0] = (uint16) (dir->tdir_offset & 0xffff); } } return (1); } else return (TIFFFetchData(tif, dir, (char *)v) != 0); } /* * Fetch a pair of SHORT or BYTE values. Some tags may have either BYTE * or SHORT type and this function works with both ones. */ static int TIFFFetchShortPair(TIFF* tif, TIFFDirEntry* dir) { switch (dir->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: { uint8 v[4]; return TIFFFetchByteArray(tif, dir, v) && TIFFSetField(tif, dir->tdir_tag, v[0], v[1]); } case TIFF_SHORT: case TIFF_SSHORT: { uint16 v[2]; return TIFFFetchShortArray(tif, dir, v) && TIFFSetField(tif, dir->tdir_tag, v[0], v[1]); } default: return 0; } } /* * Fetch an array of LONG or SLONG values. */ static int TIFFFetchLongArray(TIFF* tif, TIFFDirEntry* dir, uint32* v) { if (dir->tdir_count == 1) { v[0] = dir->tdir_offset; return (1); } else return (TIFFFetchData(tif, dir, (char*) v) != 0); } /* * Fetch an array of RATIONAL or SRATIONAL values. */ static int TIFFFetchRationalArray(TIFF* tif, TIFFDirEntry* dir, float* v) { int ok = 0; uint32* l; l = (uint32*)_TIFFCheckMalloc(tif, dir->tdir_count, TIFFDataWidth((TIFFDataType) dir->tdir_type), "to fetch array of rationals"); if (l) { if (TIFFFetchData(tif, dir, (char *)l)) { uint32 i; for (i = 0; i < dir->tdir_count; i++) { ok = cvtRational(tif, dir, l[2*i+0], l[2*i+1], &v[i]); if (!ok) break; } } _TIFFfree((char *)l); } return (ok); } /* * Fetch an array of FLOAT values. */ static int TIFFFetchFloatArray(TIFF* tif, TIFFDirEntry* dir, float* v) { if (dir->tdir_count == 1) { v[0] = *(float*) &dir->tdir_offset; TIFFCvtIEEEFloatToNative(tif, dir->tdir_count, v); return (1); } else if (TIFFFetchData(tif, dir, (char*) v)) { TIFFCvtIEEEFloatToNative(tif, dir->tdir_count, v); return (1); } else return (0); } /* * Fetch an array of DOUBLE values. */ static int TIFFFetchDoubleArray(TIFF* tif, TIFFDirEntry* dir, double* v) { if (TIFFFetchData(tif, dir, (char*) v)) { TIFFCvtIEEEDoubleToNative(tif, dir->tdir_count, v); return (1); } else return (0); } /* * Fetch an array of ANY values. The actual values are * returned as doubles which should be able hold all the * types. Yes, there really should be an tany_t to avoid * this potential non-portability ... Note in particular * that we assume that the double return value vector is * large enough to read in any fundamental type. We use * that vector as a buffer to read in the base type vector * and then convert it in place to double (from end * to front of course). */ static int TIFFFetchAnyArray(TIFF* tif, TIFFDirEntry* dir, double* v) { int i; switch (dir->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: if (!TIFFFetchByteArray(tif, dir, (uint8*) v)) return (0); if (dir->tdir_type == TIFF_BYTE) { uint8* vp = (uint8*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } else { int8* vp = (int8*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_SHORT: case TIFF_SSHORT: if (!TIFFFetchShortArray(tif, dir, (uint16*) v)) return (0); if (dir->tdir_type == TIFF_SHORT) { uint16* vp = (uint16*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } else { int16* vp = (int16*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_LONG: case TIFF_SLONG: if (!TIFFFetchLongArray(tif, dir, (uint32*) v)) return (0); if (dir->tdir_type == TIFF_LONG) { uint32* vp = (uint32*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } else { int32* vp = (int32*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_RATIONAL: case TIFF_SRATIONAL: if (!TIFFFetchRationalArray(tif, dir, (float*) v)) return (0); { float* vp = (float*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_FLOAT: if (!TIFFFetchFloatArray(tif, dir, (float*) v)) return (0); { float* vp = (float*) v; for (i = dir->tdir_count-1; i >= 0; i--) v[i] = vp[i]; } break; case TIFF_DOUBLE: return (TIFFFetchDoubleArray(tif, dir, (double*) v)); default: /* TIFF_NOTYPE */ /* TIFF_ASCII */ /* TIFF_UNDEFINED */ TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "cannot read TIFF_ANY type %d for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); return (0); } return (1); } /* * Fetch a tag that is not handled by special case code. */ static int TIFFFetchNormalTag(TIFF* tif, TIFFDirEntry* dp) { static const char mesg[] = "to fetch tag value"; int ok = 0; const TIFFFieldInfo* fip = _TIFFFieldWithTag(tif, dp->tdir_tag); if (dp->tdir_count > 1) { /* array of values */ char* cp = NULL; switch (dp->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: cp = (char *)_TIFFCheckMalloc(tif, dp->tdir_count, sizeof (uint8), mesg); ok = cp && TIFFFetchByteArray(tif, dp, (uint8*) cp); break; case TIFF_SHORT: case TIFF_SSHORT: cp = (char *)_TIFFCheckMalloc(tif, dp->tdir_count, sizeof (uint16), mesg); ok = cp && TIFFFetchShortArray(tif, dp, (uint16*) cp); break; case TIFF_LONG: case TIFF_SLONG: cp = (char *)_TIFFCheckMalloc(tif, dp->tdir_count, sizeof (uint32), mesg); ok = cp && TIFFFetchLongArray(tif, dp, (uint32*) cp); break; case TIFF_RATIONAL: case TIFF_SRATIONAL: cp = (char *)_TIFFCheckMalloc(tif, dp->tdir_count, sizeof (float), mesg); ok = cp && TIFFFetchRationalArray(tif, dp, (float*) cp); break; case TIFF_FLOAT: cp = (char *)_TIFFCheckMalloc(tif, dp->tdir_count, sizeof (float), mesg); ok = cp && TIFFFetchFloatArray(tif, dp, (float*) cp); break; case TIFF_DOUBLE: cp = (char *)_TIFFCheckMalloc(tif, dp->tdir_count, sizeof (double), mesg); ok = cp && TIFFFetchDoubleArray(tif, dp, (double*) cp); break; case TIFF_ASCII: case TIFF_UNDEFINED: /* bit of a cheat... */ /* * Some vendors write strings w/o the trailing * NULL byte, so always append one just in case. */ cp = (char *)_TIFFCheckMalloc(tif, dp->tdir_count + 1, 1, mesg); if( (ok = (cp && TIFFFetchString(tif, dp, cp))) != 0 ) cp[dp->tdir_count] = '\0'; /* XXX */ break; } if (ok) { ok = (fip->field_passcount ? TIFFSetField(tif, dp->tdir_tag, dp->tdir_count, cp) : TIFFSetField(tif, dp->tdir_tag, cp)); } if (cp != NULL) _TIFFfree(cp); } else if (CheckDirCount(tif, dp, 1)) { /* singleton value */ switch (dp->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: case TIFF_SHORT: case TIFF_SSHORT: /* * If the tag is also acceptable as a LONG or SLONG * then TIFFSetField will expect an uint32 parameter * passed to it (through varargs). Thus, for machines * where sizeof (int) != sizeof (uint32) we must do * a careful check here. It's hard to say if this * is worth optimizing. * * NB: We use TIFFFieldWithTag here knowing that * it returns us the first entry in the table * for the tag and that that entry is for the * widest potential data type the tag may have. */ { TIFFDataType type = fip->field_type; if (type != TIFF_LONG && type != TIFF_SLONG) { uint16 v = (uint16) TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset); ok = (fip->field_passcount ? TIFFSetField(tif, dp->tdir_tag, 1, &v) : TIFFSetField(tif, dp->tdir_tag, v)); break; } } /* fall thru... */ case TIFF_LONG: case TIFF_SLONG: { uint32 v32 = TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset); ok = (fip->field_passcount ? TIFFSetField(tif, dp->tdir_tag, 1, &v32) : TIFFSetField(tif, dp->tdir_tag, v32)); } break; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: { float v = (dp->tdir_type == TIFF_FLOAT ? TIFFFetchFloat(tif, dp) : TIFFFetchRational(tif, dp)); ok = (fip->field_passcount ? TIFFSetField(tif, dp->tdir_tag, 1, &v) : TIFFSetField(tif, dp->tdir_tag, v)); } break; case TIFF_DOUBLE: { double v; ok = (TIFFFetchDoubleArray(tif, dp, &v) && (fip->field_passcount ? TIFFSetField(tif, dp->tdir_tag, 1, &v) : TIFFSetField(tif, dp->tdir_tag, v)) ); } break; case TIFF_ASCII: case TIFF_UNDEFINED: /* bit of a cheat... */ { char c[2]; if( (ok = (TIFFFetchString(tif, dp, c) != 0)) != 0 ) { c[1] = '\0'; /* XXX paranoid */ ok = (fip->field_passcount ? TIFFSetField(tif, dp->tdir_tag, 1, c) : TIFFSetField(tif, dp->tdir_tag, c)); } } break; } } return (ok); } #define NITEMS(x) (sizeof (x) / sizeof (x[0])) /* * Fetch samples/pixel short values for * the specified tag and verify that * all values are the same. */ static int TIFFFetchPerSampleShorts(TIFF* tif, TIFFDirEntry* dir, uint16* pl) { uint16 samples = tif->tif_dir.td_samplesperpixel; int status = 0; if (CheckDirCount(tif, dir, (uint32) samples)) { uint16 buf[10]; uint16* v = buf; if (dir->tdir_count > NITEMS(buf)) v = (uint16*) _TIFFCheckMalloc(tif, dir->tdir_count, sizeof(uint16), "to fetch per-sample values"); if (v && TIFFFetchShortArray(tif, dir, v)) { uint16 i; int check_count = dir->tdir_count; if( samples < check_count ) check_count = samples; for (i = 1; i < check_count; i++) if (v[i] != v[0]) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Cannot handle different per-sample values for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); goto bad; } *pl = v[0]; status = 1; } bad: if (v && v != buf) _TIFFfree(v); } return (status); } /* * Fetch samples/pixel long values for * the specified tag and verify that * all values are the same. */ static int TIFFFetchPerSampleLongs(TIFF* tif, TIFFDirEntry* dir, uint32* pl) { uint16 samples = tif->tif_dir.td_samplesperpixel; int status = 0; if (CheckDirCount(tif, dir, (uint32) samples)) { uint32 buf[10]; uint32* v = buf; if (dir->tdir_count > NITEMS(buf)) v = (uint32*) _TIFFCheckMalloc(tif, dir->tdir_count, sizeof(uint32), "to fetch per-sample values"); if (v && TIFFFetchLongArray(tif, dir, v)) { uint16 i; int check_count = dir->tdir_count; if( samples < check_count ) check_count = samples; for (i = 1; i < check_count; i++) if (v[i] != v[0]) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Cannot handle different per-sample values for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); goto bad; } *pl = v[0]; status = 1; } bad: if (v && v != buf) _TIFFfree(v); } return (status); } /* * Fetch samples/pixel ANY values for the specified tag and verify that all * values are the same. */ static int TIFFFetchPerSampleAnys(TIFF* tif, TIFFDirEntry* dir, double* pl) { uint16 samples = tif->tif_dir.td_samplesperpixel; int status = 0; if (CheckDirCount(tif, dir, (uint32) samples)) { double buf[10]; double* v = buf; if (dir->tdir_count > NITEMS(buf)) v = (double*) _TIFFCheckMalloc(tif, dir->tdir_count, sizeof (double), "to fetch per-sample values"); if (v && TIFFFetchAnyArray(tif, dir, v)) { uint16 i; int check_count = dir->tdir_count; if( samples < check_count ) check_count = samples; for (i = 1; i < check_count; i++) if (v[i] != v[0]) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Cannot handle different per-sample values for field \"%s\"", _TIFFFieldWithTag(tif, dir->tdir_tag)->field_name); goto bad; } *pl = v[0]; status = 1; } bad: if (v && v != buf) _TIFFfree(v); } return (status); } #undef NITEMS /* * Fetch a set of offsets or lengths. * While this routine says "strips", in fact it's also used for tiles. */ static int TIFFFetchStripThing(TIFF* tif, TIFFDirEntry* dir, long nstrips, uint32** lpp) { register uint32* lp; int status; CheckDirCount(tif, dir, (uint32) nstrips); /* * Allocate space for strip information. */ if (*lpp == NULL && (*lpp = (uint32 *)_TIFFCheckMalloc(tif, nstrips, sizeof (uint32), "for strip array")) == NULL) return (0); lp = *lpp; _TIFFmemset( lp, 0, sizeof(uint32) * nstrips ); if (dir->tdir_type == (int)TIFF_SHORT) { /* * Handle uint16->uint32 expansion. */ uint16* dp = (uint16*) _TIFFCheckMalloc(tif, dir->tdir_count, sizeof (uint16), "to fetch strip tag"); if (dp == NULL) return (0); if( (status = TIFFFetchShortArray(tif, dir, dp)) != 0 ) { int i; for( i = 0; i < nstrips && i < (int) dir->tdir_count; i++ ) { lp[i] = dp[i]; } } _TIFFfree((char*) dp); } else if( nstrips != (int) dir->tdir_count ) { /* Special case to correct length */ uint32* dp = (uint32*) _TIFFCheckMalloc(tif, dir->tdir_count, sizeof (uint32), "to fetch strip tag"); if (dp == NULL) return (0); status = TIFFFetchLongArray(tif, dir, dp); if( status != 0 ) { int i; for( i = 0; i < nstrips && i < (int) dir->tdir_count; i++ ) { lp[i] = dp[i]; } } _TIFFfree( (char *) dp ); } else status = TIFFFetchLongArray(tif, dir, lp); return (status); } /* * Fetch and set the RefBlackWhite tag. */ static int TIFFFetchRefBlackWhite(TIFF* tif, TIFFDirEntry* dir) { static const char mesg[] = "for \"ReferenceBlackWhite\" array"; char* cp; int ok; if (dir->tdir_type == TIFF_RATIONAL) return (TIFFFetchNormalTag(tif, dir)); /* * Handle LONG's for backward compatibility. */ cp = (char *)_TIFFCheckMalloc(tif, dir->tdir_count, sizeof (uint32), mesg); if( (ok = (cp && TIFFFetchLongArray(tif, dir, (uint32*) cp))) != 0) { float* fp = (float*) _TIFFCheckMalloc(tif, dir->tdir_count, sizeof (float), mesg); if( (ok = (fp != NULL)) != 0 ) { uint32 i; for (i = 0; i < dir->tdir_count; i++) fp[i] = (float)((uint32*) cp)[i]; ok = TIFFSetField(tif, dir->tdir_tag, fp); _TIFFfree((char*) fp); } } if (cp) _TIFFfree(cp); return (ok); } /* * Replace a single strip (tile) of uncompressed data by * multiple strips (tiles), each approximately 8Kbytes. * This is useful for dealing with large images or * for dealing with machines with a limited amount * memory. */ static void ChopUpSingleUncompressedStrip(TIFF* tif) { register TIFFDirectory *td = &tif->tif_dir; uint32 bytecount = td->td_stripbytecount[0]; uint32 offset = td->td_stripoffset[0]; tsize_t rowbytes = TIFFVTileSize(tif, 1), stripbytes; tstrip_t strip, nstrips, rowsperstrip; uint32* newcounts; uint32* newoffsets; /* * Make the rows hold at least one scanline, but fill specified amount * of data if possible. */ #ifndef STRIP_SIZE_DEFAULT # define STRIP_SIZE_DEFAULT 8192 #endif if (rowbytes > STRIP_SIZE_DEFAULT) { stripbytes = rowbytes; rowsperstrip = 1; } else if (rowbytes > 0 ) { rowsperstrip = STRIP_SIZE_DEFAULT / rowbytes; stripbytes = rowbytes * rowsperstrip; } else return; #undef STRIP_SIZE_DEFAULT /* * never increase the number of strips in an image */ if (rowsperstrip >= td->td_rowsperstrip) return; nstrips = (tstrip_t) TIFFhowmany(bytecount, stripbytes); if( nstrips == 0 ) /* something is wonky, do nothing. */ return; newcounts = (uint32*) _TIFFCheckMalloc(tif, nstrips, sizeof (uint32), "for chopped \"StripByteCounts\" array"); newoffsets = (uint32*) _TIFFCheckMalloc(tif, nstrips, sizeof (uint32), "for chopped \"StripOffsets\" array"); if (newcounts == NULL || newoffsets == NULL) { /* * Unable to allocate new strip information, give * up and use the original one strip information. */ if (newcounts != NULL) _TIFFfree(newcounts); if (newoffsets != NULL) _TIFFfree(newoffsets); return; } /* * Fill the strip information arrays with new bytecounts and offsets * that reflect the broken-up format. */ for (strip = 0; strip < nstrips; strip++) { if (stripbytes > (tsize_t) bytecount) stripbytes = bytecount; newcounts[strip] = stripbytes; newoffsets[strip] = offset; offset += stripbytes; bytecount -= stripbytes; } /* * Replace old single strip info with multi-strip info. */ td->td_stripsperimage = td->td_nstrips = nstrips; TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, rowsperstrip); _TIFFfree(td->td_stripbytecount); _TIFFfree(td->td_stripoffset); td->td_stripbytecount = newcounts; td->td_stripoffset = newoffsets; td->td_stripbytecountsorted = 1; } /* vim: set ts=8 sts=8 sw=8 noet: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/libtiff_2006-03-03-a72cf60-0a36d7f.c
manybugs_data_72
/* This file is part of drd, a thread error detector. Copyright (C) 2006-2011 Bart Van Assche <[email protected]>. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. The GNU General Public License is contained in the file COPYING. */ #include "drd_bitmap.h" #include "drd_thread_bitmap.h" #include "drd_vc.h" /* DRD_(vc_snprint)() */ /* Include several source files here in order to allow the compiler to */ /* do more inlining. */ #include "drd_bitmap.c" #include "drd_load_store.h" #include "drd_segment.c" #include "drd_thread.c" #include "drd_vc.c" #include "libvex_guest_offsets.h" /* STACK_POINTER_OFFSET: VEX register offset for the stack pointer register. */ #if defined(VGA_x86) #define STACK_POINTER_OFFSET OFFSET_x86_ESP #elif defined(VGA_amd64) #define STACK_POINTER_OFFSET OFFSET_amd64_RSP #elif defined(VGA_ppc32) #define STACK_POINTER_OFFSET OFFSET_ppc32_GPR1 #elif defined(VGA_ppc64) #define STACK_POINTER_OFFSET OFFSET_ppc64_GPR1 #elif defined(VGA_arm) #define STACK_POINTER_OFFSET OFFSET_arm_R13 #elif defined(VGA_s390x) #define STACK_POINTER_OFFSET OFFSET_s390x_r15 #else #error Unknown architecture. #endif /* Local variables. */ static Bool s_check_stack_accesses = False; static Bool s_first_race_only = False; /* Function definitions. */ Bool DRD_(get_check_stack_accesses)() { return s_check_stack_accesses; } void DRD_(set_check_stack_accesses)(const Bool c) { tl_assert(c == False || c == True); s_check_stack_accesses = c; } Bool DRD_(get_first_race_only)() { return s_first_race_only; } void DRD_(set_first_race_only)(const Bool fro) { tl_assert(fro == False || fro == True); s_first_race_only = fro; } void DRD_(trace_mem_access)(const Addr addr, const SizeT size, const BmAccessTypeT access_type, const HWord stored_value_hi, const HWord stored_value_lo) { if (DRD_(is_any_traced)(addr, addr + size)) { char* vc; vc = DRD_(vc_aprint)(DRD_(thread_get_vc)(DRD_(thread_get_running_tid)())); if (access_type == eStore && size <= sizeof(HWord)) { DRD_(trace_msg_w_bt)("store 0x%lx size %ld val %ld/0x%lx (thread %d /" " vc %s)", addr, size, stored_value_lo, stored_value_lo, DRD_(thread_get_running_tid)(), vc); } else if (access_type == eStore && size > sizeof(HWord)) { ULong sv; tl_assert(sizeof(HWord) == 4); sv = ((ULong)stored_value_hi << 32) | stored_value_lo; DRD_(trace_msg_w_bt)("store 0x%lx size %ld val %lld/0x%llx (thread %d" " / vc %s)", addr, size, sv, sv, DRD_(thread_get_running_tid)(), vc); } else { DRD_(trace_msg_w_bt)("%s 0x%lx size %ld (thread %d / vc %s)", access_type == eLoad ? "load " : access_type == eStore ? "store" : access_type == eStart ? "start" : access_type == eEnd ? "end " : "????", addr, size, DRD_(thread_get_running_tid)(), vc); } VG_(free)(vc); tl_assert(DRD_(DrdThreadIdToVgThreadId)(DRD_(thread_get_running_tid)()) == VG_(get_running_tid)()); } } static VG_REGPARM(2) void drd_trace_mem_load(const Addr addr, const SizeT size) { return DRD_(trace_mem_access)(addr, size, eLoad, 0, 0); } static VG_REGPARM(3) void drd_trace_mem_store(const Addr addr,const SizeT size, const HWord stored_value_hi, const HWord stored_value_lo) { return DRD_(trace_mem_access)(addr, size, eStore, stored_value_hi, stored_value_lo); } static void drd_report_race(const Addr addr, const SizeT size, const BmAccessTypeT access_type) { ThreadId vg_tid; vg_tid = VG_(get_running_tid)(); if (DRD_(thread_address_on_any_stack)(addr)) { #if 0 GenericErrInfo GEI = { .tid = DRD_(thread_get_running_tid)(), .addr = addr, }; VG_(maybe_record_error)(vg_tid, GenericErr, VG_(get_IP)(vg_tid), "--check-stack-var=no skips checking stack" " variables shared over threads", &GEI); #endif } else { DataRaceErrInfo drei = { .tid = DRD_(thread_get_running_tid)(), .addr = addr, .size = size, .access_type = access_type, }; VG_(maybe_record_error)(vg_tid, DataRaceErr, VG_(get_IP)(vg_tid), "Conflicting access", &drei); if (s_first_race_only) DRD_(start_suppression)(addr, addr + size, "first race only"); } } VG_REGPARM(2) void DRD_(trace_load)(Addr addr, SizeT size) { #ifdef ENABLE_DRD_CONSISTENCY_CHECKS /* The assert below has been commented out because of performance reasons.*/ tl_assert(DRD_(thread_get_running_tid)() == DRD_(VgThreadIdToDrdThreadId)(VG_(get_running_tid()))); #endif if (DRD_(running_thread_is_recording_loads)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_load_triggers_conflict(addr, addr + size) && ! DRD_(is_suppressed)(addr, addr + size)) { drd_report_race(addr, size, eLoad); } } static VG_REGPARM(1) void drd_trace_load_1(Addr addr) { if (DRD_(running_thread_is_recording_loads)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_load_1_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 1)) { drd_report_race(addr, 1, eLoad); } } static VG_REGPARM(1) void drd_trace_load_2(Addr addr) { if (DRD_(running_thread_is_recording_loads)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_load_2_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 2)) { drd_report_race(addr, 2, eLoad); } } static VG_REGPARM(1) void drd_trace_load_4(Addr addr) { if (DRD_(running_thread_is_recording_loads)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_load_4_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 4)) { drd_report_race(addr, 4, eLoad); } } static VG_REGPARM(1) void drd_trace_load_8(Addr addr) { if (DRD_(running_thread_is_recording_loads)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_load_8_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 8)) { drd_report_race(addr, 8, eLoad); } } VG_REGPARM(2) void DRD_(trace_store)(Addr addr, SizeT size) { #ifdef ENABLE_DRD_CONSISTENCY_CHECKS /* The assert below has been commented out because of performance reasons.*/ tl_assert(DRD_(thread_get_running_tid)() == DRD_(VgThreadIdToDrdThreadId)(VG_(get_running_tid()))); #endif if (DRD_(running_thread_is_recording_stores)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_store_triggers_conflict(addr, addr + size) && ! DRD_(is_suppressed)(addr, addr + size)) { drd_report_race(addr, size, eStore); } } static VG_REGPARM(1) void drd_trace_store_1(Addr addr) { if (DRD_(running_thread_is_recording_stores)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_store_1_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 1)) { drd_report_race(addr, 1, eStore); } } static VG_REGPARM(1) void drd_trace_store_2(Addr addr) { if (DRD_(running_thread_is_recording_stores)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_store_2_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 2)) { drd_report_race(addr, 2, eStore); } } static VG_REGPARM(1) void drd_trace_store_4(Addr addr) { if (DRD_(running_thread_is_recording_stores)() && (s_check_stack_accesses || !DRD_(thread_address_on_stack)(addr)) && bm_access_store_4_triggers_conflict(addr) && !DRD_(is_suppressed)(addr, addr + 4)) { drd_report_race(addr, 4, eStore); } } static VG_REGPARM(1) void drd_trace_store_8(Addr addr) { if (DRD_(running_thread_is_recording_stores)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_store_8_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 8)) { drd_report_race(addr, 8, eStore); } } /** * Return true if and only if addr_expr matches the pattern (SP) or * <offset>(SP). */ static Bool is_stack_access(IRSB* const bb, IRExpr* const addr_expr) { Bool result = False; if (addr_expr->tag == Iex_RdTmp) { int i; for (i = 0; i < bb->stmts_size; i++) { if (bb->stmts[i] && bb->stmts[i]->tag == Ist_WrTmp && bb->stmts[i]->Ist.WrTmp.tmp == addr_expr->Iex.RdTmp.tmp) { IRExpr* e = bb->stmts[i]->Ist.WrTmp.data; if (e->tag == Iex_Get && e->Iex.Get.offset == STACK_POINTER_OFFSET) { result = True; } //ppIRExpr(e); //VG_(printf)(" (%s)\n", result ? "True" : "False"); break; } } } return result; } static const IROp u_widen_irop[5][9] = { [Ity_I1 - Ity_I1] = { [4] = Iop_1Uto32, [8] = Iop_1Uto64 }, [Ity_I8 - Ity_I1] = { [4] = Iop_8Uto32, [8] = Iop_8Uto64 }, [Ity_I16 - Ity_I1] = { [4] = Iop_16Uto32, [8] = Iop_16Uto64 }, [Ity_I32 - Ity_I1] = { [8] = Iop_32Uto64 }, }; /** * Instrument the client code to trace a memory load (--trace-addr). */ static IRExpr* instr_trace_mem_load(IRSB* const bb, IRExpr* addr_expr, const HWord size) { IRTemp tmp; tmp = newIRTemp(bb->tyenv, typeOfIRExpr(bb->tyenv, addr_expr)); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, addr_expr)); addr_expr = IRExpr_RdTmp(tmp); addStmtToIRSB(bb, IRStmt_Dirty( unsafeIRDirty_0_N(/*regparms*/2, "drd_trace_mem_load", VG_(fnptr_to_fnentry) (drd_trace_mem_load), mkIRExprVec_2(addr_expr, mkIRExpr_HWord(size))))); return addr_expr; } /** * Instrument the client code to trace a memory store (--trace-addr). */ static void instr_trace_mem_store(IRSB* const bb, IRExpr* const addr_expr, IRExpr* data_expr_hi, IRExpr* data_expr_lo) { IRType ty_data_expr; HWord size; tl_assert(sizeof(HWord) == 4 || sizeof(HWord) == 8); tl_assert(!data_expr_hi || typeOfIRExpr(bb->tyenv, data_expr_hi) == Ity_I32); ty_data_expr = typeOfIRExpr(bb->tyenv, data_expr_lo); size = sizeofIRType(ty_data_expr); #if 0 // Test code if (ty_data_expr == Ity_I32) { IRTemp tmp = newIRTemp(bb->tyenv, Ity_F32); data_expr_lo = IRExpr_Unop(Iop_ReinterpI32asF32, data_expr_lo); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, data_expr_lo)); data_expr_lo = IRExpr_RdTmp(tmp); ty_data_expr = Ity_F32; } else if (ty_data_expr == Ity_I64) { IRTemp tmp = newIRTemp(bb->tyenv, Ity_F64); data_expr_lo = IRExpr_Unop(Iop_ReinterpI64asF64, data_expr_lo); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, data_expr_lo)); data_expr_lo = IRExpr_RdTmp(tmp); ty_data_expr = Ity_F64; } #endif if (ty_data_expr == Ity_F32) { IRTemp tmp = newIRTemp(bb->tyenv, Ity_I32); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, IRExpr_Unop(Iop_ReinterpF32asI32, data_expr_lo))); data_expr_lo = IRExpr_RdTmp(tmp); ty_data_expr = Ity_I32; } else if (ty_data_expr == Ity_F64) { IRTemp tmp = newIRTemp(bb->tyenv, Ity_I64); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, IRExpr_Unop(Iop_ReinterpF64asI64, data_expr_lo))); data_expr_lo = IRExpr_RdTmp(tmp); ty_data_expr = Ity_I64; } if (size == sizeof(HWord) && (ty_data_expr == Ity_I32 || ty_data_expr == Ity_I64)) { /* No conversion necessary */ } else { IROp widen_op; if (Ity_I1 <= ty_data_expr && ty_data_expr < Ity_I1 + sizeof(u_widen_irop)/sizeof(u_widen_irop[0])) { widen_op = u_widen_irop[ty_data_expr - Ity_I1][sizeof(HWord)]; if (!widen_op) widen_op = Iop_INVALID; } else { widen_op = Iop_INVALID; } if (widen_op != Iop_INVALID) { IRTemp tmp; /* Widen the integer expression to a HWord */ tmp = newIRTemp(bb->tyenv, sizeof(HWord) == 4 ? Ity_I32 : Ity_I64); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, IRExpr_Unop(widen_op, data_expr_lo))); data_expr_lo = IRExpr_RdTmp(tmp); } else if (size > sizeof(HWord) && !data_expr_hi && ty_data_expr == Ity_I64) { IRTemp tmp; tl_assert(sizeof(HWord) == 4); tl_assert(size == 8); tmp = newIRTemp(bb->tyenv, Ity_I32); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, IRExpr_Unop(Iop_64HIto32, data_expr_lo))); data_expr_hi = IRExpr_RdTmp(tmp); tmp = newIRTemp(bb->tyenv, Ity_I32); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, IRExpr_Unop(Iop_64to32, data_expr_lo))); data_expr_lo = IRExpr_RdTmp(tmp); } else { data_expr_lo = mkIRExpr_HWord(0); } } addStmtToIRSB(bb, IRStmt_Dirty( unsafeIRDirty_0_N(/*regparms*/3, "drd_trace_mem_store", VG_(fnptr_to_fnentry)(drd_trace_mem_store), mkIRExprVec_4(addr_expr, mkIRExpr_HWord(size), data_expr_hi ? data_expr_hi : mkIRExpr_HWord(0), data_expr_lo)))); } static void instrument_load(IRSB* const bb, IRExpr* const addr_expr, const HWord size) { IRExpr* size_expr; IRExpr** argv; IRDirty* di; if (!s_check_stack_accesses && is_stack_access(bb, addr_expr)) return; switch (size) { case 1: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_load_1", VG_(fnptr_to_fnentry)(drd_trace_load_1), argv); break; case 2: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_load_2", VG_(fnptr_to_fnentry)(drd_trace_load_2), argv); break; case 4: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_load_4", VG_(fnptr_to_fnentry)(drd_trace_load_4), argv); break; case 8: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_load_8", VG_(fnptr_to_fnentry)(drd_trace_load_8), argv); break; default: size_expr = mkIRExpr_HWord(size); argv = mkIRExprVec_2(addr_expr, size_expr); di = unsafeIRDirty_0_N(/*regparms*/2, "drd_trace_load", VG_(fnptr_to_fnentry)(DRD_(trace_load)), argv); break; } addStmtToIRSB(bb, IRStmt_Dirty(di)); } static void instrument_store(IRSB* const bb, IRExpr* addr_expr, IRExpr* const data_expr) { IRExpr* size_expr; IRExpr** argv; IRDirty* di; HWord size; size = sizeofIRType(typeOfIRExpr(bb->tyenv, data_expr)); if (UNLIKELY(DRD_(any_address_is_traced)())) { IRTemp tmp = newIRTemp(bb->tyenv, typeOfIRExpr(bb->tyenv, addr_expr)); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, addr_expr)); addr_expr = IRExpr_RdTmp(tmp); instr_trace_mem_store(bb, addr_expr, NULL, data_expr); } if (!s_check_stack_accesses && is_stack_access(bb, addr_expr)) return; switch (size) { case 1: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_store_1", VG_(fnptr_to_fnentry)(drd_trace_store_1), argv); break; case 2: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_store_2", VG_(fnptr_to_fnentry)(drd_trace_store_2), argv); break; case 4: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_store_4", VG_(fnptr_to_fnentry)(drd_trace_store_4), argv); break; case 8: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_store_8", VG_(fnptr_to_fnentry)(drd_trace_store_8), argv); break; default: size_expr = mkIRExpr_HWord(size); argv = mkIRExprVec_2(addr_expr, size_expr); di = unsafeIRDirty_0_N(/*regparms*/2, "drd_trace_store", VG_(fnptr_to_fnentry)(DRD_(trace_store)), argv); break; } addStmtToIRSB(bb, IRStmt_Dirty(di)); } IRSB* DRD_(instrument)(VgCallbackClosure* const closure, IRSB* const bb_in, VexGuestLayout* const layout, VexGuestExtents* const vge, IRType const gWordTy, IRType const hWordTy) { IRDirty* di; Int i; IRSB* bb; IRExpr** argv; Bool instrument = True; /* Set up BB */ bb = emptyIRSB(); bb->tyenv = deepCopyIRTypeEnv(bb_in->tyenv); bb->next = deepCopyIRExpr(bb_in->next); bb->jumpkind = bb_in->jumpkind; for (i = 0; i < bb_in->stmts_used; i++) { IRStmt* const st = bb_in->stmts[i]; tl_assert(st); tl_assert(isFlatIRStmt(st)); switch (st->tag) { /* Note: the code for not instrumenting the code in .plt */ /* sections is only necessary on CentOS 3.0 x86 (kernel 2.4.21 */ /* + glibc 2.3.2 + NPTL 0.60 + binutils 2.14.90.0.4). */ /* This is because on this platform dynamic library symbols are */ /* relocated in another way than by later binutils versions. The */ /* linker e.g. does not generate .got.plt sections on CentOS 3.0. */ case Ist_IMark: instrument = VG_(DebugInfo_sect_kind)(NULL, 0, st->Ist.IMark.addr) != Vg_SectPLT; addStmtToIRSB(bb, st); break; case Ist_MBE: switch (st->Ist.MBE.event) { case Imbe_Fence: break; /* not interesting */ default: tl_assert(0); } addStmtToIRSB(bb, st); break; case Ist_Store: if (instrument) instrument_store(bb, st->Ist.Store.addr, st->Ist.Store.data); addStmtToIRSB(bb, st); break; case Ist_WrTmp: if (instrument) { const IRExpr* const data = st->Ist.WrTmp.data; IRExpr* addr_expr = data->Iex.Load.addr; if (data->tag == Iex_Load) { if (UNLIKELY(DRD_(any_address_is_traced)())) { addr_expr = instr_trace_mem_load(bb, addr_expr, sizeofIRType(data->Iex.Load.ty)); } instrument_load(bb, data->Iex.Load.addr, sizeofIRType(data->Iex.Load.ty)); } } addStmtToIRSB(bb, st); break; case Ist_Dirty: if (instrument) { IRDirty* d = st->Ist.Dirty.details; IREffect const mFx = d->mFx; switch (mFx) { case Ifx_None: break; case Ifx_Read: case Ifx_Write: case Ifx_Modify: tl_assert(d->mAddr); tl_assert(d->mSize > 0); argv = mkIRExprVec_2(d->mAddr, mkIRExpr_HWord(d->mSize)); if (mFx == Ifx_Read || mFx == Ifx_Modify) { di = unsafeIRDirty_0_N( /*regparms*/2, "drd_trace_load", VG_(fnptr_to_fnentry)(DRD_(trace_load)), argv); addStmtToIRSB(bb, IRStmt_Dirty(di)); } if (mFx == Ifx_Write || mFx == Ifx_Modify) { di = unsafeIRDirty_0_N( /*regparms*/2, "drd_trace_store", VG_(fnptr_to_fnentry)(DRD_(trace_store)), argv); addStmtToIRSB(bb, IRStmt_Dirty(di)); } break; default: tl_assert(0); } } addStmtToIRSB(bb, st); break; case Ist_CAS: if (instrument) { /* * Treat compare-and-swap as a read. By handling atomic * instructions as read instructions no data races are reported * between conflicting atomic operations nor between atomic * operations and non-atomic reads. Conflicts between atomic * operations and non-atomic write operations are still reported * however. */ Int dataSize; IRCAS* cas = st->Ist.CAS.details; tl_assert(cas->addr != NULL); tl_assert(cas->dataLo != NULL); dataSize = sizeofIRType(typeOfIRExpr(bb->tyenv, cas->dataLo)); if (cas->dataHi != NULL) dataSize *= 2; /* since it's a doubleword-CAS */ if (UNLIKELY(DRD_(any_address_is_traced)())) instr_trace_mem_store(bb, cas->addr, cas->dataHi, cas->dataLo); instrument_load(bb, cas->addr, dataSize); } addStmtToIRSB(bb, st); break; case Ist_LLSC: { /* * Ignore store-conditionals (except for tracing), and handle * load-linked's exactly like normal loads. */ IRType dataTy; if (st->Ist.LLSC.storedata == NULL) { /* LL */ dataTy = typeOfIRTemp(bb_in->tyenv, st->Ist.LLSC.result); if (instrument) { IRExpr* addr_expr = st->Ist.LLSC.addr; if (UNLIKELY(DRD_(any_address_is_traced)())) addr_expr = instr_trace_mem_load(bb, addr_expr, sizeofIRType(dataTy)); instrument_load(bb, addr_expr, sizeofIRType(dataTy)); } } else { /* SC */ instr_trace_mem_store(bb, st->Ist.LLSC.addr, NULL, st->Ist.LLSC.storedata); } addStmtToIRSB(bb, st); break; } case Ist_NoOp: case Ist_AbiHint: case Ist_Put: case Ist_PutI: case Ist_Exit: /* None of these can contain any memory references. */ addStmtToIRSB(bb, st); break; default: ppIRStmt(st); tl_assert(0); } } return bb; } /* This file is part of drd, a thread error detector. Copyright (C) 2006-2011 Bart Van Assche <[email protected]>. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. The GNU General Public License is contained in the file COPYING. */ #include "drd_bitmap.h" #include "drd_thread_bitmap.h" #include "drd_vc.h" /* DRD_(vc_snprint)() */ /* Include several source files here in order to allow the compiler to */ /* do more inlining. */ #include "drd_bitmap.c" #include "drd_load_store.h" #include "drd_segment.c" #include "drd_thread.c" #include "drd_vc.c" #include "libvex_guest_offsets.h" /* STACK_POINTER_OFFSET: VEX register offset for the stack pointer register. */ #if defined(VGA_x86) #define STACK_POINTER_OFFSET OFFSET_x86_ESP #elif defined(VGA_amd64) #define STACK_POINTER_OFFSET OFFSET_amd64_RSP #elif defined(VGA_ppc32) #define STACK_POINTER_OFFSET OFFSET_ppc32_GPR1 #elif defined(VGA_ppc64) #define STACK_POINTER_OFFSET OFFSET_ppc64_GPR1 #elif defined(VGA_arm) #define STACK_POINTER_OFFSET OFFSET_arm_R13 #elif defined(VGA_s390x) #define STACK_POINTER_OFFSET OFFSET_s390x_r15 #else #error Unknown architecture. #endif /* Local variables. */ static Bool s_check_stack_accesses = False; static Bool s_first_race_only = False; /* Function definitions. */ Bool DRD_(get_check_stack_accesses)() { return s_check_stack_accesses; } void DRD_(set_check_stack_accesses)(const Bool c) { tl_assert(c == False || c == True); s_check_stack_accesses = c; } Bool DRD_(get_first_race_only)() { return s_first_race_only; } void DRD_(set_first_race_only)(const Bool fro) { tl_assert(fro == False || fro == True); s_first_race_only = fro; } void DRD_(trace_mem_access)(const Addr addr, const SizeT size, const BmAccessTypeT access_type, const HWord stored_value_hi, const HWord stored_value_lo) { if (DRD_(is_any_traced)(addr, addr + size)) { char* vc; vc = DRD_(vc_aprint)(DRD_(thread_get_vc)(DRD_(thread_get_running_tid)())); if (access_type == eStore && size <= sizeof(HWord)) { DRD_(trace_msg_w_bt)("store 0x%lx size %ld val %ld/0x%lx (thread %d /" " vc %s)", addr, size, stored_value_lo, stored_value_lo, DRD_(thread_get_running_tid)(), vc); } else if (access_type == eStore && size > sizeof(HWord)) { ULong sv; tl_assert(sizeof(HWord) == 4); sv = ((ULong)stored_value_hi << 32) | stored_value_lo; DRD_(trace_msg_w_bt)("store 0x%lx size %ld val %lld/0x%llx (thread %d" " / vc %s)", addr, size, sv, sv, DRD_(thread_get_running_tid)(), vc); } else { DRD_(trace_msg_w_bt)("%s 0x%lx size %ld (thread %d / vc %s)", access_type == eLoad ? "load " : access_type == eStore ? "store" : access_type == eStart ? "start" : access_type == eEnd ? "end " : "????", addr, size, DRD_(thread_get_running_tid)(), vc); } VG_(free)(vc); tl_assert(DRD_(DrdThreadIdToVgThreadId)(DRD_(thread_get_running_tid)()) == VG_(get_running_tid)()); } } static VG_REGPARM(2) void drd_trace_mem_load(const Addr addr, const SizeT size) { return DRD_(trace_mem_access)(addr, size, eLoad, 0, 0); } static VG_REGPARM(3) void drd_trace_mem_store(const Addr addr,const SizeT size, const HWord stored_value_hi, const HWord stored_value_lo) { return DRD_(trace_mem_access)(addr, size, eStore, stored_value_hi, stored_value_lo); } static void drd_report_race(const Addr addr, const SizeT size, const BmAccessTypeT access_type) { DataRaceErrInfo drei; drei.tid = DRD_(thread_get_running_tid)(); drei.addr = addr; drei.size = size; drei.access_type = access_type; VG_(maybe_record_error)(VG_(get_running_tid)(), DataRaceErr, VG_(get_IP)(VG_(get_running_tid)()), "Conflicting access", &drei); if (s_first_race_only) { DRD_(start_suppression)(addr, addr + size, "first race only"); } } VG_REGPARM(2) void DRD_(trace_load)(Addr addr, SizeT size) { #ifdef ENABLE_DRD_CONSISTENCY_CHECKS /* The assert below has been commented out because of performance reasons.*/ tl_assert(DRD_(thread_get_running_tid)() == DRD_(VgThreadIdToDrdThreadId)(VG_(get_running_tid()))); #endif if (DRD_(running_thread_is_recording_loads)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_load_triggers_conflict(addr, addr + size) && ! DRD_(is_suppressed)(addr, addr + size)) { drd_report_race(addr, size, eLoad); } } static VG_REGPARM(1) void drd_trace_load_1(Addr addr) { if (DRD_(running_thread_is_recording_loads)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_load_1_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 1)) { drd_report_race(addr, 1, eLoad); } } static VG_REGPARM(1) void drd_trace_load_2(Addr addr) { if (DRD_(running_thread_is_recording_loads)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_load_2_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 2)) { drd_report_race(addr, 2, eLoad); } } static VG_REGPARM(1) void drd_trace_load_4(Addr addr) { if (DRD_(running_thread_is_recording_loads)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_load_4_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 4)) { drd_report_race(addr, 4, eLoad); } } static VG_REGPARM(1) void drd_trace_load_8(Addr addr) { if (DRD_(running_thread_is_recording_loads)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_load_8_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 8)) { drd_report_race(addr, 8, eLoad); } } VG_REGPARM(2) void DRD_(trace_store)(Addr addr, SizeT size) { #ifdef ENABLE_DRD_CONSISTENCY_CHECKS /* The assert below has been commented out because of performance reasons.*/ tl_assert(DRD_(thread_get_running_tid)() == DRD_(VgThreadIdToDrdThreadId)(VG_(get_running_tid()))); #endif if (DRD_(running_thread_is_recording_stores)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_store_triggers_conflict(addr, addr + size) && ! DRD_(is_suppressed)(addr, addr + size)) { drd_report_race(addr, size, eStore); } } static VG_REGPARM(1) void drd_trace_store_1(Addr addr) { if (DRD_(running_thread_is_recording_stores)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_store_1_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 1)) { drd_report_race(addr, 1, eStore); } } static VG_REGPARM(1) void drd_trace_store_2(Addr addr) { if (DRD_(running_thread_is_recording_stores)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_store_2_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 2)) { drd_report_race(addr, 2, eStore); } } static VG_REGPARM(1) void drd_trace_store_4(Addr addr) { if (DRD_(running_thread_is_recording_stores)() && (s_check_stack_accesses || !DRD_(thread_address_on_stack)(addr)) && bm_access_store_4_triggers_conflict(addr) && !DRD_(is_suppressed)(addr, addr + 4)) { drd_report_race(addr, 4, eStore); } } static VG_REGPARM(1) void drd_trace_store_8(Addr addr) { if (DRD_(running_thread_is_recording_stores)() && (s_check_stack_accesses || ! DRD_(thread_address_on_stack)(addr)) && bm_access_store_8_triggers_conflict(addr) && ! DRD_(is_suppressed)(addr, addr + 8)) { drd_report_race(addr, 8, eStore); } } /** * Return true if and only if addr_expr matches the pattern (SP) or * <offset>(SP). */ static Bool is_stack_access(IRSB* const bb, IRExpr* const addr_expr) { Bool result = False; if (addr_expr->tag == Iex_RdTmp) { int i; for (i = 0; i < bb->stmts_size; i++) { if (bb->stmts[i] && bb->stmts[i]->tag == Ist_WrTmp && bb->stmts[i]->Ist.WrTmp.tmp == addr_expr->Iex.RdTmp.tmp) { IRExpr* e = bb->stmts[i]->Ist.WrTmp.data; if (e->tag == Iex_Get && e->Iex.Get.offset == STACK_POINTER_OFFSET) { result = True; } //ppIRExpr(e); //VG_(printf)(" (%s)\n", result ? "True" : "False"); break; } } } return result; } static const IROp u_widen_irop[5][9] = { [Ity_I1 - Ity_I1] = { [4] = Iop_1Uto32, [8] = Iop_1Uto64 }, [Ity_I8 - Ity_I1] = { [4] = Iop_8Uto32, [8] = Iop_8Uto64 }, [Ity_I16 - Ity_I1] = { [4] = Iop_16Uto32, [8] = Iop_16Uto64 }, [Ity_I32 - Ity_I1] = { [8] = Iop_32Uto64 }, }; /** * Instrument the client code to trace a memory load (--trace-addr). */ static IRExpr* instr_trace_mem_load(IRSB* const bb, IRExpr* addr_expr, const HWord size) { IRTemp tmp; tmp = newIRTemp(bb->tyenv, typeOfIRExpr(bb->tyenv, addr_expr)); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, addr_expr)); addr_expr = IRExpr_RdTmp(tmp); addStmtToIRSB(bb, IRStmt_Dirty( unsafeIRDirty_0_N(/*regparms*/2, "drd_trace_mem_load", VG_(fnptr_to_fnentry) (drd_trace_mem_load), mkIRExprVec_2(addr_expr, mkIRExpr_HWord(size))))); return addr_expr; } /** * Instrument the client code to trace a memory store (--trace-addr). */ static void instr_trace_mem_store(IRSB* const bb, IRExpr* const addr_expr, IRExpr* data_expr_hi, IRExpr* data_expr_lo) { IRType ty_data_expr; HWord size; tl_assert(sizeof(HWord) == 4 || sizeof(HWord) == 8); tl_assert(!data_expr_hi || typeOfIRExpr(bb->tyenv, data_expr_hi) == Ity_I32); ty_data_expr = typeOfIRExpr(bb->tyenv, data_expr_lo); size = sizeofIRType(ty_data_expr); #if 0 // Test code if (ty_data_expr == Ity_I32) { IRTemp tmp = newIRTemp(bb->tyenv, Ity_F32); data_expr_lo = IRExpr_Unop(Iop_ReinterpI32asF32, data_expr_lo); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, data_expr_lo)); data_expr_lo = IRExpr_RdTmp(tmp); ty_data_expr = Ity_F32; } else if (ty_data_expr == Ity_I64) { IRTemp tmp = newIRTemp(bb->tyenv, Ity_F64); data_expr_lo = IRExpr_Unop(Iop_ReinterpI64asF64, data_expr_lo); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, data_expr_lo)); data_expr_lo = IRExpr_RdTmp(tmp); ty_data_expr = Ity_F64; } #endif if (ty_data_expr == Ity_F32) { IRTemp tmp = newIRTemp(bb->tyenv, Ity_I32); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, IRExpr_Unop(Iop_ReinterpF32asI32, data_expr_lo))); data_expr_lo = IRExpr_RdTmp(tmp); ty_data_expr = Ity_I32; } else if (ty_data_expr == Ity_F64) { IRTemp tmp = newIRTemp(bb->tyenv, Ity_I64); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, IRExpr_Unop(Iop_ReinterpF64asI64, data_expr_lo))); data_expr_lo = IRExpr_RdTmp(tmp); ty_data_expr = Ity_I64; } if (size == sizeof(HWord) && (ty_data_expr == Ity_I32 || ty_data_expr == Ity_I64)) { /* No conversion necessary */ } else { IROp widen_op; if (Ity_I1 <= ty_data_expr && ty_data_expr < Ity_I1 + sizeof(u_widen_irop)/sizeof(u_widen_irop[0])) { widen_op = u_widen_irop[ty_data_expr - Ity_I1][sizeof(HWord)]; if (!widen_op) widen_op = Iop_INVALID; } else { widen_op = Iop_INVALID; } if (widen_op != Iop_INVALID) { IRTemp tmp; /* Widen the integer expression to a HWord */ tmp = newIRTemp(bb->tyenv, sizeof(HWord) == 4 ? Ity_I32 : Ity_I64); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, IRExpr_Unop(widen_op, data_expr_lo))); data_expr_lo = IRExpr_RdTmp(tmp); } else if (size > sizeof(HWord) && !data_expr_hi && ty_data_expr == Ity_I64) { IRTemp tmp; tl_assert(sizeof(HWord) == 4); tl_assert(size == 8); tmp = newIRTemp(bb->tyenv, Ity_I32); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, IRExpr_Unop(Iop_64HIto32, data_expr_lo))); data_expr_hi = IRExpr_RdTmp(tmp); tmp = newIRTemp(bb->tyenv, Ity_I32); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, IRExpr_Unop(Iop_64to32, data_expr_lo))); data_expr_lo = IRExpr_RdTmp(tmp); } else { data_expr_lo = mkIRExpr_HWord(0); } } addStmtToIRSB(bb, IRStmt_Dirty( unsafeIRDirty_0_N(/*regparms*/3, "drd_trace_mem_store", VG_(fnptr_to_fnentry)(drd_trace_mem_store), mkIRExprVec_4(addr_expr, mkIRExpr_HWord(size), data_expr_hi ? data_expr_hi : mkIRExpr_HWord(0), data_expr_lo)))); } static void instrument_load(IRSB* const bb, IRExpr* const addr_expr, const HWord size) { IRExpr* size_expr; IRExpr** argv; IRDirty* di; if (!s_check_stack_accesses && is_stack_access(bb, addr_expr)) return; switch (size) { case 1: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_load_1", VG_(fnptr_to_fnentry)(drd_trace_load_1), argv); break; case 2: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_load_2", VG_(fnptr_to_fnentry)(drd_trace_load_2), argv); break; case 4: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_load_4", VG_(fnptr_to_fnentry)(drd_trace_load_4), argv); break; case 8: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_load_8", VG_(fnptr_to_fnentry)(drd_trace_load_8), argv); break; default: size_expr = mkIRExpr_HWord(size); argv = mkIRExprVec_2(addr_expr, size_expr); di = unsafeIRDirty_0_N(/*regparms*/2, "drd_trace_load", VG_(fnptr_to_fnentry)(DRD_(trace_load)), argv); break; } addStmtToIRSB(bb, IRStmt_Dirty(di)); } static void instrument_store(IRSB* const bb, IRExpr* addr_expr, IRExpr* const data_expr) { IRExpr* size_expr; IRExpr** argv; IRDirty* di; HWord size; size = sizeofIRType(typeOfIRExpr(bb->tyenv, data_expr)); if (UNLIKELY(DRD_(any_address_is_traced)())) { IRTemp tmp = newIRTemp(bb->tyenv, typeOfIRExpr(bb->tyenv, addr_expr)); addStmtToIRSB(bb, IRStmt_WrTmp(tmp, addr_expr)); addr_expr = IRExpr_RdTmp(tmp); instr_trace_mem_store(bb, addr_expr, NULL, data_expr); } if (!s_check_stack_accesses && is_stack_access(bb, addr_expr)) return; switch (size) { case 1: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_store_1", VG_(fnptr_to_fnentry)(drd_trace_store_1), argv); break; case 2: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_store_2", VG_(fnptr_to_fnentry)(drd_trace_store_2), argv); break; case 4: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_store_4", VG_(fnptr_to_fnentry)(drd_trace_store_4), argv); break; case 8: argv = mkIRExprVec_1(addr_expr); di = unsafeIRDirty_0_N(/*regparms*/1, "drd_trace_store_8", VG_(fnptr_to_fnentry)(drd_trace_store_8), argv); break; default: size_expr = mkIRExpr_HWord(size); argv = mkIRExprVec_2(addr_expr, size_expr); di = unsafeIRDirty_0_N(/*regparms*/2, "drd_trace_store", VG_(fnptr_to_fnentry)(DRD_(trace_store)), argv); break; } addStmtToIRSB(bb, IRStmt_Dirty(di)); } IRSB* DRD_(instrument)(VgCallbackClosure* const closure, IRSB* const bb_in, VexGuestLayout* const layout, VexGuestExtents* const vge, IRType const gWordTy, IRType const hWordTy) { IRDirty* di; Int i; IRSB* bb; IRExpr** argv; Bool instrument = True; /* Set up BB */ bb = emptyIRSB(); bb->tyenv = deepCopyIRTypeEnv(bb_in->tyenv); bb->next = deepCopyIRExpr(bb_in->next); bb->jumpkind = bb_in->jumpkind; for (i = 0; i < bb_in->stmts_used; i++) { IRStmt* const st = bb_in->stmts[i]; tl_assert(st); tl_assert(isFlatIRStmt(st)); switch (st->tag) { /* Note: the code for not instrumenting the code in .plt */ /* sections is only necessary on CentOS 3.0 x86 (kernel 2.4.21 */ /* + glibc 2.3.2 + NPTL 0.60 + binutils 2.14.90.0.4). */ /* This is because on this platform dynamic library symbols are */ /* relocated in another way than by later binutils versions. The */ /* linker e.g. does not generate .got.plt sections on CentOS 3.0. */ case Ist_IMark: instrument = VG_(DebugInfo_sect_kind)(NULL, 0, st->Ist.IMark.addr) != Vg_SectPLT; addStmtToIRSB(bb, st); break; case Ist_MBE: switch (st->Ist.MBE.event) { case Imbe_Fence: break; /* not interesting */ default: tl_assert(0); } addStmtToIRSB(bb, st); break; case Ist_Store: if (instrument) instrument_store(bb, st->Ist.Store.addr, st->Ist.Store.data); addStmtToIRSB(bb, st); break; case Ist_WrTmp: if (instrument) { const IRExpr* const data = st->Ist.WrTmp.data; IRExpr* addr_expr = data->Iex.Load.addr; if (data->tag == Iex_Load) { if (UNLIKELY(DRD_(any_address_is_traced)())) { addr_expr = instr_trace_mem_load(bb, addr_expr, sizeofIRType(data->Iex.Load.ty)); } instrument_load(bb, data->Iex.Load.addr, sizeofIRType(data->Iex.Load.ty)); } } addStmtToIRSB(bb, st); break; case Ist_Dirty: if (instrument) { IRDirty* d = st->Ist.Dirty.details; IREffect const mFx = d->mFx; switch (mFx) { case Ifx_None: break; case Ifx_Read: case Ifx_Write: case Ifx_Modify: tl_assert(d->mAddr); tl_assert(d->mSize > 0); argv = mkIRExprVec_2(d->mAddr, mkIRExpr_HWord(d->mSize)); if (mFx == Ifx_Read || mFx == Ifx_Modify) { di = unsafeIRDirty_0_N( /*regparms*/2, "drd_trace_load", VG_(fnptr_to_fnentry)(DRD_(trace_load)), argv); addStmtToIRSB(bb, IRStmt_Dirty(di)); } if (mFx == Ifx_Write || mFx == Ifx_Modify) { di = unsafeIRDirty_0_N( /*regparms*/2, "drd_trace_store", VG_(fnptr_to_fnentry)(DRD_(trace_store)), argv); addStmtToIRSB(bb, IRStmt_Dirty(di)); } break; default: tl_assert(0); } } addStmtToIRSB(bb, st); break; case Ist_CAS: if (instrument) { /* * Treat compare-and-swap as a read. By handling atomic * instructions as read instructions no data races are reported * between conflicting atomic operations nor between atomic * operations and non-atomic reads. Conflicts between atomic * operations and non-atomic write operations are still reported * however. */ Int dataSize; IRCAS* cas = st->Ist.CAS.details; tl_assert(cas->addr != NULL); tl_assert(cas->dataLo != NULL); dataSize = sizeofIRType(typeOfIRExpr(bb->tyenv, cas->dataLo)); if (cas->dataHi != NULL) dataSize *= 2; /* since it's a doubleword-CAS */ if (UNLIKELY(DRD_(any_address_is_traced)())) instr_trace_mem_store(bb, cas->addr, cas->dataHi, cas->dataLo); instrument_load(bb, cas->addr, dataSize); } addStmtToIRSB(bb, st); break; case Ist_LLSC: { /* * Ignore store-conditionals (except for tracing), and handle * load-linked's exactly like normal loads. */ IRType dataTy; if (st->Ist.LLSC.storedata == NULL) { /* LL */ dataTy = typeOfIRTemp(bb_in->tyenv, st->Ist.LLSC.result); if (instrument) { IRExpr* addr_expr = st->Ist.LLSC.addr; if (UNLIKELY(DRD_(any_address_is_traced)())) addr_expr = instr_trace_mem_load(bb, addr_expr, sizeofIRType(dataTy)); instrument_load(bb, addr_expr, sizeofIRType(dataTy)); } } else { /* SC */ instr_trace_mem_store(bb, st->Ist.LLSC.addr, NULL, st->Ist.LLSC.storedata); } addStmtToIRSB(bb, st); break; } case Ist_NoOp: case Ist_AbiHint: case Ist_Put: case Ist_PutI: case Ist_Exit: /* None of these can contain any memory references. */ addStmtToIRSB(bb, st); break; default: ppIRStmt(st); tl_assert(0); } } return bb; }
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/valgrind_12474-12473.c
manybugs_data_73
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <zend_language_parser.h> #include "zend.h" #include "zend_compile.h" #include "zend_constants.h" #include "zend_llist.h" #include "zend_API.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "zend_multibyte.h" #include "zend_language_scanner.h" #define CONSTANT_EX(op_array, op) \ (op_array)->literals[op].constant #define CONSTANT(op) \ CONSTANT_EX(CG(active_op_array), op) #define SET_NODE(target, src) do { \ target ## _type = (src)->op_type; \ if ((src)->op_type == IS_CONST) { \ target.constant = zend_add_literal(CG(active_op_array), &(src)->u.constant TSRMLS_CC); \ } else { \ target = (src)->u.op; \ } \ } while (0) #define GET_NODE(target, src) do { \ (target)->op_type = src ## _type; \ if ((target)->op_type == IS_CONST) { \ (target)->u.constant = CONSTANT(src.constant); \ } else { \ (target)->u.op = src; \ (target)->EA = 0; \ } \ } while (0) #define COPY_NODE(target, src) do { \ target ## _type = src ## _type; \ target = src; \ } while (0) #define CALCULATE_LITERAL_HASH(num) do { \ if (IS_INTERNED(Z_STRVAL(CONSTANT(num)))) { \ Z_HASH_P(&CONSTANT(num)) = INTERNED_HASH(Z_STRVAL(CONSTANT(num))); \ } else { \ Z_HASH_P(&CONSTANT(num)) = zend_hash_func(Z_STRVAL(CONSTANT(num)), Z_STRLEN(CONSTANT(num))+1); \ } \ } while (0) #define GET_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot++; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ } \ } while (0) #define POLYMORPHIC_CACHE_SLOT_SIZE 2 #define GET_POLYMORPHIC_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot; \ CG(active_op_array)->last_cache_slot += POLYMORPHIC_CACHE_SLOT_SIZE; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 2] = NULL; \ } \ } while (0) #define FREE_POLYMORPHIC_CACHE_SLOT(literal) do { \ if (CG(active_op_array)->literals[literal].cache_slot == \ CG(active_op_array)->last_cache_slot - POLYMORPHIC_CACHE_SLOT_SIZE) { \ CG(active_op_array)->literals[literal].cache_slot = -1; \ CG(active_op_array)->last_cache_slot -= POLYMORPHIC_CACHE_SLOT_SIZE; \ } \ } while (0) ZEND_API zend_op_array *(*zend_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); ZEND_API zend_op_array *(*zend_compile_string)(zval *source_string, char *filename TSRMLS_DC); #ifndef ZTS ZEND_API zend_compiler_globals compiler_globals; ZEND_API zend_executor_globals executor_globals; #endif static void zend_duplicate_property_info(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = estrndup(property_info->name, property_info->name_length); } if (property_info->doc_comment) { property_info->doc_comment = estrndup(property_info->doc_comment, property_info->doc_comment_len); } } /* }}} */ static void zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = zend_strndup(property_info->name, property_info->name_length); } } /* }}} */ static void zend_destroy_property_info(zend_property_info *property_info) /* {{{ */ { str_efree(property_info->name); if (property_info->doc_comment) { efree((char*)property_info->doc_comment); } } /* }}} */ static void zend_destroy_property_info_internal(zend_property_info *property_info) /* {{{ */ { str_free((char*)property_info->name); } /* }}} */ static void build_runtime_defined_function_key(zval *result, const char *name, int name_length TSRMLS_DC) /* {{{ */ { char char_pos_buf[32]; uint char_pos_len; const char *filename; char_pos_len = zend_sprintf(char_pos_buf, "%p", LANG_SCNG(yy_text)); if (CG(active_op_array)->filename) { filename = CG(active_op_array)->filename; } else { filename = "-"; } /* NULL, name length, filename length, last accepting char position length */ result->value.str.len = 1+name_length+strlen(filename)+char_pos_len; /* must be binary safe */ result->value.str.val = (char *) safe_emalloc(result->value.str.len, 1, 1); result->value.str.val[0] = '\0'; sprintf(result->value.str.val+1, "%s%s%s", name, filename, char_pos_buf); result->type = IS_STRING; Z_SET_REFCOUNT_P(result, 1); } /* }}} */ static void init_compiler_declarables(TSRMLS_D) /* {{{ */ { Z_TYPE(CG(declarables).ticks) = IS_LONG; Z_LVAL(CG(declarables).ticks) = 0; } /* }}} */ void zend_init_compiler_context(TSRMLS_D) /* {{{ */ { CG(context).opcodes_size = (CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) ? INITIAL_INTERACTIVE_OP_ARRAY_SIZE : INITIAL_OP_ARRAY_SIZE; CG(context).vars_size = 0; CG(context).literals_size = 0; CG(context).current_brk_cont = -1; CG(context).backpatch_count = 0; CG(context).labels = NULL; } /* }}} */ void zend_init_compiler_data_structures(TSRMLS_D) /* {{{ */ { zend_stack_init(&CG(bp_stack)); zend_stack_init(&CG(function_call_stack)); zend_stack_init(&CG(switch_cond_stack)); zend_stack_init(&CG(foreach_copy_stack)); zend_stack_init(&CG(object_stack)); zend_stack_init(&CG(declare_stack)); CG(active_class_entry) = NULL; zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_stack_init(&CG(list_stack)); CG(in_compilation) = 0; CG(start_lineno) = 0; CG(current_namespace) = NULL; CG(in_namespace) = 0; CG(has_bracketed_namespaces) = 0; CG(current_import) = NULL; init_compiler_declarables(TSRMLS_C); zend_stack_init(&CG(context_stack)); CG(encoding_declared) = 0; } /* }}} */ ZEND_API void file_handle_dtor(zend_file_handle *fh) /* {{{ */ { TSRMLS_FETCH(); zend_file_handle_dtor(fh TSRMLS_CC); } /* }}} */ void init_compiler(TSRMLS_D) /* {{{ */ { CG(active_op_array) = NULL; zend_init_compiler_data_structures(TSRMLS_C); zend_init_rsrc_list(TSRMLS_C); zend_hash_init(&CG(filenames_table), 5, NULL, (dtor_func_t) free_estring, 0); zend_llist_init(&CG(open_files), sizeof(zend_file_handle), (void (*)(void *)) file_handle_dtor, 0); CG(unclean_shutdown) = 0; } /* }}} */ void shutdown_compiler(TSRMLS_D) /* {{{ */ { zend_stack_destroy(&CG(bp_stack)); zend_stack_destroy(&CG(function_call_stack)); zend_stack_destroy(&CG(switch_cond_stack)); zend_stack_destroy(&CG(foreach_copy_stack)); zend_stack_destroy(&CG(object_stack)); zend_stack_destroy(&CG(declare_stack)); zend_stack_destroy(&CG(list_stack)); zend_hash_destroy(&CG(filenames_table)); zend_llist_destroy(&CG(open_files)); zend_stack_destroy(&CG(context_stack)); } /* }}} */ ZEND_API char *zend_set_compiled_filename(const char *new_compiled_filename TSRMLS_DC) /* {{{ */ { char **pp, *p; int length = strlen(new_compiled_filename); if (zend_hash_find(&CG(filenames_table), new_compiled_filename, length+1, (void **) &pp) == SUCCESS) { CG(compiled_filename) = *pp; return *pp; } p = estrndup(new_compiled_filename, length); zend_hash_update(&CG(filenames_table), new_compiled_filename, length+1, &p, sizeof(char *), (void **) &pp); CG(compiled_filename) = p; return p; } /* }}} */ ZEND_API void zend_restore_compiled_filename(char *original_compiled_filename TSRMLS_DC) /* {{{ */ { CG(compiled_filename) = original_compiled_filename; } /* }}} */ ZEND_API char *zend_get_compiled_filename(TSRMLS_D) /* {{{ */ { return CG(compiled_filename); } /* }}} */ ZEND_API int zend_get_compiled_lineno(TSRMLS_D) /* {{{ */ { return CG(zend_lineno); } /* }}} */ ZEND_API zend_bool zend_is_compiling(TSRMLS_D) /* {{{ */ { return CG(in_compilation); } /* }}} */ static zend_uint get_temporary_variable(zend_op_array *op_array) /* {{{ */ { return (op_array->T)++ * ZEND_MM_ALIGNED_SIZE(sizeof(temp_variable)); } /* }}} */ static int lookup_cv(zend_op_array *op_array, char* name, int name_len, ulong hash TSRMLS_DC) /* {{{ */ { int i = 0; ulong hash_value = hash ? hash : zend_inline_hash_func(name, name_len+1); while (i < op_array->last_var) { if (op_array->vars[i].name == name || (op_array->vars[i].hash_value == hash_value && op_array->vars[i].name_len == name_len && memcmp(op_array->vars[i].name, name, name_len) == 0)) { str_efree(name); return i; } i++; } i = op_array->last_var; op_array->last_var++; if (op_array->last_var > CG(context).vars_size) { CG(context).vars_size += 16; /* FIXME */ op_array->vars = erealloc(op_array->vars, CG(context).vars_size * sizeof(zend_compiled_variable)); } op_array->vars[i].name = zend_new_interned_string(name, name_len + 1, 1 TSRMLS_CC); op_array->vars[i].name_len = name_len; op_array->vars[i].hash_value = hash_value; return i; } /* }}} */ void zend_del_literal(zend_op_array *op_array, int n) /* {{{ */ { zval_dtor(&CONSTANT_EX(op_array, n)); if (n + 1 == op_array->last_literal) { op_array->last_literal--; } else { Z_TYPE(CONSTANT_EX(op_array, n)) = IS_NULL; } } /* }}} */ /* Common part of zend_add_literal and zend_append_individual_literal */ static inline void zend_insert_literal(zend_op_array *op_array, const zval *zv, int literal_position TSRMLS_DC) /* {{{ */ { if (Z_TYPE_P(zv) == IS_STRING || Z_TYPE_P(zv) == IS_CONSTANT) { zval *z = (zval*)zv; Z_STRVAL_P(z) = (char*)zend_new_interned_string(Z_STRVAL_P(zv), Z_STRLEN_P(zv) + 1, 1 TSRMLS_CC); } CONSTANT_EX(op_array, literal_position) = *zv; Z_SET_REFCOUNT(CONSTANT_EX(op_array, literal_position), 2); Z_SET_ISREF(CONSTANT_EX(op_array, literal_position)); op_array->literals[literal_position].hash_value = 0; op_array->literals[literal_position].cache_slot = -1; } /* }}} */ /* Is used while compiling a function, using the context to keep track of an approximate size to avoid to relocate to often. Literals are truncated to actual size in the second compiler pass (pass_two()). */ int zend_add_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; if (i >= CG(context).literals_size) { while (i >= CG(context).literals_size) { CG(context).literals_size += 16; /* FIXME */ } op_array->literals = (zend_literal*)erealloc(op_array->literals, CG(context).literals_size * sizeof(zend_literal)); } zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ /* Is used after normal compilation to append an additional literal. Allocation is done precisely here. */ int zend_append_individual_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; op_array->literals = (zend_literal*)erealloc(op_array->literals, (i + 1) * sizeof(zend_literal)); zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ int zend_add_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_ns_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; const char *ns_separator; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); ns_separator = (const char*)zend_memrchr(Z_STRVAL_P(zv), '\\', Z_STRLEN_P(zv)) + 1; lc_len = Z_STRLEN_P(zv) - (ns_separator - Z_STRVAL_P(zv)); lc_name = zend_str_tolower_dup(ns_separator, lc_len); ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_class_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } if (Z_STRVAL_P(zv)[0] == '\\') { lc_len = Z_STRLEN_P(zv) - 1; lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv) + 1, lc_len); } else { lc_len = Z_STRLEN_P(zv); lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), lc_len); } ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); GET_CACHE_SLOT(ret); return ret; } /* }}} */ int zend_add_const_name_literal(zend_op_array *op_array, const zval *zv, int unqualified TSRMLS_DC) /* {{{ */ { int ret, tmp_literal; char *name, *tmp_name; const char *ns_separator; int name_len, ns_len; zval c; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } /* skip leading '\\' */ if (Z_STRVAL_P(zv)[0] == '\\') { name_len = Z_STRLEN_P(zv) - 1; name = Z_STRVAL_P(zv) + 1; } else { name_len = Z_STRLEN_P(zv); name = Z_STRVAL_P(zv); } ns_separator = zend_memrchr(name, '\\', name_len); if (ns_separator) { ns_len = ns_separator - name; } else { ns_len = 0; } if (ns_len) { /* lowercased namespace name & original constant name */ tmp_name = estrndup(name, name_len); zend_str_tolower(tmp_name, ns_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased namespace name & lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); } if (ns_len) { if (!unqualified) { return ret; } ns_len++; name += ns_len; name_len -= ns_len; } /* original constant name */ tmp_name = estrndup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); return ret; } /* }}} */ #define LITERAL_STRINGL(op, str, len, copy) do { \ zval _c; \ ZVAL_STRINGL(&_c, str, len, copy); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG(op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG_EX(op_array, op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(op_array, &_c TSRMLS_CC); \ } while (0) #define LITERAL_NULL(op) do { \ zval _c; \ INIT_ZVAL( _c); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) static inline zend_bool zend_is_function_or_method_call(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; return ((type & ZEND_PARSED_METHOD_CALL) || (type == ZEND_PARSED_FUNCTION_CALL)); } /* }}} */ void zend_do_binary_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_unary_op(zend_uchar op, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); GET_NODE(result, opline->result); SET_UNUSED(opline->op2); } /* }}} */ #define MAKE_NOP(opline) { opline->opcode = ZEND_NOP; memset(&opline->result,0,sizeof(opline->result)); memset(&opline->op1,0,sizeof(opline->op1)); memset(&opline->op2,0,sizeof(opline->op2)); opline->result_type=opline->op1_type=opline->op2_type=IS_UNUSED; } static void zend_do_op_data(zend_op *data_op, const znode *value TSRMLS_DC) /* {{{ */ { data_op->opcode = ZEND_OP_DATA; SET_NODE(data_op->op1, value); SET_UNUSED(data_op->op2); } /* }}} */ void zend_do_binary_assign_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; switch (last_op->opcode) { case ZEND_FETCH_OBJ_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, op2 TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; case ZEND_FETCH_DIM_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_DIM; zend_do_op_data(opline, op2 TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result,last_op->result); return; default: break; } } opline->opcode = op; SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void fetch_simple_variable_ex(znode *result, znode *varname, int bp, zend_uchar op TSRMLS_DC) /* {{{ */ { zend_op opline; zend_op *opline_ptr; zend_llist *fetch_list_ptr; if (varname->op_type == IS_CONST) { ulong hash = 0; if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } else if (IS_INTERNED(Z_STRVAL(varname->u.constant))) { hash = INTERNED_HASH(Z_STRVAL(varname->u.constant)); } if (!zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC) && !(varname->u.constant.value.str.len == (sizeof("this")-1) && !memcmp(varname->u.constant.value.str.val, "this", sizeof("this"))) && (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE)) { result->op_type = IS_CV; result->u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC); varname->u.constant.value.str.val = (char*)CG(active_op_array)->vars[result->u.op.var].name; result->EA = 0; return; } } if (bp) { opline_ptr = &opline; init_op(opline_ptr TSRMLS_CC); } else { opline_ptr = get_next_op(CG(active_op_array) TSRMLS_CC); } opline_ptr->opcode = op; opline_ptr->result_type = IS_VAR; opline_ptr->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline_ptr->op1, varname); GET_NODE(result, opline_ptr->result); SET_UNUSED(opline_ptr->op2); opline_ptr->extended_value = ZEND_FETCH_LOCAL; if (varname->op_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline_ptr->op1.constant); if (zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC)) { opline_ptr->extended_value = ZEND_FETCH_GLOBAL; } } if (bp) { zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); zend_llist_add_element(fetch_list_ptr, opline_ptr); } } /* }}} */ void fetch_simple_variable(znode *result, znode *varname, int bp TSRMLS_DC) /* {{{ */ { /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ fetch_simple_variable_ex(result, varname, bp, ZEND_FETCH_W TSRMLS_CC); } /* }}} */ void zend_do_fetch_static_member(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { znode class_node; zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline_ptr; zend_op opline; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); } zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (result->op_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[result->u.op.var].name), CG(active_op_array)->vars[result->u.op.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } GET_NODE(result,opline.result); opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; opline_ptr = &opline; zend_llist_add_element(fetch_list_ptr, &opline); } else { le = fetch_list_ptr->head; opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode != ZEND_FETCH_W && opline_ptr->op1_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[opline_ptr->op1.var].name), CG(active_op_array)->vars[opline_ptr->op1.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; COPY_NODE(opline_ptr->op1, opline.result); zend_llist_prepend_element(fetch_list_ptr, &opline); } else { if (opline_ptr->op1_type == IS_CONST) { GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op1.constant); } if (class_node.op_type == IS_CONST) { opline_ptr->op2_type = IS_CONST; opline_ptr->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline_ptr->op2, &class_node); } opline_ptr->extended_value |= ZEND_FETCH_STATIC_MEMBER; } } } /* }}} */ void fetch_array_begin(znode *result, znode *varname, znode *first_dim TSRMLS_DC) /* {{{ */ { fetch_simple_variable(result, varname, 1 TSRMLS_CC); fetch_array_dim(result, result, first_dim TSRMLS_CC); } /* }}} */ void fetch_array_dim(znode *result, const znode *parent, const znode *dim TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (zend_is_function_or_method_call(parent)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, parent); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_DIM_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, parent); SET_NODE(opline.op2, dim); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline.op2.constant)), Z_STRLEN(CONSTANT(opline.op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline.op2.constant)); ZVAL_LONG(&CONSTANT(opline.op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline.op2.constant); } } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void fetch_string_offset(znode *result, const znode *parent, const znode *offset TSRMLS_DC) /* {{{ */ { fetch_array_dim(result, parent, offset TSRMLS_CC); } /* }}} */ void zend_do_print(znode *result, const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->opcode = ZEND_PRINT; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_echo(const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ECHO; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_abstract_method(const znode *function_name, znode *modifiers, const znode *body TSRMLS_DC) /* {{{ */ { char *method_type; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { Z_LVAL(modifiers->u.constant) |= ZEND_ACC_ABSTRACT; method_type = "Interface"; } else { method_type = "Abstract"; } if (modifiers->u.constant.value.lval & ZEND_ACC_ABSTRACT) { if(modifiers->u.constant.value.lval & ZEND_ACC_PRIVATE) { zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot be declared private", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } if (Z_LVAL(body->u.constant) == ZEND_ACC_ABSTRACT) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_RAISE_ABSTRACT_ERROR; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } else { /* we had code in the function body */ zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot contain body", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } else { if (body->u.constant.value.lval == ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Non-abstract method %s::%s() must contain body", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } } /* }}} */ static zend_bool opline_is_fetch_this(const zend_op *opline TSRMLS_DC) /* {{{ */ { if ((opline->opcode == ZEND_FETCH_W) && (opline->op1_type == IS_CONST) && (Z_TYPE(CONSTANT(opline->op1.constant)) == IS_STRING) && (Z_HASH_P(&CONSTANT(opline->op1.constant)) == THIS_HASHVAL) && (Z_STRLEN(CONSTANT(opline->op1.constant)) == (sizeof("this")-1)) && !memcmp(Z_STRVAL(CONSTANT(opline->op1.constant)), "this", sizeof("this"))) { return 1; } else { return 0; } } /* }}} */ void zend_do_assign(znode *result, znode *variable, znode *value TSRMLS_DC) /* {{{ */ { int last_op_number; zend_op *opline; if (value->op_type == IS_CV) { zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (fetch_list_ptr && fetch_list_ptr->head) { opline = (zend_op *)fetch_list_ptr->head->data; if (opline->opcode == ZEND_FETCH_DIM_W && opline->op1_type == IS_CV && opline->op1.var == value->u.op.var) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_R; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->op1_type = IS_CONST; LITERAL_STRINGL(opline->op1, CG(active_op_array)->vars[value->u.op.var].name, CG(active_op_array)->vars[value->u.op.var].name_len, 1); CALCULATE_LITERAL_HASH(opline->op1.constant); SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_LOCAL; GET_NODE(value, opline->result); } } } zend_do_end_variable_parse(variable, BP_VAR_W, 0 TSRMLS_CC); last_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (variable->op_type == IS_CV) { if (variable->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (variable->op_type == IS_VAR) { int n = 0; while (last_op_number - n > 0) { zend_op *last_op; last_op = &CG(active_op_array)->opcodes[last_op_number-n-1]; if (last_op->result_type == IS_VAR && last_op->result.var == variable->u.op.var) { if (last_op->opcode == ZEND_FETCH_OBJ_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, value TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (last_op->opcode == ZEND_FETCH_DIM_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ /* TBFixed: this can realloc opcodes, leaving last_op pointing wrong */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_DIM; zend_do_op_data(opline, value TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (opline_is_fetch_this(last_op TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } else { break; } } n++; } } opline->opcode = ZEND_ASSIGN; SET_NODE(opline->op1, variable); SET_NODE(opline->op2, value); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_assign_ref(znode *result, const znode *lvar, const znode *rvar TSRMLS_DC) /* {{{ */ { zend_op *opline; if (lvar->op_type == IS_CV) { if (lvar->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (lvar->op_type == IS_VAR) { int last_op_number = get_next_op_number(CG(active_op_array)); if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline_is_fetch_this(opline TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ASSIGN_REF; if (zend_is_function_or_method_call(rvar)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } else if (rvar->EA & ZEND_PARSED_NEW) { opline->extended_value = ZEND_RETURNS_NEW; } else { opline->extended_value = 0; } if (result) { opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } else { opline->result_type = IS_UNUSED | EXT_TYPE_UNUSED; } SET_NODE(opline->op1, lvar); SET_NODE(opline->op2, rvar); } /* }}} */ static inline void do_begin_loop(TSRMLS_D) /* {{{ */ { zend_brk_cont_element *brk_cont_element; int parent; parent = CG(context).current_brk_cont; CG(context).current_brk_cont = CG(active_op_array)->last_brk_cont; brk_cont_element = get_next_brk_cont_element(CG(active_op_array)); brk_cont_element->start = get_next_op_number(CG(active_op_array)); brk_cont_element->parent = parent; } /* }}} */ static inline void do_end_loop(int cont_addr, int has_loop_var TSRMLS_DC) /* {{{ */ { if (!has_loop_var) { /* The start fileld is used to free temporary variables in case of exceptions. * We won't try to free something of we don't have loop variable. */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].start = -1; } CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = cont_addr; CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; } /* }}} */ void zend_do_while_cond(const znode *expr, znode *close_bracket_token TSRMLS_DC) /* {{{ */ { int while_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, expr); close_bracket_token->u.op.opline_num = while_cond_op_number; SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_while_end(const znode *while_token, const znode *close_bracket_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* add unconditional jump */ opline->opcode = ZEND_JMP; opline->op1.opline_num = while_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* update while's conditional jmp */ CG(active_op_array)->opcodes[close_bracket_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); do_end_loop(while_token->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_cond(const znode *expr, znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { int for_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZNZ; SET_NODE(opline->op1, expr); /* the conditional expression */ second_semicolon_token->u.op.opline_num = for_cond_op_number; SET_UNUSED(opline->op2); } /* }}} */ void zend_do_for_before_statement(const znode *cond_start, const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = cond_start->u.op.opline_num; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_end(const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = second_semicolon_token->u.op.opline_num+1; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_end_loop(second_semicolon_token->u.op.opline_num+1, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_pre_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_PRE_INC)?ZEND_PRE_INC_OBJ:ZEND_PRE_DEC_OBJ; last_op->result_type = IS_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_post_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_POST_INC)?ZEND_POST_INC_OBJ:ZEND_POST_DEC_OBJ; last_op->result_type = IS_TMP_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_if_cond(const znode *cond, znode *closing_bracket_token TSRMLS_DC) /* {{{ */ { int if_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); closing_bracket_token->u.op.opline_num = if_cond_op_number; SET_UNUSED(opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_if_after_statement(const znode *closing_bracket_token, unsigned char initialize TSRMLS_DC) /* {{{ */ { int if_end_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; /* save for backpatching */ if (initialize) { zend_llist jmp_list; zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); } zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &if_end_op_number); CG(active_op_array)->opcodes[closing_bracket_token->u.op.opline_num].op2.opline_num = if_end_op_number+1; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_if_end(TSRMLS_D) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_llist *jmp_list_ptr; zend_llist_element *le; zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); for (le=jmp_list_ptr->head; le; le = le->next) { CG(active_op_array)->opcodes[*((int *) le->data)].op1.opline_num = next_op_number; } zend_llist_destroy(jmp_list_ptr); zend_stack_del_top(&CG(bp_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_check_writable_variable(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; if (type & ZEND_PARSED_METHOD_CALL) { zend_error(E_COMPILE_ERROR, "Can't use method return value in write context"); } if (type == ZEND_PARSED_FUNCTION_CALL) { zend_error(E_COMPILE_ERROR, "Can't use function return value in write context"); } } /* }}} */ void zend_do_begin_variable_parse(TSRMLS_D) /* {{{ */ { zend_llist fetch_list; zend_llist_init(&fetch_list, sizeof(zend_op), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &fetch_list, sizeof(zend_llist)); } /* }}} */ void zend_do_end_variable_parse(znode *variable, int type, int arg_offset TSRMLS_DC) /* {{{ */ { zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline = NULL; zend_op *opline_ptr; zend_uint this_var = -1; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); le = fetch_list_ptr->head; /* TODO: $foo->x->y->z = 1 should fetch "x" and "y" for R or RW, not just W */ if (le) { opline_ptr = (zend_op *)le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { /* convert to FETCH_?(this) into IS_CV */ if (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE) { this_var = opline_ptr->result.var; if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), Z_STRVAL(CONSTANT(opline_ptr->op1.constant)), Z_STRLEN(CONSTANT(opline_ptr->op1.constant)), Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC); Z_TYPE(CONSTANT(opline_ptr->op1.constant)) = IS_NULL; } else { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); } le = le->next; if (variable->op_type == IS_VAR && variable->u.op.var == this_var) { variable->op_type = IS_CV; variable->u.op.var = CG(active_op_array)->this_var; } } else if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } while (le) { opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode == ZEND_SEPARATE) { if (type != BP_VAR_R && type != BP_VAR_IS) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); } le = le->next; continue; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); if (opline->op1_type == IS_VAR && opline->op1.var == this_var) { opline->op1_type = IS_CV; opline->op1.var = CG(active_op_array)->this_var; } switch (type) { case BP_VAR_R: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode -= 3; break; case BP_VAR_W: break; case BP_VAR_RW: opline->opcode += 3; break; case BP_VAR_IS: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode += 6; /* 3+3 */ break; case BP_VAR_FUNC_ARG: opline->opcode += 9; /* 3+3+3 */ opline->extended_value |= arg_offset; break; case BP_VAR_UNSET: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for unsetting"); } opline->opcode += 12; /* 3+3+3+3 */ break; } le = le->next; } if (opline && type == BP_VAR_W && arg_offset) { opline->extended_value |= ZEND_FETCH_MAKE_REF; } } zend_llist_destroy(fetch_list_ptr); zend_stack_del_top(&CG(bp_stack)); } /* }}} */ void zend_do_add_string(znode *result, const znode *op1, znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline; if (Z_STRLEN(op2->u.constant) > 1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_STRING; } else if (Z_STRLEN(op2->u.constant) == 1) { int ch = *Z_STRVAL(op2->u.constant); /* Free memory and use ZEND_ADD_CHAR in case of 1 character strings */ efree(Z_STRVAL(op2->u.constant)); ZVAL_LONG(&op2->u.constant, ch); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_CHAR; } else { /* String can be empty after a variable at the end of a heredoc */ efree(Z_STRVAL(op2->u.constant)); return; } if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_add_variable(znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_VAR; if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_free(znode *op1 TSRMLS_DC) /* {{{ */ { if (op1->op_type==IS_TMP_VAR) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else if (op1->op_type==IS_VAR) { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; while (opline->opcode == ZEND_END_SILENCE || opline->opcode == ZEND_EXT_FCALL_END || opline->opcode == ZEND_OP_DATA) { opline--; } if (opline->result_type == IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_FETCH_R || opline->opcode == ZEND_FETCH_DIM_R || opline->opcode == ZEND_FETCH_OBJ_R || opline->opcode == ZEND_QM_ASSIGN_VAR) { /* It's very rare and useless case. It's better to use additional FREE opcode and simplify the FETCH handlers their selves */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else { opline->result_type |= EXT_TYPE_UNUSED; } } else { while (opline>CG(active_op_array)->opcodes) { if (opline->opcode == ZEND_FETCH_DIM_R && opline->op1_type == IS_VAR && opline->op1.var == op1->u.op.var) { /* This should the end of a list() construct * Mark its result as unused */ opline->extended_value = ZEND_FETCH_STANDARD; break; } else if (opline->result_type==IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_NEW) { opline->result_type |= EXT_TYPE_UNUSED; } break; } opline--; } } } else if (op1->op_type == IS_CONST) { zval_dtor(&op1->u.constant); } } /* }}} */ int zend_do_verify_access_types(const znode *current_access_type, const znode *new_modifier) /* {{{ */ { if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_PPP_MASK) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Multiple access type modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_ABSTRACT) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Multiple abstract modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_STATIC) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Multiple static modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_FINAL) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Multiple final modifiers are not allowed"); } if (((Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)) & (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) == (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Cannot use the final modifier on an abstract class member"); } return (Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)); } /* }}} */ void zend_do_begin_function_declaration(znode *function_token, znode *function_name, int is_method, int return_reference, znode *fn_flags_znode TSRMLS_DC) /* {{{ */ { zend_op_array op_array; char *name = function_name->u.constant.value.str.val; int name_len = function_name->u.constant.value.str.len; int function_begin_line = function_token->u.op.opline_num; zend_uint fn_flags; const char *lcname; zend_bool orig_interactive; ALLOCA_FLAG(use_heap) if (is_method) { if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((Z_LVAL(fn_flags_znode->u.constant) & ~(ZEND_ACC_STATIC|ZEND_ACC_PUBLIC))) { zend_error(E_COMPILE_ERROR, "Access type for interface method %s::%s() must be omitted", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } Z_LVAL(fn_flags_znode->u.constant) |= ZEND_ACC_ABSTRACT; /* propagates to the rest of the parser */ } fn_flags = Z_LVAL(fn_flags_znode->u.constant); /* must be done *after* the above check */ } else { fn_flags = 0; } if ((fn_flags & ZEND_ACC_STATIC) && (fn_flags & ZEND_ACC_ABSTRACT) && !(CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_STRICT, "Static function %s%s%s() should not be abstract", is_method ? CG(active_class_entry)->name : "", is_method ? "::" : "", Z_STRVAL(function_name->u.constant)); } function_token->u.op_array = CG(active_op_array); orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(&op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; op_array.function_name = name; if (return_reference) { op_array.fn_flags |= ZEND_ACC_RETURN_REFERENCE; } op_array.fn_flags |= fn_flags; op_array.scope = is_method?CG(active_class_entry):NULL; op_array.prototype = NULL; op_array.line_start = zend_get_compiled_lineno(TSRMLS_C); if (is_method) { int result; lcname = zend_new_interned_string(zend_str_tolower_dup(name, name_len), name_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lcname)) { result = zend_hash_quick_add(&CG(active_class_entry)->function_table, lcname, name_len+1, INTERNED_HASH(lcname), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } else { result = zend_hash_add(&CG(active_class_entry)->function_table, lcname, name_len+1, &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } if (result == FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::%s()", CG(active_class_entry)->name, name); } zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); if (fn_flags & ZEND_ACC_ABSTRACT) { CG(active_class_entry)->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (!(fn_flags & ZEND_ACC_PPP_MASK)) { fn_flags |= ZEND_ACC_PUBLIC; } if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } } } else { char *class_lcname; class_lcname = do_alloca(CG(active_class_entry)->name_length + 1, use_heap); zend_str_tolower_copy(class_lcname, CG(active_class_entry)->name, CG(active_class_entry)->name_length); /* Improve after RC: cache the lowercase class name */ if ((CG(active_class_entry)->name_length == name_len) && ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT) && (!memcmp(class_lcname, lcname, name_len))) { if (!CG(active_class_entry)->constructor) { CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } } else if ((name_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)))) { if (CG(active_class_entry)->constructor) { zend_error(E_STRICT, "Redefining already defined constructor for class %s", CG(active_class_entry)->name); } CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1))) { CG(active_class_entry)->destructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1))) { CG(active_class_entry)->clone = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } CG(active_class_entry)->__call = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } CG(active_class_entry)->__callstatic = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } CG(active_class_entry)->__get = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } CG(active_class_entry)->__set = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } CG(active_class_entry)->__unset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } CG(active_class_entry)->__isset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } CG(active_class_entry)->__tostring = (zend_function *) CG(active_op_array); } else if (!(fn_flags & ZEND_ACC_STATIC)) { CG(active_op_array)->fn_flags |= ZEND_ACC_ALLOW_STATIC; } free_alloca(class_lcname, use_heap); } str_efree(lcname); } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zval key; if (CG(current_namespace)) { /* Prefix function name with current namespcae name */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, function_name TSRMLS_CC); op_array.function_name = Z_STRVAL(tmp.u.constant); name_len = Z_STRLEN(tmp.u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), name_len); } else { lcname = zend_str_tolower_dup(name, name_len); } opline->opcode = ZEND_DECLARE_FUNCTION; opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, name_len TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; LITERAL_STRINGL(opline->op2, lcname, name_len, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); opline->extended_value = ZEND_DECLARE_FUNCTION; zend_hash_quick_update(CG(function_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); } if (CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_NOP; opline->lineno = function_begin_line; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } { /* Push a seperator to the switch and foreach stacks */ zend_switch_entry switch_entry; switch_entry.cond.op_type = IS_UNUSED; switch_entry.default_case = 0; switch_entry.control_var = 0; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); { /* Foreach stack separator */ zend_op dummy_opline; dummy_opline.result_type = IS_UNUSED; dummy_opline.op1_type = IS_UNUSED; zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); } } if (CG(doc_comment)) { CG(active_op_array)->doc_comment = CG(doc_comment); CG(active_op_array)->doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_begin_lambda_function_declaration(znode *result, znode *function_token, int return_reference, int is_static TSRMLS_DC) /* {{{ */ { znode function_name; zend_op_array *current_op_array = CG(active_op_array); int current_op_number = get_next_op_number(CG(active_op_array)); zend_op *current_op; function_name.op_type = IS_CONST; ZVAL_STRINGL(&function_name.u.constant, "{closure}", sizeof("{closure}")-1, 1); zend_do_begin_function_declaration(function_token, &function_name, 0, return_reference, NULL TSRMLS_CC); result->op_type = IS_TMP_VAR; result->u.op.var = get_temporary_variable(current_op_array); current_op = &current_op_array->opcodes[current_op_number]; current_op->opcode = ZEND_DECLARE_LAMBDA_FUNCTION; zend_del_literal(current_op_array, current_op->op2.constant); SET_UNUSED(current_op->op2); SET_NODE(current_op->result, result); if (is_static) { CG(active_op_array)->fn_flags |= ZEND_ACC_STATIC; } CG(active_op_array)->fn_flags |= ZEND_ACC_CLOSURE; } /* }}} */ void zend_do_handle_exception(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_HANDLE_EXCEPTION; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_function_declaration(const znode *function_token TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; zend_do_extended_info(TSRMLS_C); zend_do_return(NULL, 0 TSRMLS_CC); pass_two(CG(active_op_array) TSRMLS_CC); zend_release_labels(TSRMLS_C); if (CG(active_class_entry)) { zend_check_magic_method_implementation(CG(active_class_entry), (zend_function*)CG(active_op_array), E_COMPILE_ERROR TSRMLS_CC); } else { /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(CG(active_op_array)->function_name); zend_str_tolower_copy(lcname, CG(active_op_array)->function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME)) && CG(active_op_array)->num_args != 1) { zend_error(E_COMPILE_ERROR, "%s() must take exactly 1 argument", ZEND_AUTOLOAD_FUNC_NAME); } } CG(active_op_array)->line_end = zend_get_compiled_lineno(TSRMLS_C); CG(active_op_array) = function_token->u.op_array; /* Pop the switch and foreach seperators */ zend_stack_del_top(&CG(switch_cond_stack)); zend_stack_del_top(&CG(foreach_copy_stack)); } /* }}} */ void zend_do_receive_arg(zend_uchar op, znode *varname, const znode *offset, const znode *initialization, znode *class_type, zend_uchar pass_by_reference TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_arg_info *cur_arg_info; znode var; if (class_type->op_type == IS_CONST && Z_TYPE(class_type->u.constant) == IS_STRING && Z_STRLEN(class_type->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_type->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } if (zend_is_auto_global_quick(Z_STRVAL(varname->u.constant), Z_STRLEN(varname->u.constant), 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign auto-global variable %s", Z_STRVAL(varname->u.constant)); } else { var.op_type = IS_CV; var.u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(varname->u.constant) = (char*)CG(active_op_array)->vars[var.u.op.var].name; var.EA = 0; if (CG(active_op_array)->vars[var.u.op.var].hash_value == THIS_HASHVAL && Z_STRLEN(varname->u.constant) == sizeof("this")-1 && !memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this")-1)) { if (CG(active_op_array)->scope && (CG(active_op_array)->fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } CG(active_op_array)->this_var = var.u.op.var; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->num_args++; opline->opcode = op; SET_NODE(opline->result, &var); SET_NODE(opline->op1, offset); if (op == ZEND_RECV_INIT) { SET_NODE(opline->op2, initialization); } else { CG(active_op_array)->required_num_args = CG(active_op_array)->num_args; SET_UNUSED(opline->op2); } CG(active_op_array)->arg_info = erealloc(CG(active_op_array)->arg_info, sizeof(zend_arg_info)*(CG(active_op_array)->num_args)); cur_arg_info = &CG(active_op_array)->arg_info[CG(active_op_array)->num_args-1]; cur_arg_info->name = zend_new_interned_string(estrndup(varname->u.constant.value.str.val, varname->u.constant.value.str.len), varname->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->name_len = varname->u.constant.value.str.len; cur_arg_info->type_hint = 0; cur_arg_info->allow_null = 1; cur_arg_info->pass_by_reference = pass_by_reference; cur_arg_info->class_name = NULL; cur_arg_info->class_name_len = 0; if (class_type->op_type != IS_UNUSED) { cur_arg_info->allow_null = 0; if (class_type->u.constant.type != IS_NULL) { if (class_type->u.constant.type == IS_ARRAY) { cur_arg_info->type_hint = IS_ARRAY; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else if (Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Default value for parameters with array type hint can only be an array or NULL"); } } } else if (class_type->u.constant.type == IS_CALLABLE) { cur_arg_info->type_hint = IS_CALLABLE; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with callable type hint can only be NULL"); } } } else { cur_arg_info->type_hint = IS_OBJECT; if (ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_type->u.constant), Z_STRLEN(class_type->u.constant))) { zend_resolve_class_name(class_type, opline->extended_value, 1 TSRMLS_CC); } Z_STRVAL(class_type->u.constant) = (char*)zend_new_interned_string(class_type->u.constant.value.str.val, class_type->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->class_name = class_type->u.constant.value.str.val; cur_arg_info->class_name_len = class_type->u.constant.value.str.len; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with a class type hint can only be NULL"); } } } } } } /* }}} */ int zend_do_begin_function_call(znode *function_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { zend_function *function; char *lcname; char *is_compound = memchr(Z_STRVAL(function_name->u.constant), '\\', Z_STRLEN(function_name->u.constant)); zend_resolve_non_class_name(function_name, check_namespace TSRMLS_CC); if (check_namespace && CG(current_namespace) && !is_compound) { /* We assume we call function from the current namespace if it is not prefixed. */ /* In run-time PHP will check for function with full name and internal function with short name */ zend_do_begin_dynamic_function_call(function_name, 1 TSRMLS_CC); return 1; } lcname = zend_str_tolower_dup(function_name->u.constant.value.str.val, function_name->u.constant.value.str.len); if ((zend_hash_find(CG(function_table), lcname, function_name->u.constant.value.str.len+1, (void **) &function)==FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_FUNCTIONS) && (function->type == ZEND_INTERNAL_FUNCTION))) { zend_do_begin_dynamic_function_call(function_name, 0 TSRMLS_CC); efree(lcname); return 1; /* Dynamic */ } efree(function_name->u.constant.value.str.val); function_name->u.constant.value.str.val = lcname; zend_stack_push(&CG(function_call_stack), (void *) &function, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 0; } /* }}} */ void zend_do_begin_method_call(znode *left_bracket TSRMLS_DC) /* {{{ */ { zend_op *last_op; int last_op_number; unsigned char *ptr = NULL; zend_do_end_variable_parse(left_bracket, BP_VAR_R, 0 TSRMLS_CC); zend_do_begin_variable_parse(TSRMLS_C); last_op_number = get_next_op_number(CG(active_op_array))-1; last_op = &CG(active_op_array)->opcodes[last_op_number]; if ((last_op->op2_type == IS_CONST) && (Z_TYPE(CONSTANT(last_op->op2.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(last_op->op2.constant)) == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !zend_binary_strcasecmp(Z_STRVAL(CONSTANT(last_op->op2.constant)), Z_STRLEN(CONSTANT(last_op->op2.constant)), ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1)) { zend_error(E_COMPILE_ERROR, "Cannot call __clone() method on objects - use 'clone $obj' instead"); } if (last_op->opcode == ZEND_FETCH_OBJ_R) { if (last_op->op2_type == IS_CONST) { zval name; name = CONSTANT(last_op->op2.constant); if (!IS_INTERNED(Z_STRVAL(name))) { Z_STRVAL(name) = estrndup(Z_STRVAL(name), Z_STRLEN(name)); } FREE_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); last_op->op2.constant = zend_add_func_name_literal(CG(active_op_array), &name TSRMLS_CC); GET_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); } last_op->opcode = ZEND_INIT_METHOD_CALL; SET_UNUSED(last_op->result); Z_LVAL(left_bracket->u.constant) = ZEND_INIT_FCALL_BY_NAME; } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (left_bracket->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &left_bracket->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, left_bracket); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_do_clone(znode *result, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CLONE; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_begin_dynamic_function_call(znode *function_name, int ns_call TSRMLS_DC) /* {{{ */ { unsigned char *ptr = NULL; zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (ns_call) { /* In run-time PHP will check for function with full name and internal function with short name */ opline->opcode = ZEND_INIT_NS_FCALL_BY_NAME; SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_ns_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (function_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, function_name); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_resolve_non_class_name(znode *element_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; int len; zval **ns; char *lcname, *compound = memchr(Z_STRVAL(element_name->u.constant), '\\', Z_STRLEN(element_name->u.constant)); if (Z_STRVAL(element_name->u.constant)[0] == '\\') { /* name starts with \ so it is known and unambiguos, nothing to do here but shorten it */ memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+1, Z_STRLEN(element_name->u.constant)); --Z_STRLEN(element_name->u.constant); return; } if(!check_namespace) { return; } if (compound && CG(current_import)) { len = compound - Z_STRVAL(element_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(element_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(element_name->u.constant) -= len; memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+len, Z_STRLEN(element_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, element_name TSRMLS_CC); *element_name = tmp; efree(lcname); return; } efree(lcname); } if (CG(current_namespace)) { tmp = *element_name; Z_STRLEN(tmp.u.constant) = sizeof("\\")-1 + Z_STRLEN(element_name->u.constant) + Z_STRLEN_P(CG(current_namespace)); Z_STRVAL(tmp.u.constant) = (char *) emalloc(Z_STRLEN(tmp.u.constant)+1); memcpy(Z_STRVAL(tmp.u.constant), Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace))]), "\\", sizeof("\\")-1); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace)) + sizeof("\\")-1]), Z_STRVAL(element_name->u.constant), Z_STRLEN(element_name->u.constant)+1); STR_FREE(Z_STRVAL(element_name->u.constant)); *element_name = tmp; } } /* }}} */ void zend_resolve_class_name(znode *class_name, ulong fetch_type, int check_ns_name TSRMLS_DC) /* {{{ */ { char *compound; char *lcname; zval **ns; znode tmp; int len; compound = memchr(Z_STRVAL(class_name->u.constant), '\\', Z_STRLEN(class_name->u.constant)); if (compound) { /* This is a compound class name that contains namespace prefix */ if (Z_STRVAL(class_name->u.constant)[0] == '\\') { /* The STRING name has "\" prefix */ Z_STRLEN(class_name->u.constant) -= 1; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+1, Z_STRLEN(class_name->u.constant)+1); Z_STRVAL(class_name->u.constant) = erealloc( Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1); if (ZEND_FETCH_CLASS_DEFAULT != zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "'\\%s' is an invalid class name", Z_STRVAL(class_name->u.constant)); } } else { if (CG(current_import)) { len = compound - Z_STRVAL(class_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(class_name->u.constant) -= len; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+len, Z_STRLEN(class_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; efree(lcname); return; } efree(lcname); } /* Here name is not prefixed with \ and not imported */ if (CG(current_namespace)) { tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } } } else if (CG(current_import) || CG(current_namespace)) { /* this is a plain name (without \) */ lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns) == SUCCESS) { /* The given name is an import name. Substitute it. */ zval_dtor(&class_name->u.constant); class_name->u.constant = **ns; zval_copy_ctor(&class_name->u.constant); } else if (CG(current_namespace)) { /* plain name, no import - prepend current namespace to it */ tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } efree(lcname); } } /* }}} */ void zend_do_fetch_class(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { long fetch_class_op_number; zend_op *opline; if (class_name->op_type == IS_CONST && Z_TYPE(class_name->u.constant) == IS_STRING && Z_STRLEN(class_name->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_name->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } fetch_class_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CLASS; SET_UNUSED(opline->op1); opline->extended_value = ZEND_FETCH_CLASS_GLOBAL; CG(catch_begin) = fetch_class_op_number; if (class_name->op_type == IS_CONST) { int fetch_type; fetch_type = zend_get_class_fetch_type(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); switch (fetch_type) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: SET_UNUSED(opline->op2); opline->extended_value = fetch_type; zval_dtor(&class_name->u.constant); break; default: zend_resolve_class_name(class_name, opline->extended_value, 0 TSRMLS_CC); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_name->u.constant TSRMLS_CC); break; } } else { SET_NODE(opline->op2, class_name); } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; /* FIXME: Hack so that INIT_FCALL_BY_NAME still knows this is a class */ GET_NODE(result, opline->result); result->EA = opline->extended_value; } /* }}} */ void zend_do_label(znode *label TSRMLS_DC) /* {{{ */ { zend_label dest; if (!CG(context).labels) { ALLOC_HASHTABLE(CG(context).labels); zend_hash_init(CG(context).labels, 4, NULL, NULL, 0); } dest.brk_cont = CG(context).current_brk_cont; dest.opline_num = get_next_op_number(CG(active_op_array)); if (zend_hash_add(CG(context).labels, Z_STRVAL(label->u.constant), Z_STRLEN(label->u.constant) + 1, (void**)&dest, sizeof(zend_label), NULL) == FAILURE) { zend_error(E_COMPILE_ERROR, "Label '%s' already defined", Z_STRVAL(label->u.constant)); } /* Done with label now */ zval_dtor(&label->u.constant); } /* }}} */ void zend_resolve_goto_label(zend_op_array *op_array, zend_op *opline, int pass2 TSRMLS_DC) /* {{{ */ { zend_label *dest; long current, distance; zval *label; if (pass2) { label = opline->op2.zv; } else { label = &CONSTANT_EX(op_array, opline->op2.constant); } if (CG(context).labels == NULL || zend_hash_find(CG(context).labels, Z_STRVAL_P(label), Z_STRLEN_P(label)+1, (void**)&dest) == FAILURE) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; zend_error(E_COMPILE_ERROR, "'goto' to undefined label '%s'", Z_STRVAL_P(label)); } else { /* Label is not defined. Delay to pass 2. */ INC_BPC(op_array); return; } } opline->op1.opline_num = dest->opline_num; zval_dtor(label); Z_TYPE_P(label) = IS_NULL; /* Check that we are not moving into loop or switch */ current = opline->extended_value; for (distance = 0; current != dest->brk_cont; distance++) { if (current == -1) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; } zend_error(E_COMPILE_ERROR, "'goto' into loop or switch statement is disallowed"); } current = op_array->brk_cont_array[current].parent; } if (distance == 0) { /* Nothing to break out of, optimize to ZEND_JMP */ opline->opcode = ZEND_JMP; opline->extended_value = 0; SET_UNUSED(opline->op2); } else { /* Set real break distance */ ZVAL_LONG(label, distance); } if (pass2) { DEC_BPC(op_array); } } /* }}} */ void zend_do_goto(const znode *label TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_GOTO; opline->extended_value = CG(context).current_brk_cont; SET_UNUSED(opline->op1); SET_NODE(opline->op2, label); zend_resolve_goto_label(CG(active_op_array), opline, 0 TSRMLS_CC); } /* }}} */ void zend_release_labels(TSRMLS_D) /* {{{ */ { if (CG(context).labels) { zend_hash_destroy(CG(context).labels); FREE_HASHTABLE(CG(context).labels); } if (!zend_stack_is_empty(&CG(context_stack))) { zend_compiler_context *ctx; zend_stack_top(&CG(context_stack), (void**)&ctx); CG(context) = *ctx; zend_stack_del_top(&CG(context_stack)); } } /* }}} */ void zend_do_build_full_name(znode *result, znode *prefix, znode *name, int is_class_member TSRMLS_DC) /* {{{ */ { zend_uint length; if (!result) { result = prefix; } else { *result = *prefix; } if (is_class_member) { length = sizeof("::")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "::", sizeof("::")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("::")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } else { length = sizeof("\\")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "\\", sizeof("\\")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("\\")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } } /* }}} */ int zend_do_begin_class_member_function_call(znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { znode class_node; unsigned char *ptr = NULL; zend_op *opline; if (method_name->op_type == IS_CONST) { char *lcname = zend_str_tolower_dup(Z_STRVAL(method_name->u.constant), Z_STRLEN(method_name->u.constant)); if ((sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == Z_STRLEN(method_name->u.constant) && memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == 0) { zval_dtor(&method_name->u.constant); method_name->op_type = IS_UNUSED; } efree(lcname); } if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; opline = get_next_op(CG(active_op_array) TSRMLS_CC); } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->extended_value = class_node.EA ; } opline->opcode = ZEND_INIT_STATIC_METHOD_CALL; if (class_node.op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, &class_node); } if (method_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &method_name->u.constant TSRMLS_CC); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } } else { SET_NODE(opline->op2, method_name); } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 1; /* Dynamic */ } /* }}} */ void zend_do_end_function_call(znode *function_name, znode *result, const znode *argument_list, int is_method, int is_dynamic_fcall TSRMLS_DC) /* {{{ */ { zend_op *opline; if (is_method && function_name && function_name->op_type == IS_UNUSED) { /* clone */ if (Z_LVAL(argument_list->u.constant) != 0) { zend_error(E_WARNING, "Clone method does not require arguments"); } opline = &CG(active_op_array)->opcodes[Z_LVAL(function_name->u.constant)]; } else { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (!is_method && !is_dynamic_fcall && function_name->op_type==IS_CONST) { opline->opcode = ZEND_DO_FCALL; SET_NODE(opline->op1, function_name); CALCULATE_LITERAL_HASH(opline->op1.constant); GET_CACHE_SLOT(opline->op1.constant); } else { opline->opcode = ZEND_DO_FCALL_BY_NAME; SET_UNUSED(opline->op1); } } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(result, opline->result) ; SET_UNUSED(opline->op2); zend_stack_del_top(&CG(function_call_stack)); opline->extended_value = Z_LVAL(argument_list->u.constant); } /* }}} */ void zend_do_pass_param(znode *param, zend_uchar op, int offset TSRMLS_DC) /* {{{ */ { zend_op *opline; int original_op=op; zend_function **function_ptr_ptr, *function_ptr; int send_by_reference; int send_function = 0; zend_stack_top(&CG(function_call_stack), (void **) &function_ptr_ptr); function_ptr = *function_ptr_ptr; if (original_op == ZEND_SEND_REF) { if (function_ptr && function_ptr->common.function_name && function_ptr->common.type == ZEND_USER_FUNCTION && !ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed; " "If you would like to pass argument by reference, modify the declaration of %s().", function_ptr->common.function_name); } else { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed"); } return; } if (function_ptr) { if (ARG_MAY_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { if (param->op_type & (IS_VAR|IS_CV) && original_op != ZEND_SEND_VAL) { send_by_reference = 1; if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION | ZEND_ARG_SEND_SILENT; } } else { op = ZEND_SEND_VAL; send_by_reference = 0; } } else { send_by_reference = ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset) ? ZEND_ARG_SEND_BY_REF : 0; } } else { send_by_reference = 0; } if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION; } else if (op == ZEND_SEND_VAL && (param->op_type & (IS_VAR|IS_CV))) { op = ZEND_SEND_VAR_NO_REF; } if (op!=ZEND_SEND_VAR_NO_REF && send_by_reference==ZEND_ARG_SEND_BY_REF) { /* change to passing by reference */ switch (param->op_type) { case IS_VAR: case IS_CV: op = ZEND_SEND_REF; break; default: zend_error(E_COMPILE_ERROR, "Only variables can be passed by reference"); break; } } if (original_op == ZEND_SEND_VAR) { switch (op) { case ZEND_SEND_VAR_NO_REF: zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); break; case ZEND_SEND_VAR: if (function_ptr) { zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(param, BP_VAR_FUNC_ARG, offset TSRMLS_CC); } break; case ZEND_SEND_REF: zend_do_end_variable_parse(param, BP_VAR_W, 0 TSRMLS_CC); break; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (op == ZEND_SEND_VAR_NO_REF) { if (function_ptr) { opline->extended_value = ZEND_ARG_COMPILE_TIME_BOUND | send_by_reference | send_function; } else { opline->extended_value = send_function; } } else { if (function_ptr) { opline->extended_value = ZEND_DO_FCALL; } else { opline->extended_value = ZEND_DO_FCALL_BY_NAME; } } opline->opcode = op; SET_NODE(opline->op1, param); opline->op2.opline_num = offset; SET_UNUSED(opline->op2); } /* }}} */ static int generate_free_switch_expr(const zend_switch_entry *switch_entry TSRMLS_DC) /* {{{ */ { zend_op *opline; if (switch_entry->cond.op_type != IS_VAR && switch_entry->cond.op_type != IS_TMP_VAR) { return (switch_entry->cond.op_type == IS_UNUSED); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry->cond); SET_UNUSED(opline->op2); opline->extended_value = 0; return 0; } /* }}} */ static int generate_free_foreach_copy(const zend_op *foreach_copy TSRMLS_DC) /* {{{ */ { zend_op *opline; /* If we reach the seperator then stop applying the stack */ if (foreach_copy->result_type == IS_UNUSED && foreach_copy->op1_type == IS_UNUSED) { return 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->result_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->result); SET_UNUSED(opline->op2); opline->extended_value = 1; if (foreach_copy->op1_type != IS_UNUSED) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->op1_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->op1); SET_UNUSED(opline->op2); opline->extended_value = 0; } return 0; } /* }}} */ void zend_do_return(znode *expr, int do_end_vparse TSRMLS_DC) /* {{{ */ { zend_op *opline; int start_op_number, end_op_number; if (do_end_vparse) { if ((CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) && !zend_is_function_or_method_call(expr)) { zend_do_end_variable_parse(expr, BP_VAR_W, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(expr, BP_VAR_R, 0 TSRMLS_CC); } } start_op_number = get_next_op_number(CG(active_op_array)); #ifdef ZTS zend_stack_apply_with_argument(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_switch_expr TSRMLS_CC); zend_stack_apply_with_argument(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_foreach_copy TSRMLS_CC); #else zend_stack_apply(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_switch_expr); zend_stack_apply(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_foreach_copy); #endif end_op_number = get_next_op_number(CG(active_op_array)); while (start_op_number < end_op_number) { CG(active_op_array)->opcodes[start_op_number].extended_value |= EXT_TYPE_FREE_ON_RETURN; start_op_number++; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) ? ZEND_RETURN_BY_REF : ZEND_RETURN; if (expr) { SET_NODE(opline->op1, expr); if (do_end_vparse && zend_is_function_or_method_call(expr)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } } else { opline->op1_type = IS_CONST; LITERAL_NULL(opline->op1); } SET_UNUSED(opline->op2); } /* }}} */ static int zend_add_try_element(zend_uint try_op TSRMLS_DC) /* {{{ */ { int try_catch_offset = CG(active_op_array)->last_try_catch++; CG(active_op_array)->try_catch_array = erealloc(CG(active_op_array)->try_catch_array, sizeof(zend_try_catch_element)*CG(active_op_array)->last_try_catch); CG(active_op_array)->try_catch_array[try_catch_offset].try_op = try_op; return try_catch_offset; } /* }}} */ static void zend_add_catch_element(int offset, zend_uint catch_op TSRMLS_DC) /* {{{ */ { CG(active_op_array)->try_catch_array[offset].catch_op = catch_op; } /* }}} */ void zend_do_first_catch(znode *open_parentheses TSRMLS_DC) /* {{{ */ { open_parentheses->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_initialize_try_catch_element(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist jmp_list; zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); zend_add_catch_element(try_token->u.op.opline_num, get_next_op_number(CG(active_op_array)) TSRMLS_CC); } /* }}} */ void zend_do_mark_last_catch(const znode *first_catch, const znode *last_additional_catch TSRMLS_DC) /* {{{ */ { CG(active_op_array)->last--; zend_do_if_end(TSRMLS_C); if (last_additional_catch->u.op.opline_num == -1) { CG(active_op_array)->opcodes[first_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[first_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } else { CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_try(znode *try_token TSRMLS_DC) /* {{{ */ { try_token->u.op.opline_num = zend_add_try_element(get_next_op_number(CG(active_op_array)) TSRMLS_CC); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_catch(znode *try_token, znode *class_name, znode *catch_var, znode *first_catch TSRMLS_DC) /* {{{ */ { long catch_op_number; zend_op *opline; znode catch_class; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); catch_class = *class_name; } else { zend_error(E_COMPILE_ERROR, "Bad class name in the catch statement"); } catch_op_number = get_next_op_number(CG(active_op_array)); if (first_catch) { first_catch->u.op.opline_num = catch_op_number; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CATCH; opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &catch_class.u.constant TSRMLS_CC); opline->op2_type = IS_CV; opline->op2.var = lookup_cv(CG(active_op_array), catch_var->u.constant.value.str.val, catch_var->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(catch_var->u.constant) = (char*)CG(active_op_array)->vars[opline->op2.var].name; opline->result.num = 0; /* 1 means it's the last catch in the block */ try_token->u.op.opline_num = catch_op_number; } /* }}} */ void zend_do_end_catch(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); CG(active_op_array)->opcodes[try_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_throw(const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_THROW; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); } /* }}} */ ZEND_API void function_add_ref(zend_function *function) /* {{{ */ { if (function->type == ZEND_USER_FUNCTION) { zend_op_array *op_array = &function->op_array; (*op_array->refcount)++; if (op_array->static_variables) { HashTable *static_variables = op_array->static_variables; zval *tmp_zval; ALLOC_HASHTABLE(op_array->static_variables); zend_hash_init(op_array->static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(op_array->static_variables, static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_zval, sizeof(zval *)); } op_array->run_time_cache = NULL; } } /* }}} */ static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */ { zend_function *function; if (!ce->parent) { return; } /* You cannot change create_object */ ce->create_object = ce->parent->create_object; /* Inherit special functions if needed */ if (!ce->get_iterator) { ce->get_iterator = ce->parent->get_iterator; } if (!ce->iterator_funcs.funcs) { ce->iterator_funcs.funcs = ce->parent->iterator_funcs.funcs; } if (!ce->__get) { ce->__get = ce->parent->__get; } if (!ce->__set) { ce->__set = ce->parent->__set; } if (!ce->__unset) { ce->__unset = ce->parent->__unset; } if (!ce->__isset) { ce->__isset = ce->parent->__isset; } if (!ce->__call) { ce->__call = ce->parent->__call; } if (!ce->__callstatic) { ce->__callstatic = ce->parent->__callstatic; } if (!ce->__tostring) { ce->__tostring = ce->parent->__tostring; } if (!ce->clone) { ce->clone = ce->parent->clone; } if(!ce->serialize) { ce->serialize = ce->parent->serialize; } if(!ce->unserialize) { ce->unserialize = ce->parent->unserialize; } if (!ce->destructor) { ce->destructor = ce->parent->destructor; } if (ce->constructor) { if (ce->parent->constructor && ce->parent->constructor->common.fn_flags & ZEND_ACC_FINAL) { zend_error(E_ERROR, "Cannot override final %s::%s() with %s::%s()", ce->parent->name, ce->parent->constructor->common.function_name, ce->name, ce->constructor->common.function_name ); } return; } if (zend_hash_find(&ce->parent->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), (void **)&function)==SUCCESS) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), function, sizeof(zend_function), NULL); function_add_ref(function); } else { /* Don't inherit the old style constructor if we already have the new style constructor */ char *lc_class_name; char *lc_parent_class_name; lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); if (!zend_hash_exists(&ce->function_table, lc_class_name, ce->name_length+1)) { lc_parent_class_name = zend_str_tolower_dup(ce->parent->name, ce->parent->name_length); if (!zend_hash_exists(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1) && zend_hash_find(&ce->parent->function_table, lc_parent_class_name, ce->parent->name_length+1, (void **)&function)==SUCCESS) { if (function->common.fn_flags & ZEND_ACC_CTOR) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1, function, sizeof(zend_function), NULL); function_add_ref(function); } } efree(lc_parent_class_name); } efree(lc_class_name); } ce->constructor = ce->parent->constructor; } /* }}} */ char *zend_visibility_string(zend_uint fn_flags) /* {{{ */ { if (fn_flags & ZEND_ACC_PRIVATE) { return "private"; } if (fn_flags & ZEND_ACC_PROTECTED) { return "protected"; } if (fn_flags & ZEND_ACC_PUBLIC) { return "public"; } return ""; } /* }}} */ static void do_inherit_method(zend_function *function) /* {{{ */ { /* The class entry of the derived function intentionally remains the same * as that of the parent class. That allows us to know in which context * we're running, and handle private method calls properly. */ function_add_ref(function); } /* }}} */ static zend_bool zend_do_perform_implementation_check(const zend_function *fe, const zend_function *proto TSRMLS_DC) /* {{{ */ { zend_uint i; /* If it's a user function then arg_info == NULL means we don't have any parameters but * we still need to do the arg number checks. We are only willing to ignore this for internal * functions because extensions don't always define arg_info. */ if (!proto || (!proto->common.arg_info && proto->common.type != ZEND_USER_FUNCTION)) { return 1; } /* Checks for constructors only if they are declared in an interface, * or explicitly marked as abstract */ if ((fe->common.fn_flags & ZEND_ACC_CTOR) && ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)) { return 1; } /* check number of arguments */ if (proto->common.required_num_args < fe->common.required_num_args || proto->common.num_args > fe->common.num_args) { return 0; } if (fe->common.type != ZEND_USER_FUNCTION && (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) != 0 && (fe->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) == 0) { return 0; } /* by-ref constraints on return values are covariant */ if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) { return 0; } for (i=0; i < proto->common.num_args; i++) { if (ZEND_LOG_XOR(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)) { /* Only one has a type hint and the other one doesn't */ return 0; } if (fe->common.arg_info[i].class_name && strcasecmp(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)!=0) { const char *colon; if (fe->common.type != ZEND_USER_FUNCTION) { return 0; } else if (strchr(proto->common.arg_info[i].class_name, '\\') != NULL || (colon = zend_memrchr(fe->common.arg_info[i].class_name, '\\', fe->common.arg_info[i].class_name_len)) == NULL || strcasecmp(colon+1, proto->common.arg_info[i].class_name) != 0) { zend_class_entry **fe_ce, **proto_ce; int found, found2; found = zend_lookup_class(fe->common.arg_info[i].class_name, fe->common.arg_info[i].class_name_len, &fe_ce TSRMLS_CC); found2 = zend_lookup_class(proto->common.arg_info[i].class_name, proto->common.arg_info[i].class_name_len, &proto_ce TSRMLS_CC); /* Check for class alias */ if (found != SUCCESS || found2 != SUCCESS || (*fe_ce)->type == ZEND_INTERNAL_CLASS || (*proto_ce)->type == ZEND_INTERNAL_CLASS || *fe_ce != *proto_ce) { return 0; } } } if (fe->common.arg_info[i].type_hint != proto->common.arg_info[i].type_hint) { /* Incompatible type hint */ return 0; } /* by-ref constraints on arguments are invariant */ if (fe->common.arg_info[i].pass_by_reference != proto->common.arg_info[i].pass_by_reference) { return 0; } } if (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) { for (i=proto->common.num_args; i < fe->common.num_args; i++) { if (!fe->common.arg_info[i].pass_by_reference) { return 0; } } } return 1; } /* }}} */ #define REALLOC_BUF_IF_EXCEED(buf, offset, length, size) \ if (UNEXPECTED(offset - buf + size >= length)) { \ length += size + 1; \ buf = erealloc(buf, length); \ } static char * zend_get_function_declaration(zend_function *fptr TSRMLS_DC) /* {{{ */ { char *offset, *buf; zend_uint length = 1024; offset = buf = (char *)emalloc(length * sizeof(char)); if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { *(offset++) = '&'; *(offset++) = ' '; } if (fptr->common.scope) { memcpy(offset, fptr->common.scope->name, fptr->common.scope->name_length); offset += fptr->common.scope->name_length; *(offset++) = ':'; *(offset++) = ':'; } { size_t name_len = strlen(fptr->common.function_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, name_len); memcpy(offset, fptr->common.function_name, name_len); offset += name_len; } *(offset++) = '('; if (fptr->common.arg_info) { zend_uint i, required; zend_arg_info *arg_info = fptr->common.arg_info; required = fptr->common.required_num_args; for (i = 0; i < fptr->common.num_args;) { if (arg_info->class_name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->class_name_len); memcpy(offset, arg_info->class_name, arg_info->class_name_len); offset += arg_info->class_name_len; *(offset++) = ' '; } else if (arg_info->type_hint) { zend_uint type_name_len; char *type_name = zend_get_type_by_const(arg_info->type_hint); type_name_len = strlen(type_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, type_name_len); memcpy(offset, type_name, type_name_len); offset += type_name_len; *(offset++) = ' '; } if (arg_info->pass_by_reference) { *(offset++) = '&'; } *(offset++) = '$'; if (arg_info->name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->name_len); memcpy(offset, arg_info->name, arg_info->name_len); offset += arg_info->name_len; } else { zend_uint idx = i; memcpy(offset, "param", 5); offset += 5; do { *(offset++) = (char) (idx % 10) + '0'; idx /= 10; } while (idx > 0); } if (i >= required) { *(offset++) = ' '; *(offset++) = '='; *(offset++) = ' '; if (fptr->type == ZEND_USER_FUNCTION) { zend_op *precv = NULL; { zend_uint idx = i; zend_op *op = ((zend_op_array *)fptr)->opcodes; zend_op *end = op + ((zend_op_array *)fptr)->last; ++idx; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT) && op->op1.num == (long)idx) { precv = op; } ++op; } } if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) { zval *zv, zv_copy; int use_copy; ALLOC_ZVAL(zv); *zv = *precv->op2.zv; zval_copy_ctor(zv); INIT_PZVAL(zv); zval_update_constant_ex(&zv, (void*)1, fptr->common.scope TSRMLS_CC); if (Z_TYPE_P(zv) == IS_BOOL) { if (Z_LVAL_P(zv)) { memcpy(offset, "true", 4); offset += 4; } else { memcpy(offset, "false", 5); offset += 5; } } else if (Z_TYPE_P(zv) == IS_NULL) { memcpy(offset, "NULL", 4); offset += 4; } else if (Z_TYPE_P(zv) == IS_STRING) { *(offset++) = '\''; REALLOC_BUF_IF_EXCEED(buf, offset, length, MIN(Z_STRLEN_P(zv), 10)); memcpy(offset, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 10)); offset += MIN(Z_STRLEN_P(zv), 10); if (Z_STRLEN_P(zv) > 10) { *(offset++) = '.'; *(offset++) = '.'; *(offset++) = '.'; } *(offset++) = '\''; } else if (Z_TYPE_P(zv) == IS_ARRAY) { memcpy(offset, "Array", 5); offset += 5; } else { zend_make_printable_zval(zv, &zv_copy, &use_copy); REALLOC_BUF_IF_EXCEED(buf, offset, length, Z_STRLEN(zv_copy)); memcpy(offset, Z_STRVAL(zv_copy), Z_STRLEN(zv_copy)); offset += Z_STRLEN(zv_copy); if (use_copy) { zval_dtor(&zv_copy); } } zval_ptr_dtor(&zv); } } else { memcpy(offset, "NULL", 4); offset += 4; } } if (++i < fptr->common.num_args) { *(offset++) = ','; *(offset++) = ' '; } arg_info++; REALLOC_BUF_IF_EXCEED(buf, offset, length, 32); } } *(offset++) = ')'; *offset = '\0'; return buf; } /* }}} */ static void do_inheritance_check_on_method(zend_function *child, zend_function *parent TSRMLS_DC) /* {{{ */ { zend_uint child_flags; zend_uint parent_flags = parent->common.fn_flags; if ((parent->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && parent->common.fn_flags & ZEND_ACC_ABSTRACT && parent->common.scope != (child->common.prototype ? child->common.prototype->common.scope : child->common.scope) && child->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_IMPLEMENTED_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Can't inherit abstract function %s::%s() (previously declared abstract in %s)", parent->common.scope->name, child->common.function_name, child->common.prototype ? child->common.prototype->common.scope->name : child->common.scope->name); } if (parent_flags & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot override final method %s::%s()", ZEND_FN_SCOPE_NAME(parent), child->common.function_name); } child_flags = child->common.fn_flags; /* You cannot change from static to non static and vice versa. */ if ((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC)) { if (child->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot make non static method %s::%s() static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } else { zend_error(E_COMPILE_ERROR, "Cannot make static method %s::%s() non static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } } /* Disallow making an inherited method abstract. */ if ((child_flags & ZEND_ACC_ABSTRACT) && !(parent_flags & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Cannot make non abstract method %s::%s() abstract in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } if (parent_flags & ZEND_ACC_CHANGED) { child->common.fn_flags |= ZEND_ACC_CHANGED; } else { /* Prevent derived classes from restricting access that was available in parent classes */ if ((child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::%s() must be %s (as in class %s)%s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if (((child_flags & ZEND_ACC_PPP_MASK) < (parent_flags & ZEND_ACC_PPP_MASK)) && ((parent_flags & ZEND_ACC_PPP_MASK) & ZEND_ACC_PRIVATE)) { child->common.fn_flags |= ZEND_ACC_CHANGED; } } if (parent_flags & ZEND_ACC_PRIVATE) { child->common.prototype = NULL; } else if (parent_flags & ZEND_ACC_ABSTRACT) { child->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; child->common.prototype = parent; } else if (!(parent->common.fn_flags & ZEND_ACC_CTOR) || (parent->common.prototype && (parent->common.prototype->common.scope->ce_flags & ZEND_ACC_INTERFACE))) { /* ctors only have a prototype if it comes from an interface */ child->common.prototype = parent->common.prototype ? parent->common.prototype : parent; } if (child->common.prototype && (child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { if (!zend_do_perform_implementation_check(child, child->common.prototype TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s::%s() must be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_get_function_declaration(child->common.prototype TSRMLS_CC)); } } else if (EG(error_reporting) & E_STRICT || EG(user_error_handler)) { /* Check E_STRICT (or custom error handler) before the check so that we save some time */ if (!zend_do_perform_implementation_check(child, parent TSRMLS_CC)) { char *method_prototype = zend_get_function_declaration(child->common.prototype TSRMLS_CC); zend_error(E_STRICT, "Declaration of %s::%s() should be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, method_prototype); efree(method_prototype); } } } /* }}} */ static zend_bool do_inherit_method_check(HashTable *child_function_table, zend_function *parent, const zend_hash_key *hash_key, zend_class_entry *child_ce) /* {{{ */ { zend_uint parent_flags = parent->common.fn_flags; zend_function *child; TSRMLS_FETCH(); if (zend_hash_quick_find(child_function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child)==FAILURE) { if (parent_flags & (ZEND_ACC_ABSTRACT)) { child_ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } return 1; /* method doesn't exist in child, copy from parent */ } do_inheritance_check_on_method(child, parent TSRMLS_CC); return 0; } /* }}} */ static zend_bool do_inherit_property_access_check(HashTable *target_ht, zend_property_info *parent_info, const zend_hash_key *hash_key, zend_class_entry *ce) /* {{{ */ { zend_property_info *child_info; zend_class_entry *parent_ce = ce->parent; if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW)) { if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { child_info->flags |= ZEND_ACC_CHANGED; } else { zend_hash_quick_update(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, parent_info, sizeof(zend_property_info), (void **) &child_info); if(ce->type & ZEND_INTERNAL_CLASS) { zend_duplicate_property_info_internal(child_info); } else { zend_duplicate_property_info(child_info); } child_info->flags &= ~ZEND_ACC_PRIVATE; /* it's not private anymore */ child_info->flags |= ZEND_ACC_SHADOW; /* but it's a shadow of private */ } return 0; /* don't copy access information to child */ } if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { if ((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s", (parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", parent_ce->name, hash_key->arKey, (child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ce->name, hash_key->arKey); } if(parent_info->flags & ZEND_ACC_CHANGED) { child_info->flags |= ZEND_ACC_CHANGED; } if ((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ce->name, hash_key->arKey, zend_visibility_string(parent_info->flags), parent_ce->name, (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if ((child_info->flags & ZEND_ACC_STATIC) == 0) { Z_DELREF_P(ce->default_properties_table[parent_info->offset]); ce->default_properties_table[parent_info->offset] = ce->default_properties_table[child_info->offset]; ce->default_properties_table[child_info->offset] = NULL; child_info->offset = parent_info->offset; } return 0; /* Don't copy from parent */ } else { return 1; /* Copy from parent */ } } /* }}} */ static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce TSRMLS_CC) == FAILURE) { zend_error(E_CORE_ERROR, "Class %s could not implement interface %s", ce->name, iface->name); } if (ce == iface) { zend_error(E_ERROR, "Interface %s cannot implement itself", ce->name); } } /* }}} */ ZEND_API void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface TSRMLS_DC) /* {{{ */ { /* expects interface to be contained in ce's interface list already */ zend_uint i, ce_num, if_num = iface->num_interfaces; zend_class_entry *entry; if (if_num==0) { return; } ce_num = ce->num_interfaces; if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } /* Inherit the interfaces, only if they're not already inherited by the class */ while (if_num--) { entry = iface->interfaces[if_num]; for (i = 0; i < ce_num; i++) { if (ce->interfaces[i] == entry) { break; } } if (i == ce_num) { ce->interfaces[ce->num_interfaces++] = entry; } } /* and now call the implementing handlers */ while (ce_num < ce->num_interfaces) { do_implement_interface(ce, ce->interfaces[ce_num++] TSRMLS_CC); } } /* }}} */ #ifdef ZTS static void zval_internal_ctor(zval **p) /* {{{ */ { zval *orig_ptr = *p; ALLOC_ZVAL(*p); MAKE_COPY_ZVAL(&orig_ptr, *p); } /* }}} */ # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) (((parent_ce)->type != (ce)->type) ? zval_internal_ctor : zval_add_ref)) #else # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) zval_add_ref) #endif ZEND_API void zend_do_inheritance(zend_class_entry *ce, zend_class_entry *parent_ce TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; if ((ce->ce_flags & ZEND_ACC_INTERFACE) && !(parent_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ce->name, parent_ce->name); } if (parent_ce->ce_flags & ZEND_ACC_FINAL_CLASS) { zend_error(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ce->name, parent_ce->name); } ce->parent = parent_ce; /* Copy serialize/unserialize callbacks */ if (!ce->serialize) { ce->serialize = parent_ce->serialize; } if (!ce->unserialize) { ce->unserialize = parent_ce->unserialize; } /* Inherit interfaces */ zend_do_inherit_interfaces(ce, parent_ce TSRMLS_CC); /* Inherit properties */ if (parent_ce->default_properties_count) { int i = ce->default_properties_count + parent_ce->default_properties_count; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_properties_count) { while (i-- > parent_ce->default_properties_count) { ce->default_properties_table[i] = ce->default_properties_table[i - parent_ce->default_properties_count]; } } for (i = 0; i < parent_ce->default_properties_count; i++) { ce->default_properties_table[i] = parent_ce->default_properties_table[i]; if (ce->default_properties_table[i]) { #ifdef ZTS if (parent_ce->type != ce->type) { zval *p; ALLOC_ZVAL(p); MAKE_COPY_ZVAL(&ce->default_properties_table[i], p); ce->default_properties_table[i] = p; } else { Z_ADDREF_P(ce->default_properties_table[i]); } #else Z_ADDREF_P(ce->default_properties_table[i]); #endif } } ce->default_properties_count += parent_ce->default_properties_count; } if (parent_ce->type != ce->type) { /* User class extends internal class */ zend_update_class_constants(parent_ce TSRMLS_CC); if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = erealloc(ce->default_static_members_table, sizeof(void*) * i); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&CE_STATIC_MEMBERS(parent_ce)[i]); ce->default_static_members_table[i] = CE_STATIC_MEMBERS(parent_ce)[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; ce->static_members_table = ce->default_static_members_table; } } else { if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&parent_ce->default_static_members_table[i]); ce->default_static_members_table[i] = parent_ce->default_static_members_table[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } } for (zend_hash_internal_pointer_reset(&ce->properties_info); zend_hash_get_current_data(&ce->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->properties_info)) { if (property_info->ce == ce) { if (property_info->flags & ZEND_ACC_STATIC) { property_info->offset += parent_ce->default_static_members_count; } else { property_info->offset += parent_ce->default_properties_count; } } } zend_hash_merge_ex(&ce->properties_info, &parent_ce->properties_info, (copy_ctor_func_t) (ce->type & ZEND_INTERNAL_CLASS ? zend_duplicate_property_info_internal : zend_duplicate_property_info), sizeof(zend_property_info), (merge_checker_func_t) do_inherit_property_access_check, ce); zend_hash_merge(&ce->constants_table, &parent_ce->constants_table, zval_property_ctor(parent_ce, ce), NULL, sizeof(zval *), 0); zend_hash_merge_ex(&ce->function_table, &parent_ce->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_inherit_parent_constructor(ce); if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS && ce->type == ZEND_INTERNAL_CLASS) { ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } else if (!(ce->ce_flags & ZEND_ACC_IMPLEMENT_INTERFACES) && !(ce->ce_flags & ZEND_ACC_IMPLEMENT_TRAITS)) { /* The verification will be done in runtime by ZEND_VERIFY_ABSTRACT_CLASS */ zend_verify_abstract_class(ce TSRMLS_CC); } ce->ce_flags |= parent_ce->ce_flags & ZEND_HAS_STATIC_IN_METHODS; } /* }}} */ static zend_bool do_inherit_constant_check(HashTable *child_constants_table, const zval **parent_constant, const zend_hash_key *hash_key, const zend_class_entry *iface) /* {{{ */ { zval **old_constant; if (zend_hash_quick_find(child_constants_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**)&old_constant) == SUCCESS) { if (*old_constant != *parent_constant) { zend_error(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", hash_key->arKey, iface->name); } return 0; } return 1; } /* }}} */ static int do_interface_constant_check(zval **val TSRMLS_DC, int num_args, va_list args, const zend_hash_key *key) /* {{{ */ { zend_class_entry **iface = va_arg(args, zend_class_entry**); do_inherit_constant_check(&(*iface)->constants_table, (const zval **) val, key, *iface); return ZEND_HASH_APPLY_KEEP; } /* }}} */ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_iface_num = ce->num_interfaces; zend_uint parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0; for (i = 0; i < ce->num_interfaces; i++) { if (ce->interfaces[i] == NULL) { memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i)); i--; } else if (ce->interfaces[i] == iface) { if (i < parent_iface_num) { ignore = 1; } else { zend_error(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ce->name, iface->name); } } } if (ignore) { /* Check for attempt to redeclare interface constants */ zend_hash_apply_with_arguments(&ce->constants_table TSRMLS_CC, (apply_func_args_t) do_interface_constant_check, 1, &iface); } else { if (ce->num_interfaces >= current_iface_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } } ce->interfaces[ce->num_interfaces++] = iface; zend_hash_merge_ex(&ce->constants_table, &iface->constants_table, (copy_ctor_func_t) zval_add_ref, sizeof(zval *), (merge_checker_func_t) do_inherit_constant_check, iface); zend_hash_merge_ex(&ce->function_table, &iface->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_implement_interface(ce, iface TSRMLS_CC); zend_do_inherit_interfaces(ce, iface TSRMLS_CC); } } /* }}} */ ZEND_API void zend_do_implement_trait(zend_class_entry *ce, zend_class_entry *trait TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_trait_num = ce->num_traits; zend_uint parent_trait_num = ce->parent ? ce->parent->num_traits : 0; for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == NULL) { memmove(ce->traits + i, ce->traits + i + 1, sizeof(zend_class_entry*) * (--ce->num_traits - i)); i--; } else if (ce->traits[i] == trait) { if (i < parent_trait_num) { ignore = 1; } } } if (!ignore) { if (ce->num_traits >= current_trait_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->traits = (zend_class_entry **) realloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } else { ce->traits = (zend_class_entry **) erealloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } } ce->traits[ce->num_traits++] = trait; } } /* }}} */ static int zend_traits_merge_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { size_t current; size_t i; size_t count; HashTable* resulting_table; HashTable** function_tables; zend_class_entry *ce; size_t collision = 0; size_t abstract_solved = 0; zend_function* other_trait_fn; current = va_arg(args, size_t); /* index of current trait */ count = va_arg(args, size_t); resulting_table = va_arg(args, HashTable*); function_tables = va_arg(args, HashTable**); ce = va_arg(args, zend_class_entry*); for (i = 0; i < count; i++) { if (i == current) { continue; /* just skip this, cause its the table this function is applied on */ } if (zend_hash_quick_find(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&other_trait_fn) == SUCCESS) { /* if it is an abstract method, there is no collision */ if (other_trait_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* In case both are abstract, just check prototype, but need to do that in both directions */ if ( !zend_do_perform_implementation_check(fn, other_trait_fn TSRMLS_CC) || !zend_do_perform_implementation_check(other_trait_fn, fn TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s must be compatible with %s", //ZEND_FN_SCOPE_NAME(fn), fn->common.function_name, //::%s() zend_get_function_declaration(fn TSRMLS_CC), zend_get_function_declaration(other_trait_fn TSRMLS_CC)); } } else { /* otherwise, do the full check */ do_inheritance_check_on_method(fn, other_trait_fn TSRMLS_CC); } /* we can savely free and remove it from other table */ zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } else { /* if it is not an abstract method, there is still no collision */ /* if fn is an abstract method */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible. Here, we already know other_trait_fn cannot be abstract, full check ok. */ do_inheritance_check_on_method(other_trait_fn, fn TSRMLS_CC); /* just mark as solved, will be added if its own trait is processed */ abstract_solved = 1; } else { /* but else, we have a collision of non-abstract methods */ collision++; zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } } } if (collision) { zend_function* class_fn; /* make sure method is not already overridden in class */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&class_fn) == FAILURE || class_fn->common.scope != ce) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because there are collisions with other trait methods on %s", fn->common.function_name, ce->name); } zend_function_dtor(fn); } else if (abstract_solved) { zend_function_dtor(fn); } else { /* Add it to result function table */ if (zend_hash_quick_add(resulting_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, fn, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating resulting trait method table", fn->common.function_name); } } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ /* {{{ Originates from php_runkit_function_copy_ctor Duplicate structures in an op_array where necessary to make an outright duplicate */ static void zend_traits_duplicate_function(zend_function *fe, zend_class_entry *target_ce, char *newname TSRMLS_DC) { zend_literal *literals_copy; zend_compiled_variable *dupvars; zend_op *opcode_copy; zval class_name_zv; int class_name_literal; int i; int number_of_literals; if (fe->op_array.static_variables) { HashTable *tmpHash; ALLOC_HASHTABLE(tmpHash); zend_hash_init(tmpHash, zend_hash_num_elements(fe->op_array.static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_apply_with_arguments(fe->op_array.static_variables TSRMLS_CC, (apply_func_args_t)zval_copy_static_var, 1, tmpHash); fe->op_array.static_variables = tmpHash; } number_of_literals = fe->op_array.last_literal; literals_copy = (zend_literal*)emalloc(number_of_literals * sizeof(zend_literal)); for (i = 0; i < number_of_literals; i++) { literals_copy[i] = fe->op_array.literals[i]; zval_copy_ctor(&literals_copy[i].constant); } fe->op_array.literals = literals_copy; fe->op_array.refcount = emalloc(sizeof(zend_uint)); *(fe->op_array.refcount) = 1; if (fe->op_array.vars) { i = fe->op_array.last_var; dupvars = safe_emalloc(fe->op_array.last_var, sizeof(zend_compiled_variable), 0); while (i > 0) { i--; dupvars[i].name = estrndup(fe->op_array.vars[i].name, fe->op_array.vars[i].name_len); dupvars[i].name_len = fe->op_array.vars[i].name_len; dupvars[i].hash_value = fe->op_array.vars[i].hash_value; } fe->op_array.vars = dupvars; } else { fe->op_array.vars = NULL; } opcode_copy = safe_emalloc(sizeof(zend_op), fe->op_array.last, 0); for(i = 0; i < fe->op_array.last; i++) { opcode_copy[i] = fe->op_array.opcodes[i]; if (opcode_copy[i].op1_type != IS_CONST) { switch (opcode_copy[i].opcode) { case ZEND_GOTO: case ZEND_JMP: if (opcode_copy[i].op1.jmp_addr && opcode_copy[i].op1.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op1.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op1.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op1.jmp_addr - fe->op_array.opcodes); } break; } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op1.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op1.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op1.zv = &fe->op_array.literals[class_name_literal].constant; } } if (opcode_copy[i].op2_type != IS_CONST) { switch (opcode_copy[i].opcode) { case ZEND_JMPZ: case ZEND_JMPNZ: case ZEND_JMPZ_EX: case ZEND_JMPNZ_EX: case ZEND_JMP_SET: case ZEND_JMP_SET_VAR: if (opcode_copy[i].op2.jmp_addr && opcode_copy[i].op2.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op2.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op2.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op2.jmp_addr - fe->op_array.opcodes); } break; } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op2.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op2.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op2.zv = &fe->op_array.literals[class_name_literal].constant; } } } fe->op_array.opcodes = opcode_copy; fe->op_array.function_name = newname; /* was setting it to fe which does not work since fe is stack allocated and not a stable address */ /* fe->op_array.prototype = fe->op_array.prototype; */ if (fe->op_array.arg_info) { zend_arg_info *tmpArginfo; tmpArginfo = safe_emalloc(sizeof(zend_arg_info), fe->op_array.num_args, 0); for(i = 0; i < fe->op_array.num_args; i++) { tmpArginfo[i] = fe->op_array.arg_info[i]; tmpArginfo[i].name = estrndup(tmpArginfo[i].name, tmpArginfo[i].name_len); if (tmpArginfo[i].class_name) { tmpArginfo[i].class_name = estrndup(tmpArginfo[i].class_name, tmpArginfo[i].class_name_len); } } fe->op_array.arg_info = tmpArginfo; } fe->op_array.doc_comment = estrndup(fe->op_array.doc_comment, fe->op_array.doc_comment_len); fe->op_array.try_catch_array = (zend_try_catch_element*)estrndup((char*)fe->op_array.try_catch_array, sizeof(zend_try_catch_element) * fe->op_array.last_try_catch); fe->op_array.brk_cont_array = (zend_brk_cont_element*)estrndup((char*)fe->op_array.brk_cont_array, sizeof(zend_brk_cont_element) * fe->op_array.last_brk_cont); } /* }}} */ static void zend_add_magic_methods(zend_class_entry* ce, const char* mname, uint mname_len, zend_function* fe TSRMLS_DC) /* {{{ */ { if (!strncmp(mname, ZEND_CLONE_FUNC_NAME, mname_len)) { ce->clone = fe; fe->common.fn_flags |= ZEND_ACC_CLONE; } else if (!strncmp(mname, ZEND_CONSTRUCTOR_FUNC_NAME, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } else if (!strncmp(mname, ZEND_DESTRUCTOR_FUNC_NAME, mname_len)) { ce->destructor = fe; fe->common.fn_flags |= ZEND_ACC_DTOR; } else if (!strncmp(mname, ZEND_GET_FUNC_NAME, mname_len)) { ce->__get = fe; } else if (!strncmp(mname, ZEND_SET_FUNC_NAME, mname_len)) { ce->__set = fe; } else if (!strncmp(mname, ZEND_CALL_FUNC_NAME, mname_len)) { ce->__call = fe; } else if (!strncmp(mname, ZEND_UNSET_FUNC_NAME, mname_len)) { ce->__unset = fe; } else if (!strncmp(mname, ZEND_ISSET_FUNC_NAME, mname_len)) { ce->__isset = fe; } else if (!strncmp(mname, ZEND_CALLSTATIC_FUNC_NAME, mname_len)) { ce->__callstatic = fe; } else if (!strncmp(mname, ZEND_TOSTRING_FUNC_NAME, mname_len)) { ce->__tostring = fe; } else if (ce->name_length + 1 == mname_len) { char *lowercase_name = emalloc(ce->name_length + 1); zend_str_tolower_copy(lowercase_name, ce->name, ce->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, ce->name_length + 1, 1 TSRMLS_CC); if (!memcmp(mname, lowercase_name, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } str_efree(lowercase_name); } } /* }}} */ static int zend_traits_merge_functions_to_class(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zend_class_entry *ce = va_arg(args, zend_class_entry*); int add = 0; zend_function* existing_fn = NULL; zend_function fn_copy, *fn_copy_p; zend_function* prototype = NULL; /* is used to determine the prototype according to the inheritance chain */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &existing_fn) == FAILURE) { add = 1; /* not found */ } else if (existing_fn->common.scope != ce) { add = 1; /* or inherited from other class or interface */ } if (add) { zend_function* parent_function; if (ce->parent && zend_hash_quick_find(&ce->parent->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &parent_function) != FAILURE) { prototype = parent_function; /* ->common.fn_flags |= ZEND_ACC_ABSTRACT; */ /* we got that method in the parent class, and are going to override it, except, if the trait is just asking to have an abstract method implemented. */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* then we clean up an skip this method */ zend_function_dtor(fn); return ZEND_HASH_APPLY_REMOVE; } } fn->common.scope = ce; fn->common.prototype = prototype; if (prototype && (prototype->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT || prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { fn->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; } else if (fn->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT) { /* remove ZEND_ACC_IMPLEMENTED_ABSTRACT flag, think it shouldn't be copied to class */ fn->common.fn_flags = fn->common.fn_flags - ZEND_ACC_IMPLEMENTED_ABSTRACT; } /* check whether the trait method fullfills the inheritance requirements */ if (prototype) { do_inheritance_check_on_method(fn, prototype TSRMLS_CC); } /* one more thing: make sure we properly implement an abstract method */ if (existing_fn && existing_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { do_inheritance_check_on_method(fn, existing_fn TSRMLS_CC); } /* delete inherited fn if the function to be added is not abstract */ if (existing_fn && existing_fn->common.scope != ce && (fn->common.fn_flags & ZEND_ACC_ABSTRACT) == 0) { /* it is just a reference which was added to the subclass while doing the inheritance, so we can deleted now, and will add the overriding method afterwards. Except, if we try to add an abstract function, then we should not delete the inherited one */ zend_hash_quick_del(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h); } if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (fn->op_array.static_variables) { ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, ce, estrdup(fn->common.function_name) TSRMLS_CC); if (zend_hash_quick_update(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, &fn_copy, sizeof(zend_function), (void**)&fn_copy_p)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating class method table", hash_key->arKey); } zend_add_magic_methods(ce, hash_key->arKey, hash_key->nKeyLength, fn_copy_p TSRMLS_CC); zend_function_dtor(fn); } else { zend_function_dtor(fn); } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ static int zend_traits_copy_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { HashTable* target; zend_class_entry *target_ce; zend_trait_alias** aliases; HashTable* exclude_table; char* lcname; unsigned int fnname_len; zend_function fn_copy; void* dummy; size_t i = 0; target = va_arg(args, HashTable*); target_ce = va_arg(args, zend_class_entry*); aliases = va_arg(args, zend_trait_alias**); exclude_table = va_arg(args, HashTable*); fnname_len = strlen(fn->common.function_name); /* apply aliases which are qualified with a class name, there should not be any ambiguity */ if (aliases) { while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias != NULL && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && aliases[i]->trait_method->mname_len == fnname_len && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(aliases[i]->alias, aliases[i]->alias_len) TSRMLS_CC); /* if it is 0, no modifieres has been changed */ if (aliases[i]->modifiers) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } lcname = zend_str_tolower_dup(aliases[i]->alias, aliases[i]->alias_len); if (zend_hash_add(target, lcname, aliases[i]->alias_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add aliased trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } efree(lcname); /** Record the trait from which this alias was resolved. */ if (!aliases[i]->trait_method->ce) { aliases[i]->trait_method->ce = fn->common.scope; } } i++; } } lcname = zend_str_tolower_dup(fn->common.function_name, fnname_len); if (exclude_table == NULL || zend_hash_find(exclude_table, lcname, fnname_len, &dummy) == FAILURE) { /* is not in hashtable, thus, function is not to be excluded */ fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(fn->common.function_name, fnname_len) TSRMLS_CC); /* apply aliases which are not qualified by a class name, or which have not * alias name, just setting visibility */ if (aliases) { i = 0; while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias == NULL && aliases[i]->modifiers != 0 && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && (aliases[i]->trait_method->mname_len == fnname_len) && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); /** Record the trait from which this alias was resolved. */ if (!aliases[i]->trait_method->ce) { aliases[i]->trait_method->ce = fn->common.scope; } } i++; } } if (zend_hash_add(target, lcname, fnname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } } efree(lcname); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* Copies function table entries to target function table with applied aliasing */ static void zend_traits_copy_trait_function_table(HashTable *target, zend_class_entry *target_ce, HashTable *source, zend_trait_alias** aliases, HashTable* exclude_table TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_arguments(source TSRMLS_CC, (apply_func_args_t)zend_traits_copy_functions, 4, target, target_ce, aliases, exclude_table); } /* }}} */ static void zend_traits_init_trait_structures(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i, j = 0; zend_trait_precedence *cur_precedence; zend_trait_method_reference *cur_method_ref; char *lcname; zend_bool method_exists; /* resolve class references */ if (ce->trait_precedences) { i = 0; while ((cur_precedence = ce->trait_precedences[i])) { /** Resolve classes for all precedence operations. */ if (cur_precedence->exclude_from_classes) { cur_method_ref = cur_precedence->trait_method; cur_precedence->trait_method->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); /** Ensure that the prefered method is actually available. */ lcname = zend_str_tolower_dup(cur_method_ref->method_name, cur_method_ref->mname_len); method_exists = zend_hash_exists(&cur_method_ref->ce->function_table, lcname, cur_method_ref->mname_len + 1); efree(lcname); if (!method_exists) { zend_error(E_COMPILE_ERROR, "A precedence rule was defined for %s::%s but this method does not exist", cur_method_ref->ce->name, cur_method_ref->method_name); } /** With the other traits, we are more permissive. We do not give errors for those. This allows to be more defensive in such definitions. */ j = 0; while (cur_precedence->exclude_from_classes[j]) { char* class_name = (char*)cur_precedence->exclude_from_classes[j]; zend_uint name_length = strlen(class_name); cur_precedence->exclude_from_classes[j] = zend_fetch_class(class_name, name_length, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); efree(class_name); j++; } } i++; } } if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { /** For all aliases with an explicit class name, resolve the class now. */ if (ce->trait_aliases[i]->trait_method->class_name) { cur_method_ref = ce->trait_aliases[i]->trait_method; cur_method_ref->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); /** And, ensure that the referenced method is resolvable, too. */ lcname = zend_str_tolower_dup(cur_method_ref->method_name, cur_method_ref->mname_len); method_exists = zend_hash_exists(&cur_method_ref->ce->function_table, lcname, cur_method_ref->mname_len + 1); efree(lcname); if (!method_exists) { zend_error(E_COMPILE_ERROR, "An alias was defined for %s::%s but this method does not exist", cur_method_ref->ce->name, cur_method_ref->method_name); } } i++; } } } /* }}} */ static void zend_traits_compile_exclude_table(HashTable* exclude_table, zend_trait_precedence **precedences, zend_class_entry *trait) /* {{{ */ { size_t i = 0, j; if (!precedences) { return; } while (precedences[i]) { if (precedences[i]->exclude_from_classes) { j = 0; while (precedences[i]->exclude_from_classes[j]) { if (precedences[i]->exclude_from_classes[j] == trait) { zend_uint lcname_len = precedences[i]->trait_method->mname_len; char *lcname = zend_str_tolower_dup(precedences[i]->trait_method->method_name, lcname_len); if (zend_hash_add(exclude_table, lcname, lcname_len, NULL, 0, NULL) == FAILURE) { efree(lcname); zend_error(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", precedences[i]->trait_method->method_name, trait->name); } efree(lcname); } ++j; } } ++i; } } /* }}} */ static void zend_do_traits_method_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { HashTable** function_tables; HashTable* resulting_table; HashTable exclude_table; size_t i; /* prepare copies of trait function tables for combination */ function_tables = malloc(sizeof(HashTable*) * ce->num_traits); resulting_table = (HashTable *) malloc(sizeof(HashTable)); /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(resulting_table, 10, NULL, NULL, 1, 0); for (i = 0; i < ce->num_traits; i++) { function_tables[i] = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(function_tables[i], ce->traits[i]->function_table.nNumOfElements, NULL, NULL, 1, 0); if (ce->trait_precedences) { /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(&exclude_table, 2, NULL, NULL, 0, 0); zend_traits_compile_exclude_table(&exclude_table, ce->trait_precedences, ce->traits[i]); /* copies functions, applies defined aliasing, and excludes unused trait methods */ zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, &exclude_table TSRMLS_CC); zend_hash_graceful_destroy(&exclude_table); } else { zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, NULL TSRMLS_CC); } } /* now merge trait methods */ for (i = 0; i < ce->num_traits; i++) { zend_hash_apply_with_arguments(function_tables[i] TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions, 5, i, ce->num_traits, resulting_table, function_tables, ce); } /* Now the resulting_table contains all trait methods we would have to * add to the class in the following step the methods are inserted into the method table * if there is already a method with the same name it is replaced iff ce != fn.scope * --> all inherited methods are overridden, methods defined in the class are left untouched */ zend_hash_apply_with_arguments(resulting_table TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions_to_class, 1, ce); /* free temporary function tables */ for (i = 0; i < ce->num_traits; i++) { /* zend_hash_destroy(function_tables[i]); */ zend_hash_graceful_destroy(function_tables[i]); free(function_tables[i]); } free(function_tables); /* free temporary resulting table */ /* zend_hash_destroy(resulting_table); */ zend_hash_graceful_destroy(resulting_table); free(resulting_table); } /* }}} */ static zend_class_entry* find_first_definition(zend_class_entry *ce, size_t current_trait, const char* prop_name, int prop_name_length, ulong prop_hash, zend_class_entry *coliding_ce) /* {{{ */ { size_t i; zend_property_info *coliding_prop; for (i = 0; (i < current_trait) && (i < ce->num_traits); i++) { if (zend_hash_quick_find(&ce->traits[i]->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS) { return ce->traits[i]; } } return coliding_ce; } /* }}} */ static void zend_do_traits_property_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i; zend_property_info *property_info; zend_property_info *coliding_prop; zval compare_result; const char* prop_name; int prop_name_length; ulong prop_hash; const char* class_name_unused; zend_bool prop_found; zend_bool not_compatible; zval* prop_value; /* In the following steps the properties are inserted into the property table * for that, a very strict approach is applied: * - check for compatibility, if not compatible with any property in class -> fatal * - if compatible, then strict notice */ for (i = 0; i < ce->num_traits; i++) { for (zend_hash_internal_pointer_reset(&ce->traits[i]->properties_info); zend_hash_get_current_data(&ce->traits[i]->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->traits[i]->properties_info)) { /* first get the unmangeld name if necessary, * then check whether the property is already there */ if ((property_info->flags & ZEND_ACC_PPP_MASK) == ZEND_ACC_PUBLIC) { prop_hash = property_info->h; prop_name = property_info->name; prop_name_length = property_info->name_length; prop_found = zend_hash_quick_find(&ce->properties_info, property_info->name, property_info->name_length+1, property_info->h, (void **) &coliding_prop) == SUCCESS; } else { /* for private and protected we need to unmangle the names */ zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name_unused, &prop_name); prop_name_length = strlen(prop_name); prop_hash = zend_get_hash_value(prop_name, prop_name_length + 1); prop_found = zend_hash_quick_find(&ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS; } /* next: check for conflicts with current class */ if (prop_found) { if (coliding_prop->flags & ZEND_ACC_SHADOW) { /* this one is inherited, lets look it up in its own class */ zend_hash_quick_find(&coliding_prop->ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop); } if ((coliding_prop->flags & ZEND_ACC_PPP_MASK) == (property_info->flags & ZEND_ACC_PPP_MASK)) { /* flags are identical, now the value needs to be checked */ if (property_info->flags & ZEND_ACC_STATIC) { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_static_members_table[coliding_prop->offset], ce->traits[i]->default_static_members_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } else { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_properties_table[coliding_prop->offset], ce->traits[i]->default_properties_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } } else { /* the flags are not identical, thus, we assume properties are not compatible */ not_compatible = 1; } if (not_compatible) { zend_error(E_COMPILE_ERROR, "%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } else { zend_error(E_STRICT, "%s and %s define the same property ($%s) in the composition of %s. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } } /* property not found, so lets add it */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); zend_declare_property_ex(ce, prop_name, prop_name_length, prop_value, property_info->flags, property_info->doc_comment, property_info->doc_comment_len TSRMLS_CC); } } } /* }}} */ static void zend_do_check_for_inconsistent_traits_aliasing(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { int i = 0; zend_trait_alias* cur_alias; char* lc_method_name; if (ce->trait_aliases) { while (ce->trait_aliases[i]) { cur_alias = ce->trait_aliases[i]; /** The trait for this alias has not been resolved, this means, this alias was not applied. Abort with an error. */ if (!cur_alias->trait_method->ce) { if (cur_alias->alias) { /** Plain old inconsistency/typo/bug */ zend_error(E_COMPILE_ERROR, "An alias (%s) was defined for method %s(), but this method does not exist", cur_alias->alias, cur_alias->trait_method->method_name); } else { /** Here are two possible cases: 1) this is an attempt to modifiy the visibility of a method introduce as part of another alias. Since that seems to violate the DRY principle, we check against it and abort. 2) it is just a plain old inconsitency/typo/bug as in the case where alias is set. */ lc_method_name = zend_str_tolower_dup(cur_alias->trait_method->method_name, cur_alias->trait_method->mname_len); if (zend_hash_exists(&ce->function_table, lc_method_name, cur_alias->trait_method->mname_len+1)) { efree(lc_method_name); zend_error(E_COMPILE_ERROR, "The modifiers for the trait alias %s() need to be changed in the same statment in which the alias is defined. Error", cur_alias->trait_method->method_name); } else { efree(lc_method_name); zend_error(E_COMPILE_ERROR, "The modifiers of the trait method %s() are changed, but this method does not exist. Error", cur_alias->trait_method->method_name); } } } i++; } } } /* }}} */ ZEND_API void zend_do_bind_traits(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { if (ce->num_traits <= 0) { return; } /* complete initialization of trait strutures in ce */ zend_traits_init_trait_structures(ce TSRMLS_CC); /* first care about all methods to be flattened into the class */ zend_do_traits_method_binding(ce TSRMLS_CC); /* Aliases which have not been applied indicate typos/bugs. */ zend_do_check_for_inconsistent_traits_aliasing(ce TSRMLS_CC); /* then flatten the properties into it, to, mostly to notfiy developer about problems */ zend_do_traits_property_binding(ce TSRMLS_CC); /* verify that all abstract methods from traits have been implemented */ zend_verify_abstract_class(ce TSRMLS_CC); /* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */ if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { ce->ce_flags -= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } } /* }}} */ ZEND_API int do_bind_function(const zend_op_array *op_array, zend_op *opline, HashTable *function_table, zend_bool compile_time) /* {{{ */ { zend_function *function; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } zend_hash_quick_find(function_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void *) &function); if (zend_hash_quick_add(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), function, sizeof(zend_function), NULL)==FAILURE) { int error_level = compile_time ? E_COMPILE_ERROR : E_ERROR; zend_function *old_function; if (zend_hash_quick_find(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), (void *) &old_function)==SUCCESS && old_function->type == ZEND_USER_FUNCTION && old_function->op_array.last > 0) { zend_error(error_level, "Cannot redeclare %s() (previously declared in %s:%d)", function->common.function_name, old_function->op_array.filename, old_function->op_array.opcodes[0].lineno); } else { zend_error(error_level, "Cannot redeclare %s()", function->common.function_name); } return FAILURE; } else { (*function->op_array.refcount)++; function->op_array.static_variables = NULL; /* NULL out the unbound function */ return SUCCESS; } } /* }}} */ void zend_add_trait_precedence(znode *precedence_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_precedences, precedence_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_add_trait_alias(znode *alias_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_aliases, alias_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_prepare_reference(znode *result, znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { zend_trait_method_reference *method_ref = emalloc(sizeof(zend_trait_method_reference)); method_ref->ce = NULL; /* REM: There should not be a need for copying, zend_do_begin_class_declaration is also just using that string */ if (class_name) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); method_ref->class_name = Z_STRVAL(class_name->u.constant); method_ref->cname_len = Z_STRLEN(class_name->u.constant); } else { method_ref->class_name = NULL; method_ref->cname_len = 0; } method_ref->method_name = Z_STRVAL(method_name->u.constant); method_ref->mname_len = Z_STRLEN(method_name->u.constant); result->u.op.ptr = method_ref; result->op_type = IS_TMP_VAR; } /* }}} */ void zend_prepare_trait_alias(znode *result, znode *method_reference, znode *modifiers, znode *alias TSRMLS_DC) /* {{{ */ { zend_trait_alias *trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_alias->modifiers = Z_LVAL(modifiers->u.constant); if (Z_LVAL(modifiers->u.constant) == ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot use 'static' as method modifier"); return; } if (alias) { trait_alias->alias = Z_STRVAL(alias->u.constant); trait_alias->alias_len = Z_STRLEN(alias->u.constant); } else { trait_alias->alias = NULL; } trait_alias->function = NULL; result->u.op.ptr = trait_alias; } /* }}} */ void zend_prepare_trait_precedence(znode *result, znode *method_reference, znode *trait_list TSRMLS_DC) /* {{{ */ { zend_trait_precedence *trait_precedence = emalloc(sizeof(zend_trait_precedence)); trait_precedence->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_precedence->exclude_from_classes = (zend_class_entry**) trait_list->u.op.ptr; trait_precedence->function = NULL; result->u.op.ptr = trait_precedence; } /* }}} */ ZEND_API zend_class_entry *do_bind_class(const zend_op_array* op_array, const zend_op *opline, HashTable *class_table, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } if (zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce)==FAILURE) { zend_error(E_COMPILE_ERROR, "Internal Zend error - Missing class information for %s", Z_STRVAL_P(op1)); return NULL; } else { ce = *pce; } ce->refcount++; if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), &ce, sizeof(zend_class_entry *), NULL)==FAILURE) { ce->refcount--; if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return NULL; } else { if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLEMENT_INTERFACES))) { zend_verify_abstract_class(ce TSRMLS_CC); } return ce; } } /* }}} */ ZEND_API zend_class_entry *do_bind_inherited_class(const zend_op_array *op_array, const zend_op *opline, HashTable *class_table, zend_class_entry *parent_ce, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; int found_ce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } found_ce = zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce); if (found_ce == FAILURE) { if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", Z_STRVAL_P(op2)); } return NULL; } else { ce = *pce; } if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ce->name, parent_ce->name); } else if ((parent_ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ce->name, parent_ce->name); } zend_do_inheritance(ce, parent_ce TSRMLS_CC); ce->refcount++; /* Register the derived class */ if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), pce, sizeof(zend_class_entry *), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return ce; } /* }}} */ void zend_do_early_binding(TSRMLS_D) /* {{{ */ { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; HashTable *table; while (opline->opcode == ZEND_TICKS && opline > CG(active_op_array)->opcodes) { opline--; } switch (opline->opcode) { case ZEND_DECLARE_FUNCTION: if (do_bind_function(CG(active_op_array), opline, CG(function_table), 1) == FAILURE) { return; } table = CG(function_table); break; case ZEND_DECLARE_CLASS: if (do_bind_class(CG(active_op_array), opline, CG(class_table), 1 TSRMLS_CC) == NULL) { return; } table = CG(class_table); break; case ZEND_DECLARE_INHERITED_CLASS: { zend_op *fetch_class_opline = opline-1; zval *parent_name; zend_class_entry **pce; parent_name = &CONSTANT(fetch_class_opline->op2.constant); if ((zend_lookup_class(Z_STRVAL_P(parent_name), Z_STRLEN_P(parent_name), &pce TSRMLS_CC) == FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_CLASSES) && ((*pce)->type == ZEND_INTERNAL_CLASS))) { if (CG(compiler_options) & ZEND_COMPILE_DELAYED_BINDING) { zend_uint *opline_num = &CG(active_op_array)->early_binding; while (*opline_num != -1) { opline_num = &CG(active_op_array)->opcodes[*opline_num].result.opline_num; } *opline_num = opline - CG(active_op_array)->opcodes; opline->opcode = ZEND_DECLARE_INHERITED_CLASS_DELAYED; opline->result_type = IS_UNUSED; opline->result.opline_num = -1; } return; } if (do_bind_inherited_class(CG(active_op_array), opline, CG(class_table), *pce, 1 TSRMLS_CC) == NULL) { return; } /* clear unnecessary ZEND_FETCH_CLASS opcode */ zend_del_literal(CG(active_op_array), fetch_class_opline->op2.constant); MAKE_NOP(fetch_class_opline); table = CG(class_table); break; } case ZEND_VERIFY_ABSTRACT_CLASS: case ZEND_ADD_INTERFACE: case ZEND_ADD_TRAIT: case ZEND_BIND_TRAITS: /* We currently don't early-bind classes that implement interfaces */ /* Classes with traits are handled exactly the same, no early-bind here */ return; default: zend_error(E_COMPILE_ERROR, "Invalid binding type"); return; } zend_hash_quick_del(table, Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant)), Z_HASH_P(&CONSTANT(opline->op1.constant))); zend_del_literal(CG(active_op_array), opline->op1.constant); zend_del_literal(CG(active_op_array), opline->op2.constant); MAKE_NOP(opline); } /* }}} */ ZEND_API void zend_do_delayed_early_binding(const zend_op_array *op_array TSRMLS_DC) /* {{{ */ { if (op_array->early_binding != -1) { zend_bool orig_in_compilation = CG(in_compilation); zend_uint opline_num = op_array->early_binding; zend_class_entry **pce; CG(in_compilation) = 1; while (opline_num != -1) { if (zend_lookup_class(Z_STRVAL_P(op_array->opcodes[opline_num-1].op2.zv), Z_STRLEN_P(op_array->opcodes[opline_num-1].op2.zv), &pce TSRMLS_CC) == SUCCESS) { do_bind_inherited_class(op_array, &op_array->opcodes[opline_num], EG(class_table), *pce, 0 TSRMLS_CC); } opline_num = op_array->opcodes[opline_num].result.opline_num; } CG(in_compilation) = orig_in_compilation; } } /* }}} */ void zend_do_boolean_or_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_or_end(znode *result, const znode *expr1, const znode *expr2, znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_boolean_and_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_and_end(znode *result, const znode *expr1, const znode *expr2, const znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_do_while_begin(TSRMLS_D) /* {{{ */ { do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_do_while_end(const znode *do_token, const znode *expr_open_bracket, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ; SET_NODE(opline->op1, expr); opline->op2.opline_num = do_token->u.op.opline_num; SET_UNUSED(opline->op2); do_end_loop(expr_open_bracket->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_brk_cont(zend_uchar op, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->op1.opline_num = CG(context).current_brk_cont; SET_UNUSED(opline->op1); if (expr) { if (expr->op_type != IS_CONST) { zend_error(E_COMPILE_ERROR, "'%s' operator with non-constant operand is no longer supported", op == ZEND_BRK ? "break" : "continue"); } else if (Z_TYPE(expr->u.constant) != IS_LONG || Z_LVAL(expr->u.constant) < 1) { zend_error(E_COMPILE_ERROR, "'%s' operator accepts only positive numbers", op == ZEND_BRK ? "break" : "continue"); } SET_NODE(opline->op2, expr); } else { LITERAL_LONG(opline->op2, 1); opline->op2_type = IS_CONST; } } /* }}} */ void zend_do_switch_cond(const znode *cond TSRMLS_DC) /* {{{ */ { zend_switch_entry switch_entry; switch_entry.cond = *cond; switch_entry.default_case = -1; switch_entry.control_var = -1; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_switch_end(const znode *case_list TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); /* add code to jmp to default case */ if (switch_entry_ptr->default_case != -1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->op1.opline_num = switch_entry_ptr->default_case; } if (case_list->op_type != IS_UNUSED) { /* non-empty switch */ int next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* remember break/continue loop information */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; if (switch_entry_ptr->cond.op_type==IS_VAR || switch_entry_ptr->cond.op_type==IS_TMP_VAR) { /* emit free for the switch condition*/ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry_ptr->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_UNUSED(opline->op2); } if (switch_entry_ptr->cond.op_type == IS_CONST) { zval_dtor(&switch_entry_ptr->cond.u.constant); } zend_stack_del_top(&CG(switch_cond_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_case_before_statement(const znode *case_list, znode *case_token, const znode *case_expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); int next_op_number; zend_switch_entry *switch_entry_ptr; znode result; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); if (switch_entry_ptr->control_var == -1) { switch_entry_ptr->control_var = get_temporary_variable(CG(active_op_array)); } opline->opcode = ZEND_CASE; opline->result.var = switch_entry_ptr->control_var; opline->result_type = IS_TMP_VAR; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_NODE(opline->op2, case_expr); if (opline->op1_type == IS_CONST) { zval_copy_ctor(&CONSTANT(opline->op1.constant)); } GET_NODE(&result, opline->result); next_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, &result); SET_UNUSED(opline->op2); case_token->u.op.opline_num = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_case_after_statement(znode *result, const znode *case_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); result->u.op.opline_num = next_op_number; switch (CG(active_op_array)->opcodes[case_token->u.op.opline_num].opcode) { case ZEND_JMP: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); break; case ZEND_JMPZ: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); break; } } /* }}} */ void zend_do_default_before_statement(const znode *case_list, znode *default_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); default_token->u.op.opline_num = next_op_number; next_op_number = get_next_op_number(CG(active_op_array)); switch_entry_ptr->default_case = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_begin_class_declaration(const znode *class_token, znode *class_name, const znode *parent_class_name TSRMLS_DC) /* {{{ */ { zend_op *opline; int doing_inheritance = 0; zend_class_entry *new_class_entry; char *lcname; int error = 0; zval **ns_name, key; if (CG(active_class_entry)) { zend_error(E_COMPILE_ERROR, "Class declarations may not be nested"); return; } lcname = zend_str_tolower_dup(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); if (!(strcmp(lcname, "self") && strcmp(lcname, "parent"))) { efree(lcname); zend_error(E_COMPILE_ERROR, "Cannot use '%s' as class name as it is reserved", Z_STRVAL(class_name->u.constant)); } /* Class name must not conflict with import names */ if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns_name) == SUCCESS) { error = 1; } if (CG(current_namespace)) { /* Prefix class name with name of current namespace */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); class_name = &tmp; efree(lcname); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); } if (error) { char *tmp = zend_str_tolower_dup(Z_STRVAL_PP(ns_name), Z_STRLEN_PP(ns_name)); if (Z_STRLEN_PP(ns_name) != Z_STRLEN(class_name->u.constant) || memcmp(tmp, lcname, Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "Cannot declare class %s because the name is already in use", Z_STRVAL(class_name->u.constant)); } efree(tmp); } new_class_entry = emalloc(sizeof(zend_class_entry)); new_class_entry->type = ZEND_USER_CLASS; new_class_entry->name = zend_new_interned_string(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1, 1 TSRMLS_CC); new_class_entry->name_length = Z_STRLEN(class_name->u.constant); zend_initialize_class_data(new_class_entry, 1 TSRMLS_CC); new_class_entry->info.user.filename = zend_get_compiled_filename(TSRMLS_C); new_class_entry->info.user.line_start = class_token->u.op.opline_num; new_class_entry->ce_flags |= class_token->EA; if (parent_class_name && parent_class_name->op_type != IS_UNUSED) { switch (parent_class_name->EA) { case ZEND_FETCH_CLASS_SELF: zend_error(E_COMPILE_ERROR, "Cannot use 'self' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_PARENT: zend_error(E_COMPILE_ERROR, "Cannot use 'parent' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use 'static' as class name as it is reserved"); break; default: break; } doing_inheritance = 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, new_class_entry->name_length TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; if (doing_inheritance) { /* Make sure a trait does not try to extend a class */ if ((new_class_entry->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "A trait (%s) cannot extend a class", new_class_entry->name); } opline->extended_value = parent_class_name->u.op.var; opline->opcode = ZEND_DECLARE_INHERITED_CLASS; } else { opline->opcode = ZEND_DECLARE_CLASS; } LITERAL_STRINGL(opline->op2, lcname, new_class_entry->name_length, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); zend_hash_quick_update(CG(class_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &new_class_entry, sizeof(zend_class_entry *), NULL); CG(active_class_entry) = new_class_entry; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(&CG(implementing_class), opline->result); if (CG(doc_comment)) { CG(active_class_entry)->info.user.doc_comment = CG(doc_comment); CG(active_class_entry)->info.user.doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ static void do_verify_abstract_class(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_VERIFY_ABSTRACT_CLASS; SET_NODE(opline->op1, &CG(implementing_class)); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_class_declaration(const znode *class_token, const znode *parent_token TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); if (ce->constructor) { ce->constructor->common.fn_flags |= ZEND_ACC_CTOR; if (ce->constructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Constructor %s::%s() cannot be static", ce->name, ce->constructor->common.function_name); } } if (ce->destructor) { ce->destructor->common.fn_flags |= ZEND_ACC_DTOR; if (ce->destructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Destructor %s::%s() cannot be static", ce->name, ce->destructor->common.function_name); } } if (ce->clone) { ce->clone->common.fn_flags |= ZEND_ACC_CLONE; if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static", ce->name, ce->clone->common.function_name); } } ce->info.user.line_end = zend_get_compiled_lineno(TSRMLS_C); /* Check for traits and proceed like with interfaces. * The only difference will be a combined handling of them in the end. * Thus, we need another opcode here. */ if (ce->num_traits > 0) { zend_op *opline; ce->traits = NULL; ce->num_traits = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_TRAITS; /* opcode generation: */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BIND_TRAITS; SET_NODE(opline->op1, &CG(implementing_class)); } if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) && ((parent_token->op_type != IS_UNUSED) || (ce->num_interfaces > 0))) { zend_verify_abstract_class(ce TSRMLS_CC); if (ce->num_interfaces) { do_verify_abstract_class(TSRMLS_C); } } /* Inherit interfaces; reset number to zero, we need it for above check and * will restore it during actual implementation. * The ZEND_ACC_IMPLEMENT_INTERFACES flag disables double call to * zend_verify_abstract_class() */ if (ce->num_interfaces > 0) { ce->interfaces = NULL; ce->num_interfaces = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_INTERFACES; } CG(active_class_entry) = NULL; } /* }}} */ void zend_do_implements_interface(znode *interface_name TSRMLS_DC) /* {{{ */ { zend_op *opline; /* Traits can not implement interfaces */ if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface on '%s' since it is a Trait", Z_STRVAL(interface_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(interface_name->u.constant), Z_STRLEN(interface_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface name as it is reserved", Z_STRVAL(interface_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_INTERFACE; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(interface_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = (opline->extended_value & ~ZEND_FETCH_CLASS_MASK) | ZEND_FETCH_CLASS_INTERFACE; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &interface_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_interfaces++; } /* }}} */ void zend_do_implements_trait(znode *trait_name TSRMLS_DC) /* {{{ */ { zend_op *opline; if ((CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Cannot use traits inside of interfaces. %s is used in %s", Z_STRVAL(trait_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(trait_name->u.constant), Z_STRLEN(trait_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as trait name as it is reserved", Z_STRVAL(trait_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_TRAIT; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(trait_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = ZEND_FETCH_CLASS_TRAIT; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &trait_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_traits++; } /* }}} */ ZEND_API void zend_mangle_property_name(char **dest, int *dest_length, const char *src1, int src1_length, const char *src2, int src2_length, int internal) /* {{{ */ { char *prop_name; int prop_name_length; prop_name_length = 1 + src1_length + 1 + src2_length; prop_name = pemalloc(prop_name_length + 1, internal); prop_name[0] = '\0'; memcpy(prop_name + 1, src1, src1_length+1); memcpy(prop_name + 1 + src1_length + 1, src2, src2_length+1); *dest = prop_name; *dest_length = prop_name_length; } /* }}} */ static int zend_strnlen(const char* s, int maxlen) /* {{{ */ { int len = 0; while (*s++ && maxlen--) len++; return len; } /* }}} */ ZEND_API int zend_unmangle_property_name(const char *mangled_property, int len, const char **class_name, const char **prop_name) /* {{{ */ { int class_name_len; *class_name = NULL; if (mangled_property[0]!=0) { *prop_name = mangled_property; return SUCCESS; } if (len < 3 || mangled_property[1]==0) { zend_error(E_NOTICE, "Illegal member variable name"); *prop_name = mangled_property; return FAILURE; } class_name_len = zend_strnlen(mangled_property+1, --len - 1) + 1; if (class_name_len >= len || mangled_property[class_name_len]!=0) { zend_error(E_NOTICE, "Corrupt member variable name"); *prop_name = mangled_property; return FAILURE; } *class_name = mangled_property+1; *prop_name = (*class_name)+class_name_len; return SUCCESS; } /* }}} */ void zend_do_declare_property(const znode *var_name, const znode *value, zend_uint access_type TSRMLS_DC) /* {{{ */ { zval *property; zend_property_info *existing_property_info; char *comment = NULL; int comment_len = 0; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Interfaces may not include member variables"); } if (access_type & ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Properties cannot be declared abstract"); } if (access_type & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot declare property %s::$%s final, the final modifier is allowed only for methods and classes", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } if (zend_hash_find(&CG(active_class_entry)->properties_info, var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, (void **) &existing_property_info)==SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::$%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } ALLOC_ZVAL(property); if (value) { *property = value->u.constant; } else { INIT_PZVAL(property); Z_TYPE_P(property) = IS_NULL; } if (CG(doc_comment)) { comment = CG(doc_comment); comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } zend_declare_property_ex(CG(active_class_entry), zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len + 1, 0 TSRMLS_CC), var_name->u.constant.value.str.len, property, access_type, comment, comment_len TSRMLS_CC); efree(var_name->u.constant.value.str.val); } /* }}} */ void zend_do_declare_class_constant(znode *var_name, const znode *value TSRMLS_DC) /* {{{ */ { zval *property; const char *cname = NULL; int result; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed in class constants"); return; } if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Traits cannot have constants"); return; } ALLOC_ZVAL(property); *property = value->u.constant; cname = zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, 0 TSRMLS_CC); if (IS_INTERNED(cname)) { result = zend_hash_quick_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, INTERNED_HASH(cname), &property, sizeof(zval *), NULL); } else { result = zend_hash_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, &property, sizeof(zval *), NULL); } if (result == FAILURE) { FREE_ZVAL(property); zend_error(E_COMPILE_ERROR, "Cannot redefine class constant %s::%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } FREE_PNODE(var_name); if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_fetch_property(znode *result, znode *object, const znode *property TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (object->op_type == IS_CV) { if (object->u.op.var == CG(active_op_array)->this_var) { object->op_type = IS_UNUSED; /* this means $this for objects */ } } else if (fetch_list_ptr->count == 1) { zend_llist_element *le = fetch_list_ptr->head; zend_op *opline_ptr = (zend_op *) le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); SET_UNUSED(opline_ptr->op1); /* this means $this for objects */ SET_NODE(opline_ptr->op2, property); /* if it was usual fetch, we change it to object fetch */ switch (opline_ptr->opcode) { case ZEND_FETCH_W: opline_ptr->opcode = ZEND_FETCH_OBJ_W; break; case ZEND_FETCH_R: opline_ptr->opcode = ZEND_FETCH_OBJ_R; break; case ZEND_FETCH_RW: opline_ptr->opcode = ZEND_FETCH_OBJ_RW; break; case ZEND_FETCH_IS: opline_ptr->opcode = ZEND_FETCH_OBJ_IS; break; case ZEND_FETCH_UNSET: opline_ptr->opcode = ZEND_FETCH_OBJ_UNSET; break; case ZEND_FETCH_FUNC_ARG: opline_ptr->opcode = ZEND_FETCH_OBJ_FUNC_ARG; break; } if (opline_ptr->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline_ptr->op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline_ptr->op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op2.constant); } GET_NODE(result, opline_ptr->result); return; } } if (zend_is_function_or_method_call(object)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, object); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_OBJ_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, object); SET_NODE(opline.op2, property); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline.op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op2.constant); } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void zend_do_halt_compiler_register(TSRMLS_D) /* {{{ */ { char *name, *cfilename; char haltoff[] = "__COMPILER_HALT_OFFSET__"; int len, clen; if (CG(has_bracketed_namespaces) && CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "__HALT_COMPILER() can only be used from the outermost scope"); } cfilename = zend_get_compiled_filename(TSRMLS_C); clen = strlen(cfilename); zend_mangle_property_name(&name, &len, haltoff, sizeof(haltoff) - 1, cfilename, clen, 0); zend_register_long_constant(name, len+1, zend_get_scanned_file_offset(TSRMLS_C), CONST_CS, 0 TSRMLS_CC); pefree(name, 0); if (CG(in_namespace)) { zend_do_end_namespace(TSRMLS_C); } } /* }}} */ void zend_do_push_object(const znode *object TSRMLS_DC) /* {{{ */ { zend_stack_push(&CG(object_stack), object, sizeof(znode)); } /* }}} */ void zend_do_pop_object(znode *object TSRMLS_DC) /* {{{ */ { if (object) { znode *tmp; zend_stack_top(&CG(object_stack), (void **) &tmp); *object = *tmp; } zend_stack_del_top(&CG(object_stack)); } /* }}} */ void zend_do_begin_new_object(znode *new_token, znode *class_type TSRMLS_DC) /* {{{ */ { zend_op *opline; unsigned char *ptr = NULL; new_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_NEW; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, class_type); SET_UNUSED(opline->op2); zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(unsigned char *)); } /* }}} */ void zend_do_end_new_object(znode *result, const znode *new_token, const znode *argument_list TSRMLS_DC) /* {{{ */ { znode ctor_result; zend_do_end_function_call(NULL, &ctor_result, argument_list, 1, 0 TSRMLS_CC); zend_do_free(&ctor_result TSRMLS_CC); CG(active_op_array)->opcodes[new_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, CG(active_op_array)->opcodes[new_token->u.op.opline_num].result); } /* }}} */ static zend_constant* zend_get_ct_const(const zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = NULL; if (Z_STRVAL_P(const_name)[0] == '\\') { if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name), (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name)-1); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name), (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } } else if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)+1, (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name)+1, (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } if (c->flags & CONST_CT_SUBST) { return c; } if (all_internal_constants_substitution && (c->flags & CONST_PERSISTENT) && !(CG(compiler_options) & ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION) && Z_TYPE(c->value) != IS_CONSTANT && Z_TYPE(c->value) != IS_CONSTANT_ARRAY) { return c; } return NULL; } /* }}} */ static int zend_constant_ct_subst(znode *result, zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = zend_get_ct_const(const_name, all_internal_constants_substitution TSRMLS_CC); if (c) { zval_dtor(const_name); result->op_type = IS_CONST; result->u.constant = c->value; zval_copy_ctor(&result->u.constant); INIT_PZVAL(&result->u.constant); return 1; } return 0; } /* }}} */ void zend_do_fetch_constant(znode *result, znode *constant_container, znode *constant_name, int mode, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; zend_op *opline; int type; char *compound; ulong fetch_type = 0; if (constant_container) { switch (mode) { case ZEND_CT: /* this is a class constant */ type = zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant)); if (ZEND_FETCH_CLASS_STATIC == type) { zend_error(E_ERROR, "\"static::\" is not allowed in compile-time constants"); } else if (ZEND_FETCH_CLASS_DEFAULT == type) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } zend_do_build_full_name(NULL, constant_container, constant_name, 1 TSRMLS_CC); *result = *constant_container; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: if (constant_container->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant))) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } else { zend_do_fetch_class(&tmp, constant_container TSRMLS_CC); constant_container = &tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); if (constant_container->op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &constant_container->u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, constant_container); } SET_NODE(opline->op2, constant_name); CALCULATE_LITERAL_HASH(opline->op2.constant); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } GET_NODE(result, opline->result); break; } return; } /* namespace constant */ /* only one that did not contain \ from the start can be converted to string if unknown */ switch (mode) { case ZEND_CT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); /* this is a namespace constant, or an unprefixed constant */ if (zend_constant_ct_subst(result, &constant_name->u.constant, 0 TSRMLS_CC)) { break; } zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(!compound) { fetch_type |= IS_CONSTANT_UNQUALIFIED; } *result = *constant_name; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(zend_constant_ct_subst(result, &constant_name->u.constant, 1 TSRMLS_CC)) { break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; if (compound) { /* the name is unambiguous */ opline->extended_value = 0; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } else { opline->extended_value = IS_CONSTANT_UNQUALIFIED; if (CG(current_namespace)) { opline->extended_value |= IS_CONSTANT_IN_NAMESPACE; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 1 TSRMLS_CC); } else { opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } } GET_CACHE_SLOT(opline->op2.constant); break; } } /* }}} */ void zend_do_shell_exec(znode *result, const znode *cmd TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); switch (cmd->op_type) { case IS_CONST: case IS_TMP_VAR: opline->opcode = ZEND_SEND_VAL; break; default: opline->opcode = ZEND_SEND_VAR; break; } SET_NODE(opline->op1, cmd); opline->op2.opline_num = 0; opline->extended_value = ZEND_DO_FCALL; SET_UNUSED(opline->op2); /* FIXME: exception support not added to this op2 */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DO_FCALL; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; LITERAL_STRINGL(opline->op1, estrndup("shell_exec", sizeof("shell_exec")-1), sizeof("shell_exec")-1, 0); CALCULATE_LITERAL_HASH(opline->op1.constant); opline->op1_type = IS_CONST; GET_CACHE_SLOT(opline->op1.constant); opline->extended_value = 1; SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_init_array(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_ARRAY; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; GET_NODE(result, opline->result); if (expr) { SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } } else { SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_array_element(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_ARRAY_ELEMENT; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_static_array_element(znode *result, znode *offset, const znode *expr) /* {{{ */ { zval *element; ALLOC_ZVAL(element); *element = expr->u.constant; if (offset) { switch (offset->u.constant.type & IS_CONSTANT_TYPE_MASK) { case IS_CONSTANT: /* Ugly hack to denote that this value has a constant index */ Z_TYPE_P(element) |= IS_CONSTANT_INDEX; Z_STRVAL(offset->u.constant) = erealloc(Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+1] = Z_TYPE(offset->u.constant); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+2] = 0; zend_symtable_update(result->u.constant.value.ht, Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_STRING: zend_symtable_update(result->u.constant.value.ht, offset->u.constant.value.str.val, offset->u.constant.value.str.len+1, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_NULL: zend_symtable_update(Z_ARRVAL(result->u.constant), "", 1, &element, sizeof(zval *), NULL); break; case IS_LONG: case IS_BOOL: zend_hash_index_update(Z_ARRVAL(result->u.constant), Z_LVAL(offset->u.constant), &element, sizeof(zval *), NULL); break; case IS_DOUBLE: zend_hash_index_update(Z_ARRVAL(result->u.constant), zend_dval_to_lval(Z_DVAL(offset->u.constant)), &element, sizeof(zval *), NULL); break; case IS_CONSTANT_ARRAY: zend_error(E_ERROR, "Illegal offset type"); break; } } else { zend_hash_next_index_insert(Z_ARRVAL(result->u.constant), &element, sizeof(zval *), NULL); } } /* }}} */ void zend_do_add_list_element(const znode *element TSRMLS_DC) /* {{{ */ { list_llist_element lle; if (element) { zend_check_writable_variable(element); lle.var = *element; zend_llist_copy(&lle.dimensions, &CG(dimension_llist)); zend_llist_prepend_element(&CG(list_llist), &lle); } (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_new_list_begin(TSRMLS_D) /* {{{ */ { int current_dimension = 0; zend_llist_add_element(&CG(dimension_llist), &current_dimension); } /* }}} */ void zend_do_new_list_end(TSRMLS_D) /* {{{ */ { zend_llist_remove_tail(&CG(dimension_llist)); (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_list_init(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(list_stack), &CG(list_llist), sizeof(zend_llist)); zend_stack_push(&CG(list_stack), &CG(dimension_llist), sizeof(zend_llist)); zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_do_new_list_begin(TSRMLS_C); } /* }}} */ void zend_do_list_end(znode *result, znode *expr TSRMLS_DC) /* {{{ */ { zend_llist_element *le; zend_llist_element *dimension; zend_op *opline; znode last_container; le = CG(list_llist).head; while (le) { zend_llist *tmp_dimension_llist = &((list_llist_element *)le->data)->dimensions; dimension = tmp_dimension_llist->head; while (dimension) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (dimension == tmp_dimension_llist->head) { /* first */ last_container = *expr; switch (expr->op_type) { case IS_VAR: case IS_CV: opline->opcode = ZEND_FETCH_DIM_R; break; case IS_TMP_VAR: opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; case IS_CONST: /* fetch_dim_tmp_var will handle this bogus fetch */ zval_copy_ctor(&expr->u.constant); opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; } opline->extended_value |= ZEND_FETCH_ADD_LOCK; } else { opline->opcode = ZEND_FETCH_DIM_R; } opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, &last_container); opline->op2_type = IS_CONST; LITERAL_LONG(opline->op2, *((int *) dimension->data)); GET_NODE(&last_container, opline->result); dimension = dimension->next; } ((list_llist_element *) le->data)->value = last_container; zend_llist_destroy(&((list_llist_element *) le->data)->dimensions); zend_do_assign(result, &((list_llist_element *) le->data)->var, &((list_llist_element *) le->data)->value TSRMLS_CC); zend_do_free(result TSRMLS_CC); le = le->next; } zend_llist_destroy(&CG(dimension_llist)); zend_llist_destroy(&CG(list_llist)); *result = *expr; { zend_llist *p; /* restore previous lists */ zend_stack_top(&CG(list_stack), (void **) &p); CG(dimension_llist) = *p; zend_stack_del_top(&CG(list_stack)); zend_stack_top(&CG(list_stack), (void **) &p); CG(list_llist) = *p; zend_stack_del_top(&CG(list_stack)); } } /* }}} */ void zend_init_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = emalloc(sizeof(void*) * 2); list[0] = item; list[1] = NULL; *(void**)result = list; } /* }}} */ void zend_add_to_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = *(void**)result; size_t n = 0; while (list && list[n]) { n++; } list = erealloc(list, sizeof(void*) * (n+2)); list[n] = item; list[n+1] = NULL; *(void**)result = list; } /* }}} */ void zend_do_fetch_static_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zval *tmp; zend_op *opline; znode lval; znode result; ALLOC_ZVAL(tmp); if (static_assignment) { *tmp = static_assignment->u.constant; } else { INIT_ZVAL(*tmp); } if (!CG(active_op_array)->static_variables) { if (CG(active_op_array)->scope) { CG(active_op_array)->scope->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } ALLOC_HASHTABLE(CG(active_op_array)->static_variables); zend_hash_init(CG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } zend_hash_update(CG(active_op_array)->static_variables, varname->u.constant.value.str.val, varname->u.constant.value.str.len+1, &tmp, sizeof(zval *), NULL); if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (fetch_type == ZEND_FETCH_LEXICAL) ? ZEND_FETCH_R : ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_STATIC; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ if (fetch_type == ZEND_FETCH_LEXICAL) { znode dummy; zend_do_begin_variable_parse(TSRMLS_C); zend_do_assign(&dummy, &lval, &result TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } else { zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); } CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_fetch_lexical_variable(znode *varname, zend_bool is_ref TSRMLS_DC) /* {{{ */ { znode value; if (Z_STRLEN(varname->u.constant) == sizeof("this") - 1 && memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this") - 1) == 0) { zend_error(E_COMPILE_ERROR, "Cannot use $this as lexical variable"); return; } value.op_type = IS_CONST; ZVAL_NULL(&value.u.constant); Z_TYPE(value.u.constant) |= is_ref ? IS_LEXICAL_REF : IS_LEXICAL_VAR; Z_SET_REFCOUNT_P(&value.u.constant, 1); Z_UNSET_ISREF_P(&value.u.constant); zend_do_fetch_static_variable(varname, &value, is_ref ? ZEND_FETCH_STATIC : ZEND_FETCH_LEXICAL TSRMLS_CC); } /* }}} */ void zend_do_fetch_global_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zend_op *opline; znode lval; znode result; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = fetch_type; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_cast(znode *result, const znode *expr, int type TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CAST; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } /* }}} */ void zend_do_include_or_eval(int type, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_do_extended_fcall_begin(TSRMLS_C); { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INCLUDE_OR_EVAL; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } zend_do_extended_fcall_end(TSRMLS_C); } /* }}} */ void zend_do_indirect_references(znode *result, const znode *num_references, znode *variable TSRMLS_DC) /* {{{ */ { int i; zend_do_end_variable_parse(variable, BP_VAR_R, 0 TSRMLS_CC); for (i=1; i<num_references->u.constant.value.lval; i++) { fetch_simple_variable_ex(result, variable, 0, ZEND_FETCH_R TSRMLS_CC); *variable = *result; } zend_do_begin_variable_parse(TSRMLS_C); fetch_simple_variable(result, variable, 1 TSRMLS_CC); /* there is a chance someone is accessing $this */ if (CG(active_op_array)->scope && CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } /* }}} */ void zend_do_unset(const znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_UNSET_VAR; SET_NODE(opline->op1, variable); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); opline->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_UNSET: last_op->opcode = ZEND_UNSET_VAR; SET_UNUSED(last_op->result); break; case ZEND_FETCH_DIM_UNSET: last_op->opcode = ZEND_UNSET_DIM; SET_UNUSED(last_op->result); break; case ZEND_FETCH_OBJ_UNSET: last_op->opcode = ZEND_UNSET_OBJ; SET_UNUSED(last_op->result); break; } } } /* }}} */ void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_do_end_variable_parse(variable, BP_VAR_IS, 0 TSRMLS_CC); zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { last_op = get_next_op(CG(active_op_array) TSRMLS_CC); last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; SET_NODE(last_op->op1, variable); SET_UNUSED(last_op->op2); last_op->result.var = get_temporary_variable(CG(active_op_array)); last_op->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; break; case ZEND_FETCH_DIM_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_DIM_OBJ; break; case ZEND_FETCH_OBJ_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_PROP_OBJ; break; } } last_op->result_type = IS_TMP_VAR; last_op->extended_value |= type; GET_NODE(result, last_op->result); } /* }}} */ void zend_do_instanceof(znode *result, const znode *expr, const znode *class_znode, int type TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline->opcode == ZEND_FETCH_CLASS) { opline->extended_value |= ZEND_FETCH_CLASS_NO_AUTOLOAD; } } if (expr->op_type == IS_CONST) { zend_error(E_COMPILE_ERROR, "instanceof expects an object instance, constant given"); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INSTANCEOF; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_NODE(opline->op2, class_znode); GET_NODE(result, opline->result); } /* }}} */ void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_bool is_variable; zend_bool push_container = 0; zend_op dummy_opline; if (variable) { if (zend_is_function_or_method_call(array)) { is_variable = 0; } else { is_variable = 1; } /* save the location of FETCH_W instruction(s) */ open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); zend_do_end_variable_parse(array, BP_VAR_W, 0 TSRMLS_CC); if (CG(active_op_array)->last > 0 && CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) { /* Only lock the container if we are fetching from a real container and not $this */ if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1_type == IS_VAR) { CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK; push_container = 1; } } } else { is_variable = 0; open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* save the location of FE_RESET */ foreach_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* Preform array reset */ opline->opcode = ZEND_FE_RESET; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, array); SET_UNUSED(opline->op2); opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0; COPY_NODE(dummy_opline.result, opline->result); if (push_container) { COPY_NODE(dummy_opline.op1, CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1); } else { dummy_opline.op1_type = IS_UNUSED; } zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); /* save the location of FE_FETCH */ as_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FE_FETCH; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); COPY_NODE(opline->op1, dummy_opline.result); opline->extended_value = 0; SET_UNUSED(opline->op2); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_OP_DATA; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); } /* }}} */ void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC) /* {{{ */ { zend_op *opline; znode dummy, value_node; zend_bool assign_by_ref=0; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num]; if (key->op_type != IS_UNUSED) { znode *tmp; /* switch between the key and value... */ tmp = key; key = value; value = tmp; /* Mark extended_value in case both key and value are being used */ opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; } if ((key->op_type != IS_UNUSED) && (key->EA & ZEND_PARSED_REFERENCE_VARIABLE)) { zend_error(E_COMPILE_ERROR, "Key element cannot be a reference"); } if (value->EA & ZEND_PARSED_REFERENCE_VARIABLE) { assign_by_ref = 1; if (!(opline-1)->extended_value) { zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression"); } /* Mark extended_value for assign-by-reference */ opline->extended_value |= ZEND_FE_FETCH_BYREF; CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; } else { zend_op *foreach_copy; zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.op.opline_num]; zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.op.opline_num]; /* Change "write context" into "read context" */ fetch->extended_value = 0; /* reset ZEND_FE_RESET_VARIABLE */ while (fetch != end) { --fetch; if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } if (fetch->opcode == ZEND_SEPARATE) { MAKE_NOP(fetch); } else { fetch->opcode -= 3; /* FETCH_W -> FETCH_R */ } } /* prevent double SWITCH_FREE */ zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy); foreach_copy->op1_type = IS_UNUSED; } GET_NODE(&value_node, opline->result); if (assign_by_ref) { zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); /* Mark FE_FETCH as IS_VAR as it holds the data directly as a value */ zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC); } else { zend_do_assign(&dummy, value, &value_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } if (key->op_type != IS_UNUSED) { znode key_node; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num+1]; opline->result_type = IS_TMP_VAR; opline->result.opline_num = get_temporary_variable(CG(active_op_array)); GET_NODE(&key_node, opline->result); zend_do_assign(&dummy, key, &key_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_foreach_end(const znode *foreach_token, const znode *as_token TSRMLS_DC) /* {{{ */ { zend_op *container_ptr; zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = as_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_RESET */ CG(active_op_array)->opcodes[as_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_FETCH */ do_end_loop(as_token->u.op.opline_num, 1 TSRMLS_CC); zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr); generate_free_foreach_copy(container_ptr TSRMLS_CC); zend_stack_del_top(&CG(foreach_copy_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_declare_begin(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(declare_stack), &CG(declarables), sizeof(zend_declarables)); } /* }}} */ void zend_do_declare_stmt(znode *var, znode *val TSRMLS_DC) /* {{{ */ { if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "ticks", sizeof("ticks")-1)) { convert_to_long(&val->u.constant); CG(declarables).ticks = val->u.constant; } else if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "encoding", sizeof("encoding")-1)) { if ((Z_TYPE(val->u.constant) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Cannot use constants as encoding"); } /* * Check that the pragma comes before any opcodes. If the compilation * got as far as this, the previous portion of the script must have been * parseable according to the .ini script_encoding setting. We still * want to tell them to put declare() at the top. */ { int num = CG(active_op_array)->last; /* ignore ZEND_EXT_STMT and ZEND_TICKS */ while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Encoding declaration pragma must be the very first statement in the script"); } } if (CG(multibyte)) { const zend_encoding *new_encoding, *old_encoding; zend_encoding_filter old_input_filter; CG(encoding_declared) = 1; convert_to_string(&val->u.constant); new_encoding = zend_multibyte_fetch_encoding(val->u.constant.value.str.val TSRMLS_CC); if (!new_encoding) { zend_error(E_COMPILE_WARNING, "Unsupported encoding [%s]", val->u.constant.value.str.val); } else { old_input_filter = LANG_SCNG(input_filter); old_encoding = LANG_SCNG(script_encoding); zend_multibyte_set_filter(new_encoding TSRMLS_CC); /* need to re-scan if input filter changed */ if (old_input_filter != LANG_SCNG(input_filter) || (old_input_filter && new_encoding != old_encoding)) { zend_multibyte_yyinput_again(old_input_filter, old_encoding TSRMLS_CC); } } } else { zend_error(E_COMPILE_WARNING, "declare(encoding=...) ignored because Zend multibyte feature is turned off by settings"); } zval_dtor(&val->u.constant); } else { zend_error(E_COMPILE_WARNING, "Unsupported declare '%s'", var->u.constant.value.str.val); zval_dtor(&val->u.constant); } zval_dtor(&var->u.constant); } /* }}} */ void zend_do_declare_end(const znode *declare_token TSRMLS_DC) /* {{{ */ { zend_declarables *declarables; zend_stack_top(&CG(declare_stack), (void **) &declarables); /* We should restore if there was more than (current - start) - (ticks?1:0) opcodes */ if ((get_next_op_number(CG(active_op_array)) - declare_token->u.op.opline_num) - ((Z_LVAL(CG(declarables).ticks))?1:0)) { CG(declarables) = *declarables; } } /* }}} */ void zend_do_exit(znode *result, const znode *message TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXIT; SET_NODE(opline->op1, message); SET_UNUSED(opline->op2); result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_BOOL; Z_LVAL(result->u.constant) = 1; } /* }}} */ void zend_do_begin_silence(znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BEGIN_SILENCE; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); GET_NODE(strudel_token, opline->result); } /* }}} */ void zend_do_end_silence(const znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_END_SILENCE; SET_NODE(opline->op1, strudel_token); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_jmp_set(const znode *value, znode *jmp_token, znode *colon_token TSRMLS_DC) /* {{{ */ { int op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (value->op_type == IS_VAR || value->op_type == IS_CV) { opline->opcode = ZEND_JMP_SET_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_JMP_SET; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, value); SET_UNUSED(opline->op2); GET_NODE(colon_token, opline->result); jmp_token->u.op .opline_num = op_number; INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_jmp_set_else(znode *result, const znode *false_value, const znode *jmp_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, colon_token); if (colon_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].opcode = ZEND_JMP_SET_VAR; CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } opline->extended_value = 0; SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_qm_op(const znode *cond, znode *qm_token TSRMLS_DC) /* {{{ */ { int jmpz_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); SET_UNUSED(opline->op2); opline->op2.opline_num = jmpz_op_number; GET_NODE(qm_token, opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_qm_true(const znode *true_value, znode *qm_token, znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->opcodes[qm_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array))+1; /* jmp over the ZEND_JMP */ if (true_value->op_type == IS_VAR || true_value->op_type == IS_CV) { opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, true_value); SET_UNUSED(opline->op2); GET_NODE(qm_token, opline->result); colon_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_qm_false(znode *result, const znode *false_value, const znode *qm_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, qm_token); if (qm_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].opcode = ZEND_QM_ASSIGN_VAR; CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[colon_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, opline->result); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_extended_info(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_STMT; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_begin(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_BEGIN; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_end(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_END; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_ticks(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_TICKS; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->extended_value = Z_LVAL(CG(declarables).ticks); } /* }}} */ zend_bool zend_is_auto_global_quick(const char *name, uint name_len, ulong hashval TSRMLS_DC) /* {{{ */ { zend_auto_global *auto_global; ulong hash = hashval ? hashval : zend_hash_func(name, name_len+1); if (zend_hash_quick_find(CG(auto_globals), name, name_len+1, hash, (void **) &auto_global)==SUCCESS) { if (auto_global->armed) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } return 1; } return 0; } /* }}} */ zend_bool zend_is_auto_global(const char *name, uint name_len TSRMLS_DC) /* {{{ */ { return zend_is_auto_global_quick(name, name_len, 0 TSRMLS_CC); } /* }}} */ int zend_register_auto_global(const char *name, uint name_len, zend_bool jit, zend_auto_global_callback auto_global_callback TSRMLS_DC) /* {{{ */ { zend_auto_global auto_global; auto_global.name = zend_new_interned_string((char*)name, name_len + 1, 0 TSRMLS_CC); auto_global.name_len = name_len; auto_global.auto_global_callback = auto_global_callback; auto_global.jit = jit; return zend_hash_add(CG(auto_globals), name, name_len+1, &auto_global, sizeof(zend_auto_global), NULL); } /* }}} */ static int zend_auto_global_init(zend_auto_global *auto_global TSRMLS_DC) /* {{{ */ { if (auto_global->jit) { auto_global->armed = 1; } else if (auto_global->auto_global_callback) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } else { auto_global->armed = 0; } return 0; } /* }}} */ ZEND_API void zend_activate_auto_globals(TSRMLS_D) /* {{{ */ { zend_hash_apply(CG(auto_globals), (apply_func_t) zend_auto_global_init TSRMLS_CC); } /* }}} */ int zendlex(znode *zendlval TSRMLS_DC) /* {{{ */ { int retval; if (CG(increment_lineno)) { CG(zend_lineno)++; CG(increment_lineno) = 0; } again: Z_TYPE(zendlval->u.constant) = IS_LONG; retval = lex_scan(&zendlval->u.constant TSRMLS_CC); switch (retval) { case T_COMMENT: case T_DOC_COMMENT: case T_OPEN_TAG: case T_WHITESPACE: goto again; case T_CLOSE_TAG: if (LANG_SCNG(yy_text)[LANG_SCNG(yy_leng)-1] != '>') { CG(increment_lineno) = 1; } if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { goto again; } retval = ';'; /* implicit ; */ break; case T_OPEN_TAG_WITH_ECHO: retval = T_ECHO; break; case T_END_HEREDOC: efree(Z_STRVAL(zendlval->u.constant)); break; } INIT_PZVAL(&zendlval->u.constant); zendlval->op_type = IS_CONST; return retval; } /* }}} */ ZEND_API void zend_initialize_class_data(zend_class_entry *ce, zend_bool nullify_handlers TSRMLS_DC) /* {{{ */ { zend_bool persistent_hashes = (ce->type == ZEND_INTERNAL_CLASS) ? 1 : 0; dtor_func_t zval_ptr_dtor_func = ((persistent_hashes) ? ZVAL_INTERNAL_PTR_DTOR : ZVAL_PTR_DTOR); ce->refcount = 1; ce->ce_flags = 0; ce->default_properties_table = NULL; ce->default_static_members_table = NULL; zend_hash_init_ex(&ce->properties_info, 0, NULL, (dtor_func_t) (persistent_hashes ? zend_destroy_property_info_internal : zend_destroy_property_info), persistent_hashes, 0); zend_hash_init_ex(&ce->constants_table, 0, NULL, zval_ptr_dtor_func, persistent_hashes, 0); zend_hash_init_ex(&ce->function_table, 0, NULL, ZEND_FUNCTION_DTOR, persistent_hashes, 0); if (ce->type == ZEND_INTERNAL_CLASS) { #ifdef ZTS int n = zend_hash_num_elements(CG(class_table)); if (CG(static_members_table) && n >= CG(last_static_member)) { /* Support for run-time declaration: dl() */ CG(last_static_member) = n+1; CG(static_members_table) = realloc(CG(static_members_table), (n+1)*sizeof(zval**)); CG(static_members_table)[n] = NULL; } ce->static_members_table = (zval**)(zend_intptr_t)n; #else ce->static_members_table = NULL; #endif } else { ce->static_members_table = ce->default_static_members_table; ce->info.user.doc_comment = NULL; ce->info.user.doc_comment_len = 0; } ce->default_properties_count = 0; ce->default_static_members_count = 0; if (nullify_handlers) { ce->constructor = NULL; ce->destructor = NULL; ce->clone = NULL; ce->__get = NULL; ce->__set = NULL; ce->__unset = NULL; ce->__isset = NULL; ce->__call = NULL; ce->__callstatic = NULL; ce->__tostring = NULL; ce->create_object = NULL; ce->get_iterator = NULL; ce->iterator_funcs.funcs = NULL; ce->interface_gets_implemented = NULL; ce->get_static_method = NULL; ce->parent = NULL; ce->num_interfaces = 0; ce->interfaces = NULL; ce->num_traits = 0; ce->traits = NULL; ce->trait_aliases = NULL; ce->trait_precedences = NULL; ce->serialize = NULL; ce->unserialize = NULL; ce->serialize_func = NULL; ce->unserialize_func = NULL; if (ce->type == ZEND_INTERNAL_CLASS) { ce->info.internal.module = NULL; ce->info.internal.builtin_functions = NULL; } } } /* }}} */ int zend_get_class_fetch_type(const char *class_name, uint class_name_len) /* {{{ */ { if ((class_name_len == sizeof("self")-1) && !memcmp(class_name, "self", sizeof("self")-1)) { return ZEND_FETCH_CLASS_SELF; } else if ((class_name_len == sizeof("parent")-1) && !memcmp(class_name, "parent", sizeof("parent")-1)) { return ZEND_FETCH_CLASS_PARENT; } else if ((class_name_len == sizeof("static")-1) && !memcmp(class_name, "static", sizeof("static")-1)) { return ZEND_FETCH_CLASS_STATIC; } else { return ZEND_FETCH_CLASS_DEFAULT; } } /* }}} */ ZEND_API const char* zend_get_compiled_variable_name(const zend_op_array *op_array, zend_uint var, int* name_len) /* {{{ */ { if (name_len) { *name_len = op_array->vars[var].name_len; } return op_array->vars[var].name; } /* }}} */ void zend_do_build_namespace_name(znode *result, znode *prefix, znode *name TSRMLS_DC) /* {{{ */ { if (prefix) { *result = *prefix; if (Z_TYPE(result->u.constant) == IS_STRING && Z_STRLEN(result->u.constant) == 0) { /* namespace\ */ if (CG(current_namespace)) { znode tmp; zval_dtor(&result->u.constant); tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(result, NULL, &tmp TSRMLS_CC); } } } else { result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_STRING; Z_STRVAL(result->u.constant) = NULL; Z_STRLEN(result->u.constant) = 0; } /* prefix = result */ zend_do_build_full_name(NULL, result, name, 0 TSRMLS_CC); } /* }}} */ void zend_do_begin_namespace(const znode *name, zend_bool with_bracket TSRMLS_DC) /* {{{ */ { char *lcname; /* handle mixed syntax declaration or nested namespaces */ if (!CG(has_bracketed_namespaces)) { if (CG(current_namespace)) { /* previous namespace declarations were unbracketed */ if (with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } } } else { /* previous namespace declarations were bracketed */ if (!with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } else if (CG(current_namespace) || CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "Namespace declarations cannot be nested"); } } if (((!with_bracket && !CG(current_namespace)) || (with_bracket && !CG(has_bracketed_namespaces))) && CG(active_op_array)->last > 0) { /* ignore ZEND_EXT_STMT and ZEND_TICKS */ int num = CG(active_op_array)->last; while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Namespace declaration statement has to be the very first statement in the script"); } } CG(in_namespace) = 1; if (with_bracket) { CG(has_bracketed_namespaces) = 1; } if (name) { lcname = zend_str_tolower_dup(Z_STRVAL(name->u.constant), Z_STRLEN(name->u.constant)); if (((Z_STRLEN(name->u.constant) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN(name->u.constant) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as namespace name", Z_STRVAL(name->u.constant)); } efree(lcname); if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); } else { ALLOC_ZVAL(CG(current_namespace)); } *CG(current_namespace) = name->u.constant; } else { if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_use(znode *ns_name, znode *new_name, int is_global TSRMLS_DC) /* {{{ */ { char *lcname; zval *name, *ns, tmp; zend_bool warn = 0; zend_class_entry **pce; if (!CG(current_import)) { CG(current_import) = emalloc(sizeof(HashTable)); zend_hash_init(CG(current_import), 0, NULL, ZVAL_PTR_DTOR, 0); } ALLOC_ZVAL(ns); *ns = ns_name->u.constant; if (new_name) { name = &new_name->u.constant; } else { const char *p; /* The form "use A\B" is eqivalent to "use A\B as B". So we extract the last part of compound name to use as a new_name */ name = &tmp; p = zend_memrchr(Z_STRVAL_P(ns), '\\', Z_STRLEN_P(ns)); if (p) { ZVAL_STRING(name, p+1, 1); } else { *name = *ns; zval_copy_ctor(name); warn = !is_global && !CG(current_namespace); } } lcname = zend_str_tolower_dup(Z_STRVAL_P(name), Z_STRLEN_P(name)); if (((Z_STRLEN_P(name) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN_P(name) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because '%s' is a special class name", Z_STRVAL_P(ns), Z_STRVAL_P(name), Z_STRVAL_P(name)); } if (CG(current_namespace)) { /* Prefix import name with current namespace name to avoid conflicts with classes */ char *c_ns_name = emalloc(Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) + 1); zend_str_tolower_copy(c_ns_name, Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); c_ns_name[Z_STRLEN_P(CG(current_namespace))] = '\\'; memcpy(c_ns_name+Z_STRLEN_P(CG(current_namespace))+1, lcname, Z_STRLEN_P(name)+1); if (zend_hash_exists(CG(class_table), c_ns_name, Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name)+1)) { char *tmp2 = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) || memcmp(tmp2, c_ns_name, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(tmp2); } efree(c_ns_name); } else if (zend_hash_find(CG(class_table), lcname, Z_STRLEN_P(name)+1, (void**)&pce) == SUCCESS && (*pce)->type == ZEND_USER_CLASS && (*pce)->info.user.filename == CG(compiled_filename)) { char *c_tmp = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(name) || memcmp(c_tmp, lcname, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(c_tmp); } if (zend_hash_add(CG(current_import), lcname, Z_STRLEN_P(name)+1, &ns, sizeof(zval*), NULL) != SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } if (warn) { if (!strcmp(Z_STRVAL_P(name), "strict")) { zend_error(E_COMPILE_ERROR, "You seem to be trying to use a different language..."); } zend_error(E_WARNING, "The use statement with non-compound name '%s' has no effect", Z_STRVAL_P(name)); } efree(lcname); zval_dtor(name); } /* }}} */ void zend_do_declare_constant(znode *name, znode *value TSRMLS_DC) /* {{{ */ { zend_op *opline; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed as constants"); } if (zend_get_ct_const(&name->u.constant, 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare constant '%s'", Z_STRVAL(name->u.constant)); } if (CG(current_namespace)) { /* Prefix constant name with name of current namespace, lowercased */ znode tmp; tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); Z_STRVAL(tmp.u.constant) = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), Z_STRLEN(tmp.u.constant)); zend_do_build_namespace_name(&tmp, &tmp, name TSRMLS_CC); *name = tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DECLARE_CONST; SET_UNUSED(opline->result); SET_NODE(opline->op1, name); SET_NODE(opline->op2, value); } /* }}} */ void zend_verify_namespace(TSRMLS_D) /* {{{ */ { if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "No code may exist outside of namespace {}"); } } /* }}} */ void zend_do_end_namespace(TSRMLS_D) /* {{{ */ { CG(in_namespace) = 0; if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_end_compilation(TSRMLS_D) /* {{{ */ { CG(has_bracketed_namespaces) = 0; zend_do_end_namespace(TSRMLS_C); } /* }}} */ /* {{{ zend_dirname Returns directory name component of path */ ZEND_API size_t zend_dirname(char *path, size_t len) { register char *end = path + len - 1; unsigned int len_adjust = 0; #ifdef PHP_WIN32 /* Note that on Win32 CWD is per drive (heritage from CP/M). * This means dirname("c:foo") maps to "c:." or "c:" - which means CWD on C: drive. */ if ((2 <= len) && isalpha((int)((unsigned char *)path)[0]) && (':' == path[1])) { /* Skip over the drive spec (if any) so as not to change */ path += 2; len_adjust += 2; if (2 == len) { /* Return "c:" on Win32 for dirname("c:"). * It would be more consistent to return "c:." * but that would require making the string *longer*. */ return len; } } #elif defined(NETWARE) /* * Find the first occurence of : from the left * move the path pointer to the position just after : * increment the len_adjust to the length of path till colon character(inclusive) * If there is no character beyond : simple return len */ char *colonpos = NULL; colonpos = strchr(path, ':'); if (colonpos != NULL) { len_adjust = ((colonpos - path) + 1); path += len_adjust; if (len_adjust == len) { return len; } } #endif if (len == 0) { /* Illegal use of this function */ return 0; } /* Strip trailing slashes */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { /* The path only contained slashes */ path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } /* Strip filename */ while (end >= path && !IS_SLASH_P(end)) { end--; } if (end < path) { /* No slash found, therefore return '.' */ #ifdef NETWARE if (len_adjust == 0) { path[0] = '.'; path[1] = '\0'; return 1; /* only one character */ } else { path[0] = '\0'; return len_adjust; } #else path[0] = '.'; path[1] = '\0'; return 1 + len_adjust; #endif } /* Strip slashes which came before the file name */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } *(end+1) = '\0'; return (size_t)(end + 1 - path) + len_adjust; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */ /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <zend_language_parser.h> #include "zend.h" #include "zend_compile.h" #include "zend_constants.h" #include "zend_llist.h" #include "zend_API.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "zend_multibyte.h" #include "zend_language_scanner.h" #define CONSTANT_EX(op_array, op) \ (op_array)->literals[op].constant #define CONSTANT(op) \ CONSTANT_EX(CG(active_op_array), op) #define SET_NODE(target, src) do { \ target ## _type = (src)->op_type; \ if ((src)->op_type == IS_CONST) { \ target.constant = zend_add_literal(CG(active_op_array), &(src)->u.constant TSRMLS_CC); \ } else { \ target = (src)->u.op; \ } \ } while (0) #define GET_NODE(target, src) do { \ (target)->op_type = src ## _type; \ if ((target)->op_type == IS_CONST) { \ (target)->u.constant = CONSTANT(src.constant); \ } else { \ (target)->u.op = src; \ (target)->EA = 0; \ } \ } while (0) #define COPY_NODE(target, src) do { \ target ## _type = src ## _type; \ target = src; \ } while (0) #define CALCULATE_LITERAL_HASH(num) do { \ if (IS_INTERNED(Z_STRVAL(CONSTANT(num)))) { \ Z_HASH_P(&CONSTANT(num)) = INTERNED_HASH(Z_STRVAL(CONSTANT(num))); \ } else { \ Z_HASH_P(&CONSTANT(num)) = zend_hash_func(Z_STRVAL(CONSTANT(num)), Z_STRLEN(CONSTANT(num))+1); \ } \ } while (0) #define GET_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot++; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ } \ } while (0) #define POLYMORPHIC_CACHE_SLOT_SIZE 2 #define GET_POLYMORPHIC_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot; \ CG(active_op_array)->last_cache_slot += POLYMORPHIC_CACHE_SLOT_SIZE; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 2] = NULL; \ } \ } while (0) #define FREE_POLYMORPHIC_CACHE_SLOT(literal) do { \ if (CG(active_op_array)->literals[literal].cache_slot == \ CG(active_op_array)->last_cache_slot - POLYMORPHIC_CACHE_SLOT_SIZE) { \ CG(active_op_array)->literals[literal].cache_slot = -1; \ CG(active_op_array)->last_cache_slot -= POLYMORPHIC_CACHE_SLOT_SIZE; \ } \ } while (0) ZEND_API zend_op_array *(*zend_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); ZEND_API zend_op_array *(*zend_compile_string)(zval *source_string, char *filename TSRMLS_DC); #ifndef ZTS ZEND_API zend_compiler_globals compiler_globals; ZEND_API zend_executor_globals executor_globals; #endif static void zend_duplicate_property_info(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = estrndup(property_info->name, property_info->name_length); } if (property_info->doc_comment) { property_info->doc_comment = estrndup(property_info->doc_comment, property_info->doc_comment_len); } } /* }}} */ static void zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = zend_strndup(property_info->name, property_info->name_length); } } /* }}} */ static void zend_destroy_property_info(zend_property_info *property_info) /* {{{ */ { str_efree(property_info->name); if (property_info->doc_comment) { efree((char*)property_info->doc_comment); } } /* }}} */ static void zend_destroy_property_info_internal(zend_property_info *property_info) /* {{{ */ { str_free((char*)property_info->name); } /* }}} */ static void build_runtime_defined_function_key(zval *result, const char *name, int name_length TSRMLS_DC) /* {{{ */ { char char_pos_buf[32]; uint char_pos_len; const char *filename; char_pos_len = zend_sprintf(char_pos_buf, "%p", LANG_SCNG(yy_text)); if (CG(active_op_array)->filename) { filename = CG(active_op_array)->filename; } else { filename = "-"; } /* NULL, name length, filename length, last accepting char position length */ result->value.str.len = 1+name_length+strlen(filename)+char_pos_len; /* must be binary safe */ result->value.str.val = (char *) safe_emalloc(result->value.str.len, 1, 1); result->value.str.val[0] = '\0'; sprintf(result->value.str.val+1, "%s%s%s", name, filename, char_pos_buf); result->type = IS_STRING; Z_SET_REFCOUNT_P(result, 1); } /* }}} */ static void init_compiler_declarables(TSRMLS_D) /* {{{ */ { Z_TYPE(CG(declarables).ticks) = IS_LONG; Z_LVAL(CG(declarables).ticks) = 0; } /* }}} */ void zend_init_compiler_context(TSRMLS_D) /* {{{ */ { CG(context).opcodes_size = (CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) ? INITIAL_INTERACTIVE_OP_ARRAY_SIZE : INITIAL_OP_ARRAY_SIZE; CG(context).vars_size = 0; CG(context).literals_size = 0; CG(context).current_brk_cont = -1; CG(context).backpatch_count = 0; CG(context).labels = NULL; } /* }}} */ void zend_init_compiler_data_structures(TSRMLS_D) /* {{{ */ { zend_stack_init(&CG(bp_stack)); zend_stack_init(&CG(function_call_stack)); zend_stack_init(&CG(switch_cond_stack)); zend_stack_init(&CG(foreach_copy_stack)); zend_stack_init(&CG(object_stack)); zend_stack_init(&CG(declare_stack)); CG(active_class_entry) = NULL; zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_stack_init(&CG(list_stack)); CG(in_compilation) = 0; CG(start_lineno) = 0; CG(current_namespace) = NULL; CG(in_namespace) = 0; CG(has_bracketed_namespaces) = 0; CG(current_import) = NULL; init_compiler_declarables(TSRMLS_C); zend_stack_init(&CG(context_stack)); CG(encoding_declared) = 0; } /* }}} */ ZEND_API void file_handle_dtor(zend_file_handle *fh) /* {{{ */ { TSRMLS_FETCH(); zend_file_handle_dtor(fh TSRMLS_CC); } /* }}} */ void init_compiler(TSRMLS_D) /* {{{ */ { CG(active_op_array) = NULL; zend_init_compiler_data_structures(TSRMLS_C); zend_init_rsrc_list(TSRMLS_C); zend_hash_init(&CG(filenames_table), 5, NULL, (dtor_func_t) free_estring, 0); zend_llist_init(&CG(open_files), sizeof(zend_file_handle), (void (*)(void *)) file_handle_dtor, 0); CG(unclean_shutdown) = 0; } /* }}} */ void shutdown_compiler(TSRMLS_D) /* {{{ */ { zend_stack_destroy(&CG(bp_stack)); zend_stack_destroy(&CG(function_call_stack)); zend_stack_destroy(&CG(switch_cond_stack)); zend_stack_destroy(&CG(foreach_copy_stack)); zend_stack_destroy(&CG(object_stack)); zend_stack_destroy(&CG(declare_stack)); zend_stack_destroy(&CG(list_stack)); zend_hash_destroy(&CG(filenames_table)); zend_llist_destroy(&CG(open_files)); zend_stack_destroy(&CG(context_stack)); } /* }}} */ ZEND_API char *zend_set_compiled_filename(const char *new_compiled_filename TSRMLS_DC) /* {{{ */ { char **pp, *p; int length = strlen(new_compiled_filename); if (zend_hash_find(&CG(filenames_table), new_compiled_filename, length+1, (void **) &pp) == SUCCESS) { CG(compiled_filename) = *pp; return *pp; } p = estrndup(new_compiled_filename, length); zend_hash_update(&CG(filenames_table), new_compiled_filename, length+1, &p, sizeof(char *), (void **) &pp); CG(compiled_filename) = p; return p; } /* }}} */ ZEND_API void zend_restore_compiled_filename(char *original_compiled_filename TSRMLS_DC) /* {{{ */ { CG(compiled_filename) = original_compiled_filename; } /* }}} */ ZEND_API char *zend_get_compiled_filename(TSRMLS_D) /* {{{ */ { return CG(compiled_filename); } /* }}} */ ZEND_API int zend_get_compiled_lineno(TSRMLS_D) /* {{{ */ { return CG(zend_lineno); } /* }}} */ ZEND_API zend_bool zend_is_compiling(TSRMLS_D) /* {{{ */ { return CG(in_compilation); } /* }}} */ static zend_uint get_temporary_variable(zend_op_array *op_array) /* {{{ */ { return (op_array->T)++ * ZEND_MM_ALIGNED_SIZE(sizeof(temp_variable)); } /* }}} */ static int lookup_cv(zend_op_array *op_array, char* name, int name_len, ulong hash TSRMLS_DC) /* {{{ */ { int i = 0; ulong hash_value = hash ? hash : zend_inline_hash_func(name, name_len+1); while (i < op_array->last_var) { if (op_array->vars[i].name == name || (op_array->vars[i].hash_value == hash_value && op_array->vars[i].name_len == name_len && memcmp(op_array->vars[i].name, name, name_len) == 0)) { str_efree(name); return i; } i++; } i = op_array->last_var; op_array->last_var++; if (op_array->last_var > CG(context).vars_size) { CG(context).vars_size += 16; /* FIXME */ op_array->vars = erealloc(op_array->vars, CG(context).vars_size * sizeof(zend_compiled_variable)); } op_array->vars[i].name = zend_new_interned_string(name, name_len + 1, 1 TSRMLS_CC); op_array->vars[i].name_len = name_len; op_array->vars[i].hash_value = hash_value; return i; } /* }}} */ void zend_del_literal(zend_op_array *op_array, int n) /* {{{ */ { zval_dtor(&CONSTANT_EX(op_array, n)); if (n + 1 == op_array->last_literal) { op_array->last_literal--; } else { Z_TYPE(CONSTANT_EX(op_array, n)) = IS_NULL; } } /* }}} */ /* Common part of zend_add_literal and zend_append_individual_literal */ static inline void zend_insert_literal(zend_op_array *op_array, const zval *zv, int literal_position TSRMLS_DC) /* {{{ */ { if (Z_TYPE_P(zv) == IS_STRING || Z_TYPE_P(zv) == IS_CONSTANT) { zval *z = (zval*)zv; Z_STRVAL_P(z) = (char*)zend_new_interned_string(Z_STRVAL_P(zv), Z_STRLEN_P(zv) + 1, 1 TSRMLS_CC); } CONSTANT_EX(op_array, literal_position) = *zv; Z_SET_REFCOUNT(CONSTANT_EX(op_array, literal_position), 2); Z_SET_ISREF(CONSTANT_EX(op_array, literal_position)); op_array->literals[literal_position].hash_value = 0; op_array->literals[literal_position].cache_slot = -1; } /* }}} */ /* Is used while compiling a function, using the context to keep track of an approximate size to avoid to relocate to often. Literals are truncated to actual size in the second compiler pass (pass_two()). */ int zend_add_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; if (i >= CG(context).literals_size) { while (i >= CG(context).literals_size) { CG(context).literals_size += 16; /* FIXME */ } op_array->literals = (zend_literal*)erealloc(op_array->literals, CG(context).literals_size * sizeof(zend_literal)); } zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ /* Is used after normal compilation to append an additional literal. Allocation is done precisely here. */ int zend_append_individual_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; op_array->literals = (zend_literal*)erealloc(op_array->literals, (i + 1) * sizeof(zend_literal)); zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ int zend_add_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_ns_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; const char *ns_separator; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); ns_separator = (const char*)zend_memrchr(Z_STRVAL_P(zv), '\\', Z_STRLEN_P(zv)) + 1; lc_len = Z_STRLEN_P(zv) - (ns_separator - Z_STRVAL_P(zv)); lc_name = zend_str_tolower_dup(ns_separator, lc_len); ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_class_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } if (Z_STRVAL_P(zv)[0] == '\\') { lc_len = Z_STRLEN_P(zv) - 1; lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv) + 1, lc_len); } else { lc_len = Z_STRLEN_P(zv); lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), lc_len); } ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); GET_CACHE_SLOT(ret); return ret; } /* }}} */ int zend_add_const_name_literal(zend_op_array *op_array, const zval *zv, int unqualified TSRMLS_DC) /* {{{ */ { int ret, tmp_literal; char *name, *tmp_name; const char *ns_separator; int name_len, ns_len; zval c; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } /* skip leading '\\' */ if (Z_STRVAL_P(zv)[0] == '\\') { name_len = Z_STRLEN_P(zv) - 1; name = Z_STRVAL_P(zv) + 1; } else { name_len = Z_STRLEN_P(zv); name = Z_STRVAL_P(zv); } ns_separator = zend_memrchr(name, '\\', name_len); if (ns_separator) { ns_len = ns_separator - name; } else { ns_len = 0; } if (ns_len) { /* lowercased namespace name & original constant name */ tmp_name = estrndup(name, name_len); zend_str_tolower(tmp_name, ns_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased namespace name & lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); } if (ns_len) { if (!unqualified) { return ret; } ns_len++; name += ns_len; name_len -= ns_len; } /* original constant name */ tmp_name = estrndup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); return ret; } /* }}} */ #define LITERAL_STRINGL(op, str, len, copy) do { \ zval _c; \ ZVAL_STRINGL(&_c, str, len, copy); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG(op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG_EX(op_array, op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(op_array, &_c TSRMLS_CC); \ } while (0) #define LITERAL_NULL(op) do { \ zval _c; \ INIT_ZVAL( _c); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) static inline zend_bool zend_is_function_or_method_call(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; return ((type & ZEND_PARSED_METHOD_CALL) || (type == ZEND_PARSED_FUNCTION_CALL)); } /* }}} */ void zend_do_binary_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_unary_op(zend_uchar op, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); GET_NODE(result, opline->result); SET_UNUSED(opline->op2); } /* }}} */ #define MAKE_NOP(opline) { opline->opcode = ZEND_NOP; memset(&opline->result,0,sizeof(opline->result)); memset(&opline->op1,0,sizeof(opline->op1)); memset(&opline->op2,0,sizeof(opline->op2)); opline->result_type=opline->op1_type=opline->op2_type=IS_UNUSED; } static void zend_do_op_data(zend_op *data_op, const znode *value TSRMLS_DC) /* {{{ */ { data_op->opcode = ZEND_OP_DATA; SET_NODE(data_op->op1, value); SET_UNUSED(data_op->op2); } /* }}} */ void zend_do_binary_assign_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; switch (last_op->opcode) { case ZEND_FETCH_OBJ_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, op2 TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; case ZEND_FETCH_DIM_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_DIM; zend_do_op_data(opline, op2 TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result,last_op->result); return; default: break; } } opline->opcode = op; SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void fetch_simple_variable_ex(znode *result, znode *varname, int bp, zend_uchar op TSRMLS_DC) /* {{{ */ { zend_op opline; zend_op *opline_ptr; zend_llist *fetch_list_ptr; if (varname->op_type == IS_CONST) { ulong hash = 0; if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } else if (IS_INTERNED(Z_STRVAL(varname->u.constant))) { hash = INTERNED_HASH(Z_STRVAL(varname->u.constant)); } if (!zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC) && !(varname->u.constant.value.str.len == (sizeof("this")-1) && !memcmp(varname->u.constant.value.str.val, "this", sizeof("this"))) && (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE)) { result->op_type = IS_CV; result->u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC); varname->u.constant.value.str.val = (char*)CG(active_op_array)->vars[result->u.op.var].name; result->EA = 0; return; } } if (bp) { opline_ptr = &opline; init_op(opline_ptr TSRMLS_CC); } else { opline_ptr = get_next_op(CG(active_op_array) TSRMLS_CC); } opline_ptr->opcode = op; opline_ptr->result_type = IS_VAR; opline_ptr->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline_ptr->op1, varname); GET_NODE(result, opline_ptr->result); SET_UNUSED(opline_ptr->op2); opline_ptr->extended_value = ZEND_FETCH_LOCAL; if (varname->op_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline_ptr->op1.constant); if (zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC)) { opline_ptr->extended_value = ZEND_FETCH_GLOBAL; } } if (bp) { zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); zend_llist_add_element(fetch_list_ptr, opline_ptr); } } /* }}} */ void fetch_simple_variable(znode *result, znode *varname, int bp TSRMLS_DC) /* {{{ */ { /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ fetch_simple_variable_ex(result, varname, bp, ZEND_FETCH_W TSRMLS_CC); } /* }}} */ void zend_do_fetch_static_member(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { znode class_node; zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline_ptr; zend_op opline; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); } zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (result->op_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[result->u.op.var].name), CG(active_op_array)->vars[result->u.op.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } GET_NODE(result,opline.result); opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; opline_ptr = &opline; zend_llist_add_element(fetch_list_ptr, &opline); } else { le = fetch_list_ptr->head; opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode != ZEND_FETCH_W && opline_ptr->op1_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[opline_ptr->op1.var].name), CG(active_op_array)->vars[opline_ptr->op1.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; COPY_NODE(opline_ptr->op1, opline.result); zend_llist_prepend_element(fetch_list_ptr, &opline); } else { if (opline_ptr->op1_type == IS_CONST) { GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op1.constant); } if (class_node.op_type == IS_CONST) { opline_ptr->op2_type = IS_CONST; opline_ptr->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline_ptr->op2, &class_node); } opline_ptr->extended_value |= ZEND_FETCH_STATIC_MEMBER; } } } /* }}} */ void fetch_array_begin(znode *result, znode *varname, znode *first_dim TSRMLS_DC) /* {{{ */ { fetch_simple_variable(result, varname, 1 TSRMLS_CC); fetch_array_dim(result, result, first_dim TSRMLS_CC); } /* }}} */ void fetch_array_dim(znode *result, const znode *parent, const znode *dim TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (zend_is_function_or_method_call(parent)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, parent); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_DIM_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, parent); SET_NODE(opline.op2, dim); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline.op2.constant)), Z_STRLEN(CONSTANT(opline.op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline.op2.constant)); ZVAL_LONG(&CONSTANT(opline.op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline.op2.constant); } } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void fetch_string_offset(znode *result, const znode *parent, const znode *offset TSRMLS_DC) /* {{{ */ { fetch_array_dim(result, parent, offset TSRMLS_CC); } /* }}} */ void zend_do_print(znode *result, const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->opcode = ZEND_PRINT; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_echo(const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ECHO; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_abstract_method(const znode *function_name, znode *modifiers, const znode *body TSRMLS_DC) /* {{{ */ { char *method_type; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { Z_LVAL(modifiers->u.constant) |= ZEND_ACC_ABSTRACT; method_type = "Interface"; } else { method_type = "Abstract"; } if (modifiers->u.constant.value.lval & ZEND_ACC_ABSTRACT) { if(modifiers->u.constant.value.lval & ZEND_ACC_PRIVATE) { zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot be declared private", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } if (Z_LVAL(body->u.constant) == ZEND_ACC_ABSTRACT) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_RAISE_ABSTRACT_ERROR; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } else { /* we had code in the function body */ zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot contain body", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } else { if (body->u.constant.value.lval == ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Non-abstract method %s::%s() must contain body", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } } /* }}} */ static zend_bool opline_is_fetch_this(const zend_op *opline TSRMLS_DC) /* {{{ */ { if ((opline->opcode == ZEND_FETCH_W) && (opline->op1_type == IS_CONST) && (Z_TYPE(CONSTANT(opline->op1.constant)) == IS_STRING) && (Z_HASH_P(&CONSTANT(opline->op1.constant)) == THIS_HASHVAL) && (Z_STRLEN(CONSTANT(opline->op1.constant)) == (sizeof("this")-1)) && !memcmp(Z_STRVAL(CONSTANT(opline->op1.constant)), "this", sizeof("this"))) { return 1; } else { return 0; } } /* }}} */ void zend_do_assign(znode *result, znode *variable, znode *value TSRMLS_DC) /* {{{ */ { int last_op_number; zend_op *opline; if (value->op_type == IS_CV) { zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (fetch_list_ptr && fetch_list_ptr->head) { opline = (zend_op *)fetch_list_ptr->head->data; if (opline->opcode == ZEND_FETCH_DIM_W && opline->op1_type == IS_CV && opline->op1.var == value->u.op.var) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_R; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->op1_type = IS_CONST; LITERAL_STRINGL(opline->op1, CG(active_op_array)->vars[value->u.op.var].name, CG(active_op_array)->vars[value->u.op.var].name_len, 1); CALCULATE_LITERAL_HASH(opline->op1.constant); SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_LOCAL; GET_NODE(value, opline->result); } } } zend_do_end_variable_parse(variable, BP_VAR_W, 0 TSRMLS_CC); last_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (variable->op_type == IS_CV) { if (variable->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (variable->op_type == IS_VAR) { int n = 0; while (last_op_number - n > 0) { zend_op *last_op; last_op = &CG(active_op_array)->opcodes[last_op_number-n-1]; if (last_op->result_type == IS_VAR && last_op->result.var == variable->u.op.var) { if (last_op->opcode == ZEND_FETCH_OBJ_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, value TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (last_op->opcode == ZEND_FETCH_DIM_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ /* TBFixed: this can realloc opcodes, leaving last_op pointing wrong */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_DIM; zend_do_op_data(opline, value TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (opline_is_fetch_this(last_op TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } else { break; } } n++; } } opline->opcode = ZEND_ASSIGN; SET_NODE(opline->op1, variable); SET_NODE(opline->op2, value); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_assign_ref(znode *result, const znode *lvar, const znode *rvar TSRMLS_DC) /* {{{ */ { zend_op *opline; if (lvar->op_type == IS_CV) { if (lvar->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (lvar->op_type == IS_VAR) { int last_op_number = get_next_op_number(CG(active_op_array)); if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline_is_fetch_this(opline TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ASSIGN_REF; if (zend_is_function_or_method_call(rvar)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } else if (rvar->EA & ZEND_PARSED_NEW) { opline->extended_value = ZEND_RETURNS_NEW; } else { opline->extended_value = 0; } if (result) { opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } else { opline->result_type = IS_UNUSED | EXT_TYPE_UNUSED; } SET_NODE(opline->op1, lvar); SET_NODE(opline->op2, rvar); } /* }}} */ static inline void do_begin_loop(TSRMLS_D) /* {{{ */ { zend_brk_cont_element *brk_cont_element; int parent; parent = CG(context).current_brk_cont; CG(context).current_brk_cont = CG(active_op_array)->last_brk_cont; brk_cont_element = get_next_brk_cont_element(CG(active_op_array)); brk_cont_element->start = get_next_op_number(CG(active_op_array)); brk_cont_element->parent = parent; } /* }}} */ static inline void do_end_loop(int cont_addr, int has_loop_var TSRMLS_DC) /* {{{ */ { if (!has_loop_var) { /* The start fileld is used to free temporary variables in case of exceptions. * We won't try to free something of we don't have loop variable. */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].start = -1; } CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = cont_addr; CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; } /* }}} */ void zend_do_while_cond(const znode *expr, znode *close_bracket_token TSRMLS_DC) /* {{{ */ { int while_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, expr); close_bracket_token->u.op.opline_num = while_cond_op_number; SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_while_end(const znode *while_token, const znode *close_bracket_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* add unconditional jump */ opline->opcode = ZEND_JMP; opline->op1.opline_num = while_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* update while's conditional jmp */ CG(active_op_array)->opcodes[close_bracket_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); do_end_loop(while_token->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_cond(const znode *expr, znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { int for_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZNZ; SET_NODE(opline->op1, expr); /* the conditional expression */ second_semicolon_token->u.op.opline_num = for_cond_op_number; SET_UNUSED(opline->op2); } /* }}} */ void zend_do_for_before_statement(const znode *cond_start, const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = cond_start->u.op.opline_num; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_end(const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = second_semicolon_token->u.op.opline_num+1; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_end_loop(second_semicolon_token->u.op.opline_num+1, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_pre_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_PRE_INC)?ZEND_PRE_INC_OBJ:ZEND_PRE_DEC_OBJ; last_op->result_type = IS_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_post_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_POST_INC)?ZEND_POST_INC_OBJ:ZEND_POST_DEC_OBJ; last_op->result_type = IS_TMP_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_if_cond(const znode *cond, znode *closing_bracket_token TSRMLS_DC) /* {{{ */ { int if_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); closing_bracket_token->u.op.opline_num = if_cond_op_number; SET_UNUSED(opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_if_after_statement(const znode *closing_bracket_token, unsigned char initialize TSRMLS_DC) /* {{{ */ { int if_end_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; /* save for backpatching */ if (initialize) { zend_llist jmp_list; zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); } zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &if_end_op_number); CG(active_op_array)->opcodes[closing_bracket_token->u.op.opline_num].op2.opline_num = if_end_op_number+1; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_if_end(TSRMLS_D) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_llist *jmp_list_ptr; zend_llist_element *le; zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); for (le=jmp_list_ptr->head; le; le = le->next) { CG(active_op_array)->opcodes[*((int *) le->data)].op1.opline_num = next_op_number; } zend_llist_destroy(jmp_list_ptr); zend_stack_del_top(&CG(bp_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_check_writable_variable(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; if (type & ZEND_PARSED_METHOD_CALL) { zend_error(E_COMPILE_ERROR, "Can't use method return value in write context"); } if (type == ZEND_PARSED_FUNCTION_CALL) { zend_error(E_COMPILE_ERROR, "Can't use function return value in write context"); } } /* }}} */ void zend_do_begin_variable_parse(TSRMLS_D) /* {{{ */ { zend_llist fetch_list; zend_llist_init(&fetch_list, sizeof(zend_op), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &fetch_list, sizeof(zend_llist)); } /* }}} */ void zend_do_end_variable_parse(znode *variable, int type, int arg_offset TSRMLS_DC) /* {{{ */ { zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline = NULL; zend_op *opline_ptr; zend_uint this_var = -1; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); le = fetch_list_ptr->head; /* TODO: $foo->x->y->z = 1 should fetch "x" and "y" for R or RW, not just W */ if (le) { opline_ptr = (zend_op *)le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { /* convert to FETCH_?(this) into IS_CV */ if (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE) { this_var = opline_ptr->result.var; if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), Z_STRVAL(CONSTANT(opline_ptr->op1.constant)), Z_STRLEN(CONSTANT(opline_ptr->op1.constant)), Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC); Z_TYPE(CONSTANT(opline_ptr->op1.constant)) = IS_NULL; } else { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); } le = le->next; if (variable->op_type == IS_VAR && variable->u.op.var == this_var) { variable->op_type = IS_CV; variable->u.op.var = CG(active_op_array)->this_var; } } else if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } while (le) { opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode == ZEND_SEPARATE) { if (type != BP_VAR_R && type != BP_VAR_IS) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); } le = le->next; continue; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); if (opline->op1_type == IS_VAR && opline->op1.var == this_var) { opline->op1_type = IS_CV; opline->op1.var = CG(active_op_array)->this_var; } switch (type) { case BP_VAR_R: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode -= 3; break; case BP_VAR_W: break; case BP_VAR_RW: opline->opcode += 3; break; case BP_VAR_IS: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode += 6; /* 3+3 */ break; case BP_VAR_FUNC_ARG: opline->opcode += 9; /* 3+3+3 */ opline->extended_value |= arg_offset; break; case BP_VAR_UNSET: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for unsetting"); } opline->opcode += 12; /* 3+3+3+3 */ break; } le = le->next; } if (opline && type == BP_VAR_W && arg_offset) { opline->extended_value |= ZEND_FETCH_MAKE_REF; } } zend_llist_destroy(fetch_list_ptr); zend_stack_del_top(&CG(bp_stack)); } /* }}} */ void zend_do_add_string(znode *result, const znode *op1, znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline; if (Z_STRLEN(op2->u.constant) > 1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_STRING; } else if (Z_STRLEN(op2->u.constant) == 1) { int ch = *Z_STRVAL(op2->u.constant); /* Free memory and use ZEND_ADD_CHAR in case of 1 character strings */ efree(Z_STRVAL(op2->u.constant)); ZVAL_LONG(&op2->u.constant, ch); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_CHAR; } else { /* String can be empty after a variable at the end of a heredoc */ efree(Z_STRVAL(op2->u.constant)); return; } if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_add_variable(znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_VAR; if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_free(znode *op1 TSRMLS_DC) /* {{{ */ { if (op1->op_type==IS_TMP_VAR) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else if (op1->op_type==IS_VAR) { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; while (opline->opcode == ZEND_END_SILENCE || opline->opcode == ZEND_EXT_FCALL_END || opline->opcode == ZEND_OP_DATA) { opline--; } if (opline->result_type == IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_FETCH_R || opline->opcode == ZEND_FETCH_DIM_R || opline->opcode == ZEND_FETCH_OBJ_R || opline->opcode == ZEND_QM_ASSIGN_VAR) { /* It's very rare and useless case. It's better to use additional FREE opcode and simplify the FETCH handlers their selves */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else { opline->result_type |= EXT_TYPE_UNUSED; } } else { while (opline>CG(active_op_array)->opcodes) { if (opline->opcode == ZEND_FETCH_DIM_R && opline->op1_type == IS_VAR && opline->op1.var == op1->u.op.var) { /* This should the end of a list() construct * Mark its result as unused */ opline->extended_value = ZEND_FETCH_STANDARD; break; } else if (opline->result_type==IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_NEW) { opline->result_type |= EXT_TYPE_UNUSED; } break; } opline--; } } } else if (op1->op_type == IS_CONST) { zval_dtor(&op1->u.constant); } } /* }}} */ int zend_do_verify_access_types(const znode *current_access_type, const znode *new_modifier) /* {{{ */ { if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_PPP_MASK) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Multiple access type modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_ABSTRACT) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Multiple abstract modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_STATIC) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Multiple static modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_FINAL) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Multiple final modifiers are not allowed"); } if (((Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)) & (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) == (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Cannot use the final modifier on an abstract class member"); } return (Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)); } /* }}} */ void zend_do_begin_function_declaration(znode *function_token, znode *function_name, int is_method, int return_reference, znode *fn_flags_znode TSRMLS_DC) /* {{{ */ { zend_op_array op_array; char *name = function_name->u.constant.value.str.val; int name_len = function_name->u.constant.value.str.len; int function_begin_line = function_token->u.op.opline_num; zend_uint fn_flags; const char *lcname; zend_bool orig_interactive; ALLOCA_FLAG(use_heap) if (is_method) { if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((Z_LVAL(fn_flags_znode->u.constant) & ~(ZEND_ACC_STATIC|ZEND_ACC_PUBLIC))) { zend_error(E_COMPILE_ERROR, "Access type for interface method %s::%s() must be omitted", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } Z_LVAL(fn_flags_znode->u.constant) |= ZEND_ACC_ABSTRACT; /* propagates to the rest of the parser */ } fn_flags = Z_LVAL(fn_flags_znode->u.constant); /* must be done *after* the above check */ } else { fn_flags = 0; } if ((fn_flags & ZEND_ACC_STATIC) && (fn_flags & ZEND_ACC_ABSTRACT) && !(CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_STRICT, "Static function %s%s%s() should not be abstract", is_method ? CG(active_class_entry)->name : "", is_method ? "::" : "", Z_STRVAL(function_name->u.constant)); } function_token->u.op_array = CG(active_op_array); orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(&op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; op_array.function_name = name; if (return_reference) { op_array.fn_flags |= ZEND_ACC_RETURN_REFERENCE; } op_array.fn_flags |= fn_flags; op_array.scope = is_method?CG(active_class_entry):NULL; op_array.prototype = NULL; op_array.line_start = zend_get_compiled_lineno(TSRMLS_C); if (is_method) { int result; lcname = zend_new_interned_string(zend_str_tolower_dup(name, name_len), name_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lcname)) { result = zend_hash_quick_add(&CG(active_class_entry)->function_table, lcname, name_len+1, INTERNED_HASH(lcname), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } else { result = zend_hash_add(&CG(active_class_entry)->function_table, lcname, name_len+1, &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } if (result == FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::%s()", CG(active_class_entry)->name, name); } zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); if (fn_flags & ZEND_ACC_ABSTRACT) { CG(active_class_entry)->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (!(fn_flags & ZEND_ACC_PPP_MASK)) { fn_flags |= ZEND_ACC_PUBLIC; } if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } } } else { char *class_lcname; class_lcname = do_alloca(CG(active_class_entry)->name_length + 1, use_heap); zend_str_tolower_copy(class_lcname, CG(active_class_entry)->name, CG(active_class_entry)->name_length); /* Improve after RC: cache the lowercase class name */ if ((CG(active_class_entry)->name_length == name_len) && ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT) && (!memcmp(class_lcname, lcname, name_len))) { if (!CG(active_class_entry)->constructor) { CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } } else if ((name_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)))) { if (CG(active_class_entry)->constructor) { zend_error(E_STRICT, "Redefining already defined constructor for class %s", CG(active_class_entry)->name); } CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1))) { CG(active_class_entry)->destructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1))) { CG(active_class_entry)->clone = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } CG(active_class_entry)->__call = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } CG(active_class_entry)->__callstatic = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } CG(active_class_entry)->__get = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } CG(active_class_entry)->__set = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } CG(active_class_entry)->__unset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } CG(active_class_entry)->__isset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } CG(active_class_entry)->__tostring = (zend_function *) CG(active_op_array); } else if (!(fn_flags & ZEND_ACC_STATIC)) { CG(active_op_array)->fn_flags |= ZEND_ACC_ALLOW_STATIC; } free_alloca(class_lcname, use_heap); } str_efree(lcname); } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zval key; if (CG(current_namespace)) { /* Prefix function name with current namespcae name */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, function_name TSRMLS_CC); op_array.function_name = Z_STRVAL(tmp.u.constant); name_len = Z_STRLEN(tmp.u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), name_len); } else { lcname = zend_str_tolower_dup(name, name_len); } opline->opcode = ZEND_DECLARE_FUNCTION; opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, name_len TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; LITERAL_STRINGL(opline->op2, lcname, name_len, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); opline->extended_value = ZEND_DECLARE_FUNCTION; zend_hash_quick_update(CG(function_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); } if (CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_NOP; opline->lineno = function_begin_line; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } { /* Push a seperator to the switch and foreach stacks */ zend_switch_entry switch_entry; switch_entry.cond.op_type = IS_UNUSED; switch_entry.default_case = 0; switch_entry.control_var = 0; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); { /* Foreach stack separator */ zend_op dummy_opline; dummy_opline.result_type = IS_UNUSED; dummy_opline.op1_type = IS_UNUSED; zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); } } if (CG(doc_comment)) { CG(active_op_array)->doc_comment = CG(doc_comment); CG(active_op_array)->doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_begin_lambda_function_declaration(znode *result, znode *function_token, int return_reference, int is_static TSRMLS_DC) /* {{{ */ { znode function_name; zend_op_array *current_op_array = CG(active_op_array); int current_op_number = get_next_op_number(CG(active_op_array)); zend_op *current_op; function_name.op_type = IS_CONST; ZVAL_STRINGL(&function_name.u.constant, "{closure}", sizeof("{closure}")-1, 1); zend_do_begin_function_declaration(function_token, &function_name, 0, return_reference, NULL TSRMLS_CC); result->op_type = IS_TMP_VAR; result->u.op.var = get_temporary_variable(current_op_array); current_op = &current_op_array->opcodes[current_op_number]; current_op->opcode = ZEND_DECLARE_LAMBDA_FUNCTION; zend_del_literal(current_op_array, current_op->op2.constant); SET_UNUSED(current_op->op2); SET_NODE(current_op->result, result); if (is_static) { CG(active_op_array)->fn_flags |= ZEND_ACC_STATIC; } CG(active_op_array)->fn_flags |= ZEND_ACC_CLOSURE; } /* }}} */ void zend_do_handle_exception(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_HANDLE_EXCEPTION; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_function_declaration(const znode *function_token TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; zend_do_extended_info(TSRMLS_C); zend_do_return(NULL, 0 TSRMLS_CC); pass_two(CG(active_op_array) TSRMLS_CC); zend_release_labels(TSRMLS_C); if (CG(active_class_entry)) { zend_check_magic_method_implementation(CG(active_class_entry), (zend_function*)CG(active_op_array), E_COMPILE_ERROR TSRMLS_CC); } else { /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(CG(active_op_array)->function_name); zend_str_tolower_copy(lcname, CG(active_op_array)->function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME)) && CG(active_op_array)->num_args != 1) { zend_error(E_COMPILE_ERROR, "%s() must take exactly 1 argument", ZEND_AUTOLOAD_FUNC_NAME); } } CG(active_op_array)->line_end = zend_get_compiled_lineno(TSRMLS_C); CG(active_op_array) = function_token->u.op_array; /* Pop the switch and foreach seperators */ zend_stack_del_top(&CG(switch_cond_stack)); zend_stack_del_top(&CG(foreach_copy_stack)); } /* }}} */ void zend_do_receive_arg(zend_uchar op, znode *varname, const znode *offset, const znode *initialization, znode *class_type, zend_uchar pass_by_reference TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_arg_info *cur_arg_info; znode var; if (class_type->op_type == IS_CONST && Z_TYPE(class_type->u.constant) == IS_STRING && Z_STRLEN(class_type->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_type->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } if (zend_is_auto_global_quick(Z_STRVAL(varname->u.constant), Z_STRLEN(varname->u.constant), 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign auto-global variable %s", Z_STRVAL(varname->u.constant)); } else { var.op_type = IS_CV; var.u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(varname->u.constant) = (char*)CG(active_op_array)->vars[var.u.op.var].name; var.EA = 0; if (CG(active_op_array)->vars[var.u.op.var].hash_value == THIS_HASHVAL && Z_STRLEN(varname->u.constant) == sizeof("this")-1 && !memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this")-1)) { if (CG(active_op_array)->scope && (CG(active_op_array)->fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } CG(active_op_array)->this_var = var.u.op.var; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->num_args++; opline->opcode = op; SET_NODE(opline->result, &var); SET_NODE(opline->op1, offset); if (op == ZEND_RECV_INIT) { SET_NODE(opline->op2, initialization); } else { CG(active_op_array)->required_num_args = CG(active_op_array)->num_args; SET_UNUSED(opline->op2); } CG(active_op_array)->arg_info = erealloc(CG(active_op_array)->arg_info, sizeof(zend_arg_info)*(CG(active_op_array)->num_args)); cur_arg_info = &CG(active_op_array)->arg_info[CG(active_op_array)->num_args-1]; cur_arg_info->name = zend_new_interned_string(estrndup(varname->u.constant.value.str.val, varname->u.constant.value.str.len), varname->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->name_len = varname->u.constant.value.str.len; cur_arg_info->type_hint = 0; cur_arg_info->allow_null = 1; cur_arg_info->pass_by_reference = pass_by_reference; cur_arg_info->class_name = NULL; cur_arg_info->class_name_len = 0; if (class_type->op_type != IS_UNUSED) { cur_arg_info->allow_null = 0; if (class_type->u.constant.type != IS_NULL) { if (class_type->u.constant.type == IS_ARRAY) { cur_arg_info->type_hint = IS_ARRAY; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else if (Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Default value for parameters with array type hint can only be an array or NULL"); } } } else if (class_type->u.constant.type == IS_CALLABLE) { cur_arg_info->type_hint = IS_CALLABLE; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with callable type hint can only be NULL"); } } } else { cur_arg_info->type_hint = IS_OBJECT; if (ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_type->u.constant), Z_STRLEN(class_type->u.constant))) { zend_resolve_class_name(class_type, opline->extended_value, 1 TSRMLS_CC); } Z_STRVAL(class_type->u.constant) = (char*)zend_new_interned_string(class_type->u.constant.value.str.val, class_type->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->class_name = class_type->u.constant.value.str.val; cur_arg_info->class_name_len = class_type->u.constant.value.str.len; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with a class type hint can only be NULL"); } } } } } } /* }}} */ int zend_do_begin_function_call(znode *function_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { zend_function *function; char *lcname; char *is_compound = memchr(Z_STRVAL(function_name->u.constant), '\\', Z_STRLEN(function_name->u.constant)); zend_resolve_non_class_name(function_name, check_namespace TSRMLS_CC); if (check_namespace && CG(current_namespace) && !is_compound) { /* We assume we call function from the current namespace if it is not prefixed. */ /* In run-time PHP will check for function with full name and internal function with short name */ zend_do_begin_dynamic_function_call(function_name, 1 TSRMLS_CC); return 1; } lcname = zend_str_tolower_dup(function_name->u.constant.value.str.val, function_name->u.constant.value.str.len); if ((zend_hash_find(CG(function_table), lcname, function_name->u.constant.value.str.len+1, (void **) &function)==FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_FUNCTIONS) && (function->type == ZEND_INTERNAL_FUNCTION))) { zend_do_begin_dynamic_function_call(function_name, 0 TSRMLS_CC); efree(lcname); return 1; /* Dynamic */ } efree(function_name->u.constant.value.str.val); function_name->u.constant.value.str.val = lcname; zend_stack_push(&CG(function_call_stack), (void *) &function, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 0; } /* }}} */ void zend_do_begin_method_call(znode *left_bracket TSRMLS_DC) /* {{{ */ { zend_op *last_op; int last_op_number; unsigned char *ptr = NULL; zend_do_end_variable_parse(left_bracket, BP_VAR_R, 0 TSRMLS_CC); zend_do_begin_variable_parse(TSRMLS_C); last_op_number = get_next_op_number(CG(active_op_array))-1; last_op = &CG(active_op_array)->opcodes[last_op_number]; if ((last_op->op2_type == IS_CONST) && (Z_TYPE(CONSTANT(last_op->op2.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(last_op->op2.constant)) == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !zend_binary_strcasecmp(Z_STRVAL(CONSTANT(last_op->op2.constant)), Z_STRLEN(CONSTANT(last_op->op2.constant)), ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1)) { zend_error(E_COMPILE_ERROR, "Cannot call __clone() method on objects - use 'clone $obj' instead"); } if (last_op->opcode == ZEND_FETCH_OBJ_R) { if (last_op->op2_type == IS_CONST) { zval name; name = CONSTANT(last_op->op2.constant); if (!IS_INTERNED(Z_STRVAL(name))) { Z_STRVAL(name) = estrndup(Z_STRVAL(name), Z_STRLEN(name)); } FREE_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); last_op->op2.constant = zend_add_func_name_literal(CG(active_op_array), &name TSRMLS_CC); GET_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); } last_op->opcode = ZEND_INIT_METHOD_CALL; SET_UNUSED(last_op->result); Z_LVAL(left_bracket->u.constant) = ZEND_INIT_FCALL_BY_NAME; } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (left_bracket->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &left_bracket->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, left_bracket); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_do_clone(znode *result, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CLONE; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_begin_dynamic_function_call(znode *function_name, int ns_call TSRMLS_DC) /* {{{ */ { unsigned char *ptr = NULL; zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (ns_call) { /* In run-time PHP will check for function with full name and internal function with short name */ opline->opcode = ZEND_INIT_NS_FCALL_BY_NAME; SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_ns_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (function_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, function_name); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_resolve_non_class_name(znode *element_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; int len; zval **ns; char *lcname, *compound = memchr(Z_STRVAL(element_name->u.constant), '\\', Z_STRLEN(element_name->u.constant)); if (Z_STRVAL(element_name->u.constant)[0] == '\\') { /* name starts with \ so it is known and unambiguos, nothing to do here but shorten it */ memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+1, Z_STRLEN(element_name->u.constant)); --Z_STRLEN(element_name->u.constant); return; } if(!check_namespace) { return; } if (compound && CG(current_import)) { len = compound - Z_STRVAL(element_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(element_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(element_name->u.constant) -= len; memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+len, Z_STRLEN(element_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, element_name TSRMLS_CC); *element_name = tmp; efree(lcname); return; } efree(lcname); } if (CG(current_namespace)) { tmp = *element_name; Z_STRLEN(tmp.u.constant) = sizeof("\\")-1 + Z_STRLEN(element_name->u.constant) + Z_STRLEN_P(CG(current_namespace)); Z_STRVAL(tmp.u.constant) = (char *) emalloc(Z_STRLEN(tmp.u.constant)+1); memcpy(Z_STRVAL(tmp.u.constant), Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace))]), "\\", sizeof("\\")-1); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace)) + sizeof("\\")-1]), Z_STRVAL(element_name->u.constant), Z_STRLEN(element_name->u.constant)+1); STR_FREE(Z_STRVAL(element_name->u.constant)); *element_name = tmp; } } /* }}} */ void zend_resolve_class_name(znode *class_name, ulong fetch_type, int check_ns_name TSRMLS_DC) /* {{{ */ { char *compound; char *lcname; zval **ns; znode tmp; int len; compound = memchr(Z_STRVAL(class_name->u.constant), '\\', Z_STRLEN(class_name->u.constant)); if (compound) { /* This is a compound class name that contains namespace prefix */ if (Z_STRVAL(class_name->u.constant)[0] == '\\') { /* The STRING name has "\" prefix */ Z_STRLEN(class_name->u.constant) -= 1; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+1, Z_STRLEN(class_name->u.constant)+1); Z_STRVAL(class_name->u.constant) = erealloc( Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1); if (ZEND_FETCH_CLASS_DEFAULT != zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "'\\%s' is an invalid class name", Z_STRVAL(class_name->u.constant)); } } else { if (CG(current_import)) { len = compound - Z_STRVAL(class_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(class_name->u.constant) -= len; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+len, Z_STRLEN(class_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; efree(lcname); return; } efree(lcname); } /* Here name is not prefixed with \ and not imported */ if (CG(current_namespace)) { tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } } } else if (CG(current_import) || CG(current_namespace)) { /* this is a plain name (without \) */ lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns) == SUCCESS) { /* The given name is an import name. Substitute it. */ zval_dtor(&class_name->u.constant); class_name->u.constant = **ns; zval_copy_ctor(&class_name->u.constant); } else if (CG(current_namespace)) { /* plain name, no import - prepend current namespace to it */ tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } efree(lcname); } } /* }}} */ void zend_do_fetch_class(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { long fetch_class_op_number; zend_op *opline; if (class_name->op_type == IS_CONST && Z_TYPE(class_name->u.constant) == IS_STRING && Z_STRLEN(class_name->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_name->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } fetch_class_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CLASS; SET_UNUSED(opline->op1); opline->extended_value = ZEND_FETCH_CLASS_GLOBAL; CG(catch_begin) = fetch_class_op_number; if (class_name->op_type == IS_CONST) { int fetch_type; fetch_type = zend_get_class_fetch_type(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); switch (fetch_type) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: SET_UNUSED(opline->op2); opline->extended_value = fetch_type; zval_dtor(&class_name->u.constant); break; default: zend_resolve_class_name(class_name, opline->extended_value, 0 TSRMLS_CC); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_name->u.constant TSRMLS_CC); break; } } else { SET_NODE(opline->op2, class_name); } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; /* FIXME: Hack so that INIT_FCALL_BY_NAME still knows this is a class */ GET_NODE(result, opline->result); result->EA = opline->extended_value; } /* }}} */ void zend_do_label(znode *label TSRMLS_DC) /* {{{ */ { zend_label dest; if (!CG(context).labels) { ALLOC_HASHTABLE(CG(context).labels); zend_hash_init(CG(context).labels, 4, NULL, NULL, 0); } dest.brk_cont = CG(context).current_brk_cont; dest.opline_num = get_next_op_number(CG(active_op_array)); if (zend_hash_add(CG(context).labels, Z_STRVAL(label->u.constant), Z_STRLEN(label->u.constant) + 1, (void**)&dest, sizeof(zend_label), NULL) == FAILURE) { zend_error(E_COMPILE_ERROR, "Label '%s' already defined", Z_STRVAL(label->u.constant)); } /* Done with label now */ zval_dtor(&label->u.constant); } /* }}} */ void zend_resolve_goto_label(zend_op_array *op_array, zend_op *opline, int pass2 TSRMLS_DC) /* {{{ */ { zend_label *dest; long current, distance; zval *label; if (pass2) { label = opline->op2.zv; } else { label = &CONSTANT_EX(op_array, opline->op2.constant); } if (CG(context).labels == NULL || zend_hash_find(CG(context).labels, Z_STRVAL_P(label), Z_STRLEN_P(label)+1, (void**)&dest) == FAILURE) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; zend_error(E_COMPILE_ERROR, "'goto' to undefined label '%s'", Z_STRVAL_P(label)); } else { /* Label is not defined. Delay to pass 2. */ INC_BPC(op_array); return; } } opline->op1.opline_num = dest->opline_num; zval_dtor(label); Z_TYPE_P(label) = IS_NULL; /* Check that we are not moving into loop or switch */ current = opline->extended_value; for (distance = 0; current != dest->brk_cont; distance++) { if (current == -1) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; } zend_error(E_COMPILE_ERROR, "'goto' into loop or switch statement is disallowed"); } current = op_array->brk_cont_array[current].parent; } if (distance == 0) { /* Nothing to break out of, optimize to ZEND_JMP */ opline->opcode = ZEND_JMP; opline->extended_value = 0; SET_UNUSED(opline->op2); } else { /* Set real break distance */ ZVAL_LONG(label, distance); } if (pass2) { DEC_BPC(op_array); } } /* }}} */ void zend_do_goto(const znode *label TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_GOTO; opline->extended_value = CG(context).current_brk_cont; SET_UNUSED(opline->op1); SET_NODE(opline->op2, label); zend_resolve_goto_label(CG(active_op_array), opline, 0 TSRMLS_CC); } /* }}} */ void zend_release_labels(TSRMLS_D) /* {{{ */ { if (CG(context).labels) { zend_hash_destroy(CG(context).labels); FREE_HASHTABLE(CG(context).labels); } if (!zend_stack_is_empty(&CG(context_stack))) { zend_compiler_context *ctx; zend_stack_top(&CG(context_stack), (void**)&ctx); CG(context) = *ctx; zend_stack_del_top(&CG(context_stack)); } } /* }}} */ void zend_do_build_full_name(znode *result, znode *prefix, znode *name, int is_class_member TSRMLS_DC) /* {{{ */ { zend_uint length; if (!result) { result = prefix; } else { *result = *prefix; } if (is_class_member) { length = sizeof("::")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "::", sizeof("::")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("::")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } else { length = sizeof("\\")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "\\", sizeof("\\")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("\\")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } } /* }}} */ int zend_do_begin_class_member_function_call(znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { znode class_node; unsigned char *ptr = NULL; zend_op *opline; if (method_name->op_type == IS_CONST) { char *lcname = zend_str_tolower_dup(Z_STRVAL(method_name->u.constant), Z_STRLEN(method_name->u.constant)); if ((sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == Z_STRLEN(method_name->u.constant) && memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == 0) { zval_dtor(&method_name->u.constant); method_name->op_type = IS_UNUSED; } efree(lcname); } if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; opline = get_next_op(CG(active_op_array) TSRMLS_CC); } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->extended_value = class_node.EA ; } opline->opcode = ZEND_INIT_STATIC_METHOD_CALL; if (class_node.op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, &class_node); } if (method_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &method_name->u.constant TSRMLS_CC); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } } else { SET_NODE(opline->op2, method_name); } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 1; /* Dynamic */ } /* }}} */ void zend_do_end_function_call(znode *function_name, znode *result, const znode *argument_list, int is_method, int is_dynamic_fcall TSRMLS_DC) /* {{{ */ { zend_op *opline; if (is_method && function_name && function_name->op_type == IS_UNUSED) { /* clone */ if (Z_LVAL(argument_list->u.constant) != 0) { zend_error(E_WARNING, "Clone method does not require arguments"); } opline = &CG(active_op_array)->opcodes[Z_LVAL(function_name->u.constant)]; } else { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (!is_method && !is_dynamic_fcall && function_name->op_type==IS_CONST) { opline->opcode = ZEND_DO_FCALL; SET_NODE(opline->op1, function_name); CALCULATE_LITERAL_HASH(opline->op1.constant); GET_CACHE_SLOT(opline->op1.constant); } else { opline->opcode = ZEND_DO_FCALL_BY_NAME; SET_UNUSED(opline->op1); } } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(result, opline->result) ; SET_UNUSED(opline->op2); zend_stack_del_top(&CG(function_call_stack)); opline->extended_value = Z_LVAL(argument_list->u.constant); } /* }}} */ void zend_do_pass_param(znode *param, zend_uchar op, int offset TSRMLS_DC) /* {{{ */ { zend_op *opline; int original_op=op; zend_function **function_ptr_ptr, *function_ptr; int send_by_reference; int send_function = 0; zend_stack_top(&CG(function_call_stack), (void **) &function_ptr_ptr); function_ptr = *function_ptr_ptr; if (original_op == ZEND_SEND_REF) { if (function_ptr && function_ptr->common.function_name && function_ptr->common.type == ZEND_USER_FUNCTION && !ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed; " "If you would like to pass argument by reference, modify the declaration of %s().", function_ptr->common.function_name); } else { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed"); } return; } if (function_ptr) { if (ARG_MAY_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { if (param->op_type & (IS_VAR|IS_CV) && original_op != ZEND_SEND_VAL) { send_by_reference = 1; if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION | ZEND_ARG_SEND_SILENT; } } else { op = ZEND_SEND_VAL; send_by_reference = 0; } } else { send_by_reference = ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset) ? ZEND_ARG_SEND_BY_REF : 0; } } else { send_by_reference = 0; } if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION; } else if (op == ZEND_SEND_VAL && (param->op_type & (IS_VAR|IS_CV))) { op = ZEND_SEND_VAR_NO_REF; } if (op!=ZEND_SEND_VAR_NO_REF && send_by_reference==ZEND_ARG_SEND_BY_REF) { /* change to passing by reference */ switch (param->op_type) { case IS_VAR: case IS_CV: op = ZEND_SEND_REF; break; default: zend_error(E_COMPILE_ERROR, "Only variables can be passed by reference"); break; } } if (original_op == ZEND_SEND_VAR) { switch (op) { case ZEND_SEND_VAR_NO_REF: zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); break; case ZEND_SEND_VAR: if (function_ptr) { zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(param, BP_VAR_FUNC_ARG, offset TSRMLS_CC); } break; case ZEND_SEND_REF: zend_do_end_variable_parse(param, BP_VAR_W, 0 TSRMLS_CC); break; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (op == ZEND_SEND_VAR_NO_REF) { if (function_ptr) { opline->extended_value = ZEND_ARG_COMPILE_TIME_BOUND | send_by_reference | send_function; } else { opline->extended_value = send_function; } } else { if (function_ptr) { opline->extended_value = ZEND_DO_FCALL; } else { opline->extended_value = ZEND_DO_FCALL_BY_NAME; } } opline->opcode = op; SET_NODE(opline->op1, param); opline->op2.opline_num = offset; SET_UNUSED(opline->op2); } /* }}} */ static int generate_free_switch_expr(const zend_switch_entry *switch_entry TSRMLS_DC) /* {{{ */ { zend_op *opline; if (switch_entry->cond.op_type != IS_VAR && switch_entry->cond.op_type != IS_TMP_VAR) { return (switch_entry->cond.op_type == IS_UNUSED); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry->cond); SET_UNUSED(opline->op2); opline->extended_value = 0; return 0; } /* }}} */ static int generate_free_foreach_copy(const zend_op *foreach_copy TSRMLS_DC) /* {{{ */ { zend_op *opline; /* If we reach the seperator then stop applying the stack */ if (foreach_copy->result_type == IS_UNUSED && foreach_copy->op1_type == IS_UNUSED) { return 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->result_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->result); SET_UNUSED(opline->op2); opline->extended_value = 1; if (foreach_copy->op1_type != IS_UNUSED) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->op1_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->op1); SET_UNUSED(opline->op2); opline->extended_value = 0; } return 0; } /* }}} */ void zend_do_return(znode *expr, int do_end_vparse TSRMLS_DC) /* {{{ */ { zend_op *opline; int start_op_number, end_op_number; if (do_end_vparse) { if ((CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) && !zend_is_function_or_method_call(expr)) { zend_do_end_variable_parse(expr, BP_VAR_W, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(expr, BP_VAR_R, 0 TSRMLS_CC); } } start_op_number = get_next_op_number(CG(active_op_array)); #ifdef ZTS zend_stack_apply_with_argument(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_switch_expr TSRMLS_CC); zend_stack_apply_with_argument(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_foreach_copy TSRMLS_CC); #else zend_stack_apply(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_switch_expr); zend_stack_apply(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_foreach_copy); #endif end_op_number = get_next_op_number(CG(active_op_array)); while (start_op_number < end_op_number) { CG(active_op_array)->opcodes[start_op_number].extended_value |= EXT_TYPE_FREE_ON_RETURN; start_op_number++; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) ? ZEND_RETURN_BY_REF : ZEND_RETURN; if (expr) { SET_NODE(opline->op1, expr); if (do_end_vparse && zend_is_function_or_method_call(expr)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } } else { opline->op1_type = IS_CONST; LITERAL_NULL(opline->op1); } SET_UNUSED(opline->op2); } /* }}} */ static int zend_add_try_element(zend_uint try_op TSRMLS_DC) /* {{{ */ { int try_catch_offset = CG(active_op_array)->last_try_catch++; CG(active_op_array)->try_catch_array = erealloc(CG(active_op_array)->try_catch_array, sizeof(zend_try_catch_element)*CG(active_op_array)->last_try_catch); CG(active_op_array)->try_catch_array[try_catch_offset].try_op = try_op; return try_catch_offset; } /* }}} */ static void zend_add_catch_element(int offset, zend_uint catch_op TSRMLS_DC) /* {{{ */ { CG(active_op_array)->try_catch_array[offset].catch_op = catch_op; } /* }}} */ void zend_do_first_catch(znode *open_parentheses TSRMLS_DC) /* {{{ */ { open_parentheses->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_initialize_try_catch_element(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist jmp_list; zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); zend_add_catch_element(try_token->u.op.opline_num, get_next_op_number(CG(active_op_array)) TSRMLS_CC); } /* }}} */ void zend_do_mark_last_catch(const znode *first_catch, const znode *last_additional_catch TSRMLS_DC) /* {{{ */ { CG(active_op_array)->last--; zend_do_if_end(TSRMLS_C); if (last_additional_catch->u.op.opline_num == -1) { CG(active_op_array)->opcodes[first_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[first_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } else { CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_try(znode *try_token TSRMLS_DC) /* {{{ */ { try_token->u.op.opline_num = zend_add_try_element(get_next_op_number(CG(active_op_array)) TSRMLS_CC); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_catch(znode *try_token, znode *class_name, znode *catch_var, znode *first_catch TSRMLS_DC) /* {{{ */ { long catch_op_number; zend_op *opline; znode catch_class; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); catch_class = *class_name; } else { zend_error(E_COMPILE_ERROR, "Bad class name in the catch statement"); } catch_op_number = get_next_op_number(CG(active_op_array)); if (first_catch) { first_catch->u.op.opline_num = catch_op_number; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CATCH; opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &catch_class.u.constant TSRMLS_CC); opline->op2_type = IS_CV; opline->op2.var = lookup_cv(CG(active_op_array), catch_var->u.constant.value.str.val, catch_var->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(catch_var->u.constant) = (char*)CG(active_op_array)->vars[opline->op2.var].name; opline->result.num = 0; /* 1 means it's the last catch in the block */ try_token->u.op.opline_num = catch_op_number; } /* }}} */ void zend_do_end_catch(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); CG(active_op_array)->opcodes[try_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_throw(const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_THROW; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); } /* }}} */ ZEND_API void function_add_ref(zend_function *function) /* {{{ */ { if (function->type == ZEND_USER_FUNCTION) { zend_op_array *op_array = &function->op_array; (*op_array->refcount)++; if (op_array->static_variables) { HashTable *static_variables = op_array->static_variables; zval *tmp_zval; ALLOC_HASHTABLE(op_array->static_variables); zend_hash_init(op_array->static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(op_array->static_variables, static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_zval, sizeof(zval *)); } op_array->run_time_cache = NULL; } } /* }}} */ static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */ { zend_function *function; if (!ce->parent) { return; } /* You cannot change create_object */ ce->create_object = ce->parent->create_object; /* Inherit special functions if needed */ if (!ce->get_iterator) { ce->get_iterator = ce->parent->get_iterator; } if (!ce->iterator_funcs.funcs) { ce->iterator_funcs.funcs = ce->parent->iterator_funcs.funcs; } if (!ce->__get) { ce->__get = ce->parent->__get; } if (!ce->__set) { ce->__set = ce->parent->__set; } if (!ce->__unset) { ce->__unset = ce->parent->__unset; } if (!ce->__isset) { ce->__isset = ce->parent->__isset; } if (!ce->__call) { ce->__call = ce->parent->__call; } if (!ce->__callstatic) { ce->__callstatic = ce->parent->__callstatic; } if (!ce->__tostring) { ce->__tostring = ce->parent->__tostring; } if (!ce->clone) { ce->clone = ce->parent->clone; } if(!ce->serialize) { ce->serialize = ce->parent->serialize; } if(!ce->unserialize) { ce->unserialize = ce->parent->unserialize; } if (!ce->destructor) { ce->destructor = ce->parent->destructor; } if (ce->constructor) { if (ce->parent->constructor && ce->parent->constructor->common.fn_flags & ZEND_ACC_FINAL) { zend_error(E_ERROR, "Cannot override final %s::%s() with %s::%s()", ce->parent->name, ce->parent->constructor->common.function_name, ce->name, ce->constructor->common.function_name ); } return; } if (zend_hash_find(&ce->parent->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), (void **)&function)==SUCCESS) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), function, sizeof(zend_function), NULL); function_add_ref(function); } else { /* Don't inherit the old style constructor if we already have the new style constructor */ char *lc_class_name; char *lc_parent_class_name; lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); if (!zend_hash_exists(&ce->function_table, lc_class_name, ce->name_length+1)) { lc_parent_class_name = zend_str_tolower_dup(ce->parent->name, ce->parent->name_length); if (!zend_hash_exists(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1) && zend_hash_find(&ce->parent->function_table, lc_parent_class_name, ce->parent->name_length+1, (void **)&function)==SUCCESS) { if (function->common.fn_flags & ZEND_ACC_CTOR) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1, function, sizeof(zend_function), NULL); function_add_ref(function); } } efree(lc_parent_class_name); } efree(lc_class_name); } ce->constructor = ce->parent->constructor; } /* }}} */ char *zend_visibility_string(zend_uint fn_flags) /* {{{ */ { if (fn_flags & ZEND_ACC_PRIVATE) { return "private"; } if (fn_flags & ZEND_ACC_PROTECTED) { return "protected"; } if (fn_flags & ZEND_ACC_PUBLIC) { return "public"; } return ""; } /* }}} */ static void do_inherit_method(zend_function *function) /* {{{ */ { /* The class entry of the derived function intentionally remains the same * as that of the parent class. That allows us to know in which context * we're running, and handle private method calls properly. */ function_add_ref(function); } /* }}} */ static zend_bool zend_do_perform_implementation_check(const zend_function *fe, const zend_function *proto TSRMLS_DC) /* {{{ */ { zend_uint i; /* If it's a user function then arg_info == NULL means we don't have any parameters but * we still need to do the arg number checks. We are only willing to ignore this for internal * functions because extensions don't always define arg_info. */ if (!proto || (!proto->common.arg_info && proto->common.type != ZEND_USER_FUNCTION)) { return 1; } /* Checks for constructors only if they are declared in an interface, * or explicitly marked as abstract */ if ((fe->common.fn_flags & ZEND_ACC_CTOR) && ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)) { return 1; } /* check number of arguments */ if (proto->common.required_num_args < fe->common.required_num_args || proto->common.num_args > fe->common.num_args) { return 0; } if (fe->common.type != ZEND_USER_FUNCTION && (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) != 0 && (fe->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) == 0) { return 0; } /* by-ref constraints on return values are covariant */ if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) { return 0; } for (i=0; i < proto->common.num_args; i++) { if (ZEND_LOG_XOR(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)) { /* Only one has a type hint and the other one doesn't */ return 0; } if (fe->common.arg_info[i].class_name && strcasecmp(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)!=0) { const char *colon; if (fe->common.type != ZEND_USER_FUNCTION) { return 0; } else if (strchr(proto->common.arg_info[i].class_name, '\\') != NULL || (colon = zend_memrchr(fe->common.arg_info[i].class_name, '\\', fe->common.arg_info[i].class_name_len)) == NULL || strcasecmp(colon+1, proto->common.arg_info[i].class_name) != 0) { zend_class_entry **fe_ce, **proto_ce; int found, found2; found = zend_lookup_class(fe->common.arg_info[i].class_name, fe->common.arg_info[i].class_name_len, &fe_ce TSRMLS_CC); found2 = zend_lookup_class(proto->common.arg_info[i].class_name, proto->common.arg_info[i].class_name_len, &proto_ce TSRMLS_CC); /* Check for class alias */ if (found != SUCCESS || found2 != SUCCESS || (*fe_ce)->type == ZEND_INTERNAL_CLASS || (*proto_ce)->type == ZEND_INTERNAL_CLASS || *fe_ce != *proto_ce) { return 0; } } } if (fe->common.arg_info[i].type_hint != proto->common.arg_info[i].type_hint) { /* Incompatible type hint */ return 0; } /* by-ref constraints on arguments are invariant */ if (fe->common.arg_info[i].pass_by_reference != proto->common.arg_info[i].pass_by_reference) { return 0; } } if (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) { for (i=proto->common.num_args; i < fe->common.num_args; i++) { if (!fe->common.arg_info[i].pass_by_reference) { return 0; } } } return 1; } /* }}} */ #define REALLOC_BUF_IF_EXCEED(buf, offset, length, size) \ if (UNEXPECTED(offset - buf + size >= length)) { \ length += size + 1; \ buf = erealloc(buf, length); \ } static char * zend_get_function_declaration(zend_function *fptr TSRMLS_DC) /* {{{ */ { char *offset, *buf; zend_uint length = 1024; offset = buf = (char *)emalloc(length * sizeof(char)); if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { *(offset++) = '&'; *(offset++) = ' '; } if (fptr->common.scope) { memcpy(offset, fptr->common.scope->name, fptr->common.scope->name_length); offset += fptr->common.scope->name_length; *(offset++) = ':'; *(offset++) = ':'; } { size_t name_len = strlen(fptr->common.function_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, name_len); memcpy(offset, fptr->common.function_name, name_len); offset += name_len; } *(offset++) = '('; if (fptr->common.arg_info) { zend_uint i, required; zend_arg_info *arg_info = fptr->common.arg_info; required = fptr->common.required_num_args; for (i = 0; i < fptr->common.num_args;) { if (arg_info->class_name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->class_name_len); memcpy(offset, arg_info->class_name, arg_info->class_name_len); offset += arg_info->class_name_len; *(offset++) = ' '; } else if (arg_info->type_hint) { zend_uint type_name_len; char *type_name = zend_get_type_by_const(arg_info->type_hint); type_name_len = strlen(type_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, type_name_len); memcpy(offset, type_name, type_name_len); offset += type_name_len; *(offset++) = ' '; } if (arg_info->pass_by_reference) { *(offset++) = '&'; } *(offset++) = '$'; if (arg_info->name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->name_len); memcpy(offset, arg_info->name, arg_info->name_len); offset += arg_info->name_len; } else { zend_uint idx = i; memcpy(offset, "param", 5); offset += 5; do { *(offset++) = (char) (idx % 10) + '0'; idx /= 10; } while (idx > 0); } if (i >= required) { *(offset++) = ' '; *(offset++) = '='; *(offset++) = ' '; if (fptr->type == ZEND_USER_FUNCTION) { zend_op *precv = NULL; { zend_uint idx = i; zend_op *op = ((zend_op_array *)fptr)->opcodes; zend_op *end = op + ((zend_op_array *)fptr)->last; ++idx; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT) && op->op1.num == (long)idx) { precv = op; } ++op; } } if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) { zval *zv, zv_copy; int use_copy; ALLOC_ZVAL(zv); *zv = *precv->op2.zv; zval_copy_ctor(zv); INIT_PZVAL(zv); zval_update_constant_ex(&zv, (void*)1, fptr->common.scope TSRMLS_CC); if (Z_TYPE_P(zv) == IS_BOOL) { if (Z_LVAL_P(zv)) { memcpy(offset, "true", 4); offset += 4; } else { memcpy(offset, "false", 5); offset += 5; } } else if (Z_TYPE_P(zv) == IS_NULL) { memcpy(offset, "NULL", 4); offset += 4; } else if (Z_TYPE_P(zv) == IS_STRING) { *(offset++) = '\''; REALLOC_BUF_IF_EXCEED(buf, offset, length, MIN(Z_STRLEN_P(zv), 10)); memcpy(offset, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 10)); offset += MIN(Z_STRLEN_P(zv), 10); if (Z_STRLEN_P(zv) > 10) { *(offset++) = '.'; *(offset++) = '.'; *(offset++) = '.'; } *(offset++) = '\''; } else if (Z_TYPE_P(zv) == IS_ARRAY) { memcpy(offset, "Array", 5); offset += 5; } else { zend_make_printable_zval(zv, &zv_copy, &use_copy); REALLOC_BUF_IF_EXCEED(buf, offset, length, Z_STRLEN(zv_copy)); memcpy(offset, Z_STRVAL(zv_copy), Z_STRLEN(zv_copy)); offset += Z_STRLEN(zv_copy); if (use_copy) { zval_dtor(&zv_copy); } } zval_ptr_dtor(&zv); } } else { memcpy(offset, "NULL", 4); offset += 4; } } if (++i < fptr->common.num_args) { *(offset++) = ','; *(offset++) = ' '; } arg_info++; REALLOC_BUF_IF_EXCEED(buf, offset, length, 32); } } *(offset++) = ')'; *offset = '\0'; return buf; } /* }}} */ static void do_inheritance_check_on_method(zend_function *child, zend_function *parent TSRMLS_DC) /* {{{ */ { zend_uint child_flags; zend_uint parent_flags = parent->common.fn_flags; if ((parent->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && parent->common.fn_flags & ZEND_ACC_ABSTRACT && parent->common.scope != (child->common.prototype ? child->common.prototype->common.scope : child->common.scope) && child->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_IMPLEMENTED_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Can't inherit abstract function %s::%s() (previously declared abstract in %s)", parent->common.scope->name, child->common.function_name, child->common.prototype ? child->common.prototype->common.scope->name : child->common.scope->name); } if (parent_flags & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot override final method %s::%s()", ZEND_FN_SCOPE_NAME(parent), child->common.function_name); } child_flags = child->common.fn_flags; /* You cannot change from static to non static and vice versa. */ if ((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC)) { if (child->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot make non static method %s::%s() static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } else { zend_error(E_COMPILE_ERROR, "Cannot make static method %s::%s() non static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } } /* Disallow making an inherited method abstract. */ if ((child_flags & ZEND_ACC_ABSTRACT) && !(parent_flags & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Cannot make non abstract method %s::%s() abstract in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } if (parent_flags & ZEND_ACC_CHANGED) { child->common.fn_flags |= ZEND_ACC_CHANGED; } else { /* Prevent derived classes from restricting access that was available in parent classes */ if ((child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::%s() must be %s (as in class %s)%s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if (((child_flags & ZEND_ACC_PPP_MASK) < (parent_flags & ZEND_ACC_PPP_MASK)) && ((parent_flags & ZEND_ACC_PPP_MASK) & ZEND_ACC_PRIVATE)) { child->common.fn_flags |= ZEND_ACC_CHANGED; } } if (parent_flags & ZEND_ACC_PRIVATE) { child->common.prototype = NULL; } else if (parent_flags & ZEND_ACC_ABSTRACT) { child->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; child->common.prototype = parent; } else if (!(parent->common.fn_flags & ZEND_ACC_CTOR) || (parent->common.prototype && (parent->common.prototype->common.scope->ce_flags & ZEND_ACC_INTERFACE))) { /* ctors only have a prototype if it comes from an interface */ child->common.prototype = parent->common.prototype ? parent->common.prototype : parent; } if (child->common.prototype && (child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { if (!zend_do_perform_implementation_check(child, child->common.prototype TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s::%s() must be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_get_function_declaration(child->common.prototype TSRMLS_CC)); } } else if (EG(error_reporting) & E_STRICT || EG(user_error_handler)) { /* Check E_STRICT (or custom error handler) before the check so that we save some time */ if (!zend_do_perform_implementation_check(child, parent TSRMLS_CC)) { char *method_prototype = zend_get_function_declaration(child->common.prototype TSRMLS_CC); zend_error(E_STRICT, "Declaration of %s::%s() should be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, method_prototype); efree(method_prototype); } } } /* }}} */ static zend_bool do_inherit_method_check(HashTable *child_function_table, zend_function *parent, const zend_hash_key *hash_key, zend_class_entry *child_ce) /* {{{ */ { zend_uint parent_flags = parent->common.fn_flags; zend_function *child; TSRMLS_FETCH(); if (zend_hash_quick_find(child_function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child)==FAILURE) { if (parent_flags & (ZEND_ACC_ABSTRACT)) { child_ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } return 1; /* method doesn't exist in child, copy from parent */ } do_inheritance_check_on_method(child, parent TSRMLS_CC); return 0; } /* }}} */ static zend_bool do_inherit_property_access_check(HashTable *target_ht, zend_property_info *parent_info, const zend_hash_key *hash_key, zend_class_entry *ce) /* {{{ */ { zend_property_info *child_info; zend_class_entry *parent_ce = ce->parent; if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW)) { if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { child_info->flags |= ZEND_ACC_CHANGED; } else { zend_hash_quick_update(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, parent_info, sizeof(zend_property_info), (void **) &child_info); if(ce->type & ZEND_INTERNAL_CLASS) { zend_duplicate_property_info_internal(child_info); } else { zend_duplicate_property_info(child_info); } child_info->flags &= ~ZEND_ACC_PRIVATE; /* it's not private anymore */ child_info->flags |= ZEND_ACC_SHADOW; /* but it's a shadow of private */ } return 0; /* don't copy access information to child */ } if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { if ((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s", (parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", parent_ce->name, hash_key->arKey, (child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ce->name, hash_key->arKey); } if(parent_info->flags & ZEND_ACC_CHANGED) { child_info->flags |= ZEND_ACC_CHANGED; } if ((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ce->name, hash_key->arKey, zend_visibility_string(parent_info->flags), parent_ce->name, (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if ((child_info->flags & ZEND_ACC_STATIC) == 0) { Z_DELREF_P(ce->default_properties_table[parent_info->offset]); ce->default_properties_table[parent_info->offset] = ce->default_properties_table[child_info->offset]; ce->default_properties_table[child_info->offset] = NULL; child_info->offset = parent_info->offset; } return 0; /* Don't copy from parent */ } else { return 1; /* Copy from parent */ } } /* }}} */ static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce TSRMLS_CC) == FAILURE) { zend_error(E_CORE_ERROR, "Class %s could not implement interface %s", ce->name, iface->name); } if (ce == iface) { zend_error(E_ERROR, "Interface %s cannot implement itself", ce->name); } } /* }}} */ ZEND_API void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface TSRMLS_DC) /* {{{ */ { /* expects interface to be contained in ce's interface list already */ zend_uint i, ce_num, if_num = iface->num_interfaces; zend_class_entry *entry; if (if_num==0) { return; } ce_num = ce->num_interfaces; if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } /* Inherit the interfaces, only if they're not already inherited by the class */ while (if_num--) { entry = iface->interfaces[if_num]; for (i = 0; i < ce_num; i++) { if (ce->interfaces[i] == entry) { break; } } if (i == ce_num) { ce->interfaces[ce->num_interfaces++] = entry; } } /* and now call the implementing handlers */ while (ce_num < ce->num_interfaces) { do_implement_interface(ce, ce->interfaces[ce_num++] TSRMLS_CC); } } /* }}} */ #ifdef ZTS static void zval_internal_ctor(zval **p) /* {{{ */ { zval *orig_ptr = *p; ALLOC_ZVAL(*p); MAKE_COPY_ZVAL(&orig_ptr, *p); } /* }}} */ # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) (((parent_ce)->type != (ce)->type) ? zval_internal_ctor : zval_add_ref)) #else # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) zval_add_ref) #endif ZEND_API void zend_do_inheritance(zend_class_entry *ce, zend_class_entry *parent_ce TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; if ((ce->ce_flags & ZEND_ACC_INTERFACE) && !(parent_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ce->name, parent_ce->name); } if (parent_ce->ce_flags & ZEND_ACC_FINAL_CLASS) { zend_error(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ce->name, parent_ce->name); } ce->parent = parent_ce; /* Copy serialize/unserialize callbacks */ if (!ce->serialize) { ce->serialize = parent_ce->serialize; } if (!ce->unserialize) { ce->unserialize = parent_ce->unserialize; } /* Inherit interfaces */ zend_do_inherit_interfaces(ce, parent_ce TSRMLS_CC); /* Inherit properties */ if (parent_ce->default_properties_count) { int i = ce->default_properties_count + parent_ce->default_properties_count; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_properties_count) { while (i-- > parent_ce->default_properties_count) { ce->default_properties_table[i] = ce->default_properties_table[i - parent_ce->default_properties_count]; } } for (i = 0; i < parent_ce->default_properties_count; i++) { ce->default_properties_table[i] = parent_ce->default_properties_table[i]; if (ce->default_properties_table[i]) { #ifdef ZTS if (parent_ce->type != ce->type) { zval *p; ALLOC_ZVAL(p); MAKE_COPY_ZVAL(&ce->default_properties_table[i], p); ce->default_properties_table[i] = p; } else { Z_ADDREF_P(ce->default_properties_table[i]); } #else Z_ADDREF_P(ce->default_properties_table[i]); #endif } } ce->default_properties_count += parent_ce->default_properties_count; } if (parent_ce->type != ce->type) { /* User class extends internal class */ zend_update_class_constants(parent_ce TSRMLS_CC); if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = erealloc(ce->default_static_members_table, sizeof(void*) * i); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&CE_STATIC_MEMBERS(parent_ce)[i]); ce->default_static_members_table[i] = CE_STATIC_MEMBERS(parent_ce)[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; ce->static_members_table = ce->default_static_members_table; } } else { if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&parent_ce->default_static_members_table[i]); ce->default_static_members_table[i] = parent_ce->default_static_members_table[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } } for (zend_hash_internal_pointer_reset(&ce->properties_info); zend_hash_get_current_data(&ce->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->properties_info)) { if (property_info->ce == ce) { if (property_info->flags & ZEND_ACC_STATIC) { property_info->offset += parent_ce->default_static_members_count; } else { property_info->offset += parent_ce->default_properties_count; } } } zend_hash_merge_ex(&ce->properties_info, &parent_ce->properties_info, (copy_ctor_func_t) (ce->type & ZEND_INTERNAL_CLASS ? zend_duplicate_property_info_internal : zend_duplicate_property_info), sizeof(zend_property_info), (merge_checker_func_t) do_inherit_property_access_check, ce); zend_hash_merge(&ce->constants_table, &parent_ce->constants_table, zval_property_ctor(parent_ce, ce), NULL, sizeof(zval *), 0); zend_hash_merge_ex(&ce->function_table, &parent_ce->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_inherit_parent_constructor(ce); if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS && ce->type == ZEND_INTERNAL_CLASS) { ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } else if (!(ce->ce_flags & ZEND_ACC_IMPLEMENT_INTERFACES) && !(ce->ce_flags & ZEND_ACC_IMPLEMENT_TRAITS)) { /* The verification will be done in runtime by ZEND_VERIFY_ABSTRACT_CLASS */ zend_verify_abstract_class(ce TSRMLS_CC); } ce->ce_flags |= parent_ce->ce_flags & ZEND_HAS_STATIC_IN_METHODS; } /* }}} */ static zend_bool do_inherit_constant_check(HashTable *child_constants_table, const zval **parent_constant, const zend_hash_key *hash_key, const zend_class_entry *iface) /* {{{ */ { zval **old_constant; if (zend_hash_quick_find(child_constants_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**)&old_constant) == SUCCESS) { if (*old_constant != *parent_constant) { zend_error(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", hash_key->arKey, iface->name); } return 0; } return 1; } /* }}} */ static int do_interface_constant_check(zval **val TSRMLS_DC, int num_args, va_list args, const zend_hash_key *key) /* {{{ */ { zend_class_entry **iface = va_arg(args, zend_class_entry**); do_inherit_constant_check(&(*iface)->constants_table, (const zval **) val, key, *iface); return ZEND_HASH_APPLY_KEEP; } /* }}} */ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_iface_num = ce->num_interfaces; zend_uint parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0; for (i = 0; i < ce->num_interfaces; i++) { if (ce->interfaces[i] == NULL) { memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i)); i--; } else if (ce->interfaces[i] == iface) { if (i < parent_iface_num) { ignore = 1; } else { zend_error(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ce->name, iface->name); } } } if (ignore) { /* Check for attempt to redeclare interface constants */ zend_hash_apply_with_arguments(&ce->constants_table TSRMLS_CC, (apply_func_args_t) do_interface_constant_check, 1, &iface); } else { if (ce->num_interfaces >= current_iface_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } } ce->interfaces[ce->num_interfaces++] = iface; zend_hash_merge_ex(&ce->constants_table, &iface->constants_table, (copy_ctor_func_t) zval_add_ref, sizeof(zval *), (merge_checker_func_t) do_inherit_constant_check, iface); zend_hash_merge_ex(&ce->function_table, &iface->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_implement_interface(ce, iface TSRMLS_CC); zend_do_inherit_interfaces(ce, iface TSRMLS_CC); } } /* }}} */ ZEND_API void zend_do_implement_trait(zend_class_entry *ce, zend_class_entry *trait TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_trait_num = ce->num_traits; zend_uint parent_trait_num = ce->parent ? ce->parent->num_traits : 0; for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == NULL) { memmove(ce->traits + i, ce->traits + i + 1, sizeof(zend_class_entry*) * (--ce->num_traits - i)); i--; } else if (ce->traits[i] == trait) { if (i < parent_trait_num) { ignore = 1; } } } if (!ignore) { if (ce->num_traits >= current_trait_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->traits = (zend_class_entry **) realloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } else { ce->traits = (zend_class_entry **) erealloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } } ce->traits[ce->num_traits++] = trait; } } /* }}} */ static int zend_traits_merge_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { size_t current; size_t i; size_t count; HashTable* resulting_table; HashTable** function_tables; zend_class_entry *ce; size_t collision = 0; size_t abstract_solved = 0; zend_function* other_trait_fn; current = va_arg(args, size_t); /* index of current trait */ count = va_arg(args, size_t); resulting_table = va_arg(args, HashTable*); function_tables = va_arg(args, HashTable**); ce = va_arg(args, zend_class_entry*); for (i = 0; i < count; i++) { if (i == current) { continue; /* just skip this, cause its the table this function is applied on */ } if (zend_hash_quick_find(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&other_trait_fn) == SUCCESS) { /* if it is an abstract method, there is no collision */ if (other_trait_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* In case both are abstract, just check prototype, but need to do that in both directions */ if ( !zend_do_perform_implementation_check(fn, other_trait_fn TSRMLS_CC) || !zend_do_perform_implementation_check(other_trait_fn, fn TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s must be compatible with %s", //ZEND_FN_SCOPE_NAME(fn), fn->common.function_name, //::%s() zend_get_function_declaration(fn TSRMLS_CC), zend_get_function_declaration(other_trait_fn TSRMLS_CC)); } } else { /* otherwise, do the full check */ do_inheritance_check_on_method(fn, other_trait_fn TSRMLS_CC); } /* we can savely free and remove it from other table */ zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } else { /* if it is not an abstract method, there is still no collision */ /* if fn is an abstract method */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible. Here, we already know other_trait_fn cannot be abstract, full check ok. */ do_inheritance_check_on_method(other_trait_fn, fn TSRMLS_CC); /* just mark as solved, will be added if its own trait is processed */ abstract_solved = 1; } else { /* but else, we have a collision of non-abstract methods */ collision++; zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } } } if (collision) { zend_function* class_fn; /* make sure method is not already overridden in class */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&class_fn) == FAILURE || class_fn->common.scope != ce) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because there are collisions with other trait methods on %s", fn->common.function_name, ce->name); } zend_function_dtor(fn); } else if (abstract_solved) { zend_function_dtor(fn); } else { /* Add it to result function table */ if (zend_hash_quick_add(resulting_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, fn, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating resulting trait method table", fn->common.function_name); } } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ /* {{{ Originates from php_runkit_function_copy_ctor Duplicate structures in an op_array where necessary to make an outright duplicate */ static void zend_traits_duplicate_function(zend_function *fe, zend_class_entry *target_ce, char *newname TSRMLS_DC) { zend_literal *literals_copy; zend_compiled_variable *dupvars; zend_op *opcode_copy; zval class_name_zv; int class_name_literal; int i; int number_of_literals; if (fe->op_array.static_variables) { HashTable *tmpHash; ALLOC_HASHTABLE(tmpHash); zend_hash_init(tmpHash, zend_hash_num_elements(fe->op_array.static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_apply_with_arguments(fe->op_array.static_variables TSRMLS_CC, (apply_func_args_t)zval_copy_static_var, 1, tmpHash); fe->op_array.static_variables = tmpHash; } number_of_literals = fe->op_array.last_literal; literals_copy = (zend_literal*)emalloc(number_of_literals * sizeof(zend_literal)); for (i = 0; i < number_of_literals; i++) { literals_copy[i] = fe->op_array.literals[i]; zval_copy_ctor(&literals_copy[i].constant); } fe->op_array.literals = literals_copy; fe->op_array.refcount = emalloc(sizeof(zend_uint)); *(fe->op_array.refcount) = 1; if (fe->op_array.vars) { i = fe->op_array.last_var; dupvars = safe_emalloc(fe->op_array.last_var, sizeof(zend_compiled_variable), 0); while (i > 0) { i--; dupvars[i].name = estrndup(fe->op_array.vars[i].name, fe->op_array.vars[i].name_len); dupvars[i].name_len = fe->op_array.vars[i].name_len; dupvars[i].hash_value = fe->op_array.vars[i].hash_value; } fe->op_array.vars = dupvars; } else { fe->op_array.vars = NULL; } opcode_copy = safe_emalloc(sizeof(zend_op), fe->op_array.last, 0); for(i = 0; i < fe->op_array.last; i++) { opcode_copy[i] = fe->op_array.opcodes[i]; if (opcode_copy[i].op1_type != IS_CONST) { switch (opcode_copy[i].opcode) { case ZEND_GOTO: case ZEND_JMP: if (opcode_copy[i].op1.jmp_addr && opcode_copy[i].op1.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op1.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op1.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op1.jmp_addr - fe->op_array.opcodes); } break; } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op1.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op1.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op1.zv = &fe->op_array.literals[class_name_literal].constant; } } if (opcode_copy[i].op2_type != IS_CONST) { switch (opcode_copy[i].opcode) { case ZEND_JMPZ: case ZEND_JMPNZ: case ZEND_JMPZ_EX: case ZEND_JMPNZ_EX: case ZEND_JMP_SET: case ZEND_JMP_SET_VAR: if (opcode_copy[i].op2.jmp_addr && opcode_copy[i].op2.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op2.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op2.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op2.jmp_addr - fe->op_array.opcodes); } break; } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op2.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op2.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op2.zv = &fe->op_array.literals[class_name_literal].constant; } } } fe->op_array.opcodes = opcode_copy; fe->op_array.function_name = newname; /* was setting it to fe which does not work since fe is stack allocated and not a stable address */ /* fe->op_array.prototype = fe->op_array.prototype; */ if (fe->op_array.arg_info) { zend_arg_info *tmpArginfo; tmpArginfo = safe_emalloc(sizeof(zend_arg_info), fe->op_array.num_args, 0); for(i = 0; i < fe->op_array.num_args; i++) { tmpArginfo[i] = fe->op_array.arg_info[i]; tmpArginfo[i].name = estrndup(tmpArginfo[i].name, tmpArginfo[i].name_len); if (tmpArginfo[i].class_name) { tmpArginfo[i].class_name = estrndup(tmpArginfo[i].class_name, tmpArginfo[i].class_name_len); } } fe->op_array.arg_info = tmpArginfo; } fe->op_array.doc_comment = estrndup(fe->op_array.doc_comment, fe->op_array.doc_comment_len); fe->op_array.try_catch_array = (zend_try_catch_element*)estrndup((char*)fe->op_array.try_catch_array, sizeof(zend_try_catch_element) * fe->op_array.last_try_catch); fe->op_array.brk_cont_array = (zend_brk_cont_element*)estrndup((char*)fe->op_array.brk_cont_array, sizeof(zend_brk_cont_element) * fe->op_array.last_brk_cont); } /* }}} */ static void zend_add_magic_methods(zend_class_entry* ce, const char* mname, uint mname_len, zend_function* fe TSRMLS_DC) /* {{{ */ { if (!strncmp(mname, ZEND_CLONE_FUNC_NAME, mname_len)) { ce->clone = fe; fe->common.fn_flags |= ZEND_ACC_CLONE; } else if (!strncmp(mname, ZEND_CONSTRUCTOR_FUNC_NAME, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } else if (!strncmp(mname, ZEND_DESTRUCTOR_FUNC_NAME, mname_len)) { ce->destructor = fe; fe->common.fn_flags |= ZEND_ACC_DTOR; } else if (!strncmp(mname, ZEND_GET_FUNC_NAME, mname_len)) { ce->__get = fe; } else if (!strncmp(mname, ZEND_SET_FUNC_NAME, mname_len)) { ce->__set = fe; } else if (!strncmp(mname, ZEND_CALL_FUNC_NAME, mname_len)) { ce->__call = fe; } else if (!strncmp(mname, ZEND_UNSET_FUNC_NAME, mname_len)) { ce->__unset = fe; } else if (!strncmp(mname, ZEND_ISSET_FUNC_NAME, mname_len)) { ce->__isset = fe; } else if (!strncmp(mname, ZEND_CALLSTATIC_FUNC_NAME, mname_len)) { ce->__callstatic = fe; } else if (!strncmp(mname, ZEND_TOSTRING_FUNC_NAME, mname_len)) { ce->__tostring = fe; } else if (ce->name_length + 1 == mname_len) { char *lowercase_name = emalloc(ce->name_length + 1); zend_str_tolower_copy(lowercase_name, ce->name, ce->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, ce->name_length + 1, 1 TSRMLS_CC); if (!memcmp(mname, lowercase_name, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } str_efree(lowercase_name); } } /* }}} */ static int zend_traits_merge_functions_to_class(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zend_class_entry *ce = va_arg(args, zend_class_entry*); int add = 0; zend_function* existing_fn = NULL; zend_function fn_copy, *fn_copy_p; zend_function* prototype = NULL; /* is used to determine the prototype according to the inheritance chain */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &existing_fn) == FAILURE) { add = 1; /* not found */ } else if (existing_fn->common.scope != ce) { add = 1; /* or inherited from other class or interface */ } if (add) { zend_function* parent_function; if (ce->parent && zend_hash_quick_find(&ce->parent->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &parent_function) != FAILURE) { prototype = parent_function; /* ->common.fn_flags |= ZEND_ACC_ABSTRACT; */ /* we got that method in the parent class, and are going to override it, except, if the trait is just asking to have an abstract method implemented. */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* then we clean up an skip this method */ zend_function_dtor(fn); return ZEND_HASH_APPLY_REMOVE; } } fn->common.scope = ce; fn->common.prototype = prototype; if (prototype && (prototype->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT || prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { fn->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; } else if (fn->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT) { /* remove ZEND_ACC_IMPLEMENTED_ABSTRACT flag, think it shouldn't be copied to class */ fn->common.fn_flags = fn->common.fn_flags - ZEND_ACC_IMPLEMENTED_ABSTRACT; } /* check whether the trait method fullfills the inheritance requirements */ if (prototype) { do_inheritance_check_on_method(fn, prototype TSRMLS_CC); } /* one more thing: make sure we properly implement an abstract method */ if (existing_fn && existing_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { do_inheritance_check_on_method(fn, existing_fn TSRMLS_CC); } /* delete inherited fn if the function to be added is not abstract */ if (existing_fn && existing_fn->common.scope != ce && (fn->common.fn_flags & ZEND_ACC_ABSTRACT) == 0) { /* it is just a reference which was added to the subclass while doing the inheritance, so we can deleted now, and will add the overriding method afterwards. Except, if we try to add an abstract function, then we should not delete the inherited one */ zend_hash_quick_del(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h); } if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (fn->op_array.static_variables) { ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, ce, estrdup(fn->common.function_name) TSRMLS_CC); if (zend_hash_quick_update(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, &fn_copy, sizeof(zend_function), (void**)&fn_copy_p)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating class method table", hash_key->arKey); } zend_add_magic_methods(ce, hash_key->arKey, hash_key->nKeyLength, fn_copy_p TSRMLS_CC); zend_function_dtor(fn); } else { zend_function_dtor(fn); } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ static int zend_traits_copy_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { HashTable* target; zend_class_entry *target_ce; zend_trait_alias** aliases; HashTable* exclude_table; char* lcname; unsigned int fnname_len; zend_function fn_copy; void* dummy; size_t i = 0; target = va_arg(args, HashTable*); target_ce = va_arg(args, zend_class_entry*); aliases = va_arg(args, zend_trait_alias**); exclude_table = va_arg(args, HashTable*); fnname_len = strlen(fn->common.function_name); /* apply aliases which are qualified with a class name, there should not be any ambiguity */ if (aliases) { while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias != NULL && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && aliases[i]->trait_method->mname_len == fnname_len && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(aliases[i]->alias, aliases[i]->alias_len) TSRMLS_CC); /* if it is 0, no modifieres has been changed */ if (aliases[i]->modifiers) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } lcname = zend_str_tolower_dup(aliases[i]->alias, aliases[i]->alias_len); if (zend_hash_add(target, lcname, aliases[i]->alias_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add aliased trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } efree(lcname); /** Record the trait from which this alias was resolved. */ if (!aliases[i]->trait_method->ce) { aliases[i]->trait_method->ce = fn->common.scope; } } i++; } } lcname = zend_str_tolower_dup(fn->common.function_name, fnname_len); if (exclude_table == NULL || zend_hash_find(exclude_table, lcname, fnname_len, &dummy) == FAILURE) { /* is not in hashtable, thus, function is not to be excluded */ fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(fn->common.function_name, fnname_len) TSRMLS_CC); /* apply aliases which are not qualified by a class name, or which have not * alias name, just setting visibility */ if (aliases) { i = 0; while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias == NULL && aliases[i]->modifiers != 0 && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && (aliases[i]->trait_method->mname_len == fnname_len) && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); /** Record the trait from which this alias was resolved. */ if (!aliases[i]->trait_method->ce) { aliases[i]->trait_method->ce = fn->common.scope; } } i++; } } if (zend_hash_add(target, lcname, fnname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } } efree(lcname); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* Copies function table entries to target function table with applied aliasing */ static void zend_traits_copy_trait_function_table(HashTable *target, zend_class_entry *target_ce, HashTable *source, zend_trait_alias** aliases, HashTable* exclude_table TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_arguments(source TSRMLS_CC, (apply_func_args_t)zend_traits_copy_functions, 4, target, target_ce, aliases, exclude_table); } /* }}} */ static void zend_traits_init_trait_structures(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i, j = 0; zend_trait_precedence *cur_precedence; zend_trait_method_reference *cur_method_ref; char *lcname; zend_bool method_exists; /* resolve class references */ if (ce->trait_precedences) { i = 0; while ((cur_precedence = ce->trait_precedences[i])) { /** Resolve classes for all precedence operations. */ if (cur_precedence->exclude_from_classes) { cur_method_ref = cur_precedence->trait_method; cur_precedence->trait_method->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); /** Ensure that the prefered method is actually available. */ lcname = zend_str_tolower_dup(cur_method_ref->method_name, cur_method_ref->mname_len); method_exists = zend_hash_exists(&cur_method_ref->ce->function_table, lcname, cur_method_ref->mname_len + 1); efree(lcname); if (!method_exists) { zend_error(E_COMPILE_ERROR, "A precedence rule was defined for %s::%s but this method does not exist", cur_method_ref->ce->name, cur_method_ref->method_name); } /** With the other traits, we are more permissive. We do not give errors for those. This allows to be more defensive in such definitions. */ j = 0; while (cur_precedence->exclude_from_classes[j]) { char* class_name = (char*)cur_precedence->exclude_from_classes[j]; zend_uint name_length = strlen(class_name); cur_precedence->exclude_from_classes[j] = zend_fetch_class(class_name, name_length, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); efree(class_name); j++; } } i++; } } if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { /** For all aliases with an explicit class name, resolve the class now. */ if (ce->trait_aliases[i]->trait_method->class_name) { cur_method_ref = ce->trait_aliases[i]->trait_method; cur_method_ref->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); /** And, ensure that the referenced method is resolvable, too. */ lcname = zend_str_tolower_dup(cur_method_ref->method_name, cur_method_ref->mname_len); method_exists = zend_hash_exists(&cur_method_ref->ce->function_table, lcname, cur_method_ref->mname_len + 1); efree(lcname); if (!method_exists) { zend_error(E_COMPILE_ERROR, "An alias was defined for %s::%s but this method does not exist", cur_method_ref->ce->name, cur_method_ref->method_name); } } i++; } } } /* }}} */ static void zend_traits_compile_exclude_table(HashTable* exclude_table, zend_trait_precedence **precedences, zend_class_entry *trait) /* {{{ */ { size_t i = 0, j; if (!precedences) { return; } while (precedences[i]) { if (precedences[i]->exclude_from_classes) { j = 0; while (precedences[i]->exclude_from_classes[j]) { if (precedences[i]->exclude_from_classes[j] == trait) { zend_uint lcname_len = precedences[i]->trait_method->mname_len; char *lcname = zend_str_tolower_dup(precedences[i]->trait_method->method_name, lcname_len); if (zend_hash_add(exclude_table, lcname, lcname_len, NULL, 0, NULL) == FAILURE) { efree(lcname); zend_error(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", precedences[i]->trait_method->method_name, trait->name); } efree(lcname); } ++j; } } ++i; } } /* }}} */ static void zend_do_traits_method_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { HashTable** function_tables; HashTable* resulting_table; HashTable exclude_table; size_t i; /* prepare copies of trait function tables for combination */ function_tables = malloc(sizeof(HashTable*) * ce->num_traits); resulting_table = (HashTable *) malloc(sizeof(HashTable)); /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(resulting_table, 10, NULL, NULL, 1, 0); for (i = 0; i < ce->num_traits; i++) { function_tables[i] = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(function_tables[i], ce->traits[i]->function_table.nNumOfElements, NULL, NULL, 1, 0); if (ce->trait_precedences) { /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(&exclude_table, 2, NULL, NULL, 0, 0); zend_traits_compile_exclude_table(&exclude_table, ce->trait_precedences, ce->traits[i]); /* copies functions, applies defined aliasing, and excludes unused trait methods */ zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, &exclude_table TSRMLS_CC); zend_hash_graceful_destroy(&exclude_table); } else { zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, NULL TSRMLS_CC); } } /* now merge trait methods */ for (i = 0; i < ce->num_traits; i++) { zend_hash_apply_with_arguments(function_tables[i] TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions, 5, i, ce->num_traits, resulting_table, function_tables, ce); } /* Now the resulting_table contains all trait methods we would have to * add to the class in the following step the methods are inserted into the method table * if there is already a method with the same name it is replaced iff ce != fn.scope * --> all inherited methods are overridden, methods defined in the class are left untouched */ zend_hash_apply_with_arguments(resulting_table TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions_to_class, 1, ce); /* free temporary function tables */ for (i = 0; i < ce->num_traits; i++) { /* zend_hash_destroy(function_tables[i]); */ zend_hash_graceful_destroy(function_tables[i]); free(function_tables[i]); } free(function_tables); /* free temporary resulting table */ /* zend_hash_destroy(resulting_table); */ zend_hash_graceful_destroy(resulting_table); free(resulting_table); } /* }}} */ static zend_class_entry* find_first_definition(zend_class_entry *ce, size_t current_trait, const char* prop_name, int prop_name_length, ulong prop_hash, zend_class_entry *coliding_ce) /* {{{ */ { size_t i; zend_property_info *coliding_prop; for (i = 0; (i < current_trait) && (i < ce->num_traits); i++) { if (zend_hash_quick_find(&ce->traits[i]->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS) { return ce->traits[i]; } } return coliding_ce; } /* }}} */ static void zend_do_traits_property_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i; zend_property_info *property_info; zend_property_info *coliding_prop; zval compare_result; const char* prop_name; int prop_name_length; ulong prop_hash; const char* class_name_unused; zend_bool prop_found; zend_bool not_compatible; zval* prop_value; /* In the following steps the properties are inserted into the property table * for that, a very strict approach is applied: * - check for compatibility, if not compatible with any property in class -> fatal * - if compatible, then strict notice */ for (i = 0; i < ce->num_traits; i++) { for (zend_hash_internal_pointer_reset(&ce->traits[i]->properties_info); zend_hash_get_current_data(&ce->traits[i]->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->traits[i]->properties_info)) { /* first get the unmangeld name if necessary, * then check whether the property is already there */ if ((property_info->flags & ZEND_ACC_PPP_MASK) == ZEND_ACC_PUBLIC) { prop_hash = property_info->h; prop_name = property_info->name; prop_name_length = property_info->name_length; prop_found = zend_hash_quick_find(&ce->properties_info, property_info->name, property_info->name_length+1, property_info->h, (void **) &coliding_prop) == SUCCESS; } else { /* for private and protected we need to unmangle the names */ zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name_unused, &prop_name); prop_name_length = strlen(prop_name); prop_hash = zend_get_hash_value(prop_name, prop_name_length + 1); prop_found = zend_hash_quick_find(&ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS; } /* next: check for conflicts with current class */ if (prop_found) { if (coliding_prop->flags & ZEND_ACC_SHADOW) { /* this one is inherited, lets look it up in its own class */ zend_hash_quick_find(&coliding_prop->ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop); } if ( (coliding_prop->flags & (ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC)) == (property_info->flags & (ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC))) { /* flags are identical, now the value needs to be checked */ if (property_info->flags & ZEND_ACC_STATIC) { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_static_members_table[coliding_prop->offset], ce->traits[i]->default_static_members_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } else { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_properties_table[coliding_prop->offset], ce->traits[i]->default_properties_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } } else { /* the flags are not identical, thus, we assume properties are not compatible */ not_compatible = 1; } if (not_compatible) { zend_error(E_COMPILE_ERROR, "%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } else { zend_error(E_STRICT, "%s and %s define the same property ($%s) in the composition of %s. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } } /* property not found, so lets add it */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); zend_declare_property_ex(ce, prop_name, prop_name_length, prop_value, property_info->flags, property_info->doc_comment, property_info->doc_comment_len TSRMLS_CC); } } } /* }}} */ static void zend_do_check_for_inconsistent_traits_aliasing(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { int i = 0; zend_trait_alias* cur_alias; char* lc_method_name; if (ce->trait_aliases) { while (ce->trait_aliases[i]) { cur_alias = ce->trait_aliases[i]; /** The trait for this alias has not been resolved, this means, this alias was not applied. Abort with an error. */ if (!cur_alias->trait_method->ce) { if (cur_alias->alias) { /** Plain old inconsistency/typo/bug */ zend_error(E_COMPILE_ERROR, "An alias (%s) was defined for method %s(), but this method does not exist", cur_alias->alias, cur_alias->trait_method->method_name); } else { /** Here are two possible cases: 1) this is an attempt to modifiy the visibility of a method introduce as part of another alias. Since that seems to violate the DRY principle, we check against it and abort. 2) it is just a plain old inconsitency/typo/bug as in the case where alias is set. */ lc_method_name = zend_str_tolower_dup(cur_alias->trait_method->method_name, cur_alias->trait_method->mname_len); if (zend_hash_exists(&ce->function_table, lc_method_name, cur_alias->trait_method->mname_len+1)) { efree(lc_method_name); zend_error(E_COMPILE_ERROR, "The modifiers for the trait alias %s() need to be changed in the same statment in which the alias is defined. Error", cur_alias->trait_method->method_name); } else { efree(lc_method_name); zend_error(E_COMPILE_ERROR, "The modifiers of the trait method %s() are changed, but this method does not exist. Error", cur_alias->trait_method->method_name); } } } i++; } } } /* }}} */ ZEND_API void zend_do_bind_traits(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { if (ce->num_traits <= 0) { return; } /* complete initialization of trait strutures in ce */ zend_traits_init_trait_structures(ce TSRMLS_CC); /* first care about all methods to be flattened into the class */ zend_do_traits_method_binding(ce TSRMLS_CC); /* Aliases which have not been applied indicate typos/bugs. */ zend_do_check_for_inconsistent_traits_aliasing(ce TSRMLS_CC); /* then flatten the properties into it, to, mostly to notfiy developer about problems */ zend_do_traits_property_binding(ce TSRMLS_CC); /* verify that all abstract methods from traits have been implemented */ zend_verify_abstract_class(ce TSRMLS_CC); /* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */ if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { ce->ce_flags -= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } } /* }}} */ ZEND_API int do_bind_function(const zend_op_array *op_array, zend_op *opline, HashTable *function_table, zend_bool compile_time) /* {{{ */ { zend_function *function; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } zend_hash_quick_find(function_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void *) &function); if (zend_hash_quick_add(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), function, sizeof(zend_function), NULL)==FAILURE) { int error_level = compile_time ? E_COMPILE_ERROR : E_ERROR; zend_function *old_function; if (zend_hash_quick_find(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), (void *) &old_function)==SUCCESS && old_function->type == ZEND_USER_FUNCTION && old_function->op_array.last > 0) { zend_error(error_level, "Cannot redeclare %s() (previously declared in %s:%d)", function->common.function_name, old_function->op_array.filename, old_function->op_array.opcodes[0].lineno); } else { zend_error(error_level, "Cannot redeclare %s()", function->common.function_name); } return FAILURE; } else { (*function->op_array.refcount)++; function->op_array.static_variables = NULL; /* NULL out the unbound function */ return SUCCESS; } } /* }}} */ void zend_add_trait_precedence(znode *precedence_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_precedences, precedence_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_add_trait_alias(znode *alias_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_aliases, alias_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_prepare_reference(znode *result, znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { zend_trait_method_reference *method_ref = emalloc(sizeof(zend_trait_method_reference)); method_ref->ce = NULL; /* REM: There should not be a need for copying, zend_do_begin_class_declaration is also just using that string */ if (class_name) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); method_ref->class_name = Z_STRVAL(class_name->u.constant); method_ref->cname_len = Z_STRLEN(class_name->u.constant); } else { method_ref->class_name = NULL; method_ref->cname_len = 0; } method_ref->method_name = Z_STRVAL(method_name->u.constant); method_ref->mname_len = Z_STRLEN(method_name->u.constant); result->u.op.ptr = method_ref; result->op_type = IS_TMP_VAR; } /* }}} */ void zend_prepare_trait_alias(znode *result, znode *method_reference, znode *modifiers, znode *alias TSRMLS_DC) /* {{{ */ { zend_trait_alias *trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_alias->modifiers = Z_LVAL(modifiers->u.constant); if (Z_LVAL(modifiers->u.constant) == ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot use 'static' as method modifier"); return; } if (alias) { trait_alias->alias = Z_STRVAL(alias->u.constant); trait_alias->alias_len = Z_STRLEN(alias->u.constant); } else { trait_alias->alias = NULL; } trait_alias->function = NULL; result->u.op.ptr = trait_alias; } /* }}} */ void zend_prepare_trait_precedence(znode *result, znode *method_reference, znode *trait_list TSRMLS_DC) /* {{{ */ { zend_trait_precedence *trait_precedence = emalloc(sizeof(zend_trait_precedence)); trait_precedence->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_precedence->exclude_from_classes = (zend_class_entry**) trait_list->u.op.ptr; trait_precedence->function = NULL; result->u.op.ptr = trait_precedence; } /* }}} */ ZEND_API zend_class_entry *do_bind_class(const zend_op_array* op_array, const zend_op *opline, HashTable *class_table, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } if (zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce)==FAILURE) { zend_error(E_COMPILE_ERROR, "Internal Zend error - Missing class information for %s", Z_STRVAL_P(op1)); return NULL; } else { ce = *pce; } ce->refcount++; if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), &ce, sizeof(zend_class_entry *), NULL)==FAILURE) { ce->refcount--; if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return NULL; } else { if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLEMENT_INTERFACES))) { zend_verify_abstract_class(ce TSRMLS_CC); } return ce; } } /* }}} */ ZEND_API zend_class_entry *do_bind_inherited_class(const zend_op_array *op_array, const zend_op *opline, HashTable *class_table, zend_class_entry *parent_ce, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; int found_ce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } found_ce = zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce); if (found_ce == FAILURE) { if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", Z_STRVAL_P(op2)); } return NULL; } else { ce = *pce; } if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ce->name, parent_ce->name); } else if ((parent_ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ce->name, parent_ce->name); } zend_do_inheritance(ce, parent_ce TSRMLS_CC); ce->refcount++; /* Register the derived class */ if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), pce, sizeof(zend_class_entry *), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return ce; } /* }}} */ void zend_do_early_binding(TSRMLS_D) /* {{{ */ { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; HashTable *table; while (opline->opcode == ZEND_TICKS && opline > CG(active_op_array)->opcodes) { opline--; } switch (opline->opcode) { case ZEND_DECLARE_FUNCTION: if (do_bind_function(CG(active_op_array), opline, CG(function_table), 1) == FAILURE) { return; } table = CG(function_table); break; case ZEND_DECLARE_CLASS: if (do_bind_class(CG(active_op_array), opline, CG(class_table), 1 TSRMLS_CC) == NULL) { return; } table = CG(class_table); break; case ZEND_DECLARE_INHERITED_CLASS: { zend_op *fetch_class_opline = opline-1; zval *parent_name; zend_class_entry **pce; parent_name = &CONSTANT(fetch_class_opline->op2.constant); if ((zend_lookup_class(Z_STRVAL_P(parent_name), Z_STRLEN_P(parent_name), &pce TSRMLS_CC) == FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_CLASSES) && ((*pce)->type == ZEND_INTERNAL_CLASS))) { if (CG(compiler_options) & ZEND_COMPILE_DELAYED_BINDING) { zend_uint *opline_num = &CG(active_op_array)->early_binding; while (*opline_num != -1) { opline_num = &CG(active_op_array)->opcodes[*opline_num].result.opline_num; } *opline_num = opline - CG(active_op_array)->opcodes; opline->opcode = ZEND_DECLARE_INHERITED_CLASS_DELAYED; opline->result_type = IS_UNUSED; opline->result.opline_num = -1; } return; } if (do_bind_inherited_class(CG(active_op_array), opline, CG(class_table), *pce, 1 TSRMLS_CC) == NULL) { return; } /* clear unnecessary ZEND_FETCH_CLASS opcode */ zend_del_literal(CG(active_op_array), fetch_class_opline->op2.constant); MAKE_NOP(fetch_class_opline); table = CG(class_table); break; } case ZEND_VERIFY_ABSTRACT_CLASS: case ZEND_ADD_INTERFACE: case ZEND_ADD_TRAIT: case ZEND_BIND_TRAITS: /* We currently don't early-bind classes that implement interfaces */ /* Classes with traits are handled exactly the same, no early-bind here */ return; default: zend_error(E_COMPILE_ERROR, "Invalid binding type"); return; } zend_hash_quick_del(table, Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant)), Z_HASH_P(&CONSTANT(opline->op1.constant))); zend_del_literal(CG(active_op_array), opline->op1.constant); zend_del_literal(CG(active_op_array), opline->op2.constant); MAKE_NOP(opline); } /* }}} */ ZEND_API void zend_do_delayed_early_binding(const zend_op_array *op_array TSRMLS_DC) /* {{{ */ { if (op_array->early_binding != -1) { zend_bool orig_in_compilation = CG(in_compilation); zend_uint opline_num = op_array->early_binding; zend_class_entry **pce; CG(in_compilation) = 1; while (opline_num != -1) { if (zend_lookup_class(Z_STRVAL_P(op_array->opcodes[opline_num-1].op2.zv), Z_STRLEN_P(op_array->opcodes[opline_num-1].op2.zv), &pce TSRMLS_CC) == SUCCESS) { do_bind_inherited_class(op_array, &op_array->opcodes[opline_num], EG(class_table), *pce, 0 TSRMLS_CC); } opline_num = op_array->opcodes[opline_num].result.opline_num; } CG(in_compilation) = orig_in_compilation; } } /* }}} */ void zend_do_boolean_or_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_or_end(znode *result, const znode *expr1, const znode *expr2, znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_boolean_and_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_and_end(znode *result, const znode *expr1, const znode *expr2, const znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_do_while_begin(TSRMLS_D) /* {{{ */ { do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_do_while_end(const znode *do_token, const znode *expr_open_bracket, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ; SET_NODE(opline->op1, expr); opline->op2.opline_num = do_token->u.op.opline_num; SET_UNUSED(opline->op2); do_end_loop(expr_open_bracket->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_brk_cont(zend_uchar op, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->op1.opline_num = CG(context).current_brk_cont; SET_UNUSED(opline->op1); if (expr) { if (expr->op_type != IS_CONST) { zend_error(E_COMPILE_ERROR, "'%s' operator with non-constant operand is no longer supported", op == ZEND_BRK ? "break" : "continue"); } else if (Z_TYPE(expr->u.constant) != IS_LONG || Z_LVAL(expr->u.constant) < 1) { zend_error(E_COMPILE_ERROR, "'%s' operator accepts only positive numbers", op == ZEND_BRK ? "break" : "continue"); } SET_NODE(opline->op2, expr); } else { LITERAL_LONG(opline->op2, 1); opline->op2_type = IS_CONST; } } /* }}} */ void zend_do_switch_cond(const znode *cond TSRMLS_DC) /* {{{ */ { zend_switch_entry switch_entry; switch_entry.cond = *cond; switch_entry.default_case = -1; switch_entry.control_var = -1; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_switch_end(const znode *case_list TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); /* add code to jmp to default case */ if (switch_entry_ptr->default_case != -1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->op1.opline_num = switch_entry_ptr->default_case; } if (case_list->op_type != IS_UNUSED) { /* non-empty switch */ int next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* remember break/continue loop information */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; if (switch_entry_ptr->cond.op_type==IS_VAR || switch_entry_ptr->cond.op_type==IS_TMP_VAR) { /* emit free for the switch condition*/ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry_ptr->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_UNUSED(opline->op2); } if (switch_entry_ptr->cond.op_type == IS_CONST) { zval_dtor(&switch_entry_ptr->cond.u.constant); } zend_stack_del_top(&CG(switch_cond_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_case_before_statement(const znode *case_list, znode *case_token, const znode *case_expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); int next_op_number; zend_switch_entry *switch_entry_ptr; znode result; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); if (switch_entry_ptr->control_var == -1) { switch_entry_ptr->control_var = get_temporary_variable(CG(active_op_array)); } opline->opcode = ZEND_CASE; opline->result.var = switch_entry_ptr->control_var; opline->result_type = IS_TMP_VAR; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_NODE(opline->op2, case_expr); if (opline->op1_type == IS_CONST) { zval_copy_ctor(&CONSTANT(opline->op1.constant)); } GET_NODE(&result, opline->result); next_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, &result); SET_UNUSED(opline->op2); case_token->u.op.opline_num = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_case_after_statement(znode *result, const znode *case_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); result->u.op.opline_num = next_op_number; switch (CG(active_op_array)->opcodes[case_token->u.op.opline_num].opcode) { case ZEND_JMP: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); break; case ZEND_JMPZ: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); break; } } /* }}} */ void zend_do_default_before_statement(const znode *case_list, znode *default_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); default_token->u.op.opline_num = next_op_number; next_op_number = get_next_op_number(CG(active_op_array)); switch_entry_ptr->default_case = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_begin_class_declaration(const znode *class_token, znode *class_name, const znode *parent_class_name TSRMLS_DC) /* {{{ */ { zend_op *opline; int doing_inheritance = 0; zend_class_entry *new_class_entry; char *lcname; int error = 0; zval **ns_name, key; if (CG(active_class_entry)) { zend_error(E_COMPILE_ERROR, "Class declarations may not be nested"); return; } lcname = zend_str_tolower_dup(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); if (!(strcmp(lcname, "self") && strcmp(lcname, "parent"))) { efree(lcname); zend_error(E_COMPILE_ERROR, "Cannot use '%s' as class name as it is reserved", Z_STRVAL(class_name->u.constant)); } /* Class name must not conflict with import names */ if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns_name) == SUCCESS) { error = 1; } if (CG(current_namespace)) { /* Prefix class name with name of current namespace */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); class_name = &tmp; efree(lcname); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); } if (error) { char *tmp = zend_str_tolower_dup(Z_STRVAL_PP(ns_name), Z_STRLEN_PP(ns_name)); if (Z_STRLEN_PP(ns_name) != Z_STRLEN(class_name->u.constant) || memcmp(tmp, lcname, Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "Cannot declare class %s because the name is already in use", Z_STRVAL(class_name->u.constant)); } efree(tmp); } new_class_entry = emalloc(sizeof(zend_class_entry)); new_class_entry->type = ZEND_USER_CLASS; new_class_entry->name = zend_new_interned_string(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1, 1 TSRMLS_CC); new_class_entry->name_length = Z_STRLEN(class_name->u.constant); zend_initialize_class_data(new_class_entry, 1 TSRMLS_CC); new_class_entry->info.user.filename = zend_get_compiled_filename(TSRMLS_C); new_class_entry->info.user.line_start = class_token->u.op.opline_num; new_class_entry->ce_flags |= class_token->EA; if (parent_class_name && parent_class_name->op_type != IS_UNUSED) { switch (parent_class_name->EA) { case ZEND_FETCH_CLASS_SELF: zend_error(E_COMPILE_ERROR, "Cannot use 'self' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_PARENT: zend_error(E_COMPILE_ERROR, "Cannot use 'parent' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use 'static' as class name as it is reserved"); break; default: break; } doing_inheritance = 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, new_class_entry->name_length TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; if (doing_inheritance) { /* Make sure a trait does not try to extend a class */ if ((new_class_entry->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "A trait (%s) cannot extend a class", new_class_entry->name); } opline->extended_value = parent_class_name->u.op.var; opline->opcode = ZEND_DECLARE_INHERITED_CLASS; } else { opline->opcode = ZEND_DECLARE_CLASS; } LITERAL_STRINGL(opline->op2, lcname, new_class_entry->name_length, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); zend_hash_quick_update(CG(class_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &new_class_entry, sizeof(zend_class_entry *), NULL); CG(active_class_entry) = new_class_entry; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(&CG(implementing_class), opline->result); if (CG(doc_comment)) { CG(active_class_entry)->info.user.doc_comment = CG(doc_comment); CG(active_class_entry)->info.user.doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ static void do_verify_abstract_class(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_VERIFY_ABSTRACT_CLASS; SET_NODE(opline->op1, &CG(implementing_class)); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_class_declaration(const znode *class_token, const znode *parent_token TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); if (ce->constructor) { ce->constructor->common.fn_flags |= ZEND_ACC_CTOR; if (ce->constructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Constructor %s::%s() cannot be static", ce->name, ce->constructor->common.function_name); } } if (ce->destructor) { ce->destructor->common.fn_flags |= ZEND_ACC_DTOR; if (ce->destructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Destructor %s::%s() cannot be static", ce->name, ce->destructor->common.function_name); } } if (ce->clone) { ce->clone->common.fn_flags |= ZEND_ACC_CLONE; if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static", ce->name, ce->clone->common.function_name); } } ce->info.user.line_end = zend_get_compiled_lineno(TSRMLS_C); /* Check for traits and proceed like with interfaces. * The only difference will be a combined handling of them in the end. * Thus, we need another opcode here. */ if (ce->num_traits > 0) { zend_op *opline; ce->traits = NULL; ce->num_traits = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_TRAITS; /* opcode generation: */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BIND_TRAITS; SET_NODE(opline->op1, &CG(implementing_class)); } if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) && ((parent_token->op_type != IS_UNUSED) || (ce->num_interfaces > 0))) { zend_verify_abstract_class(ce TSRMLS_CC); if (ce->num_interfaces) { do_verify_abstract_class(TSRMLS_C); } } /* Inherit interfaces; reset number to zero, we need it for above check and * will restore it during actual implementation. * The ZEND_ACC_IMPLEMENT_INTERFACES flag disables double call to * zend_verify_abstract_class() */ if (ce->num_interfaces > 0) { ce->interfaces = NULL; ce->num_interfaces = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_INTERFACES; } CG(active_class_entry) = NULL; } /* }}} */ void zend_do_implements_interface(znode *interface_name TSRMLS_DC) /* {{{ */ { zend_op *opline; /* Traits can not implement interfaces */ if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface on '%s' since it is a Trait", Z_STRVAL(interface_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(interface_name->u.constant), Z_STRLEN(interface_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface name as it is reserved", Z_STRVAL(interface_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_INTERFACE; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(interface_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = (opline->extended_value & ~ZEND_FETCH_CLASS_MASK) | ZEND_FETCH_CLASS_INTERFACE; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &interface_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_interfaces++; } /* }}} */ void zend_do_implements_trait(znode *trait_name TSRMLS_DC) /* {{{ */ { zend_op *opline; if ((CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Cannot use traits inside of interfaces. %s is used in %s", Z_STRVAL(trait_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(trait_name->u.constant), Z_STRLEN(trait_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as trait name as it is reserved", Z_STRVAL(trait_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_TRAIT; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(trait_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = ZEND_FETCH_CLASS_TRAIT; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &trait_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_traits++; } /* }}} */ ZEND_API void zend_mangle_property_name(char **dest, int *dest_length, const char *src1, int src1_length, const char *src2, int src2_length, int internal) /* {{{ */ { char *prop_name; int prop_name_length; prop_name_length = 1 + src1_length + 1 + src2_length; prop_name = pemalloc(prop_name_length + 1, internal); prop_name[0] = '\0'; memcpy(prop_name + 1, src1, src1_length+1); memcpy(prop_name + 1 + src1_length + 1, src2, src2_length+1); *dest = prop_name; *dest_length = prop_name_length; } /* }}} */ static int zend_strnlen(const char* s, int maxlen) /* {{{ */ { int len = 0; while (*s++ && maxlen--) len++; return len; } /* }}} */ ZEND_API int zend_unmangle_property_name(const char *mangled_property, int len, const char **class_name, const char **prop_name) /* {{{ */ { int class_name_len; *class_name = NULL; if (mangled_property[0]!=0) { *prop_name = mangled_property; return SUCCESS; } if (len < 3 || mangled_property[1]==0) { zend_error(E_NOTICE, "Illegal member variable name"); *prop_name = mangled_property; return FAILURE; } class_name_len = zend_strnlen(mangled_property+1, --len - 1) + 1; if (class_name_len >= len || mangled_property[class_name_len]!=0) { zend_error(E_NOTICE, "Corrupt member variable name"); *prop_name = mangled_property; return FAILURE; } *class_name = mangled_property+1; *prop_name = (*class_name)+class_name_len; return SUCCESS; } /* }}} */ void zend_do_declare_property(const znode *var_name, const znode *value, zend_uint access_type TSRMLS_DC) /* {{{ */ { zval *property; zend_property_info *existing_property_info; char *comment = NULL; int comment_len = 0; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Interfaces may not include member variables"); } if (access_type & ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Properties cannot be declared abstract"); } if (access_type & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot declare property %s::$%s final, the final modifier is allowed only for methods and classes", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } if (zend_hash_find(&CG(active_class_entry)->properties_info, var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, (void **) &existing_property_info)==SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::$%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } ALLOC_ZVAL(property); if (value) { *property = value->u.constant; } else { INIT_PZVAL(property); Z_TYPE_P(property) = IS_NULL; } if (CG(doc_comment)) { comment = CG(doc_comment); comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } zend_declare_property_ex(CG(active_class_entry), zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len + 1, 0 TSRMLS_CC), var_name->u.constant.value.str.len, property, access_type, comment, comment_len TSRMLS_CC); efree(var_name->u.constant.value.str.val); } /* }}} */ void zend_do_declare_class_constant(znode *var_name, const znode *value TSRMLS_DC) /* {{{ */ { zval *property; const char *cname = NULL; int result; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed in class constants"); return; } if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Traits cannot have constants"); return; } ALLOC_ZVAL(property); *property = value->u.constant; cname = zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, 0 TSRMLS_CC); if (IS_INTERNED(cname)) { result = zend_hash_quick_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, INTERNED_HASH(cname), &property, sizeof(zval *), NULL); } else { result = zend_hash_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, &property, sizeof(zval *), NULL); } if (result == FAILURE) { FREE_ZVAL(property); zend_error(E_COMPILE_ERROR, "Cannot redefine class constant %s::%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } FREE_PNODE(var_name); if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_fetch_property(znode *result, znode *object, const znode *property TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (object->op_type == IS_CV) { if (object->u.op.var == CG(active_op_array)->this_var) { object->op_type = IS_UNUSED; /* this means $this for objects */ } } else if (fetch_list_ptr->count == 1) { zend_llist_element *le = fetch_list_ptr->head; zend_op *opline_ptr = (zend_op *) le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); SET_UNUSED(opline_ptr->op1); /* this means $this for objects */ SET_NODE(opline_ptr->op2, property); /* if it was usual fetch, we change it to object fetch */ switch (opline_ptr->opcode) { case ZEND_FETCH_W: opline_ptr->opcode = ZEND_FETCH_OBJ_W; break; case ZEND_FETCH_R: opline_ptr->opcode = ZEND_FETCH_OBJ_R; break; case ZEND_FETCH_RW: opline_ptr->opcode = ZEND_FETCH_OBJ_RW; break; case ZEND_FETCH_IS: opline_ptr->opcode = ZEND_FETCH_OBJ_IS; break; case ZEND_FETCH_UNSET: opline_ptr->opcode = ZEND_FETCH_OBJ_UNSET; break; case ZEND_FETCH_FUNC_ARG: opline_ptr->opcode = ZEND_FETCH_OBJ_FUNC_ARG; break; } if (opline_ptr->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline_ptr->op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline_ptr->op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op2.constant); } GET_NODE(result, opline_ptr->result); return; } } if (zend_is_function_or_method_call(object)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, object); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_OBJ_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, object); SET_NODE(opline.op2, property); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline.op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op2.constant); } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void zend_do_halt_compiler_register(TSRMLS_D) /* {{{ */ { char *name, *cfilename; char haltoff[] = "__COMPILER_HALT_OFFSET__"; int len, clen; if (CG(has_bracketed_namespaces) && CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "__HALT_COMPILER() can only be used from the outermost scope"); } cfilename = zend_get_compiled_filename(TSRMLS_C); clen = strlen(cfilename); zend_mangle_property_name(&name, &len, haltoff, sizeof(haltoff) - 1, cfilename, clen, 0); zend_register_long_constant(name, len+1, zend_get_scanned_file_offset(TSRMLS_C), CONST_CS, 0 TSRMLS_CC); pefree(name, 0); if (CG(in_namespace)) { zend_do_end_namespace(TSRMLS_C); } } /* }}} */ void zend_do_push_object(const znode *object TSRMLS_DC) /* {{{ */ { zend_stack_push(&CG(object_stack), object, sizeof(znode)); } /* }}} */ void zend_do_pop_object(znode *object TSRMLS_DC) /* {{{ */ { if (object) { znode *tmp; zend_stack_top(&CG(object_stack), (void **) &tmp); *object = *tmp; } zend_stack_del_top(&CG(object_stack)); } /* }}} */ void zend_do_begin_new_object(znode *new_token, znode *class_type TSRMLS_DC) /* {{{ */ { zend_op *opline; unsigned char *ptr = NULL; new_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_NEW; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, class_type); SET_UNUSED(opline->op2); zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(unsigned char *)); } /* }}} */ void zend_do_end_new_object(znode *result, const znode *new_token, const znode *argument_list TSRMLS_DC) /* {{{ */ { znode ctor_result; zend_do_end_function_call(NULL, &ctor_result, argument_list, 1, 0 TSRMLS_CC); zend_do_free(&ctor_result TSRMLS_CC); CG(active_op_array)->opcodes[new_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, CG(active_op_array)->opcodes[new_token->u.op.opline_num].result); } /* }}} */ static zend_constant* zend_get_ct_const(const zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = NULL; if (Z_STRVAL_P(const_name)[0] == '\\') { if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name), (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name)-1); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name), (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } } else if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)+1, (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name)+1, (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } if (c->flags & CONST_CT_SUBST) { return c; } if (all_internal_constants_substitution && (c->flags & CONST_PERSISTENT) && !(CG(compiler_options) & ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION) && Z_TYPE(c->value) != IS_CONSTANT && Z_TYPE(c->value) != IS_CONSTANT_ARRAY) { return c; } return NULL; } /* }}} */ static int zend_constant_ct_subst(znode *result, zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = zend_get_ct_const(const_name, all_internal_constants_substitution TSRMLS_CC); if (c) { zval_dtor(const_name); result->op_type = IS_CONST; result->u.constant = c->value; zval_copy_ctor(&result->u.constant); INIT_PZVAL(&result->u.constant); return 1; } return 0; } /* }}} */ void zend_do_fetch_constant(znode *result, znode *constant_container, znode *constant_name, int mode, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; zend_op *opline; int type; char *compound; ulong fetch_type = 0; if (constant_container) { switch (mode) { case ZEND_CT: /* this is a class constant */ type = zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant)); if (ZEND_FETCH_CLASS_STATIC == type) { zend_error(E_ERROR, "\"static::\" is not allowed in compile-time constants"); } else if (ZEND_FETCH_CLASS_DEFAULT == type) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } zend_do_build_full_name(NULL, constant_container, constant_name, 1 TSRMLS_CC); *result = *constant_container; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: if (constant_container->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant))) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } else { zend_do_fetch_class(&tmp, constant_container TSRMLS_CC); constant_container = &tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); if (constant_container->op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &constant_container->u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, constant_container); } SET_NODE(opline->op2, constant_name); CALCULATE_LITERAL_HASH(opline->op2.constant); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } GET_NODE(result, opline->result); break; } return; } /* namespace constant */ /* only one that did not contain \ from the start can be converted to string if unknown */ switch (mode) { case ZEND_CT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); /* this is a namespace constant, or an unprefixed constant */ if (zend_constant_ct_subst(result, &constant_name->u.constant, 0 TSRMLS_CC)) { break; } zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(!compound) { fetch_type |= IS_CONSTANT_UNQUALIFIED; } *result = *constant_name; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(zend_constant_ct_subst(result, &constant_name->u.constant, 1 TSRMLS_CC)) { break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; if (compound) { /* the name is unambiguous */ opline->extended_value = 0; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } else { opline->extended_value = IS_CONSTANT_UNQUALIFIED; if (CG(current_namespace)) { opline->extended_value |= IS_CONSTANT_IN_NAMESPACE; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 1 TSRMLS_CC); } else { opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } } GET_CACHE_SLOT(opline->op2.constant); break; } } /* }}} */ void zend_do_shell_exec(znode *result, const znode *cmd TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); switch (cmd->op_type) { case IS_CONST: case IS_TMP_VAR: opline->opcode = ZEND_SEND_VAL; break; default: opline->opcode = ZEND_SEND_VAR; break; } SET_NODE(opline->op1, cmd); opline->op2.opline_num = 0; opline->extended_value = ZEND_DO_FCALL; SET_UNUSED(opline->op2); /* FIXME: exception support not added to this op2 */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DO_FCALL; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; LITERAL_STRINGL(opline->op1, estrndup("shell_exec", sizeof("shell_exec")-1), sizeof("shell_exec")-1, 0); CALCULATE_LITERAL_HASH(opline->op1.constant); opline->op1_type = IS_CONST; GET_CACHE_SLOT(opline->op1.constant); opline->extended_value = 1; SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_init_array(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_ARRAY; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; GET_NODE(result, opline->result); if (expr) { SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } } else { SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_array_element(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_ARRAY_ELEMENT; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_static_array_element(znode *result, znode *offset, const znode *expr) /* {{{ */ { zval *element; ALLOC_ZVAL(element); *element = expr->u.constant; if (offset) { switch (offset->u.constant.type & IS_CONSTANT_TYPE_MASK) { case IS_CONSTANT: /* Ugly hack to denote that this value has a constant index */ Z_TYPE_P(element) |= IS_CONSTANT_INDEX; Z_STRVAL(offset->u.constant) = erealloc(Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+1] = Z_TYPE(offset->u.constant); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+2] = 0; zend_symtable_update(result->u.constant.value.ht, Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_STRING: zend_symtable_update(result->u.constant.value.ht, offset->u.constant.value.str.val, offset->u.constant.value.str.len+1, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_NULL: zend_symtable_update(Z_ARRVAL(result->u.constant), "", 1, &element, sizeof(zval *), NULL); break; case IS_LONG: case IS_BOOL: zend_hash_index_update(Z_ARRVAL(result->u.constant), Z_LVAL(offset->u.constant), &element, sizeof(zval *), NULL); break; case IS_DOUBLE: zend_hash_index_update(Z_ARRVAL(result->u.constant), zend_dval_to_lval(Z_DVAL(offset->u.constant)), &element, sizeof(zval *), NULL); break; case IS_CONSTANT_ARRAY: zend_error(E_ERROR, "Illegal offset type"); break; } } else { zend_hash_next_index_insert(Z_ARRVAL(result->u.constant), &element, sizeof(zval *), NULL); } } /* }}} */ void zend_do_add_list_element(const znode *element TSRMLS_DC) /* {{{ */ { list_llist_element lle; if (element) { zend_check_writable_variable(element); lle.var = *element; zend_llist_copy(&lle.dimensions, &CG(dimension_llist)); zend_llist_prepend_element(&CG(list_llist), &lle); } (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_new_list_begin(TSRMLS_D) /* {{{ */ { int current_dimension = 0; zend_llist_add_element(&CG(dimension_llist), &current_dimension); } /* }}} */ void zend_do_new_list_end(TSRMLS_D) /* {{{ */ { zend_llist_remove_tail(&CG(dimension_llist)); (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_list_init(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(list_stack), &CG(list_llist), sizeof(zend_llist)); zend_stack_push(&CG(list_stack), &CG(dimension_llist), sizeof(zend_llist)); zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_do_new_list_begin(TSRMLS_C); } /* }}} */ void zend_do_list_end(znode *result, znode *expr TSRMLS_DC) /* {{{ */ { zend_llist_element *le; zend_llist_element *dimension; zend_op *opline; znode last_container; le = CG(list_llist).head; while (le) { zend_llist *tmp_dimension_llist = &((list_llist_element *)le->data)->dimensions; dimension = tmp_dimension_llist->head; while (dimension) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (dimension == tmp_dimension_llist->head) { /* first */ last_container = *expr; switch (expr->op_type) { case IS_VAR: case IS_CV: opline->opcode = ZEND_FETCH_DIM_R; break; case IS_TMP_VAR: opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; case IS_CONST: /* fetch_dim_tmp_var will handle this bogus fetch */ zval_copy_ctor(&expr->u.constant); opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; } opline->extended_value |= ZEND_FETCH_ADD_LOCK; } else { opline->opcode = ZEND_FETCH_DIM_R; } opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, &last_container); opline->op2_type = IS_CONST; LITERAL_LONG(opline->op2, *((int *) dimension->data)); GET_NODE(&last_container, opline->result); dimension = dimension->next; } ((list_llist_element *) le->data)->value = last_container; zend_llist_destroy(&((list_llist_element *) le->data)->dimensions); zend_do_assign(result, &((list_llist_element *) le->data)->var, &((list_llist_element *) le->data)->value TSRMLS_CC); zend_do_free(result TSRMLS_CC); le = le->next; } zend_llist_destroy(&CG(dimension_llist)); zend_llist_destroy(&CG(list_llist)); *result = *expr; { zend_llist *p; /* restore previous lists */ zend_stack_top(&CG(list_stack), (void **) &p); CG(dimension_llist) = *p; zend_stack_del_top(&CG(list_stack)); zend_stack_top(&CG(list_stack), (void **) &p); CG(list_llist) = *p; zend_stack_del_top(&CG(list_stack)); } } /* }}} */ void zend_init_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = emalloc(sizeof(void*) * 2); list[0] = item; list[1] = NULL; *(void**)result = list; } /* }}} */ void zend_add_to_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = *(void**)result; size_t n = 0; while (list && list[n]) { n++; } list = erealloc(list, sizeof(void*) * (n+2)); list[n] = item; list[n+1] = NULL; *(void**)result = list; } /* }}} */ void zend_do_fetch_static_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zval *tmp; zend_op *opline; znode lval; znode result; ALLOC_ZVAL(tmp); if (static_assignment) { *tmp = static_assignment->u.constant; } else { INIT_ZVAL(*tmp); } if (!CG(active_op_array)->static_variables) { if (CG(active_op_array)->scope) { CG(active_op_array)->scope->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } ALLOC_HASHTABLE(CG(active_op_array)->static_variables); zend_hash_init(CG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } zend_hash_update(CG(active_op_array)->static_variables, varname->u.constant.value.str.val, varname->u.constant.value.str.len+1, &tmp, sizeof(zval *), NULL); if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (fetch_type == ZEND_FETCH_LEXICAL) ? ZEND_FETCH_R : ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_STATIC; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ if (fetch_type == ZEND_FETCH_LEXICAL) { znode dummy; zend_do_begin_variable_parse(TSRMLS_C); zend_do_assign(&dummy, &lval, &result TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } else { zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); } CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_fetch_lexical_variable(znode *varname, zend_bool is_ref TSRMLS_DC) /* {{{ */ { znode value; if (Z_STRLEN(varname->u.constant) == sizeof("this") - 1 && memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this") - 1) == 0) { zend_error(E_COMPILE_ERROR, "Cannot use $this as lexical variable"); return; } value.op_type = IS_CONST; ZVAL_NULL(&value.u.constant); Z_TYPE(value.u.constant) |= is_ref ? IS_LEXICAL_REF : IS_LEXICAL_VAR; Z_SET_REFCOUNT_P(&value.u.constant, 1); Z_UNSET_ISREF_P(&value.u.constant); zend_do_fetch_static_variable(varname, &value, is_ref ? ZEND_FETCH_STATIC : ZEND_FETCH_LEXICAL TSRMLS_CC); } /* }}} */ void zend_do_fetch_global_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zend_op *opline; znode lval; znode result; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = fetch_type; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_cast(znode *result, const znode *expr, int type TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CAST; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } /* }}} */ void zend_do_include_or_eval(int type, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_do_extended_fcall_begin(TSRMLS_C); { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INCLUDE_OR_EVAL; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } zend_do_extended_fcall_end(TSRMLS_C); } /* }}} */ void zend_do_indirect_references(znode *result, const znode *num_references, znode *variable TSRMLS_DC) /* {{{ */ { int i; zend_do_end_variable_parse(variable, BP_VAR_R, 0 TSRMLS_CC); for (i=1; i<num_references->u.constant.value.lval; i++) { fetch_simple_variable_ex(result, variable, 0, ZEND_FETCH_R TSRMLS_CC); *variable = *result; } zend_do_begin_variable_parse(TSRMLS_C); fetch_simple_variable(result, variable, 1 TSRMLS_CC); /* there is a chance someone is accessing $this */ if (CG(active_op_array)->scope && CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } /* }}} */ void zend_do_unset(const znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_UNSET_VAR; SET_NODE(opline->op1, variable); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); opline->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_UNSET: last_op->opcode = ZEND_UNSET_VAR; SET_UNUSED(last_op->result); break; case ZEND_FETCH_DIM_UNSET: last_op->opcode = ZEND_UNSET_DIM; SET_UNUSED(last_op->result); break; case ZEND_FETCH_OBJ_UNSET: last_op->opcode = ZEND_UNSET_OBJ; SET_UNUSED(last_op->result); break; } } } /* }}} */ void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_do_end_variable_parse(variable, BP_VAR_IS, 0 TSRMLS_CC); zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { last_op = get_next_op(CG(active_op_array) TSRMLS_CC); last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; SET_NODE(last_op->op1, variable); SET_UNUSED(last_op->op2); last_op->result.var = get_temporary_variable(CG(active_op_array)); last_op->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; break; case ZEND_FETCH_DIM_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_DIM_OBJ; break; case ZEND_FETCH_OBJ_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_PROP_OBJ; break; } } last_op->result_type = IS_TMP_VAR; last_op->extended_value |= type; GET_NODE(result, last_op->result); } /* }}} */ void zend_do_instanceof(znode *result, const znode *expr, const znode *class_znode, int type TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline->opcode == ZEND_FETCH_CLASS) { opline->extended_value |= ZEND_FETCH_CLASS_NO_AUTOLOAD; } } if (expr->op_type == IS_CONST) { zend_error(E_COMPILE_ERROR, "instanceof expects an object instance, constant given"); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INSTANCEOF; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_NODE(opline->op2, class_znode); GET_NODE(result, opline->result); } /* }}} */ void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_bool is_variable; zend_bool push_container = 0; zend_op dummy_opline; if (variable) { if (zend_is_function_or_method_call(array)) { is_variable = 0; } else { is_variable = 1; } /* save the location of FETCH_W instruction(s) */ open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); zend_do_end_variable_parse(array, BP_VAR_W, 0 TSRMLS_CC); if (CG(active_op_array)->last > 0 && CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) { /* Only lock the container if we are fetching from a real container and not $this */ if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1_type == IS_VAR) { CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK; push_container = 1; } } } else { is_variable = 0; open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* save the location of FE_RESET */ foreach_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* Preform array reset */ opline->opcode = ZEND_FE_RESET; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, array); SET_UNUSED(opline->op2); opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0; COPY_NODE(dummy_opline.result, opline->result); if (push_container) { COPY_NODE(dummy_opline.op1, CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1); } else { dummy_opline.op1_type = IS_UNUSED; } zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); /* save the location of FE_FETCH */ as_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FE_FETCH; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); COPY_NODE(opline->op1, dummy_opline.result); opline->extended_value = 0; SET_UNUSED(opline->op2); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_OP_DATA; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); } /* }}} */ void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC) /* {{{ */ { zend_op *opline; znode dummy, value_node; zend_bool assign_by_ref=0; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num]; if (key->op_type != IS_UNUSED) { znode *tmp; /* switch between the key and value... */ tmp = key; key = value; value = tmp; /* Mark extended_value in case both key and value are being used */ opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; } if ((key->op_type != IS_UNUSED) && (key->EA & ZEND_PARSED_REFERENCE_VARIABLE)) { zend_error(E_COMPILE_ERROR, "Key element cannot be a reference"); } if (value->EA & ZEND_PARSED_REFERENCE_VARIABLE) { assign_by_ref = 1; if (!(opline-1)->extended_value) { zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression"); } /* Mark extended_value for assign-by-reference */ opline->extended_value |= ZEND_FE_FETCH_BYREF; CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; } else { zend_op *foreach_copy; zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.op.opline_num]; zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.op.opline_num]; /* Change "write context" into "read context" */ fetch->extended_value = 0; /* reset ZEND_FE_RESET_VARIABLE */ while (fetch != end) { --fetch; if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } if (fetch->opcode == ZEND_SEPARATE) { MAKE_NOP(fetch); } else { fetch->opcode -= 3; /* FETCH_W -> FETCH_R */ } } /* prevent double SWITCH_FREE */ zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy); foreach_copy->op1_type = IS_UNUSED; } GET_NODE(&value_node, opline->result); if (assign_by_ref) { zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); /* Mark FE_FETCH as IS_VAR as it holds the data directly as a value */ zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC); } else { zend_do_assign(&dummy, value, &value_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } if (key->op_type != IS_UNUSED) { znode key_node; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num+1]; opline->result_type = IS_TMP_VAR; opline->result.opline_num = get_temporary_variable(CG(active_op_array)); GET_NODE(&key_node, opline->result); zend_do_assign(&dummy, key, &key_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_foreach_end(const znode *foreach_token, const znode *as_token TSRMLS_DC) /* {{{ */ { zend_op *container_ptr; zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = as_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_RESET */ CG(active_op_array)->opcodes[as_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_FETCH */ do_end_loop(as_token->u.op.opline_num, 1 TSRMLS_CC); zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr); generate_free_foreach_copy(container_ptr TSRMLS_CC); zend_stack_del_top(&CG(foreach_copy_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_declare_begin(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(declare_stack), &CG(declarables), sizeof(zend_declarables)); } /* }}} */ void zend_do_declare_stmt(znode *var, znode *val TSRMLS_DC) /* {{{ */ { if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "ticks", sizeof("ticks")-1)) { convert_to_long(&val->u.constant); CG(declarables).ticks = val->u.constant; } else if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "encoding", sizeof("encoding")-1)) { if ((Z_TYPE(val->u.constant) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Cannot use constants as encoding"); } /* * Check that the pragma comes before any opcodes. If the compilation * got as far as this, the previous portion of the script must have been * parseable according to the .ini script_encoding setting. We still * want to tell them to put declare() at the top. */ { int num = CG(active_op_array)->last; /* ignore ZEND_EXT_STMT and ZEND_TICKS */ while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Encoding declaration pragma must be the very first statement in the script"); } } if (CG(multibyte)) { const zend_encoding *new_encoding, *old_encoding; zend_encoding_filter old_input_filter; CG(encoding_declared) = 1; convert_to_string(&val->u.constant); new_encoding = zend_multibyte_fetch_encoding(val->u.constant.value.str.val TSRMLS_CC); if (!new_encoding) { zend_error(E_COMPILE_WARNING, "Unsupported encoding [%s]", val->u.constant.value.str.val); } else { old_input_filter = LANG_SCNG(input_filter); old_encoding = LANG_SCNG(script_encoding); zend_multibyte_set_filter(new_encoding TSRMLS_CC); /* need to re-scan if input filter changed */ if (old_input_filter != LANG_SCNG(input_filter) || (old_input_filter && new_encoding != old_encoding)) { zend_multibyte_yyinput_again(old_input_filter, old_encoding TSRMLS_CC); } } } else { zend_error(E_COMPILE_WARNING, "declare(encoding=...) ignored because Zend multibyte feature is turned off by settings"); } zval_dtor(&val->u.constant); } else { zend_error(E_COMPILE_WARNING, "Unsupported declare '%s'", var->u.constant.value.str.val); zval_dtor(&val->u.constant); } zval_dtor(&var->u.constant); } /* }}} */ void zend_do_declare_end(const znode *declare_token TSRMLS_DC) /* {{{ */ { zend_declarables *declarables; zend_stack_top(&CG(declare_stack), (void **) &declarables); /* We should restore if there was more than (current - start) - (ticks?1:0) opcodes */ if ((get_next_op_number(CG(active_op_array)) - declare_token->u.op.opline_num) - ((Z_LVAL(CG(declarables).ticks))?1:0)) { CG(declarables) = *declarables; } } /* }}} */ void zend_do_exit(znode *result, const znode *message TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXIT; SET_NODE(opline->op1, message); SET_UNUSED(opline->op2); result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_BOOL; Z_LVAL(result->u.constant) = 1; } /* }}} */ void zend_do_begin_silence(znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BEGIN_SILENCE; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); GET_NODE(strudel_token, opline->result); } /* }}} */ void zend_do_end_silence(const znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_END_SILENCE; SET_NODE(opline->op1, strudel_token); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_jmp_set(const znode *value, znode *jmp_token, znode *colon_token TSRMLS_DC) /* {{{ */ { int op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (value->op_type == IS_VAR || value->op_type == IS_CV) { opline->opcode = ZEND_JMP_SET_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_JMP_SET; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, value); SET_UNUSED(opline->op2); GET_NODE(colon_token, opline->result); jmp_token->u.op .opline_num = op_number; INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_jmp_set_else(znode *result, const znode *false_value, const znode *jmp_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, colon_token); if (colon_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].opcode = ZEND_JMP_SET_VAR; CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } opline->extended_value = 0; SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_qm_op(const znode *cond, znode *qm_token TSRMLS_DC) /* {{{ */ { int jmpz_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); SET_UNUSED(opline->op2); opline->op2.opline_num = jmpz_op_number; GET_NODE(qm_token, opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_qm_true(const znode *true_value, znode *qm_token, znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->opcodes[qm_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array))+1; /* jmp over the ZEND_JMP */ if (true_value->op_type == IS_VAR || true_value->op_type == IS_CV) { opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, true_value); SET_UNUSED(opline->op2); GET_NODE(qm_token, opline->result); colon_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_qm_false(znode *result, const znode *false_value, const znode *qm_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, qm_token); if (qm_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].opcode = ZEND_QM_ASSIGN_VAR; CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[colon_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, opline->result); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_extended_info(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_STMT; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_begin(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_BEGIN; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_end(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_END; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_ticks(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_TICKS; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->extended_value = Z_LVAL(CG(declarables).ticks); } /* }}} */ zend_bool zend_is_auto_global_quick(const char *name, uint name_len, ulong hashval TSRMLS_DC) /* {{{ */ { zend_auto_global *auto_global; ulong hash = hashval ? hashval : zend_hash_func(name, name_len+1); if (zend_hash_quick_find(CG(auto_globals), name, name_len+1, hash, (void **) &auto_global)==SUCCESS) { if (auto_global->armed) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } return 1; } return 0; } /* }}} */ zend_bool zend_is_auto_global(const char *name, uint name_len TSRMLS_DC) /* {{{ */ { return zend_is_auto_global_quick(name, name_len, 0 TSRMLS_CC); } /* }}} */ int zend_register_auto_global(const char *name, uint name_len, zend_bool jit, zend_auto_global_callback auto_global_callback TSRMLS_DC) /* {{{ */ { zend_auto_global auto_global; auto_global.name = zend_new_interned_string((char*)name, name_len + 1, 0 TSRMLS_CC); auto_global.name_len = name_len; auto_global.auto_global_callback = auto_global_callback; auto_global.jit = jit; return zend_hash_add(CG(auto_globals), name, name_len+1, &auto_global, sizeof(zend_auto_global), NULL); } /* }}} */ static int zend_auto_global_init(zend_auto_global *auto_global TSRMLS_DC) /* {{{ */ { if (auto_global->jit) { auto_global->armed = 1; } else if (auto_global->auto_global_callback) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } else { auto_global->armed = 0; } return 0; } /* }}} */ ZEND_API void zend_activate_auto_globals(TSRMLS_D) /* {{{ */ { zend_hash_apply(CG(auto_globals), (apply_func_t) zend_auto_global_init TSRMLS_CC); } /* }}} */ int zendlex(znode *zendlval TSRMLS_DC) /* {{{ */ { int retval; if (CG(increment_lineno)) { CG(zend_lineno)++; CG(increment_lineno) = 0; } again: Z_TYPE(zendlval->u.constant) = IS_LONG; retval = lex_scan(&zendlval->u.constant TSRMLS_CC); switch (retval) { case T_COMMENT: case T_DOC_COMMENT: case T_OPEN_TAG: case T_WHITESPACE: goto again; case T_CLOSE_TAG: if (LANG_SCNG(yy_text)[LANG_SCNG(yy_leng)-1] != '>') { CG(increment_lineno) = 1; } if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { goto again; } retval = ';'; /* implicit ; */ break; case T_OPEN_TAG_WITH_ECHO: retval = T_ECHO; break; case T_END_HEREDOC: efree(Z_STRVAL(zendlval->u.constant)); break; } INIT_PZVAL(&zendlval->u.constant); zendlval->op_type = IS_CONST; return retval; } /* }}} */ ZEND_API void zend_initialize_class_data(zend_class_entry *ce, zend_bool nullify_handlers TSRMLS_DC) /* {{{ */ { zend_bool persistent_hashes = (ce->type == ZEND_INTERNAL_CLASS) ? 1 : 0; dtor_func_t zval_ptr_dtor_func = ((persistent_hashes) ? ZVAL_INTERNAL_PTR_DTOR : ZVAL_PTR_DTOR); ce->refcount = 1; ce->ce_flags = 0; ce->default_properties_table = NULL; ce->default_static_members_table = NULL; zend_hash_init_ex(&ce->properties_info, 0, NULL, (dtor_func_t) (persistent_hashes ? zend_destroy_property_info_internal : zend_destroy_property_info), persistent_hashes, 0); zend_hash_init_ex(&ce->constants_table, 0, NULL, zval_ptr_dtor_func, persistent_hashes, 0); zend_hash_init_ex(&ce->function_table, 0, NULL, ZEND_FUNCTION_DTOR, persistent_hashes, 0); if (ce->type == ZEND_INTERNAL_CLASS) { #ifdef ZTS int n = zend_hash_num_elements(CG(class_table)); if (CG(static_members_table) && n >= CG(last_static_member)) { /* Support for run-time declaration: dl() */ CG(last_static_member) = n+1; CG(static_members_table) = realloc(CG(static_members_table), (n+1)*sizeof(zval**)); CG(static_members_table)[n] = NULL; } ce->static_members_table = (zval**)(zend_intptr_t)n; #else ce->static_members_table = NULL; #endif } else { ce->static_members_table = ce->default_static_members_table; ce->info.user.doc_comment = NULL; ce->info.user.doc_comment_len = 0; } ce->default_properties_count = 0; ce->default_static_members_count = 0; if (nullify_handlers) { ce->constructor = NULL; ce->destructor = NULL; ce->clone = NULL; ce->__get = NULL; ce->__set = NULL; ce->__unset = NULL; ce->__isset = NULL; ce->__call = NULL; ce->__callstatic = NULL; ce->__tostring = NULL; ce->create_object = NULL; ce->get_iterator = NULL; ce->iterator_funcs.funcs = NULL; ce->interface_gets_implemented = NULL; ce->get_static_method = NULL; ce->parent = NULL; ce->num_interfaces = 0; ce->interfaces = NULL; ce->num_traits = 0; ce->traits = NULL; ce->trait_aliases = NULL; ce->trait_precedences = NULL; ce->serialize = NULL; ce->unserialize = NULL; ce->serialize_func = NULL; ce->unserialize_func = NULL; if (ce->type == ZEND_INTERNAL_CLASS) { ce->info.internal.module = NULL; ce->info.internal.builtin_functions = NULL; } } } /* }}} */ int zend_get_class_fetch_type(const char *class_name, uint class_name_len) /* {{{ */ { if ((class_name_len == sizeof("self")-1) && !memcmp(class_name, "self", sizeof("self")-1)) { return ZEND_FETCH_CLASS_SELF; } else if ((class_name_len == sizeof("parent")-1) && !memcmp(class_name, "parent", sizeof("parent")-1)) { return ZEND_FETCH_CLASS_PARENT; } else if ((class_name_len == sizeof("static")-1) && !memcmp(class_name, "static", sizeof("static")-1)) { return ZEND_FETCH_CLASS_STATIC; } else { return ZEND_FETCH_CLASS_DEFAULT; } } /* }}} */ ZEND_API const char* zend_get_compiled_variable_name(const zend_op_array *op_array, zend_uint var, int* name_len) /* {{{ */ { if (name_len) { *name_len = op_array->vars[var].name_len; } return op_array->vars[var].name; } /* }}} */ void zend_do_build_namespace_name(znode *result, znode *prefix, znode *name TSRMLS_DC) /* {{{ */ { if (prefix) { *result = *prefix; if (Z_TYPE(result->u.constant) == IS_STRING && Z_STRLEN(result->u.constant) == 0) { /* namespace\ */ if (CG(current_namespace)) { znode tmp; zval_dtor(&result->u.constant); tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(result, NULL, &tmp TSRMLS_CC); } } } else { result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_STRING; Z_STRVAL(result->u.constant) = NULL; Z_STRLEN(result->u.constant) = 0; } /* prefix = result */ zend_do_build_full_name(NULL, result, name, 0 TSRMLS_CC); } /* }}} */ void zend_do_begin_namespace(const znode *name, zend_bool with_bracket TSRMLS_DC) /* {{{ */ { char *lcname; /* handle mixed syntax declaration or nested namespaces */ if (!CG(has_bracketed_namespaces)) { if (CG(current_namespace)) { /* previous namespace declarations were unbracketed */ if (with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } } } else { /* previous namespace declarations were bracketed */ if (!with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } else if (CG(current_namespace) || CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "Namespace declarations cannot be nested"); } } if (((!with_bracket && !CG(current_namespace)) || (with_bracket && !CG(has_bracketed_namespaces))) && CG(active_op_array)->last > 0) { /* ignore ZEND_EXT_STMT and ZEND_TICKS */ int num = CG(active_op_array)->last; while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Namespace declaration statement has to be the very first statement in the script"); } } CG(in_namespace) = 1; if (with_bracket) { CG(has_bracketed_namespaces) = 1; } if (name) { lcname = zend_str_tolower_dup(Z_STRVAL(name->u.constant), Z_STRLEN(name->u.constant)); if (((Z_STRLEN(name->u.constant) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN(name->u.constant) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as namespace name", Z_STRVAL(name->u.constant)); } efree(lcname); if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); } else { ALLOC_ZVAL(CG(current_namespace)); } *CG(current_namespace) = name->u.constant; } else { if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_use(znode *ns_name, znode *new_name, int is_global TSRMLS_DC) /* {{{ */ { char *lcname; zval *name, *ns, tmp; zend_bool warn = 0; zend_class_entry **pce; if (!CG(current_import)) { CG(current_import) = emalloc(sizeof(HashTable)); zend_hash_init(CG(current_import), 0, NULL, ZVAL_PTR_DTOR, 0); } ALLOC_ZVAL(ns); *ns = ns_name->u.constant; if (new_name) { name = &new_name->u.constant; } else { const char *p; /* The form "use A\B" is eqivalent to "use A\B as B". So we extract the last part of compound name to use as a new_name */ name = &tmp; p = zend_memrchr(Z_STRVAL_P(ns), '\\', Z_STRLEN_P(ns)); if (p) { ZVAL_STRING(name, p+1, 1); } else { *name = *ns; zval_copy_ctor(name); warn = !is_global && !CG(current_namespace); } } lcname = zend_str_tolower_dup(Z_STRVAL_P(name), Z_STRLEN_P(name)); if (((Z_STRLEN_P(name) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN_P(name) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because '%s' is a special class name", Z_STRVAL_P(ns), Z_STRVAL_P(name), Z_STRVAL_P(name)); } if (CG(current_namespace)) { /* Prefix import name with current namespace name to avoid conflicts with classes */ char *c_ns_name = emalloc(Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) + 1); zend_str_tolower_copy(c_ns_name, Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); c_ns_name[Z_STRLEN_P(CG(current_namespace))] = '\\'; memcpy(c_ns_name+Z_STRLEN_P(CG(current_namespace))+1, lcname, Z_STRLEN_P(name)+1); if (zend_hash_exists(CG(class_table), c_ns_name, Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name)+1)) { char *tmp2 = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) || memcmp(tmp2, c_ns_name, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(tmp2); } efree(c_ns_name); } else if (zend_hash_find(CG(class_table), lcname, Z_STRLEN_P(name)+1, (void**)&pce) == SUCCESS && (*pce)->type == ZEND_USER_CLASS && (*pce)->info.user.filename == CG(compiled_filename)) { char *c_tmp = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(name) || memcmp(c_tmp, lcname, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(c_tmp); } if (zend_hash_add(CG(current_import), lcname, Z_STRLEN_P(name)+1, &ns, sizeof(zval*), NULL) != SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } if (warn) { if (!strcmp(Z_STRVAL_P(name), "strict")) { zend_error(E_COMPILE_ERROR, "You seem to be trying to use a different language..."); } zend_error(E_WARNING, "The use statement with non-compound name '%s' has no effect", Z_STRVAL_P(name)); } efree(lcname); zval_dtor(name); } /* }}} */ void zend_do_declare_constant(znode *name, znode *value TSRMLS_DC) /* {{{ */ { zend_op *opline; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed as constants"); } if (zend_get_ct_const(&name->u.constant, 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare constant '%s'", Z_STRVAL(name->u.constant)); } if (CG(current_namespace)) { /* Prefix constant name with name of current namespace, lowercased */ znode tmp; tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); Z_STRVAL(tmp.u.constant) = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), Z_STRLEN(tmp.u.constant)); zend_do_build_namespace_name(&tmp, &tmp, name TSRMLS_CC); *name = tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DECLARE_CONST; SET_UNUSED(opline->result); SET_NODE(opline->op1, name); SET_NODE(opline->op2, value); } /* }}} */ void zend_verify_namespace(TSRMLS_D) /* {{{ */ { if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "No code may exist outside of namespace {}"); } } /* }}} */ void zend_do_end_namespace(TSRMLS_D) /* {{{ */ { CG(in_namespace) = 0; if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_end_compilation(TSRMLS_D) /* {{{ */ { CG(has_bracketed_namespaces) = 0; zend_do_end_namespace(TSRMLS_C); } /* }}} */ /* {{{ zend_dirname Returns directory name component of path */ ZEND_API size_t zend_dirname(char *path, size_t len) { register char *end = path + len - 1; unsigned int len_adjust = 0; #ifdef PHP_WIN32 /* Note that on Win32 CWD is per drive (heritage from CP/M). * This means dirname("c:foo") maps to "c:." or "c:" - which means CWD on C: drive. */ if ((2 <= len) && isalpha((int)((unsigned char *)path)[0]) && (':' == path[1])) { /* Skip over the drive spec (if any) so as not to change */ path += 2; len_adjust += 2; if (2 == len) { /* Return "c:" on Win32 for dirname("c:"). * It would be more consistent to return "c:." * but that would require making the string *longer*. */ return len; } } #elif defined(NETWARE) /* * Find the first occurence of : from the left * move the path pointer to the position just after : * increment the len_adjust to the length of path till colon character(inclusive) * If there is no character beyond : simple return len */ char *colonpos = NULL; colonpos = strchr(path, ':'); if (colonpos != NULL) { len_adjust = ((colonpos - path) + 1); path += len_adjust; if (len_adjust == len) { return len; } } #endif if (len == 0) { /* Illegal use of this function */ return 0; } /* Strip trailing slashes */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { /* The path only contained slashes */ path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } /* Strip filename */ while (end >= path && !IS_SLASH_P(end)) { end--; } if (end < path) { /* No slash found, therefore return '.' */ #ifdef NETWARE if (len_adjust == 0) { path[0] = '.'; path[1] = '\0'; return 1; /* only one character */ } else { path[0] = '\0'; return len_adjust; } #else path[0] = '.'; path[1] = '\0'; return 1 + len_adjust; #endif } /* Strip slashes which came before the file name */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } *(end+1) = '\0'; return (size_t)(end + 1 - path) + len_adjust; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-11-23-eca88d3064-db0888dfc1.c
manybugs_data_74
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2012 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Rasmus Lerdorf <[email protected]> | | Jani Taskinen <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ /* * This product includes software developed by the Apache Group * for use in the Apache HTTP server project (http://www.apache.org/). * */ #include <stdio.h> #include "php.h" #include "php_open_temporary_file.h" #include "zend_globals.h" #include "php_globals.h" #include "php_variables.h" #include "rfc1867.h" #include "ext/standard/php_string.h" #define DEBUG_FILE_UPLOAD ZEND_DEBUG static int dummy_encoding_translation(TSRMLS_D) { return 0; } static char *php_ap_getword(const zend_encoding *encoding, char **line, char stop TSRMLS_DC); static char *php_ap_getword_conf(const zend_encoding *encoding, char *str TSRMLS_DC); static php_rfc1867_encoding_translation_t php_rfc1867_encoding_translation = dummy_encoding_translation; static php_rfc1867_get_detect_order_t php_rfc1867_get_detect_order = NULL; static php_rfc1867_set_input_encoding_t php_rfc1867_set_input_encoding = NULL; static php_rfc1867_getword_t php_rfc1867_getword = php_ap_getword; static php_rfc1867_getword_conf_t php_rfc1867_getword_conf = php_ap_getword_conf; static php_rfc1867_basename_t php_rfc1867_basename = NULL; PHPAPI int (*php_rfc1867_callback)(unsigned int event, void *event_data, void **extra TSRMLS_DC) = NULL; static void safe_php_register_variable(char *var, char *strval, int val_len, zval *track_vars_array, zend_bool override_protection TSRMLS_DC); /* The longest property name we use in an uploaded file array */ #define MAX_SIZE_OF_INDEX sizeof("[tmp_name]") /* The longest anonymous name */ #define MAX_SIZE_ANONNAME 33 /* Errors */ #define UPLOAD_ERROR_OK 0 /* File upload succesful */ #define UPLOAD_ERROR_A 1 /* Uploaded file exceeded upload_max_filesize */ #define UPLOAD_ERROR_B 2 /* Uploaded file exceeded MAX_FILE_SIZE */ #define UPLOAD_ERROR_C 3 /* Partially uploaded */ #define UPLOAD_ERROR_D 4 /* No file uploaded */ #define UPLOAD_ERROR_E 6 /* Missing /tmp or similar directory */ #define UPLOAD_ERROR_F 7 /* Failed to write file to disk */ #define UPLOAD_ERROR_X 8 /* File upload stopped by extension */ void php_rfc1867_register_constants(TSRMLS_D) /* {{{ */ { REGISTER_MAIN_LONG_CONSTANT("UPLOAD_ERR_OK", UPLOAD_ERROR_OK, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("UPLOAD_ERR_INI_SIZE", UPLOAD_ERROR_A, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("UPLOAD_ERR_FORM_SIZE", UPLOAD_ERROR_B, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("UPLOAD_ERR_PARTIAL", UPLOAD_ERROR_C, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("UPLOAD_ERR_NO_FILE", UPLOAD_ERROR_D, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("UPLOAD_ERR_NO_TMP_DIR", UPLOAD_ERROR_E, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("UPLOAD_ERR_CANT_WRITE", UPLOAD_ERROR_F, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("UPLOAD_ERR_EXTENSION", UPLOAD_ERROR_X, CONST_CS | CONST_PERSISTENT); } /* }}} */ static void normalize_protected_variable(char *varname TSRMLS_DC) /* {{{ */ { char *s = varname, *index = NULL, *indexend = NULL, *p; /* overjump leading space */ while (*s == ' ') { s++; } /* and remove it */ if (s != varname) { memmove(varname, s, strlen(s)+1); } for (p = varname; *p && *p != '['; p++) { switch(*p) { case ' ': case '.': *p = '_'; break; } } /* find index */ index = strchr(varname, '['); if (index) { index++; s = index; } else { return; } /* done? */ while (index) { while (*index == ' ' || *index == '\r' || *index == '\n' || *index=='\t') { index++; } indexend = strchr(index, ']'); indexend = indexend ? indexend + 1 : index + strlen(index); if (s != index) { memmove(s, index, strlen(index)+1); s += indexend-index; } else { s = indexend; } if (*s == '[') { s++; index = s; } else { index = NULL; } } *s = '\0'; } /* }}} */ static void add_protected_variable(char *varname TSRMLS_DC) /* {{{ */ { int dummy = 1; normalize_protected_variable(varname TSRMLS_CC); zend_hash_add(&PG(rfc1867_protected_variables), varname, strlen(varname)+1, &dummy, sizeof(int), NULL); } /* }}} */ static zend_bool is_protected_variable(char *varname TSRMLS_DC) /* {{{ */ { normalize_protected_variable(varname TSRMLS_CC); return zend_hash_exists(&PG(rfc1867_protected_variables), varname, strlen(varname)+1); } /* }}} */ static void safe_php_register_variable(char *var, char *strval, int val_len, zval *track_vars_array, zend_bool override_protection TSRMLS_DC) /* {{{ */ { if (override_protection || !is_protected_variable(var TSRMLS_CC)) { php_register_variable_safe(var, strval, val_len, track_vars_array TSRMLS_CC); } } /* }}} */ static void safe_php_register_variable_ex(char *var, zval *val, zval *track_vars_array, zend_bool override_protection TSRMLS_DC) /* {{{ */ { if (override_protection || !is_protected_variable(var TSRMLS_CC)) { php_register_variable_ex(var, val, track_vars_array TSRMLS_CC); } } /* }}} */ static void register_http_post_files_variable(char *strvar, char *val, zval *http_post_files, zend_bool override_protection TSRMLS_DC) /* {{{ */ { safe_php_register_variable(strvar, val, strlen(val), http_post_files, override_protection TSRMLS_CC); } /* }}} */ static void register_http_post_files_variable_ex(char *var, zval *val, zval *http_post_files, zend_bool override_protection TSRMLS_DC) /* {{{ */ { safe_php_register_variable_ex(var, val, http_post_files, override_protection TSRMLS_CC); } /* }}} */ static int unlink_filename(char **filename TSRMLS_DC) /* {{{ */ { VCWD_UNLINK(*filename); return 0; } /* }}} */ void destroy_uploaded_files_hash(TSRMLS_D) /* {{{ */ { zend_hash_apply(SG(rfc1867_uploaded_files), (apply_func_t) unlink_filename TSRMLS_CC); zend_hash_destroy(SG(rfc1867_uploaded_files)); FREE_HASHTABLE(SG(rfc1867_uploaded_files)); } /* }}} */ /* {{{ Following code is based on apache_multipart_buffer.c from libapreq-0.33 package. */ #define FILLUNIT (1024 * 5) typedef struct { /* read buffer */ char *buffer; char *buf_begin; int bufsize; int bytes_in_buffer; /* boundary info */ char *boundary; char *boundary_next; int boundary_next_len; const zend_encoding *input_encoding; const zend_encoding **detect_order; size_t detect_order_size; } multipart_buffer; typedef struct { char *key; char *value; } mime_header_entry; /* * Fill up the buffer with client data. * Returns number of bytes added to buffer. */ static int fill_buffer(multipart_buffer *self TSRMLS_DC) { int bytes_to_read, total_read = 0, actual_read = 0; /* shift the existing data if necessary */ if (self->bytes_in_buffer > 0 && self->buf_begin != self->buffer) { memmove(self->buffer, self->buf_begin, self->bytes_in_buffer); } self->buf_begin = self->buffer; /* calculate the free space in the buffer */ bytes_to_read = self->bufsize - self->bytes_in_buffer; /* read the required number of bytes */ while (bytes_to_read > 0) { char *buf = self->buffer + self->bytes_in_buffer; actual_read = sapi_module.read_post(buf, bytes_to_read TSRMLS_CC); /* update the buffer length */ if (actual_read > 0) { self->bytes_in_buffer += actual_read; SG(read_post_bytes) += actual_read; total_read += actual_read; bytes_to_read -= actual_read; } else { break; } } return total_read; } /* eof if we are out of bytes, or if we hit the final boundary */ static int multipart_buffer_eof(multipart_buffer *self TSRMLS_DC) { if ( (self->bytes_in_buffer == 0 && fill_buffer(self TSRMLS_CC) < 1) ) { return 1; } else { return 0; } } /* create new multipart_buffer structure */ static multipart_buffer *multipart_buffer_new(char *boundary, int boundary_len TSRMLS_DC) { multipart_buffer *self = (multipart_buffer *) ecalloc(1, sizeof(multipart_buffer)); int minsize = boundary_len + 6; if (minsize < FILLUNIT) minsize = FILLUNIT; self->buffer = (char *) ecalloc(1, minsize + 1); self->bufsize = minsize; spprintf(&self->boundary, 0, "--%s", boundary); self->boundary_next_len = spprintf(&self->boundary_next, 0, "\n--%s", boundary); self->buf_begin = self->buffer; self->bytes_in_buffer = 0; if (php_rfc1867_encoding_translation(TSRMLS_C)) { php_rfc1867_get_detect_order(&self->detect_order, &self->detect_order_size TSRMLS_CC); } else { self->detect_order = NULL; self->detect_order_size = 0; } self->input_encoding = NULL; return self; } /* * Gets the next CRLF terminated line from the input buffer. * If it doesn't find a CRLF, and the buffer isn't completely full, returns * NULL; otherwise, returns the beginning of the null-terminated line, * minus the CRLF. * * Note that we really just look for LF terminated lines. This works * around a bug in internet explorer for the macintosh which sends mime * boundaries that are only LF terminated when you use an image submit * button in a multipart/form-data form. */ static char *next_line(multipart_buffer *self) { /* look for LF in the data */ char* line = self->buf_begin; char* ptr = memchr(self->buf_begin, '\n', self->bytes_in_buffer); if (ptr) { /* LF found */ /* terminate the string, remove CRLF */ if ((ptr - line) > 0 && *(ptr-1) == '\r') { *(ptr-1) = 0; } else { *ptr = 0; } /* bump the pointer */ self->buf_begin = ptr + 1; self->bytes_in_buffer -= (self->buf_begin - line); } else { /* no LF found */ /* buffer isn't completely full, fail */ if (self->bytes_in_buffer < self->bufsize) { return NULL; } /* return entire buffer as a partial line */ line[self->bufsize] = 0; self->buf_begin = ptr; self->bytes_in_buffer = 0; } return line; } /* Returns the next CRLF terminated line from the client */ static char *get_line(multipart_buffer *self TSRMLS_DC) { char* ptr = next_line(self); if (!ptr) { fill_buffer(self TSRMLS_CC); ptr = next_line(self); } return ptr; } /* Free header entry */ static void php_free_hdr_entry(mime_header_entry *h) { if (h->key) { efree(h->key); } if (h->value) { efree(h->value); } } /* finds a boundary */ static int find_boundary(multipart_buffer *self, char *boundary TSRMLS_DC) { char *line; /* loop thru lines */ while( (line = get_line(self TSRMLS_CC)) ) { /* finished if we found the boundary */ if (!strcmp(line, boundary)) { return 1; } } /* didn't find the boundary */ return 0; } /* parse headers */ static int multipart_buffer_headers(multipart_buffer *self, zend_llist *header TSRMLS_DC) { char *line; mime_header_entry prev_entry, entry; int prev_len, cur_len; /* didn't find boundary, abort */ if (!find_boundary(self, self->boundary TSRMLS_CC)) { return 0; } /* get lines of text, or CRLF_CRLF */ while( (line = get_line(self TSRMLS_CC)) && strlen(line) > 0 ) { /* add header to table */ char *key = line; char *value = NULL; if (php_rfc1867_encoding_translation(TSRMLS_C)) { self->input_encoding = zend_multibyte_encoding_detector(line, strlen(line), self->detect_order, self->detect_order_size TSRMLS_CC); } /* space in the beginning means same header */ if (!isspace(line[0])) { value = strchr(line, ':'); } if (value) { *value = 0; do { value++; } while(isspace(*value)); entry.value = estrdup(value); entry.key = estrdup(key); } else if (zend_llist_count(header)) { /* If no ':' on the line, add to previous line */ prev_len = strlen(prev_entry.value); cur_len = strlen(line); entry.value = emalloc(prev_len + cur_len + 1); memcpy(entry.value, prev_entry.value, prev_len); memcpy(entry.value + prev_len, line, cur_len); entry.value[cur_len + prev_len] = '\0'; entry.key = estrdup(prev_entry.key); zend_llist_remove_tail(header); } else { continue; } zend_llist_add_element(header, &entry); prev_entry = entry; } return 1; } static char *php_mime_get_hdr_value(zend_llist header, char *key) { mime_header_entry *entry; if (key == NULL) { return NULL; } entry = zend_llist_get_first(&header); while (entry) { if (!strcasecmp(entry->key, key)) { return entry->value; } entry = zend_llist_get_next(&header); } return NULL; } static char *php_ap_getword(const zend_encoding *encoding, char **line, char stop TSRMLS_DC) { char *pos = *line, quote; char *res; while (*pos && *pos != stop) { if ((quote = *pos) == '"' || quote == '\'') { ++pos; while (*pos && *pos != quote) { if (*pos == '\\' && pos[1] && pos[1] == quote) { pos += 2; } else { ++pos; } } if (*pos) { ++pos; } } else ++pos; } if (*pos == '\0') { res = estrdup(*line); *line += strlen(*line); return res; } res = estrndup(*line, pos - *line); while (*pos == stop) { ++pos; } *line = pos; return res; } static char *substring_conf(char *start, int len, char quote) { char *result = emalloc(len + 1); char *resp = result; int i; for (i = 0; i < len && start[i] != quote; ++i) { if (start[i] == '\\' && (start[i + 1] == '\\' || (quote && start[i + 1] == quote))) { *resp++ = start[++i]; } else { *resp++ = start[i]; } } *resp = '\0'; return result; } static char *php_ap_getword_conf(const zend_encoding *encoding, char *str TSRMLS_DC) { while (*str && isspace(*str)) { ++str; } if (!*str) { return estrdup(""); } if (*str == '"' || *str == '\'') { char quote = *str; str++; return substring_conf(str, strlen(str), quote); } else { char *strend = str; while (*strend && !isspace(*strend)) { ++strend; } return substring_conf(str, strend - str, 0); } } static char *php_ap_basename(const zend_encoding *encoding, char *path TSRMLS_DC) { char *s = strrchr(path, '\\'); char *s2 = strrchr(path, '/'); if (s && s2) { if (s > s2) { ++s; } else { s = ++s2; } return s; } else if (s) { return ++s; } else if (s2) { return ++s2; } return path; } /* * Search for a string in a fixed-length byte string. * If partial is true, partial matches are allowed at the end of the buffer. * Returns NULL if not found, or a pointer to the start of the first match. */ static void *php_ap_memstr(char *haystack, int haystacklen, char *needle, int needlen, int partial) { int len = haystacklen; char *ptr = haystack; /* iterate through first character matches */ while( (ptr = memchr(ptr, needle[0], len)) ) { /* calculate length after match */ len = haystacklen - (ptr - (char *)haystack); /* done if matches up to capacity of buffer */ if (memcmp(needle, ptr, needlen < len ? needlen : len) == 0 && (partial || len >= needlen)) { break; } /* next character */ ptr++; len--; } return ptr; } /* read until a boundary condition */ static int multipart_buffer_read(multipart_buffer *self, char *buf, int bytes, int *end TSRMLS_DC) { int len, max; char *bound; /* fill buffer if needed */ if (bytes > self->bytes_in_buffer) { fill_buffer(self TSRMLS_CC); } /* look for a potential boundary match, only read data up to that point */ if ((bound = php_ap_memstr(self->buf_begin, self->bytes_in_buffer, self->boundary_next, self->boundary_next_len, 1))) { max = bound - self->buf_begin; if (end && php_ap_memstr(self->buf_begin, self->bytes_in_buffer, self->boundary_next, self->boundary_next_len, 0)) { *end = 1; } } else { max = self->bytes_in_buffer; } /* maximum number of bytes we are reading */ len = max < bytes-1 ? max : bytes-1; /* if we read any data... */ if (len > 0) { /* copy the data */ memcpy(buf, self->buf_begin, len); buf[len] = 0; if (bound && len > 0 && buf[len-1] == '\r') { buf[--len] = 0; } /* update the buffer */ self->bytes_in_buffer -= len; self->buf_begin += len; } return len; } /* XXX: this is horrible memory-usage-wise, but we only expect to do this on small pieces of form data. */ static char *multipart_buffer_read_body(multipart_buffer *self, unsigned int *len TSRMLS_DC) { char buf[FILLUNIT], *out=NULL; int total_bytes=0, read_bytes=0; while((read_bytes = multipart_buffer_read(self, buf, sizeof(buf), NULL TSRMLS_CC))) { out = erealloc(out, total_bytes + read_bytes + 1); memcpy(out + total_bytes, buf, read_bytes); total_bytes += read_bytes; } if (out) { out[total_bytes] = '\0'; } *len = total_bytes; return out; } /* }}} */ /* * The combined READER/HANDLER * */ SAPI_API SAPI_POST_HANDLER_FUNC(rfc1867_post_handler) /* {{{ */ { char *boundary, *s = NULL, *boundary_end = NULL, *start_arr = NULL, *array_index = NULL; char *temp_filename = NULL, *lbuf = NULL, *abuf = NULL; int boundary_len = 0, total_bytes = 0, cancel_upload = 0, is_arr_upload = 0, array_len = 0; int max_file_size = 0, skip_upload = 0, anonindex = 0, is_anonymous; zval *http_post_files = NULL; HashTable *uploaded_files = NULL; multipart_buffer *mbuff; zval *array_ptr = (zval *) arg; int fd = -1; zend_llist header; void *event_extra_data = NULL; unsigned int llen = 0; int upload_cnt = INI_INT("max_file_uploads"); const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding(TSRMLS_C); php_rfc1867_getword_t getword; php_rfc1867_getword_conf_t getword_conf; php_rfc1867_basename_t _basename; if (php_rfc1867_encoding_translation(TSRMLS_C) && internal_encoding) { getword = php_rfc1867_getword; getword_conf = php_rfc1867_getword_conf; _basename = php_rfc1867_basename; } else { getword = php_ap_getword; getword_conf = php_ap_getword_conf; _basename = php_ap_basename; } if (SG(post_max_size) > 0 && SG(request_info).content_length > SG(post_max_size)) { sapi_module.sapi_error(E_WARNING, "POST Content-Length of %ld bytes exceeds the limit of %ld bytes", SG(request_info).content_length, SG(post_max_size)); return; } /* Get the boundary */ boundary = strstr(content_type_dup, "boundary"); if (!boundary) { int content_type_len = strlen(content_type_dup); char *content_type_lcase = estrndup(content_type_dup, content_type_len); php_strtolower(content_type_lcase, content_type_len); boundary = strstr(content_type_lcase, "boundary"); if (boundary) { boundary = content_type_dup + (boundary - content_type_lcase); } efree(content_type_lcase); } if (!boundary || !(boundary = strchr(boundary, '='))) { sapi_module.sapi_error(E_WARNING, "Missing boundary in multipart/form-data POST data"); return; } boundary++; boundary_len = strlen(boundary); if (boundary[0] == '"') { boundary++; boundary_end = strchr(boundary, '"'); if (!boundary_end) { sapi_module.sapi_error(E_WARNING, "Invalid boundary in multipart/form-data POST data"); return; } } else { /* search for the end of the boundary */ boundary_end = strpbrk(boundary, ",;"); } if (boundary_end) { boundary_end[0] = '\0'; boundary_len = boundary_end-boundary; } /* Initialize the buffer */ if (!(mbuff = multipart_buffer_new(boundary, boundary_len TSRMLS_CC))) { sapi_module.sapi_error(E_WARNING, "Unable to initialize the input buffer"); return; } /* Initialize $_FILES[] */ zend_hash_init(&PG(rfc1867_protected_variables), 5, NULL, NULL, 0); ALLOC_HASHTABLE(uploaded_files); zend_hash_init(uploaded_files, 5, NULL, (dtor_func_t) free_estring, 0); SG(rfc1867_uploaded_files) = uploaded_files; ALLOC_ZVAL(http_post_files); array_init(http_post_files); INIT_PZVAL(http_post_files); PG(http_globals)[TRACK_VARS_FILES] = http_post_files; zend_llist_init(&header, sizeof(mime_header_entry), (llist_dtor_func_t) php_free_hdr_entry, 0); if (php_rfc1867_callback != NULL) { multipart_event_start event_start; event_start.content_length = SG(request_info).content_length; if (php_rfc1867_callback(MULTIPART_EVENT_START, &event_start, &event_extra_data TSRMLS_CC) == FAILURE) { goto fileupload_done; } } while (!multipart_buffer_eof(mbuff TSRMLS_CC)) { char buff[FILLUNIT]; char *cd = NULL, *param = NULL, *filename = NULL, *tmp = NULL; size_t blen = 0, wlen = 0; off_t offset; zend_llist_clean(&header); if (!multipart_buffer_headers(mbuff, &header TSRMLS_CC)) { goto fileupload_done; } if ((cd = php_mime_get_hdr_value(header, "Content-Disposition"))) { char *pair = NULL; int end = 0; while (isspace(*cd)) { ++cd; } while (*cd && (pair = getword(mbuff->input_encoding, &cd, ';' TSRMLS_CC))) { char *key = NULL, *word = pair; while (isspace(*cd)) { ++cd; } if (strchr(pair, '=')) { key = getword(mbuff->input_encoding, &pair, '=' TSRMLS_CC); if (!strcasecmp(key, "name")) { if (param) { efree(param); } param = getword_conf(mbuff->input_encoding, pair TSRMLS_CC); if (mbuff->input_encoding && internal_encoding) { unsigned char *new_param; size_t new_param_len; if ((size_t)-1 != zend_multibyte_encoding_converter(&new_param, &new_param_len, (unsigned char *)param, strlen(param), internal_encoding, mbuff->input_encoding TSRMLS_CC)) { efree(param); param = (char *)new_param; } } } else if (!strcasecmp(key, "filename")) { if (filename) { efree(filename); } filename = getword_conf(mbuff->input_encoding, pair TSRMLS_CC); if (mbuff->input_encoding && internal_encoding) { unsigned char *new_filename; size_t new_filename_len; if ((size_t)-1 != zend_multibyte_encoding_converter(&new_filename, &new_filename_len, (unsigned char *)filename, strlen(filename), internal_encoding, mbuff->input_encoding TSRMLS_CC)) { efree(filename); filename = (char *)new_filename; } } } } if (key) { efree(key); } efree(word); } /* Normal form variable, safe to read all data into memory */ if (!filename && param) { unsigned int value_len; char *value = multipart_buffer_read_body(mbuff, &value_len TSRMLS_CC); unsigned int new_val_len; /* Dummy variable */ if (!value) { value = estrdup(""); value_len = 0; } if (mbuff->input_encoding && internal_encoding) { unsigned char *new_value; size_t new_value_len; if ((size_t)-1 != zend_multibyte_encoding_converter(&new_value, &new_value_len, (unsigned char *)value, value_len, internal_encoding, mbuff->input_encoding TSRMLS_CC)) { efree(value); value = (char *)new_value; value_len = new_value_len; } } if (sapi_module.input_filter(PARSE_POST, param, &value, value_len, &new_val_len TSRMLS_CC)) { if (php_rfc1867_callback != NULL) { multipart_event_formdata event_formdata; size_t newlength = new_val_len; event_formdata.post_bytes_processed = SG(read_post_bytes); event_formdata.name = param; event_formdata.value = &value; event_formdata.length = new_val_len; event_formdata.newlength = &newlength; if (php_rfc1867_callback(MULTIPART_EVENT_FORMDATA, &event_formdata, &event_extra_data TSRMLS_CC) == FAILURE) { efree(param); efree(value); continue; } new_val_len = newlength; } safe_php_register_variable(param, value, new_val_len, array_ptr, 0 TSRMLS_CC); } else if (php_rfc1867_callback != NULL) { multipart_event_formdata event_formdata; event_formdata.post_bytes_processed = SG(read_post_bytes); event_formdata.name = param; event_formdata.value = &value; event_formdata.length = value_len; event_formdata.newlength = NULL; php_rfc1867_callback(MULTIPART_EVENT_FORMDATA, &event_formdata, &event_extra_data TSRMLS_CC); } if (!strcasecmp(param, "MAX_FILE_SIZE")) { max_file_size = atol(value); } efree(param); efree(value); continue; } /* If file_uploads=off, skip the file part */ if (!PG(file_uploads)) { skip_upload = 1; } else if (upload_cnt <= 0) { skip_upload = 1; sapi_module.sapi_error(E_WARNING, "Maximum number of allowable file uploads has been exceeded"); } /* Return with an error if the posted data is garbled */ if (!param && !filename) { sapi_module.sapi_error(E_WARNING, "File Upload Mime headers garbled"); goto fileupload_done; } if (!param) { is_anonymous = 1; param = emalloc(MAX_SIZE_ANONNAME); snprintf(param, MAX_SIZE_ANONNAME, "%u", anonindex++); } else { is_anonymous = 0; } /* New Rule: never repair potential malicious user input */ if (!skip_upload) { long c = 0; tmp = param; while (*tmp) { if (*tmp == '[') { c++; } else if (*tmp == ']') { c--; if (tmp[1] && tmp[1] != '[') { skip_upload = 1; break; } } if (c < 0) { skip_upload = 1; break; } tmp++; } } total_bytes = cancel_upload = 0; temp_filename = NULL; fd = -1; if (!skip_upload && php_rfc1867_callback != NULL) { multipart_event_file_start event_file_start; event_file_start.post_bytes_processed = SG(read_post_bytes); event_file_start.name = param; event_file_start.filename = &filename; if (php_rfc1867_callback(MULTIPART_EVENT_FILE_START, &event_file_start, &event_extra_data TSRMLS_CC) == FAILURE) { temp_filename = ""; efree(param); efree(filename); continue; } } if (skip_upload) { efree(param); efree(filename); continue; } if (strlen(filename) == 0) { #if DEBUG_FILE_UPLOAD sapi_module.sapi_error(E_NOTICE, "No file uploaded"); #endif cancel_upload = UPLOAD_ERROR_D; } offset = 0; end = 0; if (!cancel_upload) { /* only bother to open temp file if we have data */ blen = multipart_buffer_read(mbuff, buff, sizeof(buff), &end TSRMLS_CC); #if DEBUG_FILE_UPLOAD if (blen > 0) { #else /* in non-debug mode we have no problem with 0-length files */ { #endif fd = php_open_temporary_fd_ex(PG(upload_tmp_dir), "php", &temp_filename, 1 TSRMLS_CC); upload_cnt--; if (fd == -1) { sapi_module.sapi_error(E_WARNING, "File upload error - unable to create a temporary file"); cancel_upload = UPLOAD_ERROR_E; } } } while (!cancel_upload && (blen > 0)) { if (php_rfc1867_callback != NULL) { multipart_event_file_data event_file_data; event_file_data.post_bytes_processed = SG(read_post_bytes); event_file_data.offset = offset; event_file_data.data = buff; event_file_data.length = blen; event_file_data.newlength = &blen; if (php_rfc1867_callback(MULTIPART_EVENT_FILE_DATA, &event_file_data, &event_extra_data TSRMLS_CC) == FAILURE) { cancel_upload = UPLOAD_ERROR_X; continue; } } if (PG(upload_max_filesize) > 0 && (long)(total_bytes+blen) > PG(upload_max_filesize)) { #if DEBUG_FILE_UPLOAD sapi_module.sapi_error(E_NOTICE, "upload_max_filesize of %ld bytes exceeded - file [%s=%s] not saved", PG(upload_max_filesize), param, filename); #endif cancel_upload = UPLOAD_ERROR_A; } else if (max_file_size && ((long)(total_bytes+blen) > max_file_size)) { #if DEBUG_FILE_UPLOAD sapi_module.sapi_error(E_NOTICE, "MAX_FILE_SIZE of %ld bytes exceeded - file [%s=%s] not saved", max_file_size, param, filename); #endif cancel_upload = UPLOAD_ERROR_B; } else if (blen > 0) { wlen = write(fd, buff, blen); if (wlen == -1) { /* write failed */ #if DEBUG_FILE_UPLOAD sapi_module.sapi_error(E_NOTICE, "write() failed - %s", strerror(errno)); #endif cancel_upload = UPLOAD_ERROR_F; } else if (wlen < blen) { #if DEBUG_FILE_UPLOAD sapi_module.sapi_error(E_NOTICE, "Only %d bytes were written, expected to write %d", wlen, blen); #endif cancel_upload = UPLOAD_ERROR_F; } else { total_bytes += wlen; } offset += wlen; } /* read data for next iteration */ blen = multipart_buffer_read(mbuff, buff, sizeof(buff), &end TSRMLS_CC); } if (fd != -1) { /* may not be initialized if file could not be created */ close(fd); } if (!cancel_upload && !end) { #if DEBUG_FILE_UPLOAD sapi_module.sapi_error(E_NOTICE, "Missing mime boundary at the end of the data for file %s", strlen(filename) > 0 ? filename : ""); #endif cancel_upload = UPLOAD_ERROR_C; } #if DEBUG_FILE_UPLOAD if (strlen(filename) > 0 && total_bytes == 0 && !cancel_upload) { sapi_module.sapi_error(E_WARNING, "Uploaded file size 0 - file [%s=%s] not saved", param, filename); cancel_upload = 5; } #endif if (php_rfc1867_callback != NULL) { multipart_event_file_end event_file_end; event_file_end.post_bytes_processed = SG(read_post_bytes); event_file_end.temp_filename = temp_filename; event_file_end.cancel_upload = cancel_upload; if (php_rfc1867_callback(MULTIPART_EVENT_FILE_END, &event_file_end, &event_extra_data TSRMLS_CC) == FAILURE) { cancel_upload = UPLOAD_ERROR_X; } } if (cancel_upload) { if (temp_filename) { if (cancel_upload != UPLOAD_ERROR_E) { /* file creation failed */ unlink(temp_filename); } efree(temp_filename); } temp_filename = ""; } else { zend_hash_add(SG(rfc1867_uploaded_files), temp_filename, strlen(temp_filename) + 1, &temp_filename, sizeof(char *), NULL); } /* is_arr_upload is true when name of file upload field * ends in [.*] * start_arr is set to point to 1st [ */ is_arr_upload = (start_arr = strchr(param,'[')) && (param[strlen(param)-1] == ']'); if (is_arr_upload) { array_len = strlen(start_arr); if (array_index) { efree(array_index); } array_index = estrndup(start_arr + 1, array_len - 2); } /* Add $foo_name */ if (llen < strlen(param) + MAX_SIZE_OF_INDEX + 1) { llen = strlen(param); lbuf = (char *) safe_erealloc(lbuf, llen, 1, MAX_SIZE_OF_INDEX + 1); llen += MAX_SIZE_OF_INDEX + 1; } if (is_arr_upload) { if (abuf) efree(abuf); abuf = estrndup(param, strlen(param)-array_len); snprintf(lbuf, llen, "%s_name[%s]", abuf, array_index); } else { snprintf(lbuf, llen, "%s_name", param); } /* The \ check should technically be needed for win32 systems only where * it is a valid path separator. However, IE in all it's wisdom always sends * the full path of the file on the user's filesystem, which means that unless * the user does basename() they get a bogus file name. Until IE's user base drops * to nill or problem is fixed this code must remain enabled for all systems. */ s = _basename(internal_encoding, filename TSRMLS_CC); if (!s) { s = filename; } if (!is_anonymous) { safe_php_register_variable(lbuf, s, strlen(s), NULL, 0 TSRMLS_CC); } /* Add $foo[name] */ if (is_arr_upload) { snprintf(lbuf, llen, "%s[name][%s]", abuf, array_index); } else { snprintf(lbuf, llen, "%s[name]", param); } register_http_post_files_variable(lbuf, s, http_post_files, 0 TSRMLS_CC); efree(filename); s = NULL; /* Possible Content-Type: */ if (cancel_upload || !(cd = php_mime_get_hdr_value(header, "Content-Type"))) { cd = ""; } else { /* fix for Opera 6.01 */ s = strchr(cd, ';'); if (s != NULL) { *s = '\0'; } } /* Add $foo_type */ if (is_arr_upload) { snprintf(lbuf, llen, "%s_type[%s]", abuf, array_index); } else { snprintf(lbuf, llen, "%s_type", param); } if (!is_anonymous) { safe_php_register_variable(lbuf, cd, strlen(cd), NULL, 0 TSRMLS_CC); } /* Add $foo[type] */ if (is_arr_upload) { snprintf(lbuf, llen, "%s[type][%s]", abuf, array_index); } else { snprintf(lbuf, llen, "%s[type]", param); } register_http_post_files_variable(lbuf, cd, http_post_files, 0 TSRMLS_CC); /* Restore Content-Type Header */ if (s != NULL) { *s = ';'; } s = ""; { /* store temp_filename as-is (in case upload_tmp_dir * contains escapeable characters. escape only the variable name.) */ zval zfilename; /* Initialize variables */ add_protected_variable(param TSRMLS_CC); /* if param is of form xxx[.*] this will cut it to xxx */ if (!is_anonymous) { ZVAL_STRING(&zfilename, temp_filename, 1); safe_php_register_variable_ex(param, &zfilename, NULL, 1 TSRMLS_CC); } /* Add $foo[tmp_name] */ if (is_arr_upload) { snprintf(lbuf, llen, "%s[tmp_name][%s]", abuf, array_index); } else { snprintf(lbuf, llen, "%s[tmp_name]", param); } add_protected_variable(lbuf TSRMLS_CC); ZVAL_STRING(&zfilename, temp_filename, 1); register_http_post_files_variable_ex(lbuf, &zfilename, http_post_files, 1 TSRMLS_CC); } { zval file_size, error_type; error_type.value.lval = cancel_upload; error_type.type = IS_LONG; /* Add $foo[error] */ if (cancel_upload) { file_size.value.lval = 0; file_size.type = IS_LONG; } else { file_size.value.lval = total_bytes; file_size.type = IS_LONG; } if (is_arr_upload) { snprintf(lbuf, llen, "%s[error][%s]", abuf, array_index); } else { snprintf(lbuf, llen, "%s[error]", param); } register_http_post_files_variable_ex(lbuf, &error_type, http_post_files, 0 TSRMLS_CC); /* Add $foo_size */ if (is_arr_upload) { snprintf(lbuf, llen, "%s_size[%s]", abuf, array_index); } else { snprintf(lbuf, llen, "%s_size", param); } if (!is_anonymous) { safe_php_register_variable_ex(lbuf, &file_size, NULL, 0 TSRMLS_CC); } /* Add $foo[size] */ if (is_arr_upload) { snprintf(lbuf, llen, "%s[size][%s]", abuf, array_index); } else { snprintf(lbuf, llen, "%s[size]", param); } register_http_post_files_variable_ex(lbuf, &file_size, http_post_files, 0 TSRMLS_CC); } efree(param); } } fileupload_done: if (php_rfc1867_callback != NULL) { multipart_event_end event_end; event_end.post_bytes_processed = SG(read_post_bytes); php_rfc1867_callback(MULTIPART_EVENT_END, &event_end, &event_extra_data TSRMLS_CC); } if (lbuf) efree(lbuf); if (abuf) efree(abuf); if (array_index) efree(array_index); zend_hash_destroy(&PG(rfc1867_protected_variables)); zend_llist_destroy(&header); if (mbuff->boundary_next) efree(mbuff->boundary_next); if (mbuff->boundary) efree(mbuff->boundary); if (mbuff->buffer) efree(mbuff->buffer); if (mbuff) efree(mbuff); } /* }}} */ SAPI_API void php_rfc1867_set_multibyte_callbacks( php_rfc1867_encoding_translation_t encoding_translation, php_rfc1867_get_detect_order_t get_detect_order, php_rfc1867_set_input_encoding_t set_input_encoding, php_rfc1867_getword_t getword, php_rfc1867_getword_conf_t getword_conf, php_rfc1867_basename_t basename) /* {{{ */ { php_rfc1867_encoding_translation = encoding_translation; php_rfc1867_get_detect_order = get_detect_order; php_rfc1867_set_input_encoding = set_input_encoding; php_rfc1867_getword = getword; php_rfc1867_getword_conf = getword_conf; php_rfc1867_basename = basename; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2012 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Rasmus Lerdorf <[email protected]> | | Jani Taskinen <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ /* * This product includes software developed by the Apache Group * for use in the Apache HTTP server project (http://www.apache.org/). * */ #include <stdio.h> #include "php.h" #include "php_open_temporary_file.h" #include "zend_globals.h" #include "php_globals.h" #include "php_variables.h" #include "rfc1867.h" #include "ext/standard/php_string.h" #define DEBUG_FILE_UPLOAD ZEND_DEBUG static int dummy_encoding_translation(TSRMLS_D) { return 0; } static char *php_ap_getword(const zend_encoding *encoding, char **line, char stop TSRMLS_DC); static char *php_ap_getword_conf(const zend_encoding *encoding, char *str TSRMLS_DC); static php_rfc1867_encoding_translation_t php_rfc1867_encoding_translation = dummy_encoding_translation; static php_rfc1867_get_detect_order_t php_rfc1867_get_detect_order = NULL; static php_rfc1867_set_input_encoding_t php_rfc1867_set_input_encoding = NULL; static php_rfc1867_getword_t php_rfc1867_getword = php_ap_getword; static php_rfc1867_getword_conf_t php_rfc1867_getword_conf = php_ap_getword_conf; static php_rfc1867_basename_t php_rfc1867_basename = NULL; PHPAPI int (*php_rfc1867_callback)(unsigned int event, void *event_data, void **extra TSRMLS_DC) = NULL; static void safe_php_register_variable(char *var, char *strval, int val_len, zval *track_vars_array, zend_bool override_protection TSRMLS_DC); /* The longest property name we use in an uploaded file array */ #define MAX_SIZE_OF_INDEX sizeof("[tmp_name]") /* The longest anonymous name */ #define MAX_SIZE_ANONNAME 33 /* Errors */ #define UPLOAD_ERROR_OK 0 /* File upload succesful */ #define UPLOAD_ERROR_A 1 /* Uploaded file exceeded upload_max_filesize */ #define UPLOAD_ERROR_B 2 /* Uploaded file exceeded MAX_FILE_SIZE */ #define UPLOAD_ERROR_C 3 /* Partially uploaded */ #define UPLOAD_ERROR_D 4 /* No file uploaded */ #define UPLOAD_ERROR_E 6 /* Missing /tmp or similar directory */ #define UPLOAD_ERROR_F 7 /* Failed to write file to disk */ #define UPLOAD_ERROR_X 8 /* File upload stopped by extension */ void php_rfc1867_register_constants(TSRMLS_D) /* {{{ */ { REGISTER_MAIN_LONG_CONSTANT("UPLOAD_ERR_OK", UPLOAD_ERROR_OK, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("UPLOAD_ERR_INI_SIZE", UPLOAD_ERROR_A, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("UPLOAD_ERR_FORM_SIZE", UPLOAD_ERROR_B, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("UPLOAD_ERR_PARTIAL", UPLOAD_ERROR_C, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("UPLOAD_ERR_NO_FILE", UPLOAD_ERROR_D, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("UPLOAD_ERR_NO_TMP_DIR", UPLOAD_ERROR_E, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("UPLOAD_ERR_CANT_WRITE", UPLOAD_ERROR_F, CONST_CS | CONST_PERSISTENT); REGISTER_MAIN_LONG_CONSTANT("UPLOAD_ERR_EXTENSION", UPLOAD_ERROR_X, CONST_CS | CONST_PERSISTENT); } /* }}} */ static void normalize_protected_variable(char *varname TSRMLS_DC) /* {{{ */ { char *s = varname, *index = NULL, *indexend = NULL, *p; /* overjump leading space */ while (*s == ' ') { s++; } /* and remove it */ if (s != varname) { memmove(varname, s, strlen(s)+1); } for (p = varname; *p && *p != '['; p++) { switch(*p) { case ' ': case '.': *p = '_'; break; } } /* find index */ index = strchr(varname, '['); if (index) { index++; s = index; } else { return; } /* done? */ while (index) { while (*index == ' ' || *index == '\r' || *index == '\n' || *index=='\t') { index++; } indexend = strchr(index, ']'); indexend = indexend ? indexend + 1 : index + strlen(index); if (s != index) { memmove(s, index, strlen(index)+1); s += indexend-index; } else { s = indexend; } if (*s == '[') { s++; index = s; } else { index = NULL; } } *s = '\0'; } /* }}} */ static void add_protected_variable(char *varname TSRMLS_DC) /* {{{ */ { int dummy = 1; normalize_protected_variable(varname TSRMLS_CC); zend_hash_add(&PG(rfc1867_protected_variables), varname, strlen(varname)+1, &dummy, sizeof(int), NULL); } /* }}} */ static zend_bool is_protected_variable(char *varname TSRMLS_DC) /* {{{ */ { normalize_protected_variable(varname TSRMLS_CC); return zend_hash_exists(&PG(rfc1867_protected_variables), varname, strlen(varname)+1); } /* }}} */ static void safe_php_register_variable(char *var, char *strval, int val_len, zval *track_vars_array, zend_bool override_protection TSRMLS_DC) /* {{{ */ { if (override_protection || !is_protected_variable(var TSRMLS_CC)) { php_register_variable_safe(var, strval, val_len, track_vars_array TSRMLS_CC); } } /* }}} */ static void safe_php_register_variable_ex(char *var, zval *val, zval *track_vars_array, zend_bool override_protection TSRMLS_DC) /* {{{ */ { if (override_protection || !is_protected_variable(var TSRMLS_CC)) { php_register_variable_ex(var, val, track_vars_array TSRMLS_CC); } } /* }}} */ static void register_http_post_files_variable(char *strvar, char *val, zval *http_post_files, zend_bool override_protection TSRMLS_DC) /* {{{ */ { safe_php_register_variable(strvar, val, strlen(val), http_post_files, override_protection TSRMLS_CC); } /* }}} */ static void register_http_post_files_variable_ex(char *var, zval *val, zval *http_post_files, zend_bool override_protection TSRMLS_DC) /* {{{ */ { safe_php_register_variable_ex(var, val, http_post_files, override_protection TSRMLS_CC); } /* }}} */ static int unlink_filename(char **filename TSRMLS_DC) /* {{{ */ { VCWD_UNLINK(*filename); return 0; } /* }}} */ void destroy_uploaded_files_hash(TSRMLS_D) /* {{{ */ { zend_hash_apply(SG(rfc1867_uploaded_files), (apply_func_t) unlink_filename TSRMLS_CC); zend_hash_destroy(SG(rfc1867_uploaded_files)); FREE_HASHTABLE(SG(rfc1867_uploaded_files)); } /* }}} */ /* {{{ Following code is based on apache_multipart_buffer.c from libapreq-0.33 package. */ #define FILLUNIT (1024 * 5) typedef struct { /* read buffer */ char *buffer; char *buf_begin; int bufsize; int bytes_in_buffer; /* boundary info */ char *boundary; char *boundary_next; int boundary_next_len; const zend_encoding *input_encoding; const zend_encoding **detect_order; size_t detect_order_size; } multipart_buffer; typedef struct { char *key; char *value; } mime_header_entry; /* * Fill up the buffer with client data. * Returns number of bytes added to buffer. */ static int fill_buffer(multipart_buffer *self TSRMLS_DC) { int bytes_to_read, total_read = 0, actual_read = 0; /* shift the existing data if necessary */ if (self->bytes_in_buffer > 0 && self->buf_begin != self->buffer) { memmove(self->buffer, self->buf_begin, self->bytes_in_buffer); } self->buf_begin = self->buffer; /* calculate the free space in the buffer */ bytes_to_read = self->bufsize - self->bytes_in_buffer; /* read the required number of bytes */ while (bytes_to_read > 0) { char *buf = self->buffer + self->bytes_in_buffer; actual_read = sapi_module.read_post(buf, bytes_to_read TSRMLS_CC); /* update the buffer length */ if (actual_read > 0) { self->bytes_in_buffer += actual_read; SG(read_post_bytes) += actual_read; total_read += actual_read; bytes_to_read -= actual_read; } else { break; } } return total_read; } /* eof if we are out of bytes, or if we hit the final boundary */ static int multipart_buffer_eof(multipart_buffer *self TSRMLS_DC) { if ( (self->bytes_in_buffer == 0 && fill_buffer(self TSRMLS_CC) < 1) ) { return 1; } else { return 0; } } /* create new multipart_buffer structure */ static multipart_buffer *multipart_buffer_new(char *boundary, int boundary_len TSRMLS_DC) { multipart_buffer *self = (multipart_buffer *) ecalloc(1, sizeof(multipart_buffer)); int minsize = boundary_len + 6; if (minsize < FILLUNIT) minsize = FILLUNIT; self->buffer = (char *) ecalloc(1, minsize + 1); self->bufsize = minsize; spprintf(&self->boundary, 0, "--%s", boundary); self->boundary_next_len = spprintf(&self->boundary_next, 0, "\n--%s", boundary); self->buf_begin = self->buffer; self->bytes_in_buffer = 0; if (php_rfc1867_encoding_translation(TSRMLS_C)) { php_rfc1867_get_detect_order(&self->detect_order, &self->detect_order_size TSRMLS_CC); } else { self->detect_order = NULL; self->detect_order_size = 0; } self->input_encoding = NULL; return self; } /* * Gets the next CRLF terminated line from the input buffer. * If it doesn't find a CRLF, and the buffer isn't completely full, returns * NULL; otherwise, returns the beginning of the null-terminated line, * minus the CRLF. * * Note that we really just look for LF terminated lines. This works * around a bug in internet explorer for the macintosh which sends mime * boundaries that are only LF terminated when you use an image submit * button in a multipart/form-data form. */ static char *next_line(multipart_buffer *self) { /* look for LF in the data */ char* line = self->buf_begin; char* ptr = memchr(self->buf_begin, '\n', self->bytes_in_buffer); if (ptr) { /* LF found */ /* terminate the string, remove CRLF */ if ((ptr - line) > 0 && *(ptr-1) == '\r') { *(ptr-1) = 0; } else { *ptr = 0; } /* bump the pointer */ self->buf_begin = ptr + 1; self->bytes_in_buffer -= (self->buf_begin - line); } else { /* no LF found */ /* buffer isn't completely full, fail */ if (self->bytes_in_buffer < self->bufsize) { return NULL; } /* return entire buffer as a partial line */ line[self->bufsize] = 0; self->buf_begin = ptr; self->bytes_in_buffer = 0; } return line; } /* Returns the next CRLF terminated line from the client */ static char *get_line(multipart_buffer *self TSRMLS_DC) { char* ptr = next_line(self); if (!ptr) { fill_buffer(self TSRMLS_CC); ptr = next_line(self); } return ptr; } /* Free header entry */ static void php_free_hdr_entry(mime_header_entry *h) { if (h->key) { efree(h->key); } if (h->value) { efree(h->value); } } /* finds a boundary */ static int find_boundary(multipart_buffer *self, char *boundary TSRMLS_DC) { char *line; /* loop thru lines */ while( (line = get_line(self TSRMLS_CC)) ) { /* finished if we found the boundary */ if (!strcmp(line, boundary)) { return 1; } } /* didn't find the boundary */ return 0; } /* parse headers */ static int multipart_buffer_headers(multipart_buffer *self, zend_llist *header TSRMLS_DC) { char *line; mime_header_entry prev_entry, entry; int prev_len, cur_len; /* didn't find boundary, abort */ if (!find_boundary(self, self->boundary TSRMLS_CC)) { return 0; } /* get lines of text, or CRLF_CRLF */ while( (line = get_line(self TSRMLS_CC)) && strlen(line) > 0 ) { /* add header to table */ char *key = line; char *value = NULL; if (php_rfc1867_encoding_translation(TSRMLS_C)) { self->input_encoding = zend_multibyte_encoding_detector(line, strlen(line), self->detect_order, self->detect_order_size TSRMLS_CC); } /* space in the beginning means same header */ if (!isspace(line[0])) { value = strchr(line, ':'); } if (value) { *value = 0; do { value++; } while(isspace(*value)); entry.value = estrdup(value); entry.key = estrdup(key); } else if (zend_llist_count(header)) { /* If no ':' on the line, add to previous line */ prev_len = strlen(prev_entry.value); cur_len = strlen(line); entry.value = emalloc(prev_len + cur_len + 1); memcpy(entry.value, prev_entry.value, prev_len); memcpy(entry.value + prev_len, line, cur_len); entry.value[cur_len + prev_len] = '\0'; entry.key = estrdup(prev_entry.key); zend_llist_remove_tail(header); } else { continue; } zend_llist_add_element(header, &entry); prev_entry = entry; } return 1; } static char *php_mime_get_hdr_value(zend_llist header, char *key) { mime_header_entry *entry; if (key == NULL) { return NULL; } entry = zend_llist_get_first(&header); while (entry) { if (!strcasecmp(entry->key, key)) { return entry->value; } entry = zend_llist_get_next(&header); } return NULL; } static char *php_ap_getword(const zend_encoding *encoding, char **line, char stop TSRMLS_DC) { char *pos = *line, quote; char *res; while (*pos && *pos != stop) { if ((quote = *pos) == '"' || quote == '\'') { ++pos; while (*pos && *pos != quote) { if (*pos == '\\' && pos[1] && pos[1] == quote) { pos += 2; } else { ++pos; } } if (*pos) { ++pos; } } else ++pos; } if (*pos == '\0') { res = estrdup(*line); *line += strlen(*line); return res; } res = estrndup(*line, pos - *line); while (*pos == stop) { ++pos; } *line = pos; return res; } static char *substring_conf(char *start, int len, char quote) { char *result = emalloc(len + 1); char *resp = result; int i; for (i = 0; i < len && start[i] != quote; ++i) { if (start[i] == '\\' && (start[i + 1] == '\\' || (quote && start[i + 1] == quote))) { *resp++ = start[++i]; } else { *resp++ = start[i]; } } *resp = '\0'; return result; } static char *php_ap_getword_conf(const zend_encoding *encoding, char *str TSRMLS_DC) { while (*str && isspace(*str)) { ++str; } if (!*str) { return estrdup(""); } if (*str == '"' || *str == '\'') { char quote = *str; str++; return substring_conf(str, strlen(str), quote); } else { char *strend = str; while (*strend && !isspace(*strend)) { ++strend; } return substring_conf(str, strend - str, 0); } } static char *php_ap_basename(const zend_encoding *encoding, char *path TSRMLS_DC) { char *s = strrchr(path, '\\'); char *s2 = strrchr(path, '/'); if (s && s2) { if (s > s2) { ++s; } else { s = ++s2; } return s; } else if (s) { return ++s; } else if (s2) { return ++s2; } return path; } /* * Search for a string in a fixed-length byte string. * If partial is true, partial matches are allowed at the end of the buffer. * Returns NULL if not found, or a pointer to the start of the first match. */ static void *php_ap_memstr(char *haystack, int haystacklen, char *needle, int needlen, int partial) { int len = haystacklen; char *ptr = haystack; /* iterate through first character matches */ while( (ptr = memchr(ptr, needle[0], len)) ) { /* calculate length after match */ len = haystacklen - (ptr - (char *)haystack); /* done if matches up to capacity of buffer */ if (memcmp(needle, ptr, needlen < len ? needlen : len) == 0 && (partial || len >= needlen)) { break; } /* next character */ ptr++; len--; } return ptr; } /* read until a boundary condition */ static int multipart_buffer_read(multipart_buffer *self, char *buf, int bytes, int *end TSRMLS_DC) { int len, max; char *bound; /* fill buffer if needed */ if (bytes > self->bytes_in_buffer) { fill_buffer(self TSRMLS_CC); } /* look for a potential boundary match, only read data up to that point */ if ((bound = php_ap_memstr(self->buf_begin, self->bytes_in_buffer, self->boundary_next, self->boundary_next_len, 1))) { max = bound - self->buf_begin; if (end && php_ap_memstr(self->buf_begin, self->bytes_in_buffer, self->boundary_next, self->boundary_next_len, 0)) { *end = 1; } } else { max = self->bytes_in_buffer; } /* maximum number of bytes we are reading */ len = max < bytes-1 ? max : bytes-1; /* if we read any data... */ if (len > 0) { /* copy the data */ memcpy(buf, self->buf_begin, len); buf[len] = 0; if (bound && len > 0 && buf[len-1] == '\r') { buf[--len] = 0; } /* update the buffer */ self->bytes_in_buffer -= len; self->buf_begin += len; } return len; } /* XXX: this is horrible memory-usage-wise, but we only expect to do this on small pieces of form data. */ static char *multipart_buffer_read_body(multipart_buffer *self, unsigned int *len TSRMLS_DC) { char buf[FILLUNIT], *out=NULL; int total_bytes=0, read_bytes=0; while((read_bytes = multipart_buffer_read(self, buf, sizeof(buf), NULL TSRMLS_CC))) { out = erealloc(out, total_bytes + read_bytes + 1); memcpy(out + total_bytes, buf, read_bytes); total_bytes += read_bytes; } if (out) { out[total_bytes] = '\0'; } *len = total_bytes; return out; } /* }}} */ /* * The combined READER/HANDLER * */ SAPI_API SAPI_POST_HANDLER_FUNC(rfc1867_post_handler) /* {{{ */ { char *boundary, *s = NULL, *boundary_end = NULL, *start_arr = NULL, *array_index = NULL; char *temp_filename = NULL, *lbuf = NULL, *abuf = NULL; int boundary_len = 0, total_bytes = 0, cancel_upload = 0, is_arr_upload = 0, array_len = 0; int max_file_size = 0, skip_upload = 0, anonindex = 0, is_anonymous; zval *http_post_files = NULL; HashTable *uploaded_files = NULL; multipart_buffer *mbuff; zval *array_ptr = (zval *) arg; int fd = -1; zend_llist header; void *event_extra_data = NULL; unsigned int llen = 0; int upload_cnt = INI_INT("max_file_uploads"); const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding(TSRMLS_C); php_rfc1867_getword_t getword; php_rfc1867_getword_conf_t getword_conf; php_rfc1867_basename_t _basename; if (php_rfc1867_encoding_translation(TSRMLS_C) && internal_encoding) { getword = php_rfc1867_getword; getword_conf = php_rfc1867_getword_conf; _basename = php_rfc1867_basename; } else { getword = php_ap_getword; getword_conf = php_ap_getword_conf; _basename = php_ap_basename; } if (SG(post_max_size) > 0 && SG(request_info).content_length > SG(post_max_size)) { sapi_module.sapi_error(E_WARNING, "POST Content-Length of %ld bytes exceeds the limit of %ld bytes", SG(request_info).content_length, SG(post_max_size)); return; } /* Get the boundary */ boundary = strstr(content_type_dup, "boundary"); if (!boundary) { int content_type_len = strlen(content_type_dup); char *content_type_lcase = estrndup(content_type_dup, content_type_len); php_strtolower(content_type_lcase, content_type_len); boundary = strstr(content_type_lcase, "boundary"); if (boundary) { boundary = content_type_dup + (boundary - content_type_lcase); } efree(content_type_lcase); } if (!boundary || !(boundary = strchr(boundary, '='))) { sapi_module.sapi_error(E_WARNING, "Missing boundary in multipart/form-data POST data"); return; } boundary++; boundary_len = strlen(boundary); if (boundary[0] == '"') { boundary++; boundary_end = strchr(boundary, '"'); if (!boundary_end) { sapi_module.sapi_error(E_WARNING, "Invalid boundary in multipart/form-data POST data"); return; } } else { /* search for the end of the boundary */ boundary_end = strpbrk(boundary, ",;"); } if (boundary_end) { boundary_end[0] = '\0'; boundary_len = boundary_end-boundary; } /* Initialize the buffer */ if (!(mbuff = multipart_buffer_new(boundary, boundary_len TSRMLS_CC))) { sapi_module.sapi_error(E_WARNING, "Unable to initialize the input buffer"); return; } /* Initialize $_FILES[] */ zend_hash_init(&PG(rfc1867_protected_variables), 5, NULL, NULL, 0); ALLOC_HASHTABLE(uploaded_files); zend_hash_init(uploaded_files, 5, NULL, (dtor_func_t) free_estring, 0); SG(rfc1867_uploaded_files) = uploaded_files; ALLOC_ZVAL(http_post_files); array_init(http_post_files); INIT_PZVAL(http_post_files); PG(http_globals)[TRACK_VARS_FILES] = http_post_files; zend_llist_init(&header, sizeof(mime_header_entry), (llist_dtor_func_t) php_free_hdr_entry, 0); if (php_rfc1867_callback != NULL) { multipart_event_start event_start; event_start.content_length = SG(request_info).content_length; if (php_rfc1867_callback(MULTIPART_EVENT_START, &event_start, &event_extra_data TSRMLS_CC) == FAILURE) { goto fileupload_done; } } while (!multipart_buffer_eof(mbuff TSRMLS_CC)) { char buff[FILLUNIT]; char *cd = NULL, *param = NULL, *filename = NULL, *tmp = NULL; size_t blen = 0, wlen = 0; off_t offset; zend_llist_clean(&header); if (!multipart_buffer_headers(mbuff, &header TSRMLS_CC)) { goto fileupload_done; } if ((cd = php_mime_get_hdr_value(header, "Content-Disposition"))) { char *pair = NULL; int end = 0; while (isspace(*cd)) { ++cd; } while (*cd && (pair = getword(mbuff->input_encoding, &cd, ';' TSRMLS_CC))) { char *key = NULL, *word = pair; while (isspace(*cd)) { ++cd; } if (strchr(pair, '=')) { key = getword(mbuff->input_encoding, &pair, '=' TSRMLS_CC); if (!strcasecmp(key, "name")) { if (param) { efree(param); } param = getword_conf(mbuff->input_encoding, pair TSRMLS_CC); if (mbuff->input_encoding && internal_encoding) { unsigned char *new_param; size_t new_param_len; if ((size_t)-1 != zend_multibyte_encoding_converter(&new_param, &new_param_len, (unsigned char *)param, strlen(param), internal_encoding, mbuff->input_encoding TSRMLS_CC)) { efree(param); param = (char *)new_param; } } } else if (!strcasecmp(key, "filename")) { if (filename) { efree(filename); } filename = getword_conf(mbuff->input_encoding, pair TSRMLS_CC); if (mbuff->input_encoding && internal_encoding) { unsigned char *new_filename; size_t new_filename_len; if ((size_t)-1 != zend_multibyte_encoding_converter(&new_filename, &new_filename_len, (unsigned char *)filename, strlen(filename), internal_encoding, mbuff->input_encoding TSRMLS_CC)) { efree(filename); filename = (char *)new_filename; } } } } if (key) { efree(key); } efree(word); } /* Normal form variable, safe to read all data into memory */ if (!filename && param) { unsigned int value_len; char *value = multipart_buffer_read_body(mbuff, &value_len TSRMLS_CC); unsigned int new_val_len; /* Dummy variable */ if (!value) { value = estrdup(""); value_len = 0; } if (mbuff->input_encoding && internal_encoding) { unsigned char *new_value; size_t new_value_len; if ((size_t)-1 != zend_multibyte_encoding_converter(&new_value, &new_value_len, (unsigned char *)value, value_len, internal_encoding, mbuff->input_encoding TSRMLS_CC)) { efree(value); value = (char *)new_value; value_len = new_value_len; } } if (sapi_module.input_filter(PARSE_POST, param, &value, value_len, &new_val_len TSRMLS_CC)) { if (php_rfc1867_callback != NULL) { multipart_event_formdata event_formdata; size_t newlength = new_val_len; event_formdata.post_bytes_processed = SG(read_post_bytes); event_formdata.name = param; event_formdata.value = &value; event_formdata.length = new_val_len; event_formdata.newlength = &newlength; if (php_rfc1867_callback(MULTIPART_EVENT_FORMDATA, &event_formdata, &event_extra_data TSRMLS_CC) == FAILURE) { efree(param); efree(value); continue; } new_val_len = newlength; } safe_php_register_variable(param, value, new_val_len, array_ptr, 0 TSRMLS_CC); } else if (php_rfc1867_callback != NULL) { multipart_event_formdata event_formdata; event_formdata.post_bytes_processed = SG(read_post_bytes); event_formdata.name = param; event_formdata.value = &value; event_formdata.length = value_len; event_formdata.newlength = NULL; php_rfc1867_callback(MULTIPART_EVENT_FORMDATA, &event_formdata, &event_extra_data TSRMLS_CC); } if (!strcasecmp(param, "MAX_FILE_SIZE")) { max_file_size = atol(value); } efree(param); efree(value); continue; } /* If file_uploads=off, skip the file part */ if (!PG(file_uploads)) { skip_upload = 1; } else if (upload_cnt <= 0) { skip_upload = 1; sapi_module.sapi_error(E_WARNING, "Maximum number of allowable file uploads has been exceeded"); } /* Return with an error if the posted data is garbled */ if (!param && !filename) { sapi_module.sapi_error(E_WARNING, "File Upload Mime headers garbled"); goto fileupload_done; } if (!param) { is_anonymous = 1; param = emalloc(MAX_SIZE_ANONNAME); snprintf(param, MAX_SIZE_ANONNAME, "%u", anonindex++); } else { is_anonymous = 0; } /* New Rule: never repair potential malicious user input */ if (!skip_upload) { long c = 0; tmp = param; while (*tmp) { if (*tmp == '[') { c++; } else if (*tmp == ']') { c--; if (tmp[1] && tmp[1] != '[') { skip_upload = 1; break; } } if (c < 0) { skip_upload = 1; break; } tmp++; } /* Brackets should always be closed */ if(c != 0) { skip_upload = 1; } } total_bytes = cancel_upload = 0; temp_filename = NULL; fd = -1; if (!skip_upload && php_rfc1867_callback != NULL) { multipart_event_file_start event_file_start; event_file_start.post_bytes_processed = SG(read_post_bytes); event_file_start.name = param; event_file_start.filename = &filename; if (php_rfc1867_callback(MULTIPART_EVENT_FILE_START, &event_file_start, &event_extra_data TSRMLS_CC) == FAILURE) { temp_filename = ""; efree(param); efree(filename); continue; } } if (skip_upload) { efree(param); efree(filename); continue; } if (strlen(filename) == 0) { #if DEBUG_FILE_UPLOAD sapi_module.sapi_error(E_NOTICE, "No file uploaded"); #endif cancel_upload = UPLOAD_ERROR_D; } offset = 0; end = 0; if (!cancel_upload) { /* only bother to open temp file if we have data */ blen = multipart_buffer_read(mbuff, buff, sizeof(buff), &end TSRMLS_CC); #if DEBUG_FILE_UPLOAD if (blen > 0) { #else /* in non-debug mode we have no problem with 0-length files */ { #endif fd = php_open_temporary_fd_ex(PG(upload_tmp_dir), "php", &temp_filename, 1 TSRMLS_CC); upload_cnt--; if (fd == -1) { sapi_module.sapi_error(E_WARNING, "File upload error - unable to create a temporary file"); cancel_upload = UPLOAD_ERROR_E; } } } while (!cancel_upload && (blen > 0)) { if (php_rfc1867_callback != NULL) { multipart_event_file_data event_file_data; event_file_data.post_bytes_processed = SG(read_post_bytes); event_file_data.offset = offset; event_file_data.data = buff; event_file_data.length = blen; event_file_data.newlength = &blen; if (php_rfc1867_callback(MULTIPART_EVENT_FILE_DATA, &event_file_data, &event_extra_data TSRMLS_CC) == FAILURE) { cancel_upload = UPLOAD_ERROR_X; continue; } } if (PG(upload_max_filesize) > 0 && (long)(total_bytes+blen) > PG(upload_max_filesize)) { #if DEBUG_FILE_UPLOAD sapi_module.sapi_error(E_NOTICE, "upload_max_filesize of %ld bytes exceeded - file [%s=%s] not saved", PG(upload_max_filesize), param, filename); #endif cancel_upload = UPLOAD_ERROR_A; } else if (max_file_size && ((long)(total_bytes+blen) > max_file_size)) { #if DEBUG_FILE_UPLOAD sapi_module.sapi_error(E_NOTICE, "MAX_FILE_SIZE of %ld bytes exceeded - file [%s=%s] not saved", max_file_size, param, filename); #endif cancel_upload = UPLOAD_ERROR_B; } else if (blen > 0) { wlen = write(fd, buff, blen); if (wlen == -1) { /* write failed */ #if DEBUG_FILE_UPLOAD sapi_module.sapi_error(E_NOTICE, "write() failed - %s", strerror(errno)); #endif cancel_upload = UPLOAD_ERROR_F; } else if (wlen < blen) { #if DEBUG_FILE_UPLOAD sapi_module.sapi_error(E_NOTICE, "Only %d bytes were written, expected to write %d", wlen, blen); #endif cancel_upload = UPLOAD_ERROR_F; } else { total_bytes += wlen; } offset += wlen; } /* read data for next iteration */ blen = multipart_buffer_read(mbuff, buff, sizeof(buff), &end TSRMLS_CC); } if (fd != -1) { /* may not be initialized if file could not be created */ close(fd); } if (!cancel_upload && !end) { #if DEBUG_FILE_UPLOAD sapi_module.sapi_error(E_NOTICE, "Missing mime boundary at the end of the data for file %s", strlen(filename) > 0 ? filename : ""); #endif cancel_upload = UPLOAD_ERROR_C; } #if DEBUG_FILE_UPLOAD if (strlen(filename) > 0 && total_bytes == 0 && !cancel_upload) { sapi_module.sapi_error(E_WARNING, "Uploaded file size 0 - file [%s=%s] not saved", param, filename); cancel_upload = 5; } #endif if (php_rfc1867_callback != NULL) { multipart_event_file_end event_file_end; event_file_end.post_bytes_processed = SG(read_post_bytes); event_file_end.temp_filename = temp_filename; event_file_end.cancel_upload = cancel_upload; if (php_rfc1867_callback(MULTIPART_EVENT_FILE_END, &event_file_end, &event_extra_data TSRMLS_CC) == FAILURE) { cancel_upload = UPLOAD_ERROR_X; } } if (cancel_upload) { if (temp_filename) { if (cancel_upload != UPLOAD_ERROR_E) { /* file creation failed */ unlink(temp_filename); } efree(temp_filename); } temp_filename = ""; } else { zend_hash_add(SG(rfc1867_uploaded_files), temp_filename, strlen(temp_filename) + 1, &temp_filename, sizeof(char *), NULL); } /* is_arr_upload is true when name of file upload field * ends in [.*] * start_arr is set to point to 1st [ */ is_arr_upload = (start_arr = strchr(param,'[')) && (param[strlen(param)-1] == ']'); if (is_arr_upload) { array_len = strlen(start_arr); if (array_index) { efree(array_index); } array_index = estrndup(start_arr + 1, array_len - 2); } /* Add $foo_name */ if (llen < strlen(param) + MAX_SIZE_OF_INDEX + 1) { llen = strlen(param); lbuf = (char *) safe_erealloc(lbuf, llen, 1, MAX_SIZE_OF_INDEX + 1); llen += MAX_SIZE_OF_INDEX + 1; } if (is_arr_upload) { if (abuf) efree(abuf); abuf = estrndup(param, strlen(param)-array_len); snprintf(lbuf, llen, "%s_name[%s]", abuf, array_index); } else { snprintf(lbuf, llen, "%s_name", param); } /* The \ check should technically be needed for win32 systems only where * it is a valid path separator. However, IE in all it's wisdom always sends * the full path of the file on the user's filesystem, which means that unless * the user does basename() they get a bogus file name. Until IE's user base drops * to nill or problem is fixed this code must remain enabled for all systems. */ s = _basename(internal_encoding, filename TSRMLS_CC); if (!s) { s = filename; } if (!is_anonymous) { safe_php_register_variable(lbuf, s, strlen(s), NULL, 0 TSRMLS_CC); } /* Add $foo[name] */ if (is_arr_upload) { snprintf(lbuf, llen, "%s[name][%s]", abuf, array_index); } else { snprintf(lbuf, llen, "%s[name]", param); } register_http_post_files_variable(lbuf, s, http_post_files, 0 TSRMLS_CC); efree(filename); s = NULL; /* Possible Content-Type: */ if (cancel_upload || !(cd = php_mime_get_hdr_value(header, "Content-Type"))) { cd = ""; } else { /* fix for Opera 6.01 */ s = strchr(cd, ';'); if (s != NULL) { *s = '\0'; } } /* Add $foo_type */ if (is_arr_upload) { snprintf(lbuf, llen, "%s_type[%s]", abuf, array_index); } else { snprintf(lbuf, llen, "%s_type", param); } if (!is_anonymous) { safe_php_register_variable(lbuf, cd, strlen(cd), NULL, 0 TSRMLS_CC); } /* Add $foo[type] */ if (is_arr_upload) { snprintf(lbuf, llen, "%s[type][%s]", abuf, array_index); } else { snprintf(lbuf, llen, "%s[type]", param); } register_http_post_files_variable(lbuf, cd, http_post_files, 0 TSRMLS_CC); /* Restore Content-Type Header */ if (s != NULL) { *s = ';'; } s = ""; { /* store temp_filename as-is (in case upload_tmp_dir * contains escapeable characters. escape only the variable name.) */ zval zfilename; /* Initialize variables */ add_protected_variable(param TSRMLS_CC); /* if param is of form xxx[.*] this will cut it to xxx */ if (!is_anonymous) { ZVAL_STRING(&zfilename, temp_filename, 1); safe_php_register_variable_ex(param, &zfilename, NULL, 1 TSRMLS_CC); } /* Add $foo[tmp_name] */ if (is_arr_upload) { snprintf(lbuf, llen, "%s[tmp_name][%s]", abuf, array_index); } else { snprintf(lbuf, llen, "%s[tmp_name]", param); } add_protected_variable(lbuf TSRMLS_CC); ZVAL_STRING(&zfilename, temp_filename, 1); register_http_post_files_variable_ex(lbuf, &zfilename, http_post_files, 1 TSRMLS_CC); } { zval file_size, error_type; error_type.value.lval = cancel_upload; error_type.type = IS_LONG; /* Add $foo[error] */ if (cancel_upload) { file_size.value.lval = 0; file_size.type = IS_LONG; } else { file_size.value.lval = total_bytes; file_size.type = IS_LONG; } if (is_arr_upload) { snprintf(lbuf, llen, "%s[error][%s]", abuf, array_index); } else { snprintf(lbuf, llen, "%s[error]", param); } register_http_post_files_variable_ex(lbuf, &error_type, http_post_files, 0 TSRMLS_CC); /* Add $foo_size */ if (is_arr_upload) { snprintf(lbuf, llen, "%s_size[%s]", abuf, array_index); } else { snprintf(lbuf, llen, "%s_size", param); } if (!is_anonymous) { safe_php_register_variable_ex(lbuf, &file_size, NULL, 0 TSRMLS_CC); } /* Add $foo[size] */ if (is_arr_upload) { snprintf(lbuf, llen, "%s[size][%s]", abuf, array_index); } else { snprintf(lbuf, llen, "%s[size]", param); } register_http_post_files_variable_ex(lbuf, &file_size, http_post_files, 0 TSRMLS_CC); } efree(param); } } fileupload_done: if (php_rfc1867_callback != NULL) { multipart_event_end event_end; event_end.post_bytes_processed = SG(read_post_bytes); php_rfc1867_callback(MULTIPART_EVENT_END, &event_end, &event_extra_data TSRMLS_CC); } if (lbuf) efree(lbuf); if (abuf) efree(abuf); if (array_index) efree(array_index); zend_hash_destroy(&PG(rfc1867_protected_variables)); zend_llist_destroy(&header); if (mbuff->boundary_next) efree(mbuff->boundary_next); if (mbuff->boundary) efree(mbuff->boundary); if (mbuff->buffer) efree(mbuff->buffer); if (mbuff) efree(mbuff); } /* }}} */ SAPI_API void php_rfc1867_set_multibyte_callbacks( php_rfc1867_encoding_translation_t encoding_translation, php_rfc1867_get_detect_order_t get_detect_order, php_rfc1867_set_input_encoding_t set_input_encoding, php_rfc1867_getword_t getword, php_rfc1867_getword_conf_t getword_conf, php_rfc1867_basename_t basename) /* {{{ */ { php_rfc1867_encoding_translation = encoding_translation; php_rfc1867_get_detect_order = get_detect_order; php_rfc1867_set_input_encoding = set_input_encoding; php_rfc1867_getword = getword; php_rfc1867_getword_conf = getword_conf; php_rfc1867_basename = basename; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2012-01-01-80dd931d40-7c3177e5ab.c
manybugs_data_75
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2012 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <zend_language_parser.h> #include "zend.h" #include "zend_compile.h" #include "zend_constants.h" #include "zend_llist.h" #include "zend_API.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "zend_multibyte.h" #include "zend_language_scanner.h" #define CONSTANT_EX(op_array, op) \ (op_array)->literals[op].constant #define CONSTANT(op) \ CONSTANT_EX(CG(active_op_array), op) #define SET_NODE(target, src) do { \ target ## _type = (src)->op_type; \ if ((src)->op_type == IS_CONST) { \ target.constant = zend_add_literal(CG(active_op_array), &(src)->u.constant TSRMLS_CC); \ } else { \ target = (src)->u.op; \ } \ } while (0) #define GET_NODE(target, src) do { \ (target)->op_type = src ## _type; \ if ((target)->op_type == IS_CONST) { \ (target)->u.constant = CONSTANT(src.constant); \ } else { \ (target)->u.op = src; \ (target)->EA = 0; \ } \ } while (0) #define COPY_NODE(target, src) do { \ target ## _type = src ## _type; \ target = src; \ } while (0) #define CALCULATE_LITERAL_HASH(num) do { \ if (IS_INTERNED(Z_STRVAL(CONSTANT(num)))) { \ Z_HASH_P(&CONSTANT(num)) = INTERNED_HASH(Z_STRVAL(CONSTANT(num))); \ } else { \ Z_HASH_P(&CONSTANT(num)) = zend_hash_func(Z_STRVAL(CONSTANT(num)), Z_STRLEN(CONSTANT(num))+1); \ } \ } while (0) #define GET_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot++; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ } \ } while (0) #define POLYMORPHIC_CACHE_SLOT_SIZE 2 #define GET_POLYMORPHIC_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot; \ CG(active_op_array)->last_cache_slot += POLYMORPHIC_CACHE_SLOT_SIZE; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 2] = NULL; \ } \ } while (0) #define FREE_POLYMORPHIC_CACHE_SLOT(literal) do { \ if (CG(active_op_array)->literals[literal].cache_slot != -1 && \ CG(active_op_array)->literals[literal].cache_slot == \ CG(active_op_array)->last_cache_slot - POLYMORPHIC_CACHE_SLOT_SIZE) { \ CG(active_op_array)->literals[literal].cache_slot = -1; \ CG(active_op_array)->last_cache_slot -= POLYMORPHIC_CACHE_SLOT_SIZE; \ } \ } while (0) ZEND_API zend_op_array *(*zend_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); ZEND_API zend_op_array *(*zend_compile_string)(zval *source_string, char *filename TSRMLS_DC); #ifndef ZTS ZEND_API zend_compiler_globals compiler_globals; ZEND_API zend_executor_globals executor_globals; #endif static void zend_duplicate_property_info(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = estrndup(property_info->name, property_info->name_length); } if (property_info->doc_comment) { property_info->doc_comment = estrndup(property_info->doc_comment, property_info->doc_comment_len); } } /* }}} */ static void zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = zend_strndup(property_info->name, property_info->name_length); } } /* }}} */ static void zend_destroy_property_info(zend_property_info *property_info) /* {{{ */ { str_efree(property_info->name); if (property_info->doc_comment) { efree((char*)property_info->doc_comment); } } /* }}} */ static void zend_destroy_property_info_internal(zend_property_info *property_info) /* {{{ */ { str_free((char*)property_info->name); } /* }}} */ static void build_runtime_defined_function_key(zval *result, const char *name, int name_length TSRMLS_DC) /* {{{ */ { char char_pos_buf[32]; uint char_pos_len; const char *filename; char_pos_len = zend_sprintf(char_pos_buf, "%p", LANG_SCNG(yy_text)); if (CG(active_op_array)->filename) { filename = CG(active_op_array)->filename; } else { filename = "-"; } /* NULL, name length, filename length, last accepting char position length */ result->value.str.len = 1+name_length+strlen(filename)+char_pos_len; /* must be binary safe */ result->value.str.val = (char *) safe_emalloc(result->value.str.len, 1, 1); result->value.str.val[0] = '\0'; sprintf(result->value.str.val+1, "%s%s%s", name, filename, char_pos_buf); result->type = IS_STRING; Z_SET_REFCOUNT_P(result, 1); } /* }}} */ static void init_compiler_declarables(TSRMLS_D) /* {{{ */ { Z_TYPE(CG(declarables).ticks) = IS_LONG; Z_LVAL(CG(declarables).ticks) = 0; } /* }}} */ void zend_init_compiler_context(TSRMLS_D) /* {{{ */ { CG(context).opcodes_size = (CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) ? INITIAL_INTERACTIVE_OP_ARRAY_SIZE : INITIAL_OP_ARRAY_SIZE; CG(context).vars_size = 0; CG(context).literals_size = 0; CG(context).current_brk_cont = -1; CG(context).backpatch_count = 0; CG(context).labels = NULL; } /* }}} */ void zend_init_compiler_data_structures(TSRMLS_D) /* {{{ */ { zend_stack_init(&CG(bp_stack)); zend_stack_init(&CG(function_call_stack)); zend_stack_init(&CG(switch_cond_stack)); zend_stack_init(&CG(foreach_copy_stack)); zend_stack_init(&CG(object_stack)); zend_stack_init(&CG(declare_stack)); CG(active_class_entry) = NULL; zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_stack_init(&CG(list_stack)); CG(in_compilation) = 0; CG(start_lineno) = 0; CG(current_namespace) = NULL; CG(in_namespace) = 0; CG(has_bracketed_namespaces) = 0; CG(current_import) = NULL; init_compiler_declarables(TSRMLS_C); zend_stack_init(&CG(context_stack)); CG(encoding_declared) = 0; } /* }}} */ ZEND_API void file_handle_dtor(zend_file_handle *fh) /* {{{ */ { TSRMLS_FETCH(); zend_file_handle_dtor(fh TSRMLS_CC); } /* }}} */ void init_compiler(TSRMLS_D) /* {{{ */ { CG(active_op_array) = NULL; zend_init_compiler_data_structures(TSRMLS_C); zend_init_rsrc_list(TSRMLS_C); zend_hash_init(&CG(filenames_table), 5, NULL, (dtor_func_t) free_estring, 0); zend_llist_init(&CG(open_files), sizeof(zend_file_handle), (void (*)(void *)) file_handle_dtor, 0); CG(unclean_shutdown) = 0; } /* }}} */ void shutdown_compiler(TSRMLS_D) /* {{{ */ { zend_stack_destroy(&CG(bp_stack)); zend_stack_destroy(&CG(function_call_stack)); zend_stack_destroy(&CG(switch_cond_stack)); zend_stack_destroy(&CG(foreach_copy_stack)); zend_stack_destroy(&CG(object_stack)); zend_stack_destroy(&CG(declare_stack)); zend_stack_destroy(&CG(list_stack)); zend_hash_destroy(&CG(filenames_table)); zend_llist_destroy(&CG(open_files)); zend_stack_destroy(&CG(context_stack)); } /* }}} */ ZEND_API char *zend_set_compiled_filename(const char *new_compiled_filename TSRMLS_DC) /* {{{ */ { char **pp, *p; int length = strlen(new_compiled_filename); if (zend_hash_find(&CG(filenames_table), new_compiled_filename, length+1, (void **) &pp) == SUCCESS) { CG(compiled_filename) = *pp; return *pp; } p = estrndup(new_compiled_filename, length); zend_hash_update(&CG(filenames_table), new_compiled_filename, length+1, &p, sizeof(char *), (void **) &pp); CG(compiled_filename) = p; return p; } /* }}} */ ZEND_API void zend_restore_compiled_filename(char *original_compiled_filename TSRMLS_DC) /* {{{ */ { CG(compiled_filename) = original_compiled_filename; } /* }}} */ ZEND_API char *zend_get_compiled_filename(TSRMLS_D) /* {{{ */ { return CG(compiled_filename); } /* }}} */ ZEND_API int zend_get_compiled_lineno(TSRMLS_D) /* {{{ */ { return CG(zend_lineno); } /* }}} */ ZEND_API zend_bool zend_is_compiling(TSRMLS_D) /* {{{ */ { return CG(in_compilation); } /* }}} */ static zend_uint get_temporary_variable(zend_op_array *op_array) /* {{{ */ { return (op_array->T)++ * ZEND_MM_ALIGNED_SIZE(sizeof(temp_variable)); } /* }}} */ static int lookup_cv(zend_op_array *op_array, char* name, int name_len, ulong hash TSRMLS_DC) /* {{{ */ { int i = 0; ulong hash_value = hash ? hash : zend_inline_hash_func(name, name_len+1); while (i < op_array->last_var) { if (op_array->vars[i].name == name || (op_array->vars[i].hash_value == hash_value && op_array->vars[i].name_len == name_len && memcmp(op_array->vars[i].name, name, name_len) == 0)) { str_efree(name); return i; } i++; } i = op_array->last_var; op_array->last_var++; if (op_array->last_var > CG(context).vars_size) { CG(context).vars_size += 16; /* FIXME */ op_array->vars = erealloc(op_array->vars, CG(context).vars_size * sizeof(zend_compiled_variable)); } op_array->vars[i].name = zend_new_interned_string(name, name_len + 1, 1 TSRMLS_CC); op_array->vars[i].name_len = name_len; op_array->vars[i].hash_value = hash_value; return i; } /* }}} */ void zend_del_literal(zend_op_array *op_array, int n) /* {{{ */ { zval_dtor(&CONSTANT_EX(op_array, n)); if (n + 1 == op_array->last_literal) { op_array->last_literal--; } else { Z_TYPE(CONSTANT_EX(op_array, n)) = IS_NULL; } } /* }}} */ /* Common part of zend_add_literal and zend_append_individual_literal */ static inline void zend_insert_literal(zend_op_array *op_array, const zval *zv, int literal_position TSRMLS_DC) /* {{{ */ { if (Z_TYPE_P(zv) == IS_STRING || Z_TYPE_P(zv) == IS_CONSTANT) { zval *z = (zval*)zv; Z_STRVAL_P(z) = (char*)zend_new_interned_string(Z_STRVAL_P(zv), Z_STRLEN_P(zv) + 1, 1 TSRMLS_CC); } CONSTANT_EX(op_array, literal_position) = *zv; Z_SET_REFCOUNT(CONSTANT_EX(op_array, literal_position), 2); Z_SET_ISREF(CONSTANT_EX(op_array, literal_position)); op_array->literals[literal_position].hash_value = 0; op_array->literals[literal_position].cache_slot = -1; } /* }}} */ /* Is used while compiling a function, using the context to keep track of an approximate size to avoid to relocate to often. Literals are truncated to actual size in the second compiler pass (pass_two()). */ int zend_add_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; if (i >= CG(context).literals_size) { while (i >= CG(context).literals_size) { CG(context).literals_size += 16; /* FIXME */ } op_array->literals = (zend_literal*)erealloc(op_array->literals, CG(context).literals_size * sizeof(zend_literal)); } zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ /* Is used after normal compilation to append an additional literal. Allocation is done precisely here. */ int zend_append_individual_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; op_array->literals = (zend_literal*)erealloc(op_array->literals, (i + 1) * sizeof(zend_literal)); zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ int zend_add_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_ns_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; const char *ns_separator; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); ns_separator = (const char*)zend_memrchr(Z_STRVAL_P(zv), '\\', Z_STRLEN_P(zv)) + 1; lc_len = Z_STRLEN_P(zv) - (ns_separator - Z_STRVAL_P(zv)); lc_name = zend_str_tolower_dup(ns_separator, lc_len); ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_class_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } if (Z_STRVAL_P(zv)[0] == '\\') { lc_len = Z_STRLEN_P(zv) - 1; lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv) + 1, lc_len); } else { lc_len = Z_STRLEN_P(zv); lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), lc_len); } ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); GET_CACHE_SLOT(ret); return ret; } /* }}} */ int zend_add_const_name_literal(zend_op_array *op_array, const zval *zv, int unqualified TSRMLS_DC) /* {{{ */ { int ret, tmp_literal; char *name, *tmp_name; const char *ns_separator; int name_len, ns_len; zval c; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } /* skip leading '\\' */ if (Z_STRVAL_P(zv)[0] == '\\') { name_len = Z_STRLEN_P(zv) - 1; name = Z_STRVAL_P(zv) + 1; } else { name_len = Z_STRLEN_P(zv); name = Z_STRVAL_P(zv); } ns_separator = zend_memrchr(name, '\\', name_len); if (ns_separator) { ns_len = ns_separator - name; } else { ns_len = 0; } if (ns_len) { /* lowercased namespace name & original constant name */ tmp_name = estrndup(name, name_len); zend_str_tolower(tmp_name, ns_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased namespace name & lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); } if (ns_len) { if (!unqualified) { return ret; } ns_len++; name += ns_len; name_len -= ns_len; } /* original constant name */ tmp_name = estrndup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); return ret; } /* }}} */ #define LITERAL_STRINGL(op, str, len, copy) do { \ zval _c; \ ZVAL_STRINGL(&_c, str, len, copy); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG(op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG_EX(op_array, op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(op_array, &_c TSRMLS_CC); \ } while (0) #define LITERAL_NULL(op) do { \ zval _c; \ INIT_ZVAL( _c); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) static inline zend_bool zend_is_function_or_method_call(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; return ((type & ZEND_PARSED_METHOD_CALL) || (type == ZEND_PARSED_FUNCTION_CALL)); } /* }}} */ void zend_do_binary_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_unary_op(zend_uchar op, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); GET_NODE(result, opline->result); SET_UNUSED(opline->op2); } /* }}} */ #define MAKE_NOP(opline) { opline->opcode = ZEND_NOP; memset(&opline->result,0,sizeof(opline->result)); memset(&opline->op1,0,sizeof(opline->op1)); memset(&opline->op2,0,sizeof(opline->op2)); opline->result_type=opline->op1_type=opline->op2_type=IS_UNUSED; } static void zend_do_op_data(zend_op *data_op, const znode *value TSRMLS_DC) /* {{{ */ { data_op->opcode = ZEND_OP_DATA; SET_NODE(data_op->op1, value); SET_UNUSED(data_op->op2); } /* }}} */ void zend_do_binary_assign_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; switch (last_op->opcode) { case ZEND_FETCH_OBJ_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, op2 TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; case ZEND_FETCH_DIM_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_DIM; zend_do_op_data(opline, op2 TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result,last_op->result); return; default: break; } } opline->opcode = op; SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void fetch_simple_variable_ex(znode *result, znode *varname, int bp, zend_uchar op TSRMLS_DC) /* {{{ */ { zend_op opline; zend_op *opline_ptr; zend_llist *fetch_list_ptr; if (varname->op_type == IS_CONST) { ulong hash = 0; if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } else if (IS_INTERNED(Z_STRVAL(varname->u.constant))) { hash = INTERNED_HASH(Z_STRVAL(varname->u.constant)); } if (!zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC) && !(varname->u.constant.value.str.len == (sizeof("this")-1) && !memcmp(varname->u.constant.value.str.val, "this", sizeof("this"))) && (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE)) { result->op_type = IS_CV; result->u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC); varname->u.constant.value.str.val = (char*)CG(active_op_array)->vars[result->u.op.var].name; result->EA = 0; return; } } if (bp) { opline_ptr = &opline; init_op(opline_ptr TSRMLS_CC); } else { opline_ptr = get_next_op(CG(active_op_array) TSRMLS_CC); } opline_ptr->opcode = op; opline_ptr->result_type = IS_VAR; opline_ptr->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline_ptr->op1, varname); GET_NODE(result, opline_ptr->result); SET_UNUSED(opline_ptr->op2); opline_ptr->extended_value = ZEND_FETCH_LOCAL; if (varname->op_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline_ptr->op1.constant); if (zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC)) { opline_ptr->extended_value = ZEND_FETCH_GLOBAL; } } if (bp) { zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); zend_llist_add_element(fetch_list_ptr, opline_ptr); } } /* }}} */ void fetch_simple_variable(znode *result, znode *varname, int bp TSRMLS_DC) /* {{{ */ { /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ fetch_simple_variable_ex(result, varname, bp, ZEND_FETCH_W TSRMLS_CC); } /* }}} */ void zend_do_fetch_static_member(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { znode class_node; zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline_ptr; zend_op opline; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); } zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (result->op_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[result->u.op.var].name), CG(active_op_array)->vars[result->u.op.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } GET_NODE(result,opline.result); opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; opline_ptr = &opline; zend_llist_add_element(fetch_list_ptr, &opline); } else { le = fetch_list_ptr->head; opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode != ZEND_FETCH_W && opline_ptr->op1_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[opline_ptr->op1.var].name), CG(active_op_array)->vars[opline_ptr->op1.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; COPY_NODE(opline_ptr->op1, opline.result); zend_llist_prepend_element(fetch_list_ptr, &opline); } else { if (opline_ptr->op1_type == IS_CONST) { GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op1.constant); } if (class_node.op_type == IS_CONST) { opline_ptr->op2_type = IS_CONST; opline_ptr->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline_ptr->op2, &class_node); } opline_ptr->extended_value |= ZEND_FETCH_STATIC_MEMBER; } } } /* }}} */ void fetch_array_begin(znode *result, znode *varname, znode *first_dim TSRMLS_DC) /* {{{ */ { fetch_simple_variable(result, varname, 1 TSRMLS_CC); fetch_array_dim(result, result, first_dim TSRMLS_CC); } /* }}} */ void fetch_array_dim(znode *result, const znode *parent, const znode *dim TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (zend_is_function_or_method_call(parent)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, parent); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_DIM_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, parent); SET_NODE(opline.op2, dim); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline.op2.constant)), Z_STRLEN(CONSTANT(opline.op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline.op2.constant)); ZVAL_LONG(&CONSTANT(opline.op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline.op2.constant); } } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void fetch_string_offset(znode *result, const znode *parent, const znode *offset TSRMLS_DC) /* {{{ */ { fetch_array_dim(result, parent, offset TSRMLS_CC); } /* }}} */ void zend_do_print(znode *result, const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->opcode = ZEND_PRINT; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_echo(const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ECHO; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_abstract_method(const znode *function_name, znode *modifiers, const znode *body TSRMLS_DC) /* {{{ */ { char *method_type; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { Z_LVAL(modifiers->u.constant) |= ZEND_ACC_ABSTRACT; method_type = "Interface"; } else { method_type = "Abstract"; } if (modifiers->u.constant.value.lval & ZEND_ACC_ABSTRACT) { if(modifiers->u.constant.value.lval & ZEND_ACC_PRIVATE) { zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot be declared private", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } if (Z_LVAL(body->u.constant) == ZEND_ACC_ABSTRACT) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_RAISE_ABSTRACT_ERROR; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } else { /* we had code in the function body */ zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot contain body", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } else { if (body->u.constant.value.lval == ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Non-abstract method %s::%s() must contain body", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } } /* }}} */ static zend_bool opline_is_fetch_this(const zend_op *opline TSRMLS_DC) /* {{{ */ { if ((opline->opcode == ZEND_FETCH_W) && (opline->op1_type == IS_CONST) && (Z_TYPE(CONSTANT(opline->op1.constant)) == IS_STRING) && (Z_HASH_P(&CONSTANT(opline->op1.constant)) == THIS_HASHVAL) && (Z_STRLEN(CONSTANT(opline->op1.constant)) == (sizeof("this")-1)) && !memcmp(Z_STRVAL(CONSTANT(opline->op1.constant)), "this", sizeof("this"))) { return 1; } else { return 0; } } /* }}} */ void zend_do_assign(znode *result, znode *variable, znode *value TSRMLS_DC) /* {{{ */ { int last_op_number; zend_op *opline; if (value->op_type == IS_CV) { zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (fetch_list_ptr && fetch_list_ptr->head) { opline = (zend_op *)fetch_list_ptr->head->data; if (opline->opcode == ZEND_FETCH_DIM_W && opline->op1_type == IS_CV && opline->op1.var == value->u.op.var) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_R; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->op1_type = IS_CONST; LITERAL_STRINGL(opline->op1, CG(active_op_array)->vars[value->u.op.var].name, CG(active_op_array)->vars[value->u.op.var].name_len, 1); CALCULATE_LITERAL_HASH(opline->op1.constant); SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_LOCAL; GET_NODE(value, opline->result); } } } zend_do_end_variable_parse(variable, BP_VAR_W, 0 TSRMLS_CC); last_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (variable->op_type == IS_CV) { if (variable->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (variable->op_type == IS_VAR) { int n = 0; while (last_op_number - n > 0) { zend_op *last_op; last_op = &CG(active_op_array)->opcodes[last_op_number-n-1]; if (last_op->result_type == IS_VAR && last_op->result.var == variable->u.op.var) { if (last_op->opcode == ZEND_FETCH_OBJ_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, value TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (last_op->opcode == ZEND_FETCH_DIM_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ /* TBFixed: this can realloc opcodes, leaving last_op pointing wrong */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_DIM; zend_do_op_data(opline, value TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (opline_is_fetch_this(last_op TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } else { break; } } n++; } } opline->opcode = ZEND_ASSIGN; SET_NODE(opline->op1, variable); SET_NODE(opline->op2, value); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_assign_ref(znode *result, const znode *lvar, const znode *rvar TSRMLS_DC) /* {{{ */ { zend_op *opline; if (lvar->op_type == IS_CV) { if (lvar->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (lvar->op_type == IS_VAR) { int last_op_number = get_next_op_number(CG(active_op_array)); if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline_is_fetch_this(opline TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ASSIGN_REF; if (zend_is_function_or_method_call(rvar)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } else if (rvar->EA & ZEND_PARSED_NEW) { opline->extended_value = ZEND_RETURNS_NEW; } else { opline->extended_value = 0; } if (result) { opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } else { opline->result_type = IS_UNUSED | EXT_TYPE_UNUSED; } SET_NODE(opline->op1, lvar); SET_NODE(opline->op2, rvar); } /* }}} */ static inline void do_begin_loop(TSRMLS_D) /* {{{ */ { zend_brk_cont_element *brk_cont_element; int parent; parent = CG(context).current_brk_cont; CG(context).current_brk_cont = CG(active_op_array)->last_brk_cont; brk_cont_element = get_next_brk_cont_element(CG(active_op_array)); brk_cont_element->start = get_next_op_number(CG(active_op_array)); brk_cont_element->parent = parent; } /* }}} */ static inline void do_end_loop(int cont_addr, int has_loop_var TSRMLS_DC) /* {{{ */ { if (!has_loop_var) { /* The start fileld is used to free temporary variables in case of exceptions. * We won't try to free something of we don't have loop variable. */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].start = -1; } CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = cont_addr; CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; } /* }}} */ void zend_do_while_cond(const znode *expr, znode *close_bracket_token TSRMLS_DC) /* {{{ */ { int while_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, expr); close_bracket_token->u.op.opline_num = while_cond_op_number; SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_while_end(const znode *while_token, const znode *close_bracket_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* add unconditional jump */ opline->opcode = ZEND_JMP; opline->op1.opline_num = while_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* update while's conditional jmp */ CG(active_op_array)->opcodes[close_bracket_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); do_end_loop(while_token->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_cond(const znode *expr, znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { int for_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZNZ; SET_NODE(opline->op1, expr); /* the conditional expression */ second_semicolon_token->u.op.opline_num = for_cond_op_number; SET_UNUSED(opline->op2); } /* }}} */ void zend_do_for_before_statement(const znode *cond_start, const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = cond_start->u.op.opline_num; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_end(const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = second_semicolon_token->u.op.opline_num+1; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_end_loop(second_semicolon_token->u.op.opline_num+1, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_pre_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_PRE_INC)?ZEND_PRE_INC_OBJ:ZEND_PRE_DEC_OBJ; last_op->result_type = IS_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_post_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_POST_INC)?ZEND_POST_INC_OBJ:ZEND_POST_DEC_OBJ; last_op->result_type = IS_TMP_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_if_cond(const znode *cond, znode *closing_bracket_token TSRMLS_DC) /* {{{ */ { int if_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); closing_bracket_token->u.op.opline_num = if_cond_op_number; SET_UNUSED(opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_if_after_statement(const znode *closing_bracket_token, unsigned char initialize TSRMLS_DC) /* {{{ */ { int if_end_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; /* save for backpatching */ if (initialize) { zend_llist jmp_list; zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); } zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &if_end_op_number); CG(active_op_array)->opcodes[closing_bracket_token->u.op.opline_num].op2.opline_num = if_end_op_number+1; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_if_end(TSRMLS_D) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_llist *jmp_list_ptr; zend_llist_element *le; zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); for (le=jmp_list_ptr->head; le; le = le->next) { CG(active_op_array)->opcodes[*((int *) le->data)].op1.opline_num = next_op_number; } zend_llist_destroy(jmp_list_ptr); zend_stack_del_top(&CG(bp_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_check_writable_variable(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; if (type & ZEND_PARSED_METHOD_CALL) { zend_error(E_COMPILE_ERROR, "Can't use method return value in write context"); } if (type == ZEND_PARSED_FUNCTION_CALL) { zend_error(E_COMPILE_ERROR, "Can't use function return value in write context"); } } /* }}} */ void zend_do_begin_variable_parse(TSRMLS_D) /* {{{ */ { zend_llist fetch_list; zend_llist_init(&fetch_list, sizeof(zend_op), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &fetch_list, sizeof(zend_llist)); } /* }}} */ void zend_do_end_variable_parse(znode *variable, int type, int arg_offset TSRMLS_DC) /* {{{ */ { zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline = NULL; zend_op *opline_ptr; zend_uint this_var = -1; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); le = fetch_list_ptr->head; /* TODO: $foo->x->y->z = 1 should fetch "x" and "y" for R or RW, not just W */ if (le) { opline_ptr = (zend_op *)le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { /* convert to FETCH_?(this) into IS_CV */ if (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE) { this_var = opline_ptr->result.var; if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), Z_STRVAL(CONSTANT(opline_ptr->op1.constant)), Z_STRLEN(CONSTANT(opline_ptr->op1.constant)), Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC); Z_TYPE(CONSTANT(opline_ptr->op1.constant)) = IS_NULL; } else { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); } le = le->next; if (variable->op_type == IS_VAR && variable->u.op.var == this_var) { variable->op_type = IS_CV; variable->u.op.var = CG(active_op_array)->this_var; } } else if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } while (le) { opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode == ZEND_SEPARATE) { if (type != BP_VAR_R && type != BP_VAR_IS) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); } le = le->next; continue; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); if (opline->op1_type == IS_VAR && opline->op1.var == this_var) { opline->op1_type = IS_CV; opline->op1.var = CG(active_op_array)->this_var; } switch (type) { case BP_VAR_R: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode -= 3; break; case BP_VAR_W: break; case BP_VAR_RW: opline->opcode += 3; break; case BP_VAR_IS: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode += 6; /* 3+3 */ break; case BP_VAR_FUNC_ARG: opline->opcode += 9; /* 3+3+3 */ opline->extended_value |= arg_offset; break; case BP_VAR_UNSET: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for unsetting"); } opline->opcode += 12; /* 3+3+3+3 */ break; } le = le->next; } if (opline && type == BP_VAR_W && arg_offset) { opline->extended_value |= ZEND_FETCH_MAKE_REF; } } zend_llist_destroy(fetch_list_ptr); zend_stack_del_top(&CG(bp_stack)); } /* }}} */ void zend_do_add_string(znode *result, const znode *op1, znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline; if (Z_STRLEN(op2->u.constant) > 1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_STRING; } else if (Z_STRLEN(op2->u.constant) == 1) { int ch = *Z_STRVAL(op2->u.constant); /* Free memory and use ZEND_ADD_CHAR in case of 1 character strings */ efree(Z_STRVAL(op2->u.constant)); ZVAL_LONG(&op2->u.constant, ch); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_CHAR; } else { /* String can be empty after a variable at the end of a heredoc */ efree(Z_STRVAL(op2->u.constant)); return; } if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_add_variable(znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_VAR; if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_free(znode *op1 TSRMLS_DC) /* {{{ */ { if (op1->op_type==IS_TMP_VAR) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else if (op1->op_type==IS_VAR) { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; while (opline->opcode == ZEND_END_SILENCE || opline->opcode == ZEND_EXT_FCALL_END || opline->opcode == ZEND_OP_DATA) { opline--; } if (opline->result_type == IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_FETCH_R || opline->opcode == ZEND_FETCH_DIM_R || opline->opcode == ZEND_FETCH_OBJ_R || opline->opcode == ZEND_QM_ASSIGN_VAR) { /* It's very rare and useless case. It's better to use additional FREE opcode and simplify the FETCH handlers their selves */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else { opline->result_type |= EXT_TYPE_UNUSED; } } else { while (opline>CG(active_op_array)->opcodes) { if (opline->opcode == ZEND_FETCH_DIM_R && opline->op1_type == IS_VAR && opline->op1.var == op1->u.op.var) { /* This should the end of a list() construct * Mark its result as unused */ opline->extended_value = ZEND_FETCH_STANDARD; break; } else if (opline->result_type==IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_NEW) { opline->result_type |= EXT_TYPE_UNUSED; } break; } opline--; } } } else if (op1->op_type == IS_CONST) { zval_dtor(&op1->u.constant); } } /* }}} */ int zend_do_verify_access_types(const znode *current_access_type, const znode *new_modifier) /* {{{ */ { if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_PPP_MASK) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Multiple access type modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_ABSTRACT) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Multiple abstract modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_STATIC) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Multiple static modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_FINAL) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Multiple final modifiers are not allowed"); } if (((Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)) & (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) == (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Cannot use the final modifier on an abstract class member"); } return (Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)); } /* }}} */ void zend_do_begin_function_declaration(znode *function_token, znode *function_name, int is_method, int return_reference, znode *fn_flags_znode TSRMLS_DC) /* {{{ */ { zend_op_array op_array; char *name = function_name->u.constant.value.str.val; int name_len = function_name->u.constant.value.str.len; int function_begin_line = function_token->u.op.opline_num; zend_uint fn_flags; const char *lcname; zend_bool orig_interactive; ALLOCA_FLAG(use_heap) if (is_method) { if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((Z_LVAL(fn_flags_znode->u.constant) & ~(ZEND_ACC_STATIC|ZEND_ACC_PUBLIC))) { zend_error(E_COMPILE_ERROR, "Access type for interface method %s::%s() must be omitted", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } Z_LVAL(fn_flags_znode->u.constant) |= ZEND_ACC_ABSTRACT; /* propagates to the rest of the parser */ } fn_flags = Z_LVAL(fn_flags_znode->u.constant); /* must be done *after* the above check */ } else { fn_flags = 0; } if ((fn_flags & ZEND_ACC_STATIC) && (fn_flags & ZEND_ACC_ABSTRACT) && !(CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_STRICT, "Static function %s%s%s() should not be abstract", is_method ? CG(active_class_entry)->name : "", is_method ? "::" : "", Z_STRVAL(function_name->u.constant)); } function_token->u.op_array = CG(active_op_array); orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(&op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; op_array.function_name = name; if (return_reference) { op_array.fn_flags |= ZEND_ACC_RETURN_REFERENCE; } op_array.fn_flags |= fn_flags; op_array.scope = is_method?CG(active_class_entry):NULL; op_array.prototype = NULL; op_array.line_start = zend_get_compiled_lineno(TSRMLS_C); if (is_method) { int result; lcname = zend_new_interned_string(zend_str_tolower_dup(name, name_len), name_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lcname)) { result = zend_hash_quick_add(&CG(active_class_entry)->function_table, lcname, name_len+1, INTERNED_HASH(lcname), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } else { result = zend_hash_add(&CG(active_class_entry)->function_table, lcname, name_len+1, &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } if (result == FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::%s()", CG(active_class_entry)->name, name); } zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); if (fn_flags & ZEND_ACC_ABSTRACT) { CG(active_class_entry)->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (!(fn_flags & ZEND_ACC_PPP_MASK)) { fn_flags |= ZEND_ACC_PUBLIC; } if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } } } else { char *class_lcname; class_lcname = do_alloca(CG(active_class_entry)->name_length + 1, use_heap); zend_str_tolower_copy(class_lcname, CG(active_class_entry)->name, CG(active_class_entry)->name_length); /* Improve after RC: cache the lowercase class name */ if ((CG(active_class_entry)->name_length == name_len) && ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT) && (!memcmp(class_lcname, lcname, name_len))) { if (!CG(active_class_entry)->constructor) { CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } } else if ((name_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)))) { if (CG(active_class_entry)->constructor) { zend_error(E_STRICT, "Redefining already defined constructor for class %s", CG(active_class_entry)->name); } CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1))) { CG(active_class_entry)->destructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1))) { CG(active_class_entry)->clone = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } CG(active_class_entry)->__call = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } CG(active_class_entry)->__callstatic = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } CG(active_class_entry)->__get = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } CG(active_class_entry)->__set = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } CG(active_class_entry)->__unset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } CG(active_class_entry)->__isset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } CG(active_class_entry)->__tostring = (zend_function *) CG(active_op_array); } else if (!(fn_flags & ZEND_ACC_STATIC)) { CG(active_op_array)->fn_flags |= ZEND_ACC_ALLOW_STATIC; } free_alloca(class_lcname, use_heap); } str_efree(lcname); } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zval key; if (CG(current_namespace)) { /* Prefix function name with current namespcae name */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, function_name TSRMLS_CC); op_array.function_name = Z_STRVAL(tmp.u.constant); name_len = Z_STRLEN(tmp.u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), name_len); } else { lcname = zend_str_tolower_dup(name, name_len); } opline->opcode = ZEND_DECLARE_FUNCTION; opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, name_len TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; LITERAL_STRINGL(opline->op2, lcname, name_len, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); opline->extended_value = ZEND_DECLARE_FUNCTION; zend_hash_quick_update(CG(function_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); } if (CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_NOP; opline->lineno = function_begin_line; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } { /* Push a seperator to the switch and foreach stacks */ zend_switch_entry switch_entry; switch_entry.cond.op_type = IS_UNUSED; switch_entry.default_case = 0; switch_entry.control_var = 0; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); { /* Foreach stack separator */ zend_op dummy_opline; dummy_opline.result_type = IS_UNUSED; dummy_opline.op1_type = IS_UNUSED; zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); } } if (CG(doc_comment)) { CG(active_op_array)->doc_comment = CG(doc_comment); CG(active_op_array)->doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_begin_lambda_function_declaration(znode *result, znode *function_token, int return_reference, int is_static TSRMLS_DC) /* {{{ */ { znode function_name; zend_op_array *current_op_array = CG(active_op_array); int current_op_number = get_next_op_number(CG(active_op_array)); zend_op *current_op; function_name.op_type = IS_CONST; ZVAL_STRINGL(&function_name.u.constant, "{closure}", sizeof("{closure}")-1, 1); zend_do_begin_function_declaration(function_token, &function_name, 0, return_reference, NULL TSRMLS_CC); result->op_type = IS_TMP_VAR; result->u.op.var = get_temporary_variable(current_op_array); current_op = &current_op_array->opcodes[current_op_number]; current_op->opcode = ZEND_DECLARE_LAMBDA_FUNCTION; zend_del_literal(current_op_array, current_op->op2.constant); SET_UNUSED(current_op->op2); SET_NODE(current_op->result, result); if (is_static) { CG(active_op_array)->fn_flags |= ZEND_ACC_STATIC; } CG(active_op_array)->fn_flags |= ZEND_ACC_CLOSURE; } /* }}} */ void zend_do_handle_exception(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_HANDLE_EXCEPTION; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_function_declaration(const znode *function_token TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; zend_do_extended_info(TSRMLS_C); zend_do_return(NULL, 0 TSRMLS_CC); pass_two(CG(active_op_array) TSRMLS_CC); zend_release_labels(TSRMLS_C); if (CG(active_class_entry)) { zend_check_magic_method_implementation(CG(active_class_entry), (zend_function*)CG(active_op_array), E_COMPILE_ERROR TSRMLS_CC); } else { /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(CG(active_op_array)->function_name); zend_str_tolower_copy(lcname, CG(active_op_array)->function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME)) && CG(active_op_array)->num_args != 1) { zend_error(E_COMPILE_ERROR, "%s() must take exactly 1 argument", ZEND_AUTOLOAD_FUNC_NAME); } } CG(active_op_array)->line_end = zend_get_compiled_lineno(TSRMLS_C); CG(active_op_array) = function_token->u.op_array; /* Pop the switch and foreach seperators */ zend_stack_del_top(&CG(switch_cond_stack)); zend_stack_del_top(&CG(foreach_copy_stack)); } /* }}} */ void zend_do_receive_arg(zend_uchar op, znode *varname, const znode *offset, const znode *initialization, znode *class_type, zend_uchar pass_by_reference TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_arg_info *cur_arg_info; znode var; if (class_type->op_type == IS_CONST && Z_TYPE(class_type->u.constant) == IS_STRING && Z_STRLEN(class_type->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_type->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } if (zend_is_auto_global_quick(Z_STRVAL(varname->u.constant), Z_STRLEN(varname->u.constant), 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign auto-global variable %s", Z_STRVAL(varname->u.constant)); } else { var.op_type = IS_CV; var.u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(varname->u.constant) = (char*)CG(active_op_array)->vars[var.u.op.var].name; var.EA = 0; if (CG(active_op_array)->vars[var.u.op.var].hash_value == THIS_HASHVAL && Z_STRLEN(varname->u.constant) == sizeof("this")-1 && !memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this")-1)) { if (CG(active_op_array)->scope && (CG(active_op_array)->fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } CG(active_op_array)->this_var = var.u.op.var; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->num_args++; opline->opcode = op; SET_NODE(opline->result, &var); SET_NODE(opline->op1, offset); if (op == ZEND_RECV_INIT) { SET_NODE(opline->op2, initialization); } else { CG(active_op_array)->required_num_args = CG(active_op_array)->num_args; SET_UNUSED(opline->op2); } CG(active_op_array)->arg_info = erealloc(CG(active_op_array)->arg_info, sizeof(zend_arg_info)*(CG(active_op_array)->num_args)); cur_arg_info = &CG(active_op_array)->arg_info[CG(active_op_array)->num_args-1]; cur_arg_info->name = zend_new_interned_string(estrndup(varname->u.constant.value.str.val, varname->u.constant.value.str.len), varname->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->name_len = varname->u.constant.value.str.len; cur_arg_info->type_hint = 0; cur_arg_info->allow_null = 1; cur_arg_info->pass_by_reference = pass_by_reference; cur_arg_info->class_name = NULL; cur_arg_info->class_name_len = 0; if (class_type->op_type != IS_UNUSED) { cur_arg_info->allow_null = 0; if (class_type->u.constant.type != IS_NULL) { if (class_type->u.constant.type == IS_ARRAY) { cur_arg_info->type_hint = IS_ARRAY; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else if (Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Default value for parameters with array type hint can only be an array or NULL"); } } } else if (class_type->u.constant.type == IS_CALLABLE) { cur_arg_info->type_hint = IS_CALLABLE; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with callable type hint can only be NULL"); } } } else { cur_arg_info->type_hint = IS_OBJECT; if (ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_type->u.constant), Z_STRLEN(class_type->u.constant))) { zend_resolve_class_name(class_type, opline->extended_value, 1 TSRMLS_CC); } Z_STRVAL(class_type->u.constant) = (char*)zend_new_interned_string(class_type->u.constant.value.str.val, class_type->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->class_name = class_type->u.constant.value.str.val; cur_arg_info->class_name_len = class_type->u.constant.value.str.len; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with a class type hint can only be NULL"); } } } } } } /* }}} */ int zend_do_begin_function_call(znode *function_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { zend_function *function; char *lcname; char *is_compound = memchr(Z_STRVAL(function_name->u.constant), '\\', Z_STRLEN(function_name->u.constant)); zend_resolve_non_class_name(function_name, check_namespace TSRMLS_CC); if (check_namespace && CG(current_namespace) && !is_compound) { /* We assume we call function from the current namespace if it is not prefixed. */ /* In run-time PHP will check for function with full name and internal function with short name */ zend_do_begin_dynamic_function_call(function_name, 1 TSRMLS_CC); return 1; } lcname = zend_str_tolower_dup(function_name->u.constant.value.str.val, function_name->u.constant.value.str.len); if ((zend_hash_find(CG(function_table), lcname, function_name->u.constant.value.str.len+1, (void **) &function)==FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_FUNCTIONS) && (function->type == ZEND_INTERNAL_FUNCTION))) { zend_do_begin_dynamic_function_call(function_name, 0 TSRMLS_CC); efree(lcname); return 1; /* Dynamic */ } efree(function_name->u.constant.value.str.val); function_name->u.constant.value.str.val = lcname; zend_stack_push(&CG(function_call_stack), (void *) &function, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 0; } /* }}} */ void zend_do_begin_method_call(znode *left_bracket TSRMLS_DC) /* {{{ */ { zend_op *last_op; int last_op_number; unsigned char *ptr = NULL; zend_do_end_variable_parse(left_bracket, BP_VAR_R, 0 TSRMLS_CC); zend_do_begin_variable_parse(TSRMLS_C); last_op_number = get_next_op_number(CG(active_op_array))-1; last_op = &CG(active_op_array)->opcodes[last_op_number]; if ((last_op->op2_type == IS_CONST) && (Z_TYPE(CONSTANT(last_op->op2.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(last_op->op2.constant)) == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !zend_binary_strcasecmp(Z_STRVAL(CONSTANT(last_op->op2.constant)), Z_STRLEN(CONSTANT(last_op->op2.constant)), ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1)) { zend_error(E_COMPILE_ERROR, "Cannot call __clone() method on objects - use 'clone $obj' instead"); } if (last_op->opcode == ZEND_FETCH_OBJ_R) { if (last_op->op2_type == IS_CONST) { zval name; name = CONSTANT(last_op->op2.constant); if (Z_TYPE(name) != IS_STRING) { zend_error(E_COMPILE_ERROR, "Method name must be a string"); } if (!IS_INTERNED(Z_STRVAL(name))) { Z_STRVAL(name) = estrndup(Z_STRVAL(name), Z_STRLEN(name)); } FREE_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); last_op->op2.constant = zend_add_func_name_literal(CG(active_op_array), &name TSRMLS_CC); GET_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); } last_op->opcode = ZEND_INIT_METHOD_CALL; SET_UNUSED(last_op->result); Z_LVAL(left_bracket->u.constant) = ZEND_INIT_FCALL_BY_NAME; } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (left_bracket->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &left_bracket->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, left_bracket); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_do_clone(znode *result, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CLONE; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_begin_dynamic_function_call(znode *function_name, int ns_call TSRMLS_DC) /* {{{ */ { unsigned char *ptr = NULL; zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (ns_call) { /* In run-time PHP will check for function with full name and internal function with short name */ opline->opcode = ZEND_INIT_NS_FCALL_BY_NAME; SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_ns_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (function_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, function_name); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_resolve_non_class_name(znode *element_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; int len; zval **ns; char *lcname, *compound = memchr(Z_STRVAL(element_name->u.constant), '\\', Z_STRLEN(element_name->u.constant)); if (Z_STRVAL(element_name->u.constant)[0] == '\\') { /* name starts with \ so it is known and unambiguos, nothing to do here but shorten it */ memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+1, Z_STRLEN(element_name->u.constant)); --Z_STRLEN(element_name->u.constant); return; } if(!check_namespace) { return; } if (compound && CG(current_import)) { len = compound - Z_STRVAL(element_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(element_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(element_name->u.constant) -= len; memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+len, Z_STRLEN(element_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, element_name TSRMLS_CC); *element_name = tmp; efree(lcname); return; } efree(lcname); } if (CG(current_namespace)) { tmp = *element_name; Z_STRLEN(tmp.u.constant) = sizeof("\\")-1 + Z_STRLEN(element_name->u.constant) + Z_STRLEN_P(CG(current_namespace)); Z_STRVAL(tmp.u.constant) = (char *) emalloc(Z_STRLEN(tmp.u.constant)+1); memcpy(Z_STRVAL(tmp.u.constant), Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace))]), "\\", sizeof("\\")-1); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace)) + sizeof("\\")-1]), Z_STRVAL(element_name->u.constant), Z_STRLEN(element_name->u.constant)+1); STR_FREE(Z_STRVAL(element_name->u.constant)); *element_name = tmp; } } /* }}} */ void zend_resolve_class_name(znode *class_name, ulong fetch_type, int check_ns_name TSRMLS_DC) /* {{{ */ { char *compound; char *lcname; zval **ns; znode tmp; int len; compound = memchr(Z_STRVAL(class_name->u.constant), '\\', Z_STRLEN(class_name->u.constant)); if (compound) { /* This is a compound class name that contains namespace prefix */ if (Z_STRVAL(class_name->u.constant)[0] == '\\') { /* The STRING name has "\" prefix */ Z_STRLEN(class_name->u.constant) -= 1; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+1, Z_STRLEN(class_name->u.constant)+1); Z_STRVAL(class_name->u.constant) = erealloc( Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1); if (ZEND_FETCH_CLASS_DEFAULT != zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "'\\%s' is an invalid class name", Z_STRVAL(class_name->u.constant)); } } else { if (CG(current_import)) { len = compound - Z_STRVAL(class_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(class_name->u.constant) -= len; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+len, Z_STRLEN(class_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; efree(lcname); return; } efree(lcname); } /* Here name is not prefixed with \ and not imported */ if (CG(current_namespace)) { tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } } } else if (CG(current_import) || CG(current_namespace)) { /* this is a plain name (without \) */ lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns) == SUCCESS) { /* The given name is an import name. Substitute it. */ zval_dtor(&class_name->u.constant); class_name->u.constant = **ns; zval_copy_ctor(&class_name->u.constant); } else if (CG(current_namespace)) { /* plain name, no import - prepend current namespace to it */ tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } efree(lcname); } } /* }}} */ void zend_do_fetch_class(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { long fetch_class_op_number; zend_op *opline; if (class_name->op_type == IS_CONST && Z_TYPE(class_name->u.constant) == IS_STRING && Z_STRLEN(class_name->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_name->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } fetch_class_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CLASS; SET_UNUSED(opline->op1); opline->extended_value = ZEND_FETCH_CLASS_GLOBAL; CG(catch_begin) = fetch_class_op_number; if (class_name->op_type == IS_CONST) { int fetch_type; fetch_type = zend_get_class_fetch_type(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); switch (fetch_type) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: SET_UNUSED(opline->op2); opline->extended_value = fetch_type; zval_dtor(&class_name->u.constant); break; default: zend_resolve_class_name(class_name, opline->extended_value, 0 TSRMLS_CC); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_name->u.constant TSRMLS_CC); break; } } else { SET_NODE(opline->op2, class_name); } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; /* FIXME: Hack so that INIT_FCALL_BY_NAME still knows this is a class */ GET_NODE(result, opline->result); result->EA = opline->extended_value; } /* }}} */ void zend_do_label(znode *label TSRMLS_DC) /* {{{ */ { zend_label dest; if (!CG(context).labels) { ALLOC_HASHTABLE(CG(context).labels); zend_hash_init(CG(context).labels, 4, NULL, NULL, 0); } dest.brk_cont = CG(context).current_brk_cont; dest.opline_num = get_next_op_number(CG(active_op_array)); if (zend_hash_add(CG(context).labels, Z_STRVAL(label->u.constant), Z_STRLEN(label->u.constant) + 1, (void**)&dest, sizeof(zend_label), NULL) == FAILURE) { zend_error(E_COMPILE_ERROR, "Label '%s' already defined", Z_STRVAL(label->u.constant)); } /* Done with label now */ zval_dtor(&label->u.constant); } /* }}} */ void zend_resolve_goto_label(zend_op_array *op_array, zend_op *opline, int pass2 TSRMLS_DC) /* {{{ */ { zend_label *dest; long current, distance; zval *label; if (pass2) { label = opline->op2.zv; } else { label = &CONSTANT_EX(op_array, opline->op2.constant); } if (CG(context).labels == NULL || zend_hash_find(CG(context).labels, Z_STRVAL_P(label), Z_STRLEN_P(label)+1, (void**)&dest) == FAILURE) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; zend_error(E_COMPILE_ERROR, "'goto' to undefined label '%s'", Z_STRVAL_P(label)); } else { /* Label is not defined. Delay to pass 2. */ INC_BPC(op_array); return; } } opline->op1.opline_num = dest->opline_num; zval_dtor(label); Z_TYPE_P(label) = IS_NULL; /* Check that we are not moving into loop or switch */ current = opline->extended_value; for (distance = 0; current != dest->brk_cont; distance++) { if (current == -1) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; } zend_error(E_COMPILE_ERROR, "'goto' into loop or switch statement is disallowed"); } current = op_array->brk_cont_array[current].parent; } if (distance == 0) { /* Nothing to break out of, optimize to ZEND_JMP */ opline->opcode = ZEND_JMP; opline->extended_value = 0; SET_UNUSED(opline->op2); } else { /* Set real break distance */ ZVAL_LONG(label, distance); } if (pass2) { DEC_BPC(op_array); } } /* }}} */ void zend_do_goto(const znode *label TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_GOTO; opline->extended_value = CG(context).current_brk_cont; SET_UNUSED(opline->op1); SET_NODE(opline->op2, label); zend_resolve_goto_label(CG(active_op_array), opline, 0 TSRMLS_CC); } /* }}} */ void zend_release_labels(TSRMLS_D) /* {{{ */ { if (CG(context).labels) { zend_hash_destroy(CG(context).labels); FREE_HASHTABLE(CG(context).labels); } if (!zend_stack_is_empty(&CG(context_stack))) { zend_compiler_context *ctx; zend_stack_top(&CG(context_stack), (void**)&ctx); CG(context) = *ctx; zend_stack_del_top(&CG(context_stack)); } } /* }}} */ void zend_do_build_full_name(znode *result, znode *prefix, znode *name, int is_class_member TSRMLS_DC) /* {{{ */ { zend_uint length; if (!result) { result = prefix; } else { *result = *prefix; } if (is_class_member) { length = sizeof("::")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "::", sizeof("::")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("::")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } else { length = sizeof("\\")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "\\", sizeof("\\")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("\\")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } } /* }}} */ int zend_do_begin_class_member_function_call(znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { znode class_node; unsigned char *ptr = NULL; zend_op *opline; if (method_name->op_type == IS_CONST) { char *lcname; if (Z_TYPE(method_name->u.constant) != IS_STRING) { zend_error(E_COMPILE_ERROR, "Method name must be a string"); } lcname = zend_str_tolower_dup(Z_STRVAL(method_name->u.constant), Z_STRLEN(method_name->u.constant)); if ((sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == Z_STRLEN(method_name->u.constant) && memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == 0) { zval_dtor(&method_name->u.constant); method_name->op_type = IS_UNUSED; } efree(lcname); } if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; opline = get_next_op(CG(active_op_array) TSRMLS_CC); } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->extended_value = class_node.EA ; } opline->opcode = ZEND_INIT_STATIC_METHOD_CALL; if (class_node.op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, &class_node); } if (method_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &method_name->u.constant TSRMLS_CC); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } } else { SET_NODE(opline->op2, method_name); } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 1; /* Dynamic */ } /* }}} */ void zend_do_end_function_call(znode *function_name, znode *result, const znode *argument_list, int is_method, int is_dynamic_fcall TSRMLS_DC) /* {{{ */ { zend_op *opline; if (is_method && function_name && function_name->op_type == IS_UNUSED) { /* clone */ if (Z_LVAL(argument_list->u.constant) != 0) { zend_error(E_WARNING, "Clone method does not require arguments"); } opline = &CG(active_op_array)->opcodes[Z_LVAL(function_name->u.constant)]; } else { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (!is_method && !is_dynamic_fcall && function_name->op_type==IS_CONST) { opline->opcode = ZEND_DO_FCALL; SET_NODE(opline->op1, function_name); CALCULATE_LITERAL_HASH(opline->op1.constant); GET_CACHE_SLOT(opline->op1.constant); } else { opline->opcode = ZEND_DO_FCALL_BY_NAME; SET_UNUSED(opline->op1); } } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(result, opline->result) ; SET_UNUSED(opline->op2); zend_stack_del_top(&CG(function_call_stack)); opline->extended_value = Z_LVAL(argument_list->u.constant); } /* }}} */ void zend_do_pass_param(znode *param, zend_uchar op, int offset TSRMLS_DC) /* {{{ */ { zend_op *opline; int original_op=op; zend_function **function_ptr_ptr, *function_ptr; int send_by_reference; int send_function = 0; zend_stack_top(&CG(function_call_stack), (void **) &function_ptr_ptr); function_ptr = *function_ptr_ptr; if (original_op == ZEND_SEND_REF) { if (function_ptr && function_ptr->common.function_name && function_ptr->common.type == ZEND_USER_FUNCTION && !ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed; " "If you would like to pass argument by reference, modify the declaration of %s().", function_ptr->common.function_name); } else { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed"); } return; } if (function_ptr) { if (ARG_MAY_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { if (param->op_type & (IS_VAR|IS_CV) && original_op != ZEND_SEND_VAL) { send_by_reference = 1; if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION | ZEND_ARG_SEND_SILENT; } } else { op = ZEND_SEND_VAL; send_by_reference = 0; } } else { send_by_reference = ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset) ? ZEND_ARG_SEND_BY_REF : 0; } } else { send_by_reference = 0; } if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION; } else if (op == ZEND_SEND_VAL && (param->op_type & (IS_VAR|IS_CV))) { op = ZEND_SEND_VAR_NO_REF; } if (op!=ZEND_SEND_VAR_NO_REF && send_by_reference==ZEND_ARG_SEND_BY_REF) { /* change to passing by reference */ switch (param->op_type) { case IS_VAR: case IS_CV: op = ZEND_SEND_REF; break; default: zend_error(E_COMPILE_ERROR, "Only variables can be passed by reference"); break; } } if (original_op == ZEND_SEND_VAR) { switch (op) { case ZEND_SEND_VAR_NO_REF: zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); break; case ZEND_SEND_VAR: if (function_ptr) { zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(param, BP_VAR_FUNC_ARG, offset TSRMLS_CC); } break; case ZEND_SEND_REF: zend_do_end_variable_parse(param, BP_VAR_W, 0 TSRMLS_CC); break; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (op == ZEND_SEND_VAR_NO_REF) { if (function_ptr) { opline->extended_value = ZEND_ARG_COMPILE_TIME_BOUND | send_by_reference | send_function; } else { opline->extended_value = send_function; } } else { if (function_ptr) { opline->extended_value = ZEND_DO_FCALL; } else { opline->extended_value = ZEND_DO_FCALL_BY_NAME; } } opline->opcode = op; SET_NODE(opline->op1, param); opline->op2.opline_num = offset; SET_UNUSED(opline->op2); } /* }}} */ static int generate_free_switch_expr(const zend_switch_entry *switch_entry TSRMLS_DC) /* {{{ */ { zend_op *opline; if (switch_entry->cond.op_type != IS_VAR && switch_entry->cond.op_type != IS_TMP_VAR) { return (switch_entry->cond.op_type == IS_UNUSED); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry->cond); SET_UNUSED(opline->op2); opline->extended_value = 0; return 0; } /* }}} */ static int generate_free_foreach_copy(const zend_op *foreach_copy TSRMLS_DC) /* {{{ */ { zend_op *opline; /* If we reach the seperator then stop applying the stack */ if (foreach_copy->result_type == IS_UNUSED && foreach_copy->op1_type == IS_UNUSED) { return 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->result_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->result); SET_UNUSED(opline->op2); opline->extended_value = 1; if (foreach_copy->op1_type != IS_UNUSED) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->op1_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->op1); SET_UNUSED(opline->op2); opline->extended_value = 0; } return 0; } /* }}} */ void zend_do_return(znode *expr, int do_end_vparse TSRMLS_DC) /* {{{ */ { zend_op *opline; int start_op_number, end_op_number; if (do_end_vparse) { if ((CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) && !zend_is_function_or_method_call(expr)) { zend_do_end_variable_parse(expr, BP_VAR_W, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(expr, BP_VAR_R, 0 TSRMLS_CC); } } start_op_number = get_next_op_number(CG(active_op_array)); #ifdef ZTS zend_stack_apply_with_argument(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_switch_expr TSRMLS_CC); zend_stack_apply_with_argument(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_foreach_copy TSRMLS_CC); #else zend_stack_apply(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_switch_expr); zend_stack_apply(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_foreach_copy); #endif end_op_number = get_next_op_number(CG(active_op_array)); while (start_op_number < end_op_number) { CG(active_op_array)->opcodes[start_op_number].extended_value |= EXT_TYPE_FREE_ON_RETURN; start_op_number++; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) ? ZEND_RETURN_BY_REF : ZEND_RETURN; if (expr) { SET_NODE(opline->op1, expr); if (do_end_vparse && zend_is_function_or_method_call(expr)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } } else { opline->op1_type = IS_CONST; LITERAL_NULL(opline->op1); } SET_UNUSED(opline->op2); } /* }}} */ static int zend_add_try_element(zend_uint try_op TSRMLS_DC) /* {{{ */ { int try_catch_offset = CG(active_op_array)->last_try_catch++; CG(active_op_array)->try_catch_array = erealloc(CG(active_op_array)->try_catch_array, sizeof(zend_try_catch_element)*CG(active_op_array)->last_try_catch); CG(active_op_array)->try_catch_array[try_catch_offset].try_op = try_op; return try_catch_offset; } /* }}} */ static void zend_add_catch_element(int offset, zend_uint catch_op TSRMLS_DC) /* {{{ */ { CG(active_op_array)->try_catch_array[offset].catch_op = catch_op; } /* }}} */ void zend_do_first_catch(znode *open_parentheses TSRMLS_DC) /* {{{ */ { open_parentheses->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_initialize_try_catch_element(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist jmp_list; zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); zend_add_catch_element(try_token->u.op.opline_num, get_next_op_number(CG(active_op_array)) TSRMLS_CC); } /* }}} */ void zend_do_mark_last_catch(const znode *first_catch, const znode *last_additional_catch TSRMLS_DC) /* {{{ */ { CG(active_op_array)->last--; zend_do_if_end(TSRMLS_C); if (last_additional_catch->u.op.opline_num == -1) { CG(active_op_array)->opcodes[first_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[first_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } else { CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_try(znode *try_token TSRMLS_DC) /* {{{ */ { try_token->u.op.opline_num = zend_add_try_element(get_next_op_number(CG(active_op_array)) TSRMLS_CC); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_catch(znode *try_token, znode *class_name, znode *catch_var, znode *first_catch TSRMLS_DC) /* {{{ */ { long catch_op_number; zend_op *opline; znode catch_class; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); catch_class = *class_name; } else { zend_error(E_COMPILE_ERROR, "Bad class name in the catch statement"); } catch_op_number = get_next_op_number(CG(active_op_array)); if (first_catch) { first_catch->u.op.opline_num = catch_op_number; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CATCH; opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &catch_class.u.constant TSRMLS_CC); opline->op2_type = IS_CV; opline->op2.var = lookup_cv(CG(active_op_array), catch_var->u.constant.value.str.val, catch_var->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(catch_var->u.constant) = (char*)CG(active_op_array)->vars[opline->op2.var].name; opline->result.num = 0; /* 1 means it's the last catch in the block */ try_token->u.op.opline_num = catch_op_number; } /* }}} */ void zend_do_end_catch(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); CG(active_op_array)->opcodes[try_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_throw(const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_THROW; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); } /* }}} */ ZEND_API void function_add_ref(zend_function *function) /* {{{ */ { if (function->type == ZEND_USER_FUNCTION) { zend_op_array *op_array = &function->op_array; (*op_array->refcount)++; if (op_array->static_variables) { HashTable *static_variables = op_array->static_variables; zval *tmp_zval; ALLOC_HASHTABLE(op_array->static_variables); zend_hash_init(op_array->static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(op_array->static_variables, static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_zval, sizeof(zval *)); } op_array->run_time_cache = NULL; } } /* }}} */ static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */ { zend_function *function, *new_function; if (!ce->parent) { return; } /* You cannot change create_object */ ce->create_object = ce->parent->create_object; /* Inherit special functions if needed */ if (!ce->get_iterator) { ce->get_iterator = ce->parent->get_iterator; } if (!ce->iterator_funcs.funcs) { ce->iterator_funcs.funcs = ce->parent->iterator_funcs.funcs; } if (!ce->__get) { ce->__get = ce->parent->__get; } if (!ce->__set) { ce->__set = ce->parent->__set; } if (!ce->__unset) { ce->__unset = ce->parent->__unset; } if (!ce->__isset) { ce->__isset = ce->parent->__isset; } if (!ce->__call) { ce->__call = ce->parent->__call; } if (!ce->__callstatic) { ce->__callstatic = ce->parent->__callstatic; } if (!ce->__tostring) { ce->__tostring = ce->parent->__tostring; } if (!ce->clone) { ce->clone = ce->parent->clone; } if(!ce->serialize) { ce->serialize = ce->parent->serialize; } if(!ce->unserialize) { ce->unserialize = ce->parent->unserialize; } if (!ce->destructor) { ce->destructor = ce->parent->destructor; } if (ce->constructor) { if (ce->parent->constructor && ce->parent->constructor->common.fn_flags & ZEND_ACC_FINAL) { zend_error(E_ERROR, "Cannot override final %s::%s() with %s::%s()", ce->parent->name, ce->parent->constructor->common.function_name, ce->name, ce->constructor->common.function_name ); } return; } if (zend_hash_find(&ce->parent->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), (void **)&function)==SUCCESS) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), function, sizeof(zend_function), (void**)&new_function); function_add_ref(new_function); } else { /* Don't inherit the old style constructor if we already have the new style constructor */ char *lc_class_name; char *lc_parent_class_name; lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); if (!zend_hash_exists(&ce->function_table, lc_class_name, ce->name_length+1)) { lc_parent_class_name = zend_str_tolower_dup(ce->parent->name, ce->parent->name_length); if (!zend_hash_exists(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1) && zend_hash_find(&ce->parent->function_table, lc_parent_class_name, ce->parent->name_length+1, (void **)&function)==SUCCESS) { if (function->common.fn_flags & ZEND_ACC_CTOR) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1, function, sizeof(zend_function), (void**)&new_function); function_add_ref(new_function); } } efree(lc_parent_class_name); } efree(lc_class_name); } ce->constructor = ce->parent->constructor; } /* }}} */ char *zend_visibility_string(zend_uint fn_flags) /* {{{ */ { if (fn_flags & ZEND_ACC_PRIVATE) { return "private"; } if (fn_flags & ZEND_ACC_PROTECTED) { return "protected"; } if (fn_flags & ZEND_ACC_PUBLIC) { return "public"; } return ""; } /* }}} */ static void do_inherit_method(zend_function *function) /* {{{ */ { /* The class entry of the derived function intentionally remains the same * as that of the parent class. That allows us to know in which context * we're running, and handle private method calls properly. */ function_add_ref(function); } /* }}} */ static zend_bool zend_do_perform_implementation_check(const zend_function *fe, const zend_function *proto TSRMLS_DC) /* {{{ */ { zend_uint i; /* If it's a user function then arg_info == NULL means we don't have any parameters but * we still need to do the arg number checks. We are only willing to ignore this for internal * functions because extensions don't always define arg_info. */ if (!proto || (!proto->common.arg_info && proto->common.type != ZEND_USER_FUNCTION)) { return 1; } /* Checks for constructors only if they are declared in an interface, * or explicitly marked as abstract */ if ((fe->common.fn_flags & ZEND_ACC_CTOR) && ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)) { return 1; } /* check number of arguments */ if (proto->common.required_num_args < fe->common.required_num_args || proto->common.num_args > fe->common.num_args) { return 0; } if (fe->common.type != ZEND_USER_FUNCTION && (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) != 0 && (fe->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) == 0) { return 0; } /* by-ref constraints on return values are covariant */ if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) { return 0; } for (i=0; i < proto->common.num_args; i++) { if (ZEND_LOG_XOR(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)) { /* Only one has a type hint and the other one doesn't */ return 0; } if (fe->common.arg_info[i].class_name) { const char *fe_class_name, *proto_class_name; zend_uint fe_class_name_len, proto_class_name_len; if (!strcasecmp(fe->common.arg_info[i].class_name, "parent") && proto->common.scope) { fe_class_name = proto->common.scope->name; fe_class_name_len = proto->common.scope->name_length; } else if (!strcasecmp(fe->common.arg_info[i].class_name, "self") && fe->common.scope) { fe_class_name = fe->common.scope->name; fe_class_name_len = fe->common.scope->name_length; } else { fe_class_name = fe->common.arg_info[i].class_name; fe_class_name_len = fe->common.arg_info[i].class_name_len; } if (!strcasecmp(proto->common.arg_info[i].class_name, "parent") && proto->common.scope && proto->common.scope->parent) { proto_class_name = proto->common.scope->parent->name; proto_class_name_len = proto->common.scope->parent->name_length; } else if (!strcasecmp(proto->common.arg_info[i].class_name, "self") && proto->common.scope) { proto_class_name = proto->common.scope->name; proto_class_name_len = proto->common.scope->name_length; } else { proto_class_name = proto->common.arg_info[i].class_name; proto_class_name_len = proto->common.arg_info[i].class_name_len; } if (strcasecmp(fe_class_name, proto_class_name)!=0) { const char *colon; if (fe->common.type != ZEND_USER_FUNCTION) { return 0; } else if (strchr(proto_class_name, '\\') != NULL || (colon = zend_memrchr(fe_class_name, '\\', fe_class_name_len)) == NULL || strcasecmp(colon+1, proto_class_name) != 0) { zend_class_entry **fe_ce, **proto_ce; int found, found2; found = zend_lookup_class(fe_class_name, fe_class_name_len, &fe_ce TSRMLS_CC); found2 = zend_lookup_class(proto_class_name, proto_class_name_len, &proto_ce TSRMLS_CC); /* Check for class alias */ if (found != SUCCESS || found2 != SUCCESS || (*fe_ce)->type == ZEND_INTERNAL_CLASS || (*proto_ce)->type == ZEND_INTERNAL_CLASS || *fe_ce != *proto_ce) { return 0; } } } } if (fe->common.arg_info[i].type_hint != proto->common.arg_info[i].type_hint) { /* Incompatible type hint */ return 0; } /* by-ref constraints on arguments are invariant */ if (fe->common.arg_info[i].pass_by_reference != proto->common.arg_info[i].pass_by_reference) { return 0; } } if (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) { for (i=proto->common.num_args; i < fe->common.num_args; i++) { if (!fe->common.arg_info[i].pass_by_reference) { return 0; } } } return 1; } /* }}} */ #define REALLOC_BUF_IF_EXCEED(buf, offset, length, size) \ if (UNEXPECTED(offset - buf + size >= length)) { \ length += size + 1; \ buf = erealloc(buf, length); \ } static char * zend_get_function_declaration(zend_function *fptr TSRMLS_DC) /* {{{ */ { char *offset, *buf; zend_uint length = 1024; offset = buf = (char *)emalloc(length * sizeof(char)); if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { *(offset++) = '&'; *(offset++) = ' '; } if (fptr->common.scope) { memcpy(offset, fptr->common.scope->name, fptr->common.scope->name_length); offset += fptr->common.scope->name_length; *(offset++) = ':'; *(offset++) = ':'; } { size_t name_len = strlen(fptr->common.function_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, name_len); memcpy(offset, fptr->common.function_name, name_len); offset += name_len; } *(offset++) = '('; if (fptr->common.arg_info) { zend_uint i, required; zend_arg_info *arg_info = fptr->common.arg_info; required = fptr->common.required_num_args; for (i = 0; i < fptr->common.num_args;) { if (arg_info->class_name) { const char *class_name; zend_uint class_name_len; if (!strcasecmp(arg_info->class_name, "self") && fptr->common.scope ) { class_name = fptr->common.scope->name; class_name_len = fptr->common.scope->name_length; } else if (!strcasecmp(arg_info->class_name, "parent") && fptr->common.scope->parent) { class_name = fptr->common.scope->parent->name; class_name_len = fptr->common.scope->parent->name_length; } else { class_name = arg_info->class_name; class_name_len = arg_info->class_name_len; } REALLOC_BUF_IF_EXCEED(buf, offset, length, class_name_len); memcpy(offset, class_name, class_name_len); offset += class_name_len; *(offset++) = ' '; } else if (arg_info->type_hint) { zend_uint type_name_len; char *type_name = zend_get_type_by_const(arg_info->type_hint); type_name_len = strlen(type_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, type_name_len); memcpy(offset, type_name, type_name_len); offset += type_name_len; *(offset++) = ' '; } if (arg_info->pass_by_reference) { *(offset++) = '&'; } *(offset++) = '$'; if (arg_info->name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->name_len); memcpy(offset, arg_info->name, arg_info->name_len); offset += arg_info->name_len; } else { zend_uint idx = i; memcpy(offset, "param", 5); offset += 5; do { *(offset++) = (char) (idx % 10) + '0'; idx /= 10; } while (idx > 0); } if (i >= required) { *(offset++) = ' '; *(offset++) = '='; *(offset++) = ' '; if (fptr->type == ZEND_USER_FUNCTION) { zend_op *precv = NULL; { zend_uint idx = i; zend_op *op = ((zend_op_array *)fptr)->opcodes; zend_op *end = op + ((zend_op_array *)fptr)->last; ++idx; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT) && op->op1.num == (long)idx) { precv = op; } ++op; } } if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) { zval *zv, zv_copy; int use_copy; ALLOC_ZVAL(zv); *zv = *precv->op2.zv; zval_copy_ctor(zv); INIT_PZVAL(zv); zval_update_constant_ex(&zv, (void*)1, fptr->common.scope TSRMLS_CC); if (Z_TYPE_P(zv) == IS_BOOL) { if (Z_LVAL_P(zv)) { memcpy(offset, "true", 4); offset += 4; } else { memcpy(offset, "false", 5); offset += 5; } } else if (Z_TYPE_P(zv) == IS_NULL) { memcpy(offset, "NULL", 4); offset += 4; } else if (Z_TYPE_P(zv) == IS_STRING) { *(offset++) = '\''; REALLOC_BUF_IF_EXCEED(buf, offset, length, MIN(Z_STRLEN_P(zv), 10)); memcpy(offset, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 10)); offset += MIN(Z_STRLEN_P(zv), 10); if (Z_STRLEN_P(zv) > 10) { *(offset++) = '.'; *(offset++) = '.'; *(offset++) = '.'; } *(offset++) = '\''; } else if (Z_TYPE_P(zv) == IS_ARRAY) { memcpy(offset, "Array", 5); offset += 5; } else { zend_make_printable_zval(zv, &zv_copy, &use_copy); REALLOC_BUF_IF_EXCEED(buf, offset, length, Z_STRLEN(zv_copy)); memcpy(offset, Z_STRVAL(zv_copy), Z_STRLEN(zv_copy)); offset += Z_STRLEN(zv_copy); if (use_copy) { zval_dtor(&zv_copy); } } zval_ptr_dtor(&zv); } } else { memcpy(offset, "NULL", 4); offset += 4; } } if (++i < fptr->common.num_args) { *(offset++) = ','; *(offset++) = ' '; } arg_info++; REALLOC_BUF_IF_EXCEED(buf, offset, length, 32); } } *(offset++) = ')'; *offset = '\0'; return buf; } /* }}} */ static void do_inheritance_check_on_method(zend_function *child, zend_function *parent TSRMLS_DC) /* {{{ */ { zend_uint child_flags; zend_uint parent_flags = parent->common.fn_flags; if ((parent->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && parent->common.fn_flags & ZEND_ACC_ABSTRACT && parent->common.scope != (child->common.prototype ? child->common.prototype->common.scope : child->common.scope) && child->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_IMPLEMENTED_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Can't inherit abstract function %s::%s() (previously declared abstract in %s)", parent->common.scope->name, child->common.function_name, child->common.prototype ? child->common.prototype->common.scope->name : child->common.scope->name); } if (parent_flags & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot override final method %s::%s()", ZEND_FN_SCOPE_NAME(parent), child->common.function_name); } child_flags = child->common.fn_flags; /* You cannot change from static to non static and vice versa. */ if ((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC)) { if (child->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot make non static method %s::%s() static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } else { zend_error(E_COMPILE_ERROR, "Cannot make static method %s::%s() non static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } } /* Disallow making an inherited method abstract. */ if ((child_flags & ZEND_ACC_ABSTRACT) && !(parent_flags & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Cannot make non abstract method %s::%s() abstract in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } if (parent_flags & ZEND_ACC_CHANGED) { child->common.fn_flags |= ZEND_ACC_CHANGED; } else { /* Prevent derived classes from restricting access that was available in parent classes */ if ((child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::%s() must be %s (as in class %s)%s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if (((child_flags & ZEND_ACC_PPP_MASK) < (parent_flags & ZEND_ACC_PPP_MASK)) && ((parent_flags & ZEND_ACC_PPP_MASK) & ZEND_ACC_PRIVATE)) { child->common.fn_flags |= ZEND_ACC_CHANGED; } } if (parent_flags & ZEND_ACC_PRIVATE) { child->common.prototype = NULL; } else if (parent_flags & ZEND_ACC_ABSTRACT) { child->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; child->common.prototype = parent; } else if (!(parent->common.fn_flags & ZEND_ACC_CTOR) || (parent->common.prototype && (parent->common.prototype->common.scope->ce_flags & ZEND_ACC_INTERFACE))) { /* ctors only have a prototype if it comes from an interface */ child->common.prototype = parent->common.prototype ? parent->common.prototype : parent; } if (child->common.prototype && (child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { if (!zend_do_perform_implementation_check(child, child->common.prototype TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s::%s() must be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_get_function_declaration(child->common.prototype TSRMLS_CC)); } } else if (EG(error_reporting) & E_STRICT || EG(user_error_handler)) { /* Check E_STRICT (or custom error handler) before the check so that we save some time */ if (!zend_do_perform_implementation_check(child, parent TSRMLS_CC)) { char *method_prototype = zend_get_function_declaration(child->common.prototype TSRMLS_CC); zend_error(E_STRICT, "Declaration of %s::%s() should be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, method_prototype); efree(method_prototype); } } } /* }}} */ static zend_bool do_inherit_method_check(HashTable *child_function_table, zend_function *parent, const zend_hash_key *hash_key, zend_class_entry *child_ce) /* {{{ */ { zend_uint parent_flags = parent->common.fn_flags; zend_function *child; TSRMLS_FETCH(); if (zend_hash_quick_find(child_function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child)==FAILURE) { if (parent_flags & (ZEND_ACC_ABSTRACT)) { child_ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } return 1; /* method doesn't exist in child, copy from parent */ } do_inheritance_check_on_method(child, parent TSRMLS_CC); return 0; } /* }}} */ static zend_bool do_inherit_property_access_check(HashTable *target_ht, zend_property_info *parent_info, const zend_hash_key *hash_key, zend_class_entry *ce) /* {{{ */ { zend_property_info *child_info; zend_class_entry *parent_ce = ce->parent; if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW)) { if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { child_info->flags |= ZEND_ACC_CHANGED; } else { zend_hash_quick_update(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, parent_info, sizeof(zend_property_info), (void **) &child_info); if(ce->type & ZEND_INTERNAL_CLASS) { zend_duplicate_property_info_internal(child_info); } else { zend_duplicate_property_info(child_info); } child_info->flags &= ~ZEND_ACC_PRIVATE; /* it's not private anymore */ child_info->flags |= ZEND_ACC_SHADOW; /* but it's a shadow of private */ } return 0; /* don't copy access information to child */ } if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { if ((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s", (parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", parent_ce->name, hash_key->arKey, (child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ce->name, hash_key->arKey); } if(parent_info->flags & ZEND_ACC_CHANGED) { child_info->flags |= ZEND_ACC_CHANGED; } if ((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ce->name, hash_key->arKey, zend_visibility_string(parent_info->flags), parent_ce->name, (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if ((child_info->flags & ZEND_ACC_STATIC) == 0) { Z_DELREF_P(ce->default_properties_table[parent_info->offset]); ce->default_properties_table[parent_info->offset] = ce->default_properties_table[child_info->offset]; ce->default_properties_table[child_info->offset] = NULL; child_info->offset = parent_info->offset; } return 0; /* Don't copy from parent */ } else { return 1; /* Copy from parent */ } } /* }}} */ static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce TSRMLS_CC) == FAILURE) { zend_error(E_CORE_ERROR, "Class %s could not implement interface %s", ce->name, iface->name); } if (ce == iface) { zend_error(E_ERROR, "Interface %s cannot implement itself", ce->name); } } /* }}} */ ZEND_API void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface TSRMLS_DC) /* {{{ */ { /* expects interface to be contained in ce's interface list already */ zend_uint i, ce_num, if_num = iface->num_interfaces; zend_class_entry *entry; if (if_num==0) { return; } ce_num = ce->num_interfaces; if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } /* Inherit the interfaces, only if they're not already inherited by the class */ while (if_num--) { entry = iface->interfaces[if_num]; for (i = 0; i < ce_num; i++) { if (ce->interfaces[i] == entry) { break; } } if (i == ce_num) { ce->interfaces[ce->num_interfaces++] = entry; } } /* and now call the implementing handlers */ while (ce_num < ce->num_interfaces) { do_implement_interface(ce, ce->interfaces[ce_num++] TSRMLS_CC); } } /* }}} */ #ifdef ZTS static void zval_internal_ctor(zval **p) /* {{{ */ { zval *orig_ptr = *p; ALLOC_ZVAL(*p); MAKE_COPY_ZVAL(&orig_ptr, *p); } /* }}} */ # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) (((parent_ce)->type != (ce)->type) ? zval_internal_ctor : zval_add_ref)) #else # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) zval_add_ref) #endif ZEND_API void zend_do_inheritance(zend_class_entry *ce, zend_class_entry *parent_ce TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; if ((ce->ce_flags & ZEND_ACC_INTERFACE) && !(parent_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ce->name, parent_ce->name); } if (parent_ce->ce_flags & ZEND_ACC_FINAL_CLASS) { zend_error(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ce->name, parent_ce->name); } ce->parent = parent_ce; /* Copy serialize/unserialize callbacks */ if (!ce->serialize) { ce->serialize = parent_ce->serialize; } if (!ce->unserialize) { ce->unserialize = parent_ce->unserialize; } /* Inherit interfaces */ zend_do_inherit_interfaces(ce, parent_ce TSRMLS_CC); /* Inherit properties */ if (parent_ce->default_properties_count) { int i = ce->default_properties_count + parent_ce->default_properties_count; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_properties_count) { while (i-- > parent_ce->default_properties_count) { ce->default_properties_table[i] = ce->default_properties_table[i - parent_ce->default_properties_count]; } } for (i = 0; i < parent_ce->default_properties_count; i++) { ce->default_properties_table[i] = parent_ce->default_properties_table[i]; if (ce->default_properties_table[i]) { #ifdef ZTS if (parent_ce->type != ce->type) { zval *p; ALLOC_ZVAL(p); MAKE_COPY_ZVAL(&ce->default_properties_table[i], p); ce->default_properties_table[i] = p; } else { Z_ADDREF_P(ce->default_properties_table[i]); } #else Z_ADDREF_P(ce->default_properties_table[i]); #endif } } ce->default_properties_count += parent_ce->default_properties_count; } if (parent_ce->type != ce->type) { /* User class extends internal class */ zend_update_class_constants(parent_ce TSRMLS_CC); if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = erealloc(ce->default_static_members_table, sizeof(void*) * i); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&CE_STATIC_MEMBERS(parent_ce)[i]); ce->default_static_members_table[i] = CE_STATIC_MEMBERS(parent_ce)[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; ce->static_members_table = ce->default_static_members_table; } } else { if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&parent_ce->default_static_members_table[i]); ce->default_static_members_table[i] = parent_ce->default_static_members_table[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } } for (zend_hash_internal_pointer_reset(&ce->properties_info); zend_hash_get_current_data(&ce->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->properties_info)) { if (property_info->ce == ce) { if (property_info->flags & ZEND_ACC_STATIC) { property_info->offset += parent_ce->default_static_members_count; } else { property_info->offset += parent_ce->default_properties_count; } } } zend_hash_merge_ex(&ce->properties_info, &parent_ce->properties_info, (copy_ctor_func_t) (ce->type & ZEND_INTERNAL_CLASS ? zend_duplicate_property_info_internal : zend_duplicate_property_info), sizeof(zend_property_info), (merge_checker_func_t) do_inherit_property_access_check, ce); zend_hash_merge(&ce->constants_table, &parent_ce->constants_table, zval_property_ctor(parent_ce, ce), NULL, sizeof(zval *), 0); zend_hash_merge_ex(&ce->function_table, &parent_ce->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_inherit_parent_constructor(ce); if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS && ce->type == ZEND_INTERNAL_CLASS) { ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } else if (!(ce->ce_flags & ZEND_ACC_IMPLEMENT_INTERFACES) && !(ce->ce_flags & ZEND_ACC_IMPLEMENT_TRAITS)) { /* The verification will be done in runtime by ZEND_VERIFY_ABSTRACT_CLASS */ zend_verify_abstract_class(ce TSRMLS_CC); } ce->ce_flags |= parent_ce->ce_flags & ZEND_HAS_STATIC_IN_METHODS; } /* }}} */ static zend_bool do_inherit_constant_check(HashTable *child_constants_table, const zval **parent_constant, const zend_hash_key *hash_key, const zend_class_entry *iface) /* {{{ */ { zval **old_constant; if (zend_hash_quick_find(child_constants_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**)&old_constant) == SUCCESS) { if (*old_constant != *parent_constant) { zend_error(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", hash_key->arKey, iface->name); } return 0; } return 1; } /* }}} */ static int do_interface_constant_check(zval **val TSRMLS_DC, int num_args, va_list args, const zend_hash_key *key) /* {{{ */ { zend_class_entry **iface = va_arg(args, zend_class_entry**); do_inherit_constant_check(&(*iface)->constants_table, (const zval **) val, key, *iface); return ZEND_HASH_APPLY_KEEP; } /* }}} */ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_iface_num = ce->num_interfaces; zend_uint parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0; for (i = 0; i < ce->num_interfaces; i++) { if (ce->interfaces[i] == NULL) { memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i)); i--; } else if (ce->interfaces[i] == iface) { if (i < parent_iface_num) { ignore = 1; } else { zend_error(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ce->name, iface->name); } } } if (ignore) { /* Check for attempt to redeclare interface constants */ zend_hash_apply_with_arguments(&ce->constants_table TSRMLS_CC, (apply_func_args_t) do_interface_constant_check, 1, &iface); } else { if (ce->num_interfaces >= current_iface_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } } ce->interfaces[ce->num_interfaces++] = iface; zend_hash_merge_ex(&ce->constants_table, &iface->constants_table, (copy_ctor_func_t) zval_add_ref, sizeof(zval *), (merge_checker_func_t) do_inherit_constant_check, iface); zend_hash_merge_ex(&ce->function_table, &iface->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_implement_interface(ce, iface TSRMLS_CC); zend_do_inherit_interfaces(ce, iface TSRMLS_CC); } } /* }}} */ ZEND_API void zend_do_implement_trait(zend_class_entry *ce, zend_class_entry *trait TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_trait_num = ce->num_traits; zend_uint parent_trait_num = ce->parent ? ce->parent->num_traits : 0; for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == NULL) { memmove(ce->traits + i, ce->traits + i + 1, sizeof(zend_class_entry*) * (--ce->num_traits - i)); i--; } else if (ce->traits[i] == trait) { if (i < parent_trait_num) { ignore = 1; } } } if (!ignore) { if (ce->num_traits >= current_trait_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->traits = (zend_class_entry **) realloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } else { ce->traits = (zend_class_entry **) erealloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } } ce->traits[ce->num_traits++] = trait; } } /* }}} */ static zend_bool zend_traits_method_compatibility_check(zend_function *fn, zend_function *other_fn TSRMLS_DC) /* {{{ */ { zend_uint fn_flags = fn->common.scope->ce_flags; zend_uint other_flags = other_fn->common.scope->ce_flags; return zend_do_perform_implementation_check(fn, other_fn TSRMLS_CC) && zend_do_perform_implementation_check(other_fn, fn TSRMLS_CC) && ((fn_flags & ZEND_ACC_FINAL) == (other_flags & ZEND_ACC_FINAL)) /* equal final qualifier */ && ((fn_flags & ZEND_ACC_STATIC)== (other_flags & ZEND_ACC_STATIC)); /* equal static qualifier */ } /* }}} */ static int zend_traits_merge_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { size_t current; size_t i; size_t count; HashTable* resulting_table; HashTable** function_tables; zend_class_entry *ce; size_t collision = 0; size_t abstract_solved = 0; zend_function* other_trait_fn; current = va_arg(args, size_t); /* index of current trait */ count = va_arg(args, size_t); resulting_table = va_arg(args, HashTable*); function_tables = va_arg(args, HashTable**); ce = va_arg(args, zend_class_entry*); for (i = 0; i < count; i++) { if (i == current) { continue; /* just skip this, cause its the table this function is applied on */ } if (zend_hash_quick_find(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&other_trait_fn) == SUCCESS) { /* if it is an abstract method, there is no collision */ if (other_trait_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible */ /* In case both are abstract, just check prototype, but need to do that in both directions */ if (!zend_traits_method_compatibility_check(fn, other_trait_fn TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s must be compatible with %s", zend_get_function_declaration(fn TSRMLS_CC), zend_get_function_declaration(other_trait_fn TSRMLS_CC)); } /* we can savely free and remove it from other table */ zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } else { /* if it is not an abstract method, there is still no collision */ /* if fn is an abstract method */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible. Here, we already know other_trait_fn cannot be abstract, full check ok. */ if (!zend_traits_method_compatibility_check(fn, other_trait_fn TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s must be compatible with %s", zend_get_function_declaration(fn TSRMLS_CC), zend_get_function_declaration(other_trait_fn TSRMLS_CC)); } /* just mark as solved, will be added if its own trait is processed */ abstract_solved = 1; } else { /* but else, we have a collision of non-abstract methods */ collision++; zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } } } if (collision) { zend_function* class_fn; /* make sure method is not already overridden in class */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&class_fn) == FAILURE || class_fn->common.scope != ce) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because there are collisions with other trait methods on %s", fn->common.function_name, ce->name); } zend_function_dtor(fn); } else if (abstract_solved) { zend_function_dtor(fn); } else { /* Add it to result function table */ if (zend_hash_quick_add(resulting_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, fn, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating resulting trait method table", fn->common.function_name); } } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ static void zend_add_magic_methods(zend_class_entry* ce, const char* mname, uint mname_len, zend_function* fe TSRMLS_DC) /* {{{ */ { if (!strncmp(mname, ZEND_CLONE_FUNC_NAME, mname_len)) { ce->clone = fe; fe->common.fn_flags |= ZEND_ACC_CLONE; } else if (!strncmp(mname, ZEND_CONSTRUCTOR_FUNC_NAME, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } else if (!strncmp(mname, ZEND_DESTRUCTOR_FUNC_NAME, mname_len)) { ce->destructor = fe; fe->common.fn_flags |= ZEND_ACC_DTOR; } else if (!strncmp(mname, ZEND_GET_FUNC_NAME, mname_len)) { ce->__get = fe; } else if (!strncmp(mname, ZEND_SET_FUNC_NAME, mname_len)) { ce->__set = fe; } else if (!strncmp(mname, ZEND_CALL_FUNC_NAME, mname_len)) { ce->__call = fe; } else if (!strncmp(mname, ZEND_UNSET_FUNC_NAME, mname_len)) { ce->__unset = fe; } else if (!strncmp(mname, ZEND_ISSET_FUNC_NAME, mname_len)) { ce->__isset = fe; } else if (!strncmp(mname, ZEND_CALLSTATIC_FUNC_NAME, mname_len)) { ce->__callstatic = fe; } else if (!strncmp(mname, ZEND_TOSTRING_FUNC_NAME, mname_len)) { ce->__tostring = fe; } else if (ce->name_length + 1 == mname_len) { char *lowercase_name = emalloc(ce->name_length + 1); zend_str_tolower_copy(lowercase_name, ce->name, ce->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, ce->name_length + 1, 1 TSRMLS_CC); if (!memcmp(mname, lowercase_name, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } str_efree(lowercase_name); } } /* }}} */ static int zend_traits_merge_functions_to_class(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zend_class_entry *ce = va_arg(args, zend_class_entry*); zend_function* existing_fn = NULL; zend_function fn_copy, *fn_copy_p; zend_function* prototype = NULL; /* is used to determine the prototype according to the inheritance chain */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &existing_fn) == FAILURE || existing_fn->common.scope != ce) { /* not found or inherited from other class or interface */ zend_function* parent_function; if (ce->parent && zend_hash_quick_find(&ce->parent->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &parent_function) != FAILURE) { prototype = parent_function; /* ->common.fn_flags |= ZEND_ACC_ABSTRACT; */ /* we got that method in the parent class, and are going to override it, except, if the trait is just asking to have an abstract method implemented. */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* then we clean up an skip this method */ zend_function_dtor(fn); return ZEND_HASH_APPLY_REMOVE; } } fn->common.scope = ce; fn->common.prototype = prototype; if (prototype && (prototype->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT || prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { fn->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; } else if (fn->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT) { /* remove ZEND_ACC_IMPLEMENTED_ABSTRACT flag, think it shouldn't be copied to class */ fn->common.fn_flags = fn->common.fn_flags - ZEND_ACC_IMPLEMENTED_ABSTRACT; } /* check whether the trait method fullfills the inheritance requirements */ if (prototype) { do_inheritance_check_on_method(fn, prototype TSRMLS_CC); } /* one more thing: make sure we properly implement an abstract method */ if (existing_fn && existing_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { do_inheritance_check_on_method(fn, existing_fn TSRMLS_CC); } /* delete inherited fn if the function to be added is not abstract */ if (existing_fn && existing_fn->common.scope != ce && (fn->common.fn_flags & ZEND_ACC_ABSTRACT) == 0) { /* it is just a reference which was added to the subclass while doing the inheritance, so we can deleted now, and will add the overriding method afterwards. Except, if we try to add an abstract function, then we should not delete the inherited one */ zend_hash_quick_del(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h); } if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (fn->op_array.static_variables) { ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } fn_copy = *fn; function_add_ref(&fn_copy); if (zend_hash_quick_update(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, &fn_copy, sizeof(zend_function), (void**)&fn_copy_p)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating class method table", hash_key->arKey); } zend_add_magic_methods(ce, hash_key->arKey, hash_key->nKeyLength, fn_copy_p TSRMLS_CC); zend_function_dtor(fn); } else { zend_function_dtor(fn); } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ static int zend_traits_copy_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { HashTable* target; zend_trait_alias** aliases; HashTable* exclude_table; char* lcname; unsigned int fnname_len; zend_function fn_copy; void* dummy; size_t i = 0; target = va_arg(args, HashTable*); aliases = va_arg(args, zend_trait_alias**); exclude_table = va_arg(args, HashTable*); fnname_len = strlen(fn->common.function_name); /* apply aliases which are qualified with a class name, there should not be any ambiguity */ if (aliases) { while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias != NULL && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && aliases[i]->trait_method->mname_len == fnname_len && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy = *fn; function_add_ref(&fn_copy); /* this function_name is never destroyed, because its refcount greater than 1, classes are always destoyed in reverse order and trait is declared early than this class */ fn_copy.common.function_name = aliases[i]->alias; /* if it is 0, no modifieres has been changed */ if (aliases[i]->modifiers) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } lcname = zend_str_tolower_dup(aliases[i]->alias, aliases[i]->alias_len); if (zend_hash_add(target, lcname, aliases[i]->alias_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add aliased trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } efree(lcname); /** Record the trait from which this alias was resolved. */ if (!aliases[i]->trait_method->ce) { aliases[i]->trait_method->ce = fn->common.scope; } } i++; } } lcname = zend_str_tolower_dup(fn->common.function_name, fnname_len); if (exclude_table == NULL || zend_hash_find(exclude_table, lcname, fnname_len, &dummy) == FAILURE) { /* is not in hashtable, thus, function is not to be excluded */ fn_copy = *fn; function_add_ref(&fn_copy); /* apply aliases which are not qualified by a class name, or which have not * alias name, just setting visibility */ if (aliases) { i = 0; while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias == NULL && aliases[i]->modifiers != 0 && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && (aliases[i]->trait_method->mname_len == fnname_len) && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); /** Record the trait from which this alias was resolved. */ if (!aliases[i]->trait_method->ce) { aliases[i]->trait_method->ce = fn->common.scope; } } i++; } } if (zend_hash_add(target, lcname, fnname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } } efree(lcname); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* Copies function table entries to target function table with applied aliasing */ static void zend_traits_copy_trait_function_table(HashTable *target, HashTable *source, zend_trait_alias** aliases, HashTable* exclude_table TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_arguments(source TSRMLS_CC, (apply_func_args_t)zend_traits_copy_functions, 3, target, aliases, exclude_table); } /* }}} */ static void zend_traits_init_trait_structures(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i, j = 0; zend_trait_precedence *cur_precedence; zend_trait_method_reference *cur_method_ref; char *lcname; zend_bool method_exists; /* resolve class references */ if (ce->trait_precedences) { i = 0; while ((cur_precedence = ce->trait_precedences[i])) { /** Resolve classes for all precedence operations. */ if (cur_precedence->exclude_from_classes) { cur_method_ref = cur_precedence->trait_method; cur_precedence->trait_method->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); /** Ensure that the prefered method is actually available. */ lcname = zend_str_tolower_dup(cur_method_ref->method_name, cur_method_ref->mname_len); method_exists = zend_hash_exists(&cur_method_ref->ce->function_table, lcname, cur_method_ref->mname_len + 1); efree(lcname); if (!method_exists) { zend_error(E_COMPILE_ERROR, "A precedence rule was defined for %s::%s but this method does not exist", cur_method_ref->ce->name, cur_method_ref->method_name); } /** With the other traits, we are more permissive. We do not give errors for those. This allows to be more defensive in such definitions. */ j = 0; while (cur_precedence->exclude_from_classes[j]) { char* class_name = (char*)cur_precedence->exclude_from_classes[j]; zend_uint name_length = strlen(class_name); cur_precedence->exclude_from_classes[j] = zend_fetch_class(class_name, name_length, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); efree(class_name); j++; } } i++; } } if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { /** For all aliases with an explicit class name, resolve the class now. */ if (ce->trait_aliases[i]->trait_method->class_name) { cur_method_ref = ce->trait_aliases[i]->trait_method; cur_method_ref->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); /** And, ensure that the referenced method is resolvable, too. */ lcname = zend_str_tolower_dup(cur_method_ref->method_name, cur_method_ref->mname_len); method_exists = zend_hash_exists(&cur_method_ref->ce->function_table, lcname, cur_method_ref->mname_len + 1); efree(lcname); if (!method_exists) { zend_error(E_COMPILE_ERROR, "An alias was defined for %s::%s but this method does not exist", cur_method_ref->ce->name, cur_method_ref->method_name); } } i++; } } } /* }}} */ static void zend_traits_compile_exclude_table(HashTable* exclude_table, zend_trait_precedence **precedences, zend_class_entry *trait) /* {{{ */ { size_t i = 0, j; if (!precedences) { return; } while (precedences[i]) { if (precedences[i]->exclude_from_classes) { j = 0; while (precedences[i]->exclude_from_classes[j]) { if (precedences[i]->exclude_from_classes[j] == trait) { zend_uint lcname_len = precedences[i]->trait_method->mname_len; char *lcname = zend_str_tolower_dup(precedences[i]->trait_method->method_name, lcname_len); if (zend_hash_add(exclude_table, lcname, lcname_len, NULL, 0, NULL) == FAILURE) { efree(lcname); zend_error(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", precedences[i]->trait_method->method_name, trait->name); } efree(lcname); } ++j; } } ++i; } } /* }}} */ static void zend_do_traits_method_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { HashTable** function_tables; HashTable* resulting_table; HashTable exclude_table; size_t i; /* prepare copies of trait function tables for combination */ function_tables = malloc(sizeof(HashTable*) * ce->num_traits); resulting_table = (HashTable *) malloc(sizeof(HashTable)); /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(resulting_table, 10, NULL, NULL, 1, 0); for (i = 0; i < ce->num_traits; i++) { function_tables[i] = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(function_tables[i], ce->traits[i]->function_table.nNumOfElements, NULL, NULL, 1, 0); if (ce->trait_precedences) { /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(&exclude_table, 2, NULL, NULL, 0, 0); zend_traits_compile_exclude_table(&exclude_table, ce->trait_precedences, ce->traits[i]); /* copies functions, applies defined aliasing, and excludes unused trait methods */ zend_traits_copy_trait_function_table(function_tables[i], &ce->traits[i]->function_table, ce->trait_aliases, &exclude_table TSRMLS_CC); zend_hash_destroy(&exclude_table); } else { zend_traits_copy_trait_function_table(function_tables[i], &ce->traits[i]->function_table, ce->trait_aliases, NULL TSRMLS_CC); } } /* now merge trait methods */ for (i = 0; i < ce->num_traits; i++) { zend_hash_apply_with_arguments(function_tables[i] TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions, 5, i, ce->num_traits, resulting_table, function_tables, ce); } /* Now the resulting_table contains all trait methods we would have to * add to the class in the following step the methods are inserted into the method table * if there is already a method with the same name it is replaced iff ce != fn.scope * --> all inherited methods are overridden, methods defined in the class are left untouched */ zend_hash_apply_with_arguments(resulting_table TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions_to_class, 1, ce); /* free temporary function tables */ for (i = 0; i < ce->num_traits; i++) { /* zend_hash_destroy(function_tables[i]); */ zend_hash_graceful_destroy(function_tables[i]); free(function_tables[i]); } free(function_tables); /* free temporary resulting table */ /* zend_hash_destroy(resulting_table); */ zend_hash_graceful_destroy(resulting_table); free(resulting_table); } /* }}} */ static zend_class_entry* find_first_definition(zend_class_entry *ce, size_t current_trait, const char* prop_name, int prop_name_length, ulong prop_hash, zend_class_entry *coliding_ce) /* {{{ */ { size_t i; zend_property_info *coliding_prop; for (i = 0; (i < current_trait) && (i < ce->num_traits); i++) { if (zend_hash_quick_find(&ce->traits[i]->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS) { return ce->traits[i]; } } return coliding_ce; } /* }}} */ static void zend_traits_register_private_property(zend_class_entry *ce, const char *name, int name_len, zend_property_info *old_info, zval *property TSRMLS_DC) /* {{{ */ { char *priv_name; int priv_name_length; const char *interned_name; zend_property_info property_info; ulong h = zend_get_hash_value(name, name_len+1); property_info = *old_info; if (old_info->flags & ZEND_ACC_STATIC) { property_info.offset = ce->default_static_members_count++; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(zval*) * ce->default_static_members_count, ce->type == ZEND_INTERNAL_CLASS); ce->default_static_members_table[property_info.offset] = property; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } else { property_info.offset = ce->default_properties_count++; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(zval*) * ce->default_properties_count, ce->type == ZEND_INTERNAL_CLASS); ce->default_properties_table[property_info.offset] = property; } zend_mangle_property_name(&priv_name, &priv_name_length, ce->name, ce->name_length, name, name_len, ce->type & ZEND_INTERNAL_CLASS); property_info.name = priv_name; property_info.name_length = priv_name_length; interned_name = zend_new_interned_string(property_info.name, property_info.name_length+1, 0 TSRMLS_CC); if (interned_name != property_info.name) { if (ce->type == ZEND_USER_CLASS) { efree((char*)property_info.name); } else { free((char*)property_info.name); } property_info.name = interned_name; } property_info.h = zend_get_hash_value(property_info.name, property_info.name_length+1); property_info.ce = ce; if (property_info.doc_comment) { property_info.doc_comment = estrndup(property_info.doc_comment, property_info.doc_comment_len); } zend_hash_quick_update(&ce->properties_info, name, name_len+1, h, &property_info, sizeof(zend_property_info), NULL); } /* }}} */ static void zend_do_traits_property_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i; zend_property_info *property_info; zend_property_info *coliding_prop; zval compare_result; const char* prop_name; int prop_name_length; ulong prop_hash; const char* class_name_unused; zend_bool not_compatible; zval* prop_value; char* doc_comment; /* In the following steps the properties are inserted into the property table * for that, a very strict approach is applied: * - check for compatibility, if not compatible with any property in class -> fatal * - if compatible, then strict notice */ for (i = 0; i < ce->num_traits; i++) { for (zend_hash_internal_pointer_reset(&ce->traits[i]->properties_info); zend_hash_get_current_data(&ce->traits[i]->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->traits[i]->properties_info)) { /* first get the unmangeld name if necessary, * then check whether the property is already there */ if ((property_info->flags & ZEND_ACC_PPP_MASK) == ZEND_ACC_PUBLIC) { prop_hash = property_info->h; prop_name = property_info->name; prop_name_length = property_info->name_length; } else { /* for private and protected we need to unmangle the names */ zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name_unused, &prop_name); prop_name_length = strlen(prop_name); prop_hash = zend_get_hash_value(prop_name, prop_name_length + 1); } /* next: check for conflicts with current class */ if (zend_hash_quick_find(&ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS) { if (coliding_prop->flags & ZEND_ACC_SHADOW) { /* this one is inherited, lets look it up in its own class */ zend_hash_quick_find(&coliding_prop->ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop); if (coliding_prop->flags & ZEND_ACC_PRIVATE) { /* private property, make the property_info.offset indenpended */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); zend_traits_register_private_property(ce, prop_name, prop_name_length, property_info, prop_value TSRMLS_CC); continue; } } if ((coliding_prop->flags & (ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC)) == (property_info->flags & (ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC))) { /* flags are identical, now the value needs to be checked */ if (property_info->flags & ZEND_ACC_STATIC) { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_static_members_table[coliding_prop->offset], ce->traits[i]->default_static_members_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } else { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_properties_table[coliding_prop->offset], ce->traits[i]->default_properties_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } } else { /* the flags are not identical, thus, we assume properties are not compatible */ not_compatible = 1; } if (not_compatible) { zend_error(E_COMPILE_ERROR, "%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } else { zend_error(E_STRICT, "%s and %s define the same property ($%s) in the composition of %s. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } } /* property not found, so lets add it */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); doc_comment = property_info->doc_comment ? estrndup(property_info->doc_comment, property_info->doc_comment_len) : NULL; zend_declare_property_ex(ce, prop_name, prop_name_length, prop_value, property_info->flags, doc_comment, property_info->doc_comment_len TSRMLS_CC); } } } /* }}} */ static void zend_do_check_for_inconsistent_traits_aliasing(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { int i = 0; zend_trait_alias* cur_alias; char* lc_method_name; if (ce->trait_aliases) { while (ce->trait_aliases[i]) { cur_alias = ce->trait_aliases[i]; /** The trait for this alias has not been resolved, this means, this alias was not applied. Abort with an error. */ if (!cur_alias->trait_method->ce) { if (cur_alias->alias) { /** Plain old inconsistency/typo/bug */ zend_error(E_COMPILE_ERROR, "An alias (%s) was defined for method %s(), but this method does not exist", cur_alias->alias, cur_alias->trait_method->method_name); } else { /** Here are two possible cases: 1) this is an attempt to modifiy the visibility of a method introduce as part of another alias. Since that seems to violate the DRY principle, we check against it and abort. 2) it is just a plain old inconsitency/typo/bug as in the case where alias is set. */ lc_method_name = zend_str_tolower_dup(cur_alias->trait_method->method_name, cur_alias->trait_method->mname_len); if (zend_hash_exists(&ce->function_table, lc_method_name, cur_alias->trait_method->mname_len+1)) { efree(lc_method_name); zend_error(E_COMPILE_ERROR, "The modifiers for the trait alias %s() need to be changed in the same statment in which the alias is defined. Error", cur_alias->trait_method->method_name); } else { efree(lc_method_name); zend_error(E_COMPILE_ERROR, "The modifiers of the trait method %s() are changed, but this method does not exist. Error", cur_alias->trait_method->method_name); } } } i++; } } } /* }}} */ ZEND_API void zend_do_bind_traits(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { if (ce->num_traits <= 0) { return; } /* complete initialization of trait strutures in ce */ zend_traits_init_trait_structures(ce TSRMLS_CC); /* first care about all methods to be flattened into the class */ zend_do_traits_method_binding(ce TSRMLS_CC); /* Aliases which have not been applied indicate typos/bugs. */ zend_do_check_for_inconsistent_traits_aliasing(ce TSRMLS_CC); /* then flatten the properties into it, to, mostly to notfiy developer about problems */ zend_do_traits_property_binding(ce TSRMLS_CC); /* verify that all abstract methods from traits have been implemented */ zend_verify_abstract_class(ce TSRMLS_CC); /* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */ if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { ce->ce_flags -= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } } /* }}} */ ZEND_API int do_bind_function(const zend_op_array *op_array, zend_op *opline, HashTable *function_table, zend_bool compile_time) /* {{{ */ { zend_function *function; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } zend_hash_quick_find(function_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void *) &function); if (zend_hash_quick_add(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), function, sizeof(zend_function), NULL)==FAILURE) { int error_level = compile_time ? E_COMPILE_ERROR : E_ERROR; zend_function *old_function; if (zend_hash_quick_find(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), (void *) &old_function)==SUCCESS && old_function->type == ZEND_USER_FUNCTION && old_function->op_array.last > 0) { zend_error(error_level, "Cannot redeclare %s() (previously declared in %s:%d)", function->common.function_name, old_function->op_array.filename, old_function->op_array.opcodes[0].lineno); } else { zend_error(error_level, "Cannot redeclare %s()", function->common.function_name); } return FAILURE; } else { (*function->op_array.refcount)++; function->op_array.static_variables = NULL; /* NULL out the unbound function */ return SUCCESS; } } /* }}} */ void zend_add_trait_precedence(znode *precedence_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_precedences, precedence_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_add_trait_alias(znode *alias_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_aliases, alias_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_prepare_reference(znode *result, znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { zend_trait_method_reference *method_ref = emalloc(sizeof(zend_trait_method_reference)); method_ref->ce = NULL; /* REM: There should not be a need for copying, zend_do_begin_class_declaration is also just using that string */ if (class_name) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); method_ref->class_name = Z_STRVAL(class_name->u.constant); method_ref->cname_len = Z_STRLEN(class_name->u.constant); } else { method_ref->class_name = NULL; method_ref->cname_len = 0; } method_ref->method_name = Z_STRVAL(method_name->u.constant); method_ref->mname_len = Z_STRLEN(method_name->u.constant); result->u.op.ptr = method_ref; result->op_type = IS_TMP_VAR; } /* }}} */ void zend_prepare_trait_alias(znode *result, znode *method_reference, znode *modifiers, znode *alias TSRMLS_DC) /* {{{ */ { zend_trait_alias *trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_alias->modifiers = Z_LVAL(modifiers->u.constant); if (Z_LVAL(modifiers->u.constant) == ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot use 'static' as method modifier"); return; } if (alias) { trait_alias->alias = Z_STRVAL(alias->u.constant); trait_alias->alias_len = Z_STRLEN(alias->u.constant); } else { trait_alias->alias = NULL; } trait_alias->function = NULL; result->u.op.ptr = trait_alias; } /* }}} */ void zend_prepare_trait_precedence(znode *result, znode *method_reference, znode *trait_list TSRMLS_DC) /* {{{ */ { zend_trait_precedence *trait_precedence = emalloc(sizeof(zend_trait_precedence)); trait_precedence->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_precedence->exclude_from_classes = (zend_class_entry**) trait_list->u.op.ptr; trait_precedence->function = NULL; result->u.op.ptr = trait_precedence; } /* }}} */ ZEND_API zend_class_entry *do_bind_class(const zend_op_array* op_array, const zend_op *opline, HashTable *class_table, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } if (zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce)==FAILURE) { zend_error(E_COMPILE_ERROR, "Internal Zend error - Missing class information for %s", Z_STRVAL_P(op1)); return NULL; } else { ce = *pce; } ce->refcount++; if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), &ce, sizeof(zend_class_entry *), NULL)==FAILURE) { ce->refcount--; if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return NULL; } else { if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLEMENT_INTERFACES))) { zend_verify_abstract_class(ce TSRMLS_CC); } return ce; } } /* }}} */ ZEND_API zend_class_entry *do_bind_inherited_class(const zend_op_array *op_array, const zend_op *opline, HashTable *class_table, zend_class_entry *parent_ce, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; int found_ce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } found_ce = zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce); if (found_ce == FAILURE) { if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", Z_STRVAL_P(op2)); } return NULL; } else { ce = *pce; } if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ce->name, parent_ce->name); } else if ((parent_ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ce->name, parent_ce->name); } zend_do_inheritance(ce, parent_ce TSRMLS_CC); ce->refcount++; /* Register the derived class */ if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), pce, sizeof(zend_class_entry *), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return ce; } /* }}} */ void zend_do_early_binding(TSRMLS_D) /* {{{ */ { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; HashTable *table; while (opline->opcode == ZEND_TICKS && opline > CG(active_op_array)->opcodes) { opline--; } switch (opline->opcode) { case ZEND_DECLARE_FUNCTION: if (do_bind_function(CG(active_op_array), opline, CG(function_table), 1) == FAILURE) { return; } table = CG(function_table); break; case ZEND_DECLARE_CLASS: if (do_bind_class(CG(active_op_array), opline, CG(class_table), 1 TSRMLS_CC) == NULL) { return; } table = CG(class_table); break; case ZEND_DECLARE_INHERITED_CLASS: { zend_op *fetch_class_opline = opline-1; zval *parent_name; zend_class_entry **pce; parent_name = &CONSTANT(fetch_class_opline->op2.constant); if ((zend_lookup_class(Z_STRVAL_P(parent_name), Z_STRLEN_P(parent_name), &pce TSRMLS_CC) == FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_CLASSES) && ((*pce)->type == ZEND_INTERNAL_CLASS))) { if (CG(compiler_options) & ZEND_COMPILE_DELAYED_BINDING) { zend_uint *opline_num = &CG(active_op_array)->early_binding; while (*opline_num != -1) { opline_num = &CG(active_op_array)->opcodes[*opline_num].result.opline_num; } *opline_num = opline - CG(active_op_array)->opcodes; opline->opcode = ZEND_DECLARE_INHERITED_CLASS_DELAYED; opline->result_type = IS_UNUSED; opline->result.opline_num = -1; } return; } if (do_bind_inherited_class(CG(active_op_array), opline, CG(class_table), *pce, 1 TSRMLS_CC) == NULL) { return; } /* clear unnecessary ZEND_FETCH_CLASS opcode */ zend_del_literal(CG(active_op_array), fetch_class_opline->op2.constant); MAKE_NOP(fetch_class_opline); table = CG(class_table); break; } case ZEND_VERIFY_ABSTRACT_CLASS: case ZEND_ADD_INTERFACE: case ZEND_ADD_TRAIT: case ZEND_BIND_TRAITS: /* We currently don't early-bind classes that implement interfaces */ /* Classes with traits are handled exactly the same, no early-bind here */ return; default: zend_error(E_COMPILE_ERROR, "Invalid binding type"); return; } zend_hash_quick_del(table, Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant)), Z_HASH_P(&CONSTANT(opline->op1.constant))); zend_del_literal(CG(active_op_array), opline->op1.constant); zend_del_literal(CG(active_op_array), opline->op2.constant); MAKE_NOP(opline); } /* }}} */ ZEND_API void zend_do_delayed_early_binding(const zend_op_array *op_array TSRMLS_DC) /* {{{ */ { if (op_array->early_binding != -1) { zend_bool orig_in_compilation = CG(in_compilation); zend_uint opline_num = op_array->early_binding; zend_class_entry **pce; CG(in_compilation) = 1; while (opline_num != -1) { if (zend_lookup_class(Z_STRVAL_P(op_array->opcodes[opline_num-1].op2.zv), Z_STRLEN_P(op_array->opcodes[opline_num-1].op2.zv), &pce TSRMLS_CC) == SUCCESS) { do_bind_inherited_class(op_array, &op_array->opcodes[opline_num], EG(class_table), *pce, 0 TSRMLS_CC); } opline_num = op_array->opcodes[opline_num].result.opline_num; } CG(in_compilation) = orig_in_compilation; } } /* }}} */ void zend_do_boolean_or_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_or_end(znode *result, const znode *expr1, const znode *expr2, znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_boolean_and_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_and_end(znode *result, const znode *expr1, const znode *expr2, const znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_do_while_begin(TSRMLS_D) /* {{{ */ { do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_do_while_end(const znode *do_token, const znode *expr_open_bracket, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ; SET_NODE(opline->op1, expr); opline->op2.opline_num = do_token->u.op.opline_num; SET_UNUSED(opline->op2); do_end_loop(expr_open_bracket->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_brk_cont(zend_uchar op, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->op1.opline_num = CG(context).current_brk_cont; SET_UNUSED(opline->op1); if (expr) { if (expr->op_type != IS_CONST) { zend_error(E_COMPILE_ERROR, "'%s' operator with non-constant operand is no longer supported", op == ZEND_BRK ? "break" : "continue"); } else if (Z_TYPE(expr->u.constant) != IS_LONG || Z_LVAL(expr->u.constant) < 1) { zend_error(E_COMPILE_ERROR, "'%s' operator accepts only positive numbers", op == ZEND_BRK ? "break" : "continue"); } SET_NODE(opline->op2, expr); } else { LITERAL_LONG(opline->op2, 1); opline->op2_type = IS_CONST; } } /* }}} */ void zend_do_switch_cond(const znode *cond TSRMLS_DC) /* {{{ */ { zend_switch_entry switch_entry; switch_entry.cond = *cond; switch_entry.default_case = -1; switch_entry.control_var = -1; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_switch_end(const znode *case_list TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); /* add code to jmp to default case */ if (switch_entry_ptr->default_case != -1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->op1.opline_num = switch_entry_ptr->default_case; } if (case_list->op_type != IS_UNUSED) { /* non-empty switch */ int next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* remember break/continue loop information */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; if (switch_entry_ptr->cond.op_type==IS_VAR || switch_entry_ptr->cond.op_type==IS_TMP_VAR) { /* emit free for the switch condition*/ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry_ptr->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_UNUSED(opline->op2); } if (switch_entry_ptr->cond.op_type == IS_CONST) { zval_dtor(&switch_entry_ptr->cond.u.constant); } zend_stack_del_top(&CG(switch_cond_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_case_before_statement(const znode *case_list, znode *case_token, const znode *case_expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); int next_op_number; zend_switch_entry *switch_entry_ptr; znode result; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); if (switch_entry_ptr->control_var == -1) { switch_entry_ptr->control_var = get_temporary_variable(CG(active_op_array)); } opline->opcode = ZEND_CASE; opline->result.var = switch_entry_ptr->control_var; opline->result_type = IS_TMP_VAR; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_NODE(opline->op2, case_expr); if (opline->op1_type == IS_CONST) { zval_copy_ctor(&CONSTANT(opline->op1.constant)); } GET_NODE(&result, opline->result); next_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, &result); SET_UNUSED(opline->op2); case_token->u.op.opline_num = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_case_after_statement(znode *result, const znode *case_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); result->u.op.opline_num = next_op_number; switch (CG(active_op_array)->opcodes[case_token->u.op.opline_num].opcode) { case ZEND_JMP: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); break; case ZEND_JMPZ: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); break; } } /* }}} */ void zend_do_default_before_statement(const znode *case_list, znode *default_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); default_token->u.op.opline_num = next_op_number; next_op_number = get_next_op_number(CG(active_op_array)); switch_entry_ptr->default_case = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_begin_class_declaration(const znode *class_token, znode *class_name, const znode *parent_class_name TSRMLS_DC) /* {{{ */ { zend_op *opline; int doing_inheritance = 0; zend_class_entry *new_class_entry; char *lcname; int error = 0; zval **ns_name, key; if (CG(active_class_entry)) { zend_error(E_COMPILE_ERROR, "Class declarations may not be nested"); return; } lcname = zend_str_tolower_dup(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); if (!(strcmp(lcname, "self") && strcmp(lcname, "parent"))) { efree(lcname); zend_error(E_COMPILE_ERROR, "Cannot use '%s' as class name as it is reserved", Z_STRVAL(class_name->u.constant)); } /* Class name must not conflict with import names */ if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns_name) == SUCCESS) { error = 1; } if (CG(current_namespace)) { /* Prefix class name with name of current namespace */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); class_name = &tmp; efree(lcname); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); } if (error) { char *tmp = zend_str_tolower_dup(Z_STRVAL_PP(ns_name), Z_STRLEN_PP(ns_name)); if (Z_STRLEN_PP(ns_name) != Z_STRLEN(class_name->u.constant) || memcmp(tmp, lcname, Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "Cannot declare class %s because the name is already in use", Z_STRVAL(class_name->u.constant)); } efree(tmp); } new_class_entry = emalloc(sizeof(zend_class_entry)); new_class_entry->type = ZEND_USER_CLASS; new_class_entry->name = zend_new_interned_string(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1, 1 TSRMLS_CC); new_class_entry->name_length = Z_STRLEN(class_name->u.constant); zend_initialize_class_data(new_class_entry, 1 TSRMLS_CC); new_class_entry->info.user.filename = zend_get_compiled_filename(TSRMLS_C); new_class_entry->info.user.line_start = class_token->u.op.opline_num; new_class_entry->ce_flags |= class_token->EA; if (parent_class_name && parent_class_name->op_type != IS_UNUSED) { switch (parent_class_name->EA) { case ZEND_FETCH_CLASS_SELF: zend_error(E_COMPILE_ERROR, "Cannot use 'self' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_PARENT: zend_error(E_COMPILE_ERROR, "Cannot use 'parent' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use 'static' as class name as it is reserved"); break; default: break; } doing_inheritance = 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, new_class_entry->name_length TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; if (doing_inheritance) { /* Make sure a trait does not try to extend a class */ if ((new_class_entry->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "A trait (%s) cannot extend a class", new_class_entry->name); } opline->extended_value = parent_class_name->u.op.var; opline->opcode = ZEND_DECLARE_INHERITED_CLASS; } else { opline->opcode = ZEND_DECLARE_CLASS; } LITERAL_STRINGL(opline->op2, lcname, new_class_entry->name_length, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); zend_hash_quick_update(CG(class_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &new_class_entry, sizeof(zend_class_entry *), NULL); CG(active_class_entry) = new_class_entry; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(&CG(implementing_class), opline->result); if (CG(doc_comment)) { CG(active_class_entry)->info.user.doc_comment = CG(doc_comment); CG(active_class_entry)->info.user.doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ static void do_verify_abstract_class(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_VERIFY_ABSTRACT_CLASS; SET_NODE(opline->op1, &CG(implementing_class)); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_class_declaration(const znode *class_token, const znode *parent_token TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); if (ce->constructor) { ce->constructor->common.fn_flags |= ZEND_ACC_CTOR; if (ce->constructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Constructor %s::%s() cannot be static", ce->name, ce->constructor->common.function_name); } } if (ce->destructor) { ce->destructor->common.fn_flags |= ZEND_ACC_DTOR; if (ce->destructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Destructor %s::%s() cannot be static", ce->name, ce->destructor->common.function_name); } } if (ce->clone) { ce->clone->common.fn_flags |= ZEND_ACC_CLONE; if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static", ce->name, ce->clone->common.function_name); } } ce->info.user.line_end = zend_get_compiled_lineno(TSRMLS_C); /* Check for traits and proceed like with interfaces. * The only difference will be a combined handling of them in the end. * Thus, we need another opcode here. */ if (ce->num_traits > 0) { zend_op *opline; ce->traits = NULL; ce->num_traits = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_TRAITS; /* opcode generation: */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BIND_TRAITS; SET_NODE(opline->op1, &CG(implementing_class)); } if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) && ((parent_token->op_type != IS_UNUSED) || (ce->num_interfaces > 0))) { zend_verify_abstract_class(ce TSRMLS_CC); if (ce->num_interfaces) { do_verify_abstract_class(TSRMLS_C); } } /* Inherit interfaces; reset number to zero, we need it for above check and * will restore it during actual implementation. * The ZEND_ACC_IMPLEMENT_INTERFACES flag disables double call to * zend_verify_abstract_class() */ if (ce->num_interfaces > 0) { ce->interfaces = NULL; ce->num_interfaces = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_INTERFACES; } CG(active_class_entry) = NULL; } /* }}} */ void zend_do_implements_interface(znode *interface_name TSRMLS_DC) /* {{{ */ { zend_op *opline; /* Traits can not implement interfaces */ if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface on '%s' since it is a Trait", Z_STRVAL(interface_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(interface_name->u.constant), Z_STRLEN(interface_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface name as it is reserved", Z_STRVAL(interface_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_INTERFACE; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(interface_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = (opline->extended_value & ~ZEND_FETCH_CLASS_MASK) | ZEND_FETCH_CLASS_INTERFACE; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &interface_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_interfaces++; } /* }}} */ void zend_do_implements_trait(znode *trait_name TSRMLS_DC) /* {{{ */ { zend_op *opline; if ((CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Cannot use traits inside of interfaces. %s is used in %s", Z_STRVAL(trait_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(trait_name->u.constant), Z_STRLEN(trait_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as trait name as it is reserved", Z_STRVAL(trait_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_TRAIT; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(trait_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = ZEND_FETCH_CLASS_TRAIT; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &trait_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_traits++; } /* }}} */ ZEND_API void zend_mangle_property_name(char **dest, int *dest_length, const char *src1, int src1_length, const char *src2, int src2_length, int internal) /* {{{ */ { char *prop_name; int prop_name_length; prop_name_length = 1 + src1_length + 1 + src2_length; prop_name = pemalloc(prop_name_length + 1, internal); prop_name[0] = '\0'; memcpy(prop_name + 1, src1, src1_length+1); memcpy(prop_name + 1 + src1_length + 1, src2, src2_length+1); *dest = prop_name; *dest_length = prop_name_length; } /* }}} */ static int zend_strnlen(const char* s, int maxlen) /* {{{ */ { int len = 0; while (*s++ && maxlen--) len++; return len; } /* }}} */ ZEND_API int zend_unmangle_property_name(const char *mangled_property, int len, const char **class_name, const char **prop_name) /* {{{ */ { int class_name_len; *class_name = NULL; if (mangled_property[0]!=0) { *prop_name = mangled_property; return SUCCESS; } if (len < 3 || mangled_property[1]==0) { zend_error(E_NOTICE, "Illegal member variable name"); *prop_name = mangled_property; return FAILURE; } class_name_len = zend_strnlen(mangled_property+1, --len - 1) + 1; if (class_name_len >= len || mangled_property[class_name_len]!=0) { zend_error(E_NOTICE, "Corrupt member variable name"); *prop_name = mangled_property; return FAILURE; } *class_name = mangled_property+1; *prop_name = (*class_name)+class_name_len; return SUCCESS; } /* }}} */ void zend_do_declare_property(const znode *var_name, const znode *value, zend_uint access_type TSRMLS_DC) /* {{{ */ { zval *property; zend_property_info *existing_property_info; char *comment = NULL; int comment_len = 0; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Interfaces may not include member variables"); } if (access_type & ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Properties cannot be declared abstract"); } if (access_type & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot declare property %s::$%s final, the final modifier is allowed only for methods and classes", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } if (zend_hash_find(&CG(active_class_entry)->properties_info, var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, (void **) &existing_property_info)==SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::$%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } ALLOC_ZVAL(property); if (value) { *property = value->u.constant; } else { INIT_PZVAL(property); Z_TYPE_P(property) = IS_NULL; } if (CG(doc_comment)) { comment = CG(doc_comment); comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } zend_declare_property_ex(CG(active_class_entry), zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len + 1, 0 TSRMLS_CC), var_name->u.constant.value.str.len, property, access_type, comment, comment_len TSRMLS_CC); efree(var_name->u.constant.value.str.val); } /* }}} */ void zend_do_declare_class_constant(znode *var_name, const znode *value TSRMLS_DC) /* {{{ */ { zval *property; const char *cname = NULL; int result; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed in class constants"); return; } if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Traits cannot have constants"); return; } ALLOC_ZVAL(property); *property = value->u.constant; cname = zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, 0 TSRMLS_CC); if (IS_INTERNED(cname)) { result = zend_hash_quick_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, INTERNED_HASH(cname), &property, sizeof(zval *), NULL); } else { result = zend_hash_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, &property, sizeof(zval *), NULL); } if (result == FAILURE) { FREE_ZVAL(property); zend_error(E_COMPILE_ERROR, "Cannot redefine class constant %s::%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } FREE_PNODE(var_name); if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_fetch_property(znode *result, znode *object, const znode *property TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (object->op_type == IS_CV) { if (object->u.op.var == CG(active_op_array)->this_var) { object->op_type = IS_UNUSED; /* this means $this for objects */ } } else if (fetch_list_ptr->count == 1) { zend_llist_element *le = fetch_list_ptr->head; zend_op *opline_ptr = (zend_op *) le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); SET_UNUSED(opline_ptr->op1); /* this means $this for objects */ SET_NODE(opline_ptr->op2, property); /* if it was usual fetch, we change it to object fetch */ switch (opline_ptr->opcode) { case ZEND_FETCH_W: opline_ptr->opcode = ZEND_FETCH_OBJ_W; break; case ZEND_FETCH_R: opline_ptr->opcode = ZEND_FETCH_OBJ_R; break; case ZEND_FETCH_RW: opline_ptr->opcode = ZEND_FETCH_OBJ_RW; break; case ZEND_FETCH_IS: opline_ptr->opcode = ZEND_FETCH_OBJ_IS; break; case ZEND_FETCH_UNSET: opline_ptr->opcode = ZEND_FETCH_OBJ_UNSET; break; case ZEND_FETCH_FUNC_ARG: opline_ptr->opcode = ZEND_FETCH_OBJ_FUNC_ARG; break; } if (opline_ptr->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline_ptr->op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline_ptr->op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op2.constant); } GET_NODE(result, opline_ptr->result); return; } } if (zend_is_function_or_method_call(object)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, object); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_OBJ_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, object); SET_NODE(opline.op2, property); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline.op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op2.constant); } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void zend_do_halt_compiler_register(TSRMLS_D) /* {{{ */ { char *name, *cfilename; char haltoff[] = "__COMPILER_HALT_OFFSET__"; int len, clen; if (CG(has_bracketed_namespaces) && CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "__HALT_COMPILER() can only be used from the outermost scope"); } cfilename = zend_get_compiled_filename(TSRMLS_C); clen = strlen(cfilename); zend_mangle_property_name(&name, &len, haltoff, sizeof(haltoff) - 1, cfilename, clen, 0); zend_register_long_constant(name, len+1, zend_get_scanned_file_offset(TSRMLS_C), CONST_CS, 0 TSRMLS_CC); pefree(name, 0); if (CG(in_namespace)) { zend_do_end_namespace(TSRMLS_C); } } /* }}} */ void zend_do_push_object(const znode *object TSRMLS_DC) /* {{{ */ { zend_stack_push(&CG(object_stack), object, sizeof(znode)); } /* }}} */ void zend_do_pop_object(znode *object TSRMLS_DC) /* {{{ */ { if (object) { znode *tmp; zend_stack_top(&CG(object_stack), (void **) &tmp); *object = *tmp; } zend_stack_del_top(&CG(object_stack)); } /* }}} */ void zend_do_begin_new_object(znode *new_token, znode *class_type TSRMLS_DC) /* {{{ */ { zend_op *opline; unsigned char *ptr = NULL; new_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_NEW; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, class_type); SET_UNUSED(opline->op2); zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(unsigned char *)); } /* }}} */ void zend_do_end_new_object(znode *result, const znode *new_token, const znode *argument_list TSRMLS_DC) /* {{{ */ { znode ctor_result; zend_do_end_function_call(NULL, &ctor_result, argument_list, 1, 0 TSRMLS_CC); zend_do_free(&ctor_result TSRMLS_CC); CG(active_op_array)->opcodes[new_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, CG(active_op_array)->opcodes[new_token->u.op.opline_num].result); } /* }}} */ static zend_constant* zend_get_ct_const(const zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = NULL; if (Z_STRVAL_P(const_name)[0] == '\\') { if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name), (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name)-1); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name), (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } } else if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)+1, (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name)+1, (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } if (c->flags & CONST_CT_SUBST) { return c; } if (all_internal_constants_substitution && (c->flags & CONST_PERSISTENT) && !(CG(compiler_options) & ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION) && Z_TYPE(c->value) != IS_CONSTANT && Z_TYPE(c->value) != IS_CONSTANT_ARRAY) { return c; } return NULL; } /* }}} */ static int zend_constant_ct_subst(znode *result, zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = zend_get_ct_const(const_name, all_internal_constants_substitution TSRMLS_CC); if (c) { zval_dtor(const_name); result->op_type = IS_CONST; result->u.constant = c->value; zval_copy_ctor(&result->u.constant); INIT_PZVAL(&result->u.constant); return 1; } return 0; } /* }}} */ void zend_do_fetch_constant(znode *result, znode *constant_container, znode *constant_name, int mode, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; zend_op *opline; int type; char *compound; ulong fetch_type = 0; if (constant_container) { switch (mode) { case ZEND_CT: /* this is a class constant */ type = zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant)); if (ZEND_FETCH_CLASS_STATIC == type) { zend_error(E_ERROR, "\"static::\" is not allowed in compile-time constants"); } else if (ZEND_FETCH_CLASS_DEFAULT == type) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } zend_do_build_full_name(NULL, constant_container, constant_name, 1 TSRMLS_CC); *result = *constant_container; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: if (constant_container->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant))) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } else { zend_do_fetch_class(&tmp, constant_container TSRMLS_CC); constant_container = &tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); if (constant_container->op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &constant_container->u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, constant_container); } SET_NODE(opline->op2, constant_name); CALCULATE_LITERAL_HASH(opline->op2.constant); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } GET_NODE(result, opline->result); break; } return; } /* namespace constant */ /* only one that did not contain \ from the start can be converted to string if unknown */ switch (mode) { case ZEND_CT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); /* this is a namespace constant, or an unprefixed constant */ if (zend_constant_ct_subst(result, &constant_name->u.constant, 0 TSRMLS_CC)) { break; } zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(!compound) { fetch_type |= IS_CONSTANT_UNQUALIFIED; } *result = *constant_name; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(zend_constant_ct_subst(result, &constant_name->u.constant, 1 TSRMLS_CC)) { break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; if (compound) { /* the name is unambiguous */ opline->extended_value = 0; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } else { opline->extended_value = IS_CONSTANT_UNQUALIFIED; if (CG(current_namespace)) { opline->extended_value |= IS_CONSTANT_IN_NAMESPACE; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 1 TSRMLS_CC); } else { opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } } GET_CACHE_SLOT(opline->op2.constant); break; } } /* }}} */ void zend_do_shell_exec(znode *result, const znode *cmd TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); switch (cmd->op_type) { case IS_CONST: case IS_TMP_VAR: opline->opcode = ZEND_SEND_VAL; break; default: opline->opcode = ZEND_SEND_VAR; break; } SET_NODE(opline->op1, cmd); opline->op2.opline_num = 0; opline->extended_value = ZEND_DO_FCALL; SET_UNUSED(opline->op2); /* FIXME: exception support not added to this op2 */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DO_FCALL; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; LITERAL_STRINGL(opline->op1, estrndup("shell_exec", sizeof("shell_exec")-1), sizeof("shell_exec")-1, 0); CALCULATE_LITERAL_HASH(opline->op1.constant); opline->op1_type = IS_CONST; GET_CACHE_SLOT(opline->op1.constant); opline->extended_value = 1; SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_init_array(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_ARRAY; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; GET_NODE(result, opline->result); if (expr) { SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } } else { SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_array_element(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_ARRAY_ELEMENT; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_static_array_element(znode *result, znode *offset, const znode *expr) /* {{{ */ { zval *element; ALLOC_ZVAL(element); *element = expr->u.constant; if (offset) { switch (offset->u.constant.type & IS_CONSTANT_TYPE_MASK) { case IS_CONSTANT: /* Ugly hack to denote that this value has a constant index */ Z_TYPE_P(element) |= IS_CONSTANT_INDEX; Z_STRVAL(offset->u.constant) = erealloc(Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+1] = Z_TYPE(offset->u.constant); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+2] = 0; zend_symtable_update(result->u.constant.value.ht, Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_STRING: zend_symtable_update(result->u.constant.value.ht, offset->u.constant.value.str.val, offset->u.constant.value.str.len+1, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_NULL: zend_symtable_update(Z_ARRVAL(result->u.constant), "", 1, &element, sizeof(zval *), NULL); break; case IS_LONG: case IS_BOOL: zend_hash_index_update(Z_ARRVAL(result->u.constant), Z_LVAL(offset->u.constant), &element, sizeof(zval *), NULL); break; case IS_DOUBLE: zend_hash_index_update(Z_ARRVAL(result->u.constant), zend_dval_to_lval(Z_DVAL(offset->u.constant)), &element, sizeof(zval *), NULL); break; case IS_CONSTANT_ARRAY: zend_error(E_ERROR, "Illegal offset type"); break; } } else { zend_hash_next_index_insert(Z_ARRVAL(result->u.constant), &element, sizeof(zval *), NULL); } } /* }}} */ void zend_do_add_list_element(const znode *element TSRMLS_DC) /* {{{ */ { list_llist_element lle; if (element) { zend_check_writable_variable(element); lle.var = *element; zend_llist_copy(&lle.dimensions, &CG(dimension_llist)); zend_llist_prepend_element(&CG(list_llist), &lle); } (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_new_list_begin(TSRMLS_D) /* {{{ */ { int current_dimension = 0; zend_llist_add_element(&CG(dimension_llist), &current_dimension); } /* }}} */ void zend_do_new_list_end(TSRMLS_D) /* {{{ */ { zend_llist_remove_tail(&CG(dimension_llist)); (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_list_init(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(list_stack), &CG(list_llist), sizeof(zend_llist)); zend_stack_push(&CG(list_stack), &CG(dimension_llist), sizeof(zend_llist)); zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_do_new_list_begin(TSRMLS_C); } /* }}} */ void zend_do_list_end(znode *result, znode *expr TSRMLS_DC) /* {{{ */ { zend_llist_element *le; zend_llist_element *dimension; zend_op *opline; znode last_container; le = CG(list_llist).head; while (le) { zend_llist *tmp_dimension_llist = &((list_llist_element *)le->data)->dimensions; dimension = tmp_dimension_llist->head; while (dimension) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (dimension == tmp_dimension_llist->head) { /* first */ last_container = *expr; switch (expr->op_type) { case IS_VAR: case IS_CV: opline->opcode = ZEND_FETCH_DIM_R; break; case IS_TMP_VAR: opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; case IS_CONST: /* fetch_dim_tmp_var will handle this bogus fetch */ zval_copy_ctor(&expr->u.constant); opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; } opline->extended_value |= ZEND_FETCH_ADD_LOCK; } else { opline->opcode = ZEND_FETCH_DIM_R; } opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, &last_container); opline->op2_type = IS_CONST; LITERAL_LONG(opline->op2, *((int *) dimension->data)); GET_NODE(&last_container, opline->result); dimension = dimension->next; } ((list_llist_element *) le->data)->value = last_container; zend_llist_destroy(&((list_llist_element *) le->data)->dimensions); zend_do_assign(result, &((list_llist_element *) le->data)->var, &((list_llist_element *) le->data)->value TSRMLS_CC); zend_do_free(result TSRMLS_CC); le = le->next; } zend_llist_destroy(&CG(dimension_llist)); zend_llist_destroy(&CG(list_llist)); *result = *expr; { zend_llist *p; /* restore previous lists */ zend_stack_top(&CG(list_stack), (void **) &p); CG(dimension_llist) = *p; zend_stack_del_top(&CG(list_stack)); zend_stack_top(&CG(list_stack), (void **) &p); CG(list_llist) = *p; zend_stack_del_top(&CG(list_stack)); } } /* }}} */ void zend_init_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = emalloc(sizeof(void*) * 2); list[0] = item; list[1] = NULL; *(void**)result = list; } /* }}} */ void zend_add_to_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = *(void**)result; size_t n = 0; while (list && list[n]) { n++; } list = erealloc(list, sizeof(void*) * (n+2)); list[n] = item; list[n+1] = NULL; *(void**)result = list; } /* }}} */ void zend_do_fetch_static_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zval *tmp; zend_op *opline; znode lval; znode result; ALLOC_ZVAL(tmp); if (static_assignment) { *tmp = static_assignment->u.constant; } else { INIT_ZVAL(*tmp); } if (!CG(active_op_array)->static_variables) { if (CG(active_op_array)->scope) { CG(active_op_array)->scope->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } ALLOC_HASHTABLE(CG(active_op_array)->static_variables); zend_hash_init(CG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } zend_hash_update(CG(active_op_array)->static_variables, varname->u.constant.value.str.val, varname->u.constant.value.str.len+1, &tmp, sizeof(zval *), NULL); if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (fetch_type == ZEND_FETCH_LEXICAL) ? ZEND_FETCH_R : ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_STATIC; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ if (fetch_type == ZEND_FETCH_LEXICAL) { znode dummy; zend_do_begin_variable_parse(TSRMLS_C); zend_do_assign(&dummy, &lval, &result TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } else { zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); } CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_fetch_lexical_variable(znode *varname, zend_bool is_ref TSRMLS_DC) /* {{{ */ { znode value; if (Z_STRLEN(varname->u.constant) == sizeof("this") - 1 && memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this") - 1) == 0) { zend_error(E_COMPILE_ERROR, "Cannot use $this as lexical variable"); return; } value.op_type = IS_CONST; ZVAL_NULL(&value.u.constant); Z_TYPE(value.u.constant) |= is_ref ? IS_LEXICAL_REF : IS_LEXICAL_VAR; Z_SET_REFCOUNT_P(&value.u.constant, 1); Z_UNSET_ISREF_P(&value.u.constant); zend_do_fetch_static_variable(varname, &value, is_ref ? ZEND_FETCH_STATIC : ZEND_FETCH_LEXICAL TSRMLS_CC); } /* }}} */ void zend_do_fetch_global_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zend_op *opline; znode lval; znode result; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = fetch_type; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_cast(znode *result, const znode *expr, int type TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CAST; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } /* }}} */ void zend_do_include_or_eval(int type, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_do_extended_fcall_begin(TSRMLS_C); { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INCLUDE_OR_EVAL; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } zend_do_extended_fcall_end(TSRMLS_C); } /* }}} */ void zend_do_indirect_references(znode *result, const znode *num_references, znode *variable TSRMLS_DC) /* {{{ */ { int i; zend_do_end_variable_parse(variable, BP_VAR_R, 0 TSRMLS_CC); for (i=1; i<num_references->u.constant.value.lval; i++) { fetch_simple_variable_ex(result, variable, 0, ZEND_FETCH_R TSRMLS_CC); *variable = *result; } zend_do_begin_variable_parse(TSRMLS_C); fetch_simple_variable(result, variable, 1 TSRMLS_CC); /* there is a chance someone is accessing $this */ if (CG(active_op_array)->scope && CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } /* }}} */ void zend_do_unset(const znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_UNSET_VAR; SET_NODE(opline->op1, variable); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); opline->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_UNSET: last_op->opcode = ZEND_UNSET_VAR; SET_UNUSED(last_op->result); break; case ZEND_FETCH_DIM_UNSET: last_op->opcode = ZEND_UNSET_DIM; SET_UNUSED(last_op->result); break; case ZEND_FETCH_OBJ_UNSET: last_op->opcode = ZEND_UNSET_OBJ; SET_UNUSED(last_op->result); break; } } } /* }}} */ void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_do_end_variable_parse(variable, BP_VAR_IS, 0 TSRMLS_CC); zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { last_op = get_next_op(CG(active_op_array) TSRMLS_CC); last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; SET_NODE(last_op->op1, variable); SET_UNUSED(last_op->op2); last_op->result.var = get_temporary_variable(CG(active_op_array)); last_op->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; break; case ZEND_FETCH_DIM_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_DIM_OBJ; break; case ZEND_FETCH_OBJ_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_PROP_OBJ; break; } } last_op->result_type = IS_TMP_VAR; last_op->extended_value |= type; GET_NODE(result, last_op->result); } /* }}} */ void zend_do_instanceof(znode *result, const znode *expr, const znode *class_znode, int type TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline->opcode == ZEND_FETCH_CLASS) { opline->extended_value |= ZEND_FETCH_CLASS_NO_AUTOLOAD; } } if (expr->op_type == IS_CONST) { zend_error(E_COMPILE_ERROR, "instanceof expects an object instance, constant given"); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INSTANCEOF; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_NODE(opline->op2, class_znode); GET_NODE(result, opline->result); } /* }}} */ void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_bool is_variable; zend_bool push_container = 0; zend_op dummy_opline; if (variable) { if (zend_is_function_or_method_call(array)) { is_variable = 0; } else { is_variable = 1; } /* save the location of FETCH_W instruction(s) */ open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); zend_do_end_variable_parse(array, BP_VAR_W, 0 TSRMLS_CC); if (CG(active_op_array)->last > 0 && CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) { /* Only lock the container if we are fetching from a real container and not $this */ if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1_type == IS_VAR) { CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK; push_container = 1; } } } else { is_variable = 0; open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* save the location of FE_RESET */ foreach_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* Preform array reset */ opline->opcode = ZEND_FE_RESET; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, array); SET_UNUSED(opline->op2); opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0; COPY_NODE(dummy_opline.result, opline->result); if (push_container) { COPY_NODE(dummy_opline.op1, CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1); } else { dummy_opline.op1_type = IS_UNUSED; } zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); /* save the location of FE_FETCH */ as_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FE_FETCH; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); COPY_NODE(opline->op1, dummy_opline.result); opline->extended_value = 0; SET_UNUSED(opline->op2); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_OP_DATA; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); } /* }}} */ void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC) /* {{{ */ { zend_op *opline; znode dummy, value_node; zend_bool assign_by_ref=0; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num]; if (key->op_type != IS_UNUSED) { znode *tmp; /* switch between the key and value... */ tmp = key; key = value; value = tmp; /* Mark extended_value in case both key and value are being used */ opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; } if ((key->op_type != IS_UNUSED) && (key->EA & ZEND_PARSED_REFERENCE_VARIABLE)) { zend_error(E_COMPILE_ERROR, "Key element cannot be a reference"); } if (value->EA & ZEND_PARSED_REFERENCE_VARIABLE) { assign_by_ref = 1; if (!(opline-1)->extended_value) { zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression"); } /* Mark extended_value for assign-by-reference */ opline->extended_value |= ZEND_FE_FETCH_BYREF; CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; } else { zend_op *foreach_copy; zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.op.opline_num]; zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.op.opline_num]; /* Change "write context" into "read context" */ fetch->extended_value = 0; /* reset ZEND_FE_RESET_VARIABLE */ while (fetch != end) { --fetch; if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } if (fetch->opcode == ZEND_SEPARATE) { MAKE_NOP(fetch); } else { fetch->opcode -= 3; /* FETCH_W -> FETCH_R */ } } /* prevent double SWITCH_FREE */ zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy); foreach_copy->op1_type = IS_UNUSED; } GET_NODE(&value_node, opline->result); if (assign_by_ref) { zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); /* Mark FE_FETCH as IS_VAR as it holds the data directly as a value */ zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC); } else { zend_do_assign(&dummy, value, &value_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } if (key->op_type != IS_UNUSED) { znode key_node; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num+1]; opline->result_type = IS_TMP_VAR; opline->result.opline_num = get_temporary_variable(CG(active_op_array)); GET_NODE(&key_node, opline->result); zend_do_assign(&dummy, key, &key_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_foreach_end(const znode *foreach_token, const znode *as_token TSRMLS_DC) /* {{{ */ { zend_op *container_ptr; zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = as_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_RESET */ CG(active_op_array)->opcodes[as_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_FETCH */ do_end_loop(as_token->u.op.opline_num, 1 TSRMLS_CC); zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr); generate_free_foreach_copy(container_ptr TSRMLS_CC); zend_stack_del_top(&CG(foreach_copy_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_declare_begin(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(declare_stack), &CG(declarables), sizeof(zend_declarables)); } /* }}} */ void zend_do_declare_stmt(znode *var, znode *val TSRMLS_DC) /* {{{ */ { if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "ticks", sizeof("ticks")-1)) { convert_to_long(&val->u.constant); CG(declarables).ticks = val->u.constant; } else if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "encoding", sizeof("encoding")-1)) { if ((Z_TYPE(val->u.constant) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Cannot use constants as encoding"); } /* * Check that the pragma comes before any opcodes. If the compilation * got as far as this, the previous portion of the script must have been * parseable according to the .ini script_encoding setting. We still * want to tell them to put declare() at the top. */ { int num = CG(active_op_array)->last; /* ignore ZEND_EXT_STMT and ZEND_TICKS */ while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Encoding declaration pragma must be the very first statement in the script"); } } if (CG(multibyte)) { const zend_encoding *new_encoding, *old_encoding; zend_encoding_filter old_input_filter; CG(encoding_declared) = 1; convert_to_string(&val->u.constant); new_encoding = zend_multibyte_fetch_encoding(val->u.constant.value.str.val TSRMLS_CC); if (!new_encoding) { zend_error(E_COMPILE_WARNING, "Unsupported encoding [%s]", val->u.constant.value.str.val); } else { old_input_filter = LANG_SCNG(input_filter); old_encoding = LANG_SCNG(script_encoding); zend_multibyte_set_filter(new_encoding TSRMLS_CC); /* need to re-scan if input filter changed */ if (old_input_filter != LANG_SCNG(input_filter) || (old_input_filter && new_encoding != old_encoding)) { zend_multibyte_yyinput_again(old_input_filter, old_encoding TSRMLS_CC); } } } else { zend_error(E_COMPILE_WARNING, "declare(encoding=...) ignored because Zend multibyte feature is turned off by settings"); } zval_dtor(&val->u.constant); } else { zend_error(E_COMPILE_WARNING, "Unsupported declare '%s'", var->u.constant.value.str.val); zval_dtor(&val->u.constant); } zval_dtor(&var->u.constant); } /* }}} */ void zend_do_declare_end(const znode *declare_token TSRMLS_DC) /* {{{ */ { zend_declarables *declarables; zend_stack_top(&CG(declare_stack), (void **) &declarables); /* We should restore if there was more than (current - start) - (ticks?1:0) opcodes */ if ((get_next_op_number(CG(active_op_array)) - declare_token->u.op.opline_num) - ((Z_LVAL(CG(declarables).ticks))?1:0)) { CG(declarables) = *declarables; } } /* }}} */ void zend_do_exit(znode *result, const znode *message TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXIT; SET_NODE(opline->op1, message); SET_UNUSED(opline->op2); result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_BOOL; Z_LVAL(result->u.constant) = 1; } /* }}} */ void zend_do_begin_silence(znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BEGIN_SILENCE; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); GET_NODE(strudel_token, opline->result); } /* }}} */ void zend_do_end_silence(const znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_END_SILENCE; SET_NODE(opline->op1, strudel_token); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_jmp_set(const znode *value, znode *jmp_token, znode *colon_token TSRMLS_DC) /* {{{ */ { int op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (value->op_type == IS_VAR || value->op_type == IS_CV) { opline->opcode = ZEND_JMP_SET_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_JMP_SET; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, value); SET_UNUSED(opline->op2); GET_NODE(colon_token, opline->result); jmp_token->u.op.opline_num = op_number; INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_jmp_set_else(znode *result, const znode *false_value, const znode *jmp_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, colon_token); if (colon_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].opcode = ZEND_JMP_SET_VAR; CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } opline->extended_value = 0; SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_qm_op(const znode *cond, znode *qm_token TSRMLS_DC) /* {{{ */ { int jmpz_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); SET_UNUSED(opline->op2); opline->op2.opline_num = jmpz_op_number; GET_NODE(qm_token, opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_qm_true(const znode *true_value, znode *qm_token, znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->opcodes[qm_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array))+1; /* jmp over the ZEND_JMP */ if (true_value->op_type == IS_VAR || true_value->op_type == IS_CV) { opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, true_value); SET_UNUSED(opline->op2); GET_NODE(qm_token, opline->result); colon_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_qm_false(znode *result, const znode *false_value, const znode *qm_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, qm_token); if (qm_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].opcode = ZEND_QM_ASSIGN_VAR; CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[colon_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, opline->result); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_extended_info(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_STMT; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_begin(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_BEGIN; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_end(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_END; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_ticks(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_TICKS; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->extended_value = Z_LVAL(CG(declarables).ticks); } /* }}} */ zend_bool zend_is_auto_global_quick(const char *name, uint name_len, ulong hashval TSRMLS_DC) /* {{{ */ { zend_auto_global *auto_global; ulong hash = hashval ? hashval : zend_hash_func(name, name_len+1); if (zend_hash_quick_find(CG(auto_globals), name, name_len+1, hash, (void **) &auto_global)==SUCCESS) { if (auto_global->armed) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } return 1; } return 0; } /* }}} */ zend_bool zend_is_auto_global(const char *name, uint name_len TSRMLS_DC) /* {{{ */ { return zend_is_auto_global_quick(name, name_len, 0 TSRMLS_CC); } /* }}} */ int zend_register_auto_global(const char *name, uint name_len, zend_bool jit, zend_auto_global_callback auto_global_callback TSRMLS_DC) /* {{{ */ { zend_auto_global auto_global; auto_global.name = zend_new_interned_string((char*)name, name_len + 1, 0 TSRMLS_CC); auto_global.name_len = name_len; auto_global.auto_global_callback = auto_global_callback; auto_global.jit = jit; return zend_hash_add(CG(auto_globals), name, name_len+1, &auto_global, sizeof(zend_auto_global), NULL); } /* }}} */ static int zend_auto_global_init(zend_auto_global *auto_global TSRMLS_DC) /* {{{ */ { if (auto_global->jit) { auto_global->armed = 1; } else if (auto_global->auto_global_callback) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } else { auto_global->armed = 0; } return 0; } /* }}} */ ZEND_API void zend_activate_auto_globals(TSRMLS_D) /* {{{ */ { zend_hash_apply(CG(auto_globals), (apply_func_t) zend_auto_global_init TSRMLS_CC); } /* }}} */ int zendlex(znode *zendlval TSRMLS_DC) /* {{{ */ { int retval; if (CG(increment_lineno)) { CG(zend_lineno)++; CG(increment_lineno) = 0; } again: Z_TYPE(zendlval->u.constant) = IS_LONG; retval = lex_scan(&zendlval->u.constant TSRMLS_CC); switch (retval) { case T_COMMENT: case T_DOC_COMMENT: case T_OPEN_TAG: case T_WHITESPACE: goto again; case T_CLOSE_TAG: if (LANG_SCNG(yy_text)[LANG_SCNG(yy_leng)-1] != '>') { CG(increment_lineno) = 1; } if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { goto again; } retval = ';'; /* implicit ; */ break; case T_OPEN_TAG_WITH_ECHO: retval = T_ECHO; break; case T_END_HEREDOC: efree(Z_STRVAL(zendlval->u.constant)); break; } INIT_PZVAL(&zendlval->u.constant); zendlval->op_type = IS_CONST; return retval; } /* }}} */ ZEND_API void zend_initialize_class_data(zend_class_entry *ce, zend_bool nullify_handlers TSRMLS_DC) /* {{{ */ { zend_bool persistent_hashes = (ce->type == ZEND_INTERNAL_CLASS) ? 1 : 0; dtor_func_t zval_ptr_dtor_func = ((persistent_hashes) ? ZVAL_INTERNAL_PTR_DTOR : ZVAL_PTR_DTOR); ce->refcount = 1; ce->ce_flags = 0; ce->default_properties_table = NULL; ce->default_static_members_table = NULL; zend_hash_init_ex(&ce->properties_info, 0, NULL, (dtor_func_t) (persistent_hashes ? zend_destroy_property_info_internal : zend_destroy_property_info), persistent_hashes, 0); zend_hash_init_ex(&ce->constants_table, 0, NULL, zval_ptr_dtor_func, persistent_hashes, 0); zend_hash_init_ex(&ce->function_table, 0, NULL, ZEND_FUNCTION_DTOR, persistent_hashes, 0); if (ce->type == ZEND_INTERNAL_CLASS) { #ifdef ZTS int n = zend_hash_num_elements(CG(class_table)); if (CG(static_members_table) && n >= CG(last_static_member)) { /* Support for run-time declaration: dl() */ CG(last_static_member) = n+1; CG(static_members_table) = realloc(CG(static_members_table), (n+1)*sizeof(zval**)); CG(static_members_table)[n] = NULL; } ce->static_members_table = (zval**)(zend_intptr_t)n; #else ce->static_members_table = NULL; #endif } else { ce->static_members_table = ce->default_static_members_table; ce->info.user.doc_comment = NULL; ce->info.user.doc_comment_len = 0; } ce->default_properties_count = 0; ce->default_static_members_count = 0; if (nullify_handlers) { ce->constructor = NULL; ce->destructor = NULL; ce->clone = NULL; ce->__get = NULL; ce->__set = NULL; ce->__unset = NULL; ce->__isset = NULL; ce->__call = NULL; ce->__callstatic = NULL; ce->__tostring = NULL; ce->create_object = NULL; ce->get_iterator = NULL; ce->iterator_funcs.funcs = NULL; ce->interface_gets_implemented = NULL; ce->get_static_method = NULL; ce->parent = NULL; ce->num_interfaces = 0; ce->interfaces = NULL; ce->num_traits = 0; ce->traits = NULL; ce->trait_aliases = NULL; ce->trait_precedences = NULL; ce->serialize = NULL; ce->unserialize = NULL; ce->serialize_func = NULL; ce->unserialize_func = NULL; if (ce->type == ZEND_INTERNAL_CLASS) { ce->info.internal.module = NULL; ce->info.internal.builtin_functions = NULL; } } } /* }}} */ int zend_get_class_fetch_type(const char *class_name, uint class_name_len) /* {{{ */ { if ((class_name_len == sizeof("self")-1) && !memcmp(class_name, "self", sizeof("self")-1)) { return ZEND_FETCH_CLASS_SELF; } else if ((class_name_len == sizeof("parent")-1) && !memcmp(class_name, "parent", sizeof("parent")-1)) { return ZEND_FETCH_CLASS_PARENT; } else if ((class_name_len == sizeof("static")-1) && !memcmp(class_name, "static", sizeof("static")-1)) { return ZEND_FETCH_CLASS_STATIC; } else { return ZEND_FETCH_CLASS_DEFAULT; } } /* }}} */ ZEND_API const char* zend_get_compiled_variable_name(const zend_op_array *op_array, zend_uint var, int* name_len) /* {{{ */ { if (name_len) { *name_len = op_array->vars[var].name_len; } return op_array->vars[var].name; } /* }}} */ void zend_do_build_namespace_name(znode *result, znode *prefix, znode *name TSRMLS_DC) /* {{{ */ { if (prefix) { *result = *prefix; if (Z_TYPE(result->u.constant) == IS_STRING && Z_STRLEN(result->u.constant) == 0) { /* namespace\ */ if (CG(current_namespace)) { znode tmp; zval_dtor(&result->u.constant); tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(result, NULL, &tmp TSRMLS_CC); } } } else { result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_STRING; Z_STRVAL(result->u.constant) = NULL; Z_STRLEN(result->u.constant) = 0; } /* prefix = result */ zend_do_build_full_name(NULL, result, name, 0 TSRMLS_CC); } /* }}} */ void zend_do_begin_namespace(const znode *name, zend_bool with_bracket TSRMLS_DC) /* {{{ */ { char *lcname; /* handle mixed syntax declaration or nested namespaces */ if (!CG(has_bracketed_namespaces)) { if (CG(current_namespace)) { /* previous namespace declarations were unbracketed */ if (with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } } } else { /* previous namespace declarations were bracketed */ if (!with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } else if (CG(current_namespace) || CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "Namespace declarations cannot be nested"); } } if (((!with_bracket && !CG(current_namespace)) || (with_bracket && !CG(has_bracketed_namespaces))) && CG(active_op_array)->last > 0) { /* ignore ZEND_EXT_STMT and ZEND_TICKS */ int num = CG(active_op_array)->last; while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Namespace declaration statement has to be the very first statement in the script"); } } CG(in_namespace) = 1; if (with_bracket) { CG(has_bracketed_namespaces) = 1; } if (name) { lcname = zend_str_tolower_dup(Z_STRVAL(name->u.constant), Z_STRLEN(name->u.constant)); if (((Z_STRLEN(name->u.constant) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN(name->u.constant) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as namespace name", Z_STRVAL(name->u.constant)); } efree(lcname); if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); } else { ALLOC_ZVAL(CG(current_namespace)); } *CG(current_namespace) = name->u.constant; } else { if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_use(znode *ns_name, znode *new_name, int is_global TSRMLS_DC) /* {{{ */ { char *lcname; zval *name, *ns, tmp; zend_bool warn = 0; zend_class_entry **pce; if (!CG(current_import)) { CG(current_import) = emalloc(sizeof(HashTable)); zend_hash_init(CG(current_import), 0, NULL, ZVAL_PTR_DTOR, 0); } ALLOC_ZVAL(ns); *ns = ns_name->u.constant; if (new_name) { name = &new_name->u.constant; } else { const char *p; /* The form "use A\B" is eqivalent to "use A\B as B". So we extract the last part of compound name to use as a new_name */ name = &tmp; p = zend_memrchr(Z_STRVAL_P(ns), '\\', Z_STRLEN_P(ns)); if (p) { ZVAL_STRING(name, p+1, 1); } else { *name = *ns; zval_copy_ctor(name); warn = !is_global && !CG(current_namespace); } } lcname = zend_str_tolower_dup(Z_STRVAL_P(name), Z_STRLEN_P(name)); if (((Z_STRLEN_P(name) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN_P(name) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because '%s' is a special class name", Z_STRVAL_P(ns), Z_STRVAL_P(name), Z_STRVAL_P(name)); } if (CG(current_namespace)) { /* Prefix import name with current namespace name to avoid conflicts with classes */ char *c_ns_name = emalloc(Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) + 1); zend_str_tolower_copy(c_ns_name, Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); c_ns_name[Z_STRLEN_P(CG(current_namespace))] = '\\'; memcpy(c_ns_name+Z_STRLEN_P(CG(current_namespace))+1, lcname, Z_STRLEN_P(name)+1); if (zend_hash_exists(CG(class_table), c_ns_name, Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name)+1)) { char *tmp2 = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) || memcmp(tmp2, c_ns_name, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(tmp2); } efree(c_ns_name); } else if (zend_hash_find(CG(class_table), lcname, Z_STRLEN_P(name)+1, (void**)&pce) == SUCCESS && (*pce)->type == ZEND_USER_CLASS && (*pce)->info.user.filename == CG(compiled_filename)) { char *c_tmp = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(name) || memcmp(c_tmp, lcname, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(c_tmp); } if (zend_hash_add(CG(current_import), lcname, Z_STRLEN_P(name)+1, &ns, sizeof(zval*), NULL) != SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } if (warn) { if (!strcmp(Z_STRVAL_P(name), "strict")) { zend_error(E_COMPILE_ERROR, "You seem to be trying to use a different language..."); } zend_error(E_WARNING, "The use statement with non-compound name '%s' has no effect", Z_STRVAL_P(name)); } efree(lcname); zval_dtor(name); } /* }}} */ void zend_do_declare_constant(znode *name, znode *value TSRMLS_DC) /* {{{ */ { zend_op *opline; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed as constants"); } if (zend_get_ct_const(&name->u.constant, 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare constant '%s'", Z_STRVAL(name->u.constant)); } if (CG(current_namespace)) { /* Prefix constant name with name of current namespace, lowercased */ znode tmp; tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); Z_STRVAL(tmp.u.constant) = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), Z_STRLEN(tmp.u.constant)); zend_do_build_namespace_name(&tmp, &tmp, name TSRMLS_CC); *name = tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DECLARE_CONST; SET_UNUSED(opline->result); SET_NODE(opline->op1, name); SET_NODE(opline->op2, value); } /* }}} */ void zend_verify_namespace(TSRMLS_D) /* {{{ */ { if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "No code may exist outside of namespace {}"); } } /* }}} */ void zend_do_end_namespace(TSRMLS_D) /* {{{ */ { CG(in_namespace) = 0; if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_end_compilation(TSRMLS_D) /* {{{ */ { CG(has_bracketed_namespaces) = 0; zend_do_end_namespace(TSRMLS_C); } /* }}} */ /* {{{ zend_dirname Returns directory name component of path */ ZEND_API size_t zend_dirname(char *path, size_t len) { register char *end = path + len - 1; unsigned int len_adjust = 0; #ifdef PHP_WIN32 /* Note that on Win32 CWD is per drive (heritage from CP/M). * This means dirname("c:foo") maps to "c:." or "c:" - which means CWD on C: drive. */ if ((2 <= len) && isalpha((int)((unsigned char *)path)[0]) && (':' == path[1])) { /* Skip over the drive spec (if any) so as not to change */ path += 2; len_adjust += 2; if (2 == len) { /* Return "c:" on Win32 for dirname("c:"). * It would be more consistent to return "c:." * but that would require making the string *longer*. */ return len; } } #elif defined(NETWARE) /* * Find the first occurence of : from the left * move the path pointer to the position just after : * increment the len_adjust to the length of path till colon character(inclusive) * If there is no character beyond : simple return len */ char *colonpos = NULL; colonpos = strchr(path, ':'); if (colonpos != NULL) { len_adjust = ((colonpos - path) + 1); path += len_adjust; if (len_adjust == len) { return len; } } #endif if (len == 0) { /* Illegal use of this function */ return 0; } /* Strip trailing slashes */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { /* The path only contained slashes */ path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } /* Strip filename */ while (end >= path && !IS_SLASH_P(end)) { end--; } if (end < path) { /* No slash found, therefore return '.' */ #ifdef NETWARE if (len_adjust == 0) { path[0] = '.'; path[1] = '\0'; return 1; /* only one character */ } else { path[0] = '\0'; return len_adjust; } #else path[0] = '.'; path[1] = '\0'; return 1 + len_adjust; #endif } /* Strip slashes which came before the file name */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } *(end+1) = '\0'; return (size_t)(end + 1 - path) + len_adjust; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */ /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2012 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <zend_language_parser.h> #include "zend.h" #include "zend_compile.h" #include "zend_constants.h" #include "zend_llist.h" #include "zend_API.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "zend_multibyte.h" #include "zend_language_scanner.h" #define CONSTANT_EX(op_array, op) \ (op_array)->literals[op].constant #define CONSTANT(op) \ CONSTANT_EX(CG(active_op_array), op) #define SET_NODE(target, src) do { \ target ## _type = (src)->op_type; \ if ((src)->op_type == IS_CONST) { \ target.constant = zend_add_literal(CG(active_op_array), &(src)->u.constant TSRMLS_CC); \ } else { \ target = (src)->u.op; \ } \ } while (0) #define GET_NODE(target, src) do { \ (target)->op_type = src ## _type; \ if ((target)->op_type == IS_CONST) { \ (target)->u.constant = CONSTANT(src.constant); \ } else { \ (target)->u.op = src; \ (target)->EA = 0; \ } \ } while (0) #define COPY_NODE(target, src) do { \ target ## _type = src ## _type; \ target = src; \ } while (0) #define CALCULATE_LITERAL_HASH(num) do { \ if (IS_INTERNED(Z_STRVAL(CONSTANT(num)))) { \ Z_HASH_P(&CONSTANT(num)) = INTERNED_HASH(Z_STRVAL(CONSTANT(num))); \ } else { \ Z_HASH_P(&CONSTANT(num)) = zend_hash_func(Z_STRVAL(CONSTANT(num)), Z_STRLEN(CONSTANT(num))+1); \ } \ } while (0) #define GET_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot++; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ } \ } while (0) #define POLYMORPHIC_CACHE_SLOT_SIZE 2 #define GET_POLYMORPHIC_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot; \ CG(active_op_array)->last_cache_slot += POLYMORPHIC_CACHE_SLOT_SIZE; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 2] = NULL; \ } \ } while (0) #define FREE_POLYMORPHIC_CACHE_SLOT(literal) do { \ if (CG(active_op_array)->literals[literal].cache_slot != -1 && \ CG(active_op_array)->literals[literal].cache_slot == \ CG(active_op_array)->last_cache_slot - POLYMORPHIC_CACHE_SLOT_SIZE) { \ CG(active_op_array)->literals[literal].cache_slot = -1; \ CG(active_op_array)->last_cache_slot -= POLYMORPHIC_CACHE_SLOT_SIZE; \ } \ } while (0) ZEND_API zend_op_array *(*zend_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); ZEND_API zend_op_array *(*zend_compile_string)(zval *source_string, char *filename TSRMLS_DC); #ifndef ZTS ZEND_API zend_compiler_globals compiler_globals; ZEND_API zend_executor_globals executor_globals; #endif static void zend_duplicate_property_info(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = estrndup(property_info->name, property_info->name_length); } if (property_info->doc_comment) { property_info->doc_comment = estrndup(property_info->doc_comment, property_info->doc_comment_len); } } /* }}} */ static void zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = zend_strndup(property_info->name, property_info->name_length); } } /* }}} */ static void zend_destroy_property_info(zend_property_info *property_info) /* {{{ */ { str_efree(property_info->name); if (property_info->doc_comment) { efree((char*)property_info->doc_comment); } } /* }}} */ static void zend_destroy_property_info_internal(zend_property_info *property_info) /* {{{ */ { str_free((char*)property_info->name); } /* }}} */ static void build_runtime_defined_function_key(zval *result, const char *name, int name_length TSRMLS_DC) /* {{{ */ { char char_pos_buf[32]; uint char_pos_len; const char *filename; char_pos_len = zend_sprintf(char_pos_buf, "%p", LANG_SCNG(yy_text)); if (CG(active_op_array)->filename) { filename = CG(active_op_array)->filename; } else { filename = "-"; } /* NULL, name length, filename length, last accepting char position length */ result->value.str.len = 1+name_length+strlen(filename)+char_pos_len; /* must be binary safe */ result->value.str.val = (char *) safe_emalloc(result->value.str.len, 1, 1); result->value.str.val[0] = '\0'; sprintf(result->value.str.val+1, "%s%s%s", name, filename, char_pos_buf); result->type = IS_STRING; Z_SET_REFCOUNT_P(result, 1); } /* }}} */ static void init_compiler_declarables(TSRMLS_D) /* {{{ */ { Z_TYPE(CG(declarables).ticks) = IS_LONG; Z_LVAL(CG(declarables).ticks) = 0; } /* }}} */ void zend_init_compiler_context(TSRMLS_D) /* {{{ */ { CG(context).opcodes_size = (CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) ? INITIAL_INTERACTIVE_OP_ARRAY_SIZE : INITIAL_OP_ARRAY_SIZE; CG(context).vars_size = 0; CG(context).literals_size = 0; CG(context).current_brk_cont = -1; CG(context).backpatch_count = 0; CG(context).labels = NULL; } /* }}} */ void zend_init_compiler_data_structures(TSRMLS_D) /* {{{ */ { zend_stack_init(&CG(bp_stack)); zend_stack_init(&CG(function_call_stack)); zend_stack_init(&CG(switch_cond_stack)); zend_stack_init(&CG(foreach_copy_stack)); zend_stack_init(&CG(object_stack)); zend_stack_init(&CG(declare_stack)); CG(active_class_entry) = NULL; zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_stack_init(&CG(list_stack)); CG(in_compilation) = 0; CG(start_lineno) = 0; CG(current_namespace) = NULL; CG(in_namespace) = 0; CG(has_bracketed_namespaces) = 0; CG(current_import) = NULL; init_compiler_declarables(TSRMLS_C); zend_stack_init(&CG(context_stack)); CG(encoding_declared) = 0; } /* }}} */ ZEND_API void file_handle_dtor(zend_file_handle *fh) /* {{{ */ { TSRMLS_FETCH(); zend_file_handle_dtor(fh TSRMLS_CC); } /* }}} */ void init_compiler(TSRMLS_D) /* {{{ */ { CG(active_op_array) = NULL; zend_init_compiler_data_structures(TSRMLS_C); zend_init_rsrc_list(TSRMLS_C); zend_hash_init(&CG(filenames_table), 5, NULL, (dtor_func_t) free_estring, 0); zend_llist_init(&CG(open_files), sizeof(zend_file_handle), (void (*)(void *)) file_handle_dtor, 0); CG(unclean_shutdown) = 0; } /* }}} */ void shutdown_compiler(TSRMLS_D) /* {{{ */ { zend_stack_destroy(&CG(bp_stack)); zend_stack_destroy(&CG(function_call_stack)); zend_stack_destroy(&CG(switch_cond_stack)); zend_stack_destroy(&CG(foreach_copy_stack)); zend_stack_destroy(&CG(object_stack)); zend_stack_destroy(&CG(declare_stack)); zend_stack_destroy(&CG(list_stack)); zend_hash_destroy(&CG(filenames_table)); zend_llist_destroy(&CG(open_files)); zend_stack_destroy(&CG(context_stack)); } /* }}} */ ZEND_API char *zend_set_compiled_filename(const char *new_compiled_filename TSRMLS_DC) /* {{{ */ { char **pp, *p; int length = strlen(new_compiled_filename); if (zend_hash_find(&CG(filenames_table), new_compiled_filename, length+1, (void **) &pp) == SUCCESS) { CG(compiled_filename) = *pp; return *pp; } p = estrndup(new_compiled_filename, length); zend_hash_update(&CG(filenames_table), new_compiled_filename, length+1, &p, sizeof(char *), (void **) &pp); CG(compiled_filename) = p; return p; } /* }}} */ ZEND_API void zend_restore_compiled_filename(char *original_compiled_filename TSRMLS_DC) /* {{{ */ { CG(compiled_filename) = original_compiled_filename; } /* }}} */ ZEND_API char *zend_get_compiled_filename(TSRMLS_D) /* {{{ */ { return CG(compiled_filename); } /* }}} */ ZEND_API int zend_get_compiled_lineno(TSRMLS_D) /* {{{ */ { return CG(zend_lineno); } /* }}} */ ZEND_API zend_bool zend_is_compiling(TSRMLS_D) /* {{{ */ { return CG(in_compilation); } /* }}} */ static zend_uint get_temporary_variable(zend_op_array *op_array) /* {{{ */ { return (op_array->T)++ * ZEND_MM_ALIGNED_SIZE(sizeof(temp_variable)); } /* }}} */ static int lookup_cv(zend_op_array *op_array, char* name, int name_len, ulong hash TSRMLS_DC) /* {{{ */ { int i = 0; ulong hash_value = hash ? hash : zend_inline_hash_func(name, name_len+1); while (i < op_array->last_var) { if (op_array->vars[i].name == name || (op_array->vars[i].hash_value == hash_value && op_array->vars[i].name_len == name_len && memcmp(op_array->vars[i].name, name, name_len) == 0)) { str_efree(name); return i; } i++; } i = op_array->last_var; op_array->last_var++; if (op_array->last_var > CG(context).vars_size) { CG(context).vars_size += 16; /* FIXME */ op_array->vars = erealloc(op_array->vars, CG(context).vars_size * sizeof(zend_compiled_variable)); } op_array->vars[i].name = zend_new_interned_string(name, name_len + 1, 1 TSRMLS_CC); op_array->vars[i].name_len = name_len; op_array->vars[i].hash_value = hash_value; return i; } /* }}} */ void zend_del_literal(zend_op_array *op_array, int n) /* {{{ */ { zval_dtor(&CONSTANT_EX(op_array, n)); if (n + 1 == op_array->last_literal) { op_array->last_literal--; } else { Z_TYPE(CONSTANT_EX(op_array, n)) = IS_NULL; } } /* }}} */ /* Common part of zend_add_literal and zend_append_individual_literal */ static inline void zend_insert_literal(zend_op_array *op_array, const zval *zv, int literal_position TSRMLS_DC) /* {{{ */ { if (Z_TYPE_P(zv) == IS_STRING || Z_TYPE_P(zv) == IS_CONSTANT) { zval *z = (zval*)zv; Z_STRVAL_P(z) = (char*)zend_new_interned_string(Z_STRVAL_P(zv), Z_STRLEN_P(zv) + 1, 1 TSRMLS_CC); } CONSTANT_EX(op_array, literal_position) = *zv; Z_SET_REFCOUNT(CONSTANT_EX(op_array, literal_position), 2); Z_SET_ISREF(CONSTANT_EX(op_array, literal_position)); op_array->literals[literal_position].hash_value = 0; op_array->literals[literal_position].cache_slot = -1; } /* }}} */ /* Is used while compiling a function, using the context to keep track of an approximate size to avoid to relocate to often. Literals are truncated to actual size in the second compiler pass (pass_two()). */ int zend_add_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; if (i >= CG(context).literals_size) { while (i >= CG(context).literals_size) { CG(context).literals_size += 16; /* FIXME */ } op_array->literals = (zend_literal*)erealloc(op_array->literals, CG(context).literals_size * sizeof(zend_literal)); } zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ /* Is used after normal compilation to append an additional literal. Allocation is done precisely here. */ int zend_append_individual_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; op_array->literals = (zend_literal*)erealloc(op_array->literals, (i + 1) * sizeof(zend_literal)); zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ int zend_add_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_ns_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; const char *ns_separator; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); ns_separator = (const char*)zend_memrchr(Z_STRVAL_P(zv), '\\', Z_STRLEN_P(zv)) + 1; lc_len = Z_STRLEN_P(zv) - (ns_separator - Z_STRVAL_P(zv)); lc_name = zend_str_tolower_dup(ns_separator, lc_len); ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_class_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } if (Z_STRVAL_P(zv)[0] == '\\') { lc_len = Z_STRLEN_P(zv) - 1; lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv) + 1, lc_len); } else { lc_len = Z_STRLEN_P(zv); lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), lc_len); } ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); GET_CACHE_SLOT(ret); return ret; } /* }}} */ int zend_add_const_name_literal(zend_op_array *op_array, const zval *zv, int unqualified TSRMLS_DC) /* {{{ */ { int ret, tmp_literal; char *name, *tmp_name; const char *ns_separator; int name_len, ns_len; zval c; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } /* skip leading '\\' */ if (Z_STRVAL_P(zv)[0] == '\\') { name_len = Z_STRLEN_P(zv) - 1; name = Z_STRVAL_P(zv) + 1; } else { name_len = Z_STRLEN_P(zv); name = Z_STRVAL_P(zv); } ns_separator = zend_memrchr(name, '\\', name_len); if (ns_separator) { ns_len = ns_separator - name; } else { ns_len = 0; } if (ns_len) { /* lowercased namespace name & original constant name */ tmp_name = estrndup(name, name_len); zend_str_tolower(tmp_name, ns_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased namespace name & lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); } if (ns_len) { if (!unqualified) { return ret; } ns_len++; name += ns_len; name_len -= ns_len; } /* original constant name */ tmp_name = estrndup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); return ret; } /* }}} */ #define LITERAL_STRINGL(op, str, len, copy) do { \ zval _c; \ ZVAL_STRINGL(&_c, str, len, copy); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG(op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG_EX(op_array, op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(op_array, &_c TSRMLS_CC); \ } while (0) #define LITERAL_NULL(op) do { \ zval _c; \ INIT_ZVAL( _c); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) static inline zend_bool zend_is_function_or_method_call(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; return ((type & ZEND_PARSED_METHOD_CALL) || (type == ZEND_PARSED_FUNCTION_CALL)); } /* }}} */ void zend_do_binary_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_unary_op(zend_uchar op, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); GET_NODE(result, opline->result); SET_UNUSED(opline->op2); } /* }}} */ #define MAKE_NOP(opline) { opline->opcode = ZEND_NOP; memset(&opline->result,0,sizeof(opline->result)); memset(&opline->op1,0,sizeof(opline->op1)); memset(&opline->op2,0,sizeof(opline->op2)); opline->result_type=opline->op1_type=opline->op2_type=IS_UNUSED; } static void zend_do_op_data(zend_op *data_op, const znode *value TSRMLS_DC) /* {{{ */ { data_op->opcode = ZEND_OP_DATA; SET_NODE(data_op->op1, value); SET_UNUSED(data_op->op2); } /* }}} */ void zend_do_binary_assign_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; switch (last_op->opcode) { case ZEND_FETCH_OBJ_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, op2 TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; case ZEND_FETCH_DIM_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_DIM; zend_do_op_data(opline, op2 TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result,last_op->result); return; default: break; } } opline->opcode = op; SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void fetch_simple_variable_ex(znode *result, znode *varname, int bp, zend_uchar op TSRMLS_DC) /* {{{ */ { zend_op opline; zend_op *opline_ptr; zend_llist *fetch_list_ptr; if (varname->op_type == IS_CONST) { ulong hash = 0; if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } else if (IS_INTERNED(Z_STRVAL(varname->u.constant))) { hash = INTERNED_HASH(Z_STRVAL(varname->u.constant)); } if (!zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC) && !(varname->u.constant.value.str.len == (sizeof("this")-1) && !memcmp(varname->u.constant.value.str.val, "this", sizeof("this"))) && (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE)) { result->op_type = IS_CV; result->u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC); varname->u.constant.value.str.val = (char*)CG(active_op_array)->vars[result->u.op.var].name; result->EA = 0; return; } } if (bp) { opline_ptr = &opline; init_op(opline_ptr TSRMLS_CC); } else { opline_ptr = get_next_op(CG(active_op_array) TSRMLS_CC); } opline_ptr->opcode = op; opline_ptr->result_type = IS_VAR; opline_ptr->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline_ptr->op1, varname); GET_NODE(result, opline_ptr->result); SET_UNUSED(opline_ptr->op2); opline_ptr->extended_value = ZEND_FETCH_LOCAL; if (varname->op_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline_ptr->op1.constant); if (zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC)) { opline_ptr->extended_value = ZEND_FETCH_GLOBAL; } } if (bp) { zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); zend_llist_add_element(fetch_list_ptr, opline_ptr); } } /* }}} */ void fetch_simple_variable(znode *result, znode *varname, int bp TSRMLS_DC) /* {{{ */ { /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ fetch_simple_variable_ex(result, varname, bp, ZEND_FETCH_W TSRMLS_CC); } /* }}} */ void zend_do_fetch_static_member(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { znode class_node; zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline_ptr; zend_op opline; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); } zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (result->op_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[result->u.op.var].name), CG(active_op_array)->vars[result->u.op.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } GET_NODE(result,opline.result); opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; opline_ptr = &opline; zend_llist_add_element(fetch_list_ptr, &opline); } else { le = fetch_list_ptr->head; opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode != ZEND_FETCH_W && opline_ptr->op1_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[opline_ptr->op1.var].name), CG(active_op_array)->vars[opline_ptr->op1.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; COPY_NODE(opline_ptr->op1, opline.result); zend_llist_prepend_element(fetch_list_ptr, &opline); } else { if (opline_ptr->op1_type == IS_CONST) { GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op1.constant); } if (class_node.op_type == IS_CONST) { opline_ptr->op2_type = IS_CONST; opline_ptr->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline_ptr->op2, &class_node); } opline_ptr->extended_value |= ZEND_FETCH_STATIC_MEMBER; } } } /* }}} */ void fetch_array_begin(znode *result, znode *varname, znode *first_dim TSRMLS_DC) /* {{{ */ { fetch_simple_variable(result, varname, 1 TSRMLS_CC); fetch_array_dim(result, result, first_dim TSRMLS_CC); } /* }}} */ void fetch_array_dim(znode *result, const znode *parent, const znode *dim TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (zend_is_function_or_method_call(parent)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, parent); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_DIM_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, parent); SET_NODE(opline.op2, dim); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline.op2.constant)), Z_STRLEN(CONSTANT(opline.op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline.op2.constant)); ZVAL_LONG(&CONSTANT(opline.op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline.op2.constant); } } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void fetch_string_offset(znode *result, const znode *parent, const znode *offset TSRMLS_DC) /* {{{ */ { fetch_array_dim(result, parent, offset TSRMLS_CC); } /* }}} */ void zend_do_print(znode *result, const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->opcode = ZEND_PRINT; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_echo(const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ECHO; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_abstract_method(const znode *function_name, znode *modifiers, const znode *body TSRMLS_DC) /* {{{ */ { char *method_type; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { Z_LVAL(modifiers->u.constant) |= ZEND_ACC_ABSTRACT; method_type = "Interface"; } else { method_type = "Abstract"; } if (modifiers->u.constant.value.lval & ZEND_ACC_ABSTRACT) { if(modifiers->u.constant.value.lval & ZEND_ACC_PRIVATE) { zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot be declared private", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } if (Z_LVAL(body->u.constant) == ZEND_ACC_ABSTRACT) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_RAISE_ABSTRACT_ERROR; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } else { /* we had code in the function body */ zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot contain body", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } else { if (body->u.constant.value.lval == ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Non-abstract method %s::%s() must contain body", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } } /* }}} */ static zend_bool opline_is_fetch_this(const zend_op *opline TSRMLS_DC) /* {{{ */ { if ((opline->opcode == ZEND_FETCH_W) && (opline->op1_type == IS_CONST) && (Z_TYPE(CONSTANT(opline->op1.constant)) == IS_STRING) && (Z_HASH_P(&CONSTANT(opline->op1.constant)) == THIS_HASHVAL) && (Z_STRLEN(CONSTANT(opline->op1.constant)) == (sizeof("this")-1)) && !memcmp(Z_STRVAL(CONSTANT(opline->op1.constant)), "this", sizeof("this"))) { return 1; } else { return 0; } } /* }}} */ void zend_do_assign(znode *result, znode *variable, znode *value TSRMLS_DC) /* {{{ */ { int last_op_number; zend_op *opline; if (value->op_type == IS_CV) { zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (fetch_list_ptr && fetch_list_ptr->head) { opline = (zend_op *)fetch_list_ptr->head->data; if (opline->opcode == ZEND_FETCH_DIM_W && opline->op1_type == IS_CV && opline->op1.var == value->u.op.var) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_R; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->op1_type = IS_CONST; LITERAL_STRINGL(opline->op1, CG(active_op_array)->vars[value->u.op.var].name, CG(active_op_array)->vars[value->u.op.var].name_len, 1); CALCULATE_LITERAL_HASH(opline->op1.constant); SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_LOCAL; GET_NODE(value, opline->result); } } } zend_do_end_variable_parse(variable, BP_VAR_W, 0 TSRMLS_CC); last_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (variable->op_type == IS_CV) { if (variable->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (variable->op_type == IS_VAR) { int n = 0; while (last_op_number - n > 0) { zend_op *last_op; last_op = &CG(active_op_array)->opcodes[last_op_number-n-1]; if (last_op->result_type == IS_VAR && last_op->result.var == variable->u.op.var) { if (last_op->opcode == ZEND_FETCH_OBJ_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, value TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (last_op->opcode == ZEND_FETCH_DIM_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ /* TBFixed: this can realloc opcodes, leaving last_op pointing wrong */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_DIM; zend_do_op_data(opline, value TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (opline_is_fetch_this(last_op TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } else { break; } } n++; } } opline->opcode = ZEND_ASSIGN; SET_NODE(opline->op1, variable); SET_NODE(opline->op2, value); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_assign_ref(znode *result, const znode *lvar, const znode *rvar TSRMLS_DC) /* {{{ */ { zend_op *opline; if (lvar->op_type == IS_CV) { if (lvar->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (lvar->op_type == IS_VAR) { int last_op_number = get_next_op_number(CG(active_op_array)); if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline_is_fetch_this(opline TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ASSIGN_REF; if (zend_is_function_or_method_call(rvar)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } else if (rvar->EA & ZEND_PARSED_NEW) { opline->extended_value = ZEND_RETURNS_NEW; } else { opline->extended_value = 0; } if (result) { opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } else { opline->result_type = IS_UNUSED | EXT_TYPE_UNUSED; } SET_NODE(opline->op1, lvar); SET_NODE(opline->op2, rvar); } /* }}} */ static inline void do_begin_loop(TSRMLS_D) /* {{{ */ { zend_brk_cont_element *brk_cont_element; int parent; parent = CG(context).current_brk_cont; CG(context).current_brk_cont = CG(active_op_array)->last_brk_cont; brk_cont_element = get_next_brk_cont_element(CG(active_op_array)); brk_cont_element->start = get_next_op_number(CG(active_op_array)); brk_cont_element->parent = parent; } /* }}} */ static inline void do_end_loop(int cont_addr, int has_loop_var TSRMLS_DC) /* {{{ */ { if (!has_loop_var) { /* The start fileld is used to free temporary variables in case of exceptions. * We won't try to free something of we don't have loop variable. */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].start = -1; } CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = cont_addr; CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; } /* }}} */ void zend_do_while_cond(const znode *expr, znode *close_bracket_token TSRMLS_DC) /* {{{ */ { int while_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, expr); close_bracket_token->u.op.opline_num = while_cond_op_number; SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_while_end(const znode *while_token, const znode *close_bracket_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* add unconditional jump */ opline->opcode = ZEND_JMP; opline->op1.opline_num = while_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* update while's conditional jmp */ CG(active_op_array)->opcodes[close_bracket_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); do_end_loop(while_token->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_cond(const znode *expr, znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { int for_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZNZ; SET_NODE(opline->op1, expr); /* the conditional expression */ second_semicolon_token->u.op.opline_num = for_cond_op_number; SET_UNUSED(opline->op2); } /* }}} */ void zend_do_for_before_statement(const znode *cond_start, const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = cond_start->u.op.opline_num; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_end(const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = second_semicolon_token->u.op.opline_num+1; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_end_loop(second_semicolon_token->u.op.opline_num+1, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_pre_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_PRE_INC)?ZEND_PRE_INC_OBJ:ZEND_PRE_DEC_OBJ; last_op->result_type = IS_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_post_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_POST_INC)?ZEND_POST_INC_OBJ:ZEND_POST_DEC_OBJ; last_op->result_type = IS_TMP_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_if_cond(const znode *cond, znode *closing_bracket_token TSRMLS_DC) /* {{{ */ { int if_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); closing_bracket_token->u.op.opline_num = if_cond_op_number; SET_UNUSED(opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_if_after_statement(const znode *closing_bracket_token, unsigned char initialize TSRMLS_DC) /* {{{ */ { int if_end_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; /* save for backpatching */ if (initialize) { zend_llist jmp_list; zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); } zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &if_end_op_number); CG(active_op_array)->opcodes[closing_bracket_token->u.op.opline_num].op2.opline_num = if_end_op_number+1; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_if_end(TSRMLS_D) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_llist *jmp_list_ptr; zend_llist_element *le; zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); for (le=jmp_list_ptr->head; le; le = le->next) { CG(active_op_array)->opcodes[*((int *) le->data)].op1.opline_num = next_op_number; } zend_llist_destroy(jmp_list_ptr); zend_stack_del_top(&CG(bp_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_check_writable_variable(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; if (type & ZEND_PARSED_METHOD_CALL) { zend_error(E_COMPILE_ERROR, "Can't use method return value in write context"); } if (type == ZEND_PARSED_FUNCTION_CALL) { zend_error(E_COMPILE_ERROR, "Can't use function return value in write context"); } } /* }}} */ void zend_do_begin_variable_parse(TSRMLS_D) /* {{{ */ { zend_llist fetch_list; zend_llist_init(&fetch_list, sizeof(zend_op), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &fetch_list, sizeof(zend_llist)); } /* }}} */ void zend_do_end_variable_parse(znode *variable, int type, int arg_offset TSRMLS_DC) /* {{{ */ { zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline = NULL; zend_op *opline_ptr; zend_uint this_var = -1; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); le = fetch_list_ptr->head; /* TODO: $foo->x->y->z = 1 should fetch "x" and "y" for R or RW, not just W */ if (le) { opline_ptr = (zend_op *)le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { /* convert to FETCH_?(this) into IS_CV */ if (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE) { this_var = opline_ptr->result.var; if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), Z_STRVAL(CONSTANT(opline_ptr->op1.constant)), Z_STRLEN(CONSTANT(opline_ptr->op1.constant)), Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC); Z_TYPE(CONSTANT(opline_ptr->op1.constant)) = IS_NULL; } else { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); } le = le->next; if (variable->op_type == IS_VAR && variable->u.op.var == this_var) { variable->op_type = IS_CV; variable->u.op.var = CG(active_op_array)->this_var; } } else if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } while (le) { opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode == ZEND_SEPARATE) { if (type != BP_VAR_R && type != BP_VAR_IS) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); } le = le->next; continue; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); if (opline->op1_type == IS_VAR && opline->op1.var == this_var) { opline->op1_type = IS_CV; opline->op1.var = CG(active_op_array)->this_var; } switch (type) { case BP_VAR_R: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode -= 3; break; case BP_VAR_W: break; case BP_VAR_RW: opline->opcode += 3; break; case BP_VAR_IS: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode += 6; /* 3+3 */ break; case BP_VAR_FUNC_ARG: opline->opcode += 9; /* 3+3+3 */ opline->extended_value |= arg_offset; break; case BP_VAR_UNSET: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for unsetting"); } opline->opcode += 12; /* 3+3+3+3 */ break; } le = le->next; } if (opline && type == BP_VAR_W && arg_offset) { opline->extended_value |= ZEND_FETCH_MAKE_REF; } } zend_llist_destroy(fetch_list_ptr); zend_stack_del_top(&CG(bp_stack)); } /* }}} */ void zend_do_add_string(znode *result, const znode *op1, znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline; if (Z_STRLEN(op2->u.constant) > 1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_STRING; } else if (Z_STRLEN(op2->u.constant) == 1) { int ch = *Z_STRVAL(op2->u.constant); /* Free memory and use ZEND_ADD_CHAR in case of 1 character strings */ efree(Z_STRVAL(op2->u.constant)); ZVAL_LONG(&op2->u.constant, ch); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_CHAR; } else { /* String can be empty after a variable at the end of a heredoc */ efree(Z_STRVAL(op2->u.constant)); return; } if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_add_variable(znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_VAR; if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_free(znode *op1 TSRMLS_DC) /* {{{ */ { if (op1->op_type==IS_TMP_VAR) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else if (op1->op_type==IS_VAR) { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; while (opline->opcode == ZEND_END_SILENCE || opline->opcode == ZEND_EXT_FCALL_END || opline->opcode == ZEND_OP_DATA) { opline--; } if (opline->result_type == IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_FETCH_R || opline->opcode == ZEND_FETCH_DIM_R || opline->opcode == ZEND_FETCH_OBJ_R || opline->opcode == ZEND_QM_ASSIGN_VAR) { /* It's very rare and useless case. It's better to use additional FREE opcode and simplify the FETCH handlers their selves */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else { opline->result_type |= EXT_TYPE_UNUSED; } } else { while (opline>CG(active_op_array)->opcodes) { if (opline->opcode == ZEND_FETCH_DIM_R && opline->op1_type == IS_VAR && opline->op1.var == op1->u.op.var) { /* This should the end of a list() construct * Mark its result as unused */ opline->extended_value = ZEND_FETCH_STANDARD; break; } else if (opline->result_type==IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_NEW) { opline->result_type |= EXT_TYPE_UNUSED; } break; } opline--; } } } else if (op1->op_type == IS_CONST) { zval_dtor(&op1->u.constant); } } /* }}} */ int zend_do_verify_access_types(const znode *current_access_type, const znode *new_modifier) /* {{{ */ { if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_PPP_MASK) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Multiple access type modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_ABSTRACT) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Multiple abstract modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_STATIC) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Multiple static modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_FINAL) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Multiple final modifiers are not allowed"); } if (((Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)) & (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) == (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Cannot use the final modifier on an abstract class member"); } return (Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)); } /* }}} */ void zend_do_begin_function_declaration(znode *function_token, znode *function_name, int is_method, int return_reference, znode *fn_flags_znode TSRMLS_DC) /* {{{ */ { zend_op_array op_array; char *name = function_name->u.constant.value.str.val; int name_len = function_name->u.constant.value.str.len; int function_begin_line = function_token->u.op.opline_num; zend_uint fn_flags; const char *lcname; zend_bool orig_interactive; ALLOCA_FLAG(use_heap) if (is_method) { if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((Z_LVAL(fn_flags_znode->u.constant) & ~(ZEND_ACC_STATIC|ZEND_ACC_PUBLIC))) { zend_error(E_COMPILE_ERROR, "Access type for interface method %s::%s() must be omitted", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } Z_LVAL(fn_flags_znode->u.constant) |= ZEND_ACC_ABSTRACT; /* propagates to the rest of the parser */ } fn_flags = Z_LVAL(fn_flags_znode->u.constant); /* must be done *after* the above check */ } else { fn_flags = 0; } if ((fn_flags & ZEND_ACC_STATIC) && (fn_flags & ZEND_ACC_ABSTRACT) && !(CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_STRICT, "Static function %s%s%s() should not be abstract", is_method ? CG(active_class_entry)->name : "", is_method ? "::" : "", Z_STRVAL(function_name->u.constant)); } function_token->u.op_array = CG(active_op_array); orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(&op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; op_array.function_name = name; if (return_reference) { op_array.fn_flags |= ZEND_ACC_RETURN_REFERENCE; } op_array.fn_flags |= fn_flags; op_array.scope = is_method?CG(active_class_entry):NULL; op_array.prototype = NULL; op_array.line_start = zend_get_compiled_lineno(TSRMLS_C); if (is_method) { int result; lcname = zend_new_interned_string(zend_str_tolower_dup(name, name_len), name_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lcname)) { result = zend_hash_quick_add(&CG(active_class_entry)->function_table, lcname, name_len+1, INTERNED_HASH(lcname), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } else { result = zend_hash_add(&CG(active_class_entry)->function_table, lcname, name_len+1, &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } if (result == FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::%s()", CG(active_class_entry)->name, name); } zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); if (fn_flags & ZEND_ACC_ABSTRACT) { CG(active_class_entry)->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (!(fn_flags & ZEND_ACC_PPP_MASK)) { fn_flags |= ZEND_ACC_PUBLIC; } if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } } } else { char *class_lcname; class_lcname = do_alloca(CG(active_class_entry)->name_length + 1, use_heap); zend_str_tolower_copy(class_lcname, CG(active_class_entry)->name, CG(active_class_entry)->name_length); /* Improve after RC: cache the lowercase class name */ if ((CG(active_class_entry)->name_length == name_len) && ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT) && (!memcmp(class_lcname, lcname, name_len))) { if (!CG(active_class_entry)->constructor) { CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } } else if ((name_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)))) { if (CG(active_class_entry)->constructor) { zend_error(E_STRICT, "Redefining already defined constructor for class %s", CG(active_class_entry)->name); } CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1))) { CG(active_class_entry)->destructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1))) { CG(active_class_entry)->clone = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } CG(active_class_entry)->__call = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } CG(active_class_entry)->__callstatic = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } CG(active_class_entry)->__get = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } CG(active_class_entry)->__set = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } CG(active_class_entry)->__unset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } CG(active_class_entry)->__isset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } CG(active_class_entry)->__tostring = (zend_function *) CG(active_op_array); } else if (!(fn_flags & ZEND_ACC_STATIC)) { CG(active_op_array)->fn_flags |= ZEND_ACC_ALLOW_STATIC; } free_alloca(class_lcname, use_heap); } str_efree(lcname); } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zval key; if (CG(current_namespace)) { /* Prefix function name with current namespcae name */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, function_name TSRMLS_CC); op_array.function_name = Z_STRVAL(tmp.u.constant); name_len = Z_STRLEN(tmp.u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), name_len); } else { lcname = zend_str_tolower_dup(name, name_len); } opline->opcode = ZEND_DECLARE_FUNCTION; opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, name_len TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; LITERAL_STRINGL(opline->op2, lcname, name_len, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); opline->extended_value = ZEND_DECLARE_FUNCTION; zend_hash_quick_update(CG(function_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); } if (CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_NOP; opline->lineno = function_begin_line; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } { /* Push a seperator to the switch and foreach stacks */ zend_switch_entry switch_entry; switch_entry.cond.op_type = IS_UNUSED; switch_entry.default_case = 0; switch_entry.control_var = 0; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); { /* Foreach stack separator */ zend_op dummy_opline; dummy_opline.result_type = IS_UNUSED; dummy_opline.op1_type = IS_UNUSED; zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); } } if (CG(doc_comment)) { CG(active_op_array)->doc_comment = CG(doc_comment); CG(active_op_array)->doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_begin_lambda_function_declaration(znode *result, znode *function_token, int return_reference, int is_static TSRMLS_DC) /* {{{ */ { znode function_name; zend_op_array *current_op_array = CG(active_op_array); int current_op_number = get_next_op_number(CG(active_op_array)); zend_op *current_op; function_name.op_type = IS_CONST; ZVAL_STRINGL(&function_name.u.constant, "{closure}", sizeof("{closure}")-1, 1); zend_do_begin_function_declaration(function_token, &function_name, 0, return_reference, NULL TSRMLS_CC); result->op_type = IS_TMP_VAR; result->u.op.var = get_temporary_variable(current_op_array); current_op = &current_op_array->opcodes[current_op_number]; current_op->opcode = ZEND_DECLARE_LAMBDA_FUNCTION; zend_del_literal(current_op_array, current_op->op2.constant); SET_UNUSED(current_op->op2); SET_NODE(current_op->result, result); if (is_static) { CG(active_op_array)->fn_flags |= ZEND_ACC_STATIC; } CG(active_op_array)->fn_flags |= ZEND_ACC_CLOSURE; } /* }}} */ void zend_do_handle_exception(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_HANDLE_EXCEPTION; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_function_declaration(const znode *function_token TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; zend_do_extended_info(TSRMLS_C); zend_do_return(NULL, 0 TSRMLS_CC); pass_two(CG(active_op_array) TSRMLS_CC); zend_release_labels(TSRMLS_C); if (CG(active_class_entry)) { zend_check_magic_method_implementation(CG(active_class_entry), (zend_function*)CG(active_op_array), E_COMPILE_ERROR TSRMLS_CC); } else { /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(CG(active_op_array)->function_name); zend_str_tolower_copy(lcname, CG(active_op_array)->function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME)) && CG(active_op_array)->num_args != 1) { zend_error(E_COMPILE_ERROR, "%s() must take exactly 1 argument", ZEND_AUTOLOAD_FUNC_NAME); } } CG(active_op_array)->line_end = zend_get_compiled_lineno(TSRMLS_C); CG(active_op_array) = function_token->u.op_array; /* Pop the switch and foreach seperators */ zend_stack_del_top(&CG(switch_cond_stack)); zend_stack_del_top(&CG(foreach_copy_stack)); } /* }}} */ void zend_do_receive_arg(zend_uchar op, znode *varname, const znode *offset, const znode *initialization, znode *class_type, zend_uchar pass_by_reference TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_arg_info *cur_arg_info; znode var; if (class_type->op_type == IS_CONST && Z_TYPE(class_type->u.constant) == IS_STRING && Z_STRLEN(class_type->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_type->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } if (zend_is_auto_global_quick(Z_STRVAL(varname->u.constant), Z_STRLEN(varname->u.constant), 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign auto-global variable %s", Z_STRVAL(varname->u.constant)); } else { var.op_type = IS_CV; var.u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(varname->u.constant) = (char*)CG(active_op_array)->vars[var.u.op.var].name; var.EA = 0; if (CG(active_op_array)->vars[var.u.op.var].hash_value == THIS_HASHVAL && Z_STRLEN(varname->u.constant) == sizeof("this")-1 && !memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this")-1)) { if (CG(active_op_array)->scope && (CG(active_op_array)->fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } CG(active_op_array)->this_var = var.u.op.var; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->num_args++; opline->opcode = op; SET_NODE(opline->result, &var); SET_NODE(opline->op1, offset); if (op == ZEND_RECV_INIT) { SET_NODE(opline->op2, initialization); } else { CG(active_op_array)->required_num_args = CG(active_op_array)->num_args; SET_UNUSED(opline->op2); } CG(active_op_array)->arg_info = erealloc(CG(active_op_array)->arg_info, sizeof(zend_arg_info)*(CG(active_op_array)->num_args)); cur_arg_info = &CG(active_op_array)->arg_info[CG(active_op_array)->num_args-1]; cur_arg_info->name = zend_new_interned_string(estrndup(varname->u.constant.value.str.val, varname->u.constant.value.str.len), varname->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->name_len = varname->u.constant.value.str.len; cur_arg_info->type_hint = 0; cur_arg_info->allow_null = 1; cur_arg_info->pass_by_reference = pass_by_reference; cur_arg_info->class_name = NULL; cur_arg_info->class_name_len = 0; if (class_type->op_type != IS_UNUSED) { cur_arg_info->allow_null = 0; if (class_type->u.constant.type != IS_NULL) { if (class_type->u.constant.type == IS_ARRAY) { cur_arg_info->type_hint = IS_ARRAY; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else if (Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Default value for parameters with array type hint can only be an array or NULL"); } } } else if (class_type->u.constant.type == IS_CALLABLE) { cur_arg_info->type_hint = IS_CALLABLE; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with callable type hint can only be NULL"); } } } else { cur_arg_info->type_hint = IS_OBJECT; if (ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_type->u.constant), Z_STRLEN(class_type->u.constant))) { zend_resolve_class_name(class_type, opline->extended_value, 1 TSRMLS_CC); } Z_STRVAL(class_type->u.constant) = (char*)zend_new_interned_string(class_type->u.constant.value.str.val, class_type->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->class_name = class_type->u.constant.value.str.val; cur_arg_info->class_name_len = class_type->u.constant.value.str.len; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with a class type hint can only be NULL"); } } } } } } /* }}} */ int zend_do_begin_function_call(znode *function_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { zend_function *function; char *lcname; char *is_compound = memchr(Z_STRVAL(function_name->u.constant), '\\', Z_STRLEN(function_name->u.constant)); zend_resolve_non_class_name(function_name, check_namespace TSRMLS_CC); if (check_namespace && CG(current_namespace) && !is_compound) { /* We assume we call function from the current namespace if it is not prefixed. */ /* In run-time PHP will check for function with full name and internal function with short name */ zend_do_begin_dynamic_function_call(function_name, 1 TSRMLS_CC); return 1; } lcname = zend_str_tolower_dup(function_name->u.constant.value.str.val, function_name->u.constant.value.str.len); if ((zend_hash_find(CG(function_table), lcname, function_name->u.constant.value.str.len+1, (void **) &function)==FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_FUNCTIONS) && (function->type == ZEND_INTERNAL_FUNCTION))) { zend_do_begin_dynamic_function_call(function_name, 0 TSRMLS_CC); efree(lcname); return 1; /* Dynamic */ } efree(function_name->u.constant.value.str.val); function_name->u.constant.value.str.val = lcname; zend_stack_push(&CG(function_call_stack), (void *) &function, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 0; } /* }}} */ void zend_do_begin_method_call(znode *left_bracket TSRMLS_DC) /* {{{ */ { zend_op *last_op; int last_op_number; unsigned char *ptr = NULL; zend_do_end_variable_parse(left_bracket, BP_VAR_R, 0 TSRMLS_CC); zend_do_begin_variable_parse(TSRMLS_C); last_op_number = get_next_op_number(CG(active_op_array))-1; last_op = &CG(active_op_array)->opcodes[last_op_number]; if ((last_op->op2_type == IS_CONST) && (Z_TYPE(CONSTANT(last_op->op2.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(last_op->op2.constant)) == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !zend_binary_strcasecmp(Z_STRVAL(CONSTANT(last_op->op2.constant)), Z_STRLEN(CONSTANT(last_op->op2.constant)), ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1)) { zend_error(E_COMPILE_ERROR, "Cannot call __clone() method on objects - use 'clone $obj' instead"); } if (last_op->opcode == ZEND_FETCH_OBJ_R) { if (last_op->op2_type == IS_CONST) { zval name; name = CONSTANT(last_op->op2.constant); if (Z_TYPE(name) != IS_STRING) { zend_error(E_COMPILE_ERROR, "Method name must be a string"); } if (!IS_INTERNED(Z_STRVAL(name))) { Z_STRVAL(name) = estrndup(Z_STRVAL(name), Z_STRLEN(name)); } FREE_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); last_op->op2.constant = zend_add_func_name_literal(CG(active_op_array), &name TSRMLS_CC); GET_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); } last_op->opcode = ZEND_INIT_METHOD_CALL; SET_UNUSED(last_op->result); Z_LVAL(left_bracket->u.constant) = ZEND_INIT_FCALL_BY_NAME; } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (left_bracket->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &left_bracket->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, left_bracket); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_do_clone(znode *result, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CLONE; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_begin_dynamic_function_call(znode *function_name, int ns_call TSRMLS_DC) /* {{{ */ { unsigned char *ptr = NULL; zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (ns_call) { /* In run-time PHP will check for function with full name and internal function with short name */ opline->opcode = ZEND_INIT_NS_FCALL_BY_NAME; SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_ns_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (function_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, function_name); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_resolve_non_class_name(znode *element_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; int len; zval **ns; char *lcname, *compound = memchr(Z_STRVAL(element_name->u.constant), '\\', Z_STRLEN(element_name->u.constant)); if (Z_STRVAL(element_name->u.constant)[0] == '\\') { /* name starts with \ so it is known and unambiguos, nothing to do here but shorten it */ memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+1, Z_STRLEN(element_name->u.constant)); --Z_STRLEN(element_name->u.constant); return; } if(!check_namespace) { return; } if (compound && CG(current_import)) { len = compound - Z_STRVAL(element_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(element_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(element_name->u.constant) -= len; memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+len, Z_STRLEN(element_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, element_name TSRMLS_CC); *element_name = tmp; efree(lcname); return; } efree(lcname); } if (CG(current_namespace)) { tmp = *element_name; Z_STRLEN(tmp.u.constant) = sizeof("\\")-1 + Z_STRLEN(element_name->u.constant) + Z_STRLEN_P(CG(current_namespace)); Z_STRVAL(tmp.u.constant) = (char *) emalloc(Z_STRLEN(tmp.u.constant)+1); memcpy(Z_STRVAL(tmp.u.constant), Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace))]), "\\", sizeof("\\")-1); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace)) + sizeof("\\")-1]), Z_STRVAL(element_name->u.constant), Z_STRLEN(element_name->u.constant)+1); STR_FREE(Z_STRVAL(element_name->u.constant)); *element_name = tmp; } } /* }}} */ void zend_resolve_class_name(znode *class_name, ulong fetch_type, int check_ns_name TSRMLS_DC) /* {{{ */ { char *compound; char *lcname; zval **ns; znode tmp; int len; compound = memchr(Z_STRVAL(class_name->u.constant), '\\', Z_STRLEN(class_name->u.constant)); if (compound) { /* This is a compound class name that contains namespace prefix */ if (Z_STRVAL(class_name->u.constant)[0] == '\\') { /* The STRING name has "\" prefix */ Z_STRLEN(class_name->u.constant) -= 1; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+1, Z_STRLEN(class_name->u.constant)+1); Z_STRVAL(class_name->u.constant) = erealloc( Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1); if (ZEND_FETCH_CLASS_DEFAULT != zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "'\\%s' is an invalid class name", Z_STRVAL(class_name->u.constant)); } } else { if (CG(current_import)) { len = compound - Z_STRVAL(class_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(class_name->u.constant) -= len; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+len, Z_STRLEN(class_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; efree(lcname); return; } efree(lcname); } /* Here name is not prefixed with \ and not imported */ if (CG(current_namespace)) { tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } } } else if (CG(current_import) || CG(current_namespace)) { /* this is a plain name (without \) */ lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns) == SUCCESS) { /* The given name is an import name. Substitute it. */ zval_dtor(&class_name->u.constant); class_name->u.constant = **ns; zval_copy_ctor(&class_name->u.constant); } else if (CG(current_namespace)) { /* plain name, no import - prepend current namespace to it */ tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } efree(lcname); } } /* }}} */ void zend_do_fetch_class(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { long fetch_class_op_number; zend_op *opline; if (class_name->op_type == IS_CONST && Z_TYPE(class_name->u.constant) == IS_STRING && Z_STRLEN(class_name->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_name->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } fetch_class_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CLASS; SET_UNUSED(opline->op1); opline->extended_value = ZEND_FETCH_CLASS_GLOBAL; CG(catch_begin) = fetch_class_op_number; if (class_name->op_type == IS_CONST) { int fetch_type; fetch_type = zend_get_class_fetch_type(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); switch (fetch_type) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: SET_UNUSED(opline->op2); opline->extended_value = fetch_type; zval_dtor(&class_name->u.constant); break; default: zend_resolve_class_name(class_name, opline->extended_value, 0 TSRMLS_CC); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_name->u.constant TSRMLS_CC); break; } } else { SET_NODE(opline->op2, class_name); } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; /* FIXME: Hack so that INIT_FCALL_BY_NAME still knows this is a class */ GET_NODE(result, opline->result); result->EA = opline->extended_value; } /* }}} */ void zend_do_label(znode *label TSRMLS_DC) /* {{{ */ { zend_label dest; if (!CG(context).labels) { ALLOC_HASHTABLE(CG(context).labels); zend_hash_init(CG(context).labels, 4, NULL, NULL, 0); } dest.brk_cont = CG(context).current_brk_cont; dest.opline_num = get_next_op_number(CG(active_op_array)); if (zend_hash_add(CG(context).labels, Z_STRVAL(label->u.constant), Z_STRLEN(label->u.constant) + 1, (void**)&dest, sizeof(zend_label), NULL) == FAILURE) { zend_error(E_COMPILE_ERROR, "Label '%s' already defined", Z_STRVAL(label->u.constant)); } /* Done with label now */ zval_dtor(&label->u.constant); } /* }}} */ void zend_resolve_goto_label(zend_op_array *op_array, zend_op *opline, int pass2 TSRMLS_DC) /* {{{ */ { zend_label *dest; long current, distance; zval *label; if (pass2) { label = opline->op2.zv; } else { label = &CONSTANT_EX(op_array, opline->op2.constant); } if (CG(context).labels == NULL || zend_hash_find(CG(context).labels, Z_STRVAL_P(label), Z_STRLEN_P(label)+1, (void**)&dest) == FAILURE) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; zend_error(E_COMPILE_ERROR, "'goto' to undefined label '%s'", Z_STRVAL_P(label)); } else { /* Label is not defined. Delay to pass 2. */ INC_BPC(op_array); return; } } opline->op1.opline_num = dest->opline_num; zval_dtor(label); Z_TYPE_P(label) = IS_NULL; /* Check that we are not moving into loop or switch */ current = opline->extended_value; for (distance = 0; current != dest->brk_cont; distance++) { if (current == -1) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; } zend_error(E_COMPILE_ERROR, "'goto' into loop or switch statement is disallowed"); } current = op_array->brk_cont_array[current].parent; } if (distance == 0) { /* Nothing to break out of, optimize to ZEND_JMP */ opline->opcode = ZEND_JMP; opline->extended_value = 0; SET_UNUSED(opline->op2); } else { /* Set real break distance */ ZVAL_LONG(label, distance); } if (pass2) { DEC_BPC(op_array); } } /* }}} */ void zend_do_goto(const znode *label TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_GOTO; opline->extended_value = CG(context).current_brk_cont; SET_UNUSED(opline->op1); SET_NODE(opline->op2, label); zend_resolve_goto_label(CG(active_op_array), opline, 0 TSRMLS_CC); } /* }}} */ void zend_release_labels(TSRMLS_D) /* {{{ */ { if (CG(context).labels) { zend_hash_destroy(CG(context).labels); FREE_HASHTABLE(CG(context).labels); } if (!zend_stack_is_empty(&CG(context_stack))) { zend_compiler_context *ctx; zend_stack_top(&CG(context_stack), (void**)&ctx); CG(context) = *ctx; zend_stack_del_top(&CG(context_stack)); } } /* }}} */ void zend_do_build_full_name(znode *result, znode *prefix, znode *name, int is_class_member TSRMLS_DC) /* {{{ */ { zend_uint length; if (!result) { result = prefix; } else { *result = *prefix; } if (is_class_member) { length = sizeof("::")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "::", sizeof("::")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("::")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } else { length = sizeof("\\")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "\\", sizeof("\\")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("\\")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } } /* }}} */ int zend_do_begin_class_member_function_call(znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { znode class_node; unsigned char *ptr = NULL; zend_op *opline; if (method_name->op_type == IS_CONST) { char *lcname; if (Z_TYPE(method_name->u.constant) != IS_STRING) { zend_error(E_COMPILE_ERROR, "Method name must be a string"); } lcname = zend_str_tolower_dup(Z_STRVAL(method_name->u.constant), Z_STRLEN(method_name->u.constant)); if ((sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == Z_STRLEN(method_name->u.constant) && memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == 0) { zval_dtor(&method_name->u.constant); method_name->op_type = IS_UNUSED; } efree(lcname); } if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; opline = get_next_op(CG(active_op_array) TSRMLS_CC); } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->extended_value = class_node.EA ; } opline->opcode = ZEND_INIT_STATIC_METHOD_CALL; if (class_node.op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, &class_node); } if (method_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &method_name->u.constant TSRMLS_CC); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } } else { SET_NODE(opline->op2, method_name); } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 1; /* Dynamic */ } /* }}} */ void zend_do_end_function_call(znode *function_name, znode *result, const znode *argument_list, int is_method, int is_dynamic_fcall TSRMLS_DC) /* {{{ */ { zend_op *opline; if (is_method && function_name && function_name->op_type == IS_UNUSED) { /* clone */ if (Z_LVAL(argument_list->u.constant) != 0) { zend_error(E_WARNING, "Clone method does not require arguments"); } opline = &CG(active_op_array)->opcodes[Z_LVAL(function_name->u.constant)]; } else { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (!is_method && !is_dynamic_fcall && function_name->op_type==IS_CONST) { opline->opcode = ZEND_DO_FCALL; SET_NODE(opline->op1, function_name); CALCULATE_LITERAL_HASH(opline->op1.constant); GET_CACHE_SLOT(opline->op1.constant); } else { opline->opcode = ZEND_DO_FCALL_BY_NAME; SET_UNUSED(opline->op1); } } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(result, opline->result) ; SET_UNUSED(opline->op2); zend_stack_del_top(&CG(function_call_stack)); opline->extended_value = Z_LVAL(argument_list->u.constant); } /* }}} */ void zend_do_pass_param(znode *param, zend_uchar op, int offset TSRMLS_DC) /* {{{ */ { zend_op *opline; int original_op=op; zend_function **function_ptr_ptr, *function_ptr; int send_by_reference; int send_function = 0; zend_stack_top(&CG(function_call_stack), (void **) &function_ptr_ptr); function_ptr = *function_ptr_ptr; if (original_op == ZEND_SEND_REF) { if (function_ptr && function_ptr->common.function_name && function_ptr->common.type == ZEND_USER_FUNCTION && !ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed; " "If you would like to pass argument by reference, modify the declaration of %s().", function_ptr->common.function_name); } else { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed"); } return; } if (function_ptr) { if (ARG_MAY_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { if (param->op_type & (IS_VAR|IS_CV) && original_op != ZEND_SEND_VAL) { send_by_reference = 1; if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION | ZEND_ARG_SEND_SILENT; } } else { op = ZEND_SEND_VAL; send_by_reference = 0; } } else { send_by_reference = ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset) ? ZEND_ARG_SEND_BY_REF : 0; } } else { send_by_reference = 0; } if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION; } else if (op == ZEND_SEND_VAL && (param->op_type & (IS_VAR|IS_CV))) { op = ZEND_SEND_VAR_NO_REF; } if (op!=ZEND_SEND_VAR_NO_REF && send_by_reference==ZEND_ARG_SEND_BY_REF) { /* change to passing by reference */ switch (param->op_type) { case IS_VAR: case IS_CV: op = ZEND_SEND_REF; break; default: zend_error(E_COMPILE_ERROR, "Only variables can be passed by reference"); break; } } if (original_op == ZEND_SEND_VAR) { switch (op) { case ZEND_SEND_VAR_NO_REF: zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); break; case ZEND_SEND_VAR: if (function_ptr) { zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(param, BP_VAR_FUNC_ARG, offset TSRMLS_CC); } break; case ZEND_SEND_REF: zend_do_end_variable_parse(param, BP_VAR_W, 0 TSRMLS_CC); break; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (op == ZEND_SEND_VAR_NO_REF) { if (function_ptr) { opline->extended_value = ZEND_ARG_COMPILE_TIME_BOUND | send_by_reference | send_function; } else { opline->extended_value = send_function; } } else { if (function_ptr) { opline->extended_value = ZEND_DO_FCALL; } else { opline->extended_value = ZEND_DO_FCALL_BY_NAME; } } opline->opcode = op; SET_NODE(opline->op1, param); opline->op2.opline_num = offset; SET_UNUSED(opline->op2); } /* }}} */ static int generate_free_switch_expr(const zend_switch_entry *switch_entry TSRMLS_DC) /* {{{ */ { zend_op *opline; if (switch_entry->cond.op_type != IS_VAR && switch_entry->cond.op_type != IS_TMP_VAR) { return (switch_entry->cond.op_type == IS_UNUSED); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry->cond); SET_UNUSED(opline->op2); opline->extended_value = 0; return 0; } /* }}} */ static int generate_free_foreach_copy(const zend_op *foreach_copy TSRMLS_DC) /* {{{ */ { zend_op *opline; /* If we reach the seperator then stop applying the stack */ if (foreach_copy->result_type == IS_UNUSED && foreach_copy->op1_type == IS_UNUSED) { return 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->result_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->result); SET_UNUSED(opline->op2); opline->extended_value = 1; if (foreach_copy->op1_type != IS_UNUSED) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->op1_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->op1); SET_UNUSED(opline->op2); opline->extended_value = 0; } return 0; } /* }}} */ void zend_do_return(znode *expr, int do_end_vparse TSRMLS_DC) /* {{{ */ { zend_op *opline; int start_op_number, end_op_number; if (do_end_vparse) { if ((CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) && !zend_is_function_or_method_call(expr)) { zend_do_end_variable_parse(expr, BP_VAR_W, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(expr, BP_VAR_R, 0 TSRMLS_CC); } } start_op_number = get_next_op_number(CG(active_op_array)); #ifdef ZTS zend_stack_apply_with_argument(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_switch_expr TSRMLS_CC); zend_stack_apply_with_argument(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_foreach_copy TSRMLS_CC); #else zend_stack_apply(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_switch_expr); zend_stack_apply(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_foreach_copy); #endif end_op_number = get_next_op_number(CG(active_op_array)); while (start_op_number < end_op_number) { CG(active_op_array)->opcodes[start_op_number].extended_value |= EXT_TYPE_FREE_ON_RETURN; start_op_number++; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) ? ZEND_RETURN_BY_REF : ZEND_RETURN; if (expr) { SET_NODE(opline->op1, expr); if (do_end_vparse && zend_is_function_or_method_call(expr)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } } else { opline->op1_type = IS_CONST; LITERAL_NULL(opline->op1); } SET_UNUSED(opline->op2); } /* }}} */ static int zend_add_try_element(zend_uint try_op TSRMLS_DC) /* {{{ */ { int try_catch_offset = CG(active_op_array)->last_try_catch++; CG(active_op_array)->try_catch_array = erealloc(CG(active_op_array)->try_catch_array, sizeof(zend_try_catch_element)*CG(active_op_array)->last_try_catch); CG(active_op_array)->try_catch_array[try_catch_offset].try_op = try_op; return try_catch_offset; } /* }}} */ static void zend_add_catch_element(int offset, zend_uint catch_op TSRMLS_DC) /* {{{ */ { CG(active_op_array)->try_catch_array[offset].catch_op = catch_op; } /* }}} */ void zend_do_first_catch(znode *open_parentheses TSRMLS_DC) /* {{{ */ { open_parentheses->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_initialize_try_catch_element(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist jmp_list; zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); zend_add_catch_element(try_token->u.op.opline_num, get_next_op_number(CG(active_op_array)) TSRMLS_CC); } /* }}} */ void zend_do_mark_last_catch(const znode *first_catch, const znode *last_additional_catch TSRMLS_DC) /* {{{ */ { CG(active_op_array)->last--; zend_do_if_end(TSRMLS_C); if (last_additional_catch->u.op.opline_num == -1) { CG(active_op_array)->opcodes[first_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[first_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } else { CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_try(znode *try_token TSRMLS_DC) /* {{{ */ { try_token->u.op.opline_num = zend_add_try_element(get_next_op_number(CG(active_op_array)) TSRMLS_CC); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_catch(znode *try_token, znode *class_name, znode *catch_var, znode *first_catch TSRMLS_DC) /* {{{ */ { long catch_op_number; zend_op *opline; znode catch_class; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); catch_class = *class_name; } else { zend_error(E_COMPILE_ERROR, "Bad class name in the catch statement"); } catch_op_number = get_next_op_number(CG(active_op_array)); if (first_catch) { first_catch->u.op.opline_num = catch_op_number; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CATCH; opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &catch_class.u.constant TSRMLS_CC); opline->op2_type = IS_CV; opline->op2.var = lookup_cv(CG(active_op_array), catch_var->u.constant.value.str.val, catch_var->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(catch_var->u.constant) = (char*)CG(active_op_array)->vars[opline->op2.var].name; opline->result.num = 0; /* 1 means it's the last catch in the block */ try_token->u.op.opline_num = catch_op_number; } /* }}} */ void zend_do_end_catch(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); CG(active_op_array)->opcodes[try_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_throw(const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_THROW; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); } /* }}} */ ZEND_API void function_add_ref(zend_function *function) /* {{{ */ { if (function->type == ZEND_USER_FUNCTION) { zend_op_array *op_array = &function->op_array; (*op_array->refcount)++; if (op_array->static_variables) { HashTable *static_variables = op_array->static_variables; zval *tmp_zval; ALLOC_HASHTABLE(op_array->static_variables); zend_hash_init(op_array->static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(op_array->static_variables, static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_zval, sizeof(zval *)); } op_array->run_time_cache = NULL; } } /* }}} */ static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */ { zend_function *function, *new_function; if (!ce->parent) { return; } /* You cannot change create_object */ ce->create_object = ce->parent->create_object; /* Inherit special functions if needed */ if (!ce->get_iterator) { ce->get_iterator = ce->parent->get_iterator; } if (!ce->iterator_funcs.funcs) { ce->iterator_funcs.funcs = ce->parent->iterator_funcs.funcs; } if (!ce->__get) { ce->__get = ce->parent->__get; } if (!ce->__set) { ce->__set = ce->parent->__set; } if (!ce->__unset) { ce->__unset = ce->parent->__unset; } if (!ce->__isset) { ce->__isset = ce->parent->__isset; } if (!ce->__call) { ce->__call = ce->parent->__call; } if (!ce->__callstatic) { ce->__callstatic = ce->parent->__callstatic; } if (!ce->__tostring) { ce->__tostring = ce->parent->__tostring; } if (!ce->clone) { ce->clone = ce->parent->clone; } if(!ce->serialize) { ce->serialize = ce->parent->serialize; } if(!ce->unserialize) { ce->unserialize = ce->parent->unserialize; } if (!ce->destructor) { ce->destructor = ce->parent->destructor; } if (ce->constructor) { if (ce->parent->constructor && ce->parent->constructor->common.fn_flags & ZEND_ACC_FINAL) { zend_error(E_ERROR, "Cannot override final %s::%s() with %s::%s()", ce->parent->name, ce->parent->constructor->common.function_name, ce->name, ce->constructor->common.function_name ); } return; } if (zend_hash_find(&ce->parent->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), (void **)&function)==SUCCESS) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), function, sizeof(zend_function), (void**)&new_function); function_add_ref(new_function); } else { /* Don't inherit the old style constructor if we already have the new style constructor */ char *lc_class_name; char *lc_parent_class_name; lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); if (!zend_hash_exists(&ce->function_table, lc_class_name, ce->name_length+1)) { lc_parent_class_name = zend_str_tolower_dup(ce->parent->name, ce->parent->name_length); if (!zend_hash_exists(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1) && zend_hash_find(&ce->parent->function_table, lc_parent_class_name, ce->parent->name_length+1, (void **)&function)==SUCCESS) { if (function->common.fn_flags & ZEND_ACC_CTOR) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1, function, sizeof(zend_function), (void**)&new_function); function_add_ref(new_function); } } efree(lc_parent_class_name); } efree(lc_class_name); } ce->constructor = ce->parent->constructor; } /* }}} */ char *zend_visibility_string(zend_uint fn_flags) /* {{{ */ { if (fn_flags & ZEND_ACC_PRIVATE) { return "private"; } if (fn_flags & ZEND_ACC_PROTECTED) { return "protected"; } if (fn_flags & ZEND_ACC_PUBLIC) { return "public"; } return ""; } /* }}} */ static void do_inherit_method(zend_function *function) /* {{{ */ { /* The class entry of the derived function intentionally remains the same * as that of the parent class. That allows us to know in which context * we're running, and handle private method calls properly. */ function_add_ref(function); } /* }}} */ static zend_bool zend_do_perform_implementation_check(const zend_function *fe, const zend_function *proto TSRMLS_DC) /* {{{ */ { zend_uint i; /* If it's a user function then arg_info == NULL means we don't have any parameters but * we still need to do the arg number checks. We are only willing to ignore this for internal * functions because extensions don't always define arg_info. */ if (!proto || (!proto->common.arg_info && proto->common.type != ZEND_USER_FUNCTION)) { return 1; } /* Checks for constructors only if they are declared in an interface, * or explicitly marked as abstract */ if ((fe->common.fn_flags & ZEND_ACC_CTOR) && ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)) { return 1; } /* check number of arguments */ if (proto->common.required_num_args < fe->common.required_num_args || proto->common.num_args > fe->common.num_args) { return 0; } if (fe->common.type != ZEND_USER_FUNCTION && (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) != 0 && (fe->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) == 0) { return 0; } /* by-ref constraints on return values are covariant */ if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) { return 0; } for (i=0; i < proto->common.num_args; i++) { if (ZEND_LOG_XOR(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)) { /* Only one has a type hint and the other one doesn't */ return 0; } if (fe->common.arg_info[i].class_name) { const char *fe_class_name, *proto_class_name; zend_uint fe_class_name_len, proto_class_name_len; if (!strcasecmp(fe->common.arg_info[i].class_name, "parent") && proto->common.scope) { fe_class_name = proto->common.scope->name; fe_class_name_len = proto->common.scope->name_length; } else if (!strcasecmp(fe->common.arg_info[i].class_name, "self") && fe->common.scope) { fe_class_name = fe->common.scope->name; fe_class_name_len = fe->common.scope->name_length; } else { fe_class_name = fe->common.arg_info[i].class_name; fe_class_name_len = fe->common.arg_info[i].class_name_len; } if (!strcasecmp(proto->common.arg_info[i].class_name, "parent") && proto->common.scope && proto->common.scope->parent) { proto_class_name = proto->common.scope->parent->name; proto_class_name_len = proto->common.scope->parent->name_length; } else if (!strcasecmp(proto->common.arg_info[i].class_name, "self") && proto->common.scope) { proto_class_name = proto->common.scope->name; proto_class_name_len = proto->common.scope->name_length; } else { proto_class_name = proto->common.arg_info[i].class_name; proto_class_name_len = proto->common.arg_info[i].class_name_len; } if (strcasecmp(fe_class_name, proto_class_name)!=0) { const char *colon; if (fe->common.type != ZEND_USER_FUNCTION) { return 0; } else if (strchr(proto_class_name, '\\') != NULL || (colon = zend_memrchr(fe_class_name, '\\', fe_class_name_len)) == NULL || strcasecmp(colon+1, proto_class_name) != 0) { zend_class_entry **fe_ce, **proto_ce; int found, found2; found = zend_lookup_class(fe_class_name, fe_class_name_len, &fe_ce TSRMLS_CC); found2 = zend_lookup_class(proto_class_name, proto_class_name_len, &proto_ce TSRMLS_CC); /* Check for class alias */ if (found != SUCCESS || found2 != SUCCESS || (*fe_ce)->type == ZEND_INTERNAL_CLASS || (*proto_ce)->type == ZEND_INTERNAL_CLASS || *fe_ce != *proto_ce) { return 0; } } } } if (fe->common.arg_info[i].type_hint != proto->common.arg_info[i].type_hint) { /* Incompatible type hint */ return 0; } /* by-ref constraints on arguments are invariant */ if (fe->common.arg_info[i].pass_by_reference != proto->common.arg_info[i].pass_by_reference) { return 0; } } if (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) { for (i=proto->common.num_args; i < fe->common.num_args; i++) { if (!fe->common.arg_info[i].pass_by_reference) { return 0; } } } return 1; } /* }}} */ #define REALLOC_BUF_IF_EXCEED(buf, offset, length, size) \ if (UNEXPECTED(offset - buf + size >= length)) { \ length += size + 1; \ buf = erealloc(buf, length); \ } static char * zend_get_function_declaration(zend_function *fptr TSRMLS_DC) /* {{{ */ { char *offset, *buf; zend_uint length = 1024; offset = buf = (char *)emalloc(length * sizeof(char)); if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { *(offset++) = '&'; *(offset++) = ' '; } if (fptr->common.scope) { memcpy(offset, fptr->common.scope->name, fptr->common.scope->name_length); offset += fptr->common.scope->name_length; *(offset++) = ':'; *(offset++) = ':'; } { size_t name_len = strlen(fptr->common.function_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, name_len); memcpy(offset, fptr->common.function_name, name_len); offset += name_len; } *(offset++) = '('; if (fptr->common.arg_info) { zend_uint i, required; zend_arg_info *arg_info = fptr->common.arg_info; required = fptr->common.required_num_args; for (i = 0; i < fptr->common.num_args;) { if (arg_info->class_name) { const char *class_name; zend_uint class_name_len; if (!strcasecmp(arg_info->class_name, "self") && fptr->common.scope ) { class_name = fptr->common.scope->name; class_name_len = fptr->common.scope->name_length; } else if (!strcasecmp(arg_info->class_name, "parent") && fptr->common.scope->parent) { class_name = fptr->common.scope->parent->name; class_name_len = fptr->common.scope->parent->name_length; } else { class_name = arg_info->class_name; class_name_len = arg_info->class_name_len; } REALLOC_BUF_IF_EXCEED(buf, offset, length, class_name_len); memcpy(offset, class_name, class_name_len); offset += class_name_len; *(offset++) = ' '; } else if (arg_info->type_hint) { zend_uint type_name_len; char *type_name = zend_get_type_by_const(arg_info->type_hint); type_name_len = strlen(type_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, type_name_len); memcpy(offset, type_name, type_name_len); offset += type_name_len; *(offset++) = ' '; } if (arg_info->pass_by_reference) { *(offset++) = '&'; } *(offset++) = '$'; if (arg_info->name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->name_len); memcpy(offset, arg_info->name, arg_info->name_len); offset += arg_info->name_len; } else { zend_uint idx = i; memcpy(offset, "param", 5); offset += 5; do { *(offset++) = (char) (idx % 10) + '0'; idx /= 10; } while (idx > 0); } if (i >= required) { *(offset++) = ' '; *(offset++) = '='; *(offset++) = ' '; if (fptr->type == ZEND_USER_FUNCTION) { zend_op *precv = NULL; { zend_uint idx = i; zend_op *op = ((zend_op_array *)fptr)->opcodes; zend_op *end = op + ((zend_op_array *)fptr)->last; ++idx; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT) && op->op1.num == (long)idx) { precv = op; } ++op; } } if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) { zval *zv, zv_copy; int use_copy; ALLOC_ZVAL(zv); *zv = *precv->op2.zv; zval_copy_ctor(zv); INIT_PZVAL(zv); zval_update_constant_ex(&zv, (void*)1, fptr->common.scope TSRMLS_CC); if (Z_TYPE_P(zv) == IS_BOOL) { if (Z_LVAL_P(zv)) { memcpy(offset, "true", 4); offset += 4; } else { memcpy(offset, "false", 5); offset += 5; } } else if (Z_TYPE_P(zv) == IS_NULL) { memcpy(offset, "NULL", 4); offset += 4; } else if (Z_TYPE_P(zv) == IS_STRING) { *(offset++) = '\''; REALLOC_BUF_IF_EXCEED(buf, offset, length, MIN(Z_STRLEN_P(zv), 10)); memcpy(offset, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 10)); offset += MIN(Z_STRLEN_P(zv), 10); if (Z_STRLEN_P(zv) > 10) { *(offset++) = '.'; *(offset++) = '.'; *(offset++) = '.'; } *(offset++) = '\''; } else if (Z_TYPE_P(zv) == IS_ARRAY) { memcpy(offset, "Array", 5); offset += 5; } else { zend_make_printable_zval(zv, &zv_copy, &use_copy); REALLOC_BUF_IF_EXCEED(buf, offset, length, Z_STRLEN(zv_copy)); memcpy(offset, Z_STRVAL(zv_copy), Z_STRLEN(zv_copy)); offset += Z_STRLEN(zv_copy); if (use_copy) { zval_dtor(&zv_copy); } } zval_ptr_dtor(&zv); } } else { memcpy(offset, "NULL", 4); offset += 4; } } if (++i < fptr->common.num_args) { *(offset++) = ','; *(offset++) = ' '; } arg_info++; REALLOC_BUF_IF_EXCEED(buf, offset, length, 32); } } *(offset++) = ')'; *offset = '\0'; return buf; } /* }}} */ static void do_inheritance_check_on_method(zend_function *child, zend_function *parent TSRMLS_DC) /* {{{ */ { zend_uint child_flags; zend_uint parent_flags = parent->common.fn_flags; if ((parent->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && parent->common.fn_flags & ZEND_ACC_ABSTRACT && parent->common.scope != (child->common.prototype ? child->common.prototype->common.scope : child->common.scope) && child->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_IMPLEMENTED_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Can't inherit abstract function %s::%s() (previously declared abstract in %s)", parent->common.scope->name, child->common.function_name, child->common.prototype ? child->common.prototype->common.scope->name : child->common.scope->name); } if (parent_flags & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot override final method %s::%s()", ZEND_FN_SCOPE_NAME(parent), child->common.function_name); } child_flags = child->common.fn_flags; /* You cannot change from static to non static and vice versa. */ if ((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC)) { if (child->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot make non static method %s::%s() static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } else { zend_error(E_COMPILE_ERROR, "Cannot make static method %s::%s() non static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } } /* Disallow making an inherited method abstract. */ if ((child_flags & ZEND_ACC_ABSTRACT) && !(parent_flags & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Cannot make non abstract method %s::%s() abstract in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } if (parent_flags & ZEND_ACC_CHANGED) { child->common.fn_flags |= ZEND_ACC_CHANGED; } else { /* Prevent derived classes from restricting access that was available in parent classes */ if ((child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::%s() must be %s (as in class %s)%s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if (((child_flags & ZEND_ACC_PPP_MASK) < (parent_flags & ZEND_ACC_PPP_MASK)) && ((parent_flags & ZEND_ACC_PPP_MASK) & ZEND_ACC_PRIVATE)) { child->common.fn_flags |= ZEND_ACC_CHANGED; } } if (parent_flags & ZEND_ACC_PRIVATE) { child->common.prototype = NULL; } else if (parent_flags & ZEND_ACC_ABSTRACT) { child->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; child->common.prototype = parent; } else if (!(parent->common.fn_flags & ZEND_ACC_CTOR) || (parent->common.prototype && (parent->common.prototype->common.scope->ce_flags & ZEND_ACC_INTERFACE))) { /* ctors only have a prototype if it comes from an interface */ child->common.prototype = parent->common.prototype ? parent->common.prototype : parent; } if (child->common.prototype && (child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { if (!zend_do_perform_implementation_check(child, child->common.prototype TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s::%s() must be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_get_function_declaration(child->common.prototype TSRMLS_CC)); } } else if (EG(error_reporting) & E_STRICT || EG(user_error_handler)) { /* Check E_STRICT (or custom error handler) before the check so that we save some time */ if (!zend_do_perform_implementation_check(child, parent TSRMLS_CC)) { char *method_prototype = zend_get_function_declaration(child->common.prototype TSRMLS_CC); zend_error(E_STRICT, "Declaration of %s::%s() should be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, method_prototype); efree(method_prototype); } } } /* }}} */ static zend_bool do_inherit_method_check(HashTable *child_function_table, zend_function *parent, const zend_hash_key *hash_key, zend_class_entry *child_ce) /* {{{ */ { zend_uint parent_flags = parent->common.fn_flags; zend_function *child; TSRMLS_FETCH(); if (zend_hash_quick_find(child_function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child)==FAILURE) { if (parent_flags & (ZEND_ACC_ABSTRACT)) { child_ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } return 1; /* method doesn't exist in child, copy from parent */ } do_inheritance_check_on_method(child, parent TSRMLS_CC); return 0; } /* }}} */ static zend_bool do_inherit_property_access_check(HashTable *target_ht, zend_property_info *parent_info, const zend_hash_key *hash_key, zend_class_entry *ce) /* {{{ */ { zend_property_info *child_info; zend_class_entry *parent_ce = ce->parent; if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW)) { if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { child_info->flags |= ZEND_ACC_CHANGED; } else { zend_hash_quick_update(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, parent_info, sizeof(zend_property_info), (void **) &child_info); if(ce->type & ZEND_INTERNAL_CLASS) { zend_duplicate_property_info_internal(child_info); } else { zend_duplicate_property_info(child_info); } child_info->flags &= ~ZEND_ACC_PRIVATE; /* it's not private anymore */ child_info->flags |= ZEND_ACC_SHADOW; /* but it's a shadow of private */ } return 0; /* don't copy access information to child */ } if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { if ((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s", (parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", parent_ce->name, hash_key->arKey, (child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ce->name, hash_key->arKey); } if(parent_info->flags & ZEND_ACC_CHANGED) { child_info->flags |= ZEND_ACC_CHANGED; } if ((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ce->name, hash_key->arKey, zend_visibility_string(parent_info->flags), parent_ce->name, (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if ((child_info->flags & ZEND_ACC_STATIC) == 0) { Z_DELREF_P(ce->default_properties_table[parent_info->offset]); ce->default_properties_table[parent_info->offset] = ce->default_properties_table[child_info->offset]; ce->default_properties_table[child_info->offset] = NULL; child_info->offset = parent_info->offset; } return 0; /* Don't copy from parent */ } else { return 1; /* Copy from parent */ } } /* }}} */ static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce TSRMLS_CC) == FAILURE) { zend_error(E_CORE_ERROR, "Class %s could not implement interface %s", ce->name, iface->name); } if (ce == iface) { zend_error(E_ERROR, "Interface %s cannot implement itself", ce->name); } } /* }}} */ ZEND_API void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface TSRMLS_DC) /* {{{ */ { /* expects interface to be contained in ce's interface list already */ zend_uint i, ce_num, if_num = iface->num_interfaces; zend_class_entry *entry; if (if_num==0) { return; } ce_num = ce->num_interfaces; if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } /* Inherit the interfaces, only if they're not already inherited by the class */ while (if_num--) { entry = iface->interfaces[if_num]; for (i = 0; i < ce_num; i++) { if (ce->interfaces[i] == entry) { break; } } if (i == ce_num) { ce->interfaces[ce->num_interfaces++] = entry; } } /* and now call the implementing handlers */ while (ce_num < ce->num_interfaces) { do_implement_interface(ce, ce->interfaces[ce_num++] TSRMLS_CC); } } /* }}} */ #ifdef ZTS static void zval_internal_ctor(zval **p) /* {{{ */ { zval *orig_ptr = *p; ALLOC_ZVAL(*p); MAKE_COPY_ZVAL(&orig_ptr, *p); } /* }}} */ # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) (((parent_ce)->type != (ce)->type) ? zval_internal_ctor : zval_add_ref)) #else # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) zval_add_ref) #endif ZEND_API void zend_do_inheritance(zend_class_entry *ce, zend_class_entry *parent_ce TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; if ((ce->ce_flags & ZEND_ACC_INTERFACE) && !(parent_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ce->name, parent_ce->name); } if (parent_ce->ce_flags & ZEND_ACC_FINAL_CLASS) { zend_error(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ce->name, parent_ce->name); } ce->parent = parent_ce; /* Copy serialize/unserialize callbacks */ if (!ce->serialize) { ce->serialize = parent_ce->serialize; } if (!ce->unserialize) { ce->unserialize = parent_ce->unserialize; } /* Inherit interfaces */ zend_do_inherit_interfaces(ce, parent_ce TSRMLS_CC); /* Inherit properties */ if (parent_ce->default_properties_count) { int i = ce->default_properties_count + parent_ce->default_properties_count; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_properties_count) { while (i-- > parent_ce->default_properties_count) { ce->default_properties_table[i] = ce->default_properties_table[i - parent_ce->default_properties_count]; } } for (i = 0; i < parent_ce->default_properties_count; i++) { ce->default_properties_table[i] = parent_ce->default_properties_table[i]; if (ce->default_properties_table[i]) { #ifdef ZTS if (parent_ce->type != ce->type) { zval *p; ALLOC_ZVAL(p); MAKE_COPY_ZVAL(&ce->default_properties_table[i], p); ce->default_properties_table[i] = p; } else { Z_ADDREF_P(ce->default_properties_table[i]); } #else Z_ADDREF_P(ce->default_properties_table[i]); #endif } } ce->default_properties_count += parent_ce->default_properties_count; } if (parent_ce->type != ce->type) { /* User class extends internal class */ zend_update_class_constants(parent_ce TSRMLS_CC); if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = erealloc(ce->default_static_members_table, sizeof(void*) * i); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&CE_STATIC_MEMBERS(parent_ce)[i]); ce->default_static_members_table[i] = CE_STATIC_MEMBERS(parent_ce)[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; ce->static_members_table = ce->default_static_members_table; } } else { if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&parent_ce->default_static_members_table[i]); ce->default_static_members_table[i] = parent_ce->default_static_members_table[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } } for (zend_hash_internal_pointer_reset(&ce->properties_info); zend_hash_get_current_data(&ce->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->properties_info)) { if (property_info->ce == ce) { if (property_info->flags & ZEND_ACC_STATIC) { property_info->offset += parent_ce->default_static_members_count; } else { property_info->offset += parent_ce->default_properties_count; } } } zend_hash_merge_ex(&ce->properties_info, &parent_ce->properties_info, (copy_ctor_func_t) (ce->type & ZEND_INTERNAL_CLASS ? zend_duplicate_property_info_internal : zend_duplicate_property_info), sizeof(zend_property_info), (merge_checker_func_t) do_inherit_property_access_check, ce); zend_hash_merge(&ce->constants_table, &parent_ce->constants_table, zval_property_ctor(parent_ce, ce), NULL, sizeof(zval *), 0); zend_hash_merge_ex(&ce->function_table, &parent_ce->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_inherit_parent_constructor(ce); if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS && ce->type == ZEND_INTERNAL_CLASS) { ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } else if (!(ce->ce_flags & ZEND_ACC_IMPLEMENT_INTERFACES) && !(ce->ce_flags & ZEND_ACC_IMPLEMENT_TRAITS)) { /* The verification will be done in runtime by ZEND_VERIFY_ABSTRACT_CLASS */ zend_verify_abstract_class(ce TSRMLS_CC); } ce->ce_flags |= parent_ce->ce_flags & ZEND_HAS_STATIC_IN_METHODS; } /* }}} */ static zend_bool do_inherit_constant_check(HashTable *child_constants_table, const zval **parent_constant, const zend_hash_key *hash_key, const zend_class_entry *iface) /* {{{ */ { zval **old_constant; if (zend_hash_quick_find(child_constants_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**)&old_constant) == SUCCESS) { if (*old_constant != *parent_constant) { zend_error(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", hash_key->arKey, iface->name); } return 0; } return 1; } /* }}} */ static int do_interface_constant_check(zval **val TSRMLS_DC, int num_args, va_list args, const zend_hash_key *key) /* {{{ */ { zend_class_entry **iface = va_arg(args, zend_class_entry**); do_inherit_constant_check(&(*iface)->constants_table, (const zval **) val, key, *iface); return ZEND_HASH_APPLY_KEEP; } /* }}} */ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_iface_num = ce->num_interfaces; zend_uint parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0; for (i = 0; i < ce->num_interfaces; i++) { if (ce->interfaces[i] == NULL) { memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i)); i--; } else if (ce->interfaces[i] == iface) { if (i < parent_iface_num) { ignore = 1; } else { zend_error(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ce->name, iface->name); } } } if (ignore) { /* Check for attempt to redeclare interface constants */ zend_hash_apply_with_arguments(&ce->constants_table TSRMLS_CC, (apply_func_args_t) do_interface_constant_check, 1, &iface); } else { if (ce->num_interfaces >= current_iface_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } } ce->interfaces[ce->num_interfaces++] = iface; zend_hash_merge_ex(&ce->constants_table, &iface->constants_table, (copy_ctor_func_t) zval_add_ref, sizeof(zval *), (merge_checker_func_t) do_inherit_constant_check, iface); zend_hash_merge_ex(&ce->function_table, &iface->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_implement_interface(ce, iface TSRMLS_CC); zend_do_inherit_interfaces(ce, iface TSRMLS_CC); } } /* }}} */ ZEND_API void zend_do_implement_trait(zend_class_entry *ce, zend_class_entry *trait TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_trait_num = ce->num_traits; zend_uint parent_trait_num = ce->parent ? ce->parent->num_traits : 0; for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == NULL) { memmove(ce->traits + i, ce->traits + i + 1, sizeof(zend_class_entry*) * (--ce->num_traits - i)); i--; } else if (ce->traits[i] == trait) { if (i < parent_trait_num) { ignore = 1; } } } if (!ignore) { if (ce->num_traits >= current_trait_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->traits = (zend_class_entry **) realloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } else { ce->traits = (zend_class_entry **) erealloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } } ce->traits[ce->num_traits++] = trait; } } /* }}} */ static zend_bool zend_traits_method_compatibility_check(zend_function *fn, zend_function *other_fn TSRMLS_DC) /* {{{ */ { zend_uint fn_flags = fn->common.scope->ce_flags; zend_uint other_flags = other_fn->common.scope->ce_flags; return zend_do_perform_implementation_check(fn, other_fn TSRMLS_CC) && zend_do_perform_implementation_check(other_fn, fn TSRMLS_CC) && ((fn_flags & ZEND_ACC_FINAL) == (other_flags & ZEND_ACC_FINAL)) /* equal final qualifier */ && ((fn_flags & ZEND_ACC_STATIC)== (other_flags & ZEND_ACC_STATIC)); /* equal static qualifier */ } /* }}} */ static int zend_traits_merge_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { size_t current; size_t i; size_t count; HashTable* resulting_table; HashTable** function_tables; zend_class_entry *ce; size_t collision = 0; size_t abstract_solved = 0; zend_function* other_trait_fn; current = va_arg(args, size_t); /* index of current trait */ count = va_arg(args, size_t); resulting_table = va_arg(args, HashTable*); function_tables = va_arg(args, HashTable**); ce = va_arg(args, zend_class_entry*); for (i = 0; i < count; i++) { if (i == current) { continue; /* just skip this, cause its the table this function is applied on */ } if (zend_hash_quick_find(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&other_trait_fn) == SUCCESS) { /* if it is an abstract method, there is no collision */ if (other_trait_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible */ /* In case both are abstract, just check prototype, but need to do that in both directions */ if (!zend_traits_method_compatibility_check(fn, other_trait_fn TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s must be compatible with %s", zend_get_function_declaration(fn TSRMLS_CC), zend_get_function_declaration(other_trait_fn TSRMLS_CC)); } /* we can savely free and remove it from other table */ zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } else { /* if it is not an abstract method, there is still no collision */ /* if fn is an abstract method */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible. Here, we already know other_trait_fn cannot be abstract, full check ok. */ if (!zend_traits_method_compatibility_check(fn, other_trait_fn TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s must be compatible with %s", zend_get_function_declaration(fn TSRMLS_CC), zend_get_function_declaration(other_trait_fn TSRMLS_CC)); } /* just mark as solved, will be added if its own trait is processed */ abstract_solved = 1; } else { /* but else, we have a collision of non-abstract methods */ collision++; zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } } } if (collision) { zend_function* class_fn; /* make sure method is not already overridden in class */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&class_fn) == FAILURE || class_fn->common.scope != ce) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because there are collisions with other trait methods on %s", fn->common.function_name, ce->name); } zend_function_dtor(fn); } else if (abstract_solved) { zend_function_dtor(fn); } else { /* Add it to result function table */ if (zend_hash_quick_add(resulting_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, fn, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating resulting trait method table", fn->common.function_name); } } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ static void zend_add_magic_methods(zend_class_entry* ce, const char* mname, uint mname_len, zend_function* fe TSRMLS_DC) /* {{{ */ { if (!strncmp(mname, ZEND_CLONE_FUNC_NAME, mname_len)) { ce->clone = fe; fe->common.fn_flags |= ZEND_ACC_CLONE; } else if (!strncmp(mname, ZEND_CONSTRUCTOR_FUNC_NAME, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } else if (!strncmp(mname, ZEND_DESTRUCTOR_FUNC_NAME, mname_len)) { ce->destructor = fe; fe->common.fn_flags |= ZEND_ACC_DTOR; } else if (!strncmp(mname, ZEND_GET_FUNC_NAME, mname_len)) { ce->__get = fe; } else if (!strncmp(mname, ZEND_SET_FUNC_NAME, mname_len)) { ce->__set = fe; } else if (!strncmp(mname, ZEND_CALL_FUNC_NAME, mname_len)) { ce->__call = fe; } else if (!strncmp(mname, ZEND_UNSET_FUNC_NAME, mname_len)) { ce->__unset = fe; } else if (!strncmp(mname, ZEND_ISSET_FUNC_NAME, mname_len)) { ce->__isset = fe; } else if (!strncmp(mname, ZEND_CALLSTATIC_FUNC_NAME, mname_len)) { ce->__callstatic = fe; } else if (!strncmp(mname, ZEND_TOSTRING_FUNC_NAME, mname_len)) { ce->__tostring = fe; } else if (ce->name_length + 1 == mname_len) { char *lowercase_name = emalloc(ce->name_length + 1); zend_str_tolower_copy(lowercase_name, ce->name, ce->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, ce->name_length + 1, 1 TSRMLS_CC); if (!memcmp(mname, lowercase_name, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } str_efree(lowercase_name); } } /* }}} */ static int zend_traits_merge_functions_to_class(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zend_class_entry *ce = va_arg(args, zend_class_entry*); zend_function* existing_fn = NULL; zend_function fn_copy, *fn_copy_p; zend_function* prototype = NULL; /* is used to determine the prototype according to the inheritance chain */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &existing_fn) == FAILURE || existing_fn->common.scope != ce) { /* not found or inherited from other class or interface */ zend_function* parent_function; if (ce->parent && zend_hash_quick_find(&ce->parent->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &parent_function) != FAILURE) { prototype = parent_function; /* ->common.fn_flags |= ZEND_ACC_ABSTRACT; */ /* we got that method in the parent class, and are going to override it, except, if the trait is just asking to have an abstract method implemented. */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* then we clean up an skip this method */ zend_function_dtor(fn); return ZEND_HASH_APPLY_REMOVE; } } fn->common.scope = ce; fn->common.prototype = prototype; if (prototype && (prototype->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT || prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { fn->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; } else if (fn->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT) { /* remove ZEND_ACC_IMPLEMENTED_ABSTRACT flag, think it shouldn't be copied to class */ fn->common.fn_flags = fn->common.fn_flags - ZEND_ACC_IMPLEMENTED_ABSTRACT; } /* check whether the trait method fullfills the inheritance requirements */ if (prototype) { do_inheritance_check_on_method(fn, prototype TSRMLS_CC); } /* one more thing: make sure we properly implement an abstract method */ if (existing_fn && existing_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { do_inheritance_check_on_method(fn, existing_fn TSRMLS_CC); } /* delete inherited fn if the function to be added is not abstract */ if (existing_fn && existing_fn->common.scope != ce && (fn->common.fn_flags & ZEND_ACC_ABSTRACT) == 0) { /* it is just a reference which was added to the subclass while doing the inheritance, so we can deleted now, and will add the overriding method afterwards. Except, if we try to add an abstract function, then we should not delete the inherited one */ zend_hash_quick_del(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h); } if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (fn->op_array.static_variables) { ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } fn_copy = *fn; function_add_ref(&fn_copy); if (zend_hash_quick_update(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, &fn_copy, sizeof(zend_function), (void**)&fn_copy_p)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating class method table", hash_key->arKey); } zend_add_magic_methods(ce, hash_key->arKey, hash_key->nKeyLength, fn_copy_p TSRMLS_CC); zend_function_dtor(fn); } else { zend_function_dtor(fn); } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ static int zend_traits_copy_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { HashTable* target; zend_trait_alias** aliases; HashTable* exclude_table; char* lcname; unsigned int fnname_len; zend_function fn_copy; void* dummy; size_t i = 0; target = va_arg(args, HashTable*); aliases = va_arg(args, zend_trait_alias**); exclude_table = va_arg(args, HashTable*); fnname_len = strlen(fn->common.function_name); /* apply aliases which are qualified with a class name, there should not be any ambiguity */ if (aliases) { while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias != NULL && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && aliases[i]->trait_method->mname_len == fnname_len && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy = *fn; function_add_ref(&fn_copy); /* this function_name is never destroyed, because its refcount greater than 1, classes are always destoyed in reverse order and trait is declared early than this class */ fn_copy.common.function_name = aliases[i]->alias; /* if it is 0, no modifieres has been changed */ if (aliases[i]->modifiers) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } lcname = zend_str_tolower_dup(aliases[i]->alias, aliases[i]->alias_len); if (zend_hash_add(target, lcname, aliases[i]->alias_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add aliased trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } efree(lcname); /** Record the trait from which this alias was resolved. */ if (!aliases[i]->trait_method->ce) { aliases[i]->trait_method->ce = fn->common.scope; } } i++; } } lcname = zend_str_tolower_dup(fn->common.function_name, fnname_len); if (exclude_table == NULL || zend_hash_find(exclude_table, lcname, fnname_len, &dummy) == FAILURE) { /* is not in hashtable, thus, function is not to be excluded */ fn_copy = *fn; function_add_ref(&fn_copy); /* apply aliases which are not qualified by a class name, or which have not * alias name, just setting visibility */ if (aliases) { i = 0; while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias == NULL && aliases[i]->modifiers != 0 && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && (aliases[i]->trait_method->mname_len == fnname_len) && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); /** Record the trait from which this alias was resolved. */ if (!aliases[i]->trait_method->ce) { aliases[i]->trait_method->ce = fn->common.scope; } } i++; } } if (zend_hash_add(target, lcname, fnname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } } efree(lcname); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* Copies function table entries to target function table with applied aliasing */ static void zend_traits_copy_trait_function_table(HashTable *target, HashTable *source, zend_trait_alias** aliases, HashTable* exclude_table TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_arguments(source TSRMLS_CC, (apply_func_args_t)zend_traits_copy_functions, 3, target, aliases, exclude_table); } /* }}} */ static void zend_traits_init_trait_structures(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i, j = 0; zend_trait_precedence *cur_precedence; zend_trait_method_reference *cur_method_ref; char *lcname; zend_bool method_exists; /* resolve class references */ if (ce->trait_precedences) { i = 0; while ((cur_precedence = ce->trait_precedences[i])) { /** Resolve classes for all precedence operations. */ if (cur_precedence->exclude_from_classes) { cur_method_ref = cur_precedence->trait_method; cur_precedence->trait_method->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); /** Ensure that the prefered method is actually available. */ lcname = zend_str_tolower_dup(cur_method_ref->method_name, cur_method_ref->mname_len); method_exists = zend_hash_exists(&cur_method_ref->ce->function_table, lcname, cur_method_ref->mname_len + 1); efree(lcname); if (!method_exists) { zend_error(E_COMPILE_ERROR, "A precedence rule was defined for %s::%s but this method does not exist", cur_method_ref->ce->name, cur_method_ref->method_name); } /** With the other traits, we are more permissive. We do not give errors for those. This allows to be more defensive in such definitions. */ j = 0; while (cur_precedence->exclude_from_classes[j]) { char* class_name = (char*)cur_precedence->exclude_from_classes[j]; zend_uint name_length = strlen(class_name); cur_precedence->exclude_from_classes[j] = zend_fetch_class(class_name, name_length, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); efree(class_name); j++; } } i++; } } if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { /** For all aliases with an explicit class name, resolve the class now. */ if (ce->trait_aliases[i]->trait_method->class_name) { cur_method_ref = ce->trait_aliases[i]->trait_method; cur_method_ref->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); /** And, ensure that the referenced method is resolvable, too. */ lcname = zend_str_tolower_dup(cur_method_ref->method_name, cur_method_ref->mname_len); method_exists = zend_hash_exists(&cur_method_ref->ce->function_table, lcname, cur_method_ref->mname_len + 1); efree(lcname); if (!method_exists) { zend_error(E_COMPILE_ERROR, "An alias was defined for %s::%s but this method does not exist", cur_method_ref->ce->name, cur_method_ref->method_name); } } i++; } } } /* }}} */ static void zend_traits_compile_exclude_table(HashTable* exclude_table, zend_trait_precedence **precedences, zend_class_entry *trait) /* {{{ */ { size_t i = 0, j; if (!precedences) { return; } while (precedences[i]) { if (precedences[i]->exclude_from_classes) { j = 0; while (precedences[i]->exclude_from_classes[j]) { if (precedences[i]->exclude_from_classes[j] == trait) { zend_uint lcname_len = precedences[i]->trait_method->mname_len; char *lcname = zend_str_tolower_dup(precedences[i]->trait_method->method_name, lcname_len); if (zend_hash_add(exclude_table, lcname, lcname_len, NULL, 0, NULL) == FAILURE) { efree(lcname); zend_error(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", precedences[i]->trait_method->method_name, trait->name); } efree(lcname); } ++j; } } ++i; } } /* }}} */ static void zend_do_traits_method_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { HashTable** function_tables; HashTable* resulting_table; HashTable exclude_table; size_t i; /* prepare copies of trait function tables for combination */ function_tables = malloc(sizeof(HashTable*) * ce->num_traits); resulting_table = (HashTable *) malloc(sizeof(HashTable)); /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(resulting_table, 10, NULL, NULL, 1, 0); for (i = 0; i < ce->num_traits; i++) { function_tables[i] = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(function_tables[i], ce->traits[i]->function_table.nNumOfElements, NULL, NULL, 1, 0); if (ce->trait_precedences) { /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(&exclude_table, 2, NULL, NULL, 0, 0); zend_traits_compile_exclude_table(&exclude_table, ce->trait_precedences, ce->traits[i]); /* copies functions, applies defined aliasing, and excludes unused trait methods */ zend_traits_copy_trait_function_table(function_tables[i], &ce->traits[i]->function_table, ce->trait_aliases, &exclude_table TSRMLS_CC); zend_hash_destroy(&exclude_table); } else { zend_traits_copy_trait_function_table(function_tables[i], &ce->traits[i]->function_table, ce->trait_aliases, NULL TSRMLS_CC); } } /* now merge trait methods */ for (i = 0; i < ce->num_traits; i++) { zend_hash_apply_with_arguments(function_tables[i] TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions, 5, i, ce->num_traits, resulting_table, function_tables, ce); } /* Now the resulting_table contains all trait methods we would have to * add to the class in the following step the methods are inserted into the method table * if there is already a method with the same name it is replaced iff ce != fn.scope * --> all inherited methods are overridden, methods defined in the class are left untouched */ zend_hash_apply_with_arguments(resulting_table TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions_to_class, 1, ce); /* free temporary function tables */ for (i = 0; i < ce->num_traits; i++) { /* zend_hash_destroy(function_tables[i]); */ zend_hash_graceful_destroy(function_tables[i]); free(function_tables[i]); } free(function_tables); /* free temporary resulting table */ /* zend_hash_destroy(resulting_table); */ zend_hash_graceful_destroy(resulting_table); free(resulting_table); } /* }}} */ static zend_class_entry* find_first_definition(zend_class_entry *ce, size_t current_trait, const char* prop_name, int prop_name_length, ulong prop_hash, zend_class_entry *coliding_ce) /* {{{ */ { size_t i; zend_property_info *coliding_prop; for (i = 0; (i < current_trait) && (i < ce->num_traits); i++) { if (zend_hash_quick_find(&ce->traits[i]->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS) { return ce->traits[i]; } } return coliding_ce; } /* }}} */ static void zend_traits_register_private_property(zend_class_entry *ce, const char *name, int name_len, zend_property_info *old_info, zval *property TSRMLS_DC) /* {{{ */ { char *priv_name; int priv_name_length; const char *interned_name; zend_property_info property_info; ulong h = zend_get_hash_value(name, name_len+1); property_info = *old_info; if (old_info->flags & ZEND_ACC_STATIC) { property_info.offset = ce->default_static_members_count++; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(zval*) * ce->default_static_members_count, ce->type == ZEND_INTERNAL_CLASS); ce->default_static_members_table[property_info.offset] = property; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } else { property_info.offset = ce->default_properties_count++; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(zval*) * ce->default_properties_count, ce->type == ZEND_INTERNAL_CLASS); ce->default_properties_table[property_info.offset] = property; } zend_mangle_property_name(&priv_name, &priv_name_length, ce->name, ce->name_length, name, name_len, ce->type & ZEND_INTERNAL_CLASS); property_info.name = priv_name; property_info.name_length = priv_name_length; interned_name = zend_new_interned_string(property_info.name, property_info.name_length+1, 0 TSRMLS_CC); if (interned_name != property_info.name) { if (ce->type == ZEND_USER_CLASS) { efree((char*)property_info.name); } else { free((char*)property_info.name); } property_info.name = interned_name; } property_info.h = zend_get_hash_value(property_info.name, property_info.name_length+1); property_info.ce = ce; if (property_info.doc_comment) { property_info.doc_comment = estrndup(property_info.doc_comment, property_info.doc_comment_len); } zend_hash_quick_update(&ce->properties_info, name, name_len+1, h, &property_info, sizeof(zend_property_info), NULL); } /* }}} */ static void zend_do_traits_property_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i; zend_property_info *property_info; zend_property_info *coliding_prop; zval compare_result; const char* prop_name; int prop_name_length; ulong prop_hash; const char* class_name_unused; zend_bool not_compatible; zval* prop_value; char* doc_comment; /* In the following steps the properties are inserted into the property table * for that, a very strict approach is applied: * - check for compatibility, if not compatible with any property in class -> fatal * - if compatible, then strict notice */ for (i = 0; i < ce->num_traits; i++) { for (zend_hash_internal_pointer_reset(&ce->traits[i]->properties_info); zend_hash_get_current_data(&ce->traits[i]->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->traits[i]->properties_info)) { /* first get the unmangeld name if necessary, * then check whether the property is already there */ if ((property_info->flags & ZEND_ACC_PPP_MASK) == ZEND_ACC_PUBLIC) { prop_hash = property_info->h; prop_name = property_info->name; prop_name_length = property_info->name_length; } else { /* for private and protected we need to unmangle the names */ zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name_unused, &prop_name); prop_name_length = strlen(prop_name); prop_hash = zend_get_hash_value(prop_name, prop_name_length + 1); } /* next: check for conflicts with current class */ if (zend_hash_quick_find(&ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS) { if (coliding_prop->flags & ZEND_ACC_SHADOW) { /* this one is inherited, lets look it up in its own class */ zend_hash_quick_find(&coliding_prop->ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop); if (coliding_prop->flags & ZEND_ACC_PRIVATE) { /* private property, make the property_info.offset indenpended */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); zend_traits_register_private_property(ce, prop_name, prop_name_length, property_info, prop_value TSRMLS_CC); continue; } } if ((coliding_prop->flags & (ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC)) == (property_info->flags & (ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC))) { /* flags are identical, now the value needs to be checked */ if (property_info->flags & ZEND_ACC_STATIC) { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_static_members_table[coliding_prop->offset], ce->traits[i]->default_static_members_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } else { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_properties_table[coliding_prop->offset], ce->traits[i]->default_properties_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } } else { /* the flags are not identical, thus, we assume properties are not compatible */ not_compatible = 1; } if (not_compatible) { zend_error(E_COMPILE_ERROR, "%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } else { zend_error(E_STRICT, "%s and %s define the same property ($%s) in the composition of %s. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } } /* property not found, so lets add it */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); doc_comment = property_info->doc_comment ? estrndup(property_info->doc_comment, property_info->doc_comment_len) : NULL; zend_declare_property_ex(ce, prop_name, prop_name_length, prop_value, property_info->flags, doc_comment, property_info->doc_comment_len TSRMLS_CC); } } } /* }}} */ static void zend_do_check_for_inconsistent_traits_aliasing(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { int i = 0; zend_trait_alias* cur_alias; char* lc_method_name; if (ce->trait_aliases) { while (ce->trait_aliases[i]) { cur_alias = ce->trait_aliases[i]; /** The trait for this alias has not been resolved, this means, this alias was not applied. Abort with an error. */ if (!cur_alias->trait_method->ce) { if (cur_alias->alias) { /** Plain old inconsistency/typo/bug */ zend_error(E_COMPILE_ERROR, "An alias (%s) was defined for method %s(), but this method does not exist", cur_alias->alias, cur_alias->trait_method->method_name); } else { /** Here are two possible cases: 1) this is an attempt to modifiy the visibility of a method introduce as part of another alias. Since that seems to violate the DRY principle, we check against it and abort. 2) it is just a plain old inconsitency/typo/bug as in the case where alias is set. */ lc_method_name = zend_str_tolower_dup(cur_alias->trait_method->method_name, cur_alias->trait_method->mname_len); if (zend_hash_exists(&ce->function_table, lc_method_name, cur_alias->trait_method->mname_len+1)) { efree(lc_method_name); zend_error(E_COMPILE_ERROR, "The modifiers for the trait alias %s() need to be changed in the same statment in which the alias is defined. Error", cur_alias->trait_method->method_name); } else { efree(lc_method_name); zend_error(E_COMPILE_ERROR, "The modifiers of the trait method %s() are changed, but this method does not exist. Error", cur_alias->trait_method->method_name); } } } i++; } } } /* }}} */ ZEND_API void zend_do_bind_traits(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { if (ce->num_traits <= 0) { return; } /* complete initialization of trait strutures in ce */ zend_traits_init_trait_structures(ce TSRMLS_CC); /* first care about all methods to be flattened into the class */ zend_do_traits_method_binding(ce TSRMLS_CC); /* Aliases which have not been applied indicate typos/bugs. */ zend_do_check_for_inconsistent_traits_aliasing(ce TSRMLS_CC); /* then flatten the properties into it, to, mostly to notfiy developer about problems */ zend_do_traits_property_binding(ce TSRMLS_CC); /* verify that all abstract methods from traits have been implemented */ zend_verify_abstract_class(ce TSRMLS_CC); /* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */ if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { ce->ce_flags -= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } } /* }}} */ ZEND_API int do_bind_function(const zend_op_array *op_array, zend_op *opline, HashTable *function_table, zend_bool compile_time) /* {{{ */ { zend_function *function; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } zend_hash_quick_find(function_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void *) &function); if (zend_hash_quick_add(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), function, sizeof(zend_function), NULL)==FAILURE) { int error_level = compile_time ? E_COMPILE_ERROR : E_ERROR; zend_function *old_function; if (zend_hash_quick_find(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), (void *) &old_function)==SUCCESS && old_function->type == ZEND_USER_FUNCTION && old_function->op_array.last > 0) { zend_error(error_level, "Cannot redeclare %s() (previously declared in %s:%d)", function->common.function_name, old_function->op_array.filename, old_function->op_array.opcodes[0].lineno); } else { zend_error(error_level, "Cannot redeclare %s()", function->common.function_name); } return FAILURE; } else { (*function->op_array.refcount)++; function->op_array.static_variables = NULL; /* NULL out the unbound function */ return SUCCESS; } } /* }}} */ void zend_add_trait_precedence(znode *precedence_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_precedences, precedence_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_add_trait_alias(znode *alias_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_aliases, alias_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_prepare_reference(znode *result, znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { zend_trait_method_reference *method_ref = emalloc(sizeof(zend_trait_method_reference)); method_ref->ce = NULL; /* REM: There should not be a need for copying, zend_do_begin_class_declaration is also just using that string */ if (class_name) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); method_ref->class_name = Z_STRVAL(class_name->u.constant); method_ref->cname_len = Z_STRLEN(class_name->u.constant); } else { method_ref->class_name = NULL; method_ref->cname_len = 0; } method_ref->method_name = Z_STRVAL(method_name->u.constant); method_ref->mname_len = Z_STRLEN(method_name->u.constant); result->u.op.ptr = method_ref; result->op_type = IS_TMP_VAR; } /* }}} */ void zend_prepare_trait_alias(znode *result, znode *method_reference, znode *modifiers, znode *alias TSRMLS_DC) /* {{{ */ { zend_trait_alias *trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_alias->modifiers = Z_LVAL(modifiers->u.constant); if (Z_LVAL(modifiers->u.constant) == ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot use 'static' as method modifier"); return; } if (alias) { trait_alias->alias = Z_STRVAL(alias->u.constant); trait_alias->alias_len = Z_STRLEN(alias->u.constant); } else { trait_alias->alias = NULL; } trait_alias->function = NULL; result->u.op.ptr = trait_alias; } /* }}} */ void zend_prepare_trait_precedence(znode *result, znode *method_reference, znode *trait_list TSRMLS_DC) /* {{{ */ { zend_trait_precedence *trait_precedence = emalloc(sizeof(zend_trait_precedence)); trait_precedence->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_precedence->exclude_from_classes = (zend_class_entry**) trait_list->u.op.ptr; trait_precedence->function = NULL; result->u.op.ptr = trait_precedence; } /* }}} */ ZEND_API zend_class_entry *do_bind_class(const zend_op_array* op_array, const zend_op *opline, HashTable *class_table, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } if (zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce)==FAILURE) { zend_error(E_COMPILE_ERROR, "Internal Zend error - Missing class information for %s", Z_STRVAL_P(op1)); return NULL; } else { ce = *pce; } ce->refcount++; if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), &ce, sizeof(zend_class_entry *), NULL)==FAILURE) { ce->refcount--; if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return NULL; } else { if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLEMENT_INTERFACES))) { zend_verify_abstract_class(ce TSRMLS_CC); } return ce; } } /* }}} */ ZEND_API zend_class_entry *do_bind_inherited_class(const zend_op_array *op_array, const zend_op *opline, HashTable *class_table, zend_class_entry *parent_ce, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; int found_ce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } found_ce = zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce); if (found_ce == FAILURE) { if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", Z_STRVAL_P(op2)); } return NULL; } else { ce = *pce; } if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ce->name, parent_ce->name); } else if ((parent_ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ce->name, parent_ce->name); } zend_do_inheritance(ce, parent_ce TSRMLS_CC); ce->refcount++; /* Register the derived class */ if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), pce, sizeof(zend_class_entry *), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return ce; } /* }}} */ void zend_do_early_binding(TSRMLS_D) /* {{{ */ { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; HashTable *table; while (opline->opcode == ZEND_TICKS && opline > CG(active_op_array)->opcodes) { opline--; } switch (opline->opcode) { case ZEND_DECLARE_FUNCTION: if (do_bind_function(CG(active_op_array), opline, CG(function_table), 1) == FAILURE) { return; } table = CG(function_table); break; case ZEND_DECLARE_CLASS: if (do_bind_class(CG(active_op_array), opline, CG(class_table), 1 TSRMLS_CC) == NULL) { return; } table = CG(class_table); break; case ZEND_DECLARE_INHERITED_CLASS: { zend_op *fetch_class_opline = opline-1; zval *parent_name; zend_class_entry **pce; parent_name = &CONSTANT(fetch_class_opline->op2.constant); if ((zend_lookup_class(Z_STRVAL_P(parent_name), Z_STRLEN_P(parent_name), &pce TSRMLS_CC) == FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_CLASSES) && ((*pce)->type == ZEND_INTERNAL_CLASS))) { if (CG(compiler_options) & ZEND_COMPILE_DELAYED_BINDING) { zend_uint *opline_num = &CG(active_op_array)->early_binding; while (*opline_num != -1) { opline_num = &CG(active_op_array)->opcodes[*opline_num].result.opline_num; } *opline_num = opline - CG(active_op_array)->opcodes; opline->opcode = ZEND_DECLARE_INHERITED_CLASS_DELAYED; opline->result_type = IS_UNUSED; opline->result.opline_num = -1; } return; } if (do_bind_inherited_class(CG(active_op_array), opline, CG(class_table), *pce, 1 TSRMLS_CC) == NULL) { return; } /* clear unnecessary ZEND_FETCH_CLASS opcode */ zend_del_literal(CG(active_op_array), fetch_class_opline->op2.constant); MAKE_NOP(fetch_class_opline); table = CG(class_table); break; } case ZEND_VERIFY_ABSTRACT_CLASS: case ZEND_ADD_INTERFACE: case ZEND_ADD_TRAIT: case ZEND_BIND_TRAITS: /* We currently don't early-bind classes that implement interfaces */ /* Classes with traits are handled exactly the same, no early-bind here */ return; default: zend_error(E_COMPILE_ERROR, "Invalid binding type"); return; } zend_hash_quick_del(table, Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant)), Z_HASH_P(&CONSTANT(opline->op1.constant))); zend_del_literal(CG(active_op_array), opline->op1.constant); zend_del_literal(CG(active_op_array), opline->op2.constant); MAKE_NOP(opline); } /* }}} */ ZEND_API void zend_do_delayed_early_binding(const zend_op_array *op_array TSRMLS_DC) /* {{{ */ { if (op_array->early_binding != -1) { zend_bool orig_in_compilation = CG(in_compilation); zend_uint opline_num = op_array->early_binding; zend_class_entry **pce; CG(in_compilation) = 1; while (opline_num != -1) { if (zend_lookup_class(Z_STRVAL_P(op_array->opcodes[opline_num-1].op2.zv), Z_STRLEN_P(op_array->opcodes[opline_num-1].op2.zv), &pce TSRMLS_CC) == SUCCESS) { do_bind_inherited_class(op_array, &op_array->opcodes[opline_num], EG(class_table), *pce, 0 TSRMLS_CC); } opline_num = op_array->opcodes[opline_num].result.opline_num; } CG(in_compilation) = orig_in_compilation; } } /* }}} */ void zend_do_boolean_or_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_or_end(znode *result, const znode *expr1, const znode *expr2, znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_boolean_and_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_and_end(znode *result, const znode *expr1, const znode *expr2, const znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_do_while_begin(TSRMLS_D) /* {{{ */ { do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_do_while_end(const znode *do_token, const znode *expr_open_bracket, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ; SET_NODE(opline->op1, expr); opline->op2.opline_num = do_token->u.op.opline_num; SET_UNUSED(opline->op2); do_end_loop(expr_open_bracket->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_brk_cont(zend_uchar op, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->op1.opline_num = CG(context).current_brk_cont; SET_UNUSED(opline->op1); if (expr) { if (expr->op_type != IS_CONST) { zend_error(E_COMPILE_ERROR, "'%s' operator with non-constant operand is no longer supported", op == ZEND_BRK ? "break" : "continue"); } else if (Z_TYPE(expr->u.constant) != IS_LONG || Z_LVAL(expr->u.constant) < 1) { zend_error(E_COMPILE_ERROR, "'%s' operator accepts only positive numbers", op == ZEND_BRK ? "break" : "continue"); } SET_NODE(opline->op2, expr); } else { LITERAL_LONG(opline->op2, 1); opline->op2_type = IS_CONST; } } /* }}} */ void zend_do_switch_cond(const znode *cond TSRMLS_DC) /* {{{ */ { zend_switch_entry switch_entry; switch_entry.cond = *cond; switch_entry.default_case = -1; switch_entry.control_var = -1; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_switch_end(const znode *case_list TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); /* add code to jmp to default case */ if (switch_entry_ptr->default_case != -1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->op1.opline_num = switch_entry_ptr->default_case; } if (case_list->op_type != IS_UNUSED) { /* non-empty switch */ int next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* remember break/continue loop information */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; if (switch_entry_ptr->cond.op_type==IS_VAR || switch_entry_ptr->cond.op_type==IS_TMP_VAR) { /* emit free for the switch condition*/ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry_ptr->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_UNUSED(opline->op2); } if (switch_entry_ptr->cond.op_type == IS_CONST) { zval_dtor(&switch_entry_ptr->cond.u.constant); } zend_stack_del_top(&CG(switch_cond_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_case_before_statement(const znode *case_list, znode *case_token, const znode *case_expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); int next_op_number; zend_switch_entry *switch_entry_ptr; znode result; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); if (switch_entry_ptr->control_var == -1) { switch_entry_ptr->control_var = get_temporary_variable(CG(active_op_array)); } opline->opcode = ZEND_CASE; opline->result.var = switch_entry_ptr->control_var; opline->result_type = IS_TMP_VAR; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_NODE(opline->op2, case_expr); if (opline->op1_type == IS_CONST) { zval_copy_ctor(&CONSTANT(opline->op1.constant)); } GET_NODE(&result, opline->result); next_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, &result); SET_UNUSED(opline->op2); case_token->u.op.opline_num = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_case_after_statement(znode *result, const znode *case_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); result->u.op.opline_num = next_op_number; switch (CG(active_op_array)->opcodes[case_token->u.op.opline_num].opcode) { case ZEND_JMP: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); break; case ZEND_JMPZ: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); break; } } /* }}} */ void zend_do_default_before_statement(const znode *case_list, znode *default_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); default_token->u.op.opline_num = next_op_number; next_op_number = get_next_op_number(CG(active_op_array)); switch_entry_ptr->default_case = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_begin_class_declaration(const znode *class_token, znode *class_name, const znode *parent_class_name TSRMLS_DC) /* {{{ */ { zend_op *opline; int doing_inheritance = 0; zend_class_entry *new_class_entry; char *lcname; int error = 0; zval **ns_name, key; if (CG(active_class_entry)) { zend_error(E_COMPILE_ERROR, "Class declarations may not be nested"); return; } lcname = zend_str_tolower_dup(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); if (!(strcmp(lcname, "self") && strcmp(lcname, "parent"))) { efree(lcname); zend_error(E_COMPILE_ERROR, "Cannot use '%s' as class name as it is reserved", Z_STRVAL(class_name->u.constant)); } /* Class name must not conflict with import names */ if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns_name) == SUCCESS) { error = 1; } if (CG(current_namespace)) { /* Prefix class name with name of current namespace */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); class_name = &tmp; efree(lcname); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); } if (error) { char *tmp = zend_str_tolower_dup(Z_STRVAL_PP(ns_name), Z_STRLEN_PP(ns_name)); if (Z_STRLEN_PP(ns_name) != Z_STRLEN(class_name->u.constant) || memcmp(tmp, lcname, Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "Cannot declare class %s because the name is already in use", Z_STRVAL(class_name->u.constant)); } efree(tmp); } new_class_entry = emalloc(sizeof(zend_class_entry)); new_class_entry->type = ZEND_USER_CLASS; new_class_entry->name = zend_new_interned_string(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1, 1 TSRMLS_CC); new_class_entry->name_length = Z_STRLEN(class_name->u.constant); zend_initialize_class_data(new_class_entry, 1 TSRMLS_CC); new_class_entry->info.user.filename = zend_get_compiled_filename(TSRMLS_C); new_class_entry->info.user.line_start = class_token->u.op.opline_num; new_class_entry->ce_flags |= class_token->EA; if (parent_class_name && parent_class_name->op_type != IS_UNUSED) { switch (parent_class_name->EA) { case ZEND_FETCH_CLASS_SELF: zend_error(E_COMPILE_ERROR, "Cannot use 'self' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_PARENT: zend_error(E_COMPILE_ERROR, "Cannot use 'parent' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use 'static' as class name as it is reserved"); break; default: break; } doing_inheritance = 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, new_class_entry->name_length TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; if (doing_inheritance) { /* Make sure a trait does not try to extend a class */ if ((new_class_entry->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "A trait (%s) cannot extend a class. Traits can only be composed from other traits with the 'use' keyword. Error", new_class_entry->name); } opline->extended_value = parent_class_name->u.op.var; opline->opcode = ZEND_DECLARE_INHERITED_CLASS; } else { opline->opcode = ZEND_DECLARE_CLASS; } LITERAL_STRINGL(opline->op2, lcname, new_class_entry->name_length, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); zend_hash_quick_update(CG(class_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &new_class_entry, sizeof(zend_class_entry *), NULL); CG(active_class_entry) = new_class_entry; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(&CG(implementing_class), opline->result); if (CG(doc_comment)) { CG(active_class_entry)->info.user.doc_comment = CG(doc_comment); CG(active_class_entry)->info.user.doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ static void do_verify_abstract_class(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_VERIFY_ABSTRACT_CLASS; SET_NODE(opline->op1, &CG(implementing_class)); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_class_declaration(const znode *class_token, const znode *parent_token TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); if (ce->constructor) { ce->constructor->common.fn_flags |= ZEND_ACC_CTOR; if (ce->constructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Constructor %s::%s() cannot be static", ce->name, ce->constructor->common.function_name); } } if (ce->destructor) { ce->destructor->common.fn_flags |= ZEND_ACC_DTOR; if (ce->destructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Destructor %s::%s() cannot be static", ce->name, ce->destructor->common.function_name); } } if (ce->clone) { ce->clone->common.fn_flags |= ZEND_ACC_CLONE; if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static", ce->name, ce->clone->common.function_name); } } ce->info.user.line_end = zend_get_compiled_lineno(TSRMLS_C); /* Check for traits and proceed like with interfaces. * The only difference will be a combined handling of them in the end. * Thus, we need another opcode here. */ if (ce->num_traits > 0) { zend_op *opline; ce->traits = NULL; ce->num_traits = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_TRAITS; /* opcode generation: */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BIND_TRAITS; SET_NODE(opline->op1, &CG(implementing_class)); } if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) && ((parent_token->op_type != IS_UNUSED) || (ce->num_interfaces > 0))) { zend_verify_abstract_class(ce TSRMLS_CC); if (ce->num_interfaces) { do_verify_abstract_class(TSRMLS_C); } } /* Inherit interfaces; reset number to zero, we need it for above check and * will restore it during actual implementation. * The ZEND_ACC_IMPLEMENT_INTERFACES flag disables double call to * zend_verify_abstract_class() */ if (ce->num_interfaces > 0) { ce->interfaces = NULL; ce->num_interfaces = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_INTERFACES; } CG(active_class_entry) = NULL; } /* }}} */ void zend_do_implements_interface(znode *interface_name TSRMLS_DC) /* {{{ */ { zend_op *opline; /* Traits can not implement interfaces */ if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface on '%s' since it is a Trait", Z_STRVAL(interface_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(interface_name->u.constant), Z_STRLEN(interface_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface name as it is reserved", Z_STRVAL(interface_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_INTERFACE; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(interface_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = (opline->extended_value & ~ZEND_FETCH_CLASS_MASK) | ZEND_FETCH_CLASS_INTERFACE; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &interface_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_interfaces++; } /* }}} */ void zend_do_implements_trait(znode *trait_name TSRMLS_DC) /* {{{ */ { zend_op *opline; if ((CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Cannot use traits inside of interfaces. %s is used in %s", Z_STRVAL(trait_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(trait_name->u.constant), Z_STRLEN(trait_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as trait name as it is reserved", Z_STRVAL(trait_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_TRAIT; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(trait_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = ZEND_FETCH_CLASS_TRAIT; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &trait_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_traits++; } /* }}} */ ZEND_API void zend_mangle_property_name(char **dest, int *dest_length, const char *src1, int src1_length, const char *src2, int src2_length, int internal) /* {{{ */ { char *prop_name; int prop_name_length; prop_name_length = 1 + src1_length + 1 + src2_length; prop_name = pemalloc(prop_name_length + 1, internal); prop_name[0] = '\0'; memcpy(prop_name + 1, src1, src1_length+1); memcpy(prop_name + 1 + src1_length + 1, src2, src2_length+1); *dest = prop_name; *dest_length = prop_name_length; } /* }}} */ static int zend_strnlen(const char* s, int maxlen) /* {{{ */ { int len = 0; while (*s++ && maxlen--) len++; return len; } /* }}} */ ZEND_API int zend_unmangle_property_name(const char *mangled_property, int len, const char **class_name, const char **prop_name) /* {{{ */ { int class_name_len; *class_name = NULL; if (mangled_property[0]!=0) { *prop_name = mangled_property; return SUCCESS; } if (len < 3 || mangled_property[1]==0) { zend_error(E_NOTICE, "Illegal member variable name"); *prop_name = mangled_property; return FAILURE; } class_name_len = zend_strnlen(mangled_property+1, --len - 1) + 1; if (class_name_len >= len || mangled_property[class_name_len]!=0) { zend_error(E_NOTICE, "Corrupt member variable name"); *prop_name = mangled_property; return FAILURE; } *class_name = mangled_property+1; *prop_name = (*class_name)+class_name_len; return SUCCESS; } /* }}} */ void zend_do_declare_property(const znode *var_name, const znode *value, zend_uint access_type TSRMLS_DC) /* {{{ */ { zval *property; zend_property_info *existing_property_info; char *comment = NULL; int comment_len = 0; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Interfaces may not include member variables"); } if (access_type & ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Properties cannot be declared abstract"); } if (access_type & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot declare property %s::$%s final, the final modifier is allowed only for methods and classes", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } if (zend_hash_find(&CG(active_class_entry)->properties_info, var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, (void **) &existing_property_info)==SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::$%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } ALLOC_ZVAL(property); if (value) { *property = value->u.constant; } else { INIT_PZVAL(property); Z_TYPE_P(property) = IS_NULL; } if (CG(doc_comment)) { comment = CG(doc_comment); comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } zend_declare_property_ex(CG(active_class_entry), zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len + 1, 0 TSRMLS_CC), var_name->u.constant.value.str.len, property, access_type, comment, comment_len TSRMLS_CC); efree(var_name->u.constant.value.str.val); } /* }}} */ void zend_do_declare_class_constant(znode *var_name, const znode *value TSRMLS_DC) /* {{{ */ { zval *property; const char *cname = NULL; int result; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed in class constants"); return; } if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Traits cannot have constants"); return; } ALLOC_ZVAL(property); *property = value->u.constant; cname = zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, 0 TSRMLS_CC); if (IS_INTERNED(cname)) { result = zend_hash_quick_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, INTERNED_HASH(cname), &property, sizeof(zval *), NULL); } else { result = zend_hash_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, &property, sizeof(zval *), NULL); } if (result == FAILURE) { FREE_ZVAL(property); zend_error(E_COMPILE_ERROR, "Cannot redefine class constant %s::%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } FREE_PNODE(var_name); if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_fetch_property(znode *result, znode *object, const znode *property TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (object->op_type == IS_CV) { if (object->u.op.var == CG(active_op_array)->this_var) { object->op_type = IS_UNUSED; /* this means $this for objects */ } } else if (fetch_list_ptr->count == 1) { zend_llist_element *le = fetch_list_ptr->head; zend_op *opline_ptr = (zend_op *) le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); SET_UNUSED(opline_ptr->op1); /* this means $this for objects */ SET_NODE(opline_ptr->op2, property); /* if it was usual fetch, we change it to object fetch */ switch (opline_ptr->opcode) { case ZEND_FETCH_W: opline_ptr->opcode = ZEND_FETCH_OBJ_W; break; case ZEND_FETCH_R: opline_ptr->opcode = ZEND_FETCH_OBJ_R; break; case ZEND_FETCH_RW: opline_ptr->opcode = ZEND_FETCH_OBJ_RW; break; case ZEND_FETCH_IS: opline_ptr->opcode = ZEND_FETCH_OBJ_IS; break; case ZEND_FETCH_UNSET: opline_ptr->opcode = ZEND_FETCH_OBJ_UNSET; break; case ZEND_FETCH_FUNC_ARG: opline_ptr->opcode = ZEND_FETCH_OBJ_FUNC_ARG; break; } if (opline_ptr->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline_ptr->op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline_ptr->op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op2.constant); } GET_NODE(result, opline_ptr->result); return; } } if (zend_is_function_or_method_call(object)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, object); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_OBJ_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, object); SET_NODE(opline.op2, property); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline.op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op2.constant); } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void zend_do_halt_compiler_register(TSRMLS_D) /* {{{ */ { char *name, *cfilename; char haltoff[] = "__COMPILER_HALT_OFFSET__"; int len, clen; if (CG(has_bracketed_namespaces) && CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "__HALT_COMPILER() can only be used from the outermost scope"); } cfilename = zend_get_compiled_filename(TSRMLS_C); clen = strlen(cfilename); zend_mangle_property_name(&name, &len, haltoff, sizeof(haltoff) - 1, cfilename, clen, 0); zend_register_long_constant(name, len+1, zend_get_scanned_file_offset(TSRMLS_C), CONST_CS, 0 TSRMLS_CC); pefree(name, 0); if (CG(in_namespace)) { zend_do_end_namespace(TSRMLS_C); } } /* }}} */ void zend_do_push_object(const znode *object TSRMLS_DC) /* {{{ */ { zend_stack_push(&CG(object_stack), object, sizeof(znode)); } /* }}} */ void zend_do_pop_object(znode *object TSRMLS_DC) /* {{{ */ { if (object) { znode *tmp; zend_stack_top(&CG(object_stack), (void **) &tmp); *object = *tmp; } zend_stack_del_top(&CG(object_stack)); } /* }}} */ void zend_do_begin_new_object(znode *new_token, znode *class_type TSRMLS_DC) /* {{{ */ { zend_op *opline; unsigned char *ptr = NULL; new_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_NEW; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, class_type); SET_UNUSED(opline->op2); zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(unsigned char *)); } /* }}} */ void zend_do_end_new_object(znode *result, const znode *new_token, const znode *argument_list TSRMLS_DC) /* {{{ */ { znode ctor_result; zend_do_end_function_call(NULL, &ctor_result, argument_list, 1, 0 TSRMLS_CC); zend_do_free(&ctor_result TSRMLS_CC); CG(active_op_array)->opcodes[new_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, CG(active_op_array)->opcodes[new_token->u.op.opline_num].result); } /* }}} */ static zend_constant* zend_get_ct_const(const zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = NULL; if (Z_STRVAL_P(const_name)[0] == '\\') { if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name), (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name)-1); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name), (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } } else if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)+1, (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name)+1, (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } if (c->flags & CONST_CT_SUBST) { return c; } if (all_internal_constants_substitution && (c->flags & CONST_PERSISTENT) && !(CG(compiler_options) & ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION) && Z_TYPE(c->value) != IS_CONSTANT && Z_TYPE(c->value) != IS_CONSTANT_ARRAY) { return c; } return NULL; } /* }}} */ static int zend_constant_ct_subst(znode *result, zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = zend_get_ct_const(const_name, all_internal_constants_substitution TSRMLS_CC); if (c) { zval_dtor(const_name); result->op_type = IS_CONST; result->u.constant = c->value; zval_copy_ctor(&result->u.constant); INIT_PZVAL(&result->u.constant); return 1; } return 0; } /* }}} */ void zend_do_fetch_constant(znode *result, znode *constant_container, znode *constant_name, int mode, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; zend_op *opline; int type; char *compound; ulong fetch_type = 0; if (constant_container) { switch (mode) { case ZEND_CT: /* this is a class constant */ type = zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant)); if (ZEND_FETCH_CLASS_STATIC == type) { zend_error(E_ERROR, "\"static::\" is not allowed in compile-time constants"); } else if (ZEND_FETCH_CLASS_DEFAULT == type) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } zend_do_build_full_name(NULL, constant_container, constant_name, 1 TSRMLS_CC); *result = *constant_container; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: if (constant_container->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant))) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } else { zend_do_fetch_class(&tmp, constant_container TSRMLS_CC); constant_container = &tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); if (constant_container->op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &constant_container->u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, constant_container); } SET_NODE(opline->op2, constant_name); CALCULATE_LITERAL_HASH(opline->op2.constant); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } GET_NODE(result, opline->result); break; } return; } /* namespace constant */ /* only one that did not contain \ from the start can be converted to string if unknown */ switch (mode) { case ZEND_CT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); /* this is a namespace constant, or an unprefixed constant */ if (zend_constant_ct_subst(result, &constant_name->u.constant, 0 TSRMLS_CC)) { break; } zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(!compound) { fetch_type |= IS_CONSTANT_UNQUALIFIED; } *result = *constant_name; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(zend_constant_ct_subst(result, &constant_name->u.constant, 1 TSRMLS_CC)) { break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; if (compound) { /* the name is unambiguous */ opline->extended_value = 0; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } else { opline->extended_value = IS_CONSTANT_UNQUALIFIED; if (CG(current_namespace)) { opline->extended_value |= IS_CONSTANT_IN_NAMESPACE; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 1 TSRMLS_CC); } else { opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } } GET_CACHE_SLOT(opline->op2.constant); break; } } /* }}} */ void zend_do_shell_exec(znode *result, const znode *cmd TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); switch (cmd->op_type) { case IS_CONST: case IS_TMP_VAR: opline->opcode = ZEND_SEND_VAL; break; default: opline->opcode = ZEND_SEND_VAR; break; } SET_NODE(opline->op1, cmd); opline->op2.opline_num = 0; opline->extended_value = ZEND_DO_FCALL; SET_UNUSED(opline->op2); /* FIXME: exception support not added to this op2 */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DO_FCALL; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; LITERAL_STRINGL(opline->op1, estrndup("shell_exec", sizeof("shell_exec")-1), sizeof("shell_exec")-1, 0); CALCULATE_LITERAL_HASH(opline->op1.constant); opline->op1_type = IS_CONST; GET_CACHE_SLOT(opline->op1.constant); opline->extended_value = 1; SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_init_array(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_ARRAY; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; GET_NODE(result, opline->result); if (expr) { SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } } else { SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_array_element(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_ARRAY_ELEMENT; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_static_array_element(znode *result, znode *offset, const znode *expr) /* {{{ */ { zval *element; ALLOC_ZVAL(element); *element = expr->u.constant; if (offset) { switch (offset->u.constant.type & IS_CONSTANT_TYPE_MASK) { case IS_CONSTANT: /* Ugly hack to denote that this value has a constant index */ Z_TYPE_P(element) |= IS_CONSTANT_INDEX; Z_STRVAL(offset->u.constant) = erealloc(Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+1] = Z_TYPE(offset->u.constant); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+2] = 0; zend_symtable_update(result->u.constant.value.ht, Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_STRING: zend_symtable_update(result->u.constant.value.ht, offset->u.constant.value.str.val, offset->u.constant.value.str.len+1, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_NULL: zend_symtable_update(Z_ARRVAL(result->u.constant), "", 1, &element, sizeof(zval *), NULL); break; case IS_LONG: case IS_BOOL: zend_hash_index_update(Z_ARRVAL(result->u.constant), Z_LVAL(offset->u.constant), &element, sizeof(zval *), NULL); break; case IS_DOUBLE: zend_hash_index_update(Z_ARRVAL(result->u.constant), zend_dval_to_lval(Z_DVAL(offset->u.constant)), &element, sizeof(zval *), NULL); break; case IS_CONSTANT_ARRAY: zend_error(E_ERROR, "Illegal offset type"); break; } } else { zend_hash_next_index_insert(Z_ARRVAL(result->u.constant), &element, sizeof(zval *), NULL); } } /* }}} */ void zend_do_add_list_element(const znode *element TSRMLS_DC) /* {{{ */ { list_llist_element lle; if (element) { zend_check_writable_variable(element); lle.var = *element; zend_llist_copy(&lle.dimensions, &CG(dimension_llist)); zend_llist_prepend_element(&CG(list_llist), &lle); } (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_new_list_begin(TSRMLS_D) /* {{{ */ { int current_dimension = 0; zend_llist_add_element(&CG(dimension_llist), &current_dimension); } /* }}} */ void zend_do_new_list_end(TSRMLS_D) /* {{{ */ { zend_llist_remove_tail(&CG(dimension_llist)); (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_list_init(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(list_stack), &CG(list_llist), sizeof(zend_llist)); zend_stack_push(&CG(list_stack), &CG(dimension_llist), sizeof(zend_llist)); zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_do_new_list_begin(TSRMLS_C); } /* }}} */ void zend_do_list_end(znode *result, znode *expr TSRMLS_DC) /* {{{ */ { zend_llist_element *le; zend_llist_element *dimension; zend_op *opline; znode last_container; le = CG(list_llist).head; while (le) { zend_llist *tmp_dimension_llist = &((list_llist_element *)le->data)->dimensions; dimension = tmp_dimension_llist->head; while (dimension) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (dimension == tmp_dimension_llist->head) { /* first */ last_container = *expr; switch (expr->op_type) { case IS_VAR: case IS_CV: opline->opcode = ZEND_FETCH_DIM_R; break; case IS_TMP_VAR: opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; case IS_CONST: /* fetch_dim_tmp_var will handle this bogus fetch */ zval_copy_ctor(&expr->u.constant); opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; } opline->extended_value |= ZEND_FETCH_ADD_LOCK; } else { opline->opcode = ZEND_FETCH_DIM_R; } opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, &last_container); opline->op2_type = IS_CONST; LITERAL_LONG(opline->op2, *((int *) dimension->data)); GET_NODE(&last_container, opline->result); dimension = dimension->next; } ((list_llist_element *) le->data)->value = last_container; zend_llist_destroy(&((list_llist_element *) le->data)->dimensions); zend_do_assign(result, &((list_llist_element *) le->data)->var, &((list_llist_element *) le->data)->value TSRMLS_CC); zend_do_free(result TSRMLS_CC); le = le->next; } zend_llist_destroy(&CG(dimension_llist)); zend_llist_destroy(&CG(list_llist)); *result = *expr; { zend_llist *p; /* restore previous lists */ zend_stack_top(&CG(list_stack), (void **) &p); CG(dimension_llist) = *p; zend_stack_del_top(&CG(list_stack)); zend_stack_top(&CG(list_stack), (void **) &p); CG(list_llist) = *p; zend_stack_del_top(&CG(list_stack)); } } /* }}} */ void zend_init_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = emalloc(sizeof(void*) * 2); list[0] = item; list[1] = NULL; *(void**)result = list; } /* }}} */ void zend_add_to_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = *(void**)result; size_t n = 0; while (list && list[n]) { n++; } list = erealloc(list, sizeof(void*) * (n+2)); list[n] = item; list[n+1] = NULL; *(void**)result = list; } /* }}} */ void zend_do_fetch_static_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zval *tmp; zend_op *opline; znode lval; znode result; ALLOC_ZVAL(tmp); if (static_assignment) { *tmp = static_assignment->u.constant; } else { INIT_ZVAL(*tmp); } if (!CG(active_op_array)->static_variables) { if (CG(active_op_array)->scope) { CG(active_op_array)->scope->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } ALLOC_HASHTABLE(CG(active_op_array)->static_variables); zend_hash_init(CG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } zend_hash_update(CG(active_op_array)->static_variables, varname->u.constant.value.str.val, varname->u.constant.value.str.len+1, &tmp, sizeof(zval *), NULL); if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (fetch_type == ZEND_FETCH_LEXICAL) ? ZEND_FETCH_R : ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_STATIC; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ if (fetch_type == ZEND_FETCH_LEXICAL) { znode dummy; zend_do_begin_variable_parse(TSRMLS_C); zend_do_assign(&dummy, &lval, &result TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } else { zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); } CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_fetch_lexical_variable(znode *varname, zend_bool is_ref TSRMLS_DC) /* {{{ */ { znode value; if (Z_STRLEN(varname->u.constant) == sizeof("this") - 1 && memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this") - 1) == 0) { zend_error(E_COMPILE_ERROR, "Cannot use $this as lexical variable"); return; } value.op_type = IS_CONST; ZVAL_NULL(&value.u.constant); Z_TYPE(value.u.constant) |= is_ref ? IS_LEXICAL_REF : IS_LEXICAL_VAR; Z_SET_REFCOUNT_P(&value.u.constant, 1); Z_UNSET_ISREF_P(&value.u.constant); zend_do_fetch_static_variable(varname, &value, is_ref ? ZEND_FETCH_STATIC : ZEND_FETCH_LEXICAL TSRMLS_CC); } /* }}} */ void zend_do_fetch_global_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zend_op *opline; znode lval; znode result; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = fetch_type; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_cast(znode *result, const znode *expr, int type TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CAST; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } /* }}} */ void zend_do_include_or_eval(int type, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_do_extended_fcall_begin(TSRMLS_C); { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INCLUDE_OR_EVAL; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } zend_do_extended_fcall_end(TSRMLS_C); } /* }}} */ void zend_do_indirect_references(znode *result, const znode *num_references, znode *variable TSRMLS_DC) /* {{{ */ { int i; zend_do_end_variable_parse(variable, BP_VAR_R, 0 TSRMLS_CC); for (i=1; i<num_references->u.constant.value.lval; i++) { fetch_simple_variable_ex(result, variable, 0, ZEND_FETCH_R TSRMLS_CC); *variable = *result; } zend_do_begin_variable_parse(TSRMLS_C); fetch_simple_variable(result, variable, 1 TSRMLS_CC); /* there is a chance someone is accessing $this */ if (CG(active_op_array)->scope && CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } /* }}} */ void zend_do_unset(const znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_UNSET_VAR; SET_NODE(opline->op1, variable); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); opline->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_UNSET: last_op->opcode = ZEND_UNSET_VAR; SET_UNUSED(last_op->result); break; case ZEND_FETCH_DIM_UNSET: last_op->opcode = ZEND_UNSET_DIM; SET_UNUSED(last_op->result); break; case ZEND_FETCH_OBJ_UNSET: last_op->opcode = ZEND_UNSET_OBJ; SET_UNUSED(last_op->result); break; } } } /* }}} */ void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_do_end_variable_parse(variable, BP_VAR_IS, 0 TSRMLS_CC); zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { last_op = get_next_op(CG(active_op_array) TSRMLS_CC); last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; SET_NODE(last_op->op1, variable); SET_UNUSED(last_op->op2); last_op->result.var = get_temporary_variable(CG(active_op_array)); last_op->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; break; case ZEND_FETCH_DIM_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_DIM_OBJ; break; case ZEND_FETCH_OBJ_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_PROP_OBJ; break; } } last_op->result_type = IS_TMP_VAR; last_op->extended_value |= type; GET_NODE(result, last_op->result); } /* }}} */ void zend_do_instanceof(znode *result, const znode *expr, const znode *class_znode, int type TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline->opcode == ZEND_FETCH_CLASS) { opline->extended_value |= ZEND_FETCH_CLASS_NO_AUTOLOAD; } } if (expr->op_type == IS_CONST) { zend_error(E_COMPILE_ERROR, "instanceof expects an object instance, constant given"); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INSTANCEOF; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_NODE(opline->op2, class_znode); GET_NODE(result, opline->result); } /* }}} */ void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_bool is_variable; zend_bool push_container = 0; zend_op dummy_opline; if (variable) { if (zend_is_function_or_method_call(array)) { is_variable = 0; } else { is_variable = 1; } /* save the location of FETCH_W instruction(s) */ open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); zend_do_end_variable_parse(array, BP_VAR_W, 0 TSRMLS_CC); if (CG(active_op_array)->last > 0 && CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) { /* Only lock the container if we are fetching from a real container and not $this */ if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1_type == IS_VAR) { CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK; push_container = 1; } } } else { is_variable = 0; open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* save the location of FE_RESET */ foreach_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* Preform array reset */ opline->opcode = ZEND_FE_RESET; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, array); SET_UNUSED(opline->op2); opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0; COPY_NODE(dummy_opline.result, opline->result); if (push_container) { COPY_NODE(dummy_opline.op1, CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1); } else { dummy_opline.op1_type = IS_UNUSED; } zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); /* save the location of FE_FETCH */ as_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FE_FETCH; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); COPY_NODE(opline->op1, dummy_opline.result); opline->extended_value = 0; SET_UNUSED(opline->op2); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_OP_DATA; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); } /* }}} */ void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC) /* {{{ */ { zend_op *opline; znode dummy, value_node; zend_bool assign_by_ref=0; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num]; if (key->op_type != IS_UNUSED) { znode *tmp; /* switch between the key and value... */ tmp = key; key = value; value = tmp; /* Mark extended_value in case both key and value are being used */ opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; } if ((key->op_type != IS_UNUSED) && (key->EA & ZEND_PARSED_REFERENCE_VARIABLE)) { zend_error(E_COMPILE_ERROR, "Key element cannot be a reference"); } if (value->EA & ZEND_PARSED_REFERENCE_VARIABLE) { assign_by_ref = 1; if (!(opline-1)->extended_value) { zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression"); } /* Mark extended_value for assign-by-reference */ opline->extended_value |= ZEND_FE_FETCH_BYREF; CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; } else { zend_op *foreach_copy; zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.op.opline_num]; zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.op.opline_num]; /* Change "write context" into "read context" */ fetch->extended_value = 0; /* reset ZEND_FE_RESET_VARIABLE */ while (fetch != end) { --fetch; if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } if (fetch->opcode == ZEND_SEPARATE) { MAKE_NOP(fetch); } else { fetch->opcode -= 3; /* FETCH_W -> FETCH_R */ } } /* prevent double SWITCH_FREE */ zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy); foreach_copy->op1_type = IS_UNUSED; } GET_NODE(&value_node, opline->result); if (assign_by_ref) { zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); /* Mark FE_FETCH as IS_VAR as it holds the data directly as a value */ zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC); } else { zend_do_assign(&dummy, value, &value_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } if (key->op_type != IS_UNUSED) { znode key_node; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num+1]; opline->result_type = IS_TMP_VAR; opline->result.opline_num = get_temporary_variable(CG(active_op_array)); GET_NODE(&key_node, opline->result); zend_do_assign(&dummy, key, &key_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_foreach_end(const znode *foreach_token, const znode *as_token TSRMLS_DC) /* {{{ */ { zend_op *container_ptr; zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = as_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_RESET */ CG(active_op_array)->opcodes[as_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_FETCH */ do_end_loop(as_token->u.op.opline_num, 1 TSRMLS_CC); zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr); generate_free_foreach_copy(container_ptr TSRMLS_CC); zend_stack_del_top(&CG(foreach_copy_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_declare_begin(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(declare_stack), &CG(declarables), sizeof(zend_declarables)); } /* }}} */ void zend_do_declare_stmt(znode *var, znode *val TSRMLS_DC) /* {{{ */ { if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "ticks", sizeof("ticks")-1)) { convert_to_long(&val->u.constant); CG(declarables).ticks = val->u.constant; } else if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "encoding", sizeof("encoding")-1)) { if ((Z_TYPE(val->u.constant) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Cannot use constants as encoding"); } /* * Check that the pragma comes before any opcodes. If the compilation * got as far as this, the previous portion of the script must have been * parseable according to the .ini script_encoding setting. We still * want to tell them to put declare() at the top. */ { int num = CG(active_op_array)->last; /* ignore ZEND_EXT_STMT and ZEND_TICKS */ while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Encoding declaration pragma must be the very first statement in the script"); } } if (CG(multibyte)) { const zend_encoding *new_encoding, *old_encoding; zend_encoding_filter old_input_filter; CG(encoding_declared) = 1; convert_to_string(&val->u.constant); new_encoding = zend_multibyte_fetch_encoding(val->u.constant.value.str.val TSRMLS_CC); if (!new_encoding) { zend_error(E_COMPILE_WARNING, "Unsupported encoding [%s]", val->u.constant.value.str.val); } else { old_input_filter = LANG_SCNG(input_filter); old_encoding = LANG_SCNG(script_encoding); zend_multibyte_set_filter(new_encoding TSRMLS_CC); /* need to re-scan if input filter changed */ if (old_input_filter != LANG_SCNG(input_filter) || (old_input_filter && new_encoding != old_encoding)) { zend_multibyte_yyinput_again(old_input_filter, old_encoding TSRMLS_CC); } } } else { zend_error(E_COMPILE_WARNING, "declare(encoding=...) ignored because Zend multibyte feature is turned off by settings"); } zval_dtor(&val->u.constant); } else { zend_error(E_COMPILE_WARNING, "Unsupported declare '%s'", var->u.constant.value.str.val); zval_dtor(&val->u.constant); } zval_dtor(&var->u.constant); } /* }}} */ void zend_do_declare_end(const znode *declare_token TSRMLS_DC) /* {{{ */ { zend_declarables *declarables; zend_stack_top(&CG(declare_stack), (void **) &declarables); /* We should restore if there was more than (current - start) - (ticks?1:0) opcodes */ if ((get_next_op_number(CG(active_op_array)) - declare_token->u.op.opline_num) - ((Z_LVAL(CG(declarables).ticks))?1:0)) { CG(declarables) = *declarables; } } /* }}} */ void zend_do_exit(znode *result, const znode *message TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXIT; SET_NODE(opline->op1, message); SET_UNUSED(opline->op2); result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_BOOL; Z_LVAL(result->u.constant) = 1; } /* }}} */ void zend_do_begin_silence(znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BEGIN_SILENCE; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); GET_NODE(strudel_token, opline->result); } /* }}} */ void zend_do_end_silence(const znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_END_SILENCE; SET_NODE(opline->op1, strudel_token); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_jmp_set(const znode *value, znode *jmp_token, znode *colon_token TSRMLS_DC) /* {{{ */ { int op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (value->op_type == IS_VAR || value->op_type == IS_CV) { opline->opcode = ZEND_JMP_SET_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_JMP_SET; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, value); SET_UNUSED(opline->op2); GET_NODE(colon_token, opline->result); jmp_token->u.op.opline_num = op_number; INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_jmp_set_else(znode *result, const znode *false_value, const znode *jmp_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, colon_token); if (colon_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].opcode = ZEND_JMP_SET_VAR; CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } opline->extended_value = 0; SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_qm_op(const znode *cond, znode *qm_token TSRMLS_DC) /* {{{ */ { int jmpz_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); SET_UNUSED(opline->op2); opline->op2.opline_num = jmpz_op_number; GET_NODE(qm_token, opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_qm_true(const znode *true_value, znode *qm_token, znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->opcodes[qm_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array))+1; /* jmp over the ZEND_JMP */ if (true_value->op_type == IS_VAR || true_value->op_type == IS_CV) { opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, true_value); SET_UNUSED(opline->op2); GET_NODE(qm_token, opline->result); colon_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_qm_false(znode *result, const znode *false_value, const znode *qm_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, qm_token); if (qm_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].opcode = ZEND_QM_ASSIGN_VAR; CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[colon_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, opline->result); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_extended_info(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_STMT; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_begin(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_BEGIN; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_end(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_END; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_ticks(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_TICKS; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->extended_value = Z_LVAL(CG(declarables).ticks); } /* }}} */ zend_bool zend_is_auto_global_quick(const char *name, uint name_len, ulong hashval TSRMLS_DC) /* {{{ */ { zend_auto_global *auto_global; ulong hash = hashval ? hashval : zend_hash_func(name, name_len+1); if (zend_hash_quick_find(CG(auto_globals), name, name_len+1, hash, (void **) &auto_global)==SUCCESS) { if (auto_global->armed) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } return 1; } return 0; } /* }}} */ zend_bool zend_is_auto_global(const char *name, uint name_len TSRMLS_DC) /* {{{ */ { return zend_is_auto_global_quick(name, name_len, 0 TSRMLS_CC); } /* }}} */ int zend_register_auto_global(const char *name, uint name_len, zend_bool jit, zend_auto_global_callback auto_global_callback TSRMLS_DC) /* {{{ */ { zend_auto_global auto_global; auto_global.name = zend_new_interned_string((char*)name, name_len + 1, 0 TSRMLS_CC); auto_global.name_len = name_len; auto_global.auto_global_callback = auto_global_callback; auto_global.jit = jit; return zend_hash_add(CG(auto_globals), name, name_len+1, &auto_global, sizeof(zend_auto_global), NULL); } /* }}} */ static int zend_auto_global_init(zend_auto_global *auto_global TSRMLS_DC) /* {{{ */ { if (auto_global->jit) { auto_global->armed = 1; } else if (auto_global->auto_global_callback) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } else { auto_global->armed = 0; } return 0; } /* }}} */ ZEND_API void zend_activate_auto_globals(TSRMLS_D) /* {{{ */ { zend_hash_apply(CG(auto_globals), (apply_func_t) zend_auto_global_init TSRMLS_CC); } /* }}} */ int zendlex(znode *zendlval TSRMLS_DC) /* {{{ */ { int retval; if (CG(increment_lineno)) { CG(zend_lineno)++; CG(increment_lineno) = 0; } again: Z_TYPE(zendlval->u.constant) = IS_LONG; retval = lex_scan(&zendlval->u.constant TSRMLS_CC); switch (retval) { case T_COMMENT: case T_DOC_COMMENT: case T_OPEN_TAG: case T_WHITESPACE: goto again; case T_CLOSE_TAG: if (LANG_SCNG(yy_text)[LANG_SCNG(yy_leng)-1] != '>') { CG(increment_lineno) = 1; } if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { goto again; } retval = ';'; /* implicit ; */ break; case T_OPEN_TAG_WITH_ECHO: retval = T_ECHO; break; case T_END_HEREDOC: efree(Z_STRVAL(zendlval->u.constant)); break; } INIT_PZVAL(&zendlval->u.constant); zendlval->op_type = IS_CONST; return retval; } /* }}} */ ZEND_API void zend_initialize_class_data(zend_class_entry *ce, zend_bool nullify_handlers TSRMLS_DC) /* {{{ */ { zend_bool persistent_hashes = (ce->type == ZEND_INTERNAL_CLASS) ? 1 : 0; dtor_func_t zval_ptr_dtor_func = ((persistent_hashes) ? ZVAL_INTERNAL_PTR_DTOR : ZVAL_PTR_DTOR); ce->refcount = 1; ce->ce_flags = 0; ce->default_properties_table = NULL; ce->default_static_members_table = NULL; zend_hash_init_ex(&ce->properties_info, 0, NULL, (dtor_func_t) (persistent_hashes ? zend_destroy_property_info_internal : zend_destroy_property_info), persistent_hashes, 0); zend_hash_init_ex(&ce->constants_table, 0, NULL, zval_ptr_dtor_func, persistent_hashes, 0); zend_hash_init_ex(&ce->function_table, 0, NULL, ZEND_FUNCTION_DTOR, persistent_hashes, 0); if (ce->type == ZEND_INTERNAL_CLASS) { #ifdef ZTS int n = zend_hash_num_elements(CG(class_table)); if (CG(static_members_table) && n >= CG(last_static_member)) { /* Support for run-time declaration: dl() */ CG(last_static_member) = n+1; CG(static_members_table) = realloc(CG(static_members_table), (n+1)*sizeof(zval**)); CG(static_members_table)[n] = NULL; } ce->static_members_table = (zval**)(zend_intptr_t)n; #else ce->static_members_table = NULL; #endif } else { ce->static_members_table = ce->default_static_members_table; ce->info.user.doc_comment = NULL; ce->info.user.doc_comment_len = 0; } ce->default_properties_count = 0; ce->default_static_members_count = 0; if (nullify_handlers) { ce->constructor = NULL; ce->destructor = NULL; ce->clone = NULL; ce->__get = NULL; ce->__set = NULL; ce->__unset = NULL; ce->__isset = NULL; ce->__call = NULL; ce->__callstatic = NULL; ce->__tostring = NULL; ce->create_object = NULL; ce->get_iterator = NULL; ce->iterator_funcs.funcs = NULL; ce->interface_gets_implemented = NULL; ce->get_static_method = NULL; ce->parent = NULL; ce->num_interfaces = 0; ce->interfaces = NULL; ce->num_traits = 0; ce->traits = NULL; ce->trait_aliases = NULL; ce->trait_precedences = NULL; ce->serialize = NULL; ce->unserialize = NULL; ce->serialize_func = NULL; ce->unserialize_func = NULL; if (ce->type == ZEND_INTERNAL_CLASS) { ce->info.internal.module = NULL; ce->info.internal.builtin_functions = NULL; } } } /* }}} */ int zend_get_class_fetch_type(const char *class_name, uint class_name_len) /* {{{ */ { if ((class_name_len == sizeof("self")-1) && !memcmp(class_name, "self", sizeof("self")-1)) { return ZEND_FETCH_CLASS_SELF; } else if ((class_name_len == sizeof("parent")-1) && !memcmp(class_name, "parent", sizeof("parent")-1)) { return ZEND_FETCH_CLASS_PARENT; } else if ((class_name_len == sizeof("static")-1) && !memcmp(class_name, "static", sizeof("static")-1)) { return ZEND_FETCH_CLASS_STATIC; } else { return ZEND_FETCH_CLASS_DEFAULT; } } /* }}} */ ZEND_API const char* zend_get_compiled_variable_name(const zend_op_array *op_array, zend_uint var, int* name_len) /* {{{ */ { if (name_len) { *name_len = op_array->vars[var].name_len; } return op_array->vars[var].name; } /* }}} */ void zend_do_build_namespace_name(znode *result, znode *prefix, znode *name TSRMLS_DC) /* {{{ */ { if (prefix) { *result = *prefix; if (Z_TYPE(result->u.constant) == IS_STRING && Z_STRLEN(result->u.constant) == 0) { /* namespace\ */ if (CG(current_namespace)) { znode tmp; zval_dtor(&result->u.constant); tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(result, NULL, &tmp TSRMLS_CC); } } } else { result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_STRING; Z_STRVAL(result->u.constant) = NULL; Z_STRLEN(result->u.constant) = 0; } /* prefix = result */ zend_do_build_full_name(NULL, result, name, 0 TSRMLS_CC); } /* }}} */ void zend_do_begin_namespace(const znode *name, zend_bool with_bracket TSRMLS_DC) /* {{{ */ { char *lcname; /* handle mixed syntax declaration or nested namespaces */ if (!CG(has_bracketed_namespaces)) { if (CG(current_namespace)) { /* previous namespace declarations were unbracketed */ if (with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } } } else { /* previous namespace declarations were bracketed */ if (!with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } else if (CG(current_namespace) || CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "Namespace declarations cannot be nested"); } } if (((!with_bracket && !CG(current_namespace)) || (with_bracket && !CG(has_bracketed_namespaces))) && CG(active_op_array)->last > 0) { /* ignore ZEND_EXT_STMT and ZEND_TICKS */ int num = CG(active_op_array)->last; while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Namespace declaration statement has to be the very first statement in the script"); } } CG(in_namespace) = 1; if (with_bracket) { CG(has_bracketed_namespaces) = 1; } if (name) { lcname = zend_str_tolower_dup(Z_STRVAL(name->u.constant), Z_STRLEN(name->u.constant)); if (((Z_STRLEN(name->u.constant) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN(name->u.constant) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as namespace name", Z_STRVAL(name->u.constant)); } efree(lcname); if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); } else { ALLOC_ZVAL(CG(current_namespace)); } *CG(current_namespace) = name->u.constant; } else { if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_use(znode *ns_name, znode *new_name, int is_global TSRMLS_DC) /* {{{ */ { char *lcname; zval *name, *ns, tmp; zend_bool warn = 0; zend_class_entry **pce; if (!CG(current_import)) { CG(current_import) = emalloc(sizeof(HashTable)); zend_hash_init(CG(current_import), 0, NULL, ZVAL_PTR_DTOR, 0); } ALLOC_ZVAL(ns); *ns = ns_name->u.constant; if (new_name) { name = &new_name->u.constant; } else { const char *p; /* The form "use A\B" is eqivalent to "use A\B as B". So we extract the last part of compound name to use as a new_name */ name = &tmp; p = zend_memrchr(Z_STRVAL_P(ns), '\\', Z_STRLEN_P(ns)); if (p) { ZVAL_STRING(name, p+1, 1); } else { *name = *ns; zval_copy_ctor(name); warn = !is_global && !CG(current_namespace); } } lcname = zend_str_tolower_dup(Z_STRVAL_P(name), Z_STRLEN_P(name)); if (((Z_STRLEN_P(name) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN_P(name) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because '%s' is a special class name", Z_STRVAL_P(ns), Z_STRVAL_P(name), Z_STRVAL_P(name)); } if (CG(current_namespace)) { /* Prefix import name with current namespace name to avoid conflicts with classes */ char *c_ns_name = emalloc(Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) + 1); zend_str_tolower_copy(c_ns_name, Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); c_ns_name[Z_STRLEN_P(CG(current_namespace))] = '\\'; memcpy(c_ns_name+Z_STRLEN_P(CG(current_namespace))+1, lcname, Z_STRLEN_P(name)+1); if (zend_hash_exists(CG(class_table), c_ns_name, Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name)+1)) { char *tmp2 = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) || memcmp(tmp2, c_ns_name, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(tmp2); } efree(c_ns_name); } else if (zend_hash_find(CG(class_table), lcname, Z_STRLEN_P(name)+1, (void**)&pce) == SUCCESS && (*pce)->type == ZEND_USER_CLASS && (*pce)->info.user.filename == CG(compiled_filename)) { char *c_tmp = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(name) || memcmp(c_tmp, lcname, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(c_tmp); } if (zend_hash_add(CG(current_import), lcname, Z_STRLEN_P(name)+1, &ns, sizeof(zval*), NULL) != SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } if (warn) { if (!strcmp(Z_STRVAL_P(name), "strict")) { zend_error(E_COMPILE_ERROR, "You seem to be trying to use a different language..."); } zend_error(E_WARNING, "The use statement with non-compound name '%s' has no effect", Z_STRVAL_P(name)); } efree(lcname); zval_dtor(name); } /* }}} */ void zend_do_declare_constant(znode *name, znode *value TSRMLS_DC) /* {{{ */ { zend_op *opline; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed as constants"); } if (zend_get_ct_const(&name->u.constant, 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare constant '%s'", Z_STRVAL(name->u.constant)); } if (CG(current_namespace)) { /* Prefix constant name with name of current namespace, lowercased */ znode tmp; tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); Z_STRVAL(tmp.u.constant) = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), Z_STRLEN(tmp.u.constant)); zend_do_build_namespace_name(&tmp, &tmp, name TSRMLS_CC); *name = tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DECLARE_CONST; SET_UNUSED(opline->result); SET_NODE(opline->op1, name); SET_NODE(opline->op2, value); } /* }}} */ void zend_verify_namespace(TSRMLS_D) /* {{{ */ { if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "No code may exist outside of namespace {}"); } } /* }}} */ void zend_do_end_namespace(TSRMLS_D) /* {{{ */ { CG(in_namespace) = 0; if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_end_compilation(TSRMLS_D) /* {{{ */ { CG(has_bracketed_namespaces) = 0; zend_do_end_namespace(TSRMLS_C); } /* }}} */ /* {{{ zend_dirname Returns directory name component of path */ ZEND_API size_t zend_dirname(char *path, size_t len) { register char *end = path + len - 1; unsigned int len_adjust = 0; #ifdef PHP_WIN32 /* Note that on Win32 CWD is per drive (heritage from CP/M). * This means dirname("c:foo") maps to "c:." or "c:" - which means CWD on C: drive. */ if ((2 <= len) && isalpha((int)((unsigned char *)path)[0]) && (':' == path[1])) { /* Skip over the drive spec (if any) so as not to change */ path += 2; len_adjust += 2; if (2 == len) { /* Return "c:" on Win32 for dirname("c:"). * It would be more consistent to return "c:." * but that would require making the string *longer*. */ return len; } } #elif defined(NETWARE) /* * Find the first occurence of : from the left * move the path pointer to the position just after : * increment the len_adjust to the length of path till colon character(inclusive) * If there is no character beyond : simple return len */ char *colonpos = NULL; colonpos = strchr(path, ':'); if (colonpos != NULL) { len_adjust = ((colonpos - path) + 1); path += len_adjust; if (len_adjust == len) { return len; } } #endif if (len == 0) { /* Illegal use of this function */ return 0; } /* Strip trailing slashes */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { /* The path only contained slashes */ path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } /* Strip filename */ while (end >= path && !IS_SLASH_P(end)) { end--; } if (end < path) { /* No slash found, therefore return '.' */ #ifdef NETWARE if (len_adjust == 0) { path[0] = '.'; path[1] = '\0'; return 1; /* only one character */ } else { path[0] = '\0'; return len_adjust; } #else path[0] = '.'; path[1] = '\0'; return 1 + len_adjust; #endif } /* Strip slashes which came before the file name */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } *(end+1) = '\0'; return (size_t)(end + 1 - path) + len_adjust; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2012-03-04-60dfd64bf2-34fe62619d.c
manybugs_data_76
/* * libfb - FreeBASIC's runtime library * Copyright (C) 2004-2011 The FreeBASIC development team. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * As a special exception, the copyright holders of this library give * you permission to link this library with independent modules to * produce an executable, regardless of the license terms of these * independent modules, and to copy and distribute the resulting * executable under terms of your choice, provided that you also meet, * for each linked independent module, the terms and conditions of the * license of that module. An independent module is a module which is * not derived from or based on this library. If you modify this library, * you may extend this exception to your version of the library, but * you are not obligated to do so. If you do not wish to do so, delete * this exception statement from your version. */ /* * qb_str_convto_lng.c -- QB compatible str$ routines for longint, ulongint * * obs.: the result string's len is being "faked" to appear as if it were shorter * than the one that has to be allocated to fit _itoa and _gvct buffers. * * chng: mar/2005 written [v1ctor] * */ #include <stdlib.h> #include <string.h> #include "fb.h" /*:::::*/ FBCALL FBSTRING *fb_LongintToStrQB ( long long num ) { FBSTRING *dst; /* alloc temp string */ dst = fb_hStrAllocTemp( NULL, sizeof( long long ) * 3 ); if( dst != NULL ) { /* convert */ #ifdef TARGET_WIN32 dst->data[0] = ' '; _i64toa( num, dst->data + (num >= 0? 1:0), 10 ); #else sprintf( dst->data, "% lld", num ); #endif fb_hStrSetLength( dst, strlen( dst->data ) ); } else dst = &__fb_ctx.null_desc; return dst; } /*:::::*/ FBCALL FBSTRING *fb_ULongintToStrQB ( unsigned long long num ) { FBSTRING *dst; /* alloc temp string */ dst = fb_hStrAllocTemp( NULL, sizeof( long long ) * 3 ); if( dst != NULL ) { /* convert */ #ifdef TARGET_WIN32 dst->data[0] = ' '; _ui64toa( num, dst->data + 1, 10 ); #else sprintf( dst->data, "%llu", num ); #endif fb_hStrSetLength( dst, strlen( dst->data ) ); } else dst = &__fb_ctx.null_desc; return dst; } /* * libfb - FreeBASIC's runtime library * Copyright (C) 2004-2011 The FreeBASIC development team. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * As a special exception, the copyright holders of this library give * you permission to link this library with independent modules to * produce an executable, regardless of the license terms of these * independent modules, and to copy and distribute the resulting * executable under terms of your choice, provided that you also meet, * for each linked independent module, the terms and conditions of the * license of that module. An independent module is a module which is * not derived from or based on this library. If you modify this library, * you may extend this exception to your version of the library, but * you are not obligated to do so. If you do not wish to do so, delete * this exception statement from your version. */ /* * qb_str_convto_lng.c -- QB compatible str$ routines for longint, ulongint * * obs.: the result string's len is being "faked" to appear as if it were shorter * than the one that has to be allocated to fit _itoa and _gvct buffers. * * chng: mar/2005 written [v1ctor] * */ #include <stdlib.h> #include <string.h> #include "fb.h" /*:::::*/ FBCALL FBSTRING *fb_LongintToStrQB ( long long num ) { FBSTRING *dst; /* alloc temp string */ dst = fb_hStrAllocTemp( NULL, sizeof( long long ) * 3 ); if( dst != NULL ) { /* convert */ #ifdef TARGET_WIN32 dst->data[0] = ' '; _i64toa( num, dst->data + (num >= 0? 1:0), 10 ); #else sprintf( dst->data, "% lld", num ); #endif fb_hStrSetLength( dst, strlen( dst->data ) ); } else dst = &__fb_ctx.null_desc; return dst; } /*:::::*/ FBCALL FBSTRING *fb_ULongintToStrQB ( unsigned long long num ) { FBSTRING *dst; /* alloc temp string */ dst = fb_hStrAllocTemp( NULL, sizeof( long long ) * 3 ); if( dst != NULL ) { /* convert */ #ifdef TARGET_WIN32 dst->data[0] = ' '; _ui64toa( num, dst->data + 1, 10 ); #else sprintf( dst->data, " %llu", num ); #endif fb_hStrSetLength( dst, strlen( dst->data ) ); } else dst = &__fb_ctx.null_desc; return dst; }
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/fbc_5556-5557.c
manybugs_data_77
/* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Revised: 2/18/01 BAR -- added syntax for extracting single images from * multi-image TIFF files. * * New syntax is: sourceFileName,image# * * image# ranges from 0..<n-1> where n is the # of images in the file. * There may be no white space between the comma and the filename or * image number. * * Example: tiffcp source.tif,1 destination.tif * * Copies the 2nd image in source.tif to the destination. * ***** * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ #include "tif_config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <assert.h> #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #include "tiffio.h" #ifndef HAVE_GETOPT extern int getopt(int, char**, char*); #endif #if defined(VMS) # define unlink delete #endif #define streq(a,b) (strcmp(a,b) == 0) #define strneq(a,b,n) (strncmp(a,b,n) == 0) #define TRUE 1 #define FALSE 0 static int outtiled = -1; static uint32 tilewidth; static uint32 tilelength; static uint16 config; static uint16 compression; static uint16 predictor; static uint16 fillorder; static uint16 orientation; static uint32 rowsperstrip; static uint32 g3opts; static int ignore = FALSE; /* if true, ignore read errors */ static uint32 defg3opts = (uint32) -1; static int quality = 75; /* JPEG quality */ static int jpegcolormode = JPEGCOLORMODE_RGB; static uint16 defcompression = (uint16) -1; static uint16 defpredictor = (uint16) -1; static int tiffcp(TIFF*, TIFF*); static int processCompressOptions(char*); static void usage(void); static char comma = ','; /* (default) comma separator character */ static TIFF* bias = NULL; static int pageNum = 0; static int nextSrcImage (TIFF *tif, char **imageSpec) /* seek to the next image specified in *imageSpec returns 1 if success, 0 if no more images to process *imageSpec=NULL if subsequent images should be processed in sequence */ { if (**imageSpec == comma) { /* if not @comma, we've done all images */ char *start = *imageSpec + 1; tdir_t nextImage = (tdir_t)strtol(start, imageSpec, 0); if (start == *imageSpec) nextImage = TIFFCurrentDirectory (tif); if (**imageSpec) { if (**imageSpec == comma) { /* a trailing comma denotes remaining images in sequence */ if ((*imageSpec)[1] == '\0') *imageSpec = NULL; }else{ fprintf (stderr, "Expected a %c separated image # list after %s\n", comma, TIFFFileName (tif)); exit (-4); /* syntax error */ } } if (TIFFSetDirectory (tif, nextImage)) return 1; fprintf (stderr, "%s%c%d not found!\n", TIFFFileName(tif), comma, (int) nextImage); } return 0; } static TIFF* openSrcImage (char **imageSpec) /* imageSpec points to a pointer to a filename followed by optional ,image#'s Open the TIFF file and assign *imageSpec to either NULL if there are no images specified, or a pointer to the next image number text */ { TIFF *tif; char *fn = *imageSpec; *imageSpec = strchr (fn, comma); if (*imageSpec) { /* there is at least one image number specifier */ **imageSpec = '\0'; tif = TIFFOpen (fn, "r"); /* but, ignore any single trailing comma */ if (!(*imageSpec)[1]) {*imageSpec = NULL; return tif;} if (tif) { **imageSpec = comma; /* replace the comma */ if (!nextSrcImage(tif, imageSpec)) { TIFFClose (tif); tif = NULL; } } }else tif = TIFFOpen (fn, "r"); return tif; } int main(int argc, char* argv[]) { uint16 defconfig = (uint16) -1; uint16 deffillorder = 0; uint32 deftilewidth = (uint32) -1; uint32 deftilelength = (uint32) -1; uint32 defrowsperstrip = (uint32) 0; uint64 diroff = 0; TIFF* in; TIFF* out; char mode[10]; char* mp = mode; int c; extern int optind; extern char* optarg; *mp++ = 'w'; *mp = '\0'; while ((c = getopt(argc, argv, ",:b:c:f:l:o:z:p:r:w:aistBLMC8")) != -1) switch (c) { case ',': if (optarg[0] != '=') usage(); comma = optarg[1]; break; case 'b': /* this file is bias image subtracted from others */ if (bias) { fputs ("Only 1 bias image may be specified\n", stderr); exit (-2); } { uint16 samples = (uint16) -1; char **biasFn = &optarg; bias = openSrcImage (biasFn); if (!bias) exit (-5); if (TIFFIsTiled (bias)) { fputs ("Bias image must be organized in strips\n", stderr); exit (-7); } TIFFGetField(bias, TIFFTAG_SAMPLESPERPIXEL, &samples); if (samples != 1) { fputs ("Bias image must be monochrome\n", stderr); exit (-7); } } break; case 'a': /* append to output */ mode[0] = 'a'; break; case 'c': /* compression scheme */ if (!processCompressOptions(optarg)) usage(); break; case 'f': /* fill order */ if (streq(optarg, "lsb2msb")) deffillorder = FILLORDER_LSB2MSB; else if (streq(optarg, "msb2lsb")) deffillorder = FILLORDER_MSB2LSB; else usage(); break; case 'i': /* ignore errors */ ignore = TRUE; break; case 'l': /* tile length */ outtiled = TRUE; deftilelength = atoi(optarg); break; case 'o': /* initial directory offset */ diroff = strtoul(optarg, NULL, 0); break; case 'p': /* planar configuration */ if (streq(optarg, "separate")) defconfig = PLANARCONFIG_SEPARATE; else if (streq(optarg, "contig")) defconfig = PLANARCONFIG_CONTIG; else usage(); break; case 'r': /* rows/strip */ defrowsperstrip = atol(optarg); break; case 's': /* generate stripped output */ outtiled = FALSE; break; case 't': /* generate tiled output */ outtiled = TRUE; break; case 'w': /* tile width */ outtiled = TRUE; deftilewidth = atoi(optarg); break; case 'B': *mp++ = 'b'; *mp = '\0'; break; case 'L': *mp++ = 'l'; *mp = '\0'; break; case 'M': *mp++ = 'm'; *mp = '\0'; break; case 'C': *mp++ = 'c'; *mp = '\0'; break; case '8': *mp++ = '8'; *mp = '\0'; break; case '?': usage(); /*NOTREACHED*/ } if (argc - optind < 2) usage(); out = TIFFOpen(argv[argc-1], mode); if (out == NULL) return (-2); if ((argc - optind) == 2) pageNum = -1; for (; optind < argc-1 ; optind++) { char *imageCursor = argv[optind]; in = openSrcImage (&imageCursor); if (in == NULL) return (-3); if (diroff != 0 && !TIFFSetSubDirectory(in, diroff)) { TIFFError(TIFFFileName(in), "Error, setting subdirectory at " TIFF_UINT64_FORMAT, diroff); (void) TIFFClose(out); return (1); } for (;;) { config = defconfig; compression = defcompression; predictor = defpredictor; fillorder = deffillorder; rowsperstrip = defrowsperstrip; tilewidth = deftilewidth; tilelength = deftilelength; g3opts = defg3opts; if (!tiffcp(in, out) || !TIFFWriteDirectory(out)) { TIFFClose(out); return (1); } if (imageCursor) { /* seek next image directory */ if (!nextSrcImage(in, &imageCursor)) break; }else if (!TIFFReadDirectory(in)) break; } TIFFClose(in); } TIFFClose(out); return (0); } static void processG3Options(char* cp) { if( (cp = strchr(cp, ':')) ) { if (defg3opts == (uint32) -1) defg3opts = 0; do { cp++; if (strneq(cp, "1d", 2)) defg3opts &= ~GROUP3OPT_2DENCODING; else if (strneq(cp, "2d", 2)) defg3opts |= GROUP3OPT_2DENCODING; else if (strneq(cp, "fill", 4)) defg3opts |= GROUP3OPT_FILLBITS; else usage(); } while( (cp = strchr(cp, ':')) ); } } static int processCompressOptions(char* opt) { if (streq(opt, "none")) { defcompression = COMPRESSION_NONE; } else if (streq(opt, "packbits")) { defcompression = COMPRESSION_PACKBITS; } else if (strneq(opt, "jpeg", 4)) { char* cp = strchr(opt, ':'); defcompression = COMPRESSION_JPEG; while( cp ) { if (isdigit((int)cp[1])) quality = atoi(cp+1); else if (cp[1] == 'r' ) jpegcolormode = JPEGCOLORMODE_RAW; else usage(); cp = strchr(cp+1,':'); } } else if (strneq(opt, "g3", 2)) { processG3Options(opt); defcompression = COMPRESSION_CCITTFAX3; } else if (streq(opt, "g4")) { defcompression = COMPRESSION_CCITTFAX4; } else if (strneq(opt, "lzw", 3)) { char* cp = strchr(opt, ':'); if (cp) defpredictor = atoi(cp+1); defcompression = COMPRESSION_LZW; } else if (strneq(opt, "zip", 3)) { char* cp = strchr(opt, ':'); if (cp) defpredictor = atoi(cp+1); defcompression = COMPRESSION_ADOBE_DEFLATE; } else if (strneq(opt, "jbig", 4)) { defcompression = COMPRESSION_JBIG; } else return (0); return (1); } char* stuff[] = { "usage: tiffcp [options] input... output", "where options are:", " -a append to output instead of overwriting", " -o offset set initial directory offset", " -p contig pack samples contiguously (e.g. RGBRGB...)", " -p separate store samples separately (e.g. RRR...GGG...BBB...)", " -s write output in strips", " -t write output in tiles", " -8 write BigTIFF instead of default ClassicTIFF", " -i ignore read errors", " -b file[,#] bias (dark) monochrome image to be subtracted from all others", " -,=% use % rather than , to separate image #'s (per Note below)", "", " -r # make each strip have no more than # rows", " -w # set output tile width (pixels)", " -l # set output tile length (pixels)", "", " -f lsb2msb force lsb-to-msb FillOrder for output", " -f msb2lsb force msb-to-lsb FillOrder for output", "", " -c lzw[:opts] compress output with Lempel-Ziv & Welch encoding", " -c zip[:opts] compress output with deflate encoding", " -c jpeg[:opts] compress output with JPEG encoding", " -c jbig compress output with ISO JBIG encoding", " -c packbits compress output with packbits encoding", " -c g3[:opts] compress output with CCITT Group 3 encoding", " -c g4 compress output with CCITT Group 4 encoding", " -c none use no compression algorithm on output", "", "Group 3 options:", " 1d use default CCITT Group 3 1D-encoding", " 2d use optional CCITT Group 3 2D-encoding", " fill byte-align EOL codes", "For example, -c g3:2d:fill to get G3-2D-encoded data with byte-aligned EOLs", "", "JPEG options:", " # set compression quality level (0-100, default 75)", " r output color image as RGB rather than YCbCr", "For example, -c jpeg:r:50 to get JPEG-encoded RGB data with 50% comp. quality", "", "LZW and deflate options:", " # set predictor value", "For example, -c lzw:2 to get LZW-encoded data with horizontal differencing", "", "Note that input filenames may be of the form filename,x,y,z", "where x, y, and z specify image numbers in the filename to copy.", "example: tiffcp -c none -b esp.tif,1 esp.tif,0 test.tif", " subtract 2nd image in esp.tif from 1st yielding uncompressed result test.tif", NULL }; static void usage(void) { char buf[BUFSIZ]; int i; setbuf(stderr, buf); fprintf(stderr, "%s\n\n", TIFFGetVersion()); for (i = 0; stuff[i] != NULL; i++) fprintf(stderr, "%s\n", stuff[i]); exit(-1); } #define CopyField(tag, v) \ if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v) #define CopyField2(tag, v1, v2) \ if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2) #define CopyField3(tag, v1, v2, v3) \ if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3) #define CopyField4(tag, v1, v2, v3, v4) \ if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4) static void cpTag(TIFF* in, TIFF* out, uint16 tag, uint16 count, TIFFDataType type) { switch (type) { case TIFF_SHORT: if (count == 1) { uint16 shortv; CopyField(tag, shortv); } else if (count == 2) { uint16 shortv1, shortv2; CopyField2(tag, shortv1, shortv2); } else if (count == 4) { uint16 *tr, *tg, *tb, *ta; CopyField4(tag, tr, tg, tb, ta); } else if (count == (uint16) -1) { uint16 shortv1; uint16* shortav; CopyField2(tag, shortv1, shortav); } break; case TIFF_LONG: { uint32 longv; CopyField(tag, longv); } break; case TIFF_RATIONAL: if (count == 1) { float floatv; CopyField(tag, floatv); } else if (count == (uint16) -1) { float* floatav; CopyField(tag, floatav); } break; case TIFF_ASCII: { char* stringv; CopyField(tag, stringv); } break; case TIFF_DOUBLE: if (count == 1) { double doublev; CopyField(tag, doublev); } else if (count == (uint16) -1) { double* doubleav; CopyField(tag, doubleav); } break; default: TIFFError(TIFFFileName(in), "Data type %d is not supported, tag %d skipped.", tag, type); } } static struct cpTag { uint16 tag; uint16 count; TIFFDataType type; } tags[] = { { TIFFTAG_SUBFILETYPE, 1, TIFF_LONG }, { TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT }, { TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII }, { TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII }, { TIFFTAG_MAKE, 1, TIFF_ASCII }, { TIFFTAG_MODEL, 1, TIFF_ASCII }, { TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT }, { TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT }, { TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL }, { TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL }, { TIFFTAG_PAGENAME, 1, TIFF_ASCII }, { TIFFTAG_XPOSITION, 1, TIFF_RATIONAL }, { TIFFTAG_YPOSITION, 1, TIFF_RATIONAL }, { TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT }, { TIFFTAG_SOFTWARE, 1, TIFF_ASCII }, { TIFFTAG_DATETIME, 1, TIFF_ASCII }, { TIFFTAG_ARTIST, 1, TIFF_ASCII }, { TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII }, { TIFFTAG_WHITEPOINT, (uint16) -1, TIFF_RATIONAL }, { TIFFTAG_PRIMARYCHROMATICITIES,(uint16) -1,TIFF_RATIONAL }, { TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT }, { TIFFTAG_INKSET, 1, TIFF_SHORT }, { TIFFTAG_DOTRANGE, 2, TIFF_SHORT }, { TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII }, { TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT }, { TIFFTAG_YCBCRCOEFFICIENTS, (uint16) -1,TIFF_RATIONAL }, { TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT }, { TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT }, { TIFFTAG_REFERENCEBLACKWHITE, (uint16) -1,TIFF_RATIONAL }, { TIFFTAG_EXTRASAMPLES, (uint16) -1, TIFF_SHORT }, { TIFFTAG_SMINSAMPLEVALUE, 1, TIFF_DOUBLE }, { TIFFTAG_SMAXSAMPLEVALUE, 1, TIFF_DOUBLE }, { TIFFTAG_STONITS, 1, TIFF_DOUBLE }, }; #define NTAGS (sizeof (tags) / sizeof (tags[0])) #define CopyTag(tag, count, type) cpTag(in, out, tag, count, type) typedef int (*copyFunc) (TIFF* in, TIFF* out, uint32 l, uint32 w, uint16 samplesperpixel); static copyFunc pickCopyFunc(TIFF*, TIFF*, uint16, uint16); /* PODD */ static int tiffcp(TIFF* in, TIFF* out) { uint16 bitspersample, samplesperpixel; copyFunc cf; uint32 width, length; struct cpTag* p; CopyField(TIFFTAG_IMAGEWIDTH, width); CopyField(TIFFTAG_IMAGELENGTH, length); CopyField(TIFFTAG_BITSPERSAMPLE, bitspersample); CopyField(TIFFTAG_SAMPLESPERPIXEL, samplesperpixel); if (compression != (uint16)-1) TIFFSetField(out, TIFFTAG_COMPRESSION, compression); else CopyField(TIFFTAG_COMPRESSION, compression); if (compression == COMPRESSION_JPEG) { uint16 input_compression, input_photometric; if (TIFFGetField(in, TIFFTAG_COMPRESSION, &input_compression) && input_compression == COMPRESSION_JPEG) { TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } if (TIFFGetField(in, TIFFTAG_PHOTOMETRIC, &input_photometric)) { if(input_photometric == PHOTOMETRIC_RGB) { if (jpegcolormode == JPEGCOLORMODE_RGB) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB); } else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric); } } else if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, samplesperpixel == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV); else CopyTag(TIFFTAG_PHOTOMETRIC, 1, TIFF_SHORT); if (fillorder != 0) TIFFSetField(out, TIFFTAG_FILLORDER, fillorder); else CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT); /* * Will copy `Orientation' tag from input image */ TIFFGetFieldDefaulted(in, TIFFTAG_ORIENTATION, &orientation); switch (orientation) { case ORIENTATION_BOTRIGHT: case ORIENTATION_RIGHTBOT: /* XXX */ TIFFWarning(TIFFFileName(in), "using bottom-left orientation"); orientation = ORIENTATION_BOTLEFT; /* fall thru... */ case ORIENTATION_LEFTBOT: /* XXX */ case ORIENTATION_BOTLEFT: break; case ORIENTATION_TOPRIGHT: case ORIENTATION_RIGHTTOP: /* XXX */ default: TIFFWarning(TIFFFileName(in), "using top-left orientation"); orientation = ORIENTATION_TOPLEFT; /* fall thru... */ case ORIENTATION_LEFTTOP: /* XXX */ case ORIENTATION_TOPLEFT: break; } TIFFSetField(out, TIFFTAG_ORIENTATION, orientation); /* * Choose tiles/strip for the output image according to * the command line arguments (-tiles, -strips) and the * structure of the input image. */ if (outtiled == -1) outtiled = TIFFIsTiled(in); if (outtiled) { /* * Setup output file's tile width&height. If either * is not specified, use either the value from the * input image or, if nothing is defined, use the * library default. */ if (tilewidth == (uint32) -1) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth); if (tilelength == (uint32) -1) TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength); TIFFDefaultTileSize(out, &tilewidth, &tilelength); TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth); TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength); } else { /* * RowsPerStrip is left unspecified: use either the * value from the input image or, if nothing is defined, * use the library default. */ if (rowsperstrip == (uint32) 0) { if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip)) { rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip); } if (rowsperstrip > length && rowsperstrip != (uint32)-1) rowsperstrip = length; } else if (rowsperstrip == (uint32) -1) rowsperstrip = length; TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip); } if (config != (uint16) -1) TIFFSetField(out, TIFFTAG_PLANARCONFIG, config); else CopyField(TIFFTAG_PLANARCONFIG, config); if (samplesperpixel <= 4) CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT); CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT); /* SMinSampleValue & SMaxSampleValue */ switch (compression) { case COMPRESSION_JPEG: TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality); TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode); break; case COMPRESSION_JBIG: CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII); CopyTag(TIFFTAG_FAXDCS, 1, TIFF_ASCII); break; case COMPRESSION_LZW: case COMPRESSION_ADOBE_DEFLATE: case COMPRESSION_DEFLATE: if (predictor != (uint16)-1) TIFFSetField(out, TIFFTAG_PREDICTOR, predictor); else CopyField(TIFFTAG_PREDICTOR, predictor); break; case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: if (compression == COMPRESSION_CCITTFAX3) { if (g3opts != (uint32) -1) TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts); else CopyField(TIFFTAG_GROUP3OPTIONS, g3opts); } else CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG); CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG); CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII); break; } { uint32 len32; void** data; if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data)) TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data); } { uint16 ninks; const char* inknames; if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) { TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks); if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) { int inknameslen = strlen(inknames) + 1; const char* cp = inknames; while (ninks > 1) { cp = strchr(cp, '\0'); cp++; inknameslen += (strlen(cp) + 1); ninks--; } TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames); } } } { unsigned short pg0, pg1; if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) { if (pageNum < 0) /* only one input file */ TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1); else TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0); } } for (p = tags; p < &tags[NTAGS]; p++) CopyTag(p->tag, p->count, p->type); cf = pickCopyFunc(in, out, bitspersample, samplesperpixel); return (cf ? (*cf)(in, out, length, width, samplesperpixel) : FALSE); } /* * Copy Functions. */ #define DECLAREcpFunc(x) \ static int x(TIFF* in, TIFF* out, \ uint32 imagelength, uint32 imagewidth, tsample_t spp) #define DECLAREreadFunc(x) \ static int x(TIFF* in, \ uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp) typedef int (*readFunc)(TIFF*, uint8*, uint32, uint32, tsample_t); #define DECLAREwriteFunc(x) \ static int x(TIFF* out, \ uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp) typedef int (*writeFunc)(TIFF*, uint8*, uint32, uint32, tsample_t); /* * Contig -> contig by scanline for rows/strip change. */ DECLAREcpFunc(cpContig2ContigByRow) { tdata_t buf = _TIFFmalloc(TIFFScanlineSize(in)); uint32 row; (void) imagewidth; (void) spp; for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, buf, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } if (TIFFWriteScanline(out, buf, row, 0) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } _TIFFfree(buf); return 1; bad: _TIFFfree(buf); return 0; } typedef void biasFn (void *image, void *bias, uint32 pixels); #define subtract(bits) \ static void subtract##bits (void *i, void *b, uint32 pixels)\ {\ uint##bits *image = i;\ uint##bits *bias = b;\ while (pixels--) {\ *image = *image > *bias ? *image-*bias : 0;\ image++, bias++; \ } \ } subtract(8) subtract(16) subtract(32) static biasFn *lineSubtractFn (unsigned bits) { switch (bits) { case 8: return subtract8; case 16: return subtract16; case 32: return subtract32; } return NULL; } /* * Contig -> contig by scanline while subtracting a bias image. */ DECLAREcpFunc(cpBiasedContig2Contig) { if (spp == 1) { tsize_t biasSize = TIFFScanlineSize(bias); tsize_t bufSize = TIFFScanlineSize(in); tdata_t buf, biasBuf; uint32 biasWidth = 0, biasLength = 0; TIFFGetField(bias, TIFFTAG_IMAGEWIDTH, &biasWidth); TIFFGetField(bias, TIFFTAG_IMAGELENGTH, &biasLength); if (biasSize == bufSize && imagelength == biasLength && imagewidth == biasWidth) { uint16 sampleBits = 0; biasFn *subtractLine; TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &sampleBits); subtractLine = lineSubtractFn (sampleBits); if (subtractLine) { uint32 row; buf = _TIFFmalloc(bufSize); biasBuf = _TIFFmalloc(bufSize); for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, buf, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } if (TIFFReadScanline(bias, biasBuf, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read biased scanline %lu", (unsigned long) row); goto bad; } subtractLine (buf, biasBuf, imagewidth); if (TIFFWriteScanline(out, buf, row, 0) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } _TIFFfree(buf); _TIFFfree(biasBuf); TIFFSetDirectory(bias, TIFFCurrentDirectory(bias)); /* rewind */ return 1; bad: _TIFFfree(buf); _TIFFfree(biasBuf); return 0; } else { TIFFError(TIFFFileName(in), "No support for biasing %d bit pixels\n", sampleBits); return 0; } } TIFFError(TIFFFileName(in), "Bias image %s,%d\nis not the same size as %s,%d\n", TIFFFileName(bias), TIFFCurrentDirectory(bias), TIFFFileName(in), TIFFCurrentDirectory(in)); return 0; } else { TIFFError(TIFFFileName(in), "Can't bias %s,%d as it has >1 Sample/Pixel\n", TIFFFileName(in), TIFFCurrentDirectory(in)); return 0; } } /* * Strip -> strip for change in encoding. */ DECLAREcpFunc(cpDecodedStrips) { tsize_t stripsize = TIFFStripSize(in); tdata_t buf = _TIFFmalloc(stripsize); (void) imagewidth; (void) spp; if (buf) { tstrip_t s, ns = TIFFNumberOfStrips(in); uint32 row = 0; for (s = 0; s < ns; s++) { tsize_t cc = (row + rowsperstrip > imagelength) ? TIFFVStripSize(in, imagelength - row) : stripsize; if (TIFFReadEncodedStrip(in, s, buf, cc) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read strip %lu", (unsigned long) s); goto bad; } if (TIFFWriteEncodedStrip(out, s, buf, cc) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %lu", (unsigned long) s); goto bad; } row += rowsperstrip; } _TIFFfree(buf); return 1; } else { TIFFError(TIFFFileName(in), "Error, can't allocate memory buffer of size %lu " "to read strips", (unsigned long) stripsize); return 0; } bad: _TIFFfree(buf); return 0; } /* * Separate -> separate by row for rows/strip change. */ DECLAREcpFunc(cpSeparate2SeparateByRow) { tdata_t buf = _TIFFmalloc(TIFFScanlineSize(in)); uint32 row; tsample_t s; (void) imagewidth; for (s = 0; s < spp; s++) { for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, buf, row, s) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } if (TIFFWriteScanline(out, buf, row, s) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } } _TIFFfree(buf); return 1; bad: _TIFFfree(buf); return 0; } /* * Contig -> separate by row. */ DECLAREcpFunc(cpContig2SeparateByRow) { tdata_t inbuf = _TIFFmalloc(TIFFScanlineSize(in)); tdata_t outbuf = _TIFFmalloc(TIFFScanlineSize(out)); register uint8 *inp, *outp; register uint32 n; uint32 row; tsample_t s; /* unpack channels */ for (s = 0; s < spp; s++) { for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, inbuf, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } inp = ((uint8*)inbuf) + s; outp = (uint8*)outbuf; for (n = imagewidth; n-- > 0;) { *outp++ = *inp; inp += spp; } if (TIFFWriteScanline(out, outbuf, row, s) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } } if (inbuf) _TIFFfree(inbuf); if (outbuf) _TIFFfree(outbuf); return 1; bad: if (inbuf) _TIFFfree(inbuf); if (outbuf) _TIFFfree(outbuf); return 0; } /* * Separate -> contig by row. */ DECLAREcpFunc(cpSeparate2ContigByRow) { tdata_t inbuf = _TIFFmalloc(TIFFScanlineSize(in)); tdata_t outbuf = _TIFFmalloc(TIFFScanlineSize(out)); register uint8 *inp, *outp; register uint32 n; uint32 row; tsample_t s; for (row = 0; row < imagelength; row++) { /* merge channels */ for (s = 0; s < spp; s++) { if (TIFFReadScanline(in, inbuf, row, s) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } inp = (uint8*)inbuf; outp = ((uint8*)outbuf) + s; for (n = imagewidth; n-- > 0;) { *outp = *inp++; outp += spp; } } if (TIFFWriteScanline(out, outbuf, row, 0) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } if (inbuf) _TIFFfree(inbuf); if (outbuf) _TIFFfree(outbuf); return 1; bad: if (inbuf) _TIFFfree(inbuf); if (outbuf) _TIFFfree(outbuf); return 0; } static void cpStripToTile(uint8* out, uint8* in, uint32 rows, uint32 cols, int outskew, int inskew) { while (rows-- > 0) { uint32 j = cols; while (j-- > 0) *out++ = *in++; out += outskew; in += inskew; } } static void cpContigBufToSeparateBuf(uint8* out, uint8* in, uint32 rows, uint32 cols, int outskew, int inskew, tsample_t spp, int bytes_per_sample ) { while (rows-- > 0) { uint32 j = cols; while (j-- > 0) { int n = bytes_per_sample; while( n-- ) { *out++ = *in++; } in += (spp-1) * bytes_per_sample; } out += outskew; in += inskew; } } static void cpSeparateBufToContigBuf(uint8* out, uint8* in, uint32 rows, uint32 cols, int outskew, int inskew, tsample_t spp, int bytes_per_sample) { while (rows-- > 0) { uint32 j = cols; while (j-- > 0) { int n = bytes_per_sample; while( n-- ) { *out++ = *in++; } out += (spp-1)*bytes_per_sample; } out += outskew; in += inskew; } } static int cpImage(TIFF* in, TIFF* out, readFunc fin, writeFunc fout, uint32 imagelength, uint32 imagewidth, tsample_t spp) { int status = 0; tdata_t buf = NULL; tsize_t scanlinesize = TIFFRasterScanlineSize(in); tsize_t bytes = scanlinesize * (tsize_t)imagelength; /* * XXX: Check for integer overflow. */ if (scanlinesize && imagelength && bytes / (tsize_t)imagelength == scanlinesize) { buf = _TIFFmalloc(bytes); if (buf) { if ((*fin)(in, (uint8*)buf, imagelength, imagewidth, spp)) { status = (*fout)(out, (uint8*)buf, imagelength, imagewidth, spp); } _TIFFfree(buf); } else { TIFFError(TIFFFileName(in), "Error, can't allocate space for image buffer"); } } else { TIFFError(TIFFFileName(in), "Error, no space for image buffer"); } return status; } DECLAREreadFunc(readContigStripsIntoBuffer) { tsize_t scanlinesize = TIFFScanlineSize(in); uint8* bufp = buf; uint32 row; (void) imagewidth; (void) spp; for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, (tdata_t) bufp, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); return 0; } bufp += scanlinesize; } return 1; } DECLAREreadFunc(readSeparateStripsIntoBuffer) { int status = 1; tsize_t scanlinesize = TIFFScanlineSize(in); tdata_t scanline; if (!scanlinesize) return 0; scanline = _TIFFmalloc(scanlinesize); (void) imagewidth; if (scanline) { uint8* bufp = (uint8*) buf; uint32 row; tsample_t s; for (row = 0; row < imagelength; row++) { /* merge channels */ for (s = 0; s < spp; s++) { uint8* bp = bufp + s; tsize_t n = scanlinesize; uint8* sbuf = scanline; if (TIFFReadScanline(in, scanline, row, s) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); status = 0; goto done; } while (n-- > 0) *bp = *sbuf++, bp += spp; } bufp += scanlinesize * spp; } } done: _TIFFfree(scanline); return status; } DECLAREreadFunc(readContigTilesIntoBuffer) { int status = 1; tdata_t tilebuf = _TIFFmalloc(TIFFTileSize(in)); uint32 imagew = TIFFScanlineSize(in); uint32 tilew = TIFFTileRowSize(in); int iskew = imagew - tilew; uint8* bufp = (uint8*) buf; uint32 tw, tl; uint32 row; (void) spp; if (tilebuf == 0) return 0; (void) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); (void) TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); for (row = 0; row < imagelength; row += tl) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { if (TIFFReadTile(in, tilebuf, col, row, 0, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile at %lu %lu", (unsigned long) col, (unsigned long) row); status = 0; goto done; } if (colb + tilew > imagew) { uint32 width = imagew - colb; uint32 oskew = tilew - width; cpStripToTile(bufp + colb, tilebuf, nrow, width, oskew + iskew, oskew ); } else cpStripToTile(bufp + colb, tilebuf, nrow, tilew, iskew, 0); colb += tilew; } bufp += imagew * nrow; } done: _TIFFfree(tilebuf); return status; } DECLAREreadFunc(readSeparateTilesIntoBuffer) { int status = 1; uint32 imagew = TIFFRasterScanlineSize(in); uint32 tilew = TIFFTileRowSize(in); int iskew = imagew - tilew*spp; tdata_t tilebuf = _TIFFmalloc(TIFFTileSize(in)); uint8* bufp = (uint8*) buf; uint32 tw, tl; uint32 row; uint16 bps, bytes_per_sample; if (tilebuf == 0) return 0; (void) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); (void) TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); (void) TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps); assert( bps % 8 == 0 ); bytes_per_sample = bps/8; for (row = 0; row < imagelength; row += tl) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { tsample_t s; for (s = 0; s < spp; s++) { if (TIFFReadTile(in, tilebuf, col, row, 0, s) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile at %lu %lu, " "sample %lu", (unsigned long) col, (unsigned long) row, (unsigned long) s); status = 0; goto done; } /* * Tile is clipped horizontally. Calculate * visible portion and skewing factors. */ if (colb + tilew*spp > imagew) { uint32 width = imagew - colb; int oskew = tilew*spp - width; cpSeparateBufToContigBuf( bufp+colb+s*bytes_per_sample, tilebuf, nrow, width/(spp*bytes_per_sample), oskew + iskew, oskew/spp, spp, bytes_per_sample); } else cpSeparateBufToContigBuf( bufp+colb+s*bytes_per_sample, tilebuf, nrow, tw, iskew, 0, spp, bytes_per_sample); } colb += tilew*spp; } bufp += imagew * nrow; } done: _TIFFfree(tilebuf); return status; } DECLAREwriteFunc(writeBufferToContigStrips) { uint32 row, rowsperstrip; tstrip_t strip = 0; (void) imagewidth; (void) spp; (void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); for (row = 0; row < imagelength; row += rowsperstrip) { uint32 nrows = (row+rowsperstrip > imagelength) ? imagelength-row : rowsperstrip; tsize_t stripsize = TIFFVStripSize(out, nrows); if (TIFFWriteEncodedStrip(out, strip++, buf, stripsize) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1); return 0; } buf += stripsize; } return 1; } DECLAREwriteFunc(writeBufferToSeparateStrips) { uint32 rowsize = imagewidth * spp; uint32 rowsperstrip; tdata_t obuf = _TIFFmalloc(TIFFStripSize(out)); tstrip_t strip = 0; tsample_t s; if (obuf == NULL) return (0); (void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); for (s = 0; s < spp; s++) { uint32 row; for (row = 0; row < imagelength; row += rowsperstrip) { uint32 nrows = (row+rowsperstrip > imagelength) ? imagelength-row : rowsperstrip; tsize_t stripsize = TIFFVStripSize(out, nrows); cpContigBufToSeparateBuf( obuf, (uint8*) buf + row*rowsize + s, nrows, imagewidth, 0, 0, spp, 1); if (TIFFWriteEncodedStrip(out, strip++, obuf, stripsize) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1); _TIFFfree(obuf); return 0; } } } _TIFFfree(obuf); return 1; } DECLAREwriteFunc(writeBufferToContigTiles) { uint32 imagew = TIFFScanlineSize(out); uint32 tilew = TIFFTileRowSize(out); int iskew = imagew - tilew; tdata_t obuf = _TIFFmalloc(TIFFTileSize(out)); uint8* bufp = (uint8*) buf; uint32 tl, tw; uint32 row; (void) spp; if (obuf == NULL) return 0; (void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl); (void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw); for (row = 0; row < imagelength; row += tilelength) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { /* * Tile is clipped horizontally. Calculate * visible portion and skewing factors. */ if (colb + tilew > imagew) { uint32 width = imagew - colb; int oskew = tilew - width; cpStripToTile(obuf, bufp + colb, nrow, width, oskew, oskew + iskew); } else cpStripToTile(obuf, bufp + colb, nrow, tilew, 0, iskew); if (TIFFWriteTile(out, obuf, col, row, 0, 0) < 0) { TIFFError(TIFFFileName(out), "Error, can't write tile at %lu %lu", (unsigned long) col, (unsigned long) row); _TIFFfree(obuf); return 0; } colb += tilew; } bufp += nrow * imagew; } _TIFFfree(obuf); return 1; } DECLAREwriteFunc(writeBufferToSeparateTiles) { uint32 imagew = TIFFScanlineSize(out); tsize_t tilew = TIFFTileRowSize(out); uint32 iimagew = TIFFRasterScanlineSize(out); int iskew = iimagew - tilew*spp; tdata_t obuf = _TIFFmalloc(TIFFTileSize(out)); uint8* bufp = (uint8*) buf; uint32 tl, tw; uint32 row; uint16 bps, bytes_per_sample; if (obuf == NULL) return 0; (void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl); (void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw); (void) TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps); assert( bps % 8 == 0 ); bytes_per_sample = bps/8; for (row = 0; row < imagelength; row += tl) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { tsample_t s; for (s = 0; s < spp; s++) { /* * Tile is clipped horizontally. Calculate * visible portion and skewing factors. */ if (colb + tilew > imagew) { uint32 width = (imagew - colb); int oskew = tilew - width; cpContigBufToSeparateBuf(obuf, bufp + (colb*spp) + s, nrow, width/bytes_per_sample, oskew, (oskew*spp)+iskew, spp, bytes_per_sample); } else cpContigBufToSeparateBuf(obuf, bufp + (colb*spp) + s, nrow, tilewidth, 0, iskew, spp, bytes_per_sample); if (TIFFWriteTile(out, obuf, col, row, 0, s) < 0) { TIFFError(TIFFFileName(out), "Error, can't write tile at %lu %lu " "sample %lu", (unsigned long) col, (unsigned long) row, (unsigned long) s); _TIFFfree(obuf); return 0; } } colb += tilew; } bufp += nrow * iimagew; } _TIFFfree(obuf); return 1; } /* * Contig strips -> contig tiles. */ DECLAREcpFunc(cpContigStrips2ContigTiles) { return cpImage(in, out, readContigStripsIntoBuffer, writeBufferToContigTiles, imagelength, imagewidth, spp); } /* * Contig strips -> separate tiles. */ DECLAREcpFunc(cpContigStrips2SeparateTiles) { return cpImage(in, out, readContigStripsIntoBuffer, writeBufferToSeparateTiles, imagelength, imagewidth, spp); } /* * Separate strips -> contig tiles. */ DECLAREcpFunc(cpSeparateStrips2ContigTiles) { return cpImage(in, out, readSeparateStripsIntoBuffer, writeBufferToContigTiles, imagelength, imagewidth, spp); } /* * Separate strips -> separate tiles. */ DECLAREcpFunc(cpSeparateStrips2SeparateTiles) { return cpImage(in, out, readSeparateStripsIntoBuffer, writeBufferToSeparateTiles, imagelength, imagewidth, spp); } /* * Contig strips -> contig tiles. */ DECLAREcpFunc(cpContigTiles2ContigTiles) { return cpImage(in, out, readContigTilesIntoBuffer, writeBufferToContigTiles, imagelength, imagewidth, spp); } /* * Contig tiles -> separate tiles. */ DECLAREcpFunc(cpContigTiles2SeparateTiles) { return cpImage(in, out, readContigTilesIntoBuffer, writeBufferToSeparateTiles, imagelength, imagewidth, spp); } /* * Separate tiles -> contig tiles. */ DECLAREcpFunc(cpSeparateTiles2ContigTiles) { return cpImage(in, out, readSeparateTilesIntoBuffer, writeBufferToContigTiles, imagelength, imagewidth, spp); } /* * Separate tiles -> separate tiles (tile dimension change). */ DECLAREcpFunc(cpSeparateTiles2SeparateTiles) { return cpImage(in, out, readSeparateTilesIntoBuffer, writeBufferToSeparateTiles, imagelength, imagewidth, spp); } /* * Contig tiles -> contig tiles (tile dimension change). */ DECLAREcpFunc(cpContigTiles2ContigStrips) { return cpImage(in, out, readContigTilesIntoBuffer, writeBufferToContigStrips, imagelength, imagewidth, spp); } /* * Contig tiles -> separate strips. */ DECLAREcpFunc(cpContigTiles2SeparateStrips) { return cpImage(in, out, readContigTilesIntoBuffer, writeBufferToSeparateStrips, imagelength, imagewidth, spp); } /* * Separate tiles -> contig strips. */ DECLAREcpFunc(cpSeparateTiles2ContigStrips) { return cpImage(in, out, readSeparateTilesIntoBuffer, writeBufferToContigStrips, imagelength, imagewidth, spp); } /* * Separate tiles -> separate strips. */ DECLAREcpFunc(cpSeparateTiles2SeparateStrips) { return cpImage(in, out, readSeparateTilesIntoBuffer, writeBufferToSeparateStrips, imagelength, imagewidth, spp); } /* * Select the appropriate copy function to use. */ static copyFunc pickCopyFunc(TIFF* in, TIFF* out, uint16 bitspersample, uint16 samplesperpixel) { uint16 shortv; uint32 w, l, tw, tl; int bychunk; (void) TIFFGetField(in, TIFFTAG_PLANARCONFIG, &shortv); if (shortv != config && bitspersample != 8 && samplesperpixel > 1) { fprintf(stderr, "%s: Cannot handle different planar configuration w/ bits/sample != 8\n", TIFFFileName(in)); return (NULL); } TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &w); TIFFGetField(in, TIFFTAG_IMAGELENGTH, &l); if (!(TIFFIsTiled(out) || TIFFIsTiled(in))) { uint32 irps = (uint32) -1L; TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &irps); /* if biased, force decoded copying to allow image subtraction */ bychunk = !bias && (rowsperstrip == irps); }else{ /* either in or out is tiled */ if (bias) { fprintf(stderr, "%s: Cannot handle tiled configuration w/bias image\n", TIFFFileName(in)); return (NULL); } if (TIFFIsTiled(out)) { if (!TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw)) tw = w; if (!TIFFGetField(in, TIFFTAG_TILELENGTH, &tl)) tl = l; bychunk = (tw == tilewidth && tl == tilelength); } else { /* out's not, so in must be tiled */ TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); bychunk = (tw == w && tl == rowsperstrip); } } #define T 1 #define F 0 #define pack(a,b,c,d,e) ((long)(((a)<<11)|((b)<<3)|((c)<<2)|((d)<<1)|(e))) switch(pack(shortv,config,TIFFIsTiled(in),TIFFIsTiled(out),bychunk)) { /* Strips -> Tiles */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,T): return cpContigStrips2ContigTiles; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,T): return cpContigStrips2SeparateTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,T): return cpSeparateStrips2ContigTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,T): return cpSeparateStrips2SeparateTiles; /* Tiles -> Tiles */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,T): return cpContigTiles2ContigTiles; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,T): return cpContigTiles2SeparateTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,T): return cpSeparateTiles2ContigTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,T): return cpSeparateTiles2SeparateTiles; /* Tiles -> Strips */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,T): return cpContigTiles2ContigStrips; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,T): return cpContigTiles2SeparateStrips; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,T): return cpSeparateTiles2ContigStrips; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,T): return cpSeparateTiles2SeparateStrips; /* Strips -> Strips */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,F): return bias ? cpBiasedContig2Contig : cpContig2ContigByRow; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,T): return cpDecodedStrips; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,T): return cpContig2SeparateByRow; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,T): return cpSeparate2ContigByRow; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,T): return cpSeparate2SeparateByRow; } #undef pack #undef F #undef T fprintf(stderr, "tiffcp: %s: Don't know how to copy/convert image.\n", TIFFFileName(in)); return (NULL); } /* vim: set ts=8 sts=8 sw=8 noet: */ /* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Revised: 2/18/01 BAR -- added syntax for extracting single images from * multi-image TIFF files. * * New syntax is: sourceFileName,image# * * image# ranges from 0..<n-1> where n is the # of images in the file. * There may be no white space between the comma and the filename or * image number. * * Example: tiffcp source.tif,1 destination.tif * * Copies the 2nd image in source.tif to the destination. * ***** * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ #include "tif_config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <assert.h> #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #include "tiffio.h" #ifndef HAVE_GETOPT extern int getopt(int, char**, char*); #endif #if defined(VMS) # define unlink delete #endif #define streq(a,b) (strcmp(a,b) == 0) #define strneq(a,b,n) (strncmp(a,b,n) == 0) #define TRUE 1 #define FALSE 0 static int outtiled = -1; static uint32 tilewidth; static uint32 tilelength; static uint16 config; static uint16 compression; static uint16 predictor; static uint16 fillorder; static uint16 orientation; static uint32 rowsperstrip; static uint32 g3opts; static int ignore = FALSE; /* if true, ignore read errors */ static uint32 defg3opts = (uint32) -1; static int quality = 75; /* JPEG quality */ static int jpegcolormode = JPEGCOLORMODE_RGB; static uint16 defcompression = (uint16) -1; static uint16 defpredictor = (uint16) -1; static int tiffcp(TIFF*, TIFF*); static int processCompressOptions(char*); static void usage(void); static char comma = ','; /* (default) comma separator character */ static TIFF* bias = NULL; static int pageNum = 0; static int nextSrcImage (TIFF *tif, char **imageSpec) /* seek to the next image specified in *imageSpec returns 1 if success, 0 if no more images to process *imageSpec=NULL if subsequent images should be processed in sequence */ { if (**imageSpec == comma) { /* if not @comma, we've done all images */ char *start = *imageSpec + 1; tdir_t nextImage = (tdir_t)strtol(start, imageSpec, 0); if (start == *imageSpec) nextImage = TIFFCurrentDirectory (tif); if (**imageSpec) { if (**imageSpec == comma) { /* a trailing comma denotes remaining images in sequence */ if ((*imageSpec)[1] == '\0') *imageSpec = NULL; }else{ fprintf (stderr, "Expected a %c separated image # list after %s\n", comma, TIFFFileName (tif)); exit (-4); /* syntax error */ } } if (TIFFSetDirectory (tif, nextImage)) return 1; fprintf (stderr, "%s%c%d not found!\n", TIFFFileName(tif), comma, (int) nextImage); } return 0; } static TIFF* openSrcImage (char **imageSpec) /* imageSpec points to a pointer to a filename followed by optional ,image#'s Open the TIFF file and assign *imageSpec to either NULL if there are no images specified, or a pointer to the next image number text */ { TIFF *tif; char *fn = *imageSpec; *imageSpec = strchr (fn, comma); if (*imageSpec) { /* there is at least one image number specifier */ **imageSpec = '\0'; tif = TIFFOpen (fn, "r"); /* but, ignore any single trailing comma */ if (!(*imageSpec)[1]) {*imageSpec = NULL; return tif;} if (tif) { **imageSpec = comma; /* replace the comma */ if (!nextSrcImage(tif, imageSpec)) { TIFFClose (tif); tif = NULL; } } }else tif = TIFFOpen (fn, "r"); return tif; } int main(int argc, char* argv[]) { uint16 defconfig = (uint16) -1; uint16 deffillorder = 0; uint32 deftilewidth = (uint32) -1; uint32 deftilelength = (uint32) -1; uint32 defrowsperstrip = (uint32) 0; uint64 diroff = 0; TIFF* in; TIFF* out; char mode[10]; char* mp = mode; int c; extern int optind; extern char* optarg; *mp++ = 'w'; *mp = '\0'; while ((c = getopt(argc, argv, ",:b:c:f:l:o:z:p:r:w:aistBLMC8")) != -1) switch (c) { case ',': if (optarg[0] != '=') usage(); comma = optarg[1]; break; case 'b': /* this file is bias image subtracted from others */ if (bias) { fputs ("Only 1 bias image may be specified\n", stderr); exit (-2); } { uint16 samples = (uint16) -1; char **biasFn = &optarg; bias = openSrcImage (biasFn); if (!bias) exit (-5); if (TIFFIsTiled (bias)) { fputs ("Bias image must be organized in strips\n", stderr); exit (-7); } TIFFGetField(bias, TIFFTAG_SAMPLESPERPIXEL, &samples); if (samples != 1) { fputs ("Bias image must be monochrome\n", stderr); exit (-7); } } break; case 'a': /* append to output */ mode[0] = 'a'; break; case 'c': /* compression scheme */ if (!processCompressOptions(optarg)) usage(); break; case 'f': /* fill order */ if (streq(optarg, "lsb2msb")) deffillorder = FILLORDER_LSB2MSB; else if (streq(optarg, "msb2lsb")) deffillorder = FILLORDER_MSB2LSB; else usage(); break; case 'i': /* ignore errors */ ignore = TRUE; break; case 'l': /* tile length */ outtiled = TRUE; deftilelength = atoi(optarg); break; case 'o': /* initial directory offset */ diroff = strtoul(optarg, NULL, 0); break; case 'p': /* planar configuration */ if (streq(optarg, "separate")) defconfig = PLANARCONFIG_SEPARATE; else if (streq(optarg, "contig")) defconfig = PLANARCONFIG_CONTIG; else usage(); break; case 'r': /* rows/strip */ defrowsperstrip = atol(optarg); break; case 's': /* generate stripped output */ outtiled = FALSE; break; case 't': /* generate tiled output */ outtiled = TRUE; break; case 'w': /* tile width */ outtiled = TRUE; deftilewidth = atoi(optarg); break; case 'B': *mp++ = 'b'; *mp = '\0'; break; case 'L': *mp++ = 'l'; *mp = '\0'; break; case 'M': *mp++ = 'm'; *mp = '\0'; break; case 'C': *mp++ = 'c'; *mp = '\0'; break; case '8': *mp++ = '8'; *mp = '\0'; break; case '?': usage(); /*NOTREACHED*/ } if (argc - optind < 2) usage(); out = TIFFOpen(argv[argc-1], mode); if (out == NULL) return (-2); if ((argc - optind) == 2) pageNum = -1; for (; optind < argc-1 ; optind++) { char *imageCursor = argv[optind]; in = openSrcImage (&imageCursor); if (in == NULL) return (-3); if (diroff != 0 && !TIFFSetSubDirectory(in, diroff)) { TIFFError(TIFFFileName(in), "Error, setting subdirectory at " TIFF_UINT64_FORMAT, diroff); (void) TIFFClose(out); return (1); } for (;;) { config = defconfig; compression = defcompression; predictor = defpredictor; fillorder = deffillorder; rowsperstrip = defrowsperstrip; tilewidth = deftilewidth; tilelength = deftilelength; g3opts = defg3opts; if (!tiffcp(in, out) || !TIFFWriteDirectory(out)) { TIFFClose(out); return (1); } if (imageCursor) { /* seek next image directory */ if (!nextSrcImage(in, &imageCursor)) break; }else if (!TIFFReadDirectory(in)) break; } TIFFClose(in); } TIFFClose(out); return (0); } static void processG3Options(char* cp) { if( (cp = strchr(cp, ':')) ) { if (defg3opts == (uint32) -1) defg3opts = 0; do { cp++; if (strneq(cp, "1d", 2)) defg3opts &= ~GROUP3OPT_2DENCODING; else if (strneq(cp, "2d", 2)) defg3opts |= GROUP3OPT_2DENCODING; else if (strneq(cp, "fill", 4)) defg3opts |= GROUP3OPT_FILLBITS; else usage(); } while( (cp = strchr(cp, ':')) ); } } static int processCompressOptions(char* opt) { if (streq(opt, "none")) { defcompression = COMPRESSION_NONE; } else if (streq(opt, "packbits")) { defcompression = COMPRESSION_PACKBITS; } else if (strneq(opt, "jpeg", 4)) { char* cp = strchr(opt, ':'); defcompression = COMPRESSION_JPEG; while( cp ) { if (isdigit((int)cp[1])) quality = atoi(cp+1); else if (cp[1] == 'r' ) jpegcolormode = JPEGCOLORMODE_RAW; else usage(); cp = strchr(cp+1,':'); } } else if (strneq(opt, "g3", 2)) { processG3Options(opt); defcompression = COMPRESSION_CCITTFAX3; } else if (streq(opt, "g4")) { defcompression = COMPRESSION_CCITTFAX4; } else if (strneq(opt, "lzw", 3)) { char* cp = strchr(opt, ':'); if (cp) defpredictor = atoi(cp+1); defcompression = COMPRESSION_LZW; } else if (strneq(opt, "zip", 3)) { char* cp = strchr(opt, ':'); if (cp) defpredictor = atoi(cp+1); defcompression = COMPRESSION_ADOBE_DEFLATE; } else if (strneq(opt, "jbig", 4)) { defcompression = COMPRESSION_JBIG; } else if (strneq(opt, "sgilog", 6)) { defcompression = COMPRESSION_SGILOG; } else return (0); return (1); } char* stuff[] = { "usage: tiffcp [options] input... output", "where options are:", " -a append to output instead of overwriting", " -o offset set initial directory offset", " -p contig pack samples contiguously (e.g. RGBRGB...)", " -p separate store samples separately (e.g. RRR...GGG...BBB...)", " -s write output in strips", " -t write output in tiles", " -8 write BigTIFF instead of default ClassicTIFF", " -i ignore read errors", " -b file[,#] bias (dark) monochrome image to be subtracted from all others", " -,=% use % rather than , to separate image #'s (per Note below)", "", " -r # make each strip have no more than # rows", " -w # set output tile width (pixels)", " -l # set output tile length (pixels)", "", " -f lsb2msb force lsb-to-msb FillOrder for output", " -f msb2lsb force msb-to-lsb FillOrder for output", "", " -c lzw[:opts] compress output with Lempel-Ziv & Welch encoding", " -c zip[:opts] compress output with deflate encoding", " -c jpeg[:opts] compress output with JPEG encoding", " -c jbig compress output with ISO JBIG encoding", " -c packbits compress output with packbits encoding", " -c g3[:opts] compress output with CCITT Group 3 encoding", " -c g4 compress output with CCITT Group 4 encoding", " -c sgilog compress output with SGILOG encoding", " -c none use no compression algorithm on output", "", "Group 3 options:", " 1d use default CCITT Group 3 1D-encoding", " 2d use optional CCITT Group 3 2D-encoding", " fill byte-align EOL codes", "For example, -c g3:2d:fill to get G3-2D-encoded data with byte-aligned EOLs", "", "JPEG options:", " # set compression quality level (0-100, default 75)", " r output color image as RGB rather than YCbCr", "For example, -c jpeg:r:50 to get JPEG-encoded RGB data with 50% comp. quality", "", "LZW and deflate options:", " # set predictor value", "For example, -c lzw:2 to get LZW-encoded data with horizontal differencing", "", "Note that input filenames may be of the form filename,x,y,z", "where x, y, and z specify image numbers in the filename to copy.", "example: tiffcp -c none -b esp.tif,1 esp.tif,0 test.tif", " subtract 2nd image in esp.tif from 1st yielding uncompressed result test.tif", NULL }; static void usage(void) { char buf[BUFSIZ]; int i; setbuf(stderr, buf); fprintf(stderr, "%s\n\n", TIFFGetVersion()); for (i = 0; stuff[i] != NULL; i++) fprintf(stderr, "%s\n", stuff[i]); exit(-1); } #define CopyField(tag, v) \ if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v) #define CopyField2(tag, v1, v2) \ if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2) #define CopyField3(tag, v1, v2, v3) \ if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3) #define CopyField4(tag, v1, v2, v3, v4) \ if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4) static void cpTag(TIFF* in, TIFF* out, uint16 tag, uint16 count, TIFFDataType type) { switch (type) { case TIFF_SHORT: if (count == 1) { uint16 shortv; CopyField(tag, shortv); } else if (count == 2) { uint16 shortv1, shortv2; CopyField2(tag, shortv1, shortv2); } else if (count == 4) { uint16 *tr, *tg, *tb, *ta; CopyField4(tag, tr, tg, tb, ta); } else if (count == (uint16) -1) { uint16 shortv1; uint16* shortav; CopyField2(tag, shortv1, shortav); } break; case TIFF_LONG: { uint32 longv; CopyField(tag, longv); } break; case TIFF_RATIONAL: if (count == 1) { float floatv; CopyField(tag, floatv); } else if (count == (uint16) -1) { float* floatav; CopyField(tag, floatav); } break; case TIFF_ASCII: { char* stringv; CopyField(tag, stringv); } break; case TIFF_DOUBLE: if (count == 1) { double doublev; CopyField(tag, doublev); } else if (count == (uint16) -1) { double* doubleav; CopyField(tag, doubleav); } break; default: TIFFError(TIFFFileName(in), "Data type %d is not supported, tag %d skipped.", tag, type); } } static struct cpTag { uint16 tag; uint16 count; TIFFDataType type; } tags[] = { { TIFFTAG_SUBFILETYPE, 1, TIFF_LONG }, { TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT }, { TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII }, { TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII }, { TIFFTAG_MAKE, 1, TIFF_ASCII }, { TIFFTAG_MODEL, 1, TIFF_ASCII }, { TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT }, { TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT }, { TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL }, { TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL }, { TIFFTAG_PAGENAME, 1, TIFF_ASCII }, { TIFFTAG_XPOSITION, 1, TIFF_RATIONAL }, { TIFFTAG_YPOSITION, 1, TIFF_RATIONAL }, { TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT }, { TIFFTAG_SOFTWARE, 1, TIFF_ASCII }, { TIFFTAG_DATETIME, 1, TIFF_ASCII }, { TIFFTAG_ARTIST, 1, TIFF_ASCII }, { TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII }, { TIFFTAG_WHITEPOINT, (uint16) -1, TIFF_RATIONAL }, { TIFFTAG_PRIMARYCHROMATICITIES,(uint16) -1,TIFF_RATIONAL }, { TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT }, { TIFFTAG_INKSET, 1, TIFF_SHORT }, { TIFFTAG_DOTRANGE, 2, TIFF_SHORT }, { TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII }, { TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT }, { TIFFTAG_YCBCRCOEFFICIENTS, (uint16) -1,TIFF_RATIONAL }, { TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT }, { TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT }, { TIFFTAG_REFERENCEBLACKWHITE, (uint16) -1,TIFF_RATIONAL }, { TIFFTAG_EXTRASAMPLES, (uint16) -1, TIFF_SHORT }, { TIFFTAG_SMINSAMPLEVALUE, 1, TIFF_DOUBLE }, { TIFFTAG_SMAXSAMPLEVALUE, 1, TIFF_DOUBLE }, { TIFFTAG_STONITS, 1, TIFF_DOUBLE }, }; #define NTAGS (sizeof (tags) / sizeof (tags[0])) #define CopyTag(tag, count, type) cpTag(in, out, tag, count, type) typedef int (*copyFunc) (TIFF* in, TIFF* out, uint32 l, uint32 w, uint16 samplesperpixel); static copyFunc pickCopyFunc(TIFF*, TIFF*, uint16, uint16); /* PODD */ static int tiffcp(TIFF* in, TIFF* out) { uint16 bitspersample, samplesperpixel; copyFunc cf; uint32 width, length; struct cpTag* p; CopyField(TIFFTAG_IMAGEWIDTH, width); CopyField(TIFFTAG_IMAGELENGTH, length); CopyField(TIFFTAG_BITSPERSAMPLE, bitspersample); CopyField(TIFFTAG_SAMPLESPERPIXEL, samplesperpixel); if (compression != (uint16)-1) TIFFSetField(out, TIFFTAG_COMPRESSION, compression); else CopyField(TIFFTAG_COMPRESSION, compression); if (compression == COMPRESSION_JPEG) { uint16 input_compression, input_photometric; if (TIFFGetField(in, TIFFTAG_COMPRESSION, &input_compression) && input_compression == COMPRESSION_JPEG) { TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } if (TIFFGetField(in, TIFFTAG_PHOTOMETRIC, &input_photometric)) { if(input_photometric == PHOTOMETRIC_RGB) { if (jpegcolormode == JPEGCOLORMODE_RGB) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB); } else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric); } } else if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, samplesperpixel == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV); else CopyTag(TIFFTAG_PHOTOMETRIC, 1, TIFF_SHORT); if (fillorder != 0) TIFFSetField(out, TIFFTAG_FILLORDER, fillorder); else CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT); /* * Will copy `Orientation' tag from input image */ TIFFGetFieldDefaulted(in, TIFFTAG_ORIENTATION, &orientation); switch (orientation) { case ORIENTATION_BOTRIGHT: case ORIENTATION_RIGHTBOT: /* XXX */ TIFFWarning(TIFFFileName(in), "using bottom-left orientation"); orientation = ORIENTATION_BOTLEFT; /* fall thru... */ case ORIENTATION_LEFTBOT: /* XXX */ case ORIENTATION_BOTLEFT: break; case ORIENTATION_TOPRIGHT: case ORIENTATION_RIGHTTOP: /* XXX */ default: TIFFWarning(TIFFFileName(in), "using top-left orientation"); orientation = ORIENTATION_TOPLEFT; /* fall thru... */ case ORIENTATION_LEFTTOP: /* XXX */ case ORIENTATION_TOPLEFT: break; } TIFFSetField(out, TIFFTAG_ORIENTATION, orientation); /* * Choose tiles/strip for the output image according to * the command line arguments (-tiles, -strips) and the * structure of the input image. */ if (outtiled == -1) outtiled = TIFFIsTiled(in); if (outtiled) { /* * Setup output file's tile width&height. If either * is not specified, use either the value from the * input image or, if nothing is defined, use the * library default. */ if (tilewidth == (uint32) -1) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth); if (tilelength == (uint32) -1) TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength); TIFFDefaultTileSize(out, &tilewidth, &tilelength); TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth); TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength); } else { /* * RowsPerStrip is left unspecified: use either the * value from the input image or, if nothing is defined, * use the library default. */ if (rowsperstrip == (uint32) 0) { if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip)) { rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip); } if (rowsperstrip > length && rowsperstrip != (uint32)-1) rowsperstrip = length; } else if (rowsperstrip == (uint32) -1) rowsperstrip = length; TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip); } if (config != (uint16) -1) TIFFSetField(out, TIFFTAG_PLANARCONFIG, config); else CopyField(TIFFTAG_PLANARCONFIG, config); if (samplesperpixel <= 4) CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT); CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT); /* SMinSampleValue & SMaxSampleValue */ switch (compression) { case COMPRESSION_JPEG: TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality); TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode); break; case COMPRESSION_JBIG: CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII); CopyTag(TIFFTAG_FAXDCS, 1, TIFF_ASCII); break; case COMPRESSION_LZW: case COMPRESSION_ADOBE_DEFLATE: case COMPRESSION_DEFLATE: if (predictor != (uint16)-1) TIFFSetField(out, TIFFTAG_PREDICTOR, predictor); else CopyField(TIFFTAG_PREDICTOR, predictor); break; case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: if (compression == COMPRESSION_CCITTFAX3) { if (g3opts != (uint32) -1) TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts); else CopyField(TIFFTAG_GROUP3OPTIONS, g3opts); } else CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG); CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG); CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII); break; } { uint32 len32; void** data; if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data)) TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data); } { uint16 ninks; const char* inknames; if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) { TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks); if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) { int inknameslen = strlen(inknames) + 1; const char* cp = inknames; while (ninks > 1) { cp = strchr(cp, '\0'); cp++; inknameslen += (strlen(cp) + 1); ninks--; } TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames); } } } { unsigned short pg0, pg1; if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) { if (pageNum < 0) /* only one input file */ TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1); else TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0); } } for (p = tags; p < &tags[NTAGS]; p++) CopyTag(p->tag, p->count, p->type); cf = pickCopyFunc(in, out, bitspersample, samplesperpixel); return (cf ? (*cf)(in, out, length, width, samplesperpixel) : FALSE); } /* * Copy Functions. */ #define DECLAREcpFunc(x) \ static int x(TIFF* in, TIFF* out, \ uint32 imagelength, uint32 imagewidth, tsample_t spp) #define DECLAREreadFunc(x) \ static int x(TIFF* in, \ uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp) typedef int (*readFunc)(TIFF*, uint8*, uint32, uint32, tsample_t); #define DECLAREwriteFunc(x) \ static int x(TIFF* out, \ uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp) typedef int (*writeFunc)(TIFF*, uint8*, uint32, uint32, tsample_t); /* * Contig -> contig by scanline for rows/strip change. */ DECLAREcpFunc(cpContig2ContigByRow) { tdata_t buf = _TIFFmalloc(TIFFScanlineSize(in)); uint32 row; (void) imagewidth; (void) spp; for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, buf, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } if (TIFFWriteScanline(out, buf, row, 0) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } _TIFFfree(buf); return 1; bad: _TIFFfree(buf); return 0; } typedef void biasFn (void *image, void *bias, uint32 pixels); #define subtract(bits) \ static void subtract##bits (void *i, void *b, uint32 pixels)\ {\ uint##bits *image = i;\ uint##bits *bias = b;\ while (pixels--) {\ *image = *image > *bias ? *image-*bias : 0;\ image++, bias++; \ } \ } subtract(8) subtract(16) subtract(32) static biasFn *lineSubtractFn (unsigned bits) { switch (bits) { case 8: return subtract8; case 16: return subtract16; case 32: return subtract32; } return NULL; } /* * Contig -> contig by scanline while subtracting a bias image. */ DECLAREcpFunc(cpBiasedContig2Contig) { if (spp == 1) { tsize_t biasSize = TIFFScanlineSize(bias); tsize_t bufSize = TIFFScanlineSize(in); tdata_t buf, biasBuf; uint32 biasWidth = 0, biasLength = 0; TIFFGetField(bias, TIFFTAG_IMAGEWIDTH, &biasWidth); TIFFGetField(bias, TIFFTAG_IMAGELENGTH, &biasLength); if (biasSize == bufSize && imagelength == biasLength && imagewidth == biasWidth) { uint16 sampleBits = 0; biasFn *subtractLine; TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &sampleBits); subtractLine = lineSubtractFn (sampleBits); if (subtractLine) { uint32 row; buf = _TIFFmalloc(bufSize); biasBuf = _TIFFmalloc(bufSize); for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, buf, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } if (TIFFReadScanline(bias, biasBuf, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read biased scanline %lu", (unsigned long) row); goto bad; } subtractLine (buf, biasBuf, imagewidth); if (TIFFWriteScanline(out, buf, row, 0) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } _TIFFfree(buf); _TIFFfree(biasBuf); TIFFSetDirectory(bias, TIFFCurrentDirectory(bias)); /* rewind */ return 1; bad: _TIFFfree(buf); _TIFFfree(biasBuf); return 0; } else { TIFFError(TIFFFileName(in), "No support for biasing %d bit pixels\n", sampleBits); return 0; } } TIFFError(TIFFFileName(in), "Bias image %s,%d\nis not the same size as %s,%d\n", TIFFFileName(bias), TIFFCurrentDirectory(bias), TIFFFileName(in), TIFFCurrentDirectory(in)); return 0; } else { TIFFError(TIFFFileName(in), "Can't bias %s,%d as it has >1 Sample/Pixel\n", TIFFFileName(in), TIFFCurrentDirectory(in)); return 0; } } /* * Strip -> strip for change in encoding. */ DECLAREcpFunc(cpDecodedStrips) { tsize_t stripsize = TIFFStripSize(in); tdata_t buf = _TIFFmalloc(stripsize); (void) imagewidth; (void) spp; if (buf) { tstrip_t s, ns = TIFFNumberOfStrips(in); uint32 row = 0; for (s = 0; s < ns; s++) { tsize_t cc = (row + rowsperstrip > imagelength) ? TIFFVStripSize(in, imagelength - row) : stripsize; if (TIFFReadEncodedStrip(in, s, buf, cc) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read strip %lu", (unsigned long) s); goto bad; } if (TIFFWriteEncodedStrip(out, s, buf, cc) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %lu", (unsigned long) s); goto bad; } row += rowsperstrip; } _TIFFfree(buf); return 1; } else { TIFFError(TIFFFileName(in), "Error, can't allocate memory buffer of size %lu " "to read strips", (unsigned long) stripsize); return 0; } bad: _TIFFfree(buf); return 0; } /* * Separate -> separate by row for rows/strip change. */ DECLAREcpFunc(cpSeparate2SeparateByRow) { tdata_t buf = _TIFFmalloc(TIFFScanlineSize(in)); uint32 row; tsample_t s; (void) imagewidth; for (s = 0; s < spp; s++) { for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, buf, row, s) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } if (TIFFWriteScanline(out, buf, row, s) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } } _TIFFfree(buf); return 1; bad: _TIFFfree(buf); return 0; } /* * Contig -> separate by row. */ DECLAREcpFunc(cpContig2SeparateByRow) { tdata_t inbuf = _TIFFmalloc(TIFFScanlineSize(in)); tdata_t outbuf = _TIFFmalloc(TIFFScanlineSize(out)); register uint8 *inp, *outp; register uint32 n; uint32 row; tsample_t s; /* unpack channels */ for (s = 0; s < spp; s++) { for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, inbuf, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } inp = ((uint8*)inbuf) + s; outp = (uint8*)outbuf; for (n = imagewidth; n-- > 0;) { *outp++ = *inp; inp += spp; } if (TIFFWriteScanline(out, outbuf, row, s) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } } if (inbuf) _TIFFfree(inbuf); if (outbuf) _TIFFfree(outbuf); return 1; bad: if (inbuf) _TIFFfree(inbuf); if (outbuf) _TIFFfree(outbuf); return 0; } /* * Separate -> contig by row. */ DECLAREcpFunc(cpSeparate2ContigByRow) { tdata_t inbuf = _TIFFmalloc(TIFFScanlineSize(in)); tdata_t outbuf = _TIFFmalloc(TIFFScanlineSize(out)); register uint8 *inp, *outp; register uint32 n; uint32 row; tsample_t s; for (row = 0; row < imagelength; row++) { /* merge channels */ for (s = 0; s < spp; s++) { if (TIFFReadScanline(in, inbuf, row, s) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } inp = (uint8*)inbuf; outp = ((uint8*)outbuf) + s; for (n = imagewidth; n-- > 0;) { *outp = *inp++; outp += spp; } } if (TIFFWriteScanline(out, outbuf, row, 0) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } if (inbuf) _TIFFfree(inbuf); if (outbuf) _TIFFfree(outbuf); return 1; bad: if (inbuf) _TIFFfree(inbuf); if (outbuf) _TIFFfree(outbuf); return 0; } static void cpStripToTile(uint8* out, uint8* in, uint32 rows, uint32 cols, int outskew, int inskew) { while (rows-- > 0) { uint32 j = cols; while (j-- > 0) *out++ = *in++; out += outskew; in += inskew; } } static void cpContigBufToSeparateBuf(uint8* out, uint8* in, uint32 rows, uint32 cols, int outskew, int inskew, tsample_t spp, int bytes_per_sample ) { while (rows-- > 0) { uint32 j = cols; while (j-- > 0) { int n = bytes_per_sample; while( n-- ) { *out++ = *in++; } in += (spp-1) * bytes_per_sample; } out += outskew; in += inskew; } } static void cpSeparateBufToContigBuf(uint8* out, uint8* in, uint32 rows, uint32 cols, int outskew, int inskew, tsample_t spp, int bytes_per_sample) { while (rows-- > 0) { uint32 j = cols; while (j-- > 0) { int n = bytes_per_sample; while( n-- ) { *out++ = *in++; } out += (spp-1)*bytes_per_sample; } out += outskew; in += inskew; } } static int cpImage(TIFF* in, TIFF* out, readFunc fin, writeFunc fout, uint32 imagelength, uint32 imagewidth, tsample_t spp) { int status = 0; tdata_t buf = NULL; tsize_t scanlinesize = TIFFRasterScanlineSize(in); tsize_t bytes = scanlinesize * (tsize_t)imagelength; /* * XXX: Check for integer overflow. */ if (scanlinesize && imagelength && bytes / (tsize_t)imagelength == scanlinesize) { buf = _TIFFmalloc(bytes); if (buf) { if ((*fin)(in, (uint8*)buf, imagelength, imagewidth, spp)) { status = (*fout)(out, (uint8*)buf, imagelength, imagewidth, spp); } _TIFFfree(buf); } else { TIFFError(TIFFFileName(in), "Error, can't allocate space for image buffer"); } } else { TIFFError(TIFFFileName(in), "Error, no space for image buffer"); } return status; } DECLAREreadFunc(readContigStripsIntoBuffer) { tsize_t scanlinesize = TIFFScanlineSize(in); uint8* bufp = buf; uint32 row; (void) imagewidth; (void) spp; for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, (tdata_t) bufp, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); return 0; } bufp += scanlinesize; } return 1; } DECLAREreadFunc(readSeparateStripsIntoBuffer) { int status = 1; tsize_t scanlinesize = TIFFScanlineSize(in); tdata_t scanline; if (!scanlinesize) return 0; scanline = _TIFFmalloc(scanlinesize); (void) imagewidth; if (scanline) { uint8* bufp = (uint8*) buf; uint32 row; tsample_t s; for (row = 0; row < imagelength; row++) { /* merge channels */ for (s = 0; s < spp; s++) { uint8* bp = bufp + s; tsize_t n = scanlinesize; uint8* sbuf = scanline; if (TIFFReadScanline(in, scanline, row, s) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); status = 0; goto done; } while (n-- > 0) *bp = *sbuf++, bp += spp; } bufp += scanlinesize * spp; } } done: _TIFFfree(scanline); return status; } DECLAREreadFunc(readContigTilesIntoBuffer) { int status = 1; tdata_t tilebuf = _TIFFmalloc(TIFFTileSize(in)); uint32 imagew = TIFFScanlineSize(in); uint32 tilew = TIFFTileRowSize(in); int iskew = imagew - tilew; uint8* bufp = (uint8*) buf; uint32 tw, tl; uint32 row; (void) spp; if (tilebuf == 0) return 0; (void) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); (void) TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); for (row = 0; row < imagelength; row += tl) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { if (TIFFReadTile(in, tilebuf, col, row, 0, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile at %lu %lu", (unsigned long) col, (unsigned long) row); status = 0; goto done; } if (colb + tilew > imagew) { uint32 width = imagew - colb; uint32 oskew = tilew - width; cpStripToTile(bufp + colb, tilebuf, nrow, width, oskew + iskew, oskew ); } else cpStripToTile(bufp + colb, tilebuf, nrow, tilew, iskew, 0); colb += tilew; } bufp += imagew * nrow; } done: _TIFFfree(tilebuf); return status; } DECLAREreadFunc(readSeparateTilesIntoBuffer) { int status = 1; uint32 imagew = TIFFRasterScanlineSize(in); uint32 tilew = TIFFTileRowSize(in); int iskew = imagew - tilew*spp; tdata_t tilebuf = _TIFFmalloc(TIFFTileSize(in)); uint8* bufp = (uint8*) buf; uint32 tw, tl; uint32 row; uint16 bps, bytes_per_sample; if (tilebuf == 0) return 0; (void) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); (void) TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); (void) TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps); assert( bps % 8 == 0 ); bytes_per_sample = bps/8; for (row = 0; row < imagelength; row += tl) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { tsample_t s; for (s = 0; s < spp; s++) { if (TIFFReadTile(in, tilebuf, col, row, 0, s) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile at %lu %lu, " "sample %lu", (unsigned long) col, (unsigned long) row, (unsigned long) s); status = 0; goto done; } /* * Tile is clipped horizontally. Calculate * visible portion and skewing factors. */ if (colb + tilew*spp > imagew) { uint32 width = imagew - colb; int oskew = tilew*spp - width; cpSeparateBufToContigBuf( bufp+colb+s*bytes_per_sample, tilebuf, nrow, width/(spp*bytes_per_sample), oskew + iskew, oskew/spp, spp, bytes_per_sample); } else cpSeparateBufToContigBuf( bufp+colb+s*bytes_per_sample, tilebuf, nrow, tw, iskew, 0, spp, bytes_per_sample); } colb += tilew*spp; } bufp += imagew * nrow; } done: _TIFFfree(tilebuf); return status; } DECLAREwriteFunc(writeBufferToContigStrips) { uint32 row, rowsperstrip; tstrip_t strip = 0; (void) imagewidth; (void) spp; (void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); for (row = 0; row < imagelength; row += rowsperstrip) { uint32 nrows = (row+rowsperstrip > imagelength) ? imagelength-row : rowsperstrip; tsize_t stripsize = TIFFVStripSize(out, nrows); if (TIFFWriteEncodedStrip(out, strip++, buf, stripsize) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1); return 0; } buf += stripsize; } return 1; } DECLAREwriteFunc(writeBufferToSeparateStrips) { uint32 rowsize = imagewidth * spp; uint32 rowsperstrip; tdata_t obuf = _TIFFmalloc(TIFFStripSize(out)); tstrip_t strip = 0; tsample_t s; if (obuf == NULL) return (0); (void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); for (s = 0; s < spp; s++) { uint32 row; for (row = 0; row < imagelength; row += rowsperstrip) { uint32 nrows = (row+rowsperstrip > imagelength) ? imagelength-row : rowsperstrip; tsize_t stripsize = TIFFVStripSize(out, nrows); cpContigBufToSeparateBuf( obuf, (uint8*) buf + row*rowsize + s, nrows, imagewidth, 0, 0, spp, 1); if (TIFFWriteEncodedStrip(out, strip++, obuf, stripsize) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1); _TIFFfree(obuf); return 0; } } } _TIFFfree(obuf); return 1; } DECLAREwriteFunc(writeBufferToContigTiles) { uint32 imagew = TIFFScanlineSize(out); uint32 tilew = TIFFTileRowSize(out); int iskew = imagew - tilew; tdata_t obuf = _TIFFmalloc(TIFFTileSize(out)); uint8* bufp = (uint8*) buf; uint32 tl, tw; uint32 row; (void) spp; if (obuf == NULL) return 0; (void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl); (void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw); for (row = 0; row < imagelength; row += tilelength) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { /* * Tile is clipped horizontally. Calculate * visible portion and skewing factors. */ if (colb + tilew > imagew) { uint32 width = imagew - colb; int oskew = tilew - width; cpStripToTile(obuf, bufp + colb, nrow, width, oskew, oskew + iskew); } else cpStripToTile(obuf, bufp + colb, nrow, tilew, 0, iskew); if (TIFFWriteTile(out, obuf, col, row, 0, 0) < 0) { TIFFError(TIFFFileName(out), "Error, can't write tile at %lu %lu", (unsigned long) col, (unsigned long) row); _TIFFfree(obuf); return 0; } colb += tilew; } bufp += nrow * imagew; } _TIFFfree(obuf); return 1; } DECLAREwriteFunc(writeBufferToSeparateTiles) { uint32 imagew = TIFFScanlineSize(out); tsize_t tilew = TIFFTileRowSize(out); uint32 iimagew = TIFFRasterScanlineSize(out); int iskew = iimagew - tilew*spp; tdata_t obuf = _TIFFmalloc(TIFFTileSize(out)); uint8* bufp = (uint8*) buf; uint32 tl, tw; uint32 row; uint16 bps, bytes_per_sample; if (obuf == NULL) return 0; (void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl); (void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw); (void) TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps); assert( bps % 8 == 0 ); bytes_per_sample = bps/8; for (row = 0; row < imagelength; row += tl) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { tsample_t s; for (s = 0; s < spp; s++) { /* * Tile is clipped horizontally. Calculate * visible portion and skewing factors. */ if (colb + tilew > imagew) { uint32 width = (imagew - colb); int oskew = tilew - width; cpContigBufToSeparateBuf(obuf, bufp + (colb*spp) + s, nrow, width/bytes_per_sample, oskew, (oskew*spp)+iskew, spp, bytes_per_sample); } else cpContigBufToSeparateBuf(obuf, bufp + (colb*spp) + s, nrow, tilewidth, 0, iskew, spp, bytes_per_sample); if (TIFFWriteTile(out, obuf, col, row, 0, s) < 0) { TIFFError(TIFFFileName(out), "Error, can't write tile at %lu %lu " "sample %lu", (unsigned long) col, (unsigned long) row, (unsigned long) s); _TIFFfree(obuf); return 0; } } colb += tilew; } bufp += nrow * iimagew; } _TIFFfree(obuf); return 1; } /* * Contig strips -> contig tiles. */ DECLAREcpFunc(cpContigStrips2ContigTiles) { return cpImage(in, out, readContigStripsIntoBuffer, writeBufferToContigTiles, imagelength, imagewidth, spp); } /* * Contig strips -> separate tiles. */ DECLAREcpFunc(cpContigStrips2SeparateTiles) { return cpImage(in, out, readContigStripsIntoBuffer, writeBufferToSeparateTiles, imagelength, imagewidth, spp); } /* * Separate strips -> contig tiles. */ DECLAREcpFunc(cpSeparateStrips2ContigTiles) { return cpImage(in, out, readSeparateStripsIntoBuffer, writeBufferToContigTiles, imagelength, imagewidth, spp); } /* * Separate strips -> separate tiles. */ DECLAREcpFunc(cpSeparateStrips2SeparateTiles) { return cpImage(in, out, readSeparateStripsIntoBuffer, writeBufferToSeparateTiles, imagelength, imagewidth, spp); } /* * Contig strips -> contig tiles. */ DECLAREcpFunc(cpContigTiles2ContigTiles) { return cpImage(in, out, readContigTilesIntoBuffer, writeBufferToContigTiles, imagelength, imagewidth, spp); } /* * Contig tiles -> separate tiles. */ DECLAREcpFunc(cpContigTiles2SeparateTiles) { return cpImage(in, out, readContigTilesIntoBuffer, writeBufferToSeparateTiles, imagelength, imagewidth, spp); } /* * Separate tiles -> contig tiles. */ DECLAREcpFunc(cpSeparateTiles2ContigTiles) { return cpImage(in, out, readSeparateTilesIntoBuffer, writeBufferToContigTiles, imagelength, imagewidth, spp); } /* * Separate tiles -> separate tiles (tile dimension change). */ DECLAREcpFunc(cpSeparateTiles2SeparateTiles) { return cpImage(in, out, readSeparateTilesIntoBuffer, writeBufferToSeparateTiles, imagelength, imagewidth, spp); } /* * Contig tiles -> contig tiles (tile dimension change). */ DECLAREcpFunc(cpContigTiles2ContigStrips) { return cpImage(in, out, readContigTilesIntoBuffer, writeBufferToContigStrips, imagelength, imagewidth, spp); } /* * Contig tiles -> separate strips. */ DECLAREcpFunc(cpContigTiles2SeparateStrips) { return cpImage(in, out, readContigTilesIntoBuffer, writeBufferToSeparateStrips, imagelength, imagewidth, spp); } /* * Separate tiles -> contig strips. */ DECLAREcpFunc(cpSeparateTiles2ContigStrips) { return cpImage(in, out, readSeparateTilesIntoBuffer, writeBufferToContigStrips, imagelength, imagewidth, spp); } /* * Separate tiles -> separate strips. */ DECLAREcpFunc(cpSeparateTiles2SeparateStrips) { return cpImage(in, out, readSeparateTilesIntoBuffer, writeBufferToSeparateStrips, imagelength, imagewidth, spp); } /* * Select the appropriate copy function to use. */ static copyFunc pickCopyFunc(TIFF* in, TIFF* out, uint16 bitspersample, uint16 samplesperpixel) { uint16 shortv; uint32 w, l, tw, tl; int bychunk; (void) TIFFGetField(in, TIFFTAG_PLANARCONFIG, &shortv); if (shortv != config && bitspersample != 8 && samplesperpixel > 1) { fprintf(stderr, "%s: Cannot handle different planar configuration w/ bits/sample != 8\n", TIFFFileName(in)); return (NULL); } TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &w); TIFFGetField(in, TIFFTAG_IMAGELENGTH, &l); if (!(TIFFIsTiled(out) || TIFFIsTiled(in))) { uint32 irps = (uint32) -1L; TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &irps); /* if biased, force decoded copying to allow image subtraction */ bychunk = !bias && (rowsperstrip == irps); }else{ /* either in or out is tiled */ if (bias) { fprintf(stderr, "%s: Cannot handle tiled configuration w/bias image\n", TIFFFileName(in)); return (NULL); } if (TIFFIsTiled(out)) { if (!TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw)) tw = w; if (!TIFFGetField(in, TIFFTAG_TILELENGTH, &tl)) tl = l; bychunk = (tw == tilewidth && tl == tilelength); } else { /* out's not, so in must be tiled */ TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); bychunk = (tw == w && tl == rowsperstrip); } } #define T 1 #define F 0 #define pack(a,b,c,d,e) ((long)(((a)<<11)|((b)<<3)|((c)<<2)|((d)<<1)|(e))) switch(pack(shortv,config,TIFFIsTiled(in),TIFFIsTiled(out),bychunk)) { /* Strips -> Tiles */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,T): return cpContigStrips2ContigTiles; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,T): return cpContigStrips2SeparateTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,T): return cpSeparateStrips2ContigTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,T): return cpSeparateStrips2SeparateTiles; /* Tiles -> Tiles */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,T): return cpContigTiles2ContigTiles; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,T): return cpContigTiles2SeparateTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,T): return cpSeparateTiles2ContigTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,T): return cpSeparateTiles2SeparateTiles; /* Tiles -> Strips */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,T): return cpContigTiles2ContigStrips; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,T): return cpContigTiles2SeparateStrips; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,T): return cpSeparateTiles2ContigStrips; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,T): return cpSeparateTiles2SeparateStrips; /* Strips -> Strips */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,F): return bias ? cpBiasedContig2Contig : cpContig2ContigByRow; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,T): return cpDecodedStrips; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,T): return cpContig2SeparateByRow; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,T): return cpSeparate2ContigByRow; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,T): return cpSeparate2SeparateByRow; } #undef pack #undef F #undef T fprintf(stderr, "tiffcp: %s: Don't know how to copy/convert image.\n", TIFFFileName(in)); return (NULL); } /* vim: set ts=8 sts=8 sw=8 noet: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/libtiff_2009-06-30-b44af47-e0b51f3.c
manybugs_data_78
/* gzip (GNU zip) -- compress files with zip algorithm and 'compress' interface Copyright (C) 1999, 2001-2002, 2006-2007, 2009 Free Software Foundation, Inc. Copyright (C) 1992-1993 Jean-loup Gailly This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * The unzip code was written and put in the public domain by Mark Adler. * Portions of the lzw code are derived from the public domain 'compress' * written by Spencer Thomas, Joe Orost, James Woods, Jim McKie, Steve Davies, * Ken Turkowski, Dave Mack and Peter Jannesen. * * See the license_msg below and the file COPYING for the software license. * See the file algorithm.doc for the compression algorithms and file formats. */ static char *license_msg[] = { "Copyright (C) 2007 Free Software Foundation, Inc.", "Copyright (C) 1993 Jean-loup Gailly.", "This is free software. You may redistribute copies of it under the terms of", "the GNU General Public License <http://www.gnu.org/licenses/gpl.html>.", "There is NO WARRANTY, to the extent permitted by law.", 0}; /* Compress files with zip algorithm and 'compress' interface. * See help() function below for all options. * Outputs: * file.gz: compressed file with same mode, owner, and utimes * or stdout with -c option or if stdin used as input. * If the output file name had to be truncated, the original name is kept * in the compressed file. * On MSDOS, file.tmp -> file.tmz. On VMS, file.tmp -> file.tmp-gz. * * Using gz on MSDOS would create too many file name conflicts. For * example, foo.txt -> foo.tgz (.tgz must be reserved as shorthand for * tar.gz). Similarly, foo.dir and foo.doc would both be mapped to foo.dgz. * I also considered 12345678.txt -> 12345txt.gz but this truncates the name * too heavily. There is no ideal solution given the MSDOS 8+3 limitation. * * For the meaning of all compilation flags, see comments in Makefile.in. */ #include <config.h> #include <ctype.h> #include <sys/types.h> #include <signal.h> #include <sys/stat.h> #include <errno.h> #include "closein.h" #include "tailor.h" #include "gzip.h" #include "lzw.h" #include "revision.h" #include "fcntl-safer.h" #include "getopt.h" #include "stat-time.h" /* configuration */ #ifdef HAVE_FCNTL_H # include <fcntl.h> #endif #ifdef HAVE_LIMITS_H # include <limits.h> #endif #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #if defined STDC_HEADERS || defined HAVE_STDLIB_H # include <stdlib.h> #else extern int errno; #endif #ifndef NO_DIR # define NO_DIR 0 #endif #if !NO_DIR # include <dirent.h> # ifndef _D_EXACT_NAMLEN # define _D_EXACT_NAMLEN(dp) strlen ((dp)->d_name) # endif #endif #ifdef CLOSEDIR_VOID # define CLOSEDIR(d) (closedir(d), 0) #else # define CLOSEDIR(d) closedir(d) #endif #ifndef NO_UTIME # include <utimens.h> #endif #define RW_USER (S_IRUSR | S_IWUSR) /* creation mode for open() */ #ifndef MAX_PATH_LEN # define MAX_PATH_LEN 1024 /* max pathname length */ #endif #ifndef SEEK_END # define SEEK_END 2 #endif #ifndef CHAR_BIT # define CHAR_BIT 8 #endif #ifdef off_t off_t lseek OF((int fd, off_t offset, int whence)); #endif #ifndef OFF_T_MIN #define OFF_T_MIN (~ (off_t) 0 << (sizeof (off_t) * CHAR_BIT - 1)) #endif #ifndef OFF_T_MAX #define OFF_T_MAX (~ (off_t) 0 - OFF_T_MIN) #endif /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is present. */ #ifndef SA_NOCLDSTOP # define SA_NOCLDSTOP 0 # define sigprocmask(how, set, oset) /* empty */ # define sigset_t int # if ! HAVE_SIGINTERRUPT # define siginterrupt(sig, flag) /* empty */ # endif #endif #ifndef HAVE_WORKING_O_NOFOLLOW # define HAVE_WORKING_O_NOFOLLOW 0 #endif #ifndef ELOOP # define ELOOP EINVAL #endif /* Separator for file name parts (see shorten_name()) */ #ifdef NO_MULTIPLE_DOTS # define PART_SEP "-" #else # define PART_SEP "." #endif /* global buffers */ DECLARE(uch, inbuf, INBUFSIZ +INBUF_EXTRA); DECLARE(uch, outbuf, OUTBUFSIZ+OUTBUF_EXTRA); DECLARE(ush, d_buf, DIST_BUFSIZE); DECLARE(uch, window, 2L*WSIZE); #ifndef MAXSEG_64K DECLARE(ush, tab_prefix, 1L<<BITS); #else DECLARE(ush, tab_prefix0, 1L<<(BITS-1)); DECLARE(ush, tab_prefix1, 1L<<(BITS-1)); #endif /* local variables */ int ascii = 0; /* convert end-of-lines to local OS conventions */ int to_stdout = 0; /* output to stdout (-c) */ int decompress = 0; /* decompress (-d) */ int force = 0; /* don't ask questions, compress links (-f) */ int no_name = -1; /* don't save or restore the original file name */ int no_time = -1; /* don't save or restore the original file time */ int recursive = 0; /* recurse through directories (-r) */ int list = 0; /* list the file contents (-l) */ int verbose = 0; /* be verbose (-v) */ int quiet = 0; /* be very quiet (-q) */ int do_lzw = 0; /* generate output compatible with old compress (-Z) */ int test = 0; /* test .gz file integrity */ int foreground = 0; /* set if program run in foreground */ char *program_name; /* program name */ int maxbits = BITS; /* max bits per code for LZW */ int method = DEFLATED;/* compression method */ int level = 6; /* compression level */ int exit_code = OK; /* program exit code */ int save_orig_name; /* set if original name must be saved */ int last_member; /* set for .zip and .Z files */ int part_nb; /* number of parts in .gz file */ struct timespec time_stamp; /* original time stamp (modification time) */ off_t ifile_size; /* input file size, -1 for devices (debug only) */ char *env; /* contents of GZIP env variable */ char **args = NULL; /* argv pointer if GZIP env variable defined */ char *z_suffix; /* default suffix (can be set with --suffix) */ size_t z_len; /* strlen(z_suffix) */ /* The set of signals that are caught. */ static sigset_t caught_signals; /* If nonzero then exit with status WARNING, rather than with the usual signal status, on receipt of a signal with this value. This suppresses a "Broken Pipe" message with some shells. */ static int volatile exiting_signal; /* If nonnegative, close this file descriptor and unlink ofname on error. */ static int volatile remove_ofname_fd = -1; off_t bytes_in; /* number of input bytes */ off_t bytes_out; /* number of output bytes */ off_t total_in; /* input bytes for all files */ off_t total_out; /* output bytes for all files */ char ifname[MAX_PATH_LEN]; /* input file name */ char ofname[MAX_PATH_LEN]; /* output file name */ struct stat istat; /* status for input file */ int ifd; /* input file descriptor */ int ofd; /* output file descriptor */ unsigned insize; /* valid bytes in inbuf */ unsigned inptr; /* index of next byte to be processed in inbuf */ unsigned outcnt; /* bytes in output buffer */ static int handled_sig[] = { /* SIGINT must be first, as 'foreground' depends on it. */ SIGINT #ifdef SIGHUP , SIGHUP #endif #ifdef SIGPIPE , SIGPIPE #else # define SIGPIPE 0 #endif #ifdef SIGTERM , SIGTERM #endif #ifdef SIGXCPU , SIGXCPU #endif #ifdef SIGXFSZ , SIGXFSZ #endif }; struct option longopts[] = { /* { name has_arg *flag val } */ {"ascii", 0, 0, 'a'}, /* ascii text mode */ {"to-stdout", 0, 0, 'c'}, /* write output on standard output */ {"stdout", 0, 0, 'c'}, /* write output on standard output */ {"decompress", 0, 0, 'd'}, /* decompress */ {"uncompress", 0, 0, 'd'}, /* decompress */ /* {"encrypt", 0, 0, 'e'}, encrypt */ {"force", 0, 0, 'f'}, /* force overwrite of output file */ {"help", 0, 0, 'h'}, /* give help */ /* {"pkzip", 0, 0, 'k'}, force output in pkzip format */ {"list", 0, 0, 'l'}, /* list .gz file contents */ {"license", 0, 0, 'L'}, /* display software license */ {"no-name", 0, 0, 'n'}, /* don't save or restore original name & time */ {"name", 0, 0, 'N'}, /* save or restore original name & time */ {"quiet", 0, 0, 'q'}, /* quiet mode */ {"silent", 0, 0, 'q'}, /* quiet mode */ {"recursive", 0, 0, 'r'}, /* recurse through directories */ {"suffix", 1, 0, 'S'}, /* use given suffix instead of .gz */ {"test", 0, 0, 't'}, /* test compressed file integrity */ {"no-time", 0, 0, 'T'}, /* don't save or restore the time stamp */ {"verbose", 0, 0, 'v'}, /* verbose mode */ {"version", 0, 0, 'V'}, /* display version number */ {"fast", 0, 0, '1'}, /* compress faster */ {"best", 0, 0, '9'}, /* compress better */ {"lzw", 0, 0, 'Z'}, /* make output compatible with old compress */ {"bits", 1, 0, 'b'}, /* max number of bits per code (implies -Z) */ { 0, 0, 0, 0 } }; /* local functions */ local void try_help OF((void)) ATTRIBUTE_NORETURN; local void help OF((void)); local void license OF((void)); local void version OF((void)); local int input_eof OF((void)); local void treat_stdin OF((void)); local void treat_file OF((char *iname)); local int create_outfile OF((void)); local char *get_suffix OF((char *name)); local int open_input_file OF((char *iname, struct stat *sbuf)); local int make_ofname OF((void)); local void shorten_name OF((char *name)); local int get_method OF((int in)); local void do_list OF((int ifd, int method)); local int check_ofname OF((void)); local void copy_stat OF((struct stat *ifstat)); local void install_signal_handlers OF((void)); local void remove_output_file OF((void)); local RETSIGTYPE abort_gzip_signal OF((int)); local void do_exit OF((int exitcode)) ATTRIBUTE_NORETURN; int main OF((int argc, char **argv)); int (*work) OF((int infile, int outfile)) = zip; /* function to call */ #if ! NO_DIR local void treat_dir OF((int fd, char *dir)); #endif #define strequ(s1, s2) (strcmp((s1),(s2)) == 0) static void try_help () { fprintf (stderr, "Try `%s --help' for more information.\n", program_name); do_exit (ERROR); } /* ======================================================================== */ local void help() { static char *help_msg[] = { "Compress or uncompress FILEs (by default, compress FILES in-place).", "", "Mandatory arguments to long options are mandatory for short options too.", "", #if O_BINARY " -a, --ascii ascii text; convert end-of-line using local conventions", #endif " -c, --stdout write on standard output, keep original files unchanged", " -d, --decompress decompress", /* -e, --encrypt encrypt */ " -f, --force force overwrite of output file and compress links", " -h, --help give this help", /* -k, --pkzip force output in pkzip format */ " -l, --list list compressed file contents", " -L, --license display software license", #ifdef UNDOCUMENTED " -m, --no-time do not save or restore the original modification time", " -M, --time save or restore the original modification time", #endif " -n, --no-name do not save or restore the original name and time stamp", " -N, --name save or restore the original name and time stamp", " -q, --quiet suppress all warnings", #if ! NO_DIR " -r, --recursive operate recursively on directories", #endif " -S, --suffix=SUF use suffix SUF on compressed files", " -t, --test test compressed file integrity", " -v, --verbose verbose mode", " -V, --version display version number", " -1, --fast compress faster", " -9, --best compress better", #ifdef LZW " -Z, --lzw produce output compatible with old compress", " -b, --bits=BITS max number of bits per code (implies -Z)", #endif "", "With no FILE, or when FILE is -, read standard input.", "", "Report bugs to <[email protected]>.", 0}; char **p = help_msg; printf ("Usage: %s [OPTION]... [FILE]...\n", program_name); while (*p) printf ("%s\n", *p++); } /* ======================================================================== */ local void license() { char **p = license_msg; printf ("%s %s\n", program_name, VERSION); while (*p) printf ("%s\n", *p++); } /* ======================================================================== */ local void version() { license (); printf ("\n"); printf ("Written by Jean-loup Gailly.\n"); } local void progerror (string) char *string; { int e = errno; fprintf (stderr, "%s: ", program_name); errno = e; perror(string); exit_code = ERROR; } /* ======================================================================== */ int main (argc, argv) int argc; char **argv; { int file_count; /* number of files to process */ size_t proglen; /* length of program_name */ int optc; /* current option */ EXPAND(argc, argv); /* wild card expansion if necessary */ program_name = gzip_base_name (argv[0]); proglen = strlen (program_name); atexit (close_stdin); /* Suppress .exe for MSDOS, OS/2 and VMS: */ if (4 < proglen && strequ (program_name + proglen - 4, ".exe")) program_name[proglen - 4] = '\0'; /* Add options in GZIP environment variable if there is one */ env = add_envopt(&argc, &argv, OPTIONS_VAR); if (env != NULL) args = argv; #ifndef GNU_STANDARD # define GNU_STANDARD 1 #endif #if !GNU_STANDARD /* For compatibility with old compress, use program name as an option. * Unless you compile with -DGNU_STANDARD=0, this program will behave as * gzip even if it is invoked under the name gunzip or zcat. * * Systems which do not support links can still use -d or -dc. * Ignore an .exe extension for MSDOS, OS/2 and VMS. */ if (strncmp (program_name, "un", 2) == 0 /* ungzip, uncompress */ || strncmp (program_name, "gun", 3) == 0) /* gunzip */ decompress = 1; else if (strequ (program_name + 1, "cat") /* zcat, pcat, gcat */ || strequ (program_name, "gzcat")) /* gzcat */ decompress = to_stdout = 1; #endif z_suffix = Z_SUFFIX; z_len = strlen(z_suffix); while ((optc = getopt_long (argc, argv, "ab:cdfhH?lLmMnNqrS:tvVZ123456789", longopts, (int *)0)) != -1) { switch (optc) { case 'a': ascii = 1; break; case 'b': maxbits = atoi(optarg); for (; *optarg; optarg++) if (! ('0' <= *optarg && *optarg <= '9')) { fprintf (stderr, "%s: -b operand is not an integer\n", program_name); try_help (); } break; case 'c': to_stdout = 1; break; case 'd': decompress = 1; break; case 'f': force++; break; case 'h': case 'H': help(); do_exit(OK); break; case 'l': list = decompress = to_stdout = 1; break; case 'L': license(); do_exit(OK); break; case 'm': /* undocumented, may change later */ no_time = 1; break; case 'M': /* undocumented, may change later */ no_time = 0; break; case 'n': no_name = no_time = 1; break; case 'N': no_name = no_time = 0; break; case 'q': quiet = 1; verbose = 0; break; case 'r': #if NO_DIR fprintf (stderr, "%s: -r not supported on this system\n", program_name); try_help (); #else recursive = 1; #endif break; case 'S': #ifdef NO_MULTIPLE_DOTS if (*optarg == '.') optarg++; #endif z_len = strlen(optarg); z_suffix = optarg; break; case 't': test = decompress = to_stdout = 1; break; case 'v': verbose++; quiet = 0; break; case 'V': version(); do_exit(OK); break; case 'Z': #ifdef LZW do_lzw = 1; break; #else fprintf(stderr, "%s: -Z not supported in this version\n", program_name); try_help (); break; #endif case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': level = optc - '0'; break; default: /* Error message already emitted by getopt_long. */ try_help (); } } /* loop on all arguments */ /* By default, save name and timestamp on compression but do not * restore them on decompression. */ if (no_time < 0) no_time = decompress; if (no_name < 0) no_name = decompress; file_count = argc - optind; #if O_BINARY #else if (ascii && !quiet) { fprintf(stderr, "%s: option --ascii ignored on this system\n", program_name); } #endif if ((z_len == 0 && !decompress) || z_len > MAX_SUFFIX) { fprintf(stderr, "%s: incorrect suffix '%s'\n", program_name, z_suffix); do_exit(ERROR); } if (do_lzw && !decompress) work = lzw; /* Allocate all global buffers (for DYN_ALLOC option) */ ALLOC(uch, inbuf, INBUFSIZ +INBUF_EXTRA); ALLOC(uch, outbuf, OUTBUFSIZ+OUTBUF_EXTRA); ALLOC(ush, d_buf, DIST_BUFSIZE); ALLOC(uch, window, 2L*WSIZE); #ifndef MAXSEG_64K ALLOC(ush, tab_prefix, 1L<<BITS); #else ALLOC(ush, tab_prefix0, 1L<<(BITS-1)); ALLOC(ush, tab_prefix1, 1L<<(BITS-1)); #endif exiting_signal = quiet ? SIGPIPE : 0; install_signal_handlers (); /* And get to work */ if (file_count != 0) { if (to_stdout && !test && !list && (!decompress || !ascii)) { SET_BINARY_MODE(fileno(stdout)); } while (optind < argc) { treat_file(argv[optind++]); } } else { /* Standard input */ treat_stdin(); } if (list && !quiet && file_count > 1) { do_list(-1, -1); /* print totals */ } do_exit(exit_code); return exit_code; /* just to avoid lint warning */ } /* Return nonzero when at end of file on input. */ local int input_eof () { if (!decompress || last_member) return 1; if (inptr == insize) { if (insize != INBUFSIZ || fill_inbuf (1) == EOF) return 1; /* Unget the char that fill_inbuf got. */ inptr = 0; } return 0; } /* ======================================================================== * Compress or decompress stdin */ local void treat_stdin() { if (!force && !list && isatty(fileno((FILE *)(decompress ? stdin : stdout)))) { /* Do not send compressed data to the terminal or read it from * the terminal. We get here when user invoked the program * without parameters, so be helpful. According to the GNU standards: * * If there is one behavior you think is most useful when the output * is to a terminal, and another that you think is most useful when * the output is a file or a pipe, then it is usually best to make * the default behavior the one that is useful with output to a * terminal, and have an option for the other behavior. * * Here we use the --force option to get the other behavior. */ fprintf(stderr, "%s: compressed data not %s a terminal. Use -f to force %scompression.\n", program_name, decompress ? "read from" : "written to", decompress ? "de" : ""); fprintf (stderr, "For help, type: %s -h\n", program_name); do_exit(ERROR); } if (decompress || !ascii) { SET_BINARY_MODE(fileno(stdin)); } if (!test && !list && (!decompress || !ascii)) { SET_BINARY_MODE(fileno(stdout)); } strcpy(ifname, "stdin"); strcpy(ofname, "stdout"); /* Get the file's time stamp and size. */ if (fstat (fileno (stdin), &istat) != 0) { progerror ("standard input"); do_exit (ERROR); } ifile_size = S_ISREG (istat.st_mode) ? istat.st_size : -1; time_stamp.tv_nsec = -1; if (!no_time || list) time_stamp = get_stat_mtime (&istat); clear_bufs(); /* clear input and output buffers */ to_stdout = 1; part_nb = 0; if (decompress) { method = get_method(ifd); if (method < 0) { do_exit(exit_code); /* error message already emitted */ } } if (list) { do_list(ifd, method); return; } /* Actually do the compression/decompression. Loop over zipped members. */ for (;;) { if ((*work)(fileno(stdin), fileno(stdout)) != OK) return; if (input_eof ()) break; method = get_method(ifd); if (method < 0) return; /* error message already emitted */ bytes_out = 0; /* required for length check */ } if (verbose) { if (test) { fprintf(stderr, " OK\n"); } else if (!decompress) { display_ratio(bytes_in-(bytes_out-header_bytes), bytes_in, stderr); fprintf(stderr, "\n"); #ifdef DISPLAY_STDIN_RATIO } else { display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out,stderr); fprintf(stderr, "\n"); #endif } } } /* ======================================================================== * Compress or decompress the given file */ local void treat_file(iname) char *iname; { /* Accept "-" as synonym for stdin */ if (strequ(iname, "-")) { int cflag = to_stdout; treat_stdin(); to_stdout = cflag; return; } /* Check if the input file is present, set ifname and istat: */ ifd = open_input_file (iname, &istat); if (ifd < 0) return; /* If the input name is that of a directory, recurse or ignore: */ if (S_ISDIR(istat.st_mode)) { #if ! NO_DIR if (recursive) { treat_dir (ifd, iname); /* Warning: ifname is now garbage */ return; } #endif close (ifd); WARN ((stderr, "%s: %s is a directory -- ignored\n", program_name, ifname)); return; } if (! to_stdout) { if (! S_ISREG (istat.st_mode)) { WARN ((stderr, "%s: %s is not a directory or a regular file - ignored\n", program_name, ifname)); close (ifd); return; } if (istat.st_mode & S_ISUID) { WARN ((stderr, "%s: %s is set-user-ID on execution - ignored\n", program_name, ifname)); close (ifd); return; } if (istat.st_mode & S_ISGID) { WARN ((stderr, "%s: %s is set-group-ID on execution - ignored\n", program_name, ifname)); close (ifd); return; } if (! force) { if (istat.st_mode & S_ISVTX) { WARN ((stderr, "%s: %s has the sticky bit set - file ignored\n", program_name, ifname)); close (ifd); return; } if (2 <= istat.st_nlink) { WARN ((stderr, "%s: %s has %lu other link%c -- unchanged\n", program_name, ifname, (unsigned long int) istat.st_nlink - 1, istat.st_nlink == 2 ? ' ' : 's')); close (ifd); return; } } } ifile_size = S_ISREG (istat.st_mode) ? istat.st_size : -1; time_stamp.tv_nsec = -1; if (!no_time || list) time_stamp = get_stat_mtime (&istat); /* Generate output file name. For -r and (-t or -l), skip files * without a valid gzip suffix (check done in make_ofname). */ if (to_stdout && !list && !test) { strcpy(ofname, "stdout"); } else if (make_ofname() != OK) { close (ifd); return; } clear_bufs(); /* clear input and output buffers */ part_nb = 0; if (decompress) { method = get_method(ifd); /* updates ofname if original given */ if (method < 0) { close(ifd); return; /* error message already emitted */ } } if (list) { do_list(ifd, method); if (close (ifd) != 0) read_error (); return; } /* If compressing to a file, check if ofname is not ambiguous * because the operating system truncates names. Otherwise, generate * a new ofname and save the original name in the compressed file. */ if (to_stdout) { ofd = fileno(stdout); /* Keep remove_ofname_fd negative. */ } else { if (create_outfile() != OK) return; if (!decompress && save_orig_name && !verbose && !quiet) { fprintf(stderr, "%s: %s compressed to %s\n", program_name, ifname, ofname); } } /* Keep the name even if not truncated except with --no-name: */ if (!save_orig_name) save_orig_name = !no_name; if (verbose) { fprintf(stderr, "%s:\t", ifname); } /* Actually do the compression/decompression. Loop over zipped members. */ for (;;) { if ((*work)(ifd, ofd) != OK) { method = -1; /* force cleanup */ break; } if (input_eof ()) break; method = get_method(ifd); if (method < 0) break; /* error message already emitted */ bytes_out = 0; /* required for length check */ } if (close (ifd) != 0) read_error (); if (!to_stdout) { sigset_t oldset; int unlink_errno; copy_stat (&istat); if (close (ofd) != 0) write_error (); sigprocmask (SIG_BLOCK, &caught_signals, &oldset); remove_ofname_fd = -1; unlink_errno = xunlink (ifname) == 0 ? 0 : errno; sigprocmask (SIG_SETMASK, &oldset, NULL); if (unlink_errno) { WARN ((stderr, "%s: ", program_name)); if (!quiet) { errno = unlink_errno; perror (ifname); } } } if (method == -1) { if (!to_stdout) remove_output_file (); return; } /* Display statistics */ if(verbose) { if (test) { fprintf(stderr, " OK"); } else if (decompress) { display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out,stderr); } else { display_ratio(bytes_in-(bytes_out-header_bytes), bytes_in, stderr); } if (!test && !to_stdout) { fprintf(stderr, " -- replaced with %s", ofname); } fprintf(stderr, "\n"); } } /* ======================================================================== * Create the output file. Return OK or ERROR. * Try several times if necessary to avoid truncating the z_suffix. For * example, do not create a compressed file of name "1234567890123." * Sets save_orig_name to true if the file name has been truncated. * IN assertions: the input file has already been open (ifd is set) and * ofname has already been updated if there was an original name. * OUT assertions: ifd and ofd are closed in case of error. */ local int create_outfile() { int name_shortened = 0; int flags = (O_WRONLY | O_CREAT | O_EXCL | (ascii && decompress ? 0 : O_BINARY)); for (;;) { int open_errno; sigset_t oldset; sigprocmask (SIG_BLOCK, &caught_signals, &oldset); remove_ofname_fd = ofd = OPEN (ofname, flags, RW_USER); open_errno = errno; sigprocmask (SIG_SETMASK, &oldset, NULL); if (0 <= ofd) break; switch (open_errno) { #ifdef ENAMETOOLONG case ENAMETOOLONG: shorten_name (ofname); name_shortened = 1; break; #endif case EEXIST: if (check_ofname () != OK) { close (ifd); return ERROR; } break; default: progerror (ofname); close (ifd); return ERROR; } } if (name_shortened && decompress) { /* name might be too long if an original name was saved */ WARN ((stderr, "%s: %s: warning, name truncated\n", program_name, ofname)); } return OK; } /* ======================================================================== * Return a pointer to the 'z' suffix of a file name, or NULL. For all * systems, ".gz", ".z", ".Z", ".taz", ".tgz", "-gz", "-z" and "_z" are * accepted suffixes, in addition to the value of the --suffix option. * ".tgz" is a useful convention for tar.z files on systems limited * to 3 characters extensions. On such systems, ".?z" and ".??z" are * also accepted suffixes. For Unix, we do not want to accept any * .??z suffix as indicating a compressed file; some people use .xyz * to denote volume data. * On systems allowing multiple versions of the same file (such as VMS), * this function removes any version suffix in the given name. */ local char *get_suffix(name) char *name; { int nlen, slen; char suffix[MAX_SUFFIX+3]; /* last chars of name, forced to lower case */ static char *known_suffixes[] = {NULL, ".gz", ".z", ".taz", ".tgz", "-gz", "-z", "_z", #ifdef MAX_EXT_CHARS "z", #endif NULL}; char **suf = known_suffixes; *suf = z_suffix; if (strequ(z_suffix, "z")) suf++; /* check long suffixes first */ #ifdef SUFFIX_SEP /* strip a version number from the file name */ { char *v = strrchr(name, SUFFIX_SEP); if (v != NULL) *v = '\0'; } #endif nlen = strlen(name); if (nlen <= MAX_SUFFIX+2) { strcpy(suffix, name); } else { strcpy(suffix, name+nlen-MAX_SUFFIX-2); } strlwr(suffix); slen = strlen(suffix); do { int s = strlen(*suf); if (slen > s && suffix[slen-s-1] != PATH_SEP && strequ(suffix + slen - s, *suf)) { return name+nlen-s; } } while (*++suf != NULL); return NULL; } /* Open file NAME with the given flags and mode and store its status into *ST. Return a file descriptor to the newly opened file, or -1 (setting errno) on failure. */ static int open_and_stat (char *name, int flags, mode_t mode, struct stat *st) { int fd; /* Refuse to follow symbolic links unless -c or -f. */ if (!to_stdout && !force) { if (HAVE_WORKING_O_NOFOLLOW) flags |= O_NOFOLLOW; else { #if HAVE_LSTAT || defined lstat if (lstat (name, st) != 0) return -1; else if (S_ISLNK (st->st_mode)) { errno = ELOOP; return -1; } #endif } } fd = OPEN (name, flags, mode); if (0 <= fd && fstat (fd, st) != 0) { int e = errno; close (fd); errno = e; return -1; } return fd; } /* ======================================================================== * Set ifname to the input file name (with a suffix appended if necessary) * and istat to its stats. For decompression, if no file exists with the * original name, try adding successively z_suffix, .gz, .z, -z and .Z. * For MSDOS, we try only z_suffix and z. * Return an open file descriptor or -1. */ static int open_input_file (iname, sbuf) char *iname; struct stat *sbuf; { int ilen; /* strlen(ifname) */ int z_suffix_errno = 0; static char *suffixes[] = {NULL, ".gz", ".z", "-z", ".Z", NULL}; char **suf = suffixes; char *s; #ifdef NO_MULTIPLE_DOTS char *dot; /* pointer to ifname extension, or NULL */ #endif int fd; int open_flags = (O_RDONLY | O_NONBLOCK | O_NOCTTY | (ascii && !decompress ? 0 : O_BINARY)); *suf = z_suffix; if (sizeof ifname - 1 <= strlen (iname)) goto name_too_long; strcpy(ifname, iname); /* If input file exists, return OK. */ fd = open_and_stat (ifname, open_flags, RW_USER, sbuf); if (0 <= fd) return fd; if (!decompress || errno != ENOENT) { progerror(ifname); return -1; } /* file.ext doesn't exist, try adding a suffix (after removing any * version number for VMS). */ s = get_suffix(ifname); if (s != NULL) { progerror(ifname); /* ifname already has z suffix and does not exist */ return -1; } #ifdef NO_MULTIPLE_DOTS dot = strrchr(ifname, '.'); if (dot == NULL) { strcat(ifname, "."); dot = strrchr(ifname, '.'); } #endif ilen = strlen(ifname); if (strequ(z_suffix, ".gz")) suf++; /* Search for all suffixes */ do { char *s0 = s = *suf; strcpy (ifname, iname); #ifdef NO_MULTIPLE_DOTS if (*s == '.') s++; if (*dot == '\0') strcpy (dot, "."); #endif #ifdef MAX_EXT_CHARS if (MAX_EXT_CHARS < strlen (s) + strlen (dot + 1)) dot[MAX_EXT_CHARS + 1 - strlen (s)] = '\0'; #endif if (sizeof ifname <= ilen + strlen (s)) goto name_too_long; strcat(ifname, s); fd = open_and_stat (ifname, open_flags, RW_USER, sbuf); if (0 <= fd) return fd; if (errno != ENOENT) { progerror (ifname); return -1; } if (strequ (s0, z_suffix)) z_suffix_errno = errno; } while (*++suf != NULL); /* No suffix found, complain using z_suffix: */ strcpy(ifname, iname); #ifdef NO_MULTIPLE_DOTS if (*dot == '\0') strcpy(dot, "."); #endif #ifdef MAX_EXT_CHARS if (MAX_EXT_CHARS < z_len + strlen (dot + 1)) dot[MAX_EXT_CHARS + 1 - z_len] = '\0'; #endif strcat(ifname, z_suffix); errno = z_suffix_errno; progerror(ifname); return -1; name_too_long: fprintf (stderr, "%s: %s: file name too long\n", program_name, iname); exit_code = ERROR; return -1; } /* ======================================================================== * Generate ofname given ifname. Return OK, or WARNING if file must be skipped. * Sets save_orig_name to true if the file name has been truncated. */ local int make_ofname() { char *suff; /* ofname z suffix */ strcpy(ofname, ifname); /* strip a version number if any and get the gzip suffix if present: */ suff = get_suffix(ofname); if (decompress) { if (suff == NULL) { /* With -t or -l, try all files (even without .gz suffix) * except with -r (behave as with just -dr). */ if (!recursive && (list || test)) return OK; /* Avoid annoying messages with -r */ if (verbose || (!recursive && !quiet)) { WARN((stderr,"%s: %s: unknown suffix -- ignored\n", program_name, ifname)); } return WARNING; } /* Make a special case for .tgz and .taz: */ strlwr(suff); if (strequ(suff, ".tgz") || strequ(suff, ".taz")) { strcpy(suff, ".tar"); } else { *suff = '\0'; /* strip the z suffix */ } /* ofname might be changed later if infile contains an original name */ } else if (suff && ! force) { /* Avoid annoying messages with -r (see treat_dir()) */ if (verbose || (!recursive && !quiet)) { /* Don't use WARN, as it affects exit status. */ fprintf (stderr, "%s: %s already has %s suffix -- unchanged\n", program_name, ifname, suff); } return WARNING; } else { save_orig_name = 0; #ifdef NO_MULTIPLE_DOTS suff = strrchr(ofname, '.'); if (suff == NULL) { if (sizeof ofname <= strlen (ofname) + 1) goto name_too_long; strcat(ofname, "."); # ifdef MAX_EXT_CHARS if (strequ(z_suffix, "z")) { if (sizeof ofname <= strlen (ofname) + 2) goto name_too_long; strcat(ofname, "gz"); /* enough room */ return OK; } /* On the Atari and some versions of MSDOS, * ENAMETOOLONG does not work correctly. So we * must truncate here. */ } else if (strlen(suff)-1 + z_len > MAX_SUFFIX) { suff[MAX_SUFFIX+1-z_len] = '\0'; save_orig_name = 1; # endif } #endif /* NO_MULTIPLE_DOTS */ if (sizeof ofname <= strlen (ofname) + z_len) goto name_too_long; strcat(ofname, z_suffix); } /* decompress ? */ return OK; name_too_long: WARN ((stderr, "%s: %s: file name too long\n", program_name, ifname)); return WARNING; } /* ======================================================================== * Check the magic number of the input file and update ofname if an * original name was given and to_stdout is not set. * Return the compression method, -1 for error, -2 for warning. * Set inptr to the offset of the next byte to be processed. * Updates time_stamp if there is one and --no-time is not used. * This function may be called repeatedly for an input file consisting * of several contiguous gzip'ed members. * IN assertions: there is at least one remaining compressed member. * If the member is a zip file, it must be the only one. */ local int get_method(in) int in; /* input file descriptor */ { uch flags; /* compression flags */ char magic[2]; /* magic header */ int imagic1; /* like magic[1], but can represent EOF */ ulg stamp; /* time stamp */ /* If --force and --stdout, zcat == cat, so do not complain about * premature end of file: use try_byte instead of get_byte. */ if (force && to_stdout) { magic[0] = (char)try_byte(); imagic1 = try_byte (); magic[1] = (char) imagic1; /* If try_byte returned EOF, magic[1] == (char) EOF. */ } else { magic[0] = (char)get_byte(); magic[1] = (char)get_byte(); imagic1 = 0; /* avoid lint warning */ } method = -1; /* unknown yet */ part_nb++; /* number of parts in gzip file */ header_bytes = 0; last_member = RECORD_IO; /* assume multiple members in gzip file except for record oriented I/O */ if (memcmp(magic, GZIP_MAGIC, 2) == 0 || memcmp(magic, OLD_GZIP_MAGIC, 2) == 0) { method = (int)get_byte(); if (method != DEFLATED) { fprintf(stderr, "%s: %s: unknown method %d -- not supported\n", program_name, ifname, method); exit_code = ERROR; return -1; } work = unzip; flags = (uch)get_byte(); if ((flags & ENCRYPTED) != 0) { fprintf(stderr, "%s: %s is encrypted -- not supported\n", program_name, ifname); exit_code = ERROR; return -1; } if ((flags & CONTINUATION) != 0) { fprintf(stderr, "%s: %s is a multi-part gzip file -- not supported\n", program_name, ifname); exit_code = ERROR; if (force <= 1) return -1; } if ((flags & RESERVED) != 0) { fprintf(stderr, "%s: %s has flags 0x%x -- not supported\n", program_name, ifname, flags); exit_code = ERROR; if (force <= 1) return -1; } stamp = (ulg)get_byte(); stamp |= ((ulg)get_byte()) << 8; stamp |= ((ulg)get_byte()) << 16; stamp |= ((ulg)get_byte()) << 24; if (stamp != 0 && !no_time) { time_stamp.tv_sec = stamp; time_stamp.tv_nsec = 0; } (void)get_byte(); /* Ignore extra flags for the moment */ (void)get_byte(); /* Ignore OS type for the moment */ if ((flags & CONTINUATION) != 0) { unsigned part = (unsigned)get_byte(); part |= ((unsigned)get_byte())<<8; if (verbose) { fprintf(stderr,"%s: %s: part number %u\n", program_name, ifname, part); } } if ((flags & EXTRA_FIELD) != 0) { unsigned len = (unsigned)get_byte(); len |= ((unsigned)get_byte())<<8; if (verbose) { fprintf(stderr,"%s: %s: extra field of %u bytes ignored\n", program_name, ifname, len); } while (len--) (void)get_byte(); } /* Get original file name if it was truncated */ if ((flags & ORIG_NAME) != 0) { if (no_name || (to_stdout && !list) || part_nb > 1) { /* Discard the old name */ char c; /* dummy used for NeXTstep 3.0 cc optimizer bug */ do {c=get_byte();} while (c != 0); } else { /* Copy the base name. Keep a directory prefix intact. */ char *p = gzip_base_name (ofname); char *base = p; for (;;) { *p = (char)get_char(); if (*p++ == '\0') break; if (p >= ofname+sizeof(ofname)) { gzip_error ("corrupted input -- file name too large"); } } p = gzip_base_name (base); memmove (base, p, strlen (p) + 1); /* If necessary, adapt the name to local OS conventions: */ if (!list) { MAKE_LEGAL_NAME(base); if (base) list=0; /* avoid warning about unused variable */ } } /* no_name || to_stdout */ } /* ORIG_NAME */ /* Discard file comment if any */ if ((flags & COMMENT) != 0) { while (get_char() != 0) /* null */ ; } if (part_nb == 1) { header_bytes = inptr + 2*sizeof(long); /* include crc and size */ } } else if (memcmp(magic, PKZIP_MAGIC, 2) == 0 && inptr == 2 && memcmp((char*)inbuf, PKZIP_MAGIC, 4) == 0) { /* To simplify the code, we support a zip file when alone only. * We are thus guaranteed that the entire local header fits in inbuf. */ inptr = 0; work = unzip; if (check_zipfile(in) != OK) return -1; /* check_zipfile may get ofname from the local header */ last_member = 1; } else if (memcmp(magic, PACK_MAGIC, 2) == 0) { work = unpack; method = PACKED; } else if (memcmp(magic, LZW_MAGIC, 2) == 0) { work = unlzw; method = COMPRESSED; last_member = 1; } else if (memcmp(magic, LZH_MAGIC, 2) == 0) { work = unlzh; method = LZHED; last_member = 1; } else if (force && to_stdout && !list) { /* pass input unchanged */ method = STORED; work = copy; inptr = 0; last_member = 1; } if (method >= 0) return method; if (part_nb == 1) { fprintf (stderr, "\n%s: %s: not in gzip format\n", program_name, ifname); exit_code = ERROR; return -1; } else { if (magic[0] == 0) { int inbyte; for (inbyte = imagic1; inbyte == 0; inbyte = try_byte ()) continue; if (inbyte == EOF) { if (verbose) WARN ((stderr, "\n%s: %s: decompression OK, trailing zero bytes ignored\n", program_name, ifname)); return -3; } } WARN((stderr, "\n%s: %s: decompression OK, trailing garbage ignored\n", program_name, ifname)); return -2; } } /* ======================================================================== * Display the characteristics of the compressed file. * If the given method is < 0, display the accumulated totals. * IN assertions: time_stamp, header_bytes and ifile_size are initialized. */ local void do_list(ifd, method) int ifd; /* input file descriptor */ int method; /* compression method */ { ulg crc; /* original crc */ static int first_time = 1; static char* methods[MAX_METHODS] = { "store", /* 0 */ "compr", /* 1 */ "pack ", /* 2 */ "lzh ", /* 3 */ "", "", "", "", /* 4 to 7 reserved */ "defla"}; /* 8 */ int positive_off_t_width = 1; off_t o; for (o = OFF_T_MAX; 9 < o; o /= 10) { positive_off_t_width++; } if (first_time && method >= 0) { first_time = 0; if (verbose) { printf("method crc date time "); } if (!quiet) { printf("%*.*s %*.*s ratio uncompressed_name\n", positive_off_t_width, positive_off_t_width, "compressed", positive_off_t_width, positive_off_t_width, "uncompressed"); } } else if (method < 0) { if (total_in <= 0 || total_out <= 0) return; if (verbose) { printf(" "); } if (verbose || !quiet) { fprint_off(stdout, total_in, positive_off_t_width); printf(" "); fprint_off(stdout, total_out, positive_off_t_width); printf(" "); } display_ratio(total_out-(total_in-header_bytes), total_out, stdout); /* header_bytes is not meaningful but used to ensure the same * ratio if there is a single file. */ printf(" (totals)\n"); return; } crc = (ulg)~0; /* unknown */ bytes_out = -1L; bytes_in = ifile_size; #if RECORD_IO == 0 if (method == DEFLATED && !last_member) { /* Get the crc and uncompressed size for gzip'ed (not zip'ed) files. * If the lseek fails, we could use read() to get to the end, but * --list is used to get quick results. * Use "gunzip < foo.gz | wc -c" to get the uncompressed size if * you are not concerned about speed. */ bytes_in = lseek(ifd, (off_t)(-8), SEEK_END); if (bytes_in != -1L) { uch buf[8]; bytes_in += 8L; if (read(ifd, (char*)buf, sizeof(buf)) != sizeof(buf)) { read_error(); } crc = LG(buf); bytes_out = LG(buf+4); } } #endif /* RECORD_IO */ if (verbose) { struct tm *tm = localtime (&time_stamp.tv_sec); printf ("%5s %08lx ", methods[method], crc); if (tm) printf ("%s%3d %02d:%02d ", ("Jan\0Feb\0Mar\0Apr\0May\0Jun\0Jul\0Aug\0Sep\0Oct\0Nov\0Dec" + 4 * tm->tm_mon), tm->tm_mday, tm->tm_hour, tm->tm_min); else printf ("??? ?? ??:?? "); } fprint_off(stdout, bytes_in, positive_off_t_width); printf(" "); fprint_off(stdout, bytes_out, positive_off_t_width); printf(" "); if (bytes_in == -1L) { total_in = -1L; bytes_in = bytes_out = header_bytes = 0; } else if (total_in >= 0) { total_in += bytes_in; } if (bytes_out == -1L) { total_out = -1L; bytes_in = bytes_out = header_bytes = 0; } else if (total_out >= 0) { total_out += bytes_out; } display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out, stdout); printf(" %s\n", ofname); } /* ======================================================================== * Shorten the given name by one character, or replace a .tar extension * with .tgz. Truncate the last part of the name which is longer than * MIN_PART characters: 1234.678.012.gz -> 123.678.012.gz. If the name * has only parts shorter than MIN_PART truncate the longest part. * For decompression, just remove the last character of the name. * * IN assertion: for compression, the suffix of the given name is z_suffix. */ local void shorten_name(name) char *name; { int len; /* length of name without z_suffix */ char *trunc = NULL; /* character to be truncated */ int plen; /* current part length */ int min_part = MIN_PART; /* current minimum part length */ char *p; len = strlen(name); if (decompress) { if (len <= 1) gzip_error ("name too short"); name[len-1] = '\0'; return; } p = get_suffix(name); if (! p) gzip_error ("can't recover suffix\n"); *p = '\0'; save_orig_name = 1; /* compress 1234567890.tar to 1234567890.tgz */ if (len > 4 && strequ(p-4, ".tar")) { strcpy(p-4, ".tgz"); return; } /* Try keeping short extensions intact: * 1234.678.012.gz -> 123.678.012.gz */ do { p = strrchr(name, PATH_SEP); p = p ? p+1 : name; while (*p) { plen = strcspn(p, PART_SEP); p += plen; if (plen > min_part) trunc = p-1; if (*p) p++; } } while (trunc == NULL && --min_part != 0); if (trunc != NULL) { do { trunc[0] = trunc[1]; } while (*trunc++); trunc--; } else { trunc = strrchr(name, PART_SEP[0]); if (!trunc) gzip_error ("internal error in shorten_name"); if (trunc[1] == '\0') trunc--; /* force truncation */ } strcpy(trunc, z_suffix); } /* ======================================================================== * The compressed file already exists, so ask for confirmation. * Return ERROR if the file must be skipped. */ local int check_ofname() { /* Ask permission to overwrite the existing file */ if (!force) { int ok = 0; fprintf (stderr, "%s: %s already exists;", program_name, ofname); if (foreground && isatty(fileno(stdin))) { fprintf(stderr, " do you wish to overwrite (y or n)? "); fflush(stderr); ok = yesno(); } if (!ok) { fprintf(stderr, "\tnot overwritten\n"); if (exit_code == OK) exit_code = WARNING; return ERROR; } } if (xunlink (ofname)) { progerror(ofname); return ERROR; } return OK; } /* ======================================================================== * Copy modes, times, ownership from input file to output file. * IN assertion: to_stdout is false. */ local void copy_stat(ifstat) struct stat *ifstat; { mode_t mode = ifstat->st_mode & S_IRWXUGO; int r; #ifndef NO_UTIME struct timespec timespec[2]; timespec[0] = get_stat_atime (ifstat); timespec[1] = get_stat_mtime (ifstat); if (decompress && 0 <= time_stamp.tv_nsec && ! (timespec[1].tv_sec == time_stamp.tv_sec && timespec[1].tv_nsec == time_stamp.tv_nsec)) { timespec[1] = time_stamp; if (verbose > 1) { fprintf(stderr, "%s: time stamp restored\n", ofname); } } if (gl_futimens (ofd, ofname, timespec) != 0) { int e = errno; WARN ((stderr, "%s: ", program_name)); if (!quiet) { errno = e; perror (ofname); } } #endif #ifndef NO_CHOWN # if HAVE_FCHOWN fchown (ofd, ifstat->st_uid, ifstat->st_gid); /* Copy ownership */ # elif HAVE_CHOWN chown(ofname, ifstat->st_uid, ifstat->st_gid); /* Copy ownership */ # endif #endif /* Copy the protection modes */ #if HAVE_FCHMOD r = fchmod (ofd, mode); #else r = chmod (ofname, mode); #endif if (r != 0) { int e = errno; WARN ((stderr, "%s: ", program_name)); if (!quiet) { errno = e; perror(ofname); } } } #if ! NO_DIR /* ======================================================================== * Recurse through the given directory. This code is taken from ncompress. */ local void treat_dir (fd, dir) int fd; char *dir; { struct dirent *dp; DIR *dirp; char nbuf[MAX_PATH_LEN]; int len; #if HAVE_FDOPENDIR dirp = fdopendir (fd); #else close (fd); dirp = opendir(dir); #endif if (dirp == NULL) { progerror(dir); #if HAVE_FDOPENDIR close (fd); #endif return ; } /* ** WARNING: the following algorithm could occasionally cause ** compress to produce error warnings of the form "<filename>.gz ** already has .gz suffix - ignored". This occurs when the ** .gz output file is inserted into the directory below ** readdir's current pointer. ** These warnings are harmless but annoying, so they are suppressed ** with option -r (except when -v is on). An alternative ** to allowing this would be to store the entire directory ** list in memory, then compress the entries in the stored ** list. Given the depth-first recursive algorithm used here, ** this could use up a tremendous amount of memory. I don't ** think it's worth it. -- Dave Mack ** (An other alternative might be two passes to avoid depth-first.) */ while ((errno = 0, dp = readdir(dirp)) != NULL) { if (strequ(dp->d_name,".") || strequ(dp->d_name,"..")) { continue; } len = strlen(dir); if (len + _D_EXACT_NAMLEN (dp) + 1 < MAX_PATH_LEN - 1) { strcpy(nbuf,dir); if (len != 0 /* dir = "" means current dir on Amiga */ #ifdef PATH_SEP2 && dir[len-1] != PATH_SEP2 #endif #ifdef PATH_SEP3 && dir[len-1] != PATH_SEP3 #endif ) { nbuf[len++] = PATH_SEP; } strcpy(nbuf+len, dp->d_name); treat_file(nbuf); } else { fprintf(stderr,"%s: %s/%s: pathname too long\n", program_name, dir, dp->d_name); exit_code = ERROR; } } if (errno != 0) progerror(dir); if (CLOSEDIR(dirp) != 0) progerror(dir); } #endif /* ! NO_DIR */ /* Make sure signals get handled properly. */ static void install_signal_handlers () { int nsigs = sizeof handled_sig / sizeof handled_sig[0]; int i; #if SA_NOCLDSTOP struct sigaction act; sigemptyset (&caught_signals); for (i = 0; i < nsigs; i++) { sigaction (handled_sig[i], NULL, &act); if (act.sa_handler != SIG_IGN) sigaddset (&caught_signals, handled_sig[i]); } act.sa_handler = abort_gzip_signal; act.sa_mask = caught_signals; act.sa_flags = 0; for (i = 0; i < nsigs; i++) if (sigismember (&caught_signals, handled_sig[i])) { if (i == 0) foreground = 1; sigaction (handled_sig[i], &act, NULL); } #else for (i = 0; i < nsigs; i++) if (signal (handled_sig[i], SIG_IGN) != SIG_IGN) { if (i == 0) foreground = 1; signal (handled_sig[i], abort_gzip_signal); siginterrupt (handled_sig[i], 1); } #endif } /* ======================================================================== * Free all dynamically allocated variables and exit with the given code. */ local void do_exit(exitcode) int exitcode; { static int in_exit = 0; if (in_exit) exit(exitcode); in_exit = 1; free(env); env = NULL; free(args); args = NULL; FREE(inbuf); FREE(outbuf); FREE(d_buf); FREE(window); #ifndef MAXSEG_64K FREE(tab_prefix); #else FREE(tab_prefix0); FREE(tab_prefix1); #endif exit(exitcode); } /* ======================================================================== * Close and unlink the output file. */ static void remove_output_file () { int fd; sigset_t oldset; sigprocmask (SIG_BLOCK, &caught_signals, &oldset); fd = remove_ofname_fd; if (0 <= fd) { remove_ofname_fd = -1; close (fd); xunlink (ofname); } sigprocmask (SIG_SETMASK, &oldset, NULL); } /* ======================================================================== * Error handler. */ void abort_gzip () { remove_output_file (); do_exit(ERROR); } /* ======================================================================== * Signal handler. */ static RETSIGTYPE abort_gzip_signal (sig) int sig; { if (! SA_NOCLDSTOP) signal (sig, SIG_IGN); remove_output_file (); if (sig == exiting_signal) _exit (WARNING); signal (sig, SIG_DFL); raise (sig); } /* gzip (GNU zip) -- compress files with zip algorithm and 'compress' interface Copyright (C) 1999, 2001-2002, 2006-2007, 2009 Free Software Foundation, Inc. Copyright (C) 1992-1993 Jean-loup Gailly This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * The unzip code was written and put in the public domain by Mark Adler. * Portions of the lzw code are derived from the public domain 'compress' * written by Spencer Thomas, Joe Orost, James Woods, Jim McKie, Steve Davies, * Ken Turkowski, Dave Mack and Peter Jannesen. * * See the license_msg below and the file COPYING for the software license. * See the file algorithm.doc for the compression algorithms and file formats. */ static char *license_msg[] = { "Copyright (C) 2007 Free Software Foundation, Inc.", "Copyright (C) 1993 Jean-loup Gailly.", "This is free software. You may redistribute copies of it under the terms of", "the GNU General Public License <http://www.gnu.org/licenses/gpl.html>.", "There is NO WARRANTY, to the extent permitted by law.", 0}; /* Compress files with zip algorithm and 'compress' interface. * See help() function below for all options. * Outputs: * file.gz: compressed file with same mode, owner, and utimes * or stdout with -c option or if stdin used as input. * If the output file name had to be truncated, the original name is kept * in the compressed file. * On MSDOS, file.tmp -> file.tmz. On VMS, file.tmp -> file.tmp-gz. * * Using gz on MSDOS would create too many file name conflicts. For * example, foo.txt -> foo.tgz (.tgz must be reserved as shorthand for * tar.gz). Similarly, foo.dir and foo.doc would both be mapped to foo.dgz. * I also considered 12345678.txt -> 12345txt.gz but this truncates the name * too heavily. There is no ideal solution given the MSDOS 8+3 limitation. * * For the meaning of all compilation flags, see comments in Makefile.in. */ #include <config.h> #include <ctype.h> #include <sys/types.h> #include <signal.h> #include <sys/stat.h> #include <errno.h> #include "closein.h" #include "tailor.h" #include "gzip.h" #include "lzw.h" #include "revision.h" #include "fcntl-safer.h" #include "getopt.h" #include "stat-time.h" /* configuration */ #ifdef HAVE_FCNTL_H # include <fcntl.h> #endif #ifdef HAVE_LIMITS_H # include <limits.h> #endif #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #if defined STDC_HEADERS || defined HAVE_STDLIB_H # include <stdlib.h> #else extern int errno; #endif #ifndef NO_DIR # define NO_DIR 0 #endif #if !NO_DIR # include <dirent.h> # ifndef _D_EXACT_NAMLEN # define _D_EXACT_NAMLEN(dp) strlen ((dp)->d_name) # endif #endif #ifdef CLOSEDIR_VOID # define CLOSEDIR(d) (closedir(d), 0) #else # define CLOSEDIR(d) closedir(d) #endif #ifndef NO_UTIME # include <utimens.h> #endif #define RW_USER (S_IRUSR | S_IWUSR) /* creation mode for open() */ #ifndef MAX_PATH_LEN # define MAX_PATH_LEN 1024 /* max pathname length */ #endif #ifndef SEEK_END # define SEEK_END 2 #endif #ifndef CHAR_BIT # define CHAR_BIT 8 #endif #ifdef off_t off_t lseek OF((int fd, off_t offset, int whence)); #endif #ifndef OFF_T_MIN #define OFF_T_MIN (~ (off_t) 0 << (sizeof (off_t) * CHAR_BIT - 1)) #endif #ifndef OFF_T_MAX #define OFF_T_MAX (~ (off_t) 0 - OFF_T_MIN) #endif /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is present. */ #ifndef SA_NOCLDSTOP # define SA_NOCLDSTOP 0 # define sigprocmask(how, set, oset) /* empty */ # define sigset_t int # if ! HAVE_SIGINTERRUPT # define siginterrupt(sig, flag) /* empty */ # endif #endif #ifndef HAVE_WORKING_O_NOFOLLOW # define HAVE_WORKING_O_NOFOLLOW 0 #endif #ifndef ELOOP # define ELOOP EINVAL #endif /* Separator for file name parts (see shorten_name()) */ #ifdef NO_MULTIPLE_DOTS # define PART_SEP "-" #else # define PART_SEP "." #endif /* global buffers */ DECLARE(uch, inbuf, INBUFSIZ +INBUF_EXTRA); DECLARE(uch, outbuf, OUTBUFSIZ+OUTBUF_EXTRA); DECLARE(ush, d_buf, DIST_BUFSIZE); DECLARE(uch, window, 2L*WSIZE); #ifndef MAXSEG_64K DECLARE(ush, tab_prefix, 1L<<BITS); #else DECLARE(ush, tab_prefix0, 1L<<(BITS-1)); DECLARE(ush, tab_prefix1, 1L<<(BITS-1)); #endif /* local variables */ int ascii = 0; /* convert end-of-lines to local OS conventions */ int to_stdout = 0; /* output to stdout (-c) */ int decompress = 0; /* decompress (-d) */ int force = 0; /* don't ask questions, compress links (-f) */ int no_name = -1; /* don't save or restore the original file name */ int no_time = -1; /* don't save or restore the original file time */ int recursive = 0; /* recurse through directories (-r) */ int list = 0; /* list the file contents (-l) */ int verbose = 0; /* be verbose (-v) */ int quiet = 0; /* be very quiet (-q) */ int do_lzw = 0; /* generate output compatible with old compress (-Z) */ int test = 0; /* test .gz file integrity */ int foreground = 0; /* set if program run in foreground */ char *program_name; /* program name */ int maxbits = BITS; /* max bits per code for LZW */ int method = DEFLATED;/* compression method */ int level = 6; /* compression level */ int exit_code = OK; /* program exit code */ int save_orig_name; /* set if original name must be saved */ int last_member; /* set for .zip and .Z files */ int part_nb; /* number of parts in .gz file */ struct timespec time_stamp; /* original time stamp (modification time) */ off_t ifile_size; /* input file size, -1 for devices (debug only) */ char *env; /* contents of GZIP env variable */ char **args = NULL; /* argv pointer if GZIP env variable defined */ char *z_suffix; /* default suffix (can be set with --suffix) */ size_t z_len; /* strlen(z_suffix) */ /* The set of signals that are caught. */ static sigset_t caught_signals; /* If nonzero then exit with status WARNING, rather than with the usual signal status, on receipt of a signal with this value. This suppresses a "Broken Pipe" message with some shells. */ static int volatile exiting_signal; /* If nonnegative, close this file descriptor and unlink ofname on error. */ static int volatile remove_ofname_fd = -1; off_t bytes_in; /* number of input bytes */ off_t bytes_out; /* number of output bytes */ off_t total_in; /* input bytes for all files */ off_t total_out; /* output bytes for all files */ char ifname[MAX_PATH_LEN]; /* input file name */ char ofname[MAX_PATH_LEN]; /* output file name */ struct stat istat; /* status for input file */ int ifd; /* input file descriptor */ int ofd; /* output file descriptor */ unsigned insize; /* valid bytes in inbuf */ unsigned inptr; /* index of next byte to be processed in inbuf */ unsigned outcnt; /* bytes in output buffer */ static int handled_sig[] = { /* SIGINT must be first, as 'foreground' depends on it. */ SIGINT #ifdef SIGHUP , SIGHUP #endif #ifdef SIGPIPE , SIGPIPE #else # define SIGPIPE 0 #endif #ifdef SIGTERM , SIGTERM #endif #ifdef SIGXCPU , SIGXCPU #endif #ifdef SIGXFSZ , SIGXFSZ #endif }; struct option longopts[] = { /* { name has_arg *flag val } */ {"ascii", 0, 0, 'a'}, /* ascii text mode */ {"to-stdout", 0, 0, 'c'}, /* write output on standard output */ {"stdout", 0, 0, 'c'}, /* write output on standard output */ {"decompress", 0, 0, 'd'}, /* decompress */ {"uncompress", 0, 0, 'd'}, /* decompress */ /* {"encrypt", 0, 0, 'e'}, encrypt */ {"force", 0, 0, 'f'}, /* force overwrite of output file */ {"help", 0, 0, 'h'}, /* give help */ /* {"pkzip", 0, 0, 'k'}, force output in pkzip format */ {"list", 0, 0, 'l'}, /* list .gz file contents */ {"license", 0, 0, 'L'}, /* display software license */ {"no-name", 0, 0, 'n'}, /* don't save or restore original name & time */ {"name", 0, 0, 'N'}, /* save or restore original name & time */ {"quiet", 0, 0, 'q'}, /* quiet mode */ {"silent", 0, 0, 'q'}, /* quiet mode */ {"recursive", 0, 0, 'r'}, /* recurse through directories */ {"suffix", 1, 0, 'S'}, /* use given suffix instead of .gz */ {"test", 0, 0, 't'}, /* test compressed file integrity */ {"no-time", 0, 0, 'T'}, /* don't save or restore the time stamp */ {"verbose", 0, 0, 'v'}, /* verbose mode */ {"version", 0, 0, 'V'}, /* display version number */ {"fast", 0, 0, '1'}, /* compress faster */ {"best", 0, 0, '9'}, /* compress better */ {"lzw", 0, 0, 'Z'}, /* make output compatible with old compress */ {"bits", 1, 0, 'b'}, /* max number of bits per code (implies -Z) */ { 0, 0, 0, 0 } }; /* local functions */ local void try_help OF((void)) ATTRIBUTE_NORETURN; local void help OF((void)); local void license OF((void)); local void version OF((void)); local int input_eof OF((void)); local void treat_stdin OF((void)); local void treat_file OF((char *iname)); local int create_outfile OF((void)); local char *get_suffix OF((char *name)); local int open_input_file OF((char *iname, struct stat *sbuf)); local int make_ofname OF((void)); local void shorten_name OF((char *name)); local int get_method OF((int in)); local void do_list OF((int ifd, int method)); local int check_ofname OF((void)); local void copy_stat OF((struct stat *ifstat)); local void install_signal_handlers OF((void)); local void remove_output_file OF((void)); local RETSIGTYPE abort_gzip_signal OF((int)); local void do_exit OF((int exitcode)) ATTRIBUTE_NORETURN; int main OF((int argc, char **argv)); int (*work) OF((int infile, int outfile)) = zip; /* function to call */ #if ! NO_DIR local void treat_dir OF((int fd, char *dir)); #endif #define strequ(s1, s2) (strcmp((s1),(s2)) == 0) static void try_help () { fprintf (stderr, "Try `%s --help' for more information.\n", program_name); do_exit (ERROR); } /* ======================================================================== */ local void help() { static char *help_msg[] = { "Compress or uncompress FILEs (by default, compress FILES in-place).", "", "Mandatory arguments to long options are mandatory for short options too.", "", #if O_BINARY " -a, --ascii ascii text; convert end-of-line using local conventions", #endif " -c, --stdout write on standard output, keep original files unchanged", " -d, --decompress decompress", /* -e, --encrypt encrypt */ " -f, --force force overwrite of output file and compress links", " -h, --help give this help", /* -k, --pkzip force output in pkzip format */ " -l, --list list compressed file contents", " -L, --license display software license", #ifdef UNDOCUMENTED " -m, --no-time do not save or restore the original modification time", " -M, --time save or restore the original modification time", #endif " -n, --no-name do not save or restore the original name and time stamp", " -N, --name save or restore the original name and time stamp", " -q, --quiet suppress all warnings", #if ! NO_DIR " -r, --recursive operate recursively on directories", #endif " -S, --suffix=SUF use suffix SUF on compressed files", " -t, --test test compressed file integrity", " -v, --verbose verbose mode", " -V, --version display version number", " -1, --fast compress faster", " -9, --best compress better", #ifdef LZW " -Z, --lzw produce output compatible with old compress", " -b, --bits=BITS max number of bits per code (implies -Z)", #endif "", "With no FILE, or when FILE is -, read standard input.", "", "Report bugs to <[email protected]>.", 0}; char **p = help_msg; printf ("Usage: %s [OPTION]... [FILE]...\n", program_name); while (*p) printf ("%s\n", *p++); } /* ======================================================================== */ local void license() { char **p = license_msg; printf ("%s %s\n", program_name, VERSION); while (*p) printf ("%s\n", *p++); } /* ======================================================================== */ local void version() { license (); printf ("\n"); printf ("Written by Jean-loup Gailly.\n"); } local void progerror (string) char *string; { int e = errno; fprintf (stderr, "%s: ", program_name); errno = e; perror(string); exit_code = ERROR; } /* ======================================================================== */ int main (argc, argv) int argc; char **argv; { int file_count; /* number of files to process */ size_t proglen; /* length of program_name */ int optc; /* current option */ EXPAND(argc, argv); /* wild card expansion if necessary */ program_name = gzip_base_name (argv[0]); proglen = strlen (program_name); atexit (close_stdin); /* Suppress .exe for MSDOS, OS/2 and VMS: */ if (4 < proglen && strequ (program_name + proglen - 4, ".exe")) program_name[proglen - 4] = '\0'; /* Add options in GZIP environment variable if there is one */ env = add_envopt(&argc, &argv, OPTIONS_VAR); if (env != NULL) args = argv; #ifndef GNU_STANDARD # define GNU_STANDARD 1 #endif #if !GNU_STANDARD /* For compatibility with old compress, use program name as an option. * Unless you compile with -DGNU_STANDARD=0, this program will behave as * gzip even if it is invoked under the name gunzip or zcat. * * Systems which do not support links can still use -d or -dc. * Ignore an .exe extension for MSDOS, OS/2 and VMS. */ if (strncmp (program_name, "un", 2) == 0 /* ungzip, uncompress */ || strncmp (program_name, "gun", 3) == 0) /* gunzip */ decompress = 1; else if (strequ (program_name + 1, "cat") /* zcat, pcat, gcat */ || strequ (program_name, "gzcat")) /* gzcat */ decompress = to_stdout = 1; #endif z_suffix = Z_SUFFIX; z_len = strlen(z_suffix); while ((optc = getopt_long (argc, argv, "ab:cdfhH?lLmMnNqrS:tvVZ123456789", longopts, (int *)0)) != -1) { switch (optc) { case 'a': ascii = 1; break; case 'b': maxbits = atoi(optarg); for (; *optarg; optarg++) if (! ('0' <= *optarg && *optarg <= '9')) { fprintf (stderr, "%s: -b operand is not an integer\n", program_name); try_help (); } break; case 'c': to_stdout = 1; break; case 'd': decompress = 1; break; case 'f': force++; break; case 'h': case 'H': help(); do_exit(OK); break; case 'l': list = decompress = to_stdout = 1; break; case 'L': license(); do_exit(OK); break; case 'm': /* undocumented, may change later */ no_time = 1; break; case 'M': /* undocumented, may change later */ no_time = 0; break; case 'n': no_name = no_time = 1; break; case 'N': no_name = no_time = 0; break; case 'q': quiet = 1; verbose = 0; break; case 'r': #if NO_DIR fprintf (stderr, "%s: -r not supported on this system\n", program_name); try_help (); #else recursive = 1; #endif break; case 'S': #ifdef NO_MULTIPLE_DOTS if (*optarg == '.') optarg++; #endif z_len = strlen(optarg); z_suffix = optarg; break; case 't': test = decompress = to_stdout = 1; break; case 'v': verbose++; quiet = 0; break; case 'V': version(); do_exit(OK); break; case 'Z': #ifdef LZW do_lzw = 1; break; #else fprintf(stderr, "%s: -Z not supported in this version\n", program_name); try_help (); break; #endif case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': level = optc - '0'; break; default: /* Error message already emitted by getopt_long. */ try_help (); } } /* loop on all arguments */ /* By default, save name and timestamp on compression but do not * restore them on decompression. */ if (no_time < 0) no_time = decompress; if (no_name < 0) no_name = decompress; file_count = argc - optind; #if O_BINARY #else if (ascii && !quiet) { fprintf(stderr, "%s: option --ascii ignored on this system\n", program_name); } #endif if ((z_len == 0 && !decompress) || z_len > MAX_SUFFIX) { fprintf(stderr, "%s: incorrect suffix '%s'\n", program_name, z_suffix); do_exit(ERROR); } if (do_lzw && !decompress) work = lzw; /* Allocate all global buffers (for DYN_ALLOC option) */ ALLOC(uch, inbuf, INBUFSIZ +INBUF_EXTRA); ALLOC(uch, outbuf, OUTBUFSIZ+OUTBUF_EXTRA); ALLOC(ush, d_buf, DIST_BUFSIZE); ALLOC(uch, window, 2L*WSIZE); #ifndef MAXSEG_64K ALLOC(ush, tab_prefix, 1L<<BITS); #else ALLOC(ush, tab_prefix0, 1L<<(BITS-1)); ALLOC(ush, tab_prefix1, 1L<<(BITS-1)); #endif exiting_signal = quiet ? SIGPIPE : 0; install_signal_handlers (); /* And get to work */ if (file_count != 0) { if (to_stdout && !test && !list && (!decompress || !ascii)) { SET_BINARY_MODE(fileno(stdout)); } while (optind < argc) { treat_file(argv[optind++]); } } else { /* Standard input */ treat_stdin(); } if (list && !quiet && file_count > 1) { do_list(-1, -1); /* print totals */ } do_exit(exit_code); return exit_code; /* just to avoid lint warning */ } /* Return nonzero when at end of file on input. */ local int input_eof () { if (!decompress || last_member) return 1; if (inptr == insize) { if (insize != INBUFSIZ || fill_inbuf (1) == EOF) return 1; /* Unget the char that fill_inbuf got. */ inptr = 0; } return 0; } /* ======================================================================== * Compress or decompress stdin */ local void treat_stdin() { if (!force && !list && isatty(fileno((FILE *)(decompress ? stdin : stdout)))) { /* Do not send compressed data to the terminal or read it from * the terminal. We get here when user invoked the program * without parameters, so be helpful. According to the GNU standards: * * If there is one behavior you think is most useful when the output * is to a terminal, and another that you think is most useful when * the output is a file or a pipe, then it is usually best to make * the default behavior the one that is useful with output to a * terminal, and have an option for the other behavior. * * Here we use the --force option to get the other behavior. */ fprintf(stderr, "%s: compressed data not %s a terminal. Use -f to force %scompression.\n", program_name, decompress ? "read from" : "written to", decompress ? "de" : ""); fprintf (stderr, "For help, type: %s -h\n", program_name); do_exit(ERROR); } if (decompress || !ascii) { SET_BINARY_MODE(fileno(stdin)); } if (!test && !list && (!decompress || !ascii)) { SET_BINARY_MODE(fileno(stdout)); } strcpy(ifname, "stdin"); strcpy(ofname, "stdout"); /* Get the file's time stamp and size. */ if (fstat (fileno (stdin), &istat) != 0) { progerror ("standard input"); do_exit (ERROR); } ifile_size = S_ISREG (istat.st_mode) ? istat.st_size : -1; time_stamp.tv_nsec = -1; if (!no_time || list) time_stamp = get_stat_mtime (&istat); clear_bufs(); /* clear input and output buffers */ to_stdout = 1; part_nb = 0; ifd = fileno(stdin); if (decompress) { method = get_method(ifd); if (method < 0) { do_exit(exit_code); /* error message already emitted */ } } if (list) { do_list(ifd, method); return; } /* Actually do the compression/decompression. Loop over zipped members. */ for (;;) { if ((*work)(fileno(stdin), fileno(stdout)) != OK) return; if (input_eof ()) break; method = get_method(ifd); if (method < 0) return; /* error message already emitted */ bytes_out = 0; /* required for length check */ } if (verbose) { if (test) { fprintf(stderr, " OK\n"); } else if (!decompress) { display_ratio(bytes_in-(bytes_out-header_bytes), bytes_in, stderr); fprintf(stderr, "\n"); #ifdef DISPLAY_STDIN_RATIO } else { display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out,stderr); fprintf(stderr, "\n"); #endif } } } /* ======================================================================== * Compress or decompress the given file */ local void treat_file(iname) char *iname; { /* Accept "-" as synonym for stdin */ if (strequ(iname, "-")) { int cflag = to_stdout; treat_stdin(); to_stdout = cflag; return; } /* Check if the input file is present, set ifname and istat: */ ifd = open_input_file (iname, &istat); if (ifd < 0) return; /* If the input name is that of a directory, recurse or ignore: */ if (S_ISDIR(istat.st_mode)) { #if ! NO_DIR if (recursive) { treat_dir (ifd, iname); /* Warning: ifname is now garbage */ return; } #endif close (ifd); WARN ((stderr, "%s: %s is a directory -- ignored\n", program_name, ifname)); return; } if (! to_stdout) { if (! S_ISREG (istat.st_mode)) { WARN ((stderr, "%s: %s is not a directory or a regular file - ignored\n", program_name, ifname)); close (ifd); return; } if (istat.st_mode & S_ISUID) { WARN ((stderr, "%s: %s is set-user-ID on execution - ignored\n", program_name, ifname)); close (ifd); return; } if (istat.st_mode & S_ISGID) { WARN ((stderr, "%s: %s is set-group-ID on execution - ignored\n", program_name, ifname)); close (ifd); return; } if (! force) { if (istat.st_mode & S_ISVTX) { WARN ((stderr, "%s: %s has the sticky bit set - file ignored\n", program_name, ifname)); close (ifd); return; } if (2 <= istat.st_nlink) { WARN ((stderr, "%s: %s has %lu other link%c -- unchanged\n", program_name, ifname, (unsigned long int) istat.st_nlink - 1, istat.st_nlink == 2 ? ' ' : 's')); close (ifd); return; } } } ifile_size = S_ISREG (istat.st_mode) ? istat.st_size : -1; time_stamp.tv_nsec = -1; if (!no_time || list) time_stamp = get_stat_mtime (&istat); /* Generate output file name. For -r and (-t or -l), skip files * without a valid gzip suffix (check done in make_ofname). */ if (to_stdout && !list && !test) { strcpy(ofname, "stdout"); } else if (make_ofname() != OK) { close (ifd); return; } clear_bufs(); /* clear input and output buffers */ part_nb = 0; if (decompress) { method = get_method(ifd); /* updates ofname if original given */ if (method < 0) { close(ifd); return; /* error message already emitted */ } } if (list) { do_list(ifd, method); if (close (ifd) != 0) read_error (); return; } /* If compressing to a file, check if ofname is not ambiguous * because the operating system truncates names. Otherwise, generate * a new ofname and save the original name in the compressed file. */ if (to_stdout) { ofd = fileno(stdout); /* Keep remove_ofname_fd negative. */ } else { if (create_outfile() != OK) return; if (!decompress && save_orig_name && !verbose && !quiet) { fprintf(stderr, "%s: %s compressed to %s\n", program_name, ifname, ofname); } } /* Keep the name even if not truncated except with --no-name: */ if (!save_orig_name) save_orig_name = !no_name; if (verbose) { fprintf(stderr, "%s:\t", ifname); } /* Actually do the compression/decompression. Loop over zipped members. */ for (;;) { if ((*work)(ifd, ofd) != OK) { method = -1; /* force cleanup */ break; } if (input_eof ()) break; method = get_method(ifd); if (method < 0) break; /* error message already emitted */ bytes_out = 0; /* required for length check */ } if (close (ifd) != 0) read_error (); if (!to_stdout) { sigset_t oldset; int unlink_errno; copy_stat (&istat); if (close (ofd) != 0) write_error (); sigprocmask (SIG_BLOCK, &caught_signals, &oldset); remove_ofname_fd = -1; unlink_errno = xunlink (ifname) == 0 ? 0 : errno; sigprocmask (SIG_SETMASK, &oldset, NULL); if (unlink_errno) { WARN ((stderr, "%s: ", program_name)); if (!quiet) { errno = unlink_errno; perror (ifname); } } } if (method == -1) { if (!to_stdout) remove_output_file (); return; } /* Display statistics */ if(verbose) { if (test) { fprintf(stderr, " OK"); } else if (decompress) { display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out,stderr); } else { display_ratio(bytes_in-(bytes_out-header_bytes), bytes_in, stderr); } if (!test && !to_stdout) { fprintf(stderr, " -- replaced with %s", ofname); } fprintf(stderr, "\n"); } } /* ======================================================================== * Create the output file. Return OK or ERROR. * Try several times if necessary to avoid truncating the z_suffix. For * example, do not create a compressed file of name "1234567890123." * Sets save_orig_name to true if the file name has been truncated. * IN assertions: the input file has already been open (ifd is set) and * ofname has already been updated if there was an original name. * OUT assertions: ifd and ofd are closed in case of error. */ local int create_outfile() { int name_shortened = 0; int flags = (O_WRONLY | O_CREAT | O_EXCL | (ascii && decompress ? 0 : O_BINARY)); for (;;) { int open_errno; sigset_t oldset; sigprocmask (SIG_BLOCK, &caught_signals, &oldset); remove_ofname_fd = ofd = OPEN (ofname, flags, RW_USER); open_errno = errno; sigprocmask (SIG_SETMASK, &oldset, NULL); if (0 <= ofd) break; switch (open_errno) { #ifdef ENAMETOOLONG case ENAMETOOLONG: shorten_name (ofname); name_shortened = 1; break; #endif case EEXIST: if (check_ofname () != OK) { close (ifd); return ERROR; } break; default: progerror (ofname); close (ifd); return ERROR; } } if (name_shortened && decompress) { /* name might be too long if an original name was saved */ WARN ((stderr, "%s: %s: warning, name truncated\n", program_name, ofname)); } return OK; } /* ======================================================================== * Return a pointer to the 'z' suffix of a file name, or NULL. For all * systems, ".gz", ".z", ".Z", ".taz", ".tgz", "-gz", "-z" and "_z" are * accepted suffixes, in addition to the value of the --suffix option. * ".tgz" is a useful convention for tar.z files on systems limited * to 3 characters extensions. On such systems, ".?z" and ".??z" are * also accepted suffixes. For Unix, we do not want to accept any * .??z suffix as indicating a compressed file; some people use .xyz * to denote volume data. * On systems allowing multiple versions of the same file (such as VMS), * this function removes any version suffix in the given name. */ local char *get_suffix(name) char *name; { int nlen, slen; char suffix[MAX_SUFFIX+3]; /* last chars of name, forced to lower case */ static char *known_suffixes[] = {NULL, ".gz", ".z", ".taz", ".tgz", "-gz", "-z", "_z", #ifdef MAX_EXT_CHARS "z", #endif NULL}; char **suf = known_suffixes; *suf = z_suffix; if (strequ(z_suffix, "z")) suf++; /* check long suffixes first */ #ifdef SUFFIX_SEP /* strip a version number from the file name */ { char *v = strrchr(name, SUFFIX_SEP); if (v != NULL) *v = '\0'; } #endif nlen = strlen(name); if (nlen <= MAX_SUFFIX+2) { strcpy(suffix, name); } else { strcpy(suffix, name+nlen-MAX_SUFFIX-2); } strlwr(suffix); slen = strlen(suffix); do { int s = strlen(*suf); if (slen > s && suffix[slen-s-1] != PATH_SEP && strequ(suffix + slen - s, *suf)) { return name+nlen-s; } } while (*++suf != NULL); return NULL; } /* Open file NAME with the given flags and mode and store its status into *ST. Return a file descriptor to the newly opened file, or -1 (setting errno) on failure. */ static int open_and_stat (char *name, int flags, mode_t mode, struct stat *st) { int fd; /* Refuse to follow symbolic links unless -c or -f. */ if (!to_stdout && !force) { if (HAVE_WORKING_O_NOFOLLOW) flags |= O_NOFOLLOW; else { #if HAVE_LSTAT || defined lstat if (lstat (name, st) != 0) return -1; else if (S_ISLNK (st->st_mode)) { errno = ELOOP; return -1; } #endif } } fd = OPEN (name, flags, mode); if (0 <= fd && fstat (fd, st) != 0) { int e = errno; close (fd); errno = e; return -1; } return fd; } /* ======================================================================== * Set ifname to the input file name (with a suffix appended if necessary) * and istat to its stats. For decompression, if no file exists with the * original name, try adding successively z_suffix, .gz, .z, -z and .Z. * For MSDOS, we try only z_suffix and z. * Return an open file descriptor or -1. */ static int open_input_file (iname, sbuf) char *iname; struct stat *sbuf; { int ilen; /* strlen(ifname) */ int z_suffix_errno = 0; static char *suffixes[] = {NULL, ".gz", ".z", "-z", ".Z", NULL}; char **suf = suffixes; char *s; #ifdef NO_MULTIPLE_DOTS char *dot; /* pointer to ifname extension, or NULL */ #endif int fd; int open_flags = (O_RDONLY | O_NONBLOCK | O_NOCTTY | (ascii && !decompress ? 0 : O_BINARY)); *suf = z_suffix; if (sizeof ifname - 1 <= strlen (iname)) goto name_too_long; strcpy(ifname, iname); /* If input file exists, return OK. */ fd = open_and_stat (ifname, open_flags, RW_USER, sbuf); if (0 <= fd) return fd; if (!decompress || errno != ENOENT) { progerror(ifname); return -1; } /* file.ext doesn't exist, try adding a suffix (after removing any * version number for VMS). */ s = get_suffix(ifname); if (s != NULL) { progerror(ifname); /* ifname already has z suffix and does not exist */ return -1; } #ifdef NO_MULTIPLE_DOTS dot = strrchr(ifname, '.'); if (dot == NULL) { strcat(ifname, "."); dot = strrchr(ifname, '.'); } #endif ilen = strlen(ifname); if (strequ(z_suffix, ".gz")) suf++; /* Search for all suffixes */ do { char *s0 = s = *suf; strcpy (ifname, iname); #ifdef NO_MULTIPLE_DOTS if (*s == '.') s++; if (*dot == '\0') strcpy (dot, "."); #endif #ifdef MAX_EXT_CHARS if (MAX_EXT_CHARS < strlen (s) + strlen (dot + 1)) dot[MAX_EXT_CHARS + 1 - strlen (s)] = '\0'; #endif if (sizeof ifname <= ilen + strlen (s)) goto name_too_long; strcat(ifname, s); fd = open_and_stat (ifname, open_flags, RW_USER, sbuf); if (0 <= fd) return fd; if (errno != ENOENT) { progerror (ifname); return -1; } if (strequ (s0, z_suffix)) z_suffix_errno = errno; } while (*++suf != NULL); /* No suffix found, complain using z_suffix: */ strcpy(ifname, iname); #ifdef NO_MULTIPLE_DOTS if (*dot == '\0') strcpy(dot, "."); #endif #ifdef MAX_EXT_CHARS if (MAX_EXT_CHARS < z_len + strlen (dot + 1)) dot[MAX_EXT_CHARS + 1 - z_len] = '\0'; #endif strcat(ifname, z_suffix); errno = z_suffix_errno; progerror(ifname); return -1; name_too_long: fprintf (stderr, "%s: %s: file name too long\n", program_name, iname); exit_code = ERROR; return -1; } /* ======================================================================== * Generate ofname given ifname. Return OK, or WARNING if file must be skipped. * Sets save_orig_name to true if the file name has been truncated. */ local int make_ofname() { char *suff; /* ofname z suffix */ strcpy(ofname, ifname); /* strip a version number if any and get the gzip suffix if present: */ suff = get_suffix(ofname); if (decompress) { if (suff == NULL) { /* With -t or -l, try all files (even without .gz suffix) * except with -r (behave as with just -dr). */ if (!recursive && (list || test)) return OK; /* Avoid annoying messages with -r */ if (verbose || (!recursive && !quiet)) { WARN((stderr,"%s: %s: unknown suffix -- ignored\n", program_name, ifname)); } return WARNING; } /* Make a special case for .tgz and .taz: */ strlwr(suff); if (strequ(suff, ".tgz") || strequ(suff, ".taz")) { strcpy(suff, ".tar"); } else { *suff = '\0'; /* strip the z suffix */ } /* ofname might be changed later if infile contains an original name */ } else if (suff && ! force) { /* Avoid annoying messages with -r (see treat_dir()) */ if (verbose || (!recursive && !quiet)) { /* Don't use WARN, as it affects exit status. */ fprintf (stderr, "%s: %s already has %s suffix -- unchanged\n", program_name, ifname, suff); } return WARNING; } else { save_orig_name = 0; #ifdef NO_MULTIPLE_DOTS suff = strrchr(ofname, '.'); if (suff == NULL) { if (sizeof ofname <= strlen (ofname) + 1) goto name_too_long; strcat(ofname, "."); # ifdef MAX_EXT_CHARS if (strequ(z_suffix, "z")) { if (sizeof ofname <= strlen (ofname) + 2) goto name_too_long; strcat(ofname, "gz"); /* enough room */ return OK; } /* On the Atari and some versions of MSDOS, * ENAMETOOLONG does not work correctly. So we * must truncate here. */ } else if (strlen(suff)-1 + z_len > MAX_SUFFIX) { suff[MAX_SUFFIX+1-z_len] = '\0'; save_orig_name = 1; # endif } #endif /* NO_MULTIPLE_DOTS */ if (sizeof ofname <= strlen (ofname) + z_len) goto name_too_long; strcat(ofname, z_suffix); } /* decompress ? */ return OK; name_too_long: WARN ((stderr, "%s: %s: file name too long\n", program_name, ifname)); return WARNING; } /* ======================================================================== * Check the magic number of the input file and update ofname if an * original name was given and to_stdout is not set. * Return the compression method, -1 for error, -2 for warning. * Set inptr to the offset of the next byte to be processed. * Updates time_stamp if there is one and --no-time is not used. * This function may be called repeatedly for an input file consisting * of several contiguous gzip'ed members. * IN assertions: there is at least one remaining compressed member. * If the member is a zip file, it must be the only one. */ local int get_method(in) int in; /* input file descriptor */ { uch flags; /* compression flags */ char magic[2]; /* magic header */ int imagic1; /* like magic[1], but can represent EOF */ ulg stamp; /* time stamp */ /* If --force and --stdout, zcat == cat, so do not complain about * premature end of file: use try_byte instead of get_byte. */ if (force && to_stdout) { magic[0] = (char)try_byte(); imagic1 = try_byte (); magic[1] = (char) imagic1; /* If try_byte returned EOF, magic[1] == (char) EOF. */ } else { magic[0] = (char)get_byte(); magic[1] = (char)get_byte(); imagic1 = 0; /* avoid lint warning */ } method = -1; /* unknown yet */ part_nb++; /* number of parts in gzip file */ header_bytes = 0; last_member = RECORD_IO; /* assume multiple members in gzip file except for record oriented I/O */ if (memcmp(magic, GZIP_MAGIC, 2) == 0 || memcmp(magic, OLD_GZIP_MAGIC, 2) == 0) { method = (int)get_byte(); if (method != DEFLATED) { fprintf(stderr, "%s: %s: unknown method %d -- not supported\n", program_name, ifname, method); exit_code = ERROR; return -1; } work = unzip; flags = (uch)get_byte(); if ((flags & ENCRYPTED) != 0) { fprintf(stderr, "%s: %s is encrypted -- not supported\n", program_name, ifname); exit_code = ERROR; return -1; } if ((flags & CONTINUATION) != 0) { fprintf(stderr, "%s: %s is a multi-part gzip file -- not supported\n", program_name, ifname); exit_code = ERROR; if (force <= 1) return -1; } if ((flags & RESERVED) != 0) { fprintf(stderr, "%s: %s has flags 0x%x -- not supported\n", program_name, ifname, flags); exit_code = ERROR; if (force <= 1) return -1; } stamp = (ulg)get_byte(); stamp |= ((ulg)get_byte()) << 8; stamp |= ((ulg)get_byte()) << 16; stamp |= ((ulg)get_byte()) << 24; if (stamp != 0 && !no_time) { time_stamp.tv_sec = stamp; time_stamp.tv_nsec = 0; } (void)get_byte(); /* Ignore extra flags for the moment */ (void)get_byte(); /* Ignore OS type for the moment */ if ((flags & CONTINUATION) != 0) { unsigned part = (unsigned)get_byte(); part |= ((unsigned)get_byte())<<8; if (verbose) { fprintf(stderr,"%s: %s: part number %u\n", program_name, ifname, part); } } if ((flags & EXTRA_FIELD) != 0) { unsigned len = (unsigned)get_byte(); len |= ((unsigned)get_byte())<<8; if (verbose) { fprintf(stderr,"%s: %s: extra field of %u bytes ignored\n", program_name, ifname, len); } while (len--) (void)get_byte(); } /* Get original file name if it was truncated */ if ((flags & ORIG_NAME) != 0) { if (no_name || (to_stdout && !list) || part_nb > 1) { /* Discard the old name */ char c; /* dummy used for NeXTstep 3.0 cc optimizer bug */ do {c=get_byte();} while (c != 0); } else { /* Copy the base name. Keep a directory prefix intact. */ char *p = gzip_base_name (ofname); char *base = p; for (;;) { *p = (char)get_char(); if (*p++ == '\0') break; if (p >= ofname+sizeof(ofname)) { gzip_error ("corrupted input -- file name too large"); } } p = gzip_base_name (base); memmove (base, p, strlen (p) + 1); /* If necessary, adapt the name to local OS conventions: */ if (!list) { MAKE_LEGAL_NAME(base); if (base) list=0; /* avoid warning about unused variable */ } } /* no_name || to_stdout */ } /* ORIG_NAME */ /* Discard file comment if any */ if ((flags & COMMENT) != 0) { while (get_char() != 0) /* null */ ; } if (part_nb == 1) { header_bytes = inptr + 2*sizeof(long); /* include crc and size */ } } else if (memcmp(magic, PKZIP_MAGIC, 2) == 0 && inptr == 2 && memcmp((char*)inbuf, PKZIP_MAGIC, 4) == 0) { /* To simplify the code, we support a zip file when alone only. * We are thus guaranteed that the entire local header fits in inbuf. */ inptr = 0; work = unzip; if (check_zipfile(in) != OK) return -1; /* check_zipfile may get ofname from the local header */ last_member = 1; } else if (memcmp(magic, PACK_MAGIC, 2) == 0) { work = unpack; method = PACKED; } else if (memcmp(magic, LZW_MAGIC, 2) == 0) { work = unlzw; method = COMPRESSED; last_member = 1; } else if (memcmp(magic, LZH_MAGIC, 2) == 0) { work = unlzh; method = LZHED; last_member = 1; } else if (force && to_stdout && !list) { /* pass input unchanged */ method = STORED; work = copy; inptr = 0; last_member = 1; } if (method >= 0) return method; if (part_nb == 1) { fprintf (stderr, "\n%s: %s: not in gzip format\n", program_name, ifname); exit_code = ERROR; return -1; } else { if (magic[0] == 0) { int inbyte; for (inbyte = imagic1; inbyte == 0; inbyte = try_byte ()) continue; if (inbyte == EOF) { if (verbose) WARN ((stderr, "\n%s: %s: decompression OK, trailing zero bytes ignored\n", program_name, ifname)); return -3; } } WARN((stderr, "\n%s: %s: decompression OK, trailing garbage ignored\n", program_name, ifname)); return -2; } } /* ======================================================================== * Display the characteristics of the compressed file. * If the given method is < 0, display the accumulated totals. * IN assertions: time_stamp, header_bytes and ifile_size are initialized. */ local void do_list(ifd, method) int ifd; /* input file descriptor */ int method; /* compression method */ { ulg crc; /* original crc */ static int first_time = 1; static char* methods[MAX_METHODS] = { "store", /* 0 */ "compr", /* 1 */ "pack ", /* 2 */ "lzh ", /* 3 */ "", "", "", "", /* 4 to 7 reserved */ "defla"}; /* 8 */ int positive_off_t_width = 1; off_t o; for (o = OFF_T_MAX; 9 < o; o /= 10) { positive_off_t_width++; } if (first_time && method >= 0) { first_time = 0; if (verbose) { printf("method crc date time "); } if (!quiet) { printf("%*.*s %*.*s ratio uncompressed_name\n", positive_off_t_width, positive_off_t_width, "compressed", positive_off_t_width, positive_off_t_width, "uncompressed"); } } else if (method < 0) { if (total_in <= 0 || total_out <= 0) return; if (verbose) { printf(" "); } if (verbose || !quiet) { fprint_off(stdout, total_in, positive_off_t_width); printf(" "); fprint_off(stdout, total_out, positive_off_t_width); printf(" "); } display_ratio(total_out-(total_in-header_bytes), total_out, stdout); /* header_bytes is not meaningful but used to ensure the same * ratio if there is a single file. */ printf(" (totals)\n"); return; } crc = (ulg)~0; /* unknown */ bytes_out = -1L; bytes_in = ifile_size; #if RECORD_IO == 0 if (method == DEFLATED && !last_member) { /* Get the crc and uncompressed size for gzip'ed (not zip'ed) files. * If the lseek fails, we could use read() to get to the end, but * --list is used to get quick results. * Use "gunzip < foo.gz | wc -c" to get the uncompressed size if * you are not concerned about speed. */ bytes_in = lseek(ifd, (off_t)(-8), SEEK_END); if (bytes_in != -1L) { uch buf[8]; bytes_in += 8L; if (read(ifd, (char*)buf, sizeof(buf)) != sizeof(buf)) { read_error(); } crc = LG(buf); bytes_out = LG(buf+4); } } #endif /* RECORD_IO */ if (verbose) { struct tm *tm = localtime (&time_stamp.tv_sec); printf ("%5s %08lx ", methods[method], crc); if (tm) printf ("%s%3d %02d:%02d ", ("Jan\0Feb\0Mar\0Apr\0May\0Jun\0Jul\0Aug\0Sep\0Oct\0Nov\0Dec" + 4 * tm->tm_mon), tm->tm_mday, tm->tm_hour, tm->tm_min); else printf ("??? ?? ??:?? "); } fprint_off(stdout, bytes_in, positive_off_t_width); printf(" "); fprint_off(stdout, bytes_out, positive_off_t_width); printf(" "); if (bytes_in == -1L) { total_in = -1L; bytes_in = bytes_out = header_bytes = 0; } else if (total_in >= 0) { total_in += bytes_in; } if (bytes_out == -1L) { total_out = -1L; bytes_in = bytes_out = header_bytes = 0; } else if (total_out >= 0) { total_out += bytes_out; } display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out, stdout); printf(" %s\n", ofname); } /* ======================================================================== * Shorten the given name by one character, or replace a .tar extension * with .tgz. Truncate the last part of the name which is longer than * MIN_PART characters: 1234.678.012.gz -> 123.678.012.gz. If the name * has only parts shorter than MIN_PART truncate the longest part. * For decompression, just remove the last character of the name. * * IN assertion: for compression, the suffix of the given name is z_suffix. */ local void shorten_name(name) char *name; { int len; /* length of name without z_suffix */ char *trunc = NULL; /* character to be truncated */ int plen; /* current part length */ int min_part = MIN_PART; /* current minimum part length */ char *p; len = strlen(name); if (decompress) { if (len <= 1) gzip_error ("name too short"); name[len-1] = '\0'; return; } p = get_suffix(name); if (! p) gzip_error ("can't recover suffix\n"); *p = '\0'; save_orig_name = 1; /* compress 1234567890.tar to 1234567890.tgz */ if (len > 4 && strequ(p-4, ".tar")) { strcpy(p-4, ".tgz"); return; } /* Try keeping short extensions intact: * 1234.678.012.gz -> 123.678.012.gz */ do { p = strrchr(name, PATH_SEP); p = p ? p+1 : name; while (*p) { plen = strcspn(p, PART_SEP); p += plen; if (plen > min_part) trunc = p-1; if (*p) p++; } } while (trunc == NULL && --min_part != 0); if (trunc != NULL) { do { trunc[0] = trunc[1]; } while (*trunc++); trunc--; } else { trunc = strrchr(name, PART_SEP[0]); if (!trunc) gzip_error ("internal error in shorten_name"); if (trunc[1] == '\0') trunc--; /* force truncation */ } strcpy(trunc, z_suffix); } /* ======================================================================== * The compressed file already exists, so ask for confirmation. * Return ERROR if the file must be skipped. */ local int check_ofname() { /* Ask permission to overwrite the existing file */ if (!force) { int ok = 0; fprintf (stderr, "%s: %s already exists;", program_name, ofname); if (foreground && isatty(fileno(stdin))) { fprintf(stderr, " do you wish to overwrite (y or n)? "); fflush(stderr); ok = yesno(); } if (!ok) { fprintf(stderr, "\tnot overwritten\n"); if (exit_code == OK) exit_code = WARNING; return ERROR; } } if (xunlink (ofname)) { progerror(ofname); return ERROR; } return OK; } /* ======================================================================== * Copy modes, times, ownership from input file to output file. * IN assertion: to_stdout is false. */ local void copy_stat(ifstat) struct stat *ifstat; { mode_t mode = ifstat->st_mode & S_IRWXUGO; int r; #ifndef NO_UTIME struct timespec timespec[2]; timespec[0] = get_stat_atime (ifstat); timespec[1] = get_stat_mtime (ifstat); if (decompress && 0 <= time_stamp.tv_nsec && ! (timespec[1].tv_sec == time_stamp.tv_sec && timespec[1].tv_nsec == time_stamp.tv_nsec)) { timespec[1] = time_stamp; if (verbose > 1) { fprintf(stderr, "%s: time stamp restored\n", ofname); } } if (gl_futimens (ofd, ofname, timespec) != 0) { int e = errno; WARN ((stderr, "%s: ", program_name)); if (!quiet) { errno = e; perror (ofname); } } #endif #ifndef NO_CHOWN # if HAVE_FCHOWN fchown (ofd, ifstat->st_uid, ifstat->st_gid); /* Copy ownership */ # elif HAVE_CHOWN chown(ofname, ifstat->st_uid, ifstat->st_gid); /* Copy ownership */ # endif #endif /* Copy the protection modes */ #if HAVE_FCHMOD r = fchmod (ofd, mode); #else r = chmod (ofname, mode); #endif if (r != 0) { int e = errno; WARN ((stderr, "%s: ", program_name)); if (!quiet) { errno = e; perror(ofname); } } } #if ! NO_DIR /* ======================================================================== * Recurse through the given directory. This code is taken from ncompress. */ local void treat_dir (fd, dir) int fd; char *dir; { struct dirent *dp; DIR *dirp; char nbuf[MAX_PATH_LEN]; int len; #if HAVE_FDOPENDIR dirp = fdopendir (fd); #else close (fd); dirp = opendir(dir); #endif if (dirp == NULL) { progerror(dir); #if HAVE_FDOPENDIR close (fd); #endif return ; } /* ** WARNING: the following algorithm could occasionally cause ** compress to produce error warnings of the form "<filename>.gz ** already has .gz suffix - ignored". This occurs when the ** .gz output file is inserted into the directory below ** readdir's current pointer. ** These warnings are harmless but annoying, so they are suppressed ** with option -r (except when -v is on). An alternative ** to allowing this would be to store the entire directory ** list in memory, then compress the entries in the stored ** list. Given the depth-first recursive algorithm used here, ** this could use up a tremendous amount of memory. I don't ** think it's worth it. -- Dave Mack ** (An other alternative might be two passes to avoid depth-first.) */ while ((errno = 0, dp = readdir(dirp)) != NULL) { if (strequ(dp->d_name,".") || strequ(dp->d_name,"..")) { continue; } len = strlen(dir); if (len + _D_EXACT_NAMLEN (dp) + 1 < MAX_PATH_LEN - 1) { strcpy(nbuf,dir); if (len != 0 /* dir = "" means current dir on Amiga */ #ifdef PATH_SEP2 && dir[len-1] != PATH_SEP2 #endif #ifdef PATH_SEP3 && dir[len-1] != PATH_SEP3 #endif ) { nbuf[len++] = PATH_SEP; } strcpy(nbuf+len, dp->d_name); treat_file(nbuf); } else { fprintf(stderr,"%s: %s/%s: pathname too long\n", program_name, dir, dp->d_name); exit_code = ERROR; } } if (errno != 0) progerror(dir); if (CLOSEDIR(dirp) != 0) progerror(dir); } #endif /* ! NO_DIR */ /* Make sure signals get handled properly. */ static void install_signal_handlers () { int nsigs = sizeof handled_sig / sizeof handled_sig[0]; int i; #if SA_NOCLDSTOP struct sigaction act; sigemptyset (&caught_signals); for (i = 0; i < nsigs; i++) { sigaction (handled_sig[i], NULL, &act); if (act.sa_handler != SIG_IGN) sigaddset (&caught_signals, handled_sig[i]); } act.sa_handler = abort_gzip_signal; act.sa_mask = caught_signals; act.sa_flags = 0; for (i = 0; i < nsigs; i++) if (sigismember (&caught_signals, handled_sig[i])) { if (i == 0) foreground = 1; sigaction (handled_sig[i], &act, NULL); } #else for (i = 0; i < nsigs; i++) if (signal (handled_sig[i], SIG_IGN) != SIG_IGN) { if (i == 0) foreground = 1; signal (handled_sig[i], abort_gzip_signal); siginterrupt (handled_sig[i], 1); } #endif } /* ======================================================================== * Free all dynamically allocated variables and exit with the given code. */ local void do_exit(exitcode) int exitcode; { static int in_exit = 0; if (in_exit) exit(exitcode); in_exit = 1; free(env); env = NULL; free(args); args = NULL; FREE(inbuf); FREE(outbuf); FREE(d_buf); FREE(window); #ifndef MAXSEG_64K FREE(tab_prefix); #else FREE(tab_prefix0); FREE(tab_prefix1); #endif exit(exitcode); } /* ======================================================================== * Close and unlink the output file. */ static void remove_output_file () { int fd; sigset_t oldset; sigprocmask (SIG_BLOCK, &caught_signals, &oldset); fd = remove_ofname_fd; if (0 <= fd) { remove_ofname_fd = -1; close (fd); xunlink (ofname); } sigprocmask (SIG_SETMASK, &oldset, NULL); } /* ======================================================================== * Error handler. */ void abort_gzip () { remove_output_file (); do_exit(ERROR); } /* ======================================================================== * Signal handler. */ static RETSIGTYPE abort_gzip_signal (sig) int sig; { if (! SA_NOCLDSTOP) signal (sig, SIG_IGN); remove_output_file (); if (sig == exiting_signal) _exit (WARNING); signal (sig, SIG_DFL); raise (sig); }
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/gzip_2009-09-26-a1d3d4019d-f17cbd13a1.c
manybugs_data_79
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2012 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | Andrei Zmievski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "zend.h" #include "zend_execute.h" #include "zend_API.h" #include "zend_modules.h" #include "zend_constants.h" #include "zend_exceptions.h" #include "zend_closures.h" #ifdef HAVE_STDARG_H #include <stdarg.h> #endif /* these variables are true statics/globals, and have to be mutex'ed on every access */ static int module_count=0; ZEND_API HashTable module_registry; static zend_module_entry **module_request_startup_handlers; static zend_module_entry **module_request_shutdown_handlers; static zend_module_entry **module_post_deactivate_handlers; static zend_class_entry **class_cleanup_handlers; /* this function doesn't check for too many parameters */ ZEND_API int zend_get_parameters(int ht, int param_count, ...) /* {{{ */ { void **p; int arg_count; va_list ptr; zval **param, *param_ptr; TSRMLS_FETCH(); p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } va_start(ptr, param_count); while (param_count-->0) { param = va_arg(ptr, zval **); param_ptr = *(p-arg_count); if (!PZVAL_IS_REF(param_ptr) && Z_REFCOUNT_P(param_ptr) > 1) { zval *new_tmp; ALLOC_ZVAL(new_tmp); *new_tmp = *param_ptr; zval_copy_ctor(new_tmp); INIT_PZVAL(new_tmp); param_ptr = new_tmp; Z_DELREF_P((zval *) *(p-arg_count)); *(p-arg_count) = param_ptr; } *param = param_ptr; arg_count--; } va_end(ptr); return SUCCESS; } /* }}} */ ZEND_API int _zend_get_parameters_array(int ht, int param_count, zval **argument_array TSRMLS_DC) /* {{{ */ { void **p; int arg_count; zval *param_ptr; p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } while (param_count-->0) { param_ptr = *(p-arg_count); if (!PZVAL_IS_REF(param_ptr) && Z_REFCOUNT_P(param_ptr) > 1) { zval *new_tmp; ALLOC_ZVAL(new_tmp); *new_tmp = *param_ptr; zval_copy_ctor(new_tmp); INIT_PZVAL(new_tmp); param_ptr = new_tmp; Z_DELREF_P((zval *) *(p-arg_count)); *(p-arg_count) = param_ptr; } *(argument_array++) = param_ptr; arg_count--; } return SUCCESS; } /* }}} */ /* Zend-optimized Extended functions */ /* this function doesn't check for too many parameters */ ZEND_API int zend_get_parameters_ex(int param_count, ...) /* {{{ */ { void **p; int arg_count; va_list ptr; zval ***param; TSRMLS_FETCH(); p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } va_start(ptr, param_count); while (param_count-->0) { param = va_arg(ptr, zval ***); *param = (zval **) p-(arg_count--); } va_end(ptr); return SUCCESS; } /* }}} */ ZEND_API int _zend_get_parameters_array_ex(int param_count, zval ***argument_array TSRMLS_DC) /* {{{ */ { void **p; int arg_count; p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } while (param_count-->0) { zval **value = (zval**)(p-arg_count); *(argument_array++) = value; arg_count--; } return SUCCESS; } /* }}} */ ZEND_API int zend_copy_parameters_array(int param_count, zval *argument_array TSRMLS_DC) /* {{{ */ { void **p; int arg_count; p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } while (param_count-->0) { zval **param = (zval **) p-(arg_count--); zval_add_ref(param); add_next_index_zval(argument_array, *param); } return SUCCESS; } /* }}} */ ZEND_API void zend_wrong_param_count(TSRMLS_D) /* {{{ */ { const char *space; const char *class_name = get_active_class_name(&space TSRMLS_CC); zend_error(E_WARNING, "Wrong parameter count for %s%s%s()", class_name, space, get_active_function_name(TSRMLS_C)); } /* }}} */ /* Argument parsing API -- andrei */ ZEND_API char *zend_get_type_by_const(int type) /* {{{ */ { switch(type) { case IS_BOOL: return "boolean"; case IS_LONG: return "integer"; case IS_DOUBLE: return "double"; case IS_STRING: return "string"; case IS_OBJECT: return "object"; case IS_RESOURCE: return "resource"; case IS_NULL: return "null"; case IS_CALLABLE: return "callable"; case IS_ARRAY: return "array"; default: return "unknown"; } } /* }}} */ ZEND_API char *zend_zval_type_name(const zval *arg) /* {{{ */ { return zend_get_type_by_const(Z_TYPE_P(arg)); } /* }}} */ ZEND_API zend_class_entry *zend_get_class_entry(const zval *zobject TSRMLS_DC) /* {{{ */ { if (Z_OBJ_HT_P(zobject)->get_class_entry) { return Z_OBJ_HT_P(zobject)->get_class_entry(zobject TSRMLS_CC); } else { zend_error(E_ERROR, "Class entry requested for an object without PHP class"); return NULL; } } /* }}} */ /* returns 1 if you need to copy result, 0 if it's already a copy */ ZEND_API int zend_get_object_classname(const zval *object, const char **class_name, zend_uint *class_name_len TSRMLS_DC) /* {{{ */ { if (Z_OBJ_HT_P(object)->get_class_name == NULL || Z_OBJ_HT_P(object)->get_class_name(object, class_name, class_name_len, 0 TSRMLS_CC) != SUCCESS) { zend_class_entry *ce = Z_OBJCE_P(object); *class_name = ce->name; *class_name_len = ce->name_length; return 1; } return 0; } /* }}} */ static int parse_arg_object_to_string(zval **arg, char **p, int *pl, int type TSRMLS_DC) /* {{{ */ { if (Z_OBJ_HANDLER_PP(arg, cast_object)) { zval *obj; ALLOC_ZVAL(obj); MAKE_COPY_ZVAL(arg, obj); if (Z_OBJ_HANDLER_P(*arg, cast_object)(*arg, obj, type TSRMLS_CC) == SUCCESS) { zval_ptr_dtor(arg); *arg = obj; *pl = Z_STRLEN_PP(arg); *p = Z_STRVAL_PP(arg); return SUCCESS; } zval_ptr_dtor(&obj); } /* Standard PHP objects */ if (Z_OBJ_HT_PP(arg) == &std_object_handlers || !Z_OBJ_HANDLER_PP(arg, cast_object)) { SEPARATE_ZVAL_IF_NOT_REF(arg); if (zend_std_cast_object_tostring(*arg, *arg, type TSRMLS_CC) == SUCCESS) { *pl = Z_STRLEN_PP(arg); *p = Z_STRVAL_PP(arg); return SUCCESS; } } if (!Z_OBJ_HANDLER_PP(arg, cast_object) && Z_OBJ_HANDLER_PP(arg, get)) { int use_copy; zval *z = Z_OBJ_HANDLER_PP(arg, get)(*arg TSRMLS_CC); Z_ADDREF_P(z); if(Z_TYPE_P(z) != IS_OBJECT) { zval_dtor(*arg); Z_TYPE_P(*arg) = IS_NULL; zend_make_printable_zval(z, *arg, &use_copy); if (!use_copy) { ZVAL_ZVAL(*arg, z, 1, 1); } *pl = Z_STRLEN_PP(arg); *p = Z_STRVAL_PP(arg); return SUCCESS; } zval_ptr_dtor(&z); } return FAILURE; } /* }}} */ static const char *zend_parse_arg_impl(int arg_num, zval **arg, va_list *va, const char **spec, char **error, int *severity TSRMLS_DC) /* {{{ */ { const char *spec_walk = *spec; char c = *spec_walk++; int return_null = 0; /* scan through modifiers */ while (1) { if (*spec_walk == '/') { SEPARATE_ZVAL_IF_NOT_REF(arg); } else if (*spec_walk == '!') { if (Z_TYPE_PP(arg) == IS_NULL) { return_null = 1; } } else { break; } spec_walk++; } switch (c) { case 'l': case 'L': { long *p = va_arg(*va, long *); switch (Z_TYPE_PP(arg)) { case IS_STRING: { double d; int type; if ((type = is_numeric_string(Z_STRVAL_PP(arg), Z_STRLEN_PP(arg), p, &d, -1)) == 0) { return "long"; } else if (type == IS_DOUBLE) { if (c == 'L') { if (d > LONG_MAX) { *p = LONG_MAX; break; } else if (d < LONG_MIN) { *p = LONG_MIN; break; } } *p = zend_dval_to_lval(d); } } break; case IS_DOUBLE: if (c == 'L') { if (Z_DVAL_PP(arg) > LONG_MAX) { *p = LONG_MAX; break; } else if (Z_DVAL_PP(arg) < LONG_MIN) { *p = LONG_MIN; break; } } case IS_NULL: case IS_LONG: case IS_BOOL: convert_to_long_ex(arg); *p = Z_LVAL_PP(arg); break; case IS_ARRAY: case IS_OBJECT: case IS_RESOURCE: default: return "long"; } } break; case 'd': { double *p = va_arg(*va, double *); switch (Z_TYPE_PP(arg)) { case IS_STRING: { long l; int type; if ((type = is_numeric_string(Z_STRVAL_PP(arg), Z_STRLEN_PP(arg), &l, p, -1)) == 0) { return "double"; } else if (type == IS_LONG) { *p = (double) l; } } break; case IS_NULL: case IS_LONG: case IS_DOUBLE: case IS_BOOL: convert_to_double_ex(arg); *p = Z_DVAL_PP(arg); break; case IS_ARRAY: case IS_OBJECT: case IS_RESOURCE: default: return "double"; } } break; case 'p': case 's': { char **p = va_arg(*va, char **); int *pl = va_arg(*va, int *); switch (Z_TYPE_PP(arg)) { case IS_NULL: if (return_null) { *p = NULL; *pl = 0; break; } /* break omitted intentionally */ case IS_STRING: case IS_LONG: case IS_DOUBLE: case IS_BOOL: convert_to_string_ex(arg); if (UNEXPECTED(Z_ISREF_PP(arg) != 0)) { /* it's dangerous to return pointers to string buffer of referenced variable, because it can be clobbered throug magic callbacks */ SEPARATE_ZVAL(arg); } *p = Z_STRVAL_PP(arg); *pl = Z_STRLEN_PP(arg); if (c == 'p' && CHECK_ZVAL_NULL_PATH(*arg)) { return "a valid path"; } break; case IS_OBJECT: if (parse_arg_object_to_string(arg, p, pl, IS_STRING TSRMLS_CC) == SUCCESS) { if (c == 'p' && CHECK_ZVAL_NULL_PATH(*arg)) { return "a valid path"; } break; } case IS_ARRAY: case IS_RESOURCE: default: return c == 's' ? "string" : "a valid path"; } } break; case 'b': { zend_bool *p = va_arg(*va, zend_bool *); switch (Z_TYPE_PP(arg)) { case IS_NULL: case IS_STRING: case IS_LONG: case IS_DOUBLE: case IS_BOOL: convert_to_boolean_ex(arg); *p = Z_BVAL_PP(arg); break; case IS_ARRAY: case IS_OBJECT: case IS_RESOURCE: default: return "boolean"; } } break; case 'r': { zval **p = va_arg(*va, zval **); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_RESOURCE) { *p = *arg; } else { return "resource"; } } break; case 'A': case 'a': { zval **p = va_arg(*va, zval **); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_ARRAY || (c == 'A' && Z_TYPE_PP(arg) == IS_OBJECT)) { *p = *arg; } else { return "array"; } } break; case 'H': case 'h': { HashTable **p = va_arg(*va, HashTable **); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_ARRAY) { *p = Z_ARRVAL_PP(arg); } else if(c == 'H' && Z_TYPE_PP(arg) == IS_OBJECT) { *p = HASH_OF(*arg); if(*p == NULL) { return "array"; } } else { return "array"; } } break; case 'o': { zval **p = va_arg(*va, zval **); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_OBJECT) { *p = *arg; } else { return "object"; } } break; case 'O': { zval **p = va_arg(*va, zval **); zend_class_entry *ce = va_arg(*va, zend_class_entry *); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_OBJECT && (!ce || instanceof_function(Z_OBJCE_PP(arg), ce TSRMLS_CC))) { *p = *arg; } else { if (ce) { return ce->name; } else { return "object"; } } } break; case 'C': { zend_class_entry **lookup, **pce = va_arg(*va, zend_class_entry **); zend_class_entry *ce_base = *pce; if (return_null) { *pce = NULL; break; } convert_to_string_ex(arg); if (zend_lookup_class(Z_STRVAL_PP(arg), Z_STRLEN_PP(arg), &lookup TSRMLS_CC) == FAILURE) { *pce = NULL; } else { *pce = *lookup; } if (ce_base) { if ((!*pce || !instanceof_function(*pce, ce_base TSRMLS_CC))) { zend_spprintf(error, 0, "to be a class name derived from %s, '%s' given", ce_base->name, Z_STRVAL_PP(arg)); *pce = NULL; return ""; } } if (!*pce) { zend_spprintf(error, 0, "to be a valid class name, '%s' given", Z_STRVAL_PP(arg)); return ""; } break; } break; case 'f': { zend_fcall_info *fci = va_arg(*va, zend_fcall_info *); zend_fcall_info_cache *fcc = va_arg(*va, zend_fcall_info_cache *); char *is_callable_error = NULL; if (return_null) { fci->size = 0; fcc->initialized = 0; break; } if (zend_fcall_info_init(*arg, 0, fci, fcc, NULL, &is_callable_error TSRMLS_CC) == SUCCESS) { if (is_callable_error) { *severity = E_STRICT; zend_spprintf(error, 0, "to be a valid callback, %s", is_callable_error); efree(is_callable_error); *spec = spec_walk; return ""; } break; } else { if (is_callable_error) { *severity = E_WARNING; zend_spprintf(error, 0, "to be a valid callback, %s", is_callable_error); efree(is_callable_error); return ""; } else { return "valid callback"; } } } case 'z': { zval **p = va_arg(*va, zval **); if (return_null) { *p = NULL; } else { *p = *arg; } } break; case 'Z': { zval ***p = va_arg(*va, zval ***); if (return_null) { *p = NULL; } else { *p = arg; } } break; default: return "unknown"; } *spec = spec_walk; return NULL; } /* }}} */ static int zend_parse_arg(int arg_num, zval **arg, va_list *va, const char **spec, int quiet TSRMLS_DC) /* {{{ */ { const char *expected_type = NULL; char *error = NULL; int severity = E_WARNING; expected_type = zend_parse_arg_impl(arg_num, arg, va, spec, &error, &severity TSRMLS_CC); if (expected_type) { if (!quiet && (*expected_type || error)) { const char *space; const char *class_name = get_active_class_name(&space TSRMLS_CC); if (error) { zend_error(severity, "%s%s%s() expects parameter %d %s", class_name, space, get_active_function_name(TSRMLS_C), arg_num, error); efree(error); } else { zend_error(severity, "%s%s%s() expects parameter %d to be %s, %s given", class_name, space, get_active_function_name(TSRMLS_C), arg_num, expected_type, zend_zval_type_name(*arg)); } } if (severity != E_STRICT) { return FAILURE; } } return SUCCESS; } /* }}} */ static int zend_parse_va_args(int num_args, const char *type_spec, va_list *va, int flags TSRMLS_DC) /* {{{ */ { const char *spec_walk; int c, i; int min_num_args = -1; int max_num_args = 0; int post_varargs = 0; zval **arg; int arg_count; int quiet = flags & ZEND_PARSE_PARAMS_QUIET; zend_bool have_varargs = 0; zval ****varargs = NULL; int *n_varargs = NULL; for (spec_walk = type_spec; *spec_walk; spec_walk++) { c = *spec_walk; switch (c) { case 'l': case 'd': case 's': case 'b': case 'r': case 'a': case 'o': case 'O': case 'z': case 'Z': case 'C': case 'h': case 'f': case 'A': case 'H': case 'p': max_num_args++; break; case '|': min_num_args = max_num_args; break; case '/': case '!': /* Pass */ break; case '*': case '+': if (have_varargs) { if (!quiet) { zend_function *active_function = EG(current_execute_data)->function_state.function; const char *class_name = active_function->common.scope ? active_function->common.scope->name : ""; zend_error(E_WARNING, "%s%s%s(): only one varargs specifier (* or +) is permitted", class_name, class_name[0] ? "::" : "", active_function->common.function_name); } return FAILURE; } have_varargs = 1; /* we expect at least one parameter in varargs */ if (c == '+') { max_num_args++; } /* mark the beginning of varargs */ post_varargs = max_num_args; break; default: if (!quiet) { zend_function *active_function = EG(current_execute_data)->function_state.function; const char *class_name = active_function->common.scope ? active_function->common.scope->name : ""; zend_error(E_WARNING, "%s%s%s(): bad type specifier while parsing parameters", class_name, class_name[0] ? "::" : "", active_function->common.function_name); } return FAILURE; } } if (min_num_args < 0) { min_num_args = max_num_args; } if (have_varargs) { /* calculate how many required args are at the end of the specifier list */ post_varargs = max_num_args - post_varargs; max_num_args = -1; } if (num_args < min_num_args || (num_args > max_num_args && max_num_args > 0)) { if (!quiet) { zend_function *active_function = EG(current_execute_data)->function_state.function; const char *class_name = active_function->common.scope ? active_function->common.scope->name : ""; zend_error(E_WARNING, "%s%s%s() expects %s %d parameter%s, %d given", class_name, class_name[0] ? "::" : "", active_function->common.function_name, min_num_args == max_num_args ? "exactly" : num_args < min_num_args ? "at least" : "at most", num_args < min_num_args ? min_num_args : max_num_args, (num_args < min_num_args ? min_num_args : max_num_args) == 1 ? "" : "s", num_args); } return FAILURE; } arg_count = (int)(zend_uintptr_t) *(zend_vm_stack_top(TSRMLS_C) - 1); if (num_args > arg_count) { zend_error(E_WARNING, "%s(): could not obtain parameters for parsing", get_active_function_name(TSRMLS_C)); return FAILURE; } i = 0; while (num_args-- > 0) { if (*type_spec == '|') { type_spec++; } if (*type_spec == '*' || *type_spec == '+') { int num_varargs = num_args + 1 - post_varargs; /* eat up the passed in storage even if it won't be filled in with varargs */ varargs = va_arg(*va, zval ****); n_varargs = va_arg(*va, int *); type_spec++; if (num_varargs > 0) { int iv = 0; zval **p = (zval **) (zend_vm_stack_top(TSRMLS_C) - 1 - (arg_count - i)); *n_varargs = num_varargs; /* allocate space for array and store args */ *varargs = safe_emalloc(num_varargs, sizeof(zval **), 0); while (num_varargs-- > 0) { (*varargs)[iv++] = p++; } /* adjust how many args we have left and restart loop */ num_args = num_args + 1 - iv; i += iv; continue; } else { *varargs = NULL; *n_varargs = 0; } } arg = (zval **) (zend_vm_stack_top(TSRMLS_C) - 1 - (arg_count-i)); if (zend_parse_arg(i+1, arg, va, &type_spec, quiet TSRMLS_CC) == FAILURE) { /* clean up varargs array if it was used */ if (varargs && *varargs) { efree(*varargs); *varargs = NULL; } return FAILURE; } i++; } return SUCCESS; } /* }}} */ #define RETURN_IF_ZERO_ARGS(num_args, type_spec, quiet) { \ int __num_args = (num_args); \ \ if (0 == (type_spec)[0] && 0 != __num_args && !(quiet)) { \ const char *__space; \ const char * __class_name = get_active_class_name(&__space TSRMLS_CC); \ zend_error(E_WARNING, "%s%s%s() expects exactly 0 parameters, %d given", \ __class_name, __space, \ get_active_function_name(TSRMLS_C), __num_args); \ return FAILURE; \ }\ } ZEND_API int zend_parse_parameters_ex(int flags, int num_args TSRMLS_DC, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; RETURN_IF_ZERO_ARGS(num_args, type_spec, flags & ZEND_PARSE_PARAMS_QUIET); va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, flags TSRMLS_CC); va_end(va); return retval; } /* }}} */ ZEND_API int zend_parse_parameters(int num_args TSRMLS_DC, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; RETURN_IF_ZERO_ARGS(num_args, type_spec, 0); va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, 0 TSRMLS_CC); va_end(va); return retval; } /* }}} */ ZEND_API int zend_parse_method_parameters(int num_args TSRMLS_DC, zval *this_ptr, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; const char *p = type_spec; zval **object; zend_class_entry *ce; if (!this_ptr) { RETURN_IF_ZERO_ARGS(num_args, p, 0); va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, 0 TSRMLS_CC); va_end(va); } else { p++; RETURN_IF_ZERO_ARGS(num_args, p, 0); va_start(va, type_spec); object = va_arg(va, zval **); ce = va_arg(va, zend_class_entry *); *object = this_ptr; if (ce && !instanceof_function(Z_OBJCE_P(this_ptr), ce TSRMLS_CC)) { zend_error(E_CORE_ERROR, "%s::%s() must be derived from %s::%s", ce->name, get_active_function_name(TSRMLS_C), Z_OBJCE_P(this_ptr)->name, get_active_function_name(TSRMLS_C)); } retval = zend_parse_va_args(num_args, p, &va, 0 TSRMLS_CC); va_end(va); } return retval; } /* }}} */ ZEND_API int zend_parse_method_parameters_ex(int flags, int num_args TSRMLS_DC, zval *this_ptr, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; const char *p = type_spec; zval **object; zend_class_entry *ce; int quiet = flags & ZEND_PARSE_PARAMS_QUIET; if (!this_ptr) { RETURN_IF_ZERO_ARGS(num_args, p, quiet); va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, flags TSRMLS_CC); va_end(va); } else { p++; RETURN_IF_ZERO_ARGS(num_args, p, quiet); va_start(va, type_spec); object = va_arg(va, zval **); ce = va_arg(va, zend_class_entry *); *object = this_ptr; if (ce && !instanceof_function(Z_OBJCE_P(this_ptr), ce TSRMLS_CC)) { if (!quiet) { zend_error(E_CORE_ERROR, "%s::%s() must be derived from %s::%s", ce->name, get_active_function_name(TSRMLS_C), Z_OBJCE_P(this_ptr)->name, get_active_function_name(TSRMLS_C)); } va_end(va); return FAILURE; } retval = zend_parse_va_args(num_args, p, &va, flags TSRMLS_CC); va_end(va); } return retval; } /* }}} */ /* Argument parsing API -- andrei */ ZEND_API int _array_init(zval *arg, uint size ZEND_FILE_LINE_DC) /* {{{ */ { ALLOC_HASHTABLE_REL(Z_ARRVAL_P(arg)); _zend_hash_init(Z_ARRVAL_P(arg), size, NULL, ZVAL_PTR_DTOR, 0 ZEND_FILE_LINE_RELAY_CC); Z_TYPE_P(arg) = IS_ARRAY; return SUCCESS; } /* }}} */ static int zend_merge_property(zval **value TSRMLS_DC, int num_args, va_list args, const zend_hash_key *hash_key) /* {{{ */ { /* which name should a numeric property have ? */ if (hash_key->nKeyLength) { zval *obj = va_arg(args, zval *); zend_object_handlers *obj_ht = va_arg(args, zend_object_handlers *); zval *member; MAKE_STD_ZVAL(member); ZVAL_STRINGL(member, hash_key->arKey, hash_key->nKeyLength-1, 1); obj_ht->write_property(obj, member, *value, 0 TSRMLS_CC); zval_ptr_dtor(&member); } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* This function should be called after the constructor has been called * because it may call __set from the uninitialized object otherwise. */ ZEND_API void zend_merge_properties(zval *obj, HashTable *properties, int destroy_ht TSRMLS_DC) /* {{{ */ { const zend_object_handlers *obj_ht = Z_OBJ_HT_P(obj); zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE_P(obj); zend_hash_apply_with_arguments(properties TSRMLS_CC, (apply_func_args_t)zend_merge_property, 2, obj, obj_ht); EG(scope) = old_scope; if (destroy_ht) { zend_hash_destroy(properties); FREE_HASHTABLE(properties); } } /* }}} */ ZEND_API void zend_update_class_constants(zend_class_entry *class_type TSRMLS_DC) /* {{{ */ { if ((class_type->ce_flags & ZEND_ACC_CONSTANTS_UPDATED) == 0 || (!CE_STATIC_MEMBERS(class_type) && class_type->default_static_members_count)) { zend_class_entry **scope = EG(in_execution)?&EG(scope):&CG(active_class_entry); zend_class_entry *old_scope = *scope; int i; *scope = class_type; zend_hash_apply_with_argument(&class_type->constants_table, (apply_func_arg_t) zval_update_constant, (void*)1 TSRMLS_CC); for (i = 0; i < class_type->default_properties_count; i++) { if (class_type->default_properties_table[i]) { zval_update_constant(&class_type->default_properties_table[i], (void**)1 TSRMLS_CC); } } if (!CE_STATIC_MEMBERS(class_type) && class_type->default_static_members_count) { zval **p; if (class_type->parent) { zend_update_class_constants(class_type->parent TSRMLS_CC); } #if ZTS CG(static_members_table)[(zend_intptr_t)(class_type->static_members_table)] = emalloc(sizeof(zval*) * class_type->default_static_members_count); #else class_type->static_members_table = emalloc(sizeof(zval*) * class_type->default_static_members_count); #endif for (i = 0; i < class_type->default_static_members_count; i++) { p = &class_type->default_static_members_table[i]; if (Z_ISREF_PP(p) && class_type->parent && i < class_type->parent->default_static_members_count && *p == class_type->parent->default_static_members_table[i] && CE_STATIC_MEMBERS(class_type->parent)[i] ) { zval *q = CE_STATIC_MEMBERS(class_type->parent)[i]; Z_ADDREF_P(q); Z_SET_ISREF_P(q); CE_STATIC_MEMBERS(class_type)[i] = q; } else { zval *r; ALLOC_ZVAL(r); *r = **p; INIT_PZVAL(r); zval_copy_ctor(r); CE_STATIC_MEMBERS(class_type)[i] = r; } } } for (i = 0; i < class_type->default_static_members_count; i++) { zval_update_constant(&CE_STATIC_MEMBERS(class_type)[i], (void**)1 TSRMLS_CC); } *scope = old_scope; class_type->ce_flags |= ZEND_ACC_CONSTANTS_UPDATED; } } /* }}} */ ZEND_API void object_properties_init(zend_object *object, zend_class_entry *class_type) /* {{{ */ { int i; if (class_type->default_properties_count) { object->properties_table = emalloc(sizeof(zval*) * class_type->default_properties_count); for (i = 0; i < class_type->default_properties_count; i++) { object->properties_table[i] = class_type->default_properties_table[i]; if (class_type->default_properties_table[i]) { Z_ADDREF_P(object->properties_table[i]); } } object->properties = NULL; } } /* }}} */ /* This function requires 'properties' to contain all props declared in the * class and all props being public. If only a subset is given or the class * has protected members then you need to merge the properties seperately by * calling zend_merge_properties(). */ ZEND_API int _object_and_properties_init(zval *arg, zend_class_entry *class_type, HashTable *properties ZEND_FILE_LINE_DC TSRMLS_DC) /* {{{ */ { zend_object *object; if (class_type->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLICIT_ABSTRACT_CLASS|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) { char *what = (class_type->ce_flags & ZEND_ACC_INTERFACE) ? "interface" :((class_type->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) ? "trait" : "abstract class"; zend_error(E_ERROR, "Cannot instantiate %s %s", what, class_type->name); } zend_update_class_constants(class_type TSRMLS_CC); Z_TYPE_P(arg) = IS_OBJECT; if (class_type->create_object == NULL) { Z_OBJVAL_P(arg) = zend_objects_new(&object, class_type TSRMLS_CC); if (properties) { object->properties = properties; object->properties_table = NULL; } else { object_properties_init(object, class_type); } } else { Z_OBJVAL_P(arg) = class_type->create_object(class_type TSRMLS_CC); } return SUCCESS; } /* }}} */ ZEND_API int _object_init_ex(zval *arg, zend_class_entry *class_type ZEND_FILE_LINE_DC TSRMLS_DC) /* {{{ */ { return _object_and_properties_init(arg, class_type, 0 ZEND_FILE_LINE_RELAY_CC TSRMLS_CC); } /* }}} */ ZEND_API int _object_init(zval *arg ZEND_FILE_LINE_DC TSRMLS_DC) /* {{{ */ { return _object_init_ex(arg, zend_standard_class_def ZEND_FILE_LINE_RELAY_CC TSRMLS_CC); } /* }}} */ ZEND_API int add_assoc_function(zval *arg, const char *key, void (*function_ptr)(INTERNAL_FUNCTION_PARAMETERS)) /* {{{ */ { zend_error(E_WARNING, "add_assoc_function() is no longer supported"); return FAILURE; } /* }}} */ ZEND_API int add_assoc_long_ex(zval *arg, const char *key, uint key_len, long n) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, n); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_null_ex(zval *arg, const char *key, uint key_len) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_NULL(tmp); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_bool_ex(zval *arg, const char *key, uint key_len, int b) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_BOOL(tmp, b); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_resource_ex(zval *arg, const char *key, uint key_len, int r) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_RESOURCE(tmp, r); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_double_ex(zval *arg, const char *key, uint key_len, double d) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_string_ex(zval *arg, const char *key, uint key_len, char *str, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_stringl_ex(zval *arg, const char *key, uint key_len, char *str, uint length, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_zval_ex(zval *arg, const char *key, uint key_len, zval *value) /* {{{ */ { return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &value, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_long(zval *arg, ulong index, long n) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, n); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_null(zval *arg, ulong index) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_NULL(tmp); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_bool(zval *arg, ulong index, int b) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_BOOL(tmp, b); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_resource(zval *arg, ulong index, int r) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_RESOURCE(tmp, r); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_double(zval *arg, ulong index, double d) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_string(zval *arg, ulong index, const char *str, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_stringl(zval *arg, ulong index, const char *str, uint length, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_zval(zval *arg, ulong index, zval *value) /* {{{ */ { return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &value, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_long(zval *arg, long n) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, n); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_null(zval *arg) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_NULL(tmp); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_bool(zval *arg, int b) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_BOOL(tmp, b); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_resource(zval *arg, int r) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_RESOURCE(tmp, r); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_double(zval *arg, double d) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_string(zval *arg, const char *str, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_stringl(zval *arg, const char *str, uint length, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_zval(zval *arg, zval *value) /* {{{ */ { return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &value, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_get_assoc_string_ex(zval *arg, const char *key, uint key_len, const char *str, void **dest, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_assoc_stringl_ex(zval *arg, const char *key, uint key_len, const char *str, uint length, void **dest, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_index_long(zval *arg, ulong index, long l, void **dest) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, l); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_index_double(zval *arg, ulong index, double d, void **dest) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_index_string(zval *arg, ulong index, const char *str, void **dest, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_index_stringl(zval *arg, ulong index, const char *str, uint length, void **dest, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_property_long_ex(zval *arg, const char *key, uint key_len, long n TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, n); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_bool_ex(zval *arg, const char *key, uint key_len, int b TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_BOOL(tmp, b); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_null_ex(zval *arg, const char *key, uint key_len TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_NULL(tmp); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_resource_ex(zval *arg, const char *key, uint key_len, long n TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_RESOURCE(tmp, n); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_double_ex(zval *arg, const char *key, uint key_len, double d TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_string_ex(zval *arg, const char *key, uint key_len, const char *str, int duplicate TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_stringl_ex(zval *arg, const char *key, uint key_len, const char *str, uint length, int duplicate TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_zval_ex(zval *arg, const char *key, uint key_len, zval *value TSRMLS_DC) /* {{{ */ { zval *z_key; MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, value, 0 TSRMLS_CC); zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int zend_startup_module_ex(zend_module_entry *module TSRMLS_DC) /* {{{ */ { int name_len; char *lcname; if (module->module_started) { return SUCCESS; } module->module_started = 1; /* Check module dependencies */ if (module->deps) { const zend_module_dep *dep = module->deps; while (dep->name) { if (dep->type == MODULE_DEP_REQUIRED) { zend_module_entry *req_mod; name_len = strlen(dep->name); lcname = zend_str_tolower_dup(dep->name, name_len); if (zend_hash_find(&module_registry, lcname, name_len+1, (void**)&req_mod) == FAILURE || !req_mod->module_started) { efree(lcname); /* TODO: Check version relationship */ zend_error(E_CORE_WARNING, "Cannot load module '%s' because required module '%s' is not loaded", module->name, dep->name); module->module_started = 0; return FAILURE; } efree(lcname); } ++dep; } } /* Initialize module globals */ if (module->globals_size) { #ifdef ZTS ts_allocate_id(module->globals_id_ptr, module->globals_size, (ts_allocate_ctor) module->globals_ctor, (ts_allocate_dtor) module->globals_dtor); #else if (module->globals_ctor) { module->globals_ctor(module->globals_ptr TSRMLS_CC); } #endif } if (module->module_startup_func) { EG(current_module) = module; if (module->module_startup_func(module->type, module->module_number TSRMLS_CC)==FAILURE) { zend_error(E_CORE_ERROR,"Unable to start %s module", module->name); EG(current_module) = NULL; return FAILURE; } EG(current_module) = NULL; } return SUCCESS; } /* }}} */ static void zend_sort_modules(void *base, size_t count, size_t siz, compare_func_t compare TSRMLS_DC) /* {{{ */ { Bucket **b1 = base; Bucket **b2; Bucket **end = b1 + count; Bucket *tmp; zend_module_entry *m, *r; while (b1 < end) { try_again: m = (zend_module_entry*)(*b1)->pData; if (!m->module_started && m->deps) { const zend_module_dep *dep = m->deps; while (dep->name) { if (dep->type == MODULE_DEP_REQUIRED || dep->type == MODULE_DEP_OPTIONAL) { b2 = b1 + 1; while (b2 < end) { r = (zend_module_entry*)(*b2)->pData; if (strcasecmp(dep->name, r->name) == 0) { tmp = *b1; *b1 = *b2; *b2 = tmp; goto try_again; } b2++; } } dep++; } } b1++; } } /* }}} */ ZEND_API void zend_collect_module_handlers(TSRMLS_D) /* {{{ */ { HashPosition pos; zend_module_entry *module; int startup_count = 0; int shutdown_count = 0; int post_deactivate_count = 0; zend_class_entry **pce; int class_count = 0; /* Collect extensions with request startup/shutdown handlers */ for (zend_hash_internal_pointer_reset_ex(&module_registry, &pos); zend_hash_get_current_data_ex(&module_registry, (void *) &module, &pos) == SUCCESS; zend_hash_move_forward_ex(&module_registry, &pos)) { if (module->request_startup_func) { startup_count++; } if (module->request_shutdown_func) { shutdown_count++; } if (module->post_deactivate_func) { post_deactivate_count++; } } module_request_startup_handlers = (zend_module_entry**)malloc( sizeof(zend_module_entry*) * (startup_count + 1 + shutdown_count + 1 + post_deactivate_count + 1)); module_request_startup_handlers[startup_count] = NULL; module_request_shutdown_handlers = module_request_startup_handlers + startup_count + 1; module_request_shutdown_handlers[shutdown_count] = NULL; module_post_deactivate_handlers = module_request_shutdown_handlers + shutdown_count + 1; module_post_deactivate_handlers[post_deactivate_count] = NULL; startup_count = 0; for (zend_hash_internal_pointer_reset_ex(&module_registry, &pos); zend_hash_get_current_data_ex(&module_registry, (void *) &module, &pos) == SUCCESS; zend_hash_move_forward_ex(&module_registry, &pos)) { if (module->request_startup_func) { module_request_startup_handlers[startup_count++] = module; } if (module->request_shutdown_func) { module_request_shutdown_handlers[--shutdown_count] = module; } if (module->post_deactivate_func) { module_post_deactivate_handlers[--post_deactivate_count] = module; } } /* Collect internal classes with static members */ for (zend_hash_internal_pointer_reset_ex(CG(class_table), &pos); zend_hash_get_current_data_ex(CG(class_table), (void *) &pce, &pos) == SUCCESS; zend_hash_move_forward_ex(CG(class_table), &pos)) { if ((*pce)->type == ZEND_INTERNAL_CLASS && (*pce)->default_static_members_count > 0) { class_count++; } } class_cleanup_handlers = (zend_class_entry**)malloc( sizeof(zend_class_entry*) * (class_count + 1)); class_cleanup_handlers[class_count] = NULL; if (class_count) { for (zend_hash_internal_pointer_reset_ex(CG(class_table), &pos); zend_hash_get_current_data_ex(CG(class_table), (void *) &pce, &pos) == SUCCESS; zend_hash_move_forward_ex(CG(class_table), &pos)) { if ((*pce)->type == ZEND_INTERNAL_CLASS && (*pce)->default_static_members_count > 0) { class_cleanup_handlers[--class_count] = *pce; } } } } /* }}} */ ZEND_API int zend_startup_modules(TSRMLS_D) /* {{{ */ { zend_hash_sort(&module_registry, zend_sort_modules, NULL, 0 TSRMLS_CC); zend_hash_apply(&module_registry, (apply_func_t)zend_startup_module_ex TSRMLS_CC); return SUCCESS; } /* }}} */ ZEND_API void zend_destroy_modules(void) /* {{{ */ { free(class_cleanup_handlers); free(module_request_startup_handlers); zend_hash_graceful_reverse_destroy(&module_registry); } /* }}} */ ZEND_API zend_module_entry* zend_register_module_ex(zend_module_entry *module TSRMLS_DC) /* {{{ */ { int name_len; char *lcname; zend_module_entry *module_ptr; if (!module) { return NULL; } #if 0 zend_printf("%s: Registering module %d\n", module->name, module->module_number); #endif /* Check module dependencies */ if (module->deps) { const zend_module_dep *dep = module->deps; while (dep->name) { if (dep->type == MODULE_DEP_CONFLICTS) { name_len = strlen(dep->name); lcname = zend_str_tolower_dup(dep->name, name_len); if (zend_hash_exists(&module_registry, lcname, name_len+1)) { efree(lcname); /* TODO: Check version relationship */ zend_error(E_CORE_WARNING, "Cannot load module '%s' because conflicting module '%s' is already loaded", module->name, dep->name); return NULL; } efree(lcname); } ++dep; } } name_len = strlen(module->name); lcname = zend_str_tolower_dup(module->name, name_len); if (zend_hash_add(&module_registry, lcname, name_len+1, (void *)module, sizeof(zend_module_entry), (void**)&module_ptr)==FAILURE) { zend_error(E_CORE_WARNING, "Module '%s' already loaded", module->name); efree(lcname); return NULL; } efree(lcname); module = module_ptr; EG(current_module) = module; if (module->functions && zend_register_functions(NULL, module->functions, NULL, module->type TSRMLS_CC)==FAILURE) { EG(current_module) = NULL; zend_error(E_CORE_WARNING,"%s: Unable to register functions, unable to load", module->name); return NULL; } EG(current_module) = NULL; return module; } /* }}} */ ZEND_API zend_module_entry* zend_register_internal_module(zend_module_entry *module TSRMLS_DC) /* {{{ */ { module->module_number = zend_next_free_module(); module->type = MODULE_PERSISTENT; return zend_register_module_ex(module TSRMLS_CC); } /* }}} */ ZEND_API void zend_check_magic_method_implementation(const zend_class_entry *ce, const zend_function *fptr, int error_type TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(fptr->common.function_name); zend_str_tolower_copy(lcname, fptr->common.function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)) && fptr->common.num_args != 0) { zend_error(error_type, "Destructor %s::%s() cannot take arguments", ce->name, ZEND_DESTRUCTOR_FUNC_NAME); } else if (name_len == sizeof(ZEND_CLONE_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)) && fptr->common.num_args != 0) { zend_error(error_type, "Method %s::%s() cannot accept any arguments", ce->name, ZEND_CLONE_FUNC_NAME); } else if (name_len == sizeof(ZEND_GET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME))) { if (fptr->common.num_args != 1) { zend_error(error_type, "Method %s::%s() must take exactly 1 argument", ce->name, ZEND_GET_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_GET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_SET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME))) { if (fptr->common.num_args != 2) { zend_error(error_type, "Method %s::%s() must take exactly 2 arguments", ce->name, ZEND_SET_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1) || ARG_SHOULD_BE_SENT_BY_REF(fptr, 2)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_SET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_UNSET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME))) { if (fptr->common.num_args != 1) { zend_error(error_type, "Method %s::%s() must take exactly 1 argument", ce->name, ZEND_UNSET_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_UNSET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_ISSET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME))) { if (fptr->common.num_args != 1) { zend_error(error_type, "Method %s::%s() must take exactly 1 argument", ce->name, ZEND_ISSET_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_ISSET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_CALL_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME))) { if (fptr->common.num_args != 2) { zend_error(error_type, "Method %s::%s() must take exactly 2 arguments", ce->name, ZEND_CALL_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1) || ARG_SHOULD_BE_SENT_BY_REF(fptr, 2)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_CALL_FUNC_NAME); } } else if (name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) ) { if (fptr->common.num_args != 2) { zend_error(error_type, "Method %s::%s() must take exactly 2 arguments", ce->name, ZEND_CALLSTATIC_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1) || ARG_SHOULD_BE_SENT_BY_REF(fptr, 2)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_CALLSTATIC_FUNC_NAME); } } else if (name_len == sizeof(ZEND_TOSTRING_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && fptr->common.num_args != 0 ) { zend_error(error_type, "Method %s::%s() cannot take arguments", ce->name, ZEND_TOSTRING_FUNC_NAME); } } /* }}} */ /* registers all functions in *library_functions in the function hash */ ZEND_API int zend_register_functions(zend_class_entry *scope, const zend_function_entry *functions, HashTable *function_table, int type TSRMLS_DC) /* {{{ */ { const zend_function_entry *ptr = functions; zend_function function, *reg_function; zend_internal_function *internal_function = (zend_internal_function *)&function; int count=0, unload=0, result=0; HashTable *target_function_table = function_table; int error_type; zend_function *ctor = NULL, *dtor = NULL, *clone = NULL, *__get = NULL, *__set = NULL, *__unset = NULL, *__isset = NULL, *__call = NULL, *__callstatic = NULL, *__tostring = NULL; const char *lowercase_name; int fname_len; const char *lc_class_name = NULL; int class_name_len = 0; if (type==MODULE_PERSISTENT) { error_type = E_CORE_WARNING; } else { error_type = E_WARNING; } if (!target_function_table) { target_function_table = CG(function_table); } internal_function->type = ZEND_INTERNAL_FUNCTION; internal_function->module = EG(current_module); if (scope) { class_name_len = strlen(scope->name); if ((lc_class_name = zend_memrchr(scope->name, '\\', class_name_len))) { ++lc_class_name; class_name_len -= (lc_class_name - scope->name); lc_class_name = zend_str_tolower_dup(lc_class_name, class_name_len); } else { lc_class_name = zend_str_tolower_dup(scope->name, class_name_len); } } while (ptr->fname) { internal_function->handler = ptr->handler; internal_function->function_name = (char*)ptr->fname; internal_function->scope = scope; internal_function->prototype = NULL; if (ptr->flags) { if (!(ptr->flags & ZEND_ACC_PPP_MASK)) { if (ptr->flags != ZEND_ACC_DEPRECATED || scope) { zend_error(error_type, "Invalid access level for %s%s%s() - access must be exactly one of public, protected or private", scope ? scope->name : "", scope ? "::" : "", ptr->fname); } internal_function->fn_flags = ZEND_ACC_PUBLIC | ptr->flags; } else { internal_function->fn_flags = ptr->flags; } } else { internal_function->fn_flags = ZEND_ACC_PUBLIC; } if (ptr->arg_info) { zend_internal_function_info *info = (zend_internal_function_info*)ptr->arg_info; internal_function->arg_info = (zend_arg_info*)ptr->arg_info+1; internal_function->num_args = ptr->num_args; /* Currently you cannot denote that the function can accept less arguments than num_args */ if (info->required_num_args == -1) { internal_function->required_num_args = ptr->num_args; } else { internal_function->required_num_args = info->required_num_args; } if (info->pass_rest_by_reference) { if (info->pass_rest_by_reference == ZEND_SEND_PREFER_REF) { internal_function->fn_flags |= ZEND_ACC_PASS_REST_PREFER_REF; } else { internal_function->fn_flags |= ZEND_ACC_PASS_REST_BY_REFERENCE; } } if (info->return_reference) { internal_function->fn_flags |= ZEND_ACC_RETURN_REFERENCE; } } else { internal_function->arg_info = NULL; internal_function->num_args = 0; internal_function->required_num_args = 0; } if (ptr->flags & ZEND_ACC_ABSTRACT) { if (scope) { /* This is a class that must be abstract itself. Here we set the check info. */ scope->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; if (!(scope->ce_flags & ZEND_ACC_INTERFACE)) { /* Since the class is not an interface it needs to be declared as a abstract class. */ /* Since here we are handling internal functions only we can add the keyword flag. */ /* This time we set the flag for the keyword 'abstract'. */ scope->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } } if (ptr->flags & ZEND_ACC_STATIC && (!scope || !(scope->ce_flags & ZEND_ACC_INTERFACE))) { zend_error(error_type, "Static function %s%s%s() cannot be abstract", scope ? scope->name : "", scope ? "::" : "", ptr->fname); } } else { if (scope && (scope->ce_flags & ZEND_ACC_INTERFACE)) { efree((char*)lc_class_name); zend_error(error_type, "Interface %s cannot contain non abstract method %s()", scope->name, ptr->fname); return FAILURE; } if (!internal_function->handler) { if (scope) { efree((char*)lc_class_name); } zend_error(error_type, "Method %s%s%s() cannot be a NULL function", scope ? scope->name : "", scope ? "::" : "", ptr->fname); zend_unregister_functions(functions, count, target_function_table TSRMLS_CC); return FAILURE; } } fname_len = strlen(ptr->fname); lowercase_name = zend_new_interned_string(zend_str_tolower_dup(ptr->fname, fname_len), fname_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lowercase_name)) { result = zend_hash_quick_add(target_function_table, lowercase_name, fname_len+1, INTERNED_HASH(lowercase_name), &function, sizeof(zend_function), (void**)&reg_function); } else { result = zend_hash_add(target_function_table, lowercase_name, fname_len+1, &function, sizeof(zend_function), (void**)&reg_function); } if (result == FAILURE) { unload=1; str_efree(lowercase_name); break; } if (scope) { /* Look for ctor, dtor, clone * If it's an old-style constructor, store it only if we don't have * a constructor already. */ if ((fname_len == class_name_len) && !ctor && !memcmp(lowercase_name, lc_class_name, class_name_len+1)) { ctor = reg_function; } else if ((fname_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME))) { ctor = reg_function; } else if ((fname_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME))) { dtor = reg_function; if (internal_function->num_args) { zend_error(error_type, "Destructor %s::%s() cannot take arguments", scope->name, ptr->fname); } } else if ((fname_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME))) { clone = reg_function; } else if ((fname_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME))) { __call = reg_function; } else if ((fname_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME))) { __callstatic = reg_function; } else if ((fname_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME))) { __tostring = reg_function; } else if ((fname_len == sizeof(ZEND_GET_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME))) { __get = reg_function; } else if ((fname_len == sizeof(ZEND_SET_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME))) { __set = reg_function; } else if ((fname_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME))) { __unset = reg_function; } else if ((fname_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME))) { __isset = reg_function; } else { reg_function = NULL; } if (reg_function) { zend_check_magic_method_implementation(scope, reg_function, error_type TSRMLS_CC); } } ptr++; count++; str_efree(lowercase_name); } if (unload) { /* before unloading, display all remaining bad function in the module */ if (scope) { efree((char*)lc_class_name); } while (ptr->fname) { fname_len = strlen(ptr->fname); lowercase_name = zend_str_tolower_dup(ptr->fname, fname_len); if (zend_hash_exists(target_function_table, lowercase_name, fname_len+1)) { zend_error(error_type, "Function registration failed - duplicate name - %s%s%s", scope ? scope->name : "", scope ? "::" : "", ptr->fname); } efree((char*)lowercase_name); ptr++; } zend_unregister_functions(functions, count, target_function_table TSRMLS_CC); return FAILURE; } if (scope) { scope->constructor = ctor; scope->destructor = dtor; scope->clone = clone; scope->__call = __call; scope->__callstatic = __callstatic; scope->__tostring = __tostring; scope->__get = __get; scope->__set = __set; scope->__unset = __unset; scope->__isset = __isset; if (ctor) { ctor->common.fn_flags |= ZEND_ACC_CTOR; if (ctor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Constructor %s::%s() cannot be static", scope->name, ctor->common.function_name); } ctor->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (dtor) { dtor->common.fn_flags |= ZEND_ACC_DTOR; if (dtor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Destructor %s::%s() cannot be static", scope->name, dtor->common.function_name); } dtor->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (clone) { clone->common.fn_flags |= ZEND_ACC_CLONE; if (clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Constructor %s::%s() cannot be static", scope->name, clone->common.function_name); } clone->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__call) { if (__call->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __call->common.function_name); } __call->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__callstatic) { if (!(__callstatic->common.fn_flags & ZEND_ACC_STATIC)) { zend_error(error_type, "Method %s::%s() must be static", scope->name, __callstatic->common.function_name); } __callstatic->common.fn_flags |= ZEND_ACC_STATIC; } if (__tostring) { if (__tostring->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __tostring->common.function_name); } __tostring->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__get) { if (__get->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __get->common.function_name); } __get->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__set) { if (__set->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __set->common.function_name); } __set->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__unset) { if (__unset->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __unset->common.function_name); } __unset->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__isset) { if (__isset->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __isset->common.function_name); } __isset->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } efree((char*)lc_class_name); } return SUCCESS; } /* }}} */ /* count=-1 means erase all functions, otherwise, * erase the first count functions */ ZEND_API void zend_unregister_functions(const zend_function_entry *functions, int count, HashTable *function_table TSRMLS_DC) /* {{{ */ { const zend_function_entry *ptr = functions; int i=0; HashTable *target_function_table = function_table; if (!target_function_table) { target_function_table = CG(function_table); } while (ptr->fname) { if (count!=-1 && i>=count) { break; } #if 0 zend_printf("Unregistering %s()\n", ptr->fname); #endif zend_hash_del(target_function_table, ptr->fname, strlen(ptr->fname)+1); ptr++; i++; } } /* }}} */ ZEND_API int zend_startup_module(zend_module_entry *module) /* {{{ */ { TSRMLS_FETCH(); if ((module = zend_register_internal_module(module TSRMLS_CC)) != NULL && zend_startup_module_ex(module TSRMLS_CC) == SUCCESS) { return SUCCESS; } return FAILURE; } /* }}} */ ZEND_API int zend_get_module_started(const char *module_name) /* {{{ */ { zend_module_entry *module; return (zend_hash_find(&module_registry, module_name, strlen(module_name)+1, (void**)&module) == SUCCESS && module->module_started) ? SUCCESS : FAILURE; } /* }}} */ static int clean_module_class(const zend_class_entry **ce, int *module_number TSRMLS_DC) /* {{{ */ { if ((*ce)->type == ZEND_INTERNAL_CLASS && (*ce)->info.internal.module->module_number == *module_number) { return ZEND_HASH_APPLY_REMOVE; } else { return ZEND_HASH_APPLY_KEEP; } } /* }}} */ static void clean_module_classes(int module_number TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_argument(EG(class_table), (apply_func_arg_t) clean_module_class, (void *) &module_number TSRMLS_CC); } /* }}} */ void module_destructor(zend_module_entry *module) /* {{{ */ { TSRMLS_FETCH(); if (module->type == MODULE_TEMPORARY) { zend_clean_module_rsrc_dtors(module->module_number TSRMLS_CC); clean_module_constants(module->module_number TSRMLS_CC); clean_module_classes(module->module_number TSRMLS_CC); } if (module->module_started && module->module_shutdown_func) { #if 0 zend_printf("%s: Module shutdown\n", module->name); #endif module->module_shutdown_func(module->type, module->module_number TSRMLS_CC); } /* Deinitilaise module globals */ if (module->globals_size) { #ifdef ZTS ts_free_id(*module->globals_id_ptr); #else if (module->globals_dtor) { module->globals_dtor(module->globals_ptr TSRMLS_CC); } #endif } module->module_started=0; if (module->functions) { zend_unregister_functions(module->functions, -1, NULL TSRMLS_CC); } #if HAVE_LIBDL #if !(defined(NETWARE) && defined(APACHE_1_BUILD)) if (module->handle && !getenv("ZEND_DONT_UNLOAD_MODULES")) { DL_UNLOAD(module->handle); } #endif #endif } /* }}} */ void zend_activate_modules(TSRMLS_D) /* {{{ */ { zend_module_entry **p = module_request_startup_handlers; while (*p) { zend_module_entry *module = *p; if (module->request_startup_func(module->type, module->module_number TSRMLS_CC)==FAILURE) { zend_error(E_WARNING, "request_startup() for %s module failed", module->name); exit(1); } p++; } } /* }}} */ /* call request shutdown for all modules */ int module_registry_cleanup(zend_module_entry *module TSRMLS_DC) /* {{{ */ { if (module->request_shutdown_func) { #if 0 zend_printf("%s: Request shutdown\n", module->name); #endif module->request_shutdown_func(module->type, module->module_number TSRMLS_CC); } return 0; } /* }}} */ void zend_deactivate_modules(TSRMLS_D) /* {{{ */ { EG(opline_ptr) = NULL; /* we're no longer executing anything */ zend_try { if (EG(full_tables_cleanup)) { zend_hash_reverse_apply(&module_registry, (apply_func_t) module_registry_cleanup TSRMLS_CC); } else { zend_module_entry **p = module_request_shutdown_handlers; while (*p) { zend_module_entry *module = *p; module->request_shutdown_func(module->type, module->module_number TSRMLS_CC); p++; } } } zend_end_try(); } /* }}} */ ZEND_API void zend_cleanup_internal_classes(TSRMLS_D) /* {{{ */ { zend_class_entry **p = class_cleanup_handlers; while (*p) { zend_cleanup_internal_class_data(*p TSRMLS_CC); p++; } } /* }}} */ int module_registry_unload_temp(const zend_module_entry *module TSRMLS_DC) /* {{{ */ { return (module->type == MODULE_TEMPORARY) ? ZEND_HASH_APPLY_REMOVE : ZEND_HASH_APPLY_STOP; } /* }}} */ static int exec_done_cb(zend_module_entry *module TSRMLS_DC) /* {{{ */ { if (module->post_deactivate_func) { module->post_deactivate_func(); } return 0; } /* }}} */ void zend_post_deactivate_modules(TSRMLS_D) /* {{{ */ { if (EG(full_tables_cleanup)) { zend_hash_apply(&module_registry, (apply_func_t) exec_done_cb TSRMLS_CC); zend_hash_reverse_apply(&module_registry, (apply_func_t) module_registry_unload_temp TSRMLS_CC); } else { zend_module_entry **p = module_post_deactivate_handlers; while (*p) { zend_module_entry *module = *p; module->post_deactivate_func(); p++; } } } /* }}} */ /* return the next free module number */ int zend_next_free_module(void) /* {{{ */ { return ++module_count; } /* }}} */ static zend_class_entry *do_register_internal_class(zend_class_entry *orig_class_entry, zend_uint ce_flags TSRMLS_DC) /* {{{ */ { zend_class_entry *class_entry = malloc(sizeof(zend_class_entry)); char *lowercase_name = emalloc(orig_class_entry->name_length + 1); *class_entry = *orig_class_entry; class_entry->type = ZEND_INTERNAL_CLASS; zend_initialize_class_data(class_entry, 0 TSRMLS_CC); class_entry->ce_flags = ce_flags; class_entry->info.internal.module = EG(current_module); if (class_entry->info.internal.builtin_functions) { zend_register_functions(class_entry, class_entry->info.internal.builtin_functions, &class_entry->function_table, MODULE_PERSISTENT TSRMLS_CC); } zend_str_tolower_copy(lowercase_name, orig_class_entry->name, class_entry->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, class_entry->name_length + 1, 1 TSRMLS_CC); if (IS_INTERNED(lowercase_name)) { zend_hash_quick_update(CG(class_table), lowercase_name, class_entry->name_length+1, INTERNED_HASH(lowercase_name), &class_entry, sizeof(zend_class_entry *), NULL); } else { zend_hash_update(CG(class_table), lowercase_name, class_entry->name_length+1, &class_entry, sizeof(zend_class_entry *), NULL); } str_efree(lowercase_name); return class_entry; } /* }}} */ /* If parent_ce is not NULL then it inherits from parent_ce * If parent_ce is NULL and parent_name isn't then it looks for the parent and inherits from it * If both parent_ce and parent_name are NULL it does a regular class registration * If parent_name is specified but not found NULL is returned */ ZEND_API zend_class_entry *zend_register_internal_class_ex(zend_class_entry *class_entry, zend_class_entry *parent_ce, char *parent_name TSRMLS_DC) /* {{{ */ { zend_class_entry *register_class; if (!parent_ce && parent_name) { zend_class_entry **pce; if (zend_hash_find(CG(class_table), parent_name, strlen(parent_name)+1, (void **) &pce)==FAILURE) { return NULL; } else { parent_ce = *pce; } } register_class = zend_register_internal_class(class_entry TSRMLS_CC); if (parent_ce) { zend_do_inheritance(register_class, parent_ce TSRMLS_CC); } return register_class; } /* }}} */ ZEND_API void zend_class_implements(zend_class_entry *class_entry TSRMLS_DC, int num_interfaces, ...) /* {{{ */ { zend_class_entry *interface_entry; va_list interface_list; va_start(interface_list, num_interfaces); while (num_interfaces--) { interface_entry = va_arg(interface_list, zend_class_entry *); zend_do_implement_interface(class_entry, interface_entry TSRMLS_CC); } va_end(interface_list); } /* }}} */ /* A class that contains at least one abstract method automatically becomes an abstract class. */ ZEND_API zend_class_entry *zend_register_internal_class(zend_class_entry *orig_class_entry TSRMLS_DC) /* {{{ */ { return do_register_internal_class(orig_class_entry, 0 TSRMLS_CC); } /* }}} */ ZEND_API zend_class_entry *zend_register_internal_interface(zend_class_entry *orig_class_entry TSRMLS_DC) /* {{{ */ { return do_register_internal_class(orig_class_entry, ZEND_ACC_INTERFACE TSRMLS_CC); } /* }}} */ ZEND_API int zend_register_class_alias_ex(const char *name, int name_len, zend_class_entry *ce TSRMLS_DC) /* {{{ */ { char *lcname = zend_str_tolower_dup(name, name_len); int ret; ret = zend_hash_add(CG(class_table), lcname, name_len+1, &ce, sizeof(zend_class_entry *), NULL); efree(lcname); if (ret == SUCCESS) { ce->refcount++; } return ret; } /* }}} */ ZEND_API int zend_set_hash_symbol(zval *symbol, const char *name, int name_length, zend_bool is_ref, int num_symbol_tables, ...) /* {{{ */ { HashTable *symbol_table; va_list symbol_table_list; if (num_symbol_tables <= 0) return FAILURE; Z_SET_ISREF_TO_P(symbol, is_ref); va_start(symbol_table_list, num_symbol_tables); while (num_symbol_tables-- > 0) { symbol_table = va_arg(symbol_table_list, HashTable *); zend_hash_update(symbol_table, name, name_length + 1, &symbol, sizeof(zval *), NULL); zval_add_ref(&symbol); } va_end(symbol_table_list); return SUCCESS; } /* }}} */ /* Disabled functions support */ /* {{{ proto void display_disabled_function(void) Dummy function which displays an error when a disabled function is called. */ ZEND_API ZEND_FUNCTION(display_disabled_function) { zend_error(E_WARNING, "%s() has been disabled for security reasons", get_active_function_name(TSRMLS_C)); } /* }}} */ static zend_function_entry disabled_function[] = { ZEND_FE(display_disabled_function, NULL) ZEND_FE_END }; ZEND_API int zend_disable_function(char *function_name, uint function_name_length TSRMLS_DC) /* {{{ */ { if (zend_hash_del(CG(function_table), function_name, function_name_length+1)==FAILURE) { return FAILURE; } disabled_function[0].fname = function_name; return zend_register_functions(NULL, disabled_function, CG(function_table), MODULE_PERSISTENT TSRMLS_CC); } /* }}} */ static zend_object_value display_disabled_class(zend_class_entry *class_type TSRMLS_DC) /* {{{ */ { zend_object_value retval; zend_object *intern; retval = zend_objects_new(&intern, class_type TSRMLS_CC); zend_error(E_WARNING, "%s() has been disabled for security reasons", class_type->name); return retval; } /* }}} */ static const zend_function_entry disabled_class_new[] = { ZEND_FE_END }; ZEND_API int zend_disable_class(char *class_name, uint class_name_length TSRMLS_DC) /* {{{ */ { zend_class_entry disabled_class; zend_str_tolower(class_name, class_name_length); if (zend_hash_del(CG(class_table), class_name, class_name_length+1)==FAILURE) { return FAILURE; } INIT_OVERLOADED_CLASS_ENTRY_EX(disabled_class, class_name, class_name_length, disabled_class_new, NULL, NULL, NULL, NULL, NULL); disabled_class.create_object = display_disabled_class; disabled_class.name_length = class_name_length; zend_register_internal_class(&disabled_class TSRMLS_CC); return SUCCESS; } /* }}} */ static int zend_is_callable_check_class(const char *name, int name_len, zend_fcall_info_cache *fcc, int *strict_class, char **error TSRMLS_DC) /* {{{ */ { int ret = 0; zend_class_entry **pce; char *lcname = zend_str_tolower_dup(name, name_len); *strict_class = 0; if (name_len == sizeof("self") - 1 && !memcmp(lcname, "self", sizeof("self") - 1)) { if (!EG(scope)) { if (error) *error = estrdup("cannot access self:: when no class scope is active"); } else { fcc->called_scope = EG(called_scope); fcc->calling_scope = EG(scope); if (!fcc->object_ptr) { fcc->object_ptr = EG(This); } ret = 1; } } else if (name_len == sizeof("parent") - 1 && !memcmp(lcname, "parent", sizeof("parent") - 1)) { if (!EG(scope)) { if (error) *error = estrdup("cannot access parent:: when no class scope is active"); } else if (!EG(scope)->parent) { if (error) *error = estrdup("cannot access parent:: when current class scope has no parent"); } else { fcc->called_scope = EG(called_scope); fcc->calling_scope = EG(scope)->parent; if (!fcc->object_ptr) { fcc->object_ptr = EG(This); } *strict_class = 1; ret = 1; } } else if (name_len == sizeof("static") - 1 && !memcmp(lcname, "static", sizeof("static") - 1)) { if (!EG(called_scope)) { if (error) *error = estrdup("cannot access static:: when no class scope is active"); } else { fcc->called_scope = EG(called_scope); fcc->calling_scope = EG(called_scope); if (!fcc->object_ptr) { fcc->object_ptr = EG(This); } *strict_class = 1; ret = 1; } } else if (zend_lookup_class_ex(name, name_len, NULL, 1, &pce TSRMLS_CC) == SUCCESS) { zend_class_entry *scope = EG(active_op_array) ? EG(active_op_array)->scope : NULL; fcc->calling_scope = *pce; if (scope && !fcc->object_ptr && EG(This) && instanceof_function(Z_OBJCE_P(EG(This)), scope TSRMLS_CC) && instanceof_function(scope, fcc->calling_scope TSRMLS_CC)) { fcc->object_ptr = EG(This); fcc->called_scope = Z_OBJCE_P(fcc->object_ptr); } else { fcc->called_scope = fcc->object_ptr ? Z_OBJCE_P(fcc->object_ptr) : fcc->calling_scope; } *strict_class = 1; ret = 1; } else { if (error) zend_spprintf(error, 0, "class '%.*s' not found", name_len, name); } efree(lcname); return ret; } /* }}} */ static int zend_is_callable_check_func(int check_flags, zval *callable, zend_fcall_info_cache *fcc, int strict_class, char **error TSRMLS_DC) /* {{{ */ { zend_class_entry *ce_org = fcc->calling_scope; int retval = 0; char *mname, *lmname; const char *colon; int clen, mlen; zend_class_entry *last_scope; HashTable *ftable; int call_via_handler = 0; if (error) { *error = NULL; } fcc->calling_scope = NULL; fcc->function_handler = NULL; if (!ce_org) { /* Skip leading \ */ if (Z_STRVAL_P(callable)[0] == '\\') { mlen = Z_STRLEN_P(callable) - 1; mname = Z_STRVAL_P(callable) + 1; lmname = zend_str_tolower_dup(Z_STRVAL_P(callable) + 1, mlen); } else { mlen = Z_STRLEN_P(callable); mname = Z_STRVAL_P(callable); lmname = zend_str_tolower_dup(Z_STRVAL_P(callable), mlen); } /* Check if function with given name exists. * This may be a compound name that includes namespace name */ if (zend_hash_find(EG(function_table), lmname, mlen+1, (void**)&fcc->function_handler) == SUCCESS) { efree(lmname); return 1; } efree(lmname); } /* Split name into class/namespace and method/function names */ if ((colon = zend_memrchr(Z_STRVAL_P(callable), ':', Z_STRLEN_P(callable))) != NULL && colon > Z_STRVAL_P(callable) && *(colon-1) == ':' ) { colon--; clen = colon - Z_STRVAL_P(callable); mlen = Z_STRLEN_P(callable) - clen - 2; if (colon == Z_STRVAL_P(callable)) { if (error) zend_spprintf(error, 0, "invalid function name"); return 0; } /* This is a compound name. * Try to fetch class and then find static method. */ last_scope = EG(scope); if (ce_org) { EG(scope) = ce_org; } if (!zend_is_callable_check_class(Z_STRVAL_P(callable), clen, fcc, &strict_class, error TSRMLS_CC)) { EG(scope) = last_scope; return 0; } EG(scope) = last_scope; ftable = &fcc->calling_scope->function_table; if (ce_org && !instanceof_function(ce_org, fcc->calling_scope TSRMLS_CC)) { if (error) zend_spprintf(error, 0, "class '%s' is not a subclass of '%s'", ce_org->name, fcc->calling_scope->name); return 0; } mname = Z_STRVAL_P(callable) + clen + 2; } else if (ce_org) { /* Try to fetch find static method of given class. */ mlen = Z_STRLEN_P(callable); mname = Z_STRVAL_P(callable); ftable = &ce_org->function_table; fcc->calling_scope = ce_org; } else { /* We already checked for plain function before. */ if (error && !(check_flags & IS_CALLABLE_CHECK_SILENT)) { zend_spprintf(error, 0, "function '%s' not found or invalid function name", Z_STRVAL_P(callable)); } return 0; } lmname = zend_str_tolower_dup(mname, mlen); if (strict_class && fcc->calling_scope && mlen == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1 && !memcmp(lmname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME))) { fcc->function_handler = fcc->calling_scope->constructor; if (fcc->function_handler) { retval = 1; } } else if (zend_hash_find(ftable, lmname, mlen+1, (void**)&fcc->function_handler) == SUCCESS) { retval = 1; if ((fcc->function_handler->op_array.fn_flags & ZEND_ACC_CHANGED) && EG(scope) && instanceof_function(fcc->function_handler->common.scope, EG(scope) TSRMLS_CC)) { zend_function *priv_fbc; if (zend_hash_find(&EG(scope)->function_table, lmname, mlen+1, (void **) &priv_fbc)==SUCCESS && priv_fbc->common.fn_flags & ZEND_ACC_PRIVATE && priv_fbc->common.scope == EG(scope)) { fcc->function_handler = priv_fbc; } } if ((check_flags & IS_CALLABLE_CHECK_NO_ACCESS) == 0 && (fcc->calling_scope && (fcc->calling_scope->__call || fcc->calling_scope->__callstatic))) { if (fcc->function_handler->op_array.fn_flags & ZEND_ACC_PRIVATE) { if (!zend_check_private(fcc->function_handler, fcc->object_ptr ? Z_OBJCE_P(fcc->object_ptr) : EG(scope), lmname, mlen TSRMLS_CC)) { retval = 0; fcc->function_handler = NULL; goto get_function_via_handler; } } else if (fcc->function_handler->common.fn_flags & ZEND_ACC_PROTECTED) { if (!zend_check_protected(fcc->function_handler->common.scope, EG(scope))) { retval = 0; fcc->function_handler = NULL; goto get_function_via_handler; } } } } else { get_function_via_handler: if (fcc->object_ptr && fcc->calling_scope == ce_org) { if (strict_class && ce_org->__call) { fcc->function_handler = emalloc(sizeof(zend_internal_function)); fcc->function_handler->internal_function.type = ZEND_INTERNAL_FUNCTION; fcc->function_handler->internal_function.module = (ce_org->type == ZEND_INTERNAL_CLASS) ? ce_org->info.internal.module : NULL; fcc->function_handler->internal_function.handler = zend_std_call_user_call; fcc->function_handler->internal_function.arg_info = NULL; fcc->function_handler->internal_function.num_args = 0; fcc->function_handler->internal_function.scope = ce_org; fcc->function_handler->internal_function.fn_flags = ZEND_ACC_CALL_VIA_HANDLER; fcc->function_handler->internal_function.function_name = estrndup(mname, mlen); call_via_handler = 1; retval = 1; } else if (Z_OBJ_HT_P(fcc->object_ptr)->get_method) { fcc->function_handler = Z_OBJ_HT_P(fcc->object_ptr)->get_method(&fcc->object_ptr, mname, mlen, NULL TSRMLS_CC); if (fcc->function_handler) { if (strict_class && (!fcc->function_handler->common.scope || !instanceof_function(ce_org, fcc->function_handler->common.scope TSRMLS_CC))) { if ((fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) != 0) { if (fcc->function_handler->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fcc->function_handler->common.function_name); } efree(fcc->function_handler); } } else { retval = 1; call_via_handler = (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) != 0; } } } } else if (fcc->calling_scope) { if (fcc->calling_scope->get_static_method) { fcc->function_handler = fcc->calling_scope->get_static_method(fcc->calling_scope, mname, mlen TSRMLS_CC); } else { fcc->function_handler = zend_std_get_static_method(fcc->calling_scope, mname, mlen, NULL TSRMLS_CC); } if (fcc->function_handler) { retval = 1; call_via_handler = (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) != 0; if (call_via_handler && !fcc->object_ptr && EG(This) && Z_OBJ_HT_P(EG(This))->get_class_entry && instanceof_function(Z_OBJCE_P(EG(This)), fcc->calling_scope TSRMLS_CC)) { fcc->object_ptr = EG(This); } } } } if (retval) { if (fcc->calling_scope && !call_via_handler) { if (!fcc->object_ptr && !(fcc->function_handler->common.fn_flags & ZEND_ACC_STATIC)) { int severity; char *verb; if (fcc->function_handler->common.fn_flags & ZEND_ACC_ALLOW_STATIC) { severity = E_STRICT; verb = "should not"; } else { /* An internal function assumes $this is present and won't check that. So PHP would crash by allowing the call. */ severity = E_ERROR; verb = "cannot"; } if ((check_flags & IS_CALLABLE_CHECK_IS_STATIC) != 0) { retval = 0; } if (EG(This) && instanceof_function(Z_OBJCE_P(EG(This)), fcc->calling_scope TSRMLS_CC)) { fcc->object_ptr = EG(This); if (error) { zend_spprintf(error, 0, "non-static method %s::%s() %s be called statically, assuming $this from compatible context %s", fcc->calling_scope->name, fcc->function_handler->common.function_name, verb, Z_OBJCE_P(EG(This))->name); if (severity == E_ERROR) { retval = 0; } } else if (retval) { zend_error(severity, "Non-static method %s::%s() %s be called statically, assuming $this from compatible context %s", fcc->calling_scope->name, fcc->function_handler->common.function_name, verb, Z_OBJCE_P(EG(This))->name); } } else { if (error) { zend_spprintf(error, 0, "non-static method %s::%s() %s be called statically", fcc->calling_scope->name, fcc->function_handler->common.function_name, verb); if (severity == E_ERROR) { retval = 0; } } else if (retval) { zend_error(severity, "Non-static method %s::%s() %s be called statically", fcc->calling_scope->name, fcc->function_handler->common.function_name, verb); } } } if (retval && (check_flags & IS_CALLABLE_CHECK_NO_ACCESS) == 0) { if (fcc->function_handler->op_array.fn_flags & ZEND_ACC_PRIVATE) { if (!zend_check_private(fcc->function_handler, fcc->object_ptr ? Z_OBJCE_P(fcc->object_ptr) : EG(scope), lmname, mlen TSRMLS_CC)) { if (error) { if (*error) { efree(*error); } zend_spprintf(error, 0, "cannot access private method %s::%s()", fcc->calling_scope->name, fcc->function_handler->common.function_name); } retval = 0; } } else if ((fcc->function_handler->common.fn_flags & ZEND_ACC_PROTECTED)) { if (!zend_check_protected(fcc->function_handler->common.scope, EG(scope))) { if (error) { if (*error) { efree(*error); } zend_spprintf(error, 0, "cannot access protected method %s::%s()", fcc->calling_scope->name, fcc->function_handler->common.function_name); } retval = 0; } } } } } else if (error && !(check_flags & IS_CALLABLE_CHECK_SILENT)) { if (fcc->calling_scope) { if (error) zend_spprintf(error, 0, "class '%s' does not have a method '%s'", fcc->calling_scope->name, mname); } else { if (error) zend_spprintf(error, 0, "function '%s' does not exist", mname); } } efree(lmname); if (fcc->object_ptr) { fcc->called_scope = Z_OBJCE_P(fcc->object_ptr); } if (retval) { fcc->initialized = 1; } return retval; } /* }}} */ ZEND_API zend_bool zend_is_callable_ex(zval *callable, zval *object_ptr, uint check_flags, char **callable_name, int *callable_name_len, zend_fcall_info_cache *fcc, char **error TSRMLS_DC) /* {{{ */ { zend_bool ret; int callable_name_len_local; zend_fcall_info_cache fcc_local; if (callable_name) { *callable_name = NULL; } if (callable_name_len == NULL) { callable_name_len = &callable_name_len_local; } if (fcc == NULL) { fcc = &fcc_local; } if (error) { *error = NULL; } fcc->initialized = 0; fcc->calling_scope = NULL; fcc->called_scope = NULL; fcc->function_handler = NULL; fcc->calling_scope = NULL; fcc->object_ptr = NULL; if (object_ptr && Z_TYPE_P(object_ptr) != IS_OBJECT) { object_ptr = NULL; } if (object_ptr && (!EG(objects_store).object_buckets || !EG(objects_store).object_buckets[Z_OBJ_HANDLE_P(object_ptr)].valid)) { return 0; } switch (Z_TYPE_P(callable)) { case IS_STRING: if (object_ptr) { fcc->object_ptr = object_ptr; fcc->calling_scope = Z_OBJCE_P(object_ptr); if (callable_name) { char *ptr; *callable_name_len = fcc->calling_scope->name_length + Z_STRLEN_P(callable) + sizeof("::") - 1; ptr = *callable_name = emalloc(*callable_name_len + 1); memcpy(ptr, fcc->calling_scope->name, fcc->calling_scope->name_length); ptr += fcc->calling_scope->name_length; memcpy(ptr, "::", sizeof("::") - 1); ptr += sizeof("::") - 1; memcpy(ptr, Z_STRVAL_P(callable), Z_STRLEN_P(callable) + 1); } } else if (callable_name) { *callable_name = estrndup(Z_STRVAL_P(callable), Z_STRLEN_P(callable)); *callable_name_len = Z_STRLEN_P(callable); } if (check_flags & IS_CALLABLE_CHECK_SYNTAX_ONLY) { fcc->called_scope = fcc->calling_scope; return 1; } ret = zend_is_callable_check_func(check_flags, callable, fcc, 0, error TSRMLS_CC); if (fcc == &fcc_local && fcc->function_handler && ((fcc->function_handler->type == ZEND_INTERNAL_FUNCTION && (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER)) || fcc->function_handler->type == ZEND_OVERLOADED_FUNCTION_TEMPORARY || fcc->function_handler->type == ZEND_OVERLOADED_FUNCTION)) { if (fcc->function_handler->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fcc->function_handler->common.function_name); } efree(fcc->function_handler); } return ret; case IS_ARRAY: { zval **method = NULL; zval **obj = NULL; int strict_class = 0; if (zend_hash_num_elements(Z_ARRVAL_P(callable)) == 2) { zend_hash_index_find(Z_ARRVAL_P(callable), 0, (void **) &obj); zend_hash_index_find(Z_ARRVAL_P(callable), 1, (void **) &method); } if (obj && method && (Z_TYPE_PP(obj) == IS_OBJECT || Z_TYPE_PP(obj) == IS_STRING) && Z_TYPE_PP(method) == IS_STRING) { if (Z_TYPE_PP(obj) == IS_STRING) { if (callable_name) { char *ptr; *callable_name_len = Z_STRLEN_PP(obj) + Z_STRLEN_PP(method) + sizeof("::") - 1; ptr = *callable_name = emalloc(*callable_name_len + 1); memcpy(ptr, Z_STRVAL_PP(obj), Z_STRLEN_PP(obj)); ptr += Z_STRLEN_PP(obj); memcpy(ptr, "::", sizeof("::") - 1); ptr += sizeof("::") - 1; memcpy(ptr, Z_STRVAL_PP(method), Z_STRLEN_PP(method) + 1); } if (check_flags & IS_CALLABLE_CHECK_SYNTAX_ONLY) { return 1; } if (!zend_is_callable_check_class(Z_STRVAL_PP(obj), Z_STRLEN_PP(obj), fcc, &strict_class, error TSRMLS_CC)) { return 0; } } else { if (!EG(objects_store).object_buckets || !EG(objects_store).object_buckets[Z_OBJ_HANDLE_PP(obj)].valid) { return 0; } fcc->calling_scope = Z_OBJCE_PP(obj); /* TBFixed: what if it's overloaded? */ fcc->object_ptr = *obj; if (callable_name) { char *ptr; *callable_name_len = fcc->calling_scope->name_length + Z_STRLEN_PP(method) + sizeof("::") - 1; ptr = *callable_name = emalloc(*callable_name_len + 1); memcpy(ptr, fcc->calling_scope->name, fcc->calling_scope->name_length); ptr += fcc->calling_scope->name_length; memcpy(ptr, "::", sizeof("::") - 1); ptr += sizeof("::") - 1; memcpy(ptr, Z_STRVAL_PP(method), Z_STRLEN_PP(method) + 1); } if (check_flags & IS_CALLABLE_CHECK_SYNTAX_ONLY) { fcc->called_scope = fcc->calling_scope; return 1; } } ret = zend_is_callable_check_func(check_flags, *method, fcc, strict_class, error TSRMLS_CC); if (fcc == &fcc_local && fcc->function_handler && ((fcc->function_handler->type == ZEND_INTERNAL_FUNCTION && (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER)) || fcc->function_handler->type == ZEND_OVERLOADED_FUNCTION_TEMPORARY || fcc->function_handler->type == ZEND_OVERLOADED_FUNCTION)) { if (fcc->function_handler->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fcc->function_handler->common.function_name); } efree(fcc->function_handler); } return ret; } else { if (zend_hash_num_elements(Z_ARRVAL_P(callable)) == 2) { if (!obj || (Z_TYPE_PP(obj) != IS_STRING && Z_TYPE_PP(obj) != IS_OBJECT)) { if (error) zend_spprintf(error, 0, "first array member is not a valid class name or object"); } else { if (error) zend_spprintf(error, 0, "second array member is not a valid method"); } } else { if (error) zend_spprintf(error, 0, "array must have exactly two members"); } if (callable_name) { *callable_name = estrndup("Array", sizeof("Array")-1); *callable_name_len = sizeof("Array") - 1; } } } return 0; case IS_OBJECT: if (Z_OBJ_HANDLER_P(callable, get_closure) && Z_OBJ_HANDLER_P(callable, get_closure)(callable, &fcc->calling_scope, &fcc->function_handler, &fcc->object_ptr TSRMLS_CC) == SUCCESS) { fcc->called_scope = fcc->calling_scope; if (callable_name) { zend_class_entry *ce = Z_OBJCE_P(callable); /* TBFixed: what if it's overloaded? */ *callable_name_len = ce->name_length + sizeof("::__invoke") - 1; *callable_name = emalloc(*callable_name_len + 1); memcpy(*callable_name, ce->name, ce->name_length); memcpy((*callable_name) + ce->name_length, "::__invoke", sizeof("::__invoke")); } return 1; } /* break missing intentionally */ default: if (callable_name) { zval expr_copy; int use_copy; zend_make_printable_zval(callable, &expr_copy, &use_copy); *callable_name = estrndup(Z_STRVAL(expr_copy), Z_STRLEN(expr_copy)); *callable_name_len = Z_STRLEN(expr_copy); zval_dtor(&expr_copy); } if (error) zend_spprintf(error, 0, "no array or string given"); return 0; } } /* }}} */ ZEND_API zend_bool zend_is_callable(zval *callable, uint check_flags, char **callable_name TSRMLS_DC) /* {{{ */ { return zend_is_callable_ex(callable, NULL, check_flags, callable_name, NULL, NULL, NULL TSRMLS_CC); } /* }}} */ ZEND_API zend_bool zend_make_callable(zval *callable, char **callable_name TSRMLS_DC) /* {{{ */ { zend_fcall_info_cache fcc; if (zend_is_callable_ex(callable, NULL, IS_CALLABLE_STRICT, callable_name, NULL, &fcc, NULL TSRMLS_CC)) { if (Z_TYPE_P(callable) == IS_STRING && fcc.calling_scope) { zval_dtor(callable); array_init(callable); add_next_index_string(callable, fcc.calling_scope->name, 1); add_next_index_string(callable, fcc.function_handler->common.function_name, 1); } if (fcc.function_handler && ((fcc.function_handler->type == ZEND_INTERNAL_FUNCTION && (fcc.function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER)) || fcc.function_handler->type == ZEND_OVERLOADED_FUNCTION_TEMPORARY || fcc.function_handler->type == ZEND_OVERLOADED_FUNCTION)) { if (fcc.function_handler->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fcc.function_handler->common.function_name); } efree(fcc.function_handler); } return 1; } return 0; } /* }}} */ ZEND_API int zend_fcall_info_init(zval *callable, uint check_flags, zend_fcall_info *fci, zend_fcall_info_cache *fcc, char **callable_name, char **error TSRMLS_DC) /* {{{ */ { if (!zend_is_callable_ex(callable, NULL, check_flags, callable_name, NULL, fcc, error TSRMLS_CC)) { return FAILURE; } fci->size = sizeof(*fci); fci->function_table = fcc->calling_scope ? &fcc->calling_scope->function_table : EG(function_table); fci->object_ptr = fcc->object_ptr; fci->function_name = callable; fci->retval_ptr_ptr = NULL; fci->param_count = 0; fci->params = NULL; fci->no_separation = 1; fci->symbol_table = NULL; return SUCCESS; } /* }}} */ ZEND_API void zend_fcall_info_args_clear(zend_fcall_info *fci, int free_mem) /* {{{ */ { if (fci->params) { if (free_mem) { efree(fci->params); fci->params = NULL; } } fci->param_count = 0; } /* }}} */ ZEND_API void zend_fcall_info_args_save(zend_fcall_info *fci, int *param_count, zval ****params) /* {{{ */ { *param_count = fci->param_count; *params = fci->params; fci->param_count = 0; fci->params = NULL; } /* }}} */ ZEND_API void zend_fcall_info_args_restore(zend_fcall_info *fci, int param_count, zval ***params) /* {{{ */ { zend_fcall_info_args_clear(fci, 1); fci->param_count = param_count; fci->params = params; } /* }}} */ ZEND_API int zend_fcall_info_args(zend_fcall_info *fci, zval *args TSRMLS_DC) /* {{{ */ { HashPosition pos; zval **arg, ***params; zend_fcall_info_args_clear(fci, !args); if (!args) { return SUCCESS; } if (Z_TYPE_P(args) != IS_ARRAY) { return FAILURE; } fci->param_count = zend_hash_num_elements(Z_ARRVAL_P(args)); fci->params = params = (zval ***) erealloc(fci->params, fci->param_count * sizeof(zval **)); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(args), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(args), (void *) &arg, &pos) == SUCCESS) { *params++ = arg; zend_hash_move_forward_ex(Z_ARRVAL_P(args), &pos); } return SUCCESS; } /* }}} */ ZEND_API int zend_fcall_info_argp(zend_fcall_info *fci TSRMLS_DC, int argc, zval ***argv) /* {{{ */ { int i; if (argc < 0) { return FAILURE; } zend_fcall_info_args_clear(fci, !argc); if (argc) { fci->param_count = argc; fci->params = (zval ***) erealloc(fci->params, fci->param_count * sizeof(zval **)); for (i = 0; i < argc; ++i) { fci->params[i] = argv[i]; } } return SUCCESS; } /* }}} */ ZEND_API int zend_fcall_info_argv(zend_fcall_info *fci TSRMLS_DC, int argc, va_list *argv) /* {{{ */ { int i; zval **arg; if (argc < 0) { return FAILURE; } zend_fcall_info_args_clear(fci, !argc); if (argc) { fci->param_count = argc; fci->params = (zval ***) erealloc(fci->params, fci->param_count * sizeof(zval **)); for (i = 0; i < argc; ++i) { arg = va_arg(*argv, zval **); fci->params[i] = arg; } } return SUCCESS; } /* }}} */ ZEND_API int zend_fcall_info_argn(zend_fcall_info *fci TSRMLS_DC, int argc, ...) /* {{{ */ { int ret; va_list argv; va_start(argv, argc); ret = zend_fcall_info_argv(fci TSRMLS_CC, argc, &argv); va_end(argv); return ret; } /* }}} */ ZEND_API int zend_fcall_info_call(zend_fcall_info *fci, zend_fcall_info_cache *fcc, zval **retval_ptr_ptr, zval *args TSRMLS_DC) /* {{{ */ { zval *retval, ***org_params = NULL; int result, org_count = 0; fci->retval_ptr_ptr = retval_ptr_ptr ? retval_ptr_ptr : &retval; if (args) { zend_fcall_info_args_save(fci, &org_count, &org_params); zend_fcall_info_args(fci, args TSRMLS_CC); } result = zend_call_function(fci, fcc TSRMLS_CC); if (!retval_ptr_ptr && retval) { zval_ptr_dtor(&retval); } if (args) { zend_fcall_info_args_restore(fci, org_count, org_params); } return result; } /* }}} */ ZEND_API const char *zend_get_module_version(const char *module_name) /* {{{ */ { char *lname; int name_len = strlen(module_name); zend_module_entry *module; lname = zend_str_tolower_dup(module_name, name_len); if (zend_hash_find(&module_registry, lname, name_len + 1, (void**)&module) == FAILURE) { efree(lname); return NULL; } efree(lname); return module->version; } /* }}} */ ZEND_API int zend_declare_property_ex(zend_class_entry *ce, const char *name, int name_length, zval *property, int access_type, const char *doc_comment, int doc_comment_len TSRMLS_DC) /* {{{ */ { zend_property_info property_info, *property_info_ptr; const char *interned_name; ulong h = zend_get_hash_value(name, name_length+1); if (!(access_type & ZEND_ACC_PPP_MASK)) { access_type |= ZEND_ACC_PUBLIC; } if (access_type & ZEND_ACC_STATIC) { if (zend_hash_quick_find(&ce->properties_info, name, name_length + 1, h, (void**)&property_info_ptr) == SUCCESS && (property_info_ptr->flags & ZEND_ACC_STATIC) != 0) { property_info.offset = property_info_ptr->offset; zval_ptr_dtor(&ce->default_static_members_table[property_info.offset]); zend_hash_quick_del(&ce->properties_info, name, name_length + 1, h); } else { property_info.offset = ce->default_static_members_count++; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(zval*) * ce->default_static_members_count, ce->type == ZEND_INTERNAL_CLASS); } ce->default_static_members_table[property_info.offset] = property; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } else { if (zend_hash_quick_find(&ce->properties_info, name, name_length + 1, h, (void**)&property_info_ptr) == SUCCESS && (property_info_ptr->flags & ZEND_ACC_STATIC) == 0) { property_info.offset = property_info_ptr->offset; zval_ptr_dtor(&ce->default_properties_table[property_info.offset]); zend_hash_quick_del(&ce->properties_info, name, name_length + 1, h); } else { property_info.offset = ce->default_properties_count++; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(zval*) * ce->default_properties_count, ce->type == ZEND_INTERNAL_CLASS); } ce->default_properties_table[property_info.offset] = property; } if (ce->type & ZEND_INTERNAL_CLASS) { switch(Z_TYPE_P(property)) { case IS_ARRAY: case IS_CONSTANT_ARRAY: case IS_OBJECT: case IS_RESOURCE: zend_error(E_CORE_ERROR, "Internal zval's can't be arrays, objects or resources"); break; default: break; } } switch (access_type & ZEND_ACC_PPP_MASK) { case ZEND_ACC_PRIVATE: { char *priv_name; int priv_name_length; zend_mangle_property_name(&priv_name, &priv_name_length, ce->name, ce->name_length, name, name_length, ce->type & ZEND_INTERNAL_CLASS); property_info.name = priv_name; property_info.name_length = priv_name_length; } break; case ZEND_ACC_PROTECTED: { char *prot_name; int prot_name_length; zend_mangle_property_name(&prot_name, &prot_name_length, "*", 1, name, name_length, ce->type & ZEND_INTERNAL_CLASS); property_info.name = prot_name; property_info.name_length = prot_name_length; } break; case ZEND_ACC_PUBLIC: if (IS_INTERNED(name)) { property_info.name = (char*)name; } else { property_info.name = ce->type & ZEND_INTERNAL_CLASS ? zend_strndup(name, name_length) : estrndup(name, name_length); } property_info.name_length = name_length; break; } interned_name = zend_new_interned_string(property_info.name, property_info.name_length+1, 0 TSRMLS_CC); if (interned_name != property_info.name) { if (ce->type == ZEND_USER_CLASS) { efree((char*)property_info.name); } else { free((char*)property_info.name); } property_info.name = interned_name; } property_info.flags = access_type; property_info.h = (access_type & ZEND_ACC_PUBLIC) ? h : zend_get_hash_value(property_info.name, property_info.name_length+1); property_info.doc_comment = doc_comment; property_info.doc_comment_len = doc_comment_len; property_info.ce = ce; zend_hash_quick_update(&ce->properties_info, name, name_length+1, h, &property_info, sizeof(zend_property_info), NULL); return SUCCESS; } /* }}} */ ZEND_API int zend_declare_property(zend_class_entry *ce, const char *name, int name_length, zval *property, int access_type TSRMLS_DC) /* {{{ */ { return zend_declare_property_ex(ce, name, name_length, property, access_type, NULL, 0 TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_null(zend_class_entry *ce, const char *name, int name_length, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); } else { ALLOC_ZVAL(property); } INIT_ZVAL(*property); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_bool(zend_class_entry *ce, const char *name, int name_length, long value, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); } else { ALLOC_ZVAL(property); } INIT_PZVAL(property); ZVAL_BOOL(property, value); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_long(zend_class_entry *ce, const char *name, int name_length, long value, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); } else { ALLOC_ZVAL(property); } INIT_PZVAL(property); ZVAL_LONG(property, value); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_double(zend_class_entry *ce, const char *name, int name_length, double value, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); } else { ALLOC_ZVAL(property); } INIT_PZVAL(property); ZVAL_DOUBLE(property, value); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_string(zend_class_entry *ce, const char *name, int name_length, const char *value, int access_type TSRMLS_DC) /* {{{ */ { zval *property; int len = strlen(value); if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); ZVAL_STRINGL(property, zend_strndup(value, len), len, 0); } else { ALLOC_ZVAL(property); ZVAL_STRINGL(property, value, len, 1); } INIT_PZVAL(property); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_stringl(zend_class_entry *ce, const char *name, int name_length, const char *value, int value_len, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); ZVAL_STRINGL(property, zend_strndup(value, value_len), value_len, 0); } else { ALLOC_ZVAL(property); ZVAL_STRINGL(property, value, value_len, 1); } INIT_PZVAL(property); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant(zend_class_entry *ce, const char *name, size_t name_length, zval *value TSRMLS_DC) /* {{{ */ { return zend_hash_update(&ce->constants_table, name, name_length+1, &value, sizeof(zval *), NULL); } /* }}} */ ZEND_API int zend_declare_class_constant_null(zend_class_entry *ce, const char *name, size_t name_length TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); } else { ALLOC_ZVAL(constant); } ZVAL_NULL(constant); INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_long(zend_class_entry *ce, const char *name, size_t name_length, long value TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); } else { ALLOC_ZVAL(constant); } ZVAL_LONG(constant, value); INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_bool(zend_class_entry *ce, const char *name, size_t name_length, zend_bool value TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); } else { ALLOC_ZVAL(constant); } ZVAL_BOOL(constant, value); INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_double(zend_class_entry *ce, const char *name, size_t name_length, double value TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); } else { ALLOC_ZVAL(constant); } ZVAL_DOUBLE(constant, value); INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_stringl(zend_class_entry *ce, const char *name, size_t name_length, const char *value, size_t value_length TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); ZVAL_STRINGL(constant, zend_strndup(value, value_length), value_length, 0); } else { ALLOC_ZVAL(constant); ZVAL_STRINGL(constant, value, value_length, 1); } INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_string(zend_class_entry *ce, const char *name, size_t name_length, const char *value TSRMLS_DC) /* {{{ */ { return zend_declare_class_constant_stringl(ce, name, name_length, value, strlen(value) TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property(zend_class_entry *scope, zval *object, const char *name, int name_length, zval *value TSRMLS_DC) /* {{{ */ { zval *property; zend_class_entry *old_scope = EG(scope); EG(scope) = scope; if (!Z_OBJ_HT_P(object)->write_property) { const char *class_name; zend_uint class_name_len; zend_get_object_classname(object, &class_name, &class_name_len TSRMLS_CC); zend_error(E_CORE_ERROR, "Property %s of class %s cannot be updated", name, class_name); } MAKE_STD_ZVAL(property); ZVAL_STRINGL(property, name, name_length, 1); Z_OBJ_HT_P(object)->write_property(object, property, value, 0 TSRMLS_CC); zval_ptr_dtor(&property); EG(scope) = old_scope; } /* }}} */ ZEND_API void zend_update_property_null(zend_class_entry *scope, zval *object, const char *name, int name_length TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_NULL(tmp); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_bool(zend_class_entry *scope, zval *object, const char *name, int name_length, long value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_BOOL(tmp, value); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_long(zend_class_entry *scope, zval *object, const char *name, int name_length, long value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_LONG(tmp, value); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_double(zend_class_entry *scope, zval *object, const char *name, int name_length, double value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_DOUBLE(tmp, value); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_string(zend_class_entry *scope, zval *object, const char *name, int name_length, const char *value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_STRING(tmp, value, 1); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_stringl(zend_class_entry *scope, zval *object, const char *name, int name_length, const char *value, int value_len TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_STRINGL(tmp, value, value_len, 1); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property(zend_class_entry *scope, const char *name, int name_length, zval *value TSRMLS_DC) /* {{{ */ { zval **property; zend_class_entry *old_scope = EG(scope); EG(scope) = scope; property = zend_std_get_static_property(scope, name, name_length, 0, NULL TSRMLS_CC); EG(scope) = old_scope; if (!property) { return FAILURE; } else { if (*property != value) { if (PZVAL_IS_REF(*property)) { zval_dtor(*property); Z_TYPE_PP(property) = Z_TYPE_P(value); (*property)->value = value->value; if (Z_REFCOUNT_P(value) > 0) { zval_copy_ctor(*property); } } else { zval *garbage = *property; Z_ADDREF_P(value); if (PZVAL_IS_REF(value)) { SEPARATE_ZVAL(&value); } *property = value; zval_ptr_dtor(&garbage); } } return SUCCESS; } } /* }}} */ ZEND_API int zend_update_static_property_null(zend_class_entry *scope, const char *name, int name_length TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_NULL(tmp); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_bool(zend_class_entry *scope, const char *name, int name_length, long value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_BOOL(tmp, value); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_long(zend_class_entry *scope, const char *name, int name_length, long value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_LONG(tmp, value); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_double(zend_class_entry *scope, const char *name, int name_length, double value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_DOUBLE(tmp, value); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_string(zend_class_entry *scope, const char *name, int name_length, const char *value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_STRING(tmp, value, 1); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_stringl(zend_class_entry *scope, const char *name, int name_length, const char *value, int value_len TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_STRINGL(tmp, value, value_len, 1); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API zval *zend_read_property(zend_class_entry *scope, zval *object, const char *name, int name_length, zend_bool silent TSRMLS_DC) /* {{{ */ { zval *property, *value; zend_class_entry *old_scope = EG(scope); EG(scope) = scope; if (!Z_OBJ_HT_P(object)->read_property) { const char *class_name; zend_uint class_name_len; zend_get_object_classname(object, &class_name, &class_name_len TSRMLS_CC); zend_error(E_CORE_ERROR, "Property %s of class %s cannot be read", name, class_name); } MAKE_STD_ZVAL(property); ZVAL_STRINGL(property, name, name_length, 1); value = Z_OBJ_HT_P(object)->read_property(object, property, silent?BP_VAR_IS:BP_VAR_R, 0 TSRMLS_CC); zval_ptr_dtor(&property); EG(scope) = old_scope; return value; } /* }}} */ ZEND_API zval *zend_read_static_property(zend_class_entry *scope, const char *name, int name_length, zend_bool silent TSRMLS_DC) /* {{{ */ { zval **property; zend_class_entry *old_scope = EG(scope); EG(scope) = scope; property = zend_std_get_static_property(scope, name, name_length, silent, NULL TSRMLS_CC); EG(scope) = old_scope; return property?*property:NULL; } /* }}} */ ZEND_API void zend_save_error_handling(zend_error_handling *current TSRMLS_DC) /* {{{ */ { current->handling = EG(error_handling); current->exception = EG(exception_class); current->user_handler = EG(user_error_handler); if (current->user_handler) { Z_ADDREF_P(current->user_handler); } } /* }}} */ ZEND_API void zend_replace_error_handling(zend_error_handling_t error_handling, zend_class_entry *exception_class, zend_error_handling *current TSRMLS_DC) /* {{{ */ { if (current) { zend_save_error_handling(current TSRMLS_CC); if (error_handling != EH_NORMAL && EG(user_error_handler)) { zval_ptr_dtor(&EG(user_error_handler)); EG(user_error_handler) = NULL; } } EG(error_handling) = error_handling; EG(exception_class) = error_handling == EH_THROW ? exception_class : NULL; } /* }}} */ ZEND_API void zend_restore_error_handling(zend_error_handling *saved TSRMLS_DC) /* {{{ */ { EG(error_handling) = saved->handling; EG(exception_class) = saved->handling == EH_THROW ? saved->exception : NULL; if (saved->user_handler && saved->user_handler != EG(user_error_handler)) { if (EG(user_error_handler)) { zval_ptr_dtor(&EG(user_error_handler)); } EG(user_error_handler) = saved->user_handler; } else if (saved->user_handler) { zval_ptr_dtor(&saved->user_handler); } saved->user_handler = NULL; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */ /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2012 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | Andrei Zmievski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "zend.h" #include "zend_execute.h" #include "zend_API.h" #include "zend_modules.h" #include "zend_constants.h" #include "zend_exceptions.h" #include "zend_closures.h" #ifdef HAVE_STDARG_H #include <stdarg.h> #endif /* these variables are true statics/globals, and have to be mutex'ed on every access */ static int module_count=0; ZEND_API HashTable module_registry; static zend_module_entry **module_request_startup_handlers; static zend_module_entry **module_request_shutdown_handlers; static zend_module_entry **module_post_deactivate_handlers; static zend_class_entry **class_cleanup_handlers; /* this function doesn't check for too many parameters */ ZEND_API int zend_get_parameters(int ht, int param_count, ...) /* {{{ */ { void **p; int arg_count; va_list ptr; zval **param, *param_ptr; TSRMLS_FETCH(); p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } va_start(ptr, param_count); while (param_count-->0) { param = va_arg(ptr, zval **); param_ptr = *(p-arg_count); if (!PZVAL_IS_REF(param_ptr) && Z_REFCOUNT_P(param_ptr) > 1) { zval *new_tmp; ALLOC_ZVAL(new_tmp); *new_tmp = *param_ptr; zval_copy_ctor(new_tmp); INIT_PZVAL(new_tmp); param_ptr = new_tmp; Z_DELREF_P((zval *) *(p-arg_count)); *(p-arg_count) = param_ptr; } *param = param_ptr; arg_count--; } va_end(ptr); return SUCCESS; } /* }}} */ ZEND_API int _zend_get_parameters_array(int ht, int param_count, zval **argument_array TSRMLS_DC) /* {{{ */ { void **p; int arg_count; zval *param_ptr; p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } while (param_count-->0) { param_ptr = *(p-arg_count); if (!PZVAL_IS_REF(param_ptr) && Z_REFCOUNT_P(param_ptr) > 1) { zval *new_tmp; ALLOC_ZVAL(new_tmp); *new_tmp = *param_ptr; zval_copy_ctor(new_tmp); INIT_PZVAL(new_tmp); param_ptr = new_tmp; Z_DELREF_P((zval *) *(p-arg_count)); *(p-arg_count) = param_ptr; } *(argument_array++) = param_ptr; arg_count--; } return SUCCESS; } /* }}} */ /* Zend-optimized Extended functions */ /* this function doesn't check for too many parameters */ ZEND_API int zend_get_parameters_ex(int param_count, ...) /* {{{ */ { void **p; int arg_count; va_list ptr; zval ***param; TSRMLS_FETCH(); p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } va_start(ptr, param_count); while (param_count-->0) { param = va_arg(ptr, zval ***); *param = (zval **) p-(arg_count--); } va_end(ptr); return SUCCESS; } /* }}} */ ZEND_API int _zend_get_parameters_array_ex(int param_count, zval ***argument_array TSRMLS_DC) /* {{{ */ { void **p; int arg_count; p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } while (param_count-->0) { zval **value = (zval**)(p-arg_count); *(argument_array++) = value; arg_count--; } return SUCCESS; } /* }}} */ ZEND_API int zend_copy_parameters_array(int param_count, zval *argument_array TSRMLS_DC) /* {{{ */ { void **p; int arg_count; p = zend_vm_stack_top(TSRMLS_C) - 1; arg_count = (int)(zend_uintptr_t) *p; if (param_count>arg_count) { return FAILURE; } while (param_count-->0) { zval **param = (zval **) p-(arg_count--); zval_add_ref(param); add_next_index_zval(argument_array, *param); } return SUCCESS; } /* }}} */ ZEND_API void zend_wrong_param_count(TSRMLS_D) /* {{{ */ { const char *space; const char *class_name = get_active_class_name(&space TSRMLS_CC); zend_error(E_WARNING, "Wrong parameter count for %s%s%s()", class_name, space, get_active_function_name(TSRMLS_C)); } /* }}} */ /* Argument parsing API -- andrei */ ZEND_API char *zend_get_type_by_const(int type) /* {{{ */ { switch(type) { case IS_BOOL: return "boolean"; case IS_LONG: return "integer"; case IS_DOUBLE: return "double"; case IS_STRING: return "string"; case IS_OBJECT: return "object"; case IS_RESOURCE: return "resource"; case IS_NULL: return "null"; case IS_CALLABLE: return "callable"; case IS_ARRAY: return "array"; default: return "unknown"; } } /* }}} */ ZEND_API char *zend_zval_type_name(const zval *arg) /* {{{ */ { return zend_get_type_by_const(Z_TYPE_P(arg)); } /* }}} */ ZEND_API zend_class_entry *zend_get_class_entry(const zval *zobject TSRMLS_DC) /* {{{ */ { if (Z_OBJ_HT_P(zobject)->get_class_entry) { return Z_OBJ_HT_P(zobject)->get_class_entry(zobject TSRMLS_CC); } else { zend_error(E_ERROR, "Class entry requested for an object without PHP class"); return NULL; } } /* }}} */ /* returns 1 if you need to copy result, 0 if it's already a copy */ ZEND_API int zend_get_object_classname(const zval *object, const char **class_name, zend_uint *class_name_len TSRMLS_DC) /* {{{ */ { if (Z_OBJ_HT_P(object)->get_class_name == NULL || Z_OBJ_HT_P(object)->get_class_name(object, class_name, class_name_len, 0 TSRMLS_CC) != SUCCESS) { zend_class_entry *ce = Z_OBJCE_P(object); *class_name = ce->name; *class_name_len = ce->name_length; return 1; } return 0; } /* }}} */ static int parse_arg_object_to_string(zval **arg, char **p, int *pl, int type TSRMLS_DC) /* {{{ */ { if (Z_OBJ_HANDLER_PP(arg, cast_object)) { zval *obj; MAKE_STD_ZVAL(obj); if (Z_OBJ_HANDLER_P(*arg, cast_object)(*arg, obj, type TSRMLS_CC) == SUCCESS) { zval_ptr_dtor(arg); *arg = obj; *pl = Z_STRLEN_PP(arg); *p = Z_STRVAL_PP(arg); return SUCCESS; } efree(obj); } /* Standard PHP objects */ if (Z_OBJ_HT_PP(arg) == &std_object_handlers || !Z_OBJ_HANDLER_PP(arg, cast_object)) { SEPARATE_ZVAL_IF_NOT_REF(arg); if (zend_std_cast_object_tostring(*arg, *arg, type TSRMLS_CC) == SUCCESS) { *pl = Z_STRLEN_PP(arg); *p = Z_STRVAL_PP(arg); return SUCCESS; } } if (!Z_OBJ_HANDLER_PP(arg, cast_object) && Z_OBJ_HANDLER_PP(arg, get)) { int use_copy; zval *z = Z_OBJ_HANDLER_PP(arg, get)(*arg TSRMLS_CC); Z_ADDREF_P(z); if(Z_TYPE_P(z) != IS_OBJECT) { zval_dtor(*arg); Z_TYPE_P(*arg) = IS_NULL; zend_make_printable_zval(z, *arg, &use_copy); if (!use_copy) { ZVAL_ZVAL(*arg, z, 1, 1); } *pl = Z_STRLEN_PP(arg); *p = Z_STRVAL_PP(arg); return SUCCESS; } zval_ptr_dtor(&z); } return FAILURE; } /* }}} */ static const char *zend_parse_arg_impl(int arg_num, zval **arg, va_list *va, const char **spec, char **error, int *severity TSRMLS_DC) /* {{{ */ { const char *spec_walk = *spec; char c = *spec_walk++; int return_null = 0; /* scan through modifiers */ while (1) { if (*spec_walk == '/') { SEPARATE_ZVAL_IF_NOT_REF(arg); } else if (*spec_walk == '!') { if (Z_TYPE_PP(arg) == IS_NULL) { return_null = 1; } } else { break; } spec_walk++; } switch (c) { case 'l': case 'L': { long *p = va_arg(*va, long *); switch (Z_TYPE_PP(arg)) { case IS_STRING: { double d; int type; if ((type = is_numeric_string(Z_STRVAL_PP(arg), Z_STRLEN_PP(arg), p, &d, -1)) == 0) { return "long"; } else if (type == IS_DOUBLE) { if (c == 'L') { if (d > LONG_MAX) { *p = LONG_MAX; break; } else if (d < LONG_MIN) { *p = LONG_MIN; break; } } *p = zend_dval_to_lval(d); } } break; case IS_DOUBLE: if (c == 'L') { if (Z_DVAL_PP(arg) > LONG_MAX) { *p = LONG_MAX; break; } else if (Z_DVAL_PP(arg) < LONG_MIN) { *p = LONG_MIN; break; } } case IS_NULL: case IS_LONG: case IS_BOOL: convert_to_long_ex(arg); *p = Z_LVAL_PP(arg); break; case IS_ARRAY: case IS_OBJECT: case IS_RESOURCE: default: return "long"; } } break; case 'd': { double *p = va_arg(*va, double *); switch (Z_TYPE_PP(arg)) { case IS_STRING: { long l; int type; if ((type = is_numeric_string(Z_STRVAL_PP(arg), Z_STRLEN_PP(arg), &l, p, -1)) == 0) { return "double"; } else if (type == IS_LONG) { *p = (double) l; } } break; case IS_NULL: case IS_LONG: case IS_DOUBLE: case IS_BOOL: convert_to_double_ex(arg); *p = Z_DVAL_PP(arg); break; case IS_ARRAY: case IS_OBJECT: case IS_RESOURCE: default: return "double"; } } break; case 'p': case 's': { char **p = va_arg(*va, char **); int *pl = va_arg(*va, int *); switch (Z_TYPE_PP(arg)) { case IS_NULL: if (return_null) { *p = NULL; *pl = 0; break; } /* break omitted intentionally */ case IS_STRING: case IS_LONG: case IS_DOUBLE: case IS_BOOL: convert_to_string_ex(arg); if (UNEXPECTED(Z_ISREF_PP(arg) != 0)) { /* it's dangerous to return pointers to string buffer of referenced variable, because it can be clobbered throug magic callbacks */ SEPARATE_ZVAL(arg); } *p = Z_STRVAL_PP(arg); *pl = Z_STRLEN_PP(arg); if (c == 'p' && CHECK_ZVAL_NULL_PATH(*arg)) { return "a valid path"; } break; case IS_OBJECT: if (parse_arg_object_to_string(arg, p, pl, IS_STRING TSRMLS_CC) == SUCCESS) { if (c == 'p' && CHECK_ZVAL_NULL_PATH(*arg)) { return "a valid path"; } break; } case IS_ARRAY: case IS_RESOURCE: default: return c == 's' ? "string" : "a valid path"; } } break; case 'b': { zend_bool *p = va_arg(*va, zend_bool *); switch (Z_TYPE_PP(arg)) { case IS_NULL: case IS_STRING: case IS_LONG: case IS_DOUBLE: case IS_BOOL: convert_to_boolean_ex(arg); *p = Z_BVAL_PP(arg); break; case IS_ARRAY: case IS_OBJECT: case IS_RESOURCE: default: return "boolean"; } } break; case 'r': { zval **p = va_arg(*va, zval **); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_RESOURCE) { *p = *arg; } else { return "resource"; } } break; case 'A': case 'a': { zval **p = va_arg(*va, zval **); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_ARRAY || (c == 'A' && Z_TYPE_PP(arg) == IS_OBJECT)) { *p = *arg; } else { return "array"; } } break; case 'H': case 'h': { HashTable **p = va_arg(*va, HashTable **); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_ARRAY) { *p = Z_ARRVAL_PP(arg); } else if(c == 'H' && Z_TYPE_PP(arg) == IS_OBJECT) { *p = HASH_OF(*arg); if(*p == NULL) { return "array"; } } else { return "array"; } } break; case 'o': { zval **p = va_arg(*va, zval **); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_OBJECT) { *p = *arg; } else { return "object"; } } break; case 'O': { zval **p = va_arg(*va, zval **); zend_class_entry *ce = va_arg(*va, zend_class_entry *); if (return_null) { *p = NULL; break; } if (Z_TYPE_PP(arg) == IS_OBJECT && (!ce || instanceof_function(Z_OBJCE_PP(arg), ce TSRMLS_CC))) { *p = *arg; } else { if (ce) { return ce->name; } else { return "object"; } } } break; case 'C': { zend_class_entry **lookup, **pce = va_arg(*va, zend_class_entry **); zend_class_entry *ce_base = *pce; if (return_null) { *pce = NULL; break; } convert_to_string_ex(arg); if (zend_lookup_class(Z_STRVAL_PP(arg), Z_STRLEN_PP(arg), &lookup TSRMLS_CC) == FAILURE) { *pce = NULL; } else { *pce = *lookup; } if (ce_base) { if ((!*pce || !instanceof_function(*pce, ce_base TSRMLS_CC))) { zend_spprintf(error, 0, "to be a class name derived from %s, '%s' given", ce_base->name, Z_STRVAL_PP(arg)); *pce = NULL; return ""; } } if (!*pce) { zend_spprintf(error, 0, "to be a valid class name, '%s' given", Z_STRVAL_PP(arg)); return ""; } break; } break; case 'f': { zend_fcall_info *fci = va_arg(*va, zend_fcall_info *); zend_fcall_info_cache *fcc = va_arg(*va, zend_fcall_info_cache *); char *is_callable_error = NULL; if (return_null) { fci->size = 0; fcc->initialized = 0; break; } if (zend_fcall_info_init(*arg, 0, fci, fcc, NULL, &is_callable_error TSRMLS_CC) == SUCCESS) { if (is_callable_error) { *severity = E_STRICT; zend_spprintf(error, 0, "to be a valid callback, %s", is_callable_error); efree(is_callable_error); *spec = spec_walk; return ""; } break; } else { if (is_callable_error) { *severity = E_WARNING; zend_spprintf(error, 0, "to be a valid callback, %s", is_callable_error); efree(is_callable_error); return ""; } else { return "valid callback"; } } } case 'z': { zval **p = va_arg(*va, zval **); if (return_null) { *p = NULL; } else { *p = *arg; } } break; case 'Z': { zval ***p = va_arg(*va, zval ***); if (return_null) { *p = NULL; } else { *p = arg; } } break; default: return "unknown"; } *spec = spec_walk; return NULL; } /* }}} */ static int zend_parse_arg(int arg_num, zval **arg, va_list *va, const char **spec, int quiet TSRMLS_DC) /* {{{ */ { const char *expected_type = NULL; char *error = NULL; int severity = E_WARNING; expected_type = zend_parse_arg_impl(arg_num, arg, va, spec, &error, &severity TSRMLS_CC); if (expected_type) { if (!quiet && (*expected_type || error)) { const char *space; const char *class_name = get_active_class_name(&space TSRMLS_CC); if (error) { zend_error(severity, "%s%s%s() expects parameter %d %s", class_name, space, get_active_function_name(TSRMLS_C), arg_num, error); efree(error); } else { zend_error(severity, "%s%s%s() expects parameter %d to be %s, %s given", class_name, space, get_active_function_name(TSRMLS_C), arg_num, expected_type, zend_zval_type_name(*arg)); } } if (severity != E_STRICT) { return FAILURE; } } return SUCCESS; } /* }}} */ static int zend_parse_va_args(int num_args, const char *type_spec, va_list *va, int flags TSRMLS_DC) /* {{{ */ { const char *spec_walk; int c, i; int min_num_args = -1; int max_num_args = 0; int post_varargs = 0; zval **arg; int arg_count; int quiet = flags & ZEND_PARSE_PARAMS_QUIET; zend_bool have_varargs = 0; zval ****varargs = NULL; int *n_varargs = NULL; for (spec_walk = type_spec; *spec_walk; spec_walk++) { c = *spec_walk; switch (c) { case 'l': case 'd': case 's': case 'b': case 'r': case 'a': case 'o': case 'O': case 'z': case 'Z': case 'C': case 'h': case 'f': case 'A': case 'H': case 'p': max_num_args++; break; case '|': min_num_args = max_num_args; break; case '/': case '!': /* Pass */ break; case '*': case '+': if (have_varargs) { if (!quiet) { zend_function *active_function = EG(current_execute_data)->function_state.function; const char *class_name = active_function->common.scope ? active_function->common.scope->name : ""; zend_error(E_WARNING, "%s%s%s(): only one varargs specifier (* or +) is permitted", class_name, class_name[0] ? "::" : "", active_function->common.function_name); } return FAILURE; } have_varargs = 1; /* we expect at least one parameter in varargs */ if (c == '+') { max_num_args++; } /* mark the beginning of varargs */ post_varargs = max_num_args; break; default: if (!quiet) { zend_function *active_function = EG(current_execute_data)->function_state.function; const char *class_name = active_function->common.scope ? active_function->common.scope->name : ""; zend_error(E_WARNING, "%s%s%s(): bad type specifier while parsing parameters", class_name, class_name[0] ? "::" : "", active_function->common.function_name); } return FAILURE; } } if (min_num_args < 0) { min_num_args = max_num_args; } if (have_varargs) { /* calculate how many required args are at the end of the specifier list */ post_varargs = max_num_args - post_varargs; max_num_args = -1; } if (num_args < min_num_args || (num_args > max_num_args && max_num_args > 0)) { if (!quiet) { zend_function *active_function = EG(current_execute_data)->function_state.function; const char *class_name = active_function->common.scope ? active_function->common.scope->name : ""; zend_error(E_WARNING, "%s%s%s() expects %s %d parameter%s, %d given", class_name, class_name[0] ? "::" : "", active_function->common.function_name, min_num_args == max_num_args ? "exactly" : num_args < min_num_args ? "at least" : "at most", num_args < min_num_args ? min_num_args : max_num_args, (num_args < min_num_args ? min_num_args : max_num_args) == 1 ? "" : "s", num_args); } return FAILURE; } arg_count = (int)(zend_uintptr_t) *(zend_vm_stack_top(TSRMLS_C) - 1); if (num_args > arg_count) { zend_error(E_WARNING, "%s(): could not obtain parameters for parsing", get_active_function_name(TSRMLS_C)); return FAILURE; } i = 0; while (num_args-- > 0) { if (*type_spec == '|') { type_spec++; } if (*type_spec == '*' || *type_spec == '+') { int num_varargs = num_args + 1 - post_varargs; /* eat up the passed in storage even if it won't be filled in with varargs */ varargs = va_arg(*va, zval ****); n_varargs = va_arg(*va, int *); type_spec++; if (num_varargs > 0) { int iv = 0; zval **p = (zval **) (zend_vm_stack_top(TSRMLS_C) - 1 - (arg_count - i)); *n_varargs = num_varargs; /* allocate space for array and store args */ *varargs = safe_emalloc(num_varargs, sizeof(zval **), 0); while (num_varargs-- > 0) { (*varargs)[iv++] = p++; } /* adjust how many args we have left and restart loop */ num_args = num_args + 1 - iv; i += iv; continue; } else { *varargs = NULL; *n_varargs = 0; } } arg = (zval **) (zend_vm_stack_top(TSRMLS_C) - 1 - (arg_count-i)); if (zend_parse_arg(i+1, arg, va, &type_spec, quiet TSRMLS_CC) == FAILURE) { /* clean up varargs array if it was used */ if (varargs && *varargs) { efree(*varargs); *varargs = NULL; } return FAILURE; } i++; } return SUCCESS; } /* }}} */ #define RETURN_IF_ZERO_ARGS(num_args, type_spec, quiet) { \ int __num_args = (num_args); \ \ if (0 == (type_spec)[0] && 0 != __num_args && !(quiet)) { \ const char *__space; \ const char * __class_name = get_active_class_name(&__space TSRMLS_CC); \ zend_error(E_WARNING, "%s%s%s() expects exactly 0 parameters, %d given", \ __class_name, __space, \ get_active_function_name(TSRMLS_C), __num_args); \ return FAILURE; \ }\ } ZEND_API int zend_parse_parameters_ex(int flags, int num_args TSRMLS_DC, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; RETURN_IF_ZERO_ARGS(num_args, type_spec, flags & ZEND_PARSE_PARAMS_QUIET); va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, flags TSRMLS_CC); va_end(va); return retval; } /* }}} */ ZEND_API int zend_parse_parameters(int num_args TSRMLS_DC, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; RETURN_IF_ZERO_ARGS(num_args, type_spec, 0); va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, 0 TSRMLS_CC); va_end(va); return retval; } /* }}} */ ZEND_API int zend_parse_method_parameters(int num_args TSRMLS_DC, zval *this_ptr, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; const char *p = type_spec; zval **object; zend_class_entry *ce; if (!this_ptr) { RETURN_IF_ZERO_ARGS(num_args, p, 0); va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, 0 TSRMLS_CC); va_end(va); } else { p++; RETURN_IF_ZERO_ARGS(num_args, p, 0); va_start(va, type_spec); object = va_arg(va, zval **); ce = va_arg(va, zend_class_entry *); *object = this_ptr; if (ce && !instanceof_function(Z_OBJCE_P(this_ptr), ce TSRMLS_CC)) { zend_error(E_CORE_ERROR, "%s::%s() must be derived from %s::%s", ce->name, get_active_function_name(TSRMLS_C), Z_OBJCE_P(this_ptr)->name, get_active_function_name(TSRMLS_C)); } retval = zend_parse_va_args(num_args, p, &va, 0 TSRMLS_CC); va_end(va); } return retval; } /* }}} */ ZEND_API int zend_parse_method_parameters_ex(int flags, int num_args TSRMLS_DC, zval *this_ptr, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; const char *p = type_spec; zval **object; zend_class_entry *ce; int quiet = flags & ZEND_PARSE_PARAMS_QUIET; if (!this_ptr) { RETURN_IF_ZERO_ARGS(num_args, p, quiet); va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, flags TSRMLS_CC); va_end(va); } else { p++; RETURN_IF_ZERO_ARGS(num_args, p, quiet); va_start(va, type_spec); object = va_arg(va, zval **); ce = va_arg(va, zend_class_entry *); *object = this_ptr; if (ce && !instanceof_function(Z_OBJCE_P(this_ptr), ce TSRMLS_CC)) { if (!quiet) { zend_error(E_CORE_ERROR, "%s::%s() must be derived from %s::%s", ce->name, get_active_function_name(TSRMLS_C), Z_OBJCE_P(this_ptr)->name, get_active_function_name(TSRMLS_C)); } va_end(va); return FAILURE; } retval = zend_parse_va_args(num_args, p, &va, flags TSRMLS_CC); va_end(va); } return retval; } /* }}} */ /* Argument parsing API -- andrei */ ZEND_API int _array_init(zval *arg, uint size ZEND_FILE_LINE_DC) /* {{{ */ { ALLOC_HASHTABLE_REL(Z_ARRVAL_P(arg)); _zend_hash_init(Z_ARRVAL_P(arg), size, NULL, ZVAL_PTR_DTOR, 0 ZEND_FILE_LINE_RELAY_CC); Z_TYPE_P(arg) = IS_ARRAY; return SUCCESS; } /* }}} */ static int zend_merge_property(zval **value TSRMLS_DC, int num_args, va_list args, const zend_hash_key *hash_key) /* {{{ */ { /* which name should a numeric property have ? */ if (hash_key->nKeyLength) { zval *obj = va_arg(args, zval *); zend_object_handlers *obj_ht = va_arg(args, zend_object_handlers *); zval *member; MAKE_STD_ZVAL(member); ZVAL_STRINGL(member, hash_key->arKey, hash_key->nKeyLength-1, 1); obj_ht->write_property(obj, member, *value, 0 TSRMLS_CC); zval_ptr_dtor(&member); } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* This function should be called after the constructor has been called * because it may call __set from the uninitialized object otherwise. */ ZEND_API void zend_merge_properties(zval *obj, HashTable *properties, int destroy_ht TSRMLS_DC) /* {{{ */ { const zend_object_handlers *obj_ht = Z_OBJ_HT_P(obj); zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE_P(obj); zend_hash_apply_with_arguments(properties TSRMLS_CC, (apply_func_args_t)zend_merge_property, 2, obj, obj_ht); EG(scope) = old_scope; if (destroy_ht) { zend_hash_destroy(properties); FREE_HASHTABLE(properties); } } /* }}} */ ZEND_API void zend_update_class_constants(zend_class_entry *class_type TSRMLS_DC) /* {{{ */ { if ((class_type->ce_flags & ZEND_ACC_CONSTANTS_UPDATED) == 0 || (!CE_STATIC_MEMBERS(class_type) && class_type->default_static_members_count)) { zend_class_entry **scope = EG(in_execution)?&EG(scope):&CG(active_class_entry); zend_class_entry *old_scope = *scope; int i; *scope = class_type; zend_hash_apply_with_argument(&class_type->constants_table, (apply_func_arg_t) zval_update_constant, (void*)1 TSRMLS_CC); for (i = 0; i < class_type->default_properties_count; i++) { if (class_type->default_properties_table[i]) { zval_update_constant(&class_type->default_properties_table[i], (void**)1 TSRMLS_CC); } } if (!CE_STATIC_MEMBERS(class_type) && class_type->default_static_members_count) { zval **p; if (class_type->parent) { zend_update_class_constants(class_type->parent TSRMLS_CC); } #if ZTS CG(static_members_table)[(zend_intptr_t)(class_type->static_members_table)] = emalloc(sizeof(zval*) * class_type->default_static_members_count); #else class_type->static_members_table = emalloc(sizeof(zval*) * class_type->default_static_members_count); #endif for (i = 0; i < class_type->default_static_members_count; i++) { p = &class_type->default_static_members_table[i]; if (Z_ISREF_PP(p) && class_type->parent && i < class_type->parent->default_static_members_count && *p == class_type->parent->default_static_members_table[i] && CE_STATIC_MEMBERS(class_type->parent)[i] ) { zval *q = CE_STATIC_MEMBERS(class_type->parent)[i]; Z_ADDREF_P(q); Z_SET_ISREF_P(q); CE_STATIC_MEMBERS(class_type)[i] = q; } else { zval *r; ALLOC_ZVAL(r); *r = **p; INIT_PZVAL(r); zval_copy_ctor(r); CE_STATIC_MEMBERS(class_type)[i] = r; } } } for (i = 0; i < class_type->default_static_members_count; i++) { zval_update_constant(&CE_STATIC_MEMBERS(class_type)[i], (void**)1 TSRMLS_CC); } *scope = old_scope; class_type->ce_flags |= ZEND_ACC_CONSTANTS_UPDATED; } } /* }}} */ ZEND_API void object_properties_init(zend_object *object, zend_class_entry *class_type) /* {{{ */ { int i; if (class_type->default_properties_count) { object->properties_table = emalloc(sizeof(zval*) * class_type->default_properties_count); for (i = 0; i < class_type->default_properties_count; i++) { object->properties_table[i] = class_type->default_properties_table[i]; if (class_type->default_properties_table[i]) { Z_ADDREF_P(object->properties_table[i]); } } object->properties = NULL; } } /* }}} */ /* This function requires 'properties' to contain all props declared in the * class and all props being public. If only a subset is given or the class * has protected members then you need to merge the properties seperately by * calling zend_merge_properties(). */ ZEND_API int _object_and_properties_init(zval *arg, zend_class_entry *class_type, HashTable *properties ZEND_FILE_LINE_DC TSRMLS_DC) /* {{{ */ { zend_object *object; if (class_type->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLICIT_ABSTRACT_CLASS|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) { char *what = (class_type->ce_flags & ZEND_ACC_INTERFACE) ? "interface" :((class_type->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) ? "trait" : "abstract class"; zend_error(E_ERROR, "Cannot instantiate %s %s", what, class_type->name); } zend_update_class_constants(class_type TSRMLS_CC); Z_TYPE_P(arg) = IS_OBJECT; if (class_type->create_object == NULL) { Z_OBJVAL_P(arg) = zend_objects_new(&object, class_type TSRMLS_CC); if (properties) { object->properties = properties; object->properties_table = NULL; } else { object_properties_init(object, class_type); } } else { Z_OBJVAL_P(arg) = class_type->create_object(class_type TSRMLS_CC); } return SUCCESS; } /* }}} */ ZEND_API int _object_init_ex(zval *arg, zend_class_entry *class_type ZEND_FILE_LINE_DC TSRMLS_DC) /* {{{ */ { return _object_and_properties_init(arg, class_type, 0 ZEND_FILE_LINE_RELAY_CC TSRMLS_CC); } /* }}} */ ZEND_API int _object_init(zval *arg ZEND_FILE_LINE_DC TSRMLS_DC) /* {{{ */ { return _object_init_ex(arg, zend_standard_class_def ZEND_FILE_LINE_RELAY_CC TSRMLS_CC); } /* }}} */ ZEND_API int add_assoc_function(zval *arg, const char *key, void (*function_ptr)(INTERNAL_FUNCTION_PARAMETERS)) /* {{{ */ { zend_error(E_WARNING, "add_assoc_function() is no longer supported"); return FAILURE; } /* }}} */ ZEND_API int add_assoc_long_ex(zval *arg, const char *key, uint key_len, long n) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, n); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_null_ex(zval *arg, const char *key, uint key_len) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_NULL(tmp); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_bool_ex(zval *arg, const char *key, uint key_len, int b) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_BOOL(tmp, b); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_resource_ex(zval *arg, const char *key, uint key_len, int r) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_RESOURCE(tmp, r); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_double_ex(zval *arg, const char *key, uint key_len, double d) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_string_ex(zval *arg, const char *key, uint key_len, char *str, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_stringl_ex(zval *arg, const char *key, uint key_len, char *str, uint length, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_assoc_zval_ex(zval *arg, const char *key, uint key_len, zval *value) /* {{{ */ { return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &value, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_long(zval *arg, ulong index, long n) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, n); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_null(zval *arg, ulong index) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_NULL(tmp); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_bool(zval *arg, ulong index, int b) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_BOOL(tmp, b); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_resource(zval *arg, ulong index, int r) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_RESOURCE(tmp, r); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_double(zval *arg, ulong index, double d) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_string(zval *arg, ulong index, const char *str, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_stringl(zval *arg, ulong index, const char *str, uint length, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_index_zval(zval *arg, ulong index, zval *value) /* {{{ */ { return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &value, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_long(zval *arg, long n) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, n); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_null(zval *arg) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_NULL(tmp); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_bool(zval *arg, int b) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_BOOL(tmp, b); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_resource(zval *arg, int r) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_RESOURCE(tmp, r); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_double(zval *arg, double d) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_string(zval *arg, const char *str, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_stringl(zval *arg, const char *str, uint length, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_next_index_zval(zval *arg, zval *value) /* {{{ */ { return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &value, sizeof(zval *), NULL); } /* }}} */ ZEND_API int add_get_assoc_string_ex(zval *arg, const char *key, uint key_len, const char *str, void **dest, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_assoc_stringl_ex(zval *arg, const char *key, uint key_len, const char *str, uint length, void **dest, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_symtable_update(Z_ARRVAL_P(arg), key, key_len, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_index_long(zval *arg, ulong index, long l, void **dest) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, l); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_index_double(zval *arg, ulong index, double d, void **dest) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_index_string(zval *arg, ulong index, const char *str, void **dest, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_get_index_stringl(zval *arg, ulong index, const char *str, uint length, void **dest, int duplicate) /* {{{ */ { zval *tmp; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); return zend_hash_index_update(Z_ARRVAL_P(arg), index, (void *) &tmp, sizeof(zval *), dest); } /* }}} */ ZEND_API int add_property_long_ex(zval *arg, const char *key, uint key_len, long n TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_LONG(tmp, n); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_bool_ex(zval *arg, const char *key, uint key_len, int b TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_BOOL(tmp, b); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_null_ex(zval *arg, const char *key, uint key_len TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_NULL(tmp); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_resource_ex(zval *arg, const char *key, uint key_len, long n TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_RESOURCE(tmp, n); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_double_ex(zval *arg, const char *key, uint key_len, double d TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_DOUBLE(tmp, d); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_string_ex(zval *arg, const char *key, uint key_len, const char *str, int duplicate TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_STRING(tmp, str, duplicate); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_stringl_ex(zval *arg, const char *key, uint key_len, const char *str, uint length, int duplicate TSRMLS_DC) /* {{{ */ { zval *tmp; zval *z_key; MAKE_STD_ZVAL(tmp); ZVAL_STRINGL(tmp, str, length, duplicate); MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, tmp, 0 TSRMLS_CC); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int add_property_zval_ex(zval *arg, const char *key, uint key_len, zval *value TSRMLS_DC) /* {{{ */ { zval *z_key; MAKE_STD_ZVAL(z_key); ZVAL_STRINGL(z_key, key, key_len-1, 1); Z_OBJ_HANDLER_P(arg, write_property)(arg, z_key, value, 0 TSRMLS_CC); zval_ptr_dtor(&z_key); return SUCCESS; } /* }}} */ ZEND_API int zend_startup_module_ex(zend_module_entry *module TSRMLS_DC) /* {{{ */ { int name_len; char *lcname; if (module->module_started) { return SUCCESS; } module->module_started = 1; /* Check module dependencies */ if (module->deps) { const zend_module_dep *dep = module->deps; while (dep->name) { if (dep->type == MODULE_DEP_REQUIRED) { zend_module_entry *req_mod; name_len = strlen(dep->name); lcname = zend_str_tolower_dup(dep->name, name_len); if (zend_hash_find(&module_registry, lcname, name_len+1, (void**)&req_mod) == FAILURE || !req_mod->module_started) { efree(lcname); /* TODO: Check version relationship */ zend_error(E_CORE_WARNING, "Cannot load module '%s' because required module '%s' is not loaded", module->name, dep->name); module->module_started = 0; return FAILURE; } efree(lcname); } ++dep; } } /* Initialize module globals */ if (module->globals_size) { #ifdef ZTS ts_allocate_id(module->globals_id_ptr, module->globals_size, (ts_allocate_ctor) module->globals_ctor, (ts_allocate_dtor) module->globals_dtor); #else if (module->globals_ctor) { module->globals_ctor(module->globals_ptr TSRMLS_CC); } #endif } if (module->module_startup_func) { EG(current_module) = module; if (module->module_startup_func(module->type, module->module_number TSRMLS_CC)==FAILURE) { zend_error(E_CORE_ERROR,"Unable to start %s module", module->name); EG(current_module) = NULL; return FAILURE; } EG(current_module) = NULL; } return SUCCESS; } /* }}} */ static void zend_sort_modules(void *base, size_t count, size_t siz, compare_func_t compare TSRMLS_DC) /* {{{ */ { Bucket **b1 = base; Bucket **b2; Bucket **end = b1 + count; Bucket *tmp; zend_module_entry *m, *r; while (b1 < end) { try_again: m = (zend_module_entry*)(*b1)->pData; if (!m->module_started && m->deps) { const zend_module_dep *dep = m->deps; while (dep->name) { if (dep->type == MODULE_DEP_REQUIRED || dep->type == MODULE_DEP_OPTIONAL) { b2 = b1 + 1; while (b2 < end) { r = (zend_module_entry*)(*b2)->pData; if (strcasecmp(dep->name, r->name) == 0) { tmp = *b1; *b1 = *b2; *b2 = tmp; goto try_again; } b2++; } } dep++; } } b1++; } } /* }}} */ ZEND_API void zend_collect_module_handlers(TSRMLS_D) /* {{{ */ { HashPosition pos; zend_module_entry *module; int startup_count = 0; int shutdown_count = 0; int post_deactivate_count = 0; zend_class_entry **pce; int class_count = 0; /* Collect extensions with request startup/shutdown handlers */ for (zend_hash_internal_pointer_reset_ex(&module_registry, &pos); zend_hash_get_current_data_ex(&module_registry, (void *) &module, &pos) == SUCCESS; zend_hash_move_forward_ex(&module_registry, &pos)) { if (module->request_startup_func) { startup_count++; } if (module->request_shutdown_func) { shutdown_count++; } if (module->post_deactivate_func) { post_deactivate_count++; } } module_request_startup_handlers = (zend_module_entry**)malloc( sizeof(zend_module_entry*) * (startup_count + 1 + shutdown_count + 1 + post_deactivate_count + 1)); module_request_startup_handlers[startup_count] = NULL; module_request_shutdown_handlers = module_request_startup_handlers + startup_count + 1; module_request_shutdown_handlers[shutdown_count] = NULL; module_post_deactivate_handlers = module_request_shutdown_handlers + shutdown_count + 1; module_post_deactivate_handlers[post_deactivate_count] = NULL; startup_count = 0; for (zend_hash_internal_pointer_reset_ex(&module_registry, &pos); zend_hash_get_current_data_ex(&module_registry, (void *) &module, &pos) == SUCCESS; zend_hash_move_forward_ex(&module_registry, &pos)) { if (module->request_startup_func) { module_request_startup_handlers[startup_count++] = module; } if (module->request_shutdown_func) { module_request_shutdown_handlers[--shutdown_count] = module; } if (module->post_deactivate_func) { module_post_deactivate_handlers[--post_deactivate_count] = module; } } /* Collect internal classes with static members */ for (zend_hash_internal_pointer_reset_ex(CG(class_table), &pos); zend_hash_get_current_data_ex(CG(class_table), (void *) &pce, &pos) == SUCCESS; zend_hash_move_forward_ex(CG(class_table), &pos)) { if ((*pce)->type == ZEND_INTERNAL_CLASS && (*pce)->default_static_members_count > 0) { class_count++; } } class_cleanup_handlers = (zend_class_entry**)malloc( sizeof(zend_class_entry*) * (class_count + 1)); class_cleanup_handlers[class_count] = NULL; if (class_count) { for (zend_hash_internal_pointer_reset_ex(CG(class_table), &pos); zend_hash_get_current_data_ex(CG(class_table), (void *) &pce, &pos) == SUCCESS; zend_hash_move_forward_ex(CG(class_table), &pos)) { if ((*pce)->type == ZEND_INTERNAL_CLASS && (*pce)->default_static_members_count > 0) { class_cleanup_handlers[--class_count] = *pce; } } } } /* }}} */ ZEND_API int zend_startup_modules(TSRMLS_D) /* {{{ */ { zend_hash_sort(&module_registry, zend_sort_modules, NULL, 0 TSRMLS_CC); zend_hash_apply(&module_registry, (apply_func_t)zend_startup_module_ex TSRMLS_CC); return SUCCESS; } /* }}} */ ZEND_API void zend_destroy_modules(void) /* {{{ */ { free(class_cleanup_handlers); free(module_request_startup_handlers); zend_hash_graceful_reverse_destroy(&module_registry); } /* }}} */ ZEND_API zend_module_entry* zend_register_module_ex(zend_module_entry *module TSRMLS_DC) /* {{{ */ { int name_len; char *lcname; zend_module_entry *module_ptr; if (!module) { return NULL; } #if 0 zend_printf("%s: Registering module %d\n", module->name, module->module_number); #endif /* Check module dependencies */ if (module->deps) { const zend_module_dep *dep = module->deps; while (dep->name) { if (dep->type == MODULE_DEP_CONFLICTS) { name_len = strlen(dep->name); lcname = zend_str_tolower_dup(dep->name, name_len); if (zend_hash_exists(&module_registry, lcname, name_len+1)) { efree(lcname); /* TODO: Check version relationship */ zend_error(E_CORE_WARNING, "Cannot load module '%s' because conflicting module '%s' is already loaded", module->name, dep->name); return NULL; } efree(lcname); } ++dep; } } name_len = strlen(module->name); lcname = zend_str_tolower_dup(module->name, name_len); if (zend_hash_add(&module_registry, lcname, name_len+1, (void *)module, sizeof(zend_module_entry), (void**)&module_ptr)==FAILURE) { zend_error(E_CORE_WARNING, "Module '%s' already loaded", module->name); efree(lcname); return NULL; } efree(lcname); module = module_ptr; EG(current_module) = module; if (module->functions && zend_register_functions(NULL, module->functions, NULL, module->type TSRMLS_CC)==FAILURE) { EG(current_module) = NULL; zend_error(E_CORE_WARNING,"%s: Unable to register functions, unable to load", module->name); return NULL; } EG(current_module) = NULL; return module; } /* }}} */ ZEND_API zend_module_entry* zend_register_internal_module(zend_module_entry *module TSRMLS_DC) /* {{{ */ { module->module_number = zend_next_free_module(); module->type = MODULE_PERSISTENT; return zend_register_module_ex(module TSRMLS_CC); } /* }}} */ ZEND_API void zend_check_magic_method_implementation(const zend_class_entry *ce, const zend_function *fptr, int error_type TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(fptr->common.function_name); zend_str_tolower_copy(lcname, fptr->common.function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)) && fptr->common.num_args != 0) { zend_error(error_type, "Destructor %s::%s() cannot take arguments", ce->name, ZEND_DESTRUCTOR_FUNC_NAME); } else if (name_len == sizeof(ZEND_CLONE_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)) && fptr->common.num_args != 0) { zend_error(error_type, "Method %s::%s() cannot accept any arguments", ce->name, ZEND_CLONE_FUNC_NAME); } else if (name_len == sizeof(ZEND_GET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME))) { if (fptr->common.num_args != 1) { zend_error(error_type, "Method %s::%s() must take exactly 1 argument", ce->name, ZEND_GET_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_GET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_SET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME))) { if (fptr->common.num_args != 2) { zend_error(error_type, "Method %s::%s() must take exactly 2 arguments", ce->name, ZEND_SET_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1) || ARG_SHOULD_BE_SENT_BY_REF(fptr, 2)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_SET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_UNSET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME))) { if (fptr->common.num_args != 1) { zend_error(error_type, "Method %s::%s() must take exactly 1 argument", ce->name, ZEND_UNSET_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_UNSET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_ISSET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME))) { if (fptr->common.num_args != 1) { zend_error(error_type, "Method %s::%s() must take exactly 1 argument", ce->name, ZEND_ISSET_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_ISSET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_CALL_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME))) { if (fptr->common.num_args != 2) { zend_error(error_type, "Method %s::%s() must take exactly 2 arguments", ce->name, ZEND_CALL_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1) || ARG_SHOULD_BE_SENT_BY_REF(fptr, 2)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_CALL_FUNC_NAME); } } else if (name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) ) { if (fptr->common.num_args != 2) { zend_error(error_type, "Method %s::%s() must take exactly 2 arguments", ce->name, ZEND_CALLSTATIC_FUNC_NAME); } else if (ARG_SHOULD_BE_SENT_BY_REF(fptr, 1) || ARG_SHOULD_BE_SENT_BY_REF(fptr, 2)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ce->name, ZEND_CALLSTATIC_FUNC_NAME); } } else if (name_len == sizeof(ZEND_TOSTRING_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && fptr->common.num_args != 0 ) { zend_error(error_type, "Method %s::%s() cannot take arguments", ce->name, ZEND_TOSTRING_FUNC_NAME); } } /* }}} */ /* registers all functions in *library_functions in the function hash */ ZEND_API int zend_register_functions(zend_class_entry *scope, const zend_function_entry *functions, HashTable *function_table, int type TSRMLS_DC) /* {{{ */ { const zend_function_entry *ptr = functions; zend_function function, *reg_function; zend_internal_function *internal_function = (zend_internal_function *)&function; int count=0, unload=0, result=0; HashTable *target_function_table = function_table; int error_type; zend_function *ctor = NULL, *dtor = NULL, *clone = NULL, *__get = NULL, *__set = NULL, *__unset = NULL, *__isset = NULL, *__call = NULL, *__callstatic = NULL, *__tostring = NULL; const char *lowercase_name; int fname_len; const char *lc_class_name = NULL; int class_name_len = 0; if (type==MODULE_PERSISTENT) { error_type = E_CORE_WARNING; } else { error_type = E_WARNING; } if (!target_function_table) { target_function_table = CG(function_table); } internal_function->type = ZEND_INTERNAL_FUNCTION; internal_function->module = EG(current_module); if (scope) { class_name_len = strlen(scope->name); if ((lc_class_name = zend_memrchr(scope->name, '\\', class_name_len))) { ++lc_class_name; class_name_len -= (lc_class_name - scope->name); lc_class_name = zend_str_tolower_dup(lc_class_name, class_name_len); } else { lc_class_name = zend_str_tolower_dup(scope->name, class_name_len); } } while (ptr->fname) { internal_function->handler = ptr->handler; internal_function->function_name = (char*)ptr->fname; internal_function->scope = scope; internal_function->prototype = NULL; if (ptr->flags) { if (!(ptr->flags & ZEND_ACC_PPP_MASK)) { if (ptr->flags != ZEND_ACC_DEPRECATED || scope) { zend_error(error_type, "Invalid access level for %s%s%s() - access must be exactly one of public, protected or private", scope ? scope->name : "", scope ? "::" : "", ptr->fname); } internal_function->fn_flags = ZEND_ACC_PUBLIC | ptr->flags; } else { internal_function->fn_flags = ptr->flags; } } else { internal_function->fn_flags = ZEND_ACC_PUBLIC; } if (ptr->arg_info) { zend_internal_function_info *info = (zend_internal_function_info*)ptr->arg_info; internal_function->arg_info = (zend_arg_info*)ptr->arg_info+1; internal_function->num_args = ptr->num_args; /* Currently you cannot denote that the function can accept less arguments than num_args */ if (info->required_num_args == -1) { internal_function->required_num_args = ptr->num_args; } else { internal_function->required_num_args = info->required_num_args; } if (info->pass_rest_by_reference) { if (info->pass_rest_by_reference == ZEND_SEND_PREFER_REF) { internal_function->fn_flags |= ZEND_ACC_PASS_REST_PREFER_REF; } else { internal_function->fn_flags |= ZEND_ACC_PASS_REST_BY_REFERENCE; } } if (info->return_reference) { internal_function->fn_flags |= ZEND_ACC_RETURN_REFERENCE; } } else { internal_function->arg_info = NULL; internal_function->num_args = 0; internal_function->required_num_args = 0; } if (ptr->flags & ZEND_ACC_ABSTRACT) { if (scope) { /* This is a class that must be abstract itself. Here we set the check info. */ scope->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; if (!(scope->ce_flags & ZEND_ACC_INTERFACE)) { /* Since the class is not an interface it needs to be declared as a abstract class. */ /* Since here we are handling internal functions only we can add the keyword flag. */ /* This time we set the flag for the keyword 'abstract'. */ scope->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } } if (ptr->flags & ZEND_ACC_STATIC && (!scope || !(scope->ce_flags & ZEND_ACC_INTERFACE))) { zend_error(error_type, "Static function %s%s%s() cannot be abstract", scope ? scope->name : "", scope ? "::" : "", ptr->fname); } } else { if (scope && (scope->ce_flags & ZEND_ACC_INTERFACE)) { efree((char*)lc_class_name); zend_error(error_type, "Interface %s cannot contain non abstract method %s()", scope->name, ptr->fname); return FAILURE; } if (!internal_function->handler) { if (scope) { efree((char*)lc_class_name); } zend_error(error_type, "Method %s%s%s() cannot be a NULL function", scope ? scope->name : "", scope ? "::" : "", ptr->fname); zend_unregister_functions(functions, count, target_function_table TSRMLS_CC); return FAILURE; } } fname_len = strlen(ptr->fname); lowercase_name = zend_new_interned_string(zend_str_tolower_dup(ptr->fname, fname_len), fname_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lowercase_name)) { result = zend_hash_quick_add(target_function_table, lowercase_name, fname_len+1, INTERNED_HASH(lowercase_name), &function, sizeof(zend_function), (void**)&reg_function); } else { result = zend_hash_add(target_function_table, lowercase_name, fname_len+1, &function, sizeof(zend_function), (void**)&reg_function); } if (result == FAILURE) { unload=1; str_efree(lowercase_name); break; } if (scope) { /* Look for ctor, dtor, clone * If it's an old-style constructor, store it only if we don't have * a constructor already. */ if ((fname_len == class_name_len) && !ctor && !memcmp(lowercase_name, lc_class_name, class_name_len+1)) { ctor = reg_function; } else if ((fname_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME))) { ctor = reg_function; } else if ((fname_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME))) { dtor = reg_function; if (internal_function->num_args) { zend_error(error_type, "Destructor %s::%s() cannot take arguments", scope->name, ptr->fname); } } else if ((fname_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME))) { clone = reg_function; } else if ((fname_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME))) { __call = reg_function; } else if ((fname_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME))) { __callstatic = reg_function; } else if ((fname_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME))) { __tostring = reg_function; } else if ((fname_len == sizeof(ZEND_GET_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME))) { __get = reg_function; } else if ((fname_len == sizeof(ZEND_SET_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME))) { __set = reg_function; } else if ((fname_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME))) { __unset = reg_function; } else if ((fname_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && !memcmp(lowercase_name, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME))) { __isset = reg_function; } else { reg_function = NULL; } if (reg_function) { zend_check_magic_method_implementation(scope, reg_function, error_type TSRMLS_CC); } } ptr++; count++; str_efree(lowercase_name); } if (unload) { /* before unloading, display all remaining bad function in the module */ if (scope) { efree((char*)lc_class_name); } while (ptr->fname) { fname_len = strlen(ptr->fname); lowercase_name = zend_str_tolower_dup(ptr->fname, fname_len); if (zend_hash_exists(target_function_table, lowercase_name, fname_len+1)) { zend_error(error_type, "Function registration failed - duplicate name - %s%s%s", scope ? scope->name : "", scope ? "::" : "", ptr->fname); } efree((char*)lowercase_name); ptr++; } zend_unregister_functions(functions, count, target_function_table TSRMLS_CC); return FAILURE; } if (scope) { scope->constructor = ctor; scope->destructor = dtor; scope->clone = clone; scope->__call = __call; scope->__callstatic = __callstatic; scope->__tostring = __tostring; scope->__get = __get; scope->__set = __set; scope->__unset = __unset; scope->__isset = __isset; if (ctor) { ctor->common.fn_flags |= ZEND_ACC_CTOR; if (ctor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Constructor %s::%s() cannot be static", scope->name, ctor->common.function_name); } ctor->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (dtor) { dtor->common.fn_flags |= ZEND_ACC_DTOR; if (dtor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Destructor %s::%s() cannot be static", scope->name, dtor->common.function_name); } dtor->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (clone) { clone->common.fn_flags |= ZEND_ACC_CLONE; if (clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Constructor %s::%s() cannot be static", scope->name, clone->common.function_name); } clone->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__call) { if (__call->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __call->common.function_name); } __call->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__callstatic) { if (!(__callstatic->common.fn_flags & ZEND_ACC_STATIC)) { zend_error(error_type, "Method %s::%s() must be static", scope->name, __callstatic->common.function_name); } __callstatic->common.fn_flags |= ZEND_ACC_STATIC; } if (__tostring) { if (__tostring->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __tostring->common.function_name); } __tostring->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__get) { if (__get->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __get->common.function_name); } __get->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__set) { if (__set->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __set->common.function_name); } __set->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__unset) { if (__unset->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __unset->common.function_name); } __unset->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } if (__isset) { if (__isset->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", scope->name, __isset->common.function_name); } __isset->common.fn_flags &= ~ZEND_ACC_ALLOW_STATIC; } efree((char*)lc_class_name); } return SUCCESS; } /* }}} */ /* count=-1 means erase all functions, otherwise, * erase the first count functions */ ZEND_API void zend_unregister_functions(const zend_function_entry *functions, int count, HashTable *function_table TSRMLS_DC) /* {{{ */ { const zend_function_entry *ptr = functions; int i=0; HashTable *target_function_table = function_table; if (!target_function_table) { target_function_table = CG(function_table); } while (ptr->fname) { if (count!=-1 && i>=count) { break; } #if 0 zend_printf("Unregistering %s()\n", ptr->fname); #endif zend_hash_del(target_function_table, ptr->fname, strlen(ptr->fname)+1); ptr++; i++; } } /* }}} */ ZEND_API int zend_startup_module(zend_module_entry *module) /* {{{ */ { TSRMLS_FETCH(); if ((module = zend_register_internal_module(module TSRMLS_CC)) != NULL && zend_startup_module_ex(module TSRMLS_CC) == SUCCESS) { return SUCCESS; } return FAILURE; } /* }}} */ ZEND_API int zend_get_module_started(const char *module_name) /* {{{ */ { zend_module_entry *module; return (zend_hash_find(&module_registry, module_name, strlen(module_name)+1, (void**)&module) == SUCCESS && module->module_started) ? SUCCESS : FAILURE; } /* }}} */ static int clean_module_class(const zend_class_entry **ce, int *module_number TSRMLS_DC) /* {{{ */ { if ((*ce)->type == ZEND_INTERNAL_CLASS && (*ce)->info.internal.module->module_number == *module_number) { return ZEND_HASH_APPLY_REMOVE; } else { return ZEND_HASH_APPLY_KEEP; } } /* }}} */ static void clean_module_classes(int module_number TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_argument(EG(class_table), (apply_func_arg_t) clean_module_class, (void *) &module_number TSRMLS_CC); } /* }}} */ void module_destructor(zend_module_entry *module) /* {{{ */ { TSRMLS_FETCH(); if (module->type == MODULE_TEMPORARY) { zend_clean_module_rsrc_dtors(module->module_number TSRMLS_CC); clean_module_constants(module->module_number TSRMLS_CC); clean_module_classes(module->module_number TSRMLS_CC); } if (module->module_started && module->module_shutdown_func) { #if 0 zend_printf("%s: Module shutdown\n", module->name); #endif module->module_shutdown_func(module->type, module->module_number TSRMLS_CC); } /* Deinitilaise module globals */ if (module->globals_size) { #ifdef ZTS ts_free_id(*module->globals_id_ptr); #else if (module->globals_dtor) { module->globals_dtor(module->globals_ptr TSRMLS_CC); } #endif } module->module_started=0; if (module->functions) { zend_unregister_functions(module->functions, -1, NULL TSRMLS_CC); } #if HAVE_LIBDL #if !(defined(NETWARE) && defined(APACHE_1_BUILD)) if (module->handle && !getenv("ZEND_DONT_UNLOAD_MODULES")) { DL_UNLOAD(module->handle); } #endif #endif } /* }}} */ void zend_activate_modules(TSRMLS_D) /* {{{ */ { zend_module_entry **p = module_request_startup_handlers; while (*p) { zend_module_entry *module = *p; if (module->request_startup_func(module->type, module->module_number TSRMLS_CC)==FAILURE) { zend_error(E_WARNING, "request_startup() for %s module failed", module->name); exit(1); } p++; } } /* }}} */ /* call request shutdown for all modules */ int module_registry_cleanup(zend_module_entry *module TSRMLS_DC) /* {{{ */ { if (module->request_shutdown_func) { #if 0 zend_printf("%s: Request shutdown\n", module->name); #endif module->request_shutdown_func(module->type, module->module_number TSRMLS_CC); } return 0; } /* }}} */ void zend_deactivate_modules(TSRMLS_D) /* {{{ */ { EG(opline_ptr) = NULL; /* we're no longer executing anything */ zend_try { if (EG(full_tables_cleanup)) { zend_hash_reverse_apply(&module_registry, (apply_func_t) module_registry_cleanup TSRMLS_CC); } else { zend_module_entry **p = module_request_shutdown_handlers; while (*p) { zend_module_entry *module = *p; module->request_shutdown_func(module->type, module->module_number TSRMLS_CC); p++; } } } zend_end_try(); } /* }}} */ ZEND_API void zend_cleanup_internal_classes(TSRMLS_D) /* {{{ */ { zend_class_entry **p = class_cleanup_handlers; while (*p) { zend_cleanup_internal_class_data(*p TSRMLS_CC); p++; } } /* }}} */ int module_registry_unload_temp(const zend_module_entry *module TSRMLS_DC) /* {{{ */ { return (module->type == MODULE_TEMPORARY) ? ZEND_HASH_APPLY_REMOVE : ZEND_HASH_APPLY_STOP; } /* }}} */ static int exec_done_cb(zend_module_entry *module TSRMLS_DC) /* {{{ */ { if (module->post_deactivate_func) { module->post_deactivate_func(); } return 0; } /* }}} */ void zend_post_deactivate_modules(TSRMLS_D) /* {{{ */ { if (EG(full_tables_cleanup)) { zend_hash_apply(&module_registry, (apply_func_t) exec_done_cb TSRMLS_CC); zend_hash_reverse_apply(&module_registry, (apply_func_t) module_registry_unload_temp TSRMLS_CC); } else { zend_module_entry **p = module_post_deactivate_handlers; while (*p) { zend_module_entry *module = *p; module->post_deactivate_func(); p++; } } } /* }}} */ /* return the next free module number */ int zend_next_free_module(void) /* {{{ */ { return ++module_count; } /* }}} */ static zend_class_entry *do_register_internal_class(zend_class_entry *orig_class_entry, zend_uint ce_flags TSRMLS_DC) /* {{{ */ { zend_class_entry *class_entry = malloc(sizeof(zend_class_entry)); char *lowercase_name = emalloc(orig_class_entry->name_length + 1); *class_entry = *orig_class_entry; class_entry->type = ZEND_INTERNAL_CLASS; zend_initialize_class_data(class_entry, 0 TSRMLS_CC); class_entry->ce_flags = ce_flags; class_entry->info.internal.module = EG(current_module); if (class_entry->info.internal.builtin_functions) { zend_register_functions(class_entry, class_entry->info.internal.builtin_functions, &class_entry->function_table, MODULE_PERSISTENT TSRMLS_CC); } zend_str_tolower_copy(lowercase_name, orig_class_entry->name, class_entry->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, class_entry->name_length + 1, 1 TSRMLS_CC); if (IS_INTERNED(lowercase_name)) { zend_hash_quick_update(CG(class_table), lowercase_name, class_entry->name_length+1, INTERNED_HASH(lowercase_name), &class_entry, sizeof(zend_class_entry *), NULL); } else { zend_hash_update(CG(class_table), lowercase_name, class_entry->name_length+1, &class_entry, sizeof(zend_class_entry *), NULL); } str_efree(lowercase_name); return class_entry; } /* }}} */ /* If parent_ce is not NULL then it inherits from parent_ce * If parent_ce is NULL and parent_name isn't then it looks for the parent and inherits from it * If both parent_ce and parent_name are NULL it does a regular class registration * If parent_name is specified but not found NULL is returned */ ZEND_API zend_class_entry *zend_register_internal_class_ex(zend_class_entry *class_entry, zend_class_entry *parent_ce, char *parent_name TSRMLS_DC) /* {{{ */ { zend_class_entry *register_class; if (!parent_ce && parent_name) { zend_class_entry **pce; if (zend_hash_find(CG(class_table), parent_name, strlen(parent_name)+1, (void **) &pce)==FAILURE) { return NULL; } else { parent_ce = *pce; } } register_class = zend_register_internal_class(class_entry TSRMLS_CC); if (parent_ce) { zend_do_inheritance(register_class, parent_ce TSRMLS_CC); } return register_class; } /* }}} */ ZEND_API void zend_class_implements(zend_class_entry *class_entry TSRMLS_DC, int num_interfaces, ...) /* {{{ */ { zend_class_entry *interface_entry; va_list interface_list; va_start(interface_list, num_interfaces); while (num_interfaces--) { interface_entry = va_arg(interface_list, zend_class_entry *); zend_do_implement_interface(class_entry, interface_entry TSRMLS_CC); } va_end(interface_list); } /* }}} */ /* A class that contains at least one abstract method automatically becomes an abstract class. */ ZEND_API zend_class_entry *zend_register_internal_class(zend_class_entry *orig_class_entry TSRMLS_DC) /* {{{ */ { return do_register_internal_class(orig_class_entry, 0 TSRMLS_CC); } /* }}} */ ZEND_API zend_class_entry *zend_register_internal_interface(zend_class_entry *orig_class_entry TSRMLS_DC) /* {{{ */ { return do_register_internal_class(orig_class_entry, ZEND_ACC_INTERFACE TSRMLS_CC); } /* }}} */ ZEND_API int zend_register_class_alias_ex(const char *name, int name_len, zend_class_entry *ce TSRMLS_DC) /* {{{ */ { char *lcname = zend_str_tolower_dup(name, name_len); int ret; ret = zend_hash_add(CG(class_table), lcname, name_len+1, &ce, sizeof(zend_class_entry *), NULL); efree(lcname); if (ret == SUCCESS) { ce->refcount++; } return ret; } /* }}} */ ZEND_API int zend_set_hash_symbol(zval *symbol, const char *name, int name_length, zend_bool is_ref, int num_symbol_tables, ...) /* {{{ */ { HashTable *symbol_table; va_list symbol_table_list; if (num_symbol_tables <= 0) return FAILURE; Z_SET_ISREF_TO_P(symbol, is_ref); va_start(symbol_table_list, num_symbol_tables); while (num_symbol_tables-- > 0) { symbol_table = va_arg(symbol_table_list, HashTable *); zend_hash_update(symbol_table, name, name_length + 1, &symbol, sizeof(zval *), NULL); zval_add_ref(&symbol); } va_end(symbol_table_list); return SUCCESS; } /* }}} */ /* Disabled functions support */ /* {{{ proto void display_disabled_function(void) Dummy function which displays an error when a disabled function is called. */ ZEND_API ZEND_FUNCTION(display_disabled_function) { zend_error(E_WARNING, "%s() has been disabled for security reasons", get_active_function_name(TSRMLS_C)); } /* }}} */ static zend_function_entry disabled_function[] = { ZEND_FE(display_disabled_function, NULL) ZEND_FE_END }; ZEND_API int zend_disable_function(char *function_name, uint function_name_length TSRMLS_DC) /* {{{ */ { if (zend_hash_del(CG(function_table), function_name, function_name_length+1)==FAILURE) { return FAILURE; } disabled_function[0].fname = function_name; return zend_register_functions(NULL, disabled_function, CG(function_table), MODULE_PERSISTENT TSRMLS_CC); } /* }}} */ static zend_object_value display_disabled_class(zend_class_entry *class_type TSRMLS_DC) /* {{{ */ { zend_object_value retval; zend_object *intern; retval = zend_objects_new(&intern, class_type TSRMLS_CC); zend_error(E_WARNING, "%s() has been disabled for security reasons", class_type->name); return retval; } /* }}} */ static const zend_function_entry disabled_class_new[] = { ZEND_FE_END }; ZEND_API int zend_disable_class(char *class_name, uint class_name_length TSRMLS_DC) /* {{{ */ { zend_class_entry disabled_class; zend_str_tolower(class_name, class_name_length); if (zend_hash_del(CG(class_table), class_name, class_name_length+1)==FAILURE) { return FAILURE; } INIT_OVERLOADED_CLASS_ENTRY_EX(disabled_class, class_name, class_name_length, disabled_class_new, NULL, NULL, NULL, NULL, NULL); disabled_class.create_object = display_disabled_class; disabled_class.name_length = class_name_length; zend_register_internal_class(&disabled_class TSRMLS_CC); return SUCCESS; } /* }}} */ static int zend_is_callable_check_class(const char *name, int name_len, zend_fcall_info_cache *fcc, int *strict_class, char **error TSRMLS_DC) /* {{{ */ { int ret = 0; zend_class_entry **pce; char *lcname = zend_str_tolower_dup(name, name_len); *strict_class = 0; if (name_len == sizeof("self") - 1 && !memcmp(lcname, "self", sizeof("self") - 1)) { if (!EG(scope)) { if (error) *error = estrdup("cannot access self:: when no class scope is active"); } else { fcc->called_scope = EG(called_scope); fcc->calling_scope = EG(scope); if (!fcc->object_ptr) { fcc->object_ptr = EG(This); } ret = 1; } } else if (name_len == sizeof("parent") - 1 && !memcmp(lcname, "parent", sizeof("parent") - 1)) { if (!EG(scope)) { if (error) *error = estrdup("cannot access parent:: when no class scope is active"); } else if (!EG(scope)->parent) { if (error) *error = estrdup("cannot access parent:: when current class scope has no parent"); } else { fcc->called_scope = EG(called_scope); fcc->calling_scope = EG(scope)->parent; if (!fcc->object_ptr) { fcc->object_ptr = EG(This); } *strict_class = 1; ret = 1; } } else if (name_len == sizeof("static") - 1 && !memcmp(lcname, "static", sizeof("static") - 1)) { if (!EG(called_scope)) { if (error) *error = estrdup("cannot access static:: when no class scope is active"); } else { fcc->called_scope = EG(called_scope); fcc->calling_scope = EG(called_scope); if (!fcc->object_ptr) { fcc->object_ptr = EG(This); } *strict_class = 1; ret = 1; } } else if (zend_lookup_class_ex(name, name_len, NULL, 1, &pce TSRMLS_CC) == SUCCESS) { zend_class_entry *scope = EG(active_op_array) ? EG(active_op_array)->scope : NULL; fcc->calling_scope = *pce; if (scope && !fcc->object_ptr && EG(This) && instanceof_function(Z_OBJCE_P(EG(This)), scope TSRMLS_CC) && instanceof_function(scope, fcc->calling_scope TSRMLS_CC)) { fcc->object_ptr = EG(This); fcc->called_scope = Z_OBJCE_P(fcc->object_ptr); } else { fcc->called_scope = fcc->object_ptr ? Z_OBJCE_P(fcc->object_ptr) : fcc->calling_scope; } *strict_class = 1; ret = 1; } else { if (error) zend_spprintf(error, 0, "class '%.*s' not found", name_len, name); } efree(lcname); return ret; } /* }}} */ static int zend_is_callable_check_func(int check_flags, zval *callable, zend_fcall_info_cache *fcc, int strict_class, char **error TSRMLS_DC) /* {{{ */ { zend_class_entry *ce_org = fcc->calling_scope; int retval = 0; char *mname, *lmname; const char *colon; int clen, mlen; zend_class_entry *last_scope; HashTable *ftable; int call_via_handler = 0; if (error) { *error = NULL; } fcc->calling_scope = NULL; fcc->function_handler = NULL; if (!ce_org) { /* Skip leading \ */ if (Z_STRVAL_P(callable)[0] == '\\') { mlen = Z_STRLEN_P(callable) - 1; mname = Z_STRVAL_P(callable) + 1; lmname = zend_str_tolower_dup(Z_STRVAL_P(callable) + 1, mlen); } else { mlen = Z_STRLEN_P(callable); mname = Z_STRVAL_P(callable); lmname = zend_str_tolower_dup(Z_STRVAL_P(callable), mlen); } /* Check if function with given name exists. * This may be a compound name that includes namespace name */ if (zend_hash_find(EG(function_table), lmname, mlen+1, (void**)&fcc->function_handler) == SUCCESS) { efree(lmname); return 1; } efree(lmname); } /* Split name into class/namespace and method/function names */ if ((colon = zend_memrchr(Z_STRVAL_P(callable), ':', Z_STRLEN_P(callable))) != NULL && colon > Z_STRVAL_P(callable) && *(colon-1) == ':' ) { colon--; clen = colon - Z_STRVAL_P(callable); mlen = Z_STRLEN_P(callable) - clen - 2; if (colon == Z_STRVAL_P(callable)) { if (error) zend_spprintf(error, 0, "invalid function name"); return 0; } /* This is a compound name. * Try to fetch class and then find static method. */ last_scope = EG(scope); if (ce_org) { EG(scope) = ce_org; } if (!zend_is_callable_check_class(Z_STRVAL_P(callable), clen, fcc, &strict_class, error TSRMLS_CC)) { EG(scope) = last_scope; return 0; } EG(scope) = last_scope; ftable = &fcc->calling_scope->function_table; if (ce_org && !instanceof_function(ce_org, fcc->calling_scope TSRMLS_CC)) { if (error) zend_spprintf(error, 0, "class '%s' is not a subclass of '%s'", ce_org->name, fcc->calling_scope->name); return 0; } mname = Z_STRVAL_P(callable) + clen + 2; } else if (ce_org) { /* Try to fetch find static method of given class. */ mlen = Z_STRLEN_P(callable); mname = Z_STRVAL_P(callable); ftable = &ce_org->function_table; fcc->calling_scope = ce_org; } else { /* We already checked for plain function before. */ if (error && !(check_flags & IS_CALLABLE_CHECK_SILENT)) { zend_spprintf(error, 0, "function '%s' not found or invalid function name", Z_STRVAL_P(callable)); } return 0; } lmname = zend_str_tolower_dup(mname, mlen); if (strict_class && fcc->calling_scope && mlen == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1 && !memcmp(lmname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME))) { fcc->function_handler = fcc->calling_scope->constructor; if (fcc->function_handler) { retval = 1; } } else if (zend_hash_find(ftable, lmname, mlen+1, (void**)&fcc->function_handler) == SUCCESS) { retval = 1; if ((fcc->function_handler->op_array.fn_flags & ZEND_ACC_CHANGED) && EG(scope) && instanceof_function(fcc->function_handler->common.scope, EG(scope) TSRMLS_CC)) { zend_function *priv_fbc; if (zend_hash_find(&EG(scope)->function_table, lmname, mlen+1, (void **) &priv_fbc)==SUCCESS && priv_fbc->common.fn_flags & ZEND_ACC_PRIVATE && priv_fbc->common.scope == EG(scope)) { fcc->function_handler = priv_fbc; } } if ((check_flags & IS_CALLABLE_CHECK_NO_ACCESS) == 0 && (fcc->calling_scope && (fcc->calling_scope->__call || fcc->calling_scope->__callstatic))) { if (fcc->function_handler->op_array.fn_flags & ZEND_ACC_PRIVATE) { if (!zend_check_private(fcc->function_handler, fcc->object_ptr ? Z_OBJCE_P(fcc->object_ptr) : EG(scope), lmname, mlen TSRMLS_CC)) { retval = 0; fcc->function_handler = NULL; goto get_function_via_handler; } } else if (fcc->function_handler->common.fn_flags & ZEND_ACC_PROTECTED) { if (!zend_check_protected(fcc->function_handler->common.scope, EG(scope))) { retval = 0; fcc->function_handler = NULL; goto get_function_via_handler; } } } } else { get_function_via_handler: if (fcc->object_ptr && fcc->calling_scope == ce_org) { if (strict_class && ce_org->__call) { fcc->function_handler = emalloc(sizeof(zend_internal_function)); fcc->function_handler->internal_function.type = ZEND_INTERNAL_FUNCTION; fcc->function_handler->internal_function.module = (ce_org->type == ZEND_INTERNAL_CLASS) ? ce_org->info.internal.module : NULL; fcc->function_handler->internal_function.handler = zend_std_call_user_call; fcc->function_handler->internal_function.arg_info = NULL; fcc->function_handler->internal_function.num_args = 0; fcc->function_handler->internal_function.scope = ce_org; fcc->function_handler->internal_function.fn_flags = ZEND_ACC_CALL_VIA_HANDLER; fcc->function_handler->internal_function.function_name = estrndup(mname, mlen); call_via_handler = 1; retval = 1; } else if (Z_OBJ_HT_P(fcc->object_ptr)->get_method) { fcc->function_handler = Z_OBJ_HT_P(fcc->object_ptr)->get_method(&fcc->object_ptr, mname, mlen, NULL TSRMLS_CC); if (fcc->function_handler) { if (strict_class && (!fcc->function_handler->common.scope || !instanceof_function(ce_org, fcc->function_handler->common.scope TSRMLS_CC))) { if ((fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) != 0) { if (fcc->function_handler->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fcc->function_handler->common.function_name); } efree(fcc->function_handler); } } else { retval = 1; call_via_handler = (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) != 0; } } } } else if (fcc->calling_scope) { if (fcc->calling_scope->get_static_method) { fcc->function_handler = fcc->calling_scope->get_static_method(fcc->calling_scope, mname, mlen TSRMLS_CC); } else { fcc->function_handler = zend_std_get_static_method(fcc->calling_scope, mname, mlen, NULL TSRMLS_CC); } if (fcc->function_handler) { retval = 1; call_via_handler = (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) != 0; if (call_via_handler && !fcc->object_ptr && EG(This) && Z_OBJ_HT_P(EG(This))->get_class_entry && instanceof_function(Z_OBJCE_P(EG(This)), fcc->calling_scope TSRMLS_CC)) { fcc->object_ptr = EG(This); } } } } if (retval) { if (fcc->calling_scope && !call_via_handler) { if (!fcc->object_ptr && !(fcc->function_handler->common.fn_flags & ZEND_ACC_STATIC)) { int severity; char *verb; if (fcc->function_handler->common.fn_flags & ZEND_ACC_ALLOW_STATIC) { severity = E_STRICT; verb = "should not"; } else { /* An internal function assumes $this is present and won't check that. So PHP would crash by allowing the call. */ severity = E_ERROR; verb = "cannot"; } if ((check_flags & IS_CALLABLE_CHECK_IS_STATIC) != 0) { retval = 0; } if (EG(This) && instanceof_function(Z_OBJCE_P(EG(This)), fcc->calling_scope TSRMLS_CC)) { fcc->object_ptr = EG(This); if (error) { zend_spprintf(error, 0, "non-static method %s::%s() %s be called statically, assuming $this from compatible context %s", fcc->calling_scope->name, fcc->function_handler->common.function_name, verb, Z_OBJCE_P(EG(This))->name); if (severity == E_ERROR) { retval = 0; } } else if (retval) { zend_error(severity, "Non-static method %s::%s() %s be called statically, assuming $this from compatible context %s", fcc->calling_scope->name, fcc->function_handler->common.function_name, verb, Z_OBJCE_P(EG(This))->name); } } else { if (error) { zend_spprintf(error, 0, "non-static method %s::%s() %s be called statically", fcc->calling_scope->name, fcc->function_handler->common.function_name, verb); if (severity == E_ERROR) { retval = 0; } } else if (retval) { zend_error(severity, "Non-static method %s::%s() %s be called statically", fcc->calling_scope->name, fcc->function_handler->common.function_name, verb); } } } if (retval && (check_flags & IS_CALLABLE_CHECK_NO_ACCESS) == 0) { if (fcc->function_handler->op_array.fn_flags & ZEND_ACC_PRIVATE) { if (!zend_check_private(fcc->function_handler, fcc->object_ptr ? Z_OBJCE_P(fcc->object_ptr) : EG(scope), lmname, mlen TSRMLS_CC)) { if (error) { if (*error) { efree(*error); } zend_spprintf(error, 0, "cannot access private method %s::%s()", fcc->calling_scope->name, fcc->function_handler->common.function_name); } retval = 0; } } else if ((fcc->function_handler->common.fn_flags & ZEND_ACC_PROTECTED)) { if (!zend_check_protected(fcc->function_handler->common.scope, EG(scope))) { if (error) { if (*error) { efree(*error); } zend_spprintf(error, 0, "cannot access protected method %s::%s()", fcc->calling_scope->name, fcc->function_handler->common.function_name); } retval = 0; } } } } } else if (error && !(check_flags & IS_CALLABLE_CHECK_SILENT)) { if (fcc->calling_scope) { if (error) zend_spprintf(error, 0, "class '%s' does not have a method '%s'", fcc->calling_scope->name, mname); } else { if (error) zend_spprintf(error, 0, "function '%s' does not exist", mname); } } efree(lmname); if (fcc->object_ptr) { fcc->called_scope = Z_OBJCE_P(fcc->object_ptr); } if (retval) { fcc->initialized = 1; } return retval; } /* }}} */ ZEND_API zend_bool zend_is_callable_ex(zval *callable, zval *object_ptr, uint check_flags, char **callable_name, int *callable_name_len, zend_fcall_info_cache *fcc, char **error TSRMLS_DC) /* {{{ */ { zend_bool ret; int callable_name_len_local; zend_fcall_info_cache fcc_local; if (callable_name) { *callable_name = NULL; } if (callable_name_len == NULL) { callable_name_len = &callable_name_len_local; } if (fcc == NULL) { fcc = &fcc_local; } if (error) { *error = NULL; } fcc->initialized = 0; fcc->calling_scope = NULL; fcc->called_scope = NULL; fcc->function_handler = NULL; fcc->calling_scope = NULL; fcc->object_ptr = NULL; if (object_ptr && Z_TYPE_P(object_ptr) != IS_OBJECT) { object_ptr = NULL; } if (object_ptr && (!EG(objects_store).object_buckets || !EG(objects_store).object_buckets[Z_OBJ_HANDLE_P(object_ptr)].valid)) { return 0; } switch (Z_TYPE_P(callable)) { case IS_STRING: if (object_ptr) { fcc->object_ptr = object_ptr; fcc->calling_scope = Z_OBJCE_P(object_ptr); if (callable_name) { char *ptr; *callable_name_len = fcc->calling_scope->name_length + Z_STRLEN_P(callable) + sizeof("::") - 1; ptr = *callable_name = emalloc(*callable_name_len + 1); memcpy(ptr, fcc->calling_scope->name, fcc->calling_scope->name_length); ptr += fcc->calling_scope->name_length; memcpy(ptr, "::", sizeof("::") - 1); ptr += sizeof("::") - 1; memcpy(ptr, Z_STRVAL_P(callable), Z_STRLEN_P(callable) + 1); } } else if (callable_name) { *callable_name = estrndup(Z_STRVAL_P(callable), Z_STRLEN_P(callable)); *callable_name_len = Z_STRLEN_P(callable); } if (check_flags & IS_CALLABLE_CHECK_SYNTAX_ONLY) { fcc->called_scope = fcc->calling_scope; return 1; } ret = zend_is_callable_check_func(check_flags, callable, fcc, 0, error TSRMLS_CC); if (fcc == &fcc_local && fcc->function_handler && ((fcc->function_handler->type == ZEND_INTERNAL_FUNCTION && (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER)) || fcc->function_handler->type == ZEND_OVERLOADED_FUNCTION_TEMPORARY || fcc->function_handler->type == ZEND_OVERLOADED_FUNCTION)) { if (fcc->function_handler->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fcc->function_handler->common.function_name); } efree(fcc->function_handler); } return ret; case IS_ARRAY: { zval **method = NULL; zval **obj = NULL; int strict_class = 0; if (zend_hash_num_elements(Z_ARRVAL_P(callable)) == 2) { zend_hash_index_find(Z_ARRVAL_P(callable), 0, (void **) &obj); zend_hash_index_find(Z_ARRVAL_P(callable), 1, (void **) &method); } if (obj && method && (Z_TYPE_PP(obj) == IS_OBJECT || Z_TYPE_PP(obj) == IS_STRING) && Z_TYPE_PP(method) == IS_STRING) { if (Z_TYPE_PP(obj) == IS_STRING) { if (callable_name) { char *ptr; *callable_name_len = Z_STRLEN_PP(obj) + Z_STRLEN_PP(method) + sizeof("::") - 1; ptr = *callable_name = emalloc(*callable_name_len + 1); memcpy(ptr, Z_STRVAL_PP(obj), Z_STRLEN_PP(obj)); ptr += Z_STRLEN_PP(obj); memcpy(ptr, "::", sizeof("::") - 1); ptr += sizeof("::") - 1; memcpy(ptr, Z_STRVAL_PP(method), Z_STRLEN_PP(method) + 1); } if (check_flags & IS_CALLABLE_CHECK_SYNTAX_ONLY) { return 1; } if (!zend_is_callable_check_class(Z_STRVAL_PP(obj), Z_STRLEN_PP(obj), fcc, &strict_class, error TSRMLS_CC)) { return 0; } } else { if (!EG(objects_store).object_buckets || !EG(objects_store).object_buckets[Z_OBJ_HANDLE_PP(obj)].valid) { return 0; } fcc->calling_scope = Z_OBJCE_PP(obj); /* TBFixed: what if it's overloaded? */ fcc->object_ptr = *obj; if (callable_name) { char *ptr; *callable_name_len = fcc->calling_scope->name_length + Z_STRLEN_PP(method) + sizeof("::") - 1; ptr = *callable_name = emalloc(*callable_name_len + 1); memcpy(ptr, fcc->calling_scope->name, fcc->calling_scope->name_length); ptr += fcc->calling_scope->name_length; memcpy(ptr, "::", sizeof("::") - 1); ptr += sizeof("::") - 1; memcpy(ptr, Z_STRVAL_PP(method), Z_STRLEN_PP(method) + 1); } if (check_flags & IS_CALLABLE_CHECK_SYNTAX_ONLY) { fcc->called_scope = fcc->calling_scope; return 1; } } ret = zend_is_callable_check_func(check_flags, *method, fcc, strict_class, error TSRMLS_CC); if (fcc == &fcc_local && fcc->function_handler && ((fcc->function_handler->type == ZEND_INTERNAL_FUNCTION && (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER)) || fcc->function_handler->type == ZEND_OVERLOADED_FUNCTION_TEMPORARY || fcc->function_handler->type == ZEND_OVERLOADED_FUNCTION)) { if (fcc->function_handler->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fcc->function_handler->common.function_name); } efree(fcc->function_handler); } return ret; } else { if (zend_hash_num_elements(Z_ARRVAL_P(callable)) == 2) { if (!obj || (Z_TYPE_PP(obj) != IS_STRING && Z_TYPE_PP(obj) != IS_OBJECT)) { if (error) zend_spprintf(error, 0, "first array member is not a valid class name or object"); } else { if (error) zend_spprintf(error, 0, "second array member is not a valid method"); } } else { if (error) zend_spprintf(error, 0, "array must have exactly two members"); } if (callable_name) { *callable_name = estrndup("Array", sizeof("Array")-1); *callable_name_len = sizeof("Array") - 1; } } } return 0; case IS_OBJECT: if (Z_OBJ_HANDLER_P(callable, get_closure) && Z_OBJ_HANDLER_P(callable, get_closure)(callable, &fcc->calling_scope, &fcc->function_handler, &fcc->object_ptr TSRMLS_CC) == SUCCESS) { fcc->called_scope = fcc->calling_scope; if (callable_name) { zend_class_entry *ce = Z_OBJCE_P(callable); /* TBFixed: what if it's overloaded? */ *callable_name_len = ce->name_length + sizeof("::__invoke") - 1; *callable_name = emalloc(*callable_name_len + 1); memcpy(*callable_name, ce->name, ce->name_length); memcpy((*callable_name) + ce->name_length, "::__invoke", sizeof("::__invoke")); } return 1; } /* break missing intentionally */ default: if (callable_name) { zval expr_copy; int use_copy; zend_make_printable_zval(callable, &expr_copy, &use_copy); *callable_name = estrndup(Z_STRVAL(expr_copy), Z_STRLEN(expr_copy)); *callable_name_len = Z_STRLEN(expr_copy); zval_dtor(&expr_copy); } if (error) zend_spprintf(error, 0, "no array or string given"); return 0; } } /* }}} */ ZEND_API zend_bool zend_is_callable(zval *callable, uint check_flags, char **callable_name TSRMLS_DC) /* {{{ */ { return zend_is_callable_ex(callable, NULL, check_flags, callable_name, NULL, NULL, NULL TSRMLS_CC); } /* }}} */ ZEND_API zend_bool zend_make_callable(zval *callable, char **callable_name TSRMLS_DC) /* {{{ */ { zend_fcall_info_cache fcc; if (zend_is_callable_ex(callable, NULL, IS_CALLABLE_STRICT, callable_name, NULL, &fcc, NULL TSRMLS_CC)) { if (Z_TYPE_P(callable) == IS_STRING && fcc.calling_scope) { zval_dtor(callable); array_init(callable); add_next_index_string(callable, fcc.calling_scope->name, 1); add_next_index_string(callable, fcc.function_handler->common.function_name, 1); } if (fcc.function_handler && ((fcc.function_handler->type == ZEND_INTERNAL_FUNCTION && (fcc.function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER)) || fcc.function_handler->type == ZEND_OVERLOADED_FUNCTION_TEMPORARY || fcc.function_handler->type == ZEND_OVERLOADED_FUNCTION)) { if (fcc.function_handler->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fcc.function_handler->common.function_name); } efree(fcc.function_handler); } return 1; } return 0; } /* }}} */ ZEND_API int zend_fcall_info_init(zval *callable, uint check_flags, zend_fcall_info *fci, zend_fcall_info_cache *fcc, char **callable_name, char **error TSRMLS_DC) /* {{{ */ { if (!zend_is_callable_ex(callable, NULL, check_flags, callable_name, NULL, fcc, error TSRMLS_CC)) { return FAILURE; } fci->size = sizeof(*fci); fci->function_table = fcc->calling_scope ? &fcc->calling_scope->function_table : EG(function_table); fci->object_ptr = fcc->object_ptr; fci->function_name = callable; fci->retval_ptr_ptr = NULL; fci->param_count = 0; fci->params = NULL; fci->no_separation = 1; fci->symbol_table = NULL; return SUCCESS; } /* }}} */ ZEND_API void zend_fcall_info_args_clear(zend_fcall_info *fci, int free_mem) /* {{{ */ { if (fci->params) { if (free_mem) { efree(fci->params); fci->params = NULL; } } fci->param_count = 0; } /* }}} */ ZEND_API void zend_fcall_info_args_save(zend_fcall_info *fci, int *param_count, zval ****params) /* {{{ */ { *param_count = fci->param_count; *params = fci->params; fci->param_count = 0; fci->params = NULL; } /* }}} */ ZEND_API void zend_fcall_info_args_restore(zend_fcall_info *fci, int param_count, zval ***params) /* {{{ */ { zend_fcall_info_args_clear(fci, 1); fci->param_count = param_count; fci->params = params; } /* }}} */ ZEND_API int zend_fcall_info_args(zend_fcall_info *fci, zval *args TSRMLS_DC) /* {{{ */ { HashPosition pos; zval **arg, ***params; zend_fcall_info_args_clear(fci, !args); if (!args) { return SUCCESS; } if (Z_TYPE_P(args) != IS_ARRAY) { return FAILURE; } fci->param_count = zend_hash_num_elements(Z_ARRVAL_P(args)); fci->params = params = (zval ***) erealloc(fci->params, fci->param_count * sizeof(zval **)); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(args), &pos); while (zend_hash_get_current_data_ex(Z_ARRVAL_P(args), (void *) &arg, &pos) == SUCCESS) { *params++ = arg; zend_hash_move_forward_ex(Z_ARRVAL_P(args), &pos); } return SUCCESS; } /* }}} */ ZEND_API int zend_fcall_info_argp(zend_fcall_info *fci TSRMLS_DC, int argc, zval ***argv) /* {{{ */ { int i; if (argc < 0) { return FAILURE; } zend_fcall_info_args_clear(fci, !argc); if (argc) { fci->param_count = argc; fci->params = (zval ***) erealloc(fci->params, fci->param_count * sizeof(zval **)); for (i = 0; i < argc; ++i) { fci->params[i] = argv[i]; } } return SUCCESS; } /* }}} */ ZEND_API int zend_fcall_info_argv(zend_fcall_info *fci TSRMLS_DC, int argc, va_list *argv) /* {{{ */ { int i; zval **arg; if (argc < 0) { return FAILURE; } zend_fcall_info_args_clear(fci, !argc); if (argc) { fci->param_count = argc; fci->params = (zval ***) erealloc(fci->params, fci->param_count * sizeof(zval **)); for (i = 0; i < argc; ++i) { arg = va_arg(*argv, zval **); fci->params[i] = arg; } } return SUCCESS; } /* }}} */ ZEND_API int zend_fcall_info_argn(zend_fcall_info *fci TSRMLS_DC, int argc, ...) /* {{{ */ { int ret; va_list argv; va_start(argv, argc); ret = zend_fcall_info_argv(fci TSRMLS_CC, argc, &argv); va_end(argv); return ret; } /* }}} */ ZEND_API int zend_fcall_info_call(zend_fcall_info *fci, zend_fcall_info_cache *fcc, zval **retval_ptr_ptr, zval *args TSRMLS_DC) /* {{{ */ { zval *retval, ***org_params = NULL; int result, org_count = 0; fci->retval_ptr_ptr = retval_ptr_ptr ? retval_ptr_ptr : &retval; if (args) { zend_fcall_info_args_save(fci, &org_count, &org_params); zend_fcall_info_args(fci, args TSRMLS_CC); } result = zend_call_function(fci, fcc TSRMLS_CC); if (!retval_ptr_ptr && retval) { zval_ptr_dtor(&retval); } if (args) { zend_fcall_info_args_restore(fci, org_count, org_params); } return result; } /* }}} */ ZEND_API const char *zend_get_module_version(const char *module_name) /* {{{ */ { char *lname; int name_len = strlen(module_name); zend_module_entry *module; lname = zend_str_tolower_dup(module_name, name_len); if (zend_hash_find(&module_registry, lname, name_len + 1, (void**)&module) == FAILURE) { efree(lname); return NULL; } efree(lname); return module->version; } /* }}} */ ZEND_API int zend_declare_property_ex(zend_class_entry *ce, const char *name, int name_length, zval *property, int access_type, const char *doc_comment, int doc_comment_len TSRMLS_DC) /* {{{ */ { zend_property_info property_info, *property_info_ptr; const char *interned_name; ulong h = zend_get_hash_value(name, name_length+1); if (!(access_type & ZEND_ACC_PPP_MASK)) { access_type |= ZEND_ACC_PUBLIC; } if (access_type & ZEND_ACC_STATIC) { if (zend_hash_quick_find(&ce->properties_info, name, name_length + 1, h, (void**)&property_info_ptr) == SUCCESS && (property_info_ptr->flags & ZEND_ACC_STATIC) != 0) { property_info.offset = property_info_ptr->offset; zval_ptr_dtor(&ce->default_static_members_table[property_info.offset]); zend_hash_quick_del(&ce->properties_info, name, name_length + 1, h); } else { property_info.offset = ce->default_static_members_count++; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(zval*) * ce->default_static_members_count, ce->type == ZEND_INTERNAL_CLASS); } ce->default_static_members_table[property_info.offset] = property; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } else { if (zend_hash_quick_find(&ce->properties_info, name, name_length + 1, h, (void**)&property_info_ptr) == SUCCESS && (property_info_ptr->flags & ZEND_ACC_STATIC) == 0) { property_info.offset = property_info_ptr->offset; zval_ptr_dtor(&ce->default_properties_table[property_info.offset]); zend_hash_quick_del(&ce->properties_info, name, name_length + 1, h); } else { property_info.offset = ce->default_properties_count++; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(zval*) * ce->default_properties_count, ce->type == ZEND_INTERNAL_CLASS); } ce->default_properties_table[property_info.offset] = property; } if (ce->type & ZEND_INTERNAL_CLASS) { switch(Z_TYPE_P(property)) { case IS_ARRAY: case IS_CONSTANT_ARRAY: case IS_OBJECT: case IS_RESOURCE: zend_error(E_CORE_ERROR, "Internal zval's can't be arrays, objects or resources"); break; default: break; } } switch (access_type & ZEND_ACC_PPP_MASK) { case ZEND_ACC_PRIVATE: { char *priv_name; int priv_name_length; zend_mangle_property_name(&priv_name, &priv_name_length, ce->name, ce->name_length, name, name_length, ce->type & ZEND_INTERNAL_CLASS); property_info.name = priv_name; property_info.name_length = priv_name_length; } break; case ZEND_ACC_PROTECTED: { char *prot_name; int prot_name_length; zend_mangle_property_name(&prot_name, &prot_name_length, "*", 1, name, name_length, ce->type & ZEND_INTERNAL_CLASS); property_info.name = prot_name; property_info.name_length = prot_name_length; } break; case ZEND_ACC_PUBLIC: if (IS_INTERNED(name)) { property_info.name = (char*)name; } else { property_info.name = ce->type & ZEND_INTERNAL_CLASS ? zend_strndup(name, name_length) : estrndup(name, name_length); } property_info.name_length = name_length; break; } interned_name = zend_new_interned_string(property_info.name, property_info.name_length+1, 0 TSRMLS_CC); if (interned_name != property_info.name) { if (ce->type == ZEND_USER_CLASS) { efree((char*)property_info.name); } else { free((char*)property_info.name); } property_info.name = interned_name; } property_info.flags = access_type; property_info.h = (access_type & ZEND_ACC_PUBLIC) ? h : zend_get_hash_value(property_info.name, property_info.name_length+1); property_info.doc_comment = doc_comment; property_info.doc_comment_len = doc_comment_len; property_info.ce = ce; zend_hash_quick_update(&ce->properties_info, name, name_length+1, h, &property_info, sizeof(zend_property_info), NULL); return SUCCESS; } /* }}} */ ZEND_API int zend_declare_property(zend_class_entry *ce, const char *name, int name_length, zval *property, int access_type TSRMLS_DC) /* {{{ */ { return zend_declare_property_ex(ce, name, name_length, property, access_type, NULL, 0 TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_null(zend_class_entry *ce, const char *name, int name_length, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); } else { ALLOC_ZVAL(property); } INIT_ZVAL(*property); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_bool(zend_class_entry *ce, const char *name, int name_length, long value, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); } else { ALLOC_ZVAL(property); } INIT_PZVAL(property); ZVAL_BOOL(property, value); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_long(zend_class_entry *ce, const char *name, int name_length, long value, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); } else { ALLOC_ZVAL(property); } INIT_PZVAL(property); ZVAL_LONG(property, value); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_double(zend_class_entry *ce, const char *name, int name_length, double value, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); } else { ALLOC_ZVAL(property); } INIT_PZVAL(property); ZVAL_DOUBLE(property, value); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_string(zend_class_entry *ce, const char *name, int name_length, const char *value, int access_type TSRMLS_DC) /* {{{ */ { zval *property; int len = strlen(value); if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); ZVAL_STRINGL(property, zend_strndup(value, len), len, 0); } else { ALLOC_ZVAL(property); ZVAL_STRINGL(property, value, len, 1); } INIT_PZVAL(property); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_property_stringl(zend_class_entry *ce, const char *name, int name_length, const char *value, int value_len, int access_type TSRMLS_DC) /* {{{ */ { zval *property; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(property); ZVAL_STRINGL(property, zend_strndup(value, value_len), value_len, 0); } else { ALLOC_ZVAL(property); ZVAL_STRINGL(property, value, value_len, 1); } INIT_PZVAL(property); return zend_declare_property(ce, name, name_length, property, access_type TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant(zend_class_entry *ce, const char *name, size_t name_length, zval *value TSRMLS_DC) /* {{{ */ { return zend_hash_update(&ce->constants_table, name, name_length+1, &value, sizeof(zval *), NULL); } /* }}} */ ZEND_API int zend_declare_class_constant_null(zend_class_entry *ce, const char *name, size_t name_length TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); } else { ALLOC_ZVAL(constant); } ZVAL_NULL(constant); INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_long(zend_class_entry *ce, const char *name, size_t name_length, long value TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); } else { ALLOC_ZVAL(constant); } ZVAL_LONG(constant, value); INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_bool(zend_class_entry *ce, const char *name, size_t name_length, zend_bool value TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); } else { ALLOC_ZVAL(constant); } ZVAL_BOOL(constant, value); INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_double(zend_class_entry *ce, const char *name, size_t name_length, double value TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); } else { ALLOC_ZVAL(constant); } ZVAL_DOUBLE(constant, value); INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_stringl(zend_class_entry *ce, const char *name, size_t name_length, const char *value, size_t value_length TSRMLS_DC) /* {{{ */ { zval *constant; if (ce->type & ZEND_INTERNAL_CLASS) { ALLOC_PERMANENT_ZVAL(constant); ZVAL_STRINGL(constant, zend_strndup(value, value_length), value_length, 0); } else { ALLOC_ZVAL(constant); ZVAL_STRINGL(constant, value, value_length, 1); } INIT_PZVAL(constant); return zend_declare_class_constant(ce, name, name_length, constant TSRMLS_CC); } /* }}} */ ZEND_API int zend_declare_class_constant_string(zend_class_entry *ce, const char *name, size_t name_length, const char *value TSRMLS_DC) /* {{{ */ { return zend_declare_class_constant_stringl(ce, name, name_length, value, strlen(value) TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property(zend_class_entry *scope, zval *object, const char *name, int name_length, zval *value TSRMLS_DC) /* {{{ */ { zval *property; zend_class_entry *old_scope = EG(scope); EG(scope) = scope; if (!Z_OBJ_HT_P(object)->write_property) { const char *class_name; zend_uint class_name_len; zend_get_object_classname(object, &class_name, &class_name_len TSRMLS_CC); zend_error(E_CORE_ERROR, "Property %s of class %s cannot be updated", name, class_name); } MAKE_STD_ZVAL(property); ZVAL_STRINGL(property, name, name_length, 1); Z_OBJ_HT_P(object)->write_property(object, property, value, 0 TSRMLS_CC); zval_ptr_dtor(&property); EG(scope) = old_scope; } /* }}} */ ZEND_API void zend_update_property_null(zend_class_entry *scope, zval *object, const char *name, int name_length TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_NULL(tmp); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_bool(zend_class_entry *scope, zval *object, const char *name, int name_length, long value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_BOOL(tmp, value); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_long(zend_class_entry *scope, zval *object, const char *name, int name_length, long value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_LONG(tmp, value); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_double(zend_class_entry *scope, zval *object, const char *name, int name_length, double value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_DOUBLE(tmp, value); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_string(zend_class_entry *scope, zval *object, const char *name, int name_length, const char *value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_STRING(tmp, value, 1); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API void zend_update_property_stringl(zend_class_entry *scope, zval *object, const char *name, int name_length, const char *value, int value_len TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_STRINGL(tmp, value, value_len, 1); zend_update_property(scope, object, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property(zend_class_entry *scope, const char *name, int name_length, zval *value TSRMLS_DC) /* {{{ */ { zval **property; zend_class_entry *old_scope = EG(scope); EG(scope) = scope; property = zend_std_get_static_property(scope, name, name_length, 0, NULL TSRMLS_CC); EG(scope) = old_scope; if (!property) { return FAILURE; } else { if (*property != value) { if (PZVAL_IS_REF(*property)) { zval_dtor(*property); Z_TYPE_PP(property) = Z_TYPE_P(value); (*property)->value = value->value; if (Z_REFCOUNT_P(value) > 0) { zval_copy_ctor(*property); } } else { zval *garbage = *property; Z_ADDREF_P(value); if (PZVAL_IS_REF(value)) { SEPARATE_ZVAL(&value); } *property = value; zval_ptr_dtor(&garbage); } } return SUCCESS; } } /* }}} */ ZEND_API int zend_update_static_property_null(zend_class_entry *scope, const char *name, int name_length TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_NULL(tmp); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_bool(zend_class_entry *scope, const char *name, int name_length, long value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_BOOL(tmp, value); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_long(zend_class_entry *scope, const char *name, int name_length, long value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_LONG(tmp, value); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_double(zend_class_entry *scope, const char *name, int name_length, double value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_DOUBLE(tmp, value); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_string(zend_class_entry *scope, const char *name, int name_length, const char *value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_STRING(tmp, value, 1); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API int zend_update_static_property_stringl(zend_class_entry *scope, const char *name, int name_length, const char *value, int value_len TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_STRINGL(tmp, value, value_len, 1); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ ZEND_API zval *zend_read_property(zend_class_entry *scope, zval *object, const char *name, int name_length, zend_bool silent TSRMLS_DC) /* {{{ */ { zval *property, *value; zend_class_entry *old_scope = EG(scope); EG(scope) = scope; if (!Z_OBJ_HT_P(object)->read_property) { const char *class_name; zend_uint class_name_len; zend_get_object_classname(object, &class_name, &class_name_len TSRMLS_CC); zend_error(E_CORE_ERROR, "Property %s of class %s cannot be read", name, class_name); } MAKE_STD_ZVAL(property); ZVAL_STRINGL(property, name, name_length, 1); value = Z_OBJ_HT_P(object)->read_property(object, property, silent?BP_VAR_IS:BP_VAR_R, 0 TSRMLS_CC); zval_ptr_dtor(&property); EG(scope) = old_scope; return value; } /* }}} */ ZEND_API zval *zend_read_static_property(zend_class_entry *scope, const char *name, int name_length, zend_bool silent TSRMLS_DC) /* {{{ */ { zval **property; zend_class_entry *old_scope = EG(scope); EG(scope) = scope; property = zend_std_get_static_property(scope, name, name_length, silent, NULL TSRMLS_CC); EG(scope) = old_scope; return property?*property:NULL; } /* }}} */ ZEND_API void zend_save_error_handling(zend_error_handling *current TSRMLS_DC) /* {{{ */ { current->handling = EG(error_handling); current->exception = EG(exception_class); current->user_handler = EG(user_error_handler); if (current->user_handler) { Z_ADDREF_P(current->user_handler); } } /* }}} */ ZEND_API void zend_replace_error_handling(zend_error_handling_t error_handling, zend_class_entry *exception_class, zend_error_handling *current TSRMLS_DC) /* {{{ */ { if (current) { zend_save_error_handling(current TSRMLS_CC); if (error_handling != EH_NORMAL && EG(user_error_handler)) { zval_ptr_dtor(&EG(user_error_handler)); EG(user_error_handler) = NULL; } } EG(error_handling) = error_handling; EG(exception_class) = error_handling == EH_THROW ? exception_class : NULL; } /* }}} */ ZEND_API void zend_restore_error_handling(zend_error_handling *saved TSRMLS_DC) /* {{{ */ { EG(error_handling) = saved->handling; EG(exception_class) = saved->handling == EH_THROW ? saved->exception : NULL; if (saved->user_handler && saved->user_handler != EG(user_error_handler)) { if (EG(user_error_handler)) { zval_ptr_dtor(&EG(user_error_handler)); } EG(user_error_handler) = saved->user_handler; } else if (saved->user_handler) { zval_ptr_dtor(&saved->user_handler); } saved->user_handler = NULL; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2012-02-25-38b549ea2f-1923ecfe25.c
manybugs_data_80
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <zend_language_parser.h> #include "zend.h" #include "zend_compile.h" #include "zend_constants.h" #include "zend_llist.h" #include "zend_API.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "zend_multibyte.h" #include "zend_language_scanner.h" #define CONSTANT_EX(op_array, op) \ (op_array)->literals[op].constant #define CONSTANT(op) \ CONSTANT_EX(CG(active_op_array), op) #define SET_NODE(target, src) do { \ target ## _type = (src)->op_type; \ if ((src)->op_type == IS_CONST) { \ target.constant = zend_add_literal(CG(active_op_array), &(src)->u.constant TSRMLS_CC); \ } else { \ target = (src)->u.op; \ } \ } while (0) #define GET_NODE(target, src) do { \ (target)->op_type = src ## _type; \ if ((target)->op_type == IS_CONST) { \ (target)->u.constant = CONSTANT(src.constant); \ } else { \ (target)->u.op = src; \ (target)->EA = 0; \ } \ } while (0) #define COPY_NODE(target, src) do { \ target ## _type = src ## _type; \ target = src; \ } while (0) #define CALCULATE_LITERAL_HASH(num) do { \ if (IS_INTERNED(Z_STRVAL(CONSTANT(num)))) { \ Z_HASH_P(&CONSTANT(num)) = INTERNED_HASH(Z_STRVAL(CONSTANT(num))); \ } else { \ Z_HASH_P(&CONSTANT(num)) = zend_hash_func(Z_STRVAL(CONSTANT(num)), Z_STRLEN(CONSTANT(num))+1); \ } \ } while (0) #define GET_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot++; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ } \ } while (0) #define POLYMORPHIC_CACHE_SLOT_SIZE 2 #define GET_POLYMORPHIC_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot; \ CG(active_op_array)->last_cache_slot += POLYMORPHIC_CACHE_SLOT_SIZE; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 2] = NULL; \ } \ } while (0) #define FREE_POLYMORPHIC_CACHE_SLOT(literal) do { \ if (CG(active_op_array)->literals[literal].cache_slot == \ CG(active_op_array)->last_cache_slot - POLYMORPHIC_CACHE_SLOT_SIZE) { \ CG(active_op_array)->literals[literal].cache_slot = -1; \ CG(active_op_array)->last_cache_slot -= POLYMORPHIC_CACHE_SLOT_SIZE; \ } \ } while (0) ZEND_API zend_op_array *(*zend_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); ZEND_API zend_op_array *(*zend_compile_string)(zval *source_string, char *filename TSRMLS_DC); #ifndef ZTS ZEND_API zend_compiler_globals compiler_globals; ZEND_API zend_executor_globals executor_globals; #endif static void zend_duplicate_property_info(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = estrndup(property_info->name, property_info->name_length); } if (property_info->doc_comment) { property_info->doc_comment = estrndup(property_info->doc_comment, property_info->doc_comment_len); } } /* }}} */ static void zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = zend_strndup(property_info->name, property_info->name_length); } } /* }}} */ static void zend_destroy_property_info(zend_property_info *property_info) /* {{{ */ { str_efree(property_info->name); if (property_info->doc_comment) { efree((char*)property_info->doc_comment); } } /* }}} */ static void zend_destroy_property_info_internal(zend_property_info *property_info) /* {{{ */ { str_free((char*)property_info->name); } /* }}} */ static void build_runtime_defined_function_key(zval *result, const char *name, int name_length TSRMLS_DC) /* {{{ */ { char char_pos_buf[32]; uint char_pos_len; const char *filename; char_pos_len = zend_sprintf(char_pos_buf, "%p", LANG_SCNG(yy_text)); if (CG(active_op_array)->filename) { filename = CG(active_op_array)->filename; } else { filename = "-"; } /* NULL, name length, filename length, last accepting char position length */ result->value.str.len = 1+name_length+strlen(filename)+char_pos_len; /* must be binary safe */ result->value.str.val = (char *) safe_emalloc(result->value.str.len, 1, 1); result->value.str.val[0] = '\0'; sprintf(result->value.str.val+1, "%s%s%s", name, filename, char_pos_buf); result->type = IS_STRING; Z_SET_REFCOUNT_P(result, 1); } /* }}} */ static void init_compiler_declarables(TSRMLS_D) /* {{{ */ { Z_TYPE(CG(declarables).ticks) = IS_LONG; Z_LVAL(CG(declarables).ticks) = 0; } /* }}} */ void zend_init_compiler_context(TSRMLS_D) /* {{{ */ { CG(context).opcodes_size = (CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) ? INITIAL_INTERACTIVE_OP_ARRAY_SIZE : INITIAL_OP_ARRAY_SIZE; CG(context).vars_size = 0; CG(context).literals_size = 0; CG(context).current_brk_cont = -1; CG(context).backpatch_count = 0; CG(context).labels = NULL; } /* }}} */ void zend_init_compiler_data_structures(TSRMLS_D) /* {{{ */ { zend_stack_init(&CG(bp_stack)); zend_stack_init(&CG(function_call_stack)); zend_stack_init(&CG(switch_cond_stack)); zend_stack_init(&CG(foreach_copy_stack)); zend_stack_init(&CG(object_stack)); zend_stack_init(&CG(declare_stack)); CG(active_class_entry) = NULL; zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_stack_init(&CG(list_stack)); CG(in_compilation) = 0; CG(start_lineno) = 0; CG(current_namespace) = NULL; CG(in_namespace) = 0; CG(has_bracketed_namespaces) = 0; CG(current_import) = NULL; init_compiler_declarables(TSRMLS_C); zend_stack_init(&CG(context_stack)); CG(encoding_declared) = 0; } /* }}} */ ZEND_API void file_handle_dtor(zend_file_handle *fh) /* {{{ */ { TSRMLS_FETCH(); zend_file_handle_dtor(fh TSRMLS_CC); } /* }}} */ void init_compiler(TSRMLS_D) /* {{{ */ { CG(active_op_array) = NULL; zend_init_compiler_data_structures(TSRMLS_C); zend_init_rsrc_list(TSRMLS_C); zend_hash_init(&CG(filenames_table), 5, NULL, (dtor_func_t) free_estring, 0); zend_llist_init(&CG(open_files), sizeof(zend_file_handle), (void (*)(void *)) file_handle_dtor, 0); CG(unclean_shutdown) = 0; } /* }}} */ void shutdown_compiler(TSRMLS_D) /* {{{ */ { zend_stack_destroy(&CG(bp_stack)); zend_stack_destroy(&CG(function_call_stack)); zend_stack_destroy(&CG(switch_cond_stack)); zend_stack_destroy(&CG(foreach_copy_stack)); zend_stack_destroy(&CG(object_stack)); zend_stack_destroy(&CG(declare_stack)); zend_stack_destroy(&CG(list_stack)); zend_hash_destroy(&CG(filenames_table)); zend_llist_destroy(&CG(open_files)); zend_stack_destroy(&CG(context_stack)); } /* }}} */ ZEND_API char *zend_set_compiled_filename(const char *new_compiled_filename TSRMLS_DC) /* {{{ */ { char **pp, *p; int length = strlen(new_compiled_filename); if (zend_hash_find(&CG(filenames_table), new_compiled_filename, length+1, (void **) &pp) == SUCCESS) { CG(compiled_filename) = *pp; return *pp; } p = estrndup(new_compiled_filename, length); zend_hash_update(&CG(filenames_table), new_compiled_filename, length+1, &p, sizeof(char *), (void **) &pp); CG(compiled_filename) = p; return p; } /* }}} */ ZEND_API void zend_restore_compiled_filename(char *original_compiled_filename TSRMLS_DC) /* {{{ */ { CG(compiled_filename) = original_compiled_filename; } /* }}} */ ZEND_API char *zend_get_compiled_filename(TSRMLS_D) /* {{{ */ { return CG(compiled_filename); } /* }}} */ ZEND_API int zend_get_compiled_lineno(TSRMLS_D) /* {{{ */ { return CG(zend_lineno); } /* }}} */ ZEND_API zend_bool zend_is_compiling(TSRMLS_D) /* {{{ */ { return CG(in_compilation); } /* }}} */ static zend_uint get_temporary_variable(zend_op_array *op_array) /* {{{ */ { return (op_array->T)++ * ZEND_MM_ALIGNED_SIZE(sizeof(temp_variable)); } /* }}} */ static int lookup_cv(zend_op_array *op_array, char* name, int name_len, ulong hash TSRMLS_DC) /* {{{ */ { int i = 0; ulong hash_value = hash ? hash : zend_inline_hash_func(name, name_len+1); while (i < op_array->last_var) { if (op_array->vars[i].name == name || (op_array->vars[i].hash_value == hash_value && op_array->vars[i].name_len == name_len && memcmp(op_array->vars[i].name, name, name_len) == 0)) { str_efree(name); return i; } i++; } i = op_array->last_var; op_array->last_var++; if (op_array->last_var > CG(context).vars_size) { CG(context).vars_size += 16; /* FIXME */ op_array->vars = erealloc(op_array->vars, CG(context).vars_size * sizeof(zend_compiled_variable)); } op_array->vars[i].name = zend_new_interned_string(name, name_len + 1, 1 TSRMLS_CC); op_array->vars[i].name_len = name_len; op_array->vars[i].hash_value = hash_value; return i; } /* }}} */ void zend_del_literal(zend_op_array *op_array, int n) /* {{{ */ { zval_dtor(&CONSTANT_EX(op_array, n)); if (n + 1 == op_array->last_literal) { op_array->last_literal--; } else { Z_TYPE(CONSTANT_EX(op_array, n)) = IS_NULL; } } /* }}} */ /* Common part of zend_add_literal and zend_append_individual_literal */ static inline void zend_insert_literal(zend_op_array *op_array, const zval *zv, int literal_position TSRMLS_DC) /* {{{ */ { if (Z_TYPE_P(zv) == IS_STRING || Z_TYPE_P(zv) == IS_CONSTANT) { zval *z = (zval*)zv; Z_STRVAL_P(z) = (char*)zend_new_interned_string(Z_STRVAL_P(zv), Z_STRLEN_P(zv) + 1, 1 TSRMLS_CC); } CONSTANT_EX(op_array, literal_position) = *zv; Z_SET_REFCOUNT(CONSTANT_EX(op_array, literal_position), 2); Z_SET_ISREF(CONSTANT_EX(op_array, literal_position)); op_array->literals[literal_position].hash_value = 0; op_array->literals[literal_position].cache_slot = -1; } /* }}} */ /* Is used while compiling a function, using the context to keep track of an approximate size to avoid to relocate to often. Literals are truncated to actual size in the second compiler pass (pass_two()). */ int zend_add_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; if (i >= CG(context).literals_size) { while (i >= CG(context).literals_size) { CG(context).literals_size += 16; /* FIXME */ } op_array->literals = (zend_literal*)erealloc(op_array->literals, CG(context).literals_size * sizeof(zend_literal)); } zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ /* Is used after normal compilation to append an additional literal. Allocation is done precisely here. */ int zend_append_individual_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; op_array->literals = (zend_literal*)erealloc(op_array->literals, (i + 1) * sizeof(zend_literal)); zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ int zend_add_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_ns_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; const char *ns_separator; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); ns_separator = (const char*)zend_memrchr(Z_STRVAL_P(zv), '\\', Z_STRLEN_P(zv)) + 1; lc_len = Z_STRLEN_P(zv) - (ns_separator - Z_STRVAL_P(zv)); lc_name = zend_str_tolower_dup(ns_separator, lc_len); ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_class_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } if (Z_STRVAL_P(zv)[0] == '\\') { lc_len = Z_STRLEN_P(zv) - 1; lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv) + 1, lc_len); } else { lc_len = Z_STRLEN_P(zv); lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), lc_len); } ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); GET_CACHE_SLOT(ret); return ret; } /* }}} */ int zend_add_const_name_literal(zend_op_array *op_array, const zval *zv, int unqualified TSRMLS_DC) /* {{{ */ { int ret, tmp_literal; char *name, *tmp_name; const char *ns_separator; int name_len, ns_len; zval c; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } /* skip leading '\\' */ if (Z_STRVAL_P(zv)[0] == '\\') { name_len = Z_STRLEN_P(zv) - 1; name = Z_STRVAL_P(zv) + 1; } else { name_len = Z_STRLEN_P(zv); name = Z_STRVAL_P(zv); } ns_separator = zend_memrchr(name, '\\', name_len); if (ns_separator) { ns_len = ns_separator - name; } else { ns_len = 0; } if (ns_len) { /* lowercased namespace name & original constant name */ tmp_name = estrndup(name, name_len); zend_str_tolower(tmp_name, ns_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased namespace name & lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); } if (ns_len) { if (!unqualified) { return ret; } ns_len++; name += ns_len; name_len -= ns_len; } /* original constant name */ tmp_name = estrndup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); return ret; } /* }}} */ #define LITERAL_STRINGL(op, str, len, copy) do { \ zval _c; \ ZVAL_STRINGL(&_c, str, len, copy); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG(op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG_EX(op_array, op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(op_array, &_c TSRMLS_CC); \ } while (0) #define LITERAL_NULL(op) do { \ zval _c; \ INIT_ZVAL( _c); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) static inline zend_bool zend_is_function_or_method_call(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; return ((type & ZEND_PARSED_METHOD_CALL) || (type == ZEND_PARSED_FUNCTION_CALL)); } /* }}} */ void zend_do_binary_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_unary_op(zend_uchar op, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); GET_NODE(result, opline->result); SET_UNUSED(opline->op2); } /* }}} */ #define MAKE_NOP(opline) { opline->opcode = ZEND_NOP; memset(&opline->result,0,sizeof(opline->result)); memset(&opline->op1,0,sizeof(opline->op1)); memset(&opline->op2,0,sizeof(opline->op2)); opline->result_type=opline->op1_type=opline->op2_type=IS_UNUSED; } static void zend_do_op_data(zend_op *data_op, const znode *value TSRMLS_DC) /* {{{ */ { data_op->opcode = ZEND_OP_DATA; SET_NODE(data_op->op1, value); SET_UNUSED(data_op->op2); } /* }}} */ void zend_do_binary_assign_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; switch (last_op->opcode) { case ZEND_FETCH_OBJ_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, op2 TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; case ZEND_FETCH_DIM_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_DIM; zend_do_op_data(opline, op2 TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result,last_op->result); return; default: break; } } opline->opcode = op; SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void fetch_simple_variable_ex(znode *result, znode *varname, int bp, zend_uchar op TSRMLS_DC) /* {{{ */ { zend_op opline; zend_op *opline_ptr; zend_llist *fetch_list_ptr; if (varname->op_type == IS_CONST) { ulong hash = 0; if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } else if (IS_INTERNED(Z_STRVAL(varname->u.constant))) { hash = INTERNED_HASH(Z_STRVAL(varname->u.constant)); } if (!zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC) && !(varname->u.constant.value.str.len == (sizeof("this")-1) && !memcmp(varname->u.constant.value.str.val, "this", sizeof("this"))) && (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE)) { result->op_type = IS_CV; result->u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC); varname->u.constant.value.str.val = (char*)CG(active_op_array)->vars[result->u.op.var].name; result->EA = 0; return; } } if (bp) { opline_ptr = &opline; init_op(opline_ptr TSRMLS_CC); } else { opline_ptr = get_next_op(CG(active_op_array) TSRMLS_CC); } opline_ptr->opcode = op; opline_ptr->result_type = IS_VAR; opline_ptr->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline_ptr->op1, varname); GET_NODE(result, opline_ptr->result); SET_UNUSED(opline_ptr->op2); opline_ptr->extended_value = ZEND_FETCH_LOCAL; if (varname->op_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline_ptr->op1.constant); if (zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC)) { opline_ptr->extended_value = ZEND_FETCH_GLOBAL; } } if (bp) { zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); zend_llist_add_element(fetch_list_ptr, opline_ptr); } } /* }}} */ void fetch_simple_variable(znode *result, znode *varname, int bp TSRMLS_DC) /* {{{ */ { /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ fetch_simple_variable_ex(result, varname, bp, ZEND_FETCH_W TSRMLS_CC); } /* }}} */ void zend_do_fetch_static_member(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { znode class_node; zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline_ptr; zend_op opline; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); } zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (result->op_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[result->u.op.var].name), CG(active_op_array)->vars[result->u.op.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } GET_NODE(result,opline.result); opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; opline_ptr = &opline; zend_llist_add_element(fetch_list_ptr, &opline); } else { le = fetch_list_ptr->head; opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode != ZEND_FETCH_W && opline_ptr->op1_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[opline_ptr->op1.var].name), CG(active_op_array)->vars[opline_ptr->op1.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; COPY_NODE(opline_ptr->op1, opline.result); zend_llist_prepend_element(fetch_list_ptr, &opline); } else { if (opline_ptr->op1_type == IS_CONST) { GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op1.constant); } if (class_node.op_type == IS_CONST) { opline_ptr->op2_type = IS_CONST; opline_ptr->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline_ptr->op2, &class_node); } opline_ptr->extended_value |= ZEND_FETCH_STATIC_MEMBER; } } } /* }}} */ void fetch_array_begin(znode *result, znode *varname, znode *first_dim TSRMLS_DC) /* {{{ */ { fetch_simple_variable(result, varname, 1 TSRMLS_CC); fetch_array_dim(result, result, first_dim TSRMLS_CC); } /* }}} */ void fetch_array_dim(znode *result, const znode *parent, const znode *dim TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (zend_is_function_or_method_call(parent)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, parent); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_DIM_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, parent); SET_NODE(opline.op2, dim); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline.op2.constant)), Z_STRLEN(CONSTANT(opline.op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline.op2.constant)); ZVAL_LONG(&CONSTANT(opline.op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline.op2.constant); } } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void fetch_string_offset(znode *result, const znode *parent, const znode *offset TSRMLS_DC) /* {{{ */ { fetch_array_dim(result, parent, offset TSRMLS_CC); } /* }}} */ void zend_do_print(znode *result, const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->opcode = ZEND_PRINT; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_echo(const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ECHO; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_abstract_method(const znode *function_name, znode *modifiers, const znode *body TSRMLS_DC) /* {{{ */ { char *method_type; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { Z_LVAL(modifiers->u.constant) |= ZEND_ACC_ABSTRACT; method_type = "Interface"; } else { method_type = "Abstract"; } if (modifiers->u.constant.value.lval & ZEND_ACC_ABSTRACT) { if(modifiers->u.constant.value.lval & ZEND_ACC_PRIVATE) { zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot be declared private", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } if (Z_LVAL(body->u.constant) == ZEND_ACC_ABSTRACT) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_RAISE_ABSTRACT_ERROR; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } else { /* we had code in the function body */ zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot contain body", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } else { if (body->u.constant.value.lval == ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Non-abstract method %s::%s() must contain body", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } } /* }}} */ static zend_bool opline_is_fetch_this(const zend_op *opline TSRMLS_DC) /* {{{ */ { if ((opline->opcode == ZEND_FETCH_W) && (opline->op1_type == IS_CONST) && (Z_TYPE(CONSTANT(opline->op1.constant)) == IS_STRING) && (Z_HASH_P(&CONSTANT(opline->op1.constant)) == THIS_HASHVAL) && (Z_STRLEN(CONSTANT(opline->op1.constant)) == (sizeof("this")-1)) && !memcmp(Z_STRVAL(CONSTANT(opline->op1.constant)), "this", sizeof("this"))) { return 1; } else { return 0; } } /* }}} */ void zend_do_assign(znode *result, znode *variable, znode *value TSRMLS_DC) /* {{{ */ { int last_op_number; zend_op *opline; if (value->op_type == IS_CV) { zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (fetch_list_ptr && fetch_list_ptr->head) { opline = (zend_op *)fetch_list_ptr->head->data; if (opline->opcode == ZEND_FETCH_DIM_W && opline->op1_type == IS_CV && opline->op1.var == value->u.op.var) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_R; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->op1_type = IS_CONST; LITERAL_STRINGL(opline->op1, CG(active_op_array)->vars[value->u.op.var].name, CG(active_op_array)->vars[value->u.op.var].name_len, 1); CALCULATE_LITERAL_HASH(opline->op1.constant); SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_LOCAL; GET_NODE(value, opline->result); } } } zend_do_end_variable_parse(variable, BP_VAR_W, 0 TSRMLS_CC); last_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (variable->op_type == IS_CV) { if (variable->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (variable->op_type == IS_VAR) { int n = 0; while (last_op_number - n > 0) { zend_op *last_op; last_op = &CG(active_op_array)->opcodes[last_op_number-n-1]; if (last_op->result_type == IS_VAR && last_op->result.var == variable->u.op.var) { if (last_op->opcode == ZEND_FETCH_OBJ_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, value TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (last_op->opcode == ZEND_FETCH_DIM_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ /* TBFixed: this can realloc opcodes, leaving last_op pointing wrong */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_DIM; zend_do_op_data(opline, value TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (opline_is_fetch_this(last_op TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } else { break; } } n++; } } opline->opcode = ZEND_ASSIGN; SET_NODE(opline->op1, variable); SET_NODE(opline->op2, value); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_assign_ref(znode *result, const znode *lvar, const znode *rvar TSRMLS_DC) /* {{{ */ { zend_op *opline; if (lvar->op_type == IS_CV) { if (lvar->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (lvar->op_type == IS_VAR) { int last_op_number = get_next_op_number(CG(active_op_array)); if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline_is_fetch_this(opline TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ASSIGN_REF; if (zend_is_function_or_method_call(rvar)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } else if (rvar->EA & ZEND_PARSED_NEW) { opline->extended_value = ZEND_RETURNS_NEW; } else { opline->extended_value = 0; } if (result) { opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } else { opline->result_type = IS_UNUSED | EXT_TYPE_UNUSED; } SET_NODE(opline->op1, lvar); SET_NODE(opline->op2, rvar); } /* }}} */ static inline void do_begin_loop(TSRMLS_D) /* {{{ */ { zend_brk_cont_element *brk_cont_element; int parent; parent = CG(context).current_brk_cont; CG(context).current_brk_cont = CG(active_op_array)->last_brk_cont; brk_cont_element = get_next_brk_cont_element(CG(active_op_array)); brk_cont_element->start = get_next_op_number(CG(active_op_array)); brk_cont_element->parent = parent; } /* }}} */ static inline void do_end_loop(int cont_addr, int has_loop_var TSRMLS_DC) /* {{{ */ { if (!has_loop_var) { /* The start fileld is used to free temporary variables in case of exceptions. * We won't try to free something of we don't have loop variable. */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].start = -1; } CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = cont_addr; CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; } /* }}} */ void zend_do_while_cond(const znode *expr, znode *close_bracket_token TSRMLS_DC) /* {{{ */ { int while_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, expr); close_bracket_token->u.op.opline_num = while_cond_op_number; SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_while_end(const znode *while_token, const znode *close_bracket_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* add unconditional jump */ opline->opcode = ZEND_JMP; opline->op1.opline_num = while_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* update while's conditional jmp */ CG(active_op_array)->opcodes[close_bracket_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); do_end_loop(while_token->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_cond(const znode *expr, znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { int for_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZNZ; SET_NODE(opline->op1, expr); /* the conditional expression */ second_semicolon_token->u.op.opline_num = for_cond_op_number; SET_UNUSED(opline->op2); } /* }}} */ void zend_do_for_before_statement(const znode *cond_start, const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = cond_start->u.op.opline_num; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_end(const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = second_semicolon_token->u.op.opline_num+1; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_end_loop(second_semicolon_token->u.op.opline_num+1, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_pre_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_PRE_INC)?ZEND_PRE_INC_OBJ:ZEND_PRE_DEC_OBJ; last_op->result_type = IS_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_post_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_POST_INC)?ZEND_POST_INC_OBJ:ZEND_POST_DEC_OBJ; last_op->result_type = IS_TMP_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_if_cond(const znode *cond, znode *closing_bracket_token TSRMLS_DC) /* {{{ */ { int if_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); closing_bracket_token->u.op.opline_num = if_cond_op_number; SET_UNUSED(opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_if_after_statement(const znode *closing_bracket_token, unsigned char initialize TSRMLS_DC) /* {{{ */ { int if_end_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; /* save for backpatching */ if (initialize) { zend_llist jmp_list; zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); } zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &if_end_op_number); CG(active_op_array)->opcodes[closing_bracket_token->u.op.opline_num].op2.opline_num = if_end_op_number+1; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_if_end(TSRMLS_D) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_llist *jmp_list_ptr; zend_llist_element *le; zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); for (le=jmp_list_ptr->head; le; le = le->next) { CG(active_op_array)->opcodes[*((int *) le->data)].op1.opline_num = next_op_number; } zend_llist_destroy(jmp_list_ptr); zend_stack_del_top(&CG(bp_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_check_writable_variable(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; if (type & ZEND_PARSED_METHOD_CALL) { zend_error(E_COMPILE_ERROR, "Can't use method return value in write context"); } if (type == ZEND_PARSED_FUNCTION_CALL) { zend_error(E_COMPILE_ERROR, "Can't use function return value in write context"); } } /* }}} */ void zend_do_begin_variable_parse(TSRMLS_D) /* {{{ */ { zend_llist fetch_list; zend_llist_init(&fetch_list, sizeof(zend_op), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &fetch_list, sizeof(zend_llist)); } /* }}} */ void zend_do_end_variable_parse(znode *variable, int type, int arg_offset TSRMLS_DC) /* {{{ */ { zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline = NULL; zend_op *opline_ptr; zend_uint this_var = -1; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); le = fetch_list_ptr->head; /* TODO: $foo->x->y->z = 1 should fetch "x" and "y" for R or RW, not just W */ if (le) { opline_ptr = (zend_op *)le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { /* convert to FETCH_?(this) into IS_CV */ if (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE) { this_var = opline_ptr->result.var; if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), Z_STRVAL(CONSTANT(opline_ptr->op1.constant)), Z_STRLEN(CONSTANT(opline_ptr->op1.constant)), Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC); Z_TYPE(CONSTANT(opline_ptr->op1.constant)) = IS_NULL; } else { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); } le = le->next; if (variable->op_type == IS_VAR && variable->u.op.var == this_var) { variable->op_type = IS_CV; variable->u.op.var = CG(active_op_array)->this_var; } } else if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } while (le) { opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode == ZEND_SEPARATE) { if (type != BP_VAR_R && type != BP_VAR_IS) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); } le = le->next; continue; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); if (opline->op1_type == IS_VAR && opline->op1.var == this_var) { opline->op1_type = IS_CV; opline->op1.var = CG(active_op_array)->this_var; } switch (type) { case BP_VAR_R: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode -= 3; break; case BP_VAR_W: break; case BP_VAR_RW: opline->opcode += 3; break; case BP_VAR_IS: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode += 6; /* 3+3 */ break; case BP_VAR_FUNC_ARG: opline->opcode += 9; /* 3+3+3 */ opline->extended_value |= arg_offset; break; case BP_VAR_UNSET: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for unsetting"); } opline->opcode += 12; /* 3+3+3+3 */ break; } le = le->next; } if (opline && type == BP_VAR_W && arg_offset) { opline->extended_value |= ZEND_FETCH_MAKE_REF; } } zend_llist_destroy(fetch_list_ptr); zend_stack_del_top(&CG(bp_stack)); } /* }}} */ void zend_do_add_string(znode *result, const znode *op1, znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline; if (Z_STRLEN(op2->u.constant) > 1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_STRING; } else if (Z_STRLEN(op2->u.constant) == 1) { int ch = *Z_STRVAL(op2->u.constant); /* Free memory and use ZEND_ADD_CHAR in case of 1 character strings */ efree(Z_STRVAL(op2->u.constant)); ZVAL_LONG(&op2->u.constant, ch); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_CHAR; } else { /* String can be empty after a variable at the end of a heredoc */ efree(Z_STRVAL(op2->u.constant)); return; } if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_add_variable(znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_VAR; if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_free(znode *op1 TSRMLS_DC) /* {{{ */ { if (op1->op_type==IS_TMP_VAR) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else if (op1->op_type==IS_VAR) { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; while (opline->opcode == ZEND_END_SILENCE || opline->opcode == ZEND_EXT_FCALL_END || opline->opcode == ZEND_OP_DATA) { opline--; } if (opline->result_type == IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_FETCH_R || opline->opcode == ZEND_FETCH_DIM_R || opline->opcode == ZEND_FETCH_OBJ_R || opline->opcode == ZEND_QM_ASSIGN_VAR) { /* It's very rare and useless case. It's better to use additional FREE opcode and simplify the FETCH handlers their selves */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else { opline->result_type |= EXT_TYPE_UNUSED; } } else { while (opline>CG(active_op_array)->opcodes) { if (opline->opcode == ZEND_FETCH_DIM_R && opline->op1_type == IS_VAR && opline->op1.var == op1->u.op.var) { /* This should the end of a list() construct * Mark its result as unused */ opline->extended_value = ZEND_FETCH_STANDARD; break; } else if (opline->result_type==IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_NEW) { opline->result_type |= EXT_TYPE_UNUSED; } break; } opline--; } } } else if (op1->op_type == IS_CONST) { zval_dtor(&op1->u.constant); } } /* }}} */ int zend_do_verify_access_types(const znode *current_access_type, const znode *new_modifier) /* {{{ */ { if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_PPP_MASK) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Multiple access type modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_ABSTRACT) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Multiple abstract modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_STATIC) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Multiple static modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_FINAL) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Multiple final modifiers are not allowed"); } if (((Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)) & (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) == (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Cannot use the final modifier on an abstract class member"); } return (Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)); } /* }}} */ void zend_do_begin_function_declaration(znode *function_token, znode *function_name, int is_method, int return_reference, znode *fn_flags_znode TSRMLS_DC) /* {{{ */ { zend_op_array op_array; char *name = function_name->u.constant.value.str.val; int name_len = function_name->u.constant.value.str.len; int function_begin_line = function_token->u.op.opline_num; zend_uint fn_flags; const char *lcname; zend_bool orig_interactive; ALLOCA_FLAG(use_heap) if (is_method) { if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((Z_LVAL(fn_flags_znode->u.constant) & ~(ZEND_ACC_STATIC|ZEND_ACC_PUBLIC))) { zend_error(E_COMPILE_ERROR, "Access type for interface method %s::%s() must be omitted", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } Z_LVAL(fn_flags_znode->u.constant) |= ZEND_ACC_ABSTRACT; /* propagates to the rest of the parser */ } fn_flags = Z_LVAL(fn_flags_znode->u.constant); /* must be done *after* the above check */ } else { fn_flags = 0; } if ((fn_flags & ZEND_ACC_STATIC) && (fn_flags & ZEND_ACC_ABSTRACT) && !(CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_STRICT, "Static function %s%s%s() should not be abstract", is_method ? CG(active_class_entry)->name : "", is_method ? "::" : "", Z_STRVAL(function_name->u.constant)); } function_token->u.op_array = CG(active_op_array); orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(&op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; op_array.function_name = name; if (return_reference) { op_array.fn_flags |= ZEND_ACC_RETURN_REFERENCE; } op_array.fn_flags |= fn_flags; op_array.scope = is_method?CG(active_class_entry):NULL; op_array.prototype = NULL; op_array.line_start = zend_get_compiled_lineno(TSRMLS_C); if (is_method) { int result; lcname = zend_new_interned_string(zend_str_tolower_dup(name, name_len), name_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lcname)) { result = zend_hash_quick_add(&CG(active_class_entry)->function_table, lcname, name_len+1, INTERNED_HASH(lcname), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } else { result = zend_hash_add(&CG(active_class_entry)->function_table, lcname, name_len+1, &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } if (result == FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::%s()", CG(active_class_entry)->name, name); } zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); if (fn_flags & ZEND_ACC_ABSTRACT) { CG(active_class_entry)->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (!(fn_flags & ZEND_ACC_PPP_MASK)) { fn_flags |= ZEND_ACC_PUBLIC; } if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } } } else { char *class_lcname; class_lcname = do_alloca(CG(active_class_entry)->name_length + 1, use_heap); zend_str_tolower_copy(class_lcname, CG(active_class_entry)->name, CG(active_class_entry)->name_length); /* Improve after RC: cache the lowercase class name */ if ((CG(active_class_entry)->name_length == name_len) && ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT) && (!memcmp(class_lcname, lcname, name_len))) { if (!CG(active_class_entry)->constructor) { CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } } else if ((name_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)))) { if (CG(active_class_entry)->constructor) { zend_error(E_STRICT, "Redefining already defined constructor for class %s", CG(active_class_entry)->name); } CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1))) { CG(active_class_entry)->destructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1))) { CG(active_class_entry)->clone = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } CG(active_class_entry)->__call = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } CG(active_class_entry)->__callstatic = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } CG(active_class_entry)->__get = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } CG(active_class_entry)->__set = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } CG(active_class_entry)->__unset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } CG(active_class_entry)->__isset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } CG(active_class_entry)->__tostring = (zend_function *) CG(active_op_array); } else if (!(fn_flags & ZEND_ACC_STATIC)) { CG(active_op_array)->fn_flags |= ZEND_ACC_ALLOW_STATIC; } free_alloca(class_lcname, use_heap); } str_efree(lcname); } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zval key; if (CG(current_namespace)) { /* Prefix function name with current namespcae name */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, function_name TSRMLS_CC); op_array.function_name = Z_STRVAL(tmp.u.constant); name_len = Z_STRLEN(tmp.u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), name_len); } else { lcname = zend_str_tolower_dup(name, name_len); } opline->opcode = ZEND_DECLARE_FUNCTION; opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, name_len TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; LITERAL_STRINGL(opline->op2, lcname, name_len, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); opline->extended_value = ZEND_DECLARE_FUNCTION; zend_hash_quick_update(CG(function_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); } if (CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_NOP; opline->lineno = function_begin_line; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } { /* Push a seperator to the switch and foreach stacks */ zend_switch_entry switch_entry; switch_entry.cond.op_type = IS_UNUSED; switch_entry.default_case = 0; switch_entry.control_var = 0; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); { /* Foreach stack separator */ zend_op dummy_opline; dummy_opline.result_type = IS_UNUSED; dummy_opline.op1_type = IS_UNUSED; zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); } } if (CG(doc_comment)) { CG(active_op_array)->doc_comment = CG(doc_comment); CG(active_op_array)->doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_begin_lambda_function_declaration(znode *result, znode *function_token, int return_reference, int is_static TSRMLS_DC) /* {{{ */ { znode function_name; zend_op_array *current_op_array = CG(active_op_array); int current_op_number = get_next_op_number(CG(active_op_array)); zend_op *current_op; function_name.op_type = IS_CONST; ZVAL_STRINGL(&function_name.u.constant, "{closure}", sizeof("{closure}")-1, 1); zend_do_begin_function_declaration(function_token, &function_name, 0, return_reference, NULL TSRMLS_CC); result->op_type = IS_TMP_VAR; result->u.op.var = get_temporary_variable(current_op_array); current_op = &current_op_array->opcodes[current_op_number]; current_op->opcode = ZEND_DECLARE_LAMBDA_FUNCTION; zend_del_literal(current_op_array, current_op->op2.constant); SET_UNUSED(current_op->op2); SET_NODE(current_op->result, result); if (is_static) { CG(active_op_array)->fn_flags |= ZEND_ACC_STATIC; } CG(active_op_array)->fn_flags |= ZEND_ACC_CLOSURE; } /* }}} */ void zend_do_handle_exception(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_HANDLE_EXCEPTION; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_function_declaration(const znode *function_token TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; zend_do_extended_info(TSRMLS_C); zend_do_return(NULL, 0 TSRMLS_CC); pass_two(CG(active_op_array) TSRMLS_CC); zend_release_labels(TSRMLS_C); if (CG(active_class_entry)) { zend_check_magic_method_implementation(CG(active_class_entry), (zend_function*)CG(active_op_array), E_COMPILE_ERROR TSRMLS_CC); } else { /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(CG(active_op_array)->function_name); zend_str_tolower_copy(lcname, CG(active_op_array)->function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME)) && CG(active_op_array)->num_args != 1) { zend_error(E_COMPILE_ERROR, "%s() must take exactly 1 argument", ZEND_AUTOLOAD_FUNC_NAME); } } CG(active_op_array)->line_end = zend_get_compiled_lineno(TSRMLS_C); CG(active_op_array) = function_token->u.op_array; /* Pop the switch and foreach seperators */ zend_stack_del_top(&CG(switch_cond_stack)); zend_stack_del_top(&CG(foreach_copy_stack)); } /* }}} */ void zend_do_receive_arg(zend_uchar op, znode *varname, const znode *offset, const znode *initialization, znode *class_type, zend_uchar pass_by_reference TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_arg_info *cur_arg_info; znode var; if (class_type->op_type == IS_CONST && Z_TYPE(class_type->u.constant) == IS_STRING && Z_STRLEN(class_type->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_type->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } if (zend_is_auto_global_quick(Z_STRVAL(varname->u.constant), Z_STRLEN(varname->u.constant), 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign auto-global variable %s", Z_STRVAL(varname->u.constant)); } else { var.op_type = IS_CV; var.u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(varname->u.constant) = (char*)CG(active_op_array)->vars[var.u.op.var].name; var.EA = 0; if (CG(active_op_array)->vars[var.u.op.var].hash_value == THIS_HASHVAL && Z_STRLEN(varname->u.constant) == sizeof("this")-1 && !memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this")-1)) { if (CG(active_op_array)->scope && (CG(active_op_array)->fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } CG(active_op_array)->this_var = var.u.op.var; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->num_args++; opline->opcode = op; SET_NODE(opline->result, &var); SET_NODE(opline->op1, offset); if (op == ZEND_RECV_INIT) { SET_NODE(opline->op2, initialization); } else { CG(active_op_array)->required_num_args = CG(active_op_array)->num_args; SET_UNUSED(opline->op2); } CG(active_op_array)->arg_info = erealloc(CG(active_op_array)->arg_info, sizeof(zend_arg_info)*(CG(active_op_array)->num_args)); cur_arg_info = &CG(active_op_array)->arg_info[CG(active_op_array)->num_args-1]; cur_arg_info->name = zend_new_interned_string(estrndup(varname->u.constant.value.str.val, varname->u.constant.value.str.len), varname->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->name_len = varname->u.constant.value.str.len; cur_arg_info->type_hint = 0; cur_arg_info->allow_null = 1; cur_arg_info->pass_by_reference = pass_by_reference; cur_arg_info->class_name = NULL; cur_arg_info->class_name_len = 0; if (class_type->op_type != IS_UNUSED) { cur_arg_info->allow_null = 0; if (class_type->u.constant.type != IS_NULL) { if (class_type->u.constant.type == IS_ARRAY) { cur_arg_info->type_hint = IS_ARRAY; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else if (Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Default value for parameters with array type hint can only be an array or NULL"); } } } else if (class_type->u.constant.type == IS_CALLABLE) { cur_arg_info->type_hint = IS_CALLABLE; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with callable type hint can only be NULL"); } } } else { cur_arg_info->type_hint = IS_OBJECT; if (ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_type->u.constant), Z_STRLEN(class_type->u.constant))) { zend_resolve_class_name(class_type, opline->extended_value, 1 TSRMLS_CC); } Z_STRVAL(class_type->u.constant) = (char*)zend_new_interned_string(class_type->u.constant.value.str.val, class_type->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->class_name = class_type->u.constant.value.str.val; cur_arg_info->class_name_len = class_type->u.constant.value.str.len; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with a class type hint can only be NULL"); } } } } } } /* }}} */ int zend_do_begin_function_call(znode *function_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { zend_function *function; char *lcname; char *is_compound = memchr(Z_STRVAL(function_name->u.constant), '\\', Z_STRLEN(function_name->u.constant)); zend_resolve_non_class_name(function_name, check_namespace TSRMLS_CC); if (check_namespace && CG(current_namespace) && !is_compound) { /* We assume we call function from the current namespace if it is not prefixed. */ /* In run-time PHP will check for function with full name and internal function with short name */ zend_do_begin_dynamic_function_call(function_name, 1 TSRMLS_CC); return 1; } lcname = zend_str_tolower_dup(function_name->u.constant.value.str.val, function_name->u.constant.value.str.len); if ((zend_hash_find(CG(function_table), lcname, function_name->u.constant.value.str.len+1, (void **) &function)==FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_FUNCTIONS) && (function->type == ZEND_INTERNAL_FUNCTION))) { zend_do_begin_dynamic_function_call(function_name, 0 TSRMLS_CC); efree(lcname); return 1; /* Dynamic */ } efree(function_name->u.constant.value.str.val); function_name->u.constant.value.str.val = lcname; zend_stack_push(&CG(function_call_stack), (void *) &function, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 0; } /* }}} */ void zend_do_begin_method_call(znode *left_bracket TSRMLS_DC) /* {{{ */ { zend_op *last_op; int last_op_number; unsigned char *ptr = NULL; zend_do_end_variable_parse(left_bracket, BP_VAR_R, 0 TSRMLS_CC); zend_do_begin_variable_parse(TSRMLS_C); last_op_number = get_next_op_number(CG(active_op_array))-1; last_op = &CG(active_op_array)->opcodes[last_op_number]; if ((last_op->op2_type == IS_CONST) && (Z_TYPE(CONSTANT(last_op->op2.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(last_op->op2.constant)) == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !zend_binary_strcasecmp(Z_STRVAL(CONSTANT(last_op->op2.constant)), Z_STRLEN(CONSTANT(last_op->op2.constant)), ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1)) { zend_error(E_COMPILE_ERROR, "Cannot call __clone() method on objects - use 'clone $obj' instead"); } if (last_op->opcode == ZEND_FETCH_OBJ_R) { if (last_op->op2_type == IS_CONST) { zval name; name = CONSTANT(last_op->op2.constant); if (!IS_INTERNED(Z_STRVAL(name))) { Z_STRVAL(name) = estrndup(Z_STRVAL(name), Z_STRLEN(name)); } FREE_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); last_op->op2.constant = zend_add_func_name_literal(CG(active_op_array), &name TSRMLS_CC); GET_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); } last_op->opcode = ZEND_INIT_METHOD_CALL; SET_UNUSED(last_op->result); Z_LVAL(left_bracket->u.constant) = ZEND_INIT_FCALL_BY_NAME; } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (left_bracket->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &left_bracket->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, left_bracket); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_do_clone(znode *result, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CLONE; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_begin_dynamic_function_call(znode *function_name, int ns_call TSRMLS_DC) /* {{{ */ { unsigned char *ptr = NULL; zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (ns_call) { /* In run-time PHP will check for function with full name and internal function with short name */ opline->opcode = ZEND_INIT_NS_FCALL_BY_NAME; SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_ns_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (function_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, function_name); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_resolve_non_class_name(znode *element_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; int len; zval **ns; char *lcname, *compound = memchr(Z_STRVAL(element_name->u.constant), '\\', Z_STRLEN(element_name->u.constant)); if (Z_STRVAL(element_name->u.constant)[0] == '\\') { /* name starts with \ so it is known and unambiguos, nothing to do here but shorten it */ memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+1, Z_STRLEN(element_name->u.constant)); --Z_STRLEN(element_name->u.constant); return; } if(!check_namespace) { return; } if (compound && CG(current_import)) { len = compound - Z_STRVAL(element_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(element_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(element_name->u.constant) -= len; memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+len, Z_STRLEN(element_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, element_name TSRMLS_CC); *element_name = tmp; efree(lcname); return; } efree(lcname); } if (CG(current_namespace)) { tmp = *element_name; Z_STRLEN(tmp.u.constant) = sizeof("\\")-1 + Z_STRLEN(element_name->u.constant) + Z_STRLEN_P(CG(current_namespace)); Z_STRVAL(tmp.u.constant) = (char *) emalloc(Z_STRLEN(tmp.u.constant)+1); memcpy(Z_STRVAL(tmp.u.constant), Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace))]), "\\", sizeof("\\")-1); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace)) + sizeof("\\")-1]), Z_STRVAL(element_name->u.constant), Z_STRLEN(element_name->u.constant)+1); STR_FREE(Z_STRVAL(element_name->u.constant)); *element_name = tmp; } } /* }}} */ void zend_resolve_class_name(znode *class_name, ulong fetch_type, int check_ns_name TSRMLS_DC) /* {{{ */ { char *compound; char *lcname; zval **ns; znode tmp; int len; compound = memchr(Z_STRVAL(class_name->u.constant), '\\', Z_STRLEN(class_name->u.constant)); if (compound) { /* This is a compound class name that contains namespace prefix */ if (Z_STRVAL(class_name->u.constant)[0] == '\\') { /* The STRING name has "\" prefix */ Z_STRLEN(class_name->u.constant) -= 1; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+1, Z_STRLEN(class_name->u.constant)+1); Z_STRVAL(class_name->u.constant) = erealloc( Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1); if (ZEND_FETCH_CLASS_DEFAULT != zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "'\\%s' is an invalid class name", Z_STRVAL(class_name->u.constant)); } } else { if (CG(current_import)) { len = compound - Z_STRVAL(class_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(class_name->u.constant) -= len; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+len, Z_STRLEN(class_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; efree(lcname); return; } efree(lcname); } /* Here name is not prefixed with \ and not imported */ if (CG(current_namespace)) { tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } } } else if (CG(current_import) || CG(current_namespace)) { /* this is a plain name (without \) */ lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns) == SUCCESS) { /* The given name is an import name. Substitute it. */ zval_dtor(&class_name->u.constant); class_name->u.constant = **ns; zval_copy_ctor(&class_name->u.constant); } else if (CG(current_namespace)) { /* plain name, no import - prepend current namespace to it */ tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } efree(lcname); } } /* }}} */ void zend_do_fetch_class(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { long fetch_class_op_number; zend_op *opline; if (class_name->op_type == IS_CONST && Z_TYPE(class_name->u.constant) == IS_STRING && Z_STRLEN(class_name->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_name->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } fetch_class_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CLASS; SET_UNUSED(opline->op1); opline->extended_value = ZEND_FETCH_CLASS_GLOBAL; CG(catch_begin) = fetch_class_op_number; if (class_name->op_type == IS_CONST) { int fetch_type; fetch_type = zend_get_class_fetch_type(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); switch (fetch_type) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: SET_UNUSED(opline->op2); opline->extended_value = fetch_type; zval_dtor(&class_name->u.constant); break; default: zend_resolve_class_name(class_name, opline->extended_value, 0 TSRMLS_CC); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_name->u.constant TSRMLS_CC); break; } } else { SET_NODE(opline->op2, class_name); } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; /* FIXME: Hack so that INIT_FCALL_BY_NAME still knows this is a class */ GET_NODE(result, opline->result); result->EA = opline->extended_value; } /* }}} */ void zend_do_label(znode *label TSRMLS_DC) /* {{{ */ { zend_label dest; if (!CG(context).labels) { ALLOC_HASHTABLE(CG(context).labels); zend_hash_init(CG(context).labels, 4, NULL, NULL, 0); } dest.brk_cont = CG(context).current_brk_cont; dest.opline_num = get_next_op_number(CG(active_op_array)); if (zend_hash_add(CG(context).labels, Z_STRVAL(label->u.constant), Z_STRLEN(label->u.constant) + 1, (void**)&dest, sizeof(zend_label), NULL) == FAILURE) { zend_error(E_COMPILE_ERROR, "Label '%s' already defined", Z_STRVAL(label->u.constant)); } /* Done with label now */ zval_dtor(&label->u.constant); } /* }}} */ void zend_resolve_goto_label(zend_op_array *op_array, zend_op *opline, int pass2 TSRMLS_DC) /* {{{ */ { zend_label *dest; long current, distance; zval *label; if (pass2) { label = opline->op2.zv; } else { label = &CONSTANT_EX(op_array, opline->op2.constant); } if (CG(context).labels == NULL || zend_hash_find(CG(context).labels, Z_STRVAL_P(label), Z_STRLEN_P(label)+1, (void**)&dest) == FAILURE) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; zend_error(E_COMPILE_ERROR, "'goto' to undefined label '%s'", Z_STRVAL_P(label)); } else { /* Label is not defined. Delay to pass 2. */ INC_BPC(op_array); return; } } opline->op1.opline_num = dest->opline_num; zval_dtor(label); Z_TYPE_P(label) = IS_NULL; /* Check that we are not moving into loop or switch */ current = opline->extended_value; for (distance = 0; current != dest->brk_cont; distance++) { if (current == -1) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; } zend_error(E_COMPILE_ERROR, "'goto' into loop or switch statement is disallowed"); } current = op_array->brk_cont_array[current].parent; } if (distance == 0) { /* Nothing to break out of, optimize to ZEND_JMP */ opline->opcode = ZEND_JMP; opline->extended_value = 0; SET_UNUSED(opline->op2); } else { /* Set real break distance */ ZVAL_LONG(label, distance); } if (pass2) { DEC_BPC(op_array); } } /* }}} */ void zend_do_goto(const znode *label TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_GOTO; opline->extended_value = CG(context).current_brk_cont; SET_UNUSED(opline->op1); SET_NODE(opline->op2, label); zend_resolve_goto_label(CG(active_op_array), opline, 0 TSRMLS_CC); } /* }}} */ void zend_release_labels(TSRMLS_D) /* {{{ */ { if (CG(context).labels) { zend_hash_destroy(CG(context).labels); FREE_HASHTABLE(CG(context).labels); } if (!zend_stack_is_empty(&CG(context_stack))) { zend_compiler_context *ctx; zend_stack_top(&CG(context_stack), (void**)&ctx); CG(context) = *ctx; zend_stack_del_top(&CG(context_stack)); } } /* }}} */ void zend_do_build_full_name(znode *result, znode *prefix, znode *name, int is_class_member TSRMLS_DC) /* {{{ */ { zend_uint length; if (!result) { result = prefix; } else { *result = *prefix; } if (is_class_member) { length = sizeof("::")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "::", sizeof("::")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("::")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } else { length = sizeof("\\")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "\\", sizeof("\\")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("\\")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } } /* }}} */ int zend_do_begin_class_member_function_call(znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { znode class_node; unsigned char *ptr = NULL; zend_op *opline; if (method_name->op_type == IS_CONST) { char *lcname = zend_str_tolower_dup(Z_STRVAL(method_name->u.constant), Z_STRLEN(method_name->u.constant)); if ((sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == Z_STRLEN(method_name->u.constant) && memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == 0) { zval_dtor(&method_name->u.constant); method_name->op_type = IS_UNUSED; } efree(lcname); } if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; opline = get_next_op(CG(active_op_array) TSRMLS_CC); } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->extended_value = class_node.EA ; } opline->opcode = ZEND_INIT_STATIC_METHOD_CALL; if (class_node.op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, &class_node); } if (method_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &method_name->u.constant TSRMLS_CC); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } } else { SET_NODE(opline->op2, method_name); } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 1; /* Dynamic */ } /* }}} */ void zend_do_end_function_call(znode *function_name, znode *result, const znode *argument_list, int is_method, int is_dynamic_fcall TSRMLS_DC) /* {{{ */ { zend_op *opline; if (is_method && function_name && function_name->op_type == IS_UNUSED) { /* clone */ if (Z_LVAL(argument_list->u.constant) != 0) { zend_error(E_WARNING, "Clone method does not require arguments"); } opline = &CG(active_op_array)->opcodes[Z_LVAL(function_name->u.constant)]; } else { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (!is_method && !is_dynamic_fcall && function_name->op_type==IS_CONST) { opline->opcode = ZEND_DO_FCALL; SET_NODE(opline->op1, function_name); CALCULATE_LITERAL_HASH(opline->op1.constant); GET_CACHE_SLOT(opline->op1.constant); } else { opline->opcode = ZEND_DO_FCALL_BY_NAME; SET_UNUSED(opline->op1); } } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(result, opline->result) ; SET_UNUSED(opline->op2); zend_stack_del_top(&CG(function_call_stack)); opline->extended_value = Z_LVAL(argument_list->u.constant); } /* }}} */ void zend_do_pass_param(znode *param, zend_uchar op, int offset TSRMLS_DC) /* {{{ */ { zend_op *opline; int original_op=op; zend_function **function_ptr_ptr, *function_ptr; int send_by_reference; int send_function = 0; zend_stack_top(&CG(function_call_stack), (void **) &function_ptr_ptr); function_ptr = *function_ptr_ptr; if (original_op == ZEND_SEND_REF) { if (function_ptr && function_ptr->common.function_name && function_ptr->common.type == ZEND_USER_FUNCTION && !ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed; " "If you would like to pass argument by reference, modify the declaration of %s().", function_ptr->common.function_name); } else { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed"); } return; } if (function_ptr) { if (ARG_MAY_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { if (param->op_type & (IS_VAR|IS_CV) && original_op != ZEND_SEND_VAL) { send_by_reference = 1; if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION | ZEND_ARG_SEND_SILENT; } } else { op = ZEND_SEND_VAL; send_by_reference = 0; } } else { send_by_reference = ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset) ? ZEND_ARG_SEND_BY_REF : 0; } } else { send_by_reference = 0; } if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION; } else if (op == ZEND_SEND_VAL && (param->op_type & (IS_VAR|IS_CV))) { op = ZEND_SEND_VAR_NO_REF; } if (op!=ZEND_SEND_VAR_NO_REF && send_by_reference==ZEND_ARG_SEND_BY_REF) { /* change to passing by reference */ switch (param->op_type) { case IS_VAR: case IS_CV: op = ZEND_SEND_REF; break; default: zend_error(E_COMPILE_ERROR, "Only variables can be passed by reference"); break; } } if (original_op == ZEND_SEND_VAR) { switch (op) { case ZEND_SEND_VAR_NO_REF: zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); break; case ZEND_SEND_VAR: if (function_ptr) { zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(param, BP_VAR_FUNC_ARG, offset TSRMLS_CC); } break; case ZEND_SEND_REF: zend_do_end_variable_parse(param, BP_VAR_W, 0 TSRMLS_CC); break; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (op == ZEND_SEND_VAR_NO_REF) { if (function_ptr) { opline->extended_value = ZEND_ARG_COMPILE_TIME_BOUND | send_by_reference | send_function; } else { opline->extended_value = send_function; } } else { if (function_ptr) { opline->extended_value = ZEND_DO_FCALL; } else { opline->extended_value = ZEND_DO_FCALL_BY_NAME; } } opline->opcode = op; SET_NODE(opline->op1, param); opline->op2.opline_num = offset; SET_UNUSED(opline->op2); } /* }}} */ static int generate_free_switch_expr(const zend_switch_entry *switch_entry TSRMLS_DC) /* {{{ */ { zend_op *opline; if (switch_entry->cond.op_type != IS_VAR && switch_entry->cond.op_type != IS_TMP_VAR) { return (switch_entry->cond.op_type == IS_UNUSED); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry->cond); SET_UNUSED(opline->op2); opline->extended_value = 0; return 0; } /* }}} */ static int generate_free_foreach_copy(const zend_op *foreach_copy TSRMLS_DC) /* {{{ */ { zend_op *opline; /* If we reach the seperator then stop applying the stack */ if (foreach_copy->result_type == IS_UNUSED && foreach_copy->op1_type == IS_UNUSED) { return 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->result_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->result); SET_UNUSED(opline->op2); opline->extended_value = 1; if (foreach_copy->op1_type != IS_UNUSED) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->op1_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->op1); SET_UNUSED(opline->op2); opline->extended_value = 0; } return 0; } /* }}} */ void zend_do_return(znode *expr, int do_end_vparse TSRMLS_DC) /* {{{ */ { zend_op *opline; int start_op_number, end_op_number; if (do_end_vparse) { if ((CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) && !zend_is_function_or_method_call(expr)) { zend_do_end_variable_parse(expr, BP_VAR_W, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(expr, BP_VAR_R, 0 TSRMLS_CC); } } start_op_number = get_next_op_number(CG(active_op_array)); #ifdef ZTS zend_stack_apply_with_argument(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_switch_expr TSRMLS_CC); zend_stack_apply_with_argument(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_foreach_copy TSRMLS_CC); #else zend_stack_apply(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_switch_expr); zend_stack_apply(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_foreach_copy); #endif end_op_number = get_next_op_number(CG(active_op_array)); while (start_op_number < end_op_number) { CG(active_op_array)->opcodes[start_op_number].extended_value |= EXT_TYPE_FREE_ON_RETURN; start_op_number++; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) ? ZEND_RETURN_BY_REF : ZEND_RETURN; if (expr) { SET_NODE(opline->op1, expr); if (do_end_vparse && zend_is_function_or_method_call(expr)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } } else { opline->op1_type = IS_CONST; LITERAL_NULL(opline->op1); } SET_UNUSED(opline->op2); } /* }}} */ static int zend_add_try_element(zend_uint try_op TSRMLS_DC) /* {{{ */ { int try_catch_offset = CG(active_op_array)->last_try_catch++; CG(active_op_array)->try_catch_array = erealloc(CG(active_op_array)->try_catch_array, sizeof(zend_try_catch_element)*CG(active_op_array)->last_try_catch); CG(active_op_array)->try_catch_array[try_catch_offset].try_op = try_op; return try_catch_offset; } /* }}} */ static void zend_add_catch_element(int offset, zend_uint catch_op TSRMLS_DC) /* {{{ */ { CG(active_op_array)->try_catch_array[offset].catch_op = catch_op; } /* }}} */ void zend_do_first_catch(znode *open_parentheses TSRMLS_DC) /* {{{ */ { open_parentheses->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_initialize_try_catch_element(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist jmp_list; zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); zend_add_catch_element(try_token->u.op.opline_num, get_next_op_number(CG(active_op_array)) TSRMLS_CC); } /* }}} */ void zend_do_mark_last_catch(const znode *first_catch, const znode *last_additional_catch TSRMLS_DC) /* {{{ */ { CG(active_op_array)->last--; zend_do_if_end(TSRMLS_C); if (last_additional_catch->u.op.opline_num == -1) { CG(active_op_array)->opcodes[first_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[first_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } else { CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_try(znode *try_token TSRMLS_DC) /* {{{ */ { try_token->u.op.opline_num = zend_add_try_element(get_next_op_number(CG(active_op_array)) TSRMLS_CC); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_catch(znode *try_token, znode *class_name, znode *catch_var, znode *first_catch TSRMLS_DC) /* {{{ */ { long catch_op_number; zend_op *opline; znode catch_class; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); catch_class = *class_name; } else { zend_error(E_COMPILE_ERROR, "Bad class name in the catch statement"); } catch_op_number = get_next_op_number(CG(active_op_array)); if (first_catch) { first_catch->u.op.opline_num = catch_op_number; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CATCH; opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &catch_class.u.constant TSRMLS_CC); opline->op2_type = IS_CV; opline->op2.var = lookup_cv(CG(active_op_array), catch_var->u.constant.value.str.val, catch_var->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(catch_var->u.constant) = (char*)CG(active_op_array)->vars[opline->op2.var].name; opline->result.num = 0; /* 1 means it's the last catch in the block */ try_token->u.op.opline_num = catch_op_number; } /* }}} */ void zend_do_end_catch(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); CG(active_op_array)->opcodes[try_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_throw(const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_THROW; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); } /* }}} */ ZEND_API void function_add_ref(zend_function *function) /* {{{ */ { if (function->type == ZEND_USER_FUNCTION) { zend_op_array *op_array = &function->op_array; (*op_array->refcount)++; if (op_array->static_variables) { HashTable *static_variables = op_array->static_variables; zval *tmp_zval; ALLOC_HASHTABLE(op_array->static_variables); zend_hash_init(op_array->static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(op_array->static_variables, static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_zval, sizeof(zval *)); } op_array->run_time_cache = NULL; } } /* }}} */ static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */ { zend_function *function; if (!ce->parent) { return; } /* You cannot change create_object */ ce->create_object = ce->parent->create_object; /* Inherit special functions if needed */ if (!ce->get_iterator) { ce->get_iterator = ce->parent->get_iterator; } if (!ce->iterator_funcs.funcs) { ce->iterator_funcs.funcs = ce->parent->iterator_funcs.funcs; } if (!ce->__get) { ce->__get = ce->parent->__get; } if (!ce->__set) { ce->__set = ce->parent->__set; } if (!ce->__unset) { ce->__unset = ce->parent->__unset; } if (!ce->__isset) { ce->__isset = ce->parent->__isset; } if (!ce->__call) { ce->__call = ce->parent->__call; } if (!ce->__callstatic) { ce->__callstatic = ce->parent->__callstatic; } if (!ce->__tostring) { ce->__tostring = ce->parent->__tostring; } if (!ce->clone) { ce->clone = ce->parent->clone; } if(!ce->serialize) { ce->serialize = ce->parent->serialize; } if(!ce->unserialize) { ce->unserialize = ce->parent->unserialize; } if (!ce->destructor) { ce->destructor = ce->parent->destructor; } if (ce->constructor) { if (ce->parent->constructor && ce->parent->constructor->common.fn_flags & ZEND_ACC_FINAL) { zend_error(E_ERROR, "Cannot override final %s::%s() with %s::%s()", ce->parent->name, ce->parent->constructor->common.function_name, ce->name, ce->constructor->common.function_name ); } return; } if (zend_hash_find(&ce->parent->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), (void **)&function)==SUCCESS) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), function, sizeof(zend_function), NULL); function_add_ref(function); } else { /* Don't inherit the old style constructor if we already have the new style constructor */ char *lc_class_name; char *lc_parent_class_name; lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); if (!zend_hash_exists(&ce->function_table, lc_class_name, ce->name_length+1)) { lc_parent_class_name = zend_str_tolower_dup(ce->parent->name, ce->parent->name_length); if (!zend_hash_exists(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1) && zend_hash_find(&ce->parent->function_table, lc_parent_class_name, ce->parent->name_length+1, (void **)&function)==SUCCESS) { if (function->common.fn_flags & ZEND_ACC_CTOR) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1, function, sizeof(zend_function), NULL); function_add_ref(function); } } efree(lc_parent_class_name); } efree(lc_class_name); } ce->constructor = ce->parent->constructor; } /* }}} */ char *zend_visibility_string(zend_uint fn_flags) /* {{{ */ { if (fn_flags & ZEND_ACC_PRIVATE) { return "private"; } if (fn_flags & ZEND_ACC_PROTECTED) { return "protected"; } if (fn_flags & ZEND_ACC_PUBLIC) { return "public"; } return ""; } /* }}} */ static void do_inherit_method(zend_function *function) /* {{{ */ { /* The class entry of the derived function intentionally remains the same * as that of the parent class. That allows us to know in which context * we're running, and handle private method calls properly. */ function_add_ref(function); } /* }}} */ static zend_bool zend_do_perform_implementation_check(const zend_function *fe, const zend_function *proto TSRMLS_DC) /* {{{ */ { zend_uint i; /* If it's a user function then arg_info == NULL means we don't have any parameters but * we still need to do the arg number checks. We are only willing to ignore this for internal * functions because extensions don't always define arg_info. */ if (!proto || (!proto->common.arg_info && proto->common.type != ZEND_USER_FUNCTION)) { return 1; } /* Checks for constructors only if they are declared in an interface, * or explicitly marked as abstract */ if ((fe->common.fn_flags & ZEND_ACC_CTOR) && ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)) { return 1; } /* check number of arguments */ if (proto->common.required_num_args < fe->common.required_num_args || proto->common.num_args > fe->common.num_args) { return 0; } if (fe->common.type != ZEND_USER_FUNCTION && (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) != 0 && (fe->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) == 0) { return 0; } /* by-ref constraints on return values are covariant */ if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) { return 0; } for (i=0; i < proto->common.num_args; i++) { if (ZEND_LOG_XOR(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)) { /* Only one has a type hint and the other one doesn't */ return 0; } if (fe->common.arg_info[i].class_name && strcasecmp(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)!=0) { const char *colon; if (fe->common.type != ZEND_USER_FUNCTION) { return 0; } else if (strchr(proto->common.arg_info[i].class_name, '\\') != NULL || (colon = zend_memrchr(fe->common.arg_info[i].class_name, '\\', fe->common.arg_info[i].class_name_len)) == NULL || strcasecmp(colon+1, proto->common.arg_info[i].class_name) != 0) { zend_class_entry **fe_ce, **proto_ce; int found, found2; found = zend_lookup_class(fe->common.arg_info[i].class_name, fe->common.arg_info[i].class_name_len, &fe_ce TSRMLS_CC); found2 = zend_lookup_class(proto->common.arg_info[i].class_name, proto->common.arg_info[i].class_name_len, &proto_ce TSRMLS_CC); /* Check for class alias */ if (found != SUCCESS || found2 != SUCCESS || (*fe_ce)->type == ZEND_INTERNAL_CLASS || (*proto_ce)->type == ZEND_INTERNAL_CLASS || *fe_ce != *proto_ce) { return 0; } } } if (fe->common.arg_info[i].type_hint != proto->common.arg_info[i].type_hint) { /* Incompatible type hint */ return 0; } /* by-ref constraints on arguments are invariant */ if (fe->common.arg_info[i].pass_by_reference != proto->common.arg_info[i].pass_by_reference) { return 0; } } if (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) { for (i=proto->common.num_args; i < fe->common.num_args; i++) { if (!fe->common.arg_info[i].pass_by_reference) { return 0; } } } return 1; } /* }}} */ #define REALLOC_BUF_IF_EXCEED(buf, offset, length, size) \ if (UNEXPECTED(offset - buf + size >= length)) { \ length += size + 1; \ buf = erealloc(buf, length); \ } static char * zend_get_function_declaration(zend_function *fptr TSRMLS_DC) /* {{{ */ { char *offset, *buf; zend_uint length = 1024; offset = buf = (char *)emalloc(length * sizeof(char)); if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { *(offset++) = '&'; *(offset++) = ' '; } if (fptr->common.scope) { memcpy(offset, fptr->common.scope->name, fptr->common.scope->name_length); offset += fptr->common.scope->name_length; *(offset++) = ':'; *(offset++) = ':'; } { size_t name_len = strlen(fptr->common.function_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, name_len); memcpy(offset, fptr->common.function_name, name_len); offset += name_len; } *(offset++) = '('; if (fptr->common.arg_info) { zend_uint i, required; zend_arg_info *arg_info = fptr->common.arg_info; required = fptr->common.required_num_args; for (i = 0; i < fptr->common.num_args;) { if (arg_info->class_name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->class_name_len); memcpy(offset, arg_info->class_name, arg_info->class_name_len); offset += arg_info->class_name_len; *(offset++) = ' '; } else if (arg_info->type_hint) { zend_uint type_name_len; char *type_name = zend_get_type_by_const(arg_info->type_hint); type_name_len = strlen(type_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, type_name_len); memcpy(offset, type_name, type_name_len); offset += type_name_len; *(offset++) = ' '; } if (arg_info->pass_by_reference) { *(offset++) = '&'; } *(offset++) = '$'; if (arg_info->name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->name_len); memcpy(offset, arg_info->name, arg_info->name_len); offset += arg_info->name_len; } else { zend_uint idx = i; memcpy(offset, "param", 5); offset += 5; do { *(offset++) = (char) (idx % 10) + '0'; idx /= 10; } while (idx > 0); } if (i >= required) { *(offset++) = ' '; *(offset++) = '='; *(offset++) = ' '; if (fptr->type == ZEND_USER_FUNCTION) { zend_op *precv = NULL; { zend_uint idx = i; zend_op *op = ((zend_op_array *)fptr)->opcodes; zend_op *end = op + ((zend_op_array *)fptr)->last; ++idx; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT) && op->op1.num == (long)idx) { precv = op; } ++op; } } if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) { zval *zv, zv_copy; int use_copy; ALLOC_ZVAL(zv); *zv = *precv->op2.zv; zval_copy_ctor(zv); INIT_PZVAL(zv); zval_update_constant_ex(&zv, (void*)1, fptr->common.scope TSRMLS_CC); if (Z_TYPE_P(zv) == IS_BOOL) { if (Z_LVAL_P(zv)) { memcpy(offset, "true", 4); offset += 4; } else { memcpy(offset, "false", 5); offset += 5; } } else if (Z_TYPE_P(zv) == IS_NULL) { memcpy(offset, "NULL", 4); offset += 4; } else if (Z_TYPE_P(zv) == IS_STRING) { *(offset++) = '\''; REALLOC_BUF_IF_EXCEED(buf, offset, length, MIN(Z_STRLEN_P(zv), 10)); memcpy(offset, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 10)); offset += MIN(Z_STRLEN_P(zv), 10); if (Z_STRLEN_P(zv) > 10) { *(offset++) = '.'; *(offset++) = '.'; *(offset++) = '.'; } *(offset++) = '\''; } else { zend_make_printable_zval(zv, &zv_copy, &use_copy); REALLOC_BUF_IF_EXCEED(buf, offset, length, Z_STRLEN(zv_copy)); memcpy(offset, Z_STRVAL(zv_copy), Z_STRLEN(zv_copy)); offset += Z_STRLEN(zv_copy); if (use_copy) { zval_dtor(&zv_copy); } } zval_ptr_dtor(&zv); } } else { memcpy(offset, "NULL", 4); offset += 4; } } if (++i < fptr->common.num_args) { *(offset++) = ','; *(offset++) = ' '; } arg_info++; REALLOC_BUF_IF_EXCEED(buf, offset, length, 23); } } *(offset++) = ')'; *offset = '\0'; return buf; } /* }}} */ static void do_inheritance_check_on_method(zend_function *child, zend_function *parent TSRMLS_DC) /* {{{ */ { zend_uint child_flags; zend_uint parent_flags = parent->common.fn_flags; if (parent->common.fn_flags & ZEND_ACC_ABSTRACT && parent->common.scope != (child->common.prototype ? child->common.prototype->common.scope : child->common.scope) && child->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_IMPLEMENTED_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Can't inherit abstract function %s::%s() (previously declared abstract in %s)", parent->common.scope->name, child->common.function_name, child->common.prototype ? child->common.prototype->common.scope->name : child->common.scope->name); } if (parent_flags & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot override final method %s::%s()", ZEND_FN_SCOPE_NAME(parent), child->common.function_name); } child_flags = child->common.fn_flags; /* You cannot change from static to non static and vice versa. */ if ((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC)) { if (child->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot make non static method %s::%s() static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } else { zend_error(E_COMPILE_ERROR, "Cannot make static method %s::%s() non static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } } /* Disallow making an inherited method abstract. */ if ((child_flags & ZEND_ACC_ABSTRACT) && !(parent_flags & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Cannot make non abstract method %s::%s() abstract in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } if (parent_flags & ZEND_ACC_CHANGED) { child->common.fn_flags |= ZEND_ACC_CHANGED; } else { /* Prevent derived classes from restricting access that was available in parent classes */ if ((child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::%s() must be %s (as in class %s)%s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if (((child_flags & ZEND_ACC_PPP_MASK) < (parent_flags & ZEND_ACC_PPP_MASK)) && ((parent_flags & ZEND_ACC_PPP_MASK) & ZEND_ACC_PRIVATE)) { child->common.fn_flags |= ZEND_ACC_CHANGED; } } if (parent_flags & ZEND_ACC_PRIVATE) { child->common.prototype = NULL; } else if (parent_flags & ZEND_ACC_ABSTRACT) { child->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; child->common.prototype = parent; } else if (!(parent->common.fn_flags & ZEND_ACC_CTOR) || (parent->common.prototype && (parent->common.prototype->common.scope->ce_flags & ZEND_ACC_INTERFACE))) { /* ctors only have a prototype if it comes from an interface */ child->common.prototype = parent->common.prototype ? parent->common.prototype : parent; } if (child->common.prototype && (child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { if (!zend_do_perform_implementation_check(child, child->common.prototype TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s::%s() must be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_get_function_declaration(child->common.prototype TSRMLS_CC)); } } else if (EG(error_reporting) & E_STRICT || EG(user_error_handler)) { /* Check E_STRICT (or custom error handler) before the check so that we save some time */ if (!zend_do_perform_implementation_check(child, parent TSRMLS_CC)) { char *method_prototype = zend_get_function_declaration(child->common.prototype TSRMLS_CC); zend_error(E_STRICT, "Declaration of %s::%s() should be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, method_prototype); efree(method_prototype); } } } /* }}} */ static zend_bool do_inherit_method_check(HashTable *child_function_table, zend_function *parent, const zend_hash_key *hash_key, zend_class_entry *child_ce) /* {{{ */ { zend_uint parent_flags = parent->common.fn_flags; zend_function *child; TSRMLS_FETCH(); if (zend_hash_quick_find(child_function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child)==FAILURE) { if (parent_flags & (ZEND_ACC_ABSTRACT)) { child_ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } return 1; /* method doesn't exist in child, copy from parent */ } do_inheritance_check_on_method(child, parent TSRMLS_CC); return 0; } /* }}} */ static zend_bool do_inherit_property_access_check(HashTable *target_ht, zend_property_info *parent_info, const zend_hash_key *hash_key, zend_class_entry *ce) /* {{{ */ { zend_property_info *child_info; zend_class_entry *parent_ce = ce->parent; if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW)) { if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { child_info->flags |= ZEND_ACC_CHANGED; } else { zend_hash_quick_update(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, parent_info, sizeof(zend_property_info), (void **) &child_info); if(ce->type & ZEND_INTERNAL_CLASS) { zend_duplicate_property_info_internal(child_info); } else { zend_duplicate_property_info(child_info); } child_info->flags &= ~ZEND_ACC_PRIVATE; /* it's not private anymore */ child_info->flags |= ZEND_ACC_SHADOW; /* but it's a shadow of private */ } return 0; /* don't copy access information to child */ } if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { if ((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s", (parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", parent_ce->name, hash_key->arKey, (child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ce->name, hash_key->arKey); } if(parent_info->flags & ZEND_ACC_CHANGED) { child_info->flags |= ZEND_ACC_CHANGED; } if ((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ce->name, hash_key->arKey, zend_visibility_string(parent_info->flags), parent_ce->name, (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if ((child_info->flags & ZEND_ACC_STATIC) == 0) { Z_DELREF_P(ce->default_properties_table[parent_info->offset]); ce->default_properties_table[parent_info->offset] = ce->default_properties_table[child_info->offset]; ce->default_properties_table[child_info->offset] = NULL; child_info->offset = parent_info->offset; } return 0; /* Don't copy from parent */ } else { return 1; /* Copy from parent */ } } /* }}} */ static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce TSRMLS_CC) == FAILURE) { zend_error(E_CORE_ERROR, "Class %s could not implement interface %s", ce->name, iface->name); } if (ce == iface) { zend_error(E_ERROR, "Interface %s cannot implement itself", ce->name); } } /* }}} */ ZEND_API void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface TSRMLS_DC) /* {{{ */ { /* expects interface to be contained in ce's interface list already */ zend_uint i, ce_num, if_num = iface->num_interfaces; zend_class_entry *entry; if (if_num==0) { return; } ce_num = ce->num_interfaces; if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } /* Inherit the interfaces, only if they're not already inherited by the class */ while (if_num--) { entry = iface->interfaces[if_num]; for (i = 0; i < ce_num; i++) { if (ce->interfaces[i] == entry) { break; } } if (i == ce_num) { ce->interfaces[ce->num_interfaces++] = entry; } } /* and now call the implementing handlers */ while (ce_num < ce->num_interfaces) { do_implement_interface(ce, ce->interfaces[ce_num++] TSRMLS_CC); } } /* }}} */ #ifdef ZTS static void zval_internal_ctor(zval **p) /* {{{ */ { zval *orig_ptr = *p; ALLOC_ZVAL(*p); MAKE_COPY_ZVAL(&orig_ptr, *p); } /* }}} */ # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) (((parent_ce)->type != (ce)->type) ? zval_internal_ctor : zval_add_ref)) #else # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) zval_add_ref) #endif ZEND_API void zend_do_inheritance(zend_class_entry *ce, zend_class_entry *parent_ce TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; if ((ce->ce_flags & ZEND_ACC_INTERFACE) && !(parent_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ce->name, parent_ce->name); } if (parent_ce->ce_flags & ZEND_ACC_FINAL_CLASS) { zend_error(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ce->name, parent_ce->name); } ce->parent = parent_ce; /* Copy serialize/unserialize callbacks */ if (!ce->serialize) { ce->serialize = parent_ce->serialize; } if (!ce->unserialize) { ce->unserialize = parent_ce->unserialize; } /* Inherit interfaces */ zend_do_inherit_interfaces(ce, parent_ce TSRMLS_CC); /* Inherit properties */ if (parent_ce->default_properties_count) { int i = ce->default_properties_count + parent_ce->default_properties_count; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_properties_count) { while (i-- > parent_ce->default_properties_count) { ce->default_properties_table[i] = ce->default_properties_table[i - parent_ce->default_properties_count]; } } for (i = 0; i < parent_ce->default_properties_count; i++) { ce->default_properties_table[i] = parent_ce->default_properties_table[i]; if (ce->default_properties_table[i]) { #ifdef ZTS if (parent_ce->type != ce->type) { zval *p; ALLOC_ZVAL(p); MAKE_COPY_ZVAL(&ce->default_properties_table[i], p); ce->default_properties_table[i] = p; } else { Z_ADDREF_P(ce->default_properties_table[i]); } #else Z_ADDREF_P(ce->default_properties_table[i]); #endif } } ce->default_properties_count += parent_ce->default_properties_count; } if (parent_ce->type != ce->type) { /* User class extends internal class */ zend_update_class_constants(parent_ce TSRMLS_CC); if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = erealloc(ce->default_static_members_table, sizeof(void*) * i); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&CE_STATIC_MEMBERS(parent_ce)[i]); ce->default_static_members_table[i] = CE_STATIC_MEMBERS(parent_ce)[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; ce->static_members_table = ce->default_static_members_table; } } else { if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&parent_ce->default_static_members_table[i]); ce->default_static_members_table[i] = parent_ce->default_static_members_table[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } } for (zend_hash_internal_pointer_reset(&ce->properties_info); zend_hash_get_current_data(&ce->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->properties_info)) { if (property_info->ce == ce) { if (property_info->flags & ZEND_ACC_STATIC) { property_info->offset += parent_ce->default_static_members_count; } else { property_info->offset += parent_ce->default_properties_count; } } } zend_hash_merge_ex(&ce->properties_info, &parent_ce->properties_info, (copy_ctor_func_t) (ce->type & ZEND_INTERNAL_CLASS ? zend_duplicate_property_info_internal : zend_duplicate_property_info), sizeof(zend_property_info), (merge_checker_func_t) do_inherit_property_access_check, ce); zend_hash_merge(&ce->constants_table, &parent_ce->constants_table, zval_property_ctor(parent_ce, ce), NULL, sizeof(zval *), 0); zend_hash_merge_ex(&ce->function_table, &parent_ce->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_inherit_parent_constructor(ce); if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS && ce->type == ZEND_INTERNAL_CLASS) { ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } else if (!(ce->ce_flags & ZEND_ACC_IMPLEMENT_INTERFACES) && !(ce->ce_flags & ZEND_ACC_IMPLEMENT_TRAITS)) { /* The verification will be done in runtime by ZEND_VERIFY_ABSTRACT_CLASS */ zend_verify_abstract_class(ce TSRMLS_CC); } ce->ce_flags |= parent_ce->ce_flags & ZEND_HAS_STATIC_IN_METHODS; } /* }}} */ static zend_bool do_inherit_constant_check(HashTable *child_constants_table, const zval **parent_constant, const zend_hash_key *hash_key, const zend_class_entry *iface) /* {{{ */ { zval **old_constant; if (zend_hash_quick_find(child_constants_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**)&old_constant) == SUCCESS) { if (*old_constant != *parent_constant) { zend_error(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", hash_key->arKey, iface->name); } return 0; } return 1; } /* }}} */ static int do_interface_constant_check(zval **val TSRMLS_DC, int num_args, va_list args, const zend_hash_key *key) /* {{{ */ { zend_class_entry **iface = va_arg(args, zend_class_entry**); do_inherit_constant_check(&(*iface)->constants_table, (const zval **) val, key, *iface); return ZEND_HASH_APPLY_KEEP; } /* }}} */ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_iface_num = ce->num_interfaces; zend_uint parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0; for (i = 0; i < ce->num_interfaces; i++) { if (ce->interfaces[i] == NULL) { memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i)); i--; } else if (ce->interfaces[i] == iface) { if (i < parent_iface_num) { ignore = 1; } else { zend_error(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ce->name, iface->name); } } } if (ignore) { /* Check for attempt to redeclare interface constants */ zend_hash_apply_with_arguments(&ce->constants_table TSRMLS_CC, (apply_func_args_t) do_interface_constant_check, 1, &iface); } else { if (ce->num_interfaces >= current_iface_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } } ce->interfaces[ce->num_interfaces++] = iface; zend_hash_merge_ex(&ce->constants_table, &iface->constants_table, (copy_ctor_func_t) zval_add_ref, sizeof(zval *), (merge_checker_func_t) do_inherit_constant_check, iface); zend_hash_merge_ex(&ce->function_table, &iface->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_implement_interface(ce, iface TSRMLS_CC); zend_do_inherit_interfaces(ce, iface TSRMLS_CC); } } /* }}} */ ZEND_API void zend_do_implement_trait(zend_class_entry *ce, zend_class_entry *trait TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_trait_num = ce->num_traits; zend_uint parent_trait_num = ce->parent ? ce->parent->num_traits : 0; for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == NULL) { memmove(ce->traits + i, ce->traits + i + 1, sizeof(zend_class_entry*) * (--ce->num_traits - i)); i--; } else if (ce->traits[i] == trait) { if (i < parent_trait_num) { ignore = 1; } } } if (!ignore) { if (ce->num_traits >= current_trait_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->traits = (zend_class_entry **) realloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } else { ce->traits = (zend_class_entry **) erealloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } } ce->traits[ce->num_traits++] = trait; } } /* }}} */ static int zend_traits_merge_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { size_t current; size_t i; size_t count; HashTable* resulting_table; HashTable** function_tables; zend_class_entry *ce; size_t collision = 0; size_t abstract_solved = 0; zend_function* other_trait_fn; current = va_arg(args, size_t); /* index of current trait */ count = va_arg(args, size_t); resulting_table = va_arg(args, HashTable*); function_tables = va_arg(args, HashTable**); ce = va_arg(args, zend_class_entry*); for (i = 0; i < count; i++) { if (i == current) { continue; /* just skip this, cause its the table this function is applied on */ } if (zend_hash_quick_find(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&other_trait_fn) == SUCCESS) { /* if it is an abstract method, there is no collision */ if (other_trait_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* we can savely free and remove it from other table */ zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } else { /* if it is not an abstract method, there is still no collision */ /* if fn is an abstract method */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* just mark as solved, will be added if its own trait is processed */ abstract_solved = 1; } else { /* but else, we have a collision of non-abstract methods */ collision++; zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } } } if (collision) { zend_function* class_fn; /* make sure method is not already overridden in class */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&class_fn) == FAILURE || class_fn->common.scope != ce) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because there are collisions with other trait methods on %s", fn->common.function_name, ce->name); } zend_function_dtor(fn); } else if (abstract_solved) { zend_function_dtor(fn); } else { /* Add it to result function table */ if (zend_hash_quick_add(resulting_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, fn, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating resulting trait method table", fn->common.function_name); } } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ /* {{{ Originates from php_runkit_function_copy_ctor Duplicate structures in an op_array where necessary to make an outright duplicate */ static void zend_traits_duplicate_function(zend_function *fe, zend_class_entry *target_ce, char *newname TSRMLS_DC) { zend_literal *literals_copy; zend_compiled_variable *dupvars; zend_op *opcode_copy; zval class_name_zv; int class_name_literal; int i; int number_of_literals; if (fe->op_array.static_variables) { HashTable *tmpHash; ALLOC_HASHTABLE(tmpHash); zend_hash_init(tmpHash, zend_hash_num_elements(fe->op_array.static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_apply_with_arguments(fe->op_array.static_variables TSRMLS_CC, (apply_func_args_t)zval_copy_static_var, 1, tmpHash); fe->op_array.static_variables = tmpHash; } number_of_literals = fe->op_array.last_literal; literals_copy = (zend_literal*)emalloc(number_of_literals * sizeof(zend_literal)); for (i = 0; i < number_of_literals; i++) { literals_copy[i] = fe->op_array.literals[i]; zval_copy_ctor(&literals_copy[i].constant); } fe->op_array.literals = literals_copy; fe->op_array.refcount = emalloc(sizeof(zend_uint)); *(fe->op_array.refcount) = 1; if (fe->op_array.vars) { i = fe->op_array.last_var; dupvars = safe_emalloc(fe->op_array.last_var, sizeof(zend_compiled_variable), 0); while (i > 0) { i--; dupvars[i].name = estrndup(fe->op_array.vars[i].name, fe->op_array.vars[i].name_len); dupvars[i].name_len = fe->op_array.vars[i].name_len; dupvars[i].hash_value = fe->op_array.vars[i].hash_value; } fe->op_array.vars = dupvars; } else { fe->op_array.vars = NULL; } opcode_copy = safe_emalloc(sizeof(zend_op), fe->op_array.last, 0); for(i = 0; i < fe->op_array.last; i++) { opcode_copy[i] = fe->op_array.opcodes[i]; if (opcode_copy[i].op1_type != IS_CONST) { if (opcode_copy[i].op1.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op1.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op1.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op1.jmp_addr - fe->op_array.opcodes); } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op1.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op1.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op1.zv = &fe->op_array.literals[class_name_literal].constant; } } if (opcode_copy[i].op2_type != IS_CONST) { if (opcode_copy[i].op2.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op2.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op2.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op2.jmp_addr - fe->op_array.opcodes); } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op2.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op2.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op2.zv = &fe->op_array.literals[class_name_literal].constant; } } } fe->op_array.opcodes = opcode_copy; fe->op_array.function_name = newname; /* was setting it to fe which does not work since fe is stack allocated and not a stable address */ /* fe->op_array.prototype = fe->op_array.prototype; */ if (fe->op_array.arg_info) { zend_arg_info *tmpArginfo; tmpArginfo = safe_emalloc(sizeof(zend_arg_info), fe->op_array.num_args, 0); for(i = 0; i < fe->op_array.num_args; i++) { tmpArginfo[i] = fe->op_array.arg_info[i]; tmpArginfo[i].name = estrndup(tmpArginfo[i].name, tmpArginfo[i].name_len); if (tmpArginfo[i].class_name) { tmpArginfo[i].class_name = estrndup(tmpArginfo[i].class_name, tmpArginfo[i].class_name_len); } } fe->op_array.arg_info = tmpArginfo; } fe->op_array.doc_comment = estrndup(fe->op_array.doc_comment, fe->op_array.doc_comment_len); fe->op_array.try_catch_array = (zend_try_catch_element*)estrndup((char*)fe->op_array.try_catch_array, sizeof(zend_try_catch_element) * fe->op_array.last_try_catch); fe->op_array.brk_cont_array = (zend_brk_cont_element*)estrndup((char*)fe->op_array.brk_cont_array, sizeof(zend_brk_cont_element) * fe->op_array.last_brk_cont); } /* }}} */ static void zend_add_magic_methods(zend_class_entry* ce, const char* mname, uint mname_len, zend_function* fe TSRMLS_DC) { if ( !strncmp(mname, ZEND_CLONE_FUNC_NAME, mname_len)) { ce->clone = fe; fe->common.fn_flags |= ZEND_ACC_CLONE; } else if (!strncmp(mname, ZEND_CONSTRUCTOR_FUNC_NAME, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } else if (!strncmp(mname, ZEND_DESTRUCTOR_FUNC_NAME, mname_len)) { ce->destructor = fe; fe->common.fn_flags |= ZEND_ACC_DTOR; } else if (!strncmp(mname, ZEND_GET_FUNC_NAME, mname_len)) ce->__get = fe; else if (!strncmp(mname, ZEND_SET_FUNC_NAME, mname_len)) ce->__set = fe; else if (!strncmp(mname, ZEND_CALL_FUNC_NAME, mname_len)) ce->__call = fe; else if (!strncmp(mname, ZEND_UNSET_FUNC_NAME, mname_len)) ce->__unset = fe; else if (!strncmp(mname, ZEND_ISSET_FUNC_NAME, mname_len)) ce->__isset = fe; else if (!strncmp(mname, ZEND_CALLSTATIC_FUNC_NAME, mname_len)) ce->__callstatic= fe; else if (!strncmp(mname, ZEND_TOSTRING_FUNC_NAME, mname_len)) ce->__tostring = fe; else if (ce->name_length + 1 == mname_len) { char *lowercase_name = emalloc(ce->name_length + 1); zend_str_tolower_copy(lowercase_name, ce->name, ce->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, ce->name_length + 1, 1 TSRMLS_CC); if (!memcmp(mname, lowercase_name, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } str_efree(lowercase_name); } } static int zend_traits_merge_functions_to_class(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zend_class_entry *ce = va_arg(args, zend_class_entry*); int add = 0; zend_function* existing_fn; zend_function fn_copy, *fn_copy_p; zend_function* prototype = NULL; /* is used to determine the prototype according to the inheritance chain */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &existing_fn) == FAILURE) { add = 1; /* not found */ } else if (existing_fn->common.scope != ce) { add = 1; /* or inherited from other class or interface */ /* it is just a reference which was added to the subclass while doing the inheritance */ /* so we can deleted now, and will add the overriding method afterwards */ /* except, if we try to add an abstract function, then we should not delete the inherited one */ /* delete inherited fn if the function to be added is not abstract */ if ((fn->common.fn_flags & ZEND_ACC_ABSTRACT) == 0) { zend_hash_quick_del(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } if (add) { zend_function* parent_function; if (ce->parent && zend_hash_quick_find(&ce->parent->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &parent_function) != FAILURE) { prototype = parent_function; /* ->common.fn_flags |= ZEND_ACC_ABSTRACT; */ /* we got that method in the parent class, and are going to override it, except, if the trait is just asking to have an abstract method implemented. */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* then we clean up an skip this method */ zend_function_dtor(fn); return ZEND_HASH_APPLY_REMOVE; } } fn->common.scope = ce; fn->common.prototype = prototype; if (prototype && (prototype->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT || prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { fn->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; } else if (fn->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT) { /* remove ZEND_ACC_IMPLEMENTED_ABSTRACT flag, think it shouldn't be copied to class */ fn->common.fn_flags = fn->common.fn_flags - ZEND_ACC_IMPLEMENTED_ABSTRACT; } /* check whether the trait method fullfills the inheritance requirements */ if (prototype) { do_inheritance_check_on_method(fn, prototype TSRMLS_CC); } if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (fn->op_array.static_variables) { ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, ce, estrdup(fn->common.function_name) TSRMLS_CC); if (zend_hash_quick_update(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, &fn_copy, sizeof(zend_function), (void**)&fn_copy_p)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating class method table", hash_key->arKey); } zend_add_magic_methods(ce, hash_key->arKey, hash_key->nKeyLength, fn_copy_p TSRMLS_CC); zend_function_dtor(fn); } else { zend_function_dtor(fn); } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ static int zend_traits_copy_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { HashTable* target; zend_class_entry *target_ce; zend_trait_alias** aliases; HashTable* exclude_table; char* lcname; unsigned int fnname_len; zend_function fn_copy; void* dummy; size_t i = 0; target = va_arg(args, HashTable*); target_ce = va_arg(args, zend_class_entry*); aliases = va_arg(args, zend_trait_alias**); exclude_table = va_arg(args, HashTable*); fnname_len = strlen(fn->common.function_name); /* apply aliases which are qualified with a class name, there should not be any ambiguity */ if (aliases) { while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias != NULL && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && aliases[i]->trait_method->mname_len == fnname_len && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(aliases[i]->alias, aliases[i]->alias_len) TSRMLS_CC); /* if it is 0, no modifieres has been changed */ if (aliases[i]->modifiers) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } lcname = zend_str_tolower_dup(aliases[i]->alias, aliases[i]->alias_len); if (zend_hash_add(target, lcname, aliases[i]->alias_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add aliased trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } efree(lcname); } i++; } } lcname = zend_str_tolower_dup(fn->common.function_name, fnname_len); if (exclude_table == NULL || zend_hash_find(exclude_table, lcname, fnname_len, &dummy) == FAILURE) { /* is not in hashtable, thus, function is not to be excluded */ fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(fn->common.function_name, fnname_len) TSRMLS_CC); /* apply aliases which are not qualified by a class name, or which have not * alias name, just setting visibility */ if (aliases) { i = 0; while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias == NULL && aliases[i]->modifiers != 0 && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && (aliases[i]->trait_method->mname_len == fnname_len) && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } i++; } } if (zend_hash_add(target, lcname, fnname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } } efree(lcname); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* Copies function table entries to target function table with applied aliasing */ static void zend_traits_copy_trait_function_table(HashTable *target, zend_class_entry *target_ce, HashTable *source, zend_trait_alias** aliases, HashTable* exclude_table TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_arguments(source TSRMLS_CC, (apply_func_args_t)zend_traits_copy_functions, 4, target, target_ce, aliases, exclude_table); } /* }}} */ static void zend_traits_init_trait_structures(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i, j = 0; zend_trait_precedence *cur_precedence; zend_trait_method_reference *cur_method_ref; /* resolve class references */ if (ce->trait_precedences) { i = 0; while ((cur_precedence = ce->trait_precedences[i])) { if (cur_precedence->exclude_from_classes) { cur_precedence->trait_method->ce = zend_fetch_class(cur_precedence->trait_method->class_name, cur_precedence->trait_method->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); j = 0; while (cur_precedence->exclude_from_classes[j]) { char* class_name = (char*)cur_precedence->exclude_from_classes[j]; zend_uint name_length = strlen(class_name); cur_precedence->exclude_from_classes[j] = zend_fetch_class(class_name, name_length, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); efree(class_name); j++; } } i++; } } if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { if (ce->trait_aliases[i]->trait_method->class_name) { cur_method_ref = ce->trait_aliases[i]->trait_method; cur_method_ref->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); } i++; } } } /* }}} */ static void zend_traits_compile_exclude_table(HashTable* exclude_table, zend_trait_precedence **precedences, zend_class_entry *trait) /* {{{ */ { size_t i = 0, j; if (!precedences) { return; } while (precedences[i]) { if (precedences[i]->exclude_from_classes) { j = 0; while (precedences[i]->exclude_from_classes[j]) { if (precedences[i]->exclude_from_classes[j] == trait) { zend_uint lcname_len = precedences[i]->trait_method->mname_len; char *lcname = zend_str_tolower_dup(precedences[i]->trait_method->method_name, lcname_len); if (zend_hash_add(exclude_table, lcname, lcname_len, NULL, 0, NULL) == FAILURE) { efree(lcname); zend_error(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", precedences[i]->trait_method->method_name, trait->name); } efree(lcname); } ++j; } } ++i; } } /* }}} */ static void zend_do_traits_method_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { HashTable** function_tables; HashTable* resulting_table; HashTable exclude_table; size_t i; /* prepare copies of trait function tables for combination */ function_tables = malloc(sizeof(HashTable*) * ce->num_traits); resulting_table = (HashTable *) malloc(sizeof(HashTable)); /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(resulting_table, 10, NULL, NULL, 1, 0); for (i = 0; i < ce->num_traits; i++) { function_tables[i] = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(function_tables[i], ce->traits[i]->function_table.nNumOfElements, NULL, NULL, 1, 0); if (ce->trait_precedences) { /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(&exclude_table, 2, NULL, NULL, 0, 0); zend_traits_compile_exclude_table(&exclude_table, ce->trait_precedences, ce->traits[i]); /* copies functions, applies defined aliasing, and excludes unused trait methods */ zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, &exclude_table TSRMLS_CC); zend_hash_graceful_destroy(&exclude_table); } else { zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, NULL TSRMLS_CC); } } /* now merge trait methods */ for (i = 0; i < ce->num_traits; i++) { zend_hash_apply_with_arguments(function_tables[i] TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions, 5, i, ce->num_traits, resulting_table, function_tables, ce); } /* Now the resulting_table contains all trait methods we would have to * add to the class in the following step the methods are inserted into the method table * if there is already a method with the same name it is replaced iff ce != fn.scope * --> all inherited methods are overridden, methods defined in the class are left untouched */ zend_hash_apply_with_arguments(resulting_table TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions_to_class, 1, ce); /* free temporary function tables */ for (i = 0; i < ce->num_traits; i++) { /* zend_hash_destroy(function_tables[i]); */ zend_hash_graceful_destroy(function_tables[i]); free(function_tables[i]); } free(function_tables); /* free temporary resulting table */ /* zend_hash_destroy(resulting_table); */ zend_hash_graceful_destroy(resulting_table); free(resulting_table); } /* }}} */ static zend_class_entry* find_first_definition(zend_class_entry *ce, size_t current_trait, const char* prop_name, int prop_name_length, ulong prop_hash, zend_class_entry *coliding_ce) /* {{{ */ { size_t i; zend_property_info *coliding_prop; for (i = 0; (i < current_trait) && (i < ce->num_traits); i++) { if (zend_hash_quick_find(&ce->traits[i]->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS) { return ce->traits[i]; } } return coliding_ce; } /* }}} */ static void zend_do_traits_property_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i; zend_property_info *property_info; zend_property_info *coliding_prop; zval compare_result; const char* prop_name; int prop_name_length; ulong prop_hash; const char* class_name_unused; zend_bool prop_found; zend_bool not_compatible; zval* prop_value; /* In the following steps the properties are inserted into the property table * for that, a very strict approach is applied: * - check for compatibility, if not compatible with any property in class -> fatal * - if compatible, then strict notice */ for (i = 0; i < ce->num_traits; i++) { for (zend_hash_internal_pointer_reset(&ce->traits[i]->properties_info); zend_hash_get_current_data(&ce->traits[i]->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->traits[i]->properties_info)) { /* first get the unmangeld name if necessary, * then check whether the property is already there */ if ((property_info->flags & ZEND_ACC_PPP_MASK) == ZEND_ACC_PUBLIC) { prop_hash = property_info->h; prop_name = property_info->name; prop_name_length = property_info->name_length; prop_found = zend_hash_quick_find(&ce->properties_info, property_info->name, property_info->name_length+1, property_info->h, (void **) &coliding_prop) == SUCCESS; } else { /* for private and protected we need to unmangle the names */ zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name_unused, &prop_name); prop_name_length = strlen(prop_name); prop_hash = zend_get_hash_value(prop_name, prop_name_length + 1); prop_found = zend_hash_quick_find(&ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS; } /* next: check for conflicts with current class */ if (prop_found) { if (coliding_prop->flags & ZEND_ACC_SHADOW) { /* this one is inherited, lets look it up in its own class */ zend_hash_quick_find(&coliding_prop->ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop); } if ((coliding_prop->flags & ZEND_ACC_PPP_MASK) == (property_info->flags & ZEND_ACC_PPP_MASK)) { /* flags are identical, now the value needs to be checked */ if (property_info->flags & ZEND_ACC_STATIC) { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_static_members_table[coliding_prop->offset], ce->traits[i]->default_static_members_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } else { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_properties_table[coliding_prop->offset], ce->traits[i]->default_properties_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } } else { /* the flags are not identical, thus, we assume properties are not compatible */ not_compatible = 1; } if (not_compatible) { zend_error(E_COMPILE_ERROR, "%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } else { zend_error(E_STRICT, "%s and %s define the same property ($%s) in the composition of %s. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } } /* property not found, so lets add it */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); zend_declare_property_ex(ce, prop_name, prop_name_length, prop_value, property_info->flags, property_info->doc_comment, property_info->doc_comment_len TSRMLS_CC); } } } /* }}} */ ZEND_API void zend_do_bind_traits(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { if (ce->num_traits <= 0) { return; } /* complete initialization of trait strutures in ce */ zend_traits_init_trait_structures(ce TSRMLS_CC); /* first care about all methods to be flattened into the class */ zend_do_traits_method_binding(ce TSRMLS_CC); /* then flatten the properties into it, to, mostly to notfiy developer about problems */ zend_do_traits_property_binding(ce TSRMLS_CC); /* verify that all abstract methods from traits have been implemented */ zend_verify_abstract_class(ce TSRMLS_CC); /* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */ if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { ce->ce_flags -= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } } /* }}} */ ZEND_API int do_bind_function(const zend_op_array *op_array, zend_op *opline, HashTable *function_table, zend_bool compile_time) /* {{{ */ { zend_function *function; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } zend_hash_quick_find(function_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void *) &function); if (zend_hash_quick_add(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), function, sizeof(zend_function), NULL)==FAILURE) { int error_level = compile_time ? E_COMPILE_ERROR : E_ERROR; zend_function *old_function; if (zend_hash_quick_find(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), (void *) &old_function)==SUCCESS && old_function->type == ZEND_USER_FUNCTION && old_function->op_array.last > 0) { zend_error(error_level, "Cannot redeclare %s() (previously declared in %s:%d)", function->common.function_name, old_function->op_array.filename, old_function->op_array.opcodes[0].lineno); } else { zend_error(error_level, "Cannot redeclare %s()", function->common.function_name); } return FAILURE; } else { (*function->op_array.refcount)++; function->op_array.static_variables = NULL; /* NULL out the unbound function */ return SUCCESS; } } /* }}} */ void zend_add_trait_precedence(znode *precedence_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_precedences, precedence_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_add_trait_alias(znode *alias_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_aliases, alias_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_prepare_reference(znode *result, znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { zend_trait_method_reference *method_ref = emalloc(sizeof(zend_trait_method_reference)); method_ref->ce = NULL; /* REM: There should not be a need for copying, zend_do_begin_class_declaration is also just using that string */ if (class_name) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); method_ref->class_name = Z_STRVAL(class_name->u.constant); method_ref->cname_len = Z_STRLEN(class_name->u.constant); } else { method_ref->class_name = NULL; method_ref->cname_len = 0; } method_ref->method_name = Z_STRVAL(method_name->u.constant); method_ref->mname_len = Z_STRLEN(method_name->u.constant); result->u.op.ptr = method_ref; result->op_type = IS_TMP_VAR; } /* }}} */ void zend_prepare_trait_alias(znode *result, znode *method_reference, znode *modifiers, znode *alias TSRMLS_DC) /* {{{ */ { zend_trait_alias *trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_alias->modifiers = Z_LVAL(modifiers->u.constant); if (Z_LVAL(modifiers->u.constant) == ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot use 'static' as method modifier"); return; } if (alias) { trait_alias->alias = Z_STRVAL(alias->u.constant); trait_alias->alias_len = Z_STRLEN(alias->u.constant); } else { trait_alias->alias = NULL; } trait_alias->function = NULL; result->u.op.ptr = trait_alias; } /* }}} */ void zend_prepare_trait_precedence(znode *result, znode *method_reference, znode *trait_list TSRMLS_DC) /* {{{ */ { zend_trait_precedence *trait_precedence = emalloc(sizeof(zend_trait_precedence)); trait_precedence->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_precedence->exclude_from_classes = (zend_class_entry**) trait_list->u.op.ptr; trait_precedence->function = NULL; result->u.op.ptr = trait_precedence; } /* }}} */ ZEND_API zend_class_entry *do_bind_class(const zend_op_array* op_array, const zend_op *opline, HashTable *class_table, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } if (zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce)==FAILURE) { zend_error(E_COMPILE_ERROR, "Internal Zend error - Missing class information for %s", Z_STRVAL_P(op1)); return NULL; } else { ce = *pce; } ce->refcount++; if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), &ce, sizeof(zend_class_entry *), NULL)==FAILURE) { ce->refcount--; if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return NULL; } else { if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLEMENT_INTERFACES))) { zend_verify_abstract_class(ce TSRMLS_CC); } return ce; } } /* }}} */ ZEND_API zend_class_entry *do_bind_inherited_class(const zend_op_array *op_array, const zend_op *opline, HashTable *class_table, zend_class_entry *parent_ce, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; int found_ce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } found_ce = zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce); if (found_ce == FAILURE) { if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", Z_STRVAL_P(op2)); } return NULL; } else { ce = *pce; } if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ce->name, parent_ce->name); } else if ((parent_ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ce->name, parent_ce->name); } zend_do_inheritance(ce, parent_ce TSRMLS_CC); ce->refcount++; /* Register the derived class */ if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), pce, sizeof(zend_class_entry *), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return ce; } /* }}} */ void zend_do_early_binding(TSRMLS_D) /* {{{ */ { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; HashTable *table; while (opline->opcode == ZEND_TICKS && opline > CG(active_op_array)->opcodes) { opline--; } switch (opline->opcode) { case ZEND_DECLARE_FUNCTION: if (do_bind_function(CG(active_op_array), opline, CG(function_table), 1) == FAILURE) { return; } table = CG(function_table); break; case ZEND_DECLARE_CLASS: if (do_bind_class(CG(active_op_array), opline, CG(class_table), 1 TSRMLS_CC) == NULL) { return; } table = CG(class_table); break; case ZEND_DECLARE_INHERITED_CLASS: { zend_op *fetch_class_opline = opline-1; zval *parent_name; zend_class_entry **pce; parent_name = &CONSTANT(fetch_class_opline->op2.constant); if ((zend_lookup_class(Z_STRVAL_P(parent_name), Z_STRLEN_P(parent_name), &pce TSRMLS_CC) == FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_CLASSES) && ((*pce)->type == ZEND_INTERNAL_CLASS))) { if (CG(compiler_options) & ZEND_COMPILE_DELAYED_BINDING) { zend_uint *opline_num = &CG(active_op_array)->early_binding; while (*opline_num != -1) { opline_num = &CG(active_op_array)->opcodes[*opline_num].result.opline_num; } *opline_num = opline - CG(active_op_array)->opcodes; opline->opcode = ZEND_DECLARE_INHERITED_CLASS_DELAYED; opline->result_type = IS_UNUSED; opline->result.opline_num = -1; } return; } if (do_bind_inherited_class(CG(active_op_array), opline, CG(class_table), *pce, 1 TSRMLS_CC) == NULL) { return; } /* clear unnecessary ZEND_FETCH_CLASS opcode */ zend_del_literal(CG(active_op_array), fetch_class_opline->op2.constant); MAKE_NOP(fetch_class_opline); table = CG(class_table); break; } case ZEND_VERIFY_ABSTRACT_CLASS: case ZEND_ADD_INTERFACE: case ZEND_ADD_TRAIT: case ZEND_BIND_TRAITS: /* We currently don't early-bind classes that implement interfaces */ /* Classes with traits are handled exactly the same, no early-bind here */ return; default: zend_error(E_COMPILE_ERROR, "Invalid binding type"); return; } zend_hash_quick_del(table, Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant)), Z_HASH_P(&CONSTANT(opline->op1.constant))); zend_del_literal(CG(active_op_array), opline->op1.constant); zend_del_literal(CG(active_op_array), opline->op2.constant); MAKE_NOP(opline); } /* }}} */ ZEND_API void zend_do_delayed_early_binding(const zend_op_array *op_array TSRMLS_DC) /* {{{ */ { if (op_array->early_binding != -1) { zend_bool orig_in_compilation = CG(in_compilation); zend_uint opline_num = op_array->early_binding; zend_class_entry **pce; CG(in_compilation) = 1; while (opline_num != -1) { if (zend_lookup_class(Z_STRVAL_P(op_array->opcodes[opline_num-1].op2.zv), Z_STRLEN_P(op_array->opcodes[opline_num-1].op2.zv), &pce TSRMLS_CC) == SUCCESS) { do_bind_inherited_class(op_array, &op_array->opcodes[opline_num], EG(class_table), *pce, 0 TSRMLS_CC); } opline_num = op_array->opcodes[opline_num].result.opline_num; } CG(in_compilation) = orig_in_compilation; } } /* }}} */ void zend_do_boolean_or_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_or_end(znode *result, const znode *expr1, const znode *expr2, znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_boolean_and_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_and_end(znode *result, const znode *expr1, const znode *expr2, const znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_do_while_begin(TSRMLS_D) /* {{{ */ { do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_do_while_end(const znode *do_token, const znode *expr_open_bracket, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ; SET_NODE(opline->op1, expr); opline->op2.opline_num = do_token->u.op.opline_num; SET_UNUSED(opline->op2); do_end_loop(expr_open_bracket->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_brk_cont(zend_uchar op, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->op1.opline_num = CG(context).current_brk_cont; SET_UNUSED(opline->op1); if (expr) { if (expr->op_type != IS_CONST) { zend_error(E_COMPILE_ERROR, "'%s' operator with non-constant operand is no longer supported", op == ZEND_BRK ? "break" : "continue"); } else if (Z_TYPE(expr->u.constant) != IS_LONG || Z_LVAL(expr->u.constant) < 1) { zend_error(E_COMPILE_ERROR, "'%s' operator accepts only positive numbers", op == ZEND_BRK ? "break" : "continue"); } SET_NODE(opline->op2, expr); } else { LITERAL_LONG(opline->op2, 1); opline->op2_type = IS_CONST; } } /* }}} */ void zend_do_switch_cond(const znode *cond TSRMLS_DC) /* {{{ */ { zend_switch_entry switch_entry; switch_entry.cond = *cond; switch_entry.default_case = -1; switch_entry.control_var = -1; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_switch_end(const znode *case_list TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); /* add code to jmp to default case */ if (switch_entry_ptr->default_case != -1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->op1.opline_num = switch_entry_ptr->default_case; } if (case_list->op_type != IS_UNUSED) { /* non-empty switch */ int next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* remember break/continue loop information */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; if (switch_entry_ptr->cond.op_type==IS_VAR || switch_entry_ptr->cond.op_type==IS_TMP_VAR) { /* emit free for the switch condition*/ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry_ptr->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_UNUSED(opline->op2); } if (switch_entry_ptr->cond.op_type == IS_CONST) { zval_dtor(&switch_entry_ptr->cond.u.constant); } zend_stack_del_top(&CG(switch_cond_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_case_before_statement(const znode *case_list, znode *case_token, const znode *case_expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); int next_op_number; zend_switch_entry *switch_entry_ptr; znode result; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); if (switch_entry_ptr->control_var == -1) { switch_entry_ptr->control_var = get_temporary_variable(CG(active_op_array)); } opline->opcode = ZEND_CASE; opline->result.var = switch_entry_ptr->control_var; opline->result_type = IS_TMP_VAR; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_NODE(opline->op2, case_expr); if (opline->op1_type == IS_CONST) { zval_copy_ctor(&CONSTANT(opline->op1.constant)); } GET_NODE(&result, opline->result); next_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, &result); SET_UNUSED(opline->op2); case_token->u.op.opline_num = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_case_after_statement(znode *result, const znode *case_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); result->u.op.opline_num = next_op_number; switch (CG(active_op_array)->opcodes[case_token->u.op.opline_num].opcode) { case ZEND_JMP: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); break; case ZEND_JMPZ: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); break; } } /* }}} */ void zend_do_default_before_statement(const znode *case_list, znode *default_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); default_token->u.op.opline_num = next_op_number; next_op_number = get_next_op_number(CG(active_op_array)); switch_entry_ptr->default_case = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_begin_class_declaration(const znode *class_token, znode *class_name, const znode *parent_class_name TSRMLS_DC) /* {{{ */ { zend_op *opline; int doing_inheritance = 0; zend_class_entry *new_class_entry; char *lcname; int error = 0; zval **ns_name, key; if (CG(active_class_entry)) { zend_error(E_COMPILE_ERROR, "Class declarations may not be nested"); return; } lcname = zend_str_tolower_dup(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); if (!(strcmp(lcname, "self") && strcmp(lcname, "parent"))) { efree(lcname); zend_error(E_COMPILE_ERROR, "Cannot use '%s' as class name as it is reserved", Z_STRVAL(class_name->u.constant)); } /* Class name must not conflict with import names */ if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns_name) == SUCCESS) { error = 1; } if (CG(current_namespace)) { /* Prefix class name with name of current namespace */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); class_name = &tmp; efree(lcname); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); } if (error) { char *tmp = zend_str_tolower_dup(Z_STRVAL_PP(ns_name), Z_STRLEN_PP(ns_name)); if (Z_STRLEN_PP(ns_name) != Z_STRLEN(class_name->u.constant) || memcmp(tmp, lcname, Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "Cannot declare class %s because the name is already in use", Z_STRVAL(class_name->u.constant)); } efree(tmp); } new_class_entry = emalloc(sizeof(zend_class_entry)); new_class_entry->type = ZEND_USER_CLASS; new_class_entry->name = zend_new_interned_string(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1, 1 TSRMLS_CC); new_class_entry->name_length = Z_STRLEN(class_name->u.constant); zend_initialize_class_data(new_class_entry, 1 TSRMLS_CC); new_class_entry->info.user.filename = zend_get_compiled_filename(TSRMLS_C); new_class_entry->info.user.line_start = class_token->u.op.opline_num; new_class_entry->ce_flags |= class_token->EA; if (parent_class_name && parent_class_name->op_type != IS_UNUSED) { switch (parent_class_name->EA) { case ZEND_FETCH_CLASS_SELF: zend_error(E_COMPILE_ERROR, "Cannot use 'self' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_PARENT: zend_error(E_COMPILE_ERROR, "Cannot use 'parent' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use 'static' as class name as it is reserved"); break; default: break; } doing_inheritance = 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, new_class_entry->name_length TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; if (doing_inheritance) { /* Make sure a trait does not try to extend a class */ if ((new_class_entry->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "A trait (%s) cannot extend a class", new_class_entry->name); } opline->extended_value = parent_class_name->u.op.var; opline->opcode = ZEND_DECLARE_INHERITED_CLASS; } else { opline->opcode = ZEND_DECLARE_CLASS; } LITERAL_STRINGL(opline->op2, lcname, new_class_entry->name_length, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); zend_hash_quick_update(CG(class_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &new_class_entry, sizeof(zend_class_entry *), NULL); CG(active_class_entry) = new_class_entry; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(&CG(implementing_class), opline->result); if (CG(doc_comment)) { CG(active_class_entry)->info.user.doc_comment = CG(doc_comment); CG(active_class_entry)->info.user.doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ static void do_verify_abstract_class(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_VERIFY_ABSTRACT_CLASS; SET_NODE(opline->op1, &CG(implementing_class)); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_class_declaration(const znode *class_token, const znode *parent_token TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); if (ce->constructor) { ce->constructor->common.fn_flags |= ZEND_ACC_CTOR; if (ce->constructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Constructor %s::%s() cannot be static", ce->name, ce->constructor->common.function_name); } } if (ce->destructor) { ce->destructor->common.fn_flags |= ZEND_ACC_DTOR; if (ce->destructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Destructor %s::%s() cannot be static", ce->name, ce->destructor->common.function_name); } } if (ce->clone) { ce->clone->common.fn_flags |= ZEND_ACC_CLONE; if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static", ce->name, ce->clone->common.function_name); } } ce->info.user.line_end = zend_get_compiled_lineno(TSRMLS_C); /* Check for traits and proceed like with interfaces. * The only difference will be a combined handling of them in the end. * Thus, we need another opcode here. */ if (ce->num_traits > 0) { zend_op *opline; ce->traits = NULL; ce->num_traits = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_TRAITS; /* opcode generation: */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BIND_TRAITS; SET_NODE(opline->op1, &CG(implementing_class)); } if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) && ((parent_token->op_type != IS_UNUSED) || (ce->num_interfaces > 0))) { zend_verify_abstract_class(ce TSRMLS_CC); if (ce->num_interfaces) { do_verify_abstract_class(TSRMLS_C); } } /* Inherit interfaces; reset number to zero, we need it for above check and * will restore it during actual implementation. * The ZEND_ACC_IMPLEMENT_INTERFACES flag disables double call to * zend_verify_abstract_class() */ if (ce->num_interfaces > 0) { ce->interfaces = NULL; ce->num_interfaces = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_INTERFACES; } CG(active_class_entry) = NULL; } /* }}} */ void zend_do_implements_interface(znode *interface_name TSRMLS_DC) /* {{{ */ { zend_op *opline; /* Traits can not implement interfaces */ if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface on '%s' since it is a Trait", Z_STRVAL(interface_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(interface_name->u.constant), Z_STRLEN(interface_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface name as it is reserved", Z_STRVAL(interface_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_INTERFACE; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(interface_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = (opline->extended_value & ~ZEND_FETCH_CLASS_MASK) | ZEND_FETCH_CLASS_INTERFACE; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &interface_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_interfaces++; } /* }}} */ void zend_do_implements_trait(znode *trait_name TSRMLS_DC) /* {{{ */ { zend_op *opline; switch (zend_get_class_fetch_type(Z_STRVAL(trait_name->u.constant), Z_STRLEN(trait_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as trait name as it is reserved", Z_STRVAL(trait_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_TRAIT; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(trait_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = ZEND_FETCH_CLASS_TRAIT; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &trait_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_traits++; } /* }}} */ ZEND_API void zend_mangle_property_name(char **dest, int *dest_length, const char *src1, int src1_length, const char *src2, int src2_length, int internal) /* {{{ */ { char *prop_name; int prop_name_length; prop_name_length = 1 + src1_length + 1 + src2_length; prop_name = pemalloc(prop_name_length + 1, internal); prop_name[0] = '\0'; memcpy(prop_name + 1, src1, src1_length+1); memcpy(prop_name + 1 + src1_length + 1, src2, src2_length+1); *dest = prop_name; *dest_length = prop_name_length; } /* }}} */ static int zend_strnlen(const char* s, int maxlen) /* {{{ */ { int len = 0; while (*s++ && maxlen--) len++; return len; } /* }}} */ ZEND_API int zend_unmangle_property_name(const char *mangled_property, int len, const char **class_name, const char **prop_name) /* {{{ */ { int class_name_len; *class_name = NULL; if (mangled_property[0]!=0) { *prop_name = mangled_property; return SUCCESS; } if (len < 3 || mangled_property[1]==0) { zend_error(E_NOTICE, "Illegal member variable name"); *prop_name = mangled_property; return FAILURE; } class_name_len = zend_strnlen(mangled_property+1, --len - 1) + 1; if (class_name_len >= len || mangled_property[class_name_len]!=0) { zend_error(E_NOTICE, "Corrupt member variable name"); *prop_name = mangled_property; return FAILURE; } *class_name = mangled_property+1; *prop_name = (*class_name)+class_name_len; return SUCCESS; } /* }}} */ void zend_do_declare_property(const znode *var_name, const znode *value, zend_uint access_type TSRMLS_DC) /* {{{ */ { zval *property; zend_property_info *existing_property_info; char *comment = NULL; int comment_len = 0; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Interfaces may not include member variables"); } if (access_type & ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Properties cannot be declared abstract"); } if (access_type & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot declare property %s::$%s final, the final modifier is allowed only for methods and classes", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } if (zend_hash_find(&CG(active_class_entry)->properties_info, var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, (void **) &existing_property_info)==SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::$%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } ALLOC_ZVAL(property); if (value) { *property = value->u.constant; } else { INIT_PZVAL(property); Z_TYPE_P(property) = IS_NULL; } if (CG(doc_comment)) { comment = CG(doc_comment); comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } zend_declare_property_ex(CG(active_class_entry), zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len + 1, 0 TSRMLS_CC), var_name->u.constant.value.str.len, property, access_type, comment, comment_len TSRMLS_CC); efree(var_name->u.constant.value.str.val); } /* }}} */ void zend_do_declare_class_constant(znode *var_name, const znode *value TSRMLS_DC) /* {{{ */ { zval *property; const char *cname = NULL; int result; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed in class constants"); return; } if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Traits cannot have constants"); return; } ALLOC_ZVAL(property); *property = value->u.constant; cname = zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, 0 TSRMLS_CC); if (IS_INTERNED(cname)) { result = zend_hash_quick_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, INTERNED_HASH(cname), &property, sizeof(zval *), NULL); } else { result = zend_hash_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, &property, sizeof(zval *), NULL); } if (result == FAILURE) { FREE_ZVAL(property); zend_error(E_COMPILE_ERROR, "Cannot redefine class constant %s::%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } FREE_PNODE(var_name); if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_fetch_property(znode *result, znode *object, const znode *property TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (object->op_type == IS_CV) { if (object->u.op.var == CG(active_op_array)->this_var) { object->op_type = IS_UNUSED; /* this means $this for objects */ } } else if (fetch_list_ptr->count == 1) { zend_llist_element *le = fetch_list_ptr->head; zend_op *opline_ptr = (zend_op *) le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); SET_UNUSED(opline_ptr->op1); /* this means $this for objects */ SET_NODE(opline_ptr->op2, property); /* if it was usual fetch, we change it to object fetch */ switch (opline_ptr->opcode) { case ZEND_FETCH_W: opline_ptr->opcode = ZEND_FETCH_OBJ_W; break; case ZEND_FETCH_R: opline_ptr->opcode = ZEND_FETCH_OBJ_R; break; case ZEND_FETCH_RW: opline_ptr->opcode = ZEND_FETCH_OBJ_RW; break; case ZEND_FETCH_IS: opline_ptr->opcode = ZEND_FETCH_OBJ_IS; break; case ZEND_FETCH_UNSET: opline_ptr->opcode = ZEND_FETCH_OBJ_UNSET; break; case ZEND_FETCH_FUNC_ARG: opline_ptr->opcode = ZEND_FETCH_OBJ_FUNC_ARG; break; } if (opline_ptr->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline_ptr->op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline_ptr->op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op2.constant); } GET_NODE(result, opline_ptr->result); return; } } if (zend_is_function_or_method_call(object)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, object); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_OBJ_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, object); SET_NODE(opline.op2, property); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline.op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op2.constant); } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void zend_do_halt_compiler_register(TSRMLS_D) /* {{{ */ { char *name, *cfilename; char haltoff[] = "__COMPILER_HALT_OFFSET__"; int len, clen; cfilename = zend_get_compiled_filename(TSRMLS_C); clen = strlen(cfilename); zend_mangle_property_name(&name, &len, haltoff, sizeof(haltoff) - 1, cfilename, clen, 0); zend_register_long_constant(name, len+1, zend_get_scanned_file_offset(TSRMLS_C), CONST_CS, 0 TSRMLS_CC); pefree(name, 0); if (CG(in_namespace)) { zend_do_end_namespace(TSRMLS_C); } } /* }}} */ void zend_do_push_object(const znode *object TSRMLS_DC) /* {{{ */ { zend_stack_push(&CG(object_stack), object, sizeof(znode)); } /* }}} */ void zend_do_pop_object(znode *object TSRMLS_DC) /* {{{ */ { if (object) { znode *tmp; zend_stack_top(&CG(object_stack), (void **) &tmp); *object = *tmp; } zend_stack_del_top(&CG(object_stack)); } /* }}} */ void zend_do_begin_new_object(znode *new_token, znode *class_type TSRMLS_DC) /* {{{ */ { zend_op *opline; unsigned char *ptr = NULL; new_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_NEW; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, class_type); SET_UNUSED(opline->op2); zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(unsigned char *)); } /* }}} */ void zend_do_end_new_object(znode *result, const znode *new_token, const znode *argument_list TSRMLS_DC) /* {{{ */ { znode ctor_result; zend_do_end_function_call(NULL, &ctor_result, argument_list, 1, 0 TSRMLS_CC); zend_do_free(&ctor_result TSRMLS_CC); CG(active_op_array)->opcodes[new_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, CG(active_op_array)->opcodes[new_token->u.op.opline_num].result); } /* }}} */ static zend_constant* zend_get_ct_const(const zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = NULL; if (Z_STRVAL_P(const_name)[0] == '\\') { if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name), (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name)-1); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name), (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } } else if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)+1, (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name)+1, (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } if (c->flags & CONST_CT_SUBST) { return c; } if (all_internal_constants_substitution && (c->flags & CONST_PERSISTENT) && !(CG(compiler_options) & ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION) && Z_TYPE(c->value) != IS_CONSTANT && Z_TYPE(c->value) != IS_CONSTANT_ARRAY) { return c; } return NULL; } /* }}} */ static int zend_constant_ct_subst(znode *result, zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = zend_get_ct_const(const_name, all_internal_constants_substitution TSRMLS_CC); if (c) { zval_dtor(const_name); result->op_type = IS_CONST; result->u.constant = c->value; zval_copy_ctor(&result->u.constant); INIT_PZVAL(&result->u.constant); return 1; } return 0; } /* }}} */ void zend_do_fetch_constant(znode *result, znode *constant_container, znode *constant_name, int mode, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; zend_op *opline; int type; char *compound; ulong fetch_type = 0; if (constant_container) { switch (mode) { case ZEND_CT: /* this is a class constant */ type = zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant)); if (ZEND_FETCH_CLASS_STATIC == type) { zend_error(E_ERROR, "\"static::\" is not allowed in compile-time constants"); } else if (ZEND_FETCH_CLASS_DEFAULT == type) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } zend_do_build_full_name(NULL, constant_container, constant_name, 1 TSRMLS_CC); *result = *constant_container; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: if (constant_container->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant))) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } else { zend_do_fetch_class(&tmp, constant_container TSRMLS_CC); constant_container = &tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); if (constant_container->op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &constant_container->u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, constant_container); } SET_NODE(opline->op2, constant_name); CALCULATE_LITERAL_HASH(opline->op2.constant); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } GET_NODE(result, opline->result); break; } return; } /* namespace constant */ /* only one that did not contain \ from the start can be converted to string if unknown */ switch (mode) { case ZEND_CT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); /* this is a namespace constant, or an unprefixed constant */ if (zend_constant_ct_subst(result, &constant_name->u.constant, 0 TSRMLS_CC)) { break; } zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(!compound) { fetch_type |= IS_CONSTANT_UNQUALIFIED; } *result = *constant_name; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(zend_constant_ct_subst(result, &constant_name->u.constant, 1 TSRMLS_CC)) { break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; if (compound) { /* the name is unambiguous */ opline->extended_value = 0; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } else { opline->extended_value = IS_CONSTANT_UNQUALIFIED; if (CG(current_namespace)) { opline->extended_value |= IS_CONSTANT_IN_NAMESPACE; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 1 TSRMLS_CC); } else { opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } } GET_CACHE_SLOT(opline->op2.constant); break; } } /* }}} */ void zend_do_shell_exec(znode *result, const znode *cmd TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); switch (cmd->op_type) { case IS_CONST: case IS_TMP_VAR: opline->opcode = ZEND_SEND_VAL; break; default: opline->opcode = ZEND_SEND_VAR; break; } SET_NODE(opline->op1, cmd); opline->op2.opline_num = 0; opline->extended_value = ZEND_DO_FCALL; SET_UNUSED(opline->op2); /* FIXME: exception support not added to this op2 */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DO_FCALL; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; LITERAL_STRINGL(opline->op1, estrndup("shell_exec", sizeof("shell_exec")-1), sizeof("shell_exec")-1, 0); CALCULATE_LITERAL_HASH(opline->op1.constant); opline->op1_type = IS_CONST; GET_CACHE_SLOT(opline->op1.constant); opline->extended_value = 1; SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_init_array(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_ARRAY; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; GET_NODE(result, opline->result); if (expr) { SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } } else { SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_array_element(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_ARRAY_ELEMENT; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_static_array_element(znode *result, znode *offset, const znode *expr) /* {{{ */ { zval *element; ALLOC_ZVAL(element); *element = expr->u.constant; if (offset) { switch (offset->u.constant.type & IS_CONSTANT_TYPE_MASK) { case IS_CONSTANT: /* Ugly hack to denote that this value has a constant index */ Z_TYPE_P(element) |= IS_CONSTANT_INDEX; Z_STRVAL(offset->u.constant) = erealloc(Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+1] = Z_TYPE(offset->u.constant); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+2] = 0; zend_symtable_update(result->u.constant.value.ht, Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_STRING: zend_symtable_update(result->u.constant.value.ht, offset->u.constant.value.str.val, offset->u.constant.value.str.len+1, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_NULL: zend_symtable_update(Z_ARRVAL(result->u.constant), "", 1, &element, sizeof(zval *), NULL); break; case IS_LONG: case IS_BOOL: zend_hash_index_update(Z_ARRVAL(result->u.constant), Z_LVAL(offset->u.constant), &element, sizeof(zval *), NULL); break; case IS_DOUBLE: zend_hash_index_update(Z_ARRVAL(result->u.constant), zend_dval_to_lval(Z_DVAL(offset->u.constant)), &element, sizeof(zval *), NULL); break; case IS_CONSTANT_ARRAY: zend_error(E_ERROR, "Illegal offset type"); break; } } else { zend_hash_next_index_insert(Z_ARRVAL(result->u.constant), &element, sizeof(zval *), NULL); } } /* }}} */ void zend_do_add_list_element(const znode *element TSRMLS_DC) /* {{{ */ { list_llist_element lle; if (element) { zend_check_writable_variable(element); lle.var = *element; zend_llist_copy(&lle.dimensions, &CG(dimension_llist)); zend_llist_prepend_element(&CG(list_llist), &lle); } (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_new_list_begin(TSRMLS_D) /* {{{ */ { int current_dimension = 0; zend_llist_add_element(&CG(dimension_llist), &current_dimension); } /* }}} */ void zend_do_new_list_end(TSRMLS_D) /* {{{ */ { zend_llist_remove_tail(&CG(dimension_llist)); (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_list_init(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(list_stack), &CG(list_llist), sizeof(zend_llist)); zend_stack_push(&CG(list_stack), &CG(dimension_llist), sizeof(zend_llist)); zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_do_new_list_begin(TSRMLS_C); } /* }}} */ void zend_do_list_end(znode *result, znode *expr TSRMLS_DC) /* {{{ */ { zend_llist_element *le; zend_llist_element *dimension; zend_op *opline; znode last_container; le = CG(list_llist).head; while (le) { zend_llist *tmp_dimension_llist = &((list_llist_element *)le->data)->dimensions; dimension = tmp_dimension_llist->head; while (dimension) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (dimension == tmp_dimension_llist->head) { /* first */ last_container = *expr; switch (expr->op_type) { case IS_VAR: case IS_CV: opline->opcode = ZEND_FETCH_DIM_R; break; case IS_TMP_VAR: opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; case IS_CONST: /* fetch_dim_tmp_var will handle this bogus fetch */ zval_copy_ctor(&expr->u.constant); opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; } opline->extended_value |= ZEND_FETCH_ADD_LOCK; } else { opline->opcode = ZEND_FETCH_DIM_R; } opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, &last_container); opline->op2_type = IS_CONST; LITERAL_LONG(opline->op2, *((int *) dimension->data)); GET_NODE(&last_container, opline->result); dimension = dimension->next; } ((list_llist_element *) le->data)->value = last_container; zend_llist_destroy(&((list_llist_element *) le->data)->dimensions); zend_do_assign(result, &((list_llist_element *) le->data)->var, &((list_llist_element *) le->data)->value TSRMLS_CC); zend_do_free(result TSRMLS_CC); le = le->next; } zend_llist_destroy(&CG(dimension_llist)); zend_llist_destroy(&CG(list_llist)); *result = *expr; { zend_llist *p; /* restore previous lists */ zend_stack_top(&CG(list_stack), (void **) &p); CG(dimension_llist) = *p; zend_stack_del_top(&CG(list_stack)); zend_stack_top(&CG(list_stack), (void **) &p); CG(list_llist) = *p; zend_stack_del_top(&CG(list_stack)); } } /* }}} */ void zend_init_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = emalloc(sizeof(void*) * 2); list[0] = item; list[1] = NULL; *(void**)result = list; } /* }}} */ void zend_add_to_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = *(void**)result; size_t n = 0; while (list && list[n]) { n++; } list = erealloc(list, sizeof(void*) * (n+2)); list[n] = item; list[n+1] = NULL; *(void**)result = list; } /* }}} */ void zend_do_fetch_static_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zval *tmp; zend_op *opline; znode lval; znode result; ALLOC_ZVAL(tmp); if (static_assignment) { *tmp = static_assignment->u.constant; } else { INIT_ZVAL(*tmp); } if (!CG(active_op_array)->static_variables) { if (CG(active_op_array)->scope) { CG(active_op_array)->scope->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } ALLOC_HASHTABLE(CG(active_op_array)->static_variables); zend_hash_init(CG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } zend_hash_update(CG(active_op_array)->static_variables, varname->u.constant.value.str.val, varname->u.constant.value.str.len+1, &tmp, sizeof(zval *), NULL); if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (fetch_type == ZEND_FETCH_LEXICAL) ? ZEND_FETCH_R : ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_STATIC; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ if (fetch_type == ZEND_FETCH_LEXICAL) { znode dummy; zend_do_begin_variable_parse(TSRMLS_C); zend_do_assign(&dummy, &lval, &result TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } else { zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); } CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_fetch_lexical_variable(znode *varname, zend_bool is_ref TSRMLS_DC) /* {{{ */ { znode value; if (Z_STRLEN(varname->u.constant) == sizeof("this") - 1 && memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this") - 1) == 0) { zend_error(E_COMPILE_ERROR, "Cannot use $this as lexical variable"); return; } value.op_type = IS_CONST; ZVAL_NULL(&value.u.constant); Z_TYPE(value.u.constant) |= is_ref ? IS_LEXICAL_REF : IS_LEXICAL_VAR; Z_SET_REFCOUNT_P(&value.u.constant, 1); Z_UNSET_ISREF_P(&value.u.constant); zend_do_fetch_static_variable(varname, &value, is_ref ? ZEND_FETCH_STATIC : ZEND_FETCH_LEXICAL TSRMLS_CC); } /* }}} */ void zend_do_fetch_global_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zend_op *opline; znode lval; znode result; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = fetch_type; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_cast(znode *result, const znode *expr, int type TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CAST; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } /* }}} */ void zend_do_include_or_eval(int type, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_do_extended_fcall_begin(TSRMLS_C); { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INCLUDE_OR_EVAL; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } zend_do_extended_fcall_end(TSRMLS_C); } /* }}} */ void zend_do_indirect_references(znode *result, const znode *num_references, znode *variable TSRMLS_DC) /* {{{ */ { int i; zend_do_end_variable_parse(variable, BP_VAR_R, 0 TSRMLS_CC); for (i=1; i<num_references->u.constant.value.lval; i++) { fetch_simple_variable_ex(result, variable, 0, ZEND_FETCH_R TSRMLS_CC); *variable = *result; } zend_do_begin_variable_parse(TSRMLS_C); fetch_simple_variable(result, variable, 1 TSRMLS_CC); /* there is a chance someone is accessing $this */ if (CG(active_op_array)->scope && CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } /* }}} */ void zend_do_unset(const znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_UNSET_VAR; SET_NODE(opline->op1, variable); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); opline->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_UNSET: last_op->opcode = ZEND_UNSET_VAR; SET_UNUSED(last_op->result); break; case ZEND_FETCH_DIM_UNSET: last_op->opcode = ZEND_UNSET_DIM; SET_UNUSED(last_op->result); break; case ZEND_FETCH_OBJ_UNSET: last_op->opcode = ZEND_UNSET_OBJ; SET_UNUSED(last_op->result); break; } } } /* }}} */ void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_do_end_variable_parse(variable, BP_VAR_IS, 0 TSRMLS_CC); zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { last_op = get_next_op(CG(active_op_array) TSRMLS_CC); last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; SET_NODE(last_op->op1, variable); SET_UNUSED(last_op->op2); last_op->result.var = get_temporary_variable(CG(active_op_array)); last_op->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; break; case ZEND_FETCH_DIM_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_DIM_OBJ; break; case ZEND_FETCH_OBJ_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_PROP_OBJ; break; } } last_op->result_type = IS_TMP_VAR; last_op->extended_value |= type; GET_NODE(result, last_op->result); } /* }}} */ void zend_do_instanceof(znode *result, const znode *expr, const znode *class_znode, int type TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline->opcode == ZEND_FETCH_CLASS) { opline->extended_value |= ZEND_FETCH_CLASS_NO_AUTOLOAD; } } if (expr->op_type == IS_CONST) { zend_error(E_COMPILE_ERROR, "instanceof expects an object instance, constant given"); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INSTANCEOF; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_NODE(opline->op2, class_znode); GET_NODE(result, opline->result); } /* }}} */ void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_bool is_variable; zend_bool push_container = 0; zend_op dummy_opline; if (variable) { if (zend_is_function_or_method_call(array)) { is_variable = 0; } else { is_variable = 1; } /* save the location of FETCH_W instruction(s) */ open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); zend_do_end_variable_parse(array, BP_VAR_W, 0 TSRMLS_CC); if (CG(active_op_array)->last > 0 && CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) { /* Only lock the container if we are fetching from a real container and not $this */ if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1_type == IS_VAR) { CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK; push_container = 1; } } } else { is_variable = 0; open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* save the location of FE_RESET */ foreach_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* Preform array reset */ opline->opcode = ZEND_FE_RESET; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, array); SET_UNUSED(opline->op2); opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0; COPY_NODE(dummy_opline.result, opline->result); if (push_container) { COPY_NODE(dummy_opline.op1, CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1); } else { dummy_opline.op1_type = IS_UNUSED; } zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); /* save the location of FE_FETCH */ as_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FE_FETCH; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); COPY_NODE(opline->op1, dummy_opline.result); opline->extended_value = 0; SET_UNUSED(opline->op2); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_OP_DATA; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); } /* }}} */ void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC) /* {{{ */ { zend_op *opline; znode dummy, value_node; zend_bool assign_by_ref=0; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num]; if (key->op_type != IS_UNUSED) { znode *tmp; /* switch between the key and value... */ tmp = key; key = value; value = tmp; /* Mark extended_value in case both key and value are being used */ opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; } if ((key->op_type != IS_UNUSED) && (key->EA & ZEND_PARSED_REFERENCE_VARIABLE)) { zend_error(E_COMPILE_ERROR, "Key element cannot be a reference"); } if (value->EA & ZEND_PARSED_REFERENCE_VARIABLE) { assign_by_ref = 1; if (!(opline-1)->extended_value) { zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression"); } /* Mark extended_value for assign-by-reference */ opline->extended_value |= ZEND_FE_FETCH_BYREF; CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; } else { zend_op *foreach_copy; zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.op.opline_num]; zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.op.opline_num]; /* Change "write context" into "read context" */ fetch->extended_value = 0; /* reset ZEND_FE_RESET_VARIABLE */ while (fetch != end) { --fetch; if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } if (fetch->opcode == ZEND_SEPARATE) { MAKE_NOP(fetch); } else { fetch->opcode -= 3; /* FETCH_W -> FETCH_R */ } } /* prevent double SWITCH_FREE */ zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy); foreach_copy->op1_type = IS_UNUSED; } GET_NODE(&value_node, opline->result); if (assign_by_ref) { zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); /* Mark FE_FETCH as IS_VAR as it holds the data directly as a value */ zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC); } else { zend_do_assign(&dummy, value, &value_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } if (key->op_type != IS_UNUSED) { znode key_node; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num+1]; opline->result_type = IS_TMP_VAR; opline->result.opline_num = get_temporary_variable(CG(active_op_array)); GET_NODE(&key_node, opline->result); zend_do_assign(&dummy, key, &key_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_foreach_end(const znode *foreach_token, const znode *as_token TSRMLS_DC) /* {{{ */ { zend_op *container_ptr; zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = as_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_RESET */ CG(active_op_array)->opcodes[as_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_FETCH */ do_end_loop(as_token->u.op.opline_num, 1 TSRMLS_CC); zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr); generate_free_foreach_copy(container_ptr TSRMLS_CC); zend_stack_del_top(&CG(foreach_copy_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_declare_begin(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(declare_stack), &CG(declarables), sizeof(zend_declarables)); } /* }}} */ void zend_do_declare_stmt(znode *var, znode *val TSRMLS_DC) /* {{{ */ { if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "ticks", sizeof("ticks")-1)) { convert_to_long(&val->u.constant); CG(declarables).ticks = val->u.constant; } else if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "encoding", sizeof("encoding")-1)) { if ((Z_TYPE(val->u.constant) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Cannot use constants as encoding"); } /* * Check that the pragma comes before any opcodes. If the compilation * got as far as this, the previous portion of the script must have been * parseable according to the .ini script_encoding setting. We still * want to tell them to put declare() at the top. */ { int num = CG(active_op_array)->last; /* ignore ZEND_EXT_STMT and ZEND_TICKS */ while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Encoding declaration pragma must be the very first statement in the script"); } } if (CG(multibyte)) { const zend_encoding *new_encoding, *old_encoding; zend_encoding_filter old_input_filter; CG(encoding_declared) = 1; convert_to_string(&val->u.constant); new_encoding = zend_multibyte_fetch_encoding(val->u.constant.value.str.val TSRMLS_CC); if (!new_encoding) { zend_error(E_COMPILE_WARNING, "Unsupported encoding [%s]", val->u.constant.value.str.val); } else { old_input_filter = LANG_SCNG(input_filter); old_encoding = LANG_SCNG(script_encoding); zend_multibyte_set_filter(new_encoding TSRMLS_CC); /* need to re-scan if input filter changed */ if (old_input_filter != LANG_SCNG(input_filter) || (old_input_filter && new_encoding != old_encoding)) { zend_multibyte_yyinput_again(old_input_filter, old_encoding TSRMLS_CC); } } } else { zend_error(E_COMPILE_WARNING, "declare(encoding=...) ignored because Zend multibyte feature is turned off by settings"); } zval_dtor(&val->u.constant); } else { zend_error(E_COMPILE_WARNING, "Unsupported declare '%s'", var->u.constant.value.str.val); zval_dtor(&val->u.constant); } zval_dtor(&var->u.constant); } /* }}} */ void zend_do_declare_end(const znode *declare_token TSRMLS_DC) /* {{{ */ { zend_declarables *declarables; zend_stack_top(&CG(declare_stack), (void **) &declarables); /* We should restore if there was more than (current - start) - (ticks?1:0) opcodes */ if ((get_next_op_number(CG(active_op_array)) - declare_token->u.op.opline_num) - ((Z_LVAL(CG(declarables).ticks))?1:0)) { CG(declarables) = *declarables; } } /* }}} */ void zend_do_exit(znode *result, const znode *message TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXIT; SET_NODE(opline->op1, message); SET_UNUSED(opline->op2); result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_BOOL; Z_LVAL(result->u.constant) = 1; } /* }}} */ void zend_do_begin_silence(znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BEGIN_SILENCE; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); GET_NODE(strudel_token, opline->result); } /* }}} */ void zend_do_end_silence(const znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_END_SILENCE; SET_NODE(opline->op1, strudel_token); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_jmp_set(const znode *value, znode *jmp_token, znode *colon_token TSRMLS_DC) /* {{{ */ { int op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (value->op_type == IS_VAR || value->op_type == IS_CV) { opline->opcode = ZEND_JMP_SET_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_JMP_SET; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, value); SET_UNUSED(opline->op2); GET_NODE(colon_token, opline->result); jmp_token->u.op .opline_num = op_number; INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_jmp_set_else(znode *result, const znode *false_value, const znode *jmp_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, colon_token); if (colon_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].opcode = ZEND_JMP_SET_VAR; CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } opline->extended_value = 0; SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_qm_op(const znode *cond, znode *qm_token TSRMLS_DC) /* {{{ */ { int jmpz_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); SET_UNUSED(opline->op2); opline->op2.opline_num = jmpz_op_number; GET_NODE(qm_token, opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_qm_true(const znode *true_value, znode *qm_token, znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->opcodes[qm_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array))+1; /* jmp over the ZEND_JMP */ if (true_value->op_type == IS_VAR || true_value->op_type == IS_CV) { opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, true_value); SET_UNUSED(opline->op2); GET_NODE(qm_token, opline->result); colon_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_qm_false(znode *result, const znode *false_value, const znode *qm_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, qm_token); if (qm_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].opcode = ZEND_QM_ASSIGN_VAR; CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[colon_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, opline->result); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_extended_info(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_STMT; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_begin(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_BEGIN; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_end(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_END; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_ticks(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_TICKS; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->extended_value = Z_LVAL(CG(declarables).ticks); } /* }}} */ zend_bool zend_is_auto_global_quick(const char *name, uint name_len, ulong hashval TSRMLS_DC) /* {{{ */ { zend_auto_global *auto_global; ulong hash = hashval ? hashval : zend_hash_func(name, name_len+1); if (zend_hash_quick_find(CG(auto_globals), name, name_len+1, hash, (void **) &auto_global)==SUCCESS) { if (auto_global->armed) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } return 1; } return 0; } /* }}} */ zend_bool zend_is_auto_global(const char *name, uint name_len TSRMLS_DC) /* {{{ */ { return zend_is_auto_global_quick(name, name_len, 0 TSRMLS_CC); } /* }}} */ int zend_register_auto_global(const char *name, uint name_len, zend_bool jit, zend_auto_global_callback auto_global_callback TSRMLS_DC) /* {{{ */ { zend_auto_global auto_global; auto_global.name = zend_new_interned_string((char*)name, name_len + 1, 0 TSRMLS_CC); auto_global.name_len = name_len; auto_global.auto_global_callback = auto_global_callback; auto_global.jit = jit; return zend_hash_add(CG(auto_globals), name, name_len+1, &auto_global, sizeof(zend_auto_global), NULL); } /* }}} */ static int zend_auto_global_init(zend_auto_global *auto_global TSRMLS_DC) /* {{{ */ { if (auto_global->jit) { auto_global->armed = 1; } else if (auto_global->auto_global_callback) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } else { auto_global->armed = 0; } return 0; } /* }}} */ ZEND_API void zend_activate_auto_globals(TSRMLS_D) /* {{{ */ { zend_hash_apply(CG(auto_globals), (apply_func_t) zend_auto_global_init TSRMLS_CC); } /* }}} */ int zendlex(znode *zendlval TSRMLS_DC) /* {{{ */ { int retval; if (CG(increment_lineno)) { CG(zend_lineno)++; CG(increment_lineno) = 0; } again: Z_TYPE(zendlval->u.constant) = IS_LONG; retval = lex_scan(&zendlval->u.constant TSRMLS_CC); switch (retval) { case T_COMMENT: case T_DOC_COMMENT: case T_OPEN_TAG: case T_WHITESPACE: goto again; case T_CLOSE_TAG: if (LANG_SCNG(yy_text)[LANG_SCNG(yy_leng)-1] != '>') { CG(increment_lineno) = 1; } if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { goto again; } retval = ';'; /* implicit ; */ break; case T_OPEN_TAG_WITH_ECHO: retval = T_ECHO; break; case T_END_HEREDOC: efree(Z_STRVAL(zendlval->u.constant)); break; } INIT_PZVAL(&zendlval->u.constant); zendlval->op_type = IS_CONST; return retval; } /* }}} */ ZEND_API void zend_initialize_class_data(zend_class_entry *ce, zend_bool nullify_handlers TSRMLS_DC) /* {{{ */ { zend_bool persistent_hashes = (ce->type == ZEND_INTERNAL_CLASS) ? 1 : 0; dtor_func_t zval_ptr_dtor_func = ((persistent_hashes) ? ZVAL_INTERNAL_PTR_DTOR : ZVAL_PTR_DTOR); ce->refcount = 1; ce->ce_flags = 0; ce->default_properties_table = NULL; ce->default_static_members_table = NULL; zend_hash_init_ex(&ce->properties_info, 0, NULL, (dtor_func_t) (persistent_hashes ? zend_destroy_property_info_internal : zend_destroy_property_info), persistent_hashes, 0); zend_hash_init_ex(&ce->constants_table, 0, NULL, zval_ptr_dtor_func, persistent_hashes, 0); zend_hash_init_ex(&ce->function_table, 0, NULL, ZEND_FUNCTION_DTOR, persistent_hashes, 0); if (ce->type == ZEND_INTERNAL_CLASS) { #ifdef ZTS int n = zend_hash_num_elements(CG(class_table)); if (CG(static_members_table) && n >= CG(last_static_member)) { /* Support for run-time declaration: dl() */ CG(last_static_member) = n+1; CG(static_members_table) = realloc(CG(static_members_table), (n+1)*sizeof(zval**)); CG(static_members_table)[n] = NULL; } ce->static_members_table = (zval**)(zend_intptr_t)n; #else ce->static_members_table = NULL; #endif } else { ce->static_members_table = ce->default_static_members_table; ce->info.user.doc_comment = NULL; ce->info.user.doc_comment_len = 0; } ce->default_properties_count = 0; ce->default_static_members_count = 0; if (nullify_handlers) { ce->constructor = NULL; ce->destructor = NULL; ce->clone = NULL; ce->__get = NULL; ce->__set = NULL; ce->__unset = NULL; ce->__isset = NULL; ce->__call = NULL; ce->__callstatic = NULL; ce->__tostring = NULL; ce->create_object = NULL; ce->get_iterator = NULL; ce->iterator_funcs.funcs = NULL; ce->interface_gets_implemented = NULL; ce->get_static_method = NULL; ce->parent = NULL; ce->num_interfaces = 0; ce->interfaces = NULL; ce->num_traits = 0; ce->traits = NULL; ce->trait_aliases = NULL; ce->trait_precedences = NULL; ce->serialize = NULL; ce->unserialize = NULL; ce->serialize_func = NULL; ce->unserialize_func = NULL; if (ce->type == ZEND_INTERNAL_CLASS) { ce->info.internal.module = NULL; ce->info.internal.builtin_functions = NULL; } } } /* }}} */ int zend_get_class_fetch_type(const char *class_name, uint class_name_len) /* {{{ */ { if ((class_name_len == sizeof("self")-1) && !memcmp(class_name, "self", sizeof("self")-1)) { return ZEND_FETCH_CLASS_SELF; } else if ((class_name_len == sizeof("parent")-1) && !memcmp(class_name, "parent", sizeof("parent")-1)) { return ZEND_FETCH_CLASS_PARENT; } else if ((class_name_len == sizeof("static")-1) && !memcmp(class_name, "static", sizeof("static")-1)) { return ZEND_FETCH_CLASS_STATIC; } else { return ZEND_FETCH_CLASS_DEFAULT; } } /* }}} */ ZEND_API const char* zend_get_compiled_variable_name(const zend_op_array *op_array, zend_uint var, int* name_len) /* {{{ */ { if (name_len) { *name_len = op_array->vars[var].name_len; } return op_array->vars[var].name; } /* }}} */ void zend_do_build_namespace_name(znode *result, znode *prefix, znode *name TSRMLS_DC) /* {{{ */ { if (prefix) { *result = *prefix; if (Z_TYPE(result->u.constant) == IS_STRING && Z_STRLEN(result->u.constant) == 0) { /* namespace\ */ if (CG(current_namespace)) { znode tmp; zval_dtor(&result->u.constant); tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(result, NULL, &tmp TSRMLS_CC); } } } else { result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_STRING; Z_STRVAL(result->u.constant) = NULL; Z_STRLEN(result->u.constant) = 0; } /* prefix = result */ zend_do_build_full_name(NULL, result, name, 0 TSRMLS_CC); } /* }}} */ void zend_do_begin_namespace(const znode *name, zend_bool with_bracket TSRMLS_DC) /* {{{ */ { char *lcname; /* handle mixed syntax declaration or nested namespaces */ if (!CG(has_bracketed_namespaces)) { if (CG(current_namespace)) { /* previous namespace declarations were unbracketed */ if (with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } } } else { /* previous namespace declarations were bracketed */ if (!with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } else if (CG(current_namespace) || CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "Namespace declarations cannot be nested"); } } if (((!with_bracket && !CG(current_namespace)) || (with_bracket && !CG(has_bracketed_namespaces))) && CG(active_op_array)->last > 0) { /* ignore ZEND_EXT_STMT and ZEND_TICKS */ int num = CG(active_op_array)->last; while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Namespace declaration statement has to be the very first statement in the script"); } } CG(in_namespace) = 1; if (with_bracket) { CG(has_bracketed_namespaces) = 1; } if (name) { lcname = zend_str_tolower_dup(Z_STRVAL(name->u.constant), Z_STRLEN(name->u.constant)); if (((Z_STRLEN(name->u.constant) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN(name->u.constant) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as namespace name", Z_STRVAL(name->u.constant)); } efree(lcname); if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); } else { ALLOC_ZVAL(CG(current_namespace)); } *CG(current_namespace) = name->u.constant; } else { if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_use(znode *ns_name, znode *new_name, int is_global TSRMLS_DC) /* {{{ */ { char *lcname; zval *name, *ns, tmp; zend_bool warn = 0; zend_class_entry **pce; if (!CG(current_import)) { CG(current_import) = emalloc(sizeof(HashTable)); zend_hash_init(CG(current_import), 0, NULL, ZVAL_PTR_DTOR, 0); } ALLOC_ZVAL(ns); *ns = ns_name->u.constant; if (new_name) { name = &new_name->u.constant; } else { const char *p; /* The form "use A\B" is eqivalent to "use A\B as B". So we extract the last part of compound name to use as a new_name */ name = &tmp; p = zend_memrchr(Z_STRVAL_P(ns), '\\', Z_STRLEN_P(ns)); if (p) { ZVAL_STRING(name, p+1, 1); } else { *name = *ns; zval_copy_ctor(name); warn = !is_global && !CG(current_namespace); } } lcname = zend_str_tolower_dup(Z_STRVAL_P(name), Z_STRLEN_P(name)); if (((Z_STRLEN_P(name) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN_P(name) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because '%s' is a special class name", Z_STRVAL_P(ns), Z_STRVAL_P(name), Z_STRVAL_P(name)); } if (CG(current_namespace)) { /* Prefix import name with current namespace name to avoid conflicts with classes */ char *c_ns_name = emalloc(Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) + 1); zend_str_tolower_copy(c_ns_name, Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); c_ns_name[Z_STRLEN_P(CG(current_namespace))] = '\\'; memcpy(c_ns_name+Z_STRLEN_P(CG(current_namespace))+1, lcname, Z_STRLEN_P(name)+1); if (zend_hash_exists(CG(class_table), c_ns_name, Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name)+1)) { char *tmp2 = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) || memcmp(tmp2, c_ns_name, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(tmp2); } efree(c_ns_name); } else if (zend_hash_find(CG(class_table), lcname, Z_STRLEN_P(name)+1, (void**)&pce) == SUCCESS && (*pce)->type == ZEND_USER_CLASS && (*pce)->info.user.filename == CG(compiled_filename)) { char *c_tmp = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(name) || memcmp(c_tmp, lcname, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(c_tmp); } if (zend_hash_add(CG(current_import), lcname, Z_STRLEN_P(name)+1, &ns, sizeof(zval*), NULL) != SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } if (warn) { if (!strcmp(Z_STRVAL_P(name), "strict")) { zend_error(E_COMPILE_ERROR, "You seem to be trying to use a different language..."); } zend_error(E_WARNING, "The use statement with non-compound name '%s' has no effect", Z_STRVAL_P(name)); } efree(lcname); zval_dtor(name); } /* }}} */ void zend_do_declare_constant(znode *name, znode *value TSRMLS_DC) /* {{{ */ { zend_op *opline; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed as constants"); } if (zend_get_ct_const(&name->u.constant, 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare constant '%s'", Z_STRVAL(name->u.constant)); } if (CG(current_namespace)) { /* Prefix constant name with name of current namespace, lowercased */ znode tmp; tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); Z_STRVAL(tmp.u.constant) = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), Z_STRLEN(tmp.u.constant)); zend_do_build_namespace_name(&tmp, &tmp, name TSRMLS_CC); *name = tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DECLARE_CONST; SET_UNUSED(opline->result); SET_NODE(opline->op1, name); SET_NODE(opline->op2, value); } /* }}} */ void zend_verify_namespace(TSRMLS_D) /* {{{ */ { if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "No code may exist outside of namespace {}"); } } /* }}} */ void zend_do_end_namespace(TSRMLS_D) /* {{{ */ { CG(in_namespace) = 0; if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_end_compilation(TSRMLS_D) /* {{{ */ { CG(has_bracketed_namespaces) = 0; zend_do_end_namespace(TSRMLS_C); } /* }}} */ /* {{{ zend_dirname Returns directory name component of path */ ZEND_API size_t zend_dirname(char *path, size_t len) { register char *end = path + len - 1; unsigned int len_adjust = 0; #ifdef PHP_WIN32 /* Note that on Win32 CWD is per drive (heritage from CP/M). * This means dirname("c:foo") maps to "c:." or "c:" - which means CWD on C: drive. */ if ((2 <= len) && isalpha((int)((unsigned char *)path)[0]) && (':' == path[1])) { /* Skip over the drive spec (if any) so as not to change */ path += 2; len_adjust += 2; if (2 == len) { /* Return "c:" on Win32 for dirname("c:"). * It would be more consistent to return "c:." * but that would require making the string *longer*. */ return len; } } #elif defined(NETWARE) /* * Find the first occurence of : from the left * move the path pointer to the position just after : * increment the len_adjust to the length of path till colon character(inclusive) * If there is no character beyond : simple return len */ char *colonpos = NULL; colonpos = strchr(path, ':'); if (colonpos != NULL) { len_adjust = ((colonpos - path) + 1); path += len_adjust; if (len_adjust == len) { return len; } } #endif if (len == 0) { /* Illegal use of this function */ return 0; } /* Strip trailing slashes */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { /* The path only contained slashes */ path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } /* Strip filename */ while (end >= path && !IS_SLASH_P(end)) { end--; } if (end < path) { /* No slash found, therefore return '.' */ #ifdef NETWARE if (len_adjust == 0) { path[0] = '.'; path[1] = '\0'; return 1; /* only one character */ } else { path[0] = '\0'; return len_adjust; } #else path[0] = '.'; path[1] = '\0'; return 1 + len_adjust; #endif } /* Strip slashes which came before the file name */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } *(end+1) = '\0'; return (size_t)(end + 1 - path) + len_adjust; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */ /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <zend_language_parser.h> #include "zend.h" #include "zend_compile.h" #include "zend_constants.h" #include "zend_llist.h" #include "zend_API.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "zend_multibyte.h" #include "zend_language_scanner.h" #define CONSTANT_EX(op_array, op) \ (op_array)->literals[op].constant #define CONSTANT(op) \ CONSTANT_EX(CG(active_op_array), op) #define SET_NODE(target, src) do { \ target ## _type = (src)->op_type; \ if ((src)->op_type == IS_CONST) { \ target.constant = zend_add_literal(CG(active_op_array), &(src)->u.constant TSRMLS_CC); \ } else { \ target = (src)->u.op; \ } \ } while (0) #define GET_NODE(target, src) do { \ (target)->op_type = src ## _type; \ if ((target)->op_type == IS_CONST) { \ (target)->u.constant = CONSTANT(src.constant); \ } else { \ (target)->u.op = src; \ (target)->EA = 0; \ } \ } while (0) #define COPY_NODE(target, src) do { \ target ## _type = src ## _type; \ target = src; \ } while (0) #define CALCULATE_LITERAL_HASH(num) do { \ if (IS_INTERNED(Z_STRVAL(CONSTANT(num)))) { \ Z_HASH_P(&CONSTANT(num)) = INTERNED_HASH(Z_STRVAL(CONSTANT(num))); \ } else { \ Z_HASH_P(&CONSTANT(num)) = zend_hash_func(Z_STRVAL(CONSTANT(num)), Z_STRLEN(CONSTANT(num))+1); \ } \ } while (0) #define GET_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot++; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ } \ } while (0) #define POLYMORPHIC_CACHE_SLOT_SIZE 2 #define GET_POLYMORPHIC_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot; \ CG(active_op_array)->last_cache_slot += POLYMORPHIC_CACHE_SLOT_SIZE; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 2] = NULL; \ } \ } while (0) #define FREE_POLYMORPHIC_CACHE_SLOT(literal) do { \ if (CG(active_op_array)->literals[literal].cache_slot == \ CG(active_op_array)->last_cache_slot - POLYMORPHIC_CACHE_SLOT_SIZE) { \ CG(active_op_array)->literals[literal].cache_slot = -1; \ CG(active_op_array)->last_cache_slot -= POLYMORPHIC_CACHE_SLOT_SIZE; \ } \ } while (0) ZEND_API zend_op_array *(*zend_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); ZEND_API zend_op_array *(*zend_compile_string)(zval *source_string, char *filename TSRMLS_DC); #ifndef ZTS ZEND_API zend_compiler_globals compiler_globals; ZEND_API zend_executor_globals executor_globals; #endif static void zend_duplicate_property_info(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = estrndup(property_info->name, property_info->name_length); } if (property_info->doc_comment) { property_info->doc_comment = estrndup(property_info->doc_comment, property_info->doc_comment_len); } } /* }}} */ static void zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = zend_strndup(property_info->name, property_info->name_length); } } /* }}} */ static void zend_destroy_property_info(zend_property_info *property_info) /* {{{ */ { str_efree(property_info->name); if (property_info->doc_comment) { efree((char*)property_info->doc_comment); } } /* }}} */ static void zend_destroy_property_info_internal(zend_property_info *property_info) /* {{{ */ { str_free((char*)property_info->name); } /* }}} */ static void build_runtime_defined_function_key(zval *result, const char *name, int name_length TSRMLS_DC) /* {{{ */ { char char_pos_buf[32]; uint char_pos_len; const char *filename; char_pos_len = zend_sprintf(char_pos_buf, "%p", LANG_SCNG(yy_text)); if (CG(active_op_array)->filename) { filename = CG(active_op_array)->filename; } else { filename = "-"; } /* NULL, name length, filename length, last accepting char position length */ result->value.str.len = 1+name_length+strlen(filename)+char_pos_len; /* must be binary safe */ result->value.str.val = (char *) safe_emalloc(result->value.str.len, 1, 1); result->value.str.val[0] = '\0'; sprintf(result->value.str.val+1, "%s%s%s", name, filename, char_pos_buf); result->type = IS_STRING; Z_SET_REFCOUNT_P(result, 1); } /* }}} */ static void init_compiler_declarables(TSRMLS_D) /* {{{ */ { Z_TYPE(CG(declarables).ticks) = IS_LONG; Z_LVAL(CG(declarables).ticks) = 0; } /* }}} */ void zend_init_compiler_context(TSRMLS_D) /* {{{ */ { CG(context).opcodes_size = (CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) ? INITIAL_INTERACTIVE_OP_ARRAY_SIZE : INITIAL_OP_ARRAY_SIZE; CG(context).vars_size = 0; CG(context).literals_size = 0; CG(context).current_brk_cont = -1; CG(context).backpatch_count = 0; CG(context).labels = NULL; } /* }}} */ void zend_init_compiler_data_structures(TSRMLS_D) /* {{{ */ { zend_stack_init(&CG(bp_stack)); zend_stack_init(&CG(function_call_stack)); zend_stack_init(&CG(switch_cond_stack)); zend_stack_init(&CG(foreach_copy_stack)); zend_stack_init(&CG(object_stack)); zend_stack_init(&CG(declare_stack)); CG(active_class_entry) = NULL; zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_stack_init(&CG(list_stack)); CG(in_compilation) = 0; CG(start_lineno) = 0; CG(current_namespace) = NULL; CG(in_namespace) = 0; CG(has_bracketed_namespaces) = 0; CG(current_import) = NULL; init_compiler_declarables(TSRMLS_C); zend_stack_init(&CG(context_stack)); CG(encoding_declared) = 0; } /* }}} */ ZEND_API void file_handle_dtor(zend_file_handle *fh) /* {{{ */ { TSRMLS_FETCH(); zend_file_handle_dtor(fh TSRMLS_CC); } /* }}} */ void init_compiler(TSRMLS_D) /* {{{ */ { CG(active_op_array) = NULL; zend_init_compiler_data_structures(TSRMLS_C); zend_init_rsrc_list(TSRMLS_C); zend_hash_init(&CG(filenames_table), 5, NULL, (dtor_func_t) free_estring, 0); zend_llist_init(&CG(open_files), sizeof(zend_file_handle), (void (*)(void *)) file_handle_dtor, 0); CG(unclean_shutdown) = 0; } /* }}} */ void shutdown_compiler(TSRMLS_D) /* {{{ */ { zend_stack_destroy(&CG(bp_stack)); zend_stack_destroy(&CG(function_call_stack)); zend_stack_destroy(&CG(switch_cond_stack)); zend_stack_destroy(&CG(foreach_copy_stack)); zend_stack_destroy(&CG(object_stack)); zend_stack_destroy(&CG(declare_stack)); zend_stack_destroy(&CG(list_stack)); zend_hash_destroy(&CG(filenames_table)); zend_llist_destroy(&CG(open_files)); zend_stack_destroy(&CG(context_stack)); } /* }}} */ ZEND_API char *zend_set_compiled_filename(const char *new_compiled_filename TSRMLS_DC) /* {{{ */ { char **pp, *p; int length = strlen(new_compiled_filename); if (zend_hash_find(&CG(filenames_table), new_compiled_filename, length+1, (void **) &pp) == SUCCESS) { CG(compiled_filename) = *pp; return *pp; } p = estrndup(new_compiled_filename, length); zend_hash_update(&CG(filenames_table), new_compiled_filename, length+1, &p, sizeof(char *), (void **) &pp); CG(compiled_filename) = p; return p; } /* }}} */ ZEND_API void zend_restore_compiled_filename(char *original_compiled_filename TSRMLS_DC) /* {{{ */ { CG(compiled_filename) = original_compiled_filename; } /* }}} */ ZEND_API char *zend_get_compiled_filename(TSRMLS_D) /* {{{ */ { return CG(compiled_filename); } /* }}} */ ZEND_API int zend_get_compiled_lineno(TSRMLS_D) /* {{{ */ { return CG(zend_lineno); } /* }}} */ ZEND_API zend_bool zend_is_compiling(TSRMLS_D) /* {{{ */ { return CG(in_compilation); } /* }}} */ static zend_uint get_temporary_variable(zend_op_array *op_array) /* {{{ */ { return (op_array->T)++ * ZEND_MM_ALIGNED_SIZE(sizeof(temp_variable)); } /* }}} */ static int lookup_cv(zend_op_array *op_array, char* name, int name_len, ulong hash TSRMLS_DC) /* {{{ */ { int i = 0; ulong hash_value = hash ? hash : zend_inline_hash_func(name, name_len+1); while (i < op_array->last_var) { if (op_array->vars[i].name == name || (op_array->vars[i].hash_value == hash_value && op_array->vars[i].name_len == name_len && memcmp(op_array->vars[i].name, name, name_len) == 0)) { str_efree(name); return i; } i++; } i = op_array->last_var; op_array->last_var++; if (op_array->last_var > CG(context).vars_size) { CG(context).vars_size += 16; /* FIXME */ op_array->vars = erealloc(op_array->vars, CG(context).vars_size * sizeof(zend_compiled_variable)); } op_array->vars[i].name = zend_new_interned_string(name, name_len + 1, 1 TSRMLS_CC); op_array->vars[i].name_len = name_len; op_array->vars[i].hash_value = hash_value; return i; } /* }}} */ void zend_del_literal(zend_op_array *op_array, int n) /* {{{ */ { zval_dtor(&CONSTANT_EX(op_array, n)); if (n + 1 == op_array->last_literal) { op_array->last_literal--; } else { Z_TYPE(CONSTANT_EX(op_array, n)) = IS_NULL; } } /* }}} */ /* Common part of zend_add_literal and zend_append_individual_literal */ static inline void zend_insert_literal(zend_op_array *op_array, const zval *zv, int literal_position TSRMLS_DC) /* {{{ */ { if (Z_TYPE_P(zv) == IS_STRING || Z_TYPE_P(zv) == IS_CONSTANT) { zval *z = (zval*)zv; Z_STRVAL_P(z) = (char*)zend_new_interned_string(Z_STRVAL_P(zv), Z_STRLEN_P(zv) + 1, 1 TSRMLS_CC); } CONSTANT_EX(op_array, literal_position) = *zv; Z_SET_REFCOUNT(CONSTANT_EX(op_array, literal_position), 2); Z_SET_ISREF(CONSTANT_EX(op_array, literal_position)); op_array->literals[literal_position].hash_value = 0; op_array->literals[literal_position].cache_slot = -1; } /* }}} */ /* Is used while compiling a function, using the context to keep track of an approximate size to avoid to relocate to often. Literals are truncated to actual size in the second compiler pass (pass_two()). */ int zend_add_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; if (i >= CG(context).literals_size) { while (i >= CG(context).literals_size) { CG(context).literals_size += 16; /* FIXME */ } op_array->literals = (zend_literal*)erealloc(op_array->literals, CG(context).literals_size * sizeof(zend_literal)); } zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ /* Is used after normal compilation to append an additional literal. Allocation is done precisely here. */ int zend_append_individual_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; op_array->literals = (zend_literal*)erealloc(op_array->literals, (i + 1) * sizeof(zend_literal)); zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ int zend_add_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_ns_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; const char *ns_separator; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); ns_separator = (const char*)zend_memrchr(Z_STRVAL_P(zv), '\\', Z_STRLEN_P(zv)) + 1; lc_len = Z_STRLEN_P(zv) - (ns_separator - Z_STRVAL_P(zv)); lc_name = zend_str_tolower_dup(ns_separator, lc_len); ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_class_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } if (Z_STRVAL_P(zv)[0] == '\\') { lc_len = Z_STRLEN_P(zv) - 1; lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv) + 1, lc_len); } else { lc_len = Z_STRLEN_P(zv); lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), lc_len); } ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); GET_CACHE_SLOT(ret); return ret; } /* }}} */ int zend_add_const_name_literal(zend_op_array *op_array, const zval *zv, int unqualified TSRMLS_DC) /* {{{ */ { int ret, tmp_literal; char *name, *tmp_name; const char *ns_separator; int name_len, ns_len; zval c; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } /* skip leading '\\' */ if (Z_STRVAL_P(zv)[0] == '\\') { name_len = Z_STRLEN_P(zv) - 1; name = Z_STRVAL_P(zv) + 1; } else { name_len = Z_STRLEN_P(zv); name = Z_STRVAL_P(zv); } ns_separator = zend_memrchr(name, '\\', name_len); if (ns_separator) { ns_len = ns_separator - name; } else { ns_len = 0; } if (ns_len) { /* lowercased namespace name & original constant name */ tmp_name = estrndup(name, name_len); zend_str_tolower(tmp_name, ns_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased namespace name & lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); } if (ns_len) { if (!unqualified) { return ret; } ns_len++; name += ns_len; name_len -= ns_len; } /* original constant name */ tmp_name = estrndup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); return ret; } /* }}} */ #define LITERAL_STRINGL(op, str, len, copy) do { \ zval _c; \ ZVAL_STRINGL(&_c, str, len, copy); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG(op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG_EX(op_array, op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(op_array, &_c TSRMLS_CC); \ } while (0) #define LITERAL_NULL(op) do { \ zval _c; \ INIT_ZVAL( _c); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) static inline zend_bool zend_is_function_or_method_call(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; return ((type & ZEND_PARSED_METHOD_CALL) || (type == ZEND_PARSED_FUNCTION_CALL)); } /* }}} */ void zend_do_binary_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_unary_op(zend_uchar op, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); GET_NODE(result, opline->result); SET_UNUSED(opline->op2); } /* }}} */ #define MAKE_NOP(opline) { opline->opcode = ZEND_NOP; memset(&opline->result,0,sizeof(opline->result)); memset(&opline->op1,0,sizeof(opline->op1)); memset(&opline->op2,0,sizeof(opline->op2)); opline->result_type=opline->op1_type=opline->op2_type=IS_UNUSED; } static void zend_do_op_data(zend_op *data_op, const znode *value TSRMLS_DC) /* {{{ */ { data_op->opcode = ZEND_OP_DATA; SET_NODE(data_op->op1, value); SET_UNUSED(data_op->op2); } /* }}} */ void zend_do_binary_assign_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; switch (last_op->opcode) { case ZEND_FETCH_OBJ_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, op2 TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; case ZEND_FETCH_DIM_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_DIM; zend_do_op_data(opline, op2 TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result,last_op->result); return; default: break; } } opline->opcode = op; SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void fetch_simple_variable_ex(znode *result, znode *varname, int bp, zend_uchar op TSRMLS_DC) /* {{{ */ { zend_op opline; zend_op *opline_ptr; zend_llist *fetch_list_ptr; if (varname->op_type == IS_CONST) { ulong hash = 0; if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } else if (IS_INTERNED(Z_STRVAL(varname->u.constant))) { hash = INTERNED_HASH(Z_STRVAL(varname->u.constant)); } if (!zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC) && !(varname->u.constant.value.str.len == (sizeof("this")-1) && !memcmp(varname->u.constant.value.str.val, "this", sizeof("this"))) && (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE)) { result->op_type = IS_CV; result->u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC); varname->u.constant.value.str.val = (char*)CG(active_op_array)->vars[result->u.op.var].name; result->EA = 0; return; } } if (bp) { opline_ptr = &opline; init_op(opline_ptr TSRMLS_CC); } else { opline_ptr = get_next_op(CG(active_op_array) TSRMLS_CC); } opline_ptr->opcode = op; opline_ptr->result_type = IS_VAR; opline_ptr->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline_ptr->op1, varname); GET_NODE(result, opline_ptr->result); SET_UNUSED(opline_ptr->op2); opline_ptr->extended_value = ZEND_FETCH_LOCAL; if (varname->op_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline_ptr->op1.constant); if (zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC)) { opline_ptr->extended_value = ZEND_FETCH_GLOBAL; } } if (bp) { zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); zend_llist_add_element(fetch_list_ptr, opline_ptr); } } /* }}} */ void fetch_simple_variable(znode *result, znode *varname, int bp TSRMLS_DC) /* {{{ */ { /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ fetch_simple_variable_ex(result, varname, bp, ZEND_FETCH_W TSRMLS_CC); } /* }}} */ void zend_do_fetch_static_member(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { znode class_node; zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline_ptr; zend_op opline; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); } zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (result->op_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[result->u.op.var].name), CG(active_op_array)->vars[result->u.op.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } GET_NODE(result,opline.result); opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; opline_ptr = &opline; zend_llist_add_element(fetch_list_ptr, &opline); } else { le = fetch_list_ptr->head; opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode != ZEND_FETCH_W && opline_ptr->op1_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[opline_ptr->op1.var].name), CG(active_op_array)->vars[opline_ptr->op1.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; COPY_NODE(opline_ptr->op1, opline.result); zend_llist_prepend_element(fetch_list_ptr, &opline); } else { if (opline_ptr->op1_type == IS_CONST) { GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op1.constant); } if (class_node.op_type == IS_CONST) { opline_ptr->op2_type = IS_CONST; opline_ptr->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline_ptr->op2, &class_node); } opline_ptr->extended_value |= ZEND_FETCH_STATIC_MEMBER; } } } /* }}} */ void fetch_array_begin(znode *result, znode *varname, znode *first_dim TSRMLS_DC) /* {{{ */ { fetch_simple_variable(result, varname, 1 TSRMLS_CC); fetch_array_dim(result, result, first_dim TSRMLS_CC); } /* }}} */ void fetch_array_dim(znode *result, const znode *parent, const znode *dim TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (zend_is_function_or_method_call(parent)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, parent); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_DIM_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, parent); SET_NODE(opline.op2, dim); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline.op2.constant)), Z_STRLEN(CONSTANT(opline.op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline.op2.constant)); ZVAL_LONG(&CONSTANT(opline.op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline.op2.constant); } } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void fetch_string_offset(znode *result, const znode *parent, const znode *offset TSRMLS_DC) /* {{{ */ { fetch_array_dim(result, parent, offset TSRMLS_CC); } /* }}} */ void zend_do_print(znode *result, const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->opcode = ZEND_PRINT; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_echo(const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ECHO; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_abstract_method(const znode *function_name, znode *modifiers, const znode *body TSRMLS_DC) /* {{{ */ { char *method_type; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { Z_LVAL(modifiers->u.constant) |= ZEND_ACC_ABSTRACT; method_type = "Interface"; } else { method_type = "Abstract"; } if (modifiers->u.constant.value.lval & ZEND_ACC_ABSTRACT) { if(modifiers->u.constant.value.lval & ZEND_ACC_PRIVATE) { zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot be declared private", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } if (Z_LVAL(body->u.constant) == ZEND_ACC_ABSTRACT) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_RAISE_ABSTRACT_ERROR; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } else { /* we had code in the function body */ zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot contain body", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } else { if (body->u.constant.value.lval == ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Non-abstract method %s::%s() must contain body", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } } /* }}} */ static zend_bool opline_is_fetch_this(const zend_op *opline TSRMLS_DC) /* {{{ */ { if ((opline->opcode == ZEND_FETCH_W) && (opline->op1_type == IS_CONST) && (Z_TYPE(CONSTANT(opline->op1.constant)) == IS_STRING) && (Z_HASH_P(&CONSTANT(opline->op1.constant)) == THIS_HASHVAL) && (Z_STRLEN(CONSTANT(opline->op1.constant)) == (sizeof("this")-1)) && !memcmp(Z_STRVAL(CONSTANT(opline->op1.constant)), "this", sizeof("this"))) { return 1; } else { return 0; } } /* }}} */ void zend_do_assign(znode *result, znode *variable, znode *value TSRMLS_DC) /* {{{ */ { int last_op_number; zend_op *opline; if (value->op_type == IS_CV) { zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (fetch_list_ptr && fetch_list_ptr->head) { opline = (zend_op *)fetch_list_ptr->head->data; if (opline->opcode == ZEND_FETCH_DIM_W && opline->op1_type == IS_CV && opline->op1.var == value->u.op.var) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_R; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->op1_type = IS_CONST; LITERAL_STRINGL(opline->op1, CG(active_op_array)->vars[value->u.op.var].name, CG(active_op_array)->vars[value->u.op.var].name_len, 1); CALCULATE_LITERAL_HASH(opline->op1.constant); SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_LOCAL; GET_NODE(value, opline->result); } } } zend_do_end_variable_parse(variable, BP_VAR_W, 0 TSRMLS_CC); last_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (variable->op_type == IS_CV) { if (variable->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (variable->op_type == IS_VAR) { int n = 0; while (last_op_number - n > 0) { zend_op *last_op; last_op = &CG(active_op_array)->opcodes[last_op_number-n-1]; if (last_op->result_type == IS_VAR && last_op->result.var == variable->u.op.var) { if (last_op->opcode == ZEND_FETCH_OBJ_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, value TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (last_op->opcode == ZEND_FETCH_DIM_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ /* TBFixed: this can realloc opcodes, leaving last_op pointing wrong */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_DIM; zend_do_op_data(opline, value TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (opline_is_fetch_this(last_op TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } else { break; } } n++; } } opline->opcode = ZEND_ASSIGN; SET_NODE(opline->op1, variable); SET_NODE(opline->op2, value); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_assign_ref(znode *result, const znode *lvar, const znode *rvar TSRMLS_DC) /* {{{ */ { zend_op *opline; if (lvar->op_type == IS_CV) { if (lvar->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (lvar->op_type == IS_VAR) { int last_op_number = get_next_op_number(CG(active_op_array)); if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline_is_fetch_this(opline TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ASSIGN_REF; if (zend_is_function_or_method_call(rvar)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } else if (rvar->EA & ZEND_PARSED_NEW) { opline->extended_value = ZEND_RETURNS_NEW; } else { opline->extended_value = 0; } if (result) { opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } else { opline->result_type = IS_UNUSED | EXT_TYPE_UNUSED; } SET_NODE(opline->op1, lvar); SET_NODE(opline->op2, rvar); } /* }}} */ static inline void do_begin_loop(TSRMLS_D) /* {{{ */ { zend_brk_cont_element *brk_cont_element; int parent; parent = CG(context).current_brk_cont; CG(context).current_brk_cont = CG(active_op_array)->last_brk_cont; brk_cont_element = get_next_brk_cont_element(CG(active_op_array)); brk_cont_element->start = get_next_op_number(CG(active_op_array)); brk_cont_element->parent = parent; } /* }}} */ static inline void do_end_loop(int cont_addr, int has_loop_var TSRMLS_DC) /* {{{ */ { if (!has_loop_var) { /* The start fileld is used to free temporary variables in case of exceptions. * We won't try to free something of we don't have loop variable. */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].start = -1; } CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = cont_addr; CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; } /* }}} */ void zend_do_while_cond(const znode *expr, znode *close_bracket_token TSRMLS_DC) /* {{{ */ { int while_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, expr); close_bracket_token->u.op.opline_num = while_cond_op_number; SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_while_end(const znode *while_token, const znode *close_bracket_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* add unconditional jump */ opline->opcode = ZEND_JMP; opline->op1.opline_num = while_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* update while's conditional jmp */ CG(active_op_array)->opcodes[close_bracket_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); do_end_loop(while_token->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_cond(const znode *expr, znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { int for_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZNZ; SET_NODE(opline->op1, expr); /* the conditional expression */ second_semicolon_token->u.op.opline_num = for_cond_op_number; SET_UNUSED(opline->op2); } /* }}} */ void zend_do_for_before_statement(const znode *cond_start, const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = cond_start->u.op.opline_num; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_end(const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = second_semicolon_token->u.op.opline_num+1; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_end_loop(second_semicolon_token->u.op.opline_num+1, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_pre_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_PRE_INC)?ZEND_PRE_INC_OBJ:ZEND_PRE_DEC_OBJ; last_op->result_type = IS_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_post_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_POST_INC)?ZEND_POST_INC_OBJ:ZEND_POST_DEC_OBJ; last_op->result_type = IS_TMP_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_if_cond(const znode *cond, znode *closing_bracket_token TSRMLS_DC) /* {{{ */ { int if_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); closing_bracket_token->u.op.opline_num = if_cond_op_number; SET_UNUSED(opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_if_after_statement(const znode *closing_bracket_token, unsigned char initialize TSRMLS_DC) /* {{{ */ { int if_end_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; /* save for backpatching */ if (initialize) { zend_llist jmp_list; zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); } zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &if_end_op_number); CG(active_op_array)->opcodes[closing_bracket_token->u.op.opline_num].op2.opline_num = if_end_op_number+1; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_if_end(TSRMLS_D) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_llist *jmp_list_ptr; zend_llist_element *le; zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); for (le=jmp_list_ptr->head; le; le = le->next) { CG(active_op_array)->opcodes[*((int *) le->data)].op1.opline_num = next_op_number; } zend_llist_destroy(jmp_list_ptr); zend_stack_del_top(&CG(bp_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_check_writable_variable(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; if (type & ZEND_PARSED_METHOD_CALL) { zend_error(E_COMPILE_ERROR, "Can't use method return value in write context"); } if (type == ZEND_PARSED_FUNCTION_CALL) { zend_error(E_COMPILE_ERROR, "Can't use function return value in write context"); } } /* }}} */ void zend_do_begin_variable_parse(TSRMLS_D) /* {{{ */ { zend_llist fetch_list; zend_llist_init(&fetch_list, sizeof(zend_op), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &fetch_list, sizeof(zend_llist)); } /* }}} */ void zend_do_end_variable_parse(znode *variable, int type, int arg_offset TSRMLS_DC) /* {{{ */ { zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline = NULL; zend_op *opline_ptr; zend_uint this_var = -1; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); le = fetch_list_ptr->head; /* TODO: $foo->x->y->z = 1 should fetch "x" and "y" for R or RW, not just W */ if (le) { opline_ptr = (zend_op *)le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { /* convert to FETCH_?(this) into IS_CV */ if (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE) { this_var = opline_ptr->result.var; if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), Z_STRVAL(CONSTANT(opline_ptr->op1.constant)), Z_STRLEN(CONSTANT(opline_ptr->op1.constant)), Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC); Z_TYPE(CONSTANT(opline_ptr->op1.constant)) = IS_NULL; } else { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); } le = le->next; if (variable->op_type == IS_VAR && variable->u.op.var == this_var) { variable->op_type = IS_CV; variable->u.op.var = CG(active_op_array)->this_var; } } else if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } while (le) { opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode == ZEND_SEPARATE) { if (type != BP_VAR_R && type != BP_VAR_IS) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); } le = le->next; continue; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); if (opline->op1_type == IS_VAR && opline->op1.var == this_var) { opline->op1_type = IS_CV; opline->op1.var = CG(active_op_array)->this_var; } switch (type) { case BP_VAR_R: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode -= 3; break; case BP_VAR_W: break; case BP_VAR_RW: opline->opcode += 3; break; case BP_VAR_IS: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode += 6; /* 3+3 */ break; case BP_VAR_FUNC_ARG: opline->opcode += 9; /* 3+3+3 */ opline->extended_value |= arg_offset; break; case BP_VAR_UNSET: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for unsetting"); } opline->opcode += 12; /* 3+3+3+3 */ break; } le = le->next; } if (opline && type == BP_VAR_W && arg_offset) { opline->extended_value |= ZEND_FETCH_MAKE_REF; } } zend_llist_destroy(fetch_list_ptr); zend_stack_del_top(&CG(bp_stack)); } /* }}} */ void zend_do_add_string(znode *result, const znode *op1, znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline; if (Z_STRLEN(op2->u.constant) > 1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_STRING; } else if (Z_STRLEN(op2->u.constant) == 1) { int ch = *Z_STRVAL(op2->u.constant); /* Free memory and use ZEND_ADD_CHAR in case of 1 character strings */ efree(Z_STRVAL(op2->u.constant)); ZVAL_LONG(&op2->u.constant, ch); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_CHAR; } else { /* String can be empty after a variable at the end of a heredoc */ efree(Z_STRVAL(op2->u.constant)); return; } if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_add_variable(znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_VAR; if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_free(znode *op1 TSRMLS_DC) /* {{{ */ { if (op1->op_type==IS_TMP_VAR) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else if (op1->op_type==IS_VAR) { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; while (opline->opcode == ZEND_END_SILENCE || opline->opcode == ZEND_EXT_FCALL_END || opline->opcode == ZEND_OP_DATA) { opline--; } if (opline->result_type == IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_FETCH_R || opline->opcode == ZEND_FETCH_DIM_R || opline->opcode == ZEND_FETCH_OBJ_R || opline->opcode == ZEND_QM_ASSIGN_VAR) { /* It's very rare and useless case. It's better to use additional FREE opcode and simplify the FETCH handlers their selves */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else { opline->result_type |= EXT_TYPE_UNUSED; } } else { while (opline>CG(active_op_array)->opcodes) { if (opline->opcode == ZEND_FETCH_DIM_R && opline->op1_type == IS_VAR && opline->op1.var == op1->u.op.var) { /* This should the end of a list() construct * Mark its result as unused */ opline->extended_value = ZEND_FETCH_STANDARD; break; } else if (opline->result_type==IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_NEW) { opline->result_type |= EXT_TYPE_UNUSED; } break; } opline--; } } } else if (op1->op_type == IS_CONST) { zval_dtor(&op1->u.constant); } } /* }}} */ int zend_do_verify_access_types(const znode *current_access_type, const znode *new_modifier) /* {{{ */ { if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_PPP_MASK) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Multiple access type modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_ABSTRACT) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Multiple abstract modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_STATIC) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Multiple static modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_FINAL) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Multiple final modifiers are not allowed"); } if (((Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)) & (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) == (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Cannot use the final modifier on an abstract class member"); } return (Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)); } /* }}} */ void zend_do_begin_function_declaration(znode *function_token, znode *function_name, int is_method, int return_reference, znode *fn_flags_znode TSRMLS_DC) /* {{{ */ { zend_op_array op_array; char *name = function_name->u.constant.value.str.val; int name_len = function_name->u.constant.value.str.len; int function_begin_line = function_token->u.op.opline_num; zend_uint fn_flags; const char *lcname; zend_bool orig_interactive; ALLOCA_FLAG(use_heap) if (is_method) { if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((Z_LVAL(fn_flags_znode->u.constant) & ~(ZEND_ACC_STATIC|ZEND_ACC_PUBLIC))) { zend_error(E_COMPILE_ERROR, "Access type for interface method %s::%s() must be omitted", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } Z_LVAL(fn_flags_znode->u.constant) |= ZEND_ACC_ABSTRACT; /* propagates to the rest of the parser */ } fn_flags = Z_LVAL(fn_flags_znode->u.constant); /* must be done *after* the above check */ } else { fn_flags = 0; } if ((fn_flags & ZEND_ACC_STATIC) && (fn_flags & ZEND_ACC_ABSTRACT) && !(CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_STRICT, "Static function %s%s%s() should not be abstract", is_method ? CG(active_class_entry)->name : "", is_method ? "::" : "", Z_STRVAL(function_name->u.constant)); } function_token->u.op_array = CG(active_op_array); orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(&op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; op_array.function_name = name; if (return_reference) { op_array.fn_flags |= ZEND_ACC_RETURN_REFERENCE; } op_array.fn_flags |= fn_flags; op_array.scope = is_method?CG(active_class_entry):NULL; op_array.prototype = NULL; op_array.line_start = zend_get_compiled_lineno(TSRMLS_C); if (is_method) { int result; lcname = zend_new_interned_string(zend_str_tolower_dup(name, name_len), name_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lcname)) { result = zend_hash_quick_add(&CG(active_class_entry)->function_table, lcname, name_len+1, INTERNED_HASH(lcname), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } else { result = zend_hash_add(&CG(active_class_entry)->function_table, lcname, name_len+1, &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } if (result == FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::%s()", CG(active_class_entry)->name, name); } zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); if (fn_flags & ZEND_ACC_ABSTRACT) { CG(active_class_entry)->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (!(fn_flags & ZEND_ACC_PPP_MASK)) { fn_flags |= ZEND_ACC_PUBLIC; } if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } } } else { char *class_lcname; class_lcname = do_alloca(CG(active_class_entry)->name_length + 1, use_heap); zend_str_tolower_copy(class_lcname, CG(active_class_entry)->name, CG(active_class_entry)->name_length); /* Improve after RC: cache the lowercase class name */ if ((CG(active_class_entry)->name_length == name_len) && ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT) && (!memcmp(class_lcname, lcname, name_len))) { if (!CG(active_class_entry)->constructor) { CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } } else if ((name_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)))) { if (CG(active_class_entry)->constructor) { zend_error(E_STRICT, "Redefining already defined constructor for class %s", CG(active_class_entry)->name); } CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1))) { CG(active_class_entry)->destructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1))) { CG(active_class_entry)->clone = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } CG(active_class_entry)->__call = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } CG(active_class_entry)->__callstatic = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } CG(active_class_entry)->__get = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } CG(active_class_entry)->__set = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } CG(active_class_entry)->__unset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } CG(active_class_entry)->__isset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } CG(active_class_entry)->__tostring = (zend_function *) CG(active_op_array); } else if (!(fn_flags & ZEND_ACC_STATIC)) { CG(active_op_array)->fn_flags |= ZEND_ACC_ALLOW_STATIC; } free_alloca(class_lcname, use_heap); } str_efree(lcname); } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zval key; if (CG(current_namespace)) { /* Prefix function name with current namespcae name */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, function_name TSRMLS_CC); op_array.function_name = Z_STRVAL(tmp.u.constant); name_len = Z_STRLEN(tmp.u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), name_len); } else { lcname = zend_str_tolower_dup(name, name_len); } opline->opcode = ZEND_DECLARE_FUNCTION; opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, name_len TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; LITERAL_STRINGL(opline->op2, lcname, name_len, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); opline->extended_value = ZEND_DECLARE_FUNCTION; zend_hash_quick_update(CG(function_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); } if (CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_NOP; opline->lineno = function_begin_line; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } { /* Push a seperator to the switch and foreach stacks */ zend_switch_entry switch_entry; switch_entry.cond.op_type = IS_UNUSED; switch_entry.default_case = 0; switch_entry.control_var = 0; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); { /* Foreach stack separator */ zend_op dummy_opline; dummy_opline.result_type = IS_UNUSED; dummy_opline.op1_type = IS_UNUSED; zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); } } if (CG(doc_comment)) { CG(active_op_array)->doc_comment = CG(doc_comment); CG(active_op_array)->doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_begin_lambda_function_declaration(znode *result, znode *function_token, int return_reference, int is_static TSRMLS_DC) /* {{{ */ { znode function_name; zend_op_array *current_op_array = CG(active_op_array); int current_op_number = get_next_op_number(CG(active_op_array)); zend_op *current_op; function_name.op_type = IS_CONST; ZVAL_STRINGL(&function_name.u.constant, "{closure}", sizeof("{closure}")-1, 1); zend_do_begin_function_declaration(function_token, &function_name, 0, return_reference, NULL TSRMLS_CC); result->op_type = IS_TMP_VAR; result->u.op.var = get_temporary_variable(current_op_array); current_op = &current_op_array->opcodes[current_op_number]; current_op->opcode = ZEND_DECLARE_LAMBDA_FUNCTION; zend_del_literal(current_op_array, current_op->op2.constant); SET_UNUSED(current_op->op2); SET_NODE(current_op->result, result); if (is_static) { CG(active_op_array)->fn_flags |= ZEND_ACC_STATIC; } CG(active_op_array)->fn_flags |= ZEND_ACC_CLOSURE; } /* }}} */ void zend_do_handle_exception(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_HANDLE_EXCEPTION; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_function_declaration(const znode *function_token TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; zend_do_extended_info(TSRMLS_C); zend_do_return(NULL, 0 TSRMLS_CC); pass_two(CG(active_op_array) TSRMLS_CC); zend_release_labels(TSRMLS_C); if (CG(active_class_entry)) { zend_check_magic_method_implementation(CG(active_class_entry), (zend_function*)CG(active_op_array), E_COMPILE_ERROR TSRMLS_CC); } else { /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(CG(active_op_array)->function_name); zend_str_tolower_copy(lcname, CG(active_op_array)->function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME)) && CG(active_op_array)->num_args != 1) { zend_error(E_COMPILE_ERROR, "%s() must take exactly 1 argument", ZEND_AUTOLOAD_FUNC_NAME); } } CG(active_op_array)->line_end = zend_get_compiled_lineno(TSRMLS_C); CG(active_op_array) = function_token->u.op_array; /* Pop the switch and foreach seperators */ zend_stack_del_top(&CG(switch_cond_stack)); zend_stack_del_top(&CG(foreach_copy_stack)); } /* }}} */ void zend_do_receive_arg(zend_uchar op, znode *varname, const znode *offset, const znode *initialization, znode *class_type, zend_uchar pass_by_reference TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_arg_info *cur_arg_info; znode var; if (class_type->op_type == IS_CONST && Z_TYPE(class_type->u.constant) == IS_STRING && Z_STRLEN(class_type->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_type->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } if (zend_is_auto_global_quick(Z_STRVAL(varname->u.constant), Z_STRLEN(varname->u.constant), 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign auto-global variable %s", Z_STRVAL(varname->u.constant)); } else { var.op_type = IS_CV; var.u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(varname->u.constant) = (char*)CG(active_op_array)->vars[var.u.op.var].name; var.EA = 0; if (CG(active_op_array)->vars[var.u.op.var].hash_value == THIS_HASHVAL && Z_STRLEN(varname->u.constant) == sizeof("this")-1 && !memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this")-1)) { if (CG(active_op_array)->scope && (CG(active_op_array)->fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } CG(active_op_array)->this_var = var.u.op.var; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->num_args++; opline->opcode = op; SET_NODE(opline->result, &var); SET_NODE(opline->op1, offset); if (op == ZEND_RECV_INIT) { SET_NODE(opline->op2, initialization); } else { CG(active_op_array)->required_num_args = CG(active_op_array)->num_args; SET_UNUSED(opline->op2); } CG(active_op_array)->arg_info = erealloc(CG(active_op_array)->arg_info, sizeof(zend_arg_info)*(CG(active_op_array)->num_args)); cur_arg_info = &CG(active_op_array)->arg_info[CG(active_op_array)->num_args-1]; cur_arg_info->name = zend_new_interned_string(estrndup(varname->u.constant.value.str.val, varname->u.constant.value.str.len), varname->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->name_len = varname->u.constant.value.str.len; cur_arg_info->type_hint = 0; cur_arg_info->allow_null = 1; cur_arg_info->pass_by_reference = pass_by_reference; cur_arg_info->class_name = NULL; cur_arg_info->class_name_len = 0; if (class_type->op_type != IS_UNUSED) { cur_arg_info->allow_null = 0; if (class_type->u.constant.type != IS_NULL) { if (class_type->u.constant.type == IS_ARRAY) { cur_arg_info->type_hint = IS_ARRAY; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else if (Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Default value for parameters with array type hint can only be an array or NULL"); } } } else if (class_type->u.constant.type == IS_CALLABLE) { cur_arg_info->type_hint = IS_CALLABLE; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with callable type hint can only be NULL"); } } } else { cur_arg_info->type_hint = IS_OBJECT; if (ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_type->u.constant), Z_STRLEN(class_type->u.constant))) { zend_resolve_class_name(class_type, opline->extended_value, 1 TSRMLS_CC); } Z_STRVAL(class_type->u.constant) = (char*)zend_new_interned_string(class_type->u.constant.value.str.val, class_type->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->class_name = class_type->u.constant.value.str.val; cur_arg_info->class_name_len = class_type->u.constant.value.str.len; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with a class type hint can only be NULL"); } } } } } } /* }}} */ int zend_do_begin_function_call(znode *function_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { zend_function *function; char *lcname; char *is_compound = memchr(Z_STRVAL(function_name->u.constant), '\\', Z_STRLEN(function_name->u.constant)); zend_resolve_non_class_name(function_name, check_namespace TSRMLS_CC); if (check_namespace && CG(current_namespace) && !is_compound) { /* We assume we call function from the current namespace if it is not prefixed. */ /* In run-time PHP will check for function with full name and internal function with short name */ zend_do_begin_dynamic_function_call(function_name, 1 TSRMLS_CC); return 1; } lcname = zend_str_tolower_dup(function_name->u.constant.value.str.val, function_name->u.constant.value.str.len); if ((zend_hash_find(CG(function_table), lcname, function_name->u.constant.value.str.len+1, (void **) &function)==FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_FUNCTIONS) && (function->type == ZEND_INTERNAL_FUNCTION))) { zend_do_begin_dynamic_function_call(function_name, 0 TSRMLS_CC); efree(lcname); return 1; /* Dynamic */ } efree(function_name->u.constant.value.str.val); function_name->u.constant.value.str.val = lcname; zend_stack_push(&CG(function_call_stack), (void *) &function, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 0; } /* }}} */ void zend_do_begin_method_call(znode *left_bracket TSRMLS_DC) /* {{{ */ { zend_op *last_op; int last_op_number; unsigned char *ptr = NULL; zend_do_end_variable_parse(left_bracket, BP_VAR_R, 0 TSRMLS_CC); zend_do_begin_variable_parse(TSRMLS_C); last_op_number = get_next_op_number(CG(active_op_array))-1; last_op = &CG(active_op_array)->opcodes[last_op_number]; if ((last_op->op2_type == IS_CONST) && (Z_TYPE(CONSTANT(last_op->op2.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(last_op->op2.constant)) == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !zend_binary_strcasecmp(Z_STRVAL(CONSTANT(last_op->op2.constant)), Z_STRLEN(CONSTANT(last_op->op2.constant)), ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1)) { zend_error(E_COMPILE_ERROR, "Cannot call __clone() method on objects - use 'clone $obj' instead"); } if (last_op->opcode == ZEND_FETCH_OBJ_R) { if (last_op->op2_type == IS_CONST) { zval name; name = CONSTANT(last_op->op2.constant); if (!IS_INTERNED(Z_STRVAL(name))) { Z_STRVAL(name) = estrndup(Z_STRVAL(name), Z_STRLEN(name)); } FREE_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); last_op->op2.constant = zend_add_func_name_literal(CG(active_op_array), &name TSRMLS_CC); GET_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); } last_op->opcode = ZEND_INIT_METHOD_CALL; SET_UNUSED(last_op->result); Z_LVAL(left_bracket->u.constant) = ZEND_INIT_FCALL_BY_NAME; } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (left_bracket->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &left_bracket->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, left_bracket); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_do_clone(znode *result, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CLONE; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_begin_dynamic_function_call(znode *function_name, int ns_call TSRMLS_DC) /* {{{ */ { unsigned char *ptr = NULL; zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (ns_call) { /* In run-time PHP will check for function with full name and internal function with short name */ opline->opcode = ZEND_INIT_NS_FCALL_BY_NAME; SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_ns_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (function_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, function_name); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_resolve_non_class_name(znode *element_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; int len; zval **ns; char *lcname, *compound = memchr(Z_STRVAL(element_name->u.constant), '\\', Z_STRLEN(element_name->u.constant)); if (Z_STRVAL(element_name->u.constant)[0] == '\\') { /* name starts with \ so it is known and unambiguos, nothing to do here but shorten it */ memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+1, Z_STRLEN(element_name->u.constant)); --Z_STRLEN(element_name->u.constant); return; } if(!check_namespace) { return; } if (compound && CG(current_import)) { len = compound - Z_STRVAL(element_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(element_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(element_name->u.constant) -= len; memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+len, Z_STRLEN(element_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, element_name TSRMLS_CC); *element_name = tmp; efree(lcname); return; } efree(lcname); } if (CG(current_namespace)) { tmp = *element_name; Z_STRLEN(tmp.u.constant) = sizeof("\\")-1 + Z_STRLEN(element_name->u.constant) + Z_STRLEN_P(CG(current_namespace)); Z_STRVAL(tmp.u.constant) = (char *) emalloc(Z_STRLEN(tmp.u.constant)+1); memcpy(Z_STRVAL(tmp.u.constant), Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace))]), "\\", sizeof("\\")-1); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace)) + sizeof("\\")-1]), Z_STRVAL(element_name->u.constant), Z_STRLEN(element_name->u.constant)+1); STR_FREE(Z_STRVAL(element_name->u.constant)); *element_name = tmp; } } /* }}} */ void zend_resolve_class_name(znode *class_name, ulong fetch_type, int check_ns_name TSRMLS_DC) /* {{{ */ { char *compound; char *lcname; zval **ns; znode tmp; int len; compound = memchr(Z_STRVAL(class_name->u.constant), '\\', Z_STRLEN(class_name->u.constant)); if (compound) { /* This is a compound class name that contains namespace prefix */ if (Z_STRVAL(class_name->u.constant)[0] == '\\') { /* The STRING name has "\" prefix */ Z_STRLEN(class_name->u.constant) -= 1; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+1, Z_STRLEN(class_name->u.constant)+1); Z_STRVAL(class_name->u.constant) = erealloc( Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1); if (ZEND_FETCH_CLASS_DEFAULT != zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "'\\%s' is an invalid class name", Z_STRVAL(class_name->u.constant)); } } else { if (CG(current_import)) { len = compound - Z_STRVAL(class_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(class_name->u.constant) -= len; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+len, Z_STRLEN(class_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; efree(lcname); return; } efree(lcname); } /* Here name is not prefixed with \ and not imported */ if (CG(current_namespace)) { tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } } } else if (CG(current_import) || CG(current_namespace)) { /* this is a plain name (without \) */ lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns) == SUCCESS) { /* The given name is an import name. Substitute it. */ zval_dtor(&class_name->u.constant); class_name->u.constant = **ns; zval_copy_ctor(&class_name->u.constant); } else if (CG(current_namespace)) { /* plain name, no import - prepend current namespace to it */ tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } efree(lcname); } } /* }}} */ void zend_do_fetch_class(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { long fetch_class_op_number; zend_op *opline; if (class_name->op_type == IS_CONST && Z_TYPE(class_name->u.constant) == IS_STRING && Z_STRLEN(class_name->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_name->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } fetch_class_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CLASS; SET_UNUSED(opline->op1); opline->extended_value = ZEND_FETCH_CLASS_GLOBAL; CG(catch_begin) = fetch_class_op_number; if (class_name->op_type == IS_CONST) { int fetch_type; fetch_type = zend_get_class_fetch_type(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); switch (fetch_type) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: SET_UNUSED(opline->op2); opline->extended_value = fetch_type; zval_dtor(&class_name->u.constant); break; default: zend_resolve_class_name(class_name, opline->extended_value, 0 TSRMLS_CC); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_name->u.constant TSRMLS_CC); break; } } else { SET_NODE(opline->op2, class_name); } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; /* FIXME: Hack so that INIT_FCALL_BY_NAME still knows this is a class */ GET_NODE(result, opline->result); result->EA = opline->extended_value; } /* }}} */ void zend_do_label(znode *label TSRMLS_DC) /* {{{ */ { zend_label dest; if (!CG(context).labels) { ALLOC_HASHTABLE(CG(context).labels); zend_hash_init(CG(context).labels, 4, NULL, NULL, 0); } dest.brk_cont = CG(context).current_brk_cont; dest.opline_num = get_next_op_number(CG(active_op_array)); if (zend_hash_add(CG(context).labels, Z_STRVAL(label->u.constant), Z_STRLEN(label->u.constant) + 1, (void**)&dest, sizeof(zend_label), NULL) == FAILURE) { zend_error(E_COMPILE_ERROR, "Label '%s' already defined", Z_STRVAL(label->u.constant)); } /* Done with label now */ zval_dtor(&label->u.constant); } /* }}} */ void zend_resolve_goto_label(zend_op_array *op_array, zend_op *opline, int pass2 TSRMLS_DC) /* {{{ */ { zend_label *dest; long current, distance; zval *label; if (pass2) { label = opline->op2.zv; } else { label = &CONSTANT_EX(op_array, opline->op2.constant); } if (CG(context).labels == NULL || zend_hash_find(CG(context).labels, Z_STRVAL_P(label), Z_STRLEN_P(label)+1, (void**)&dest) == FAILURE) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; zend_error(E_COMPILE_ERROR, "'goto' to undefined label '%s'", Z_STRVAL_P(label)); } else { /* Label is not defined. Delay to pass 2. */ INC_BPC(op_array); return; } } opline->op1.opline_num = dest->opline_num; zval_dtor(label); Z_TYPE_P(label) = IS_NULL; /* Check that we are not moving into loop or switch */ current = opline->extended_value; for (distance = 0; current != dest->brk_cont; distance++) { if (current == -1) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; } zend_error(E_COMPILE_ERROR, "'goto' into loop or switch statement is disallowed"); } current = op_array->brk_cont_array[current].parent; } if (distance == 0) { /* Nothing to break out of, optimize to ZEND_JMP */ opline->opcode = ZEND_JMP; opline->extended_value = 0; SET_UNUSED(opline->op2); } else { /* Set real break distance */ ZVAL_LONG(label, distance); } if (pass2) { DEC_BPC(op_array); } } /* }}} */ void zend_do_goto(const znode *label TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_GOTO; opline->extended_value = CG(context).current_brk_cont; SET_UNUSED(opline->op1); SET_NODE(opline->op2, label); zend_resolve_goto_label(CG(active_op_array), opline, 0 TSRMLS_CC); } /* }}} */ void zend_release_labels(TSRMLS_D) /* {{{ */ { if (CG(context).labels) { zend_hash_destroy(CG(context).labels); FREE_HASHTABLE(CG(context).labels); } if (!zend_stack_is_empty(&CG(context_stack))) { zend_compiler_context *ctx; zend_stack_top(&CG(context_stack), (void**)&ctx); CG(context) = *ctx; zend_stack_del_top(&CG(context_stack)); } } /* }}} */ void zend_do_build_full_name(znode *result, znode *prefix, znode *name, int is_class_member TSRMLS_DC) /* {{{ */ { zend_uint length; if (!result) { result = prefix; } else { *result = *prefix; } if (is_class_member) { length = sizeof("::")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "::", sizeof("::")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("::")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } else { length = sizeof("\\")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "\\", sizeof("\\")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("\\")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } } /* }}} */ int zend_do_begin_class_member_function_call(znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { znode class_node; unsigned char *ptr = NULL; zend_op *opline; if (method_name->op_type == IS_CONST) { char *lcname = zend_str_tolower_dup(Z_STRVAL(method_name->u.constant), Z_STRLEN(method_name->u.constant)); if ((sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == Z_STRLEN(method_name->u.constant) && memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == 0) { zval_dtor(&method_name->u.constant); method_name->op_type = IS_UNUSED; } efree(lcname); } if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; opline = get_next_op(CG(active_op_array) TSRMLS_CC); } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->extended_value = class_node.EA ; } opline->opcode = ZEND_INIT_STATIC_METHOD_CALL; if (class_node.op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, &class_node); } if (method_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &method_name->u.constant TSRMLS_CC); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } } else { SET_NODE(opline->op2, method_name); } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 1; /* Dynamic */ } /* }}} */ void zend_do_end_function_call(znode *function_name, znode *result, const znode *argument_list, int is_method, int is_dynamic_fcall TSRMLS_DC) /* {{{ */ { zend_op *opline; if (is_method && function_name && function_name->op_type == IS_UNUSED) { /* clone */ if (Z_LVAL(argument_list->u.constant) != 0) { zend_error(E_WARNING, "Clone method does not require arguments"); } opline = &CG(active_op_array)->opcodes[Z_LVAL(function_name->u.constant)]; } else { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (!is_method && !is_dynamic_fcall && function_name->op_type==IS_CONST) { opline->opcode = ZEND_DO_FCALL; SET_NODE(opline->op1, function_name); CALCULATE_LITERAL_HASH(opline->op1.constant); GET_CACHE_SLOT(opline->op1.constant); } else { opline->opcode = ZEND_DO_FCALL_BY_NAME; SET_UNUSED(opline->op1); } } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(result, opline->result) ; SET_UNUSED(opline->op2); zend_stack_del_top(&CG(function_call_stack)); opline->extended_value = Z_LVAL(argument_list->u.constant); } /* }}} */ void zend_do_pass_param(znode *param, zend_uchar op, int offset TSRMLS_DC) /* {{{ */ { zend_op *opline; int original_op=op; zend_function **function_ptr_ptr, *function_ptr; int send_by_reference; int send_function = 0; zend_stack_top(&CG(function_call_stack), (void **) &function_ptr_ptr); function_ptr = *function_ptr_ptr; if (original_op == ZEND_SEND_REF) { if (function_ptr && function_ptr->common.function_name && function_ptr->common.type == ZEND_USER_FUNCTION && !ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed; " "If you would like to pass argument by reference, modify the declaration of %s().", function_ptr->common.function_name); } else { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed"); } return; } if (function_ptr) { if (ARG_MAY_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { if (param->op_type & (IS_VAR|IS_CV) && original_op != ZEND_SEND_VAL) { send_by_reference = 1; if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION | ZEND_ARG_SEND_SILENT; } } else { op = ZEND_SEND_VAL; send_by_reference = 0; } } else { send_by_reference = ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset) ? ZEND_ARG_SEND_BY_REF : 0; } } else { send_by_reference = 0; } if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION; } else if (op == ZEND_SEND_VAL && (param->op_type & (IS_VAR|IS_CV))) { op = ZEND_SEND_VAR_NO_REF; } if (op!=ZEND_SEND_VAR_NO_REF && send_by_reference==ZEND_ARG_SEND_BY_REF) { /* change to passing by reference */ switch (param->op_type) { case IS_VAR: case IS_CV: op = ZEND_SEND_REF; break; default: zend_error(E_COMPILE_ERROR, "Only variables can be passed by reference"); break; } } if (original_op == ZEND_SEND_VAR) { switch (op) { case ZEND_SEND_VAR_NO_REF: zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); break; case ZEND_SEND_VAR: if (function_ptr) { zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(param, BP_VAR_FUNC_ARG, offset TSRMLS_CC); } break; case ZEND_SEND_REF: zend_do_end_variable_parse(param, BP_VAR_W, 0 TSRMLS_CC); break; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (op == ZEND_SEND_VAR_NO_REF) { if (function_ptr) { opline->extended_value = ZEND_ARG_COMPILE_TIME_BOUND | send_by_reference | send_function; } else { opline->extended_value = send_function; } } else { if (function_ptr) { opline->extended_value = ZEND_DO_FCALL; } else { opline->extended_value = ZEND_DO_FCALL_BY_NAME; } } opline->opcode = op; SET_NODE(opline->op1, param); opline->op2.opline_num = offset; SET_UNUSED(opline->op2); } /* }}} */ static int generate_free_switch_expr(const zend_switch_entry *switch_entry TSRMLS_DC) /* {{{ */ { zend_op *opline; if (switch_entry->cond.op_type != IS_VAR && switch_entry->cond.op_type != IS_TMP_VAR) { return (switch_entry->cond.op_type == IS_UNUSED); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry->cond); SET_UNUSED(opline->op2); opline->extended_value = 0; return 0; } /* }}} */ static int generate_free_foreach_copy(const zend_op *foreach_copy TSRMLS_DC) /* {{{ */ { zend_op *opline; /* If we reach the seperator then stop applying the stack */ if (foreach_copy->result_type == IS_UNUSED && foreach_copy->op1_type == IS_UNUSED) { return 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->result_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->result); SET_UNUSED(opline->op2); opline->extended_value = 1; if (foreach_copy->op1_type != IS_UNUSED) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->op1_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->op1); SET_UNUSED(opline->op2); opline->extended_value = 0; } return 0; } /* }}} */ void zend_do_return(znode *expr, int do_end_vparse TSRMLS_DC) /* {{{ */ { zend_op *opline; int start_op_number, end_op_number; if (do_end_vparse) { if ((CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) && !zend_is_function_or_method_call(expr)) { zend_do_end_variable_parse(expr, BP_VAR_W, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(expr, BP_VAR_R, 0 TSRMLS_CC); } } start_op_number = get_next_op_number(CG(active_op_array)); #ifdef ZTS zend_stack_apply_with_argument(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_switch_expr TSRMLS_CC); zend_stack_apply_with_argument(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_foreach_copy TSRMLS_CC); #else zend_stack_apply(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_switch_expr); zend_stack_apply(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_foreach_copy); #endif end_op_number = get_next_op_number(CG(active_op_array)); while (start_op_number < end_op_number) { CG(active_op_array)->opcodes[start_op_number].extended_value |= EXT_TYPE_FREE_ON_RETURN; start_op_number++; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) ? ZEND_RETURN_BY_REF : ZEND_RETURN; if (expr) { SET_NODE(opline->op1, expr); if (do_end_vparse && zend_is_function_or_method_call(expr)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } } else { opline->op1_type = IS_CONST; LITERAL_NULL(opline->op1); } SET_UNUSED(opline->op2); } /* }}} */ static int zend_add_try_element(zend_uint try_op TSRMLS_DC) /* {{{ */ { int try_catch_offset = CG(active_op_array)->last_try_catch++; CG(active_op_array)->try_catch_array = erealloc(CG(active_op_array)->try_catch_array, sizeof(zend_try_catch_element)*CG(active_op_array)->last_try_catch); CG(active_op_array)->try_catch_array[try_catch_offset].try_op = try_op; return try_catch_offset; } /* }}} */ static void zend_add_catch_element(int offset, zend_uint catch_op TSRMLS_DC) /* {{{ */ { CG(active_op_array)->try_catch_array[offset].catch_op = catch_op; } /* }}} */ void zend_do_first_catch(znode *open_parentheses TSRMLS_DC) /* {{{ */ { open_parentheses->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_initialize_try_catch_element(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist jmp_list; zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); zend_add_catch_element(try_token->u.op.opline_num, get_next_op_number(CG(active_op_array)) TSRMLS_CC); } /* }}} */ void zend_do_mark_last_catch(const znode *first_catch, const znode *last_additional_catch TSRMLS_DC) /* {{{ */ { CG(active_op_array)->last--; zend_do_if_end(TSRMLS_C); if (last_additional_catch->u.op.opline_num == -1) { CG(active_op_array)->opcodes[first_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[first_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } else { CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_try(znode *try_token TSRMLS_DC) /* {{{ */ { try_token->u.op.opline_num = zend_add_try_element(get_next_op_number(CG(active_op_array)) TSRMLS_CC); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_catch(znode *try_token, znode *class_name, znode *catch_var, znode *first_catch TSRMLS_DC) /* {{{ */ { long catch_op_number; zend_op *opline; znode catch_class; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); catch_class = *class_name; } else { zend_error(E_COMPILE_ERROR, "Bad class name in the catch statement"); } catch_op_number = get_next_op_number(CG(active_op_array)); if (first_catch) { first_catch->u.op.opline_num = catch_op_number; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CATCH; opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &catch_class.u.constant TSRMLS_CC); opline->op2_type = IS_CV; opline->op2.var = lookup_cv(CG(active_op_array), catch_var->u.constant.value.str.val, catch_var->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(catch_var->u.constant) = (char*)CG(active_op_array)->vars[opline->op2.var].name; opline->result.num = 0; /* 1 means it's the last catch in the block */ try_token->u.op.opline_num = catch_op_number; } /* }}} */ void zend_do_end_catch(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); CG(active_op_array)->opcodes[try_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_throw(const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_THROW; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); } /* }}} */ ZEND_API void function_add_ref(zend_function *function) /* {{{ */ { if (function->type == ZEND_USER_FUNCTION) { zend_op_array *op_array = &function->op_array; (*op_array->refcount)++; if (op_array->static_variables) { HashTable *static_variables = op_array->static_variables; zval *tmp_zval; ALLOC_HASHTABLE(op_array->static_variables); zend_hash_init(op_array->static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(op_array->static_variables, static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_zval, sizeof(zval *)); } op_array->run_time_cache = NULL; } } /* }}} */ static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */ { zend_function *function; if (!ce->parent) { return; } /* You cannot change create_object */ ce->create_object = ce->parent->create_object; /* Inherit special functions if needed */ if (!ce->get_iterator) { ce->get_iterator = ce->parent->get_iterator; } if (!ce->iterator_funcs.funcs) { ce->iterator_funcs.funcs = ce->parent->iterator_funcs.funcs; } if (!ce->__get) { ce->__get = ce->parent->__get; } if (!ce->__set) { ce->__set = ce->parent->__set; } if (!ce->__unset) { ce->__unset = ce->parent->__unset; } if (!ce->__isset) { ce->__isset = ce->parent->__isset; } if (!ce->__call) { ce->__call = ce->parent->__call; } if (!ce->__callstatic) { ce->__callstatic = ce->parent->__callstatic; } if (!ce->__tostring) { ce->__tostring = ce->parent->__tostring; } if (!ce->clone) { ce->clone = ce->parent->clone; } if(!ce->serialize) { ce->serialize = ce->parent->serialize; } if(!ce->unserialize) { ce->unserialize = ce->parent->unserialize; } if (!ce->destructor) { ce->destructor = ce->parent->destructor; } if (ce->constructor) { if (ce->parent->constructor && ce->parent->constructor->common.fn_flags & ZEND_ACC_FINAL) { zend_error(E_ERROR, "Cannot override final %s::%s() with %s::%s()", ce->parent->name, ce->parent->constructor->common.function_name, ce->name, ce->constructor->common.function_name ); } return; } if (zend_hash_find(&ce->parent->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), (void **)&function)==SUCCESS) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), function, sizeof(zend_function), NULL); function_add_ref(function); } else { /* Don't inherit the old style constructor if we already have the new style constructor */ char *lc_class_name; char *lc_parent_class_name; lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); if (!zend_hash_exists(&ce->function_table, lc_class_name, ce->name_length+1)) { lc_parent_class_name = zend_str_tolower_dup(ce->parent->name, ce->parent->name_length); if (!zend_hash_exists(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1) && zend_hash_find(&ce->parent->function_table, lc_parent_class_name, ce->parent->name_length+1, (void **)&function)==SUCCESS) { if (function->common.fn_flags & ZEND_ACC_CTOR) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1, function, sizeof(zend_function), NULL); function_add_ref(function); } } efree(lc_parent_class_name); } efree(lc_class_name); } ce->constructor = ce->parent->constructor; } /* }}} */ char *zend_visibility_string(zend_uint fn_flags) /* {{{ */ { if (fn_flags & ZEND_ACC_PRIVATE) { return "private"; } if (fn_flags & ZEND_ACC_PROTECTED) { return "protected"; } if (fn_flags & ZEND_ACC_PUBLIC) { return "public"; } return ""; } /* }}} */ static void do_inherit_method(zend_function *function) /* {{{ */ { /* The class entry of the derived function intentionally remains the same * as that of the parent class. That allows us to know in which context * we're running, and handle private method calls properly. */ function_add_ref(function); } /* }}} */ static zend_bool zend_do_perform_implementation_check(const zend_function *fe, const zend_function *proto TSRMLS_DC) /* {{{ */ { zend_uint i; /* If it's a user function then arg_info == NULL means we don't have any parameters but * we still need to do the arg number checks. We are only willing to ignore this for internal * functions because extensions don't always define arg_info. */ if (!proto || (!proto->common.arg_info && proto->common.type != ZEND_USER_FUNCTION)) { return 1; } /* Checks for constructors only if they are declared in an interface, * or explicitly marked as abstract */ if ((fe->common.fn_flags & ZEND_ACC_CTOR) && ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)) { return 1; } /* check number of arguments */ if (proto->common.required_num_args < fe->common.required_num_args || proto->common.num_args > fe->common.num_args) { return 0; } if (fe->common.type != ZEND_USER_FUNCTION && (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) != 0 && (fe->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) == 0) { return 0; } /* by-ref constraints on return values are covariant */ if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) { return 0; } for (i=0; i < proto->common.num_args; i++) { if (ZEND_LOG_XOR(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)) { /* Only one has a type hint and the other one doesn't */ return 0; } if (fe->common.arg_info[i].class_name && strcasecmp(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)!=0) { const char *colon; if (fe->common.type != ZEND_USER_FUNCTION) { return 0; } else if (strchr(proto->common.arg_info[i].class_name, '\\') != NULL || (colon = zend_memrchr(fe->common.arg_info[i].class_name, '\\', fe->common.arg_info[i].class_name_len)) == NULL || strcasecmp(colon+1, proto->common.arg_info[i].class_name) != 0) { zend_class_entry **fe_ce, **proto_ce; int found, found2; found = zend_lookup_class(fe->common.arg_info[i].class_name, fe->common.arg_info[i].class_name_len, &fe_ce TSRMLS_CC); found2 = zend_lookup_class(proto->common.arg_info[i].class_name, proto->common.arg_info[i].class_name_len, &proto_ce TSRMLS_CC); /* Check for class alias */ if (found != SUCCESS || found2 != SUCCESS || (*fe_ce)->type == ZEND_INTERNAL_CLASS || (*proto_ce)->type == ZEND_INTERNAL_CLASS || *fe_ce != *proto_ce) { return 0; } } } if (fe->common.arg_info[i].type_hint != proto->common.arg_info[i].type_hint) { /* Incompatible type hint */ return 0; } /* by-ref constraints on arguments are invariant */ if (fe->common.arg_info[i].pass_by_reference != proto->common.arg_info[i].pass_by_reference) { return 0; } } if (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) { for (i=proto->common.num_args; i < fe->common.num_args; i++) { if (!fe->common.arg_info[i].pass_by_reference) { return 0; } } } return 1; } /* }}} */ #define REALLOC_BUF_IF_EXCEED(buf, offset, length, size) \ if (UNEXPECTED(offset - buf + size >= length)) { \ length += size + 1; \ buf = erealloc(buf, length); \ } static char * zend_get_function_declaration(zend_function *fptr TSRMLS_DC) /* {{{ */ { char *offset, *buf; zend_uint length = 1024; offset = buf = (char *)emalloc(length * sizeof(char)); if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { *(offset++) = '&'; *(offset++) = ' '; } if (fptr->common.scope) { memcpy(offset, fptr->common.scope->name, fptr->common.scope->name_length); offset += fptr->common.scope->name_length; *(offset++) = ':'; *(offset++) = ':'; } { size_t name_len = strlen(fptr->common.function_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, name_len); memcpy(offset, fptr->common.function_name, name_len); offset += name_len; } *(offset++) = '('; if (fptr->common.arg_info) { zend_uint i, required; zend_arg_info *arg_info = fptr->common.arg_info; required = fptr->common.required_num_args; for (i = 0; i < fptr->common.num_args;) { if (arg_info->class_name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->class_name_len); memcpy(offset, arg_info->class_name, arg_info->class_name_len); offset += arg_info->class_name_len; *(offset++) = ' '; } else if (arg_info->type_hint) { zend_uint type_name_len; char *type_name = zend_get_type_by_const(arg_info->type_hint); type_name_len = strlen(type_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, type_name_len); memcpy(offset, type_name, type_name_len); offset += type_name_len; *(offset++) = ' '; } if (arg_info->pass_by_reference) { *(offset++) = '&'; } *(offset++) = '$'; if (arg_info->name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->name_len); memcpy(offset, arg_info->name, arg_info->name_len); offset += arg_info->name_len; } else { zend_uint idx = i; memcpy(offset, "param", 5); offset += 5; do { *(offset++) = (char) (idx % 10) + '0'; idx /= 10; } while (idx > 0); } if (i >= required) { *(offset++) = ' '; *(offset++) = '='; *(offset++) = ' '; if (fptr->type == ZEND_USER_FUNCTION) { zend_op *precv = NULL; { zend_uint idx = i; zend_op *op = ((zend_op_array *)fptr)->opcodes; zend_op *end = op + ((zend_op_array *)fptr)->last; ++idx; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT) && op->op1.num == (long)idx) { precv = op; } ++op; } } if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) { zval *zv, zv_copy; int use_copy; ALLOC_ZVAL(zv); *zv = *precv->op2.zv; zval_copy_ctor(zv); INIT_PZVAL(zv); zval_update_constant_ex(&zv, (void*)1, fptr->common.scope TSRMLS_CC); if (Z_TYPE_P(zv) == IS_BOOL) { if (Z_LVAL_P(zv)) { memcpy(offset, "true", 4); offset += 4; } else { memcpy(offset, "false", 5); offset += 5; } } else if (Z_TYPE_P(zv) == IS_NULL) { memcpy(offset, "NULL", 4); offset += 4; } else if (Z_TYPE_P(zv) == IS_STRING) { *(offset++) = '\''; REALLOC_BUF_IF_EXCEED(buf, offset, length, MIN(Z_STRLEN_P(zv), 10)); memcpy(offset, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 10)); offset += MIN(Z_STRLEN_P(zv), 10); if (Z_STRLEN_P(zv) > 10) { *(offset++) = '.'; *(offset++) = '.'; *(offset++) = '.'; } *(offset++) = '\''; } else if (Z_TYPE_P(zv) == IS_ARRAY) { memcpy(offset, "Array", 5); offset += 5; } else { zend_make_printable_zval(zv, &zv_copy, &use_copy); REALLOC_BUF_IF_EXCEED(buf, offset, length, Z_STRLEN(zv_copy)); memcpy(offset, Z_STRVAL(zv_copy), Z_STRLEN(zv_copy)); offset += Z_STRLEN(zv_copy); if (use_copy) { zval_dtor(&zv_copy); } } zval_ptr_dtor(&zv); } } else { memcpy(offset, "NULL", 4); offset += 4; } } if (++i < fptr->common.num_args) { *(offset++) = ','; *(offset++) = ' '; } arg_info++; REALLOC_BUF_IF_EXCEED(buf, offset, length, 32); } } *(offset++) = ')'; *offset = '\0'; return buf; } /* }}} */ static void do_inheritance_check_on_method(zend_function *child, zend_function *parent TSRMLS_DC) /* {{{ */ { zend_uint child_flags; zend_uint parent_flags = parent->common.fn_flags; if (parent->common.fn_flags & ZEND_ACC_ABSTRACT && parent->common.scope != (child->common.prototype ? child->common.prototype->common.scope : child->common.scope) && child->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_IMPLEMENTED_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Can't inherit abstract function %s::%s() (previously declared abstract in %s)", parent->common.scope->name, child->common.function_name, child->common.prototype ? child->common.prototype->common.scope->name : child->common.scope->name); } if (parent_flags & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot override final method %s::%s()", ZEND_FN_SCOPE_NAME(parent), child->common.function_name); } child_flags = child->common.fn_flags; /* You cannot change from static to non static and vice versa. */ if ((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC)) { if (child->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot make non static method %s::%s() static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } else { zend_error(E_COMPILE_ERROR, "Cannot make static method %s::%s() non static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } } /* Disallow making an inherited method abstract. */ if ((child_flags & ZEND_ACC_ABSTRACT) && !(parent_flags & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Cannot make non abstract method %s::%s() abstract in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } if (parent_flags & ZEND_ACC_CHANGED) { child->common.fn_flags |= ZEND_ACC_CHANGED; } else { /* Prevent derived classes from restricting access that was available in parent classes */ if ((child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::%s() must be %s (as in class %s)%s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if (((child_flags & ZEND_ACC_PPP_MASK) < (parent_flags & ZEND_ACC_PPP_MASK)) && ((parent_flags & ZEND_ACC_PPP_MASK) & ZEND_ACC_PRIVATE)) { child->common.fn_flags |= ZEND_ACC_CHANGED; } } if (parent_flags & ZEND_ACC_PRIVATE) { child->common.prototype = NULL; } else if (parent_flags & ZEND_ACC_ABSTRACT) { child->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; child->common.prototype = parent; } else if (!(parent->common.fn_flags & ZEND_ACC_CTOR) || (parent->common.prototype && (parent->common.prototype->common.scope->ce_flags & ZEND_ACC_INTERFACE))) { /* ctors only have a prototype if it comes from an interface */ child->common.prototype = parent->common.prototype ? parent->common.prototype : parent; } if (child->common.prototype && (child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { if (!zend_do_perform_implementation_check(child, child->common.prototype TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s::%s() must be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_get_function_declaration(child->common.prototype TSRMLS_CC)); } } else if (EG(error_reporting) & E_STRICT || EG(user_error_handler)) { /* Check E_STRICT (or custom error handler) before the check so that we save some time */ if (!zend_do_perform_implementation_check(child, parent TSRMLS_CC)) { char *method_prototype = zend_get_function_declaration(child->common.prototype TSRMLS_CC); zend_error(E_STRICT, "Declaration of %s::%s() should be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, method_prototype); efree(method_prototype); } } } /* }}} */ static zend_bool do_inherit_method_check(HashTable *child_function_table, zend_function *parent, const zend_hash_key *hash_key, zend_class_entry *child_ce) /* {{{ */ { zend_uint parent_flags = parent->common.fn_flags; zend_function *child; TSRMLS_FETCH(); if (zend_hash_quick_find(child_function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child)==FAILURE) { if (parent_flags & (ZEND_ACC_ABSTRACT)) { child_ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } return 1; /* method doesn't exist in child, copy from parent */ } do_inheritance_check_on_method(child, parent TSRMLS_CC); return 0; } /* }}} */ static zend_bool do_inherit_property_access_check(HashTable *target_ht, zend_property_info *parent_info, const zend_hash_key *hash_key, zend_class_entry *ce) /* {{{ */ { zend_property_info *child_info; zend_class_entry *parent_ce = ce->parent; if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW)) { if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { child_info->flags |= ZEND_ACC_CHANGED; } else { zend_hash_quick_update(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, parent_info, sizeof(zend_property_info), (void **) &child_info); if(ce->type & ZEND_INTERNAL_CLASS) { zend_duplicate_property_info_internal(child_info); } else { zend_duplicate_property_info(child_info); } child_info->flags &= ~ZEND_ACC_PRIVATE; /* it's not private anymore */ child_info->flags |= ZEND_ACC_SHADOW; /* but it's a shadow of private */ } return 0; /* don't copy access information to child */ } if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { if ((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s", (parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", parent_ce->name, hash_key->arKey, (child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ce->name, hash_key->arKey); } if(parent_info->flags & ZEND_ACC_CHANGED) { child_info->flags |= ZEND_ACC_CHANGED; } if ((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ce->name, hash_key->arKey, zend_visibility_string(parent_info->flags), parent_ce->name, (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if ((child_info->flags & ZEND_ACC_STATIC) == 0) { Z_DELREF_P(ce->default_properties_table[parent_info->offset]); ce->default_properties_table[parent_info->offset] = ce->default_properties_table[child_info->offset]; ce->default_properties_table[child_info->offset] = NULL; child_info->offset = parent_info->offset; } return 0; /* Don't copy from parent */ } else { return 1; /* Copy from parent */ } } /* }}} */ static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce TSRMLS_CC) == FAILURE) { zend_error(E_CORE_ERROR, "Class %s could not implement interface %s", ce->name, iface->name); } if (ce == iface) { zend_error(E_ERROR, "Interface %s cannot implement itself", ce->name); } } /* }}} */ ZEND_API void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface TSRMLS_DC) /* {{{ */ { /* expects interface to be contained in ce's interface list already */ zend_uint i, ce_num, if_num = iface->num_interfaces; zend_class_entry *entry; if (if_num==0) { return; } ce_num = ce->num_interfaces; if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } /* Inherit the interfaces, only if they're not already inherited by the class */ while (if_num--) { entry = iface->interfaces[if_num]; for (i = 0; i < ce_num; i++) { if (ce->interfaces[i] == entry) { break; } } if (i == ce_num) { ce->interfaces[ce->num_interfaces++] = entry; } } /* and now call the implementing handlers */ while (ce_num < ce->num_interfaces) { do_implement_interface(ce, ce->interfaces[ce_num++] TSRMLS_CC); } } /* }}} */ #ifdef ZTS static void zval_internal_ctor(zval **p) /* {{{ */ { zval *orig_ptr = *p; ALLOC_ZVAL(*p); MAKE_COPY_ZVAL(&orig_ptr, *p); } /* }}} */ # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) (((parent_ce)->type != (ce)->type) ? zval_internal_ctor : zval_add_ref)) #else # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) zval_add_ref) #endif ZEND_API void zend_do_inheritance(zend_class_entry *ce, zend_class_entry *parent_ce TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; if ((ce->ce_flags & ZEND_ACC_INTERFACE) && !(parent_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ce->name, parent_ce->name); } if (parent_ce->ce_flags & ZEND_ACC_FINAL_CLASS) { zend_error(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ce->name, parent_ce->name); } ce->parent = parent_ce; /* Copy serialize/unserialize callbacks */ if (!ce->serialize) { ce->serialize = parent_ce->serialize; } if (!ce->unserialize) { ce->unserialize = parent_ce->unserialize; } /* Inherit interfaces */ zend_do_inherit_interfaces(ce, parent_ce TSRMLS_CC); /* Inherit properties */ if (parent_ce->default_properties_count) { int i = ce->default_properties_count + parent_ce->default_properties_count; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_properties_count) { while (i-- > parent_ce->default_properties_count) { ce->default_properties_table[i] = ce->default_properties_table[i - parent_ce->default_properties_count]; } } for (i = 0; i < parent_ce->default_properties_count; i++) { ce->default_properties_table[i] = parent_ce->default_properties_table[i]; if (ce->default_properties_table[i]) { #ifdef ZTS if (parent_ce->type != ce->type) { zval *p; ALLOC_ZVAL(p); MAKE_COPY_ZVAL(&ce->default_properties_table[i], p); ce->default_properties_table[i] = p; } else { Z_ADDREF_P(ce->default_properties_table[i]); } #else Z_ADDREF_P(ce->default_properties_table[i]); #endif } } ce->default_properties_count += parent_ce->default_properties_count; } if (parent_ce->type != ce->type) { /* User class extends internal class */ zend_update_class_constants(parent_ce TSRMLS_CC); if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = erealloc(ce->default_static_members_table, sizeof(void*) * i); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&CE_STATIC_MEMBERS(parent_ce)[i]); ce->default_static_members_table[i] = CE_STATIC_MEMBERS(parent_ce)[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; ce->static_members_table = ce->default_static_members_table; } } else { if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&parent_ce->default_static_members_table[i]); ce->default_static_members_table[i] = parent_ce->default_static_members_table[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } } for (zend_hash_internal_pointer_reset(&ce->properties_info); zend_hash_get_current_data(&ce->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->properties_info)) { if (property_info->ce == ce) { if (property_info->flags & ZEND_ACC_STATIC) { property_info->offset += parent_ce->default_static_members_count; } else { property_info->offset += parent_ce->default_properties_count; } } } zend_hash_merge_ex(&ce->properties_info, &parent_ce->properties_info, (copy_ctor_func_t) (ce->type & ZEND_INTERNAL_CLASS ? zend_duplicate_property_info_internal : zend_duplicate_property_info), sizeof(zend_property_info), (merge_checker_func_t) do_inherit_property_access_check, ce); zend_hash_merge(&ce->constants_table, &parent_ce->constants_table, zval_property_ctor(parent_ce, ce), NULL, sizeof(zval *), 0); zend_hash_merge_ex(&ce->function_table, &parent_ce->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_inherit_parent_constructor(ce); if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS && ce->type == ZEND_INTERNAL_CLASS) { ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } else if (!(ce->ce_flags & ZEND_ACC_IMPLEMENT_INTERFACES) && !(ce->ce_flags & ZEND_ACC_IMPLEMENT_TRAITS)) { /* The verification will be done in runtime by ZEND_VERIFY_ABSTRACT_CLASS */ zend_verify_abstract_class(ce TSRMLS_CC); } ce->ce_flags |= parent_ce->ce_flags & ZEND_HAS_STATIC_IN_METHODS; } /* }}} */ static zend_bool do_inherit_constant_check(HashTable *child_constants_table, const zval **parent_constant, const zend_hash_key *hash_key, const zend_class_entry *iface) /* {{{ */ { zval **old_constant; if (zend_hash_quick_find(child_constants_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**)&old_constant) == SUCCESS) { if (*old_constant != *parent_constant) { zend_error(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", hash_key->arKey, iface->name); } return 0; } return 1; } /* }}} */ static int do_interface_constant_check(zval **val TSRMLS_DC, int num_args, va_list args, const zend_hash_key *key) /* {{{ */ { zend_class_entry **iface = va_arg(args, zend_class_entry**); do_inherit_constant_check(&(*iface)->constants_table, (const zval **) val, key, *iface); return ZEND_HASH_APPLY_KEEP; } /* }}} */ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_iface_num = ce->num_interfaces; zend_uint parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0; for (i = 0; i < ce->num_interfaces; i++) { if (ce->interfaces[i] == NULL) { memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i)); i--; } else if (ce->interfaces[i] == iface) { if (i < parent_iface_num) { ignore = 1; } else { zend_error(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ce->name, iface->name); } } } if (ignore) { /* Check for attempt to redeclare interface constants */ zend_hash_apply_with_arguments(&ce->constants_table TSRMLS_CC, (apply_func_args_t) do_interface_constant_check, 1, &iface); } else { if (ce->num_interfaces >= current_iface_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } } ce->interfaces[ce->num_interfaces++] = iface; zend_hash_merge_ex(&ce->constants_table, &iface->constants_table, (copy_ctor_func_t) zval_add_ref, sizeof(zval *), (merge_checker_func_t) do_inherit_constant_check, iface); zend_hash_merge_ex(&ce->function_table, &iface->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_implement_interface(ce, iface TSRMLS_CC); zend_do_inherit_interfaces(ce, iface TSRMLS_CC); } } /* }}} */ ZEND_API void zend_do_implement_trait(zend_class_entry *ce, zend_class_entry *trait TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_trait_num = ce->num_traits; zend_uint parent_trait_num = ce->parent ? ce->parent->num_traits : 0; for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == NULL) { memmove(ce->traits + i, ce->traits + i + 1, sizeof(zend_class_entry*) * (--ce->num_traits - i)); i--; } else if (ce->traits[i] == trait) { if (i < parent_trait_num) { ignore = 1; } } } if (!ignore) { if (ce->num_traits >= current_trait_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->traits = (zend_class_entry **) realloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } else { ce->traits = (zend_class_entry **) erealloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } } ce->traits[ce->num_traits++] = trait; } } /* }}} */ static int zend_traits_merge_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { size_t current; size_t i; size_t count; HashTable* resulting_table; HashTable** function_tables; zend_class_entry *ce; size_t collision = 0; size_t abstract_solved = 0; zend_function* other_trait_fn; current = va_arg(args, size_t); /* index of current trait */ count = va_arg(args, size_t); resulting_table = va_arg(args, HashTable*); function_tables = va_arg(args, HashTable**); ce = va_arg(args, zend_class_entry*); for (i = 0; i < count; i++) { if (i == current) { continue; /* just skip this, cause its the table this function is applied on */ } if (zend_hash_quick_find(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&other_trait_fn) == SUCCESS) { /* if it is an abstract method, there is no collision */ if (other_trait_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* we can savely free and remove it from other table */ zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } else { /* if it is not an abstract method, there is still no collision */ /* if fn is an abstract method */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* just mark as solved, will be added if its own trait is processed */ abstract_solved = 1; } else { /* but else, we have a collision of non-abstract methods */ collision++; zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } } } if (collision) { zend_function* class_fn; /* make sure method is not already overridden in class */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&class_fn) == FAILURE || class_fn->common.scope != ce) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because there are collisions with other trait methods on %s", fn->common.function_name, ce->name); } zend_function_dtor(fn); } else if (abstract_solved) { zend_function_dtor(fn); } else { /* Add it to result function table */ if (zend_hash_quick_add(resulting_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, fn, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating resulting trait method table", fn->common.function_name); } } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ /* {{{ Originates from php_runkit_function_copy_ctor Duplicate structures in an op_array where necessary to make an outright duplicate */ static void zend_traits_duplicate_function(zend_function *fe, zend_class_entry *target_ce, char *newname TSRMLS_DC) { zend_literal *literals_copy; zend_compiled_variable *dupvars; zend_op *opcode_copy; zval class_name_zv; int class_name_literal; int i; int number_of_literals; if (fe->op_array.static_variables) { HashTable *tmpHash; ALLOC_HASHTABLE(tmpHash); zend_hash_init(tmpHash, zend_hash_num_elements(fe->op_array.static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_apply_with_arguments(fe->op_array.static_variables TSRMLS_CC, (apply_func_args_t)zval_copy_static_var, 1, tmpHash); fe->op_array.static_variables = tmpHash; } number_of_literals = fe->op_array.last_literal; literals_copy = (zend_literal*)emalloc(number_of_literals * sizeof(zend_literal)); for (i = 0; i < number_of_literals; i++) { literals_copy[i] = fe->op_array.literals[i]; zval_copy_ctor(&literals_copy[i].constant); } fe->op_array.literals = literals_copy; fe->op_array.refcount = emalloc(sizeof(zend_uint)); *(fe->op_array.refcount) = 1; if (fe->op_array.vars) { i = fe->op_array.last_var; dupvars = safe_emalloc(fe->op_array.last_var, sizeof(zend_compiled_variable), 0); while (i > 0) { i--; dupvars[i].name = estrndup(fe->op_array.vars[i].name, fe->op_array.vars[i].name_len); dupvars[i].name_len = fe->op_array.vars[i].name_len; dupvars[i].hash_value = fe->op_array.vars[i].hash_value; } fe->op_array.vars = dupvars; } else { fe->op_array.vars = NULL; } opcode_copy = safe_emalloc(sizeof(zend_op), fe->op_array.last, 0); for(i = 0; i < fe->op_array.last; i++) { opcode_copy[i] = fe->op_array.opcodes[i]; if (opcode_copy[i].op1_type != IS_CONST) { if (opcode_copy[i].op1.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op1.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op1.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op1.jmp_addr - fe->op_array.opcodes); } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op1.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op1.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op1.zv = &fe->op_array.literals[class_name_literal].constant; } } if (opcode_copy[i].op2_type != IS_CONST) { if (opcode_copy[i].op2.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op2.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op2.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op2.jmp_addr - fe->op_array.opcodes); } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op2.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op2.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op2.zv = &fe->op_array.literals[class_name_literal].constant; } } } fe->op_array.opcodes = opcode_copy; fe->op_array.function_name = newname; /* was setting it to fe which does not work since fe is stack allocated and not a stable address */ /* fe->op_array.prototype = fe->op_array.prototype; */ if (fe->op_array.arg_info) { zend_arg_info *tmpArginfo; tmpArginfo = safe_emalloc(sizeof(zend_arg_info), fe->op_array.num_args, 0); for(i = 0; i < fe->op_array.num_args; i++) { tmpArginfo[i] = fe->op_array.arg_info[i]; tmpArginfo[i].name = estrndup(tmpArginfo[i].name, tmpArginfo[i].name_len); if (tmpArginfo[i].class_name) { tmpArginfo[i].class_name = estrndup(tmpArginfo[i].class_name, tmpArginfo[i].class_name_len); } } fe->op_array.arg_info = tmpArginfo; } fe->op_array.doc_comment = estrndup(fe->op_array.doc_comment, fe->op_array.doc_comment_len); fe->op_array.try_catch_array = (zend_try_catch_element*)estrndup((char*)fe->op_array.try_catch_array, sizeof(zend_try_catch_element) * fe->op_array.last_try_catch); fe->op_array.brk_cont_array = (zend_brk_cont_element*)estrndup((char*)fe->op_array.brk_cont_array, sizeof(zend_brk_cont_element) * fe->op_array.last_brk_cont); } /* }}} */ static void zend_add_magic_methods(zend_class_entry* ce, const char* mname, uint mname_len, zend_function* fe TSRMLS_DC) { if ( !strncmp(mname, ZEND_CLONE_FUNC_NAME, mname_len)) { ce->clone = fe; fe->common.fn_flags |= ZEND_ACC_CLONE; } else if (!strncmp(mname, ZEND_CONSTRUCTOR_FUNC_NAME, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } else if (!strncmp(mname, ZEND_DESTRUCTOR_FUNC_NAME, mname_len)) { ce->destructor = fe; fe->common.fn_flags |= ZEND_ACC_DTOR; } else if (!strncmp(mname, ZEND_GET_FUNC_NAME, mname_len)) ce->__get = fe; else if (!strncmp(mname, ZEND_SET_FUNC_NAME, mname_len)) ce->__set = fe; else if (!strncmp(mname, ZEND_CALL_FUNC_NAME, mname_len)) ce->__call = fe; else if (!strncmp(mname, ZEND_UNSET_FUNC_NAME, mname_len)) ce->__unset = fe; else if (!strncmp(mname, ZEND_ISSET_FUNC_NAME, mname_len)) ce->__isset = fe; else if (!strncmp(mname, ZEND_CALLSTATIC_FUNC_NAME, mname_len)) ce->__callstatic= fe; else if (!strncmp(mname, ZEND_TOSTRING_FUNC_NAME, mname_len)) ce->__tostring = fe; else if (ce->name_length + 1 == mname_len) { char *lowercase_name = emalloc(ce->name_length + 1); zend_str_tolower_copy(lowercase_name, ce->name, ce->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, ce->name_length + 1, 1 TSRMLS_CC); if (!memcmp(mname, lowercase_name, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } str_efree(lowercase_name); } } static int zend_traits_merge_functions_to_class(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zend_class_entry *ce = va_arg(args, zend_class_entry*); int add = 0; zend_function* existing_fn; zend_function fn_copy, *fn_copy_p; zend_function* prototype = NULL; /* is used to determine the prototype according to the inheritance chain */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &existing_fn) == FAILURE) { add = 1; /* not found */ } else if (existing_fn->common.scope != ce) { add = 1; /* or inherited from other class or interface */ /* it is just a reference which was added to the subclass while doing the inheritance */ /* so we can deleted now, and will add the overriding method afterwards */ /* except, if we try to add an abstract function, then we should not delete the inherited one */ /* delete inherited fn if the function to be added is not abstract */ if ((fn->common.fn_flags & ZEND_ACC_ABSTRACT) == 0) { zend_hash_quick_del(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } if (add) { zend_function* parent_function; if (ce->parent && zend_hash_quick_find(&ce->parent->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &parent_function) != FAILURE) { prototype = parent_function; /* ->common.fn_flags |= ZEND_ACC_ABSTRACT; */ /* we got that method in the parent class, and are going to override it, except, if the trait is just asking to have an abstract method implemented. */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* then we clean up an skip this method */ zend_function_dtor(fn); return ZEND_HASH_APPLY_REMOVE; } } fn->common.scope = ce; fn->common.prototype = prototype; if (prototype && (prototype->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT || prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { fn->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; } else if (fn->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT) { /* remove ZEND_ACC_IMPLEMENTED_ABSTRACT flag, think it shouldn't be copied to class */ fn->common.fn_flags = fn->common.fn_flags - ZEND_ACC_IMPLEMENTED_ABSTRACT; } /* check whether the trait method fullfills the inheritance requirements */ if (prototype) { do_inheritance_check_on_method(fn, prototype TSRMLS_CC); } if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (fn->op_array.static_variables) { ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, ce, estrdup(fn->common.function_name) TSRMLS_CC); if (zend_hash_quick_update(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, &fn_copy, sizeof(zend_function), (void**)&fn_copy_p)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating class method table", hash_key->arKey); } zend_add_magic_methods(ce, hash_key->arKey, hash_key->nKeyLength, fn_copy_p TSRMLS_CC); zend_function_dtor(fn); } else { zend_function_dtor(fn); } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ static int zend_traits_copy_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { HashTable* target; zend_class_entry *target_ce; zend_trait_alias** aliases; HashTable* exclude_table; char* lcname; unsigned int fnname_len; zend_function fn_copy; void* dummy; size_t i = 0; target = va_arg(args, HashTable*); target_ce = va_arg(args, zend_class_entry*); aliases = va_arg(args, zend_trait_alias**); exclude_table = va_arg(args, HashTable*); fnname_len = strlen(fn->common.function_name); /* apply aliases which are qualified with a class name, there should not be any ambiguity */ if (aliases) { while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias != NULL && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && aliases[i]->trait_method->mname_len == fnname_len && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(aliases[i]->alias, aliases[i]->alias_len) TSRMLS_CC); /* if it is 0, no modifieres has been changed */ if (aliases[i]->modifiers) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } lcname = zend_str_tolower_dup(aliases[i]->alias, aliases[i]->alias_len); if (zend_hash_add(target, lcname, aliases[i]->alias_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add aliased trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } efree(lcname); } i++; } } lcname = zend_str_tolower_dup(fn->common.function_name, fnname_len); if (exclude_table == NULL || zend_hash_find(exclude_table, lcname, fnname_len, &dummy) == FAILURE) { /* is not in hashtable, thus, function is not to be excluded */ fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(fn->common.function_name, fnname_len) TSRMLS_CC); /* apply aliases which are not qualified by a class name, or which have not * alias name, just setting visibility */ if (aliases) { i = 0; while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias == NULL && aliases[i]->modifiers != 0 && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && (aliases[i]->trait_method->mname_len == fnname_len) && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } i++; } } if (zend_hash_add(target, lcname, fnname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } } efree(lcname); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* Copies function table entries to target function table with applied aliasing */ static void zend_traits_copy_trait_function_table(HashTable *target, zend_class_entry *target_ce, HashTable *source, zend_trait_alias** aliases, HashTable* exclude_table TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_arguments(source TSRMLS_CC, (apply_func_args_t)zend_traits_copy_functions, 4, target, target_ce, aliases, exclude_table); } /* }}} */ static void zend_traits_init_trait_structures(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i, j = 0; zend_trait_precedence *cur_precedence; zend_trait_method_reference *cur_method_ref; /* resolve class references */ if (ce->trait_precedences) { i = 0; while ((cur_precedence = ce->trait_precedences[i])) { if (cur_precedence->exclude_from_classes) { cur_precedence->trait_method->ce = zend_fetch_class(cur_precedence->trait_method->class_name, cur_precedence->trait_method->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); j = 0; while (cur_precedence->exclude_from_classes[j]) { char* class_name = (char*)cur_precedence->exclude_from_classes[j]; zend_uint name_length = strlen(class_name); cur_precedence->exclude_from_classes[j] = zend_fetch_class(class_name, name_length, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); efree(class_name); j++; } } i++; } } if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { if (ce->trait_aliases[i]->trait_method->class_name) { cur_method_ref = ce->trait_aliases[i]->trait_method; cur_method_ref->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); } i++; } } } /* }}} */ static void zend_traits_compile_exclude_table(HashTable* exclude_table, zend_trait_precedence **precedences, zend_class_entry *trait) /* {{{ */ { size_t i = 0, j; if (!precedences) { return; } while (precedences[i]) { if (precedences[i]->exclude_from_classes) { j = 0; while (precedences[i]->exclude_from_classes[j]) { if (precedences[i]->exclude_from_classes[j] == trait) { zend_uint lcname_len = precedences[i]->trait_method->mname_len; char *lcname = zend_str_tolower_dup(precedences[i]->trait_method->method_name, lcname_len); if (zend_hash_add(exclude_table, lcname, lcname_len, NULL, 0, NULL) == FAILURE) { efree(lcname); zend_error(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", precedences[i]->trait_method->method_name, trait->name); } efree(lcname); } ++j; } } ++i; } } /* }}} */ static void zend_do_traits_method_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { HashTable** function_tables; HashTable* resulting_table; HashTable exclude_table; size_t i; /* prepare copies of trait function tables for combination */ function_tables = malloc(sizeof(HashTable*) * ce->num_traits); resulting_table = (HashTable *) malloc(sizeof(HashTable)); /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(resulting_table, 10, NULL, NULL, 1, 0); for (i = 0; i < ce->num_traits; i++) { function_tables[i] = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(function_tables[i], ce->traits[i]->function_table.nNumOfElements, NULL, NULL, 1, 0); if (ce->trait_precedences) { /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(&exclude_table, 2, NULL, NULL, 0, 0); zend_traits_compile_exclude_table(&exclude_table, ce->trait_precedences, ce->traits[i]); /* copies functions, applies defined aliasing, and excludes unused trait methods */ zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, &exclude_table TSRMLS_CC); zend_hash_graceful_destroy(&exclude_table); } else { zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, NULL TSRMLS_CC); } } /* now merge trait methods */ for (i = 0; i < ce->num_traits; i++) { zend_hash_apply_with_arguments(function_tables[i] TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions, 5, i, ce->num_traits, resulting_table, function_tables, ce); } /* Now the resulting_table contains all trait methods we would have to * add to the class in the following step the methods are inserted into the method table * if there is already a method with the same name it is replaced iff ce != fn.scope * --> all inherited methods are overridden, methods defined in the class are left untouched */ zend_hash_apply_with_arguments(resulting_table TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions_to_class, 1, ce); /* free temporary function tables */ for (i = 0; i < ce->num_traits; i++) { /* zend_hash_destroy(function_tables[i]); */ zend_hash_graceful_destroy(function_tables[i]); free(function_tables[i]); } free(function_tables); /* free temporary resulting table */ /* zend_hash_destroy(resulting_table); */ zend_hash_graceful_destroy(resulting_table); free(resulting_table); } /* }}} */ static zend_class_entry* find_first_definition(zend_class_entry *ce, size_t current_trait, const char* prop_name, int prop_name_length, ulong prop_hash, zend_class_entry *coliding_ce) /* {{{ */ { size_t i; zend_property_info *coliding_prop; for (i = 0; (i < current_trait) && (i < ce->num_traits); i++) { if (zend_hash_quick_find(&ce->traits[i]->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS) { return ce->traits[i]; } } return coliding_ce; } /* }}} */ static void zend_do_traits_property_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i; zend_property_info *property_info; zend_property_info *coliding_prop; zval compare_result; const char* prop_name; int prop_name_length; ulong prop_hash; const char* class_name_unused; zend_bool prop_found; zend_bool not_compatible; zval* prop_value; /* In the following steps the properties are inserted into the property table * for that, a very strict approach is applied: * - check for compatibility, if not compatible with any property in class -> fatal * - if compatible, then strict notice */ for (i = 0; i < ce->num_traits; i++) { for (zend_hash_internal_pointer_reset(&ce->traits[i]->properties_info); zend_hash_get_current_data(&ce->traits[i]->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->traits[i]->properties_info)) { /* first get the unmangeld name if necessary, * then check whether the property is already there */ if ((property_info->flags & ZEND_ACC_PPP_MASK) == ZEND_ACC_PUBLIC) { prop_hash = property_info->h; prop_name = property_info->name; prop_name_length = property_info->name_length; prop_found = zend_hash_quick_find(&ce->properties_info, property_info->name, property_info->name_length+1, property_info->h, (void **) &coliding_prop) == SUCCESS; } else { /* for private and protected we need to unmangle the names */ zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name_unused, &prop_name); prop_name_length = strlen(prop_name); prop_hash = zend_get_hash_value(prop_name, prop_name_length + 1); prop_found = zend_hash_quick_find(&ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS; } /* next: check for conflicts with current class */ if (prop_found) { if (coliding_prop->flags & ZEND_ACC_SHADOW) { /* this one is inherited, lets look it up in its own class */ zend_hash_quick_find(&coliding_prop->ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop); } if ((coliding_prop->flags & ZEND_ACC_PPP_MASK) == (property_info->flags & ZEND_ACC_PPP_MASK)) { /* flags are identical, now the value needs to be checked */ if (property_info->flags & ZEND_ACC_STATIC) { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_static_members_table[coliding_prop->offset], ce->traits[i]->default_static_members_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } else { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_properties_table[coliding_prop->offset], ce->traits[i]->default_properties_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } } else { /* the flags are not identical, thus, we assume properties are not compatible */ not_compatible = 1; } if (not_compatible) { zend_error(E_COMPILE_ERROR, "%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } else { zend_error(E_STRICT, "%s and %s define the same property ($%s) in the composition of %s. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } } /* property not found, so lets add it */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); zend_declare_property_ex(ce, prop_name, prop_name_length, prop_value, property_info->flags, property_info->doc_comment, property_info->doc_comment_len TSRMLS_CC); } } } /* }}} */ ZEND_API void zend_do_bind_traits(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { if (ce->num_traits <= 0) { return; } /* complete initialization of trait strutures in ce */ zend_traits_init_trait_structures(ce TSRMLS_CC); /* first care about all methods to be flattened into the class */ zend_do_traits_method_binding(ce TSRMLS_CC); /* then flatten the properties into it, to, mostly to notfiy developer about problems */ zend_do_traits_property_binding(ce TSRMLS_CC); /* verify that all abstract methods from traits have been implemented */ zend_verify_abstract_class(ce TSRMLS_CC); /* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */ if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { ce->ce_flags -= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } } /* }}} */ ZEND_API int do_bind_function(const zend_op_array *op_array, zend_op *opline, HashTable *function_table, zend_bool compile_time) /* {{{ */ { zend_function *function; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } zend_hash_quick_find(function_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void *) &function); if (zend_hash_quick_add(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), function, sizeof(zend_function), NULL)==FAILURE) { int error_level = compile_time ? E_COMPILE_ERROR : E_ERROR; zend_function *old_function; if (zend_hash_quick_find(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), (void *) &old_function)==SUCCESS && old_function->type == ZEND_USER_FUNCTION && old_function->op_array.last > 0) { zend_error(error_level, "Cannot redeclare %s() (previously declared in %s:%d)", function->common.function_name, old_function->op_array.filename, old_function->op_array.opcodes[0].lineno); } else { zend_error(error_level, "Cannot redeclare %s()", function->common.function_name); } return FAILURE; } else { (*function->op_array.refcount)++; function->op_array.static_variables = NULL; /* NULL out the unbound function */ return SUCCESS; } } /* }}} */ void zend_add_trait_precedence(znode *precedence_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_precedences, precedence_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_add_trait_alias(znode *alias_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_aliases, alias_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_prepare_reference(znode *result, znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { zend_trait_method_reference *method_ref = emalloc(sizeof(zend_trait_method_reference)); method_ref->ce = NULL; /* REM: There should not be a need for copying, zend_do_begin_class_declaration is also just using that string */ if (class_name) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); method_ref->class_name = Z_STRVAL(class_name->u.constant); method_ref->cname_len = Z_STRLEN(class_name->u.constant); } else { method_ref->class_name = NULL; method_ref->cname_len = 0; } method_ref->method_name = Z_STRVAL(method_name->u.constant); method_ref->mname_len = Z_STRLEN(method_name->u.constant); result->u.op.ptr = method_ref; result->op_type = IS_TMP_VAR; } /* }}} */ void zend_prepare_trait_alias(znode *result, znode *method_reference, znode *modifiers, znode *alias TSRMLS_DC) /* {{{ */ { zend_trait_alias *trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_alias->modifiers = Z_LVAL(modifiers->u.constant); if (Z_LVAL(modifiers->u.constant) == ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot use 'static' as method modifier"); return; } if (alias) { trait_alias->alias = Z_STRVAL(alias->u.constant); trait_alias->alias_len = Z_STRLEN(alias->u.constant); } else { trait_alias->alias = NULL; } trait_alias->function = NULL; result->u.op.ptr = trait_alias; } /* }}} */ void zend_prepare_trait_precedence(znode *result, znode *method_reference, znode *trait_list TSRMLS_DC) /* {{{ */ { zend_trait_precedence *trait_precedence = emalloc(sizeof(zend_trait_precedence)); trait_precedence->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_precedence->exclude_from_classes = (zend_class_entry**) trait_list->u.op.ptr; trait_precedence->function = NULL; result->u.op.ptr = trait_precedence; } /* }}} */ ZEND_API zend_class_entry *do_bind_class(const zend_op_array* op_array, const zend_op *opline, HashTable *class_table, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } if (zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce)==FAILURE) { zend_error(E_COMPILE_ERROR, "Internal Zend error - Missing class information for %s", Z_STRVAL_P(op1)); return NULL; } else { ce = *pce; } ce->refcount++; if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), &ce, sizeof(zend_class_entry *), NULL)==FAILURE) { ce->refcount--; if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return NULL; } else { if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLEMENT_INTERFACES))) { zend_verify_abstract_class(ce TSRMLS_CC); } return ce; } } /* }}} */ ZEND_API zend_class_entry *do_bind_inherited_class(const zend_op_array *op_array, const zend_op *opline, HashTable *class_table, zend_class_entry *parent_ce, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; int found_ce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } found_ce = zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce); if (found_ce == FAILURE) { if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", Z_STRVAL_P(op2)); } return NULL; } else { ce = *pce; } if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ce->name, parent_ce->name); } else if ((parent_ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ce->name, parent_ce->name); } zend_do_inheritance(ce, parent_ce TSRMLS_CC); ce->refcount++; /* Register the derived class */ if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), pce, sizeof(zend_class_entry *), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return ce; } /* }}} */ void zend_do_early_binding(TSRMLS_D) /* {{{ */ { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; HashTable *table; while (opline->opcode == ZEND_TICKS && opline > CG(active_op_array)->opcodes) { opline--; } switch (opline->opcode) { case ZEND_DECLARE_FUNCTION: if (do_bind_function(CG(active_op_array), opline, CG(function_table), 1) == FAILURE) { return; } table = CG(function_table); break; case ZEND_DECLARE_CLASS: if (do_bind_class(CG(active_op_array), opline, CG(class_table), 1 TSRMLS_CC) == NULL) { return; } table = CG(class_table); break; case ZEND_DECLARE_INHERITED_CLASS: { zend_op *fetch_class_opline = opline-1; zval *parent_name; zend_class_entry **pce; parent_name = &CONSTANT(fetch_class_opline->op2.constant); if ((zend_lookup_class(Z_STRVAL_P(parent_name), Z_STRLEN_P(parent_name), &pce TSRMLS_CC) == FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_CLASSES) && ((*pce)->type == ZEND_INTERNAL_CLASS))) { if (CG(compiler_options) & ZEND_COMPILE_DELAYED_BINDING) { zend_uint *opline_num = &CG(active_op_array)->early_binding; while (*opline_num != -1) { opline_num = &CG(active_op_array)->opcodes[*opline_num].result.opline_num; } *opline_num = opline - CG(active_op_array)->opcodes; opline->opcode = ZEND_DECLARE_INHERITED_CLASS_DELAYED; opline->result_type = IS_UNUSED; opline->result.opline_num = -1; } return; } if (do_bind_inherited_class(CG(active_op_array), opline, CG(class_table), *pce, 1 TSRMLS_CC) == NULL) { return; } /* clear unnecessary ZEND_FETCH_CLASS opcode */ zend_del_literal(CG(active_op_array), fetch_class_opline->op2.constant); MAKE_NOP(fetch_class_opline); table = CG(class_table); break; } case ZEND_VERIFY_ABSTRACT_CLASS: case ZEND_ADD_INTERFACE: case ZEND_ADD_TRAIT: case ZEND_BIND_TRAITS: /* We currently don't early-bind classes that implement interfaces */ /* Classes with traits are handled exactly the same, no early-bind here */ return; default: zend_error(E_COMPILE_ERROR, "Invalid binding type"); return; } zend_hash_quick_del(table, Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant)), Z_HASH_P(&CONSTANT(opline->op1.constant))); zend_del_literal(CG(active_op_array), opline->op1.constant); zend_del_literal(CG(active_op_array), opline->op2.constant); MAKE_NOP(opline); } /* }}} */ ZEND_API void zend_do_delayed_early_binding(const zend_op_array *op_array TSRMLS_DC) /* {{{ */ { if (op_array->early_binding != -1) { zend_bool orig_in_compilation = CG(in_compilation); zend_uint opline_num = op_array->early_binding; zend_class_entry **pce; CG(in_compilation) = 1; while (opline_num != -1) { if (zend_lookup_class(Z_STRVAL_P(op_array->opcodes[opline_num-1].op2.zv), Z_STRLEN_P(op_array->opcodes[opline_num-1].op2.zv), &pce TSRMLS_CC) == SUCCESS) { do_bind_inherited_class(op_array, &op_array->opcodes[opline_num], EG(class_table), *pce, 0 TSRMLS_CC); } opline_num = op_array->opcodes[opline_num].result.opline_num; } CG(in_compilation) = orig_in_compilation; } } /* }}} */ void zend_do_boolean_or_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_or_end(znode *result, const znode *expr1, const znode *expr2, znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_boolean_and_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_and_end(znode *result, const znode *expr1, const znode *expr2, const znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_do_while_begin(TSRMLS_D) /* {{{ */ { do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_do_while_end(const znode *do_token, const znode *expr_open_bracket, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ; SET_NODE(opline->op1, expr); opline->op2.opline_num = do_token->u.op.opline_num; SET_UNUSED(opline->op2); do_end_loop(expr_open_bracket->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_brk_cont(zend_uchar op, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->op1.opline_num = CG(context).current_brk_cont; SET_UNUSED(opline->op1); if (expr) { if (expr->op_type != IS_CONST) { zend_error(E_COMPILE_ERROR, "'%s' operator with non-constant operand is no longer supported", op == ZEND_BRK ? "break" : "continue"); } else if (Z_TYPE(expr->u.constant) != IS_LONG || Z_LVAL(expr->u.constant) < 1) { zend_error(E_COMPILE_ERROR, "'%s' operator accepts only positive numbers", op == ZEND_BRK ? "break" : "continue"); } SET_NODE(opline->op2, expr); } else { LITERAL_LONG(opline->op2, 1); opline->op2_type = IS_CONST; } } /* }}} */ void zend_do_switch_cond(const znode *cond TSRMLS_DC) /* {{{ */ { zend_switch_entry switch_entry; switch_entry.cond = *cond; switch_entry.default_case = -1; switch_entry.control_var = -1; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_switch_end(const znode *case_list TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); /* add code to jmp to default case */ if (switch_entry_ptr->default_case != -1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->op1.opline_num = switch_entry_ptr->default_case; } if (case_list->op_type != IS_UNUSED) { /* non-empty switch */ int next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* remember break/continue loop information */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; if (switch_entry_ptr->cond.op_type==IS_VAR || switch_entry_ptr->cond.op_type==IS_TMP_VAR) { /* emit free for the switch condition*/ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry_ptr->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_UNUSED(opline->op2); } if (switch_entry_ptr->cond.op_type == IS_CONST) { zval_dtor(&switch_entry_ptr->cond.u.constant); } zend_stack_del_top(&CG(switch_cond_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_case_before_statement(const znode *case_list, znode *case_token, const znode *case_expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); int next_op_number; zend_switch_entry *switch_entry_ptr; znode result; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); if (switch_entry_ptr->control_var == -1) { switch_entry_ptr->control_var = get_temporary_variable(CG(active_op_array)); } opline->opcode = ZEND_CASE; opline->result.var = switch_entry_ptr->control_var; opline->result_type = IS_TMP_VAR; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_NODE(opline->op2, case_expr); if (opline->op1_type == IS_CONST) { zval_copy_ctor(&CONSTANT(opline->op1.constant)); } GET_NODE(&result, opline->result); next_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, &result); SET_UNUSED(opline->op2); case_token->u.op.opline_num = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_case_after_statement(znode *result, const znode *case_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); result->u.op.opline_num = next_op_number; switch (CG(active_op_array)->opcodes[case_token->u.op.opline_num].opcode) { case ZEND_JMP: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); break; case ZEND_JMPZ: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); break; } } /* }}} */ void zend_do_default_before_statement(const znode *case_list, znode *default_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); default_token->u.op.opline_num = next_op_number; next_op_number = get_next_op_number(CG(active_op_array)); switch_entry_ptr->default_case = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_begin_class_declaration(const znode *class_token, znode *class_name, const znode *parent_class_name TSRMLS_DC) /* {{{ */ { zend_op *opline; int doing_inheritance = 0; zend_class_entry *new_class_entry; char *lcname; int error = 0; zval **ns_name, key; if (CG(active_class_entry)) { zend_error(E_COMPILE_ERROR, "Class declarations may not be nested"); return; } lcname = zend_str_tolower_dup(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); if (!(strcmp(lcname, "self") && strcmp(lcname, "parent"))) { efree(lcname); zend_error(E_COMPILE_ERROR, "Cannot use '%s' as class name as it is reserved", Z_STRVAL(class_name->u.constant)); } /* Class name must not conflict with import names */ if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns_name) == SUCCESS) { error = 1; } if (CG(current_namespace)) { /* Prefix class name with name of current namespace */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); class_name = &tmp; efree(lcname); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); } if (error) { char *tmp = zend_str_tolower_dup(Z_STRVAL_PP(ns_name), Z_STRLEN_PP(ns_name)); if (Z_STRLEN_PP(ns_name) != Z_STRLEN(class_name->u.constant) || memcmp(tmp, lcname, Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "Cannot declare class %s because the name is already in use", Z_STRVAL(class_name->u.constant)); } efree(tmp); } new_class_entry = emalloc(sizeof(zend_class_entry)); new_class_entry->type = ZEND_USER_CLASS; new_class_entry->name = zend_new_interned_string(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1, 1 TSRMLS_CC); new_class_entry->name_length = Z_STRLEN(class_name->u.constant); zend_initialize_class_data(new_class_entry, 1 TSRMLS_CC); new_class_entry->info.user.filename = zend_get_compiled_filename(TSRMLS_C); new_class_entry->info.user.line_start = class_token->u.op.opline_num; new_class_entry->ce_flags |= class_token->EA; if (parent_class_name && parent_class_name->op_type != IS_UNUSED) { switch (parent_class_name->EA) { case ZEND_FETCH_CLASS_SELF: zend_error(E_COMPILE_ERROR, "Cannot use 'self' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_PARENT: zend_error(E_COMPILE_ERROR, "Cannot use 'parent' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use 'static' as class name as it is reserved"); break; default: break; } doing_inheritance = 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, new_class_entry->name_length TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; if (doing_inheritance) { /* Make sure a trait does not try to extend a class */ if ((new_class_entry->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "A trait (%s) cannot extend a class", new_class_entry->name); } opline->extended_value = parent_class_name->u.op.var; opline->opcode = ZEND_DECLARE_INHERITED_CLASS; } else { opline->opcode = ZEND_DECLARE_CLASS; } LITERAL_STRINGL(opline->op2, lcname, new_class_entry->name_length, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); zend_hash_quick_update(CG(class_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &new_class_entry, sizeof(zend_class_entry *), NULL); CG(active_class_entry) = new_class_entry; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(&CG(implementing_class), opline->result); if (CG(doc_comment)) { CG(active_class_entry)->info.user.doc_comment = CG(doc_comment); CG(active_class_entry)->info.user.doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ static void do_verify_abstract_class(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_VERIFY_ABSTRACT_CLASS; SET_NODE(opline->op1, &CG(implementing_class)); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_class_declaration(const znode *class_token, const znode *parent_token TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); if (ce->constructor) { ce->constructor->common.fn_flags |= ZEND_ACC_CTOR; if (ce->constructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Constructor %s::%s() cannot be static", ce->name, ce->constructor->common.function_name); } } if (ce->destructor) { ce->destructor->common.fn_flags |= ZEND_ACC_DTOR; if (ce->destructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Destructor %s::%s() cannot be static", ce->name, ce->destructor->common.function_name); } } if (ce->clone) { ce->clone->common.fn_flags |= ZEND_ACC_CLONE; if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static", ce->name, ce->clone->common.function_name); } } ce->info.user.line_end = zend_get_compiled_lineno(TSRMLS_C); /* Check for traits and proceed like with interfaces. * The only difference will be a combined handling of them in the end. * Thus, we need another opcode here. */ if (ce->num_traits > 0) { zend_op *opline; ce->traits = NULL; ce->num_traits = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_TRAITS; /* opcode generation: */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BIND_TRAITS; SET_NODE(opline->op1, &CG(implementing_class)); } if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) && ((parent_token->op_type != IS_UNUSED) || (ce->num_interfaces > 0))) { zend_verify_abstract_class(ce TSRMLS_CC); if (ce->num_interfaces) { do_verify_abstract_class(TSRMLS_C); } } /* Inherit interfaces; reset number to zero, we need it for above check and * will restore it during actual implementation. * The ZEND_ACC_IMPLEMENT_INTERFACES flag disables double call to * zend_verify_abstract_class() */ if (ce->num_interfaces > 0) { ce->interfaces = NULL; ce->num_interfaces = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_INTERFACES; } CG(active_class_entry) = NULL; } /* }}} */ void zend_do_implements_interface(znode *interface_name TSRMLS_DC) /* {{{ */ { zend_op *opline; /* Traits can not implement interfaces */ if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface on '%s' since it is a Trait", Z_STRVAL(interface_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(interface_name->u.constant), Z_STRLEN(interface_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface name as it is reserved", Z_STRVAL(interface_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_INTERFACE; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(interface_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = (opline->extended_value & ~ZEND_FETCH_CLASS_MASK) | ZEND_FETCH_CLASS_INTERFACE; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &interface_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_interfaces++; } /* }}} */ void zend_do_implements_trait(znode *trait_name TSRMLS_DC) /* {{{ */ { zend_op *opline; switch (zend_get_class_fetch_type(Z_STRVAL(trait_name->u.constant), Z_STRLEN(trait_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as trait name as it is reserved", Z_STRVAL(trait_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_TRAIT; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(trait_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = ZEND_FETCH_CLASS_TRAIT; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &trait_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_traits++; } /* }}} */ ZEND_API void zend_mangle_property_name(char **dest, int *dest_length, const char *src1, int src1_length, const char *src2, int src2_length, int internal) /* {{{ */ { char *prop_name; int prop_name_length; prop_name_length = 1 + src1_length + 1 + src2_length; prop_name = pemalloc(prop_name_length + 1, internal); prop_name[0] = '\0'; memcpy(prop_name + 1, src1, src1_length+1); memcpy(prop_name + 1 + src1_length + 1, src2, src2_length+1); *dest = prop_name; *dest_length = prop_name_length; } /* }}} */ static int zend_strnlen(const char* s, int maxlen) /* {{{ */ { int len = 0; while (*s++ && maxlen--) len++; return len; } /* }}} */ ZEND_API int zend_unmangle_property_name(const char *mangled_property, int len, const char **class_name, const char **prop_name) /* {{{ */ { int class_name_len; *class_name = NULL; if (mangled_property[0]!=0) { *prop_name = mangled_property; return SUCCESS; } if (len < 3 || mangled_property[1]==0) { zend_error(E_NOTICE, "Illegal member variable name"); *prop_name = mangled_property; return FAILURE; } class_name_len = zend_strnlen(mangled_property+1, --len - 1) + 1; if (class_name_len >= len || mangled_property[class_name_len]!=0) { zend_error(E_NOTICE, "Corrupt member variable name"); *prop_name = mangled_property; return FAILURE; } *class_name = mangled_property+1; *prop_name = (*class_name)+class_name_len; return SUCCESS; } /* }}} */ void zend_do_declare_property(const znode *var_name, const znode *value, zend_uint access_type TSRMLS_DC) /* {{{ */ { zval *property; zend_property_info *existing_property_info; char *comment = NULL; int comment_len = 0; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Interfaces may not include member variables"); } if (access_type & ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Properties cannot be declared abstract"); } if (access_type & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot declare property %s::$%s final, the final modifier is allowed only for methods and classes", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } if (zend_hash_find(&CG(active_class_entry)->properties_info, var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, (void **) &existing_property_info)==SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::$%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } ALLOC_ZVAL(property); if (value) { *property = value->u.constant; } else { INIT_PZVAL(property); Z_TYPE_P(property) = IS_NULL; } if (CG(doc_comment)) { comment = CG(doc_comment); comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } zend_declare_property_ex(CG(active_class_entry), zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len + 1, 0 TSRMLS_CC), var_name->u.constant.value.str.len, property, access_type, comment, comment_len TSRMLS_CC); efree(var_name->u.constant.value.str.val); } /* }}} */ void zend_do_declare_class_constant(znode *var_name, const znode *value TSRMLS_DC) /* {{{ */ { zval *property; const char *cname = NULL; int result; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed in class constants"); return; } if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Traits cannot have constants"); return; } ALLOC_ZVAL(property); *property = value->u.constant; cname = zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, 0 TSRMLS_CC); if (IS_INTERNED(cname)) { result = zend_hash_quick_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, INTERNED_HASH(cname), &property, sizeof(zval *), NULL); } else { result = zend_hash_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, &property, sizeof(zval *), NULL); } if (result == FAILURE) { FREE_ZVAL(property); zend_error(E_COMPILE_ERROR, "Cannot redefine class constant %s::%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } FREE_PNODE(var_name); if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_fetch_property(znode *result, znode *object, const znode *property TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (object->op_type == IS_CV) { if (object->u.op.var == CG(active_op_array)->this_var) { object->op_type = IS_UNUSED; /* this means $this for objects */ } } else if (fetch_list_ptr->count == 1) { zend_llist_element *le = fetch_list_ptr->head; zend_op *opline_ptr = (zend_op *) le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); SET_UNUSED(opline_ptr->op1); /* this means $this for objects */ SET_NODE(opline_ptr->op2, property); /* if it was usual fetch, we change it to object fetch */ switch (opline_ptr->opcode) { case ZEND_FETCH_W: opline_ptr->opcode = ZEND_FETCH_OBJ_W; break; case ZEND_FETCH_R: opline_ptr->opcode = ZEND_FETCH_OBJ_R; break; case ZEND_FETCH_RW: opline_ptr->opcode = ZEND_FETCH_OBJ_RW; break; case ZEND_FETCH_IS: opline_ptr->opcode = ZEND_FETCH_OBJ_IS; break; case ZEND_FETCH_UNSET: opline_ptr->opcode = ZEND_FETCH_OBJ_UNSET; break; case ZEND_FETCH_FUNC_ARG: opline_ptr->opcode = ZEND_FETCH_OBJ_FUNC_ARG; break; } if (opline_ptr->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline_ptr->op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline_ptr->op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op2.constant); } GET_NODE(result, opline_ptr->result); return; } } if (zend_is_function_or_method_call(object)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, object); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_OBJ_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, object); SET_NODE(opline.op2, property); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline.op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op2.constant); } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void zend_do_halt_compiler_register(TSRMLS_D) /* {{{ */ { char *name, *cfilename; char haltoff[] = "__COMPILER_HALT_OFFSET__"; int len, clen; cfilename = zend_get_compiled_filename(TSRMLS_C); clen = strlen(cfilename); zend_mangle_property_name(&name, &len, haltoff, sizeof(haltoff) - 1, cfilename, clen, 0); zend_register_long_constant(name, len+1, zend_get_scanned_file_offset(TSRMLS_C), CONST_CS, 0 TSRMLS_CC); pefree(name, 0); if (CG(in_namespace)) { zend_do_end_namespace(TSRMLS_C); } } /* }}} */ void zend_do_push_object(const znode *object TSRMLS_DC) /* {{{ */ { zend_stack_push(&CG(object_stack), object, sizeof(znode)); } /* }}} */ void zend_do_pop_object(znode *object TSRMLS_DC) /* {{{ */ { if (object) { znode *tmp; zend_stack_top(&CG(object_stack), (void **) &tmp); *object = *tmp; } zend_stack_del_top(&CG(object_stack)); } /* }}} */ void zend_do_begin_new_object(znode *new_token, znode *class_type TSRMLS_DC) /* {{{ */ { zend_op *opline; unsigned char *ptr = NULL; new_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_NEW; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, class_type); SET_UNUSED(opline->op2); zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(unsigned char *)); } /* }}} */ void zend_do_end_new_object(znode *result, const znode *new_token, const znode *argument_list TSRMLS_DC) /* {{{ */ { znode ctor_result; zend_do_end_function_call(NULL, &ctor_result, argument_list, 1, 0 TSRMLS_CC); zend_do_free(&ctor_result TSRMLS_CC); CG(active_op_array)->opcodes[new_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, CG(active_op_array)->opcodes[new_token->u.op.opline_num].result); } /* }}} */ static zend_constant* zend_get_ct_const(const zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = NULL; if (Z_STRVAL_P(const_name)[0] == '\\') { if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name), (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name)-1); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name), (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } } else if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)+1, (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name)+1, (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } if (c->flags & CONST_CT_SUBST) { return c; } if (all_internal_constants_substitution && (c->flags & CONST_PERSISTENT) && !(CG(compiler_options) & ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION) && Z_TYPE(c->value) != IS_CONSTANT && Z_TYPE(c->value) != IS_CONSTANT_ARRAY) { return c; } return NULL; } /* }}} */ static int zend_constant_ct_subst(znode *result, zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = zend_get_ct_const(const_name, all_internal_constants_substitution TSRMLS_CC); if (c) { zval_dtor(const_name); result->op_type = IS_CONST; result->u.constant = c->value; zval_copy_ctor(&result->u.constant); INIT_PZVAL(&result->u.constant); return 1; } return 0; } /* }}} */ void zend_do_fetch_constant(znode *result, znode *constant_container, znode *constant_name, int mode, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; zend_op *opline; int type; char *compound; ulong fetch_type = 0; if (constant_container) { switch (mode) { case ZEND_CT: /* this is a class constant */ type = zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant)); if (ZEND_FETCH_CLASS_STATIC == type) { zend_error(E_ERROR, "\"static::\" is not allowed in compile-time constants"); } else if (ZEND_FETCH_CLASS_DEFAULT == type) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } zend_do_build_full_name(NULL, constant_container, constant_name, 1 TSRMLS_CC); *result = *constant_container; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: if (constant_container->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant))) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } else { zend_do_fetch_class(&tmp, constant_container TSRMLS_CC); constant_container = &tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); if (constant_container->op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &constant_container->u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, constant_container); } SET_NODE(opline->op2, constant_name); CALCULATE_LITERAL_HASH(opline->op2.constant); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } GET_NODE(result, opline->result); break; } return; } /* namespace constant */ /* only one that did not contain \ from the start can be converted to string if unknown */ switch (mode) { case ZEND_CT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); /* this is a namespace constant, or an unprefixed constant */ if (zend_constant_ct_subst(result, &constant_name->u.constant, 0 TSRMLS_CC)) { break; } zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(!compound) { fetch_type |= IS_CONSTANT_UNQUALIFIED; } *result = *constant_name; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(zend_constant_ct_subst(result, &constant_name->u.constant, 1 TSRMLS_CC)) { break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; if (compound) { /* the name is unambiguous */ opline->extended_value = 0; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } else { opline->extended_value = IS_CONSTANT_UNQUALIFIED; if (CG(current_namespace)) { opline->extended_value |= IS_CONSTANT_IN_NAMESPACE; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 1 TSRMLS_CC); } else { opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } } GET_CACHE_SLOT(opline->op2.constant); break; } } /* }}} */ void zend_do_shell_exec(znode *result, const znode *cmd TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); switch (cmd->op_type) { case IS_CONST: case IS_TMP_VAR: opline->opcode = ZEND_SEND_VAL; break; default: opline->opcode = ZEND_SEND_VAR; break; } SET_NODE(opline->op1, cmd); opline->op2.opline_num = 0; opline->extended_value = ZEND_DO_FCALL; SET_UNUSED(opline->op2); /* FIXME: exception support not added to this op2 */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DO_FCALL; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; LITERAL_STRINGL(opline->op1, estrndup("shell_exec", sizeof("shell_exec")-1), sizeof("shell_exec")-1, 0); CALCULATE_LITERAL_HASH(opline->op1.constant); opline->op1_type = IS_CONST; GET_CACHE_SLOT(opline->op1.constant); opline->extended_value = 1; SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_init_array(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_ARRAY; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; GET_NODE(result, opline->result); if (expr) { SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } } else { SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_array_element(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_ARRAY_ELEMENT; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_static_array_element(znode *result, znode *offset, const znode *expr) /* {{{ */ { zval *element; ALLOC_ZVAL(element); *element = expr->u.constant; if (offset) { switch (offset->u.constant.type & IS_CONSTANT_TYPE_MASK) { case IS_CONSTANT: /* Ugly hack to denote that this value has a constant index */ Z_TYPE_P(element) |= IS_CONSTANT_INDEX; Z_STRVAL(offset->u.constant) = erealloc(Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+1] = Z_TYPE(offset->u.constant); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+2] = 0; zend_symtable_update(result->u.constant.value.ht, Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_STRING: zend_symtable_update(result->u.constant.value.ht, offset->u.constant.value.str.val, offset->u.constant.value.str.len+1, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_NULL: zend_symtable_update(Z_ARRVAL(result->u.constant), "", 1, &element, sizeof(zval *), NULL); break; case IS_LONG: case IS_BOOL: zend_hash_index_update(Z_ARRVAL(result->u.constant), Z_LVAL(offset->u.constant), &element, sizeof(zval *), NULL); break; case IS_DOUBLE: zend_hash_index_update(Z_ARRVAL(result->u.constant), zend_dval_to_lval(Z_DVAL(offset->u.constant)), &element, sizeof(zval *), NULL); break; case IS_CONSTANT_ARRAY: zend_error(E_ERROR, "Illegal offset type"); break; } } else { zend_hash_next_index_insert(Z_ARRVAL(result->u.constant), &element, sizeof(zval *), NULL); } } /* }}} */ void zend_do_add_list_element(const znode *element TSRMLS_DC) /* {{{ */ { list_llist_element lle; if (element) { zend_check_writable_variable(element); lle.var = *element; zend_llist_copy(&lle.dimensions, &CG(dimension_llist)); zend_llist_prepend_element(&CG(list_llist), &lle); } (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_new_list_begin(TSRMLS_D) /* {{{ */ { int current_dimension = 0; zend_llist_add_element(&CG(dimension_llist), &current_dimension); } /* }}} */ void zend_do_new_list_end(TSRMLS_D) /* {{{ */ { zend_llist_remove_tail(&CG(dimension_llist)); (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_list_init(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(list_stack), &CG(list_llist), sizeof(zend_llist)); zend_stack_push(&CG(list_stack), &CG(dimension_llist), sizeof(zend_llist)); zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_do_new_list_begin(TSRMLS_C); } /* }}} */ void zend_do_list_end(znode *result, znode *expr TSRMLS_DC) /* {{{ */ { zend_llist_element *le; zend_llist_element *dimension; zend_op *opline; znode last_container; le = CG(list_llist).head; while (le) { zend_llist *tmp_dimension_llist = &((list_llist_element *)le->data)->dimensions; dimension = tmp_dimension_llist->head; while (dimension) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (dimension == tmp_dimension_llist->head) { /* first */ last_container = *expr; switch (expr->op_type) { case IS_VAR: case IS_CV: opline->opcode = ZEND_FETCH_DIM_R; break; case IS_TMP_VAR: opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; case IS_CONST: /* fetch_dim_tmp_var will handle this bogus fetch */ zval_copy_ctor(&expr->u.constant); opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; } opline->extended_value |= ZEND_FETCH_ADD_LOCK; } else { opline->opcode = ZEND_FETCH_DIM_R; } opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, &last_container); opline->op2_type = IS_CONST; LITERAL_LONG(opline->op2, *((int *) dimension->data)); GET_NODE(&last_container, opline->result); dimension = dimension->next; } ((list_llist_element *) le->data)->value = last_container; zend_llist_destroy(&((list_llist_element *) le->data)->dimensions); zend_do_assign(result, &((list_llist_element *) le->data)->var, &((list_llist_element *) le->data)->value TSRMLS_CC); zend_do_free(result TSRMLS_CC); le = le->next; } zend_llist_destroy(&CG(dimension_llist)); zend_llist_destroy(&CG(list_llist)); *result = *expr; { zend_llist *p; /* restore previous lists */ zend_stack_top(&CG(list_stack), (void **) &p); CG(dimension_llist) = *p; zend_stack_del_top(&CG(list_stack)); zend_stack_top(&CG(list_stack), (void **) &p); CG(list_llist) = *p; zend_stack_del_top(&CG(list_stack)); } } /* }}} */ void zend_init_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = emalloc(sizeof(void*) * 2); list[0] = item; list[1] = NULL; *(void**)result = list; } /* }}} */ void zend_add_to_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = *(void**)result; size_t n = 0; while (list && list[n]) { n++; } list = erealloc(list, sizeof(void*) * (n+2)); list[n] = item; list[n+1] = NULL; *(void**)result = list; } /* }}} */ void zend_do_fetch_static_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zval *tmp; zend_op *opline; znode lval; znode result; ALLOC_ZVAL(tmp); if (static_assignment) { *tmp = static_assignment->u.constant; } else { INIT_ZVAL(*tmp); } if (!CG(active_op_array)->static_variables) { if (CG(active_op_array)->scope) { CG(active_op_array)->scope->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } ALLOC_HASHTABLE(CG(active_op_array)->static_variables); zend_hash_init(CG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } zend_hash_update(CG(active_op_array)->static_variables, varname->u.constant.value.str.val, varname->u.constant.value.str.len+1, &tmp, sizeof(zval *), NULL); if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (fetch_type == ZEND_FETCH_LEXICAL) ? ZEND_FETCH_R : ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_STATIC; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ if (fetch_type == ZEND_FETCH_LEXICAL) { znode dummy; zend_do_begin_variable_parse(TSRMLS_C); zend_do_assign(&dummy, &lval, &result TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } else { zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); } CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_fetch_lexical_variable(znode *varname, zend_bool is_ref TSRMLS_DC) /* {{{ */ { znode value; if (Z_STRLEN(varname->u.constant) == sizeof("this") - 1 && memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this") - 1) == 0) { zend_error(E_COMPILE_ERROR, "Cannot use $this as lexical variable"); return; } value.op_type = IS_CONST; ZVAL_NULL(&value.u.constant); Z_TYPE(value.u.constant) |= is_ref ? IS_LEXICAL_REF : IS_LEXICAL_VAR; Z_SET_REFCOUNT_P(&value.u.constant, 1); Z_UNSET_ISREF_P(&value.u.constant); zend_do_fetch_static_variable(varname, &value, is_ref ? ZEND_FETCH_STATIC : ZEND_FETCH_LEXICAL TSRMLS_CC); } /* }}} */ void zend_do_fetch_global_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zend_op *opline; znode lval; znode result; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = fetch_type; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_cast(znode *result, const znode *expr, int type TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CAST; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } /* }}} */ void zend_do_include_or_eval(int type, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_do_extended_fcall_begin(TSRMLS_C); { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INCLUDE_OR_EVAL; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } zend_do_extended_fcall_end(TSRMLS_C); } /* }}} */ void zend_do_indirect_references(znode *result, const znode *num_references, znode *variable TSRMLS_DC) /* {{{ */ { int i; zend_do_end_variable_parse(variable, BP_VAR_R, 0 TSRMLS_CC); for (i=1; i<num_references->u.constant.value.lval; i++) { fetch_simple_variable_ex(result, variable, 0, ZEND_FETCH_R TSRMLS_CC); *variable = *result; } zend_do_begin_variable_parse(TSRMLS_C); fetch_simple_variable(result, variable, 1 TSRMLS_CC); /* there is a chance someone is accessing $this */ if (CG(active_op_array)->scope && CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } /* }}} */ void zend_do_unset(const znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_UNSET_VAR; SET_NODE(opline->op1, variable); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); opline->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_UNSET: last_op->opcode = ZEND_UNSET_VAR; SET_UNUSED(last_op->result); break; case ZEND_FETCH_DIM_UNSET: last_op->opcode = ZEND_UNSET_DIM; SET_UNUSED(last_op->result); break; case ZEND_FETCH_OBJ_UNSET: last_op->opcode = ZEND_UNSET_OBJ; SET_UNUSED(last_op->result); break; } } } /* }}} */ void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_do_end_variable_parse(variable, BP_VAR_IS, 0 TSRMLS_CC); zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { last_op = get_next_op(CG(active_op_array) TSRMLS_CC); last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; SET_NODE(last_op->op1, variable); SET_UNUSED(last_op->op2); last_op->result.var = get_temporary_variable(CG(active_op_array)); last_op->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; break; case ZEND_FETCH_DIM_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_DIM_OBJ; break; case ZEND_FETCH_OBJ_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_PROP_OBJ; break; } } last_op->result_type = IS_TMP_VAR; last_op->extended_value |= type; GET_NODE(result, last_op->result); } /* }}} */ void zend_do_instanceof(znode *result, const znode *expr, const znode *class_znode, int type TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline->opcode == ZEND_FETCH_CLASS) { opline->extended_value |= ZEND_FETCH_CLASS_NO_AUTOLOAD; } } if (expr->op_type == IS_CONST) { zend_error(E_COMPILE_ERROR, "instanceof expects an object instance, constant given"); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INSTANCEOF; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_NODE(opline->op2, class_znode); GET_NODE(result, opline->result); } /* }}} */ void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_bool is_variable; zend_bool push_container = 0; zend_op dummy_opline; if (variable) { if (zend_is_function_or_method_call(array)) { is_variable = 0; } else { is_variable = 1; } /* save the location of FETCH_W instruction(s) */ open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); zend_do_end_variable_parse(array, BP_VAR_W, 0 TSRMLS_CC); if (CG(active_op_array)->last > 0 && CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) { /* Only lock the container if we are fetching from a real container and not $this */ if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1_type == IS_VAR) { CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK; push_container = 1; } } } else { is_variable = 0; open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* save the location of FE_RESET */ foreach_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* Preform array reset */ opline->opcode = ZEND_FE_RESET; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, array); SET_UNUSED(opline->op2); opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0; COPY_NODE(dummy_opline.result, opline->result); if (push_container) { COPY_NODE(dummy_opline.op1, CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1); } else { dummy_opline.op1_type = IS_UNUSED; } zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); /* save the location of FE_FETCH */ as_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FE_FETCH; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); COPY_NODE(opline->op1, dummy_opline.result); opline->extended_value = 0; SET_UNUSED(opline->op2); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_OP_DATA; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); } /* }}} */ void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC) /* {{{ */ { zend_op *opline; znode dummy, value_node; zend_bool assign_by_ref=0; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num]; if (key->op_type != IS_UNUSED) { znode *tmp; /* switch between the key and value... */ tmp = key; key = value; value = tmp; /* Mark extended_value in case both key and value are being used */ opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; } if ((key->op_type != IS_UNUSED) && (key->EA & ZEND_PARSED_REFERENCE_VARIABLE)) { zend_error(E_COMPILE_ERROR, "Key element cannot be a reference"); } if (value->EA & ZEND_PARSED_REFERENCE_VARIABLE) { assign_by_ref = 1; if (!(opline-1)->extended_value) { zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression"); } /* Mark extended_value for assign-by-reference */ opline->extended_value |= ZEND_FE_FETCH_BYREF; CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; } else { zend_op *foreach_copy; zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.op.opline_num]; zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.op.opline_num]; /* Change "write context" into "read context" */ fetch->extended_value = 0; /* reset ZEND_FE_RESET_VARIABLE */ while (fetch != end) { --fetch; if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } if (fetch->opcode == ZEND_SEPARATE) { MAKE_NOP(fetch); } else { fetch->opcode -= 3; /* FETCH_W -> FETCH_R */ } } /* prevent double SWITCH_FREE */ zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy); foreach_copy->op1_type = IS_UNUSED; } GET_NODE(&value_node, opline->result); if (assign_by_ref) { zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); /* Mark FE_FETCH as IS_VAR as it holds the data directly as a value */ zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC); } else { zend_do_assign(&dummy, value, &value_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } if (key->op_type != IS_UNUSED) { znode key_node; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num+1]; opline->result_type = IS_TMP_VAR; opline->result.opline_num = get_temporary_variable(CG(active_op_array)); GET_NODE(&key_node, opline->result); zend_do_assign(&dummy, key, &key_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_foreach_end(const znode *foreach_token, const znode *as_token TSRMLS_DC) /* {{{ */ { zend_op *container_ptr; zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = as_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_RESET */ CG(active_op_array)->opcodes[as_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_FETCH */ do_end_loop(as_token->u.op.opline_num, 1 TSRMLS_CC); zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr); generate_free_foreach_copy(container_ptr TSRMLS_CC); zend_stack_del_top(&CG(foreach_copy_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_declare_begin(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(declare_stack), &CG(declarables), sizeof(zend_declarables)); } /* }}} */ void zend_do_declare_stmt(znode *var, znode *val TSRMLS_DC) /* {{{ */ { if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "ticks", sizeof("ticks")-1)) { convert_to_long(&val->u.constant); CG(declarables).ticks = val->u.constant; } else if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "encoding", sizeof("encoding")-1)) { if ((Z_TYPE(val->u.constant) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Cannot use constants as encoding"); } /* * Check that the pragma comes before any opcodes. If the compilation * got as far as this, the previous portion of the script must have been * parseable according to the .ini script_encoding setting. We still * want to tell them to put declare() at the top. */ { int num = CG(active_op_array)->last; /* ignore ZEND_EXT_STMT and ZEND_TICKS */ while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Encoding declaration pragma must be the very first statement in the script"); } } if (CG(multibyte)) { const zend_encoding *new_encoding, *old_encoding; zend_encoding_filter old_input_filter; CG(encoding_declared) = 1; convert_to_string(&val->u.constant); new_encoding = zend_multibyte_fetch_encoding(val->u.constant.value.str.val TSRMLS_CC); if (!new_encoding) { zend_error(E_COMPILE_WARNING, "Unsupported encoding [%s]", val->u.constant.value.str.val); } else { old_input_filter = LANG_SCNG(input_filter); old_encoding = LANG_SCNG(script_encoding); zend_multibyte_set_filter(new_encoding TSRMLS_CC); /* need to re-scan if input filter changed */ if (old_input_filter != LANG_SCNG(input_filter) || (old_input_filter && new_encoding != old_encoding)) { zend_multibyte_yyinput_again(old_input_filter, old_encoding TSRMLS_CC); } } } else { zend_error(E_COMPILE_WARNING, "declare(encoding=...) ignored because Zend multibyte feature is turned off by settings"); } zval_dtor(&val->u.constant); } else { zend_error(E_COMPILE_WARNING, "Unsupported declare '%s'", var->u.constant.value.str.val); zval_dtor(&val->u.constant); } zval_dtor(&var->u.constant); } /* }}} */ void zend_do_declare_end(const znode *declare_token TSRMLS_DC) /* {{{ */ { zend_declarables *declarables; zend_stack_top(&CG(declare_stack), (void **) &declarables); /* We should restore if there was more than (current - start) - (ticks?1:0) opcodes */ if ((get_next_op_number(CG(active_op_array)) - declare_token->u.op.opline_num) - ((Z_LVAL(CG(declarables).ticks))?1:0)) { CG(declarables) = *declarables; } } /* }}} */ void zend_do_exit(znode *result, const znode *message TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXIT; SET_NODE(opline->op1, message); SET_UNUSED(opline->op2); result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_BOOL; Z_LVAL(result->u.constant) = 1; } /* }}} */ void zend_do_begin_silence(znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BEGIN_SILENCE; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); GET_NODE(strudel_token, opline->result); } /* }}} */ void zend_do_end_silence(const znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_END_SILENCE; SET_NODE(opline->op1, strudel_token); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_jmp_set(const znode *value, znode *jmp_token, znode *colon_token TSRMLS_DC) /* {{{ */ { int op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (value->op_type == IS_VAR || value->op_type == IS_CV) { opline->opcode = ZEND_JMP_SET_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_JMP_SET; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, value); SET_UNUSED(opline->op2); GET_NODE(colon_token, opline->result); jmp_token->u.op .opline_num = op_number; INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_jmp_set_else(znode *result, const znode *false_value, const znode *jmp_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, colon_token); if (colon_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].opcode = ZEND_JMP_SET_VAR; CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } opline->extended_value = 0; SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_qm_op(const znode *cond, znode *qm_token TSRMLS_DC) /* {{{ */ { int jmpz_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); SET_UNUSED(opline->op2); opline->op2.opline_num = jmpz_op_number; GET_NODE(qm_token, opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_qm_true(const znode *true_value, znode *qm_token, znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->opcodes[qm_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array))+1; /* jmp over the ZEND_JMP */ if (true_value->op_type == IS_VAR || true_value->op_type == IS_CV) { opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, true_value); SET_UNUSED(opline->op2); GET_NODE(qm_token, opline->result); colon_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_qm_false(znode *result, const znode *false_value, const znode *qm_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, qm_token); if (qm_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].opcode = ZEND_QM_ASSIGN_VAR; CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[colon_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, opline->result); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_extended_info(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_STMT; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_begin(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_BEGIN; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_end(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_END; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_ticks(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_TICKS; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->extended_value = Z_LVAL(CG(declarables).ticks); } /* }}} */ zend_bool zend_is_auto_global_quick(const char *name, uint name_len, ulong hashval TSRMLS_DC) /* {{{ */ { zend_auto_global *auto_global; ulong hash = hashval ? hashval : zend_hash_func(name, name_len+1); if (zend_hash_quick_find(CG(auto_globals), name, name_len+1, hash, (void **) &auto_global)==SUCCESS) { if (auto_global->armed) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } return 1; } return 0; } /* }}} */ zend_bool zend_is_auto_global(const char *name, uint name_len TSRMLS_DC) /* {{{ */ { return zend_is_auto_global_quick(name, name_len, 0 TSRMLS_CC); } /* }}} */ int zend_register_auto_global(const char *name, uint name_len, zend_bool jit, zend_auto_global_callback auto_global_callback TSRMLS_DC) /* {{{ */ { zend_auto_global auto_global; auto_global.name = zend_new_interned_string((char*)name, name_len + 1, 0 TSRMLS_CC); auto_global.name_len = name_len; auto_global.auto_global_callback = auto_global_callback; auto_global.jit = jit; return zend_hash_add(CG(auto_globals), name, name_len+1, &auto_global, sizeof(zend_auto_global), NULL); } /* }}} */ static int zend_auto_global_init(zend_auto_global *auto_global TSRMLS_DC) /* {{{ */ { if (auto_global->jit) { auto_global->armed = 1; } else if (auto_global->auto_global_callback) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } else { auto_global->armed = 0; } return 0; } /* }}} */ ZEND_API void zend_activate_auto_globals(TSRMLS_D) /* {{{ */ { zend_hash_apply(CG(auto_globals), (apply_func_t) zend_auto_global_init TSRMLS_CC); } /* }}} */ int zendlex(znode *zendlval TSRMLS_DC) /* {{{ */ { int retval; if (CG(increment_lineno)) { CG(zend_lineno)++; CG(increment_lineno) = 0; } again: Z_TYPE(zendlval->u.constant) = IS_LONG; retval = lex_scan(&zendlval->u.constant TSRMLS_CC); switch (retval) { case T_COMMENT: case T_DOC_COMMENT: case T_OPEN_TAG: case T_WHITESPACE: goto again; case T_CLOSE_TAG: if (LANG_SCNG(yy_text)[LANG_SCNG(yy_leng)-1] != '>') { CG(increment_lineno) = 1; } if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { goto again; } retval = ';'; /* implicit ; */ break; case T_OPEN_TAG_WITH_ECHO: retval = T_ECHO; break; case T_END_HEREDOC: efree(Z_STRVAL(zendlval->u.constant)); break; } INIT_PZVAL(&zendlval->u.constant); zendlval->op_type = IS_CONST; return retval; } /* }}} */ ZEND_API void zend_initialize_class_data(zend_class_entry *ce, zend_bool nullify_handlers TSRMLS_DC) /* {{{ */ { zend_bool persistent_hashes = (ce->type == ZEND_INTERNAL_CLASS) ? 1 : 0; dtor_func_t zval_ptr_dtor_func = ((persistent_hashes) ? ZVAL_INTERNAL_PTR_DTOR : ZVAL_PTR_DTOR); ce->refcount = 1; ce->ce_flags = 0; ce->default_properties_table = NULL; ce->default_static_members_table = NULL; zend_hash_init_ex(&ce->properties_info, 0, NULL, (dtor_func_t) (persistent_hashes ? zend_destroy_property_info_internal : zend_destroy_property_info), persistent_hashes, 0); zend_hash_init_ex(&ce->constants_table, 0, NULL, zval_ptr_dtor_func, persistent_hashes, 0); zend_hash_init_ex(&ce->function_table, 0, NULL, ZEND_FUNCTION_DTOR, persistent_hashes, 0); if (ce->type == ZEND_INTERNAL_CLASS) { #ifdef ZTS int n = zend_hash_num_elements(CG(class_table)); if (CG(static_members_table) && n >= CG(last_static_member)) { /* Support for run-time declaration: dl() */ CG(last_static_member) = n+1; CG(static_members_table) = realloc(CG(static_members_table), (n+1)*sizeof(zval**)); CG(static_members_table)[n] = NULL; } ce->static_members_table = (zval**)(zend_intptr_t)n; #else ce->static_members_table = NULL; #endif } else { ce->static_members_table = ce->default_static_members_table; ce->info.user.doc_comment = NULL; ce->info.user.doc_comment_len = 0; } ce->default_properties_count = 0; ce->default_static_members_count = 0; if (nullify_handlers) { ce->constructor = NULL; ce->destructor = NULL; ce->clone = NULL; ce->__get = NULL; ce->__set = NULL; ce->__unset = NULL; ce->__isset = NULL; ce->__call = NULL; ce->__callstatic = NULL; ce->__tostring = NULL; ce->create_object = NULL; ce->get_iterator = NULL; ce->iterator_funcs.funcs = NULL; ce->interface_gets_implemented = NULL; ce->get_static_method = NULL; ce->parent = NULL; ce->num_interfaces = 0; ce->interfaces = NULL; ce->num_traits = 0; ce->traits = NULL; ce->trait_aliases = NULL; ce->trait_precedences = NULL; ce->serialize = NULL; ce->unserialize = NULL; ce->serialize_func = NULL; ce->unserialize_func = NULL; if (ce->type == ZEND_INTERNAL_CLASS) { ce->info.internal.module = NULL; ce->info.internal.builtin_functions = NULL; } } } /* }}} */ int zend_get_class_fetch_type(const char *class_name, uint class_name_len) /* {{{ */ { if ((class_name_len == sizeof("self")-1) && !memcmp(class_name, "self", sizeof("self")-1)) { return ZEND_FETCH_CLASS_SELF; } else if ((class_name_len == sizeof("parent")-1) && !memcmp(class_name, "parent", sizeof("parent")-1)) { return ZEND_FETCH_CLASS_PARENT; } else if ((class_name_len == sizeof("static")-1) && !memcmp(class_name, "static", sizeof("static")-1)) { return ZEND_FETCH_CLASS_STATIC; } else { return ZEND_FETCH_CLASS_DEFAULT; } } /* }}} */ ZEND_API const char* zend_get_compiled_variable_name(const zend_op_array *op_array, zend_uint var, int* name_len) /* {{{ */ { if (name_len) { *name_len = op_array->vars[var].name_len; } return op_array->vars[var].name; } /* }}} */ void zend_do_build_namespace_name(znode *result, znode *prefix, znode *name TSRMLS_DC) /* {{{ */ { if (prefix) { *result = *prefix; if (Z_TYPE(result->u.constant) == IS_STRING && Z_STRLEN(result->u.constant) == 0) { /* namespace\ */ if (CG(current_namespace)) { znode tmp; zval_dtor(&result->u.constant); tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(result, NULL, &tmp TSRMLS_CC); } } } else { result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_STRING; Z_STRVAL(result->u.constant) = NULL; Z_STRLEN(result->u.constant) = 0; } /* prefix = result */ zend_do_build_full_name(NULL, result, name, 0 TSRMLS_CC); } /* }}} */ void zend_do_begin_namespace(const znode *name, zend_bool with_bracket TSRMLS_DC) /* {{{ */ { char *lcname; /* handle mixed syntax declaration or nested namespaces */ if (!CG(has_bracketed_namespaces)) { if (CG(current_namespace)) { /* previous namespace declarations were unbracketed */ if (with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } } } else { /* previous namespace declarations were bracketed */ if (!with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } else if (CG(current_namespace) || CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "Namespace declarations cannot be nested"); } } if (((!with_bracket && !CG(current_namespace)) || (with_bracket && !CG(has_bracketed_namespaces))) && CG(active_op_array)->last > 0) { /* ignore ZEND_EXT_STMT and ZEND_TICKS */ int num = CG(active_op_array)->last; while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Namespace declaration statement has to be the very first statement in the script"); } } CG(in_namespace) = 1; if (with_bracket) { CG(has_bracketed_namespaces) = 1; } if (name) { lcname = zend_str_tolower_dup(Z_STRVAL(name->u.constant), Z_STRLEN(name->u.constant)); if (((Z_STRLEN(name->u.constant) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN(name->u.constant) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as namespace name", Z_STRVAL(name->u.constant)); } efree(lcname); if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); } else { ALLOC_ZVAL(CG(current_namespace)); } *CG(current_namespace) = name->u.constant; } else { if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_use(znode *ns_name, znode *new_name, int is_global TSRMLS_DC) /* {{{ */ { char *lcname; zval *name, *ns, tmp; zend_bool warn = 0; zend_class_entry **pce; if (!CG(current_import)) { CG(current_import) = emalloc(sizeof(HashTable)); zend_hash_init(CG(current_import), 0, NULL, ZVAL_PTR_DTOR, 0); } ALLOC_ZVAL(ns); *ns = ns_name->u.constant; if (new_name) { name = &new_name->u.constant; } else { const char *p; /* The form "use A\B" is eqivalent to "use A\B as B". So we extract the last part of compound name to use as a new_name */ name = &tmp; p = zend_memrchr(Z_STRVAL_P(ns), '\\', Z_STRLEN_P(ns)); if (p) { ZVAL_STRING(name, p+1, 1); } else { *name = *ns; zval_copy_ctor(name); warn = !is_global && !CG(current_namespace); } } lcname = zend_str_tolower_dup(Z_STRVAL_P(name), Z_STRLEN_P(name)); if (((Z_STRLEN_P(name) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN_P(name) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because '%s' is a special class name", Z_STRVAL_P(ns), Z_STRVAL_P(name), Z_STRVAL_P(name)); } if (CG(current_namespace)) { /* Prefix import name with current namespace name to avoid conflicts with classes */ char *c_ns_name = emalloc(Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) + 1); zend_str_tolower_copy(c_ns_name, Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); c_ns_name[Z_STRLEN_P(CG(current_namespace))] = '\\'; memcpy(c_ns_name+Z_STRLEN_P(CG(current_namespace))+1, lcname, Z_STRLEN_P(name)+1); if (zend_hash_exists(CG(class_table), c_ns_name, Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name)+1)) { char *tmp2 = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) || memcmp(tmp2, c_ns_name, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(tmp2); } efree(c_ns_name); } else if (zend_hash_find(CG(class_table), lcname, Z_STRLEN_P(name)+1, (void**)&pce) == SUCCESS && (*pce)->type == ZEND_USER_CLASS && (*pce)->info.user.filename == CG(compiled_filename)) { char *c_tmp = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(name) || memcmp(c_tmp, lcname, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(c_tmp); } if (zend_hash_add(CG(current_import), lcname, Z_STRLEN_P(name)+1, &ns, sizeof(zval*), NULL) != SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } if (warn) { if (!strcmp(Z_STRVAL_P(name), "strict")) { zend_error(E_COMPILE_ERROR, "You seem to be trying to use a different language..."); } zend_error(E_WARNING, "The use statement with non-compound name '%s' has no effect", Z_STRVAL_P(name)); } efree(lcname); zval_dtor(name); } /* }}} */ void zend_do_declare_constant(znode *name, znode *value TSRMLS_DC) /* {{{ */ { zend_op *opline; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed as constants"); } if (zend_get_ct_const(&name->u.constant, 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare constant '%s'", Z_STRVAL(name->u.constant)); } if (CG(current_namespace)) { /* Prefix constant name with name of current namespace, lowercased */ znode tmp; tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); Z_STRVAL(tmp.u.constant) = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), Z_STRLEN(tmp.u.constant)); zend_do_build_namespace_name(&tmp, &tmp, name TSRMLS_CC); *name = tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DECLARE_CONST; SET_UNUSED(opline->result); SET_NODE(opline->op1, name); SET_NODE(opline->op2, value); } /* }}} */ void zend_verify_namespace(TSRMLS_D) /* {{{ */ { if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "No code may exist outside of namespace {}"); } } /* }}} */ void zend_do_end_namespace(TSRMLS_D) /* {{{ */ { CG(in_namespace) = 0; if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_end_compilation(TSRMLS_D) /* {{{ */ { CG(has_bracketed_namespaces) = 0; zend_do_end_namespace(TSRMLS_C); } /* }}} */ /* {{{ zend_dirname Returns directory name component of path */ ZEND_API size_t zend_dirname(char *path, size_t len) { register char *end = path + len - 1; unsigned int len_adjust = 0; #ifdef PHP_WIN32 /* Note that on Win32 CWD is per drive (heritage from CP/M). * This means dirname("c:foo") maps to "c:." or "c:" - which means CWD on C: drive. */ if ((2 <= len) && isalpha((int)((unsigned char *)path)[0]) && (':' == path[1])) { /* Skip over the drive spec (if any) so as not to change */ path += 2; len_adjust += 2; if (2 == len) { /* Return "c:" on Win32 for dirname("c:"). * It would be more consistent to return "c:." * but that would require making the string *longer*. */ return len; } } #elif defined(NETWARE) /* * Find the first occurence of : from the left * move the path pointer to the position just after : * increment the len_adjust to the length of path till colon character(inclusive) * If there is no character beyond : simple return len */ char *colonpos = NULL; colonpos = strchr(path, ':'); if (colonpos != NULL) { len_adjust = ((colonpos - path) + 1); path += len_adjust; if (len_adjust == len) { return len; } } #endif if (len == 0) { /* Illegal use of this function */ return 0; } /* Strip trailing slashes */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { /* The path only contained slashes */ path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } /* Strip filename */ while (end >= path && !IS_SLASH_P(end)) { end--; } if (end < path) { /* No slash found, therefore return '.' */ #ifdef NETWARE if (len_adjust == 0) { path[0] = '.'; path[1] = '\0'; return 1; /* only one character */ } else { path[0] = '\0'; return len_adjust; } #else path[0] = '.'; path[1] = '\0'; return 1 + len_adjust; #endif } /* Strip slashes which came before the file name */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } *(end+1) = '\0'; return (size_t)(end + 1 - path) + len_adjust; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-10-30-c1a4a36c14-5921e73a37.c
manybugs_data_81
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Shane Caraveo <[email protected]> | | Wez Furlong <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #define IS_EXT_MODULE #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "SAPI.h" #define PHP_XML_INTERNAL #include "zend_variables.h" #include "ext/standard/php_string.h" #include "ext/standard/info.h" #include "ext/standard/file.h" #if HAVE_LIBXML #include <libxml/parser.h> #include <libxml/parserInternals.h> #include <libxml/tree.h> #include <libxml/uri.h> #include <libxml/xmlerror.h> #include <libxml/xmlsave.h> #ifdef LIBXML_SCHEMAS_ENABLED #include <libxml/relaxng.h> #endif #include "php_libxml.h" #define PHP_LIBXML_ERROR 0 #define PHP_LIBXML_CTX_ERROR 1 #define PHP_LIBXML_CTX_WARNING 2 /* a true global for initialization */ static int _php_libxml_initialized = 0; static int _php_libxml_per_request_initialization = 1; typedef struct _php_libxml_func_handler { php_libxml_export_node export_func; } php_libxml_func_handler; static HashTable php_libxml_exports; static ZEND_DECLARE_MODULE_GLOBALS(libxml) static PHP_GINIT_FUNCTION(libxml); static PHP_FUNCTION(libxml_set_streams_context); static PHP_FUNCTION(libxml_use_internal_errors); static PHP_FUNCTION(libxml_get_last_error); static PHP_FUNCTION(libxml_clear_errors); static PHP_FUNCTION(libxml_get_errors); static PHP_FUNCTION(libxml_disable_entity_loader); static zend_class_entry *libxmlerror_class_entry; /* {{{ dynamically loadable module stuff */ #ifdef COMPILE_DL_LIBXML ZEND_GET_MODULE(libxml) #endif /* COMPILE_DL_LIBXML */ /* }}} */ /* {{{ function prototypes */ static PHP_MINIT_FUNCTION(libxml); static PHP_RINIT_FUNCTION(libxml); static PHP_MSHUTDOWN_FUNCTION(libxml); static PHP_RSHUTDOWN_FUNCTION(libxml); static PHP_MINFO_FUNCTION(libxml); /* }}} */ /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO(arginfo_libxml_set_streams_context, 0) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_libxml_use_internal_errors, 0, 0, 0) ZEND_ARG_INFO(0, use_errors) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_libxml_get_last_error, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_libxml_get_errors, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_libxml_clear_errors, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_libxml_disable_entity_loader, 0, 0, 0) ZEND_ARG_INFO(0, disable) ZEND_END_ARG_INFO() /* }}} */ /* {{{ extension definition structures */ static const zend_function_entry libxml_functions[] = { PHP_FE(libxml_set_streams_context, arginfo_libxml_set_streams_context) PHP_FE(libxml_use_internal_errors, arginfo_libxml_use_internal_errors) PHP_FE(libxml_get_last_error, arginfo_libxml_get_last_error) PHP_FE(libxml_clear_errors, arginfo_libxml_clear_errors) PHP_FE(libxml_get_errors, arginfo_libxml_get_errors) PHP_FE(libxml_disable_entity_loader, arginfo_libxml_disable_entity_loader) {NULL, NULL, NULL} }; zend_module_entry libxml_module_entry = { STANDARD_MODULE_HEADER, "libxml", /* extension name */ libxml_functions, /* extension function list */ PHP_MINIT(libxml), /* extension-wide startup function */ PHP_MSHUTDOWN(libxml), /* extension-wide shutdown function */ PHP_RINIT(libxml), /* per-request startup function */ PHP_RSHUTDOWN(libxml), /* per-request shutdown function */ PHP_MINFO(libxml), /* information function */ NO_VERSION_YET, PHP_MODULE_GLOBALS(libxml), /* globals descriptor */ PHP_GINIT(libxml), /* globals ctor */ NULL, /* globals dtor */ NULL, /* post deactivate */ STANDARD_MODULE_PROPERTIES_EX }; /* }}} */ /* {{{ internal functions for interoperability */ static int php_libxml_clear_object(php_libxml_node_object *object TSRMLS_DC) { if (object->properties) { object->properties = NULL; } php_libxml_decrement_node_ptr(object TSRMLS_CC); return php_libxml_decrement_doc_ref(object TSRMLS_CC); } static int php_libxml_unregister_node(xmlNodePtr nodep TSRMLS_DC) { php_libxml_node_object *wrapper; php_libxml_node_ptr *nodeptr = nodep->_private; if (nodeptr != NULL) { wrapper = nodeptr->_private; if (wrapper) { php_libxml_clear_object(wrapper TSRMLS_CC); } else { if (nodeptr->node != NULL && nodeptr->node->type != XML_DOCUMENT_NODE) { nodeptr->node->_private = NULL; } nodeptr->node = NULL; } } return -1; } static void php_libxml_node_free(xmlNodePtr node) { if(node) { if (node->_private != NULL) { ((php_libxml_node_ptr *) node->_private)->node = NULL; } switch (node->type) { case XML_ATTRIBUTE_NODE: xmlFreeProp((xmlAttrPtr) node); break; case XML_ENTITY_DECL: case XML_ELEMENT_DECL: case XML_ATTRIBUTE_DECL: break; case XML_NOTATION_NODE: /* These require special handling */ if (node->name != NULL) { xmlFree((char *) node->name); } if (((xmlEntityPtr) node)->ExternalID != NULL) { xmlFree((char *) ((xmlEntityPtr) node)->ExternalID); } if (((xmlEntityPtr) node)->SystemID != NULL) { xmlFree((char *) ((xmlEntityPtr) node)->SystemID); } xmlFree(node); break; case XML_NAMESPACE_DECL: if (node->ns) { xmlFreeNs(node->ns); node->ns = NULL; } node->type = XML_ELEMENT_NODE; default: xmlFreeNode(node); } } } static void php_libxml_node_free_list(xmlNodePtr node TSRMLS_DC) { xmlNodePtr curnode; if (node != NULL) { curnode = node; while (curnode != NULL) { node = curnode; switch (node->type) { /* Skip property freeing for the following types */ case XML_NOTATION_NODE: break; case XML_ENTITY_REF_NODE: php_libxml_node_free_list((xmlNodePtr) node->properties TSRMLS_CC); break; case XML_ATTRIBUTE_NODE: if ((node->doc != NULL) && (((xmlAttrPtr) node)->atype == XML_ATTRIBUTE_ID)) { xmlRemoveID(node->doc, (xmlAttrPtr) node); } case XML_ATTRIBUTE_DECL: case XML_DTD_NODE: case XML_DOCUMENT_TYPE_NODE: case XML_ENTITY_DECL: case XML_NAMESPACE_DECL: case XML_TEXT_NODE: php_libxml_node_free_list(node->children TSRMLS_CC); break; default: php_libxml_node_free_list(node->children TSRMLS_CC); php_libxml_node_free_list((xmlNodePtr) node->properties TSRMLS_CC); } curnode = node->next; xmlUnlinkNode(node); if (php_libxml_unregister_node(node TSRMLS_CC) == 0) { node->doc = NULL; } php_libxml_node_free(node); } } } /* }}} */ /* {{{ startup, shutdown and info functions */ static PHP_GINIT_FUNCTION(libxml) { libxml_globals->stream_context = NULL; libxml_globals->error_buffer.c = NULL; libxml_globals->error_list = NULL; } /* Channel libxml file io layer through the PHP streams subsystem. * This allows use of ftps:// and https:// urls */ static void *php_libxml_streams_IO_open_wrapper(const char *filename, const char *mode, const int read_only) { php_stream_statbuf ssbuf; php_stream_context *context = NULL; php_stream_wrapper *wrapper = NULL; char *resolved_path, *path_to_open = NULL; void *ret_val = NULL; int isescaped=0; xmlURI *uri; TSRMLS_FETCH(); uri = xmlParseURI((xmlChar *)filename); if (uri && (uri->scheme == NULL || (xmlStrncmp(uri->scheme, "file", 4) == 0))) { resolved_path = xmlURIUnescapeString(filename, 0, NULL); isescaped = 1; } else { resolved_path = (char *)filename; } if (uri) { xmlFreeURI(uri); } if (resolved_path == NULL) { return NULL; } /* logic copied from _php_stream_stat, but we only want to fail if the wrapper supports stat, otherwise, figure it out from the open. This logic is only to support hiding warnings that the streams layer puts out at times, but for libxml we may try to open files that don't exist, but it is not a failure in xml processing (eg. DTD files) */ wrapper = php_stream_locate_url_wrapper(resolved_path, &path_to_open, 0 TSRMLS_CC); if (wrapper && read_only && wrapper->wops->url_stat) { if (wrapper->wops->url_stat(wrapper, path_to_open, PHP_STREAM_URL_STAT_QUIET, &ssbuf, NULL TSRMLS_CC) == -1) { if (isescaped) { xmlFree(resolved_path); } return NULL; } } if (LIBXML(stream_context)) { context = zend_fetch_resource(&LIBXML(stream_context) TSRMLS_CC, -1, "Stream-Context", NULL, 1, php_le_stream_context(TSRMLS_C)); } ret_val = php_stream_open_wrapper_ex(path_to_open, (char *)mode, REPORT_ERRORS, NULL, context); if (isescaped) { xmlFree(resolved_path); } return ret_val; } static void *php_libxml_streams_IO_open_read_wrapper(const char *filename) { return php_libxml_streams_IO_open_wrapper(filename, "rb", 1); } static void *php_libxml_streams_IO_open_write_wrapper(const char *filename) { return php_libxml_streams_IO_open_wrapper(filename, "wb", 0); } static int php_libxml_streams_IO_read(void *context, char *buffer, int len) { TSRMLS_FETCH(); return php_stream_read((php_stream*)context, buffer, len); } static int php_libxml_streams_IO_write(void *context, const char *buffer, int len) { TSRMLS_FETCH(); return php_stream_write((php_stream*)context, buffer, len); } static int php_libxml_streams_IO_close(void *context) { TSRMLS_FETCH(); return php_stream_close((php_stream*)context); } static xmlParserInputBufferPtr php_libxml_input_buffer_noload(const char *URI, xmlCharEncoding enc) { return NULL; } static xmlParserInputBufferPtr php_libxml_input_buffer_create_filename(const char *URI, xmlCharEncoding enc) { xmlParserInputBufferPtr ret; void *context = NULL; if (URI == NULL) return(NULL); context = php_libxml_streams_IO_open_read_wrapper(URI); if (context == NULL) { return(NULL); } /* Allocate the Input buffer front-end. */ ret = xmlAllocParserInputBuffer(enc); if (ret != NULL) { ret->context = context; ret->readcallback = php_libxml_streams_IO_read; ret->closecallback = php_libxml_streams_IO_close; } else php_libxml_streams_IO_close(context); return(ret); } static xmlOutputBufferPtr php_libxml_output_buffer_create_filename(const char *URI, xmlCharEncodingHandlerPtr encoder, int compression ATTRIBUTE_UNUSED) { xmlOutputBufferPtr ret; xmlURIPtr puri; void *context = NULL; char *unescaped = NULL; if (URI == NULL) return(NULL); puri = xmlParseURI(URI); if (puri != NULL) { if (puri->scheme != NULL) unescaped = xmlURIUnescapeString(URI, 0, NULL); xmlFreeURI(puri); } if (unescaped != NULL) { context = php_libxml_streams_IO_open_write_wrapper(unescaped); xmlFree(unescaped); } /* try with a non-escaped URI this may be a strange filename */ if (context == NULL) { context = php_libxml_streams_IO_open_write_wrapper(URI); } if (context == NULL) { return(NULL); } /* Allocate the Output buffer front-end. */ ret = xmlAllocOutputBuffer(encoder); if (ret != NULL) { ret->context = context; ret->writecallback = php_libxml_streams_IO_write; ret->closecallback = php_libxml_streams_IO_close; } return(ret); } static int _php_libxml_free_error(xmlErrorPtr error) { /* This will free the libxml alloc'd memory */ xmlResetError(error); return 1; } static void _php_list_set_error_structure(xmlErrorPtr error, const char *msg) { xmlError error_copy; int ret; TSRMLS_FETCH(); memset(&error_copy, 0, sizeof(xmlError)); if (error) { ret = xmlCopyError(error, &error_copy); } else { error_copy.domain = 0; error_copy.code = XML_ERR_INTERNAL_ERROR; error_copy.level = XML_ERR_ERROR; error_copy.line = 0; error_copy.node = NULL; error_copy.int1 = 0; error_copy.int2 = 0; error_copy.ctxt = NULL; error_copy.message = xmlStrdup(msg); error_copy.file = NULL; error_copy.str1 = NULL; error_copy.str2 = NULL; error_copy.str3 = NULL; ret = 0; } if (ret == 0) { zend_llist_add_element(LIBXML(error_list), &error_copy); } } static void php_libxml_ctx_error_level(int level, void *ctx, const char *msg TSRMLS_DC) { xmlParserCtxtPtr parser; parser = (xmlParserCtxtPtr) ctx; if (parser != NULL && parser->input != NULL) { if (parser->input->filename) { php_error_docref(NULL TSRMLS_CC, level, "%s in %s, line: %d", msg, parser->input->filename, parser->input->line); } else { php_error_docref(NULL TSRMLS_CC, level, "%s in Entity, line: %d", msg, parser->input->line); } } } void php_libxml_issue_error(int level, const char *msg TSRMLS_DC) { if (LIBXML(error_list)) { _php_list_set_error_structure(NULL, msg); } else { php_error_docref(NULL TSRMLS_CC, level, "%s", msg); } } static void php_libxml_internal_error_handler(int error_type, void *ctx, const char **msg, va_list ap) { char *buf; int len, len_iter, output = 0; TSRMLS_FETCH(); len = vspprintf(&buf, 0, *msg, ap); len_iter = len; /* remove any trailing \n */ while (len_iter && buf[--len_iter] == '\n') { buf[len_iter] = '\0'; output = 1; } smart_str_appendl(&LIBXML(error_buffer), buf, len); efree(buf); if (output == 1) { if (LIBXML(error_list)) { _php_list_set_error_structure(NULL, LIBXML(error_buffer).c); } else { switch (error_type) { case PHP_LIBXML_CTX_ERROR: php_libxml_ctx_error_level(E_WARNING, ctx, LIBXML(error_buffer).c TSRMLS_CC); break; case PHP_LIBXML_CTX_WARNING: php_libxml_ctx_error_level(E_NOTICE, ctx, LIBXML(error_buffer).c TSRMLS_CC); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", LIBXML(error_buffer).c); } } smart_str_free(&LIBXML(error_buffer)); } } PHP_LIBXML_API void php_libxml_ctx_error(void *ctx, const char *msg, ...) { va_list args; va_start(args, msg); php_libxml_internal_error_handler(PHP_LIBXML_CTX_ERROR, ctx, &msg, args); va_end(args); } PHP_LIBXML_API void php_libxml_ctx_warning(void *ctx, const char *msg, ...) { va_list args; va_start(args, msg); php_libxml_internal_error_handler(PHP_LIBXML_CTX_WARNING, ctx, &msg, args); va_end(args); } PHP_LIBXML_API void php_libxml_structured_error_handler(void *userData, xmlErrorPtr error) { _php_list_set_error_structure(error, NULL); return; } PHP_LIBXML_API void php_libxml_error_handler(void *ctx, const char *msg, ...) { va_list args; va_start(args, msg); php_libxml_internal_error_handler(PHP_LIBXML_ERROR, ctx, &msg, args); va_end(args); } PHP_LIBXML_API void php_libxml_initialize(void) { if (!_php_libxml_initialized) { /* we should be the only one's to ever init!! */ xmlInitParser(); zend_hash_init(&php_libxml_exports, 0, NULL, NULL, 1); _php_libxml_initialized = 1; } } PHP_LIBXML_API void php_libxml_shutdown(void) { if (_php_libxml_initialized) { #if defined(LIBXML_SCHEMAS_ENABLED) xmlRelaxNGCleanupTypes(); #endif xmlCleanupParser(); zend_hash_destroy(&php_libxml_exports); _php_libxml_initialized = 0; } } PHP_LIBXML_API zval *php_libxml_switch_context(zval *context TSRMLS_DC) { zval *oldcontext; oldcontext = LIBXML(stream_context); LIBXML(stream_context) = context; return oldcontext; } static PHP_MINIT_FUNCTION(libxml) { zend_class_entry ce; php_libxml_initialize(); REGISTER_LONG_CONSTANT("LIBXML_VERSION", LIBXML_VERSION, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("LIBXML_DOTTED_VERSION", LIBXML_DOTTED_VERSION, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("LIBXML_LOADED_VERSION", (char *)xmlParserVersion, CONST_CS | CONST_PERSISTENT); /* For use with loading xml */ REGISTER_LONG_CONSTANT("LIBXML_NOENT", XML_PARSE_NOENT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_DTDLOAD", XML_PARSE_DTDLOAD, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_DTDATTR", XML_PARSE_DTDATTR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_DTDVALID", XML_PARSE_DTDVALID, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_NOERROR", XML_PARSE_NOERROR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_NOWARNING", XML_PARSE_NOWARNING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_NOBLANKS", XML_PARSE_NOBLANKS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_XINCLUDE", XML_PARSE_XINCLUDE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_NSCLEAN", XML_PARSE_NSCLEAN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_NOCDATA", XML_PARSE_NOCDATA, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_NONET", XML_PARSE_NONET, CONST_CS | CONST_PERSISTENT); #if LIBXML_VERSION >= 20621 REGISTER_LONG_CONSTANT("LIBXML_COMPACT", XML_PARSE_COMPACT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_NOXMLDECL", XML_SAVE_NO_DECL, CONST_CS | CONST_PERSISTENT); #endif #if LIBXML_VERSION >= 20703 REGISTER_LONG_CONSTANT("LIBXML_PARSEHUGE", XML_PARSE_HUGE, CONST_CS | CONST_PERSISTENT); #endif REGISTER_LONG_CONSTANT("LIBXML_NOEMPTYTAG", LIBXML_SAVE_NOEMPTYTAG, CONST_CS | CONST_PERSISTENT); /* Error levels */ REGISTER_LONG_CONSTANT("LIBXML_ERR_NONE", XML_ERR_NONE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_ERR_WARNING", XML_ERR_WARNING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_ERR_ERROR", XML_ERR_ERROR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_ERR_FATAL", XML_ERR_FATAL, CONST_CS | CONST_PERSISTENT); INIT_CLASS_ENTRY(ce, "LibXMLError", NULL); libxmlerror_class_entry = zend_register_internal_class(&ce TSRMLS_CC); if (sapi_module.name) { static const char * const supported_sapis[] = { "cgi-fcgi", "fpm-fcgi", "litespeed", NULL }; const char * const *sapi_name; for (sapi_name = supported_sapis; *sapi_name; sapi_name++) { if (strcmp(sapi_module.name, *sapi_name) == 0) { _php_libxml_per_request_initialization = 0; break; } } } if (!_php_libxml_per_request_initialization) { /* report errors via handler rather than stderr */ xmlSetGenericErrorFunc(NULL, php_libxml_error_handler); xmlParserInputBufferCreateFilenameDefault(php_libxml_input_buffer_create_filename); xmlOutputBufferCreateFilenameDefault(php_libxml_output_buffer_create_filename); } return SUCCESS; } static PHP_RINIT_FUNCTION(libxml) { if (_php_libxml_per_request_initialization) { /* report errors via handler rather than stderr */ xmlSetGenericErrorFunc(NULL, php_libxml_error_handler); xmlParserInputBufferCreateFilenameDefault(php_libxml_input_buffer_create_filename); xmlOutputBufferCreateFilenameDefault(php_libxml_output_buffer_create_filename); } return SUCCESS; } static PHP_MSHUTDOWN_FUNCTION(libxml) { if (!_php_libxml_per_request_initialization) { xmlSetGenericErrorFunc(NULL, NULL); xmlSetStructuredErrorFunc(NULL, NULL); xmlParserInputBufferCreateFilenameDefault(NULL); xmlOutputBufferCreateFilenameDefault(NULL); } php_libxml_shutdown(); return SUCCESS; } static PHP_RSHUTDOWN_FUNCTION(libxml) { /* reset libxml generic error handling */ if (_php_libxml_per_request_initialization) { xmlSetGenericErrorFunc(NULL, NULL); xmlSetStructuredErrorFunc(NULL, NULL); xmlParserInputBufferCreateFilenameDefault(NULL); xmlOutputBufferCreateFilenameDefault(NULL); } if (LIBXML(stream_context)) { zval_ptr_dtor(&LIBXML(stream_context)); LIBXML(stream_context) = NULL; } smart_str_free(&LIBXML(error_buffer)); if (LIBXML(error_list)) { zend_llist_destroy(LIBXML(error_list)); efree(LIBXML(error_list)); LIBXML(error_list) = NULL; } xmlResetLastError(); return SUCCESS; } static PHP_MINFO_FUNCTION(libxml) { php_info_print_table_start(); php_info_print_table_row(2, "libXML support", "active"); php_info_print_table_row(2, "libXML Compiled Version", LIBXML_DOTTED_VERSION); php_info_print_table_row(2, "libXML Loaded Version", (char *)xmlParserVersion); php_info_print_table_row(2, "libXML streams", "enabled"); php_info_print_table_end(); } /* }}} */ /* {{{ proto void libxml_set_streams_context(resource streams_context) Set the streams context for the next libxml document load or write */ static PHP_FUNCTION(libxml_set_streams_context) { zval *arg; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &arg) == FAILURE) { return; } if (LIBXML(stream_context)) { zval_ptr_dtor(&LIBXML(stream_context)); LIBXML(stream_context) = NULL; } Z_ADDREF_P(arg); LIBXML(stream_context) = arg; } /* }}} */ /* {{{ proto bool libxml_use_internal_errors([boolean use_errors]) Disable libxml errors and allow user to fetch error information as needed */ static PHP_FUNCTION(libxml_use_internal_errors) { xmlStructuredErrorFunc current_handler; zend_bool use_errors=0, retval; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &use_errors) == FAILURE) { return; } current_handler = xmlStructuredError; if (current_handler && current_handler == php_libxml_structured_error_handler) { retval = 1; } else { retval = 0; } if (ZEND_NUM_ARGS() == 0) { RETURN_BOOL(retval); } if (use_errors == 0) { xmlSetStructuredErrorFunc(NULL, NULL); if (LIBXML(error_list)) { zend_llist_destroy(LIBXML(error_list)); efree(LIBXML(error_list)); LIBXML(error_list) = NULL; } } else { xmlSetStructuredErrorFunc(NULL, php_libxml_structured_error_handler); if (LIBXML(error_list) == NULL) { LIBXML(error_list) = (zend_llist *) emalloc(sizeof(zend_llist)); zend_llist_init(LIBXML(error_list), sizeof(xmlError), (llist_dtor_func_t) _php_libxml_free_error, 0); } } RETURN_BOOL(retval); } /* }}} */ /* {{{ proto object libxml_get_last_error() Retrieve last error from libxml */ static PHP_FUNCTION(libxml_get_last_error) { xmlErrorPtr error; error = xmlGetLastError(); if (error) { object_init_ex(return_value, libxmlerror_class_entry); add_property_long(return_value, "level", error->level); add_property_long(return_value, "code", error->code); add_property_long(return_value, "column", error->int2); if (error->message) { add_property_string(return_value, "message", error->message, 1); } else { add_property_stringl(return_value, "message", "", 0, 1); } if (error->file) { add_property_string(return_value, "file", error->file, 1); } else { add_property_stringl(return_value, "file", "", 0, 1); } add_property_long(return_value, "line", error->line); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto object libxml_get_errors() Retrieve array of errors */ static PHP_FUNCTION(libxml_get_errors) { xmlErrorPtr error; if (array_init(return_value) == FAILURE) { RETURN_FALSE; } if (LIBXML(error_list)) { error = zend_llist_get_first(LIBXML(error_list)); while (error != NULL) { zval *z_error; MAKE_STD_ZVAL(z_error); object_init_ex(z_error, libxmlerror_class_entry); add_property_long(z_error, "level", error->level); add_property_long(z_error, "code", error->code); add_property_long(z_error, "column", error->int2); if (error->message) { add_property_string(z_error, "message", error->message, 1); } else { add_property_stringl(z_error, "message", "", 0, 1); } if (error->file) { add_property_string(z_error, "file", error->file, 1); } else { add_property_stringl(z_error, "file", "", 0, 1); } add_property_long(z_error, "line", error->line); add_next_index_zval(return_value, z_error); error = zend_llist_get_next(LIBXML(error_list)); } } } /* }}} */ /* {{{ proto void libxml_clear_errors() Clear last error from libxml */ static PHP_FUNCTION(libxml_clear_errors) { xmlResetLastError(); if (LIBXML(error_list)) { zend_llist_clean(LIBXML(error_list)); } } /* }}} */ /* {{{ proto bool libxml_disable_entity_loader([boolean disable]) Disable/Enable ability to load external entities */ static PHP_FUNCTION(libxml_disable_entity_loader) { zend_bool disable = 1; xmlParserInputBufferCreateFilenameFunc old; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &disable) == FAILURE) { return; } if (disable == 0) { old = xmlParserInputBufferCreateFilenameDefault(php_libxml_input_buffer_create_filename); } else { old = xmlParserInputBufferCreateFilenameDefault(php_libxml_input_buffer_noload); } if (old == php_libxml_input_buffer_noload) { RETURN_TRUE; } RETURN_FALSE; } /* }}} */ /* {{{ Common functions shared by extensions */ int php_libxml_xmlCheckUTF8(const unsigned char *s) { int i; unsigned char c; for (i = 0; (c = s[i++]);) { if ((c & 0x80) == 0) { } else if ((c & 0xe0) == 0xc0) { if ((s[i++] & 0xc0) != 0x80) { return 0; } } else if ((c & 0xf0) == 0xe0) { if ((s[i++] & 0xc0) != 0x80 || (s[i++] & 0xc0) != 0x80) { return 0; } } else if ((c & 0xf8) == 0xf0) { if ((s[i++] & 0xc0) != 0x80 || (s[i++] & 0xc0) != 0x80 || (s[i++] & 0xc0) != 0x80) { return 0; } } else { return 0; } } return 1; } int php_libxml_register_export(zend_class_entry *ce, php_libxml_export_node export_function) { php_libxml_func_handler export_hnd; /* Initialize in case this module hasnt been loaded yet */ php_libxml_initialize(); export_hnd.export_func = export_function; return zend_hash_add(&php_libxml_exports, ce->name, ce->name_length + 1, &export_hnd, sizeof(export_hnd), NULL); } PHP_LIBXML_API xmlNodePtr php_libxml_import_node(zval *object TSRMLS_DC) { zend_class_entry *ce = NULL; xmlNodePtr node = NULL; php_libxml_func_handler *export_hnd; if (object->type == IS_OBJECT) { ce = Z_OBJCE_P(object); while (ce->parent != NULL) { ce = ce->parent; } if (zend_hash_find(&php_libxml_exports, ce->name, ce->name_length + 1, (void **) &export_hnd) == SUCCESS) { node = export_hnd->export_func(object TSRMLS_CC); } } return node; } PHP_LIBXML_API int php_libxml_increment_node_ptr(php_libxml_node_object *object, xmlNodePtr node, void *private_data TSRMLS_DC) { int ret_refcount = -1; if (object != NULL && node != NULL) { if (object->node != NULL) { if (object->node->node == node) { return object->node->refcount; } else { php_libxml_decrement_node_ptr(object TSRMLS_CC); } } if (node->_private != NULL) { object->node = node->_private; ret_refcount = ++object->node->refcount; /* Only dom uses _private */ if (object->node->_private == NULL) { object->node->_private = private_data; } } else { ret_refcount = 1; object->node = emalloc(sizeof(php_libxml_node_ptr)); object->node->node = node; object->node->refcount = 1; object->node->_private = private_data; node->_private = object->node; } } return ret_refcount; } PHP_LIBXML_API int php_libxml_decrement_node_ptr(php_libxml_node_object *object TSRMLS_DC) { int ret_refcount = -1; php_libxml_node_ptr *obj_node; if (object != NULL && object->node != NULL) { obj_node = (php_libxml_node_ptr *) object->node; ret_refcount = --obj_node->refcount; if (ret_refcount == 0) { if (obj_node->node != NULL) { obj_node->node->_private = NULL; } efree(obj_node); } object->node = NULL; } return ret_refcount; } PHP_LIBXML_API int php_libxml_increment_doc_ref(php_libxml_node_object *object, xmlDocPtr docp TSRMLS_DC) { int ret_refcount = -1; if (object->document != NULL) { object->document->refcount++; ret_refcount = object->document->refcount; } else if (docp != NULL) { ret_refcount = 1; object->document = emalloc(sizeof(php_libxml_ref_obj)); object->document->ptr = docp; object->document->refcount = ret_refcount; object->document->doc_props = NULL; } return ret_refcount; } PHP_LIBXML_API int php_libxml_decrement_doc_ref(php_libxml_node_object *object TSRMLS_DC) { int ret_refcount = -1; if (object != NULL && object->document != NULL) { ret_refcount = --object->document->refcount; if (ret_refcount == 0) { if (object->document->ptr != NULL) { xmlFreeDoc((xmlDoc *) object->document->ptr); } if (object->document->doc_props != NULL) { if (object->document->doc_props->classmap) { zend_hash_destroy(object->document->doc_props->classmap); FREE_HASHTABLE(object->document->doc_props->classmap); } efree(object->document->doc_props); } efree(object->document); object->document = NULL; } } return ret_refcount; } PHP_LIBXML_API void php_libxml_node_free_resource(xmlNodePtr node TSRMLS_DC) { if (!node) { return; } switch (node->type) { case XML_DOCUMENT_NODE: case XML_HTML_DOCUMENT_NODE: break; default: if (node->parent == NULL || node->type == XML_NAMESPACE_DECL) { php_libxml_node_free_list((xmlNodePtr) node->children TSRMLS_CC); switch (node->type) { /* Skip property freeing for the following types */ case XML_ATTRIBUTE_DECL: case XML_DTD_NODE: case XML_DOCUMENT_TYPE_NODE: case XML_ENTITY_DECL: case XML_ATTRIBUTE_NODE: case XML_NAMESPACE_DECL: case XML_TEXT_NODE: break; default: php_libxml_node_free_list((xmlNodePtr) node->properties TSRMLS_CC); } if (php_libxml_unregister_node(node TSRMLS_CC) == 0) { node->doc = NULL; } php_libxml_node_free(node); } else { php_libxml_unregister_node(node TSRMLS_CC); } } } PHP_LIBXML_API void php_libxml_node_decrement_resource(php_libxml_node_object *object TSRMLS_DC) { int ret_refcount = -1; xmlNodePtr nodep; php_libxml_node_ptr *obj_node; if (object != NULL && object->node != NULL) { obj_node = (php_libxml_node_ptr *) object->node; nodep = object->node->node; ret_refcount = php_libxml_decrement_node_ptr(object TSRMLS_CC); if (ret_refcount == 0) { php_libxml_node_free_resource(nodep TSRMLS_CC); } else { if (obj_node && object == obj_node->_private) { obj_node->_private = NULL; } } } if (object != NULL && object->document != NULL) { /* Safe to call as if the resource were freed then doc pointer is NULL */ php_libxml_decrement_doc_ref(object TSRMLS_CC); } } /* }}} */ #ifdef PHP_WIN32 PHP_LIBXML_API BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { return xmlDllMain(hinstDLL, fdwReason, lpvReserved); } #endif #endif /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Shane Caraveo <[email protected]> | | Wez Furlong <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #define IS_EXT_MODULE #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "SAPI.h" #define PHP_XML_INTERNAL #include "zend_variables.h" #include "ext/standard/php_string.h" #include "ext/standard/info.h" #include "ext/standard/file.h" #if HAVE_LIBXML #include <libxml/parser.h> #include <libxml/parserInternals.h> #include <libxml/tree.h> #include <libxml/uri.h> #include <libxml/xmlerror.h> #include <libxml/xmlsave.h> #ifdef LIBXML_SCHEMAS_ENABLED #include <libxml/relaxng.h> #endif #include "php_libxml.h" #define PHP_LIBXML_ERROR 0 #define PHP_LIBXML_CTX_ERROR 1 #define PHP_LIBXML_CTX_WARNING 2 /* a true global for initialization */ static int _php_libxml_initialized = 0; static int _php_libxml_per_request_initialization = 1; typedef struct _php_libxml_func_handler { php_libxml_export_node export_func; } php_libxml_func_handler; static HashTable php_libxml_exports; static ZEND_DECLARE_MODULE_GLOBALS(libxml) static PHP_GINIT_FUNCTION(libxml); static PHP_FUNCTION(libxml_set_streams_context); static PHP_FUNCTION(libxml_use_internal_errors); static PHP_FUNCTION(libxml_get_last_error); static PHP_FUNCTION(libxml_clear_errors); static PHP_FUNCTION(libxml_get_errors); static PHP_FUNCTION(libxml_disable_entity_loader); static zend_class_entry *libxmlerror_class_entry; /* {{{ dynamically loadable module stuff */ #ifdef COMPILE_DL_LIBXML ZEND_GET_MODULE(libxml) #endif /* COMPILE_DL_LIBXML */ /* }}} */ /* {{{ function prototypes */ static PHP_MINIT_FUNCTION(libxml); static PHP_RINIT_FUNCTION(libxml); static PHP_MSHUTDOWN_FUNCTION(libxml); static PHP_RSHUTDOWN_FUNCTION(libxml); static PHP_MINFO_FUNCTION(libxml); /* }}} */ /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO(arginfo_libxml_set_streams_context, 0) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_libxml_use_internal_errors, 0, 0, 0) ZEND_ARG_INFO(0, use_errors) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_libxml_get_last_error, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_libxml_get_errors, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_libxml_clear_errors, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_libxml_disable_entity_loader, 0, 0, 0) ZEND_ARG_INFO(0, disable) ZEND_END_ARG_INFO() /* }}} */ /* {{{ extension definition structures */ static const zend_function_entry libxml_functions[] = { PHP_FE(libxml_set_streams_context, arginfo_libxml_set_streams_context) PHP_FE(libxml_use_internal_errors, arginfo_libxml_use_internal_errors) PHP_FE(libxml_get_last_error, arginfo_libxml_get_last_error) PHP_FE(libxml_clear_errors, arginfo_libxml_clear_errors) PHP_FE(libxml_get_errors, arginfo_libxml_get_errors) PHP_FE(libxml_disable_entity_loader, arginfo_libxml_disable_entity_loader) {NULL, NULL, NULL} }; zend_module_entry libxml_module_entry = { STANDARD_MODULE_HEADER, "libxml", /* extension name */ libxml_functions, /* extension function list */ PHP_MINIT(libxml), /* extension-wide startup function */ PHP_MSHUTDOWN(libxml), /* extension-wide shutdown function */ PHP_RINIT(libxml), /* per-request startup function */ PHP_RSHUTDOWN(libxml), /* per-request shutdown function */ PHP_MINFO(libxml), /* information function */ NO_VERSION_YET, PHP_MODULE_GLOBALS(libxml), /* globals descriptor */ PHP_GINIT(libxml), /* globals ctor */ NULL, /* globals dtor */ NULL, /* post deactivate */ STANDARD_MODULE_PROPERTIES_EX }; /* }}} */ /* {{{ internal functions for interoperability */ static int php_libxml_clear_object(php_libxml_node_object *object TSRMLS_DC) { if (object->properties) { object->properties = NULL; } php_libxml_decrement_node_ptr(object TSRMLS_CC); return php_libxml_decrement_doc_ref(object TSRMLS_CC); } static int php_libxml_unregister_node(xmlNodePtr nodep TSRMLS_DC) { php_libxml_node_object *wrapper; php_libxml_node_ptr *nodeptr = nodep->_private; if (nodeptr != NULL) { wrapper = nodeptr->_private; if (wrapper) { php_libxml_clear_object(wrapper TSRMLS_CC); } else { if (nodeptr->node != NULL && nodeptr->node->type != XML_DOCUMENT_NODE) { nodeptr->node->_private = NULL; } nodeptr->node = NULL; } } return -1; } static void php_libxml_node_free(xmlNodePtr node) { if(node) { if (node->_private != NULL) { ((php_libxml_node_ptr *) node->_private)->node = NULL; } switch (node->type) { case XML_ATTRIBUTE_NODE: xmlFreeProp((xmlAttrPtr) node); break; case XML_ENTITY_DECL: case XML_ELEMENT_DECL: case XML_ATTRIBUTE_DECL: break; case XML_NOTATION_NODE: /* These require special handling */ if (node->name != NULL) { xmlFree((char *) node->name); } if (((xmlEntityPtr) node)->ExternalID != NULL) { xmlFree((char *) ((xmlEntityPtr) node)->ExternalID); } if (((xmlEntityPtr) node)->SystemID != NULL) { xmlFree((char *) ((xmlEntityPtr) node)->SystemID); } xmlFree(node); break; case XML_NAMESPACE_DECL: if (node->ns) { xmlFreeNs(node->ns); node->ns = NULL; } node->type = XML_ELEMENT_NODE; default: xmlFreeNode(node); } } } static void php_libxml_node_free_list(xmlNodePtr node TSRMLS_DC) { xmlNodePtr curnode; if (node != NULL) { curnode = node; while (curnode != NULL) { node = curnode; switch (node->type) { /* Skip property freeing for the following types */ case XML_NOTATION_NODE: break; case XML_ENTITY_REF_NODE: php_libxml_node_free_list((xmlNodePtr) node->properties TSRMLS_CC); break; case XML_ATTRIBUTE_NODE: if ((node->doc != NULL) && (((xmlAttrPtr) node)->atype == XML_ATTRIBUTE_ID)) { xmlRemoveID(node->doc, (xmlAttrPtr) node); } case XML_ATTRIBUTE_DECL: case XML_DTD_NODE: case XML_DOCUMENT_TYPE_NODE: case XML_ENTITY_DECL: case XML_NAMESPACE_DECL: case XML_TEXT_NODE: php_libxml_node_free_list(node->children TSRMLS_CC); break; default: php_libxml_node_free_list(node->children TSRMLS_CC); php_libxml_node_free_list((xmlNodePtr) node->properties TSRMLS_CC); } curnode = node->next; xmlUnlinkNode(node); if (php_libxml_unregister_node(node TSRMLS_CC) == 0) { node->doc = NULL; } php_libxml_node_free(node); } } } /* }}} */ /* {{{ startup, shutdown and info functions */ static PHP_GINIT_FUNCTION(libxml) { libxml_globals->stream_context = NULL; libxml_globals->error_buffer.c = NULL; libxml_globals->error_list = NULL; } /* Channel libxml file io layer through the PHP streams subsystem. * This allows use of ftps:// and https:// urls */ static void *php_libxml_streams_IO_open_wrapper(const char *filename, const char *mode, const int read_only) { php_stream_statbuf ssbuf; php_stream_context *context = NULL; php_stream_wrapper *wrapper = NULL; char *resolved_path, *path_to_open = NULL; void *ret_val = NULL; int isescaped=0; xmlURI *uri; TSRMLS_FETCH(); uri = xmlParseURI((xmlChar *)filename); if (uri && (uri->scheme == NULL || (xmlStrncmp(uri->scheme, "file", 4) == 0))) { resolved_path = xmlURIUnescapeString(filename, 0, NULL); isescaped = 1; } else { resolved_path = (char *)filename; } if (uri) { xmlFreeURI(uri); } if (resolved_path == NULL) { return NULL; } /* logic copied from _php_stream_stat, but we only want to fail if the wrapper supports stat, otherwise, figure it out from the open. This logic is only to support hiding warnings that the streams layer puts out at times, but for libxml we may try to open files that don't exist, but it is not a failure in xml processing (eg. DTD files) */ wrapper = php_stream_locate_url_wrapper(resolved_path, &path_to_open, 0 TSRMLS_CC); if (wrapper && read_only && wrapper->wops->url_stat) { if (wrapper->wops->url_stat(wrapper, path_to_open, PHP_STREAM_URL_STAT_QUIET, &ssbuf, NULL TSRMLS_CC) == -1) { if (isescaped) { xmlFree(resolved_path); } return NULL; } } context = php_stream_context_from_zval(LIBXML(stream_context), 0); ret_val = php_stream_open_wrapper_ex(path_to_open, (char *)mode, REPORT_ERRORS, NULL, context); if (isescaped) { xmlFree(resolved_path); } return ret_val; } static void *php_libxml_streams_IO_open_read_wrapper(const char *filename) { return php_libxml_streams_IO_open_wrapper(filename, "rb", 1); } static void *php_libxml_streams_IO_open_write_wrapper(const char *filename) { return php_libxml_streams_IO_open_wrapper(filename, "wb", 0); } static int php_libxml_streams_IO_read(void *context, char *buffer, int len) { TSRMLS_FETCH(); return php_stream_read((php_stream*)context, buffer, len); } static int php_libxml_streams_IO_write(void *context, const char *buffer, int len) { TSRMLS_FETCH(); return php_stream_write((php_stream*)context, buffer, len); } static int php_libxml_streams_IO_close(void *context) { TSRMLS_FETCH(); return php_stream_close((php_stream*)context); } static xmlParserInputBufferPtr php_libxml_input_buffer_noload(const char *URI, xmlCharEncoding enc) { return NULL; } static xmlParserInputBufferPtr php_libxml_input_buffer_create_filename(const char *URI, xmlCharEncoding enc) { xmlParserInputBufferPtr ret; void *context = NULL; if (URI == NULL) return(NULL); context = php_libxml_streams_IO_open_read_wrapper(URI); if (context == NULL) { return(NULL); } /* Allocate the Input buffer front-end. */ ret = xmlAllocParserInputBuffer(enc); if (ret != NULL) { ret->context = context; ret->readcallback = php_libxml_streams_IO_read; ret->closecallback = php_libxml_streams_IO_close; } else php_libxml_streams_IO_close(context); return(ret); } static xmlOutputBufferPtr php_libxml_output_buffer_create_filename(const char *URI, xmlCharEncodingHandlerPtr encoder, int compression ATTRIBUTE_UNUSED) { xmlOutputBufferPtr ret; xmlURIPtr puri; void *context = NULL; char *unescaped = NULL; if (URI == NULL) return(NULL); puri = xmlParseURI(URI); if (puri != NULL) { if (puri->scheme != NULL) unescaped = xmlURIUnescapeString(URI, 0, NULL); xmlFreeURI(puri); } if (unescaped != NULL) { context = php_libxml_streams_IO_open_write_wrapper(unescaped); xmlFree(unescaped); } /* try with a non-escaped URI this may be a strange filename */ if (context == NULL) { context = php_libxml_streams_IO_open_write_wrapper(URI); } if (context == NULL) { return(NULL); } /* Allocate the Output buffer front-end. */ ret = xmlAllocOutputBuffer(encoder); if (ret != NULL) { ret->context = context; ret->writecallback = php_libxml_streams_IO_write; ret->closecallback = php_libxml_streams_IO_close; } return(ret); } static int _php_libxml_free_error(xmlErrorPtr error) { /* This will free the libxml alloc'd memory */ xmlResetError(error); return 1; } static void _php_list_set_error_structure(xmlErrorPtr error, const char *msg) { xmlError error_copy; int ret; TSRMLS_FETCH(); memset(&error_copy, 0, sizeof(xmlError)); if (error) { ret = xmlCopyError(error, &error_copy); } else { error_copy.domain = 0; error_copy.code = XML_ERR_INTERNAL_ERROR; error_copy.level = XML_ERR_ERROR; error_copy.line = 0; error_copy.node = NULL; error_copy.int1 = 0; error_copy.int2 = 0; error_copy.ctxt = NULL; error_copy.message = xmlStrdup(msg); error_copy.file = NULL; error_copy.str1 = NULL; error_copy.str2 = NULL; error_copy.str3 = NULL; ret = 0; } if (ret == 0) { zend_llist_add_element(LIBXML(error_list), &error_copy); } } static void php_libxml_ctx_error_level(int level, void *ctx, const char *msg TSRMLS_DC) { xmlParserCtxtPtr parser; parser = (xmlParserCtxtPtr) ctx; if (parser != NULL && parser->input != NULL) { if (parser->input->filename) { php_error_docref(NULL TSRMLS_CC, level, "%s in %s, line: %d", msg, parser->input->filename, parser->input->line); } else { php_error_docref(NULL TSRMLS_CC, level, "%s in Entity, line: %d", msg, parser->input->line); } } } void php_libxml_issue_error(int level, const char *msg TSRMLS_DC) { if (LIBXML(error_list)) { _php_list_set_error_structure(NULL, msg); } else { php_error_docref(NULL TSRMLS_CC, level, "%s", msg); } } static void php_libxml_internal_error_handler(int error_type, void *ctx, const char **msg, va_list ap) { char *buf; int len, len_iter, output = 0; TSRMLS_FETCH(); len = vspprintf(&buf, 0, *msg, ap); len_iter = len; /* remove any trailing \n */ while (len_iter && buf[--len_iter] == '\n') { buf[len_iter] = '\0'; output = 1; } smart_str_appendl(&LIBXML(error_buffer), buf, len); efree(buf); if (output == 1) { if (LIBXML(error_list)) { _php_list_set_error_structure(NULL, LIBXML(error_buffer).c); } else { switch (error_type) { case PHP_LIBXML_CTX_ERROR: php_libxml_ctx_error_level(E_WARNING, ctx, LIBXML(error_buffer).c TSRMLS_CC); break; case PHP_LIBXML_CTX_WARNING: php_libxml_ctx_error_level(E_NOTICE, ctx, LIBXML(error_buffer).c TSRMLS_CC); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", LIBXML(error_buffer).c); } } smart_str_free(&LIBXML(error_buffer)); } } PHP_LIBXML_API void php_libxml_ctx_error(void *ctx, const char *msg, ...) { va_list args; va_start(args, msg); php_libxml_internal_error_handler(PHP_LIBXML_CTX_ERROR, ctx, &msg, args); va_end(args); } PHP_LIBXML_API void php_libxml_ctx_warning(void *ctx, const char *msg, ...) { va_list args; va_start(args, msg); php_libxml_internal_error_handler(PHP_LIBXML_CTX_WARNING, ctx, &msg, args); va_end(args); } PHP_LIBXML_API void php_libxml_structured_error_handler(void *userData, xmlErrorPtr error) { _php_list_set_error_structure(error, NULL); return; } PHP_LIBXML_API void php_libxml_error_handler(void *ctx, const char *msg, ...) { va_list args; va_start(args, msg); php_libxml_internal_error_handler(PHP_LIBXML_ERROR, ctx, &msg, args); va_end(args); } PHP_LIBXML_API void php_libxml_initialize(void) { if (!_php_libxml_initialized) { /* we should be the only one's to ever init!! */ xmlInitParser(); zend_hash_init(&php_libxml_exports, 0, NULL, NULL, 1); _php_libxml_initialized = 1; } } PHP_LIBXML_API void php_libxml_shutdown(void) { if (_php_libxml_initialized) { #if defined(LIBXML_SCHEMAS_ENABLED) xmlRelaxNGCleanupTypes(); #endif xmlCleanupParser(); zend_hash_destroy(&php_libxml_exports); _php_libxml_initialized = 0; } } PHP_LIBXML_API zval *php_libxml_switch_context(zval *context TSRMLS_DC) { zval *oldcontext; oldcontext = LIBXML(stream_context); LIBXML(stream_context) = context; return oldcontext; } static PHP_MINIT_FUNCTION(libxml) { zend_class_entry ce; php_libxml_initialize(); REGISTER_LONG_CONSTANT("LIBXML_VERSION", LIBXML_VERSION, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("LIBXML_DOTTED_VERSION", LIBXML_DOTTED_VERSION, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("LIBXML_LOADED_VERSION", (char *)xmlParserVersion, CONST_CS | CONST_PERSISTENT); /* For use with loading xml */ REGISTER_LONG_CONSTANT("LIBXML_NOENT", XML_PARSE_NOENT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_DTDLOAD", XML_PARSE_DTDLOAD, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_DTDATTR", XML_PARSE_DTDATTR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_DTDVALID", XML_PARSE_DTDVALID, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_NOERROR", XML_PARSE_NOERROR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_NOWARNING", XML_PARSE_NOWARNING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_NOBLANKS", XML_PARSE_NOBLANKS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_XINCLUDE", XML_PARSE_XINCLUDE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_NSCLEAN", XML_PARSE_NSCLEAN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_NOCDATA", XML_PARSE_NOCDATA, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_NONET", XML_PARSE_NONET, CONST_CS | CONST_PERSISTENT); #if LIBXML_VERSION >= 20621 REGISTER_LONG_CONSTANT("LIBXML_COMPACT", XML_PARSE_COMPACT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_NOXMLDECL", XML_SAVE_NO_DECL, CONST_CS | CONST_PERSISTENT); #endif #if LIBXML_VERSION >= 20703 REGISTER_LONG_CONSTANT("LIBXML_PARSEHUGE", XML_PARSE_HUGE, CONST_CS | CONST_PERSISTENT); #endif REGISTER_LONG_CONSTANT("LIBXML_NOEMPTYTAG", LIBXML_SAVE_NOEMPTYTAG, CONST_CS | CONST_PERSISTENT); /* Error levels */ REGISTER_LONG_CONSTANT("LIBXML_ERR_NONE", XML_ERR_NONE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_ERR_WARNING", XML_ERR_WARNING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_ERR_ERROR", XML_ERR_ERROR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("LIBXML_ERR_FATAL", XML_ERR_FATAL, CONST_CS | CONST_PERSISTENT); INIT_CLASS_ENTRY(ce, "LibXMLError", NULL); libxmlerror_class_entry = zend_register_internal_class(&ce TSRMLS_CC); if (sapi_module.name) { static const char * const supported_sapis[] = { "cgi-fcgi", "fpm-fcgi", "litespeed", NULL }; const char * const *sapi_name; for (sapi_name = supported_sapis; *sapi_name; sapi_name++) { if (strcmp(sapi_module.name, *sapi_name) == 0) { _php_libxml_per_request_initialization = 0; break; } } } if (!_php_libxml_per_request_initialization) { /* report errors via handler rather than stderr */ xmlSetGenericErrorFunc(NULL, php_libxml_error_handler); xmlParserInputBufferCreateFilenameDefault(php_libxml_input_buffer_create_filename); xmlOutputBufferCreateFilenameDefault(php_libxml_output_buffer_create_filename); } return SUCCESS; } static PHP_RINIT_FUNCTION(libxml) { if (_php_libxml_per_request_initialization) { /* report errors via handler rather than stderr */ xmlSetGenericErrorFunc(NULL, php_libxml_error_handler); xmlParserInputBufferCreateFilenameDefault(php_libxml_input_buffer_create_filename); xmlOutputBufferCreateFilenameDefault(php_libxml_output_buffer_create_filename); } return SUCCESS; } static PHP_MSHUTDOWN_FUNCTION(libxml) { if (!_php_libxml_per_request_initialization) { xmlSetGenericErrorFunc(NULL, NULL); xmlSetStructuredErrorFunc(NULL, NULL); xmlParserInputBufferCreateFilenameDefault(NULL); xmlOutputBufferCreateFilenameDefault(NULL); } php_libxml_shutdown(); return SUCCESS; } static PHP_RSHUTDOWN_FUNCTION(libxml) { /* reset libxml generic error handling */ if (_php_libxml_per_request_initialization) { xmlSetGenericErrorFunc(NULL, NULL); xmlSetStructuredErrorFunc(NULL, NULL); xmlParserInputBufferCreateFilenameDefault(NULL); xmlOutputBufferCreateFilenameDefault(NULL); } if (LIBXML(stream_context)) { zval_ptr_dtor(&LIBXML(stream_context)); LIBXML(stream_context) = NULL; } smart_str_free(&LIBXML(error_buffer)); if (LIBXML(error_list)) { zend_llist_destroy(LIBXML(error_list)); efree(LIBXML(error_list)); LIBXML(error_list) = NULL; } xmlResetLastError(); return SUCCESS; } static PHP_MINFO_FUNCTION(libxml) { php_info_print_table_start(); php_info_print_table_row(2, "libXML support", "active"); php_info_print_table_row(2, "libXML Compiled Version", LIBXML_DOTTED_VERSION); php_info_print_table_row(2, "libXML Loaded Version", (char *)xmlParserVersion); php_info_print_table_row(2, "libXML streams", "enabled"); php_info_print_table_end(); } /* }}} */ /* {{{ proto void libxml_set_streams_context(resource streams_context) Set the streams context for the next libxml document load or write */ static PHP_FUNCTION(libxml_set_streams_context) { zval *arg; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &arg) == FAILURE) { return; } if (LIBXML(stream_context)) { zval_ptr_dtor(&LIBXML(stream_context)); LIBXML(stream_context) = NULL; } Z_ADDREF_P(arg); LIBXML(stream_context) = arg; } /* }}} */ /* {{{ proto bool libxml_use_internal_errors([boolean use_errors]) Disable libxml errors and allow user to fetch error information as needed */ static PHP_FUNCTION(libxml_use_internal_errors) { xmlStructuredErrorFunc current_handler; zend_bool use_errors=0, retval; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &use_errors) == FAILURE) { return; } current_handler = xmlStructuredError; if (current_handler && current_handler == php_libxml_structured_error_handler) { retval = 1; } else { retval = 0; } if (ZEND_NUM_ARGS() == 0) { RETURN_BOOL(retval); } if (use_errors == 0) { xmlSetStructuredErrorFunc(NULL, NULL); if (LIBXML(error_list)) { zend_llist_destroy(LIBXML(error_list)); efree(LIBXML(error_list)); LIBXML(error_list) = NULL; } } else { xmlSetStructuredErrorFunc(NULL, php_libxml_structured_error_handler); if (LIBXML(error_list) == NULL) { LIBXML(error_list) = (zend_llist *) emalloc(sizeof(zend_llist)); zend_llist_init(LIBXML(error_list), sizeof(xmlError), (llist_dtor_func_t) _php_libxml_free_error, 0); } } RETURN_BOOL(retval); } /* }}} */ /* {{{ proto object libxml_get_last_error() Retrieve last error from libxml */ static PHP_FUNCTION(libxml_get_last_error) { xmlErrorPtr error; error = xmlGetLastError(); if (error) { object_init_ex(return_value, libxmlerror_class_entry); add_property_long(return_value, "level", error->level); add_property_long(return_value, "code", error->code); add_property_long(return_value, "column", error->int2); if (error->message) { add_property_string(return_value, "message", error->message, 1); } else { add_property_stringl(return_value, "message", "", 0, 1); } if (error->file) { add_property_string(return_value, "file", error->file, 1); } else { add_property_stringl(return_value, "file", "", 0, 1); } add_property_long(return_value, "line", error->line); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto object libxml_get_errors() Retrieve array of errors */ static PHP_FUNCTION(libxml_get_errors) { xmlErrorPtr error; if (array_init(return_value) == FAILURE) { RETURN_FALSE; } if (LIBXML(error_list)) { error = zend_llist_get_first(LIBXML(error_list)); while (error != NULL) { zval *z_error; MAKE_STD_ZVAL(z_error); object_init_ex(z_error, libxmlerror_class_entry); add_property_long(z_error, "level", error->level); add_property_long(z_error, "code", error->code); add_property_long(z_error, "column", error->int2); if (error->message) { add_property_string(z_error, "message", error->message, 1); } else { add_property_stringl(z_error, "message", "", 0, 1); } if (error->file) { add_property_string(z_error, "file", error->file, 1); } else { add_property_stringl(z_error, "file", "", 0, 1); } add_property_long(z_error, "line", error->line); add_next_index_zval(return_value, z_error); error = zend_llist_get_next(LIBXML(error_list)); } } } /* }}} */ /* {{{ proto void libxml_clear_errors() Clear last error from libxml */ static PHP_FUNCTION(libxml_clear_errors) { xmlResetLastError(); if (LIBXML(error_list)) { zend_llist_clean(LIBXML(error_list)); } } /* }}} */ /* {{{ proto bool libxml_disable_entity_loader([boolean disable]) Disable/Enable ability to load external entities */ static PHP_FUNCTION(libxml_disable_entity_loader) { zend_bool disable = 1; xmlParserInputBufferCreateFilenameFunc old; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &disable) == FAILURE) { return; } if (disable == 0) { old = xmlParserInputBufferCreateFilenameDefault(php_libxml_input_buffer_create_filename); } else { old = xmlParserInputBufferCreateFilenameDefault(php_libxml_input_buffer_noload); } if (old == php_libxml_input_buffer_noload) { RETURN_TRUE; } RETURN_FALSE; } /* }}} */ /* {{{ Common functions shared by extensions */ int php_libxml_xmlCheckUTF8(const unsigned char *s) { int i; unsigned char c; for (i = 0; (c = s[i++]);) { if ((c & 0x80) == 0) { } else if ((c & 0xe0) == 0xc0) { if ((s[i++] & 0xc0) != 0x80) { return 0; } } else if ((c & 0xf0) == 0xe0) { if ((s[i++] & 0xc0) != 0x80 || (s[i++] & 0xc0) != 0x80) { return 0; } } else if ((c & 0xf8) == 0xf0) { if ((s[i++] & 0xc0) != 0x80 || (s[i++] & 0xc0) != 0x80 || (s[i++] & 0xc0) != 0x80) { return 0; } } else { return 0; } } return 1; } int php_libxml_register_export(zend_class_entry *ce, php_libxml_export_node export_function) { php_libxml_func_handler export_hnd; /* Initialize in case this module hasnt been loaded yet */ php_libxml_initialize(); export_hnd.export_func = export_function; return zend_hash_add(&php_libxml_exports, ce->name, ce->name_length + 1, &export_hnd, sizeof(export_hnd), NULL); } PHP_LIBXML_API xmlNodePtr php_libxml_import_node(zval *object TSRMLS_DC) { zend_class_entry *ce = NULL; xmlNodePtr node = NULL; php_libxml_func_handler *export_hnd; if (object->type == IS_OBJECT) { ce = Z_OBJCE_P(object); while (ce->parent != NULL) { ce = ce->parent; } if (zend_hash_find(&php_libxml_exports, ce->name, ce->name_length + 1, (void **) &export_hnd) == SUCCESS) { node = export_hnd->export_func(object TSRMLS_CC); } } return node; } PHP_LIBXML_API int php_libxml_increment_node_ptr(php_libxml_node_object *object, xmlNodePtr node, void *private_data TSRMLS_DC) { int ret_refcount = -1; if (object != NULL && node != NULL) { if (object->node != NULL) { if (object->node->node == node) { return object->node->refcount; } else { php_libxml_decrement_node_ptr(object TSRMLS_CC); } } if (node->_private != NULL) { object->node = node->_private; ret_refcount = ++object->node->refcount; /* Only dom uses _private */ if (object->node->_private == NULL) { object->node->_private = private_data; } } else { ret_refcount = 1; object->node = emalloc(sizeof(php_libxml_node_ptr)); object->node->node = node; object->node->refcount = 1; object->node->_private = private_data; node->_private = object->node; } } return ret_refcount; } PHP_LIBXML_API int php_libxml_decrement_node_ptr(php_libxml_node_object *object TSRMLS_DC) { int ret_refcount = -1; php_libxml_node_ptr *obj_node; if (object != NULL && object->node != NULL) { obj_node = (php_libxml_node_ptr *) object->node; ret_refcount = --obj_node->refcount; if (ret_refcount == 0) { if (obj_node->node != NULL) { obj_node->node->_private = NULL; } efree(obj_node); } object->node = NULL; } return ret_refcount; } PHP_LIBXML_API int php_libxml_increment_doc_ref(php_libxml_node_object *object, xmlDocPtr docp TSRMLS_DC) { int ret_refcount = -1; if (object->document != NULL) { object->document->refcount++; ret_refcount = object->document->refcount; } else if (docp != NULL) { ret_refcount = 1; object->document = emalloc(sizeof(php_libxml_ref_obj)); object->document->ptr = docp; object->document->refcount = ret_refcount; object->document->doc_props = NULL; } return ret_refcount; } PHP_LIBXML_API int php_libxml_decrement_doc_ref(php_libxml_node_object *object TSRMLS_DC) { int ret_refcount = -1; if (object != NULL && object->document != NULL) { ret_refcount = --object->document->refcount; if (ret_refcount == 0) { if (object->document->ptr != NULL) { xmlFreeDoc((xmlDoc *) object->document->ptr); } if (object->document->doc_props != NULL) { if (object->document->doc_props->classmap) { zend_hash_destroy(object->document->doc_props->classmap); FREE_HASHTABLE(object->document->doc_props->classmap); } efree(object->document->doc_props); } efree(object->document); object->document = NULL; } } return ret_refcount; } PHP_LIBXML_API void php_libxml_node_free_resource(xmlNodePtr node TSRMLS_DC) { if (!node) { return; } switch (node->type) { case XML_DOCUMENT_NODE: case XML_HTML_DOCUMENT_NODE: break; default: if (node->parent == NULL || node->type == XML_NAMESPACE_DECL) { php_libxml_node_free_list((xmlNodePtr) node->children TSRMLS_CC); switch (node->type) { /* Skip property freeing for the following types */ case XML_ATTRIBUTE_DECL: case XML_DTD_NODE: case XML_DOCUMENT_TYPE_NODE: case XML_ENTITY_DECL: case XML_ATTRIBUTE_NODE: case XML_NAMESPACE_DECL: case XML_TEXT_NODE: break; default: php_libxml_node_free_list((xmlNodePtr) node->properties TSRMLS_CC); } if (php_libxml_unregister_node(node TSRMLS_CC) == 0) { node->doc = NULL; } php_libxml_node_free(node); } else { php_libxml_unregister_node(node TSRMLS_CC); } } } PHP_LIBXML_API void php_libxml_node_decrement_resource(php_libxml_node_object *object TSRMLS_DC) { int ret_refcount = -1; xmlNodePtr nodep; php_libxml_node_ptr *obj_node; if (object != NULL && object->node != NULL) { obj_node = (php_libxml_node_ptr *) object->node; nodep = object->node->node; ret_refcount = php_libxml_decrement_node_ptr(object TSRMLS_CC); if (ret_refcount == 0) { php_libxml_node_free_resource(nodep TSRMLS_CC); } else { if (obj_node && object == obj_node->_private) { obj_node->_private = NULL; } } } if (object != NULL && object->document != NULL) { /* Safe to call as if the resource were freed then doc pointer is NULL */ php_libxml_decrement_doc_ref(object TSRMLS_CC); } } /* }}} */ #ifdef PHP_WIN32 PHP_LIBXML_API BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { return xmlDllMain(hinstDLL, fdwReason, lpvReserved); } #endif #endif /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-04-09-db01e840c2-09b990f499.c
manybugs_data_82
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Derick Rethans <[email protected]> | | Pierre-A. Joye <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "php_filter.h" #include "filter_private.h" #include "ext/standard/url.h" #include "ext/pcre/php_pcre.h" #include "zend_multiply.h" #if HAVE_ARPA_INET_H # include <arpa/inet.h> #endif #ifndef INADDR_NONE # define INADDR_NONE ((unsigned long int) -1) #endif /* {{{ FETCH_LONG_OPTION(var_name, option_name) */ #define FETCH_LONG_OPTION(var_name, option_name) \ var_name = 0; \ var_name##_set = 0; \ if (option_array) { \ if (zend_hash_find(HASH_OF(option_array), option_name, sizeof(option_name), (void **) &option_val) == SUCCESS) { \ PHP_FILTER_GET_LONG_OPT(option_val, var_name); \ var_name##_set = 1; \ } \ } /* }}} */ /* {{{ FETCH_STRING_OPTION(var_name, option_name) */ #define FETCH_STRING_OPTION(var_name, option_name) \ var_name = NULL; \ var_name##_set = 0; \ var_name##_len = 0; \ if (option_array) { \ if (zend_hash_find(HASH_OF(option_array), option_name, sizeof(option_name), (void **) &option_val) == SUCCESS) { \ if (Z_TYPE_PP(option_val) == IS_STRING) { \ var_name = Z_STRVAL_PP(option_val); \ var_name##_len = Z_STRLEN_PP(option_val); \ var_name##_set = 1; \ } \ } \ } /* }}} */ #define FORMAT_IPV4 4 #define FORMAT_IPV6 6 static int php_filter_parse_int(const char *str, unsigned int str_len, long *ret TSRMLS_DC) { /* {{{ */ long ctx_value; int sign = 0, digit = 0; const char *end = str + str_len; switch (*str) { case '-': sign = 1; case '+': str++; default: break; } /* must start with 1..9*/ if (str < end && *str >= '1' && *str <= '9') { ctx_value = ((sign)?-1:1) * ((*(str++)) - '0'); } else { return -1; } if ((end - str > MAX_LENGTH_OF_LONG - 1) /* number too long */ || (SIZEOF_LONG == 4 && (end - str == MAX_LENGTH_OF_LONG - 1) && *str > '2')) { /* overflow */ return -1; } while (str < end) { if (*str >= '0' && *str <= '9') { digit = (*(str++) - '0'); if ( (!sign) && ctx_value <= (LONG_MAX-digit)/10 ) { ctx_value = (ctx_value * 10) + digit; } else if ( sign && ctx_value >= (LONG_MIN+digit)/10) { ctx_value = (ctx_value * 10) - digit; } else { return -1; } } else { return -1; } } *ret = ctx_value; return 1; } /* }}} */ static int php_filter_parse_octal(const char *str, unsigned int str_len, long *ret TSRMLS_DC) { /* {{{ */ unsigned long ctx_value = 0; const char *end = str + str_len; while (str < end) { if (*str >= '0' && *str <= '7') { unsigned long n = ((*(str++)) - '0'); if ((ctx_value > ((unsigned long)(~(long)0)) / 8) || ((ctx_value = ctx_value * 8) > ((unsigned long)(~(long)0)) - n)) { return -1; } ctx_value += n; } else { return -1; } } *ret = (long)ctx_value; return 1; } /* }}} */ static int php_filter_parse_hex(const char *str, unsigned int str_len, long *ret TSRMLS_DC) { /* {{{ */ unsigned long ctx_value = 0; const char *end = str + str_len; unsigned long n; while (str < end) { if (*str >= '0' && *str <= '9') { n = ((*(str++)) - '0'); } else if (*str >= 'a' && *str <= 'f') { n = ((*(str++)) - ('a' - 10)); } else if (*str >= 'A' && *str <= 'F') { n = ((*(str++)) - ('A' - 10)); } else { return -1; } if ((ctx_value > ((unsigned long)(~(long)0)) / 16) || ((ctx_value = ctx_value * 16) > ((unsigned long)(~(long)0)) - n)) { return -1; } ctx_value += n; } *ret = (long)ctx_value; return 1; } /* }}} */ void php_filter_int(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { zval **option_val; long min_range, max_range, option_flags; int min_range_set, max_range_set; int allow_octal = 0, allow_hex = 0; int len, error = 0; long ctx_value; char *p; /* Parse options */ FETCH_LONG_OPTION(min_range, "min_range"); FETCH_LONG_OPTION(max_range, "max_range"); option_flags = flags; len = Z_STRLEN_P(value); if (len == 0) { RETURN_VALIDATION_FAILED } if (option_flags & FILTER_FLAG_ALLOW_OCTAL) { allow_octal = 1; } if (option_flags & FILTER_FLAG_ALLOW_HEX) { allow_hex = 1; } /* Start the validating loop */ p = Z_STRVAL_P(value); ctx_value = 0; PHP_FILTER_TRIM_DEFAULT(p, len); if (*p == '0') { p++; len--; if (allow_hex && (*p == 'x' || *p == 'X')) { p++; len--; if (php_filter_parse_hex(p, len, &ctx_value TSRMLS_CC) < 0) { error = 1; } } else if (allow_octal) { if (php_filter_parse_octal(p, len, &ctx_value TSRMLS_CC) < 0) { error = 1; } } else if (len != 0) { error = 1; } } else { if (php_filter_parse_int(p, len, &ctx_value TSRMLS_CC) < 0) { error = 1; } } if (error > 0 || (min_range_set && (ctx_value < min_range)) || (max_range_set && (ctx_value > max_range))) { RETURN_VALIDATION_FAILED } else { zval_dtor(value); Z_TYPE_P(value) = IS_LONG; Z_LVAL_P(value) = ctx_value; return; } } /* }}} */ void php_filter_boolean(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { char *str = Z_STRVAL_P(value); int len = Z_STRLEN_P(value); int ret; PHP_FILTER_TRIM_DEFAULT(str, len); /* returns true for "1", "true", "on" and "yes" * returns false for "0", "false", "off", "no", and "" * null otherwise. */ switch (len) { case 1: if (*str == '1') { ret = 1; } else if (*str == '0') { ret = 0; } else { ret = -1; } break; case 2: if (strncasecmp(str, "on", 2) == 0) { ret = 1; } else if (strncasecmp(str, "no", 2) == 0) { ret = 0; } else { ret = -1; } break; case 3: if (strncasecmp(str, "yes", 3) == 0) { ret = 1; } else if (strncasecmp(str, "off", 3) == 0) { ret = 0; } else { ret = -1; } break; case 4: if (strncasecmp(str, "true", 4) == 0) { ret = 1; } else { ret = -1; } break; case 5: if (strncasecmp(str, "false", 5) == 0) { ret = 0; } else { ret = -1; } break; default: ret = -1; } if (ret == -1) { RETURN_VALIDATION_FAILED } else { zval_dtor(value); ZVAL_BOOL(value, ret); } } /* }}} */ void php_filter_float(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { int len; char *str, *end; char *num, *p; zval **option_val; char *decimal; int decimal_set, decimal_len; char dec_sep = '.'; char tsd_sep[3] = "',."; long lval; double dval; int first, n; len = Z_STRLEN_P(value); str = Z_STRVAL_P(value); PHP_FILTER_TRIM_DEFAULT(str, len); end = str + len; FETCH_STRING_OPTION(decimal, "decimal"); if (decimal_set) { if (decimal_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "decimal separator must be one char"); RETURN_VALIDATION_FAILED } else { dec_sep = *decimal; } } num = p = emalloc(len+1); if (str < end && (*str == '+' || *str == '-')) { *p++ = *str++; } first = 1; while (1) { n = 0; while (str < end && *str >= '0' && *str <= '9') { ++n; *p++ = *str++; } if (str == end || *str == dec_sep || *str == 'e' || *str == 'E') { if (!first && n != 3) { goto error; } if (*str == dec_sep) { *p++ = '.'; str++; while (str < end && *str >= '0' && *str <= '9') { *p++ = *str++; } } if (*str == 'e' || *str == 'E') { *p++ = *str++; if (str < end && (*str == '+' || *str == '-')) { *p++ = *str++; } while (str < end && *str >= '0' && *str <= '9') { *p++ = *str++; } } break; } if ((flags & FILTER_FLAG_ALLOW_THOUSAND) && (*str == tsd_sep[0] || *str == tsd_sep[1] || *str == tsd_sep[2])) { if (first?(n < 1 || n > 3):(n != 3)) { goto error; } first = 0; str++; } else { goto error; } } if (str != end) { goto error; } *p = 0; switch (is_numeric_string(num, p - num, &lval, &dval, 0)) { case IS_LONG: zval_dtor(value); Z_TYPE_P(value) = IS_DOUBLE; Z_DVAL_P(value) = lval; break; case IS_DOUBLE: if ((!dval && p - num > 1 && strpbrk(num, "123456789")) || !zend_finite(dval)) { goto error; } zval_dtor(value); Z_TYPE_P(value) = IS_DOUBLE; Z_DVAL_P(value) = dval; break; default: error: efree(num); RETURN_VALIDATION_FAILED } efree(num); } /* }}} */ void php_filter_validate_regexp(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { zval **option_val; char *regexp; int regexp_len; long option_flags; int regexp_set, option_flags_set; pcre *re = NULL; pcre_extra *pcre_extra = NULL; int preg_options = 0; int ovector[3]; int matches; /* Parse options */ FETCH_STRING_OPTION(regexp, "regexp"); FETCH_LONG_OPTION(option_flags, "flags"); if (!regexp_set) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "'regexp' option missing"); RETURN_VALIDATION_FAILED } re = pcre_get_compiled_regex(regexp, &pcre_extra, &preg_options TSRMLS_CC); if (!re) { RETURN_VALIDATION_FAILED } matches = pcre_exec(re, NULL, Z_STRVAL_P(value), Z_STRLEN_P(value), 0, 0, ovector, 3); /* 0 means that the vector is too small to hold all the captured substring offsets */ if (matches < 0) { RETURN_VALIDATION_FAILED } } /* }}} */ void php_filter_validate_url(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { php_url *url; int old_len = Z_STRLEN_P(value); php_filter_url(value, flags, option_array, charset TSRMLS_CC); if (Z_TYPE_P(value) != IS_STRING || old_len != Z_STRLEN_P(value)) { RETURN_VALIDATION_FAILED } /* Use parse_url - if it returns false, we return NULL */ url = php_url_parse_ex(Z_STRVAL_P(value), Z_STRLEN_P(value)); if (url == NULL) { RETURN_VALIDATION_FAILED } if (url->scheme != NULL && (!strcasecmp(url->scheme, "http") || !strcasecmp(url->scheme, "https"))) { char *e, *s; if (url->host == NULL) { goto bad_url; } e = url->host + strlen(url->host); s = url->host; /* First char of hostname must be alphanumeric */ if(!isalnum((int)*(unsigned char *)s)) { goto bad_url; } while (s < e) { if (!isalnum((int)*(unsigned char *)s) && *s != '-' && *s != '.') { goto bad_url; } s++; } if (*(e - 1) == '.') { goto bad_url; } } if ( url->scheme == NULL || /* some schemas allow the host to be empty */ (url->host == NULL && (strcmp(url->scheme, "mailto") && strcmp(url->scheme, "news") && strcmp(url->scheme, "file"))) || ((flags & FILTER_FLAG_PATH_REQUIRED) && url->path == NULL) || ((flags & FILTER_FLAG_QUERY_REQUIRED) && url->query == NULL) ) { bad_url: php_url_free(url); RETURN_VALIDATION_FAILED } php_url_free(url); } /* }}} */ void php_filter_validate_email(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { /* * The regex below is based on a regex by Michael Rushton. * However, it is not identical. I changed it to only consider routeable * addresses as valid. Michael's regex considers a@b a valid address * which conflicts with section 2.3.5 of RFC 5321 which states that: * * Only resolvable, fully-qualified domain names (FQDNs) are permitted * when domain names are used in SMTP. In other words, names that can * be resolved to MX RRs or address (i.e., A or AAAA) RRs (as discussed * in Section 5) are permitted, as are CNAME RRs whose targets can be * resolved, in turn, to MX or address RRs. Local nicknames or * unqualified names MUST NOT be used. * * This regex does not handle comments and folding whitespace. While * this is technically valid in an email address, these parts aren't * actually part of the address itself. * * Michael's regex carries this copyright: * * Copyright © Michael Rushton 2009-10 * http://squiloople.com/ * Feel free to use and redistribute this code. But please keep this copyright notice. * */ const char regexp[] = "/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}@)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD"; pcre *re = NULL; pcre_extra *pcre_extra = NULL; int preg_options = 0; int ovector[150]; /* Needs to be a multiple of 3 */ int matches; /* The maximum length of an e-mail address is 320 octets, per RFC 2821. */ if (Z_STRLEN_P(value) > 320) { RETURN_VALIDATION_FAILED } re = pcre_get_compiled_regex((char *)regexp, &pcre_extra, &preg_options TSRMLS_CC); if (!re) { RETURN_VALIDATION_FAILED } matches = pcre_exec(re, NULL, Z_STRVAL_P(value), Z_STRLEN_P(value), 0, 0, ovector, 3); /* 0 means that the vector is too small to hold all the captured substring offsets */ if (matches < 0) { RETURN_VALIDATION_FAILED } } /* }}} */ static int _php_filter_validate_ipv4(char *str, int str_len, int *ip) /* {{{ */ { const char *end = str + str_len; int num, m; int n = 0; while (str < end) { int leading_zero; if (*str < '0' || *str > '9') { return 0; } leading_zero = (*str == '0'); m = 1; num = ((*(str++)) - '0'); while (str < end && (*str >= '0' && *str <= '9')) { num = num * 10 + ((*(str++)) - '0'); if (num > 255 || ++m > 3) { return 0; } } /* don't allow a leading 0; that introduces octal numbers, * which we don't support */ if (leading_zero && (num != 0 || m > 1)) return 0; ip[n++] = num; if (n == 4) { return str == end; } else if (str >= end || *(str++) != '.') { return 0; } } return 0; } /* }}} */ static int _php_filter_validate_ipv6(char *str, int str_len TSRMLS_DC) /* {{{ */ { int compressed = 0; int blocks = 0; int n; char *ipv4; char *end; int ip4elm[4]; char *s = str; if (!memchr(str, ':', str_len)) { return 0; } /* check for bundled IPv4 */ ipv4 = memchr(str, '.', str_len); if (ipv4) { while (ipv4 > str && *(ipv4-1) != ':') { ipv4--; } if (!_php_filter_validate_ipv4(ipv4, (str_len - (ipv4 - str)), ip4elm)) { return 0; } str_len = ipv4 - str; /* length excluding ipv4 */ if (str_len < 2) { return 0; } if (ipv4[-2] != ':') { /* don't include : before ipv4 unless it's a :: */ str_len--; } blocks = 2; } end = str + str_len; while (str < end) { if (*str == ':') { if (++str >= end) { /* cannot end in : without previous : */ return 0; } if (*str == ':') { if (compressed) { return 0; } blocks++; /* :: means 1 or more 16-bit 0 blocks */ compressed = 1; if (++str == end) { return (blocks <= 8); } } else if ((str - 1) == s) { /* dont allow leading : without another : following */ return 0; } } n = 0; while ((str < end) && ((*str >= '0' && *str <= '9') || (*str >= 'a' && *str <= 'f') || (*str >= 'A' && *str <= 'F'))) { n++; str++; } if (n < 1 || n > 4) { return 0; } if (++blocks > 8) return 0; } return ((compressed && blocks <= 8) || blocks == 8); } /* }}} */ void php_filter_validate_ip(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { /* validates an ipv4 or ipv6 IP, based on the flag (4, 6, or both) add a * flag to throw out reserved ranges; multicast ranges... etc. If both * allow_ipv4 and allow_ipv6 flags flag are used, then the first dot or * colon determine the format */ int ip[4]; int mode; if (memchr(Z_STRVAL_P(value), ':', Z_STRLEN_P(value))) { mode = FORMAT_IPV6; } else if (memchr(Z_STRVAL_P(value), '.', Z_STRLEN_P(value))) { mode = FORMAT_IPV4; } else { RETURN_VALIDATION_FAILED } if ((flags & FILTER_FLAG_IPV4) && (flags & FILTER_FLAG_IPV6)) { /* Both formats are cool */ } else if ((flags & FILTER_FLAG_IPV4) && mode == FORMAT_IPV6) { RETURN_VALIDATION_FAILED } else if ((flags & FILTER_FLAG_IPV6) && mode == FORMAT_IPV4) { RETURN_VALIDATION_FAILED } switch (mode) { case FORMAT_IPV4: if (!_php_filter_validate_ipv4(Z_STRVAL_P(value), Z_STRLEN_P(value), ip)) { RETURN_VALIDATION_FAILED } /* Check flags */ if (flags & FILTER_FLAG_NO_PRIV_RANGE) { if ( (ip[0] == 10) || (ip[0] == 172 && (ip[1] >= 16 && ip[1] <= 31)) || (ip[0] == 192 && ip[1] == 168) ) { RETURN_VALIDATION_FAILED } } if (flags & FILTER_FLAG_NO_RES_RANGE) { if ( (ip[0] == 0) || (ip[0] == 128 && ip[1] == 0) || (ip[0] == 191 && ip[1] == 255) || (ip[0] == 169 && ip[1] == 254) || (ip[0] == 192 && ip[1] == 0 && ip[2] == 2) || (ip[0] == 127 && ip[1] == 0 && ip[2] == 0 && ip[3] == 1) || (ip[0] >= 224 && ip[0] <= 255) ) { RETURN_VALIDATION_FAILED } } break; case FORMAT_IPV6: { int res = 0; res = _php_filter_validate_ipv6(Z_STRVAL_P(value), Z_STRLEN_P(value) TSRMLS_CC); if (res < 1) { RETURN_VALIDATION_FAILED } /* Check flags */ if (flags & FILTER_FLAG_NO_PRIV_RANGE) { if (Z_STRLEN_P(value) >=2 && (!strncasecmp("FC", Z_STRVAL_P(value), 2) || !strncasecmp("FD", Z_STRVAL_P(value), 2))) { RETURN_VALIDATION_FAILED } } if (flags & FILTER_FLAG_NO_RES_RANGE) { switch (Z_STRLEN_P(value)) { case 1: case 0: break; case 2: if (!strcmp("::", Z_STRVAL_P(value))) { RETURN_VALIDATION_FAILED } break; case 3: if (!strcmp("::1", Z_STRVAL_P(value)) || !strcmp("5f:", Z_STRVAL_P(value))) { RETURN_VALIDATION_FAILED } break; default: if (Z_STRLEN_P(value) >= 5) { if ( !strncasecmp("fe8", Z_STRVAL_P(value), 3) || !strncasecmp("fe9", Z_STRVAL_P(value), 3) || !strncasecmp("fea", Z_STRVAL_P(value), 3) || !strncasecmp("feb", Z_STRVAL_P(value), 3) ) { RETURN_VALIDATION_FAILED } } if ( (Z_STRLEN_P(value) >= 9 && !strncasecmp("2001:0db8", Z_STRVAL_P(value), 9)) || (Z_STRLEN_P(value) >= 2 && !strncasecmp("5f", Z_STRVAL_P(value), 2)) || (Z_STRLEN_P(value) >= 4 && !strncasecmp("3ff3", Z_STRVAL_P(value), 4)) || (Z_STRLEN_P(value) >= 8 && !strncasecmp("2001:001", Z_STRVAL_P(value), 8)) ) { RETURN_VALIDATION_FAILED } } } } break; } } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Derick Rethans <[email protected]> | | Pierre-A. Joye <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "php_filter.h" #include "filter_private.h" #include "ext/standard/url.h" #include "ext/pcre/php_pcre.h" #include "zend_multiply.h" #if HAVE_ARPA_INET_H # include <arpa/inet.h> #endif #ifndef INADDR_NONE # define INADDR_NONE ((unsigned long int) -1) #endif /* {{{ FETCH_LONG_OPTION(var_name, option_name) */ #define FETCH_LONG_OPTION(var_name, option_name) \ var_name = 0; \ var_name##_set = 0; \ if (option_array) { \ if (zend_hash_find(HASH_OF(option_array), option_name, sizeof(option_name), (void **) &option_val) == SUCCESS) { \ PHP_FILTER_GET_LONG_OPT(option_val, var_name); \ var_name##_set = 1; \ } \ } /* }}} */ /* {{{ FETCH_STRING_OPTION(var_name, option_name) */ #define FETCH_STRING_OPTION(var_name, option_name) \ var_name = NULL; \ var_name##_set = 0; \ var_name##_len = 0; \ if (option_array) { \ if (zend_hash_find(HASH_OF(option_array), option_name, sizeof(option_name), (void **) &option_val) == SUCCESS) { \ if (Z_TYPE_PP(option_val) == IS_STRING) { \ var_name = Z_STRVAL_PP(option_val); \ var_name##_len = Z_STRLEN_PP(option_val); \ var_name##_set = 1; \ } \ } \ } /* }}} */ #define FORMAT_IPV4 4 #define FORMAT_IPV6 6 static int php_filter_parse_int(const char *str, unsigned int str_len, long *ret TSRMLS_DC) { /* {{{ */ long ctx_value; int sign = 0, digit = 0; const char *end = str + str_len; switch (*str) { case '-': sign = 1; case '+': str++; default: break; } /* must start with 1..9*/ if (str < end && *str >= '1' && *str <= '9') { ctx_value = ((sign)?-1:1) * ((*(str++)) - '0'); } else { return -1; } if ((end - str > MAX_LENGTH_OF_LONG - 1) /* number too long */ || (SIZEOF_LONG == 4 && (end - str == MAX_LENGTH_OF_LONG - 1) && *str > '2')) { /* overflow */ return -1; } while (str < end) { if (*str >= '0' && *str <= '9') { digit = (*(str++) - '0'); if ( (!sign) && ctx_value <= (LONG_MAX-digit)/10 ) { ctx_value = (ctx_value * 10) + digit; } else if ( sign && ctx_value >= (LONG_MIN+digit)/10) { ctx_value = (ctx_value * 10) - digit; } else { return -1; } } else { return -1; } } *ret = ctx_value; return 1; } /* }}} */ static int php_filter_parse_octal(const char *str, unsigned int str_len, long *ret TSRMLS_DC) { /* {{{ */ unsigned long ctx_value = 0; const char *end = str + str_len; while (str < end) { if (*str >= '0' && *str <= '7') { unsigned long n = ((*(str++)) - '0'); if ((ctx_value > ((unsigned long)(~(long)0)) / 8) || ((ctx_value = ctx_value * 8) > ((unsigned long)(~(long)0)) - n)) { return -1; } ctx_value += n; } else { return -1; } } *ret = (long)ctx_value; return 1; } /* }}} */ static int php_filter_parse_hex(const char *str, unsigned int str_len, long *ret TSRMLS_DC) { /* {{{ */ unsigned long ctx_value = 0; const char *end = str + str_len; unsigned long n; while (str < end) { if (*str >= '0' && *str <= '9') { n = ((*(str++)) - '0'); } else if (*str >= 'a' && *str <= 'f') { n = ((*(str++)) - ('a' - 10)); } else if (*str >= 'A' && *str <= 'F') { n = ((*(str++)) - ('A' - 10)); } else { return -1; } if ((ctx_value > ((unsigned long)(~(long)0)) / 16) || ((ctx_value = ctx_value * 16) > ((unsigned long)(~(long)0)) - n)) { return -1; } ctx_value += n; } *ret = (long)ctx_value; return 1; } /* }}} */ void php_filter_int(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { zval **option_val; long min_range, max_range, option_flags; int min_range_set, max_range_set; int allow_octal = 0, allow_hex = 0; int len, error = 0; long ctx_value; char *p; /* Parse options */ FETCH_LONG_OPTION(min_range, "min_range"); FETCH_LONG_OPTION(max_range, "max_range"); option_flags = flags; len = Z_STRLEN_P(value); if (len == 0) { RETURN_VALIDATION_FAILED } if (option_flags & FILTER_FLAG_ALLOW_OCTAL) { allow_octal = 1; } if (option_flags & FILTER_FLAG_ALLOW_HEX) { allow_hex = 1; } /* Start the validating loop */ p = Z_STRVAL_P(value); ctx_value = 0; PHP_FILTER_TRIM_DEFAULT(p, len); if (*p == '0') { p++; len--; if (allow_hex && (*p == 'x' || *p == 'X')) { p++; len--; if (php_filter_parse_hex(p, len, &ctx_value TSRMLS_CC) < 0) { error = 1; } } else if (allow_octal) { if (php_filter_parse_octal(p, len, &ctx_value TSRMLS_CC) < 0) { error = 1; } } else if (len != 0) { error = 1; } } else { if (php_filter_parse_int(p, len, &ctx_value TSRMLS_CC) < 0) { error = 1; } } if (error > 0 || (min_range_set && (ctx_value < min_range)) || (max_range_set && (ctx_value > max_range))) { RETURN_VALIDATION_FAILED } else { zval_dtor(value); Z_TYPE_P(value) = IS_LONG; Z_LVAL_P(value) = ctx_value; return; } } /* }}} */ void php_filter_boolean(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { char *str = Z_STRVAL_P(value); int len = Z_STRLEN_P(value); int ret; PHP_FILTER_TRIM_DEFAULT(str, len); /* returns true for "1", "true", "on" and "yes" * returns false for "0", "false", "off", "no", and "" * null otherwise. */ switch (len) { case 1: if (*str == '1') { ret = 1; } else if (*str == '0') { ret = 0; } else { ret = -1; } break; case 2: if (strncasecmp(str, "on", 2) == 0) { ret = 1; } else if (strncasecmp(str, "no", 2) == 0) { ret = 0; } else { ret = -1; } break; case 3: if (strncasecmp(str, "yes", 3) == 0) { ret = 1; } else if (strncasecmp(str, "off", 3) == 0) { ret = 0; } else { ret = -1; } break; case 4: if (strncasecmp(str, "true", 4) == 0) { ret = 1; } else { ret = -1; } break; case 5: if (strncasecmp(str, "false", 5) == 0) { ret = 0; } else { ret = -1; } break; default: ret = -1; } if (ret == -1) { RETURN_VALIDATION_FAILED } else { zval_dtor(value); ZVAL_BOOL(value, ret); } } /* }}} */ void php_filter_float(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { int len; char *str, *end; char *num, *p; zval **option_val; char *decimal; int decimal_set, decimal_len; char dec_sep = '.'; char tsd_sep[3] = "',."; long lval; double dval; int first, n; len = Z_STRLEN_P(value); str = Z_STRVAL_P(value); PHP_FILTER_TRIM_DEFAULT(str, len); end = str + len; FETCH_STRING_OPTION(decimal, "decimal"); if (decimal_set) { if (decimal_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "decimal separator must be one char"); RETURN_VALIDATION_FAILED } else { dec_sep = *decimal; } } num = p = emalloc(len+1); if (str < end && (*str == '+' || *str == '-')) { *p++ = *str++; } first = 1; while (1) { n = 0; while (str < end && *str >= '0' && *str <= '9') { ++n; *p++ = *str++; } if (str == end || *str == dec_sep || *str == 'e' || *str == 'E') { if (!first && n != 3) { goto error; } if (*str == dec_sep) { *p++ = '.'; str++; while (str < end && *str >= '0' && *str <= '9') { *p++ = *str++; } } if (*str == 'e' || *str == 'E') { *p++ = *str++; if (str < end && (*str == '+' || *str == '-')) { *p++ = *str++; } while (str < end && *str >= '0' && *str <= '9') { *p++ = *str++; } } break; } if ((flags & FILTER_FLAG_ALLOW_THOUSAND) && (*str == tsd_sep[0] || *str == tsd_sep[1] || *str == tsd_sep[2])) { if (first?(n < 1 || n > 3):(n != 3)) { goto error; } first = 0; str++; } else { goto error; } } if (str != end) { goto error; } *p = 0; switch (is_numeric_string(num, p - num, &lval, &dval, 0)) { case IS_LONG: zval_dtor(value); Z_TYPE_P(value) = IS_DOUBLE; Z_DVAL_P(value) = lval; break; case IS_DOUBLE: if ((!dval && p - num > 1 && strpbrk(num, "123456789")) || !zend_finite(dval)) { goto error; } zval_dtor(value); Z_TYPE_P(value) = IS_DOUBLE; Z_DVAL_P(value) = dval; break; default: error: efree(num); RETURN_VALIDATION_FAILED } efree(num); } /* }}} */ void php_filter_validate_regexp(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { zval **option_val; char *regexp; int regexp_len; long option_flags; int regexp_set, option_flags_set; pcre *re = NULL; pcre_extra *pcre_extra = NULL; int preg_options = 0; int ovector[3]; int matches; /* Parse options */ FETCH_STRING_OPTION(regexp, "regexp"); FETCH_LONG_OPTION(option_flags, "flags"); if (!regexp_set) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "'regexp' option missing"); RETURN_VALIDATION_FAILED } re = pcre_get_compiled_regex(regexp, &pcre_extra, &preg_options TSRMLS_CC); if (!re) { RETURN_VALIDATION_FAILED } matches = pcre_exec(re, NULL, Z_STRVAL_P(value), Z_STRLEN_P(value), 0, 0, ovector, 3); /* 0 means that the vector is too small to hold all the captured substring offsets */ if (matches < 0) { RETURN_VALIDATION_FAILED } } /* }}} */ void php_filter_validate_url(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { php_url *url; int old_len = Z_STRLEN_P(value); php_filter_url(value, flags, option_array, charset TSRMLS_CC); if (Z_TYPE_P(value) != IS_STRING || old_len != Z_STRLEN_P(value)) { RETURN_VALIDATION_FAILED } /* Use parse_url - if it returns false, we return NULL */ url = php_url_parse_ex(Z_STRVAL_P(value), Z_STRLEN_P(value)); if (url == NULL) { RETURN_VALIDATION_FAILED } if (url->scheme != NULL && (!strcasecmp(url->scheme, "http") || !strcasecmp(url->scheme, "https"))) { char *e, *s; if (url->host == NULL) { goto bad_url; } e = url->host + strlen(url->host); s = url->host; /* First char of hostname must be alphanumeric */ if(!isalnum((int)*(unsigned char *)s)) { goto bad_url; } while (s < e) { if (!isalnum((int)*(unsigned char *)s) && *s != '-' && *s != '.') { goto bad_url; } s++; } if (*(e - 1) == '.') { goto bad_url; } } if ( url->scheme == NULL || /* some schemas allow the host to be empty */ (url->host == NULL && (strcmp(url->scheme, "mailto") && strcmp(url->scheme, "news") && strcmp(url->scheme, "file"))) || ((flags & FILTER_FLAG_PATH_REQUIRED) && url->path == NULL) || ((flags & FILTER_FLAG_QUERY_REQUIRED) && url->query == NULL) ) { bad_url: php_url_free(url); RETURN_VALIDATION_FAILED } php_url_free(url); } /* }}} */ void php_filter_validate_email(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { /* * The regex below is based on a regex by Michael Rushton. * However, it is not identical. I changed it to only consider routeable * addresses as valid. Michael's regex considers a@b a valid address * which conflicts with section 2.3.5 of RFC 5321 which states that: * * Only resolvable, fully-qualified domain names (FQDNs) are permitted * when domain names are used in SMTP. In other words, names that can * be resolved to MX RRs or address (i.e., A or AAAA) RRs (as discussed * in Section 5) are permitted, as are CNAME RRs whose targets can be * resolved, in turn, to MX or address RRs. Local nicknames or * unqualified names MUST NOT be used. * * This regex does not handle comments and folding whitespace. While * this is technically valid in an email address, these parts aren't * actually part of the address itself. * * Michael's regex carries this copyright: * * Copyright © Michael Rushton 2009-10 * http://squiloople.com/ * Feel free to use and redistribute this code. But please keep this copyright notice. * */ const char regexp[] = "/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}@)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD"; pcre *re = NULL; pcre_extra *pcre_extra = NULL; int preg_options = 0; int ovector[150]; /* Needs to be a multiple of 3 */ int matches; /* The maximum length of an e-mail address is 320 octets, per RFC 2821. */ if (Z_STRLEN_P(value) > 320) { RETURN_VALIDATION_FAILED } re = pcre_get_compiled_regex((char *)regexp, &pcre_extra, &preg_options TSRMLS_CC); if (!re) { RETURN_VALIDATION_FAILED } matches = pcre_exec(re, NULL, Z_STRVAL_P(value), Z_STRLEN_P(value), 0, 0, ovector, 3); /* 0 means that the vector is too small to hold all the captured substring offsets */ if (matches < 0) { RETURN_VALIDATION_FAILED } } /* }}} */ static int _php_filter_validate_ipv4(char *str, int str_len, int *ip) /* {{{ */ { const char *end = str + str_len; int num, m; int n = 0; while (str < end) { int leading_zero; if (*str < '0' || *str > '9') { return 0; } leading_zero = (*str == '0'); m = 1; num = ((*(str++)) - '0'); while (str < end && (*str >= '0' && *str <= '9')) { num = num * 10 + ((*(str++)) - '0'); if (num > 255 || ++m > 3) { return 0; } } /* don't allow a leading 0; that introduces octal numbers, * which we don't support */ if (leading_zero && (num != 0 || m > 1)) return 0; ip[n++] = num; if (n == 4) { return str == end; } else if (str >= end || *(str++) != '.') { return 0; } } return 0; } /* }}} */ static int _php_filter_validate_ipv6(char *str, int str_len TSRMLS_DC) /* {{{ */ { int compressed = 0; int blocks = 0; int n; char *ipv4; char *end; int ip4elm[4]; char *s = str; if (!memchr(str, ':', str_len)) { return 0; } /* check for bundled IPv4 */ ipv4 = memchr(str, '.', str_len); if (ipv4) { while (ipv4 > str && *(ipv4-1) != ':') { ipv4--; } if (!_php_filter_validate_ipv4(ipv4, (str_len - (ipv4 - str)), ip4elm)) { return 0; } str_len = ipv4 - str; /* length excluding ipv4 */ if (str_len < 2) { return 0; } if (ipv4[-2] != ':') { /* don't include : before ipv4 unless it's a :: */ str_len--; } blocks = 2; } end = str + str_len; while (str < end) { if (*str == ':') { if (++str >= end) { /* cannot end in : without previous : */ return 0; } if (*str == ':') { if (compressed) { return 0; } blocks++; /* :: means 1 or more 16-bit 0 blocks */ compressed = 1; if (++str == end) { return (blocks <= 8); } } else if ((str - 1) == s) { /* dont allow leading : without another : following */ return 0; } } n = 0; while ((str < end) && ((*str >= '0' && *str <= '9') || (*str >= 'a' && *str <= 'f') || (*str >= 'A' && *str <= 'F'))) { n++; str++; } if (n < 1 || n > 4) { return 0; } if (++blocks > 8) return 0; } return ((compressed && blocks <= 8) || blocks == 8); } /* }}} */ void php_filter_validate_ip(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ { /* validates an ipv4 or ipv6 IP, based on the flag (4, 6, or both) add a * flag to throw out reserved ranges; multicast ranges... etc. If both * allow_ipv4 and allow_ipv6 flags flag are used, then the first dot or * colon determine the format */ int ip[4]; int mode; if (memchr(Z_STRVAL_P(value), ':', Z_STRLEN_P(value))) { mode = FORMAT_IPV6; } else if (memchr(Z_STRVAL_P(value), '.', Z_STRLEN_P(value))) { mode = FORMAT_IPV4; } else { RETURN_VALIDATION_FAILED } if ((flags & FILTER_FLAG_IPV4) && (flags & FILTER_FLAG_IPV6)) { /* Both formats are cool */ } else if ((flags & FILTER_FLAG_IPV4) && mode == FORMAT_IPV6) { RETURN_VALIDATION_FAILED } else if ((flags & FILTER_FLAG_IPV6) && mode == FORMAT_IPV4) { RETURN_VALIDATION_FAILED } switch (mode) { case FORMAT_IPV4: if (!_php_filter_validate_ipv4(Z_STRVAL_P(value), Z_STRLEN_P(value), ip)) { RETURN_VALIDATION_FAILED } /* Check flags */ if (flags & FILTER_FLAG_NO_PRIV_RANGE) { if ( (ip[0] == 10) || (ip[0] == 172 && (ip[1] >= 16 && ip[1] <= 31)) || (ip[0] == 192 && ip[1] == 168) ) { RETURN_VALIDATION_FAILED } } if (flags & FILTER_FLAG_NO_RES_RANGE) { if ( (ip[0] == 0) || (ip[0] == 128 && ip[1] == 0) || (ip[0] == 191 && ip[1] == 255) || (ip[0] == 169 && ip[1] == 254) || (ip[0] == 192 && ip[1] == 0 && ip[2] == 2) || (ip[0] == 127 && ip[1] == 0 && ip[2] == 0 && ip[3] == 1) || (ip[0] >= 224 && ip[0] <= 255) ) { RETURN_VALIDATION_FAILED } } break; case FORMAT_IPV6: { int res = 0; res = _php_filter_validate_ipv6(Z_STRVAL_P(value), Z_STRLEN_P(value) TSRMLS_CC); if (res < 1) { RETURN_VALIDATION_FAILED } /* Check flags */ if (flags & FILTER_FLAG_NO_PRIV_RANGE) { if (Z_STRLEN_P(value) >=2 && (!strncasecmp("FC", Z_STRVAL_P(value), 2) || !strncasecmp("FD", Z_STRVAL_P(value), 2))) { RETURN_VALIDATION_FAILED } } if (flags & FILTER_FLAG_NO_RES_RANGE) { switch (Z_STRLEN_P(value)) { case 1: case 0: break; case 2: if (!strcmp("::", Z_STRVAL_P(value))) { RETURN_VALIDATION_FAILED } break; case 3: if (!strcmp("::1", Z_STRVAL_P(value)) || !strcmp("5f:", Z_STRVAL_P(value))) { RETURN_VALIDATION_FAILED } break; default: if (Z_STRLEN_P(value) >= 5) { if ( !strncasecmp("fe8", Z_STRVAL_P(value), 3) || !strncasecmp("fe9", Z_STRVAL_P(value), 3) || !strncasecmp("fea", Z_STRVAL_P(value), 3) || !strncasecmp("feb", Z_STRVAL_P(value), 3) ) { RETURN_VALIDATION_FAILED } } if ( (Z_STRLEN_P(value) >= 9 && !strncasecmp("2001:0db8", Z_STRVAL_P(value), 9)) || (Z_STRLEN_P(value) >= 2 && !strncasecmp("5f", Z_STRVAL_P(value), 2)) || (Z_STRLEN_P(value) >= 4 && !strncasecmp("3ff3", Z_STRVAL_P(value), 4)) || (Z_STRLEN_P(value) >= 8 && !strncasecmp("2001:001", Z_STRVAL_P(value), 8)) ) { RETURN_VALIDATION_FAILED } } } } break; } } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-12-04-1e6a82a1cf-dfa08dc325.c
manybugs_data_83
/* select - Module containing unix select(2) call. Under Unix, the file descriptors are small integers. Under Win32, select only exists for sockets, and sockets may have any value except INVALID_SOCKET. */ #include "Python.h" #include <structmember.h> #ifdef __APPLE__ /* Perform runtime testing for a broken poll on OSX to make it easier * to use the same binary on multiple releases of the OS. */ #undef HAVE_BROKEN_POLL #endif /* Windows #defines FD_SETSIZE to 64 if FD_SETSIZE isn't already defined. 64 is too small (too many people have bumped into that limit). Here we boost it. Users who want even more than the boosted limit should #define FD_SETSIZE higher before this; e.g., via compiler /D switch. */ #if defined(MS_WINDOWS) && !defined(FD_SETSIZE) #define FD_SETSIZE 512 #endif #if defined(HAVE_POLL_H) #include <poll.h> #elif defined(HAVE_SYS_POLL_H) #include <sys/poll.h> #endif #ifdef __sgi /* This is missing from unistd.h */ extern void bzero(void *, int); #endif #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #if defined(PYOS_OS2) && !defined(PYCC_GCC) #include <sys/time.h> #include <utils.h> #endif #ifdef MS_WINDOWS # define WIN32_LEAN_AND_MEAN # include <winsock.h> #else # define SOCKET int # if defined(__VMS) # include <socket.h> # endif #endif static PyObject *SelectError; /* list of Python objects and their file descriptor */ typedef struct { PyObject *obj; /* owned reference */ SOCKET fd; int sentinel; /* -1 == sentinel */ } pylist; static void reap_obj(pylist fd2obj[FD_SETSIZE + 1]) { int i; for (i = 0; i < FD_SETSIZE + 1 && fd2obj[i].sentinel >= 0; i++) { Py_XDECREF(fd2obj[i].obj); fd2obj[i].obj = NULL; } fd2obj[0].sentinel = -1; } /* returns -1 and sets the Python exception if an error occurred, otherwise returns a number >= 0 */ static int seq2set(PyObject *seq, fd_set *set, pylist fd2obj[FD_SETSIZE + 1]) { int max = -1; int index = 0; Py_ssize_t i, len = -1; PyObject* fast_seq = NULL; PyObject* o = NULL; fd2obj[0].obj = (PyObject*)0; /* set list to zero size */ FD_ZERO(set); fast_seq = PySequence_Fast(seq, "arguments 1-3 must be sequences"); if (!fast_seq) return -1; len = PySequence_Fast_GET_SIZE(fast_seq); for (i = 0; i < len; i++) { SOCKET v; /* any intervening fileno() calls could decr this refcnt */ if (!(o = PySequence_Fast_GET_ITEM(fast_seq, i))) return -1; Py_INCREF(o); v = PyObject_AsFileDescriptor( o ); if (v == -1) goto finally; #if defined(_MSC_VER) max = 0; /* not used for Win32 */ #else /* !_MSC_VER */ if (v < 0 || v >= FD_SETSIZE) { PyErr_SetString(PyExc_ValueError, "filedescriptor out of range in select()"); goto finally; } if (v > max) max = v; #endif /* _MSC_VER */ FD_SET(v, set); /* add object and its file descriptor to the list */ if (index >= FD_SETSIZE) { PyErr_SetString(PyExc_ValueError, "too many file descriptors in select()"); goto finally; } fd2obj[index].obj = o; fd2obj[index].fd = v; fd2obj[index].sentinel = 0; fd2obj[++index].sentinel = -1; } Py_DECREF(fast_seq); return max+1; finally: Py_XDECREF(o); Py_DECREF(fast_seq); return -1; } /* returns NULL and sets the Python exception if an error occurred */ static PyObject * set2list(fd_set *set, pylist fd2obj[FD_SETSIZE + 1]) { int i, j, count=0; PyObject *list, *o; SOCKET fd; for (j = 0; fd2obj[j].sentinel >= 0; j++) { if (FD_ISSET(fd2obj[j].fd, set)) count++; } list = PyList_New(count); if (!list) return NULL; i = 0; for (j = 0; fd2obj[j].sentinel >= 0; j++) { fd = fd2obj[j].fd; if (FD_ISSET(fd, set)) { #ifndef _MSC_VER if (fd > FD_SETSIZE) { PyErr_SetString(PyExc_SystemError, "filedescriptor out of range returned in select()"); goto finally; } #endif o = fd2obj[j].obj; fd2obj[j].obj = NULL; /* transfer ownership */ if (PyList_SetItem(list, i, o) < 0) goto finally; i++; } } return list; finally: Py_DECREF(list); return NULL; } #undef SELECT_USES_HEAP #if FD_SETSIZE > 1024 #define SELECT_USES_HEAP #endif /* FD_SETSIZE > 1024 */ static PyObject * select_select(PyObject *self, PyObject *args) { #ifdef SELECT_USES_HEAP pylist *rfd2obj, *wfd2obj, *efd2obj; #else /* !SELECT_USES_HEAP */ /* XXX: All this should probably be implemented as follows: * - find the highest descriptor we're interested in * - add one * - that's the size * See: Stevens, APitUE, $12.5.1 */ pylist rfd2obj[FD_SETSIZE + 1]; pylist wfd2obj[FD_SETSIZE + 1]; pylist efd2obj[FD_SETSIZE + 1]; #endif /* SELECT_USES_HEAP */ PyObject *ifdlist, *ofdlist, *efdlist; PyObject *ret = NULL; PyObject *tout = Py_None; fd_set ifdset, ofdset, efdset; double timeout; struct timeval tv, *tvp; long seconds; int imax, omax, emax, max; int n; /* convert arguments */ if (!PyArg_UnpackTuple(args, "select", 3, 4, &ifdlist, &ofdlist, &efdlist, &tout)) return NULL; if (tout == Py_None) tvp = (struct timeval *)0; else if (!PyNumber_Check(tout)) { PyErr_SetString(PyExc_TypeError, "timeout must be a float or None"); return NULL; } else { timeout = PyFloat_AsDouble(tout); if (timeout == -1 && PyErr_Occurred()) return NULL; if (timeout > (double)LONG_MAX) { PyErr_SetString(PyExc_OverflowError, "timeout period too long"); return NULL; } seconds = (long)timeout; timeout = timeout - (double)seconds; tv.tv_sec = seconds; tv.tv_usec = (long)(timeout * 1E6); tvp = &tv; } #ifdef SELECT_USES_HEAP /* Allocate memory for the lists */ rfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1); wfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1); efd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1); if (rfd2obj == NULL || wfd2obj == NULL || efd2obj == NULL) { if (rfd2obj) PyMem_DEL(rfd2obj); if (wfd2obj) PyMem_DEL(wfd2obj); if (efd2obj) PyMem_DEL(efd2obj); return PyErr_NoMemory(); } #endif /* SELECT_USES_HEAP */ /* Convert sequences to fd_sets, and get maximum fd number * propagates the Python exception set in seq2set() */ rfd2obj[0].sentinel = -1; wfd2obj[0].sentinel = -1; efd2obj[0].sentinel = -1; if ((imax=seq2set(ifdlist, &ifdset, rfd2obj)) < 0) goto finally; if ((omax=seq2set(ofdlist, &ofdset, wfd2obj)) < 0) goto finally; if ((emax=seq2set(efdlist, &efdset, efd2obj)) < 0) goto finally; max = imax; if (omax > max) max = omax; if (emax > max) max = emax; Py_BEGIN_ALLOW_THREADS n = select(max, &ifdset, &ofdset, &efdset, tvp); Py_END_ALLOW_THREADS #ifdef MS_WINDOWS if (n == SOCKET_ERROR) { PyErr_SetExcFromWindowsErr(SelectError, WSAGetLastError()); } #else if (n < 0) { PyErr_SetFromErrno(SelectError); } #endif else { /* any of these three calls can raise an exception. it's more convenient to test for this after all three calls... but is that acceptable? */ ifdlist = set2list(&ifdset, rfd2obj); ofdlist = set2list(&ofdset, wfd2obj); efdlist = set2list(&efdset, efd2obj); if (PyErr_Occurred()) ret = NULL; else ret = PyTuple_Pack(3, ifdlist, ofdlist, efdlist); Py_DECREF(ifdlist); Py_DECREF(ofdlist); Py_DECREF(efdlist); } finally: reap_obj(rfd2obj); reap_obj(wfd2obj); reap_obj(efd2obj); #ifdef SELECT_USES_HEAP PyMem_DEL(rfd2obj); PyMem_DEL(wfd2obj); PyMem_DEL(efd2obj); #endif /* SELECT_USES_HEAP */ return ret; } #if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL) /* * poll() support */ typedef struct { PyObject_HEAD PyObject *dict; int ufd_uptodate; int ufd_len; struct pollfd *ufds; } pollObject; static PyTypeObject poll_Type; /* Update the malloc'ed array of pollfds to match the dictionary contained within a pollObject. Return 1 on success, 0 on an error. */ static int update_ufd_array(pollObject *self) { Py_ssize_t i, pos; PyObject *key, *value; struct pollfd *old_ufds = self->ufds; self->ufd_len = PyDict_Size(self->dict); PyMem_RESIZE(self->ufds, struct pollfd, self->ufd_len); if (self->ufds == NULL) { self->ufds = old_ufds; PyErr_NoMemory(); return 0; } i = pos = 0; while (PyDict_Next(self->dict, &pos, &key, &value)) { self->ufds[i].fd = PyLong_AsLong(key); self->ufds[i].events = (short)PyLong_AsLong(value); i++; } self->ufd_uptodate = 1; return 1; } PyDoc_STRVAR(poll_register_doc, "register(fd [, eventmask] ) -> None\n\n\ Register a file descriptor with the polling object.\n\ fd -- either an integer, or an object with a fileno() method returning an\n\ int.\n\ events -- an optional bitmask describing the type of events to check for"); static PyObject * poll_register(pollObject *self, PyObject *args) { PyObject *o, *key, *value; int fd, events = POLLIN | POLLPRI | POLLOUT; int err; if (!PyArg_ParseTuple(args, "O|i:register", &o, &events)) { return NULL; } fd = PyObject_AsFileDescriptor(o); if (fd == -1) return NULL; /* Add entry to the internal dictionary: the key is the file descriptor, and the value is the event mask. */ key = PyLong_FromLong(fd); if (key == NULL) return NULL; value = PyLong_FromLong(events); if (value == NULL) { Py_DECREF(key); return NULL; } err = PyDict_SetItem(self->dict, key, value); Py_DECREF(key); Py_DECREF(value); if (err < 0) return NULL; self->ufd_uptodate = 0; Py_INCREF(Py_None); return Py_None; } PyDoc_STRVAR(poll_modify_doc, "modify(fd, eventmask) -> None\n\n\ Modify an already registered file descriptor.\n\ fd -- either an integer, or an object with a fileno() method returning an\n\ int.\n\ events -- an optional bitmask describing the type of events to check for"); static PyObject * poll_modify(pollObject *self, PyObject *args) { PyObject *o, *key, *value; int fd, events; int err; if (!PyArg_ParseTuple(args, "Oi:modify", &o, &events)) { return NULL; } fd = PyObject_AsFileDescriptor(o); if (fd == -1) return NULL; /* Modify registered fd */ key = PyLong_FromLong(fd); if (key == NULL) return NULL; if (PyDict_GetItem(self->dict, key) == NULL) { errno = ENOENT; PyErr_SetFromErrno(PyExc_IOError); return NULL; } value = PyLong_FromLong(events); if (value == NULL) { Py_DECREF(key); return NULL; } err = PyDict_SetItem(self->dict, key, value); Py_DECREF(key); Py_DECREF(value); if (err < 0) return NULL; self->ufd_uptodate = 0; Py_INCREF(Py_None); return Py_None; } PyDoc_STRVAR(poll_unregister_doc, "unregister(fd) -> None\n\n\ Remove a file descriptor being tracked by the polling object."); static PyObject * poll_unregister(pollObject *self, PyObject *o) { PyObject *key; int fd; fd = PyObject_AsFileDescriptor( o ); if (fd == -1) return NULL; /* Check whether the fd is already in the array */ key = PyLong_FromLong(fd); if (key == NULL) return NULL; if (PyDict_DelItem(self->dict, key) == -1) { Py_DECREF(key); /* This will simply raise the KeyError set by PyDict_DelItem if the file descriptor isn't registered. */ return NULL; } Py_DECREF(key); self->ufd_uptodate = 0; Py_INCREF(Py_None); return Py_None; } PyDoc_STRVAR(poll_poll_doc, "poll( [timeout] ) -> list of (fd, event) 2-tuples\n\n\ Polls the set of registered file descriptors, returning a list containing \n\ any descriptors that have events or errors to report."); static PyObject * poll_poll(pollObject *self, PyObject *args) { PyObject *result_list = NULL, *tout = NULL; int timeout = 0, poll_result, i, j; PyObject *value = NULL, *num = NULL; if (!PyArg_UnpackTuple(args, "poll", 0, 1, &tout)) { return NULL; } /* Check values for timeout */ if (tout == NULL || tout == Py_None) timeout = -1; else if (!PyNumber_Check(tout)) { PyErr_SetString(PyExc_TypeError, "timeout must be an integer or None"); return NULL; } else { tout = PyNumber_Long(tout); if (!tout) return NULL; timeout = PyLong_AsLong(tout); Py_DECREF(tout); if (timeout == -1 && PyErr_Occurred()) return NULL; } /* Ensure the ufd array is up to date */ if (!self->ufd_uptodate) if (update_ufd_array(self) == 0) return NULL; /* call poll() */ Py_BEGIN_ALLOW_THREADS poll_result = poll(self->ufds, self->ufd_len, timeout); Py_END_ALLOW_THREADS if (poll_result < 0) { PyErr_SetFromErrno(SelectError); return NULL; } /* build the result list */ result_list = PyList_New(poll_result); if (!result_list) return NULL; else { for (i = 0, j = 0; j < poll_result; j++) { /* skip to the next fired descriptor */ while (!self->ufds[i].revents) { i++; } /* if we hit a NULL return, set value to NULL and break out of loop; code at end will clean up result_list */ value = PyTuple_New(2); if (value == NULL) goto error; num = PyLong_FromLong(self->ufds[i].fd); if (num == NULL) { Py_DECREF(value); goto error; } PyTuple_SET_ITEM(value, 0, num); /* The &0xffff is a workaround for AIX. 'revents' is a 16-bit short, and IBM assigned POLLNVAL to be 0x8000, so the conversion to int results in a negative number. See SF bug #923315. */ num = PyLong_FromLong(self->ufds[i].revents & 0xffff); if (num == NULL) { Py_DECREF(value); goto error; } PyTuple_SET_ITEM(value, 1, num); if ((PyList_SetItem(result_list, j, value)) == -1) { Py_DECREF(value); goto error; } i++; } } return result_list; error: Py_DECREF(result_list); return NULL; } static PyMethodDef poll_methods[] = { {"register", (PyCFunction)poll_register, METH_VARARGS, poll_register_doc}, {"modify", (PyCFunction)poll_modify, METH_VARARGS, poll_modify_doc}, {"unregister", (PyCFunction)poll_unregister, METH_O, poll_unregister_doc}, {"poll", (PyCFunction)poll_poll, METH_VARARGS, poll_poll_doc}, {NULL, NULL} /* sentinel */ }; static pollObject * newPollObject(void) { pollObject *self; self = PyObject_New(pollObject, &poll_Type); if (self == NULL) return NULL; /* ufd_uptodate is a Boolean, denoting whether the array pointed to by ufds matches the contents of the dictionary. */ self->ufd_uptodate = 0; self->ufds = NULL; self->dict = PyDict_New(); if (self->dict == NULL) { Py_DECREF(self); return NULL; } return self; } static void poll_dealloc(pollObject *self) { if (self->ufds != NULL) PyMem_DEL(self->ufds); Py_XDECREF(self->dict); PyObject_Del(self); } static PyTypeObject poll_Type = { /* The ob_type field must be initialized in the module init function * to be portable to Windows without using C++. */ PyVarObject_HEAD_INIT(NULL, 0) "select.poll", /*tp_name*/ sizeof(pollObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ /* methods */ (destructor)poll_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ poll_methods, /*tp_methods*/ }; PyDoc_STRVAR(poll_doc, "Returns a polling object, which supports registering and\n\ unregistering file descriptors, and then polling them for I/O events."); static PyObject * select_poll(PyObject *self, PyObject *unused) { return (PyObject *)newPollObject(); } #ifdef __APPLE__ /* * On some systems poll() sets errno on invalid file descriptors. We test * for this at runtime because this bug may be fixed or introduced between * OS releases. */ static int select_have_broken_poll(void) { int poll_test; int filedes[2]; struct pollfd poll_struct = { 0, POLLIN|POLLPRI|POLLOUT, 0 }; /* Create a file descriptor to make invalid */ if (pipe(filedes) < 0) { return 1; } poll_struct.fd = filedes[0]; close(filedes[0]); close(filedes[1]); poll_test = poll(&poll_struct, 1, 0); if (poll_test < 0) { return 1; } else if (poll_test == 0 && poll_struct.revents != POLLNVAL) { return 1; } return 0; } #endif /* __APPLE__ */ #endif /* HAVE_POLL */ #ifdef HAVE_EPOLL /* ************************************************************************** * epoll interface for Linux 2.6 * * Written by Christian Heimes * Inspired by Twisted's _epoll.pyx and select.poll() */ #ifdef HAVE_SYS_EPOLL_H #include <sys/epoll.h> #endif typedef struct { PyObject_HEAD SOCKET epfd; /* epoll control file descriptor */ } pyEpoll_Object; static PyTypeObject pyEpoll_Type; #define pyepoll_CHECK(op) (PyObject_TypeCheck((op), &pyEpoll_Type)) static PyObject * pyepoll_err_closed(void) { PyErr_SetString(PyExc_ValueError, "I/O operation on closed epoll fd"); return NULL; } static int pyepoll_internal_close(pyEpoll_Object *self) { int save_errno = 0; if (self->epfd >= 0) { int epfd = self->epfd; self->epfd = -1; Py_BEGIN_ALLOW_THREADS if (close(epfd) < 0) save_errno = errno; Py_END_ALLOW_THREADS } return save_errno; } static PyObject * newPyEpoll_Object(PyTypeObject *type, int sizehint, SOCKET fd) { pyEpoll_Object *self; if (sizehint == -1) { sizehint = FD_SETSIZE-1; } else if (sizehint < 1) { PyErr_Format(PyExc_ValueError, "sizehint must be greater zero, got %d", sizehint); return NULL; } assert(type != NULL && type->tp_alloc != NULL); self = (pyEpoll_Object *) type->tp_alloc(type, 0); if (self == NULL) return NULL; if (fd == -1) { Py_BEGIN_ALLOW_THREADS self->epfd = epoll_create(sizehint); Py_END_ALLOW_THREADS } else { self->epfd = fd; } if (self->epfd < 0) { Py_DECREF(self); PyErr_SetFromErrno(PyExc_IOError); return NULL; } return (PyObject *)self; } static PyObject * pyepoll_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { int sizehint = -1; static char *kwlist[] = {"sizehint", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:epoll", kwlist, &sizehint)) return NULL; return newPyEpoll_Object(type, sizehint, -1); } static void pyepoll_dealloc(pyEpoll_Object *self) { (void)pyepoll_internal_close(self); Py_TYPE(self)->tp_free(self); } static PyObject* pyepoll_close(pyEpoll_Object *self) { errno = pyepoll_internal_close(self); if (errno < 0) { PyErr_SetFromErrno(PyExc_IOError); return NULL; } Py_RETURN_NONE; } PyDoc_STRVAR(pyepoll_close_doc, "close() -> None\n\ \n\ Close the epoll control file descriptor. Further operations on the epoll\n\ object will raise an exception."); static PyObject* pyepoll_get_closed(pyEpoll_Object *self) { if (self->epfd < 0) Py_RETURN_TRUE; else Py_RETURN_FALSE; } static PyObject* pyepoll_fileno(pyEpoll_Object *self) { if (self->epfd < 0) return pyepoll_err_closed(); return PyLong_FromLong(self->epfd); } PyDoc_STRVAR(pyepoll_fileno_doc, "fileno() -> int\n\ \n\ Return the epoll control file descriptor."); static PyObject* pyepoll_fromfd(PyObject *cls, PyObject *args) { SOCKET fd; if (!PyArg_ParseTuple(args, "i:fromfd", &fd)) return NULL; return newPyEpoll_Object((PyTypeObject*)cls, -1, fd); } PyDoc_STRVAR(pyepoll_fromfd_doc, "fromfd(fd) -> epoll\n\ \n\ Create an epoll object from a given control fd."); static PyObject * pyepoll_internal_ctl(int epfd, int op, PyObject *pfd, unsigned int events) { struct epoll_event ev; int result; int fd; if (epfd < 0) return pyepoll_err_closed(); fd = PyObject_AsFileDescriptor(pfd); if (fd == -1) { return NULL; } switch(op) { case EPOLL_CTL_ADD: case EPOLL_CTL_MOD: ev.events = events; ev.data.fd = fd; Py_BEGIN_ALLOW_THREADS result = epoll_ctl(epfd, op, fd, &ev); Py_END_ALLOW_THREADS break; case EPOLL_CTL_DEL: /* In kernel versions before 2.6.9, the EPOLL_CTL_DEL * operation required a non-NULL pointer in event, even * though this argument is ignored. */ Py_BEGIN_ALLOW_THREADS result = epoll_ctl(epfd, op, fd, &ev); if (errno == EBADF) { /* fd already closed */ result = 0; errno = 0; } Py_END_ALLOW_THREADS break; default: result = -1; errno = EINVAL; } if (result < 0) { PyErr_SetFromErrno(PyExc_IOError); return NULL; } Py_RETURN_NONE; } static PyObject * pyepoll_register(pyEpoll_Object *self, PyObject *args, PyObject *kwds) { PyObject *pfd; unsigned int events = EPOLLIN | EPOLLOUT | EPOLLPRI; static char *kwlist[] = {"fd", "eventmask", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|I:register", kwlist, &pfd, &events)) { return NULL; } return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_ADD, pfd, events); } PyDoc_STRVAR(pyepoll_register_doc, "register(fd[, eventmask]) -> None\n\ \n\ Registers a new fd or modifies an already registered fd.\n\ fd is the target file descriptor of the operation.\n\ events is a bit set composed of the various EPOLL constants; the default\n\ is EPOLL_IN | EPOLL_OUT | EPOLL_PRI.\n\ \n\ The epoll interface supports all file descriptors that support poll."); static PyObject * pyepoll_modify(pyEpoll_Object *self, PyObject *args, PyObject *kwds) { PyObject *pfd; unsigned int events; static char *kwlist[] = {"fd", "eventmask", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OI:modify", kwlist, &pfd, &events)) { return NULL; } return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_MOD, pfd, events); } PyDoc_STRVAR(pyepoll_modify_doc, "modify(fd, eventmask) -> None\n\ \n\ fd is the target file descriptor of the operation\n\ events is a bit set composed of the various EPOLL constants"); static PyObject * pyepoll_unregister(pyEpoll_Object *self, PyObject *args, PyObject *kwds) { PyObject *pfd; static char *kwlist[] = {"fd", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:unregister", kwlist, &pfd)) { return NULL; } return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_DEL, pfd, 0); } PyDoc_STRVAR(pyepoll_unregister_doc, "unregister(fd) -> None\n\ \n\ fd is the target file descriptor of the operation."); static PyObject * pyepoll_poll(pyEpoll_Object *self, PyObject *args, PyObject *kwds) { double dtimeout = -1.; int timeout; int maxevents = -1; int nfds, i; PyObject *elist = NULL, *etuple = NULL; struct epoll_event *evs = NULL; static char *kwlist[] = {"timeout", "maxevents", NULL}; if (self->epfd < 0) return pyepoll_err_closed(); if (!PyArg_ParseTupleAndKeywords(args, kwds, "|di:poll", kwlist, &dtimeout, &maxevents)) { return NULL; } if (dtimeout < 0) { timeout = -1; } else if (dtimeout * 1000.0 > INT_MAX) { PyErr_SetString(PyExc_OverflowError, "timeout is too large"); return NULL; } else { timeout = (int)(dtimeout * 1000.0); } if (maxevents == -1) { maxevents = FD_SETSIZE-1; } else if (maxevents < 1) { PyErr_Format(PyExc_ValueError, "maxevents must be greater than 0, got %d", maxevents); return NULL; } evs = PyMem_New(struct epoll_event, maxevents); if (evs == NULL) { Py_DECREF(self); PyErr_NoMemory(); return NULL; } Py_BEGIN_ALLOW_THREADS nfds = epoll_wait(self->epfd, evs, maxevents, timeout); Py_END_ALLOW_THREADS if (nfds < 0) { PyErr_SetFromErrno(PyExc_IOError); goto error; } elist = PyList_New(nfds); if (elist == NULL) { goto error; } for (i = 0; i < nfds; i++) { etuple = Py_BuildValue("iI", evs[i].data.fd, evs[i].events); if (etuple == NULL) { Py_CLEAR(elist); goto error; } PyList_SET_ITEM(elist, i, etuple); } error: PyMem_Free(evs); return elist; } PyDoc_STRVAR(pyepoll_poll_doc, "poll([timeout=-1[, maxevents=-1]]) -> [(fd, events), (...)]\n\ \n\ Wait for events on the epoll file descriptor for a maximum time of timeout\n\ in seconds (as float). -1 makes poll wait indefinitely.\n\ Up to maxevents are returned to the caller."); static PyMethodDef pyepoll_methods[] = { {"fromfd", (PyCFunction)pyepoll_fromfd, METH_VARARGS | METH_CLASS, pyepoll_fromfd_doc}, {"close", (PyCFunction)pyepoll_close, METH_NOARGS, pyepoll_close_doc}, {"fileno", (PyCFunction)pyepoll_fileno, METH_NOARGS, pyepoll_fileno_doc}, {"modify", (PyCFunction)pyepoll_modify, METH_VARARGS | METH_KEYWORDS, pyepoll_modify_doc}, {"register", (PyCFunction)pyepoll_register, METH_VARARGS | METH_KEYWORDS, pyepoll_register_doc}, {"unregister", (PyCFunction)pyepoll_unregister, METH_VARARGS | METH_KEYWORDS, pyepoll_unregister_doc}, {"poll", (PyCFunction)pyepoll_poll, METH_VARARGS | METH_KEYWORDS, pyepoll_poll_doc}, {NULL, NULL}, }; static PyGetSetDef pyepoll_getsetlist[] = { {"closed", (getter)pyepoll_get_closed, NULL, "True if the epoll handler is closed"}, {0}, }; PyDoc_STRVAR(pyepoll_doc, "select.epoll([sizehint=-1])\n\ \n\ Returns an epolling object\n\ \n\ sizehint must be a positive integer or -1 for the default size. The\n\ sizehint is used to optimize internal data structures. It doesn't limit\n\ the maximum number of monitored events."); static PyTypeObject pyEpoll_Type = { PyVarObject_HEAD_INIT(NULL, 0) "select.epoll", /* tp_name */ sizeof(pyEpoll_Object), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)pyepoll_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ pyepoll_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ pyepoll_methods, /* tp_methods */ 0, /* tp_members */ pyepoll_getsetlist, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ pyepoll_new, /* tp_new */ 0, /* tp_free */ }; #endif /* HAVE_EPOLL */ #ifdef HAVE_KQUEUE /* ************************************************************************** * kqueue interface for BSD * * Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifdef HAVE_SYS_EVENT_H #include <sys/event.h> #endif PyDoc_STRVAR(kqueue_event_doc, "kevent(ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD, fflags=0, data=0, udata=0)\n\ \n\ This object is the equivalent of the struct kevent for the C API.\n\ \n\ See the kqueue manpage for more detailed information about the meaning\n\ of the arguments.\n\ \n\ One minor note: while you might hope that udata could store a\n\ reference to a python object, it cannot, because it is impossible to\n\ keep a proper reference count of the object once it's passed into the\n\ kernel. Therefore, I have restricted it to only storing an integer. I\n\ recommend ignoring it and simply using the 'ident' field to key off\n\ of. You could also set up a dictionary on the python side to store a\n\ udata->object mapping."); typedef struct { PyObject_HEAD struct kevent e; } kqueue_event_Object; static PyTypeObject kqueue_event_Type; #define kqueue_event_Check(op) (PyObject_TypeCheck((op), &kqueue_event_Type)) typedef struct { PyObject_HEAD SOCKET kqfd; /* kqueue control fd */ } kqueue_queue_Object; static PyTypeObject kqueue_queue_Type; #define kqueue_queue_Check(op) (PyObject_TypeCheck((op), &kqueue_queue_Type)) #if (SIZEOF_UINTPTR_T != SIZEOF_VOID_P) # error uintptr_t does not match void *! #elif (SIZEOF_UINTPTR_T == SIZEOF_LONG_LONG) # define T_UINTPTRT T_ULONGLONG # define T_INTPTRT T_LONGLONG # define PyLong_AsUintptr_t PyLong_AsUnsignedLongLong # define UINTPTRT_FMT_UNIT "K" # define INTPTRT_FMT_UNIT "L" #elif (SIZEOF_UINTPTR_T == SIZEOF_LONG) # define T_UINTPTRT T_ULONG # define T_INTPTRT T_LONG # define PyLong_AsUintptr_t PyLong_AsUnsignedLong # define UINTPTRT_FMT_UNIT "k" # define INTPTRT_FMT_UNIT "l" #elif (SIZEOF_UINTPTR_T == SIZEOF_INT) # define T_UINTPTRT T_UINT # define T_INTPTRT T_INT # define PyLong_AsUintptr_t PyLong_AsUnsignedLong # define UINTPTRT_FMT_UNIT "I" # define INTPTRT_FMT_UNIT "i" #else # error uintptr_t does not match int, long, or long long! #endif /* Unfortunately, we can't store python objects in udata, because * kevents in the kernel can be removed without warning, which would * forever lose the refcount on the object stored with it. */ #define KQ_OFF(x) offsetof(kqueue_event_Object, x) static struct PyMemberDef kqueue_event_members[] = { {"ident", T_UINTPTRT, KQ_OFF(e.ident)}, {"filter", T_SHORT, KQ_OFF(e.filter)}, {"flags", T_USHORT, KQ_OFF(e.flags)}, {"fflags", T_UINT, KQ_OFF(e.fflags)}, {"data", T_INTPTRT, KQ_OFF(e.data)}, {"udata", T_UINTPTRT, KQ_OFF(e.udata)}, {NULL} /* Sentinel */ }; #undef KQ_OFF static PyObject * kqueue_event_repr(kqueue_event_Object *s) { char buf[1024]; PyOS_snprintf( buf, sizeof(buf), "<select.kevent ident=%zu filter=%d flags=0x%x fflags=0x%x " "data=0x%zd udata=%p>", (size_t)(s->e.ident), s->e.filter, s->e.flags, s->e.fflags, (Py_ssize_t)(s->e.data), s->e.udata); return PyUnicode_FromString(buf); } static int kqueue_event_init(kqueue_event_Object *self, PyObject *args, PyObject *kwds) { PyObject *pfd; static char *kwlist[] = {"ident", "filter", "flags", "fflags", "data", "udata", NULL}; static char *fmt = "O|hhi" INTPTRT_FMT_UNIT UINTPTRT_FMT_UNIT ":kevent"; EV_SET(&(self->e), 0, EVFILT_READ, EV_ADD, 0, 0, 0); /* defaults */ if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist, &pfd, &(self->e.filter), &(self->e.flags), &(self->e.fflags), &(self->e.data), &(self->e.udata))) { return -1; } if (PyLong_Check(pfd)) { self->e.ident = PyLong_AsUintptr_t(pfd); } else { self->e.ident = PyObject_AsFileDescriptor(pfd); } if (PyErr_Occurred()) { return -1; } return 0; } static PyObject * kqueue_event_richcompare(kqueue_event_Object *s, kqueue_event_Object *o, int op) { Py_intptr_t result = 0; if (!kqueue_event_Check(o)) { if (op == Py_EQ || op == Py_NE) { PyObject *res = op == Py_EQ ? Py_False : Py_True; Py_INCREF(res); return res; } PyErr_Format(PyExc_TypeError, "can't compare %.200s to %.200s", Py_TYPE(s)->tp_name, Py_TYPE(o)->tp_name); return NULL; } if (((result = s->e.ident - o->e.ident) == 0) && ((result = s->e.filter - o->e.filter) == 0) && ((result = s->e.flags - o->e.flags) == 0) && ((result = s->e.fflags - o->e.fflags) == 0) && ((result = s->e.data - o->e.data) == 0) && ((result = s->e.udata - o->e.udata) == 0) ) { result = 0; } switch (op) { case Py_EQ: result = (result == 0); break; case Py_NE: result = (result != 0); break; case Py_LE: result = (result <= 0); break; case Py_GE: result = (result >= 0); break; case Py_LT: result = (result < 0); break; case Py_GT: result = (result > 0); break; } return PyBool_FromLong((long)result); } static PyTypeObject kqueue_event_Type = { PyVarObject_HEAD_INIT(NULL, 0) "select.kevent", /* tp_name */ sizeof(kqueue_event_Object), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)kqueue_event_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ kqueue_event_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ (richcmpfunc)kqueue_event_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ kqueue_event_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)kqueue_event_init, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ }; static PyObject * kqueue_queue_err_closed(void) { PyErr_SetString(PyExc_ValueError, "I/O operation on closed kqueue fd"); return NULL; } static int kqueue_queue_internal_close(kqueue_queue_Object *self) { int save_errno = 0; if (self->kqfd >= 0) { int kqfd = self->kqfd; self->kqfd = -1; Py_BEGIN_ALLOW_THREADS if (close(kqfd) < 0) save_errno = errno; Py_END_ALLOW_THREADS } return save_errno; } static PyObject * newKqueue_Object(PyTypeObject *type, SOCKET fd) { kqueue_queue_Object *self; assert(type != NULL && type->tp_alloc != NULL); self = (kqueue_queue_Object *) type->tp_alloc(type, 0); if (self == NULL) { return NULL; } if (fd == -1) { Py_BEGIN_ALLOW_THREADS self->kqfd = kqueue(); Py_END_ALLOW_THREADS } else { self->kqfd = fd; } if (self->kqfd < 0) { Py_DECREF(self); PyErr_SetFromErrno(PyExc_IOError); return NULL; } return (PyObject *)self; } static PyObject * kqueue_queue_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { if ((args != NULL && PyObject_Size(args)) || (kwds != NULL && PyObject_Size(kwds))) { PyErr_SetString(PyExc_ValueError, "select.kqueue doesn't accept arguments"); return NULL; } return newKqueue_Object(type, -1); } static void kqueue_queue_dealloc(kqueue_queue_Object *self) { kqueue_queue_internal_close(self); Py_TYPE(self)->tp_free(self); } static PyObject* kqueue_queue_close(kqueue_queue_Object *self) { errno = kqueue_queue_internal_close(self); if (errno < 0) { PyErr_SetFromErrno(PyExc_IOError); return NULL; } Py_RETURN_NONE; } PyDoc_STRVAR(kqueue_queue_close_doc, "close() -> None\n\ \n\ Close the kqueue control file descriptor. Further operations on the kqueue\n\ object will raise an exception."); static PyObject* kqueue_queue_get_closed(kqueue_queue_Object *self) { if (self->kqfd < 0) Py_RETURN_TRUE; else Py_RETURN_FALSE; } static PyObject* kqueue_queue_fileno(kqueue_queue_Object *self) { if (self->kqfd < 0) return kqueue_queue_err_closed(); return PyLong_FromLong(self->kqfd); } PyDoc_STRVAR(kqueue_queue_fileno_doc, "fileno() -> int\n\ \n\ Return the kqueue control file descriptor."); static PyObject* kqueue_queue_fromfd(PyObject *cls, PyObject *args) { SOCKET fd; if (!PyArg_ParseTuple(args, "i:fromfd", &fd)) return NULL; return newKqueue_Object((PyTypeObject*)cls, fd); } PyDoc_STRVAR(kqueue_queue_fromfd_doc, "fromfd(fd) -> kqueue\n\ \n\ Create a kqueue object from a given control fd."); static PyObject * kqueue_queue_control(kqueue_queue_Object *self, PyObject *args) { int nevents = 0; int gotevents = 0; int nchanges = 0; int i = 0; PyObject *otimeout = NULL; PyObject *ch = NULL; PyObject *it = NULL, *ei = NULL; PyObject *result = NULL; struct kevent *evl = NULL; struct kevent *chl = NULL; struct timespec timeoutspec; struct timespec *ptimeoutspec; if (self->kqfd < 0) return kqueue_queue_err_closed(); if (!PyArg_ParseTuple(args, "Oi|O:control", &ch, &nevents, &otimeout)) return NULL; if (nevents < 0) { PyErr_Format(PyExc_ValueError, "Length of eventlist must be 0 or positive, got %d", nevents); return NULL; } if (otimeout == Py_None || otimeout == NULL) { ptimeoutspec = NULL; } else if (PyNumber_Check(otimeout)) { double timeout; long seconds; timeout = PyFloat_AsDouble(otimeout); if (timeout == -1 && PyErr_Occurred()) return NULL; if (timeout > (double)LONG_MAX) { PyErr_SetString(PyExc_OverflowError, "timeout period too long"); return NULL; } if (timeout < 0) { PyErr_SetString(PyExc_ValueError, "timeout must be positive or None"); return NULL; } seconds = (long)timeout; timeout = timeout - (double)seconds; timeoutspec.tv_sec = seconds; timeoutspec.tv_nsec = (long)(timeout * 1E9); ptimeoutspec = &timeoutspec; } else { PyErr_Format(PyExc_TypeError, "timeout argument must be an number " "or None, got %.200s", Py_TYPE(otimeout)->tp_name); return NULL; } if (ch != NULL && ch != Py_None) { it = PyObject_GetIter(ch); if (it == NULL) { PyErr_SetString(PyExc_TypeError, "changelist is not iterable"); return NULL; } nchanges = PyObject_Size(ch); if (nchanges < 0) { goto error; } chl = PyMem_New(struct kevent, nchanges); if (chl == NULL) { PyErr_NoMemory(); goto error; } i = 0; while ((ei = PyIter_Next(it)) != NULL) { if (!kqueue_event_Check(ei)) { Py_DECREF(ei); PyErr_SetString(PyExc_TypeError, "changelist must be an iterable of " "select.kevent objects"); goto error; } else { chl[i++] = ((kqueue_event_Object *)ei)->e; } Py_DECREF(ei); } } Py_CLEAR(it); /* event list */ if (nevents) { evl = PyMem_New(struct kevent, nevents); if (evl == NULL) { PyErr_NoMemory(); goto error; } } Py_BEGIN_ALLOW_THREADS gotevents = kevent(self->kqfd, chl, nchanges, evl, nevents, ptimeoutspec); Py_END_ALLOW_THREADS if (gotevents == -1) { PyErr_SetFromErrno(PyExc_OSError); goto error; } result = PyList_New(gotevents); if (result == NULL) { goto error; } for (i = 0; i < gotevents; i++) { kqueue_event_Object *ch; ch = PyObject_New(kqueue_event_Object, &kqueue_event_Type); if (ch == NULL) { goto error; } ch->e = evl[i]; PyList_SET_ITEM(result, i, (PyObject *)ch); } PyMem_Free(chl); PyMem_Free(evl); return result; error: PyMem_Free(chl); PyMem_Free(evl); Py_XDECREF(result); Py_XDECREF(it); return NULL; } PyDoc_STRVAR(kqueue_queue_control_doc, "control(changelist, max_events[, timeout=None]) -> eventlist\n\ \n\ Calls the kernel kevent function.\n\ - changelist must be a list of kevent objects describing the changes\n\ to be made to the kernel's watch list or None.\n\ - max_events lets you specify the maximum number of events that the\n\ kernel will return.\n\ - timeout is the maximum time to wait in seconds, or else None,\n\ to wait forever. timeout accepts floats for smaller timeouts, too."); static PyMethodDef kqueue_queue_methods[] = { {"fromfd", (PyCFunction)kqueue_queue_fromfd, METH_VARARGS | METH_CLASS, kqueue_queue_fromfd_doc}, {"close", (PyCFunction)kqueue_queue_close, METH_NOARGS, kqueue_queue_close_doc}, {"fileno", (PyCFunction)kqueue_queue_fileno, METH_NOARGS, kqueue_queue_fileno_doc}, {"control", (PyCFunction)kqueue_queue_control, METH_VARARGS , kqueue_queue_control_doc}, {NULL, NULL}, }; static PyGetSetDef kqueue_queue_getsetlist[] = { {"closed", (getter)kqueue_queue_get_closed, NULL, "True if the kqueue handler is closed"}, {0}, }; PyDoc_STRVAR(kqueue_queue_doc, "Kqueue syscall wrapper.\n\ \n\ For example, to start watching a socket for input:\n\ >>> kq = kqueue()\n\ >>> sock = socket()\n\ >>> sock.connect((host, port))\n\ >>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_ADD)], 0)\n\ \n\ To wait one second for it to become writeable:\n\ >>> kq.control(None, 1, 1000)\n\ \n\ To stop listening:\n\ >>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_DELETE)], 0)"); static PyTypeObject kqueue_queue_Type = { PyVarObject_HEAD_INIT(NULL, 0) "select.kqueue", /* tp_name */ sizeof(kqueue_queue_Object), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)kqueue_queue_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ kqueue_queue_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ kqueue_queue_methods, /* tp_methods */ 0, /* tp_members */ kqueue_queue_getsetlist, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ kqueue_queue_new, /* tp_new */ 0, /* tp_free */ }; #endif /* HAVE_KQUEUE */ /* ************************************************************************ */ PyDoc_STRVAR(select_doc, "select(rlist, wlist, xlist[, timeout]) -> (rlist, wlist, xlist)\n\ \n\ Wait until one or more file descriptors are ready for some kind of I/O.\n\ The first three arguments are sequences of file descriptors to be waited for:\n\ rlist -- wait until ready for reading\n\ wlist -- wait until ready for writing\n\ xlist -- wait for an ``exceptional condition''\n\ If only one kind of condition is required, pass [] for the other lists.\n\ A file descriptor is either a socket or file object, or a small integer\n\ gotten from a fileno() method call on one of those.\n\ \n\ The optional 4th argument specifies a timeout in seconds; it may be\n\ a floating point number to specify fractions of seconds. If it is absent\n\ or None, the call will never time out.\n\ \n\ The return value is a tuple of three lists corresponding to the first three\n\ arguments; each contains the subset of the corresponding file descriptors\n\ that are ready.\n\ \n\ *** IMPORTANT NOTICE ***\n\ On Windows and OpenVMS, only sockets are supported; on Unix, all file\n\ descriptors can be used."); static PyMethodDef select_methods[] = { {"select", select_select, METH_VARARGS, select_doc}, #ifdef HAVE_POLL {"poll", select_poll, METH_NOARGS, poll_doc}, #endif /* HAVE_POLL */ {0, 0}, /* sentinel */ }; PyDoc_STRVAR(module_doc, "This module supports asynchronous I/O on multiple file descriptors.\n\ \n\ *** IMPORTANT NOTICE ***\n\ On Windows and OpenVMS, only sockets are supported; on Unix, all file descriptors."); static struct PyModuleDef selectmodule = { PyModuleDef_HEAD_INIT, "select", module_doc, -1, select_methods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_select(void) { PyObject *m; m = PyModule_Create(&selectmodule); if (m == NULL) return NULL; SelectError = PyErr_NewException("select.error", NULL, NULL); Py_INCREF(SelectError); PyModule_AddObject(m, "error", SelectError); #ifdef PIPE_BUF #ifdef HAVE_BROKEN_PIPE_BUF #undef PIPE_BUF #define PIPE_BUF 512 #endif PyModule_AddIntConstant(m, "PIPE_BUF", PIPE_BUF); #endif #if defined(HAVE_POLL) #ifdef __APPLE__ if (select_have_broken_poll()) { if (PyObject_DelAttrString(m, "poll") == -1) { PyErr_Clear(); } } else { #else { #endif if (PyType_Ready(&poll_Type) < 0) return NULL; PyModule_AddIntConstant(m, "POLLIN", POLLIN); PyModule_AddIntConstant(m, "POLLPRI", POLLPRI); PyModule_AddIntConstant(m, "POLLOUT", POLLOUT); PyModule_AddIntConstant(m, "POLLERR", POLLERR); PyModule_AddIntConstant(m, "POLLHUP", POLLHUP); PyModule_AddIntConstant(m, "POLLNVAL", POLLNVAL); #ifdef POLLRDNORM PyModule_AddIntConstant(m, "POLLRDNORM", POLLRDNORM); #endif #ifdef POLLRDBAND PyModule_AddIntConstant(m, "POLLRDBAND", POLLRDBAND); #endif #ifdef POLLWRNORM PyModule_AddIntConstant(m, "POLLWRNORM", POLLWRNORM); #endif #ifdef POLLWRBAND PyModule_AddIntConstant(m, "POLLWRBAND", POLLWRBAND); #endif #ifdef POLLMSG PyModule_AddIntConstant(m, "POLLMSG", POLLMSG); #endif } #endif /* HAVE_POLL */ #ifdef HAVE_EPOLL Py_TYPE(&pyEpoll_Type) = &PyType_Type; if (PyType_Ready(&pyEpoll_Type) < 0) return NULL; Py_INCREF(&pyEpoll_Type); PyModule_AddObject(m, "epoll", (PyObject *) &pyEpoll_Type); PyModule_AddIntConstant(m, "EPOLLIN", EPOLLIN); PyModule_AddIntConstant(m, "EPOLLOUT", EPOLLOUT); PyModule_AddIntConstant(m, "EPOLLPRI", EPOLLPRI); PyModule_AddIntConstant(m, "EPOLLERR", EPOLLERR); PyModule_AddIntConstant(m, "EPOLLHUP", EPOLLHUP); PyModule_AddIntConstant(m, "EPOLLET", EPOLLET); #ifdef EPOLLONESHOT /* Kernel 2.6.2+ */ PyModule_AddIntConstant(m, "EPOLLONESHOT", EPOLLONESHOT); #endif /* PyModule_AddIntConstant(m, "EPOLL_RDHUP", EPOLLRDHUP); */ PyModule_AddIntConstant(m, "EPOLLRDNORM", EPOLLRDNORM); PyModule_AddIntConstant(m, "EPOLLRDBAND", EPOLLRDBAND); PyModule_AddIntConstant(m, "EPOLLWRNORM", EPOLLWRNORM); PyModule_AddIntConstant(m, "EPOLLWRBAND", EPOLLWRBAND); PyModule_AddIntConstant(m, "EPOLLMSG", EPOLLMSG); #endif /* HAVE_EPOLL */ #ifdef HAVE_KQUEUE kqueue_event_Type.tp_new = PyType_GenericNew; Py_TYPE(&kqueue_event_Type) = &PyType_Type; if(PyType_Ready(&kqueue_event_Type) < 0) return NULL; Py_INCREF(&kqueue_event_Type); PyModule_AddObject(m, "kevent", (PyObject *)&kqueue_event_Type); Py_TYPE(&kqueue_queue_Type) = &PyType_Type; if(PyType_Ready(&kqueue_queue_Type) < 0) return NULL; Py_INCREF(&kqueue_queue_Type); PyModule_AddObject(m, "kqueue", (PyObject *)&kqueue_queue_Type); /* event filters */ PyModule_AddIntConstant(m, "KQ_FILTER_READ", EVFILT_READ); PyModule_AddIntConstant(m, "KQ_FILTER_WRITE", EVFILT_WRITE); PyModule_AddIntConstant(m, "KQ_FILTER_AIO", EVFILT_AIO); PyModule_AddIntConstant(m, "KQ_FILTER_VNODE", EVFILT_VNODE); PyModule_AddIntConstant(m, "KQ_FILTER_PROC", EVFILT_PROC); #ifdef EVFILT_NETDEV PyModule_AddIntConstant(m, "KQ_FILTER_NETDEV", EVFILT_NETDEV); #endif PyModule_AddIntConstant(m, "KQ_FILTER_SIGNAL", EVFILT_SIGNAL); PyModule_AddIntConstant(m, "KQ_FILTER_TIMER", EVFILT_TIMER); /* event flags */ PyModule_AddIntConstant(m, "KQ_EV_ADD", EV_ADD); PyModule_AddIntConstant(m, "KQ_EV_DELETE", EV_DELETE); PyModule_AddIntConstant(m, "KQ_EV_ENABLE", EV_ENABLE); PyModule_AddIntConstant(m, "KQ_EV_DISABLE", EV_DISABLE); PyModule_AddIntConstant(m, "KQ_EV_ONESHOT", EV_ONESHOT); PyModule_AddIntConstant(m, "KQ_EV_CLEAR", EV_CLEAR); PyModule_AddIntConstant(m, "KQ_EV_SYSFLAGS", EV_SYSFLAGS); PyModule_AddIntConstant(m, "KQ_EV_FLAG1", EV_FLAG1); PyModule_AddIntConstant(m, "KQ_EV_EOF", EV_EOF); PyModule_AddIntConstant(m, "KQ_EV_ERROR", EV_ERROR); /* READ WRITE filter flag */ PyModule_AddIntConstant(m, "KQ_NOTE_LOWAT", NOTE_LOWAT); /* VNODE filter flags */ PyModule_AddIntConstant(m, "KQ_NOTE_DELETE", NOTE_DELETE); PyModule_AddIntConstant(m, "KQ_NOTE_WRITE", NOTE_WRITE); PyModule_AddIntConstant(m, "KQ_NOTE_EXTEND", NOTE_EXTEND); PyModule_AddIntConstant(m, "KQ_NOTE_ATTRIB", NOTE_ATTRIB); PyModule_AddIntConstant(m, "KQ_NOTE_LINK", NOTE_LINK); PyModule_AddIntConstant(m, "KQ_NOTE_RENAME", NOTE_RENAME); PyModule_AddIntConstant(m, "KQ_NOTE_REVOKE", NOTE_REVOKE); /* PROC filter flags */ PyModule_AddIntConstant(m, "KQ_NOTE_EXIT", NOTE_EXIT); PyModule_AddIntConstant(m, "KQ_NOTE_FORK", NOTE_FORK); PyModule_AddIntConstant(m, "KQ_NOTE_EXEC", NOTE_EXEC); PyModule_AddIntConstant(m, "KQ_NOTE_PCTRLMASK", NOTE_PCTRLMASK); PyModule_AddIntConstant(m, "KQ_NOTE_PDATAMASK", NOTE_PDATAMASK); PyModule_AddIntConstant(m, "KQ_NOTE_TRACK", NOTE_TRACK); PyModule_AddIntConstant(m, "KQ_NOTE_CHILD", NOTE_CHILD); PyModule_AddIntConstant(m, "KQ_NOTE_TRACKERR", NOTE_TRACKERR); /* NETDEV filter flags */ #ifdef EVFILT_NETDEV PyModule_AddIntConstant(m, "KQ_NOTE_LINKUP", NOTE_LINKUP); PyModule_AddIntConstant(m, "KQ_NOTE_LINKDOWN", NOTE_LINKDOWN); PyModule_AddIntConstant(m, "KQ_NOTE_LINKINV", NOTE_LINKINV); #endif #endif /* HAVE_KQUEUE */ return m; } /* select - Module containing unix select(2) call. Under Unix, the file descriptors are small integers. Under Win32, select only exists for sockets, and sockets may have any value except INVALID_SOCKET. */ #include "Python.h" #include <structmember.h> #ifdef __APPLE__ /* Perform runtime testing for a broken poll on OSX to make it easier * to use the same binary on multiple releases of the OS. */ #undef HAVE_BROKEN_POLL #endif /* Windows #defines FD_SETSIZE to 64 if FD_SETSIZE isn't already defined. 64 is too small (too many people have bumped into that limit). Here we boost it. Users who want even more than the boosted limit should #define FD_SETSIZE higher before this; e.g., via compiler /D switch. */ #if defined(MS_WINDOWS) && !defined(FD_SETSIZE) #define FD_SETSIZE 512 #endif #if defined(HAVE_POLL_H) #include <poll.h> #elif defined(HAVE_SYS_POLL_H) #include <sys/poll.h> #endif #ifdef __sgi /* This is missing from unistd.h */ extern void bzero(void *, int); #endif #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #if defined(PYOS_OS2) && !defined(PYCC_GCC) #include <sys/time.h> #include <utils.h> #endif #ifdef MS_WINDOWS # define WIN32_LEAN_AND_MEAN # include <winsock.h> #else # define SOCKET int # if defined(__VMS) # include <socket.h> # endif #endif static PyObject *SelectError; /* list of Python objects and their file descriptor */ typedef struct { PyObject *obj; /* owned reference */ SOCKET fd; int sentinel; /* -1 == sentinel */ } pylist; static void reap_obj(pylist fd2obj[FD_SETSIZE + 1]) { int i; for (i = 0; i < FD_SETSIZE + 1 && fd2obj[i].sentinel >= 0; i++) { Py_XDECREF(fd2obj[i].obj); fd2obj[i].obj = NULL; } fd2obj[0].sentinel = -1; } /* returns -1 and sets the Python exception if an error occurred, otherwise returns a number >= 0 */ static int seq2set(PyObject *seq, fd_set *set, pylist fd2obj[FD_SETSIZE + 1]) { int max = -1; int index = 0; Py_ssize_t i, len = -1; PyObject* fast_seq = NULL; PyObject* o = NULL; fd2obj[0].obj = (PyObject*)0; /* set list to zero size */ FD_ZERO(set); fast_seq = PySequence_Fast(seq, "arguments 1-3 must be sequences"); if (!fast_seq) return -1; len = PySequence_Fast_GET_SIZE(fast_seq); for (i = 0; i < len; i++) { SOCKET v; /* any intervening fileno() calls could decr this refcnt */ if (!(o = PySequence_Fast_GET_ITEM(fast_seq, i))) return -1; Py_INCREF(o); v = PyObject_AsFileDescriptor( o ); if (v == -1) goto finally; #if defined(_MSC_VER) max = 0; /* not used for Win32 */ #else /* !_MSC_VER */ if (v < 0 || v >= FD_SETSIZE) { PyErr_SetString(PyExc_ValueError, "filedescriptor out of range in select()"); goto finally; } if (v > max) max = v; #endif /* _MSC_VER */ FD_SET(v, set); /* add object and its file descriptor to the list */ if (index >= FD_SETSIZE) { PyErr_SetString(PyExc_ValueError, "too many file descriptors in select()"); goto finally; } fd2obj[index].obj = o; fd2obj[index].fd = v; fd2obj[index].sentinel = 0; fd2obj[++index].sentinel = -1; } Py_DECREF(fast_seq); return max+1; finally: Py_XDECREF(o); Py_DECREF(fast_seq); return -1; } /* returns NULL and sets the Python exception if an error occurred */ static PyObject * set2list(fd_set *set, pylist fd2obj[FD_SETSIZE + 1]) { int i, j, count=0; PyObject *list, *o; SOCKET fd; for (j = 0; fd2obj[j].sentinel >= 0; j++) { if (FD_ISSET(fd2obj[j].fd, set)) count++; } list = PyList_New(count); if (!list) return NULL; i = 0; for (j = 0; fd2obj[j].sentinel >= 0; j++) { fd = fd2obj[j].fd; if (FD_ISSET(fd, set)) { #ifndef _MSC_VER if (fd > FD_SETSIZE) { PyErr_SetString(PyExc_SystemError, "filedescriptor out of range returned in select()"); goto finally; } #endif o = fd2obj[j].obj; fd2obj[j].obj = NULL; /* transfer ownership */ if (PyList_SetItem(list, i, o) < 0) goto finally; i++; } } return list; finally: Py_DECREF(list); return NULL; } #undef SELECT_USES_HEAP #if FD_SETSIZE > 1024 #define SELECT_USES_HEAP #endif /* FD_SETSIZE > 1024 */ static PyObject * select_select(PyObject *self, PyObject *args) { #ifdef SELECT_USES_HEAP pylist *rfd2obj, *wfd2obj, *efd2obj; #else /* !SELECT_USES_HEAP */ /* XXX: All this should probably be implemented as follows: * - find the highest descriptor we're interested in * - add one * - that's the size * See: Stevens, APitUE, $12.5.1 */ pylist rfd2obj[FD_SETSIZE + 1]; pylist wfd2obj[FD_SETSIZE + 1]; pylist efd2obj[FD_SETSIZE + 1]; #endif /* SELECT_USES_HEAP */ PyObject *ifdlist, *ofdlist, *efdlist; PyObject *ret = NULL; PyObject *tout = Py_None; fd_set ifdset, ofdset, efdset; double timeout; struct timeval tv, *tvp; long seconds; int imax, omax, emax, max; int n; /* convert arguments */ if (!PyArg_UnpackTuple(args, "select", 3, 4, &ifdlist, &ofdlist, &efdlist, &tout)) return NULL; if (tout == Py_None) tvp = (struct timeval *)0; else if (!PyNumber_Check(tout)) { PyErr_SetString(PyExc_TypeError, "timeout must be a float or None"); return NULL; } else { timeout = PyFloat_AsDouble(tout); if (timeout == -1 && PyErr_Occurred()) return NULL; if (timeout > (double)LONG_MAX) { PyErr_SetString(PyExc_OverflowError, "timeout period too long"); return NULL; } if (timeout < 0) { PyErr_SetString(PyExc_ValueError, "timeout must be non-negative"); return NULL; } seconds = (long)timeout; timeout = timeout - (double)seconds; tv.tv_sec = seconds; tv.tv_usec = (long)(timeout * 1E6); tvp = &tv; } #ifdef SELECT_USES_HEAP /* Allocate memory for the lists */ rfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1); wfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1); efd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1); if (rfd2obj == NULL || wfd2obj == NULL || efd2obj == NULL) { if (rfd2obj) PyMem_DEL(rfd2obj); if (wfd2obj) PyMem_DEL(wfd2obj); if (efd2obj) PyMem_DEL(efd2obj); return PyErr_NoMemory(); } #endif /* SELECT_USES_HEAP */ /* Convert sequences to fd_sets, and get maximum fd number * propagates the Python exception set in seq2set() */ rfd2obj[0].sentinel = -1; wfd2obj[0].sentinel = -1; efd2obj[0].sentinel = -1; if ((imax=seq2set(ifdlist, &ifdset, rfd2obj)) < 0) goto finally; if ((omax=seq2set(ofdlist, &ofdset, wfd2obj)) < 0) goto finally; if ((emax=seq2set(efdlist, &efdset, efd2obj)) < 0) goto finally; max = imax; if (omax > max) max = omax; if (emax > max) max = emax; Py_BEGIN_ALLOW_THREADS n = select(max, &ifdset, &ofdset, &efdset, tvp); Py_END_ALLOW_THREADS #ifdef MS_WINDOWS if (n == SOCKET_ERROR) { PyErr_SetExcFromWindowsErr(SelectError, WSAGetLastError()); } #else if (n < 0) { PyErr_SetFromErrno(SelectError); } #endif else { /* any of these three calls can raise an exception. it's more convenient to test for this after all three calls... but is that acceptable? */ ifdlist = set2list(&ifdset, rfd2obj); ofdlist = set2list(&ofdset, wfd2obj); efdlist = set2list(&efdset, efd2obj); if (PyErr_Occurred()) ret = NULL; else ret = PyTuple_Pack(3, ifdlist, ofdlist, efdlist); Py_DECREF(ifdlist); Py_DECREF(ofdlist); Py_DECREF(efdlist); } finally: reap_obj(rfd2obj); reap_obj(wfd2obj); reap_obj(efd2obj); #ifdef SELECT_USES_HEAP PyMem_DEL(rfd2obj); PyMem_DEL(wfd2obj); PyMem_DEL(efd2obj); #endif /* SELECT_USES_HEAP */ return ret; } #if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL) /* * poll() support */ typedef struct { PyObject_HEAD PyObject *dict; int ufd_uptodate; int ufd_len; struct pollfd *ufds; } pollObject; static PyTypeObject poll_Type; /* Update the malloc'ed array of pollfds to match the dictionary contained within a pollObject. Return 1 on success, 0 on an error. */ static int update_ufd_array(pollObject *self) { Py_ssize_t i, pos; PyObject *key, *value; struct pollfd *old_ufds = self->ufds; self->ufd_len = PyDict_Size(self->dict); PyMem_RESIZE(self->ufds, struct pollfd, self->ufd_len); if (self->ufds == NULL) { self->ufds = old_ufds; PyErr_NoMemory(); return 0; } i = pos = 0; while (PyDict_Next(self->dict, &pos, &key, &value)) { self->ufds[i].fd = PyLong_AsLong(key); self->ufds[i].events = (short)PyLong_AsLong(value); i++; } self->ufd_uptodate = 1; return 1; } PyDoc_STRVAR(poll_register_doc, "register(fd [, eventmask] ) -> None\n\n\ Register a file descriptor with the polling object.\n\ fd -- either an integer, or an object with a fileno() method returning an\n\ int.\n\ events -- an optional bitmask describing the type of events to check for"); static PyObject * poll_register(pollObject *self, PyObject *args) { PyObject *o, *key, *value; int fd, events = POLLIN | POLLPRI | POLLOUT; int err; if (!PyArg_ParseTuple(args, "O|i:register", &o, &events)) { return NULL; } fd = PyObject_AsFileDescriptor(o); if (fd == -1) return NULL; /* Add entry to the internal dictionary: the key is the file descriptor, and the value is the event mask. */ key = PyLong_FromLong(fd); if (key == NULL) return NULL; value = PyLong_FromLong(events); if (value == NULL) { Py_DECREF(key); return NULL; } err = PyDict_SetItem(self->dict, key, value); Py_DECREF(key); Py_DECREF(value); if (err < 0) return NULL; self->ufd_uptodate = 0; Py_INCREF(Py_None); return Py_None; } PyDoc_STRVAR(poll_modify_doc, "modify(fd, eventmask) -> None\n\n\ Modify an already registered file descriptor.\n\ fd -- either an integer, or an object with a fileno() method returning an\n\ int.\n\ events -- an optional bitmask describing the type of events to check for"); static PyObject * poll_modify(pollObject *self, PyObject *args) { PyObject *o, *key, *value; int fd, events; int err; if (!PyArg_ParseTuple(args, "Oi:modify", &o, &events)) { return NULL; } fd = PyObject_AsFileDescriptor(o); if (fd == -1) return NULL; /* Modify registered fd */ key = PyLong_FromLong(fd); if (key == NULL) return NULL; if (PyDict_GetItem(self->dict, key) == NULL) { errno = ENOENT; PyErr_SetFromErrno(PyExc_IOError); return NULL; } value = PyLong_FromLong(events); if (value == NULL) { Py_DECREF(key); return NULL; } err = PyDict_SetItem(self->dict, key, value); Py_DECREF(key); Py_DECREF(value); if (err < 0) return NULL; self->ufd_uptodate = 0; Py_INCREF(Py_None); return Py_None; } PyDoc_STRVAR(poll_unregister_doc, "unregister(fd) -> None\n\n\ Remove a file descriptor being tracked by the polling object."); static PyObject * poll_unregister(pollObject *self, PyObject *o) { PyObject *key; int fd; fd = PyObject_AsFileDescriptor( o ); if (fd == -1) return NULL; /* Check whether the fd is already in the array */ key = PyLong_FromLong(fd); if (key == NULL) return NULL; if (PyDict_DelItem(self->dict, key) == -1) { Py_DECREF(key); /* This will simply raise the KeyError set by PyDict_DelItem if the file descriptor isn't registered. */ return NULL; } Py_DECREF(key); self->ufd_uptodate = 0; Py_INCREF(Py_None); return Py_None; } PyDoc_STRVAR(poll_poll_doc, "poll( [timeout] ) -> list of (fd, event) 2-tuples\n\n\ Polls the set of registered file descriptors, returning a list containing \n\ any descriptors that have events or errors to report."); static PyObject * poll_poll(pollObject *self, PyObject *args) { PyObject *result_list = NULL, *tout = NULL; int timeout = 0, poll_result, i, j; PyObject *value = NULL, *num = NULL; if (!PyArg_UnpackTuple(args, "poll", 0, 1, &tout)) { return NULL; } /* Check values for timeout */ if (tout == NULL || tout == Py_None) timeout = -1; else if (!PyNumber_Check(tout)) { PyErr_SetString(PyExc_TypeError, "timeout must be an integer or None"); return NULL; } else { tout = PyNumber_Long(tout); if (!tout) return NULL; timeout = PyLong_AsLong(tout); Py_DECREF(tout); if (timeout == -1 && PyErr_Occurred()) return NULL; } /* Ensure the ufd array is up to date */ if (!self->ufd_uptodate) if (update_ufd_array(self) == 0) return NULL; /* call poll() */ Py_BEGIN_ALLOW_THREADS poll_result = poll(self->ufds, self->ufd_len, timeout); Py_END_ALLOW_THREADS if (poll_result < 0) { PyErr_SetFromErrno(SelectError); return NULL; } /* build the result list */ result_list = PyList_New(poll_result); if (!result_list) return NULL; else { for (i = 0, j = 0; j < poll_result; j++) { /* skip to the next fired descriptor */ while (!self->ufds[i].revents) { i++; } /* if we hit a NULL return, set value to NULL and break out of loop; code at end will clean up result_list */ value = PyTuple_New(2); if (value == NULL) goto error; num = PyLong_FromLong(self->ufds[i].fd); if (num == NULL) { Py_DECREF(value); goto error; } PyTuple_SET_ITEM(value, 0, num); /* The &0xffff is a workaround for AIX. 'revents' is a 16-bit short, and IBM assigned POLLNVAL to be 0x8000, so the conversion to int results in a negative number. See SF bug #923315. */ num = PyLong_FromLong(self->ufds[i].revents & 0xffff); if (num == NULL) { Py_DECREF(value); goto error; } PyTuple_SET_ITEM(value, 1, num); if ((PyList_SetItem(result_list, j, value)) == -1) { Py_DECREF(value); goto error; } i++; } } return result_list; error: Py_DECREF(result_list); return NULL; } static PyMethodDef poll_methods[] = { {"register", (PyCFunction)poll_register, METH_VARARGS, poll_register_doc}, {"modify", (PyCFunction)poll_modify, METH_VARARGS, poll_modify_doc}, {"unregister", (PyCFunction)poll_unregister, METH_O, poll_unregister_doc}, {"poll", (PyCFunction)poll_poll, METH_VARARGS, poll_poll_doc}, {NULL, NULL} /* sentinel */ }; static pollObject * newPollObject(void) { pollObject *self; self = PyObject_New(pollObject, &poll_Type); if (self == NULL) return NULL; /* ufd_uptodate is a Boolean, denoting whether the array pointed to by ufds matches the contents of the dictionary. */ self->ufd_uptodate = 0; self->ufds = NULL; self->dict = PyDict_New(); if (self->dict == NULL) { Py_DECREF(self); return NULL; } return self; } static void poll_dealloc(pollObject *self) { if (self->ufds != NULL) PyMem_DEL(self->ufds); Py_XDECREF(self->dict); PyObject_Del(self); } static PyTypeObject poll_Type = { /* The ob_type field must be initialized in the module init function * to be portable to Windows without using C++. */ PyVarObject_HEAD_INIT(NULL, 0) "select.poll", /*tp_name*/ sizeof(pollObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ /* methods */ (destructor)poll_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ poll_methods, /*tp_methods*/ }; PyDoc_STRVAR(poll_doc, "Returns a polling object, which supports registering and\n\ unregistering file descriptors, and then polling them for I/O events."); static PyObject * select_poll(PyObject *self, PyObject *unused) { return (PyObject *)newPollObject(); } #ifdef __APPLE__ /* * On some systems poll() sets errno on invalid file descriptors. We test * for this at runtime because this bug may be fixed or introduced between * OS releases. */ static int select_have_broken_poll(void) { int poll_test; int filedes[2]; struct pollfd poll_struct = { 0, POLLIN|POLLPRI|POLLOUT, 0 }; /* Create a file descriptor to make invalid */ if (pipe(filedes) < 0) { return 1; } poll_struct.fd = filedes[0]; close(filedes[0]); close(filedes[1]); poll_test = poll(&poll_struct, 1, 0); if (poll_test < 0) { return 1; } else if (poll_test == 0 && poll_struct.revents != POLLNVAL) { return 1; } return 0; } #endif /* __APPLE__ */ #endif /* HAVE_POLL */ #ifdef HAVE_EPOLL /* ************************************************************************** * epoll interface for Linux 2.6 * * Written by Christian Heimes * Inspired by Twisted's _epoll.pyx and select.poll() */ #ifdef HAVE_SYS_EPOLL_H #include <sys/epoll.h> #endif typedef struct { PyObject_HEAD SOCKET epfd; /* epoll control file descriptor */ } pyEpoll_Object; static PyTypeObject pyEpoll_Type; #define pyepoll_CHECK(op) (PyObject_TypeCheck((op), &pyEpoll_Type)) static PyObject * pyepoll_err_closed(void) { PyErr_SetString(PyExc_ValueError, "I/O operation on closed epoll fd"); return NULL; } static int pyepoll_internal_close(pyEpoll_Object *self) { int save_errno = 0; if (self->epfd >= 0) { int epfd = self->epfd; self->epfd = -1; Py_BEGIN_ALLOW_THREADS if (close(epfd) < 0) save_errno = errno; Py_END_ALLOW_THREADS } return save_errno; } static PyObject * newPyEpoll_Object(PyTypeObject *type, int sizehint, SOCKET fd) { pyEpoll_Object *self; if (sizehint == -1) { sizehint = FD_SETSIZE-1; } else if (sizehint < 1) { PyErr_Format(PyExc_ValueError, "sizehint must be greater zero, got %d", sizehint); return NULL; } assert(type != NULL && type->tp_alloc != NULL); self = (pyEpoll_Object *) type->tp_alloc(type, 0); if (self == NULL) return NULL; if (fd == -1) { Py_BEGIN_ALLOW_THREADS self->epfd = epoll_create(sizehint); Py_END_ALLOW_THREADS } else { self->epfd = fd; } if (self->epfd < 0) { Py_DECREF(self); PyErr_SetFromErrno(PyExc_IOError); return NULL; } return (PyObject *)self; } static PyObject * pyepoll_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { int sizehint = -1; static char *kwlist[] = {"sizehint", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:epoll", kwlist, &sizehint)) return NULL; return newPyEpoll_Object(type, sizehint, -1); } static void pyepoll_dealloc(pyEpoll_Object *self) { (void)pyepoll_internal_close(self); Py_TYPE(self)->tp_free(self); } static PyObject* pyepoll_close(pyEpoll_Object *self) { errno = pyepoll_internal_close(self); if (errno < 0) { PyErr_SetFromErrno(PyExc_IOError); return NULL; } Py_RETURN_NONE; } PyDoc_STRVAR(pyepoll_close_doc, "close() -> None\n\ \n\ Close the epoll control file descriptor. Further operations on the epoll\n\ object will raise an exception."); static PyObject* pyepoll_get_closed(pyEpoll_Object *self) { if (self->epfd < 0) Py_RETURN_TRUE; else Py_RETURN_FALSE; } static PyObject* pyepoll_fileno(pyEpoll_Object *self) { if (self->epfd < 0) return pyepoll_err_closed(); return PyLong_FromLong(self->epfd); } PyDoc_STRVAR(pyepoll_fileno_doc, "fileno() -> int\n\ \n\ Return the epoll control file descriptor."); static PyObject* pyepoll_fromfd(PyObject *cls, PyObject *args) { SOCKET fd; if (!PyArg_ParseTuple(args, "i:fromfd", &fd)) return NULL; return newPyEpoll_Object((PyTypeObject*)cls, -1, fd); } PyDoc_STRVAR(pyepoll_fromfd_doc, "fromfd(fd) -> epoll\n\ \n\ Create an epoll object from a given control fd."); static PyObject * pyepoll_internal_ctl(int epfd, int op, PyObject *pfd, unsigned int events) { struct epoll_event ev; int result; int fd; if (epfd < 0) return pyepoll_err_closed(); fd = PyObject_AsFileDescriptor(pfd); if (fd == -1) { return NULL; } switch(op) { case EPOLL_CTL_ADD: case EPOLL_CTL_MOD: ev.events = events; ev.data.fd = fd; Py_BEGIN_ALLOW_THREADS result = epoll_ctl(epfd, op, fd, &ev); Py_END_ALLOW_THREADS break; case EPOLL_CTL_DEL: /* In kernel versions before 2.6.9, the EPOLL_CTL_DEL * operation required a non-NULL pointer in event, even * though this argument is ignored. */ Py_BEGIN_ALLOW_THREADS result = epoll_ctl(epfd, op, fd, &ev); if (errno == EBADF) { /* fd already closed */ result = 0; errno = 0; } Py_END_ALLOW_THREADS break; default: result = -1; errno = EINVAL; } if (result < 0) { PyErr_SetFromErrno(PyExc_IOError); return NULL; } Py_RETURN_NONE; } static PyObject * pyepoll_register(pyEpoll_Object *self, PyObject *args, PyObject *kwds) { PyObject *pfd; unsigned int events = EPOLLIN | EPOLLOUT | EPOLLPRI; static char *kwlist[] = {"fd", "eventmask", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|I:register", kwlist, &pfd, &events)) { return NULL; } return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_ADD, pfd, events); } PyDoc_STRVAR(pyepoll_register_doc, "register(fd[, eventmask]) -> None\n\ \n\ Registers a new fd or modifies an already registered fd.\n\ fd is the target file descriptor of the operation.\n\ events is a bit set composed of the various EPOLL constants; the default\n\ is EPOLL_IN | EPOLL_OUT | EPOLL_PRI.\n\ \n\ The epoll interface supports all file descriptors that support poll."); static PyObject * pyepoll_modify(pyEpoll_Object *self, PyObject *args, PyObject *kwds) { PyObject *pfd; unsigned int events; static char *kwlist[] = {"fd", "eventmask", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OI:modify", kwlist, &pfd, &events)) { return NULL; } return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_MOD, pfd, events); } PyDoc_STRVAR(pyepoll_modify_doc, "modify(fd, eventmask) -> None\n\ \n\ fd is the target file descriptor of the operation\n\ events is a bit set composed of the various EPOLL constants"); static PyObject * pyepoll_unregister(pyEpoll_Object *self, PyObject *args, PyObject *kwds) { PyObject *pfd; static char *kwlist[] = {"fd", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:unregister", kwlist, &pfd)) { return NULL; } return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_DEL, pfd, 0); } PyDoc_STRVAR(pyepoll_unregister_doc, "unregister(fd) -> None\n\ \n\ fd is the target file descriptor of the operation."); static PyObject * pyepoll_poll(pyEpoll_Object *self, PyObject *args, PyObject *kwds) { double dtimeout = -1.; int timeout; int maxevents = -1; int nfds, i; PyObject *elist = NULL, *etuple = NULL; struct epoll_event *evs = NULL; static char *kwlist[] = {"timeout", "maxevents", NULL}; if (self->epfd < 0) return pyepoll_err_closed(); if (!PyArg_ParseTupleAndKeywords(args, kwds, "|di:poll", kwlist, &dtimeout, &maxevents)) { return NULL; } if (dtimeout < 0) { timeout = -1; } else if (dtimeout * 1000.0 > INT_MAX) { PyErr_SetString(PyExc_OverflowError, "timeout is too large"); return NULL; } else { timeout = (int)(dtimeout * 1000.0); } if (maxevents == -1) { maxevents = FD_SETSIZE-1; } else if (maxevents < 1) { PyErr_Format(PyExc_ValueError, "maxevents must be greater than 0, got %d", maxevents); return NULL; } evs = PyMem_New(struct epoll_event, maxevents); if (evs == NULL) { Py_DECREF(self); PyErr_NoMemory(); return NULL; } Py_BEGIN_ALLOW_THREADS nfds = epoll_wait(self->epfd, evs, maxevents, timeout); Py_END_ALLOW_THREADS if (nfds < 0) { PyErr_SetFromErrno(PyExc_IOError); goto error; } elist = PyList_New(nfds); if (elist == NULL) { goto error; } for (i = 0; i < nfds; i++) { etuple = Py_BuildValue("iI", evs[i].data.fd, evs[i].events); if (etuple == NULL) { Py_CLEAR(elist); goto error; } PyList_SET_ITEM(elist, i, etuple); } error: PyMem_Free(evs); return elist; } PyDoc_STRVAR(pyepoll_poll_doc, "poll([timeout=-1[, maxevents=-1]]) -> [(fd, events), (...)]\n\ \n\ Wait for events on the epoll file descriptor for a maximum time of timeout\n\ in seconds (as float). -1 makes poll wait indefinitely.\n\ Up to maxevents are returned to the caller."); static PyMethodDef pyepoll_methods[] = { {"fromfd", (PyCFunction)pyepoll_fromfd, METH_VARARGS | METH_CLASS, pyepoll_fromfd_doc}, {"close", (PyCFunction)pyepoll_close, METH_NOARGS, pyepoll_close_doc}, {"fileno", (PyCFunction)pyepoll_fileno, METH_NOARGS, pyepoll_fileno_doc}, {"modify", (PyCFunction)pyepoll_modify, METH_VARARGS | METH_KEYWORDS, pyepoll_modify_doc}, {"register", (PyCFunction)pyepoll_register, METH_VARARGS | METH_KEYWORDS, pyepoll_register_doc}, {"unregister", (PyCFunction)pyepoll_unregister, METH_VARARGS | METH_KEYWORDS, pyepoll_unregister_doc}, {"poll", (PyCFunction)pyepoll_poll, METH_VARARGS | METH_KEYWORDS, pyepoll_poll_doc}, {NULL, NULL}, }; static PyGetSetDef pyepoll_getsetlist[] = { {"closed", (getter)pyepoll_get_closed, NULL, "True if the epoll handler is closed"}, {0}, }; PyDoc_STRVAR(pyepoll_doc, "select.epoll([sizehint=-1])\n\ \n\ Returns an epolling object\n\ \n\ sizehint must be a positive integer or -1 for the default size. The\n\ sizehint is used to optimize internal data structures. It doesn't limit\n\ the maximum number of monitored events."); static PyTypeObject pyEpoll_Type = { PyVarObject_HEAD_INIT(NULL, 0) "select.epoll", /* tp_name */ sizeof(pyEpoll_Object), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)pyepoll_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ pyepoll_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ pyepoll_methods, /* tp_methods */ 0, /* tp_members */ pyepoll_getsetlist, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ pyepoll_new, /* tp_new */ 0, /* tp_free */ }; #endif /* HAVE_EPOLL */ #ifdef HAVE_KQUEUE /* ************************************************************************** * kqueue interface for BSD * * Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifdef HAVE_SYS_EVENT_H #include <sys/event.h> #endif PyDoc_STRVAR(kqueue_event_doc, "kevent(ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD, fflags=0, data=0, udata=0)\n\ \n\ This object is the equivalent of the struct kevent for the C API.\n\ \n\ See the kqueue manpage for more detailed information about the meaning\n\ of the arguments.\n\ \n\ One minor note: while you might hope that udata could store a\n\ reference to a python object, it cannot, because it is impossible to\n\ keep a proper reference count of the object once it's passed into the\n\ kernel. Therefore, I have restricted it to only storing an integer. I\n\ recommend ignoring it and simply using the 'ident' field to key off\n\ of. You could also set up a dictionary on the python side to store a\n\ udata->object mapping."); typedef struct { PyObject_HEAD struct kevent e; } kqueue_event_Object; static PyTypeObject kqueue_event_Type; #define kqueue_event_Check(op) (PyObject_TypeCheck((op), &kqueue_event_Type)) typedef struct { PyObject_HEAD SOCKET kqfd; /* kqueue control fd */ } kqueue_queue_Object; static PyTypeObject kqueue_queue_Type; #define kqueue_queue_Check(op) (PyObject_TypeCheck((op), &kqueue_queue_Type)) #if (SIZEOF_UINTPTR_T != SIZEOF_VOID_P) # error uintptr_t does not match void *! #elif (SIZEOF_UINTPTR_T == SIZEOF_LONG_LONG) # define T_UINTPTRT T_ULONGLONG # define T_INTPTRT T_LONGLONG # define PyLong_AsUintptr_t PyLong_AsUnsignedLongLong # define UINTPTRT_FMT_UNIT "K" # define INTPTRT_FMT_UNIT "L" #elif (SIZEOF_UINTPTR_T == SIZEOF_LONG) # define T_UINTPTRT T_ULONG # define T_INTPTRT T_LONG # define PyLong_AsUintptr_t PyLong_AsUnsignedLong # define UINTPTRT_FMT_UNIT "k" # define INTPTRT_FMT_UNIT "l" #elif (SIZEOF_UINTPTR_T == SIZEOF_INT) # define T_UINTPTRT T_UINT # define T_INTPTRT T_INT # define PyLong_AsUintptr_t PyLong_AsUnsignedLong # define UINTPTRT_FMT_UNIT "I" # define INTPTRT_FMT_UNIT "i" #else # error uintptr_t does not match int, long, or long long! #endif /* Unfortunately, we can't store python objects in udata, because * kevents in the kernel can be removed without warning, which would * forever lose the refcount on the object stored with it. */ #define KQ_OFF(x) offsetof(kqueue_event_Object, x) static struct PyMemberDef kqueue_event_members[] = { {"ident", T_UINTPTRT, KQ_OFF(e.ident)}, {"filter", T_SHORT, KQ_OFF(e.filter)}, {"flags", T_USHORT, KQ_OFF(e.flags)}, {"fflags", T_UINT, KQ_OFF(e.fflags)}, {"data", T_INTPTRT, KQ_OFF(e.data)}, {"udata", T_UINTPTRT, KQ_OFF(e.udata)}, {NULL} /* Sentinel */ }; #undef KQ_OFF static PyObject * kqueue_event_repr(kqueue_event_Object *s) { char buf[1024]; PyOS_snprintf( buf, sizeof(buf), "<select.kevent ident=%zu filter=%d flags=0x%x fflags=0x%x " "data=0x%zd udata=%p>", (size_t)(s->e.ident), s->e.filter, s->e.flags, s->e.fflags, (Py_ssize_t)(s->e.data), s->e.udata); return PyUnicode_FromString(buf); } static int kqueue_event_init(kqueue_event_Object *self, PyObject *args, PyObject *kwds) { PyObject *pfd; static char *kwlist[] = {"ident", "filter", "flags", "fflags", "data", "udata", NULL}; static char *fmt = "O|hhi" INTPTRT_FMT_UNIT UINTPTRT_FMT_UNIT ":kevent"; EV_SET(&(self->e), 0, EVFILT_READ, EV_ADD, 0, 0, 0); /* defaults */ if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist, &pfd, &(self->e.filter), &(self->e.flags), &(self->e.fflags), &(self->e.data), &(self->e.udata))) { return -1; } if (PyLong_Check(pfd)) { self->e.ident = PyLong_AsUintptr_t(pfd); } else { self->e.ident = PyObject_AsFileDescriptor(pfd); } if (PyErr_Occurred()) { return -1; } return 0; } static PyObject * kqueue_event_richcompare(kqueue_event_Object *s, kqueue_event_Object *o, int op) { Py_intptr_t result = 0; if (!kqueue_event_Check(o)) { if (op == Py_EQ || op == Py_NE) { PyObject *res = op == Py_EQ ? Py_False : Py_True; Py_INCREF(res); return res; } PyErr_Format(PyExc_TypeError, "can't compare %.200s to %.200s", Py_TYPE(s)->tp_name, Py_TYPE(o)->tp_name); return NULL; } if (((result = s->e.ident - o->e.ident) == 0) && ((result = s->e.filter - o->e.filter) == 0) && ((result = s->e.flags - o->e.flags) == 0) && ((result = s->e.fflags - o->e.fflags) == 0) && ((result = s->e.data - o->e.data) == 0) && ((result = s->e.udata - o->e.udata) == 0) ) { result = 0; } switch (op) { case Py_EQ: result = (result == 0); break; case Py_NE: result = (result != 0); break; case Py_LE: result = (result <= 0); break; case Py_GE: result = (result >= 0); break; case Py_LT: result = (result < 0); break; case Py_GT: result = (result > 0); break; } return PyBool_FromLong((long)result); } static PyTypeObject kqueue_event_Type = { PyVarObject_HEAD_INIT(NULL, 0) "select.kevent", /* tp_name */ sizeof(kqueue_event_Object), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)kqueue_event_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ kqueue_event_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ (richcmpfunc)kqueue_event_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ kqueue_event_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)kqueue_event_init, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ }; static PyObject * kqueue_queue_err_closed(void) { PyErr_SetString(PyExc_ValueError, "I/O operation on closed kqueue fd"); return NULL; } static int kqueue_queue_internal_close(kqueue_queue_Object *self) { int save_errno = 0; if (self->kqfd >= 0) { int kqfd = self->kqfd; self->kqfd = -1; Py_BEGIN_ALLOW_THREADS if (close(kqfd) < 0) save_errno = errno; Py_END_ALLOW_THREADS } return save_errno; } static PyObject * newKqueue_Object(PyTypeObject *type, SOCKET fd) { kqueue_queue_Object *self; assert(type != NULL && type->tp_alloc != NULL); self = (kqueue_queue_Object *) type->tp_alloc(type, 0); if (self == NULL) { return NULL; } if (fd == -1) { Py_BEGIN_ALLOW_THREADS self->kqfd = kqueue(); Py_END_ALLOW_THREADS } else { self->kqfd = fd; } if (self->kqfd < 0) { Py_DECREF(self); PyErr_SetFromErrno(PyExc_IOError); return NULL; } return (PyObject *)self; } static PyObject * kqueue_queue_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { if ((args != NULL && PyObject_Size(args)) || (kwds != NULL && PyObject_Size(kwds))) { PyErr_SetString(PyExc_ValueError, "select.kqueue doesn't accept arguments"); return NULL; } return newKqueue_Object(type, -1); } static void kqueue_queue_dealloc(kqueue_queue_Object *self) { kqueue_queue_internal_close(self); Py_TYPE(self)->tp_free(self); } static PyObject* kqueue_queue_close(kqueue_queue_Object *self) { errno = kqueue_queue_internal_close(self); if (errno < 0) { PyErr_SetFromErrno(PyExc_IOError); return NULL; } Py_RETURN_NONE; } PyDoc_STRVAR(kqueue_queue_close_doc, "close() -> None\n\ \n\ Close the kqueue control file descriptor. Further operations on the kqueue\n\ object will raise an exception."); static PyObject* kqueue_queue_get_closed(kqueue_queue_Object *self) { if (self->kqfd < 0) Py_RETURN_TRUE; else Py_RETURN_FALSE; } static PyObject* kqueue_queue_fileno(kqueue_queue_Object *self) { if (self->kqfd < 0) return kqueue_queue_err_closed(); return PyLong_FromLong(self->kqfd); } PyDoc_STRVAR(kqueue_queue_fileno_doc, "fileno() -> int\n\ \n\ Return the kqueue control file descriptor."); static PyObject* kqueue_queue_fromfd(PyObject *cls, PyObject *args) { SOCKET fd; if (!PyArg_ParseTuple(args, "i:fromfd", &fd)) return NULL; return newKqueue_Object((PyTypeObject*)cls, fd); } PyDoc_STRVAR(kqueue_queue_fromfd_doc, "fromfd(fd) -> kqueue\n\ \n\ Create a kqueue object from a given control fd."); static PyObject * kqueue_queue_control(kqueue_queue_Object *self, PyObject *args) { int nevents = 0; int gotevents = 0; int nchanges = 0; int i = 0; PyObject *otimeout = NULL; PyObject *ch = NULL; PyObject *it = NULL, *ei = NULL; PyObject *result = NULL; struct kevent *evl = NULL; struct kevent *chl = NULL; struct timespec timeoutspec; struct timespec *ptimeoutspec; if (self->kqfd < 0) return kqueue_queue_err_closed(); if (!PyArg_ParseTuple(args, "Oi|O:control", &ch, &nevents, &otimeout)) return NULL; if (nevents < 0) { PyErr_Format(PyExc_ValueError, "Length of eventlist must be 0 or positive, got %d", nevents); return NULL; } if (otimeout == Py_None || otimeout == NULL) { ptimeoutspec = NULL; } else if (PyNumber_Check(otimeout)) { double timeout; long seconds; timeout = PyFloat_AsDouble(otimeout); if (timeout == -1 && PyErr_Occurred()) return NULL; if (timeout > (double)LONG_MAX) { PyErr_SetString(PyExc_OverflowError, "timeout period too long"); return NULL; } if (timeout < 0) { PyErr_SetString(PyExc_ValueError, "timeout must be positive or None"); return NULL; } seconds = (long)timeout; timeout = timeout - (double)seconds; timeoutspec.tv_sec = seconds; timeoutspec.tv_nsec = (long)(timeout * 1E9); ptimeoutspec = &timeoutspec; } else { PyErr_Format(PyExc_TypeError, "timeout argument must be an number " "or None, got %.200s", Py_TYPE(otimeout)->tp_name); return NULL; } if (ch != NULL && ch != Py_None) { it = PyObject_GetIter(ch); if (it == NULL) { PyErr_SetString(PyExc_TypeError, "changelist is not iterable"); return NULL; } nchanges = PyObject_Size(ch); if (nchanges < 0) { goto error; } chl = PyMem_New(struct kevent, nchanges); if (chl == NULL) { PyErr_NoMemory(); goto error; } i = 0; while ((ei = PyIter_Next(it)) != NULL) { if (!kqueue_event_Check(ei)) { Py_DECREF(ei); PyErr_SetString(PyExc_TypeError, "changelist must be an iterable of " "select.kevent objects"); goto error; } else { chl[i++] = ((kqueue_event_Object *)ei)->e; } Py_DECREF(ei); } } Py_CLEAR(it); /* event list */ if (nevents) { evl = PyMem_New(struct kevent, nevents); if (evl == NULL) { PyErr_NoMemory(); goto error; } } Py_BEGIN_ALLOW_THREADS gotevents = kevent(self->kqfd, chl, nchanges, evl, nevents, ptimeoutspec); Py_END_ALLOW_THREADS if (gotevents == -1) { PyErr_SetFromErrno(PyExc_OSError); goto error; } result = PyList_New(gotevents); if (result == NULL) { goto error; } for (i = 0; i < gotevents; i++) { kqueue_event_Object *ch; ch = PyObject_New(kqueue_event_Object, &kqueue_event_Type); if (ch == NULL) { goto error; } ch->e = evl[i]; PyList_SET_ITEM(result, i, (PyObject *)ch); } PyMem_Free(chl); PyMem_Free(evl); return result; error: PyMem_Free(chl); PyMem_Free(evl); Py_XDECREF(result); Py_XDECREF(it); return NULL; } PyDoc_STRVAR(kqueue_queue_control_doc, "control(changelist, max_events[, timeout=None]) -> eventlist\n\ \n\ Calls the kernel kevent function.\n\ - changelist must be a list of kevent objects describing the changes\n\ to be made to the kernel's watch list or None.\n\ - max_events lets you specify the maximum number of events that the\n\ kernel will return.\n\ - timeout is the maximum time to wait in seconds, or else None,\n\ to wait forever. timeout accepts floats for smaller timeouts, too."); static PyMethodDef kqueue_queue_methods[] = { {"fromfd", (PyCFunction)kqueue_queue_fromfd, METH_VARARGS | METH_CLASS, kqueue_queue_fromfd_doc}, {"close", (PyCFunction)kqueue_queue_close, METH_NOARGS, kqueue_queue_close_doc}, {"fileno", (PyCFunction)kqueue_queue_fileno, METH_NOARGS, kqueue_queue_fileno_doc}, {"control", (PyCFunction)kqueue_queue_control, METH_VARARGS , kqueue_queue_control_doc}, {NULL, NULL}, }; static PyGetSetDef kqueue_queue_getsetlist[] = { {"closed", (getter)kqueue_queue_get_closed, NULL, "True if the kqueue handler is closed"}, {0}, }; PyDoc_STRVAR(kqueue_queue_doc, "Kqueue syscall wrapper.\n\ \n\ For example, to start watching a socket for input:\n\ >>> kq = kqueue()\n\ >>> sock = socket()\n\ >>> sock.connect((host, port))\n\ >>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_ADD)], 0)\n\ \n\ To wait one second for it to become writeable:\n\ >>> kq.control(None, 1, 1000)\n\ \n\ To stop listening:\n\ >>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_DELETE)], 0)"); static PyTypeObject kqueue_queue_Type = { PyVarObject_HEAD_INIT(NULL, 0) "select.kqueue", /* tp_name */ sizeof(kqueue_queue_Object), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)kqueue_queue_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ kqueue_queue_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ kqueue_queue_methods, /* tp_methods */ 0, /* tp_members */ kqueue_queue_getsetlist, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ kqueue_queue_new, /* tp_new */ 0, /* tp_free */ }; #endif /* HAVE_KQUEUE */ /* ************************************************************************ */ PyDoc_STRVAR(select_doc, "select(rlist, wlist, xlist[, timeout]) -> (rlist, wlist, xlist)\n\ \n\ Wait until one or more file descriptors are ready for some kind of I/O.\n\ The first three arguments are sequences of file descriptors to be waited for:\n\ rlist -- wait until ready for reading\n\ wlist -- wait until ready for writing\n\ xlist -- wait for an ``exceptional condition''\n\ If only one kind of condition is required, pass [] for the other lists.\n\ A file descriptor is either a socket or file object, or a small integer\n\ gotten from a fileno() method call on one of those.\n\ \n\ The optional 4th argument specifies a timeout in seconds; it may be\n\ a floating point number to specify fractions of seconds. If it is absent\n\ or None, the call will never time out.\n\ \n\ The return value is a tuple of three lists corresponding to the first three\n\ arguments; each contains the subset of the corresponding file descriptors\n\ that are ready.\n\ \n\ *** IMPORTANT NOTICE ***\n\ On Windows and OpenVMS, only sockets are supported; on Unix, all file\n\ descriptors can be used."); static PyMethodDef select_methods[] = { {"select", select_select, METH_VARARGS, select_doc}, #ifdef HAVE_POLL {"poll", select_poll, METH_NOARGS, poll_doc}, #endif /* HAVE_POLL */ {0, 0}, /* sentinel */ }; PyDoc_STRVAR(module_doc, "This module supports asynchronous I/O on multiple file descriptors.\n\ \n\ *** IMPORTANT NOTICE ***\n\ On Windows and OpenVMS, only sockets are supported; on Unix, all file descriptors."); static struct PyModuleDef selectmodule = { PyModuleDef_HEAD_INIT, "select", module_doc, -1, select_methods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_select(void) { PyObject *m; m = PyModule_Create(&selectmodule); if (m == NULL) return NULL; SelectError = PyErr_NewException("select.error", NULL, NULL); Py_INCREF(SelectError); PyModule_AddObject(m, "error", SelectError); #ifdef PIPE_BUF #ifdef HAVE_BROKEN_PIPE_BUF #undef PIPE_BUF #define PIPE_BUF 512 #endif PyModule_AddIntConstant(m, "PIPE_BUF", PIPE_BUF); #endif #if defined(HAVE_POLL) #ifdef __APPLE__ if (select_have_broken_poll()) { if (PyObject_DelAttrString(m, "poll") == -1) { PyErr_Clear(); } } else { #else { #endif if (PyType_Ready(&poll_Type) < 0) return NULL; PyModule_AddIntConstant(m, "POLLIN", POLLIN); PyModule_AddIntConstant(m, "POLLPRI", POLLPRI); PyModule_AddIntConstant(m, "POLLOUT", POLLOUT); PyModule_AddIntConstant(m, "POLLERR", POLLERR); PyModule_AddIntConstant(m, "POLLHUP", POLLHUP); PyModule_AddIntConstant(m, "POLLNVAL", POLLNVAL); #ifdef POLLRDNORM PyModule_AddIntConstant(m, "POLLRDNORM", POLLRDNORM); #endif #ifdef POLLRDBAND PyModule_AddIntConstant(m, "POLLRDBAND", POLLRDBAND); #endif #ifdef POLLWRNORM PyModule_AddIntConstant(m, "POLLWRNORM", POLLWRNORM); #endif #ifdef POLLWRBAND PyModule_AddIntConstant(m, "POLLWRBAND", POLLWRBAND); #endif #ifdef POLLMSG PyModule_AddIntConstant(m, "POLLMSG", POLLMSG); #endif } #endif /* HAVE_POLL */ #ifdef HAVE_EPOLL Py_TYPE(&pyEpoll_Type) = &PyType_Type; if (PyType_Ready(&pyEpoll_Type) < 0) return NULL; Py_INCREF(&pyEpoll_Type); PyModule_AddObject(m, "epoll", (PyObject *) &pyEpoll_Type); PyModule_AddIntConstant(m, "EPOLLIN", EPOLLIN); PyModule_AddIntConstant(m, "EPOLLOUT", EPOLLOUT); PyModule_AddIntConstant(m, "EPOLLPRI", EPOLLPRI); PyModule_AddIntConstant(m, "EPOLLERR", EPOLLERR); PyModule_AddIntConstant(m, "EPOLLHUP", EPOLLHUP); PyModule_AddIntConstant(m, "EPOLLET", EPOLLET); #ifdef EPOLLONESHOT /* Kernel 2.6.2+ */ PyModule_AddIntConstant(m, "EPOLLONESHOT", EPOLLONESHOT); #endif /* PyModule_AddIntConstant(m, "EPOLL_RDHUP", EPOLLRDHUP); */ PyModule_AddIntConstant(m, "EPOLLRDNORM", EPOLLRDNORM); PyModule_AddIntConstant(m, "EPOLLRDBAND", EPOLLRDBAND); PyModule_AddIntConstant(m, "EPOLLWRNORM", EPOLLWRNORM); PyModule_AddIntConstant(m, "EPOLLWRBAND", EPOLLWRBAND); PyModule_AddIntConstant(m, "EPOLLMSG", EPOLLMSG); #endif /* HAVE_EPOLL */ #ifdef HAVE_KQUEUE kqueue_event_Type.tp_new = PyType_GenericNew; Py_TYPE(&kqueue_event_Type) = &PyType_Type; if(PyType_Ready(&kqueue_event_Type) < 0) return NULL; Py_INCREF(&kqueue_event_Type); PyModule_AddObject(m, "kevent", (PyObject *)&kqueue_event_Type); Py_TYPE(&kqueue_queue_Type) = &PyType_Type; if(PyType_Ready(&kqueue_queue_Type) < 0) return NULL; Py_INCREF(&kqueue_queue_Type); PyModule_AddObject(m, "kqueue", (PyObject *)&kqueue_queue_Type); /* event filters */ PyModule_AddIntConstant(m, "KQ_FILTER_READ", EVFILT_READ); PyModule_AddIntConstant(m, "KQ_FILTER_WRITE", EVFILT_WRITE); PyModule_AddIntConstant(m, "KQ_FILTER_AIO", EVFILT_AIO); PyModule_AddIntConstant(m, "KQ_FILTER_VNODE", EVFILT_VNODE); PyModule_AddIntConstant(m, "KQ_FILTER_PROC", EVFILT_PROC); #ifdef EVFILT_NETDEV PyModule_AddIntConstant(m, "KQ_FILTER_NETDEV", EVFILT_NETDEV); #endif PyModule_AddIntConstant(m, "KQ_FILTER_SIGNAL", EVFILT_SIGNAL); PyModule_AddIntConstant(m, "KQ_FILTER_TIMER", EVFILT_TIMER); /* event flags */ PyModule_AddIntConstant(m, "KQ_EV_ADD", EV_ADD); PyModule_AddIntConstant(m, "KQ_EV_DELETE", EV_DELETE); PyModule_AddIntConstant(m, "KQ_EV_ENABLE", EV_ENABLE); PyModule_AddIntConstant(m, "KQ_EV_DISABLE", EV_DISABLE); PyModule_AddIntConstant(m, "KQ_EV_ONESHOT", EV_ONESHOT); PyModule_AddIntConstant(m, "KQ_EV_CLEAR", EV_CLEAR); PyModule_AddIntConstant(m, "KQ_EV_SYSFLAGS", EV_SYSFLAGS); PyModule_AddIntConstant(m, "KQ_EV_FLAG1", EV_FLAG1); PyModule_AddIntConstant(m, "KQ_EV_EOF", EV_EOF); PyModule_AddIntConstant(m, "KQ_EV_ERROR", EV_ERROR); /* READ WRITE filter flag */ PyModule_AddIntConstant(m, "KQ_NOTE_LOWAT", NOTE_LOWAT); /* VNODE filter flags */ PyModule_AddIntConstant(m, "KQ_NOTE_DELETE", NOTE_DELETE); PyModule_AddIntConstant(m, "KQ_NOTE_WRITE", NOTE_WRITE); PyModule_AddIntConstant(m, "KQ_NOTE_EXTEND", NOTE_EXTEND); PyModule_AddIntConstant(m, "KQ_NOTE_ATTRIB", NOTE_ATTRIB); PyModule_AddIntConstant(m, "KQ_NOTE_LINK", NOTE_LINK); PyModule_AddIntConstant(m, "KQ_NOTE_RENAME", NOTE_RENAME); PyModule_AddIntConstant(m, "KQ_NOTE_REVOKE", NOTE_REVOKE); /* PROC filter flags */ PyModule_AddIntConstant(m, "KQ_NOTE_EXIT", NOTE_EXIT); PyModule_AddIntConstant(m, "KQ_NOTE_FORK", NOTE_FORK); PyModule_AddIntConstant(m, "KQ_NOTE_EXEC", NOTE_EXEC); PyModule_AddIntConstant(m, "KQ_NOTE_PCTRLMASK", NOTE_PCTRLMASK); PyModule_AddIntConstant(m, "KQ_NOTE_PDATAMASK", NOTE_PDATAMASK); PyModule_AddIntConstant(m, "KQ_NOTE_TRACK", NOTE_TRACK); PyModule_AddIntConstant(m, "KQ_NOTE_CHILD", NOTE_CHILD); PyModule_AddIntConstant(m, "KQ_NOTE_TRACKERR", NOTE_TRACKERR); /* NETDEV filter flags */ #ifdef EVFILT_NETDEV PyModule_AddIntConstant(m, "KQ_NOTE_LINKUP", NOTE_LINKUP); PyModule_AddIntConstant(m, "KQ_NOTE_LINKDOWN", NOTE_LINKDOWN); PyModule_AddIntConstant(m, "KQ_NOTE_LINKINV", NOTE_LINKINV); #endif #endif /* HAVE_KQUEUE */ return m; }
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/python_69223-69224.c
manybugs_data_84
/* Generated by re2c 0.13.5 on Wed Feb 15 17:27:19 2012 */ #line 1 "Zend/zend_language_scanner.l" /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2012 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Marcus Boerger <[email protected]> | | Nuno Lopes <[email protected]> | | Scott MacVicar <[email protected]> | | Flex version authors: | | Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #if 0 # define YYDEBUG(s, c) printf("state: %d char: %c\n", s, c) #else # define YYDEBUG(s, c) #endif #include "zend_language_scanner_defs.h" #include <errno.h> #include "zend.h" #include "zend_alloc.h" #include <zend_language_parser.h> #include "zend_compile.h" #include "zend_language_scanner.h" #include "zend_highlight.h" #include "zend_constants.h" #include "zend_variables.h" #include "zend_operators.h" #include "zend_API.h" #include "zend_strtod.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "tsrm_config_common.h" #define YYCTYPE unsigned char #define YYFILL(n) { if ((YYCURSOR + n) >= (YYLIMIT + ZEND_MMAP_AHEAD)) { return 0; } } #define YYCURSOR SCNG(yy_cursor) #define YYLIMIT SCNG(yy_limit) #define YYMARKER SCNG(yy_marker) #define YYGETCONDITION() SCNG(yy_state) #define YYSETCONDITION(s) SCNG(yy_state) = s #define STATE(name) yyc##name /* emulate flex constructs */ #define BEGIN(state) YYSETCONDITION(STATE(state)) #define YYSTATE YYGETCONDITION() #define yytext ((char*)SCNG(yy_text)) #define yyleng SCNG(yy_leng) #define yyless(x) do { YYCURSOR = (unsigned char*)yytext + x; \ yyleng = (unsigned int)x; } while(0) #define yymore() goto yymore_restart /* perform sanity check. If this message is triggered you should increase the ZEND_MMAP_AHEAD value in the zend_streams.h file */ #define YYMAXFILL 16 #if ZEND_MMAP_AHEAD < YYMAXFILL # error ZEND_MMAP_AHEAD should be greater than or equal to YYMAXFILL #endif #ifdef HAVE_STDARG_H # include <stdarg.h> #endif #ifdef HAVE_UNISTD_H # include <unistd.h> #endif /* Globals Macros */ #define SCNG LANG_SCNG #ifdef ZTS ZEND_API ts_rsrc_id language_scanner_globals_id; #else ZEND_API zend_php_scanner_globals language_scanner_globals; #endif #define HANDLE_NEWLINES(s, l) \ do { \ char *p = (s), *boundary = p+(l); \ \ while (p<boundary) { \ if (*p == '\n' || (*p == '\r' && (*(p+1) != '\n'))) { \ CG(zend_lineno)++; \ } \ p++; \ } \ } while (0) #define HANDLE_NEWLINE(c) \ { \ if (c == '\n' || c == '\r') { \ CG(zend_lineno)++; \ } \ } /* To save initial string length after scanning to first variable, CG(doc_comment_len) can be reused */ #define SET_DOUBLE_QUOTES_SCANNED_LENGTH(len) CG(doc_comment_len) = (len) #define GET_DOUBLE_QUOTES_SCANNED_LENGTH() CG(doc_comment_len) #define IS_LABEL_START(c) (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z') || (c) == '_' || (c) >= 0x7F) #define ZEND_IS_OCT(c) ((c)>='0' && (c)<='7') #define ZEND_IS_HEX(c) (((c)>='0' && (c)<='9') || ((c)>='a' && (c)<='f') || ((c)>='A' && (c)<='F')) BEGIN_EXTERN_C() static size_t encoding_filter_script_to_internal(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) { const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding(TSRMLS_C); assert(internal_encoding && zend_multibyte_check_lexer_compatibility(internal_encoding)); return zend_multibyte_encoding_converter(to, to_length, from, from_length, internal_encoding, LANG_SCNG(script_encoding) TSRMLS_CC); } static size_t encoding_filter_script_to_intermediate(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) { return zend_multibyte_encoding_converter(to, to_length, from, from_length, zend_multibyte_encoding_utf8, LANG_SCNG(script_encoding) TSRMLS_CC); } static size_t encoding_filter_intermediate_to_script(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) { return zend_multibyte_encoding_converter(to, to_length, from, from_length, LANG_SCNG(script_encoding), zend_multibyte_encoding_utf8 TSRMLS_CC); } static size_t encoding_filter_intermediate_to_internal(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) { const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding(TSRMLS_C); assert(internal_encoding && zend_multibyte_check_lexer_compatibility(internal_encoding)); return zend_multibyte_encoding_converter(to, to_length, from, from_length, internal_encoding, zend_multibyte_encoding_utf8 TSRMLS_CC); } static void _yy_push_state(int new_state TSRMLS_DC) { zend_stack_push(&SCNG(state_stack), (void *) &YYGETCONDITION(), sizeof(int)); YYSETCONDITION(new_state); } #define yy_push_state(state_and_tsrm) _yy_push_state(yyc##state_and_tsrm) static void yy_pop_state(TSRMLS_D) { int *stack_state; zend_stack_top(&SCNG(state_stack), (void **) &stack_state); YYSETCONDITION(*stack_state); zend_stack_del_top(&SCNG(state_stack)); } static void yy_scan_buffer(char *str, unsigned int len TSRMLS_DC) { YYCURSOR = (YYCTYPE*)str; YYLIMIT = YYCURSOR + len; if (!SCNG(yy_start)) { SCNG(yy_start) = YYCURSOR; } } void startup_scanner(TSRMLS_D) { CG(parse_error) = 0; CG(heredoc) = NULL; CG(heredoc_len) = 0; CG(doc_comment) = NULL; CG(doc_comment_len) = 0; zend_stack_init(&SCNG(state_stack)); } void shutdown_scanner(TSRMLS_D) { if (CG(heredoc)) { efree(CG(heredoc)); CG(heredoc_len)=0; } CG(parse_error) = 0; zend_stack_destroy(&SCNG(state_stack)); RESET_DOC_COMMENT(); } ZEND_API void zend_save_lexical_state(zend_lex_state *lex_state TSRMLS_DC) { lex_state->yy_leng = SCNG(yy_leng); lex_state->yy_start = SCNG(yy_start); lex_state->yy_text = SCNG(yy_text); lex_state->yy_cursor = SCNG(yy_cursor); lex_state->yy_marker = SCNG(yy_marker); lex_state->yy_limit = SCNG(yy_limit); lex_state->state_stack = SCNG(state_stack); zend_stack_init(&SCNG(state_stack)); lex_state->in = SCNG(yy_in); lex_state->yy_state = YYSTATE; lex_state->filename = zend_get_compiled_filename(TSRMLS_C); lex_state->lineno = CG(zend_lineno); lex_state->script_org = SCNG(script_org); lex_state->script_org_size = SCNG(script_org_size); lex_state->script_filtered = SCNG(script_filtered); lex_state->script_filtered_size = SCNG(script_filtered_size); lex_state->input_filter = SCNG(input_filter); lex_state->output_filter = SCNG(output_filter); lex_state->script_encoding = SCNG(script_encoding); } ZEND_API void zend_restore_lexical_state(zend_lex_state *lex_state TSRMLS_DC) { SCNG(yy_leng) = lex_state->yy_leng; SCNG(yy_start) = lex_state->yy_start; SCNG(yy_text) = lex_state->yy_text; SCNG(yy_cursor) = lex_state->yy_cursor; SCNG(yy_marker) = lex_state->yy_marker; SCNG(yy_limit) = lex_state->yy_limit; zend_stack_destroy(&SCNG(state_stack)); SCNG(state_stack) = lex_state->state_stack; SCNG(yy_in) = lex_state->in; YYSETCONDITION(lex_state->yy_state); CG(zend_lineno) = lex_state->lineno; zend_restore_compiled_filename(lex_state->filename TSRMLS_CC); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } SCNG(script_org) = lex_state->script_org; SCNG(script_org_size) = lex_state->script_org_size; SCNG(script_filtered) = lex_state->script_filtered; SCNG(script_filtered_size) = lex_state->script_filtered_size; SCNG(input_filter) = lex_state->input_filter; SCNG(output_filter) = lex_state->output_filter; SCNG(script_encoding) = lex_state->script_encoding; if (CG(heredoc)) { efree(CG(heredoc)); CG(heredoc) = NULL; CG(heredoc_len) = 0; } } ZEND_API void zend_destroy_file_handle(zend_file_handle *file_handle TSRMLS_DC) { zend_llist_del_element(&CG(open_files), file_handle, (int (*)(void *, void *)) zend_compare_file_handles); /* zend_file_handle_dtor() operates on the copy, so we have to NULLify the original here */ file_handle->opened_path = NULL; if (file_handle->free_filename) { file_handle->filename = NULL; } } #define BOM_UTF32_BE "\x00\x00\xfe\xff" #define BOM_UTF32_LE "\xff\xfe\x00\x00" #define BOM_UTF16_BE "\xfe\xff" #define BOM_UTF16_LE "\xff\xfe" #define BOM_UTF8 "\xef\xbb\xbf" static const zend_encoding *zend_multibyte_detect_utf_encoding(const unsigned char *script, size_t script_size TSRMLS_DC) { const unsigned char *p; int wchar_size = 2; int le = 0; /* utf-16 or utf-32? */ p = script; while ((p-script) < script_size) { p = memchr(p, 0, script_size-(p-script)-2); if (!p) { break; } if (*(p+1) == '\0' && *(p+2) == '\0') { wchar_size = 4; break; } /* searching for UTF-32 specific byte orders, so this will do */ p += 4; } /* BE or LE? */ p = script; while ((p-script) < script_size) { if (*p == '\0' && *(p+wchar_size-1) != '\0') { /* BE */ le = 0; break; } else if (*p != '\0' && *(p+wchar_size-1) == '\0') { /* LE* */ le = 1; break; } p += wchar_size; } if (wchar_size == 2) { return le ? zend_multibyte_encoding_utf16le : zend_multibyte_encoding_utf16be; } else { return le ? zend_multibyte_encoding_utf32le : zend_multibyte_encoding_utf32be; } return NULL; } static const zend_encoding* zend_multibyte_detect_unicode(TSRMLS_D) { const zend_encoding *script_encoding = NULL; int bom_size; unsigned char *pos1, *pos2; if (LANG_SCNG(script_org_size) < sizeof(BOM_UTF32_LE)-1) { return NULL; } /* check out BOM */ if (!memcmp(LANG_SCNG(script_org), BOM_UTF32_BE, sizeof(BOM_UTF32_BE)-1)) { script_encoding = zend_multibyte_encoding_utf32be; bom_size = sizeof(BOM_UTF32_BE)-1; } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF32_LE, sizeof(BOM_UTF32_LE)-1)) { script_encoding = zend_multibyte_encoding_utf32le; bom_size = sizeof(BOM_UTF32_LE)-1; } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF16_BE, sizeof(BOM_UTF16_BE)-1)) { script_encoding = zend_multibyte_encoding_utf16be; bom_size = sizeof(BOM_UTF16_BE)-1; } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF16_LE, sizeof(BOM_UTF16_LE)-1)) { script_encoding = zend_multibyte_encoding_utf16le; bom_size = sizeof(BOM_UTF16_LE)-1; } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF8, sizeof(BOM_UTF8)-1)) { script_encoding = zend_multibyte_encoding_utf8; bom_size = sizeof(BOM_UTF8)-1; } if (script_encoding) { /* remove BOM */ LANG_SCNG(script_org) += bom_size; LANG_SCNG(script_org_size) -= bom_size; return script_encoding; } /* script contains NULL bytes -> auto-detection */ if ((pos1 = memchr(LANG_SCNG(script_org), 0, LANG_SCNG(script_org_size)))) { /* check if the NULL byte is after the __HALT_COMPILER(); */ pos2 = LANG_SCNG(script_org); while (pos1 - pos2 >= sizeof("__HALT_COMPILER();")-1) { pos2 = memchr(pos2, '_', pos1 - pos2); if (!pos2) break; pos2++; if (strncasecmp((char*)pos2, "_HALT_COMPILER", sizeof("_HALT_COMPILER")-1) == 0) { pos2 += sizeof("_HALT_COMPILER")-1; while (*pos2 == ' ' || *pos2 == '\t' || *pos2 == '\r' || *pos2 == '\n') { pos2++; } if (*pos2 == '(') { pos2++; while (*pos2 == ' ' || *pos2 == '\t' || *pos2 == '\r' || *pos2 == '\n') { pos2++; } if (*pos2 == ')') { pos2++; while (*pos2 == ' ' || *pos2 == '\t' || *pos2 == '\r' || *pos2 == '\n') { pos2++; } if (*pos2 == ';') { return NULL; } } } } } /* make best effort if BOM is missing */ return zend_multibyte_detect_utf_encoding(LANG_SCNG(script_org), LANG_SCNG(script_org_size) TSRMLS_CC); } return NULL; } static const zend_encoding* zend_multibyte_find_script_encoding(TSRMLS_D) { const zend_encoding *script_encoding; if (CG(detect_unicode)) { /* check out bom(byte order mark) and see if containing wchars */ script_encoding = zend_multibyte_detect_unicode(TSRMLS_C); if (script_encoding != NULL) { /* bom or wchar detection is prior to 'script_encoding' option */ return script_encoding; } } /* if no script_encoding specified, just leave alone */ if (!CG(script_encoding_list) || !CG(script_encoding_list_size)) { return NULL; } /* if multiple encodings specified, detect automagically */ if (CG(script_encoding_list_size) > 1) { return zend_multibyte_encoding_detector(LANG_SCNG(script_org), LANG_SCNG(script_org_size), CG(script_encoding_list), CG(script_encoding_list_size) TSRMLS_CC); } return CG(script_encoding_list)[0]; } ZEND_API int zend_multibyte_set_filter(const zend_encoding *onetime_encoding TSRMLS_DC) { const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding(TSRMLS_C); const zend_encoding *script_encoding = onetime_encoding ? onetime_encoding: zend_multibyte_find_script_encoding(TSRMLS_C); if (!script_encoding) { return FAILURE; } /* judge input/output filter */ LANG_SCNG(script_encoding) = script_encoding; LANG_SCNG(input_filter) = NULL; LANG_SCNG(output_filter) = NULL; if (!internal_encoding || LANG_SCNG(script_encoding) == internal_encoding) { if (!zend_multibyte_check_lexer_compatibility(LANG_SCNG(script_encoding))) { /* and if not, work around w/ script_encoding -> utf-8 -> script_encoding conversion */ LANG_SCNG(input_filter) = encoding_filter_script_to_intermediate; LANG_SCNG(output_filter) = encoding_filter_intermediate_to_script; } else { LANG_SCNG(input_filter) = NULL; LANG_SCNG(output_filter) = NULL; } return SUCCESS; } if (zend_multibyte_check_lexer_compatibility(internal_encoding)) { LANG_SCNG(input_filter) = encoding_filter_script_to_internal; LANG_SCNG(output_filter) = NULL; } else if (zend_multibyte_check_lexer_compatibility(LANG_SCNG(script_encoding))) { LANG_SCNG(input_filter) = NULL; LANG_SCNG(output_filter) = encoding_filter_script_to_internal; } else { /* both script and internal encodings are incompatible w/ flex */ LANG_SCNG(input_filter) = encoding_filter_script_to_intermediate; LANG_SCNG(output_filter) = encoding_filter_intermediate_to_internal; } return 0; } ZEND_API int open_file_for_scanning(zend_file_handle *file_handle TSRMLS_DC) { const char *file_path = NULL; char *buf; size_t size, offset = 0; /* The shebang line was read, get the current position to obtain the buffer start */ if (CG(start_lineno) == 2 && file_handle->type == ZEND_HANDLE_FP && file_handle->handle.fp) { if ((offset = ftell(file_handle->handle.fp)) == -1) { offset = 0; } } if (zend_stream_fixup(file_handle, &buf, &size TSRMLS_CC) == FAILURE) { return FAILURE; } zend_llist_add_element(&CG(open_files), file_handle); if (file_handle->handle.stream.handle >= (void*)file_handle && file_handle->handle.stream.handle <= (void*)(file_handle+1)) { zend_file_handle *fh = (zend_file_handle*)zend_llist_get_last(&CG(open_files)); size_t diff = (char*)file_handle->handle.stream.handle - (char*)file_handle; fh->handle.stream.handle = (void*)(((char*)fh) + diff); file_handle->handle.stream.handle = fh->handle.stream.handle; } /* Reset the scanner for scanning the new file */ SCNG(yy_in) = file_handle; SCNG(yy_start) = NULL; if (size != -1) { if (CG(multibyte)) { SCNG(script_org) = (unsigned char*)buf; SCNG(script_org_size) = size; SCNG(script_filtered) = NULL; zend_multibyte_set_filter(NULL TSRMLS_CC); if (SCNG(input_filter)) { if ((size_t)-1 == SCNG(input_filter)(&SCNG(script_filtered), &SCNG(script_filtered_size), SCNG(script_org), SCNG(script_org_size) TSRMLS_CC)) { zend_error_noreturn(E_COMPILE_ERROR, "Could not convert the script from the detected " "encoding \"%s\" to a compatible encoding", zend_multibyte_get_encoding_name(LANG_SCNG(script_encoding))); } buf = (char*)SCNG(script_filtered); size = SCNG(script_filtered_size); } } SCNG(yy_start) = (unsigned char *)buf - offset; yy_scan_buffer(buf, size TSRMLS_CC); } else { zend_error_noreturn(E_COMPILE_ERROR, "zend_stream_mmap() failed"); } BEGIN(INITIAL); if (file_handle->opened_path) { file_path = file_handle->opened_path; } else { file_path = file_handle->filename; } zend_set_compiled_filename(file_path TSRMLS_CC); if (CG(start_lineno)) { CG(zend_lineno) = CG(start_lineno); CG(start_lineno) = 0; } else { CG(zend_lineno) = 1; } CG(increment_lineno) = 0; return SUCCESS; } END_EXTERN_C() ZEND_API zend_op_array *compile_file(zend_file_handle *file_handle, int type TSRMLS_DC) { zend_lex_state original_lex_state; zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array)); zend_op_array *original_active_op_array = CG(active_op_array); zend_op_array *retval=NULL; int compiler_result; zend_bool compilation_successful=0; znode retval_znode; zend_bool original_in_compilation = CG(in_compilation); retval_znode.op_type = IS_CONST; retval_znode.u.constant.type = IS_LONG; retval_znode.u.constant.value.lval = 1; Z_UNSET_ISREF(retval_znode.u.constant); Z_SET_REFCOUNT(retval_znode.u.constant, 1); zend_save_lexical_state(&original_lex_state TSRMLS_CC); retval = op_array; /* success oriented */ if (open_file_for_scanning(file_handle TSRMLS_CC)==FAILURE) { if (type==ZEND_REQUIRE) { zend_message_dispatcher(ZMSG_FAILED_REQUIRE_FOPEN, file_handle->filename TSRMLS_CC); zend_bailout(); } else { zend_message_dispatcher(ZMSG_FAILED_INCLUDE_FOPEN, file_handle->filename TSRMLS_CC); } compilation_successful=0; } else { init_op_array(op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(in_compilation) = 1; CG(active_op_array) = op_array; zend_init_compiler_context(TSRMLS_C); compiler_result = zendparse(TSRMLS_C); zend_do_return(&retval_znode, 0 TSRMLS_CC); CG(in_compilation) = original_in_compilation; if (compiler_result==1) { /* parser error */ zend_bailout(); } compilation_successful=1; } if (retval) { CG(active_op_array) = original_active_op_array; if (compilation_successful) { pass_two(op_array TSRMLS_CC); zend_release_labels(TSRMLS_C); } else { efree(op_array); retval = NULL; } } zend_restore_lexical_state(&original_lex_state TSRMLS_CC); return retval; } zend_op_array *compile_filename(int type, zval *filename TSRMLS_DC) { zend_file_handle file_handle; zval tmp; zend_op_array *retval; char *opened_path = NULL; if (filename->type != IS_STRING) { tmp = *filename; zval_copy_ctor(&tmp); convert_to_string(&tmp); filename = &tmp; } file_handle.filename = filename->value.str.val; file_handle.free_filename = 0; file_handle.type = ZEND_HANDLE_FILENAME; file_handle.opened_path = NULL; file_handle.handle.fp = NULL; retval = zend_compile_file(&file_handle, type TSRMLS_CC); if (retval && file_handle.handle.stream.handle) { int dummy = 1; if (!file_handle.opened_path) { file_handle.opened_path = opened_path = estrndup(filename->value.str.val, filename->value.str.len); } zend_hash_add(&EG(included_files), file_handle.opened_path, strlen(file_handle.opened_path)+1, (void *)&dummy, sizeof(int), NULL); if (opened_path) { efree(opened_path); } } zend_destroy_file_handle(&file_handle TSRMLS_CC); if (filename==&tmp) { zval_dtor(&tmp); } return retval; } ZEND_API int zend_prepare_string_for_scanning(zval *str, char *filename TSRMLS_DC) { char *buf; size_t size; /* enforce two trailing NULLs for flex... */ if (IS_INTERNED(str->value.str.val)) { char *tmp = safe_emalloc(1, str->value.str.len, ZEND_MMAP_AHEAD); memcpy(tmp, str->value.str.val, str->value.str.len + ZEND_MMAP_AHEAD); str->value.str.val = tmp; } else { str->value.str.val = safe_erealloc(str->value.str.val, 1, str->value.str.len, ZEND_MMAP_AHEAD); } memset(str->value.str.val + str->value.str.len, 0, ZEND_MMAP_AHEAD); SCNG(yy_in) = NULL; SCNG(yy_start) = NULL; buf = str->value.str.val; size = str->value.str.len; if (CG(multibyte)) { SCNG(script_org) = (unsigned char*)buf; SCNG(script_org_size) = size; SCNG(script_filtered) = NULL; zend_multibyte_set_filter(zend_multibyte_get_internal_encoding(TSRMLS_C) TSRMLS_CC); if (SCNG(input_filter)) { if ((size_t)-1 == SCNG(input_filter)(&SCNG(script_filtered), &SCNG(script_filtered_size), SCNG(script_org), SCNG(script_org_size) TSRMLS_CC)) { zend_error_noreturn(E_COMPILE_ERROR, "Could not convert the script from the detected " "encoding \"%s\" to a compatible encoding", zend_multibyte_get_encoding_name(LANG_SCNG(script_encoding))); } buf = (char*)SCNG(script_filtered); size = SCNG(script_filtered_size); } } yy_scan_buffer(buf, size TSRMLS_CC); zend_set_compiled_filename(filename TSRMLS_CC); CG(zend_lineno) = 1; CG(increment_lineno) = 0; return SUCCESS; } ZEND_API size_t zend_get_scanned_file_offset(TSRMLS_D) { size_t offset = SCNG(yy_cursor) - SCNG(yy_start); if (SCNG(input_filter)) { size_t original_offset = offset, length = 0; do { unsigned char *p = NULL; if ((size_t)-1 == SCNG(input_filter)(&p, &length, SCNG(script_org), offset TSRMLS_CC)) { return (size_t)-1; } efree(p); if (length > original_offset) { offset--; } else if (length < original_offset) { offset++; } } while (original_offset != length); } return offset; } zend_op_array *compile_string(zval *source_string, char *filename TSRMLS_DC) { zend_lex_state original_lex_state; zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array)); zend_op_array *original_active_op_array = CG(active_op_array); zend_op_array *retval; zval tmp; int compiler_result; zend_bool original_in_compilation = CG(in_compilation); if (source_string->value.str.len==0) { efree(op_array); return NULL; } CG(in_compilation) = 1; tmp = *source_string; zval_copy_ctor(&tmp); convert_to_string(&tmp); source_string = &tmp; zend_save_lexical_state(&original_lex_state TSRMLS_CC); if (zend_prepare_string_for_scanning(source_string, filename TSRMLS_CC)==FAILURE) { efree(op_array); retval = NULL; } else { zend_bool orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(op_array, ZEND_EVAL_CODE, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; CG(active_op_array) = op_array; zend_init_compiler_context(TSRMLS_C); BEGIN(ST_IN_SCRIPTING); compiler_result = zendparse(TSRMLS_C); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } if (compiler_result==1) { CG(active_op_array) = original_active_op_array; CG(unclean_shutdown)=1; destroy_op_array(op_array TSRMLS_CC); efree(op_array); retval = NULL; } else { zend_do_return(NULL, 0 TSRMLS_CC); CG(active_op_array) = original_active_op_array; pass_two(op_array TSRMLS_CC); zend_release_labels(TSRMLS_C); retval = op_array; } } zend_restore_lexical_state(&original_lex_state TSRMLS_CC); zval_dtor(&tmp); CG(in_compilation) = original_in_compilation; return retval; } BEGIN_EXTERN_C() int highlight_file(char *filename, zend_syntax_highlighter_ini *syntax_highlighter_ini TSRMLS_DC) { zend_lex_state original_lex_state; zend_file_handle file_handle; file_handle.type = ZEND_HANDLE_FILENAME; file_handle.filename = filename; file_handle.free_filename = 0; file_handle.opened_path = NULL; zend_save_lexical_state(&original_lex_state TSRMLS_CC); if (open_file_for_scanning(&file_handle TSRMLS_CC)==FAILURE) { zend_message_dispatcher(ZMSG_FAILED_HIGHLIGHT_FOPEN, filename TSRMLS_CC); zend_restore_lexical_state(&original_lex_state TSRMLS_CC); return FAILURE; } zend_highlight(syntax_highlighter_ini TSRMLS_CC); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } zend_destroy_file_handle(&file_handle TSRMLS_CC); zend_restore_lexical_state(&original_lex_state TSRMLS_CC); return SUCCESS; } int highlight_string(zval *str, zend_syntax_highlighter_ini *syntax_highlighter_ini, char *str_name TSRMLS_DC) { zend_lex_state original_lex_state; zval tmp = *str; str = &tmp; zval_copy_ctor(str); zend_save_lexical_state(&original_lex_state TSRMLS_CC); if (zend_prepare_string_for_scanning(str, str_name TSRMLS_CC)==FAILURE) { zend_restore_lexical_state(&original_lex_state TSRMLS_CC); return FAILURE; } BEGIN(INITIAL); zend_highlight(syntax_highlighter_ini TSRMLS_CC); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } zend_restore_lexical_state(&original_lex_state TSRMLS_CC); zval_dtor(str); return SUCCESS; } ZEND_API void zend_multibyte_yyinput_again(zend_encoding_filter old_input_filter, const zend_encoding *old_encoding TSRMLS_DC) { size_t length; unsigned char *new_yy_start; /* convert and set */ if (!SCNG(input_filter)) { if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } SCNG(script_filtered_size) = 0; length = SCNG(script_org_size); new_yy_start = SCNG(script_org); } else { if ((size_t)-1 == SCNG(input_filter)(&new_yy_start, &length, SCNG(script_org), SCNG(script_org_size) TSRMLS_CC)) { zend_error_noreturn(E_COMPILE_ERROR, "Could not convert the script from the detected " "encoding \"%s\" to a compatible encoding", zend_multibyte_get_encoding_name(LANG_SCNG(script_encoding))); } SCNG(script_filtered) = new_yy_start; SCNG(script_filtered_size) = length; } SCNG(yy_cursor) = new_yy_start + (SCNG(yy_cursor) - SCNG(yy_start)); SCNG(yy_marker) = new_yy_start + (SCNG(yy_marker) - SCNG(yy_start)); SCNG(yy_text) = new_yy_start + (SCNG(yy_text) - SCNG(yy_start)); SCNG(yy_limit) = new_yy_start + (SCNG(yy_limit) - SCNG(yy_start)); SCNG(yy_start) = new_yy_start; } # define zend_copy_value(zendlval, yytext, yyleng) \ if (SCNG(output_filter)) { \ size_t sz = 0; \ SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)yytext, (size_t)yyleng TSRMLS_CC); \ zendlval->value.str.len = sz; \ } else { \ zendlval->value.str.val = (char *) estrndup(yytext, yyleng); \ zendlval->value.str.len = yyleng; \ } static void zend_scan_escape_string(zval *zendlval, char *str, int len, char quote_type TSRMLS_DC) { register char *s, *t; char *end; ZVAL_STRINGL(zendlval, str, len, 1); /* convert escape sequences */ s = t = zendlval->value.str.val; end = s+zendlval->value.str.len; while (s<end) { if (*s=='\\') { s++; if (s >= end) { *t++ = '\\'; break; } switch(*s) { case 'n': *t++ = '\n'; zendlval->value.str.len--; break; case 'r': *t++ = '\r'; zendlval->value.str.len--; break; case 't': *t++ = '\t'; zendlval->value.str.len--; break; case 'f': *t++ = '\f'; zendlval->value.str.len--; break; case 'v': *t++ = '\v'; zendlval->value.str.len--; break; case 'e': *t++ = '\e'; zendlval->value.str.len--; break; case '"': case '`': if (*s != quote_type) { *t++ = '\\'; *t++ = *s; break; } case '\\': case '$': *t++ = *s; zendlval->value.str.len--; break; case 'x': case 'X': if (ZEND_IS_HEX(*(s+1))) { char hex_buf[3] = { 0, 0, 0 }; zendlval->value.str.len--; /* for the 'x' */ hex_buf[0] = *(++s); zendlval->value.str.len--; if (ZEND_IS_HEX(*(s+1))) { hex_buf[1] = *(++s); zendlval->value.str.len--; } *t++ = (char) strtol(hex_buf, NULL, 16); } else { *t++ = '\\'; *t++ = *s; } break; default: /* check for an octal */ if (ZEND_IS_OCT(*s)) { char octal_buf[4] = { 0, 0, 0, 0 }; octal_buf[0] = *s; zendlval->value.str.len--; if (ZEND_IS_OCT(*(s+1))) { octal_buf[1] = *(++s); zendlval->value.str.len--; if (ZEND_IS_OCT(*(s+1))) { octal_buf[2] = *(++s); zendlval->value.str.len--; } } *t++ = (char) strtol(octal_buf, NULL, 8); } else { *t++ = '\\'; *t++ = *s; } break; } } else { *t++ = *s; } if (*s == '\n' || (*s == '\r' && (*(s+1) != '\n'))) { CG(zend_lineno)++; } s++; } *t = 0; if (SCNG(output_filter)) { size_t sz = 0; s = zendlval->value.str.val; SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)s, (size_t)zendlval->value.str.len TSRMLS_CC); zendlval->value.str.len = sz; efree(s); } } int lex_scan(zval *zendlval TSRMLS_DC) { restart: SCNG(yy_text) = YYCURSOR; yymore_restart: #line 995 "Zend/zend_language_scanner.c" { YYCTYPE yych; unsigned int yyaccept = 0; if (YYGETCONDITION() < 5) { if (YYGETCONDITION() < 2) { if (YYGETCONDITION() < 1) { goto yyc_ST_IN_SCRIPTING; } else { goto yyc_ST_LOOKING_FOR_PROPERTY; } } else { if (YYGETCONDITION() < 3) { goto yyc_ST_BACKQUOTE; } else { if (YYGETCONDITION() < 4) { goto yyc_ST_DOUBLE_QUOTES; } else { goto yyc_ST_HEREDOC; } } } } else { if (YYGETCONDITION() < 7) { if (YYGETCONDITION() < 6) { goto yyc_ST_LOOKING_FOR_VARNAME; } else { goto yyc_ST_VAR_OFFSET; } } else { if (YYGETCONDITION() < 8) { goto yyc_INITIAL; } else { if (YYGETCONDITION() < 9) { goto yyc_ST_END_HEREDOC; } else { goto yyc_ST_NOWDOC; } } } } /* *********************************** */ yyc_INITIAL: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; YYDEBUG(0, *YYCURSOR); YYFILL(8); yych = *YYCURSOR; if (yych != '<') goto yy4; YYDEBUG(2, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '?') { if (yych == '%') goto yy7; if (yych >= '?') goto yy5; } else { if (yych <= 'S') { if (yych >= 'S') goto yy9; } else { if (yych == 's') goto yy9; } } yy3: YYDEBUG(3, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1779 "Zend/zend_language_scanner.l" { if (YYCURSOR > YYLIMIT) { return 0; } inline_char_handler: while (1) { YYCTYPE *ptr = memchr(YYCURSOR, '<', YYLIMIT - YYCURSOR); YYCURSOR = ptr ? ptr + 1 : YYLIMIT; if (YYCURSOR < YYLIMIT) { switch (*YYCURSOR) { case '?': if (CG(short_tags) || !strncasecmp((char*)YYCURSOR + 1, "php", 3) || (*(YYCURSOR + 1) == '=')) { /* Assume [ \t\n\r] follows "php" */ break; } continue; case '%': if (CG(asp_tags)) { break; } continue; case 's': case 'S': /* Probably NOT an opening PHP <script> tag, so don't end the HTML chunk yet * If it is, the PHP <script> tag rule checks for any HTML scanned before it */ YYCURSOR--; yymore(); default: continue; } YYCURSOR--; } break; } inline_html: yyleng = YYCURSOR - SCNG(yy_text); if (SCNG(output_filter)) { int readsize; size_t sz = 0; readsize = SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)yytext, (size_t)yyleng TSRMLS_CC); zendlval->value.str.len = sz; if (readsize < yyleng) { yyless(readsize); } } else { zendlval->value.str.val = (char *) estrndup(yytext, yyleng); zendlval->value.str.len = yyleng; } zendlval->type = IS_STRING; HANDLE_NEWLINES(yytext, yyleng); return T_INLINE_HTML; } #line 1154 "Zend/zend_language_scanner.c" yy4: YYDEBUG(4, *YYCURSOR); yych = *++YYCURSOR; goto yy3; yy5: YYDEBUG(5, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'O') { if (yych == '=') goto yy45; } else { if (yych <= 'P') goto yy47; if (yych == 'p') goto yy47; } yy6: YYDEBUG(6, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1767 "Zend/zend_language_scanner.l" { if (CG(short_tags)) { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG; } else { goto inline_char_handler; } } #line 1184 "Zend/zend_language_scanner.c" yy7: YYDEBUG(7, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '=') goto yy43; YYDEBUG(8, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1744 "Zend/zend_language_scanner.l" { if (CG(asp_tags)) { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG; } else { goto inline_char_handler; } } #line 1203 "Zend/zend_language_scanner.c" yy9: YYDEBUG(9, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy11; if (yych == 'c') goto yy11; yy10: YYDEBUG(10, *YYCURSOR); YYCURSOR = YYMARKER; if (yyaccept <= 0) { goto yy3; } else { goto yy6; } yy11: YYDEBUG(11, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy12; if (yych != 'r') goto yy10; yy12: YYDEBUG(12, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy13; if (yych != 'i') goto yy10; yy13: YYDEBUG(13, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy14; if (yych != 'p') goto yy10; yy14: YYDEBUG(14, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy15; if (yych != 't') goto yy10; yy15: YYDEBUG(15, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy10; if (yych == 'l') goto yy10; goto yy17; yy16: YYDEBUG(16, *YYCURSOR); ++YYCURSOR; YYFILL(8); yych = *YYCURSOR; yy17: YYDEBUG(17, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy16; } if (yych == 'L') goto yy18; if (yych != 'l') goto yy10; yy18: YYDEBUG(18, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy19; if (yych != 'a') goto yy10; yy19: YYDEBUG(19, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy20; if (yych != 'n') goto yy10; yy20: YYDEBUG(20, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy21; if (yych != 'g') goto yy10; yy21: YYDEBUG(21, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy22; if (yych != 'u') goto yy10; yy22: YYDEBUG(22, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy23; if (yych != 'a') goto yy10; yy23: YYDEBUG(23, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy24; if (yych != 'g') goto yy10; yy24: YYDEBUG(24, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy25; if (yych != 'e') goto yy10; yy25: YYDEBUG(25, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(26, *YYCURSOR); if (yych <= '\r') { if (yych <= 0x08) goto yy10; if (yych <= '\n') goto yy25; if (yych <= '\f') goto yy10; goto yy25; } else { if (yych <= ' ') { if (yych <= 0x1F) goto yy10; goto yy25; } else { if (yych != '=') goto yy10; } } yy27: YYDEBUG(27, *YYCURSOR); ++YYCURSOR; YYFILL(5); yych = *YYCURSOR; YYDEBUG(28, *YYCURSOR); if (yych <= '!') { if (yych <= '\f') { if (yych <= 0x08) goto yy10; if (yych <= '\n') goto yy27; goto yy10; } else { if (yych <= '\r') goto yy27; if (yych == ' ') goto yy27; goto yy10; } } else { if (yych <= 'O') { if (yych <= '"') goto yy30; if (yych == '\'') goto yy31; goto yy10; } else { if (yych <= 'P') goto yy29; if (yych != 'p') goto yy10; } } yy29: YYDEBUG(29, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy42; if (yych == 'h') goto yy42; goto yy10; yy30: YYDEBUG(30, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy39; if (yych == 'p') goto yy39; goto yy10; yy31: YYDEBUG(31, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy32; if (yych != 'p') goto yy10; yy32: YYDEBUG(32, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy33; if (yych != 'h') goto yy10; yy33: YYDEBUG(33, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy34; if (yych != 'p') goto yy10; yy34: YYDEBUG(34, *YYCURSOR); yych = *++YYCURSOR; if (yych != '\'') goto yy10; yy35: YYDEBUG(35, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(36, *YYCURSOR); if (yych <= '\r') { if (yych <= 0x08) goto yy10; if (yych <= '\n') goto yy35; if (yych <= '\f') goto yy10; goto yy35; } else { if (yych <= ' ') { if (yych <= 0x1F) goto yy10; goto yy35; } else { if (yych != '>') goto yy10; } } YYDEBUG(37, *YYCURSOR); ++YYCURSOR; YYDEBUG(38, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1704 "Zend/zend_language_scanner.l" { YYCTYPE *bracket = (YYCTYPE*)zend_memrchr(yytext, '<', yyleng - (sizeof("script language=php>") - 1)); if (bracket != SCNG(yy_text)) { /* Handle previously scanned HTML, as possible <script> tags found are assumed to not be PHP's */ YYCURSOR = bracket; goto inline_html; } HANDLE_NEWLINES(yytext, yyleng); zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG; } #line 1406 "Zend/zend_language_scanner.c" yy39: YYDEBUG(39, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy40; if (yych != 'h') goto yy10; yy40: YYDEBUG(40, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy41; if (yych != 'p') goto yy10; yy41: YYDEBUG(41, *YYCURSOR); yych = *++YYCURSOR; if (yych == '"') goto yy35; goto yy10; yy42: YYDEBUG(42, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy35; if (yych == 'p') goto yy35; goto yy10; yy43: YYDEBUG(43, *YYCURSOR); ++YYCURSOR; YYDEBUG(44, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1722 "Zend/zend_language_scanner.l" { if (CG(asp_tags)) { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG_WITH_ECHO; } else { goto inline_char_handler; } } #line 1445 "Zend/zend_language_scanner.c" yy45: YYDEBUG(45, *YYCURSOR); ++YYCURSOR; YYDEBUG(46, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1735 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG_WITH_ECHO; } #line 1459 "Zend/zend_language_scanner.c" yy47: YYDEBUG(47, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy48; if (yych != 'h') goto yy10; yy48: YYDEBUG(48, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy49; if (yych != 'p') goto yy10; yy49: YYDEBUG(49, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '\f') { if (yych <= 0x08) goto yy10; if (yych >= '\v') goto yy10; } else { if (yych <= '\r') goto yy52; if (yych != ' ') goto yy10; } yy50: YYDEBUG(50, *YYCURSOR); ++YYCURSOR; yy51: YYDEBUG(51, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1757 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; HANDLE_NEWLINE(yytext[yyleng-1]); BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG; } #line 1495 "Zend/zend_language_scanner.c" yy52: YYDEBUG(52, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '\n') goto yy50; goto yy51; } /* *********************************** */ yyc_ST_BACKQUOTE: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; YYDEBUG(53, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych <= '_') { if (yych != '$') goto yy60; } else { if (yych <= '`') goto yy58; if (yych == '{') goto yy57; goto yy60; } YYDEBUG(55, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '_') { if (yych <= '@') goto yy56; if (yych <= 'Z') goto yy63; if (yych >= '_') goto yy63; } else { if (yych <= 'z') { if (yych >= 'a') goto yy63; } else { if (yych <= '{') goto yy66; if (yych >= 0x7F) goto yy63; } } yy56: YYDEBUG(56, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2230 "Zend/zend_language_scanner.l" { if (YYCURSOR > YYLIMIT) { return 0; } if (yytext[0] == '\\' && YYCURSOR < YYLIMIT) { YYCURSOR++; } while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '`': break; case '$': if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { break; } continue; case '{': if (*YYCURSOR == '$') { break; } continue; case '\\': if (YYCURSOR < YYLIMIT) { YYCURSOR++; } /* fall through */ default: continue; } YYCURSOR--; break; } yyleng = YYCURSOR - SCNG(yy_text); zend_scan_escape_string(zendlval, yytext, yyleng, '`' TSRMLS_CC); return T_ENCAPSED_AND_WHITESPACE; } #line 1607 "Zend/zend_language_scanner.c" yy57: YYDEBUG(57, *YYCURSOR); yych = *++YYCURSOR; if (yych == '$') goto yy61; goto yy56; yy58: YYDEBUG(58, *YYCURSOR); ++YYCURSOR; YYDEBUG(59, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2174 "Zend/zend_language_scanner.l" { BEGIN(ST_IN_SCRIPTING); return '`'; } #line 1623 "Zend/zend_language_scanner.c" yy60: YYDEBUG(60, *YYCURSOR); yych = *++YYCURSOR; goto yy56; yy61: YYDEBUG(61, *YYCURSOR); ++YYCURSOR; YYDEBUG(62, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2161 "Zend/zend_language_scanner.l" { zendlval->value.lval = (long) '{'; yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); yyless(1); return T_CURLY_OPEN; } #line 1640 "Zend/zend_language_scanner.c" yy63: YYDEBUG(63, *YYCURSOR); yyaccept = 0; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(64, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy63; } if (yych == '-') goto yy68; if (yych == '[') goto yy70; yy65: YYDEBUG(65, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1861 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1662 "Zend/zend_language_scanner.c" yy66: YYDEBUG(66, *YYCURSOR); ++YYCURSOR; YYDEBUG(67, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1442 "Zend/zend_language_scanner.l" { yy_push_state(ST_LOOKING_FOR_VARNAME TSRMLS_CC); return T_DOLLAR_OPEN_CURLY_BRACES; } #line 1673 "Zend/zend_language_scanner.c" yy68: YYDEBUG(68, *YYCURSOR); yych = *++YYCURSOR; if (yych == '>') goto yy72; yy69: YYDEBUG(69, *YYCURSOR); YYCURSOR = YYMARKER; goto yy65; yy70: YYDEBUG(70, *YYCURSOR); ++YYCURSOR; YYDEBUG(71, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1853 "Zend/zend_language_scanner.l" { yyless(yyleng - 1); yy_push_state(ST_VAR_OFFSET TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1695 "Zend/zend_language_scanner.c" yy72: YYDEBUG(72, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy69; if (yych <= 'Z') goto yy73; if (yych <= '^') goto yy69; } else { if (yych <= '`') goto yy69; if (yych <= 'z') goto yy73; if (yych <= '~') goto yy69; } yy73: YYDEBUG(73, *YYCURSOR); ++YYCURSOR; YYDEBUG(74, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1843 "Zend/zend_language_scanner.l" { yyless(yyleng - 3); yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1721 "Zend/zend_language_scanner.c" } /* *********************************** */ yyc_ST_DOUBLE_QUOTES: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; YYDEBUG(75, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych <= '#') { if (yych == '"') goto yy80; goto yy82; } else { if (yych <= '$') goto yy77; if (yych == '{') goto yy79; goto yy82; } yy77: YYDEBUG(77, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '_') { if (yych <= '@') goto yy78; if (yych <= 'Z') goto yy85; if (yych >= '_') goto yy85; } else { if (yych <= 'z') { if (yych >= 'a') goto yy85; } else { if (yych <= '{') goto yy88; if (yych >= 0x7F) goto yy85; } } yy78: YYDEBUG(78, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2180 "Zend/zend_language_scanner.l" { if (GET_DOUBLE_QUOTES_SCANNED_LENGTH()) { YYCURSOR += GET_DOUBLE_QUOTES_SCANNED_LENGTH() - 1; SET_DOUBLE_QUOTES_SCANNED_LENGTH(0); goto double_quotes_scan_done; } if (YYCURSOR > YYLIMIT) { return 0; } if (yytext[0] == '\\' && YYCURSOR < YYLIMIT) { YYCURSOR++; } while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '"': break; case '$': if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { break; } continue; case '{': if (*YYCURSOR == '$') { break; } continue; case '\\': if (YYCURSOR < YYLIMIT) { YYCURSOR++; } /* fall through */ default: continue; } YYCURSOR--; break; } double_quotes_scan_done: yyleng = YYCURSOR - SCNG(yy_text); zend_scan_escape_string(zendlval, yytext, yyleng, '"' TSRMLS_CC); return T_ENCAPSED_AND_WHITESPACE; } #line 1838 "Zend/zend_language_scanner.c" yy79: YYDEBUG(79, *YYCURSOR); yych = *++YYCURSOR; if (yych == '$') goto yy83; goto yy78; yy80: YYDEBUG(80, *YYCURSOR); ++YYCURSOR; YYDEBUG(81, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2169 "Zend/zend_language_scanner.l" { BEGIN(ST_IN_SCRIPTING); return '"'; } #line 1854 "Zend/zend_language_scanner.c" yy82: YYDEBUG(82, *YYCURSOR); yych = *++YYCURSOR; goto yy78; yy83: YYDEBUG(83, *YYCURSOR); ++YYCURSOR; YYDEBUG(84, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2161 "Zend/zend_language_scanner.l" { zendlval->value.lval = (long) '{'; yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); yyless(1); return T_CURLY_OPEN; } #line 1871 "Zend/zend_language_scanner.c" yy85: YYDEBUG(85, *YYCURSOR); yyaccept = 0; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(86, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy85; } if (yych == '-') goto yy90; if (yych == '[') goto yy92; yy87: YYDEBUG(87, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1861 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1893 "Zend/zend_language_scanner.c" yy88: YYDEBUG(88, *YYCURSOR); ++YYCURSOR; YYDEBUG(89, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1442 "Zend/zend_language_scanner.l" { yy_push_state(ST_LOOKING_FOR_VARNAME TSRMLS_CC); return T_DOLLAR_OPEN_CURLY_BRACES; } #line 1904 "Zend/zend_language_scanner.c" yy90: YYDEBUG(90, *YYCURSOR); yych = *++YYCURSOR; if (yych == '>') goto yy94; yy91: YYDEBUG(91, *YYCURSOR); YYCURSOR = YYMARKER; goto yy87; yy92: YYDEBUG(92, *YYCURSOR); ++YYCURSOR; YYDEBUG(93, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1853 "Zend/zend_language_scanner.l" { yyless(yyleng - 1); yy_push_state(ST_VAR_OFFSET TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1926 "Zend/zend_language_scanner.c" yy94: YYDEBUG(94, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy91; if (yych <= 'Z') goto yy95; if (yych <= '^') goto yy91; } else { if (yych <= '`') goto yy91; if (yych <= 'z') goto yy95; if (yych <= '~') goto yy91; } yy95: YYDEBUG(95, *YYCURSOR); ++YYCURSOR; YYDEBUG(96, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1843 "Zend/zend_language_scanner.l" { yyless(yyleng - 3); yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1952 "Zend/zend_language_scanner.c" } /* *********************************** */ yyc_ST_END_HEREDOC: YYDEBUG(97, *YYCURSOR); YYFILL(1); yych = *YYCURSOR; YYDEBUG(99, *YYCURSOR); ++YYCURSOR; YYDEBUG(100, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2148 "Zend/zend_language_scanner.l" { YYCURSOR += CG(heredoc_len) - 1; yyleng = CG(heredoc_len); Z_STRVAL_P(zendlval) = CG(heredoc); Z_STRLEN_P(zendlval) = CG(heredoc_len); CG(heredoc) = NULL; CG(heredoc_len) = 0; BEGIN(ST_IN_SCRIPTING); return T_END_HEREDOC; } #line 1975 "Zend/zend_language_scanner.c" /* *********************************** */ yyc_ST_HEREDOC: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; YYDEBUG(101, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych == '$') goto yy103; if (yych == '{') goto yy105; goto yy106; yy103: YYDEBUG(103, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '_') { if (yych <= '@') goto yy104; if (yych <= 'Z') goto yy109; if (yych >= '_') goto yy109; } else { if (yych <= 'z') { if (yych >= 'a') goto yy109; } else { if (yych <= '{') goto yy112; if (yych >= 0x7F) goto yy109; } } yy104: YYDEBUG(104, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2272 "Zend/zend_language_scanner.l" { int newline = 0; if (YYCURSOR > YYLIMIT) { return 0; } YYCURSOR--; while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '\r': if (*YYCURSOR == '\n') { YYCURSOR++; } /* fall through */ case '\n': /* Check for ending label on the next line */ if (IS_LABEL_START(*YYCURSOR) && CG(heredoc_len) < YYLIMIT - YYCURSOR && !memcmp(YYCURSOR, CG(heredoc), CG(heredoc_len))) { YYCTYPE *end = YYCURSOR + CG(heredoc_len); if (*end == ';') { end++; } if (*end == '\n' || *end == '\r') { /* newline before label will be subtracted from returned text, but * yyleng/yytext will include it, for zend_highlight/strip, tokenizer, etc. */ if (YYCURSOR[-2] == '\r' && YYCURSOR[-1] == '\n') { newline = 2; /* Windows newline */ } else { newline = 1; } CG(increment_lineno) = 1; /* For newline before label */ BEGIN(ST_END_HEREDOC); goto heredoc_scan_done; } } continue; case '$': if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { break; } continue; case '{': if (*YYCURSOR == '$') { break; } continue; case '\\': if (YYCURSOR < YYLIMIT && *YYCURSOR != '\n' && *YYCURSOR != '\r') { YYCURSOR++; } /* fall through */ default: continue; } YYCURSOR--; break; } heredoc_scan_done: yyleng = YYCURSOR - SCNG(yy_text); zend_scan_escape_string(zendlval, yytext, yyleng - newline, 0 TSRMLS_CC); return T_ENCAPSED_AND_WHITESPACE; } #line 2108 "Zend/zend_language_scanner.c" yy105: YYDEBUG(105, *YYCURSOR); yych = *++YYCURSOR; if (yych == '$') goto yy107; goto yy104; yy106: YYDEBUG(106, *YYCURSOR); yych = *++YYCURSOR; goto yy104; yy107: YYDEBUG(107, *YYCURSOR); ++YYCURSOR; YYDEBUG(108, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2161 "Zend/zend_language_scanner.l" { zendlval->value.lval = (long) '{'; yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); yyless(1); return T_CURLY_OPEN; } #line 2130 "Zend/zend_language_scanner.c" yy109: YYDEBUG(109, *YYCURSOR); yyaccept = 0; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(110, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy109; } if (yych == '-') goto yy114; if (yych == '[') goto yy116; yy111: YYDEBUG(111, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1861 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 2152 "Zend/zend_language_scanner.c" yy112: YYDEBUG(112, *YYCURSOR); ++YYCURSOR; YYDEBUG(113, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1442 "Zend/zend_language_scanner.l" { yy_push_state(ST_LOOKING_FOR_VARNAME TSRMLS_CC); return T_DOLLAR_OPEN_CURLY_BRACES; } #line 2163 "Zend/zend_language_scanner.c" yy114: YYDEBUG(114, *YYCURSOR); yych = *++YYCURSOR; if (yych == '>') goto yy118; yy115: YYDEBUG(115, *YYCURSOR); YYCURSOR = YYMARKER; goto yy111; yy116: YYDEBUG(116, *YYCURSOR); ++YYCURSOR; YYDEBUG(117, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1853 "Zend/zend_language_scanner.l" { yyless(yyleng - 1); yy_push_state(ST_VAR_OFFSET TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 2185 "Zend/zend_language_scanner.c" yy118: YYDEBUG(118, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy115; if (yych <= 'Z') goto yy119; if (yych <= '^') goto yy115; } else { if (yych <= '`') goto yy115; if (yych <= 'z') goto yy119; if (yych <= '~') goto yy115; } yy119: YYDEBUG(119, *YYCURSOR); ++YYCURSOR; YYDEBUG(120, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1843 "Zend/zend_language_scanner.l" { yyless(yyleng - 3); yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 2211 "Zend/zend_language_scanner.c" } /* *********************************** */ yyc_ST_IN_SCRIPTING: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 64, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 60, 60, 44, 44, 44, 44, 44, 44, 44, 44, 0, 0, 0, 0, 0, 0, 0, 36, 36, 36, 36, 36, 36, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 4, 0, 36, 36, 36, 36, 36, 36, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, }; YYDEBUG(121, *YYCURSOR); YYFILL(16); yych = *YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case '\v': case '\f': case 0x0E: case 0x0F: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1A: case 0x1B: case 0x1C: case 0x1D: case 0x1E: case 0x1F: goto yy183; case '\t': case '\n': case '\r': case ' ': goto yy139; case '!': goto yy152; case '"': goto yy179; case '#': goto yy175; case '$': goto yy164; case '%': goto yy158; case '&': goto yy159; case '\'': goto yy177; case '(': goto yy146; case ')': case ',': case ';': case '@': case '[': case ']': case '~': goto yy165; case '*': goto yy155; case '+': goto yy151; case '-': goto yy137; case '.': goto yy157; case '/': goto yy156; case '0': goto yy171; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy173; case ':': goto yy141; case '<': goto yy153; case '=': goto yy149; case '>': goto yy154; case '?': goto yy166; case 'A': case 'a': goto yy132; case 'B': case 'b': goto yy134; case 'C': case 'c': goto yy127; case 'D': case 'd': goto yy125; case 'E': case 'e': goto yy123; case 'F': case 'f': goto yy126; case 'G': case 'g': goto yy135; case 'I': case 'i': goto yy130; case 'L': case 'l': goto yy150; case 'N': case 'n': goto yy144; case 'O': case 'o': goto yy162; case 'P': case 'p': goto yy136; case 'R': case 'r': goto yy128; case 'S': case 's': goto yy133; case 'T': case 't': goto yy129; case 'U': case 'u': goto yy147; case 'V': case 'v': goto yy145; case 'W': case 'w': goto yy131; case 'X': case 'x': goto yy163; case '\\': goto yy142; case '^': goto yy161; case '_': goto yy148; case '`': goto yy181; case '{': goto yy167; case '|': goto yy160; case '}': goto yy169; default: goto yy174; } yy123: YYDEBUG(123, *YYCURSOR); ++YYCURSOR; YYDEBUG(-1, yych); switch ((yych = *YYCURSOR)) { case 'C': case 'c': goto yy726; case 'L': case 'l': goto yy727; case 'M': case 'm': goto yy728; case 'N': case 'n': goto yy729; case 'V': case 'v': goto yy730; case 'X': case 'x': goto yy731; default: goto yy186; } yy124: YYDEBUG(124, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1884 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, yytext, yyleng); zendlval->type = IS_STRING; return T_STRING; } #line 2398 "Zend/zend_language_scanner.c" yy125: YYDEBUG(125, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= 'H') { if (yych == 'E') goto yy708; goto yy186; } else { if (yych <= 'I') goto yy709; if (yych <= 'N') goto yy186; goto yy710; } } else { if (yych <= 'h') { if (yych == 'e') goto yy708; goto yy186; } else { if (yych <= 'i') goto yy709; if (yych == 'o') goto yy710; goto yy186; } } yy126: YYDEBUG(126, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= 'N') { if (yych == 'I') goto yy687; goto yy186; } else { if (yych <= 'O') goto yy688; if (yych <= 'T') goto yy186; goto yy689; } } else { if (yych <= 'n') { if (yych == 'i') goto yy687; goto yy186; } else { if (yych <= 'o') goto yy688; if (yych == 'u') goto yy689; goto yy186; } } yy127: YYDEBUG(127, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= 'K') { if (yych == 'A') goto yy652; goto yy186; } else { if (yych <= 'L') goto yy653; if (yych <= 'N') goto yy186; goto yy654; } } else { if (yych <= 'k') { if (yych == 'a') goto yy652; goto yy186; } else { if (yych <= 'l') goto yy653; if (yych == 'o') goto yy654; goto yy186; } } yy128: YYDEBUG(128, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy634; if (yych == 'e') goto yy634; goto yy186; yy129: YYDEBUG(129, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych == 'H') goto yy622; if (yych <= 'Q') goto yy186; goto yy623; } else { if (yych <= 'h') { if (yych <= 'g') goto yy186; goto yy622; } else { if (yych == 'r') goto yy623; goto yy186; } } yy130: YYDEBUG(130, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= 'L') { if (yych == 'F') goto yy569; goto yy186; } else { if (yych <= 'M') goto yy571; if (yych <= 'N') goto yy572; if (yych <= 'R') goto yy186; goto yy573; } } else { if (yych <= 'm') { if (yych == 'f') goto yy569; if (yych <= 'l') goto yy186; goto yy571; } else { if (yych <= 'n') goto yy572; if (yych == 's') goto yy573; goto yy186; } } yy131: YYDEBUG(131, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy564; if (yych == 'h') goto yy564; goto yy186; yy132: YYDEBUG(132, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= 'M') { if (yych == 'B') goto yy546; goto yy186; } else { if (yych <= 'N') goto yy547; if (yych <= 'Q') goto yy186; if (yych <= 'R') goto yy548; goto yy549; } } else { if (yych <= 'n') { if (yych == 'b') goto yy546; if (yych <= 'm') goto yy186; goto yy547; } else { if (yych <= 'q') goto yy186; if (yych <= 'r') goto yy548; if (yych <= 's') goto yy549; goto yy186; } } yy133: YYDEBUG(133, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'W') { if (yych == 'T') goto yy534; if (yych <= 'V') goto yy186; goto yy535; } else { if (yych <= 't') { if (yych <= 's') goto yy186; goto yy534; } else { if (yych == 'w') goto yy535; goto yy186; } } yy134: YYDEBUG(134, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ';') { if (yych <= '"') { if (yych <= '!') goto yy186; goto yy526; } else { if (yych == '\'') goto yy527; goto yy186; } } else { if (yych <= 'R') { if (yych <= '<') goto yy525; if (yych <= 'Q') goto yy186; goto yy528; } else { if (yych == 'r') goto yy528; goto yy186; } } yy135: YYDEBUG(135, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'L') goto yy515; if (yych <= 'N') goto yy186; goto yy516; } else { if (yych <= 'l') { if (yych <= 'k') goto yy186; goto yy515; } else { if (yych == 'o') goto yy516; goto yy186; } } yy136: YYDEBUG(136, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'R') goto yy491; if (yych <= 'T') goto yy186; goto yy492; } else { if (yych <= 'r') { if (yych <= 'q') goto yy186; goto yy491; } else { if (yych == 'u') goto yy492; goto yy186; } } yy137: YYDEBUG(137, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '<') { if (yych == '-') goto yy487; } else { if (yych <= '=') goto yy485; if (yych <= '>') goto yy489; } yy138: YYDEBUG(138, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1431 "Zend/zend_language_scanner.l" { return yytext[0]; } #line 2628 "Zend/zend_language_scanner.c" yy139: YYDEBUG(139, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy484; yy140: YYDEBUG(140, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1162 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; HANDLE_NEWLINES(yytext, yyleng); return T_WHITESPACE; } #line 2645 "Zend/zend_language_scanner.c" yy141: YYDEBUG(141, *YYCURSOR); yych = *++YYCURSOR; if (yych == ':') goto yy481; goto yy138; yy142: YYDEBUG(142, *YYCURSOR); ++YYCURSOR; YYDEBUG(143, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1191 "Zend/zend_language_scanner.l" { return T_NS_SEPARATOR; } #line 2660 "Zend/zend_language_scanner.c" yy144: YYDEBUG(144, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych == 'A') goto yy469; if (yych <= 'D') goto yy186; goto yy470; } else { if (yych <= 'a') { if (yych <= '`') goto yy186; goto yy469; } else { if (yych == 'e') goto yy470; goto yy186; } } yy145: YYDEBUG(145, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy466; if (yych == 'a') goto yy466; goto yy186; yy146: YYDEBUG(146, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy391; if (yych <= 0x1F) goto yy138; goto yy391; } else { if (yych <= '@') goto yy138; if (yych == 'C') goto yy138; goto yy391; } } else { if (yych <= 'I') { if (yych == 'F') goto yy391; if (yych <= 'H') goto yy138; goto yy391; } else { if (yych == 'O') goto yy391; if (yych <= 'Q') goto yy138; goto yy391; } } } else { if (yych <= 'f') { if (yych <= 'b') { if (yych == 'U') goto yy391; if (yych <= '`') goto yy138; goto yy391; } else { if (yych == 'd') goto yy391; if (yych <= 'e') goto yy138; goto yy391; } } else { if (yych <= 'o') { if (yych == 'i') goto yy391; if (yych <= 'n') goto yy138; goto yy391; } else { if (yych <= 's') { if (yych <= 'q') goto yy138; goto yy391; } else { if (yych == 'u') goto yy391; goto yy138; } } } } yy147: YYDEBUG(147, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych == 'N') goto yy382; if (yych <= 'R') goto yy186; goto yy383; } else { if (yych <= 'n') { if (yych <= 'm') goto yy186; goto yy382; } else { if (yych == 's') goto yy383; goto yy186; } } yy148: YYDEBUG(148, *YYCURSOR); yych = *++YYCURSOR; if (yych == '_') goto yy300; goto yy186; yy149: YYDEBUG(149, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '<') goto yy138; if (yych <= '=') goto yy294; if (yych <= '>') goto yy296; goto yy138; yy150: YYDEBUG(150, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy290; if (yych == 'i') goto yy290; goto yy186; yy151: YYDEBUG(151, *YYCURSOR); yych = *++YYCURSOR; if (yych == '+') goto yy288; if (yych == '=') goto yy286; goto yy138; yy152: YYDEBUG(152, *YYCURSOR); yych = *++YYCURSOR; if (yych == '=') goto yy283; goto yy138; yy153: YYDEBUG(153, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ';') { if (yych == '/') goto yy255; goto yy138; } else { if (yych <= '<') goto yy253; if (yych <= '=') goto yy256; if (yych <= '>') goto yy258; goto yy138; } yy154: YYDEBUG(154, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '<') goto yy138; if (yych <= '=') goto yy249; if (yych <= '>') goto yy247; goto yy138; yy155: YYDEBUG(155, *YYCURSOR); yych = *++YYCURSOR; if (yych == '=') goto yy245; goto yy138; yy156: YYDEBUG(156, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '.') { if (yych == '*') goto yy237; goto yy138; } else { if (yych <= '/') goto yy239; if (yych == '=') goto yy240; goto yy138; } yy157: YYDEBUG(157, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy138; if (yych <= '9') goto yy233; if (yych == '=') goto yy235; goto yy138; yy158: YYDEBUG(158, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '<') goto yy138; if (yych <= '=') goto yy229; if (yych <= '>') goto yy227; goto yy138; yy159: YYDEBUG(159, *YYCURSOR); yych = *++YYCURSOR; if (yych == '&') goto yy223; if (yych == '=') goto yy225; goto yy138; yy160: YYDEBUG(160, *YYCURSOR); yych = *++YYCURSOR; if (yych == '=') goto yy221; if (yych == '|') goto yy219; goto yy138; yy161: YYDEBUG(161, *YYCURSOR); yych = *++YYCURSOR; if (yych == '=') goto yy217; goto yy138; yy162: YYDEBUG(162, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy215; if (yych == 'r') goto yy215; goto yy186; yy163: YYDEBUG(163, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy212; if (yych == 'o') goto yy212; goto yy186; yy164: YYDEBUG(164, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy138; if (yych <= 'Z') goto yy209; if (yych <= '^') goto yy138; goto yy209; } else { if (yych <= '`') goto yy138; if (yych <= 'z') goto yy209; if (yych <= '~') goto yy138; goto yy209; } yy165: YYDEBUG(165, *YYCURSOR); yych = *++YYCURSOR; goto yy138; yy166: YYDEBUG(166, *YYCURSOR); yych = *++YYCURSOR; if (yych == '>') goto yy205; goto yy138; yy167: YYDEBUG(167, *YYCURSOR); ++YYCURSOR; YYDEBUG(168, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1436 "Zend/zend_language_scanner.l" { yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); return '{'; } #line 2893 "Zend/zend_language_scanner.c" yy169: YYDEBUG(169, *YYCURSOR); ++YYCURSOR; YYDEBUG(170, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1448 "Zend/zend_language_scanner.l" { RESET_DOC_COMMENT(); if (!zend_stack_is_empty(&SCNG(state_stack))) { yy_pop_state(TSRMLS_C); } return '}'; } #line 2907 "Zend/zend_language_scanner.c" yy171: YYDEBUG(171, *YYCURSOR); yyaccept = 2; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'E') { if (yych <= '9') { if (yych == '.') goto yy187; if (yych >= '0') goto yy190; } else { if (yych == 'B') goto yy198; if (yych >= 'E') goto yy192; } } else { if (yych <= 'b') { if (yych == 'X') goto yy197; if (yych >= 'b') goto yy198; } else { if (yych <= 'e') { if (yych >= 'e') goto yy192; } else { if (yych == 'x') goto yy197; } } } yy172: YYDEBUG(172, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1494 "Zend/zend_language_scanner.l" { if (yyleng < MAX_LENGTH_OF_LONG - 1) { /* Won't overflow */ zendlval->value.lval = strtol(yytext, NULL, 0); } else { errno = 0; zendlval->value.lval = strtol(yytext, NULL, 0); if (errno == ERANGE) { /* Overflow */ if (yytext[0] == '0') { /* octal overflow */ zendlval->value.dval = zend_oct_strtod(yytext, NULL); } else { zendlval->value.dval = zend_strtod(yytext, NULL); } zendlval->type = IS_DOUBLE; return T_DNUMBER; } } zendlval->type = IS_LONG; return T_LNUMBER; } #line 2956 "Zend/zend_language_scanner.c" yy173: YYDEBUG(173, *YYCURSOR); yyaccept = 2; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych == '.') goto yy187; if (yych <= '/') goto yy172; goto yy190; } else { if (yych <= 'E') { if (yych <= 'D') goto yy172; goto yy192; } else { if (yych == 'e') goto yy192; goto yy172; } } yy174: YYDEBUG(174, *YYCURSOR); yych = *++YYCURSOR; goto yy186; yy175: YYDEBUG(175, *YYCURSOR); ++YYCURSOR; yy176: YYDEBUG(176, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1891 "Zend/zend_language_scanner.l" { while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '\r': if (*YYCURSOR == '\n') { YYCURSOR++; } /* fall through */ case '\n': CG(zend_lineno)++; break; case '%': if (!CG(asp_tags)) { continue; } /* fall through */ case '?': if (*YYCURSOR == '>') { YYCURSOR--; break; } /* fall through */ default: continue; } break; } yyleng = YYCURSOR - SCNG(yy_text); return T_COMMENT; } #line 3018 "Zend/zend_language_scanner.c" yy177: YYDEBUG(177, *YYCURSOR); ++YYCURSOR; yy178: YYDEBUG(178, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1982 "Zend/zend_language_scanner.l" { register char *s, *t; char *end; int bprefix = (yytext[0] != '\'') ? 1 : 0; while (1) { if (YYCURSOR < YYLIMIT) { if (*YYCURSOR == '\'') { YYCURSOR++; yyleng = YYCURSOR - SCNG(yy_text); break; } else if (*YYCURSOR++ == '\\' && YYCURSOR < YYLIMIT) { YYCURSOR++; } } else { yyleng = YYLIMIT - SCNG(yy_text); /* Unclosed single quotes; treat similar to double quotes, but without a separate token * for ' (unrecognized by parser), instead of old flex fallback to "Unexpected character..." * rule, which continued in ST_IN_SCRIPTING state after the quote */ return T_ENCAPSED_AND_WHITESPACE; } } zendlval->value.str.val = estrndup(yytext+bprefix+1, yyleng-bprefix-2); zendlval->value.str.len = yyleng-bprefix-2; zendlval->type = IS_STRING; /* convert escape sequences */ s = t = zendlval->value.str.val; end = s+zendlval->value.str.len; while (s<end) { if (*s=='\\') { s++; switch(*s) { case '\\': case '\'': *t++ = *s; zendlval->value.str.len--; break; default: *t++ = '\\'; *t++ = *s; break; } } else { *t++ = *s; } if (*s == '\n' || (*s == '\r' && (*(s+1) != '\n'))) { CG(zend_lineno)++; } s++; } *t = 0; if (SCNG(output_filter)) { size_t sz = 0; s = zendlval->value.str.val; SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)s, (size_t)zendlval->value.str.len TSRMLS_CC); zendlval->value.str.len = sz; efree(s); } return T_CONSTANT_ENCAPSED_STRING; } #line 3093 "Zend/zend_language_scanner.c" yy179: YYDEBUG(179, *YYCURSOR); ++YYCURSOR; yy180: YYDEBUG(180, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2051 "Zend/zend_language_scanner.l" { int bprefix = (yytext[0] != '"') ? 1 : 0; while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '"': yyleng = YYCURSOR - SCNG(yy_text); zend_scan_escape_string(zendlval, yytext+bprefix+1, yyleng-bprefix-2, '"' TSRMLS_CC); return T_CONSTANT_ENCAPSED_STRING; case '$': if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { break; } continue; case '{': if (*YYCURSOR == '$') { break; } continue; case '\\': if (YYCURSOR < YYLIMIT) { YYCURSOR++; } /* fall through */ default: continue; } YYCURSOR--; break; } /* Remember how much was scanned to save rescanning */ SET_DOUBLE_QUOTES_SCANNED_LENGTH(YYCURSOR - SCNG(yy_text) - yyleng); YYCURSOR = SCNG(yy_text) + yyleng; BEGIN(ST_DOUBLE_QUOTES); return '"'; } #line 3141 "Zend/zend_language_scanner.c" yy181: YYDEBUG(181, *YYCURSOR); ++YYCURSOR; YYDEBUG(182, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2142 "Zend/zend_language_scanner.l" { BEGIN(ST_BACKQUOTE); return '`'; } #line 3152 "Zend/zend_language_scanner.c" yy183: YYDEBUG(183, *YYCURSOR); ++YYCURSOR; YYDEBUG(184, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2400 "Zend/zend_language_scanner.l" { if (YYCURSOR > YYLIMIT) { return 0; } zend_error(E_COMPILE_WARNING,"Unexpected character in input: '%c' (ASCII=%d) state=%d", yytext[0], yytext[0], YYSTATE); goto restart; } #line 3167 "Zend/zend_language_scanner.c" yy185: YYDEBUG(185, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy186: YYDEBUG(186, *YYCURSOR); if (yybm[0+yych] & 4) { goto yy185; } goto yy124; yy187: YYDEBUG(187, *YYCURSOR); yyaccept = 3; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(188, *YYCURSOR); if (yybm[0+yych] & 8) { goto yy187; } if (yych == 'E') goto yy192; if (yych == 'e') goto yy192; yy189: YYDEBUG(189, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1559 "Zend/zend_language_scanner.l" { zendlval->value.dval = zend_strtod(yytext, NULL); zendlval->type = IS_DOUBLE; return T_DNUMBER; } #line 3200 "Zend/zend_language_scanner.c" yy190: YYDEBUG(190, *YYCURSOR); yyaccept = 2; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(191, *YYCURSOR); if (yych <= '9') { if (yych == '.') goto yy187; if (yych <= '/') goto yy172; goto yy190; } else { if (yych <= 'E') { if (yych <= 'D') goto yy172; } else { if (yych != 'e') goto yy172; } } yy192: YYDEBUG(192, *YYCURSOR); yych = *++YYCURSOR; if (yych <= ',') { if (yych == '+') goto yy194; } else { if (yych <= '-') goto yy194; if (yych <= '/') goto yy193; if (yych <= '9') goto yy195; } yy193: YYDEBUG(193, *YYCURSOR); YYCURSOR = YYMARKER; if (yyaccept <= 2) { if (yyaccept <= 1) { if (yyaccept <= 0) { goto yy124; } else { goto yy138; } } else { goto yy172; } } else { if (yyaccept <= 4) { if (yyaccept <= 3) { goto yy189; } else { goto yy238; } } else { goto yy254; } } yy194: YYDEBUG(194, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy193; if (yych >= ':') goto yy193; yy195: YYDEBUG(195, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(196, *YYCURSOR); if (yych <= '/') goto yy189; if (yych <= '9') goto yy195; goto yy189; yy197: YYDEBUG(197, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 32) { goto yy202; } goto yy193; yy198: YYDEBUG(198, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 16) { goto yy199; } goto yy193; yy199: YYDEBUG(199, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(200, *YYCURSOR); if (yybm[0+yych] & 16) { goto yy199; } YYDEBUG(201, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1473 "Zend/zend_language_scanner.l" { char *bin = yytext + 2; /* Skip "0b" */ int len = yyleng - 2; /* Skip any leading 0s */ while (*bin == '0') { ++bin; --len; } if (len < SIZEOF_LONG * 8) { zendlval->value.lval = strtol(bin, NULL, 2); zendlval->type = IS_LONG; return T_LNUMBER; } else { zendlval->value.dval = zend_bin_strtod(bin, NULL); zendlval->type = IS_DOUBLE; return T_DNUMBER; } } #line 3313 "Zend/zend_language_scanner.c" yy202: YYDEBUG(202, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(203, *YYCURSOR); if (yybm[0+yych] & 32) { goto yy202; } YYDEBUG(204, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1515 "Zend/zend_language_scanner.l" { char *hex = yytext + 2; /* Skip "0x" */ int len = yyleng - 2; /* Skip any leading 0s */ while (*hex == '0') { hex++; len--; } if (len < SIZEOF_LONG * 2 || (len == SIZEOF_LONG * 2 && *hex <= '7')) { if (len == 0) { zendlval->value.lval = 0; } else { zendlval->value.lval = strtol(hex, NULL, 16); } zendlval->type = IS_LONG; return T_LNUMBER; } else { zendlval->value.dval = zend_hex_strtod(hex, NULL); zendlval->type = IS_DOUBLE; return T_DNUMBER; } } #line 3350 "Zend/zend_language_scanner.c" yy205: YYDEBUG(205, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '\n') goto yy207; if (yych == '\r') goto yy208; yy206: YYDEBUG(206, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1959 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(INITIAL); return T_CLOSE_TAG; /* implicit ';' at php-end tag */ } #line 3367 "Zend/zend_language_scanner.c" yy207: YYDEBUG(207, *YYCURSOR); yych = *++YYCURSOR; goto yy206; yy208: YYDEBUG(208, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\n') goto yy207; goto yy206; yy209: YYDEBUG(209, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(210, *YYCURSOR); if (yych <= '^') { if (yych <= '9') { if (yych >= '0') goto yy209; } else { if (yych <= '@') goto yy211; if (yych <= 'Z') goto yy209; } } else { if (yych <= '`') { if (yych <= '_') goto yy209; } else { if (yych <= 'z') goto yy209; if (yych >= 0x7F) goto yy209; } } yy211: YYDEBUG(211, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1861 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 3407 "Zend/zend_language_scanner.c" yy212: YYDEBUG(212, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy213; if (yych != 'r') goto yy186; yy213: YYDEBUG(213, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(214, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1419 "Zend/zend_language_scanner.l" { return T_LOGICAL_XOR; } #line 3425 "Zend/zend_language_scanner.c" yy215: YYDEBUG(215, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(216, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1411 "Zend/zend_language_scanner.l" { return T_LOGICAL_OR; } #line 3438 "Zend/zend_language_scanner.c" yy217: YYDEBUG(217, *YYCURSOR); ++YYCURSOR; YYDEBUG(218, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1399 "Zend/zend_language_scanner.l" { return T_XOR_EQUAL; } #line 3448 "Zend/zend_language_scanner.c" yy219: YYDEBUG(219, *YYCURSOR); ++YYCURSOR; YYDEBUG(220, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1403 "Zend/zend_language_scanner.l" { return T_BOOLEAN_OR; } #line 3458 "Zend/zend_language_scanner.c" yy221: YYDEBUG(221, *YYCURSOR); ++YYCURSOR; YYDEBUG(222, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1395 "Zend/zend_language_scanner.l" { return T_OR_EQUAL; } #line 3468 "Zend/zend_language_scanner.c" yy223: YYDEBUG(223, *YYCURSOR); ++YYCURSOR; YYDEBUG(224, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1407 "Zend/zend_language_scanner.l" { return T_BOOLEAN_AND; } #line 3478 "Zend/zend_language_scanner.c" yy225: YYDEBUG(225, *YYCURSOR); ++YYCURSOR; YYDEBUG(226, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1391 "Zend/zend_language_scanner.l" { return T_AND_EQUAL; } #line 3488 "Zend/zend_language_scanner.c" yy227: YYDEBUG(227, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '\n') goto yy231; if (yych == '\r') goto yy232; yy228: YYDEBUG(228, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1968 "Zend/zend_language_scanner.l" { if (CG(asp_tags)) { BEGIN(INITIAL); zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; zendlval->value.str.val = yytext; /* no copying - intentional */ return T_CLOSE_TAG; /* implicit ';' at php-end tag */ } else { yyless(1); return yytext[0]; } } #line 3510 "Zend/zend_language_scanner.c" yy229: YYDEBUG(229, *YYCURSOR); ++YYCURSOR; YYDEBUG(230, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1379 "Zend/zend_language_scanner.l" { return T_MOD_EQUAL; } #line 3520 "Zend/zend_language_scanner.c" yy231: YYDEBUG(231, *YYCURSOR); yych = *++YYCURSOR; goto yy228; yy232: YYDEBUG(232, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\n') goto yy231; goto yy228; yy233: YYDEBUG(233, *YYCURSOR); yyaccept = 3; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(234, *YYCURSOR); if (yych <= 'D') { if (yych <= '/') goto yy189; if (yych <= '9') goto yy233; goto yy189; } else { if (yych <= 'E') goto yy192; if (yych == 'e') goto yy192; goto yy189; } yy235: YYDEBUG(235, *YYCURSOR); ++YYCURSOR; YYDEBUG(236, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1375 "Zend/zend_language_scanner.l" { return T_CONCAT_EQUAL; } #line 3555 "Zend/zend_language_scanner.c" yy237: YYDEBUG(237, *YYCURSOR); yyaccept = 4; yych = *(YYMARKER = ++YYCURSOR); if (yych == '*') goto yy242; yy238: YYDEBUG(238, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1925 "Zend/zend_language_scanner.l" { int doc_com; if (yyleng > 2) { doc_com = 1; RESET_DOC_COMMENT(); } else { doc_com = 0; } while (YYCURSOR < YYLIMIT) { if (*YYCURSOR++ == '*' && *YYCURSOR == '/') { break; } } if (YYCURSOR < YYLIMIT) { YYCURSOR++; } else { zend_error(E_COMPILE_WARNING, "Unterminated comment starting line %d", CG(zend_lineno)); } yyleng = YYCURSOR - SCNG(yy_text); HANDLE_NEWLINES(yytext, yyleng); if (doc_com) { CG(doc_comment) = estrndup(yytext, yyleng); CG(doc_comment_len) = yyleng; return T_DOC_COMMENT; } return T_COMMENT; } #line 3598 "Zend/zend_language_scanner.c" yy239: YYDEBUG(239, *YYCURSOR); yych = *++YYCURSOR; goto yy176; yy240: YYDEBUG(240, *YYCURSOR); ++YYCURSOR; YYDEBUG(241, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1371 "Zend/zend_language_scanner.l" { return T_DIV_EQUAL; } #line 3612 "Zend/zend_language_scanner.c" yy242: YYDEBUG(242, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 64) { goto yy243; } goto yy193; yy243: YYDEBUG(243, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(244, *YYCURSOR); if (yybm[0+yych] & 64) { goto yy243; } goto yy238; yy245: YYDEBUG(245, *YYCURSOR); ++YYCURSOR; YYDEBUG(246, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1367 "Zend/zend_language_scanner.l" { return T_MUL_EQUAL; } #line 3639 "Zend/zend_language_scanner.c" yy247: YYDEBUG(247, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '=') goto yy251; YYDEBUG(248, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1427 "Zend/zend_language_scanner.l" { return T_SR; } #line 3650 "Zend/zend_language_scanner.c" yy249: YYDEBUG(249, *YYCURSOR); ++YYCURSOR; YYDEBUG(250, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1355 "Zend/zend_language_scanner.l" { return T_IS_GREATER_OR_EQUAL; } #line 3660 "Zend/zend_language_scanner.c" yy251: YYDEBUG(251, *YYCURSOR); ++YYCURSOR; YYDEBUG(252, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1387 "Zend/zend_language_scanner.l" { return T_SR_EQUAL; } #line 3670 "Zend/zend_language_scanner.c" yy253: YYDEBUG(253, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ';') goto yy254; if (yych <= '<') goto yy269; if (yych <= '=') goto yy267; yy254: YYDEBUG(254, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1423 "Zend/zend_language_scanner.l" { return T_SL; } #line 3685 "Zend/zend_language_scanner.c" yy255: YYDEBUG(255, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy260; if (yych == 's') goto yy260; goto yy193; yy256: YYDEBUG(256, *YYCURSOR); ++YYCURSOR; YYDEBUG(257, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1351 "Zend/zend_language_scanner.l" { return T_IS_SMALLER_OR_EQUAL; } #line 3701 "Zend/zend_language_scanner.c" yy258: YYDEBUG(258, *YYCURSOR); ++YYCURSOR; yy259: YYDEBUG(259, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1347 "Zend/zend_language_scanner.l" { return T_IS_NOT_EQUAL; } #line 3712 "Zend/zend_language_scanner.c" yy260: YYDEBUG(260, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy261; if (yych != 'c') goto yy193; yy261: YYDEBUG(261, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy262; if (yych != 'r') goto yy193; yy262: YYDEBUG(262, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy263; if (yych != 'i') goto yy193; yy263: YYDEBUG(263, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy264; if (yych != 'p') goto yy193; yy264: YYDEBUG(264, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy265; if (yych != 't') goto yy193; yy265: YYDEBUG(265, *YYCURSOR); ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(266, *YYCURSOR); if (yych <= '\r') { if (yych <= 0x08) goto yy193; if (yych <= '\n') goto yy265; if (yych <= '\f') goto yy193; goto yy265; } else { if (yych <= ' ') { if (yych <= 0x1F) goto yy193; goto yy265; } else { if (yych == '>') goto yy205; goto yy193; } } yy267: YYDEBUG(267, *YYCURSOR); ++YYCURSOR; YYDEBUG(268, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1383 "Zend/zend_language_scanner.l" { return T_SL_EQUAL; } #line 3767 "Zend/zend_language_scanner.c" yy269: YYDEBUG(269, *YYCURSOR); ++YYCURSOR; YYFILL(2); yych = *YYCURSOR; YYDEBUG(270, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy269; } if (yych <= 'Z') { if (yych <= '&') { if (yych == '"') goto yy274; goto yy193; } else { if (yych <= '\'') goto yy273; if (yych <= '@') goto yy193; } } else { if (yych <= '`') { if (yych != '_') goto yy193; } else { if (yych <= 'z') goto yy271; if (yych <= '~') goto yy193; } } yy271: YYDEBUG(271, *YYCURSOR); ++YYCURSOR; YYFILL(2); yych = *YYCURSOR; YYDEBUG(272, *YYCURSOR); if (yych <= '@') { if (yych <= '\f') { if (yych == '\n') goto yy278; goto yy193; } else { if (yych <= '\r') goto yy280; if (yych <= '/') goto yy193; if (yych <= '9') goto yy271; goto yy193; } } else { if (yych <= '_') { if (yych <= 'Z') goto yy271; if (yych <= '^') goto yy193; goto yy271; } else { if (yych <= '`') goto yy193; if (yych <= 'z') goto yy271; if (yych <= '~') goto yy193; goto yy271; } } yy273: YYDEBUG(273, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\'') goto yy193; if (yych <= '/') goto yy282; if (yych <= '9') goto yy193; goto yy282; yy274: YYDEBUG(274, *YYCURSOR); yych = *++YYCURSOR; if (yych == '"') goto yy193; if (yych <= '/') goto yy276; if (yych <= '9') goto yy193; goto yy276; yy275: YYDEBUG(275, *YYCURSOR); ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; yy276: YYDEBUG(276, *YYCURSOR); if (yych <= 'Z') { if (yych <= '/') { if (yych != '"') goto yy193; } else { if (yych <= '9') goto yy275; if (yych <= '@') goto yy193; goto yy275; } } else { if (yych <= '`') { if (yych == '_') goto yy275; goto yy193; } else { if (yych <= 'z') goto yy275; if (yych <= '~') goto yy193; goto yy275; } } yy277: YYDEBUG(277, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\n') goto yy278; if (yych == '\r') goto yy280; goto yy193; yy278: YYDEBUG(278, *YYCURSOR); ++YYCURSOR; yy279: YYDEBUG(279, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2093 "Zend/zend_language_scanner.l" { char *s; int bprefix = (yytext[0] != '<') ? 1 : 0; /* save old heredoc label */ Z_STRVAL_P(zendlval) = CG(heredoc); Z_STRLEN_P(zendlval) = CG(heredoc_len); CG(zend_lineno)++; CG(heredoc_len) = yyleng-bprefix-3-1-(yytext[yyleng-2]=='\r'?1:0); s = yytext+bprefix+3; while ((*s == ' ') || (*s == '\t')) { s++; CG(heredoc_len)--; } if (*s == '\'') { s++; CG(heredoc_len) -= 2; BEGIN(ST_NOWDOC); } else { if (*s == '"') { s++; CG(heredoc_len) -= 2; } BEGIN(ST_HEREDOC); } CG(heredoc) = estrndup(s, CG(heredoc_len)); /* Check for ending label on the next line */ if (CG(heredoc_len) < YYLIMIT - YYCURSOR && !memcmp(YYCURSOR, s, CG(heredoc_len))) { YYCTYPE *end = YYCURSOR + CG(heredoc_len); if (*end == ';') { end++; } if (*end == '\n' || *end == '\r') { BEGIN(ST_END_HEREDOC); } } return T_START_HEREDOC; } #line 3920 "Zend/zend_language_scanner.c" yy280: YYDEBUG(280, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\n') goto yy278; goto yy279; yy281: YYDEBUG(281, *YYCURSOR); ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; yy282: YYDEBUG(282, *YYCURSOR); if (yych <= 'Z') { if (yych <= '/') { if (yych == '\'') goto yy277; goto yy193; } else { if (yych <= '9') goto yy281; if (yych <= '@') goto yy193; goto yy281; } } else { if (yych <= '`') { if (yych == '_') goto yy281; goto yy193; } else { if (yych <= 'z') goto yy281; if (yych <= '~') goto yy193; goto yy281; } } yy283: YYDEBUG(283, *YYCURSOR); yych = *++YYCURSOR; if (yych != '=') goto yy259; YYDEBUG(284, *YYCURSOR); ++YYCURSOR; YYDEBUG(285, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1339 "Zend/zend_language_scanner.l" { return T_IS_NOT_IDENTICAL; } #line 3964 "Zend/zend_language_scanner.c" yy286: YYDEBUG(286, *YYCURSOR); ++YYCURSOR; YYDEBUG(287, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1359 "Zend/zend_language_scanner.l" { return T_PLUS_EQUAL; } #line 3974 "Zend/zend_language_scanner.c" yy288: YYDEBUG(288, *YYCURSOR); ++YYCURSOR; YYDEBUG(289, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1327 "Zend/zend_language_scanner.l" { return T_INC; } #line 3984 "Zend/zend_language_scanner.c" yy290: YYDEBUG(290, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy291; if (yych != 's') goto yy186; yy291: YYDEBUG(291, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy292; if (yych != 't') goto yy186; yy292: YYDEBUG(292, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(293, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1315 "Zend/zend_language_scanner.l" { return T_LIST; } #line 4007 "Zend/zend_language_scanner.c" yy294: YYDEBUG(294, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '=') goto yy298; YYDEBUG(295, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1343 "Zend/zend_language_scanner.l" { return T_IS_EQUAL; } #line 4018 "Zend/zend_language_scanner.c" yy296: YYDEBUG(296, *YYCURSOR); ++YYCURSOR; YYDEBUG(297, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1311 "Zend/zend_language_scanner.l" { return T_DOUBLE_ARROW; } #line 4028 "Zend/zend_language_scanner.c" yy298: YYDEBUG(298, *YYCURSOR); ++YYCURSOR; YYDEBUG(299, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1335 "Zend/zend_language_scanner.l" { return T_IS_IDENTICAL; } #line 4038 "Zend/zend_language_scanner.c" yy300: YYDEBUG(300, *YYCURSOR); yych = *++YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case 'C': case 'c': goto yy302; case 'D': case 'd': goto yy307; case 'F': case 'f': goto yy304; case 'H': case 'h': goto yy301; case 'L': case 'l': goto yy306; case 'M': case 'm': goto yy305; case 'N': case 'n': goto yy308; case 'T': case 't': goto yy303; default: goto yy186; } yy301: YYDEBUG(301, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy369; if (yych == 'a') goto yy369; goto yy186; yy302: YYDEBUG(302, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy362; if (yych == 'l') goto yy362; goto yy186; yy303: YYDEBUG(303, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy355; if (yych == 'r') goto yy355; goto yy186; yy304: YYDEBUG(304, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'I') goto yy339; if (yych <= 'T') goto yy186; goto yy340; } else { if (yych <= 'i') { if (yych <= 'h') goto yy186; goto yy339; } else { if (yych == 'u') goto yy340; goto yy186; } } yy305: YYDEBUG(305, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy331; if (yych == 'e') goto yy331; goto yy186; yy306: YYDEBUG(306, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy325; if (yych == 'i') goto yy325; goto yy186; yy307: YYDEBUG(307, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy320; if (yych == 'i') goto yy320; goto yy186; yy308: YYDEBUG(308, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy309; if (yych != 'a') goto yy186; yy309: YYDEBUG(309, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy310; if (yych != 'm') goto yy186; yy310: YYDEBUG(310, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy311; if (yych != 'e') goto yy186; yy311: YYDEBUG(311, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy312; if (yych != 's') goto yy186; yy312: YYDEBUG(312, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy313; if (yych != 'p') goto yy186; yy313: YYDEBUG(313, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy314; if (yych != 'a') goto yy186; yy314: YYDEBUG(314, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy315; if (yych != 'c') goto yy186; yy315: YYDEBUG(315, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy316; if (yych != 'e') goto yy186; yy316: YYDEBUG(316, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(317, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(318, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(319, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1694 "Zend/zend_language_scanner.l" { if (CG(current_namespace)) { *zendlval = *CG(current_namespace); zval_copy_ctor(zendlval); } else { ZVAL_EMPTY_STRING(zendlval); } return T_NS_C; } #line 4178 "Zend/zend_language_scanner.c" yy320: YYDEBUG(320, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy321; if (yych != 'r') goto yy186; yy321: YYDEBUG(321, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(322, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(323, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(324, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1667 "Zend/zend_language_scanner.l" { char *filename = zend_get_compiled_filename(TSRMLS_C); const size_t filename_len = strlen(filename); char *dirname; if (!filename) { filename = ""; } dirname = estrndup(filename, filename_len); zend_dirname(dirname, filename_len); if (strcmp(dirname, ".") == 0) { dirname = erealloc(dirname, MAXPATHLEN); #if HAVE_GETCWD VCWD_GETCWD(dirname, MAXPATHLEN); #elif HAVE_GETWD VCWD_GETWD(dirname); #endif } zendlval->value.str.len = strlen(dirname); zendlval->value.str.val = dirname; zendlval->type = IS_STRING; return T_DIR; } #line 4225 "Zend/zend_language_scanner.c" yy325: YYDEBUG(325, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy326; if (yych != 'n') goto yy186; yy326: YYDEBUG(326, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy327; if (yych != 'e') goto yy186; yy327: YYDEBUG(327, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(328, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(329, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(330, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1649 "Zend/zend_language_scanner.l" { zendlval->value.lval = CG(zend_lineno); zendlval->type = IS_LONG; return T_LINE; } #line 4256 "Zend/zend_language_scanner.c" yy331: YYDEBUG(331, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy332; if (yych != 't') goto yy186; yy332: YYDEBUG(332, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy333; if (yych != 'h') goto yy186; yy333: YYDEBUG(333, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy334; if (yych != 'o') goto yy186; yy334: YYDEBUG(334, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy335; if (yych != 'd') goto yy186; yy335: YYDEBUG(335, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(336, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(337, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(338, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1628 "Zend/zend_language_scanner.l" { const char *class_name = CG(active_class_entry) ? CG(active_class_entry)->name : NULL; const char *func_name = CG(active_op_array)? CG(active_op_array)->function_name : NULL; size_t len = 0; if (class_name) { len += strlen(class_name) + 2; } if (func_name) { len += strlen(func_name); } zendlval->value.str.len = zend_spprintf(&zendlval->value.str.val, 0, "%s%s%s", class_name ? class_name : "", class_name && func_name ? "::" : "", func_name ? func_name : "" ); zendlval->type = IS_STRING; return T_METHOD_C; } #line 4312 "Zend/zend_language_scanner.c" yy339: YYDEBUG(339, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy350; if (yych == 'l') goto yy350; goto yy186; yy340: YYDEBUG(340, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy341; if (yych != 'n') goto yy186; yy341: YYDEBUG(341, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy342; if (yych != 'c') goto yy186; yy342: YYDEBUG(342, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy343; if (yych != 't') goto yy186; yy343: YYDEBUG(343, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy344; if (yych != 'i') goto yy186; yy344: YYDEBUG(344, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy345; if (yych != 'o') goto yy186; yy345: YYDEBUG(345, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy346; if (yych != 'n') goto yy186; yy346: YYDEBUG(346, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(347, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(348, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(349, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1612 "Zend/zend_language_scanner.l" { const char *func_name = NULL; if (CG(active_op_array)) { func_name = CG(active_op_array)->function_name; } if (!func_name) { func_name = ""; } zendlval->value.str.len = strlen(func_name); zendlval->value.str.val = estrndup(func_name, zendlval->value.str.len); zendlval->type = IS_STRING; return T_FUNC_C; } #line 4379 "Zend/zend_language_scanner.c" yy350: YYDEBUG(350, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy351; if (yych != 'e') goto yy186; yy351: YYDEBUG(351, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(352, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(353, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(354, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1655 "Zend/zend_language_scanner.l" { char *filename = zend_get_compiled_filename(TSRMLS_C); if (!filename) { filename = ""; } zendlval->value.str.len = strlen(filename); zendlval->value.str.val = estrndup(filename, zendlval->value.str.len); zendlval->type = IS_STRING; return T_FILE; } #line 4411 "Zend/zend_language_scanner.c" yy355: YYDEBUG(355, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy356; if (yych != 'a') goto yy186; yy356: YYDEBUG(356, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy357; if (yych != 'i') goto yy186; yy357: YYDEBUG(357, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy358; if (yych != 't') goto yy186; yy358: YYDEBUG(358, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(359, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(360, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(361, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1592 "Zend/zend_language_scanner.l" { const char *trait_name = NULL; if (CG(active_class_entry) && (ZEND_ACC_TRAIT == (CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT))) { trait_name = CG(active_class_entry)->name; } if (!trait_name) { trait_name = ""; } zendlval->value.str.len = strlen(trait_name); zendlval->value.str.val = estrndup(trait_name, zendlval->value.str.len); zendlval->type = IS_STRING; return T_TRAIT_C; } #line 4461 "Zend/zend_language_scanner.c" yy362: YYDEBUG(362, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy363; if (yych != 'a') goto yy186; yy363: YYDEBUG(363, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy364; if (yych != 's') goto yy186; yy364: YYDEBUG(364, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy365; if (yych != 's') goto yy186; yy365: YYDEBUG(365, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(366, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(367, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(368, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1565 "Zend/zend_language_scanner.l" { const char *class_name = NULL; if (CG(active_class_entry) && (ZEND_ACC_TRAIT == (CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT))) { /* We create a special __CLASS__ constant that is going to be resolved at run-time */ zendlval->value.str.len = sizeof("__CLASS__")-1; zendlval->value.str.val = estrndup("__CLASS__", zendlval->value.str.len); zendlval->type = IS_CONSTANT; } else { if (CG(active_class_entry)) { class_name = CG(active_class_entry)->name; } if (!class_name) { class_name = ""; } zendlval->value.str.len = strlen(class_name); zendlval->value.str.val = estrndup(class_name, zendlval->value.str.len); zendlval->type = IS_STRING; } return T_CLASS_C; } #line 4518 "Zend/zend_language_scanner.c" yy369: YYDEBUG(369, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy370; if (yych != 'l') goto yy186; yy370: YYDEBUG(370, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy371; if (yych != 't') goto yy186; yy371: YYDEBUG(371, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(372, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy373; if (yych != 'c') goto yy186; yy373: YYDEBUG(373, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy374; if (yych != 'o') goto yy186; yy374: YYDEBUG(374, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy375; if (yych != 'm') goto yy186; yy375: YYDEBUG(375, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy376; if (yych != 'p') goto yy186; yy376: YYDEBUG(376, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy377; if (yych != 'i') goto yy186; yy377: YYDEBUG(377, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy378; if (yych != 'l') goto yy186; yy378: YYDEBUG(378, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy379; if (yych != 'e') goto yy186; yy379: YYDEBUG(379, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy380; if (yych != 'r') goto yy186; yy380: YYDEBUG(380, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(381, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1279 "Zend/zend_language_scanner.l" { return T_HALT_COMPILER; } #line 4584 "Zend/zend_language_scanner.c" yy382: YYDEBUG(382, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy386; if (yych == 's') goto yy386; goto yy186; yy383: YYDEBUG(383, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy384; if (yych != 'e') goto yy186; yy384: YYDEBUG(384, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(385, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1259 "Zend/zend_language_scanner.l" { return T_USE; } #line 4608 "Zend/zend_language_scanner.c" yy386: YYDEBUG(386, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy387; if (yych != 'e') goto yy186; yy387: YYDEBUG(387, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy388; if (yych != 't') goto yy186; yy388: YYDEBUG(388, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(389, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1307 "Zend/zend_language_scanner.l" { return T_UNSET; } #line 4631 "Zend/zend_language_scanner.c" yy390: YYDEBUG(390, *YYCURSOR); ++YYCURSOR; YYFILL(7); yych = *YYCURSOR; yy391: YYDEBUG(391, *YYCURSOR); if (yych <= 'S') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy390; if (yych <= 0x1F) goto yy193; goto yy390; } else { if (yych <= 'A') { if (yych <= '@') goto yy193; goto yy395; } else { if (yych <= 'B') goto yy393; if (yych <= 'C') goto yy193; goto yy398; } } } else { if (yych <= 'I') { if (yych == 'F') goto yy399; if (yych <= 'H') goto yy193; goto yy400; } else { if (yych <= 'O') { if (yych <= 'N') goto yy193; goto yy394; } else { if (yych <= 'Q') goto yy193; if (yych <= 'R') goto yy397; goto yy396; } } } } else { if (yych <= 'f') { if (yych <= 'a') { if (yych == 'U') goto yy392; if (yych <= '`') goto yy193; goto yy395; } else { if (yych <= 'c') { if (yych <= 'b') goto yy393; goto yy193; } else { if (yych <= 'd') goto yy398; if (yych <= 'e') goto yy193; goto yy399; } } } else { if (yych <= 'q') { if (yych <= 'i') { if (yych <= 'h') goto yy193; goto yy400; } else { if (yych == 'o') goto yy394; goto yy193; } } else { if (yych <= 's') { if (yych <= 'r') goto yy397; goto yy396; } else { if (yych != 'u') goto yy193; } } } } yy392: YYDEBUG(392, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy459; if (yych == 'n') goto yy459; goto yy193; yy393: YYDEBUG(393, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'I') goto yy446; if (yych <= 'N') goto yy193; goto yy447; } else { if (yych <= 'i') { if (yych <= 'h') goto yy193; goto yy446; } else { if (yych == 'o') goto yy447; goto yy193; } } yy394: YYDEBUG(394, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy438; if (yych == 'b') goto yy438; goto yy193; yy395: YYDEBUG(395, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy431; if (yych == 'r') goto yy431; goto yy193; yy396: YYDEBUG(396, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy423; if (yych == 't') goto yy423; goto yy193; yy397: YYDEBUG(397, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy421; if (yych == 'e') goto yy421; goto yy193; yy398: YYDEBUG(398, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy417; if (yych == 'o') goto yy417; goto yy193; yy399: YYDEBUG(399, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy410; if (yych == 'l') goto yy410; goto yy193; yy400: YYDEBUG(400, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy401; if (yych != 'n') goto yy193; yy401: YYDEBUG(401, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy402; if (yych != 't') goto yy193; yy402: YYDEBUG(402, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy403; if (yych != 'e') goto yy405; yy403: YYDEBUG(403, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy408; if (yych == 'g') goto yy408; goto yy193; yy404: YYDEBUG(404, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy405: YYDEBUG(405, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy404; goto yy193; } else { if (yych <= ' ') goto yy404; if (yych != ')') goto yy193; } YYDEBUG(406, *YYCURSOR); ++YYCURSOR; YYDEBUG(407, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1207 "Zend/zend_language_scanner.l" { return T_INT_CAST; } #line 4807 "Zend/zend_language_scanner.c" yy408: YYDEBUG(408, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy409; if (yych != 'e') goto yy193; yy409: YYDEBUG(409, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy404; if (yych == 'r') goto yy404; goto yy193; yy410: YYDEBUG(410, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy411; if (yych != 'o') goto yy193; yy411: YYDEBUG(411, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy412; if (yych != 'a') goto yy193; yy412: YYDEBUG(412, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy413; if (yych != 't') goto yy193; yy413: YYDEBUG(413, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(414, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy413; goto yy193; } else { if (yych <= ' ') goto yy413; if (yych != ')') goto yy193; } YYDEBUG(415, *YYCURSOR); ++YYCURSOR; YYDEBUG(416, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1211 "Zend/zend_language_scanner.l" { return T_DOUBLE_CAST; } #line 4855 "Zend/zend_language_scanner.c" yy417: YYDEBUG(417, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy418; if (yych != 'u') goto yy193; yy418: YYDEBUG(418, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy419; if (yych != 'b') goto yy193; yy419: YYDEBUG(419, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy420; if (yych != 'l') goto yy193; yy420: YYDEBUG(420, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy413; if (yych == 'e') goto yy413; goto yy193; yy421: YYDEBUG(421, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy422; if (yych != 'a') goto yy193; yy422: YYDEBUG(422, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy413; if (yych == 'l') goto yy413; goto yy193; yy423: YYDEBUG(423, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy424; if (yych != 'r') goto yy193; yy424: YYDEBUG(424, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy425; if (yych != 'i') goto yy193; yy425: YYDEBUG(425, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy426; if (yych != 'n') goto yy193; yy426: YYDEBUG(426, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy427; if (yych != 'g') goto yy193; yy427: YYDEBUG(427, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(428, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy427; goto yy193; } else { if (yych <= ' ') goto yy427; if (yych != ')') goto yy193; } YYDEBUG(429, *YYCURSOR); ++YYCURSOR; YYDEBUG(430, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1215 "Zend/zend_language_scanner.l" { return T_STRING_CAST; } #line 4929 "Zend/zend_language_scanner.c" yy431: YYDEBUG(431, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy432; if (yych != 'r') goto yy193; yy432: YYDEBUG(432, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy433; if (yych != 'a') goto yy193; yy433: YYDEBUG(433, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy434; if (yych != 'y') goto yy193; yy434: YYDEBUG(434, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(435, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy434; goto yy193; } else { if (yych <= ' ') goto yy434; if (yych != ')') goto yy193; } YYDEBUG(436, *YYCURSOR); ++YYCURSOR; YYDEBUG(437, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1219 "Zend/zend_language_scanner.l" { return T_ARRAY_CAST; } #line 4966 "Zend/zend_language_scanner.c" yy438: YYDEBUG(438, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'J') goto yy439; if (yych != 'j') goto yy193; yy439: YYDEBUG(439, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy440; if (yych != 'e') goto yy193; yy440: YYDEBUG(440, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy441; if (yych != 'c') goto yy193; yy441: YYDEBUG(441, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy442; if (yych != 't') goto yy193; yy442: YYDEBUG(442, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(443, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy442; goto yy193; } else { if (yych <= ' ') goto yy442; if (yych != ')') goto yy193; } YYDEBUG(444, *YYCURSOR); ++YYCURSOR; YYDEBUG(445, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1223 "Zend/zend_language_scanner.l" { return T_OBJECT_CAST; } #line 5008 "Zend/zend_language_scanner.c" yy446: YYDEBUG(446, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy456; if (yych == 'n') goto yy456; goto yy193; yy447: YYDEBUG(447, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy448; if (yych != 'o') goto yy193; yy448: YYDEBUG(448, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy449; if (yych != 'l') goto yy193; yy449: YYDEBUG(449, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy454; if (yych == 'e') goto yy454; goto yy451; yy450: YYDEBUG(450, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy451: YYDEBUG(451, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy450; goto yy193; } else { if (yych <= ' ') goto yy450; if (yych != ')') goto yy193; } YYDEBUG(452, *YYCURSOR); ++YYCURSOR; YYDEBUG(453, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1227 "Zend/zend_language_scanner.l" { return T_BOOL_CAST; } #line 5053 "Zend/zend_language_scanner.c" yy454: YYDEBUG(454, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy455; if (yych != 'a') goto yy193; yy455: YYDEBUG(455, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy450; if (yych == 'n') goto yy450; goto yy193; yy456: YYDEBUG(456, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy457; if (yych != 'a') goto yy193; yy457: YYDEBUG(457, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy458; if (yych != 'r') goto yy193; yy458: YYDEBUG(458, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy427; if (yych == 'y') goto yy427; goto yy193; yy459: YYDEBUG(459, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy460; if (yych != 's') goto yy193; yy460: YYDEBUG(460, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy461; if (yych != 'e') goto yy193; yy461: YYDEBUG(461, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy462; if (yych != 't') goto yy193; yy462: YYDEBUG(462, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(463, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy462; goto yy193; } else { if (yych <= ' ') goto yy462; if (yych != ')') goto yy193; } YYDEBUG(464, *YYCURSOR); ++YYCURSOR; YYDEBUG(465, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1231 "Zend/zend_language_scanner.l" { return T_UNSET_CAST; } #line 5117 "Zend/zend_language_scanner.c" yy466: YYDEBUG(466, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy467; if (yych != 'r') goto yy186; yy467: YYDEBUG(467, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(468, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1203 "Zend/zend_language_scanner.l" { return T_VAR; } #line 5135 "Zend/zend_language_scanner.c" yy469: YYDEBUG(469, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy473; if (yych == 'm') goto yy473; goto yy186; yy470: YYDEBUG(470, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'W') goto yy471; if (yych != 'w') goto yy186; yy471: YYDEBUG(471, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(472, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1195 "Zend/zend_language_scanner.l" { return T_NEW; } #line 5159 "Zend/zend_language_scanner.c" yy473: YYDEBUG(473, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy474; if (yych != 'e') goto yy186; yy474: YYDEBUG(474, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy475; if (yych != 's') goto yy186; yy475: YYDEBUG(475, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy476; if (yych != 'p') goto yy186; yy476: YYDEBUG(476, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy477; if (yych != 'a') goto yy186; yy477: YYDEBUG(477, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy478; if (yych != 'c') goto yy186; yy478: YYDEBUG(478, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy479; if (yych != 'e') goto yy186; yy479: YYDEBUG(479, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(480, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1255 "Zend/zend_language_scanner.l" { return T_NAMESPACE; } #line 5202 "Zend/zend_language_scanner.c" yy481: YYDEBUG(481, *YYCURSOR); ++YYCURSOR; YYDEBUG(482, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1187 "Zend/zend_language_scanner.l" { return T_PAAMAYIM_NEKUDOTAYIM; } #line 5212 "Zend/zend_language_scanner.c" yy483: YYDEBUG(483, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy484: YYDEBUG(484, *YYCURSOR); if (yych <= '\f') { if (yych <= 0x08) goto yy140; if (yych <= '\n') goto yy483; goto yy140; } else { if (yych <= '\r') goto yy483; if (yych == ' ') goto yy483; goto yy140; } yy485: YYDEBUG(485, *YYCURSOR); ++YYCURSOR; YYDEBUG(486, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1363 "Zend/zend_language_scanner.l" { return T_MINUS_EQUAL; } #line 5238 "Zend/zend_language_scanner.c" yy487: YYDEBUG(487, *YYCURSOR); ++YYCURSOR; YYDEBUG(488, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1331 "Zend/zend_language_scanner.l" { return T_DEC; } #line 5248 "Zend/zend_language_scanner.c" yy489: YYDEBUG(489, *YYCURSOR); ++YYCURSOR; YYDEBUG(490, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1157 "Zend/zend_language_scanner.l" { yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC); return T_OBJECT_OPERATOR; } #line 5259 "Zend/zend_language_scanner.c" yy491: YYDEBUG(491, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'I') goto yy498; if (yych <= 'N') goto yy186; goto yy499; } else { if (yych <= 'i') { if (yych <= 'h') goto yy186; goto yy498; } else { if (yych == 'o') goto yy499; goto yy186; } } yy492: YYDEBUG(492, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy493; if (yych != 'b') goto yy186; yy493: YYDEBUG(493, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy494; if (yych != 'l') goto yy186; yy494: YYDEBUG(494, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy495; if (yych != 'i') goto yy186; yy495: YYDEBUG(495, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy496; if (yych != 'c') goto yy186; yy496: YYDEBUG(496, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(497, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1303 "Zend/zend_language_scanner.l" { return T_PUBLIC; } #line 5308 "Zend/zend_language_scanner.c" yy498: YYDEBUG(498, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'V') { if (yych == 'N') goto yy507; if (yych <= 'U') goto yy186; goto yy508; } else { if (yych <= 'n') { if (yych <= 'm') goto yy186; goto yy507; } else { if (yych == 'v') goto yy508; goto yy186; } } yy499: YYDEBUG(499, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy500; if (yych != 't') goto yy186; yy500: YYDEBUG(500, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy501; if (yych != 'e') goto yy186; yy501: YYDEBUG(501, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy502; if (yych != 'c') goto yy186; yy502: YYDEBUG(502, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy503; if (yych != 't') goto yy186; yy503: YYDEBUG(503, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy504; if (yych != 'e') goto yy186; yy504: YYDEBUG(504, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy505; if (yych != 'd') goto yy186; yy505: YYDEBUG(505, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(506, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1299 "Zend/zend_language_scanner.l" { return T_PROTECTED; } #line 5367 "Zend/zend_language_scanner.c" yy507: YYDEBUG(507, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy513; if (yych == 't') goto yy513; goto yy186; yy508: YYDEBUG(508, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy509; if (yych != 'a') goto yy186; yy509: YYDEBUG(509, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy510; if (yych != 't') goto yy186; yy510: YYDEBUG(510, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy511; if (yych != 'e') goto yy186; yy511: YYDEBUG(511, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(512, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1295 "Zend/zend_language_scanner.l" { return T_PRIVATE; } #line 5401 "Zend/zend_language_scanner.c" yy513: YYDEBUG(513, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(514, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1133 "Zend/zend_language_scanner.l" { return T_PRINT; } #line 5414 "Zend/zend_language_scanner.c" yy515: YYDEBUG(515, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy520; if (yych == 'o') goto yy520; goto yy186; yy516: YYDEBUG(516, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy517; if (yych != 't') goto yy186; yy517: YYDEBUG(517, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy518; if (yych != 'o') goto yy186; yy518: YYDEBUG(518, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(519, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1125 "Zend/zend_language_scanner.l" { return T_GOTO; } #line 5443 "Zend/zend_language_scanner.c" yy520: YYDEBUG(520, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy521; if (yych != 'b') goto yy186; yy521: YYDEBUG(521, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy522; if (yych != 'a') goto yy186; yy522: YYDEBUG(522, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy523; if (yych != 'l') goto yy186; yy523: YYDEBUG(523, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(524, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1267 "Zend/zend_language_scanner.l" { return T_GLOBAL; } #line 5471 "Zend/zend_language_scanner.c" yy525: YYDEBUG(525, *YYCURSOR); yych = *++YYCURSOR; if (yych == '<') goto yy533; goto yy193; yy526: YYDEBUG(526, *YYCURSOR); yych = *++YYCURSOR; goto yy180; yy527: YYDEBUG(527, *YYCURSOR); yych = *++YYCURSOR; goto yy178; yy528: YYDEBUG(528, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy529; if (yych != 'e') goto yy186; yy529: YYDEBUG(529, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy530; if (yych != 'a') goto yy186; yy530: YYDEBUG(530, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'K') goto yy531; if (yych != 'k') goto yy186; yy531: YYDEBUG(531, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(532, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1117 "Zend/zend_language_scanner.l" { return T_BREAK; } #line 5512 "Zend/zend_language_scanner.c" yy533: YYDEBUG(533, *YYCURSOR); yych = *++YYCURSOR; if (yych == '<') goto yy269; goto yy193; yy534: YYDEBUG(534, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy541; if (yych == 'a') goto yy541; goto yy186; yy535: YYDEBUG(535, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy536; if (yych != 'i') goto yy186; yy536: YYDEBUG(536, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy537; if (yych != 't') goto yy186; yy537: YYDEBUG(537, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy538; if (yych != 'c') goto yy186; yy538: YYDEBUG(538, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy539; if (yych != 'h') goto yy186; yy539: YYDEBUG(539, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(540, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1101 "Zend/zend_language_scanner.l" { return T_SWITCH; } #line 5556 "Zend/zend_language_scanner.c" yy541: YYDEBUG(541, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy542; if (yych != 't') goto yy186; yy542: YYDEBUG(542, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy543; if (yych != 'i') goto yy186; yy543: YYDEBUG(543, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy544; if (yych != 'c') goto yy186; yy544: YYDEBUG(544, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(545, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1283 "Zend/zend_language_scanner.l" { return T_STATIC; } #line 5584 "Zend/zend_language_scanner.c" yy546: YYDEBUG(546, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy557; if (yych == 's') goto yy557; goto yy186; yy547: YYDEBUG(547, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy555; if (yych == 'd') goto yy555; goto yy186; yy548: YYDEBUG(548, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy551; if (yych == 'r') goto yy551; goto yy186; yy549: YYDEBUG(549, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(550, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1097 "Zend/zend_language_scanner.l" { return T_AS; } #line 5615 "Zend/zend_language_scanner.c" yy551: YYDEBUG(551, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy552; if (yych != 'a') goto yy186; yy552: YYDEBUG(552, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy553; if (yych != 'y') goto yy186; yy553: YYDEBUG(553, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(554, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1319 "Zend/zend_language_scanner.l" { return T_ARRAY; } #line 5638 "Zend/zend_language_scanner.c" yy555: YYDEBUG(555, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(556, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1415 "Zend/zend_language_scanner.l" { return T_LOGICAL_AND; } #line 5651 "Zend/zend_language_scanner.c" yy557: YYDEBUG(557, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy558; if (yych != 't') goto yy186; yy558: YYDEBUG(558, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy559; if (yych != 'r') goto yy186; yy559: YYDEBUG(559, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy560; if (yych != 'a') goto yy186; yy560: YYDEBUG(560, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy561; if (yych != 'c') goto yy186; yy561: YYDEBUG(561, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy562; if (yych != 't') goto yy186; yy562: YYDEBUG(562, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(563, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1287 "Zend/zend_language_scanner.l" { return T_ABSTRACT; } #line 5689 "Zend/zend_language_scanner.c" yy564: YYDEBUG(564, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy565; if (yych != 'i') goto yy186; yy565: YYDEBUG(565, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy566; if (yych != 'l') goto yy186; yy566: YYDEBUG(566, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy567; if (yych != 'e') goto yy186; yy567: YYDEBUG(567, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(568, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1057 "Zend/zend_language_scanner.l" { return T_WHILE; } #line 5717 "Zend/zend_language_scanner.c" yy569: YYDEBUG(569, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(570, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1041 "Zend/zend_language_scanner.l" { return T_IF; } #line 5730 "Zend/zend_language_scanner.c" yy571: YYDEBUG(571, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy613; if (yych == 'p') goto yy613; goto yy186; yy572: YYDEBUG(572, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= 'C') { if (yych <= 'B') goto yy186; goto yy580; } else { if (yych <= 'R') goto yy186; if (yych <= 'S') goto yy578; goto yy579; } } else { if (yych <= 'r') { if (yych == 'c') goto yy580; goto yy186; } else { if (yych <= 's') goto yy578; if (yych <= 't') goto yy579; goto yy186; } } yy573: YYDEBUG(573, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy574; if (yych != 's') goto yy186; yy574: YYDEBUG(574, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy575; if (yych != 'e') goto yy186; yy575: YYDEBUG(575, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy576; if (yych != 't') goto yy186; yy576: YYDEBUG(576, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(577, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1271 "Zend/zend_language_scanner.l" { return T_ISSET; } #line 5786 "Zend/zend_language_scanner.c" yy578: YYDEBUG(578, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy599; if (yych == 't') goto yy599; goto yy186; yy579: YYDEBUG(579, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy592; if (yych == 'e') goto yy592; goto yy186; yy580: YYDEBUG(580, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy581; if (yych != 'l') goto yy186; yy581: YYDEBUG(581, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy582; if (yych != 'u') goto yy186; yy582: YYDEBUG(582, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy583; if (yych != 'd') goto yy186; yy583: YYDEBUG(583, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy584; if (yych != 'e') goto yy186; yy584: YYDEBUG(584, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '9') { if (yych >= '0') goto yy185; } else { if (yych <= '@') goto yy585; if (yych <= 'Z') goto yy185; } } else { if (yych <= '`') { if (yych <= '_') goto yy586; } else { if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy585: YYDEBUG(585, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1239 "Zend/zend_language_scanner.l" { return T_INCLUDE; } #line 5844 "Zend/zend_language_scanner.c" yy586: YYDEBUG(586, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy587; if (yych != 'o') goto yy186; yy587: YYDEBUG(587, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy588; if (yych != 'n') goto yy186; yy588: YYDEBUG(588, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy589; if (yych != 'c') goto yy186; yy589: YYDEBUG(589, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy590; if (yych != 'e') goto yy186; yy590: YYDEBUG(590, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(591, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1243 "Zend/zend_language_scanner.l" { return T_INCLUDE_ONCE; } #line 5877 "Zend/zend_language_scanner.c" yy592: YYDEBUG(592, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy593; if (yych != 'r') goto yy186; yy593: YYDEBUG(593, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy594; if (yych != 'f') goto yy186; yy594: YYDEBUG(594, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy595; if (yych != 'a') goto yy186; yy595: YYDEBUG(595, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy596; if (yych != 'c') goto yy186; yy596: YYDEBUG(596, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy597; if (yych != 'e') goto yy186; yy597: YYDEBUG(597, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(598, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1141 "Zend/zend_language_scanner.l" { return T_INTERFACE; } #line 5915 "Zend/zend_language_scanner.c" yy599: YYDEBUG(599, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych == 'A') goto yy600; if (yych <= 'D') goto yy186; goto yy601; } else { if (yych <= 'a') { if (yych <= '`') goto yy186; } else { if (yych == 'e') goto yy601; goto yy186; } } yy600: YYDEBUG(600, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy607; if (yych == 'n') goto yy607; goto yy186; yy601: YYDEBUG(601, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy602; if (yych != 'a') goto yy186; yy602: YYDEBUG(602, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy603; if (yych != 'd') goto yy186; yy603: YYDEBUG(603, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy604; if (yych != 'o') goto yy186; yy604: YYDEBUG(604, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy605; if (yych != 'f') goto yy186; yy605: YYDEBUG(605, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(606, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1263 "Zend/zend_language_scanner.l" { return T_INSTEADOF; } #line 5969 "Zend/zend_language_scanner.c" yy607: YYDEBUG(607, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy608; if (yych != 'c') goto yy186; yy608: YYDEBUG(608, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy609; if (yych != 'e') goto yy186; yy609: YYDEBUG(609, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy610; if (yych != 'o') goto yy186; yy610: YYDEBUG(610, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy611; if (yych != 'f') goto yy186; yy611: YYDEBUG(611, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(612, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1093 "Zend/zend_language_scanner.l" { return T_INSTANCEOF; } #line 6002 "Zend/zend_language_scanner.c" yy613: YYDEBUG(613, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy614; if (yych != 'l') goto yy186; yy614: YYDEBUG(614, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy615; if (yych != 'e') goto yy186; yy615: YYDEBUG(615, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy616; if (yych != 'm') goto yy186; yy616: YYDEBUG(616, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy617; if (yych != 'e') goto yy186; yy617: YYDEBUG(617, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy618; if (yych != 'n') goto yy186; yy618: YYDEBUG(618, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy619; if (yych != 't') goto yy186; yy619: YYDEBUG(619, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy620; if (yych != 's') goto yy186; yy620: YYDEBUG(620, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(621, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1153 "Zend/zend_language_scanner.l" { return T_IMPLEMENTS; } #line 6050 "Zend/zend_language_scanner.c" yy622: YYDEBUG(622, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy630; if (yych == 'r') goto yy630; goto yy186; yy623: YYDEBUG(623, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych == 'A') goto yy626; if (yych <= 'X') goto yy186; } else { if (yych <= 'a') { if (yych <= '`') goto yy186; goto yy626; } else { if (yych != 'y') goto yy186; } } YYDEBUG(624, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(625, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1029 "Zend/zend_language_scanner.l" { return T_TRY; } #line 6082 "Zend/zend_language_scanner.c" yy626: YYDEBUG(626, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy627; if (yych != 'i') goto yy186; yy627: YYDEBUG(627, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy628; if (yych != 't') goto yy186; yy628: YYDEBUG(628, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(629, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1145 "Zend/zend_language_scanner.l" { return T_TRAIT; } #line 6105 "Zend/zend_language_scanner.c" yy630: YYDEBUG(630, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy631; if (yych != 'o') goto yy186; yy631: YYDEBUG(631, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'W') goto yy632; if (yych != 'w') goto yy186; yy632: YYDEBUG(632, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(633, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1037 "Zend/zend_language_scanner.l" { return T_THROW; } #line 6128 "Zend/zend_language_scanner.c" yy634: YYDEBUG(634, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych == 'Q') goto yy636; if (yych <= 'S') goto yy186; } else { if (yych <= 'q') { if (yych <= 'p') goto yy186; goto yy636; } else { if (yych != 't') goto yy186; } } YYDEBUG(635, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy648; if (yych == 'u') goto yy648; goto yy186; yy636: YYDEBUG(636, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy637; if (yych != 'u') goto yy186; yy637: YYDEBUG(637, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy638; if (yych != 'i') goto yy186; yy638: YYDEBUG(638, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy639; if (yych != 'r') goto yy186; yy639: YYDEBUG(639, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy640; if (yych != 'e') goto yy186; yy640: YYDEBUG(640, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '9') { if (yych >= '0') goto yy185; } else { if (yych <= '@') goto yy641; if (yych <= 'Z') goto yy185; } } else { if (yych <= '`') { if (yych <= '_') goto yy642; } else { if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy641: YYDEBUG(641, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1247 "Zend/zend_language_scanner.l" { return T_REQUIRE; } #line 6193 "Zend/zend_language_scanner.c" yy642: YYDEBUG(642, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy643; if (yych != 'o') goto yy186; yy643: YYDEBUG(643, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy644; if (yych != 'n') goto yy186; yy644: YYDEBUG(644, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy645; if (yych != 'c') goto yy186; yy645: YYDEBUG(645, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy646; if (yych != 'e') goto yy186; yy646: YYDEBUG(646, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(647, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1251 "Zend/zend_language_scanner.l" { return T_REQUIRE_ONCE; } #line 6226 "Zend/zend_language_scanner.c" yy648: YYDEBUG(648, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy649; if (yych != 'r') goto yy186; yy649: YYDEBUG(649, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy650; if (yych != 'n') goto yy186; yy650: YYDEBUG(650, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(651, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1025 "Zend/zend_language_scanner.l" { return T_RETURN; } #line 6249 "Zend/zend_language_scanner.c" yy652: YYDEBUG(652, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= 'L') { if (yych <= 'K') goto yy186; goto yy675; } else { if (yych <= 'R') goto yy186; if (yych <= 'S') goto yy674; goto yy673; } } else { if (yych <= 'r') { if (yych == 'l') goto yy675; goto yy186; } else { if (yych <= 's') goto yy674; if (yych <= 't') goto yy673; goto yy186; } } yy653: YYDEBUG(653, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'A') goto yy665; if (yych <= 'N') goto yy186; goto yy666; } else { if (yych <= 'a') { if (yych <= '`') goto yy186; goto yy665; } else { if (yych == 'o') goto yy666; goto yy186; } } yy654: YYDEBUG(654, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy655; if (yych != 'n') goto yy186; yy655: YYDEBUG(655, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= 'R') goto yy186; if (yych >= 'T') goto yy657; } else { if (yych <= 'r') goto yy186; if (yych <= 's') goto yy656; if (yych <= 't') goto yy657; goto yy186; } yy656: YYDEBUG(656, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy663; if (yych == 't') goto yy663; goto yy186; yy657: YYDEBUG(657, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy658; if (yych != 'i') goto yy186; yy658: YYDEBUG(658, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy659; if (yych != 'n') goto yy186; yy659: YYDEBUG(659, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy660; if (yych != 'u') goto yy186; yy660: YYDEBUG(660, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy661; if (yych != 'e') goto yy186; yy661: YYDEBUG(661, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(662, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1121 "Zend/zend_language_scanner.l" { return T_CONTINUE; } #line 6343 "Zend/zend_language_scanner.c" yy663: YYDEBUG(663, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(664, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1021 "Zend/zend_language_scanner.l" { return T_CONST; } #line 6356 "Zend/zend_language_scanner.c" yy665: YYDEBUG(665, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy670; if (yych == 's') goto yy670; goto yy186; yy666: YYDEBUG(666, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy667; if (yych != 'n') goto yy186; yy667: YYDEBUG(667, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy668; if (yych != 'e') goto yy186; yy668: YYDEBUG(668, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(669, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1199 "Zend/zend_language_scanner.l" { return T_CLONE; } #line 6385 "Zend/zend_language_scanner.c" yy670: YYDEBUG(670, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy671; if (yych != 's') goto yy186; yy671: YYDEBUG(671, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(672, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1137 "Zend/zend_language_scanner.l" { return T_CLASS; } #line 6403 "Zend/zend_language_scanner.c" yy673: YYDEBUG(673, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy684; if (yych == 'c') goto yy684; goto yy186; yy674: YYDEBUG(674, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy682; if (yych == 'e') goto yy682; goto yy186; yy675: YYDEBUG(675, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy676; if (yych != 'l') goto yy186; yy676: YYDEBUG(676, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy677; if (yych != 'a') goto yy186; yy677: YYDEBUG(677, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy678; if (yych != 'b') goto yy186; yy678: YYDEBUG(678, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy679; if (yych != 'l') goto yy186; yy679: YYDEBUG(679, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy680; if (yych != 'e') goto yy186; yy680: YYDEBUG(680, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(681, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1323 "Zend/zend_language_scanner.l" { return T_CALLABLE; } #line 6453 "Zend/zend_language_scanner.c" yy682: YYDEBUG(682, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(683, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1109 "Zend/zend_language_scanner.l" { return T_CASE; } #line 6466 "Zend/zend_language_scanner.c" yy684: YYDEBUG(684, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy685; if (yych != 'h') goto yy186; yy685: YYDEBUG(685, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(686, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1033 "Zend/zend_language_scanner.l" { return T_CATCH; } #line 6484 "Zend/zend_language_scanner.c" yy687: YYDEBUG(687, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy704; if (yych == 'n') goto yy704; goto yy186; yy688: YYDEBUG(688, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy697; if (yych == 'r') goto yy697; goto yy186; yy689: YYDEBUG(689, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy690; if (yych != 'n') goto yy186; yy690: YYDEBUG(690, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy691; if (yych != 'c') goto yy186; yy691: YYDEBUG(691, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy692; if (yych != 't') goto yy186; yy692: YYDEBUG(692, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy693; if (yych != 'i') goto yy186; yy693: YYDEBUG(693, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy694; if (yych != 'o') goto yy186; yy694: YYDEBUG(694, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy695; if (yych != 'n') goto yy186; yy695: YYDEBUG(695, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(696, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1017 "Zend/zend_language_scanner.l" { return T_FUNCTION; } #line 6539 "Zend/zend_language_scanner.c" yy697: YYDEBUG(697, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '@') { if (yych <= '/') goto yy698; if (yych <= '9') goto yy185; } else { if (yych == 'E') goto yy699; if (yych <= 'Z') goto yy185; } } else { if (yych <= 'd') { if (yych != '`') goto yy185; } else { if (yych <= 'e') goto yy699; if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy698: YYDEBUG(698, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1069 "Zend/zend_language_scanner.l" { return T_FOR; } #line 6567 "Zend/zend_language_scanner.c" yy699: YYDEBUG(699, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy700; if (yych != 'a') goto yy186; yy700: YYDEBUG(700, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy701; if (yych != 'c') goto yy186; yy701: YYDEBUG(701, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy702; if (yych != 'h') goto yy186; yy702: YYDEBUG(702, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(703, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1077 "Zend/zend_language_scanner.l" { return T_FOREACH; } #line 6595 "Zend/zend_language_scanner.c" yy704: YYDEBUG(704, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy705; if (yych != 'a') goto yy186; yy705: YYDEBUG(705, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy706; if (yych != 'l') goto yy186; yy706: YYDEBUG(706, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(707, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1291 "Zend/zend_language_scanner.l" { return T_FINAL; } #line 6618 "Zend/zend_language_scanner.c" yy708: YYDEBUG(708, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'F') { if (yych == 'C') goto yy714; if (yych <= 'E') goto yy186; goto yy715; } else { if (yych <= 'c') { if (yych <= 'b') goto yy186; goto yy714; } else { if (yych == 'f') goto yy715; goto yy186; } } yy709: YYDEBUG(709, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy712; if (yych == 'e') goto yy712; goto yy186; yy710: YYDEBUG(710, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(711, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1065 "Zend/zend_language_scanner.l" { return T_DO; } #line 6653 "Zend/zend_language_scanner.c" yy712: YYDEBUG(712, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(713, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1013 "Zend/zend_language_scanner.l" { return T_EXIT; } #line 6666 "Zend/zend_language_scanner.c" yy714: YYDEBUG(714, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy721; if (yych == 'l') goto yy721; goto yy186; yy715: YYDEBUG(715, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy716; if (yych != 'a') goto yy186; yy716: YYDEBUG(716, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy717; if (yych != 'u') goto yy186; yy717: YYDEBUG(717, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy718; if (yych != 'l') goto yy186; yy718: YYDEBUG(718, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy719; if (yych != 't') goto yy186; yy719: YYDEBUG(719, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(720, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1113 "Zend/zend_language_scanner.l" { return T_DEFAULT; } #line 6705 "Zend/zend_language_scanner.c" yy721: YYDEBUG(721, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy722; if (yych != 'a') goto yy186; yy722: YYDEBUG(722, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy723; if (yych != 'r') goto yy186; yy723: YYDEBUG(723, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy724; if (yych != 'e') goto yy186; yy724: YYDEBUG(724, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(725, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1085 "Zend/zend_language_scanner.l" { return T_DECLARE; } #line 6733 "Zend/zend_language_scanner.c" yy726: YYDEBUG(726, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy788; if (yych == 'h') goto yy788; goto yy186; yy727: YYDEBUG(727, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy782; if (yych == 's') goto yy782; goto yy186; yy728: YYDEBUG(728, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy778; if (yych == 'p') goto yy778; goto yy186; yy729: YYDEBUG(729, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy744; if (yych == 'd') goto yy744; goto yy186; yy730: YYDEBUG(730, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy741; if (yych == 'a') goto yy741; goto yy186; yy731: YYDEBUG(731, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych == 'I') goto yy732; if (yych <= 'S') goto yy186; goto yy733; } else { if (yych <= 'i') { if (yych <= 'h') goto yy186; } else { if (yych == 't') goto yy733; goto yy186; } } yy732: YYDEBUG(732, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy739; if (yych == 't') goto yy739; goto yy186; yy733: YYDEBUG(733, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy734; if (yych != 'e') goto yy186; yy734: YYDEBUG(734, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy735; if (yych != 'n') goto yy186; yy735: YYDEBUG(735, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy736; if (yych != 'd') goto yy186; yy736: YYDEBUG(736, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy737; if (yych != 's') goto yy186; yy737: YYDEBUG(737, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(738, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1149 "Zend/zend_language_scanner.l" { return T_EXTENDS; } #line 6817 "Zend/zend_language_scanner.c" yy739: YYDEBUG(739, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(740, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1009 "Zend/zend_language_scanner.l" { return T_EXIT; } #line 6830 "Zend/zend_language_scanner.c" yy741: YYDEBUG(741, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy742; if (yych != 'l') goto yy186; yy742: YYDEBUG(742, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(743, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1235 "Zend/zend_language_scanner.l" { return T_EVAL; } #line 6848 "Zend/zend_language_scanner.c" yy744: YYDEBUG(744, *YYCURSOR); yych = *++YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case 'D': case 'd': goto yy745; case 'F': case 'f': goto yy746; case 'I': case 'i': goto yy747; case 'S': case 's': goto yy748; case 'W': case 'w': goto yy749; default: goto yy186; } yy745: YYDEBUG(745, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy771; if (yych == 'e') goto yy771; goto yy186; yy746: YYDEBUG(746, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy763; if (yych == 'o') goto yy763; goto yy186; yy747: YYDEBUG(747, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy761; if (yych == 'f') goto yy761; goto yy186; yy748: YYDEBUG(748, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'W') goto yy755; if (yych == 'w') goto yy755; goto yy186; yy749: YYDEBUG(749, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy750; if (yych != 'h') goto yy186; yy750: YYDEBUG(750, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy751; if (yych != 'i') goto yy186; yy751: YYDEBUG(751, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy752; if (yych != 'l') goto yy186; yy752: YYDEBUG(752, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy753; if (yych != 'e') goto yy186; yy753: YYDEBUG(753, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(754, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1061 "Zend/zend_language_scanner.l" { return T_ENDWHILE; } #line 6922 "Zend/zend_language_scanner.c" yy755: YYDEBUG(755, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy756; if (yych != 'i') goto yy186; yy756: YYDEBUG(756, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy757; if (yych != 't') goto yy186; yy757: YYDEBUG(757, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy758; if (yych != 'c') goto yy186; yy758: YYDEBUG(758, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy759; if (yych != 'h') goto yy186; yy759: YYDEBUG(759, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(760, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1105 "Zend/zend_language_scanner.l" { return T_ENDSWITCH; } #line 6955 "Zend/zend_language_scanner.c" yy761: YYDEBUG(761, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(762, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1049 "Zend/zend_language_scanner.l" { return T_ENDIF; } #line 6968 "Zend/zend_language_scanner.c" yy763: YYDEBUG(763, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy764; if (yych != 'r') goto yy186; yy764: YYDEBUG(764, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '@') { if (yych <= '/') goto yy765; if (yych <= '9') goto yy185; } else { if (yych == 'E') goto yy766; if (yych <= 'Z') goto yy185; } } else { if (yych <= 'd') { if (yych != '`') goto yy185; } else { if (yych <= 'e') goto yy766; if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy765: YYDEBUG(765, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1073 "Zend/zend_language_scanner.l" { return T_ENDFOR; } #line 7001 "Zend/zend_language_scanner.c" yy766: YYDEBUG(766, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy767; if (yych != 'a') goto yy186; yy767: YYDEBUG(767, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy768; if (yych != 'c') goto yy186; yy768: YYDEBUG(768, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy769; if (yych != 'h') goto yy186; yy769: YYDEBUG(769, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(770, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1081 "Zend/zend_language_scanner.l" { return T_ENDFOREACH; } #line 7029 "Zend/zend_language_scanner.c" yy771: YYDEBUG(771, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy772; if (yych != 'c') goto yy186; yy772: YYDEBUG(772, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy773; if (yych != 'l') goto yy186; yy773: YYDEBUG(773, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy774; if (yych != 'a') goto yy186; yy774: YYDEBUG(774, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy775; if (yych != 'r') goto yy186; yy775: YYDEBUG(775, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy776; if (yych != 'e') goto yy186; yy776: YYDEBUG(776, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(777, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1089 "Zend/zend_language_scanner.l" { return T_ENDDECLARE; } #line 7067 "Zend/zend_language_scanner.c" yy778: YYDEBUG(778, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy779; if (yych != 't') goto yy186; yy779: YYDEBUG(779, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy780; if (yych != 'y') goto yy186; yy780: YYDEBUG(780, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(781, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1275 "Zend/zend_language_scanner.l" { return T_EMPTY; } #line 7090 "Zend/zend_language_scanner.c" yy782: YYDEBUG(782, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy783; if (yych != 'e') goto yy186; yy783: YYDEBUG(783, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '@') { if (yych <= '/') goto yy784; if (yych <= '9') goto yy185; } else { if (yych == 'I') goto yy785; if (yych <= 'Z') goto yy185; } } else { if (yych <= 'h') { if (yych != '`') goto yy185; } else { if (yych <= 'i') goto yy785; if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy784: YYDEBUG(784, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1053 "Zend/zend_language_scanner.l" { return T_ELSE; } #line 7123 "Zend/zend_language_scanner.c" yy785: YYDEBUG(785, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy786; if (yych != 'f') goto yy186; yy786: YYDEBUG(786, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(787, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1045 "Zend/zend_language_scanner.l" { return T_ELSEIF; } #line 7141 "Zend/zend_language_scanner.c" yy788: YYDEBUG(788, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy789; if (yych != 'o') goto yy186; yy789: YYDEBUG(789, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(790, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1129 "Zend/zend_language_scanner.l" { return T_ECHO; } #line 7159 "Zend/zend_language_scanner.c" } /* *********************************** */ yyc_ST_LOOKING_FOR_PROPERTY: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 0, 0, 0, 0, 0, 0, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 0, 0, 0, 0, 64, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 0, 0, 0, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, }; YYDEBUG(791, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych <= '-') { if (yych <= '\r') { if (yych <= 0x08) goto yy799; if (yych <= '\n') goto yy793; if (yych <= '\f') goto yy799; } else { if (yych == ' ') goto yy793; if (yych <= ',') goto yy799; goto yy795; } } else { if (yych <= '_') { if (yych <= '@') goto yy799; if (yych <= 'Z') goto yy797; if (yych <= '^') goto yy799; goto yy797; } else { if (yych <= '`') goto yy799; if (yych <= 'z') goto yy797; if (yych <= '~') goto yy799; goto yy797; } } yy793: YYDEBUG(793, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy805; yy794: YYDEBUG(794, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1162 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; HANDLE_NEWLINES(yytext, yyleng); return T_WHITESPACE; } #line 7240 "Zend/zend_language_scanner.c" yy795: YYDEBUG(795, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '>') goto yy802; yy796: YYDEBUG(796, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1181 "Zend/zend_language_scanner.l" { yyless(0); yy_pop_state(TSRMLS_C); goto restart; } #line 7254 "Zend/zend_language_scanner.c" yy797: YYDEBUG(797, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy801; yy798: YYDEBUG(798, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1174 "Zend/zend_language_scanner.l" { yy_pop_state(TSRMLS_C); zend_copy_value(zendlval, yytext, yyleng); zendlval->type = IS_STRING; return T_STRING; } #line 7270 "Zend/zend_language_scanner.c" yy799: YYDEBUG(799, *YYCURSOR); yych = *++YYCURSOR; goto yy796; yy800: YYDEBUG(800, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy801: YYDEBUG(801, *YYCURSOR); if (yybm[0+yych] & 64) { goto yy800; } goto yy798; yy802: YYDEBUG(802, *YYCURSOR); ++YYCURSOR; YYDEBUG(803, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1170 "Zend/zend_language_scanner.l" { return T_OBJECT_OPERATOR; } #line 7295 "Zend/zend_language_scanner.c" yy804: YYDEBUG(804, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy805: YYDEBUG(805, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy804; } goto yy794; } /* *********************************** */ yyc_ST_LOOKING_FOR_VARNAME: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; YYDEBUG(806, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy810; if (yych <= 'Z') goto yy808; if (yych <= '^') goto yy810; } else { if (yych <= '`') goto yy810; if (yych <= 'z') goto yy808; if (yych <= '~') goto yy810; } yy808: YYDEBUG(808, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy813; yy809: YYDEBUG(809, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1457 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, yytext, yyleng); zendlval->type = IS_STRING; yy_pop_state(TSRMLS_C); yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); return T_STRING_VARNAME; } #line 7373 "Zend/zend_language_scanner.c" yy810: YYDEBUG(810, *YYCURSOR); ++YYCURSOR; YYDEBUG(811, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1466 "Zend/zend_language_scanner.l" { yyless(0); yy_pop_state(TSRMLS_C); yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); goto restart; } #line 7386 "Zend/zend_language_scanner.c" yy812: YYDEBUG(812, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy813: YYDEBUG(813, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy812; } goto yy809; } /* *********************************** */ yyc_ST_NOWDOC: YYDEBUG(814, *YYCURSOR); YYFILL(1); yych = *YYCURSOR; YYDEBUG(816, *YYCURSOR); ++YYCURSOR; YYDEBUG(817, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2344 "Zend/zend_language_scanner.l" { int newline = 0; if (YYCURSOR > YYLIMIT) { return 0; } YYCURSOR--; while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '\r': if (*YYCURSOR == '\n') { YYCURSOR++; } /* fall through */ case '\n': /* Check for ending label on the next line */ if (IS_LABEL_START(*YYCURSOR) && CG(heredoc_len) < YYLIMIT - YYCURSOR && !memcmp(YYCURSOR, CG(heredoc), CG(heredoc_len))) { YYCTYPE *end = YYCURSOR + CG(heredoc_len); if (*end == ';') { end++; } if (*end == '\n' || *end == '\r') { /* newline before label will be subtracted from returned text, but * yyleng/yytext will include it, for zend_highlight/strip, tokenizer, etc. */ if (YYCURSOR[-2] == '\r' && YYCURSOR[-1] == '\n') { newline = 2; /* Windows newline */ } else { newline = 1; } CG(increment_lineno) = 1; /* For newline before label */ BEGIN(ST_END_HEREDOC); goto nowdoc_scan_done; } } /* fall through */ default: continue; } } nowdoc_scan_done: yyleng = YYCURSOR - SCNG(yy_text); zend_copy_value(zendlval, yytext, yyleng - newline); zendlval->type = IS_STRING; HANDLE_NEWLINES(yytext, yyleng - newline); return T_ENCAPSED_AND_WHITESPACE; } #line 7463 "Zend/zend_language_scanner.c" /* *********************************** */ yyc_ST_VAR_OFFSET: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 240, 240, 112, 112, 112, 112, 112, 112, 112, 112, 0, 0, 0, 0, 0, 0, 0, 80, 80, 80, 80, 80, 80, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 16, 0, 80, 80, 80, 80, 80, 80, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, }; YYDEBUG(818, *YYCURSOR); YYFILL(3); yych = *YYCURSOR; if (yych <= '/') { if (yych <= ' ') { if (yych <= '\f') { if (yych <= 0x08) goto yy832; if (yych <= '\n') goto yy828; goto yy832; } else { if (yych <= '\r') goto yy828; if (yych <= 0x1F) goto yy832; goto yy828; } } else { if (yych <= '$') { if (yych <= '"') goto yy827; if (yych <= '#') goto yy828; goto yy823; } else { if (yych == '\'') goto yy828; goto yy827; } } } else { if (yych <= '\\') { if (yych <= '@') { if (yych <= '0') goto yy820; if (yych <= '9') goto yy822; goto yy827; } else { if (yych <= 'Z') goto yy830; if (yych <= '[') goto yy827; goto yy828; } } else { if (yych <= '_') { if (yych <= ']') goto yy825; if (yych <= '^') goto yy827; goto yy830; } else { if (yych <= '`') goto yy827; if (yych <= 'z') goto yy830; if (yych <= '~') goto yy827; goto yy830; } } } yy820: YYDEBUG(820, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'W') { if (yych <= '9') { if (yych >= '0') goto yy844; } else { if (yych == 'B') goto yy841; } } else { if (yych <= 'b') { if (yych <= 'X') goto yy843; if (yych >= 'b') goto yy841; } else { if (yych == 'x') goto yy843; } } yy821: YYDEBUG(821, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1540 "Zend/zend_language_scanner.l" { /* Offset could be treated as a long */ if (yyleng < MAX_LENGTH_OF_LONG - 1 || (yyleng == MAX_LENGTH_OF_LONG - 1 && strcmp(yytext, long_min_digits) < 0)) { zendlval->value.lval = strtol(yytext, NULL, 10); zendlval->type = IS_LONG; } else { zendlval->value.str.val = (char *)estrndup(yytext, yyleng); zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; } return T_NUM_STRING; } #line 7582 "Zend/zend_language_scanner.c" yy822: YYDEBUG(822, *YYCURSOR); yych = *++YYCURSOR; goto yy840; yy823: YYDEBUG(823, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '_') { if (yych <= '@') goto yy824; if (yych <= 'Z') goto yy836; if (yych >= '_') goto yy836; } else { if (yych <= '`') goto yy824; if (yych <= 'z') goto yy836; if (yych >= 0x7F) goto yy836; } yy824: YYDEBUG(824, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1872 "Zend/zend_language_scanner.l" { /* Only '[' can be valid, but returning other tokens will allow a more explicit parse error */ return yytext[0]; } #line 7607 "Zend/zend_language_scanner.c" yy825: YYDEBUG(825, *YYCURSOR); ++YYCURSOR; YYDEBUG(826, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1867 "Zend/zend_language_scanner.l" { yy_pop_state(TSRMLS_C); return ']'; } #line 7618 "Zend/zend_language_scanner.c" yy827: YYDEBUG(827, *YYCURSOR); yych = *++YYCURSOR; goto yy824; yy828: YYDEBUG(828, *YYCURSOR); ++YYCURSOR; YYDEBUG(829, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1877 "Zend/zend_language_scanner.l" { /* Invalid rule to return a more explicit parse error with proper line number */ yyless(0); yy_pop_state(TSRMLS_C); return T_ENCAPSED_AND_WHITESPACE; } #line 7635 "Zend/zend_language_scanner.c" yy830: YYDEBUG(830, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy835; yy831: YYDEBUG(831, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1884 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, yytext, yyleng); zendlval->type = IS_STRING; return T_STRING; } #line 7650 "Zend/zend_language_scanner.c" yy832: YYDEBUG(832, *YYCURSOR); ++YYCURSOR; YYDEBUG(833, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2400 "Zend/zend_language_scanner.l" { if (YYCURSOR > YYLIMIT) { return 0; } zend_error(E_COMPILE_WARNING,"Unexpected character in input: '%c' (ASCII=%d) state=%d", yytext[0], yytext[0], YYSTATE); goto restart; } #line 7665 "Zend/zend_language_scanner.c" yy834: YYDEBUG(834, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy835: YYDEBUG(835, *YYCURSOR); if (yybm[0+yych] & 16) { goto yy834; } goto yy831; yy836: YYDEBUG(836, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(837, *YYCURSOR); if (yych <= '^') { if (yych <= '9') { if (yych >= '0') goto yy836; } else { if (yych <= '@') goto yy838; if (yych <= 'Z') goto yy836; } } else { if (yych <= '`') { if (yych <= '_') goto yy836; } else { if (yych <= 'z') goto yy836; if (yych >= 0x7F) goto yy836; } } yy838: YYDEBUG(838, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1861 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 7707 "Zend/zend_language_scanner.c" yy839: YYDEBUG(839, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy840: YYDEBUG(840, *YYCURSOR); if (yybm[0+yych] & 32) { goto yy839; } goto yy821; yy841: YYDEBUG(841, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 128) { goto yy849; } yy842: YYDEBUG(842, *YYCURSOR); YYCURSOR = YYMARKER; goto yy821; yy843: YYDEBUG(843, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 64) { goto yy847; } goto yy842; yy844: YYDEBUG(844, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(845, *YYCURSOR); if (yych <= '/') goto yy846; if (yych <= '9') goto yy844; yy846: YYDEBUG(846, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1552 "Zend/zend_language_scanner.l" { /* Offset must be treated as a string */ zendlval->value.str.val = (char *)estrndup(yytext, yyleng); zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; return T_NUM_STRING; } #line 7754 "Zend/zend_language_scanner.c" yy847: YYDEBUG(847, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(848, *YYCURSOR); if (yybm[0+yych] & 64) { goto yy847; } goto yy846; yy849: YYDEBUG(849, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(850, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy849; } goto yy846; } } #line 2409 "Zend/zend_language_scanner.l" } /* Generated by re2c 0.13.5 on Thu Mar 1 21:30:38 2012 */ #line 1 "Zend/zend_language_scanner.l" /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2012 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Marcus Boerger <[email protected]> | | Nuno Lopes <[email protected]> | | Scott MacVicar <[email protected]> | | Flex version authors: | | Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #if 0 # define YYDEBUG(s, c) printf("state: %d char: %c\n", s, c) #else # define YYDEBUG(s, c) #endif #include "zend_language_scanner_defs.h" #include <errno.h> #include "zend.h" #include "zend_alloc.h" #include <zend_language_parser.h> #include "zend_compile.h" #include "zend_language_scanner.h" #include "zend_highlight.h" #include "zend_constants.h" #include "zend_variables.h" #include "zend_operators.h" #include "zend_API.h" #include "zend_strtod.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "tsrm_config_common.h" #define YYCTYPE unsigned char #define YYFILL(n) { if ((YYCURSOR + n) >= (YYLIMIT + ZEND_MMAP_AHEAD)) { return 0; } } #define YYCURSOR SCNG(yy_cursor) #define YYLIMIT SCNG(yy_limit) #define YYMARKER SCNG(yy_marker) #define YYGETCONDITION() SCNG(yy_state) #define YYSETCONDITION(s) SCNG(yy_state) = s #define STATE(name) yyc##name /* emulate flex constructs */ #define BEGIN(state) YYSETCONDITION(STATE(state)) #define YYSTATE YYGETCONDITION() #define yytext ((char*)SCNG(yy_text)) #define yyleng SCNG(yy_leng) #define yyless(x) do { YYCURSOR = (unsigned char*)yytext + x; \ yyleng = (unsigned int)x; } while(0) #define yymore() goto yymore_restart /* perform sanity check. If this message is triggered you should increase the ZEND_MMAP_AHEAD value in the zend_streams.h file */ #define YYMAXFILL 16 #if ZEND_MMAP_AHEAD < YYMAXFILL # error ZEND_MMAP_AHEAD should be greater than or equal to YYMAXFILL #endif #ifdef HAVE_STDARG_H # include <stdarg.h> #endif #ifdef HAVE_UNISTD_H # include <unistd.h> #endif /* Globals Macros */ #define SCNG LANG_SCNG #ifdef ZTS ZEND_API ts_rsrc_id language_scanner_globals_id; #else ZEND_API zend_php_scanner_globals language_scanner_globals; #endif #define HANDLE_NEWLINES(s, l) \ do { \ char *p = (s), *boundary = p+(l); \ \ while (p<boundary) { \ if (*p == '\n' || (*p == '\r' && (*(p+1) != '\n'))) { \ CG(zend_lineno)++; \ } \ p++; \ } \ } while (0) #define HANDLE_NEWLINE(c) \ { \ if (c == '\n' || c == '\r') { \ CG(zend_lineno)++; \ } \ } /* To save initial string length after scanning to first variable, CG(doc_comment_len) can be reused */ #define SET_DOUBLE_QUOTES_SCANNED_LENGTH(len) CG(doc_comment_len) = (len) #define GET_DOUBLE_QUOTES_SCANNED_LENGTH() CG(doc_comment_len) #define IS_LABEL_START(c) (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z') || (c) == '_' || (c) >= 0x7F) #define ZEND_IS_OCT(c) ((c)>='0' && (c)<='7') #define ZEND_IS_HEX(c) (((c)>='0' && (c)<='9') || ((c)>='a' && (c)<='f') || ((c)>='A' && (c)<='F')) BEGIN_EXTERN_C() static size_t encoding_filter_script_to_internal(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) { const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding(TSRMLS_C); assert(internal_encoding && zend_multibyte_check_lexer_compatibility(internal_encoding)); return zend_multibyte_encoding_converter(to, to_length, from, from_length, internal_encoding, LANG_SCNG(script_encoding) TSRMLS_CC); } static size_t encoding_filter_script_to_intermediate(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) { return zend_multibyte_encoding_converter(to, to_length, from, from_length, zend_multibyte_encoding_utf8, LANG_SCNG(script_encoding) TSRMLS_CC); } static size_t encoding_filter_intermediate_to_script(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) { return zend_multibyte_encoding_converter(to, to_length, from, from_length, LANG_SCNG(script_encoding), zend_multibyte_encoding_utf8 TSRMLS_CC); } static size_t encoding_filter_intermediate_to_internal(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length TSRMLS_DC) { const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding(TSRMLS_C); assert(internal_encoding && zend_multibyte_check_lexer_compatibility(internal_encoding)); return zend_multibyte_encoding_converter(to, to_length, from, from_length, internal_encoding, zend_multibyte_encoding_utf8 TSRMLS_CC); } static void _yy_push_state(int new_state TSRMLS_DC) { zend_stack_push(&SCNG(state_stack), (void *) &YYGETCONDITION(), sizeof(int)); YYSETCONDITION(new_state); } #define yy_push_state(state_and_tsrm) _yy_push_state(yyc##state_and_tsrm) static void yy_pop_state(TSRMLS_D) { int *stack_state; zend_stack_top(&SCNG(state_stack), (void **) &stack_state); YYSETCONDITION(*stack_state); zend_stack_del_top(&SCNG(state_stack)); } static void yy_scan_buffer(char *str, unsigned int len TSRMLS_DC) { YYCURSOR = (YYCTYPE*)str; YYLIMIT = YYCURSOR + len; if (!SCNG(yy_start)) { SCNG(yy_start) = YYCURSOR; } } void startup_scanner(TSRMLS_D) { CG(parse_error) = 0; CG(heredoc) = NULL; CG(heredoc_len) = 0; CG(doc_comment) = NULL; CG(doc_comment_len) = 0; zend_stack_init(&SCNG(state_stack)); } void shutdown_scanner(TSRMLS_D) { if (CG(heredoc)) { efree(CG(heredoc)); CG(heredoc_len)=0; } CG(parse_error) = 0; zend_stack_destroy(&SCNG(state_stack)); RESET_DOC_COMMENT(); } ZEND_API void zend_save_lexical_state(zend_lex_state *lex_state TSRMLS_DC) { lex_state->yy_leng = SCNG(yy_leng); lex_state->yy_start = SCNG(yy_start); lex_state->yy_text = SCNG(yy_text); lex_state->yy_cursor = SCNG(yy_cursor); lex_state->yy_marker = SCNG(yy_marker); lex_state->yy_limit = SCNG(yy_limit); lex_state->state_stack = SCNG(state_stack); zend_stack_init(&SCNG(state_stack)); lex_state->in = SCNG(yy_in); lex_state->yy_state = YYSTATE; lex_state->filename = zend_get_compiled_filename(TSRMLS_C); lex_state->lineno = CG(zend_lineno); lex_state->script_org = SCNG(script_org); lex_state->script_org_size = SCNG(script_org_size); lex_state->script_filtered = SCNG(script_filtered); lex_state->script_filtered_size = SCNG(script_filtered_size); lex_state->input_filter = SCNG(input_filter); lex_state->output_filter = SCNG(output_filter); lex_state->script_encoding = SCNG(script_encoding); } ZEND_API void zend_restore_lexical_state(zend_lex_state *lex_state TSRMLS_DC) { SCNG(yy_leng) = lex_state->yy_leng; SCNG(yy_start) = lex_state->yy_start; SCNG(yy_text) = lex_state->yy_text; SCNG(yy_cursor) = lex_state->yy_cursor; SCNG(yy_marker) = lex_state->yy_marker; SCNG(yy_limit) = lex_state->yy_limit; zend_stack_destroy(&SCNG(state_stack)); SCNG(state_stack) = lex_state->state_stack; SCNG(yy_in) = lex_state->in; YYSETCONDITION(lex_state->yy_state); CG(zend_lineno) = lex_state->lineno; zend_restore_compiled_filename(lex_state->filename TSRMLS_CC); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } SCNG(script_org) = lex_state->script_org; SCNG(script_org_size) = lex_state->script_org_size; SCNG(script_filtered) = lex_state->script_filtered; SCNG(script_filtered_size) = lex_state->script_filtered_size; SCNG(input_filter) = lex_state->input_filter; SCNG(output_filter) = lex_state->output_filter; SCNG(script_encoding) = lex_state->script_encoding; if (CG(heredoc)) { efree(CG(heredoc)); CG(heredoc) = NULL; CG(heredoc_len) = 0; } } ZEND_API void zend_destroy_file_handle(zend_file_handle *file_handle TSRMLS_DC) { zend_llist_del_element(&CG(open_files), file_handle, (int (*)(void *, void *)) zend_compare_file_handles); /* zend_file_handle_dtor() operates on the copy, so we have to NULLify the original here */ file_handle->opened_path = NULL; if (file_handle->free_filename) { file_handle->filename = NULL; } } #define BOM_UTF32_BE "\x00\x00\xfe\xff" #define BOM_UTF32_LE "\xff\xfe\x00\x00" #define BOM_UTF16_BE "\xfe\xff" #define BOM_UTF16_LE "\xff\xfe" #define BOM_UTF8 "\xef\xbb\xbf" static const zend_encoding *zend_multibyte_detect_utf_encoding(const unsigned char *script, size_t script_size TSRMLS_DC) { const unsigned char *p; int wchar_size = 2; int le = 0; /* utf-16 or utf-32? */ p = script; while ((p-script) < script_size) { p = memchr(p, 0, script_size-(p-script)-2); if (!p) { break; } if (*(p+1) == '\0' && *(p+2) == '\0') { wchar_size = 4; break; } /* searching for UTF-32 specific byte orders, so this will do */ p += 4; } /* BE or LE? */ p = script; while ((p-script) < script_size) { if (*p == '\0' && *(p+wchar_size-1) != '\0') { /* BE */ le = 0; break; } else if (*p != '\0' && *(p+wchar_size-1) == '\0') { /* LE* */ le = 1; break; } p += wchar_size; } if (wchar_size == 2) { return le ? zend_multibyte_encoding_utf16le : zend_multibyte_encoding_utf16be; } else { return le ? zend_multibyte_encoding_utf32le : zend_multibyte_encoding_utf32be; } return NULL; } static const zend_encoding* zend_multibyte_detect_unicode(TSRMLS_D) { const zend_encoding *script_encoding = NULL; int bom_size; unsigned char *pos1, *pos2; if (LANG_SCNG(script_org_size) < sizeof(BOM_UTF32_LE)-1) { return NULL; } /* check out BOM */ if (!memcmp(LANG_SCNG(script_org), BOM_UTF32_BE, sizeof(BOM_UTF32_BE)-1)) { script_encoding = zend_multibyte_encoding_utf32be; bom_size = sizeof(BOM_UTF32_BE)-1; } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF32_LE, sizeof(BOM_UTF32_LE)-1)) { script_encoding = zend_multibyte_encoding_utf32le; bom_size = sizeof(BOM_UTF32_LE)-1; } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF16_BE, sizeof(BOM_UTF16_BE)-1)) { script_encoding = zend_multibyte_encoding_utf16be; bom_size = sizeof(BOM_UTF16_BE)-1; } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF16_LE, sizeof(BOM_UTF16_LE)-1)) { script_encoding = zend_multibyte_encoding_utf16le; bom_size = sizeof(BOM_UTF16_LE)-1; } else if (!memcmp(LANG_SCNG(script_org), BOM_UTF8, sizeof(BOM_UTF8)-1)) { script_encoding = zend_multibyte_encoding_utf8; bom_size = sizeof(BOM_UTF8)-1; } if (script_encoding) { /* remove BOM */ LANG_SCNG(script_org) += bom_size; LANG_SCNG(script_org_size) -= bom_size; return script_encoding; } /* script contains NULL bytes -> auto-detection */ if ((pos1 = memchr(LANG_SCNG(script_org), 0, LANG_SCNG(script_org_size)))) { /* check if the NULL byte is after the __HALT_COMPILER(); */ pos2 = LANG_SCNG(script_org); while (pos1 - pos2 >= sizeof("__HALT_COMPILER();")-1) { pos2 = memchr(pos2, '_', pos1 - pos2); if (!pos2) break; pos2++; if (strncasecmp((char*)pos2, "_HALT_COMPILER", sizeof("_HALT_COMPILER")-1) == 0) { pos2 += sizeof("_HALT_COMPILER")-1; while (*pos2 == ' ' || *pos2 == '\t' || *pos2 == '\r' || *pos2 == '\n') { pos2++; } if (*pos2 == '(') { pos2++; while (*pos2 == ' ' || *pos2 == '\t' || *pos2 == '\r' || *pos2 == '\n') { pos2++; } if (*pos2 == ')') { pos2++; while (*pos2 == ' ' || *pos2 == '\t' || *pos2 == '\r' || *pos2 == '\n') { pos2++; } if (*pos2 == ';') { return NULL; } } } } } /* make best effort if BOM is missing */ return zend_multibyte_detect_utf_encoding(LANG_SCNG(script_org), LANG_SCNG(script_org_size) TSRMLS_CC); } return NULL; } static const zend_encoding* zend_multibyte_find_script_encoding(TSRMLS_D) { const zend_encoding *script_encoding; if (CG(detect_unicode)) { /* check out bom(byte order mark) and see if containing wchars */ script_encoding = zend_multibyte_detect_unicode(TSRMLS_C); if (script_encoding != NULL) { /* bom or wchar detection is prior to 'script_encoding' option */ return script_encoding; } } /* if no script_encoding specified, just leave alone */ if (!CG(script_encoding_list) || !CG(script_encoding_list_size)) { return NULL; } /* if multiple encodings specified, detect automagically */ if (CG(script_encoding_list_size) > 1) { return zend_multibyte_encoding_detector(LANG_SCNG(script_org), LANG_SCNG(script_org_size), CG(script_encoding_list), CG(script_encoding_list_size) TSRMLS_CC); } return CG(script_encoding_list)[0]; } ZEND_API int zend_multibyte_set_filter(const zend_encoding *onetime_encoding TSRMLS_DC) { const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding(TSRMLS_C); const zend_encoding *script_encoding = onetime_encoding ? onetime_encoding: zend_multibyte_find_script_encoding(TSRMLS_C); if (!script_encoding) { return FAILURE; } /* judge input/output filter */ LANG_SCNG(script_encoding) = script_encoding; LANG_SCNG(input_filter) = NULL; LANG_SCNG(output_filter) = NULL; if (!internal_encoding || LANG_SCNG(script_encoding) == internal_encoding) { if (!zend_multibyte_check_lexer_compatibility(LANG_SCNG(script_encoding))) { /* and if not, work around w/ script_encoding -> utf-8 -> script_encoding conversion */ LANG_SCNG(input_filter) = encoding_filter_script_to_intermediate; LANG_SCNG(output_filter) = encoding_filter_intermediate_to_script; } else { LANG_SCNG(input_filter) = NULL; LANG_SCNG(output_filter) = NULL; } return SUCCESS; } if (zend_multibyte_check_lexer_compatibility(internal_encoding)) { LANG_SCNG(input_filter) = encoding_filter_script_to_internal; LANG_SCNG(output_filter) = NULL; } else if (zend_multibyte_check_lexer_compatibility(LANG_SCNG(script_encoding))) { LANG_SCNG(input_filter) = NULL; LANG_SCNG(output_filter) = encoding_filter_script_to_internal; } else { /* both script and internal encodings are incompatible w/ flex */ LANG_SCNG(input_filter) = encoding_filter_script_to_intermediate; LANG_SCNG(output_filter) = encoding_filter_intermediate_to_internal; } return 0; } ZEND_API int open_file_for_scanning(zend_file_handle *file_handle TSRMLS_DC) { const char *file_path = NULL; char *buf; size_t size, offset = 0; /* The shebang line was read, get the current position to obtain the buffer start */ if (CG(start_lineno) == 2 && file_handle->type == ZEND_HANDLE_FP && file_handle->handle.fp) { if ((offset = ftell(file_handle->handle.fp)) == -1) { offset = 0; } } if (zend_stream_fixup(file_handle, &buf, &size TSRMLS_CC) == FAILURE) { return FAILURE; } zend_llist_add_element(&CG(open_files), file_handle); if (file_handle->handle.stream.handle >= (void*)file_handle && file_handle->handle.stream.handle <= (void*)(file_handle+1)) { zend_file_handle *fh = (zend_file_handle*)zend_llist_get_last(&CG(open_files)); size_t diff = (char*)file_handle->handle.stream.handle - (char*)file_handle; fh->handle.stream.handle = (void*)(((char*)fh) + diff); file_handle->handle.stream.handle = fh->handle.stream.handle; } /* Reset the scanner for scanning the new file */ SCNG(yy_in) = file_handle; SCNG(yy_start) = NULL; if (size != -1) { if (CG(multibyte)) { SCNG(script_org) = (unsigned char*)buf; SCNG(script_org_size) = size; SCNG(script_filtered) = NULL; zend_multibyte_set_filter(NULL TSRMLS_CC); if (SCNG(input_filter)) { if ((size_t)-1 == SCNG(input_filter)(&SCNG(script_filtered), &SCNG(script_filtered_size), SCNG(script_org), SCNG(script_org_size) TSRMLS_CC)) { zend_error_noreturn(E_COMPILE_ERROR, "Could not convert the script from the detected " "encoding \"%s\" to a compatible encoding", zend_multibyte_get_encoding_name(LANG_SCNG(script_encoding))); } buf = (char*)SCNG(script_filtered); size = SCNG(script_filtered_size); } } SCNG(yy_start) = (unsigned char *)buf - offset; yy_scan_buffer(buf, size TSRMLS_CC); } else { zend_error_noreturn(E_COMPILE_ERROR, "zend_stream_mmap() failed"); } BEGIN(INITIAL); if (file_handle->opened_path) { file_path = file_handle->opened_path; } else { file_path = file_handle->filename; } zend_set_compiled_filename(file_path TSRMLS_CC); if (CG(start_lineno)) { CG(zend_lineno) = CG(start_lineno); CG(start_lineno) = 0; } else { CG(zend_lineno) = 1; } CG(increment_lineno) = 0; return SUCCESS; } END_EXTERN_C() ZEND_API zend_op_array *compile_file(zend_file_handle *file_handle, int type TSRMLS_DC) { zend_lex_state original_lex_state; zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array)); zend_op_array *original_active_op_array = CG(active_op_array); zend_op_array *retval=NULL; int compiler_result; zend_bool compilation_successful=0; znode retval_znode; zend_bool original_in_compilation = CG(in_compilation); retval_znode.op_type = IS_CONST; retval_znode.u.constant.type = IS_LONG; retval_znode.u.constant.value.lval = 1; Z_UNSET_ISREF(retval_znode.u.constant); Z_SET_REFCOUNT(retval_znode.u.constant, 1); zend_save_lexical_state(&original_lex_state TSRMLS_CC); retval = op_array; /* success oriented */ if (open_file_for_scanning(file_handle TSRMLS_CC)==FAILURE) { if (type==ZEND_REQUIRE) { zend_message_dispatcher(ZMSG_FAILED_REQUIRE_FOPEN, file_handle->filename TSRMLS_CC); zend_bailout(); } else { zend_message_dispatcher(ZMSG_FAILED_INCLUDE_FOPEN, file_handle->filename TSRMLS_CC); } compilation_successful=0; } else { init_op_array(op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(in_compilation) = 1; CG(active_op_array) = op_array; zend_init_compiler_context(TSRMLS_C); compiler_result = zendparse(TSRMLS_C); zend_do_return(&retval_znode, 0 TSRMLS_CC); CG(in_compilation) = original_in_compilation; if (compiler_result==1) { /* parser error */ zend_bailout(); } compilation_successful=1; } if (retval) { CG(active_op_array) = original_active_op_array; if (compilation_successful) { pass_two(op_array TSRMLS_CC); zend_release_labels(TSRMLS_C); } else { efree(op_array); retval = NULL; } } zend_restore_lexical_state(&original_lex_state TSRMLS_CC); return retval; } zend_op_array *compile_filename(int type, zval *filename TSRMLS_DC) { zend_file_handle file_handle; zval tmp; zend_op_array *retval; char *opened_path = NULL; if (filename->type != IS_STRING) { tmp = *filename; zval_copy_ctor(&tmp); convert_to_string(&tmp); filename = &tmp; } file_handle.filename = filename->value.str.val; file_handle.free_filename = 0; file_handle.type = ZEND_HANDLE_FILENAME; file_handle.opened_path = NULL; file_handle.handle.fp = NULL; retval = zend_compile_file(&file_handle, type TSRMLS_CC); if (retval && file_handle.handle.stream.handle) { int dummy = 1; if (!file_handle.opened_path) { file_handle.opened_path = opened_path = estrndup(filename->value.str.val, filename->value.str.len); } zend_hash_add(&EG(included_files), file_handle.opened_path, strlen(file_handle.opened_path)+1, (void *)&dummy, sizeof(int), NULL); if (opened_path) { efree(opened_path); } } zend_destroy_file_handle(&file_handle TSRMLS_CC); if (filename==&tmp) { zval_dtor(&tmp); } return retval; } ZEND_API int zend_prepare_string_for_scanning(zval *str, char *filename TSRMLS_DC) { char *buf; size_t size; /* enforce two trailing NULLs for flex... */ if (IS_INTERNED(str->value.str.val)) { char *tmp = safe_emalloc(1, str->value.str.len, ZEND_MMAP_AHEAD); memcpy(tmp, str->value.str.val, str->value.str.len + ZEND_MMAP_AHEAD); str->value.str.val = tmp; } else { str->value.str.val = safe_erealloc(str->value.str.val, 1, str->value.str.len, ZEND_MMAP_AHEAD); } memset(str->value.str.val + str->value.str.len, 0, ZEND_MMAP_AHEAD); SCNG(yy_in) = NULL; SCNG(yy_start) = NULL; buf = str->value.str.val; size = str->value.str.len; if (CG(multibyte)) { SCNG(script_org) = (unsigned char*)buf; SCNG(script_org_size) = size; SCNG(script_filtered) = NULL; zend_multibyte_set_filter(zend_multibyte_get_internal_encoding(TSRMLS_C) TSRMLS_CC); if (SCNG(input_filter)) { if ((size_t)-1 == SCNG(input_filter)(&SCNG(script_filtered), &SCNG(script_filtered_size), SCNG(script_org), SCNG(script_org_size) TSRMLS_CC)) { zend_error_noreturn(E_COMPILE_ERROR, "Could not convert the script from the detected " "encoding \"%s\" to a compatible encoding", zend_multibyte_get_encoding_name(LANG_SCNG(script_encoding))); } buf = (char*)SCNG(script_filtered); size = SCNG(script_filtered_size); } } yy_scan_buffer(buf, size TSRMLS_CC); zend_set_compiled_filename(filename TSRMLS_CC); CG(zend_lineno) = 1; CG(increment_lineno) = 0; return SUCCESS; } ZEND_API size_t zend_get_scanned_file_offset(TSRMLS_D) { size_t offset = SCNG(yy_cursor) - SCNG(yy_start); if (SCNG(input_filter)) { size_t original_offset = offset, length = 0; do { unsigned char *p = NULL; if ((size_t)-1 == SCNG(input_filter)(&p, &length, SCNG(script_org), offset TSRMLS_CC)) { return (size_t)-1; } efree(p); if (length > original_offset) { offset--; } else if (length < original_offset) { offset++; } } while (original_offset != length); } return offset; } zend_op_array *compile_string(zval *source_string, char *filename TSRMLS_DC) { zend_lex_state original_lex_state; zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array)); zend_op_array *original_active_op_array = CG(active_op_array); zend_op_array *retval; zval tmp; int compiler_result; zend_bool original_in_compilation = CG(in_compilation); if (source_string->value.str.len==0) { efree(op_array); return NULL; } CG(in_compilation) = 1; tmp = *source_string; zval_copy_ctor(&tmp); convert_to_string(&tmp); source_string = &tmp; zend_save_lexical_state(&original_lex_state TSRMLS_CC); if (zend_prepare_string_for_scanning(source_string, filename TSRMLS_CC)==FAILURE) { efree(op_array); retval = NULL; } else { zend_bool orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(op_array, ZEND_EVAL_CODE, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; CG(active_op_array) = op_array; zend_init_compiler_context(TSRMLS_C); BEGIN(ST_IN_SCRIPTING); compiler_result = zendparse(TSRMLS_C); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } if (compiler_result==1) { CG(active_op_array) = original_active_op_array; CG(unclean_shutdown)=1; destroy_op_array(op_array TSRMLS_CC); efree(op_array); retval = NULL; } else { zend_do_return(NULL, 0 TSRMLS_CC); CG(active_op_array) = original_active_op_array; pass_two(op_array TSRMLS_CC); zend_release_labels(TSRMLS_C); retval = op_array; } } zend_restore_lexical_state(&original_lex_state TSRMLS_CC); zval_dtor(&tmp); CG(in_compilation) = original_in_compilation; return retval; } BEGIN_EXTERN_C() int highlight_file(char *filename, zend_syntax_highlighter_ini *syntax_highlighter_ini TSRMLS_DC) { zend_lex_state original_lex_state; zend_file_handle file_handle; file_handle.type = ZEND_HANDLE_FILENAME; file_handle.filename = filename; file_handle.free_filename = 0; file_handle.opened_path = NULL; zend_save_lexical_state(&original_lex_state TSRMLS_CC); if (open_file_for_scanning(&file_handle TSRMLS_CC)==FAILURE) { zend_message_dispatcher(ZMSG_FAILED_HIGHLIGHT_FOPEN, filename TSRMLS_CC); zend_restore_lexical_state(&original_lex_state TSRMLS_CC); return FAILURE; } zend_highlight(syntax_highlighter_ini TSRMLS_CC); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } zend_destroy_file_handle(&file_handle TSRMLS_CC); zend_restore_lexical_state(&original_lex_state TSRMLS_CC); return SUCCESS; } int highlight_string(zval *str, zend_syntax_highlighter_ini *syntax_highlighter_ini, char *str_name TSRMLS_DC) { zend_lex_state original_lex_state; zval tmp = *str; str = &tmp; zval_copy_ctor(str); zend_save_lexical_state(&original_lex_state TSRMLS_CC); if (zend_prepare_string_for_scanning(str, str_name TSRMLS_CC)==FAILURE) { zend_restore_lexical_state(&original_lex_state TSRMLS_CC); return FAILURE; } BEGIN(INITIAL); zend_highlight(syntax_highlighter_ini TSRMLS_CC); if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } zend_restore_lexical_state(&original_lex_state TSRMLS_CC); zval_dtor(str); return SUCCESS; } ZEND_API void zend_multibyte_yyinput_again(zend_encoding_filter old_input_filter, const zend_encoding *old_encoding TSRMLS_DC) { size_t length; unsigned char *new_yy_start; /* convert and set */ if (!SCNG(input_filter)) { if (SCNG(script_filtered)) { efree(SCNG(script_filtered)); SCNG(script_filtered) = NULL; } SCNG(script_filtered_size) = 0; length = SCNG(script_org_size); new_yy_start = SCNG(script_org); } else { if ((size_t)-1 == SCNG(input_filter)(&new_yy_start, &length, SCNG(script_org), SCNG(script_org_size) TSRMLS_CC)) { zend_error_noreturn(E_COMPILE_ERROR, "Could not convert the script from the detected " "encoding \"%s\" to a compatible encoding", zend_multibyte_get_encoding_name(LANG_SCNG(script_encoding))); } SCNG(script_filtered) = new_yy_start; SCNG(script_filtered_size) = length; } SCNG(yy_cursor) = new_yy_start + (SCNG(yy_cursor) - SCNG(yy_start)); SCNG(yy_marker) = new_yy_start + (SCNG(yy_marker) - SCNG(yy_start)); SCNG(yy_text) = new_yy_start + (SCNG(yy_text) - SCNG(yy_start)); SCNG(yy_limit) = new_yy_start + (SCNG(yy_limit) - SCNG(yy_start)); SCNG(yy_start) = new_yy_start; } # define zend_copy_value(zendlval, yytext, yyleng) \ if (SCNG(output_filter)) { \ size_t sz = 0; \ SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)yytext, (size_t)yyleng TSRMLS_CC); \ zendlval->value.str.len = sz; \ } else { \ zendlval->value.str.val = (char *) estrndup(yytext, yyleng); \ zendlval->value.str.len = yyleng; \ } static void zend_scan_escape_string(zval *zendlval, char *str, int len, char quote_type TSRMLS_DC) { register char *s, *t; char *end; ZVAL_STRINGL(zendlval, str, len, 1); /* convert escape sequences */ s = t = zendlval->value.str.val; end = s+zendlval->value.str.len; while (s<end) { if (*s=='\\') { s++; if (s >= end) { *t++ = '\\'; break; } switch(*s) { case 'n': *t++ = '\n'; zendlval->value.str.len--; break; case 'r': *t++ = '\r'; zendlval->value.str.len--; break; case 't': *t++ = '\t'; zendlval->value.str.len--; break; case 'f': *t++ = '\f'; zendlval->value.str.len--; break; case 'v': *t++ = '\v'; zendlval->value.str.len--; break; case 'e': *t++ = '\e'; zendlval->value.str.len--; break; case '"': case '`': if (*s != quote_type) { *t++ = '\\'; *t++ = *s; break; } case '\\': case '$': *t++ = *s; zendlval->value.str.len--; break; case 'x': case 'X': if (ZEND_IS_HEX(*(s+1))) { char hex_buf[3] = { 0, 0, 0 }; zendlval->value.str.len--; /* for the 'x' */ hex_buf[0] = *(++s); zendlval->value.str.len--; if (ZEND_IS_HEX(*(s+1))) { hex_buf[1] = *(++s); zendlval->value.str.len--; } *t++ = (char) strtol(hex_buf, NULL, 16); } else { *t++ = '\\'; *t++ = *s; } break; default: /* check for an octal */ if (ZEND_IS_OCT(*s)) { char octal_buf[4] = { 0, 0, 0, 0 }; octal_buf[0] = *s; zendlval->value.str.len--; if (ZEND_IS_OCT(*(s+1))) { octal_buf[1] = *(++s); zendlval->value.str.len--; if (ZEND_IS_OCT(*(s+1))) { octal_buf[2] = *(++s); zendlval->value.str.len--; } } *t++ = (char) strtol(octal_buf, NULL, 8); } else { *t++ = '\\'; *t++ = *s; } break; } } else { *t++ = *s; } if (*s == '\n' || (*s == '\r' && (*(s+1) != '\n'))) { CG(zend_lineno)++; } s++; } *t = 0; if (SCNG(output_filter)) { size_t sz = 0; s = zendlval->value.str.val; SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)s, (size_t)zendlval->value.str.len TSRMLS_CC); zendlval->value.str.len = sz; efree(s); } } int lex_scan(zval *zendlval TSRMLS_DC) { restart: SCNG(yy_text) = YYCURSOR; yymore_restart: #line 995 "Zend/zend_language_scanner.c" { YYCTYPE yych; unsigned int yyaccept = 0; if (YYGETCONDITION() < 5) { if (YYGETCONDITION() < 2) { if (YYGETCONDITION() < 1) { goto yyc_ST_IN_SCRIPTING; } else { goto yyc_ST_LOOKING_FOR_PROPERTY; } } else { if (YYGETCONDITION() < 3) { goto yyc_ST_BACKQUOTE; } else { if (YYGETCONDITION() < 4) { goto yyc_ST_DOUBLE_QUOTES; } else { goto yyc_ST_HEREDOC; } } } } else { if (YYGETCONDITION() < 7) { if (YYGETCONDITION() < 6) { goto yyc_ST_LOOKING_FOR_VARNAME; } else { goto yyc_ST_VAR_OFFSET; } } else { if (YYGETCONDITION() < 8) { goto yyc_INITIAL; } else { if (YYGETCONDITION() < 9) { goto yyc_ST_END_HEREDOC; } else { goto yyc_ST_NOWDOC; } } } } /* *********************************** */ yyc_INITIAL: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; YYDEBUG(0, *YYCURSOR); YYFILL(8); yych = *YYCURSOR; if (yych != '<') goto yy4; YYDEBUG(2, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '?') { if (yych == '%') goto yy7; if (yych >= '?') goto yy5; } else { if (yych <= 'S') { if (yych >= 'S') goto yy9; } else { if (yych == 's') goto yy9; } } yy3: YYDEBUG(3, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1783 "Zend/zend_language_scanner.l" { if (YYCURSOR > YYLIMIT) { return 0; } inline_char_handler: while (1) { YYCTYPE *ptr = memchr(YYCURSOR, '<', YYLIMIT - YYCURSOR); YYCURSOR = ptr ? ptr + 1 : YYLIMIT; if (YYCURSOR < YYLIMIT) { switch (*YYCURSOR) { case '?': if (CG(short_tags) || !strncasecmp((char*)YYCURSOR + 1, "php", 3) || (*(YYCURSOR + 1) == '=')) { /* Assume [ \t\n\r] follows "php" */ break; } continue; case '%': if (CG(asp_tags)) { break; } continue; case 's': case 'S': /* Probably NOT an opening PHP <script> tag, so don't end the HTML chunk yet * If it is, the PHP <script> tag rule checks for any HTML scanned before it */ YYCURSOR--; yymore(); default: continue; } YYCURSOR--; } break; } inline_html: yyleng = YYCURSOR - SCNG(yy_text); if (SCNG(output_filter)) { int readsize; size_t sz = 0; readsize = SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)yytext, (size_t)yyleng TSRMLS_CC); zendlval->value.str.len = sz; if (readsize < yyleng) { yyless(readsize); } } else { zendlval->value.str.val = (char *) estrndup(yytext, yyleng); zendlval->value.str.len = yyleng; } zendlval->type = IS_STRING; HANDLE_NEWLINES(yytext, yyleng); return T_INLINE_HTML; } #line 1154 "Zend/zend_language_scanner.c" yy4: YYDEBUG(4, *YYCURSOR); yych = *++YYCURSOR; goto yy3; yy5: YYDEBUG(5, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'O') { if (yych == '=') goto yy45; } else { if (yych <= 'P') goto yy47; if (yych == 'p') goto yy47; } yy6: YYDEBUG(6, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1771 "Zend/zend_language_scanner.l" { if (CG(short_tags)) { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG; } else { goto inline_char_handler; } } #line 1184 "Zend/zend_language_scanner.c" yy7: YYDEBUG(7, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '=') goto yy43; YYDEBUG(8, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1748 "Zend/zend_language_scanner.l" { if (CG(asp_tags)) { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG; } else { goto inline_char_handler; } } #line 1203 "Zend/zend_language_scanner.c" yy9: YYDEBUG(9, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy11; if (yych == 'c') goto yy11; yy10: YYDEBUG(10, *YYCURSOR); YYCURSOR = YYMARKER; if (yyaccept <= 0) { goto yy3; } else { goto yy6; } yy11: YYDEBUG(11, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy12; if (yych != 'r') goto yy10; yy12: YYDEBUG(12, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy13; if (yych != 'i') goto yy10; yy13: YYDEBUG(13, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy14; if (yych != 'p') goto yy10; yy14: YYDEBUG(14, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy15; if (yych != 't') goto yy10; yy15: YYDEBUG(15, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy10; if (yych == 'l') goto yy10; goto yy17; yy16: YYDEBUG(16, *YYCURSOR); ++YYCURSOR; YYFILL(8); yych = *YYCURSOR; yy17: YYDEBUG(17, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy16; } if (yych == 'L') goto yy18; if (yych != 'l') goto yy10; yy18: YYDEBUG(18, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy19; if (yych != 'a') goto yy10; yy19: YYDEBUG(19, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy20; if (yych != 'n') goto yy10; yy20: YYDEBUG(20, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy21; if (yych != 'g') goto yy10; yy21: YYDEBUG(21, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy22; if (yych != 'u') goto yy10; yy22: YYDEBUG(22, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy23; if (yych != 'a') goto yy10; yy23: YYDEBUG(23, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy24; if (yych != 'g') goto yy10; yy24: YYDEBUG(24, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy25; if (yych != 'e') goto yy10; yy25: YYDEBUG(25, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(26, *YYCURSOR); if (yych <= '\r') { if (yych <= 0x08) goto yy10; if (yych <= '\n') goto yy25; if (yych <= '\f') goto yy10; goto yy25; } else { if (yych <= ' ') { if (yych <= 0x1F) goto yy10; goto yy25; } else { if (yych != '=') goto yy10; } } yy27: YYDEBUG(27, *YYCURSOR); ++YYCURSOR; YYFILL(5); yych = *YYCURSOR; YYDEBUG(28, *YYCURSOR); if (yych <= '!') { if (yych <= '\f') { if (yych <= 0x08) goto yy10; if (yych <= '\n') goto yy27; goto yy10; } else { if (yych <= '\r') goto yy27; if (yych == ' ') goto yy27; goto yy10; } } else { if (yych <= 'O') { if (yych <= '"') goto yy30; if (yych == '\'') goto yy31; goto yy10; } else { if (yych <= 'P') goto yy29; if (yych != 'p') goto yy10; } } yy29: YYDEBUG(29, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy42; if (yych == 'h') goto yy42; goto yy10; yy30: YYDEBUG(30, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy39; if (yych == 'p') goto yy39; goto yy10; yy31: YYDEBUG(31, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy32; if (yych != 'p') goto yy10; yy32: YYDEBUG(32, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy33; if (yych != 'h') goto yy10; yy33: YYDEBUG(33, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy34; if (yych != 'p') goto yy10; yy34: YYDEBUG(34, *YYCURSOR); yych = *++YYCURSOR; if (yych != '\'') goto yy10; yy35: YYDEBUG(35, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(36, *YYCURSOR); if (yych <= '\r') { if (yych <= 0x08) goto yy10; if (yych <= '\n') goto yy35; if (yych <= '\f') goto yy10; goto yy35; } else { if (yych <= ' ') { if (yych <= 0x1F) goto yy10; goto yy35; } else { if (yych != '>') goto yy10; } } YYDEBUG(37, *YYCURSOR); ++YYCURSOR; YYDEBUG(38, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1708 "Zend/zend_language_scanner.l" { YYCTYPE *bracket = (YYCTYPE*)zend_memrchr(yytext, '<', yyleng - (sizeof("script language=php>") - 1)); if (bracket != SCNG(yy_text)) { /* Handle previously scanned HTML, as possible <script> tags found are assumed to not be PHP's */ YYCURSOR = bracket; goto inline_html; } HANDLE_NEWLINES(yytext, yyleng); zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG; } #line 1406 "Zend/zend_language_scanner.c" yy39: YYDEBUG(39, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy40; if (yych != 'h') goto yy10; yy40: YYDEBUG(40, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy41; if (yych != 'p') goto yy10; yy41: YYDEBUG(41, *YYCURSOR); yych = *++YYCURSOR; if (yych == '"') goto yy35; goto yy10; yy42: YYDEBUG(42, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy35; if (yych == 'p') goto yy35; goto yy10; yy43: YYDEBUG(43, *YYCURSOR); ++YYCURSOR; YYDEBUG(44, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1726 "Zend/zend_language_scanner.l" { if (CG(asp_tags)) { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG_WITH_ECHO; } else { goto inline_char_handler; } } #line 1445 "Zend/zend_language_scanner.c" yy45: YYDEBUG(45, *YYCURSOR); ++YYCURSOR; YYDEBUG(46, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1739 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG_WITH_ECHO; } #line 1459 "Zend/zend_language_scanner.c" yy47: YYDEBUG(47, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy48; if (yych != 'h') goto yy10; yy48: YYDEBUG(48, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy49; if (yych != 'p') goto yy10; yy49: YYDEBUG(49, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '\f') { if (yych <= 0x08) goto yy10; if (yych >= '\v') goto yy10; } else { if (yych <= '\r') goto yy52; if (yych != ' ') goto yy10; } yy50: YYDEBUG(50, *YYCURSOR); ++YYCURSOR; yy51: YYDEBUG(51, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1761 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; HANDLE_NEWLINE(yytext[yyleng-1]); BEGIN(ST_IN_SCRIPTING); return T_OPEN_TAG; } #line 1495 "Zend/zend_language_scanner.c" yy52: YYDEBUG(52, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '\n') goto yy50; goto yy51; } /* *********************************** */ yyc_ST_BACKQUOTE: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; YYDEBUG(53, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych <= '_') { if (yych != '$') goto yy60; } else { if (yych <= '`') goto yy58; if (yych == '{') goto yy57; goto yy60; } YYDEBUG(55, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '_') { if (yych <= '@') goto yy56; if (yych <= 'Z') goto yy63; if (yych >= '_') goto yy63; } else { if (yych <= 'z') { if (yych >= 'a') goto yy63; } else { if (yych <= '{') goto yy66; if (yych >= 0x7F) goto yy63; } } yy56: YYDEBUG(56, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2234 "Zend/zend_language_scanner.l" { if (YYCURSOR > YYLIMIT) { return 0; } if (yytext[0] == '\\' && YYCURSOR < YYLIMIT) { YYCURSOR++; } while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '`': break; case '$': if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { break; } continue; case '{': if (*YYCURSOR == '$') { break; } continue; case '\\': if (YYCURSOR < YYLIMIT) { YYCURSOR++; } /* fall through */ default: continue; } YYCURSOR--; break; } yyleng = YYCURSOR - SCNG(yy_text); zend_scan_escape_string(zendlval, yytext, yyleng, '`' TSRMLS_CC); return T_ENCAPSED_AND_WHITESPACE; } #line 1607 "Zend/zend_language_scanner.c" yy57: YYDEBUG(57, *YYCURSOR); yych = *++YYCURSOR; if (yych == '$') goto yy61; goto yy56; yy58: YYDEBUG(58, *YYCURSOR); ++YYCURSOR; YYDEBUG(59, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2178 "Zend/zend_language_scanner.l" { BEGIN(ST_IN_SCRIPTING); return '`'; } #line 1623 "Zend/zend_language_scanner.c" yy60: YYDEBUG(60, *YYCURSOR); yych = *++YYCURSOR; goto yy56; yy61: YYDEBUG(61, *YYCURSOR); ++YYCURSOR; YYDEBUG(62, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2165 "Zend/zend_language_scanner.l" { zendlval->value.lval = (long) '{'; yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); yyless(1); return T_CURLY_OPEN; } #line 1640 "Zend/zend_language_scanner.c" yy63: YYDEBUG(63, *YYCURSOR); yyaccept = 0; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(64, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy63; } if (yych == '-') goto yy68; if (yych == '[') goto yy70; yy65: YYDEBUG(65, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1865 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1662 "Zend/zend_language_scanner.c" yy66: YYDEBUG(66, *YYCURSOR); ++YYCURSOR; YYDEBUG(67, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1442 "Zend/zend_language_scanner.l" { yy_push_state(ST_LOOKING_FOR_VARNAME TSRMLS_CC); return T_DOLLAR_OPEN_CURLY_BRACES; } #line 1673 "Zend/zend_language_scanner.c" yy68: YYDEBUG(68, *YYCURSOR); yych = *++YYCURSOR; if (yych == '>') goto yy72; yy69: YYDEBUG(69, *YYCURSOR); YYCURSOR = YYMARKER; goto yy65; yy70: YYDEBUG(70, *YYCURSOR); ++YYCURSOR; YYDEBUG(71, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1857 "Zend/zend_language_scanner.l" { yyless(yyleng - 1); yy_push_state(ST_VAR_OFFSET TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1695 "Zend/zend_language_scanner.c" yy72: YYDEBUG(72, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy69; if (yych <= 'Z') goto yy73; if (yych <= '^') goto yy69; } else { if (yych <= '`') goto yy69; if (yych <= 'z') goto yy73; if (yych <= '~') goto yy69; } yy73: YYDEBUG(73, *YYCURSOR); ++YYCURSOR; YYDEBUG(74, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1847 "Zend/zend_language_scanner.l" { yyless(yyleng - 3); yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1721 "Zend/zend_language_scanner.c" } /* *********************************** */ yyc_ST_DOUBLE_QUOTES: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; YYDEBUG(75, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych <= '#') { if (yych == '"') goto yy80; goto yy82; } else { if (yych <= '$') goto yy77; if (yych == '{') goto yy79; goto yy82; } yy77: YYDEBUG(77, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '_') { if (yych <= '@') goto yy78; if (yych <= 'Z') goto yy85; if (yych >= '_') goto yy85; } else { if (yych <= 'z') { if (yych >= 'a') goto yy85; } else { if (yych <= '{') goto yy88; if (yych >= 0x7F) goto yy85; } } yy78: YYDEBUG(78, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2184 "Zend/zend_language_scanner.l" { if (GET_DOUBLE_QUOTES_SCANNED_LENGTH()) { YYCURSOR += GET_DOUBLE_QUOTES_SCANNED_LENGTH() - 1; SET_DOUBLE_QUOTES_SCANNED_LENGTH(0); goto double_quotes_scan_done; } if (YYCURSOR > YYLIMIT) { return 0; } if (yytext[0] == '\\' && YYCURSOR < YYLIMIT) { YYCURSOR++; } while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '"': break; case '$': if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { break; } continue; case '{': if (*YYCURSOR == '$') { break; } continue; case '\\': if (YYCURSOR < YYLIMIT) { YYCURSOR++; } /* fall through */ default: continue; } YYCURSOR--; break; } double_quotes_scan_done: yyleng = YYCURSOR - SCNG(yy_text); zend_scan_escape_string(zendlval, yytext, yyleng, '"' TSRMLS_CC); return T_ENCAPSED_AND_WHITESPACE; } #line 1838 "Zend/zend_language_scanner.c" yy79: YYDEBUG(79, *YYCURSOR); yych = *++YYCURSOR; if (yych == '$') goto yy83; goto yy78; yy80: YYDEBUG(80, *YYCURSOR); ++YYCURSOR; YYDEBUG(81, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2173 "Zend/zend_language_scanner.l" { BEGIN(ST_IN_SCRIPTING); return '"'; } #line 1854 "Zend/zend_language_scanner.c" yy82: YYDEBUG(82, *YYCURSOR); yych = *++YYCURSOR; goto yy78; yy83: YYDEBUG(83, *YYCURSOR); ++YYCURSOR; YYDEBUG(84, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2165 "Zend/zend_language_scanner.l" { zendlval->value.lval = (long) '{'; yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); yyless(1); return T_CURLY_OPEN; } #line 1871 "Zend/zend_language_scanner.c" yy85: YYDEBUG(85, *YYCURSOR); yyaccept = 0; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(86, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy85; } if (yych == '-') goto yy90; if (yych == '[') goto yy92; yy87: YYDEBUG(87, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1865 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1893 "Zend/zend_language_scanner.c" yy88: YYDEBUG(88, *YYCURSOR); ++YYCURSOR; YYDEBUG(89, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1442 "Zend/zend_language_scanner.l" { yy_push_state(ST_LOOKING_FOR_VARNAME TSRMLS_CC); return T_DOLLAR_OPEN_CURLY_BRACES; } #line 1904 "Zend/zend_language_scanner.c" yy90: YYDEBUG(90, *YYCURSOR); yych = *++YYCURSOR; if (yych == '>') goto yy94; yy91: YYDEBUG(91, *YYCURSOR); YYCURSOR = YYMARKER; goto yy87; yy92: YYDEBUG(92, *YYCURSOR); ++YYCURSOR; YYDEBUG(93, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1857 "Zend/zend_language_scanner.l" { yyless(yyleng - 1); yy_push_state(ST_VAR_OFFSET TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1926 "Zend/zend_language_scanner.c" yy94: YYDEBUG(94, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy91; if (yych <= 'Z') goto yy95; if (yych <= '^') goto yy91; } else { if (yych <= '`') goto yy91; if (yych <= 'z') goto yy95; if (yych <= '~') goto yy91; } yy95: YYDEBUG(95, *YYCURSOR); ++YYCURSOR; YYDEBUG(96, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1847 "Zend/zend_language_scanner.l" { yyless(yyleng - 3); yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 1952 "Zend/zend_language_scanner.c" } /* *********************************** */ yyc_ST_END_HEREDOC: YYDEBUG(97, *YYCURSOR); YYFILL(1); yych = *YYCURSOR; YYDEBUG(99, *YYCURSOR); ++YYCURSOR; YYDEBUG(100, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2152 "Zend/zend_language_scanner.l" { YYCURSOR += CG(heredoc_len) - 1; yyleng = CG(heredoc_len); Z_STRVAL_P(zendlval) = CG(heredoc); Z_STRLEN_P(zendlval) = CG(heredoc_len); CG(heredoc) = NULL; CG(heredoc_len) = 0; BEGIN(ST_IN_SCRIPTING); return T_END_HEREDOC; } #line 1975 "Zend/zend_language_scanner.c" /* *********************************** */ yyc_ST_HEREDOC: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; YYDEBUG(101, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych == '$') goto yy103; if (yych == '{') goto yy105; goto yy106; yy103: YYDEBUG(103, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '_') { if (yych <= '@') goto yy104; if (yych <= 'Z') goto yy109; if (yych >= '_') goto yy109; } else { if (yych <= 'z') { if (yych >= 'a') goto yy109; } else { if (yych <= '{') goto yy112; if (yych >= 0x7F) goto yy109; } } yy104: YYDEBUG(104, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2276 "Zend/zend_language_scanner.l" { int newline = 0; if (YYCURSOR > YYLIMIT) { return 0; } YYCURSOR--; while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '\r': if (*YYCURSOR == '\n') { YYCURSOR++; } /* fall through */ case '\n': /* Check for ending label on the next line */ if (IS_LABEL_START(*YYCURSOR) && CG(heredoc_len) < YYLIMIT - YYCURSOR && !memcmp(YYCURSOR, CG(heredoc), CG(heredoc_len))) { YYCTYPE *end = YYCURSOR + CG(heredoc_len); if (*end == ';') { end++; } if (*end == '\n' || *end == '\r') { /* newline before label will be subtracted from returned text, but * yyleng/yytext will include it, for zend_highlight/strip, tokenizer, etc. */ if (YYCURSOR[-2] == '\r' && YYCURSOR[-1] == '\n') { newline = 2; /* Windows newline */ } else { newline = 1; } CG(increment_lineno) = 1; /* For newline before label */ BEGIN(ST_END_HEREDOC); goto heredoc_scan_done; } } continue; case '$': if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { break; } continue; case '{': if (*YYCURSOR == '$') { break; } continue; case '\\': if (YYCURSOR < YYLIMIT && *YYCURSOR != '\n' && *YYCURSOR != '\r') { YYCURSOR++; } /* fall through */ default: continue; } YYCURSOR--; break; } heredoc_scan_done: yyleng = YYCURSOR - SCNG(yy_text); zend_scan_escape_string(zendlval, yytext, yyleng - newline, 0 TSRMLS_CC); return T_ENCAPSED_AND_WHITESPACE; } #line 2108 "Zend/zend_language_scanner.c" yy105: YYDEBUG(105, *YYCURSOR); yych = *++YYCURSOR; if (yych == '$') goto yy107; goto yy104; yy106: YYDEBUG(106, *YYCURSOR); yych = *++YYCURSOR; goto yy104; yy107: YYDEBUG(107, *YYCURSOR); ++YYCURSOR; YYDEBUG(108, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2165 "Zend/zend_language_scanner.l" { zendlval->value.lval = (long) '{'; yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); yyless(1); return T_CURLY_OPEN; } #line 2130 "Zend/zend_language_scanner.c" yy109: YYDEBUG(109, *YYCURSOR); yyaccept = 0; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(110, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy109; } if (yych == '-') goto yy114; if (yych == '[') goto yy116; yy111: YYDEBUG(111, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1865 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 2152 "Zend/zend_language_scanner.c" yy112: YYDEBUG(112, *YYCURSOR); ++YYCURSOR; YYDEBUG(113, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1442 "Zend/zend_language_scanner.l" { yy_push_state(ST_LOOKING_FOR_VARNAME TSRMLS_CC); return T_DOLLAR_OPEN_CURLY_BRACES; } #line 2163 "Zend/zend_language_scanner.c" yy114: YYDEBUG(114, *YYCURSOR); yych = *++YYCURSOR; if (yych == '>') goto yy118; yy115: YYDEBUG(115, *YYCURSOR); YYCURSOR = YYMARKER; goto yy111; yy116: YYDEBUG(116, *YYCURSOR); ++YYCURSOR; YYDEBUG(117, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1857 "Zend/zend_language_scanner.l" { yyless(yyleng - 1); yy_push_state(ST_VAR_OFFSET TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 2185 "Zend/zend_language_scanner.c" yy118: YYDEBUG(118, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy115; if (yych <= 'Z') goto yy119; if (yych <= '^') goto yy115; } else { if (yych <= '`') goto yy115; if (yych <= 'z') goto yy119; if (yych <= '~') goto yy115; } yy119: YYDEBUG(119, *YYCURSOR); ++YYCURSOR; YYDEBUG(120, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1847 "Zend/zend_language_scanner.l" { yyless(yyleng - 3); yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC); zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 2211 "Zend/zend_language_scanner.c" } /* *********************************** */ yyc_ST_IN_SCRIPTING: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 64, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 60, 60, 44, 44, 44, 44, 44, 44, 44, 44, 0, 0, 0, 0, 0, 0, 0, 36, 36, 36, 36, 36, 36, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 4, 0, 36, 36, 36, 36, 36, 36, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, }; YYDEBUG(121, *YYCURSOR); YYFILL(16); yych = *YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case '\v': case '\f': case 0x0E: case 0x0F: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1A: case 0x1B: case 0x1C: case 0x1D: case 0x1E: case 0x1F: goto yy183; case '\t': case '\n': case '\r': case ' ': goto yy139; case '!': goto yy152; case '"': goto yy179; case '#': goto yy175; case '$': goto yy164; case '%': goto yy158; case '&': goto yy159; case '\'': goto yy177; case '(': goto yy146; case ')': case ',': case ';': case '@': case '[': case ']': case '~': goto yy165; case '*': goto yy155; case '+': goto yy151; case '-': goto yy137; case '.': goto yy157; case '/': goto yy156; case '0': goto yy171; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy173; case ':': goto yy141; case '<': goto yy153; case '=': goto yy149; case '>': goto yy154; case '?': goto yy166; case 'A': case 'a': goto yy132; case 'B': case 'b': goto yy134; case 'C': case 'c': goto yy127; case 'D': case 'd': goto yy125; case 'E': case 'e': goto yy123; case 'F': case 'f': goto yy126; case 'G': case 'g': goto yy135; case 'I': case 'i': goto yy130; case 'L': case 'l': goto yy150; case 'N': case 'n': goto yy144; case 'O': case 'o': goto yy162; case 'P': case 'p': goto yy136; case 'R': case 'r': goto yy128; case 'S': case 's': goto yy133; case 'T': case 't': goto yy129; case 'U': case 'u': goto yy147; case 'V': case 'v': goto yy145; case 'W': case 'w': goto yy131; case 'X': case 'x': goto yy163; case '\\': goto yy142; case '^': goto yy161; case '_': goto yy148; case '`': goto yy181; case '{': goto yy167; case '|': goto yy160; case '}': goto yy169; default: goto yy174; } yy123: YYDEBUG(123, *YYCURSOR); ++YYCURSOR; YYDEBUG(-1, yych); switch ((yych = *YYCURSOR)) { case 'C': case 'c': goto yy726; case 'L': case 'l': goto yy727; case 'M': case 'm': goto yy728; case 'N': case 'n': goto yy729; case 'V': case 'v': goto yy730; case 'X': case 'x': goto yy731; default: goto yy186; } yy124: YYDEBUG(124, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1888 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, yytext, yyleng); zendlval->type = IS_STRING; return T_STRING; } #line 2398 "Zend/zend_language_scanner.c" yy125: YYDEBUG(125, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= 'H') { if (yych == 'E') goto yy708; goto yy186; } else { if (yych <= 'I') goto yy709; if (yych <= 'N') goto yy186; goto yy710; } } else { if (yych <= 'h') { if (yych == 'e') goto yy708; goto yy186; } else { if (yych <= 'i') goto yy709; if (yych == 'o') goto yy710; goto yy186; } } yy126: YYDEBUG(126, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych <= 'N') { if (yych == 'I') goto yy687; goto yy186; } else { if (yych <= 'O') goto yy688; if (yych <= 'T') goto yy186; goto yy689; } } else { if (yych <= 'n') { if (yych == 'i') goto yy687; goto yy186; } else { if (yych <= 'o') goto yy688; if (yych == 'u') goto yy689; goto yy186; } } yy127: YYDEBUG(127, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych <= 'K') { if (yych == 'A') goto yy652; goto yy186; } else { if (yych <= 'L') goto yy653; if (yych <= 'N') goto yy186; goto yy654; } } else { if (yych <= 'k') { if (yych == 'a') goto yy652; goto yy186; } else { if (yych <= 'l') goto yy653; if (yych == 'o') goto yy654; goto yy186; } } yy128: YYDEBUG(128, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy634; if (yych == 'e') goto yy634; goto yy186; yy129: YYDEBUG(129, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'R') { if (yych == 'H') goto yy622; if (yych <= 'Q') goto yy186; goto yy623; } else { if (yych <= 'h') { if (yych <= 'g') goto yy186; goto yy622; } else { if (yych == 'r') goto yy623; goto yy186; } } yy130: YYDEBUG(130, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= 'L') { if (yych == 'F') goto yy569; goto yy186; } else { if (yych <= 'M') goto yy571; if (yych <= 'N') goto yy572; if (yych <= 'R') goto yy186; goto yy573; } } else { if (yych <= 'm') { if (yych == 'f') goto yy569; if (yych <= 'l') goto yy186; goto yy571; } else { if (yych <= 'n') goto yy572; if (yych == 's') goto yy573; goto yy186; } } yy131: YYDEBUG(131, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy564; if (yych == 'h') goto yy564; goto yy186; yy132: YYDEBUG(132, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych <= 'M') { if (yych == 'B') goto yy546; goto yy186; } else { if (yych <= 'N') goto yy547; if (yych <= 'Q') goto yy186; if (yych <= 'R') goto yy548; goto yy549; } } else { if (yych <= 'n') { if (yych == 'b') goto yy546; if (yych <= 'm') goto yy186; goto yy547; } else { if (yych <= 'q') goto yy186; if (yych <= 'r') goto yy548; if (yych <= 's') goto yy549; goto yy186; } } yy133: YYDEBUG(133, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'W') { if (yych == 'T') goto yy534; if (yych <= 'V') goto yy186; goto yy535; } else { if (yych <= 't') { if (yych <= 's') goto yy186; goto yy534; } else { if (yych == 'w') goto yy535; goto yy186; } } yy134: YYDEBUG(134, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ';') { if (yych <= '"') { if (yych <= '!') goto yy186; goto yy526; } else { if (yych == '\'') goto yy527; goto yy186; } } else { if (yych <= 'R') { if (yych <= '<') goto yy525; if (yych <= 'Q') goto yy186; goto yy528; } else { if (yych == 'r') goto yy528; goto yy186; } } yy135: YYDEBUG(135, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'L') goto yy515; if (yych <= 'N') goto yy186; goto yy516; } else { if (yych <= 'l') { if (yych <= 'k') goto yy186; goto yy515; } else { if (yych == 'o') goto yy516; goto yy186; } } yy136: YYDEBUG(136, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'R') goto yy491; if (yych <= 'T') goto yy186; goto yy492; } else { if (yych <= 'r') { if (yych <= 'q') goto yy186; goto yy491; } else { if (yych == 'u') goto yy492; goto yy186; } } yy137: YYDEBUG(137, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '<') { if (yych == '-') goto yy487; } else { if (yych <= '=') goto yy485; if (yych <= '>') goto yy489; } yy138: YYDEBUG(138, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1431 "Zend/zend_language_scanner.l" { return yytext[0]; } #line 2628 "Zend/zend_language_scanner.c" yy139: YYDEBUG(139, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy484; yy140: YYDEBUG(140, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1162 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; HANDLE_NEWLINES(yytext, yyleng); return T_WHITESPACE; } #line 2645 "Zend/zend_language_scanner.c" yy141: YYDEBUG(141, *YYCURSOR); yych = *++YYCURSOR; if (yych == ':') goto yy481; goto yy138; yy142: YYDEBUG(142, *YYCURSOR); ++YYCURSOR; YYDEBUG(143, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1191 "Zend/zend_language_scanner.l" { return T_NS_SEPARATOR; } #line 2660 "Zend/zend_language_scanner.c" yy144: YYDEBUG(144, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych == 'A') goto yy469; if (yych <= 'D') goto yy186; goto yy470; } else { if (yych <= 'a') { if (yych <= '`') goto yy186; goto yy469; } else { if (yych == 'e') goto yy470; goto yy186; } } yy145: YYDEBUG(145, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy466; if (yych == 'a') goto yy466; goto yy186; yy146: YYDEBUG(146, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'S') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy391; if (yych <= 0x1F) goto yy138; goto yy391; } else { if (yych <= '@') goto yy138; if (yych == 'C') goto yy138; goto yy391; } } else { if (yych <= 'I') { if (yych == 'F') goto yy391; if (yych <= 'H') goto yy138; goto yy391; } else { if (yych == 'O') goto yy391; if (yych <= 'Q') goto yy138; goto yy391; } } } else { if (yych <= 'f') { if (yych <= 'b') { if (yych == 'U') goto yy391; if (yych <= '`') goto yy138; goto yy391; } else { if (yych == 'd') goto yy391; if (yych <= 'e') goto yy138; goto yy391; } } else { if (yych <= 'o') { if (yych == 'i') goto yy391; if (yych <= 'n') goto yy138; goto yy391; } else { if (yych <= 's') { if (yych <= 'q') goto yy138; goto yy391; } else { if (yych == 'u') goto yy391; goto yy138; } } } } yy147: YYDEBUG(147, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'S') { if (yych == 'N') goto yy382; if (yych <= 'R') goto yy186; goto yy383; } else { if (yych <= 'n') { if (yych <= 'm') goto yy186; goto yy382; } else { if (yych == 's') goto yy383; goto yy186; } } yy148: YYDEBUG(148, *YYCURSOR); yych = *++YYCURSOR; if (yych == '_') goto yy300; goto yy186; yy149: YYDEBUG(149, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '<') goto yy138; if (yych <= '=') goto yy294; if (yych <= '>') goto yy296; goto yy138; yy150: YYDEBUG(150, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy290; if (yych == 'i') goto yy290; goto yy186; yy151: YYDEBUG(151, *YYCURSOR); yych = *++YYCURSOR; if (yych == '+') goto yy288; if (yych == '=') goto yy286; goto yy138; yy152: YYDEBUG(152, *YYCURSOR); yych = *++YYCURSOR; if (yych == '=') goto yy283; goto yy138; yy153: YYDEBUG(153, *YYCURSOR); yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ';') { if (yych == '/') goto yy255; goto yy138; } else { if (yych <= '<') goto yy253; if (yych <= '=') goto yy256; if (yych <= '>') goto yy258; goto yy138; } yy154: YYDEBUG(154, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '<') goto yy138; if (yych <= '=') goto yy249; if (yych <= '>') goto yy247; goto yy138; yy155: YYDEBUG(155, *YYCURSOR); yych = *++YYCURSOR; if (yych == '=') goto yy245; goto yy138; yy156: YYDEBUG(156, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '.') { if (yych == '*') goto yy237; goto yy138; } else { if (yych <= '/') goto yy239; if (yych == '=') goto yy240; goto yy138; } yy157: YYDEBUG(157, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy138; if (yych <= '9') goto yy233; if (yych == '=') goto yy235; goto yy138; yy158: YYDEBUG(158, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '<') goto yy138; if (yych <= '=') goto yy229; if (yych <= '>') goto yy227; goto yy138; yy159: YYDEBUG(159, *YYCURSOR); yych = *++YYCURSOR; if (yych == '&') goto yy223; if (yych == '=') goto yy225; goto yy138; yy160: YYDEBUG(160, *YYCURSOR); yych = *++YYCURSOR; if (yych == '=') goto yy221; if (yych == '|') goto yy219; goto yy138; yy161: YYDEBUG(161, *YYCURSOR); yych = *++YYCURSOR; if (yych == '=') goto yy217; goto yy138; yy162: YYDEBUG(162, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy215; if (yych == 'r') goto yy215; goto yy186; yy163: YYDEBUG(163, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy212; if (yych == 'o') goto yy212; goto yy186; yy164: YYDEBUG(164, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy138; if (yych <= 'Z') goto yy209; if (yych <= '^') goto yy138; goto yy209; } else { if (yych <= '`') goto yy138; if (yych <= 'z') goto yy209; if (yych <= '~') goto yy138; goto yy209; } yy165: YYDEBUG(165, *YYCURSOR); yych = *++YYCURSOR; goto yy138; yy166: YYDEBUG(166, *YYCURSOR); yych = *++YYCURSOR; if (yych == '>') goto yy205; goto yy138; yy167: YYDEBUG(167, *YYCURSOR); ++YYCURSOR; YYDEBUG(168, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1436 "Zend/zend_language_scanner.l" { yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); return '{'; } #line 2893 "Zend/zend_language_scanner.c" yy169: YYDEBUG(169, *YYCURSOR); ++YYCURSOR; YYDEBUG(170, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1448 "Zend/zend_language_scanner.l" { RESET_DOC_COMMENT(); if (!zend_stack_is_empty(&SCNG(state_stack))) { yy_pop_state(TSRMLS_C); } return '}'; } #line 2907 "Zend/zend_language_scanner.c" yy171: YYDEBUG(171, *YYCURSOR); yyaccept = 2; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'E') { if (yych <= '9') { if (yych == '.') goto yy187; if (yych >= '0') goto yy190; } else { if (yych == 'B') goto yy198; if (yych >= 'E') goto yy192; } } else { if (yych <= 'b') { if (yych == 'X') goto yy197; if (yych >= 'b') goto yy198; } else { if (yych <= 'e') { if (yych >= 'e') goto yy192; } else { if (yych == 'x') goto yy197; } } } yy172: YYDEBUG(172, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1498 "Zend/zend_language_scanner.l" { if (yyleng < MAX_LENGTH_OF_LONG - 1) { /* Won't overflow */ zendlval->value.lval = strtol(yytext, NULL, 0); } else { errno = 0; zendlval->value.lval = strtol(yytext, NULL, 0); if (errno == ERANGE) { /* Overflow */ if (yytext[0] == '0') { /* octal overflow */ zendlval->value.dval = zend_oct_strtod(yytext, NULL); } else { zendlval->value.dval = zend_strtod(yytext, NULL); } zendlval->type = IS_DOUBLE; return T_DNUMBER; } } zendlval->type = IS_LONG; return T_LNUMBER; } #line 2956 "Zend/zend_language_scanner.c" yy173: YYDEBUG(173, *YYCURSOR); yyaccept = 2; yych = *(YYMARKER = ++YYCURSOR); if (yych <= '9') { if (yych == '.') goto yy187; if (yych <= '/') goto yy172; goto yy190; } else { if (yych <= 'E') { if (yych <= 'D') goto yy172; goto yy192; } else { if (yych == 'e') goto yy192; goto yy172; } } yy174: YYDEBUG(174, *YYCURSOR); yych = *++YYCURSOR; goto yy186; yy175: YYDEBUG(175, *YYCURSOR); ++YYCURSOR; yy176: YYDEBUG(176, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1895 "Zend/zend_language_scanner.l" { while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '\r': if (*YYCURSOR == '\n') { YYCURSOR++; } /* fall through */ case '\n': CG(zend_lineno)++; break; case '%': if (!CG(asp_tags)) { continue; } /* fall through */ case '?': if (*YYCURSOR == '>') { YYCURSOR--; break; } /* fall through */ default: continue; } break; } yyleng = YYCURSOR - SCNG(yy_text); return T_COMMENT; } #line 3018 "Zend/zend_language_scanner.c" yy177: YYDEBUG(177, *YYCURSOR); ++YYCURSOR; yy178: YYDEBUG(178, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1986 "Zend/zend_language_scanner.l" { register char *s, *t; char *end; int bprefix = (yytext[0] != '\'') ? 1 : 0; while (1) { if (YYCURSOR < YYLIMIT) { if (*YYCURSOR == '\'') { YYCURSOR++; yyleng = YYCURSOR - SCNG(yy_text); break; } else if (*YYCURSOR++ == '\\' && YYCURSOR < YYLIMIT) { YYCURSOR++; } } else { yyleng = YYLIMIT - SCNG(yy_text); /* Unclosed single quotes; treat similar to double quotes, but without a separate token * for ' (unrecognized by parser), instead of old flex fallback to "Unexpected character..." * rule, which continued in ST_IN_SCRIPTING state after the quote */ return T_ENCAPSED_AND_WHITESPACE; } } zendlval->value.str.val = estrndup(yytext+bprefix+1, yyleng-bprefix-2); zendlval->value.str.len = yyleng-bprefix-2; zendlval->type = IS_STRING; /* convert escape sequences */ s = t = zendlval->value.str.val; end = s+zendlval->value.str.len; while (s<end) { if (*s=='\\') { s++; switch(*s) { case '\\': case '\'': *t++ = *s; zendlval->value.str.len--; break; default: *t++ = '\\'; *t++ = *s; break; } } else { *t++ = *s; } if (*s == '\n' || (*s == '\r' && (*(s+1) != '\n'))) { CG(zend_lineno)++; } s++; } *t = 0; if (SCNG(output_filter)) { size_t sz = 0; s = zendlval->value.str.val; SCNG(output_filter)((unsigned char **)&(zendlval->value.str.val), &sz, (unsigned char *)s, (size_t)zendlval->value.str.len TSRMLS_CC); zendlval->value.str.len = sz; efree(s); } return T_CONSTANT_ENCAPSED_STRING; } #line 3093 "Zend/zend_language_scanner.c" yy179: YYDEBUG(179, *YYCURSOR); ++YYCURSOR; yy180: YYDEBUG(180, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2055 "Zend/zend_language_scanner.l" { int bprefix = (yytext[0] != '"') ? 1 : 0; while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '"': yyleng = YYCURSOR - SCNG(yy_text); zend_scan_escape_string(zendlval, yytext+bprefix+1, yyleng-bprefix-2, '"' TSRMLS_CC); return T_CONSTANT_ENCAPSED_STRING; case '$': if (IS_LABEL_START(*YYCURSOR) || *YYCURSOR == '{') { break; } continue; case '{': if (*YYCURSOR == '$') { break; } continue; case '\\': if (YYCURSOR < YYLIMIT) { YYCURSOR++; } /* fall through */ default: continue; } YYCURSOR--; break; } /* Remember how much was scanned to save rescanning */ SET_DOUBLE_QUOTES_SCANNED_LENGTH(YYCURSOR - SCNG(yy_text) - yyleng); YYCURSOR = SCNG(yy_text) + yyleng; BEGIN(ST_DOUBLE_QUOTES); return '"'; } #line 3141 "Zend/zend_language_scanner.c" yy181: YYDEBUG(181, *YYCURSOR); ++YYCURSOR; YYDEBUG(182, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2146 "Zend/zend_language_scanner.l" { BEGIN(ST_BACKQUOTE); return '`'; } #line 3152 "Zend/zend_language_scanner.c" yy183: YYDEBUG(183, *YYCURSOR); ++YYCURSOR; YYDEBUG(184, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2404 "Zend/zend_language_scanner.l" { if (YYCURSOR > YYLIMIT) { return 0; } zend_error(E_COMPILE_WARNING,"Unexpected character in input: '%c' (ASCII=%d) state=%d", yytext[0], yytext[0], YYSTATE); goto restart; } #line 3167 "Zend/zend_language_scanner.c" yy185: YYDEBUG(185, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy186: YYDEBUG(186, *YYCURSOR); if (yybm[0+yych] & 4) { goto yy185; } goto yy124; yy187: YYDEBUG(187, *YYCURSOR); yyaccept = 3; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(188, *YYCURSOR); if (yybm[0+yych] & 8) { goto yy187; } if (yych == 'E') goto yy192; if (yych == 'e') goto yy192; yy189: YYDEBUG(189, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1563 "Zend/zend_language_scanner.l" { zendlval->value.dval = zend_strtod(yytext, NULL); zendlval->type = IS_DOUBLE; return T_DNUMBER; } #line 3200 "Zend/zend_language_scanner.c" yy190: YYDEBUG(190, *YYCURSOR); yyaccept = 2; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(191, *YYCURSOR); if (yych <= '9') { if (yych == '.') goto yy187; if (yych <= '/') goto yy172; goto yy190; } else { if (yych <= 'E') { if (yych <= 'D') goto yy172; } else { if (yych != 'e') goto yy172; } } yy192: YYDEBUG(192, *YYCURSOR); yych = *++YYCURSOR; if (yych <= ',') { if (yych == '+') goto yy194; } else { if (yych <= '-') goto yy194; if (yych <= '/') goto yy193; if (yych <= '9') goto yy195; } yy193: YYDEBUG(193, *YYCURSOR); YYCURSOR = YYMARKER; if (yyaccept <= 2) { if (yyaccept <= 1) { if (yyaccept <= 0) { goto yy124; } else { goto yy138; } } else { goto yy172; } } else { if (yyaccept <= 4) { if (yyaccept <= 3) { goto yy189; } else { goto yy238; } } else { goto yy254; } } yy194: YYDEBUG(194, *YYCURSOR); yych = *++YYCURSOR; if (yych <= '/') goto yy193; if (yych >= ':') goto yy193; yy195: YYDEBUG(195, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(196, *YYCURSOR); if (yych <= '/') goto yy189; if (yych <= '9') goto yy195; goto yy189; yy197: YYDEBUG(197, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 32) { goto yy202; } goto yy193; yy198: YYDEBUG(198, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 16) { goto yy199; } goto yy193; yy199: YYDEBUG(199, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(200, *YYCURSOR); if (yybm[0+yych] & 16) { goto yy199; } YYDEBUG(201, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1473 "Zend/zend_language_scanner.l" { char *bin = yytext + 2; /* Skip "0b" */ int len = yyleng - 2; /* Skip any leading 0s */ while (*bin == '0') { ++bin; --len; } if (len < SIZEOF_LONG * 8) { if (len == 0) { zendlval->value.lval = 0; } else { zendlval->value.lval = strtol(bin, NULL, 2); } zendlval->type = IS_LONG; return T_LNUMBER; } else { zendlval->value.dval = zend_bin_strtod(bin, NULL); zendlval->type = IS_DOUBLE; return T_DNUMBER; } } #line 3317 "Zend/zend_language_scanner.c" yy202: YYDEBUG(202, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(203, *YYCURSOR); if (yybm[0+yych] & 32) { goto yy202; } YYDEBUG(204, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1519 "Zend/zend_language_scanner.l" { char *hex = yytext + 2; /* Skip "0x" */ int len = yyleng - 2; /* Skip any leading 0s */ while (*hex == '0') { hex++; len--; } if (len < SIZEOF_LONG * 2 || (len == SIZEOF_LONG * 2 && *hex <= '7')) { if (len == 0) { zendlval->value.lval = 0; } else { zendlval->value.lval = strtol(hex, NULL, 16); } zendlval->type = IS_LONG; return T_LNUMBER; } else { zendlval->value.dval = zend_hex_strtod(hex, NULL); zendlval->type = IS_DOUBLE; return T_DNUMBER; } } #line 3354 "Zend/zend_language_scanner.c" yy205: YYDEBUG(205, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '\n') goto yy207; if (yych == '\r') goto yy208; yy206: YYDEBUG(206, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1963 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; BEGIN(INITIAL); return T_CLOSE_TAG; /* implicit ';' at php-end tag */ } #line 3371 "Zend/zend_language_scanner.c" yy207: YYDEBUG(207, *YYCURSOR); yych = *++YYCURSOR; goto yy206; yy208: YYDEBUG(208, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\n') goto yy207; goto yy206; yy209: YYDEBUG(209, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(210, *YYCURSOR); if (yych <= '^') { if (yych <= '9') { if (yych >= '0') goto yy209; } else { if (yych <= '@') goto yy211; if (yych <= 'Z') goto yy209; } } else { if (yych <= '`') { if (yych <= '_') goto yy209; } else { if (yych <= 'z') goto yy209; if (yych >= 0x7F) goto yy209; } } yy211: YYDEBUG(211, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1865 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 3411 "Zend/zend_language_scanner.c" yy212: YYDEBUG(212, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy213; if (yych != 'r') goto yy186; yy213: YYDEBUG(213, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(214, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1419 "Zend/zend_language_scanner.l" { return T_LOGICAL_XOR; } #line 3429 "Zend/zend_language_scanner.c" yy215: YYDEBUG(215, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(216, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1411 "Zend/zend_language_scanner.l" { return T_LOGICAL_OR; } #line 3442 "Zend/zend_language_scanner.c" yy217: YYDEBUG(217, *YYCURSOR); ++YYCURSOR; YYDEBUG(218, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1399 "Zend/zend_language_scanner.l" { return T_XOR_EQUAL; } #line 3452 "Zend/zend_language_scanner.c" yy219: YYDEBUG(219, *YYCURSOR); ++YYCURSOR; YYDEBUG(220, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1403 "Zend/zend_language_scanner.l" { return T_BOOLEAN_OR; } #line 3462 "Zend/zend_language_scanner.c" yy221: YYDEBUG(221, *YYCURSOR); ++YYCURSOR; YYDEBUG(222, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1395 "Zend/zend_language_scanner.l" { return T_OR_EQUAL; } #line 3472 "Zend/zend_language_scanner.c" yy223: YYDEBUG(223, *YYCURSOR); ++YYCURSOR; YYDEBUG(224, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1407 "Zend/zend_language_scanner.l" { return T_BOOLEAN_AND; } #line 3482 "Zend/zend_language_scanner.c" yy225: YYDEBUG(225, *YYCURSOR); ++YYCURSOR; YYDEBUG(226, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1391 "Zend/zend_language_scanner.l" { return T_AND_EQUAL; } #line 3492 "Zend/zend_language_scanner.c" yy227: YYDEBUG(227, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '\n') goto yy231; if (yych == '\r') goto yy232; yy228: YYDEBUG(228, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1972 "Zend/zend_language_scanner.l" { if (CG(asp_tags)) { BEGIN(INITIAL); zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; zendlval->value.str.val = yytext; /* no copying - intentional */ return T_CLOSE_TAG; /* implicit ';' at php-end tag */ } else { yyless(1); return yytext[0]; } } #line 3514 "Zend/zend_language_scanner.c" yy229: YYDEBUG(229, *YYCURSOR); ++YYCURSOR; YYDEBUG(230, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1379 "Zend/zend_language_scanner.l" { return T_MOD_EQUAL; } #line 3524 "Zend/zend_language_scanner.c" yy231: YYDEBUG(231, *YYCURSOR); yych = *++YYCURSOR; goto yy228; yy232: YYDEBUG(232, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\n') goto yy231; goto yy228; yy233: YYDEBUG(233, *YYCURSOR); yyaccept = 3; YYMARKER = ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(234, *YYCURSOR); if (yych <= 'D') { if (yych <= '/') goto yy189; if (yych <= '9') goto yy233; goto yy189; } else { if (yych <= 'E') goto yy192; if (yych == 'e') goto yy192; goto yy189; } yy235: YYDEBUG(235, *YYCURSOR); ++YYCURSOR; YYDEBUG(236, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1375 "Zend/zend_language_scanner.l" { return T_CONCAT_EQUAL; } #line 3559 "Zend/zend_language_scanner.c" yy237: YYDEBUG(237, *YYCURSOR); yyaccept = 4; yych = *(YYMARKER = ++YYCURSOR); if (yych == '*') goto yy242; yy238: YYDEBUG(238, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1929 "Zend/zend_language_scanner.l" { int doc_com; if (yyleng > 2) { doc_com = 1; RESET_DOC_COMMENT(); } else { doc_com = 0; } while (YYCURSOR < YYLIMIT) { if (*YYCURSOR++ == '*' && *YYCURSOR == '/') { break; } } if (YYCURSOR < YYLIMIT) { YYCURSOR++; } else { zend_error(E_COMPILE_WARNING, "Unterminated comment starting line %d", CG(zend_lineno)); } yyleng = YYCURSOR - SCNG(yy_text); HANDLE_NEWLINES(yytext, yyleng); if (doc_com) { CG(doc_comment) = estrndup(yytext, yyleng); CG(doc_comment_len) = yyleng; return T_DOC_COMMENT; } return T_COMMENT; } #line 3602 "Zend/zend_language_scanner.c" yy239: YYDEBUG(239, *YYCURSOR); yych = *++YYCURSOR; goto yy176; yy240: YYDEBUG(240, *YYCURSOR); ++YYCURSOR; YYDEBUG(241, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1371 "Zend/zend_language_scanner.l" { return T_DIV_EQUAL; } #line 3616 "Zend/zend_language_scanner.c" yy242: YYDEBUG(242, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 64) { goto yy243; } goto yy193; yy243: YYDEBUG(243, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(244, *YYCURSOR); if (yybm[0+yych] & 64) { goto yy243; } goto yy238; yy245: YYDEBUG(245, *YYCURSOR); ++YYCURSOR; YYDEBUG(246, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1367 "Zend/zend_language_scanner.l" { return T_MUL_EQUAL; } #line 3643 "Zend/zend_language_scanner.c" yy247: YYDEBUG(247, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '=') goto yy251; YYDEBUG(248, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1427 "Zend/zend_language_scanner.l" { return T_SR; } #line 3654 "Zend/zend_language_scanner.c" yy249: YYDEBUG(249, *YYCURSOR); ++YYCURSOR; YYDEBUG(250, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1355 "Zend/zend_language_scanner.l" { return T_IS_GREATER_OR_EQUAL; } #line 3664 "Zend/zend_language_scanner.c" yy251: YYDEBUG(251, *YYCURSOR); ++YYCURSOR; YYDEBUG(252, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1387 "Zend/zend_language_scanner.l" { return T_SR_EQUAL; } #line 3674 "Zend/zend_language_scanner.c" yy253: YYDEBUG(253, *YYCURSOR); yyaccept = 5; yych = *(YYMARKER = ++YYCURSOR); if (yych <= ';') goto yy254; if (yych <= '<') goto yy269; if (yych <= '=') goto yy267; yy254: YYDEBUG(254, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1423 "Zend/zend_language_scanner.l" { return T_SL; } #line 3689 "Zend/zend_language_scanner.c" yy255: YYDEBUG(255, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy260; if (yych == 's') goto yy260; goto yy193; yy256: YYDEBUG(256, *YYCURSOR); ++YYCURSOR; YYDEBUG(257, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1351 "Zend/zend_language_scanner.l" { return T_IS_SMALLER_OR_EQUAL; } #line 3705 "Zend/zend_language_scanner.c" yy258: YYDEBUG(258, *YYCURSOR); ++YYCURSOR; yy259: YYDEBUG(259, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1347 "Zend/zend_language_scanner.l" { return T_IS_NOT_EQUAL; } #line 3716 "Zend/zend_language_scanner.c" yy260: YYDEBUG(260, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy261; if (yych != 'c') goto yy193; yy261: YYDEBUG(261, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy262; if (yych != 'r') goto yy193; yy262: YYDEBUG(262, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy263; if (yych != 'i') goto yy193; yy263: YYDEBUG(263, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy264; if (yych != 'p') goto yy193; yy264: YYDEBUG(264, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy265; if (yych != 't') goto yy193; yy265: YYDEBUG(265, *YYCURSOR); ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; YYDEBUG(266, *YYCURSOR); if (yych <= '\r') { if (yych <= 0x08) goto yy193; if (yych <= '\n') goto yy265; if (yych <= '\f') goto yy193; goto yy265; } else { if (yych <= ' ') { if (yych <= 0x1F) goto yy193; goto yy265; } else { if (yych == '>') goto yy205; goto yy193; } } yy267: YYDEBUG(267, *YYCURSOR); ++YYCURSOR; YYDEBUG(268, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1383 "Zend/zend_language_scanner.l" { return T_SL_EQUAL; } #line 3771 "Zend/zend_language_scanner.c" yy269: YYDEBUG(269, *YYCURSOR); ++YYCURSOR; YYFILL(2); yych = *YYCURSOR; YYDEBUG(270, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy269; } if (yych <= 'Z') { if (yych <= '&') { if (yych == '"') goto yy274; goto yy193; } else { if (yych <= '\'') goto yy273; if (yych <= '@') goto yy193; } } else { if (yych <= '`') { if (yych != '_') goto yy193; } else { if (yych <= 'z') goto yy271; if (yych <= '~') goto yy193; } } yy271: YYDEBUG(271, *YYCURSOR); ++YYCURSOR; YYFILL(2); yych = *YYCURSOR; YYDEBUG(272, *YYCURSOR); if (yych <= '@') { if (yych <= '\f') { if (yych == '\n') goto yy278; goto yy193; } else { if (yych <= '\r') goto yy280; if (yych <= '/') goto yy193; if (yych <= '9') goto yy271; goto yy193; } } else { if (yych <= '_') { if (yych <= 'Z') goto yy271; if (yych <= '^') goto yy193; goto yy271; } else { if (yych <= '`') goto yy193; if (yych <= 'z') goto yy271; if (yych <= '~') goto yy193; goto yy271; } } yy273: YYDEBUG(273, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\'') goto yy193; if (yych <= '/') goto yy282; if (yych <= '9') goto yy193; goto yy282; yy274: YYDEBUG(274, *YYCURSOR); yych = *++YYCURSOR; if (yych == '"') goto yy193; if (yych <= '/') goto yy276; if (yych <= '9') goto yy193; goto yy276; yy275: YYDEBUG(275, *YYCURSOR); ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; yy276: YYDEBUG(276, *YYCURSOR); if (yych <= 'Z') { if (yych <= '/') { if (yych != '"') goto yy193; } else { if (yych <= '9') goto yy275; if (yych <= '@') goto yy193; goto yy275; } } else { if (yych <= '`') { if (yych == '_') goto yy275; goto yy193; } else { if (yych <= 'z') goto yy275; if (yych <= '~') goto yy193; goto yy275; } } yy277: YYDEBUG(277, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\n') goto yy278; if (yych == '\r') goto yy280; goto yy193; yy278: YYDEBUG(278, *YYCURSOR); ++YYCURSOR; yy279: YYDEBUG(279, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2097 "Zend/zend_language_scanner.l" { char *s; int bprefix = (yytext[0] != '<') ? 1 : 0; /* save old heredoc label */ Z_STRVAL_P(zendlval) = CG(heredoc); Z_STRLEN_P(zendlval) = CG(heredoc_len); CG(zend_lineno)++; CG(heredoc_len) = yyleng-bprefix-3-1-(yytext[yyleng-2]=='\r'?1:0); s = yytext+bprefix+3; while ((*s == ' ') || (*s == '\t')) { s++; CG(heredoc_len)--; } if (*s == '\'') { s++; CG(heredoc_len) -= 2; BEGIN(ST_NOWDOC); } else { if (*s == '"') { s++; CG(heredoc_len) -= 2; } BEGIN(ST_HEREDOC); } CG(heredoc) = estrndup(s, CG(heredoc_len)); /* Check for ending label on the next line */ if (CG(heredoc_len) < YYLIMIT - YYCURSOR && !memcmp(YYCURSOR, s, CG(heredoc_len))) { YYCTYPE *end = YYCURSOR + CG(heredoc_len); if (*end == ';') { end++; } if (*end == '\n' || *end == '\r') { BEGIN(ST_END_HEREDOC); } } return T_START_HEREDOC; } #line 3924 "Zend/zend_language_scanner.c" yy280: YYDEBUG(280, *YYCURSOR); yych = *++YYCURSOR; if (yych == '\n') goto yy278; goto yy279; yy281: YYDEBUG(281, *YYCURSOR); ++YYCURSOR; YYFILL(3); yych = *YYCURSOR; yy282: YYDEBUG(282, *YYCURSOR); if (yych <= 'Z') { if (yych <= '/') { if (yych == '\'') goto yy277; goto yy193; } else { if (yych <= '9') goto yy281; if (yych <= '@') goto yy193; goto yy281; } } else { if (yych <= '`') { if (yych == '_') goto yy281; goto yy193; } else { if (yych <= 'z') goto yy281; if (yych <= '~') goto yy193; goto yy281; } } yy283: YYDEBUG(283, *YYCURSOR); yych = *++YYCURSOR; if (yych != '=') goto yy259; YYDEBUG(284, *YYCURSOR); ++YYCURSOR; YYDEBUG(285, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1339 "Zend/zend_language_scanner.l" { return T_IS_NOT_IDENTICAL; } #line 3968 "Zend/zend_language_scanner.c" yy286: YYDEBUG(286, *YYCURSOR); ++YYCURSOR; YYDEBUG(287, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1359 "Zend/zend_language_scanner.l" { return T_PLUS_EQUAL; } #line 3978 "Zend/zend_language_scanner.c" yy288: YYDEBUG(288, *YYCURSOR); ++YYCURSOR; YYDEBUG(289, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1327 "Zend/zend_language_scanner.l" { return T_INC; } #line 3988 "Zend/zend_language_scanner.c" yy290: YYDEBUG(290, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy291; if (yych != 's') goto yy186; yy291: YYDEBUG(291, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy292; if (yych != 't') goto yy186; yy292: YYDEBUG(292, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(293, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1315 "Zend/zend_language_scanner.l" { return T_LIST; } #line 4011 "Zend/zend_language_scanner.c" yy294: YYDEBUG(294, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '=') goto yy298; YYDEBUG(295, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1343 "Zend/zend_language_scanner.l" { return T_IS_EQUAL; } #line 4022 "Zend/zend_language_scanner.c" yy296: YYDEBUG(296, *YYCURSOR); ++YYCURSOR; YYDEBUG(297, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1311 "Zend/zend_language_scanner.l" { return T_DOUBLE_ARROW; } #line 4032 "Zend/zend_language_scanner.c" yy298: YYDEBUG(298, *YYCURSOR); ++YYCURSOR; YYDEBUG(299, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1335 "Zend/zend_language_scanner.l" { return T_IS_IDENTICAL; } #line 4042 "Zend/zend_language_scanner.c" yy300: YYDEBUG(300, *YYCURSOR); yych = *++YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case 'C': case 'c': goto yy302; case 'D': case 'd': goto yy307; case 'F': case 'f': goto yy304; case 'H': case 'h': goto yy301; case 'L': case 'l': goto yy306; case 'M': case 'm': goto yy305; case 'N': case 'n': goto yy308; case 'T': case 't': goto yy303; default: goto yy186; } yy301: YYDEBUG(301, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy369; if (yych == 'a') goto yy369; goto yy186; yy302: YYDEBUG(302, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy362; if (yych == 'l') goto yy362; goto yy186; yy303: YYDEBUG(303, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy355; if (yych == 'r') goto yy355; goto yy186; yy304: YYDEBUG(304, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'U') { if (yych == 'I') goto yy339; if (yych <= 'T') goto yy186; goto yy340; } else { if (yych <= 'i') { if (yych <= 'h') goto yy186; goto yy339; } else { if (yych == 'u') goto yy340; goto yy186; } } yy305: YYDEBUG(305, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy331; if (yych == 'e') goto yy331; goto yy186; yy306: YYDEBUG(306, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy325; if (yych == 'i') goto yy325; goto yy186; yy307: YYDEBUG(307, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy320; if (yych == 'i') goto yy320; goto yy186; yy308: YYDEBUG(308, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy309; if (yych != 'a') goto yy186; yy309: YYDEBUG(309, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy310; if (yych != 'm') goto yy186; yy310: YYDEBUG(310, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy311; if (yych != 'e') goto yy186; yy311: YYDEBUG(311, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy312; if (yych != 's') goto yy186; yy312: YYDEBUG(312, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy313; if (yych != 'p') goto yy186; yy313: YYDEBUG(313, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy314; if (yych != 'a') goto yy186; yy314: YYDEBUG(314, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy315; if (yych != 'c') goto yy186; yy315: YYDEBUG(315, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy316; if (yych != 'e') goto yy186; yy316: YYDEBUG(316, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(317, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(318, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(319, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1698 "Zend/zend_language_scanner.l" { if (CG(current_namespace)) { *zendlval = *CG(current_namespace); zval_copy_ctor(zendlval); } else { ZVAL_EMPTY_STRING(zendlval); } return T_NS_C; } #line 4182 "Zend/zend_language_scanner.c" yy320: YYDEBUG(320, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy321; if (yych != 'r') goto yy186; yy321: YYDEBUG(321, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(322, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(323, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(324, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1671 "Zend/zend_language_scanner.l" { char *filename = zend_get_compiled_filename(TSRMLS_C); const size_t filename_len = strlen(filename); char *dirname; if (!filename) { filename = ""; } dirname = estrndup(filename, filename_len); zend_dirname(dirname, filename_len); if (strcmp(dirname, ".") == 0) { dirname = erealloc(dirname, MAXPATHLEN); #if HAVE_GETCWD VCWD_GETCWD(dirname, MAXPATHLEN); #elif HAVE_GETWD VCWD_GETWD(dirname); #endif } zendlval->value.str.len = strlen(dirname); zendlval->value.str.val = dirname; zendlval->type = IS_STRING; return T_DIR; } #line 4229 "Zend/zend_language_scanner.c" yy325: YYDEBUG(325, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy326; if (yych != 'n') goto yy186; yy326: YYDEBUG(326, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy327; if (yych != 'e') goto yy186; yy327: YYDEBUG(327, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(328, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(329, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(330, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1653 "Zend/zend_language_scanner.l" { zendlval->value.lval = CG(zend_lineno); zendlval->type = IS_LONG; return T_LINE; } #line 4260 "Zend/zend_language_scanner.c" yy331: YYDEBUG(331, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy332; if (yych != 't') goto yy186; yy332: YYDEBUG(332, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy333; if (yych != 'h') goto yy186; yy333: YYDEBUG(333, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy334; if (yych != 'o') goto yy186; yy334: YYDEBUG(334, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy335; if (yych != 'd') goto yy186; yy335: YYDEBUG(335, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(336, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(337, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(338, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1632 "Zend/zend_language_scanner.l" { const char *class_name = CG(active_class_entry) ? CG(active_class_entry)->name : NULL; const char *func_name = CG(active_op_array)? CG(active_op_array)->function_name : NULL; size_t len = 0; if (class_name) { len += strlen(class_name) + 2; } if (func_name) { len += strlen(func_name); } zendlval->value.str.len = zend_spprintf(&zendlval->value.str.val, 0, "%s%s%s", class_name ? class_name : "", class_name && func_name ? "::" : "", func_name ? func_name : "" ); zendlval->type = IS_STRING; return T_METHOD_C; } #line 4316 "Zend/zend_language_scanner.c" yy339: YYDEBUG(339, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy350; if (yych == 'l') goto yy350; goto yy186; yy340: YYDEBUG(340, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy341; if (yych != 'n') goto yy186; yy341: YYDEBUG(341, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy342; if (yych != 'c') goto yy186; yy342: YYDEBUG(342, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy343; if (yych != 't') goto yy186; yy343: YYDEBUG(343, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy344; if (yych != 'i') goto yy186; yy344: YYDEBUG(344, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy345; if (yych != 'o') goto yy186; yy345: YYDEBUG(345, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy346; if (yych != 'n') goto yy186; yy346: YYDEBUG(346, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(347, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(348, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(349, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1616 "Zend/zend_language_scanner.l" { const char *func_name = NULL; if (CG(active_op_array)) { func_name = CG(active_op_array)->function_name; } if (!func_name) { func_name = ""; } zendlval->value.str.len = strlen(func_name); zendlval->value.str.val = estrndup(func_name, zendlval->value.str.len); zendlval->type = IS_STRING; return T_FUNC_C; } #line 4383 "Zend/zend_language_scanner.c" yy350: YYDEBUG(350, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy351; if (yych != 'e') goto yy186; yy351: YYDEBUG(351, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(352, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(353, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(354, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1659 "Zend/zend_language_scanner.l" { char *filename = zend_get_compiled_filename(TSRMLS_C); if (!filename) { filename = ""; } zendlval->value.str.len = strlen(filename); zendlval->value.str.val = estrndup(filename, zendlval->value.str.len); zendlval->type = IS_STRING; return T_FILE; } #line 4415 "Zend/zend_language_scanner.c" yy355: YYDEBUG(355, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy356; if (yych != 'a') goto yy186; yy356: YYDEBUG(356, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy357; if (yych != 'i') goto yy186; yy357: YYDEBUG(357, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy358; if (yych != 't') goto yy186; yy358: YYDEBUG(358, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(359, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(360, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(361, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1596 "Zend/zend_language_scanner.l" { const char *trait_name = NULL; if (CG(active_class_entry) && (ZEND_ACC_TRAIT == (CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT))) { trait_name = CG(active_class_entry)->name; } if (!trait_name) { trait_name = ""; } zendlval->value.str.len = strlen(trait_name); zendlval->value.str.val = estrndup(trait_name, zendlval->value.str.len); zendlval->type = IS_STRING; return T_TRAIT_C; } #line 4465 "Zend/zend_language_scanner.c" yy362: YYDEBUG(362, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy363; if (yych != 'a') goto yy186; yy363: YYDEBUG(363, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy364; if (yych != 's') goto yy186; yy364: YYDEBUG(364, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy365; if (yych != 's') goto yy186; yy365: YYDEBUG(365, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(366, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(367, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(368, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1569 "Zend/zend_language_scanner.l" { const char *class_name = NULL; if (CG(active_class_entry) && (ZEND_ACC_TRAIT == (CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT))) { /* We create a special __CLASS__ constant that is going to be resolved at run-time */ zendlval->value.str.len = sizeof("__CLASS__")-1; zendlval->value.str.val = estrndup("__CLASS__", zendlval->value.str.len); zendlval->type = IS_CONSTANT; } else { if (CG(active_class_entry)) { class_name = CG(active_class_entry)->name; } if (!class_name) { class_name = ""; } zendlval->value.str.len = strlen(class_name); zendlval->value.str.val = estrndup(class_name, zendlval->value.str.len); zendlval->type = IS_STRING; } return T_CLASS_C; } #line 4522 "Zend/zend_language_scanner.c" yy369: YYDEBUG(369, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy370; if (yych != 'l') goto yy186; yy370: YYDEBUG(370, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy371; if (yych != 't') goto yy186; yy371: YYDEBUG(371, *YYCURSOR); yych = *++YYCURSOR; if (yych != '_') goto yy186; YYDEBUG(372, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy373; if (yych != 'c') goto yy186; yy373: YYDEBUG(373, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy374; if (yych != 'o') goto yy186; yy374: YYDEBUG(374, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy375; if (yych != 'm') goto yy186; yy375: YYDEBUG(375, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy376; if (yych != 'p') goto yy186; yy376: YYDEBUG(376, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy377; if (yych != 'i') goto yy186; yy377: YYDEBUG(377, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy378; if (yych != 'l') goto yy186; yy378: YYDEBUG(378, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy379; if (yych != 'e') goto yy186; yy379: YYDEBUG(379, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy380; if (yych != 'r') goto yy186; yy380: YYDEBUG(380, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(381, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1279 "Zend/zend_language_scanner.l" { return T_HALT_COMPILER; } #line 4588 "Zend/zend_language_scanner.c" yy382: YYDEBUG(382, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy386; if (yych == 's') goto yy386; goto yy186; yy383: YYDEBUG(383, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy384; if (yych != 'e') goto yy186; yy384: YYDEBUG(384, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(385, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1259 "Zend/zend_language_scanner.l" { return T_USE; } #line 4612 "Zend/zend_language_scanner.c" yy386: YYDEBUG(386, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy387; if (yych != 'e') goto yy186; yy387: YYDEBUG(387, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy388; if (yych != 't') goto yy186; yy388: YYDEBUG(388, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(389, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1307 "Zend/zend_language_scanner.l" { return T_UNSET; } #line 4635 "Zend/zend_language_scanner.c" yy390: YYDEBUG(390, *YYCURSOR); ++YYCURSOR; YYFILL(7); yych = *YYCURSOR; yy391: YYDEBUG(391, *YYCURSOR); if (yych <= 'S') { if (yych <= 'D') { if (yych <= ' ') { if (yych == '\t') goto yy390; if (yych <= 0x1F) goto yy193; goto yy390; } else { if (yych <= 'A') { if (yych <= '@') goto yy193; goto yy395; } else { if (yych <= 'B') goto yy393; if (yych <= 'C') goto yy193; goto yy398; } } } else { if (yych <= 'I') { if (yych == 'F') goto yy399; if (yych <= 'H') goto yy193; goto yy400; } else { if (yych <= 'O') { if (yych <= 'N') goto yy193; goto yy394; } else { if (yych <= 'Q') goto yy193; if (yych <= 'R') goto yy397; goto yy396; } } } } else { if (yych <= 'f') { if (yych <= 'a') { if (yych == 'U') goto yy392; if (yych <= '`') goto yy193; goto yy395; } else { if (yych <= 'c') { if (yych <= 'b') goto yy393; goto yy193; } else { if (yych <= 'd') goto yy398; if (yych <= 'e') goto yy193; goto yy399; } } } else { if (yych <= 'q') { if (yych <= 'i') { if (yych <= 'h') goto yy193; goto yy400; } else { if (yych == 'o') goto yy394; goto yy193; } } else { if (yych <= 's') { if (yych <= 'r') goto yy397; goto yy396; } else { if (yych != 'u') goto yy193; } } } } yy392: YYDEBUG(392, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy459; if (yych == 'n') goto yy459; goto yy193; yy393: YYDEBUG(393, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'I') goto yy446; if (yych <= 'N') goto yy193; goto yy447; } else { if (yych <= 'i') { if (yych <= 'h') goto yy193; goto yy446; } else { if (yych == 'o') goto yy447; goto yy193; } } yy394: YYDEBUG(394, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy438; if (yych == 'b') goto yy438; goto yy193; yy395: YYDEBUG(395, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy431; if (yych == 'r') goto yy431; goto yy193; yy396: YYDEBUG(396, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy423; if (yych == 't') goto yy423; goto yy193; yy397: YYDEBUG(397, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy421; if (yych == 'e') goto yy421; goto yy193; yy398: YYDEBUG(398, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy417; if (yych == 'o') goto yy417; goto yy193; yy399: YYDEBUG(399, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy410; if (yych == 'l') goto yy410; goto yy193; yy400: YYDEBUG(400, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy401; if (yych != 'n') goto yy193; yy401: YYDEBUG(401, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy402; if (yych != 't') goto yy193; yy402: YYDEBUG(402, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy403; if (yych != 'e') goto yy405; yy403: YYDEBUG(403, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy408; if (yych == 'g') goto yy408; goto yy193; yy404: YYDEBUG(404, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy405: YYDEBUG(405, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy404; goto yy193; } else { if (yych <= ' ') goto yy404; if (yych != ')') goto yy193; } YYDEBUG(406, *YYCURSOR); ++YYCURSOR; YYDEBUG(407, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1207 "Zend/zend_language_scanner.l" { return T_INT_CAST; } #line 4811 "Zend/zend_language_scanner.c" yy408: YYDEBUG(408, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy409; if (yych != 'e') goto yy193; yy409: YYDEBUG(409, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy404; if (yych == 'r') goto yy404; goto yy193; yy410: YYDEBUG(410, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy411; if (yych != 'o') goto yy193; yy411: YYDEBUG(411, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy412; if (yych != 'a') goto yy193; yy412: YYDEBUG(412, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy413; if (yych != 't') goto yy193; yy413: YYDEBUG(413, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(414, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy413; goto yy193; } else { if (yych <= ' ') goto yy413; if (yych != ')') goto yy193; } YYDEBUG(415, *YYCURSOR); ++YYCURSOR; YYDEBUG(416, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1211 "Zend/zend_language_scanner.l" { return T_DOUBLE_CAST; } #line 4859 "Zend/zend_language_scanner.c" yy417: YYDEBUG(417, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy418; if (yych != 'u') goto yy193; yy418: YYDEBUG(418, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy419; if (yych != 'b') goto yy193; yy419: YYDEBUG(419, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy420; if (yych != 'l') goto yy193; yy420: YYDEBUG(420, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy413; if (yych == 'e') goto yy413; goto yy193; yy421: YYDEBUG(421, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy422; if (yych != 'a') goto yy193; yy422: YYDEBUG(422, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy413; if (yych == 'l') goto yy413; goto yy193; yy423: YYDEBUG(423, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy424; if (yych != 'r') goto yy193; yy424: YYDEBUG(424, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy425; if (yych != 'i') goto yy193; yy425: YYDEBUG(425, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy426; if (yych != 'n') goto yy193; yy426: YYDEBUG(426, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'G') goto yy427; if (yych != 'g') goto yy193; yy427: YYDEBUG(427, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(428, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy427; goto yy193; } else { if (yych <= ' ') goto yy427; if (yych != ')') goto yy193; } YYDEBUG(429, *YYCURSOR); ++YYCURSOR; YYDEBUG(430, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1215 "Zend/zend_language_scanner.l" { return T_STRING_CAST; } #line 4933 "Zend/zend_language_scanner.c" yy431: YYDEBUG(431, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy432; if (yych != 'r') goto yy193; yy432: YYDEBUG(432, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy433; if (yych != 'a') goto yy193; yy433: YYDEBUG(433, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy434; if (yych != 'y') goto yy193; yy434: YYDEBUG(434, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(435, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy434; goto yy193; } else { if (yych <= ' ') goto yy434; if (yych != ')') goto yy193; } YYDEBUG(436, *YYCURSOR); ++YYCURSOR; YYDEBUG(437, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1219 "Zend/zend_language_scanner.l" { return T_ARRAY_CAST; } #line 4970 "Zend/zend_language_scanner.c" yy438: YYDEBUG(438, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'J') goto yy439; if (yych != 'j') goto yy193; yy439: YYDEBUG(439, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy440; if (yych != 'e') goto yy193; yy440: YYDEBUG(440, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy441; if (yych != 'c') goto yy193; yy441: YYDEBUG(441, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy442; if (yych != 't') goto yy193; yy442: YYDEBUG(442, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(443, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy442; goto yy193; } else { if (yych <= ' ') goto yy442; if (yych != ')') goto yy193; } YYDEBUG(444, *YYCURSOR); ++YYCURSOR; YYDEBUG(445, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1223 "Zend/zend_language_scanner.l" { return T_OBJECT_CAST; } #line 5012 "Zend/zend_language_scanner.c" yy446: YYDEBUG(446, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy456; if (yych == 'n') goto yy456; goto yy193; yy447: YYDEBUG(447, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy448; if (yych != 'o') goto yy193; yy448: YYDEBUG(448, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy449; if (yych != 'l') goto yy193; yy449: YYDEBUG(449, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy454; if (yych == 'e') goto yy454; goto yy451; yy450: YYDEBUG(450, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy451: YYDEBUG(451, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy450; goto yy193; } else { if (yych <= ' ') goto yy450; if (yych != ')') goto yy193; } YYDEBUG(452, *YYCURSOR); ++YYCURSOR; YYDEBUG(453, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1227 "Zend/zend_language_scanner.l" { return T_BOOL_CAST; } #line 5057 "Zend/zend_language_scanner.c" yy454: YYDEBUG(454, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy455; if (yych != 'a') goto yy193; yy455: YYDEBUG(455, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy450; if (yych == 'n') goto yy450; goto yy193; yy456: YYDEBUG(456, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy457; if (yych != 'a') goto yy193; yy457: YYDEBUG(457, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy458; if (yych != 'r') goto yy193; yy458: YYDEBUG(458, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy427; if (yych == 'y') goto yy427; goto yy193; yy459: YYDEBUG(459, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy460; if (yych != 's') goto yy193; yy460: YYDEBUG(460, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy461; if (yych != 'e') goto yy193; yy461: YYDEBUG(461, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy462; if (yych != 't') goto yy193; yy462: YYDEBUG(462, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(463, *YYCURSOR); if (yych <= 0x1F) { if (yych == '\t') goto yy462; goto yy193; } else { if (yych <= ' ') goto yy462; if (yych != ')') goto yy193; } YYDEBUG(464, *YYCURSOR); ++YYCURSOR; YYDEBUG(465, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1231 "Zend/zend_language_scanner.l" { return T_UNSET_CAST; } #line 5121 "Zend/zend_language_scanner.c" yy466: YYDEBUG(466, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy467; if (yych != 'r') goto yy186; yy467: YYDEBUG(467, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(468, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1203 "Zend/zend_language_scanner.l" { return T_VAR; } #line 5139 "Zend/zend_language_scanner.c" yy469: YYDEBUG(469, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy473; if (yych == 'm') goto yy473; goto yy186; yy470: YYDEBUG(470, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'W') goto yy471; if (yych != 'w') goto yy186; yy471: YYDEBUG(471, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(472, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1195 "Zend/zend_language_scanner.l" { return T_NEW; } #line 5163 "Zend/zend_language_scanner.c" yy473: YYDEBUG(473, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy474; if (yych != 'e') goto yy186; yy474: YYDEBUG(474, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy475; if (yych != 's') goto yy186; yy475: YYDEBUG(475, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy476; if (yych != 'p') goto yy186; yy476: YYDEBUG(476, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy477; if (yych != 'a') goto yy186; yy477: YYDEBUG(477, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy478; if (yych != 'c') goto yy186; yy478: YYDEBUG(478, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy479; if (yych != 'e') goto yy186; yy479: YYDEBUG(479, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(480, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1255 "Zend/zend_language_scanner.l" { return T_NAMESPACE; } #line 5206 "Zend/zend_language_scanner.c" yy481: YYDEBUG(481, *YYCURSOR); ++YYCURSOR; YYDEBUG(482, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1187 "Zend/zend_language_scanner.l" { return T_PAAMAYIM_NEKUDOTAYIM; } #line 5216 "Zend/zend_language_scanner.c" yy483: YYDEBUG(483, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy484: YYDEBUG(484, *YYCURSOR); if (yych <= '\f') { if (yych <= 0x08) goto yy140; if (yych <= '\n') goto yy483; goto yy140; } else { if (yych <= '\r') goto yy483; if (yych == ' ') goto yy483; goto yy140; } yy485: YYDEBUG(485, *YYCURSOR); ++YYCURSOR; YYDEBUG(486, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1363 "Zend/zend_language_scanner.l" { return T_MINUS_EQUAL; } #line 5242 "Zend/zend_language_scanner.c" yy487: YYDEBUG(487, *YYCURSOR); ++YYCURSOR; YYDEBUG(488, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1331 "Zend/zend_language_scanner.l" { return T_DEC; } #line 5252 "Zend/zend_language_scanner.c" yy489: YYDEBUG(489, *YYCURSOR); ++YYCURSOR; YYDEBUG(490, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1157 "Zend/zend_language_scanner.l" { yy_push_state(ST_LOOKING_FOR_PROPERTY TSRMLS_CC); return T_OBJECT_OPERATOR; } #line 5263 "Zend/zend_language_scanner.c" yy491: YYDEBUG(491, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'I') goto yy498; if (yych <= 'N') goto yy186; goto yy499; } else { if (yych <= 'i') { if (yych <= 'h') goto yy186; goto yy498; } else { if (yych == 'o') goto yy499; goto yy186; } } yy492: YYDEBUG(492, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy493; if (yych != 'b') goto yy186; yy493: YYDEBUG(493, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy494; if (yych != 'l') goto yy186; yy494: YYDEBUG(494, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy495; if (yych != 'i') goto yy186; yy495: YYDEBUG(495, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy496; if (yych != 'c') goto yy186; yy496: YYDEBUG(496, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(497, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1303 "Zend/zend_language_scanner.l" { return T_PUBLIC; } #line 5312 "Zend/zend_language_scanner.c" yy498: YYDEBUG(498, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'V') { if (yych == 'N') goto yy507; if (yych <= 'U') goto yy186; goto yy508; } else { if (yych <= 'n') { if (yych <= 'm') goto yy186; goto yy507; } else { if (yych == 'v') goto yy508; goto yy186; } } yy499: YYDEBUG(499, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy500; if (yych != 't') goto yy186; yy500: YYDEBUG(500, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy501; if (yych != 'e') goto yy186; yy501: YYDEBUG(501, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy502; if (yych != 'c') goto yy186; yy502: YYDEBUG(502, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy503; if (yych != 't') goto yy186; yy503: YYDEBUG(503, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy504; if (yych != 'e') goto yy186; yy504: YYDEBUG(504, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy505; if (yych != 'd') goto yy186; yy505: YYDEBUG(505, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(506, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1299 "Zend/zend_language_scanner.l" { return T_PROTECTED; } #line 5371 "Zend/zend_language_scanner.c" yy507: YYDEBUG(507, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy513; if (yych == 't') goto yy513; goto yy186; yy508: YYDEBUG(508, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy509; if (yych != 'a') goto yy186; yy509: YYDEBUG(509, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy510; if (yych != 't') goto yy186; yy510: YYDEBUG(510, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy511; if (yych != 'e') goto yy186; yy511: YYDEBUG(511, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(512, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1295 "Zend/zend_language_scanner.l" { return T_PRIVATE; } #line 5405 "Zend/zend_language_scanner.c" yy513: YYDEBUG(513, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(514, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1133 "Zend/zend_language_scanner.l" { return T_PRINT; } #line 5418 "Zend/zend_language_scanner.c" yy515: YYDEBUG(515, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy520; if (yych == 'o') goto yy520; goto yy186; yy516: YYDEBUG(516, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy517; if (yych != 't') goto yy186; yy517: YYDEBUG(517, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy518; if (yych != 'o') goto yy186; yy518: YYDEBUG(518, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(519, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1125 "Zend/zend_language_scanner.l" { return T_GOTO; } #line 5447 "Zend/zend_language_scanner.c" yy520: YYDEBUG(520, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy521; if (yych != 'b') goto yy186; yy521: YYDEBUG(521, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy522; if (yych != 'a') goto yy186; yy522: YYDEBUG(522, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy523; if (yych != 'l') goto yy186; yy523: YYDEBUG(523, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(524, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1267 "Zend/zend_language_scanner.l" { return T_GLOBAL; } #line 5475 "Zend/zend_language_scanner.c" yy525: YYDEBUG(525, *YYCURSOR); yych = *++YYCURSOR; if (yych == '<') goto yy533; goto yy193; yy526: YYDEBUG(526, *YYCURSOR); yych = *++YYCURSOR; goto yy180; yy527: YYDEBUG(527, *YYCURSOR); yych = *++YYCURSOR; goto yy178; yy528: YYDEBUG(528, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy529; if (yych != 'e') goto yy186; yy529: YYDEBUG(529, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy530; if (yych != 'a') goto yy186; yy530: YYDEBUG(530, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'K') goto yy531; if (yych != 'k') goto yy186; yy531: YYDEBUG(531, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(532, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1117 "Zend/zend_language_scanner.l" { return T_BREAK; } #line 5516 "Zend/zend_language_scanner.c" yy533: YYDEBUG(533, *YYCURSOR); yych = *++YYCURSOR; if (yych == '<') goto yy269; goto yy193; yy534: YYDEBUG(534, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy541; if (yych == 'a') goto yy541; goto yy186; yy535: YYDEBUG(535, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy536; if (yych != 'i') goto yy186; yy536: YYDEBUG(536, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy537; if (yych != 't') goto yy186; yy537: YYDEBUG(537, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy538; if (yych != 'c') goto yy186; yy538: YYDEBUG(538, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy539; if (yych != 'h') goto yy186; yy539: YYDEBUG(539, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(540, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1101 "Zend/zend_language_scanner.l" { return T_SWITCH; } #line 5560 "Zend/zend_language_scanner.c" yy541: YYDEBUG(541, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy542; if (yych != 't') goto yy186; yy542: YYDEBUG(542, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy543; if (yych != 'i') goto yy186; yy543: YYDEBUG(543, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy544; if (yych != 'c') goto yy186; yy544: YYDEBUG(544, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(545, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1283 "Zend/zend_language_scanner.l" { return T_STATIC; } #line 5588 "Zend/zend_language_scanner.c" yy546: YYDEBUG(546, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy557; if (yych == 's') goto yy557; goto yy186; yy547: YYDEBUG(547, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy555; if (yych == 'd') goto yy555; goto yy186; yy548: YYDEBUG(548, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy551; if (yych == 'r') goto yy551; goto yy186; yy549: YYDEBUG(549, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(550, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1097 "Zend/zend_language_scanner.l" { return T_AS; } #line 5619 "Zend/zend_language_scanner.c" yy551: YYDEBUG(551, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy552; if (yych != 'a') goto yy186; yy552: YYDEBUG(552, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy553; if (yych != 'y') goto yy186; yy553: YYDEBUG(553, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(554, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1319 "Zend/zend_language_scanner.l" { return T_ARRAY; } #line 5642 "Zend/zend_language_scanner.c" yy555: YYDEBUG(555, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(556, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1415 "Zend/zend_language_scanner.l" { return T_LOGICAL_AND; } #line 5655 "Zend/zend_language_scanner.c" yy557: YYDEBUG(557, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy558; if (yych != 't') goto yy186; yy558: YYDEBUG(558, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy559; if (yych != 'r') goto yy186; yy559: YYDEBUG(559, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy560; if (yych != 'a') goto yy186; yy560: YYDEBUG(560, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy561; if (yych != 'c') goto yy186; yy561: YYDEBUG(561, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy562; if (yych != 't') goto yy186; yy562: YYDEBUG(562, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(563, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1287 "Zend/zend_language_scanner.l" { return T_ABSTRACT; } #line 5693 "Zend/zend_language_scanner.c" yy564: YYDEBUG(564, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy565; if (yych != 'i') goto yy186; yy565: YYDEBUG(565, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy566; if (yych != 'l') goto yy186; yy566: YYDEBUG(566, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy567; if (yych != 'e') goto yy186; yy567: YYDEBUG(567, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(568, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1057 "Zend/zend_language_scanner.l" { return T_WHILE; } #line 5721 "Zend/zend_language_scanner.c" yy569: YYDEBUG(569, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(570, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1041 "Zend/zend_language_scanner.l" { return T_IF; } #line 5734 "Zend/zend_language_scanner.c" yy571: YYDEBUG(571, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy613; if (yych == 'p') goto yy613; goto yy186; yy572: YYDEBUG(572, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= 'C') { if (yych <= 'B') goto yy186; goto yy580; } else { if (yych <= 'R') goto yy186; if (yych <= 'S') goto yy578; goto yy579; } } else { if (yych <= 'r') { if (yych == 'c') goto yy580; goto yy186; } else { if (yych <= 's') goto yy578; if (yych <= 't') goto yy579; goto yy186; } } yy573: YYDEBUG(573, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy574; if (yych != 's') goto yy186; yy574: YYDEBUG(574, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy575; if (yych != 'e') goto yy186; yy575: YYDEBUG(575, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy576; if (yych != 't') goto yy186; yy576: YYDEBUG(576, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(577, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1271 "Zend/zend_language_scanner.l" { return T_ISSET; } #line 5790 "Zend/zend_language_scanner.c" yy578: YYDEBUG(578, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy599; if (yych == 't') goto yy599; goto yy186; yy579: YYDEBUG(579, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy592; if (yych == 'e') goto yy592; goto yy186; yy580: YYDEBUG(580, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy581; if (yych != 'l') goto yy186; yy581: YYDEBUG(581, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy582; if (yych != 'u') goto yy186; yy582: YYDEBUG(582, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy583; if (yych != 'd') goto yy186; yy583: YYDEBUG(583, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy584; if (yych != 'e') goto yy186; yy584: YYDEBUG(584, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '9') { if (yych >= '0') goto yy185; } else { if (yych <= '@') goto yy585; if (yych <= 'Z') goto yy185; } } else { if (yych <= '`') { if (yych <= '_') goto yy586; } else { if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy585: YYDEBUG(585, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1239 "Zend/zend_language_scanner.l" { return T_INCLUDE; } #line 5848 "Zend/zend_language_scanner.c" yy586: YYDEBUG(586, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy587; if (yych != 'o') goto yy186; yy587: YYDEBUG(587, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy588; if (yych != 'n') goto yy186; yy588: YYDEBUG(588, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy589; if (yych != 'c') goto yy186; yy589: YYDEBUG(589, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy590; if (yych != 'e') goto yy186; yy590: YYDEBUG(590, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(591, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1243 "Zend/zend_language_scanner.l" { return T_INCLUDE_ONCE; } #line 5881 "Zend/zend_language_scanner.c" yy592: YYDEBUG(592, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy593; if (yych != 'r') goto yy186; yy593: YYDEBUG(593, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy594; if (yych != 'f') goto yy186; yy594: YYDEBUG(594, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy595; if (yych != 'a') goto yy186; yy595: YYDEBUG(595, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy596; if (yych != 'c') goto yy186; yy596: YYDEBUG(596, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy597; if (yych != 'e') goto yy186; yy597: YYDEBUG(597, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(598, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1141 "Zend/zend_language_scanner.l" { return T_INTERFACE; } #line 5919 "Zend/zend_language_scanner.c" yy599: YYDEBUG(599, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'E') { if (yych == 'A') goto yy600; if (yych <= 'D') goto yy186; goto yy601; } else { if (yych <= 'a') { if (yych <= '`') goto yy186; } else { if (yych == 'e') goto yy601; goto yy186; } } yy600: YYDEBUG(600, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy607; if (yych == 'n') goto yy607; goto yy186; yy601: YYDEBUG(601, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy602; if (yych != 'a') goto yy186; yy602: YYDEBUG(602, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy603; if (yych != 'd') goto yy186; yy603: YYDEBUG(603, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy604; if (yych != 'o') goto yy186; yy604: YYDEBUG(604, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy605; if (yych != 'f') goto yy186; yy605: YYDEBUG(605, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(606, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1263 "Zend/zend_language_scanner.l" { return T_INSTEADOF; } #line 5973 "Zend/zend_language_scanner.c" yy607: YYDEBUG(607, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy608; if (yych != 'c') goto yy186; yy608: YYDEBUG(608, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy609; if (yych != 'e') goto yy186; yy609: YYDEBUG(609, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy610; if (yych != 'o') goto yy186; yy610: YYDEBUG(610, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy611; if (yych != 'f') goto yy186; yy611: YYDEBUG(611, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(612, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1093 "Zend/zend_language_scanner.l" { return T_INSTANCEOF; } #line 6006 "Zend/zend_language_scanner.c" yy613: YYDEBUG(613, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy614; if (yych != 'l') goto yy186; yy614: YYDEBUG(614, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy615; if (yych != 'e') goto yy186; yy615: YYDEBUG(615, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'M') goto yy616; if (yych != 'm') goto yy186; yy616: YYDEBUG(616, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy617; if (yych != 'e') goto yy186; yy617: YYDEBUG(617, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy618; if (yych != 'n') goto yy186; yy618: YYDEBUG(618, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy619; if (yych != 't') goto yy186; yy619: YYDEBUG(619, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy620; if (yych != 's') goto yy186; yy620: YYDEBUG(620, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(621, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1153 "Zend/zend_language_scanner.l" { return T_IMPLEMENTS; } #line 6054 "Zend/zend_language_scanner.c" yy622: YYDEBUG(622, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy630; if (yych == 'r') goto yy630; goto yy186; yy623: YYDEBUG(623, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'Y') { if (yych == 'A') goto yy626; if (yych <= 'X') goto yy186; } else { if (yych <= 'a') { if (yych <= '`') goto yy186; goto yy626; } else { if (yych != 'y') goto yy186; } } YYDEBUG(624, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(625, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1029 "Zend/zend_language_scanner.l" { return T_TRY; } #line 6086 "Zend/zend_language_scanner.c" yy626: YYDEBUG(626, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy627; if (yych != 'i') goto yy186; yy627: YYDEBUG(627, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy628; if (yych != 't') goto yy186; yy628: YYDEBUG(628, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(629, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1145 "Zend/zend_language_scanner.l" { return T_TRAIT; } #line 6109 "Zend/zend_language_scanner.c" yy630: YYDEBUG(630, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy631; if (yych != 'o') goto yy186; yy631: YYDEBUG(631, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'W') goto yy632; if (yych != 'w') goto yy186; yy632: YYDEBUG(632, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(633, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1037 "Zend/zend_language_scanner.l" { return T_THROW; } #line 6132 "Zend/zend_language_scanner.c" yy634: YYDEBUG(634, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych == 'Q') goto yy636; if (yych <= 'S') goto yy186; } else { if (yych <= 'q') { if (yych <= 'p') goto yy186; goto yy636; } else { if (yych != 't') goto yy186; } } YYDEBUG(635, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy648; if (yych == 'u') goto yy648; goto yy186; yy636: YYDEBUG(636, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy637; if (yych != 'u') goto yy186; yy637: YYDEBUG(637, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy638; if (yych != 'i') goto yy186; yy638: YYDEBUG(638, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy639; if (yych != 'r') goto yy186; yy639: YYDEBUG(639, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy640; if (yych != 'e') goto yy186; yy640: YYDEBUG(640, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '9') { if (yych >= '0') goto yy185; } else { if (yych <= '@') goto yy641; if (yych <= 'Z') goto yy185; } } else { if (yych <= '`') { if (yych <= '_') goto yy642; } else { if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy641: YYDEBUG(641, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1247 "Zend/zend_language_scanner.l" { return T_REQUIRE; } #line 6197 "Zend/zend_language_scanner.c" yy642: YYDEBUG(642, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy643; if (yych != 'o') goto yy186; yy643: YYDEBUG(643, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy644; if (yych != 'n') goto yy186; yy644: YYDEBUG(644, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy645; if (yych != 'c') goto yy186; yy645: YYDEBUG(645, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy646; if (yych != 'e') goto yy186; yy646: YYDEBUG(646, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(647, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1251 "Zend/zend_language_scanner.l" { return T_REQUIRE_ONCE; } #line 6230 "Zend/zend_language_scanner.c" yy648: YYDEBUG(648, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy649; if (yych != 'r') goto yy186; yy649: YYDEBUG(649, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy650; if (yych != 'n') goto yy186; yy650: YYDEBUG(650, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(651, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1025 "Zend/zend_language_scanner.l" { return T_RETURN; } #line 6253 "Zend/zend_language_scanner.c" yy652: YYDEBUG(652, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= 'L') { if (yych <= 'K') goto yy186; goto yy675; } else { if (yych <= 'R') goto yy186; if (yych <= 'S') goto yy674; goto yy673; } } else { if (yych <= 'r') { if (yych == 'l') goto yy675; goto yy186; } else { if (yych <= 's') goto yy674; if (yych <= 't') goto yy673; goto yy186; } } yy653: YYDEBUG(653, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'O') { if (yych == 'A') goto yy665; if (yych <= 'N') goto yy186; goto yy666; } else { if (yych <= 'a') { if (yych <= '`') goto yy186; goto yy665; } else { if (yych == 'o') goto yy666; goto yy186; } } yy654: YYDEBUG(654, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy655; if (yych != 'n') goto yy186; yy655: YYDEBUG(655, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych <= 'R') goto yy186; if (yych >= 'T') goto yy657; } else { if (yych <= 'r') goto yy186; if (yych <= 's') goto yy656; if (yych <= 't') goto yy657; goto yy186; } yy656: YYDEBUG(656, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy663; if (yych == 't') goto yy663; goto yy186; yy657: YYDEBUG(657, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy658; if (yych != 'i') goto yy186; yy658: YYDEBUG(658, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy659; if (yych != 'n') goto yy186; yy659: YYDEBUG(659, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy660; if (yych != 'u') goto yy186; yy660: YYDEBUG(660, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy661; if (yych != 'e') goto yy186; yy661: YYDEBUG(661, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(662, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1121 "Zend/zend_language_scanner.l" { return T_CONTINUE; } #line 6347 "Zend/zend_language_scanner.c" yy663: YYDEBUG(663, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(664, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1021 "Zend/zend_language_scanner.l" { return T_CONST; } #line 6360 "Zend/zend_language_scanner.c" yy665: YYDEBUG(665, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy670; if (yych == 's') goto yy670; goto yy186; yy666: YYDEBUG(666, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy667; if (yych != 'n') goto yy186; yy667: YYDEBUG(667, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy668; if (yych != 'e') goto yy186; yy668: YYDEBUG(668, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(669, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1199 "Zend/zend_language_scanner.l" { return T_CLONE; } #line 6389 "Zend/zend_language_scanner.c" yy670: YYDEBUG(670, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy671; if (yych != 's') goto yy186; yy671: YYDEBUG(671, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(672, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1137 "Zend/zend_language_scanner.l" { return T_CLASS; } #line 6407 "Zend/zend_language_scanner.c" yy673: YYDEBUG(673, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy684; if (yych == 'c') goto yy684; goto yy186; yy674: YYDEBUG(674, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy682; if (yych == 'e') goto yy682; goto yy186; yy675: YYDEBUG(675, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy676; if (yych != 'l') goto yy186; yy676: YYDEBUG(676, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy677; if (yych != 'a') goto yy186; yy677: YYDEBUG(677, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'B') goto yy678; if (yych != 'b') goto yy186; yy678: YYDEBUG(678, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy679; if (yych != 'l') goto yy186; yy679: YYDEBUG(679, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy680; if (yych != 'e') goto yy186; yy680: YYDEBUG(680, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(681, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1323 "Zend/zend_language_scanner.l" { return T_CALLABLE; } #line 6457 "Zend/zend_language_scanner.c" yy682: YYDEBUG(682, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(683, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1109 "Zend/zend_language_scanner.l" { return T_CASE; } #line 6470 "Zend/zend_language_scanner.c" yy684: YYDEBUG(684, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy685; if (yych != 'h') goto yy186; yy685: YYDEBUG(685, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(686, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1033 "Zend/zend_language_scanner.l" { return T_CATCH; } #line 6488 "Zend/zend_language_scanner.c" yy687: YYDEBUG(687, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy704; if (yych == 'n') goto yy704; goto yy186; yy688: YYDEBUG(688, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy697; if (yych == 'r') goto yy697; goto yy186; yy689: YYDEBUG(689, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy690; if (yych != 'n') goto yy186; yy690: YYDEBUG(690, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy691; if (yych != 'c') goto yy186; yy691: YYDEBUG(691, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy692; if (yych != 't') goto yy186; yy692: YYDEBUG(692, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy693; if (yych != 'i') goto yy186; yy693: YYDEBUG(693, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy694; if (yych != 'o') goto yy186; yy694: YYDEBUG(694, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy695; if (yych != 'n') goto yy186; yy695: YYDEBUG(695, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(696, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1017 "Zend/zend_language_scanner.l" { return T_FUNCTION; } #line 6543 "Zend/zend_language_scanner.c" yy697: YYDEBUG(697, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '@') { if (yych <= '/') goto yy698; if (yych <= '9') goto yy185; } else { if (yych == 'E') goto yy699; if (yych <= 'Z') goto yy185; } } else { if (yych <= 'd') { if (yych != '`') goto yy185; } else { if (yych <= 'e') goto yy699; if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy698: YYDEBUG(698, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1069 "Zend/zend_language_scanner.l" { return T_FOR; } #line 6571 "Zend/zend_language_scanner.c" yy699: YYDEBUG(699, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy700; if (yych != 'a') goto yy186; yy700: YYDEBUG(700, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy701; if (yych != 'c') goto yy186; yy701: YYDEBUG(701, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy702; if (yych != 'h') goto yy186; yy702: YYDEBUG(702, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(703, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1077 "Zend/zend_language_scanner.l" { return T_FOREACH; } #line 6599 "Zend/zend_language_scanner.c" yy704: YYDEBUG(704, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy705; if (yych != 'a') goto yy186; yy705: YYDEBUG(705, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy706; if (yych != 'l') goto yy186; yy706: YYDEBUG(706, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(707, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1291 "Zend/zend_language_scanner.l" { return T_FINAL; } #line 6622 "Zend/zend_language_scanner.c" yy708: YYDEBUG(708, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'F') { if (yych == 'C') goto yy714; if (yych <= 'E') goto yy186; goto yy715; } else { if (yych <= 'c') { if (yych <= 'b') goto yy186; goto yy714; } else { if (yych == 'f') goto yy715; goto yy186; } } yy709: YYDEBUG(709, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy712; if (yych == 'e') goto yy712; goto yy186; yy710: YYDEBUG(710, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(711, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1065 "Zend/zend_language_scanner.l" { return T_DO; } #line 6657 "Zend/zend_language_scanner.c" yy712: YYDEBUG(712, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(713, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1013 "Zend/zend_language_scanner.l" { return T_EXIT; } #line 6670 "Zend/zend_language_scanner.c" yy714: YYDEBUG(714, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy721; if (yych == 'l') goto yy721; goto yy186; yy715: YYDEBUG(715, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy716; if (yych != 'a') goto yy186; yy716: YYDEBUG(716, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'U') goto yy717; if (yych != 'u') goto yy186; yy717: YYDEBUG(717, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy718; if (yych != 'l') goto yy186; yy718: YYDEBUG(718, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy719; if (yych != 't') goto yy186; yy719: YYDEBUG(719, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(720, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1113 "Zend/zend_language_scanner.l" { return T_DEFAULT; } #line 6709 "Zend/zend_language_scanner.c" yy721: YYDEBUG(721, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy722; if (yych != 'a') goto yy186; yy722: YYDEBUG(722, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy723; if (yych != 'r') goto yy186; yy723: YYDEBUG(723, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy724; if (yych != 'e') goto yy186; yy724: YYDEBUG(724, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(725, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1085 "Zend/zend_language_scanner.l" { return T_DECLARE; } #line 6737 "Zend/zend_language_scanner.c" yy726: YYDEBUG(726, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy788; if (yych == 'h') goto yy788; goto yy186; yy727: YYDEBUG(727, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy782; if (yych == 's') goto yy782; goto yy186; yy728: YYDEBUG(728, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'P') goto yy778; if (yych == 'p') goto yy778; goto yy186; yy729: YYDEBUG(729, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy744; if (yych == 'd') goto yy744; goto yy186; yy730: YYDEBUG(730, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy741; if (yych == 'a') goto yy741; goto yy186; yy731: YYDEBUG(731, *YYCURSOR); yych = *++YYCURSOR; if (yych <= 'T') { if (yych == 'I') goto yy732; if (yych <= 'S') goto yy186; goto yy733; } else { if (yych <= 'i') { if (yych <= 'h') goto yy186; } else { if (yych == 't') goto yy733; goto yy186; } } yy732: YYDEBUG(732, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy739; if (yych == 't') goto yy739; goto yy186; yy733: YYDEBUG(733, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy734; if (yych != 'e') goto yy186; yy734: YYDEBUG(734, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'N') goto yy735; if (yych != 'n') goto yy186; yy735: YYDEBUG(735, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'D') goto yy736; if (yych != 'd') goto yy186; yy736: YYDEBUG(736, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'S') goto yy737; if (yych != 's') goto yy186; yy737: YYDEBUG(737, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(738, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1149 "Zend/zend_language_scanner.l" { return T_EXTENDS; } #line 6821 "Zend/zend_language_scanner.c" yy739: YYDEBUG(739, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(740, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1009 "Zend/zend_language_scanner.l" { return T_EXIT; } #line 6834 "Zend/zend_language_scanner.c" yy741: YYDEBUG(741, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy742; if (yych != 'l') goto yy186; yy742: YYDEBUG(742, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(743, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1235 "Zend/zend_language_scanner.l" { return T_EVAL; } #line 6852 "Zend/zend_language_scanner.c" yy744: YYDEBUG(744, *YYCURSOR); yych = *++YYCURSOR; YYDEBUG(-1, yych); switch (yych) { case 'D': case 'd': goto yy745; case 'F': case 'f': goto yy746; case 'I': case 'i': goto yy747; case 'S': case 's': goto yy748; case 'W': case 'w': goto yy749; default: goto yy186; } yy745: YYDEBUG(745, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy771; if (yych == 'e') goto yy771; goto yy186; yy746: YYDEBUG(746, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy763; if (yych == 'o') goto yy763; goto yy186; yy747: YYDEBUG(747, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy761; if (yych == 'f') goto yy761; goto yy186; yy748: YYDEBUG(748, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'W') goto yy755; if (yych == 'w') goto yy755; goto yy186; yy749: YYDEBUG(749, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy750; if (yych != 'h') goto yy186; yy750: YYDEBUG(750, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy751; if (yych != 'i') goto yy186; yy751: YYDEBUG(751, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy752; if (yych != 'l') goto yy186; yy752: YYDEBUG(752, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy753; if (yych != 'e') goto yy186; yy753: YYDEBUG(753, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(754, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1061 "Zend/zend_language_scanner.l" { return T_ENDWHILE; } #line 6926 "Zend/zend_language_scanner.c" yy755: YYDEBUG(755, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'I') goto yy756; if (yych != 'i') goto yy186; yy756: YYDEBUG(756, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy757; if (yych != 't') goto yy186; yy757: YYDEBUG(757, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy758; if (yych != 'c') goto yy186; yy758: YYDEBUG(758, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy759; if (yych != 'h') goto yy186; yy759: YYDEBUG(759, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(760, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1105 "Zend/zend_language_scanner.l" { return T_ENDSWITCH; } #line 6959 "Zend/zend_language_scanner.c" yy761: YYDEBUG(761, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(762, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1049 "Zend/zend_language_scanner.l" { return T_ENDIF; } #line 6972 "Zend/zend_language_scanner.c" yy763: YYDEBUG(763, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy764; if (yych != 'r') goto yy186; yy764: YYDEBUG(764, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '@') { if (yych <= '/') goto yy765; if (yych <= '9') goto yy185; } else { if (yych == 'E') goto yy766; if (yych <= 'Z') goto yy185; } } else { if (yych <= 'd') { if (yych != '`') goto yy185; } else { if (yych <= 'e') goto yy766; if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy765: YYDEBUG(765, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1073 "Zend/zend_language_scanner.l" { return T_ENDFOR; } #line 7005 "Zend/zend_language_scanner.c" yy766: YYDEBUG(766, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy767; if (yych != 'a') goto yy186; yy767: YYDEBUG(767, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy768; if (yych != 'c') goto yy186; yy768: YYDEBUG(768, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'H') goto yy769; if (yych != 'h') goto yy186; yy769: YYDEBUG(769, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(770, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1081 "Zend/zend_language_scanner.l" { return T_ENDFOREACH; } #line 7033 "Zend/zend_language_scanner.c" yy771: YYDEBUG(771, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'C') goto yy772; if (yych != 'c') goto yy186; yy772: YYDEBUG(772, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'L') goto yy773; if (yych != 'l') goto yy186; yy773: YYDEBUG(773, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'A') goto yy774; if (yych != 'a') goto yy186; yy774: YYDEBUG(774, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'R') goto yy775; if (yych != 'r') goto yy186; yy775: YYDEBUG(775, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy776; if (yych != 'e') goto yy186; yy776: YYDEBUG(776, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(777, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1089 "Zend/zend_language_scanner.l" { return T_ENDDECLARE; } #line 7071 "Zend/zend_language_scanner.c" yy778: YYDEBUG(778, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'T') goto yy779; if (yych != 't') goto yy186; yy779: YYDEBUG(779, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'Y') goto yy780; if (yych != 'y') goto yy186; yy780: YYDEBUG(780, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(781, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1275 "Zend/zend_language_scanner.l" { return T_EMPTY; } #line 7094 "Zend/zend_language_scanner.c" yy782: YYDEBUG(782, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'E') goto yy783; if (yych != 'e') goto yy186; yy783: YYDEBUG(783, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '^') { if (yych <= '@') { if (yych <= '/') goto yy784; if (yych <= '9') goto yy185; } else { if (yych == 'I') goto yy785; if (yych <= 'Z') goto yy185; } } else { if (yych <= 'h') { if (yych != '`') goto yy185; } else { if (yych <= 'i') goto yy785; if (yych <= 'z') goto yy185; if (yych >= 0x7F) goto yy185; } } yy784: YYDEBUG(784, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1053 "Zend/zend_language_scanner.l" { return T_ELSE; } #line 7127 "Zend/zend_language_scanner.c" yy785: YYDEBUG(785, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'F') goto yy786; if (yych != 'f') goto yy186; yy786: YYDEBUG(786, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(787, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1045 "Zend/zend_language_scanner.l" { return T_ELSEIF; } #line 7145 "Zend/zend_language_scanner.c" yy788: YYDEBUG(788, *YYCURSOR); yych = *++YYCURSOR; if (yych == 'O') goto yy789; if (yych != 'o') goto yy186; yy789: YYDEBUG(789, *YYCURSOR); ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 4) { goto yy185; } YYDEBUG(790, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1129 "Zend/zend_language_scanner.l" { return T_ECHO; } #line 7163 "Zend/zend_language_scanner.c" } /* *********************************** */ yyc_ST_LOOKING_FOR_PROPERTY: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 0, 0, 0, 0, 0, 0, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 0, 0, 0, 0, 64, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 0, 0, 0, 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, }; YYDEBUG(791, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych <= '-') { if (yych <= '\r') { if (yych <= 0x08) goto yy799; if (yych <= '\n') goto yy793; if (yych <= '\f') goto yy799; } else { if (yych == ' ') goto yy793; if (yych <= ',') goto yy799; goto yy795; } } else { if (yych <= '_') { if (yych <= '@') goto yy799; if (yych <= 'Z') goto yy797; if (yych <= '^') goto yy799; goto yy797; } else { if (yych <= '`') goto yy799; if (yych <= 'z') goto yy797; if (yych <= '~') goto yy799; goto yy797; } } yy793: YYDEBUG(793, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy805; yy794: YYDEBUG(794, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1162 "Zend/zend_language_scanner.l" { zendlval->value.str.val = yytext; /* no copying - intentional */ zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; HANDLE_NEWLINES(yytext, yyleng); return T_WHITESPACE; } #line 7244 "Zend/zend_language_scanner.c" yy795: YYDEBUG(795, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) == '>') goto yy802; yy796: YYDEBUG(796, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1181 "Zend/zend_language_scanner.l" { yyless(0); yy_pop_state(TSRMLS_C); goto restart; } #line 7258 "Zend/zend_language_scanner.c" yy797: YYDEBUG(797, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy801; yy798: YYDEBUG(798, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1174 "Zend/zend_language_scanner.l" { yy_pop_state(TSRMLS_C); zend_copy_value(zendlval, yytext, yyleng); zendlval->type = IS_STRING; return T_STRING; } #line 7274 "Zend/zend_language_scanner.c" yy799: YYDEBUG(799, *YYCURSOR); yych = *++YYCURSOR; goto yy796; yy800: YYDEBUG(800, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy801: YYDEBUG(801, *YYCURSOR); if (yybm[0+yych] & 64) { goto yy800; } goto yy798; yy802: YYDEBUG(802, *YYCURSOR); ++YYCURSOR; YYDEBUG(803, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1170 "Zend/zend_language_scanner.l" { return T_OBJECT_OPERATOR; } #line 7299 "Zend/zend_language_scanner.c" yy804: YYDEBUG(804, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy805: YYDEBUG(805, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy804; } goto yy794; } /* *********************************** */ yyc_ST_LOOKING_FOR_VARNAME: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; YYDEBUG(806, *YYCURSOR); YYFILL(2); yych = *YYCURSOR; if (yych <= '_') { if (yych <= '@') goto yy810; if (yych <= 'Z') goto yy808; if (yych <= '^') goto yy810; } else { if (yych <= '`') goto yy810; if (yych <= 'z') goto yy808; if (yych <= '~') goto yy810; } yy808: YYDEBUG(808, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy813; yy809: YYDEBUG(809, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1457 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, yytext, yyleng); zendlval->type = IS_STRING; yy_pop_state(TSRMLS_C); yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); return T_STRING_VARNAME; } #line 7377 "Zend/zend_language_scanner.c" yy810: YYDEBUG(810, *YYCURSOR); ++YYCURSOR; YYDEBUG(811, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1466 "Zend/zend_language_scanner.l" { yyless(0); yy_pop_state(TSRMLS_C); yy_push_state(ST_IN_SCRIPTING TSRMLS_CC); goto restart; } #line 7390 "Zend/zend_language_scanner.c" yy812: YYDEBUG(812, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy813: YYDEBUG(813, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy812; } goto yy809; } /* *********************************** */ yyc_ST_NOWDOC: YYDEBUG(814, *YYCURSOR); YYFILL(1); yych = *YYCURSOR; YYDEBUG(816, *YYCURSOR); ++YYCURSOR; YYDEBUG(817, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2348 "Zend/zend_language_scanner.l" { int newline = 0; if (YYCURSOR > YYLIMIT) { return 0; } YYCURSOR--; while (YYCURSOR < YYLIMIT) { switch (*YYCURSOR++) { case '\r': if (*YYCURSOR == '\n') { YYCURSOR++; } /* fall through */ case '\n': /* Check for ending label on the next line */ if (IS_LABEL_START(*YYCURSOR) && CG(heredoc_len) < YYLIMIT - YYCURSOR && !memcmp(YYCURSOR, CG(heredoc), CG(heredoc_len))) { YYCTYPE *end = YYCURSOR + CG(heredoc_len); if (*end == ';') { end++; } if (*end == '\n' || *end == '\r') { /* newline before label will be subtracted from returned text, but * yyleng/yytext will include it, for zend_highlight/strip, tokenizer, etc. */ if (YYCURSOR[-2] == '\r' && YYCURSOR[-1] == '\n') { newline = 2; /* Windows newline */ } else { newline = 1; } CG(increment_lineno) = 1; /* For newline before label */ BEGIN(ST_END_HEREDOC); goto nowdoc_scan_done; } } /* fall through */ default: continue; } } nowdoc_scan_done: yyleng = YYCURSOR - SCNG(yy_text); zend_copy_value(zendlval, yytext, yyleng - newline); zendlval->type = IS_STRING; HANDLE_NEWLINES(yytext, yyleng - newline); return T_ENCAPSED_AND_WHITESPACE; } #line 7467 "Zend/zend_language_scanner.c" /* *********************************** */ yyc_ST_VAR_OFFSET: { static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 240, 240, 112, 112, 112, 112, 112, 112, 112, 112, 0, 0, 0, 0, 0, 0, 0, 80, 80, 80, 80, 80, 80, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 16, 0, 80, 80, 80, 80, 80, 80, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, }; YYDEBUG(818, *YYCURSOR); YYFILL(3); yych = *YYCURSOR; if (yych <= '/') { if (yych <= ' ') { if (yych <= '\f') { if (yych <= 0x08) goto yy832; if (yych <= '\n') goto yy828; goto yy832; } else { if (yych <= '\r') goto yy828; if (yych <= 0x1F) goto yy832; goto yy828; } } else { if (yych <= '$') { if (yych <= '"') goto yy827; if (yych <= '#') goto yy828; goto yy823; } else { if (yych == '\'') goto yy828; goto yy827; } } } else { if (yych <= '\\') { if (yych <= '@') { if (yych <= '0') goto yy820; if (yych <= '9') goto yy822; goto yy827; } else { if (yych <= 'Z') goto yy830; if (yych <= '[') goto yy827; goto yy828; } } else { if (yych <= '_') { if (yych <= ']') goto yy825; if (yych <= '^') goto yy827; goto yy830; } else { if (yych <= '`') goto yy827; if (yych <= 'z') goto yy830; if (yych <= '~') goto yy827; goto yy830; } } } yy820: YYDEBUG(820, *YYCURSOR); yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 'W') { if (yych <= '9') { if (yych >= '0') goto yy844; } else { if (yych == 'B') goto yy841; } } else { if (yych <= 'b') { if (yych <= 'X') goto yy843; if (yych >= 'b') goto yy841; } else { if (yych == 'x') goto yy843; } } yy821: YYDEBUG(821, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1544 "Zend/zend_language_scanner.l" { /* Offset could be treated as a long */ if (yyleng < MAX_LENGTH_OF_LONG - 1 || (yyleng == MAX_LENGTH_OF_LONG - 1 && strcmp(yytext, long_min_digits) < 0)) { zendlval->value.lval = strtol(yytext, NULL, 10); zendlval->type = IS_LONG; } else { zendlval->value.str.val = (char *)estrndup(yytext, yyleng); zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; } return T_NUM_STRING; } #line 7586 "Zend/zend_language_scanner.c" yy822: YYDEBUG(822, *YYCURSOR); yych = *++YYCURSOR; goto yy840; yy823: YYDEBUG(823, *YYCURSOR); ++YYCURSOR; if ((yych = *YYCURSOR) <= '_') { if (yych <= '@') goto yy824; if (yych <= 'Z') goto yy836; if (yych >= '_') goto yy836; } else { if (yych <= '`') goto yy824; if (yych <= 'z') goto yy836; if (yych >= 0x7F) goto yy836; } yy824: YYDEBUG(824, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1876 "Zend/zend_language_scanner.l" { /* Only '[' can be valid, but returning other tokens will allow a more explicit parse error */ return yytext[0]; } #line 7611 "Zend/zend_language_scanner.c" yy825: YYDEBUG(825, *YYCURSOR); ++YYCURSOR; YYDEBUG(826, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1871 "Zend/zend_language_scanner.l" { yy_pop_state(TSRMLS_C); return ']'; } #line 7622 "Zend/zend_language_scanner.c" yy827: YYDEBUG(827, *YYCURSOR); yych = *++YYCURSOR; goto yy824; yy828: YYDEBUG(828, *YYCURSOR); ++YYCURSOR; YYDEBUG(829, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1881 "Zend/zend_language_scanner.l" { /* Invalid rule to return a more explicit parse error with proper line number */ yyless(0); yy_pop_state(TSRMLS_C); return T_ENCAPSED_AND_WHITESPACE; } #line 7639 "Zend/zend_language_scanner.c" yy830: YYDEBUG(830, *YYCURSOR); ++YYCURSOR; yych = *YYCURSOR; goto yy835; yy831: YYDEBUG(831, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1888 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, yytext, yyleng); zendlval->type = IS_STRING; return T_STRING; } #line 7654 "Zend/zend_language_scanner.c" yy832: YYDEBUG(832, *YYCURSOR); ++YYCURSOR; YYDEBUG(833, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 2404 "Zend/zend_language_scanner.l" { if (YYCURSOR > YYLIMIT) { return 0; } zend_error(E_COMPILE_WARNING,"Unexpected character in input: '%c' (ASCII=%d) state=%d", yytext[0], yytext[0], YYSTATE); goto restart; } #line 7669 "Zend/zend_language_scanner.c" yy834: YYDEBUG(834, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy835: YYDEBUG(835, *YYCURSOR); if (yybm[0+yych] & 16) { goto yy834; } goto yy831; yy836: YYDEBUG(836, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(837, *YYCURSOR); if (yych <= '^') { if (yych <= '9') { if (yych >= '0') goto yy836; } else { if (yych <= '@') goto yy838; if (yych <= 'Z') goto yy836; } } else { if (yych <= '`') { if (yych <= '_') goto yy836; } else { if (yych <= 'z') goto yy836; if (yych >= 0x7F) goto yy836; } } yy838: YYDEBUG(838, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1865 "Zend/zend_language_scanner.l" { zend_copy_value(zendlval, (yytext+1), (yyleng-1)); zendlval->type = IS_STRING; return T_VARIABLE; } #line 7711 "Zend/zend_language_scanner.c" yy839: YYDEBUG(839, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy840: YYDEBUG(840, *YYCURSOR); if (yybm[0+yych] & 32) { goto yy839; } goto yy821; yy841: YYDEBUG(841, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 128) { goto yy849; } yy842: YYDEBUG(842, *YYCURSOR); YYCURSOR = YYMARKER; goto yy821; yy843: YYDEBUG(843, *YYCURSOR); yych = *++YYCURSOR; if (yybm[0+yych] & 64) { goto yy847; } goto yy842; yy844: YYDEBUG(844, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(845, *YYCURSOR); if (yych <= '/') goto yy846; if (yych <= '9') goto yy844; yy846: YYDEBUG(846, *YYCURSOR); yyleng = YYCURSOR - SCNG(yy_text); #line 1556 "Zend/zend_language_scanner.l" { /* Offset must be treated as a string */ zendlval->value.str.val = (char *)estrndup(yytext, yyleng); zendlval->value.str.len = yyleng; zendlval->type = IS_STRING; return T_NUM_STRING; } #line 7758 "Zend/zend_language_scanner.c" yy847: YYDEBUG(847, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(848, *YYCURSOR); if (yybm[0+yych] & 64) { goto yy847; } goto yy846; yy849: YYDEBUG(849, *YYCURSOR); ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; YYDEBUG(850, *YYCURSOR); if (yybm[0+yych] & 128) { goto yy849; } goto yy846; } } #line 2413 "Zend/zend_language_scanner.l" }
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2012-03-02-730b54a374-1953161b8c.c
manybugs_data_85
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <zend_language_parser.h> #include "zend.h" #include "zend_compile.h" #include "zend_constants.h" #include "zend_llist.h" #include "zend_API.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "zend_multibyte.h" #include "zend_language_scanner.h" #define CONSTANT_EX(op_array, op) \ (op_array)->literals[op].constant #define CONSTANT(op) \ CONSTANT_EX(CG(active_op_array), op) #define SET_NODE(target, src) do { \ target ## _type = (src)->op_type; \ if ((src)->op_type == IS_CONST) { \ target.constant = zend_add_literal(CG(active_op_array), &(src)->u.constant TSRMLS_CC); \ } else { \ target = (src)->u.op; \ } \ } while (0) #define GET_NODE(target, src) do { \ (target)->op_type = src ## _type; \ if ((target)->op_type == IS_CONST) { \ (target)->u.constant = CONSTANT(src.constant); \ } else { \ (target)->u.op = src; \ (target)->EA = 0; \ } \ } while (0) #define COPY_NODE(target, src) do { \ target ## _type = src ## _type; \ target = src; \ } while (0) #define CALCULATE_LITERAL_HASH(num) do { \ if (IS_INTERNED(Z_STRVAL(CONSTANT(num)))) { \ Z_HASH_P(&CONSTANT(num)) = INTERNED_HASH(Z_STRVAL(CONSTANT(num))); \ } else { \ Z_HASH_P(&CONSTANT(num)) = zend_hash_func(Z_STRVAL(CONSTANT(num)), Z_STRLEN(CONSTANT(num))+1); \ } \ } while (0) #define GET_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot++; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ } \ } while (0) #define POLYMORPHIC_CACHE_SLOT_SIZE 2 #define GET_POLYMORPHIC_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot; \ CG(active_op_array)->last_cache_slot += POLYMORPHIC_CACHE_SLOT_SIZE; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 2] = NULL; \ } \ } while (0) #define FREE_POLYMORPHIC_CACHE_SLOT(literal) do { \ if (CG(active_op_array)->literals[literal].cache_slot == \ CG(active_op_array)->last_cache_slot - POLYMORPHIC_CACHE_SLOT_SIZE) { \ CG(active_op_array)->literals[literal].cache_slot = -1; \ CG(active_op_array)->last_cache_slot -= POLYMORPHIC_CACHE_SLOT_SIZE; \ } \ } while (0) ZEND_API zend_op_array *(*zend_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); ZEND_API zend_op_array *(*zend_compile_string)(zval *source_string, char *filename TSRMLS_DC); #ifndef ZTS ZEND_API zend_compiler_globals compiler_globals; ZEND_API zend_executor_globals executor_globals; #endif static void zend_duplicate_property_info(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = estrndup(property_info->name, property_info->name_length); } if (property_info->doc_comment) { property_info->doc_comment = estrndup(property_info->doc_comment, property_info->doc_comment_len); } } /* }}} */ static void zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = zend_strndup(property_info->name, property_info->name_length); } } /* }}} */ static void zend_destroy_property_info(zend_property_info *property_info) /* {{{ */ { str_efree(property_info->name); if (property_info->doc_comment) { efree((char*)property_info->doc_comment); } } /* }}} */ static void zend_destroy_property_info_internal(zend_property_info *property_info) /* {{{ */ { str_free((char*)property_info->name); } /* }}} */ static void build_runtime_defined_function_key(zval *result, const char *name, int name_length TSRMLS_DC) /* {{{ */ { char char_pos_buf[32]; uint char_pos_len; const char *filename; char_pos_len = zend_sprintf(char_pos_buf, "%p", LANG_SCNG(yy_text)); if (CG(active_op_array)->filename) { filename = CG(active_op_array)->filename; } else { filename = "-"; } /* NULL, name length, filename length, last accepting char position length */ result->value.str.len = 1+name_length+strlen(filename)+char_pos_len; /* must be binary safe */ result->value.str.val = (char *) safe_emalloc(result->value.str.len, 1, 1); result->value.str.val[0] = '\0'; sprintf(result->value.str.val+1, "%s%s%s", name, filename, char_pos_buf); result->type = IS_STRING; Z_SET_REFCOUNT_P(result, 1); } /* }}} */ static void init_compiler_declarables(TSRMLS_D) /* {{{ */ { Z_TYPE(CG(declarables).ticks) = IS_LONG; Z_LVAL(CG(declarables).ticks) = 0; } /* }}} */ void zend_init_compiler_context(TSRMLS_D) /* {{{ */ { CG(context).opcodes_size = (CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) ? INITIAL_INTERACTIVE_OP_ARRAY_SIZE : INITIAL_OP_ARRAY_SIZE; CG(context).vars_size = 0; CG(context).literals_size = 0; CG(context).current_brk_cont = -1; CG(context).backpatch_count = 0; CG(context).labels = NULL; } /* }}} */ void zend_init_compiler_data_structures(TSRMLS_D) /* {{{ */ { zend_stack_init(&CG(bp_stack)); zend_stack_init(&CG(function_call_stack)); zend_stack_init(&CG(switch_cond_stack)); zend_stack_init(&CG(foreach_copy_stack)); zend_stack_init(&CG(object_stack)); zend_stack_init(&CG(declare_stack)); CG(active_class_entry) = NULL; zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_stack_init(&CG(list_stack)); CG(in_compilation) = 0; CG(start_lineno) = 0; CG(current_namespace) = NULL; CG(in_namespace) = 0; CG(has_bracketed_namespaces) = 0; CG(current_import) = NULL; init_compiler_declarables(TSRMLS_C); zend_stack_init(&CG(context_stack)); CG(encoding_declared) = 0; } /* }}} */ ZEND_API void file_handle_dtor(zend_file_handle *fh) /* {{{ */ { TSRMLS_FETCH(); zend_file_handle_dtor(fh TSRMLS_CC); } /* }}} */ void init_compiler(TSRMLS_D) /* {{{ */ { CG(active_op_array) = NULL; zend_init_compiler_data_structures(TSRMLS_C); zend_init_rsrc_list(TSRMLS_C); zend_hash_init(&CG(filenames_table), 5, NULL, (dtor_func_t) free_estring, 0); zend_llist_init(&CG(open_files), sizeof(zend_file_handle), (void (*)(void *)) file_handle_dtor, 0); CG(unclean_shutdown) = 0; } /* }}} */ void shutdown_compiler(TSRMLS_D) /* {{{ */ { zend_stack_destroy(&CG(bp_stack)); zend_stack_destroy(&CG(function_call_stack)); zend_stack_destroy(&CG(switch_cond_stack)); zend_stack_destroy(&CG(foreach_copy_stack)); zend_stack_destroy(&CG(object_stack)); zend_stack_destroy(&CG(declare_stack)); zend_stack_destroy(&CG(list_stack)); zend_hash_destroy(&CG(filenames_table)); zend_llist_destroy(&CG(open_files)); zend_stack_destroy(&CG(context_stack)); } /* }}} */ ZEND_API char *zend_set_compiled_filename(const char *new_compiled_filename TSRMLS_DC) /* {{{ */ { char **pp, *p; int length = strlen(new_compiled_filename); if (zend_hash_find(&CG(filenames_table), new_compiled_filename, length+1, (void **) &pp) == SUCCESS) { CG(compiled_filename) = *pp; return *pp; } p = estrndup(new_compiled_filename, length); zend_hash_update(&CG(filenames_table), new_compiled_filename, length+1, &p, sizeof(char *), (void **) &pp); CG(compiled_filename) = p; return p; } /* }}} */ ZEND_API void zend_restore_compiled_filename(char *original_compiled_filename TSRMLS_DC) /* {{{ */ { CG(compiled_filename) = original_compiled_filename; } /* }}} */ ZEND_API char *zend_get_compiled_filename(TSRMLS_D) /* {{{ */ { return CG(compiled_filename); } /* }}} */ ZEND_API int zend_get_compiled_lineno(TSRMLS_D) /* {{{ */ { return CG(zend_lineno); } /* }}} */ ZEND_API zend_bool zend_is_compiling(TSRMLS_D) /* {{{ */ { return CG(in_compilation); } /* }}} */ static zend_uint get_temporary_variable(zend_op_array *op_array) /* {{{ */ { return (op_array->T)++ * ZEND_MM_ALIGNED_SIZE(sizeof(temp_variable)); } /* }}} */ static int lookup_cv(zend_op_array *op_array, char* name, int name_len, ulong hash TSRMLS_DC) /* {{{ */ { int i = 0; ulong hash_value = hash ? hash : zend_inline_hash_func(name, name_len+1); while (i < op_array->last_var) { if (op_array->vars[i].name == name || (op_array->vars[i].hash_value == hash_value && op_array->vars[i].name_len == name_len && memcmp(op_array->vars[i].name, name, name_len) == 0)) { str_efree(name); return i; } i++; } i = op_array->last_var; op_array->last_var++; if (op_array->last_var > CG(context).vars_size) { CG(context).vars_size += 16; /* FIXME */ op_array->vars = erealloc(op_array->vars, CG(context).vars_size * sizeof(zend_compiled_variable)); } op_array->vars[i].name = zend_new_interned_string(name, name_len + 1, 1 TSRMLS_CC); op_array->vars[i].name_len = name_len; op_array->vars[i].hash_value = hash_value; return i; } /* }}} */ void zend_del_literal(zend_op_array *op_array, int n) /* {{{ */ { zval_dtor(&CONSTANT_EX(op_array, n)); if (n + 1 == op_array->last_literal) { op_array->last_literal--; } else { Z_TYPE(CONSTANT_EX(op_array, n)) = IS_NULL; } } /* }}} */ /* Common part of zend_add_literal and zend_append_individual_literal */ static inline void zend_insert_literal(zend_op_array *op_array, const zval *zv, int literal_position TSRMLS_DC) /* {{{ */ { if (Z_TYPE_P(zv) == IS_STRING || Z_TYPE_P(zv) == IS_CONSTANT) { zval *z = (zval*)zv; Z_STRVAL_P(z) = (char*)zend_new_interned_string(Z_STRVAL_P(zv), Z_STRLEN_P(zv) + 1, 1 TSRMLS_CC); } CONSTANT_EX(op_array, literal_position) = *zv; Z_SET_REFCOUNT(CONSTANT_EX(op_array, literal_position), 2); Z_SET_ISREF(CONSTANT_EX(op_array, literal_position)); op_array->literals[literal_position].hash_value = 0; op_array->literals[literal_position].cache_slot = -1; } /* }}} */ /* Is used while compiling a function, using the context to keep track of an approximate size to avoid to relocate to often. Literals are truncated to actual size in the second compiler pass (pass_two()). */ int zend_add_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; if (i >= CG(context).literals_size) { while (i >= CG(context).literals_size) { CG(context).literals_size += 16; /* FIXME */ } op_array->literals = (zend_literal*)erealloc(op_array->literals, CG(context).literals_size * sizeof(zend_literal)); } zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ /* Is used after normal compilation to append an additional literal. Allocation is done precisely here. */ int zend_append_individual_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; op_array->literals = (zend_literal*)erealloc(op_array->literals, (i + 1) * sizeof(zend_literal)); zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ int zend_add_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_ns_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; const char *ns_separator; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); ns_separator = (const char*)zend_memrchr(Z_STRVAL_P(zv), '\\', Z_STRLEN_P(zv)) + 1; lc_len = Z_STRLEN_P(zv) - (ns_separator - Z_STRVAL_P(zv)); lc_name = zend_str_tolower_dup(ns_separator, lc_len); ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_class_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } if (Z_STRVAL_P(zv)[0] == '\\') { lc_len = Z_STRLEN_P(zv) - 1; lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv) + 1, lc_len); } else { lc_len = Z_STRLEN_P(zv); lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), lc_len); } ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); GET_CACHE_SLOT(ret); return ret; } /* }}} */ int zend_add_const_name_literal(zend_op_array *op_array, const zval *zv, int unqualified TSRMLS_DC) /* {{{ */ { int ret, tmp_literal; char *name, *tmp_name; const char *ns_separator; int name_len, ns_len; zval c; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } /* skip leading '\\' */ if (Z_STRVAL_P(zv)[0] == '\\') { name_len = Z_STRLEN_P(zv) - 1; name = Z_STRVAL_P(zv) + 1; } else { name_len = Z_STRLEN_P(zv); name = Z_STRVAL_P(zv); } ns_separator = zend_memrchr(name, '\\', name_len); if (ns_separator) { ns_len = ns_separator - name; } else { ns_len = 0; } if (ns_len) { /* lowercased namespace name & original constant name */ tmp_name = estrndup(name, name_len); zend_str_tolower(tmp_name, ns_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased namespace name & lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); } if (ns_len) { if (!unqualified) { return ret; } ns_len++; name += ns_len; name_len -= ns_len; } /* original constant name */ tmp_name = estrndup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); return ret; } /* }}} */ #define LITERAL_STRINGL(op, str, len, copy) do { \ zval _c; \ ZVAL_STRINGL(&_c, str, len, copy); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG(op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG_EX(op_array, op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(op_array, &_c TSRMLS_CC); \ } while (0) #define LITERAL_NULL(op) do { \ zval _c; \ INIT_ZVAL( _c); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) static inline zend_bool zend_is_function_or_method_call(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; return ((type & ZEND_PARSED_METHOD_CALL) || (type == ZEND_PARSED_FUNCTION_CALL)); } /* }}} */ void zend_do_binary_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_unary_op(zend_uchar op, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); GET_NODE(result, opline->result); SET_UNUSED(opline->op2); } /* }}} */ #define MAKE_NOP(opline) { opline->opcode = ZEND_NOP; memset(&opline->result,0,sizeof(opline->result)); memset(&opline->op1,0,sizeof(opline->op1)); memset(&opline->op2,0,sizeof(opline->op2)); opline->result_type=opline->op1_type=opline->op2_type=IS_UNUSED; } static void zend_do_op_data(zend_op *data_op, const znode *value TSRMLS_DC) /* {{{ */ { data_op->opcode = ZEND_OP_DATA; SET_NODE(data_op->op1, value); SET_UNUSED(data_op->op2); } /* }}} */ void zend_do_binary_assign_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; switch (last_op->opcode) { case ZEND_FETCH_OBJ_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, op2 TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; case ZEND_FETCH_DIM_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_DIM; zend_do_op_data(opline, op2 TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result,last_op->result); return; default: break; } } opline->opcode = op; SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void fetch_simple_variable_ex(znode *result, znode *varname, int bp, zend_uchar op TSRMLS_DC) /* {{{ */ { zend_op opline; zend_op *opline_ptr; zend_llist *fetch_list_ptr; if (varname->op_type == IS_CONST) { ulong hash = 0; if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } else if (IS_INTERNED(Z_STRVAL(varname->u.constant))) { hash = INTERNED_HASH(Z_STRVAL(varname->u.constant)); } if (!zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC) && !(varname->u.constant.value.str.len == (sizeof("this")-1) && !memcmp(varname->u.constant.value.str.val, "this", sizeof("this"))) && (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE)) { result->op_type = IS_CV; result->u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC); varname->u.constant.value.str.val = (char*)CG(active_op_array)->vars[result->u.op.var].name; result->EA = 0; return; } } if (bp) { opline_ptr = &opline; init_op(opline_ptr TSRMLS_CC); } else { opline_ptr = get_next_op(CG(active_op_array) TSRMLS_CC); } opline_ptr->opcode = op; opline_ptr->result_type = IS_VAR; opline_ptr->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline_ptr->op1, varname); GET_NODE(result, opline_ptr->result); SET_UNUSED(opline_ptr->op2); opline_ptr->extended_value = ZEND_FETCH_LOCAL; if (varname->op_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline_ptr->op1.constant); if (zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC)) { opline_ptr->extended_value = ZEND_FETCH_GLOBAL; } } if (bp) { zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); zend_llist_add_element(fetch_list_ptr, opline_ptr); } } /* }}} */ void fetch_simple_variable(znode *result, znode *varname, int bp TSRMLS_DC) /* {{{ */ { /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ fetch_simple_variable_ex(result, varname, bp, ZEND_FETCH_W TSRMLS_CC); } /* }}} */ void zend_do_fetch_static_member(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { znode class_node; zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline_ptr; zend_op opline; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); } zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (result->op_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[result->u.op.var].name), CG(active_op_array)->vars[result->u.op.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } GET_NODE(result,opline.result); opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; opline_ptr = &opline; zend_llist_add_element(fetch_list_ptr, &opline); } else { le = fetch_list_ptr->head; opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode != ZEND_FETCH_W && opline_ptr->op1_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[opline_ptr->op1.var].name), CG(active_op_array)->vars[opline_ptr->op1.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; COPY_NODE(opline_ptr->op1, opline.result); zend_llist_prepend_element(fetch_list_ptr, &opline); } else { if (opline_ptr->op1_type == IS_CONST) { GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op1.constant); } if (class_node.op_type == IS_CONST) { opline_ptr->op2_type = IS_CONST; opline_ptr->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline_ptr->op2, &class_node); } opline_ptr->extended_value |= ZEND_FETCH_STATIC_MEMBER; } } } /* }}} */ void fetch_array_begin(znode *result, znode *varname, znode *first_dim TSRMLS_DC) /* {{{ */ { fetch_simple_variable(result, varname, 1 TSRMLS_CC); fetch_array_dim(result, result, first_dim TSRMLS_CC); } /* }}} */ void fetch_array_dim(znode *result, const znode *parent, const znode *dim TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (zend_is_function_or_method_call(parent)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, parent); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_DIM_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, parent); SET_NODE(opline.op2, dim); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline.op2.constant)), Z_STRLEN(CONSTANT(opline.op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline.op2.constant)); ZVAL_LONG(&CONSTANT(opline.op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline.op2.constant); } } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void fetch_string_offset(znode *result, const znode *parent, const znode *offset TSRMLS_DC) /* {{{ */ { fetch_array_dim(result, parent, offset TSRMLS_CC); } /* }}} */ void zend_do_print(znode *result, const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->opcode = ZEND_PRINT; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_echo(const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ECHO; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_abstract_method(const znode *function_name, znode *modifiers, const znode *body TSRMLS_DC) /* {{{ */ { char *method_type; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { Z_LVAL(modifiers->u.constant) |= ZEND_ACC_ABSTRACT; method_type = "Interface"; } else { method_type = "Abstract"; } if (modifiers->u.constant.value.lval & ZEND_ACC_ABSTRACT) { if(modifiers->u.constant.value.lval & ZEND_ACC_PRIVATE) { zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot be declared private", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } if (Z_LVAL(body->u.constant) == ZEND_ACC_ABSTRACT) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_RAISE_ABSTRACT_ERROR; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } else { /* we had code in the function body */ zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot contain body", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } else { if (body->u.constant.value.lval == ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Non-abstract method %s::%s() must contain body", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } } /* }}} */ static zend_bool opline_is_fetch_this(const zend_op *opline TSRMLS_DC) /* {{{ */ { if ((opline->opcode == ZEND_FETCH_W) && (opline->op1_type == IS_CONST) && (Z_TYPE(CONSTANT(opline->op1.constant)) == IS_STRING) && (Z_HASH_P(&CONSTANT(opline->op1.constant)) == THIS_HASHVAL) && (Z_STRLEN(CONSTANT(opline->op1.constant)) == (sizeof("this")-1)) && !memcmp(Z_STRVAL(CONSTANT(opline->op1.constant)), "this", sizeof("this"))) { return 1; } else { return 0; } } /* }}} */ void zend_do_assign(znode *result, znode *variable, znode *value TSRMLS_DC) /* {{{ */ { int last_op_number; zend_op *opline; if (value->op_type == IS_CV) { zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (fetch_list_ptr && fetch_list_ptr->head) { opline = (zend_op *)fetch_list_ptr->head->data; if (opline->opcode == ZEND_FETCH_DIM_W && opline->op1_type == IS_CV && opline->op1.var == value->u.op.var) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_R; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->op1_type = IS_CONST; LITERAL_STRINGL(opline->op1, CG(active_op_array)->vars[value->u.op.var].name, CG(active_op_array)->vars[value->u.op.var].name_len, 1); CALCULATE_LITERAL_HASH(opline->op1.constant); SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_LOCAL; GET_NODE(value, opline->result); } } } zend_do_end_variable_parse(variable, BP_VAR_W, 0 TSRMLS_CC); last_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (variable->op_type == IS_CV) { if (variable->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (variable->op_type == IS_VAR) { int n = 0; while (last_op_number - n > 0) { zend_op *last_op; last_op = &CG(active_op_array)->opcodes[last_op_number-n-1]; if (last_op->result_type == IS_VAR && last_op->result.var == variable->u.op.var) { if (last_op->opcode == ZEND_FETCH_OBJ_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, value TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (last_op->opcode == ZEND_FETCH_DIM_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ /* TBFixed: this can realloc opcodes, leaving last_op pointing wrong */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_DIM; zend_do_op_data(opline, value TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (opline_is_fetch_this(last_op TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } else { break; } } n++; } } opline->opcode = ZEND_ASSIGN; SET_NODE(opline->op1, variable); SET_NODE(opline->op2, value); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_assign_ref(znode *result, const znode *lvar, const znode *rvar TSRMLS_DC) /* {{{ */ { zend_op *opline; if (lvar->op_type == IS_CV) { if (lvar->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (lvar->op_type == IS_VAR) { int last_op_number = get_next_op_number(CG(active_op_array)); if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline_is_fetch_this(opline TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ASSIGN_REF; if (zend_is_function_or_method_call(rvar)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } else if (rvar->EA & ZEND_PARSED_NEW) { opline->extended_value = ZEND_RETURNS_NEW; } else { opline->extended_value = 0; } if (result) { opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } else { opline->result_type = IS_UNUSED | EXT_TYPE_UNUSED; } SET_NODE(opline->op1, lvar); SET_NODE(opline->op2, rvar); } /* }}} */ static inline void do_begin_loop(TSRMLS_D) /* {{{ */ { zend_brk_cont_element *brk_cont_element; int parent; parent = CG(context).current_brk_cont; CG(context).current_brk_cont = CG(active_op_array)->last_brk_cont; brk_cont_element = get_next_brk_cont_element(CG(active_op_array)); brk_cont_element->start = get_next_op_number(CG(active_op_array)); brk_cont_element->parent = parent; } /* }}} */ static inline void do_end_loop(int cont_addr, int has_loop_var TSRMLS_DC) /* {{{ */ { if (!has_loop_var) { /* The start fileld is used to free temporary variables in case of exceptions. * We won't try to free something of we don't have loop variable. */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].start = -1; } CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = cont_addr; CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; } /* }}} */ void zend_do_while_cond(const znode *expr, znode *close_bracket_token TSRMLS_DC) /* {{{ */ { int while_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, expr); close_bracket_token->u.op.opline_num = while_cond_op_number; SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_while_end(const znode *while_token, const znode *close_bracket_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* add unconditional jump */ opline->opcode = ZEND_JMP; opline->op1.opline_num = while_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* update while's conditional jmp */ CG(active_op_array)->opcodes[close_bracket_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); do_end_loop(while_token->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_cond(const znode *expr, znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { int for_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZNZ; SET_NODE(opline->op1, expr); /* the conditional expression */ second_semicolon_token->u.op.opline_num = for_cond_op_number; SET_UNUSED(opline->op2); } /* }}} */ void zend_do_for_before_statement(const znode *cond_start, const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = cond_start->u.op.opline_num; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_end(const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = second_semicolon_token->u.op.opline_num+1; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_end_loop(second_semicolon_token->u.op.opline_num+1, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_pre_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_PRE_INC)?ZEND_PRE_INC_OBJ:ZEND_PRE_DEC_OBJ; last_op->result_type = IS_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_post_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_POST_INC)?ZEND_POST_INC_OBJ:ZEND_POST_DEC_OBJ; last_op->result_type = IS_TMP_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_if_cond(const znode *cond, znode *closing_bracket_token TSRMLS_DC) /* {{{ */ { int if_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); closing_bracket_token->u.op.opline_num = if_cond_op_number; SET_UNUSED(opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_if_after_statement(const znode *closing_bracket_token, unsigned char initialize TSRMLS_DC) /* {{{ */ { int if_end_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; /* save for backpatching */ if (initialize) { zend_llist jmp_list; zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); } zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &if_end_op_number); CG(active_op_array)->opcodes[closing_bracket_token->u.op.opline_num].op2.opline_num = if_end_op_number+1; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_if_end(TSRMLS_D) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_llist *jmp_list_ptr; zend_llist_element *le; zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); for (le=jmp_list_ptr->head; le; le = le->next) { CG(active_op_array)->opcodes[*((int *) le->data)].op1.opline_num = next_op_number; } zend_llist_destroy(jmp_list_ptr); zend_stack_del_top(&CG(bp_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_check_writable_variable(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; if (type & ZEND_PARSED_METHOD_CALL) { zend_error(E_COMPILE_ERROR, "Can't use method return value in write context"); } if (type == ZEND_PARSED_FUNCTION_CALL) { zend_error(E_COMPILE_ERROR, "Can't use function return value in write context"); } } /* }}} */ void zend_do_begin_variable_parse(TSRMLS_D) /* {{{ */ { zend_llist fetch_list; zend_llist_init(&fetch_list, sizeof(zend_op), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &fetch_list, sizeof(zend_llist)); } /* }}} */ void zend_do_end_variable_parse(znode *variable, int type, int arg_offset TSRMLS_DC) /* {{{ */ { zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline = NULL; zend_op *opline_ptr; zend_uint this_var = -1; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); le = fetch_list_ptr->head; /* TODO: $foo->x->y->z = 1 should fetch "x" and "y" for R or RW, not just W */ if (le) { opline_ptr = (zend_op *)le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { /* convert to FETCH_?(this) into IS_CV */ if (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE) { this_var = opline_ptr->result.var; if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), Z_STRVAL(CONSTANT(opline_ptr->op1.constant)), Z_STRLEN(CONSTANT(opline_ptr->op1.constant)), Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC); Z_TYPE(CONSTANT(opline_ptr->op1.constant)) = IS_NULL; } else { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); } le = le->next; if (variable->op_type == IS_VAR && variable->u.op.var == this_var) { variable->op_type = IS_CV; variable->u.op.var = CG(active_op_array)->this_var; } } else if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } while (le) { opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode == ZEND_SEPARATE) { if (type != BP_VAR_R && type != BP_VAR_IS) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); } le = le->next; continue; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); if (opline->op1_type == IS_VAR && opline->op1.var == this_var) { opline->op1_type = IS_CV; opline->op1.var = CG(active_op_array)->this_var; } switch (type) { case BP_VAR_R: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode -= 3; break; case BP_VAR_W: break; case BP_VAR_RW: opline->opcode += 3; break; case BP_VAR_IS: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode += 6; /* 3+3 */ break; case BP_VAR_FUNC_ARG: opline->opcode += 9; /* 3+3+3 */ opline->extended_value |= arg_offset; break; case BP_VAR_UNSET: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for unsetting"); } opline->opcode += 12; /* 3+3+3+3 */ break; } le = le->next; } if (opline && type == BP_VAR_W && arg_offset) { opline->extended_value |= ZEND_FETCH_MAKE_REF; } } zend_llist_destroy(fetch_list_ptr); zend_stack_del_top(&CG(bp_stack)); } /* }}} */ void zend_do_add_string(znode *result, const znode *op1, znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline; if (Z_STRLEN(op2->u.constant) > 1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_STRING; } else if (Z_STRLEN(op2->u.constant) == 1) { int ch = *Z_STRVAL(op2->u.constant); /* Free memory and use ZEND_ADD_CHAR in case of 1 character strings */ efree(Z_STRVAL(op2->u.constant)); ZVAL_LONG(&op2->u.constant, ch); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_CHAR; } else { /* String can be empty after a variable at the end of a heredoc */ efree(Z_STRVAL(op2->u.constant)); return; } if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_add_variable(znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_VAR; if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_free(znode *op1 TSRMLS_DC) /* {{{ */ { if (op1->op_type==IS_TMP_VAR) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else if (op1->op_type==IS_VAR) { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; while (opline->opcode == ZEND_END_SILENCE || opline->opcode == ZEND_EXT_FCALL_END || opline->opcode == ZEND_OP_DATA) { opline--; } if (opline->result_type == IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_FETCH_R || opline->opcode == ZEND_FETCH_DIM_R || opline->opcode == ZEND_FETCH_OBJ_R) { /* It's very rare and useless case. It's better to use additional FREE opcode and simplify the FETCH handlers their selves */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else { opline->result_type |= EXT_TYPE_UNUSED; } } else { while (opline>CG(active_op_array)->opcodes) { if (opline->opcode == ZEND_FETCH_DIM_R && opline->op1_type == IS_VAR && opline->op1.var == op1->u.op.var) { /* This should the end of a list() construct * Mark its result as unused */ opline->extended_value = ZEND_FETCH_STANDARD; break; } else if (opline->result_type==IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_NEW) { opline->result_type |= EXT_TYPE_UNUSED; } break; } opline--; } } } else if (op1->op_type == IS_CONST) { zval_dtor(&op1->u.constant); } } /* }}} */ int zend_do_verify_access_types(const znode *current_access_type, const znode *new_modifier) /* {{{ */ { if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_PPP_MASK) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Multiple access type modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_ABSTRACT) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Multiple abstract modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_STATIC) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Multiple static modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_FINAL) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Multiple final modifiers are not allowed"); } if (((Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)) & (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) == (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Cannot use the final modifier on an abstract class member"); } return (Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)); } /* }}} */ void zend_do_begin_function_declaration(znode *function_token, znode *function_name, int is_method, int return_reference, znode *fn_flags_znode TSRMLS_DC) /* {{{ */ { zend_op_array op_array; char *name = function_name->u.constant.value.str.val; int name_len = function_name->u.constant.value.str.len; int function_begin_line = function_token->u.op.opline_num; zend_uint fn_flags; const char *lcname; zend_bool orig_interactive; ALLOCA_FLAG(use_heap) if (is_method) { if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((Z_LVAL(fn_flags_znode->u.constant) & ~(ZEND_ACC_STATIC|ZEND_ACC_PUBLIC))) { zend_error(E_COMPILE_ERROR, "Access type for interface method %s::%s() must be omitted", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } Z_LVAL(fn_flags_znode->u.constant) |= ZEND_ACC_ABSTRACT; /* propagates to the rest of the parser */ } fn_flags = Z_LVAL(fn_flags_znode->u.constant); /* must be done *after* the above check */ } else { fn_flags = 0; } if ((fn_flags & ZEND_ACC_STATIC) && (fn_flags & ZEND_ACC_ABSTRACT) && !(CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_STRICT, "Static function %s%s%s() should not be abstract", is_method ? CG(active_class_entry)->name : "", is_method ? "::" : "", Z_STRVAL(function_name->u.constant)); } function_token->u.op_array = CG(active_op_array); orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(&op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; op_array.function_name = name; if (return_reference) { op_array.fn_flags |= ZEND_ACC_RETURN_REFERENCE; } op_array.fn_flags |= fn_flags; op_array.scope = is_method?CG(active_class_entry):NULL; op_array.prototype = NULL; op_array.line_start = zend_get_compiled_lineno(TSRMLS_C); if (is_method) { int result; lcname = zend_new_interned_string(zend_str_tolower_dup(name, name_len), name_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lcname)) { result = zend_hash_quick_add(&CG(active_class_entry)->function_table, lcname, name_len+1, INTERNED_HASH(lcname), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } else { result = zend_hash_add(&CG(active_class_entry)->function_table, lcname, name_len+1, &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } if (result == FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::%s()", CG(active_class_entry)->name, name); } zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); if (fn_flags & ZEND_ACC_ABSTRACT) { CG(active_class_entry)->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (!(fn_flags & ZEND_ACC_PPP_MASK)) { fn_flags |= ZEND_ACC_PUBLIC; } if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } } } else { char *class_lcname; class_lcname = do_alloca(CG(active_class_entry)->name_length + 1, use_heap); zend_str_tolower_copy(class_lcname, CG(active_class_entry)->name, CG(active_class_entry)->name_length); /* Improve after RC: cache the lowercase class name */ if ((CG(active_class_entry)->name_length == name_len) && ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT) && (!memcmp(class_lcname, lcname, name_len))) { if (!CG(active_class_entry)->constructor) { CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } } else if ((name_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)))) { if (CG(active_class_entry)->constructor) { zend_error(E_STRICT, "Redefining already defined constructor for class %s", CG(active_class_entry)->name); } CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1))) { CG(active_class_entry)->destructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1))) { CG(active_class_entry)->clone = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } CG(active_class_entry)->__call = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } CG(active_class_entry)->__callstatic = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } CG(active_class_entry)->__get = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } CG(active_class_entry)->__set = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } CG(active_class_entry)->__unset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } CG(active_class_entry)->__isset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } CG(active_class_entry)->__tostring = (zend_function *) CG(active_op_array); } else if (!(fn_flags & ZEND_ACC_STATIC)) { CG(active_op_array)->fn_flags |= ZEND_ACC_ALLOW_STATIC; } free_alloca(class_lcname, use_heap); } str_efree(lcname); } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zval key; if (CG(current_namespace)) { /* Prefix function name with current namespcae name */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, function_name TSRMLS_CC); op_array.function_name = Z_STRVAL(tmp.u.constant); name_len = Z_STRLEN(tmp.u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), name_len); } else { lcname = zend_str_tolower_dup(name, name_len); } opline->opcode = ZEND_DECLARE_FUNCTION; opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, name_len TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; LITERAL_STRINGL(opline->op2, lcname, name_len, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); opline->extended_value = ZEND_DECLARE_FUNCTION; zend_hash_quick_update(CG(function_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); } if (CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_NOP; opline->lineno = function_begin_line; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } { /* Push a seperator to the switch and foreach stacks */ zend_switch_entry switch_entry; switch_entry.cond.op_type = IS_UNUSED; switch_entry.default_case = 0; switch_entry.control_var = 0; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); { /* Foreach stack separator */ zend_op dummy_opline; dummy_opline.result_type = IS_UNUSED; dummy_opline.op1_type = IS_UNUSED; zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); } } if (CG(doc_comment)) { CG(active_op_array)->doc_comment = CG(doc_comment); CG(active_op_array)->doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_begin_lambda_function_declaration(znode *result, znode *function_token, int return_reference, int is_static TSRMLS_DC) /* {{{ */ { znode function_name; zend_op_array *current_op_array = CG(active_op_array); int current_op_number = get_next_op_number(CG(active_op_array)); zend_op *current_op; function_name.op_type = IS_CONST; ZVAL_STRINGL(&function_name.u.constant, "{closure}", sizeof("{closure}")-1, 1); zend_do_begin_function_declaration(function_token, &function_name, 0, return_reference, NULL TSRMLS_CC); result->op_type = IS_TMP_VAR; result->u.op.var = get_temporary_variable(current_op_array); current_op = &current_op_array->opcodes[current_op_number]; current_op->opcode = ZEND_DECLARE_LAMBDA_FUNCTION; zend_del_literal(current_op_array, current_op->op2.constant); SET_UNUSED(current_op->op2); SET_NODE(current_op->result, result); if (is_static) { CG(active_op_array)->fn_flags |= ZEND_ACC_STATIC; } CG(active_op_array)->fn_flags |= ZEND_ACC_CLOSURE; } /* }}} */ void zend_do_handle_exception(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_HANDLE_EXCEPTION; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_function_declaration(const znode *function_token TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; zend_do_extended_info(TSRMLS_C); zend_do_return(NULL, 0 TSRMLS_CC); pass_two(CG(active_op_array) TSRMLS_CC); zend_release_labels(TSRMLS_C); if (CG(active_class_entry)) { zend_check_magic_method_implementation(CG(active_class_entry), (zend_function*)CG(active_op_array), E_COMPILE_ERROR TSRMLS_CC); } else { /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(CG(active_op_array)->function_name); zend_str_tolower_copy(lcname, CG(active_op_array)->function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME)) && CG(active_op_array)->num_args != 1) { zend_error(E_COMPILE_ERROR, "%s() must take exactly 1 argument", ZEND_AUTOLOAD_FUNC_NAME); } } CG(active_op_array)->line_end = zend_get_compiled_lineno(TSRMLS_C); CG(active_op_array) = function_token->u.op_array; /* Pop the switch and foreach seperators */ zend_stack_del_top(&CG(switch_cond_stack)); zend_stack_del_top(&CG(foreach_copy_stack)); } /* }}} */ void zend_do_receive_arg(zend_uchar op, znode *varname, const znode *offset, const znode *initialization, znode *class_type, zend_uchar pass_by_reference TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_arg_info *cur_arg_info; znode var; if (class_type->op_type == IS_CONST && Z_TYPE(class_type->u.constant) == IS_STRING && Z_STRLEN(class_type->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_type->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } if (zend_is_auto_global_quick(Z_STRVAL(varname->u.constant), Z_STRLEN(varname->u.constant), 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign auto-global variable %s", Z_STRVAL(varname->u.constant)); } else { var.op_type = IS_CV; var.u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(varname->u.constant) = (char*)CG(active_op_array)->vars[var.u.op.var].name; var.EA = 0; if (CG(active_op_array)->vars[var.u.op.var].hash_value == THIS_HASHVAL && Z_STRLEN(varname->u.constant) == sizeof("this")-1 && !memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this")-1)) { if (CG(active_op_array)->scope && (CG(active_op_array)->fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } CG(active_op_array)->this_var = var.u.op.var; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->num_args++; opline->opcode = op; SET_NODE(opline->result, &var); SET_NODE(opline->op1, offset); if (op == ZEND_RECV_INIT) { SET_NODE(opline->op2, initialization); } else { CG(active_op_array)->required_num_args = CG(active_op_array)->num_args; SET_UNUSED(opline->op2); } CG(active_op_array)->arg_info = erealloc(CG(active_op_array)->arg_info, sizeof(zend_arg_info)*(CG(active_op_array)->num_args)); cur_arg_info = &CG(active_op_array)->arg_info[CG(active_op_array)->num_args-1]; cur_arg_info->name = zend_new_interned_string(estrndup(varname->u.constant.value.str.val, varname->u.constant.value.str.len), varname->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->name_len = varname->u.constant.value.str.len; cur_arg_info->type_hint = 0; cur_arg_info->allow_null = 1; cur_arg_info->pass_by_reference = pass_by_reference; cur_arg_info->class_name = NULL; cur_arg_info->class_name_len = 0; if (class_type->op_type != IS_UNUSED) { cur_arg_info->allow_null = 0; if (class_type->u.constant.type != IS_NULL) { if (class_type->u.constant.type == IS_ARRAY) { cur_arg_info->type_hint = IS_ARRAY; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else if (Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Default value for parameters with array type hint can only be an array or NULL"); } } } else if (class_type->u.constant.type == IS_CALLABLE) { cur_arg_info->type_hint = IS_CALLABLE; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with callable type hint can only be NULL"); } } } else { cur_arg_info->type_hint = IS_OBJECT; if (ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_type->u.constant), Z_STRLEN(class_type->u.constant))) { zend_resolve_class_name(class_type, opline->extended_value, 1 TSRMLS_CC); } Z_STRVAL(class_type->u.constant) = (char*)zend_new_interned_string(class_type->u.constant.value.str.val, class_type->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->class_name = class_type->u.constant.value.str.val; cur_arg_info->class_name_len = class_type->u.constant.value.str.len; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with a class type hint can only be NULL"); } } } } } } /* }}} */ int zend_do_begin_function_call(znode *function_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { zend_function *function; char *lcname; char *is_compound = memchr(Z_STRVAL(function_name->u.constant), '\\', Z_STRLEN(function_name->u.constant)); zend_resolve_non_class_name(function_name, check_namespace TSRMLS_CC); if (check_namespace && CG(current_namespace) && !is_compound) { /* We assume we call function from the current namespace if it is not prefixed. */ /* In run-time PHP will check for function with full name and internal function with short name */ zend_do_begin_dynamic_function_call(function_name, 1 TSRMLS_CC); return 1; } lcname = zend_str_tolower_dup(function_name->u.constant.value.str.val, function_name->u.constant.value.str.len); if ((zend_hash_find(CG(function_table), lcname, function_name->u.constant.value.str.len+1, (void **) &function)==FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_FUNCTIONS) && (function->type == ZEND_INTERNAL_FUNCTION))) { zend_do_begin_dynamic_function_call(function_name, 0 TSRMLS_CC); efree(lcname); return 1; /* Dynamic */ } efree(function_name->u.constant.value.str.val); function_name->u.constant.value.str.val = lcname; zend_stack_push(&CG(function_call_stack), (void *) &function, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 0; } /* }}} */ void zend_do_begin_method_call(znode *left_bracket TSRMLS_DC) /* {{{ */ { zend_op *last_op; int last_op_number; unsigned char *ptr = NULL; zend_do_end_variable_parse(left_bracket, BP_VAR_R, 0 TSRMLS_CC); zend_do_begin_variable_parse(TSRMLS_C); last_op_number = get_next_op_number(CG(active_op_array))-1; last_op = &CG(active_op_array)->opcodes[last_op_number]; if ((last_op->op2_type == IS_CONST) && (Z_TYPE(CONSTANT(last_op->op2.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(last_op->op2.constant)) == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !zend_binary_strcasecmp(Z_STRVAL(CONSTANT(last_op->op2.constant)), Z_STRLEN(CONSTANT(last_op->op2.constant)), ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1)) { zend_error(E_COMPILE_ERROR, "Cannot call __clone() method on objects - use 'clone $obj' instead"); } if (last_op->opcode == ZEND_FETCH_OBJ_R) { if (last_op->op2_type == IS_CONST) { zval name; name = CONSTANT(last_op->op2.constant); if (!IS_INTERNED(Z_STRVAL(name))) { Z_STRVAL(name) = estrndup(Z_STRVAL(name), Z_STRLEN(name)); } FREE_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); last_op->op2.constant = zend_add_func_name_literal(CG(active_op_array), &name TSRMLS_CC); GET_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); } last_op->opcode = ZEND_INIT_METHOD_CALL; SET_UNUSED(last_op->result); Z_LVAL(left_bracket->u.constant) = ZEND_INIT_FCALL_BY_NAME; } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (left_bracket->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &left_bracket->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, left_bracket); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_do_clone(znode *result, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CLONE; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_begin_dynamic_function_call(znode *function_name, int ns_call TSRMLS_DC) /* {{{ */ { unsigned char *ptr = NULL; zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (ns_call) { /* In run-time PHP will check for function with full name and internal function with short name */ opline->opcode = ZEND_INIT_NS_FCALL_BY_NAME; SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_ns_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (function_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, function_name); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_resolve_non_class_name(znode *element_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; int len; zval **ns; char *lcname, *compound = memchr(Z_STRVAL(element_name->u.constant), '\\', Z_STRLEN(element_name->u.constant)); if (Z_STRVAL(element_name->u.constant)[0] == '\\') { /* name starts with \ so it is known and unambiguos, nothing to do here but shorten it */ memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+1, Z_STRLEN(element_name->u.constant)); --Z_STRLEN(element_name->u.constant); return; } if(!check_namespace) { return; } if (compound && CG(current_import)) { len = compound - Z_STRVAL(element_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(element_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(element_name->u.constant) -= len; memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+len, Z_STRLEN(element_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, element_name TSRMLS_CC); *element_name = tmp; efree(lcname); return; } efree(lcname); } if (CG(current_namespace)) { tmp = *element_name; Z_STRLEN(tmp.u.constant) = sizeof("\\")-1 + Z_STRLEN(element_name->u.constant) + Z_STRLEN_P(CG(current_namespace)); Z_STRVAL(tmp.u.constant) = (char *) emalloc(Z_STRLEN(tmp.u.constant)+1); memcpy(Z_STRVAL(tmp.u.constant), Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace))]), "\\", sizeof("\\")-1); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace)) + sizeof("\\")-1]), Z_STRVAL(element_name->u.constant), Z_STRLEN(element_name->u.constant)+1); STR_FREE(Z_STRVAL(element_name->u.constant)); *element_name = tmp; } } /* }}} */ void zend_resolve_class_name(znode *class_name, ulong fetch_type, int check_ns_name TSRMLS_DC) /* {{{ */ { char *compound; char *lcname; zval **ns; znode tmp; int len; compound = memchr(Z_STRVAL(class_name->u.constant), '\\', Z_STRLEN(class_name->u.constant)); if (compound) { /* This is a compound class name that contains namespace prefix */ if (Z_STRVAL(class_name->u.constant)[0] == '\\') { /* The STRING name has "\" prefix */ Z_STRLEN(class_name->u.constant) -= 1; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+1, Z_STRLEN(class_name->u.constant)+1); Z_STRVAL(class_name->u.constant) = erealloc( Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1); if (ZEND_FETCH_CLASS_DEFAULT != zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "'\\%s' is an invalid class name", Z_STRVAL(class_name->u.constant)); } } else { if (CG(current_import)) { len = compound - Z_STRVAL(class_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(class_name->u.constant) -= len; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+len, Z_STRLEN(class_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; efree(lcname); return; } efree(lcname); } /* Here name is not prefixed with \ and not imported */ if (CG(current_namespace)) { tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } } } else if (CG(current_import) || CG(current_namespace)) { /* this is a plain name (without \) */ lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns) == SUCCESS) { /* The given name is an import name. Substitute it. */ zval_dtor(&class_name->u.constant); class_name->u.constant = **ns; zval_copy_ctor(&class_name->u.constant); } else if (CG(current_namespace)) { /* plain name, no import - prepend current namespace to it */ tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } efree(lcname); } } /* }}} */ void zend_do_fetch_class(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { long fetch_class_op_number; zend_op *opline; if (class_name->op_type == IS_CONST && Z_TYPE(class_name->u.constant) == IS_STRING && Z_STRLEN(class_name->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_name->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } fetch_class_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CLASS; SET_UNUSED(opline->op1); opline->extended_value = ZEND_FETCH_CLASS_GLOBAL; CG(catch_begin) = fetch_class_op_number; if (class_name->op_type == IS_CONST) { int fetch_type; fetch_type = zend_get_class_fetch_type(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); switch (fetch_type) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: SET_UNUSED(opline->op2); opline->extended_value = fetch_type; zval_dtor(&class_name->u.constant); break; default: zend_resolve_class_name(class_name, opline->extended_value, 0 TSRMLS_CC); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_name->u.constant TSRMLS_CC); break; } } else { SET_NODE(opline->op2, class_name); } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; /* FIXME: Hack so that INIT_FCALL_BY_NAME still knows this is a class */ GET_NODE(result, opline->result); result->EA = opline->extended_value; } /* }}} */ void zend_do_label(znode *label TSRMLS_DC) /* {{{ */ { zend_label dest; if (!CG(context).labels) { ALLOC_HASHTABLE(CG(context).labels); zend_hash_init(CG(context).labels, 4, NULL, NULL, 0); } dest.brk_cont = CG(context).current_brk_cont; dest.opline_num = get_next_op_number(CG(active_op_array)); if (zend_hash_add(CG(context).labels, Z_STRVAL(label->u.constant), Z_STRLEN(label->u.constant) + 1, (void**)&dest, sizeof(zend_label), NULL) == FAILURE) { zend_error(E_COMPILE_ERROR, "Label '%s' already defined", Z_STRVAL(label->u.constant)); } /* Done with label now */ zval_dtor(&label->u.constant); } /* }}} */ void zend_resolve_goto_label(zend_op_array *op_array, zend_op *opline, int pass2 TSRMLS_DC) /* {{{ */ { zend_label *dest; long current, distance; zval *label; if (pass2) { label = opline->op2.zv; } else { label = &CONSTANT_EX(op_array, opline->op2.constant); } if (CG(context).labels == NULL || zend_hash_find(CG(context).labels, Z_STRVAL_P(label), Z_STRLEN_P(label)+1, (void**)&dest) == FAILURE) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; zend_error(E_COMPILE_ERROR, "'goto' to undefined label '%s'", Z_STRVAL_P(label)); } else { /* Label is not defined. Delay to pass 2. */ INC_BPC(op_array); return; } } opline->op1.opline_num = dest->opline_num; zval_dtor(label); Z_TYPE_P(label) = IS_NULL; /* Check that we are not moving into loop or switch */ current = opline->extended_value; for (distance = 0; current != dest->brk_cont; distance++) { if (current == -1) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; } zend_error(E_COMPILE_ERROR, "'goto' into loop or switch statement is disallowed"); } current = op_array->brk_cont_array[current].parent; } if (distance == 0) { /* Nothing to break out of, optimize to ZEND_JMP */ opline->opcode = ZEND_JMP; opline->extended_value = 0; SET_UNUSED(opline->op2); } else { /* Set real break distance */ ZVAL_LONG(label, distance); } if (pass2) { DEC_BPC(op_array); } } /* }}} */ void zend_do_goto(const znode *label TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_GOTO; opline->extended_value = CG(context).current_brk_cont; SET_UNUSED(opline->op1); SET_NODE(opline->op2, label); zend_resolve_goto_label(CG(active_op_array), opline, 0 TSRMLS_CC); } /* }}} */ void zend_release_labels(TSRMLS_D) /* {{{ */ { if (CG(context).labels) { zend_hash_destroy(CG(context).labels); FREE_HASHTABLE(CG(context).labels); } if (!zend_stack_is_empty(&CG(context_stack))) { zend_compiler_context *ctx; zend_stack_top(&CG(context_stack), (void**)&ctx); CG(context) = *ctx; zend_stack_del_top(&CG(context_stack)); } } /* }}} */ void zend_do_build_full_name(znode *result, znode *prefix, znode *name, int is_class_member TSRMLS_DC) /* {{{ */ { zend_uint length; if (!result) { result = prefix; } else { *result = *prefix; } if (is_class_member) { length = sizeof("::")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "::", sizeof("::")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("::")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } else { length = sizeof("\\")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "\\", sizeof("\\")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("\\")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } } /* }}} */ int zend_do_begin_class_member_function_call(znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { znode class_node; unsigned char *ptr = NULL; zend_op *opline; if (method_name->op_type == IS_CONST) { char *lcname = zend_str_tolower_dup(Z_STRVAL(method_name->u.constant), Z_STRLEN(method_name->u.constant)); if ((sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == Z_STRLEN(method_name->u.constant) && memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == 0) { zval_dtor(&method_name->u.constant); method_name->op_type = IS_UNUSED; } efree(lcname); } if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; opline = get_next_op(CG(active_op_array) TSRMLS_CC); } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->extended_value = class_node.EA ; } opline->opcode = ZEND_INIT_STATIC_METHOD_CALL; if (class_node.op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, &class_node); } if (method_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &method_name->u.constant TSRMLS_CC); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } } else { SET_NODE(opline->op2, method_name); } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 1; /* Dynamic */ } /* }}} */ void zend_do_end_function_call(znode *function_name, znode *result, const znode *argument_list, int is_method, int is_dynamic_fcall TSRMLS_DC) /* {{{ */ { zend_op *opline; if (is_method && function_name && function_name->op_type == IS_UNUSED) { /* clone */ if (Z_LVAL(argument_list->u.constant) != 0) { zend_error(E_WARNING, "Clone method does not require arguments"); } opline = &CG(active_op_array)->opcodes[Z_LVAL(function_name->u.constant)]; } else { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (!is_method && !is_dynamic_fcall && function_name->op_type==IS_CONST) { opline->opcode = ZEND_DO_FCALL; SET_NODE(opline->op1, function_name); CALCULATE_LITERAL_HASH(opline->op1.constant); GET_CACHE_SLOT(opline->op1.constant); } else { opline->opcode = ZEND_DO_FCALL_BY_NAME; SET_UNUSED(opline->op1); } } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(result, opline->result) ; SET_UNUSED(opline->op2); zend_stack_del_top(&CG(function_call_stack)); opline->extended_value = Z_LVAL(argument_list->u.constant); } /* }}} */ void zend_do_pass_param(znode *param, zend_uchar op, int offset TSRMLS_DC) /* {{{ */ { zend_op *opline; int original_op=op; zend_function **function_ptr_ptr, *function_ptr; int send_by_reference; int send_function = 0; zend_stack_top(&CG(function_call_stack), (void **) &function_ptr_ptr); function_ptr = *function_ptr_ptr; if (original_op == ZEND_SEND_REF) { if (function_ptr && function_ptr->common.function_name && function_ptr->common.type == ZEND_USER_FUNCTION && !ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed; " "If you would like to pass argument by reference, modify the declaration of %s().", function_ptr->common.function_name); } else { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed"); } return; } if (function_ptr) { if (ARG_MAY_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { if (param->op_type & (IS_VAR|IS_CV)) { send_by_reference = 1; if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION | ZEND_ARG_SEND_SILENT; } } else { op = ZEND_SEND_VAL; send_by_reference = 0; } } else { send_by_reference = ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset) ? ZEND_ARG_SEND_BY_REF : 0; } } else { send_by_reference = 0; } if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION; } else if (op == ZEND_SEND_VAL && (param->op_type & (IS_VAR|IS_CV))) { op = ZEND_SEND_VAR_NO_REF; } if (op!=ZEND_SEND_VAR_NO_REF && send_by_reference==ZEND_ARG_SEND_BY_REF) { /* change to passing by reference */ switch (param->op_type) { case IS_VAR: case IS_CV: op = ZEND_SEND_REF; break; default: zend_error(E_COMPILE_ERROR, "Only variables can be passed by reference"); break; } } if (original_op == ZEND_SEND_VAR) { switch (op) { case ZEND_SEND_VAR_NO_REF: zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); break; case ZEND_SEND_VAR: if (function_ptr) { zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(param, BP_VAR_FUNC_ARG, offset TSRMLS_CC); } break; case ZEND_SEND_REF: zend_do_end_variable_parse(param, BP_VAR_W, 0 TSRMLS_CC); break; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (op == ZEND_SEND_VAR_NO_REF) { if (function_ptr) { opline->extended_value = ZEND_ARG_COMPILE_TIME_BOUND | send_by_reference | send_function; } else { opline->extended_value = send_function; } } else { if (function_ptr) { opline->extended_value = ZEND_DO_FCALL; } else { opline->extended_value = ZEND_DO_FCALL_BY_NAME; } } opline->opcode = op; SET_NODE(opline->op1, param); opline->op2.opline_num = offset; SET_UNUSED(opline->op2); } /* }}} */ static int generate_free_switch_expr(const zend_switch_entry *switch_entry TSRMLS_DC) /* {{{ */ { zend_op *opline; if (switch_entry->cond.op_type != IS_VAR && switch_entry->cond.op_type != IS_TMP_VAR) { return (switch_entry->cond.op_type == IS_UNUSED); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry->cond); SET_UNUSED(opline->op2); opline->extended_value = 0; return 0; } /* }}} */ static int generate_free_foreach_copy(const zend_op *foreach_copy TSRMLS_DC) /* {{{ */ { zend_op *opline; /* If we reach the seperator then stop applying the stack */ if (foreach_copy->result_type == IS_UNUSED && foreach_copy->op1_type == IS_UNUSED) { return 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->result_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->result); SET_UNUSED(opline->op2); opline->extended_value = 1; if (foreach_copy->op1_type != IS_UNUSED) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->op1_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->op1); SET_UNUSED(opline->op2); opline->extended_value = 0; } return 0; } /* }}} */ void zend_do_return(znode *expr, int do_end_vparse TSRMLS_DC) /* {{{ */ { zend_op *opline; int start_op_number, end_op_number; if (do_end_vparse) { if ((CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) && !zend_is_function_or_method_call(expr)) { zend_do_end_variable_parse(expr, BP_VAR_W, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(expr, BP_VAR_R, 0 TSRMLS_CC); } } start_op_number = get_next_op_number(CG(active_op_array)); #ifdef ZTS zend_stack_apply_with_argument(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_switch_expr TSRMLS_CC); zend_stack_apply_with_argument(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_foreach_copy TSRMLS_CC); #else zend_stack_apply(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_switch_expr); zend_stack_apply(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_foreach_copy); #endif end_op_number = get_next_op_number(CG(active_op_array)); while (start_op_number < end_op_number) { CG(active_op_array)->opcodes[start_op_number].extended_value |= EXT_TYPE_FREE_ON_RETURN; start_op_number++; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) ? ZEND_RETURN_BY_REF : ZEND_RETURN; if (expr) { SET_NODE(opline->op1, expr); if (do_end_vparse && zend_is_function_or_method_call(expr)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } } else { opline->op1_type = IS_CONST; LITERAL_NULL(opline->op1); } SET_UNUSED(opline->op2); } /* }}} */ static int zend_add_try_element(zend_uint try_op TSRMLS_DC) /* {{{ */ { int try_catch_offset = CG(active_op_array)->last_try_catch++; CG(active_op_array)->try_catch_array = erealloc(CG(active_op_array)->try_catch_array, sizeof(zend_try_catch_element)*CG(active_op_array)->last_try_catch); CG(active_op_array)->try_catch_array[try_catch_offset].try_op = try_op; return try_catch_offset; } /* }}} */ static void zend_add_catch_element(int offset, zend_uint catch_op TSRMLS_DC) /* {{{ */ { CG(active_op_array)->try_catch_array[offset].catch_op = catch_op; } /* }}} */ void zend_do_first_catch(znode *open_parentheses TSRMLS_DC) /* {{{ */ { open_parentheses->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_initialize_try_catch_element(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist jmp_list; zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); zend_add_catch_element(try_token->u.op.opline_num, get_next_op_number(CG(active_op_array)) TSRMLS_CC); } /* }}} */ void zend_do_mark_last_catch(const znode *first_catch, const znode *last_additional_catch TSRMLS_DC) /* {{{ */ { CG(active_op_array)->last--; zend_do_if_end(TSRMLS_C); if (last_additional_catch->u.op.opline_num == -1) { CG(active_op_array)->opcodes[first_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[first_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } else { CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_try(znode *try_token TSRMLS_DC) /* {{{ */ { try_token->u.op.opline_num = zend_add_try_element(get_next_op_number(CG(active_op_array)) TSRMLS_CC); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_catch(znode *try_token, znode *class_name, znode *catch_var, znode *first_catch TSRMLS_DC) /* {{{ */ { long catch_op_number; zend_op *opline; znode catch_class; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); catch_class = *class_name; } else { zend_error(E_COMPILE_ERROR, "Bad class name in the catch statement"); } catch_op_number = get_next_op_number(CG(active_op_array)); if (first_catch) { first_catch->u.op.opline_num = catch_op_number; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CATCH; opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &catch_class.u.constant TSRMLS_CC); opline->op2_type = IS_CV; opline->op2.var = lookup_cv(CG(active_op_array), catch_var->u.constant.value.str.val, catch_var->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(catch_var->u.constant) = (char*)CG(active_op_array)->vars[opline->op2.var].name; opline->result.num = 0; /* 1 means it's the last catch in the block */ try_token->u.op.opline_num = catch_op_number; } /* }}} */ void zend_do_end_catch(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); CG(active_op_array)->opcodes[try_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_throw(const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_THROW; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); } /* }}} */ ZEND_API void function_add_ref(zend_function *function) /* {{{ */ { if (function->type == ZEND_USER_FUNCTION) { zend_op_array *op_array = &function->op_array; (*op_array->refcount)++; if (op_array->static_variables) { HashTable *static_variables = op_array->static_variables; zval *tmp_zval; ALLOC_HASHTABLE(op_array->static_variables); zend_hash_init(op_array->static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(op_array->static_variables, static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_zval, sizeof(zval *)); } op_array->run_time_cache = NULL; } } /* }}} */ static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */ { zend_function *function; if (!ce->parent) { return; } /* You cannot change create_object */ ce->create_object = ce->parent->create_object; /* Inherit special functions if needed */ if (!ce->get_iterator) { ce->get_iterator = ce->parent->get_iterator; } if (!ce->iterator_funcs.funcs) { ce->iterator_funcs.funcs = ce->parent->iterator_funcs.funcs; } if (!ce->__get) { ce->__get = ce->parent->__get; } if (!ce->__set) { ce->__set = ce->parent->__set; } if (!ce->__unset) { ce->__unset = ce->parent->__unset; } if (!ce->__isset) { ce->__isset = ce->parent->__isset; } if (!ce->__call) { ce->__call = ce->parent->__call; } if (!ce->__callstatic) { ce->__callstatic = ce->parent->__callstatic; } if (!ce->__tostring) { ce->__tostring = ce->parent->__tostring; } if (!ce->clone) { ce->clone = ce->parent->clone; } if(!ce->serialize) { ce->serialize = ce->parent->serialize; } if(!ce->unserialize) { ce->unserialize = ce->parent->unserialize; } if (!ce->destructor) { ce->destructor = ce->parent->destructor; } if (ce->constructor) { if (ce->parent->constructor && ce->parent->constructor->common.fn_flags & ZEND_ACC_FINAL) { zend_error(E_ERROR, "Cannot override final %s::%s() with %s::%s()", ce->parent->name, ce->parent->constructor->common.function_name, ce->name, ce->constructor->common.function_name ); } return; } if (zend_hash_find(&ce->parent->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), (void **)&function)==SUCCESS) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), function, sizeof(zend_function), NULL); function_add_ref(function); } else { /* Don't inherit the old style constructor if we already have the new style constructor */ char *lc_class_name; char *lc_parent_class_name; lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); if (!zend_hash_exists(&ce->function_table, lc_class_name, ce->name_length+1)) { lc_parent_class_name = zend_str_tolower_dup(ce->parent->name, ce->parent->name_length); if (!zend_hash_exists(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1) && zend_hash_find(&ce->parent->function_table, lc_parent_class_name, ce->parent->name_length+1, (void **)&function)==SUCCESS) { if (function->common.fn_flags & ZEND_ACC_CTOR) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1, function, sizeof(zend_function), NULL); function_add_ref(function); } } efree(lc_parent_class_name); } efree(lc_class_name); } ce->constructor = ce->parent->constructor; } /* }}} */ char *zend_visibility_string(zend_uint fn_flags) /* {{{ */ { if (fn_flags & ZEND_ACC_PRIVATE) { return "private"; } if (fn_flags & ZEND_ACC_PROTECTED) { return "protected"; } if (fn_flags & ZEND_ACC_PUBLIC) { return "public"; } return ""; } /* }}} */ static void do_inherit_method(zend_function *function) /* {{{ */ { /* The class entry of the derived function intentionally remains the same * as that of the parent class. That allows us to know in which context * we're running, and handle private method calls properly. */ function_add_ref(function); } /* }}} */ static zend_bool zend_do_perform_implementation_check(const zend_function *fe, const zend_function *proto TSRMLS_DC) /* {{{ */ { zend_uint i; /* If it's a user function then arg_info == NULL means we don't have any parameters but * we still need to do the arg number checks. We are only willing to ignore this for internal * functions because extensions don't always define arg_info. */ if (!proto || (!proto->common.arg_info && proto->common.type != ZEND_USER_FUNCTION)) { return 1; } /* Checks for constructors only if they are declared in an interface, * or explicitly marked as abstract */ if ((fe->common.fn_flags & ZEND_ACC_CTOR) && ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)) { return 1; } /* check number of arguments */ if (proto->common.required_num_args < fe->common.required_num_args || proto->common.num_args > fe->common.num_args) { return 0; } if (fe->common.type != ZEND_USER_FUNCTION && (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) != 0 && (fe->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) == 0) { return 0; } /* by-ref constraints on return values are covariant */ if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) { return 0; } for (i=0; i < proto->common.num_args; i++) { if (ZEND_LOG_XOR(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)) { /* Only one has a type hint and the other one doesn't */ return 0; } if (fe->common.arg_info[i].class_name && strcasecmp(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)!=0) { const char *colon; if (fe->common.type != ZEND_USER_FUNCTION) { return 0; } else if (strchr(proto->common.arg_info[i].class_name, '\\') != NULL || (colon = zend_memrchr(fe->common.arg_info[i].class_name, '\\', fe->common.arg_info[i].class_name_len)) == NULL || strcasecmp(colon+1, proto->common.arg_info[i].class_name) != 0) { zend_class_entry **fe_ce, **proto_ce; int found, found2; found = zend_lookup_class(fe->common.arg_info[i].class_name, fe->common.arg_info[i].class_name_len, &fe_ce TSRMLS_CC); found2 = zend_lookup_class(proto->common.arg_info[i].class_name, proto->common.arg_info[i].class_name_len, &proto_ce TSRMLS_CC); /* Check for class alias */ if (found != SUCCESS || found2 != SUCCESS || (*fe_ce)->type == ZEND_INTERNAL_CLASS || (*proto_ce)->type == ZEND_INTERNAL_CLASS || *fe_ce != *proto_ce) { return 0; } } } if (fe->common.arg_info[i].type_hint != proto->common.arg_info[i].type_hint) { /* Incompatible type hint */ return 0; } /* by-ref constraints on arguments are invariant */ if (fe->common.arg_info[i].pass_by_reference != proto->common.arg_info[i].pass_by_reference) { return 0; } } if (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) { for (i=proto->common.num_args; i < fe->common.num_args; i++) { if (!fe->common.arg_info[i].pass_by_reference) { return 0; } } } return 1; } /* }}} */ #define REALLOC_BUF_IF_EXCEED(buf, offset, length, size) \ if (UNEXPECTED(offset - buf + size >= length)) { \ length += size + 1; \ buf = erealloc(buf, length); \ } static char * zend_get_function_declaration(zend_function *fptr TSRMLS_DC) /* {{{ */ { char *offset, *buf; zend_uint length = 1024; offset = buf = (char *)emalloc(length * sizeof(char)); if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { *(offset++) = '&'; *(offset++) = ' '; } if (fptr->common.scope) { memcpy(offset, fptr->common.scope->name, fptr->common.scope->name_length); offset += fptr->common.scope->name_length; *(offset++) = ':'; *(offset++) = ':'; } { size_t name_len = strlen(fptr->common.function_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, name_len); memcpy(offset, fptr->common.function_name, name_len); offset += name_len; } *(offset++) = '('; if (fptr->common.arg_info) { zend_uint i, required; zend_arg_info *arg_info = fptr->common.arg_info; required = fptr->common.required_num_args; for (i = 0; i < fptr->common.num_args;) { if (arg_info->class_name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->class_name_len); memcpy(offset, arg_info->class_name, arg_info->class_name_len); offset += arg_info->class_name_len; *(offset++) = ' '; } else if (arg_info->type_hint) { zend_uint type_name_len; char *type_name = zend_get_type_by_const(arg_info->type_hint); type_name_len = strlen(type_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, type_name_len); memcpy(offset, type_name, type_name_len); offset += type_name_len; *(offset++) = ' '; } if (arg_info->pass_by_reference) { *(offset++) = '&'; } *(offset++) = '$'; if (arg_info->name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->name_len); memcpy(offset, arg_info->name, arg_info->name_len); offset += arg_info->name_len; } else { zend_uint idx = i; memcpy(offset, "param", 5); offset += 5; do { *(offset++) = (char) (idx % 10) + '0'; idx /= 10; } while (idx > 0); } if (i >= required) { *(offset++) = ' '; *(offset++) = '='; *(offset++) = ' '; if (fptr->type == ZEND_USER_FUNCTION) { zend_op *precv = NULL; { zend_uint idx = i; zend_op *op = ((zend_op_array *)fptr)->opcodes; zend_op *end = op + ((zend_op_array *)fptr)->last; ++idx; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT) && op->op1.num == (long)idx) { precv = op; } ++op; } } if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) { zval *zv, zv_copy; int use_copy; ALLOC_ZVAL(zv); *zv = *precv->op2.zv; zval_copy_ctor(zv); INIT_PZVAL(zv); zval_update_constant_ex(&zv, (void*)1, fptr->common.scope TSRMLS_CC); if (Z_TYPE_P(zv) == IS_BOOL) { if (Z_LVAL_P(zv)) { memcpy(offset, "true", 4); offset += 4; } else { memcpy(offset, "false", 5); offset += 5; } } else if (Z_TYPE_P(zv) == IS_NULL) { memcpy(offset, "NULL", 4); offset += 4; } else if (Z_TYPE_P(zv) == IS_STRING) { *(offset++) = '\''; REALLOC_BUF_IF_EXCEED(buf, offset, length, MIN(Z_STRLEN_P(zv), 10)); memcpy(offset, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 10)); offset += MIN(Z_STRLEN_P(zv), 10); if (Z_STRLEN_P(zv) > 10) { *(offset++) = '.'; *(offset++) = '.'; *(offset++) = '.'; } *(offset++) = '\''; } else { zend_make_printable_zval(zv, &zv_copy, &use_copy); REALLOC_BUF_IF_EXCEED(buf, offset, length, Z_STRLEN(zv_copy)); memcpy(offset, Z_STRVAL(zv_copy), Z_STRLEN(zv_copy)); offset += Z_STRLEN(zv_copy); if (use_copy) { zval_dtor(&zv_copy); } } zval_ptr_dtor(&zv); } } else { memcpy(offset, "NULL", 4); offset += 4; } } if (++i < fptr->common.num_args) { *(offset++) = ','; *(offset++) = ' '; } arg_info++; REALLOC_BUF_IF_EXCEED(buf, offset, length, 23); } } *(offset++) = ')'; *offset = '\0'; return buf; } /* }}} */ static void do_inheritance_check_on_method(zend_function *child, zend_function *parent TSRMLS_DC) /* {{{ */ { zend_uint child_flags; zend_uint parent_flags = parent->common.fn_flags; if (parent->common.fn_flags & ZEND_ACC_ABSTRACT && parent->common.scope != (child->common.prototype ? child->common.prototype->common.scope : child->common.scope) && child->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_IMPLEMENTED_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Can't inherit abstract function %s::%s() (previously declared abstract in %s)", parent->common.scope->name, child->common.function_name, child->common.prototype ? child->common.prototype->common.scope->name : child->common.scope->name); } if (parent_flags & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot override final method %s::%s()", ZEND_FN_SCOPE_NAME(parent), child->common.function_name); } child_flags = child->common.fn_flags; /* You cannot change from static to non static and vice versa. */ if ((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC)) { if (child->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot make non static method %s::%s() static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } else { zend_error(E_COMPILE_ERROR, "Cannot make static method %s::%s() non static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } } /* Disallow making an inherited method abstract. */ if ((child_flags & ZEND_ACC_ABSTRACT) && !(parent_flags & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Cannot make non abstract method %s::%s() abstract in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } if (parent_flags & ZEND_ACC_CHANGED) { child->common.fn_flags |= ZEND_ACC_CHANGED; } else { /* Prevent derived classes from restricting access that was available in parent classes */ if ((child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::%s() must be %s (as in class %s)%s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if (((child_flags & ZEND_ACC_PPP_MASK) < (parent_flags & ZEND_ACC_PPP_MASK)) && ((parent_flags & ZEND_ACC_PPP_MASK) & ZEND_ACC_PRIVATE)) { child->common.fn_flags |= ZEND_ACC_CHANGED; } } if (parent_flags & ZEND_ACC_PRIVATE) { child->common.prototype = NULL; } else if (parent_flags & ZEND_ACC_ABSTRACT) { child->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; child->common.prototype = parent; } else if (!(parent->common.fn_flags & ZEND_ACC_CTOR) || (parent->common.prototype && (parent->common.prototype->common.scope->ce_flags & ZEND_ACC_INTERFACE))) { /* ctors only have a prototype if it comes from an interface */ child->common.prototype = parent->common.prototype ? parent->common.prototype : parent; } if (child->common.prototype && (child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { if (!zend_do_perform_implementation_check(child, child->common.prototype TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s::%s() must be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_get_function_declaration(child->common.prototype TSRMLS_CC)); } } else if (EG(error_reporting) & E_STRICT || EG(user_error_handler)) { /* Check E_STRICT (or custom error handler) before the check so that we save some time */ if (!zend_do_perform_implementation_check(child, parent TSRMLS_CC)) { char *method_prototype = zend_get_function_declaration(child->common.prototype TSRMLS_CC); zend_error(E_STRICT, "Declaration of %s::%s() should be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, method_prototype); efree(method_prototype); } } } /* }}} */ static zend_bool do_inherit_method_check(HashTable *child_function_table, zend_function *parent, const zend_hash_key *hash_key, zend_class_entry *child_ce) /* {{{ */ { zend_uint parent_flags = parent->common.fn_flags; zend_function *child; TSRMLS_FETCH(); if (zend_hash_quick_find(child_function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child)==FAILURE) { if (parent_flags & (ZEND_ACC_ABSTRACT)) { child_ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } return 1; /* method doesn't exist in child, copy from parent */ } do_inheritance_check_on_method(child, parent TSRMLS_CC); return 0; } /* }}} */ static zend_bool do_inherit_property_access_check(HashTable *target_ht, zend_property_info *parent_info, const zend_hash_key *hash_key, zend_class_entry *ce) /* {{{ */ { zend_property_info *child_info; zend_class_entry *parent_ce = ce->parent; if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW)) { if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { child_info->flags |= ZEND_ACC_CHANGED; } else { zend_hash_quick_update(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, parent_info, sizeof(zend_property_info), (void **) &child_info); if(ce->type & ZEND_INTERNAL_CLASS) { zend_duplicate_property_info_internal(child_info); } else { zend_duplicate_property_info(child_info); } child_info->flags &= ~ZEND_ACC_PRIVATE; /* it's not private anymore */ child_info->flags |= ZEND_ACC_SHADOW; /* but it's a shadow of private */ } return 0; /* don't copy access information to child */ } if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { if ((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s", (parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", parent_ce->name, hash_key->arKey, (child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ce->name, hash_key->arKey); } if(parent_info->flags & ZEND_ACC_CHANGED) { child_info->flags |= ZEND_ACC_CHANGED; } if ((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ce->name, hash_key->arKey, zend_visibility_string(parent_info->flags), parent_ce->name, (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if ((child_info->flags & ZEND_ACC_STATIC) == 0) { Z_DELREF_P(ce->default_properties_table[parent_info->offset]); ce->default_properties_table[parent_info->offset] = ce->default_properties_table[child_info->offset]; ce->default_properties_table[child_info->offset] = NULL; child_info->offset = parent_info->offset; } return 0; /* Don't copy from parent */ } else { return 1; /* Copy from parent */ } } /* }}} */ static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce TSRMLS_CC) == FAILURE) { zend_error(E_CORE_ERROR, "Class %s could not implement interface %s", ce->name, iface->name); } if (ce == iface) { zend_error(E_ERROR, "Interface %s cannot implement itself", ce->name); } } /* }}} */ ZEND_API void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface TSRMLS_DC) /* {{{ */ { /* expects interface to be contained in ce's interface list already */ zend_uint i, ce_num, if_num = iface->num_interfaces; zend_class_entry *entry; if (if_num==0) { return; } ce_num = ce->num_interfaces; if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } /* Inherit the interfaces, only if they're not already inherited by the class */ while (if_num--) { entry = iface->interfaces[if_num]; for (i = 0; i < ce_num; i++) { if (ce->interfaces[i] == entry) { break; } } if (i == ce_num) { ce->interfaces[ce->num_interfaces++] = entry; } } /* and now call the implementing handlers */ while (ce_num < ce->num_interfaces) { do_implement_interface(ce, ce->interfaces[ce_num++] TSRMLS_CC); } } /* }}} */ #ifdef ZTS static void zval_internal_ctor(zval **p) /* {{{ */ { zval *orig_ptr = *p; ALLOC_ZVAL(*p); MAKE_COPY_ZVAL(&orig_ptr, *p); } /* }}} */ # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) (((parent_ce)->type != (ce)->type) ? zval_internal_ctor : zval_add_ref)) #else # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) zval_add_ref) #endif ZEND_API void zend_do_inheritance(zend_class_entry *ce, zend_class_entry *parent_ce TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; if ((ce->ce_flags & ZEND_ACC_INTERFACE) && !(parent_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ce->name, parent_ce->name); } if (parent_ce->ce_flags & ZEND_ACC_FINAL_CLASS) { zend_error(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ce->name, parent_ce->name); } ce->parent = parent_ce; /* Copy serialize/unserialize callbacks */ if (!ce->serialize) { ce->serialize = parent_ce->serialize; } if (!ce->unserialize) { ce->unserialize = parent_ce->unserialize; } /* Inherit interfaces */ zend_do_inherit_interfaces(ce, parent_ce TSRMLS_CC); /* Inherit properties */ if (parent_ce->default_properties_count) { int i = ce->default_properties_count + parent_ce->default_properties_count; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_properties_count) { while (i-- > parent_ce->default_properties_count) { ce->default_properties_table[i] = ce->default_properties_table[i - parent_ce->default_properties_count]; } } for (i = 0; i < parent_ce->default_properties_count; i++) { ce->default_properties_table[i] = parent_ce->default_properties_table[i]; if (ce->default_properties_table[i]) { #ifdef ZTS if (parent_ce->type != ce->type) { zval *p; ALLOC_ZVAL(p); MAKE_COPY_ZVAL(&ce->default_properties_table[i], p); ce->default_properties_table[i] = p; } else { Z_ADDREF_P(ce->default_properties_table[i]); } #else Z_ADDREF_P(ce->default_properties_table[i]); #endif } } ce->default_properties_count += parent_ce->default_properties_count; } if (parent_ce->type != ce->type) { /* User class extends internal class */ zend_update_class_constants(parent_ce TSRMLS_CC); if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = erealloc(ce->default_static_members_table, sizeof(void*) * i); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&CE_STATIC_MEMBERS(parent_ce)[i]); ce->default_static_members_table[i] = CE_STATIC_MEMBERS(parent_ce)[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; ce->static_members_table = ce->default_static_members_table; } } else { if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&parent_ce->default_static_members_table[i]); ce->default_static_members_table[i] = parent_ce->default_static_members_table[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } } for (zend_hash_internal_pointer_reset(&ce->properties_info); zend_hash_get_current_data(&ce->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->properties_info)) { if (property_info->ce == ce) { if (property_info->flags & ZEND_ACC_STATIC) { property_info->offset += parent_ce->default_static_members_count; } else { property_info->offset += parent_ce->default_properties_count; } } } zend_hash_merge_ex(&ce->properties_info, &parent_ce->properties_info, (copy_ctor_func_t) (ce->type & ZEND_INTERNAL_CLASS ? zend_duplicate_property_info_internal : zend_duplicate_property_info), sizeof(zend_property_info), (merge_checker_func_t) do_inherit_property_access_check, ce); zend_hash_merge(&ce->constants_table, &parent_ce->constants_table, zval_property_ctor(parent_ce, ce), NULL, sizeof(zval *), 0); zend_hash_merge_ex(&ce->function_table, &parent_ce->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_inherit_parent_constructor(ce); if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS && ce->type == ZEND_INTERNAL_CLASS) { ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } else if (!(ce->ce_flags & ZEND_ACC_IMPLEMENT_INTERFACES) && !(ce->ce_flags & ZEND_ACC_IMPLEMENT_TRAITS)) { /* The verification will be done in runtime by ZEND_VERIFY_ABSTRACT_CLASS */ zend_verify_abstract_class(ce TSRMLS_CC); } ce->ce_flags |= parent_ce->ce_flags & ZEND_HAS_STATIC_IN_METHODS; } /* }}} */ static zend_bool do_inherit_constant_check(HashTable *child_constants_table, const zval **parent_constant, const zend_hash_key *hash_key, const zend_class_entry *iface) /* {{{ */ { zval **old_constant; if (zend_hash_quick_find(child_constants_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**)&old_constant) == SUCCESS) { if (*old_constant != *parent_constant) { zend_error(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", hash_key->arKey, iface->name); } return 0; } return 1; } /* }}} */ static int do_interface_constant_check(zval **val TSRMLS_DC, int num_args, va_list args, const zend_hash_key *key) /* {{{ */ { zend_class_entry **iface = va_arg(args, zend_class_entry**); do_inherit_constant_check(&(*iface)->constants_table, (const zval **) val, key, *iface); return ZEND_HASH_APPLY_KEEP; } /* }}} */ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_iface_num = ce->num_interfaces; zend_uint parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0; for (i = 0; i < ce->num_interfaces; i++) { if (ce->interfaces[i] == NULL) { memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i)); i--; } else if (ce->interfaces[i] == iface) { if (i < parent_iface_num) { ignore = 1; } else { zend_error(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ce->name, iface->name); } } } if (ignore) { /* Check for attempt to redeclare interface constants */ zend_hash_apply_with_arguments(&ce->constants_table TSRMLS_CC, (apply_func_args_t) do_interface_constant_check, 1, &iface); } else { if (ce->num_interfaces >= current_iface_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } } ce->interfaces[ce->num_interfaces++] = iface; zend_hash_merge_ex(&ce->constants_table, &iface->constants_table, (copy_ctor_func_t) zval_add_ref, sizeof(zval *), (merge_checker_func_t) do_inherit_constant_check, iface); zend_hash_merge_ex(&ce->function_table, &iface->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_implement_interface(ce, iface TSRMLS_CC); zend_do_inherit_interfaces(ce, iface TSRMLS_CC); } } /* }}} */ ZEND_API void zend_do_implement_trait(zend_class_entry *ce, zend_class_entry *trait TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_trait_num = ce->num_traits; zend_uint parent_trait_num = ce->parent ? ce->parent->num_traits : 0; for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == NULL) { memmove(ce->traits + i, ce->traits + i + 1, sizeof(zend_class_entry*) * (--ce->num_traits - i)); i--; } else if (ce->traits[i] == trait) { if (i < parent_trait_num) { ignore = 1; } } } if (!ignore) { if (ce->num_traits >= current_trait_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->traits = (zend_class_entry **) realloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } else { ce->traits = (zend_class_entry **) erealloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } } ce->traits[ce->num_traits++] = trait; } } /* }}} */ static int zend_traits_merge_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { size_t current; size_t i; size_t count; HashTable* resulting_table; HashTable** function_tables; zend_class_entry *ce; size_t collision = 0; size_t abstract_solved = 0; zend_function* other_trait_fn; current = va_arg(args, size_t); /* index of current trait */ count = va_arg(args, size_t); resulting_table = va_arg(args, HashTable*); function_tables = va_arg(args, HashTable**); ce = va_arg(args, zend_class_entry*); for (i = 0; i < count; i++) { if (i == current) { continue; /* just skip this, cause its the table this function is applied on */ } if (zend_hash_quick_find(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&other_trait_fn) == SUCCESS) { /* if it is an abstract method, there is no collision */ if (other_trait_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* we can savely free and remove it from other table */ zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } else { /* if it is not an abstract method, there is still no collision */ /* if fn is an abstract method */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* just mark as solved, will be added if its own trait is processed */ abstract_solved = 1; } else { /* but else, we have a collision of non-abstract methods */ collision++; zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } } } if (collision) { zend_function* class_fn; /* make sure method is not already overridden in class */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&class_fn) == FAILURE || class_fn->common.scope != ce) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because there are collisions with other trait methods on %s", fn->common.function_name, ce->name); } zend_function_dtor(fn); } else if (abstract_solved) { zend_function_dtor(fn); } else { /* Add it to result function table */ if (zend_hash_quick_add(resulting_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, fn, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating resulting trait method table", fn->common.function_name); } } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ /* {{{ Originates from php_runkit_function_copy_ctor Duplicate structures in an op_array where necessary to make an outright duplicate */ static void zend_traits_duplicate_function(zend_function *fe, zend_class_entry *target_ce, char *newname TSRMLS_DC) { zend_literal *literals_copy; zend_compiled_variable *dupvars; zend_op *opcode_copy; zval class_name_zv; int class_name_literal; int i; int number_of_literals; if (fe->op_array.static_variables) { HashTable *tmpHash; ALLOC_HASHTABLE(tmpHash); zend_hash_init(tmpHash, zend_hash_num_elements(fe->op_array.static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_apply_with_arguments(fe->op_array.static_variables TSRMLS_CC, (apply_func_args_t)zval_copy_static_var, 1, tmpHash); fe->op_array.static_variables = tmpHash; } number_of_literals = fe->op_array.last_literal; literals_copy = (zend_literal*)emalloc(number_of_literals * sizeof(zend_literal)); for (i = 0; i < number_of_literals; i++) { literals_copy[i] = fe->op_array.literals[i]; zval_copy_ctor(&literals_copy[i].constant); } fe->op_array.literals = literals_copy; fe->op_array.refcount = emalloc(sizeof(zend_uint)); *(fe->op_array.refcount) = 1; if (fe->op_array.vars) { i = fe->op_array.last_var; dupvars = safe_emalloc(fe->op_array.last_var, sizeof(zend_compiled_variable), 0); while (i > 0) { i--; dupvars[i].name = estrndup(fe->op_array.vars[i].name, fe->op_array.vars[i].name_len); dupvars[i].name_len = fe->op_array.vars[i].name_len; dupvars[i].hash_value = fe->op_array.vars[i].hash_value; } fe->op_array.vars = dupvars; } else { fe->op_array.vars = NULL; } opcode_copy = safe_emalloc(sizeof(zend_op), fe->op_array.last, 0); for(i = 0; i < fe->op_array.last; i++) { opcode_copy[i] = fe->op_array.opcodes[i]; if (opcode_copy[i].op1_type != IS_CONST) { if (opcode_copy[i].op1.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op1.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op1.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op1.jmp_addr - fe->op_array.opcodes); } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op1.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op1.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op1.zv = &fe->op_array.literals[class_name_literal].constant; } } if (opcode_copy[i].op2_type != IS_CONST) { if (opcode_copy[i].op2.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op2.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op2.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op2.jmp_addr - fe->op_array.opcodes); } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op2.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op2.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op2.zv = &fe->op_array.literals[class_name_literal].constant; } } } fe->op_array.opcodes = opcode_copy; fe->op_array.function_name = newname; /* was setting it to fe which does not work since fe is stack allocated and not a stable address */ /* fe->op_array.prototype = fe->op_array.prototype; */ if (fe->op_array.arg_info) { zend_arg_info *tmpArginfo; tmpArginfo = safe_emalloc(sizeof(zend_arg_info), fe->op_array.num_args, 0); for(i = 0; i < fe->op_array.num_args; i++) { tmpArginfo[i] = fe->op_array.arg_info[i]; tmpArginfo[i].name = estrndup(tmpArginfo[i].name, tmpArginfo[i].name_len); if (tmpArginfo[i].class_name) { tmpArginfo[i].class_name = estrndup(tmpArginfo[i].class_name, tmpArginfo[i].class_name_len); } } fe->op_array.arg_info = tmpArginfo; } fe->op_array.doc_comment = estrndup(fe->op_array.doc_comment, fe->op_array.doc_comment_len); fe->op_array.try_catch_array = (zend_try_catch_element*)estrndup((char*)fe->op_array.try_catch_array, sizeof(zend_try_catch_element) * fe->op_array.last_try_catch); fe->op_array.brk_cont_array = (zend_brk_cont_element*)estrndup((char*)fe->op_array.brk_cont_array, sizeof(zend_brk_cont_element) * fe->op_array.last_brk_cont); } /* }}} */ static void zend_add_magic_methods(zend_class_entry* ce, const char* mname, uint mname_len, zend_function* fe TSRMLS_DC) { if ( !strncmp(mname, ZEND_CLONE_FUNC_NAME, mname_len)) { ce->clone = fe; fe->common.fn_flags |= ZEND_ACC_CLONE; } else if (!strncmp(mname, ZEND_CONSTRUCTOR_FUNC_NAME, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } else if (!strncmp(mname, ZEND_DESTRUCTOR_FUNC_NAME, mname_len)) { ce->destructor = fe; fe->common.fn_flags |= ZEND_ACC_DTOR; } else if (!strncmp(mname, ZEND_GET_FUNC_NAME, mname_len)) ce->__get = fe; else if (!strncmp(mname, ZEND_SET_FUNC_NAME, mname_len)) ce->__set = fe; else if (!strncmp(mname, ZEND_CALL_FUNC_NAME, mname_len)) ce->__call = fe; else if (!strncmp(mname, ZEND_UNSET_FUNC_NAME, mname_len)) ce->__unset = fe; else if (!strncmp(mname, ZEND_ISSET_FUNC_NAME, mname_len)) ce->__isset = fe; else if (!strncmp(mname, ZEND_CALLSTATIC_FUNC_NAME, mname_len)) ce->__callstatic= fe; else if (!strncmp(mname, ZEND_TOSTRING_FUNC_NAME, mname_len)) ce->__tostring = fe; else if (ce->name_length + 1 == mname_len) { char *lowercase_name = emalloc(ce->name_length + 1); zend_str_tolower_copy(lowercase_name, ce->name, ce->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, ce->name_length + 1, 1 TSRMLS_CC); if (!memcmp(mname, lowercase_name, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } str_efree(lowercase_name); } } static int zend_traits_merge_functions_to_class(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zend_class_entry *ce = va_arg(args, zend_class_entry*); int add = 0; zend_function* existing_fn; zend_function fn_copy, *fn_copy_p; zend_function* prototype = NULL; /* is used to determine the prototype according to the inheritance chain */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &existing_fn) == FAILURE) { add = 1; /* not found */ } else if (existing_fn->common.scope != ce) { add = 1; /* or inherited from other class or interface */ /* it is just a reference which was added to the subclass while doing the inheritance */ /* so we can deleted now, and will add the overriding method afterwards */ /* except, if we try to add an abstract function, then we should not delete the inherited one */ /* delete inherited fn if the function to be added is not abstract */ if ((fn->common.fn_flags & ZEND_ACC_ABSTRACT) == 0) { zend_hash_quick_del(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } if (add) { zend_function* parent_function; if (ce->parent && zend_hash_quick_find(&ce->parent->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &parent_function) != FAILURE) { prototype = parent_function; /* ->common.fn_flags |= ZEND_ACC_ABSTRACT; */ /* we got that method in the parent class, and are going to override it, except, if the trait is just asking to have an abstract method implemented. */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* then we clean up an skip this method */ zend_function_dtor(fn); return ZEND_HASH_APPLY_REMOVE; } } fn->common.scope = ce; fn->common.prototype = prototype; if (prototype && (prototype->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT || prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { fn->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; } else if (fn->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT) { /* remove ZEND_ACC_IMPLEMENTED_ABSTRACT flag, think it shouldn't be copied to class */ fn->common.fn_flags = fn->common.fn_flags - ZEND_ACC_IMPLEMENTED_ABSTRACT; } /* check whether the trait method fullfills the inheritance requirements */ if (prototype) { do_inheritance_check_on_method(fn, prototype TSRMLS_CC); } if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (fn->op_array.static_variables) { ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, ce, estrdup(fn->common.function_name) TSRMLS_CC); if (zend_hash_quick_update(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, &fn_copy, sizeof(zend_function), (void**)&fn_copy_p)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating class method table", hash_key->arKey); } zend_add_magic_methods(ce, hash_key->arKey, hash_key->nKeyLength, fn_copy_p TSRMLS_CC); zend_function_dtor(fn); } else { zend_function_dtor(fn); } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ static int zend_traits_copy_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { HashTable* target; zend_class_entry *target_ce; zend_trait_alias** aliases; HashTable* exclude_table; char* lcname; unsigned int fnname_len; zend_function fn_copy; void* dummy; size_t i = 0; target = va_arg(args, HashTable*); target_ce = va_arg(args, zend_class_entry*); aliases = va_arg(args, zend_trait_alias**); exclude_table = va_arg(args, HashTable*); fnname_len = strlen(fn->common.function_name); /* apply aliases which are qualified with a class name, there should not be any ambiguity */ if (aliases) { while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias != NULL && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && aliases[i]->trait_method->mname_len == fnname_len && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(aliases[i]->alias, aliases[i]->alias_len) TSRMLS_CC); /* if it is 0, no modifieres has been changed */ if (aliases[i]->modifiers) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } lcname = zend_str_tolower_dup(aliases[i]->alias, aliases[i]->alias_len); if (zend_hash_add(target, lcname, aliases[i]->alias_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add aliased trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } efree(lcname); } i++; } } lcname = zend_str_tolower_dup(fn->common.function_name, fnname_len); if (exclude_table == NULL || zend_hash_find(exclude_table, lcname, fnname_len, &dummy) == FAILURE) { /* is not in hashtable, thus, function is not to be excluded */ fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(fn->common.function_name, fnname_len) TSRMLS_CC); /* apply aliases which are not qualified by a class name, or which have not * alias name, just setting visibility */ if (aliases) { i = 0; while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias == NULL && aliases[i]->modifiers != 0 && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && (aliases[i]->trait_method->mname_len == fnname_len) && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } i++; } } if (zend_hash_add(target, lcname, fnname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } } efree(lcname); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* Copies function table entries to target function table with applied aliasing */ static void zend_traits_copy_trait_function_table(HashTable *target, zend_class_entry *target_ce, HashTable *source, zend_trait_alias** aliases, HashTable* exclude_table TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_arguments(source TSRMLS_CC, (apply_func_args_t)zend_traits_copy_functions, 4, target, target_ce, aliases, exclude_table); } /* }}} */ static void zend_traits_init_trait_structures(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i, j = 0; zend_trait_precedence *cur_precedence; zend_trait_method_reference *cur_method_ref; /* resolve class references */ if (ce->trait_precedences) { i = 0; while ((cur_precedence = ce->trait_precedences[i])) { if (cur_precedence->exclude_from_classes) { cur_precedence->trait_method->ce = zend_fetch_class(cur_precedence->trait_method->class_name, cur_precedence->trait_method->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); j = 0; while (cur_precedence->exclude_from_classes[j]) { char* class_name = (char*)cur_precedence->exclude_from_classes[j]; zend_uint name_length = strlen(class_name); cur_precedence->exclude_from_classes[j] = zend_fetch_class(class_name, name_length, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); efree(class_name); j++; } } i++; } } if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { if (ce->trait_aliases[i]->trait_method->class_name) { cur_method_ref = ce->trait_aliases[i]->trait_method; cur_method_ref->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); } i++; } } } /* }}} */ static void zend_traits_compile_exclude_table(HashTable* exclude_table, zend_trait_precedence **precedences, zend_class_entry *trait) /* {{{ */ { size_t i = 0, j; if (!precedences) { return; } while (precedences[i]) { if (precedences[i]->exclude_from_classes) { j = 0; while (precedences[i]->exclude_from_classes[j]) { if (precedences[i]->exclude_from_classes[j] == trait) { zend_uint lcname_len = precedences[i]->trait_method->mname_len; char *lcname = zend_str_tolower_dup(precedences[i]->trait_method->method_name, lcname_len); if (zend_hash_add(exclude_table, lcname, lcname_len, NULL, 0, NULL) == FAILURE) { efree(lcname); zend_error(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", precedences[i]->trait_method->method_name, trait->name); } efree(lcname); } ++j; } } ++i; } } /* }}} */ static void zend_do_traits_method_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { HashTable** function_tables; HashTable* resulting_table; HashTable exclude_table; size_t i; /* prepare copies of trait function tables for combination */ function_tables = malloc(sizeof(HashTable*) * ce->num_traits); resulting_table = (HashTable *) malloc(sizeof(HashTable)); /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(resulting_table, 10, NULL, NULL, 1, 0); for (i = 0; i < ce->num_traits; i++) { function_tables[i] = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(function_tables[i], ce->traits[i]->function_table.nNumOfElements, NULL, NULL, 1, 0); if (ce->trait_precedences) { /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(&exclude_table, 2, NULL, NULL, 0, 0); zend_traits_compile_exclude_table(&exclude_table, ce->trait_precedences, ce->traits[i]); /* copies functions, applies defined aliasing, and excludes unused trait methods */ zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, &exclude_table TSRMLS_CC); zend_hash_graceful_destroy(&exclude_table); } else { zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, NULL TSRMLS_CC); } } /* now merge trait methods */ for (i = 0; i < ce->num_traits; i++) { zend_hash_apply_with_arguments(function_tables[i] TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions, 5, i, ce->num_traits, resulting_table, function_tables, ce); } /* Now the resulting_table contains all trait methods we would have to * add to the class in the following step the methods are inserted into the method table * if there is already a method with the same name it is replaced iff ce != fn.scope * --> all inherited methods are overridden, methods defined in the class are left untouched */ zend_hash_apply_with_arguments(resulting_table TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions_to_class, 1, ce); /* free temporary function tables */ for (i = 0; i < ce->num_traits; i++) { /* zend_hash_destroy(function_tables[i]); */ zend_hash_graceful_destroy(function_tables[i]); free(function_tables[i]); } free(function_tables); /* free temporary resulting table */ /* zend_hash_destroy(resulting_table); */ zend_hash_graceful_destroy(resulting_table); free(resulting_table); } /* }}} */ static zend_class_entry* find_first_definition(zend_class_entry *ce, size_t current_trait, const char* prop_name, int prop_name_length, ulong prop_hash, zend_class_entry *coliding_ce) /* {{{ */ { size_t i; zend_property_info *coliding_prop; for (i = 0; (i < current_trait) && (i < ce->num_traits); i++) { if (zend_hash_quick_find(&ce->traits[i]->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS) { return ce->traits[i]; } } return coliding_ce; } /* }}} */ static void zend_do_traits_property_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i; zend_property_info *property_info; zend_property_info *coliding_prop; zval compare_result; const char* prop_name; int prop_name_length; ulong prop_hash; const char* class_name_unused; zend_bool prop_found; zend_bool not_compatible; zval* prop_value; /* In the following steps the properties are inserted into the property table * for that, a very strict approach is applied: * - check for compatibility, if not compatible with any property in class -> fatal * - if compatible, then strict notice */ for (i = 0; i < ce->num_traits; i++) { for (zend_hash_internal_pointer_reset(&ce->traits[i]->properties_info); zend_hash_get_current_data(&ce->traits[i]->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->traits[i]->properties_info)) { /* first get the unmangeld name if necessary, * then check whether the property is already there */ if ((property_info->flags & ZEND_ACC_PPP_MASK) == ZEND_ACC_PUBLIC) { prop_hash = property_info->h; prop_name = property_info->name; prop_name_length = property_info->name_length; prop_found = zend_hash_quick_find(&ce->properties_info, property_info->name, property_info->name_length+1, property_info->h, (void **) &coliding_prop) == SUCCESS; } else { /* for private and protected we need to unmangle the names */ zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name_unused, &prop_name); prop_name_length = strlen(prop_name); prop_hash = zend_get_hash_value(prop_name, prop_name_length + 1); prop_found = zend_hash_quick_find(&ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS; } /* next: check for conflicts with current class */ if (prop_found) { if (coliding_prop->flags & ZEND_ACC_SHADOW) { /* this one is inherited, lets look it up in its own class */ zend_hash_quick_find(&coliding_prop->ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop); } if ((coliding_prop->flags & ZEND_ACC_PPP_MASK) == (property_info->flags & ZEND_ACC_PPP_MASK)) { /* flags are identical, now the value needs to be checked */ if (property_info->flags & ZEND_ACC_STATIC) { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_static_members_table[coliding_prop->offset], ce->traits[i]->default_static_members_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } else { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_properties_table[coliding_prop->offset], ce->traits[i]->default_properties_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } } else { /* the flags are not identical, thus, we assume properties are not compatible */ not_compatible = 1; } if (not_compatible) { zend_error(E_COMPILE_ERROR, "%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } else { zend_error(E_STRICT, "%s and %s define the same property ($%s) in the composition of %s. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } } /* property not found, so lets add it */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); zend_declare_property_ex(ce, prop_name, prop_name_length, prop_value, property_info->flags, property_info->doc_comment, property_info->doc_comment_len TSRMLS_CC); } } } /* }}} */ ZEND_API void zend_do_bind_traits(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { if (ce->num_traits <= 0) { return; } /* complete initialization of trait strutures in ce */ zend_traits_init_trait_structures(ce TSRMLS_CC); /* first care about all methods to be flattened into the class */ zend_do_traits_method_binding(ce TSRMLS_CC); /* then flatten the properties into it, to, mostly to notfiy developer about problems */ zend_do_traits_property_binding(ce TSRMLS_CC); /* verify that all abstract methods from traits have been implemented */ zend_verify_abstract_class(ce TSRMLS_CC); /* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */ if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { ce->ce_flags -= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } } /* }}} */ ZEND_API int do_bind_function(const zend_op_array *op_array, zend_op *opline, HashTable *function_table, zend_bool compile_time) /* {{{ */ { zend_function *function; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } zend_hash_quick_find(function_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void *) &function); if (zend_hash_quick_add(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), function, sizeof(zend_function), NULL)==FAILURE) { int error_level = compile_time ? E_COMPILE_ERROR : E_ERROR; zend_function *old_function; if (zend_hash_quick_find(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), (void *) &old_function)==SUCCESS && old_function->type == ZEND_USER_FUNCTION && old_function->op_array.last > 0) { zend_error(error_level, "Cannot redeclare %s() (previously declared in %s:%d)", function->common.function_name, old_function->op_array.filename, old_function->op_array.opcodes[0].lineno); } else { zend_error(error_level, "Cannot redeclare %s()", function->common.function_name); } return FAILURE; } else { (*function->op_array.refcount)++; function->op_array.static_variables = NULL; /* NULL out the unbound function */ return SUCCESS; } } /* }}} */ void zend_add_trait_precedence(znode *precedence_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_precedences, precedence_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_add_trait_alias(znode *alias_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_aliases, alias_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_prepare_reference(znode *result, znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { zend_trait_method_reference *method_ref = emalloc(sizeof(zend_trait_method_reference)); method_ref->ce = NULL; /* REM: There should not be a need for copying, zend_do_begin_class_declaration is also just using that string */ if (class_name) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); method_ref->class_name = Z_STRVAL(class_name->u.constant); method_ref->cname_len = Z_STRLEN(class_name->u.constant); } else { method_ref->class_name = NULL; method_ref->cname_len = 0; } method_ref->method_name = Z_STRVAL(method_name->u.constant); method_ref->mname_len = Z_STRLEN(method_name->u.constant); result->u.op.ptr = method_ref; result->op_type = IS_TMP_VAR; } /* }}} */ void zend_prepare_trait_alias(znode *result, znode *method_reference, znode *modifiers, znode *alias TSRMLS_DC) /* {{{ */ { zend_trait_alias *trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_alias->modifiers = Z_LVAL(modifiers->u.constant); if (Z_LVAL(modifiers->u.constant) == ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot use 'static' as method modifier"); return; } if (alias) { trait_alias->alias = Z_STRVAL(alias->u.constant); trait_alias->alias_len = Z_STRLEN(alias->u.constant); } else { trait_alias->alias = NULL; } trait_alias->function = NULL; result->u.op.ptr = trait_alias; } /* }}} */ void zend_prepare_trait_precedence(znode *result, znode *method_reference, znode *trait_list TSRMLS_DC) /* {{{ */ { zend_trait_precedence *trait_precedence = emalloc(sizeof(zend_trait_precedence)); trait_precedence->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_precedence->exclude_from_classes = (zend_class_entry**) trait_list->u.op.ptr; trait_precedence->function = NULL; result->u.op.ptr = trait_precedence; } /* }}} */ ZEND_API zend_class_entry *do_bind_class(const zend_op_array* op_array, const zend_op *opline, HashTable *class_table, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } if (zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce)==FAILURE) { zend_error(E_COMPILE_ERROR, "Internal Zend error - Missing class information for %s", Z_STRVAL_P(op1)); return NULL; } else { ce = *pce; } ce->refcount++; if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), &ce, sizeof(zend_class_entry *), NULL)==FAILURE) { ce->refcount--; if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return NULL; } else { if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLEMENT_INTERFACES))) { zend_verify_abstract_class(ce TSRMLS_CC); } return ce; } } /* }}} */ ZEND_API zend_class_entry *do_bind_inherited_class(const zend_op_array *op_array, const zend_op *opline, HashTable *class_table, zend_class_entry *parent_ce, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; int found_ce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } found_ce = zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce); if (found_ce == FAILURE) { if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", Z_STRVAL_P(op2)); } return NULL; } else { ce = *pce; } if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ce->name, parent_ce->name); } else if ((parent_ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ce->name, parent_ce->name); } zend_do_inheritance(ce, parent_ce TSRMLS_CC); ce->refcount++; /* Register the derived class */ if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), pce, sizeof(zend_class_entry *), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return ce; } /* }}} */ void zend_do_early_binding(TSRMLS_D) /* {{{ */ { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; HashTable *table; while (opline->opcode == ZEND_TICKS && opline > CG(active_op_array)->opcodes) { opline--; } switch (opline->opcode) { case ZEND_DECLARE_FUNCTION: if (do_bind_function(CG(active_op_array), opline, CG(function_table), 1) == FAILURE) { return; } table = CG(function_table); break; case ZEND_DECLARE_CLASS: if (do_bind_class(CG(active_op_array), opline, CG(class_table), 1 TSRMLS_CC) == NULL) { return; } table = CG(class_table); break; case ZEND_DECLARE_INHERITED_CLASS: { zend_op *fetch_class_opline = opline-1; zval *parent_name; zend_class_entry **pce; parent_name = &CONSTANT(fetch_class_opline->op2.constant); if ((zend_lookup_class(Z_STRVAL_P(parent_name), Z_STRLEN_P(parent_name), &pce TSRMLS_CC) == FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_CLASSES) && ((*pce)->type == ZEND_INTERNAL_CLASS))) { if (CG(compiler_options) & ZEND_COMPILE_DELAYED_BINDING) { zend_uint *opline_num = &CG(active_op_array)->early_binding; while (*opline_num != -1) { opline_num = &CG(active_op_array)->opcodes[*opline_num].result.opline_num; } *opline_num = opline - CG(active_op_array)->opcodes; opline->opcode = ZEND_DECLARE_INHERITED_CLASS_DELAYED; opline->result_type = IS_UNUSED; opline->result.opline_num = -1; } return; } if (do_bind_inherited_class(CG(active_op_array), opline, CG(class_table), *pce, 1 TSRMLS_CC) == NULL) { return; } /* clear unnecessary ZEND_FETCH_CLASS opcode */ zend_del_literal(CG(active_op_array), fetch_class_opline->op2.constant); MAKE_NOP(fetch_class_opline); table = CG(class_table); break; } case ZEND_VERIFY_ABSTRACT_CLASS: case ZEND_ADD_INTERFACE: case ZEND_ADD_TRAIT: case ZEND_BIND_TRAITS: /* We currently don't early-bind classes that implement interfaces */ /* Classes with traits are handled exactly the same, no early-bind here */ return; default: zend_error(E_COMPILE_ERROR, "Invalid binding type"); return; } zend_hash_quick_del(table, Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant)), Z_HASH_P(&CONSTANT(opline->op1.constant))); zend_del_literal(CG(active_op_array), opline->op1.constant); zend_del_literal(CG(active_op_array), opline->op2.constant); MAKE_NOP(opline); } /* }}} */ ZEND_API void zend_do_delayed_early_binding(const zend_op_array *op_array TSRMLS_DC) /* {{{ */ { if (op_array->early_binding != -1) { zend_bool orig_in_compilation = CG(in_compilation); zend_uint opline_num = op_array->early_binding; zend_class_entry **pce; CG(in_compilation) = 1; while (opline_num != -1) { if (zend_lookup_class(Z_STRVAL_P(op_array->opcodes[opline_num-1].op2.zv), Z_STRLEN_P(op_array->opcodes[opline_num-1].op2.zv), &pce TSRMLS_CC) == SUCCESS) { do_bind_inherited_class(op_array, &op_array->opcodes[opline_num], EG(class_table), *pce, 0 TSRMLS_CC); } opline_num = op_array->opcodes[opline_num].result.opline_num; } CG(in_compilation) = orig_in_compilation; } } /* }}} */ void zend_do_boolean_or_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_or_end(znode *result, const znode *expr1, const znode *expr2, znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_boolean_and_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_and_end(znode *result, const znode *expr1, const znode *expr2, const znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_do_while_begin(TSRMLS_D) /* {{{ */ { do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_do_while_end(const znode *do_token, const znode *expr_open_bracket, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ; SET_NODE(opline->op1, expr); opline->op2.opline_num = do_token->u.op.opline_num; SET_UNUSED(opline->op2); do_end_loop(expr_open_bracket->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_brk_cont(zend_uchar op, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->op1.opline_num = CG(context).current_brk_cont; SET_UNUSED(opline->op1); if (expr) { if (expr->op_type != IS_CONST) { zend_error(E_COMPILE_ERROR, "'%s' operator with non-constant operand is no longer supported", op == ZEND_BRK ? "break" : "continue"); } else if (Z_TYPE(expr->u.constant) != IS_LONG || Z_LVAL(expr->u.constant) < 1) { zend_error(E_COMPILE_ERROR, "'%s' operator accepts only positive numbers", op == ZEND_BRK ? "break" : "continue"); } SET_NODE(opline->op2, expr); } else { LITERAL_LONG(opline->op2, 1); opline->op2_type = IS_CONST; } } /* }}} */ void zend_do_switch_cond(const znode *cond TSRMLS_DC) /* {{{ */ { zend_switch_entry switch_entry; switch_entry.cond = *cond; switch_entry.default_case = -1; switch_entry.control_var = -1; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_switch_end(const znode *case_list TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); /* add code to jmp to default case */ if (switch_entry_ptr->default_case != -1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->op1.opline_num = switch_entry_ptr->default_case; } if (case_list->op_type != IS_UNUSED) { /* non-empty switch */ int next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* remember break/continue loop information */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; if (switch_entry_ptr->cond.op_type==IS_VAR || switch_entry_ptr->cond.op_type==IS_TMP_VAR) { /* emit free for the switch condition*/ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry_ptr->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_UNUSED(opline->op2); } if (switch_entry_ptr->cond.op_type == IS_CONST) { zval_dtor(&switch_entry_ptr->cond.u.constant); } zend_stack_del_top(&CG(switch_cond_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_case_before_statement(const znode *case_list, znode *case_token, const znode *case_expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); int next_op_number; zend_switch_entry *switch_entry_ptr; znode result; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); if (switch_entry_ptr->control_var == -1) { switch_entry_ptr->control_var = get_temporary_variable(CG(active_op_array)); } opline->opcode = ZEND_CASE; opline->result.var = switch_entry_ptr->control_var; opline->result_type = IS_TMP_VAR; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_NODE(opline->op2, case_expr); if (opline->op1_type == IS_CONST) { zval_copy_ctor(&CONSTANT(opline->op1.constant)); } GET_NODE(&result, opline->result); next_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, &result); SET_UNUSED(opline->op2); case_token->u.op.opline_num = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_case_after_statement(znode *result, const znode *case_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); result->u.op.opline_num = next_op_number; switch (CG(active_op_array)->opcodes[case_token->u.op.opline_num].opcode) { case ZEND_JMP: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); break; case ZEND_JMPZ: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); break; } } /* }}} */ void zend_do_default_before_statement(const znode *case_list, znode *default_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); default_token->u.op.opline_num = next_op_number; next_op_number = get_next_op_number(CG(active_op_array)); switch_entry_ptr->default_case = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_begin_class_declaration(const znode *class_token, znode *class_name, const znode *parent_class_name TSRMLS_DC) /* {{{ */ { zend_op *opline; int doing_inheritance = 0; zend_class_entry *new_class_entry; char *lcname; int error = 0; zval **ns_name, key; if (CG(active_class_entry)) { zend_error(E_COMPILE_ERROR, "Class declarations may not be nested"); return; } lcname = zend_str_tolower_dup(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); if (!(strcmp(lcname, "self") && strcmp(lcname, "parent"))) { efree(lcname); zend_error(E_COMPILE_ERROR, "Cannot use '%s' as class name as it is reserved", Z_STRVAL(class_name->u.constant)); } /* Class name must not conflict with import names */ if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns_name) == SUCCESS) { error = 1; } if (CG(current_namespace)) { /* Prefix class name with name of current namespace */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); class_name = &tmp; efree(lcname); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); } if (error) { char *tmp = zend_str_tolower_dup(Z_STRVAL_PP(ns_name), Z_STRLEN_PP(ns_name)); if (Z_STRLEN_PP(ns_name) != Z_STRLEN(class_name->u.constant) || memcmp(tmp, lcname, Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "Cannot declare class %s because the name is already in use", Z_STRVAL(class_name->u.constant)); } efree(tmp); } new_class_entry = emalloc(sizeof(zend_class_entry)); new_class_entry->type = ZEND_USER_CLASS; new_class_entry->name = zend_new_interned_string(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1, 1 TSRMLS_CC); new_class_entry->name_length = Z_STRLEN(class_name->u.constant); zend_initialize_class_data(new_class_entry, 1 TSRMLS_CC); new_class_entry->info.user.filename = zend_get_compiled_filename(TSRMLS_C); new_class_entry->info.user.line_start = class_token->u.op.opline_num; new_class_entry->ce_flags |= class_token->EA; if (parent_class_name && parent_class_name->op_type != IS_UNUSED) { switch (parent_class_name->EA) { case ZEND_FETCH_CLASS_SELF: zend_error(E_COMPILE_ERROR, "Cannot use 'self' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_PARENT: zend_error(E_COMPILE_ERROR, "Cannot use 'parent' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use 'static' as class name as it is reserved"); break; default: break; } doing_inheritance = 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, new_class_entry->name_length TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; if (doing_inheritance) { /* Make sure a trait does not try to extend a class */ if ((new_class_entry->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "A trait (%s) cannot extend a class", new_class_entry->name); } opline->extended_value = parent_class_name->u.op.var; opline->opcode = ZEND_DECLARE_INHERITED_CLASS; } else { opline->opcode = ZEND_DECLARE_CLASS; } LITERAL_STRINGL(opline->op2, lcname, new_class_entry->name_length, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); zend_hash_quick_update(CG(class_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &new_class_entry, sizeof(zend_class_entry *), NULL); CG(active_class_entry) = new_class_entry; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(&CG(implementing_class), opline->result); if (CG(doc_comment)) { CG(active_class_entry)->info.user.doc_comment = CG(doc_comment); CG(active_class_entry)->info.user.doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ static void do_verify_abstract_class(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_VERIFY_ABSTRACT_CLASS; SET_NODE(opline->op1, &CG(implementing_class)); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_class_declaration(const znode *class_token, const znode *parent_token TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); if (ce->constructor) { ce->constructor->common.fn_flags |= ZEND_ACC_CTOR; if (ce->constructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Constructor %s::%s() cannot be static", ce->name, ce->constructor->common.function_name); } } if (ce->destructor) { ce->destructor->common.fn_flags |= ZEND_ACC_DTOR; if (ce->destructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Destructor %s::%s() cannot be static", ce->name, ce->destructor->common.function_name); } } if (ce->clone) { ce->clone->common.fn_flags |= ZEND_ACC_CLONE; if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static", ce->name, ce->clone->common.function_name); } } ce->info.user.line_end = zend_get_compiled_lineno(TSRMLS_C); /* Check for traits and proceed like with interfaces. * The only difference will be a combined handling of them in the end. * Thus, we need another opcode here. */ if (ce->num_traits > 0) { zend_op *opline; ce->traits = NULL; ce->num_traits = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_TRAITS; /* opcode generation: */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BIND_TRAITS; SET_NODE(opline->op1, &CG(implementing_class)); } if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) && ((parent_token->op_type != IS_UNUSED) || (ce->num_interfaces > 0))) { zend_verify_abstract_class(ce TSRMLS_CC); if (ce->num_interfaces) { do_verify_abstract_class(TSRMLS_C); } } /* Inherit interfaces; reset number to zero, we need it for above check and * will restore it during actual implementation. * The ZEND_ACC_IMPLEMENT_INTERFACES flag disables double call to * zend_verify_abstract_class() */ if (ce->num_interfaces > 0) { ce->interfaces = NULL; ce->num_interfaces = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_INTERFACES; } CG(active_class_entry) = NULL; } /* }}} */ void zend_do_implements_interface(znode *interface_name TSRMLS_DC) /* {{{ */ { zend_op *opline; /* Traits can not implement interfaces */ if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface on '%s' since it is a Trait", Z_STRVAL(interface_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(interface_name->u.constant), Z_STRLEN(interface_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface name as it is reserved", Z_STRVAL(interface_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_INTERFACE; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(interface_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = (opline->extended_value & ~ZEND_FETCH_CLASS_MASK) | ZEND_FETCH_CLASS_INTERFACE; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &interface_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_interfaces++; } /* }}} */ void zend_do_implements_trait(znode *trait_name TSRMLS_DC) /* {{{ */ { zend_op *opline; switch (zend_get_class_fetch_type(Z_STRVAL(trait_name->u.constant), Z_STRLEN(trait_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as trait name as it is reserved", Z_STRVAL(trait_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_TRAIT; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(trait_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = ZEND_FETCH_CLASS_TRAIT; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &trait_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_traits++; } /* }}} */ ZEND_API void zend_mangle_property_name(char **dest, int *dest_length, const char *src1, int src1_length, const char *src2, int src2_length, int internal) /* {{{ */ { char *prop_name; int prop_name_length; prop_name_length = 1 + src1_length + 1 + src2_length; prop_name = pemalloc(prop_name_length + 1, internal); prop_name[0] = '\0'; memcpy(prop_name + 1, src1, src1_length+1); memcpy(prop_name + 1 + src1_length + 1, src2, src2_length+1); *dest = prop_name; *dest_length = prop_name_length; } /* }}} */ static int zend_strnlen(const char* s, int maxlen) /* {{{ */ { int len = 0; while (*s++ && maxlen--) len++; return len; } /* }}} */ ZEND_API int zend_unmangle_property_name(const char *mangled_property, int len, const char **class_name, const char **prop_name) /* {{{ */ { int class_name_len; *class_name = NULL; if (mangled_property[0]!=0) { *prop_name = mangled_property; return SUCCESS; } if (len < 3 || mangled_property[1]==0) { zend_error(E_NOTICE, "Illegal member variable name"); *prop_name = mangled_property; return FAILURE; } class_name_len = zend_strnlen(mangled_property+1, --len - 1) + 1; if (class_name_len >= len || mangled_property[class_name_len]!=0) { zend_error(E_NOTICE, "Corrupt member variable name"); *prop_name = mangled_property; return FAILURE; } *class_name = mangled_property+1; *prop_name = (*class_name)+class_name_len; return SUCCESS; } /* }}} */ void zend_do_declare_property(const znode *var_name, const znode *value, zend_uint access_type TSRMLS_DC) /* {{{ */ { zval *property; zend_property_info *existing_property_info; char *comment = NULL; int comment_len = 0; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Interfaces may not include member variables"); } if (access_type & ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Properties cannot be declared abstract"); } if (access_type & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot declare property %s::$%s final, the final modifier is allowed only for methods and classes", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } if (zend_hash_find(&CG(active_class_entry)->properties_info, var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, (void **) &existing_property_info)==SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::$%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } ALLOC_ZVAL(property); if (value) { *property = value->u.constant; } else { INIT_PZVAL(property); Z_TYPE_P(property) = IS_NULL; } if (CG(doc_comment)) { comment = CG(doc_comment); comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } zend_declare_property_ex(CG(active_class_entry), zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len + 1, 0 TSRMLS_CC), var_name->u.constant.value.str.len, property, access_type, comment, comment_len TSRMLS_CC); efree(var_name->u.constant.value.str.val); } /* }}} */ void zend_do_declare_class_constant(znode *var_name, const znode *value TSRMLS_DC) /* {{{ */ { zval *property; const char *cname = NULL; int result; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed in class constants"); return; } if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Traits cannot have constants"); return; } ALLOC_ZVAL(property); *property = value->u.constant; cname = zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, 0 TSRMLS_CC); if (IS_INTERNED(cname)) { result = zend_hash_quick_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, INTERNED_HASH(cname), &property, sizeof(zval *), NULL); } else { result = zend_hash_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, &property, sizeof(zval *), NULL); } if (result == FAILURE) { FREE_ZVAL(property); zend_error(E_COMPILE_ERROR, "Cannot redefine class constant %s::%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } FREE_PNODE(var_name); if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_fetch_property(znode *result, znode *object, const znode *property TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (object->op_type == IS_CV) { if (object->u.op.var == CG(active_op_array)->this_var) { object->op_type = IS_UNUSED; /* this means $this for objects */ } } else if (fetch_list_ptr->count == 1) { zend_llist_element *le = fetch_list_ptr->head; zend_op *opline_ptr = (zend_op *) le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); SET_UNUSED(opline_ptr->op1); /* this means $this for objects */ SET_NODE(opline_ptr->op2, property); /* if it was usual fetch, we change it to object fetch */ switch (opline_ptr->opcode) { case ZEND_FETCH_W: opline_ptr->opcode = ZEND_FETCH_OBJ_W; break; case ZEND_FETCH_R: opline_ptr->opcode = ZEND_FETCH_OBJ_R; break; case ZEND_FETCH_RW: opline_ptr->opcode = ZEND_FETCH_OBJ_RW; break; case ZEND_FETCH_IS: opline_ptr->opcode = ZEND_FETCH_OBJ_IS; break; case ZEND_FETCH_UNSET: opline_ptr->opcode = ZEND_FETCH_OBJ_UNSET; break; case ZEND_FETCH_FUNC_ARG: opline_ptr->opcode = ZEND_FETCH_OBJ_FUNC_ARG; break; } if (opline_ptr->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline_ptr->op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline_ptr->op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op2.constant); } GET_NODE(result, opline_ptr->result); return; } } if (zend_is_function_or_method_call(object)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, object); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_OBJ_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, object); SET_NODE(opline.op2, property); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline.op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op2.constant); } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void zend_do_halt_compiler_register(TSRMLS_D) /* {{{ */ { char *name, *cfilename; char haltoff[] = "__COMPILER_HALT_OFFSET__"; int len, clen; cfilename = zend_get_compiled_filename(TSRMLS_C); clen = strlen(cfilename); zend_mangle_property_name(&name, &len, haltoff, sizeof(haltoff) - 1, cfilename, clen, 0); zend_register_long_constant(name, len+1, zend_get_scanned_file_offset(TSRMLS_C), CONST_CS, 0 TSRMLS_CC); pefree(name, 0); if (CG(in_namespace)) { zend_do_end_namespace(TSRMLS_C); } } /* }}} */ void zend_do_push_object(const znode *object TSRMLS_DC) /* {{{ */ { zend_stack_push(&CG(object_stack), object, sizeof(znode)); } /* }}} */ void zend_do_pop_object(znode *object TSRMLS_DC) /* {{{ */ { if (object) { znode *tmp; zend_stack_top(&CG(object_stack), (void **) &tmp); *object = *tmp; } zend_stack_del_top(&CG(object_stack)); } /* }}} */ void zend_do_begin_new_object(znode *new_token, znode *class_type TSRMLS_DC) /* {{{ */ { zend_op *opline; unsigned char *ptr = NULL; new_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_NEW; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, class_type); SET_UNUSED(opline->op2); zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(unsigned char *)); } /* }}} */ void zend_do_end_new_object(znode *result, const znode *new_token, const znode *argument_list TSRMLS_DC) /* {{{ */ { znode ctor_result; zend_do_end_function_call(NULL, &ctor_result, argument_list, 1, 0 TSRMLS_CC); zend_do_free(&ctor_result TSRMLS_CC); CG(active_op_array)->opcodes[new_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, CG(active_op_array)->opcodes[new_token->u.op.opline_num].result); } /* }}} */ static zend_constant* zend_get_ct_const(const zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = NULL; if (Z_STRVAL_P(const_name)[0] == '\\') { if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name), (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name)-1); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name), (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } } else if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)+1, (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name)+1, (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } if (c->flags & CONST_CT_SUBST) { return c; } if (all_internal_constants_substitution && (c->flags & CONST_PERSISTENT) && !(CG(compiler_options) & ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION) && Z_TYPE(c->value) != IS_CONSTANT && Z_TYPE(c->value) != IS_CONSTANT_ARRAY) { return c; } return NULL; } /* }}} */ static int zend_constant_ct_subst(znode *result, zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = zend_get_ct_const(const_name, all_internal_constants_substitution TSRMLS_CC); if (c) { zval_dtor(const_name); result->op_type = IS_CONST; result->u.constant = c->value; zval_copy_ctor(&result->u.constant); INIT_PZVAL(&result->u.constant); return 1; } return 0; } /* }}} */ void zend_do_fetch_constant(znode *result, znode *constant_container, znode *constant_name, int mode, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; zend_op *opline; int type; char *compound; ulong fetch_type = 0; if (constant_container) { switch (mode) { case ZEND_CT: /* this is a class constant */ type = zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant)); if (ZEND_FETCH_CLASS_STATIC == type) { zend_error(E_ERROR, "\"static::\" is not allowed in compile-time constants"); } else if (ZEND_FETCH_CLASS_DEFAULT == type) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } zend_do_build_full_name(NULL, constant_container, constant_name, 1 TSRMLS_CC); *result = *constant_container; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: if (constant_container->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant))) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } else { zend_do_fetch_class(&tmp, constant_container TSRMLS_CC); constant_container = &tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); if (constant_container->op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &constant_container->u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, constant_container); } SET_NODE(opline->op2, constant_name); CALCULATE_LITERAL_HASH(opline->op2.constant); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } GET_NODE(result, opline->result); break; } return; } /* namespace constant */ /* only one that did not contain \ from the start can be converted to string if unknown */ switch (mode) { case ZEND_CT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); /* this is a namespace constant, or an unprefixed constant */ if (zend_constant_ct_subst(result, &constant_name->u.constant, 0 TSRMLS_CC)) { break; } zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(!compound) { fetch_type |= IS_CONSTANT_UNQUALIFIED; } *result = *constant_name; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(zend_constant_ct_subst(result, &constant_name->u.constant, 1 TSRMLS_CC)) { break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; if (compound) { /* the name is unambiguous */ opline->extended_value = 0; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } else { opline->extended_value = IS_CONSTANT_UNQUALIFIED; if (CG(current_namespace)) { opline->extended_value |= IS_CONSTANT_IN_NAMESPACE; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 1 TSRMLS_CC); } else { opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } } GET_CACHE_SLOT(opline->op2.constant); break; } } /* }}} */ void zend_do_shell_exec(znode *result, const znode *cmd TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); switch (cmd->op_type) { case IS_CONST: case IS_TMP_VAR: opline->opcode = ZEND_SEND_VAL; break; default: opline->opcode = ZEND_SEND_VAR; break; } SET_NODE(opline->op1, cmd); opline->op2.opline_num = 0; opline->extended_value = ZEND_DO_FCALL; SET_UNUSED(opline->op2); /* FIXME: exception support not added to this op2 */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DO_FCALL; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; LITERAL_STRINGL(opline->op1, estrndup("shell_exec", sizeof("shell_exec")-1), sizeof("shell_exec")-1, 0); CALCULATE_LITERAL_HASH(opline->op1.constant); opline->op1_type = IS_CONST; GET_CACHE_SLOT(opline->op1.constant); opline->extended_value = 1; SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_init_array(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_ARRAY; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; GET_NODE(result, opline->result); if (expr) { SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } } else { SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_array_element(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_ARRAY_ELEMENT; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_static_array_element(znode *result, znode *offset, const znode *expr) /* {{{ */ { zval *element; ALLOC_ZVAL(element); *element = expr->u.constant; if (offset) { switch (offset->u.constant.type & IS_CONSTANT_TYPE_MASK) { case IS_CONSTANT: /* Ugly hack to denote that this value has a constant index */ Z_TYPE_P(element) |= IS_CONSTANT_INDEX; Z_STRVAL(offset->u.constant) = erealloc(Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+1] = Z_TYPE(offset->u.constant); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+2] = 0; zend_symtable_update(result->u.constant.value.ht, Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_STRING: zend_symtable_update(result->u.constant.value.ht, offset->u.constant.value.str.val, offset->u.constant.value.str.len+1, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_NULL: zend_symtable_update(Z_ARRVAL(result->u.constant), "", 1, &element, sizeof(zval *), NULL); break; case IS_LONG: case IS_BOOL: zend_hash_index_update(Z_ARRVAL(result->u.constant), Z_LVAL(offset->u.constant), &element, sizeof(zval *), NULL); break; case IS_DOUBLE: zend_hash_index_update(Z_ARRVAL(result->u.constant), zend_dval_to_lval(Z_DVAL(offset->u.constant)), &element, sizeof(zval *), NULL); break; case IS_CONSTANT_ARRAY: zend_error(E_ERROR, "Illegal offset type"); break; } } else { zend_hash_next_index_insert(Z_ARRVAL(result->u.constant), &element, sizeof(zval *), NULL); } } /* }}} */ void zend_do_add_list_element(const znode *element TSRMLS_DC) /* {{{ */ { list_llist_element lle; if (element) { zend_check_writable_variable(element); lle.var = *element; zend_llist_copy(&lle.dimensions, &CG(dimension_llist)); zend_llist_prepend_element(&CG(list_llist), &lle); } (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_new_list_begin(TSRMLS_D) /* {{{ */ { int current_dimension = 0; zend_llist_add_element(&CG(dimension_llist), &current_dimension); } /* }}} */ void zend_do_new_list_end(TSRMLS_D) /* {{{ */ { zend_llist_remove_tail(&CG(dimension_llist)); (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_list_init(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(list_stack), &CG(list_llist), sizeof(zend_llist)); zend_stack_push(&CG(list_stack), &CG(dimension_llist), sizeof(zend_llist)); zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_do_new_list_begin(TSRMLS_C); } /* }}} */ void zend_do_list_end(znode *result, znode *expr TSRMLS_DC) /* {{{ */ { zend_llist_element *le; zend_llist_element *dimension; zend_op *opline; znode last_container; le = CG(list_llist).head; while (le) { zend_llist *tmp_dimension_llist = &((list_llist_element *)le->data)->dimensions; dimension = tmp_dimension_llist->head; while (dimension) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (dimension == tmp_dimension_llist->head) { /* first */ last_container = *expr; switch (expr->op_type) { case IS_VAR: case IS_CV: opline->opcode = ZEND_FETCH_DIM_R; break; case IS_TMP_VAR: opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; case IS_CONST: /* fetch_dim_tmp_var will handle this bogus fetch */ zval_copy_ctor(&expr->u.constant); opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; } opline->extended_value |= ZEND_FETCH_ADD_LOCK; } else { opline->opcode = ZEND_FETCH_DIM_R; } opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, &last_container); opline->op2_type = IS_CONST; LITERAL_LONG(opline->op2, *((int *) dimension->data)); GET_NODE(&last_container, opline->result); dimension = dimension->next; } ((list_llist_element *) le->data)->value = last_container; zend_llist_destroy(&((list_llist_element *) le->data)->dimensions); zend_do_assign(result, &((list_llist_element *) le->data)->var, &((list_llist_element *) le->data)->value TSRMLS_CC); zend_do_free(result TSRMLS_CC); le = le->next; } zend_llist_destroy(&CG(dimension_llist)); zend_llist_destroy(&CG(list_llist)); *result = *expr; { zend_llist *p; /* restore previous lists */ zend_stack_top(&CG(list_stack), (void **) &p); CG(dimension_llist) = *p; zend_stack_del_top(&CG(list_stack)); zend_stack_top(&CG(list_stack), (void **) &p); CG(list_llist) = *p; zend_stack_del_top(&CG(list_stack)); } } /* }}} */ void zend_init_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = emalloc(sizeof(void*) * 2); list[0] = item; list[1] = NULL; *(void**)result = list; } /* }}} */ void zend_add_to_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = *(void**)result; size_t n = 0; while (list && list[n]) { n++; } list = erealloc(list, sizeof(void*) * (n+2)); list[n] = item; list[n+1] = NULL; *(void**)result = list; } /* }}} */ void zend_do_fetch_static_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zval *tmp; zend_op *opline; znode lval; znode result; ALLOC_ZVAL(tmp); if (static_assignment) { *tmp = static_assignment->u.constant; } else { INIT_ZVAL(*tmp); } if (!CG(active_op_array)->static_variables) { if (CG(active_op_array)->scope) { CG(active_op_array)->scope->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } ALLOC_HASHTABLE(CG(active_op_array)->static_variables); zend_hash_init(CG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } zend_hash_update(CG(active_op_array)->static_variables, varname->u.constant.value.str.val, varname->u.constant.value.str.len+1, &tmp, sizeof(zval *), NULL); if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (fetch_type == ZEND_FETCH_LEXICAL) ? ZEND_FETCH_R : ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_STATIC; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ if (fetch_type == ZEND_FETCH_LEXICAL) { znode dummy; zend_do_begin_variable_parse(TSRMLS_C); zend_do_assign(&dummy, &lval, &result TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } else { zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); } CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_fetch_lexical_variable(znode *varname, zend_bool is_ref TSRMLS_DC) /* {{{ */ { znode value; if (Z_STRLEN(varname->u.constant) == sizeof("this") - 1 && memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this") - 1) == 0) { zend_error(E_COMPILE_ERROR, "Cannot use $this as lexical variable"); return; } value.op_type = IS_CONST; ZVAL_NULL(&value.u.constant); Z_TYPE(value.u.constant) |= is_ref ? IS_LEXICAL_REF : IS_LEXICAL_VAR; Z_SET_REFCOUNT_P(&value.u.constant, 1); Z_UNSET_ISREF_P(&value.u.constant); zend_do_fetch_static_variable(varname, &value, is_ref ? ZEND_FETCH_STATIC : ZEND_FETCH_LEXICAL TSRMLS_CC); } /* }}} */ void zend_do_fetch_global_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zend_op *opline; znode lval; znode result; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = fetch_type; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_cast(znode *result, const znode *expr, int type TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CAST; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } /* }}} */ void zend_do_include_or_eval(int type, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_do_extended_fcall_begin(TSRMLS_C); { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INCLUDE_OR_EVAL; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } zend_do_extended_fcall_end(TSRMLS_C); } /* }}} */ void zend_do_indirect_references(znode *result, const znode *num_references, znode *variable TSRMLS_DC) /* {{{ */ { int i; zend_do_end_variable_parse(variable, BP_VAR_R, 0 TSRMLS_CC); for (i=1; i<num_references->u.constant.value.lval; i++) { fetch_simple_variable_ex(result, variable, 0, ZEND_FETCH_R TSRMLS_CC); *variable = *result; } zend_do_begin_variable_parse(TSRMLS_C); fetch_simple_variable(result, variable, 1 TSRMLS_CC); /* there is a chance someone is accessing $this */ if (CG(active_op_array)->scope && CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } /* }}} */ void zend_do_unset(const znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_UNSET_VAR; SET_NODE(opline->op1, variable); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); opline->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_UNSET: last_op->opcode = ZEND_UNSET_VAR; SET_UNUSED(last_op->result); break; case ZEND_FETCH_DIM_UNSET: last_op->opcode = ZEND_UNSET_DIM; SET_UNUSED(last_op->result); break; case ZEND_FETCH_OBJ_UNSET: last_op->opcode = ZEND_UNSET_OBJ; SET_UNUSED(last_op->result); break; } } } /* }}} */ void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_do_end_variable_parse(variable, BP_VAR_IS, 0 TSRMLS_CC); zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { last_op = get_next_op(CG(active_op_array) TSRMLS_CC); last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; SET_NODE(last_op->op1, variable); SET_UNUSED(last_op->op2); last_op->result.var = get_temporary_variable(CG(active_op_array)); last_op->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; break; case ZEND_FETCH_DIM_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_DIM_OBJ; break; case ZEND_FETCH_OBJ_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_PROP_OBJ; break; } } last_op->result_type = IS_TMP_VAR; last_op->extended_value |= type; GET_NODE(result, last_op->result); } /* }}} */ void zend_do_instanceof(znode *result, const znode *expr, const znode *class_znode, int type TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline->opcode == ZEND_FETCH_CLASS) { opline->extended_value |= ZEND_FETCH_CLASS_NO_AUTOLOAD; } } if (expr->op_type == IS_CONST) { zend_error(E_COMPILE_ERROR, "instanceof expects an object instance, constant given"); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INSTANCEOF; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_NODE(opline->op2, class_znode); GET_NODE(result, opline->result); } /* }}} */ void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_bool is_variable; zend_bool push_container = 0; zend_op dummy_opline; if (variable) { if (zend_is_function_or_method_call(array)) { is_variable = 0; } else { is_variable = 1; } /* save the location of FETCH_W instruction(s) */ open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); zend_do_end_variable_parse(array, BP_VAR_W, 0 TSRMLS_CC); if (CG(active_op_array)->last > 0 && CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) { /* Only lock the container if we are fetching from a real container and not $this */ if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1_type == IS_VAR) { CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK; push_container = 1; } } } else { is_variable = 0; open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* save the location of FE_RESET */ foreach_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* Preform array reset */ opline->opcode = ZEND_FE_RESET; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, array); SET_UNUSED(opline->op2); opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0; COPY_NODE(dummy_opline.result, opline->result); if (push_container) { COPY_NODE(dummy_opline.op1, CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1); } else { dummy_opline.op1_type = IS_UNUSED; } zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); /* save the location of FE_FETCH */ as_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FE_FETCH; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); COPY_NODE(opline->op1, dummy_opline.result); opline->extended_value = 0; SET_UNUSED(opline->op2); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_OP_DATA; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); } /* }}} */ void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC) /* {{{ */ { zend_op *opline; znode dummy, value_node; zend_bool assign_by_ref=0; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num]; if (key->op_type != IS_UNUSED) { znode *tmp; /* switch between the key and value... */ tmp = key; key = value; value = tmp; /* Mark extended_value in case both key and value are being used */ opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; } if ((key->op_type != IS_UNUSED) && (key->EA & ZEND_PARSED_REFERENCE_VARIABLE)) { zend_error(E_COMPILE_ERROR, "Key element cannot be a reference"); } if (value->EA & ZEND_PARSED_REFERENCE_VARIABLE) { assign_by_ref = 1; if (!(opline-1)->extended_value) { zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression"); } /* Mark extended_value for assign-by-reference */ opline->extended_value |= ZEND_FE_FETCH_BYREF; CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; } else { zend_op *foreach_copy; zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.op.opline_num]; zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.op.opline_num]; /* Change "write context" into "read context" */ fetch->extended_value = 0; /* reset ZEND_FE_RESET_VARIABLE */ while (fetch != end) { --fetch; if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } if (fetch->opcode == ZEND_SEPARATE) { MAKE_NOP(fetch); } else { fetch->opcode -= 3; /* FETCH_W -> FETCH_R */ } } /* prevent double SWITCH_FREE */ zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy); foreach_copy->op1_type = IS_UNUSED; } GET_NODE(&value_node, opline->result); if (assign_by_ref) { zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); /* Mark FE_FETCH as IS_VAR as it holds the data directly as a value */ zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC); } else { zend_do_assign(&dummy, value, &value_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } if (key->op_type != IS_UNUSED) { znode key_node; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num+1]; opline->result_type = IS_TMP_VAR; opline->result.opline_num = get_temporary_variable(CG(active_op_array)); GET_NODE(&key_node, opline->result); zend_do_assign(&dummy, key, &key_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_foreach_end(const znode *foreach_token, const znode *as_token TSRMLS_DC) /* {{{ */ { zend_op *container_ptr; zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = as_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_RESET */ CG(active_op_array)->opcodes[as_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_FETCH */ do_end_loop(as_token->u.op.opline_num, 1 TSRMLS_CC); zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr); generate_free_foreach_copy(container_ptr TSRMLS_CC); zend_stack_del_top(&CG(foreach_copy_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_declare_begin(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(declare_stack), &CG(declarables), sizeof(zend_declarables)); } /* }}} */ void zend_do_declare_stmt(znode *var, znode *val TSRMLS_DC) /* {{{ */ { if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "ticks", sizeof("ticks")-1)) { convert_to_long(&val->u.constant); CG(declarables).ticks = val->u.constant; } else if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "encoding", sizeof("encoding")-1)) { if ((Z_TYPE(val->u.constant) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Cannot use constants as encoding"); } /* * Check that the pragma comes before any opcodes. If the compilation * got as far as this, the previous portion of the script must have been * parseable according to the .ini script_encoding setting. We still * want to tell them to put declare() at the top. */ { int num = CG(active_op_array)->last; /* ignore ZEND_EXT_STMT and ZEND_TICKS */ while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Encoding declaration pragma must be the very first statement in the script"); } } if (CG(multibyte)) { const zend_encoding *new_encoding, *old_encoding; zend_encoding_filter old_input_filter; CG(encoding_declared) = 1; convert_to_string(&val->u.constant); new_encoding = zend_multibyte_fetch_encoding(val->u.constant.value.str.val TSRMLS_CC); if (!new_encoding) { zend_error(E_COMPILE_WARNING, "Unsupported encoding [%s]", val->u.constant.value.str.val); } else { old_input_filter = LANG_SCNG(input_filter); old_encoding = LANG_SCNG(script_encoding); zend_multibyte_set_filter(new_encoding TSRMLS_CC); /* need to re-scan if input filter changed */ if (old_input_filter != LANG_SCNG(input_filter) || (old_input_filter && new_encoding != old_encoding)) { zend_multibyte_yyinput_again(old_input_filter, old_encoding TSRMLS_CC); } } } else { zend_error(E_COMPILE_WARNING, "declare(encoding=...) ignored because Zend multibyte feature is turned off by settings"); } zval_dtor(&val->u.constant); } else { zend_error(E_COMPILE_WARNING, "Unsupported declare '%s'", var->u.constant.value.str.val); zval_dtor(&val->u.constant); } zval_dtor(&var->u.constant); } /* }}} */ void zend_do_declare_end(const znode *declare_token TSRMLS_DC) /* {{{ */ { zend_declarables *declarables; zend_stack_top(&CG(declare_stack), (void **) &declarables); /* We should restore if there was more than (current - start) - (ticks?1:0) opcodes */ if ((get_next_op_number(CG(active_op_array)) - declare_token->u.op.opline_num) - ((Z_LVAL(CG(declarables).ticks))?1:0)) { CG(declarables) = *declarables; } } /* }}} */ void zend_do_exit(znode *result, const znode *message TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXIT; SET_NODE(opline->op1, message); SET_UNUSED(opline->op2); result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_BOOL; Z_LVAL(result->u.constant) = 1; } /* }}} */ void zend_do_begin_silence(znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BEGIN_SILENCE; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); GET_NODE(strudel_token, opline->result); } /* }}} */ void zend_do_end_silence(const znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_END_SILENCE; SET_NODE(opline->op1, strudel_token); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_jmp_set(const znode *value, znode *jmp_token, znode *colon_token TSRMLS_DC) /* {{{ */ { int op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP_SET; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, value); SET_UNUSED(opline->op2); GET_NODE(colon_token, opline->result); jmp_token->u.op .opline_num = op_number; INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_jmp_set_else(znode *result, const znode *false_value, const znode *jmp_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_QM_ASSIGN; opline->extended_value = 0; SET_NODE(opline->result, colon_token); SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_qm_op(const znode *cond, znode *qm_token TSRMLS_DC) /* {{{ */ { int jmpz_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); SET_UNUSED(opline->op2); opline->op2.opline_num = jmpz_op_number; GET_NODE(qm_token, opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_qm_true(const znode *true_value, znode *qm_token, znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->opcodes[qm_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array))+1; /* jmp over the ZEND_JMP */ opline->opcode = ZEND_QM_ASSIGN; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, true_value); SET_UNUSED(opline->op2); GET_NODE(qm_token, opline->result); colon_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_qm_false(znode *result, const znode *false_value, const znode *qm_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_QM_ASSIGN; SET_NODE(opline->result, qm_token); SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[colon_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, opline->result); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_extended_info(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_STMT; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_begin(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_BEGIN; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_end(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_END; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_ticks(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_TICKS; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->extended_value = Z_LVAL(CG(declarables).ticks); } /* }}} */ zend_bool zend_is_auto_global_quick(const char *name, uint name_len, ulong hashval TSRMLS_DC) /* {{{ */ { zend_auto_global *auto_global; ulong hash = hashval ? hashval : zend_hash_func(name, name_len+1); if (zend_hash_quick_find(CG(auto_globals), name, name_len+1, hash, (void **) &auto_global)==SUCCESS) { if (auto_global->armed) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } return 1; } return 0; } /* }}} */ zend_bool zend_is_auto_global(const char *name, uint name_len TSRMLS_DC) /* {{{ */ { return zend_is_auto_global_quick(name, name_len, 0 TSRMLS_CC); } /* }}} */ int zend_register_auto_global(const char *name, uint name_len, zend_bool jit, zend_auto_global_callback auto_global_callback TSRMLS_DC) /* {{{ */ { zend_auto_global auto_global; auto_global.name = zend_new_interned_string((char*)name, name_len + 1, 0 TSRMLS_CC); auto_global.name_len = name_len; auto_global.auto_global_callback = auto_global_callback; auto_global.jit = jit; return zend_hash_add(CG(auto_globals), name, name_len+1, &auto_global, sizeof(zend_auto_global), NULL); } /* }}} */ static int zend_auto_global_init(zend_auto_global *auto_global TSRMLS_DC) /* {{{ */ { if (auto_global->jit) { auto_global->armed = 1; } else if (auto_global->auto_global_callback) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } else { auto_global->armed = 0; } return 0; } /* }}} */ ZEND_API void zend_activate_auto_globals(TSRMLS_D) /* {{{ */ { zend_hash_apply(CG(auto_globals), (apply_func_t) zend_auto_global_init TSRMLS_CC); } /* }}} */ int zendlex(znode *zendlval TSRMLS_DC) /* {{{ */ { int retval; if (CG(increment_lineno)) { CG(zend_lineno)++; CG(increment_lineno) = 0; } again: Z_TYPE(zendlval->u.constant) = IS_LONG; retval = lex_scan(&zendlval->u.constant TSRMLS_CC); switch (retval) { case T_COMMENT: case T_DOC_COMMENT: case T_OPEN_TAG: case T_WHITESPACE: goto again; case T_CLOSE_TAG: if (LANG_SCNG(yy_text)[LANG_SCNG(yy_leng)-1] != '>') { CG(increment_lineno) = 1; } if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { goto again; } retval = ';'; /* implicit ; */ break; case T_OPEN_TAG_WITH_ECHO: retval = T_ECHO; break; case T_END_HEREDOC: efree(Z_STRVAL(zendlval->u.constant)); break; } INIT_PZVAL(&zendlval->u.constant); zendlval->op_type = IS_CONST; return retval; } /* }}} */ ZEND_API void zend_initialize_class_data(zend_class_entry *ce, zend_bool nullify_handlers TSRMLS_DC) /* {{{ */ { zend_bool persistent_hashes = (ce->type == ZEND_INTERNAL_CLASS) ? 1 : 0; dtor_func_t zval_ptr_dtor_func = ((persistent_hashes) ? ZVAL_INTERNAL_PTR_DTOR : ZVAL_PTR_DTOR); ce->refcount = 1; ce->ce_flags = 0; ce->default_properties_table = NULL; ce->default_static_members_table = NULL; zend_hash_init_ex(&ce->properties_info, 0, NULL, (dtor_func_t) (persistent_hashes ? zend_destroy_property_info_internal : zend_destroy_property_info), persistent_hashes, 0); zend_hash_init_ex(&ce->constants_table, 0, NULL, zval_ptr_dtor_func, persistent_hashes, 0); zend_hash_init_ex(&ce->function_table, 0, NULL, ZEND_FUNCTION_DTOR, persistent_hashes, 0); if (ce->type == ZEND_INTERNAL_CLASS) { #ifdef ZTS int n = zend_hash_num_elements(CG(class_table)); if (CG(static_members_table) && n >= CG(last_static_member)) { /* Support for run-time declaration: dl() */ CG(last_static_member) = n+1; CG(static_members_table) = realloc(CG(static_members_table), (n+1)*sizeof(zval**)); CG(static_members_table)[n] = NULL; } ce->static_members_table = (zval**)(zend_intptr_t)n; #else ce->static_members_table = NULL; #endif } else { ce->static_members_table = ce->default_static_members_table; ce->info.user.doc_comment = NULL; ce->info.user.doc_comment_len = 0; } ce->default_properties_count = 0; ce->default_static_members_count = 0; if (nullify_handlers) { ce->constructor = NULL; ce->destructor = NULL; ce->clone = NULL; ce->__get = NULL; ce->__set = NULL; ce->__unset = NULL; ce->__isset = NULL; ce->__call = NULL; ce->__callstatic = NULL; ce->__tostring = NULL; ce->create_object = NULL; ce->get_iterator = NULL; ce->iterator_funcs.funcs = NULL; ce->interface_gets_implemented = NULL; ce->get_static_method = NULL; ce->parent = NULL; ce->num_interfaces = 0; ce->interfaces = NULL; ce->num_traits = 0; ce->traits = NULL; ce->trait_aliases = NULL; ce->trait_precedences = NULL; ce->serialize = NULL; ce->unserialize = NULL; ce->serialize_func = NULL; ce->unserialize_func = NULL; if (ce->type == ZEND_INTERNAL_CLASS) { ce->info.internal.module = NULL; ce->info.internal.builtin_functions = NULL; } } } /* }}} */ int zend_get_class_fetch_type(const char *class_name, uint class_name_len) /* {{{ */ { if ((class_name_len == sizeof("self")-1) && !memcmp(class_name, "self", sizeof("self")-1)) { return ZEND_FETCH_CLASS_SELF; } else if ((class_name_len == sizeof("parent")-1) && !memcmp(class_name, "parent", sizeof("parent")-1)) { return ZEND_FETCH_CLASS_PARENT; } else if ((class_name_len == sizeof("static")-1) && !memcmp(class_name, "static", sizeof("static")-1)) { return ZEND_FETCH_CLASS_STATIC; } else { return ZEND_FETCH_CLASS_DEFAULT; } } /* }}} */ ZEND_API const char* zend_get_compiled_variable_name(const zend_op_array *op_array, zend_uint var, int* name_len) /* {{{ */ { if (name_len) { *name_len = op_array->vars[var].name_len; } return op_array->vars[var].name; } /* }}} */ void zend_do_build_namespace_name(znode *result, znode *prefix, znode *name TSRMLS_DC) /* {{{ */ { if (prefix) { *result = *prefix; if (Z_TYPE(result->u.constant) == IS_STRING && Z_STRLEN(result->u.constant) == 0) { /* namespace\ */ if (CG(current_namespace)) { znode tmp; zval_dtor(&result->u.constant); tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(result, NULL, &tmp TSRMLS_CC); } } } else { result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_STRING; Z_STRVAL(result->u.constant) = NULL; Z_STRLEN(result->u.constant) = 0; } /* prefix = result */ zend_do_build_full_name(NULL, result, name, 0 TSRMLS_CC); } /* }}} */ void zend_do_begin_namespace(const znode *name, zend_bool with_bracket TSRMLS_DC) /* {{{ */ { char *lcname; /* handle mixed syntax declaration or nested namespaces */ if (!CG(has_bracketed_namespaces)) { if (CG(current_namespace)) { /* previous namespace declarations were unbracketed */ if (with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } } } else { /* previous namespace declarations were bracketed */ if (!with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } else if (CG(current_namespace) || CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "Namespace declarations cannot be nested"); } } if (((!with_bracket && !CG(current_namespace)) || (with_bracket && !CG(has_bracketed_namespaces))) && CG(active_op_array)->last > 0) { /* ignore ZEND_EXT_STMT and ZEND_TICKS */ int num = CG(active_op_array)->last; while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Namespace declaration statement has to be the very first statement in the script"); } } CG(in_namespace) = 1; if (with_bracket) { CG(has_bracketed_namespaces) = 1; } if (name) { lcname = zend_str_tolower_dup(Z_STRVAL(name->u.constant), Z_STRLEN(name->u.constant)); if (((Z_STRLEN(name->u.constant) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN(name->u.constant) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as namespace name", Z_STRVAL(name->u.constant)); } efree(lcname); if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); } else { ALLOC_ZVAL(CG(current_namespace)); } *CG(current_namespace) = name->u.constant; } else { if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_use(znode *ns_name, znode *new_name, int is_global TSRMLS_DC) /* {{{ */ { char *lcname; zval *name, *ns, tmp; zend_bool warn = 0; zend_class_entry **pce; if (!CG(current_import)) { CG(current_import) = emalloc(sizeof(HashTable)); zend_hash_init(CG(current_import), 0, NULL, ZVAL_PTR_DTOR, 0); } ALLOC_ZVAL(ns); *ns = ns_name->u.constant; if (new_name) { name = &new_name->u.constant; } else { const char *p; /* The form "use A\B" is eqivalent to "use A\B as B". So we extract the last part of compound name to use as a new_name */ name = &tmp; p = zend_memrchr(Z_STRVAL_P(ns), '\\', Z_STRLEN_P(ns)); if (p) { ZVAL_STRING(name, p+1, 1); } else { *name = *ns; zval_copy_ctor(name); warn = !is_global && !CG(current_namespace); } } lcname = zend_str_tolower_dup(Z_STRVAL_P(name), Z_STRLEN_P(name)); if (((Z_STRLEN_P(name) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN_P(name) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because '%s' is a special class name", Z_STRVAL_P(ns), Z_STRVAL_P(name), Z_STRVAL_P(name)); } if (CG(current_namespace)) { /* Prefix import name with current namespace name to avoid conflicts with classes */ char *c_ns_name = emalloc(Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) + 1); zend_str_tolower_copy(c_ns_name, Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); c_ns_name[Z_STRLEN_P(CG(current_namespace))] = '\\'; memcpy(c_ns_name+Z_STRLEN_P(CG(current_namespace))+1, lcname, Z_STRLEN_P(name)+1); if (zend_hash_exists(CG(class_table), c_ns_name, Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name)+1)) { char *tmp2 = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) || memcmp(tmp2, c_ns_name, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(tmp2); } efree(c_ns_name); } else if (zend_hash_find(CG(class_table), lcname, Z_STRLEN_P(name)+1, (void**)&pce) == SUCCESS && (*pce)->type == ZEND_USER_CLASS && (*pce)->info.user.filename == CG(compiled_filename)) { char *c_tmp = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(name) || memcmp(c_tmp, lcname, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(c_tmp); } if (zend_hash_add(CG(current_import), lcname, Z_STRLEN_P(name)+1, &ns, sizeof(zval*), NULL) != SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } if (warn) { if (!strcmp(Z_STRVAL_P(name), "strict")) { zend_error(E_COMPILE_ERROR, "You seem to be trying to use a different language..."); } zend_error(E_WARNING, "The use statement with non-compound name '%s' has no effect", Z_STRVAL_P(name)); } efree(lcname); zval_dtor(name); } /* }}} */ void zend_do_declare_constant(znode *name, znode *value TSRMLS_DC) /* {{{ */ { zend_op *opline; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed as constants"); } if (zend_get_ct_const(&name->u.constant, 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare constant '%s'", Z_STRVAL(name->u.constant)); } if (CG(current_namespace)) { /* Prefix constant name with name of current namespace, lowercased */ znode tmp; tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); Z_STRVAL(tmp.u.constant) = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), Z_STRLEN(tmp.u.constant)); zend_do_build_namespace_name(&tmp, &tmp, name TSRMLS_CC); *name = tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DECLARE_CONST; SET_UNUSED(opline->result); SET_NODE(opline->op1, name); SET_NODE(opline->op2, value); } /* }}} */ void zend_verify_namespace(TSRMLS_D) /* {{{ */ { if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "No code may exist outside of namespace {}"); } } /* }}} */ void zend_do_end_namespace(TSRMLS_D) /* {{{ */ { CG(in_namespace) = 0; if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_end_compilation(TSRMLS_D) /* {{{ */ { CG(has_bracketed_namespaces) = 0; zend_do_end_namespace(TSRMLS_C); } /* }}} */ /* {{{ zend_dirname Returns directory name component of path */ ZEND_API size_t zend_dirname(char *path, size_t len) { register char *end = path + len - 1; unsigned int len_adjust = 0; #ifdef PHP_WIN32 /* Note that on Win32 CWD is per drive (heritage from CP/M). * This means dirname("c:foo") maps to "c:." or "c:" - which means CWD on C: drive. */ if ((2 <= len) && isalpha((int)((unsigned char *)path)[0]) && (':' == path[1])) { /* Skip over the drive spec (if any) so as not to change */ path += 2; len_adjust += 2; if (2 == len) { /* Return "c:" on Win32 for dirname("c:"). * It would be more consistent to return "c:." * but that would require making the string *longer*. */ return len; } } #elif defined(NETWARE) /* * Find the first occurence of : from the left * move the path pointer to the position just after : * increment the len_adjust to the length of path till colon character(inclusive) * If there is no character beyond : simple return len */ char *colonpos = NULL; colonpos = strchr(path, ':'); if (colonpos != NULL) { len_adjust = ((colonpos - path) + 1); path += len_adjust; if (len_adjust == len) { return len; } } #endif if (len == 0) { /* Illegal use of this function */ return 0; } /* Strip trailing slashes */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { /* The path only contained slashes */ path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } /* Strip filename */ while (end >= path && !IS_SLASH_P(end)) { end--; } if (end < path) { /* No slash found, therefore return '.' */ #ifdef NETWARE if (len_adjust == 0) { path[0] = '.'; path[1] = '\0'; return 1; /* only one character */ } else { path[0] = '\0'; return len_adjust; } #else path[0] = '.'; path[1] = '\0'; return 1 + len_adjust; #endif } /* Strip slashes which came before the file name */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } *(end+1) = '\0'; return (size_t)(end + 1 - path) + len_adjust; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */ /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <zend_language_parser.h> #include "zend.h" #include "zend_compile.h" #include "zend_constants.h" #include "zend_llist.h" #include "zend_API.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "zend_multibyte.h" #include "zend_language_scanner.h" #define CONSTANT_EX(op_array, op) \ (op_array)->literals[op].constant #define CONSTANT(op) \ CONSTANT_EX(CG(active_op_array), op) #define SET_NODE(target, src) do { \ target ## _type = (src)->op_type; \ if ((src)->op_type == IS_CONST) { \ target.constant = zend_add_literal(CG(active_op_array), &(src)->u.constant TSRMLS_CC); \ } else { \ target = (src)->u.op; \ } \ } while (0) #define GET_NODE(target, src) do { \ (target)->op_type = src ## _type; \ if ((target)->op_type == IS_CONST) { \ (target)->u.constant = CONSTANT(src.constant); \ } else { \ (target)->u.op = src; \ (target)->EA = 0; \ } \ } while (0) #define COPY_NODE(target, src) do { \ target ## _type = src ## _type; \ target = src; \ } while (0) #define CALCULATE_LITERAL_HASH(num) do { \ if (IS_INTERNED(Z_STRVAL(CONSTANT(num)))) { \ Z_HASH_P(&CONSTANT(num)) = INTERNED_HASH(Z_STRVAL(CONSTANT(num))); \ } else { \ Z_HASH_P(&CONSTANT(num)) = zend_hash_func(Z_STRVAL(CONSTANT(num)), Z_STRLEN(CONSTANT(num))+1); \ } \ } while (0) #define GET_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot++; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ } \ } while (0) #define POLYMORPHIC_CACHE_SLOT_SIZE 2 #define GET_POLYMORPHIC_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot; \ CG(active_op_array)->last_cache_slot += POLYMORPHIC_CACHE_SLOT_SIZE; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 2] = NULL; \ } \ } while (0) #define FREE_POLYMORPHIC_CACHE_SLOT(literal) do { \ if (CG(active_op_array)->literals[literal].cache_slot == \ CG(active_op_array)->last_cache_slot - POLYMORPHIC_CACHE_SLOT_SIZE) { \ CG(active_op_array)->literals[literal].cache_slot = -1; \ CG(active_op_array)->last_cache_slot -= POLYMORPHIC_CACHE_SLOT_SIZE; \ } \ } while (0) ZEND_API zend_op_array *(*zend_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); ZEND_API zend_op_array *(*zend_compile_string)(zval *source_string, char *filename TSRMLS_DC); #ifndef ZTS ZEND_API zend_compiler_globals compiler_globals; ZEND_API zend_executor_globals executor_globals; #endif static void zend_duplicate_property_info(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = estrndup(property_info->name, property_info->name_length); } if (property_info->doc_comment) { property_info->doc_comment = estrndup(property_info->doc_comment, property_info->doc_comment_len); } } /* }}} */ static void zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = zend_strndup(property_info->name, property_info->name_length); } } /* }}} */ static void zend_destroy_property_info(zend_property_info *property_info) /* {{{ */ { str_efree(property_info->name); if (property_info->doc_comment) { efree((char*)property_info->doc_comment); } } /* }}} */ static void zend_destroy_property_info_internal(zend_property_info *property_info) /* {{{ */ { str_free((char*)property_info->name); } /* }}} */ static void build_runtime_defined_function_key(zval *result, const char *name, int name_length TSRMLS_DC) /* {{{ */ { char char_pos_buf[32]; uint char_pos_len; const char *filename; char_pos_len = zend_sprintf(char_pos_buf, "%p", LANG_SCNG(yy_text)); if (CG(active_op_array)->filename) { filename = CG(active_op_array)->filename; } else { filename = "-"; } /* NULL, name length, filename length, last accepting char position length */ result->value.str.len = 1+name_length+strlen(filename)+char_pos_len; /* must be binary safe */ result->value.str.val = (char *) safe_emalloc(result->value.str.len, 1, 1); result->value.str.val[0] = '\0'; sprintf(result->value.str.val+1, "%s%s%s", name, filename, char_pos_buf); result->type = IS_STRING; Z_SET_REFCOUNT_P(result, 1); } /* }}} */ static void init_compiler_declarables(TSRMLS_D) /* {{{ */ { Z_TYPE(CG(declarables).ticks) = IS_LONG; Z_LVAL(CG(declarables).ticks) = 0; } /* }}} */ void zend_init_compiler_context(TSRMLS_D) /* {{{ */ { CG(context).opcodes_size = (CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) ? INITIAL_INTERACTIVE_OP_ARRAY_SIZE : INITIAL_OP_ARRAY_SIZE; CG(context).vars_size = 0; CG(context).literals_size = 0; CG(context).current_brk_cont = -1; CG(context).backpatch_count = 0; CG(context).labels = NULL; } /* }}} */ void zend_init_compiler_data_structures(TSRMLS_D) /* {{{ */ { zend_stack_init(&CG(bp_stack)); zend_stack_init(&CG(function_call_stack)); zend_stack_init(&CG(switch_cond_stack)); zend_stack_init(&CG(foreach_copy_stack)); zend_stack_init(&CG(object_stack)); zend_stack_init(&CG(declare_stack)); CG(active_class_entry) = NULL; zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_stack_init(&CG(list_stack)); CG(in_compilation) = 0; CG(start_lineno) = 0; CG(current_namespace) = NULL; CG(in_namespace) = 0; CG(has_bracketed_namespaces) = 0; CG(current_import) = NULL; init_compiler_declarables(TSRMLS_C); zend_stack_init(&CG(context_stack)); CG(encoding_declared) = 0; } /* }}} */ ZEND_API void file_handle_dtor(zend_file_handle *fh) /* {{{ */ { TSRMLS_FETCH(); zend_file_handle_dtor(fh TSRMLS_CC); } /* }}} */ void init_compiler(TSRMLS_D) /* {{{ */ { CG(active_op_array) = NULL; zend_init_compiler_data_structures(TSRMLS_C); zend_init_rsrc_list(TSRMLS_C); zend_hash_init(&CG(filenames_table), 5, NULL, (dtor_func_t) free_estring, 0); zend_llist_init(&CG(open_files), sizeof(zend_file_handle), (void (*)(void *)) file_handle_dtor, 0); CG(unclean_shutdown) = 0; } /* }}} */ void shutdown_compiler(TSRMLS_D) /* {{{ */ { zend_stack_destroy(&CG(bp_stack)); zend_stack_destroy(&CG(function_call_stack)); zend_stack_destroy(&CG(switch_cond_stack)); zend_stack_destroy(&CG(foreach_copy_stack)); zend_stack_destroy(&CG(object_stack)); zend_stack_destroy(&CG(declare_stack)); zend_stack_destroy(&CG(list_stack)); zend_hash_destroy(&CG(filenames_table)); zend_llist_destroy(&CG(open_files)); zend_stack_destroy(&CG(context_stack)); } /* }}} */ ZEND_API char *zend_set_compiled_filename(const char *new_compiled_filename TSRMLS_DC) /* {{{ */ { char **pp, *p; int length = strlen(new_compiled_filename); if (zend_hash_find(&CG(filenames_table), new_compiled_filename, length+1, (void **) &pp) == SUCCESS) { CG(compiled_filename) = *pp; return *pp; } p = estrndup(new_compiled_filename, length); zend_hash_update(&CG(filenames_table), new_compiled_filename, length+1, &p, sizeof(char *), (void **) &pp); CG(compiled_filename) = p; return p; } /* }}} */ ZEND_API void zend_restore_compiled_filename(char *original_compiled_filename TSRMLS_DC) /* {{{ */ { CG(compiled_filename) = original_compiled_filename; } /* }}} */ ZEND_API char *zend_get_compiled_filename(TSRMLS_D) /* {{{ */ { return CG(compiled_filename); } /* }}} */ ZEND_API int zend_get_compiled_lineno(TSRMLS_D) /* {{{ */ { return CG(zend_lineno); } /* }}} */ ZEND_API zend_bool zend_is_compiling(TSRMLS_D) /* {{{ */ { return CG(in_compilation); } /* }}} */ static zend_uint get_temporary_variable(zend_op_array *op_array) /* {{{ */ { return (op_array->T)++ * ZEND_MM_ALIGNED_SIZE(sizeof(temp_variable)); } /* }}} */ static int lookup_cv(zend_op_array *op_array, char* name, int name_len, ulong hash TSRMLS_DC) /* {{{ */ { int i = 0; ulong hash_value = hash ? hash : zend_inline_hash_func(name, name_len+1); while (i < op_array->last_var) { if (op_array->vars[i].name == name || (op_array->vars[i].hash_value == hash_value && op_array->vars[i].name_len == name_len && memcmp(op_array->vars[i].name, name, name_len) == 0)) { str_efree(name); return i; } i++; } i = op_array->last_var; op_array->last_var++; if (op_array->last_var > CG(context).vars_size) { CG(context).vars_size += 16; /* FIXME */ op_array->vars = erealloc(op_array->vars, CG(context).vars_size * sizeof(zend_compiled_variable)); } op_array->vars[i].name = zend_new_interned_string(name, name_len + 1, 1 TSRMLS_CC); op_array->vars[i].name_len = name_len; op_array->vars[i].hash_value = hash_value; return i; } /* }}} */ void zend_del_literal(zend_op_array *op_array, int n) /* {{{ */ { zval_dtor(&CONSTANT_EX(op_array, n)); if (n + 1 == op_array->last_literal) { op_array->last_literal--; } else { Z_TYPE(CONSTANT_EX(op_array, n)) = IS_NULL; } } /* }}} */ /* Common part of zend_add_literal and zend_append_individual_literal */ static inline void zend_insert_literal(zend_op_array *op_array, const zval *zv, int literal_position TSRMLS_DC) /* {{{ */ { if (Z_TYPE_P(zv) == IS_STRING || Z_TYPE_P(zv) == IS_CONSTANT) { zval *z = (zval*)zv; Z_STRVAL_P(z) = (char*)zend_new_interned_string(Z_STRVAL_P(zv), Z_STRLEN_P(zv) + 1, 1 TSRMLS_CC); } CONSTANT_EX(op_array, literal_position) = *zv; Z_SET_REFCOUNT(CONSTANT_EX(op_array, literal_position), 2); Z_SET_ISREF(CONSTANT_EX(op_array, literal_position)); op_array->literals[literal_position].hash_value = 0; op_array->literals[literal_position].cache_slot = -1; } /* }}} */ /* Is used while compiling a function, using the context to keep track of an approximate size to avoid to relocate to often. Literals are truncated to actual size in the second compiler pass (pass_two()). */ int zend_add_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; if (i >= CG(context).literals_size) { while (i >= CG(context).literals_size) { CG(context).literals_size += 16; /* FIXME */ } op_array->literals = (zend_literal*)erealloc(op_array->literals, CG(context).literals_size * sizeof(zend_literal)); } zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ /* Is used after normal compilation to append an additional literal. Allocation is done precisely here. */ int zend_append_individual_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; op_array->literals = (zend_literal*)erealloc(op_array->literals, (i + 1) * sizeof(zend_literal)); zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ int zend_add_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_ns_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; const char *ns_separator; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); ns_separator = (const char*)zend_memrchr(Z_STRVAL_P(zv), '\\', Z_STRLEN_P(zv)) + 1; lc_len = Z_STRLEN_P(zv) - (ns_separator - Z_STRVAL_P(zv)); lc_name = zend_str_tolower_dup(ns_separator, lc_len); ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_class_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } if (Z_STRVAL_P(zv)[0] == '\\') { lc_len = Z_STRLEN_P(zv) - 1; lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv) + 1, lc_len); } else { lc_len = Z_STRLEN_P(zv); lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), lc_len); } ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); GET_CACHE_SLOT(ret); return ret; } /* }}} */ int zend_add_const_name_literal(zend_op_array *op_array, const zval *zv, int unqualified TSRMLS_DC) /* {{{ */ { int ret, tmp_literal; char *name, *tmp_name; const char *ns_separator; int name_len, ns_len; zval c; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } /* skip leading '\\' */ if (Z_STRVAL_P(zv)[0] == '\\') { name_len = Z_STRLEN_P(zv) - 1; name = Z_STRVAL_P(zv) + 1; } else { name_len = Z_STRLEN_P(zv); name = Z_STRVAL_P(zv); } ns_separator = zend_memrchr(name, '\\', name_len); if (ns_separator) { ns_len = ns_separator - name; } else { ns_len = 0; } if (ns_len) { /* lowercased namespace name & original constant name */ tmp_name = estrndup(name, name_len); zend_str_tolower(tmp_name, ns_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased namespace name & lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); } if (ns_len) { if (!unqualified) { return ret; } ns_len++; name += ns_len; name_len -= ns_len; } /* original constant name */ tmp_name = estrndup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); return ret; } /* }}} */ #define LITERAL_STRINGL(op, str, len, copy) do { \ zval _c; \ ZVAL_STRINGL(&_c, str, len, copy); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG(op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG_EX(op_array, op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(op_array, &_c TSRMLS_CC); \ } while (0) #define LITERAL_NULL(op) do { \ zval _c; \ INIT_ZVAL( _c); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) static inline zend_bool zend_is_function_or_method_call(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; return ((type & ZEND_PARSED_METHOD_CALL) || (type == ZEND_PARSED_FUNCTION_CALL)); } /* }}} */ void zend_do_binary_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_unary_op(zend_uchar op, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); GET_NODE(result, opline->result); SET_UNUSED(opline->op2); } /* }}} */ #define MAKE_NOP(opline) { opline->opcode = ZEND_NOP; memset(&opline->result,0,sizeof(opline->result)); memset(&opline->op1,0,sizeof(opline->op1)); memset(&opline->op2,0,sizeof(opline->op2)); opline->result_type=opline->op1_type=opline->op2_type=IS_UNUSED; } static void zend_do_op_data(zend_op *data_op, const znode *value TSRMLS_DC) /* {{{ */ { data_op->opcode = ZEND_OP_DATA; SET_NODE(data_op->op1, value); SET_UNUSED(data_op->op2); } /* }}} */ void zend_do_binary_assign_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; switch (last_op->opcode) { case ZEND_FETCH_OBJ_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, op2 TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; case ZEND_FETCH_DIM_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_DIM; zend_do_op_data(opline, op2 TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result,last_op->result); return; default: break; } } opline->opcode = op; SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void fetch_simple_variable_ex(znode *result, znode *varname, int bp, zend_uchar op TSRMLS_DC) /* {{{ */ { zend_op opline; zend_op *opline_ptr; zend_llist *fetch_list_ptr; if (varname->op_type == IS_CONST) { ulong hash = 0; if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } else if (IS_INTERNED(Z_STRVAL(varname->u.constant))) { hash = INTERNED_HASH(Z_STRVAL(varname->u.constant)); } if (!zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC) && !(varname->u.constant.value.str.len == (sizeof("this")-1) && !memcmp(varname->u.constant.value.str.val, "this", sizeof("this"))) && (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE)) { result->op_type = IS_CV; result->u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC); varname->u.constant.value.str.val = (char*)CG(active_op_array)->vars[result->u.op.var].name; result->EA = 0; return; } } if (bp) { opline_ptr = &opline; init_op(opline_ptr TSRMLS_CC); } else { opline_ptr = get_next_op(CG(active_op_array) TSRMLS_CC); } opline_ptr->opcode = op; opline_ptr->result_type = IS_VAR; opline_ptr->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline_ptr->op1, varname); GET_NODE(result, opline_ptr->result); SET_UNUSED(opline_ptr->op2); opline_ptr->extended_value = ZEND_FETCH_LOCAL; if (varname->op_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline_ptr->op1.constant); if (zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC)) { opline_ptr->extended_value = ZEND_FETCH_GLOBAL; } } if (bp) { zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); zend_llist_add_element(fetch_list_ptr, opline_ptr); } } /* }}} */ void fetch_simple_variable(znode *result, znode *varname, int bp TSRMLS_DC) /* {{{ */ { /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ fetch_simple_variable_ex(result, varname, bp, ZEND_FETCH_W TSRMLS_CC); } /* }}} */ void zend_do_fetch_static_member(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { znode class_node; zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline_ptr; zend_op opline; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); } zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (result->op_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[result->u.op.var].name), CG(active_op_array)->vars[result->u.op.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } GET_NODE(result,opline.result); opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; opline_ptr = &opline; zend_llist_add_element(fetch_list_ptr, &opline); } else { le = fetch_list_ptr->head; opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode != ZEND_FETCH_W && opline_ptr->op1_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[opline_ptr->op1.var].name), CG(active_op_array)->vars[opline_ptr->op1.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; COPY_NODE(opline_ptr->op1, opline.result); zend_llist_prepend_element(fetch_list_ptr, &opline); } else { if (opline_ptr->op1_type == IS_CONST) { GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op1.constant); } if (class_node.op_type == IS_CONST) { opline_ptr->op2_type = IS_CONST; opline_ptr->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline_ptr->op2, &class_node); } opline_ptr->extended_value |= ZEND_FETCH_STATIC_MEMBER; } } } /* }}} */ void fetch_array_begin(znode *result, znode *varname, znode *first_dim TSRMLS_DC) /* {{{ */ { fetch_simple_variable(result, varname, 1 TSRMLS_CC); fetch_array_dim(result, result, first_dim TSRMLS_CC); } /* }}} */ void fetch_array_dim(znode *result, const znode *parent, const znode *dim TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (zend_is_function_or_method_call(parent)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, parent); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_DIM_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, parent); SET_NODE(opline.op2, dim); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline.op2.constant)), Z_STRLEN(CONSTANT(opline.op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline.op2.constant)); ZVAL_LONG(&CONSTANT(opline.op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline.op2.constant); } } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void fetch_string_offset(znode *result, const znode *parent, const znode *offset TSRMLS_DC) /* {{{ */ { fetch_array_dim(result, parent, offset TSRMLS_CC); } /* }}} */ void zend_do_print(znode *result, const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->opcode = ZEND_PRINT; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_echo(const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ECHO; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_abstract_method(const znode *function_name, znode *modifiers, const znode *body TSRMLS_DC) /* {{{ */ { char *method_type; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { Z_LVAL(modifiers->u.constant) |= ZEND_ACC_ABSTRACT; method_type = "Interface"; } else { method_type = "Abstract"; } if (modifiers->u.constant.value.lval & ZEND_ACC_ABSTRACT) { if(modifiers->u.constant.value.lval & ZEND_ACC_PRIVATE) { zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot be declared private", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } if (Z_LVAL(body->u.constant) == ZEND_ACC_ABSTRACT) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_RAISE_ABSTRACT_ERROR; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } else { /* we had code in the function body */ zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot contain body", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } else { if (body->u.constant.value.lval == ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Non-abstract method %s::%s() must contain body", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } } /* }}} */ static zend_bool opline_is_fetch_this(const zend_op *opline TSRMLS_DC) /* {{{ */ { if ((opline->opcode == ZEND_FETCH_W) && (opline->op1_type == IS_CONST) && (Z_TYPE(CONSTANT(opline->op1.constant)) == IS_STRING) && (Z_HASH_P(&CONSTANT(opline->op1.constant)) == THIS_HASHVAL) && (Z_STRLEN(CONSTANT(opline->op1.constant)) == (sizeof("this")-1)) && !memcmp(Z_STRVAL(CONSTANT(opline->op1.constant)), "this", sizeof("this"))) { return 1; } else { return 0; } } /* }}} */ void zend_do_assign(znode *result, znode *variable, znode *value TSRMLS_DC) /* {{{ */ { int last_op_number; zend_op *opline; if (value->op_type == IS_CV) { zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (fetch_list_ptr && fetch_list_ptr->head) { opline = (zend_op *)fetch_list_ptr->head->data; if (opline->opcode == ZEND_FETCH_DIM_W && opline->op1_type == IS_CV && opline->op1.var == value->u.op.var) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_R; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->op1_type = IS_CONST; LITERAL_STRINGL(opline->op1, CG(active_op_array)->vars[value->u.op.var].name, CG(active_op_array)->vars[value->u.op.var].name_len, 1); CALCULATE_LITERAL_HASH(opline->op1.constant); SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_LOCAL; GET_NODE(value, opline->result); } } } zend_do_end_variable_parse(variable, BP_VAR_W, 0 TSRMLS_CC); last_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (variable->op_type == IS_CV) { if (variable->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (variable->op_type == IS_VAR) { int n = 0; while (last_op_number - n > 0) { zend_op *last_op; last_op = &CG(active_op_array)->opcodes[last_op_number-n-1]; if (last_op->result_type == IS_VAR && last_op->result.var == variable->u.op.var) { if (last_op->opcode == ZEND_FETCH_OBJ_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, value TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (last_op->opcode == ZEND_FETCH_DIM_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ /* TBFixed: this can realloc opcodes, leaving last_op pointing wrong */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_DIM; zend_do_op_data(opline, value TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (opline_is_fetch_this(last_op TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } else { break; } } n++; } } opline->opcode = ZEND_ASSIGN; SET_NODE(opline->op1, variable); SET_NODE(opline->op2, value); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_assign_ref(znode *result, const znode *lvar, const znode *rvar TSRMLS_DC) /* {{{ */ { zend_op *opline; if (lvar->op_type == IS_CV) { if (lvar->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (lvar->op_type == IS_VAR) { int last_op_number = get_next_op_number(CG(active_op_array)); if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline_is_fetch_this(opline TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ASSIGN_REF; if (zend_is_function_or_method_call(rvar)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } else if (rvar->EA & ZEND_PARSED_NEW) { opline->extended_value = ZEND_RETURNS_NEW; } else { opline->extended_value = 0; } if (result) { opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } else { opline->result_type = IS_UNUSED | EXT_TYPE_UNUSED; } SET_NODE(opline->op1, lvar); SET_NODE(opline->op2, rvar); } /* }}} */ static inline void do_begin_loop(TSRMLS_D) /* {{{ */ { zend_brk_cont_element *brk_cont_element; int parent; parent = CG(context).current_brk_cont; CG(context).current_brk_cont = CG(active_op_array)->last_brk_cont; brk_cont_element = get_next_brk_cont_element(CG(active_op_array)); brk_cont_element->start = get_next_op_number(CG(active_op_array)); brk_cont_element->parent = parent; } /* }}} */ static inline void do_end_loop(int cont_addr, int has_loop_var TSRMLS_DC) /* {{{ */ { if (!has_loop_var) { /* The start fileld is used to free temporary variables in case of exceptions. * We won't try to free something of we don't have loop variable. */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].start = -1; } CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = cont_addr; CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; } /* }}} */ void zend_do_while_cond(const znode *expr, znode *close_bracket_token TSRMLS_DC) /* {{{ */ { int while_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, expr); close_bracket_token->u.op.opline_num = while_cond_op_number; SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_while_end(const znode *while_token, const znode *close_bracket_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* add unconditional jump */ opline->opcode = ZEND_JMP; opline->op1.opline_num = while_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* update while's conditional jmp */ CG(active_op_array)->opcodes[close_bracket_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); do_end_loop(while_token->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_cond(const znode *expr, znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { int for_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZNZ; SET_NODE(opline->op1, expr); /* the conditional expression */ second_semicolon_token->u.op.opline_num = for_cond_op_number; SET_UNUSED(opline->op2); } /* }}} */ void zend_do_for_before_statement(const znode *cond_start, const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = cond_start->u.op.opline_num; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_end(const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = second_semicolon_token->u.op.opline_num+1; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_end_loop(second_semicolon_token->u.op.opline_num+1, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_pre_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_PRE_INC)?ZEND_PRE_INC_OBJ:ZEND_PRE_DEC_OBJ; last_op->result_type = IS_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_post_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_POST_INC)?ZEND_POST_INC_OBJ:ZEND_POST_DEC_OBJ; last_op->result_type = IS_TMP_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_if_cond(const znode *cond, znode *closing_bracket_token TSRMLS_DC) /* {{{ */ { int if_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); closing_bracket_token->u.op.opline_num = if_cond_op_number; SET_UNUSED(opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_if_after_statement(const znode *closing_bracket_token, unsigned char initialize TSRMLS_DC) /* {{{ */ { int if_end_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; /* save for backpatching */ if (initialize) { zend_llist jmp_list; zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); } zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &if_end_op_number); CG(active_op_array)->opcodes[closing_bracket_token->u.op.opline_num].op2.opline_num = if_end_op_number+1; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_if_end(TSRMLS_D) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_llist *jmp_list_ptr; zend_llist_element *le; zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); for (le=jmp_list_ptr->head; le; le = le->next) { CG(active_op_array)->opcodes[*((int *) le->data)].op1.opline_num = next_op_number; } zend_llist_destroy(jmp_list_ptr); zend_stack_del_top(&CG(bp_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_check_writable_variable(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; if (type & ZEND_PARSED_METHOD_CALL) { zend_error(E_COMPILE_ERROR, "Can't use method return value in write context"); } if (type == ZEND_PARSED_FUNCTION_CALL) { zend_error(E_COMPILE_ERROR, "Can't use function return value in write context"); } } /* }}} */ void zend_do_begin_variable_parse(TSRMLS_D) /* {{{ */ { zend_llist fetch_list; zend_llist_init(&fetch_list, sizeof(zend_op), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &fetch_list, sizeof(zend_llist)); } /* }}} */ void zend_do_end_variable_parse(znode *variable, int type, int arg_offset TSRMLS_DC) /* {{{ */ { zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline = NULL; zend_op *opline_ptr; zend_uint this_var = -1; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); le = fetch_list_ptr->head; /* TODO: $foo->x->y->z = 1 should fetch "x" and "y" for R or RW, not just W */ if (le) { opline_ptr = (zend_op *)le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { /* convert to FETCH_?(this) into IS_CV */ if (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE) { this_var = opline_ptr->result.var; if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), Z_STRVAL(CONSTANT(opline_ptr->op1.constant)), Z_STRLEN(CONSTANT(opline_ptr->op1.constant)), Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC); Z_TYPE(CONSTANT(opline_ptr->op1.constant)) = IS_NULL; } else { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); } le = le->next; if (variable->op_type == IS_VAR && variable->u.op.var == this_var) { variable->op_type = IS_CV; variable->u.op.var = CG(active_op_array)->this_var; } } else if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } while (le) { opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode == ZEND_SEPARATE) { if (type != BP_VAR_R && type != BP_VAR_IS) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); } le = le->next; continue; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); if (opline->op1_type == IS_VAR && opline->op1.var == this_var) { opline->op1_type = IS_CV; opline->op1.var = CG(active_op_array)->this_var; } switch (type) { case BP_VAR_R: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode -= 3; break; case BP_VAR_W: break; case BP_VAR_RW: opline->opcode += 3; break; case BP_VAR_IS: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode += 6; /* 3+3 */ break; case BP_VAR_FUNC_ARG: opline->opcode += 9; /* 3+3+3 */ opline->extended_value |= arg_offset; break; case BP_VAR_UNSET: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for unsetting"); } opline->opcode += 12; /* 3+3+3+3 */ break; } le = le->next; } if (opline && type == BP_VAR_W && arg_offset) { opline->extended_value |= ZEND_FETCH_MAKE_REF; } } zend_llist_destroy(fetch_list_ptr); zend_stack_del_top(&CG(bp_stack)); } /* }}} */ void zend_do_add_string(znode *result, const znode *op1, znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline; if (Z_STRLEN(op2->u.constant) > 1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_STRING; } else if (Z_STRLEN(op2->u.constant) == 1) { int ch = *Z_STRVAL(op2->u.constant); /* Free memory and use ZEND_ADD_CHAR in case of 1 character strings */ efree(Z_STRVAL(op2->u.constant)); ZVAL_LONG(&op2->u.constant, ch); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_CHAR; } else { /* String can be empty after a variable at the end of a heredoc */ efree(Z_STRVAL(op2->u.constant)); return; } if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_add_variable(znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_VAR; if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_free(znode *op1 TSRMLS_DC) /* {{{ */ { if (op1->op_type==IS_TMP_VAR) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else if (op1->op_type==IS_VAR) { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; while (opline->opcode == ZEND_END_SILENCE || opline->opcode == ZEND_EXT_FCALL_END || opline->opcode == ZEND_OP_DATA) { opline--; } if (opline->result_type == IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_FETCH_R || opline->opcode == ZEND_FETCH_DIM_R || opline->opcode == ZEND_FETCH_OBJ_R) { /* It's very rare and useless case. It's better to use additional FREE opcode and simplify the FETCH handlers their selves */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else { opline->result_type |= EXT_TYPE_UNUSED; } } else { while (opline>CG(active_op_array)->opcodes) { if (opline->opcode == ZEND_FETCH_DIM_R && opline->op1_type == IS_VAR && opline->op1.var == op1->u.op.var) { /* This should the end of a list() construct * Mark its result as unused */ opline->extended_value = ZEND_FETCH_STANDARD; break; } else if (opline->result_type==IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_NEW) { opline->result_type |= EXT_TYPE_UNUSED; } break; } opline--; } } } else if (op1->op_type == IS_CONST) { zval_dtor(&op1->u.constant); } } /* }}} */ int zend_do_verify_access_types(const znode *current_access_type, const znode *new_modifier) /* {{{ */ { if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_PPP_MASK) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Multiple access type modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_ABSTRACT) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Multiple abstract modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_STATIC) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Multiple static modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_FINAL) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Multiple final modifiers are not allowed"); } if (((Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)) & (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) == (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Cannot use the final modifier on an abstract class member"); } return (Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)); } /* }}} */ void zend_do_begin_function_declaration(znode *function_token, znode *function_name, int is_method, int return_reference, znode *fn_flags_znode TSRMLS_DC) /* {{{ */ { zend_op_array op_array; char *name = function_name->u.constant.value.str.val; int name_len = function_name->u.constant.value.str.len; int function_begin_line = function_token->u.op.opline_num; zend_uint fn_flags; const char *lcname; zend_bool orig_interactive; ALLOCA_FLAG(use_heap) if (is_method) { if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((Z_LVAL(fn_flags_znode->u.constant) & ~(ZEND_ACC_STATIC|ZEND_ACC_PUBLIC))) { zend_error(E_COMPILE_ERROR, "Access type for interface method %s::%s() must be omitted", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } Z_LVAL(fn_flags_znode->u.constant) |= ZEND_ACC_ABSTRACT; /* propagates to the rest of the parser */ } fn_flags = Z_LVAL(fn_flags_znode->u.constant); /* must be done *after* the above check */ } else { fn_flags = 0; } if ((fn_flags & ZEND_ACC_STATIC) && (fn_flags & ZEND_ACC_ABSTRACT) && !(CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_STRICT, "Static function %s%s%s() should not be abstract", is_method ? CG(active_class_entry)->name : "", is_method ? "::" : "", Z_STRVAL(function_name->u.constant)); } function_token->u.op_array = CG(active_op_array); orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(&op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; op_array.function_name = name; if (return_reference) { op_array.fn_flags |= ZEND_ACC_RETURN_REFERENCE; } op_array.fn_flags |= fn_flags; op_array.scope = is_method?CG(active_class_entry):NULL; op_array.prototype = NULL; op_array.line_start = zend_get_compiled_lineno(TSRMLS_C); if (is_method) { int result; lcname = zend_new_interned_string(zend_str_tolower_dup(name, name_len), name_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lcname)) { result = zend_hash_quick_add(&CG(active_class_entry)->function_table, lcname, name_len+1, INTERNED_HASH(lcname), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } else { result = zend_hash_add(&CG(active_class_entry)->function_table, lcname, name_len+1, &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } if (result == FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::%s()", CG(active_class_entry)->name, name); } zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); if (fn_flags & ZEND_ACC_ABSTRACT) { CG(active_class_entry)->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (!(fn_flags & ZEND_ACC_PPP_MASK)) { fn_flags |= ZEND_ACC_PUBLIC; } if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } } } else { char *class_lcname; class_lcname = do_alloca(CG(active_class_entry)->name_length + 1, use_heap); zend_str_tolower_copy(class_lcname, CG(active_class_entry)->name, CG(active_class_entry)->name_length); /* Improve after RC: cache the lowercase class name */ if ((CG(active_class_entry)->name_length == name_len) && ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT) && (!memcmp(class_lcname, lcname, name_len))) { if (!CG(active_class_entry)->constructor) { CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } } else if ((name_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)))) { if (CG(active_class_entry)->constructor) { zend_error(E_STRICT, "Redefining already defined constructor for class %s", CG(active_class_entry)->name); } CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1))) { CG(active_class_entry)->destructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1))) { CG(active_class_entry)->clone = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } CG(active_class_entry)->__call = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } CG(active_class_entry)->__callstatic = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } CG(active_class_entry)->__get = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } CG(active_class_entry)->__set = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } CG(active_class_entry)->__unset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } CG(active_class_entry)->__isset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } CG(active_class_entry)->__tostring = (zend_function *) CG(active_op_array); } else if (!(fn_flags & ZEND_ACC_STATIC)) { CG(active_op_array)->fn_flags |= ZEND_ACC_ALLOW_STATIC; } free_alloca(class_lcname, use_heap); } str_efree(lcname); } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zval key; if (CG(current_namespace)) { /* Prefix function name with current namespcae name */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, function_name TSRMLS_CC); op_array.function_name = Z_STRVAL(tmp.u.constant); name_len = Z_STRLEN(tmp.u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), name_len); } else { lcname = zend_str_tolower_dup(name, name_len); } opline->opcode = ZEND_DECLARE_FUNCTION; opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, name_len TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; LITERAL_STRINGL(opline->op2, lcname, name_len, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); opline->extended_value = ZEND_DECLARE_FUNCTION; zend_hash_quick_update(CG(function_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); } if (CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_NOP; opline->lineno = function_begin_line; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } { /* Push a seperator to the switch and foreach stacks */ zend_switch_entry switch_entry; switch_entry.cond.op_type = IS_UNUSED; switch_entry.default_case = 0; switch_entry.control_var = 0; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); { /* Foreach stack separator */ zend_op dummy_opline; dummy_opline.result_type = IS_UNUSED; dummy_opline.op1_type = IS_UNUSED; zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); } } if (CG(doc_comment)) { CG(active_op_array)->doc_comment = CG(doc_comment); CG(active_op_array)->doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_begin_lambda_function_declaration(znode *result, znode *function_token, int return_reference, int is_static TSRMLS_DC) /* {{{ */ { znode function_name; zend_op_array *current_op_array = CG(active_op_array); int current_op_number = get_next_op_number(CG(active_op_array)); zend_op *current_op; function_name.op_type = IS_CONST; ZVAL_STRINGL(&function_name.u.constant, "{closure}", sizeof("{closure}")-1, 1); zend_do_begin_function_declaration(function_token, &function_name, 0, return_reference, NULL TSRMLS_CC); result->op_type = IS_TMP_VAR; result->u.op.var = get_temporary_variable(current_op_array); current_op = &current_op_array->opcodes[current_op_number]; current_op->opcode = ZEND_DECLARE_LAMBDA_FUNCTION; zend_del_literal(current_op_array, current_op->op2.constant); SET_UNUSED(current_op->op2); SET_NODE(current_op->result, result); if (is_static) { CG(active_op_array)->fn_flags |= ZEND_ACC_STATIC; } CG(active_op_array)->fn_flags |= ZEND_ACC_CLOSURE; } /* }}} */ void zend_do_handle_exception(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_HANDLE_EXCEPTION; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_function_declaration(const znode *function_token TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; zend_do_extended_info(TSRMLS_C); zend_do_return(NULL, 0 TSRMLS_CC); pass_two(CG(active_op_array) TSRMLS_CC); zend_release_labels(TSRMLS_C); if (CG(active_class_entry)) { zend_check_magic_method_implementation(CG(active_class_entry), (zend_function*)CG(active_op_array), E_COMPILE_ERROR TSRMLS_CC); } else { /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(CG(active_op_array)->function_name); zend_str_tolower_copy(lcname, CG(active_op_array)->function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME)) && CG(active_op_array)->num_args != 1) { zend_error(E_COMPILE_ERROR, "%s() must take exactly 1 argument", ZEND_AUTOLOAD_FUNC_NAME); } } CG(active_op_array)->line_end = zend_get_compiled_lineno(TSRMLS_C); CG(active_op_array) = function_token->u.op_array; /* Pop the switch and foreach seperators */ zend_stack_del_top(&CG(switch_cond_stack)); zend_stack_del_top(&CG(foreach_copy_stack)); } /* }}} */ void zend_do_receive_arg(zend_uchar op, znode *varname, const znode *offset, const znode *initialization, znode *class_type, zend_uchar pass_by_reference TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_arg_info *cur_arg_info; znode var; if (class_type->op_type == IS_CONST && Z_TYPE(class_type->u.constant) == IS_STRING && Z_STRLEN(class_type->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_type->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } if (zend_is_auto_global_quick(Z_STRVAL(varname->u.constant), Z_STRLEN(varname->u.constant), 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign auto-global variable %s", Z_STRVAL(varname->u.constant)); } else { var.op_type = IS_CV; var.u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(varname->u.constant) = (char*)CG(active_op_array)->vars[var.u.op.var].name; var.EA = 0; if (CG(active_op_array)->vars[var.u.op.var].hash_value == THIS_HASHVAL && Z_STRLEN(varname->u.constant) == sizeof("this")-1 && !memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this")-1)) { if (CG(active_op_array)->scope && (CG(active_op_array)->fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } CG(active_op_array)->this_var = var.u.op.var; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->num_args++; opline->opcode = op; SET_NODE(opline->result, &var); SET_NODE(opline->op1, offset); if (op == ZEND_RECV_INIT) { SET_NODE(opline->op2, initialization); } else { CG(active_op_array)->required_num_args = CG(active_op_array)->num_args; SET_UNUSED(opline->op2); } CG(active_op_array)->arg_info = erealloc(CG(active_op_array)->arg_info, sizeof(zend_arg_info)*(CG(active_op_array)->num_args)); cur_arg_info = &CG(active_op_array)->arg_info[CG(active_op_array)->num_args-1]; cur_arg_info->name = zend_new_interned_string(estrndup(varname->u.constant.value.str.val, varname->u.constant.value.str.len), varname->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->name_len = varname->u.constant.value.str.len; cur_arg_info->type_hint = 0; cur_arg_info->allow_null = 1; cur_arg_info->pass_by_reference = pass_by_reference; cur_arg_info->class_name = NULL; cur_arg_info->class_name_len = 0; if (class_type->op_type != IS_UNUSED) { cur_arg_info->allow_null = 0; if (class_type->u.constant.type != IS_NULL) { if (class_type->u.constant.type == IS_ARRAY) { cur_arg_info->type_hint = IS_ARRAY; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else if (Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Default value for parameters with array type hint can only be an array or NULL"); } } } else if (class_type->u.constant.type == IS_CALLABLE) { cur_arg_info->type_hint = IS_CALLABLE; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with callable type hint can only be NULL"); } } } else { cur_arg_info->type_hint = IS_OBJECT; if (ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_type->u.constant), Z_STRLEN(class_type->u.constant))) { zend_resolve_class_name(class_type, opline->extended_value, 1 TSRMLS_CC); } Z_STRVAL(class_type->u.constant) = (char*)zend_new_interned_string(class_type->u.constant.value.str.val, class_type->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->class_name = class_type->u.constant.value.str.val; cur_arg_info->class_name_len = class_type->u.constant.value.str.len; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with a class type hint can only be NULL"); } } } } } } /* }}} */ int zend_do_begin_function_call(znode *function_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { zend_function *function; char *lcname; char *is_compound = memchr(Z_STRVAL(function_name->u.constant), '\\', Z_STRLEN(function_name->u.constant)); zend_resolve_non_class_name(function_name, check_namespace TSRMLS_CC); if (check_namespace && CG(current_namespace) && !is_compound) { /* We assume we call function from the current namespace if it is not prefixed. */ /* In run-time PHP will check for function with full name and internal function with short name */ zend_do_begin_dynamic_function_call(function_name, 1 TSRMLS_CC); return 1; } lcname = zend_str_tolower_dup(function_name->u.constant.value.str.val, function_name->u.constant.value.str.len); if ((zend_hash_find(CG(function_table), lcname, function_name->u.constant.value.str.len+1, (void **) &function)==FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_FUNCTIONS) && (function->type == ZEND_INTERNAL_FUNCTION))) { zend_do_begin_dynamic_function_call(function_name, 0 TSRMLS_CC); efree(lcname); return 1; /* Dynamic */ } efree(function_name->u.constant.value.str.val); function_name->u.constant.value.str.val = lcname; zend_stack_push(&CG(function_call_stack), (void *) &function, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 0; } /* }}} */ void zend_do_begin_method_call(znode *left_bracket TSRMLS_DC) /* {{{ */ { zend_op *last_op; int last_op_number; unsigned char *ptr = NULL; zend_do_end_variable_parse(left_bracket, BP_VAR_R, 0 TSRMLS_CC); zend_do_begin_variable_parse(TSRMLS_C); last_op_number = get_next_op_number(CG(active_op_array))-1; last_op = &CG(active_op_array)->opcodes[last_op_number]; if ((last_op->op2_type == IS_CONST) && (Z_TYPE(CONSTANT(last_op->op2.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(last_op->op2.constant)) == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !zend_binary_strcasecmp(Z_STRVAL(CONSTANT(last_op->op2.constant)), Z_STRLEN(CONSTANT(last_op->op2.constant)), ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1)) { zend_error(E_COMPILE_ERROR, "Cannot call __clone() method on objects - use 'clone $obj' instead"); } if (last_op->opcode == ZEND_FETCH_OBJ_R) { if (last_op->op2_type == IS_CONST) { zval name; name = CONSTANT(last_op->op2.constant); if (!IS_INTERNED(Z_STRVAL(name))) { Z_STRVAL(name) = estrndup(Z_STRVAL(name), Z_STRLEN(name)); } FREE_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); last_op->op2.constant = zend_add_func_name_literal(CG(active_op_array), &name TSRMLS_CC); GET_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); } last_op->opcode = ZEND_INIT_METHOD_CALL; SET_UNUSED(last_op->result); Z_LVAL(left_bracket->u.constant) = ZEND_INIT_FCALL_BY_NAME; } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (left_bracket->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &left_bracket->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, left_bracket); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_do_clone(znode *result, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CLONE; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_begin_dynamic_function_call(znode *function_name, int ns_call TSRMLS_DC) /* {{{ */ { unsigned char *ptr = NULL; zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (ns_call) { /* In run-time PHP will check for function with full name and internal function with short name */ opline->opcode = ZEND_INIT_NS_FCALL_BY_NAME; SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_ns_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (function_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, function_name); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_resolve_non_class_name(znode *element_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; int len; zval **ns; char *lcname, *compound = memchr(Z_STRVAL(element_name->u.constant), '\\', Z_STRLEN(element_name->u.constant)); if (Z_STRVAL(element_name->u.constant)[0] == '\\') { /* name starts with \ so it is known and unambiguos, nothing to do here but shorten it */ memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+1, Z_STRLEN(element_name->u.constant)); --Z_STRLEN(element_name->u.constant); return; } if(!check_namespace) { return; } if (compound && CG(current_import)) { len = compound - Z_STRVAL(element_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(element_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(element_name->u.constant) -= len; memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+len, Z_STRLEN(element_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, element_name TSRMLS_CC); *element_name = tmp; efree(lcname); return; } efree(lcname); } if (CG(current_namespace)) { tmp = *element_name; Z_STRLEN(tmp.u.constant) = sizeof("\\")-1 + Z_STRLEN(element_name->u.constant) + Z_STRLEN_P(CG(current_namespace)); Z_STRVAL(tmp.u.constant) = (char *) emalloc(Z_STRLEN(tmp.u.constant)+1); memcpy(Z_STRVAL(tmp.u.constant), Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace))]), "\\", sizeof("\\")-1); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace)) + sizeof("\\")-1]), Z_STRVAL(element_name->u.constant), Z_STRLEN(element_name->u.constant)+1); STR_FREE(Z_STRVAL(element_name->u.constant)); *element_name = tmp; } } /* }}} */ void zend_resolve_class_name(znode *class_name, ulong fetch_type, int check_ns_name TSRMLS_DC) /* {{{ */ { char *compound; char *lcname; zval **ns; znode tmp; int len; compound = memchr(Z_STRVAL(class_name->u.constant), '\\', Z_STRLEN(class_name->u.constant)); if (compound) { /* This is a compound class name that contains namespace prefix */ if (Z_STRVAL(class_name->u.constant)[0] == '\\') { /* The STRING name has "\" prefix */ Z_STRLEN(class_name->u.constant) -= 1; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+1, Z_STRLEN(class_name->u.constant)+1); Z_STRVAL(class_name->u.constant) = erealloc( Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1); if (ZEND_FETCH_CLASS_DEFAULT != zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "'\\%s' is an invalid class name", Z_STRVAL(class_name->u.constant)); } } else { if (CG(current_import)) { len = compound - Z_STRVAL(class_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(class_name->u.constant) -= len; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+len, Z_STRLEN(class_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; efree(lcname); return; } efree(lcname); } /* Here name is not prefixed with \ and not imported */ if (CG(current_namespace)) { tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } } } else if (CG(current_import) || CG(current_namespace)) { /* this is a plain name (without \) */ lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns) == SUCCESS) { /* The given name is an import name. Substitute it. */ zval_dtor(&class_name->u.constant); class_name->u.constant = **ns; zval_copy_ctor(&class_name->u.constant); } else if (CG(current_namespace)) { /* plain name, no import - prepend current namespace to it */ tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } efree(lcname); } } /* }}} */ void zend_do_fetch_class(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { long fetch_class_op_number; zend_op *opline; if (class_name->op_type == IS_CONST && Z_TYPE(class_name->u.constant) == IS_STRING && Z_STRLEN(class_name->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_name->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } fetch_class_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CLASS; SET_UNUSED(opline->op1); opline->extended_value = ZEND_FETCH_CLASS_GLOBAL; CG(catch_begin) = fetch_class_op_number; if (class_name->op_type == IS_CONST) { int fetch_type; fetch_type = zend_get_class_fetch_type(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); switch (fetch_type) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: SET_UNUSED(opline->op2); opline->extended_value = fetch_type; zval_dtor(&class_name->u.constant); break; default: zend_resolve_class_name(class_name, opline->extended_value, 0 TSRMLS_CC); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_name->u.constant TSRMLS_CC); break; } } else { SET_NODE(opline->op2, class_name); } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; /* FIXME: Hack so that INIT_FCALL_BY_NAME still knows this is a class */ GET_NODE(result, opline->result); result->EA = opline->extended_value; } /* }}} */ void zend_do_label(znode *label TSRMLS_DC) /* {{{ */ { zend_label dest; if (!CG(context).labels) { ALLOC_HASHTABLE(CG(context).labels); zend_hash_init(CG(context).labels, 4, NULL, NULL, 0); } dest.brk_cont = CG(context).current_brk_cont; dest.opline_num = get_next_op_number(CG(active_op_array)); if (zend_hash_add(CG(context).labels, Z_STRVAL(label->u.constant), Z_STRLEN(label->u.constant) + 1, (void**)&dest, sizeof(zend_label), NULL) == FAILURE) { zend_error(E_COMPILE_ERROR, "Label '%s' already defined", Z_STRVAL(label->u.constant)); } /* Done with label now */ zval_dtor(&label->u.constant); } /* }}} */ void zend_resolve_goto_label(zend_op_array *op_array, zend_op *opline, int pass2 TSRMLS_DC) /* {{{ */ { zend_label *dest; long current, distance; zval *label; if (pass2) { label = opline->op2.zv; } else { label = &CONSTANT_EX(op_array, opline->op2.constant); } if (CG(context).labels == NULL || zend_hash_find(CG(context).labels, Z_STRVAL_P(label), Z_STRLEN_P(label)+1, (void**)&dest) == FAILURE) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; zend_error(E_COMPILE_ERROR, "'goto' to undefined label '%s'", Z_STRVAL_P(label)); } else { /* Label is not defined. Delay to pass 2. */ INC_BPC(op_array); return; } } opline->op1.opline_num = dest->opline_num; zval_dtor(label); Z_TYPE_P(label) = IS_NULL; /* Check that we are not moving into loop or switch */ current = opline->extended_value; for (distance = 0; current != dest->brk_cont; distance++) { if (current == -1) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; } zend_error(E_COMPILE_ERROR, "'goto' into loop or switch statement is disallowed"); } current = op_array->brk_cont_array[current].parent; } if (distance == 0) { /* Nothing to break out of, optimize to ZEND_JMP */ opline->opcode = ZEND_JMP; opline->extended_value = 0; SET_UNUSED(opline->op2); } else { /* Set real break distance */ ZVAL_LONG(label, distance); } if (pass2) { DEC_BPC(op_array); } } /* }}} */ void zend_do_goto(const znode *label TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_GOTO; opline->extended_value = CG(context).current_brk_cont; SET_UNUSED(opline->op1); SET_NODE(opline->op2, label); zend_resolve_goto_label(CG(active_op_array), opline, 0 TSRMLS_CC); } /* }}} */ void zend_release_labels(TSRMLS_D) /* {{{ */ { if (CG(context).labels) { zend_hash_destroy(CG(context).labels); FREE_HASHTABLE(CG(context).labels); } if (!zend_stack_is_empty(&CG(context_stack))) { zend_compiler_context *ctx; zend_stack_top(&CG(context_stack), (void**)&ctx); CG(context) = *ctx; zend_stack_del_top(&CG(context_stack)); } } /* }}} */ void zend_do_build_full_name(znode *result, znode *prefix, znode *name, int is_class_member TSRMLS_DC) /* {{{ */ { zend_uint length; if (!result) { result = prefix; } else { *result = *prefix; } if (is_class_member) { length = sizeof("::")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "::", sizeof("::")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("::")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } else { length = sizeof("\\")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "\\", sizeof("\\")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("\\")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } } /* }}} */ int zend_do_begin_class_member_function_call(znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { znode class_node; unsigned char *ptr = NULL; zend_op *opline; if (method_name->op_type == IS_CONST) { char *lcname = zend_str_tolower_dup(Z_STRVAL(method_name->u.constant), Z_STRLEN(method_name->u.constant)); if ((sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == Z_STRLEN(method_name->u.constant) && memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == 0) { zval_dtor(&method_name->u.constant); method_name->op_type = IS_UNUSED; } efree(lcname); } if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; opline = get_next_op(CG(active_op_array) TSRMLS_CC); } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->extended_value = class_node.EA ; } opline->opcode = ZEND_INIT_STATIC_METHOD_CALL; if (class_node.op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, &class_node); } if (method_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &method_name->u.constant TSRMLS_CC); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } } else { SET_NODE(opline->op2, method_name); } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 1; /* Dynamic */ } /* }}} */ void zend_do_end_function_call(znode *function_name, znode *result, const znode *argument_list, int is_method, int is_dynamic_fcall TSRMLS_DC) /* {{{ */ { zend_op *opline; if (is_method && function_name && function_name->op_type == IS_UNUSED) { /* clone */ if (Z_LVAL(argument_list->u.constant) != 0) { zend_error(E_WARNING, "Clone method does not require arguments"); } opline = &CG(active_op_array)->opcodes[Z_LVAL(function_name->u.constant)]; } else { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (!is_method && !is_dynamic_fcall && function_name->op_type==IS_CONST) { opline->opcode = ZEND_DO_FCALL; SET_NODE(opline->op1, function_name); CALCULATE_LITERAL_HASH(opline->op1.constant); GET_CACHE_SLOT(opline->op1.constant); } else { opline->opcode = ZEND_DO_FCALL_BY_NAME; SET_UNUSED(opline->op1); } } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(result, opline->result) ; SET_UNUSED(opline->op2); zend_stack_del_top(&CG(function_call_stack)); opline->extended_value = Z_LVAL(argument_list->u.constant); } /* }}} */ void zend_do_pass_param(znode *param, zend_uchar op, int offset TSRMLS_DC) /* {{{ */ { zend_op *opline; int original_op=op; zend_function **function_ptr_ptr, *function_ptr; int send_by_reference; int send_function = 0; zend_stack_top(&CG(function_call_stack), (void **) &function_ptr_ptr); function_ptr = *function_ptr_ptr; if (original_op == ZEND_SEND_REF) { if (function_ptr && function_ptr->common.function_name && function_ptr->common.type == ZEND_USER_FUNCTION && !ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed; " "If you would like to pass argument by reference, modify the declaration of %s().", function_ptr->common.function_name); } else { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed"); } return; } if (function_ptr) { if (ARG_MAY_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { if (param->op_type & (IS_VAR|IS_CV) && original_op != ZEND_SEND_VAL) { send_by_reference = 1; if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION | ZEND_ARG_SEND_SILENT; } } else { op = ZEND_SEND_VAL; send_by_reference = 0; } } else { send_by_reference = ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset) ? ZEND_ARG_SEND_BY_REF : 0; } } else { send_by_reference = 0; } if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION; } else if (op == ZEND_SEND_VAL && (param->op_type & (IS_VAR|IS_CV))) { op = ZEND_SEND_VAR_NO_REF; } if (op!=ZEND_SEND_VAR_NO_REF && send_by_reference==ZEND_ARG_SEND_BY_REF) { /* change to passing by reference */ switch (param->op_type) { case IS_VAR: case IS_CV: op = ZEND_SEND_REF; break; default: zend_error(E_COMPILE_ERROR, "Only variables can be passed by reference"); break; } } if (original_op == ZEND_SEND_VAR) { switch (op) { case ZEND_SEND_VAR_NO_REF: zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); break; case ZEND_SEND_VAR: if (function_ptr) { zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(param, BP_VAR_FUNC_ARG, offset TSRMLS_CC); } break; case ZEND_SEND_REF: zend_do_end_variable_parse(param, BP_VAR_W, 0 TSRMLS_CC); break; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (op == ZEND_SEND_VAR_NO_REF) { if (function_ptr) { opline->extended_value = ZEND_ARG_COMPILE_TIME_BOUND | send_by_reference | send_function; } else { opline->extended_value = send_function; } } else { if (function_ptr) { opline->extended_value = ZEND_DO_FCALL; } else { opline->extended_value = ZEND_DO_FCALL_BY_NAME; } } opline->opcode = op; SET_NODE(opline->op1, param); opline->op2.opline_num = offset; SET_UNUSED(opline->op2); } /* }}} */ static int generate_free_switch_expr(const zend_switch_entry *switch_entry TSRMLS_DC) /* {{{ */ { zend_op *opline; if (switch_entry->cond.op_type != IS_VAR && switch_entry->cond.op_type != IS_TMP_VAR) { return (switch_entry->cond.op_type == IS_UNUSED); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry->cond); SET_UNUSED(opline->op2); opline->extended_value = 0; return 0; } /* }}} */ static int generate_free_foreach_copy(const zend_op *foreach_copy TSRMLS_DC) /* {{{ */ { zend_op *opline; /* If we reach the seperator then stop applying the stack */ if (foreach_copy->result_type == IS_UNUSED && foreach_copy->op1_type == IS_UNUSED) { return 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->result_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->result); SET_UNUSED(opline->op2); opline->extended_value = 1; if (foreach_copy->op1_type != IS_UNUSED) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->op1_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->op1); SET_UNUSED(opline->op2); opline->extended_value = 0; } return 0; } /* }}} */ void zend_do_return(znode *expr, int do_end_vparse TSRMLS_DC) /* {{{ */ { zend_op *opline; int start_op_number, end_op_number; if (do_end_vparse) { if ((CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) && !zend_is_function_or_method_call(expr)) { zend_do_end_variable_parse(expr, BP_VAR_W, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(expr, BP_VAR_R, 0 TSRMLS_CC); } } start_op_number = get_next_op_number(CG(active_op_array)); #ifdef ZTS zend_stack_apply_with_argument(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_switch_expr TSRMLS_CC); zend_stack_apply_with_argument(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_foreach_copy TSRMLS_CC); #else zend_stack_apply(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_switch_expr); zend_stack_apply(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_foreach_copy); #endif end_op_number = get_next_op_number(CG(active_op_array)); while (start_op_number < end_op_number) { CG(active_op_array)->opcodes[start_op_number].extended_value |= EXT_TYPE_FREE_ON_RETURN; start_op_number++; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) ? ZEND_RETURN_BY_REF : ZEND_RETURN; if (expr) { SET_NODE(opline->op1, expr); if (do_end_vparse && zend_is_function_or_method_call(expr)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } } else { opline->op1_type = IS_CONST; LITERAL_NULL(opline->op1); } SET_UNUSED(opline->op2); } /* }}} */ static int zend_add_try_element(zend_uint try_op TSRMLS_DC) /* {{{ */ { int try_catch_offset = CG(active_op_array)->last_try_catch++; CG(active_op_array)->try_catch_array = erealloc(CG(active_op_array)->try_catch_array, sizeof(zend_try_catch_element)*CG(active_op_array)->last_try_catch); CG(active_op_array)->try_catch_array[try_catch_offset].try_op = try_op; return try_catch_offset; } /* }}} */ static void zend_add_catch_element(int offset, zend_uint catch_op TSRMLS_DC) /* {{{ */ { CG(active_op_array)->try_catch_array[offset].catch_op = catch_op; } /* }}} */ void zend_do_first_catch(znode *open_parentheses TSRMLS_DC) /* {{{ */ { open_parentheses->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_initialize_try_catch_element(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist jmp_list; zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); zend_add_catch_element(try_token->u.op.opline_num, get_next_op_number(CG(active_op_array)) TSRMLS_CC); } /* }}} */ void zend_do_mark_last_catch(const znode *first_catch, const znode *last_additional_catch TSRMLS_DC) /* {{{ */ { CG(active_op_array)->last--; zend_do_if_end(TSRMLS_C); if (last_additional_catch->u.op.opline_num == -1) { CG(active_op_array)->opcodes[first_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[first_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } else { CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_try(znode *try_token TSRMLS_DC) /* {{{ */ { try_token->u.op.opline_num = zend_add_try_element(get_next_op_number(CG(active_op_array)) TSRMLS_CC); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_catch(znode *try_token, znode *class_name, znode *catch_var, znode *first_catch TSRMLS_DC) /* {{{ */ { long catch_op_number; zend_op *opline; znode catch_class; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); catch_class = *class_name; } else { zend_error(E_COMPILE_ERROR, "Bad class name in the catch statement"); } catch_op_number = get_next_op_number(CG(active_op_array)); if (first_catch) { first_catch->u.op.opline_num = catch_op_number; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CATCH; opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &catch_class.u.constant TSRMLS_CC); opline->op2_type = IS_CV; opline->op2.var = lookup_cv(CG(active_op_array), catch_var->u.constant.value.str.val, catch_var->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(catch_var->u.constant) = (char*)CG(active_op_array)->vars[opline->op2.var].name; opline->result.num = 0; /* 1 means it's the last catch in the block */ try_token->u.op.opline_num = catch_op_number; } /* }}} */ void zend_do_end_catch(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); CG(active_op_array)->opcodes[try_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_throw(const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_THROW; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); } /* }}} */ ZEND_API void function_add_ref(zend_function *function) /* {{{ */ { if (function->type == ZEND_USER_FUNCTION) { zend_op_array *op_array = &function->op_array; (*op_array->refcount)++; if (op_array->static_variables) { HashTable *static_variables = op_array->static_variables; zval *tmp_zval; ALLOC_HASHTABLE(op_array->static_variables); zend_hash_init(op_array->static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(op_array->static_variables, static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_zval, sizeof(zval *)); } op_array->run_time_cache = NULL; } } /* }}} */ static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */ { zend_function *function; if (!ce->parent) { return; } /* You cannot change create_object */ ce->create_object = ce->parent->create_object; /* Inherit special functions if needed */ if (!ce->get_iterator) { ce->get_iterator = ce->parent->get_iterator; } if (!ce->iterator_funcs.funcs) { ce->iterator_funcs.funcs = ce->parent->iterator_funcs.funcs; } if (!ce->__get) { ce->__get = ce->parent->__get; } if (!ce->__set) { ce->__set = ce->parent->__set; } if (!ce->__unset) { ce->__unset = ce->parent->__unset; } if (!ce->__isset) { ce->__isset = ce->parent->__isset; } if (!ce->__call) { ce->__call = ce->parent->__call; } if (!ce->__callstatic) { ce->__callstatic = ce->parent->__callstatic; } if (!ce->__tostring) { ce->__tostring = ce->parent->__tostring; } if (!ce->clone) { ce->clone = ce->parent->clone; } if(!ce->serialize) { ce->serialize = ce->parent->serialize; } if(!ce->unserialize) { ce->unserialize = ce->parent->unserialize; } if (!ce->destructor) { ce->destructor = ce->parent->destructor; } if (ce->constructor) { if (ce->parent->constructor && ce->parent->constructor->common.fn_flags & ZEND_ACC_FINAL) { zend_error(E_ERROR, "Cannot override final %s::%s() with %s::%s()", ce->parent->name, ce->parent->constructor->common.function_name, ce->name, ce->constructor->common.function_name ); } return; } if (zend_hash_find(&ce->parent->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), (void **)&function)==SUCCESS) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), function, sizeof(zend_function), NULL); function_add_ref(function); } else { /* Don't inherit the old style constructor if we already have the new style constructor */ char *lc_class_name; char *lc_parent_class_name; lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); if (!zend_hash_exists(&ce->function_table, lc_class_name, ce->name_length+1)) { lc_parent_class_name = zend_str_tolower_dup(ce->parent->name, ce->parent->name_length); if (!zend_hash_exists(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1) && zend_hash_find(&ce->parent->function_table, lc_parent_class_name, ce->parent->name_length+1, (void **)&function)==SUCCESS) { if (function->common.fn_flags & ZEND_ACC_CTOR) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1, function, sizeof(zend_function), NULL); function_add_ref(function); } } efree(lc_parent_class_name); } efree(lc_class_name); } ce->constructor = ce->parent->constructor; } /* }}} */ char *zend_visibility_string(zend_uint fn_flags) /* {{{ */ { if (fn_flags & ZEND_ACC_PRIVATE) { return "private"; } if (fn_flags & ZEND_ACC_PROTECTED) { return "protected"; } if (fn_flags & ZEND_ACC_PUBLIC) { return "public"; } return ""; } /* }}} */ static void do_inherit_method(zend_function *function) /* {{{ */ { /* The class entry of the derived function intentionally remains the same * as that of the parent class. That allows us to know in which context * we're running, and handle private method calls properly. */ function_add_ref(function); } /* }}} */ static zend_bool zend_do_perform_implementation_check(const zend_function *fe, const zend_function *proto TSRMLS_DC) /* {{{ */ { zend_uint i; /* If it's a user function then arg_info == NULL means we don't have any parameters but * we still need to do the arg number checks. We are only willing to ignore this for internal * functions because extensions don't always define arg_info. */ if (!proto || (!proto->common.arg_info && proto->common.type != ZEND_USER_FUNCTION)) { return 1; } /* Checks for constructors only if they are declared in an interface, * or explicitly marked as abstract */ if ((fe->common.fn_flags & ZEND_ACC_CTOR) && ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)) { return 1; } /* check number of arguments */ if (proto->common.required_num_args < fe->common.required_num_args || proto->common.num_args > fe->common.num_args) { return 0; } if (fe->common.type != ZEND_USER_FUNCTION && (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) != 0 && (fe->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) == 0) { return 0; } /* by-ref constraints on return values are covariant */ if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) { return 0; } for (i=0; i < proto->common.num_args; i++) { if (ZEND_LOG_XOR(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)) { /* Only one has a type hint and the other one doesn't */ return 0; } if (fe->common.arg_info[i].class_name && strcasecmp(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)!=0) { const char *colon; if (fe->common.type != ZEND_USER_FUNCTION) { return 0; } else if (strchr(proto->common.arg_info[i].class_name, '\\') != NULL || (colon = zend_memrchr(fe->common.arg_info[i].class_name, '\\', fe->common.arg_info[i].class_name_len)) == NULL || strcasecmp(colon+1, proto->common.arg_info[i].class_name) != 0) { zend_class_entry **fe_ce, **proto_ce; int found, found2; found = zend_lookup_class(fe->common.arg_info[i].class_name, fe->common.arg_info[i].class_name_len, &fe_ce TSRMLS_CC); found2 = zend_lookup_class(proto->common.arg_info[i].class_name, proto->common.arg_info[i].class_name_len, &proto_ce TSRMLS_CC); /* Check for class alias */ if (found != SUCCESS || found2 != SUCCESS || (*fe_ce)->type == ZEND_INTERNAL_CLASS || (*proto_ce)->type == ZEND_INTERNAL_CLASS || *fe_ce != *proto_ce) { return 0; } } } if (fe->common.arg_info[i].type_hint != proto->common.arg_info[i].type_hint) { /* Incompatible type hint */ return 0; } /* by-ref constraints on arguments are invariant */ if (fe->common.arg_info[i].pass_by_reference != proto->common.arg_info[i].pass_by_reference) { return 0; } } if (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) { for (i=proto->common.num_args; i < fe->common.num_args; i++) { if (!fe->common.arg_info[i].pass_by_reference) { return 0; } } } return 1; } /* }}} */ #define REALLOC_BUF_IF_EXCEED(buf, offset, length, size) \ if (UNEXPECTED(offset - buf + size >= length)) { \ length += size + 1; \ buf = erealloc(buf, length); \ } static char * zend_get_function_declaration(zend_function *fptr TSRMLS_DC) /* {{{ */ { char *offset, *buf; zend_uint length = 1024; offset = buf = (char *)emalloc(length * sizeof(char)); if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { *(offset++) = '&'; *(offset++) = ' '; } if (fptr->common.scope) { memcpy(offset, fptr->common.scope->name, fptr->common.scope->name_length); offset += fptr->common.scope->name_length; *(offset++) = ':'; *(offset++) = ':'; } { size_t name_len = strlen(fptr->common.function_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, name_len); memcpy(offset, fptr->common.function_name, name_len); offset += name_len; } *(offset++) = '('; if (fptr->common.arg_info) { zend_uint i, required; zend_arg_info *arg_info = fptr->common.arg_info; required = fptr->common.required_num_args; for (i = 0; i < fptr->common.num_args;) { if (arg_info->class_name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->class_name_len); memcpy(offset, arg_info->class_name, arg_info->class_name_len); offset += arg_info->class_name_len; *(offset++) = ' '; } else if (arg_info->type_hint) { zend_uint type_name_len; char *type_name = zend_get_type_by_const(arg_info->type_hint); type_name_len = strlen(type_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, type_name_len); memcpy(offset, type_name, type_name_len); offset += type_name_len; *(offset++) = ' '; } if (arg_info->pass_by_reference) { *(offset++) = '&'; } *(offset++) = '$'; if (arg_info->name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->name_len); memcpy(offset, arg_info->name, arg_info->name_len); offset += arg_info->name_len; } else { zend_uint idx = i; memcpy(offset, "param", 5); offset += 5; do { *(offset++) = (char) (idx % 10) + '0'; idx /= 10; } while (idx > 0); } if (i >= required) { *(offset++) = ' '; *(offset++) = '='; *(offset++) = ' '; if (fptr->type == ZEND_USER_FUNCTION) { zend_op *precv = NULL; { zend_uint idx = i; zend_op *op = ((zend_op_array *)fptr)->opcodes; zend_op *end = op + ((zend_op_array *)fptr)->last; ++idx; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT) && op->op1.num == (long)idx) { precv = op; } ++op; } } if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) { zval *zv, zv_copy; int use_copy; ALLOC_ZVAL(zv); *zv = *precv->op2.zv; zval_copy_ctor(zv); INIT_PZVAL(zv); zval_update_constant_ex(&zv, (void*)1, fptr->common.scope TSRMLS_CC); if (Z_TYPE_P(zv) == IS_BOOL) { if (Z_LVAL_P(zv)) { memcpy(offset, "true", 4); offset += 4; } else { memcpy(offset, "false", 5); offset += 5; } } else if (Z_TYPE_P(zv) == IS_NULL) { memcpy(offset, "NULL", 4); offset += 4; } else if (Z_TYPE_P(zv) == IS_STRING) { *(offset++) = '\''; REALLOC_BUF_IF_EXCEED(buf, offset, length, MIN(Z_STRLEN_P(zv), 10)); memcpy(offset, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 10)); offset += MIN(Z_STRLEN_P(zv), 10); if (Z_STRLEN_P(zv) > 10) { *(offset++) = '.'; *(offset++) = '.'; *(offset++) = '.'; } *(offset++) = '\''; } else { zend_make_printable_zval(zv, &zv_copy, &use_copy); REALLOC_BUF_IF_EXCEED(buf, offset, length, Z_STRLEN(zv_copy)); memcpy(offset, Z_STRVAL(zv_copy), Z_STRLEN(zv_copy)); offset += Z_STRLEN(zv_copy); if (use_copy) { zval_dtor(&zv_copy); } } zval_ptr_dtor(&zv); } } else { memcpy(offset, "NULL", 4); offset += 4; } } if (++i < fptr->common.num_args) { *(offset++) = ','; *(offset++) = ' '; } arg_info++; REALLOC_BUF_IF_EXCEED(buf, offset, length, 23); } } *(offset++) = ')'; *offset = '\0'; return buf; } /* }}} */ static void do_inheritance_check_on_method(zend_function *child, zend_function *parent TSRMLS_DC) /* {{{ */ { zend_uint child_flags; zend_uint parent_flags = parent->common.fn_flags; if (parent->common.fn_flags & ZEND_ACC_ABSTRACT && parent->common.scope != (child->common.prototype ? child->common.prototype->common.scope : child->common.scope) && child->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_IMPLEMENTED_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Can't inherit abstract function %s::%s() (previously declared abstract in %s)", parent->common.scope->name, child->common.function_name, child->common.prototype ? child->common.prototype->common.scope->name : child->common.scope->name); } if (parent_flags & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot override final method %s::%s()", ZEND_FN_SCOPE_NAME(parent), child->common.function_name); } child_flags = child->common.fn_flags; /* You cannot change from static to non static and vice versa. */ if ((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC)) { if (child->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot make non static method %s::%s() static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } else { zend_error(E_COMPILE_ERROR, "Cannot make static method %s::%s() non static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } } /* Disallow making an inherited method abstract. */ if ((child_flags & ZEND_ACC_ABSTRACT) && !(parent_flags & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Cannot make non abstract method %s::%s() abstract in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } if (parent_flags & ZEND_ACC_CHANGED) { child->common.fn_flags |= ZEND_ACC_CHANGED; } else { /* Prevent derived classes from restricting access that was available in parent classes */ if ((child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::%s() must be %s (as in class %s)%s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if (((child_flags & ZEND_ACC_PPP_MASK) < (parent_flags & ZEND_ACC_PPP_MASK)) && ((parent_flags & ZEND_ACC_PPP_MASK) & ZEND_ACC_PRIVATE)) { child->common.fn_flags |= ZEND_ACC_CHANGED; } } if (parent_flags & ZEND_ACC_PRIVATE) { child->common.prototype = NULL; } else if (parent_flags & ZEND_ACC_ABSTRACT) { child->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; child->common.prototype = parent; } else if (!(parent->common.fn_flags & ZEND_ACC_CTOR) || (parent->common.prototype && (parent->common.prototype->common.scope->ce_flags & ZEND_ACC_INTERFACE))) { /* ctors only have a prototype if it comes from an interface */ child->common.prototype = parent->common.prototype ? parent->common.prototype : parent; } if (child->common.prototype && (child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { if (!zend_do_perform_implementation_check(child, child->common.prototype TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s::%s() must be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_get_function_declaration(child->common.prototype TSRMLS_CC)); } } else if (EG(error_reporting) & E_STRICT || EG(user_error_handler)) { /* Check E_STRICT (or custom error handler) before the check so that we save some time */ if (!zend_do_perform_implementation_check(child, parent TSRMLS_CC)) { char *method_prototype = zend_get_function_declaration(child->common.prototype TSRMLS_CC); zend_error(E_STRICT, "Declaration of %s::%s() should be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, method_prototype); efree(method_prototype); } } } /* }}} */ static zend_bool do_inherit_method_check(HashTable *child_function_table, zend_function *parent, const zend_hash_key *hash_key, zend_class_entry *child_ce) /* {{{ */ { zend_uint parent_flags = parent->common.fn_flags; zend_function *child; TSRMLS_FETCH(); if (zend_hash_quick_find(child_function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child)==FAILURE) { if (parent_flags & (ZEND_ACC_ABSTRACT)) { child_ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } return 1; /* method doesn't exist in child, copy from parent */ } do_inheritance_check_on_method(child, parent TSRMLS_CC); return 0; } /* }}} */ static zend_bool do_inherit_property_access_check(HashTable *target_ht, zend_property_info *parent_info, const zend_hash_key *hash_key, zend_class_entry *ce) /* {{{ */ { zend_property_info *child_info; zend_class_entry *parent_ce = ce->parent; if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW)) { if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { child_info->flags |= ZEND_ACC_CHANGED; } else { zend_hash_quick_update(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, parent_info, sizeof(zend_property_info), (void **) &child_info); if(ce->type & ZEND_INTERNAL_CLASS) { zend_duplicate_property_info_internal(child_info); } else { zend_duplicate_property_info(child_info); } child_info->flags &= ~ZEND_ACC_PRIVATE; /* it's not private anymore */ child_info->flags |= ZEND_ACC_SHADOW; /* but it's a shadow of private */ } return 0; /* don't copy access information to child */ } if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { if ((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s", (parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", parent_ce->name, hash_key->arKey, (child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ce->name, hash_key->arKey); } if(parent_info->flags & ZEND_ACC_CHANGED) { child_info->flags |= ZEND_ACC_CHANGED; } if ((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ce->name, hash_key->arKey, zend_visibility_string(parent_info->flags), parent_ce->name, (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if ((child_info->flags & ZEND_ACC_STATIC) == 0) { Z_DELREF_P(ce->default_properties_table[parent_info->offset]); ce->default_properties_table[parent_info->offset] = ce->default_properties_table[child_info->offset]; ce->default_properties_table[child_info->offset] = NULL; child_info->offset = parent_info->offset; } return 0; /* Don't copy from parent */ } else { return 1; /* Copy from parent */ } } /* }}} */ static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce TSRMLS_CC) == FAILURE) { zend_error(E_CORE_ERROR, "Class %s could not implement interface %s", ce->name, iface->name); } if (ce == iface) { zend_error(E_ERROR, "Interface %s cannot implement itself", ce->name); } } /* }}} */ ZEND_API void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface TSRMLS_DC) /* {{{ */ { /* expects interface to be contained in ce's interface list already */ zend_uint i, ce_num, if_num = iface->num_interfaces; zend_class_entry *entry; if (if_num==0) { return; } ce_num = ce->num_interfaces; if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } /* Inherit the interfaces, only if they're not already inherited by the class */ while (if_num--) { entry = iface->interfaces[if_num]; for (i = 0; i < ce_num; i++) { if (ce->interfaces[i] == entry) { break; } } if (i == ce_num) { ce->interfaces[ce->num_interfaces++] = entry; } } /* and now call the implementing handlers */ while (ce_num < ce->num_interfaces) { do_implement_interface(ce, ce->interfaces[ce_num++] TSRMLS_CC); } } /* }}} */ #ifdef ZTS static void zval_internal_ctor(zval **p) /* {{{ */ { zval *orig_ptr = *p; ALLOC_ZVAL(*p); MAKE_COPY_ZVAL(&orig_ptr, *p); } /* }}} */ # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) (((parent_ce)->type != (ce)->type) ? zval_internal_ctor : zval_add_ref)) #else # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) zval_add_ref) #endif ZEND_API void zend_do_inheritance(zend_class_entry *ce, zend_class_entry *parent_ce TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; if ((ce->ce_flags & ZEND_ACC_INTERFACE) && !(parent_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ce->name, parent_ce->name); } if (parent_ce->ce_flags & ZEND_ACC_FINAL_CLASS) { zend_error(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ce->name, parent_ce->name); } ce->parent = parent_ce; /* Copy serialize/unserialize callbacks */ if (!ce->serialize) { ce->serialize = parent_ce->serialize; } if (!ce->unserialize) { ce->unserialize = parent_ce->unserialize; } /* Inherit interfaces */ zend_do_inherit_interfaces(ce, parent_ce TSRMLS_CC); /* Inherit properties */ if (parent_ce->default_properties_count) { int i = ce->default_properties_count + parent_ce->default_properties_count; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_properties_count) { while (i-- > parent_ce->default_properties_count) { ce->default_properties_table[i] = ce->default_properties_table[i - parent_ce->default_properties_count]; } } for (i = 0; i < parent_ce->default_properties_count; i++) { ce->default_properties_table[i] = parent_ce->default_properties_table[i]; if (ce->default_properties_table[i]) { #ifdef ZTS if (parent_ce->type != ce->type) { zval *p; ALLOC_ZVAL(p); MAKE_COPY_ZVAL(&ce->default_properties_table[i], p); ce->default_properties_table[i] = p; } else { Z_ADDREF_P(ce->default_properties_table[i]); } #else Z_ADDREF_P(ce->default_properties_table[i]); #endif } } ce->default_properties_count += parent_ce->default_properties_count; } if (parent_ce->type != ce->type) { /* User class extends internal class */ zend_update_class_constants(parent_ce TSRMLS_CC); if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = erealloc(ce->default_static_members_table, sizeof(void*) * i); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&CE_STATIC_MEMBERS(parent_ce)[i]); ce->default_static_members_table[i] = CE_STATIC_MEMBERS(parent_ce)[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; ce->static_members_table = ce->default_static_members_table; } } else { if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&parent_ce->default_static_members_table[i]); ce->default_static_members_table[i] = parent_ce->default_static_members_table[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } } for (zend_hash_internal_pointer_reset(&ce->properties_info); zend_hash_get_current_data(&ce->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->properties_info)) { if (property_info->ce == ce) { if (property_info->flags & ZEND_ACC_STATIC) { property_info->offset += parent_ce->default_static_members_count; } else { property_info->offset += parent_ce->default_properties_count; } } } zend_hash_merge_ex(&ce->properties_info, &parent_ce->properties_info, (copy_ctor_func_t) (ce->type & ZEND_INTERNAL_CLASS ? zend_duplicate_property_info_internal : zend_duplicate_property_info), sizeof(zend_property_info), (merge_checker_func_t) do_inherit_property_access_check, ce); zend_hash_merge(&ce->constants_table, &parent_ce->constants_table, zval_property_ctor(parent_ce, ce), NULL, sizeof(zval *), 0); zend_hash_merge_ex(&ce->function_table, &parent_ce->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_inherit_parent_constructor(ce); if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS && ce->type == ZEND_INTERNAL_CLASS) { ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } else if (!(ce->ce_flags & ZEND_ACC_IMPLEMENT_INTERFACES) && !(ce->ce_flags & ZEND_ACC_IMPLEMENT_TRAITS)) { /* The verification will be done in runtime by ZEND_VERIFY_ABSTRACT_CLASS */ zend_verify_abstract_class(ce TSRMLS_CC); } ce->ce_flags |= parent_ce->ce_flags & ZEND_HAS_STATIC_IN_METHODS; } /* }}} */ static zend_bool do_inherit_constant_check(HashTable *child_constants_table, const zval **parent_constant, const zend_hash_key *hash_key, const zend_class_entry *iface) /* {{{ */ { zval **old_constant; if (zend_hash_quick_find(child_constants_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**)&old_constant) == SUCCESS) { if (*old_constant != *parent_constant) { zend_error(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", hash_key->arKey, iface->name); } return 0; } return 1; } /* }}} */ static int do_interface_constant_check(zval **val TSRMLS_DC, int num_args, va_list args, const zend_hash_key *key) /* {{{ */ { zend_class_entry **iface = va_arg(args, zend_class_entry**); do_inherit_constant_check(&(*iface)->constants_table, (const zval **) val, key, *iface); return ZEND_HASH_APPLY_KEEP; } /* }}} */ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_iface_num = ce->num_interfaces; zend_uint parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0; for (i = 0; i < ce->num_interfaces; i++) { if (ce->interfaces[i] == NULL) { memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i)); i--; } else if (ce->interfaces[i] == iface) { if (i < parent_iface_num) { ignore = 1; } else { zend_error(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ce->name, iface->name); } } } if (ignore) { /* Check for attempt to redeclare interface constants */ zend_hash_apply_with_arguments(&ce->constants_table TSRMLS_CC, (apply_func_args_t) do_interface_constant_check, 1, &iface); } else { if (ce->num_interfaces >= current_iface_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } } ce->interfaces[ce->num_interfaces++] = iface; zend_hash_merge_ex(&ce->constants_table, &iface->constants_table, (copy_ctor_func_t) zval_add_ref, sizeof(zval *), (merge_checker_func_t) do_inherit_constant_check, iface); zend_hash_merge_ex(&ce->function_table, &iface->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_implement_interface(ce, iface TSRMLS_CC); zend_do_inherit_interfaces(ce, iface TSRMLS_CC); } } /* }}} */ ZEND_API void zend_do_implement_trait(zend_class_entry *ce, zend_class_entry *trait TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_trait_num = ce->num_traits; zend_uint parent_trait_num = ce->parent ? ce->parent->num_traits : 0; for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == NULL) { memmove(ce->traits + i, ce->traits + i + 1, sizeof(zend_class_entry*) * (--ce->num_traits - i)); i--; } else if (ce->traits[i] == trait) { if (i < parent_trait_num) { ignore = 1; } } } if (!ignore) { if (ce->num_traits >= current_trait_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->traits = (zend_class_entry **) realloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } else { ce->traits = (zend_class_entry **) erealloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } } ce->traits[ce->num_traits++] = trait; } } /* }}} */ static int zend_traits_merge_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { size_t current; size_t i; size_t count; HashTable* resulting_table; HashTable** function_tables; zend_class_entry *ce; size_t collision = 0; size_t abstract_solved = 0; zend_function* other_trait_fn; current = va_arg(args, size_t); /* index of current trait */ count = va_arg(args, size_t); resulting_table = va_arg(args, HashTable*); function_tables = va_arg(args, HashTable**); ce = va_arg(args, zend_class_entry*); for (i = 0; i < count; i++) { if (i == current) { continue; /* just skip this, cause its the table this function is applied on */ } if (zend_hash_quick_find(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&other_trait_fn) == SUCCESS) { /* if it is an abstract method, there is no collision */ if (other_trait_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* we can savely free and remove it from other table */ zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } else { /* if it is not an abstract method, there is still no collision */ /* if fn is an abstract method */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* just mark as solved, will be added if its own trait is processed */ abstract_solved = 1; } else { /* but else, we have a collision of non-abstract methods */ collision++; zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } } } if (collision) { zend_function* class_fn; /* make sure method is not already overridden in class */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&class_fn) == FAILURE || class_fn->common.scope != ce) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because there are collisions with other trait methods on %s", fn->common.function_name, ce->name); } zend_function_dtor(fn); } else if (abstract_solved) { zend_function_dtor(fn); } else { /* Add it to result function table */ if (zend_hash_quick_add(resulting_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, fn, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating resulting trait method table", fn->common.function_name); } } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ /* {{{ Originates from php_runkit_function_copy_ctor Duplicate structures in an op_array where necessary to make an outright duplicate */ static void zend_traits_duplicate_function(zend_function *fe, zend_class_entry *target_ce, char *newname TSRMLS_DC) { zend_literal *literals_copy; zend_compiled_variable *dupvars; zend_op *opcode_copy; zval class_name_zv; int class_name_literal; int i; int number_of_literals; if (fe->op_array.static_variables) { HashTable *tmpHash; ALLOC_HASHTABLE(tmpHash); zend_hash_init(tmpHash, zend_hash_num_elements(fe->op_array.static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_apply_with_arguments(fe->op_array.static_variables TSRMLS_CC, (apply_func_args_t)zval_copy_static_var, 1, tmpHash); fe->op_array.static_variables = tmpHash; } number_of_literals = fe->op_array.last_literal; literals_copy = (zend_literal*)emalloc(number_of_literals * sizeof(zend_literal)); for (i = 0; i < number_of_literals; i++) { literals_copy[i] = fe->op_array.literals[i]; zval_copy_ctor(&literals_copy[i].constant); } fe->op_array.literals = literals_copy; fe->op_array.refcount = emalloc(sizeof(zend_uint)); *(fe->op_array.refcount) = 1; if (fe->op_array.vars) { i = fe->op_array.last_var; dupvars = safe_emalloc(fe->op_array.last_var, sizeof(zend_compiled_variable), 0); while (i > 0) { i--; dupvars[i].name = estrndup(fe->op_array.vars[i].name, fe->op_array.vars[i].name_len); dupvars[i].name_len = fe->op_array.vars[i].name_len; dupvars[i].hash_value = fe->op_array.vars[i].hash_value; } fe->op_array.vars = dupvars; } else { fe->op_array.vars = NULL; } opcode_copy = safe_emalloc(sizeof(zend_op), fe->op_array.last, 0); for(i = 0; i < fe->op_array.last; i++) { opcode_copy[i] = fe->op_array.opcodes[i]; if (opcode_copy[i].op1_type != IS_CONST) { if (opcode_copy[i].op1.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op1.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op1.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op1.jmp_addr - fe->op_array.opcodes); } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op1.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op1.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op1.zv = &fe->op_array.literals[class_name_literal].constant; } } if (opcode_copy[i].op2_type != IS_CONST) { if (opcode_copy[i].op2.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op2.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op2.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op2.jmp_addr - fe->op_array.opcodes); } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op2.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op2.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op2.zv = &fe->op_array.literals[class_name_literal].constant; } } } fe->op_array.opcodes = opcode_copy; fe->op_array.function_name = newname; /* was setting it to fe which does not work since fe is stack allocated and not a stable address */ /* fe->op_array.prototype = fe->op_array.prototype; */ if (fe->op_array.arg_info) { zend_arg_info *tmpArginfo; tmpArginfo = safe_emalloc(sizeof(zend_arg_info), fe->op_array.num_args, 0); for(i = 0; i < fe->op_array.num_args; i++) { tmpArginfo[i] = fe->op_array.arg_info[i]; tmpArginfo[i].name = estrndup(tmpArginfo[i].name, tmpArginfo[i].name_len); if (tmpArginfo[i].class_name) { tmpArginfo[i].class_name = estrndup(tmpArginfo[i].class_name, tmpArginfo[i].class_name_len); } } fe->op_array.arg_info = tmpArginfo; } fe->op_array.doc_comment = estrndup(fe->op_array.doc_comment, fe->op_array.doc_comment_len); fe->op_array.try_catch_array = (zend_try_catch_element*)estrndup((char*)fe->op_array.try_catch_array, sizeof(zend_try_catch_element) * fe->op_array.last_try_catch); fe->op_array.brk_cont_array = (zend_brk_cont_element*)estrndup((char*)fe->op_array.brk_cont_array, sizeof(zend_brk_cont_element) * fe->op_array.last_brk_cont); } /* }}} */ static void zend_add_magic_methods(zend_class_entry* ce, const char* mname, uint mname_len, zend_function* fe TSRMLS_DC) { if ( !strncmp(mname, ZEND_CLONE_FUNC_NAME, mname_len)) { ce->clone = fe; fe->common.fn_flags |= ZEND_ACC_CLONE; } else if (!strncmp(mname, ZEND_CONSTRUCTOR_FUNC_NAME, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } else if (!strncmp(mname, ZEND_DESTRUCTOR_FUNC_NAME, mname_len)) { ce->destructor = fe; fe->common.fn_flags |= ZEND_ACC_DTOR; } else if (!strncmp(mname, ZEND_GET_FUNC_NAME, mname_len)) ce->__get = fe; else if (!strncmp(mname, ZEND_SET_FUNC_NAME, mname_len)) ce->__set = fe; else if (!strncmp(mname, ZEND_CALL_FUNC_NAME, mname_len)) ce->__call = fe; else if (!strncmp(mname, ZEND_UNSET_FUNC_NAME, mname_len)) ce->__unset = fe; else if (!strncmp(mname, ZEND_ISSET_FUNC_NAME, mname_len)) ce->__isset = fe; else if (!strncmp(mname, ZEND_CALLSTATIC_FUNC_NAME, mname_len)) ce->__callstatic= fe; else if (!strncmp(mname, ZEND_TOSTRING_FUNC_NAME, mname_len)) ce->__tostring = fe; else if (ce->name_length + 1 == mname_len) { char *lowercase_name = emalloc(ce->name_length + 1); zend_str_tolower_copy(lowercase_name, ce->name, ce->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, ce->name_length + 1, 1 TSRMLS_CC); if (!memcmp(mname, lowercase_name, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } str_efree(lowercase_name); } } static int zend_traits_merge_functions_to_class(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zend_class_entry *ce = va_arg(args, zend_class_entry*); int add = 0; zend_function* existing_fn; zend_function fn_copy, *fn_copy_p; zend_function* prototype = NULL; /* is used to determine the prototype according to the inheritance chain */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &existing_fn) == FAILURE) { add = 1; /* not found */ } else if (existing_fn->common.scope != ce) { add = 1; /* or inherited from other class or interface */ /* it is just a reference which was added to the subclass while doing the inheritance */ /* so we can deleted now, and will add the overriding method afterwards */ /* except, if we try to add an abstract function, then we should not delete the inherited one */ /* delete inherited fn if the function to be added is not abstract */ if ((fn->common.fn_flags & ZEND_ACC_ABSTRACT) == 0) { zend_hash_quick_del(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } if (add) { zend_function* parent_function; if (ce->parent && zend_hash_quick_find(&ce->parent->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &parent_function) != FAILURE) { prototype = parent_function; /* ->common.fn_flags |= ZEND_ACC_ABSTRACT; */ /* we got that method in the parent class, and are going to override it, except, if the trait is just asking to have an abstract method implemented. */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* then we clean up an skip this method */ zend_function_dtor(fn); return ZEND_HASH_APPLY_REMOVE; } } fn->common.scope = ce; fn->common.prototype = prototype; if (prototype && (prototype->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT || prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { fn->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; } else if (fn->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT) { /* remove ZEND_ACC_IMPLEMENTED_ABSTRACT flag, think it shouldn't be copied to class */ fn->common.fn_flags = fn->common.fn_flags - ZEND_ACC_IMPLEMENTED_ABSTRACT; } /* check whether the trait method fullfills the inheritance requirements */ if (prototype) { do_inheritance_check_on_method(fn, prototype TSRMLS_CC); } if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (fn->op_array.static_variables) { ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, ce, estrdup(fn->common.function_name) TSRMLS_CC); if (zend_hash_quick_update(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, &fn_copy, sizeof(zend_function), (void**)&fn_copy_p)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating class method table", hash_key->arKey); } zend_add_magic_methods(ce, hash_key->arKey, hash_key->nKeyLength, fn_copy_p TSRMLS_CC); zend_function_dtor(fn); } else { zend_function_dtor(fn); } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ static int zend_traits_copy_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { HashTable* target; zend_class_entry *target_ce; zend_trait_alias** aliases; HashTable* exclude_table; char* lcname; unsigned int fnname_len; zend_function fn_copy; void* dummy; size_t i = 0; target = va_arg(args, HashTable*); target_ce = va_arg(args, zend_class_entry*); aliases = va_arg(args, zend_trait_alias**); exclude_table = va_arg(args, HashTable*); fnname_len = strlen(fn->common.function_name); /* apply aliases which are qualified with a class name, there should not be any ambiguity */ if (aliases) { while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias != NULL && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && aliases[i]->trait_method->mname_len == fnname_len && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(aliases[i]->alias, aliases[i]->alias_len) TSRMLS_CC); /* if it is 0, no modifieres has been changed */ if (aliases[i]->modifiers) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } lcname = zend_str_tolower_dup(aliases[i]->alias, aliases[i]->alias_len); if (zend_hash_add(target, lcname, aliases[i]->alias_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add aliased trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } efree(lcname); } i++; } } lcname = zend_str_tolower_dup(fn->common.function_name, fnname_len); if (exclude_table == NULL || zend_hash_find(exclude_table, lcname, fnname_len, &dummy) == FAILURE) { /* is not in hashtable, thus, function is not to be excluded */ fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(fn->common.function_name, fnname_len) TSRMLS_CC); /* apply aliases which are not qualified by a class name, or which have not * alias name, just setting visibility */ if (aliases) { i = 0; while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias == NULL && aliases[i]->modifiers != 0 && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && (aliases[i]->trait_method->mname_len == fnname_len) && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } i++; } } if (zend_hash_add(target, lcname, fnname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } } efree(lcname); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* Copies function table entries to target function table with applied aliasing */ static void zend_traits_copy_trait_function_table(HashTable *target, zend_class_entry *target_ce, HashTable *source, zend_trait_alias** aliases, HashTable* exclude_table TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_arguments(source TSRMLS_CC, (apply_func_args_t)zend_traits_copy_functions, 4, target, target_ce, aliases, exclude_table); } /* }}} */ static void zend_traits_init_trait_structures(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i, j = 0; zend_trait_precedence *cur_precedence; zend_trait_method_reference *cur_method_ref; /* resolve class references */ if (ce->trait_precedences) { i = 0; while ((cur_precedence = ce->trait_precedences[i])) { if (cur_precedence->exclude_from_classes) { cur_precedence->trait_method->ce = zend_fetch_class(cur_precedence->trait_method->class_name, cur_precedence->trait_method->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); j = 0; while (cur_precedence->exclude_from_classes[j]) { char* class_name = (char*)cur_precedence->exclude_from_classes[j]; zend_uint name_length = strlen(class_name); cur_precedence->exclude_from_classes[j] = zend_fetch_class(class_name, name_length, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); efree(class_name); j++; } } i++; } } if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { if (ce->trait_aliases[i]->trait_method->class_name) { cur_method_ref = ce->trait_aliases[i]->trait_method; cur_method_ref->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); } i++; } } } /* }}} */ static void zend_traits_compile_exclude_table(HashTable* exclude_table, zend_trait_precedence **precedences, zend_class_entry *trait) /* {{{ */ { size_t i = 0, j; if (!precedences) { return; } while (precedences[i]) { if (precedences[i]->exclude_from_classes) { j = 0; while (precedences[i]->exclude_from_classes[j]) { if (precedences[i]->exclude_from_classes[j] == trait) { zend_uint lcname_len = precedences[i]->trait_method->mname_len; char *lcname = zend_str_tolower_dup(precedences[i]->trait_method->method_name, lcname_len); if (zend_hash_add(exclude_table, lcname, lcname_len, NULL, 0, NULL) == FAILURE) { efree(lcname); zend_error(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", precedences[i]->trait_method->method_name, trait->name); } efree(lcname); } ++j; } } ++i; } } /* }}} */ static void zend_do_traits_method_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { HashTable** function_tables; HashTable* resulting_table; HashTable exclude_table; size_t i; /* prepare copies of trait function tables for combination */ function_tables = malloc(sizeof(HashTable*) * ce->num_traits); resulting_table = (HashTable *) malloc(sizeof(HashTable)); /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(resulting_table, 10, NULL, NULL, 1, 0); for (i = 0; i < ce->num_traits; i++) { function_tables[i] = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(function_tables[i], ce->traits[i]->function_table.nNumOfElements, NULL, NULL, 1, 0); if (ce->trait_precedences) { /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(&exclude_table, 2, NULL, NULL, 0, 0); zend_traits_compile_exclude_table(&exclude_table, ce->trait_precedences, ce->traits[i]); /* copies functions, applies defined aliasing, and excludes unused trait methods */ zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, &exclude_table TSRMLS_CC); zend_hash_graceful_destroy(&exclude_table); } else { zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, NULL TSRMLS_CC); } } /* now merge trait methods */ for (i = 0; i < ce->num_traits; i++) { zend_hash_apply_with_arguments(function_tables[i] TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions, 5, i, ce->num_traits, resulting_table, function_tables, ce); } /* Now the resulting_table contains all trait methods we would have to * add to the class in the following step the methods are inserted into the method table * if there is already a method with the same name it is replaced iff ce != fn.scope * --> all inherited methods are overridden, methods defined in the class are left untouched */ zend_hash_apply_with_arguments(resulting_table TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions_to_class, 1, ce); /* free temporary function tables */ for (i = 0; i < ce->num_traits; i++) { /* zend_hash_destroy(function_tables[i]); */ zend_hash_graceful_destroy(function_tables[i]); free(function_tables[i]); } free(function_tables); /* free temporary resulting table */ /* zend_hash_destroy(resulting_table); */ zend_hash_graceful_destroy(resulting_table); free(resulting_table); } /* }}} */ static zend_class_entry* find_first_definition(zend_class_entry *ce, size_t current_trait, const char* prop_name, int prop_name_length, ulong prop_hash, zend_class_entry *coliding_ce) /* {{{ */ { size_t i; zend_property_info *coliding_prop; for (i = 0; (i < current_trait) && (i < ce->num_traits); i++) { if (zend_hash_quick_find(&ce->traits[i]->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS) { return ce->traits[i]; } } return coliding_ce; } /* }}} */ static void zend_do_traits_property_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i; zend_property_info *property_info; zend_property_info *coliding_prop; zval compare_result; const char* prop_name; int prop_name_length; ulong prop_hash; const char* class_name_unused; zend_bool prop_found; zend_bool not_compatible; zval* prop_value; /* In the following steps the properties are inserted into the property table * for that, a very strict approach is applied: * - check for compatibility, if not compatible with any property in class -> fatal * - if compatible, then strict notice */ for (i = 0; i < ce->num_traits; i++) { for (zend_hash_internal_pointer_reset(&ce->traits[i]->properties_info); zend_hash_get_current_data(&ce->traits[i]->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->traits[i]->properties_info)) { /* first get the unmangeld name if necessary, * then check whether the property is already there */ if ((property_info->flags & ZEND_ACC_PPP_MASK) == ZEND_ACC_PUBLIC) { prop_hash = property_info->h; prop_name = property_info->name; prop_name_length = property_info->name_length; prop_found = zend_hash_quick_find(&ce->properties_info, property_info->name, property_info->name_length+1, property_info->h, (void **) &coliding_prop) == SUCCESS; } else { /* for private and protected we need to unmangle the names */ zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name_unused, &prop_name); prop_name_length = strlen(prop_name); prop_hash = zend_get_hash_value(prop_name, prop_name_length + 1); prop_found = zend_hash_quick_find(&ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS; } /* next: check for conflicts with current class */ if (prop_found) { if (coliding_prop->flags & ZEND_ACC_SHADOW) { /* this one is inherited, lets look it up in its own class */ zend_hash_quick_find(&coliding_prop->ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop); } if ((coliding_prop->flags & ZEND_ACC_PPP_MASK) == (property_info->flags & ZEND_ACC_PPP_MASK)) { /* flags are identical, now the value needs to be checked */ if (property_info->flags & ZEND_ACC_STATIC) { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_static_members_table[coliding_prop->offset], ce->traits[i]->default_static_members_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } else { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_properties_table[coliding_prop->offset], ce->traits[i]->default_properties_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } } else { /* the flags are not identical, thus, we assume properties are not compatible */ not_compatible = 1; } if (not_compatible) { zend_error(E_COMPILE_ERROR, "%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } else { zend_error(E_STRICT, "%s and %s define the same property ($%s) in the composition of %s. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } } /* property not found, so lets add it */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); zend_declare_property_ex(ce, prop_name, prop_name_length, prop_value, property_info->flags, property_info->doc_comment, property_info->doc_comment_len TSRMLS_CC); } } } /* }}} */ ZEND_API void zend_do_bind_traits(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { if (ce->num_traits <= 0) { return; } /* complete initialization of trait strutures in ce */ zend_traits_init_trait_structures(ce TSRMLS_CC); /* first care about all methods to be flattened into the class */ zend_do_traits_method_binding(ce TSRMLS_CC); /* then flatten the properties into it, to, mostly to notfiy developer about problems */ zend_do_traits_property_binding(ce TSRMLS_CC); /* verify that all abstract methods from traits have been implemented */ zend_verify_abstract_class(ce TSRMLS_CC); /* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */ if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { ce->ce_flags -= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } } /* }}} */ ZEND_API int do_bind_function(const zend_op_array *op_array, zend_op *opline, HashTable *function_table, zend_bool compile_time) /* {{{ */ { zend_function *function; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } zend_hash_quick_find(function_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void *) &function); if (zend_hash_quick_add(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), function, sizeof(zend_function), NULL)==FAILURE) { int error_level = compile_time ? E_COMPILE_ERROR : E_ERROR; zend_function *old_function; if (zend_hash_quick_find(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), (void *) &old_function)==SUCCESS && old_function->type == ZEND_USER_FUNCTION && old_function->op_array.last > 0) { zend_error(error_level, "Cannot redeclare %s() (previously declared in %s:%d)", function->common.function_name, old_function->op_array.filename, old_function->op_array.opcodes[0].lineno); } else { zend_error(error_level, "Cannot redeclare %s()", function->common.function_name); } return FAILURE; } else { (*function->op_array.refcount)++; function->op_array.static_variables = NULL; /* NULL out the unbound function */ return SUCCESS; } } /* }}} */ void zend_add_trait_precedence(znode *precedence_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_precedences, precedence_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_add_trait_alias(znode *alias_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_aliases, alias_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_prepare_reference(znode *result, znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { zend_trait_method_reference *method_ref = emalloc(sizeof(zend_trait_method_reference)); method_ref->ce = NULL; /* REM: There should not be a need for copying, zend_do_begin_class_declaration is also just using that string */ if (class_name) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); method_ref->class_name = Z_STRVAL(class_name->u.constant); method_ref->cname_len = Z_STRLEN(class_name->u.constant); } else { method_ref->class_name = NULL; method_ref->cname_len = 0; } method_ref->method_name = Z_STRVAL(method_name->u.constant); method_ref->mname_len = Z_STRLEN(method_name->u.constant); result->u.op.ptr = method_ref; result->op_type = IS_TMP_VAR; } /* }}} */ void zend_prepare_trait_alias(znode *result, znode *method_reference, znode *modifiers, znode *alias TSRMLS_DC) /* {{{ */ { zend_trait_alias *trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_alias->modifiers = Z_LVAL(modifiers->u.constant); if (Z_LVAL(modifiers->u.constant) == ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot use 'static' as method modifier"); return; } if (alias) { trait_alias->alias = Z_STRVAL(alias->u.constant); trait_alias->alias_len = Z_STRLEN(alias->u.constant); } else { trait_alias->alias = NULL; } trait_alias->function = NULL; result->u.op.ptr = trait_alias; } /* }}} */ void zend_prepare_trait_precedence(znode *result, znode *method_reference, znode *trait_list TSRMLS_DC) /* {{{ */ { zend_trait_precedence *trait_precedence = emalloc(sizeof(zend_trait_precedence)); trait_precedence->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_precedence->exclude_from_classes = (zend_class_entry**) trait_list->u.op.ptr; trait_precedence->function = NULL; result->u.op.ptr = trait_precedence; } /* }}} */ ZEND_API zend_class_entry *do_bind_class(const zend_op_array* op_array, const zend_op *opline, HashTable *class_table, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } if (zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce)==FAILURE) { zend_error(E_COMPILE_ERROR, "Internal Zend error - Missing class information for %s", Z_STRVAL_P(op1)); return NULL; } else { ce = *pce; } ce->refcount++; if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), &ce, sizeof(zend_class_entry *), NULL)==FAILURE) { ce->refcount--; if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return NULL; } else { if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLEMENT_INTERFACES))) { zend_verify_abstract_class(ce TSRMLS_CC); } return ce; } } /* }}} */ ZEND_API zend_class_entry *do_bind_inherited_class(const zend_op_array *op_array, const zend_op *opline, HashTable *class_table, zend_class_entry *parent_ce, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; int found_ce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } found_ce = zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce); if (found_ce == FAILURE) { if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", Z_STRVAL_P(op2)); } return NULL; } else { ce = *pce; } if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ce->name, parent_ce->name); } else if ((parent_ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ce->name, parent_ce->name); } zend_do_inheritance(ce, parent_ce TSRMLS_CC); ce->refcount++; /* Register the derived class */ if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), pce, sizeof(zend_class_entry *), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return ce; } /* }}} */ void zend_do_early_binding(TSRMLS_D) /* {{{ */ { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; HashTable *table; while (opline->opcode == ZEND_TICKS && opline > CG(active_op_array)->opcodes) { opline--; } switch (opline->opcode) { case ZEND_DECLARE_FUNCTION: if (do_bind_function(CG(active_op_array), opline, CG(function_table), 1) == FAILURE) { return; } table = CG(function_table); break; case ZEND_DECLARE_CLASS: if (do_bind_class(CG(active_op_array), opline, CG(class_table), 1 TSRMLS_CC) == NULL) { return; } table = CG(class_table); break; case ZEND_DECLARE_INHERITED_CLASS: { zend_op *fetch_class_opline = opline-1; zval *parent_name; zend_class_entry **pce; parent_name = &CONSTANT(fetch_class_opline->op2.constant); if ((zend_lookup_class(Z_STRVAL_P(parent_name), Z_STRLEN_P(parent_name), &pce TSRMLS_CC) == FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_CLASSES) && ((*pce)->type == ZEND_INTERNAL_CLASS))) { if (CG(compiler_options) & ZEND_COMPILE_DELAYED_BINDING) { zend_uint *opline_num = &CG(active_op_array)->early_binding; while (*opline_num != -1) { opline_num = &CG(active_op_array)->opcodes[*opline_num].result.opline_num; } *opline_num = opline - CG(active_op_array)->opcodes; opline->opcode = ZEND_DECLARE_INHERITED_CLASS_DELAYED; opline->result_type = IS_UNUSED; opline->result.opline_num = -1; } return; } if (do_bind_inherited_class(CG(active_op_array), opline, CG(class_table), *pce, 1 TSRMLS_CC) == NULL) { return; } /* clear unnecessary ZEND_FETCH_CLASS opcode */ zend_del_literal(CG(active_op_array), fetch_class_opline->op2.constant); MAKE_NOP(fetch_class_opline); table = CG(class_table); break; } case ZEND_VERIFY_ABSTRACT_CLASS: case ZEND_ADD_INTERFACE: case ZEND_ADD_TRAIT: case ZEND_BIND_TRAITS: /* We currently don't early-bind classes that implement interfaces */ /* Classes with traits are handled exactly the same, no early-bind here */ return; default: zend_error(E_COMPILE_ERROR, "Invalid binding type"); return; } zend_hash_quick_del(table, Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant)), Z_HASH_P(&CONSTANT(opline->op1.constant))); zend_del_literal(CG(active_op_array), opline->op1.constant); zend_del_literal(CG(active_op_array), opline->op2.constant); MAKE_NOP(opline); } /* }}} */ ZEND_API void zend_do_delayed_early_binding(const zend_op_array *op_array TSRMLS_DC) /* {{{ */ { if (op_array->early_binding != -1) { zend_bool orig_in_compilation = CG(in_compilation); zend_uint opline_num = op_array->early_binding; zend_class_entry **pce; CG(in_compilation) = 1; while (opline_num != -1) { if (zend_lookup_class(Z_STRVAL_P(op_array->opcodes[opline_num-1].op2.zv), Z_STRLEN_P(op_array->opcodes[opline_num-1].op2.zv), &pce TSRMLS_CC) == SUCCESS) { do_bind_inherited_class(op_array, &op_array->opcodes[opline_num], EG(class_table), *pce, 0 TSRMLS_CC); } opline_num = op_array->opcodes[opline_num].result.opline_num; } CG(in_compilation) = orig_in_compilation; } } /* }}} */ void zend_do_boolean_or_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_or_end(znode *result, const znode *expr1, const znode *expr2, znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_boolean_and_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_and_end(znode *result, const znode *expr1, const znode *expr2, const znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_do_while_begin(TSRMLS_D) /* {{{ */ { do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_do_while_end(const znode *do_token, const znode *expr_open_bracket, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ; SET_NODE(opline->op1, expr); opline->op2.opline_num = do_token->u.op.opline_num; SET_UNUSED(opline->op2); do_end_loop(expr_open_bracket->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_brk_cont(zend_uchar op, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->op1.opline_num = CG(context).current_brk_cont; SET_UNUSED(opline->op1); if (expr) { if (expr->op_type != IS_CONST) { zend_error(E_COMPILE_ERROR, "'%s' operator with non-constant operand is no longer supported", op == ZEND_BRK ? "break" : "continue"); } else if (Z_TYPE(expr->u.constant) != IS_LONG || Z_LVAL(expr->u.constant) < 1) { zend_error(E_COMPILE_ERROR, "'%s' operator accepts only positive numbers", op == ZEND_BRK ? "break" : "continue"); } SET_NODE(opline->op2, expr); } else { LITERAL_LONG(opline->op2, 1); opline->op2_type = IS_CONST; } } /* }}} */ void zend_do_switch_cond(const znode *cond TSRMLS_DC) /* {{{ */ { zend_switch_entry switch_entry; switch_entry.cond = *cond; switch_entry.default_case = -1; switch_entry.control_var = -1; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_switch_end(const znode *case_list TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); /* add code to jmp to default case */ if (switch_entry_ptr->default_case != -1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->op1.opline_num = switch_entry_ptr->default_case; } if (case_list->op_type != IS_UNUSED) { /* non-empty switch */ int next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* remember break/continue loop information */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; if (switch_entry_ptr->cond.op_type==IS_VAR || switch_entry_ptr->cond.op_type==IS_TMP_VAR) { /* emit free for the switch condition*/ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry_ptr->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_UNUSED(opline->op2); } if (switch_entry_ptr->cond.op_type == IS_CONST) { zval_dtor(&switch_entry_ptr->cond.u.constant); } zend_stack_del_top(&CG(switch_cond_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_case_before_statement(const znode *case_list, znode *case_token, const znode *case_expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); int next_op_number; zend_switch_entry *switch_entry_ptr; znode result; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); if (switch_entry_ptr->control_var == -1) { switch_entry_ptr->control_var = get_temporary_variable(CG(active_op_array)); } opline->opcode = ZEND_CASE; opline->result.var = switch_entry_ptr->control_var; opline->result_type = IS_TMP_VAR; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_NODE(opline->op2, case_expr); if (opline->op1_type == IS_CONST) { zval_copy_ctor(&CONSTANT(opline->op1.constant)); } GET_NODE(&result, opline->result); next_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, &result); SET_UNUSED(opline->op2); case_token->u.op.opline_num = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_case_after_statement(znode *result, const znode *case_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); result->u.op.opline_num = next_op_number; switch (CG(active_op_array)->opcodes[case_token->u.op.opline_num].opcode) { case ZEND_JMP: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); break; case ZEND_JMPZ: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); break; } } /* }}} */ void zend_do_default_before_statement(const znode *case_list, znode *default_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); default_token->u.op.opline_num = next_op_number; next_op_number = get_next_op_number(CG(active_op_array)); switch_entry_ptr->default_case = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_begin_class_declaration(const znode *class_token, znode *class_name, const znode *parent_class_name TSRMLS_DC) /* {{{ */ { zend_op *opline; int doing_inheritance = 0; zend_class_entry *new_class_entry; char *lcname; int error = 0; zval **ns_name, key; if (CG(active_class_entry)) { zend_error(E_COMPILE_ERROR, "Class declarations may not be nested"); return; } lcname = zend_str_tolower_dup(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); if (!(strcmp(lcname, "self") && strcmp(lcname, "parent"))) { efree(lcname); zend_error(E_COMPILE_ERROR, "Cannot use '%s' as class name as it is reserved", Z_STRVAL(class_name->u.constant)); } /* Class name must not conflict with import names */ if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns_name) == SUCCESS) { error = 1; } if (CG(current_namespace)) { /* Prefix class name with name of current namespace */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); class_name = &tmp; efree(lcname); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); } if (error) { char *tmp = zend_str_tolower_dup(Z_STRVAL_PP(ns_name), Z_STRLEN_PP(ns_name)); if (Z_STRLEN_PP(ns_name) != Z_STRLEN(class_name->u.constant) || memcmp(tmp, lcname, Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "Cannot declare class %s because the name is already in use", Z_STRVAL(class_name->u.constant)); } efree(tmp); } new_class_entry = emalloc(sizeof(zend_class_entry)); new_class_entry->type = ZEND_USER_CLASS; new_class_entry->name = zend_new_interned_string(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1, 1 TSRMLS_CC); new_class_entry->name_length = Z_STRLEN(class_name->u.constant); zend_initialize_class_data(new_class_entry, 1 TSRMLS_CC); new_class_entry->info.user.filename = zend_get_compiled_filename(TSRMLS_C); new_class_entry->info.user.line_start = class_token->u.op.opline_num; new_class_entry->ce_flags |= class_token->EA; if (parent_class_name && parent_class_name->op_type != IS_UNUSED) { switch (parent_class_name->EA) { case ZEND_FETCH_CLASS_SELF: zend_error(E_COMPILE_ERROR, "Cannot use 'self' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_PARENT: zend_error(E_COMPILE_ERROR, "Cannot use 'parent' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use 'static' as class name as it is reserved"); break; default: break; } doing_inheritance = 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, new_class_entry->name_length TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; if (doing_inheritance) { /* Make sure a trait does not try to extend a class */ if ((new_class_entry->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "A trait (%s) cannot extend a class", new_class_entry->name); } opline->extended_value = parent_class_name->u.op.var; opline->opcode = ZEND_DECLARE_INHERITED_CLASS; } else { opline->opcode = ZEND_DECLARE_CLASS; } LITERAL_STRINGL(opline->op2, lcname, new_class_entry->name_length, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); zend_hash_quick_update(CG(class_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &new_class_entry, sizeof(zend_class_entry *), NULL); CG(active_class_entry) = new_class_entry; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(&CG(implementing_class), opline->result); if (CG(doc_comment)) { CG(active_class_entry)->info.user.doc_comment = CG(doc_comment); CG(active_class_entry)->info.user.doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ static void do_verify_abstract_class(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_VERIFY_ABSTRACT_CLASS; SET_NODE(opline->op1, &CG(implementing_class)); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_class_declaration(const znode *class_token, const znode *parent_token TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); if (ce->constructor) { ce->constructor->common.fn_flags |= ZEND_ACC_CTOR; if (ce->constructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Constructor %s::%s() cannot be static", ce->name, ce->constructor->common.function_name); } } if (ce->destructor) { ce->destructor->common.fn_flags |= ZEND_ACC_DTOR; if (ce->destructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Destructor %s::%s() cannot be static", ce->name, ce->destructor->common.function_name); } } if (ce->clone) { ce->clone->common.fn_flags |= ZEND_ACC_CLONE; if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static", ce->name, ce->clone->common.function_name); } } ce->info.user.line_end = zend_get_compiled_lineno(TSRMLS_C); /* Check for traits and proceed like with interfaces. * The only difference will be a combined handling of them in the end. * Thus, we need another opcode here. */ if (ce->num_traits > 0) { zend_op *opline; ce->traits = NULL; ce->num_traits = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_TRAITS; /* opcode generation: */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BIND_TRAITS; SET_NODE(opline->op1, &CG(implementing_class)); } if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) && ((parent_token->op_type != IS_UNUSED) || (ce->num_interfaces > 0))) { zend_verify_abstract_class(ce TSRMLS_CC); if (ce->num_interfaces) { do_verify_abstract_class(TSRMLS_C); } } /* Inherit interfaces; reset number to zero, we need it for above check and * will restore it during actual implementation. * The ZEND_ACC_IMPLEMENT_INTERFACES flag disables double call to * zend_verify_abstract_class() */ if (ce->num_interfaces > 0) { ce->interfaces = NULL; ce->num_interfaces = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_INTERFACES; } CG(active_class_entry) = NULL; } /* }}} */ void zend_do_implements_interface(znode *interface_name TSRMLS_DC) /* {{{ */ { zend_op *opline; /* Traits can not implement interfaces */ if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface on '%s' since it is a Trait", Z_STRVAL(interface_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(interface_name->u.constant), Z_STRLEN(interface_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface name as it is reserved", Z_STRVAL(interface_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_INTERFACE; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(interface_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = (opline->extended_value & ~ZEND_FETCH_CLASS_MASK) | ZEND_FETCH_CLASS_INTERFACE; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &interface_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_interfaces++; } /* }}} */ void zend_do_implements_trait(znode *trait_name TSRMLS_DC) /* {{{ */ { zend_op *opline; switch (zend_get_class_fetch_type(Z_STRVAL(trait_name->u.constant), Z_STRLEN(trait_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as trait name as it is reserved", Z_STRVAL(trait_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_TRAIT; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(trait_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = ZEND_FETCH_CLASS_TRAIT; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &trait_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_traits++; } /* }}} */ ZEND_API void zend_mangle_property_name(char **dest, int *dest_length, const char *src1, int src1_length, const char *src2, int src2_length, int internal) /* {{{ */ { char *prop_name; int prop_name_length; prop_name_length = 1 + src1_length + 1 + src2_length; prop_name = pemalloc(prop_name_length + 1, internal); prop_name[0] = '\0'; memcpy(prop_name + 1, src1, src1_length+1); memcpy(prop_name + 1 + src1_length + 1, src2, src2_length+1); *dest = prop_name; *dest_length = prop_name_length; } /* }}} */ static int zend_strnlen(const char* s, int maxlen) /* {{{ */ { int len = 0; while (*s++ && maxlen--) len++; return len; } /* }}} */ ZEND_API int zend_unmangle_property_name(const char *mangled_property, int len, const char **class_name, const char **prop_name) /* {{{ */ { int class_name_len; *class_name = NULL; if (mangled_property[0]!=0) { *prop_name = mangled_property; return SUCCESS; } if (len < 3 || mangled_property[1]==0) { zend_error(E_NOTICE, "Illegal member variable name"); *prop_name = mangled_property; return FAILURE; } class_name_len = zend_strnlen(mangled_property+1, --len - 1) + 1; if (class_name_len >= len || mangled_property[class_name_len]!=0) { zend_error(E_NOTICE, "Corrupt member variable name"); *prop_name = mangled_property; return FAILURE; } *class_name = mangled_property+1; *prop_name = (*class_name)+class_name_len; return SUCCESS; } /* }}} */ void zend_do_declare_property(const znode *var_name, const znode *value, zend_uint access_type TSRMLS_DC) /* {{{ */ { zval *property; zend_property_info *existing_property_info; char *comment = NULL; int comment_len = 0; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Interfaces may not include member variables"); } if (access_type & ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Properties cannot be declared abstract"); } if (access_type & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot declare property %s::$%s final, the final modifier is allowed only for methods and classes", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } if (zend_hash_find(&CG(active_class_entry)->properties_info, var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, (void **) &existing_property_info)==SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::$%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } ALLOC_ZVAL(property); if (value) { *property = value->u.constant; } else { INIT_PZVAL(property); Z_TYPE_P(property) = IS_NULL; } if (CG(doc_comment)) { comment = CG(doc_comment); comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } zend_declare_property_ex(CG(active_class_entry), zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len + 1, 0 TSRMLS_CC), var_name->u.constant.value.str.len, property, access_type, comment, comment_len TSRMLS_CC); efree(var_name->u.constant.value.str.val); } /* }}} */ void zend_do_declare_class_constant(znode *var_name, const znode *value TSRMLS_DC) /* {{{ */ { zval *property; const char *cname = NULL; int result; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed in class constants"); return; } if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Traits cannot have constants"); return; } ALLOC_ZVAL(property); *property = value->u.constant; cname = zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, 0 TSRMLS_CC); if (IS_INTERNED(cname)) { result = zend_hash_quick_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, INTERNED_HASH(cname), &property, sizeof(zval *), NULL); } else { result = zend_hash_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, &property, sizeof(zval *), NULL); } if (result == FAILURE) { FREE_ZVAL(property); zend_error(E_COMPILE_ERROR, "Cannot redefine class constant %s::%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } FREE_PNODE(var_name); if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_fetch_property(znode *result, znode *object, const znode *property TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (object->op_type == IS_CV) { if (object->u.op.var == CG(active_op_array)->this_var) { object->op_type = IS_UNUSED; /* this means $this for objects */ } } else if (fetch_list_ptr->count == 1) { zend_llist_element *le = fetch_list_ptr->head; zend_op *opline_ptr = (zend_op *) le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); SET_UNUSED(opline_ptr->op1); /* this means $this for objects */ SET_NODE(opline_ptr->op2, property); /* if it was usual fetch, we change it to object fetch */ switch (opline_ptr->opcode) { case ZEND_FETCH_W: opline_ptr->opcode = ZEND_FETCH_OBJ_W; break; case ZEND_FETCH_R: opline_ptr->opcode = ZEND_FETCH_OBJ_R; break; case ZEND_FETCH_RW: opline_ptr->opcode = ZEND_FETCH_OBJ_RW; break; case ZEND_FETCH_IS: opline_ptr->opcode = ZEND_FETCH_OBJ_IS; break; case ZEND_FETCH_UNSET: opline_ptr->opcode = ZEND_FETCH_OBJ_UNSET; break; case ZEND_FETCH_FUNC_ARG: opline_ptr->opcode = ZEND_FETCH_OBJ_FUNC_ARG; break; } if (opline_ptr->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline_ptr->op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline_ptr->op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op2.constant); } GET_NODE(result, opline_ptr->result); return; } } if (zend_is_function_or_method_call(object)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, object); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_OBJ_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, object); SET_NODE(opline.op2, property); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline.op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op2.constant); } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void zend_do_halt_compiler_register(TSRMLS_D) /* {{{ */ { char *name, *cfilename; char haltoff[] = "__COMPILER_HALT_OFFSET__"; int len, clen; cfilename = zend_get_compiled_filename(TSRMLS_C); clen = strlen(cfilename); zend_mangle_property_name(&name, &len, haltoff, sizeof(haltoff) - 1, cfilename, clen, 0); zend_register_long_constant(name, len+1, zend_get_scanned_file_offset(TSRMLS_C), CONST_CS, 0 TSRMLS_CC); pefree(name, 0); if (CG(in_namespace)) { zend_do_end_namespace(TSRMLS_C); } } /* }}} */ void zend_do_push_object(const znode *object TSRMLS_DC) /* {{{ */ { zend_stack_push(&CG(object_stack), object, sizeof(znode)); } /* }}} */ void zend_do_pop_object(znode *object TSRMLS_DC) /* {{{ */ { if (object) { znode *tmp; zend_stack_top(&CG(object_stack), (void **) &tmp); *object = *tmp; } zend_stack_del_top(&CG(object_stack)); } /* }}} */ void zend_do_begin_new_object(znode *new_token, znode *class_type TSRMLS_DC) /* {{{ */ { zend_op *opline; unsigned char *ptr = NULL; new_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_NEW; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, class_type); SET_UNUSED(opline->op2); zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(unsigned char *)); } /* }}} */ void zend_do_end_new_object(znode *result, const znode *new_token, const znode *argument_list TSRMLS_DC) /* {{{ */ { znode ctor_result; zend_do_end_function_call(NULL, &ctor_result, argument_list, 1, 0 TSRMLS_CC); zend_do_free(&ctor_result TSRMLS_CC); CG(active_op_array)->opcodes[new_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, CG(active_op_array)->opcodes[new_token->u.op.opline_num].result); } /* }}} */ static zend_constant* zend_get_ct_const(const zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = NULL; if (Z_STRVAL_P(const_name)[0] == '\\') { if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name), (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name)-1); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name), (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } } else if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)+1, (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name)+1, (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } if (c->flags & CONST_CT_SUBST) { return c; } if (all_internal_constants_substitution && (c->flags & CONST_PERSISTENT) && !(CG(compiler_options) & ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION) && Z_TYPE(c->value) != IS_CONSTANT && Z_TYPE(c->value) != IS_CONSTANT_ARRAY) { return c; } return NULL; } /* }}} */ static int zend_constant_ct_subst(znode *result, zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = zend_get_ct_const(const_name, all_internal_constants_substitution TSRMLS_CC); if (c) { zval_dtor(const_name); result->op_type = IS_CONST; result->u.constant = c->value; zval_copy_ctor(&result->u.constant); INIT_PZVAL(&result->u.constant); return 1; } return 0; } /* }}} */ void zend_do_fetch_constant(znode *result, znode *constant_container, znode *constant_name, int mode, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; zend_op *opline; int type; char *compound; ulong fetch_type = 0; if (constant_container) { switch (mode) { case ZEND_CT: /* this is a class constant */ type = zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant)); if (ZEND_FETCH_CLASS_STATIC == type) { zend_error(E_ERROR, "\"static::\" is not allowed in compile-time constants"); } else if (ZEND_FETCH_CLASS_DEFAULT == type) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } zend_do_build_full_name(NULL, constant_container, constant_name, 1 TSRMLS_CC); *result = *constant_container; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: if (constant_container->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant))) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } else { zend_do_fetch_class(&tmp, constant_container TSRMLS_CC); constant_container = &tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); if (constant_container->op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &constant_container->u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, constant_container); } SET_NODE(opline->op2, constant_name); CALCULATE_LITERAL_HASH(opline->op2.constant); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } GET_NODE(result, opline->result); break; } return; } /* namespace constant */ /* only one that did not contain \ from the start can be converted to string if unknown */ switch (mode) { case ZEND_CT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); /* this is a namespace constant, or an unprefixed constant */ if (zend_constant_ct_subst(result, &constant_name->u.constant, 0 TSRMLS_CC)) { break; } zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(!compound) { fetch_type |= IS_CONSTANT_UNQUALIFIED; } *result = *constant_name; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(zend_constant_ct_subst(result, &constant_name->u.constant, 1 TSRMLS_CC)) { break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; if (compound) { /* the name is unambiguous */ opline->extended_value = 0; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } else { opline->extended_value = IS_CONSTANT_UNQUALIFIED; if (CG(current_namespace)) { opline->extended_value |= IS_CONSTANT_IN_NAMESPACE; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 1 TSRMLS_CC); } else { opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } } GET_CACHE_SLOT(opline->op2.constant); break; } } /* }}} */ void zend_do_shell_exec(znode *result, const znode *cmd TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); switch (cmd->op_type) { case IS_CONST: case IS_TMP_VAR: opline->opcode = ZEND_SEND_VAL; break; default: opline->opcode = ZEND_SEND_VAR; break; } SET_NODE(opline->op1, cmd); opline->op2.opline_num = 0; opline->extended_value = ZEND_DO_FCALL; SET_UNUSED(opline->op2); /* FIXME: exception support not added to this op2 */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DO_FCALL; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; LITERAL_STRINGL(opline->op1, estrndup("shell_exec", sizeof("shell_exec")-1), sizeof("shell_exec")-1, 0); CALCULATE_LITERAL_HASH(opline->op1.constant); opline->op1_type = IS_CONST; GET_CACHE_SLOT(opline->op1.constant); opline->extended_value = 1; SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_init_array(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_ARRAY; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; GET_NODE(result, opline->result); if (expr) { SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } } else { SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_array_element(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_ARRAY_ELEMENT; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_static_array_element(znode *result, znode *offset, const znode *expr) /* {{{ */ { zval *element; ALLOC_ZVAL(element); *element = expr->u.constant; if (offset) { switch (offset->u.constant.type & IS_CONSTANT_TYPE_MASK) { case IS_CONSTANT: /* Ugly hack to denote that this value has a constant index */ Z_TYPE_P(element) |= IS_CONSTANT_INDEX; Z_STRVAL(offset->u.constant) = erealloc(Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+1] = Z_TYPE(offset->u.constant); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+2] = 0; zend_symtable_update(result->u.constant.value.ht, Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_STRING: zend_symtable_update(result->u.constant.value.ht, offset->u.constant.value.str.val, offset->u.constant.value.str.len+1, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_NULL: zend_symtable_update(Z_ARRVAL(result->u.constant), "", 1, &element, sizeof(zval *), NULL); break; case IS_LONG: case IS_BOOL: zend_hash_index_update(Z_ARRVAL(result->u.constant), Z_LVAL(offset->u.constant), &element, sizeof(zval *), NULL); break; case IS_DOUBLE: zend_hash_index_update(Z_ARRVAL(result->u.constant), zend_dval_to_lval(Z_DVAL(offset->u.constant)), &element, sizeof(zval *), NULL); break; case IS_CONSTANT_ARRAY: zend_error(E_ERROR, "Illegal offset type"); break; } } else { zend_hash_next_index_insert(Z_ARRVAL(result->u.constant), &element, sizeof(zval *), NULL); } } /* }}} */ void zend_do_add_list_element(const znode *element TSRMLS_DC) /* {{{ */ { list_llist_element lle; if (element) { zend_check_writable_variable(element); lle.var = *element; zend_llist_copy(&lle.dimensions, &CG(dimension_llist)); zend_llist_prepend_element(&CG(list_llist), &lle); } (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_new_list_begin(TSRMLS_D) /* {{{ */ { int current_dimension = 0; zend_llist_add_element(&CG(dimension_llist), &current_dimension); } /* }}} */ void zend_do_new_list_end(TSRMLS_D) /* {{{ */ { zend_llist_remove_tail(&CG(dimension_llist)); (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_list_init(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(list_stack), &CG(list_llist), sizeof(zend_llist)); zend_stack_push(&CG(list_stack), &CG(dimension_llist), sizeof(zend_llist)); zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_do_new_list_begin(TSRMLS_C); } /* }}} */ void zend_do_list_end(znode *result, znode *expr TSRMLS_DC) /* {{{ */ { zend_llist_element *le; zend_llist_element *dimension; zend_op *opline; znode last_container; le = CG(list_llist).head; while (le) { zend_llist *tmp_dimension_llist = &((list_llist_element *)le->data)->dimensions; dimension = tmp_dimension_llist->head; while (dimension) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (dimension == tmp_dimension_llist->head) { /* first */ last_container = *expr; switch (expr->op_type) { case IS_VAR: case IS_CV: opline->opcode = ZEND_FETCH_DIM_R; break; case IS_TMP_VAR: opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; case IS_CONST: /* fetch_dim_tmp_var will handle this bogus fetch */ zval_copy_ctor(&expr->u.constant); opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; } opline->extended_value |= ZEND_FETCH_ADD_LOCK; } else { opline->opcode = ZEND_FETCH_DIM_R; } opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, &last_container); opline->op2_type = IS_CONST; LITERAL_LONG(opline->op2, *((int *) dimension->data)); GET_NODE(&last_container, opline->result); dimension = dimension->next; } ((list_llist_element *) le->data)->value = last_container; zend_llist_destroy(&((list_llist_element *) le->data)->dimensions); zend_do_assign(result, &((list_llist_element *) le->data)->var, &((list_llist_element *) le->data)->value TSRMLS_CC); zend_do_free(result TSRMLS_CC); le = le->next; } zend_llist_destroy(&CG(dimension_llist)); zend_llist_destroy(&CG(list_llist)); *result = *expr; { zend_llist *p; /* restore previous lists */ zend_stack_top(&CG(list_stack), (void **) &p); CG(dimension_llist) = *p; zend_stack_del_top(&CG(list_stack)); zend_stack_top(&CG(list_stack), (void **) &p); CG(list_llist) = *p; zend_stack_del_top(&CG(list_stack)); } } /* }}} */ void zend_init_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = emalloc(sizeof(void*) * 2); list[0] = item; list[1] = NULL; *(void**)result = list; } /* }}} */ void zend_add_to_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = *(void**)result; size_t n = 0; while (list && list[n]) { n++; } list = erealloc(list, sizeof(void*) * (n+2)); list[n] = item; list[n+1] = NULL; *(void**)result = list; } /* }}} */ void zend_do_fetch_static_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zval *tmp; zend_op *opline; znode lval; znode result; ALLOC_ZVAL(tmp); if (static_assignment) { *tmp = static_assignment->u.constant; } else { INIT_ZVAL(*tmp); } if (!CG(active_op_array)->static_variables) { if (CG(active_op_array)->scope) { CG(active_op_array)->scope->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } ALLOC_HASHTABLE(CG(active_op_array)->static_variables); zend_hash_init(CG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } zend_hash_update(CG(active_op_array)->static_variables, varname->u.constant.value.str.val, varname->u.constant.value.str.len+1, &tmp, sizeof(zval *), NULL); if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (fetch_type == ZEND_FETCH_LEXICAL) ? ZEND_FETCH_R : ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_STATIC; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ if (fetch_type == ZEND_FETCH_LEXICAL) { znode dummy; zend_do_begin_variable_parse(TSRMLS_C); zend_do_assign(&dummy, &lval, &result TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } else { zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); } CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_fetch_lexical_variable(znode *varname, zend_bool is_ref TSRMLS_DC) /* {{{ */ { znode value; if (Z_STRLEN(varname->u.constant) == sizeof("this") - 1 && memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this") - 1) == 0) { zend_error(E_COMPILE_ERROR, "Cannot use $this as lexical variable"); return; } value.op_type = IS_CONST; ZVAL_NULL(&value.u.constant); Z_TYPE(value.u.constant) |= is_ref ? IS_LEXICAL_REF : IS_LEXICAL_VAR; Z_SET_REFCOUNT_P(&value.u.constant, 1); Z_UNSET_ISREF_P(&value.u.constant); zend_do_fetch_static_variable(varname, &value, is_ref ? ZEND_FETCH_STATIC : ZEND_FETCH_LEXICAL TSRMLS_CC); } /* }}} */ void zend_do_fetch_global_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zend_op *opline; znode lval; znode result; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = fetch_type; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_cast(znode *result, const znode *expr, int type TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CAST; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } /* }}} */ void zend_do_include_or_eval(int type, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_do_extended_fcall_begin(TSRMLS_C); { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INCLUDE_OR_EVAL; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } zend_do_extended_fcall_end(TSRMLS_C); } /* }}} */ void zend_do_indirect_references(znode *result, const znode *num_references, znode *variable TSRMLS_DC) /* {{{ */ { int i; zend_do_end_variable_parse(variable, BP_VAR_R, 0 TSRMLS_CC); for (i=1; i<num_references->u.constant.value.lval; i++) { fetch_simple_variable_ex(result, variable, 0, ZEND_FETCH_R TSRMLS_CC); *variable = *result; } zend_do_begin_variable_parse(TSRMLS_C); fetch_simple_variable(result, variable, 1 TSRMLS_CC); /* there is a chance someone is accessing $this */ if (CG(active_op_array)->scope && CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } /* }}} */ void zend_do_unset(const znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_UNSET_VAR; SET_NODE(opline->op1, variable); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); opline->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_UNSET: last_op->opcode = ZEND_UNSET_VAR; SET_UNUSED(last_op->result); break; case ZEND_FETCH_DIM_UNSET: last_op->opcode = ZEND_UNSET_DIM; SET_UNUSED(last_op->result); break; case ZEND_FETCH_OBJ_UNSET: last_op->opcode = ZEND_UNSET_OBJ; SET_UNUSED(last_op->result); break; } } } /* }}} */ void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_do_end_variable_parse(variable, BP_VAR_IS, 0 TSRMLS_CC); zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { last_op = get_next_op(CG(active_op_array) TSRMLS_CC); last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; SET_NODE(last_op->op1, variable); SET_UNUSED(last_op->op2); last_op->result.var = get_temporary_variable(CG(active_op_array)); last_op->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; break; case ZEND_FETCH_DIM_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_DIM_OBJ; break; case ZEND_FETCH_OBJ_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_PROP_OBJ; break; } } last_op->result_type = IS_TMP_VAR; last_op->extended_value |= type; GET_NODE(result, last_op->result); } /* }}} */ void zend_do_instanceof(znode *result, const znode *expr, const znode *class_znode, int type TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline->opcode == ZEND_FETCH_CLASS) { opline->extended_value |= ZEND_FETCH_CLASS_NO_AUTOLOAD; } } if (expr->op_type == IS_CONST) { zend_error(E_COMPILE_ERROR, "instanceof expects an object instance, constant given"); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INSTANCEOF; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_NODE(opline->op2, class_znode); GET_NODE(result, opline->result); } /* }}} */ void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_bool is_variable; zend_bool push_container = 0; zend_op dummy_opline; if (variable) { if (zend_is_function_or_method_call(array)) { is_variable = 0; } else { is_variable = 1; } /* save the location of FETCH_W instruction(s) */ open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); zend_do_end_variable_parse(array, BP_VAR_W, 0 TSRMLS_CC); if (CG(active_op_array)->last > 0 && CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) { /* Only lock the container if we are fetching from a real container and not $this */ if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1_type == IS_VAR) { CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK; push_container = 1; } } } else { is_variable = 0; open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* save the location of FE_RESET */ foreach_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* Preform array reset */ opline->opcode = ZEND_FE_RESET; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, array); SET_UNUSED(opline->op2); opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0; COPY_NODE(dummy_opline.result, opline->result); if (push_container) { COPY_NODE(dummy_opline.op1, CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1); } else { dummy_opline.op1_type = IS_UNUSED; } zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); /* save the location of FE_FETCH */ as_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FE_FETCH; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); COPY_NODE(opline->op1, dummy_opline.result); opline->extended_value = 0; SET_UNUSED(opline->op2); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_OP_DATA; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); } /* }}} */ void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC) /* {{{ */ { zend_op *opline; znode dummy, value_node; zend_bool assign_by_ref=0; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num]; if (key->op_type != IS_UNUSED) { znode *tmp; /* switch between the key and value... */ tmp = key; key = value; value = tmp; /* Mark extended_value in case both key and value are being used */ opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; } if ((key->op_type != IS_UNUSED) && (key->EA & ZEND_PARSED_REFERENCE_VARIABLE)) { zend_error(E_COMPILE_ERROR, "Key element cannot be a reference"); } if (value->EA & ZEND_PARSED_REFERENCE_VARIABLE) { assign_by_ref = 1; if (!(opline-1)->extended_value) { zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression"); } /* Mark extended_value for assign-by-reference */ opline->extended_value |= ZEND_FE_FETCH_BYREF; CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; } else { zend_op *foreach_copy; zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.op.opline_num]; zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.op.opline_num]; /* Change "write context" into "read context" */ fetch->extended_value = 0; /* reset ZEND_FE_RESET_VARIABLE */ while (fetch != end) { --fetch; if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } if (fetch->opcode == ZEND_SEPARATE) { MAKE_NOP(fetch); } else { fetch->opcode -= 3; /* FETCH_W -> FETCH_R */ } } /* prevent double SWITCH_FREE */ zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy); foreach_copy->op1_type = IS_UNUSED; } GET_NODE(&value_node, opline->result); if (assign_by_ref) { zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); /* Mark FE_FETCH as IS_VAR as it holds the data directly as a value */ zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC); } else { zend_do_assign(&dummy, value, &value_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } if (key->op_type != IS_UNUSED) { znode key_node; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num+1]; opline->result_type = IS_TMP_VAR; opline->result.opline_num = get_temporary_variable(CG(active_op_array)); GET_NODE(&key_node, opline->result); zend_do_assign(&dummy, key, &key_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_foreach_end(const znode *foreach_token, const znode *as_token TSRMLS_DC) /* {{{ */ { zend_op *container_ptr; zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = as_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_RESET */ CG(active_op_array)->opcodes[as_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_FETCH */ do_end_loop(as_token->u.op.opline_num, 1 TSRMLS_CC); zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr); generate_free_foreach_copy(container_ptr TSRMLS_CC); zend_stack_del_top(&CG(foreach_copy_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_declare_begin(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(declare_stack), &CG(declarables), sizeof(zend_declarables)); } /* }}} */ void zend_do_declare_stmt(znode *var, znode *val TSRMLS_DC) /* {{{ */ { if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "ticks", sizeof("ticks")-1)) { convert_to_long(&val->u.constant); CG(declarables).ticks = val->u.constant; } else if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "encoding", sizeof("encoding")-1)) { if ((Z_TYPE(val->u.constant) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Cannot use constants as encoding"); } /* * Check that the pragma comes before any opcodes. If the compilation * got as far as this, the previous portion of the script must have been * parseable according to the .ini script_encoding setting. We still * want to tell them to put declare() at the top. */ { int num = CG(active_op_array)->last; /* ignore ZEND_EXT_STMT and ZEND_TICKS */ while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Encoding declaration pragma must be the very first statement in the script"); } } if (CG(multibyte)) { const zend_encoding *new_encoding, *old_encoding; zend_encoding_filter old_input_filter; CG(encoding_declared) = 1; convert_to_string(&val->u.constant); new_encoding = zend_multibyte_fetch_encoding(val->u.constant.value.str.val TSRMLS_CC); if (!new_encoding) { zend_error(E_COMPILE_WARNING, "Unsupported encoding [%s]", val->u.constant.value.str.val); } else { old_input_filter = LANG_SCNG(input_filter); old_encoding = LANG_SCNG(script_encoding); zend_multibyte_set_filter(new_encoding TSRMLS_CC); /* need to re-scan if input filter changed */ if (old_input_filter != LANG_SCNG(input_filter) || (old_input_filter && new_encoding != old_encoding)) { zend_multibyte_yyinput_again(old_input_filter, old_encoding TSRMLS_CC); } } } else { zend_error(E_COMPILE_WARNING, "declare(encoding=...) ignored because Zend multibyte feature is turned off by settings"); } zval_dtor(&val->u.constant); } else { zend_error(E_COMPILE_WARNING, "Unsupported declare '%s'", var->u.constant.value.str.val); zval_dtor(&val->u.constant); } zval_dtor(&var->u.constant); } /* }}} */ void zend_do_declare_end(const znode *declare_token TSRMLS_DC) /* {{{ */ { zend_declarables *declarables; zend_stack_top(&CG(declare_stack), (void **) &declarables); /* We should restore if there was more than (current - start) - (ticks?1:0) opcodes */ if ((get_next_op_number(CG(active_op_array)) - declare_token->u.op.opline_num) - ((Z_LVAL(CG(declarables).ticks))?1:0)) { CG(declarables) = *declarables; } } /* }}} */ void zend_do_exit(znode *result, const znode *message TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXIT; SET_NODE(opline->op1, message); SET_UNUSED(opline->op2); result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_BOOL; Z_LVAL(result->u.constant) = 1; } /* }}} */ void zend_do_begin_silence(znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BEGIN_SILENCE; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); GET_NODE(strudel_token, opline->result); } /* }}} */ void zend_do_end_silence(const znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_END_SILENCE; SET_NODE(opline->op1, strudel_token); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_jmp_set(const znode *value, znode *jmp_token, znode *colon_token TSRMLS_DC) /* {{{ */ { int op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP_SET; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, value); SET_UNUSED(opline->op2); GET_NODE(colon_token, opline->result); jmp_token->u.op .opline_num = op_number; INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_jmp_set_else(znode *result, const znode *false_value, const znode *jmp_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_QM_ASSIGN; opline->extended_value = 0; SET_NODE(opline->result, colon_token); SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_qm_op(const znode *cond, znode *qm_token TSRMLS_DC) /* {{{ */ { int jmpz_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); SET_UNUSED(opline->op2); opline->op2.opline_num = jmpz_op_number; GET_NODE(qm_token, opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_qm_true(const znode *true_value, znode *qm_token, znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->opcodes[qm_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array))+1; /* jmp over the ZEND_JMP */ opline->opcode = ZEND_QM_ASSIGN; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, true_value); SET_UNUSED(opline->op2); GET_NODE(qm_token, opline->result); colon_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_qm_false(znode *result, const znode *false_value, const znode *qm_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_QM_ASSIGN; SET_NODE(opline->result, qm_token); SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[colon_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, opline->result); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_extended_info(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_STMT; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_begin(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_BEGIN; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_end(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_END; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_ticks(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_TICKS; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->extended_value = Z_LVAL(CG(declarables).ticks); } /* }}} */ zend_bool zend_is_auto_global_quick(const char *name, uint name_len, ulong hashval TSRMLS_DC) /* {{{ */ { zend_auto_global *auto_global; ulong hash = hashval ? hashval : zend_hash_func(name, name_len+1); if (zend_hash_quick_find(CG(auto_globals), name, name_len+1, hash, (void **) &auto_global)==SUCCESS) { if (auto_global->armed) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } return 1; } return 0; } /* }}} */ zend_bool zend_is_auto_global(const char *name, uint name_len TSRMLS_DC) /* {{{ */ { return zend_is_auto_global_quick(name, name_len, 0 TSRMLS_CC); } /* }}} */ int zend_register_auto_global(const char *name, uint name_len, zend_bool jit, zend_auto_global_callback auto_global_callback TSRMLS_DC) /* {{{ */ { zend_auto_global auto_global; auto_global.name = zend_new_interned_string((char*)name, name_len + 1, 0 TSRMLS_CC); auto_global.name_len = name_len; auto_global.auto_global_callback = auto_global_callback; auto_global.jit = jit; return zend_hash_add(CG(auto_globals), name, name_len+1, &auto_global, sizeof(zend_auto_global), NULL); } /* }}} */ static int zend_auto_global_init(zend_auto_global *auto_global TSRMLS_DC) /* {{{ */ { if (auto_global->jit) { auto_global->armed = 1; } else if (auto_global->auto_global_callback) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } else { auto_global->armed = 0; } return 0; } /* }}} */ ZEND_API void zend_activate_auto_globals(TSRMLS_D) /* {{{ */ { zend_hash_apply(CG(auto_globals), (apply_func_t) zend_auto_global_init TSRMLS_CC); } /* }}} */ int zendlex(znode *zendlval TSRMLS_DC) /* {{{ */ { int retval; if (CG(increment_lineno)) { CG(zend_lineno)++; CG(increment_lineno) = 0; } again: Z_TYPE(zendlval->u.constant) = IS_LONG; retval = lex_scan(&zendlval->u.constant TSRMLS_CC); switch (retval) { case T_COMMENT: case T_DOC_COMMENT: case T_OPEN_TAG: case T_WHITESPACE: goto again; case T_CLOSE_TAG: if (LANG_SCNG(yy_text)[LANG_SCNG(yy_leng)-1] != '>') { CG(increment_lineno) = 1; } if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { goto again; } retval = ';'; /* implicit ; */ break; case T_OPEN_TAG_WITH_ECHO: retval = T_ECHO; break; case T_END_HEREDOC: efree(Z_STRVAL(zendlval->u.constant)); break; } INIT_PZVAL(&zendlval->u.constant); zendlval->op_type = IS_CONST; return retval; } /* }}} */ ZEND_API void zend_initialize_class_data(zend_class_entry *ce, zend_bool nullify_handlers TSRMLS_DC) /* {{{ */ { zend_bool persistent_hashes = (ce->type == ZEND_INTERNAL_CLASS) ? 1 : 0; dtor_func_t zval_ptr_dtor_func = ((persistent_hashes) ? ZVAL_INTERNAL_PTR_DTOR : ZVAL_PTR_DTOR); ce->refcount = 1; ce->ce_flags = 0; ce->default_properties_table = NULL; ce->default_static_members_table = NULL; zend_hash_init_ex(&ce->properties_info, 0, NULL, (dtor_func_t) (persistent_hashes ? zend_destroy_property_info_internal : zend_destroy_property_info), persistent_hashes, 0); zend_hash_init_ex(&ce->constants_table, 0, NULL, zval_ptr_dtor_func, persistent_hashes, 0); zend_hash_init_ex(&ce->function_table, 0, NULL, ZEND_FUNCTION_DTOR, persistent_hashes, 0); if (ce->type == ZEND_INTERNAL_CLASS) { #ifdef ZTS int n = zend_hash_num_elements(CG(class_table)); if (CG(static_members_table) && n >= CG(last_static_member)) { /* Support for run-time declaration: dl() */ CG(last_static_member) = n+1; CG(static_members_table) = realloc(CG(static_members_table), (n+1)*sizeof(zval**)); CG(static_members_table)[n] = NULL; } ce->static_members_table = (zval**)(zend_intptr_t)n; #else ce->static_members_table = NULL; #endif } else { ce->static_members_table = ce->default_static_members_table; ce->info.user.doc_comment = NULL; ce->info.user.doc_comment_len = 0; } ce->default_properties_count = 0; ce->default_static_members_count = 0; if (nullify_handlers) { ce->constructor = NULL; ce->destructor = NULL; ce->clone = NULL; ce->__get = NULL; ce->__set = NULL; ce->__unset = NULL; ce->__isset = NULL; ce->__call = NULL; ce->__callstatic = NULL; ce->__tostring = NULL; ce->create_object = NULL; ce->get_iterator = NULL; ce->iterator_funcs.funcs = NULL; ce->interface_gets_implemented = NULL; ce->get_static_method = NULL; ce->parent = NULL; ce->num_interfaces = 0; ce->interfaces = NULL; ce->num_traits = 0; ce->traits = NULL; ce->trait_aliases = NULL; ce->trait_precedences = NULL; ce->serialize = NULL; ce->unserialize = NULL; ce->serialize_func = NULL; ce->unserialize_func = NULL; if (ce->type == ZEND_INTERNAL_CLASS) { ce->info.internal.module = NULL; ce->info.internal.builtin_functions = NULL; } } } /* }}} */ int zend_get_class_fetch_type(const char *class_name, uint class_name_len) /* {{{ */ { if ((class_name_len == sizeof("self")-1) && !memcmp(class_name, "self", sizeof("self")-1)) { return ZEND_FETCH_CLASS_SELF; } else if ((class_name_len == sizeof("parent")-1) && !memcmp(class_name, "parent", sizeof("parent")-1)) { return ZEND_FETCH_CLASS_PARENT; } else if ((class_name_len == sizeof("static")-1) && !memcmp(class_name, "static", sizeof("static")-1)) { return ZEND_FETCH_CLASS_STATIC; } else { return ZEND_FETCH_CLASS_DEFAULT; } } /* }}} */ ZEND_API const char* zend_get_compiled_variable_name(const zend_op_array *op_array, zend_uint var, int* name_len) /* {{{ */ { if (name_len) { *name_len = op_array->vars[var].name_len; } return op_array->vars[var].name; } /* }}} */ void zend_do_build_namespace_name(znode *result, znode *prefix, znode *name TSRMLS_DC) /* {{{ */ { if (prefix) { *result = *prefix; if (Z_TYPE(result->u.constant) == IS_STRING && Z_STRLEN(result->u.constant) == 0) { /* namespace\ */ if (CG(current_namespace)) { znode tmp; zval_dtor(&result->u.constant); tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(result, NULL, &tmp TSRMLS_CC); } } } else { result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_STRING; Z_STRVAL(result->u.constant) = NULL; Z_STRLEN(result->u.constant) = 0; } /* prefix = result */ zend_do_build_full_name(NULL, result, name, 0 TSRMLS_CC); } /* }}} */ void zend_do_begin_namespace(const znode *name, zend_bool with_bracket TSRMLS_DC) /* {{{ */ { char *lcname; /* handle mixed syntax declaration or nested namespaces */ if (!CG(has_bracketed_namespaces)) { if (CG(current_namespace)) { /* previous namespace declarations were unbracketed */ if (with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } } } else { /* previous namespace declarations were bracketed */ if (!with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } else if (CG(current_namespace) || CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "Namespace declarations cannot be nested"); } } if (((!with_bracket && !CG(current_namespace)) || (with_bracket && !CG(has_bracketed_namespaces))) && CG(active_op_array)->last > 0) { /* ignore ZEND_EXT_STMT and ZEND_TICKS */ int num = CG(active_op_array)->last; while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Namespace declaration statement has to be the very first statement in the script"); } } CG(in_namespace) = 1; if (with_bracket) { CG(has_bracketed_namespaces) = 1; } if (name) { lcname = zend_str_tolower_dup(Z_STRVAL(name->u.constant), Z_STRLEN(name->u.constant)); if (((Z_STRLEN(name->u.constant) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN(name->u.constant) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as namespace name", Z_STRVAL(name->u.constant)); } efree(lcname); if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); } else { ALLOC_ZVAL(CG(current_namespace)); } *CG(current_namespace) = name->u.constant; } else { if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_use(znode *ns_name, znode *new_name, int is_global TSRMLS_DC) /* {{{ */ { char *lcname; zval *name, *ns, tmp; zend_bool warn = 0; zend_class_entry **pce; if (!CG(current_import)) { CG(current_import) = emalloc(sizeof(HashTable)); zend_hash_init(CG(current_import), 0, NULL, ZVAL_PTR_DTOR, 0); } ALLOC_ZVAL(ns); *ns = ns_name->u.constant; if (new_name) { name = &new_name->u.constant; } else { const char *p; /* The form "use A\B" is eqivalent to "use A\B as B". So we extract the last part of compound name to use as a new_name */ name = &tmp; p = zend_memrchr(Z_STRVAL_P(ns), '\\', Z_STRLEN_P(ns)); if (p) { ZVAL_STRING(name, p+1, 1); } else { *name = *ns; zval_copy_ctor(name); warn = !is_global && !CG(current_namespace); } } lcname = zend_str_tolower_dup(Z_STRVAL_P(name), Z_STRLEN_P(name)); if (((Z_STRLEN_P(name) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN_P(name) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because '%s' is a special class name", Z_STRVAL_P(ns), Z_STRVAL_P(name), Z_STRVAL_P(name)); } if (CG(current_namespace)) { /* Prefix import name with current namespace name to avoid conflicts with classes */ char *c_ns_name = emalloc(Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) + 1); zend_str_tolower_copy(c_ns_name, Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); c_ns_name[Z_STRLEN_P(CG(current_namespace))] = '\\'; memcpy(c_ns_name+Z_STRLEN_P(CG(current_namespace))+1, lcname, Z_STRLEN_P(name)+1); if (zend_hash_exists(CG(class_table), c_ns_name, Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name)+1)) { char *tmp2 = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) || memcmp(tmp2, c_ns_name, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(tmp2); } efree(c_ns_name); } else if (zend_hash_find(CG(class_table), lcname, Z_STRLEN_P(name)+1, (void**)&pce) == SUCCESS && (*pce)->type == ZEND_USER_CLASS && (*pce)->info.user.filename == CG(compiled_filename)) { char *c_tmp = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(name) || memcmp(c_tmp, lcname, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(c_tmp); } if (zend_hash_add(CG(current_import), lcname, Z_STRLEN_P(name)+1, &ns, sizeof(zval*), NULL) != SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } if (warn) { if (!strcmp(Z_STRVAL_P(name), "strict")) { zend_error(E_COMPILE_ERROR, "You seem to be trying to use a different language..."); } zend_error(E_WARNING, "The use statement with non-compound name '%s' has no effect", Z_STRVAL_P(name)); } efree(lcname); zval_dtor(name); } /* }}} */ void zend_do_declare_constant(znode *name, znode *value TSRMLS_DC) /* {{{ */ { zend_op *opline; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed as constants"); } if (zend_get_ct_const(&name->u.constant, 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare constant '%s'", Z_STRVAL(name->u.constant)); } if (CG(current_namespace)) { /* Prefix constant name with name of current namespace, lowercased */ znode tmp; tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); Z_STRVAL(tmp.u.constant) = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), Z_STRLEN(tmp.u.constant)); zend_do_build_namespace_name(&tmp, &tmp, name TSRMLS_CC); *name = tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DECLARE_CONST; SET_UNUSED(opline->result); SET_NODE(opline->op1, name); SET_NODE(opline->op2, value); } /* }}} */ void zend_verify_namespace(TSRMLS_D) /* {{{ */ { if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "No code may exist outside of namespace {}"); } } /* }}} */ void zend_do_end_namespace(TSRMLS_D) /* {{{ */ { CG(in_namespace) = 0; if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_end_compilation(TSRMLS_D) /* {{{ */ { CG(has_bracketed_namespaces) = 0; zend_do_end_namespace(TSRMLS_C); } /* }}} */ /* {{{ zend_dirname Returns directory name component of path */ ZEND_API size_t zend_dirname(char *path, size_t len) { register char *end = path + len - 1; unsigned int len_adjust = 0; #ifdef PHP_WIN32 /* Note that on Win32 CWD is per drive (heritage from CP/M). * This means dirname("c:foo") maps to "c:." or "c:" - which means CWD on C: drive. */ if ((2 <= len) && isalpha((int)((unsigned char *)path)[0]) && (':' == path[1])) { /* Skip over the drive spec (if any) so as not to change */ path += 2; len_adjust += 2; if (2 == len) { /* Return "c:" on Win32 for dirname("c:"). * It would be more consistent to return "c:." * but that would require making the string *longer*. */ return len; } } #elif defined(NETWARE) /* * Find the first occurence of : from the left * move the path pointer to the position just after : * increment the len_adjust to the length of path till colon character(inclusive) * If there is no character beyond : simple return len */ char *colonpos = NULL; colonpos = strchr(path, ':'); if (colonpos != NULL) { len_adjust = ((colonpos - path) + 1); path += len_adjust; if (len_adjust == len) { return len; } } #endif if (len == 0) { /* Illegal use of this function */ return 0; } /* Strip trailing slashes */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { /* The path only contained slashes */ path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } /* Strip filename */ while (end >= path && !IS_SLASH_P(end)) { end--; } if (end < path) { /* No slash found, therefore return '.' */ #ifdef NETWARE if (len_adjust == 0) { path[0] = '.'; path[1] = '\0'; return 1; /* only one character */ } else { path[0] = '\0'; return len_adjust; } #else path[0] = '.'; path[1] = '\0'; return 1 + len_adjust; #endif } /* Strip slashes which came before the file name */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } *(end+1) = '\0'; return (size_t)(end + 1 - path) + len_adjust; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-10-15-0a1cc5f01c-05c5c8958e.c
manybugs_data_86
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <zend_language_parser.h> #include "zend.h" #include "zend_compile.h" #include "zend_constants.h" #include "zend_llist.h" #include "zend_API.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "zend_multibyte.h" #include "zend_language_scanner.h" #define CONSTANT_EX(op_array, op) \ (op_array)->literals[op].constant #define CONSTANT(op) \ CONSTANT_EX(CG(active_op_array), op) #define SET_NODE(target, src) do { \ target ## _type = (src)->op_type; \ if ((src)->op_type == IS_CONST) { \ target.constant = zend_add_literal(CG(active_op_array), &(src)->u.constant TSRMLS_CC); \ } else { \ target = (src)->u.op; \ } \ } while (0) #define GET_NODE(target, src) do { \ (target)->op_type = src ## _type; \ if ((target)->op_type == IS_CONST) { \ (target)->u.constant = CONSTANT(src.constant); \ } else { \ (target)->u.op = src; \ (target)->EA = 0; \ } \ } while (0) #define COPY_NODE(target, src) do { \ target ## _type = src ## _type; \ target = src; \ } while (0) #define CALCULATE_LITERAL_HASH(num) do { \ if (IS_INTERNED(Z_STRVAL(CONSTANT(num)))) { \ Z_HASH_P(&CONSTANT(num)) = INTERNED_HASH(Z_STRVAL(CONSTANT(num))); \ } else { \ Z_HASH_P(&CONSTANT(num)) = zend_hash_func(Z_STRVAL(CONSTANT(num)), Z_STRLEN(CONSTANT(num))+1); \ } \ } while (0) #define GET_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot++; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ } \ } while (0) #define POLYMORPHIC_CACHE_SLOT_SIZE 2 #define GET_POLYMORPHIC_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot; \ CG(active_op_array)->last_cache_slot += POLYMORPHIC_CACHE_SLOT_SIZE; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 2] = NULL; \ } \ } while (0) #define FREE_POLYMORPHIC_CACHE_SLOT(literal) do { \ if (CG(active_op_array)->literals[literal].cache_slot == \ CG(active_op_array)->last_cache_slot - POLYMORPHIC_CACHE_SLOT_SIZE) { \ CG(active_op_array)->literals[literal].cache_slot = -1; \ CG(active_op_array)->last_cache_slot -= POLYMORPHIC_CACHE_SLOT_SIZE; \ } \ } while (0) ZEND_API zend_op_array *(*zend_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); ZEND_API zend_op_array *(*zend_compile_string)(zval *source_string, char *filename TSRMLS_DC); #ifndef ZTS ZEND_API zend_compiler_globals compiler_globals; ZEND_API zend_executor_globals executor_globals; #endif static void zend_duplicate_property_info(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = estrndup(property_info->name, property_info->name_length); } if (property_info->doc_comment) { property_info->doc_comment = estrndup(property_info->doc_comment, property_info->doc_comment_len); } } /* }}} */ static void zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = zend_strndup(property_info->name, property_info->name_length); } } /* }}} */ static void zend_destroy_property_info(zend_property_info *property_info) /* {{{ */ { str_efree(property_info->name); if (property_info->doc_comment) { efree((char*)property_info->doc_comment); } } /* }}} */ static void zend_destroy_property_info_internal(zend_property_info *property_info) /* {{{ */ { str_free((char*)property_info->name); } /* }}} */ static void build_runtime_defined_function_key(zval *result, const char *name, int name_length TSRMLS_DC) /* {{{ */ { char char_pos_buf[32]; uint char_pos_len; const char *filename; char_pos_len = zend_sprintf(char_pos_buf, "%p", LANG_SCNG(yy_text)); if (CG(active_op_array)->filename) { filename = CG(active_op_array)->filename; } else { filename = "-"; } /* NULL, name length, filename length, last accepting char position length */ result->value.str.len = 1+name_length+strlen(filename)+char_pos_len; /* must be binary safe */ result->value.str.val = (char *) safe_emalloc(result->value.str.len, 1, 1); result->value.str.val[0] = '\0'; sprintf(result->value.str.val+1, "%s%s%s", name, filename, char_pos_buf); result->type = IS_STRING; Z_SET_REFCOUNT_P(result, 1); } /* }}} */ static void init_compiler_declarables(TSRMLS_D) /* {{{ */ { Z_TYPE(CG(declarables).ticks) = IS_LONG; Z_LVAL(CG(declarables).ticks) = 0; } /* }}} */ void zend_init_compiler_context(TSRMLS_D) /* {{{ */ { CG(context).opcodes_size = (CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) ? INITIAL_INTERACTIVE_OP_ARRAY_SIZE : INITIAL_OP_ARRAY_SIZE; CG(context).vars_size = 0; CG(context).literals_size = 0; CG(context).current_brk_cont = -1; CG(context).backpatch_count = 0; CG(context).labels = NULL; } /* }}} */ void zend_init_compiler_data_structures(TSRMLS_D) /* {{{ */ { zend_stack_init(&CG(bp_stack)); zend_stack_init(&CG(function_call_stack)); zend_stack_init(&CG(switch_cond_stack)); zend_stack_init(&CG(foreach_copy_stack)); zend_stack_init(&CG(object_stack)); zend_stack_init(&CG(declare_stack)); CG(active_class_entry) = NULL; zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_stack_init(&CG(list_stack)); CG(in_compilation) = 0; CG(start_lineno) = 0; CG(current_namespace) = NULL; CG(in_namespace) = 0; CG(has_bracketed_namespaces) = 0; CG(current_import) = NULL; init_compiler_declarables(TSRMLS_C); zend_stack_init(&CG(context_stack)); CG(encoding_declared) = 0; } /* }}} */ ZEND_API void file_handle_dtor(zend_file_handle *fh) /* {{{ */ { TSRMLS_FETCH(); zend_file_handle_dtor(fh TSRMLS_CC); } /* }}} */ void init_compiler(TSRMLS_D) /* {{{ */ { CG(active_op_array) = NULL; zend_init_compiler_data_structures(TSRMLS_C); zend_init_rsrc_list(TSRMLS_C); zend_hash_init(&CG(filenames_table), 5, NULL, (dtor_func_t) free_estring, 0); zend_llist_init(&CG(open_files), sizeof(zend_file_handle), (void (*)(void *)) file_handle_dtor, 0); CG(unclean_shutdown) = 0; } /* }}} */ void shutdown_compiler(TSRMLS_D) /* {{{ */ { zend_stack_destroy(&CG(bp_stack)); zend_stack_destroy(&CG(function_call_stack)); zend_stack_destroy(&CG(switch_cond_stack)); zend_stack_destroy(&CG(foreach_copy_stack)); zend_stack_destroy(&CG(object_stack)); zend_stack_destroy(&CG(declare_stack)); zend_stack_destroy(&CG(list_stack)); zend_hash_destroy(&CG(filenames_table)); zend_llist_destroy(&CG(open_files)); zend_stack_destroy(&CG(context_stack)); } /* }}} */ ZEND_API char *zend_set_compiled_filename(const char *new_compiled_filename TSRMLS_DC) /* {{{ */ { char **pp, *p; int length = strlen(new_compiled_filename); if (zend_hash_find(&CG(filenames_table), new_compiled_filename, length+1, (void **) &pp) == SUCCESS) { CG(compiled_filename) = *pp; return *pp; } p = estrndup(new_compiled_filename, length); zend_hash_update(&CG(filenames_table), new_compiled_filename, length+1, &p, sizeof(char *), (void **) &pp); CG(compiled_filename) = p; return p; } /* }}} */ ZEND_API void zend_restore_compiled_filename(char *original_compiled_filename TSRMLS_DC) /* {{{ */ { CG(compiled_filename) = original_compiled_filename; } /* }}} */ ZEND_API char *zend_get_compiled_filename(TSRMLS_D) /* {{{ */ { return CG(compiled_filename); } /* }}} */ ZEND_API int zend_get_compiled_lineno(TSRMLS_D) /* {{{ */ { return CG(zend_lineno); } /* }}} */ ZEND_API zend_bool zend_is_compiling(TSRMLS_D) /* {{{ */ { return CG(in_compilation); } /* }}} */ static zend_uint get_temporary_variable(zend_op_array *op_array) /* {{{ */ { return (op_array->T)++ * ZEND_MM_ALIGNED_SIZE(sizeof(temp_variable)); } /* }}} */ static int lookup_cv(zend_op_array *op_array, char* name, int name_len, ulong hash TSRMLS_DC) /* {{{ */ { int i = 0; ulong hash_value = hash ? hash : zend_inline_hash_func(name, name_len+1); while (i < op_array->last_var) { if (op_array->vars[i].name == name || (op_array->vars[i].hash_value == hash_value && op_array->vars[i].name_len == name_len && memcmp(op_array->vars[i].name, name, name_len) == 0)) { str_efree(name); return i; } i++; } i = op_array->last_var; op_array->last_var++; if (op_array->last_var > CG(context).vars_size) { CG(context).vars_size += 16; /* FIXME */ op_array->vars = erealloc(op_array->vars, CG(context).vars_size * sizeof(zend_compiled_variable)); } op_array->vars[i].name = zend_new_interned_string(name, name_len + 1, 1 TSRMLS_CC); op_array->vars[i].name_len = name_len; op_array->vars[i].hash_value = hash_value; return i; } /* }}} */ void zend_del_literal(zend_op_array *op_array, int n) /* {{{ */ { zval_dtor(&CONSTANT_EX(op_array, n)); if (n + 1 == op_array->last_literal) { op_array->last_literal--; } else { Z_TYPE(CONSTANT_EX(op_array, n)) = IS_NULL; } } /* }}} */ /* Common part of zend_add_literal and zend_append_individual_literal */ static inline void zend_insert_literal(zend_op_array *op_array, const zval *zv, int literal_position TSRMLS_DC) /* {{{ */ { if (Z_TYPE_P(zv) == IS_STRING || Z_TYPE_P(zv) == IS_CONSTANT) { zval *z = (zval*)zv; Z_STRVAL_P(z) = (char*)zend_new_interned_string(Z_STRVAL_P(zv), Z_STRLEN_P(zv) + 1, 1 TSRMLS_CC); } CONSTANT_EX(op_array, literal_position) = *zv; Z_SET_REFCOUNT(CONSTANT_EX(op_array, literal_position), 2); Z_SET_ISREF(CONSTANT_EX(op_array, literal_position)); op_array->literals[literal_position].hash_value = 0; op_array->literals[literal_position].cache_slot = -1; } /* }}} */ /* Is used while compiling a function, using the context to keep track of an approximate size to avoid to relocate to often. Literals are truncated to actual size in the second compiler pass (pass_two()). */ int zend_add_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; if (i >= CG(context).literals_size) { while (i >= CG(context).literals_size) { CG(context).literals_size += 16; /* FIXME */ } op_array->literals = (zend_literal*)erealloc(op_array->literals, CG(context).literals_size * sizeof(zend_literal)); } zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ /* Is used after normal compilation to append an additional literal. Allocation is done precisely here. */ int zend_append_individual_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; op_array->literals = (zend_literal*)erealloc(op_array->literals, (i + 1) * sizeof(zend_literal)); zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ int zend_add_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_ns_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; const char *ns_separator; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); ns_separator = (const char*)zend_memrchr(Z_STRVAL_P(zv), '\\', Z_STRLEN_P(zv)) + 1; lc_len = Z_STRLEN_P(zv) - (ns_separator - Z_STRVAL_P(zv)); lc_name = zend_str_tolower_dup(ns_separator, lc_len); ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_class_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } if (Z_STRVAL_P(zv)[0] == '\\') { lc_len = Z_STRLEN_P(zv) - 1; lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv) + 1, lc_len); } else { lc_len = Z_STRLEN_P(zv); lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), lc_len); } ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); GET_CACHE_SLOT(ret); return ret; } /* }}} */ int zend_add_const_name_literal(zend_op_array *op_array, const zval *zv, int unqualified TSRMLS_DC) /* {{{ */ { int ret, tmp_literal; char *name, *tmp_name; const char *ns_separator; int name_len, ns_len; zval c; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } /* skip leading '\\' */ if (Z_STRVAL_P(zv)[0] == '\\') { name_len = Z_STRLEN_P(zv) - 1; name = Z_STRVAL_P(zv) + 1; } else { name_len = Z_STRLEN_P(zv); name = Z_STRVAL_P(zv); } ns_separator = zend_memrchr(name, '\\', name_len); if (ns_separator) { ns_len = ns_separator - name; } else { ns_len = 0; } if (ns_len) { /* lowercased namespace name & original constant name */ tmp_name = estrndup(name, name_len); zend_str_tolower(tmp_name, ns_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased namespace name & lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); } if (ns_len) { if (!unqualified) { return ret; } ns_len++; name += ns_len; name_len -= ns_len; } /* original constant name */ tmp_name = estrndup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); return ret; } /* }}} */ #define LITERAL_STRINGL(op, str, len, copy) do { \ zval _c; \ ZVAL_STRINGL(&_c, str, len, copy); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG(op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG_EX(op_array, op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(op_array, &_c TSRMLS_CC); \ } while (0) #define LITERAL_NULL(op) do { \ zval _c; \ INIT_ZVAL( _c); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) static inline zend_bool zend_is_function_or_method_call(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; return ((type & ZEND_PARSED_METHOD_CALL) || (type == ZEND_PARSED_FUNCTION_CALL)); } /* }}} */ void zend_do_binary_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_unary_op(zend_uchar op, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); GET_NODE(result, opline->result); SET_UNUSED(opline->op2); } /* }}} */ #define MAKE_NOP(opline) { opline->opcode = ZEND_NOP; memset(&opline->result,0,sizeof(opline->result)); memset(&opline->op1,0,sizeof(opline->op1)); memset(&opline->op2,0,sizeof(opline->op2)); opline->result_type=opline->op1_type=opline->op2_type=IS_UNUSED; } static void zend_do_op_data(zend_op *data_op, const znode *value TSRMLS_DC) /* {{{ */ { data_op->opcode = ZEND_OP_DATA; SET_NODE(data_op->op1, value); SET_UNUSED(data_op->op2); } /* }}} */ void zend_do_binary_assign_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; switch (last_op->opcode) { case ZEND_FETCH_OBJ_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, op2 TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; case ZEND_FETCH_DIM_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_DIM; zend_do_op_data(opline, op2 TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result,last_op->result); return; default: break; } } opline->opcode = op; SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void fetch_simple_variable_ex(znode *result, znode *varname, int bp, zend_uchar op TSRMLS_DC) /* {{{ */ { zend_op opline; zend_op *opline_ptr; zend_llist *fetch_list_ptr; if (varname->op_type == IS_CONST) { ulong hash = 0; if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } else if (IS_INTERNED(Z_STRVAL(varname->u.constant))) { hash = INTERNED_HASH(Z_STRVAL(varname->u.constant)); } if (!zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC) && !(varname->u.constant.value.str.len == (sizeof("this")-1) && !memcmp(varname->u.constant.value.str.val, "this", sizeof("this"))) && (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE)) { result->op_type = IS_CV; result->u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC); varname->u.constant.value.str.val = (char*)CG(active_op_array)->vars[result->u.op.var].name; result->EA = 0; return; } } if (bp) { opline_ptr = &opline; init_op(opline_ptr TSRMLS_CC); } else { opline_ptr = get_next_op(CG(active_op_array) TSRMLS_CC); } opline_ptr->opcode = op; opline_ptr->result_type = IS_VAR; opline_ptr->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline_ptr->op1, varname); GET_NODE(result, opline_ptr->result); SET_UNUSED(opline_ptr->op2); opline_ptr->extended_value = ZEND_FETCH_LOCAL; if (varname->op_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline_ptr->op1.constant); if (zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC)) { opline_ptr->extended_value = ZEND_FETCH_GLOBAL; } } if (bp) { zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); zend_llist_add_element(fetch_list_ptr, opline_ptr); } } /* }}} */ void fetch_simple_variable(znode *result, znode *varname, int bp TSRMLS_DC) /* {{{ */ { /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ fetch_simple_variable_ex(result, varname, bp, ZEND_FETCH_W TSRMLS_CC); } /* }}} */ void zend_do_fetch_static_member(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { znode class_node; zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline_ptr; zend_op opline; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); } zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (result->op_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[result->u.op.var].name), CG(active_op_array)->vars[result->u.op.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } GET_NODE(result,opline.result); opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; opline_ptr = &opline; zend_llist_add_element(fetch_list_ptr, &opline); } else { le = fetch_list_ptr->head; opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode != ZEND_FETCH_W && opline_ptr->op1_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[opline_ptr->op1.var].name), CG(active_op_array)->vars[opline_ptr->op1.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; COPY_NODE(opline_ptr->op1, opline.result); zend_llist_prepend_element(fetch_list_ptr, &opline); } else { if (opline_ptr->op1_type == IS_CONST) { GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op1.constant); } if (class_node.op_type == IS_CONST) { opline_ptr->op2_type = IS_CONST; opline_ptr->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline_ptr->op2, &class_node); } opline_ptr->extended_value |= ZEND_FETCH_STATIC_MEMBER; } } } /* }}} */ void fetch_array_begin(znode *result, znode *varname, znode *first_dim TSRMLS_DC) /* {{{ */ { fetch_simple_variable(result, varname, 1 TSRMLS_CC); fetch_array_dim(result, result, first_dim TSRMLS_CC); } /* }}} */ void fetch_array_dim(znode *result, const znode *parent, const znode *dim TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (zend_is_function_or_method_call(parent)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, parent); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_DIM_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, parent); SET_NODE(opline.op2, dim); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline.op2.constant)), Z_STRLEN(CONSTANT(opline.op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline.op2.constant)); ZVAL_LONG(&CONSTANT(opline.op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline.op2.constant); } } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void fetch_string_offset(znode *result, const znode *parent, const znode *offset TSRMLS_DC) /* {{{ */ { fetch_array_dim(result, parent, offset TSRMLS_CC); } /* }}} */ void zend_do_print(znode *result, const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->opcode = ZEND_PRINT; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_echo(const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ECHO; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_abstract_method(const znode *function_name, znode *modifiers, const znode *body TSRMLS_DC) /* {{{ */ { char *method_type; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { Z_LVAL(modifiers->u.constant) |= ZEND_ACC_ABSTRACT; method_type = "Interface"; } else { method_type = "Abstract"; } if (modifiers->u.constant.value.lval & ZEND_ACC_ABSTRACT) { if(modifiers->u.constant.value.lval & ZEND_ACC_PRIVATE) { zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot be declared private", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } if (Z_LVAL(body->u.constant) == ZEND_ACC_ABSTRACT) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_RAISE_ABSTRACT_ERROR; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } else { /* we had code in the function body */ zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot contain body", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } else { if (body->u.constant.value.lval == ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Non-abstract method %s::%s() must contain body", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } } /* }}} */ static zend_bool opline_is_fetch_this(const zend_op *opline TSRMLS_DC) /* {{{ */ { if ((opline->opcode == ZEND_FETCH_W) && (opline->op1_type == IS_CONST) && (Z_TYPE(CONSTANT(opline->op1.constant)) == IS_STRING) && (Z_HASH_P(&CONSTANT(opline->op1.constant)) == THIS_HASHVAL) && (Z_STRLEN(CONSTANT(opline->op1.constant)) == (sizeof("this")-1)) && !memcmp(Z_STRVAL(CONSTANT(opline->op1.constant)), "this", sizeof("this"))) { return 1; } else { return 0; } } /* }}} */ void zend_do_assign(znode *result, znode *variable, znode *value TSRMLS_DC) /* {{{ */ { int last_op_number; zend_op *opline; if (value->op_type == IS_CV) { zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (fetch_list_ptr && fetch_list_ptr->head) { opline = (zend_op *)fetch_list_ptr->head->data; if (opline->opcode == ZEND_FETCH_DIM_W && opline->op1_type == IS_CV && opline->op1.var == value->u.op.var) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_R; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->op1_type = IS_CONST; LITERAL_STRINGL(opline->op1, CG(active_op_array)->vars[value->u.op.var].name, CG(active_op_array)->vars[value->u.op.var].name_len, 1); CALCULATE_LITERAL_HASH(opline->op1.constant); SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_LOCAL; GET_NODE(value, opline->result); } } } zend_do_end_variable_parse(variable, BP_VAR_W, 0 TSRMLS_CC); last_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (variable->op_type == IS_CV) { if (variable->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (variable->op_type == IS_VAR) { int n = 0; while (last_op_number - n > 0) { zend_op *last_op; last_op = &CG(active_op_array)->opcodes[last_op_number-n-1]; if (last_op->result_type == IS_VAR && last_op->result.var == variable->u.op.var) { if (last_op->opcode == ZEND_FETCH_OBJ_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, value TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (last_op->opcode == ZEND_FETCH_DIM_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ /* TBFixed: this can realloc opcodes, leaving last_op pointing wrong */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_DIM; zend_do_op_data(opline, value TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (opline_is_fetch_this(last_op TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } else { break; } } n++; } } opline->opcode = ZEND_ASSIGN; SET_NODE(opline->op1, variable); SET_NODE(opline->op2, value); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_assign_ref(znode *result, const znode *lvar, const znode *rvar TSRMLS_DC) /* {{{ */ { zend_op *opline; if (lvar->op_type == IS_CV) { if (lvar->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (lvar->op_type == IS_VAR) { int last_op_number = get_next_op_number(CG(active_op_array)); if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline_is_fetch_this(opline TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ASSIGN_REF; if (zend_is_function_or_method_call(rvar)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } else if (rvar->EA & ZEND_PARSED_NEW) { opline->extended_value = ZEND_RETURNS_NEW; } else { opline->extended_value = 0; } if (result) { opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } else { opline->result_type = IS_UNUSED | EXT_TYPE_UNUSED; } SET_NODE(opline->op1, lvar); SET_NODE(opline->op2, rvar); } /* }}} */ static inline void do_begin_loop(TSRMLS_D) /* {{{ */ { zend_brk_cont_element *brk_cont_element; int parent; parent = CG(context).current_brk_cont; CG(context).current_brk_cont = CG(active_op_array)->last_brk_cont; brk_cont_element = get_next_brk_cont_element(CG(active_op_array)); brk_cont_element->start = get_next_op_number(CG(active_op_array)); brk_cont_element->parent = parent; } /* }}} */ static inline void do_end_loop(int cont_addr, int has_loop_var TSRMLS_DC) /* {{{ */ { if (!has_loop_var) { /* The start fileld is used to free temporary variables in case of exceptions. * We won't try to free something of we don't have loop variable. */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].start = -1; } CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = cont_addr; CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; } /* }}} */ void zend_do_while_cond(const znode *expr, znode *close_bracket_token TSRMLS_DC) /* {{{ */ { int while_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, expr); close_bracket_token->u.op.opline_num = while_cond_op_number; SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_while_end(const znode *while_token, const znode *close_bracket_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* add unconditional jump */ opline->opcode = ZEND_JMP; opline->op1.opline_num = while_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* update while's conditional jmp */ CG(active_op_array)->opcodes[close_bracket_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); do_end_loop(while_token->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_cond(const znode *expr, znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { int for_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZNZ; SET_NODE(opline->op1, expr); /* the conditional expression */ second_semicolon_token->u.op.opline_num = for_cond_op_number; SET_UNUSED(opline->op2); } /* }}} */ void zend_do_for_before_statement(const znode *cond_start, const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = cond_start->u.op.opline_num; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_end(const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = second_semicolon_token->u.op.opline_num+1; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_end_loop(second_semicolon_token->u.op.opline_num+1, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_pre_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_PRE_INC)?ZEND_PRE_INC_OBJ:ZEND_PRE_DEC_OBJ; last_op->result_type = IS_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_post_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_POST_INC)?ZEND_POST_INC_OBJ:ZEND_POST_DEC_OBJ; last_op->result_type = IS_TMP_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_if_cond(const znode *cond, znode *closing_bracket_token TSRMLS_DC) /* {{{ */ { int if_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); closing_bracket_token->u.op.opline_num = if_cond_op_number; SET_UNUSED(opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_if_after_statement(const znode *closing_bracket_token, unsigned char initialize TSRMLS_DC) /* {{{ */ { int if_end_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; /* save for backpatching */ if (initialize) { zend_llist jmp_list; zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); } zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &if_end_op_number); CG(active_op_array)->opcodes[closing_bracket_token->u.op.opline_num].op2.opline_num = if_end_op_number+1; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_if_end(TSRMLS_D) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_llist *jmp_list_ptr; zend_llist_element *le; zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); for (le=jmp_list_ptr->head; le; le = le->next) { CG(active_op_array)->opcodes[*((int *) le->data)].op1.opline_num = next_op_number; } zend_llist_destroy(jmp_list_ptr); zend_stack_del_top(&CG(bp_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_check_writable_variable(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; if (type & ZEND_PARSED_METHOD_CALL) { zend_error(E_COMPILE_ERROR, "Can't use method return value in write context"); } if (type == ZEND_PARSED_FUNCTION_CALL) { zend_error(E_COMPILE_ERROR, "Can't use function return value in write context"); } } /* }}} */ void zend_do_begin_variable_parse(TSRMLS_D) /* {{{ */ { zend_llist fetch_list; zend_llist_init(&fetch_list, sizeof(zend_op), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &fetch_list, sizeof(zend_llist)); } /* }}} */ void zend_do_end_variable_parse(znode *variable, int type, int arg_offset TSRMLS_DC) /* {{{ */ { zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline = NULL; zend_op *opline_ptr; zend_uint this_var = -1; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); le = fetch_list_ptr->head; /* TODO: $foo->x->y->z = 1 should fetch "x" and "y" for R or RW, not just W */ if (le) { opline_ptr = (zend_op *)le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { /* convert to FETCH_?(this) into IS_CV */ if (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE) { this_var = opline_ptr->result.var; if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), Z_STRVAL(CONSTANT(opline_ptr->op1.constant)), Z_STRLEN(CONSTANT(opline_ptr->op1.constant)), Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC); Z_TYPE(CONSTANT(opline_ptr->op1.constant)) = IS_NULL; } else { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); } le = le->next; if (variable->op_type == IS_VAR && variable->u.op.var == this_var) { variable->op_type = IS_CV; variable->u.op.var = CG(active_op_array)->this_var; } } else if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } while (le) { opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode == ZEND_SEPARATE) { if (type != BP_VAR_R && type != BP_VAR_IS) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); } le = le->next; continue; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); if (opline->op1_type == IS_VAR && opline->op1.var == this_var) { opline->op1_type = IS_CV; opline->op1.var = CG(active_op_array)->this_var; } switch (type) { case BP_VAR_R: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode -= 3; break; case BP_VAR_W: break; case BP_VAR_RW: opline->opcode += 3; break; case BP_VAR_IS: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode += 6; /* 3+3 */ break; case BP_VAR_FUNC_ARG: opline->opcode += 9; /* 3+3+3 */ opline->extended_value |= arg_offset; break; case BP_VAR_UNSET: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for unsetting"); } opline->opcode += 12; /* 3+3+3+3 */ break; } le = le->next; } if (opline && type == BP_VAR_W && arg_offset) { opline->extended_value |= ZEND_FETCH_MAKE_REF; } } zend_llist_destroy(fetch_list_ptr); zend_stack_del_top(&CG(bp_stack)); } /* }}} */ void zend_do_add_string(znode *result, const znode *op1, znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline; if (Z_STRLEN(op2->u.constant) > 1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_STRING; } else if (Z_STRLEN(op2->u.constant) == 1) { int ch = *Z_STRVAL(op2->u.constant); /* Free memory and use ZEND_ADD_CHAR in case of 1 character strings */ efree(Z_STRVAL(op2->u.constant)); ZVAL_LONG(&op2->u.constant, ch); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_CHAR; } else { /* String can be empty after a variable at the end of a heredoc */ efree(Z_STRVAL(op2->u.constant)); return; } if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_add_variable(znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_VAR; if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_free(znode *op1 TSRMLS_DC) /* {{{ */ { if (op1->op_type==IS_TMP_VAR) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else if (op1->op_type==IS_VAR) { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; while (opline->opcode == ZEND_END_SILENCE || opline->opcode == ZEND_EXT_FCALL_END || opline->opcode == ZEND_OP_DATA) { opline--; } if (opline->result_type == IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_FETCH_R || opline->opcode == ZEND_FETCH_DIM_R || opline->opcode == ZEND_FETCH_OBJ_R || opline->opcode == ZEND_QM_ASSIGN_VAR) { /* It's very rare and useless case. It's better to use additional FREE opcode and simplify the FETCH handlers their selves */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else { opline->result_type |= EXT_TYPE_UNUSED; } } else { while (opline>CG(active_op_array)->opcodes) { if (opline->opcode == ZEND_FETCH_DIM_R && opline->op1_type == IS_VAR && opline->op1.var == op1->u.op.var) { /* This should the end of a list() construct * Mark its result as unused */ opline->extended_value = ZEND_FETCH_STANDARD; break; } else if (opline->result_type==IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_NEW) { opline->result_type |= EXT_TYPE_UNUSED; } break; } opline--; } } } else if (op1->op_type == IS_CONST) { zval_dtor(&op1->u.constant); } } /* }}} */ int zend_do_verify_access_types(const znode *current_access_type, const znode *new_modifier) /* {{{ */ { if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_PPP_MASK) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Multiple access type modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_ABSTRACT) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Multiple abstract modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_STATIC) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Multiple static modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_FINAL) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Multiple final modifiers are not allowed"); } if (((Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)) & (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) == (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Cannot use the final modifier on an abstract class member"); } return (Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)); } /* }}} */ void zend_do_begin_function_declaration(znode *function_token, znode *function_name, int is_method, int return_reference, znode *fn_flags_znode TSRMLS_DC) /* {{{ */ { zend_op_array op_array; char *name = function_name->u.constant.value.str.val; int name_len = function_name->u.constant.value.str.len; int function_begin_line = function_token->u.op.opline_num; zend_uint fn_flags; const char *lcname; zend_bool orig_interactive; ALLOCA_FLAG(use_heap) if (is_method) { if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((Z_LVAL(fn_flags_znode->u.constant) & ~(ZEND_ACC_STATIC|ZEND_ACC_PUBLIC))) { zend_error(E_COMPILE_ERROR, "Access type for interface method %s::%s() must be omitted", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } Z_LVAL(fn_flags_znode->u.constant) |= ZEND_ACC_ABSTRACT; /* propagates to the rest of the parser */ } fn_flags = Z_LVAL(fn_flags_znode->u.constant); /* must be done *after* the above check */ } else { fn_flags = 0; } if ((fn_flags & ZEND_ACC_STATIC) && (fn_flags & ZEND_ACC_ABSTRACT) && !(CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_STRICT, "Static function %s%s%s() should not be abstract", is_method ? CG(active_class_entry)->name : "", is_method ? "::" : "", Z_STRVAL(function_name->u.constant)); } function_token->u.op_array = CG(active_op_array); orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(&op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; op_array.function_name = name; if (return_reference) { op_array.fn_flags |= ZEND_ACC_RETURN_REFERENCE; } op_array.fn_flags |= fn_flags; op_array.scope = is_method?CG(active_class_entry):NULL; op_array.prototype = NULL; op_array.line_start = zend_get_compiled_lineno(TSRMLS_C); if (is_method) { int result; lcname = zend_new_interned_string(zend_str_tolower_dup(name, name_len), name_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lcname)) { result = zend_hash_quick_add(&CG(active_class_entry)->function_table, lcname, name_len+1, INTERNED_HASH(lcname), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } else { result = zend_hash_add(&CG(active_class_entry)->function_table, lcname, name_len+1, &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } if (result == FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::%s()", CG(active_class_entry)->name, name); } zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); if (fn_flags & ZEND_ACC_ABSTRACT) { CG(active_class_entry)->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (!(fn_flags & ZEND_ACC_PPP_MASK)) { fn_flags |= ZEND_ACC_PUBLIC; } if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } } } else { char *class_lcname; class_lcname = do_alloca(CG(active_class_entry)->name_length + 1, use_heap); zend_str_tolower_copy(class_lcname, CG(active_class_entry)->name, CG(active_class_entry)->name_length); /* Improve after RC: cache the lowercase class name */ if ((CG(active_class_entry)->name_length == name_len) && ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT) && (!memcmp(class_lcname, lcname, name_len))) { if (!CG(active_class_entry)->constructor) { CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } } else if ((name_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)))) { if (CG(active_class_entry)->constructor) { zend_error(E_STRICT, "Redefining already defined constructor for class %s", CG(active_class_entry)->name); } CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1))) { CG(active_class_entry)->destructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1))) { CG(active_class_entry)->clone = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } CG(active_class_entry)->__call = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } CG(active_class_entry)->__callstatic = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } CG(active_class_entry)->__get = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } CG(active_class_entry)->__set = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } CG(active_class_entry)->__unset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } CG(active_class_entry)->__isset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } CG(active_class_entry)->__tostring = (zend_function *) CG(active_op_array); } else if (!(fn_flags & ZEND_ACC_STATIC)) { CG(active_op_array)->fn_flags |= ZEND_ACC_ALLOW_STATIC; } free_alloca(class_lcname, use_heap); } str_efree(lcname); } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zval key; if (CG(current_namespace)) { /* Prefix function name with current namespcae name */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, function_name TSRMLS_CC); op_array.function_name = Z_STRVAL(tmp.u.constant); name_len = Z_STRLEN(tmp.u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), name_len); } else { lcname = zend_str_tolower_dup(name, name_len); } opline->opcode = ZEND_DECLARE_FUNCTION; opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, name_len TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; LITERAL_STRINGL(opline->op2, lcname, name_len, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); opline->extended_value = ZEND_DECLARE_FUNCTION; zend_hash_quick_update(CG(function_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); } if (CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_NOP; opline->lineno = function_begin_line; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } { /* Push a seperator to the switch and foreach stacks */ zend_switch_entry switch_entry; switch_entry.cond.op_type = IS_UNUSED; switch_entry.default_case = 0; switch_entry.control_var = 0; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); { /* Foreach stack separator */ zend_op dummy_opline; dummy_opline.result_type = IS_UNUSED; dummy_opline.op1_type = IS_UNUSED; zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); } } if (CG(doc_comment)) { CG(active_op_array)->doc_comment = CG(doc_comment); CG(active_op_array)->doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_begin_lambda_function_declaration(znode *result, znode *function_token, int return_reference, int is_static TSRMLS_DC) /* {{{ */ { znode function_name; zend_op_array *current_op_array = CG(active_op_array); int current_op_number = get_next_op_number(CG(active_op_array)); zend_op *current_op; function_name.op_type = IS_CONST; ZVAL_STRINGL(&function_name.u.constant, "{closure}", sizeof("{closure}")-1, 1); zend_do_begin_function_declaration(function_token, &function_name, 0, return_reference, NULL TSRMLS_CC); result->op_type = IS_TMP_VAR; result->u.op.var = get_temporary_variable(current_op_array); current_op = &current_op_array->opcodes[current_op_number]; current_op->opcode = ZEND_DECLARE_LAMBDA_FUNCTION; zend_del_literal(current_op_array, current_op->op2.constant); SET_UNUSED(current_op->op2); SET_NODE(current_op->result, result); if (is_static) { CG(active_op_array)->fn_flags |= ZEND_ACC_STATIC; } CG(active_op_array)->fn_flags |= ZEND_ACC_CLOSURE; } /* }}} */ void zend_do_handle_exception(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_HANDLE_EXCEPTION; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_function_declaration(const znode *function_token TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; zend_do_extended_info(TSRMLS_C); zend_do_return(NULL, 0 TSRMLS_CC); pass_two(CG(active_op_array) TSRMLS_CC); zend_release_labels(TSRMLS_C); if (CG(active_class_entry)) { zend_check_magic_method_implementation(CG(active_class_entry), (zend_function*)CG(active_op_array), E_COMPILE_ERROR TSRMLS_CC); } else { /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(CG(active_op_array)->function_name); zend_str_tolower_copy(lcname, CG(active_op_array)->function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME)) && CG(active_op_array)->num_args != 1) { zend_error(E_COMPILE_ERROR, "%s() must take exactly 1 argument", ZEND_AUTOLOAD_FUNC_NAME); } } CG(active_op_array)->line_end = zend_get_compiled_lineno(TSRMLS_C); CG(active_op_array) = function_token->u.op_array; /* Pop the switch and foreach seperators */ zend_stack_del_top(&CG(switch_cond_stack)); zend_stack_del_top(&CG(foreach_copy_stack)); } /* }}} */ void zend_do_receive_arg(zend_uchar op, znode *varname, const znode *offset, const znode *initialization, znode *class_type, zend_uchar pass_by_reference TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_arg_info *cur_arg_info; znode var; if (class_type->op_type == IS_CONST && Z_TYPE(class_type->u.constant) == IS_STRING && Z_STRLEN(class_type->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_type->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } if (zend_is_auto_global_quick(Z_STRVAL(varname->u.constant), Z_STRLEN(varname->u.constant), 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign auto-global variable %s", Z_STRVAL(varname->u.constant)); } else { var.op_type = IS_CV; var.u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(varname->u.constant) = (char*)CG(active_op_array)->vars[var.u.op.var].name; var.EA = 0; if (CG(active_op_array)->vars[var.u.op.var].hash_value == THIS_HASHVAL && Z_STRLEN(varname->u.constant) == sizeof("this")-1 && !memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this")-1)) { if (CG(active_op_array)->scope && (CG(active_op_array)->fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } CG(active_op_array)->this_var = var.u.op.var; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->num_args++; opline->opcode = op; SET_NODE(opline->result, &var); SET_NODE(opline->op1, offset); if (op == ZEND_RECV_INIT) { SET_NODE(opline->op2, initialization); } else { CG(active_op_array)->required_num_args = CG(active_op_array)->num_args; SET_UNUSED(opline->op2); } CG(active_op_array)->arg_info = erealloc(CG(active_op_array)->arg_info, sizeof(zend_arg_info)*(CG(active_op_array)->num_args)); cur_arg_info = &CG(active_op_array)->arg_info[CG(active_op_array)->num_args-1]; cur_arg_info->name = zend_new_interned_string(estrndup(varname->u.constant.value.str.val, varname->u.constant.value.str.len), varname->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->name_len = varname->u.constant.value.str.len; cur_arg_info->type_hint = 0; cur_arg_info->allow_null = 1; cur_arg_info->pass_by_reference = pass_by_reference; cur_arg_info->class_name = NULL; cur_arg_info->class_name_len = 0; if (class_type->op_type != IS_UNUSED) { cur_arg_info->allow_null = 0; if (class_type->u.constant.type != IS_NULL) { if (class_type->u.constant.type == IS_ARRAY) { cur_arg_info->type_hint = IS_ARRAY; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else if (Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Default value for parameters with array type hint can only be an array or NULL"); } } } else if (class_type->u.constant.type == IS_CALLABLE) { cur_arg_info->type_hint = IS_CALLABLE; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with callable type hint can only be NULL"); } } } else { cur_arg_info->type_hint = IS_OBJECT; if (ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_type->u.constant), Z_STRLEN(class_type->u.constant))) { zend_resolve_class_name(class_type, opline->extended_value, 1 TSRMLS_CC); } Z_STRVAL(class_type->u.constant) = (char*)zend_new_interned_string(class_type->u.constant.value.str.val, class_type->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->class_name = class_type->u.constant.value.str.val; cur_arg_info->class_name_len = class_type->u.constant.value.str.len; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with a class type hint can only be NULL"); } } } } } } /* }}} */ int zend_do_begin_function_call(znode *function_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { zend_function *function; char *lcname; char *is_compound = memchr(Z_STRVAL(function_name->u.constant), '\\', Z_STRLEN(function_name->u.constant)); zend_resolve_non_class_name(function_name, check_namespace TSRMLS_CC); if (check_namespace && CG(current_namespace) && !is_compound) { /* We assume we call function from the current namespace if it is not prefixed. */ /* In run-time PHP will check for function with full name and internal function with short name */ zend_do_begin_dynamic_function_call(function_name, 1 TSRMLS_CC); return 1; } lcname = zend_str_tolower_dup(function_name->u.constant.value.str.val, function_name->u.constant.value.str.len); if ((zend_hash_find(CG(function_table), lcname, function_name->u.constant.value.str.len+1, (void **) &function)==FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_FUNCTIONS) && (function->type == ZEND_INTERNAL_FUNCTION))) { zend_do_begin_dynamic_function_call(function_name, 0 TSRMLS_CC); efree(lcname); return 1; /* Dynamic */ } efree(function_name->u.constant.value.str.val); function_name->u.constant.value.str.val = lcname; zend_stack_push(&CG(function_call_stack), (void *) &function, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 0; } /* }}} */ void zend_do_begin_method_call(znode *left_bracket TSRMLS_DC) /* {{{ */ { zend_op *last_op; int last_op_number; unsigned char *ptr = NULL; zend_do_end_variable_parse(left_bracket, BP_VAR_R, 0 TSRMLS_CC); zend_do_begin_variable_parse(TSRMLS_C); last_op_number = get_next_op_number(CG(active_op_array))-1; last_op = &CG(active_op_array)->opcodes[last_op_number]; if ((last_op->op2_type == IS_CONST) && (Z_TYPE(CONSTANT(last_op->op2.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(last_op->op2.constant)) == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !zend_binary_strcasecmp(Z_STRVAL(CONSTANT(last_op->op2.constant)), Z_STRLEN(CONSTANT(last_op->op2.constant)), ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1)) { zend_error(E_COMPILE_ERROR, "Cannot call __clone() method on objects - use 'clone $obj' instead"); } if (last_op->opcode == ZEND_FETCH_OBJ_R) { if (last_op->op2_type == IS_CONST) { zval name; name = CONSTANT(last_op->op2.constant); if (!IS_INTERNED(Z_STRVAL(name))) { Z_STRVAL(name) = estrndup(Z_STRVAL(name), Z_STRLEN(name)); } FREE_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); last_op->op2.constant = zend_add_func_name_literal(CG(active_op_array), &name TSRMLS_CC); GET_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); } last_op->opcode = ZEND_INIT_METHOD_CALL; SET_UNUSED(last_op->result); Z_LVAL(left_bracket->u.constant) = ZEND_INIT_FCALL_BY_NAME; } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (left_bracket->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &left_bracket->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, left_bracket); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_do_clone(znode *result, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CLONE; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_begin_dynamic_function_call(znode *function_name, int ns_call TSRMLS_DC) /* {{{ */ { unsigned char *ptr = NULL; zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (ns_call) { /* In run-time PHP will check for function with full name and internal function with short name */ opline->opcode = ZEND_INIT_NS_FCALL_BY_NAME; SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_ns_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (function_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, function_name); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_resolve_non_class_name(znode *element_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; int len; zval **ns; char *lcname, *compound = memchr(Z_STRVAL(element_name->u.constant), '\\', Z_STRLEN(element_name->u.constant)); if (Z_STRVAL(element_name->u.constant)[0] == '\\') { /* name starts with \ so it is known and unambiguos, nothing to do here but shorten it */ memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+1, Z_STRLEN(element_name->u.constant)); --Z_STRLEN(element_name->u.constant); return; } if(!check_namespace) { return; } if (compound && CG(current_import)) { len = compound - Z_STRVAL(element_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(element_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(element_name->u.constant) -= len; memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+len, Z_STRLEN(element_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, element_name TSRMLS_CC); *element_name = tmp; efree(lcname); return; } efree(lcname); } if (CG(current_namespace)) { tmp = *element_name; Z_STRLEN(tmp.u.constant) = sizeof("\\")-1 + Z_STRLEN(element_name->u.constant) + Z_STRLEN_P(CG(current_namespace)); Z_STRVAL(tmp.u.constant) = (char *) emalloc(Z_STRLEN(tmp.u.constant)+1); memcpy(Z_STRVAL(tmp.u.constant), Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace))]), "\\", sizeof("\\")-1); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace)) + sizeof("\\")-1]), Z_STRVAL(element_name->u.constant), Z_STRLEN(element_name->u.constant)+1); STR_FREE(Z_STRVAL(element_name->u.constant)); *element_name = tmp; } } /* }}} */ void zend_resolve_class_name(znode *class_name, ulong fetch_type, int check_ns_name TSRMLS_DC) /* {{{ */ { char *compound; char *lcname; zval **ns; znode tmp; int len; compound = memchr(Z_STRVAL(class_name->u.constant), '\\', Z_STRLEN(class_name->u.constant)); if (compound) { /* This is a compound class name that contains namespace prefix */ if (Z_STRVAL(class_name->u.constant)[0] == '\\') { /* The STRING name has "\" prefix */ Z_STRLEN(class_name->u.constant) -= 1; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+1, Z_STRLEN(class_name->u.constant)+1); Z_STRVAL(class_name->u.constant) = erealloc( Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1); if (ZEND_FETCH_CLASS_DEFAULT != zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "'\\%s' is an invalid class name", Z_STRVAL(class_name->u.constant)); } } else { if (CG(current_import)) { len = compound - Z_STRVAL(class_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(class_name->u.constant) -= len; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+len, Z_STRLEN(class_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; efree(lcname); return; } efree(lcname); } /* Here name is not prefixed with \ and not imported */ if (CG(current_namespace)) { tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } } } else if (CG(current_import) || CG(current_namespace)) { /* this is a plain name (without \) */ lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns) == SUCCESS) { /* The given name is an import name. Substitute it. */ zval_dtor(&class_name->u.constant); class_name->u.constant = **ns; zval_copy_ctor(&class_name->u.constant); } else if (CG(current_namespace)) { /* plain name, no import - prepend current namespace to it */ tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } efree(lcname); } } /* }}} */ void zend_do_fetch_class(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { long fetch_class_op_number; zend_op *opline; if (class_name->op_type == IS_CONST && Z_TYPE(class_name->u.constant) == IS_STRING && Z_STRLEN(class_name->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_name->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } fetch_class_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CLASS; SET_UNUSED(opline->op1); opline->extended_value = ZEND_FETCH_CLASS_GLOBAL; CG(catch_begin) = fetch_class_op_number; if (class_name->op_type == IS_CONST) { int fetch_type; fetch_type = zend_get_class_fetch_type(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); switch (fetch_type) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: SET_UNUSED(opline->op2); opline->extended_value = fetch_type; zval_dtor(&class_name->u.constant); break; default: zend_resolve_class_name(class_name, opline->extended_value, 0 TSRMLS_CC); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_name->u.constant TSRMLS_CC); break; } } else { SET_NODE(opline->op2, class_name); } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; /* FIXME: Hack so that INIT_FCALL_BY_NAME still knows this is a class */ GET_NODE(result, opline->result); result->EA = opline->extended_value; } /* }}} */ void zend_do_label(znode *label TSRMLS_DC) /* {{{ */ { zend_label dest; if (!CG(context).labels) { ALLOC_HASHTABLE(CG(context).labels); zend_hash_init(CG(context).labels, 4, NULL, NULL, 0); } dest.brk_cont = CG(context).current_brk_cont; dest.opline_num = get_next_op_number(CG(active_op_array)); if (zend_hash_add(CG(context).labels, Z_STRVAL(label->u.constant), Z_STRLEN(label->u.constant) + 1, (void**)&dest, sizeof(zend_label), NULL) == FAILURE) { zend_error(E_COMPILE_ERROR, "Label '%s' already defined", Z_STRVAL(label->u.constant)); } /* Done with label now */ zval_dtor(&label->u.constant); } /* }}} */ void zend_resolve_goto_label(zend_op_array *op_array, zend_op *opline, int pass2 TSRMLS_DC) /* {{{ */ { zend_label *dest; long current, distance; zval *label; if (pass2) { label = opline->op2.zv; } else { label = &CONSTANT_EX(op_array, opline->op2.constant); } if (CG(context).labels == NULL || zend_hash_find(CG(context).labels, Z_STRVAL_P(label), Z_STRLEN_P(label)+1, (void**)&dest) == FAILURE) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; zend_error(E_COMPILE_ERROR, "'goto' to undefined label '%s'", Z_STRVAL_P(label)); } else { /* Label is not defined. Delay to pass 2. */ INC_BPC(op_array); return; } } opline->op1.opline_num = dest->opline_num; zval_dtor(label); Z_TYPE_P(label) = IS_NULL; /* Check that we are not moving into loop or switch */ current = opline->extended_value; for (distance = 0; current != dest->brk_cont; distance++) { if (current == -1) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; } zend_error(E_COMPILE_ERROR, "'goto' into loop or switch statement is disallowed"); } current = op_array->brk_cont_array[current].parent; } if (distance == 0) { /* Nothing to break out of, optimize to ZEND_JMP */ opline->opcode = ZEND_JMP; opline->extended_value = 0; SET_UNUSED(opline->op2); } else { /* Set real break distance */ ZVAL_LONG(label, distance); } if (pass2) { DEC_BPC(op_array); } } /* }}} */ void zend_do_goto(const znode *label TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_GOTO; opline->extended_value = CG(context).current_brk_cont; SET_UNUSED(opline->op1); SET_NODE(opline->op2, label); zend_resolve_goto_label(CG(active_op_array), opline, 0 TSRMLS_CC); } /* }}} */ void zend_release_labels(TSRMLS_D) /* {{{ */ { if (CG(context).labels) { zend_hash_destroy(CG(context).labels); FREE_HASHTABLE(CG(context).labels); } if (!zend_stack_is_empty(&CG(context_stack))) { zend_compiler_context *ctx; zend_stack_top(&CG(context_stack), (void**)&ctx); CG(context) = *ctx; zend_stack_del_top(&CG(context_stack)); } } /* }}} */ void zend_do_build_full_name(znode *result, znode *prefix, znode *name, int is_class_member TSRMLS_DC) /* {{{ */ { zend_uint length; if (!result) { result = prefix; } else { *result = *prefix; } if (is_class_member) { length = sizeof("::")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "::", sizeof("::")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("::")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } else { length = sizeof("\\")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "\\", sizeof("\\")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("\\")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } } /* }}} */ int zend_do_begin_class_member_function_call(znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { znode class_node; unsigned char *ptr = NULL; zend_op *opline; if (method_name->op_type == IS_CONST) { char *lcname = zend_str_tolower_dup(Z_STRVAL(method_name->u.constant), Z_STRLEN(method_name->u.constant)); if ((sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == Z_STRLEN(method_name->u.constant) && memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == 0) { zval_dtor(&method_name->u.constant); method_name->op_type = IS_UNUSED; } efree(lcname); } if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; opline = get_next_op(CG(active_op_array) TSRMLS_CC); } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->extended_value = class_node.EA ; } opline->opcode = ZEND_INIT_STATIC_METHOD_CALL; if (class_node.op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, &class_node); } if (method_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &method_name->u.constant TSRMLS_CC); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } } else { SET_NODE(opline->op2, method_name); } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 1; /* Dynamic */ } /* }}} */ void zend_do_end_function_call(znode *function_name, znode *result, const znode *argument_list, int is_method, int is_dynamic_fcall TSRMLS_DC) /* {{{ */ { zend_op *opline; if (is_method && function_name && function_name->op_type == IS_UNUSED) { /* clone */ if (Z_LVAL(argument_list->u.constant) != 0) { zend_error(E_WARNING, "Clone method does not require arguments"); } opline = &CG(active_op_array)->opcodes[Z_LVAL(function_name->u.constant)]; } else { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (!is_method && !is_dynamic_fcall && function_name->op_type==IS_CONST) { opline->opcode = ZEND_DO_FCALL; SET_NODE(opline->op1, function_name); CALCULATE_LITERAL_HASH(opline->op1.constant); GET_CACHE_SLOT(opline->op1.constant); } else { opline->opcode = ZEND_DO_FCALL_BY_NAME; SET_UNUSED(opline->op1); } } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(result, opline->result) ; SET_UNUSED(opline->op2); zend_stack_del_top(&CG(function_call_stack)); opline->extended_value = Z_LVAL(argument_list->u.constant); } /* }}} */ void zend_do_pass_param(znode *param, zend_uchar op, int offset TSRMLS_DC) /* {{{ */ { zend_op *opline; int original_op=op; zend_function **function_ptr_ptr, *function_ptr; int send_by_reference; int send_function = 0; zend_stack_top(&CG(function_call_stack), (void **) &function_ptr_ptr); function_ptr = *function_ptr_ptr; if (original_op == ZEND_SEND_REF) { if (function_ptr && function_ptr->common.function_name && function_ptr->common.type == ZEND_USER_FUNCTION && !ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed; " "If you would like to pass argument by reference, modify the declaration of %s().", function_ptr->common.function_name); } else { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed"); } return; } if (function_ptr) { if (ARG_MAY_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { if (param->op_type & (IS_VAR|IS_CV) && original_op != ZEND_SEND_VAL) { send_by_reference = 1; if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION | ZEND_ARG_SEND_SILENT; } } else { op = ZEND_SEND_VAL; send_by_reference = 0; } } else { send_by_reference = ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset) ? ZEND_ARG_SEND_BY_REF : 0; } } else { send_by_reference = 0; } if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION; } else if (op == ZEND_SEND_VAL && (param->op_type & (IS_VAR|IS_CV))) { op = ZEND_SEND_VAR_NO_REF; } if (op!=ZEND_SEND_VAR_NO_REF && send_by_reference==ZEND_ARG_SEND_BY_REF) { /* change to passing by reference */ switch (param->op_type) { case IS_VAR: case IS_CV: op = ZEND_SEND_REF; break; default: zend_error(E_COMPILE_ERROR, "Only variables can be passed by reference"); break; } } if (original_op == ZEND_SEND_VAR) { switch (op) { case ZEND_SEND_VAR_NO_REF: zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); break; case ZEND_SEND_VAR: if (function_ptr) { zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(param, BP_VAR_FUNC_ARG, offset TSRMLS_CC); } break; case ZEND_SEND_REF: zend_do_end_variable_parse(param, BP_VAR_W, 0 TSRMLS_CC); break; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (op == ZEND_SEND_VAR_NO_REF) { if (function_ptr) { opline->extended_value = ZEND_ARG_COMPILE_TIME_BOUND | send_by_reference | send_function; } else { opline->extended_value = send_function; } } else { if (function_ptr) { opline->extended_value = ZEND_DO_FCALL; } else { opline->extended_value = ZEND_DO_FCALL_BY_NAME; } } opline->opcode = op; SET_NODE(opline->op1, param); opline->op2.opline_num = offset; SET_UNUSED(opline->op2); } /* }}} */ static int generate_free_switch_expr(const zend_switch_entry *switch_entry TSRMLS_DC) /* {{{ */ { zend_op *opline; if (switch_entry->cond.op_type != IS_VAR && switch_entry->cond.op_type != IS_TMP_VAR) { return (switch_entry->cond.op_type == IS_UNUSED); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry->cond); SET_UNUSED(opline->op2); opline->extended_value = 0; return 0; } /* }}} */ static int generate_free_foreach_copy(const zend_op *foreach_copy TSRMLS_DC) /* {{{ */ { zend_op *opline; /* If we reach the seperator then stop applying the stack */ if (foreach_copy->result_type == IS_UNUSED && foreach_copy->op1_type == IS_UNUSED) { return 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->result_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->result); SET_UNUSED(opline->op2); opline->extended_value = 1; if (foreach_copy->op1_type != IS_UNUSED) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->op1_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->op1); SET_UNUSED(opline->op2); opline->extended_value = 0; } return 0; } /* }}} */ void zend_do_return(znode *expr, int do_end_vparse TSRMLS_DC) /* {{{ */ { zend_op *opline; int start_op_number, end_op_number; if (do_end_vparse) { if ((CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) && !zend_is_function_or_method_call(expr)) { zend_do_end_variable_parse(expr, BP_VAR_W, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(expr, BP_VAR_R, 0 TSRMLS_CC); } } start_op_number = get_next_op_number(CG(active_op_array)); #ifdef ZTS zend_stack_apply_with_argument(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_switch_expr TSRMLS_CC); zend_stack_apply_with_argument(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_foreach_copy TSRMLS_CC); #else zend_stack_apply(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_switch_expr); zend_stack_apply(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_foreach_copy); #endif end_op_number = get_next_op_number(CG(active_op_array)); while (start_op_number < end_op_number) { CG(active_op_array)->opcodes[start_op_number].extended_value |= EXT_TYPE_FREE_ON_RETURN; start_op_number++; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) ? ZEND_RETURN_BY_REF : ZEND_RETURN; if (expr) { SET_NODE(opline->op1, expr); if (do_end_vparse && zend_is_function_or_method_call(expr)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } } else { opline->op1_type = IS_CONST; LITERAL_NULL(opline->op1); } SET_UNUSED(opline->op2); } /* }}} */ static int zend_add_try_element(zend_uint try_op TSRMLS_DC) /* {{{ */ { int try_catch_offset = CG(active_op_array)->last_try_catch++; CG(active_op_array)->try_catch_array = erealloc(CG(active_op_array)->try_catch_array, sizeof(zend_try_catch_element)*CG(active_op_array)->last_try_catch); CG(active_op_array)->try_catch_array[try_catch_offset].try_op = try_op; return try_catch_offset; } /* }}} */ static void zend_add_catch_element(int offset, zend_uint catch_op TSRMLS_DC) /* {{{ */ { CG(active_op_array)->try_catch_array[offset].catch_op = catch_op; } /* }}} */ void zend_do_first_catch(znode *open_parentheses TSRMLS_DC) /* {{{ */ { open_parentheses->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_initialize_try_catch_element(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist jmp_list; zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); zend_add_catch_element(try_token->u.op.opline_num, get_next_op_number(CG(active_op_array)) TSRMLS_CC); } /* }}} */ void zend_do_mark_last_catch(const znode *first_catch, const znode *last_additional_catch TSRMLS_DC) /* {{{ */ { CG(active_op_array)->last--; zend_do_if_end(TSRMLS_C); if (last_additional_catch->u.op.opline_num == -1) { CG(active_op_array)->opcodes[first_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[first_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } else { CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_try(znode *try_token TSRMLS_DC) /* {{{ */ { try_token->u.op.opline_num = zend_add_try_element(get_next_op_number(CG(active_op_array)) TSRMLS_CC); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_catch(znode *try_token, znode *class_name, znode *catch_var, znode *first_catch TSRMLS_DC) /* {{{ */ { long catch_op_number; zend_op *opline; znode catch_class; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); catch_class = *class_name; } else { zend_error(E_COMPILE_ERROR, "Bad class name in the catch statement"); } catch_op_number = get_next_op_number(CG(active_op_array)); if (first_catch) { first_catch->u.op.opline_num = catch_op_number; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CATCH; opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &catch_class.u.constant TSRMLS_CC); opline->op2_type = IS_CV; opline->op2.var = lookup_cv(CG(active_op_array), catch_var->u.constant.value.str.val, catch_var->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(catch_var->u.constant) = (char*)CG(active_op_array)->vars[opline->op2.var].name; opline->result.num = 0; /* 1 means it's the last catch in the block */ try_token->u.op.opline_num = catch_op_number; } /* }}} */ void zend_do_end_catch(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); CG(active_op_array)->opcodes[try_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_throw(const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_THROW; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); } /* }}} */ ZEND_API void function_add_ref(zend_function *function) /* {{{ */ { if (function->type == ZEND_USER_FUNCTION) { zend_op_array *op_array = &function->op_array; (*op_array->refcount)++; if (op_array->static_variables) { HashTable *static_variables = op_array->static_variables; zval *tmp_zval; ALLOC_HASHTABLE(op_array->static_variables); zend_hash_init(op_array->static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(op_array->static_variables, static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_zval, sizeof(zval *)); } op_array->run_time_cache = NULL; } } /* }}} */ static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */ { zend_function *function; if (!ce->parent) { return; } /* You cannot change create_object */ ce->create_object = ce->parent->create_object; /* Inherit special functions if needed */ if (!ce->get_iterator) { ce->get_iterator = ce->parent->get_iterator; } if (!ce->iterator_funcs.funcs) { ce->iterator_funcs.funcs = ce->parent->iterator_funcs.funcs; } if (!ce->__get) { ce->__get = ce->parent->__get; } if (!ce->__set) { ce->__set = ce->parent->__set; } if (!ce->__unset) { ce->__unset = ce->parent->__unset; } if (!ce->__isset) { ce->__isset = ce->parent->__isset; } if (!ce->__call) { ce->__call = ce->parent->__call; } if (!ce->__callstatic) { ce->__callstatic = ce->parent->__callstatic; } if (!ce->__tostring) { ce->__tostring = ce->parent->__tostring; } if (!ce->clone) { ce->clone = ce->parent->clone; } if(!ce->serialize) { ce->serialize = ce->parent->serialize; } if(!ce->unserialize) { ce->unserialize = ce->parent->unserialize; } if (!ce->destructor) { ce->destructor = ce->parent->destructor; } if (ce->constructor) { if (ce->parent->constructor && ce->parent->constructor->common.fn_flags & ZEND_ACC_FINAL) { zend_error(E_ERROR, "Cannot override final %s::%s() with %s::%s()", ce->parent->name, ce->parent->constructor->common.function_name, ce->name, ce->constructor->common.function_name ); } return; } if (zend_hash_find(&ce->parent->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), (void **)&function)==SUCCESS) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), function, sizeof(zend_function), NULL); function_add_ref(function); } else { /* Don't inherit the old style constructor if we already have the new style constructor */ char *lc_class_name; char *lc_parent_class_name; lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); if (!zend_hash_exists(&ce->function_table, lc_class_name, ce->name_length+1)) { lc_parent_class_name = zend_str_tolower_dup(ce->parent->name, ce->parent->name_length); if (!zend_hash_exists(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1) && zend_hash_find(&ce->parent->function_table, lc_parent_class_name, ce->parent->name_length+1, (void **)&function)==SUCCESS) { if (function->common.fn_flags & ZEND_ACC_CTOR) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1, function, sizeof(zend_function), NULL); function_add_ref(function); } } efree(lc_parent_class_name); } efree(lc_class_name); } ce->constructor = ce->parent->constructor; } /* }}} */ char *zend_visibility_string(zend_uint fn_flags) /* {{{ */ { if (fn_flags & ZEND_ACC_PRIVATE) { return "private"; } if (fn_flags & ZEND_ACC_PROTECTED) { return "protected"; } if (fn_flags & ZEND_ACC_PUBLIC) { return "public"; } return ""; } /* }}} */ static void do_inherit_method(zend_function *function) /* {{{ */ { /* The class entry of the derived function intentionally remains the same * as that of the parent class. That allows us to know in which context * we're running, and handle private method calls properly. */ function_add_ref(function); } /* }}} */ static zend_bool zend_do_perform_implementation_check(const zend_function *fe, const zend_function *proto TSRMLS_DC) /* {{{ */ { zend_uint i; /* If it's a user function then arg_info == NULL means we don't have any parameters but * we still need to do the arg number checks. We are only willing to ignore this for internal * functions because extensions don't always define arg_info. */ if (!proto || (!proto->common.arg_info && proto->common.type != ZEND_USER_FUNCTION)) { return 1; } /* Checks for constructors only if they are declared in an interface, * or explicitly marked as abstract */ if ((fe->common.fn_flags & ZEND_ACC_CTOR) && ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)) { return 1; } /* check number of arguments */ if (proto->common.required_num_args < fe->common.required_num_args || proto->common.num_args > fe->common.num_args) { return 0; } if (fe->common.type != ZEND_USER_FUNCTION && (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) != 0 && (fe->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) == 0) { return 0; } /* by-ref constraints on return values are covariant */ if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) { return 0; } for (i=0; i < proto->common.num_args; i++) { if (ZEND_LOG_XOR(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)) { /* Only one has a type hint and the other one doesn't */ return 0; } if (fe->common.arg_info[i].class_name && strcasecmp(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)!=0) { const char *colon; if (fe->common.type != ZEND_USER_FUNCTION) { return 0; } else if (strchr(proto->common.arg_info[i].class_name, '\\') != NULL || (colon = zend_memrchr(fe->common.arg_info[i].class_name, '\\', fe->common.arg_info[i].class_name_len)) == NULL || strcasecmp(colon+1, proto->common.arg_info[i].class_name) != 0) { zend_class_entry **fe_ce, **proto_ce; int found, found2; found = zend_lookup_class(fe->common.arg_info[i].class_name, fe->common.arg_info[i].class_name_len, &fe_ce TSRMLS_CC); found2 = zend_lookup_class(proto->common.arg_info[i].class_name, proto->common.arg_info[i].class_name_len, &proto_ce TSRMLS_CC); /* Check for class alias */ if (found != SUCCESS || found2 != SUCCESS || (*fe_ce)->type == ZEND_INTERNAL_CLASS || (*proto_ce)->type == ZEND_INTERNAL_CLASS || *fe_ce != *proto_ce) { return 0; } } } if (fe->common.arg_info[i].type_hint != proto->common.arg_info[i].type_hint) { /* Incompatible type hint */ return 0; } /* by-ref constraints on arguments are invariant */ if (fe->common.arg_info[i].pass_by_reference != proto->common.arg_info[i].pass_by_reference) { return 0; } } if (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) { for (i=proto->common.num_args; i < fe->common.num_args; i++) { if (!fe->common.arg_info[i].pass_by_reference) { return 0; } } } return 1; } /* }}} */ #define REALLOC_BUF_IF_EXCEED(buf, offset, length, size) \ if (UNEXPECTED(offset - buf + size >= length)) { \ length += size + 1; \ buf = erealloc(buf, length); \ } static char * zend_get_function_declaration(zend_function *fptr TSRMLS_DC) /* {{{ */ { char *offset, *buf; zend_uint length = 1024; offset = buf = (char *)emalloc(length * sizeof(char)); if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { *(offset++) = '&'; *(offset++) = ' '; } if (fptr->common.scope) { memcpy(offset, fptr->common.scope->name, fptr->common.scope->name_length); offset += fptr->common.scope->name_length; *(offset++) = ':'; *(offset++) = ':'; } { size_t name_len = strlen(fptr->common.function_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, name_len); memcpy(offset, fptr->common.function_name, name_len); offset += name_len; } *(offset++) = '('; if (fptr->common.arg_info) { zend_uint i, required; zend_arg_info *arg_info = fptr->common.arg_info; required = fptr->common.required_num_args; for (i = 0; i < fptr->common.num_args;) { if (arg_info->class_name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->class_name_len); memcpy(offset, arg_info->class_name, arg_info->class_name_len); offset += arg_info->class_name_len; *(offset++) = ' '; } else if (arg_info->type_hint) { zend_uint type_name_len; char *type_name = zend_get_type_by_const(arg_info->type_hint); type_name_len = strlen(type_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, type_name_len); memcpy(offset, type_name, type_name_len); offset += type_name_len; *(offset++) = ' '; } if (arg_info->pass_by_reference) { *(offset++) = '&'; } *(offset++) = '$'; if (arg_info->name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->name_len); memcpy(offset, arg_info->name, arg_info->name_len); offset += arg_info->name_len; } else { zend_uint idx = i; memcpy(offset, "param", 5); offset += 5; do { *(offset++) = (char) (idx % 10) + '0'; idx /= 10; } while (idx > 0); } if (i >= required) { *(offset++) = ' '; *(offset++) = '='; *(offset++) = ' '; if (fptr->type == ZEND_USER_FUNCTION) { zend_op *precv = NULL; { zend_uint idx = i; zend_op *op = ((zend_op_array *)fptr)->opcodes; zend_op *end = op + ((zend_op_array *)fptr)->last; ++idx; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT) && op->op1.num == (long)idx) { precv = op; } ++op; } } if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) { zval *zv, zv_copy; int use_copy; ALLOC_ZVAL(zv); *zv = *precv->op2.zv; zval_copy_ctor(zv); INIT_PZVAL(zv); zval_update_constant_ex(&zv, (void*)1, fptr->common.scope TSRMLS_CC); if (Z_TYPE_P(zv) == IS_BOOL) { if (Z_LVAL_P(zv)) { memcpy(offset, "true", 4); offset += 4; } else { memcpy(offset, "false", 5); offset += 5; } } else if (Z_TYPE_P(zv) == IS_NULL) { memcpy(offset, "NULL", 4); offset += 4; } else if (Z_TYPE_P(zv) == IS_STRING) { *(offset++) = '\''; REALLOC_BUF_IF_EXCEED(buf, offset, length, MIN(Z_STRLEN_P(zv), 10)); memcpy(offset, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 10)); offset += MIN(Z_STRLEN_P(zv), 10); if (Z_STRLEN_P(zv) > 10) { *(offset++) = '.'; *(offset++) = '.'; *(offset++) = '.'; } *(offset++) = '\''; } else if (Z_TYPE_P(zv) == IS_ARRAY) { memcpy(offset, "Array", 5); offset += 5; } else { zend_make_printable_zval(zv, &zv_copy, &use_copy); REALLOC_BUF_IF_EXCEED(buf, offset, length, Z_STRLEN(zv_copy)); memcpy(offset, Z_STRVAL(zv_copy), Z_STRLEN(zv_copy)); offset += Z_STRLEN(zv_copy); if (use_copy) { zval_dtor(&zv_copy); } } zval_ptr_dtor(&zv); } } else { memcpy(offset, "NULL", 4); offset += 4; } } if (++i < fptr->common.num_args) { *(offset++) = ','; *(offset++) = ' '; } arg_info++; REALLOC_BUF_IF_EXCEED(buf, offset, length, 32); } } *(offset++) = ')'; *offset = '\0'; return buf; } /* }}} */ static void do_inheritance_check_on_method(zend_function *child, zend_function *parent TSRMLS_DC) /* {{{ */ { zend_uint child_flags; zend_uint parent_flags = parent->common.fn_flags; if (parent->common.fn_flags & ZEND_ACC_ABSTRACT && parent->common.scope != (child->common.prototype ? child->common.prototype->common.scope : child->common.scope) && child->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_IMPLEMENTED_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Can't inherit abstract function %s::%s() (previously declared abstract in %s)", parent->common.scope->name, child->common.function_name, child->common.prototype ? child->common.prototype->common.scope->name : child->common.scope->name); } if (parent_flags & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot override final method %s::%s()", ZEND_FN_SCOPE_NAME(parent), child->common.function_name); } child_flags = child->common.fn_flags; /* You cannot change from static to non static and vice versa. */ if ((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC)) { if (child->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot make non static method %s::%s() static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } else { zend_error(E_COMPILE_ERROR, "Cannot make static method %s::%s() non static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } } /* Disallow making an inherited method abstract. */ if ((child_flags & ZEND_ACC_ABSTRACT) && !(parent_flags & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Cannot make non abstract method %s::%s() abstract in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } if (parent_flags & ZEND_ACC_CHANGED) { child->common.fn_flags |= ZEND_ACC_CHANGED; } else { /* Prevent derived classes from restricting access that was available in parent classes */ if ((child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::%s() must be %s (as in class %s)%s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if (((child_flags & ZEND_ACC_PPP_MASK) < (parent_flags & ZEND_ACC_PPP_MASK)) && ((parent_flags & ZEND_ACC_PPP_MASK) & ZEND_ACC_PRIVATE)) { child->common.fn_flags |= ZEND_ACC_CHANGED; } } if (parent_flags & ZEND_ACC_PRIVATE) { child->common.prototype = NULL; } else if (parent_flags & ZEND_ACC_ABSTRACT) { child->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; child->common.prototype = parent; } else if (!(parent->common.fn_flags & ZEND_ACC_CTOR) || (parent->common.prototype && (parent->common.prototype->common.scope->ce_flags & ZEND_ACC_INTERFACE))) { /* ctors only have a prototype if it comes from an interface */ child->common.prototype = parent->common.prototype ? parent->common.prototype : parent; } if (child->common.prototype && (child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { if (!zend_do_perform_implementation_check(child, child->common.prototype TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s::%s() must be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_get_function_declaration(child->common.prototype TSRMLS_CC)); } } else if (EG(error_reporting) & E_STRICT || EG(user_error_handler)) { /* Check E_STRICT (or custom error handler) before the check so that we save some time */ if (!zend_do_perform_implementation_check(child, parent TSRMLS_CC)) { char *method_prototype = zend_get_function_declaration(child->common.prototype TSRMLS_CC); zend_error(E_STRICT, "Declaration of %s::%s() should be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, method_prototype); efree(method_prototype); } } } /* }}} */ static zend_bool do_inherit_method_check(HashTable *child_function_table, zend_function *parent, const zend_hash_key *hash_key, zend_class_entry *child_ce) /* {{{ */ { zend_uint parent_flags = parent->common.fn_flags; zend_function *child; TSRMLS_FETCH(); if (zend_hash_quick_find(child_function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child)==FAILURE) { if (parent_flags & (ZEND_ACC_ABSTRACT)) { child_ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } return 1; /* method doesn't exist in child, copy from parent */ } do_inheritance_check_on_method(child, parent TSRMLS_CC); return 0; } /* }}} */ static zend_bool do_inherit_property_access_check(HashTable *target_ht, zend_property_info *parent_info, const zend_hash_key *hash_key, zend_class_entry *ce) /* {{{ */ { zend_property_info *child_info; zend_class_entry *parent_ce = ce->parent; if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW)) { if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { child_info->flags |= ZEND_ACC_CHANGED; } else { zend_hash_quick_update(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, parent_info, sizeof(zend_property_info), (void **) &child_info); if(ce->type & ZEND_INTERNAL_CLASS) { zend_duplicate_property_info_internal(child_info); } else { zend_duplicate_property_info(child_info); } child_info->flags &= ~ZEND_ACC_PRIVATE; /* it's not private anymore */ child_info->flags |= ZEND_ACC_SHADOW; /* but it's a shadow of private */ } return 0; /* don't copy access information to child */ } if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { if ((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s", (parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", parent_ce->name, hash_key->arKey, (child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ce->name, hash_key->arKey); } if(parent_info->flags & ZEND_ACC_CHANGED) { child_info->flags |= ZEND_ACC_CHANGED; } if ((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ce->name, hash_key->arKey, zend_visibility_string(parent_info->flags), parent_ce->name, (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if ((child_info->flags & ZEND_ACC_STATIC) == 0) { Z_DELREF_P(ce->default_properties_table[parent_info->offset]); ce->default_properties_table[parent_info->offset] = ce->default_properties_table[child_info->offset]; ce->default_properties_table[child_info->offset] = NULL; child_info->offset = parent_info->offset; } return 0; /* Don't copy from parent */ } else { return 1; /* Copy from parent */ } } /* }}} */ static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce TSRMLS_CC) == FAILURE) { zend_error(E_CORE_ERROR, "Class %s could not implement interface %s", ce->name, iface->name); } if (ce == iface) { zend_error(E_ERROR, "Interface %s cannot implement itself", ce->name); } } /* }}} */ ZEND_API void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface TSRMLS_DC) /* {{{ */ { /* expects interface to be contained in ce's interface list already */ zend_uint i, ce_num, if_num = iface->num_interfaces; zend_class_entry *entry; if (if_num==0) { return; } ce_num = ce->num_interfaces; if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } /* Inherit the interfaces, only if they're not already inherited by the class */ while (if_num--) { entry = iface->interfaces[if_num]; for (i = 0; i < ce_num; i++) { if (ce->interfaces[i] == entry) { break; } } if (i == ce_num) { ce->interfaces[ce->num_interfaces++] = entry; } } /* and now call the implementing handlers */ while (ce_num < ce->num_interfaces) { do_implement_interface(ce, ce->interfaces[ce_num++] TSRMLS_CC); } } /* }}} */ #ifdef ZTS static void zval_internal_ctor(zval **p) /* {{{ */ { zval *orig_ptr = *p; ALLOC_ZVAL(*p); MAKE_COPY_ZVAL(&orig_ptr, *p); } /* }}} */ # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) (((parent_ce)->type != (ce)->type) ? zval_internal_ctor : zval_add_ref)) #else # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) zval_add_ref) #endif ZEND_API void zend_do_inheritance(zend_class_entry *ce, zend_class_entry *parent_ce TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; if ((ce->ce_flags & ZEND_ACC_INTERFACE) && !(parent_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ce->name, parent_ce->name); } if (parent_ce->ce_flags & ZEND_ACC_FINAL_CLASS) { zend_error(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ce->name, parent_ce->name); } ce->parent = parent_ce; /* Copy serialize/unserialize callbacks */ if (!ce->serialize) { ce->serialize = parent_ce->serialize; } if (!ce->unserialize) { ce->unserialize = parent_ce->unserialize; } /* Inherit interfaces */ zend_do_inherit_interfaces(ce, parent_ce TSRMLS_CC); /* Inherit properties */ if (parent_ce->default_properties_count) { int i = ce->default_properties_count + parent_ce->default_properties_count; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_properties_count) { while (i-- > parent_ce->default_properties_count) { ce->default_properties_table[i] = ce->default_properties_table[i - parent_ce->default_properties_count]; } } for (i = 0; i < parent_ce->default_properties_count; i++) { ce->default_properties_table[i] = parent_ce->default_properties_table[i]; if (ce->default_properties_table[i]) { #ifdef ZTS if (parent_ce->type != ce->type) { zval *p; ALLOC_ZVAL(p); MAKE_COPY_ZVAL(&ce->default_properties_table[i], p); ce->default_properties_table[i] = p; } else { Z_ADDREF_P(ce->default_properties_table[i]); } #else Z_ADDREF_P(ce->default_properties_table[i]); #endif } } ce->default_properties_count += parent_ce->default_properties_count; } if (parent_ce->type != ce->type) { /* User class extends internal class */ zend_update_class_constants(parent_ce TSRMLS_CC); if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = erealloc(ce->default_static_members_table, sizeof(void*) * i); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&CE_STATIC_MEMBERS(parent_ce)[i]); ce->default_static_members_table[i] = CE_STATIC_MEMBERS(parent_ce)[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; ce->static_members_table = ce->default_static_members_table; } } else { if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&parent_ce->default_static_members_table[i]); ce->default_static_members_table[i] = parent_ce->default_static_members_table[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } } for (zend_hash_internal_pointer_reset(&ce->properties_info); zend_hash_get_current_data(&ce->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->properties_info)) { if (property_info->ce == ce) { if (property_info->flags & ZEND_ACC_STATIC) { property_info->offset += parent_ce->default_static_members_count; } else { property_info->offset += parent_ce->default_properties_count; } } } zend_hash_merge_ex(&ce->properties_info, &parent_ce->properties_info, (copy_ctor_func_t) (ce->type & ZEND_INTERNAL_CLASS ? zend_duplicate_property_info_internal : zend_duplicate_property_info), sizeof(zend_property_info), (merge_checker_func_t) do_inherit_property_access_check, ce); zend_hash_merge(&ce->constants_table, &parent_ce->constants_table, zval_property_ctor(parent_ce, ce), NULL, sizeof(zval *), 0); zend_hash_merge_ex(&ce->function_table, &parent_ce->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_inherit_parent_constructor(ce); if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS && ce->type == ZEND_INTERNAL_CLASS) { ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } else if (!(ce->ce_flags & ZEND_ACC_IMPLEMENT_INTERFACES) && !(ce->ce_flags & ZEND_ACC_IMPLEMENT_TRAITS)) { /* The verification will be done in runtime by ZEND_VERIFY_ABSTRACT_CLASS */ zend_verify_abstract_class(ce TSRMLS_CC); } ce->ce_flags |= parent_ce->ce_flags & ZEND_HAS_STATIC_IN_METHODS; } /* }}} */ static zend_bool do_inherit_constant_check(HashTable *child_constants_table, const zval **parent_constant, const zend_hash_key *hash_key, const zend_class_entry *iface) /* {{{ */ { zval **old_constant; if (zend_hash_quick_find(child_constants_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**)&old_constant) == SUCCESS) { if (*old_constant != *parent_constant) { zend_error(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", hash_key->arKey, iface->name); } return 0; } return 1; } /* }}} */ static int do_interface_constant_check(zval **val TSRMLS_DC, int num_args, va_list args, const zend_hash_key *key) /* {{{ */ { zend_class_entry **iface = va_arg(args, zend_class_entry**); do_inherit_constant_check(&(*iface)->constants_table, (const zval **) val, key, *iface); return ZEND_HASH_APPLY_KEEP; } /* }}} */ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_iface_num = ce->num_interfaces; zend_uint parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0; for (i = 0; i < ce->num_interfaces; i++) { if (ce->interfaces[i] == NULL) { memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i)); i--; } else if (ce->interfaces[i] == iface) { if (i < parent_iface_num) { ignore = 1; } else { zend_error(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ce->name, iface->name); } } } if (ignore) { /* Check for attempt to redeclare interface constants */ zend_hash_apply_with_arguments(&ce->constants_table TSRMLS_CC, (apply_func_args_t) do_interface_constant_check, 1, &iface); } else { if (ce->num_interfaces >= current_iface_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } } ce->interfaces[ce->num_interfaces++] = iface; zend_hash_merge_ex(&ce->constants_table, &iface->constants_table, (copy_ctor_func_t) zval_add_ref, sizeof(zval *), (merge_checker_func_t) do_inherit_constant_check, iface); zend_hash_merge_ex(&ce->function_table, &iface->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_implement_interface(ce, iface TSRMLS_CC); zend_do_inherit_interfaces(ce, iface TSRMLS_CC); } } /* }}} */ ZEND_API void zend_do_implement_trait(zend_class_entry *ce, zend_class_entry *trait TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_trait_num = ce->num_traits; zend_uint parent_trait_num = ce->parent ? ce->parent->num_traits : 0; for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == NULL) { memmove(ce->traits + i, ce->traits + i + 1, sizeof(zend_class_entry*) * (--ce->num_traits - i)); i--; } else if (ce->traits[i] == trait) { if (i < parent_trait_num) { ignore = 1; } } } if (!ignore) { if (ce->num_traits >= current_trait_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->traits = (zend_class_entry **) realloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } else { ce->traits = (zend_class_entry **) erealloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } } ce->traits[ce->num_traits++] = trait; } } /* }}} */ static int zend_traits_merge_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { size_t current; size_t i; size_t count; HashTable* resulting_table; HashTable** function_tables; zend_class_entry *ce; size_t collision = 0; size_t abstract_solved = 0; zend_function* other_trait_fn; current = va_arg(args, size_t); /* index of current trait */ count = va_arg(args, size_t); resulting_table = va_arg(args, HashTable*); function_tables = va_arg(args, HashTable**); ce = va_arg(args, zend_class_entry*); for (i = 0; i < count; i++) { if (i == current) { continue; /* just skip this, cause its the table this function is applied on */ } if (zend_hash_quick_find(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&other_trait_fn) == SUCCESS) { /* if it is an abstract method, there is no collision */ if (other_trait_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* we can savely free and remove it from other table */ zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } else { /* if it is not an abstract method, there is still no collision */ /* if fn is an abstract method */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* just mark as solved, will be added if its own trait is processed */ abstract_solved = 1; } else { /* but else, we have a collision of non-abstract methods */ collision++; zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } } } if (collision) { zend_function* class_fn; /* make sure method is not already overridden in class */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&class_fn) == FAILURE || class_fn->common.scope != ce) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because there are collisions with other trait methods on %s", fn->common.function_name, ce->name); } zend_function_dtor(fn); } else if (abstract_solved) { zend_function_dtor(fn); } else { /* Add it to result function table */ if (zend_hash_quick_add(resulting_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, fn, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating resulting trait method table", fn->common.function_name); } } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ /* {{{ Originates from php_runkit_function_copy_ctor Duplicate structures in an op_array where necessary to make an outright duplicate */ static void zend_traits_duplicate_function(zend_function *fe, zend_class_entry *target_ce, char *newname TSRMLS_DC) { zend_literal *literals_copy; zend_compiled_variable *dupvars; zend_op *opcode_copy; zval class_name_zv; int class_name_literal; int i; int number_of_literals; if (fe->op_array.static_variables) { HashTable *tmpHash; ALLOC_HASHTABLE(tmpHash); zend_hash_init(tmpHash, zend_hash_num_elements(fe->op_array.static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_apply_with_arguments(fe->op_array.static_variables TSRMLS_CC, (apply_func_args_t)zval_copy_static_var, 1, tmpHash); fe->op_array.static_variables = tmpHash; } number_of_literals = fe->op_array.last_literal; literals_copy = (zend_literal*)emalloc(number_of_literals * sizeof(zend_literal)); for (i = 0; i < number_of_literals; i++) { literals_copy[i] = fe->op_array.literals[i]; zval_copy_ctor(&literals_copy[i].constant); } fe->op_array.literals = literals_copy; fe->op_array.refcount = emalloc(sizeof(zend_uint)); *(fe->op_array.refcount) = 1; if (fe->op_array.vars) { i = fe->op_array.last_var; dupvars = safe_emalloc(fe->op_array.last_var, sizeof(zend_compiled_variable), 0); while (i > 0) { i--; dupvars[i].name = estrndup(fe->op_array.vars[i].name, fe->op_array.vars[i].name_len); dupvars[i].name_len = fe->op_array.vars[i].name_len; dupvars[i].hash_value = fe->op_array.vars[i].hash_value; } fe->op_array.vars = dupvars; } else { fe->op_array.vars = NULL; } opcode_copy = safe_emalloc(sizeof(zend_op), fe->op_array.last, 0); for(i = 0; i < fe->op_array.last; i++) { opcode_copy[i] = fe->op_array.opcodes[i]; if (opcode_copy[i].op1_type != IS_CONST) { if (opcode_copy[i].op1.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op1.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op1.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op1.jmp_addr - fe->op_array.opcodes); } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op1.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op1.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op1.zv = &fe->op_array.literals[class_name_literal].constant; } } if (opcode_copy[i].op2_type != IS_CONST) { if (opcode_copy[i].op2.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op2.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op2.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op2.jmp_addr - fe->op_array.opcodes); } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op2.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op2.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op2.zv = &fe->op_array.literals[class_name_literal].constant; } } } fe->op_array.opcodes = opcode_copy; fe->op_array.function_name = newname; /* was setting it to fe which does not work since fe is stack allocated and not a stable address */ /* fe->op_array.prototype = fe->op_array.prototype; */ if (fe->op_array.arg_info) { zend_arg_info *tmpArginfo; tmpArginfo = safe_emalloc(sizeof(zend_arg_info), fe->op_array.num_args, 0); for(i = 0; i < fe->op_array.num_args; i++) { tmpArginfo[i] = fe->op_array.arg_info[i]; tmpArginfo[i].name = estrndup(tmpArginfo[i].name, tmpArginfo[i].name_len); if (tmpArginfo[i].class_name) { tmpArginfo[i].class_name = estrndup(tmpArginfo[i].class_name, tmpArginfo[i].class_name_len); } } fe->op_array.arg_info = tmpArginfo; } fe->op_array.doc_comment = estrndup(fe->op_array.doc_comment, fe->op_array.doc_comment_len); fe->op_array.try_catch_array = (zend_try_catch_element*)estrndup((char*)fe->op_array.try_catch_array, sizeof(zend_try_catch_element) * fe->op_array.last_try_catch); fe->op_array.brk_cont_array = (zend_brk_cont_element*)estrndup((char*)fe->op_array.brk_cont_array, sizeof(zend_brk_cont_element) * fe->op_array.last_brk_cont); } /* }}} */ static void zend_add_magic_methods(zend_class_entry* ce, const char* mname, uint mname_len, zend_function* fe TSRMLS_DC) { if ( !strncmp(mname, ZEND_CLONE_FUNC_NAME, mname_len)) { ce->clone = fe; fe->common.fn_flags |= ZEND_ACC_CLONE; } else if (!strncmp(mname, ZEND_CONSTRUCTOR_FUNC_NAME, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } else if (!strncmp(mname, ZEND_DESTRUCTOR_FUNC_NAME, mname_len)) { ce->destructor = fe; fe->common.fn_flags |= ZEND_ACC_DTOR; } else if (!strncmp(mname, ZEND_GET_FUNC_NAME, mname_len)) ce->__get = fe; else if (!strncmp(mname, ZEND_SET_FUNC_NAME, mname_len)) ce->__set = fe; else if (!strncmp(mname, ZEND_CALL_FUNC_NAME, mname_len)) ce->__call = fe; else if (!strncmp(mname, ZEND_UNSET_FUNC_NAME, mname_len)) ce->__unset = fe; else if (!strncmp(mname, ZEND_ISSET_FUNC_NAME, mname_len)) ce->__isset = fe; else if (!strncmp(mname, ZEND_CALLSTATIC_FUNC_NAME, mname_len)) ce->__callstatic= fe; else if (!strncmp(mname, ZEND_TOSTRING_FUNC_NAME, mname_len)) ce->__tostring = fe; else if (ce->name_length + 1 == mname_len) { char *lowercase_name = emalloc(ce->name_length + 1); zend_str_tolower_copy(lowercase_name, ce->name, ce->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, ce->name_length + 1, 1 TSRMLS_CC); if (!memcmp(mname, lowercase_name, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } str_efree(lowercase_name); } } static int zend_traits_merge_functions_to_class(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zend_class_entry *ce = va_arg(args, zend_class_entry*); int add = 0; zend_function* existing_fn; zend_function fn_copy, *fn_copy_p; zend_function* prototype = NULL; /* is used to determine the prototype according to the inheritance chain */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &existing_fn) == FAILURE) { add = 1; /* not found */ } else if (existing_fn->common.scope != ce) { add = 1; /* or inherited from other class or interface */ /* it is just a reference which was added to the subclass while doing the inheritance */ /* so we can deleted now, and will add the overriding method afterwards */ /* except, if we try to add an abstract function, then we should not delete the inherited one */ /* delete inherited fn if the function to be added is not abstract */ if ((fn->common.fn_flags & ZEND_ACC_ABSTRACT) == 0) { zend_hash_quick_del(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } if (add) { zend_function* parent_function; if (ce->parent && zend_hash_quick_find(&ce->parent->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &parent_function) != FAILURE) { prototype = parent_function; /* ->common.fn_flags |= ZEND_ACC_ABSTRACT; */ /* we got that method in the parent class, and are going to override it, except, if the trait is just asking to have an abstract method implemented. */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* then we clean up an skip this method */ zend_function_dtor(fn); return ZEND_HASH_APPLY_REMOVE; } } fn->common.scope = ce; fn->common.prototype = prototype; if (prototype && (prototype->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT || prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { fn->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; } else if (fn->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT) { /* remove ZEND_ACC_IMPLEMENTED_ABSTRACT flag, think it shouldn't be copied to class */ fn->common.fn_flags = fn->common.fn_flags - ZEND_ACC_IMPLEMENTED_ABSTRACT; } /* check whether the trait method fullfills the inheritance requirements */ if (prototype) { do_inheritance_check_on_method(fn, prototype TSRMLS_CC); } if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (fn->op_array.static_variables) { ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, ce, estrdup(fn->common.function_name) TSRMLS_CC); if (zend_hash_quick_update(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, &fn_copy, sizeof(zend_function), (void**)&fn_copy_p)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating class method table", hash_key->arKey); } zend_add_magic_methods(ce, hash_key->arKey, hash_key->nKeyLength, fn_copy_p TSRMLS_CC); zend_function_dtor(fn); } else { zend_function_dtor(fn); } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ static int zend_traits_copy_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { HashTable* target; zend_class_entry *target_ce; zend_trait_alias** aliases; HashTable* exclude_table; char* lcname; unsigned int fnname_len; zend_function fn_copy; void* dummy; size_t i = 0; target = va_arg(args, HashTable*); target_ce = va_arg(args, zend_class_entry*); aliases = va_arg(args, zend_trait_alias**); exclude_table = va_arg(args, HashTable*); fnname_len = strlen(fn->common.function_name); /* apply aliases which are qualified with a class name, there should not be any ambiguity */ if (aliases) { while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias != NULL && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && aliases[i]->trait_method->mname_len == fnname_len && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(aliases[i]->alias, aliases[i]->alias_len) TSRMLS_CC); /* if it is 0, no modifieres has been changed */ if (aliases[i]->modifiers) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } lcname = zend_str_tolower_dup(aliases[i]->alias, aliases[i]->alias_len); if (zend_hash_add(target, lcname, aliases[i]->alias_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add aliased trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } efree(lcname); } i++; } } lcname = zend_str_tolower_dup(fn->common.function_name, fnname_len); if (exclude_table == NULL || zend_hash_find(exclude_table, lcname, fnname_len, &dummy) == FAILURE) { /* is not in hashtable, thus, function is not to be excluded */ fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(fn->common.function_name, fnname_len) TSRMLS_CC); /* apply aliases which are not qualified by a class name, or which have not * alias name, just setting visibility */ if (aliases) { i = 0; while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias == NULL && aliases[i]->modifiers != 0 && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && (aliases[i]->trait_method->mname_len == fnname_len) && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } i++; } } if (zend_hash_add(target, lcname, fnname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } } efree(lcname); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* Copies function table entries to target function table with applied aliasing */ static void zend_traits_copy_trait_function_table(HashTable *target, zend_class_entry *target_ce, HashTable *source, zend_trait_alias** aliases, HashTable* exclude_table TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_arguments(source TSRMLS_CC, (apply_func_args_t)zend_traits_copy_functions, 4, target, target_ce, aliases, exclude_table); } /* }}} */ static void zend_traits_init_trait_structures(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i, j = 0; zend_trait_precedence *cur_precedence; zend_trait_method_reference *cur_method_ref; /* resolve class references */ if (ce->trait_precedences) { i = 0; while ((cur_precedence = ce->trait_precedences[i])) { if (cur_precedence->exclude_from_classes) { cur_precedence->trait_method->ce = zend_fetch_class(cur_precedence->trait_method->class_name, cur_precedence->trait_method->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); j = 0; while (cur_precedence->exclude_from_classes[j]) { char* class_name = (char*)cur_precedence->exclude_from_classes[j]; zend_uint name_length = strlen(class_name); cur_precedence->exclude_from_classes[j] = zend_fetch_class(class_name, name_length, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); efree(class_name); j++; } } i++; } } if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { if (ce->trait_aliases[i]->trait_method->class_name) { cur_method_ref = ce->trait_aliases[i]->trait_method; cur_method_ref->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); } i++; } } } /* }}} */ static void zend_traits_compile_exclude_table(HashTable* exclude_table, zend_trait_precedence **precedences, zend_class_entry *trait) /* {{{ */ { size_t i = 0, j; if (!precedences) { return; } while (precedences[i]) { if (precedences[i]->exclude_from_classes) { j = 0; while (precedences[i]->exclude_from_classes[j]) { if (precedences[i]->exclude_from_classes[j] == trait) { zend_uint lcname_len = precedences[i]->trait_method->mname_len; char *lcname = zend_str_tolower_dup(precedences[i]->trait_method->method_name, lcname_len); if (zend_hash_add(exclude_table, lcname, lcname_len, NULL, 0, NULL) == FAILURE) { efree(lcname); zend_error(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", precedences[i]->trait_method->method_name, trait->name); } efree(lcname); } ++j; } } ++i; } } /* }}} */ static void zend_do_traits_method_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { HashTable** function_tables; HashTable* resulting_table; HashTable exclude_table; size_t i; /* prepare copies of trait function tables for combination */ function_tables = malloc(sizeof(HashTable*) * ce->num_traits); resulting_table = (HashTable *) malloc(sizeof(HashTable)); /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(resulting_table, 10, NULL, NULL, 1, 0); for (i = 0; i < ce->num_traits; i++) { function_tables[i] = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(function_tables[i], ce->traits[i]->function_table.nNumOfElements, NULL, NULL, 1, 0); if (ce->trait_precedences) { /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(&exclude_table, 2, NULL, NULL, 0, 0); zend_traits_compile_exclude_table(&exclude_table, ce->trait_precedences, ce->traits[i]); /* copies functions, applies defined aliasing, and excludes unused trait methods */ zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, &exclude_table TSRMLS_CC); zend_hash_graceful_destroy(&exclude_table); } else { zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, NULL TSRMLS_CC); } } /* now merge trait methods */ for (i = 0; i < ce->num_traits; i++) { zend_hash_apply_with_arguments(function_tables[i] TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions, 5, i, ce->num_traits, resulting_table, function_tables, ce); } /* Now the resulting_table contains all trait methods we would have to * add to the class in the following step the methods are inserted into the method table * if there is already a method with the same name it is replaced iff ce != fn.scope * --> all inherited methods are overridden, methods defined in the class are left untouched */ zend_hash_apply_with_arguments(resulting_table TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions_to_class, 1, ce); /* free temporary function tables */ for (i = 0; i < ce->num_traits; i++) { /* zend_hash_destroy(function_tables[i]); */ zend_hash_graceful_destroy(function_tables[i]); free(function_tables[i]); } free(function_tables); /* free temporary resulting table */ /* zend_hash_destroy(resulting_table); */ zend_hash_graceful_destroy(resulting_table); free(resulting_table); } /* }}} */ static zend_class_entry* find_first_definition(zend_class_entry *ce, size_t current_trait, const char* prop_name, int prop_name_length, ulong prop_hash, zend_class_entry *coliding_ce) /* {{{ */ { size_t i; zend_property_info *coliding_prop; for (i = 0; (i < current_trait) && (i < ce->num_traits); i++) { if (zend_hash_quick_find(&ce->traits[i]->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS) { return ce->traits[i]; } } return coliding_ce; } /* }}} */ static void zend_do_traits_property_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i; zend_property_info *property_info; zend_property_info *coliding_prop; zval compare_result; const char* prop_name; int prop_name_length; ulong prop_hash; const char* class_name_unused; zend_bool prop_found; zend_bool not_compatible; zval* prop_value; /* In the following steps the properties are inserted into the property table * for that, a very strict approach is applied: * - check for compatibility, if not compatible with any property in class -> fatal * - if compatible, then strict notice */ for (i = 0; i < ce->num_traits; i++) { for (zend_hash_internal_pointer_reset(&ce->traits[i]->properties_info); zend_hash_get_current_data(&ce->traits[i]->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->traits[i]->properties_info)) { /* first get the unmangeld name if necessary, * then check whether the property is already there */ if ((property_info->flags & ZEND_ACC_PPP_MASK) == ZEND_ACC_PUBLIC) { prop_hash = property_info->h; prop_name = property_info->name; prop_name_length = property_info->name_length; prop_found = zend_hash_quick_find(&ce->properties_info, property_info->name, property_info->name_length+1, property_info->h, (void **) &coliding_prop) == SUCCESS; } else { /* for private and protected we need to unmangle the names */ zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name_unused, &prop_name); prop_name_length = strlen(prop_name); prop_hash = zend_get_hash_value(prop_name, prop_name_length + 1); prop_found = zend_hash_quick_find(&ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS; } /* next: check for conflicts with current class */ if (prop_found) { if (coliding_prop->flags & ZEND_ACC_SHADOW) { /* this one is inherited, lets look it up in its own class */ zend_hash_quick_find(&coliding_prop->ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop); } if ((coliding_prop->flags & ZEND_ACC_PPP_MASK) == (property_info->flags & ZEND_ACC_PPP_MASK)) { /* flags are identical, now the value needs to be checked */ if (property_info->flags & ZEND_ACC_STATIC) { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_static_members_table[coliding_prop->offset], ce->traits[i]->default_static_members_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } else { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_properties_table[coliding_prop->offset], ce->traits[i]->default_properties_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } } else { /* the flags are not identical, thus, we assume properties are not compatible */ not_compatible = 1; } if (not_compatible) { zend_error(E_COMPILE_ERROR, "%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } else { zend_error(E_STRICT, "%s and %s define the same property ($%s) in the composition of %s. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } } /* property not found, so lets add it */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); zend_declare_property_ex(ce, prop_name, prop_name_length, prop_value, property_info->flags, property_info->doc_comment, property_info->doc_comment_len TSRMLS_CC); } } } /* }}} */ ZEND_API void zend_do_bind_traits(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { if (ce->num_traits <= 0) { return; } /* complete initialization of trait strutures in ce */ zend_traits_init_trait_structures(ce TSRMLS_CC); /* first care about all methods to be flattened into the class */ zend_do_traits_method_binding(ce TSRMLS_CC); /* then flatten the properties into it, to, mostly to notfiy developer about problems */ zend_do_traits_property_binding(ce TSRMLS_CC); /* verify that all abstract methods from traits have been implemented */ zend_verify_abstract_class(ce TSRMLS_CC); /* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */ if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { ce->ce_flags -= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } } /* }}} */ ZEND_API int do_bind_function(const zend_op_array *op_array, zend_op *opline, HashTable *function_table, zend_bool compile_time) /* {{{ */ { zend_function *function; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } zend_hash_quick_find(function_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void *) &function); if (zend_hash_quick_add(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), function, sizeof(zend_function), NULL)==FAILURE) { int error_level = compile_time ? E_COMPILE_ERROR : E_ERROR; zend_function *old_function; if (zend_hash_quick_find(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), (void *) &old_function)==SUCCESS && old_function->type == ZEND_USER_FUNCTION && old_function->op_array.last > 0) { zend_error(error_level, "Cannot redeclare %s() (previously declared in %s:%d)", function->common.function_name, old_function->op_array.filename, old_function->op_array.opcodes[0].lineno); } else { zend_error(error_level, "Cannot redeclare %s()", function->common.function_name); } return FAILURE; } else { (*function->op_array.refcount)++; function->op_array.static_variables = NULL; /* NULL out the unbound function */ return SUCCESS; } } /* }}} */ void zend_add_trait_precedence(znode *precedence_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_precedences, precedence_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_add_trait_alias(znode *alias_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_aliases, alias_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_prepare_reference(znode *result, znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { zend_trait_method_reference *method_ref = emalloc(sizeof(zend_trait_method_reference)); method_ref->ce = NULL; /* REM: There should not be a need for copying, zend_do_begin_class_declaration is also just using that string */ if (class_name) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); method_ref->class_name = Z_STRVAL(class_name->u.constant); method_ref->cname_len = Z_STRLEN(class_name->u.constant); } else { method_ref->class_name = NULL; method_ref->cname_len = 0; } method_ref->method_name = Z_STRVAL(method_name->u.constant); method_ref->mname_len = Z_STRLEN(method_name->u.constant); result->u.op.ptr = method_ref; result->op_type = IS_TMP_VAR; } /* }}} */ void zend_prepare_trait_alias(znode *result, znode *method_reference, znode *modifiers, znode *alias TSRMLS_DC) /* {{{ */ { zend_trait_alias *trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_alias->modifiers = Z_LVAL(modifiers->u.constant); if (Z_LVAL(modifiers->u.constant) == ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot use 'static' as method modifier"); return; } if (alias) { trait_alias->alias = Z_STRVAL(alias->u.constant); trait_alias->alias_len = Z_STRLEN(alias->u.constant); } else { trait_alias->alias = NULL; } trait_alias->function = NULL; result->u.op.ptr = trait_alias; } /* }}} */ void zend_prepare_trait_precedence(znode *result, znode *method_reference, znode *trait_list TSRMLS_DC) /* {{{ */ { zend_trait_precedence *trait_precedence = emalloc(sizeof(zend_trait_precedence)); trait_precedence->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_precedence->exclude_from_classes = (zend_class_entry**) trait_list->u.op.ptr; trait_precedence->function = NULL; result->u.op.ptr = trait_precedence; } /* }}} */ ZEND_API zend_class_entry *do_bind_class(const zend_op_array* op_array, const zend_op *opline, HashTable *class_table, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } if (zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce)==FAILURE) { zend_error(E_COMPILE_ERROR, "Internal Zend error - Missing class information for %s", Z_STRVAL_P(op1)); return NULL; } else { ce = *pce; } ce->refcount++; if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), &ce, sizeof(zend_class_entry *), NULL)==FAILURE) { ce->refcount--; if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return NULL; } else { if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLEMENT_INTERFACES))) { zend_verify_abstract_class(ce TSRMLS_CC); } return ce; } } /* }}} */ ZEND_API zend_class_entry *do_bind_inherited_class(const zend_op_array *op_array, const zend_op *opline, HashTable *class_table, zend_class_entry *parent_ce, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; int found_ce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } found_ce = zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce); if (found_ce == FAILURE) { if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", Z_STRVAL_P(op2)); } return NULL; } else { ce = *pce; } if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ce->name, parent_ce->name); } else if ((parent_ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ce->name, parent_ce->name); } zend_do_inheritance(ce, parent_ce TSRMLS_CC); ce->refcount++; /* Register the derived class */ if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), pce, sizeof(zend_class_entry *), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return ce; } /* }}} */ void zend_do_early_binding(TSRMLS_D) /* {{{ */ { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; HashTable *table; while (opline->opcode == ZEND_TICKS && opline > CG(active_op_array)->opcodes) { opline--; } switch (opline->opcode) { case ZEND_DECLARE_FUNCTION: if (do_bind_function(CG(active_op_array), opline, CG(function_table), 1) == FAILURE) { return; } table = CG(function_table); break; case ZEND_DECLARE_CLASS: if (do_bind_class(CG(active_op_array), opline, CG(class_table), 1 TSRMLS_CC) == NULL) { return; } table = CG(class_table); break; case ZEND_DECLARE_INHERITED_CLASS: { zend_op *fetch_class_opline = opline-1; zval *parent_name; zend_class_entry **pce; parent_name = &CONSTANT(fetch_class_opline->op2.constant); if ((zend_lookup_class(Z_STRVAL_P(parent_name), Z_STRLEN_P(parent_name), &pce TSRMLS_CC) == FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_CLASSES) && ((*pce)->type == ZEND_INTERNAL_CLASS))) { if (CG(compiler_options) & ZEND_COMPILE_DELAYED_BINDING) { zend_uint *opline_num = &CG(active_op_array)->early_binding; while (*opline_num != -1) { opline_num = &CG(active_op_array)->opcodes[*opline_num].result.opline_num; } *opline_num = opline - CG(active_op_array)->opcodes; opline->opcode = ZEND_DECLARE_INHERITED_CLASS_DELAYED; opline->result_type = IS_UNUSED; opline->result.opline_num = -1; } return; } if (do_bind_inherited_class(CG(active_op_array), opline, CG(class_table), *pce, 1 TSRMLS_CC) == NULL) { return; } /* clear unnecessary ZEND_FETCH_CLASS opcode */ zend_del_literal(CG(active_op_array), fetch_class_opline->op2.constant); MAKE_NOP(fetch_class_opline); table = CG(class_table); break; } case ZEND_VERIFY_ABSTRACT_CLASS: case ZEND_ADD_INTERFACE: case ZEND_ADD_TRAIT: case ZEND_BIND_TRAITS: /* We currently don't early-bind classes that implement interfaces */ /* Classes with traits are handled exactly the same, no early-bind here */ return; default: zend_error(E_COMPILE_ERROR, "Invalid binding type"); return; } zend_hash_quick_del(table, Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant)), Z_HASH_P(&CONSTANT(opline->op1.constant))); zend_del_literal(CG(active_op_array), opline->op1.constant); zend_del_literal(CG(active_op_array), opline->op2.constant); MAKE_NOP(opline); } /* }}} */ ZEND_API void zend_do_delayed_early_binding(const zend_op_array *op_array TSRMLS_DC) /* {{{ */ { if (op_array->early_binding != -1) { zend_bool orig_in_compilation = CG(in_compilation); zend_uint opline_num = op_array->early_binding; zend_class_entry **pce; CG(in_compilation) = 1; while (opline_num != -1) { if (zend_lookup_class(Z_STRVAL_P(op_array->opcodes[opline_num-1].op2.zv), Z_STRLEN_P(op_array->opcodes[opline_num-1].op2.zv), &pce TSRMLS_CC) == SUCCESS) { do_bind_inherited_class(op_array, &op_array->opcodes[opline_num], EG(class_table), *pce, 0 TSRMLS_CC); } opline_num = op_array->opcodes[opline_num].result.opline_num; } CG(in_compilation) = orig_in_compilation; } } /* }}} */ void zend_do_boolean_or_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_or_end(znode *result, const znode *expr1, const znode *expr2, znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_boolean_and_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_and_end(znode *result, const znode *expr1, const znode *expr2, const znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_do_while_begin(TSRMLS_D) /* {{{ */ { do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_do_while_end(const znode *do_token, const znode *expr_open_bracket, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ; SET_NODE(opline->op1, expr); opline->op2.opline_num = do_token->u.op.opline_num; SET_UNUSED(opline->op2); do_end_loop(expr_open_bracket->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_brk_cont(zend_uchar op, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->op1.opline_num = CG(context).current_brk_cont; SET_UNUSED(opline->op1); if (expr) { if (expr->op_type != IS_CONST) { zend_error(E_COMPILE_ERROR, "'%s' operator with non-constant operand is no longer supported", op == ZEND_BRK ? "break" : "continue"); } else if (Z_TYPE(expr->u.constant) != IS_LONG || Z_LVAL(expr->u.constant) < 1) { zend_error(E_COMPILE_ERROR, "'%s' operator accepts only positive numbers", op == ZEND_BRK ? "break" : "continue"); } SET_NODE(opline->op2, expr); } else { LITERAL_LONG(opline->op2, 1); opline->op2_type = IS_CONST; } } /* }}} */ void zend_do_switch_cond(const znode *cond TSRMLS_DC) /* {{{ */ { zend_switch_entry switch_entry; switch_entry.cond = *cond; switch_entry.default_case = -1; switch_entry.control_var = -1; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_switch_end(const znode *case_list TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); /* add code to jmp to default case */ if (switch_entry_ptr->default_case != -1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->op1.opline_num = switch_entry_ptr->default_case; } if (case_list->op_type != IS_UNUSED) { /* non-empty switch */ int next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* remember break/continue loop information */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; if (switch_entry_ptr->cond.op_type==IS_VAR || switch_entry_ptr->cond.op_type==IS_TMP_VAR) { /* emit free for the switch condition*/ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry_ptr->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_UNUSED(opline->op2); } if (switch_entry_ptr->cond.op_type == IS_CONST) { zval_dtor(&switch_entry_ptr->cond.u.constant); } zend_stack_del_top(&CG(switch_cond_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_case_before_statement(const znode *case_list, znode *case_token, const znode *case_expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); int next_op_number; zend_switch_entry *switch_entry_ptr; znode result; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); if (switch_entry_ptr->control_var == -1) { switch_entry_ptr->control_var = get_temporary_variable(CG(active_op_array)); } opline->opcode = ZEND_CASE; opline->result.var = switch_entry_ptr->control_var; opline->result_type = IS_TMP_VAR; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_NODE(opline->op2, case_expr); if (opline->op1_type == IS_CONST) { zval_copy_ctor(&CONSTANT(opline->op1.constant)); } GET_NODE(&result, opline->result); next_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, &result); SET_UNUSED(opline->op2); case_token->u.op.opline_num = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_case_after_statement(znode *result, const znode *case_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); result->u.op.opline_num = next_op_number; switch (CG(active_op_array)->opcodes[case_token->u.op.opline_num].opcode) { case ZEND_JMP: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); break; case ZEND_JMPZ: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); break; } } /* }}} */ void zend_do_default_before_statement(const znode *case_list, znode *default_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); default_token->u.op.opline_num = next_op_number; next_op_number = get_next_op_number(CG(active_op_array)); switch_entry_ptr->default_case = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_begin_class_declaration(const znode *class_token, znode *class_name, const znode *parent_class_name TSRMLS_DC) /* {{{ */ { zend_op *opline; int doing_inheritance = 0; zend_class_entry *new_class_entry; char *lcname; int error = 0; zval **ns_name, key; if (CG(active_class_entry)) { zend_error(E_COMPILE_ERROR, "Class declarations may not be nested"); return; } lcname = zend_str_tolower_dup(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); if (!(strcmp(lcname, "self") && strcmp(lcname, "parent"))) { efree(lcname); zend_error(E_COMPILE_ERROR, "Cannot use '%s' as class name as it is reserved", Z_STRVAL(class_name->u.constant)); } /* Class name must not conflict with import names */ if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns_name) == SUCCESS) { error = 1; } if (CG(current_namespace)) { /* Prefix class name with name of current namespace */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); class_name = &tmp; efree(lcname); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); } if (error) { char *tmp = zend_str_tolower_dup(Z_STRVAL_PP(ns_name), Z_STRLEN_PP(ns_name)); if (Z_STRLEN_PP(ns_name) != Z_STRLEN(class_name->u.constant) || memcmp(tmp, lcname, Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "Cannot declare class %s because the name is already in use", Z_STRVAL(class_name->u.constant)); } efree(tmp); } new_class_entry = emalloc(sizeof(zend_class_entry)); new_class_entry->type = ZEND_USER_CLASS; new_class_entry->name = zend_new_interned_string(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1, 1 TSRMLS_CC); new_class_entry->name_length = Z_STRLEN(class_name->u.constant); zend_initialize_class_data(new_class_entry, 1 TSRMLS_CC); new_class_entry->info.user.filename = zend_get_compiled_filename(TSRMLS_C); new_class_entry->info.user.line_start = class_token->u.op.opline_num; new_class_entry->ce_flags |= class_token->EA; if (parent_class_name && parent_class_name->op_type != IS_UNUSED) { switch (parent_class_name->EA) { case ZEND_FETCH_CLASS_SELF: zend_error(E_COMPILE_ERROR, "Cannot use 'self' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_PARENT: zend_error(E_COMPILE_ERROR, "Cannot use 'parent' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use 'static' as class name as it is reserved"); break; default: break; } doing_inheritance = 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, new_class_entry->name_length TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; if (doing_inheritance) { /* Make sure a trait does not try to extend a class */ if ((new_class_entry->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "A trait (%s) cannot extend a class", new_class_entry->name); } opline->extended_value = parent_class_name->u.op.var; opline->opcode = ZEND_DECLARE_INHERITED_CLASS; } else { opline->opcode = ZEND_DECLARE_CLASS; } LITERAL_STRINGL(opline->op2, lcname, new_class_entry->name_length, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); zend_hash_quick_update(CG(class_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &new_class_entry, sizeof(zend_class_entry *), NULL); CG(active_class_entry) = new_class_entry; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(&CG(implementing_class), opline->result); if (CG(doc_comment)) { CG(active_class_entry)->info.user.doc_comment = CG(doc_comment); CG(active_class_entry)->info.user.doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ static void do_verify_abstract_class(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_VERIFY_ABSTRACT_CLASS; SET_NODE(opline->op1, &CG(implementing_class)); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_class_declaration(const znode *class_token, const znode *parent_token TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); if (ce->constructor) { ce->constructor->common.fn_flags |= ZEND_ACC_CTOR; if (ce->constructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Constructor %s::%s() cannot be static", ce->name, ce->constructor->common.function_name); } } if (ce->destructor) { ce->destructor->common.fn_flags |= ZEND_ACC_DTOR; if (ce->destructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Destructor %s::%s() cannot be static", ce->name, ce->destructor->common.function_name); } } if (ce->clone) { ce->clone->common.fn_flags |= ZEND_ACC_CLONE; if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static", ce->name, ce->clone->common.function_name); } } ce->info.user.line_end = zend_get_compiled_lineno(TSRMLS_C); /* Check for traits and proceed like with interfaces. * The only difference will be a combined handling of them in the end. * Thus, we need another opcode here. */ if (ce->num_traits > 0) { zend_op *opline; ce->traits = NULL; ce->num_traits = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_TRAITS; /* opcode generation: */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BIND_TRAITS; SET_NODE(opline->op1, &CG(implementing_class)); } if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) && ((parent_token->op_type != IS_UNUSED) || (ce->num_interfaces > 0))) { zend_verify_abstract_class(ce TSRMLS_CC); if (ce->num_interfaces) { do_verify_abstract_class(TSRMLS_C); } } /* Inherit interfaces; reset number to zero, we need it for above check and * will restore it during actual implementation. * The ZEND_ACC_IMPLEMENT_INTERFACES flag disables double call to * zend_verify_abstract_class() */ if (ce->num_interfaces > 0) { ce->interfaces = NULL; ce->num_interfaces = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_INTERFACES; } CG(active_class_entry) = NULL; } /* }}} */ void zend_do_implements_interface(znode *interface_name TSRMLS_DC) /* {{{ */ { zend_op *opline; /* Traits can not implement interfaces */ if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface on '%s' since it is a Trait", Z_STRVAL(interface_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(interface_name->u.constant), Z_STRLEN(interface_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface name as it is reserved", Z_STRVAL(interface_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_INTERFACE; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(interface_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = (opline->extended_value & ~ZEND_FETCH_CLASS_MASK) | ZEND_FETCH_CLASS_INTERFACE; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &interface_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_interfaces++; } /* }}} */ void zend_do_implements_trait(znode *trait_name TSRMLS_DC) /* {{{ */ { zend_op *opline; switch (zend_get_class_fetch_type(Z_STRVAL(trait_name->u.constant), Z_STRLEN(trait_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as trait name as it is reserved", Z_STRVAL(trait_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_TRAIT; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(trait_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = ZEND_FETCH_CLASS_TRAIT; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &trait_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_traits++; } /* }}} */ ZEND_API void zend_mangle_property_name(char **dest, int *dest_length, const char *src1, int src1_length, const char *src2, int src2_length, int internal) /* {{{ */ { char *prop_name; int prop_name_length; prop_name_length = 1 + src1_length + 1 + src2_length; prop_name = pemalloc(prop_name_length + 1, internal); prop_name[0] = '\0'; memcpy(prop_name + 1, src1, src1_length+1); memcpy(prop_name + 1 + src1_length + 1, src2, src2_length+1); *dest = prop_name; *dest_length = prop_name_length; } /* }}} */ static int zend_strnlen(const char* s, int maxlen) /* {{{ */ { int len = 0; while (*s++ && maxlen--) len++; return len; } /* }}} */ ZEND_API int zend_unmangle_property_name(const char *mangled_property, int len, const char **class_name, const char **prop_name) /* {{{ */ { int class_name_len; *class_name = NULL; if (mangled_property[0]!=0) { *prop_name = mangled_property; return SUCCESS; } if (len < 3 || mangled_property[1]==0) { zend_error(E_NOTICE, "Illegal member variable name"); *prop_name = mangled_property; return FAILURE; } class_name_len = zend_strnlen(mangled_property+1, --len - 1) + 1; if (class_name_len >= len || mangled_property[class_name_len]!=0) { zend_error(E_NOTICE, "Corrupt member variable name"); *prop_name = mangled_property; return FAILURE; } *class_name = mangled_property+1; *prop_name = (*class_name)+class_name_len; return SUCCESS; } /* }}} */ void zend_do_declare_property(const znode *var_name, const znode *value, zend_uint access_type TSRMLS_DC) /* {{{ */ { zval *property; zend_property_info *existing_property_info; char *comment = NULL; int comment_len = 0; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Interfaces may not include member variables"); } if (access_type & ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Properties cannot be declared abstract"); } if (access_type & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot declare property %s::$%s final, the final modifier is allowed only for methods and classes", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } if (zend_hash_find(&CG(active_class_entry)->properties_info, var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, (void **) &existing_property_info)==SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::$%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } ALLOC_ZVAL(property); if (value) { *property = value->u.constant; } else { INIT_PZVAL(property); Z_TYPE_P(property) = IS_NULL; } if (CG(doc_comment)) { comment = CG(doc_comment); comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } zend_declare_property_ex(CG(active_class_entry), zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len + 1, 0 TSRMLS_CC), var_name->u.constant.value.str.len, property, access_type, comment, comment_len TSRMLS_CC); efree(var_name->u.constant.value.str.val); } /* }}} */ void zend_do_declare_class_constant(znode *var_name, const znode *value TSRMLS_DC) /* {{{ */ { zval *property; const char *cname = NULL; int result; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed in class constants"); return; } if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Traits cannot have constants"); return; } ALLOC_ZVAL(property); *property = value->u.constant; cname = zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, 0 TSRMLS_CC); if (IS_INTERNED(cname)) { result = zend_hash_quick_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, INTERNED_HASH(cname), &property, sizeof(zval *), NULL); } else { result = zend_hash_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, &property, sizeof(zval *), NULL); } if (result == FAILURE) { FREE_ZVAL(property); zend_error(E_COMPILE_ERROR, "Cannot redefine class constant %s::%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } FREE_PNODE(var_name); if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_fetch_property(znode *result, znode *object, const znode *property TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (object->op_type == IS_CV) { if (object->u.op.var == CG(active_op_array)->this_var) { object->op_type = IS_UNUSED; /* this means $this for objects */ } } else if (fetch_list_ptr->count == 1) { zend_llist_element *le = fetch_list_ptr->head; zend_op *opline_ptr = (zend_op *) le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); SET_UNUSED(opline_ptr->op1); /* this means $this for objects */ SET_NODE(opline_ptr->op2, property); /* if it was usual fetch, we change it to object fetch */ switch (opline_ptr->opcode) { case ZEND_FETCH_W: opline_ptr->opcode = ZEND_FETCH_OBJ_W; break; case ZEND_FETCH_R: opline_ptr->opcode = ZEND_FETCH_OBJ_R; break; case ZEND_FETCH_RW: opline_ptr->opcode = ZEND_FETCH_OBJ_RW; break; case ZEND_FETCH_IS: opline_ptr->opcode = ZEND_FETCH_OBJ_IS; break; case ZEND_FETCH_UNSET: opline_ptr->opcode = ZEND_FETCH_OBJ_UNSET; break; case ZEND_FETCH_FUNC_ARG: opline_ptr->opcode = ZEND_FETCH_OBJ_FUNC_ARG; break; } if (opline_ptr->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline_ptr->op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline_ptr->op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op2.constant); } GET_NODE(result, opline_ptr->result); return; } } if (zend_is_function_or_method_call(object)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, object); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_OBJ_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, object); SET_NODE(opline.op2, property); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline.op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op2.constant); } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void zend_do_halt_compiler_register(TSRMLS_D) /* {{{ */ { char *name, *cfilename; char haltoff[] = "__COMPILER_HALT_OFFSET__"; int len, clen; cfilename = zend_get_compiled_filename(TSRMLS_C); clen = strlen(cfilename); zend_mangle_property_name(&name, &len, haltoff, sizeof(haltoff) - 1, cfilename, clen, 0); zend_register_long_constant(name, len+1, zend_get_scanned_file_offset(TSRMLS_C), CONST_CS, 0 TSRMLS_CC); pefree(name, 0); if (CG(in_namespace)) { zend_do_end_namespace(TSRMLS_C); } } /* }}} */ void zend_do_push_object(const znode *object TSRMLS_DC) /* {{{ */ { zend_stack_push(&CG(object_stack), object, sizeof(znode)); } /* }}} */ void zend_do_pop_object(znode *object TSRMLS_DC) /* {{{ */ { if (object) { znode *tmp; zend_stack_top(&CG(object_stack), (void **) &tmp); *object = *tmp; } zend_stack_del_top(&CG(object_stack)); } /* }}} */ void zend_do_begin_new_object(znode *new_token, znode *class_type TSRMLS_DC) /* {{{ */ { zend_op *opline; unsigned char *ptr = NULL; new_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_NEW; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, class_type); SET_UNUSED(opline->op2); zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(unsigned char *)); } /* }}} */ void zend_do_end_new_object(znode *result, const znode *new_token, const znode *argument_list TSRMLS_DC) /* {{{ */ { znode ctor_result; zend_do_end_function_call(NULL, &ctor_result, argument_list, 1, 0 TSRMLS_CC); zend_do_free(&ctor_result TSRMLS_CC); CG(active_op_array)->opcodes[new_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, CG(active_op_array)->opcodes[new_token->u.op.opline_num].result); } /* }}} */ static zend_constant* zend_get_ct_const(const zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = NULL; if (Z_STRVAL_P(const_name)[0] == '\\') { if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name), (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name)-1); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name), (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } } else if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)+1, (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name)+1, (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } if (c->flags & CONST_CT_SUBST) { return c; } if (all_internal_constants_substitution && (c->flags & CONST_PERSISTENT) && !(CG(compiler_options) & ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION) && Z_TYPE(c->value) != IS_CONSTANT && Z_TYPE(c->value) != IS_CONSTANT_ARRAY) { return c; } return NULL; } /* }}} */ static int zend_constant_ct_subst(znode *result, zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = zend_get_ct_const(const_name, all_internal_constants_substitution TSRMLS_CC); if (c) { zval_dtor(const_name); result->op_type = IS_CONST; result->u.constant = c->value; zval_copy_ctor(&result->u.constant); INIT_PZVAL(&result->u.constant); return 1; } return 0; } /* }}} */ void zend_do_fetch_constant(znode *result, znode *constant_container, znode *constant_name, int mode, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; zend_op *opline; int type; char *compound; ulong fetch_type = 0; if (constant_container) { switch (mode) { case ZEND_CT: /* this is a class constant */ type = zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant)); if (ZEND_FETCH_CLASS_STATIC == type) { zend_error(E_ERROR, "\"static::\" is not allowed in compile-time constants"); } else if (ZEND_FETCH_CLASS_DEFAULT == type) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } zend_do_build_full_name(NULL, constant_container, constant_name, 1 TSRMLS_CC); *result = *constant_container; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: if (constant_container->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant))) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } else { zend_do_fetch_class(&tmp, constant_container TSRMLS_CC); constant_container = &tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); if (constant_container->op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &constant_container->u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, constant_container); } SET_NODE(opline->op2, constant_name); CALCULATE_LITERAL_HASH(opline->op2.constant); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } GET_NODE(result, opline->result); break; } return; } /* namespace constant */ /* only one that did not contain \ from the start can be converted to string if unknown */ switch (mode) { case ZEND_CT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); /* this is a namespace constant, or an unprefixed constant */ if (zend_constant_ct_subst(result, &constant_name->u.constant, 0 TSRMLS_CC)) { break; } zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(!compound) { fetch_type |= IS_CONSTANT_UNQUALIFIED; } *result = *constant_name; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(zend_constant_ct_subst(result, &constant_name->u.constant, 1 TSRMLS_CC)) { break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; if (compound) { /* the name is unambiguous */ opline->extended_value = 0; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } else { opline->extended_value = IS_CONSTANT_UNQUALIFIED; if (CG(current_namespace)) { opline->extended_value |= IS_CONSTANT_IN_NAMESPACE; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 1 TSRMLS_CC); } else { opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } } GET_CACHE_SLOT(opline->op2.constant); break; } } /* }}} */ void zend_do_shell_exec(znode *result, const znode *cmd TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); switch (cmd->op_type) { case IS_CONST: case IS_TMP_VAR: opline->opcode = ZEND_SEND_VAL; break; default: opline->opcode = ZEND_SEND_VAR; break; } SET_NODE(opline->op1, cmd); opline->op2.opline_num = 0; opline->extended_value = ZEND_DO_FCALL; SET_UNUSED(opline->op2); /* FIXME: exception support not added to this op2 */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DO_FCALL; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; LITERAL_STRINGL(opline->op1, estrndup("shell_exec", sizeof("shell_exec")-1), sizeof("shell_exec")-1, 0); CALCULATE_LITERAL_HASH(opline->op1.constant); opline->op1_type = IS_CONST; GET_CACHE_SLOT(opline->op1.constant); opline->extended_value = 1; SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_init_array(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_ARRAY; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; GET_NODE(result, opline->result); if (expr) { SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } } else { SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_array_element(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_ARRAY_ELEMENT; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_static_array_element(znode *result, znode *offset, const znode *expr) /* {{{ */ { zval *element; ALLOC_ZVAL(element); *element = expr->u.constant; if (offset) { switch (offset->u.constant.type & IS_CONSTANT_TYPE_MASK) { case IS_CONSTANT: /* Ugly hack to denote that this value has a constant index */ Z_TYPE_P(element) |= IS_CONSTANT_INDEX; Z_STRVAL(offset->u.constant) = erealloc(Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+1] = Z_TYPE(offset->u.constant); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+2] = 0; zend_symtable_update(result->u.constant.value.ht, Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_STRING: zend_symtable_update(result->u.constant.value.ht, offset->u.constant.value.str.val, offset->u.constant.value.str.len+1, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_NULL: zend_symtable_update(Z_ARRVAL(result->u.constant), "", 1, &element, sizeof(zval *), NULL); break; case IS_LONG: case IS_BOOL: zend_hash_index_update(Z_ARRVAL(result->u.constant), Z_LVAL(offset->u.constant), &element, sizeof(zval *), NULL); break; case IS_DOUBLE: zend_hash_index_update(Z_ARRVAL(result->u.constant), zend_dval_to_lval(Z_DVAL(offset->u.constant)), &element, sizeof(zval *), NULL); break; case IS_CONSTANT_ARRAY: zend_error(E_ERROR, "Illegal offset type"); break; } } else { zend_hash_next_index_insert(Z_ARRVAL(result->u.constant), &element, sizeof(zval *), NULL); } } /* }}} */ void zend_do_add_list_element(const znode *element TSRMLS_DC) /* {{{ */ { list_llist_element lle; if (element) { zend_check_writable_variable(element); lle.var = *element; zend_llist_copy(&lle.dimensions, &CG(dimension_llist)); zend_llist_prepend_element(&CG(list_llist), &lle); } (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_new_list_begin(TSRMLS_D) /* {{{ */ { int current_dimension = 0; zend_llist_add_element(&CG(dimension_llist), &current_dimension); } /* }}} */ void zend_do_new_list_end(TSRMLS_D) /* {{{ */ { zend_llist_remove_tail(&CG(dimension_llist)); (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_list_init(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(list_stack), &CG(list_llist), sizeof(zend_llist)); zend_stack_push(&CG(list_stack), &CG(dimension_llist), sizeof(zend_llist)); zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_do_new_list_begin(TSRMLS_C); } /* }}} */ void zend_do_list_end(znode *result, znode *expr TSRMLS_DC) /* {{{ */ { zend_llist_element *le; zend_llist_element *dimension; zend_op *opline; znode last_container; le = CG(list_llist).head; while (le) { zend_llist *tmp_dimension_llist = &((list_llist_element *)le->data)->dimensions; dimension = tmp_dimension_llist->head; while (dimension) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (dimension == tmp_dimension_llist->head) { /* first */ last_container = *expr; switch (expr->op_type) { case IS_VAR: case IS_CV: opline->opcode = ZEND_FETCH_DIM_R; break; case IS_TMP_VAR: opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; case IS_CONST: /* fetch_dim_tmp_var will handle this bogus fetch */ zval_copy_ctor(&expr->u.constant); opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; } opline->extended_value |= ZEND_FETCH_ADD_LOCK; } else { opline->opcode = ZEND_FETCH_DIM_R; } opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, &last_container); opline->op2_type = IS_CONST; LITERAL_LONG(opline->op2, *((int *) dimension->data)); GET_NODE(&last_container, opline->result); dimension = dimension->next; } ((list_llist_element *) le->data)->value = last_container; zend_llist_destroy(&((list_llist_element *) le->data)->dimensions); zend_do_assign(result, &((list_llist_element *) le->data)->var, &((list_llist_element *) le->data)->value TSRMLS_CC); zend_do_free(result TSRMLS_CC); le = le->next; } zend_llist_destroy(&CG(dimension_llist)); zend_llist_destroy(&CG(list_llist)); *result = *expr; { zend_llist *p; /* restore previous lists */ zend_stack_top(&CG(list_stack), (void **) &p); CG(dimension_llist) = *p; zend_stack_del_top(&CG(list_stack)); zend_stack_top(&CG(list_stack), (void **) &p); CG(list_llist) = *p; zend_stack_del_top(&CG(list_stack)); } } /* }}} */ void zend_init_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = emalloc(sizeof(void*) * 2); list[0] = item; list[1] = NULL; *(void**)result = list; } /* }}} */ void zend_add_to_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = *(void**)result; size_t n = 0; while (list && list[n]) { n++; } list = erealloc(list, sizeof(void*) * (n+2)); list[n] = item; list[n+1] = NULL; *(void**)result = list; } /* }}} */ void zend_do_fetch_static_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zval *tmp; zend_op *opline; znode lval; znode result; ALLOC_ZVAL(tmp); if (static_assignment) { *tmp = static_assignment->u.constant; } else { INIT_ZVAL(*tmp); } if (!CG(active_op_array)->static_variables) { if (CG(active_op_array)->scope) { CG(active_op_array)->scope->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } ALLOC_HASHTABLE(CG(active_op_array)->static_variables); zend_hash_init(CG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } zend_hash_update(CG(active_op_array)->static_variables, varname->u.constant.value.str.val, varname->u.constant.value.str.len+1, &tmp, sizeof(zval *), NULL); if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (fetch_type == ZEND_FETCH_LEXICAL) ? ZEND_FETCH_R : ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_STATIC; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ if (fetch_type == ZEND_FETCH_LEXICAL) { znode dummy; zend_do_begin_variable_parse(TSRMLS_C); zend_do_assign(&dummy, &lval, &result TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } else { zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); } CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_fetch_lexical_variable(znode *varname, zend_bool is_ref TSRMLS_DC) /* {{{ */ { znode value; if (Z_STRLEN(varname->u.constant) == sizeof("this") - 1 && memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this") - 1) == 0) { zend_error(E_COMPILE_ERROR, "Cannot use $this as lexical variable"); return; } value.op_type = IS_CONST; ZVAL_NULL(&value.u.constant); Z_TYPE(value.u.constant) |= is_ref ? IS_LEXICAL_REF : IS_LEXICAL_VAR; Z_SET_REFCOUNT_P(&value.u.constant, 1); Z_UNSET_ISREF_P(&value.u.constant); zend_do_fetch_static_variable(varname, &value, is_ref ? ZEND_FETCH_STATIC : ZEND_FETCH_LEXICAL TSRMLS_CC); } /* }}} */ void zend_do_fetch_global_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zend_op *opline; znode lval; znode result; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = fetch_type; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_cast(znode *result, const znode *expr, int type TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CAST; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } /* }}} */ void zend_do_include_or_eval(int type, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_do_extended_fcall_begin(TSRMLS_C); { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INCLUDE_OR_EVAL; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } zend_do_extended_fcall_end(TSRMLS_C); } /* }}} */ void zend_do_indirect_references(znode *result, const znode *num_references, znode *variable TSRMLS_DC) /* {{{ */ { int i; zend_do_end_variable_parse(variable, BP_VAR_R, 0 TSRMLS_CC); for (i=1; i<num_references->u.constant.value.lval; i++) { fetch_simple_variable_ex(result, variable, 0, ZEND_FETCH_R TSRMLS_CC); *variable = *result; } zend_do_begin_variable_parse(TSRMLS_C); fetch_simple_variable(result, variable, 1 TSRMLS_CC); /* there is a chance someone is accessing $this */ if (CG(active_op_array)->scope && CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } /* }}} */ void zend_do_unset(const znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_UNSET_VAR; SET_NODE(opline->op1, variable); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); opline->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_UNSET: last_op->opcode = ZEND_UNSET_VAR; SET_UNUSED(last_op->result); break; case ZEND_FETCH_DIM_UNSET: last_op->opcode = ZEND_UNSET_DIM; SET_UNUSED(last_op->result); break; case ZEND_FETCH_OBJ_UNSET: last_op->opcode = ZEND_UNSET_OBJ; SET_UNUSED(last_op->result); break; } } } /* }}} */ void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_do_end_variable_parse(variable, BP_VAR_IS, 0 TSRMLS_CC); zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { last_op = get_next_op(CG(active_op_array) TSRMLS_CC); last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; SET_NODE(last_op->op1, variable); SET_UNUSED(last_op->op2); last_op->result.var = get_temporary_variable(CG(active_op_array)); last_op->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; break; case ZEND_FETCH_DIM_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_DIM_OBJ; break; case ZEND_FETCH_OBJ_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_PROP_OBJ; break; } } last_op->result_type = IS_TMP_VAR; last_op->extended_value |= type; GET_NODE(result, last_op->result); } /* }}} */ void zend_do_instanceof(znode *result, const znode *expr, const znode *class_znode, int type TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline->opcode == ZEND_FETCH_CLASS) { opline->extended_value |= ZEND_FETCH_CLASS_NO_AUTOLOAD; } } if (expr->op_type == IS_CONST) { zend_error(E_COMPILE_ERROR, "instanceof expects an object instance, constant given"); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INSTANCEOF; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_NODE(opline->op2, class_znode); GET_NODE(result, opline->result); } /* }}} */ void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_bool is_variable; zend_bool push_container = 0; zend_op dummy_opline; if (variable) { if (zend_is_function_or_method_call(array)) { is_variable = 0; } else { is_variable = 1; } /* save the location of FETCH_W instruction(s) */ open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); zend_do_end_variable_parse(array, BP_VAR_W, 0 TSRMLS_CC); if (CG(active_op_array)->last > 0 && CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) { /* Only lock the container if we are fetching from a real container and not $this */ if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1_type == IS_VAR) { CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK; push_container = 1; } } } else { is_variable = 0; open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* save the location of FE_RESET */ foreach_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* Preform array reset */ opline->opcode = ZEND_FE_RESET; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, array); SET_UNUSED(opline->op2); opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0; COPY_NODE(dummy_opline.result, opline->result); if (push_container) { COPY_NODE(dummy_opline.op1, CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1); } else { dummy_opline.op1_type = IS_UNUSED; } zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); /* save the location of FE_FETCH */ as_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FE_FETCH; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); COPY_NODE(opline->op1, dummy_opline.result); opline->extended_value = 0; SET_UNUSED(opline->op2); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_OP_DATA; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); } /* }}} */ void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC) /* {{{ */ { zend_op *opline; znode dummy, value_node; zend_bool assign_by_ref=0; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num]; if (key->op_type != IS_UNUSED) { znode *tmp; /* switch between the key and value... */ tmp = key; key = value; value = tmp; /* Mark extended_value in case both key and value are being used */ opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; } if ((key->op_type != IS_UNUSED) && (key->EA & ZEND_PARSED_REFERENCE_VARIABLE)) { zend_error(E_COMPILE_ERROR, "Key element cannot be a reference"); } if (value->EA & ZEND_PARSED_REFERENCE_VARIABLE) { assign_by_ref = 1; if (!(opline-1)->extended_value) { zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression"); } /* Mark extended_value for assign-by-reference */ opline->extended_value |= ZEND_FE_FETCH_BYREF; CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; } else { zend_op *foreach_copy; zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.op.opline_num]; zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.op.opline_num]; /* Change "write context" into "read context" */ fetch->extended_value = 0; /* reset ZEND_FE_RESET_VARIABLE */ while (fetch != end) { --fetch; if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } if (fetch->opcode == ZEND_SEPARATE) { MAKE_NOP(fetch); } else { fetch->opcode -= 3; /* FETCH_W -> FETCH_R */ } } /* prevent double SWITCH_FREE */ zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy); foreach_copy->op1_type = IS_UNUSED; } GET_NODE(&value_node, opline->result); if (assign_by_ref) { zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); /* Mark FE_FETCH as IS_VAR as it holds the data directly as a value */ zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC); } else { zend_do_assign(&dummy, value, &value_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } if (key->op_type != IS_UNUSED) { znode key_node; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num+1]; opline->result_type = IS_TMP_VAR; opline->result.opline_num = get_temporary_variable(CG(active_op_array)); GET_NODE(&key_node, opline->result); zend_do_assign(&dummy, key, &key_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_foreach_end(const znode *foreach_token, const znode *as_token TSRMLS_DC) /* {{{ */ { zend_op *container_ptr; zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = as_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_RESET */ CG(active_op_array)->opcodes[as_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_FETCH */ do_end_loop(as_token->u.op.opline_num, 1 TSRMLS_CC); zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr); generate_free_foreach_copy(container_ptr TSRMLS_CC); zend_stack_del_top(&CG(foreach_copy_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_declare_begin(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(declare_stack), &CG(declarables), sizeof(zend_declarables)); } /* }}} */ void zend_do_declare_stmt(znode *var, znode *val TSRMLS_DC) /* {{{ */ { if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "ticks", sizeof("ticks")-1)) { convert_to_long(&val->u.constant); CG(declarables).ticks = val->u.constant; } else if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "encoding", sizeof("encoding")-1)) { if ((Z_TYPE(val->u.constant) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Cannot use constants as encoding"); } /* * Check that the pragma comes before any opcodes. If the compilation * got as far as this, the previous portion of the script must have been * parseable according to the .ini script_encoding setting. We still * want to tell them to put declare() at the top. */ { int num = CG(active_op_array)->last; /* ignore ZEND_EXT_STMT and ZEND_TICKS */ while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Encoding declaration pragma must be the very first statement in the script"); } } if (CG(multibyte)) { const zend_encoding *new_encoding, *old_encoding; zend_encoding_filter old_input_filter; CG(encoding_declared) = 1; convert_to_string(&val->u.constant); new_encoding = zend_multibyte_fetch_encoding(val->u.constant.value.str.val TSRMLS_CC); if (!new_encoding) { zend_error(E_COMPILE_WARNING, "Unsupported encoding [%s]", val->u.constant.value.str.val); } else { old_input_filter = LANG_SCNG(input_filter); old_encoding = LANG_SCNG(script_encoding); zend_multibyte_set_filter(new_encoding TSRMLS_CC); /* need to re-scan if input filter changed */ if (old_input_filter != LANG_SCNG(input_filter) || (old_input_filter && new_encoding != old_encoding)) { zend_multibyte_yyinput_again(old_input_filter, old_encoding TSRMLS_CC); } } } else { zend_error(E_COMPILE_WARNING, "declare(encoding=...) ignored because Zend multibyte feature is turned off by settings"); } zval_dtor(&val->u.constant); } else { zend_error(E_COMPILE_WARNING, "Unsupported declare '%s'", var->u.constant.value.str.val); zval_dtor(&val->u.constant); } zval_dtor(&var->u.constant); } /* }}} */ void zend_do_declare_end(const znode *declare_token TSRMLS_DC) /* {{{ */ { zend_declarables *declarables; zend_stack_top(&CG(declare_stack), (void **) &declarables); /* We should restore if there was more than (current - start) - (ticks?1:0) opcodes */ if ((get_next_op_number(CG(active_op_array)) - declare_token->u.op.opline_num) - ((Z_LVAL(CG(declarables).ticks))?1:0)) { CG(declarables) = *declarables; } } /* }}} */ void zend_do_exit(znode *result, const znode *message TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXIT; SET_NODE(opline->op1, message); SET_UNUSED(opline->op2); result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_BOOL; Z_LVAL(result->u.constant) = 1; } /* }}} */ void zend_do_begin_silence(znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BEGIN_SILENCE; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); GET_NODE(strudel_token, opline->result); } /* }}} */ void zend_do_end_silence(const znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_END_SILENCE; SET_NODE(opline->op1, strudel_token); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_jmp_set(const znode *value, znode *jmp_token, znode *colon_token TSRMLS_DC) /* {{{ */ { int op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (value->op_type == IS_VAR || value->op_type == IS_CV) { opline->opcode = ZEND_JMP_SET_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_JMP_SET; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, value); SET_UNUSED(opline->op2); GET_NODE(colon_token, opline->result); jmp_token->u.op .opline_num = op_number; INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_jmp_set_else(znode *result, const znode *false_value, const znode *jmp_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, colon_token); if (colon_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].opcode = ZEND_JMP_SET_VAR; CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } opline->extended_value = 0; SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_qm_op(const znode *cond, znode *qm_token TSRMLS_DC) /* {{{ */ { int jmpz_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); SET_UNUSED(opline->op2); opline->op2.opline_num = jmpz_op_number; GET_NODE(qm_token, opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_qm_true(const znode *true_value, znode *qm_token, znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->opcodes[qm_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array))+1; /* jmp over the ZEND_JMP */ if (true_value->op_type == IS_VAR || true_value->op_type == IS_CV) { opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, true_value); SET_UNUSED(opline->op2); GET_NODE(qm_token, opline->result); colon_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_qm_false(znode *result, const znode *false_value, const znode *qm_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, qm_token); if (qm_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].opcode = ZEND_QM_ASSIGN_VAR; CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[colon_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, opline->result); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_extended_info(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_STMT; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_begin(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_BEGIN; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_end(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_END; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_ticks(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_TICKS; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->extended_value = Z_LVAL(CG(declarables).ticks); } /* }}} */ zend_bool zend_is_auto_global_quick(const char *name, uint name_len, ulong hashval TSRMLS_DC) /* {{{ */ { zend_auto_global *auto_global; ulong hash = hashval ? hashval : zend_hash_func(name, name_len+1); if (zend_hash_quick_find(CG(auto_globals), name, name_len+1, hash, (void **) &auto_global)==SUCCESS) { if (auto_global->armed) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } return 1; } return 0; } /* }}} */ zend_bool zend_is_auto_global(const char *name, uint name_len TSRMLS_DC) /* {{{ */ { return zend_is_auto_global_quick(name, name_len, 0 TSRMLS_CC); } /* }}} */ int zend_register_auto_global(const char *name, uint name_len, zend_bool jit, zend_auto_global_callback auto_global_callback TSRMLS_DC) /* {{{ */ { zend_auto_global auto_global; auto_global.name = zend_new_interned_string((char*)name, name_len + 1, 0 TSRMLS_CC); auto_global.name_len = name_len; auto_global.auto_global_callback = auto_global_callback; auto_global.jit = jit; return zend_hash_add(CG(auto_globals), name, name_len+1, &auto_global, sizeof(zend_auto_global), NULL); } /* }}} */ static int zend_auto_global_init(zend_auto_global *auto_global TSRMLS_DC) /* {{{ */ { if (auto_global->jit) { auto_global->armed = 1; } else if (auto_global->auto_global_callback) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } else { auto_global->armed = 0; } return 0; } /* }}} */ ZEND_API void zend_activate_auto_globals(TSRMLS_D) /* {{{ */ { zend_hash_apply(CG(auto_globals), (apply_func_t) zend_auto_global_init TSRMLS_CC); } /* }}} */ int zendlex(znode *zendlval TSRMLS_DC) /* {{{ */ { int retval; if (CG(increment_lineno)) { CG(zend_lineno)++; CG(increment_lineno) = 0; } again: Z_TYPE(zendlval->u.constant) = IS_LONG; retval = lex_scan(&zendlval->u.constant TSRMLS_CC); switch (retval) { case T_COMMENT: case T_DOC_COMMENT: case T_OPEN_TAG: case T_WHITESPACE: goto again; case T_CLOSE_TAG: if (LANG_SCNG(yy_text)[LANG_SCNG(yy_leng)-1] != '>') { CG(increment_lineno) = 1; } if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { goto again; } retval = ';'; /* implicit ; */ break; case T_OPEN_TAG_WITH_ECHO: retval = T_ECHO; break; case T_END_HEREDOC: efree(Z_STRVAL(zendlval->u.constant)); break; } INIT_PZVAL(&zendlval->u.constant); zendlval->op_type = IS_CONST; return retval; } /* }}} */ ZEND_API void zend_initialize_class_data(zend_class_entry *ce, zend_bool nullify_handlers TSRMLS_DC) /* {{{ */ { zend_bool persistent_hashes = (ce->type == ZEND_INTERNAL_CLASS) ? 1 : 0; dtor_func_t zval_ptr_dtor_func = ((persistent_hashes) ? ZVAL_INTERNAL_PTR_DTOR : ZVAL_PTR_DTOR); ce->refcount = 1; ce->ce_flags = 0; ce->default_properties_table = NULL; ce->default_static_members_table = NULL; zend_hash_init_ex(&ce->properties_info, 0, NULL, (dtor_func_t) (persistent_hashes ? zend_destroy_property_info_internal : zend_destroy_property_info), persistent_hashes, 0); zend_hash_init_ex(&ce->constants_table, 0, NULL, zval_ptr_dtor_func, persistent_hashes, 0); zend_hash_init_ex(&ce->function_table, 0, NULL, ZEND_FUNCTION_DTOR, persistent_hashes, 0); if (ce->type == ZEND_INTERNAL_CLASS) { #ifdef ZTS int n = zend_hash_num_elements(CG(class_table)); if (CG(static_members_table) && n >= CG(last_static_member)) { /* Support for run-time declaration: dl() */ CG(last_static_member) = n+1; CG(static_members_table) = realloc(CG(static_members_table), (n+1)*sizeof(zval**)); CG(static_members_table)[n] = NULL; } ce->static_members_table = (zval**)(zend_intptr_t)n; #else ce->static_members_table = NULL; #endif } else { ce->static_members_table = ce->default_static_members_table; ce->info.user.doc_comment = NULL; ce->info.user.doc_comment_len = 0; } ce->default_properties_count = 0; ce->default_static_members_count = 0; if (nullify_handlers) { ce->constructor = NULL; ce->destructor = NULL; ce->clone = NULL; ce->__get = NULL; ce->__set = NULL; ce->__unset = NULL; ce->__isset = NULL; ce->__call = NULL; ce->__callstatic = NULL; ce->__tostring = NULL; ce->create_object = NULL; ce->get_iterator = NULL; ce->iterator_funcs.funcs = NULL; ce->interface_gets_implemented = NULL; ce->get_static_method = NULL; ce->parent = NULL; ce->num_interfaces = 0; ce->interfaces = NULL; ce->num_traits = 0; ce->traits = NULL; ce->trait_aliases = NULL; ce->trait_precedences = NULL; ce->serialize = NULL; ce->unserialize = NULL; ce->serialize_func = NULL; ce->unserialize_func = NULL; if (ce->type == ZEND_INTERNAL_CLASS) { ce->info.internal.module = NULL; ce->info.internal.builtin_functions = NULL; } } } /* }}} */ int zend_get_class_fetch_type(const char *class_name, uint class_name_len) /* {{{ */ { if ((class_name_len == sizeof("self")-1) && !memcmp(class_name, "self", sizeof("self")-1)) { return ZEND_FETCH_CLASS_SELF; } else if ((class_name_len == sizeof("parent")-1) && !memcmp(class_name, "parent", sizeof("parent")-1)) { return ZEND_FETCH_CLASS_PARENT; } else if ((class_name_len == sizeof("static")-1) && !memcmp(class_name, "static", sizeof("static")-1)) { return ZEND_FETCH_CLASS_STATIC; } else { return ZEND_FETCH_CLASS_DEFAULT; } } /* }}} */ ZEND_API const char* zend_get_compiled_variable_name(const zend_op_array *op_array, zend_uint var, int* name_len) /* {{{ */ { if (name_len) { *name_len = op_array->vars[var].name_len; } return op_array->vars[var].name; } /* }}} */ void zend_do_build_namespace_name(znode *result, znode *prefix, znode *name TSRMLS_DC) /* {{{ */ { if (prefix) { *result = *prefix; if (Z_TYPE(result->u.constant) == IS_STRING && Z_STRLEN(result->u.constant) == 0) { /* namespace\ */ if (CG(current_namespace)) { znode tmp; zval_dtor(&result->u.constant); tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(result, NULL, &tmp TSRMLS_CC); } } } else { result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_STRING; Z_STRVAL(result->u.constant) = NULL; Z_STRLEN(result->u.constant) = 0; } /* prefix = result */ zend_do_build_full_name(NULL, result, name, 0 TSRMLS_CC); } /* }}} */ void zend_do_begin_namespace(const znode *name, zend_bool with_bracket TSRMLS_DC) /* {{{ */ { char *lcname; /* handle mixed syntax declaration or nested namespaces */ if (!CG(has_bracketed_namespaces)) { if (CG(current_namespace)) { /* previous namespace declarations were unbracketed */ if (with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } } } else { /* previous namespace declarations were bracketed */ if (!with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } else if (CG(current_namespace) || CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "Namespace declarations cannot be nested"); } } if (((!with_bracket && !CG(current_namespace)) || (with_bracket && !CG(has_bracketed_namespaces))) && CG(active_op_array)->last > 0) { /* ignore ZEND_EXT_STMT and ZEND_TICKS */ int num = CG(active_op_array)->last; while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Namespace declaration statement has to be the very first statement in the script"); } } CG(in_namespace) = 1; if (with_bracket) { CG(has_bracketed_namespaces) = 1; } if (name) { lcname = zend_str_tolower_dup(Z_STRVAL(name->u.constant), Z_STRLEN(name->u.constant)); if (((Z_STRLEN(name->u.constant) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN(name->u.constant) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as namespace name", Z_STRVAL(name->u.constant)); } efree(lcname); if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); } else { ALLOC_ZVAL(CG(current_namespace)); } *CG(current_namespace) = name->u.constant; } else { if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_use(znode *ns_name, znode *new_name, int is_global TSRMLS_DC) /* {{{ */ { char *lcname; zval *name, *ns, tmp; zend_bool warn = 0; zend_class_entry **pce; if (!CG(current_import)) { CG(current_import) = emalloc(sizeof(HashTable)); zend_hash_init(CG(current_import), 0, NULL, ZVAL_PTR_DTOR, 0); } ALLOC_ZVAL(ns); *ns = ns_name->u.constant; if (new_name) { name = &new_name->u.constant; } else { const char *p; /* The form "use A\B" is eqivalent to "use A\B as B". So we extract the last part of compound name to use as a new_name */ name = &tmp; p = zend_memrchr(Z_STRVAL_P(ns), '\\', Z_STRLEN_P(ns)); if (p) { ZVAL_STRING(name, p+1, 1); } else { *name = *ns; zval_copy_ctor(name); warn = !is_global && !CG(current_namespace); } } lcname = zend_str_tolower_dup(Z_STRVAL_P(name), Z_STRLEN_P(name)); if (((Z_STRLEN_P(name) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN_P(name) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because '%s' is a special class name", Z_STRVAL_P(ns), Z_STRVAL_P(name), Z_STRVAL_P(name)); } if (CG(current_namespace)) { /* Prefix import name with current namespace name to avoid conflicts with classes */ char *c_ns_name = emalloc(Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) + 1); zend_str_tolower_copy(c_ns_name, Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); c_ns_name[Z_STRLEN_P(CG(current_namespace))] = '\\'; memcpy(c_ns_name+Z_STRLEN_P(CG(current_namespace))+1, lcname, Z_STRLEN_P(name)+1); if (zend_hash_exists(CG(class_table), c_ns_name, Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name)+1)) { char *tmp2 = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) || memcmp(tmp2, c_ns_name, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(tmp2); } efree(c_ns_name); } else if (zend_hash_find(CG(class_table), lcname, Z_STRLEN_P(name)+1, (void**)&pce) == SUCCESS && (*pce)->type == ZEND_USER_CLASS && (*pce)->info.user.filename == CG(compiled_filename)) { char *c_tmp = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(name) || memcmp(c_tmp, lcname, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(c_tmp); } if (zend_hash_add(CG(current_import), lcname, Z_STRLEN_P(name)+1, &ns, sizeof(zval*), NULL) != SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } if (warn) { if (!strcmp(Z_STRVAL_P(name), "strict")) { zend_error(E_COMPILE_ERROR, "You seem to be trying to use a different language..."); } zend_error(E_WARNING, "The use statement with non-compound name '%s' has no effect", Z_STRVAL_P(name)); } efree(lcname); zval_dtor(name); } /* }}} */ void zend_do_declare_constant(znode *name, znode *value TSRMLS_DC) /* {{{ */ { zend_op *opline; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed as constants"); } if (zend_get_ct_const(&name->u.constant, 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare constant '%s'", Z_STRVAL(name->u.constant)); } if (CG(current_namespace)) { /* Prefix constant name with name of current namespace, lowercased */ znode tmp; tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); Z_STRVAL(tmp.u.constant) = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), Z_STRLEN(tmp.u.constant)); zend_do_build_namespace_name(&tmp, &tmp, name TSRMLS_CC); *name = tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DECLARE_CONST; SET_UNUSED(opline->result); SET_NODE(opline->op1, name); SET_NODE(opline->op2, value); } /* }}} */ void zend_verify_namespace(TSRMLS_D) /* {{{ */ { if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "No code may exist outside of namespace {}"); } } /* }}} */ void zend_do_end_namespace(TSRMLS_D) /* {{{ */ { CG(in_namespace) = 0; if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_end_compilation(TSRMLS_D) /* {{{ */ { CG(has_bracketed_namespaces) = 0; zend_do_end_namespace(TSRMLS_C); } /* }}} */ /* {{{ zend_dirname Returns directory name component of path */ ZEND_API size_t zend_dirname(char *path, size_t len) { register char *end = path + len - 1; unsigned int len_adjust = 0; #ifdef PHP_WIN32 /* Note that on Win32 CWD is per drive (heritage from CP/M). * This means dirname("c:foo") maps to "c:." or "c:" - which means CWD on C: drive. */ if ((2 <= len) && isalpha((int)((unsigned char *)path)[0]) && (':' == path[1])) { /* Skip over the drive spec (if any) so as not to change */ path += 2; len_adjust += 2; if (2 == len) { /* Return "c:" on Win32 for dirname("c:"). * It would be more consistent to return "c:." * but that would require making the string *longer*. */ return len; } } #elif defined(NETWARE) /* * Find the first occurence of : from the left * move the path pointer to the position just after : * increment the len_adjust to the length of path till colon character(inclusive) * If there is no character beyond : simple return len */ char *colonpos = NULL; colonpos = strchr(path, ':'); if (colonpos != NULL) { len_adjust = ((colonpos - path) + 1); path += len_adjust; if (len_adjust == len) { return len; } } #endif if (len == 0) { /* Illegal use of this function */ return 0; } /* Strip trailing slashes */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { /* The path only contained slashes */ path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } /* Strip filename */ while (end >= path && !IS_SLASH_P(end)) { end--; } if (end < path) { /* No slash found, therefore return '.' */ #ifdef NETWARE if (len_adjust == 0) { path[0] = '.'; path[1] = '\0'; return 1; /* only one character */ } else { path[0] = '\0'; return len_adjust; } #else path[0] = '.'; path[1] = '\0'; return 1 + len_adjust; #endif } /* Strip slashes which came before the file name */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } *(end+1) = '\0'; return (size_t)(end + 1 - path) + len_adjust; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */ /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <zend_language_parser.h> #include "zend.h" #include "zend_compile.h" #include "zend_constants.h" #include "zend_llist.h" #include "zend_API.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "zend_multibyte.h" #include "zend_language_scanner.h" #define CONSTANT_EX(op_array, op) \ (op_array)->literals[op].constant #define CONSTANT(op) \ CONSTANT_EX(CG(active_op_array), op) #define SET_NODE(target, src) do { \ target ## _type = (src)->op_type; \ if ((src)->op_type == IS_CONST) { \ target.constant = zend_add_literal(CG(active_op_array), &(src)->u.constant TSRMLS_CC); \ } else { \ target = (src)->u.op; \ } \ } while (0) #define GET_NODE(target, src) do { \ (target)->op_type = src ## _type; \ if ((target)->op_type == IS_CONST) { \ (target)->u.constant = CONSTANT(src.constant); \ } else { \ (target)->u.op = src; \ (target)->EA = 0; \ } \ } while (0) #define COPY_NODE(target, src) do { \ target ## _type = src ## _type; \ target = src; \ } while (0) #define CALCULATE_LITERAL_HASH(num) do { \ if (IS_INTERNED(Z_STRVAL(CONSTANT(num)))) { \ Z_HASH_P(&CONSTANT(num)) = INTERNED_HASH(Z_STRVAL(CONSTANT(num))); \ } else { \ Z_HASH_P(&CONSTANT(num)) = zend_hash_func(Z_STRVAL(CONSTANT(num)), Z_STRLEN(CONSTANT(num))+1); \ } \ } while (0) #define GET_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot++; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ } \ } while (0) #define POLYMORPHIC_CACHE_SLOT_SIZE 2 #define GET_POLYMORPHIC_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot; \ CG(active_op_array)->last_cache_slot += POLYMORPHIC_CACHE_SLOT_SIZE; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 2] = NULL; \ } \ } while (0) #define FREE_POLYMORPHIC_CACHE_SLOT(literal) do { \ if (CG(active_op_array)->literals[literal].cache_slot == \ CG(active_op_array)->last_cache_slot - POLYMORPHIC_CACHE_SLOT_SIZE) { \ CG(active_op_array)->literals[literal].cache_slot = -1; \ CG(active_op_array)->last_cache_slot -= POLYMORPHIC_CACHE_SLOT_SIZE; \ } \ } while (0) ZEND_API zend_op_array *(*zend_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); ZEND_API zend_op_array *(*zend_compile_string)(zval *source_string, char *filename TSRMLS_DC); #ifndef ZTS ZEND_API zend_compiler_globals compiler_globals; ZEND_API zend_executor_globals executor_globals; #endif static void zend_duplicate_property_info(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = estrndup(property_info->name, property_info->name_length); } if (property_info->doc_comment) { property_info->doc_comment = estrndup(property_info->doc_comment, property_info->doc_comment_len); } } /* }}} */ static void zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = zend_strndup(property_info->name, property_info->name_length); } } /* }}} */ static void zend_destroy_property_info(zend_property_info *property_info) /* {{{ */ { str_efree(property_info->name); if (property_info->doc_comment) { efree((char*)property_info->doc_comment); } } /* }}} */ static void zend_destroy_property_info_internal(zend_property_info *property_info) /* {{{ */ { str_free((char*)property_info->name); } /* }}} */ static void build_runtime_defined_function_key(zval *result, const char *name, int name_length TSRMLS_DC) /* {{{ */ { char char_pos_buf[32]; uint char_pos_len; const char *filename; char_pos_len = zend_sprintf(char_pos_buf, "%p", LANG_SCNG(yy_text)); if (CG(active_op_array)->filename) { filename = CG(active_op_array)->filename; } else { filename = "-"; } /* NULL, name length, filename length, last accepting char position length */ result->value.str.len = 1+name_length+strlen(filename)+char_pos_len; /* must be binary safe */ result->value.str.val = (char *) safe_emalloc(result->value.str.len, 1, 1); result->value.str.val[0] = '\0'; sprintf(result->value.str.val+1, "%s%s%s", name, filename, char_pos_buf); result->type = IS_STRING; Z_SET_REFCOUNT_P(result, 1); } /* }}} */ static void init_compiler_declarables(TSRMLS_D) /* {{{ */ { Z_TYPE(CG(declarables).ticks) = IS_LONG; Z_LVAL(CG(declarables).ticks) = 0; } /* }}} */ void zend_init_compiler_context(TSRMLS_D) /* {{{ */ { CG(context).opcodes_size = (CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) ? INITIAL_INTERACTIVE_OP_ARRAY_SIZE : INITIAL_OP_ARRAY_SIZE; CG(context).vars_size = 0; CG(context).literals_size = 0; CG(context).current_brk_cont = -1; CG(context).backpatch_count = 0; CG(context).labels = NULL; } /* }}} */ void zend_init_compiler_data_structures(TSRMLS_D) /* {{{ */ { zend_stack_init(&CG(bp_stack)); zend_stack_init(&CG(function_call_stack)); zend_stack_init(&CG(switch_cond_stack)); zend_stack_init(&CG(foreach_copy_stack)); zend_stack_init(&CG(object_stack)); zend_stack_init(&CG(declare_stack)); CG(active_class_entry) = NULL; zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_stack_init(&CG(list_stack)); CG(in_compilation) = 0; CG(start_lineno) = 0; CG(current_namespace) = NULL; CG(in_namespace) = 0; CG(has_bracketed_namespaces) = 0; CG(current_import) = NULL; init_compiler_declarables(TSRMLS_C); zend_stack_init(&CG(context_stack)); CG(encoding_declared) = 0; } /* }}} */ ZEND_API void file_handle_dtor(zend_file_handle *fh) /* {{{ */ { TSRMLS_FETCH(); zend_file_handle_dtor(fh TSRMLS_CC); } /* }}} */ void init_compiler(TSRMLS_D) /* {{{ */ { CG(active_op_array) = NULL; zend_init_compiler_data_structures(TSRMLS_C); zend_init_rsrc_list(TSRMLS_C); zend_hash_init(&CG(filenames_table), 5, NULL, (dtor_func_t) free_estring, 0); zend_llist_init(&CG(open_files), sizeof(zend_file_handle), (void (*)(void *)) file_handle_dtor, 0); CG(unclean_shutdown) = 0; } /* }}} */ void shutdown_compiler(TSRMLS_D) /* {{{ */ { zend_stack_destroy(&CG(bp_stack)); zend_stack_destroy(&CG(function_call_stack)); zend_stack_destroy(&CG(switch_cond_stack)); zend_stack_destroy(&CG(foreach_copy_stack)); zend_stack_destroy(&CG(object_stack)); zend_stack_destroy(&CG(declare_stack)); zend_stack_destroy(&CG(list_stack)); zend_hash_destroy(&CG(filenames_table)); zend_llist_destroy(&CG(open_files)); zend_stack_destroy(&CG(context_stack)); } /* }}} */ ZEND_API char *zend_set_compiled_filename(const char *new_compiled_filename TSRMLS_DC) /* {{{ */ { char **pp, *p; int length = strlen(new_compiled_filename); if (zend_hash_find(&CG(filenames_table), new_compiled_filename, length+1, (void **) &pp) == SUCCESS) { CG(compiled_filename) = *pp; return *pp; } p = estrndup(new_compiled_filename, length); zend_hash_update(&CG(filenames_table), new_compiled_filename, length+1, &p, sizeof(char *), (void **) &pp); CG(compiled_filename) = p; return p; } /* }}} */ ZEND_API void zend_restore_compiled_filename(char *original_compiled_filename TSRMLS_DC) /* {{{ */ { CG(compiled_filename) = original_compiled_filename; } /* }}} */ ZEND_API char *zend_get_compiled_filename(TSRMLS_D) /* {{{ */ { return CG(compiled_filename); } /* }}} */ ZEND_API int zend_get_compiled_lineno(TSRMLS_D) /* {{{ */ { return CG(zend_lineno); } /* }}} */ ZEND_API zend_bool zend_is_compiling(TSRMLS_D) /* {{{ */ { return CG(in_compilation); } /* }}} */ static zend_uint get_temporary_variable(zend_op_array *op_array) /* {{{ */ { return (op_array->T)++ * ZEND_MM_ALIGNED_SIZE(sizeof(temp_variable)); } /* }}} */ static int lookup_cv(zend_op_array *op_array, char* name, int name_len, ulong hash TSRMLS_DC) /* {{{ */ { int i = 0; ulong hash_value = hash ? hash : zend_inline_hash_func(name, name_len+1); while (i < op_array->last_var) { if (op_array->vars[i].name == name || (op_array->vars[i].hash_value == hash_value && op_array->vars[i].name_len == name_len && memcmp(op_array->vars[i].name, name, name_len) == 0)) { str_efree(name); return i; } i++; } i = op_array->last_var; op_array->last_var++; if (op_array->last_var > CG(context).vars_size) { CG(context).vars_size += 16; /* FIXME */ op_array->vars = erealloc(op_array->vars, CG(context).vars_size * sizeof(zend_compiled_variable)); } op_array->vars[i].name = zend_new_interned_string(name, name_len + 1, 1 TSRMLS_CC); op_array->vars[i].name_len = name_len; op_array->vars[i].hash_value = hash_value; return i; } /* }}} */ void zend_del_literal(zend_op_array *op_array, int n) /* {{{ */ { zval_dtor(&CONSTANT_EX(op_array, n)); if (n + 1 == op_array->last_literal) { op_array->last_literal--; } else { Z_TYPE(CONSTANT_EX(op_array, n)) = IS_NULL; } } /* }}} */ /* Common part of zend_add_literal and zend_append_individual_literal */ static inline void zend_insert_literal(zend_op_array *op_array, const zval *zv, int literal_position TSRMLS_DC) /* {{{ */ { if (Z_TYPE_P(zv) == IS_STRING || Z_TYPE_P(zv) == IS_CONSTANT) { zval *z = (zval*)zv; Z_STRVAL_P(z) = (char*)zend_new_interned_string(Z_STRVAL_P(zv), Z_STRLEN_P(zv) + 1, 1 TSRMLS_CC); } CONSTANT_EX(op_array, literal_position) = *zv; Z_SET_REFCOUNT(CONSTANT_EX(op_array, literal_position), 2); Z_SET_ISREF(CONSTANT_EX(op_array, literal_position)); op_array->literals[literal_position].hash_value = 0; op_array->literals[literal_position].cache_slot = -1; } /* }}} */ /* Is used while compiling a function, using the context to keep track of an approximate size to avoid to relocate to often. Literals are truncated to actual size in the second compiler pass (pass_two()). */ int zend_add_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; if (i >= CG(context).literals_size) { while (i >= CG(context).literals_size) { CG(context).literals_size += 16; /* FIXME */ } op_array->literals = (zend_literal*)erealloc(op_array->literals, CG(context).literals_size * sizeof(zend_literal)); } zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ /* Is used after normal compilation to append an additional literal. Allocation is done precisely here. */ int zend_append_individual_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; op_array->literals = (zend_literal*)erealloc(op_array->literals, (i + 1) * sizeof(zend_literal)); zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ int zend_add_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_ns_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; const char *ns_separator; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); ns_separator = (const char*)zend_memrchr(Z_STRVAL_P(zv), '\\', Z_STRLEN_P(zv)) + 1; lc_len = Z_STRLEN_P(zv) - (ns_separator - Z_STRVAL_P(zv)); lc_name = zend_str_tolower_dup(ns_separator, lc_len); ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_class_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } if (Z_STRVAL_P(zv)[0] == '\\') { lc_len = Z_STRLEN_P(zv) - 1; lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv) + 1, lc_len); } else { lc_len = Z_STRLEN_P(zv); lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), lc_len); } ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); GET_CACHE_SLOT(ret); return ret; } /* }}} */ int zend_add_const_name_literal(zend_op_array *op_array, const zval *zv, int unqualified TSRMLS_DC) /* {{{ */ { int ret, tmp_literal; char *name, *tmp_name; const char *ns_separator; int name_len, ns_len; zval c; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } /* skip leading '\\' */ if (Z_STRVAL_P(zv)[0] == '\\') { name_len = Z_STRLEN_P(zv) - 1; name = Z_STRVAL_P(zv) + 1; } else { name_len = Z_STRLEN_P(zv); name = Z_STRVAL_P(zv); } ns_separator = zend_memrchr(name, '\\', name_len); if (ns_separator) { ns_len = ns_separator - name; } else { ns_len = 0; } if (ns_len) { /* lowercased namespace name & original constant name */ tmp_name = estrndup(name, name_len); zend_str_tolower(tmp_name, ns_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased namespace name & lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); } if (ns_len) { if (!unqualified) { return ret; } ns_len++; name += ns_len; name_len -= ns_len; } /* original constant name */ tmp_name = estrndup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); return ret; } /* }}} */ #define LITERAL_STRINGL(op, str, len, copy) do { \ zval _c; \ ZVAL_STRINGL(&_c, str, len, copy); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG(op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG_EX(op_array, op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(op_array, &_c TSRMLS_CC); \ } while (0) #define LITERAL_NULL(op) do { \ zval _c; \ INIT_ZVAL( _c); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) static inline zend_bool zend_is_function_or_method_call(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; return ((type & ZEND_PARSED_METHOD_CALL) || (type == ZEND_PARSED_FUNCTION_CALL)); } /* }}} */ void zend_do_binary_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_unary_op(zend_uchar op, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); GET_NODE(result, opline->result); SET_UNUSED(opline->op2); } /* }}} */ #define MAKE_NOP(opline) { opline->opcode = ZEND_NOP; memset(&opline->result,0,sizeof(opline->result)); memset(&opline->op1,0,sizeof(opline->op1)); memset(&opline->op2,0,sizeof(opline->op2)); opline->result_type=opline->op1_type=opline->op2_type=IS_UNUSED; } static void zend_do_op_data(zend_op *data_op, const znode *value TSRMLS_DC) /* {{{ */ { data_op->opcode = ZEND_OP_DATA; SET_NODE(data_op->op1, value); SET_UNUSED(data_op->op2); } /* }}} */ void zend_do_binary_assign_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; switch (last_op->opcode) { case ZEND_FETCH_OBJ_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, op2 TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; case ZEND_FETCH_DIM_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_DIM; zend_do_op_data(opline, op2 TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result,last_op->result); return; default: break; } } opline->opcode = op; SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void fetch_simple_variable_ex(znode *result, znode *varname, int bp, zend_uchar op TSRMLS_DC) /* {{{ */ { zend_op opline; zend_op *opline_ptr; zend_llist *fetch_list_ptr; if (varname->op_type == IS_CONST) { ulong hash = 0; if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } else if (IS_INTERNED(Z_STRVAL(varname->u.constant))) { hash = INTERNED_HASH(Z_STRVAL(varname->u.constant)); } if (!zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC) && !(varname->u.constant.value.str.len == (sizeof("this")-1) && !memcmp(varname->u.constant.value.str.val, "this", sizeof("this"))) && (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE)) { result->op_type = IS_CV; result->u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC); varname->u.constant.value.str.val = (char*)CG(active_op_array)->vars[result->u.op.var].name; result->EA = 0; return; } } if (bp) { opline_ptr = &opline; init_op(opline_ptr TSRMLS_CC); } else { opline_ptr = get_next_op(CG(active_op_array) TSRMLS_CC); } opline_ptr->opcode = op; opline_ptr->result_type = IS_VAR; opline_ptr->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline_ptr->op1, varname); GET_NODE(result, opline_ptr->result); SET_UNUSED(opline_ptr->op2); opline_ptr->extended_value = ZEND_FETCH_LOCAL; if (varname->op_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline_ptr->op1.constant); if (zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC)) { opline_ptr->extended_value = ZEND_FETCH_GLOBAL; } } if (bp) { zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); zend_llist_add_element(fetch_list_ptr, opline_ptr); } } /* }}} */ void fetch_simple_variable(znode *result, znode *varname, int bp TSRMLS_DC) /* {{{ */ { /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ fetch_simple_variable_ex(result, varname, bp, ZEND_FETCH_W TSRMLS_CC); } /* }}} */ void zend_do_fetch_static_member(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { znode class_node; zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline_ptr; zend_op opline; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); } zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (result->op_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[result->u.op.var].name), CG(active_op_array)->vars[result->u.op.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } GET_NODE(result,opline.result); opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; opline_ptr = &opline; zend_llist_add_element(fetch_list_ptr, &opline); } else { le = fetch_list_ptr->head; opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode != ZEND_FETCH_W && opline_ptr->op1_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[opline_ptr->op1.var].name), CG(active_op_array)->vars[opline_ptr->op1.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; COPY_NODE(opline_ptr->op1, opline.result); zend_llist_prepend_element(fetch_list_ptr, &opline); } else { if (opline_ptr->op1_type == IS_CONST) { GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op1.constant); } if (class_node.op_type == IS_CONST) { opline_ptr->op2_type = IS_CONST; opline_ptr->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline_ptr->op2, &class_node); } opline_ptr->extended_value |= ZEND_FETCH_STATIC_MEMBER; } } } /* }}} */ void fetch_array_begin(znode *result, znode *varname, znode *first_dim TSRMLS_DC) /* {{{ */ { fetch_simple_variable(result, varname, 1 TSRMLS_CC); fetch_array_dim(result, result, first_dim TSRMLS_CC); } /* }}} */ void fetch_array_dim(znode *result, const znode *parent, const znode *dim TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (zend_is_function_or_method_call(parent)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, parent); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_DIM_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, parent); SET_NODE(opline.op2, dim); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline.op2.constant)), Z_STRLEN(CONSTANT(opline.op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline.op2.constant)); ZVAL_LONG(&CONSTANT(opline.op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline.op2.constant); } } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void fetch_string_offset(znode *result, const znode *parent, const znode *offset TSRMLS_DC) /* {{{ */ { fetch_array_dim(result, parent, offset TSRMLS_CC); } /* }}} */ void zend_do_print(znode *result, const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->opcode = ZEND_PRINT; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_echo(const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ECHO; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_abstract_method(const znode *function_name, znode *modifiers, const znode *body TSRMLS_DC) /* {{{ */ { char *method_type; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { Z_LVAL(modifiers->u.constant) |= ZEND_ACC_ABSTRACT; method_type = "Interface"; } else { method_type = "Abstract"; } if (modifiers->u.constant.value.lval & ZEND_ACC_ABSTRACT) { if(modifiers->u.constant.value.lval & ZEND_ACC_PRIVATE) { zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot be declared private", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } if (Z_LVAL(body->u.constant) == ZEND_ACC_ABSTRACT) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_RAISE_ABSTRACT_ERROR; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } else { /* we had code in the function body */ zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot contain body", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } else { if (body->u.constant.value.lval == ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Non-abstract method %s::%s() must contain body", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } } /* }}} */ static zend_bool opline_is_fetch_this(const zend_op *opline TSRMLS_DC) /* {{{ */ { if ((opline->opcode == ZEND_FETCH_W) && (opline->op1_type == IS_CONST) && (Z_TYPE(CONSTANT(opline->op1.constant)) == IS_STRING) && (Z_HASH_P(&CONSTANT(opline->op1.constant)) == THIS_HASHVAL) && (Z_STRLEN(CONSTANT(opline->op1.constant)) == (sizeof("this")-1)) && !memcmp(Z_STRVAL(CONSTANT(opline->op1.constant)), "this", sizeof("this"))) { return 1; } else { return 0; } } /* }}} */ void zend_do_assign(znode *result, znode *variable, znode *value TSRMLS_DC) /* {{{ */ { int last_op_number; zend_op *opline; if (value->op_type == IS_CV) { zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (fetch_list_ptr && fetch_list_ptr->head) { opline = (zend_op *)fetch_list_ptr->head->data; if (opline->opcode == ZEND_FETCH_DIM_W && opline->op1_type == IS_CV && opline->op1.var == value->u.op.var) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_R; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->op1_type = IS_CONST; LITERAL_STRINGL(opline->op1, CG(active_op_array)->vars[value->u.op.var].name, CG(active_op_array)->vars[value->u.op.var].name_len, 1); CALCULATE_LITERAL_HASH(opline->op1.constant); SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_LOCAL; GET_NODE(value, opline->result); } } } zend_do_end_variable_parse(variable, BP_VAR_W, 0 TSRMLS_CC); last_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (variable->op_type == IS_CV) { if (variable->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (variable->op_type == IS_VAR) { int n = 0; while (last_op_number - n > 0) { zend_op *last_op; last_op = &CG(active_op_array)->opcodes[last_op_number-n-1]; if (last_op->result_type == IS_VAR && last_op->result.var == variable->u.op.var) { if (last_op->opcode == ZEND_FETCH_OBJ_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, value TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (last_op->opcode == ZEND_FETCH_DIM_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ /* TBFixed: this can realloc opcodes, leaving last_op pointing wrong */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_DIM; zend_do_op_data(opline, value TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (opline_is_fetch_this(last_op TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } else { break; } } n++; } } opline->opcode = ZEND_ASSIGN; SET_NODE(opline->op1, variable); SET_NODE(opline->op2, value); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_assign_ref(znode *result, const znode *lvar, const znode *rvar TSRMLS_DC) /* {{{ */ { zend_op *opline; if (lvar->op_type == IS_CV) { if (lvar->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (lvar->op_type == IS_VAR) { int last_op_number = get_next_op_number(CG(active_op_array)); if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline_is_fetch_this(opline TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ASSIGN_REF; if (zend_is_function_or_method_call(rvar)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } else if (rvar->EA & ZEND_PARSED_NEW) { opline->extended_value = ZEND_RETURNS_NEW; } else { opline->extended_value = 0; } if (result) { opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } else { opline->result_type = IS_UNUSED | EXT_TYPE_UNUSED; } SET_NODE(opline->op1, lvar); SET_NODE(opline->op2, rvar); } /* }}} */ static inline void do_begin_loop(TSRMLS_D) /* {{{ */ { zend_brk_cont_element *brk_cont_element; int parent; parent = CG(context).current_brk_cont; CG(context).current_brk_cont = CG(active_op_array)->last_brk_cont; brk_cont_element = get_next_brk_cont_element(CG(active_op_array)); brk_cont_element->start = get_next_op_number(CG(active_op_array)); brk_cont_element->parent = parent; } /* }}} */ static inline void do_end_loop(int cont_addr, int has_loop_var TSRMLS_DC) /* {{{ */ { if (!has_loop_var) { /* The start fileld is used to free temporary variables in case of exceptions. * We won't try to free something of we don't have loop variable. */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].start = -1; } CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = cont_addr; CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; } /* }}} */ void zend_do_while_cond(const znode *expr, znode *close_bracket_token TSRMLS_DC) /* {{{ */ { int while_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, expr); close_bracket_token->u.op.opline_num = while_cond_op_number; SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_while_end(const znode *while_token, const znode *close_bracket_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* add unconditional jump */ opline->opcode = ZEND_JMP; opline->op1.opline_num = while_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* update while's conditional jmp */ CG(active_op_array)->opcodes[close_bracket_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); do_end_loop(while_token->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_cond(const znode *expr, znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { int for_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZNZ; SET_NODE(opline->op1, expr); /* the conditional expression */ second_semicolon_token->u.op.opline_num = for_cond_op_number; SET_UNUSED(opline->op2); } /* }}} */ void zend_do_for_before_statement(const znode *cond_start, const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = cond_start->u.op.opline_num; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_end(const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = second_semicolon_token->u.op.opline_num+1; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_end_loop(second_semicolon_token->u.op.opline_num+1, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_pre_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_PRE_INC)?ZEND_PRE_INC_OBJ:ZEND_PRE_DEC_OBJ; last_op->result_type = IS_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_post_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_POST_INC)?ZEND_POST_INC_OBJ:ZEND_POST_DEC_OBJ; last_op->result_type = IS_TMP_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_if_cond(const znode *cond, znode *closing_bracket_token TSRMLS_DC) /* {{{ */ { int if_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); closing_bracket_token->u.op.opline_num = if_cond_op_number; SET_UNUSED(opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_if_after_statement(const znode *closing_bracket_token, unsigned char initialize TSRMLS_DC) /* {{{ */ { int if_end_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; /* save for backpatching */ if (initialize) { zend_llist jmp_list; zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); } zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &if_end_op_number); CG(active_op_array)->opcodes[closing_bracket_token->u.op.opline_num].op2.opline_num = if_end_op_number+1; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_if_end(TSRMLS_D) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_llist *jmp_list_ptr; zend_llist_element *le; zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); for (le=jmp_list_ptr->head; le; le = le->next) { CG(active_op_array)->opcodes[*((int *) le->data)].op1.opline_num = next_op_number; } zend_llist_destroy(jmp_list_ptr); zend_stack_del_top(&CG(bp_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_check_writable_variable(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; if (type & ZEND_PARSED_METHOD_CALL) { zend_error(E_COMPILE_ERROR, "Can't use method return value in write context"); } if (type == ZEND_PARSED_FUNCTION_CALL) { zend_error(E_COMPILE_ERROR, "Can't use function return value in write context"); } } /* }}} */ void zend_do_begin_variable_parse(TSRMLS_D) /* {{{ */ { zend_llist fetch_list; zend_llist_init(&fetch_list, sizeof(zend_op), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &fetch_list, sizeof(zend_llist)); } /* }}} */ void zend_do_end_variable_parse(znode *variable, int type, int arg_offset TSRMLS_DC) /* {{{ */ { zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline = NULL; zend_op *opline_ptr; zend_uint this_var = -1; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); le = fetch_list_ptr->head; /* TODO: $foo->x->y->z = 1 should fetch "x" and "y" for R or RW, not just W */ if (le) { opline_ptr = (zend_op *)le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { /* convert to FETCH_?(this) into IS_CV */ if (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE) { this_var = opline_ptr->result.var; if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), Z_STRVAL(CONSTANT(opline_ptr->op1.constant)), Z_STRLEN(CONSTANT(opline_ptr->op1.constant)), Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC); Z_TYPE(CONSTANT(opline_ptr->op1.constant)) = IS_NULL; } else { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); } le = le->next; if (variable->op_type == IS_VAR && variable->u.op.var == this_var) { variable->op_type = IS_CV; variable->u.op.var = CG(active_op_array)->this_var; } } else if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } while (le) { opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode == ZEND_SEPARATE) { if (type != BP_VAR_R && type != BP_VAR_IS) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); } le = le->next; continue; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); if (opline->op1_type == IS_VAR && opline->op1.var == this_var) { opline->op1_type = IS_CV; opline->op1.var = CG(active_op_array)->this_var; } switch (type) { case BP_VAR_R: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode -= 3; break; case BP_VAR_W: break; case BP_VAR_RW: opline->opcode += 3; break; case BP_VAR_IS: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode += 6; /* 3+3 */ break; case BP_VAR_FUNC_ARG: opline->opcode += 9; /* 3+3+3 */ opline->extended_value |= arg_offset; break; case BP_VAR_UNSET: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for unsetting"); } opline->opcode += 12; /* 3+3+3+3 */ break; } le = le->next; } if (opline && type == BP_VAR_W && arg_offset) { opline->extended_value |= ZEND_FETCH_MAKE_REF; } } zend_llist_destroy(fetch_list_ptr); zend_stack_del_top(&CG(bp_stack)); } /* }}} */ void zend_do_add_string(znode *result, const znode *op1, znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline; if (Z_STRLEN(op2->u.constant) > 1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_STRING; } else if (Z_STRLEN(op2->u.constant) == 1) { int ch = *Z_STRVAL(op2->u.constant); /* Free memory and use ZEND_ADD_CHAR in case of 1 character strings */ efree(Z_STRVAL(op2->u.constant)); ZVAL_LONG(&op2->u.constant, ch); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_CHAR; } else { /* String can be empty after a variable at the end of a heredoc */ efree(Z_STRVAL(op2->u.constant)); return; } if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_add_variable(znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_VAR; if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_free(znode *op1 TSRMLS_DC) /* {{{ */ { if (op1->op_type==IS_TMP_VAR) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else if (op1->op_type==IS_VAR) { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; while (opline->opcode == ZEND_END_SILENCE || opline->opcode == ZEND_EXT_FCALL_END || opline->opcode == ZEND_OP_DATA) { opline--; } if (opline->result_type == IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_FETCH_R || opline->opcode == ZEND_FETCH_DIM_R || opline->opcode == ZEND_FETCH_OBJ_R || opline->opcode == ZEND_QM_ASSIGN_VAR) { /* It's very rare and useless case. It's better to use additional FREE opcode and simplify the FETCH handlers their selves */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else { opline->result_type |= EXT_TYPE_UNUSED; } } else { while (opline>CG(active_op_array)->opcodes) { if (opline->opcode == ZEND_FETCH_DIM_R && opline->op1_type == IS_VAR && opline->op1.var == op1->u.op.var) { /* This should the end of a list() construct * Mark its result as unused */ opline->extended_value = ZEND_FETCH_STANDARD; break; } else if (opline->result_type==IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_NEW) { opline->result_type |= EXT_TYPE_UNUSED; } break; } opline--; } } } else if (op1->op_type == IS_CONST) { zval_dtor(&op1->u.constant); } } /* }}} */ int zend_do_verify_access_types(const znode *current_access_type, const znode *new_modifier) /* {{{ */ { if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_PPP_MASK) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Multiple access type modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_ABSTRACT) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Multiple abstract modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_STATIC) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Multiple static modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_FINAL) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Multiple final modifiers are not allowed"); } if (((Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)) & (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) == (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Cannot use the final modifier on an abstract class member"); } return (Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)); } /* }}} */ void zend_do_begin_function_declaration(znode *function_token, znode *function_name, int is_method, int return_reference, znode *fn_flags_znode TSRMLS_DC) /* {{{ */ { zend_op_array op_array; char *name = function_name->u.constant.value.str.val; int name_len = function_name->u.constant.value.str.len; int function_begin_line = function_token->u.op.opline_num; zend_uint fn_flags; const char *lcname; zend_bool orig_interactive; ALLOCA_FLAG(use_heap) if (is_method) { if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((Z_LVAL(fn_flags_znode->u.constant) & ~(ZEND_ACC_STATIC|ZEND_ACC_PUBLIC))) { zend_error(E_COMPILE_ERROR, "Access type for interface method %s::%s() must be omitted", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } Z_LVAL(fn_flags_znode->u.constant) |= ZEND_ACC_ABSTRACT; /* propagates to the rest of the parser */ } fn_flags = Z_LVAL(fn_flags_znode->u.constant); /* must be done *after* the above check */ } else { fn_flags = 0; } if ((fn_flags & ZEND_ACC_STATIC) && (fn_flags & ZEND_ACC_ABSTRACT) && !(CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_STRICT, "Static function %s%s%s() should not be abstract", is_method ? CG(active_class_entry)->name : "", is_method ? "::" : "", Z_STRVAL(function_name->u.constant)); } function_token->u.op_array = CG(active_op_array); orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(&op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; op_array.function_name = name; if (return_reference) { op_array.fn_flags |= ZEND_ACC_RETURN_REFERENCE; } op_array.fn_flags |= fn_flags; op_array.scope = is_method?CG(active_class_entry):NULL; op_array.prototype = NULL; op_array.line_start = zend_get_compiled_lineno(TSRMLS_C); if (is_method) { int result; lcname = zend_new_interned_string(zend_str_tolower_dup(name, name_len), name_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lcname)) { result = zend_hash_quick_add(&CG(active_class_entry)->function_table, lcname, name_len+1, INTERNED_HASH(lcname), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } else { result = zend_hash_add(&CG(active_class_entry)->function_table, lcname, name_len+1, &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } if (result == FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::%s()", CG(active_class_entry)->name, name); } zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); if (fn_flags & ZEND_ACC_ABSTRACT) { CG(active_class_entry)->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (!(fn_flags & ZEND_ACC_PPP_MASK)) { fn_flags |= ZEND_ACC_PUBLIC; } if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } } } else { char *class_lcname; class_lcname = do_alloca(CG(active_class_entry)->name_length + 1, use_heap); zend_str_tolower_copy(class_lcname, CG(active_class_entry)->name, CG(active_class_entry)->name_length); /* Improve after RC: cache the lowercase class name */ if ((CG(active_class_entry)->name_length == name_len) && ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT) && (!memcmp(class_lcname, lcname, name_len))) { if (!CG(active_class_entry)->constructor) { CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } } else if ((name_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)))) { if (CG(active_class_entry)->constructor) { zend_error(E_STRICT, "Redefining already defined constructor for class %s", CG(active_class_entry)->name); } CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1))) { CG(active_class_entry)->destructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1))) { CG(active_class_entry)->clone = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } CG(active_class_entry)->__call = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } CG(active_class_entry)->__callstatic = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } CG(active_class_entry)->__get = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } CG(active_class_entry)->__set = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } CG(active_class_entry)->__unset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } CG(active_class_entry)->__isset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } CG(active_class_entry)->__tostring = (zend_function *) CG(active_op_array); } else if (!(fn_flags & ZEND_ACC_STATIC)) { CG(active_op_array)->fn_flags |= ZEND_ACC_ALLOW_STATIC; } free_alloca(class_lcname, use_heap); } str_efree(lcname); } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zval key; if (CG(current_namespace)) { /* Prefix function name with current namespcae name */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, function_name TSRMLS_CC); op_array.function_name = Z_STRVAL(tmp.u.constant); name_len = Z_STRLEN(tmp.u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), name_len); } else { lcname = zend_str_tolower_dup(name, name_len); } opline->opcode = ZEND_DECLARE_FUNCTION; opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, name_len TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; LITERAL_STRINGL(opline->op2, lcname, name_len, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); opline->extended_value = ZEND_DECLARE_FUNCTION; zend_hash_quick_update(CG(function_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); } if (CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_NOP; opline->lineno = function_begin_line; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } { /* Push a seperator to the switch and foreach stacks */ zend_switch_entry switch_entry; switch_entry.cond.op_type = IS_UNUSED; switch_entry.default_case = 0; switch_entry.control_var = 0; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); { /* Foreach stack separator */ zend_op dummy_opline; dummy_opline.result_type = IS_UNUSED; dummy_opline.op1_type = IS_UNUSED; zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); } } if (CG(doc_comment)) { CG(active_op_array)->doc_comment = CG(doc_comment); CG(active_op_array)->doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_begin_lambda_function_declaration(znode *result, znode *function_token, int return_reference, int is_static TSRMLS_DC) /* {{{ */ { znode function_name; zend_op_array *current_op_array = CG(active_op_array); int current_op_number = get_next_op_number(CG(active_op_array)); zend_op *current_op; function_name.op_type = IS_CONST; ZVAL_STRINGL(&function_name.u.constant, "{closure}", sizeof("{closure}")-1, 1); zend_do_begin_function_declaration(function_token, &function_name, 0, return_reference, NULL TSRMLS_CC); result->op_type = IS_TMP_VAR; result->u.op.var = get_temporary_variable(current_op_array); current_op = &current_op_array->opcodes[current_op_number]; current_op->opcode = ZEND_DECLARE_LAMBDA_FUNCTION; zend_del_literal(current_op_array, current_op->op2.constant); SET_UNUSED(current_op->op2); SET_NODE(current_op->result, result); if (is_static) { CG(active_op_array)->fn_flags |= ZEND_ACC_STATIC; } CG(active_op_array)->fn_flags |= ZEND_ACC_CLOSURE; } /* }}} */ void zend_do_handle_exception(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_HANDLE_EXCEPTION; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_function_declaration(const znode *function_token TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; zend_do_extended_info(TSRMLS_C); zend_do_return(NULL, 0 TSRMLS_CC); pass_two(CG(active_op_array) TSRMLS_CC); zend_release_labels(TSRMLS_C); if (CG(active_class_entry)) { zend_check_magic_method_implementation(CG(active_class_entry), (zend_function*)CG(active_op_array), E_COMPILE_ERROR TSRMLS_CC); } else { /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(CG(active_op_array)->function_name); zend_str_tolower_copy(lcname, CG(active_op_array)->function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME)) && CG(active_op_array)->num_args != 1) { zend_error(E_COMPILE_ERROR, "%s() must take exactly 1 argument", ZEND_AUTOLOAD_FUNC_NAME); } } CG(active_op_array)->line_end = zend_get_compiled_lineno(TSRMLS_C); CG(active_op_array) = function_token->u.op_array; /* Pop the switch and foreach seperators */ zend_stack_del_top(&CG(switch_cond_stack)); zend_stack_del_top(&CG(foreach_copy_stack)); } /* }}} */ void zend_do_receive_arg(zend_uchar op, znode *varname, const znode *offset, const znode *initialization, znode *class_type, zend_uchar pass_by_reference TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_arg_info *cur_arg_info; znode var; if (class_type->op_type == IS_CONST && Z_TYPE(class_type->u.constant) == IS_STRING && Z_STRLEN(class_type->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_type->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } if (zend_is_auto_global_quick(Z_STRVAL(varname->u.constant), Z_STRLEN(varname->u.constant), 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign auto-global variable %s", Z_STRVAL(varname->u.constant)); } else { var.op_type = IS_CV; var.u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(varname->u.constant) = (char*)CG(active_op_array)->vars[var.u.op.var].name; var.EA = 0; if (CG(active_op_array)->vars[var.u.op.var].hash_value == THIS_HASHVAL && Z_STRLEN(varname->u.constant) == sizeof("this")-1 && !memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this")-1)) { if (CG(active_op_array)->scope && (CG(active_op_array)->fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } CG(active_op_array)->this_var = var.u.op.var; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->num_args++; opline->opcode = op; SET_NODE(opline->result, &var); SET_NODE(opline->op1, offset); if (op == ZEND_RECV_INIT) { SET_NODE(opline->op2, initialization); } else { CG(active_op_array)->required_num_args = CG(active_op_array)->num_args; SET_UNUSED(opline->op2); } CG(active_op_array)->arg_info = erealloc(CG(active_op_array)->arg_info, sizeof(zend_arg_info)*(CG(active_op_array)->num_args)); cur_arg_info = &CG(active_op_array)->arg_info[CG(active_op_array)->num_args-1]; cur_arg_info->name = zend_new_interned_string(estrndup(varname->u.constant.value.str.val, varname->u.constant.value.str.len), varname->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->name_len = varname->u.constant.value.str.len; cur_arg_info->type_hint = 0; cur_arg_info->allow_null = 1; cur_arg_info->pass_by_reference = pass_by_reference; cur_arg_info->class_name = NULL; cur_arg_info->class_name_len = 0; if (class_type->op_type != IS_UNUSED) { cur_arg_info->allow_null = 0; if (class_type->u.constant.type != IS_NULL) { if (class_type->u.constant.type == IS_ARRAY) { cur_arg_info->type_hint = IS_ARRAY; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else if (Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Default value for parameters with array type hint can only be an array or NULL"); } } } else if (class_type->u.constant.type == IS_CALLABLE) { cur_arg_info->type_hint = IS_CALLABLE; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with callable type hint can only be NULL"); } } } else { cur_arg_info->type_hint = IS_OBJECT; if (ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_type->u.constant), Z_STRLEN(class_type->u.constant))) { zend_resolve_class_name(class_type, opline->extended_value, 1 TSRMLS_CC); } Z_STRVAL(class_type->u.constant) = (char*)zend_new_interned_string(class_type->u.constant.value.str.val, class_type->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->class_name = class_type->u.constant.value.str.val; cur_arg_info->class_name_len = class_type->u.constant.value.str.len; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with a class type hint can only be NULL"); } } } } } } /* }}} */ int zend_do_begin_function_call(znode *function_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { zend_function *function; char *lcname; char *is_compound = memchr(Z_STRVAL(function_name->u.constant), '\\', Z_STRLEN(function_name->u.constant)); zend_resolve_non_class_name(function_name, check_namespace TSRMLS_CC); if (check_namespace && CG(current_namespace) && !is_compound) { /* We assume we call function from the current namespace if it is not prefixed. */ /* In run-time PHP will check for function with full name and internal function with short name */ zend_do_begin_dynamic_function_call(function_name, 1 TSRMLS_CC); return 1; } lcname = zend_str_tolower_dup(function_name->u.constant.value.str.val, function_name->u.constant.value.str.len); if ((zend_hash_find(CG(function_table), lcname, function_name->u.constant.value.str.len+1, (void **) &function)==FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_FUNCTIONS) && (function->type == ZEND_INTERNAL_FUNCTION))) { zend_do_begin_dynamic_function_call(function_name, 0 TSRMLS_CC); efree(lcname); return 1; /* Dynamic */ } efree(function_name->u.constant.value.str.val); function_name->u.constant.value.str.val = lcname; zend_stack_push(&CG(function_call_stack), (void *) &function, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 0; } /* }}} */ void zend_do_begin_method_call(znode *left_bracket TSRMLS_DC) /* {{{ */ { zend_op *last_op; int last_op_number; unsigned char *ptr = NULL; zend_do_end_variable_parse(left_bracket, BP_VAR_R, 0 TSRMLS_CC); zend_do_begin_variable_parse(TSRMLS_C); last_op_number = get_next_op_number(CG(active_op_array))-1; last_op = &CG(active_op_array)->opcodes[last_op_number]; if ((last_op->op2_type == IS_CONST) && (Z_TYPE(CONSTANT(last_op->op2.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(last_op->op2.constant)) == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !zend_binary_strcasecmp(Z_STRVAL(CONSTANT(last_op->op2.constant)), Z_STRLEN(CONSTANT(last_op->op2.constant)), ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1)) { zend_error(E_COMPILE_ERROR, "Cannot call __clone() method on objects - use 'clone $obj' instead"); } if (last_op->opcode == ZEND_FETCH_OBJ_R) { if (last_op->op2_type == IS_CONST) { zval name; name = CONSTANT(last_op->op2.constant); if (!IS_INTERNED(Z_STRVAL(name))) { Z_STRVAL(name) = estrndup(Z_STRVAL(name), Z_STRLEN(name)); } FREE_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); last_op->op2.constant = zend_add_func_name_literal(CG(active_op_array), &name TSRMLS_CC); GET_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); } last_op->opcode = ZEND_INIT_METHOD_CALL; SET_UNUSED(last_op->result); Z_LVAL(left_bracket->u.constant) = ZEND_INIT_FCALL_BY_NAME; } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (left_bracket->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &left_bracket->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, left_bracket); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_do_clone(znode *result, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CLONE; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_begin_dynamic_function_call(znode *function_name, int ns_call TSRMLS_DC) /* {{{ */ { unsigned char *ptr = NULL; zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (ns_call) { /* In run-time PHP will check for function with full name and internal function with short name */ opline->opcode = ZEND_INIT_NS_FCALL_BY_NAME; SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_ns_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (function_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, function_name); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_resolve_non_class_name(znode *element_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; int len; zval **ns; char *lcname, *compound = memchr(Z_STRVAL(element_name->u.constant), '\\', Z_STRLEN(element_name->u.constant)); if (Z_STRVAL(element_name->u.constant)[0] == '\\') { /* name starts with \ so it is known and unambiguos, nothing to do here but shorten it */ memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+1, Z_STRLEN(element_name->u.constant)); --Z_STRLEN(element_name->u.constant); return; } if(!check_namespace) { return; } if (compound && CG(current_import)) { len = compound - Z_STRVAL(element_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(element_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(element_name->u.constant) -= len; memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+len, Z_STRLEN(element_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, element_name TSRMLS_CC); *element_name = tmp; efree(lcname); return; } efree(lcname); } if (CG(current_namespace)) { tmp = *element_name; Z_STRLEN(tmp.u.constant) = sizeof("\\")-1 + Z_STRLEN(element_name->u.constant) + Z_STRLEN_P(CG(current_namespace)); Z_STRVAL(tmp.u.constant) = (char *) emalloc(Z_STRLEN(tmp.u.constant)+1); memcpy(Z_STRVAL(tmp.u.constant), Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace))]), "\\", sizeof("\\")-1); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace)) + sizeof("\\")-1]), Z_STRVAL(element_name->u.constant), Z_STRLEN(element_name->u.constant)+1); STR_FREE(Z_STRVAL(element_name->u.constant)); *element_name = tmp; } } /* }}} */ void zend_resolve_class_name(znode *class_name, ulong fetch_type, int check_ns_name TSRMLS_DC) /* {{{ */ { char *compound; char *lcname; zval **ns; znode tmp; int len; compound = memchr(Z_STRVAL(class_name->u.constant), '\\', Z_STRLEN(class_name->u.constant)); if (compound) { /* This is a compound class name that contains namespace prefix */ if (Z_STRVAL(class_name->u.constant)[0] == '\\') { /* The STRING name has "\" prefix */ Z_STRLEN(class_name->u.constant) -= 1; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+1, Z_STRLEN(class_name->u.constant)+1); Z_STRVAL(class_name->u.constant) = erealloc( Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1); if (ZEND_FETCH_CLASS_DEFAULT != zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "'\\%s' is an invalid class name", Z_STRVAL(class_name->u.constant)); } } else { if (CG(current_import)) { len = compound - Z_STRVAL(class_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(class_name->u.constant) -= len; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+len, Z_STRLEN(class_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; efree(lcname); return; } efree(lcname); } /* Here name is not prefixed with \ and not imported */ if (CG(current_namespace)) { tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } } } else if (CG(current_import) || CG(current_namespace)) { /* this is a plain name (without \) */ lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns) == SUCCESS) { /* The given name is an import name. Substitute it. */ zval_dtor(&class_name->u.constant); class_name->u.constant = **ns; zval_copy_ctor(&class_name->u.constant); } else if (CG(current_namespace)) { /* plain name, no import - prepend current namespace to it */ tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } efree(lcname); } } /* }}} */ void zend_do_fetch_class(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { long fetch_class_op_number; zend_op *opline; if (class_name->op_type == IS_CONST && Z_TYPE(class_name->u.constant) == IS_STRING && Z_STRLEN(class_name->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_name->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } fetch_class_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CLASS; SET_UNUSED(opline->op1); opline->extended_value = ZEND_FETCH_CLASS_GLOBAL; CG(catch_begin) = fetch_class_op_number; if (class_name->op_type == IS_CONST) { int fetch_type; fetch_type = zend_get_class_fetch_type(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); switch (fetch_type) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: SET_UNUSED(opline->op2); opline->extended_value = fetch_type; zval_dtor(&class_name->u.constant); break; default: zend_resolve_class_name(class_name, opline->extended_value, 0 TSRMLS_CC); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_name->u.constant TSRMLS_CC); break; } } else { SET_NODE(opline->op2, class_name); } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; /* FIXME: Hack so that INIT_FCALL_BY_NAME still knows this is a class */ GET_NODE(result, opline->result); result->EA = opline->extended_value; } /* }}} */ void zend_do_label(znode *label TSRMLS_DC) /* {{{ */ { zend_label dest; if (!CG(context).labels) { ALLOC_HASHTABLE(CG(context).labels); zend_hash_init(CG(context).labels, 4, NULL, NULL, 0); } dest.brk_cont = CG(context).current_brk_cont; dest.opline_num = get_next_op_number(CG(active_op_array)); if (zend_hash_add(CG(context).labels, Z_STRVAL(label->u.constant), Z_STRLEN(label->u.constant) + 1, (void**)&dest, sizeof(zend_label), NULL) == FAILURE) { zend_error(E_COMPILE_ERROR, "Label '%s' already defined", Z_STRVAL(label->u.constant)); } /* Done with label now */ zval_dtor(&label->u.constant); } /* }}} */ void zend_resolve_goto_label(zend_op_array *op_array, zend_op *opline, int pass2 TSRMLS_DC) /* {{{ */ { zend_label *dest; long current, distance; zval *label; if (pass2) { label = opline->op2.zv; } else { label = &CONSTANT_EX(op_array, opline->op2.constant); } if (CG(context).labels == NULL || zend_hash_find(CG(context).labels, Z_STRVAL_P(label), Z_STRLEN_P(label)+1, (void**)&dest) == FAILURE) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; zend_error(E_COMPILE_ERROR, "'goto' to undefined label '%s'", Z_STRVAL_P(label)); } else { /* Label is not defined. Delay to pass 2. */ INC_BPC(op_array); return; } } opline->op1.opline_num = dest->opline_num; zval_dtor(label); Z_TYPE_P(label) = IS_NULL; /* Check that we are not moving into loop or switch */ current = opline->extended_value; for (distance = 0; current != dest->brk_cont; distance++) { if (current == -1) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; } zend_error(E_COMPILE_ERROR, "'goto' into loop or switch statement is disallowed"); } current = op_array->brk_cont_array[current].parent; } if (distance == 0) { /* Nothing to break out of, optimize to ZEND_JMP */ opline->opcode = ZEND_JMP; opline->extended_value = 0; SET_UNUSED(opline->op2); } else { /* Set real break distance */ ZVAL_LONG(label, distance); } if (pass2) { DEC_BPC(op_array); } } /* }}} */ void zend_do_goto(const znode *label TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_GOTO; opline->extended_value = CG(context).current_brk_cont; SET_UNUSED(opline->op1); SET_NODE(opline->op2, label); zend_resolve_goto_label(CG(active_op_array), opline, 0 TSRMLS_CC); } /* }}} */ void zend_release_labels(TSRMLS_D) /* {{{ */ { if (CG(context).labels) { zend_hash_destroy(CG(context).labels); FREE_HASHTABLE(CG(context).labels); } if (!zend_stack_is_empty(&CG(context_stack))) { zend_compiler_context *ctx; zend_stack_top(&CG(context_stack), (void**)&ctx); CG(context) = *ctx; zend_stack_del_top(&CG(context_stack)); } } /* }}} */ void zend_do_build_full_name(znode *result, znode *prefix, znode *name, int is_class_member TSRMLS_DC) /* {{{ */ { zend_uint length; if (!result) { result = prefix; } else { *result = *prefix; } if (is_class_member) { length = sizeof("::")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "::", sizeof("::")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("::")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } else { length = sizeof("\\")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "\\", sizeof("\\")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("\\")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } } /* }}} */ int zend_do_begin_class_member_function_call(znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { znode class_node; unsigned char *ptr = NULL; zend_op *opline; if (method_name->op_type == IS_CONST) { char *lcname = zend_str_tolower_dup(Z_STRVAL(method_name->u.constant), Z_STRLEN(method_name->u.constant)); if ((sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == Z_STRLEN(method_name->u.constant) && memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == 0) { zval_dtor(&method_name->u.constant); method_name->op_type = IS_UNUSED; } efree(lcname); } if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; opline = get_next_op(CG(active_op_array) TSRMLS_CC); } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->extended_value = class_node.EA ; } opline->opcode = ZEND_INIT_STATIC_METHOD_CALL; if (class_node.op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, &class_node); } if (method_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &method_name->u.constant TSRMLS_CC); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } } else { SET_NODE(opline->op2, method_name); } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 1; /* Dynamic */ } /* }}} */ void zend_do_end_function_call(znode *function_name, znode *result, const znode *argument_list, int is_method, int is_dynamic_fcall TSRMLS_DC) /* {{{ */ { zend_op *opline; if (is_method && function_name && function_name->op_type == IS_UNUSED) { /* clone */ if (Z_LVAL(argument_list->u.constant) != 0) { zend_error(E_WARNING, "Clone method does not require arguments"); } opline = &CG(active_op_array)->opcodes[Z_LVAL(function_name->u.constant)]; } else { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (!is_method && !is_dynamic_fcall && function_name->op_type==IS_CONST) { opline->opcode = ZEND_DO_FCALL; SET_NODE(opline->op1, function_name); CALCULATE_LITERAL_HASH(opline->op1.constant); GET_CACHE_SLOT(opline->op1.constant); } else { opline->opcode = ZEND_DO_FCALL_BY_NAME; SET_UNUSED(opline->op1); } } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(result, opline->result) ; SET_UNUSED(opline->op2); zend_stack_del_top(&CG(function_call_stack)); opline->extended_value = Z_LVAL(argument_list->u.constant); } /* }}} */ void zend_do_pass_param(znode *param, zend_uchar op, int offset TSRMLS_DC) /* {{{ */ { zend_op *opline; int original_op=op; zend_function **function_ptr_ptr, *function_ptr; int send_by_reference; int send_function = 0; zend_stack_top(&CG(function_call_stack), (void **) &function_ptr_ptr); function_ptr = *function_ptr_ptr; if (original_op == ZEND_SEND_REF) { if (function_ptr && function_ptr->common.function_name && function_ptr->common.type == ZEND_USER_FUNCTION && !ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed; " "If you would like to pass argument by reference, modify the declaration of %s().", function_ptr->common.function_name); } else { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed"); } return; } if (function_ptr) { if (ARG_MAY_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { if (param->op_type & (IS_VAR|IS_CV) && original_op != ZEND_SEND_VAL) { send_by_reference = 1; if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION | ZEND_ARG_SEND_SILENT; } } else { op = ZEND_SEND_VAL; send_by_reference = 0; } } else { send_by_reference = ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset) ? ZEND_ARG_SEND_BY_REF : 0; } } else { send_by_reference = 0; } if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION; } else if (op == ZEND_SEND_VAL && (param->op_type & (IS_VAR|IS_CV))) { op = ZEND_SEND_VAR_NO_REF; } if (op!=ZEND_SEND_VAR_NO_REF && send_by_reference==ZEND_ARG_SEND_BY_REF) { /* change to passing by reference */ switch (param->op_type) { case IS_VAR: case IS_CV: op = ZEND_SEND_REF; break; default: zend_error(E_COMPILE_ERROR, "Only variables can be passed by reference"); break; } } if (original_op == ZEND_SEND_VAR) { switch (op) { case ZEND_SEND_VAR_NO_REF: zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); break; case ZEND_SEND_VAR: if (function_ptr) { zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(param, BP_VAR_FUNC_ARG, offset TSRMLS_CC); } break; case ZEND_SEND_REF: zend_do_end_variable_parse(param, BP_VAR_W, 0 TSRMLS_CC); break; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (op == ZEND_SEND_VAR_NO_REF) { if (function_ptr) { opline->extended_value = ZEND_ARG_COMPILE_TIME_BOUND | send_by_reference | send_function; } else { opline->extended_value = send_function; } } else { if (function_ptr) { opline->extended_value = ZEND_DO_FCALL; } else { opline->extended_value = ZEND_DO_FCALL_BY_NAME; } } opline->opcode = op; SET_NODE(opline->op1, param); opline->op2.opline_num = offset; SET_UNUSED(opline->op2); } /* }}} */ static int generate_free_switch_expr(const zend_switch_entry *switch_entry TSRMLS_DC) /* {{{ */ { zend_op *opline; if (switch_entry->cond.op_type != IS_VAR && switch_entry->cond.op_type != IS_TMP_VAR) { return (switch_entry->cond.op_type == IS_UNUSED); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry->cond); SET_UNUSED(opline->op2); opline->extended_value = 0; return 0; } /* }}} */ static int generate_free_foreach_copy(const zend_op *foreach_copy TSRMLS_DC) /* {{{ */ { zend_op *opline; /* If we reach the seperator then stop applying the stack */ if (foreach_copy->result_type == IS_UNUSED && foreach_copy->op1_type == IS_UNUSED) { return 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->result_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->result); SET_UNUSED(opline->op2); opline->extended_value = 1; if (foreach_copy->op1_type != IS_UNUSED) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->op1_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->op1); SET_UNUSED(opline->op2); opline->extended_value = 0; } return 0; } /* }}} */ void zend_do_return(znode *expr, int do_end_vparse TSRMLS_DC) /* {{{ */ { zend_op *opline; int start_op_number, end_op_number; if (do_end_vparse) { if ((CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) && !zend_is_function_or_method_call(expr)) { zend_do_end_variable_parse(expr, BP_VAR_W, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(expr, BP_VAR_R, 0 TSRMLS_CC); } } start_op_number = get_next_op_number(CG(active_op_array)); #ifdef ZTS zend_stack_apply_with_argument(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_switch_expr TSRMLS_CC); zend_stack_apply_with_argument(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_foreach_copy TSRMLS_CC); #else zend_stack_apply(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_switch_expr); zend_stack_apply(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_foreach_copy); #endif end_op_number = get_next_op_number(CG(active_op_array)); while (start_op_number < end_op_number) { CG(active_op_array)->opcodes[start_op_number].extended_value |= EXT_TYPE_FREE_ON_RETURN; start_op_number++; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) ? ZEND_RETURN_BY_REF : ZEND_RETURN; if (expr) { SET_NODE(opline->op1, expr); if (do_end_vparse && zend_is_function_or_method_call(expr)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } } else { opline->op1_type = IS_CONST; LITERAL_NULL(opline->op1); } SET_UNUSED(opline->op2); } /* }}} */ static int zend_add_try_element(zend_uint try_op TSRMLS_DC) /* {{{ */ { int try_catch_offset = CG(active_op_array)->last_try_catch++; CG(active_op_array)->try_catch_array = erealloc(CG(active_op_array)->try_catch_array, sizeof(zend_try_catch_element)*CG(active_op_array)->last_try_catch); CG(active_op_array)->try_catch_array[try_catch_offset].try_op = try_op; return try_catch_offset; } /* }}} */ static void zend_add_catch_element(int offset, zend_uint catch_op TSRMLS_DC) /* {{{ */ { CG(active_op_array)->try_catch_array[offset].catch_op = catch_op; } /* }}} */ void zend_do_first_catch(znode *open_parentheses TSRMLS_DC) /* {{{ */ { open_parentheses->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_initialize_try_catch_element(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist jmp_list; zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); zend_add_catch_element(try_token->u.op.opline_num, get_next_op_number(CG(active_op_array)) TSRMLS_CC); } /* }}} */ void zend_do_mark_last_catch(const znode *first_catch, const znode *last_additional_catch TSRMLS_DC) /* {{{ */ { CG(active_op_array)->last--; zend_do_if_end(TSRMLS_C); if (last_additional_catch->u.op.opline_num == -1) { CG(active_op_array)->opcodes[first_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[first_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } else { CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_try(znode *try_token TSRMLS_DC) /* {{{ */ { try_token->u.op.opline_num = zend_add_try_element(get_next_op_number(CG(active_op_array)) TSRMLS_CC); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_catch(znode *try_token, znode *class_name, znode *catch_var, znode *first_catch TSRMLS_DC) /* {{{ */ { long catch_op_number; zend_op *opline; znode catch_class; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); catch_class = *class_name; } else { zend_error(E_COMPILE_ERROR, "Bad class name in the catch statement"); } catch_op_number = get_next_op_number(CG(active_op_array)); if (first_catch) { first_catch->u.op.opline_num = catch_op_number; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CATCH; opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &catch_class.u.constant TSRMLS_CC); opline->op2_type = IS_CV; opline->op2.var = lookup_cv(CG(active_op_array), catch_var->u.constant.value.str.val, catch_var->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(catch_var->u.constant) = (char*)CG(active_op_array)->vars[opline->op2.var].name; opline->result.num = 0; /* 1 means it's the last catch in the block */ try_token->u.op.opline_num = catch_op_number; } /* }}} */ void zend_do_end_catch(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); CG(active_op_array)->opcodes[try_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_throw(const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_THROW; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); } /* }}} */ ZEND_API void function_add_ref(zend_function *function) /* {{{ */ { if (function->type == ZEND_USER_FUNCTION) { zend_op_array *op_array = &function->op_array; (*op_array->refcount)++; if (op_array->static_variables) { HashTable *static_variables = op_array->static_variables; zval *tmp_zval; ALLOC_HASHTABLE(op_array->static_variables); zend_hash_init(op_array->static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(op_array->static_variables, static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_zval, sizeof(zval *)); } op_array->run_time_cache = NULL; } } /* }}} */ static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */ { zend_function *function; if (!ce->parent) { return; } /* You cannot change create_object */ ce->create_object = ce->parent->create_object; /* Inherit special functions if needed */ if (!ce->get_iterator) { ce->get_iterator = ce->parent->get_iterator; } if (!ce->iterator_funcs.funcs) { ce->iterator_funcs.funcs = ce->parent->iterator_funcs.funcs; } if (!ce->__get) { ce->__get = ce->parent->__get; } if (!ce->__set) { ce->__set = ce->parent->__set; } if (!ce->__unset) { ce->__unset = ce->parent->__unset; } if (!ce->__isset) { ce->__isset = ce->parent->__isset; } if (!ce->__call) { ce->__call = ce->parent->__call; } if (!ce->__callstatic) { ce->__callstatic = ce->parent->__callstatic; } if (!ce->__tostring) { ce->__tostring = ce->parent->__tostring; } if (!ce->clone) { ce->clone = ce->parent->clone; } if(!ce->serialize) { ce->serialize = ce->parent->serialize; } if(!ce->unserialize) { ce->unserialize = ce->parent->unserialize; } if (!ce->destructor) { ce->destructor = ce->parent->destructor; } if (ce->constructor) { if (ce->parent->constructor && ce->parent->constructor->common.fn_flags & ZEND_ACC_FINAL) { zend_error(E_ERROR, "Cannot override final %s::%s() with %s::%s()", ce->parent->name, ce->parent->constructor->common.function_name, ce->name, ce->constructor->common.function_name ); } return; } if (zend_hash_find(&ce->parent->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), (void **)&function)==SUCCESS) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), function, sizeof(zend_function), NULL); function_add_ref(function); } else { /* Don't inherit the old style constructor if we already have the new style constructor */ char *lc_class_name; char *lc_parent_class_name; lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); if (!zend_hash_exists(&ce->function_table, lc_class_name, ce->name_length+1)) { lc_parent_class_name = zend_str_tolower_dup(ce->parent->name, ce->parent->name_length); if (!zend_hash_exists(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1) && zend_hash_find(&ce->parent->function_table, lc_parent_class_name, ce->parent->name_length+1, (void **)&function)==SUCCESS) { if (function->common.fn_flags & ZEND_ACC_CTOR) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1, function, sizeof(zend_function), NULL); function_add_ref(function); } } efree(lc_parent_class_name); } efree(lc_class_name); } ce->constructor = ce->parent->constructor; } /* }}} */ char *zend_visibility_string(zend_uint fn_flags) /* {{{ */ { if (fn_flags & ZEND_ACC_PRIVATE) { return "private"; } if (fn_flags & ZEND_ACC_PROTECTED) { return "protected"; } if (fn_flags & ZEND_ACC_PUBLIC) { return "public"; } return ""; } /* }}} */ static void do_inherit_method(zend_function *function) /* {{{ */ { /* The class entry of the derived function intentionally remains the same * as that of the parent class. That allows us to know in which context * we're running, and handle private method calls properly. */ function_add_ref(function); } /* }}} */ static zend_bool zend_do_perform_implementation_check(const zend_function *fe, const zend_function *proto TSRMLS_DC) /* {{{ */ { zend_uint i; /* If it's a user function then arg_info == NULL means we don't have any parameters but * we still need to do the arg number checks. We are only willing to ignore this for internal * functions because extensions don't always define arg_info. */ if (!proto || (!proto->common.arg_info && proto->common.type != ZEND_USER_FUNCTION)) { return 1; } /* Checks for constructors only if they are declared in an interface, * or explicitly marked as abstract */ if ((fe->common.fn_flags & ZEND_ACC_CTOR) && ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)) { return 1; } /* check number of arguments */ if (proto->common.required_num_args < fe->common.required_num_args || proto->common.num_args > fe->common.num_args) { return 0; } if (fe->common.type != ZEND_USER_FUNCTION && (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) != 0 && (fe->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) == 0) { return 0; } /* by-ref constraints on return values are covariant */ if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) { return 0; } for (i=0; i < proto->common.num_args; i++) { if (ZEND_LOG_XOR(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)) { /* Only one has a type hint and the other one doesn't */ return 0; } if (fe->common.arg_info[i].class_name && strcasecmp(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)!=0) { const char *colon; if (fe->common.type != ZEND_USER_FUNCTION) { return 0; } else if (strchr(proto->common.arg_info[i].class_name, '\\') != NULL || (colon = zend_memrchr(fe->common.arg_info[i].class_name, '\\', fe->common.arg_info[i].class_name_len)) == NULL || strcasecmp(colon+1, proto->common.arg_info[i].class_name) != 0) { zend_class_entry **fe_ce, **proto_ce; int found, found2; found = zend_lookup_class(fe->common.arg_info[i].class_name, fe->common.arg_info[i].class_name_len, &fe_ce TSRMLS_CC); found2 = zend_lookup_class(proto->common.arg_info[i].class_name, proto->common.arg_info[i].class_name_len, &proto_ce TSRMLS_CC); /* Check for class alias */ if (found != SUCCESS || found2 != SUCCESS || (*fe_ce)->type == ZEND_INTERNAL_CLASS || (*proto_ce)->type == ZEND_INTERNAL_CLASS || *fe_ce != *proto_ce) { return 0; } } } if (fe->common.arg_info[i].type_hint != proto->common.arg_info[i].type_hint) { /* Incompatible type hint */ return 0; } /* by-ref constraints on arguments are invariant */ if (fe->common.arg_info[i].pass_by_reference != proto->common.arg_info[i].pass_by_reference) { return 0; } } if (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) { for (i=proto->common.num_args; i < fe->common.num_args; i++) { if (!fe->common.arg_info[i].pass_by_reference) { return 0; } } } return 1; } /* }}} */ #define REALLOC_BUF_IF_EXCEED(buf, offset, length, size) \ if (UNEXPECTED(offset - buf + size >= length)) { \ length += size + 1; \ buf = erealloc(buf, length); \ } static char * zend_get_function_declaration(zend_function *fptr TSRMLS_DC) /* {{{ */ { char *offset, *buf; zend_uint length = 1024; offset = buf = (char *)emalloc(length * sizeof(char)); if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { *(offset++) = '&'; *(offset++) = ' '; } if (fptr->common.scope) { memcpy(offset, fptr->common.scope->name, fptr->common.scope->name_length); offset += fptr->common.scope->name_length; *(offset++) = ':'; *(offset++) = ':'; } { size_t name_len = strlen(fptr->common.function_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, name_len); memcpy(offset, fptr->common.function_name, name_len); offset += name_len; } *(offset++) = '('; if (fptr->common.arg_info) { zend_uint i, required; zend_arg_info *arg_info = fptr->common.arg_info; required = fptr->common.required_num_args; for (i = 0; i < fptr->common.num_args;) { if (arg_info->class_name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->class_name_len); memcpy(offset, arg_info->class_name, arg_info->class_name_len); offset += arg_info->class_name_len; *(offset++) = ' '; } else if (arg_info->type_hint) { zend_uint type_name_len; char *type_name = zend_get_type_by_const(arg_info->type_hint); type_name_len = strlen(type_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, type_name_len); memcpy(offset, type_name, type_name_len); offset += type_name_len; *(offset++) = ' '; } if (arg_info->pass_by_reference) { *(offset++) = '&'; } *(offset++) = '$'; if (arg_info->name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->name_len); memcpy(offset, arg_info->name, arg_info->name_len); offset += arg_info->name_len; } else { zend_uint idx = i; memcpy(offset, "param", 5); offset += 5; do { *(offset++) = (char) (idx % 10) + '0'; idx /= 10; } while (idx > 0); } if (i >= required) { *(offset++) = ' '; *(offset++) = '='; *(offset++) = ' '; if (fptr->type == ZEND_USER_FUNCTION) { zend_op *precv = NULL; { zend_uint idx = i; zend_op *op = ((zend_op_array *)fptr)->opcodes; zend_op *end = op + ((zend_op_array *)fptr)->last; ++idx; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT) && op->op1.num == (long)idx) { precv = op; } ++op; } } if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) { zval *zv, zv_copy; int use_copy; ALLOC_ZVAL(zv); *zv = *precv->op2.zv; zval_copy_ctor(zv); INIT_PZVAL(zv); zval_update_constant_ex(&zv, (void*)1, fptr->common.scope TSRMLS_CC); if (Z_TYPE_P(zv) == IS_BOOL) { if (Z_LVAL_P(zv)) { memcpy(offset, "true", 4); offset += 4; } else { memcpy(offset, "false", 5); offset += 5; } } else if (Z_TYPE_P(zv) == IS_NULL) { memcpy(offset, "NULL", 4); offset += 4; } else if (Z_TYPE_P(zv) == IS_STRING) { *(offset++) = '\''; REALLOC_BUF_IF_EXCEED(buf, offset, length, MIN(Z_STRLEN_P(zv), 10)); memcpy(offset, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 10)); offset += MIN(Z_STRLEN_P(zv), 10); if (Z_STRLEN_P(zv) > 10) { *(offset++) = '.'; *(offset++) = '.'; *(offset++) = '.'; } *(offset++) = '\''; } else if (Z_TYPE_P(zv) == IS_ARRAY) { memcpy(offset, "Array", 5); offset += 5; } else { zend_make_printable_zval(zv, &zv_copy, &use_copy); REALLOC_BUF_IF_EXCEED(buf, offset, length, Z_STRLEN(zv_copy)); memcpy(offset, Z_STRVAL(zv_copy), Z_STRLEN(zv_copy)); offset += Z_STRLEN(zv_copy); if (use_copy) { zval_dtor(&zv_copy); } } zval_ptr_dtor(&zv); } } else { memcpy(offset, "NULL", 4); offset += 4; } } if (++i < fptr->common.num_args) { *(offset++) = ','; *(offset++) = ' '; } arg_info++; REALLOC_BUF_IF_EXCEED(buf, offset, length, 32); } } *(offset++) = ')'; *offset = '\0'; return buf; } /* }}} */ static void do_inheritance_check_on_method(zend_function *child, zend_function *parent TSRMLS_DC) /* {{{ */ { zend_uint child_flags; zend_uint parent_flags = parent->common.fn_flags; if (parent->common.fn_flags & ZEND_ACC_ABSTRACT && parent->common.scope != (child->common.prototype ? child->common.prototype->common.scope : child->common.scope) && child->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_IMPLEMENTED_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Can't inherit abstract function %s::%s() (previously declared abstract in %s)", parent->common.scope->name, child->common.function_name, child->common.prototype ? child->common.prototype->common.scope->name : child->common.scope->name); } if (parent_flags & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot override final method %s::%s()", ZEND_FN_SCOPE_NAME(parent), child->common.function_name); } child_flags = child->common.fn_flags; /* You cannot change from static to non static and vice versa. */ if ((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC)) { if (child->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot make non static method %s::%s() static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } else { zend_error(E_COMPILE_ERROR, "Cannot make static method %s::%s() non static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } } /* Disallow making an inherited method abstract. */ if ((child_flags & ZEND_ACC_ABSTRACT) && !(parent_flags & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Cannot make non abstract method %s::%s() abstract in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } if (parent_flags & ZEND_ACC_CHANGED) { child->common.fn_flags |= ZEND_ACC_CHANGED; } else { /* Prevent derived classes from restricting access that was available in parent classes */ if ((child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::%s() must be %s (as in class %s)%s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if (((child_flags & ZEND_ACC_PPP_MASK) < (parent_flags & ZEND_ACC_PPP_MASK)) && ((parent_flags & ZEND_ACC_PPP_MASK) & ZEND_ACC_PRIVATE)) { child->common.fn_flags |= ZEND_ACC_CHANGED; } } if (parent_flags & ZEND_ACC_PRIVATE) { child->common.prototype = NULL; } else if (parent_flags & ZEND_ACC_ABSTRACT) { child->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; child->common.prototype = parent; } else if (!(parent->common.fn_flags & ZEND_ACC_CTOR) || (parent->common.prototype && (parent->common.prototype->common.scope->ce_flags & ZEND_ACC_INTERFACE))) { /* ctors only have a prototype if it comes from an interface */ child->common.prototype = parent->common.prototype ? parent->common.prototype : parent; } if (child->common.prototype && (child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { if (!zend_do_perform_implementation_check(child, child->common.prototype TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s::%s() must be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_get_function_declaration(child->common.prototype TSRMLS_CC)); } } else if (EG(error_reporting) & E_STRICT || EG(user_error_handler)) { /* Check E_STRICT (or custom error handler) before the check so that we save some time */ if (!zend_do_perform_implementation_check(child, parent TSRMLS_CC)) { char *method_prototype = zend_get_function_declaration(child->common.prototype TSRMLS_CC); zend_error(E_STRICT, "Declaration of %s::%s() should be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, method_prototype); efree(method_prototype); } } } /* }}} */ static zend_bool do_inherit_method_check(HashTable *child_function_table, zend_function *parent, const zend_hash_key *hash_key, zend_class_entry *child_ce) /* {{{ */ { zend_uint parent_flags = parent->common.fn_flags; zend_function *child; TSRMLS_FETCH(); if (zend_hash_quick_find(child_function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child)==FAILURE) { if (parent_flags & (ZEND_ACC_ABSTRACT)) { child_ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } return 1; /* method doesn't exist in child, copy from parent */ } do_inheritance_check_on_method(child, parent TSRMLS_CC); return 0; } /* }}} */ static zend_bool do_inherit_property_access_check(HashTable *target_ht, zend_property_info *parent_info, const zend_hash_key *hash_key, zend_class_entry *ce) /* {{{ */ { zend_property_info *child_info; zend_class_entry *parent_ce = ce->parent; if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW)) { if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { child_info->flags |= ZEND_ACC_CHANGED; } else { zend_hash_quick_update(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, parent_info, sizeof(zend_property_info), (void **) &child_info); if(ce->type & ZEND_INTERNAL_CLASS) { zend_duplicate_property_info_internal(child_info); } else { zend_duplicate_property_info(child_info); } child_info->flags &= ~ZEND_ACC_PRIVATE; /* it's not private anymore */ child_info->flags |= ZEND_ACC_SHADOW; /* but it's a shadow of private */ } return 0; /* don't copy access information to child */ } if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { if ((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s", (parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", parent_ce->name, hash_key->arKey, (child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ce->name, hash_key->arKey); } if(parent_info->flags & ZEND_ACC_CHANGED) { child_info->flags |= ZEND_ACC_CHANGED; } if ((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ce->name, hash_key->arKey, zend_visibility_string(parent_info->flags), parent_ce->name, (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if ((child_info->flags & ZEND_ACC_STATIC) == 0) { Z_DELREF_P(ce->default_properties_table[parent_info->offset]); ce->default_properties_table[parent_info->offset] = ce->default_properties_table[child_info->offset]; ce->default_properties_table[child_info->offset] = NULL; child_info->offset = parent_info->offset; } return 0; /* Don't copy from parent */ } else { return 1; /* Copy from parent */ } } /* }}} */ static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce TSRMLS_CC) == FAILURE) { zend_error(E_CORE_ERROR, "Class %s could not implement interface %s", ce->name, iface->name); } if (ce == iface) { zend_error(E_ERROR, "Interface %s cannot implement itself", ce->name); } } /* }}} */ ZEND_API void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface TSRMLS_DC) /* {{{ */ { /* expects interface to be contained in ce's interface list already */ zend_uint i, ce_num, if_num = iface->num_interfaces; zend_class_entry *entry; if (if_num==0) { return; } ce_num = ce->num_interfaces; if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } /* Inherit the interfaces, only if they're not already inherited by the class */ while (if_num--) { entry = iface->interfaces[if_num]; for (i = 0; i < ce_num; i++) { if (ce->interfaces[i] == entry) { break; } } if (i == ce_num) { ce->interfaces[ce->num_interfaces++] = entry; } } /* and now call the implementing handlers */ while (ce_num < ce->num_interfaces) { do_implement_interface(ce, ce->interfaces[ce_num++] TSRMLS_CC); } } /* }}} */ #ifdef ZTS static void zval_internal_ctor(zval **p) /* {{{ */ { zval *orig_ptr = *p; ALLOC_ZVAL(*p); MAKE_COPY_ZVAL(&orig_ptr, *p); } /* }}} */ # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) (((parent_ce)->type != (ce)->type) ? zval_internal_ctor : zval_add_ref)) #else # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) zval_add_ref) #endif ZEND_API void zend_do_inheritance(zend_class_entry *ce, zend_class_entry *parent_ce TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; if ((ce->ce_flags & ZEND_ACC_INTERFACE) && !(parent_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ce->name, parent_ce->name); } if (parent_ce->ce_flags & ZEND_ACC_FINAL_CLASS) { zend_error(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ce->name, parent_ce->name); } ce->parent = parent_ce; /* Copy serialize/unserialize callbacks */ if (!ce->serialize) { ce->serialize = parent_ce->serialize; } if (!ce->unserialize) { ce->unserialize = parent_ce->unserialize; } /* Inherit interfaces */ zend_do_inherit_interfaces(ce, parent_ce TSRMLS_CC); /* Inherit properties */ if (parent_ce->default_properties_count) { int i = ce->default_properties_count + parent_ce->default_properties_count; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_properties_count) { while (i-- > parent_ce->default_properties_count) { ce->default_properties_table[i] = ce->default_properties_table[i - parent_ce->default_properties_count]; } } for (i = 0; i < parent_ce->default_properties_count; i++) { ce->default_properties_table[i] = parent_ce->default_properties_table[i]; if (ce->default_properties_table[i]) { #ifdef ZTS if (parent_ce->type != ce->type) { zval *p; ALLOC_ZVAL(p); MAKE_COPY_ZVAL(&ce->default_properties_table[i], p); ce->default_properties_table[i] = p; } else { Z_ADDREF_P(ce->default_properties_table[i]); } #else Z_ADDREF_P(ce->default_properties_table[i]); #endif } } ce->default_properties_count += parent_ce->default_properties_count; } if (parent_ce->type != ce->type) { /* User class extends internal class */ zend_update_class_constants(parent_ce TSRMLS_CC); if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = erealloc(ce->default_static_members_table, sizeof(void*) * i); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&CE_STATIC_MEMBERS(parent_ce)[i]); ce->default_static_members_table[i] = CE_STATIC_MEMBERS(parent_ce)[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; ce->static_members_table = ce->default_static_members_table; } } else { if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&parent_ce->default_static_members_table[i]); ce->default_static_members_table[i] = parent_ce->default_static_members_table[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } } for (zend_hash_internal_pointer_reset(&ce->properties_info); zend_hash_get_current_data(&ce->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->properties_info)) { if (property_info->ce == ce) { if (property_info->flags & ZEND_ACC_STATIC) { property_info->offset += parent_ce->default_static_members_count; } else { property_info->offset += parent_ce->default_properties_count; } } } zend_hash_merge_ex(&ce->properties_info, &parent_ce->properties_info, (copy_ctor_func_t) (ce->type & ZEND_INTERNAL_CLASS ? zend_duplicate_property_info_internal : zend_duplicate_property_info), sizeof(zend_property_info), (merge_checker_func_t) do_inherit_property_access_check, ce); zend_hash_merge(&ce->constants_table, &parent_ce->constants_table, zval_property_ctor(parent_ce, ce), NULL, sizeof(zval *), 0); zend_hash_merge_ex(&ce->function_table, &parent_ce->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_inherit_parent_constructor(ce); if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS && ce->type == ZEND_INTERNAL_CLASS) { ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } else if (!(ce->ce_flags & ZEND_ACC_IMPLEMENT_INTERFACES) && !(ce->ce_flags & ZEND_ACC_IMPLEMENT_TRAITS)) { /* The verification will be done in runtime by ZEND_VERIFY_ABSTRACT_CLASS */ zend_verify_abstract_class(ce TSRMLS_CC); } ce->ce_flags |= parent_ce->ce_flags & ZEND_HAS_STATIC_IN_METHODS; } /* }}} */ static zend_bool do_inherit_constant_check(HashTable *child_constants_table, const zval **parent_constant, const zend_hash_key *hash_key, const zend_class_entry *iface) /* {{{ */ { zval **old_constant; if (zend_hash_quick_find(child_constants_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**)&old_constant) == SUCCESS) { if (*old_constant != *parent_constant) { zend_error(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", hash_key->arKey, iface->name); } return 0; } return 1; } /* }}} */ static int do_interface_constant_check(zval **val TSRMLS_DC, int num_args, va_list args, const zend_hash_key *key) /* {{{ */ { zend_class_entry **iface = va_arg(args, zend_class_entry**); do_inherit_constant_check(&(*iface)->constants_table, (const zval **) val, key, *iface); return ZEND_HASH_APPLY_KEEP; } /* }}} */ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_iface_num = ce->num_interfaces; zend_uint parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0; for (i = 0; i < ce->num_interfaces; i++) { if (ce->interfaces[i] == NULL) { memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i)); i--; } else if (ce->interfaces[i] == iface) { if (i < parent_iface_num) { ignore = 1; } else { zend_error(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ce->name, iface->name); } } } if (ignore) { /* Check for attempt to redeclare interface constants */ zend_hash_apply_with_arguments(&ce->constants_table TSRMLS_CC, (apply_func_args_t) do_interface_constant_check, 1, &iface); } else { if (ce->num_interfaces >= current_iface_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } } ce->interfaces[ce->num_interfaces++] = iface; zend_hash_merge_ex(&ce->constants_table, &iface->constants_table, (copy_ctor_func_t) zval_add_ref, sizeof(zval *), (merge_checker_func_t) do_inherit_constant_check, iface); zend_hash_merge_ex(&ce->function_table, &iface->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_implement_interface(ce, iface TSRMLS_CC); zend_do_inherit_interfaces(ce, iface TSRMLS_CC); } } /* }}} */ ZEND_API void zend_do_implement_trait(zend_class_entry *ce, zend_class_entry *trait TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_trait_num = ce->num_traits; zend_uint parent_trait_num = ce->parent ? ce->parent->num_traits : 0; for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == NULL) { memmove(ce->traits + i, ce->traits + i + 1, sizeof(zend_class_entry*) * (--ce->num_traits - i)); i--; } else if (ce->traits[i] == trait) { if (i < parent_trait_num) { ignore = 1; } } } if (!ignore) { if (ce->num_traits >= current_trait_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->traits = (zend_class_entry **) realloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } else { ce->traits = (zend_class_entry **) erealloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } } ce->traits[ce->num_traits++] = trait; } } /* }}} */ static int zend_traits_merge_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { size_t current; size_t i; size_t count; HashTable* resulting_table; HashTable** function_tables; zend_class_entry *ce; size_t collision = 0; size_t abstract_solved = 0; zend_function* other_trait_fn; current = va_arg(args, size_t); /* index of current trait */ count = va_arg(args, size_t); resulting_table = va_arg(args, HashTable*); function_tables = va_arg(args, HashTable**); ce = va_arg(args, zend_class_entry*); for (i = 0; i < count; i++) { if (i == current) { continue; /* just skip this, cause its the table this function is applied on */ } if (zend_hash_quick_find(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&other_trait_fn) == SUCCESS) { /* if it is an abstract method, there is no collision */ if (other_trait_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* we can savely free and remove it from other table */ zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } else { /* if it is not an abstract method, there is still no collision */ /* if fn is an abstract method */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* just mark as solved, will be added if its own trait is processed */ abstract_solved = 1; } else { /* but else, we have a collision of non-abstract methods */ collision++; zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } } } if (collision) { zend_function* class_fn; /* make sure method is not already overridden in class */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&class_fn) == FAILURE || class_fn->common.scope != ce) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because there are collisions with other trait methods on %s", fn->common.function_name, ce->name); } zend_function_dtor(fn); } else if (abstract_solved) { zend_function_dtor(fn); } else { /* Add it to result function table */ if (zend_hash_quick_add(resulting_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, fn, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating resulting trait method table", fn->common.function_name); } } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ /* {{{ Originates from php_runkit_function_copy_ctor Duplicate structures in an op_array where necessary to make an outright duplicate */ static void zend_traits_duplicate_function(zend_function *fe, zend_class_entry *target_ce, char *newname TSRMLS_DC) { zend_literal *literals_copy; zend_compiled_variable *dupvars; zend_op *opcode_copy; zval class_name_zv; int class_name_literal; int i; int number_of_literals; if (fe->op_array.static_variables) { HashTable *tmpHash; ALLOC_HASHTABLE(tmpHash); zend_hash_init(tmpHash, zend_hash_num_elements(fe->op_array.static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_apply_with_arguments(fe->op_array.static_variables TSRMLS_CC, (apply_func_args_t)zval_copy_static_var, 1, tmpHash); fe->op_array.static_variables = tmpHash; } number_of_literals = fe->op_array.last_literal; literals_copy = (zend_literal*)emalloc(number_of_literals * sizeof(zend_literal)); for (i = 0; i < number_of_literals; i++) { literals_copy[i] = fe->op_array.literals[i]; zval_copy_ctor(&literals_copy[i].constant); } fe->op_array.literals = literals_copy; fe->op_array.refcount = emalloc(sizeof(zend_uint)); *(fe->op_array.refcount) = 1; if (fe->op_array.vars) { i = fe->op_array.last_var; dupvars = safe_emalloc(fe->op_array.last_var, sizeof(zend_compiled_variable), 0); while (i > 0) { i--; dupvars[i].name = estrndup(fe->op_array.vars[i].name, fe->op_array.vars[i].name_len); dupvars[i].name_len = fe->op_array.vars[i].name_len; dupvars[i].hash_value = fe->op_array.vars[i].hash_value; } fe->op_array.vars = dupvars; } else { fe->op_array.vars = NULL; } opcode_copy = safe_emalloc(sizeof(zend_op), fe->op_array.last, 0); for(i = 0; i < fe->op_array.last; i++) { opcode_copy[i] = fe->op_array.opcodes[i]; if (opcode_copy[i].op1_type != IS_CONST) { if (opcode_copy[i].op1.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op1.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op1.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op1.jmp_addr - fe->op_array.opcodes); } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op1.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op1.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op1.zv = &fe->op_array.literals[class_name_literal].constant; } } if (opcode_copy[i].op2_type != IS_CONST) { if (opcode_copy[i].op2.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op2.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op2.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op2.jmp_addr - fe->op_array.opcodes); } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op2.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op2.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op2.zv = &fe->op_array.literals[class_name_literal].constant; } } } fe->op_array.opcodes = opcode_copy; fe->op_array.function_name = newname; /* was setting it to fe which does not work since fe is stack allocated and not a stable address */ /* fe->op_array.prototype = fe->op_array.prototype; */ if (fe->op_array.arg_info) { zend_arg_info *tmpArginfo; tmpArginfo = safe_emalloc(sizeof(zend_arg_info), fe->op_array.num_args, 0); for(i = 0; i < fe->op_array.num_args; i++) { tmpArginfo[i] = fe->op_array.arg_info[i]; tmpArginfo[i].name = estrndup(tmpArginfo[i].name, tmpArginfo[i].name_len); if (tmpArginfo[i].class_name) { tmpArginfo[i].class_name = estrndup(tmpArginfo[i].class_name, tmpArginfo[i].class_name_len); } } fe->op_array.arg_info = tmpArginfo; } fe->op_array.doc_comment = estrndup(fe->op_array.doc_comment, fe->op_array.doc_comment_len); fe->op_array.try_catch_array = (zend_try_catch_element*)estrndup((char*)fe->op_array.try_catch_array, sizeof(zend_try_catch_element) * fe->op_array.last_try_catch); fe->op_array.brk_cont_array = (zend_brk_cont_element*)estrndup((char*)fe->op_array.brk_cont_array, sizeof(zend_brk_cont_element) * fe->op_array.last_brk_cont); } /* }}} */ static void zend_add_magic_methods(zend_class_entry* ce, const char* mname, uint mname_len, zend_function* fe TSRMLS_DC) { if ( !strncmp(mname, ZEND_CLONE_FUNC_NAME, mname_len)) { ce->clone = fe; fe->common.fn_flags |= ZEND_ACC_CLONE; } else if (!strncmp(mname, ZEND_CONSTRUCTOR_FUNC_NAME, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } else if (!strncmp(mname, ZEND_DESTRUCTOR_FUNC_NAME, mname_len)) { ce->destructor = fe; fe->common.fn_flags |= ZEND_ACC_DTOR; } else if (!strncmp(mname, ZEND_GET_FUNC_NAME, mname_len)) ce->__get = fe; else if (!strncmp(mname, ZEND_SET_FUNC_NAME, mname_len)) ce->__set = fe; else if (!strncmp(mname, ZEND_CALL_FUNC_NAME, mname_len)) ce->__call = fe; else if (!strncmp(mname, ZEND_UNSET_FUNC_NAME, mname_len)) ce->__unset = fe; else if (!strncmp(mname, ZEND_ISSET_FUNC_NAME, mname_len)) ce->__isset = fe; else if (!strncmp(mname, ZEND_CALLSTATIC_FUNC_NAME, mname_len)) ce->__callstatic= fe; else if (!strncmp(mname, ZEND_TOSTRING_FUNC_NAME, mname_len)) ce->__tostring = fe; else if (ce->name_length + 1 == mname_len) { char *lowercase_name = emalloc(ce->name_length + 1); zend_str_tolower_copy(lowercase_name, ce->name, ce->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, ce->name_length + 1, 1 TSRMLS_CC); if (!memcmp(mname, lowercase_name, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } str_efree(lowercase_name); } } static int zend_traits_merge_functions_to_class(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zend_class_entry *ce = va_arg(args, zend_class_entry*); int add = 0; zend_function* existing_fn; zend_function fn_copy, *fn_copy_p; zend_function* prototype = NULL; /* is used to determine the prototype according to the inheritance chain */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &existing_fn) == FAILURE) { add = 1; /* not found */ } else if (existing_fn->common.scope != ce) { add = 1; /* or inherited from other class or interface */ /* it is just a reference which was added to the subclass while doing the inheritance */ /* so we can deleted now, and will add the overriding method afterwards */ /* except, if we try to add an abstract function, then we should not delete the inherited one */ /* delete inherited fn if the function to be added is not abstract */ if ((fn->common.fn_flags & ZEND_ACC_ABSTRACT) == 0) { zend_hash_quick_del(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } if (add) { zend_function* parent_function; if (ce->parent && zend_hash_quick_find(&ce->parent->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &parent_function) != FAILURE) { prototype = parent_function; /* ->common.fn_flags |= ZEND_ACC_ABSTRACT; */ /* we got that method in the parent class, and are going to override it, except, if the trait is just asking to have an abstract method implemented. */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* then we clean up an skip this method */ zend_function_dtor(fn); return ZEND_HASH_APPLY_REMOVE; } } fn->common.scope = ce; fn->common.prototype = prototype; if (prototype && (prototype->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT || prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { fn->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; } else if (fn->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT) { /* remove ZEND_ACC_IMPLEMENTED_ABSTRACT flag, think it shouldn't be copied to class */ fn->common.fn_flags = fn->common.fn_flags - ZEND_ACC_IMPLEMENTED_ABSTRACT; } /* check whether the trait method fullfills the inheritance requirements */ if (prototype) { do_inheritance_check_on_method(fn, prototype TSRMLS_CC); } if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (fn->op_array.static_variables) { ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, ce, estrdup(fn->common.function_name) TSRMLS_CC); if (zend_hash_quick_update(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, &fn_copy, sizeof(zend_function), (void**)&fn_copy_p)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating class method table", hash_key->arKey); } zend_add_magic_methods(ce, hash_key->arKey, hash_key->nKeyLength, fn_copy_p TSRMLS_CC); zend_function_dtor(fn); } else { zend_function_dtor(fn); } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ static int zend_traits_copy_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { HashTable* target; zend_class_entry *target_ce; zend_trait_alias** aliases; HashTable* exclude_table; char* lcname; unsigned int fnname_len; zend_function fn_copy; void* dummy; size_t i = 0; target = va_arg(args, HashTable*); target_ce = va_arg(args, zend_class_entry*); aliases = va_arg(args, zend_trait_alias**); exclude_table = va_arg(args, HashTable*); fnname_len = strlen(fn->common.function_name); /* apply aliases which are qualified with a class name, there should not be any ambiguity */ if (aliases) { while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias != NULL && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && aliases[i]->trait_method->mname_len == fnname_len && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(aliases[i]->alias, aliases[i]->alias_len) TSRMLS_CC); /* if it is 0, no modifieres has been changed */ if (aliases[i]->modifiers) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } lcname = zend_str_tolower_dup(aliases[i]->alias, aliases[i]->alias_len); if (zend_hash_add(target, lcname, aliases[i]->alias_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add aliased trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } efree(lcname); } i++; } } lcname = zend_str_tolower_dup(fn->common.function_name, fnname_len); if (exclude_table == NULL || zend_hash_find(exclude_table, lcname, fnname_len, &dummy) == FAILURE) { /* is not in hashtable, thus, function is not to be excluded */ fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(fn->common.function_name, fnname_len) TSRMLS_CC); /* apply aliases which are not qualified by a class name, or which have not * alias name, just setting visibility */ if (aliases) { i = 0; while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias == NULL && aliases[i]->modifiers != 0 && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && (aliases[i]->trait_method->mname_len == fnname_len) && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } i++; } } if (zend_hash_add(target, lcname, fnname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } } efree(lcname); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* Copies function table entries to target function table with applied aliasing */ static void zend_traits_copy_trait_function_table(HashTable *target, zend_class_entry *target_ce, HashTable *source, zend_trait_alias** aliases, HashTable* exclude_table TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_arguments(source TSRMLS_CC, (apply_func_args_t)zend_traits_copy_functions, 4, target, target_ce, aliases, exclude_table); } /* }}} */ static void zend_traits_init_trait_structures(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i, j = 0; zend_trait_precedence *cur_precedence; zend_trait_method_reference *cur_method_ref; /* resolve class references */ if (ce->trait_precedences) { i = 0; while ((cur_precedence = ce->trait_precedences[i])) { if (cur_precedence->exclude_from_classes) { cur_precedence->trait_method->ce = zend_fetch_class(cur_precedence->trait_method->class_name, cur_precedence->trait_method->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); j = 0; while (cur_precedence->exclude_from_classes[j]) { char* class_name = (char*)cur_precedence->exclude_from_classes[j]; zend_uint name_length = strlen(class_name); cur_precedence->exclude_from_classes[j] = zend_fetch_class(class_name, name_length, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); efree(class_name); j++; } } i++; } } if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { if (ce->trait_aliases[i]->trait_method->class_name) { cur_method_ref = ce->trait_aliases[i]->trait_method; cur_method_ref->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); } i++; } } } /* }}} */ static void zend_traits_compile_exclude_table(HashTable* exclude_table, zend_trait_precedence **precedences, zend_class_entry *trait) /* {{{ */ { size_t i = 0, j; if (!precedences) { return; } while (precedences[i]) { if (precedences[i]->exclude_from_classes) { j = 0; while (precedences[i]->exclude_from_classes[j]) { if (precedences[i]->exclude_from_classes[j] == trait) { zend_uint lcname_len = precedences[i]->trait_method->mname_len; char *lcname = zend_str_tolower_dup(precedences[i]->trait_method->method_name, lcname_len); if (zend_hash_add(exclude_table, lcname, lcname_len, NULL, 0, NULL) == FAILURE) { efree(lcname); zend_error(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", precedences[i]->trait_method->method_name, trait->name); } efree(lcname); } ++j; } } ++i; } } /* }}} */ static void zend_do_traits_method_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { HashTable** function_tables; HashTable* resulting_table; HashTable exclude_table; size_t i; /* prepare copies of trait function tables for combination */ function_tables = malloc(sizeof(HashTable*) * ce->num_traits); resulting_table = (HashTable *) malloc(sizeof(HashTable)); /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(resulting_table, 10, NULL, NULL, 1, 0); for (i = 0; i < ce->num_traits; i++) { function_tables[i] = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(function_tables[i], ce->traits[i]->function_table.nNumOfElements, NULL, NULL, 1, 0); if (ce->trait_precedences) { /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(&exclude_table, 2, NULL, NULL, 0, 0); zend_traits_compile_exclude_table(&exclude_table, ce->trait_precedences, ce->traits[i]); /* copies functions, applies defined aliasing, and excludes unused trait methods */ zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, &exclude_table TSRMLS_CC); zend_hash_graceful_destroy(&exclude_table); } else { zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, NULL TSRMLS_CC); } } /* now merge trait methods */ for (i = 0; i < ce->num_traits; i++) { zend_hash_apply_with_arguments(function_tables[i] TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions, 5, i, ce->num_traits, resulting_table, function_tables, ce); } /* Now the resulting_table contains all trait methods we would have to * add to the class in the following step the methods are inserted into the method table * if there is already a method with the same name it is replaced iff ce != fn.scope * --> all inherited methods are overridden, methods defined in the class are left untouched */ zend_hash_apply_with_arguments(resulting_table TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions_to_class, 1, ce); /* free temporary function tables */ for (i = 0; i < ce->num_traits; i++) { /* zend_hash_destroy(function_tables[i]); */ zend_hash_graceful_destroy(function_tables[i]); free(function_tables[i]); } free(function_tables); /* free temporary resulting table */ /* zend_hash_destroy(resulting_table); */ zend_hash_graceful_destroy(resulting_table); free(resulting_table); } /* }}} */ static zend_class_entry* find_first_definition(zend_class_entry *ce, size_t current_trait, const char* prop_name, int prop_name_length, ulong prop_hash, zend_class_entry *coliding_ce) /* {{{ */ { size_t i; zend_property_info *coliding_prop; for (i = 0; (i < current_trait) && (i < ce->num_traits); i++) { if (zend_hash_quick_find(&ce->traits[i]->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS) { return ce->traits[i]; } } return coliding_ce; } /* }}} */ static void zend_do_traits_property_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i; zend_property_info *property_info; zend_property_info *coliding_prop; zval compare_result; const char* prop_name; int prop_name_length; ulong prop_hash; const char* class_name_unused; zend_bool prop_found; zend_bool not_compatible; zval* prop_value; /* In the following steps the properties are inserted into the property table * for that, a very strict approach is applied: * - check for compatibility, if not compatible with any property in class -> fatal * - if compatible, then strict notice */ for (i = 0; i < ce->num_traits; i++) { for (zend_hash_internal_pointer_reset(&ce->traits[i]->properties_info); zend_hash_get_current_data(&ce->traits[i]->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->traits[i]->properties_info)) { /* first get the unmangeld name if necessary, * then check whether the property is already there */ if ((property_info->flags & ZEND_ACC_PPP_MASK) == ZEND_ACC_PUBLIC) { prop_hash = property_info->h; prop_name = property_info->name; prop_name_length = property_info->name_length; prop_found = zend_hash_quick_find(&ce->properties_info, property_info->name, property_info->name_length+1, property_info->h, (void **) &coliding_prop) == SUCCESS; } else { /* for private and protected we need to unmangle the names */ zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name_unused, &prop_name); prop_name_length = strlen(prop_name); prop_hash = zend_get_hash_value(prop_name, prop_name_length + 1); prop_found = zend_hash_quick_find(&ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS; } /* next: check for conflicts with current class */ if (prop_found) { if (coliding_prop->flags & ZEND_ACC_SHADOW) { /* this one is inherited, lets look it up in its own class */ zend_hash_quick_find(&coliding_prop->ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop); } if ((coliding_prop->flags & ZEND_ACC_PPP_MASK) == (property_info->flags & ZEND_ACC_PPP_MASK)) { /* flags are identical, now the value needs to be checked */ if (property_info->flags & ZEND_ACC_STATIC) { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_static_members_table[coliding_prop->offset], ce->traits[i]->default_static_members_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } else { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_properties_table[coliding_prop->offset], ce->traits[i]->default_properties_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } } else { /* the flags are not identical, thus, we assume properties are not compatible */ not_compatible = 1; } if (not_compatible) { zend_error(E_COMPILE_ERROR, "%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } else { zend_error(E_STRICT, "%s and %s define the same property ($%s) in the composition of %s. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } } /* property not found, so lets add it */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); zend_declare_property_ex(ce, prop_name, prop_name_length, prop_value, property_info->flags, property_info->doc_comment, property_info->doc_comment_len TSRMLS_CC); } } } /* }}} */ ZEND_API void zend_do_bind_traits(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { if (ce->num_traits <= 0) { return; } /* complete initialization of trait strutures in ce */ zend_traits_init_trait_structures(ce TSRMLS_CC); /* first care about all methods to be flattened into the class */ zend_do_traits_method_binding(ce TSRMLS_CC); /* then flatten the properties into it, to, mostly to notfiy developer about problems */ zend_do_traits_property_binding(ce TSRMLS_CC); /* verify that all abstract methods from traits have been implemented */ zend_verify_abstract_class(ce TSRMLS_CC); /* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */ if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { ce->ce_flags -= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } } /* }}} */ ZEND_API int do_bind_function(const zend_op_array *op_array, zend_op *opline, HashTable *function_table, zend_bool compile_time) /* {{{ */ { zend_function *function; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } zend_hash_quick_find(function_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void *) &function); if (zend_hash_quick_add(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), function, sizeof(zend_function), NULL)==FAILURE) { int error_level = compile_time ? E_COMPILE_ERROR : E_ERROR; zend_function *old_function; if (zend_hash_quick_find(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), (void *) &old_function)==SUCCESS && old_function->type == ZEND_USER_FUNCTION && old_function->op_array.last > 0) { zend_error(error_level, "Cannot redeclare %s() (previously declared in %s:%d)", function->common.function_name, old_function->op_array.filename, old_function->op_array.opcodes[0].lineno); } else { zend_error(error_level, "Cannot redeclare %s()", function->common.function_name); } return FAILURE; } else { (*function->op_array.refcount)++; function->op_array.static_variables = NULL; /* NULL out the unbound function */ return SUCCESS; } } /* }}} */ void zend_add_trait_precedence(znode *precedence_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_precedences, precedence_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_add_trait_alias(znode *alias_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_aliases, alias_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_prepare_reference(znode *result, znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { zend_trait_method_reference *method_ref = emalloc(sizeof(zend_trait_method_reference)); method_ref->ce = NULL; /* REM: There should not be a need for copying, zend_do_begin_class_declaration is also just using that string */ if (class_name) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); method_ref->class_name = Z_STRVAL(class_name->u.constant); method_ref->cname_len = Z_STRLEN(class_name->u.constant); } else { method_ref->class_name = NULL; method_ref->cname_len = 0; } method_ref->method_name = Z_STRVAL(method_name->u.constant); method_ref->mname_len = Z_STRLEN(method_name->u.constant); result->u.op.ptr = method_ref; result->op_type = IS_TMP_VAR; } /* }}} */ void zend_prepare_trait_alias(znode *result, znode *method_reference, znode *modifiers, znode *alias TSRMLS_DC) /* {{{ */ { zend_trait_alias *trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_alias->modifiers = Z_LVAL(modifiers->u.constant); if (Z_LVAL(modifiers->u.constant) == ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot use 'static' as method modifier"); return; } if (alias) { trait_alias->alias = Z_STRVAL(alias->u.constant); trait_alias->alias_len = Z_STRLEN(alias->u.constant); } else { trait_alias->alias = NULL; } trait_alias->function = NULL; result->u.op.ptr = trait_alias; } /* }}} */ void zend_prepare_trait_precedence(znode *result, znode *method_reference, znode *trait_list TSRMLS_DC) /* {{{ */ { zend_trait_precedence *trait_precedence = emalloc(sizeof(zend_trait_precedence)); trait_precedence->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_precedence->exclude_from_classes = (zend_class_entry**) trait_list->u.op.ptr; trait_precedence->function = NULL; result->u.op.ptr = trait_precedence; } /* }}} */ ZEND_API zend_class_entry *do_bind_class(const zend_op_array* op_array, const zend_op *opline, HashTable *class_table, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } if (zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce)==FAILURE) { zend_error(E_COMPILE_ERROR, "Internal Zend error - Missing class information for %s", Z_STRVAL_P(op1)); return NULL; } else { ce = *pce; } ce->refcount++; if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), &ce, sizeof(zend_class_entry *), NULL)==FAILURE) { ce->refcount--; if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return NULL; } else { if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLEMENT_INTERFACES))) { zend_verify_abstract_class(ce TSRMLS_CC); } return ce; } } /* }}} */ ZEND_API zend_class_entry *do_bind_inherited_class(const zend_op_array *op_array, const zend_op *opline, HashTable *class_table, zend_class_entry *parent_ce, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; int found_ce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } found_ce = zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce); if (found_ce == FAILURE) { if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", Z_STRVAL_P(op2)); } return NULL; } else { ce = *pce; } if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ce->name, parent_ce->name); } else if ((parent_ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ce->name, parent_ce->name); } zend_do_inheritance(ce, parent_ce TSRMLS_CC); ce->refcount++; /* Register the derived class */ if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), pce, sizeof(zend_class_entry *), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return ce; } /* }}} */ void zend_do_early_binding(TSRMLS_D) /* {{{ */ { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; HashTable *table; while (opline->opcode == ZEND_TICKS && opline > CG(active_op_array)->opcodes) { opline--; } switch (opline->opcode) { case ZEND_DECLARE_FUNCTION: if (do_bind_function(CG(active_op_array), opline, CG(function_table), 1) == FAILURE) { return; } table = CG(function_table); break; case ZEND_DECLARE_CLASS: if (do_bind_class(CG(active_op_array), opline, CG(class_table), 1 TSRMLS_CC) == NULL) { return; } table = CG(class_table); break; case ZEND_DECLARE_INHERITED_CLASS: { zend_op *fetch_class_opline = opline-1; zval *parent_name; zend_class_entry **pce; parent_name = &CONSTANT(fetch_class_opline->op2.constant); if ((zend_lookup_class(Z_STRVAL_P(parent_name), Z_STRLEN_P(parent_name), &pce TSRMLS_CC) == FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_CLASSES) && ((*pce)->type == ZEND_INTERNAL_CLASS))) { if (CG(compiler_options) & ZEND_COMPILE_DELAYED_BINDING) { zend_uint *opline_num = &CG(active_op_array)->early_binding; while (*opline_num != -1) { opline_num = &CG(active_op_array)->opcodes[*opline_num].result.opline_num; } *opline_num = opline - CG(active_op_array)->opcodes; opline->opcode = ZEND_DECLARE_INHERITED_CLASS_DELAYED; opline->result_type = IS_UNUSED; opline->result.opline_num = -1; } return; } if (do_bind_inherited_class(CG(active_op_array), opline, CG(class_table), *pce, 1 TSRMLS_CC) == NULL) { return; } /* clear unnecessary ZEND_FETCH_CLASS opcode */ zend_del_literal(CG(active_op_array), fetch_class_opline->op2.constant); MAKE_NOP(fetch_class_opline); table = CG(class_table); break; } case ZEND_VERIFY_ABSTRACT_CLASS: case ZEND_ADD_INTERFACE: case ZEND_ADD_TRAIT: case ZEND_BIND_TRAITS: /* We currently don't early-bind classes that implement interfaces */ /* Classes with traits are handled exactly the same, no early-bind here */ return; default: zend_error(E_COMPILE_ERROR, "Invalid binding type"); return; } zend_hash_quick_del(table, Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant)), Z_HASH_P(&CONSTANT(opline->op1.constant))); zend_del_literal(CG(active_op_array), opline->op1.constant); zend_del_literal(CG(active_op_array), opline->op2.constant); MAKE_NOP(opline); } /* }}} */ ZEND_API void zend_do_delayed_early_binding(const zend_op_array *op_array TSRMLS_DC) /* {{{ */ { if (op_array->early_binding != -1) { zend_bool orig_in_compilation = CG(in_compilation); zend_uint opline_num = op_array->early_binding; zend_class_entry **pce; CG(in_compilation) = 1; while (opline_num != -1) { if (zend_lookup_class(Z_STRVAL_P(op_array->opcodes[opline_num-1].op2.zv), Z_STRLEN_P(op_array->opcodes[opline_num-1].op2.zv), &pce TSRMLS_CC) == SUCCESS) { do_bind_inherited_class(op_array, &op_array->opcodes[opline_num], EG(class_table), *pce, 0 TSRMLS_CC); } opline_num = op_array->opcodes[opline_num].result.opline_num; } CG(in_compilation) = orig_in_compilation; } } /* }}} */ void zend_do_boolean_or_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_or_end(znode *result, const znode *expr1, const znode *expr2, znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_boolean_and_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_and_end(znode *result, const znode *expr1, const znode *expr2, const znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_do_while_begin(TSRMLS_D) /* {{{ */ { do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_do_while_end(const znode *do_token, const znode *expr_open_bracket, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ; SET_NODE(opline->op1, expr); opline->op2.opline_num = do_token->u.op.opline_num; SET_UNUSED(opline->op2); do_end_loop(expr_open_bracket->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_brk_cont(zend_uchar op, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->op1.opline_num = CG(context).current_brk_cont; SET_UNUSED(opline->op1); if (expr) { if (expr->op_type != IS_CONST) { zend_error(E_COMPILE_ERROR, "'%s' operator with non-constant operand is no longer supported", op == ZEND_BRK ? "break" : "continue"); } else if (Z_TYPE(expr->u.constant) != IS_LONG || Z_LVAL(expr->u.constant) < 1) { zend_error(E_COMPILE_ERROR, "'%s' operator accepts only positive numbers", op == ZEND_BRK ? "break" : "continue"); } SET_NODE(opline->op2, expr); } else { LITERAL_LONG(opline->op2, 1); opline->op2_type = IS_CONST; } } /* }}} */ void zend_do_switch_cond(const znode *cond TSRMLS_DC) /* {{{ */ { zend_switch_entry switch_entry; switch_entry.cond = *cond; switch_entry.default_case = -1; switch_entry.control_var = -1; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_switch_end(const znode *case_list TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); /* add code to jmp to default case */ if (switch_entry_ptr->default_case != -1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->op1.opline_num = switch_entry_ptr->default_case; } if (case_list->op_type != IS_UNUSED) { /* non-empty switch */ int next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* remember break/continue loop information */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; if (switch_entry_ptr->cond.op_type==IS_VAR || switch_entry_ptr->cond.op_type==IS_TMP_VAR) { /* emit free for the switch condition*/ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry_ptr->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_UNUSED(opline->op2); } if (switch_entry_ptr->cond.op_type == IS_CONST) { zval_dtor(&switch_entry_ptr->cond.u.constant); } zend_stack_del_top(&CG(switch_cond_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_case_before_statement(const znode *case_list, znode *case_token, const znode *case_expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); int next_op_number; zend_switch_entry *switch_entry_ptr; znode result; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); if (switch_entry_ptr->control_var == -1) { switch_entry_ptr->control_var = get_temporary_variable(CG(active_op_array)); } opline->opcode = ZEND_CASE; opline->result.var = switch_entry_ptr->control_var; opline->result_type = IS_TMP_VAR; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_NODE(opline->op2, case_expr); if (opline->op1_type == IS_CONST) { zval_copy_ctor(&CONSTANT(opline->op1.constant)); } GET_NODE(&result, opline->result); next_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, &result); SET_UNUSED(opline->op2); case_token->u.op.opline_num = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_case_after_statement(znode *result, const znode *case_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); result->u.op.opline_num = next_op_number; switch (CG(active_op_array)->opcodes[case_token->u.op.opline_num].opcode) { case ZEND_JMP: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); break; case ZEND_JMPZ: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); break; } } /* }}} */ void zend_do_default_before_statement(const znode *case_list, znode *default_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); default_token->u.op.opline_num = next_op_number; next_op_number = get_next_op_number(CG(active_op_array)); switch_entry_ptr->default_case = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_begin_class_declaration(const znode *class_token, znode *class_name, const znode *parent_class_name TSRMLS_DC) /* {{{ */ { zend_op *opline; int doing_inheritance = 0; zend_class_entry *new_class_entry; char *lcname; int error = 0; zval **ns_name, key; if (CG(active_class_entry)) { zend_error(E_COMPILE_ERROR, "Class declarations may not be nested"); return; } lcname = zend_str_tolower_dup(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); if (!(strcmp(lcname, "self") && strcmp(lcname, "parent"))) { efree(lcname); zend_error(E_COMPILE_ERROR, "Cannot use '%s' as class name as it is reserved", Z_STRVAL(class_name->u.constant)); } /* Class name must not conflict with import names */ if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns_name) == SUCCESS) { error = 1; } if (CG(current_namespace)) { /* Prefix class name with name of current namespace */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); class_name = &tmp; efree(lcname); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); } if (error) { char *tmp = zend_str_tolower_dup(Z_STRVAL_PP(ns_name), Z_STRLEN_PP(ns_name)); if (Z_STRLEN_PP(ns_name) != Z_STRLEN(class_name->u.constant) || memcmp(tmp, lcname, Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "Cannot declare class %s because the name is already in use", Z_STRVAL(class_name->u.constant)); } efree(tmp); } new_class_entry = emalloc(sizeof(zend_class_entry)); new_class_entry->type = ZEND_USER_CLASS; new_class_entry->name = zend_new_interned_string(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1, 1 TSRMLS_CC); new_class_entry->name_length = Z_STRLEN(class_name->u.constant); zend_initialize_class_data(new_class_entry, 1 TSRMLS_CC); new_class_entry->info.user.filename = zend_get_compiled_filename(TSRMLS_C); new_class_entry->info.user.line_start = class_token->u.op.opline_num; new_class_entry->ce_flags |= class_token->EA; if (parent_class_name && parent_class_name->op_type != IS_UNUSED) { switch (parent_class_name->EA) { case ZEND_FETCH_CLASS_SELF: zend_error(E_COMPILE_ERROR, "Cannot use 'self' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_PARENT: zend_error(E_COMPILE_ERROR, "Cannot use 'parent' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use 'static' as class name as it is reserved"); break; default: break; } doing_inheritance = 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, new_class_entry->name_length TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; if (doing_inheritance) { /* Make sure a trait does not try to extend a class */ if ((new_class_entry->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "A trait (%s) cannot extend a class", new_class_entry->name); } opline->extended_value = parent_class_name->u.op.var; opline->opcode = ZEND_DECLARE_INHERITED_CLASS; } else { opline->opcode = ZEND_DECLARE_CLASS; } LITERAL_STRINGL(opline->op2, lcname, new_class_entry->name_length, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); zend_hash_quick_update(CG(class_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &new_class_entry, sizeof(zend_class_entry *), NULL); CG(active_class_entry) = new_class_entry; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(&CG(implementing_class), opline->result); if (CG(doc_comment)) { CG(active_class_entry)->info.user.doc_comment = CG(doc_comment); CG(active_class_entry)->info.user.doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ static void do_verify_abstract_class(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_VERIFY_ABSTRACT_CLASS; SET_NODE(opline->op1, &CG(implementing_class)); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_class_declaration(const znode *class_token, const znode *parent_token TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); if (ce->constructor) { ce->constructor->common.fn_flags |= ZEND_ACC_CTOR; if (ce->constructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Constructor %s::%s() cannot be static", ce->name, ce->constructor->common.function_name); } } if (ce->destructor) { ce->destructor->common.fn_flags |= ZEND_ACC_DTOR; if (ce->destructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Destructor %s::%s() cannot be static", ce->name, ce->destructor->common.function_name); } } if (ce->clone) { ce->clone->common.fn_flags |= ZEND_ACC_CLONE; if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static", ce->name, ce->clone->common.function_name); } } ce->info.user.line_end = zend_get_compiled_lineno(TSRMLS_C); /* Check for traits and proceed like with interfaces. * The only difference will be a combined handling of them in the end. * Thus, we need another opcode here. */ if (ce->num_traits > 0) { zend_op *opline; ce->traits = NULL; ce->num_traits = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_TRAITS; /* opcode generation: */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BIND_TRAITS; SET_NODE(opline->op1, &CG(implementing_class)); } if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) && ((parent_token->op_type != IS_UNUSED) || (ce->num_interfaces > 0))) { zend_verify_abstract_class(ce TSRMLS_CC); if (ce->num_interfaces) { do_verify_abstract_class(TSRMLS_C); } } /* Inherit interfaces; reset number to zero, we need it for above check and * will restore it during actual implementation. * The ZEND_ACC_IMPLEMENT_INTERFACES flag disables double call to * zend_verify_abstract_class() */ if (ce->num_interfaces > 0) { ce->interfaces = NULL; ce->num_interfaces = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_INTERFACES; } CG(active_class_entry) = NULL; } /* }}} */ void zend_do_implements_interface(znode *interface_name TSRMLS_DC) /* {{{ */ { zend_op *opline; /* Traits can not implement interfaces */ if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface on '%s' since it is a Trait", Z_STRVAL(interface_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(interface_name->u.constant), Z_STRLEN(interface_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface name as it is reserved", Z_STRVAL(interface_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_INTERFACE; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(interface_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = (opline->extended_value & ~ZEND_FETCH_CLASS_MASK) | ZEND_FETCH_CLASS_INTERFACE; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &interface_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_interfaces++; } /* }}} */ void zend_do_implements_trait(znode *trait_name TSRMLS_DC) /* {{{ */ { zend_op *opline; if ((CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Cannot use traits inside of interfaces. %s is used in %s", Z_STRVAL(trait_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(trait_name->u.constant), Z_STRLEN(trait_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as trait name as it is reserved", Z_STRVAL(trait_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_TRAIT; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(trait_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = ZEND_FETCH_CLASS_TRAIT; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &trait_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_traits++; } /* }}} */ ZEND_API void zend_mangle_property_name(char **dest, int *dest_length, const char *src1, int src1_length, const char *src2, int src2_length, int internal) /* {{{ */ { char *prop_name; int prop_name_length; prop_name_length = 1 + src1_length + 1 + src2_length; prop_name = pemalloc(prop_name_length + 1, internal); prop_name[0] = '\0'; memcpy(prop_name + 1, src1, src1_length+1); memcpy(prop_name + 1 + src1_length + 1, src2, src2_length+1); *dest = prop_name; *dest_length = prop_name_length; } /* }}} */ static int zend_strnlen(const char* s, int maxlen) /* {{{ */ { int len = 0; while (*s++ && maxlen--) len++; return len; } /* }}} */ ZEND_API int zend_unmangle_property_name(const char *mangled_property, int len, const char **class_name, const char **prop_name) /* {{{ */ { int class_name_len; *class_name = NULL; if (mangled_property[0]!=0) { *prop_name = mangled_property; return SUCCESS; } if (len < 3 || mangled_property[1]==0) { zend_error(E_NOTICE, "Illegal member variable name"); *prop_name = mangled_property; return FAILURE; } class_name_len = zend_strnlen(mangled_property+1, --len - 1) + 1; if (class_name_len >= len || mangled_property[class_name_len]!=0) { zend_error(E_NOTICE, "Corrupt member variable name"); *prop_name = mangled_property; return FAILURE; } *class_name = mangled_property+1; *prop_name = (*class_name)+class_name_len; return SUCCESS; } /* }}} */ void zend_do_declare_property(const znode *var_name, const znode *value, zend_uint access_type TSRMLS_DC) /* {{{ */ { zval *property; zend_property_info *existing_property_info; char *comment = NULL; int comment_len = 0; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Interfaces may not include member variables"); } if (access_type & ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Properties cannot be declared abstract"); } if (access_type & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot declare property %s::$%s final, the final modifier is allowed only for methods and classes", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } if (zend_hash_find(&CG(active_class_entry)->properties_info, var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, (void **) &existing_property_info)==SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::$%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } ALLOC_ZVAL(property); if (value) { *property = value->u.constant; } else { INIT_PZVAL(property); Z_TYPE_P(property) = IS_NULL; } if (CG(doc_comment)) { comment = CG(doc_comment); comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } zend_declare_property_ex(CG(active_class_entry), zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len + 1, 0 TSRMLS_CC), var_name->u.constant.value.str.len, property, access_type, comment, comment_len TSRMLS_CC); efree(var_name->u.constant.value.str.val); } /* }}} */ void zend_do_declare_class_constant(znode *var_name, const znode *value TSRMLS_DC) /* {{{ */ { zval *property; const char *cname = NULL; int result; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed in class constants"); return; } if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Traits cannot have constants"); return; } ALLOC_ZVAL(property); *property = value->u.constant; cname = zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, 0 TSRMLS_CC); if (IS_INTERNED(cname)) { result = zend_hash_quick_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, INTERNED_HASH(cname), &property, sizeof(zval *), NULL); } else { result = zend_hash_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, &property, sizeof(zval *), NULL); } if (result == FAILURE) { FREE_ZVAL(property); zend_error(E_COMPILE_ERROR, "Cannot redefine class constant %s::%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } FREE_PNODE(var_name); if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_fetch_property(znode *result, znode *object, const znode *property TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (object->op_type == IS_CV) { if (object->u.op.var == CG(active_op_array)->this_var) { object->op_type = IS_UNUSED; /* this means $this for objects */ } } else if (fetch_list_ptr->count == 1) { zend_llist_element *le = fetch_list_ptr->head; zend_op *opline_ptr = (zend_op *) le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); SET_UNUSED(opline_ptr->op1); /* this means $this for objects */ SET_NODE(opline_ptr->op2, property); /* if it was usual fetch, we change it to object fetch */ switch (opline_ptr->opcode) { case ZEND_FETCH_W: opline_ptr->opcode = ZEND_FETCH_OBJ_W; break; case ZEND_FETCH_R: opline_ptr->opcode = ZEND_FETCH_OBJ_R; break; case ZEND_FETCH_RW: opline_ptr->opcode = ZEND_FETCH_OBJ_RW; break; case ZEND_FETCH_IS: opline_ptr->opcode = ZEND_FETCH_OBJ_IS; break; case ZEND_FETCH_UNSET: opline_ptr->opcode = ZEND_FETCH_OBJ_UNSET; break; case ZEND_FETCH_FUNC_ARG: opline_ptr->opcode = ZEND_FETCH_OBJ_FUNC_ARG; break; } if (opline_ptr->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline_ptr->op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline_ptr->op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op2.constant); } GET_NODE(result, opline_ptr->result); return; } } if (zend_is_function_or_method_call(object)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, object); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_OBJ_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, object); SET_NODE(opline.op2, property); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline.op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op2.constant); } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void zend_do_halt_compiler_register(TSRMLS_D) /* {{{ */ { char *name, *cfilename; char haltoff[] = "__COMPILER_HALT_OFFSET__"; int len, clen; cfilename = zend_get_compiled_filename(TSRMLS_C); clen = strlen(cfilename); zend_mangle_property_name(&name, &len, haltoff, sizeof(haltoff) - 1, cfilename, clen, 0); zend_register_long_constant(name, len+1, zend_get_scanned_file_offset(TSRMLS_C), CONST_CS, 0 TSRMLS_CC); pefree(name, 0); if (CG(in_namespace)) { zend_do_end_namespace(TSRMLS_C); } } /* }}} */ void zend_do_push_object(const znode *object TSRMLS_DC) /* {{{ */ { zend_stack_push(&CG(object_stack), object, sizeof(znode)); } /* }}} */ void zend_do_pop_object(znode *object TSRMLS_DC) /* {{{ */ { if (object) { znode *tmp; zend_stack_top(&CG(object_stack), (void **) &tmp); *object = *tmp; } zend_stack_del_top(&CG(object_stack)); } /* }}} */ void zend_do_begin_new_object(znode *new_token, znode *class_type TSRMLS_DC) /* {{{ */ { zend_op *opline; unsigned char *ptr = NULL; new_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_NEW; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, class_type); SET_UNUSED(opline->op2); zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(unsigned char *)); } /* }}} */ void zend_do_end_new_object(znode *result, const znode *new_token, const znode *argument_list TSRMLS_DC) /* {{{ */ { znode ctor_result; zend_do_end_function_call(NULL, &ctor_result, argument_list, 1, 0 TSRMLS_CC); zend_do_free(&ctor_result TSRMLS_CC); CG(active_op_array)->opcodes[new_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, CG(active_op_array)->opcodes[new_token->u.op.opline_num].result); } /* }}} */ static zend_constant* zend_get_ct_const(const zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = NULL; if (Z_STRVAL_P(const_name)[0] == '\\') { if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name), (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name)-1); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name), (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } } else if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)+1, (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name)+1, (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } if (c->flags & CONST_CT_SUBST) { return c; } if (all_internal_constants_substitution && (c->flags & CONST_PERSISTENT) && !(CG(compiler_options) & ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION) && Z_TYPE(c->value) != IS_CONSTANT && Z_TYPE(c->value) != IS_CONSTANT_ARRAY) { return c; } return NULL; } /* }}} */ static int zend_constant_ct_subst(znode *result, zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = zend_get_ct_const(const_name, all_internal_constants_substitution TSRMLS_CC); if (c) { zval_dtor(const_name); result->op_type = IS_CONST; result->u.constant = c->value; zval_copy_ctor(&result->u.constant); INIT_PZVAL(&result->u.constant); return 1; } return 0; } /* }}} */ void zend_do_fetch_constant(znode *result, znode *constant_container, znode *constant_name, int mode, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; zend_op *opline; int type; char *compound; ulong fetch_type = 0; if (constant_container) { switch (mode) { case ZEND_CT: /* this is a class constant */ type = zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant)); if (ZEND_FETCH_CLASS_STATIC == type) { zend_error(E_ERROR, "\"static::\" is not allowed in compile-time constants"); } else if (ZEND_FETCH_CLASS_DEFAULT == type) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } zend_do_build_full_name(NULL, constant_container, constant_name, 1 TSRMLS_CC); *result = *constant_container; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: if (constant_container->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant))) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } else { zend_do_fetch_class(&tmp, constant_container TSRMLS_CC); constant_container = &tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); if (constant_container->op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &constant_container->u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, constant_container); } SET_NODE(opline->op2, constant_name); CALCULATE_LITERAL_HASH(opline->op2.constant); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } GET_NODE(result, opline->result); break; } return; } /* namespace constant */ /* only one that did not contain \ from the start can be converted to string if unknown */ switch (mode) { case ZEND_CT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); /* this is a namespace constant, or an unprefixed constant */ if (zend_constant_ct_subst(result, &constant_name->u.constant, 0 TSRMLS_CC)) { break; } zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(!compound) { fetch_type |= IS_CONSTANT_UNQUALIFIED; } *result = *constant_name; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(zend_constant_ct_subst(result, &constant_name->u.constant, 1 TSRMLS_CC)) { break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; if (compound) { /* the name is unambiguous */ opline->extended_value = 0; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } else { opline->extended_value = IS_CONSTANT_UNQUALIFIED; if (CG(current_namespace)) { opline->extended_value |= IS_CONSTANT_IN_NAMESPACE; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 1 TSRMLS_CC); } else { opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } } GET_CACHE_SLOT(opline->op2.constant); break; } } /* }}} */ void zend_do_shell_exec(znode *result, const znode *cmd TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); switch (cmd->op_type) { case IS_CONST: case IS_TMP_VAR: opline->opcode = ZEND_SEND_VAL; break; default: opline->opcode = ZEND_SEND_VAR; break; } SET_NODE(opline->op1, cmd); opline->op2.opline_num = 0; opline->extended_value = ZEND_DO_FCALL; SET_UNUSED(opline->op2); /* FIXME: exception support not added to this op2 */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DO_FCALL; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; LITERAL_STRINGL(opline->op1, estrndup("shell_exec", sizeof("shell_exec")-1), sizeof("shell_exec")-1, 0); CALCULATE_LITERAL_HASH(opline->op1.constant); opline->op1_type = IS_CONST; GET_CACHE_SLOT(opline->op1.constant); opline->extended_value = 1; SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_init_array(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_ARRAY; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; GET_NODE(result, opline->result); if (expr) { SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } } else { SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_array_element(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_ARRAY_ELEMENT; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_static_array_element(znode *result, znode *offset, const znode *expr) /* {{{ */ { zval *element; ALLOC_ZVAL(element); *element = expr->u.constant; if (offset) { switch (offset->u.constant.type & IS_CONSTANT_TYPE_MASK) { case IS_CONSTANT: /* Ugly hack to denote that this value has a constant index */ Z_TYPE_P(element) |= IS_CONSTANT_INDEX; Z_STRVAL(offset->u.constant) = erealloc(Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+1] = Z_TYPE(offset->u.constant); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+2] = 0; zend_symtable_update(result->u.constant.value.ht, Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_STRING: zend_symtable_update(result->u.constant.value.ht, offset->u.constant.value.str.val, offset->u.constant.value.str.len+1, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_NULL: zend_symtable_update(Z_ARRVAL(result->u.constant), "", 1, &element, sizeof(zval *), NULL); break; case IS_LONG: case IS_BOOL: zend_hash_index_update(Z_ARRVAL(result->u.constant), Z_LVAL(offset->u.constant), &element, sizeof(zval *), NULL); break; case IS_DOUBLE: zend_hash_index_update(Z_ARRVAL(result->u.constant), zend_dval_to_lval(Z_DVAL(offset->u.constant)), &element, sizeof(zval *), NULL); break; case IS_CONSTANT_ARRAY: zend_error(E_ERROR, "Illegal offset type"); break; } } else { zend_hash_next_index_insert(Z_ARRVAL(result->u.constant), &element, sizeof(zval *), NULL); } } /* }}} */ void zend_do_add_list_element(const znode *element TSRMLS_DC) /* {{{ */ { list_llist_element lle; if (element) { zend_check_writable_variable(element); lle.var = *element; zend_llist_copy(&lle.dimensions, &CG(dimension_llist)); zend_llist_prepend_element(&CG(list_llist), &lle); } (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_new_list_begin(TSRMLS_D) /* {{{ */ { int current_dimension = 0; zend_llist_add_element(&CG(dimension_llist), &current_dimension); } /* }}} */ void zend_do_new_list_end(TSRMLS_D) /* {{{ */ { zend_llist_remove_tail(&CG(dimension_llist)); (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_list_init(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(list_stack), &CG(list_llist), sizeof(zend_llist)); zend_stack_push(&CG(list_stack), &CG(dimension_llist), sizeof(zend_llist)); zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_do_new_list_begin(TSRMLS_C); } /* }}} */ void zend_do_list_end(znode *result, znode *expr TSRMLS_DC) /* {{{ */ { zend_llist_element *le; zend_llist_element *dimension; zend_op *opline; znode last_container; le = CG(list_llist).head; while (le) { zend_llist *tmp_dimension_llist = &((list_llist_element *)le->data)->dimensions; dimension = tmp_dimension_llist->head; while (dimension) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (dimension == tmp_dimension_llist->head) { /* first */ last_container = *expr; switch (expr->op_type) { case IS_VAR: case IS_CV: opline->opcode = ZEND_FETCH_DIM_R; break; case IS_TMP_VAR: opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; case IS_CONST: /* fetch_dim_tmp_var will handle this bogus fetch */ zval_copy_ctor(&expr->u.constant); opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; } opline->extended_value |= ZEND_FETCH_ADD_LOCK; } else { opline->opcode = ZEND_FETCH_DIM_R; } opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, &last_container); opline->op2_type = IS_CONST; LITERAL_LONG(opline->op2, *((int *) dimension->data)); GET_NODE(&last_container, opline->result); dimension = dimension->next; } ((list_llist_element *) le->data)->value = last_container; zend_llist_destroy(&((list_llist_element *) le->data)->dimensions); zend_do_assign(result, &((list_llist_element *) le->data)->var, &((list_llist_element *) le->data)->value TSRMLS_CC); zend_do_free(result TSRMLS_CC); le = le->next; } zend_llist_destroy(&CG(dimension_llist)); zend_llist_destroy(&CG(list_llist)); *result = *expr; { zend_llist *p; /* restore previous lists */ zend_stack_top(&CG(list_stack), (void **) &p); CG(dimension_llist) = *p; zend_stack_del_top(&CG(list_stack)); zend_stack_top(&CG(list_stack), (void **) &p); CG(list_llist) = *p; zend_stack_del_top(&CG(list_stack)); } } /* }}} */ void zend_init_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = emalloc(sizeof(void*) * 2); list[0] = item; list[1] = NULL; *(void**)result = list; } /* }}} */ void zend_add_to_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = *(void**)result; size_t n = 0; while (list && list[n]) { n++; } list = erealloc(list, sizeof(void*) * (n+2)); list[n] = item; list[n+1] = NULL; *(void**)result = list; } /* }}} */ void zend_do_fetch_static_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zval *tmp; zend_op *opline; znode lval; znode result; ALLOC_ZVAL(tmp); if (static_assignment) { *tmp = static_assignment->u.constant; } else { INIT_ZVAL(*tmp); } if (!CG(active_op_array)->static_variables) { if (CG(active_op_array)->scope) { CG(active_op_array)->scope->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } ALLOC_HASHTABLE(CG(active_op_array)->static_variables); zend_hash_init(CG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } zend_hash_update(CG(active_op_array)->static_variables, varname->u.constant.value.str.val, varname->u.constant.value.str.len+1, &tmp, sizeof(zval *), NULL); if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (fetch_type == ZEND_FETCH_LEXICAL) ? ZEND_FETCH_R : ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_STATIC; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ if (fetch_type == ZEND_FETCH_LEXICAL) { znode dummy; zend_do_begin_variable_parse(TSRMLS_C); zend_do_assign(&dummy, &lval, &result TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } else { zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); } CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_fetch_lexical_variable(znode *varname, zend_bool is_ref TSRMLS_DC) /* {{{ */ { znode value; if (Z_STRLEN(varname->u.constant) == sizeof("this") - 1 && memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this") - 1) == 0) { zend_error(E_COMPILE_ERROR, "Cannot use $this as lexical variable"); return; } value.op_type = IS_CONST; ZVAL_NULL(&value.u.constant); Z_TYPE(value.u.constant) |= is_ref ? IS_LEXICAL_REF : IS_LEXICAL_VAR; Z_SET_REFCOUNT_P(&value.u.constant, 1); Z_UNSET_ISREF_P(&value.u.constant); zend_do_fetch_static_variable(varname, &value, is_ref ? ZEND_FETCH_STATIC : ZEND_FETCH_LEXICAL TSRMLS_CC); } /* }}} */ void zend_do_fetch_global_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zend_op *opline; znode lval; znode result; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = fetch_type; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_cast(znode *result, const znode *expr, int type TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CAST; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } /* }}} */ void zend_do_include_or_eval(int type, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_do_extended_fcall_begin(TSRMLS_C); { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INCLUDE_OR_EVAL; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } zend_do_extended_fcall_end(TSRMLS_C); } /* }}} */ void zend_do_indirect_references(znode *result, const znode *num_references, znode *variable TSRMLS_DC) /* {{{ */ { int i; zend_do_end_variable_parse(variable, BP_VAR_R, 0 TSRMLS_CC); for (i=1; i<num_references->u.constant.value.lval; i++) { fetch_simple_variable_ex(result, variable, 0, ZEND_FETCH_R TSRMLS_CC); *variable = *result; } zend_do_begin_variable_parse(TSRMLS_C); fetch_simple_variable(result, variable, 1 TSRMLS_CC); /* there is a chance someone is accessing $this */ if (CG(active_op_array)->scope && CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } /* }}} */ void zend_do_unset(const znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_UNSET_VAR; SET_NODE(opline->op1, variable); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); opline->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_UNSET: last_op->opcode = ZEND_UNSET_VAR; SET_UNUSED(last_op->result); break; case ZEND_FETCH_DIM_UNSET: last_op->opcode = ZEND_UNSET_DIM; SET_UNUSED(last_op->result); break; case ZEND_FETCH_OBJ_UNSET: last_op->opcode = ZEND_UNSET_OBJ; SET_UNUSED(last_op->result); break; } } } /* }}} */ void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_do_end_variable_parse(variable, BP_VAR_IS, 0 TSRMLS_CC); zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { last_op = get_next_op(CG(active_op_array) TSRMLS_CC); last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; SET_NODE(last_op->op1, variable); SET_UNUSED(last_op->op2); last_op->result.var = get_temporary_variable(CG(active_op_array)); last_op->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; break; case ZEND_FETCH_DIM_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_DIM_OBJ; break; case ZEND_FETCH_OBJ_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_PROP_OBJ; break; } } last_op->result_type = IS_TMP_VAR; last_op->extended_value |= type; GET_NODE(result, last_op->result); } /* }}} */ void zend_do_instanceof(znode *result, const znode *expr, const znode *class_znode, int type TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline->opcode == ZEND_FETCH_CLASS) { opline->extended_value |= ZEND_FETCH_CLASS_NO_AUTOLOAD; } } if (expr->op_type == IS_CONST) { zend_error(E_COMPILE_ERROR, "instanceof expects an object instance, constant given"); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INSTANCEOF; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_NODE(opline->op2, class_znode); GET_NODE(result, opline->result); } /* }}} */ void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_bool is_variable; zend_bool push_container = 0; zend_op dummy_opline; if (variable) { if (zend_is_function_or_method_call(array)) { is_variable = 0; } else { is_variable = 1; } /* save the location of FETCH_W instruction(s) */ open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); zend_do_end_variable_parse(array, BP_VAR_W, 0 TSRMLS_CC); if (CG(active_op_array)->last > 0 && CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) { /* Only lock the container if we are fetching from a real container and not $this */ if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1_type == IS_VAR) { CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK; push_container = 1; } } } else { is_variable = 0; open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* save the location of FE_RESET */ foreach_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* Preform array reset */ opline->opcode = ZEND_FE_RESET; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, array); SET_UNUSED(opline->op2); opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0; COPY_NODE(dummy_opline.result, opline->result); if (push_container) { COPY_NODE(dummy_opline.op1, CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1); } else { dummy_opline.op1_type = IS_UNUSED; } zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); /* save the location of FE_FETCH */ as_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FE_FETCH; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); COPY_NODE(opline->op1, dummy_opline.result); opline->extended_value = 0; SET_UNUSED(opline->op2); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_OP_DATA; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); } /* }}} */ void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC) /* {{{ */ { zend_op *opline; znode dummy, value_node; zend_bool assign_by_ref=0; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num]; if (key->op_type != IS_UNUSED) { znode *tmp; /* switch between the key and value... */ tmp = key; key = value; value = tmp; /* Mark extended_value in case both key and value are being used */ opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; } if ((key->op_type != IS_UNUSED) && (key->EA & ZEND_PARSED_REFERENCE_VARIABLE)) { zend_error(E_COMPILE_ERROR, "Key element cannot be a reference"); } if (value->EA & ZEND_PARSED_REFERENCE_VARIABLE) { assign_by_ref = 1; if (!(opline-1)->extended_value) { zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression"); } /* Mark extended_value for assign-by-reference */ opline->extended_value |= ZEND_FE_FETCH_BYREF; CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; } else { zend_op *foreach_copy; zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.op.opline_num]; zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.op.opline_num]; /* Change "write context" into "read context" */ fetch->extended_value = 0; /* reset ZEND_FE_RESET_VARIABLE */ while (fetch != end) { --fetch; if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } if (fetch->opcode == ZEND_SEPARATE) { MAKE_NOP(fetch); } else { fetch->opcode -= 3; /* FETCH_W -> FETCH_R */ } } /* prevent double SWITCH_FREE */ zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy); foreach_copy->op1_type = IS_UNUSED; } GET_NODE(&value_node, opline->result); if (assign_by_ref) { zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); /* Mark FE_FETCH as IS_VAR as it holds the data directly as a value */ zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC); } else { zend_do_assign(&dummy, value, &value_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } if (key->op_type != IS_UNUSED) { znode key_node; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num+1]; opline->result_type = IS_TMP_VAR; opline->result.opline_num = get_temporary_variable(CG(active_op_array)); GET_NODE(&key_node, opline->result); zend_do_assign(&dummy, key, &key_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_foreach_end(const znode *foreach_token, const znode *as_token TSRMLS_DC) /* {{{ */ { zend_op *container_ptr; zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = as_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_RESET */ CG(active_op_array)->opcodes[as_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_FETCH */ do_end_loop(as_token->u.op.opline_num, 1 TSRMLS_CC); zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr); generate_free_foreach_copy(container_ptr TSRMLS_CC); zend_stack_del_top(&CG(foreach_copy_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_declare_begin(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(declare_stack), &CG(declarables), sizeof(zend_declarables)); } /* }}} */ void zend_do_declare_stmt(znode *var, znode *val TSRMLS_DC) /* {{{ */ { if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "ticks", sizeof("ticks")-1)) { convert_to_long(&val->u.constant); CG(declarables).ticks = val->u.constant; } else if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "encoding", sizeof("encoding")-1)) { if ((Z_TYPE(val->u.constant) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Cannot use constants as encoding"); } /* * Check that the pragma comes before any opcodes. If the compilation * got as far as this, the previous portion of the script must have been * parseable according to the .ini script_encoding setting. We still * want to tell them to put declare() at the top. */ { int num = CG(active_op_array)->last; /* ignore ZEND_EXT_STMT and ZEND_TICKS */ while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Encoding declaration pragma must be the very first statement in the script"); } } if (CG(multibyte)) { const zend_encoding *new_encoding, *old_encoding; zend_encoding_filter old_input_filter; CG(encoding_declared) = 1; convert_to_string(&val->u.constant); new_encoding = zend_multibyte_fetch_encoding(val->u.constant.value.str.val TSRMLS_CC); if (!new_encoding) { zend_error(E_COMPILE_WARNING, "Unsupported encoding [%s]", val->u.constant.value.str.val); } else { old_input_filter = LANG_SCNG(input_filter); old_encoding = LANG_SCNG(script_encoding); zend_multibyte_set_filter(new_encoding TSRMLS_CC); /* need to re-scan if input filter changed */ if (old_input_filter != LANG_SCNG(input_filter) || (old_input_filter && new_encoding != old_encoding)) { zend_multibyte_yyinput_again(old_input_filter, old_encoding TSRMLS_CC); } } } else { zend_error(E_COMPILE_WARNING, "declare(encoding=...) ignored because Zend multibyte feature is turned off by settings"); } zval_dtor(&val->u.constant); } else { zend_error(E_COMPILE_WARNING, "Unsupported declare '%s'", var->u.constant.value.str.val); zval_dtor(&val->u.constant); } zval_dtor(&var->u.constant); } /* }}} */ void zend_do_declare_end(const znode *declare_token TSRMLS_DC) /* {{{ */ { zend_declarables *declarables; zend_stack_top(&CG(declare_stack), (void **) &declarables); /* We should restore if there was more than (current - start) - (ticks?1:0) opcodes */ if ((get_next_op_number(CG(active_op_array)) - declare_token->u.op.opline_num) - ((Z_LVAL(CG(declarables).ticks))?1:0)) { CG(declarables) = *declarables; } } /* }}} */ void zend_do_exit(znode *result, const znode *message TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXIT; SET_NODE(opline->op1, message); SET_UNUSED(opline->op2); result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_BOOL; Z_LVAL(result->u.constant) = 1; } /* }}} */ void zend_do_begin_silence(znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BEGIN_SILENCE; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); GET_NODE(strudel_token, opline->result); } /* }}} */ void zend_do_end_silence(const znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_END_SILENCE; SET_NODE(opline->op1, strudel_token); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_jmp_set(const znode *value, znode *jmp_token, znode *colon_token TSRMLS_DC) /* {{{ */ { int op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (value->op_type == IS_VAR || value->op_type == IS_CV) { opline->opcode = ZEND_JMP_SET_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_JMP_SET; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, value); SET_UNUSED(opline->op2); GET_NODE(colon_token, opline->result); jmp_token->u.op .opline_num = op_number; INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_jmp_set_else(znode *result, const znode *false_value, const znode *jmp_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, colon_token); if (colon_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].opcode = ZEND_JMP_SET_VAR; CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } opline->extended_value = 0; SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_qm_op(const znode *cond, znode *qm_token TSRMLS_DC) /* {{{ */ { int jmpz_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); SET_UNUSED(opline->op2); opline->op2.opline_num = jmpz_op_number; GET_NODE(qm_token, opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_qm_true(const znode *true_value, znode *qm_token, znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->opcodes[qm_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array))+1; /* jmp over the ZEND_JMP */ if (true_value->op_type == IS_VAR || true_value->op_type == IS_CV) { opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, true_value); SET_UNUSED(opline->op2); GET_NODE(qm_token, opline->result); colon_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_qm_false(znode *result, const znode *false_value, const znode *qm_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, qm_token); if (qm_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].opcode = ZEND_QM_ASSIGN_VAR; CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[colon_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, opline->result); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_extended_info(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_STMT; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_begin(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_BEGIN; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_end(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_END; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_ticks(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_TICKS; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->extended_value = Z_LVAL(CG(declarables).ticks); } /* }}} */ zend_bool zend_is_auto_global_quick(const char *name, uint name_len, ulong hashval TSRMLS_DC) /* {{{ */ { zend_auto_global *auto_global; ulong hash = hashval ? hashval : zend_hash_func(name, name_len+1); if (zend_hash_quick_find(CG(auto_globals), name, name_len+1, hash, (void **) &auto_global)==SUCCESS) { if (auto_global->armed) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } return 1; } return 0; } /* }}} */ zend_bool zend_is_auto_global(const char *name, uint name_len TSRMLS_DC) /* {{{ */ { return zend_is_auto_global_quick(name, name_len, 0 TSRMLS_CC); } /* }}} */ int zend_register_auto_global(const char *name, uint name_len, zend_bool jit, zend_auto_global_callback auto_global_callback TSRMLS_DC) /* {{{ */ { zend_auto_global auto_global; auto_global.name = zend_new_interned_string((char*)name, name_len + 1, 0 TSRMLS_CC); auto_global.name_len = name_len; auto_global.auto_global_callback = auto_global_callback; auto_global.jit = jit; return zend_hash_add(CG(auto_globals), name, name_len+1, &auto_global, sizeof(zend_auto_global), NULL); } /* }}} */ static int zend_auto_global_init(zend_auto_global *auto_global TSRMLS_DC) /* {{{ */ { if (auto_global->jit) { auto_global->armed = 1; } else if (auto_global->auto_global_callback) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } else { auto_global->armed = 0; } return 0; } /* }}} */ ZEND_API void zend_activate_auto_globals(TSRMLS_D) /* {{{ */ { zend_hash_apply(CG(auto_globals), (apply_func_t) zend_auto_global_init TSRMLS_CC); } /* }}} */ int zendlex(znode *zendlval TSRMLS_DC) /* {{{ */ { int retval; if (CG(increment_lineno)) { CG(zend_lineno)++; CG(increment_lineno) = 0; } again: Z_TYPE(zendlval->u.constant) = IS_LONG; retval = lex_scan(&zendlval->u.constant TSRMLS_CC); switch (retval) { case T_COMMENT: case T_DOC_COMMENT: case T_OPEN_TAG: case T_WHITESPACE: goto again; case T_CLOSE_TAG: if (LANG_SCNG(yy_text)[LANG_SCNG(yy_leng)-1] != '>') { CG(increment_lineno) = 1; } if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { goto again; } retval = ';'; /* implicit ; */ break; case T_OPEN_TAG_WITH_ECHO: retval = T_ECHO; break; case T_END_HEREDOC: efree(Z_STRVAL(zendlval->u.constant)); break; } INIT_PZVAL(&zendlval->u.constant); zendlval->op_type = IS_CONST; return retval; } /* }}} */ ZEND_API void zend_initialize_class_data(zend_class_entry *ce, zend_bool nullify_handlers TSRMLS_DC) /* {{{ */ { zend_bool persistent_hashes = (ce->type == ZEND_INTERNAL_CLASS) ? 1 : 0; dtor_func_t zval_ptr_dtor_func = ((persistent_hashes) ? ZVAL_INTERNAL_PTR_DTOR : ZVAL_PTR_DTOR); ce->refcount = 1; ce->ce_flags = 0; ce->default_properties_table = NULL; ce->default_static_members_table = NULL; zend_hash_init_ex(&ce->properties_info, 0, NULL, (dtor_func_t) (persistent_hashes ? zend_destroy_property_info_internal : zend_destroy_property_info), persistent_hashes, 0); zend_hash_init_ex(&ce->constants_table, 0, NULL, zval_ptr_dtor_func, persistent_hashes, 0); zend_hash_init_ex(&ce->function_table, 0, NULL, ZEND_FUNCTION_DTOR, persistent_hashes, 0); if (ce->type == ZEND_INTERNAL_CLASS) { #ifdef ZTS int n = zend_hash_num_elements(CG(class_table)); if (CG(static_members_table) && n >= CG(last_static_member)) { /* Support for run-time declaration: dl() */ CG(last_static_member) = n+1; CG(static_members_table) = realloc(CG(static_members_table), (n+1)*sizeof(zval**)); CG(static_members_table)[n] = NULL; } ce->static_members_table = (zval**)(zend_intptr_t)n; #else ce->static_members_table = NULL; #endif } else { ce->static_members_table = ce->default_static_members_table; ce->info.user.doc_comment = NULL; ce->info.user.doc_comment_len = 0; } ce->default_properties_count = 0; ce->default_static_members_count = 0; if (nullify_handlers) { ce->constructor = NULL; ce->destructor = NULL; ce->clone = NULL; ce->__get = NULL; ce->__set = NULL; ce->__unset = NULL; ce->__isset = NULL; ce->__call = NULL; ce->__callstatic = NULL; ce->__tostring = NULL; ce->create_object = NULL; ce->get_iterator = NULL; ce->iterator_funcs.funcs = NULL; ce->interface_gets_implemented = NULL; ce->get_static_method = NULL; ce->parent = NULL; ce->num_interfaces = 0; ce->interfaces = NULL; ce->num_traits = 0; ce->traits = NULL; ce->trait_aliases = NULL; ce->trait_precedences = NULL; ce->serialize = NULL; ce->unserialize = NULL; ce->serialize_func = NULL; ce->unserialize_func = NULL; if (ce->type == ZEND_INTERNAL_CLASS) { ce->info.internal.module = NULL; ce->info.internal.builtin_functions = NULL; } } } /* }}} */ int zend_get_class_fetch_type(const char *class_name, uint class_name_len) /* {{{ */ { if ((class_name_len == sizeof("self")-1) && !memcmp(class_name, "self", sizeof("self")-1)) { return ZEND_FETCH_CLASS_SELF; } else if ((class_name_len == sizeof("parent")-1) && !memcmp(class_name, "parent", sizeof("parent")-1)) { return ZEND_FETCH_CLASS_PARENT; } else if ((class_name_len == sizeof("static")-1) && !memcmp(class_name, "static", sizeof("static")-1)) { return ZEND_FETCH_CLASS_STATIC; } else { return ZEND_FETCH_CLASS_DEFAULT; } } /* }}} */ ZEND_API const char* zend_get_compiled_variable_name(const zend_op_array *op_array, zend_uint var, int* name_len) /* {{{ */ { if (name_len) { *name_len = op_array->vars[var].name_len; } return op_array->vars[var].name; } /* }}} */ void zend_do_build_namespace_name(znode *result, znode *prefix, znode *name TSRMLS_DC) /* {{{ */ { if (prefix) { *result = *prefix; if (Z_TYPE(result->u.constant) == IS_STRING && Z_STRLEN(result->u.constant) == 0) { /* namespace\ */ if (CG(current_namespace)) { znode tmp; zval_dtor(&result->u.constant); tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(result, NULL, &tmp TSRMLS_CC); } } } else { result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_STRING; Z_STRVAL(result->u.constant) = NULL; Z_STRLEN(result->u.constant) = 0; } /* prefix = result */ zend_do_build_full_name(NULL, result, name, 0 TSRMLS_CC); } /* }}} */ void zend_do_begin_namespace(const znode *name, zend_bool with_bracket TSRMLS_DC) /* {{{ */ { char *lcname; /* handle mixed syntax declaration or nested namespaces */ if (!CG(has_bracketed_namespaces)) { if (CG(current_namespace)) { /* previous namespace declarations were unbracketed */ if (with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } } } else { /* previous namespace declarations were bracketed */ if (!with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } else if (CG(current_namespace) || CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "Namespace declarations cannot be nested"); } } if (((!with_bracket && !CG(current_namespace)) || (with_bracket && !CG(has_bracketed_namespaces))) && CG(active_op_array)->last > 0) { /* ignore ZEND_EXT_STMT and ZEND_TICKS */ int num = CG(active_op_array)->last; while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Namespace declaration statement has to be the very first statement in the script"); } } CG(in_namespace) = 1; if (with_bracket) { CG(has_bracketed_namespaces) = 1; } if (name) { lcname = zend_str_tolower_dup(Z_STRVAL(name->u.constant), Z_STRLEN(name->u.constant)); if (((Z_STRLEN(name->u.constant) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN(name->u.constant) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as namespace name", Z_STRVAL(name->u.constant)); } efree(lcname); if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); } else { ALLOC_ZVAL(CG(current_namespace)); } *CG(current_namespace) = name->u.constant; } else { if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_use(znode *ns_name, znode *new_name, int is_global TSRMLS_DC) /* {{{ */ { char *lcname; zval *name, *ns, tmp; zend_bool warn = 0; zend_class_entry **pce; if (!CG(current_import)) { CG(current_import) = emalloc(sizeof(HashTable)); zend_hash_init(CG(current_import), 0, NULL, ZVAL_PTR_DTOR, 0); } ALLOC_ZVAL(ns); *ns = ns_name->u.constant; if (new_name) { name = &new_name->u.constant; } else { const char *p; /* The form "use A\B" is eqivalent to "use A\B as B". So we extract the last part of compound name to use as a new_name */ name = &tmp; p = zend_memrchr(Z_STRVAL_P(ns), '\\', Z_STRLEN_P(ns)); if (p) { ZVAL_STRING(name, p+1, 1); } else { *name = *ns; zval_copy_ctor(name); warn = !is_global && !CG(current_namespace); } } lcname = zend_str_tolower_dup(Z_STRVAL_P(name), Z_STRLEN_P(name)); if (((Z_STRLEN_P(name) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN_P(name) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because '%s' is a special class name", Z_STRVAL_P(ns), Z_STRVAL_P(name), Z_STRVAL_P(name)); } if (CG(current_namespace)) { /* Prefix import name with current namespace name to avoid conflicts with classes */ char *c_ns_name = emalloc(Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) + 1); zend_str_tolower_copy(c_ns_name, Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); c_ns_name[Z_STRLEN_P(CG(current_namespace))] = '\\'; memcpy(c_ns_name+Z_STRLEN_P(CG(current_namespace))+1, lcname, Z_STRLEN_P(name)+1); if (zend_hash_exists(CG(class_table), c_ns_name, Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name)+1)) { char *tmp2 = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) || memcmp(tmp2, c_ns_name, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(tmp2); } efree(c_ns_name); } else if (zend_hash_find(CG(class_table), lcname, Z_STRLEN_P(name)+1, (void**)&pce) == SUCCESS && (*pce)->type == ZEND_USER_CLASS && (*pce)->info.user.filename == CG(compiled_filename)) { char *c_tmp = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(name) || memcmp(c_tmp, lcname, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(c_tmp); } if (zend_hash_add(CG(current_import), lcname, Z_STRLEN_P(name)+1, &ns, sizeof(zval*), NULL) != SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } if (warn) { if (!strcmp(Z_STRVAL_P(name), "strict")) { zend_error(E_COMPILE_ERROR, "You seem to be trying to use a different language..."); } zend_error(E_WARNING, "The use statement with non-compound name '%s' has no effect", Z_STRVAL_P(name)); } efree(lcname); zval_dtor(name); } /* }}} */ void zend_do_declare_constant(znode *name, znode *value TSRMLS_DC) /* {{{ */ { zend_op *opline; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed as constants"); } if (zend_get_ct_const(&name->u.constant, 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare constant '%s'", Z_STRVAL(name->u.constant)); } if (CG(current_namespace)) { /* Prefix constant name with name of current namespace, lowercased */ znode tmp; tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); Z_STRVAL(tmp.u.constant) = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), Z_STRLEN(tmp.u.constant)); zend_do_build_namespace_name(&tmp, &tmp, name TSRMLS_CC); *name = tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DECLARE_CONST; SET_UNUSED(opline->result); SET_NODE(opline->op1, name); SET_NODE(opline->op2, value); } /* }}} */ void zend_verify_namespace(TSRMLS_D) /* {{{ */ { if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "No code may exist outside of namespace {}"); } } /* }}} */ void zend_do_end_namespace(TSRMLS_D) /* {{{ */ { CG(in_namespace) = 0; if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_end_compilation(TSRMLS_D) /* {{{ */ { CG(has_bracketed_namespaces) = 0; zend_do_end_namespace(TSRMLS_C); } /* }}} */ /* {{{ zend_dirname Returns directory name component of path */ ZEND_API size_t zend_dirname(char *path, size_t len) { register char *end = path + len - 1; unsigned int len_adjust = 0; #ifdef PHP_WIN32 /* Note that on Win32 CWD is per drive (heritage from CP/M). * This means dirname("c:foo") maps to "c:." or "c:" - which means CWD on C: drive. */ if ((2 <= len) && isalpha((int)((unsigned char *)path)[0]) && (':' == path[1])) { /* Skip over the drive spec (if any) so as not to change */ path += 2; len_adjust += 2; if (2 == len) { /* Return "c:" on Win32 for dirname("c:"). * It would be more consistent to return "c:." * but that would require making the string *longer*. */ return len; } } #elif defined(NETWARE) /* * Find the first occurence of : from the left * move the path pointer to the position just after : * increment the len_adjust to the length of path till colon character(inclusive) * If there is no character beyond : simple return len */ char *colonpos = NULL; colonpos = strchr(path, ':'); if (colonpos != NULL) { len_adjust = ((colonpos - path) + 1); path += len_adjust; if (len_adjust == len) { return len; } } #endif if (len == 0) { /* Illegal use of this function */ return 0; } /* Strip trailing slashes */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { /* The path only contained slashes */ path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } /* Strip filename */ while (end >= path && !IS_SLASH_P(end)) { end--; } if (end < path) { /* No slash found, therefore return '.' */ #ifdef NETWARE if (len_adjust == 0) { path[0] = '.'; path[1] = '\0'; return 1; /* only one character */ } else { path[0] = '\0'; return len_adjust; } #else path[0] = '.'; path[1] = '\0'; return 1 + len_adjust; #endif } /* Strip slashes which came before the file name */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } *(end+1) = '\0'; return (size_t)(end + 1 - path) + len_adjust; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-10-31-2e5d5e5ac6-b5f15ef561.c
manybugs_data_87
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Timm Friebe <[email protected]> | | George Schlossnagle <[email protected]> | | Andrei Zmievski <[email protected]> | | Marcus Boerger <[email protected]> | | Johannes Schlueter <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ini.h" #include "php_reflection.h" #include "ext/standard/info.h" #include "zend.h" #include "zend_API.h" #include "zend_exceptions.h" #include "zend_operators.h" #include "zend_constants.h" #include "zend_ini.h" #include "zend_interfaces.h" #include "zend_closures.h" #include "zend_extensions.h" #define reflection_update_property(object, name, value) do { \ zval *member; \ MAKE_STD_ZVAL(member); \ ZVAL_STRINGL(member, name, sizeof(name)-1, 1); \ zend_std_write_property(object, member, value, NULL TSRMLS_CC); \ Z_DELREF_P(value); \ zval_ptr_dtor(&member); \ } while (0) /* Class entry pointers */ PHPAPI zend_class_entry *reflector_ptr; PHPAPI zend_class_entry *reflection_exception_ptr; PHPAPI zend_class_entry *reflection_ptr; PHPAPI zend_class_entry *reflection_function_abstract_ptr; PHPAPI zend_class_entry *reflection_function_ptr; PHPAPI zend_class_entry *reflection_parameter_ptr; PHPAPI zend_class_entry *reflection_class_ptr; PHPAPI zend_class_entry *reflection_object_ptr; PHPAPI zend_class_entry *reflection_method_ptr; PHPAPI zend_class_entry *reflection_property_ptr; PHPAPI zend_class_entry *reflection_extension_ptr; PHPAPI zend_class_entry *reflection_zend_extension_ptr; #if MBO_0 ZEND_BEGIN_MODULE_GLOBALS(reflection) int dummy; ZEND_END_MODULE_GLOBALS(reflection) #ifdef ZTS # define REFLECTION_G(v) \ TSRMG(reflection_globals_id, zend_reflection_globals*, v) extern int reflection_globals_id; #else # define REFLECTION_G(v) (reflection_globals.v) extern zend_reflection_globals reflectionglobals; #endif ZEND_DECLARE_MODULE_GLOBALS(reflection) #endif /* MBO_0 */ /* Method macros */ #define METHOD_NOTSTATIC(ce) \ if (!this_ptr || !instanceof_function(Z_OBJCE_P(this_ptr), ce TSRMLS_CC)) { \ php_error_docref(NULL TSRMLS_CC, E_ERROR, "%s() cannot be called statically", get_active_function_name(TSRMLS_C)); \ return; \ } \ /* Exception throwing macro */ #define _DO_THROW(msg) \ zend_throw_exception(reflection_exception_ptr, msg, 0 TSRMLS_CC); \ return; \ #define RETURN_ON_EXCEPTION \ if (EG(exception) && Z_OBJCE_P(EG(exception)) == reflection_exception_ptr) { \ return; \ } #define GET_REFLECTION_OBJECT_PTR(target) \ intern = (reflection_object *) zend_object_store_get_object(getThis() TSRMLS_CC); \ if (intern == NULL || intern->ptr == NULL) { \ RETURN_ON_EXCEPTION \ php_error_docref(NULL TSRMLS_CC, E_ERROR, "Internal error: Failed to retrieve the reflection object"); \ } \ target = intern->ptr; \ /* Class constants */ #define REGISTER_REFLECTION_CLASS_CONST_LONG(class_name, const_name, value) \ zend_declare_class_constant_long(reflection_ ## class_name ## _ptr, const_name, sizeof(const_name)-1, (long)value TSRMLS_CC); /* {{{ Smart string functions */ typedef struct _string { char *string; int len; int alloced; } string; static void string_init(string *str) { str->string = (char *) emalloc(1024); str->len = 1; str->alloced = 1024; *str->string = '\0'; } static string *string_printf(string *str, const char *format, ...) { int len; va_list arg; char *s_tmp; va_start(arg, format); len = zend_vspprintf(&s_tmp, 0, format, arg); if (len) { register int nlen = (str->len + len + (1024 - 1)) & ~(1024 - 1); if (str->alloced < nlen) { str->alloced = nlen; str->string = erealloc(str->string, str->alloced); } memcpy(str->string + str->len - 1, s_tmp, len + 1); str->len += len; } efree(s_tmp); va_end(arg); return str; } static string *string_write(string *str, char *buf, int len) { register int nlen = (str->len + len + (1024 - 1)) & ~(1024 - 1); if (str->alloced < nlen) { str->alloced = nlen; str->string = erealloc(str->string, str->alloced); } memcpy(str->string + str->len - 1, buf, len); str->len += len; str->string[str->len - 1] = '\0'; return str; } static string *string_append(string *str, string *append) { if (append->len > 1) { string_write(str, append->string, append->len - 1); } return str; } static void string_free(string *str) { efree(str->string); str->len = 0; str->alloced = 0; str->string = NULL; } /* }}} */ /* {{{ Object structure */ /* Struct for properties */ typedef struct _property_reference { zend_class_entry *ce; zend_property_info prop; } property_reference; /* Struct for parameters */ typedef struct _parameter_reference { zend_uint offset; zend_uint required; struct _zend_arg_info *arg_info; zend_function *fptr; } parameter_reference; typedef enum { REF_TYPE_OTHER, /* Must be 0 */ REF_TYPE_FUNCTION, REF_TYPE_PARAMETER, REF_TYPE_PROPERTY, REF_TYPE_DYNAMIC_PROPERTY } reflection_type_t; /* Struct for reflection objects */ typedef struct { zend_object zo; void *ptr; reflection_type_t ref_type; zval *obj; zend_class_entry *ce; unsigned int ignore_visibility:1; } reflection_object; /* }}} */ static zend_object_handlers reflection_object_handlers; static void _default_get_entry(zval *object, char *name, int name_len, zval *return_value TSRMLS_DC) /* {{{ */ { zval **value; if (zend_hash_find(Z_OBJPROP_P(object), name, name_len, (void **) &value) == FAILURE) { RETURN_FALSE; } MAKE_COPY_ZVAL(value, return_value); } /* }}} */ #ifdef ilia_0 static void _default_lookup_entry(zval *object, char *name, int name_len, zval **return_value TSRMLS_DC) /* {{{ */ { zval **value; if (zend_hash_find(Z_OBJPROP_P(object), name, name_len, (void **) &value) == FAILURE) { *return_value = NULL; } else { *return_value = *value; } } /* }}} */ #endif static void reflection_register_implement(zend_class_entry *class_entry, zend_class_entry *interface_entry TSRMLS_DC) /* {{{ */ { zend_uint num_interfaces = ++class_entry->num_interfaces; class_entry->interfaces = (zend_class_entry **) realloc(class_entry->interfaces, sizeof(zend_class_entry *) * num_interfaces); class_entry->interfaces[num_interfaces - 1] = interface_entry; } /* }}} */ static zend_function *_copy_function(zend_function *fptr TSRMLS_DC) /* {{{ */ { if (fptr && fptr->type == ZEND_INTERNAL_FUNCTION && (fptr->internal_function.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) != 0) { zend_function *copy_fptr; copy_fptr = emalloc(sizeof(zend_function)); memcpy(copy_fptr, fptr, sizeof(zend_function)); copy_fptr->internal_function.function_name = estrdup(fptr->internal_function.function_name); return copy_fptr; } else { /* no copy needed */ return fptr; } } /* }}} */ static void _free_function(zend_function *fptr TSRMLS_DC) /* {{{ */ { if (fptr && fptr->type == ZEND_INTERNAL_FUNCTION && (fptr->internal_function.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) != 0) { efree((char*)fptr->internal_function.function_name); efree(fptr); } } /* }}} */ static void reflection_free_objects_storage(void *object TSRMLS_DC) /* {{{ */ { reflection_object *intern = (reflection_object *) object; parameter_reference *reference; property_reference *prop_reference; if (intern->ptr) { switch (intern->ref_type) { case REF_TYPE_PARAMETER: reference = (parameter_reference*)intern->ptr; _free_function(reference->fptr TSRMLS_CC); efree(intern->ptr); break; case REF_TYPE_FUNCTION: _free_function(intern->ptr TSRMLS_CC); break; case REF_TYPE_PROPERTY: efree(intern->ptr); break; case REF_TYPE_DYNAMIC_PROPERTY: prop_reference = (property_reference*)intern->ptr; efree((char*)prop_reference->prop.name); efree(intern->ptr); break; case REF_TYPE_OTHER: break; } } intern->ptr = NULL; if (intern->obj) { zval_ptr_dtor(&intern->obj); } zend_objects_free_object_storage(object TSRMLS_CC); } /* }}} */ static zend_object_value reflection_objects_new(zend_class_entry *class_type TSRMLS_DC) /* {{{ */ { zend_object_value retval; reflection_object *intern; intern = ecalloc(1, sizeof(reflection_object)); intern->zo.ce = class_type; zend_object_std_init(&intern->zo, class_type TSRMLS_CC); object_properties_init(&intern->zo, class_type); retval.handle = zend_objects_store_put(intern, NULL, reflection_free_objects_storage, NULL TSRMLS_CC); retval.handlers = &reflection_object_handlers; return retval; } /* }}} */ static zval * reflection_instantiate(zend_class_entry *pce, zval *object TSRMLS_DC) /* {{{ */ { if (!object) { ALLOC_ZVAL(object); } Z_TYPE_P(object) = IS_OBJECT; object_init_ex(object, pce); Z_SET_REFCOUNT_P(object, 1); Z_SET_ISREF_P(object); return object; } /* }}} */ static void _const_string(string *str, char *name, zval *value, char *indent TSRMLS_DC); static void _function_string(string *str, zend_function *fptr, zend_class_entry *scope, char* indent TSRMLS_DC); static void _property_string(string *str, zend_property_info *prop, char *prop_name, char* indent TSRMLS_DC); static void _class_string(string *str, zend_class_entry *ce, zval *obj, char *indent TSRMLS_DC); static void _extension_string(string *str, zend_module_entry *module, char *indent TSRMLS_DC); static void _zend_extension_string(string *str, zend_extension *extension, char *indent TSRMLS_DC); /* {{{ _class_string */ static void _class_string(string *str, zend_class_entry *ce, zval *obj, char *indent TSRMLS_DC) { int count, count_static_props = 0, count_static_funcs = 0, count_shadow_props = 0; string sub_indent; string_init(&sub_indent); string_printf(&sub_indent, "%s ", indent); /* TBD: Repair indenting of doc comment (or is this to be done in the parser?) */ if (ce->type == ZEND_USER_CLASS && ce->info.user.doc_comment) { string_printf(str, "%s%s", indent, ce->info.user.doc_comment); string_write(str, "\n", 1); } if (obj) { string_printf(str, "%sObject of class [ ", indent); } else { char *kind = "Class"; if (ce->ce_flags & ZEND_ACC_INTERFACE) { kind = "Interface"; } else if ((ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { kind = "Trait"; } string_printf(str, "%s%s [ ", indent, kind); } string_printf(str, (ce->type == ZEND_USER_CLASS) ? "<user" : "<internal"); if (ce->type == ZEND_INTERNAL_CLASS && ce->info.internal.module) { string_printf(str, ":%s", ce->info.internal.module->name); } string_printf(str, "> "); if (ce->get_iterator != NULL) { string_printf(str, "<iterateable> "); } if (ce->ce_flags & ZEND_ACC_INTERFACE) { string_printf(str, "interface "); } else if ((ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { string_printf(str, "trait "); } else { if (ce->ce_flags & (ZEND_ACC_IMPLICIT_ABSTRACT_CLASS|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) { string_printf(str, "abstract "); } if (ce->ce_flags & ZEND_ACC_FINAL_CLASS) { string_printf(str, "final "); } string_printf(str, "class "); } string_printf(str, "%s", ce->name); if (ce->parent) { string_printf(str, " extends %s", ce->parent->name); } if (ce->num_interfaces) { zend_uint i; if (ce->ce_flags & ZEND_ACC_INTERFACE) { string_printf(str, " extends %s", ce->interfaces[0]->name); } else { string_printf(str, " implements %s", ce->interfaces[0]->name); } for (i = 1; i < ce->num_interfaces; ++i) { string_printf(str, ", %s", ce->interfaces[i]->name); } } string_printf(str, " ] {\n"); /* The information where a class is declared is only available for user classes */ if (ce->type == ZEND_USER_CLASS) { string_printf(str, "%s @@ %s %d-%d\n", indent, ce->info.user.filename, ce->info.user.line_start, ce->info.user.line_end); } /* Constants */ if (&ce->constants_table) { zend_hash_apply_with_argument(&ce->constants_table, (apply_func_arg_t) zval_update_constant, (void*)1 TSRMLS_CC); string_printf(str, "\n"); count = zend_hash_num_elements(&ce->constants_table); string_printf(str, "%s - Constants [%d] {\n", indent, count); if (count > 0) { HashPosition pos; zval **value; char *key; uint key_len; ulong num_index; zend_hash_internal_pointer_reset_ex(&ce->constants_table, &pos); while (zend_hash_get_current_data_ex(&ce->constants_table, (void **) &value, &pos) == SUCCESS) { zend_hash_get_current_key_ex(&ce->constants_table, &key, &key_len, &num_index, 0, &pos); _const_string(str, key, *value, indent TSRMLS_CC); zend_hash_move_forward_ex(&ce->constants_table, &pos); } } string_printf(str, "%s }\n", indent); } /* Static properties */ if (&ce->properties_info) { /* counting static properties */ count = zend_hash_num_elements(&ce->properties_info); if (count > 0) { HashPosition pos; zend_property_info *prop; zend_hash_internal_pointer_reset_ex(&ce->properties_info, &pos); while (zend_hash_get_current_data_ex(&ce->properties_info, (void **) &prop, &pos) == SUCCESS) { if(prop->flags & ZEND_ACC_SHADOW) { count_shadow_props++; } else if (prop->flags & ZEND_ACC_STATIC) { count_static_props++; } zend_hash_move_forward_ex(&ce->properties_info, &pos); } } /* static properties */ string_printf(str, "\n%s - Static properties [%d] {\n", indent, count_static_props); if (count_static_props > 0) { HashPosition pos; zend_property_info *prop; zend_hash_internal_pointer_reset_ex(&ce->properties_info, &pos); while (zend_hash_get_current_data_ex(&ce->properties_info, (void **) &prop, &pos) == SUCCESS) { if ((prop->flags & ZEND_ACC_STATIC) && !(prop->flags & ZEND_ACC_SHADOW)) { _property_string(str, prop, NULL, sub_indent.string TSRMLS_CC); } zend_hash_move_forward_ex(&ce->properties_info, &pos); } } string_printf(str, "%s }\n", indent); } /* Static methods */ if (&ce->function_table) { /* counting static methods */ count = zend_hash_num_elements(&ce->function_table); if (count > 0) { HashPosition pos; zend_function *mptr; zend_hash_internal_pointer_reset_ex(&ce->function_table, &pos); while (zend_hash_get_current_data_ex(&ce->function_table, (void **) &mptr, &pos) == SUCCESS) { if (mptr->common.fn_flags & ZEND_ACC_STATIC && ((mptr->common.fn_flags & ZEND_ACC_PRIVATE) == 0 || mptr->common.scope == ce)) { count_static_funcs++; } zend_hash_move_forward_ex(&ce->function_table, &pos); } } /* static methods */ string_printf(str, "\n%s - Static methods [%d] {", indent, count_static_funcs); if (count_static_funcs > 0) { HashPosition pos; zend_function *mptr; zend_hash_internal_pointer_reset_ex(&ce->function_table, &pos); while (zend_hash_get_current_data_ex(&ce->function_table, (void **) &mptr, &pos) == SUCCESS) { if (mptr->common.fn_flags & ZEND_ACC_STATIC && ((mptr->common.fn_flags & ZEND_ACC_PRIVATE) == 0 || mptr->common.scope == ce)) { string_printf(str, "\n"); _function_string(str, mptr, ce, sub_indent.string TSRMLS_CC); } zend_hash_move_forward_ex(&ce->function_table, &pos); } } else { string_printf(str, "\n"); } string_printf(str, "%s }\n", indent); } /* Default/Implicit properties */ if (&ce->properties_info) { count = zend_hash_num_elements(&ce->properties_info) - count_static_props - count_shadow_props; string_printf(str, "\n%s - Properties [%d] {\n", indent, count); if (count > 0) { HashPosition pos; zend_property_info *prop; zend_hash_internal_pointer_reset_ex(&ce->properties_info, &pos); while (zend_hash_get_current_data_ex(&ce->properties_info, (void **) &prop, &pos) == SUCCESS) { if (!(prop->flags & (ZEND_ACC_STATIC|ZEND_ACC_SHADOW))) { _property_string(str, prop, NULL, sub_indent.string TSRMLS_CC); } zend_hash_move_forward_ex(&ce->properties_info, &pos); } } string_printf(str, "%s }\n", indent); } if (obj && Z_OBJ_HT_P(obj)->get_properties) { string dyn; HashTable *properties = Z_OBJ_HT_P(obj)->get_properties(obj TSRMLS_CC); HashPosition pos; zval **prop; string_init(&dyn); count = 0; if (properties && zend_hash_num_elements(properties)) { zend_hash_internal_pointer_reset_ex(properties, &pos); while (zend_hash_get_current_data_ex(properties, (void **) &prop, &pos) == SUCCESS) { char *prop_name; uint prop_name_size; ulong index; if (zend_hash_get_current_key_ex(properties, &prop_name, &prop_name_size, &index, 1, &pos) == HASH_KEY_IS_STRING) { if (prop_name_size && prop_name[0]) { /* skip all private and protected properties */ if (!zend_hash_quick_exists(&ce->properties_info, prop_name, prop_name_size, zend_get_hash_value(prop_name, prop_name_size))) { count++; _property_string(&dyn, NULL, prop_name, sub_indent.string TSRMLS_CC); } } efree(prop_name); } zend_hash_move_forward_ex(properties, &pos); } } string_printf(str, "\n%s - Dynamic properties [%d] {\n", indent, count); string_append(str, &dyn); string_printf(str, "%s }\n", indent); string_free(&dyn); } /* Non static methods */ if (&ce->function_table) { count = zend_hash_num_elements(&ce->function_table) - count_static_funcs; if (count > 0) { HashPosition pos; zend_function *mptr; string dyn; count = 0; string_init(&dyn); zend_hash_internal_pointer_reset_ex(&ce->function_table, &pos); while (zend_hash_get_current_data_ex(&ce->function_table, (void **) &mptr, &pos) == SUCCESS) { if ((mptr->common.fn_flags & ZEND_ACC_STATIC) == 0 && ((mptr->common.fn_flags & ZEND_ACC_PRIVATE) == 0 || mptr->common.scope == ce)) { char *key; uint key_len; ulong num_index; uint len = strlen(mptr->common.function_name); /* Do not display old-style inherited constructors */ if ((mptr->common.fn_flags & ZEND_ACC_CTOR) == 0 || mptr->common.scope == ce || zend_hash_get_current_key_ex(&ce->function_table, &key, &key_len, &num_index, 0, &pos) != HASH_KEY_IS_STRING || zend_binary_strcasecmp(key, key_len-1, mptr->common.function_name, len) == 0) { zend_function *closure; /* see if this is a closure */ if (ce == zend_ce_closure && obj && (len == sizeof(ZEND_INVOKE_FUNC_NAME)-1) && memcmp(mptr->common.function_name, ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME)-1) == 0 && (closure = zend_get_closure_invoke_method(obj TSRMLS_CC)) != NULL) { mptr = closure; } else { closure = NULL; } string_printf(&dyn, "\n"); _function_string(&dyn, mptr, ce, sub_indent.string TSRMLS_CC); count++; _free_function(closure TSRMLS_CC); } } zend_hash_move_forward_ex(&ce->function_table, &pos); } string_printf(str, "\n%s - Methods [%d] {", indent, count); if (!count) { string_printf(str, "\n"); } string_append(str, &dyn); string_free(&dyn); } else { string_printf(str, "\n%s - Methods [0] {\n", indent); } string_printf(str, "%s }\n", indent); } string_printf(str, "%s}\n", indent); string_free(&sub_indent); } /* }}} */ /* {{{ _const_string */ static void _const_string(string *str, char *name, zval *value, char *indent TSRMLS_DC) { char *type; zval value_copy; int use_copy; type = zend_zval_type_name(value); zend_make_printable_zval(value, &value_copy, &use_copy); if (use_copy) { value = &value_copy; } string_printf(str, "%s Constant [ %s %s ] { %s }\n", indent, type, name, Z_STRVAL_P(value)); if (use_copy) { zval_dtor(value); } } /* }}} */ /* {{{ _get_recv_opcode */ static zend_op* _get_recv_op(zend_op_array *op_array, zend_uint offset) { zend_op *op = op_array->opcodes; zend_op *end = op + op_array->last; ++offset; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT) && op->op1.num == (long)offset) { return op; } ++op; } return NULL; } /* }}} */ /* {{{ _parameter_string */ static void _parameter_string(string *str, zend_function *fptr, struct _zend_arg_info *arg_info, zend_uint offset, zend_uint required, char* indent TSRMLS_DC) { string_printf(str, "Parameter #%d [ ", offset); if (offset >= required) { string_printf(str, "<optional> "); } else { string_printf(str, "<required> "); } if (arg_info->class_name) { string_printf(str, "%s ", arg_info->class_name); if (arg_info->allow_null) { string_printf(str, "or NULL "); } } else if (arg_info->type_hint) { string_printf(str, "%s ", zend_get_type_by_const(arg_info->type_hint)); if (arg_info->allow_null) { string_printf(str, "or NULL "); } } if (arg_info->pass_by_reference) { string_write(str, "&", sizeof("&")-1); } if (arg_info->name) { string_printf(str, "$%s", arg_info->name); } else { string_printf(str, "$param%d", offset); } if (fptr->type == ZEND_USER_FUNCTION && offset >= required) { zend_op *precv = _get_recv_op((zend_op_array*)fptr, offset); if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) { zval *zv, zv_copy; int use_copy; string_write(str, " = ", sizeof(" = ")-1); ALLOC_ZVAL(zv); *zv = *precv->op2.zv; zval_copy_ctor(zv); INIT_PZVAL(zv); zval_update_constant_ex(&zv, (void*)1, fptr->common.scope TSRMLS_CC); if (Z_TYPE_P(zv) == IS_BOOL) { if (Z_LVAL_P(zv)) { string_write(str, "true", sizeof("true")-1); } else { string_write(str, "false", sizeof("false")-1); } } else if (Z_TYPE_P(zv) == IS_NULL) { string_write(str, "NULL", sizeof("NULL")-1); } else if (Z_TYPE_P(zv) == IS_STRING) { string_write(str, "'", sizeof("'")-1); string_write(str, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 15)); if (Z_STRLEN_P(zv) > 15) { string_write(str, "...", sizeof("...")-1); } string_write(str, "'", sizeof("'")-1); } else { zend_make_printable_zval(zv, &zv_copy, &use_copy); string_write(str, Z_STRVAL(zv_copy), Z_STRLEN(zv_copy)); if (use_copy) { zval_dtor(&zv_copy); } } zval_ptr_dtor(&zv); } } string_write(str, " ]", sizeof(" ]")-1); } /* }}} */ /* {{{ _function_parameter_string */ static void _function_parameter_string(string *str, zend_function *fptr, char* indent TSRMLS_DC) { struct _zend_arg_info *arg_info = fptr->common.arg_info; zend_uint i, required = fptr->common.required_num_args; if (!arg_info) { return; } string_printf(str, "\n"); string_printf(str, "%s- Parameters [%d] {\n", indent, fptr->common.num_args); for (i = 0; i < fptr->common.num_args; i++) { string_printf(str, "%s ", indent); _parameter_string(str, fptr, arg_info, i, required, indent TSRMLS_CC); string_write(str, "\n", sizeof("\n")-1); arg_info++; } string_printf(str, "%s}\n", indent); } /* }}} */ /* {{{ _function_closure_string */ static void _function_closure_string(string *str, zend_function *fptr, char* indent TSRMLS_DC) { zend_uint i, count; ulong num_index; char *key; uint key_len; HashTable *static_variables; HashPosition pos; if (fptr->type != ZEND_USER_FUNCTION || !fptr->op_array.static_variables) { return; } static_variables = fptr->op_array.static_variables; count = zend_hash_num_elements(static_variables); if (!count) { return; } string_printf(str, "\n"); string_printf(str, "%s- Bound Variables [%d] {\n", indent, zend_hash_num_elements(static_variables)); zend_hash_internal_pointer_reset_ex(static_variables, &pos); i = 0; while (i < count) { zend_hash_get_current_key_ex(static_variables, &key, &key_len, &num_index, 0, &pos); string_printf(str, "%s Variable #%d [ $%s ]\n", indent, i++, key); zend_hash_move_forward_ex(static_variables, &pos); } string_printf(str, "%s}\n", indent); } /* }}} */ /* {{{ _function_string */ static void _function_string(string *str, zend_function *fptr, zend_class_entry *scope, char* indent TSRMLS_DC) { string param_indent; zend_function *overwrites; char *lc_name; unsigned int lc_name_len; /* TBD: Repair indenting of doc comment (or is this to be done in the parser?) * What's "wrong" is that any whitespace before the doc comment start is * swallowed, leading to an unaligned comment. */ if (fptr->type == ZEND_USER_FUNCTION && fptr->op_array.doc_comment) { string_printf(str, "%s%s\n", indent, fptr->op_array.doc_comment); } string_write(str, indent, strlen(indent)); string_printf(str, fptr->common.fn_flags & ZEND_ACC_CLOSURE ? "Closure [ " : (fptr->common.scope ? "Method [ " : "Function [ ")); string_printf(str, (fptr->type == ZEND_USER_FUNCTION) ? "<user" : "<internal"); if (fptr->common.fn_flags & ZEND_ACC_DEPRECATED) { string_printf(str, ", deprecated"); } if (fptr->type == ZEND_INTERNAL_FUNCTION && ((zend_internal_function*)fptr)->module) { string_printf(str, ":%s", ((zend_internal_function*)fptr)->module->name); } if (scope && fptr->common.scope) { if (fptr->common.scope != scope) { string_printf(str, ", inherits %s", fptr->common.scope->name); } else if (fptr->common.scope->parent) { lc_name_len = strlen(fptr->common.function_name); lc_name = zend_str_tolower_dup(fptr->common.function_name, lc_name_len); if (zend_hash_find(&fptr->common.scope->parent->function_table, lc_name, lc_name_len + 1, (void**) &overwrites) == SUCCESS) { if (fptr->common.scope != overwrites->common.scope) { string_printf(str, ", overwrites %s", overwrites->common.scope->name); } } efree(lc_name); } } if (fptr->common.prototype && fptr->common.prototype->common.scope) { string_printf(str, ", prototype %s", fptr->common.prototype->common.scope->name); } if (fptr->common.fn_flags & ZEND_ACC_CTOR) { string_printf(str, ", ctor"); } if (fptr->common.fn_flags & ZEND_ACC_DTOR) { string_printf(str, ", dtor"); } string_printf(str, "> "); if (fptr->common.fn_flags & ZEND_ACC_ABSTRACT) { string_printf(str, "abstract "); } if (fptr->common.fn_flags & ZEND_ACC_FINAL) { string_printf(str, "final "); } if (fptr->common.fn_flags & ZEND_ACC_STATIC) { string_printf(str, "static "); } if (fptr->common.scope) { /* These are mutually exclusive */ switch (fptr->common.fn_flags & ZEND_ACC_PPP_MASK) { case ZEND_ACC_PUBLIC: string_printf(str, "public "); break; case ZEND_ACC_PRIVATE: string_printf(str, "private "); break; case ZEND_ACC_PROTECTED: string_printf(str, "protected "); break; default: string_printf(str, "<visibility error> "); break; } string_printf(str, "method "); } else { string_printf(str, "function "); } if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { string_printf(str, "&"); } string_printf(str, "%s ] {\n", fptr->common.function_name); /* The information where a function is declared is only available for user classes */ if (fptr->type == ZEND_USER_FUNCTION) { string_printf(str, "%s @@ %s %d - %d\n", indent, fptr->op_array.filename, fptr->op_array.line_start, fptr->op_array.line_end); } string_init(&param_indent); string_printf(&param_indent, "%s ", indent); if (fptr->common.fn_flags & ZEND_ACC_CLOSURE) { _function_closure_string(str, fptr, param_indent.string TSRMLS_CC); } _function_parameter_string(str, fptr, param_indent.string TSRMLS_CC); string_free(&param_indent); string_printf(str, "%s}\n", indent); } /* }}} */ /* {{{ _property_string */ static void _property_string(string *str, zend_property_info *prop, char *prop_name, char* indent TSRMLS_DC) { const char *class_name; string_printf(str, "%sProperty [ ", indent); if (!prop) { string_printf(str, "<dynamic> public $%s", prop_name); } else { if (!(prop->flags & ZEND_ACC_STATIC)) { if (prop->flags & ZEND_ACC_IMPLICIT_PUBLIC) { string_write(str, "<implicit> ", sizeof("<implicit> ") - 1); } else { string_write(str, "<default> ", sizeof("<default> ") - 1); } } /* These are mutually exclusive */ switch (prop->flags & ZEND_ACC_PPP_MASK) { case ZEND_ACC_PUBLIC: string_printf(str, "public "); break; case ZEND_ACC_PRIVATE: string_printf(str, "private "); break; case ZEND_ACC_PROTECTED: string_printf(str, "protected "); break; } if(prop->flags & ZEND_ACC_STATIC) { string_printf(str, "static "); } zend_unmangle_property_name(prop->name, prop->name_length, &class_name, (const char**)&prop_name); string_printf(str, "$%s", prop_name); } string_printf(str, " ]\n"); } /* }}} */ static int _extension_ini_string(zend_ini_entry *ini_entry TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { string *str = va_arg(args, string *); char *indent = va_arg(args, char *); int number = va_arg(args, int); char *comma = ""; if (number == ini_entry->module_number) { string_printf(str, " %sEntry [ %s <", indent, ini_entry->name); if (ini_entry->modifiable == ZEND_INI_ALL) { string_printf(str, "ALL"); } else { if (ini_entry->modifiable & ZEND_INI_USER) { string_printf(str, "USER"); comma = ","; } if (ini_entry->modifiable & ZEND_INI_PERDIR) { string_printf(str, "%sPERDIR", comma); comma = ","; } if (ini_entry->modifiable & ZEND_INI_SYSTEM) { string_printf(str, "%sSYSTEM", comma); } } string_printf(str, "> ]\n"); string_printf(str, " %s Current = '%s'\n", indent, ini_entry->value ? ini_entry->value : ""); if (ini_entry->modified) { string_printf(str, " %s Default = '%s'\n", indent, ini_entry->orig_value ? ini_entry->orig_value : ""); } string_printf(str, " %s}\n", indent); } return ZEND_HASH_APPLY_KEEP; } /* }}} */ static int _extension_class_string(zend_class_entry **pce TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { string *str = va_arg(args, string *); char *indent = va_arg(args, char *); struct _zend_module_entry *module = va_arg(args, struct _zend_module_entry*); int *num_classes = va_arg(args, int*); if (((*pce)->type == ZEND_INTERNAL_CLASS) && (*pce)->info.internal.module && !strcasecmp((*pce)->info.internal.module->name, module->name)) { string_printf(str, "\n"); _class_string(str, *pce, NULL, indent TSRMLS_CC); (*num_classes)++; } return ZEND_HASH_APPLY_KEEP; } /* }}} */ static int _extension_const_string(zend_constant *constant TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { string *str = va_arg(args, string *); char *indent = va_arg(args, char *); struct _zend_module_entry *module = va_arg(args, struct _zend_module_entry*); int *num_classes = va_arg(args, int*); if (constant->module_number == module->module_number) { _const_string(str, constant->name, &constant->value, indent TSRMLS_CC); (*num_classes)++; } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* {{{ _extension_string */ static void _extension_string(string *str, zend_module_entry *module, char *indent TSRMLS_DC) { string_printf(str, "%sExtension [ ", indent); if (module->type == MODULE_PERSISTENT) { string_printf(str, "<persistent>"); } if (module->type == MODULE_TEMPORARY) { string_printf(str, "<temporary>" ); } string_printf(str, " extension #%d %s version %s ] {\n", module->module_number, module->name, (module->version == NO_VERSION_YET) ? "<no_version>" : module->version); if (module->deps) { const zend_module_dep* dep = module->deps; string_printf(str, "\n - Dependencies {\n"); while(dep->name) { string_printf(str, "%s Dependency [ %s (", indent, dep->name); switch(dep->type) { case MODULE_DEP_REQUIRED: string_write(str, "Required", sizeof("Required") - 1); break; case MODULE_DEP_CONFLICTS: string_write(str, "Conflicts", sizeof("Conflicts") - 1); break; case MODULE_DEP_OPTIONAL: string_write(str, "Optional", sizeof("Optional") - 1); break; default: string_write(str, "Error", sizeof("Error") - 1); /* shouldn't happen */ break; } if (dep->rel) { string_printf(str, " %s", dep->rel); } if (dep->version) { string_printf(str, " %s", dep->version); } string_write(str, ") ]\n", sizeof(") ]\n") - 1); dep++; } string_printf(str, "%s }\n", indent); } { string str_ini; string_init(&str_ini); zend_hash_apply_with_arguments(EG(ini_directives) TSRMLS_CC, (apply_func_args_t) _extension_ini_string, 3, &str_ini, indent, module->module_number); if (str_ini.len > 1) { string_printf(str, "\n - INI {\n"); string_append(str, &str_ini); string_printf(str, "%s }\n", indent); } string_free(&str_ini); } { string str_constants; int num_constants = 0; string_init(&str_constants); zend_hash_apply_with_arguments(EG(zend_constants) TSRMLS_CC, (apply_func_args_t) _extension_const_string, 4, &str_constants, indent, module, &num_constants); if (num_constants) { string_printf(str, "\n - Constants [%d] {\n", num_constants); string_append(str, &str_constants); string_printf(str, "%s }\n", indent); } string_free(&str_constants); } if (module->functions && module->functions->fname) { zend_function *fptr; const zend_function_entry *func = module->functions; string_printf(str, "\n - Functions {\n"); /* Is there a better way of doing this? */ while (func->fname) { int fname_len = strlen(func->fname); char *lc_name = zend_str_tolower_dup(func->fname, fname_len); if (zend_hash_find(EG(function_table), lc_name, fname_len + 1, (void**) &fptr) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Internal error: Cannot find extension function %s in global function table", func->fname); func++; efree(lc_name); continue; } _function_string(str, fptr, NULL, " " TSRMLS_CC); efree(lc_name); func++; } string_printf(str, "%s }\n", indent); } { string str_classes; string sub_indent; int num_classes = 0; string_init(&sub_indent); string_printf(&sub_indent, "%s ", indent); string_init(&str_classes); zend_hash_apply_with_arguments(EG(class_table) TSRMLS_CC, (apply_func_args_t) _extension_class_string, 4, &str_classes, sub_indent.string, module, &num_classes); if (num_classes) { string_printf(str, "\n - Classes [%d] {", num_classes); string_append(str, &str_classes); string_printf(str, "%s }\n", indent); } string_free(&str_classes); string_free(&sub_indent); } string_printf(str, "%s}\n", indent); } /* }}} */ static void _zend_extension_string(string *str, zend_extension *extension, char *indent TSRMLS_DC) /* {{{ */ { string_printf(str, "%sZend Extension [ %s ", indent, extension->name); if (extension->version) { string_printf(str, "%s ", extension->version); } if (extension->copyright) { string_printf(str, "%s ", extension->copyright); } if (extension->author) { string_printf(str, "by %s ", extension->author); } if (extension->URL) { string_printf(str, "<%s> ", extension->URL); } string_printf(str, "]\n"); } /* }}} */ /* {{{ _function_check_flag */ static void _function_check_flag(INTERNAL_FUNCTION_PARAMETERS, int mask) { reflection_object *intern; zend_function *mptr; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(mptr); RETURN_BOOL(mptr->common.fn_flags & mask); } /* }}} */ /* {{{ zend_reflection_class_factory */ PHPAPI void zend_reflection_class_factory(zend_class_entry *ce, zval *object TSRMLS_DC) { reflection_object *intern; zval *name; MAKE_STD_ZVAL(name); ZVAL_STRINGL(name, ce->name, ce->name_length, 1); reflection_instantiate(reflection_class_ptr, object TSRMLS_CC); intern = (reflection_object *) zend_object_store_get_object(object TSRMLS_CC); intern->ptr = ce; intern->ref_type = REF_TYPE_OTHER; intern->ce = ce; reflection_update_property(object, "name", name); } /* }}} */ /* {{{ reflection_extension_factory */ static void reflection_extension_factory(zval *object, const char *name_str TSRMLS_DC) { reflection_object *intern; zval *name; int name_len = strlen(name_str); char *lcname; struct _zend_module_entry *module; ALLOCA_FLAG(use_heap) lcname = do_alloca(name_len + 1, use_heap); zend_str_tolower_copy(lcname, name_str, name_len); if (zend_hash_find(&module_registry, lcname, name_len + 1, (void **)&module) == FAILURE) { free_alloca(lcname, use_heap); return; } free_alloca(lcname, use_heap); reflection_instantiate(reflection_extension_ptr, object TSRMLS_CC); intern = (reflection_object *) zend_object_store_get_object(object TSRMLS_CC); MAKE_STD_ZVAL(name); ZVAL_STRINGL(name, module->name, name_len, 1); intern->ptr = module; intern->ref_type = REF_TYPE_OTHER; intern->ce = NULL; reflection_update_property(object, "name", name); } /* }}} */ /* {{{ reflection_parameter_factory */ static void reflection_parameter_factory(zend_function *fptr, zval *closure_object, struct _zend_arg_info *arg_info, zend_uint offset, zend_uint required, zval *object TSRMLS_DC) { reflection_object *intern; parameter_reference *reference; zval *name; if (closure_object) { Z_ADDREF_P(closure_object); } MAKE_STD_ZVAL(name); if (arg_info->name) { ZVAL_STRINGL(name, arg_info->name, arg_info->name_len, 1); } else { ZVAL_NULL(name); } reflection_instantiate(reflection_parameter_ptr, object TSRMLS_CC); intern = (reflection_object *) zend_object_store_get_object(object TSRMLS_CC); reference = (parameter_reference*) emalloc(sizeof(parameter_reference)); reference->arg_info = arg_info; reference->offset = offset; reference->required = required; reference->fptr = fptr; intern->ptr = reference; intern->ref_type = REF_TYPE_PARAMETER; intern->ce = fptr->common.scope; intern->obj = closure_object; reflection_update_property(object, "name", name); } /* }}} */ /* {{{ reflection_function_factory */ static void reflection_function_factory(zend_function *function, zval *closure_object, zval *object TSRMLS_DC) { reflection_object *intern; zval *name; if (closure_object) { Z_ADDREF_P(closure_object); } MAKE_STD_ZVAL(name); ZVAL_STRING(name, function->common.function_name, 1); reflection_instantiate(reflection_function_ptr, object TSRMLS_CC); intern = (reflection_object *) zend_object_store_get_object(object TSRMLS_CC); intern->ptr = function; intern->ref_type = REF_TYPE_FUNCTION; intern->ce = NULL; intern->obj = closure_object; reflection_update_property(object, "name", name); } /* }}} */ /* {{{ reflection_method_factory */ static void reflection_method_factory(zend_class_entry *ce, zend_function *method, zval *closure_object, zval *object TSRMLS_DC) { reflection_object *intern; zval *name; zval *classname; if (closure_object) { Z_ADDREF_P(closure_object); } MAKE_STD_ZVAL(name); MAKE_STD_ZVAL(classname); ZVAL_STRING(name, method->common.function_name, 1); ZVAL_STRINGL(classname, method->common.scope->name, method->common.scope->name_length, 1); reflection_instantiate(reflection_method_ptr, object TSRMLS_CC); intern = (reflection_object *) zend_object_store_get_object(object TSRMLS_CC); intern->ptr = method; intern->ref_type = REF_TYPE_FUNCTION; intern->ce = ce; intern->obj = closure_object; reflection_update_property(object, "name", name); reflection_update_property(object, "class", classname); } /* }}} */ /* {{{ reflection_property_factory */ static void reflection_property_factory(zend_class_entry *ce, zend_property_info *prop, zval *object TSRMLS_DC) { reflection_object *intern; zval *name; zval *classname; property_reference *reference; const char *class_name, *prop_name; zend_unmangle_property_name(prop->name, prop->name_length, &class_name, &prop_name); if (!(prop->flags & ZEND_ACC_PRIVATE)) { /* we have to search the class hierarchy for this (implicit) public or protected property */ zend_class_entry *tmp_ce = ce, *store_ce = ce; zend_property_info *tmp_info = NULL; while (tmp_ce && zend_hash_find(&tmp_ce->properties_info, prop_name, strlen(prop_name) + 1, (void **) &tmp_info) != SUCCESS) { ce = tmp_ce; tmp_ce = tmp_ce->parent; } if (tmp_info && !(tmp_info->flags & ZEND_ACC_SHADOW)) { /* found something and it's not a parent's private */ prop = tmp_info; } else { /* not found, use initial value */ ce = store_ce; } } MAKE_STD_ZVAL(name); MAKE_STD_ZVAL(classname); ZVAL_STRING(name, prop_name, 1); ZVAL_STRINGL(classname, prop->ce->name, prop->ce->name_length, 1); reflection_instantiate(reflection_property_ptr, object TSRMLS_CC); intern = (reflection_object *) zend_object_store_get_object(object TSRMLS_CC); reference = (property_reference*) emalloc(sizeof(property_reference)); reference->ce = ce; reference->prop = *prop; intern->ptr = reference; intern->ref_type = REF_TYPE_PROPERTY; intern->ce = ce; intern->ignore_visibility = 0; reflection_update_property(object, "name", name); reflection_update_property(object, "class", classname); } /* }}} */ /* {{{ _reflection_export */ static void _reflection_export(INTERNAL_FUNCTION_PARAMETERS, zend_class_entry *ce_ptr, int ctor_argc) { zval *reflector_ptr; zval output, *output_ptr = &output; zval *argument_ptr, *argument2_ptr; zval *retval_ptr, **params[2]; int result; int return_output = 0; zend_fcall_info fci; zend_fcall_info_cache fcc; zval fname; if (ctor_argc == 1) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|b", &argument_ptr, &return_output) == FAILURE) { return; } } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz|b", &argument_ptr, &argument2_ptr, &return_output) == FAILURE) { return; } } INIT_PZVAL(&output); /* Create object */ MAKE_STD_ZVAL(reflector_ptr); if (object_and_properties_init(reflector_ptr, ce_ptr, NULL) == FAILURE) { _DO_THROW("Could not create reflector"); } /* Call __construct() */ params[0] = &argument_ptr; params[1] = &argument2_ptr; fci.size = sizeof(fci); fci.function_table = NULL; fci.function_name = NULL; fci.symbol_table = NULL; fci.object_ptr = reflector_ptr; fci.retval_ptr_ptr = &retval_ptr; fci.param_count = ctor_argc; fci.params = params; fci.no_separation = 1; fcc.initialized = 1; fcc.function_handler = ce_ptr->constructor; fcc.calling_scope = ce_ptr; fcc.called_scope = Z_OBJCE_P(reflector_ptr); fcc.object_ptr = reflector_ptr; result = zend_call_function(&fci, &fcc TSRMLS_CC); if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } if (EG(exception)) { zval_ptr_dtor(&reflector_ptr); return; } if (result == FAILURE) { zval_ptr_dtor(&reflector_ptr); _DO_THROW("Could not create reflector"); } /* Call static reflection::export */ ZVAL_BOOL(&output, return_output); params[0] = &reflector_ptr; params[1] = &output_ptr; ZVAL_STRINGL(&fname, "reflection::export", sizeof("reflection::export") - 1, 0); fci.function_table = &reflection_ptr->function_table; fci.function_name = &fname; fci.object_ptr = NULL; fci.retval_ptr_ptr = &retval_ptr; fci.param_count = 2; fci.params = params; fci.no_separation = 1; result = zend_call_function(&fci, NULL TSRMLS_CC); if (result == FAILURE && EG(exception) == NULL) { zval_ptr_dtor(&reflector_ptr); zval_ptr_dtor(&retval_ptr); _DO_THROW("Could not execute reflection::export()"); } if (return_output) { COPY_PZVAL_TO_ZVAL(*return_value, retval_ptr); } else { zval_ptr_dtor(&retval_ptr); } /* Destruct reflector which is no longer needed */ zval_ptr_dtor(&reflector_ptr); } /* }}} */ /* {{{ Preventing __clone from being called */ ZEND_METHOD(reflection, __clone) { /* Should never be executable */ _DO_THROW("Cannot clone object using __clone()"); } /* }}} */ /* {{{ proto public static mixed Reflection::export(Reflector r [, bool return]) Exports a reflection object. Returns the output if TRUE is specified for return, printing it otherwise. */ ZEND_METHOD(reflection, export) { zval *object, fname, *retval_ptr; int result; zend_bool return_output = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|b", &object, reflector_ptr, &return_output) == FAILURE) { return; } /* Invoke the __toString() method */ ZVAL_STRINGL(&fname, "__tostring", sizeof("__tostring") - 1, 1); result= call_user_function_ex(NULL, &object, &fname, &retval_ptr, 0, NULL, 0, NULL TSRMLS_CC); zval_dtor(&fname); if (result == FAILURE) { _DO_THROW("Invocation of method __toString() failed"); /* Returns from this function */ } if (!retval_ptr) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::__toString() did not return anything", Z_OBJCE_P(object)->name); RETURN_FALSE; } if (return_output) { COPY_PZVAL_TO_ZVAL(*return_value, retval_ptr); } else { /* No need for _r variant, return of __toString should always be a string */ zend_print_zval(retval_ptr, 0); zend_printf("\n"); zval_ptr_dtor(&retval_ptr); } } /* }}} */ /* {{{ proto public static array Reflection::getModifierNames(int modifiers) Returns an array of modifier names */ ZEND_METHOD(reflection, getModifierNames) { long modifiers; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &modifiers) == FAILURE) { return; } array_init(return_value); if (modifiers & (ZEND_ACC_ABSTRACT | ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) { add_next_index_stringl(return_value, "abstract", sizeof("abstract")-1, 1); } if (modifiers & (ZEND_ACC_FINAL | ZEND_ACC_FINAL_CLASS)) { add_next_index_stringl(return_value, "final", sizeof("final")-1, 1); } if (modifiers & ZEND_ACC_IMPLICIT_PUBLIC) { add_next_index_stringl(return_value, "public", sizeof("public")-1, 1); } /* These are mutually exclusive */ switch (modifiers & ZEND_ACC_PPP_MASK) { case ZEND_ACC_PUBLIC: add_next_index_stringl(return_value, "public", sizeof("public")-1, 1); break; case ZEND_ACC_PRIVATE: add_next_index_stringl(return_value, "private", sizeof("private")-1, 1); break; case ZEND_ACC_PROTECTED: add_next_index_stringl(return_value, "protected", sizeof("protected")-1, 1); break; } if (modifiers & ZEND_ACC_STATIC) { add_next_index_stringl(return_value, "static", sizeof("static")-1, 1); } } /* }}} */ /* {{{ proto public static mixed ReflectionFunction::export(string name [, bool return]) Exports a reflection object. Returns the output if TRUE is specified for return, printing it otherwise. */ ZEND_METHOD(reflection_function, export) { _reflection_export(INTERNAL_FUNCTION_PARAM_PASSTHRU, reflection_function_ptr, 1); } /* }}} */ /* {{{ proto public void ReflectionFunction::__construct(string name) Constructor. Throws an Exception in case the given function does not exist */ ZEND_METHOD(reflection_function, __construct) { zval *name; zval *object; zval *closure = NULL; char *lcname; reflection_object *intern; zend_function *fptr; char *name_str; int name_len; object = getThis(); intern = (reflection_object *) zend_object_store_get_object(object TSRMLS_CC); if (intern == NULL) { return; } if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "O", &closure, zend_ce_closure) == SUCCESS) { fptr = (zend_function*)zend_get_closure_method_def(closure TSRMLS_CC); Z_ADDREF_P(closure); } else if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name_str, &name_len) == SUCCESS) { char *nsname; lcname = zend_str_tolower_dup(name_str, name_len); /* Ignore leading "\" */ nsname = lcname; if (lcname[0] == '\\') { nsname = &lcname[1]; name_len--; } if (zend_hash_find(EG(function_table), nsname, name_len + 1, (void **)&fptr) == FAILURE) { efree(lcname); zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Function %s() does not exist", name_str); return; } efree(lcname); } else { return; } MAKE_STD_ZVAL(name); ZVAL_STRING(name, fptr->common.function_name, 1); reflection_update_property(object, "name", name); intern->ptr = fptr; intern->ref_type = REF_TYPE_FUNCTION; intern->obj = closure; intern->ce = NULL; } /* }}} */ /* {{{ proto public string ReflectionFunction::__toString() Returns a string representation */ ZEND_METHOD(reflection_function, __toString) { reflection_object *intern; zend_function *fptr; string str; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(fptr); string_init(&str); _function_string(&str, fptr, intern->ce, "" TSRMLS_CC); RETURN_STRINGL(str.string, str.len - 1, 0); } /* }}} */ /* {{{ proto public string ReflectionFunction::getName() Returns this function's name */ ZEND_METHOD(reflection_function, getName) { if (zend_parse_parameters_none() == FAILURE) { return; } _default_get_entry(getThis(), "name", sizeof("name"), return_value TSRMLS_CC); } /* }}} */ /* {{{ proto public bool ReflectionFunction::isClosure() Returns whether this is a closure */ ZEND_METHOD(reflection_function, isClosure) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(fptr); RETURN_BOOL(fptr->common.fn_flags & ZEND_ACC_CLOSURE); } /* }}} */ /* {{{ proto public bool ReflectionFunction::getClosureThis() Returns this pointer bound to closure */ ZEND_METHOD(reflection_function, getClosureThis) { reflection_object *intern; zend_function *fptr; zval* closure_this; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(fptr); if (intern->obj) { closure_this = zend_get_closure_this_ptr(intern->obj TSRMLS_CC); if (closure_this) { RETURN_ZVAL(closure_this, 1, 0); } } } /* }}} */ /* {{{ proto public ReflectionClass ReflectionFunction::getClosureScopeClass() Returns the scope associated to the closure */ ZEND_METHOD(reflection_function, getClosureScopeClass) { reflection_object *intern; zend_function *fptr; const zend_function *closure_func; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(fptr); if (intern->obj) { closure_func = zend_get_closure_method_def(intern->obj TSRMLS_CC); if (closure_func && closure_func->common.scope) { zend_reflection_class_factory(closure_func->common.scope, return_value TSRMLS_CC); } } } /* }}} */ /* {{{ proto public mixed ReflectionFunction::getClosure() Returns a dynamically created closure for the function */ ZEND_METHOD(reflection_function, getClosure) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(fptr); zend_create_closure(return_value, fptr, NULL, NULL TSRMLS_CC); } /* }}} */ /* {{{ proto public bool ReflectionFunction::isInternal() Returns whether this is an internal function */ ZEND_METHOD(reflection_function, isInternal) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(fptr); RETURN_BOOL(fptr->type == ZEND_INTERNAL_FUNCTION); } /* }}} */ /* {{{ proto public bool ReflectionFunction::isUserDefined() Returns whether this is an user-defined function */ ZEND_METHOD(reflection_function, isUserDefined) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(fptr); RETURN_BOOL(fptr->type == ZEND_USER_FUNCTION); } /* }}} */ /* {{{ proto public bool ReflectionFunction::isDisabled() Returns whether this function has been disabled or not */ ZEND_METHOD(reflection_function, isDisabled) { reflection_object *intern; zend_function *fptr; METHOD_NOTSTATIC(reflection_function_ptr); GET_REFLECTION_OBJECT_PTR(fptr); RETURN_BOOL(fptr->type == ZEND_INTERNAL_FUNCTION && fptr->internal_function.handler == zif_display_disabled_function); } /* }}} */ /* {{{ proto public string ReflectionFunction::getFileName() Returns the filename of the file this function was declared in */ ZEND_METHOD(reflection_function, getFileName) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(fptr); if (fptr->type == ZEND_USER_FUNCTION) { RETURN_STRING(fptr->op_array.filename, 1); } RETURN_FALSE; } /* }}} */ /* {{{ proto public int ReflectionFunction::getStartLine() Returns the line this function's declaration starts at */ ZEND_METHOD(reflection_function, getStartLine) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(fptr); if (fptr->type == ZEND_USER_FUNCTION) { RETURN_LONG(fptr->op_array.line_start); } RETURN_FALSE; } /* }}} */ /* {{{ proto public int ReflectionFunction::getEndLine() Returns the line this function's declaration ends at */ ZEND_METHOD(reflection_function, getEndLine) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(fptr); if (fptr->type == ZEND_USER_FUNCTION) { RETURN_LONG(fptr->op_array.line_end); } RETURN_FALSE; } /* }}} */ /* {{{ proto public string ReflectionFunction::getDocComment() Returns the doc comment for this function */ ZEND_METHOD(reflection_function, getDocComment) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(fptr); if (fptr->type == ZEND_USER_FUNCTION && fptr->op_array.doc_comment) { RETURN_STRINGL(fptr->op_array.doc_comment, fptr->op_array.doc_comment_len, 1); } RETURN_FALSE; } /* }}} */ /* {{{ proto public array ReflectionFunction::getStaticVariables() Returns an associative array containing this function's static variables and their values */ ZEND_METHOD(reflection_function, getStaticVariables) { zval *tmp_copy; reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(fptr); /* Return an empty array in case no static variables exist */ array_init(return_value); if (fptr->type == ZEND_USER_FUNCTION && fptr->op_array.static_variables != NULL) { zend_hash_apply_with_argument(fptr->op_array.static_variables, (apply_func_arg_t) zval_update_constant, (void*)1 TSRMLS_CC); zend_hash_copy(Z_ARRVAL_P(return_value), fptr->op_array.static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_copy, sizeof(zval *)); } } /* }}} */ /* {{{ proto public mixed ReflectionFunction::invoke([mixed* args]) Invokes the function */ ZEND_METHOD(reflection_function, invoke) { zval *retval_ptr; zval ***params = NULL; int result, num_args = 0; zend_fcall_info fci; zend_fcall_info_cache fcc; reflection_object *intern; zend_function *fptr; METHOD_NOTSTATIC(reflection_function_ptr); GET_REFLECTION_OBJECT_PTR(fptr); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "*", &params, &num_args) == FAILURE) { return; } fci.size = sizeof(fci); fci.function_table = NULL; fci.function_name = NULL; fci.symbol_table = NULL; fci.object_ptr = NULL; fci.retval_ptr_ptr = &retval_ptr; fci.param_count = num_args; fci.params = params; fci.no_separation = 1; fcc.initialized = 1; fcc.function_handler = fptr; fcc.calling_scope = EG(scope); fcc.called_scope = NULL; fcc.object_ptr = NULL; result = zend_call_function(&fci, &fcc TSRMLS_CC); if (num_args) { efree(params); } if (result == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Invocation of function %s() failed", fptr->common.function_name); return; } if (retval_ptr) { COPY_PZVAL_TO_ZVAL(*return_value, retval_ptr); } } /* }}} */ static int _zval_array_to_c_array(zval **arg, zval ****params TSRMLS_DC) /* {{{ */ { *(*params)++ = arg; return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* {{{ proto public mixed ReflectionFunction::invokeArgs(array args) Invokes the function and pass its arguments as array. */ ZEND_METHOD(reflection_function, invokeArgs) { zval *retval_ptr; zval ***params; int result; int argc; zend_fcall_info fci; zend_fcall_info_cache fcc; reflection_object *intern; zend_function *fptr; zval *param_array; METHOD_NOTSTATIC(reflection_function_ptr); GET_REFLECTION_OBJECT_PTR(fptr); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &param_array) == FAILURE) { return; } argc = zend_hash_num_elements(Z_ARRVAL_P(param_array)); params = safe_emalloc(sizeof(zval **), argc, 0); zend_hash_apply_with_argument(Z_ARRVAL_P(param_array), (apply_func_arg_t)_zval_array_to_c_array, &params TSRMLS_CC); params -= argc; fci.size = sizeof(fci); fci.function_table = NULL; fci.function_name = NULL; fci.symbol_table = NULL; fci.object_ptr = NULL; fci.retval_ptr_ptr = &retval_ptr; fci.param_count = argc; fci.params = params; fci.no_separation = 1; fcc.initialized = 1; fcc.function_handler = fptr; fcc.calling_scope = EG(scope); fcc.called_scope = NULL; fcc.object_ptr = NULL; result = zend_call_function(&fci, &fcc TSRMLS_CC); efree(params); if (result == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Invocation of function %s() failed", fptr->common.function_name); return; } if (retval_ptr) { COPY_PZVAL_TO_ZVAL(*return_value, retval_ptr); } } /* }}} */ /* {{{ proto public bool ReflectionFunction::returnsReference() Gets whether this function returns a reference */ ZEND_METHOD(reflection_function, returnsReference) { reflection_object *intern; zend_function *fptr; METHOD_NOTSTATIC(reflection_function_abstract_ptr); GET_REFLECTION_OBJECT_PTR(fptr); RETURN_BOOL((fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) != 0); } /* }}} */ /* {{{ proto public bool ReflectionFunction::getNumberOfParameters() Gets the number of required parameters */ ZEND_METHOD(reflection_function, getNumberOfParameters) { reflection_object *intern; zend_function *fptr; METHOD_NOTSTATIC(reflection_function_abstract_ptr); GET_REFLECTION_OBJECT_PTR(fptr); RETURN_LONG(fptr->common.num_args); } /* }}} */ /* {{{ proto public bool ReflectionFunction::getNumberOfRequiredParameters() Gets the number of required parameters */ ZEND_METHOD(reflection_function, getNumberOfRequiredParameters) { reflection_object *intern; zend_function *fptr; METHOD_NOTSTATIC(reflection_function_abstract_ptr); GET_REFLECTION_OBJECT_PTR(fptr); RETURN_LONG(fptr->common.required_num_args); } /* }}} */ /* {{{ proto public ReflectionParameter[] ReflectionFunction::getParameters() Returns an array of parameter objects for this function */ ZEND_METHOD(reflection_function, getParameters) { reflection_object *intern; zend_function *fptr; zend_uint i; struct _zend_arg_info *arg_info; METHOD_NOTSTATIC(reflection_function_abstract_ptr); GET_REFLECTION_OBJECT_PTR(fptr); arg_info= fptr->common.arg_info; array_init(return_value); for (i = 0; i < fptr->common.num_args; i++) { zval *parameter; ALLOC_ZVAL(parameter); reflection_parameter_factory(_copy_function(fptr TSRMLS_CC), intern->obj, arg_info, i, fptr->common.required_num_args, parameter TSRMLS_CC); add_next_index_zval(return_value, parameter); arg_info++; } } /* }}} */ /* {{{ proto public ReflectionExtension|NULL ReflectionFunction::getExtension() Returns NULL or the extension the function belongs to */ ZEND_METHOD(reflection_function, getExtension) { reflection_object *intern; zend_function *fptr; zend_internal_function *internal; METHOD_NOTSTATIC(reflection_function_abstract_ptr); GET_REFLECTION_OBJECT_PTR(fptr); if (fptr->type != ZEND_INTERNAL_FUNCTION) { RETURN_NULL(); } internal = (zend_internal_function *)fptr; if (internal->module) { reflection_extension_factory(return_value, internal->module->name TSRMLS_CC); } else { RETURN_NULL(); } } /* }}} */ /* {{{ proto public string|false ReflectionFunction::getExtensionName() Returns false or the name of the extension the function belongs to */ ZEND_METHOD(reflection_function, getExtensionName) { reflection_object *intern; zend_function *fptr; zend_internal_function *internal; METHOD_NOTSTATIC(reflection_function_abstract_ptr); GET_REFLECTION_OBJECT_PTR(fptr); if (fptr->type != ZEND_INTERNAL_FUNCTION) { RETURN_FALSE; } internal = (zend_internal_function *)fptr; if (internal->module) { RETURN_STRING(internal->module->name, 1); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto public static mixed ReflectionParameter::export(mixed function, mixed parameter [, bool return]) throws ReflectionException Exports a reflection object. Returns the output if TRUE is specified for return, printing it otherwise. */ ZEND_METHOD(reflection_parameter, export) { _reflection_export(INTERNAL_FUNCTION_PARAM_PASSTHRU, reflection_parameter_ptr, 2); } /* }}} */ /* {{{ proto public void ReflectionParameter::__construct(mixed function, mixed parameter) Constructor. Throws an Exception in case the given method does not exist */ ZEND_METHOD(reflection_parameter, __construct) { parameter_reference *ref; zval *reference, **parameter; zval *object; zval *name; reflection_object *intern; zend_function *fptr; struct _zend_arg_info *arg_info; int position; zend_class_entry *ce = NULL; zend_bool is_closure = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zZ", &reference, &parameter) == FAILURE) { return; } object = getThis(); intern = (reflection_object *) zend_object_store_get_object(object TSRMLS_CC); if (intern == NULL) { return; } /* First, find the function */ switch (Z_TYPE_P(reference)) { case IS_STRING: { unsigned int lcname_len; char *lcname; lcname_len = Z_STRLEN_P(reference); lcname = zend_str_tolower_dup(Z_STRVAL_P(reference), lcname_len); if (zend_hash_find(EG(function_table), lcname, lcname_len + 1, (void**) &fptr) == FAILURE) { efree(lcname); zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Function %s() does not exist", Z_STRVAL_P(reference)); return; } efree(lcname); } ce = fptr->common.scope; break; case IS_ARRAY: { zval **classref; zval **method; zend_class_entry **pce; unsigned int lcname_len; char *lcname; if ((zend_hash_index_find(Z_ARRVAL_P(reference), 0, (void **) &classref) == FAILURE) || (zend_hash_index_find(Z_ARRVAL_P(reference), 1, (void **) &method) == FAILURE)) { _DO_THROW("Expected array($object, $method) or array($classname, $method)"); /* returns out of this function */ } if (Z_TYPE_PP(classref) == IS_OBJECT) { ce = Z_OBJCE_PP(classref); } else { convert_to_string_ex(classref); if (zend_lookup_class(Z_STRVAL_PP(classref), Z_STRLEN_PP(classref), &pce TSRMLS_CC) == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Class %s does not exist", Z_STRVAL_PP(classref)); return; } ce = *pce; } convert_to_string_ex(method); lcname_len = Z_STRLEN_PP(method); lcname = zend_str_tolower_dup(Z_STRVAL_PP(method), lcname_len); if (ce == zend_ce_closure && Z_TYPE_PP(classref) == IS_OBJECT && (lcname_len == sizeof(ZEND_INVOKE_FUNC_NAME)-1) && memcmp(lcname, ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME)-1) == 0 && (fptr = zend_get_closure_invoke_method(*classref TSRMLS_CC)) != NULL) { /* nothing to do. don't set is_closure since is the invoke handler, - not the closure itself */ } else if (zend_hash_find(&ce->function_table, lcname, lcname_len + 1, (void **) &fptr) == FAILURE) { efree(lcname); zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Method %s::%s() does not exist", ce->name, Z_STRVAL_PP(method)); return; } efree(lcname); } break; case IS_OBJECT: { ce = Z_OBJCE_P(reference); if (instanceof_function(ce, zend_ce_closure TSRMLS_CC)) { fptr = (zend_function *)zend_get_closure_method_def(reference TSRMLS_CC); Z_ADDREF_P(reference); is_closure = 1; } else if (zend_hash_find(&ce->function_table, ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME), (void **)&fptr) == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Method %s::%s() does not exist", ce->name, ZEND_INVOKE_FUNC_NAME); return; } } break; default: _DO_THROW("The parameter class is expected to be either a string, an array(class, method) or a callable object"); /* returns out of this function */ } /* Now, search for the parameter */ arg_info = fptr->common.arg_info; if (Z_TYPE_PP(parameter) == IS_LONG) { position= Z_LVAL_PP(parameter); if (position < 0 || (zend_uint)position >= fptr->common.num_args) { if (fptr->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) { if (fptr->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fptr->common.function_name); } efree(fptr); } if (is_closure) { zval_ptr_dtor(&reference); } _DO_THROW("The parameter specified by its offset could not be found"); /* returns out of this function */ } } else { zend_uint i; position= -1; convert_to_string_ex(parameter); for (i = 0; i < fptr->common.num_args; i++) { if (arg_info[i].name && strcmp(arg_info[i].name, Z_STRVAL_PP(parameter)) == 0) { position= i; break; } } if (position == -1) { if (fptr->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) { if (fptr->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fptr->common.function_name); } efree(fptr); } if (is_closure) { zval_ptr_dtor(&reference); } _DO_THROW("The parameter specified by its name could not be found"); /* returns out of this function */ } } MAKE_STD_ZVAL(name); if (arg_info[position].name) { ZVAL_STRINGL(name, arg_info[position].name, arg_info[position].name_len, 1); } else { ZVAL_NULL(name); } reflection_update_property(object, "name", name); ref = (parameter_reference*) emalloc(sizeof(parameter_reference)); ref->arg_info = &arg_info[position]; ref->offset = (zend_uint)position; ref->required = fptr->common.required_num_args; ref->fptr = fptr; /* TODO: copy fptr */ intern->ptr = ref; intern->ref_type = REF_TYPE_PARAMETER; intern->ce = ce; if (reference && is_closure) { intern->obj = reference; } } /* }}} */ /* {{{ proto public string ReflectionParameter::__toString() Returns a string representation */ ZEND_METHOD(reflection_parameter, __toString) { reflection_object *intern; parameter_reference *param; string str; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(param); string_init(&str); _parameter_string(&str, param->fptr, param->arg_info, param->offset, param->required, "" TSRMLS_CC); RETURN_STRINGL(str.string, str.len - 1, 0); } /* }}} */ /* {{{ proto public string ReflectionParameter::getName() Returns this parameters's name */ ZEND_METHOD(reflection_parameter, getName) { if (zend_parse_parameters_none() == FAILURE) { return; } _default_get_entry(getThis(), "name", sizeof("name"), return_value TSRMLS_CC); } /* }}} */ /* {{{ proto public ReflectionFunction ReflectionParameter::getDeclaringFunction() Returns the ReflectionFunction for the function of this parameter */ ZEND_METHOD(reflection_parameter, getDeclaringFunction) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(param); if (!param->fptr->common.scope) { reflection_function_factory(_copy_function(param->fptr TSRMLS_CC), intern->obj, return_value TSRMLS_CC); } else { reflection_method_factory(param->fptr->common.scope, _copy_function(param->fptr TSRMLS_CC), intern->obj, return_value TSRMLS_CC); } } /* }}} */ /* {{{ proto public ReflectionClass|NULL ReflectionParameter::getDeclaringClass() Returns in which class this parameter is defined (not the typehint of the parameter) */ ZEND_METHOD(reflection_parameter, getDeclaringClass) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(param); if (param->fptr->common.scope) { zend_reflection_class_factory(param->fptr->common.scope, return_value TSRMLS_CC); } } /* }}} */ /* {{{ proto public ReflectionClass|NULL ReflectionParameter::getClass() Returns this parameters's class hint or NULL if there is none */ ZEND_METHOD(reflection_parameter, getClass) { reflection_object *intern; parameter_reference *param; zend_class_entry **pce, *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(param); if (param->arg_info->class_name) { /* Class name is stored as a string, we might also get "self" or "parent" * - For "self", simply use the function scope. If scope is NULL then * the function is global and thus self does not make any sense * * - For "parent", use the function scope's parent. If scope is NULL then * the function is global and thus parent does not make any sense. * If the parent is NULL then the class does not extend anything and * thus parent does not make any sense, either. * * TODO: Think about moving these checks to the compiler or some sort of * lint-mode. */ if (0 == zend_binary_strcasecmp(param->arg_info->class_name, param->arg_info->class_name_len, "self", sizeof("self")- 1)) { ce = param->fptr->common.scope; if (!ce) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Parameter uses 'self' as type hint but function is not a class member!"); return; } pce= &ce; } else if (0 == zend_binary_strcasecmp(param->arg_info->class_name, param->arg_info->class_name_len, "parent", sizeof("parent")- 1)) { ce = param->fptr->common.scope; if (!ce) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Parameter uses 'parent' as type hint but function is not a class member!"); return; } if (!ce->parent) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Parameter uses 'parent' as type hint although class does not have a parent!"); return; } pce= &ce->parent; } else if (zend_lookup_class(param->arg_info->class_name, param->arg_info->class_name_len, &pce TSRMLS_CC) == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Class %s does not exist", param->arg_info->class_name); return; } zend_reflection_class_factory(*pce, return_value TSRMLS_CC); } } /* }}} */ /* {{{ proto public bool ReflectionParameter::isArray() Returns whether parameter MUST be an array */ ZEND_METHOD(reflection_parameter, isArray) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(param); RETVAL_BOOL(param->arg_info->type_hint == IS_ARRAY); } /* }}} */ /* {{{ proto public bool ReflectionParameter::isCallable() Returns whether parameter MUST be callable */ ZEND_METHOD(reflection_parameter, isCallable) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(param); RETVAL_BOOL(param->arg_info->type_hint == IS_CALLABLE); } /* }}} */ /* {{{ proto public bool ReflectionParameter::allowsNull() Returns whether NULL is allowed as this parameters's value */ ZEND_METHOD(reflection_parameter, allowsNull) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(param); RETVAL_BOOL(param->arg_info->allow_null); } /* }}} */ /* {{{ proto public bool ReflectionParameter::isPassedByReference() Returns whether this parameters is passed to by reference */ ZEND_METHOD(reflection_parameter, isPassedByReference) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(param); RETVAL_BOOL(param->arg_info->pass_by_reference); } /* }}} */ /* {{{ proto public bool ReflectionParameter::canBePassedByValue() Returns whether this parameter can be passed by value */ ZEND_METHOD(reflection_parameter, canBePassedByValue) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(param); /* true if it's ZEND_SEND_BY_VAL or ZEND_SEND_PREFER_REF */ RETVAL_BOOL(param->arg_info->pass_by_reference != ZEND_SEND_BY_REF); } /* }}} */ /* {{{ proto public bool ReflectionParameter::getPosition() Returns whether this parameter is an optional parameter */ ZEND_METHOD(reflection_parameter, getPosition) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(param); RETVAL_LONG(param->offset); } /* }}} */ /* {{{ proto public bool ReflectionParameter::isOptional() Returns whether this parameter is an optional parameter */ ZEND_METHOD(reflection_parameter, isOptional) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(param); RETVAL_BOOL(param->offset >= param->required); } /* }}} */ /* {{{ proto public bool ReflectionParameter::isDefaultValueAvailable() Returns whether the default value of this parameter is available */ ZEND_METHOD(reflection_parameter, isDefaultValueAvailable) { reflection_object *intern; parameter_reference *param; zend_op *precv; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(param); if (param->fptr->type != ZEND_USER_FUNCTION) { RETURN_FALSE; } if (param->offset < param->required) { RETURN_FALSE; } precv = _get_recv_op((zend_op_array*)param->fptr, param->offset); if (!precv || precv->opcode != ZEND_RECV_INIT || precv->op2_type == IS_UNUSED) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto public bool ReflectionParameter::getDefaultValue() Returns the default value of this parameter or throws an exception */ ZEND_METHOD(reflection_parameter, getDefaultValue) { reflection_object *intern; parameter_reference *param; zend_op *precv; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(param); if (param->fptr->type != ZEND_USER_FUNCTION) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Cannot determine default value for internal functions"); return; } if (param->offset < param->required) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Parameter is not optional"); return; } precv = _get_recv_op((zend_op_array*)param->fptr, param->offset); if (!precv || precv->opcode != ZEND_RECV_INIT || precv->op2_type == IS_UNUSED) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Internal error"); return; } *return_value = *precv->op2.zv; INIT_PZVAL(return_value); if (Z_TYPE_P(return_value) != IS_CONSTANT && Z_TYPE_P(return_value) != IS_CONSTANT_ARRAY) { zval_copy_ctor(return_value); } zval_update_constant_ex(&return_value, (void*)0, param->fptr->common.scope TSRMLS_CC); } /* }}} */ /* {{{ proto public static mixed ReflectionMethod::export(mixed class, string name [, bool return]) throws ReflectionException Exports a reflection object. Returns the output if TRUE is specified for return, printing it otherwise. */ ZEND_METHOD(reflection_method, export) { _reflection_export(INTERNAL_FUNCTION_PARAM_PASSTHRU, reflection_method_ptr, 2); } /* }}} */ /* {{{ proto public void ReflectionMethod::__construct(mixed class_or_method [, string name]) Constructor. Throws an Exception in case the given method does not exist */ ZEND_METHOD(reflection_method, __construct) { zval *name, *classname; zval *object, *orig_obj; reflection_object *intern; char *lcname; zend_class_entry **pce; zend_class_entry *ce; zend_function *mptr; char *name_str, *tmp; int name_len, tmp_len; zval ztmp; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "zs", &classname, &name_str, &name_len) == FAILURE) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name_str, &name_len) == FAILURE) { return; } if ((tmp = strstr(name_str, "::")) == NULL) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Invalid method name %s", name_str); return; } classname = &ztmp; tmp_len = tmp - name_str; ZVAL_STRINGL(classname, name_str, tmp_len, 1); name_len = name_len - (tmp_len + 2); name_str = tmp + 2; orig_obj = NULL; } else if (Z_TYPE_P(classname) == IS_OBJECT) { orig_obj = classname; } else { orig_obj = NULL; } object = getThis(); intern = (reflection_object *) zend_object_store_get_object(object TSRMLS_CC); if (intern == NULL) { return; } /* Find the class entry */ switch (Z_TYPE_P(classname)) { case IS_STRING: if (zend_lookup_class(Z_STRVAL_P(classname), Z_STRLEN_P(classname), &pce TSRMLS_CC) == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Class %s does not exist", Z_STRVAL_P(classname)); if (classname == &ztmp) { zval_dtor(&ztmp); } return; } ce = *pce; break; case IS_OBJECT: ce = Z_OBJCE_P(classname); break; default: if (classname == &ztmp) { zval_dtor(&ztmp); } _DO_THROW("The parameter class is expected to be either a string or an object"); /* returns out of this function */ } if (classname == &ztmp) { zval_dtor(&ztmp); } lcname = zend_str_tolower_dup(name_str, name_len); if (ce == zend_ce_closure && orig_obj && (name_len == sizeof(ZEND_INVOKE_FUNC_NAME)-1) && memcmp(lcname, ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME)-1) == 0 && (mptr = zend_get_closure_invoke_method(orig_obj TSRMLS_CC)) != NULL) { /* do nothing, mptr already set */ } else if (zend_hash_find(&ce->function_table, lcname, name_len + 1, (void **) &mptr) == FAILURE) { efree(lcname); zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Method %s::%s() does not exist", ce->name, name_str); return; } efree(lcname); MAKE_STD_ZVAL(classname); ZVAL_STRINGL(classname, mptr->common.scope->name, mptr->common.scope->name_length, 1); reflection_update_property(object, "class", classname); MAKE_STD_ZVAL(name); ZVAL_STRING(name, mptr->common.function_name, 1); reflection_update_property(object, "name", name); intern->ptr = mptr; intern->ref_type = REF_TYPE_FUNCTION; intern->ce = ce; } /* }}} */ /* {{{ proto public string ReflectionMethod::__toString() Returns a string representation */ ZEND_METHOD(reflection_method, __toString) { reflection_object *intern; zend_function *mptr; string str; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(mptr); string_init(&str); _function_string(&str, mptr, intern->ce, "" TSRMLS_CC); RETURN_STRINGL(str.string, str.len - 1, 0); } /* }}} */ /* {{{ proto public mixed ReflectionMethod::getClosure([mixed object]) Invokes the function */ ZEND_METHOD(reflection_method, getClosure) { reflection_object *intern; zval *obj; zend_function *mptr; METHOD_NOTSTATIC(reflection_method_ptr); GET_REFLECTION_OBJECT_PTR(mptr); if (mptr->common.fn_flags & ZEND_ACC_STATIC) { zend_create_closure(return_value, mptr, mptr->common.scope, NULL TSRMLS_CC); } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "o", &obj) == FAILURE) { return; } if (!instanceof_function(Z_OBJCE_P(obj), mptr->common.scope TSRMLS_CC)) { _DO_THROW("Given object is not an instance of the class this method was declared in"); /* Returns from this function */ } /* This is an original closure object and __invoke is to be called. */ if (Z_OBJCE_P(obj) == zend_ce_closure && mptr->type == ZEND_INTERNAL_FUNCTION && (mptr->internal_function.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) != 0) { RETURN_ZVAL(obj, 1, 0); } else { zend_create_closure(return_value, mptr, mptr->common.scope, obj TSRMLS_CC); } } } /* }}} */ /* {{{ proto public mixed ReflectionMethod::invoke(mixed object, mixed* args) Invokes the method. */ ZEND_METHOD(reflection_method, invoke) { zval *retval_ptr; zval ***params = NULL; zval *object_ptr; reflection_object *intern; zend_function *mptr; int result, num_args = 0; zend_fcall_info fci; zend_fcall_info_cache fcc; zend_class_entry *obj_ce; METHOD_NOTSTATIC(reflection_method_ptr); GET_REFLECTION_OBJECT_PTR(mptr); if ((!(mptr->common.fn_flags & ZEND_ACC_PUBLIC) || (mptr->common.fn_flags & ZEND_ACC_ABSTRACT)) && intern->ignore_visibility == 0) { if (mptr->common.fn_flags & ZEND_ACC_ABSTRACT) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Trying to invoke abstract method %s::%s()", mptr->common.scope->name, mptr->common.function_name); } else { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Trying to invoke %s method %s::%s() from scope %s", mptr->common.fn_flags & ZEND_ACC_PROTECTED ? "protected" : "private", mptr->common.scope->name, mptr->common.function_name, Z_OBJCE_P(getThis())->name); } return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &params, &num_args) == FAILURE) { return; } /* In case this is a static method, we should'nt pass an object_ptr * (which is used as calling context aka $this). We can thus ignore the * first parameter. * * Else, we verify that the given object is an instance of the class. */ if (mptr->common.fn_flags & ZEND_ACC_STATIC) { object_ptr = NULL; obj_ce = mptr->common.scope; } else { if (Z_TYPE_PP(params[0]) != IS_OBJECT) { efree(params); _DO_THROW("Non-object passed to Invoke()"); /* Returns from this function */ } obj_ce = Z_OBJCE_PP(params[0]); if (!instanceof_function(obj_ce, mptr->common.scope TSRMLS_CC)) { if (params) { efree(params); } _DO_THROW("Given object is not an instance of the class this method was declared in"); /* Returns from this function */ } object_ptr = *params[0]; } fci.size = sizeof(fci); fci.function_table = NULL; fci.function_name = NULL; fci.symbol_table = NULL; fci.object_ptr = object_ptr; fci.retval_ptr_ptr = &retval_ptr; fci.param_count = num_args - 1; fci.params = params + 1; fci.no_separation = 1; fcc.initialized = 1; fcc.function_handler = mptr; fcc.calling_scope = obj_ce; fcc.called_scope = obj_ce; fcc.object_ptr = object_ptr; result = zend_call_function(&fci, &fcc TSRMLS_CC); if (params) { efree(params); } if (result == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Invocation of method %s::%s() failed", mptr->common.scope->name, mptr->common.function_name); return; } if (retval_ptr) { COPY_PZVAL_TO_ZVAL(*return_value, retval_ptr); } } /* }}} */ /* {{{ proto public mixed ReflectionMethod::invokeArgs(mixed object, array args) Invokes the function and pass its arguments as array. */ ZEND_METHOD(reflection_method, invokeArgs) { zval *retval_ptr; zval ***params; zval *object; reflection_object *intern; zend_function *mptr; int argc; int result; zend_fcall_info fci; zend_fcall_info_cache fcc; zend_class_entry *obj_ce; zval *param_array; METHOD_NOTSTATIC(reflection_method_ptr); GET_REFLECTION_OBJECT_PTR(mptr); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "o!a", &object, &param_array) == FAILURE) { return; } if ((!(mptr->common.fn_flags & ZEND_ACC_PUBLIC) || (mptr->common.fn_flags & ZEND_ACC_ABSTRACT)) && intern->ignore_visibility == 0) { if (mptr->common.fn_flags & ZEND_ACC_ABSTRACT) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Trying to invoke abstract method %s::%s()", mptr->common.scope->name, mptr->common.function_name); } else { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Trying to invoke %s method %s::%s() from scope %s", mptr->common.fn_flags & ZEND_ACC_PROTECTED ? "protected" : "private", mptr->common.scope->name, mptr->common.function_name, Z_OBJCE_P(getThis())->name); } return; } argc = zend_hash_num_elements(Z_ARRVAL_P(param_array)); params = safe_emalloc(sizeof(zval **), argc, 0); zend_hash_apply_with_argument(Z_ARRVAL_P(param_array), (apply_func_arg_t)_zval_array_to_c_array, &params TSRMLS_CC); params -= argc; /* In case this is a static method, we should'nt pass an object_ptr * (which is used as calling context aka $this). We can thus ignore the * first parameter. * * Else, we verify that the given object is an instance of the class. */ if (mptr->common.fn_flags & ZEND_ACC_STATIC) { object = NULL; obj_ce = mptr->common.scope; } else { if (!object) { efree(params); zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Trying to invoke non static method %s::%s() without an object", mptr->common.scope->name, mptr->common.function_name); return; } obj_ce = Z_OBJCE_P(object); if (!instanceof_function(obj_ce, mptr->common.scope TSRMLS_CC)) { efree(params); _DO_THROW("Given object is not an instance of the class this method was declared in"); /* Returns from this function */ } } fci.size = sizeof(fci); fci.function_table = NULL; fci.function_name = NULL; fci.symbol_table = NULL; fci.object_ptr = object; fci.retval_ptr_ptr = &retval_ptr; fci.param_count = argc; fci.params = params; fci.no_separation = 1; fcc.initialized = 1; fcc.function_handler = mptr; fcc.calling_scope = obj_ce; fcc.called_scope = obj_ce; fcc.object_ptr = object; result = zend_call_function(&fci, &fcc TSRMLS_CC); efree(params); if (result == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Invocation of method %s::%s() failed", mptr->common.scope->name, mptr->common.function_name); return; } if (retval_ptr) { COPY_PZVAL_TO_ZVAL(*return_value, retval_ptr); } } /* }}} */ /* {{{ proto public bool ReflectionMethod::isFinal() Returns whether this method is final */ ZEND_METHOD(reflection_method, isFinal) { _function_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_FINAL); } /* }}} */ /* {{{ proto public bool ReflectionMethod::isAbstract() Returns whether this method is abstract */ ZEND_METHOD(reflection_method, isAbstract) { _function_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_ABSTRACT); } /* }}} */ /* {{{ proto public bool ReflectionMethod::isPublic() Returns whether this method is public */ ZEND_METHOD(reflection_method, isPublic) { _function_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_PUBLIC); } /* }}} */ /* {{{ proto public bool ReflectionMethod::isPrivate() Returns whether this method is private */ ZEND_METHOD(reflection_method, isPrivate) { _function_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_PRIVATE); } /* }}} */ /* {{{ proto public bool ReflectionMethod::isProtected() Returns whether this method is protected */ ZEND_METHOD(reflection_method, isProtected) { _function_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_PROTECTED); } /* }}} */ /* {{{ proto public bool ReflectionMethod::isStatic() Returns whether this method is static */ ZEND_METHOD(reflection_method, isStatic) { _function_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_STATIC); } /* }}} */ /* {{{ proto public bool ReflectionFunction::isDeprecated() Returns whether this function is deprecated */ ZEND_METHOD(reflection_function, isDeprecated) { _function_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_DEPRECATED); } /* }}} */ /* {{{ proto public bool ReflectionFunction::inNamespace() Returns whether this function is defined in namespace */ ZEND_METHOD(reflection_function, inNamespace) { zval **name; const char *backslash; if (zend_parse_parameters_none() == FAILURE) { return; } if (zend_hash_find(Z_OBJPROP_P(getThis()), "name", sizeof("name"), (void **) &name) == FAILURE) { RETURN_FALSE; } if (Z_TYPE_PP(name) == IS_STRING && (backslash = zend_memrchr(Z_STRVAL_PP(name), '\\', Z_STRLEN_PP(name))) && backslash > Z_STRVAL_PP(name)) { RETURN_TRUE; } RETURN_FALSE; } /* }}} */ /* {{{ proto public string ReflectionFunction::getNamespaceName() Returns the name of namespace where this function is defined */ ZEND_METHOD(reflection_function, getNamespaceName) { zval **name; const char *backslash; if (zend_parse_parameters_none() == FAILURE) { return; } if (zend_hash_find(Z_OBJPROP_P(getThis()), "name", sizeof("name"), (void **) &name) == FAILURE) { RETURN_FALSE; } if (Z_TYPE_PP(name) == IS_STRING && (backslash = zend_memrchr(Z_STRVAL_PP(name), '\\', Z_STRLEN_PP(name))) && backslash > Z_STRVAL_PP(name)) { RETURN_STRINGL(Z_STRVAL_PP(name), backslash - Z_STRVAL_PP(name), 1); } RETURN_EMPTY_STRING(); } /* }}} */ /* {{{ proto public string ReflectionFunction::getShortName() Returns the short name of the function (without namespace part) */ ZEND_METHOD(reflection_function, getShortName) { zval **name; const char *backslash; if (zend_parse_parameters_none() == FAILURE) { return; } if (zend_hash_find(Z_OBJPROP_P(getThis()), "name", sizeof("name"), (void **) &name) == FAILURE) { RETURN_FALSE; } if (Z_TYPE_PP(name) == IS_STRING && (backslash = zend_memrchr(Z_STRVAL_PP(name), '\\', Z_STRLEN_PP(name))) && backslash > Z_STRVAL_PP(name)) { RETURN_STRINGL(backslash + 1, Z_STRLEN_PP(name) - (backslash - Z_STRVAL_PP(name) + 1), 1); } RETURN_ZVAL(*name, 1, 0); } /* }}} */ /* {{{ proto public bool ReflectionMethod::isConstructor() Returns whether this method is the constructor */ ZEND_METHOD(reflection_method, isConstructor) { reflection_object *intern; zend_function *mptr; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(mptr); /* we need to check if the ctor is the ctor of the class level we we * looking at since we might be looking at an inherited old style ctor * defined in base class. */ RETURN_BOOL(mptr->common.fn_flags & ZEND_ACC_CTOR && intern->ce->constructor && intern->ce->constructor->common.scope == mptr->common.scope); } /* }}} */ /* {{{ proto public bool ReflectionMethod::isDestructor() Returns whether this method is static */ ZEND_METHOD(reflection_method, isDestructor) { reflection_object *intern; zend_function *mptr; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(mptr); RETURN_BOOL(mptr->common.fn_flags & ZEND_ACC_DTOR); } /* }}} */ /* {{{ proto public int ReflectionMethod::getModifiers() Returns a bitfield of the access modifiers for this method */ ZEND_METHOD(reflection_method, getModifiers) { reflection_object *intern; zend_function *mptr; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(mptr); RETURN_LONG(mptr->common.fn_flags); } /* }}} */ /* {{{ proto public ReflectionClass ReflectionMethod::getDeclaringClass() Get the declaring class */ ZEND_METHOD(reflection_method, getDeclaringClass) { reflection_object *intern; zend_function *mptr; METHOD_NOTSTATIC(reflection_method_ptr); GET_REFLECTION_OBJECT_PTR(mptr); if (zend_parse_parameters_none() == FAILURE) { return; } zend_reflection_class_factory(mptr->common.scope, return_value TSRMLS_CC); } /* }}} */ /* {{{ proto public ReflectionClass ReflectionMethod::getPrototype() Get the prototype */ ZEND_METHOD(reflection_method, getPrototype) { reflection_object *intern; zend_function *mptr; METHOD_NOTSTATIC(reflection_method_ptr); GET_REFLECTION_OBJECT_PTR(mptr); if (zend_parse_parameters_none() == FAILURE) { return; } if (!mptr->common.prototype) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Method %s::%s does not have a prototype", intern->ce->name, mptr->common.function_name); return; } reflection_method_factory(mptr->common.prototype->common.scope, mptr->common.prototype, NULL, return_value TSRMLS_CC); } /* }}} */ /* {{{ proto public void ReflectionMethod::setAccessible(bool visible) Sets whether non-public methods can be invoked */ ZEND_METHOD(reflection_method, setAccessible) { reflection_object *intern; zend_bool visible; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "b", &visible) == FAILURE) { return; } intern = (reflection_object *) zend_object_store_get_object(getThis() TSRMLS_CC); if (intern == NULL) { return; } intern->ignore_visibility = visible; } /* }}} */ /* {{{ proto public static mixed ReflectionClass::export(mixed argument [, bool return]) throws ReflectionException Exports a reflection object. Returns the output if TRUE is specified for return, printing it otherwise. */ ZEND_METHOD(reflection_class, export) { _reflection_export(INTERNAL_FUNCTION_PARAM_PASSTHRU, reflection_class_ptr, 1); } /* }}} */ /* {{{ reflection_class_object_ctor */ static void reflection_class_object_ctor(INTERNAL_FUNCTION_PARAMETERS, int is_object) { zval *argument; zval *object; zval *classname; reflection_object *intern; zend_class_entry **ce; if (is_object) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "o", &argument) == FAILURE) { return; } } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z/", &argument) == FAILURE) { return; } } object = getThis(); intern = (reflection_object *) zend_object_store_get_object(object TSRMLS_CC); if (intern == NULL) { return; } if (Z_TYPE_P(argument) == IS_OBJECT) { MAKE_STD_ZVAL(classname); ZVAL_STRINGL(classname, Z_OBJCE_P(argument)->name, Z_OBJCE_P(argument)->name_length, 1); reflection_update_property(object, "name", classname); intern->ptr = Z_OBJCE_P(argument); if (is_object) { intern->obj = argument; zval_add_ref(&argument); } } else { convert_to_string_ex(&argument); if (zend_lookup_class(Z_STRVAL_P(argument), Z_STRLEN_P(argument), &ce TSRMLS_CC) == FAILURE) { if (!EG(exception)) { zend_throw_exception_ex(reflection_exception_ptr, -1 TSRMLS_CC, "Class %s does not exist", Z_STRVAL_P(argument)); } return; } MAKE_STD_ZVAL(classname); ZVAL_STRINGL(classname, (*ce)->name, (*ce)->name_length, 1); reflection_update_property(object, "name", classname); intern->ptr = *ce; } intern->ref_type = REF_TYPE_OTHER; } /* }}} */ /* {{{ proto public void ReflectionClass::__construct(mixed argument) throws ReflectionException Constructor. Takes a string or an instance as an argument */ ZEND_METHOD(reflection_class, __construct) { reflection_class_object_ctor(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ add_class_vars */ static void add_class_vars(zend_class_entry *ce, int statics, zval *return_value TSRMLS_DC) { HashPosition pos; zend_property_info *prop_info; zval *prop, *prop_copy; char *key; uint key_len; ulong num_index; zend_hash_internal_pointer_reset_ex(&ce->properties_info, &pos); while (zend_hash_get_current_data_ex(&ce->properties_info, (void **) &prop_info, &pos) == SUCCESS) { zend_hash_get_current_key_ex(&ce->properties_info, &key, &key_len, &num_index, 0, &pos); zend_hash_move_forward_ex(&ce->properties_info, &pos); if (((prop_info->flags & ZEND_ACC_SHADOW) && prop_info->ce != ce) || ((prop_info->flags & ZEND_ACC_PROTECTED) && !zend_check_protected(prop_info->ce, ce)) || ((prop_info->flags & ZEND_ACC_PRIVATE) && prop_info->ce != ce)) { continue; } prop = NULL; if (prop_info->offset >= 0) { if (statics && (prop_info->flags & ZEND_ACC_STATIC) != 0) { prop = ce->default_static_members_table[prop_info->offset]; } else if (!statics && (prop_info->flags & ZEND_ACC_STATIC) == 0) { prop = ce->default_properties_table[prop_info->offset]; } } if (!prop) { continue; } /* copy: enforce read only access */ ALLOC_ZVAL(prop_copy); *prop_copy = *prop; zval_copy_ctor(prop_copy); INIT_PZVAL(prop_copy); /* this is necessary to make it able to work with default array * properties, returned to user */ if (Z_TYPE_P(prop_copy) == IS_CONSTANT_ARRAY || (Z_TYPE_P(prop_copy) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zval_update_constant(&prop_copy, (void *) 1 TSRMLS_CC); } add_assoc_zval(return_value, key, prop_copy); } } /* }}} */ /* {{{ proto public array ReflectionClass::getStaticProperties() Returns an associative array containing all static property values of the class */ ZEND_METHOD(reflection_class, getStaticProperties) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); zend_update_class_constants(ce TSRMLS_CC); array_init(return_value); add_class_vars(ce, 1, return_value TSRMLS_CC); } /* }}} */ /* {{{ proto public mixed ReflectionClass::getStaticPropertyValue(string name [, mixed default]) Returns the value of a static property */ ZEND_METHOD(reflection_class, getStaticPropertyValue) { reflection_object *intern; zend_class_entry *ce; char *name; int name_len; zval **prop, *def_value = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|z", &name, &name_len, &def_value) == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); zend_update_class_constants(ce TSRMLS_CC); prop = zend_std_get_static_property(ce, name, name_len, 1, NULL TSRMLS_CC); if (!prop) { if (def_value) { RETURN_ZVAL(def_value, 1, 0); } else { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Class %s does not have a property named %s", ce->name, name); } return; } else { RETURN_ZVAL(*prop, 1, 0); } } /* }}} */ /* {{{ proto public void ReflectionClass::setStaticPropertyValue($name, $value) Sets the value of a static property */ ZEND_METHOD(reflection_class, setStaticPropertyValue) { reflection_object *intern; zend_class_entry *ce; char *name; int name_len; zval **variable_ptr, *value; int refcount; zend_uchar is_ref; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz", &name, &name_len, &value) == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); zend_update_class_constants(ce TSRMLS_CC); variable_ptr = zend_std_get_static_property(ce, name, name_len, 1, NULL TSRMLS_CC); if (!variable_ptr) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Class %s does not have a property named %s", ce->name, name); return; } refcount = Z_REFCOUNT_PP(variable_ptr); is_ref = Z_ISREF_PP(variable_ptr); zval_dtor(*variable_ptr); **variable_ptr = *value; zval_copy_ctor(*variable_ptr); Z_SET_REFCOUNT_PP(variable_ptr, refcount); Z_SET_ISREF_TO_PP(variable_ptr, is_ref); } /* }}} */ /* {{{ proto public array ReflectionClass::getDefaultProperties() Returns an associative array containing copies of all default property values of the class */ ZEND_METHOD(reflection_class, getDefaultProperties) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); array_init(return_value); zend_update_class_constants(ce TSRMLS_CC); add_class_vars(ce, 1, return_value TSRMLS_CC); add_class_vars(ce, 0, return_value TSRMLS_CC); } /* }}} */ /* {{{ proto public string ReflectionClass::__toString() Returns a string representation */ ZEND_METHOD(reflection_class, __toString) { reflection_object *intern; zend_class_entry *ce; string str; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); string_init(&str); _class_string(&str, ce, intern->obj, "" TSRMLS_CC); RETURN_STRINGL(str.string, str.len - 1, 0); } /* }}} */ /* {{{ proto public string ReflectionClass::getName() Returns the class' name */ ZEND_METHOD(reflection_class, getName) { if (zend_parse_parameters_none() == FAILURE) { return; } _default_get_entry(getThis(), "name", sizeof("name"), return_value TSRMLS_CC); } /* }}} */ /* {{{ proto public bool ReflectionClass::isInternal() Returns whether this class is an internal class */ ZEND_METHOD(reflection_class, isInternal) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); RETURN_BOOL(ce->type == ZEND_INTERNAL_CLASS); } /* }}} */ /* {{{ proto public bool ReflectionClass::isUserDefined() Returns whether this class is user-defined */ ZEND_METHOD(reflection_class, isUserDefined) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); RETURN_BOOL(ce->type == ZEND_USER_CLASS); } /* }}} */ /* {{{ proto public string ReflectionClass::getFileName() Returns the filename of the file this class was declared in */ ZEND_METHOD(reflection_class, getFileName) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); if (ce->type == ZEND_USER_CLASS) { RETURN_STRING(ce->info.user.filename, 1); } RETURN_FALSE; } /* }}} */ /* {{{ proto public int ReflectionClass::getStartLine() Returns the line this class' declaration starts at */ ZEND_METHOD(reflection_class, getStartLine) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); if (ce->type == ZEND_USER_FUNCTION) { RETURN_LONG(ce->info.user.line_start); } RETURN_FALSE; } /* }}} */ /* {{{ proto public int ReflectionClass::getEndLine() Returns the line this class' declaration ends at */ ZEND_METHOD(reflection_class, getEndLine) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); if (ce->type == ZEND_USER_CLASS) { RETURN_LONG(ce->info.user.line_end); } RETURN_FALSE; } /* }}} */ /* {{{ proto public string ReflectionClass::getDocComment() Returns the doc comment for this class */ ZEND_METHOD(reflection_class, getDocComment) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); if (ce->type == ZEND_USER_CLASS && ce->info.user.doc_comment) { RETURN_STRINGL(ce->info.user.doc_comment, ce->info.user.doc_comment_len, 1); } RETURN_FALSE; } /* }}} */ /* {{{ proto public ReflectionMethod ReflectionClass::getConstructor() Returns the class' constructor if there is one, NULL otherwise */ ZEND_METHOD(reflection_class, getConstructor) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); if (ce->constructor) { reflection_method_factory(ce, ce->constructor, NULL, return_value TSRMLS_CC); } else { RETURN_NULL(); } } /* }}} */ /* {{{ proto public bool ReflectionClass::hasMethod(string name) Returns whether a method exists or not */ ZEND_METHOD(reflection_class, hasMethod) { reflection_object *intern; zend_class_entry *ce; char *name, *lc_name; int name_len; METHOD_NOTSTATIC(reflection_class_ptr); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); lc_name = zend_str_tolower_dup(name, name_len); if ((ce == zend_ce_closure && (name_len == sizeof(ZEND_INVOKE_FUNC_NAME)-1) && memcmp(lc_name, ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME)-1) == 0) || zend_hash_exists(&ce->function_table, lc_name, name_len + 1)) { efree(lc_name); RETURN_TRUE; } else { efree(lc_name); RETURN_FALSE; } } /* }}} */ /* {{{ proto public ReflectionMethod ReflectionClass::getMethod(string name) throws ReflectionException Returns the class' method specified by its name */ ZEND_METHOD(reflection_class, getMethod) { reflection_object *intern; zend_class_entry *ce; zend_function *mptr; zval obj_tmp; char *name, *lc_name; int name_len; METHOD_NOTSTATIC(reflection_class_ptr); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); lc_name = zend_str_tolower_dup(name, name_len); if (ce == zend_ce_closure && intern->obj && (name_len == sizeof(ZEND_INVOKE_FUNC_NAME)-1) && memcmp(lc_name, ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME)-1) == 0 && (mptr = zend_get_closure_invoke_method(intern->obj TSRMLS_CC)) != NULL) { /* don't assign closure_object since we only reflect the invoke handler method and not the closure definition itself */ reflection_method_factory(ce, mptr, NULL, return_value TSRMLS_CC); efree(lc_name); } else if (ce == zend_ce_closure && !intern->obj && (name_len == sizeof(ZEND_INVOKE_FUNC_NAME)-1) && memcmp(lc_name, ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME)-1) == 0 && object_init_ex(&obj_tmp, ce) == SUCCESS && (mptr = zend_get_closure_invoke_method(&obj_tmp TSRMLS_CC)) != NULL) { /* don't assign closure_object since we only reflect the invoke handler method and not the closure definition itself */ reflection_method_factory(ce, mptr, NULL, return_value TSRMLS_CC); zval_dtor(&obj_tmp); efree(lc_name); } else if (zend_hash_find(&ce->function_table, lc_name, name_len + 1, (void**) &mptr) == SUCCESS) { reflection_method_factory(ce, mptr, NULL, return_value TSRMLS_CC); efree(lc_name); } else { efree(lc_name); zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Method %s does not exist", name); return; } } /* }}} */ /* {{{ _addmethod */ static void _addmethod(zend_function *mptr, zend_class_entry *ce, zval *retval, long filter, zval *obj TSRMLS_DC) { zval *method; uint len = strlen(mptr->common.function_name); zend_function *closure; if (mptr->common.fn_flags & filter) { ALLOC_ZVAL(method); if (ce == zend_ce_closure && obj && (len == sizeof(ZEND_INVOKE_FUNC_NAME)-1) && memcmp(mptr->common.function_name, ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME)-1) == 0 && (closure = zend_get_closure_invoke_method(obj TSRMLS_CC)) != NULL) { mptr = closure; } /* don't assign closure_object since we only reflect the invoke handler method and not the closure definition itself, even if we have a closure */ reflection_method_factory(ce, mptr, NULL, method TSRMLS_CC); add_next_index_zval(retval, method); } } /* }}} */ /* {{{ _addmethod */ static int _addmethod_va(zend_function *mptr TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) { zend_class_entry *ce = *va_arg(args, zend_class_entry**); zval *retval = va_arg(args, zval*); long filter = va_arg(args, long); zval *obj = va_arg(args, zval *); _addmethod(mptr, ce, retval, filter, obj TSRMLS_CC); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* {{{ proto public ReflectionMethod[] ReflectionClass::getMethods([long $filter]) Returns an array of this class' methods */ ZEND_METHOD(reflection_class, getMethods) { reflection_object *intern; zend_class_entry *ce; long filter = 0; int argc = ZEND_NUM_ARGS(); METHOD_NOTSTATIC(reflection_class_ptr); if (argc) { if (zend_parse_parameters(argc TSRMLS_CC, "|l", &filter) == FAILURE) { return; } } else { /* No parameters given, default to "return all" */ filter = ZEND_ACC_PPP_MASK | ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL | ZEND_ACC_STATIC; } GET_REFLECTION_OBJECT_PTR(ce); array_init(return_value); zend_hash_apply_with_arguments(&ce->function_table TSRMLS_CC, (apply_func_args_t) _addmethod_va, 4, &ce, return_value, filter, intern->obj); if (intern->obj && instanceof_function(ce, zend_ce_closure TSRMLS_CC)) { zend_function *closure = zend_get_closure_invoke_method(intern->obj TSRMLS_CC); if (closure) { _addmethod(closure, ce, return_value, filter, intern->obj TSRMLS_CC); _free_function(closure TSRMLS_CC); } } } /* }}} */ /* {{{ proto public bool ReflectionClass::hasProperty(string name) Returns whether a property exists or not */ ZEND_METHOD(reflection_class, hasProperty) { reflection_object *intern; zend_property_info *property_info; zend_class_entry *ce; char *name; int name_len; zval *property; METHOD_NOTSTATIC(reflection_class_ptr); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); if (zend_hash_find(&ce->properties_info, name, name_len+1, (void **) &property_info) == SUCCESS) { if (property_info->flags & ZEND_ACC_SHADOW) { RETURN_FALSE; } RETURN_TRUE; } else { if (intern->obj && Z_OBJ_HANDLER_P(intern->obj, has_property)) { MAKE_STD_ZVAL(property); ZVAL_STRINGL(property, name, name_len, 1); if (Z_OBJ_HANDLER_P(intern->obj, has_property)(intern->obj, property, 2, 0 TSRMLS_CC)) { zval_ptr_dtor(&property); RETURN_TRUE; } zval_ptr_dtor(&property); } RETURN_FALSE; } } /* }}} */ /* {{{ proto public ReflectionProperty ReflectionClass::getProperty(string name) throws ReflectionException Returns the class' property specified by its name */ ZEND_METHOD(reflection_class, getProperty) { reflection_object *intern; zend_class_entry *ce, **pce; zend_property_info *property_info; char *name, *tmp, *classname; int name_len, classname_len; METHOD_NOTSTATIC(reflection_class_ptr); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); if (zend_hash_find(&ce->properties_info, name, name_len + 1, (void**) &property_info) == SUCCESS) { if ((property_info->flags & ZEND_ACC_SHADOW) == 0) { reflection_property_factory(ce, property_info, return_value TSRMLS_CC); return; } } else if (intern->obj) { /* Check for dynamic properties */ if (zend_hash_exists(Z_OBJ_HT_P(intern->obj)->get_properties(intern->obj TSRMLS_CC), name, name_len+1)) { zend_property_info property_info_tmp; property_info_tmp.flags = ZEND_ACC_IMPLICIT_PUBLIC; property_info_tmp.name = estrndup(name, name_len); property_info_tmp.name_length = name_len; property_info_tmp.h = zend_get_hash_value(name, name_len+1); property_info_tmp.doc_comment = NULL; property_info_tmp.ce = ce; reflection_property_factory(ce, &property_info_tmp, return_value TSRMLS_CC); intern = (reflection_object *) zend_object_store_get_object(return_value TSRMLS_CC); intern->ref_type = REF_TYPE_DYNAMIC_PROPERTY; return; } } if ((tmp = strstr(name, "::")) != NULL) { classname_len = tmp - name; classname = zend_str_tolower_dup(name, classname_len); classname[classname_len] = '\0'; name_len = name_len - (classname_len + 2); name = tmp + 2; if (zend_lookup_class(classname, classname_len, &pce TSRMLS_CC) == FAILURE) { if (!EG(exception)) { zend_throw_exception_ex(reflection_exception_ptr, -1 TSRMLS_CC, "Class %s does not exist", classname); } efree(classname); return; } efree(classname); if (!instanceof_function(ce, *pce TSRMLS_CC)) { zend_throw_exception_ex(reflection_exception_ptr, -1 TSRMLS_CC, "Fully qualified property name %s::%s does not specify a base class of %s", (*pce)->name, name, ce->name); return; } ce = *pce; if (zend_hash_find(&ce->properties_info, name, name_len + 1, (void**) &property_info) == SUCCESS && (property_info->flags & ZEND_ACC_SHADOW) == 0) { reflection_property_factory(ce, property_info, return_value TSRMLS_CC); return; } } zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Property %s does not exist", name); } /* }}} */ /* {{{ _addproperty */ static int _addproperty(zend_property_info *pptr TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) { zval *property; zend_class_entry *ce = *va_arg(args, zend_class_entry**); zval *retval = va_arg(args, zval*); long filter = va_arg(args, long); if (pptr->flags & ZEND_ACC_SHADOW) { return 0; } if (pptr->flags & filter) { ALLOC_ZVAL(property); reflection_property_factory(ce, pptr, property TSRMLS_CC); add_next_index_zval(retval, property); } return 0; } /* }}} */ /* {{{ _adddynproperty */ static int _adddynproperty(zval **pptr TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) { zval *property; zend_class_entry *ce = *va_arg(args, zend_class_entry**); zval *retval = va_arg(args, zval*), member; if (hash_key->arKey[0] == '\0') { return 0; /* non public cannot be dynamic */ } ZVAL_STRINGL(&member, hash_key->arKey, hash_key->nKeyLength-1, 0); if (zend_get_property_info(ce, &member, 1 TSRMLS_CC) == &EG(std_property_info)) { MAKE_STD_ZVAL(property); EG(std_property_info).flags = ZEND_ACC_IMPLICIT_PUBLIC; reflection_property_factory(ce, &EG(std_property_info), property TSRMLS_CC); add_next_index_zval(retval, property); } return 0; } /* }}} */ /* {{{ proto public ReflectionProperty[] ReflectionClass::getProperties([long $filter]) Returns an array of this class' properties */ ZEND_METHOD(reflection_class, getProperties) { reflection_object *intern; zend_class_entry *ce; long filter = 0; int argc = ZEND_NUM_ARGS(); METHOD_NOTSTATIC(reflection_class_ptr); if (argc) { if (zend_parse_parameters(argc TSRMLS_CC, "|l", &filter) == FAILURE) { return; } } else { /* No parameters given, default to "return all" */ filter = ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC; } GET_REFLECTION_OBJECT_PTR(ce); array_init(return_value); zend_hash_apply_with_arguments(&ce->properties_info TSRMLS_CC, (apply_func_args_t) _addproperty, 3, &ce, return_value, filter); if (intern->obj && (filter & ZEND_ACC_PUBLIC) != 0 && Z_OBJ_HT_P(intern->obj)->get_properties) { HashTable *properties = Z_OBJ_HT_P(intern->obj)->get_properties(intern->obj TSRMLS_CC); zend_hash_apply_with_arguments(properties TSRMLS_CC, (apply_func_args_t) _adddynproperty, 2, &ce, return_value); } } /* }}} */ /* {{{ proto public bool ReflectionClass::hasConstant(string name) Returns whether a constant exists or not */ ZEND_METHOD(reflection_class, hasConstant) { reflection_object *intern; zend_class_entry *ce; char *name; int name_len; METHOD_NOTSTATIC(reflection_class_ptr); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); if (zend_hash_exists(&ce->constants_table, name, name_len + 1)) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto public array ReflectionClass::getConstants() Returns an associative array containing this class' constants and their values */ ZEND_METHOD(reflection_class, getConstants) { zval *tmp_copy; reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); array_init(return_value); zend_hash_apply_with_argument(&ce->constants_table, (apply_func_arg_t)zval_update_constant_inline_change, ce TSRMLS_CC); zend_hash_copy(Z_ARRVAL_P(return_value), &ce->constants_table, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_copy, sizeof(zval *)); } /* }}} */ /* {{{ proto public mixed ReflectionClass::getConstant(string name) Returns the class' constant specified by its name */ ZEND_METHOD(reflection_class, getConstant) { reflection_object *intern; zend_class_entry *ce; zval **value; char *name; int name_len; METHOD_NOTSTATIC(reflection_class_ptr); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); zend_hash_apply_with_argument(&ce->constants_table, (apply_func_arg_t)zval_update_constant_inline_change, ce TSRMLS_CC); if (zend_hash_find(&ce->constants_table, name, name_len + 1, (void **) &value) == FAILURE) { RETURN_FALSE; } MAKE_COPY_ZVAL(value, return_value); } /* }}} */ /* {{{ _class_check_flag */ static void _class_check_flag(INTERNAL_FUNCTION_PARAMETERS, int mask) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); RETVAL_BOOL(ce->ce_flags & mask); } /* }}} */ /* {{{ proto public bool ReflectionClass::isInstantiable() Returns whether this class is instantiable */ ZEND_METHOD(reflection_class, isInstantiable) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); if (ce->ce_flags & (ZEND_ACC_INTERFACE | ZEND_ACC_EXPLICIT_ABSTRACT_CLASS | ZEND_ACC_IMPLICIT_ABSTRACT_CLASS)) { RETURN_FALSE; } /* Basically, the class is instantiable. Though, if there is a constructor * and it is not publicly accessible, it isn't! */ if (!ce->constructor) { RETURN_TRUE; } RETURN_BOOL(ce->constructor->common.fn_flags & ZEND_ACC_PUBLIC); } /* }}} */ /* {{{ proto public bool ReflectionClass::isCloneable() Returns whether this class is cloneable */ ZEND_METHOD(reflection_class, isCloneable) { reflection_object *intern; zend_class_entry *ce; zval obj; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); if (ce->ce_flags & (ZEND_ACC_INTERFACE | ZEND_ACC_TRAIT | ZEND_ACC_EXPLICIT_ABSTRACT_CLASS | ZEND_ACC_IMPLICIT_ABSTRACT_CLASS)) { RETURN_FALSE; } if (intern->obj) { if (ce->clone) { RETURN_BOOL(ce->clone->common.fn_flags & ZEND_ACC_PUBLIC); } else { RETURN_BOOL(Z_OBJ_HANDLER_P(intern->obj, clone_obj) != NULL); } } else { if (ce->clone) { RETURN_BOOL(ce->clone->common.fn_flags & ZEND_ACC_PUBLIC); } else { object_init_ex(&obj, ce); RETVAL_BOOL(Z_OBJ_HANDLER(obj, clone_obj) != NULL); zval_dtor(&obj); } } } /* }}} */ /* {{{ proto public bool ReflectionClass::isInterface() Returns whether this is an interface or a class */ ZEND_METHOD(reflection_class, isInterface) { _class_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_INTERFACE); } /* }}} */ /* {{{ proto public bool ReflectionClass::isTrait() Returns whether this is a trait */ ZEND_METHOD(reflection_class, isTrait) { _class_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_TRAIT & ~ZEND_ACC_EXPLICIT_ABSTRACT_CLASS); } /* }}} */ /* {{{ proto public bool ReflectionClass::isFinal() Returns whether this class is final */ ZEND_METHOD(reflection_class, isFinal) { _class_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_FINAL_CLASS); } /* }}} */ /* {{{ proto public bool ReflectionClass::isAbstract() Returns whether this class is abstract */ ZEND_METHOD(reflection_class, isAbstract) { _class_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_IMPLICIT_ABSTRACT_CLASS|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS); } /* }}} */ /* {{{ proto public int ReflectionClass::getModifiers() Returns a bitfield of the access modifiers for this class */ ZEND_METHOD(reflection_class, getModifiers) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); RETURN_LONG(ce->ce_flags); } /* }}} */ /* {{{ proto public bool ReflectionClass::isInstance(stdclass object) Returns whether the given object is an instance of this class */ ZEND_METHOD(reflection_class, isInstance) { reflection_object *intern; zend_class_entry *ce; zval *object; METHOD_NOTSTATIC(reflection_class_ptr); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "o", &object) == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); RETURN_BOOL(HAS_CLASS_ENTRY(*object) && instanceof_function(Z_OBJCE_P(object), ce TSRMLS_CC)); } /* }}} */ /* {{{ proto public stdclass ReflectionClass::newInstance(mixed* args, ...) Returns an instance of this class */ ZEND_METHOD(reflection_class, newInstance) { zval *retval_ptr = NULL; reflection_object *intern; zend_class_entry *ce; METHOD_NOTSTATIC(reflection_class_ptr); GET_REFLECTION_OBJECT_PTR(ce); /* Run the constructor if there is one */ if (ce->constructor) { zval ***params = NULL; int num_args = 0; zend_fcall_info fci; zend_fcall_info_cache fcc; if (!(ce->constructor->common.fn_flags & ZEND_ACC_PUBLIC)) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Access to non-public constructor of class %s", ce->name); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "*", &params, &num_args) == FAILURE) { if (params) { efree(params); } RETURN_FALSE; } object_init_ex(return_value, ce); fci.size = sizeof(fci); fci.function_table = EG(function_table); fci.function_name = NULL; fci.symbol_table = NULL; fci.object_ptr = return_value; fci.retval_ptr_ptr = &retval_ptr; fci.param_count = num_args; fci.params = params; fci.no_separation = 1; fcc.initialized = 1; fcc.function_handler = ce->constructor; fcc.calling_scope = EG(scope); fcc.called_scope = Z_OBJCE_P(return_value); fcc.object_ptr = return_value; if (zend_call_function(&fci, &fcc TSRMLS_CC) == FAILURE) { if (params) { efree(params); } if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invocation of %s's constructor failed", ce->name); RETURN_NULL(); } if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } if (params) { efree(params); } } else if (!ZEND_NUM_ARGS()) { object_init_ex(return_value, ce); } else { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Class %s does not have a constructor, so you cannot pass any constructor arguments", ce->name); } } /* }}} */ /* {{{ proto public stdclass ReflectionClass::newInstanceWithoutConstructor() Returns an instance of this class without invoking its constructor */ ZEND_METHOD(reflection_class, newInstanceWithoutConstructor) { reflection_object *intern; zend_class_entry *ce; METHOD_NOTSTATIC(reflection_class_ptr); GET_REFLECTION_OBJECT_PTR(ce); if (ce->create_object != NULL) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Class %s is an internal class that cannot be instantiated without invoking its constructor", ce->name); } object_init_ex(return_value, ce); } /* }}} */ /* {{{ proto public stdclass ReflectionClass::newInstanceArgs([array args]) Returns an instance of this class */ ZEND_METHOD(reflection_class, newInstanceArgs) { zval *retval_ptr = NULL; reflection_object *intern; zend_class_entry *ce; int argc = 0; HashTable *args; METHOD_NOTSTATIC(reflection_class_ptr); GET_REFLECTION_OBJECT_PTR(ce); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|h", &args) == FAILURE) { return; } if (ZEND_NUM_ARGS() > 0) { argc = args->nNumOfElements; } /* Run the constructor if there is one */ if (ce->constructor) { zval ***params = NULL; zend_fcall_info fci; zend_fcall_info_cache fcc; if (!(ce->constructor->common.fn_flags & ZEND_ACC_PUBLIC)) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Access to non-public constructor of class %s", ce->name); return; } if (argc) { params = safe_emalloc(sizeof(zval **), argc, 0); zend_hash_apply_with_argument(args, (apply_func_arg_t)_zval_array_to_c_array, &params TSRMLS_CC); params -= argc; } object_init_ex(return_value, ce); fci.size = sizeof(fci); fci.function_table = EG(function_table); fci.function_name = NULL; fci.symbol_table = NULL; fci.object_ptr = return_value; fci.retval_ptr_ptr = &retval_ptr; fci.param_count = argc; fci.params = params; fci.no_separation = 1; fcc.initialized = 1; fcc.function_handler = ce->constructor; fcc.calling_scope = EG(scope); fcc.called_scope = Z_OBJCE_P(return_value); fcc.object_ptr = return_value; if (zend_call_function(&fci, &fcc TSRMLS_CC) == FAILURE) { if (params) { efree(params); } if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invocation of %s's constructor failed", ce->name); RETURN_NULL(); } if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } if (params) { efree(params); } } else if (!ZEND_NUM_ARGS() || !argc) { object_init_ex(return_value, ce); } else { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Class %s does not have a constructor, so you cannot pass any constructor arguments", ce->name); } } /* }}} */ /* {{{ proto public ReflectionClass[] ReflectionClass::getInterfaces() Returns an array of interfaces this class implements */ ZEND_METHOD(reflection_class, getInterfaces) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); /* Return an empty array if this class implements no interfaces */ array_init(return_value); if (ce->num_interfaces) { zend_uint i; for (i=0; i < ce->num_interfaces; i++) { zval *interface; ALLOC_ZVAL(interface); zend_reflection_class_factory(ce->interfaces[i], interface TSRMLS_CC); add_assoc_zval_ex(return_value, ce->interfaces[i]->name, ce->interfaces[i]->name_length + 1, interface); } } } /* }}} */ /* {{{ proto public String[] ReflectionClass::getInterfaceNames() Returns an array of names of interfaces this class implements */ ZEND_METHOD(reflection_class, getInterfaceNames) { reflection_object *intern; zend_class_entry *ce; zend_uint i; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); /* Return an empty array if this class implements no interfaces */ array_init(return_value); for (i=0; i < ce->num_interfaces; i++) { add_next_index_stringl(return_value, ce->interfaces[i]->name, ce->interfaces[i]->name_length, 1); } } /* }}} */ /* {{{ proto public ReflectionClass[] ReflectionClass::getTraits() Returns an array of traits used by this class */ ZEND_METHOD(reflection_class, getTraits) { reflection_object *intern; zend_class_entry *ce; zend_uint i; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); array_init(return_value); for (i=0; i < ce->num_traits; i++) { zval *trait; ALLOC_ZVAL(trait); zend_reflection_class_factory(ce->traits[i], trait TSRMLS_CC); add_assoc_zval_ex(return_value, ce->traits[i]->name, ce->traits[i]->name_length + 1, trait); } } /* }}} */ /* {{{ proto public String[] ReflectionClass::getTraitNames() Returns an array of names of traits used by this class */ ZEND_METHOD(reflection_class, getTraitNames) { reflection_object *intern; zend_class_entry *ce; zend_uint i; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); array_init(return_value); for (i=0; i < ce->num_traits; i++) { add_next_index_stringl(return_value, ce->traits[i]->name, ce->traits[i]->name_length, 1); } } /* }}} */ /* {{{ proto public arra ReflectionClass::getTraitaliases() Returns an array of trait aliases */ ZEND_METHOD(reflection_class, getTraitAliases) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); array_init(return_value); if (ce->trait_aliases) { zend_uint i = 0; while (ce->trait_aliases[i]) { char *method_name; int method_name_len; zend_trait_method_reference *cur_ref = ce->trait_aliases[i]->trait_method; method_name_len = spprintf(&method_name, 0, "%s::%s", cur_ref->class_name, cur_ref->method_name); add_assoc_stringl_ex(return_value, ce->trait_aliases[i]->alias, ce->trait_aliases[i]->alias_len + 1, method_name, method_name_len, 0); i++; } } } /* }}} */ /* {{{ proto public ReflectionClass ReflectionClass::getParentClass() Returns the class' parent class, or, if none exists, FALSE */ ZEND_METHOD(reflection_class, getParentClass) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); if (ce->parent) { zend_reflection_class_factory(ce->parent, return_value TSRMLS_CC); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto public bool ReflectionClass::isSubclassOf(string|ReflectionClass class) Returns whether this class is a subclass of another class */ ZEND_METHOD(reflection_class, isSubclassOf) { reflection_object *intern, *argument; zend_class_entry *ce, **pce, *class_ce; zval *class_name; METHOD_NOTSTATIC(reflection_class_ptr); GET_REFLECTION_OBJECT_PTR(ce); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &class_name) == FAILURE) { return; } switch(class_name->type) { case IS_STRING: if (zend_lookup_class(Z_STRVAL_P(class_name), Z_STRLEN_P(class_name), &pce TSRMLS_CC) == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Class %s does not exist", Z_STRVAL_P(class_name)); return; } class_ce = *pce; break; case IS_OBJECT: if (instanceof_function(Z_OBJCE_P(class_name), reflection_class_ptr TSRMLS_CC)) { argument = (reflection_object *) zend_object_store_get_object(class_name TSRMLS_CC); if (argument == NULL || argument->ptr == NULL) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Internal error: Failed to retrieve the argument's reflection object"); /* Bails out */ } class_ce = argument->ptr; break; } /* no break */ default: zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Parameter one must either be a string or a ReflectionClass object"); return; } RETURN_BOOL((ce != class_ce && instanceof_function(ce, class_ce TSRMLS_CC))); } /* }}} */ /* {{{ proto public bool ReflectionClass::implementsInterface(string|ReflectionClass interface_name) Returns whether this class is a subclass of another class */ ZEND_METHOD(reflection_class, implementsInterface) { reflection_object *intern, *argument; zend_class_entry *ce, *interface_ce, **pce; zval *interface; METHOD_NOTSTATIC(reflection_class_ptr); GET_REFLECTION_OBJECT_PTR(ce); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &interface) == FAILURE) { return; } switch(interface->type) { case IS_STRING: if (zend_lookup_class(Z_STRVAL_P(interface), Z_STRLEN_P(interface), &pce TSRMLS_CC) == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Interface %s does not exist", Z_STRVAL_P(interface)); return; } interface_ce = *pce; break; case IS_OBJECT: if (instanceof_function(Z_OBJCE_P(interface), reflection_class_ptr TSRMLS_CC)) { argument = (reflection_object *) zend_object_store_get_object(interface TSRMLS_CC); if (argument == NULL || argument->ptr == NULL) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Internal error: Failed to retrieve the argument's reflection object"); /* Bails out */ } interface_ce = argument->ptr; break; } /* no break */ default: zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Parameter one must either be a string or a ReflectionClass object"); return; } if (!(interface_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Interface %s is a Class", interface_ce->name); return; } RETURN_BOOL(instanceof_function(ce, interface_ce TSRMLS_CC)); } /* }}} */ /* {{{ proto public bool ReflectionClass::isIterateable() Returns whether this class is iterateable (can be used inside foreach) */ ZEND_METHOD(reflection_class, isIterateable) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } METHOD_NOTSTATIC(reflection_class_ptr); GET_REFLECTION_OBJECT_PTR(ce); RETURN_BOOL(ce->get_iterator != NULL); } /* }}} */ /* {{{ proto public ReflectionExtension|NULL ReflectionClass::getExtension() Returns NULL or the extension the class belongs to */ ZEND_METHOD(reflection_class, getExtension) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } METHOD_NOTSTATIC(reflection_class_ptr); GET_REFLECTION_OBJECT_PTR(ce); if ((ce->type == ZEND_INTERNAL_CLASS) && ce->info.internal.module) { reflection_extension_factory(return_value, ce->info.internal.module->name TSRMLS_CC); } } /* }}} */ /* {{{ proto public string|false ReflectionClass::getExtensionName() Returns false or the name of the extension the class belongs to */ ZEND_METHOD(reflection_class, getExtensionName) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } METHOD_NOTSTATIC(reflection_class_ptr); GET_REFLECTION_OBJECT_PTR(ce); if ((ce->type == ZEND_INTERNAL_CLASS) && ce->info.internal.module) { RETURN_STRING(ce->info.internal.module->name, 1); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto public bool ReflectionClass::inNamespace() Returns whether this class is defined in namespace */ ZEND_METHOD(reflection_class, inNamespace) { zval **name; const char *backslash; if (zend_parse_parameters_none() == FAILURE) { return; } if (zend_hash_find(Z_OBJPROP_P(getThis()), "name", sizeof("name"), (void **) &name) == FAILURE) { RETURN_FALSE; } if (Z_TYPE_PP(name) == IS_STRING && (backslash = zend_memrchr(Z_STRVAL_PP(name), '\\', Z_STRLEN_PP(name))) && backslash > Z_STRVAL_PP(name)) { RETURN_TRUE; } RETURN_FALSE; } /* }}} */ /* {{{ proto public string ReflectionClass::getNamespaceName() Returns the name of namespace where this class is defined */ ZEND_METHOD(reflection_class, getNamespaceName) { zval **name; const char *backslash; if (zend_parse_parameters_none() == FAILURE) { return; } if (zend_hash_find(Z_OBJPROP_P(getThis()), "name", sizeof("name"), (void **) &name) == FAILURE) { RETURN_FALSE; } if (Z_TYPE_PP(name) == IS_STRING && (backslash = zend_memrchr(Z_STRVAL_PP(name), '\\', Z_STRLEN_PP(name))) && backslash > Z_STRVAL_PP(name)) { RETURN_STRINGL(Z_STRVAL_PP(name), backslash - Z_STRVAL_PP(name), 1); } RETURN_EMPTY_STRING(); } /* }}} */ /* {{{ proto public string ReflectionClass::getShortName() Returns the short name of the class (without namespace part) */ ZEND_METHOD(reflection_class, getShortName) { zval **name; const char *backslash; if (zend_parse_parameters_none() == FAILURE) { return; } if (zend_hash_find(Z_OBJPROP_P(getThis()), "name", sizeof("name"), (void **) &name) == FAILURE) { RETURN_FALSE; } if (Z_TYPE_PP(name) == IS_STRING && (backslash = zend_memrchr(Z_STRVAL_PP(name), '\\', Z_STRLEN_PP(name))) && backslash > Z_STRVAL_PP(name)) { RETURN_STRINGL(backslash + 1, Z_STRLEN_PP(name) - (backslash - Z_STRVAL_PP(name) + 1), 1); } RETURN_ZVAL(*name, 1, 0); } /* }}} */ /* {{{ proto public static mixed ReflectionObject::export(mixed argument [, bool return]) throws ReflectionException Exports a reflection object. Returns the output if TRUE is specified for return, printing it otherwise. */ ZEND_METHOD(reflection_object, export) { _reflection_export(INTERNAL_FUNCTION_PARAM_PASSTHRU, reflection_object_ptr, 1); } /* }}} */ /* {{{ proto public void ReflectionObject::__construct(mixed argument) throws ReflectionException Constructor. Takes an instance as an argument */ ZEND_METHOD(reflection_object, __construct) { reflection_class_object_ctor(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto public static mixed ReflectionProperty::export(mixed class, string name [, bool return]) throws ReflectionException Exports a reflection object. Returns the output if TRUE is specified for return, printing it otherwise. */ ZEND_METHOD(reflection_property, export) { _reflection_export(INTERNAL_FUNCTION_PARAM_PASSTHRU, reflection_property_ptr, 2); } /* }}} */ /* {{{ proto public void ReflectionProperty::__construct(mixed class, string name) Constructor. Throws an Exception in case the given property does not exist */ ZEND_METHOD(reflection_property, __construct) { zval *propname, *classname; char *name_str; const char *class_name, *prop_name; int name_len, dynam_prop = 0; zval *object; reflection_object *intern; zend_class_entry **pce; zend_class_entry *ce; zend_property_info *property_info = NULL; property_reference *reference; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zs", &classname, &name_str, &name_len) == FAILURE) { return; } object = getThis(); intern = (reflection_object *) zend_object_store_get_object(object TSRMLS_CC); if (intern == NULL) { return; } /* Find the class entry */ switch (Z_TYPE_P(classname)) { case IS_STRING: if (zend_lookup_class(Z_STRVAL_P(classname), Z_STRLEN_P(classname), &pce TSRMLS_CC) == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Class %s does not exist", Z_STRVAL_P(classname)); return; } ce = *pce; break; case IS_OBJECT: ce = Z_OBJCE_P(classname); break; default: _DO_THROW("The parameter class is expected to be either a string or an object"); /* returns out of this function */ } if (zend_hash_find(&ce->properties_info, name_str, name_len + 1, (void **) &property_info) == FAILURE || (property_info->flags & ZEND_ACC_SHADOW)) { /* Check for dynamic properties */ if (property_info == NULL && Z_TYPE_P(classname) == IS_OBJECT && Z_OBJ_HT_P(classname)->get_properties) { if (zend_hash_exists(Z_OBJ_HT_P(classname)->get_properties(classname TSRMLS_CC), name_str, name_len+1)) { dynam_prop = 1; } } if (dynam_prop == 0) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Property %s::$%s does not exist", ce->name, name_str); return; } } if (dynam_prop == 0 && (property_info->flags & ZEND_ACC_PRIVATE) == 0) { /* we have to search the class hierarchy for this (implicit) public or protected property */ zend_class_entry *tmp_ce = ce; zend_property_info *tmp_info; while (tmp_ce && zend_hash_find(&tmp_ce->properties_info, name_str, name_len + 1, (void **) &tmp_info) != SUCCESS) { ce = tmp_ce; property_info = tmp_info; tmp_ce = tmp_ce->parent; } } MAKE_STD_ZVAL(classname); MAKE_STD_ZVAL(propname); if (dynam_prop == 0) { zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name, &prop_name); ZVAL_STRINGL(classname, property_info->ce->name, property_info->ce->name_length, 1); ZVAL_STRING(propname, prop_name, 1); } else { ZVAL_STRINGL(classname, ce->name, ce->name_length, 1); ZVAL_STRINGL(propname, name_str, name_len, 1); } reflection_update_property(object, "class", classname); reflection_update_property(object, "name", propname); reference = (property_reference*) emalloc(sizeof(property_reference)); if (dynam_prop) { reference->prop.flags = ZEND_ACC_IMPLICIT_PUBLIC; reference->prop.name = Z_STRVAL_P(propname); reference->prop.name_length = Z_STRLEN_P(propname); reference->prop.h = zend_get_hash_value(name_str, name_len+1); reference->prop.doc_comment = NULL; reference->prop.ce = ce; } else { reference->prop = *property_info; } reference->ce = ce; intern->ptr = reference; intern->ref_type = REF_TYPE_PROPERTY; intern->ce = ce; intern->ignore_visibility = 0; } /* }}} */ /* {{{ proto public string ReflectionProperty::__toString() Returns a string representation */ ZEND_METHOD(reflection_property, __toString) { reflection_object *intern; property_reference *ref; string str; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ref); string_init(&str); _property_string(&str, &ref->prop, NULL, "" TSRMLS_CC); RETURN_STRINGL(str.string, str.len - 1, 0); } /* }}} */ /* {{{ proto public string ReflectionProperty::getName() Returns the class' name */ ZEND_METHOD(reflection_property, getName) { if (zend_parse_parameters_none() == FAILURE) { return; } _default_get_entry(getThis(), "name", sizeof("name"), return_value TSRMLS_CC); } /* }}} */ static void _property_check_flag(INTERNAL_FUNCTION_PARAMETERS, int mask) /* {{{ */ { reflection_object *intern; property_reference *ref; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ref); RETURN_BOOL(ref->prop.flags & mask); } /* }}} */ /* {{{ proto public bool ReflectionProperty::isPublic() Returns whether this property is public */ ZEND_METHOD(reflection_property, isPublic) { _property_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_PUBLIC | ZEND_ACC_IMPLICIT_PUBLIC); } /* }}} */ /* {{{ proto public bool ReflectionProperty::isPrivate() Returns whether this property is private */ ZEND_METHOD(reflection_property, isPrivate) { _property_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_PRIVATE); } /* }}} */ /* {{{ proto public bool ReflectionProperty::isProtected() Returns whether this property is protected */ ZEND_METHOD(reflection_property, isProtected) { _property_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_PROTECTED); } /* }}} */ /* {{{ proto public bool ReflectionProperty::isStatic() Returns whether this property is static */ ZEND_METHOD(reflection_property, isStatic) { _property_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_STATIC); } /* }}} */ /* {{{ proto public bool ReflectionProperty::isDefault() Returns whether this property is default (declared at compilation time). */ ZEND_METHOD(reflection_property, isDefault) { _property_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ~ZEND_ACC_IMPLICIT_PUBLIC); } /* }}} */ /* {{{ proto public int ReflectionProperty::getModifiers() Returns a bitfield of the access modifiers for this property */ ZEND_METHOD(reflection_property, getModifiers) { reflection_object *intern; property_reference *ref; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ref); RETURN_LONG(ref->prop.flags); } /* }}} */ /* {{{ proto public mixed ReflectionProperty::getValue([stdclass object]) Returns this property's value */ ZEND_METHOD(reflection_property, getValue) { reflection_object *intern; property_reference *ref; zval *object, name; zval *member_p = NULL; METHOD_NOTSTATIC(reflection_property_ptr); GET_REFLECTION_OBJECT_PTR(ref); if (!(ref->prop.flags & (ZEND_ACC_PUBLIC | ZEND_ACC_IMPLICIT_PUBLIC)) && intern->ignore_visibility == 0) { _default_get_entry(getThis(), "name", sizeof("name"), &name TSRMLS_CC); zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Cannot access non-public member %s::%s", intern->ce->name, Z_STRVAL(name)); zval_dtor(&name); return; } if ((ref->prop.flags & ZEND_ACC_STATIC)) { zend_update_class_constants(intern->ce TSRMLS_CC); if (!CE_STATIC_MEMBERS(intern->ce)[ref->prop.offset]) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Internal error: Could not find the property %s::%s", intern->ce->name, ref->prop.name); /* Bails out */ } *return_value= *CE_STATIC_MEMBERS(intern->ce)[ref->prop.offset]; zval_copy_ctor(return_value); INIT_PZVAL(return_value); } else { const char *class_name, *prop_name; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "o", &object) == FAILURE) { return; } zend_unmangle_property_name(ref->prop.name, ref->prop.name_length, &class_name, &prop_name); member_p = zend_read_property(ref->ce, object, prop_name, strlen(prop_name), 1 TSRMLS_CC); MAKE_COPY_ZVAL(&member_p, return_value); if (member_p != EG(uninitialized_zval_ptr)) { zval_add_ref(&member_p); zval_ptr_dtor(&member_p); } } } /* }}} */ /* {{{ proto public void ReflectionProperty::setValue([stdclass object,] mixed value) Sets this property's value */ ZEND_METHOD(reflection_property, setValue) { reflection_object *intern; property_reference *ref; zval **variable_ptr; zval *object, name; zval *value; zval *tmp; METHOD_NOTSTATIC(reflection_property_ptr); GET_REFLECTION_OBJECT_PTR(ref); if (!(ref->prop.flags & ZEND_ACC_PUBLIC) && intern->ignore_visibility == 0) { _default_get_entry(getThis(), "name", sizeof("name"), &name TSRMLS_CC); zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Cannot access non-public member %s::%s", intern->ce->name, Z_STRVAL(name)); zval_dtor(&name); return; } if ((ref->prop.flags & ZEND_ACC_STATIC)) { if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "z", &value) == FAILURE) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &tmp, &value) == FAILURE) { return; } } zend_update_class_constants(intern->ce TSRMLS_CC); if (!CE_STATIC_MEMBERS(intern->ce)[ref->prop.offset]) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Internal error: Could not find the property %s::%s", intern->ce->name, ref->prop.name); /* Bails out */ } variable_ptr = &CE_STATIC_MEMBERS(intern->ce)[ref->prop.offset]; if (*variable_ptr != value) { if (PZVAL_IS_REF(*variable_ptr)) { zval garbage = **variable_ptr; /* old value should be destroyed */ /* To check: can't *variable_ptr be some system variable like error_zval here? */ Z_TYPE_PP(variable_ptr) = Z_TYPE_P(value); (*variable_ptr)->value = value->value; if (Z_REFCOUNT_P(value) > 0) { zval_copy_ctor(*variable_ptr); } zval_dtor(&garbage); } else { zval *garbage = *variable_ptr; /* if we assign referenced variable, we should separate it */ Z_ADDREF_P(value); if (PZVAL_IS_REF(value)) { SEPARATE_ZVAL(&value); } *variable_ptr = value; zval_ptr_dtor(&garbage); } } } else { const char *class_name, *prop_name; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "oz", &object, &value) == FAILURE) { return; } zend_unmangle_property_name(ref->prop.name, ref->prop.name_length, &class_name, &prop_name); zend_update_property(ref->ce, object, prop_name, strlen(prop_name), value TSRMLS_CC); } } /* }}} */ /* {{{ proto public ReflectionClass ReflectionProperty::getDeclaringClass() Get the declaring class */ ZEND_METHOD(reflection_property, getDeclaringClass) { reflection_object *intern; property_reference *ref; zend_class_entry *tmp_ce, *ce; zend_property_info *tmp_info; const char *prop_name, *class_name; int prop_name_len; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ref); if (zend_unmangle_property_name(ref->prop.name, ref->prop.name_length, &class_name, &prop_name) != SUCCESS) { RETURN_FALSE; } prop_name_len = strlen(prop_name); ce = tmp_ce = ref->ce; while (tmp_ce && zend_hash_find(&tmp_ce->properties_info, prop_name, prop_name_len + 1, (void **) &tmp_info) == SUCCESS) { if (tmp_info->flags & ZEND_ACC_PRIVATE || tmp_info->flags & ZEND_ACC_SHADOW) { /* it's a private property, so it can't be inherited */ break; } ce = tmp_ce; if (tmp_ce == tmp_info->ce) { /* declared in this class, done */ break; } tmp_ce = tmp_ce->parent; } zend_reflection_class_factory(ce, return_value TSRMLS_CC); } /* }}} */ /* {{{ proto public string ReflectionProperty::getDocComment() Returns the doc comment for this property */ ZEND_METHOD(reflection_property, getDocComment) { reflection_object *intern; property_reference *ref; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ref); if (ref->prop.doc_comment) { RETURN_STRINGL(ref->prop.doc_comment, ref->prop.doc_comment_len, 1); } RETURN_FALSE; } /* }}} */ /* {{{ proto public int ReflectionProperty::setAccessible(bool visible) Sets whether non-public properties can be requested */ ZEND_METHOD(reflection_property, setAccessible) { reflection_object *intern; zend_bool visible; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "b", &visible) == FAILURE) { return; } intern = (reflection_object *) zend_object_store_get_object(getThis() TSRMLS_CC); if (intern == NULL) { return; } intern->ignore_visibility = visible; } /* }}} */ /* {{{ proto public static mixed ReflectionExtension::export(string name [, bool return]) throws ReflectionException Exports a reflection object. Returns the output if TRUE is specified for return, printing it otherwise. */ ZEND_METHOD(reflection_extension, export) { _reflection_export(INTERNAL_FUNCTION_PARAM_PASSTHRU, reflection_extension_ptr, 1); } /* }}} */ /* {{{ proto public void ReflectionExtension::__construct(string name) Constructor. Throws an Exception in case the given extension does not exist */ ZEND_METHOD(reflection_extension, __construct) { zval *name; zval *object; char *lcname; reflection_object *intern; zend_module_entry *module; char *name_str; int name_len; ALLOCA_FLAG(use_heap) if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name_str, &name_len) == FAILURE) { return; } object = getThis(); intern = (reflection_object *) zend_object_store_get_object(object TSRMLS_CC); if (intern == NULL) { return; } lcname = do_alloca(name_len + 1, use_heap); zend_str_tolower_copy(lcname, name_str, name_len); if (zend_hash_find(&module_registry, lcname, name_len + 1, (void **)&module) == FAILURE) { free_alloca(lcname, use_heap); zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Extension %s does not exist", name_str); return; } free_alloca(lcname, use_heap); MAKE_STD_ZVAL(name); ZVAL_STRING(name, module->name, 1); reflection_update_property( object, "name", name); intern->ptr = module; intern->ref_type = REF_TYPE_OTHER; intern->ce = NULL; } /* }}} */ /* {{{ proto public string ReflectionExtension::__toString() Returns a string representation */ ZEND_METHOD(reflection_extension, __toString) { reflection_object *intern; zend_module_entry *module; string str; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(module); string_init(&str); _extension_string(&str, module, "" TSRMLS_CC); RETURN_STRINGL(str.string, str.len - 1, 0); } /* }}} */ /* {{{ proto public string ReflectionExtension::getName() Returns this extension's name */ ZEND_METHOD(reflection_extension, getName) { if (zend_parse_parameters_none() == FAILURE) { return; } _default_get_entry(getThis(), "name", sizeof("name"), return_value TSRMLS_CC); } /* }}} */ /* {{{ proto public string ReflectionExtension::getVersion() Returns this extension's version */ ZEND_METHOD(reflection_extension, getVersion) { reflection_object *intern; zend_module_entry *module; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(module); /* An extension does not necessarily have a version number */ if (module->version == NO_VERSION_YET) { RETURN_NULL(); } else { RETURN_STRING(module->version, 1); } } /* }}} */ /* {{{ proto public ReflectionFunction[] ReflectionExtension::getFunctions() Returns an array of this extension's fuctions */ ZEND_METHOD(reflection_extension, getFunctions) { reflection_object *intern; zend_module_entry *module; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(module); array_init(return_value); if (module->functions) { zval *function; zend_function *fptr; const zend_function_entry *func = module->functions; /* Is there a better way of doing this? */ while (func->fname) { int fname_len = strlen(func->fname); char *lc_name = zend_str_tolower_dup(func->fname, fname_len); if (zend_hash_find(EG(function_table), lc_name, fname_len + 1, (void**) &fptr) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Internal error: Cannot find extension function %s in global function table", func->fname); func++; efree(lc_name); continue; } ALLOC_ZVAL(function); reflection_function_factory(fptr, NULL, function TSRMLS_CC); add_assoc_zval_ex(return_value, func->fname, fname_len+1, function); func++; efree(lc_name); } } } /* }}} */ static int _addconstant(zend_constant *constant TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zval *const_val; zval *retval = va_arg(args, zval*); int number = va_arg(args, int); if (number == constant->module_number) { ALLOC_ZVAL(const_val); *const_val = constant->value; zval_copy_ctor(const_val); INIT_PZVAL(const_val); add_assoc_zval_ex(retval, constant->name, constant->name_len, const_val); } return 0; } /* }}} */ /* {{{ proto public array ReflectionExtension::getConstants() Returns an associative array containing this extension's constants and their values */ ZEND_METHOD(reflection_extension, getConstants) { reflection_object *intern; zend_module_entry *module; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(module); array_init(return_value); zend_hash_apply_with_arguments(EG(zend_constants) TSRMLS_CC, (apply_func_args_t) _addconstant, 2, return_value, module->module_number); } /* }}} */ /* {{{ _addinientry */ static int _addinientry(zend_ini_entry *ini_entry TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) { zval *retval = va_arg(args, zval*); int number = va_arg(args, int); if (number == ini_entry->module_number) { if (ini_entry->value) { add_assoc_stringl(retval, ini_entry->name, ini_entry->value, ini_entry->value_length, 1); } else { add_assoc_null(retval, ini_entry->name); } } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* {{{ proto public array ReflectionExtension::getINIEntries() Returns an associative array containing this extension's INI entries and their values */ ZEND_METHOD(reflection_extension, getINIEntries) { reflection_object *intern; zend_module_entry *module; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(module); array_init(return_value); zend_hash_apply_with_arguments(EG(ini_directives) TSRMLS_CC, (apply_func_args_t) _addinientry, 2, return_value, module->module_number); } /* }}} */ /* {{{ add_extension_class */ static int add_extension_class(zend_class_entry **pce TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) { zval *class_array = va_arg(args, zval*), *zclass; struct _zend_module_entry *module = va_arg(args, struct _zend_module_entry*); int add_reflection_class = va_arg(args, int); if (((*pce)->type == ZEND_INTERNAL_CLASS) && (*pce)->info.internal.module && !strcasecmp((*pce)->info.internal.module->name, module->name)) { if (add_reflection_class) { ALLOC_ZVAL(zclass); zend_reflection_class_factory(*pce, zclass TSRMLS_CC); add_assoc_zval_ex(class_array, (*pce)->name, (*pce)->name_length + 1, zclass); } else { add_next_index_stringl(class_array, (*pce)->name, (*pce)->name_length, 1); } } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* {{{ proto public ReflectionClass[] ReflectionExtension::getClasses() Returns an array containing ReflectionClass objects for all classes of this extension */ ZEND_METHOD(reflection_extension, getClasses) { reflection_object *intern; zend_module_entry *module; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(module); array_init(return_value); zend_hash_apply_with_arguments(EG(class_table) TSRMLS_CC, (apply_func_args_t) add_extension_class, 3, return_value, module, 1); } /* }}} */ /* {{{ proto public array ReflectionExtension::getClassNames() Returns an array containing all names of all classes of this extension */ ZEND_METHOD(reflection_extension, getClassNames) { reflection_object *intern; zend_module_entry *module; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(module); array_init(return_value); zend_hash_apply_with_arguments(EG(class_table) TSRMLS_CC, (apply_func_args_t) add_extension_class, 3, return_value, module, 0); } /* }}} */ /* {{{ proto public array ReflectionExtension::getDependencies() Returns an array containing all names of all extensions this extension depends on */ ZEND_METHOD(reflection_extension, getDependencies) { reflection_object *intern; zend_module_entry *module; const zend_module_dep *dep; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(module); array_init(return_value); dep = module->deps; if (!dep) { return; } while(dep->name) { char *relation; char *rel_type; int len; switch(dep->type) { case MODULE_DEP_REQUIRED: rel_type = "Required"; break; case MODULE_DEP_CONFLICTS: rel_type = "Conflicts"; break; case MODULE_DEP_OPTIONAL: rel_type = "Optional"; break; default: rel_type = "Error"; /* shouldn't happen */ break; } len = spprintf(&relation, 0, "%s%s%s%s%s", rel_type, dep->rel ? " " : "", dep->rel ? dep->rel : "", dep->version ? " " : "", dep->version ? dep->version : ""); add_assoc_stringl(return_value, dep->name, relation, len, 0); dep++; } } /* }}} */ /* {{{ proto public void ReflectionExtension::info() Prints phpinfo block for the extension */ ZEND_METHOD(reflection_extension, info) { reflection_object *intern; zend_module_entry *module; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(module); php_info_print_module(module TSRMLS_CC); } /* }}} */ /* {{{ proto public bool ReflectionExtension::isPersistent() Returns whether this extension is persistent */ ZEND_METHOD(reflection_extension, isPersistent) { reflection_object *intern; zend_module_entry *module; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(module); RETURN_BOOL(module->type == MODULE_PERSISTENT); } /* }}} */ /* {{{ proto public bool ReflectionExtension::isTemporary() Returns whether this extension is temporary */ ZEND_METHOD(reflection_extension, isTemporary) { reflection_object *intern; zend_module_entry *module; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(module); RETURN_BOOL(module->type == MODULE_TEMPORARY); } /* }}} */ /* {{{ proto public static mixed ReflectionZendExtension::export(string name [, bool return]) throws ReflectionException * Exports a reflection object. Returns the output if TRUE is specified for return, printing it otherwise. */ ZEND_METHOD(reflection_zend_extension, export) { _reflection_export(INTERNAL_FUNCTION_PARAM_PASSTHRU, reflection_zend_extension_ptr, 1); } /* }}} */ /* {{{ proto public void ReflectionZendExtension::__construct(string name) Constructor. Throws an Exception in case the given Zend extension does not exist */ ZEND_METHOD(reflection_zend_extension, __construct) { zval *name; zval *object; reflection_object *intern; zend_extension *extension; char *name_str; int name_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name_str, &name_len) == FAILURE) { return; } object = getThis(); intern = (reflection_object *) zend_object_store_get_object(object TSRMLS_CC); if (intern == NULL) { return; } extension = zend_get_extension(name_str); if (!extension) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Zend Extension %s does not exist", name_str); return; } MAKE_STD_ZVAL(name); ZVAL_STRING(name, extension->name, 1); reflection_update_property(object, "name", name); intern->ptr = extension; intern->ref_type = REF_TYPE_OTHER; intern->ce = NULL; } /* }}} */ /* {{{ proto public string ReflectionZendExtension::__toString() Returns a string representation */ ZEND_METHOD(reflection_zend_extension, __toString) { reflection_object *intern; zend_extension *extension; string str; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(extension); string_init(&str); _zend_extension_string(&str, extension, "" TSRMLS_CC); RETURN_STRINGL(str.string, str.len - 1, 0); } /* }}} */ /* {{{ proto public string ReflectionZendExtension::getName() Returns the name of this Zend extension */ ZEND_METHOD(reflection_zend_extension, getName) { reflection_object *intern; zend_extension *extension; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(extension); RETURN_STRING(extension->name, 1); } /* }}} */ /* {{{ proto public string ReflectionZendExtension::getVersion() Returns the version information of this Zend extension */ ZEND_METHOD(reflection_zend_extension, getVersion) { reflection_object *intern; zend_extension *extension; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(extension); RETURN_STRING(extension->version ? extension->version : "", 1); } /* }}} */ /* {{{ proto public void ReflectionZendExtension::getAuthor() * Returns the name of this Zend extension's author */ ZEND_METHOD(reflection_zend_extension, getAuthor) { reflection_object *intern; zend_extension *extension; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(extension); RETURN_STRING(extension->author ? extension->author : "", 1); } /* }}} */ /* {{{ proto public void ReflectionZendExtension::getURL() Returns this Zend extension's URL*/ ZEND_METHOD(reflection_zend_extension, getURL) { reflection_object *intern; zend_extension *extension; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(extension); RETURN_STRING(extension->URL ? extension->URL : "", 1); } /* }}} */ /* {{{ proto public void ReflectionZendExtension::getCopyright() Returns this Zend extension's copyright information */ ZEND_METHOD(reflection_zend_extension, getCopyright) { reflection_object *intern; zend_extension *extension; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(extension); RETURN_STRING(extension->copyright ? extension->copyright : "", 1); } /* }}} */ /* {{{ method tables */ static const zend_function_entry reflection_exception_functions[] = { PHP_FE_END }; ZEND_BEGIN_ARG_INFO(arginfo_reflection__void, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_getModifierNames, 0) ZEND_ARG_INFO(0, modifiers) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_export, 0, 0, 1) ZEND_ARG_OBJ_INFO(0, reflector, Reflector, 0) ZEND_ARG_INFO(0, return) ZEND_END_ARG_INFO() static const zend_function_entry reflection_functions[] = { ZEND_ME(reflection, getModifierNames, arginfo_reflection_getModifierNames, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) ZEND_ME(reflection, export, arginfo_reflection_export, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_FE_END }; static const zend_function_entry reflector_functions[] = { ZEND_FENTRY(export, NULL, NULL, ZEND_ACC_STATIC|ZEND_ACC_ABSTRACT|ZEND_ACC_PUBLIC) ZEND_ABSTRACT_ME(reflector, __toString, arginfo_reflection__void) PHP_FE_END }; ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_function_export, 0, 0, 1) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, return) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_function___construct, 0) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_function_invoke, 0, 0, 0) ZEND_ARG_INFO(0, args) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_function_invokeArgs, 0) ZEND_ARG_ARRAY_INFO(0, args, 0) ZEND_END_ARG_INFO() static const zend_function_entry reflection_function_abstract_functions[] = { ZEND_ME(reflection, __clone, arginfo_reflection__void, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL) PHP_ABSTRACT_ME(reflection_function, __toString, arginfo_reflection__void) ZEND_ME(reflection_function, inNamespace, arginfo_reflection__void, 0) ZEND_ME(reflection_function, isClosure, arginfo_reflection__void, 0) ZEND_ME(reflection_function, isDeprecated, arginfo_reflection__void, 0) ZEND_ME(reflection_function, isInternal, arginfo_reflection__void, 0) ZEND_ME(reflection_function, isUserDefined, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getClosureThis, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getClosureScopeClass, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getDocComment, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getEndLine, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getExtension, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getExtensionName, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getFileName, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getName, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getNamespaceName, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getNumberOfParameters, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getNumberOfRequiredParameters, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getParameters, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getShortName, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getStartLine, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getStaticVariables, arginfo_reflection__void, 0) ZEND_ME(reflection_function, returnsReference, arginfo_reflection__void, 0) PHP_FE_END }; static const zend_function_entry reflection_function_functions[] = { ZEND_ME(reflection_function, __construct, arginfo_reflection_function___construct, 0) ZEND_ME(reflection_function, __toString, arginfo_reflection__void, 0) ZEND_ME(reflection_function, export, arginfo_reflection_function_export, ZEND_ACC_STATIC|ZEND_ACC_PUBLIC) ZEND_ME(reflection_function, isDisabled, arginfo_reflection__void, 0) ZEND_ME(reflection_function, invoke, arginfo_reflection_function_invoke, 0) ZEND_ME(reflection_function, invokeArgs, arginfo_reflection_function_invokeArgs, 0) ZEND_ME(reflection_function, getClosure, arginfo_reflection__void, 0) PHP_FE_END }; ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_method_export, 0, 0, 2) ZEND_ARG_INFO(0, class) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, return) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_method___construct, 0, 0, 1) ZEND_ARG_INFO(0, class_or_method) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_method_invoke, 0) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, args) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_method_invokeArgs, 0) ZEND_ARG_INFO(0, object) ZEND_ARG_ARRAY_INFO(0, args, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_method_setAccessible, 0) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_method_getClosure, 0) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() static const zend_function_entry reflection_method_functions[] = { ZEND_ME(reflection_method, export, arginfo_reflection_method_export, ZEND_ACC_STATIC|ZEND_ACC_PUBLIC) ZEND_ME(reflection_method, __construct, arginfo_reflection_method___construct, 0) ZEND_ME(reflection_method, __toString, arginfo_reflection__void, 0) ZEND_ME(reflection_method, isPublic, arginfo_reflection__void, 0) ZEND_ME(reflection_method, isPrivate, arginfo_reflection__void, 0) ZEND_ME(reflection_method, isProtected, arginfo_reflection__void, 0) ZEND_ME(reflection_method, isAbstract, arginfo_reflection__void, 0) ZEND_ME(reflection_method, isFinal, arginfo_reflection__void, 0) ZEND_ME(reflection_method, isStatic, arginfo_reflection__void, 0) ZEND_ME(reflection_method, isConstructor, arginfo_reflection__void, 0) ZEND_ME(reflection_method, isDestructor, arginfo_reflection__void, 0) ZEND_ME(reflection_method, getClosure, arginfo_reflection_method_getClosure, 0) ZEND_ME(reflection_method, getModifiers, arginfo_reflection__void, 0) ZEND_ME(reflection_method, invoke, arginfo_reflection_method_invoke, 0) ZEND_ME(reflection_method, invokeArgs, arginfo_reflection_method_invokeArgs, 0) ZEND_ME(reflection_method, getDeclaringClass, arginfo_reflection__void, 0) ZEND_ME(reflection_method, getPrototype, arginfo_reflection__void, 0) ZEND_ME(reflection_property, setAccessible, arginfo_reflection_method_setAccessible, 0) PHP_FE_END }; ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_class_export, 0, 0, 1) ZEND_ARG_INFO(0, argument) ZEND_ARG_INFO(0, return) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_class___construct, 0) ZEND_ARG_INFO(0, argument) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_class_getStaticPropertyValue, 0, 0, 1) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, default) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_class_setStaticPropertyValue, 0) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_class_hasMethod, 0) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_class_getMethod, 0) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_class_getMethods, 0, 0, 0) ZEND_ARG_INFO(0, filter) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_class_hasProperty, 0) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_class_getProperty, 0) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_class_getProperties, 0, 0, 0) ZEND_ARG_INFO(0, filter) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_class_hasConstant, 0) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_class_getConstant, 0) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_class_isInstance, 0) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_class_newInstance, 0) ZEND_ARG_INFO(0, args) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_class_newInstanceWithoutConstructor, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_class_newInstanceArgs, 0, 0, 0) ZEND_ARG_ARRAY_INFO(0, args, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_class_isSubclassOf, 0) ZEND_ARG_INFO(0, class) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_class_implementsInterface, 0) ZEND_ARG_INFO(0, interface) ZEND_END_ARG_INFO() static const zend_function_entry reflection_class_functions[] = { ZEND_ME(reflection, __clone, arginfo_reflection__void, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL) ZEND_ME(reflection_class, export, arginfo_reflection_class_export, ZEND_ACC_STATIC|ZEND_ACC_PUBLIC) ZEND_ME(reflection_class, __construct, arginfo_reflection_class___construct, 0) ZEND_ME(reflection_class, __toString, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getName, arginfo_reflection__void, 0) ZEND_ME(reflection_class, isInternal, arginfo_reflection__void, 0) ZEND_ME(reflection_class, isUserDefined, arginfo_reflection__void, 0) ZEND_ME(reflection_class, isInstantiable, arginfo_reflection__void, 0) ZEND_ME(reflection_class, isCloneable, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getFileName, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getStartLine, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getEndLine, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getDocComment, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getConstructor, arginfo_reflection__void, 0) ZEND_ME(reflection_class, hasMethod, arginfo_reflection_class_hasMethod, 0) ZEND_ME(reflection_class, getMethod, arginfo_reflection_class_getMethod, 0) ZEND_ME(reflection_class, getMethods, arginfo_reflection_class_getMethods, 0) ZEND_ME(reflection_class, hasProperty, arginfo_reflection_class_hasProperty, 0) ZEND_ME(reflection_class, getProperty, arginfo_reflection_class_getProperty, 0) ZEND_ME(reflection_class, getProperties, arginfo_reflection_class_getProperties, 0) ZEND_ME(reflection_class, hasConstant, arginfo_reflection_class_hasConstant, 0) ZEND_ME(reflection_class, getConstants, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getConstant, arginfo_reflection_class_getConstant, 0) ZEND_ME(reflection_class, getInterfaces, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getInterfaceNames, arginfo_reflection__void, 0) ZEND_ME(reflection_class, isInterface, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getTraits, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getTraitNames, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getTraitAliases, arginfo_reflection__void, 0) ZEND_ME(reflection_class, isTrait, arginfo_reflection__void, 0) ZEND_ME(reflection_class, isAbstract, arginfo_reflection__void, 0) ZEND_ME(reflection_class, isFinal, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getModifiers, arginfo_reflection__void, 0) ZEND_ME(reflection_class, isInstance, arginfo_reflection_class_isInstance, 0) ZEND_ME(reflection_class, newInstance, arginfo_reflection_class_newInstance, 0) ZEND_ME(reflection_class, newInstanceWithoutConstructor, arginfo_reflection_class_newInstanceWithoutConstructor, 0) ZEND_ME(reflection_class, newInstanceArgs, arginfo_reflection_class_newInstanceArgs, 0) ZEND_ME(reflection_class, getParentClass, arginfo_reflection__void, 0) ZEND_ME(reflection_class, isSubclassOf, arginfo_reflection_class_isSubclassOf, 0) ZEND_ME(reflection_class, getStaticProperties, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getStaticPropertyValue, arginfo_reflection_class_getStaticPropertyValue, 0) ZEND_ME(reflection_class, setStaticPropertyValue, arginfo_reflection_class_setStaticPropertyValue, 0) ZEND_ME(reflection_class, getDefaultProperties, arginfo_reflection__void, 0) ZEND_ME(reflection_class, isIterateable, arginfo_reflection__void, 0) ZEND_ME(reflection_class, implementsInterface, arginfo_reflection_class_implementsInterface, 0) ZEND_ME(reflection_class, getExtension, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getExtensionName, arginfo_reflection__void, 0) ZEND_ME(reflection_class, inNamespace, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getNamespaceName, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getShortName, arginfo_reflection__void, 0) PHP_FE_END }; ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_object_export, 0, 0, 1) ZEND_ARG_INFO(0, argument) ZEND_ARG_INFO(0, return) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_object___construct, 0) ZEND_ARG_INFO(0, argument) ZEND_END_ARG_INFO() static const zend_function_entry reflection_object_functions[] = { ZEND_ME(reflection_object, export, arginfo_reflection_object_export, ZEND_ACC_STATIC|ZEND_ACC_PUBLIC) ZEND_ME(reflection_object, __construct, arginfo_reflection_object___construct, 0) PHP_FE_END }; ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_property_export, 0, 0, 2) ZEND_ARG_INFO(0, class) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, return) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_property___construct, 0, 0, 2) ZEND_ARG_INFO(0, class) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_property_getValue, 0, 0, 0) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_property_setValue, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_property_setAccessible, 0) ZEND_ARG_INFO(0, visible) ZEND_END_ARG_INFO() static const zend_function_entry reflection_property_functions[] = { ZEND_ME(reflection, __clone, arginfo_reflection__void, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL) ZEND_ME(reflection_property, export, arginfo_reflection_property_export, ZEND_ACC_STATIC|ZEND_ACC_PUBLIC) ZEND_ME(reflection_property, __construct, arginfo_reflection_property___construct, 0) ZEND_ME(reflection_property, __toString, arginfo_reflection__void, 0) ZEND_ME(reflection_property, getName, arginfo_reflection__void, 0) ZEND_ME(reflection_property, getValue, arginfo_reflection_property_getValue, 0) ZEND_ME(reflection_property, setValue, arginfo_reflection_property_setValue, 0) ZEND_ME(reflection_property, isPublic, arginfo_reflection__void, 0) ZEND_ME(reflection_property, isPrivate, arginfo_reflection__void, 0) ZEND_ME(reflection_property, isProtected, arginfo_reflection__void, 0) ZEND_ME(reflection_property, isStatic, arginfo_reflection__void, 0) ZEND_ME(reflection_property, isDefault, arginfo_reflection__void, 0) ZEND_ME(reflection_property, getModifiers, arginfo_reflection__void, 0) ZEND_ME(reflection_property, getDeclaringClass, arginfo_reflection__void, 0) ZEND_ME(reflection_property, getDocComment, arginfo_reflection__void, 0) ZEND_ME(reflection_property, setAccessible, arginfo_reflection_property_setAccessible, 0) PHP_FE_END }; ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_parameter_export, 0, 0, 2) ZEND_ARG_INFO(0, function) ZEND_ARG_INFO(0, parameter) ZEND_ARG_INFO(0, return) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_parameter___construct, 0) ZEND_ARG_INFO(0, function) ZEND_ARG_INFO(0, parameter) ZEND_END_ARG_INFO() static const zend_function_entry reflection_parameter_functions[] = { ZEND_ME(reflection, __clone, arginfo_reflection__void, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL) ZEND_ME(reflection_parameter, export, arginfo_reflection_parameter_export, ZEND_ACC_STATIC|ZEND_ACC_PUBLIC) ZEND_ME(reflection_parameter, __construct, arginfo_reflection_parameter___construct, 0) ZEND_ME(reflection_parameter, __toString, arginfo_reflection__void, 0) ZEND_ME(reflection_parameter, getName, arginfo_reflection__void, 0) ZEND_ME(reflection_parameter, isPassedByReference, arginfo_reflection__void, 0) ZEND_ME(reflection_parameter, canBePassedByValue, arginfo_reflection__void, 0) ZEND_ME(reflection_parameter, getDeclaringFunction, arginfo_reflection__void, 0) ZEND_ME(reflection_parameter, getDeclaringClass, arginfo_reflection__void, 0) ZEND_ME(reflection_parameter, getClass, arginfo_reflection__void, 0) ZEND_ME(reflection_parameter, isArray, arginfo_reflection__void, 0) ZEND_ME(reflection_parameter, isCallable, arginfo_reflection__void, 0) ZEND_ME(reflection_parameter, allowsNull, arginfo_reflection__void, 0) ZEND_ME(reflection_parameter, getPosition, arginfo_reflection__void, 0) ZEND_ME(reflection_parameter, isOptional, arginfo_reflection__void, 0) ZEND_ME(reflection_parameter, isDefaultValueAvailable, arginfo_reflection__void, 0) ZEND_ME(reflection_parameter, getDefaultValue, arginfo_reflection__void, 0) PHP_FE_END }; ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_extension_export, 0, 0, 1) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, return) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_extension___construct, 0) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() static const zend_function_entry reflection_extension_functions[] = { ZEND_ME(reflection, __clone, arginfo_reflection__void, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL) ZEND_ME(reflection_extension, export, arginfo_reflection_extension_export, ZEND_ACC_STATIC|ZEND_ACC_PUBLIC) ZEND_ME(reflection_extension, __construct, arginfo_reflection_extension___construct, 0) ZEND_ME(reflection_extension, __toString, arginfo_reflection__void, 0) ZEND_ME(reflection_extension, getName, arginfo_reflection__void, 0) ZEND_ME(reflection_extension, getVersion, arginfo_reflection__void, 0) ZEND_ME(reflection_extension, getFunctions, arginfo_reflection__void, 0) ZEND_ME(reflection_extension, getConstants, arginfo_reflection__void, 0) ZEND_ME(reflection_extension, getINIEntries, arginfo_reflection__void, 0) ZEND_ME(reflection_extension, getClasses, arginfo_reflection__void, 0) ZEND_ME(reflection_extension, getClassNames, arginfo_reflection__void, 0) ZEND_ME(reflection_extension, getDependencies, arginfo_reflection__void, 0) ZEND_ME(reflection_extension, info, arginfo_reflection__void, 0) ZEND_ME(reflection_extension, isPersistent, arginfo_reflection__void, 0) ZEND_ME(reflection_extension, isTemporary, arginfo_reflection__void, 0) PHP_FE_END }; ZEND_BEGIN_ARG_INFO(arginfo_reflection_zend_extension___construct, 0) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() static const zend_function_entry reflection_zend_extension_functions[] = { ZEND_ME(reflection, __clone, arginfo_reflection__void, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL) ZEND_ME(reflection_zend_extension, export, arginfo_reflection_extension_export, ZEND_ACC_STATIC|ZEND_ACC_PUBLIC) ZEND_ME(reflection_zend_extension, __construct, arginfo_reflection_extension___construct, 0) ZEND_ME(reflection_zend_extension, __toString, arginfo_reflection__void, 0) ZEND_ME(reflection_zend_extension, getName, arginfo_reflection__void, 0) ZEND_ME(reflection_zend_extension, getVersion, arginfo_reflection__void, 0) ZEND_ME(reflection_zend_extension, getAuthor, arginfo_reflection__void, 0) ZEND_ME(reflection_zend_extension, getURL, arginfo_reflection__void, 0) ZEND_ME(reflection_zend_extension, getCopyright, arginfo_reflection__void, 0) PHP_FE_END }; /* }}} */ const zend_function_entry reflection_ext_functions[] = { /* {{{ */ PHP_FE_END }; /* }}} */ static zend_object_handlers *zend_std_obj_handlers; /* {{{ _reflection_write_property */ static void _reflection_write_property(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC) { if ((Z_TYPE_P(member) == IS_STRING) && zend_hash_exists(&Z_OBJCE_P(object)->properties_info, Z_STRVAL_P(member), Z_STRLEN_P(member)+1) && ((Z_STRLEN_P(member) == sizeof("name") - 1 && !memcmp(Z_STRVAL_P(member), "name", sizeof("name"))) || (Z_STRLEN_P(member) == sizeof("class") - 1 && !memcmp(Z_STRVAL_P(member), "class", sizeof("class"))))) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Cannot set read-only property %s::$%s", Z_OBJCE_P(object)->name, Z_STRVAL_P(member)); } else { zend_std_obj_handlers->write_property(object, member, value, key TSRMLS_CC); } } /* }}} */ PHP_MINIT_FUNCTION(reflection) /* {{{ */ { zend_class_entry _reflection_entry; zend_std_obj_handlers = zend_get_std_object_handlers(); memcpy(&reflection_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); reflection_object_handlers.clone_obj = NULL; reflection_object_handlers.write_property = _reflection_write_property; INIT_CLASS_ENTRY(_reflection_entry, "ReflectionException", reflection_exception_functions); reflection_exception_ptr = zend_register_internal_class_ex(&_reflection_entry, zend_exception_get_default(TSRMLS_C), NULL TSRMLS_CC); INIT_CLASS_ENTRY(_reflection_entry, "Reflection", reflection_functions); reflection_ptr = zend_register_internal_class(&_reflection_entry TSRMLS_CC); INIT_CLASS_ENTRY(_reflection_entry, "Reflector", reflector_functions); reflector_ptr = zend_register_internal_interface(&_reflection_entry TSRMLS_CC); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionFunctionAbstract", reflection_function_abstract_functions); _reflection_entry.create_object = reflection_objects_new; reflection_function_abstract_ptr = zend_register_internal_class(&_reflection_entry TSRMLS_CC); reflection_register_implement(reflection_function_abstract_ptr, reflector_ptr TSRMLS_CC); zend_declare_property_string(reflection_function_abstract_ptr, "name", sizeof("name")-1, "", ZEND_ACC_ABSTRACT TSRMLS_CC); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionFunction", reflection_function_functions); _reflection_entry.create_object = reflection_objects_new; reflection_function_ptr = zend_register_internal_class_ex(&_reflection_entry, reflection_function_abstract_ptr, NULL TSRMLS_CC); zend_declare_property_string(reflection_function_ptr, "name", sizeof("name")-1, "", ZEND_ACC_PUBLIC TSRMLS_CC); REGISTER_REFLECTION_CLASS_CONST_LONG(function, "IS_DEPRECATED", ZEND_ACC_DEPRECATED); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionParameter", reflection_parameter_functions); _reflection_entry.create_object = reflection_objects_new; reflection_parameter_ptr = zend_register_internal_class(&_reflection_entry TSRMLS_CC); reflection_register_implement(reflection_parameter_ptr, reflector_ptr TSRMLS_CC); zend_declare_property_string(reflection_parameter_ptr, "name", sizeof("name")-1, "", ZEND_ACC_PUBLIC TSRMLS_CC); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionMethod", reflection_method_functions); _reflection_entry.create_object = reflection_objects_new; reflection_method_ptr = zend_register_internal_class_ex(&_reflection_entry, reflection_function_abstract_ptr, NULL TSRMLS_CC); zend_declare_property_string(reflection_method_ptr, "name", sizeof("name")-1, "", ZEND_ACC_PUBLIC TSRMLS_CC); zend_declare_property_string(reflection_method_ptr, "class", sizeof("class")-1, "", ZEND_ACC_PUBLIC TSRMLS_CC); REGISTER_REFLECTION_CLASS_CONST_LONG(method, "IS_STATIC", ZEND_ACC_STATIC); REGISTER_REFLECTION_CLASS_CONST_LONG(method, "IS_PUBLIC", ZEND_ACC_PUBLIC); REGISTER_REFLECTION_CLASS_CONST_LONG(method, "IS_PROTECTED", ZEND_ACC_PROTECTED); REGISTER_REFLECTION_CLASS_CONST_LONG(method, "IS_PRIVATE", ZEND_ACC_PRIVATE); REGISTER_REFLECTION_CLASS_CONST_LONG(method, "IS_ABSTRACT", ZEND_ACC_ABSTRACT); REGISTER_REFLECTION_CLASS_CONST_LONG(method, "IS_FINAL", ZEND_ACC_FINAL); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionClass", reflection_class_functions); _reflection_entry.create_object = reflection_objects_new; reflection_class_ptr = zend_register_internal_class(&_reflection_entry TSRMLS_CC); reflection_register_implement(reflection_class_ptr, reflector_ptr TSRMLS_CC); zend_declare_property_string(reflection_class_ptr, "name", sizeof("name")-1, "", ZEND_ACC_PUBLIC TSRMLS_CC); REGISTER_REFLECTION_CLASS_CONST_LONG(class, "IS_IMPLICIT_ABSTRACT", ZEND_ACC_IMPLICIT_ABSTRACT_CLASS); REGISTER_REFLECTION_CLASS_CONST_LONG(class, "IS_EXPLICIT_ABSTRACT", ZEND_ACC_EXPLICIT_ABSTRACT_CLASS); REGISTER_REFLECTION_CLASS_CONST_LONG(class, "IS_FINAL", ZEND_ACC_FINAL_CLASS); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionObject", reflection_object_functions); _reflection_entry.create_object = reflection_objects_new; reflection_object_ptr = zend_register_internal_class_ex(&_reflection_entry, reflection_class_ptr, NULL TSRMLS_CC); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionProperty", reflection_property_functions); _reflection_entry.create_object = reflection_objects_new; reflection_property_ptr = zend_register_internal_class(&_reflection_entry TSRMLS_CC); reflection_register_implement(reflection_property_ptr, reflector_ptr TSRMLS_CC); zend_declare_property_string(reflection_property_ptr, "name", sizeof("name")-1, "", ZEND_ACC_PUBLIC TSRMLS_CC); zend_declare_property_string(reflection_property_ptr, "class", sizeof("class")-1, "", ZEND_ACC_PUBLIC TSRMLS_CC); REGISTER_REFLECTION_CLASS_CONST_LONG(property, "IS_STATIC", ZEND_ACC_STATIC); REGISTER_REFLECTION_CLASS_CONST_LONG(property, "IS_PUBLIC", ZEND_ACC_PUBLIC); REGISTER_REFLECTION_CLASS_CONST_LONG(property, "IS_PROTECTED", ZEND_ACC_PROTECTED); REGISTER_REFLECTION_CLASS_CONST_LONG(property, "IS_PRIVATE", ZEND_ACC_PRIVATE); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionExtension", reflection_extension_functions); _reflection_entry.create_object = reflection_objects_new; reflection_extension_ptr = zend_register_internal_class(&_reflection_entry TSRMLS_CC); reflection_register_implement(reflection_extension_ptr, reflector_ptr TSRMLS_CC); zend_declare_property_string(reflection_extension_ptr, "name", sizeof("name")-1, "", ZEND_ACC_PUBLIC TSRMLS_CC); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionZendExtension", reflection_zend_extension_functions); _reflection_entry.create_object = reflection_objects_new; reflection_zend_extension_ptr = zend_register_internal_class(&_reflection_entry TSRMLS_CC); reflection_register_implement(reflection_zend_extension_ptr, reflector_ptr TSRMLS_CC); zend_declare_property_string(reflection_zend_extension_ptr, "name", sizeof("name")-1, "", ZEND_ACC_PUBLIC TSRMLS_CC); return SUCCESS; } /* }}} */ PHP_MINFO_FUNCTION(reflection) /* {{{ */ { php_info_print_table_start(); php_info_print_table_header(2, "Reflection", "enabled"); php_info_print_table_row(2, "Version", "$Revision$"); php_info_print_table_end(); } /* }}} */ zend_module_entry reflection_module_entry = { /* {{{ */ STANDARD_MODULE_HEADER, "Reflection", reflection_ext_functions, PHP_MINIT(reflection), NULL, NULL, NULL, PHP_MINFO(reflection), "$Revision$", STANDARD_MODULE_PROPERTIES }; /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: * vim600: noet sw=4 ts=4 fdm=marker */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Timm Friebe <[email protected]> | | George Schlossnagle <[email protected]> | | Andrei Zmievski <[email protected]> | | Marcus Boerger <[email protected]> | | Johannes Schlueter <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ini.h" #include "php_reflection.h" #include "ext/standard/info.h" #include "zend.h" #include "zend_API.h" #include "zend_exceptions.h" #include "zend_operators.h" #include "zend_constants.h" #include "zend_ini.h" #include "zend_interfaces.h" #include "zend_closures.h" #include "zend_extensions.h" #define reflection_update_property(object, name, value) do { \ zval *member; \ MAKE_STD_ZVAL(member); \ ZVAL_STRINGL(member, name, sizeof(name)-1, 1); \ zend_std_write_property(object, member, value, NULL TSRMLS_CC); \ Z_DELREF_P(value); \ zval_ptr_dtor(&member); \ } while (0) /* Class entry pointers */ PHPAPI zend_class_entry *reflector_ptr; PHPAPI zend_class_entry *reflection_exception_ptr; PHPAPI zend_class_entry *reflection_ptr; PHPAPI zend_class_entry *reflection_function_abstract_ptr; PHPAPI zend_class_entry *reflection_function_ptr; PHPAPI zend_class_entry *reflection_parameter_ptr; PHPAPI zend_class_entry *reflection_class_ptr; PHPAPI zend_class_entry *reflection_object_ptr; PHPAPI zend_class_entry *reflection_method_ptr; PHPAPI zend_class_entry *reflection_property_ptr; PHPAPI zend_class_entry *reflection_extension_ptr; PHPAPI zend_class_entry *reflection_zend_extension_ptr; #if MBO_0 ZEND_BEGIN_MODULE_GLOBALS(reflection) int dummy; ZEND_END_MODULE_GLOBALS(reflection) #ifdef ZTS # define REFLECTION_G(v) \ TSRMG(reflection_globals_id, zend_reflection_globals*, v) extern int reflection_globals_id; #else # define REFLECTION_G(v) (reflection_globals.v) extern zend_reflection_globals reflectionglobals; #endif ZEND_DECLARE_MODULE_GLOBALS(reflection) #endif /* MBO_0 */ /* Method macros */ #define METHOD_NOTSTATIC(ce) \ if (!this_ptr || !instanceof_function(Z_OBJCE_P(this_ptr), ce TSRMLS_CC)) { \ php_error_docref(NULL TSRMLS_CC, E_ERROR, "%s() cannot be called statically", get_active_function_name(TSRMLS_C)); \ return; \ } \ /* Exception throwing macro */ #define _DO_THROW(msg) \ zend_throw_exception(reflection_exception_ptr, msg, 0 TSRMLS_CC); \ return; \ #define RETURN_ON_EXCEPTION \ if (EG(exception) && Z_OBJCE_P(EG(exception)) == reflection_exception_ptr) { \ return; \ } #define GET_REFLECTION_OBJECT_PTR(target) \ intern = (reflection_object *) zend_object_store_get_object(getThis() TSRMLS_CC); \ if (intern == NULL || intern->ptr == NULL) { \ RETURN_ON_EXCEPTION \ php_error_docref(NULL TSRMLS_CC, E_ERROR, "Internal error: Failed to retrieve the reflection object"); \ } \ target = intern->ptr; \ /* Class constants */ #define REGISTER_REFLECTION_CLASS_CONST_LONG(class_name, const_name, value) \ zend_declare_class_constant_long(reflection_ ## class_name ## _ptr, const_name, sizeof(const_name)-1, (long)value TSRMLS_CC); /* {{{ Smart string functions */ typedef struct _string { char *string; int len; int alloced; } string; static void string_init(string *str) { str->string = (char *) emalloc(1024); str->len = 1; str->alloced = 1024; *str->string = '\0'; } static string *string_printf(string *str, const char *format, ...) { int len; va_list arg; char *s_tmp; va_start(arg, format); len = zend_vspprintf(&s_tmp, 0, format, arg); if (len) { register int nlen = (str->len + len + (1024 - 1)) & ~(1024 - 1); if (str->alloced < nlen) { str->alloced = nlen; str->string = erealloc(str->string, str->alloced); } memcpy(str->string + str->len - 1, s_tmp, len + 1); str->len += len; } efree(s_tmp); va_end(arg); return str; } static string *string_write(string *str, char *buf, int len) { register int nlen = (str->len + len + (1024 - 1)) & ~(1024 - 1); if (str->alloced < nlen) { str->alloced = nlen; str->string = erealloc(str->string, str->alloced); } memcpy(str->string + str->len - 1, buf, len); str->len += len; str->string[str->len - 1] = '\0'; return str; } static string *string_append(string *str, string *append) { if (append->len > 1) { string_write(str, append->string, append->len - 1); } return str; } static void string_free(string *str) { efree(str->string); str->len = 0; str->alloced = 0; str->string = NULL; } /* }}} */ /* {{{ Object structure */ /* Struct for properties */ typedef struct _property_reference { zend_class_entry *ce; zend_property_info prop; } property_reference; /* Struct for parameters */ typedef struct _parameter_reference { zend_uint offset; zend_uint required; struct _zend_arg_info *arg_info; zend_function *fptr; } parameter_reference; typedef enum { REF_TYPE_OTHER, /* Must be 0 */ REF_TYPE_FUNCTION, REF_TYPE_PARAMETER, REF_TYPE_PROPERTY, REF_TYPE_DYNAMIC_PROPERTY } reflection_type_t; /* Struct for reflection objects */ typedef struct { zend_object zo; void *ptr; reflection_type_t ref_type; zval *obj; zend_class_entry *ce; unsigned int ignore_visibility:1; } reflection_object; /* }}} */ static zend_object_handlers reflection_object_handlers; static void _default_get_entry(zval *object, char *name, int name_len, zval *return_value TSRMLS_DC) /* {{{ */ { zval **value; if (zend_hash_find(Z_OBJPROP_P(object), name, name_len, (void **) &value) == FAILURE) { RETURN_FALSE; } MAKE_COPY_ZVAL(value, return_value); } /* }}} */ #ifdef ilia_0 static void _default_lookup_entry(zval *object, char *name, int name_len, zval **return_value TSRMLS_DC) /* {{{ */ { zval **value; if (zend_hash_find(Z_OBJPROP_P(object), name, name_len, (void **) &value) == FAILURE) { *return_value = NULL; } else { *return_value = *value; } } /* }}} */ #endif static void reflection_register_implement(zend_class_entry *class_entry, zend_class_entry *interface_entry TSRMLS_DC) /* {{{ */ { zend_uint num_interfaces = ++class_entry->num_interfaces; class_entry->interfaces = (zend_class_entry **) realloc(class_entry->interfaces, sizeof(zend_class_entry *) * num_interfaces); class_entry->interfaces[num_interfaces - 1] = interface_entry; } /* }}} */ static zend_function *_copy_function(zend_function *fptr TSRMLS_DC) /* {{{ */ { if (fptr && fptr->type == ZEND_INTERNAL_FUNCTION && (fptr->internal_function.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) != 0) { zend_function *copy_fptr; copy_fptr = emalloc(sizeof(zend_function)); memcpy(copy_fptr, fptr, sizeof(zend_function)); copy_fptr->internal_function.function_name = estrdup(fptr->internal_function.function_name); return copy_fptr; } else { /* no copy needed */ return fptr; } } /* }}} */ static void _free_function(zend_function *fptr TSRMLS_DC) /* {{{ */ { if (fptr && fptr->type == ZEND_INTERNAL_FUNCTION && (fptr->internal_function.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) != 0) { efree((char*)fptr->internal_function.function_name); efree(fptr); } } /* }}} */ static void reflection_free_objects_storage(void *object TSRMLS_DC) /* {{{ */ { reflection_object *intern = (reflection_object *) object; parameter_reference *reference; property_reference *prop_reference; if (intern->ptr) { switch (intern->ref_type) { case REF_TYPE_PARAMETER: reference = (parameter_reference*)intern->ptr; _free_function(reference->fptr TSRMLS_CC); efree(intern->ptr); break; case REF_TYPE_FUNCTION: _free_function(intern->ptr TSRMLS_CC); break; case REF_TYPE_PROPERTY: efree(intern->ptr); break; case REF_TYPE_DYNAMIC_PROPERTY: prop_reference = (property_reference*)intern->ptr; efree((char*)prop_reference->prop.name); efree(intern->ptr); break; case REF_TYPE_OTHER: break; } } intern->ptr = NULL; if (intern->obj) { zval_ptr_dtor(&intern->obj); } zend_objects_free_object_storage(object TSRMLS_CC); } /* }}} */ static zend_object_value reflection_objects_new(zend_class_entry *class_type TSRMLS_DC) /* {{{ */ { zend_object_value retval; reflection_object *intern; intern = ecalloc(1, sizeof(reflection_object)); intern->zo.ce = class_type; zend_object_std_init(&intern->zo, class_type TSRMLS_CC); object_properties_init(&intern->zo, class_type); retval.handle = zend_objects_store_put(intern, NULL, reflection_free_objects_storage, NULL TSRMLS_CC); retval.handlers = &reflection_object_handlers; return retval; } /* }}} */ static zval * reflection_instantiate(zend_class_entry *pce, zval *object TSRMLS_DC) /* {{{ */ { if (!object) { ALLOC_ZVAL(object); } Z_TYPE_P(object) = IS_OBJECT; object_init_ex(object, pce); Z_SET_REFCOUNT_P(object, 1); Z_SET_ISREF_P(object); return object; } /* }}} */ static void _const_string(string *str, char *name, zval *value, char *indent TSRMLS_DC); static void _function_string(string *str, zend_function *fptr, zend_class_entry *scope, char* indent TSRMLS_DC); static void _property_string(string *str, zend_property_info *prop, char *prop_name, char* indent TSRMLS_DC); static void _class_string(string *str, zend_class_entry *ce, zval *obj, char *indent TSRMLS_DC); static void _extension_string(string *str, zend_module_entry *module, char *indent TSRMLS_DC); static void _zend_extension_string(string *str, zend_extension *extension, char *indent TSRMLS_DC); /* {{{ _class_string */ static void _class_string(string *str, zend_class_entry *ce, zval *obj, char *indent TSRMLS_DC) { int count, count_static_props = 0, count_static_funcs = 0, count_shadow_props = 0; string sub_indent; string_init(&sub_indent); string_printf(&sub_indent, "%s ", indent); /* TBD: Repair indenting of doc comment (or is this to be done in the parser?) */ if (ce->type == ZEND_USER_CLASS && ce->info.user.doc_comment) { string_printf(str, "%s%s", indent, ce->info.user.doc_comment); string_write(str, "\n", 1); } if (obj) { string_printf(str, "%sObject of class [ ", indent); } else { char *kind = "Class"; if (ce->ce_flags & ZEND_ACC_INTERFACE) { kind = "Interface"; } else if ((ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { kind = "Trait"; } string_printf(str, "%s%s [ ", indent, kind); } string_printf(str, (ce->type == ZEND_USER_CLASS) ? "<user" : "<internal"); if (ce->type == ZEND_INTERNAL_CLASS && ce->info.internal.module) { string_printf(str, ":%s", ce->info.internal.module->name); } string_printf(str, "> "); if (ce->get_iterator != NULL) { string_printf(str, "<iterateable> "); } if (ce->ce_flags & ZEND_ACC_INTERFACE) { string_printf(str, "interface "); } else if ((ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { string_printf(str, "trait "); } else { if (ce->ce_flags & (ZEND_ACC_IMPLICIT_ABSTRACT_CLASS|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) { string_printf(str, "abstract "); } if (ce->ce_flags & ZEND_ACC_FINAL_CLASS) { string_printf(str, "final "); } string_printf(str, "class "); } string_printf(str, "%s", ce->name); if (ce->parent) { string_printf(str, " extends %s", ce->parent->name); } if (ce->num_interfaces) { zend_uint i; if (ce->ce_flags & ZEND_ACC_INTERFACE) { string_printf(str, " extends %s", ce->interfaces[0]->name); } else { string_printf(str, " implements %s", ce->interfaces[0]->name); } for (i = 1; i < ce->num_interfaces; ++i) { string_printf(str, ", %s", ce->interfaces[i]->name); } } string_printf(str, " ] {\n"); /* The information where a class is declared is only available for user classes */ if (ce->type == ZEND_USER_CLASS) { string_printf(str, "%s @@ %s %d-%d\n", indent, ce->info.user.filename, ce->info.user.line_start, ce->info.user.line_end); } /* Constants */ if (&ce->constants_table) { zend_hash_apply_with_argument(&ce->constants_table, (apply_func_arg_t) zval_update_constant, (void*)1 TSRMLS_CC); string_printf(str, "\n"); count = zend_hash_num_elements(&ce->constants_table); string_printf(str, "%s - Constants [%d] {\n", indent, count); if (count > 0) { HashPosition pos; zval **value; char *key; uint key_len; ulong num_index; zend_hash_internal_pointer_reset_ex(&ce->constants_table, &pos); while (zend_hash_get_current_data_ex(&ce->constants_table, (void **) &value, &pos) == SUCCESS) { zend_hash_get_current_key_ex(&ce->constants_table, &key, &key_len, &num_index, 0, &pos); _const_string(str, key, *value, indent TSRMLS_CC); zend_hash_move_forward_ex(&ce->constants_table, &pos); } } string_printf(str, "%s }\n", indent); } /* Static properties */ if (&ce->properties_info) { /* counting static properties */ count = zend_hash_num_elements(&ce->properties_info); if (count > 0) { HashPosition pos; zend_property_info *prop; zend_hash_internal_pointer_reset_ex(&ce->properties_info, &pos); while (zend_hash_get_current_data_ex(&ce->properties_info, (void **) &prop, &pos) == SUCCESS) { if(prop->flags & ZEND_ACC_SHADOW) { count_shadow_props++; } else if (prop->flags & ZEND_ACC_STATIC) { count_static_props++; } zend_hash_move_forward_ex(&ce->properties_info, &pos); } } /* static properties */ string_printf(str, "\n%s - Static properties [%d] {\n", indent, count_static_props); if (count_static_props > 0) { HashPosition pos; zend_property_info *prop; zend_hash_internal_pointer_reset_ex(&ce->properties_info, &pos); while (zend_hash_get_current_data_ex(&ce->properties_info, (void **) &prop, &pos) == SUCCESS) { if ((prop->flags & ZEND_ACC_STATIC) && !(prop->flags & ZEND_ACC_SHADOW)) { _property_string(str, prop, NULL, sub_indent.string TSRMLS_CC); } zend_hash_move_forward_ex(&ce->properties_info, &pos); } } string_printf(str, "%s }\n", indent); } /* Static methods */ if (&ce->function_table) { /* counting static methods */ count = zend_hash_num_elements(&ce->function_table); if (count > 0) { HashPosition pos; zend_function *mptr; zend_hash_internal_pointer_reset_ex(&ce->function_table, &pos); while (zend_hash_get_current_data_ex(&ce->function_table, (void **) &mptr, &pos) == SUCCESS) { if (mptr->common.fn_flags & ZEND_ACC_STATIC && ((mptr->common.fn_flags & ZEND_ACC_PRIVATE) == 0 || mptr->common.scope == ce)) { count_static_funcs++; } zend_hash_move_forward_ex(&ce->function_table, &pos); } } /* static methods */ string_printf(str, "\n%s - Static methods [%d] {", indent, count_static_funcs); if (count_static_funcs > 0) { HashPosition pos; zend_function *mptr; zend_hash_internal_pointer_reset_ex(&ce->function_table, &pos); while (zend_hash_get_current_data_ex(&ce->function_table, (void **) &mptr, &pos) == SUCCESS) { if (mptr->common.fn_flags & ZEND_ACC_STATIC && ((mptr->common.fn_flags & ZEND_ACC_PRIVATE) == 0 || mptr->common.scope == ce)) { string_printf(str, "\n"); _function_string(str, mptr, ce, sub_indent.string TSRMLS_CC); } zend_hash_move_forward_ex(&ce->function_table, &pos); } } else { string_printf(str, "\n"); } string_printf(str, "%s }\n", indent); } /* Default/Implicit properties */ if (&ce->properties_info) { count = zend_hash_num_elements(&ce->properties_info) - count_static_props - count_shadow_props; string_printf(str, "\n%s - Properties [%d] {\n", indent, count); if (count > 0) { HashPosition pos; zend_property_info *prop; zend_hash_internal_pointer_reset_ex(&ce->properties_info, &pos); while (zend_hash_get_current_data_ex(&ce->properties_info, (void **) &prop, &pos) == SUCCESS) { if (!(prop->flags & (ZEND_ACC_STATIC|ZEND_ACC_SHADOW))) { _property_string(str, prop, NULL, sub_indent.string TSRMLS_CC); } zend_hash_move_forward_ex(&ce->properties_info, &pos); } } string_printf(str, "%s }\n", indent); } if (obj && Z_OBJ_HT_P(obj)->get_properties) { string dyn; HashTable *properties = Z_OBJ_HT_P(obj)->get_properties(obj TSRMLS_CC); HashPosition pos; zval **prop; string_init(&dyn); count = 0; if (properties && zend_hash_num_elements(properties)) { zend_hash_internal_pointer_reset_ex(properties, &pos); while (zend_hash_get_current_data_ex(properties, (void **) &prop, &pos) == SUCCESS) { char *prop_name; uint prop_name_size; ulong index; if (zend_hash_get_current_key_ex(properties, &prop_name, &prop_name_size, &index, 1, &pos) == HASH_KEY_IS_STRING) { if (prop_name_size && prop_name[0]) { /* skip all private and protected properties */ if (!zend_hash_quick_exists(&ce->properties_info, prop_name, prop_name_size, zend_get_hash_value(prop_name, prop_name_size))) { count++; _property_string(&dyn, NULL, prop_name, sub_indent.string TSRMLS_CC); } } efree(prop_name); } zend_hash_move_forward_ex(properties, &pos); } } string_printf(str, "\n%s - Dynamic properties [%d] {\n", indent, count); string_append(str, &dyn); string_printf(str, "%s }\n", indent); string_free(&dyn); } /* Non static methods */ if (&ce->function_table) { count = zend_hash_num_elements(&ce->function_table) - count_static_funcs; if (count > 0) { HashPosition pos; zend_function *mptr; string dyn; count = 0; string_init(&dyn); zend_hash_internal_pointer_reset_ex(&ce->function_table, &pos); while (zend_hash_get_current_data_ex(&ce->function_table, (void **) &mptr, &pos) == SUCCESS) { if ((mptr->common.fn_flags & ZEND_ACC_STATIC) == 0 && ((mptr->common.fn_flags & ZEND_ACC_PRIVATE) == 0 || mptr->common.scope == ce)) { char *key; uint key_len; ulong num_index; uint len = strlen(mptr->common.function_name); /* Do not display old-style inherited constructors */ if ((mptr->common.fn_flags & ZEND_ACC_CTOR) == 0 || mptr->common.scope == ce || zend_hash_get_current_key_ex(&ce->function_table, &key, &key_len, &num_index, 0, &pos) != HASH_KEY_IS_STRING || zend_binary_strcasecmp(key, key_len-1, mptr->common.function_name, len) == 0) { zend_function *closure; /* see if this is a closure */ if (ce == zend_ce_closure && obj && (len == sizeof(ZEND_INVOKE_FUNC_NAME)-1) && memcmp(mptr->common.function_name, ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME)-1) == 0 && (closure = zend_get_closure_invoke_method(obj TSRMLS_CC)) != NULL) { mptr = closure; } else { closure = NULL; } string_printf(&dyn, "\n"); _function_string(&dyn, mptr, ce, sub_indent.string TSRMLS_CC); count++; _free_function(closure TSRMLS_CC); } } zend_hash_move_forward_ex(&ce->function_table, &pos); } string_printf(str, "\n%s - Methods [%d] {", indent, count); if (!count) { string_printf(str, "\n"); } string_append(str, &dyn); string_free(&dyn); } else { string_printf(str, "\n%s - Methods [0] {\n", indent); } string_printf(str, "%s }\n", indent); } string_printf(str, "%s}\n", indent); string_free(&sub_indent); } /* }}} */ /* {{{ _const_string */ static void _const_string(string *str, char *name, zval *value, char *indent TSRMLS_DC) { char *type; zval value_copy; int use_copy; type = zend_zval_type_name(value); zend_make_printable_zval(value, &value_copy, &use_copy); if (use_copy) { value = &value_copy; } string_printf(str, "%s Constant [ %s %s ] { %s }\n", indent, type, name, Z_STRVAL_P(value)); if (use_copy) { zval_dtor(value); } } /* }}} */ /* {{{ _get_recv_opcode */ static zend_op* _get_recv_op(zend_op_array *op_array, zend_uint offset) { zend_op *op = op_array->opcodes; zend_op *end = op + op_array->last; ++offset; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT) && op->op1.num == (long)offset) { return op; } ++op; } return NULL; } /* }}} */ /* {{{ _parameter_string */ static void _parameter_string(string *str, zend_function *fptr, struct _zend_arg_info *arg_info, zend_uint offset, zend_uint required, char* indent TSRMLS_DC) { string_printf(str, "Parameter #%d [ ", offset); if (offset >= required) { string_printf(str, "<optional> "); } else { string_printf(str, "<required> "); } if (arg_info->class_name) { string_printf(str, "%s ", arg_info->class_name); if (arg_info->allow_null) { string_printf(str, "or NULL "); } } else if (arg_info->type_hint) { string_printf(str, "%s ", zend_get_type_by_const(arg_info->type_hint)); if (arg_info->allow_null) { string_printf(str, "or NULL "); } } if (arg_info->pass_by_reference) { string_write(str, "&", sizeof("&")-1); } if (arg_info->name) { string_printf(str, "$%s", arg_info->name); } else { string_printf(str, "$param%d", offset); } if (fptr->type == ZEND_USER_FUNCTION && offset >= required) { zend_op *precv = _get_recv_op((zend_op_array*)fptr, offset); if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) { zval *zv, zv_copy; int use_copy; string_write(str, " = ", sizeof(" = ")-1); ALLOC_ZVAL(zv); *zv = *precv->op2.zv; zval_copy_ctor(zv); INIT_PZVAL(zv); zval_update_constant_ex(&zv, (void*)1, fptr->common.scope TSRMLS_CC); if (Z_TYPE_P(zv) == IS_BOOL) { if (Z_LVAL_P(zv)) { string_write(str, "true", sizeof("true")-1); } else { string_write(str, "false", sizeof("false")-1); } } else if (Z_TYPE_P(zv) == IS_NULL) { string_write(str, "NULL", sizeof("NULL")-1); } else if (Z_TYPE_P(zv) == IS_STRING) { string_write(str, "'", sizeof("'")-1); string_write(str, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 15)); if (Z_STRLEN_P(zv) > 15) { string_write(str, "...", sizeof("...")-1); } string_write(str, "'", sizeof("'")-1); } else if (Z_TYPE_P(zv) == IS_ARRAY) { string_write(str, "Array", sizeof("Array")-1); } else { zend_make_printable_zval(zv, &zv_copy, &use_copy); string_write(str, Z_STRVAL(zv_copy), Z_STRLEN(zv_copy)); if (use_copy) { zval_dtor(&zv_copy); } } zval_ptr_dtor(&zv); } } string_write(str, " ]", sizeof(" ]")-1); } /* }}} */ /* {{{ _function_parameter_string */ static void _function_parameter_string(string *str, zend_function *fptr, char* indent TSRMLS_DC) { struct _zend_arg_info *arg_info = fptr->common.arg_info; zend_uint i, required = fptr->common.required_num_args; if (!arg_info) { return; } string_printf(str, "\n"); string_printf(str, "%s- Parameters [%d] {\n", indent, fptr->common.num_args); for (i = 0; i < fptr->common.num_args; i++) { string_printf(str, "%s ", indent); _parameter_string(str, fptr, arg_info, i, required, indent TSRMLS_CC); string_write(str, "\n", sizeof("\n")-1); arg_info++; } string_printf(str, "%s}\n", indent); } /* }}} */ /* {{{ _function_closure_string */ static void _function_closure_string(string *str, zend_function *fptr, char* indent TSRMLS_DC) { zend_uint i, count; ulong num_index; char *key; uint key_len; HashTable *static_variables; HashPosition pos; if (fptr->type != ZEND_USER_FUNCTION || !fptr->op_array.static_variables) { return; } static_variables = fptr->op_array.static_variables; count = zend_hash_num_elements(static_variables); if (!count) { return; } string_printf(str, "\n"); string_printf(str, "%s- Bound Variables [%d] {\n", indent, zend_hash_num_elements(static_variables)); zend_hash_internal_pointer_reset_ex(static_variables, &pos); i = 0; while (i < count) { zend_hash_get_current_key_ex(static_variables, &key, &key_len, &num_index, 0, &pos); string_printf(str, "%s Variable #%d [ $%s ]\n", indent, i++, key); zend_hash_move_forward_ex(static_variables, &pos); } string_printf(str, "%s}\n", indent); } /* }}} */ /* {{{ _function_string */ static void _function_string(string *str, zend_function *fptr, zend_class_entry *scope, char* indent TSRMLS_DC) { string param_indent; zend_function *overwrites; char *lc_name; unsigned int lc_name_len; /* TBD: Repair indenting of doc comment (or is this to be done in the parser?) * What's "wrong" is that any whitespace before the doc comment start is * swallowed, leading to an unaligned comment. */ if (fptr->type == ZEND_USER_FUNCTION && fptr->op_array.doc_comment) { string_printf(str, "%s%s\n", indent, fptr->op_array.doc_comment); } string_write(str, indent, strlen(indent)); string_printf(str, fptr->common.fn_flags & ZEND_ACC_CLOSURE ? "Closure [ " : (fptr->common.scope ? "Method [ " : "Function [ ")); string_printf(str, (fptr->type == ZEND_USER_FUNCTION) ? "<user" : "<internal"); if (fptr->common.fn_flags & ZEND_ACC_DEPRECATED) { string_printf(str, ", deprecated"); } if (fptr->type == ZEND_INTERNAL_FUNCTION && ((zend_internal_function*)fptr)->module) { string_printf(str, ":%s", ((zend_internal_function*)fptr)->module->name); } if (scope && fptr->common.scope) { if (fptr->common.scope != scope) { string_printf(str, ", inherits %s", fptr->common.scope->name); } else if (fptr->common.scope->parent) { lc_name_len = strlen(fptr->common.function_name); lc_name = zend_str_tolower_dup(fptr->common.function_name, lc_name_len); if (zend_hash_find(&fptr->common.scope->parent->function_table, lc_name, lc_name_len + 1, (void**) &overwrites) == SUCCESS) { if (fptr->common.scope != overwrites->common.scope) { string_printf(str, ", overwrites %s", overwrites->common.scope->name); } } efree(lc_name); } } if (fptr->common.prototype && fptr->common.prototype->common.scope) { string_printf(str, ", prototype %s", fptr->common.prototype->common.scope->name); } if (fptr->common.fn_flags & ZEND_ACC_CTOR) { string_printf(str, ", ctor"); } if (fptr->common.fn_flags & ZEND_ACC_DTOR) { string_printf(str, ", dtor"); } string_printf(str, "> "); if (fptr->common.fn_flags & ZEND_ACC_ABSTRACT) { string_printf(str, "abstract "); } if (fptr->common.fn_flags & ZEND_ACC_FINAL) { string_printf(str, "final "); } if (fptr->common.fn_flags & ZEND_ACC_STATIC) { string_printf(str, "static "); } if (fptr->common.scope) { /* These are mutually exclusive */ switch (fptr->common.fn_flags & ZEND_ACC_PPP_MASK) { case ZEND_ACC_PUBLIC: string_printf(str, "public "); break; case ZEND_ACC_PRIVATE: string_printf(str, "private "); break; case ZEND_ACC_PROTECTED: string_printf(str, "protected "); break; default: string_printf(str, "<visibility error> "); break; } string_printf(str, "method "); } else { string_printf(str, "function "); } if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { string_printf(str, "&"); } string_printf(str, "%s ] {\n", fptr->common.function_name); /* The information where a function is declared is only available for user classes */ if (fptr->type == ZEND_USER_FUNCTION) { string_printf(str, "%s @@ %s %d - %d\n", indent, fptr->op_array.filename, fptr->op_array.line_start, fptr->op_array.line_end); } string_init(&param_indent); string_printf(&param_indent, "%s ", indent); if (fptr->common.fn_flags & ZEND_ACC_CLOSURE) { _function_closure_string(str, fptr, param_indent.string TSRMLS_CC); } _function_parameter_string(str, fptr, param_indent.string TSRMLS_CC); string_free(&param_indent); string_printf(str, "%s}\n", indent); } /* }}} */ /* {{{ _property_string */ static void _property_string(string *str, zend_property_info *prop, char *prop_name, char* indent TSRMLS_DC) { const char *class_name; string_printf(str, "%sProperty [ ", indent); if (!prop) { string_printf(str, "<dynamic> public $%s", prop_name); } else { if (!(prop->flags & ZEND_ACC_STATIC)) { if (prop->flags & ZEND_ACC_IMPLICIT_PUBLIC) { string_write(str, "<implicit> ", sizeof("<implicit> ") - 1); } else { string_write(str, "<default> ", sizeof("<default> ") - 1); } } /* These are mutually exclusive */ switch (prop->flags & ZEND_ACC_PPP_MASK) { case ZEND_ACC_PUBLIC: string_printf(str, "public "); break; case ZEND_ACC_PRIVATE: string_printf(str, "private "); break; case ZEND_ACC_PROTECTED: string_printf(str, "protected "); break; } if(prop->flags & ZEND_ACC_STATIC) { string_printf(str, "static "); } zend_unmangle_property_name(prop->name, prop->name_length, &class_name, (const char**)&prop_name); string_printf(str, "$%s", prop_name); } string_printf(str, " ]\n"); } /* }}} */ static int _extension_ini_string(zend_ini_entry *ini_entry TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { string *str = va_arg(args, string *); char *indent = va_arg(args, char *); int number = va_arg(args, int); char *comma = ""; if (number == ini_entry->module_number) { string_printf(str, " %sEntry [ %s <", indent, ini_entry->name); if (ini_entry->modifiable == ZEND_INI_ALL) { string_printf(str, "ALL"); } else { if (ini_entry->modifiable & ZEND_INI_USER) { string_printf(str, "USER"); comma = ","; } if (ini_entry->modifiable & ZEND_INI_PERDIR) { string_printf(str, "%sPERDIR", comma); comma = ","; } if (ini_entry->modifiable & ZEND_INI_SYSTEM) { string_printf(str, "%sSYSTEM", comma); } } string_printf(str, "> ]\n"); string_printf(str, " %s Current = '%s'\n", indent, ini_entry->value ? ini_entry->value : ""); if (ini_entry->modified) { string_printf(str, " %s Default = '%s'\n", indent, ini_entry->orig_value ? ini_entry->orig_value : ""); } string_printf(str, " %s}\n", indent); } return ZEND_HASH_APPLY_KEEP; } /* }}} */ static int _extension_class_string(zend_class_entry **pce TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { string *str = va_arg(args, string *); char *indent = va_arg(args, char *); struct _zend_module_entry *module = va_arg(args, struct _zend_module_entry*); int *num_classes = va_arg(args, int*); if (((*pce)->type == ZEND_INTERNAL_CLASS) && (*pce)->info.internal.module && !strcasecmp((*pce)->info.internal.module->name, module->name)) { string_printf(str, "\n"); _class_string(str, *pce, NULL, indent TSRMLS_CC); (*num_classes)++; } return ZEND_HASH_APPLY_KEEP; } /* }}} */ static int _extension_const_string(zend_constant *constant TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { string *str = va_arg(args, string *); char *indent = va_arg(args, char *); struct _zend_module_entry *module = va_arg(args, struct _zend_module_entry*); int *num_classes = va_arg(args, int*); if (constant->module_number == module->module_number) { _const_string(str, constant->name, &constant->value, indent TSRMLS_CC); (*num_classes)++; } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* {{{ _extension_string */ static void _extension_string(string *str, zend_module_entry *module, char *indent TSRMLS_DC) { string_printf(str, "%sExtension [ ", indent); if (module->type == MODULE_PERSISTENT) { string_printf(str, "<persistent>"); } if (module->type == MODULE_TEMPORARY) { string_printf(str, "<temporary>" ); } string_printf(str, " extension #%d %s version %s ] {\n", module->module_number, module->name, (module->version == NO_VERSION_YET) ? "<no_version>" : module->version); if (module->deps) { const zend_module_dep* dep = module->deps; string_printf(str, "\n - Dependencies {\n"); while(dep->name) { string_printf(str, "%s Dependency [ %s (", indent, dep->name); switch(dep->type) { case MODULE_DEP_REQUIRED: string_write(str, "Required", sizeof("Required") - 1); break; case MODULE_DEP_CONFLICTS: string_write(str, "Conflicts", sizeof("Conflicts") - 1); break; case MODULE_DEP_OPTIONAL: string_write(str, "Optional", sizeof("Optional") - 1); break; default: string_write(str, "Error", sizeof("Error") - 1); /* shouldn't happen */ break; } if (dep->rel) { string_printf(str, " %s", dep->rel); } if (dep->version) { string_printf(str, " %s", dep->version); } string_write(str, ") ]\n", sizeof(") ]\n") - 1); dep++; } string_printf(str, "%s }\n", indent); } { string str_ini; string_init(&str_ini); zend_hash_apply_with_arguments(EG(ini_directives) TSRMLS_CC, (apply_func_args_t) _extension_ini_string, 3, &str_ini, indent, module->module_number); if (str_ini.len > 1) { string_printf(str, "\n - INI {\n"); string_append(str, &str_ini); string_printf(str, "%s }\n", indent); } string_free(&str_ini); } { string str_constants; int num_constants = 0; string_init(&str_constants); zend_hash_apply_with_arguments(EG(zend_constants) TSRMLS_CC, (apply_func_args_t) _extension_const_string, 4, &str_constants, indent, module, &num_constants); if (num_constants) { string_printf(str, "\n - Constants [%d] {\n", num_constants); string_append(str, &str_constants); string_printf(str, "%s }\n", indent); } string_free(&str_constants); } if (module->functions && module->functions->fname) { zend_function *fptr; const zend_function_entry *func = module->functions; string_printf(str, "\n - Functions {\n"); /* Is there a better way of doing this? */ while (func->fname) { int fname_len = strlen(func->fname); char *lc_name = zend_str_tolower_dup(func->fname, fname_len); if (zend_hash_find(EG(function_table), lc_name, fname_len + 1, (void**) &fptr) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Internal error: Cannot find extension function %s in global function table", func->fname); func++; efree(lc_name); continue; } _function_string(str, fptr, NULL, " " TSRMLS_CC); efree(lc_name); func++; } string_printf(str, "%s }\n", indent); } { string str_classes; string sub_indent; int num_classes = 0; string_init(&sub_indent); string_printf(&sub_indent, "%s ", indent); string_init(&str_classes); zend_hash_apply_with_arguments(EG(class_table) TSRMLS_CC, (apply_func_args_t) _extension_class_string, 4, &str_classes, sub_indent.string, module, &num_classes); if (num_classes) { string_printf(str, "\n - Classes [%d] {", num_classes); string_append(str, &str_classes); string_printf(str, "%s }\n", indent); } string_free(&str_classes); string_free(&sub_indent); } string_printf(str, "%s}\n", indent); } /* }}} */ static void _zend_extension_string(string *str, zend_extension *extension, char *indent TSRMLS_DC) /* {{{ */ { string_printf(str, "%sZend Extension [ %s ", indent, extension->name); if (extension->version) { string_printf(str, "%s ", extension->version); } if (extension->copyright) { string_printf(str, "%s ", extension->copyright); } if (extension->author) { string_printf(str, "by %s ", extension->author); } if (extension->URL) { string_printf(str, "<%s> ", extension->URL); } string_printf(str, "]\n"); } /* }}} */ /* {{{ _function_check_flag */ static void _function_check_flag(INTERNAL_FUNCTION_PARAMETERS, int mask) { reflection_object *intern; zend_function *mptr; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(mptr); RETURN_BOOL(mptr->common.fn_flags & mask); } /* }}} */ /* {{{ zend_reflection_class_factory */ PHPAPI void zend_reflection_class_factory(zend_class_entry *ce, zval *object TSRMLS_DC) { reflection_object *intern; zval *name; MAKE_STD_ZVAL(name); ZVAL_STRINGL(name, ce->name, ce->name_length, 1); reflection_instantiate(reflection_class_ptr, object TSRMLS_CC); intern = (reflection_object *) zend_object_store_get_object(object TSRMLS_CC); intern->ptr = ce; intern->ref_type = REF_TYPE_OTHER; intern->ce = ce; reflection_update_property(object, "name", name); } /* }}} */ /* {{{ reflection_extension_factory */ static void reflection_extension_factory(zval *object, const char *name_str TSRMLS_DC) { reflection_object *intern; zval *name; int name_len = strlen(name_str); char *lcname; struct _zend_module_entry *module; ALLOCA_FLAG(use_heap) lcname = do_alloca(name_len + 1, use_heap); zend_str_tolower_copy(lcname, name_str, name_len); if (zend_hash_find(&module_registry, lcname, name_len + 1, (void **)&module) == FAILURE) { free_alloca(lcname, use_heap); return; } free_alloca(lcname, use_heap); reflection_instantiate(reflection_extension_ptr, object TSRMLS_CC); intern = (reflection_object *) zend_object_store_get_object(object TSRMLS_CC); MAKE_STD_ZVAL(name); ZVAL_STRINGL(name, module->name, name_len, 1); intern->ptr = module; intern->ref_type = REF_TYPE_OTHER; intern->ce = NULL; reflection_update_property(object, "name", name); } /* }}} */ /* {{{ reflection_parameter_factory */ static void reflection_parameter_factory(zend_function *fptr, zval *closure_object, struct _zend_arg_info *arg_info, zend_uint offset, zend_uint required, zval *object TSRMLS_DC) { reflection_object *intern; parameter_reference *reference; zval *name; if (closure_object) { Z_ADDREF_P(closure_object); } MAKE_STD_ZVAL(name); if (arg_info->name) { ZVAL_STRINGL(name, arg_info->name, arg_info->name_len, 1); } else { ZVAL_NULL(name); } reflection_instantiate(reflection_parameter_ptr, object TSRMLS_CC); intern = (reflection_object *) zend_object_store_get_object(object TSRMLS_CC); reference = (parameter_reference*) emalloc(sizeof(parameter_reference)); reference->arg_info = arg_info; reference->offset = offset; reference->required = required; reference->fptr = fptr; intern->ptr = reference; intern->ref_type = REF_TYPE_PARAMETER; intern->ce = fptr->common.scope; intern->obj = closure_object; reflection_update_property(object, "name", name); } /* }}} */ /* {{{ reflection_function_factory */ static void reflection_function_factory(zend_function *function, zval *closure_object, zval *object TSRMLS_DC) { reflection_object *intern; zval *name; if (closure_object) { Z_ADDREF_P(closure_object); } MAKE_STD_ZVAL(name); ZVAL_STRING(name, function->common.function_name, 1); reflection_instantiate(reflection_function_ptr, object TSRMLS_CC); intern = (reflection_object *) zend_object_store_get_object(object TSRMLS_CC); intern->ptr = function; intern->ref_type = REF_TYPE_FUNCTION; intern->ce = NULL; intern->obj = closure_object; reflection_update_property(object, "name", name); } /* }}} */ /* {{{ reflection_method_factory */ static void reflection_method_factory(zend_class_entry *ce, zend_function *method, zval *closure_object, zval *object TSRMLS_DC) { reflection_object *intern; zval *name; zval *classname; if (closure_object) { Z_ADDREF_P(closure_object); } MAKE_STD_ZVAL(name); MAKE_STD_ZVAL(classname); ZVAL_STRING(name, method->common.function_name, 1); ZVAL_STRINGL(classname, method->common.scope->name, method->common.scope->name_length, 1); reflection_instantiate(reflection_method_ptr, object TSRMLS_CC); intern = (reflection_object *) zend_object_store_get_object(object TSRMLS_CC); intern->ptr = method; intern->ref_type = REF_TYPE_FUNCTION; intern->ce = ce; intern->obj = closure_object; reflection_update_property(object, "name", name); reflection_update_property(object, "class", classname); } /* }}} */ /* {{{ reflection_property_factory */ static void reflection_property_factory(zend_class_entry *ce, zend_property_info *prop, zval *object TSRMLS_DC) { reflection_object *intern; zval *name; zval *classname; property_reference *reference; const char *class_name, *prop_name; zend_unmangle_property_name(prop->name, prop->name_length, &class_name, &prop_name); if (!(prop->flags & ZEND_ACC_PRIVATE)) { /* we have to search the class hierarchy for this (implicit) public or protected property */ zend_class_entry *tmp_ce = ce, *store_ce = ce; zend_property_info *tmp_info = NULL; while (tmp_ce && zend_hash_find(&tmp_ce->properties_info, prop_name, strlen(prop_name) + 1, (void **) &tmp_info) != SUCCESS) { ce = tmp_ce; tmp_ce = tmp_ce->parent; } if (tmp_info && !(tmp_info->flags & ZEND_ACC_SHADOW)) { /* found something and it's not a parent's private */ prop = tmp_info; } else { /* not found, use initial value */ ce = store_ce; } } MAKE_STD_ZVAL(name); MAKE_STD_ZVAL(classname); ZVAL_STRING(name, prop_name, 1); ZVAL_STRINGL(classname, prop->ce->name, prop->ce->name_length, 1); reflection_instantiate(reflection_property_ptr, object TSRMLS_CC); intern = (reflection_object *) zend_object_store_get_object(object TSRMLS_CC); reference = (property_reference*) emalloc(sizeof(property_reference)); reference->ce = ce; reference->prop = *prop; intern->ptr = reference; intern->ref_type = REF_TYPE_PROPERTY; intern->ce = ce; intern->ignore_visibility = 0; reflection_update_property(object, "name", name); reflection_update_property(object, "class", classname); } /* }}} */ /* {{{ _reflection_export */ static void _reflection_export(INTERNAL_FUNCTION_PARAMETERS, zend_class_entry *ce_ptr, int ctor_argc) { zval *reflector_ptr; zval output, *output_ptr = &output; zval *argument_ptr, *argument2_ptr; zval *retval_ptr, **params[2]; int result; int return_output = 0; zend_fcall_info fci; zend_fcall_info_cache fcc; zval fname; if (ctor_argc == 1) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|b", &argument_ptr, &return_output) == FAILURE) { return; } } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz|b", &argument_ptr, &argument2_ptr, &return_output) == FAILURE) { return; } } INIT_PZVAL(&output); /* Create object */ MAKE_STD_ZVAL(reflector_ptr); if (object_and_properties_init(reflector_ptr, ce_ptr, NULL) == FAILURE) { _DO_THROW("Could not create reflector"); } /* Call __construct() */ params[0] = &argument_ptr; params[1] = &argument2_ptr; fci.size = sizeof(fci); fci.function_table = NULL; fci.function_name = NULL; fci.symbol_table = NULL; fci.object_ptr = reflector_ptr; fci.retval_ptr_ptr = &retval_ptr; fci.param_count = ctor_argc; fci.params = params; fci.no_separation = 1; fcc.initialized = 1; fcc.function_handler = ce_ptr->constructor; fcc.calling_scope = ce_ptr; fcc.called_scope = Z_OBJCE_P(reflector_ptr); fcc.object_ptr = reflector_ptr; result = zend_call_function(&fci, &fcc TSRMLS_CC); if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } if (EG(exception)) { zval_ptr_dtor(&reflector_ptr); return; } if (result == FAILURE) { zval_ptr_dtor(&reflector_ptr); _DO_THROW("Could not create reflector"); } /* Call static reflection::export */ ZVAL_BOOL(&output, return_output); params[0] = &reflector_ptr; params[1] = &output_ptr; ZVAL_STRINGL(&fname, "reflection::export", sizeof("reflection::export") - 1, 0); fci.function_table = &reflection_ptr->function_table; fci.function_name = &fname; fci.object_ptr = NULL; fci.retval_ptr_ptr = &retval_ptr; fci.param_count = 2; fci.params = params; fci.no_separation = 1; result = zend_call_function(&fci, NULL TSRMLS_CC); if (result == FAILURE && EG(exception) == NULL) { zval_ptr_dtor(&reflector_ptr); zval_ptr_dtor(&retval_ptr); _DO_THROW("Could not execute reflection::export()"); } if (return_output) { COPY_PZVAL_TO_ZVAL(*return_value, retval_ptr); } else { zval_ptr_dtor(&retval_ptr); } /* Destruct reflector which is no longer needed */ zval_ptr_dtor(&reflector_ptr); } /* }}} */ /* {{{ Preventing __clone from being called */ ZEND_METHOD(reflection, __clone) { /* Should never be executable */ _DO_THROW("Cannot clone object using __clone()"); } /* }}} */ /* {{{ proto public static mixed Reflection::export(Reflector r [, bool return]) Exports a reflection object. Returns the output if TRUE is specified for return, printing it otherwise. */ ZEND_METHOD(reflection, export) { zval *object, fname, *retval_ptr; int result; zend_bool return_output = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|b", &object, reflector_ptr, &return_output) == FAILURE) { return; } /* Invoke the __toString() method */ ZVAL_STRINGL(&fname, "__tostring", sizeof("__tostring") - 1, 1); result= call_user_function_ex(NULL, &object, &fname, &retval_ptr, 0, NULL, 0, NULL TSRMLS_CC); zval_dtor(&fname); if (result == FAILURE) { _DO_THROW("Invocation of method __toString() failed"); /* Returns from this function */ } if (!retval_ptr) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::__toString() did not return anything", Z_OBJCE_P(object)->name); RETURN_FALSE; } if (return_output) { COPY_PZVAL_TO_ZVAL(*return_value, retval_ptr); } else { /* No need for _r variant, return of __toString should always be a string */ zend_print_zval(retval_ptr, 0); zend_printf("\n"); zval_ptr_dtor(&retval_ptr); } } /* }}} */ /* {{{ proto public static array Reflection::getModifierNames(int modifiers) Returns an array of modifier names */ ZEND_METHOD(reflection, getModifierNames) { long modifiers; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &modifiers) == FAILURE) { return; } array_init(return_value); if (modifiers & (ZEND_ACC_ABSTRACT | ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) { add_next_index_stringl(return_value, "abstract", sizeof("abstract")-1, 1); } if (modifiers & (ZEND_ACC_FINAL | ZEND_ACC_FINAL_CLASS)) { add_next_index_stringl(return_value, "final", sizeof("final")-1, 1); } if (modifiers & ZEND_ACC_IMPLICIT_PUBLIC) { add_next_index_stringl(return_value, "public", sizeof("public")-1, 1); } /* These are mutually exclusive */ switch (modifiers & ZEND_ACC_PPP_MASK) { case ZEND_ACC_PUBLIC: add_next_index_stringl(return_value, "public", sizeof("public")-1, 1); break; case ZEND_ACC_PRIVATE: add_next_index_stringl(return_value, "private", sizeof("private")-1, 1); break; case ZEND_ACC_PROTECTED: add_next_index_stringl(return_value, "protected", sizeof("protected")-1, 1); break; } if (modifiers & ZEND_ACC_STATIC) { add_next_index_stringl(return_value, "static", sizeof("static")-1, 1); } } /* }}} */ /* {{{ proto public static mixed ReflectionFunction::export(string name [, bool return]) Exports a reflection object. Returns the output if TRUE is specified for return, printing it otherwise. */ ZEND_METHOD(reflection_function, export) { _reflection_export(INTERNAL_FUNCTION_PARAM_PASSTHRU, reflection_function_ptr, 1); } /* }}} */ /* {{{ proto public void ReflectionFunction::__construct(string name) Constructor. Throws an Exception in case the given function does not exist */ ZEND_METHOD(reflection_function, __construct) { zval *name; zval *object; zval *closure = NULL; char *lcname; reflection_object *intern; zend_function *fptr; char *name_str; int name_len; object = getThis(); intern = (reflection_object *) zend_object_store_get_object(object TSRMLS_CC); if (intern == NULL) { return; } if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "O", &closure, zend_ce_closure) == SUCCESS) { fptr = (zend_function*)zend_get_closure_method_def(closure TSRMLS_CC); Z_ADDREF_P(closure); } else if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name_str, &name_len) == SUCCESS) { char *nsname; lcname = zend_str_tolower_dup(name_str, name_len); /* Ignore leading "\" */ nsname = lcname; if (lcname[0] == '\\') { nsname = &lcname[1]; name_len--; } if (zend_hash_find(EG(function_table), nsname, name_len + 1, (void **)&fptr) == FAILURE) { efree(lcname); zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Function %s() does not exist", name_str); return; } efree(lcname); } else { return; } MAKE_STD_ZVAL(name); ZVAL_STRING(name, fptr->common.function_name, 1); reflection_update_property(object, "name", name); intern->ptr = fptr; intern->ref_type = REF_TYPE_FUNCTION; intern->obj = closure; intern->ce = NULL; } /* }}} */ /* {{{ proto public string ReflectionFunction::__toString() Returns a string representation */ ZEND_METHOD(reflection_function, __toString) { reflection_object *intern; zend_function *fptr; string str; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(fptr); string_init(&str); _function_string(&str, fptr, intern->ce, "" TSRMLS_CC); RETURN_STRINGL(str.string, str.len - 1, 0); } /* }}} */ /* {{{ proto public string ReflectionFunction::getName() Returns this function's name */ ZEND_METHOD(reflection_function, getName) { if (zend_parse_parameters_none() == FAILURE) { return; } _default_get_entry(getThis(), "name", sizeof("name"), return_value TSRMLS_CC); } /* }}} */ /* {{{ proto public bool ReflectionFunction::isClosure() Returns whether this is a closure */ ZEND_METHOD(reflection_function, isClosure) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(fptr); RETURN_BOOL(fptr->common.fn_flags & ZEND_ACC_CLOSURE); } /* }}} */ /* {{{ proto public bool ReflectionFunction::getClosureThis() Returns this pointer bound to closure */ ZEND_METHOD(reflection_function, getClosureThis) { reflection_object *intern; zend_function *fptr; zval* closure_this; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(fptr); if (intern->obj) { closure_this = zend_get_closure_this_ptr(intern->obj TSRMLS_CC); if (closure_this) { RETURN_ZVAL(closure_this, 1, 0); } } } /* }}} */ /* {{{ proto public ReflectionClass ReflectionFunction::getClosureScopeClass() Returns the scope associated to the closure */ ZEND_METHOD(reflection_function, getClosureScopeClass) { reflection_object *intern; zend_function *fptr; const zend_function *closure_func; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(fptr); if (intern->obj) { closure_func = zend_get_closure_method_def(intern->obj TSRMLS_CC); if (closure_func && closure_func->common.scope) { zend_reflection_class_factory(closure_func->common.scope, return_value TSRMLS_CC); } } } /* }}} */ /* {{{ proto public mixed ReflectionFunction::getClosure() Returns a dynamically created closure for the function */ ZEND_METHOD(reflection_function, getClosure) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(fptr); zend_create_closure(return_value, fptr, NULL, NULL TSRMLS_CC); } /* }}} */ /* {{{ proto public bool ReflectionFunction::isInternal() Returns whether this is an internal function */ ZEND_METHOD(reflection_function, isInternal) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(fptr); RETURN_BOOL(fptr->type == ZEND_INTERNAL_FUNCTION); } /* }}} */ /* {{{ proto public bool ReflectionFunction::isUserDefined() Returns whether this is an user-defined function */ ZEND_METHOD(reflection_function, isUserDefined) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(fptr); RETURN_BOOL(fptr->type == ZEND_USER_FUNCTION); } /* }}} */ /* {{{ proto public bool ReflectionFunction::isDisabled() Returns whether this function has been disabled or not */ ZEND_METHOD(reflection_function, isDisabled) { reflection_object *intern; zend_function *fptr; METHOD_NOTSTATIC(reflection_function_ptr); GET_REFLECTION_OBJECT_PTR(fptr); RETURN_BOOL(fptr->type == ZEND_INTERNAL_FUNCTION && fptr->internal_function.handler == zif_display_disabled_function); } /* }}} */ /* {{{ proto public string ReflectionFunction::getFileName() Returns the filename of the file this function was declared in */ ZEND_METHOD(reflection_function, getFileName) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(fptr); if (fptr->type == ZEND_USER_FUNCTION) { RETURN_STRING(fptr->op_array.filename, 1); } RETURN_FALSE; } /* }}} */ /* {{{ proto public int ReflectionFunction::getStartLine() Returns the line this function's declaration starts at */ ZEND_METHOD(reflection_function, getStartLine) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(fptr); if (fptr->type == ZEND_USER_FUNCTION) { RETURN_LONG(fptr->op_array.line_start); } RETURN_FALSE; } /* }}} */ /* {{{ proto public int ReflectionFunction::getEndLine() Returns the line this function's declaration ends at */ ZEND_METHOD(reflection_function, getEndLine) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(fptr); if (fptr->type == ZEND_USER_FUNCTION) { RETURN_LONG(fptr->op_array.line_end); } RETURN_FALSE; } /* }}} */ /* {{{ proto public string ReflectionFunction::getDocComment() Returns the doc comment for this function */ ZEND_METHOD(reflection_function, getDocComment) { reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(fptr); if (fptr->type == ZEND_USER_FUNCTION && fptr->op_array.doc_comment) { RETURN_STRINGL(fptr->op_array.doc_comment, fptr->op_array.doc_comment_len, 1); } RETURN_FALSE; } /* }}} */ /* {{{ proto public array ReflectionFunction::getStaticVariables() Returns an associative array containing this function's static variables and their values */ ZEND_METHOD(reflection_function, getStaticVariables) { zval *tmp_copy; reflection_object *intern; zend_function *fptr; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(fptr); /* Return an empty array in case no static variables exist */ array_init(return_value); if (fptr->type == ZEND_USER_FUNCTION && fptr->op_array.static_variables != NULL) { zend_hash_apply_with_argument(fptr->op_array.static_variables, (apply_func_arg_t) zval_update_constant, (void*)1 TSRMLS_CC); zend_hash_copy(Z_ARRVAL_P(return_value), fptr->op_array.static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_copy, sizeof(zval *)); } } /* }}} */ /* {{{ proto public mixed ReflectionFunction::invoke([mixed* args]) Invokes the function */ ZEND_METHOD(reflection_function, invoke) { zval *retval_ptr; zval ***params = NULL; int result, num_args = 0; zend_fcall_info fci; zend_fcall_info_cache fcc; reflection_object *intern; zend_function *fptr; METHOD_NOTSTATIC(reflection_function_ptr); GET_REFLECTION_OBJECT_PTR(fptr); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "*", &params, &num_args) == FAILURE) { return; } fci.size = sizeof(fci); fci.function_table = NULL; fci.function_name = NULL; fci.symbol_table = NULL; fci.object_ptr = NULL; fci.retval_ptr_ptr = &retval_ptr; fci.param_count = num_args; fci.params = params; fci.no_separation = 1; fcc.initialized = 1; fcc.function_handler = fptr; fcc.calling_scope = EG(scope); fcc.called_scope = NULL; fcc.object_ptr = NULL; result = zend_call_function(&fci, &fcc TSRMLS_CC); if (num_args) { efree(params); } if (result == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Invocation of function %s() failed", fptr->common.function_name); return; } if (retval_ptr) { COPY_PZVAL_TO_ZVAL(*return_value, retval_ptr); } } /* }}} */ static int _zval_array_to_c_array(zval **arg, zval ****params TSRMLS_DC) /* {{{ */ { *(*params)++ = arg; return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* {{{ proto public mixed ReflectionFunction::invokeArgs(array args) Invokes the function and pass its arguments as array. */ ZEND_METHOD(reflection_function, invokeArgs) { zval *retval_ptr; zval ***params; int result; int argc; zend_fcall_info fci; zend_fcall_info_cache fcc; reflection_object *intern; zend_function *fptr; zval *param_array; METHOD_NOTSTATIC(reflection_function_ptr); GET_REFLECTION_OBJECT_PTR(fptr); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &param_array) == FAILURE) { return; } argc = zend_hash_num_elements(Z_ARRVAL_P(param_array)); params = safe_emalloc(sizeof(zval **), argc, 0); zend_hash_apply_with_argument(Z_ARRVAL_P(param_array), (apply_func_arg_t)_zval_array_to_c_array, &params TSRMLS_CC); params -= argc; fci.size = sizeof(fci); fci.function_table = NULL; fci.function_name = NULL; fci.symbol_table = NULL; fci.object_ptr = NULL; fci.retval_ptr_ptr = &retval_ptr; fci.param_count = argc; fci.params = params; fci.no_separation = 1; fcc.initialized = 1; fcc.function_handler = fptr; fcc.calling_scope = EG(scope); fcc.called_scope = NULL; fcc.object_ptr = NULL; result = zend_call_function(&fci, &fcc TSRMLS_CC); efree(params); if (result == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Invocation of function %s() failed", fptr->common.function_name); return; } if (retval_ptr) { COPY_PZVAL_TO_ZVAL(*return_value, retval_ptr); } } /* }}} */ /* {{{ proto public bool ReflectionFunction::returnsReference() Gets whether this function returns a reference */ ZEND_METHOD(reflection_function, returnsReference) { reflection_object *intern; zend_function *fptr; METHOD_NOTSTATIC(reflection_function_abstract_ptr); GET_REFLECTION_OBJECT_PTR(fptr); RETURN_BOOL((fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) != 0); } /* }}} */ /* {{{ proto public bool ReflectionFunction::getNumberOfParameters() Gets the number of required parameters */ ZEND_METHOD(reflection_function, getNumberOfParameters) { reflection_object *intern; zend_function *fptr; METHOD_NOTSTATIC(reflection_function_abstract_ptr); GET_REFLECTION_OBJECT_PTR(fptr); RETURN_LONG(fptr->common.num_args); } /* }}} */ /* {{{ proto public bool ReflectionFunction::getNumberOfRequiredParameters() Gets the number of required parameters */ ZEND_METHOD(reflection_function, getNumberOfRequiredParameters) { reflection_object *intern; zend_function *fptr; METHOD_NOTSTATIC(reflection_function_abstract_ptr); GET_REFLECTION_OBJECT_PTR(fptr); RETURN_LONG(fptr->common.required_num_args); } /* }}} */ /* {{{ proto public ReflectionParameter[] ReflectionFunction::getParameters() Returns an array of parameter objects for this function */ ZEND_METHOD(reflection_function, getParameters) { reflection_object *intern; zend_function *fptr; zend_uint i; struct _zend_arg_info *arg_info; METHOD_NOTSTATIC(reflection_function_abstract_ptr); GET_REFLECTION_OBJECT_PTR(fptr); arg_info= fptr->common.arg_info; array_init(return_value); for (i = 0; i < fptr->common.num_args; i++) { zval *parameter; ALLOC_ZVAL(parameter); reflection_parameter_factory(_copy_function(fptr TSRMLS_CC), intern->obj, arg_info, i, fptr->common.required_num_args, parameter TSRMLS_CC); add_next_index_zval(return_value, parameter); arg_info++; } } /* }}} */ /* {{{ proto public ReflectionExtension|NULL ReflectionFunction::getExtension() Returns NULL or the extension the function belongs to */ ZEND_METHOD(reflection_function, getExtension) { reflection_object *intern; zend_function *fptr; zend_internal_function *internal; METHOD_NOTSTATIC(reflection_function_abstract_ptr); GET_REFLECTION_OBJECT_PTR(fptr); if (fptr->type != ZEND_INTERNAL_FUNCTION) { RETURN_NULL(); } internal = (zend_internal_function *)fptr; if (internal->module) { reflection_extension_factory(return_value, internal->module->name TSRMLS_CC); } else { RETURN_NULL(); } } /* }}} */ /* {{{ proto public string|false ReflectionFunction::getExtensionName() Returns false or the name of the extension the function belongs to */ ZEND_METHOD(reflection_function, getExtensionName) { reflection_object *intern; zend_function *fptr; zend_internal_function *internal; METHOD_NOTSTATIC(reflection_function_abstract_ptr); GET_REFLECTION_OBJECT_PTR(fptr); if (fptr->type != ZEND_INTERNAL_FUNCTION) { RETURN_FALSE; } internal = (zend_internal_function *)fptr; if (internal->module) { RETURN_STRING(internal->module->name, 1); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto public static mixed ReflectionParameter::export(mixed function, mixed parameter [, bool return]) throws ReflectionException Exports a reflection object. Returns the output if TRUE is specified for return, printing it otherwise. */ ZEND_METHOD(reflection_parameter, export) { _reflection_export(INTERNAL_FUNCTION_PARAM_PASSTHRU, reflection_parameter_ptr, 2); } /* }}} */ /* {{{ proto public void ReflectionParameter::__construct(mixed function, mixed parameter) Constructor. Throws an Exception in case the given method does not exist */ ZEND_METHOD(reflection_parameter, __construct) { parameter_reference *ref; zval *reference, **parameter; zval *object; zval *name; reflection_object *intern; zend_function *fptr; struct _zend_arg_info *arg_info; int position; zend_class_entry *ce = NULL; zend_bool is_closure = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zZ", &reference, &parameter) == FAILURE) { return; } object = getThis(); intern = (reflection_object *) zend_object_store_get_object(object TSRMLS_CC); if (intern == NULL) { return; } /* First, find the function */ switch (Z_TYPE_P(reference)) { case IS_STRING: { unsigned int lcname_len; char *lcname; lcname_len = Z_STRLEN_P(reference); lcname = zend_str_tolower_dup(Z_STRVAL_P(reference), lcname_len); if (zend_hash_find(EG(function_table), lcname, lcname_len + 1, (void**) &fptr) == FAILURE) { efree(lcname); zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Function %s() does not exist", Z_STRVAL_P(reference)); return; } efree(lcname); } ce = fptr->common.scope; break; case IS_ARRAY: { zval **classref; zval **method; zend_class_entry **pce; unsigned int lcname_len; char *lcname; if ((zend_hash_index_find(Z_ARRVAL_P(reference), 0, (void **) &classref) == FAILURE) || (zend_hash_index_find(Z_ARRVAL_P(reference), 1, (void **) &method) == FAILURE)) { _DO_THROW("Expected array($object, $method) or array($classname, $method)"); /* returns out of this function */ } if (Z_TYPE_PP(classref) == IS_OBJECT) { ce = Z_OBJCE_PP(classref); } else { convert_to_string_ex(classref); if (zend_lookup_class(Z_STRVAL_PP(classref), Z_STRLEN_PP(classref), &pce TSRMLS_CC) == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Class %s does not exist", Z_STRVAL_PP(classref)); return; } ce = *pce; } convert_to_string_ex(method); lcname_len = Z_STRLEN_PP(method); lcname = zend_str_tolower_dup(Z_STRVAL_PP(method), lcname_len); if (ce == zend_ce_closure && Z_TYPE_PP(classref) == IS_OBJECT && (lcname_len == sizeof(ZEND_INVOKE_FUNC_NAME)-1) && memcmp(lcname, ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME)-1) == 0 && (fptr = zend_get_closure_invoke_method(*classref TSRMLS_CC)) != NULL) { /* nothing to do. don't set is_closure since is the invoke handler, - not the closure itself */ } else if (zend_hash_find(&ce->function_table, lcname, lcname_len + 1, (void **) &fptr) == FAILURE) { efree(lcname); zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Method %s::%s() does not exist", ce->name, Z_STRVAL_PP(method)); return; } efree(lcname); } break; case IS_OBJECT: { ce = Z_OBJCE_P(reference); if (instanceof_function(ce, zend_ce_closure TSRMLS_CC)) { fptr = (zend_function *)zend_get_closure_method_def(reference TSRMLS_CC); Z_ADDREF_P(reference); is_closure = 1; } else if (zend_hash_find(&ce->function_table, ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME), (void **)&fptr) == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Method %s::%s() does not exist", ce->name, ZEND_INVOKE_FUNC_NAME); return; } } break; default: _DO_THROW("The parameter class is expected to be either a string, an array(class, method) or a callable object"); /* returns out of this function */ } /* Now, search for the parameter */ arg_info = fptr->common.arg_info; if (Z_TYPE_PP(parameter) == IS_LONG) { position= Z_LVAL_PP(parameter); if (position < 0 || (zend_uint)position >= fptr->common.num_args) { if (fptr->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) { if (fptr->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fptr->common.function_name); } efree(fptr); } if (is_closure) { zval_ptr_dtor(&reference); } _DO_THROW("The parameter specified by its offset could not be found"); /* returns out of this function */ } } else { zend_uint i; position= -1; convert_to_string_ex(parameter); for (i = 0; i < fptr->common.num_args; i++) { if (arg_info[i].name && strcmp(arg_info[i].name, Z_STRVAL_PP(parameter)) == 0) { position= i; break; } } if (position == -1) { if (fptr->common.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) { if (fptr->type != ZEND_OVERLOADED_FUNCTION) { efree((char*)fptr->common.function_name); } efree(fptr); } if (is_closure) { zval_ptr_dtor(&reference); } _DO_THROW("The parameter specified by its name could not be found"); /* returns out of this function */ } } MAKE_STD_ZVAL(name); if (arg_info[position].name) { ZVAL_STRINGL(name, arg_info[position].name, arg_info[position].name_len, 1); } else { ZVAL_NULL(name); } reflection_update_property(object, "name", name); ref = (parameter_reference*) emalloc(sizeof(parameter_reference)); ref->arg_info = &arg_info[position]; ref->offset = (zend_uint)position; ref->required = fptr->common.required_num_args; ref->fptr = fptr; /* TODO: copy fptr */ intern->ptr = ref; intern->ref_type = REF_TYPE_PARAMETER; intern->ce = ce; if (reference && is_closure) { intern->obj = reference; } } /* }}} */ /* {{{ proto public string ReflectionParameter::__toString() Returns a string representation */ ZEND_METHOD(reflection_parameter, __toString) { reflection_object *intern; parameter_reference *param; string str; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(param); string_init(&str); _parameter_string(&str, param->fptr, param->arg_info, param->offset, param->required, "" TSRMLS_CC); RETURN_STRINGL(str.string, str.len - 1, 0); } /* }}} */ /* {{{ proto public string ReflectionParameter::getName() Returns this parameters's name */ ZEND_METHOD(reflection_parameter, getName) { if (zend_parse_parameters_none() == FAILURE) { return; } _default_get_entry(getThis(), "name", sizeof("name"), return_value TSRMLS_CC); } /* }}} */ /* {{{ proto public ReflectionFunction ReflectionParameter::getDeclaringFunction() Returns the ReflectionFunction for the function of this parameter */ ZEND_METHOD(reflection_parameter, getDeclaringFunction) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(param); if (!param->fptr->common.scope) { reflection_function_factory(_copy_function(param->fptr TSRMLS_CC), intern->obj, return_value TSRMLS_CC); } else { reflection_method_factory(param->fptr->common.scope, _copy_function(param->fptr TSRMLS_CC), intern->obj, return_value TSRMLS_CC); } } /* }}} */ /* {{{ proto public ReflectionClass|NULL ReflectionParameter::getDeclaringClass() Returns in which class this parameter is defined (not the typehint of the parameter) */ ZEND_METHOD(reflection_parameter, getDeclaringClass) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(param); if (param->fptr->common.scope) { zend_reflection_class_factory(param->fptr->common.scope, return_value TSRMLS_CC); } } /* }}} */ /* {{{ proto public ReflectionClass|NULL ReflectionParameter::getClass() Returns this parameters's class hint or NULL if there is none */ ZEND_METHOD(reflection_parameter, getClass) { reflection_object *intern; parameter_reference *param; zend_class_entry **pce, *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(param); if (param->arg_info->class_name) { /* Class name is stored as a string, we might also get "self" or "parent" * - For "self", simply use the function scope. If scope is NULL then * the function is global and thus self does not make any sense * * - For "parent", use the function scope's parent. If scope is NULL then * the function is global and thus parent does not make any sense. * If the parent is NULL then the class does not extend anything and * thus parent does not make any sense, either. * * TODO: Think about moving these checks to the compiler or some sort of * lint-mode. */ if (0 == zend_binary_strcasecmp(param->arg_info->class_name, param->arg_info->class_name_len, "self", sizeof("self")- 1)) { ce = param->fptr->common.scope; if (!ce) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Parameter uses 'self' as type hint but function is not a class member!"); return; } pce= &ce; } else if (0 == zend_binary_strcasecmp(param->arg_info->class_name, param->arg_info->class_name_len, "parent", sizeof("parent")- 1)) { ce = param->fptr->common.scope; if (!ce) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Parameter uses 'parent' as type hint but function is not a class member!"); return; } if (!ce->parent) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Parameter uses 'parent' as type hint although class does not have a parent!"); return; } pce= &ce->parent; } else if (zend_lookup_class(param->arg_info->class_name, param->arg_info->class_name_len, &pce TSRMLS_CC) == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Class %s does not exist", param->arg_info->class_name); return; } zend_reflection_class_factory(*pce, return_value TSRMLS_CC); } } /* }}} */ /* {{{ proto public bool ReflectionParameter::isArray() Returns whether parameter MUST be an array */ ZEND_METHOD(reflection_parameter, isArray) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(param); RETVAL_BOOL(param->arg_info->type_hint == IS_ARRAY); } /* }}} */ /* {{{ proto public bool ReflectionParameter::isCallable() Returns whether parameter MUST be callable */ ZEND_METHOD(reflection_parameter, isCallable) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(param); RETVAL_BOOL(param->arg_info->type_hint == IS_CALLABLE); } /* }}} */ /* {{{ proto public bool ReflectionParameter::allowsNull() Returns whether NULL is allowed as this parameters's value */ ZEND_METHOD(reflection_parameter, allowsNull) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(param); RETVAL_BOOL(param->arg_info->allow_null); } /* }}} */ /* {{{ proto public bool ReflectionParameter::isPassedByReference() Returns whether this parameters is passed to by reference */ ZEND_METHOD(reflection_parameter, isPassedByReference) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(param); RETVAL_BOOL(param->arg_info->pass_by_reference); } /* }}} */ /* {{{ proto public bool ReflectionParameter::canBePassedByValue() Returns whether this parameter can be passed by value */ ZEND_METHOD(reflection_parameter, canBePassedByValue) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(param); /* true if it's ZEND_SEND_BY_VAL or ZEND_SEND_PREFER_REF */ RETVAL_BOOL(param->arg_info->pass_by_reference != ZEND_SEND_BY_REF); } /* }}} */ /* {{{ proto public bool ReflectionParameter::getPosition() Returns whether this parameter is an optional parameter */ ZEND_METHOD(reflection_parameter, getPosition) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(param); RETVAL_LONG(param->offset); } /* }}} */ /* {{{ proto public bool ReflectionParameter::isOptional() Returns whether this parameter is an optional parameter */ ZEND_METHOD(reflection_parameter, isOptional) { reflection_object *intern; parameter_reference *param; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(param); RETVAL_BOOL(param->offset >= param->required); } /* }}} */ /* {{{ proto public bool ReflectionParameter::isDefaultValueAvailable() Returns whether the default value of this parameter is available */ ZEND_METHOD(reflection_parameter, isDefaultValueAvailable) { reflection_object *intern; parameter_reference *param; zend_op *precv; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(param); if (param->fptr->type != ZEND_USER_FUNCTION) { RETURN_FALSE; } if (param->offset < param->required) { RETURN_FALSE; } precv = _get_recv_op((zend_op_array*)param->fptr, param->offset); if (!precv || precv->opcode != ZEND_RECV_INIT || precv->op2_type == IS_UNUSED) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto public bool ReflectionParameter::getDefaultValue() Returns the default value of this parameter or throws an exception */ ZEND_METHOD(reflection_parameter, getDefaultValue) { reflection_object *intern; parameter_reference *param; zend_op *precv; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(param); if (param->fptr->type != ZEND_USER_FUNCTION) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Cannot determine default value for internal functions"); return; } if (param->offset < param->required) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Parameter is not optional"); return; } precv = _get_recv_op((zend_op_array*)param->fptr, param->offset); if (!precv || precv->opcode != ZEND_RECV_INIT || precv->op2_type == IS_UNUSED) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Internal error"); return; } *return_value = *precv->op2.zv; INIT_PZVAL(return_value); if (Z_TYPE_P(return_value) != IS_CONSTANT && Z_TYPE_P(return_value) != IS_CONSTANT_ARRAY) { zval_copy_ctor(return_value); } zval_update_constant_ex(&return_value, (void*)0, param->fptr->common.scope TSRMLS_CC); } /* }}} */ /* {{{ proto public static mixed ReflectionMethod::export(mixed class, string name [, bool return]) throws ReflectionException Exports a reflection object. Returns the output if TRUE is specified for return, printing it otherwise. */ ZEND_METHOD(reflection_method, export) { _reflection_export(INTERNAL_FUNCTION_PARAM_PASSTHRU, reflection_method_ptr, 2); } /* }}} */ /* {{{ proto public void ReflectionMethod::__construct(mixed class_or_method [, string name]) Constructor. Throws an Exception in case the given method does not exist */ ZEND_METHOD(reflection_method, __construct) { zval *name, *classname; zval *object, *orig_obj; reflection_object *intern; char *lcname; zend_class_entry **pce; zend_class_entry *ce; zend_function *mptr; char *name_str, *tmp; int name_len, tmp_len; zval ztmp; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "zs", &classname, &name_str, &name_len) == FAILURE) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name_str, &name_len) == FAILURE) { return; } if ((tmp = strstr(name_str, "::")) == NULL) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Invalid method name %s", name_str); return; } classname = &ztmp; tmp_len = tmp - name_str; ZVAL_STRINGL(classname, name_str, tmp_len, 1); name_len = name_len - (tmp_len + 2); name_str = tmp + 2; orig_obj = NULL; } else if (Z_TYPE_P(classname) == IS_OBJECT) { orig_obj = classname; } else { orig_obj = NULL; } object = getThis(); intern = (reflection_object *) zend_object_store_get_object(object TSRMLS_CC); if (intern == NULL) { return; } /* Find the class entry */ switch (Z_TYPE_P(classname)) { case IS_STRING: if (zend_lookup_class(Z_STRVAL_P(classname), Z_STRLEN_P(classname), &pce TSRMLS_CC) == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Class %s does not exist", Z_STRVAL_P(classname)); if (classname == &ztmp) { zval_dtor(&ztmp); } return; } ce = *pce; break; case IS_OBJECT: ce = Z_OBJCE_P(classname); break; default: if (classname == &ztmp) { zval_dtor(&ztmp); } _DO_THROW("The parameter class is expected to be either a string or an object"); /* returns out of this function */ } if (classname == &ztmp) { zval_dtor(&ztmp); } lcname = zend_str_tolower_dup(name_str, name_len); if (ce == zend_ce_closure && orig_obj && (name_len == sizeof(ZEND_INVOKE_FUNC_NAME)-1) && memcmp(lcname, ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME)-1) == 0 && (mptr = zend_get_closure_invoke_method(orig_obj TSRMLS_CC)) != NULL) { /* do nothing, mptr already set */ } else if (zend_hash_find(&ce->function_table, lcname, name_len + 1, (void **) &mptr) == FAILURE) { efree(lcname); zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Method %s::%s() does not exist", ce->name, name_str); return; } efree(lcname); MAKE_STD_ZVAL(classname); ZVAL_STRINGL(classname, mptr->common.scope->name, mptr->common.scope->name_length, 1); reflection_update_property(object, "class", classname); MAKE_STD_ZVAL(name); ZVAL_STRING(name, mptr->common.function_name, 1); reflection_update_property(object, "name", name); intern->ptr = mptr; intern->ref_type = REF_TYPE_FUNCTION; intern->ce = ce; } /* }}} */ /* {{{ proto public string ReflectionMethod::__toString() Returns a string representation */ ZEND_METHOD(reflection_method, __toString) { reflection_object *intern; zend_function *mptr; string str; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(mptr); string_init(&str); _function_string(&str, mptr, intern->ce, "" TSRMLS_CC); RETURN_STRINGL(str.string, str.len - 1, 0); } /* }}} */ /* {{{ proto public mixed ReflectionMethod::getClosure([mixed object]) Invokes the function */ ZEND_METHOD(reflection_method, getClosure) { reflection_object *intern; zval *obj; zend_function *mptr; METHOD_NOTSTATIC(reflection_method_ptr); GET_REFLECTION_OBJECT_PTR(mptr); if (mptr->common.fn_flags & ZEND_ACC_STATIC) { zend_create_closure(return_value, mptr, mptr->common.scope, NULL TSRMLS_CC); } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "o", &obj) == FAILURE) { return; } if (!instanceof_function(Z_OBJCE_P(obj), mptr->common.scope TSRMLS_CC)) { _DO_THROW("Given object is not an instance of the class this method was declared in"); /* Returns from this function */ } /* This is an original closure object and __invoke is to be called. */ if (Z_OBJCE_P(obj) == zend_ce_closure && mptr->type == ZEND_INTERNAL_FUNCTION && (mptr->internal_function.fn_flags & ZEND_ACC_CALL_VIA_HANDLER) != 0) { RETURN_ZVAL(obj, 1, 0); } else { zend_create_closure(return_value, mptr, mptr->common.scope, obj TSRMLS_CC); } } } /* }}} */ /* {{{ proto public mixed ReflectionMethod::invoke(mixed object, mixed* args) Invokes the method. */ ZEND_METHOD(reflection_method, invoke) { zval *retval_ptr; zval ***params = NULL; zval *object_ptr; reflection_object *intern; zend_function *mptr; int result, num_args = 0; zend_fcall_info fci; zend_fcall_info_cache fcc; zend_class_entry *obj_ce; METHOD_NOTSTATIC(reflection_method_ptr); GET_REFLECTION_OBJECT_PTR(mptr); if ((!(mptr->common.fn_flags & ZEND_ACC_PUBLIC) || (mptr->common.fn_flags & ZEND_ACC_ABSTRACT)) && intern->ignore_visibility == 0) { if (mptr->common.fn_flags & ZEND_ACC_ABSTRACT) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Trying to invoke abstract method %s::%s()", mptr->common.scope->name, mptr->common.function_name); } else { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Trying to invoke %s method %s::%s() from scope %s", mptr->common.fn_flags & ZEND_ACC_PROTECTED ? "protected" : "private", mptr->common.scope->name, mptr->common.function_name, Z_OBJCE_P(getThis())->name); } return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &params, &num_args) == FAILURE) { return; } /* In case this is a static method, we should'nt pass an object_ptr * (which is used as calling context aka $this). We can thus ignore the * first parameter. * * Else, we verify that the given object is an instance of the class. */ if (mptr->common.fn_flags & ZEND_ACC_STATIC) { object_ptr = NULL; obj_ce = mptr->common.scope; } else { if (Z_TYPE_PP(params[0]) != IS_OBJECT) { efree(params); _DO_THROW("Non-object passed to Invoke()"); /* Returns from this function */ } obj_ce = Z_OBJCE_PP(params[0]); if (!instanceof_function(obj_ce, mptr->common.scope TSRMLS_CC)) { if (params) { efree(params); } _DO_THROW("Given object is not an instance of the class this method was declared in"); /* Returns from this function */ } object_ptr = *params[0]; } fci.size = sizeof(fci); fci.function_table = NULL; fci.function_name = NULL; fci.symbol_table = NULL; fci.object_ptr = object_ptr; fci.retval_ptr_ptr = &retval_ptr; fci.param_count = num_args - 1; fci.params = params + 1; fci.no_separation = 1; fcc.initialized = 1; fcc.function_handler = mptr; fcc.calling_scope = obj_ce; fcc.called_scope = obj_ce; fcc.object_ptr = object_ptr; result = zend_call_function(&fci, &fcc TSRMLS_CC); if (params) { efree(params); } if (result == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Invocation of method %s::%s() failed", mptr->common.scope->name, mptr->common.function_name); return; } if (retval_ptr) { COPY_PZVAL_TO_ZVAL(*return_value, retval_ptr); } } /* }}} */ /* {{{ proto public mixed ReflectionMethod::invokeArgs(mixed object, array args) Invokes the function and pass its arguments as array. */ ZEND_METHOD(reflection_method, invokeArgs) { zval *retval_ptr; zval ***params; zval *object; reflection_object *intern; zend_function *mptr; int argc; int result; zend_fcall_info fci; zend_fcall_info_cache fcc; zend_class_entry *obj_ce; zval *param_array; METHOD_NOTSTATIC(reflection_method_ptr); GET_REFLECTION_OBJECT_PTR(mptr); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "o!a", &object, &param_array) == FAILURE) { return; } if ((!(mptr->common.fn_flags & ZEND_ACC_PUBLIC) || (mptr->common.fn_flags & ZEND_ACC_ABSTRACT)) && intern->ignore_visibility == 0) { if (mptr->common.fn_flags & ZEND_ACC_ABSTRACT) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Trying to invoke abstract method %s::%s()", mptr->common.scope->name, mptr->common.function_name); } else { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Trying to invoke %s method %s::%s() from scope %s", mptr->common.fn_flags & ZEND_ACC_PROTECTED ? "protected" : "private", mptr->common.scope->name, mptr->common.function_name, Z_OBJCE_P(getThis())->name); } return; } argc = zend_hash_num_elements(Z_ARRVAL_P(param_array)); params = safe_emalloc(sizeof(zval **), argc, 0); zend_hash_apply_with_argument(Z_ARRVAL_P(param_array), (apply_func_arg_t)_zval_array_to_c_array, &params TSRMLS_CC); params -= argc; /* In case this is a static method, we should'nt pass an object_ptr * (which is used as calling context aka $this). We can thus ignore the * first parameter. * * Else, we verify that the given object is an instance of the class. */ if (mptr->common.fn_flags & ZEND_ACC_STATIC) { object = NULL; obj_ce = mptr->common.scope; } else { if (!object) { efree(params); zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Trying to invoke non static method %s::%s() without an object", mptr->common.scope->name, mptr->common.function_name); return; } obj_ce = Z_OBJCE_P(object); if (!instanceof_function(obj_ce, mptr->common.scope TSRMLS_CC)) { efree(params); _DO_THROW("Given object is not an instance of the class this method was declared in"); /* Returns from this function */ } } fci.size = sizeof(fci); fci.function_table = NULL; fci.function_name = NULL; fci.symbol_table = NULL; fci.object_ptr = object; fci.retval_ptr_ptr = &retval_ptr; fci.param_count = argc; fci.params = params; fci.no_separation = 1; fcc.initialized = 1; fcc.function_handler = mptr; fcc.calling_scope = obj_ce; fcc.called_scope = obj_ce; fcc.object_ptr = object; result = zend_call_function(&fci, &fcc TSRMLS_CC); efree(params); if (result == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Invocation of method %s::%s() failed", mptr->common.scope->name, mptr->common.function_name); return; } if (retval_ptr) { COPY_PZVAL_TO_ZVAL(*return_value, retval_ptr); } } /* }}} */ /* {{{ proto public bool ReflectionMethod::isFinal() Returns whether this method is final */ ZEND_METHOD(reflection_method, isFinal) { _function_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_FINAL); } /* }}} */ /* {{{ proto public bool ReflectionMethod::isAbstract() Returns whether this method is abstract */ ZEND_METHOD(reflection_method, isAbstract) { _function_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_ABSTRACT); } /* }}} */ /* {{{ proto public bool ReflectionMethod::isPublic() Returns whether this method is public */ ZEND_METHOD(reflection_method, isPublic) { _function_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_PUBLIC); } /* }}} */ /* {{{ proto public bool ReflectionMethod::isPrivate() Returns whether this method is private */ ZEND_METHOD(reflection_method, isPrivate) { _function_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_PRIVATE); } /* }}} */ /* {{{ proto public bool ReflectionMethod::isProtected() Returns whether this method is protected */ ZEND_METHOD(reflection_method, isProtected) { _function_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_PROTECTED); } /* }}} */ /* {{{ proto public bool ReflectionMethod::isStatic() Returns whether this method is static */ ZEND_METHOD(reflection_method, isStatic) { _function_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_STATIC); } /* }}} */ /* {{{ proto public bool ReflectionFunction::isDeprecated() Returns whether this function is deprecated */ ZEND_METHOD(reflection_function, isDeprecated) { _function_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_DEPRECATED); } /* }}} */ /* {{{ proto public bool ReflectionFunction::inNamespace() Returns whether this function is defined in namespace */ ZEND_METHOD(reflection_function, inNamespace) { zval **name; const char *backslash; if (zend_parse_parameters_none() == FAILURE) { return; } if (zend_hash_find(Z_OBJPROP_P(getThis()), "name", sizeof("name"), (void **) &name) == FAILURE) { RETURN_FALSE; } if (Z_TYPE_PP(name) == IS_STRING && (backslash = zend_memrchr(Z_STRVAL_PP(name), '\\', Z_STRLEN_PP(name))) && backslash > Z_STRVAL_PP(name)) { RETURN_TRUE; } RETURN_FALSE; } /* }}} */ /* {{{ proto public string ReflectionFunction::getNamespaceName() Returns the name of namespace where this function is defined */ ZEND_METHOD(reflection_function, getNamespaceName) { zval **name; const char *backslash; if (zend_parse_parameters_none() == FAILURE) { return; } if (zend_hash_find(Z_OBJPROP_P(getThis()), "name", sizeof("name"), (void **) &name) == FAILURE) { RETURN_FALSE; } if (Z_TYPE_PP(name) == IS_STRING && (backslash = zend_memrchr(Z_STRVAL_PP(name), '\\', Z_STRLEN_PP(name))) && backslash > Z_STRVAL_PP(name)) { RETURN_STRINGL(Z_STRVAL_PP(name), backslash - Z_STRVAL_PP(name), 1); } RETURN_EMPTY_STRING(); } /* }}} */ /* {{{ proto public string ReflectionFunction::getShortName() Returns the short name of the function (without namespace part) */ ZEND_METHOD(reflection_function, getShortName) { zval **name; const char *backslash; if (zend_parse_parameters_none() == FAILURE) { return; } if (zend_hash_find(Z_OBJPROP_P(getThis()), "name", sizeof("name"), (void **) &name) == FAILURE) { RETURN_FALSE; } if (Z_TYPE_PP(name) == IS_STRING && (backslash = zend_memrchr(Z_STRVAL_PP(name), '\\', Z_STRLEN_PP(name))) && backslash > Z_STRVAL_PP(name)) { RETURN_STRINGL(backslash + 1, Z_STRLEN_PP(name) - (backslash - Z_STRVAL_PP(name) + 1), 1); } RETURN_ZVAL(*name, 1, 0); } /* }}} */ /* {{{ proto public bool ReflectionMethod::isConstructor() Returns whether this method is the constructor */ ZEND_METHOD(reflection_method, isConstructor) { reflection_object *intern; zend_function *mptr; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(mptr); /* we need to check if the ctor is the ctor of the class level we we * looking at since we might be looking at an inherited old style ctor * defined in base class. */ RETURN_BOOL(mptr->common.fn_flags & ZEND_ACC_CTOR && intern->ce->constructor && intern->ce->constructor->common.scope == mptr->common.scope); } /* }}} */ /* {{{ proto public bool ReflectionMethod::isDestructor() Returns whether this method is static */ ZEND_METHOD(reflection_method, isDestructor) { reflection_object *intern; zend_function *mptr; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(mptr); RETURN_BOOL(mptr->common.fn_flags & ZEND_ACC_DTOR); } /* }}} */ /* {{{ proto public int ReflectionMethod::getModifiers() Returns a bitfield of the access modifiers for this method */ ZEND_METHOD(reflection_method, getModifiers) { reflection_object *intern; zend_function *mptr; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(mptr); RETURN_LONG(mptr->common.fn_flags); } /* }}} */ /* {{{ proto public ReflectionClass ReflectionMethod::getDeclaringClass() Get the declaring class */ ZEND_METHOD(reflection_method, getDeclaringClass) { reflection_object *intern; zend_function *mptr; METHOD_NOTSTATIC(reflection_method_ptr); GET_REFLECTION_OBJECT_PTR(mptr); if (zend_parse_parameters_none() == FAILURE) { return; } zend_reflection_class_factory(mptr->common.scope, return_value TSRMLS_CC); } /* }}} */ /* {{{ proto public ReflectionClass ReflectionMethod::getPrototype() Get the prototype */ ZEND_METHOD(reflection_method, getPrototype) { reflection_object *intern; zend_function *mptr; METHOD_NOTSTATIC(reflection_method_ptr); GET_REFLECTION_OBJECT_PTR(mptr); if (zend_parse_parameters_none() == FAILURE) { return; } if (!mptr->common.prototype) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Method %s::%s does not have a prototype", intern->ce->name, mptr->common.function_name); return; } reflection_method_factory(mptr->common.prototype->common.scope, mptr->common.prototype, NULL, return_value TSRMLS_CC); } /* }}} */ /* {{{ proto public void ReflectionMethod::setAccessible(bool visible) Sets whether non-public methods can be invoked */ ZEND_METHOD(reflection_method, setAccessible) { reflection_object *intern; zend_bool visible; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "b", &visible) == FAILURE) { return; } intern = (reflection_object *) zend_object_store_get_object(getThis() TSRMLS_CC); if (intern == NULL) { return; } intern->ignore_visibility = visible; } /* }}} */ /* {{{ proto public static mixed ReflectionClass::export(mixed argument [, bool return]) throws ReflectionException Exports a reflection object. Returns the output if TRUE is specified for return, printing it otherwise. */ ZEND_METHOD(reflection_class, export) { _reflection_export(INTERNAL_FUNCTION_PARAM_PASSTHRU, reflection_class_ptr, 1); } /* }}} */ /* {{{ reflection_class_object_ctor */ static void reflection_class_object_ctor(INTERNAL_FUNCTION_PARAMETERS, int is_object) { zval *argument; zval *object; zval *classname; reflection_object *intern; zend_class_entry **ce; if (is_object) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "o", &argument) == FAILURE) { return; } } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z/", &argument) == FAILURE) { return; } } object = getThis(); intern = (reflection_object *) zend_object_store_get_object(object TSRMLS_CC); if (intern == NULL) { return; } if (Z_TYPE_P(argument) == IS_OBJECT) { MAKE_STD_ZVAL(classname); ZVAL_STRINGL(classname, Z_OBJCE_P(argument)->name, Z_OBJCE_P(argument)->name_length, 1); reflection_update_property(object, "name", classname); intern->ptr = Z_OBJCE_P(argument); if (is_object) { intern->obj = argument; zval_add_ref(&argument); } } else { convert_to_string_ex(&argument); if (zend_lookup_class(Z_STRVAL_P(argument), Z_STRLEN_P(argument), &ce TSRMLS_CC) == FAILURE) { if (!EG(exception)) { zend_throw_exception_ex(reflection_exception_ptr, -1 TSRMLS_CC, "Class %s does not exist", Z_STRVAL_P(argument)); } return; } MAKE_STD_ZVAL(classname); ZVAL_STRINGL(classname, (*ce)->name, (*ce)->name_length, 1); reflection_update_property(object, "name", classname); intern->ptr = *ce; } intern->ref_type = REF_TYPE_OTHER; } /* }}} */ /* {{{ proto public void ReflectionClass::__construct(mixed argument) throws ReflectionException Constructor. Takes a string or an instance as an argument */ ZEND_METHOD(reflection_class, __construct) { reflection_class_object_ctor(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ add_class_vars */ static void add_class_vars(zend_class_entry *ce, int statics, zval *return_value TSRMLS_DC) { HashPosition pos; zend_property_info *prop_info; zval *prop, *prop_copy; char *key; uint key_len; ulong num_index; zend_hash_internal_pointer_reset_ex(&ce->properties_info, &pos); while (zend_hash_get_current_data_ex(&ce->properties_info, (void **) &prop_info, &pos) == SUCCESS) { zend_hash_get_current_key_ex(&ce->properties_info, &key, &key_len, &num_index, 0, &pos); zend_hash_move_forward_ex(&ce->properties_info, &pos); if (((prop_info->flags & ZEND_ACC_SHADOW) && prop_info->ce != ce) || ((prop_info->flags & ZEND_ACC_PROTECTED) && !zend_check_protected(prop_info->ce, ce)) || ((prop_info->flags & ZEND_ACC_PRIVATE) && prop_info->ce != ce)) { continue; } prop = NULL; if (prop_info->offset >= 0) { if (statics && (prop_info->flags & ZEND_ACC_STATIC) != 0) { prop = ce->default_static_members_table[prop_info->offset]; } else if (!statics && (prop_info->flags & ZEND_ACC_STATIC) == 0) { prop = ce->default_properties_table[prop_info->offset]; } } if (!prop) { continue; } /* copy: enforce read only access */ ALLOC_ZVAL(prop_copy); *prop_copy = *prop; zval_copy_ctor(prop_copy); INIT_PZVAL(prop_copy); /* this is necessary to make it able to work with default array * properties, returned to user */ if (Z_TYPE_P(prop_copy) == IS_CONSTANT_ARRAY || (Z_TYPE_P(prop_copy) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zval_update_constant(&prop_copy, (void *) 1 TSRMLS_CC); } add_assoc_zval(return_value, key, prop_copy); } } /* }}} */ /* {{{ proto public array ReflectionClass::getStaticProperties() Returns an associative array containing all static property values of the class */ ZEND_METHOD(reflection_class, getStaticProperties) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); zend_update_class_constants(ce TSRMLS_CC); array_init(return_value); add_class_vars(ce, 1, return_value TSRMLS_CC); } /* }}} */ /* {{{ proto public mixed ReflectionClass::getStaticPropertyValue(string name [, mixed default]) Returns the value of a static property */ ZEND_METHOD(reflection_class, getStaticPropertyValue) { reflection_object *intern; zend_class_entry *ce; char *name; int name_len; zval **prop, *def_value = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|z", &name, &name_len, &def_value) == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); zend_update_class_constants(ce TSRMLS_CC); prop = zend_std_get_static_property(ce, name, name_len, 1, NULL TSRMLS_CC); if (!prop) { if (def_value) { RETURN_ZVAL(def_value, 1, 0); } else { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Class %s does not have a property named %s", ce->name, name); } return; } else { RETURN_ZVAL(*prop, 1, 0); } } /* }}} */ /* {{{ proto public void ReflectionClass::setStaticPropertyValue($name, $value) Sets the value of a static property */ ZEND_METHOD(reflection_class, setStaticPropertyValue) { reflection_object *intern; zend_class_entry *ce; char *name; int name_len; zval **variable_ptr, *value; int refcount; zend_uchar is_ref; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz", &name, &name_len, &value) == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); zend_update_class_constants(ce TSRMLS_CC); variable_ptr = zend_std_get_static_property(ce, name, name_len, 1, NULL TSRMLS_CC); if (!variable_ptr) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Class %s does not have a property named %s", ce->name, name); return; } refcount = Z_REFCOUNT_PP(variable_ptr); is_ref = Z_ISREF_PP(variable_ptr); zval_dtor(*variable_ptr); **variable_ptr = *value; zval_copy_ctor(*variable_ptr); Z_SET_REFCOUNT_PP(variable_ptr, refcount); Z_SET_ISREF_TO_PP(variable_ptr, is_ref); } /* }}} */ /* {{{ proto public array ReflectionClass::getDefaultProperties() Returns an associative array containing copies of all default property values of the class */ ZEND_METHOD(reflection_class, getDefaultProperties) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); array_init(return_value); zend_update_class_constants(ce TSRMLS_CC); add_class_vars(ce, 1, return_value TSRMLS_CC); add_class_vars(ce, 0, return_value TSRMLS_CC); } /* }}} */ /* {{{ proto public string ReflectionClass::__toString() Returns a string representation */ ZEND_METHOD(reflection_class, __toString) { reflection_object *intern; zend_class_entry *ce; string str; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); string_init(&str); _class_string(&str, ce, intern->obj, "" TSRMLS_CC); RETURN_STRINGL(str.string, str.len - 1, 0); } /* }}} */ /* {{{ proto public string ReflectionClass::getName() Returns the class' name */ ZEND_METHOD(reflection_class, getName) { if (zend_parse_parameters_none() == FAILURE) { return; } _default_get_entry(getThis(), "name", sizeof("name"), return_value TSRMLS_CC); } /* }}} */ /* {{{ proto public bool ReflectionClass::isInternal() Returns whether this class is an internal class */ ZEND_METHOD(reflection_class, isInternal) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); RETURN_BOOL(ce->type == ZEND_INTERNAL_CLASS); } /* }}} */ /* {{{ proto public bool ReflectionClass::isUserDefined() Returns whether this class is user-defined */ ZEND_METHOD(reflection_class, isUserDefined) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); RETURN_BOOL(ce->type == ZEND_USER_CLASS); } /* }}} */ /* {{{ proto public string ReflectionClass::getFileName() Returns the filename of the file this class was declared in */ ZEND_METHOD(reflection_class, getFileName) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); if (ce->type == ZEND_USER_CLASS) { RETURN_STRING(ce->info.user.filename, 1); } RETURN_FALSE; } /* }}} */ /* {{{ proto public int ReflectionClass::getStartLine() Returns the line this class' declaration starts at */ ZEND_METHOD(reflection_class, getStartLine) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); if (ce->type == ZEND_USER_FUNCTION) { RETURN_LONG(ce->info.user.line_start); } RETURN_FALSE; } /* }}} */ /* {{{ proto public int ReflectionClass::getEndLine() Returns the line this class' declaration ends at */ ZEND_METHOD(reflection_class, getEndLine) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); if (ce->type == ZEND_USER_CLASS) { RETURN_LONG(ce->info.user.line_end); } RETURN_FALSE; } /* }}} */ /* {{{ proto public string ReflectionClass::getDocComment() Returns the doc comment for this class */ ZEND_METHOD(reflection_class, getDocComment) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); if (ce->type == ZEND_USER_CLASS && ce->info.user.doc_comment) { RETURN_STRINGL(ce->info.user.doc_comment, ce->info.user.doc_comment_len, 1); } RETURN_FALSE; } /* }}} */ /* {{{ proto public ReflectionMethod ReflectionClass::getConstructor() Returns the class' constructor if there is one, NULL otherwise */ ZEND_METHOD(reflection_class, getConstructor) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); if (ce->constructor) { reflection_method_factory(ce, ce->constructor, NULL, return_value TSRMLS_CC); } else { RETURN_NULL(); } } /* }}} */ /* {{{ proto public bool ReflectionClass::hasMethod(string name) Returns whether a method exists or not */ ZEND_METHOD(reflection_class, hasMethod) { reflection_object *intern; zend_class_entry *ce; char *name, *lc_name; int name_len; METHOD_NOTSTATIC(reflection_class_ptr); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); lc_name = zend_str_tolower_dup(name, name_len); if ((ce == zend_ce_closure && (name_len == sizeof(ZEND_INVOKE_FUNC_NAME)-1) && memcmp(lc_name, ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME)-1) == 0) || zend_hash_exists(&ce->function_table, lc_name, name_len + 1)) { efree(lc_name); RETURN_TRUE; } else { efree(lc_name); RETURN_FALSE; } } /* }}} */ /* {{{ proto public ReflectionMethod ReflectionClass::getMethod(string name) throws ReflectionException Returns the class' method specified by its name */ ZEND_METHOD(reflection_class, getMethod) { reflection_object *intern; zend_class_entry *ce; zend_function *mptr; zval obj_tmp; char *name, *lc_name; int name_len; METHOD_NOTSTATIC(reflection_class_ptr); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); lc_name = zend_str_tolower_dup(name, name_len); if (ce == zend_ce_closure && intern->obj && (name_len == sizeof(ZEND_INVOKE_FUNC_NAME)-1) && memcmp(lc_name, ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME)-1) == 0 && (mptr = zend_get_closure_invoke_method(intern->obj TSRMLS_CC)) != NULL) { /* don't assign closure_object since we only reflect the invoke handler method and not the closure definition itself */ reflection_method_factory(ce, mptr, NULL, return_value TSRMLS_CC); efree(lc_name); } else if (ce == zend_ce_closure && !intern->obj && (name_len == sizeof(ZEND_INVOKE_FUNC_NAME)-1) && memcmp(lc_name, ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME)-1) == 0 && object_init_ex(&obj_tmp, ce) == SUCCESS && (mptr = zend_get_closure_invoke_method(&obj_tmp TSRMLS_CC)) != NULL) { /* don't assign closure_object since we only reflect the invoke handler method and not the closure definition itself */ reflection_method_factory(ce, mptr, NULL, return_value TSRMLS_CC); zval_dtor(&obj_tmp); efree(lc_name); } else if (zend_hash_find(&ce->function_table, lc_name, name_len + 1, (void**) &mptr) == SUCCESS) { reflection_method_factory(ce, mptr, NULL, return_value TSRMLS_CC); efree(lc_name); } else { efree(lc_name); zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Method %s does not exist", name); return; } } /* }}} */ /* {{{ _addmethod */ static void _addmethod(zend_function *mptr, zend_class_entry *ce, zval *retval, long filter, zval *obj TSRMLS_DC) { zval *method; uint len = strlen(mptr->common.function_name); zend_function *closure; if (mptr->common.fn_flags & filter) { ALLOC_ZVAL(method); if (ce == zend_ce_closure && obj && (len == sizeof(ZEND_INVOKE_FUNC_NAME)-1) && memcmp(mptr->common.function_name, ZEND_INVOKE_FUNC_NAME, sizeof(ZEND_INVOKE_FUNC_NAME)-1) == 0 && (closure = zend_get_closure_invoke_method(obj TSRMLS_CC)) != NULL) { mptr = closure; } /* don't assign closure_object since we only reflect the invoke handler method and not the closure definition itself, even if we have a closure */ reflection_method_factory(ce, mptr, NULL, method TSRMLS_CC); add_next_index_zval(retval, method); } } /* }}} */ /* {{{ _addmethod */ static int _addmethod_va(zend_function *mptr TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) { zend_class_entry *ce = *va_arg(args, zend_class_entry**); zval *retval = va_arg(args, zval*); long filter = va_arg(args, long); zval *obj = va_arg(args, zval *); _addmethod(mptr, ce, retval, filter, obj TSRMLS_CC); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* {{{ proto public ReflectionMethod[] ReflectionClass::getMethods([long $filter]) Returns an array of this class' methods */ ZEND_METHOD(reflection_class, getMethods) { reflection_object *intern; zend_class_entry *ce; long filter = 0; int argc = ZEND_NUM_ARGS(); METHOD_NOTSTATIC(reflection_class_ptr); if (argc) { if (zend_parse_parameters(argc TSRMLS_CC, "|l", &filter) == FAILURE) { return; } } else { /* No parameters given, default to "return all" */ filter = ZEND_ACC_PPP_MASK | ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL | ZEND_ACC_STATIC; } GET_REFLECTION_OBJECT_PTR(ce); array_init(return_value); zend_hash_apply_with_arguments(&ce->function_table TSRMLS_CC, (apply_func_args_t) _addmethod_va, 4, &ce, return_value, filter, intern->obj); if (intern->obj && instanceof_function(ce, zend_ce_closure TSRMLS_CC)) { zend_function *closure = zend_get_closure_invoke_method(intern->obj TSRMLS_CC); if (closure) { _addmethod(closure, ce, return_value, filter, intern->obj TSRMLS_CC); _free_function(closure TSRMLS_CC); } } } /* }}} */ /* {{{ proto public bool ReflectionClass::hasProperty(string name) Returns whether a property exists or not */ ZEND_METHOD(reflection_class, hasProperty) { reflection_object *intern; zend_property_info *property_info; zend_class_entry *ce; char *name; int name_len; zval *property; METHOD_NOTSTATIC(reflection_class_ptr); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); if (zend_hash_find(&ce->properties_info, name, name_len+1, (void **) &property_info) == SUCCESS) { if (property_info->flags & ZEND_ACC_SHADOW) { RETURN_FALSE; } RETURN_TRUE; } else { if (intern->obj && Z_OBJ_HANDLER_P(intern->obj, has_property)) { MAKE_STD_ZVAL(property); ZVAL_STRINGL(property, name, name_len, 1); if (Z_OBJ_HANDLER_P(intern->obj, has_property)(intern->obj, property, 2, 0 TSRMLS_CC)) { zval_ptr_dtor(&property); RETURN_TRUE; } zval_ptr_dtor(&property); } RETURN_FALSE; } } /* }}} */ /* {{{ proto public ReflectionProperty ReflectionClass::getProperty(string name) throws ReflectionException Returns the class' property specified by its name */ ZEND_METHOD(reflection_class, getProperty) { reflection_object *intern; zend_class_entry *ce, **pce; zend_property_info *property_info; char *name, *tmp, *classname; int name_len, classname_len; METHOD_NOTSTATIC(reflection_class_ptr); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); if (zend_hash_find(&ce->properties_info, name, name_len + 1, (void**) &property_info) == SUCCESS) { if ((property_info->flags & ZEND_ACC_SHADOW) == 0) { reflection_property_factory(ce, property_info, return_value TSRMLS_CC); return; } } else if (intern->obj) { /* Check for dynamic properties */ if (zend_hash_exists(Z_OBJ_HT_P(intern->obj)->get_properties(intern->obj TSRMLS_CC), name, name_len+1)) { zend_property_info property_info_tmp; property_info_tmp.flags = ZEND_ACC_IMPLICIT_PUBLIC; property_info_tmp.name = estrndup(name, name_len); property_info_tmp.name_length = name_len; property_info_tmp.h = zend_get_hash_value(name, name_len+1); property_info_tmp.doc_comment = NULL; property_info_tmp.ce = ce; reflection_property_factory(ce, &property_info_tmp, return_value TSRMLS_CC); intern = (reflection_object *) zend_object_store_get_object(return_value TSRMLS_CC); intern->ref_type = REF_TYPE_DYNAMIC_PROPERTY; return; } } if ((tmp = strstr(name, "::")) != NULL) { classname_len = tmp - name; classname = zend_str_tolower_dup(name, classname_len); classname[classname_len] = '\0'; name_len = name_len - (classname_len + 2); name = tmp + 2; if (zend_lookup_class(classname, classname_len, &pce TSRMLS_CC) == FAILURE) { if (!EG(exception)) { zend_throw_exception_ex(reflection_exception_ptr, -1 TSRMLS_CC, "Class %s does not exist", classname); } efree(classname); return; } efree(classname); if (!instanceof_function(ce, *pce TSRMLS_CC)) { zend_throw_exception_ex(reflection_exception_ptr, -1 TSRMLS_CC, "Fully qualified property name %s::%s does not specify a base class of %s", (*pce)->name, name, ce->name); return; } ce = *pce; if (zend_hash_find(&ce->properties_info, name, name_len + 1, (void**) &property_info) == SUCCESS && (property_info->flags & ZEND_ACC_SHADOW) == 0) { reflection_property_factory(ce, property_info, return_value TSRMLS_CC); return; } } zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Property %s does not exist", name); } /* }}} */ /* {{{ _addproperty */ static int _addproperty(zend_property_info *pptr TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) { zval *property; zend_class_entry *ce = *va_arg(args, zend_class_entry**); zval *retval = va_arg(args, zval*); long filter = va_arg(args, long); if (pptr->flags & ZEND_ACC_SHADOW) { return 0; } if (pptr->flags & filter) { ALLOC_ZVAL(property); reflection_property_factory(ce, pptr, property TSRMLS_CC); add_next_index_zval(retval, property); } return 0; } /* }}} */ /* {{{ _adddynproperty */ static int _adddynproperty(zval **pptr TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) { zval *property; zend_class_entry *ce = *va_arg(args, zend_class_entry**); zval *retval = va_arg(args, zval*), member; if (hash_key->arKey[0] == '\0') { return 0; /* non public cannot be dynamic */ } ZVAL_STRINGL(&member, hash_key->arKey, hash_key->nKeyLength-1, 0); if (zend_get_property_info(ce, &member, 1 TSRMLS_CC) == &EG(std_property_info)) { MAKE_STD_ZVAL(property); EG(std_property_info).flags = ZEND_ACC_IMPLICIT_PUBLIC; reflection_property_factory(ce, &EG(std_property_info), property TSRMLS_CC); add_next_index_zval(retval, property); } return 0; } /* }}} */ /* {{{ proto public ReflectionProperty[] ReflectionClass::getProperties([long $filter]) Returns an array of this class' properties */ ZEND_METHOD(reflection_class, getProperties) { reflection_object *intern; zend_class_entry *ce; long filter = 0; int argc = ZEND_NUM_ARGS(); METHOD_NOTSTATIC(reflection_class_ptr); if (argc) { if (zend_parse_parameters(argc TSRMLS_CC, "|l", &filter) == FAILURE) { return; } } else { /* No parameters given, default to "return all" */ filter = ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC; } GET_REFLECTION_OBJECT_PTR(ce); array_init(return_value); zend_hash_apply_with_arguments(&ce->properties_info TSRMLS_CC, (apply_func_args_t) _addproperty, 3, &ce, return_value, filter); if (intern->obj && (filter & ZEND_ACC_PUBLIC) != 0 && Z_OBJ_HT_P(intern->obj)->get_properties) { HashTable *properties = Z_OBJ_HT_P(intern->obj)->get_properties(intern->obj TSRMLS_CC); zend_hash_apply_with_arguments(properties TSRMLS_CC, (apply_func_args_t) _adddynproperty, 2, &ce, return_value); } } /* }}} */ /* {{{ proto public bool ReflectionClass::hasConstant(string name) Returns whether a constant exists or not */ ZEND_METHOD(reflection_class, hasConstant) { reflection_object *intern; zend_class_entry *ce; char *name; int name_len; METHOD_NOTSTATIC(reflection_class_ptr); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); if (zend_hash_exists(&ce->constants_table, name, name_len + 1)) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto public array ReflectionClass::getConstants() Returns an associative array containing this class' constants and their values */ ZEND_METHOD(reflection_class, getConstants) { zval *tmp_copy; reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); array_init(return_value); zend_hash_apply_with_argument(&ce->constants_table, (apply_func_arg_t)zval_update_constant_inline_change, ce TSRMLS_CC); zend_hash_copy(Z_ARRVAL_P(return_value), &ce->constants_table, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_copy, sizeof(zval *)); } /* }}} */ /* {{{ proto public mixed ReflectionClass::getConstant(string name) Returns the class' constant specified by its name */ ZEND_METHOD(reflection_class, getConstant) { reflection_object *intern; zend_class_entry *ce; zval **value; char *name; int name_len; METHOD_NOTSTATIC(reflection_class_ptr); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); zend_hash_apply_with_argument(&ce->constants_table, (apply_func_arg_t)zval_update_constant_inline_change, ce TSRMLS_CC); if (zend_hash_find(&ce->constants_table, name, name_len + 1, (void **) &value) == FAILURE) { RETURN_FALSE; } MAKE_COPY_ZVAL(value, return_value); } /* }}} */ /* {{{ _class_check_flag */ static void _class_check_flag(INTERNAL_FUNCTION_PARAMETERS, int mask) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); RETVAL_BOOL(ce->ce_flags & mask); } /* }}} */ /* {{{ proto public bool ReflectionClass::isInstantiable() Returns whether this class is instantiable */ ZEND_METHOD(reflection_class, isInstantiable) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); if (ce->ce_flags & (ZEND_ACC_INTERFACE | ZEND_ACC_EXPLICIT_ABSTRACT_CLASS | ZEND_ACC_IMPLICIT_ABSTRACT_CLASS)) { RETURN_FALSE; } /* Basically, the class is instantiable. Though, if there is a constructor * and it is not publicly accessible, it isn't! */ if (!ce->constructor) { RETURN_TRUE; } RETURN_BOOL(ce->constructor->common.fn_flags & ZEND_ACC_PUBLIC); } /* }}} */ /* {{{ proto public bool ReflectionClass::isCloneable() Returns whether this class is cloneable */ ZEND_METHOD(reflection_class, isCloneable) { reflection_object *intern; zend_class_entry *ce; zval obj; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); if (ce->ce_flags & (ZEND_ACC_INTERFACE | ZEND_ACC_TRAIT | ZEND_ACC_EXPLICIT_ABSTRACT_CLASS | ZEND_ACC_IMPLICIT_ABSTRACT_CLASS)) { RETURN_FALSE; } if (intern->obj) { if (ce->clone) { RETURN_BOOL(ce->clone->common.fn_flags & ZEND_ACC_PUBLIC); } else { RETURN_BOOL(Z_OBJ_HANDLER_P(intern->obj, clone_obj) != NULL); } } else { if (ce->clone) { RETURN_BOOL(ce->clone->common.fn_flags & ZEND_ACC_PUBLIC); } else { object_init_ex(&obj, ce); RETVAL_BOOL(Z_OBJ_HANDLER(obj, clone_obj) != NULL); zval_dtor(&obj); } } } /* }}} */ /* {{{ proto public bool ReflectionClass::isInterface() Returns whether this is an interface or a class */ ZEND_METHOD(reflection_class, isInterface) { _class_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_INTERFACE); } /* }}} */ /* {{{ proto public bool ReflectionClass::isTrait() Returns whether this is a trait */ ZEND_METHOD(reflection_class, isTrait) { _class_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_TRAIT & ~ZEND_ACC_EXPLICIT_ABSTRACT_CLASS); } /* }}} */ /* {{{ proto public bool ReflectionClass::isFinal() Returns whether this class is final */ ZEND_METHOD(reflection_class, isFinal) { _class_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_FINAL_CLASS); } /* }}} */ /* {{{ proto public bool ReflectionClass::isAbstract() Returns whether this class is abstract */ ZEND_METHOD(reflection_class, isAbstract) { _class_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_IMPLICIT_ABSTRACT_CLASS|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS); } /* }}} */ /* {{{ proto public int ReflectionClass::getModifiers() Returns a bitfield of the access modifiers for this class */ ZEND_METHOD(reflection_class, getModifiers) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); RETURN_LONG(ce->ce_flags); } /* }}} */ /* {{{ proto public bool ReflectionClass::isInstance(stdclass object) Returns whether the given object is an instance of this class */ ZEND_METHOD(reflection_class, isInstance) { reflection_object *intern; zend_class_entry *ce; zval *object; METHOD_NOTSTATIC(reflection_class_ptr); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "o", &object) == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); RETURN_BOOL(HAS_CLASS_ENTRY(*object) && instanceof_function(Z_OBJCE_P(object), ce TSRMLS_CC)); } /* }}} */ /* {{{ proto public stdclass ReflectionClass::newInstance(mixed* args, ...) Returns an instance of this class */ ZEND_METHOD(reflection_class, newInstance) { zval *retval_ptr = NULL; reflection_object *intern; zend_class_entry *ce; METHOD_NOTSTATIC(reflection_class_ptr); GET_REFLECTION_OBJECT_PTR(ce); /* Run the constructor if there is one */ if (ce->constructor) { zval ***params = NULL; int num_args = 0; zend_fcall_info fci; zend_fcall_info_cache fcc; if (!(ce->constructor->common.fn_flags & ZEND_ACC_PUBLIC)) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Access to non-public constructor of class %s", ce->name); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "*", &params, &num_args) == FAILURE) { if (params) { efree(params); } RETURN_FALSE; } object_init_ex(return_value, ce); fci.size = sizeof(fci); fci.function_table = EG(function_table); fci.function_name = NULL; fci.symbol_table = NULL; fci.object_ptr = return_value; fci.retval_ptr_ptr = &retval_ptr; fci.param_count = num_args; fci.params = params; fci.no_separation = 1; fcc.initialized = 1; fcc.function_handler = ce->constructor; fcc.calling_scope = EG(scope); fcc.called_scope = Z_OBJCE_P(return_value); fcc.object_ptr = return_value; if (zend_call_function(&fci, &fcc TSRMLS_CC) == FAILURE) { if (params) { efree(params); } if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invocation of %s's constructor failed", ce->name); RETURN_NULL(); } if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } if (params) { efree(params); } } else if (!ZEND_NUM_ARGS()) { object_init_ex(return_value, ce); } else { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Class %s does not have a constructor, so you cannot pass any constructor arguments", ce->name); } } /* }}} */ /* {{{ proto public stdclass ReflectionClass::newInstanceWithoutConstructor() Returns an instance of this class without invoking its constructor */ ZEND_METHOD(reflection_class, newInstanceWithoutConstructor) { reflection_object *intern; zend_class_entry *ce; METHOD_NOTSTATIC(reflection_class_ptr); GET_REFLECTION_OBJECT_PTR(ce); if (ce->create_object != NULL) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Class %s is an internal class that cannot be instantiated without invoking its constructor", ce->name); } object_init_ex(return_value, ce); } /* }}} */ /* {{{ proto public stdclass ReflectionClass::newInstanceArgs([array args]) Returns an instance of this class */ ZEND_METHOD(reflection_class, newInstanceArgs) { zval *retval_ptr = NULL; reflection_object *intern; zend_class_entry *ce; int argc = 0; HashTable *args; METHOD_NOTSTATIC(reflection_class_ptr); GET_REFLECTION_OBJECT_PTR(ce); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|h", &args) == FAILURE) { return; } if (ZEND_NUM_ARGS() > 0) { argc = args->nNumOfElements; } /* Run the constructor if there is one */ if (ce->constructor) { zval ***params = NULL; zend_fcall_info fci; zend_fcall_info_cache fcc; if (!(ce->constructor->common.fn_flags & ZEND_ACC_PUBLIC)) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Access to non-public constructor of class %s", ce->name); return; } if (argc) { params = safe_emalloc(sizeof(zval **), argc, 0); zend_hash_apply_with_argument(args, (apply_func_arg_t)_zval_array_to_c_array, &params TSRMLS_CC); params -= argc; } object_init_ex(return_value, ce); fci.size = sizeof(fci); fci.function_table = EG(function_table); fci.function_name = NULL; fci.symbol_table = NULL; fci.object_ptr = return_value; fci.retval_ptr_ptr = &retval_ptr; fci.param_count = argc; fci.params = params; fci.no_separation = 1; fcc.initialized = 1; fcc.function_handler = ce->constructor; fcc.calling_scope = EG(scope); fcc.called_scope = Z_OBJCE_P(return_value); fcc.object_ptr = return_value; if (zend_call_function(&fci, &fcc TSRMLS_CC) == FAILURE) { if (params) { efree(params); } if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invocation of %s's constructor failed", ce->name); RETURN_NULL(); } if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } if (params) { efree(params); } } else if (!ZEND_NUM_ARGS() || !argc) { object_init_ex(return_value, ce); } else { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Class %s does not have a constructor, so you cannot pass any constructor arguments", ce->name); } } /* }}} */ /* {{{ proto public ReflectionClass[] ReflectionClass::getInterfaces() Returns an array of interfaces this class implements */ ZEND_METHOD(reflection_class, getInterfaces) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); /* Return an empty array if this class implements no interfaces */ array_init(return_value); if (ce->num_interfaces) { zend_uint i; for (i=0; i < ce->num_interfaces; i++) { zval *interface; ALLOC_ZVAL(interface); zend_reflection_class_factory(ce->interfaces[i], interface TSRMLS_CC); add_assoc_zval_ex(return_value, ce->interfaces[i]->name, ce->interfaces[i]->name_length + 1, interface); } } } /* }}} */ /* {{{ proto public String[] ReflectionClass::getInterfaceNames() Returns an array of names of interfaces this class implements */ ZEND_METHOD(reflection_class, getInterfaceNames) { reflection_object *intern; zend_class_entry *ce; zend_uint i; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); /* Return an empty array if this class implements no interfaces */ array_init(return_value); for (i=0; i < ce->num_interfaces; i++) { add_next_index_stringl(return_value, ce->interfaces[i]->name, ce->interfaces[i]->name_length, 1); } } /* }}} */ /* {{{ proto public ReflectionClass[] ReflectionClass::getTraits() Returns an array of traits used by this class */ ZEND_METHOD(reflection_class, getTraits) { reflection_object *intern; zend_class_entry *ce; zend_uint i; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); array_init(return_value); for (i=0; i < ce->num_traits; i++) { zval *trait; ALLOC_ZVAL(trait); zend_reflection_class_factory(ce->traits[i], trait TSRMLS_CC); add_assoc_zval_ex(return_value, ce->traits[i]->name, ce->traits[i]->name_length + 1, trait); } } /* }}} */ /* {{{ proto public String[] ReflectionClass::getTraitNames() Returns an array of names of traits used by this class */ ZEND_METHOD(reflection_class, getTraitNames) { reflection_object *intern; zend_class_entry *ce; zend_uint i; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); array_init(return_value); for (i=0; i < ce->num_traits; i++) { add_next_index_stringl(return_value, ce->traits[i]->name, ce->traits[i]->name_length, 1); } } /* }}} */ /* {{{ proto public arra ReflectionClass::getTraitaliases() Returns an array of trait aliases */ ZEND_METHOD(reflection_class, getTraitAliases) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); array_init(return_value); if (ce->trait_aliases) { zend_uint i = 0; while (ce->trait_aliases[i]) { char *method_name; int method_name_len; zend_trait_method_reference *cur_ref = ce->trait_aliases[i]->trait_method; method_name_len = spprintf(&method_name, 0, "%s::%s", cur_ref->class_name, cur_ref->method_name); add_assoc_stringl_ex(return_value, ce->trait_aliases[i]->alias, ce->trait_aliases[i]->alias_len + 1, method_name, method_name_len, 0); i++; } } } /* }}} */ /* {{{ proto public ReflectionClass ReflectionClass::getParentClass() Returns the class' parent class, or, if none exists, FALSE */ ZEND_METHOD(reflection_class, getParentClass) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ce); if (ce->parent) { zend_reflection_class_factory(ce->parent, return_value TSRMLS_CC); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto public bool ReflectionClass::isSubclassOf(string|ReflectionClass class) Returns whether this class is a subclass of another class */ ZEND_METHOD(reflection_class, isSubclassOf) { reflection_object *intern, *argument; zend_class_entry *ce, **pce, *class_ce; zval *class_name; METHOD_NOTSTATIC(reflection_class_ptr); GET_REFLECTION_OBJECT_PTR(ce); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &class_name) == FAILURE) { return; } switch(class_name->type) { case IS_STRING: if (zend_lookup_class(Z_STRVAL_P(class_name), Z_STRLEN_P(class_name), &pce TSRMLS_CC) == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Class %s does not exist", Z_STRVAL_P(class_name)); return; } class_ce = *pce; break; case IS_OBJECT: if (instanceof_function(Z_OBJCE_P(class_name), reflection_class_ptr TSRMLS_CC)) { argument = (reflection_object *) zend_object_store_get_object(class_name TSRMLS_CC); if (argument == NULL || argument->ptr == NULL) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Internal error: Failed to retrieve the argument's reflection object"); /* Bails out */ } class_ce = argument->ptr; break; } /* no break */ default: zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Parameter one must either be a string or a ReflectionClass object"); return; } RETURN_BOOL((ce != class_ce && instanceof_function(ce, class_ce TSRMLS_CC))); } /* }}} */ /* {{{ proto public bool ReflectionClass::implementsInterface(string|ReflectionClass interface_name) Returns whether this class is a subclass of another class */ ZEND_METHOD(reflection_class, implementsInterface) { reflection_object *intern, *argument; zend_class_entry *ce, *interface_ce, **pce; zval *interface; METHOD_NOTSTATIC(reflection_class_ptr); GET_REFLECTION_OBJECT_PTR(ce); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &interface) == FAILURE) { return; } switch(interface->type) { case IS_STRING: if (zend_lookup_class(Z_STRVAL_P(interface), Z_STRLEN_P(interface), &pce TSRMLS_CC) == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Interface %s does not exist", Z_STRVAL_P(interface)); return; } interface_ce = *pce; break; case IS_OBJECT: if (instanceof_function(Z_OBJCE_P(interface), reflection_class_ptr TSRMLS_CC)) { argument = (reflection_object *) zend_object_store_get_object(interface TSRMLS_CC); if (argument == NULL || argument->ptr == NULL) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Internal error: Failed to retrieve the argument's reflection object"); /* Bails out */ } interface_ce = argument->ptr; break; } /* no break */ default: zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Parameter one must either be a string or a ReflectionClass object"); return; } if (!(interface_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Interface %s is a Class", interface_ce->name); return; } RETURN_BOOL(instanceof_function(ce, interface_ce TSRMLS_CC)); } /* }}} */ /* {{{ proto public bool ReflectionClass::isIterateable() Returns whether this class is iterateable (can be used inside foreach) */ ZEND_METHOD(reflection_class, isIterateable) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } METHOD_NOTSTATIC(reflection_class_ptr); GET_REFLECTION_OBJECT_PTR(ce); RETURN_BOOL(ce->get_iterator != NULL); } /* }}} */ /* {{{ proto public ReflectionExtension|NULL ReflectionClass::getExtension() Returns NULL or the extension the class belongs to */ ZEND_METHOD(reflection_class, getExtension) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } METHOD_NOTSTATIC(reflection_class_ptr); GET_REFLECTION_OBJECT_PTR(ce); if ((ce->type == ZEND_INTERNAL_CLASS) && ce->info.internal.module) { reflection_extension_factory(return_value, ce->info.internal.module->name TSRMLS_CC); } } /* }}} */ /* {{{ proto public string|false ReflectionClass::getExtensionName() Returns false or the name of the extension the class belongs to */ ZEND_METHOD(reflection_class, getExtensionName) { reflection_object *intern; zend_class_entry *ce; if (zend_parse_parameters_none() == FAILURE) { return; } METHOD_NOTSTATIC(reflection_class_ptr); GET_REFLECTION_OBJECT_PTR(ce); if ((ce->type == ZEND_INTERNAL_CLASS) && ce->info.internal.module) { RETURN_STRING(ce->info.internal.module->name, 1); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto public bool ReflectionClass::inNamespace() Returns whether this class is defined in namespace */ ZEND_METHOD(reflection_class, inNamespace) { zval **name; const char *backslash; if (zend_parse_parameters_none() == FAILURE) { return; } if (zend_hash_find(Z_OBJPROP_P(getThis()), "name", sizeof("name"), (void **) &name) == FAILURE) { RETURN_FALSE; } if (Z_TYPE_PP(name) == IS_STRING && (backslash = zend_memrchr(Z_STRVAL_PP(name), '\\', Z_STRLEN_PP(name))) && backslash > Z_STRVAL_PP(name)) { RETURN_TRUE; } RETURN_FALSE; } /* }}} */ /* {{{ proto public string ReflectionClass::getNamespaceName() Returns the name of namespace where this class is defined */ ZEND_METHOD(reflection_class, getNamespaceName) { zval **name; const char *backslash; if (zend_parse_parameters_none() == FAILURE) { return; } if (zend_hash_find(Z_OBJPROP_P(getThis()), "name", sizeof("name"), (void **) &name) == FAILURE) { RETURN_FALSE; } if (Z_TYPE_PP(name) == IS_STRING && (backslash = zend_memrchr(Z_STRVAL_PP(name), '\\', Z_STRLEN_PP(name))) && backslash > Z_STRVAL_PP(name)) { RETURN_STRINGL(Z_STRVAL_PP(name), backslash - Z_STRVAL_PP(name), 1); } RETURN_EMPTY_STRING(); } /* }}} */ /* {{{ proto public string ReflectionClass::getShortName() Returns the short name of the class (without namespace part) */ ZEND_METHOD(reflection_class, getShortName) { zval **name; const char *backslash; if (zend_parse_parameters_none() == FAILURE) { return; } if (zend_hash_find(Z_OBJPROP_P(getThis()), "name", sizeof("name"), (void **) &name) == FAILURE) { RETURN_FALSE; } if (Z_TYPE_PP(name) == IS_STRING && (backslash = zend_memrchr(Z_STRVAL_PP(name), '\\', Z_STRLEN_PP(name))) && backslash > Z_STRVAL_PP(name)) { RETURN_STRINGL(backslash + 1, Z_STRLEN_PP(name) - (backslash - Z_STRVAL_PP(name) + 1), 1); } RETURN_ZVAL(*name, 1, 0); } /* }}} */ /* {{{ proto public static mixed ReflectionObject::export(mixed argument [, bool return]) throws ReflectionException Exports a reflection object. Returns the output if TRUE is specified for return, printing it otherwise. */ ZEND_METHOD(reflection_object, export) { _reflection_export(INTERNAL_FUNCTION_PARAM_PASSTHRU, reflection_object_ptr, 1); } /* }}} */ /* {{{ proto public void ReflectionObject::__construct(mixed argument) throws ReflectionException Constructor. Takes an instance as an argument */ ZEND_METHOD(reflection_object, __construct) { reflection_class_object_ctor(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto public static mixed ReflectionProperty::export(mixed class, string name [, bool return]) throws ReflectionException Exports a reflection object. Returns the output if TRUE is specified for return, printing it otherwise. */ ZEND_METHOD(reflection_property, export) { _reflection_export(INTERNAL_FUNCTION_PARAM_PASSTHRU, reflection_property_ptr, 2); } /* }}} */ /* {{{ proto public void ReflectionProperty::__construct(mixed class, string name) Constructor. Throws an Exception in case the given property does not exist */ ZEND_METHOD(reflection_property, __construct) { zval *propname, *classname; char *name_str; const char *class_name, *prop_name; int name_len, dynam_prop = 0; zval *object; reflection_object *intern; zend_class_entry **pce; zend_class_entry *ce; zend_property_info *property_info = NULL; property_reference *reference; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zs", &classname, &name_str, &name_len) == FAILURE) { return; } object = getThis(); intern = (reflection_object *) zend_object_store_get_object(object TSRMLS_CC); if (intern == NULL) { return; } /* Find the class entry */ switch (Z_TYPE_P(classname)) { case IS_STRING: if (zend_lookup_class(Z_STRVAL_P(classname), Z_STRLEN_P(classname), &pce TSRMLS_CC) == FAILURE) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Class %s does not exist", Z_STRVAL_P(classname)); return; } ce = *pce; break; case IS_OBJECT: ce = Z_OBJCE_P(classname); break; default: _DO_THROW("The parameter class is expected to be either a string or an object"); /* returns out of this function */ } if (zend_hash_find(&ce->properties_info, name_str, name_len + 1, (void **) &property_info) == FAILURE || (property_info->flags & ZEND_ACC_SHADOW)) { /* Check for dynamic properties */ if (property_info == NULL && Z_TYPE_P(classname) == IS_OBJECT && Z_OBJ_HT_P(classname)->get_properties) { if (zend_hash_exists(Z_OBJ_HT_P(classname)->get_properties(classname TSRMLS_CC), name_str, name_len+1)) { dynam_prop = 1; } } if (dynam_prop == 0) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Property %s::$%s does not exist", ce->name, name_str); return; } } if (dynam_prop == 0 && (property_info->flags & ZEND_ACC_PRIVATE) == 0) { /* we have to search the class hierarchy for this (implicit) public or protected property */ zend_class_entry *tmp_ce = ce; zend_property_info *tmp_info; while (tmp_ce && zend_hash_find(&tmp_ce->properties_info, name_str, name_len + 1, (void **) &tmp_info) != SUCCESS) { ce = tmp_ce; property_info = tmp_info; tmp_ce = tmp_ce->parent; } } MAKE_STD_ZVAL(classname); MAKE_STD_ZVAL(propname); if (dynam_prop == 0) { zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name, &prop_name); ZVAL_STRINGL(classname, property_info->ce->name, property_info->ce->name_length, 1); ZVAL_STRING(propname, prop_name, 1); } else { ZVAL_STRINGL(classname, ce->name, ce->name_length, 1); ZVAL_STRINGL(propname, name_str, name_len, 1); } reflection_update_property(object, "class", classname); reflection_update_property(object, "name", propname); reference = (property_reference*) emalloc(sizeof(property_reference)); if (dynam_prop) { reference->prop.flags = ZEND_ACC_IMPLICIT_PUBLIC; reference->prop.name = Z_STRVAL_P(propname); reference->prop.name_length = Z_STRLEN_P(propname); reference->prop.h = zend_get_hash_value(name_str, name_len+1); reference->prop.doc_comment = NULL; reference->prop.ce = ce; } else { reference->prop = *property_info; } reference->ce = ce; intern->ptr = reference; intern->ref_type = REF_TYPE_PROPERTY; intern->ce = ce; intern->ignore_visibility = 0; } /* }}} */ /* {{{ proto public string ReflectionProperty::__toString() Returns a string representation */ ZEND_METHOD(reflection_property, __toString) { reflection_object *intern; property_reference *ref; string str; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ref); string_init(&str); _property_string(&str, &ref->prop, NULL, "" TSRMLS_CC); RETURN_STRINGL(str.string, str.len - 1, 0); } /* }}} */ /* {{{ proto public string ReflectionProperty::getName() Returns the class' name */ ZEND_METHOD(reflection_property, getName) { if (zend_parse_parameters_none() == FAILURE) { return; } _default_get_entry(getThis(), "name", sizeof("name"), return_value TSRMLS_CC); } /* }}} */ static void _property_check_flag(INTERNAL_FUNCTION_PARAMETERS, int mask) /* {{{ */ { reflection_object *intern; property_reference *ref; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ref); RETURN_BOOL(ref->prop.flags & mask); } /* }}} */ /* {{{ proto public bool ReflectionProperty::isPublic() Returns whether this property is public */ ZEND_METHOD(reflection_property, isPublic) { _property_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_PUBLIC | ZEND_ACC_IMPLICIT_PUBLIC); } /* }}} */ /* {{{ proto public bool ReflectionProperty::isPrivate() Returns whether this property is private */ ZEND_METHOD(reflection_property, isPrivate) { _property_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_PRIVATE); } /* }}} */ /* {{{ proto public bool ReflectionProperty::isProtected() Returns whether this property is protected */ ZEND_METHOD(reflection_property, isProtected) { _property_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_PROTECTED); } /* }}} */ /* {{{ proto public bool ReflectionProperty::isStatic() Returns whether this property is static */ ZEND_METHOD(reflection_property, isStatic) { _property_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ZEND_ACC_STATIC); } /* }}} */ /* {{{ proto public bool ReflectionProperty::isDefault() Returns whether this property is default (declared at compilation time). */ ZEND_METHOD(reflection_property, isDefault) { _property_check_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, ~ZEND_ACC_IMPLICIT_PUBLIC); } /* }}} */ /* {{{ proto public int ReflectionProperty::getModifiers() Returns a bitfield of the access modifiers for this property */ ZEND_METHOD(reflection_property, getModifiers) { reflection_object *intern; property_reference *ref; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ref); RETURN_LONG(ref->prop.flags); } /* }}} */ /* {{{ proto public mixed ReflectionProperty::getValue([stdclass object]) Returns this property's value */ ZEND_METHOD(reflection_property, getValue) { reflection_object *intern; property_reference *ref; zval *object, name; zval *member_p = NULL; METHOD_NOTSTATIC(reflection_property_ptr); GET_REFLECTION_OBJECT_PTR(ref); if (!(ref->prop.flags & (ZEND_ACC_PUBLIC | ZEND_ACC_IMPLICIT_PUBLIC)) && intern->ignore_visibility == 0) { _default_get_entry(getThis(), "name", sizeof("name"), &name TSRMLS_CC); zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Cannot access non-public member %s::%s", intern->ce->name, Z_STRVAL(name)); zval_dtor(&name); return; } if ((ref->prop.flags & ZEND_ACC_STATIC)) { zend_update_class_constants(intern->ce TSRMLS_CC); if (!CE_STATIC_MEMBERS(intern->ce)[ref->prop.offset]) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Internal error: Could not find the property %s::%s", intern->ce->name, ref->prop.name); /* Bails out */ } *return_value= *CE_STATIC_MEMBERS(intern->ce)[ref->prop.offset]; zval_copy_ctor(return_value); INIT_PZVAL(return_value); } else { const char *class_name, *prop_name; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "o", &object) == FAILURE) { return; } zend_unmangle_property_name(ref->prop.name, ref->prop.name_length, &class_name, &prop_name); member_p = zend_read_property(ref->ce, object, prop_name, strlen(prop_name), 1 TSRMLS_CC); MAKE_COPY_ZVAL(&member_p, return_value); if (member_p != EG(uninitialized_zval_ptr)) { zval_add_ref(&member_p); zval_ptr_dtor(&member_p); } } } /* }}} */ /* {{{ proto public void ReflectionProperty::setValue([stdclass object,] mixed value) Sets this property's value */ ZEND_METHOD(reflection_property, setValue) { reflection_object *intern; property_reference *ref; zval **variable_ptr; zval *object, name; zval *value; zval *tmp; METHOD_NOTSTATIC(reflection_property_ptr); GET_REFLECTION_OBJECT_PTR(ref); if (!(ref->prop.flags & ZEND_ACC_PUBLIC) && intern->ignore_visibility == 0) { _default_get_entry(getThis(), "name", sizeof("name"), &name TSRMLS_CC); zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Cannot access non-public member %s::%s", intern->ce->name, Z_STRVAL(name)); zval_dtor(&name); return; } if ((ref->prop.flags & ZEND_ACC_STATIC)) { if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "z", &value) == FAILURE) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &tmp, &value) == FAILURE) { return; } } zend_update_class_constants(intern->ce TSRMLS_CC); if (!CE_STATIC_MEMBERS(intern->ce)[ref->prop.offset]) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Internal error: Could not find the property %s::%s", intern->ce->name, ref->prop.name); /* Bails out */ } variable_ptr = &CE_STATIC_MEMBERS(intern->ce)[ref->prop.offset]; if (*variable_ptr != value) { if (PZVAL_IS_REF(*variable_ptr)) { zval garbage = **variable_ptr; /* old value should be destroyed */ /* To check: can't *variable_ptr be some system variable like error_zval here? */ Z_TYPE_PP(variable_ptr) = Z_TYPE_P(value); (*variable_ptr)->value = value->value; if (Z_REFCOUNT_P(value) > 0) { zval_copy_ctor(*variable_ptr); } zval_dtor(&garbage); } else { zval *garbage = *variable_ptr; /* if we assign referenced variable, we should separate it */ Z_ADDREF_P(value); if (PZVAL_IS_REF(value)) { SEPARATE_ZVAL(&value); } *variable_ptr = value; zval_ptr_dtor(&garbage); } } } else { const char *class_name, *prop_name; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "oz", &object, &value) == FAILURE) { return; } zend_unmangle_property_name(ref->prop.name, ref->prop.name_length, &class_name, &prop_name); zend_update_property(ref->ce, object, prop_name, strlen(prop_name), value TSRMLS_CC); } } /* }}} */ /* {{{ proto public ReflectionClass ReflectionProperty::getDeclaringClass() Get the declaring class */ ZEND_METHOD(reflection_property, getDeclaringClass) { reflection_object *intern; property_reference *ref; zend_class_entry *tmp_ce, *ce; zend_property_info *tmp_info; const char *prop_name, *class_name; int prop_name_len; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ref); if (zend_unmangle_property_name(ref->prop.name, ref->prop.name_length, &class_name, &prop_name) != SUCCESS) { RETURN_FALSE; } prop_name_len = strlen(prop_name); ce = tmp_ce = ref->ce; while (tmp_ce && zend_hash_find(&tmp_ce->properties_info, prop_name, prop_name_len + 1, (void **) &tmp_info) == SUCCESS) { if (tmp_info->flags & ZEND_ACC_PRIVATE || tmp_info->flags & ZEND_ACC_SHADOW) { /* it's a private property, so it can't be inherited */ break; } ce = tmp_ce; if (tmp_ce == tmp_info->ce) { /* declared in this class, done */ break; } tmp_ce = tmp_ce->parent; } zend_reflection_class_factory(ce, return_value TSRMLS_CC); } /* }}} */ /* {{{ proto public string ReflectionProperty::getDocComment() Returns the doc comment for this property */ ZEND_METHOD(reflection_property, getDocComment) { reflection_object *intern; property_reference *ref; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(ref); if (ref->prop.doc_comment) { RETURN_STRINGL(ref->prop.doc_comment, ref->prop.doc_comment_len, 1); } RETURN_FALSE; } /* }}} */ /* {{{ proto public int ReflectionProperty::setAccessible(bool visible) Sets whether non-public properties can be requested */ ZEND_METHOD(reflection_property, setAccessible) { reflection_object *intern; zend_bool visible; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "b", &visible) == FAILURE) { return; } intern = (reflection_object *) zend_object_store_get_object(getThis() TSRMLS_CC); if (intern == NULL) { return; } intern->ignore_visibility = visible; } /* }}} */ /* {{{ proto public static mixed ReflectionExtension::export(string name [, bool return]) throws ReflectionException Exports a reflection object. Returns the output if TRUE is specified for return, printing it otherwise. */ ZEND_METHOD(reflection_extension, export) { _reflection_export(INTERNAL_FUNCTION_PARAM_PASSTHRU, reflection_extension_ptr, 1); } /* }}} */ /* {{{ proto public void ReflectionExtension::__construct(string name) Constructor. Throws an Exception in case the given extension does not exist */ ZEND_METHOD(reflection_extension, __construct) { zval *name; zval *object; char *lcname; reflection_object *intern; zend_module_entry *module; char *name_str; int name_len; ALLOCA_FLAG(use_heap) if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name_str, &name_len) == FAILURE) { return; } object = getThis(); intern = (reflection_object *) zend_object_store_get_object(object TSRMLS_CC); if (intern == NULL) { return; } lcname = do_alloca(name_len + 1, use_heap); zend_str_tolower_copy(lcname, name_str, name_len); if (zend_hash_find(&module_registry, lcname, name_len + 1, (void **)&module) == FAILURE) { free_alloca(lcname, use_heap); zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Extension %s does not exist", name_str); return; } free_alloca(lcname, use_heap); MAKE_STD_ZVAL(name); ZVAL_STRING(name, module->name, 1); reflection_update_property( object, "name", name); intern->ptr = module; intern->ref_type = REF_TYPE_OTHER; intern->ce = NULL; } /* }}} */ /* {{{ proto public string ReflectionExtension::__toString() Returns a string representation */ ZEND_METHOD(reflection_extension, __toString) { reflection_object *intern; zend_module_entry *module; string str; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(module); string_init(&str); _extension_string(&str, module, "" TSRMLS_CC); RETURN_STRINGL(str.string, str.len - 1, 0); } /* }}} */ /* {{{ proto public string ReflectionExtension::getName() Returns this extension's name */ ZEND_METHOD(reflection_extension, getName) { if (zend_parse_parameters_none() == FAILURE) { return; } _default_get_entry(getThis(), "name", sizeof("name"), return_value TSRMLS_CC); } /* }}} */ /* {{{ proto public string ReflectionExtension::getVersion() Returns this extension's version */ ZEND_METHOD(reflection_extension, getVersion) { reflection_object *intern; zend_module_entry *module; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(module); /* An extension does not necessarily have a version number */ if (module->version == NO_VERSION_YET) { RETURN_NULL(); } else { RETURN_STRING(module->version, 1); } } /* }}} */ /* {{{ proto public ReflectionFunction[] ReflectionExtension::getFunctions() Returns an array of this extension's fuctions */ ZEND_METHOD(reflection_extension, getFunctions) { reflection_object *intern; zend_module_entry *module; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(module); array_init(return_value); if (module->functions) { zval *function; zend_function *fptr; const zend_function_entry *func = module->functions; /* Is there a better way of doing this? */ while (func->fname) { int fname_len = strlen(func->fname); char *lc_name = zend_str_tolower_dup(func->fname, fname_len); if (zend_hash_find(EG(function_table), lc_name, fname_len + 1, (void**) &fptr) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Internal error: Cannot find extension function %s in global function table", func->fname); func++; efree(lc_name); continue; } ALLOC_ZVAL(function); reflection_function_factory(fptr, NULL, function TSRMLS_CC); add_assoc_zval_ex(return_value, func->fname, fname_len+1, function); func++; efree(lc_name); } } } /* }}} */ static int _addconstant(zend_constant *constant TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zval *const_val; zval *retval = va_arg(args, zval*); int number = va_arg(args, int); if (number == constant->module_number) { ALLOC_ZVAL(const_val); *const_val = constant->value; zval_copy_ctor(const_val); INIT_PZVAL(const_val); add_assoc_zval_ex(retval, constant->name, constant->name_len, const_val); } return 0; } /* }}} */ /* {{{ proto public array ReflectionExtension::getConstants() Returns an associative array containing this extension's constants and their values */ ZEND_METHOD(reflection_extension, getConstants) { reflection_object *intern; zend_module_entry *module; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(module); array_init(return_value); zend_hash_apply_with_arguments(EG(zend_constants) TSRMLS_CC, (apply_func_args_t) _addconstant, 2, return_value, module->module_number); } /* }}} */ /* {{{ _addinientry */ static int _addinientry(zend_ini_entry *ini_entry TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) { zval *retval = va_arg(args, zval*); int number = va_arg(args, int); if (number == ini_entry->module_number) { if (ini_entry->value) { add_assoc_stringl(retval, ini_entry->name, ini_entry->value, ini_entry->value_length, 1); } else { add_assoc_null(retval, ini_entry->name); } } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* {{{ proto public array ReflectionExtension::getINIEntries() Returns an associative array containing this extension's INI entries and their values */ ZEND_METHOD(reflection_extension, getINIEntries) { reflection_object *intern; zend_module_entry *module; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(module); array_init(return_value); zend_hash_apply_with_arguments(EG(ini_directives) TSRMLS_CC, (apply_func_args_t) _addinientry, 2, return_value, module->module_number); } /* }}} */ /* {{{ add_extension_class */ static int add_extension_class(zend_class_entry **pce TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) { zval *class_array = va_arg(args, zval*), *zclass; struct _zend_module_entry *module = va_arg(args, struct _zend_module_entry*); int add_reflection_class = va_arg(args, int); if (((*pce)->type == ZEND_INTERNAL_CLASS) && (*pce)->info.internal.module && !strcasecmp((*pce)->info.internal.module->name, module->name)) { if (add_reflection_class) { ALLOC_ZVAL(zclass); zend_reflection_class_factory(*pce, zclass TSRMLS_CC); add_assoc_zval_ex(class_array, (*pce)->name, (*pce)->name_length + 1, zclass); } else { add_next_index_stringl(class_array, (*pce)->name, (*pce)->name_length, 1); } } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* {{{ proto public ReflectionClass[] ReflectionExtension::getClasses() Returns an array containing ReflectionClass objects for all classes of this extension */ ZEND_METHOD(reflection_extension, getClasses) { reflection_object *intern; zend_module_entry *module; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(module); array_init(return_value); zend_hash_apply_with_arguments(EG(class_table) TSRMLS_CC, (apply_func_args_t) add_extension_class, 3, return_value, module, 1); } /* }}} */ /* {{{ proto public array ReflectionExtension::getClassNames() Returns an array containing all names of all classes of this extension */ ZEND_METHOD(reflection_extension, getClassNames) { reflection_object *intern; zend_module_entry *module; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(module); array_init(return_value); zend_hash_apply_with_arguments(EG(class_table) TSRMLS_CC, (apply_func_args_t) add_extension_class, 3, return_value, module, 0); } /* }}} */ /* {{{ proto public array ReflectionExtension::getDependencies() Returns an array containing all names of all extensions this extension depends on */ ZEND_METHOD(reflection_extension, getDependencies) { reflection_object *intern; zend_module_entry *module; const zend_module_dep *dep; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(module); array_init(return_value); dep = module->deps; if (!dep) { return; } while(dep->name) { char *relation; char *rel_type; int len; switch(dep->type) { case MODULE_DEP_REQUIRED: rel_type = "Required"; break; case MODULE_DEP_CONFLICTS: rel_type = "Conflicts"; break; case MODULE_DEP_OPTIONAL: rel_type = "Optional"; break; default: rel_type = "Error"; /* shouldn't happen */ break; } len = spprintf(&relation, 0, "%s%s%s%s%s", rel_type, dep->rel ? " " : "", dep->rel ? dep->rel : "", dep->version ? " " : "", dep->version ? dep->version : ""); add_assoc_stringl(return_value, dep->name, relation, len, 0); dep++; } } /* }}} */ /* {{{ proto public void ReflectionExtension::info() Prints phpinfo block for the extension */ ZEND_METHOD(reflection_extension, info) { reflection_object *intern; zend_module_entry *module; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(module); php_info_print_module(module TSRMLS_CC); } /* }}} */ /* {{{ proto public bool ReflectionExtension::isPersistent() Returns whether this extension is persistent */ ZEND_METHOD(reflection_extension, isPersistent) { reflection_object *intern; zend_module_entry *module; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(module); RETURN_BOOL(module->type == MODULE_PERSISTENT); } /* }}} */ /* {{{ proto public bool ReflectionExtension::isTemporary() Returns whether this extension is temporary */ ZEND_METHOD(reflection_extension, isTemporary) { reflection_object *intern; zend_module_entry *module; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(module); RETURN_BOOL(module->type == MODULE_TEMPORARY); } /* }}} */ /* {{{ proto public static mixed ReflectionZendExtension::export(string name [, bool return]) throws ReflectionException * Exports a reflection object. Returns the output if TRUE is specified for return, printing it otherwise. */ ZEND_METHOD(reflection_zend_extension, export) { _reflection_export(INTERNAL_FUNCTION_PARAM_PASSTHRU, reflection_zend_extension_ptr, 1); } /* }}} */ /* {{{ proto public void ReflectionZendExtension::__construct(string name) Constructor. Throws an Exception in case the given Zend extension does not exist */ ZEND_METHOD(reflection_zend_extension, __construct) { zval *name; zval *object; reflection_object *intern; zend_extension *extension; char *name_str; int name_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name_str, &name_len) == FAILURE) { return; } object = getThis(); intern = (reflection_object *) zend_object_store_get_object(object TSRMLS_CC); if (intern == NULL) { return; } extension = zend_get_extension(name_str); if (!extension) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Zend Extension %s does not exist", name_str); return; } MAKE_STD_ZVAL(name); ZVAL_STRING(name, extension->name, 1); reflection_update_property(object, "name", name); intern->ptr = extension; intern->ref_type = REF_TYPE_OTHER; intern->ce = NULL; } /* }}} */ /* {{{ proto public string ReflectionZendExtension::__toString() Returns a string representation */ ZEND_METHOD(reflection_zend_extension, __toString) { reflection_object *intern; zend_extension *extension; string str; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(extension); string_init(&str); _zend_extension_string(&str, extension, "" TSRMLS_CC); RETURN_STRINGL(str.string, str.len - 1, 0); } /* }}} */ /* {{{ proto public string ReflectionZendExtension::getName() Returns the name of this Zend extension */ ZEND_METHOD(reflection_zend_extension, getName) { reflection_object *intern; zend_extension *extension; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(extension); RETURN_STRING(extension->name, 1); } /* }}} */ /* {{{ proto public string ReflectionZendExtension::getVersion() Returns the version information of this Zend extension */ ZEND_METHOD(reflection_zend_extension, getVersion) { reflection_object *intern; zend_extension *extension; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(extension); RETURN_STRING(extension->version ? extension->version : "", 1); } /* }}} */ /* {{{ proto public void ReflectionZendExtension::getAuthor() * Returns the name of this Zend extension's author */ ZEND_METHOD(reflection_zend_extension, getAuthor) { reflection_object *intern; zend_extension *extension; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(extension); RETURN_STRING(extension->author ? extension->author : "", 1); } /* }}} */ /* {{{ proto public void ReflectionZendExtension::getURL() Returns this Zend extension's URL*/ ZEND_METHOD(reflection_zend_extension, getURL) { reflection_object *intern; zend_extension *extension; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(extension); RETURN_STRING(extension->URL ? extension->URL : "", 1); } /* }}} */ /* {{{ proto public void ReflectionZendExtension::getCopyright() Returns this Zend extension's copyright information */ ZEND_METHOD(reflection_zend_extension, getCopyright) { reflection_object *intern; zend_extension *extension; if (zend_parse_parameters_none() == FAILURE) { return; } GET_REFLECTION_OBJECT_PTR(extension); RETURN_STRING(extension->copyright ? extension->copyright : "", 1); } /* }}} */ /* {{{ method tables */ static const zend_function_entry reflection_exception_functions[] = { PHP_FE_END }; ZEND_BEGIN_ARG_INFO(arginfo_reflection__void, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_getModifierNames, 0) ZEND_ARG_INFO(0, modifiers) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_export, 0, 0, 1) ZEND_ARG_OBJ_INFO(0, reflector, Reflector, 0) ZEND_ARG_INFO(0, return) ZEND_END_ARG_INFO() static const zend_function_entry reflection_functions[] = { ZEND_ME(reflection, getModifierNames, arginfo_reflection_getModifierNames, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) ZEND_ME(reflection, export, arginfo_reflection_export, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_FE_END }; static const zend_function_entry reflector_functions[] = { ZEND_FENTRY(export, NULL, NULL, ZEND_ACC_STATIC|ZEND_ACC_ABSTRACT|ZEND_ACC_PUBLIC) ZEND_ABSTRACT_ME(reflector, __toString, arginfo_reflection__void) PHP_FE_END }; ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_function_export, 0, 0, 1) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, return) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_function___construct, 0) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_function_invoke, 0, 0, 0) ZEND_ARG_INFO(0, args) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_function_invokeArgs, 0) ZEND_ARG_ARRAY_INFO(0, args, 0) ZEND_END_ARG_INFO() static const zend_function_entry reflection_function_abstract_functions[] = { ZEND_ME(reflection, __clone, arginfo_reflection__void, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL) PHP_ABSTRACT_ME(reflection_function, __toString, arginfo_reflection__void) ZEND_ME(reflection_function, inNamespace, arginfo_reflection__void, 0) ZEND_ME(reflection_function, isClosure, arginfo_reflection__void, 0) ZEND_ME(reflection_function, isDeprecated, arginfo_reflection__void, 0) ZEND_ME(reflection_function, isInternal, arginfo_reflection__void, 0) ZEND_ME(reflection_function, isUserDefined, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getClosureThis, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getClosureScopeClass, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getDocComment, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getEndLine, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getExtension, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getExtensionName, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getFileName, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getName, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getNamespaceName, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getNumberOfParameters, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getNumberOfRequiredParameters, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getParameters, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getShortName, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getStartLine, arginfo_reflection__void, 0) ZEND_ME(reflection_function, getStaticVariables, arginfo_reflection__void, 0) ZEND_ME(reflection_function, returnsReference, arginfo_reflection__void, 0) PHP_FE_END }; static const zend_function_entry reflection_function_functions[] = { ZEND_ME(reflection_function, __construct, arginfo_reflection_function___construct, 0) ZEND_ME(reflection_function, __toString, arginfo_reflection__void, 0) ZEND_ME(reflection_function, export, arginfo_reflection_function_export, ZEND_ACC_STATIC|ZEND_ACC_PUBLIC) ZEND_ME(reflection_function, isDisabled, arginfo_reflection__void, 0) ZEND_ME(reflection_function, invoke, arginfo_reflection_function_invoke, 0) ZEND_ME(reflection_function, invokeArgs, arginfo_reflection_function_invokeArgs, 0) ZEND_ME(reflection_function, getClosure, arginfo_reflection__void, 0) PHP_FE_END }; ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_method_export, 0, 0, 2) ZEND_ARG_INFO(0, class) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, return) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_method___construct, 0, 0, 1) ZEND_ARG_INFO(0, class_or_method) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_method_invoke, 0) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, args) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_method_invokeArgs, 0) ZEND_ARG_INFO(0, object) ZEND_ARG_ARRAY_INFO(0, args, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_method_setAccessible, 0) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_method_getClosure, 0) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() static const zend_function_entry reflection_method_functions[] = { ZEND_ME(reflection_method, export, arginfo_reflection_method_export, ZEND_ACC_STATIC|ZEND_ACC_PUBLIC) ZEND_ME(reflection_method, __construct, arginfo_reflection_method___construct, 0) ZEND_ME(reflection_method, __toString, arginfo_reflection__void, 0) ZEND_ME(reflection_method, isPublic, arginfo_reflection__void, 0) ZEND_ME(reflection_method, isPrivate, arginfo_reflection__void, 0) ZEND_ME(reflection_method, isProtected, arginfo_reflection__void, 0) ZEND_ME(reflection_method, isAbstract, arginfo_reflection__void, 0) ZEND_ME(reflection_method, isFinal, arginfo_reflection__void, 0) ZEND_ME(reflection_method, isStatic, arginfo_reflection__void, 0) ZEND_ME(reflection_method, isConstructor, arginfo_reflection__void, 0) ZEND_ME(reflection_method, isDestructor, arginfo_reflection__void, 0) ZEND_ME(reflection_method, getClosure, arginfo_reflection_method_getClosure, 0) ZEND_ME(reflection_method, getModifiers, arginfo_reflection__void, 0) ZEND_ME(reflection_method, invoke, arginfo_reflection_method_invoke, 0) ZEND_ME(reflection_method, invokeArgs, arginfo_reflection_method_invokeArgs, 0) ZEND_ME(reflection_method, getDeclaringClass, arginfo_reflection__void, 0) ZEND_ME(reflection_method, getPrototype, arginfo_reflection__void, 0) ZEND_ME(reflection_property, setAccessible, arginfo_reflection_method_setAccessible, 0) PHP_FE_END }; ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_class_export, 0, 0, 1) ZEND_ARG_INFO(0, argument) ZEND_ARG_INFO(0, return) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_class___construct, 0) ZEND_ARG_INFO(0, argument) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_class_getStaticPropertyValue, 0, 0, 1) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, default) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_class_setStaticPropertyValue, 0) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_class_hasMethod, 0) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_class_getMethod, 0) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_class_getMethods, 0, 0, 0) ZEND_ARG_INFO(0, filter) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_class_hasProperty, 0) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_class_getProperty, 0) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_class_getProperties, 0, 0, 0) ZEND_ARG_INFO(0, filter) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_class_hasConstant, 0) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_class_getConstant, 0) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_class_isInstance, 0) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_class_newInstance, 0) ZEND_ARG_INFO(0, args) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_class_newInstanceWithoutConstructor, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_class_newInstanceArgs, 0, 0, 0) ZEND_ARG_ARRAY_INFO(0, args, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_class_isSubclassOf, 0) ZEND_ARG_INFO(0, class) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_class_implementsInterface, 0) ZEND_ARG_INFO(0, interface) ZEND_END_ARG_INFO() static const zend_function_entry reflection_class_functions[] = { ZEND_ME(reflection, __clone, arginfo_reflection__void, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL) ZEND_ME(reflection_class, export, arginfo_reflection_class_export, ZEND_ACC_STATIC|ZEND_ACC_PUBLIC) ZEND_ME(reflection_class, __construct, arginfo_reflection_class___construct, 0) ZEND_ME(reflection_class, __toString, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getName, arginfo_reflection__void, 0) ZEND_ME(reflection_class, isInternal, arginfo_reflection__void, 0) ZEND_ME(reflection_class, isUserDefined, arginfo_reflection__void, 0) ZEND_ME(reflection_class, isInstantiable, arginfo_reflection__void, 0) ZEND_ME(reflection_class, isCloneable, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getFileName, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getStartLine, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getEndLine, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getDocComment, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getConstructor, arginfo_reflection__void, 0) ZEND_ME(reflection_class, hasMethod, arginfo_reflection_class_hasMethod, 0) ZEND_ME(reflection_class, getMethod, arginfo_reflection_class_getMethod, 0) ZEND_ME(reflection_class, getMethods, arginfo_reflection_class_getMethods, 0) ZEND_ME(reflection_class, hasProperty, arginfo_reflection_class_hasProperty, 0) ZEND_ME(reflection_class, getProperty, arginfo_reflection_class_getProperty, 0) ZEND_ME(reflection_class, getProperties, arginfo_reflection_class_getProperties, 0) ZEND_ME(reflection_class, hasConstant, arginfo_reflection_class_hasConstant, 0) ZEND_ME(reflection_class, getConstants, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getConstant, arginfo_reflection_class_getConstant, 0) ZEND_ME(reflection_class, getInterfaces, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getInterfaceNames, arginfo_reflection__void, 0) ZEND_ME(reflection_class, isInterface, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getTraits, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getTraitNames, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getTraitAliases, arginfo_reflection__void, 0) ZEND_ME(reflection_class, isTrait, arginfo_reflection__void, 0) ZEND_ME(reflection_class, isAbstract, arginfo_reflection__void, 0) ZEND_ME(reflection_class, isFinal, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getModifiers, arginfo_reflection__void, 0) ZEND_ME(reflection_class, isInstance, arginfo_reflection_class_isInstance, 0) ZEND_ME(reflection_class, newInstance, arginfo_reflection_class_newInstance, 0) ZEND_ME(reflection_class, newInstanceWithoutConstructor, arginfo_reflection_class_newInstanceWithoutConstructor, 0) ZEND_ME(reflection_class, newInstanceArgs, arginfo_reflection_class_newInstanceArgs, 0) ZEND_ME(reflection_class, getParentClass, arginfo_reflection__void, 0) ZEND_ME(reflection_class, isSubclassOf, arginfo_reflection_class_isSubclassOf, 0) ZEND_ME(reflection_class, getStaticProperties, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getStaticPropertyValue, arginfo_reflection_class_getStaticPropertyValue, 0) ZEND_ME(reflection_class, setStaticPropertyValue, arginfo_reflection_class_setStaticPropertyValue, 0) ZEND_ME(reflection_class, getDefaultProperties, arginfo_reflection__void, 0) ZEND_ME(reflection_class, isIterateable, arginfo_reflection__void, 0) ZEND_ME(reflection_class, implementsInterface, arginfo_reflection_class_implementsInterface, 0) ZEND_ME(reflection_class, getExtension, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getExtensionName, arginfo_reflection__void, 0) ZEND_ME(reflection_class, inNamespace, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getNamespaceName, arginfo_reflection__void, 0) ZEND_ME(reflection_class, getShortName, arginfo_reflection__void, 0) PHP_FE_END }; ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_object_export, 0, 0, 1) ZEND_ARG_INFO(0, argument) ZEND_ARG_INFO(0, return) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_object___construct, 0) ZEND_ARG_INFO(0, argument) ZEND_END_ARG_INFO() static const zend_function_entry reflection_object_functions[] = { ZEND_ME(reflection_object, export, arginfo_reflection_object_export, ZEND_ACC_STATIC|ZEND_ACC_PUBLIC) ZEND_ME(reflection_object, __construct, arginfo_reflection_object___construct, 0) PHP_FE_END }; ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_property_export, 0, 0, 2) ZEND_ARG_INFO(0, class) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, return) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_property___construct, 0, 0, 2) ZEND_ARG_INFO(0, class) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_property_getValue, 0, 0, 0) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_property_setValue, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_property_setAccessible, 0) ZEND_ARG_INFO(0, visible) ZEND_END_ARG_INFO() static const zend_function_entry reflection_property_functions[] = { ZEND_ME(reflection, __clone, arginfo_reflection__void, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL) ZEND_ME(reflection_property, export, arginfo_reflection_property_export, ZEND_ACC_STATIC|ZEND_ACC_PUBLIC) ZEND_ME(reflection_property, __construct, arginfo_reflection_property___construct, 0) ZEND_ME(reflection_property, __toString, arginfo_reflection__void, 0) ZEND_ME(reflection_property, getName, arginfo_reflection__void, 0) ZEND_ME(reflection_property, getValue, arginfo_reflection_property_getValue, 0) ZEND_ME(reflection_property, setValue, arginfo_reflection_property_setValue, 0) ZEND_ME(reflection_property, isPublic, arginfo_reflection__void, 0) ZEND_ME(reflection_property, isPrivate, arginfo_reflection__void, 0) ZEND_ME(reflection_property, isProtected, arginfo_reflection__void, 0) ZEND_ME(reflection_property, isStatic, arginfo_reflection__void, 0) ZEND_ME(reflection_property, isDefault, arginfo_reflection__void, 0) ZEND_ME(reflection_property, getModifiers, arginfo_reflection__void, 0) ZEND_ME(reflection_property, getDeclaringClass, arginfo_reflection__void, 0) ZEND_ME(reflection_property, getDocComment, arginfo_reflection__void, 0) ZEND_ME(reflection_property, setAccessible, arginfo_reflection_property_setAccessible, 0) PHP_FE_END }; ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_parameter_export, 0, 0, 2) ZEND_ARG_INFO(0, function) ZEND_ARG_INFO(0, parameter) ZEND_ARG_INFO(0, return) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_parameter___construct, 0) ZEND_ARG_INFO(0, function) ZEND_ARG_INFO(0, parameter) ZEND_END_ARG_INFO() static const zend_function_entry reflection_parameter_functions[] = { ZEND_ME(reflection, __clone, arginfo_reflection__void, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL) ZEND_ME(reflection_parameter, export, arginfo_reflection_parameter_export, ZEND_ACC_STATIC|ZEND_ACC_PUBLIC) ZEND_ME(reflection_parameter, __construct, arginfo_reflection_parameter___construct, 0) ZEND_ME(reflection_parameter, __toString, arginfo_reflection__void, 0) ZEND_ME(reflection_parameter, getName, arginfo_reflection__void, 0) ZEND_ME(reflection_parameter, isPassedByReference, arginfo_reflection__void, 0) ZEND_ME(reflection_parameter, canBePassedByValue, arginfo_reflection__void, 0) ZEND_ME(reflection_parameter, getDeclaringFunction, arginfo_reflection__void, 0) ZEND_ME(reflection_parameter, getDeclaringClass, arginfo_reflection__void, 0) ZEND_ME(reflection_parameter, getClass, arginfo_reflection__void, 0) ZEND_ME(reflection_parameter, isArray, arginfo_reflection__void, 0) ZEND_ME(reflection_parameter, isCallable, arginfo_reflection__void, 0) ZEND_ME(reflection_parameter, allowsNull, arginfo_reflection__void, 0) ZEND_ME(reflection_parameter, getPosition, arginfo_reflection__void, 0) ZEND_ME(reflection_parameter, isOptional, arginfo_reflection__void, 0) ZEND_ME(reflection_parameter, isDefaultValueAvailable, arginfo_reflection__void, 0) ZEND_ME(reflection_parameter, getDefaultValue, arginfo_reflection__void, 0) PHP_FE_END }; ZEND_BEGIN_ARG_INFO_EX(arginfo_reflection_extension_export, 0, 0, 1) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, return) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_reflection_extension___construct, 0) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() static const zend_function_entry reflection_extension_functions[] = { ZEND_ME(reflection, __clone, arginfo_reflection__void, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL) ZEND_ME(reflection_extension, export, arginfo_reflection_extension_export, ZEND_ACC_STATIC|ZEND_ACC_PUBLIC) ZEND_ME(reflection_extension, __construct, arginfo_reflection_extension___construct, 0) ZEND_ME(reflection_extension, __toString, arginfo_reflection__void, 0) ZEND_ME(reflection_extension, getName, arginfo_reflection__void, 0) ZEND_ME(reflection_extension, getVersion, arginfo_reflection__void, 0) ZEND_ME(reflection_extension, getFunctions, arginfo_reflection__void, 0) ZEND_ME(reflection_extension, getConstants, arginfo_reflection__void, 0) ZEND_ME(reflection_extension, getINIEntries, arginfo_reflection__void, 0) ZEND_ME(reflection_extension, getClasses, arginfo_reflection__void, 0) ZEND_ME(reflection_extension, getClassNames, arginfo_reflection__void, 0) ZEND_ME(reflection_extension, getDependencies, arginfo_reflection__void, 0) ZEND_ME(reflection_extension, info, arginfo_reflection__void, 0) ZEND_ME(reflection_extension, isPersistent, arginfo_reflection__void, 0) ZEND_ME(reflection_extension, isTemporary, arginfo_reflection__void, 0) PHP_FE_END }; ZEND_BEGIN_ARG_INFO(arginfo_reflection_zend_extension___construct, 0) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() static const zend_function_entry reflection_zend_extension_functions[] = { ZEND_ME(reflection, __clone, arginfo_reflection__void, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL) ZEND_ME(reflection_zend_extension, export, arginfo_reflection_extension_export, ZEND_ACC_STATIC|ZEND_ACC_PUBLIC) ZEND_ME(reflection_zend_extension, __construct, arginfo_reflection_extension___construct, 0) ZEND_ME(reflection_zend_extension, __toString, arginfo_reflection__void, 0) ZEND_ME(reflection_zend_extension, getName, arginfo_reflection__void, 0) ZEND_ME(reflection_zend_extension, getVersion, arginfo_reflection__void, 0) ZEND_ME(reflection_zend_extension, getAuthor, arginfo_reflection__void, 0) ZEND_ME(reflection_zend_extension, getURL, arginfo_reflection__void, 0) ZEND_ME(reflection_zend_extension, getCopyright, arginfo_reflection__void, 0) PHP_FE_END }; /* }}} */ const zend_function_entry reflection_ext_functions[] = { /* {{{ */ PHP_FE_END }; /* }}} */ static zend_object_handlers *zend_std_obj_handlers; /* {{{ _reflection_write_property */ static void _reflection_write_property(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC) { if ((Z_TYPE_P(member) == IS_STRING) && zend_hash_exists(&Z_OBJCE_P(object)->properties_info, Z_STRVAL_P(member), Z_STRLEN_P(member)+1) && ((Z_STRLEN_P(member) == sizeof("name") - 1 && !memcmp(Z_STRVAL_P(member), "name", sizeof("name"))) || (Z_STRLEN_P(member) == sizeof("class") - 1 && !memcmp(Z_STRVAL_P(member), "class", sizeof("class"))))) { zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, "Cannot set read-only property %s::$%s", Z_OBJCE_P(object)->name, Z_STRVAL_P(member)); } else { zend_std_obj_handlers->write_property(object, member, value, key TSRMLS_CC); } } /* }}} */ PHP_MINIT_FUNCTION(reflection) /* {{{ */ { zend_class_entry _reflection_entry; zend_std_obj_handlers = zend_get_std_object_handlers(); memcpy(&reflection_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); reflection_object_handlers.clone_obj = NULL; reflection_object_handlers.write_property = _reflection_write_property; INIT_CLASS_ENTRY(_reflection_entry, "ReflectionException", reflection_exception_functions); reflection_exception_ptr = zend_register_internal_class_ex(&_reflection_entry, zend_exception_get_default(TSRMLS_C), NULL TSRMLS_CC); INIT_CLASS_ENTRY(_reflection_entry, "Reflection", reflection_functions); reflection_ptr = zend_register_internal_class(&_reflection_entry TSRMLS_CC); INIT_CLASS_ENTRY(_reflection_entry, "Reflector", reflector_functions); reflector_ptr = zend_register_internal_interface(&_reflection_entry TSRMLS_CC); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionFunctionAbstract", reflection_function_abstract_functions); _reflection_entry.create_object = reflection_objects_new; reflection_function_abstract_ptr = zend_register_internal_class(&_reflection_entry TSRMLS_CC); reflection_register_implement(reflection_function_abstract_ptr, reflector_ptr TSRMLS_CC); zend_declare_property_string(reflection_function_abstract_ptr, "name", sizeof("name")-1, "", ZEND_ACC_ABSTRACT TSRMLS_CC); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionFunction", reflection_function_functions); _reflection_entry.create_object = reflection_objects_new; reflection_function_ptr = zend_register_internal_class_ex(&_reflection_entry, reflection_function_abstract_ptr, NULL TSRMLS_CC); zend_declare_property_string(reflection_function_ptr, "name", sizeof("name")-1, "", ZEND_ACC_PUBLIC TSRMLS_CC); REGISTER_REFLECTION_CLASS_CONST_LONG(function, "IS_DEPRECATED", ZEND_ACC_DEPRECATED); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionParameter", reflection_parameter_functions); _reflection_entry.create_object = reflection_objects_new; reflection_parameter_ptr = zend_register_internal_class(&_reflection_entry TSRMLS_CC); reflection_register_implement(reflection_parameter_ptr, reflector_ptr TSRMLS_CC); zend_declare_property_string(reflection_parameter_ptr, "name", sizeof("name")-1, "", ZEND_ACC_PUBLIC TSRMLS_CC); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionMethod", reflection_method_functions); _reflection_entry.create_object = reflection_objects_new; reflection_method_ptr = zend_register_internal_class_ex(&_reflection_entry, reflection_function_abstract_ptr, NULL TSRMLS_CC); zend_declare_property_string(reflection_method_ptr, "name", sizeof("name")-1, "", ZEND_ACC_PUBLIC TSRMLS_CC); zend_declare_property_string(reflection_method_ptr, "class", sizeof("class")-1, "", ZEND_ACC_PUBLIC TSRMLS_CC); REGISTER_REFLECTION_CLASS_CONST_LONG(method, "IS_STATIC", ZEND_ACC_STATIC); REGISTER_REFLECTION_CLASS_CONST_LONG(method, "IS_PUBLIC", ZEND_ACC_PUBLIC); REGISTER_REFLECTION_CLASS_CONST_LONG(method, "IS_PROTECTED", ZEND_ACC_PROTECTED); REGISTER_REFLECTION_CLASS_CONST_LONG(method, "IS_PRIVATE", ZEND_ACC_PRIVATE); REGISTER_REFLECTION_CLASS_CONST_LONG(method, "IS_ABSTRACT", ZEND_ACC_ABSTRACT); REGISTER_REFLECTION_CLASS_CONST_LONG(method, "IS_FINAL", ZEND_ACC_FINAL); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionClass", reflection_class_functions); _reflection_entry.create_object = reflection_objects_new; reflection_class_ptr = zend_register_internal_class(&_reflection_entry TSRMLS_CC); reflection_register_implement(reflection_class_ptr, reflector_ptr TSRMLS_CC); zend_declare_property_string(reflection_class_ptr, "name", sizeof("name")-1, "", ZEND_ACC_PUBLIC TSRMLS_CC); REGISTER_REFLECTION_CLASS_CONST_LONG(class, "IS_IMPLICIT_ABSTRACT", ZEND_ACC_IMPLICIT_ABSTRACT_CLASS); REGISTER_REFLECTION_CLASS_CONST_LONG(class, "IS_EXPLICIT_ABSTRACT", ZEND_ACC_EXPLICIT_ABSTRACT_CLASS); REGISTER_REFLECTION_CLASS_CONST_LONG(class, "IS_FINAL", ZEND_ACC_FINAL_CLASS); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionObject", reflection_object_functions); _reflection_entry.create_object = reflection_objects_new; reflection_object_ptr = zend_register_internal_class_ex(&_reflection_entry, reflection_class_ptr, NULL TSRMLS_CC); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionProperty", reflection_property_functions); _reflection_entry.create_object = reflection_objects_new; reflection_property_ptr = zend_register_internal_class(&_reflection_entry TSRMLS_CC); reflection_register_implement(reflection_property_ptr, reflector_ptr TSRMLS_CC); zend_declare_property_string(reflection_property_ptr, "name", sizeof("name")-1, "", ZEND_ACC_PUBLIC TSRMLS_CC); zend_declare_property_string(reflection_property_ptr, "class", sizeof("class")-1, "", ZEND_ACC_PUBLIC TSRMLS_CC); REGISTER_REFLECTION_CLASS_CONST_LONG(property, "IS_STATIC", ZEND_ACC_STATIC); REGISTER_REFLECTION_CLASS_CONST_LONG(property, "IS_PUBLIC", ZEND_ACC_PUBLIC); REGISTER_REFLECTION_CLASS_CONST_LONG(property, "IS_PROTECTED", ZEND_ACC_PROTECTED); REGISTER_REFLECTION_CLASS_CONST_LONG(property, "IS_PRIVATE", ZEND_ACC_PRIVATE); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionExtension", reflection_extension_functions); _reflection_entry.create_object = reflection_objects_new; reflection_extension_ptr = zend_register_internal_class(&_reflection_entry TSRMLS_CC); reflection_register_implement(reflection_extension_ptr, reflector_ptr TSRMLS_CC); zend_declare_property_string(reflection_extension_ptr, "name", sizeof("name")-1, "", ZEND_ACC_PUBLIC TSRMLS_CC); INIT_CLASS_ENTRY(_reflection_entry, "ReflectionZendExtension", reflection_zend_extension_functions); _reflection_entry.create_object = reflection_objects_new; reflection_zend_extension_ptr = zend_register_internal_class(&_reflection_entry TSRMLS_CC); reflection_register_implement(reflection_zend_extension_ptr, reflector_ptr TSRMLS_CC); zend_declare_property_string(reflection_zend_extension_ptr, "name", sizeof("name")-1, "", ZEND_ACC_PUBLIC TSRMLS_CC); return SUCCESS; } /* }}} */ PHP_MINFO_FUNCTION(reflection) /* {{{ */ { php_info_print_table_start(); php_info_print_table_header(2, "Reflection", "enabled"); php_info_print_table_row(2, "Version", "$Revision$"); php_info_print_table_end(); } /* }}} */ zend_module_entry reflection_module_entry = { /* {{{ */ STANDARD_MODULE_HEADER, "Reflection", reflection_ext_functions, PHP_MINIT(reflection), NULL, NULL, NULL, PHP_MINFO(reflection), "$Revision$", STANDARD_MODULE_PROPERTIES }; /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: * vim600: noet sw=4 ts=4 fdm=marker */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-11-22-ecc6c335c5-b548293b99.c
manybugs_data_88
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.0 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_0.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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Ilia Alshanetsky <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include <magic.h> /* * HOWMANY specifies the maximum offset libmagic will look at * this is currently hardcoded in the libmagic source but not exported */ #ifndef HOWMANY #define HOWMANY 65536 #endif #include "php_ini.h" #include "ext/standard/info.h" #include "ext/standard/file.h" /* needed for context stuff */ #include "php_fileinfo.h" #include "fopen_wrappers.h" /* needed for is_url */ #ifndef _S_IFDIR # define _S_IFDIR S_IFDIR #endif /* {{{ macros and type definitions */ struct php_fileinfo { long options; struct magic_set *magic; }; static zend_object_handlers finfo_object_handlers; zend_class_entry *finfo_class_entry; struct finfo_object { zend_object zo; struct php_fileinfo *ptr; }; #define FILEINFO_DECLARE_INIT_OBJECT(object) \ zval *object = getThis(); #define FILEINFO_REGISTER_OBJECT(_object, _ptr) \ { \ struct finfo_object *obj; \ obj = (struct finfo_object*)zend_object_store_get_object(_object TSRMLS_CC); \ obj->ptr = _ptr; \ } #define FILEINFO_FROM_OBJECT(finfo, object) \ { \ struct finfo_object *obj = zend_object_store_get_object(object TSRMLS_CC); \ finfo = obj->ptr; \ if (!finfo) { \ php_error_docref(NULL TSRMLS_CC, E_WARNING, "The invalid fileinfo object."); \ RETURN_FALSE; \ } \ } /* {{{ finfo_objects_dtor */ static void finfo_objects_dtor(void *object, zend_object_handle handle TSRMLS_DC) { struct finfo_object *intern = (struct finfo_object *) object; if (intern->ptr) { magic_close(intern->ptr->magic); efree(intern->ptr); } zend_object_std_dtor(&intern->zo TSRMLS_CC); efree(intern); } /* }}} */ /* {{{ finfo_objects_new */ PHP_FILEINFO_API zend_object_value finfo_objects_new(zend_class_entry *class_type TSRMLS_DC) { zend_object_value retval; struct finfo_object *intern; intern = emalloc(sizeof(struct finfo_object)); memset(intern, 0, sizeof(struct finfo_object)); zend_object_std_init(&intern->zo, class_type TSRMLS_CC); object_properties_init(&intern->zo, class_type); intern->ptr = NULL; retval.handle = zend_objects_store_put(intern, finfo_objects_dtor, NULL, NULL TSRMLS_CC); retval.handlers = (zend_object_handlers *) &finfo_object_handlers; return retval; } /* }}} */ /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_finfo_open, 0, 0, 0) ZEND_ARG_INFO(0, options) ZEND_ARG_INFO(0, arg) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_finfo_close, 0, 0, 1) ZEND_ARG_INFO(0, finfo) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_finfo_set_flags, 0, 0, 2) ZEND_ARG_INFO(0, finfo) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_finfo_method_set_flags, 0, 0, 1) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_finfo_file, 0, 0, 2) ZEND_ARG_INFO(0, finfo) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, options) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_finfo_method_file, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, options) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_finfo_buffer, 0, 0, 2) ZEND_ARG_INFO(0, finfo) ZEND_ARG_INFO(0, string) ZEND_ARG_INFO(0, options) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_finfo_method_buffer, 0, 0, 1) ZEND_ARG_INFO(0, string) ZEND_ARG_INFO(0, options) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mime_content_type, 0, 0, 1) ZEND_ARG_INFO(0, string) ZEND_END_ARG_INFO() /* }}} */ /* {{{ finfo_class_functions */ zend_function_entry finfo_class_functions[] = { ZEND_ME_MAPPING(finfo, finfo_open, arginfo_finfo_open, ZEND_ACC_PUBLIC) ZEND_ME_MAPPING(set_flags, finfo_set_flags,arginfo_finfo_method_set_flags, ZEND_ACC_PUBLIC) ZEND_ME_MAPPING(file, finfo_file, arginfo_finfo_method_file, ZEND_ACC_PUBLIC) ZEND_ME_MAPPING(buffer, finfo_buffer, arginfo_finfo_method_buffer, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; /* }}} */ #define FINFO_SET_OPTION(magic, options) \ if (magic_setflags(magic, options) == -1) { \ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to set option '%ld' %d:%s", \ options, magic_errno(magic), magic_error(magic)); \ RETURN_FALSE; \ } /* True global resources - no need for thread safety here */ static int le_fileinfo; /* }}} */ void finfo_resource_destructor(zend_rsrc_list_entry *rsrc TSRMLS_DC) /* {{{ */ { if (rsrc->ptr) { struct php_fileinfo *finfo = (struct php_fileinfo *) rsrc->ptr; magic_close(finfo->magic); efree(rsrc->ptr); rsrc->ptr = NULL; } } /* }}} */ /* {{{ fileinfo_functions[] */ zend_function_entry fileinfo_functions[] = { PHP_FE(finfo_open, arginfo_finfo_open) PHP_FE(finfo_close, arginfo_finfo_close) PHP_FE(finfo_set_flags, arginfo_finfo_set_flags) PHP_FE(finfo_file, arginfo_finfo_file) PHP_FE(finfo_buffer, arginfo_finfo_buffer) PHP_FE(mime_content_type, arginfo_mime_content_type) {NULL, NULL, NULL} }; /* }}} */ /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(finfo) { zend_class_entry _finfo_class_entry; INIT_CLASS_ENTRY(_finfo_class_entry, "finfo", finfo_class_functions); _finfo_class_entry.create_object = finfo_objects_new; finfo_class_entry = zend_register_internal_class(&_finfo_class_entry TSRMLS_CC); /* copy the standard object handlers to you handler table */ memcpy(&finfo_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); le_fileinfo = zend_register_list_destructors_ex(finfo_resource_destructor, NULL, "file_info", module_number); REGISTER_LONG_CONSTANT("FILEINFO_NONE", MAGIC_NONE, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILEINFO_SYMLINK", MAGIC_SYMLINK, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILEINFO_MIME", MAGIC_MIME, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILEINFO_MIME_TYPE", MAGIC_MIME_TYPE, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILEINFO_MIME_ENCODING",MAGIC_MIME_ENCODING, CONST_CS|CONST_PERSISTENT); /* REGISTER_LONG_CONSTANT("FILEINFO_COMPRESS", MAGIC_COMPRESS, CONST_CS|CONST_PERSISTENT); disabled, as it does fork now */ REGISTER_LONG_CONSTANT("FILEINFO_DEVICES", MAGIC_DEVICES, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILEINFO_CONTINUE", MAGIC_CONTINUE, CONST_CS|CONST_PERSISTENT); #ifdef MAGIC_PRESERVE_ATIME REGISTER_LONG_CONSTANT("FILEINFO_PRESERVE_ATIME", MAGIC_PRESERVE_ATIME, CONST_CS|CONST_PERSISTENT); #endif #ifdef MAGIC_RAW REGISTER_LONG_CONSTANT("FILEINFO_RAW", MAGIC_RAW, CONST_CS|CONST_PERSISTENT); #endif return SUCCESS; } /* }}} */ /* {{{ fileinfo_module_entry */ zend_module_entry fileinfo_module_entry = { STANDARD_MODULE_HEADER, "fileinfo", fileinfo_functions, PHP_MINIT(finfo), NULL, NULL, NULL, PHP_MINFO(fileinfo), PHP_FILEINFO_VERSION, STANDARD_MODULE_PROPERTIES }; /* }}} */ #ifdef COMPILE_DL_FILEINFO ZEND_GET_MODULE(fileinfo) #endif /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(fileinfo) { php_info_print_table_start(); php_info_print_table_header(2, "fileinfo support", "enabled"); php_info_print_table_row(2, "version", PHP_FILEINFO_VERSION); php_info_print_table_end(); } /* }}} */ /* {{{ proto resource finfo_open([int options [, string arg]]) Create a new fileinfo resource. */ PHP_FUNCTION(finfo_open) { long options = MAGIC_NONE; char *file = NULL; int file_len = 0; struct php_fileinfo *finfo; FILEINFO_DECLARE_INIT_OBJECT(object) char resolved_path[MAXPATHLEN]; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|ls", &options, &file, &file_len) == FAILURE) { RETURN_FALSE; } if (file_len == 0) { file = NULL; } else if (file && *file) { /* user specified file, perform open_basedir checks */ if (!VCWD_REALPATH(file, resolved_path)) { RETURN_FALSE; } file = resolved_path; #if PHP_API_VERSION < 20100412 if ((PG(safe_mode) && (!php_checkuid(file, NULL, CHECKUID_CHECK_FILE_AND_DIR))) || php_check_open_basedir(file TSRMLS_CC)) { #else if (php_check_open_basedir(file TSRMLS_CC)) { #endif RETURN_FALSE; } } finfo = emalloc(sizeof(struct php_fileinfo)); finfo->options = options; finfo->magic = magic_open(options); if (finfo->magic == NULL) { efree(finfo); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid mode '%ld'.", options); RETURN_FALSE; } if (magic_load(finfo->magic, file) == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to load magic database at '%s'.", file); magic_close(finfo->magic); efree(finfo); RETURN_FALSE; } if (object) { FILEINFO_REGISTER_OBJECT(object, finfo); } else { ZEND_REGISTER_RESOURCE(return_value, finfo, le_fileinfo); } } /* }}} */ /* {{{ proto resource finfo_close(resource finfo) Close fileinfo resource. */ PHP_FUNCTION(finfo_close) { struct php_fileinfo *finfo; zval *zfinfo; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zfinfo) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(finfo, struct php_fileinfo *, &zfinfo, -1, "file_info", le_fileinfo); zend_list_delete(Z_RESVAL_P(zfinfo)); RETURN_TRUE; } /* }}} */ /* {{{ proto bool finfo_set_flags(resource finfo, int options) Set libmagic configuration options. */ PHP_FUNCTION(finfo_set_flags) { long options; struct php_fileinfo *finfo; zval *zfinfo; FILEINFO_DECLARE_INIT_OBJECT(object) if (object) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &options) == FAILURE) { RETURN_FALSE; } FILEINFO_FROM_OBJECT(finfo, object); } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &zfinfo, &options) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(finfo, struct php_fileinfo *, &zfinfo, -1, "file_info", le_fileinfo); } FINFO_SET_OPTION(finfo->magic, options) finfo->options = options; RETURN_TRUE; } /* }}} */ #define FILEINFO_MODE_BUFFER 0 #define FILEINFO_MODE_STREAM 1 #define FILEINFO_MODE_FILE 2 static void _php_finfo_get_type(INTERNAL_FUNCTION_PARAMETERS, int mode, int mimetype_emu) /* {{{ */ { long options = 0; char *ret_val = NULL, *buffer = NULL; int buffer_len; struct php_fileinfo *finfo; zval *zfinfo, *zcontext = NULL; zval *what; char mime_directory[] = "directory"; struct magic_set *magic = NULL; FILEINFO_DECLARE_INIT_OBJECT(object) if (mimetype_emu) { /* mime_content_type(..) emulation */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &what) == FAILURE) { return; } switch (Z_TYPE_P(what)) { case IS_STRING: buffer = Z_STRVAL_P(what); buffer_len = Z_STRLEN_P(what); mode = FILEINFO_MODE_FILE; break; case IS_RESOURCE: mode = FILEINFO_MODE_STREAM; break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can only process string or stream arguments"); RETURN_FALSE; } magic = magic_open(MAGIC_MIME_TYPE); if (magic_load(magic, NULL) == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to load magic database."); goto common; } } else if (object) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|lr", &buffer, &buffer_len, &options, &zcontext) == FAILURE) { RETURN_FALSE; } FILEINFO_FROM_OBJECT(finfo, object); magic = finfo->magic; } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs|lr", &zfinfo, &buffer, &buffer_len, &options, &zcontext) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(finfo, struct php_fileinfo *, &zfinfo, -1, "file_info", le_fileinfo); magic = finfo->magic; } /* Set options for the current file/buffer. */ if (options) { FINFO_SET_OPTION(magic, options) } switch (mode) { case FILEINFO_MODE_BUFFER: { ret_val = (char *) magic_buffer(magic, buffer, buffer_len); break; } case FILEINFO_MODE_STREAM: { php_stream *stream; off_t streampos; php_stream_from_zval_no_verify(stream, &what); if (!stream) { goto common; } streampos = php_stream_tell(stream); /* remember stream position for restoration */ php_stream_seek(stream, 0, SEEK_SET); ret_val = (char *) magic_stream(magic, stream); php_stream_seek(stream, streampos, SEEK_SET); break; } case FILEINFO_MODE_FILE: { /* determine if the file is a local file or remote URL */ char *tmp2; php_stream_wrapper *wrap; struct stat sb; if (buffer == NULL || !*buffer) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty filename or path"); RETVAL_FALSE; goto clean; } if (php_sys_stat(buffer, &sb) == 0) { if (sb.st_mode & _S_IFDIR) { ret_val = mime_directory; goto common; } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "File or path not found '%s'", buffer); RETVAL_FALSE; goto clean; } wrap = php_stream_locate_url_wrapper(buffer, &tmp2, 0 TSRMLS_CC); if (wrap) { php_stream_context *context = php_stream_context_from_zval(zcontext, 0); #if PHP_API_VERSION < 20100412 php_stream *stream = php_stream_open_wrapper_ex(buffer, "rb", ENFORCE_SAFE_MODE | REPORT_ERRORS, NULL, context); #else php_stream *stream = php_stream_open_wrapper_ex(buffer, "rb", REPORT_ERRORS, NULL, context); #endif if (!stream) { RETVAL_FALSE; goto clean; } ret_val = (char *)magic_stream(magic, stream); php_stream_close(stream); } break; } default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can only process string or stream arguments"); } common: if (ret_val) { RETVAL_STRING(ret_val, 1); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed identify data %d:%s", magic_errno(magic), magic_error(magic)); RETVAL_FALSE; } clean: if (mimetype_emu) { magic_close(magic); } /* Restore options */ if (options) { FINFO_SET_OPTION(magic, finfo->options) } return; } /* }}} */ /* {{{ proto string finfo_file(resource finfo, char *file_name [, int options [, resource context]]) Return information about a file. */ PHP_FUNCTION(finfo_file) { _php_finfo_get_type(INTERNAL_FUNCTION_PARAM_PASSTHRU, FILEINFO_MODE_FILE, 0); } /* }}} */ /* {{{ proto string finfo_buffer(resource finfo, char *string [, int options [, resource context]]) Return infromation about a string buffer. */ PHP_FUNCTION(finfo_buffer) { _php_finfo_get_type(INTERNAL_FUNCTION_PARAM_PASSTHRU, FILEINFO_MODE_BUFFER, 0); } /* }}} */ /* {{{ proto string mime_content_type(string filename|resource stream) Return content-type for file */ PHP_FUNCTION(mime_content_type) { _php_finfo_get_type(INTERNAL_FUNCTION_PARAM_PASSTHRU, -1, 1); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.0 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_0.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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Ilia Alshanetsky <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include <magic.h> /* * HOWMANY specifies the maximum offset libmagic will look at * this is currently hardcoded in the libmagic source but not exported */ #ifndef HOWMANY #define HOWMANY 65536 #endif #include "php_ini.h" #include "ext/standard/info.h" #include "ext/standard/file.h" /* needed for context stuff */ #include "php_fileinfo.h" #include "fopen_wrappers.h" /* needed for is_url */ #ifndef _S_IFDIR # define _S_IFDIR S_IFDIR #endif /* {{{ macros and type definitions */ struct php_fileinfo { long options; struct magic_set *magic; }; static zend_object_handlers finfo_object_handlers; zend_class_entry *finfo_class_entry; struct finfo_object { zend_object zo; struct php_fileinfo *ptr; }; #define FILEINFO_DECLARE_INIT_OBJECT(object) \ zval *object = getThis(); #define FILEINFO_REGISTER_OBJECT(_object, _ptr) \ { \ struct finfo_object *obj; \ obj = (struct finfo_object*)zend_object_store_get_object(_object TSRMLS_CC); \ obj->ptr = _ptr; \ } #define FILEINFO_FROM_OBJECT(finfo, object) \ { \ struct finfo_object *obj = zend_object_store_get_object(object TSRMLS_CC); \ finfo = obj->ptr; \ if (!finfo) { \ php_error_docref(NULL TSRMLS_CC, E_WARNING, "The invalid fileinfo object."); \ RETURN_FALSE; \ } \ } /* {{{ finfo_objects_dtor */ static void finfo_objects_dtor(void *object, zend_object_handle handle TSRMLS_DC) { struct finfo_object *intern = (struct finfo_object *) object; if (intern->ptr) { magic_close(intern->ptr->magic); efree(intern->ptr); } zend_object_std_dtor(&intern->zo TSRMLS_CC); efree(intern); } /* }}} */ /* {{{ finfo_objects_new */ PHP_FILEINFO_API zend_object_value finfo_objects_new(zend_class_entry *class_type TSRMLS_DC) { zend_object_value retval; struct finfo_object *intern; intern = emalloc(sizeof(struct finfo_object)); memset(intern, 0, sizeof(struct finfo_object)); zend_object_std_init(&intern->zo, class_type TSRMLS_CC); object_properties_init(&intern->zo, class_type); intern->ptr = NULL; retval.handle = zend_objects_store_put(intern, finfo_objects_dtor, NULL, NULL TSRMLS_CC); retval.handlers = (zend_object_handlers *) &finfo_object_handlers; return retval; } /* }}} */ /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_finfo_open, 0, 0, 0) ZEND_ARG_INFO(0, options) ZEND_ARG_INFO(0, arg) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_finfo_close, 0, 0, 1) ZEND_ARG_INFO(0, finfo) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_finfo_set_flags, 0, 0, 2) ZEND_ARG_INFO(0, finfo) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_finfo_method_set_flags, 0, 0, 1) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_finfo_file, 0, 0, 2) ZEND_ARG_INFO(0, finfo) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, options) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_finfo_method_file, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, options) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_finfo_buffer, 0, 0, 2) ZEND_ARG_INFO(0, finfo) ZEND_ARG_INFO(0, string) ZEND_ARG_INFO(0, options) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_finfo_method_buffer, 0, 0, 1) ZEND_ARG_INFO(0, string) ZEND_ARG_INFO(0, options) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mime_content_type, 0, 0, 1) ZEND_ARG_INFO(0, string) ZEND_END_ARG_INFO() /* }}} */ /* {{{ finfo_class_functions */ zend_function_entry finfo_class_functions[] = { ZEND_ME_MAPPING(finfo, finfo_open, arginfo_finfo_open, ZEND_ACC_PUBLIC) ZEND_ME_MAPPING(set_flags, finfo_set_flags,arginfo_finfo_method_set_flags, ZEND_ACC_PUBLIC) ZEND_ME_MAPPING(file, finfo_file, arginfo_finfo_method_file, ZEND_ACC_PUBLIC) ZEND_ME_MAPPING(buffer, finfo_buffer, arginfo_finfo_method_buffer, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; /* }}} */ #define FINFO_SET_OPTION(magic, options) \ if (magic_setflags(magic, options) == -1) { \ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to set option '%ld' %d:%s", \ options, magic_errno(magic), magic_error(magic)); \ RETURN_FALSE; \ } /* True global resources - no need for thread safety here */ static int le_fileinfo; /* }}} */ void finfo_resource_destructor(zend_rsrc_list_entry *rsrc TSRMLS_DC) /* {{{ */ { if (rsrc->ptr) { struct php_fileinfo *finfo = (struct php_fileinfo *) rsrc->ptr; magic_close(finfo->magic); efree(rsrc->ptr); rsrc->ptr = NULL; } } /* }}} */ /* {{{ fileinfo_functions[] */ zend_function_entry fileinfo_functions[] = { PHP_FE(finfo_open, arginfo_finfo_open) PHP_FE(finfo_close, arginfo_finfo_close) PHP_FE(finfo_set_flags, arginfo_finfo_set_flags) PHP_FE(finfo_file, arginfo_finfo_file) PHP_FE(finfo_buffer, arginfo_finfo_buffer) PHP_FE(mime_content_type, arginfo_mime_content_type) {NULL, NULL, NULL} }; /* }}} */ /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(finfo) { zend_class_entry _finfo_class_entry; INIT_CLASS_ENTRY(_finfo_class_entry, "finfo", finfo_class_functions); _finfo_class_entry.create_object = finfo_objects_new; finfo_class_entry = zend_register_internal_class(&_finfo_class_entry TSRMLS_CC); /* copy the standard object handlers to you handler table */ memcpy(&finfo_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); le_fileinfo = zend_register_list_destructors_ex(finfo_resource_destructor, NULL, "file_info", module_number); REGISTER_LONG_CONSTANT("FILEINFO_NONE", MAGIC_NONE, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILEINFO_SYMLINK", MAGIC_SYMLINK, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILEINFO_MIME", MAGIC_MIME, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILEINFO_MIME_TYPE", MAGIC_MIME_TYPE, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILEINFO_MIME_ENCODING",MAGIC_MIME_ENCODING, CONST_CS|CONST_PERSISTENT); /* REGISTER_LONG_CONSTANT("FILEINFO_COMPRESS", MAGIC_COMPRESS, CONST_CS|CONST_PERSISTENT); disabled, as it does fork now */ REGISTER_LONG_CONSTANT("FILEINFO_DEVICES", MAGIC_DEVICES, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILEINFO_CONTINUE", MAGIC_CONTINUE, CONST_CS|CONST_PERSISTENT); #ifdef MAGIC_PRESERVE_ATIME REGISTER_LONG_CONSTANT("FILEINFO_PRESERVE_ATIME", MAGIC_PRESERVE_ATIME, CONST_CS|CONST_PERSISTENT); #endif #ifdef MAGIC_RAW REGISTER_LONG_CONSTANT("FILEINFO_RAW", MAGIC_RAW, CONST_CS|CONST_PERSISTENT); #endif return SUCCESS; } /* }}} */ /* {{{ fileinfo_module_entry */ zend_module_entry fileinfo_module_entry = { STANDARD_MODULE_HEADER, "fileinfo", fileinfo_functions, PHP_MINIT(finfo), NULL, NULL, NULL, PHP_MINFO(fileinfo), PHP_FILEINFO_VERSION, STANDARD_MODULE_PROPERTIES }; /* }}} */ #ifdef COMPILE_DL_FILEINFO ZEND_GET_MODULE(fileinfo) #endif /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(fileinfo) { php_info_print_table_start(); php_info_print_table_header(2, "fileinfo support", "enabled"); php_info_print_table_row(2, "version", PHP_FILEINFO_VERSION); php_info_print_table_end(); } /* }}} */ /* {{{ proto resource finfo_open([int options [, string arg]]) Create a new fileinfo resource. */ PHP_FUNCTION(finfo_open) { long options = MAGIC_NONE; char *file = NULL; int file_len = 0; struct php_fileinfo *finfo; FILEINFO_DECLARE_INIT_OBJECT(object) char resolved_path[MAXPATHLEN]; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|ls", &options, &file, &file_len) == FAILURE) { RETURN_FALSE; } if (file_len == 0) { file = NULL; } else if (file && *file) { /* user specified file, perform open_basedir checks */ if (!VCWD_REALPATH(file, resolved_path)) { RETURN_FALSE; } file = resolved_path; #if PHP_API_VERSION < 20100412 if ((PG(safe_mode) && (!php_checkuid(file, NULL, CHECKUID_CHECK_FILE_AND_DIR))) || php_check_open_basedir(file TSRMLS_CC)) { #else if (php_check_open_basedir(file TSRMLS_CC)) { #endif RETURN_FALSE; } } finfo = emalloc(sizeof(struct php_fileinfo)); finfo->options = options; finfo->magic = magic_open(options); if (finfo->magic == NULL) { efree(finfo); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid mode '%ld'.", options); RETURN_FALSE; } if (magic_load(finfo->magic, file) == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to load magic database at '%s'.", file); magic_close(finfo->magic); efree(finfo); RETURN_FALSE; } if (object) { FILEINFO_REGISTER_OBJECT(object, finfo); } else { ZEND_REGISTER_RESOURCE(return_value, finfo, le_fileinfo); } } /* }}} */ /* {{{ proto resource finfo_close(resource finfo) Close fileinfo resource. */ PHP_FUNCTION(finfo_close) { struct php_fileinfo *finfo; zval *zfinfo; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zfinfo) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(finfo, struct php_fileinfo *, &zfinfo, -1, "file_info", le_fileinfo); zend_list_delete(Z_RESVAL_P(zfinfo)); RETURN_TRUE; } /* }}} */ /* {{{ proto bool finfo_set_flags(resource finfo, int options) Set libmagic configuration options. */ PHP_FUNCTION(finfo_set_flags) { long options; struct php_fileinfo *finfo; zval *zfinfo; FILEINFO_DECLARE_INIT_OBJECT(object) if (object) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &options) == FAILURE) { RETURN_FALSE; } FILEINFO_FROM_OBJECT(finfo, object); } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &zfinfo, &options) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(finfo, struct php_fileinfo *, &zfinfo, -1, "file_info", le_fileinfo); } FINFO_SET_OPTION(finfo->magic, options) finfo->options = options; RETURN_TRUE; } /* }}} */ #define FILEINFO_MODE_BUFFER 0 #define FILEINFO_MODE_STREAM 1 #define FILEINFO_MODE_FILE 2 static void _php_finfo_get_type(INTERNAL_FUNCTION_PARAMETERS, int mode, int mimetype_emu) /* {{{ */ { long options = 0; char *ret_val = NULL, *buffer = NULL; int buffer_len; struct php_fileinfo *finfo; zval *zfinfo, *zcontext = NULL; zval *what; char mime_directory[] = "directory"; struct magic_set *magic = NULL; FILEINFO_DECLARE_INIT_OBJECT(object) if (mimetype_emu) { /* mime_content_type(..) emulation */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &what) == FAILURE) { return; } switch (Z_TYPE_P(what)) { case IS_STRING: buffer = Z_STRVAL_P(what); buffer_len = Z_STRLEN_P(what); mode = FILEINFO_MODE_FILE; break; case IS_RESOURCE: mode = FILEINFO_MODE_STREAM; break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can only process string or stream arguments"); RETURN_FALSE; } magic = magic_open(MAGIC_MIME_TYPE); if (magic_load(magic, NULL) == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to load magic database."); goto common; } } else if (object) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|lr", &buffer, &buffer_len, &options, &zcontext) == FAILURE) { RETURN_FALSE; } FILEINFO_FROM_OBJECT(finfo, object); magic = finfo->magic; } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs|lr", &zfinfo, &buffer, &buffer_len, &options, &zcontext) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(finfo, struct php_fileinfo *, &zfinfo, -1, "file_info", le_fileinfo); magic = finfo->magic; } /* Set options for the current file/buffer. */ if (options) { FINFO_SET_OPTION(magic, options) } switch (mode) { case FILEINFO_MODE_BUFFER: { ret_val = (char *) magic_buffer(magic, buffer, buffer_len); break; } case FILEINFO_MODE_STREAM: { php_stream *stream; off_t streampos; php_stream_from_zval_no_verify(stream, &what); if (!stream) { goto common; } streampos = php_stream_tell(stream); /* remember stream position for restoration */ php_stream_seek(stream, 0, SEEK_SET); ret_val = (char *) magic_stream(magic, stream); php_stream_seek(stream, streampos, SEEK_SET); break; } case FILEINFO_MODE_FILE: { /* determine if the file is a local file or remote URL */ char *tmp2; php_stream_wrapper *wrap; php_stream_statbuf ssb; if (buffer == NULL || !*buffer) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty filename or path"); RETVAL_FALSE; goto clean; } wrap = php_stream_locate_url_wrapper(buffer, &tmp2, 0 TSRMLS_CC); if (wrap) { php_stream_context *context = php_stream_context_from_zval(zcontext, 0); #if PHP_API_VERSION < 20100412 php_stream *stream = php_stream_open_wrapper_ex(buffer, "rb", ENFORCE_SAFE_MODE | REPORT_ERRORS, NULL, context); #else php_stream *stream = php_stream_open_wrapper_ex(buffer, "rb", REPORT_ERRORS, NULL, context); #endif if (!stream) { RETVAL_FALSE; goto clean; } if (php_stream_stat(stream, &ssb) == SUCCESS) { if (ssb.sb.st_mode & S_IFDIR) { ret_val = mime_directory; } else { ret_val = (char *)magic_stream(magic, stream); } } php_stream_close(stream); } break; } default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can only process string or stream arguments"); } common: if (ret_val) { RETVAL_STRING(ret_val, 1); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed identify data %d:%s", magic_errno(magic), magic_error(magic)); RETVAL_FALSE; } clean: if (mimetype_emu) { magic_close(magic); } /* Restore options */ if (options) { FINFO_SET_OPTION(magic, finfo->options) } return; } /* }}} */ /* {{{ proto string finfo_file(resource finfo, char *file_name [, int options [, resource context]]) Return information about a file. */ PHP_FUNCTION(finfo_file) { _php_finfo_get_type(INTERNAL_FUNCTION_PARAM_PASSTHRU, FILEINFO_MODE_FILE, 0); } /* }}} */ /* {{{ proto string finfo_buffer(resource finfo, char *string [, int options [, resource context]]) Return infromation about a string buffer. */ PHP_FUNCTION(finfo_buffer) { _php_finfo_get_type(INTERNAL_FUNCTION_PARAM_PASSTHRU, FILEINFO_MODE_BUFFER, 0); } /* }}} */ /* {{{ proto string mime_content_type(string filename|resource stream) Return content-type for file */ PHP_FUNCTION(mime_content_type) { _php_finfo_get_type(INTERNAL_FUNCTION_PARAM_PASSTHRU, -1, 1); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-02-14-86efc8e55e-d1d61ce612.c
manybugs_data_89
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <stdio.h> #include "zend.h" #include "zend_API.h" #include "zend_globals.h" #include "zend_constants.h" #include "zend_list.h" ZEND_API void _zval_dtor_func(zval *zvalue ZEND_FILE_LINE_DC) { switch (Z_TYPE_P(zvalue) & IS_CONSTANT_TYPE_MASK) { case IS_STRING: case IS_CONSTANT: case IS_CLASS: CHECK_ZVAL_STRING_REL(zvalue); STR_FREE_REL(zvalue->value.str.val); break; case IS_ARRAY: case IS_CONSTANT_ARRAY: { TSRMLS_FETCH(); if (zvalue->value.ht && (zvalue->value.ht != &EG(symbol_table))) { zend_hash_destroy(zvalue->value.ht); FREE_HASHTABLE(zvalue->value.ht); } } break; case IS_OBJECT: { TSRMLS_FETCH(); Z_OBJ_HT_P(zvalue)->del_ref(zvalue TSRMLS_CC); } break; case IS_RESOURCE: { TSRMLS_FETCH(); /* destroy resource */ zend_list_delete(zvalue->value.lval); } break; case IS_LONG: case IS_DOUBLE: case IS_BOOL: case IS_NULL: default: return; break; } } ZEND_API void _zval_internal_dtor(zval *zvalue ZEND_FILE_LINE_DC) { switch (Z_TYPE_P(zvalue) & IS_CONSTANT_TYPE_MASK) { case IS_STRING: case IS_CONSTANT: CHECK_ZVAL_STRING_REL(zvalue); str_free(zvalue->value.str.val); break; case IS_ARRAY: case IS_CONSTANT_ARRAY: case IS_OBJECT: case IS_RESOURCE: zend_error(E_CORE_ERROR, "Internal zval's can't be arrays, objects or resources"); break; case IS_LONG: case IS_DOUBLE: case IS_BOOL: case IS_NULL: default: break; } } ZEND_API void zval_add_ref(zval **p) { Z_ADDREF_PP(p); } ZEND_API void _zval_copy_ctor_func(zval *zvalue ZEND_FILE_LINE_DC) { switch (Z_TYPE_P(zvalue) & IS_CONSTANT_TYPE_MASK) { case IS_RESOURCE: { TSRMLS_FETCH(); zend_list_addref(zvalue->value.lval); } break; case IS_BOOL: case IS_LONG: case IS_NULL: break; case IS_CONSTANT: case IS_STRING: CHECK_ZVAL_STRING_REL(zvalue); if (!IS_INTERNED(zvalue->value.str.val)) { zvalue->value.str.val = (char *) estrndup_rel(zvalue->value.str.val, zvalue->value.str.len); } break; case IS_ARRAY: case IS_CONSTANT_ARRAY: { zval *tmp; HashTable *original_ht = zvalue->value.ht; HashTable *tmp_ht = NULL; TSRMLS_FETCH(); if (zvalue->value.ht == &EG(symbol_table)) { return; /* do nothing */ } ALLOC_HASHTABLE_REL(tmp_ht); zend_hash_init(tmp_ht, zend_hash_num_elements(original_ht), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(tmp_ht, original_ht, (copy_ctor_func_t) zval_add_ref, (void *) &tmp, sizeof(zval *)); zvalue->value.ht = tmp_ht; } break; case IS_OBJECT: { TSRMLS_FETCH(); Z_OBJ_HT_P(zvalue)->add_ref(zvalue TSRMLS_CC); } break; } } ZEND_API int zend_print_variable(zval *var) { return zend_print_zval(var, 0); } ZEND_API void _zval_dtor_wrapper(zval *zvalue) { TSRMLS_FETCH(); GC_REMOVE_ZVAL_FROM_BUFFER(zvalue); zval_dtor(zvalue); } #if ZEND_DEBUG ZEND_API void _zval_copy_ctor_wrapper(zval *zvalue) { zval_copy_ctor(zvalue); } ZEND_API void _zval_internal_dtor_wrapper(zval *zvalue) { zval_internal_dtor(zvalue); } ZEND_API void _zval_ptr_dtor_wrapper(zval **zval_ptr) { zval_ptr_dtor(zval_ptr); } ZEND_API void _zval_internal_ptr_dtor_wrapper(zval **zval_ptr) { zval_internal_ptr_dtor(zval_ptr); } #endif ZEND_API int zval_copy_static_var(zval **p TSRMLS_DC, int num_args, va_list args, zend_hash_key *key) /* {{{ */ { HashTable *target = va_arg(args, HashTable*); zend_bool is_ref; zval *tmp; if (Z_TYPE_PP(p) & (IS_LEXICAL_VAR|IS_LEXICAL_REF)) { is_ref = Z_TYPE_PP(p) & IS_LEXICAL_REF; if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } if (zend_hash_quick_find(EG(active_symbol_table), key->arKey, key->nKeyLength, key->h, (void **) &p) == FAILURE) { if (is_ref) { ALLOC_INIT_ZVAL(tmp); Z_SET_ISREF_P(tmp); zend_hash_quick_add(EG(active_symbol_table), key->arKey, key->nKeyLength, key->h, &tmp, sizeof(zval*), (void**)&p); } else { tmp = EG(uninitialized_zval_ptr); zend_error(E_NOTICE,"Undefined variable: %s", key->arKey); } } else { if (is_ref) { SEPARATE_ZVAL_TO_MAKE_IS_REF(p); tmp = *p; } else if (Z_ISREF_PP(p)) { ALLOC_INIT_ZVAL(tmp); ZVAL_COPY_VALUE(tmp, *p); Z_SET_REFCOUNT_P(tmp, 0); Z_UNSET_ISREF_P(tmp); } else { tmp = *p; } } } else { tmp = *p; } if (zend_hash_quick_add(target, key->arKey, key->nKeyLength, key->h, &tmp, sizeof(zval*), NULL) == SUCCESS) { Z_ADDREF_P(tmp); } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */ /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <stdio.h> #include "zend.h" #include "zend_API.h" #include "zend_globals.h" #include "zend_constants.h" #include "zend_list.h" ZEND_API void _zval_dtor_func(zval *zvalue ZEND_FILE_LINE_DC) { switch (Z_TYPE_P(zvalue) & IS_CONSTANT_TYPE_MASK) { case IS_STRING: case IS_CONSTANT: case IS_CLASS: CHECK_ZVAL_STRING_REL(zvalue); STR_FREE_REL(zvalue->value.str.val); break; case IS_ARRAY: case IS_CONSTANT_ARRAY: { TSRMLS_FETCH(); if (zvalue->value.ht && (zvalue->value.ht != &EG(symbol_table))) { zend_hash_destroy(zvalue->value.ht); FREE_HASHTABLE(zvalue->value.ht); } } break; case IS_OBJECT: { TSRMLS_FETCH(); Z_OBJ_HT_P(zvalue)->del_ref(zvalue TSRMLS_CC); } break; case IS_RESOURCE: { TSRMLS_FETCH(); /* destroy resource */ zend_list_delete(zvalue->value.lval); } break; case IS_LONG: case IS_DOUBLE: case IS_BOOL: case IS_NULL: default: return; break; } } ZEND_API void _zval_internal_dtor(zval *zvalue ZEND_FILE_LINE_DC) { switch (Z_TYPE_P(zvalue) & IS_CONSTANT_TYPE_MASK) { case IS_STRING: case IS_CONSTANT: CHECK_ZVAL_STRING_REL(zvalue); str_free(zvalue->value.str.val); break; case IS_ARRAY: case IS_CONSTANT_ARRAY: case IS_OBJECT: case IS_RESOURCE: zend_error(E_CORE_ERROR, "Internal zval's can't be arrays, objects or resources"); break; case IS_LONG: case IS_DOUBLE: case IS_BOOL: case IS_NULL: default: break; } } ZEND_API void zval_add_ref(zval **p) { Z_ADDREF_PP(p); } ZEND_API void _zval_copy_ctor_func(zval *zvalue ZEND_FILE_LINE_DC) { switch (Z_TYPE_P(zvalue) & IS_CONSTANT_TYPE_MASK) { case IS_RESOURCE: { TSRMLS_FETCH(); zend_list_addref(zvalue->value.lval); } break; case IS_BOOL: case IS_LONG: case IS_NULL: break; case IS_CONSTANT: case IS_STRING: CHECK_ZVAL_STRING_REL(zvalue); if (!IS_INTERNED(zvalue->value.str.val)) { zvalue->value.str.val = (char *) estrndup_rel(zvalue->value.str.val, zvalue->value.str.len); } break; case IS_ARRAY: case IS_CONSTANT_ARRAY: { zval *tmp; HashTable *original_ht = zvalue->value.ht; HashTable *tmp_ht = NULL; TSRMLS_FETCH(); if (zvalue->value.ht == &EG(symbol_table)) { return; /* do nothing */ } ALLOC_HASHTABLE_REL(tmp_ht); zend_hash_init(tmp_ht, zend_hash_num_elements(original_ht), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(tmp_ht, original_ht, (copy_ctor_func_t) zval_add_ref, (void *) &tmp, sizeof(zval *)); zvalue->value.ht = tmp_ht; } break; case IS_OBJECT: { TSRMLS_FETCH(); Z_OBJ_HT_P(zvalue)->add_ref(zvalue TSRMLS_CC); } break; } } ZEND_API int zend_print_variable(zval *var) { return zend_print_zval(var, 0); } ZEND_API void _zval_dtor_wrapper(zval *zvalue) { TSRMLS_FETCH(); GC_REMOVE_ZVAL_FROM_BUFFER(zvalue); zval_dtor(zvalue); } #if ZEND_DEBUG ZEND_API void _zval_copy_ctor_wrapper(zval *zvalue) { zval_copy_ctor(zvalue); } ZEND_API void _zval_internal_dtor_wrapper(zval *zvalue) { zval_internal_dtor(zvalue); } ZEND_API void _zval_ptr_dtor_wrapper(zval **zval_ptr) { zval_ptr_dtor(zval_ptr); } ZEND_API void _zval_internal_ptr_dtor_wrapper(zval **zval_ptr) { zval_internal_ptr_dtor(zval_ptr); } #endif ZEND_API int zval_copy_static_var(zval **p TSRMLS_DC, int num_args, va_list args, zend_hash_key *key) /* {{{ */ { HashTable *target = va_arg(args, HashTable*); zend_bool is_ref; zval *tmp; if (Z_TYPE_PP(p) & (IS_LEXICAL_VAR|IS_LEXICAL_REF)) { is_ref = Z_TYPE_PP(p) & IS_LEXICAL_REF; if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } if (zend_hash_quick_find(EG(active_symbol_table), key->arKey, key->nKeyLength, key->h, (void **) &p) == FAILURE) { if (is_ref) { ALLOC_INIT_ZVAL(tmp); Z_SET_ISREF_P(tmp); zend_hash_quick_add(EG(active_symbol_table), key->arKey, key->nKeyLength, key->h, &tmp, sizeof(zval*), (void**)&p); } else { tmp = EG(uninitialized_zval_ptr); zend_error(E_NOTICE,"Undefined variable: %s", key->arKey); } } else { if (is_ref) { SEPARATE_ZVAL_TO_MAKE_IS_REF(p); tmp = *p; } else if (Z_ISREF_PP(p)) { ALLOC_INIT_ZVAL(tmp); ZVAL_COPY_VALUE(tmp, *p); zval_copy_ctor(tmp); Z_SET_REFCOUNT_P(tmp, 0); Z_UNSET_ISREF_P(tmp); } else { tmp = *p; } } } else { tmp = *p; } if (zend_hash_quick_add(target, key->arKey, key->nKeyLength, key->h, &tmp, sizeof(zval*), NULL) == SUCCESS) { Z_ADDREF_P(tmp); } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-04-07-77ed819430-efcb9a71cd.c
manybugs_data_90
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <zend_language_parser.h> #include "zend.h" #include "zend_compile.h" #include "zend_constants.h" #include "zend_llist.h" #include "zend_API.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "zend_multibyte.h" #include "zend_language_scanner.h" #define CONSTANT_EX(op_array, op) \ (op_array)->literals[op].constant #define CONSTANT(op) \ CONSTANT_EX(CG(active_op_array), op) #define SET_NODE(target, src) do { \ target ## _type = (src)->op_type; \ if ((src)->op_type == IS_CONST) { \ target.constant = zend_add_literal(CG(active_op_array), &(src)->u.constant TSRMLS_CC); \ } else { \ target = (src)->u.op; \ } \ } while (0) #define GET_NODE(target, src) do { \ (target)->op_type = src ## _type; \ if ((target)->op_type == IS_CONST) { \ (target)->u.constant = CONSTANT(src.constant); \ } else { \ (target)->u.op = src; \ (target)->EA = 0; \ } \ } while (0) #define COPY_NODE(target, src) do { \ target ## _type = src ## _type; \ target = src; \ } while (0) #define CALCULATE_LITERAL_HASH(num) do { \ if (IS_INTERNED(Z_STRVAL(CONSTANT(num)))) { \ Z_HASH_P(&CONSTANT(num)) = INTERNED_HASH(Z_STRVAL(CONSTANT(num))); \ } else { \ Z_HASH_P(&CONSTANT(num)) = zend_hash_func(Z_STRVAL(CONSTANT(num)), Z_STRLEN(CONSTANT(num))+1); \ } \ } while (0) #define GET_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot++; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ } \ } while (0) #define POLYMORPHIC_CACHE_SLOT_SIZE 2 #define GET_POLYMORPHIC_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot; \ CG(active_op_array)->last_cache_slot += POLYMORPHIC_CACHE_SLOT_SIZE; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 2] = NULL; \ } \ } while (0) #define FREE_POLYMORPHIC_CACHE_SLOT(literal) do { \ if (CG(active_op_array)->literals[literal].cache_slot == \ CG(active_op_array)->last_cache_slot - POLYMORPHIC_CACHE_SLOT_SIZE) { \ CG(active_op_array)->literals[literal].cache_slot = -1; \ CG(active_op_array)->last_cache_slot -= POLYMORPHIC_CACHE_SLOT_SIZE; \ } \ } while (0) ZEND_API zend_op_array *(*zend_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); ZEND_API zend_op_array *(*zend_compile_string)(zval *source_string, char *filename TSRMLS_DC); #ifndef ZTS ZEND_API zend_compiler_globals compiler_globals; ZEND_API zend_executor_globals executor_globals; #endif static void zend_duplicate_property_info(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = estrndup(property_info->name, property_info->name_length); } if (property_info->doc_comment) { property_info->doc_comment = estrndup(property_info->doc_comment, property_info->doc_comment_len); } } /* }}} */ static void zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = zend_strndup(property_info->name, property_info->name_length); } } /* }}} */ static void zend_destroy_property_info(zend_property_info *property_info) /* {{{ */ { str_efree(property_info->name); if (property_info->doc_comment) { efree((char*)property_info->doc_comment); } } /* }}} */ static void zend_destroy_property_info_internal(zend_property_info *property_info) /* {{{ */ { str_free((char*)property_info->name); } /* }}} */ static void build_runtime_defined_function_key(zval *result, const char *name, int name_length TSRMLS_DC) /* {{{ */ { char char_pos_buf[32]; uint char_pos_len; const char *filename; char_pos_len = zend_sprintf(char_pos_buf, "%p", LANG_SCNG(yy_text)); if (CG(active_op_array)->filename) { filename = CG(active_op_array)->filename; } else { filename = "-"; } /* NULL, name length, filename length, last accepting char position length */ result->value.str.len = 1+name_length+strlen(filename)+char_pos_len; /* must be binary safe */ result->value.str.val = (char *) safe_emalloc(result->value.str.len, 1, 1); result->value.str.val[0] = '\0'; sprintf(result->value.str.val+1, "%s%s%s", name, filename, char_pos_buf); result->type = IS_STRING; Z_SET_REFCOUNT_P(result, 1); } /* }}} */ static void init_compiler_declarables(TSRMLS_D) /* {{{ */ { Z_TYPE(CG(declarables).ticks) = IS_LONG; Z_LVAL(CG(declarables).ticks) = 0; } /* }}} */ void zend_init_compiler_context(TSRMLS_D) /* {{{ */ { CG(context).opcodes_size = (CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) ? INITIAL_INTERACTIVE_OP_ARRAY_SIZE : INITIAL_OP_ARRAY_SIZE; CG(context).vars_size = 0; CG(context).literals_size = 0; CG(context).current_brk_cont = -1; CG(context).backpatch_count = 0; CG(context).labels = NULL; } /* }}} */ void zend_init_compiler_data_structures(TSRMLS_D) /* {{{ */ { zend_stack_init(&CG(bp_stack)); zend_stack_init(&CG(function_call_stack)); zend_stack_init(&CG(switch_cond_stack)); zend_stack_init(&CG(foreach_copy_stack)); zend_stack_init(&CG(object_stack)); zend_stack_init(&CG(declare_stack)); CG(active_class_entry) = NULL; zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_stack_init(&CG(list_stack)); CG(in_compilation) = 0; CG(start_lineno) = 0; CG(current_namespace) = NULL; CG(in_namespace) = 0; CG(has_bracketed_namespaces) = 0; CG(current_import) = NULL; init_compiler_declarables(TSRMLS_C); zend_stack_init(&CG(context_stack)); CG(encoding_declared) = 0; } /* }}} */ ZEND_API void file_handle_dtor(zend_file_handle *fh) /* {{{ */ { TSRMLS_FETCH(); zend_file_handle_dtor(fh TSRMLS_CC); } /* }}} */ void init_compiler(TSRMLS_D) /* {{{ */ { CG(active_op_array) = NULL; zend_init_compiler_data_structures(TSRMLS_C); zend_init_rsrc_list(TSRMLS_C); zend_hash_init(&CG(filenames_table), 5, NULL, (dtor_func_t) free_estring, 0); zend_llist_init(&CG(open_files), sizeof(zend_file_handle), (void (*)(void *)) file_handle_dtor, 0); CG(unclean_shutdown) = 0; } /* }}} */ void shutdown_compiler(TSRMLS_D) /* {{{ */ { zend_stack_destroy(&CG(bp_stack)); zend_stack_destroy(&CG(function_call_stack)); zend_stack_destroy(&CG(switch_cond_stack)); zend_stack_destroy(&CG(foreach_copy_stack)); zend_stack_destroy(&CG(object_stack)); zend_stack_destroy(&CG(declare_stack)); zend_stack_destroy(&CG(list_stack)); zend_hash_destroy(&CG(filenames_table)); zend_llist_destroy(&CG(open_files)); zend_stack_destroy(&CG(context_stack)); } /* }}} */ ZEND_API char *zend_set_compiled_filename(const char *new_compiled_filename TSRMLS_DC) /* {{{ */ { char **pp, *p; int length = strlen(new_compiled_filename); if (zend_hash_find(&CG(filenames_table), new_compiled_filename, length+1, (void **) &pp) == SUCCESS) { CG(compiled_filename) = *pp; return *pp; } p = estrndup(new_compiled_filename, length); zend_hash_update(&CG(filenames_table), new_compiled_filename, length+1, &p, sizeof(char *), (void **) &pp); CG(compiled_filename) = p; return p; } /* }}} */ ZEND_API void zend_restore_compiled_filename(char *original_compiled_filename TSRMLS_DC) /* {{{ */ { CG(compiled_filename) = original_compiled_filename; } /* }}} */ ZEND_API char *zend_get_compiled_filename(TSRMLS_D) /* {{{ */ { return CG(compiled_filename); } /* }}} */ ZEND_API int zend_get_compiled_lineno(TSRMLS_D) /* {{{ */ { return CG(zend_lineno); } /* }}} */ ZEND_API zend_bool zend_is_compiling(TSRMLS_D) /* {{{ */ { return CG(in_compilation); } /* }}} */ static zend_uint get_temporary_variable(zend_op_array *op_array) /* {{{ */ { return (op_array->T)++ * ZEND_MM_ALIGNED_SIZE(sizeof(temp_variable)); } /* }}} */ static int lookup_cv(zend_op_array *op_array, char* name, int name_len, ulong hash TSRMLS_DC) /* {{{ */ { int i = 0; ulong hash_value = hash ? hash : zend_inline_hash_func(name, name_len+1); while (i < op_array->last_var) { if (op_array->vars[i].name == name || (op_array->vars[i].hash_value == hash_value && op_array->vars[i].name_len == name_len && memcmp(op_array->vars[i].name, name, name_len) == 0)) { str_efree(name); return i; } i++; } i = op_array->last_var; op_array->last_var++; if (op_array->last_var > CG(context).vars_size) { CG(context).vars_size += 16; /* FIXME */ op_array->vars = erealloc(op_array->vars, CG(context).vars_size * sizeof(zend_compiled_variable)); } op_array->vars[i].name = zend_new_interned_string(name, name_len + 1, 1 TSRMLS_CC); op_array->vars[i].name_len = name_len; op_array->vars[i].hash_value = hash_value; return i; } /* }}} */ void zend_del_literal(zend_op_array *op_array, int n) /* {{{ */ { zval_dtor(&CONSTANT_EX(op_array, n)); if (n + 1 == op_array->last_literal) { op_array->last_literal--; } else { Z_TYPE(CONSTANT_EX(op_array, n)) = IS_NULL; } } /* }}} */ /* Common part of zend_add_literal and zend_append_individual_literal */ static inline void zend_insert_literal(zend_op_array *op_array, const zval *zv, int literal_position TSRMLS_DC) /* {{{ */ { if (Z_TYPE_P(zv) == IS_STRING || Z_TYPE_P(zv) == IS_CONSTANT) { zval *z = (zval*)zv; Z_STRVAL_P(z) = (char*)zend_new_interned_string(Z_STRVAL_P(zv), Z_STRLEN_P(zv) + 1, 1 TSRMLS_CC); } CONSTANT_EX(op_array, literal_position) = *zv; Z_SET_REFCOUNT(CONSTANT_EX(op_array, literal_position), 2); Z_SET_ISREF(CONSTANT_EX(op_array, literal_position)); op_array->literals[literal_position].hash_value = 0; op_array->literals[literal_position].cache_slot = -1; } /* }}} */ /* Is used while compiling a function, using the context to keep track of an approximate size to avoid to relocate to often. Literals are truncated to actual size in the second compiler pass (pass_two()). */ int zend_add_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; if (i >= CG(context).literals_size) { while (i >= CG(context).literals_size) { CG(context).literals_size += 16; /* FIXME */ } op_array->literals = (zend_literal*)erealloc(op_array->literals, CG(context).literals_size * sizeof(zend_literal)); } zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ /* Is used after normal compilation to append an additional literal. Allocation is done precisely here. */ int zend_append_individual_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; op_array->literals = (zend_literal*)erealloc(op_array->literals, (i + 1) * sizeof(zend_literal)); zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ int zend_add_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_ns_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; const char *ns_separator; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); ns_separator = (const char*)zend_memrchr(Z_STRVAL_P(zv), '\\', Z_STRLEN_P(zv)) + 1; lc_len = Z_STRLEN_P(zv) - (ns_separator - Z_STRVAL_P(zv)); lc_name = zend_str_tolower_dup(ns_separator, lc_len); ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_class_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } if (Z_STRVAL_P(zv)[0] == '\\') { lc_len = Z_STRLEN_P(zv) - 1; lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv) + 1, lc_len); } else { lc_len = Z_STRLEN_P(zv); lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), lc_len); } ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); GET_CACHE_SLOT(ret); return ret; } /* }}} */ int zend_add_const_name_literal(zend_op_array *op_array, const zval *zv, int unqualified TSRMLS_DC) /* {{{ */ { int ret, tmp_literal; char *name, *tmp_name; const char *ns_separator; int name_len, ns_len; zval c; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } /* skip leading '\\' */ if (Z_STRVAL_P(zv)[0] == '\\') { name_len = Z_STRLEN_P(zv) - 1; name = Z_STRVAL_P(zv) + 1; } else { name_len = Z_STRLEN_P(zv); name = Z_STRVAL_P(zv); } ns_separator = zend_memrchr(name, '\\', name_len); if (ns_separator) { ns_len = ns_separator - name; } else { ns_len = 0; } if (ns_len) { /* lowercased namespace name & original constant name */ tmp_name = estrndup(name, name_len); zend_str_tolower(tmp_name, ns_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased namespace name & lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); } if (ns_len) { if (!unqualified) { return ret; } ns_len++; name += ns_len; name_len -= ns_len; } /* original constant name */ tmp_name = estrndup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); return ret; } /* }}} */ #define LITERAL_STRINGL(op, str, len, copy) do { \ zval _c; \ ZVAL_STRINGL(&_c, str, len, copy); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG(op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG_EX(op_array, op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(op_array, &_c TSRMLS_CC); \ } while (0) #define LITERAL_NULL(op) do { \ zval _c; \ INIT_ZVAL( _c); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) static inline zend_bool zend_is_function_or_method_call(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; return ((type & ZEND_PARSED_METHOD_CALL) || (type == ZEND_PARSED_FUNCTION_CALL)); } /* }}} */ void zend_do_binary_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_unary_op(zend_uchar op, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); GET_NODE(result, opline->result); SET_UNUSED(opline->op2); } /* }}} */ #define MAKE_NOP(opline) { opline->opcode = ZEND_NOP; memset(&opline->result,0,sizeof(opline->result)); memset(&opline->op1,0,sizeof(opline->op1)); memset(&opline->op2,0,sizeof(opline->op2)); opline->result_type=opline->op1_type=opline->op2_type=IS_UNUSED; } static void zend_do_op_data(zend_op *data_op, const znode *value TSRMLS_DC) /* {{{ */ { data_op->opcode = ZEND_OP_DATA; SET_NODE(data_op->op1, value); SET_UNUSED(data_op->op2); } /* }}} */ void zend_do_binary_assign_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; switch (last_op->opcode) { case ZEND_FETCH_OBJ_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, op2 TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; case ZEND_FETCH_DIM_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_DIM; zend_do_op_data(opline, op2 TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result,last_op->result); return; default: break; } } opline->opcode = op; SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void fetch_simple_variable_ex(znode *result, znode *varname, int bp, zend_uchar op TSRMLS_DC) /* {{{ */ { zend_op opline; zend_op *opline_ptr; zend_llist *fetch_list_ptr; if (varname->op_type == IS_CONST) { ulong hash = 0; if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } else if (IS_INTERNED(Z_STRVAL(varname->u.constant))) { hash = INTERNED_HASH(Z_STRVAL(varname->u.constant)); } if (!zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC) && !(varname->u.constant.value.str.len == (sizeof("this")-1) && !memcmp(varname->u.constant.value.str.val, "this", sizeof("this"))) && (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE)) { result->op_type = IS_CV; result->u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC); varname->u.constant.value.str.val = (char*)CG(active_op_array)->vars[result->u.op.var].name; result->EA = 0; return; } } if (bp) { opline_ptr = &opline; init_op(opline_ptr TSRMLS_CC); } else { opline_ptr = get_next_op(CG(active_op_array) TSRMLS_CC); } opline_ptr->opcode = op; opline_ptr->result_type = IS_VAR; opline_ptr->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline_ptr->op1, varname); GET_NODE(result, opline_ptr->result); SET_UNUSED(opline_ptr->op2); opline_ptr->extended_value = ZEND_FETCH_LOCAL; if (varname->op_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline_ptr->op1.constant); if (zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC)) { opline_ptr->extended_value = ZEND_FETCH_GLOBAL; } } if (bp) { zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); zend_llist_add_element(fetch_list_ptr, opline_ptr); } } /* }}} */ void fetch_simple_variable(znode *result, znode *varname, int bp TSRMLS_DC) /* {{{ */ { /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ fetch_simple_variable_ex(result, varname, bp, ZEND_FETCH_W TSRMLS_CC); } /* }}} */ void zend_do_fetch_static_member(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { znode class_node; zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline_ptr; zend_op opline; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); } zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (result->op_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[result->u.op.var].name), CG(active_op_array)->vars[result->u.op.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } GET_NODE(result,opline.result); opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; opline_ptr = &opline; zend_llist_add_element(fetch_list_ptr, &opline); } else { le = fetch_list_ptr->head; opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode != ZEND_FETCH_W && opline_ptr->op1_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[opline_ptr->op1.var].name), CG(active_op_array)->vars[opline_ptr->op1.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; COPY_NODE(opline_ptr->op1, opline.result); zend_llist_prepend_element(fetch_list_ptr, &opline); } else { if (opline_ptr->op1_type == IS_CONST) { GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op1.constant); } if (class_node.op_type == IS_CONST) { opline_ptr->op2_type = IS_CONST; opline_ptr->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline_ptr->op2, &class_node); } opline_ptr->extended_value |= ZEND_FETCH_STATIC_MEMBER; } } } /* }}} */ void fetch_array_begin(znode *result, znode *varname, znode *first_dim TSRMLS_DC) /* {{{ */ { fetch_simple_variable(result, varname, 1 TSRMLS_CC); fetch_array_dim(result, result, first_dim TSRMLS_CC); } /* }}} */ void fetch_array_dim(znode *result, const znode *parent, const znode *dim TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (zend_is_function_or_method_call(parent)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, parent); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_DIM_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, parent); SET_NODE(opline.op2, dim); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline.op2.constant)), Z_STRLEN(CONSTANT(opline.op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline.op2.constant)); ZVAL_LONG(&CONSTANT(opline.op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline.op2.constant); } } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void fetch_string_offset(znode *result, const znode *parent, const znode *offset TSRMLS_DC) /* {{{ */ { fetch_array_dim(result, parent, offset TSRMLS_CC); } /* }}} */ void zend_do_print(znode *result, const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->opcode = ZEND_PRINT; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_echo(const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ECHO; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_abstract_method(const znode *function_name, znode *modifiers, const znode *body TSRMLS_DC) /* {{{ */ { char *method_type; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { Z_LVAL(modifiers->u.constant) |= ZEND_ACC_ABSTRACT; method_type = "Interface"; } else { method_type = "Abstract"; } if (modifiers->u.constant.value.lval & ZEND_ACC_ABSTRACT) { if(modifiers->u.constant.value.lval & ZEND_ACC_PRIVATE) { zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot be declared private", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } if (Z_LVAL(body->u.constant) == ZEND_ACC_ABSTRACT) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_RAISE_ABSTRACT_ERROR; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } else { /* we had code in the function body */ zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot contain body", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } else { if (body->u.constant.value.lval == ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Non-abstract method %s::%s() must contain body", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } } /* }}} */ static zend_bool opline_is_fetch_this(const zend_op *opline TSRMLS_DC) /* {{{ */ { if ((opline->opcode == ZEND_FETCH_W) && (opline->op1_type == IS_CONST) && (Z_TYPE(CONSTANT(opline->op1.constant)) == IS_STRING) && (Z_HASH_P(&CONSTANT(opline->op1.constant)) == THIS_HASHVAL) && (Z_STRLEN(CONSTANT(opline->op1.constant)) == (sizeof("this")-1)) && !memcmp(Z_STRVAL(CONSTANT(opline->op1.constant)), "this", sizeof("this"))) { return 1; } else { return 0; } } /* }}} */ void zend_do_assign(znode *result, znode *variable, znode *value TSRMLS_DC) /* {{{ */ { int last_op_number; zend_op *opline; if (value->op_type == IS_CV) { zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (fetch_list_ptr && fetch_list_ptr->head) { opline = (zend_op *)fetch_list_ptr->head->data; if (opline->opcode == ZEND_FETCH_DIM_W && opline->op1_type == IS_CV && opline->op1.var == value->u.op.var) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_R; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->op1_type = IS_CONST; LITERAL_STRINGL(opline->op1, CG(active_op_array)->vars[value->u.op.var].name, CG(active_op_array)->vars[value->u.op.var].name_len, 1); CALCULATE_LITERAL_HASH(opline->op1.constant); SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_LOCAL; GET_NODE(value, opline->result); } } } zend_do_end_variable_parse(variable, BP_VAR_W, 0 TSRMLS_CC); last_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (variable->op_type == IS_CV) { if (variable->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (variable->op_type == IS_VAR) { int n = 0; while (last_op_number - n > 0) { zend_op *last_op; last_op = &CG(active_op_array)->opcodes[last_op_number-n-1]; if (last_op->result_type == IS_VAR && last_op->result.var == variable->u.op.var) { if (last_op->opcode == ZEND_FETCH_OBJ_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, value TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (last_op->opcode == ZEND_FETCH_DIM_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ /* TBFixed: this can realloc opcodes, leaving last_op pointing wrong */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_DIM; zend_do_op_data(opline, value TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (opline_is_fetch_this(last_op TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } else { break; } } n++; } } opline->opcode = ZEND_ASSIGN; SET_NODE(opline->op1, variable); SET_NODE(opline->op2, value); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_assign_ref(znode *result, const znode *lvar, const znode *rvar TSRMLS_DC) /* {{{ */ { zend_op *opline; if (lvar->op_type == IS_CV) { if (lvar->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (lvar->op_type == IS_VAR) { int last_op_number = get_next_op_number(CG(active_op_array)); if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline_is_fetch_this(opline TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ASSIGN_REF; if (zend_is_function_or_method_call(rvar)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } else if (rvar->EA & ZEND_PARSED_NEW) { opline->extended_value = ZEND_RETURNS_NEW; } else { opline->extended_value = 0; } if (result) { opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } else { opline->result_type = IS_UNUSED | EXT_TYPE_UNUSED; } SET_NODE(opline->op1, lvar); SET_NODE(opline->op2, rvar); } /* }}} */ static inline void do_begin_loop(TSRMLS_D) /* {{{ */ { zend_brk_cont_element *brk_cont_element; int parent; parent = CG(context).current_brk_cont; CG(context).current_brk_cont = CG(active_op_array)->last_brk_cont; brk_cont_element = get_next_brk_cont_element(CG(active_op_array)); brk_cont_element->start = get_next_op_number(CG(active_op_array)); brk_cont_element->parent = parent; } /* }}} */ static inline void do_end_loop(int cont_addr, int has_loop_var TSRMLS_DC) /* {{{ */ { if (!has_loop_var) { /* The start fileld is used to free temporary variables in case of exceptions. * We won't try to free something of we don't have loop variable. */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].start = -1; } CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = cont_addr; CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; } /* }}} */ void zend_do_while_cond(const znode *expr, znode *close_bracket_token TSRMLS_DC) /* {{{ */ { int while_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, expr); close_bracket_token->u.op.opline_num = while_cond_op_number; SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_while_end(const znode *while_token, const znode *close_bracket_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* add unconditional jump */ opline->opcode = ZEND_JMP; opline->op1.opline_num = while_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* update while's conditional jmp */ CG(active_op_array)->opcodes[close_bracket_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); do_end_loop(while_token->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_cond(const znode *expr, znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { int for_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZNZ; SET_NODE(opline->op1, expr); /* the conditional expression */ second_semicolon_token->u.op.opline_num = for_cond_op_number; SET_UNUSED(opline->op2); } /* }}} */ void zend_do_for_before_statement(const znode *cond_start, const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = cond_start->u.op.opline_num; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_end(const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = second_semicolon_token->u.op.opline_num+1; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_end_loop(second_semicolon_token->u.op.opline_num+1, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_pre_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_PRE_INC)?ZEND_PRE_INC_OBJ:ZEND_PRE_DEC_OBJ; last_op->result_type = IS_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_post_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_POST_INC)?ZEND_POST_INC_OBJ:ZEND_POST_DEC_OBJ; last_op->result_type = IS_TMP_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_if_cond(const znode *cond, znode *closing_bracket_token TSRMLS_DC) /* {{{ */ { int if_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); closing_bracket_token->u.op.opline_num = if_cond_op_number; SET_UNUSED(opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_if_after_statement(const znode *closing_bracket_token, unsigned char initialize TSRMLS_DC) /* {{{ */ { int if_end_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; /* save for backpatching */ if (initialize) { zend_llist jmp_list; zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); } zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &if_end_op_number); CG(active_op_array)->opcodes[closing_bracket_token->u.op.opline_num].op2.opline_num = if_end_op_number+1; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_if_end(TSRMLS_D) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_llist *jmp_list_ptr; zend_llist_element *le; zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); for (le=jmp_list_ptr->head; le; le = le->next) { CG(active_op_array)->opcodes[*((int *) le->data)].op1.opline_num = next_op_number; } zend_llist_destroy(jmp_list_ptr); zend_stack_del_top(&CG(bp_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_check_writable_variable(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; if (type & ZEND_PARSED_METHOD_CALL) { zend_error(E_COMPILE_ERROR, "Can't use method return value in write context"); } if (type == ZEND_PARSED_FUNCTION_CALL) { zend_error(E_COMPILE_ERROR, "Can't use function return value in write context"); } } /* }}} */ void zend_do_begin_variable_parse(TSRMLS_D) /* {{{ */ { zend_llist fetch_list; zend_llist_init(&fetch_list, sizeof(zend_op), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &fetch_list, sizeof(zend_llist)); } /* }}} */ void zend_do_end_variable_parse(znode *variable, int type, int arg_offset TSRMLS_DC) /* {{{ */ { zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline = NULL; zend_op *opline_ptr; zend_uint this_var = -1; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); le = fetch_list_ptr->head; /* TODO: $foo->x->y->z = 1 should fetch "x" and "y" for R or RW, not just W */ if (le) { opline_ptr = (zend_op *)le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { /* convert to FETCH_?(this) into IS_CV */ if (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE) { this_var = opline_ptr->result.var; if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), Z_STRVAL(CONSTANT(opline_ptr->op1.constant)), Z_STRLEN(CONSTANT(opline_ptr->op1.constant)), Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC); Z_TYPE(CONSTANT(opline_ptr->op1.constant)) = IS_NULL; } else { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); } le = le->next; if (variable->op_type == IS_VAR && variable->u.op.var == this_var) { variable->op_type = IS_CV; variable->u.op.var = CG(active_op_array)->this_var; } } else if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } while (le) { opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode == ZEND_SEPARATE) { if (type != BP_VAR_R && type != BP_VAR_IS) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); } le = le->next; continue; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); if (opline->op1_type == IS_VAR && opline->op1.var == this_var) { opline->op1_type = IS_CV; opline->op1.var = CG(active_op_array)->this_var; } switch (type) { case BP_VAR_R: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode -= 3; break; case BP_VAR_W: break; case BP_VAR_RW: opline->opcode += 3; break; case BP_VAR_IS: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode += 6; /* 3+3 */ break; case BP_VAR_FUNC_ARG: opline->opcode += 9; /* 3+3+3 */ opline->extended_value |= arg_offset; break; case BP_VAR_UNSET: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for unsetting"); } opline->opcode += 12; /* 3+3+3+3 */ break; } le = le->next; } if (opline && type == BP_VAR_W && arg_offset) { opline->extended_value |= ZEND_FETCH_MAKE_REF; } } zend_llist_destroy(fetch_list_ptr); zend_stack_del_top(&CG(bp_stack)); } /* }}} */ void zend_do_add_string(znode *result, const znode *op1, znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline; if (Z_STRLEN(op2->u.constant) > 1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_STRING; } else if (Z_STRLEN(op2->u.constant) == 1) { int ch = *Z_STRVAL(op2->u.constant); /* Free memory and use ZEND_ADD_CHAR in case of 1 character strings */ efree(Z_STRVAL(op2->u.constant)); ZVAL_LONG(&op2->u.constant, ch); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_CHAR; } else { /* String can be empty after a variable at the end of a heredoc */ efree(Z_STRVAL(op2->u.constant)); return; } if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_add_variable(znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_VAR; if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_free(znode *op1 TSRMLS_DC) /* {{{ */ { if (op1->op_type==IS_TMP_VAR) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else if (op1->op_type==IS_VAR) { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; while (opline->opcode == ZEND_END_SILENCE || opline->opcode == ZEND_EXT_FCALL_END || opline->opcode == ZEND_OP_DATA) { opline--; } if (opline->result_type == IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_FETCH_R || opline->opcode == ZEND_FETCH_DIM_R || opline->opcode == ZEND_FETCH_OBJ_R || opline->opcode == ZEND_QM_ASSIGN_VAR) { /* It's very rare and useless case. It's better to use additional FREE opcode and simplify the FETCH handlers their selves */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else { opline->result_type |= EXT_TYPE_UNUSED; } } else { while (opline>CG(active_op_array)->opcodes) { if (opline->opcode == ZEND_FETCH_DIM_R && opline->op1_type == IS_VAR && opline->op1.var == op1->u.op.var) { /* This should the end of a list() construct * Mark its result as unused */ opline->extended_value = ZEND_FETCH_STANDARD; break; } else if (opline->result_type==IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_NEW) { opline->result_type |= EXT_TYPE_UNUSED; } break; } opline--; } } } else if (op1->op_type == IS_CONST) { zval_dtor(&op1->u.constant); } } /* }}} */ int zend_do_verify_access_types(const znode *current_access_type, const znode *new_modifier) /* {{{ */ { if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_PPP_MASK) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Multiple access type modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_ABSTRACT) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Multiple abstract modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_STATIC) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Multiple static modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_FINAL) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Multiple final modifiers are not allowed"); } if (((Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)) & (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) == (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Cannot use the final modifier on an abstract class member"); } return (Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)); } /* }}} */ void zend_do_begin_function_declaration(znode *function_token, znode *function_name, int is_method, int return_reference, znode *fn_flags_znode TSRMLS_DC) /* {{{ */ { zend_op_array op_array; char *name = function_name->u.constant.value.str.val; int name_len = function_name->u.constant.value.str.len; int function_begin_line = function_token->u.op.opline_num; zend_uint fn_flags; const char *lcname; zend_bool orig_interactive; ALLOCA_FLAG(use_heap) if (is_method) { if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((Z_LVAL(fn_flags_znode->u.constant) & ~(ZEND_ACC_STATIC|ZEND_ACC_PUBLIC))) { zend_error(E_COMPILE_ERROR, "Access type for interface method %s::%s() must be omitted", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } Z_LVAL(fn_flags_znode->u.constant) |= ZEND_ACC_ABSTRACT; /* propagates to the rest of the parser */ } fn_flags = Z_LVAL(fn_flags_znode->u.constant); /* must be done *after* the above check */ } else { fn_flags = 0; } if ((fn_flags & ZEND_ACC_STATIC) && (fn_flags & ZEND_ACC_ABSTRACT) && !(CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_STRICT, "Static function %s%s%s() should not be abstract", is_method ? CG(active_class_entry)->name : "", is_method ? "::" : "", Z_STRVAL(function_name->u.constant)); } function_token->u.op_array = CG(active_op_array); orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(&op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; op_array.function_name = name; if (return_reference) { op_array.fn_flags |= ZEND_ACC_RETURN_REFERENCE; } op_array.fn_flags |= fn_flags; op_array.scope = is_method?CG(active_class_entry):NULL; op_array.prototype = NULL; op_array.line_start = zend_get_compiled_lineno(TSRMLS_C); if (is_method) { int result; lcname = zend_new_interned_string(zend_str_tolower_dup(name, name_len), name_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lcname)) { result = zend_hash_quick_add(&CG(active_class_entry)->function_table, lcname, name_len+1, INTERNED_HASH(lcname), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } else { result = zend_hash_add(&CG(active_class_entry)->function_table, lcname, name_len+1, &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } if (result == FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::%s()", CG(active_class_entry)->name, name); } zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); if (fn_flags & ZEND_ACC_ABSTRACT) { CG(active_class_entry)->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (!(fn_flags & ZEND_ACC_PPP_MASK)) { fn_flags |= ZEND_ACC_PUBLIC; } if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } } } else { char *class_lcname; class_lcname = do_alloca(CG(active_class_entry)->name_length + 1, use_heap); zend_str_tolower_copy(class_lcname, CG(active_class_entry)->name, CG(active_class_entry)->name_length); /* Improve after RC: cache the lowercase class name */ if ((CG(active_class_entry)->name_length == name_len) && ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT) && (!memcmp(class_lcname, lcname, name_len))) { if (!CG(active_class_entry)->constructor) { CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } } else if ((name_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)))) { if (CG(active_class_entry)->constructor) { zend_error(E_STRICT, "Redefining already defined constructor for class %s", CG(active_class_entry)->name); } CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1))) { CG(active_class_entry)->destructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1))) { CG(active_class_entry)->clone = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } CG(active_class_entry)->__call = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } CG(active_class_entry)->__callstatic = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } CG(active_class_entry)->__get = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } CG(active_class_entry)->__set = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } CG(active_class_entry)->__unset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } CG(active_class_entry)->__isset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } CG(active_class_entry)->__tostring = (zend_function *) CG(active_op_array); } else if (!(fn_flags & ZEND_ACC_STATIC)) { CG(active_op_array)->fn_flags |= ZEND_ACC_ALLOW_STATIC; } free_alloca(class_lcname, use_heap); } str_efree(lcname); } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zval key; if (CG(current_namespace)) { /* Prefix function name with current namespcae name */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, function_name TSRMLS_CC); op_array.function_name = Z_STRVAL(tmp.u.constant); name_len = Z_STRLEN(tmp.u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), name_len); } else { lcname = zend_str_tolower_dup(name, name_len); } opline->opcode = ZEND_DECLARE_FUNCTION; opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, name_len TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; LITERAL_STRINGL(opline->op2, lcname, name_len, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); opline->extended_value = ZEND_DECLARE_FUNCTION; zend_hash_quick_update(CG(function_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); } if (CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_NOP; opline->lineno = function_begin_line; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } { /* Push a seperator to the switch and foreach stacks */ zend_switch_entry switch_entry; switch_entry.cond.op_type = IS_UNUSED; switch_entry.default_case = 0; switch_entry.control_var = 0; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); { /* Foreach stack separator */ zend_op dummy_opline; dummy_opline.result_type = IS_UNUSED; dummy_opline.op1_type = IS_UNUSED; zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); } } if (CG(doc_comment)) { CG(active_op_array)->doc_comment = CG(doc_comment); CG(active_op_array)->doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_begin_lambda_function_declaration(znode *result, znode *function_token, int return_reference, int is_static TSRMLS_DC) /* {{{ */ { znode function_name; zend_op_array *current_op_array = CG(active_op_array); int current_op_number = get_next_op_number(CG(active_op_array)); zend_op *current_op; function_name.op_type = IS_CONST; ZVAL_STRINGL(&function_name.u.constant, "{closure}", sizeof("{closure}")-1, 1); zend_do_begin_function_declaration(function_token, &function_name, 0, return_reference, NULL TSRMLS_CC); result->op_type = IS_TMP_VAR; result->u.op.var = get_temporary_variable(current_op_array); current_op = &current_op_array->opcodes[current_op_number]; current_op->opcode = ZEND_DECLARE_LAMBDA_FUNCTION; zend_del_literal(current_op_array, current_op->op2.constant); SET_UNUSED(current_op->op2); SET_NODE(current_op->result, result); if (is_static) { CG(active_op_array)->fn_flags |= ZEND_ACC_STATIC; } CG(active_op_array)->fn_flags |= ZEND_ACC_CLOSURE; } /* }}} */ void zend_do_handle_exception(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_HANDLE_EXCEPTION; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_function_declaration(const znode *function_token TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; zend_do_extended_info(TSRMLS_C); zend_do_return(NULL, 0 TSRMLS_CC); pass_two(CG(active_op_array) TSRMLS_CC); zend_release_labels(TSRMLS_C); if (CG(active_class_entry)) { zend_check_magic_method_implementation(CG(active_class_entry), (zend_function*)CG(active_op_array), E_COMPILE_ERROR TSRMLS_CC); } else { /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(CG(active_op_array)->function_name); zend_str_tolower_copy(lcname, CG(active_op_array)->function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME)) && CG(active_op_array)->num_args != 1) { zend_error(E_COMPILE_ERROR, "%s() must take exactly 1 argument", ZEND_AUTOLOAD_FUNC_NAME); } } CG(active_op_array)->line_end = zend_get_compiled_lineno(TSRMLS_C); CG(active_op_array) = function_token->u.op_array; /* Pop the switch and foreach seperators */ zend_stack_del_top(&CG(switch_cond_stack)); zend_stack_del_top(&CG(foreach_copy_stack)); } /* }}} */ void zend_do_receive_arg(zend_uchar op, znode *varname, const znode *offset, const znode *initialization, znode *class_type, zend_uchar pass_by_reference TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_arg_info *cur_arg_info; znode var; if (class_type->op_type == IS_CONST && Z_TYPE(class_type->u.constant) == IS_STRING && Z_STRLEN(class_type->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_type->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } if (zend_is_auto_global_quick(Z_STRVAL(varname->u.constant), Z_STRLEN(varname->u.constant), 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign auto-global variable %s", Z_STRVAL(varname->u.constant)); } else { var.op_type = IS_CV; var.u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(varname->u.constant) = (char*)CG(active_op_array)->vars[var.u.op.var].name; var.EA = 0; if (CG(active_op_array)->vars[var.u.op.var].hash_value == THIS_HASHVAL && Z_STRLEN(varname->u.constant) == sizeof("this")-1 && !memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this")-1)) { if (CG(active_op_array)->scope && (CG(active_op_array)->fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } CG(active_op_array)->this_var = var.u.op.var; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->num_args++; opline->opcode = op; SET_NODE(opline->result, &var); SET_NODE(opline->op1, offset); if (op == ZEND_RECV_INIT) { SET_NODE(opline->op2, initialization); } else { CG(active_op_array)->required_num_args = CG(active_op_array)->num_args; SET_UNUSED(opline->op2); } CG(active_op_array)->arg_info = erealloc(CG(active_op_array)->arg_info, sizeof(zend_arg_info)*(CG(active_op_array)->num_args)); cur_arg_info = &CG(active_op_array)->arg_info[CG(active_op_array)->num_args-1]; cur_arg_info->name = zend_new_interned_string(estrndup(varname->u.constant.value.str.val, varname->u.constant.value.str.len), varname->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->name_len = varname->u.constant.value.str.len; cur_arg_info->type_hint = 0; cur_arg_info->allow_null = 1; cur_arg_info->pass_by_reference = pass_by_reference; cur_arg_info->class_name = NULL; cur_arg_info->class_name_len = 0; if (class_type->op_type != IS_UNUSED) { cur_arg_info->allow_null = 0; if (class_type->u.constant.type != IS_NULL) { if (class_type->u.constant.type == IS_ARRAY) { cur_arg_info->type_hint = IS_ARRAY; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else if (Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Default value for parameters with array type hint can only be an array or NULL"); } } } else if (class_type->u.constant.type == IS_CALLABLE) { cur_arg_info->type_hint = IS_CALLABLE; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with callable type hint can only be NULL"); } } } else { cur_arg_info->type_hint = IS_OBJECT; if (ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_type->u.constant), Z_STRLEN(class_type->u.constant))) { zend_resolve_class_name(class_type, opline->extended_value, 1 TSRMLS_CC); } Z_STRVAL(class_type->u.constant) = (char*)zend_new_interned_string(class_type->u.constant.value.str.val, class_type->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->class_name = class_type->u.constant.value.str.val; cur_arg_info->class_name_len = class_type->u.constant.value.str.len; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with a class type hint can only be NULL"); } } } } } } /* }}} */ int zend_do_begin_function_call(znode *function_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { zend_function *function; char *lcname; char *is_compound = memchr(Z_STRVAL(function_name->u.constant), '\\', Z_STRLEN(function_name->u.constant)); zend_resolve_non_class_name(function_name, check_namespace TSRMLS_CC); if (check_namespace && CG(current_namespace) && !is_compound) { /* We assume we call function from the current namespace if it is not prefixed. */ /* In run-time PHP will check for function with full name and internal function with short name */ zend_do_begin_dynamic_function_call(function_name, 1 TSRMLS_CC); return 1; } lcname = zend_str_tolower_dup(function_name->u.constant.value.str.val, function_name->u.constant.value.str.len); if ((zend_hash_find(CG(function_table), lcname, function_name->u.constant.value.str.len+1, (void **) &function)==FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_FUNCTIONS) && (function->type == ZEND_INTERNAL_FUNCTION))) { zend_do_begin_dynamic_function_call(function_name, 0 TSRMLS_CC); efree(lcname); return 1; /* Dynamic */ } efree(function_name->u.constant.value.str.val); function_name->u.constant.value.str.val = lcname; zend_stack_push(&CG(function_call_stack), (void *) &function, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 0; } /* }}} */ void zend_do_begin_method_call(znode *left_bracket TSRMLS_DC) /* {{{ */ { zend_op *last_op; int last_op_number; unsigned char *ptr = NULL; zend_do_end_variable_parse(left_bracket, BP_VAR_R, 0 TSRMLS_CC); zend_do_begin_variable_parse(TSRMLS_C); last_op_number = get_next_op_number(CG(active_op_array))-1; last_op = &CG(active_op_array)->opcodes[last_op_number]; if ((last_op->op2_type == IS_CONST) && (Z_TYPE(CONSTANT(last_op->op2.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(last_op->op2.constant)) == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !zend_binary_strcasecmp(Z_STRVAL(CONSTANT(last_op->op2.constant)), Z_STRLEN(CONSTANT(last_op->op2.constant)), ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1)) { zend_error(E_COMPILE_ERROR, "Cannot call __clone() method on objects - use 'clone $obj' instead"); } if (last_op->opcode == ZEND_FETCH_OBJ_R) { if (last_op->op2_type == IS_CONST) { zval name; name = CONSTANT(last_op->op2.constant); if (!IS_INTERNED(Z_STRVAL(name))) { Z_STRVAL(name) = estrndup(Z_STRVAL(name), Z_STRLEN(name)); } FREE_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); last_op->op2.constant = zend_add_func_name_literal(CG(active_op_array), &name TSRMLS_CC); GET_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); } last_op->opcode = ZEND_INIT_METHOD_CALL; SET_UNUSED(last_op->result); Z_LVAL(left_bracket->u.constant) = ZEND_INIT_FCALL_BY_NAME; } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (left_bracket->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &left_bracket->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, left_bracket); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_do_clone(znode *result, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CLONE; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_begin_dynamic_function_call(znode *function_name, int ns_call TSRMLS_DC) /* {{{ */ { unsigned char *ptr = NULL; zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (ns_call) { /* In run-time PHP will check for function with full name and internal function with short name */ opline->opcode = ZEND_INIT_NS_FCALL_BY_NAME; SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_ns_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (function_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, function_name); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_resolve_non_class_name(znode *element_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; int len; zval **ns; char *lcname, *compound = memchr(Z_STRVAL(element_name->u.constant), '\\', Z_STRLEN(element_name->u.constant)); if (Z_STRVAL(element_name->u.constant)[0] == '\\') { /* name starts with \ so it is known and unambiguos, nothing to do here but shorten it */ memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+1, Z_STRLEN(element_name->u.constant)); --Z_STRLEN(element_name->u.constant); return; } if(!check_namespace) { return; } if (compound && CG(current_import)) { len = compound - Z_STRVAL(element_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(element_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(element_name->u.constant) -= len; memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+len, Z_STRLEN(element_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, element_name TSRMLS_CC); *element_name = tmp; efree(lcname); return; } efree(lcname); } if (CG(current_namespace)) { tmp = *element_name; Z_STRLEN(tmp.u.constant) = sizeof("\\")-1 + Z_STRLEN(element_name->u.constant) + Z_STRLEN_P(CG(current_namespace)); Z_STRVAL(tmp.u.constant) = (char *) emalloc(Z_STRLEN(tmp.u.constant)+1); memcpy(Z_STRVAL(tmp.u.constant), Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace))]), "\\", sizeof("\\")-1); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace)) + sizeof("\\")-1]), Z_STRVAL(element_name->u.constant), Z_STRLEN(element_name->u.constant)+1); STR_FREE(Z_STRVAL(element_name->u.constant)); *element_name = tmp; } } /* }}} */ void zend_resolve_class_name(znode *class_name, ulong fetch_type, int check_ns_name TSRMLS_DC) /* {{{ */ { char *compound; char *lcname; zval **ns; znode tmp; int len; compound = memchr(Z_STRVAL(class_name->u.constant), '\\', Z_STRLEN(class_name->u.constant)); if (compound) { /* This is a compound class name that contains namespace prefix */ if (Z_STRVAL(class_name->u.constant)[0] == '\\') { /* The STRING name has "\" prefix */ Z_STRLEN(class_name->u.constant) -= 1; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+1, Z_STRLEN(class_name->u.constant)+1); Z_STRVAL(class_name->u.constant) = erealloc( Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1); if (ZEND_FETCH_CLASS_DEFAULT != zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "'\\%s' is an invalid class name", Z_STRVAL(class_name->u.constant)); } } else { if (CG(current_import)) { len = compound - Z_STRVAL(class_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(class_name->u.constant) -= len; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+len, Z_STRLEN(class_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; efree(lcname); return; } efree(lcname); } /* Here name is not prefixed with \ and not imported */ if (CG(current_namespace)) { tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } } } else if (CG(current_import) || CG(current_namespace)) { /* this is a plain name (without \) */ lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns) == SUCCESS) { /* The given name is an import name. Substitute it. */ zval_dtor(&class_name->u.constant); class_name->u.constant = **ns; zval_copy_ctor(&class_name->u.constant); } else if (CG(current_namespace)) { /* plain name, no import - prepend current namespace to it */ tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } efree(lcname); } } /* }}} */ void zend_do_fetch_class(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { long fetch_class_op_number; zend_op *opline; if (class_name->op_type == IS_CONST && Z_TYPE(class_name->u.constant) == IS_STRING && Z_STRLEN(class_name->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_name->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } fetch_class_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CLASS; SET_UNUSED(opline->op1); opline->extended_value = ZEND_FETCH_CLASS_GLOBAL; CG(catch_begin) = fetch_class_op_number; if (class_name->op_type == IS_CONST) { int fetch_type; fetch_type = zend_get_class_fetch_type(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); switch (fetch_type) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: SET_UNUSED(opline->op2); opline->extended_value = fetch_type; zval_dtor(&class_name->u.constant); break; default: zend_resolve_class_name(class_name, opline->extended_value, 0 TSRMLS_CC); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_name->u.constant TSRMLS_CC); break; } } else { SET_NODE(opline->op2, class_name); } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; /* FIXME: Hack so that INIT_FCALL_BY_NAME still knows this is a class */ GET_NODE(result, opline->result); result->EA = opline->extended_value; } /* }}} */ void zend_do_label(znode *label TSRMLS_DC) /* {{{ */ { zend_label dest; if (!CG(context).labels) { ALLOC_HASHTABLE(CG(context).labels); zend_hash_init(CG(context).labels, 4, NULL, NULL, 0); } dest.brk_cont = CG(context).current_brk_cont; dest.opline_num = get_next_op_number(CG(active_op_array)); if (zend_hash_add(CG(context).labels, Z_STRVAL(label->u.constant), Z_STRLEN(label->u.constant) + 1, (void**)&dest, sizeof(zend_label), NULL) == FAILURE) { zend_error(E_COMPILE_ERROR, "Label '%s' already defined", Z_STRVAL(label->u.constant)); } /* Done with label now */ zval_dtor(&label->u.constant); } /* }}} */ void zend_resolve_goto_label(zend_op_array *op_array, zend_op *opline, int pass2 TSRMLS_DC) /* {{{ */ { zend_label *dest; long current, distance; zval *label; if (pass2) { label = opline->op2.zv; } else { label = &CONSTANT_EX(op_array, opline->op2.constant); } if (CG(context).labels == NULL || zend_hash_find(CG(context).labels, Z_STRVAL_P(label), Z_STRLEN_P(label)+1, (void**)&dest) == FAILURE) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; zend_error(E_COMPILE_ERROR, "'goto' to undefined label '%s'", Z_STRVAL_P(label)); } else { /* Label is not defined. Delay to pass 2. */ INC_BPC(op_array); return; } } opline->op1.opline_num = dest->opline_num; zval_dtor(label); Z_TYPE_P(label) = IS_NULL; /* Check that we are not moving into loop or switch */ current = opline->extended_value; for (distance = 0; current != dest->brk_cont; distance++) { if (current == -1) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; } zend_error(E_COMPILE_ERROR, "'goto' into loop or switch statement is disallowed"); } current = op_array->brk_cont_array[current].parent; } if (distance == 0) { /* Nothing to break out of, optimize to ZEND_JMP */ opline->opcode = ZEND_JMP; opline->extended_value = 0; SET_UNUSED(opline->op2); } else { /* Set real break distance */ ZVAL_LONG(label, distance); } if (pass2) { DEC_BPC(op_array); } } /* }}} */ void zend_do_goto(const znode *label TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_GOTO; opline->extended_value = CG(context).current_brk_cont; SET_UNUSED(opline->op1); SET_NODE(opline->op2, label); zend_resolve_goto_label(CG(active_op_array), opline, 0 TSRMLS_CC); } /* }}} */ void zend_release_labels(TSRMLS_D) /* {{{ */ { if (CG(context).labels) { zend_hash_destroy(CG(context).labels); FREE_HASHTABLE(CG(context).labels); } if (!zend_stack_is_empty(&CG(context_stack))) { zend_compiler_context *ctx; zend_stack_top(&CG(context_stack), (void**)&ctx); CG(context) = *ctx; zend_stack_del_top(&CG(context_stack)); } } /* }}} */ void zend_do_build_full_name(znode *result, znode *prefix, znode *name, int is_class_member TSRMLS_DC) /* {{{ */ { zend_uint length; if (!result) { result = prefix; } else { *result = *prefix; } if (is_class_member) { length = sizeof("::")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "::", sizeof("::")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("::")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } else { length = sizeof("\\")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "\\", sizeof("\\")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("\\")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } } /* }}} */ int zend_do_begin_class_member_function_call(znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { znode class_node; unsigned char *ptr = NULL; zend_op *opline; if (method_name->op_type == IS_CONST) { char *lcname = zend_str_tolower_dup(Z_STRVAL(method_name->u.constant), Z_STRLEN(method_name->u.constant)); if ((sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == Z_STRLEN(method_name->u.constant) && memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == 0) { zval_dtor(&method_name->u.constant); method_name->op_type = IS_UNUSED; } efree(lcname); } if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; opline = get_next_op(CG(active_op_array) TSRMLS_CC); } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->extended_value = class_node.EA ; } opline->opcode = ZEND_INIT_STATIC_METHOD_CALL; if (class_node.op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, &class_node); } if (method_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &method_name->u.constant TSRMLS_CC); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } } else { SET_NODE(opline->op2, method_name); } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 1; /* Dynamic */ } /* }}} */ void zend_do_end_function_call(znode *function_name, znode *result, const znode *argument_list, int is_method, int is_dynamic_fcall TSRMLS_DC) /* {{{ */ { zend_op *opline; if (is_method && function_name && function_name->op_type == IS_UNUSED) { /* clone */ if (Z_LVAL(argument_list->u.constant) != 0) { zend_error(E_WARNING, "Clone method does not require arguments"); } opline = &CG(active_op_array)->opcodes[Z_LVAL(function_name->u.constant)]; } else { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (!is_method && !is_dynamic_fcall && function_name->op_type==IS_CONST) { opline->opcode = ZEND_DO_FCALL; SET_NODE(opline->op1, function_name); CALCULATE_LITERAL_HASH(opline->op1.constant); GET_CACHE_SLOT(opline->op1.constant); } else { opline->opcode = ZEND_DO_FCALL_BY_NAME; SET_UNUSED(opline->op1); } } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(result, opline->result) ; SET_UNUSED(opline->op2); zend_stack_del_top(&CG(function_call_stack)); opline->extended_value = Z_LVAL(argument_list->u.constant); } /* }}} */ void zend_do_pass_param(znode *param, zend_uchar op, int offset TSRMLS_DC) /* {{{ */ { zend_op *opline; int original_op=op; zend_function **function_ptr_ptr, *function_ptr; int send_by_reference; int send_function = 0; zend_stack_top(&CG(function_call_stack), (void **) &function_ptr_ptr); function_ptr = *function_ptr_ptr; if (original_op == ZEND_SEND_REF) { if (function_ptr && function_ptr->common.function_name && function_ptr->common.type == ZEND_USER_FUNCTION && !ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed; " "If you would like to pass argument by reference, modify the declaration of %s().", function_ptr->common.function_name); } else { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed"); } return; } if (function_ptr) { if (ARG_MAY_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { if (param->op_type & (IS_VAR|IS_CV) && original_op != ZEND_SEND_VAL) { send_by_reference = 1; if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION | ZEND_ARG_SEND_SILENT; } } else { op = ZEND_SEND_VAL; send_by_reference = 0; } } else { send_by_reference = ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset) ? ZEND_ARG_SEND_BY_REF : 0; } } else { send_by_reference = 0; } if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION; } else if (op == ZEND_SEND_VAL && (param->op_type & (IS_VAR|IS_CV))) { op = ZEND_SEND_VAR_NO_REF; } if (op!=ZEND_SEND_VAR_NO_REF && send_by_reference==ZEND_ARG_SEND_BY_REF) { /* change to passing by reference */ switch (param->op_type) { case IS_VAR: case IS_CV: op = ZEND_SEND_REF; break; default: zend_error(E_COMPILE_ERROR, "Only variables can be passed by reference"); break; } } if (original_op == ZEND_SEND_VAR) { switch (op) { case ZEND_SEND_VAR_NO_REF: zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); break; case ZEND_SEND_VAR: if (function_ptr) { zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(param, BP_VAR_FUNC_ARG, offset TSRMLS_CC); } break; case ZEND_SEND_REF: zend_do_end_variable_parse(param, BP_VAR_W, 0 TSRMLS_CC); break; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (op == ZEND_SEND_VAR_NO_REF) { if (function_ptr) { opline->extended_value = ZEND_ARG_COMPILE_TIME_BOUND | send_by_reference | send_function; } else { opline->extended_value = send_function; } } else { if (function_ptr) { opline->extended_value = ZEND_DO_FCALL; } else { opline->extended_value = ZEND_DO_FCALL_BY_NAME; } } opline->opcode = op; SET_NODE(opline->op1, param); opline->op2.opline_num = offset; SET_UNUSED(opline->op2); } /* }}} */ static int generate_free_switch_expr(const zend_switch_entry *switch_entry TSRMLS_DC) /* {{{ */ { zend_op *opline; if (switch_entry->cond.op_type != IS_VAR && switch_entry->cond.op_type != IS_TMP_VAR) { return (switch_entry->cond.op_type == IS_UNUSED); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry->cond); SET_UNUSED(opline->op2); opline->extended_value = 0; return 0; } /* }}} */ static int generate_free_foreach_copy(const zend_op *foreach_copy TSRMLS_DC) /* {{{ */ { zend_op *opline; /* If we reach the seperator then stop applying the stack */ if (foreach_copy->result_type == IS_UNUSED && foreach_copy->op1_type == IS_UNUSED) { return 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->result_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->result); SET_UNUSED(opline->op2); opline->extended_value = 1; if (foreach_copy->op1_type != IS_UNUSED) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->op1_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->op1); SET_UNUSED(opline->op2); opline->extended_value = 0; } return 0; } /* }}} */ void zend_do_return(znode *expr, int do_end_vparse TSRMLS_DC) /* {{{ */ { zend_op *opline; int start_op_number, end_op_number; if (do_end_vparse) { if ((CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) && !zend_is_function_or_method_call(expr)) { zend_do_end_variable_parse(expr, BP_VAR_W, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(expr, BP_VAR_R, 0 TSRMLS_CC); } } start_op_number = get_next_op_number(CG(active_op_array)); #ifdef ZTS zend_stack_apply_with_argument(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_switch_expr TSRMLS_CC); zend_stack_apply_with_argument(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_foreach_copy TSRMLS_CC); #else zend_stack_apply(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_switch_expr); zend_stack_apply(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_foreach_copy); #endif end_op_number = get_next_op_number(CG(active_op_array)); while (start_op_number < end_op_number) { CG(active_op_array)->opcodes[start_op_number].extended_value |= EXT_TYPE_FREE_ON_RETURN; start_op_number++; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) ? ZEND_RETURN_BY_REF : ZEND_RETURN; if (expr) { SET_NODE(opline->op1, expr); if (do_end_vparse && zend_is_function_or_method_call(expr)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } } else { opline->op1_type = IS_CONST; LITERAL_NULL(opline->op1); } SET_UNUSED(opline->op2); } /* }}} */ static int zend_add_try_element(zend_uint try_op TSRMLS_DC) /* {{{ */ { int try_catch_offset = CG(active_op_array)->last_try_catch++; CG(active_op_array)->try_catch_array = erealloc(CG(active_op_array)->try_catch_array, sizeof(zend_try_catch_element)*CG(active_op_array)->last_try_catch); CG(active_op_array)->try_catch_array[try_catch_offset].try_op = try_op; return try_catch_offset; } /* }}} */ static void zend_add_catch_element(int offset, zend_uint catch_op TSRMLS_DC) /* {{{ */ { CG(active_op_array)->try_catch_array[offset].catch_op = catch_op; } /* }}} */ void zend_do_first_catch(znode *open_parentheses TSRMLS_DC) /* {{{ */ { open_parentheses->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_initialize_try_catch_element(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist jmp_list; zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); zend_add_catch_element(try_token->u.op.opline_num, get_next_op_number(CG(active_op_array)) TSRMLS_CC); } /* }}} */ void zend_do_mark_last_catch(const znode *first_catch, const znode *last_additional_catch TSRMLS_DC) /* {{{ */ { CG(active_op_array)->last--; zend_do_if_end(TSRMLS_C); if (last_additional_catch->u.op.opline_num == -1) { CG(active_op_array)->opcodes[first_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[first_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } else { CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_try(znode *try_token TSRMLS_DC) /* {{{ */ { try_token->u.op.opline_num = zend_add_try_element(get_next_op_number(CG(active_op_array)) TSRMLS_CC); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_catch(znode *try_token, znode *class_name, znode *catch_var, znode *first_catch TSRMLS_DC) /* {{{ */ { long catch_op_number; zend_op *opline; znode catch_class; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); catch_class = *class_name; } else { zend_error(E_COMPILE_ERROR, "Bad class name in the catch statement"); } catch_op_number = get_next_op_number(CG(active_op_array)); if (first_catch) { first_catch->u.op.opline_num = catch_op_number; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CATCH; opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &catch_class.u.constant TSRMLS_CC); opline->op2_type = IS_CV; opline->op2.var = lookup_cv(CG(active_op_array), catch_var->u.constant.value.str.val, catch_var->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(catch_var->u.constant) = (char*)CG(active_op_array)->vars[opline->op2.var].name; opline->result.num = 0; /* 1 means it's the last catch in the block */ try_token->u.op.opline_num = catch_op_number; } /* }}} */ void zend_do_end_catch(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); CG(active_op_array)->opcodes[try_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_throw(const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_THROW; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); } /* }}} */ ZEND_API void function_add_ref(zend_function *function) /* {{{ */ { if (function->type == ZEND_USER_FUNCTION) { zend_op_array *op_array = &function->op_array; (*op_array->refcount)++; if (op_array->static_variables) { HashTable *static_variables = op_array->static_variables; zval *tmp_zval; ALLOC_HASHTABLE(op_array->static_variables); zend_hash_init(op_array->static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(op_array->static_variables, static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_zval, sizeof(zval *)); } op_array->run_time_cache = NULL; } } /* }}} */ static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */ { zend_function *function, *new_function; if (!ce->parent) { return; } /* You cannot change create_object */ ce->create_object = ce->parent->create_object; /* Inherit special functions if needed */ if (!ce->get_iterator) { ce->get_iterator = ce->parent->get_iterator; } if (!ce->iterator_funcs.funcs) { ce->iterator_funcs.funcs = ce->parent->iterator_funcs.funcs; } if (!ce->__get) { ce->__get = ce->parent->__get; } if (!ce->__set) { ce->__set = ce->parent->__set; } if (!ce->__unset) { ce->__unset = ce->parent->__unset; } if (!ce->__isset) { ce->__isset = ce->parent->__isset; } if (!ce->__call) { ce->__call = ce->parent->__call; } if (!ce->__callstatic) { ce->__callstatic = ce->parent->__callstatic; } if (!ce->__tostring) { ce->__tostring = ce->parent->__tostring; } if (!ce->clone) { ce->clone = ce->parent->clone; } if(!ce->serialize) { ce->serialize = ce->parent->serialize; } if(!ce->unserialize) { ce->unserialize = ce->parent->unserialize; } if (!ce->destructor) { ce->destructor = ce->parent->destructor; } if (ce->constructor) { if (ce->parent->constructor && ce->parent->constructor->common.fn_flags & ZEND_ACC_FINAL) { zend_error(E_ERROR, "Cannot override final %s::%s() with %s::%s()", ce->parent->name, ce->parent->constructor->common.function_name, ce->name, ce->constructor->common.function_name ); } return; } if (zend_hash_find(&ce->parent->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), (void **)&function)==SUCCESS) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), function, sizeof(zend_function), (void**)&new_function); function_add_ref(new_function); } else { /* Don't inherit the old style constructor if we already have the new style constructor */ char *lc_class_name; char *lc_parent_class_name; lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); if (!zend_hash_exists(&ce->function_table, lc_class_name, ce->name_length+1)) { lc_parent_class_name = zend_str_tolower_dup(ce->parent->name, ce->parent->name_length); if (!zend_hash_exists(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1) && zend_hash_find(&ce->parent->function_table, lc_parent_class_name, ce->parent->name_length+1, (void **)&function)==SUCCESS) { if (function->common.fn_flags & ZEND_ACC_CTOR) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1, function, sizeof(zend_function), (void**)&new_function); function_add_ref(new_function); } } efree(lc_parent_class_name); } efree(lc_class_name); } ce->constructor = ce->parent->constructor; } /* }}} */ char *zend_visibility_string(zend_uint fn_flags) /* {{{ */ { if (fn_flags & ZEND_ACC_PRIVATE) { return "private"; } if (fn_flags & ZEND_ACC_PROTECTED) { return "protected"; } if (fn_flags & ZEND_ACC_PUBLIC) { return "public"; } return ""; } /* }}} */ static void do_inherit_method(zend_function *function) /* {{{ */ { /* The class entry of the derived function intentionally remains the same * as that of the parent class. That allows us to know in which context * we're running, and handle private method calls properly. */ function_add_ref(function); } /* }}} */ static zend_bool zend_do_perform_implementation_check(const zend_function *fe, const zend_function *proto TSRMLS_DC) /* {{{ */ { zend_uint i; /* If it's a user function then arg_info == NULL means we don't have any parameters but * we still need to do the arg number checks. We are only willing to ignore this for internal * functions because extensions don't always define arg_info. */ if (!proto || (!proto->common.arg_info && proto->common.type != ZEND_USER_FUNCTION)) { return 1; } /* Checks for constructors only if they are declared in an interface, * or explicitly marked as abstract */ if ((fe->common.fn_flags & ZEND_ACC_CTOR) && ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)) { return 1; } /* check number of arguments */ if (proto->common.required_num_args < fe->common.required_num_args || proto->common.num_args > fe->common.num_args) { return 0; } if (fe->common.type != ZEND_USER_FUNCTION && (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) != 0 && (fe->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) == 0) { return 0; } /* by-ref constraints on return values are covariant */ if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) { return 0; } for (i=0; i < proto->common.num_args; i++) { if (ZEND_LOG_XOR(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)) { /* Only one has a type hint and the other one doesn't */ return 0; } if (fe->common.arg_info[i].class_name && strcasecmp(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)!=0) { const char *colon; if (fe->common.type != ZEND_USER_FUNCTION) { return 0; } else if (strchr(proto->common.arg_info[i].class_name, '\\') != NULL || (colon = zend_memrchr(fe->common.arg_info[i].class_name, '\\', fe->common.arg_info[i].class_name_len)) == NULL || strcasecmp(colon+1, proto->common.arg_info[i].class_name) != 0) { zend_class_entry **fe_ce, **proto_ce; int found, found2; found = zend_lookup_class(fe->common.arg_info[i].class_name, fe->common.arg_info[i].class_name_len, &fe_ce TSRMLS_CC); found2 = zend_lookup_class(proto->common.arg_info[i].class_name, proto->common.arg_info[i].class_name_len, &proto_ce TSRMLS_CC); /* Check for class alias */ if (found != SUCCESS || found2 != SUCCESS || (*fe_ce)->type == ZEND_INTERNAL_CLASS || (*proto_ce)->type == ZEND_INTERNAL_CLASS || *fe_ce != *proto_ce) { return 0; } } } if (fe->common.arg_info[i].type_hint != proto->common.arg_info[i].type_hint) { /* Incompatible type hint */ return 0; } /* by-ref constraints on arguments are invariant */ if (fe->common.arg_info[i].pass_by_reference != proto->common.arg_info[i].pass_by_reference) { return 0; } } if (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) { for (i=proto->common.num_args; i < fe->common.num_args; i++) { if (!fe->common.arg_info[i].pass_by_reference) { return 0; } } } return 1; } /* }}} */ #define REALLOC_BUF_IF_EXCEED(buf, offset, length, size) \ if (UNEXPECTED(offset - buf + size >= length)) { \ length += size + 1; \ buf = erealloc(buf, length); \ } static char * zend_get_function_declaration(zend_function *fptr TSRMLS_DC) /* {{{ */ { char *offset, *buf; zend_uint length = 1024; offset = buf = (char *)emalloc(length * sizeof(char)); if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { *(offset++) = '&'; *(offset++) = ' '; } if (fptr->common.scope) { memcpy(offset, fptr->common.scope->name, fptr->common.scope->name_length); offset += fptr->common.scope->name_length; *(offset++) = ':'; *(offset++) = ':'; } { size_t name_len = strlen(fptr->common.function_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, name_len); memcpy(offset, fptr->common.function_name, name_len); offset += name_len; } *(offset++) = '('; if (fptr->common.arg_info) { zend_uint i, required; zend_arg_info *arg_info = fptr->common.arg_info; required = fptr->common.required_num_args; for (i = 0; i < fptr->common.num_args;) { if (arg_info->class_name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->class_name_len); memcpy(offset, arg_info->class_name, arg_info->class_name_len); offset += arg_info->class_name_len; *(offset++) = ' '; } else if (arg_info->type_hint) { zend_uint type_name_len; char *type_name = zend_get_type_by_const(arg_info->type_hint); type_name_len = strlen(type_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, type_name_len); memcpy(offset, type_name, type_name_len); offset += type_name_len; *(offset++) = ' '; } if (arg_info->pass_by_reference) { *(offset++) = '&'; } *(offset++) = '$'; if (arg_info->name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->name_len); memcpy(offset, arg_info->name, arg_info->name_len); offset += arg_info->name_len; } else { zend_uint idx = i; memcpy(offset, "param", 5); offset += 5; do { *(offset++) = (char) (idx % 10) + '0'; idx /= 10; } while (idx > 0); } if (i >= required) { *(offset++) = ' '; *(offset++) = '='; *(offset++) = ' '; if (fptr->type == ZEND_USER_FUNCTION) { zend_op *precv = NULL; { zend_uint idx = i; zend_op *op = ((zend_op_array *)fptr)->opcodes; zend_op *end = op + ((zend_op_array *)fptr)->last; ++idx; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT) && op->op1.num == (long)idx) { precv = op; } ++op; } } if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) { zval *zv, zv_copy; int use_copy; ALLOC_ZVAL(zv); *zv = *precv->op2.zv; zval_copy_ctor(zv); INIT_PZVAL(zv); zval_update_constant_ex(&zv, (void*)1, fptr->common.scope TSRMLS_CC); if (Z_TYPE_P(zv) == IS_BOOL) { if (Z_LVAL_P(zv)) { memcpy(offset, "true", 4); offset += 4; } else { memcpy(offset, "false", 5); offset += 5; } } else if (Z_TYPE_P(zv) == IS_NULL) { memcpy(offset, "NULL", 4); offset += 4; } else if (Z_TYPE_P(zv) == IS_STRING) { *(offset++) = '\''; REALLOC_BUF_IF_EXCEED(buf, offset, length, MIN(Z_STRLEN_P(zv), 10)); memcpy(offset, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 10)); offset += MIN(Z_STRLEN_P(zv), 10); if (Z_STRLEN_P(zv) > 10) { *(offset++) = '.'; *(offset++) = '.'; *(offset++) = '.'; } *(offset++) = '\''; } else if (Z_TYPE_P(zv) == IS_ARRAY) { memcpy(offset, "Array", 5); offset += 5; } else { zend_make_printable_zval(zv, &zv_copy, &use_copy); REALLOC_BUF_IF_EXCEED(buf, offset, length, Z_STRLEN(zv_copy)); memcpy(offset, Z_STRVAL(zv_copy), Z_STRLEN(zv_copy)); offset += Z_STRLEN(zv_copy); if (use_copy) { zval_dtor(&zv_copy); } } zval_ptr_dtor(&zv); } } else { memcpy(offset, "NULL", 4); offset += 4; } } if (++i < fptr->common.num_args) { *(offset++) = ','; *(offset++) = ' '; } arg_info++; REALLOC_BUF_IF_EXCEED(buf, offset, length, 32); } } *(offset++) = ')'; *offset = '\0'; return buf; } /* }}} */ static void do_inheritance_check_on_method(zend_function *child, zend_function *parent TSRMLS_DC) /* {{{ */ { zend_uint child_flags; zend_uint parent_flags = parent->common.fn_flags; if ((parent->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && parent->common.fn_flags & ZEND_ACC_ABSTRACT && parent->common.scope != (child->common.prototype ? child->common.prototype->common.scope : child->common.scope) && child->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_IMPLEMENTED_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Can't inherit abstract function %s::%s() (previously declared abstract in %s)", parent->common.scope->name, child->common.function_name, child->common.prototype ? child->common.prototype->common.scope->name : child->common.scope->name); } if (parent_flags & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot override final method %s::%s()", ZEND_FN_SCOPE_NAME(parent), child->common.function_name); } child_flags = child->common.fn_flags; /* You cannot change from static to non static and vice versa. */ if ((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC)) { if (child->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot make non static method %s::%s() static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } else { zend_error(E_COMPILE_ERROR, "Cannot make static method %s::%s() non static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } } /* Disallow making an inherited method abstract. */ if ((child_flags & ZEND_ACC_ABSTRACT) && !(parent_flags & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Cannot make non abstract method %s::%s() abstract in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } if (parent_flags & ZEND_ACC_CHANGED) { child->common.fn_flags |= ZEND_ACC_CHANGED; } else { /* Prevent derived classes from restricting access that was available in parent classes */ if ((child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::%s() must be %s (as in class %s)%s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if (((child_flags & ZEND_ACC_PPP_MASK) < (parent_flags & ZEND_ACC_PPP_MASK)) && ((parent_flags & ZEND_ACC_PPP_MASK) & ZEND_ACC_PRIVATE)) { child->common.fn_flags |= ZEND_ACC_CHANGED; } } if (parent_flags & ZEND_ACC_PRIVATE) { child->common.prototype = NULL; } else if (parent_flags & ZEND_ACC_ABSTRACT) { child->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; child->common.prototype = parent; } else if (!(parent->common.fn_flags & ZEND_ACC_CTOR) || (parent->common.prototype && (parent->common.prototype->common.scope->ce_flags & ZEND_ACC_INTERFACE))) { /* ctors only have a prototype if it comes from an interface */ child->common.prototype = parent->common.prototype ? parent->common.prototype : parent; } if (child->common.prototype && (child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { if (!zend_do_perform_implementation_check(child, child->common.prototype TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s::%s() must be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_get_function_declaration(child->common.prototype TSRMLS_CC)); } } else if (EG(error_reporting) & E_STRICT || EG(user_error_handler)) { /* Check E_STRICT (or custom error handler) before the check so that we save some time */ if (!zend_do_perform_implementation_check(child, parent TSRMLS_CC)) { char *method_prototype = zend_get_function_declaration(child->common.prototype TSRMLS_CC); zend_error(E_STRICT, "Declaration of %s::%s() should be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, method_prototype); efree(method_prototype); } } } /* }}} */ static zend_bool do_inherit_method_check(HashTable *child_function_table, zend_function *parent, const zend_hash_key *hash_key, zend_class_entry *child_ce) /* {{{ */ { zend_uint parent_flags = parent->common.fn_flags; zend_function *child; TSRMLS_FETCH(); if (zend_hash_quick_find(child_function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child)==FAILURE) { if (parent_flags & (ZEND_ACC_ABSTRACT)) { child_ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } return 1; /* method doesn't exist in child, copy from parent */ } do_inheritance_check_on_method(child, parent TSRMLS_CC); return 0; } /* }}} */ static zend_bool do_inherit_property_access_check(HashTable *target_ht, zend_property_info *parent_info, const zend_hash_key *hash_key, zend_class_entry *ce) /* {{{ */ { zend_property_info *child_info; zend_class_entry *parent_ce = ce->parent; if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW)) { if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { child_info->flags |= ZEND_ACC_CHANGED; } else { zend_hash_quick_update(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, parent_info, sizeof(zend_property_info), (void **) &child_info); if(ce->type & ZEND_INTERNAL_CLASS) { zend_duplicate_property_info_internal(child_info); } else { zend_duplicate_property_info(child_info); } child_info->flags &= ~ZEND_ACC_PRIVATE; /* it's not private anymore */ child_info->flags |= ZEND_ACC_SHADOW; /* but it's a shadow of private */ } return 0; /* don't copy access information to child */ } if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { if ((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s", (parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", parent_ce->name, hash_key->arKey, (child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ce->name, hash_key->arKey); } if(parent_info->flags & ZEND_ACC_CHANGED) { child_info->flags |= ZEND_ACC_CHANGED; } if ((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ce->name, hash_key->arKey, zend_visibility_string(parent_info->flags), parent_ce->name, (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if ((child_info->flags & ZEND_ACC_STATIC) == 0) { Z_DELREF_P(ce->default_properties_table[parent_info->offset]); ce->default_properties_table[parent_info->offset] = ce->default_properties_table[child_info->offset]; ce->default_properties_table[child_info->offset] = NULL; child_info->offset = parent_info->offset; } return 0; /* Don't copy from parent */ } else { return 1; /* Copy from parent */ } } /* }}} */ static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce TSRMLS_CC) == FAILURE) { zend_error(E_CORE_ERROR, "Class %s could not implement interface %s", ce->name, iface->name); } if (ce == iface) { zend_error(E_ERROR, "Interface %s cannot implement itself", ce->name); } } /* }}} */ ZEND_API void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface TSRMLS_DC) /* {{{ */ { /* expects interface to be contained in ce's interface list already */ zend_uint i, ce_num, if_num = iface->num_interfaces; zend_class_entry *entry; if (if_num==0) { return; } ce_num = ce->num_interfaces; if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } /* Inherit the interfaces, only if they're not already inherited by the class */ while (if_num--) { entry = iface->interfaces[if_num]; for (i = 0; i < ce_num; i++) { if (ce->interfaces[i] == entry) { break; } } if (i == ce_num) { ce->interfaces[ce->num_interfaces++] = entry; } } /* and now call the implementing handlers */ while (ce_num < ce->num_interfaces) { do_implement_interface(ce, ce->interfaces[ce_num++] TSRMLS_CC); } } /* }}} */ #ifdef ZTS static void zval_internal_ctor(zval **p) /* {{{ */ { zval *orig_ptr = *p; ALLOC_ZVAL(*p); MAKE_COPY_ZVAL(&orig_ptr, *p); } /* }}} */ # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) (((parent_ce)->type != (ce)->type) ? zval_internal_ctor : zval_add_ref)) #else # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) zval_add_ref) #endif ZEND_API void zend_do_inheritance(zend_class_entry *ce, zend_class_entry *parent_ce TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; if ((ce->ce_flags & ZEND_ACC_INTERFACE) && !(parent_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ce->name, parent_ce->name); } if (parent_ce->ce_flags & ZEND_ACC_FINAL_CLASS) { zend_error(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ce->name, parent_ce->name); } ce->parent = parent_ce; /* Copy serialize/unserialize callbacks */ if (!ce->serialize) { ce->serialize = parent_ce->serialize; } if (!ce->unserialize) { ce->unserialize = parent_ce->unserialize; } /* Inherit interfaces */ zend_do_inherit_interfaces(ce, parent_ce TSRMLS_CC); /* Inherit properties */ if (parent_ce->default_properties_count) { int i = ce->default_properties_count + parent_ce->default_properties_count; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_properties_count) { while (i-- > parent_ce->default_properties_count) { ce->default_properties_table[i] = ce->default_properties_table[i - parent_ce->default_properties_count]; } } for (i = 0; i < parent_ce->default_properties_count; i++) { ce->default_properties_table[i] = parent_ce->default_properties_table[i]; if (ce->default_properties_table[i]) { #ifdef ZTS if (parent_ce->type != ce->type) { zval *p; ALLOC_ZVAL(p); MAKE_COPY_ZVAL(&ce->default_properties_table[i], p); ce->default_properties_table[i] = p; } else { Z_ADDREF_P(ce->default_properties_table[i]); } #else Z_ADDREF_P(ce->default_properties_table[i]); #endif } } ce->default_properties_count += parent_ce->default_properties_count; } if (parent_ce->type != ce->type) { /* User class extends internal class */ zend_update_class_constants(parent_ce TSRMLS_CC); if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = erealloc(ce->default_static_members_table, sizeof(void*) * i); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&CE_STATIC_MEMBERS(parent_ce)[i]); ce->default_static_members_table[i] = CE_STATIC_MEMBERS(parent_ce)[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; ce->static_members_table = ce->default_static_members_table; } } else { if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&parent_ce->default_static_members_table[i]); ce->default_static_members_table[i] = parent_ce->default_static_members_table[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } } for (zend_hash_internal_pointer_reset(&ce->properties_info); zend_hash_get_current_data(&ce->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->properties_info)) { if (property_info->ce == ce) { if (property_info->flags & ZEND_ACC_STATIC) { property_info->offset += parent_ce->default_static_members_count; } else { property_info->offset += parent_ce->default_properties_count; } } } zend_hash_merge_ex(&ce->properties_info, &parent_ce->properties_info, (copy_ctor_func_t) (ce->type & ZEND_INTERNAL_CLASS ? zend_duplicate_property_info_internal : zend_duplicate_property_info), sizeof(zend_property_info), (merge_checker_func_t) do_inherit_property_access_check, ce); zend_hash_merge(&ce->constants_table, &parent_ce->constants_table, zval_property_ctor(parent_ce, ce), NULL, sizeof(zval *), 0); zend_hash_merge_ex(&ce->function_table, &parent_ce->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_inherit_parent_constructor(ce); if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS && ce->type == ZEND_INTERNAL_CLASS) { ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } else if (!(ce->ce_flags & ZEND_ACC_IMPLEMENT_INTERFACES) && !(ce->ce_flags & ZEND_ACC_IMPLEMENT_TRAITS)) { /* The verification will be done in runtime by ZEND_VERIFY_ABSTRACT_CLASS */ zend_verify_abstract_class(ce TSRMLS_CC); } ce->ce_flags |= parent_ce->ce_flags & ZEND_HAS_STATIC_IN_METHODS; } /* }}} */ static zend_bool do_inherit_constant_check(HashTable *child_constants_table, const zval **parent_constant, const zend_hash_key *hash_key, const zend_class_entry *iface) /* {{{ */ { zval **old_constant; if (zend_hash_quick_find(child_constants_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**)&old_constant) == SUCCESS) { if (*old_constant != *parent_constant) { zend_error(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", hash_key->arKey, iface->name); } return 0; } return 1; } /* }}} */ static int do_interface_constant_check(zval **val TSRMLS_DC, int num_args, va_list args, const zend_hash_key *key) /* {{{ */ { zend_class_entry **iface = va_arg(args, zend_class_entry**); do_inherit_constant_check(&(*iface)->constants_table, (const zval **) val, key, *iface); return ZEND_HASH_APPLY_KEEP; } /* }}} */ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_iface_num = ce->num_interfaces; zend_uint parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0; for (i = 0; i < ce->num_interfaces; i++) { if (ce->interfaces[i] == NULL) { memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i)); i--; } else if (ce->interfaces[i] == iface) { if (i < parent_iface_num) { ignore = 1; } else { zend_error(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ce->name, iface->name); } } } if (ignore) { /* Check for attempt to redeclare interface constants */ zend_hash_apply_with_arguments(&ce->constants_table TSRMLS_CC, (apply_func_args_t) do_interface_constant_check, 1, &iface); } else { if (ce->num_interfaces >= current_iface_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } } ce->interfaces[ce->num_interfaces++] = iface; zend_hash_merge_ex(&ce->constants_table, &iface->constants_table, (copy_ctor_func_t) zval_add_ref, sizeof(zval *), (merge_checker_func_t) do_inherit_constant_check, iface); zend_hash_merge_ex(&ce->function_table, &iface->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_implement_interface(ce, iface TSRMLS_CC); zend_do_inherit_interfaces(ce, iface TSRMLS_CC); } } /* }}} */ ZEND_API void zend_do_implement_trait(zend_class_entry *ce, zend_class_entry *trait TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_trait_num = ce->num_traits; zend_uint parent_trait_num = ce->parent ? ce->parent->num_traits : 0; for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == NULL) { memmove(ce->traits + i, ce->traits + i + 1, sizeof(zend_class_entry*) * (--ce->num_traits - i)); i--; } else if (ce->traits[i] == trait) { if (i < parent_trait_num) { ignore = 1; } } } if (!ignore) { if (ce->num_traits >= current_trait_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->traits = (zend_class_entry **) realloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } else { ce->traits = (zend_class_entry **) erealloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } } ce->traits[ce->num_traits++] = trait; } } /* }}} */ static int zend_traits_merge_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { size_t current; size_t i; size_t count; HashTable* resulting_table; HashTable** function_tables; zend_class_entry *ce; size_t collision = 0; size_t abstract_solved = 0; zend_function* other_trait_fn; current = va_arg(args, size_t); /* index of current trait */ count = va_arg(args, size_t); resulting_table = va_arg(args, HashTable*); function_tables = va_arg(args, HashTable**); ce = va_arg(args, zend_class_entry*); for (i = 0; i < count; i++) { if (i == current) { continue; /* just skip this, cause its the table this function is applied on */ } if (zend_hash_quick_find(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&other_trait_fn) == SUCCESS) { /* if it is an abstract method, there is no collision */ if (other_trait_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* In case both are abstract, just check prototype, but need to do that in both directions */ if ( !zend_do_perform_implementation_check(fn, other_trait_fn TSRMLS_CC) || !zend_do_perform_implementation_check(other_trait_fn, fn TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s must be compatible with %s", //ZEND_FN_SCOPE_NAME(fn), fn->common.function_name, //::%s() zend_get_function_declaration(fn TSRMLS_CC), zend_get_function_declaration(other_trait_fn TSRMLS_CC)); } } else { /* otherwise, do the full check */ do_inheritance_check_on_method(fn, other_trait_fn TSRMLS_CC); } /* we can savely free and remove it from other table */ zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } else { /* if it is not an abstract method, there is still no collision */ /* if fn is an abstract method */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible. Here, we already know other_trait_fn cannot be abstract, full check ok. */ do_inheritance_check_on_method(other_trait_fn, fn TSRMLS_CC); /* just mark as solved, will be added if its own trait is processed */ abstract_solved = 1; } else { /* but else, we have a collision of non-abstract methods */ collision++; zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } } } if (collision) { zend_function* class_fn; /* make sure method is not already overridden in class */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&class_fn) == FAILURE || class_fn->common.scope != ce) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because there are collisions with other trait methods on %s", fn->common.function_name, ce->name); } zend_function_dtor(fn); } else if (abstract_solved) { zend_function_dtor(fn); } else { /* Add it to result function table */ if (zend_hash_quick_add(resulting_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, fn, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating resulting trait method table", fn->common.function_name); } } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ /* {{{ Originates from php_runkit_function_copy_ctor Duplicate structures in an op_array where necessary to make an outright duplicate */ static void zend_traits_duplicate_function(zend_function *fe, zend_class_entry *target_ce, char *newname TSRMLS_DC) { zend_literal *literals_copy; zend_compiled_variable *dupvars; zend_op *opcode_copy; zval class_name_zv; int class_name_literal; int i; int number_of_literals; if (fe->op_array.static_variables) { HashTable *tmpHash; ALLOC_HASHTABLE(tmpHash); zend_hash_init(tmpHash, zend_hash_num_elements(fe->op_array.static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_apply_with_arguments(fe->op_array.static_variables TSRMLS_CC, (apply_func_args_t)zval_copy_static_var, 1, tmpHash); fe->op_array.static_variables = tmpHash; } number_of_literals = fe->op_array.last_literal; literals_copy = (zend_literal*)emalloc(number_of_literals * sizeof(zend_literal)); for (i = 0; i < number_of_literals; i++) { literals_copy[i] = fe->op_array.literals[i]; zval_copy_ctor(&literals_copy[i].constant); } fe->op_array.literals = literals_copy; fe->op_array.refcount = emalloc(sizeof(zend_uint)); *(fe->op_array.refcount) = 1; if (fe->op_array.vars) { i = fe->op_array.last_var; dupvars = safe_emalloc(fe->op_array.last_var, sizeof(zend_compiled_variable), 0); while (i > 0) { i--; dupvars[i].name = estrndup(fe->op_array.vars[i].name, fe->op_array.vars[i].name_len); dupvars[i].name_len = fe->op_array.vars[i].name_len; dupvars[i].hash_value = fe->op_array.vars[i].hash_value; } fe->op_array.vars = dupvars; } else { fe->op_array.vars = NULL; } opcode_copy = safe_emalloc(sizeof(zend_op), fe->op_array.last, 0); for(i = 0; i < fe->op_array.last; i++) { opcode_copy[i] = fe->op_array.opcodes[i]; if (opcode_copy[i].op1_type != IS_CONST) { switch (opcode_copy[i].opcode) { case ZEND_GOTO: case ZEND_JMP: if (opcode_copy[i].op1.jmp_addr && opcode_copy[i].op1.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op1.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op1.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op1.jmp_addr - fe->op_array.opcodes); } break; } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op1.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op1.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op1.zv = &fe->op_array.literals[class_name_literal].constant; } } if (opcode_copy[i].op2_type != IS_CONST) { switch (opcode_copy[i].opcode) { case ZEND_JMPZ: case ZEND_JMPNZ: case ZEND_JMPZ_EX: case ZEND_JMPNZ_EX: case ZEND_JMP_SET: case ZEND_JMP_SET_VAR: if (opcode_copy[i].op2.jmp_addr && opcode_copy[i].op2.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op2.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op2.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op2.jmp_addr - fe->op_array.opcodes); } break; } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op2.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op2.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op2.zv = &fe->op_array.literals[class_name_literal].constant; } } } fe->op_array.opcodes = opcode_copy; fe->op_array.function_name = newname; /* was setting it to fe which does not work since fe is stack allocated and not a stable address */ /* fe->op_array.prototype = fe->op_array.prototype; */ if (fe->op_array.arg_info) { zend_arg_info *tmpArginfo; tmpArginfo = safe_emalloc(sizeof(zend_arg_info), fe->op_array.num_args, 0); for(i = 0; i < fe->op_array.num_args; i++) { tmpArginfo[i] = fe->op_array.arg_info[i]; tmpArginfo[i].name = estrndup(tmpArginfo[i].name, tmpArginfo[i].name_len); if (tmpArginfo[i].class_name) { tmpArginfo[i].class_name = estrndup(tmpArginfo[i].class_name, tmpArginfo[i].class_name_len); } } fe->op_array.arg_info = tmpArginfo; } fe->op_array.doc_comment = estrndup(fe->op_array.doc_comment, fe->op_array.doc_comment_len); fe->op_array.try_catch_array = (zend_try_catch_element*)estrndup((char*)fe->op_array.try_catch_array, sizeof(zend_try_catch_element) * fe->op_array.last_try_catch); fe->op_array.brk_cont_array = (zend_brk_cont_element*)estrndup((char*)fe->op_array.brk_cont_array, sizeof(zend_brk_cont_element) * fe->op_array.last_brk_cont); } /* }}} */ static void zend_add_magic_methods(zend_class_entry* ce, const char* mname, uint mname_len, zend_function* fe TSRMLS_DC) /* {{{ */ { if (!strncmp(mname, ZEND_CLONE_FUNC_NAME, mname_len)) { ce->clone = fe; fe->common.fn_flags |= ZEND_ACC_CLONE; } else if (!strncmp(mname, ZEND_CONSTRUCTOR_FUNC_NAME, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } else if (!strncmp(mname, ZEND_DESTRUCTOR_FUNC_NAME, mname_len)) { ce->destructor = fe; fe->common.fn_flags |= ZEND_ACC_DTOR; } else if (!strncmp(mname, ZEND_GET_FUNC_NAME, mname_len)) { ce->__get = fe; } else if (!strncmp(mname, ZEND_SET_FUNC_NAME, mname_len)) { ce->__set = fe; } else if (!strncmp(mname, ZEND_CALL_FUNC_NAME, mname_len)) { ce->__call = fe; } else if (!strncmp(mname, ZEND_UNSET_FUNC_NAME, mname_len)) { ce->__unset = fe; } else if (!strncmp(mname, ZEND_ISSET_FUNC_NAME, mname_len)) { ce->__isset = fe; } else if (!strncmp(mname, ZEND_CALLSTATIC_FUNC_NAME, mname_len)) { ce->__callstatic = fe; } else if (!strncmp(mname, ZEND_TOSTRING_FUNC_NAME, mname_len)) { ce->__tostring = fe; } else if (ce->name_length + 1 == mname_len) { char *lowercase_name = emalloc(ce->name_length + 1); zend_str_tolower_copy(lowercase_name, ce->name, ce->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, ce->name_length + 1, 1 TSRMLS_CC); if (!memcmp(mname, lowercase_name, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } str_efree(lowercase_name); } } /* }}} */ static int zend_traits_merge_functions_to_class(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zend_class_entry *ce = va_arg(args, zend_class_entry*); int add = 0; zend_function* existing_fn = NULL; zend_function fn_copy, *fn_copy_p; zend_function* prototype = NULL; /* is used to determine the prototype according to the inheritance chain */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &existing_fn) == FAILURE) { add = 1; /* not found */ } else if (existing_fn->common.scope != ce) { add = 1; /* or inherited from other class or interface */ } if (add) { zend_function* parent_function; if (ce->parent && zend_hash_quick_find(&ce->parent->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &parent_function) != FAILURE) { prototype = parent_function; /* ->common.fn_flags |= ZEND_ACC_ABSTRACT; */ /* we got that method in the parent class, and are going to override it, except, if the trait is just asking to have an abstract method implemented. */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* then we clean up an skip this method */ zend_function_dtor(fn); return ZEND_HASH_APPLY_REMOVE; } } fn->common.scope = ce; fn->common.prototype = prototype; if (prototype && (prototype->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT || prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { fn->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; } else if (fn->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT) { /* remove ZEND_ACC_IMPLEMENTED_ABSTRACT flag, think it shouldn't be copied to class */ fn->common.fn_flags = fn->common.fn_flags - ZEND_ACC_IMPLEMENTED_ABSTRACT; } /* check whether the trait method fullfills the inheritance requirements */ if (prototype) { do_inheritance_check_on_method(fn, prototype TSRMLS_CC); } /* one more thing: make sure we properly implement an abstract method */ if (existing_fn && existing_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { do_inheritance_check_on_method(fn, existing_fn TSRMLS_CC); } /* delete inherited fn if the function to be added is not abstract */ if (existing_fn && existing_fn->common.scope != ce && (fn->common.fn_flags & ZEND_ACC_ABSTRACT) == 0) { /* it is just a reference which was added to the subclass while doing the inheritance, so we can deleted now, and will add the overriding method afterwards. Except, if we try to add an abstract function, then we should not delete the inherited one */ zend_hash_quick_del(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h); } if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (fn->op_array.static_variables) { ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, ce, estrdup(fn->common.function_name) TSRMLS_CC); if (zend_hash_quick_update(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, &fn_copy, sizeof(zend_function), (void**)&fn_copy_p)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating class method table", hash_key->arKey); } zend_add_magic_methods(ce, hash_key->arKey, hash_key->nKeyLength, fn_copy_p TSRMLS_CC); zend_function_dtor(fn); } else { zend_function_dtor(fn); } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ static int zend_traits_copy_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { HashTable* target; zend_class_entry *target_ce; zend_trait_alias** aliases; HashTable* exclude_table; char* lcname; unsigned int fnname_len; zend_function fn_copy; void* dummy; size_t i = 0; target = va_arg(args, HashTable*); target_ce = va_arg(args, zend_class_entry*); aliases = va_arg(args, zend_trait_alias**); exclude_table = va_arg(args, HashTable*); fnname_len = strlen(fn->common.function_name); /* apply aliases which are qualified with a class name, there should not be any ambiguity */ if (aliases) { while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias != NULL && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && aliases[i]->trait_method->mname_len == fnname_len && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(aliases[i]->alias, aliases[i]->alias_len) TSRMLS_CC); /* if it is 0, no modifieres has been changed */ if (aliases[i]->modifiers) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } lcname = zend_str_tolower_dup(aliases[i]->alias, aliases[i]->alias_len); if (zend_hash_add(target, lcname, aliases[i]->alias_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add aliased trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } efree(lcname); /** Record the trait from which this alias was resolved. */ if (!aliases[i]->trait_method->ce) { aliases[i]->trait_method->ce = fn->common.scope; } } i++; } } lcname = zend_str_tolower_dup(fn->common.function_name, fnname_len); if (exclude_table == NULL || zend_hash_find(exclude_table, lcname, fnname_len, &dummy) == FAILURE) { /* is not in hashtable, thus, function is not to be excluded */ fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(fn->common.function_name, fnname_len) TSRMLS_CC); /* apply aliases which are not qualified by a class name, or which have not * alias name, just setting visibility */ if (aliases) { i = 0; while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias == NULL && aliases[i]->modifiers != 0 && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && (aliases[i]->trait_method->mname_len == fnname_len) && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); /** Record the trait from which this alias was resolved. */ if (!aliases[i]->trait_method->ce) { aliases[i]->trait_method->ce = fn->common.scope; } } i++; } } if (zend_hash_add(target, lcname, fnname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } } efree(lcname); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* Copies function table entries to target function table with applied aliasing */ static void zend_traits_copy_trait_function_table(HashTable *target, zend_class_entry *target_ce, HashTable *source, zend_trait_alias** aliases, HashTable* exclude_table TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_arguments(source TSRMLS_CC, (apply_func_args_t)zend_traits_copy_functions, 4, target, target_ce, aliases, exclude_table); } /* }}} */ static void zend_traits_init_trait_structures(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i, j = 0; zend_trait_precedence *cur_precedence; zend_trait_method_reference *cur_method_ref; char *lcname; zend_bool method_exists; /* resolve class references */ if (ce->trait_precedences) { i = 0; while ((cur_precedence = ce->trait_precedences[i])) { /** Resolve classes for all precedence operations. */ if (cur_precedence->exclude_from_classes) { cur_method_ref = cur_precedence->trait_method; cur_precedence->trait_method->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); /** Ensure that the prefered method is actually available. */ lcname = zend_str_tolower_dup(cur_method_ref->method_name, cur_method_ref->mname_len); method_exists = zend_hash_exists(&cur_method_ref->ce->function_table, lcname, cur_method_ref->mname_len + 1); efree(lcname); if (!method_exists) { zend_error(E_COMPILE_ERROR, "A precedence rule was defined for %s::%s but this method does not exist", cur_method_ref->ce->name, cur_method_ref->method_name); } /** With the other traits, we are more permissive. We do not give errors for those. This allows to be more defensive in such definitions. */ j = 0; while (cur_precedence->exclude_from_classes[j]) { char* class_name = (char*)cur_precedence->exclude_from_classes[j]; zend_uint name_length = strlen(class_name); cur_precedence->exclude_from_classes[j] = zend_fetch_class(class_name, name_length, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); efree(class_name); j++; } } i++; } } if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { /** For all aliases with an explicit class name, resolve the class now. */ if (ce->trait_aliases[i]->trait_method->class_name) { cur_method_ref = ce->trait_aliases[i]->trait_method; cur_method_ref->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); /** And, ensure that the referenced method is resolvable, too. */ lcname = zend_str_tolower_dup(cur_method_ref->method_name, cur_method_ref->mname_len); method_exists = zend_hash_exists(&cur_method_ref->ce->function_table, lcname, cur_method_ref->mname_len + 1); efree(lcname); if (!method_exists) { zend_error(E_COMPILE_ERROR, "An alias was defined for %s::%s but this method does not exist", cur_method_ref->ce->name, cur_method_ref->method_name); } } i++; } } } /* }}} */ static void zend_traits_compile_exclude_table(HashTable* exclude_table, zend_trait_precedence **precedences, zend_class_entry *trait) /* {{{ */ { size_t i = 0, j; if (!precedences) { return; } while (precedences[i]) { if (precedences[i]->exclude_from_classes) { j = 0; while (precedences[i]->exclude_from_classes[j]) { if (precedences[i]->exclude_from_classes[j] == trait) { zend_uint lcname_len = precedences[i]->trait_method->mname_len; char *lcname = zend_str_tolower_dup(precedences[i]->trait_method->method_name, lcname_len); if (zend_hash_add(exclude_table, lcname, lcname_len, NULL, 0, NULL) == FAILURE) { efree(lcname); zend_error(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", precedences[i]->trait_method->method_name, trait->name); } efree(lcname); } ++j; } } ++i; } } /* }}} */ static void zend_do_traits_method_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { HashTable** function_tables; HashTable* resulting_table; HashTable exclude_table; size_t i; /* prepare copies of trait function tables for combination */ function_tables = malloc(sizeof(HashTable*) * ce->num_traits); resulting_table = (HashTable *) malloc(sizeof(HashTable)); /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(resulting_table, 10, NULL, NULL, 1, 0); for (i = 0; i < ce->num_traits; i++) { function_tables[i] = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(function_tables[i], ce->traits[i]->function_table.nNumOfElements, NULL, NULL, 1, 0); if (ce->trait_precedences) { /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(&exclude_table, 2, NULL, NULL, 0, 0); zend_traits_compile_exclude_table(&exclude_table, ce->trait_precedences, ce->traits[i]); /* copies functions, applies defined aliasing, and excludes unused trait methods */ zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, &exclude_table TSRMLS_CC); zend_hash_graceful_destroy(&exclude_table); } else { zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, NULL TSRMLS_CC); } } /* now merge trait methods */ for (i = 0; i < ce->num_traits; i++) { zend_hash_apply_with_arguments(function_tables[i] TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions, 5, i, ce->num_traits, resulting_table, function_tables, ce); } /* Now the resulting_table contains all trait methods we would have to * add to the class in the following step the methods are inserted into the method table * if there is already a method with the same name it is replaced iff ce != fn.scope * --> all inherited methods are overridden, methods defined in the class are left untouched */ zend_hash_apply_with_arguments(resulting_table TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions_to_class, 1, ce); /* free temporary function tables */ for (i = 0; i < ce->num_traits; i++) { /* zend_hash_destroy(function_tables[i]); */ zend_hash_graceful_destroy(function_tables[i]); free(function_tables[i]); } free(function_tables); /* free temporary resulting table */ /* zend_hash_destroy(resulting_table); */ zend_hash_graceful_destroy(resulting_table); free(resulting_table); } /* }}} */ static zend_class_entry* find_first_definition(zend_class_entry *ce, size_t current_trait, const char* prop_name, int prop_name_length, ulong prop_hash, zend_class_entry *coliding_ce) /* {{{ */ { size_t i; zend_property_info *coliding_prop; for (i = 0; (i < current_trait) && (i < ce->num_traits); i++) { if (zend_hash_quick_find(&ce->traits[i]->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS) { return ce->traits[i]; } } return coliding_ce; } /* }}} */ static void zend_do_traits_property_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i; zend_property_info *property_info; zend_property_info *coliding_prop; zval compare_result; const char* prop_name; int prop_name_length; ulong prop_hash; const char* class_name_unused; zend_bool prop_found; zend_bool not_compatible; zval* prop_value; /* In the following steps the properties are inserted into the property table * for that, a very strict approach is applied: * - check for compatibility, if not compatible with any property in class -> fatal * - if compatible, then strict notice */ for (i = 0; i < ce->num_traits; i++) { for (zend_hash_internal_pointer_reset(&ce->traits[i]->properties_info); zend_hash_get_current_data(&ce->traits[i]->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->traits[i]->properties_info)) { /* first get the unmangeld name if necessary, * then check whether the property is already there */ if ((property_info->flags & ZEND_ACC_PPP_MASK) == ZEND_ACC_PUBLIC) { prop_hash = property_info->h; prop_name = property_info->name; prop_name_length = property_info->name_length; prop_found = zend_hash_quick_find(&ce->properties_info, property_info->name, property_info->name_length+1, property_info->h, (void **) &coliding_prop) == SUCCESS; } else { /* for private and protected we need to unmangle the names */ zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name_unused, &prop_name); prop_name_length = strlen(prop_name); prop_hash = zend_get_hash_value(prop_name, prop_name_length + 1); prop_found = zend_hash_quick_find(&ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS; } /* next: check for conflicts with current class */ if (prop_found) { if (coliding_prop->flags & ZEND_ACC_SHADOW) { /* this one is inherited, lets look it up in its own class */ zend_hash_quick_find(&coliding_prop->ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop); } if ( (coliding_prop->flags & (ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC)) == (property_info->flags & (ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC))) { /* flags are identical, now the value needs to be checked */ if (property_info->flags & ZEND_ACC_STATIC) { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_static_members_table[coliding_prop->offset], ce->traits[i]->default_static_members_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } else { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_properties_table[coliding_prop->offset], ce->traits[i]->default_properties_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } } else { /* the flags are not identical, thus, we assume properties are not compatible */ not_compatible = 1; } if (not_compatible) { zend_error(E_COMPILE_ERROR, "%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } else { zend_error(E_STRICT, "%s and %s define the same property ($%s) in the composition of %s. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } } /* property not found, so lets add it */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); zend_declare_property_ex(ce, prop_name, prop_name_length, prop_value, property_info->flags, property_info->doc_comment, property_info->doc_comment_len TSRMLS_CC); } } } /* }}} */ static void zend_do_check_for_inconsistent_traits_aliasing(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { int i = 0; zend_trait_alias* cur_alias; char* lc_method_name; if (ce->trait_aliases) { while (ce->trait_aliases[i]) { cur_alias = ce->trait_aliases[i]; /** The trait for this alias has not been resolved, this means, this alias was not applied. Abort with an error. */ if (!cur_alias->trait_method->ce) { if (cur_alias->alias) { /** Plain old inconsistency/typo/bug */ zend_error(E_COMPILE_ERROR, "An alias (%s) was defined for method %s(), but this method does not exist", cur_alias->alias, cur_alias->trait_method->method_name); } else { /** Here are two possible cases: 1) this is an attempt to modifiy the visibility of a method introduce as part of another alias. Since that seems to violate the DRY principle, we check against it and abort. 2) it is just a plain old inconsitency/typo/bug as in the case where alias is set. */ lc_method_name = zend_str_tolower_dup(cur_alias->trait_method->method_name, cur_alias->trait_method->mname_len); if (zend_hash_exists(&ce->function_table, lc_method_name, cur_alias->trait_method->mname_len+1)) { efree(lc_method_name); zend_error(E_COMPILE_ERROR, "The modifiers for the trait alias %s() need to be changed in the same statment in which the alias is defined. Error", cur_alias->trait_method->method_name); } else { efree(lc_method_name); zend_error(E_COMPILE_ERROR, "The modifiers of the trait method %s() are changed, but this method does not exist. Error", cur_alias->trait_method->method_name); } } } i++; } } } /* }}} */ ZEND_API void zend_do_bind_traits(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { if (ce->num_traits <= 0) { return; } /* complete initialization of trait strutures in ce */ zend_traits_init_trait_structures(ce TSRMLS_CC); /* first care about all methods to be flattened into the class */ zend_do_traits_method_binding(ce TSRMLS_CC); /* Aliases which have not been applied indicate typos/bugs. */ zend_do_check_for_inconsistent_traits_aliasing(ce TSRMLS_CC); /* then flatten the properties into it, to, mostly to notfiy developer about problems */ zend_do_traits_property_binding(ce TSRMLS_CC); /* verify that all abstract methods from traits have been implemented */ zend_verify_abstract_class(ce TSRMLS_CC); /* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */ if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { ce->ce_flags -= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } } /* }}} */ ZEND_API int do_bind_function(const zend_op_array *op_array, zend_op *opline, HashTable *function_table, zend_bool compile_time) /* {{{ */ { zend_function *function; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } zend_hash_quick_find(function_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void *) &function); if (zend_hash_quick_add(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), function, sizeof(zend_function), NULL)==FAILURE) { int error_level = compile_time ? E_COMPILE_ERROR : E_ERROR; zend_function *old_function; if (zend_hash_quick_find(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), (void *) &old_function)==SUCCESS && old_function->type == ZEND_USER_FUNCTION && old_function->op_array.last > 0) { zend_error(error_level, "Cannot redeclare %s() (previously declared in %s:%d)", function->common.function_name, old_function->op_array.filename, old_function->op_array.opcodes[0].lineno); } else { zend_error(error_level, "Cannot redeclare %s()", function->common.function_name); } return FAILURE; } else { (*function->op_array.refcount)++; function->op_array.static_variables = NULL; /* NULL out the unbound function */ return SUCCESS; } } /* }}} */ void zend_add_trait_precedence(znode *precedence_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_precedences, precedence_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_add_trait_alias(znode *alias_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_aliases, alias_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_prepare_reference(znode *result, znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { zend_trait_method_reference *method_ref = emalloc(sizeof(zend_trait_method_reference)); method_ref->ce = NULL; /* REM: There should not be a need for copying, zend_do_begin_class_declaration is also just using that string */ if (class_name) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); method_ref->class_name = Z_STRVAL(class_name->u.constant); method_ref->cname_len = Z_STRLEN(class_name->u.constant); } else { method_ref->class_name = NULL; method_ref->cname_len = 0; } method_ref->method_name = Z_STRVAL(method_name->u.constant); method_ref->mname_len = Z_STRLEN(method_name->u.constant); result->u.op.ptr = method_ref; result->op_type = IS_TMP_VAR; } /* }}} */ void zend_prepare_trait_alias(znode *result, znode *method_reference, znode *modifiers, znode *alias TSRMLS_DC) /* {{{ */ { zend_trait_alias *trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_alias->modifiers = Z_LVAL(modifiers->u.constant); if (Z_LVAL(modifiers->u.constant) == ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot use 'static' as method modifier"); return; } if (alias) { trait_alias->alias = Z_STRVAL(alias->u.constant); trait_alias->alias_len = Z_STRLEN(alias->u.constant); } else { trait_alias->alias = NULL; } trait_alias->function = NULL; result->u.op.ptr = trait_alias; } /* }}} */ void zend_prepare_trait_precedence(znode *result, znode *method_reference, znode *trait_list TSRMLS_DC) /* {{{ */ { zend_trait_precedence *trait_precedence = emalloc(sizeof(zend_trait_precedence)); trait_precedence->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_precedence->exclude_from_classes = (zend_class_entry**) trait_list->u.op.ptr; trait_precedence->function = NULL; result->u.op.ptr = trait_precedence; } /* }}} */ ZEND_API zend_class_entry *do_bind_class(const zend_op_array* op_array, const zend_op *opline, HashTable *class_table, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } if (zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce)==FAILURE) { zend_error(E_COMPILE_ERROR, "Internal Zend error - Missing class information for %s", Z_STRVAL_P(op1)); return NULL; } else { ce = *pce; } ce->refcount++; if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), &ce, sizeof(zend_class_entry *), NULL)==FAILURE) { ce->refcount--; if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return NULL; } else { if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLEMENT_INTERFACES))) { zend_verify_abstract_class(ce TSRMLS_CC); } return ce; } } /* }}} */ ZEND_API zend_class_entry *do_bind_inherited_class(const zend_op_array *op_array, const zend_op *opline, HashTable *class_table, zend_class_entry *parent_ce, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; int found_ce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } found_ce = zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce); if (found_ce == FAILURE) { if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", Z_STRVAL_P(op2)); } return NULL; } else { ce = *pce; } if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ce->name, parent_ce->name); } else if ((parent_ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ce->name, parent_ce->name); } zend_do_inheritance(ce, parent_ce TSRMLS_CC); ce->refcount++; /* Register the derived class */ if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), pce, sizeof(zend_class_entry *), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return ce; } /* }}} */ void zend_do_early_binding(TSRMLS_D) /* {{{ */ { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; HashTable *table; while (opline->opcode == ZEND_TICKS && opline > CG(active_op_array)->opcodes) { opline--; } switch (opline->opcode) { case ZEND_DECLARE_FUNCTION: if (do_bind_function(CG(active_op_array), opline, CG(function_table), 1) == FAILURE) { return; } table = CG(function_table); break; case ZEND_DECLARE_CLASS: if (do_bind_class(CG(active_op_array), opline, CG(class_table), 1 TSRMLS_CC) == NULL) { return; } table = CG(class_table); break; case ZEND_DECLARE_INHERITED_CLASS: { zend_op *fetch_class_opline = opline-1; zval *parent_name; zend_class_entry **pce; parent_name = &CONSTANT(fetch_class_opline->op2.constant); if ((zend_lookup_class(Z_STRVAL_P(parent_name), Z_STRLEN_P(parent_name), &pce TSRMLS_CC) == FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_CLASSES) && ((*pce)->type == ZEND_INTERNAL_CLASS))) { if (CG(compiler_options) & ZEND_COMPILE_DELAYED_BINDING) { zend_uint *opline_num = &CG(active_op_array)->early_binding; while (*opline_num != -1) { opline_num = &CG(active_op_array)->opcodes[*opline_num].result.opline_num; } *opline_num = opline - CG(active_op_array)->opcodes; opline->opcode = ZEND_DECLARE_INHERITED_CLASS_DELAYED; opline->result_type = IS_UNUSED; opline->result.opline_num = -1; } return; } if (do_bind_inherited_class(CG(active_op_array), opline, CG(class_table), *pce, 1 TSRMLS_CC) == NULL) { return; } /* clear unnecessary ZEND_FETCH_CLASS opcode */ zend_del_literal(CG(active_op_array), fetch_class_opline->op2.constant); MAKE_NOP(fetch_class_opline); table = CG(class_table); break; } case ZEND_VERIFY_ABSTRACT_CLASS: case ZEND_ADD_INTERFACE: case ZEND_ADD_TRAIT: case ZEND_BIND_TRAITS: /* We currently don't early-bind classes that implement interfaces */ /* Classes with traits are handled exactly the same, no early-bind here */ return; default: zend_error(E_COMPILE_ERROR, "Invalid binding type"); return; } zend_hash_quick_del(table, Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant)), Z_HASH_P(&CONSTANT(opline->op1.constant))); zend_del_literal(CG(active_op_array), opline->op1.constant); zend_del_literal(CG(active_op_array), opline->op2.constant); MAKE_NOP(opline); } /* }}} */ ZEND_API void zend_do_delayed_early_binding(const zend_op_array *op_array TSRMLS_DC) /* {{{ */ { if (op_array->early_binding != -1) { zend_bool orig_in_compilation = CG(in_compilation); zend_uint opline_num = op_array->early_binding; zend_class_entry **pce; CG(in_compilation) = 1; while (opline_num != -1) { if (zend_lookup_class(Z_STRVAL_P(op_array->opcodes[opline_num-1].op2.zv), Z_STRLEN_P(op_array->opcodes[opline_num-1].op2.zv), &pce TSRMLS_CC) == SUCCESS) { do_bind_inherited_class(op_array, &op_array->opcodes[opline_num], EG(class_table), *pce, 0 TSRMLS_CC); } opline_num = op_array->opcodes[opline_num].result.opline_num; } CG(in_compilation) = orig_in_compilation; } } /* }}} */ void zend_do_boolean_or_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_or_end(znode *result, const znode *expr1, const znode *expr2, znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_boolean_and_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_and_end(znode *result, const znode *expr1, const znode *expr2, const znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_do_while_begin(TSRMLS_D) /* {{{ */ { do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_do_while_end(const znode *do_token, const znode *expr_open_bracket, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ; SET_NODE(opline->op1, expr); opline->op2.opline_num = do_token->u.op.opline_num; SET_UNUSED(opline->op2); do_end_loop(expr_open_bracket->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_brk_cont(zend_uchar op, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->op1.opline_num = CG(context).current_brk_cont; SET_UNUSED(opline->op1); if (expr) { if (expr->op_type != IS_CONST) { zend_error(E_COMPILE_ERROR, "'%s' operator with non-constant operand is no longer supported", op == ZEND_BRK ? "break" : "continue"); } else if (Z_TYPE(expr->u.constant) != IS_LONG || Z_LVAL(expr->u.constant) < 1) { zend_error(E_COMPILE_ERROR, "'%s' operator accepts only positive numbers", op == ZEND_BRK ? "break" : "continue"); } SET_NODE(opline->op2, expr); } else { LITERAL_LONG(opline->op2, 1); opline->op2_type = IS_CONST; } } /* }}} */ void zend_do_switch_cond(const znode *cond TSRMLS_DC) /* {{{ */ { zend_switch_entry switch_entry; switch_entry.cond = *cond; switch_entry.default_case = -1; switch_entry.control_var = -1; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_switch_end(const znode *case_list TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); /* add code to jmp to default case */ if (switch_entry_ptr->default_case != -1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->op1.opline_num = switch_entry_ptr->default_case; } if (case_list->op_type != IS_UNUSED) { /* non-empty switch */ int next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* remember break/continue loop information */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; if (switch_entry_ptr->cond.op_type==IS_VAR || switch_entry_ptr->cond.op_type==IS_TMP_VAR) { /* emit free for the switch condition*/ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry_ptr->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_UNUSED(opline->op2); } if (switch_entry_ptr->cond.op_type == IS_CONST) { zval_dtor(&switch_entry_ptr->cond.u.constant); } zend_stack_del_top(&CG(switch_cond_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_case_before_statement(const znode *case_list, znode *case_token, const znode *case_expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); int next_op_number; zend_switch_entry *switch_entry_ptr; znode result; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); if (switch_entry_ptr->control_var == -1) { switch_entry_ptr->control_var = get_temporary_variable(CG(active_op_array)); } opline->opcode = ZEND_CASE; opline->result.var = switch_entry_ptr->control_var; opline->result_type = IS_TMP_VAR; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_NODE(opline->op2, case_expr); if (opline->op1_type == IS_CONST) { zval_copy_ctor(&CONSTANT(opline->op1.constant)); } GET_NODE(&result, opline->result); next_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, &result); SET_UNUSED(opline->op2); case_token->u.op.opline_num = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_case_after_statement(znode *result, const znode *case_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); result->u.op.opline_num = next_op_number; switch (CG(active_op_array)->opcodes[case_token->u.op.opline_num].opcode) { case ZEND_JMP: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); break; case ZEND_JMPZ: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); break; } } /* }}} */ void zend_do_default_before_statement(const znode *case_list, znode *default_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); default_token->u.op.opline_num = next_op_number; next_op_number = get_next_op_number(CG(active_op_array)); switch_entry_ptr->default_case = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_begin_class_declaration(const znode *class_token, znode *class_name, const znode *parent_class_name TSRMLS_DC) /* {{{ */ { zend_op *opline; int doing_inheritance = 0; zend_class_entry *new_class_entry; char *lcname; int error = 0; zval **ns_name, key; if (CG(active_class_entry)) { zend_error(E_COMPILE_ERROR, "Class declarations may not be nested"); return; } lcname = zend_str_tolower_dup(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); if (!(strcmp(lcname, "self") && strcmp(lcname, "parent"))) { efree(lcname); zend_error(E_COMPILE_ERROR, "Cannot use '%s' as class name as it is reserved", Z_STRVAL(class_name->u.constant)); } /* Class name must not conflict with import names */ if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns_name) == SUCCESS) { error = 1; } if (CG(current_namespace)) { /* Prefix class name with name of current namespace */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); class_name = &tmp; efree(lcname); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); } if (error) { char *tmp = zend_str_tolower_dup(Z_STRVAL_PP(ns_name), Z_STRLEN_PP(ns_name)); if (Z_STRLEN_PP(ns_name) != Z_STRLEN(class_name->u.constant) || memcmp(tmp, lcname, Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "Cannot declare class %s because the name is already in use", Z_STRVAL(class_name->u.constant)); } efree(tmp); } new_class_entry = emalloc(sizeof(zend_class_entry)); new_class_entry->type = ZEND_USER_CLASS; new_class_entry->name = zend_new_interned_string(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1, 1 TSRMLS_CC); new_class_entry->name_length = Z_STRLEN(class_name->u.constant); zend_initialize_class_data(new_class_entry, 1 TSRMLS_CC); new_class_entry->info.user.filename = zend_get_compiled_filename(TSRMLS_C); new_class_entry->info.user.line_start = class_token->u.op.opline_num; new_class_entry->ce_flags |= class_token->EA; if (parent_class_name && parent_class_name->op_type != IS_UNUSED) { switch (parent_class_name->EA) { case ZEND_FETCH_CLASS_SELF: zend_error(E_COMPILE_ERROR, "Cannot use 'self' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_PARENT: zend_error(E_COMPILE_ERROR, "Cannot use 'parent' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use 'static' as class name as it is reserved"); break; default: break; } doing_inheritance = 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, new_class_entry->name_length TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; if (doing_inheritance) { /* Make sure a trait does not try to extend a class */ if ((new_class_entry->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "A trait (%s) cannot extend a class", new_class_entry->name); } opline->extended_value = parent_class_name->u.op.var; opline->opcode = ZEND_DECLARE_INHERITED_CLASS; } else { opline->opcode = ZEND_DECLARE_CLASS; } LITERAL_STRINGL(opline->op2, lcname, new_class_entry->name_length, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); zend_hash_quick_update(CG(class_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &new_class_entry, sizeof(zend_class_entry *), NULL); CG(active_class_entry) = new_class_entry; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(&CG(implementing_class), opline->result); if (CG(doc_comment)) { CG(active_class_entry)->info.user.doc_comment = CG(doc_comment); CG(active_class_entry)->info.user.doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ static void do_verify_abstract_class(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_VERIFY_ABSTRACT_CLASS; SET_NODE(opline->op1, &CG(implementing_class)); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_class_declaration(const znode *class_token, const znode *parent_token TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); if (ce->constructor) { ce->constructor->common.fn_flags |= ZEND_ACC_CTOR; if (ce->constructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Constructor %s::%s() cannot be static", ce->name, ce->constructor->common.function_name); } } if (ce->destructor) { ce->destructor->common.fn_flags |= ZEND_ACC_DTOR; if (ce->destructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Destructor %s::%s() cannot be static", ce->name, ce->destructor->common.function_name); } } if (ce->clone) { ce->clone->common.fn_flags |= ZEND_ACC_CLONE; if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static", ce->name, ce->clone->common.function_name); } } ce->info.user.line_end = zend_get_compiled_lineno(TSRMLS_C); /* Check for traits and proceed like with interfaces. * The only difference will be a combined handling of them in the end. * Thus, we need another opcode here. */ if (ce->num_traits > 0) { zend_op *opline; ce->traits = NULL; ce->num_traits = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_TRAITS; /* opcode generation: */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BIND_TRAITS; SET_NODE(opline->op1, &CG(implementing_class)); } if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) && ((parent_token->op_type != IS_UNUSED) || (ce->num_interfaces > 0))) { zend_verify_abstract_class(ce TSRMLS_CC); if (ce->num_interfaces) { do_verify_abstract_class(TSRMLS_C); } } /* Inherit interfaces; reset number to zero, we need it for above check and * will restore it during actual implementation. * The ZEND_ACC_IMPLEMENT_INTERFACES flag disables double call to * zend_verify_abstract_class() */ if (ce->num_interfaces > 0) { ce->interfaces = NULL; ce->num_interfaces = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_INTERFACES; } CG(active_class_entry) = NULL; } /* }}} */ void zend_do_implements_interface(znode *interface_name TSRMLS_DC) /* {{{ */ { zend_op *opline; /* Traits can not implement interfaces */ if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface on '%s' since it is a Trait", Z_STRVAL(interface_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(interface_name->u.constant), Z_STRLEN(interface_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface name as it is reserved", Z_STRVAL(interface_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_INTERFACE; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(interface_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = (opline->extended_value & ~ZEND_FETCH_CLASS_MASK) | ZEND_FETCH_CLASS_INTERFACE; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &interface_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_interfaces++; } /* }}} */ void zend_do_implements_trait(znode *trait_name TSRMLS_DC) /* {{{ */ { zend_op *opline; if ((CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Cannot use traits inside of interfaces. %s is used in %s", Z_STRVAL(trait_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(trait_name->u.constant), Z_STRLEN(trait_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as trait name as it is reserved", Z_STRVAL(trait_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_TRAIT; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(trait_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = ZEND_FETCH_CLASS_TRAIT; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &trait_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_traits++; } /* }}} */ ZEND_API void zend_mangle_property_name(char **dest, int *dest_length, const char *src1, int src1_length, const char *src2, int src2_length, int internal) /* {{{ */ { char *prop_name; int prop_name_length; prop_name_length = 1 + src1_length + 1 + src2_length; prop_name = pemalloc(prop_name_length + 1, internal); prop_name[0] = '\0'; memcpy(prop_name + 1, src1, src1_length+1); memcpy(prop_name + 1 + src1_length + 1, src2, src2_length+1); *dest = prop_name; *dest_length = prop_name_length; } /* }}} */ static int zend_strnlen(const char* s, int maxlen) /* {{{ */ { int len = 0; while (*s++ && maxlen--) len++; return len; } /* }}} */ ZEND_API int zend_unmangle_property_name(const char *mangled_property, int len, const char **class_name, const char **prop_name) /* {{{ */ { int class_name_len; *class_name = NULL; if (mangled_property[0]!=0) { *prop_name = mangled_property; return SUCCESS; } if (len < 3 || mangled_property[1]==0) { zend_error(E_NOTICE, "Illegal member variable name"); *prop_name = mangled_property; return FAILURE; } class_name_len = zend_strnlen(mangled_property+1, --len - 1) + 1; if (class_name_len >= len || mangled_property[class_name_len]!=0) { zend_error(E_NOTICE, "Corrupt member variable name"); *prop_name = mangled_property; return FAILURE; } *class_name = mangled_property+1; *prop_name = (*class_name)+class_name_len; return SUCCESS; } /* }}} */ void zend_do_declare_property(const znode *var_name, const znode *value, zend_uint access_type TSRMLS_DC) /* {{{ */ { zval *property; zend_property_info *existing_property_info; char *comment = NULL; int comment_len = 0; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Interfaces may not include member variables"); } if (access_type & ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Properties cannot be declared abstract"); } if (access_type & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot declare property %s::$%s final, the final modifier is allowed only for methods and classes", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } if (zend_hash_find(&CG(active_class_entry)->properties_info, var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, (void **) &existing_property_info)==SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::$%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } ALLOC_ZVAL(property); if (value) { *property = value->u.constant; } else { INIT_PZVAL(property); Z_TYPE_P(property) = IS_NULL; } if (CG(doc_comment)) { comment = CG(doc_comment); comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } zend_declare_property_ex(CG(active_class_entry), zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len + 1, 0 TSRMLS_CC), var_name->u.constant.value.str.len, property, access_type, comment, comment_len TSRMLS_CC); efree(var_name->u.constant.value.str.val); } /* }}} */ void zend_do_declare_class_constant(znode *var_name, const znode *value TSRMLS_DC) /* {{{ */ { zval *property; const char *cname = NULL; int result; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed in class constants"); return; } if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Traits cannot have constants"); return; } ALLOC_ZVAL(property); *property = value->u.constant; cname = zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, 0 TSRMLS_CC); if (IS_INTERNED(cname)) { result = zend_hash_quick_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, INTERNED_HASH(cname), &property, sizeof(zval *), NULL); } else { result = zend_hash_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, &property, sizeof(zval *), NULL); } if (result == FAILURE) { FREE_ZVAL(property); zend_error(E_COMPILE_ERROR, "Cannot redefine class constant %s::%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } FREE_PNODE(var_name); if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_fetch_property(znode *result, znode *object, const znode *property TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (object->op_type == IS_CV) { if (object->u.op.var == CG(active_op_array)->this_var) { object->op_type = IS_UNUSED; /* this means $this for objects */ } } else if (fetch_list_ptr->count == 1) { zend_llist_element *le = fetch_list_ptr->head; zend_op *opline_ptr = (zend_op *) le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); SET_UNUSED(opline_ptr->op1); /* this means $this for objects */ SET_NODE(opline_ptr->op2, property); /* if it was usual fetch, we change it to object fetch */ switch (opline_ptr->opcode) { case ZEND_FETCH_W: opline_ptr->opcode = ZEND_FETCH_OBJ_W; break; case ZEND_FETCH_R: opline_ptr->opcode = ZEND_FETCH_OBJ_R; break; case ZEND_FETCH_RW: opline_ptr->opcode = ZEND_FETCH_OBJ_RW; break; case ZEND_FETCH_IS: opline_ptr->opcode = ZEND_FETCH_OBJ_IS; break; case ZEND_FETCH_UNSET: opline_ptr->opcode = ZEND_FETCH_OBJ_UNSET; break; case ZEND_FETCH_FUNC_ARG: opline_ptr->opcode = ZEND_FETCH_OBJ_FUNC_ARG; break; } if (opline_ptr->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline_ptr->op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline_ptr->op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op2.constant); } GET_NODE(result, opline_ptr->result); return; } } if (zend_is_function_or_method_call(object)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, object); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_OBJ_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, object); SET_NODE(opline.op2, property); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline.op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op2.constant); } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void zend_do_halt_compiler_register(TSRMLS_D) /* {{{ */ { char *name, *cfilename; char haltoff[] = "__COMPILER_HALT_OFFSET__"; int len, clen; if (CG(has_bracketed_namespaces) && CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "__HALT_COMPILER() can only be used from the outermost scope"); } cfilename = zend_get_compiled_filename(TSRMLS_C); clen = strlen(cfilename); zend_mangle_property_name(&name, &len, haltoff, sizeof(haltoff) - 1, cfilename, clen, 0); zend_register_long_constant(name, len+1, zend_get_scanned_file_offset(TSRMLS_C), CONST_CS, 0 TSRMLS_CC); pefree(name, 0); if (CG(in_namespace)) { zend_do_end_namespace(TSRMLS_C); } } /* }}} */ void zend_do_push_object(const znode *object TSRMLS_DC) /* {{{ */ { zend_stack_push(&CG(object_stack), object, sizeof(znode)); } /* }}} */ void zend_do_pop_object(znode *object TSRMLS_DC) /* {{{ */ { if (object) { znode *tmp; zend_stack_top(&CG(object_stack), (void **) &tmp); *object = *tmp; } zend_stack_del_top(&CG(object_stack)); } /* }}} */ void zend_do_begin_new_object(znode *new_token, znode *class_type TSRMLS_DC) /* {{{ */ { zend_op *opline; unsigned char *ptr = NULL; new_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_NEW; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, class_type); SET_UNUSED(opline->op2); zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(unsigned char *)); } /* }}} */ void zend_do_end_new_object(znode *result, const znode *new_token, const znode *argument_list TSRMLS_DC) /* {{{ */ { znode ctor_result; zend_do_end_function_call(NULL, &ctor_result, argument_list, 1, 0 TSRMLS_CC); zend_do_free(&ctor_result TSRMLS_CC); CG(active_op_array)->opcodes[new_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, CG(active_op_array)->opcodes[new_token->u.op.opline_num].result); } /* }}} */ static zend_constant* zend_get_ct_const(const zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = NULL; if (Z_STRVAL_P(const_name)[0] == '\\') { if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name), (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name)-1); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name), (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } } else if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)+1, (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name)+1, (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } if (c->flags & CONST_CT_SUBST) { return c; } if (all_internal_constants_substitution && (c->flags & CONST_PERSISTENT) && !(CG(compiler_options) & ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION) && Z_TYPE(c->value) != IS_CONSTANT && Z_TYPE(c->value) != IS_CONSTANT_ARRAY) { return c; } return NULL; } /* }}} */ static int zend_constant_ct_subst(znode *result, zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = zend_get_ct_const(const_name, all_internal_constants_substitution TSRMLS_CC); if (c) { zval_dtor(const_name); result->op_type = IS_CONST; result->u.constant = c->value; zval_copy_ctor(&result->u.constant); INIT_PZVAL(&result->u.constant); return 1; } return 0; } /* }}} */ void zend_do_fetch_constant(znode *result, znode *constant_container, znode *constant_name, int mode, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; zend_op *opline; int type; char *compound; ulong fetch_type = 0; if (constant_container) { switch (mode) { case ZEND_CT: /* this is a class constant */ type = zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant)); if (ZEND_FETCH_CLASS_STATIC == type) { zend_error(E_ERROR, "\"static::\" is not allowed in compile-time constants"); } else if (ZEND_FETCH_CLASS_DEFAULT == type) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } zend_do_build_full_name(NULL, constant_container, constant_name, 1 TSRMLS_CC); *result = *constant_container; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: if (constant_container->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant))) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } else { zend_do_fetch_class(&tmp, constant_container TSRMLS_CC); constant_container = &tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); if (constant_container->op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &constant_container->u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, constant_container); } SET_NODE(opline->op2, constant_name); CALCULATE_LITERAL_HASH(opline->op2.constant); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } GET_NODE(result, opline->result); break; } return; } /* namespace constant */ /* only one that did not contain \ from the start can be converted to string if unknown */ switch (mode) { case ZEND_CT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); /* this is a namespace constant, or an unprefixed constant */ if (zend_constant_ct_subst(result, &constant_name->u.constant, 0 TSRMLS_CC)) { break; } zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(!compound) { fetch_type |= IS_CONSTANT_UNQUALIFIED; } *result = *constant_name; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(zend_constant_ct_subst(result, &constant_name->u.constant, 1 TSRMLS_CC)) { break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; if (compound) { /* the name is unambiguous */ opline->extended_value = 0; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } else { opline->extended_value = IS_CONSTANT_UNQUALIFIED; if (CG(current_namespace)) { opline->extended_value |= IS_CONSTANT_IN_NAMESPACE; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 1 TSRMLS_CC); } else { opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } } GET_CACHE_SLOT(opline->op2.constant); break; } } /* }}} */ void zend_do_shell_exec(znode *result, const znode *cmd TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); switch (cmd->op_type) { case IS_CONST: case IS_TMP_VAR: opline->opcode = ZEND_SEND_VAL; break; default: opline->opcode = ZEND_SEND_VAR; break; } SET_NODE(opline->op1, cmd); opline->op2.opline_num = 0; opline->extended_value = ZEND_DO_FCALL; SET_UNUSED(opline->op2); /* FIXME: exception support not added to this op2 */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DO_FCALL; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; LITERAL_STRINGL(opline->op1, estrndup("shell_exec", sizeof("shell_exec")-1), sizeof("shell_exec")-1, 0); CALCULATE_LITERAL_HASH(opline->op1.constant); opline->op1_type = IS_CONST; GET_CACHE_SLOT(opline->op1.constant); opline->extended_value = 1; SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_init_array(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_ARRAY; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; GET_NODE(result, opline->result); if (expr) { SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } } else { SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_array_element(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_ARRAY_ELEMENT; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_static_array_element(znode *result, znode *offset, const znode *expr) /* {{{ */ { zval *element; ALLOC_ZVAL(element); *element = expr->u.constant; if (offset) { switch (offset->u.constant.type & IS_CONSTANT_TYPE_MASK) { case IS_CONSTANT: /* Ugly hack to denote that this value has a constant index */ Z_TYPE_P(element) |= IS_CONSTANT_INDEX; Z_STRVAL(offset->u.constant) = erealloc(Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+1] = Z_TYPE(offset->u.constant); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+2] = 0; zend_symtable_update(result->u.constant.value.ht, Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_STRING: zend_symtable_update(result->u.constant.value.ht, offset->u.constant.value.str.val, offset->u.constant.value.str.len+1, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_NULL: zend_symtable_update(Z_ARRVAL(result->u.constant), "", 1, &element, sizeof(zval *), NULL); break; case IS_LONG: case IS_BOOL: zend_hash_index_update(Z_ARRVAL(result->u.constant), Z_LVAL(offset->u.constant), &element, sizeof(zval *), NULL); break; case IS_DOUBLE: zend_hash_index_update(Z_ARRVAL(result->u.constant), zend_dval_to_lval(Z_DVAL(offset->u.constant)), &element, sizeof(zval *), NULL); break; case IS_CONSTANT_ARRAY: zend_error(E_ERROR, "Illegal offset type"); break; } } else { zend_hash_next_index_insert(Z_ARRVAL(result->u.constant), &element, sizeof(zval *), NULL); } } /* }}} */ void zend_do_add_list_element(const znode *element TSRMLS_DC) /* {{{ */ { list_llist_element lle; if (element) { zend_check_writable_variable(element); lle.var = *element; zend_llist_copy(&lle.dimensions, &CG(dimension_llist)); zend_llist_prepend_element(&CG(list_llist), &lle); } (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_new_list_begin(TSRMLS_D) /* {{{ */ { int current_dimension = 0; zend_llist_add_element(&CG(dimension_llist), &current_dimension); } /* }}} */ void zend_do_new_list_end(TSRMLS_D) /* {{{ */ { zend_llist_remove_tail(&CG(dimension_llist)); (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_list_init(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(list_stack), &CG(list_llist), sizeof(zend_llist)); zend_stack_push(&CG(list_stack), &CG(dimension_llist), sizeof(zend_llist)); zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_do_new_list_begin(TSRMLS_C); } /* }}} */ void zend_do_list_end(znode *result, znode *expr TSRMLS_DC) /* {{{ */ { zend_llist_element *le; zend_llist_element *dimension; zend_op *opline; znode last_container; le = CG(list_llist).head; while (le) { zend_llist *tmp_dimension_llist = &((list_llist_element *)le->data)->dimensions; dimension = tmp_dimension_llist->head; while (dimension) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (dimension == tmp_dimension_llist->head) { /* first */ last_container = *expr; switch (expr->op_type) { case IS_VAR: case IS_CV: opline->opcode = ZEND_FETCH_DIM_R; break; case IS_TMP_VAR: opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; case IS_CONST: /* fetch_dim_tmp_var will handle this bogus fetch */ zval_copy_ctor(&expr->u.constant); opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; } opline->extended_value |= ZEND_FETCH_ADD_LOCK; } else { opline->opcode = ZEND_FETCH_DIM_R; } opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, &last_container); opline->op2_type = IS_CONST; LITERAL_LONG(opline->op2, *((int *) dimension->data)); GET_NODE(&last_container, opline->result); dimension = dimension->next; } ((list_llist_element *) le->data)->value = last_container; zend_llist_destroy(&((list_llist_element *) le->data)->dimensions); zend_do_assign(result, &((list_llist_element *) le->data)->var, &((list_llist_element *) le->data)->value TSRMLS_CC); zend_do_free(result TSRMLS_CC); le = le->next; } zend_llist_destroy(&CG(dimension_llist)); zend_llist_destroy(&CG(list_llist)); *result = *expr; { zend_llist *p; /* restore previous lists */ zend_stack_top(&CG(list_stack), (void **) &p); CG(dimension_llist) = *p; zend_stack_del_top(&CG(list_stack)); zend_stack_top(&CG(list_stack), (void **) &p); CG(list_llist) = *p; zend_stack_del_top(&CG(list_stack)); } } /* }}} */ void zend_init_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = emalloc(sizeof(void*) * 2); list[0] = item; list[1] = NULL; *(void**)result = list; } /* }}} */ void zend_add_to_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = *(void**)result; size_t n = 0; while (list && list[n]) { n++; } list = erealloc(list, sizeof(void*) * (n+2)); list[n] = item; list[n+1] = NULL; *(void**)result = list; } /* }}} */ void zend_do_fetch_static_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zval *tmp; zend_op *opline; znode lval; znode result; ALLOC_ZVAL(tmp); if (static_assignment) { *tmp = static_assignment->u.constant; } else { INIT_ZVAL(*tmp); } if (!CG(active_op_array)->static_variables) { if (CG(active_op_array)->scope) { CG(active_op_array)->scope->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } ALLOC_HASHTABLE(CG(active_op_array)->static_variables); zend_hash_init(CG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } zend_hash_update(CG(active_op_array)->static_variables, varname->u.constant.value.str.val, varname->u.constant.value.str.len+1, &tmp, sizeof(zval *), NULL); if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (fetch_type == ZEND_FETCH_LEXICAL) ? ZEND_FETCH_R : ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_STATIC; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ if (fetch_type == ZEND_FETCH_LEXICAL) { znode dummy; zend_do_begin_variable_parse(TSRMLS_C); zend_do_assign(&dummy, &lval, &result TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } else { zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); } CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_fetch_lexical_variable(znode *varname, zend_bool is_ref TSRMLS_DC) /* {{{ */ { znode value; if (Z_STRLEN(varname->u.constant) == sizeof("this") - 1 && memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this") - 1) == 0) { zend_error(E_COMPILE_ERROR, "Cannot use $this as lexical variable"); return; } value.op_type = IS_CONST; ZVAL_NULL(&value.u.constant); Z_TYPE(value.u.constant) |= is_ref ? IS_LEXICAL_REF : IS_LEXICAL_VAR; Z_SET_REFCOUNT_P(&value.u.constant, 1); Z_UNSET_ISREF_P(&value.u.constant); zend_do_fetch_static_variable(varname, &value, is_ref ? ZEND_FETCH_STATIC : ZEND_FETCH_LEXICAL TSRMLS_CC); } /* }}} */ void zend_do_fetch_global_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zend_op *opline; znode lval; znode result; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = fetch_type; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_cast(znode *result, const znode *expr, int type TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CAST; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } /* }}} */ void zend_do_include_or_eval(int type, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_do_extended_fcall_begin(TSRMLS_C); { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INCLUDE_OR_EVAL; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } zend_do_extended_fcall_end(TSRMLS_C); } /* }}} */ void zend_do_indirect_references(znode *result, const znode *num_references, znode *variable TSRMLS_DC) /* {{{ */ { int i; zend_do_end_variable_parse(variable, BP_VAR_R, 0 TSRMLS_CC); for (i=1; i<num_references->u.constant.value.lval; i++) { fetch_simple_variable_ex(result, variable, 0, ZEND_FETCH_R TSRMLS_CC); *variable = *result; } zend_do_begin_variable_parse(TSRMLS_C); fetch_simple_variable(result, variable, 1 TSRMLS_CC); /* there is a chance someone is accessing $this */ if (CG(active_op_array)->scope && CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } /* }}} */ void zend_do_unset(const znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_UNSET_VAR; SET_NODE(opline->op1, variable); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); opline->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_UNSET: last_op->opcode = ZEND_UNSET_VAR; SET_UNUSED(last_op->result); break; case ZEND_FETCH_DIM_UNSET: last_op->opcode = ZEND_UNSET_DIM; SET_UNUSED(last_op->result); break; case ZEND_FETCH_OBJ_UNSET: last_op->opcode = ZEND_UNSET_OBJ; SET_UNUSED(last_op->result); break; } } } /* }}} */ void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_do_end_variable_parse(variable, BP_VAR_IS, 0 TSRMLS_CC); zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { last_op = get_next_op(CG(active_op_array) TSRMLS_CC); last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; SET_NODE(last_op->op1, variable); SET_UNUSED(last_op->op2); last_op->result.var = get_temporary_variable(CG(active_op_array)); last_op->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; break; case ZEND_FETCH_DIM_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_DIM_OBJ; break; case ZEND_FETCH_OBJ_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_PROP_OBJ; break; } } last_op->result_type = IS_TMP_VAR; last_op->extended_value |= type; GET_NODE(result, last_op->result); } /* }}} */ void zend_do_instanceof(znode *result, const znode *expr, const znode *class_znode, int type TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline->opcode == ZEND_FETCH_CLASS) { opline->extended_value |= ZEND_FETCH_CLASS_NO_AUTOLOAD; } } if (expr->op_type == IS_CONST) { zend_error(E_COMPILE_ERROR, "instanceof expects an object instance, constant given"); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INSTANCEOF; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_NODE(opline->op2, class_znode); GET_NODE(result, opline->result); } /* }}} */ void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_bool is_variable; zend_bool push_container = 0; zend_op dummy_opline; if (variable) { if (zend_is_function_or_method_call(array)) { is_variable = 0; } else { is_variable = 1; } /* save the location of FETCH_W instruction(s) */ open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); zend_do_end_variable_parse(array, BP_VAR_W, 0 TSRMLS_CC); if (CG(active_op_array)->last > 0 && CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) { /* Only lock the container if we are fetching from a real container and not $this */ if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1_type == IS_VAR) { CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK; push_container = 1; } } } else { is_variable = 0; open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* save the location of FE_RESET */ foreach_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* Preform array reset */ opline->opcode = ZEND_FE_RESET; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, array); SET_UNUSED(opline->op2); opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0; COPY_NODE(dummy_opline.result, opline->result); if (push_container) { COPY_NODE(dummy_opline.op1, CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1); } else { dummy_opline.op1_type = IS_UNUSED; } zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); /* save the location of FE_FETCH */ as_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FE_FETCH; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); COPY_NODE(opline->op1, dummy_opline.result); opline->extended_value = 0; SET_UNUSED(opline->op2); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_OP_DATA; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); } /* }}} */ void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC) /* {{{ */ { zend_op *opline; znode dummy, value_node; zend_bool assign_by_ref=0; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num]; if (key->op_type != IS_UNUSED) { znode *tmp; /* switch between the key and value... */ tmp = key; key = value; value = tmp; /* Mark extended_value in case both key and value are being used */ opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; } if ((key->op_type != IS_UNUSED) && (key->EA & ZEND_PARSED_REFERENCE_VARIABLE)) { zend_error(E_COMPILE_ERROR, "Key element cannot be a reference"); } if (value->EA & ZEND_PARSED_REFERENCE_VARIABLE) { assign_by_ref = 1; if (!(opline-1)->extended_value) { zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression"); } /* Mark extended_value for assign-by-reference */ opline->extended_value |= ZEND_FE_FETCH_BYREF; CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; } else { zend_op *foreach_copy; zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.op.opline_num]; zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.op.opline_num]; /* Change "write context" into "read context" */ fetch->extended_value = 0; /* reset ZEND_FE_RESET_VARIABLE */ while (fetch != end) { --fetch; if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } if (fetch->opcode == ZEND_SEPARATE) { MAKE_NOP(fetch); } else { fetch->opcode -= 3; /* FETCH_W -> FETCH_R */ } } /* prevent double SWITCH_FREE */ zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy); foreach_copy->op1_type = IS_UNUSED; } GET_NODE(&value_node, opline->result); if (assign_by_ref) { zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); /* Mark FE_FETCH as IS_VAR as it holds the data directly as a value */ zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC); } else { zend_do_assign(&dummy, value, &value_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } if (key->op_type != IS_UNUSED) { znode key_node; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num+1]; opline->result_type = IS_TMP_VAR; opline->result.opline_num = get_temporary_variable(CG(active_op_array)); GET_NODE(&key_node, opline->result); zend_do_assign(&dummy, key, &key_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_foreach_end(const znode *foreach_token, const znode *as_token TSRMLS_DC) /* {{{ */ { zend_op *container_ptr; zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = as_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_RESET */ CG(active_op_array)->opcodes[as_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_FETCH */ do_end_loop(as_token->u.op.opline_num, 1 TSRMLS_CC); zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr); generate_free_foreach_copy(container_ptr TSRMLS_CC); zend_stack_del_top(&CG(foreach_copy_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_declare_begin(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(declare_stack), &CG(declarables), sizeof(zend_declarables)); } /* }}} */ void zend_do_declare_stmt(znode *var, znode *val TSRMLS_DC) /* {{{ */ { if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "ticks", sizeof("ticks")-1)) { convert_to_long(&val->u.constant); CG(declarables).ticks = val->u.constant; } else if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "encoding", sizeof("encoding")-1)) { if ((Z_TYPE(val->u.constant) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Cannot use constants as encoding"); } /* * Check that the pragma comes before any opcodes. If the compilation * got as far as this, the previous portion of the script must have been * parseable according to the .ini script_encoding setting. We still * want to tell them to put declare() at the top. */ { int num = CG(active_op_array)->last; /* ignore ZEND_EXT_STMT and ZEND_TICKS */ while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Encoding declaration pragma must be the very first statement in the script"); } } if (CG(multibyte)) { const zend_encoding *new_encoding, *old_encoding; zend_encoding_filter old_input_filter; CG(encoding_declared) = 1; convert_to_string(&val->u.constant); new_encoding = zend_multibyte_fetch_encoding(val->u.constant.value.str.val TSRMLS_CC); if (!new_encoding) { zend_error(E_COMPILE_WARNING, "Unsupported encoding [%s]", val->u.constant.value.str.val); } else { old_input_filter = LANG_SCNG(input_filter); old_encoding = LANG_SCNG(script_encoding); zend_multibyte_set_filter(new_encoding TSRMLS_CC); /* need to re-scan if input filter changed */ if (old_input_filter != LANG_SCNG(input_filter) || (old_input_filter && new_encoding != old_encoding)) { zend_multibyte_yyinput_again(old_input_filter, old_encoding TSRMLS_CC); } } } else { zend_error(E_COMPILE_WARNING, "declare(encoding=...) ignored because Zend multibyte feature is turned off by settings"); } zval_dtor(&val->u.constant); } else { zend_error(E_COMPILE_WARNING, "Unsupported declare '%s'", var->u.constant.value.str.val); zval_dtor(&val->u.constant); } zval_dtor(&var->u.constant); } /* }}} */ void zend_do_declare_end(const znode *declare_token TSRMLS_DC) /* {{{ */ { zend_declarables *declarables; zend_stack_top(&CG(declare_stack), (void **) &declarables); /* We should restore if there was more than (current - start) - (ticks?1:0) opcodes */ if ((get_next_op_number(CG(active_op_array)) - declare_token->u.op.opline_num) - ((Z_LVAL(CG(declarables).ticks))?1:0)) { CG(declarables) = *declarables; } } /* }}} */ void zend_do_exit(znode *result, const znode *message TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXIT; SET_NODE(opline->op1, message); SET_UNUSED(opline->op2); result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_BOOL; Z_LVAL(result->u.constant) = 1; } /* }}} */ void zend_do_begin_silence(znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BEGIN_SILENCE; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); GET_NODE(strudel_token, opline->result); } /* }}} */ void zend_do_end_silence(const znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_END_SILENCE; SET_NODE(opline->op1, strudel_token); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_jmp_set(const znode *value, znode *jmp_token, znode *colon_token TSRMLS_DC) /* {{{ */ { int op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (value->op_type == IS_VAR || value->op_type == IS_CV) { opline->opcode = ZEND_JMP_SET_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_JMP_SET; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, value); SET_UNUSED(opline->op2); GET_NODE(colon_token, opline->result); jmp_token->u.op.opline_num = op_number; INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_jmp_set_else(znode *result, const znode *false_value, const znode *jmp_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, colon_token); if (colon_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].opcode = ZEND_JMP_SET_VAR; CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } opline->extended_value = 0; SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_qm_op(const znode *cond, znode *qm_token TSRMLS_DC) /* {{{ */ { int jmpz_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); SET_UNUSED(opline->op2); opline->op2.opline_num = jmpz_op_number; GET_NODE(qm_token, opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_qm_true(const znode *true_value, znode *qm_token, znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->opcodes[qm_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array))+1; /* jmp over the ZEND_JMP */ if (true_value->op_type == IS_VAR || true_value->op_type == IS_CV) { opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, true_value); SET_UNUSED(opline->op2); GET_NODE(qm_token, opline->result); colon_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_qm_false(znode *result, const znode *false_value, const znode *qm_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, qm_token); if (qm_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].opcode = ZEND_QM_ASSIGN_VAR; CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[colon_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, opline->result); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_extended_info(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_STMT; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_begin(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_BEGIN; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_end(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_END; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_ticks(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_TICKS; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->extended_value = Z_LVAL(CG(declarables).ticks); } /* }}} */ zend_bool zend_is_auto_global_quick(const char *name, uint name_len, ulong hashval TSRMLS_DC) /* {{{ */ { zend_auto_global *auto_global; ulong hash = hashval ? hashval : zend_hash_func(name, name_len+1); if (zend_hash_quick_find(CG(auto_globals), name, name_len+1, hash, (void **) &auto_global)==SUCCESS) { if (auto_global->armed) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } return 1; } return 0; } /* }}} */ zend_bool zend_is_auto_global(const char *name, uint name_len TSRMLS_DC) /* {{{ */ { return zend_is_auto_global_quick(name, name_len, 0 TSRMLS_CC); } /* }}} */ int zend_register_auto_global(const char *name, uint name_len, zend_bool jit, zend_auto_global_callback auto_global_callback TSRMLS_DC) /* {{{ */ { zend_auto_global auto_global; auto_global.name = zend_new_interned_string((char*)name, name_len + 1, 0 TSRMLS_CC); auto_global.name_len = name_len; auto_global.auto_global_callback = auto_global_callback; auto_global.jit = jit; return zend_hash_add(CG(auto_globals), name, name_len+1, &auto_global, sizeof(zend_auto_global), NULL); } /* }}} */ static int zend_auto_global_init(zend_auto_global *auto_global TSRMLS_DC) /* {{{ */ { if (auto_global->jit) { auto_global->armed = 1; } else if (auto_global->auto_global_callback) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } else { auto_global->armed = 0; } return 0; } /* }}} */ ZEND_API void zend_activate_auto_globals(TSRMLS_D) /* {{{ */ { zend_hash_apply(CG(auto_globals), (apply_func_t) zend_auto_global_init TSRMLS_CC); } /* }}} */ int zendlex(znode *zendlval TSRMLS_DC) /* {{{ */ { int retval; if (CG(increment_lineno)) { CG(zend_lineno)++; CG(increment_lineno) = 0; } again: Z_TYPE(zendlval->u.constant) = IS_LONG; retval = lex_scan(&zendlval->u.constant TSRMLS_CC); switch (retval) { case T_COMMENT: case T_DOC_COMMENT: case T_OPEN_TAG: case T_WHITESPACE: goto again; case T_CLOSE_TAG: if (LANG_SCNG(yy_text)[LANG_SCNG(yy_leng)-1] != '>') { CG(increment_lineno) = 1; } if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { goto again; } retval = ';'; /* implicit ; */ break; case T_OPEN_TAG_WITH_ECHO: retval = T_ECHO; break; case T_END_HEREDOC: efree(Z_STRVAL(zendlval->u.constant)); break; } INIT_PZVAL(&zendlval->u.constant); zendlval->op_type = IS_CONST; return retval; } /* }}} */ ZEND_API void zend_initialize_class_data(zend_class_entry *ce, zend_bool nullify_handlers TSRMLS_DC) /* {{{ */ { zend_bool persistent_hashes = (ce->type == ZEND_INTERNAL_CLASS) ? 1 : 0; dtor_func_t zval_ptr_dtor_func = ((persistent_hashes) ? ZVAL_INTERNAL_PTR_DTOR : ZVAL_PTR_DTOR); ce->refcount = 1; ce->ce_flags = 0; ce->default_properties_table = NULL; ce->default_static_members_table = NULL; zend_hash_init_ex(&ce->properties_info, 0, NULL, (dtor_func_t) (persistent_hashes ? zend_destroy_property_info_internal : zend_destroy_property_info), persistent_hashes, 0); zend_hash_init_ex(&ce->constants_table, 0, NULL, zval_ptr_dtor_func, persistent_hashes, 0); zend_hash_init_ex(&ce->function_table, 0, NULL, ZEND_FUNCTION_DTOR, persistent_hashes, 0); if (ce->type == ZEND_INTERNAL_CLASS) { #ifdef ZTS int n = zend_hash_num_elements(CG(class_table)); if (CG(static_members_table) && n >= CG(last_static_member)) { /* Support for run-time declaration: dl() */ CG(last_static_member) = n+1; CG(static_members_table) = realloc(CG(static_members_table), (n+1)*sizeof(zval**)); CG(static_members_table)[n] = NULL; } ce->static_members_table = (zval**)(zend_intptr_t)n; #else ce->static_members_table = NULL; #endif } else { ce->static_members_table = ce->default_static_members_table; ce->info.user.doc_comment = NULL; ce->info.user.doc_comment_len = 0; } ce->default_properties_count = 0; ce->default_static_members_count = 0; if (nullify_handlers) { ce->constructor = NULL; ce->destructor = NULL; ce->clone = NULL; ce->__get = NULL; ce->__set = NULL; ce->__unset = NULL; ce->__isset = NULL; ce->__call = NULL; ce->__callstatic = NULL; ce->__tostring = NULL; ce->create_object = NULL; ce->get_iterator = NULL; ce->iterator_funcs.funcs = NULL; ce->interface_gets_implemented = NULL; ce->get_static_method = NULL; ce->parent = NULL; ce->num_interfaces = 0; ce->interfaces = NULL; ce->num_traits = 0; ce->traits = NULL; ce->trait_aliases = NULL; ce->trait_precedences = NULL; ce->serialize = NULL; ce->unserialize = NULL; ce->serialize_func = NULL; ce->unserialize_func = NULL; if (ce->type == ZEND_INTERNAL_CLASS) { ce->info.internal.module = NULL; ce->info.internal.builtin_functions = NULL; } } } /* }}} */ int zend_get_class_fetch_type(const char *class_name, uint class_name_len) /* {{{ */ { if ((class_name_len == sizeof("self")-1) && !memcmp(class_name, "self", sizeof("self")-1)) { return ZEND_FETCH_CLASS_SELF; } else if ((class_name_len == sizeof("parent")-1) && !memcmp(class_name, "parent", sizeof("parent")-1)) { return ZEND_FETCH_CLASS_PARENT; } else if ((class_name_len == sizeof("static")-1) && !memcmp(class_name, "static", sizeof("static")-1)) { return ZEND_FETCH_CLASS_STATIC; } else { return ZEND_FETCH_CLASS_DEFAULT; } } /* }}} */ ZEND_API const char* zend_get_compiled_variable_name(const zend_op_array *op_array, zend_uint var, int* name_len) /* {{{ */ { if (name_len) { *name_len = op_array->vars[var].name_len; } return op_array->vars[var].name; } /* }}} */ void zend_do_build_namespace_name(znode *result, znode *prefix, znode *name TSRMLS_DC) /* {{{ */ { if (prefix) { *result = *prefix; if (Z_TYPE(result->u.constant) == IS_STRING && Z_STRLEN(result->u.constant) == 0) { /* namespace\ */ if (CG(current_namespace)) { znode tmp; zval_dtor(&result->u.constant); tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(result, NULL, &tmp TSRMLS_CC); } } } else { result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_STRING; Z_STRVAL(result->u.constant) = NULL; Z_STRLEN(result->u.constant) = 0; } /* prefix = result */ zend_do_build_full_name(NULL, result, name, 0 TSRMLS_CC); } /* }}} */ void zend_do_begin_namespace(const znode *name, zend_bool with_bracket TSRMLS_DC) /* {{{ */ { char *lcname; /* handle mixed syntax declaration or nested namespaces */ if (!CG(has_bracketed_namespaces)) { if (CG(current_namespace)) { /* previous namespace declarations were unbracketed */ if (with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } } } else { /* previous namespace declarations were bracketed */ if (!with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } else if (CG(current_namespace) || CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "Namespace declarations cannot be nested"); } } if (((!with_bracket && !CG(current_namespace)) || (with_bracket && !CG(has_bracketed_namespaces))) && CG(active_op_array)->last > 0) { /* ignore ZEND_EXT_STMT and ZEND_TICKS */ int num = CG(active_op_array)->last; while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Namespace declaration statement has to be the very first statement in the script"); } } CG(in_namespace) = 1; if (with_bracket) { CG(has_bracketed_namespaces) = 1; } if (name) { lcname = zend_str_tolower_dup(Z_STRVAL(name->u.constant), Z_STRLEN(name->u.constant)); if (((Z_STRLEN(name->u.constant) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN(name->u.constant) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as namespace name", Z_STRVAL(name->u.constant)); } efree(lcname); if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); } else { ALLOC_ZVAL(CG(current_namespace)); } *CG(current_namespace) = name->u.constant; } else { if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_use(znode *ns_name, znode *new_name, int is_global TSRMLS_DC) /* {{{ */ { char *lcname; zval *name, *ns, tmp; zend_bool warn = 0; zend_class_entry **pce; if (!CG(current_import)) { CG(current_import) = emalloc(sizeof(HashTable)); zend_hash_init(CG(current_import), 0, NULL, ZVAL_PTR_DTOR, 0); } ALLOC_ZVAL(ns); *ns = ns_name->u.constant; if (new_name) { name = &new_name->u.constant; } else { const char *p; /* The form "use A\B" is eqivalent to "use A\B as B". So we extract the last part of compound name to use as a new_name */ name = &tmp; p = zend_memrchr(Z_STRVAL_P(ns), '\\', Z_STRLEN_P(ns)); if (p) { ZVAL_STRING(name, p+1, 1); } else { *name = *ns; zval_copy_ctor(name); warn = !is_global && !CG(current_namespace); } } lcname = zend_str_tolower_dup(Z_STRVAL_P(name), Z_STRLEN_P(name)); if (((Z_STRLEN_P(name) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN_P(name) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because '%s' is a special class name", Z_STRVAL_P(ns), Z_STRVAL_P(name), Z_STRVAL_P(name)); } if (CG(current_namespace)) { /* Prefix import name with current namespace name to avoid conflicts with classes */ char *c_ns_name = emalloc(Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) + 1); zend_str_tolower_copy(c_ns_name, Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); c_ns_name[Z_STRLEN_P(CG(current_namespace))] = '\\'; memcpy(c_ns_name+Z_STRLEN_P(CG(current_namespace))+1, lcname, Z_STRLEN_P(name)+1); if (zend_hash_exists(CG(class_table), c_ns_name, Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name)+1)) { char *tmp2 = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) || memcmp(tmp2, c_ns_name, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(tmp2); } efree(c_ns_name); } else if (zend_hash_find(CG(class_table), lcname, Z_STRLEN_P(name)+1, (void**)&pce) == SUCCESS && (*pce)->type == ZEND_USER_CLASS && (*pce)->info.user.filename == CG(compiled_filename)) { char *c_tmp = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(name) || memcmp(c_tmp, lcname, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(c_tmp); } if (zend_hash_add(CG(current_import), lcname, Z_STRLEN_P(name)+1, &ns, sizeof(zval*), NULL) != SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } if (warn) { if (!strcmp(Z_STRVAL_P(name), "strict")) { zend_error(E_COMPILE_ERROR, "You seem to be trying to use a different language..."); } zend_error(E_WARNING, "The use statement with non-compound name '%s' has no effect", Z_STRVAL_P(name)); } efree(lcname); zval_dtor(name); } /* }}} */ void zend_do_declare_constant(znode *name, znode *value TSRMLS_DC) /* {{{ */ { zend_op *opline; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed as constants"); } if (zend_get_ct_const(&name->u.constant, 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare constant '%s'", Z_STRVAL(name->u.constant)); } if (CG(current_namespace)) { /* Prefix constant name with name of current namespace, lowercased */ znode tmp; tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); Z_STRVAL(tmp.u.constant) = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), Z_STRLEN(tmp.u.constant)); zend_do_build_namespace_name(&tmp, &tmp, name TSRMLS_CC); *name = tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DECLARE_CONST; SET_UNUSED(opline->result); SET_NODE(opline->op1, name); SET_NODE(opline->op2, value); } /* }}} */ void zend_verify_namespace(TSRMLS_D) /* {{{ */ { if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "No code may exist outside of namespace {}"); } } /* }}} */ void zend_do_end_namespace(TSRMLS_D) /* {{{ */ { CG(in_namespace) = 0; if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_end_compilation(TSRMLS_D) /* {{{ */ { CG(has_bracketed_namespaces) = 0; zend_do_end_namespace(TSRMLS_C); } /* }}} */ /* {{{ zend_dirname Returns directory name component of path */ ZEND_API size_t zend_dirname(char *path, size_t len) { register char *end = path + len - 1; unsigned int len_adjust = 0; #ifdef PHP_WIN32 /* Note that on Win32 CWD is per drive (heritage from CP/M). * This means dirname("c:foo") maps to "c:." or "c:" - which means CWD on C: drive. */ if ((2 <= len) && isalpha((int)((unsigned char *)path)[0]) && (':' == path[1])) { /* Skip over the drive spec (if any) so as not to change */ path += 2; len_adjust += 2; if (2 == len) { /* Return "c:" on Win32 for dirname("c:"). * It would be more consistent to return "c:." * but that would require making the string *longer*. */ return len; } } #elif defined(NETWARE) /* * Find the first occurence of : from the left * move the path pointer to the position just after : * increment the len_adjust to the length of path till colon character(inclusive) * If there is no character beyond : simple return len */ char *colonpos = NULL; colonpos = strchr(path, ':'); if (colonpos != NULL) { len_adjust = ((colonpos - path) + 1); path += len_adjust; if (len_adjust == len) { return len; } } #endif if (len == 0) { /* Illegal use of this function */ return 0; } /* Strip trailing slashes */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { /* The path only contained slashes */ path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } /* Strip filename */ while (end >= path && !IS_SLASH_P(end)) { end--; } if (end < path) { /* No slash found, therefore return '.' */ #ifdef NETWARE if (len_adjust == 0) { path[0] = '.'; path[1] = '\0'; return 1; /* only one character */ } else { path[0] = '\0'; return len_adjust; } #else path[0] = '.'; path[1] = '\0'; return 1 + len_adjust; #endif } /* Strip slashes which came before the file name */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } *(end+1) = '\0'; return (size_t)(end + 1 - path) + len_adjust; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */ /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2011 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <zend_language_parser.h> #include "zend.h" #include "zend_compile.h" #include "zend_constants.h" #include "zend_llist.h" #include "zend_API.h" #include "zend_exceptions.h" #include "tsrm_virtual_cwd.h" #include "zend_multibyte.h" #include "zend_language_scanner.h" #define CONSTANT_EX(op_array, op) \ (op_array)->literals[op].constant #define CONSTANT(op) \ CONSTANT_EX(CG(active_op_array), op) #define SET_NODE(target, src) do { \ target ## _type = (src)->op_type; \ if ((src)->op_type == IS_CONST) { \ target.constant = zend_add_literal(CG(active_op_array), &(src)->u.constant TSRMLS_CC); \ } else { \ target = (src)->u.op; \ } \ } while (0) #define GET_NODE(target, src) do { \ (target)->op_type = src ## _type; \ if ((target)->op_type == IS_CONST) { \ (target)->u.constant = CONSTANT(src.constant); \ } else { \ (target)->u.op = src; \ (target)->EA = 0; \ } \ } while (0) #define COPY_NODE(target, src) do { \ target ## _type = src ## _type; \ target = src; \ } while (0) #define CALCULATE_LITERAL_HASH(num) do { \ if (IS_INTERNED(Z_STRVAL(CONSTANT(num)))) { \ Z_HASH_P(&CONSTANT(num)) = INTERNED_HASH(Z_STRVAL(CONSTANT(num))); \ } else { \ Z_HASH_P(&CONSTANT(num)) = zend_hash_func(Z_STRVAL(CONSTANT(num)), Z_STRLEN(CONSTANT(num))+1); \ } \ } while (0) #define GET_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot++; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ } \ } while (0) #define POLYMORPHIC_CACHE_SLOT_SIZE 2 #define GET_POLYMORPHIC_CACHE_SLOT(literal) do { \ CG(active_op_array)->literals[literal].cache_slot = CG(active_op_array)->last_cache_slot; \ CG(active_op_array)->last_cache_slot += POLYMORPHIC_CACHE_SLOT_SIZE; \ if ((CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) && CG(active_op_array)->run_time_cache) { \ CG(active_op_array)->run_time_cache = erealloc(CG(active_op_array)->run_time_cache, CG(active_op_array)->last_cache_slot * sizeof(void*)); \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 1] = NULL; \ CG(active_op_array)->run_time_cache[CG(active_op_array)->last_cache_slot - 2] = NULL; \ } \ } while (0) #define FREE_POLYMORPHIC_CACHE_SLOT(literal) do { \ if (CG(active_op_array)->literals[literal].cache_slot == \ CG(active_op_array)->last_cache_slot - POLYMORPHIC_CACHE_SLOT_SIZE) { \ CG(active_op_array)->literals[literal].cache_slot = -1; \ CG(active_op_array)->last_cache_slot -= POLYMORPHIC_CACHE_SLOT_SIZE; \ } \ } while (0) ZEND_API zend_op_array *(*zend_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); ZEND_API zend_op_array *(*zend_compile_string)(zval *source_string, char *filename TSRMLS_DC); #ifndef ZTS ZEND_API zend_compiler_globals compiler_globals; ZEND_API zend_executor_globals executor_globals; #endif static void zend_duplicate_property_info(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = estrndup(property_info->name, property_info->name_length); } if (property_info->doc_comment) { property_info->doc_comment = estrndup(property_info->doc_comment, property_info->doc_comment_len); } } /* }}} */ static void zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */ { if (!IS_INTERNED(property_info->name)) { property_info->name = zend_strndup(property_info->name, property_info->name_length); } } /* }}} */ static void zend_destroy_property_info(zend_property_info *property_info) /* {{{ */ { str_efree(property_info->name); if (property_info->doc_comment) { efree((char*)property_info->doc_comment); } } /* }}} */ static void zend_destroy_property_info_internal(zend_property_info *property_info) /* {{{ */ { str_free((char*)property_info->name); } /* }}} */ static void build_runtime_defined_function_key(zval *result, const char *name, int name_length TSRMLS_DC) /* {{{ */ { char char_pos_buf[32]; uint char_pos_len; const char *filename; char_pos_len = zend_sprintf(char_pos_buf, "%p", LANG_SCNG(yy_text)); if (CG(active_op_array)->filename) { filename = CG(active_op_array)->filename; } else { filename = "-"; } /* NULL, name length, filename length, last accepting char position length */ result->value.str.len = 1+name_length+strlen(filename)+char_pos_len; /* must be binary safe */ result->value.str.val = (char *) safe_emalloc(result->value.str.len, 1, 1); result->value.str.val[0] = '\0'; sprintf(result->value.str.val+1, "%s%s%s", name, filename, char_pos_buf); result->type = IS_STRING; Z_SET_REFCOUNT_P(result, 1); } /* }}} */ static void init_compiler_declarables(TSRMLS_D) /* {{{ */ { Z_TYPE(CG(declarables).ticks) = IS_LONG; Z_LVAL(CG(declarables).ticks) = 0; } /* }}} */ void zend_init_compiler_context(TSRMLS_D) /* {{{ */ { CG(context).opcodes_size = (CG(active_op_array)->fn_flags & ZEND_ACC_INTERACTIVE) ? INITIAL_INTERACTIVE_OP_ARRAY_SIZE : INITIAL_OP_ARRAY_SIZE; CG(context).vars_size = 0; CG(context).literals_size = 0; CG(context).current_brk_cont = -1; CG(context).backpatch_count = 0; CG(context).labels = NULL; } /* }}} */ void zend_init_compiler_data_structures(TSRMLS_D) /* {{{ */ { zend_stack_init(&CG(bp_stack)); zend_stack_init(&CG(function_call_stack)); zend_stack_init(&CG(switch_cond_stack)); zend_stack_init(&CG(foreach_copy_stack)); zend_stack_init(&CG(object_stack)); zend_stack_init(&CG(declare_stack)); CG(active_class_entry) = NULL; zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_stack_init(&CG(list_stack)); CG(in_compilation) = 0; CG(start_lineno) = 0; CG(current_namespace) = NULL; CG(in_namespace) = 0; CG(has_bracketed_namespaces) = 0; CG(current_import) = NULL; init_compiler_declarables(TSRMLS_C); zend_stack_init(&CG(context_stack)); CG(encoding_declared) = 0; } /* }}} */ ZEND_API void file_handle_dtor(zend_file_handle *fh) /* {{{ */ { TSRMLS_FETCH(); zend_file_handle_dtor(fh TSRMLS_CC); } /* }}} */ void init_compiler(TSRMLS_D) /* {{{ */ { CG(active_op_array) = NULL; zend_init_compiler_data_structures(TSRMLS_C); zend_init_rsrc_list(TSRMLS_C); zend_hash_init(&CG(filenames_table), 5, NULL, (dtor_func_t) free_estring, 0); zend_llist_init(&CG(open_files), sizeof(zend_file_handle), (void (*)(void *)) file_handle_dtor, 0); CG(unclean_shutdown) = 0; } /* }}} */ void shutdown_compiler(TSRMLS_D) /* {{{ */ { zend_stack_destroy(&CG(bp_stack)); zend_stack_destroy(&CG(function_call_stack)); zend_stack_destroy(&CG(switch_cond_stack)); zend_stack_destroy(&CG(foreach_copy_stack)); zend_stack_destroy(&CG(object_stack)); zend_stack_destroy(&CG(declare_stack)); zend_stack_destroy(&CG(list_stack)); zend_hash_destroy(&CG(filenames_table)); zend_llist_destroy(&CG(open_files)); zend_stack_destroy(&CG(context_stack)); } /* }}} */ ZEND_API char *zend_set_compiled_filename(const char *new_compiled_filename TSRMLS_DC) /* {{{ */ { char **pp, *p; int length = strlen(new_compiled_filename); if (zend_hash_find(&CG(filenames_table), new_compiled_filename, length+1, (void **) &pp) == SUCCESS) { CG(compiled_filename) = *pp; return *pp; } p = estrndup(new_compiled_filename, length); zend_hash_update(&CG(filenames_table), new_compiled_filename, length+1, &p, sizeof(char *), (void **) &pp); CG(compiled_filename) = p; return p; } /* }}} */ ZEND_API void zend_restore_compiled_filename(char *original_compiled_filename TSRMLS_DC) /* {{{ */ { CG(compiled_filename) = original_compiled_filename; } /* }}} */ ZEND_API char *zend_get_compiled_filename(TSRMLS_D) /* {{{ */ { return CG(compiled_filename); } /* }}} */ ZEND_API int zend_get_compiled_lineno(TSRMLS_D) /* {{{ */ { return CG(zend_lineno); } /* }}} */ ZEND_API zend_bool zend_is_compiling(TSRMLS_D) /* {{{ */ { return CG(in_compilation); } /* }}} */ static zend_uint get_temporary_variable(zend_op_array *op_array) /* {{{ */ { return (op_array->T)++ * ZEND_MM_ALIGNED_SIZE(sizeof(temp_variable)); } /* }}} */ static int lookup_cv(zend_op_array *op_array, char* name, int name_len, ulong hash TSRMLS_DC) /* {{{ */ { int i = 0; ulong hash_value = hash ? hash : zend_inline_hash_func(name, name_len+1); while (i < op_array->last_var) { if (op_array->vars[i].name == name || (op_array->vars[i].hash_value == hash_value && op_array->vars[i].name_len == name_len && memcmp(op_array->vars[i].name, name, name_len) == 0)) { str_efree(name); return i; } i++; } i = op_array->last_var; op_array->last_var++; if (op_array->last_var > CG(context).vars_size) { CG(context).vars_size += 16; /* FIXME */ op_array->vars = erealloc(op_array->vars, CG(context).vars_size * sizeof(zend_compiled_variable)); } op_array->vars[i].name = zend_new_interned_string(name, name_len + 1, 1 TSRMLS_CC); op_array->vars[i].name_len = name_len; op_array->vars[i].hash_value = hash_value; return i; } /* }}} */ void zend_del_literal(zend_op_array *op_array, int n) /* {{{ */ { zval_dtor(&CONSTANT_EX(op_array, n)); if (n + 1 == op_array->last_literal) { op_array->last_literal--; } else { Z_TYPE(CONSTANT_EX(op_array, n)) = IS_NULL; } } /* }}} */ /* Common part of zend_add_literal and zend_append_individual_literal */ static inline void zend_insert_literal(zend_op_array *op_array, const zval *zv, int literal_position TSRMLS_DC) /* {{{ */ { if (Z_TYPE_P(zv) == IS_STRING || Z_TYPE_P(zv) == IS_CONSTANT) { zval *z = (zval*)zv; Z_STRVAL_P(z) = (char*)zend_new_interned_string(Z_STRVAL_P(zv), Z_STRLEN_P(zv) + 1, 1 TSRMLS_CC); } CONSTANT_EX(op_array, literal_position) = *zv; Z_SET_REFCOUNT(CONSTANT_EX(op_array, literal_position), 2); Z_SET_ISREF(CONSTANT_EX(op_array, literal_position)); op_array->literals[literal_position].hash_value = 0; op_array->literals[literal_position].cache_slot = -1; } /* }}} */ /* Is used while compiling a function, using the context to keep track of an approximate size to avoid to relocate to often. Literals are truncated to actual size in the second compiler pass (pass_two()). */ int zend_add_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; if (i >= CG(context).literals_size) { while (i >= CG(context).literals_size) { CG(context).literals_size += 16; /* FIXME */ } op_array->literals = (zend_literal*)erealloc(op_array->literals, CG(context).literals_size * sizeof(zend_literal)); } zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ /* Is used after normal compilation to append an additional literal. Allocation is done precisely here. */ int zend_append_individual_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int i = op_array->last_literal; op_array->last_literal++; op_array->literals = (zend_literal*)erealloc(op_array->literals, (i + 1) * sizeof(zend_literal)); zend_insert_literal(op_array, zv, i TSRMLS_CC); return i; } /* }}} */ int zend_add_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_ns_func_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; const char *ns_separator; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), Z_STRLEN_P(zv)); ZVAL_STRINGL(&c, lc_name, Z_STRLEN_P(zv), 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); ns_separator = (const char*)zend_memrchr(Z_STRVAL_P(zv), '\\', Z_STRLEN_P(zv)) + 1; lc_len = Z_STRLEN_P(zv) - (ns_separator - Z_STRVAL_P(zv)); lc_name = zend_str_tolower_dup(ns_separator, lc_len); ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); return ret; } /* }}} */ int zend_add_class_name_literal(zend_op_array *op_array, const zval *zv TSRMLS_DC) /* {{{ */ { int ret; char *lc_name; int lc_len; zval c; int lc_literal; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } if (Z_STRVAL_P(zv)[0] == '\\') { lc_len = Z_STRLEN_P(zv) - 1; lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv) + 1, lc_len); } else { lc_len = Z_STRLEN_P(zv); lc_name = zend_str_tolower_dup(Z_STRVAL_P(zv), lc_len); } ZVAL_STRINGL(&c, lc_name, lc_len, 0); lc_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(lc_literal); GET_CACHE_SLOT(ret); return ret; } /* }}} */ int zend_add_const_name_literal(zend_op_array *op_array, const zval *zv, int unqualified TSRMLS_DC) /* {{{ */ { int ret, tmp_literal; char *name, *tmp_name; const char *ns_separator; int name_len, ns_len; zval c; if (op_array->last_literal > 0 && &op_array->literals[op_array->last_literal - 1].constant == zv && op_array->literals[op_array->last_literal - 1].cache_slot == -1) { /* we already have function name as last literal (do nothing) */ ret = op_array->last_literal - 1; } else { ret = zend_add_literal(op_array, zv TSRMLS_CC); } /* skip leading '\\' */ if (Z_STRVAL_P(zv)[0] == '\\') { name_len = Z_STRLEN_P(zv) - 1; name = Z_STRVAL_P(zv) + 1; } else { name_len = Z_STRLEN_P(zv); name = Z_STRVAL_P(zv); } ns_separator = zend_memrchr(name, '\\', name_len); if (ns_separator) { ns_len = ns_separator - name; } else { ns_len = 0; } if (ns_len) { /* lowercased namespace name & original constant name */ tmp_name = estrndup(name, name_len); zend_str_tolower(tmp_name, ns_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased namespace name & lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); } if (ns_len) { if (!unqualified) { return ret; } ns_len++; name += ns_len; name_len -= ns_len; } /* original constant name */ tmp_name = estrndup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); /* lowercased constant name */ tmp_name = zend_str_tolower_dup(name, name_len); ZVAL_STRINGL(&c, tmp_name, name_len, 0); tmp_literal = zend_add_literal(CG(active_op_array), &c TSRMLS_CC); CALCULATE_LITERAL_HASH(tmp_literal); return ret; } /* }}} */ #define LITERAL_STRINGL(op, str, len, copy) do { \ zval _c; \ ZVAL_STRINGL(&_c, str, len, copy); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG(op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) #define LITERAL_LONG_EX(op_array, op, val) do { \ zval _c; \ ZVAL_LONG(&_c, val); \ op.constant = zend_add_literal(op_array, &_c TSRMLS_CC); \ } while (0) #define LITERAL_NULL(op) do { \ zval _c; \ INIT_ZVAL( _c); \ op.constant = zend_add_literal(CG(active_op_array), &_c TSRMLS_CC); \ } while (0) static inline zend_bool zend_is_function_or_method_call(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; return ((type & ZEND_PARSED_METHOD_CALL) || (type == ZEND_PARSED_FUNCTION_CALL)); } /* }}} */ void zend_do_binary_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_unary_op(zend_uchar op, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); GET_NODE(result, opline->result); SET_UNUSED(opline->op2); } /* }}} */ #define MAKE_NOP(opline) { opline->opcode = ZEND_NOP; memset(&opline->result,0,sizeof(opline->result)); memset(&opline->op1,0,sizeof(opline->op1)); memset(&opline->op2,0,sizeof(opline->op2)); opline->result_type=opline->op1_type=opline->op2_type=IS_UNUSED; } static void zend_do_op_data(zend_op *data_op, const znode *value TSRMLS_DC) /* {{{ */ { data_op->opcode = ZEND_OP_DATA; SET_NODE(data_op->op1, value); SET_UNUSED(data_op->op2); } /* }}} */ void zend_do_binary_assign_op(zend_uchar op, znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; switch (last_op->opcode) { case ZEND_FETCH_OBJ_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, op2 TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; case ZEND_FETCH_DIM_RW: last_op->opcode = op; last_op->extended_value = ZEND_ASSIGN_DIM; zend_do_op_data(opline, op2 TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result,last_op->result); return; default: break; } } opline->opcode = op; SET_NODE(opline->op1, op1); SET_NODE(opline->op2, op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void fetch_simple_variable_ex(znode *result, znode *varname, int bp, zend_uchar op TSRMLS_DC) /* {{{ */ { zend_op opline; zend_op *opline_ptr; zend_llist *fetch_list_ptr; if (varname->op_type == IS_CONST) { ulong hash = 0; if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } else if (IS_INTERNED(Z_STRVAL(varname->u.constant))) { hash = INTERNED_HASH(Z_STRVAL(varname->u.constant)); } if (!zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC) && !(varname->u.constant.value.str.len == (sizeof("this")-1) && !memcmp(varname->u.constant.value.str.val, "this", sizeof("this"))) && (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE)) { result->op_type = IS_CV; result->u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, hash TSRMLS_CC); varname->u.constant.value.str.val = (char*)CG(active_op_array)->vars[result->u.op.var].name; result->EA = 0; return; } } if (bp) { opline_ptr = &opline; init_op(opline_ptr TSRMLS_CC); } else { opline_ptr = get_next_op(CG(active_op_array) TSRMLS_CC); } opline_ptr->opcode = op; opline_ptr->result_type = IS_VAR; opline_ptr->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline_ptr->op1, varname); GET_NODE(result, opline_ptr->result); SET_UNUSED(opline_ptr->op2); opline_ptr->extended_value = ZEND_FETCH_LOCAL; if (varname->op_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline_ptr->op1.constant); if (zend_is_auto_global_quick(varname->u.constant.value.str.val, varname->u.constant.value.str.len, Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC)) { opline_ptr->extended_value = ZEND_FETCH_GLOBAL; } } if (bp) { zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); zend_llist_add_element(fetch_list_ptr, opline_ptr); } } /* }}} */ void fetch_simple_variable(znode *result, znode *varname, int bp TSRMLS_DC) /* {{{ */ { /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ fetch_simple_variable_ex(result, varname, bp, ZEND_FETCH_W TSRMLS_CC); } /* }}} */ void zend_do_fetch_static_member(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { znode class_node; zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline_ptr; zend_op opline; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); } zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (result->op_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[result->u.op.var].name), CG(active_op_array)->vars[result->u.op.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } GET_NODE(result,opline.result); opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; opline_ptr = &opline; zend_llist_add_element(fetch_list_ptr, &opline); } else { le = fetch_list_ptr->head; opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode != ZEND_FETCH_W && opline_ptr->op1_type == IS_CV) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_W; opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); opline.op1_type = IS_CONST; LITERAL_STRINGL(opline.op1, estrdup(CG(active_op_array)->vars[opline_ptr->op1.var].name), CG(active_op_array)->vars[opline_ptr->op1.var].name_len, 0); CALCULATE_LITERAL_HASH(opline.op1.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op1.constant); if (class_node.op_type == IS_CONST) { opline.op2_type = IS_CONST; opline.op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline.op2, &class_node); } opline.extended_value |= ZEND_FETCH_STATIC_MEMBER; COPY_NODE(opline_ptr->op1, opline.result); zend_llist_prepend_element(fetch_list_ptr, &opline); } else { if (opline_ptr->op1_type == IS_CONST) { GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op1.constant); } if (class_node.op_type == IS_CONST) { opline_ptr->op2_type = IS_CONST; opline_ptr->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline_ptr->op2, &class_node); } opline_ptr->extended_value |= ZEND_FETCH_STATIC_MEMBER; } } } /* }}} */ void fetch_array_begin(znode *result, znode *varname, znode *first_dim TSRMLS_DC) /* {{{ */ { fetch_simple_variable(result, varname, 1 TSRMLS_CC); fetch_array_dim(result, result, first_dim TSRMLS_CC); } /* }}} */ void fetch_array_dim(znode *result, const znode *parent, const znode *dim TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (zend_is_function_or_method_call(parent)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, parent); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_DIM_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, parent); SET_NODE(opline.op2, dim); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline.op2.constant)), Z_STRLEN(CONSTANT(opline.op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline.op2.constant)); ZVAL_LONG(&CONSTANT(opline.op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline.op2.constant); } } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void fetch_string_offset(znode *result, const znode *parent, const znode *offset TSRMLS_DC) /* {{{ */ { fetch_array_dim(result, parent, offset TSRMLS_CC); } /* }}} */ void zend_do_print(znode *result, const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->opcode = ZEND_PRINT; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_echo(const znode *arg TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ECHO; SET_NODE(opline->op1, arg); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_abstract_method(const znode *function_name, znode *modifiers, const znode *body TSRMLS_DC) /* {{{ */ { char *method_type; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { Z_LVAL(modifiers->u.constant) |= ZEND_ACC_ABSTRACT; method_type = "Interface"; } else { method_type = "Abstract"; } if (modifiers->u.constant.value.lval & ZEND_ACC_ABSTRACT) { if(modifiers->u.constant.value.lval & ZEND_ACC_PRIVATE) { zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot be declared private", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } if (Z_LVAL(body->u.constant) == ZEND_ACC_ABSTRACT) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_RAISE_ABSTRACT_ERROR; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } else { /* we had code in the function body */ zend_error(E_COMPILE_ERROR, "%s function %s::%s() cannot contain body", method_type, CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } else { if (body->u.constant.value.lval == ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Non-abstract method %s::%s() must contain body", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } } } /* }}} */ static zend_bool opline_is_fetch_this(const zend_op *opline TSRMLS_DC) /* {{{ */ { if ((opline->opcode == ZEND_FETCH_W) && (opline->op1_type == IS_CONST) && (Z_TYPE(CONSTANT(opline->op1.constant)) == IS_STRING) && (Z_HASH_P(&CONSTANT(opline->op1.constant)) == THIS_HASHVAL) && (Z_STRLEN(CONSTANT(opline->op1.constant)) == (sizeof("this")-1)) && !memcmp(Z_STRVAL(CONSTANT(opline->op1.constant)), "this", sizeof("this"))) { return 1; } else { return 0; } } /* }}} */ void zend_do_assign(znode *result, znode *variable, znode *value TSRMLS_DC) /* {{{ */ { int last_op_number; zend_op *opline; if (value->op_type == IS_CV) { zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (fetch_list_ptr && fetch_list_ptr->head) { opline = (zend_op *)fetch_list_ptr->head->data; if (opline->opcode == ZEND_FETCH_DIM_W && opline->op1_type == IS_CV && opline->op1.var == value->u.op.var) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_R; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->op1_type = IS_CONST; LITERAL_STRINGL(opline->op1, CG(active_op_array)->vars[value->u.op.var].name, CG(active_op_array)->vars[value->u.op.var].name_len, 1); CALCULATE_LITERAL_HASH(opline->op1.constant); SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_LOCAL; GET_NODE(value, opline->result); } } } zend_do_end_variable_parse(variable, BP_VAR_W, 0 TSRMLS_CC); last_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (variable->op_type == IS_CV) { if (variable->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (variable->op_type == IS_VAR) { int n = 0; while (last_op_number - n > 0) { zend_op *last_op; last_op = &CG(active_op_array)->opcodes[last_op_number-n-1]; if (last_op->result_type == IS_VAR && last_op->result.var == variable->u.op.var) { if (last_op->opcode == ZEND_FETCH_OBJ_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_OBJ; zend_do_op_data(opline, value TSRMLS_CC); SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (last_op->opcode == ZEND_FETCH_DIM_W) { if (n > 0) { int opline_no = (opline-CG(active_op_array)->opcodes)/sizeof(*opline); *opline = *last_op; MAKE_NOP(last_op); /* last_op = opline; */ /* TBFixed: this can realloc opcodes, leaving last_op pointing wrong */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* get_next_op can realloc, we need to move last_op */ last_op = &CG(active_op_array)->opcodes[opline_no]; } last_op->opcode = ZEND_ASSIGN_DIM; zend_do_op_data(opline, value TSRMLS_CC); opline->op2.var = get_temporary_variable(CG(active_op_array)); opline->op2_type = IS_VAR; SET_UNUSED(opline->result); GET_NODE(result, last_op->result); return; } else if (opline_is_fetch_this(last_op TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } else { break; } } n++; } } opline->opcode = ZEND_ASSIGN; SET_NODE(opline->op1, variable); SET_NODE(opline->op2, value); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_assign_ref(znode *result, const znode *lvar, const znode *rvar TSRMLS_DC) /* {{{ */ { zend_op *opline; if (lvar->op_type == IS_CV) { if (lvar->u.op.var == CG(active_op_array)->this_var) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } else if (lvar->op_type == IS_VAR) { int last_op_number = get_next_op_number(CG(active_op_array)); if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline_is_fetch_this(opline TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ASSIGN_REF; if (zend_is_function_or_method_call(rvar)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } else if (rvar->EA & ZEND_PARSED_NEW) { opline->extended_value = ZEND_RETURNS_NEW; } else { opline->extended_value = 0; } if (result) { opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } else { opline->result_type = IS_UNUSED | EXT_TYPE_UNUSED; } SET_NODE(opline->op1, lvar); SET_NODE(opline->op2, rvar); } /* }}} */ static inline void do_begin_loop(TSRMLS_D) /* {{{ */ { zend_brk_cont_element *brk_cont_element; int parent; parent = CG(context).current_brk_cont; CG(context).current_brk_cont = CG(active_op_array)->last_brk_cont; brk_cont_element = get_next_brk_cont_element(CG(active_op_array)); brk_cont_element->start = get_next_op_number(CG(active_op_array)); brk_cont_element->parent = parent; } /* }}} */ static inline void do_end_loop(int cont_addr, int has_loop_var TSRMLS_DC) /* {{{ */ { if (!has_loop_var) { /* The start fileld is used to free temporary variables in case of exceptions. * We won't try to free something of we don't have loop variable. */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].start = -1; } CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = cont_addr; CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; } /* }}} */ void zend_do_while_cond(const znode *expr, znode *close_bracket_token TSRMLS_DC) /* {{{ */ { int while_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, expr); close_bracket_token->u.op.opline_num = while_cond_op_number; SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_while_end(const znode *while_token, const znode *close_bracket_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* add unconditional jump */ opline->opcode = ZEND_JMP; opline->op1.opline_num = while_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* update while's conditional jmp */ CG(active_op_array)->opcodes[close_bracket_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); do_end_loop(while_token->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_cond(const znode *expr, znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { int for_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZNZ; SET_NODE(opline->op1, expr); /* the conditional expression */ second_semicolon_token->u.op.opline_num = for_cond_op_number; SET_UNUSED(opline->op2); } /* }}} */ void zend_do_for_before_statement(const znode *cond_start, const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = cond_start->u.op.opline_num; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_for_end(const znode *second_semicolon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = second_semicolon_token->u.op.opline_num+1; CG(active_op_array)->opcodes[second_semicolon_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); do_end_loop(second_semicolon_token->u.op.opline_num+1, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_pre_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_PRE_INC)?ZEND_PRE_INC_OBJ:ZEND_PRE_DEC_OBJ; last_op->result_type = IS_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_post_incdec(znode *result, const znode *op1, zend_uchar op TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { zend_op *last_op = &CG(active_op_array)->opcodes[last_op_number-1]; if (last_op->opcode == ZEND_FETCH_OBJ_RW) { last_op->opcode = (op==ZEND_POST_INC)?ZEND_POST_INC_OBJ:ZEND_POST_DEC_OBJ; last_op->result_type = IS_TMP_VAR; last_op->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, last_op->result); return; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_if_cond(const znode *cond, znode *closing_bracket_token TSRMLS_DC) /* {{{ */ { int if_cond_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); closing_bracket_token->u.op.opline_num = if_cond_op_number; SET_UNUSED(opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_if_after_statement(const znode *closing_bracket_token, unsigned char initialize TSRMLS_DC) /* {{{ */ { int if_end_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; /* save for backpatching */ if (initialize) { zend_llist jmp_list; zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); } zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &if_end_op_number); CG(active_op_array)->opcodes[closing_bracket_token->u.op.opline_num].op2.opline_num = if_end_op_number+1; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_if_end(TSRMLS_D) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_llist *jmp_list_ptr; zend_llist_element *le; zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); for (le=jmp_list_ptr->head; le; le = le->next) { CG(active_op_array)->opcodes[*((int *) le->data)].op1.opline_num = next_op_number; } zend_llist_destroy(jmp_list_ptr); zend_stack_del_top(&CG(bp_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_check_writable_variable(const znode *variable) /* {{{ */ { zend_uint type = variable->EA; if (type & ZEND_PARSED_METHOD_CALL) { zend_error(E_COMPILE_ERROR, "Can't use method return value in write context"); } if (type == ZEND_PARSED_FUNCTION_CALL) { zend_error(E_COMPILE_ERROR, "Can't use function return value in write context"); } } /* }}} */ void zend_do_begin_variable_parse(TSRMLS_D) /* {{{ */ { zend_llist fetch_list; zend_llist_init(&fetch_list, sizeof(zend_op), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &fetch_list, sizeof(zend_llist)); } /* }}} */ void zend_do_end_variable_parse(znode *variable, int type, int arg_offset TSRMLS_DC) /* {{{ */ { zend_llist *fetch_list_ptr; zend_llist_element *le; zend_op *opline = NULL; zend_op *opline_ptr; zend_uint this_var = -1; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); le = fetch_list_ptr->head; /* TODO: $foo->x->y->z = 1 should fetch "x" and "y" for R or RW, not just W */ if (le) { opline_ptr = (zend_op *)le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { /* convert to FETCH_?(this) into IS_CV */ if (CG(active_op_array)->last == 0 || CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode != ZEND_BEGIN_SILENCE) { this_var = opline_ptr->result.var; if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), Z_STRVAL(CONSTANT(opline_ptr->op1.constant)), Z_STRLEN(CONSTANT(opline_ptr->op1.constant)), Z_HASH_P(&CONSTANT(opline_ptr->op1.constant)) TSRMLS_CC); Z_TYPE(CONSTANT(opline_ptr->op1.constant)) = IS_NULL; } else { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); } le = le->next; if (variable->op_type == IS_VAR && variable->u.op.var == this_var) { variable->op_type = IS_CV; variable->u.op.var = CG(active_op_array)->this_var; } } else if (CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } while (le) { opline_ptr = (zend_op *)le->data; if (opline_ptr->opcode == ZEND_SEPARATE) { if (type != BP_VAR_R && type != BP_VAR_IS) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); } le = le->next; continue; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); memcpy(opline, opline_ptr, sizeof(zend_op)); if (opline->op1_type == IS_VAR && opline->op1.var == this_var) { opline->op1_type = IS_CV; opline->op1.var = CG(active_op_array)->this_var; } switch (type) { case BP_VAR_R: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode -= 3; break; case BP_VAR_W: break; case BP_VAR_RW: opline->opcode += 3; break; case BP_VAR_IS: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } opline->opcode += 6; /* 3+3 */ break; case BP_VAR_FUNC_ARG: opline->opcode += 9; /* 3+3+3 */ opline->extended_value |= arg_offset; break; case BP_VAR_UNSET: if (opline->opcode == ZEND_FETCH_DIM_W && opline->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for unsetting"); } opline->opcode += 12; /* 3+3+3+3 */ break; } le = le->next; } if (opline && type == BP_VAR_W && arg_offset) { opline->extended_value |= ZEND_FETCH_MAKE_REF; } } zend_llist_destroy(fetch_list_ptr); zend_stack_del_top(&CG(bp_stack)); } /* }}} */ void zend_do_add_string(znode *result, const znode *op1, znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline; if (Z_STRLEN(op2->u.constant) > 1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_STRING; } else if (Z_STRLEN(op2->u.constant) == 1) { int ch = *Z_STRVAL(op2->u.constant); /* Free memory and use ZEND_ADD_CHAR in case of 1 character strings */ efree(Z_STRVAL(op2->u.constant)); ZVAL_LONG(&op2->u.constant, ch); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_CHAR; } else { /* String can be empty after a variable at the end of a heredoc */ efree(Z_STRVAL(op2->u.constant)); return; } if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_add_variable(znode *result, const znode *op1, const znode *op2 TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_VAR; if (op1) { SET_NODE(opline->op1, op1); SET_NODE(opline->result, op1); } else { SET_UNUSED(opline->op1); opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); } SET_NODE(opline->op2, op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_free(znode *op1 TSRMLS_DC) /* {{{ */ { if (op1->op_type==IS_TMP_VAR) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else if (op1->op_type==IS_VAR) { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; while (opline->opcode == ZEND_END_SILENCE || opline->opcode == ZEND_EXT_FCALL_END || opline->opcode == ZEND_OP_DATA) { opline--; } if (opline->result_type == IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_FETCH_R || opline->opcode == ZEND_FETCH_DIM_R || opline->opcode == ZEND_FETCH_OBJ_R || opline->opcode == ZEND_QM_ASSIGN_VAR) { /* It's very rare and useless case. It's better to use additional FREE opcode and simplify the FETCH handlers their selves */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FREE; SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); } else { opline->result_type |= EXT_TYPE_UNUSED; } } else { while (opline>CG(active_op_array)->opcodes) { if (opline->opcode == ZEND_FETCH_DIM_R && opline->op1_type == IS_VAR && opline->op1.var == op1->u.op.var) { /* This should the end of a list() construct * Mark its result as unused */ opline->extended_value = ZEND_FETCH_STANDARD; break; } else if (opline->result_type==IS_VAR && opline->result.var == op1->u.op.var) { if (opline->opcode == ZEND_NEW) { opline->result_type |= EXT_TYPE_UNUSED; } break; } opline--; } } } else if (op1->op_type == IS_CONST) { zval_dtor(&op1->u.constant); } } /* }}} */ int zend_do_verify_access_types(const znode *current_access_type, const znode *new_modifier) /* {{{ */ { if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_PPP_MASK) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Multiple access type modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_ABSTRACT) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Multiple abstract modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_STATIC) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Multiple static modifiers are not allowed"); } if ((Z_LVAL(current_access_type->u.constant) & ZEND_ACC_FINAL) && (Z_LVAL(new_modifier->u.constant) & ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Multiple final modifiers are not allowed"); } if (((Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)) & (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) == (ZEND_ACC_ABSTRACT | ZEND_ACC_FINAL)) { zend_error(E_COMPILE_ERROR, "Cannot use the final modifier on an abstract class member"); } return (Z_LVAL(current_access_type->u.constant) | Z_LVAL(new_modifier->u.constant)); } /* }}} */ void zend_do_begin_function_declaration(znode *function_token, znode *function_name, int is_method, int return_reference, znode *fn_flags_znode TSRMLS_DC) /* {{{ */ { zend_op_array op_array; char *name = function_name->u.constant.value.str.val; int name_len = function_name->u.constant.value.str.len; int function_begin_line = function_token->u.op.opline_num; zend_uint fn_flags; const char *lcname; zend_bool orig_interactive; ALLOCA_FLAG(use_heap) if (is_method) { if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((Z_LVAL(fn_flags_znode->u.constant) & ~(ZEND_ACC_STATIC|ZEND_ACC_PUBLIC))) { zend_error(E_COMPILE_ERROR, "Access type for interface method %s::%s() must be omitted", CG(active_class_entry)->name, function_name->u.constant.value.str.val); } Z_LVAL(fn_flags_znode->u.constant) |= ZEND_ACC_ABSTRACT; /* propagates to the rest of the parser */ } fn_flags = Z_LVAL(fn_flags_znode->u.constant); /* must be done *after* the above check */ } else { fn_flags = 0; } if ((fn_flags & ZEND_ACC_STATIC) && (fn_flags & ZEND_ACC_ABSTRACT) && !(CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_STRICT, "Static function %s%s%s() should not be abstract", is_method ? CG(active_class_entry)->name : "", is_method ? "::" : "", Z_STRVAL(function_name->u.constant)); } function_token->u.op_array = CG(active_op_array); orig_interactive = CG(interactive); CG(interactive) = 0; init_op_array(&op_array, ZEND_USER_FUNCTION, INITIAL_OP_ARRAY_SIZE TSRMLS_CC); CG(interactive) = orig_interactive; op_array.function_name = name; if (return_reference) { op_array.fn_flags |= ZEND_ACC_RETURN_REFERENCE; } op_array.fn_flags |= fn_flags; op_array.scope = is_method?CG(active_class_entry):NULL; op_array.prototype = NULL; op_array.line_start = zend_get_compiled_lineno(TSRMLS_C); if (is_method) { int result; lcname = zend_new_interned_string(zend_str_tolower_dup(name, name_len), name_len + 1, 1 TSRMLS_CC); if (IS_INTERNED(lcname)) { result = zend_hash_quick_add(&CG(active_class_entry)->function_table, lcname, name_len+1, INTERNED_HASH(lcname), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } else { result = zend_hash_add(&CG(active_class_entry)->function_table, lcname, name_len+1, &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); } if (result == FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::%s()", CG(active_class_entry)->name, name); } zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); if (fn_flags & ZEND_ACC_ABSTRACT) { CG(active_class_entry)->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (!(fn_flags & ZEND_ACC_PPP_MASK)) { fn_flags |= ZEND_ACC_PUBLIC; } if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } } } else { char *class_lcname; class_lcname = do_alloca(CG(active_class_entry)->name_length + 1, use_heap); zend_str_tolower_copy(class_lcname, CG(active_class_entry)->name, CG(active_class_entry)->name_length); /* Improve after RC: cache the lowercase class name */ if ((CG(active_class_entry)->name_length == name_len) && ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT) && (!memcmp(class_lcname, lcname, name_len))) { if (!CG(active_class_entry)->constructor) { CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } } else if ((name_len == sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)))) { if (CG(active_class_entry)->constructor) { zend_error(E_STRICT, "Redefining already defined constructor for class %s", CG(active_class_entry)->name); } CG(active_class_entry)->constructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME)-1))) { CG(active_class_entry)->destructor = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CLONE_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1))) { CG(active_class_entry)->clone = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALL_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __call() must have public visibility and cannot be static"); } CG(active_class_entry)->__call = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1))) { if ((fn_flags & (ZEND_ACC_PPP_MASK ^ ZEND_ACC_PUBLIC)) || (fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_WARNING, "The magic method __callStatic() must have public visibility and be static"); } CG(active_class_entry)->__callstatic = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_GET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __get() must have public visibility and cannot be static"); } CG(active_class_entry)->__get = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_SET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __set() must have public visibility and cannot be static"); } CG(active_class_entry)->__set = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_UNSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __unset() must have public visibility and cannot be static"); } CG(active_class_entry)->__unset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_ISSET_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __isset() must have public visibility and cannot be static"); } CG(active_class_entry)->__isset = (zend_function *) CG(active_op_array); } else if ((name_len == sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && (!memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1))) { if (fn_flags & ((ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC) ^ ZEND_ACC_PUBLIC)) { zend_error(E_WARNING, "The magic method __toString() must have public visibility and cannot be static"); } CG(active_class_entry)->__tostring = (zend_function *) CG(active_op_array); } else if (!(fn_flags & ZEND_ACC_STATIC)) { CG(active_op_array)->fn_flags |= ZEND_ACC_ALLOW_STATIC; } free_alloca(class_lcname, use_heap); } str_efree(lcname); } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zval key; if (CG(current_namespace)) { /* Prefix function name with current namespcae name */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, function_name TSRMLS_CC); op_array.function_name = Z_STRVAL(tmp.u.constant); name_len = Z_STRLEN(tmp.u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), name_len); } else { lcname = zend_str_tolower_dup(name, name_len); } opline->opcode = ZEND_DECLARE_FUNCTION; opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, name_len TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; LITERAL_STRINGL(opline->op2, lcname, name_len, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); opline->extended_value = ZEND_DECLARE_FUNCTION; zend_hash_quick_update(CG(function_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &op_array, sizeof(zend_op_array), (void **) &CG(active_op_array)); zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context))); zend_init_compiler_context(TSRMLS_C); } if (CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_NOP; opline->lineno = function_begin_line; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } { /* Push a seperator to the switch and foreach stacks */ zend_switch_entry switch_entry; switch_entry.cond.op_type = IS_UNUSED; switch_entry.default_case = 0; switch_entry.control_var = 0; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); { /* Foreach stack separator */ zend_op dummy_opline; dummy_opline.result_type = IS_UNUSED; dummy_opline.op1_type = IS_UNUSED; zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); } } if (CG(doc_comment)) { CG(active_op_array)->doc_comment = CG(doc_comment); CG(active_op_array)->doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_begin_lambda_function_declaration(znode *result, znode *function_token, int return_reference, int is_static TSRMLS_DC) /* {{{ */ { znode function_name; zend_op_array *current_op_array = CG(active_op_array); int current_op_number = get_next_op_number(CG(active_op_array)); zend_op *current_op; function_name.op_type = IS_CONST; ZVAL_STRINGL(&function_name.u.constant, "{closure}", sizeof("{closure}")-1, 1); zend_do_begin_function_declaration(function_token, &function_name, 0, return_reference, NULL TSRMLS_CC); result->op_type = IS_TMP_VAR; result->u.op.var = get_temporary_variable(current_op_array); current_op = &current_op_array->opcodes[current_op_number]; current_op->opcode = ZEND_DECLARE_LAMBDA_FUNCTION; zend_del_literal(current_op_array, current_op->op2.constant); SET_UNUSED(current_op->op2); SET_NODE(current_op->result, result); if (is_static) { CG(active_op_array)->fn_flags |= ZEND_ACC_STATIC; } CG(active_op_array)->fn_flags |= ZEND_ACC_CLOSURE; } /* }}} */ void zend_do_handle_exception(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_HANDLE_EXCEPTION; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_function_declaration(const znode *function_token TSRMLS_DC) /* {{{ */ { char lcname[16]; int name_len; zend_do_extended_info(TSRMLS_C); zend_do_return(NULL, 0 TSRMLS_CC); pass_two(CG(active_op_array) TSRMLS_CC); zend_release_labels(TSRMLS_C); if (CG(active_class_entry)) { zend_check_magic_method_implementation(CG(active_class_entry), (zend_function*)CG(active_op_array), E_COMPILE_ERROR TSRMLS_CC); } else { /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = strlen(CG(active_op_array)->function_name); zend_str_tolower_copy(lcname, CG(active_op_array)->function_name, MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_AUTOLOAD_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_AUTOLOAD_FUNC_NAME, sizeof(ZEND_AUTOLOAD_FUNC_NAME)) && CG(active_op_array)->num_args != 1) { zend_error(E_COMPILE_ERROR, "%s() must take exactly 1 argument", ZEND_AUTOLOAD_FUNC_NAME); } } CG(active_op_array)->line_end = zend_get_compiled_lineno(TSRMLS_C); CG(active_op_array) = function_token->u.op_array; /* Pop the switch and foreach seperators */ zend_stack_del_top(&CG(switch_cond_stack)); zend_stack_del_top(&CG(foreach_copy_stack)); } /* }}} */ void zend_do_receive_arg(zend_uchar op, znode *varname, const znode *offset, const znode *initialization, znode *class_type, zend_uchar pass_by_reference TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_arg_info *cur_arg_info; znode var; if (class_type->op_type == IS_CONST && Z_TYPE(class_type->u.constant) == IS_STRING && Z_STRLEN(class_type->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_type->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } if (zend_is_auto_global_quick(Z_STRVAL(varname->u.constant), Z_STRLEN(varname->u.constant), 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot re-assign auto-global variable %s", Z_STRVAL(varname->u.constant)); } else { var.op_type = IS_CV; var.u.op.var = lookup_cv(CG(active_op_array), varname->u.constant.value.str.val, varname->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(varname->u.constant) = (char*)CG(active_op_array)->vars[var.u.op.var].name; var.EA = 0; if (CG(active_op_array)->vars[var.u.op.var].hash_value == THIS_HASHVAL && Z_STRLEN(varname->u.constant) == sizeof("this")-1 && !memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this")-1)) { if (CG(active_op_array)->scope && (CG(active_op_array)->fn_flags & ZEND_ACC_STATIC) == 0) { zend_error(E_COMPILE_ERROR, "Cannot re-assign $this"); } CG(active_op_array)->this_var = var.u.op.var; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->num_args++; opline->opcode = op; SET_NODE(opline->result, &var); SET_NODE(opline->op1, offset); if (op == ZEND_RECV_INIT) { SET_NODE(opline->op2, initialization); } else { CG(active_op_array)->required_num_args = CG(active_op_array)->num_args; SET_UNUSED(opline->op2); } CG(active_op_array)->arg_info = erealloc(CG(active_op_array)->arg_info, sizeof(zend_arg_info)*(CG(active_op_array)->num_args)); cur_arg_info = &CG(active_op_array)->arg_info[CG(active_op_array)->num_args-1]; cur_arg_info->name = zend_new_interned_string(estrndup(varname->u.constant.value.str.val, varname->u.constant.value.str.len), varname->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->name_len = varname->u.constant.value.str.len; cur_arg_info->type_hint = 0; cur_arg_info->allow_null = 1; cur_arg_info->pass_by_reference = pass_by_reference; cur_arg_info->class_name = NULL; cur_arg_info->class_name_len = 0; if (class_type->op_type != IS_UNUSED) { cur_arg_info->allow_null = 0; if (class_type->u.constant.type != IS_NULL) { if (class_type->u.constant.type == IS_ARRAY) { cur_arg_info->type_hint = IS_ARRAY; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else if (Z_TYPE(initialization->u.constant) != IS_ARRAY && Z_TYPE(initialization->u.constant) != IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Default value for parameters with array type hint can only be an array or NULL"); } } } else if (class_type->u.constant.type == IS_CALLABLE) { cur_arg_info->type_hint = IS_CALLABLE; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with callable type hint can only be NULL"); } } } else { cur_arg_info->type_hint = IS_OBJECT; if (ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_type->u.constant), Z_STRLEN(class_type->u.constant))) { zend_resolve_class_name(class_type, opline->extended_value, 1 TSRMLS_CC); } Z_STRVAL(class_type->u.constant) = (char*)zend_new_interned_string(class_type->u.constant.value.str.val, class_type->u.constant.value.str.len + 1, 1 TSRMLS_CC); cur_arg_info->class_name = class_type->u.constant.value.str.val; cur_arg_info->class_name_len = class_type->u.constant.value.str.len; if (op == ZEND_RECV_INIT) { if (Z_TYPE(initialization->u.constant) == IS_NULL || (Z_TYPE(initialization->u.constant) == IS_CONSTANT && !strcasecmp(Z_STRVAL(initialization->u.constant), "NULL"))) { cur_arg_info->allow_null = 1; } else { zend_error(E_COMPILE_ERROR, "Default value for parameters with a class type hint can only be NULL"); } } } } } } /* }}} */ int zend_do_begin_function_call(znode *function_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { zend_function *function; char *lcname; char *is_compound = memchr(Z_STRVAL(function_name->u.constant), '\\', Z_STRLEN(function_name->u.constant)); zend_resolve_non_class_name(function_name, check_namespace TSRMLS_CC); if (check_namespace && CG(current_namespace) && !is_compound) { /* We assume we call function from the current namespace if it is not prefixed. */ /* In run-time PHP will check for function with full name and internal function with short name */ zend_do_begin_dynamic_function_call(function_name, 1 TSRMLS_CC); return 1; } lcname = zend_str_tolower_dup(function_name->u.constant.value.str.val, function_name->u.constant.value.str.len); if ((zend_hash_find(CG(function_table), lcname, function_name->u.constant.value.str.len+1, (void **) &function)==FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_FUNCTIONS) && (function->type == ZEND_INTERNAL_FUNCTION))) { zend_do_begin_dynamic_function_call(function_name, 0 TSRMLS_CC); efree(lcname); return 1; /* Dynamic */ } efree(function_name->u.constant.value.str.val); function_name->u.constant.value.str.val = lcname; zend_stack_push(&CG(function_call_stack), (void *) &function, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 0; } /* }}} */ void zend_do_begin_method_call(znode *left_bracket TSRMLS_DC) /* {{{ */ { zend_op *last_op; int last_op_number; unsigned char *ptr = NULL; zend_do_end_variable_parse(left_bracket, BP_VAR_R, 0 TSRMLS_CC); zend_do_begin_variable_parse(TSRMLS_C); last_op_number = get_next_op_number(CG(active_op_array))-1; last_op = &CG(active_op_array)->opcodes[last_op_number]; if ((last_op->op2_type == IS_CONST) && (Z_TYPE(CONSTANT(last_op->op2.constant)) == IS_STRING) && (Z_STRLEN(CONSTANT(last_op->op2.constant)) == sizeof(ZEND_CLONE_FUNC_NAME)-1) && !zend_binary_strcasecmp(Z_STRVAL(CONSTANT(last_op->op2.constant)), Z_STRLEN(CONSTANT(last_op->op2.constant)), ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME)-1)) { zend_error(E_COMPILE_ERROR, "Cannot call __clone() method on objects - use 'clone $obj' instead"); } if (last_op->opcode == ZEND_FETCH_OBJ_R) { if (last_op->op2_type == IS_CONST) { zval name; name = CONSTANT(last_op->op2.constant); if (!IS_INTERNED(Z_STRVAL(name))) { Z_STRVAL(name) = estrndup(Z_STRVAL(name), Z_STRLEN(name)); } FREE_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); last_op->op2.constant = zend_add_func_name_literal(CG(active_op_array), &name TSRMLS_CC); GET_POLYMORPHIC_CACHE_SLOT(last_op->op2.constant); } last_op->opcode = ZEND_INIT_METHOD_CALL; SET_UNUSED(last_op->result); Z_LVAL(left_bracket->u.constant) = ZEND_INIT_FCALL_BY_NAME; } else { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (left_bracket->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &left_bracket->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, left_bracket); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_do_clone(znode *result, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CLONE; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); } /* }}} */ void zend_do_begin_dynamic_function_call(znode *function_name, int ns_call TSRMLS_DC) /* {{{ */ { unsigned char *ptr = NULL; zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (ns_call) { /* In run-time PHP will check for function with full name and internal function with short name */ opline->opcode = ZEND_INIT_NS_FCALL_BY_NAME; SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_ns_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { opline->opcode = ZEND_INIT_FCALL_BY_NAME; SET_UNUSED(opline->op1); if (function_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &function_name->u.constant TSRMLS_CC); GET_CACHE_SLOT(opline->op2.constant); } else { SET_NODE(opline->op2, function_name); } } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); } /* }}} */ void zend_resolve_non_class_name(znode *element_name, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; int len; zval **ns; char *lcname, *compound = memchr(Z_STRVAL(element_name->u.constant), '\\', Z_STRLEN(element_name->u.constant)); if (Z_STRVAL(element_name->u.constant)[0] == '\\') { /* name starts with \ so it is known and unambiguos, nothing to do here but shorten it */ memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+1, Z_STRLEN(element_name->u.constant)); --Z_STRLEN(element_name->u.constant); return; } if(!check_namespace) { return; } if (compound && CG(current_import)) { len = compound - Z_STRVAL(element_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(element_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(element_name->u.constant) -= len; memmove(Z_STRVAL(element_name->u.constant), Z_STRVAL(element_name->u.constant)+len, Z_STRLEN(element_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, element_name TSRMLS_CC); *element_name = tmp; efree(lcname); return; } efree(lcname); } if (CG(current_namespace)) { tmp = *element_name; Z_STRLEN(tmp.u.constant) = sizeof("\\")-1 + Z_STRLEN(element_name->u.constant) + Z_STRLEN_P(CG(current_namespace)); Z_STRVAL(tmp.u.constant) = (char *) emalloc(Z_STRLEN(tmp.u.constant)+1); memcpy(Z_STRVAL(tmp.u.constant), Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace))]), "\\", sizeof("\\")-1); memcpy(&(Z_STRVAL(tmp.u.constant)[Z_STRLEN_P(CG(current_namespace)) + sizeof("\\")-1]), Z_STRVAL(element_name->u.constant), Z_STRLEN(element_name->u.constant)+1); STR_FREE(Z_STRVAL(element_name->u.constant)); *element_name = tmp; } } /* }}} */ void zend_resolve_class_name(znode *class_name, ulong fetch_type, int check_ns_name TSRMLS_DC) /* {{{ */ { char *compound; char *lcname; zval **ns; znode tmp; int len; compound = memchr(Z_STRVAL(class_name->u.constant), '\\', Z_STRLEN(class_name->u.constant)); if (compound) { /* This is a compound class name that contains namespace prefix */ if (Z_STRVAL(class_name->u.constant)[0] == '\\') { /* The STRING name has "\" prefix */ Z_STRLEN(class_name->u.constant) -= 1; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+1, Z_STRLEN(class_name->u.constant)+1); Z_STRVAL(class_name->u.constant) = erealloc( Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1); if (ZEND_FETCH_CLASS_DEFAULT != zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "'\\%s' is an invalid class name", Z_STRVAL(class_name->u.constant)); } } else { if (CG(current_import)) { len = compound - Z_STRVAL(class_name->u.constant); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), len); /* Check if first part of compound name is an import name */ if (zend_hash_find(CG(current_import), lcname, len+1, (void**)&ns) == SUCCESS) { /* Substitute import name */ tmp.op_type = IS_CONST; tmp.u.constant = **ns; zval_copy_ctor(&tmp.u.constant); len += 1; Z_STRLEN(class_name->u.constant) -= len; memmove(Z_STRVAL(class_name->u.constant), Z_STRVAL(class_name->u.constant)+len, Z_STRLEN(class_name->u.constant)+1); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; efree(lcname); return; } efree(lcname); } /* Here name is not prefixed with \ and not imported */ if (CG(current_namespace)) { tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } } } else if (CG(current_import) || CG(current_namespace)) { /* this is a plain name (without \) */ lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns) == SUCCESS) { /* The given name is an import name. Substitute it. */ zval_dtor(&class_name->u.constant); class_name->u.constant = **ns; zval_copy_ctor(&class_name->u.constant); } else if (CG(current_namespace)) { /* plain name, no import - prepend current namespace to it */ tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); *class_name = tmp; } efree(lcname); } } /* }}} */ void zend_do_fetch_class(znode *result, znode *class_name TSRMLS_DC) /* {{{ */ { long fetch_class_op_number; zend_op *opline; if (class_name->op_type == IS_CONST && Z_TYPE(class_name->u.constant) == IS_STRING && Z_STRLEN(class_name->u.constant) == 0) { /* Usage of namespace as class name not in namespace */ zval_dtor(&class_name->u.constant); zend_error(E_COMPILE_ERROR, "Cannot use 'namespace' as a class name"); return; } fetch_class_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CLASS; SET_UNUSED(opline->op1); opline->extended_value = ZEND_FETCH_CLASS_GLOBAL; CG(catch_begin) = fetch_class_op_number; if (class_name->op_type == IS_CONST) { int fetch_type; fetch_type = zend_get_class_fetch_type(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); switch (fetch_type) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: SET_UNUSED(opline->op2); opline->extended_value = fetch_type; zval_dtor(&class_name->u.constant); break; default: zend_resolve_class_name(class_name, opline->extended_value, 0 TSRMLS_CC); opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &class_name->u.constant TSRMLS_CC); break; } } else { SET_NODE(opline->op2, class_name); } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; /* FIXME: Hack so that INIT_FCALL_BY_NAME still knows this is a class */ GET_NODE(result, opline->result); result->EA = opline->extended_value; } /* }}} */ void zend_do_label(znode *label TSRMLS_DC) /* {{{ */ { zend_label dest; if (!CG(context).labels) { ALLOC_HASHTABLE(CG(context).labels); zend_hash_init(CG(context).labels, 4, NULL, NULL, 0); } dest.brk_cont = CG(context).current_brk_cont; dest.opline_num = get_next_op_number(CG(active_op_array)); if (zend_hash_add(CG(context).labels, Z_STRVAL(label->u.constant), Z_STRLEN(label->u.constant) + 1, (void**)&dest, sizeof(zend_label), NULL) == FAILURE) { zend_error(E_COMPILE_ERROR, "Label '%s' already defined", Z_STRVAL(label->u.constant)); } /* Done with label now */ zval_dtor(&label->u.constant); } /* }}} */ void zend_resolve_goto_label(zend_op_array *op_array, zend_op *opline, int pass2 TSRMLS_DC) /* {{{ */ { zend_label *dest; long current, distance; zval *label; if (pass2) { label = opline->op2.zv; } else { label = &CONSTANT_EX(op_array, opline->op2.constant); } if (CG(context).labels == NULL || zend_hash_find(CG(context).labels, Z_STRVAL_P(label), Z_STRLEN_P(label)+1, (void**)&dest) == FAILURE) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; zend_error(E_COMPILE_ERROR, "'goto' to undefined label '%s'", Z_STRVAL_P(label)); } else { /* Label is not defined. Delay to pass 2. */ INC_BPC(op_array); return; } } opline->op1.opline_num = dest->opline_num; zval_dtor(label); Z_TYPE_P(label) = IS_NULL; /* Check that we are not moving into loop or switch */ current = opline->extended_value; for (distance = 0; current != dest->brk_cont; distance++) { if (current == -1) { if (pass2) { CG(in_compilation) = 1; CG(active_op_array) = op_array; CG(zend_lineno) = opline->lineno; } zend_error(E_COMPILE_ERROR, "'goto' into loop or switch statement is disallowed"); } current = op_array->brk_cont_array[current].parent; } if (distance == 0) { /* Nothing to break out of, optimize to ZEND_JMP */ opline->opcode = ZEND_JMP; opline->extended_value = 0; SET_UNUSED(opline->op2); } else { /* Set real break distance */ ZVAL_LONG(label, distance); } if (pass2) { DEC_BPC(op_array); } } /* }}} */ void zend_do_goto(const znode *label TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_GOTO; opline->extended_value = CG(context).current_brk_cont; SET_UNUSED(opline->op1); SET_NODE(opline->op2, label); zend_resolve_goto_label(CG(active_op_array), opline, 0 TSRMLS_CC); } /* }}} */ void zend_release_labels(TSRMLS_D) /* {{{ */ { if (CG(context).labels) { zend_hash_destroy(CG(context).labels); FREE_HASHTABLE(CG(context).labels); } if (!zend_stack_is_empty(&CG(context_stack))) { zend_compiler_context *ctx; zend_stack_top(&CG(context_stack), (void**)&ctx); CG(context) = *ctx; zend_stack_del_top(&CG(context_stack)); } } /* }}} */ void zend_do_build_full_name(znode *result, znode *prefix, znode *name, int is_class_member TSRMLS_DC) /* {{{ */ { zend_uint length; if (!result) { result = prefix; } else { *result = *prefix; } if (is_class_member) { length = sizeof("::")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "::", sizeof("::")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("::")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } else { length = sizeof("\\")-1 + result->u.constant.value.str.len + name->u.constant.value.str.len; result->u.constant.value.str.val = erealloc(result->u.constant.value.str.val, length+1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len], "\\", sizeof("\\")-1); memcpy(&result->u.constant.value.str.val[result->u.constant.value.str.len + sizeof("\\")-1], name->u.constant.value.str.val, name->u.constant.value.str.len+1); STR_FREE(name->u.constant.value.str.val); result->u.constant.value.str.len = length; } } /* }}} */ int zend_do_begin_class_member_function_call(znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { znode class_node; unsigned char *ptr = NULL; zend_op *opline; if (method_name->op_type == IS_CONST) { char *lcname = zend_str_tolower_dup(Z_STRVAL(method_name->u.constant), Z_STRLEN(method_name->u.constant)); if ((sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == Z_STRLEN(method_name->u.constant) && memcmp(lcname, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME)-1) == 0) { zval_dtor(&method_name->u.constant); method_name->op_type = IS_UNUSED; } efree(lcname); } if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); class_node = *class_name; opline = get_next_op(CG(active_op_array) TSRMLS_CC); } else { zend_do_fetch_class(&class_node, class_name TSRMLS_CC); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->extended_value = class_node.EA ; } opline->opcode = ZEND_INIT_STATIC_METHOD_CALL; if (class_node.op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &class_node.u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, &class_node); } if (method_name->op_type == IS_CONST) { opline->op2_type = IS_CONST; opline->op2.constant = zend_add_func_name_literal(CG(active_op_array), &method_name->u.constant TSRMLS_CC); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } } else { SET_NODE(opline->op2, method_name); } zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(zend_function *)); zend_do_extended_fcall_begin(TSRMLS_C); return 1; /* Dynamic */ } /* }}} */ void zend_do_end_function_call(znode *function_name, znode *result, const znode *argument_list, int is_method, int is_dynamic_fcall TSRMLS_DC) /* {{{ */ { zend_op *opline; if (is_method && function_name && function_name->op_type == IS_UNUSED) { /* clone */ if (Z_LVAL(argument_list->u.constant) != 0) { zend_error(E_WARNING, "Clone method does not require arguments"); } opline = &CG(active_op_array)->opcodes[Z_LVAL(function_name->u.constant)]; } else { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (!is_method && !is_dynamic_fcall && function_name->op_type==IS_CONST) { opline->opcode = ZEND_DO_FCALL; SET_NODE(opline->op1, function_name); CALCULATE_LITERAL_HASH(opline->op1.constant); GET_CACHE_SLOT(opline->op1.constant); } else { opline->opcode = ZEND_DO_FCALL_BY_NAME; SET_UNUSED(opline->op1); } } opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(result, opline->result) ; SET_UNUSED(opline->op2); zend_stack_del_top(&CG(function_call_stack)); opline->extended_value = Z_LVAL(argument_list->u.constant); } /* }}} */ void zend_do_pass_param(znode *param, zend_uchar op, int offset TSRMLS_DC) /* {{{ */ { zend_op *opline; int original_op=op; zend_function **function_ptr_ptr, *function_ptr; int send_by_reference; int send_function = 0; zend_stack_top(&CG(function_call_stack), (void **) &function_ptr_ptr); function_ptr = *function_ptr_ptr; if (original_op == ZEND_SEND_REF) { if (function_ptr && function_ptr->common.function_name && function_ptr->common.type == ZEND_USER_FUNCTION && !ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed; " "If you would like to pass argument by reference, modify the declaration of %s().", function_ptr->common.function_name); } else { zend_error(E_COMPILE_ERROR, "Call-time pass-by-reference has been removed"); } return; } if (function_ptr) { if (ARG_MAY_BE_SENT_BY_REF(function_ptr, (zend_uint) offset)) { if (param->op_type & (IS_VAR|IS_CV) && original_op != ZEND_SEND_VAL) { send_by_reference = 1; if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION | ZEND_ARG_SEND_SILENT; } } else { op = ZEND_SEND_VAL; send_by_reference = 0; } } else { send_by_reference = ARG_SHOULD_BE_SENT_BY_REF(function_ptr, (zend_uint) offset) ? ZEND_ARG_SEND_BY_REF : 0; } } else { send_by_reference = 0; } if (op == ZEND_SEND_VAR && zend_is_function_or_method_call(param)) { /* Method call */ op = ZEND_SEND_VAR_NO_REF; send_function = ZEND_ARG_SEND_FUNCTION; } else if (op == ZEND_SEND_VAL && (param->op_type & (IS_VAR|IS_CV))) { op = ZEND_SEND_VAR_NO_REF; } if (op!=ZEND_SEND_VAR_NO_REF && send_by_reference==ZEND_ARG_SEND_BY_REF) { /* change to passing by reference */ switch (param->op_type) { case IS_VAR: case IS_CV: op = ZEND_SEND_REF; break; default: zend_error(E_COMPILE_ERROR, "Only variables can be passed by reference"); break; } } if (original_op == ZEND_SEND_VAR) { switch (op) { case ZEND_SEND_VAR_NO_REF: zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); break; case ZEND_SEND_VAR: if (function_ptr) { zend_do_end_variable_parse(param, BP_VAR_R, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(param, BP_VAR_FUNC_ARG, offset TSRMLS_CC); } break; case ZEND_SEND_REF: zend_do_end_variable_parse(param, BP_VAR_W, 0 TSRMLS_CC); break; } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (op == ZEND_SEND_VAR_NO_REF) { if (function_ptr) { opline->extended_value = ZEND_ARG_COMPILE_TIME_BOUND | send_by_reference | send_function; } else { opline->extended_value = send_function; } } else { if (function_ptr) { opline->extended_value = ZEND_DO_FCALL; } else { opline->extended_value = ZEND_DO_FCALL_BY_NAME; } } opline->opcode = op; SET_NODE(opline->op1, param); opline->op2.opline_num = offset; SET_UNUSED(opline->op2); } /* }}} */ static int generate_free_switch_expr(const zend_switch_entry *switch_entry TSRMLS_DC) /* {{{ */ { zend_op *opline; if (switch_entry->cond.op_type != IS_VAR && switch_entry->cond.op_type != IS_TMP_VAR) { return (switch_entry->cond.op_type == IS_UNUSED); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry->cond); SET_UNUSED(opline->op2); opline->extended_value = 0; return 0; } /* }}} */ static int generate_free_foreach_copy(const zend_op *foreach_copy TSRMLS_DC) /* {{{ */ { zend_op *opline; /* If we reach the seperator then stop applying the stack */ if (foreach_copy->result_type == IS_UNUSED && foreach_copy->op1_type == IS_UNUSED) { return 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->result_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->result); SET_UNUSED(opline->op2); opline->extended_value = 1; if (foreach_copy->op1_type != IS_UNUSED) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (foreach_copy->op1_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; COPY_NODE(opline->op1, foreach_copy->op1); SET_UNUSED(opline->op2); opline->extended_value = 0; } return 0; } /* }}} */ void zend_do_return(znode *expr, int do_end_vparse TSRMLS_DC) /* {{{ */ { zend_op *opline; int start_op_number, end_op_number; if (do_end_vparse) { if ((CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) && !zend_is_function_or_method_call(expr)) { zend_do_end_variable_parse(expr, BP_VAR_W, 0 TSRMLS_CC); } else { zend_do_end_variable_parse(expr, BP_VAR_R, 0 TSRMLS_CC); } } start_op_number = get_next_op_number(CG(active_op_array)); #ifdef ZTS zend_stack_apply_with_argument(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_switch_expr TSRMLS_CC); zend_stack_apply_with_argument(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element, void *)) generate_free_foreach_copy TSRMLS_CC); #else zend_stack_apply(&CG(switch_cond_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_switch_expr); zend_stack_apply(&CG(foreach_copy_stack), ZEND_STACK_APPLY_TOPDOWN, (int (*)(void *element)) generate_free_foreach_copy); #endif end_op_number = get_next_op_number(CG(active_op_array)); while (start_op_number < end_op_number) { CG(active_op_array)->opcodes[start_op_number].extended_value |= EXT_TYPE_FREE_ON_RETURN; start_op_number++; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (CG(active_op_array)->fn_flags & ZEND_ACC_RETURN_REFERENCE) ? ZEND_RETURN_BY_REF : ZEND_RETURN; if (expr) { SET_NODE(opline->op1, expr); if (do_end_vparse && zend_is_function_or_method_call(expr)) { opline->extended_value = ZEND_RETURNS_FUNCTION; } } else { opline->op1_type = IS_CONST; LITERAL_NULL(opline->op1); } SET_UNUSED(opline->op2); } /* }}} */ static int zend_add_try_element(zend_uint try_op TSRMLS_DC) /* {{{ */ { int try_catch_offset = CG(active_op_array)->last_try_catch++; CG(active_op_array)->try_catch_array = erealloc(CG(active_op_array)->try_catch_array, sizeof(zend_try_catch_element)*CG(active_op_array)->last_try_catch); CG(active_op_array)->try_catch_array[try_catch_offset].try_op = try_op; return try_catch_offset; } /* }}} */ static void zend_add_catch_element(int offset, zend_uint catch_op TSRMLS_DC) /* {{{ */ { CG(active_op_array)->try_catch_array[offset].catch_op = catch_op; } /* }}} */ void zend_do_first_catch(znode *open_parentheses TSRMLS_DC) /* {{{ */ { open_parentheses->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_initialize_try_catch_element(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist jmp_list; zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_llist_init(&jmp_list, sizeof(int), NULL, 0); zend_stack_push(&CG(bp_stack), (void *) &jmp_list, sizeof(zend_llist)); zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); zend_add_catch_element(try_token->u.op.opline_num, get_next_op_number(CG(active_op_array)) TSRMLS_CC); } /* }}} */ void zend_do_mark_last_catch(const znode *first_catch, const znode *last_additional_catch TSRMLS_DC) /* {{{ */ { CG(active_op_array)->last--; zend_do_if_end(TSRMLS_C); if (last_additional_catch->u.op.opline_num == -1) { CG(active_op_array)->opcodes[first_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[first_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } else { CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].result.num = 1; CG(active_op_array)->opcodes[last_additional_catch->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_try(znode *try_token TSRMLS_DC) /* {{{ */ { try_token->u.op.opline_num = zend_add_try_element(get_next_op_number(CG(active_op_array)) TSRMLS_CC); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_catch(znode *try_token, znode *class_name, znode *catch_var, znode *first_catch TSRMLS_DC) /* {{{ */ { long catch_op_number; zend_op *opline; znode catch_class; if (class_name->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant))) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); catch_class = *class_name; } else { zend_error(E_COMPILE_ERROR, "Bad class name in the catch statement"); } catch_op_number = get_next_op_number(CG(active_op_array)); if (first_catch) { first_catch->u.op.opline_num = catch_op_number; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CATCH; opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &catch_class.u.constant TSRMLS_CC); opline->op2_type = IS_CV; opline->op2.var = lookup_cv(CG(active_op_array), catch_var->u.constant.value.str.val, catch_var->u.constant.value.str.len, 0 TSRMLS_CC); Z_STRVAL(catch_var->u.constant) = (char*)CG(active_op_array)->vars[opline->op2.var].name; opline->result.num = 0; /* 1 means it's the last catch in the block */ try_token->u.op.opline_num = catch_op_number; } /* }}} */ void zend_do_end_catch(const znode *try_token TSRMLS_DC) /* {{{ */ { int jmp_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_llist *jmp_list_ptr; opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); /* save for backpatching */ zend_stack_top(&CG(bp_stack), (void **) &jmp_list_ptr); zend_llist_add_element(jmp_list_ptr, &jmp_op_number); CG(active_op_array)->opcodes[try_token->u.op.opline_num].extended_value = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_throw(const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_THROW; SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); } /* }}} */ ZEND_API void function_add_ref(zend_function *function) /* {{{ */ { if (function->type == ZEND_USER_FUNCTION) { zend_op_array *op_array = &function->op_array; (*op_array->refcount)++; if (op_array->static_variables) { HashTable *static_variables = op_array->static_variables; zval *tmp_zval; ALLOC_HASHTABLE(op_array->static_variables); zend_hash_init(op_array->static_variables, zend_hash_num_elements(static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(op_array->static_variables, static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_zval, sizeof(zval *)); } op_array->run_time_cache = NULL; } } /* }}} */ static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */ { zend_function *function, *new_function; if (!ce->parent) { return; } /* You cannot change create_object */ ce->create_object = ce->parent->create_object; /* Inherit special functions if needed */ if (!ce->get_iterator) { ce->get_iterator = ce->parent->get_iterator; } if (!ce->iterator_funcs.funcs) { ce->iterator_funcs.funcs = ce->parent->iterator_funcs.funcs; } if (!ce->__get) { ce->__get = ce->parent->__get; } if (!ce->__set) { ce->__set = ce->parent->__set; } if (!ce->__unset) { ce->__unset = ce->parent->__unset; } if (!ce->__isset) { ce->__isset = ce->parent->__isset; } if (!ce->__call) { ce->__call = ce->parent->__call; } if (!ce->__callstatic) { ce->__callstatic = ce->parent->__callstatic; } if (!ce->__tostring) { ce->__tostring = ce->parent->__tostring; } if (!ce->clone) { ce->clone = ce->parent->clone; } if(!ce->serialize) { ce->serialize = ce->parent->serialize; } if(!ce->unserialize) { ce->unserialize = ce->parent->unserialize; } if (!ce->destructor) { ce->destructor = ce->parent->destructor; } if (ce->constructor) { if (ce->parent->constructor && ce->parent->constructor->common.fn_flags & ZEND_ACC_FINAL) { zend_error(E_ERROR, "Cannot override final %s::%s() with %s::%s()", ce->parent->name, ce->parent->constructor->common.function_name, ce->name, ce->constructor->common.function_name ); } return; } if (zend_hash_find(&ce->parent->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), (void **)&function)==SUCCESS) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, ZEND_CONSTRUCTOR_FUNC_NAME, sizeof(ZEND_CONSTRUCTOR_FUNC_NAME), function, sizeof(zend_function), (void**)&new_function); function_add_ref(new_function); } else { /* Don't inherit the old style constructor if we already have the new style constructor */ char *lc_class_name; char *lc_parent_class_name; lc_class_name = zend_str_tolower_dup(ce->name, ce->name_length); if (!zend_hash_exists(&ce->function_table, lc_class_name, ce->name_length+1)) { lc_parent_class_name = zend_str_tolower_dup(ce->parent->name, ce->parent->name_length); if (!zend_hash_exists(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1) && zend_hash_find(&ce->parent->function_table, lc_parent_class_name, ce->parent->name_length+1, (void **)&function)==SUCCESS) { if (function->common.fn_flags & ZEND_ACC_CTOR) { /* inherit parent's constructor */ zend_hash_update(&ce->function_table, lc_parent_class_name, ce->parent->name_length+1, function, sizeof(zend_function), (void**)&new_function); function_add_ref(new_function); } } efree(lc_parent_class_name); } efree(lc_class_name); } ce->constructor = ce->parent->constructor; } /* }}} */ char *zend_visibility_string(zend_uint fn_flags) /* {{{ */ { if (fn_flags & ZEND_ACC_PRIVATE) { return "private"; } if (fn_flags & ZEND_ACC_PROTECTED) { return "protected"; } if (fn_flags & ZEND_ACC_PUBLIC) { return "public"; } return ""; } /* }}} */ static void do_inherit_method(zend_function *function) /* {{{ */ { /* The class entry of the derived function intentionally remains the same * as that of the parent class. That allows us to know in which context * we're running, and handle private method calls properly. */ function_add_ref(function); } /* }}} */ static zend_bool zend_do_perform_implementation_check(const zend_function *fe, const zend_function *proto TSRMLS_DC) /* {{{ */ { zend_uint i; /* If it's a user function then arg_info == NULL means we don't have any parameters but * we still need to do the arg number checks. We are only willing to ignore this for internal * functions because extensions don't always define arg_info. */ if (!proto || (!proto->common.arg_info && proto->common.type != ZEND_USER_FUNCTION)) { return 1; } /* Checks for constructors only if they are declared in an interface, * or explicitly marked as abstract */ if ((fe->common.fn_flags & ZEND_ACC_CTOR) && ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)) { return 1; } /* check number of arguments */ if (proto->common.required_num_args < fe->common.required_num_args || proto->common.num_args > fe->common.num_args) { return 0; } if (fe->common.type != ZEND_USER_FUNCTION && (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) != 0 && (fe->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) == 0) { return 0; } /* by-ref constraints on return values are covariant */ if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) { return 0; } for (i=0; i < proto->common.num_args; i++) { if (ZEND_LOG_XOR(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)) { /* Only one has a type hint and the other one doesn't */ return 0; } if (fe->common.arg_info[i].class_name && strcasecmp(fe->common.arg_info[i].class_name, proto->common.arg_info[i].class_name)!=0) { const char *colon; if (fe->common.type != ZEND_USER_FUNCTION) { return 0; } else if (strchr(proto->common.arg_info[i].class_name, '\\') != NULL || (colon = zend_memrchr(fe->common.arg_info[i].class_name, '\\', fe->common.arg_info[i].class_name_len)) == NULL || strcasecmp(colon+1, proto->common.arg_info[i].class_name) != 0) { zend_class_entry **fe_ce, **proto_ce; int found, found2; found = zend_lookup_class(fe->common.arg_info[i].class_name, fe->common.arg_info[i].class_name_len, &fe_ce TSRMLS_CC); found2 = zend_lookup_class(proto->common.arg_info[i].class_name, proto->common.arg_info[i].class_name_len, &proto_ce TSRMLS_CC); /* Check for class alias */ if (found != SUCCESS || found2 != SUCCESS || (*fe_ce)->type == ZEND_INTERNAL_CLASS || (*proto_ce)->type == ZEND_INTERNAL_CLASS || *fe_ce != *proto_ce) { return 0; } } } if (fe->common.arg_info[i].type_hint != proto->common.arg_info[i].type_hint) { /* Incompatible type hint */ return 0; } /* by-ref constraints on arguments are invariant */ if (fe->common.arg_info[i].pass_by_reference != proto->common.arg_info[i].pass_by_reference) { return 0; } } if (proto->common.fn_flags & ZEND_ACC_PASS_REST_BY_REFERENCE) { for (i=proto->common.num_args; i < fe->common.num_args; i++) { if (!fe->common.arg_info[i].pass_by_reference) { return 0; } } } return 1; } /* }}} */ #define REALLOC_BUF_IF_EXCEED(buf, offset, length, size) \ if (UNEXPECTED(offset - buf + size >= length)) { \ length += size + 1; \ buf = erealloc(buf, length); \ } static char * zend_get_function_declaration(zend_function *fptr TSRMLS_DC) /* {{{ */ { char *offset, *buf; zend_uint length = 1024; offset = buf = (char *)emalloc(length * sizeof(char)); if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { *(offset++) = '&'; *(offset++) = ' '; } if (fptr->common.scope) { memcpy(offset, fptr->common.scope->name, fptr->common.scope->name_length); offset += fptr->common.scope->name_length; *(offset++) = ':'; *(offset++) = ':'; } { size_t name_len = strlen(fptr->common.function_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, name_len); memcpy(offset, fptr->common.function_name, name_len); offset += name_len; } *(offset++) = '('; if (fptr->common.arg_info) { zend_uint i, required; zend_arg_info *arg_info = fptr->common.arg_info; required = fptr->common.required_num_args; for (i = 0; i < fptr->common.num_args;) { if (arg_info->class_name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->class_name_len); memcpy(offset, arg_info->class_name, arg_info->class_name_len); offset += arg_info->class_name_len; *(offset++) = ' '; } else if (arg_info->type_hint) { zend_uint type_name_len; char *type_name = zend_get_type_by_const(arg_info->type_hint); type_name_len = strlen(type_name); REALLOC_BUF_IF_EXCEED(buf, offset, length, type_name_len); memcpy(offset, type_name, type_name_len); offset += type_name_len; *(offset++) = ' '; } if (arg_info->pass_by_reference) { *(offset++) = '&'; } *(offset++) = '$'; if (arg_info->name) { REALLOC_BUF_IF_EXCEED(buf, offset, length, arg_info->name_len); memcpy(offset, arg_info->name, arg_info->name_len); offset += arg_info->name_len; } else { zend_uint idx = i; memcpy(offset, "param", 5); offset += 5; do { *(offset++) = (char) (idx % 10) + '0'; idx /= 10; } while (idx > 0); } if (i >= required) { *(offset++) = ' '; *(offset++) = '='; *(offset++) = ' '; if (fptr->type == ZEND_USER_FUNCTION) { zend_op *precv = NULL; { zend_uint idx = i; zend_op *op = ((zend_op_array *)fptr)->opcodes; zend_op *end = op + ((zend_op_array *)fptr)->last; ++idx; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT) && op->op1.num == (long)idx) { precv = op; } ++op; } } if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) { zval *zv, zv_copy; int use_copy; ALLOC_ZVAL(zv); *zv = *precv->op2.zv; zval_copy_ctor(zv); INIT_PZVAL(zv); zval_update_constant_ex(&zv, (void*)1, fptr->common.scope TSRMLS_CC); if (Z_TYPE_P(zv) == IS_BOOL) { if (Z_LVAL_P(zv)) { memcpy(offset, "true", 4); offset += 4; } else { memcpy(offset, "false", 5); offset += 5; } } else if (Z_TYPE_P(zv) == IS_NULL) { memcpy(offset, "NULL", 4); offset += 4; } else if (Z_TYPE_P(zv) == IS_STRING) { *(offset++) = '\''; REALLOC_BUF_IF_EXCEED(buf, offset, length, MIN(Z_STRLEN_P(zv), 10)); memcpy(offset, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 10)); offset += MIN(Z_STRLEN_P(zv), 10); if (Z_STRLEN_P(zv) > 10) { *(offset++) = '.'; *(offset++) = '.'; *(offset++) = '.'; } *(offset++) = '\''; } else if (Z_TYPE_P(zv) == IS_ARRAY) { memcpy(offset, "Array", 5); offset += 5; } else { zend_make_printable_zval(zv, &zv_copy, &use_copy); REALLOC_BUF_IF_EXCEED(buf, offset, length, Z_STRLEN(zv_copy)); memcpy(offset, Z_STRVAL(zv_copy), Z_STRLEN(zv_copy)); offset += Z_STRLEN(zv_copy); if (use_copy) { zval_dtor(&zv_copy); } } zval_ptr_dtor(&zv); } } else { memcpy(offset, "NULL", 4); offset += 4; } } if (++i < fptr->common.num_args) { *(offset++) = ','; *(offset++) = ' '; } arg_info++; REALLOC_BUF_IF_EXCEED(buf, offset, length, 32); } } *(offset++) = ')'; *offset = '\0'; return buf; } /* }}} */ static void do_inheritance_check_on_method(zend_function *child, zend_function *parent TSRMLS_DC) /* {{{ */ { zend_uint child_flags; zend_uint parent_flags = parent->common.fn_flags; if ((parent->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && parent->common.fn_flags & ZEND_ACC_ABSTRACT && parent->common.scope != (child->common.prototype ? child->common.prototype->common.scope : child->common.scope) && child->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_IMPLEMENTED_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Can't inherit abstract function %s::%s() (previously declared abstract in %s)", parent->common.scope->name, child->common.function_name, child->common.prototype ? child->common.prototype->common.scope->name : child->common.scope->name); } if (parent_flags & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot override final method %s::%s()", ZEND_FN_SCOPE_NAME(parent), child->common.function_name); } child_flags = child->common.fn_flags; /* You cannot change from static to non static and vice versa. */ if ((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC)) { if (child->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot make non static method %s::%s() static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } else { zend_error(E_COMPILE_ERROR, "Cannot make static method %s::%s() non static in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } } /* Disallow making an inherited method abstract. */ if ((child_flags & ZEND_ACC_ABSTRACT) && !(parent_flags & ZEND_ACC_ABSTRACT)) { zend_error(E_COMPILE_ERROR, "Cannot make non abstract method %s::%s() abstract in class %s", ZEND_FN_SCOPE_NAME(parent), child->common.function_name, ZEND_FN_SCOPE_NAME(child)); } if (parent_flags & ZEND_ACC_CHANGED) { child->common.fn_flags |= ZEND_ACC_CHANGED; } else { /* Prevent derived classes from restricting access that was available in parent classes */ if ((child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::%s() must be %s (as in class %s)%s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if (((child_flags & ZEND_ACC_PPP_MASK) < (parent_flags & ZEND_ACC_PPP_MASK)) && ((parent_flags & ZEND_ACC_PPP_MASK) & ZEND_ACC_PRIVATE)) { child->common.fn_flags |= ZEND_ACC_CHANGED; } } if (parent_flags & ZEND_ACC_PRIVATE) { child->common.prototype = NULL; } else if (parent_flags & ZEND_ACC_ABSTRACT) { child->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; child->common.prototype = parent; } else if (!(parent->common.fn_flags & ZEND_ACC_CTOR) || (parent->common.prototype && (parent->common.prototype->common.scope->ce_flags & ZEND_ACC_INTERFACE))) { /* ctors only have a prototype if it comes from an interface */ child->common.prototype = parent->common.prototype ? parent->common.prototype : parent; } if (child->common.prototype && (child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { if (!zend_do_perform_implementation_check(child, child->common.prototype TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s::%s() must be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, zend_get_function_declaration(child->common.prototype TSRMLS_CC)); } } else if (EG(error_reporting) & E_STRICT || EG(user_error_handler)) { /* Check E_STRICT (or custom error handler) before the check so that we save some time */ if (!zend_do_perform_implementation_check(child, parent TSRMLS_CC)) { char *method_prototype = zend_get_function_declaration(child->common.prototype TSRMLS_CC); zend_error(E_STRICT, "Declaration of %s::%s() should be compatible with %s", ZEND_FN_SCOPE_NAME(child), child->common.function_name, method_prototype); efree(method_prototype); } } } /* }}} */ static zend_bool do_inherit_method_check(HashTable *child_function_table, zend_function *parent, const zend_hash_key *hash_key, zend_class_entry *child_ce) /* {{{ */ { zend_uint parent_flags = parent->common.fn_flags; zend_function *child; TSRMLS_FETCH(); if (zend_hash_quick_find(child_function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child)==FAILURE) { if (parent_flags & (ZEND_ACC_ABSTRACT)) { child_ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } return 1; /* method doesn't exist in child, copy from parent */ } do_inheritance_check_on_method(child, parent TSRMLS_CC); return 0; } /* }}} */ static zend_bool do_inherit_property_access_check(HashTable *target_ht, zend_property_info *parent_info, const zend_hash_key *hash_key, zend_class_entry *ce) /* {{{ */ { zend_property_info *child_info; zend_class_entry *parent_ce = ce->parent; if (parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW)) { if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { child_info->flags |= ZEND_ACC_CHANGED; } else { zend_hash_quick_update(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, parent_info, sizeof(zend_property_info), (void **) &child_info); if(ce->type & ZEND_INTERNAL_CLASS) { zend_duplicate_property_info_internal(child_info); } else { zend_duplicate_property_info(child_info); } child_info->flags &= ~ZEND_ACC_PRIVATE; /* it's not private anymore */ child_info->flags |= ZEND_ACC_SHADOW; /* but it's a shadow of private */ } return 0; /* don't copy access information to child */ } if (zend_hash_quick_find(&ce->properties_info, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **) &child_info)==SUCCESS) { if ((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s", (parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", parent_ce->name, hash_key->arKey, (child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ce->name, hash_key->arKey); } if(parent_info->flags & ZEND_ACC_CHANGED) { child_info->flags |= ZEND_ACC_CHANGED; } if ((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK)) { zend_error(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ce->name, hash_key->arKey, zend_visibility_string(parent_info->flags), parent_ce->name, (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if ((child_info->flags & ZEND_ACC_STATIC) == 0) { Z_DELREF_P(ce->default_properties_table[parent_info->offset]); ce->default_properties_table[parent_info->offset] = ce->default_properties_table[child_info->offset]; ce->default_properties_table[child_info->offset] = NULL; child_info->offset = parent_info->offset; } return 0; /* Don't copy from parent */ } else { return 1; /* Copy from parent */ } } /* }}} */ static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce TSRMLS_CC) == FAILURE) { zend_error(E_CORE_ERROR, "Class %s could not implement interface %s", ce->name, iface->name); } if (ce == iface) { zend_error(E_ERROR, "Interface %s cannot implement itself", ce->name); } } /* }}} */ ZEND_API void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface TSRMLS_DC) /* {{{ */ { /* expects interface to be contained in ce's interface list already */ zend_uint i, ce_num, if_num = iface->num_interfaces; zend_class_entry *entry; if (if_num==0) { return; } ce_num = ce->num_interfaces; if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } /* Inherit the interfaces, only if they're not already inherited by the class */ while (if_num--) { entry = iface->interfaces[if_num]; for (i = 0; i < ce_num; i++) { if (ce->interfaces[i] == entry) { break; } } if (i == ce_num) { ce->interfaces[ce->num_interfaces++] = entry; } } /* and now call the implementing handlers */ while (ce_num < ce->num_interfaces) { do_implement_interface(ce, ce->interfaces[ce_num++] TSRMLS_CC); } } /* }}} */ #ifdef ZTS static void zval_internal_ctor(zval **p) /* {{{ */ { zval *orig_ptr = *p; ALLOC_ZVAL(*p); MAKE_COPY_ZVAL(&orig_ptr, *p); } /* }}} */ # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) (((parent_ce)->type != (ce)->type) ? zval_internal_ctor : zval_add_ref)) #else # define zval_property_ctor(parent_ce, ce) \ ((void (*)(void *)) zval_add_ref) #endif ZEND_API void zend_do_inheritance(zend_class_entry *ce, zend_class_entry *parent_ce TSRMLS_DC) /* {{{ */ { zend_property_info *property_info; if ((ce->ce_flags & ZEND_ACC_INTERFACE) && !(parent_ce->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ce->name, parent_ce->name); } if (parent_ce->ce_flags & ZEND_ACC_FINAL_CLASS) { zend_error(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ce->name, parent_ce->name); } ce->parent = parent_ce; /* Copy serialize/unserialize callbacks */ if (!ce->serialize) { ce->serialize = parent_ce->serialize; } if (!ce->unserialize) { ce->unserialize = parent_ce->unserialize; } /* Inherit interfaces */ zend_do_inherit_interfaces(ce, parent_ce TSRMLS_CC); /* Inherit properties */ if (parent_ce->default_properties_count) { int i = ce->default_properties_count + parent_ce->default_properties_count; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_properties_count) { while (i-- > parent_ce->default_properties_count) { ce->default_properties_table[i] = ce->default_properties_table[i - parent_ce->default_properties_count]; } } for (i = 0; i < parent_ce->default_properties_count; i++) { ce->default_properties_table[i] = parent_ce->default_properties_table[i]; if (ce->default_properties_table[i]) { #ifdef ZTS if (parent_ce->type != ce->type) { zval *p; ALLOC_ZVAL(p); MAKE_COPY_ZVAL(&ce->default_properties_table[i], p); ce->default_properties_table[i] = p; } else { Z_ADDREF_P(ce->default_properties_table[i]); } #else Z_ADDREF_P(ce->default_properties_table[i]); #endif } } ce->default_properties_count += parent_ce->default_properties_count; } if (parent_ce->type != ce->type) { /* User class extends internal class */ zend_update_class_constants(parent_ce TSRMLS_CC); if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = erealloc(ce->default_static_members_table, sizeof(void*) * i); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&CE_STATIC_MEMBERS(parent_ce)[i]); ce->default_static_members_table[i] = CE_STATIC_MEMBERS(parent_ce)[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; ce->static_members_table = ce->default_static_members_table; } } else { if (parent_ce->default_static_members_count) { int i = ce->default_static_members_count + parent_ce->default_static_members_count; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(void*) * i, ce->type == ZEND_INTERNAL_CLASS); if (ce->default_static_members_count) { while (i-- > parent_ce->default_static_members_count) { ce->default_static_members_table[i] = ce->default_static_members_table[i - parent_ce->default_static_members_count]; } } for (i = 0; i < parent_ce->default_static_members_count; i++) { SEPARATE_ZVAL_TO_MAKE_IS_REF(&parent_ce->default_static_members_table[i]); ce->default_static_members_table[i] = parent_ce->default_static_members_table[i]; Z_ADDREF_P(ce->default_static_members_table[i]); } ce->default_static_members_count += parent_ce->default_static_members_count; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } } } for (zend_hash_internal_pointer_reset(&ce->properties_info); zend_hash_get_current_data(&ce->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->properties_info)) { if (property_info->ce == ce) { if (property_info->flags & ZEND_ACC_STATIC) { property_info->offset += parent_ce->default_static_members_count; } else { property_info->offset += parent_ce->default_properties_count; } } } zend_hash_merge_ex(&ce->properties_info, &parent_ce->properties_info, (copy_ctor_func_t) (ce->type & ZEND_INTERNAL_CLASS ? zend_duplicate_property_info_internal : zend_duplicate_property_info), sizeof(zend_property_info), (merge_checker_func_t) do_inherit_property_access_check, ce); zend_hash_merge(&ce->constants_table, &parent_ce->constants_table, zval_property_ctor(parent_ce, ce), NULL, sizeof(zval *), 0); zend_hash_merge_ex(&ce->function_table, &parent_ce->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_inherit_parent_constructor(ce); if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS && ce->type == ZEND_INTERNAL_CLASS) { ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } else if (!(ce->ce_flags & ZEND_ACC_IMPLEMENT_INTERFACES) && !(ce->ce_flags & ZEND_ACC_IMPLEMENT_TRAITS)) { /* The verification will be done in runtime by ZEND_VERIFY_ABSTRACT_CLASS */ zend_verify_abstract_class(ce TSRMLS_CC); } ce->ce_flags |= parent_ce->ce_flags & ZEND_HAS_STATIC_IN_METHODS; } /* }}} */ static zend_bool do_inherit_constant_check(HashTable *child_constants_table, const zval **parent_constant, const zend_hash_key *hash_key, const zend_class_entry *iface) /* {{{ */ { zval **old_constant; if (zend_hash_quick_find(child_constants_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**)&old_constant) == SUCCESS) { if (*old_constant != *parent_constant) { zend_error(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", hash_key->arKey, iface->name); } return 0; } return 1; } /* }}} */ static int do_interface_constant_check(zval **val TSRMLS_DC, int num_args, va_list args, const zend_hash_key *key) /* {{{ */ { zend_class_entry **iface = va_arg(args, zend_class_entry**); do_inherit_constant_check(&(*iface)->constants_table, (const zval **) val, key, *iface); return ZEND_HASH_APPLY_KEEP; } /* }}} */ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_iface_num = ce->num_interfaces; zend_uint parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0; for (i = 0; i < ce->num_interfaces; i++) { if (ce->interfaces[i] == NULL) { memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i)); i--; } else if (ce->interfaces[i] == iface) { if (i < parent_iface_num) { ignore = 1; } else { zend_error(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ce->name, iface->name); } } } if (ignore) { /* Check for attempt to redeclare interface constants */ zend_hash_apply_with_arguments(&ce->constants_table TSRMLS_CC, (apply_func_args_t) do_interface_constant_check, 1, &iface); } else { if (ce->num_interfaces >= current_iface_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } } ce->interfaces[ce->num_interfaces++] = iface; zend_hash_merge_ex(&ce->constants_table, &iface->constants_table, (copy_ctor_func_t) zval_add_ref, sizeof(zval *), (merge_checker_func_t) do_inherit_constant_check, iface); zend_hash_merge_ex(&ce->function_table, &iface->function_table, (copy_ctor_func_t) do_inherit_method, sizeof(zend_function), (merge_checker_func_t) do_inherit_method_check, ce); do_implement_interface(ce, iface TSRMLS_CC); zend_do_inherit_interfaces(ce, iface TSRMLS_CC); } } /* }}} */ ZEND_API void zend_do_implement_trait(zend_class_entry *ce, zend_class_entry *trait TSRMLS_DC) /* {{{ */ { zend_uint i, ignore = 0; zend_uint current_trait_num = ce->num_traits; zend_uint parent_trait_num = ce->parent ? ce->parent->num_traits : 0; for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == NULL) { memmove(ce->traits + i, ce->traits + i + 1, sizeof(zend_class_entry*) * (--ce->num_traits - i)); i--; } else if (ce->traits[i] == trait) { if (i < parent_trait_num) { ignore = 1; } } } if (!ignore) { if (ce->num_traits >= current_trait_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->traits = (zend_class_entry **) realloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } else { ce->traits = (zend_class_entry **) erealloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } } ce->traits[ce->num_traits++] = trait; } } /* }}} */ static int zend_traits_merge_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { size_t current; size_t i; size_t count; HashTable* resulting_table; HashTable** function_tables; zend_class_entry *ce; size_t collision = 0; size_t abstract_solved = 0; zend_function* other_trait_fn; current = va_arg(args, size_t); /* index of current trait */ count = va_arg(args, size_t); resulting_table = va_arg(args, HashTable*); function_tables = va_arg(args, HashTable**); ce = va_arg(args, zend_class_entry*); for (i = 0; i < count; i++) { if (i == current) { continue; /* just skip this, cause its the table this function is applied on */ } if (zend_hash_quick_find(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&other_trait_fn) == SUCCESS) { /* if it is an abstract method, there is no collision */ if (other_trait_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* In case both are abstract, just check prototype, but need to do that in both directions */ if ( !zend_do_perform_implementation_check(fn, other_trait_fn TSRMLS_CC) || !zend_do_perform_implementation_check(other_trait_fn, fn TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Declaration of %s must be compatible with %s", //ZEND_FN_SCOPE_NAME(fn), fn->common.function_name, //::%s() zend_get_function_declaration(fn TSRMLS_CC), zend_get_function_declaration(other_trait_fn TSRMLS_CC)); } } else { /* otherwise, do the full check */ do_inheritance_check_on_method(fn, other_trait_fn TSRMLS_CC); } /* we can savely free and remove it from other table */ zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } else { /* if it is not an abstract method, there is still no collision */ /* if fn is an abstract method */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure they are compatible. Here, we already know other_trait_fn cannot be abstract, full check ok. */ do_inheritance_check_on_method(other_trait_fn, fn TSRMLS_CC); /* just mark as solved, will be added if its own trait is processed */ abstract_solved = 1; } else { /* but else, we have a collision of non-abstract methods */ collision++; zend_function_dtor(other_trait_fn); zend_hash_quick_del(function_tables[i], hash_key->arKey, hash_key->nKeyLength, hash_key->h); } } } } if (collision) { zend_function* class_fn; /* make sure method is not already overridden in class */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void **)&class_fn) == FAILURE || class_fn->common.scope != ce) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because there are collisions with other trait methods on %s", fn->common.function_name, ce->name); } zend_function_dtor(fn); } else if (abstract_solved) { zend_function_dtor(fn); } else { /* Add it to result function table */ if (zend_hash_quick_add(resulting_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, fn, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating resulting trait method table", fn->common.function_name); } } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ /* {{{ Originates from php_runkit_function_copy_ctor Duplicate structures in an op_array where necessary to make an outright duplicate */ static void zend_traits_duplicate_function(zend_function *fe, zend_class_entry *target_ce, char *newname TSRMLS_DC) { zend_literal *literals_copy; zend_compiled_variable *dupvars; zend_op *opcode_copy; zval class_name_zv; int class_name_literal; int i; int number_of_literals; if (fe->op_array.static_variables) { HashTable *tmpHash; ALLOC_HASHTABLE(tmpHash); zend_hash_init(tmpHash, zend_hash_num_elements(fe->op_array.static_variables), NULL, ZVAL_PTR_DTOR, 0); zend_hash_apply_with_arguments(fe->op_array.static_variables TSRMLS_CC, (apply_func_args_t)zval_copy_static_var, 1, tmpHash); fe->op_array.static_variables = tmpHash; } number_of_literals = fe->op_array.last_literal; literals_copy = (zend_literal*)emalloc(number_of_literals * sizeof(zend_literal)); for (i = 0; i < number_of_literals; i++) { literals_copy[i] = fe->op_array.literals[i]; zval_copy_ctor(&literals_copy[i].constant); } fe->op_array.literals = literals_copy; fe->op_array.refcount = emalloc(sizeof(zend_uint)); *(fe->op_array.refcount) = 1; if (fe->op_array.vars) { i = fe->op_array.last_var; dupvars = safe_emalloc(fe->op_array.last_var, sizeof(zend_compiled_variable), 0); while (i > 0) { i--; dupvars[i].name = estrndup(fe->op_array.vars[i].name, fe->op_array.vars[i].name_len); dupvars[i].name_len = fe->op_array.vars[i].name_len; dupvars[i].hash_value = fe->op_array.vars[i].hash_value; } fe->op_array.vars = dupvars; } else { fe->op_array.vars = NULL; } opcode_copy = safe_emalloc(sizeof(zend_op), fe->op_array.last, 0); for(i = 0; i < fe->op_array.last; i++) { opcode_copy[i] = fe->op_array.opcodes[i]; if (opcode_copy[i].op1_type != IS_CONST) { switch (opcode_copy[i].opcode) { case ZEND_GOTO: case ZEND_JMP: if (opcode_copy[i].op1.jmp_addr && opcode_copy[i].op1.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op1.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op1.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op1.jmp_addr - fe->op_array.opcodes); } break; } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op1.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op1.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op1.zv = &fe->op_array.literals[class_name_literal].constant; } } if (opcode_copy[i].op2_type != IS_CONST) { switch (opcode_copy[i].opcode) { case ZEND_JMPZ: case ZEND_JMPNZ: case ZEND_JMPZ_EX: case ZEND_JMPNZ_EX: case ZEND_JMP_SET: case ZEND_JMP_SET_VAR: if (opcode_copy[i].op2.jmp_addr && opcode_copy[i].op2.jmp_addr >= fe->op_array.opcodes && opcode_copy[i].op2.jmp_addr < fe->op_array.opcodes + fe->op_array.last) { opcode_copy[i].op2.jmp_addr = opcode_copy + (fe->op_array.opcodes[i].op2.jmp_addr - fe->op_array.opcodes); } break; } } else { /* if __CLASS__ i.e. T_CLASS_C was used, we need to fix it up here */ if (target_ce /* REM: used a IS_NULL place holder with a special marker LVAL */ && Z_TYPE_P(opcode_copy[i].op2.zv) == IS_NULL && Z_LVAL_P(opcode_copy[i].op2.zv) == ZEND_ACC_TRAIT /* Only on merge into an actual class */ && (ZEND_ACC_TRAIT != (target_ce->ce_flags & ZEND_ACC_TRAIT))) { INIT_ZVAL(class_name_zv); ZVAL_STRINGL(&class_name_zv, target_ce->name, target_ce->name_length, 1); class_name_literal = zend_append_individual_literal(&fe->op_array, &class_name_zv TSRMLS_CC); opcode_copy[i].op2.zv = &fe->op_array.literals[class_name_literal].constant; } } } fe->op_array.opcodes = opcode_copy; fe->op_array.function_name = newname; /* was setting it to fe which does not work since fe is stack allocated and not a stable address */ /* fe->op_array.prototype = fe->op_array.prototype; */ if (fe->op_array.arg_info) { zend_arg_info *tmpArginfo; tmpArginfo = safe_emalloc(sizeof(zend_arg_info), fe->op_array.num_args, 0); for(i = 0; i < fe->op_array.num_args; i++) { tmpArginfo[i] = fe->op_array.arg_info[i]; tmpArginfo[i].name = estrndup(tmpArginfo[i].name, tmpArginfo[i].name_len); if (tmpArginfo[i].class_name) { tmpArginfo[i].class_name = estrndup(tmpArginfo[i].class_name, tmpArginfo[i].class_name_len); } } fe->op_array.arg_info = tmpArginfo; } fe->op_array.doc_comment = estrndup(fe->op_array.doc_comment, fe->op_array.doc_comment_len); fe->op_array.try_catch_array = (zend_try_catch_element*)estrndup((char*)fe->op_array.try_catch_array, sizeof(zend_try_catch_element) * fe->op_array.last_try_catch); fe->op_array.brk_cont_array = (zend_brk_cont_element*)estrndup((char*)fe->op_array.brk_cont_array, sizeof(zend_brk_cont_element) * fe->op_array.last_brk_cont); } /* }}} */ static void zend_add_magic_methods(zend_class_entry* ce, const char* mname, uint mname_len, zend_function* fe TSRMLS_DC) /* {{{ */ { if (!strncmp(mname, ZEND_CLONE_FUNC_NAME, mname_len)) { ce->clone = fe; fe->common.fn_flags |= ZEND_ACC_CLONE; } else if (!strncmp(mname, ZEND_CONSTRUCTOR_FUNC_NAME, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } else if (!strncmp(mname, ZEND_DESTRUCTOR_FUNC_NAME, mname_len)) { ce->destructor = fe; fe->common.fn_flags |= ZEND_ACC_DTOR; } else if (!strncmp(mname, ZEND_GET_FUNC_NAME, mname_len)) { ce->__get = fe; } else if (!strncmp(mname, ZEND_SET_FUNC_NAME, mname_len)) { ce->__set = fe; } else if (!strncmp(mname, ZEND_CALL_FUNC_NAME, mname_len)) { ce->__call = fe; } else if (!strncmp(mname, ZEND_UNSET_FUNC_NAME, mname_len)) { ce->__unset = fe; } else if (!strncmp(mname, ZEND_ISSET_FUNC_NAME, mname_len)) { ce->__isset = fe; } else if (!strncmp(mname, ZEND_CALLSTATIC_FUNC_NAME, mname_len)) { ce->__callstatic = fe; } else if (!strncmp(mname, ZEND_TOSTRING_FUNC_NAME, mname_len)) { ce->__tostring = fe; } else if (ce->name_length + 1 == mname_len) { char *lowercase_name = emalloc(ce->name_length + 1); zend_str_tolower_copy(lowercase_name, ce->name, ce->name_length); lowercase_name = (char*)zend_new_interned_string(lowercase_name, ce->name_length + 1, 1 TSRMLS_CC); if (!memcmp(mname, lowercase_name, mname_len)) { if (ce->constructor) { zend_error(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ce->name); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } str_efree(lowercase_name); } } /* }}} */ static int zend_traits_merge_functions_to_class(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { zend_class_entry *ce = va_arg(args, zend_class_entry*); int add = 0; zend_function* existing_fn = NULL; zend_function fn_copy, *fn_copy_p; zend_function* prototype = NULL; /* is used to determine the prototype according to the inheritance chain */ if (zend_hash_quick_find(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &existing_fn) == FAILURE) { add = 1; /* not found */ } else if (existing_fn->common.scope != ce) { add = 1; /* or inherited from other class or interface */ } if (add) { zend_function* parent_function; if (ce->parent && zend_hash_quick_find(&ce->parent->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, (void**) &parent_function) != FAILURE) { prototype = parent_function; /* ->common.fn_flags |= ZEND_ACC_ABSTRACT; */ /* we got that method in the parent class, and are going to override it, except, if the trait is just asking to have an abstract method implemented. */ if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* then we clean up an skip this method */ zend_function_dtor(fn); return ZEND_HASH_APPLY_REMOVE; } } fn->common.scope = ce; fn->common.prototype = prototype; if (prototype && (prototype->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT || prototype->common.fn_flags & ZEND_ACC_ABSTRACT)) { fn->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; } else if (fn->common.fn_flags & ZEND_ACC_IMPLEMENTED_ABSTRACT) { /* remove ZEND_ACC_IMPLEMENTED_ABSTRACT flag, think it shouldn't be copied to class */ fn->common.fn_flags = fn->common.fn_flags - ZEND_ACC_IMPLEMENTED_ABSTRACT; } /* check whether the trait method fullfills the inheritance requirements */ if (prototype) { do_inheritance_check_on_method(fn, prototype TSRMLS_CC); } /* one more thing: make sure we properly implement an abstract method */ if (existing_fn && existing_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { do_inheritance_check_on_method(fn, existing_fn TSRMLS_CC); } /* delete inherited fn if the function to be added is not abstract */ if (existing_fn && existing_fn->common.scope != ce && (fn->common.fn_flags & ZEND_ACC_ABSTRACT) == 0) { /* it is just a reference which was added to the subclass while doing the inheritance, so we can deleted now, and will add the overriding method afterwards. Except, if we try to add an abstract function, then we should not delete the inherited one */ zend_hash_quick_del(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h); } if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (fn->op_array.static_variables) { ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, ce, estrdup(fn->common.function_name) TSRMLS_CC); if (zend_hash_quick_update(&ce->function_table, hash_key->arKey, hash_key->nKeyLength, hash_key->h, &fn_copy, sizeof(zend_function), (void**)&fn_copy_p)==FAILURE) { zend_error(E_COMPILE_ERROR, "Trait method %s has not been applied, because failure occured during updating class method table", hash_key->arKey); } zend_add_magic_methods(ce, hash_key->arKey, hash_key->nKeyLength, fn_copy_p TSRMLS_CC); zend_function_dtor(fn); } else { zend_function_dtor(fn); } return ZEND_HASH_APPLY_REMOVE; } /* }}} */ static int zend_traits_copy_functions(zend_function *fn TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { HashTable* target; zend_class_entry *target_ce; zend_trait_alias** aliases; HashTable* exclude_table; char* lcname; unsigned int fnname_len; zend_function fn_copy; void* dummy; size_t i = 0; target = va_arg(args, HashTable*); target_ce = va_arg(args, zend_class_entry*); aliases = va_arg(args, zend_trait_alias**); exclude_table = va_arg(args, HashTable*); fnname_len = strlen(fn->common.function_name); /* apply aliases which are qualified with a class name, there should not be any ambiguity */ if (aliases) { while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias != NULL && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && aliases[i]->trait_method->mname_len == fnname_len && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(aliases[i]->alias, aliases[i]->alias_len) TSRMLS_CC); /* if it is 0, no modifieres has been changed */ if (aliases[i]->modifiers) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); } lcname = zend_str_tolower_dup(aliases[i]->alias, aliases[i]->alias_len); if (zend_hash_add(target, lcname, aliases[i]->alias_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add aliased trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } efree(lcname); /** Record the trait from which this alias was resolved. */ if (!aliases[i]->trait_method->ce) { aliases[i]->trait_method->ce = fn->common.scope; } } i++; } } lcname = zend_str_tolower_dup(fn->common.function_name, fnname_len); if (exclude_table == NULL || zend_hash_find(exclude_table, lcname, fnname_len, &dummy) == FAILURE) { /* is not in hashtable, thus, function is not to be excluded */ fn_copy = *fn; zend_traits_duplicate_function(&fn_copy, NULL, estrndup(fn->common.function_name, fnname_len) TSRMLS_CC); /* apply aliases which are not qualified by a class name, or which have not * alias name, just setting visibility */ if (aliases) { i = 0; while (aliases[i]) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (aliases[i]->alias == NULL && aliases[i]->modifiers != 0 && (!aliases[i]->trait_method->ce || fn->common.scope == aliases[i]->trait_method->ce) && (aliases[i]->trait_method->mname_len == fnname_len) && (zend_binary_strcasecmp(aliases[i]->trait_method->method_name, aliases[i]->trait_method->mname_len, fn->common.function_name, fnname_len) == 0)) { fn_copy.common.fn_flags = aliases[i]->modifiers; if (!(aliases[i]->modifiers & ZEND_ACC_PPP_MASK)) { fn_copy.common.fn_flags |= ZEND_ACC_PUBLIC; } fn_copy.common.fn_flags |= fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK); /** Record the trait from which this alias was resolved. */ if (!aliases[i]->trait_method->ce) { aliases[i]->trait_method->ce = fn->common.scope; } } i++; } } if (zend_hash_add(target, lcname, fnname_len+1, &fn_copy, sizeof(zend_function), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Failed to add trait method (%s) to the trait table. There is probably already a trait method with the same name", fn_copy.common.function_name); } } efree(lcname); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* Copies function table entries to target function table with applied aliasing */ static void zend_traits_copy_trait_function_table(HashTable *target, zend_class_entry *target_ce, HashTable *source, zend_trait_alias** aliases, HashTable* exclude_table TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_arguments(source TSRMLS_CC, (apply_func_args_t)zend_traits_copy_functions, 4, target, target_ce, aliases, exclude_table); } /* }}} */ static void zend_traits_init_trait_structures(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i, j = 0; zend_trait_precedence *cur_precedence; zend_trait_method_reference *cur_method_ref; char *lcname; zend_bool method_exists; /* resolve class references */ if (ce->trait_precedences) { i = 0; while ((cur_precedence = ce->trait_precedences[i])) { /** Resolve classes for all precedence operations. */ if (cur_precedence->exclude_from_classes) { cur_method_ref = cur_precedence->trait_method; cur_precedence->trait_method->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); /** Ensure that the prefered method is actually available. */ lcname = zend_str_tolower_dup(cur_method_ref->method_name, cur_method_ref->mname_len); method_exists = zend_hash_exists(&cur_method_ref->ce->function_table, lcname, cur_method_ref->mname_len + 1); efree(lcname); if (!method_exists) { zend_error(E_COMPILE_ERROR, "A precedence rule was defined for %s::%s but this method does not exist", cur_method_ref->ce->name, cur_method_ref->method_name); } /** With the other traits, we are more permissive. We do not give errors for those. This allows to be more defensive in such definitions. */ j = 0; while (cur_precedence->exclude_from_classes[j]) { char* class_name = (char*)cur_precedence->exclude_from_classes[j]; zend_uint name_length = strlen(class_name); cur_precedence->exclude_from_classes[j] = zend_fetch_class(class_name, name_length, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); efree(class_name); j++; } } i++; } } if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { /** For all aliases with an explicit class name, resolve the class now. */ if (ce->trait_aliases[i]->trait_method->class_name) { cur_method_ref = ce->trait_aliases[i]->trait_method; cur_method_ref->ce = zend_fetch_class(cur_method_ref->class_name, cur_method_ref->cname_len, ZEND_FETCH_CLASS_TRAIT TSRMLS_CC); /** And, ensure that the referenced method is resolvable, too. */ lcname = zend_str_tolower_dup(cur_method_ref->method_name, cur_method_ref->mname_len); method_exists = zend_hash_exists(&cur_method_ref->ce->function_table, lcname, cur_method_ref->mname_len + 1); efree(lcname); if (!method_exists) { zend_error(E_COMPILE_ERROR, "An alias was defined for %s::%s but this method does not exist", cur_method_ref->ce->name, cur_method_ref->method_name); } } i++; } } } /* }}} */ static void zend_traits_compile_exclude_table(HashTable* exclude_table, zend_trait_precedence **precedences, zend_class_entry *trait) /* {{{ */ { size_t i = 0, j; if (!precedences) { return; } while (precedences[i]) { if (precedences[i]->exclude_from_classes) { j = 0; while (precedences[i]->exclude_from_classes[j]) { if (precedences[i]->exclude_from_classes[j] == trait) { zend_uint lcname_len = precedences[i]->trait_method->mname_len; char *lcname = zend_str_tolower_dup(precedences[i]->trait_method->method_name, lcname_len); if (zend_hash_add(exclude_table, lcname, lcname_len, NULL, 0, NULL) == FAILURE) { efree(lcname); zend_error(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", precedences[i]->trait_method->method_name, trait->name); } efree(lcname); } ++j; } } ++i; } } /* }}} */ static void zend_do_traits_method_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { HashTable** function_tables; HashTable* resulting_table; HashTable exclude_table; size_t i; /* prepare copies of trait function tables for combination */ function_tables = malloc(sizeof(HashTable*) * ce->num_traits); resulting_table = (HashTable *) malloc(sizeof(HashTable)); /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(resulting_table, 10, NULL, NULL, 1, 0); for (i = 0; i < ce->num_traits; i++) { function_tables[i] = (HashTable *) malloc(sizeof(HashTable)); zend_hash_init_ex(function_tables[i], ce->traits[i]->function_table.nNumOfElements, NULL, NULL, 1, 0); if (ce->trait_precedences) { /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(&exclude_table, 2, NULL, NULL, 0, 0); zend_traits_compile_exclude_table(&exclude_table, ce->trait_precedences, ce->traits[i]); /* copies functions, applies defined aliasing, and excludes unused trait methods */ zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, &exclude_table TSRMLS_CC); zend_hash_graceful_destroy(&exclude_table); } else { zend_traits_copy_trait_function_table(function_tables[i], ce, &ce->traits[i]->function_table, ce->trait_aliases, NULL TSRMLS_CC); } } /* now merge trait methods */ for (i = 0; i < ce->num_traits; i++) { zend_hash_apply_with_arguments(function_tables[i] TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions, 5, i, ce->num_traits, resulting_table, function_tables, ce); } /* Now the resulting_table contains all trait methods we would have to * add to the class in the following step the methods are inserted into the method table * if there is already a method with the same name it is replaced iff ce != fn.scope * --> all inherited methods are overridden, methods defined in the class are left untouched */ zend_hash_apply_with_arguments(resulting_table TSRMLS_CC, (apply_func_args_t)zend_traits_merge_functions_to_class, 1, ce); /* free temporary function tables */ for (i = 0; i < ce->num_traits; i++) { /* zend_hash_destroy(function_tables[i]); */ zend_hash_graceful_destroy(function_tables[i]); free(function_tables[i]); } free(function_tables); /* free temporary resulting table */ /* zend_hash_destroy(resulting_table); */ zend_hash_graceful_destroy(resulting_table); free(resulting_table); } /* }}} */ static zend_class_entry* find_first_definition(zend_class_entry *ce, size_t current_trait, const char* prop_name, int prop_name_length, ulong prop_hash, zend_class_entry *coliding_ce) /* {{{ */ { size_t i; zend_property_info *coliding_prop; for (i = 0; (i < current_trait) && (i < ce->num_traits); i++) { if (zend_hash_quick_find(&ce->traits[i]->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS) { return ce->traits[i]; } } return coliding_ce; } /* }}} */ static void zend_do_traits_property_binding(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { size_t i; zend_property_info *property_info; zend_property_info *coliding_prop; zval compare_result; const char* prop_name; int prop_name_length; ulong prop_hash; const char* class_name_unused; zend_bool prop_found; zend_bool parent_prop_is_private = 0; zend_bool not_compatible; zval* prop_value; /* In the following steps the properties are inserted into the property table * for that, a very strict approach is applied: * - check for compatibility, if not compatible with any property in class -> fatal * - if compatible, then strict notice */ for (i = 0; i < ce->num_traits; i++) { for (zend_hash_internal_pointer_reset(&ce->traits[i]->properties_info); zend_hash_get_current_data(&ce->traits[i]->properties_info, (void *) &property_info) == SUCCESS; zend_hash_move_forward(&ce->traits[i]->properties_info)) { /* first get the unmangeld name if necessary, * then check whether the property is already there */ if ((property_info->flags & ZEND_ACC_PPP_MASK) == ZEND_ACC_PUBLIC) { prop_hash = property_info->h; prop_name = property_info->name; prop_name_length = property_info->name_length; prop_found = zend_hash_quick_find(&ce->properties_info, property_info->name, property_info->name_length+1, property_info->h, (void **) &coliding_prop) == SUCCESS; } else { /* for private and protected we need to unmangle the names */ zend_unmangle_property_name(property_info->name, property_info->name_length, &class_name_unused, &prop_name); prop_name_length = strlen(prop_name); prop_hash = zend_get_hash_value(prop_name, prop_name_length + 1); prop_found = zend_hash_quick_find(&ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop) == SUCCESS; } /* next: check for conflicts with current class */ if (prop_found) { if (coliding_prop->flags & ZEND_ACC_SHADOW) { /* this one is inherited, lets look it up in its own class */ zend_hash_quick_find(&coliding_prop->ce->properties_info, prop_name, prop_name_length+1, prop_hash, (void **) &coliding_prop); parent_prop_is_private = (coliding_prop->flags & ZEND_ACC_PRIVATE) == ZEND_ACC_PRIVATE; } if (!parent_prop_is_private) { if ( (coliding_prop->flags & (ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC)) == (property_info->flags & (ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC))) { /* flags are identical, now the value needs to be checked */ if (property_info->flags & ZEND_ACC_STATIC) { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_static_members_table[coliding_prop->offset], ce->traits[i]->default_static_members_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } else { not_compatible = (FAILURE == compare_function(&compare_result, ce->default_properties_table[coliding_prop->offset], ce->traits[i]->default_properties_table[property_info->offset] TSRMLS_CC)) || (Z_LVAL(compare_result) != 0); } } else { /* the flags are not identical, thus, we assume properties are not compatible */ not_compatible = 1; } if (not_compatible) { zend_error(E_COMPILE_ERROR, "%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } else { zend_error(E_STRICT, "%s and %s define the same property ($%s) in the composition of %s. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed", find_first_definition(ce, i, prop_name, prop_name_length, prop_hash, coliding_prop->ce)->name, property_info->ce->name, prop_name, ce->name); } } } /* property not found, so lets add it */ if (property_info->flags & ZEND_ACC_STATIC) { prop_value = ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = ce->traits[i]->default_properties_table[property_info->offset]; } Z_ADDREF_P(prop_value); zend_declare_property_ex(ce, prop_name, prop_name_length, prop_value, property_info->flags, property_info->doc_comment, property_info->doc_comment_len TSRMLS_CC); } } } /* }}} */ static void zend_do_check_for_inconsistent_traits_aliasing(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { int i = 0; zend_trait_alias* cur_alias; char* lc_method_name; if (ce->trait_aliases) { while (ce->trait_aliases[i]) { cur_alias = ce->trait_aliases[i]; /** The trait for this alias has not been resolved, this means, this alias was not applied. Abort with an error. */ if (!cur_alias->trait_method->ce) { if (cur_alias->alias) { /** Plain old inconsistency/typo/bug */ zend_error(E_COMPILE_ERROR, "An alias (%s) was defined for method %s(), but this method does not exist", cur_alias->alias, cur_alias->trait_method->method_name); } else { /** Here are two possible cases: 1) this is an attempt to modifiy the visibility of a method introduce as part of another alias. Since that seems to violate the DRY principle, we check against it and abort. 2) it is just a plain old inconsitency/typo/bug as in the case where alias is set. */ lc_method_name = zend_str_tolower_dup(cur_alias->trait_method->method_name, cur_alias->trait_method->mname_len); if (zend_hash_exists(&ce->function_table, lc_method_name, cur_alias->trait_method->mname_len+1)) { efree(lc_method_name); zend_error(E_COMPILE_ERROR, "The modifiers for the trait alias %s() need to be changed in the same statment in which the alias is defined. Error", cur_alias->trait_method->method_name); } else { efree(lc_method_name); zend_error(E_COMPILE_ERROR, "The modifiers of the trait method %s() are changed, but this method does not exist. Error", cur_alias->trait_method->method_name); } } } i++; } } } /* }}} */ ZEND_API void zend_do_bind_traits(zend_class_entry *ce TSRMLS_DC) /* {{{ */ { if (ce->num_traits <= 0) { return; } /* complete initialization of trait strutures in ce */ zend_traits_init_trait_structures(ce TSRMLS_CC); /* first care about all methods to be flattened into the class */ zend_do_traits_method_binding(ce TSRMLS_CC); /* Aliases which have not been applied indicate typos/bugs. */ zend_do_check_for_inconsistent_traits_aliasing(ce TSRMLS_CC); /* then flatten the properties into it, to, mostly to notfiy developer about problems */ zend_do_traits_property_binding(ce TSRMLS_CC); /* verify that all abstract methods from traits have been implemented */ zend_verify_abstract_class(ce TSRMLS_CC); /* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */ if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { ce->ce_flags -= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } } /* }}} */ ZEND_API int do_bind_function(const zend_op_array *op_array, zend_op *opline, HashTable *function_table, zend_bool compile_time) /* {{{ */ { zend_function *function; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } zend_hash_quick_find(function_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void *) &function); if (zend_hash_quick_add(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), function, sizeof(zend_function), NULL)==FAILURE) { int error_level = compile_time ? E_COMPILE_ERROR : E_ERROR; zend_function *old_function; if (zend_hash_quick_find(function_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), (void *) &old_function)==SUCCESS && old_function->type == ZEND_USER_FUNCTION && old_function->op_array.last > 0) { zend_error(error_level, "Cannot redeclare %s() (previously declared in %s:%d)", function->common.function_name, old_function->op_array.filename, old_function->op_array.opcodes[0].lineno); } else { zend_error(error_level, "Cannot redeclare %s()", function->common.function_name); } return FAILURE; } else { (*function->op_array.refcount)++; function->op_array.static_variables = NULL; /* NULL out the unbound function */ return SUCCESS; } } /* }}} */ void zend_add_trait_precedence(znode *precedence_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_precedences, precedence_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_add_trait_alias(znode *alias_znode TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); zend_add_to_list(&ce->trait_aliases, alias_znode->u.op.ptr TSRMLS_CC); } /* }}} */ void zend_prepare_reference(znode *result, znode *class_name, znode *method_name TSRMLS_DC) /* {{{ */ { zend_trait_method_reference *method_ref = emalloc(sizeof(zend_trait_method_reference)); method_ref->ce = NULL; /* REM: There should not be a need for copying, zend_do_begin_class_declaration is also just using that string */ if (class_name) { zend_resolve_class_name(class_name, ZEND_FETCH_CLASS_GLOBAL, 1 TSRMLS_CC); method_ref->class_name = Z_STRVAL(class_name->u.constant); method_ref->cname_len = Z_STRLEN(class_name->u.constant); } else { method_ref->class_name = NULL; method_ref->cname_len = 0; } method_ref->method_name = Z_STRVAL(method_name->u.constant); method_ref->mname_len = Z_STRLEN(method_name->u.constant); result->u.op.ptr = method_ref; result->op_type = IS_TMP_VAR; } /* }}} */ void zend_prepare_trait_alias(znode *result, znode *method_reference, znode *modifiers, znode *alias TSRMLS_DC) /* {{{ */ { zend_trait_alias *trait_alias = emalloc(sizeof(zend_trait_alias)); trait_alias->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_alias->modifiers = Z_LVAL(modifiers->u.constant); if (Z_LVAL(modifiers->u.constant) == ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Cannot use 'static' as method modifier"); return; } if (alias) { trait_alias->alias = Z_STRVAL(alias->u.constant); trait_alias->alias_len = Z_STRLEN(alias->u.constant); } else { trait_alias->alias = NULL; } trait_alias->function = NULL; result->u.op.ptr = trait_alias; } /* }}} */ void zend_prepare_trait_precedence(znode *result, znode *method_reference, znode *trait_list TSRMLS_DC) /* {{{ */ { zend_trait_precedence *trait_precedence = emalloc(sizeof(zend_trait_precedence)); trait_precedence->trait_method = (zend_trait_method_reference*)method_reference->u.op.ptr; trait_precedence->exclude_from_classes = (zend_class_entry**) trait_list->u.op.ptr; trait_precedence->function = NULL; result->u.op.ptr = trait_precedence; } /* }}} */ ZEND_API zend_class_entry *do_bind_class(const zend_op_array* op_array, const zend_op *opline, HashTable *class_table, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } if (zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce)==FAILURE) { zend_error(E_COMPILE_ERROR, "Internal Zend error - Missing class information for %s", Z_STRVAL_P(op1)); return NULL; } else { ce = *pce; } ce->refcount++; if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), &ce, sizeof(zend_class_entry *), NULL)==FAILURE) { ce->refcount--; if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return NULL; } else { if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_IMPLEMENT_INTERFACES))) { zend_verify_abstract_class(ce TSRMLS_CC); } return ce; } } /* }}} */ ZEND_API zend_class_entry *do_bind_inherited_class(const zend_op_array *op_array, const zend_op *opline, HashTable *class_table, zend_class_entry *parent_ce, zend_bool compile_time TSRMLS_DC) /* {{{ */ { zend_class_entry *ce, **pce; int found_ce; zval *op1, *op2; if (compile_time) { op1 = &CONSTANT_EX(op_array, opline->op1.constant); op2 = &CONSTANT_EX(op_array, opline->op2.constant); } else { op1 = opline->op1.zv; op2 = opline->op2.zv; } found_ce = zend_hash_quick_find(class_table, Z_STRVAL_P(op1), Z_STRLEN_P(op1), Z_HASH_P(op1), (void **) &pce); if (found_ce == FAILURE) { if (!compile_time) { /* If we're in compile time, in practice, it's quite possible * that we'll never reach this class declaration at runtime, * so we shut up about it. This allows the if (!defined('FOO')) { return; } * approach to work. */ zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", Z_STRVAL_P(op2)); } return NULL; } else { ce = *pce; } if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ce->name, parent_ce->name); } else if ((parent_ce->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ce->name, parent_ce->name); } zend_do_inheritance(ce, parent_ce TSRMLS_CC); ce->refcount++; /* Register the derived class */ if (zend_hash_quick_add(class_table, Z_STRVAL_P(op2), Z_STRLEN_P(op2)+1, Z_HASH_P(op2), pce, sizeof(zend_class_entry *), NULL)==FAILURE) { zend_error(E_COMPILE_ERROR, "Cannot redeclare class %s", ce->name); } return ce; } /* }}} */ void zend_do_early_binding(TSRMLS_D) /* {{{ */ { zend_op *opline = &CG(active_op_array)->opcodes[CG(active_op_array)->last-1]; HashTable *table; while (opline->opcode == ZEND_TICKS && opline > CG(active_op_array)->opcodes) { opline--; } switch (opline->opcode) { case ZEND_DECLARE_FUNCTION: if (do_bind_function(CG(active_op_array), opline, CG(function_table), 1) == FAILURE) { return; } table = CG(function_table); break; case ZEND_DECLARE_CLASS: if (do_bind_class(CG(active_op_array), opline, CG(class_table), 1 TSRMLS_CC) == NULL) { return; } table = CG(class_table); break; case ZEND_DECLARE_INHERITED_CLASS: { zend_op *fetch_class_opline = opline-1; zval *parent_name; zend_class_entry **pce; parent_name = &CONSTANT(fetch_class_opline->op2.constant); if ((zend_lookup_class(Z_STRVAL_P(parent_name), Z_STRLEN_P(parent_name), &pce TSRMLS_CC) == FAILURE) || ((CG(compiler_options) & ZEND_COMPILE_IGNORE_INTERNAL_CLASSES) && ((*pce)->type == ZEND_INTERNAL_CLASS))) { if (CG(compiler_options) & ZEND_COMPILE_DELAYED_BINDING) { zend_uint *opline_num = &CG(active_op_array)->early_binding; while (*opline_num != -1) { opline_num = &CG(active_op_array)->opcodes[*opline_num].result.opline_num; } *opline_num = opline - CG(active_op_array)->opcodes; opline->opcode = ZEND_DECLARE_INHERITED_CLASS_DELAYED; opline->result_type = IS_UNUSED; opline->result.opline_num = -1; } return; } if (do_bind_inherited_class(CG(active_op_array), opline, CG(class_table), *pce, 1 TSRMLS_CC) == NULL) { return; } /* clear unnecessary ZEND_FETCH_CLASS opcode */ zend_del_literal(CG(active_op_array), fetch_class_opline->op2.constant); MAKE_NOP(fetch_class_opline); table = CG(class_table); break; } case ZEND_VERIFY_ABSTRACT_CLASS: case ZEND_ADD_INTERFACE: case ZEND_ADD_TRAIT: case ZEND_BIND_TRAITS: /* We currently don't early-bind classes that implement interfaces */ /* Classes with traits are handled exactly the same, no early-bind here */ return; default: zend_error(E_COMPILE_ERROR, "Invalid binding type"); return; } zend_hash_quick_del(table, Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant)), Z_HASH_P(&CONSTANT(opline->op1.constant))); zend_del_literal(CG(active_op_array), opline->op1.constant); zend_del_literal(CG(active_op_array), opline->op2.constant); MAKE_NOP(opline); } /* }}} */ ZEND_API void zend_do_delayed_early_binding(const zend_op_array *op_array TSRMLS_DC) /* {{{ */ { if (op_array->early_binding != -1) { zend_bool orig_in_compilation = CG(in_compilation); zend_uint opline_num = op_array->early_binding; zend_class_entry **pce; CG(in_compilation) = 1; while (opline_num != -1) { if (zend_lookup_class(Z_STRVAL_P(op_array->opcodes[opline_num-1].op2.zv), Z_STRLEN_P(op_array->opcodes[opline_num-1].op2.zv), &pce TSRMLS_CC) == SUCCESS) { do_bind_inherited_class(op_array, &op_array->opcodes[opline_num], EG(class_table), *pce, 0 TSRMLS_CC); } opline_num = op_array->opcodes[opline_num].result.opline_num; } CG(in_compilation) = orig_in_compilation; } } /* }}} */ void zend_do_boolean_or_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_or_end(znode *result, const znode *expr1, const znode *expr2, znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_boolean_and_begin(znode *expr1, znode *op_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ_EX; if (expr1->op_type == IS_TMP_VAR) { SET_NODE(opline->result, expr1); } else { opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; } SET_NODE(opline->op1, expr1); SET_UNUSED(opline->op2); op_token->u.op.opline_num = next_op_number; GET_NODE(expr1, opline->result); } /* }}} */ void zend_do_boolean_and_end(znode *result, const znode *expr1, const znode *expr2, const znode *op_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); *result = *expr1; /* we saved the original result in expr1 */ opline->opcode = ZEND_BOOL; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr2); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[op_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); } /* }}} */ void zend_do_do_while_begin(TSRMLS_D) /* {{{ */ { do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_do_while_end(const znode *do_token, const znode *expr_open_bracket, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPNZ; SET_NODE(opline->op1, expr); opline->op2.opline_num = do_token->u.op.opline_num; SET_UNUSED(opline->op2); do_end_loop(expr_open_bracket->u.op.opline_num, 0 TSRMLS_CC); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_brk_cont(zend_uchar op, const znode *expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = op; opline->op1.opline_num = CG(context).current_brk_cont; SET_UNUSED(opline->op1); if (expr) { if (expr->op_type != IS_CONST) { zend_error(E_COMPILE_ERROR, "'%s' operator with non-constant operand is no longer supported", op == ZEND_BRK ? "break" : "continue"); } else if (Z_TYPE(expr->u.constant) != IS_LONG || Z_LVAL(expr->u.constant) < 1) { zend_error(E_COMPILE_ERROR, "'%s' operator accepts only positive numbers", op == ZEND_BRK ? "break" : "continue"); } SET_NODE(opline->op2, expr); } else { LITERAL_LONG(opline->op2, 1); opline->op2_type = IS_CONST; } } /* }}} */ void zend_do_switch_cond(const znode *cond TSRMLS_DC) /* {{{ */ { zend_switch_entry switch_entry; switch_entry.cond = *cond; switch_entry.default_case = -1; switch_entry.control_var = -1; zend_stack_push(&CG(switch_cond_stack), (void *) &switch_entry, sizeof(switch_entry)); do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_switch_end(const znode *case_list TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); /* add code to jmp to default case */ if (switch_entry_ptr->default_case != -1) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->op1.opline_num = switch_entry_ptr->default_case; } if (case_list->op_type != IS_UNUSED) { /* non-empty switch */ int next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* remember break/continue loop information */ CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].brk = get_next_op_number(CG(active_op_array)); CG(context).current_brk_cont = CG(active_op_array)->brk_cont_array[CG(context).current_brk_cont].parent; if (switch_entry_ptr->cond.op_type==IS_VAR || switch_entry_ptr->cond.op_type==IS_TMP_VAR) { /* emit free for the switch condition*/ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (switch_entry_ptr->cond.op_type == IS_TMP_VAR) ? ZEND_FREE : ZEND_SWITCH_FREE; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_UNUSED(opline->op2); } if (switch_entry_ptr->cond.op_type == IS_CONST) { zval_dtor(&switch_entry_ptr->cond.u.constant); } zend_stack_del_top(&CG(switch_cond_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_case_before_statement(const znode *case_list, znode *case_token, const znode *case_expr TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); int next_op_number; zend_switch_entry *switch_entry_ptr; znode result; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); if (switch_entry_ptr->control_var == -1) { switch_entry_ptr->control_var = get_temporary_variable(CG(active_op_array)); } opline->opcode = ZEND_CASE; opline->result.var = switch_entry_ptr->control_var; opline->result_type = IS_TMP_VAR; SET_NODE(opline->op1, &switch_entry_ptr->cond); SET_NODE(opline->op2, case_expr); if (opline->op1_type == IS_CONST) { zval_copy_ctor(&CONSTANT(opline->op1.constant)); } GET_NODE(&result, opline->result); next_op_number = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, &result); SET_UNUSED(opline->op2); case_token->u.op.opline_num = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } next_op_number = get_next_op_number(CG(active_op_array)); CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_case_after_statement(znode *result, const znode *case_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); result->u.op.opline_num = next_op_number; switch (CG(active_op_array)->opcodes[case_token->u.op.opline_num].opcode) { case ZEND_JMP: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); break; case ZEND_JMPZ: CG(active_op_array)->opcodes[case_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); break; } } /* }}} */ void zend_do_default_before_statement(const znode *case_list, znode *default_token TSRMLS_DC) /* {{{ */ { int next_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); zend_switch_entry *switch_entry_ptr; zend_stack_top(&CG(switch_cond_stack), (void **) &switch_entry_ptr); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); default_token->u.op.opline_num = next_op_number; next_op_number = get_next_op_number(CG(active_op_array)); switch_entry_ptr->default_case = next_op_number; if (case_list->op_type==IS_UNUSED) { return; } CG(active_op_array)->opcodes[case_list->u.op.opline_num].op1.opline_num = next_op_number; } /* }}} */ void zend_do_begin_class_declaration(const znode *class_token, znode *class_name, const znode *parent_class_name TSRMLS_DC) /* {{{ */ { zend_op *opline; int doing_inheritance = 0; zend_class_entry *new_class_entry; char *lcname; int error = 0; zval **ns_name, key; if (CG(active_class_entry)) { zend_error(E_COMPILE_ERROR, "Class declarations may not be nested"); return; } lcname = zend_str_tolower_dup(class_name->u.constant.value.str.val, class_name->u.constant.value.str.len); if (!(strcmp(lcname, "self") && strcmp(lcname, "parent"))) { efree(lcname); zend_error(E_COMPILE_ERROR, "Cannot use '%s' as class name as it is reserved", Z_STRVAL(class_name->u.constant)); } /* Class name must not conflict with import names */ if (CG(current_import) && zend_hash_find(CG(current_import), lcname, Z_STRLEN(class_name->u.constant)+1, (void**)&ns_name) == SUCCESS) { error = 1; } if (CG(current_namespace)) { /* Prefix class name with name of current namespace */ znode tmp; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(&tmp, &tmp, class_name TSRMLS_CC); class_name = &tmp; efree(lcname); lcname = zend_str_tolower_dup(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant)); } if (error) { char *tmp = zend_str_tolower_dup(Z_STRVAL_PP(ns_name), Z_STRLEN_PP(ns_name)); if (Z_STRLEN_PP(ns_name) != Z_STRLEN(class_name->u.constant) || memcmp(tmp, lcname, Z_STRLEN(class_name->u.constant))) { zend_error(E_COMPILE_ERROR, "Cannot declare class %s because the name is already in use", Z_STRVAL(class_name->u.constant)); } efree(tmp); } new_class_entry = emalloc(sizeof(zend_class_entry)); new_class_entry->type = ZEND_USER_CLASS; new_class_entry->name = zend_new_interned_string(Z_STRVAL(class_name->u.constant), Z_STRLEN(class_name->u.constant) + 1, 1 TSRMLS_CC); new_class_entry->name_length = Z_STRLEN(class_name->u.constant); zend_initialize_class_data(new_class_entry, 1 TSRMLS_CC); new_class_entry->info.user.filename = zend_get_compiled_filename(TSRMLS_C); new_class_entry->info.user.line_start = class_token->u.op.opline_num; new_class_entry->ce_flags |= class_token->EA; if (parent_class_name && parent_class_name->op_type != IS_UNUSED) { switch (parent_class_name->EA) { case ZEND_FETCH_CLASS_SELF: zend_error(E_COMPILE_ERROR, "Cannot use 'self' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_PARENT: zend_error(E_COMPILE_ERROR, "Cannot use 'parent' as class name as it is reserved"); break; case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use 'static' as class name as it is reserved"); break; default: break; } doing_inheritance = 1; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->op1_type = IS_CONST; build_runtime_defined_function_key(&key, lcname, new_class_entry->name_length TSRMLS_CC); opline->op1.constant = zend_add_literal(CG(active_op_array), &key TSRMLS_CC); Z_HASH_P(&CONSTANT(opline->op1.constant)) = zend_hash_func(Z_STRVAL(CONSTANT(opline->op1.constant)), Z_STRLEN(CONSTANT(opline->op1.constant))); opline->op2_type = IS_CONST; if (doing_inheritance) { /* Make sure a trait does not try to extend a class */ if ((new_class_entry->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "A trait (%s) cannot extend a class", new_class_entry->name); } opline->extended_value = parent_class_name->u.op.var; opline->opcode = ZEND_DECLARE_INHERITED_CLASS; } else { opline->opcode = ZEND_DECLARE_CLASS; } LITERAL_STRINGL(opline->op2, lcname, new_class_entry->name_length, 0); CALCULATE_LITERAL_HASH(opline->op2.constant); zend_hash_quick_update(CG(class_table), Z_STRVAL(key), Z_STRLEN(key), Z_HASH_P(&CONSTANT(opline->op1.constant)), &new_class_entry, sizeof(zend_class_entry *), NULL); CG(active_class_entry) = new_class_entry; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; GET_NODE(&CG(implementing_class), opline->result); if (CG(doc_comment)) { CG(active_class_entry)->info.user.doc_comment = CG(doc_comment); CG(active_class_entry)->info.user.doc_comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ static void do_verify_abstract_class(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_VERIFY_ABSTRACT_CLASS; SET_NODE(opline->op1, &CG(implementing_class)); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_end_class_declaration(const znode *class_token, const znode *parent_token TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = CG(active_class_entry); if (ce->constructor) { ce->constructor->common.fn_flags |= ZEND_ACC_CTOR; if (ce->constructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Constructor %s::%s() cannot be static", ce->name, ce->constructor->common.function_name); } } if (ce->destructor) { ce->destructor->common.fn_flags |= ZEND_ACC_DTOR; if (ce->destructor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Destructor %s::%s() cannot be static", ce->name, ce->destructor->common.function_name); } } if (ce->clone) { ce->clone->common.fn_flags |= ZEND_ACC_CLONE; if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static", ce->name, ce->clone->common.function_name); } } ce->info.user.line_end = zend_get_compiled_lineno(TSRMLS_C); /* Check for traits and proceed like with interfaces. * The only difference will be a combined handling of them in the end. * Thus, we need another opcode here. */ if (ce->num_traits > 0) { zend_op *opline; ce->traits = NULL; ce->num_traits = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_TRAITS; /* opcode generation: */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BIND_TRAITS; SET_NODE(opline->op1, &CG(implementing_class)); } if (!(ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS)) && ((parent_token->op_type != IS_UNUSED) || (ce->num_interfaces > 0))) { zend_verify_abstract_class(ce TSRMLS_CC); if (ce->num_interfaces) { do_verify_abstract_class(TSRMLS_C); } } /* Inherit interfaces; reset number to zero, we need it for above check and * will restore it during actual implementation. * The ZEND_ACC_IMPLEMENT_INTERFACES flag disables double call to * zend_verify_abstract_class() */ if (ce->num_interfaces > 0) { ce->interfaces = NULL; ce->num_interfaces = 0; ce->ce_flags |= ZEND_ACC_IMPLEMENT_INTERFACES; } CG(active_class_entry) = NULL; } /* }}} */ void zend_do_implements_interface(znode *interface_name TSRMLS_DC) /* {{{ */ { zend_op *opline; /* Traits can not implement interfaces */ if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface on '%s' since it is a Trait", Z_STRVAL(interface_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(interface_name->u.constant), Z_STRLEN(interface_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as interface name as it is reserved", Z_STRVAL(interface_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_INTERFACE; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(interface_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = (opline->extended_value & ~ZEND_FETCH_CLASS_MASK) | ZEND_FETCH_CLASS_INTERFACE; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &interface_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_interfaces++; } /* }}} */ void zend_do_implements_trait(znode *trait_name TSRMLS_DC) /* {{{ */ { zend_op *opline; if ((CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE)) { zend_error(E_COMPILE_ERROR, "Cannot use traits inside of interfaces. %s is used in %s", Z_STRVAL(trait_name->u.constant), CG(active_class_entry)->name); } switch (zend_get_class_fetch_type(Z_STRVAL(trait_name->u.constant), Z_STRLEN(trait_name->u.constant))) { case ZEND_FETCH_CLASS_SELF: case ZEND_FETCH_CLASS_PARENT: case ZEND_FETCH_CLASS_STATIC: zend_error(E_COMPILE_ERROR, "Cannot use '%s' as trait name as it is reserved", Z_STRVAL(trait_name->u.constant)); break; default: break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_TRAIT; SET_NODE(opline->op1, &CG(implementing_class)); zend_resolve_class_name(trait_name, opline->extended_value, 0 TSRMLS_CC); opline->extended_value = ZEND_FETCH_CLASS_TRAIT; opline->op2_type = IS_CONST; opline->op2.constant = zend_add_class_name_literal(CG(active_op_array), &trait_name->u.constant TSRMLS_CC); CG(active_class_entry)->num_traits++; } /* }}} */ ZEND_API void zend_mangle_property_name(char **dest, int *dest_length, const char *src1, int src1_length, const char *src2, int src2_length, int internal) /* {{{ */ { char *prop_name; int prop_name_length; prop_name_length = 1 + src1_length + 1 + src2_length; prop_name = pemalloc(prop_name_length + 1, internal); prop_name[0] = '\0'; memcpy(prop_name + 1, src1, src1_length+1); memcpy(prop_name + 1 + src1_length + 1, src2, src2_length+1); *dest = prop_name; *dest_length = prop_name_length; } /* }}} */ static int zend_strnlen(const char* s, int maxlen) /* {{{ */ { int len = 0; while (*s++ && maxlen--) len++; return len; } /* }}} */ ZEND_API int zend_unmangle_property_name(const char *mangled_property, int len, const char **class_name, const char **prop_name) /* {{{ */ { int class_name_len; *class_name = NULL; if (mangled_property[0]!=0) { *prop_name = mangled_property; return SUCCESS; } if (len < 3 || mangled_property[1]==0) { zend_error(E_NOTICE, "Illegal member variable name"); *prop_name = mangled_property; return FAILURE; } class_name_len = zend_strnlen(mangled_property+1, --len - 1) + 1; if (class_name_len >= len || mangled_property[class_name_len]!=0) { zend_error(E_NOTICE, "Corrupt member variable name"); *prop_name = mangled_property; return FAILURE; } *class_name = mangled_property+1; *prop_name = (*class_name)+class_name_len; return SUCCESS; } /* }}} */ void zend_do_declare_property(const znode *var_name, const znode *value, zend_uint access_type TSRMLS_DC) /* {{{ */ { zval *property; zend_property_info *existing_property_info; char *comment = NULL; int comment_len = 0; if (CG(active_class_entry)->ce_flags & ZEND_ACC_INTERFACE) { zend_error(E_COMPILE_ERROR, "Interfaces may not include member variables"); } if (access_type & ZEND_ACC_ABSTRACT) { zend_error(E_COMPILE_ERROR, "Properties cannot be declared abstract"); } if (access_type & ZEND_ACC_FINAL) { zend_error(E_COMPILE_ERROR, "Cannot declare property %s::$%s final, the final modifier is allowed only for methods and classes", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } if (zend_hash_find(&CG(active_class_entry)->properties_info, var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, (void **) &existing_property_info)==SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot redeclare %s::$%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } ALLOC_ZVAL(property); if (value) { *property = value->u.constant; } else { INIT_PZVAL(property); Z_TYPE_P(property) = IS_NULL; } if (CG(doc_comment)) { comment = CG(doc_comment); comment_len = CG(doc_comment_len); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } zend_declare_property_ex(CG(active_class_entry), zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len + 1, 0 TSRMLS_CC), var_name->u.constant.value.str.len, property, access_type, comment, comment_len TSRMLS_CC); efree(var_name->u.constant.value.str.val); } /* }}} */ void zend_do_declare_class_constant(znode *var_name, const znode *value TSRMLS_DC) /* {{{ */ { zval *property; const char *cname = NULL; int result; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed in class constants"); return; } if ((CG(active_class_entry)->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { zend_error(E_COMPILE_ERROR, "Traits cannot have constants"); return; } ALLOC_ZVAL(property); *property = value->u.constant; cname = zend_new_interned_string(var_name->u.constant.value.str.val, var_name->u.constant.value.str.len+1, 0 TSRMLS_CC); if (IS_INTERNED(cname)) { result = zend_hash_quick_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, INTERNED_HASH(cname), &property, sizeof(zval *), NULL); } else { result = zend_hash_add(&CG(active_class_entry)->constants_table, cname, var_name->u.constant.value.str.len+1, &property, sizeof(zval *), NULL); } if (result == FAILURE) { FREE_ZVAL(property); zend_error(E_COMPILE_ERROR, "Cannot redefine class constant %s::%s", CG(active_class_entry)->name, var_name->u.constant.value.str.val); } FREE_PNODE(var_name); if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_fetch_property(znode *result, znode *object, const znode *property TSRMLS_DC) /* {{{ */ { zend_op opline; zend_llist *fetch_list_ptr; zend_stack_top(&CG(bp_stack), (void **) &fetch_list_ptr); if (object->op_type == IS_CV) { if (object->u.op.var == CG(active_op_array)->this_var) { object->op_type = IS_UNUSED; /* this means $this for objects */ } } else if (fetch_list_ptr->count == 1) { zend_llist_element *le = fetch_list_ptr->head; zend_op *opline_ptr = (zend_op *) le->data; if (opline_is_fetch_this(opline_ptr TSRMLS_CC)) { zend_del_literal(CG(active_op_array), opline_ptr->op1.constant); SET_UNUSED(opline_ptr->op1); /* this means $this for objects */ SET_NODE(opline_ptr->op2, property); /* if it was usual fetch, we change it to object fetch */ switch (opline_ptr->opcode) { case ZEND_FETCH_W: opline_ptr->opcode = ZEND_FETCH_OBJ_W; break; case ZEND_FETCH_R: opline_ptr->opcode = ZEND_FETCH_OBJ_R; break; case ZEND_FETCH_RW: opline_ptr->opcode = ZEND_FETCH_OBJ_RW; break; case ZEND_FETCH_IS: opline_ptr->opcode = ZEND_FETCH_OBJ_IS; break; case ZEND_FETCH_UNSET: opline_ptr->opcode = ZEND_FETCH_OBJ_UNSET; break; case ZEND_FETCH_FUNC_ARG: opline_ptr->opcode = ZEND_FETCH_OBJ_FUNC_ARG; break; } if (opline_ptr->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline_ptr->op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline_ptr->op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline_ptr->op2.constant); } GET_NODE(result, opline_ptr->result); return; } } if (zend_is_function_or_method_call(object)) { init_op(&opline TSRMLS_CC); opline.opcode = ZEND_SEPARATE; SET_NODE(opline.op1, object); SET_UNUSED(opline.op2); opline.result_type = IS_VAR; opline.result.var = opline.op1.var; zend_llist_add_element(fetch_list_ptr, &opline); } init_op(&opline TSRMLS_CC); opline.opcode = ZEND_FETCH_OBJ_W; /* the backpatching routine assumes W */ opline.result_type = IS_VAR; opline.result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline.op1, object); SET_NODE(opline.op2, property); if (opline.op2_type == IS_CONST && Z_TYPE(CONSTANT(opline.op2.constant)) == IS_STRING) { CALCULATE_LITERAL_HASH(opline.op2.constant); GET_POLYMORPHIC_CACHE_SLOT(opline.op2.constant); } GET_NODE(result, opline.result); zend_llist_add_element(fetch_list_ptr, &opline); } /* }}} */ void zend_do_halt_compiler_register(TSRMLS_D) /* {{{ */ { char *name, *cfilename; char haltoff[] = "__COMPILER_HALT_OFFSET__"; int len, clen; if (CG(has_bracketed_namespaces) && CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "__HALT_COMPILER() can only be used from the outermost scope"); } cfilename = zend_get_compiled_filename(TSRMLS_C); clen = strlen(cfilename); zend_mangle_property_name(&name, &len, haltoff, sizeof(haltoff) - 1, cfilename, clen, 0); zend_register_long_constant(name, len+1, zend_get_scanned_file_offset(TSRMLS_C), CONST_CS, 0 TSRMLS_CC); pefree(name, 0); if (CG(in_namespace)) { zend_do_end_namespace(TSRMLS_C); } } /* }}} */ void zend_do_push_object(const znode *object TSRMLS_DC) /* {{{ */ { zend_stack_push(&CG(object_stack), object, sizeof(znode)); } /* }}} */ void zend_do_pop_object(znode *object TSRMLS_DC) /* {{{ */ { if (object) { znode *tmp; zend_stack_top(&CG(object_stack), (void **) &tmp); *object = *tmp; } zend_stack_del_top(&CG(object_stack)); } /* }}} */ void zend_do_begin_new_object(znode *new_token, znode *class_type TSRMLS_DC) /* {{{ */ { zend_op *opline; unsigned char *ptr = NULL; new_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_NEW; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, class_type); SET_UNUSED(opline->op2); zend_stack_push(&CG(function_call_stack), (void *) &ptr, sizeof(unsigned char *)); } /* }}} */ void zend_do_end_new_object(znode *result, const znode *new_token, const znode *argument_list TSRMLS_DC) /* {{{ */ { znode ctor_result; zend_do_end_function_call(NULL, &ctor_result, argument_list, 1, 0 TSRMLS_CC); zend_do_free(&ctor_result TSRMLS_CC); CG(active_op_array)->opcodes[new_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, CG(active_op_array)->opcodes[new_token->u.op.opline_num].result); } /* }}} */ static zend_constant* zend_get_ct_const(const zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = NULL; if (Z_STRVAL_P(const_name)[0] == '\\') { if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name), (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name)+1, Z_STRLEN_P(const_name)-1); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name), (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } } else if (zend_hash_find(EG(zend_constants), Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)+1, (void **) &c) == FAILURE) { char *lookup_name = zend_str_tolower_dup(Z_STRVAL_P(const_name), Z_STRLEN_P(const_name)); if (zend_hash_find(EG(zend_constants), lookup_name, Z_STRLEN_P(const_name)+1, (void **) &c)==SUCCESS) { if ((c->flags & CONST_CT_SUBST) && !(c->flags & CONST_CS)) { efree(lookup_name); return c; } } efree(lookup_name); return NULL; } if (c->flags & CONST_CT_SUBST) { return c; } if (all_internal_constants_substitution && (c->flags & CONST_PERSISTENT) && !(CG(compiler_options) & ZEND_COMPILE_NO_CONSTANT_SUBSTITUTION) && Z_TYPE(c->value) != IS_CONSTANT && Z_TYPE(c->value) != IS_CONSTANT_ARRAY) { return c; } return NULL; } /* }}} */ static int zend_constant_ct_subst(znode *result, zval *const_name, int all_internal_constants_substitution TSRMLS_DC) /* {{{ */ { zend_constant *c = zend_get_ct_const(const_name, all_internal_constants_substitution TSRMLS_CC); if (c) { zval_dtor(const_name); result->op_type = IS_CONST; result->u.constant = c->value; zval_copy_ctor(&result->u.constant); INIT_PZVAL(&result->u.constant); return 1; } return 0; } /* }}} */ void zend_do_fetch_constant(znode *result, znode *constant_container, znode *constant_name, int mode, zend_bool check_namespace TSRMLS_DC) /* {{{ */ { znode tmp; zend_op *opline; int type; char *compound; ulong fetch_type = 0; if (constant_container) { switch (mode) { case ZEND_CT: /* this is a class constant */ type = zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant)); if (ZEND_FETCH_CLASS_STATIC == type) { zend_error(E_ERROR, "\"static::\" is not allowed in compile-time constants"); } else if (ZEND_FETCH_CLASS_DEFAULT == type) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } zend_do_build_full_name(NULL, constant_container, constant_name, 1 TSRMLS_CC); *result = *constant_container; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: if (constant_container->op_type == IS_CONST && ZEND_FETCH_CLASS_DEFAULT == zend_get_class_fetch_type(Z_STRVAL(constant_container->u.constant), Z_STRLEN(constant_container->u.constant))) { zend_resolve_class_name(constant_container, fetch_type, 1 TSRMLS_CC); } else { zend_do_fetch_class(&tmp, constant_container TSRMLS_CC); constant_container = &tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); if (constant_container->op_type == IS_CONST) { opline->op1_type = IS_CONST; opline->op1.constant = zend_add_class_name_literal(CG(active_op_array), &constant_container->u.constant TSRMLS_CC); } else { SET_NODE(opline->op1, constant_container); } SET_NODE(opline->op2, constant_name); CALCULATE_LITERAL_HASH(opline->op2.constant); if (opline->op1_type == IS_CONST) { GET_CACHE_SLOT(opline->op2.constant); } else { GET_POLYMORPHIC_CACHE_SLOT(opline->op2.constant); } GET_NODE(result, opline->result); break; } return; } /* namespace constant */ /* only one that did not contain \ from the start can be converted to string if unknown */ switch (mode) { case ZEND_CT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); /* this is a namespace constant, or an unprefixed constant */ if (zend_constant_ct_subst(result, &constant_name->u.constant, 0 TSRMLS_CC)) { break; } zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(!compound) { fetch_type |= IS_CONSTANT_UNQUALIFIED; } *result = *constant_name; result->u.constant.type = IS_CONSTANT | fetch_type; break; case ZEND_RT: compound = memchr(Z_STRVAL(constant_name->u.constant), '\\', Z_STRLEN(constant_name->u.constant)); zend_resolve_non_class_name(constant_name, check_namespace TSRMLS_CC); if(zend_constant_ct_subst(result, &constant_name->u.constant, 1 TSRMLS_CC)) { break; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_CONSTANT; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); GET_NODE(result, opline->result); SET_UNUSED(opline->op1); opline->op2_type = IS_CONST; if (compound) { /* the name is unambiguous */ opline->extended_value = 0; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } else { opline->extended_value = IS_CONSTANT_UNQUALIFIED; if (CG(current_namespace)) { opline->extended_value |= IS_CONSTANT_IN_NAMESPACE; opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 1 TSRMLS_CC); } else { opline->op2.constant = zend_add_const_name_literal(CG(active_op_array), &constant_name->u.constant, 0 TSRMLS_CC); } } GET_CACHE_SLOT(opline->op2.constant); break; } } /* }}} */ void zend_do_shell_exec(znode *result, const znode *cmd TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); switch (cmd->op_type) { case IS_CONST: case IS_TMP_VAR: opline->opcode = ZEND_SEND_VAL; break; default: opline->opcode = ZEND_SEND_VAR; break; } SET_NODE(opline->op1, cmd); opline->op2.opline_num = 0; opline->extended_value = ZEND_DO_FCALL; SET_UNUSED(opline->op2); /* FIXME: exception support not added to this op2 */ opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DO_FCALL; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_VAR; LITERAL_STRINGL(opline->op1, estrndup("shell_exec", sizeof("shell_exec")-1), sizeof("shell_exec")-1, 0); CALCULATE_LITERAL_HASH(opline->op1.constant); opline->op1_type = IS_CONST; GET_CACHE_SLOT(opline->op1.constant); opline->extended_value = 1; SET_UNUSED(opline->op2); GET_NODE(result, opline->result); } /* }}} */ void zend_do_init_array(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INIT_ARRAY; opline->result.var = get_temporary_variable(CG(active_op_array)); opline->result_type = IS_TMP_VAR; GET_NODE(result, opline->result); if (expr) { SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } } else { SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_array_element(znode *result, const znode *expr, const znode *offset, zend_bool is_ref TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_ADD_ARRAY_ELEMENT; SET_NODE(opline->result, result); SET_NODE(opline->op1, expr); if (offset) { SET_NODE(opline->op2, offset); if (opline->op2_type == IS_CONST && Z_TYPE(CONSTANT(opline->op2.constant)) == IS_STRING) { ulong index; int numeric = 0; ZEND_HANDLE_NUMERIC_EX(Z_STRVAL(CONSTANT(opline->op2.constant)), Z_STRLEN(CONSTANT(opline->op2.constant))+1, index, numeric = 1); if (numeric) { zval_dtor(&CONSTANT(opline->op2.constant)); ZVAL_LONG(&CONSTANT(opline->op2.constant), index); } else { CALCULATE_LITERAL_HASH(opline->op2.constant); } } } else { SET_UNUSED(opline->op2); } opline->extended_value = is_ref; } /* }}} */ void zend_do_add_static_array_element(znode *result, znode *offset, const znode *expr) /* {{{ */ { zval *element; ALLOC_ZVAL(element); *element = expr->u.constant; if (offset) { switch (offset->u.constant.type & IS_CONSTANT_TYPE_MASK) { case IS_CONSTANT: /* Ugly hack to denote that this value has a constant index */ Z_TYPE_P(element) |= IS_CONSTANT_INDEX; Z_STRVAL(offset->u.constant) = erealloc(Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+1] = Z_TYPE(offset->u.constant); Z_STRVAL(offset->u.constant)[Z_STRLEN(offset->u.constant)+2] = 0; zend_symtable_update(result->u.constant.value.ht, Z_STRVAL(offset->u.constant), Z_STRLEN(offset->u.constant)+3, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_STRING: zend_symtable_update(result->u.constant.value.ht, offset->u.constant.value.str.val, offset->u.constant.value.str.len+1, &element, sizeof(zval *), NULL); zval_dtor(&offset->u.constant); break; case IS_NULL: zend_symtable_update(Z_ARRVAL(result->u.constant), "", 1, &element, sizeof(zval *), NULL); break; case IS_LONG: case IS_BOOL: zend_hash_index_update(Z_ARRVAL(result->u.constant), Z_LVAL(offset->u.constant), &element, sizeof(zval *), NULL); break; case IS_DOUBLE: zend_hash_index_update(Z_ARRVAL(result->u.constant), zend_dval_to_lval(Z_DVAL(offset->u.constant)), &element, sizeof(zval *), NULL); break; case IS_CONSTANT_ARRAY: zend_error(E_ERROR, "Illegal offset type"); break; } } else { zend_hash_next_index_insert(Z_ARRVAL(result->u.constant), &element, sizeof(zval *), NULL); } } /* }}} */ void zend_do_add_list_element(const znode *element TSRMLS_DC) /* {{{ */ { list_llist_element lle; if (element) { zend_check_writable_variable(element); lle.var = *element; zend_llist_copy(&lle.dimensions, &CG(dimension_llist)); zend_llist_prepend_element(&CG(list_llist), &lle); } (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_new_list_begin(TSRMLS_D) /* {{{ */ { int current_dimension = 0; zend_llist_add_element(&CG(dimension_llist), &current_dimension); } /* }}} */ void zend_do_new_list_end(TSRMLS_D) /* {{{ */ { zend_llist_remove_tail(&CG(dimension_llist)); (*((int *)CG(dimension_llist).tail->data))++; } /* }}} */ void zend_do_list_init(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(list_stack), &CG(list_llist), sizeof(zend_llist)); zend_stack_push(&CG(list_stack), &CG(dimension_llist), sizeof(zend_llist)); zend_llist_init(&CG(list_llist), sizeof(list_llist_element), NULL, 0); zend_llist_init(&CG(dimension_llist), sizeof(int), NULL, 0); zend_do_new_list_begin(TSRMLS_C); } /* }}} */ void zend_do_list_end(znode *result, znode *expr TSRMLS_DC) /* {{{ */ { zend_llist_element *le; zend_llist_element *dimension; zend_op *opline; znode last_container; le = CG(list_llist).head; while (le) { zend_llist *tmp_dimension_llist = &((list_llist_element *)le->data)->dimensions; dimension = tmp_dimension_llist->head; while (dimension) { opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (dimension == tmp_dimension_llist->head) { /* first */ last_container = *expr; switch (expr->op_type) { case IS_VAR: case IS_CV: opline->opcode = ZEND_FETCH_DIM_R; break; case IS_TMP_VAR: opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; case IS_CONST: /* fetch_dim_tmp_var will handle this bogus fetch */ zval_copy_ctor(&expr->u.constant); opline->opcode = ZEND_FETCH_DIM_TMP_VAR; break; } opline->extended_value |= ZEND_FETCH_ADD_LOCK; } else { opline->opcode = ZEND_FETCH_DIM_R; } opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, &last_container); opline->op2_type = IS_CONST; LITERAL_LONG(opline->op2, *((int *) dimension->data)); GET_NODE(&last_container, opline->result); dimension = dimension->next; } ((list_llist_element *) le->data)->value = last_container; zend_llist_destroy(&((list_llist_element *) le->data)->dimensions); zend_do_assign(result, &((list_llist_element *) le->data)->var, &((list_llist_element *) le->data)->value TSRMLS_CC); zend_do_free(result TSRMLS_CC); le = le->next; } zend_llist_destroy(&CG(dimension_llist)); zend_llist_destroy(&CG(list_llist)); *result = *expr; { zend_llist *p; /* restore previous lists */ zend_stack_top(&CG(list_stack), (void **) &p); CG(dimension_llist) = *p; zend_stack_del_top(&CG(list_stack)); zend_stack_top(&CG(list_stack), (void **) &p); CG(list_llist) = *p; zend_stack_del_top(&CG(list_stack)); } } /* }}} */ void zend_init_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = emalloc(sizeof(void*) * 2); list[0] = item; list[1] = NULL; *(void**)result = list; } /* }}} */ void zend_add_to_list(void *result, void *item TSRMLS_DC) /* {{{ */ { void** list = *(void**)result; size_t n = 0; while (list && list[n]) { n++; } list = erealloc(list, sizeof(void*) * (n+2)); list[n] = item; list[n+1] = NULL; *(void**)result = list; } /* }}} */ void zend_do_fetch_static_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zval *tmp; zend_op *opline; znode lval; znode result; ALLOC_ZVAL(tmp); if (static_assignment) { *tmp = static_assignment->u.constant; } else { INIT_ZVAL(*tmp); } if (!CG(active_op_array)->static_variables) { if (CG(active_op_array)->scope) { CG(active_op_array)->scope->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } ALLOC_HASHTABLE(CG(active_op_array)->static_variables); zend_hash_init(CG(active_op_array)->static_variables, 2, NULL, ZVAL_PTR_DTOR, 0); } zend_hash_update(CG(active_op_array)->static_variables, varname->u.constant.value.str.val, varname->u.constant.value.str.len+1, &tmp, sizeof(zval *), NULL); if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = (fetch_type == ZEND_FETCH_LEXICAL) ? ZEND_FETCH_R : ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = ZEND_FETCH_STATIC; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ if (fetch_type == ZEND_FETCH_LEXICAL) { znode dummy; zend_do_begin_variable_parse(TSRMLS_C); zend_do_assign(&dummy, &lval, &result TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } else { zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); } CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_fetch_lexical_variable(znode *varname, zend_bool is_ref TSRMLS_DC) /* {{{ */ { znode value; if (Z_STRLEN(varname->u.constant) == sizeof("this") - 1 && memcmp(Z_STRVAL(varname->u.constant), "this", sizeof("this") - 1) == 0) { zend_error(E_COMPILE_ERROR, "Cannot use $this as lexical variable"); return; } value.op_type = IS_CONST; ZVAL_NULL(&value.u.constant); Z_TYPE(value.u.constant) |= is_ref ? IS_LEXICAL_REF : IS_LEXICAL_VAR; Z_SET_REFCOUNT_P(&value.u.constant, 1); Z_UNSET_ISREF_P(&value.u.constant); zend_do_fetch_static_variable(varname, &value, is_ref ? ZEND_FETCH_STATIC : ZEND_FETCH_LEXICAL TSRMLS_CC); } /* }}} */ void zend_do_fetch_global_variable(znode *varname, const znode *static_assignment, int fetch_type TSRMLS_DC) /* {{{ */ { zend_op *opline; znode lval; znode result; if (varname->op_type == IS_CONST) { if (Z_TYPE(varname->u.constant) != IS_STRING) { convert_to_string(&varname->u.constant); } } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FETCH_W; /* the default mode must be Write, since fetch_simple_variable() is used to define function arguments */ opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, varname); if (opline->op1_type == IS_CONST) { CALCULATE_LITERAL_HASH(opline->op1.constant); } SET_UNUSED(opline->op2); opline->extended_value = fetch_type; GET_NODE(&result, opline->result); if (varname->op_type == IS_CONST) { zval_copy_ctor(&varname->u.constant); } fetch_simple_variable(&lval, varname, 0 TSRMLS_CC); /* Relies on the fact that the default fetch is BP_VAR_W */ zend_do_assign_ref(NULL, &lval, &result TSRMLS_CC); CG(active_op_array)->opcodes[CG(active_op_array)->last-1].result_type |= EXT_TYPE_UNUSED; } /* }}} */ void zend_do_cast(znode *result, const znode *expr, int type TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_CAST; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } /* }}} */ void zend_do_include_or_eval(int type, znode *result, const znode *op1 TSRMLS_DC) /* {{{ */ { zend_do_extended_fcall_begin(TSRMLS_C); { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INCLUDE_OR_EVAL; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, op1); SET_UNUSED(opline->op2); opline->extended_value = type; GET_NODE(result, opline->result); } zend_do_extended_fcall_end(TSRMLS_C); } /* }}} */ void zend_do_indirect_references(znode *result, const znode *num_references, znode *variable TSRMLS_DC) /* {{{ */ { int i; zend_do_end_variable_parse(variable, BP_VAR_R, 0 TSRMLS_CC); for (i=1; i<num_references->u.constant.value.lval; i++) { fetch_simple_variable_ex(result, variable, 0, ZEND_FETCH_R TSRMLS_CC); *variable = *result; } zend_do_begin_variable_parse(TSRMLS_C); fetch_simple_variable(result, variable, 1 TSRMLS_CC); /* there is a chance someone is accessing $this */ if (CG(active_op_array)->scope && CG(active_op_array)->this_var == -1) { CG(active_op_array)->this_var = lookup_cv(CG(active_op_array), estrndup("this", sizeof("this")-1), sizeof("this")-1, THIS_HASHVAL TSRMLS_CC); } } /* }}} */ void zend_do_unset(const znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_UNSET_VAR; SET_NODE(opline->op1, variable); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); opline->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_UNSET: last_op->opcode = ZEND_UNSET_VAR; SET_UNUSED(last_op->result); break; case ZEND_FETCH_DIM_UNSET: last_op->opcode = ZEND_UNSET_DIM; SET_UNUSED(last_op->result); break; case ZEND_FETCH_OBJ_UNSET: last_op->opcode = ZEND_UNSET_OBJ; SET_UNUSED(last_op->result); break; } } } /* }}} */ void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {{{ */ { zend_op *last_op; zend_do_end_variable_parse(variable, BP_VAR_IS, 0 TSRMLS_CC); zend_check_writable_variable(variable); if (variable->op_type == IS_CV) { last_op = get_next_op(CG(active_op_array) TSRMLS_CC); last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; SET_NODE(last_op->op1, variable); SET_UNUSED(last_op->op2); last_op->result.var = get_temporary_variable(CG(active_op_array)); last_op->extended_value = ZEND_FETCH_LOCAL | ZEND_QUICK_SET; } else { last_op = &CG(active_op_array)->opcodes[get_next_op_number(CG(active_op_array))-1]; switch (last_op->opcode) { case ZEND_FETCH_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_VAR; break; case ZEND_FETCH_DIM_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_DIM_OBJ; break; case ZEND_FETCH_OBJ_IS: last_op->opcode = ZEND_ISSET_ISEMPTY_PROP_OBJ; break; } } last_op->result_type = IS_TMP_VAR; last_op->extended_value |= type; GET_NODE(result, last_op->result); } /* }}} */ void zend_do_instanceof(znode *result, const znode *expr, const znode *class_znode, int type TSRMLS_DC) /* {{{ */ { int last_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; if (last_op_number > 0) { opline = &CG(active_op_array)->opcodes[last_op_number-1]; if (opline->opcode == ZEND_FETCH_CLASS) { opline->extended_value |= ZEND_FETCH_CLASS_NO_AUTOLOAD; } } if (expr->op_type == IS_CONST) { zend_error(E_COMPILE_ERROR, "instanceof expects an object instance, constant given"); } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_INSTANCEOF; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, expr); SET_NODE(opline->op2, class_znode); GET_NODE(result, opline->result); } /* }}} */ void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC) /* {{{ */ { zend_op *opline; zend_bool is_variable; zend_bool push_container = 0; zend_op dummy_opline; if (variable) { if (zend_is_function_or_method_call(array)) { is_variable = 0; } else { is_variable = 1; } /* save the location of FETCH_W instruction(s) */ open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); zend_do_end_variable_parse(array, BP_VAR_W, 0 TSRMLS_CC); if (CG(active_op_array)->last > 0 && CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) { /* Only lock the container if we are fetching from a real container and not $this */ if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1_type == IS_VAR) { CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK; push_container = 1; } } } else { is_variable = 0; open_brackets_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); } /* save the location of FE_RESET */ foreach_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); /* Preform array reset */ opline->opcode = ZEND_FE_RESET; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, array); SET_UNUSED(opline->op2); opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0; COPY_NODE(dummy_opline.result, opline->result); if (push_container) { COPY_NODE(dummy_opline.op1, CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1); } else { dummy_opline.op1_type = IS_UNUSED; } zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op)); /* save the location of FE_FETCH */ as_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_FE_FETCH; opline->result_type = IS_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); COPY_NODE(opline->op1, dummy_opline.result); opline->extended_value = 0; SET_UNUSED(opline->op2); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_OP_DATA; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); SET_UNUSED(opline->result); } /* }}} */ void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC) /* {{{ */ { zend_op *opline; znode dummy, value_node; zend_bool assign_by_ref=0; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num]; if (key->op_type != IS_UNUSED) { znode *tmp; /* switch between the key and value... */ tmp = key; key = value; value = tmp; /* Mark extended_value in case both key and value are being used */ opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; } if ((key->op_type != IS_UNUSED) && (key->EA & ZEND_PARSED_REFERENCE_VARIABLE)) { zend_error(E_COMPILE_ERROR, "Key element cannot be a reference"); } if (value->EA & ZEND_PARSED_REFERENCE_VARIABLE) { assign_by_ref = 1; if (!(opline-1)->extended_value) { zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression"); } /* Mark extended_value for assign-by-reference */ opline->extended_value |= ZEND_FE_FETCH_BYREF; CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; } else { zend_op *foreach_copy; zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.op.opline_num]; zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.op.opline_num]; /* Change "write context" into "read context" */ fetch->extended_value = 0; /* reset ZEND_FE_RESET_VARIABLE */ while (fetch != end) { --fetch; if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2_type == IS_UNUSED) { zend_error(E_COMPILE_ERROR, "Cannot use [] for reading"); } if (fetch->opcode == ZEND_SEPARATE) { MAKE_NOP(fetch); } else { fetch->opcode -= 3; /* FETCH_W -> FETCH_R */ } } /* prevent double SWITCH_FREE */ zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy); foreach_copy->op1_type = IS_UNUSED; } GET_NODE(&value_node, opline->result); if (assign_by_ref) { zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); /* Mark FE_FETCH as IS_VAR as it holds the data directly as a value */ zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC); } else { zend_do_assign(&dummy, value, &value_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } if (key->op_type != IS_UNUSED) { znode key_node; opline = &CG(active_op_array)->opcodes[as_token->u.op.opline_num+1]; opline->result_type = IS_TMP_VAR; opline->result.opline_num = get_temporary_variable(CG(active_op_array)); GET_NODE(&key_node, opline->result); zend_do_assign(&dummy, key, &key_node TSRMLS_CC); zend_do_free(&dummy TSRMLS_CC); } do_begin_loop(TSRMLS_C); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_foreach_end(const znode *foreach_token, const znode *as_token TSRMLS_DC) /* {{{ */ { zend_op *container_ptr; zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; opline->op1.opline_num = as_token->u.op.opline_num; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[foreach_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_RESET */ CG(active_op_array)->opcodes[as_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); /* FE_FETCH */ do_end_loop(as_token->u.op.opline_num, 1 TSRMLS_CC); zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr); generate_free_foreach_copy(container_ptr TSRMLS_CC); zend_stack_del_top(&CG(foreach_copy_stack)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_declare_begin(TSRMLS_D) /* {{{ */ { zend_stack_push(&CG(declare_stack), &CG(declarables), sizeof(zend_declarables)); } /* }}} */ void zend_do_declare_stmt(znode *var, znode *val TSRMLS_DC) /* {{{ */ { if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "ticks", sizeof("ticks")-1)) { convert_to_long(&val->u.constant); CG(declarables).ticks = val->u.constant; } else if (!zend_binary_strcasecmp(var->u.constant.value.str.val, var->u.constant.value.str.len, "encoding", sizeof("encoding")-1)) { if ((Z_TYPE(val->u.constant) & IS_CONSTANT_TYPE_MASK) == IS_CONSTANT) { zend_error(E_COMPILE_ERROR, "Cannot use constants as encoding"); } /* * Check that the pragma comes before any opcodes. If the compilation * got as far as this, the previous portion of the script must have been * parseable according to the .ini script_encoding setting. We still * want to tell them to put declare() at the top. */ { int num = CG(active_op_array)->last; /* ignore ZEND_EXT_STMT and ZEND_TICKS */ while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Encoding declaration pragma must be the very first statement in the script"); } } if (CG(multibyte)) { const zend_encoding *new_encoding, *old_encoding; zend_encoding_filter old_input_filter; CG(encoding_declared) = 1; convert_to_string(&val->u.constant); new_encoding = zend_multibyte_fetch_encoding(val->u.constant.value.str.val TSRMLS_CC); if (!new_encoding) { zend_error(E_COMPILE_WARNING, "Unsupported encoding [%s]", val->u.constant.value.str.val); } else { old_input_filter = LANG_SCNG(input_filter); old_encoding = LANG_SCNG(script_encoding); zend_multibyte_set_filter(new_encoding TSRMLS_CC); /* need to re-scan if input filter changed */ if (old_input_filter != LANG_SCNG(input_filter) || (old_input_filter && new_encoding != old_encoding)) { zend_multibyte_yyinput_again(old_input_filter, old_encoding TSRMLS_CC); } } } else { zend_error(E_COMPILE_WARNING, "declare(encoding=...) ignored because Zend multibyte feature is turned off by settings"); } zval_dtor(&val->u.constant); } else { zend_error(E_COMPILE_WARNING, "Unsupported declare '%s'", var->u.constant.value.str.val); zval_dtor(&val->u.constant); } zval_dtor(&var->u.constant); } /* }}} */ void zend_do_declare_end(const znode *declare_token TSRMLS_DC) /* {{{ */ { zend_declarables *declarables; zend_stack_top(&CG(declare_stack), (void **) &declarables); /* We should restore if there was more than (current - start) - (ticks?1:0) opcodes */ if ((get_next_op_number(CG(active_op_array)) - declare_token->u.op.opline_num) - ((Z_LVAL(CG(declarables).ticks))?1:0)) { CG(declarables) = *declarables; } } /* }}} */ void zend_do_exit(znode *result, const znode *message TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXIT; SET_NODE(opline->op1, message); SET_UNUSED(opline->op2); result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_BOOL; Z_LVAL(result->u.constant) = 1; } /* }}} */ void zend_do_begin_silence(znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_BEGIN_SILENCE; opline->result_type = IS_TMP_VAR; opline->result.var = get_temporary_variable(CG(active_op_array)); SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); GET_NODE(strudel_token, opline->result); } /* }}} */ void zend_do_end_silence(const znode *strudel_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_END_SILENCE; SET_NODE(opline->op1, strudel_token); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_jmp_set(const znode *value, znode *jmp_token, znode *colon_token TSRMLS_DC) /* {{{ */ { int op_number = get_next_op_number(CG(active_op_array)); zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); if (value->op_type == IS_VAR || value->op_type == IS_CV) { opline->opcode = ZEND_JMP_SET_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_JMP_SET; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, value); SET_UNUSED(opline->op2); GET_NODE(colon_token, opline->result); jmp_token->u.op.opline_num = op_number; INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_jmp_set_else(znode *result, const znode *false_value, const znode *jmp_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, colon_token); if (colon_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].opcode = ZEND_JMP_SET_VAR; CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } opline->extended_value = 0; SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); GET_NODE(result, opline->result); CG(active_op_array)->opcodes[jmp_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array)); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_begin_qm_op(const znode *cond, znode *qm_token TSRMLS_DC) /* {{{ */ { int jmpz_op_number = get_next_op_number(CG(active_op_array)); zend_op *opline; opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMPZ; SET_NODE(opline->op1, cond); SET_UNUSED(opline->op2); opline->op2.opline_num = jmpz_op_number; GET_NODE(qm_token, opline->op2); INC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_qm_true(const znode *true_value, znode *qm_token, znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); CG(active_op_array)->opcodes[qm_token->u.op.opline_num].op2.opline_num = get_next_op_number(CG(active_op_array))+1; /* jmp over the ZEND_JMP */ if (true_value->op_type == IS_VAR || true_value->op_type == IS_CV) { opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; opline->result_type = IS_TMP_VAR; } opline->result.var = get_temporary_variable(CG(active_op_array)); SET_NODE(opline->op1, true_value); SET_UNUSED(opline->op2); GET_NODE(qm_token, opline->result); colon_token->u.op.opline_num = get_next_op_number(CG(active_op_array)); opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_JMP; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_qm_false(znode *result, const znode *false_value, const znode *qm_token, const znode *colon_token TSRMLS_DC) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); SET_NODE(opline->result, qm_token); if (qm_token->op_type == IS_TMP_VAR) { if (false_value->op_type == IS_VAR || false_value->op_type == IS_CV) { CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].opcode = ZEND_QM_ASSIGN_VAR; CG(active_op_array)->opcodes[colon_token->u.op.opline_num - 1].result_type = IS_VAR; opline->opcode = ZEND_QM_ASSIGN_VAR; opline->result_type = IS_VAR; } else { opline->opcode = ZEND_QM_ASSIGN; } } else { opline->opcode = ZEND_QM_ASSIGN_VAR; } SET_NODE(opline->op1, false_value); SET_UNUSED(opline->op2); CG(active_op_array)->opcodes[colon_token->u.op.opline_num].op1.opline_num = get_next_op_number(CG(active_op_array)); GET_NODE(result, opline->result); DEC_BPC(CG(active_op_array)); } /* }}} */ void zend_do_extended_info(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_STMT; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_begin(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_BEGIN; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_extended_fcall_end(TSRMLS_D) /* {{{ */ { zend_op *opline; if (!(CG(compiler_options) & ZEND_COMPILE_EXTENDED_INFO)) { return; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_EXT_FCALL_END; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); } /* }}} */ void zend_do_ticks(TSRMLS_D) /* {{{ */ { zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_TICKS; SET_UNUSED(opline->op1); SET_UNUSED(opline->op2); opline->extended_value = Z_LVAL(CG(declarables).ticks); } /* }}} */ zend_bool zend_is_auto_global_quick(const char *name, uint name_len, ulong hashval TSRMLS_DC) /* {{{ */ { zend_auto_global *auto_global; ulong hash = hashval ? hashval : zend_hash_func(name, name_len+1); if (zend_hash_quick_find(CG(auto_globals), name, name_len+1, hash, (void **) &auto_global)==SUCCESS) { if (auto_global->armed) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } return 1; } return 0; } /* }}} */ zend_bool zend_is_auto_global(const char *name, uint name_len TSRMLS_DC) /* {{{ */ { return zend_is_auto_global_quick(name, name_len, 0 TSRMLS_CC); } /* }}} */ int zend_register_auto_global(const char *name, uint name_len, zend_bool jit, zend_auto_global_callback auto_global_callback TSRMLS_DC) /* {{{ */ { zend_auto_global auto_global; auto_global.name = zend_new_interned_string((char*)name, name_len + 1, 0 TSRMLS_CC); auto_global.name_len = name_len; auto_global.auto_global_callback = auto_global_callback; auto_global.jit = jit; return zend_hash_add(CG(auto_globals), name, name_len+1, &auto_global, sizeof(zend_auto_global), NULL); } /* }}} */ static int zend_auto_global_init(zend_auto_global *auto_global TSRMLS_DC) /* {{{ */ { if (auto_global->jit) { auto_global->armed = 1; } else if (auto_global->auto_global_callback) { auto_global->armed = auto_global->auto_global_callback(auto_global->name, auto_global->name_len TSRMLS_CC); } else { auto_global->armed = 0; } return 0; } /* }}} */ ZEND_API void zend_activate_auto_globals(TSRMLS_D) /* {{{ */ { zend_hash_apply(CG(auto_globals), (apply_func_t) zend_auto_global_init TSRMLS_CC); } /* }}} */ int zendlex(znode *zendlval TSRMLS_DC) /* {{{ */ { int retval; if (CG(increment_lineno)) { CG(zend_lineno)++; CG(increment_lineno) = 0; } again: Z_TYPE(zendlval->u.constant) = IS_LONG; retval = lex_scan(&zendlval->u.constant TSRMLS_CC); switch (retval) { case T_COMMENT: case T_DOC_COMMENT: case T_OPEN_TAG: case T_WHITESPACE: goto again; case T_CLOSE_TAG: if (LANG_SCNG(yy_text)[LANG_SCNG(yy_leng)-1] != '>') { CG(increment_lineno) = 1; } if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { goto again; } retval = ';'; /* implicit ; */ break; case T_OPEN_TAG_WITH_ECHO: retval = T_ECHO; break; case T_END_HEREDOC: efree(Z_STRVAL(zendlval->u.constant)); break; } INIT_PZVAL(&zendlval->u.constant); zendlval->op_type = IS_CONST; return retval; } /* }}} */ ZEND_API void zend_initialize_class_data(zend_class_entry *ce, zend_bool nullify_handlers TSRMLS_DC) /* {{{ */ { zend_bool persistent_hashes = (ce->type == ZEND_INTERNAL_CLASS) ? 1 : 0; dtor_func_t zval_ptr_dtor_func = ((persistent_hashes) ? ZVAL_INTERNAL_PTR_DTOR : ZVAL_PTR_DTOR); ce->refcount = 1; ce->ce_flags = 0; ce->default_properties_table = NULL; ce->default_static_members_table = NULL; zend_hash_init_ex(&ce->properties_info, 0, NULL, (dtor_func_t) (persistent_hashes ? zend_destroy_property_info_internal : zend_destroy_property_info), persistent_hashes, 0); zend_hash_init_ex(&ce->constants_table, 0, NULL, zval_ptr_dtor_func, persistent_hashes, 0); zend_hash_init_ex(&ce->function_table, 0, NULL, ZEND_FUNCTION_DTOR, persistent_hashes, 0); if (ce->type == ZEND_INTERNAL_CLASS) { #ifdef ZTS int n = zend_hash_num_elements(CG(class_table)); if (CG(static_members_table) && n >= CG(last_static_member)) { /* Support for run-time declaration: dl() */ CG(last_static_member) = n+1; CG(static_members_table) = realloc(CG(static_members_table), (n+1)*sizeof(zval**)); CG(static_members_table)[n] = NULL; } ce->static_members_table = (zval**)(zend_intptr_t)n; #else ce->static_members_table = NULL; #endif } else { ce->static_members_table = ce->default_static_members_table; ce->info.user.doc_comment = NULL; ce->info.user.doc_comment_len = 0; } ce->default_properties_count = 0; ce->default_static_members_count = 0; if (nullify_handlers) { ce->constructor = NULL; ce->destructor = NULL; ce->clone = NULL; ce->__get = NULL; ce->__set = NULL; ce->__unset = NULL; ce->__isset = NULL; ce->__call = NULL; ce->__callstatic = NULL; ce->__tostring = NULL; ce->create_object = NULL; ce->get_iterator = NULL; ce->iterator_funcs.funcs = NULL; ce->interface_gets_implemented = NULL; ce->get_static_method = NULL; ce->parent = NULL; ce->num_interfaces = 0; ce->interfaces = NULL; ce->num_traits = 0; ce->traits = NULL; ce->trait_aliases = NULL; ce->trait_precedences = NULL; ce->serialize = NULL; ce->unserialize = NULL; ce->serialize_func = NULL; ce->unserialize_func = NULL; if (ce->type == ZEND_INTERNAL_CLASS) { ce->info.internal.module = NULL; ce->info.internal.builtin_functions = NULL; } } } /* }}} */ int zend_get_class_fetch_type(const char *class_name, uint class_name_len) /* {{{ */ { if ((class_name_len == sizeof("self")-1) && !memcmp(class_name, "self", sizeof("self")-1)) { return ZEND_FETCH_CLASS_SELF; } else if ((class_name_len == sizeof("parent")-1) && !memcmp(class_name, "parent", sizeof("parent")-1)) { return ZEND_FETCH_CLASS_PARENT; } else if ((class_name_len == sizeof("static")-1) && !memcmp(class_name, "static", sizeof("static")-1)) { return ZEND_FETCH_CLASS_STATIC; } else { return ZEND_FETCH_CLASS_DEFAULT; } } /* }}} */ ZEND_API const char* zend_get_compiled_variable_name(const zend_op_array *op_array, zend_uint var, int* name_len) /* {{{ */ { if (name_len) { *name_len = op_array->vars[var].name_len; } return op_array->vars[var].name; } /* }}} */ void zend_do_build_namespace_name(znode *result, znode *prefix, znode *name TSRMLS_DC) /* {{{ */ { if (prefix) { *result = *prefix; if (Z_TYPE(result->u.constant) == IS_STRING && Z_STRLEN(result->u.constant) == 0) { /* namespace\ */ if (CG(current_namespace)) { znode tmp; zval_dtor(&result->u.constant); tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); zval_copy_ctor(&tmp.u.constant); zend_do_build_namespace_name(result, NULL, &tmp TSRMLS_CC); } } } else { result->op_type = IS_CONST; Z_TYPE(result->u.constant) = IS_STRING; Z_STRVAL(result->u.constant) = NULL; Z_STRLEN(result->u.constant) = 0; } /* prefix = result */ zend_do_build_full_name(NULL, result, name, 0 TSRMLS_CC); } /* }}} */ void zend_do_begin_namespace(const znode *name, zend_bool with_bracket TSRMLS_DC) /* {{{ */ { char *lcname; /* handle mixed syntax declaration or nested namespaces */ if (!CG(has_bracketed_namespaces)) { if (CG(current_namespace)) { /* previous namespace declarations were unbracketed */ if (with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } } } else { /* previous namespace declarations were bracketed */ if (!with_bracket) { zend_error(E_COMPILE_ERROR, "Cannot mix bracketed namespace declarations with unbracketed namespace declarations"); } else if (CG(current_namespace) || CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "Namespace declarations cannot be nested"); } } if (((!with_bracket && !CG(current_namespace)) || (with_bracket && !CG(has_bracketed_namespaces))) && CG(active_op_array)->last > 0) { /* ignore ZEND_EXT_STMT and ZEND_TICKS */ int num = CG(active_op_array)->last; while (num > 0 && (CG(active_op_array)->opcodes[num-1].opcode == ZEND_EXT_STMT || CG(active_op_array)->opcodes[num-1].opcode == ZEND_TICKS)) { --num; } if (num > 0) { zend_error(E_COMPILE_ERROR, "Namespace declaration statement has to be the very first statement in the script"); } } CG(in_namespace) = 1; if (with_bracket) { CG(has_bracketed_namespaces) = 1; } if (name) { lcname = zend_str_tolower_dup(Z_STRVAL(name->u.constant), Z_STRLEN(name->u.constant)); if (((Z_STRLEN(name->u.constant) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN(name->u.constant) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use '%s' as namespace name", Z_STRVAL(name->u.constant)); } efree(lcname); if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); } else { ALLOC_ZVAL(CG(current_namespace)); } *CG(current_namespace) = name->u.constant; } else { if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } if (CG(doc_comment)) { efree(CG(doc_comment)); CG(doc_comment) = NULL; CG(doc_comment_len) = 0; } } /* }}} */ void zend_do_use(znode *ns_name, znode *new_name, int is_global TSRMLS_DC) /* {{{ */ { char *lcname; zval *name, *ns, tmp; zend_bool warn = 0; zend_class_entry **pce; if (!CG(current_import)) { CG(current_import) = emalloc(sizeof(HashTable)); zend_hash_init(CG(current_import), 0, NULL, ZVAL_PTR_DTOR, 0); } ALLOC_ZVAL(ns); *ns = ns_name->u.constant; if (new_name) { name = &new_name->u.constant; } else { const char *p; /* The form "use A\B" is eqivalent to "use A\B as B". So we extract the last part of compound name to use as a new_name */ name = &tmp; p = zend_memrchr(Z_STRVAL_P(ns), '\\', Z_STRLEN_P(ns)); if (p) { ZVAL_STRING(name, p+1, 1); } else { *name = *ns; zval_copy_ctor(name); warn = !is_global && !CG(current_namespace); } } lcname = zend_str_tolower_dup(Z_STRVAL_P(name), Z_STRLEN_P(name)); if (((Z_STRLEN_P(name) == sizeof("self")-1) && !memcmp(lcname, "self", sizeof("self")-1)) || ((Z_STRLEN_P(name) == sizeof("parent")-1) && !memcmp(lcname, "parent", sizeof("parent")-1))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because '%s' is a special class name", Z_STRVAL_P(ns), Z_STRVAL_P(name), Z_STRVAL_P(name)); } if (CG(current_namespace)) { /* Prefix import name with current namespace name to avoid conflicts with classes */ char *c_ns_name = emalloc(Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) + 1); zend_str_tolower_copy(c_ns_name, Z_STRVAL_P(CG(current_namespace)), Z_STRLEN_P(CG(current_namespace))); c_ns_name[Z_STRLEN_P(CG(current_namespace))] = '\\'; memcpy(c_ns_name+Z_STRLEN_P(CG(current_namespace))+1, lcname, Z_STRLEN_P(name)+1); if (zend_hash_exists(CG(class_table), c_ns_name, Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name)+1)) { char *tmp2 = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(CG(current_namespace)) + 1 + Z_STRLEN_P(name) || memcmp(tmp2, c_ns_name, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(tmp2); } efree(c_ns_name); } else if (zend_hash_find(CG(class_table), lcname, Z_STRLEN_P(name)+1, (void**)&pce) == SUCCESS && (*pce)->type == ZEND_USER_CLASS && (*pce)->info.user.filename == CG(compiled_filename)) { char *c_tmp = zend_str_tolower_dup(Z_STRVAL_P(ns), Z_STRLEN_P(ns)); if (Z_STRLEN_P(ns) != Z_STRLEN_P(name) || memcmp(c_tmp, lcname, Z_STRLEN_P(ns))) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } efree(c_tmp); } if (zend_hash_add(CG(current_import), lcname, Z_STRLEN_P(name)+1, &ns, sizeof(zval*), NULL) != SUCCESS) { zend_error(E_COMPILE_ERROR, "Cannot use %s as %s because the name is already in use", Z_STRVAL_P(ns), Z_STRVAL_P(name)); } if (warn) { if (!strcmp(Z_STRVAL_P(name), "strict")) { zend_error(E_COMPILE_ERROR, "You seem to be trying to use a different language..."); } zend_error(E_WARNING, "The use statement with non-compound name '%s' has no effect", Z_STRVAL_P(name)); } efree(lcname); zval_dtor(name); } /* }}} */ void zend_do_declare_constant(znode *name, znode *value TSRMLS_DC) /* {{{ */ { zend_op *opline; if(Z_TYPE(value->u.constant) == IS_CONSTANT_ARRAY) { zend_error(E_COMPILE_ERROR, "Arrays are not allowed as constants"); } if (zend_get_ct_const(&name->u.constant, 0 TSRMLS_CC)) { zend_error(E_COMPILE_ERROR, "Cannot redeclare constant '%s'", Z_STRVAL(name->u.constant)); } if (CG(current_namespace)) { /* Prefix constant name with name of current namespace, lowercased */ znode tmp; tmp.op_type = IS_CONST; tmp.u.constant = *CG(current_namespace); Z_STRVAL(tmp.u.constant) = zend_str_tolower_dup(Z_STRVAL(tmp.u.constant), Z_STRLEN(tmp.u.constant)); zend_do_build_namespace_name(&tmp, &tmp, name TSRMLS_CC); *name = tmp; } opline = get_next_op(CG(active_op_array) TSRMLS_CC); opline->opcode = ZEND_DECLARE_CONST; SET_UNUSED(opline->result); SET_NODE(opline->op1, name); SET_NODE(opline->op2, value); } /* }}} */ void zend_verify_namespace(TSRMLS_D) /* {{{ */ { if (CG(has_bracketed_namespaces) && !CG(in_namespace)) { zend_error(E_COMPILE_ERROR, "No code may exist outside of namespace {}"); } } /* }}} */ void zend_do_end_namespace(TSRMLS_D) /* {{{ */ { CG(in_namespace) = 0; if (CG(current_namespace)) { zval_dtor(CG(current_namespace)); FREE_ZVAL(CG(current_namespace)); CG(current_namespace) = NULL; } if (CG(current_import)) { zend_hash_destroy(CG(current_import)); efree(CG(current_import)); CG(current_import) = NULL; } } /* }}} */ void zend_do_end_compilation(TSRMLS_D) /* {{{ */ { CG(has_bracketed_namespaces) = 0; zend_do_end_namespace(TSRMLS_C); } /* }}} */ /* {{{ zend_dirname Returns directory name component of path */ ZEND_API size_t zend_dirname(char *path, size_t len) { register char *end = path + len - 1; unsigned int len_adjust = 0; #ifdef PHP_WIN32 /* Note that on Win32 CWD is per drive (heritage from CP/M). * This means dirname("c:foo") maps to "c:." or "c:" - which means CWD on C: drive. */ if ((2 <= len) && isalpha((int)((unsigned char *)path)[0]) && (':' == path[1])) { /* Skip over the drive spec (if any) so as not to change */ path += 2; len_adjust += 2; if (2 == len) { /* Return "c:" on Win32 for dirname("c:"). * It would be more consistent to return "c:." * but that would require making the string *longer*. */ return len; } } #elif defined(NETWARE) /* * Find the first occurence of : from the left * move the path pointer to the position just after : * increment the len_adjust to the length of path till colon character(inclusive) * If there is no character beyond : simple return len */ char *colonpos = NULL; colonpos = strchr(path, ':'); if (colonpos != NULL) { len_adjust = ((colonpos - path) + 1); path += len_adjust; if (len_adjust == len) { return len; } } #endif if (len == 0) { /* Illegal use of this function */ return 0; } /* Strip trailing slashes */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { /* The path only contained slashes */ path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } /* Strip filename */ while (end >= path && !IS_SLASH_P(end)) { end--; } if (end < path) { /* No slash found, therefore return '.' */ #ifdef NETWARE if (len_adjust == 0) { path[0] = '.'; path[1] = '\0'; return 1; /* only one character */ } else { path[0] = '\0'; return len_adjust; } #else path[0] = '.'; path[1] = '\0'; return 1 + len_adjust; #endif } /* Strip slashes which came before the file name */ while (end >= path && IS_SLASH_P(end)) { end--; } if (end < path) { path[0] = DEFAULT_SLASH; path[1] = '\0'; return 1 + len_adjust; } *(end+1) = '\0'; return (size_t)(end + 1 - path) + len_adjust; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-12-17-db63456a8d-3dc9f0abe6.c
manybugs_data_91
#include "Python.h" #include "structmember.h" #if PY_VERSION_HEX < 0x02060000 && !defined(Py_TYPE) #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) #endif #if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN) typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define PyInt_FromSsize_t PyInt_FromLong #define PyInt_AsSsize_t PyInt_AsLong #endif #ifndef Py_IS_FINITE #define Py_IS_FINITE(X) (!Py_IS_INFINITY(X) && !Py_IS_NAN(X)) #endif #ifdef __GNUC__ #define UNUSED __attribute__((__unused__)) #else #define UNUSED #endif #define PyScanner_Check(op) PyObject_TypeCheck(op, &PyScannerType) #define PyScanner_CheckExact(op) (Py_TYPE(op) == &PyScannerType) #define PyEncoder_Check(op) PyObject_TypeCheck(op, &PyEncoderType) #define PyEncoder_CheckExact(op) (Py_TYPE(op) == &PyEncoderType) static PyTypeObject PyScannerType; static PyTypeObject PyEncoderType; typedef struct _PyScannerObject { PyObject_HEAD PyObject *strict; PyObject *object_hook; PyObject *object_pairs_hook; PyObject *parse_float; PyObject *parse_int; PyObject *parse_constant; PyObject *memo; } PyScannerObject; static PyMemberDef scanner_members[] = { {"strict", T_OBJECT, offsetof(PyScannerObject, strict), READONLY, "strict"}, {"object_hook", T_OBJECT, offsetof(PyScannerObject, object_hook), READONLY, "object_hook"}, {"object_pairs_hook", T_OBJECT, offsetof(PyScannerObject, object_pairs_hook), READONLY}, {"parse_float", T_OBJECT, offsetof(PyScannerObject, parse_float), READONLY, "parse_float"}, {"parse_int", T_OBJECT, offsetof(PyScannerObject, parse_int), READONLY, "parse_int"}, {"parse_constant", T_OBJECT, offsetof(PyScannerObject, parse_constant), READONLY, "parse_constant"}, {NULL} }; typedef struct _PyEncoderObject { PyObject_HEAD PyObject *markers; PyObject *defaultfn; PyObject *encoder; PyObject *indent; PyObject *key_separator; PyObject *item_separator; PyObject *sort_keys; PyObject *skipkeys; int fast_encode; int allow_nan; } PyEncoderObject; static PyMemberDef encoder_members[] = { {"markers", T_OBJECT, offsetof(PyEncoderObject, markers), READONLY, "markers"}, {"default", T_OBJECT, offsetof(PyEncoderObject, defaultfn), READONLY, "default"}, {"encoder", T_OBJECT, offsetof(PyEncoderObject, encoder), READONLY, "encoder"}, {"indent", T_OBJECT, offsetof(PyEncoderObject, indent), READONLY, "indent"}, {"key_separator", T_OBJECT, offsetof(PyEncoderObject, key_separator), READONLY, "key_separator"}, {"item_separator", T_OBJECT, offsetof(PyEncoderObject, item_separator), READONLY, "item_separator"}, {"sort_keys", T_OBJECT, offsetof(PyEncoderObject, sort_keys), READONLY, "sort_keys"}, {"skipkeys", T_OBJECT, offsetof(PyEncoderObject, skipkeys), READONLY, "skipkeys"}, {NULL} }; static PyObject * ascii_escape_unicode(PyObject *pystr); static PyObject * py_encode_basestring_ascii(PyObject* self UNUSED, PyObject *pystr); void init_json(void); static PyObject * scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr); static PyObject * _build_rval_index_tuple(PyObject *rval, Py_ssize_t idx); static PyObject * scanner_new(PyTypeObject *type, PyObject *args, PyObject *kwds); static int scanner_init(PyObject *self, PyObject *args, PyObject *kwds); static void scanner_dealloc(PyObject *self); static int scanner_clear(PyObject *self); static PyObject * encoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds); static int encoder_init(PyObject *self, PyObject *args, PyObject *kwds); static void encoder_dealloc(PyObject *self); static int encoder_clear(PyObject *self); static int encoder_listencode_list(PyEncoderObject *s, PyObject *rval, PyObject *seq, Py_ssize_t indent_level); static int encoder_listencode_obj(PyEncoderObject *s, PyObject *rval, PyObject *obj, Py_ssize_t indent_level); static int encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ssize_t indent_level); static PyObject * _encoded_const(PyObject *obj); static void raise_errmsg(char *msg, PyObject *s, Py_ssize_t end); static PyObject * encoder_encode_string(PyEncoderObject *s, PyObject *obj); static int _convertPyInt_AsSsize_t(PyObject *o, Py_ssize_t *size_ptr); static PyObject * _convertPyInt_FromSsize_t(Py_ssize_t *size_ptr); static PyObject * encoder_encode_float(PyEncoderObject *s, PyObject *obj); #define S_CHAR(c) (c >= ' ' && c <= '~' && c != '\\' && c != '"') #define IS_WHITESPACE(c) (((c) == ' ') || ((c) == '\t') || ((c) == '\n') || ((c) == '\r')) #define MIN_EXPANSION 6 #ifdef Py_UNICODE_WIDE #define MAX_EXPANSION (2 * MIN_EXPANSION) #else #define MAX_EXPANSION MIN_EXPANSION #endif static int _convertPyInt_AsSsize_t(PyObject *o, Py_ssize_t *size_ptr) { /* PyObject to Py_ssize_t converter */ *size_ptr = PyLong_AsSsize_t(o); if (*size_ptr == -1 && PyErr_Occurred()) return 0; return 1; } static PyObject * _convertPyInt_FromSsize_t(Py_ssize_t *size_ptr) { /* Py_ssize_t to PyObject converter */ return PyLong_FromSsize_t(*size_ptr); } static Py_ssize_t ascii_escape_unichar(Py_UNICODE c, Py_UNICODE *output, Py_ssize_t chars) { /* Escape unicode code point c to ASCII escape sequences in char *output. output must have at least 12 bytes unused to accommodate an escaped surrogate pair "\uXXXX\uXXXX" */ output[chars++] = '\\'; switch (c) { case '\\': output[chars++] = c; break; case '"': output[chars++] = c; break; case '\b': output[chars++] = 'b'; break; case '\f': output[chars++] = 'f'; break; case '\n': output[chars++] = 'n'; break; case '\r': output[chars++] = 'r'; break; case '\t': output[chars++] = 't'; break; default: #ifdef Py_UNICODE_WIDE if (c >= 0x10000) { /* UTF-16 surrogate pair */ Py_UNICODE v = c - 0x10000; c = 0xd800 | ((v >> 10) & 0x3ff); output[chars++] = 'u'; output[chars++] = "0123456789abcdef"[(c >> 12) & 0xf]; output[chars++] = "0123456789abcdef"[(c >> 8) & 0xf]; output[chars++] = "0123456789abcdef"[(c >> 4) & 0xf]; output[chars++] = "0123456789abcdef"[(c ) & 0xf]; c = 0xdc00 | (v & 0x3ff); output[chars++] = '\\'; } #endif output[chars++] = 'u'; output[chars++] = "0123456789abcdef"[(c >> 12) & 0xf]; output[chars++] = "0123456789abcdef"[(c >> 8) & 0xf]; output[chars++] = "0123456789abcdef"[(c >> 4) & 0xf]; output[chars++] = "0123456789abcdef"[(c ) & 0xf]; } return chars; } static PyObject * ascii_escape_unicode(PyObject *pystr) { /* Take a PyUnicode pystr and return a new ASCII-only escaped PyUnicode */ Py_ssize_t i; Py_ssize_t input_chars; Py_ssize_t output_size; Py_ssize_t max_output_size; Py_ssize_t chars; PyObject *rval; Py_UNICODE *output; Py_UNICODE *input_unicode; input_chars = PyUnicode_GET_SIZE(pystr); input_unicode = PyUnicode_AS_UNICODE(pystr); /* One char input can be up to 6 chars output, estimate 4 of these */ output_size = 2 + (MIN_EXPANSION * 4) + input_chars; max_output_size = 2 + (input_chars * MAX_EXPANSION); rval = PyUnicode_FromStringAndSize(NULL, output_size); if (rval == NULL) { return NULL; } output = PyUnicode_AS_UNICODE(rval); chars = 0; output[chars++] = '"'; for (i = 0; i < input_chars; i++) { Py_UNICODE c = input_unicode[i]; if (S_CHAR(c)) { output[chars++] = c; } else { chars = ascii_escape_unichar(c, output, chars); } if (output_size - chars < (1 + MAX_EXPANSION)) { /* There's more than four, so let's resize by a lot */ Py_ssize_t new_output_size = output_size * 2; /* This is an upper bound */ if (new_output_size > max_output_size) { new_output_size = max_output_size; } /* Make sure that the output size changed before resizing */ if (new_output_size != output_size) { output_size = new_output_size; if (PyUnicode_Resize(&rval, output_size) == -1) { return NULL; } output = PyUnicode_AS_UNICODE(rval); } } } output[chars++] = '"'; if (PyUnicode_Resize(&rval, chars) == -1) { return NULL; } return rval; } static void raise_errmsg(char *msg, PyObject *s, Py_ssize_t end) { /* Use the Python function json.decoder.errmsg to raise a nice looking ValueError exception */ static PyObject *errmsg_fn = NULL; PyObject *pymsg; if (errmsg_fn == NULL) { PyObject *decoder = PyImport_ImportModule("json.decoder"); if (decoder == NULL) return; errmsg_fn = PyObject_GetAttrString(decoder, "errmsg"); Py_DECREF(decoder); if (errmsg_fn == NULL) return; } pymsg = PyObject_CallFunction(errmsg_fn, "(zOO&)", msg, s, _convertPyInt_FromSsize_t, &end); if (pymsg) { PyErr_SetObject(PyExc_ValueError, pymsg); Py_DECREF(pymsg); } } static PyObject * join_list_unicode(PyObject *lst) { /* return u''.join(lst) */ static PyObject *sep = NULL; if (sep == NULL) { sep = PyUnicode_FromStringAndSize("", 0); if (sep == NULL) return NULL; } return PyUnicode_Join(sep, lst); } static PyObject * _build_rval_index_tuple(PyObject *rval, Py_ssize_t idx) { /* return (rval, idx) tuple, stealing reference to rval */ PyObject *tpl; PyObject *pyidx; /* steal a reference to rval, returns (rval, idx) */ if (rval == NULL) { return NULL; } pyidx = PyLong_FromSsize_t(idx); if (pyidx == NULL) { Py_DECREF(rval); return NULL; } tpl = PyTuple_New(2); if (tpl == NULL) { Py_DECREF(pyidx); Py_DECREF(rval); return NULL; } PyTuple_SET_ITEM(tpl, 0, rval); PyTuple_SET_ITEM(tpl, 1, pyidx); return tpl; } #define APPEND_OLD_CHUNK \ if (chunk != NULL) { \ if (chunks == NULL) { \ chunks = PyList_New(0); \ if (chunks == NULL) { \ goto bail; \ } \ } \ if (PyList_Append(chunks, chunk)) { \ Py_DECREF(chunk); \ goto bail; \ } \ Py_CLEAR(chunk); \ } static PyObject * scanstring_unicode(PyObject *pystr, Py_ssize_t end, int strict, Py_ssize_t *next_end_ptr) { /* Read the JSON string from PyUnicode pystr. end is the index of the first character after the quote. if strict is zero then literal control characters are allowed *next_end_ptr is a return-by-reference index of the character after the end quote Return value is a new PyUnicode */ PyObject *rval = NULL; Py_ssize_t len = PyUnicode_GET_SIZE(pystr); Py_ssize_t begin = end - 1; Py_ssize_t next /* = begin */; const Py_UNICODE *buf = PyUnicode_AS_UNICODE(pystr); PyObject *chunks = NULL; PyObject *chunk = NULL; if (end < 0 || len <= end) { PyErr_SetString(PyExc_ValueError, "end is out of bounds"); goto bail; } while (1) { /* Find the end of the string or the next escape */ Py_UNICODE c = 0; for (next = end; next < len; next++) { c = buf[next]; if (c == '"' || c == '\\') { break; } else if (strict && c <= 0x1f) { raise_errmsg("Invalid control character at", pystr, next); goto bail; } } if (!(c == '"' || c == '\\')) { raise_errmsg("Unterminated string starting at", pystr, begin); goto bail; } /* Pick up this chunk if it's not zero length */ if (next != end) { APPEND_OLD_CHUNK chunk = PyUnicode_FromUnicode(&buf[end], next - end); if (chunk == NULL) { goto bail; } } next++; if (c == '"') { end = next; break; } if (next == len) { raise_errmsg("Unterminated string starting at", pystr, begin); goto bail; } c = buf[next]; if (c != 'u') { /* Non-unicode backslash escapes */ end = next + 1; switch (c) { case '"': break; case '\\': break; case '/': break; case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; default: c = 0; } if (c == 0) { raise_errmsg("Invalid \\escape", pystr, end - 2); goto bail; } } else { c = 0; next++; end = next + 4; if (end >= len) { raise_errmsg("Invalid \\uXXXX escape", pystr, next - 1); goto bail; } /* Decode 4 hex digits */ for (; next < end; next++) { Py_UNICODE digit = buf[next]; c <<= 4; switch (digit) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': c |= (digit - '0'); break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': c |= (digit - 'a' + 10); break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': c |= (digit - 'A' + 10); break; default: raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5); goto bail; } } #ifdef Py_UNICODE_WIDE /* Surrogate pair */ if ((c & 0xfc00) == 0xd800) { Py_UNICODE c2 = 0; if (end + 6 >= len) { raise_errmsg("Unpaired high surrogate", pystr, end - 5); goto bail; } if (buf[next++] != '\\' || buf[next++] != 'u') { raise_errmsg("Unpaired high surrogate", pystr, end - 5); goto bail; } end += 6; /* Decode 4 hex digits */ for (; next < end; next++) { Py_UNICODE digit = buf[next]; c2 <<= 4; switch (digit) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': c2 |= (digit - '0'); break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': c2 |= (digit - 'a' + 10); break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': c2 |= (digit - 'A' + 10); break; default: raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5); goto bail; } } if ((c2 & 0xfc00) != 0xdc00) { raise_errmsg("Unpaired high surrogate", pystr, end - 5); goto bail; } c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00)); } else if ((c & 0xfc00) == 0xdc00) { raise_errmsg("Unpaired low surrogate", pystr, end - 5); goto bail; } #endif } APPEND_OLD_CHUNK chunk = PyUnicode_FromUnicode(&c, 1); if (chunk == NULL) { goto bail; } } if (chunks == NULL) { if (chunk != NULL) rval = chunk; else rval = PyUnicode_FromStringAndSize("", 0); } else { APPEND_OLD_CHUNK rval = join_list_unicode(chunks); if (rval == NULL) { goto bail; } Py_CLEAR(chunks); } *next_end_ptr = end; return rval; bail: *next_end_ptr = -1; Py_XDECREF(chunks); Py_XDECREF(chunk); return NULL; } PyDoc_STRVAR(pydoc_scanstring, "scanstring(string, end, strict=True) -> (string, end)\n" "\n" "Scan the string s for a JSON string. End is the index of the\n" "character in s after the quote that started the JSON string.\n" "Unescapes all valid JSON string escape sequences and raises ValueError\n" "on attempt to decode an invalid string. If strict is False then literal\n" "control characters are allowed in the string.\n" "\n" "Returns a tuple of the decoded string and the index of the character in s\n" "after the end quote." ); static PyObject * py_scanstring(PyObject* self UNUSED, PyObject *args) { PyObject *pystr; PyObject *rval; Py_ssize_t end; Py_ssize_t next_end = -1; int strict = 1; if (!PyArg_ParseTuple(args, "OO&|i:scanstring", &pystr, _convertPyInt_AsSsize_t, &end, &strict)) { return NULL; } if (PyUnicode_Check(pystr)) { rval = scanstring_unicode(pystr, end, strict, &next_end); } else { PyErr_Format(PyExc_TypeError, "first argument must be a string, not %.80s", Py_TYPE(pystr)->tp_name); return NULL; } return _build_rval_index_tuple(rval, next_end); } PyDoc_STRVAR(pydoc_encode_basestring_ascii, "encode_basestring_ascii(string) -> string\n" "\n" "Return an ASCII-only JSON representation of a Python string" ); static PyObject * py_encode_basestring_ascii(PyObject* self UNUSED, PyObject *pystr) { PyObject *rval; /* Return an ASCII-only JSON representation of a Python string */ /* METH_O */ if (PyUnicode_Check(pystr)) { rval = ascii_escape_unicode(pystr); } else { PyErr_Format(PyExc_TypeError, "first argument must be a string, not %.80s", Py_TYPE(pystr)->tp_name); return NULL; } return rval; } static void scanner_dealloc(PyObject *self) { /* Deallocate scanner object */ scanner_clear(self); Py_TYPE(self)->tp_free(self); } static int scanner_traverse(PyObject *self, visitproc visit, void *arg) { PyScannerObject *s; assert(PyScanner_Check(self)); s = (PyScannerObject *)self; Py_VISIT(s->strict); Py_VISIT(s->object_hook); Py_VISIT(s->object_pairs_hook); Py_VISIT(s->parse_float); Py_VISIT(s->parse_int); Py_VISIT(s->parse_constant); return 0; } static int scanner_clear(PyObject *self) { PyScannerObject *s; assert(PyScanner_Check(self)); s = (PyScannerObject *)self; Py_CLEAR(s->strict); Py_CLEAR(s->object_hook); Py_CLEAR(s->object_pairs_hook); Py_CLEAR(s->parse_float); Py_CLEAR(s->parse_int); Py_CLEAR(s->parse_constant); Py_CLEAR(s->memo); return 0; } static PyObject * _parse_object_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read a JSON object from PyUnicode pystr. idx is the index of the first character after the opening curly brace. *next_idx_ptr is a return-by-reference index to the first character after the closing curly brace. Returns a new PyObject (usually a dict, but object_hook can change that) */ Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr); Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1; PyObject *val = NULL; PyObject *rval = NULL; PyObject *key = NULL; int strict = PyObject_IsTrue(s->strict); int has_pairs_hook = (s->object_pairs_hook != Py_None); Py_ssize_t next_idx; if (has_pairs_hook) rval = PyList_New(0); else rval = PyDict_New(); if (rval == NULL) return NULL; /* skip whitespace after { */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* only loop if the object is non-empty */ if (idx <= end_idx && str[idx] != '}') { while (idx <= end_idx) { PyObject *memokey; /* read key */ if (str[idx] != '"') { raise_errmsg("Expecting property name", pystr, idx); goto bail; } key = scanstring_unicode(pystr, idx + 1, strict, &next_idx); if (key == NULL) goto bail; memokey = PyDict_GetItem(s->memo, key); if (memokey != NULL) { Py_INCREF(memokey); Py_DECREF(key); key = memokey; } else { if (PyDict_SetItem(s->memo, key, key) < 0) goto bail; } idx = next_idx; /* skip whitespace between key and : delimiter, read :, skip whitespace */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; if (idx > end_idx || str[idx] != ':') { raise_errmsg("Expecting : delimiter", pystr, idx); goto bail; } idx++; while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* read any JSON term */ val = scan_once_unicode(s, pystr, idx, &next_idx); if (val == NULL) goto bail; if (has_pairs_hook) { PyObject *item = PyTuple_Pack(2, key, val); if (item == NULL) goto bail; Py_CLEAR(key); Py_CLEAR(val); if (PyList_Append(rval, item) == -1) { Py_DECREF(item); goto bail; } Py_DECREF(item); } else { if (PyDict_SetItem(rval, key, val) < 0) goto bail; Py_CLEAR(key); Py_CLEAR(val); } idx = next_idx; /* skip whitespace before } or , */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* bail if the object is closed or we didn't get the , delimiter */ if (idx > end_idx) break; if (str[idx] == '}') { break; } else if (str[idx] != ',') { raise_errmsg("Expecting , delimiter", pystr, idx); goto bail; } idx++; /* skip whitespace after , delimiter */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; } } /* verify that idx < end_idx, str[idx] should be '}' */ if (idx > end_idx || str[idx] != '}') { raise_errmsg("Expecting object", pystr, end_idx); goto bail; } *next_idx_ptr = idx + 1; if (has_pairs_hook) { val = PyObject_CallFunctionObjArgs(s->object_pairs_hook, rval, NULL); Py_DECREF(rval); return val; } /* if object_hook is not None: rval = object_hook(rval) */ if (s->object_hook != Py_None) { val = PyObject_CallFunctionObjArgs(s->object_hook, rval, NULL); Py_DECREF(rval); return val; } return rval; bail: Py_XDECREF(key); Py_XDECREF(val); Py_XDECREF(rval); return NULL; } static PyObject * _parse_array_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read a JSON array from PyString pystr. idx is the index of the first character after the opening brace. *next_idx_ptr is a return-by-reference index to the first character after the closing brace. Returns a new PyList */ Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr); Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1; PyObject *val = NULL; PyObject *rval = PyList_New(0); Py_ssize_t next_idx; if (rval == NULL) return NULL; /* skip whitespace after [ */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* only loop if the array is non-empty */ if (idx <= end_idx && str[idx] != ']') { while (idx <= end_idx) { /* read any JSON term */ val = scan_once_unicode(s, pystr, idx, &next_idx); if (val == NULL) goto bail; if (PyList_Append(rval, val) == -1) goto bail; Py_CLEAR(val); idx = next_idx; /* skip whitespace between term and , */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* bail if the array is closed or we didn't get the , delimiter */ if (idx > end_idx) break; if (str[idx] == ']') { break; } else if (str[idx] != ',') { raise_errmsg("Expecting , delimiter", pystr, idx); goto bail; } idx++; /* skip whitespace after , */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; } } /* verify that idx < end_idx, str[idx] should be ']' */ if (idx > end_idx || str[idx] != ']') { raise_errmsg("Expecting object", pystr, end_idx); goto bail; } *next_idx_ptr = idx + 1; return rval; bail: Py_XDECREF(val); Py_DECREF(rval); return NULL; } static PyObject * _parse_constant(PyScannerObject *s, char *constant, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read a JSON constant from PyString pystr. constant is the constant string that was found ("NaN", "Infinity", "-Infinity"). idx is the index of the first character of the constant *next_idx_ptr is a return-by-reference index to the first character after the constant. Returns the result of parse_constant */ PyObject *cstr; PyObject *rval; /* constant is "NaN", "Infinity", or "-Infinity" */ cstr = PyUnicode_InternFromString(constant); if (cstr == NULL) return NULL; /* rval = parse_constant(constant) */ rval = PyObject_CallFunctionObjArgs(s->parse_constant, cstr, NULL); idx += PyUnicode_GET_SIZE(cstr); Py_DECREF(cstr); *next_idx_ptr = idx; return rval; } static PyObject * _match_number_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t start, Py_ssize_t *next_idx_ptr) { /* Read a JSON number from PyUnicode pystr. idx is the index of the first character of the number *next_idx_ptr is a return-by-reference index to the first character after the number. Returns a new PyObject representation of that number: PyInt, PyLong, or PyFloat. May return other types if parse_int or parse_float are set */ Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr); Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1; Py_ssize_t idx = start; int is_float = 0; PyObject *rval; PyObject *numstr = NULL; PyObject *custom_func; /* read a sign if it's there, make sure it's not the end of the string */ if (str[idx] == '-') { idx++; if (idx > end_idx) { PyErr_SetNone(PyExc_StopIteration); return NULL; } } /* read as many integer digits as we find as long as it doesn't start with 0 */ if (str[idx] >= '1' && str[idx] <= '9') { idx++; while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++; } /* if it starts with 0 we only expect one integer digit */ else if (str[idx] == '0') { idx++; } /* no integer digits, error */ else { PyErr_SetNone(PyExc_StopIteration); return NULL; } /* if the next char is '.' followed by a digit then read all float digits */ if (idx < end_idx && str[idx] == '.' && str[idx + 1] >= '0' && str[idx + 1] <= '9') { is_float = 1; idx += 2; while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++; } /* if the next char is 'e' or 'E' then maybe read the exponent (or backtrack) */ if (idx < end_idx && (str[idx] == 'e' || str[idx] == 'E')) { Py_ssize_t e_start = idx; idx++; /* read an exponent sign if present */ if (idx < end_idx && (str[idx] == '-' || str[idx] == '+')) idx++; /* read all digits */ while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++; /* if we got a digit, then parse as float. if not, backtrack */ if (str[idx - 1] >= '0' && str[idx - 1] <= '9') { is_float = 1; } else { idx = e_start; } } if (is_float && s->parse_float != (PyObject *)&PyFloat_Type) custom_func = s->parse_float; else if (!is_float && s->parse_int != (PyObject *) &PyLong_Type) custom_func = s->parse_int; else custom_func = NULL; if (custom_func) { /* copy the section we determined to be a number */ numstr = PyUnicode_FromUnicode(&str[start], idx - start); if (numstr == NULL) return NULL; rval = PyObject_CallFunctionObjArgs(custom_func, numstr, NULL); } else { Py_ssize_t i, n; char *buf; /* Straight conversion to ASCII, to avoid costly conversion of decimal unicode digits (which cannot appear here) */ n = idx - start; numstr = PyBytes_FromStringAndSize(NULL, n); if (numstr == NULL) return NULL; buf = PyBytes_AS_STRING(numstr); for (i = 0; i < n; i++) { buf[i] = (char) str[i + start]; } if (is_float) rval = PyFloat_FromString(numstr); else rval = PyLong_FromString(buf, NULL, 10); } Py_DECREF(numstr); *next_idx_ptr = idx; return rval; } static PyObject * scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read one JSON term (of any kind) from PyUnicode pystr. idx is the index of the first character of the term *next_idx_ptr is a return-by-reference index to the first character after the number. Returns a new PyObject representation of the term. */ PyObject *res; Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr); Py_ssize_t length = PyUnicode_GET_SIZE(pystr); if (idx >= length) { PyErr_SetNone(PyExc_StopIteration); return NULL; } switch (str[idx]) { case '"': /* string */ return scanstring_unicode(pystr, idx + 1, PyObject_IsTrue(s->strict), next_idx_ptr); case '{': /* object */ if (Py_EnterRecursiveCall(" while decoding a JSON object " "from a unicode string")) return NULL; res = _parse_object_unicode(s, pystr, idx + 1, next_idx_ptr); Py_LeaveRecursiveCall(); return res; case '[': /* array */ if (Py_EnterRecursiveCall(" while decoding a JSON array " "from a unicode string")) return NULL; res = _parse_array_unicode(s, pystr, idx + 1, next_idx_ptr); Py_LeaveRecursiveCall(); return res; case 'n': /* null */ if ((idx + 3 < length) && str[idx + 1] == 'u' && str[idx + 2] == 'l' && str[idx + 3] == 'l') { Py_INCREF(Py_None); *next_idx_ptr = idx + 4; return Py_None; } break; case 't': /* true */ if ((idx + 3 < length) && str[idx + 1] == 'r' && str[idx + 2] == 'u' && str[idx + 3] == 'e') { Py_INCREF(Py_True); *next_idx_ptr = idx + 4; return Py_True; } break; case 'f': /* false */ if ((idx + 4 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'l' && str[idx + 3] == 's' && str[idx + 4] == 'e') { Py_INCREF(Py_False); *next_idx_ptr = idx + 5; return Py_False; } break; case 'N': /* NaN */ if ((idx + 2 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'N') { return _parse_constant(s, "NaN", idx, next_idx_ptr); } break; case 'I': /* Infinity */ if ((idx + 7 < length) && str[idx + 1] == 'n' && str[idx + 2] == 'f' && str[idx + 3] == 'i' && str[idx + 4] == 'n' && str[idx + 5] == 'i' && str[idx + 6] == 't' && str[idx + 7] == 'y') { return _parse_constant(s, "Infinity", idx, next_idx_ptr); } break; case '-': /* -Infinity */ if ((idx + 8 < length) && str[idx + 1] == 'I' && str[idx + 2] == 'n' && str[idx + 3] == 'f' && str[idx + 4] == 'i' && str[idx + 5] == 'n' && str[idx + 6] == 'i' && str[idx + 7] == 't' && str[idx + 8] == 'y') { return _parse_constant(s, "-Infinity", idx, next_idx_ptr); } break; } /* Didn't find a string, object, array, or named constant. Look for a number. */ return _match_number_unicode(s, pystr, idx, next_idx_ptr); } static PyObject * scanner_call(PyObject *self, PyObject *args, PyObject *kwds) { /* Python callable interface to scan_once_{str,unicode} */ PyObject *pystr; PyObject *rval; Py_ssize_t idx; Py_ssize_t next_idx = -1; static char *kwlist[] = {"string", "idx", NULL}; PyScannerObject *s; assert(PyScanner_Check(self)); s = (PyScannerObject *)self; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&:scan_once", kwlist, &pystr, _convertPyInt_AsSsize_t, &idx)) return NULL; if (PyUnicode_Check(pystr)) { rval = scan_once_unicode(s, pystr, idx, &next_idx); } else { PyErr_Format(PyExc_TypeError, "first argument must be a string, not %.80s", Py_TYPE(pystr)->tp_name); return NULL; } PyDict_Clear(s->memo); if (rval == NULL) return NULL; return _build_rval_index_tuple(rval, next_idx); } static PyObject * scanner_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyScannerObject *s; s = (PyScannerObject *)type->tp_alloc(type, 0); if (s != NULL) { s->strict = NULL; s->object_hook = NULL; s->object_pairs_hook = NULL; s->parse_float = NULL; s->parse_int = NULL; s->parse_constant = NULL; } return (PyObject *)s; } static int scanner_init(PyObject *self, PyObject *args, PyObject *kwds) { /* Initialize Scanner object */ PyObject *ctx; static char *kwlist[] = {"context", NULL}; PyScannerObject *s; assert(PyScanner_Check(self)); s = (PyScannerObject *)self; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:make_scanner", kwlist, &ctx)) return -1; if (s->memo == NULL) { s->memo = PyDict_New(); if (s->memo == NULL) goto bail; } /* All of these will fail "gracefully" so we don't need to verify them */ s->strict = PyObject_GetAttrString(ctx, "strict"); if (s->strict == NULL) goto bail; s->object_hook = PyObject_GetAttrString(ctx, "object_hook"); if (s->object_hook == NULL) goto bail; s->object_pairs_hook = PyObject_GetAttrString(ctx, "object_pairs_hook"); if (s->object_pairs_hook == NULL) goto bail; s->parse_float = PyObject_GetAttrString(ctx, "parse_float"); if (s->parse_float == NULL) goto bail; s->parse_int = PyObject_GetAttrString(ctx, "parse_int"); if (s->parse_int == NULL) goto bail; s->parse_constant = PyObject_GetAttrString(ctx, "parse_constant"); if (s->parse_constant == NULL) goto bail; return 0; bail: Py_CLEAR(s->strict); Py_CLEAR(s->object_hook); Py_CLEAR(s->object_pairs_hook); Py_CLEAR(s->parse_float); Py_CLEAR(s->parse_int); Py_CLEAR(s->parse_constant); return -1; } PyDoc_STRVAR(scanner_doc, "JSON scanner object"); static PyTypeObject PyScannerType = { PyVarObject_HEAD_INIT(NULL, 0) "_json.Scanner", /* tp_name */ sizeof(PyScannerObject), /* tp_basicsize */ 0, /* tp_itemsize */ scanner_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ scanner_call, /* tp_call */ 0, /* tp_str */ 0,/* PyObject_GenericGetAttr, */ /* tp_getattro */ 0,/* PyObject_GenericSetAttr, */ /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ scanner_doc, /* tp_doc */ scanner_traverse, /* tp_traverse */ scanner_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ scanner_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ scanner_init, /* tp_init */ 0,/* PyType_GenericAlloc, */ /* tp_alloc */ scanner_new, /* tp_new */ 0,/* PyObject_GC_Del, */ /* tp_free */ }; static PyObject * encoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyEncoderObject *s; s = (PyEncoderObject *)type->tp_alloc(type, 0); if (s != NULL) { s->markers = NULL; s->defaultfn = NULL; s->encoder = NULL; s->indent = NULL; s->key_separator = NULL; s->item_separator = NULL; s->sort_keys = NULL; s->skipkeys = NULL; } return (PyObject *)s; } static int encoder_init(PyObject *self, PyObject *args, PyObject *kwds) { /* initialize Encoder object */ static char *kwlist[] = {"markers", "default", "encoder", "indent", "key_separator", "item_separator", "sort_keys", "skipkeys", "allow_nan", NULL}; PyEncoderObject *s; PyObject *markers, *defaultfn, *encoder, *indent, *key_separator; PyObject *item_separator, *sort_keys, *skipkeys, *allow_nan; assert(PyEncoder_Check(self)); s = (PyEncoderObject *)self; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOOOOO:make_encoder", kwlist, &markers, &defaultfn, &encoder, &indent, &key_separator, &item_separator, &sort_keys, &skipkeys, &allow_nan)) return -1; s->markers = markers; s->defaultfn = defaultfn; s->encoder = encoder; s->indent = indent; s->key_separator = key_separator; s->item_separator = item_separator; s->sort_keys = sort_keys; s->skipkeys = skipkeys; s->fast_encode = (PyCFunction_Check(s->encoder) && PyCFunction_GetFunction(s->encoder) == (PyCFunction)py_encode_basestring_ascii); s->allow_nan = PyObject_IsTrue(allow_nan); Py_INCREF(s->markers); Py_INCREF(s->defaultfn); Py_INCREF(s->encoder); Py_INCREF(s->indent); Py_INCREF(s->key_separator); Py_INCREF(s->item_separator); Py_INCREF(s->sort_keys); Py_INCREF(s->skipkeys); return 0; } static PyObject * encoder_call(PyObject *self, PyObject *args, PyObject *kwds) { /* Python callable interface to encode_listencode_obj */ static char *kwlist[] = {"obj", "_current_indent_level", NULL}; PyObject *obj; PyObject *rval; Py_ssize_t indent_level; PyEncoderObject *s; assert(PyEncoder_Check(self)); s = (PyEncoderObject *)self; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&:_iterencode", kwlist, &obj, _convertPyInt_AsSsize_t, &indent_level)) return NULL; rval = PyList_New(0); if (rval == NULL) return NULL; if (encoder_listencode_obj(s, rval, obj, indent_level)) { Py_DECREF(rval); return NULL; } return rval; } static PyObject * _encoded_const(PyObject *obj) { /* Return the JSON string representation of None, True, False */ if (obj == Py_None) { static PyObject *s_null = NULL; if (s_null == NULL) { s_null = PyUnicode_InternFromString("null"); } Py_INCREF(s_null); return s_null; } else if (obj == Py_True) { static PyObject *s_true = NULL; if (s_true == NULL) { s_true = PyUnicode_InternFromString("true"); } Py_INCREF(s_true); return s_true; } else if (obj == Py_False) { static PyObject *s_false = NULL; if (s_false == NULL) { s_false = PyUnicode_InternFromString("false"); } Py_INCREF(s_false); return s_false; } else { PyErr_SetString(PyExc_ValueError, "not a const"); return NULL; } } static PyObject * encoder_encode_float(PyEncoderObject *s, PyObject *obj) { /* Return the JSON representation of a PyFloat */ double i = PyFloat_AS_DOUBLE(obj); if (!Py_IS_FINITE(i)) { if (!s->allow_nan) { PyErr_SetString(PyExc_ValueError, "Out of range float values are not JSON compliant"); return NULL; } if (i > 0) { return PyUnicode_FromString("Infinity"); } else if (i < 0) { return PyUnicode_FromString("-Infinity"); } else { return PyUnicode_FromString("NaN"); } } /* Use a better float format here? */ return PyObject_Repr(obj); } static PyObject * encoder_encode_string(PyEncoderObject *s, PyObject *obj) { /* Return the JSON representation of a string */ if (s->fast_encode) return py_encode_basestring_ascii(NULL, obj); else return PyObject_CallFunctionObjArgs(s->encoder, obj, NULL); } static int _steal_list_append(PyObject *lst, PyObject *stolen) { /* Append stolen and then decrement its reference count */ int rval = PyList_Append(lst, stolen); Py_DECREF(stolen); return rval; } static int encoder_listencode_obj(PyEncoderObject *s, PyObject *rval, PyObject *obj, Py_ssize_t indent_level) { /* Encode Python object obj to a JSON term, rval is a PyList */ PyObject *newobj; int rv; if (obj == Py_None || obj == Py_True || obj == Py_False) { PyObject *cstr = _encoded_const(obj); if (cstr == NULL) return -1; return _steal_list_append(rval, cstr); } else if (PyUnicode_Check(obj)) { PyObject *encoded = encoder_encode_string(s, obj); if (encoded == NULL) return -1; return _steal_list_append(rval, encoded); } else if (PyLong_Check(obj)) { PyObject *encoded = PyObject_Str(obj); if (encoded == NULL) return -1; return _steal_list_append(rval, encoded); } else if (PyFloat_Check(obj)) { PyObject *encoded = encoder_encode_float(s, obj); if (encoded == NULL) return -1; return _steal_list_append(rval, encoded); } else if (PyList_Check(obj) || PyTuple_Check(obj)) { return encoder_listencode_list(s, rval, obj, indent_level); } else if (PyDict_Check(obj)) { return encoder_listencode_dict(s, rval, obj, indent_level); } else { PyObject *ident = NULL; if (s->markers != Py_None) { int has_key; ident = PyLong_FromVoidPtr(obj); if (ident == NULL) return -1; has_key = PyDict_Contains(s->markers, ident); if (has_key) { if (has_key != -1) PyErr_SetString(PyExc_ValueError, "Circular reference detected"); Py_DECREF(ident); return -1; } if (PyDict_SetItem(s->markers, ident, obj)) { Py_DECREF(ident); return -1; } } newobj = PyObject_CallFunctionObjArgs(s->defaultfn, obj, NULL); if (newobj == NULL) { Py_XDECREF(ident); return -1; } rv = encoder_listencode_obj(s, rval, newobj, indent_level); Py_DECREF(newobj); if (rv) { Py_XDECREF(ident); return -1; } if (ident != NULL) { if (PyDict_DelItem(s->markers, ident)) { Py_XDECREF(ident); return -1; } Py_XDECREF(ident); } return rv; } } static int encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ssize_t indent_level) { /* Encode Python dict dct a JSON term, rval is a PyList */ static PyObject *open_dict = NULL; static PyObject *close_dict = NULL; static PyObject *empty_dict = NULL; PyObject *kstr = NULL; PyObject *ident = NULL; PyObject *it = NULL; PyObject *items; PyObject *item = NULL; int skipkeys; Py_ssize_t idx; if (open_dict == NULL || close_dict == NULL || empty_dict == NULL) { open_dict = PyUnicode_InternFromString("{"); close_dict = PyUnicode_InternFromString("}"); empty_dict = PyUnicode_InternFromString("{}"); if (open_dict == NULL || close_dict == NULL || empty_dict == NULL) return -1; } if (Py_SIZE(dct) == 0) return PyList_Append(rval, empty_dict); if (s->markers != Py_None) { int has_key; ident = PyLong_FromVoidPtr(dct); if (ident == NULL) goto bail; has_key = PyDict_Contains(s->markers, ident); if (has_key) { if (has_key != -1) PyErr_SetString(PyExc_ValueError, "Circular reference detected"); goto bail; } if (PyDict_SetItem(s->markers, ident, dct)) { goto bail; } } if (PyList_Append(rval, open_dict)) goto bail; if (s->indent != Py_None) { /* TODO: DOES NOT RUN */ indent_level += 1; /* newline_indent = '\n' + (' ' * (_indent * _current_indent_level)) separator = _item_separator + newline_indent buf += newline_indent */ } if (PyObject_IsTrue(s->sort_keys)) { /* First sort the keys then replace them with (key, value) tuples. */ Py_ssize_t i, nitems; items = PyMapping_Keys(dct); if (items == NULL) goto bail; if (!PyList_Check(items)) { PyErr_SetString(PyExc_ValueError, "keys must return list"); goto bail; } if (PyList_Sort(items) < 0) goto bail; nitems = PyList_GET_SIZE(items); for (i = 0; i < nitems; i++) { PyObject *key, *value; key = PyList_GET_ITEM(items, i); value = PyDict_GetItem(dct, key); item = PyTuple_Pack(2, key, value); if (item == NULL) goto bail; PyList_SET_ITEM(items, i, item); Py_DECREF(key); } } else { items = PyMapping_Items(dct); } if (items == NULL) goto bail; it = PyObject_GetIter(items); Py_DECREF(items); if (it == NULL) goto bail; skipkeys = PyObject_IsTrue(s->skipkeys); idx = 0; while ((item = PyIter_Next(it)) != NULL) { PyObject *encoded, *key, *value; if (!PyTuple_Check(item) || Py_SIZE(item) != 2) { PyErr_SetString(PyExc_ValueError, "items must return 2-tuples"); goto bail; } key = PyTuple_GET_ITEM(item, 0); if (PyUnicode_Check(key)) { Py_INCREF(key); kstr = key; } else if (PyFloat_Check(key)) { kstr = encoder_encode_float(s, key); if (kstr == NULL) goto bail; } else if (key == Py_True || key == Py_False || key == Py_None) { /* This must come before the PyLong_Check because True and False are also 1 and 0.*/ kstr = _encoded_const(key); if (kstr == NULL) goto bail; } else if (PyLong_Check(key)) { kstr = PyObject_Str(key); if (kstr == NULL) goto bail; } else if (skipkeys) { Py_DECREF(item); continue; } else { /* TODO: include repr of key */ PyErr_SetString(PyExc_TypeError, "keys must be a string"); goto bail; } if (idx) { if (PyList_Append(rval, s->item_separator)) goto bail; } encoded = encoder_encode_string(s, kstr); Py_CLEAR(kstr); if (encoded == NULL) goto bail; if (PyList_Append(rval, encoded)) { Py_DECREF(encoded); goto bail; } Py_DECREF(encoded); if (PyList_Append(rval, s->key_separator)) goto bail; value = PyTuple_GET_ITEM(item, 1); if (encoder_listencode_obj(s, rval, value, indent_level)) goto bail; idx += 1; Py_DECREF(item); } if (PyErr_Occurred()) goto bail; Py_CLEAR(it); if (ident != NULL) { if (PyDict_DelItem(s->markers, ident)) goto bail; Py_CLEAR(ident); } /* TODO DOES NOT RUN; dead code if (s->indent != Py_None) { indent_level -= 1; yield '\n' + (' ' * (_indent * _current_indent_level)) }*/ if (PyList_Append(rval, close_dict)) goto bail; return 0; bail: Py_XDECREF(it); Py_XDECREF(item); Py_XDECREF(kstr); Py_XDECREF(ident); return -1; } static int encoder_listencode_list(PyEncoderObject *s, PyObject *rval, PyObject *seq, Py_ssize_t indent_level) { /* Encode Python list seq to a JSON term, rval is a PyList */ static PyObject *open_array = NULL; static PyObject *close_array = NULL; static PyObject *empty_array = NULL; PyObject *ident = NULL; PyObject *s_fast = NULL; Py_ssize_t num_items; PyObject **seq_items; Py_ssize_t i; if (open_array == NULL || close_array == NULL || empty_array == NULL) { open_array = PyUnicode_InternFromString("["); close_array = PyUnicode_InternFromString("]"); empty_array = PyUnicode_InternFromString("[]"); if (open_array == NULL || close_array == NULL || empty_array == NULL) return -1; } ident = NULL; s_fast = PySequence_Fast(seq, "_iterencode_list needs a sequence"); if (s_fast == NULL) return -1; num_items = PySequence_Fast_GET_SIZE(s_fast); if (num_items == 0) { Py_DECREF(s_fast); return PyList_Append(rval, empty_array); } if (s->markers != Py_None) { int has_key; ident = PyLong_FromVoidPtr(seq); if (ident == NULL) goto bail; has_key = PyDict_Contains(s->markers, ident); if (has_key) { if (has_key != -1) PyErr_SetString(PyExc_ValueError, "Circular reference detected"); goto bail; } if (PyDict_SetItem(s->markers, ident, seq)) { goto bail; } } seq_items = PySequence_Fast_ITEMS(s_fast); if (PyList_Append(rval, open_array)) goto bail; if (s->indent != Py_None) { /* TODO: DOES NOT RUN */ indent_level += 1; /* newline_indent = '\n' + (' ' * (_indent * _current_indent_level)) separator = _item_separator + newline_indent buf += newline_indent */ } for (i = 0; i < num_items; i++) { PyObject *obj = seq_items[i]; if (i) { if (PyList_Append(rval, s->item_separator)) goto bail; } if (encoder_listencode_obj(s, rval, obj, indent_level)) goto bail; } if (ident != NULL) { if (PyDict_DelItem(s->markers, ident)) goto bail; Py_CLEAR(ident); } /* TODO: DOES NOT RUN if (s->indent != Py_None) { indent_level -= 1; yield '\n' + (' ' * (_indent * _current_indent_level)) }*/ if (PyList_Append(rval, close_array)) goto bail; Py_DECREF(s_fast); return 0; bail: Py_XDECREF(ident); Py_DECREF(s_fast); return -1; } static void encoder_dealloc(PyObject *self) { /* Deallocate Encoder */ encoder_clear(self); Py_TYPE(self)->tp_free(self); } static int encoder_traverse(PyObject *self, visitproc visit, void *arg) { PyEncoderObject *s; assert(PyEncoder_Check(self)); s = (PyEncoderObject *)self; Py_VISIT(s->markers); Py_VISIT(s->defaultfn); Py_VISIT(s->encoder); Py_VISIT(s->indent); Py_VISIT(s->key_separator); Py_VISIT(s->item_separator); Py_VISIT(s->sort_keys); Py_VISIT(s->skipkeys); return 0; } static int encoder_clear(PyObject *self) { /* Deallocate Encoder */ PyEncoderObject *s; assert(PyEncoder_Check(self)); s = (PyEncoderObject *)self; Py_CLEAR(s->markers); Py_CLEAR(s->defaultfn); Py_CLEAR(s->encoder); Py_CLEAR(s->indent); Py_CLEAR(s->key_separator); Py_CLEAR(s->item_separator); Py_CLEAR(s->sort_keys); Py_CLEAR(s->skipkeys); return 0; } PyDoc_STRVAR(encoder_doc, "_iterencode(obj, _current_indent_level) -> iterable"); static PyTypeObject PyEncoderType = { PyVarObject_HEAD_INIT(NULL, 0) "_json.Encoder", /* tp_name */ sizeof(PyEncoderObject), /* tp_basicsize */ 0, /* tp_itemsize */ encoder_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ encoder_call, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ encoder_doc, /* tp_doc */ encoder_traverse, /* tp_traverse */ encoder_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ encoder_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ encoder_init, /* tp_init */ 0, /* tp_alloc */ encoder_new, /* tp_new */ 0, /* tp_free */ }; static PyMethodDef speedups_methods[] = { {"encode_basestring_ascii", (PyCFunction)py_encode_basestring_ascii, METH_O, pydoc_encode_basestring_ascii}, {"scanstring", (PyCFunction)py_scanstring, METH_VARARGS, pydoc_scanstring}, {NULL, NULL, 0, NULL} }; PyDoc_STRVAR(module_doc, "json speedups\n"); static struct PyModuleDef jsonmodule = { PyModuleDef_HEAD_INIT, "_json", module_doc, -1, speedups_methods, NULL, NULL, NULL, NULL }; PyObject* PyInit__json(void) { PyObject *m = PyModule_Create(&jsonmodule); if (!m) return NULL; PyScannerType.tp_new = PyType_GenericNew; if (PyType_Ready(&PyScannerType) < 0) goto fail; PyEncoderType.tp_new = PyType_GenericNew; if (PyType_Ready(&PyEncoderType) < 0) goto fail; Py_INCREF((PyObject*)&PyScannerType); if (PyModule_AddObject(m, "make_scanner", (PyObject*)&PyScannerType) < 0) { Py_DECREF((PyObject*)&PyScannerType); goto fail; } Py_INCREF((PyObject*)&PyEncoderType); if (PyModule_AddObject(m, "make_encoder", (PyObject*)&PyEncoderType) < 0) { Py_DECREF((PyObject*)&PyEncoderType); goto fail; } return m; fail: Py_DECREF(m); return NULL; } #include "Python.h" #include "structmember.h" #if PY_VERSION_HEX < 0x02060000 && !defined(Py_TYPE) #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) #endif #if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN) typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define PyInt_FromSsize_t PyInt_FromLong #define PyInt_AsSsize_t PyInt_AsLong #endif #ifndef Py_IS_FINITE #define Py_IS_FINITE(X) (!Py_IS_INFINITY(X) && !Py_IS_NAN(X)) #endif #ifdef __GNUC__ #define UNUSED __attribute__((__unused__)) #else #define UNUSED #endif #define PyScanner_Check(op) PyObject_TypeCheck(op, &PyScannerType) #define PyScanner_CheckExact(op) (Py_TYPE(op) == &PyScannerType) #define PyEncoder_Check(op) PyObject_TypeCheck(op, &PyEncoderType) #define PyEncoder_CheckExact(op) (Py_TYPE(op) == &PyEncoderType) static PyTypeObject PyScannerType; static PyTypeObject PyEncoderType; typedef struct _PyScannerObject { PyObject_HEAD PyObject *strict; PyObject *object_hook; PyObject *object_pairs_hook; PyObject *parse_float; PyObject *parse_int; PyObject *parse_constant; PyObject *memo; } PyScannerObject; static PyMemberDef scanner_members[] = { {"strict", T_OBJECT, offsetof(PyScannerObject, strict), READONLY, "strict"}, {"object_hook", T_OBJECT, offsetof(PyScannerObject, object_hook), READONLY, "object_hook"}, {"object_pairs_hook", T_OBJECT, offsetof(PyScannerObject, object_pairs_hook), READONLY}, {"parse_float", T_OBJECT, offsetof(PyScannerObject, parse_float), READONLY, "parse_float"}, {"parse_int", T_OBJECT, offsetof(PyScannerObject, parse_int), READONLY, "parse_int"}, {"parse_constant", T_OBJECT, offsetof(PyScannerObject, parse_constant), READONLY, "parse_constant"}, {NULL} }; typedef struct _PyEncoderObject { PyObject_HEAD PyObject *markers; PyObject *defaultfn; PyObject *encoder; PyObject *indent; PyObject *key_separator; PyObject *item_separator; PyObject *sort_keys; PyObject *skipkeys; int fast_encode; int allow_nan; } PyEncoderObject; static PyMemberDef encoder_members[] = { {"markers", T_OBJECT, offsetof(PyEncoderObject, markers), READONLY, "markers"}, {"default", T_OBJECT, offsetof(PyEncoderObject, defaultfn), READONLY, "default"}, {"encoder", T_OBJECT, offsetof(PyEncoderObject, encoder), READONLY, "encoder"}, {"indent", T_OBJECT, offsetof(PyEncoderObject, indent), READONLY, "indent"}, {"key_separator", T_OBJECT, offsetof(PyEncoderObject, key_separator), READONLY, "key_separator"}, {"item_separator", T_OBJECT, offsetof(PyEncoderObject, item_separator), READONLY, "item_separator"}, {"sort_keys", T_OBJECT, offsetof(PyEncoderObject, sort_keys), READONLY, "sort_keys"}, {"skipkeys", T_OBJECT, offsetof(PyEncoderObject, skipkeys), READONLY, "skipkeys"}, {NULL} }; static PyObject * ascii_escape_unicode(PyObject *pystr); static PyObject * py_encode_basestring_ascii(PyObject* self UNUSED, PyObject *pystr); void init_json(void); static PyObject * scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr); static PyObject * _build_rval_index_tuple(PyObject *rval, Py_ssize_t idx); static PyObject * scanner_new(PyTypeObject *type, PyObject *args, PyObject *kwds); static int scanner_init(PyObject *self, PyObject *args, PyObject *kwds); static void scanner_dealloc(PyObject *self); static int scanner_clear(PyObject *self); static PyObject * encoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds); static int encoder_init(PyObject *self, PyObject *args, PyObject *kwds); static void encoder_dealloc(PyObject *self); static int encoder_clear(PyObject *self); static int encoder_listencode_list(PyEncoderObject *s, PyObject *rval, PyObject *seq, Py_ssize_t indent_level); static int encoder_listencode_obj(PyEncoderObject *s, PyObject *rval, PyObject *obj, Py_ssize_t indent_level); static int encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ssize_t indent_level); static PyObject * _encoded_const(PyObject *obj); static void raise_errmsg(char *msg, PyObject *s, Py_ssize_t end); static PyObject * encoder_encode_string(PyEncoderObject *s, PyObject *obj); static int _convertPyInt_AsSsize_t(PyObject *o, Py_ssize_t *size_ptr); static PyObject * _convertPyInt_FromSsize_t(Py_ssize_t *size_ptr); static PyObject * encoder_encode_float(PyEncoderObject *s, PyObject *obj); #define S_CHAR(c) (c >= ' ' && c <= '~' && c != '\\' && c != '"') #define IS_WHITESPACE(c) (((c) == ' ') || ((c) == '\t') || ((c) == '\n') || ((c) == '\r')) #define MIN_EXPANSION 6 #ifdef Py_UNICODE_WIDE #define MAX_EXPANSION (2 * MIN_EXPANSION) #else #define MAX_EXPANSION MIN_EXPANSION #endif static int _convertPyInt_AsSsize_t(PyObject *o, Py_ssize_t *size_ptr) { /* PyObject to Py_ssize_t converter */ *size_ptr = PyLong_AsSsize_t(o); if (*size_ptr == -1 && PyErr_Occurred()) return 0; return 1; } static PyObject * _convertPyInt_FromSsize_t(Py_ssize_t *size_ptr) { /* Py_ssize_t to PyObject converter */ return PyLong_FromSsize_t(*size_ptr); } static Py_ssize_t ascii_escape_unichar(Py_UNICODE c, Py_UNICODE *output, Py_ssize_t chars) { /* Escape unicode code point c to ASCII escape sequences in char *output. output must have at least 12 bytes unused to accommodate an escaped surrogate pair "\uXXXX\uXXXX" */ output[chars++] = '\\'; switch (c) { case '\\': output[chars++] = c; break; case '"': output[chars++] = c; break; case '\b': output[chars++] = 'b'; break; case '\f': output[chars++] = 'f'; break; case '\n': output[chars++] = 'n'; break; case '\r': output[chars++] = 'r'; break; case '\t': output[chars++] = 't'; break; default: #ifdef Py_UNICODE_WIDE if (c >= 0x10000) { /* UTF-16 surrogate pair */ Py_UNICODE v = c - 0x10000; c = 0xd800 | ((v >> 10) & 0x3ff); output[chars++] = 'u'; output[chars++] = "0123456789abcdef"[(c >> 12) & 0xf]; output[chars++] = "0123456789abcdef"[(c >> 8) & 0xf]; output[chars++] = "0123456789abcdef"[(c >> 4) & 0xf]; output[chars++] = "0123456789abcdef"[(c ) & 0xf]; c = 0xdc00 | (v & 0x3ff); output[chars++] = '\\'; } #endif output[chars++] = 'u'; output[chars++] = "0123456789abcdef"[(c >> 12) & 0xf]; output[chars++] = "0123456789abcdef"[(c >> 8) & 0xf]; output[chars++] = "0123456789abcdef"[(c >> 4) & 0xf]; output[chars++] = "0123456789abcdef"[(c ) & 0xf]; } return chars; } static PyObject * ascii_escape_unicode(PyObject *pystr) { /* Take a PyUnicode pystr and return a new ASCII-only escaped PyUnicode */ Py_ssize_t i; Py_ssize_t input_chars; Py_ssize_t output_size; Py_ssize_t max_output_size; Py_ssize_t chars; PyObject *rval; Py_UNICODE *output; Py_UNICODE *input_unicode; input_chars = PyUnicode_GET_SIZE(pystr); input_unicode = PyUnicode_AS_UNICODE(pystr); /* One char input can be up to 6 chars output, estimate 4 of these */ output_size = 2 + (MIN_EXPANSION * 4) + input_chars; max_output_size = 2 + (input_chars * MAX_EXPANSION); rval = PyUnicode_FromStringAndSize(NULL, output_size); if (rval == NULL) { return NULL; } output = PyUnicode_AS_UNICODE(rval); chars = 0; output[chars++] = '"'; for (i = 0; i < input_chars; i++) { Py_UNICODE c = input_unicode[i]; if (S_CHAR(c)) { output[chars++] = c; } else { chars = ascii_escape_unichar(c, output, chars); } if (output_size - chars < (1 + MAX_EXPANSION)) { /* There's more than four, so let's resize by a lot */ Py_ssize_t new_output_size = output_size * 2; /* This is an upper bound */ if (new_output_size > max_output_size) { new_output_size = max_output_size; } /* Make sure that the output size changed before resizing */ if (new_output_size != output_size) { output_size = new_output_size; if (PyUnicode_Resize(&rval, output_size) == -1) { return NULL; } output = PyUnicode_AS_UNICODE(rval); } } } output[chars++] = '"'; if (PyUnicode_Resize(&rval, chars) == -1) { return NULL; } return rval; } static void raise_errmsg(char *msg, PyObject *s, Py_ssize_t end) { /* Use the Python function json.decoder.errmsg to raise a nice looking ValueError exception */ static PyObject *errmsg_fn = NULL; PyObject *pymsg; if (errmsg_fn == NULL) { PyObject *decoder = PyImport_ImportModule("json.decoder"); if (decoder == NULL) return; errmsg_fn = PyObject_GetAttrString(decoder, "errmsg"); Py_DECREF(decoder); if (errmsg_fn == NULL) return; } pymsg = PyObject_CallFunction(errmsg_fn, "(zOO&)", msg, s, _convertPyInt_FromSsize_t, &end); if (pymsg) { PyErr_SetObject(PyExc_ValueError, pymsg); Py_DECREF(pymsg); } } static PyObject * join_list_unicode(PyObject *lst) { /* return u''.join(lst) */ static PyObject *sep = NULL; if (sep == NULL) { sep = PyUnicode_FromStringAndSize("", 0); if (sep == NULL) return NULL; } return PyUnicode_Join(sep, lst); } static PyObject * _build_rval_index_tuple(PyObject *rval, Py_ssize_t idx) { /* return (rval, idx) tuple, stealing reference to rval */ PyObject *tpl; PyObject *pyidx; /* steal a reference to rval, returns (rval, idx) */ if (rval == NULL) { return NULL; } pyidx = PyLong_FromSsize_t(idx); if (pyidx == NULL) { Py_DECREF(rval); return NULL; } tpl = PyTuple_New(2); if (tpl == NULL) { Py_DECREF(pyidx); Py_DECREF(rval); return NULL; } PyTuple_SET_ITEM(tpl, 0, rval); PyTuple_SET_ITEM(tpl, 1, pyidx); return tpl; } #define APPEND_OLD_CHUNK \ if (chunk != NULL) { \ if (chunks == NULL) { \ chunks = PyList_New(0); \ if (chunks == NULL) { \ goto bail; \ } \ } \ if (PyList_Append(chunks, chunk)) { \ Py_DECREF(chunk); \ goto bail; \ } \ Py_CLEAR(chunk); \ } static PyObject * scanstring_unicode(PyObject *pystr, Py_ssize_t end, int strict, Py_ssize_t *next_end_ptr) { /* Read the JSON string from PyUnicode pystr. end is the index of the first character after the quote. if strict is zero then literal control characters are allowed *next_end_ptr is a return-by-reference index of the character after the end quote Return value is a new PyUnicode */ PyObject *rval = NULL; Py_ssize_t len = PyUnicode_GET_SIZE(pystr); Py_ssize_t begin = end - 1; Py_ssize_t next /* = begin */; const Py_UNICODE *buf = PyUnicode_AS_UNICODE(pystr); PyObject *chunks = NULL; PyObject *chunk = NULL; if (end < 0 || len <= end) { PyErr_SetString(PyExc_ValueError, "end is out of bounds"); goto bail; } while (1) { /* Find the end of the string or the next escape */ Py_UNICODE c = 0; for (next = end; next < len; next++) { c = buf[next]; if (c == '"' || c == '\\') { break; } else if (strict && c <= 0x1f) { raise_errmsg("Invalid control character at", pystr, next); goto bail; } } if (!(c == '"' || c == '\\')) { raise_errmsg("Unterminated string starting at", pystr, begin); goto bail; } /* Pick up this chunk if it's not zero length */ if (next != end) { APPEND_OLD_CHUNK chunk = PyUnicode_FromUnicode(&buf[end], next - end); if (chunk == NULL) { goto bail; } } next++; if (c == '"') { end = next; break; } if (next == len) { raise_errmsg("Unterminated string starting at", pystr, begin); goto bail; } c = buf[next]; if (c != 'u') { /* Non-unicode backslash escapes */ end = next + 1; switch (c) { case '"': break; case '\\': break; case '/': break; case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; default: c = 0; } if (c == 0) { raise_errmsg("Invalid \\escape", pystr, end - 2); goto bail; } } else { c = 0; next++; end = next + 4; if (end >= len) { raise_errmsg("Invalid \\uXXXX escape", pystr, next - 1); goto bail; } /* Decode 4 hex digits */ for (; next < end; next++) { Py_UNICODE digit = buf[next]; c <<= 4; switch (digit) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': c |= (digit - '0'); break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': c |= (digit - 'a' + 10); break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': c |= (digit - 'A' + 10); break; default: raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5); goto bail; } } #ifdef Py_UNICODE_WIDE /* Surrogate pair */ if ((c & 0xfc00) == 0xd800) { Py_UNICODE c2 = 0; if (end + 6 >= len) { raise_errmsg("Unpaired high surrogate", pystr, end - 5); goto bail; } if (buf[next++] != '\\' || buf[next++] != 'u') { raise_errmsg("Unpaired high surrogate", pystr, end - 5); goto bail; } end += 6; /* Decode 4 hex digits */ for (; next < end; next++) { Py_UNICODE digit = buf[next]; c2 <<= 4; switch (digit) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': c2 |= (digit - '0'); break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': c2 |= (digit - 'a' + 10); break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': c2 |= (digit - 'A' + 10); break; default: raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5); goto bail; } } if ((c2 & 0xfc00) != 0xdc00) { raise_errmsg("Unpaired high surrogate", pystr, end - 5); goto bail; } c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00)); } else if ((c & 0xfc00) == 0xdc00) { raise_errmsg("Unpaired low surrogate", pystr, end - 5); goto bail; } #endif } APPEND_OLD_CHUNK chunk = PyUnicode_FromUnicode(&c, 1); if (chunk == NULL) { goto bail; } } if (chunks == NULL) { if (chunk != NULL) rval = chunk; else rval = PyUnicode_FromStringAndSize("", 0); } else { APPEND_OLD_CHUNK rval = join_list_unicode(chunks); if (rval == NULL) { goto bail; } Py_CLEAR(chunks); } *next_end_ptr = end; return rval; bail: *next_end_ptr = -1; Py_XDECREF(chunks); Py_XDECREF(chunk); return NULL; } PyDoc_STRVAR(pydoc_scanstring, "scanstring(string, end, strict=True) -> (string, end)\n" "\n" "Scan the string s for a JSON string. End is the index of the\n" "character in s after the quote that started the JSON string.\n" "Unescapes all valid JSON string escape sequences and raises ValueError\n" "on attempt to decode an invalid string. If strict is False then literal\n" "control characters are allowed in the string.\n" "\n" "Returns a tuple of the decoded string and the index of the character in s\n" "after the end quote." ); static PyObject * py_scanstring(PyObject* self UNUSED, PyObject *args) { PyObject *pystr; PyObject *rval; Py_ssize_t end; Py_ssize_t next_end = -1; int strict = 1; if (!PyArg_ParseTuple(args, "OO&|i:scanstring", &pystr, _convertPyInt_AsSsize_t, &end, &strict)) { return NULL; } if (PyUnicode_Check(pystr)) { rval = scanstring_unicode(pystr, end, strict, &next_end); } else { PyErr_Format(PyExc_TypeError, "first argument must be a string, not %.80s", Py_TYPE(pystr)->tp_name); return NULL; } return _build_rval_index_tuple(rval, next_end); } PyDoc_STRVAR(pydoc_encode_basestring_ascii, "encode_basestring_ascii(string) -> string\n" "\n" "Return an ASCII-only JSON representation of a Python string" ); static PyObject * py_encode_basestring_ascii(PyObject* self UNUSED, PyObject *pystr) { PyObject *rval; /* Return an ASCII-only JSON representation of a Python string */ /* METH_O */ if (PyUnicode_Check(pystr)) { rval = ascii_escape_unicode(pystr); } else { PyErr_Format(PyExc_TypeError, "first argument must be a string, not %.80s", Py_TYPE(pystr)->tp_name); return NULL; } return rval; } static void scanner_dealloc(PyObject *self) { /* Deallocate scanner object */ scanner_clear(self); Py_TYPE(self)->tp_free(self); } static int scanner_traverse(PyObject *self, visitproc visit, void *arg) { PyScannerObject *s; assert(PyScanner_Check(self)); s = (PyScannerObject *)self; Py_VISIT(s->strict); Py_VISIT(s->object_hook); Py_VISIT(s->object_pairs_hook); Py_VISIT(s->parse_float); Py_VISIT(s->parse_int); Py_VISIT(s->parse_constant); return 0; } static int scanner_clear(PyObject *self) { PyScannerObject *s; assert(PyScanner_Check(self)); s = (PyScannerObject *)self; Py_CLEAR(s->strict); Py_CLEAR(s->object_hook); Py_CLEAR(s->object_pairs_hook); Py_CLEAR(s->parse_float); Py_CLEAR(s->parse_int); Py_CLEAR(s->parse_constant); Py_CLEAR(s->memo); return 0; } static PyObject * _parse_object_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read a JSON object from PyUnicode pystr. idx is the index of the first character after the opening curly brace. *next_idx_ptr is a return-by-reference index to the first character after the closing curly brace. Returns a new PyObject (usually a dict, but object_hook can change that) */ Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr); Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1; PyObject *val = NULL; PyObject *rval = NULL; PyObject *key = NULL; int strict = PyObject_IsTrue(s->strict); int has_pairs_hook = (s->object_pairs_hook != Py_None); Py_ssize_t next_idx; if (has_pairs_hook) rval = PyList_New(0); else rval = PyDict_New(); if (rval == NULL) return NULL; /* skip whitespace after { */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* only loop if the object is non-empty */ if (idx <= end_idx && str[idx] != '}') { while (idx <= end_idx) { PyObject *memokey; /* read key */ if (str[idx] != '"') { raise_errmsg("Expecting property name", pystr, idx); goto bail; } key = scanstring_unicode(pystr, idx + 1, strict, &next_idx); if (key == NULL) goto bail; memokey = PyDict_GetItem(s->memo, key); if (memokey != NULL) { Py_INCREF(memokey); Py_DECREF(key); key = memokey; } else { if (PyDict_SetItem(s->memo, key, key) < 0) goto bail; } idx = next_idx; /* skip whitespace between key and : delimiter, read :, skip whitespace */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; if (idx > end_idx || str[idx] != ':') { raise_errmsg("Expecting : delimiter", pystr, idx); goto bail; } idx++; while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* read any JSON term */ val = scan_once_unicode(s, pystr, idx, &next_idx); if (val == NULL) goto bail; if (has_pairs_hook) { PyObject *item = PyTuple_Pack(2, key, val); if (item == NULL) goto bail; Py_CLEAR(key); Py_CLEAR(val); if (PyList_Append(rval, item) == -1) { Py_DECREF(item); goto bail; } Py_DECREF(item); } else { if (PyDict_SetItem(rval, key, val) < 0) goto bail; Py_CLEAR(key); Py_CLEAR(val); } idx = next_idx; /* skip whitespace before } or , */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* bail if the object is closed or we didn't get the , delimiter */ if (idx > end_idx) break; if (str[idx] == '}') { break; } else if (str[idx] != ',') { raise_errmsg("Expecting , delimiter", pystr, idx); goto bail; } idx++; /* skip whitespace after , delimiter */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; } } /* verify that idx < end_idx, str[idx] should be '}' */ if (idx > end_idx || str[idx] != '}') { raise_errmsg("Expecting object", pystr, end_idx); goto bail; } *next_idx_ptr = idx + 1; if (has_pairs_hook) { val = PyObject_CallFunctionObjArgs(s->object_pairs_hook, rval, NULL); Py_DECREF(rval); return val; } /* if object_hook is not None: rval = object_hook(rval) */ if (s->object_hook != Py_None) { val = PyObject_CallFunctionObjArgs(s->object_hook, rval, NULL); Py_DECREF(rval); return val; } return rval; bail: Py_XDECREF(key); Py_XDECREF(val); Py_XDECREF(rval); return NULL; } static PyObject * _parse_array_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read a JSON array from PyString pystr. idx is the index of the first character after the opening brace. *next_idx_ptr is a return-by-reference index to the first character after the closing brace. Returns a new PyList */ Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr); Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1; PyObject *val = NULL; PyObject *rval = PyList_New(0); Py_ssize_t next_idx; if (rval == NULL) return NULL; /* skip whitespace after [ */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* only loop if the array is non-empty */ if (idx <= end_idx && str[idx] != ']') { while (idx <= end_idx) { /* read any JSON term */ val = scan_once_unicode(s, pystr, idx, &next_idx); if (val == NULL) goto bail; if (PyList_Append(rval, val) == -1) goto bail; Py_CLEAR(val); idx = next_idx; /* skip whitespace between term and , */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; /* bail if the array is closed or we didn't get the , delimiter */ if (idx > end_idx) break; if (str[idx] == ']') { break; } else if (str[idx] != ',') { raise_errmsg("Expecting , delimiter", pystr, idx); goto bail; } idx++; /* skip whitespace after , */ while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++; } } /* verify that idx < end_idx, str[idx] should be ']' */ if (idx > end_idx || str[idx] != ']') { raise_errmsg("Expecting object", pystr, end_idx); goto bail; } *next_idx_ptr = idx + 1; return rval; bail: Py_XDECREF(val); Py_DECREF(rval); return NULL; } static PyObject * _parse_constant(PyScannerObject *s, char *constant, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read a JSON constant from PyString pystr. constant is the constant string that was found ("NaN", "Infinity", "-Infinity"). idx is the index of the first character of the constant *next_idx_ptr is a return-by-reference index to the first character after the constant. Returns the result of parse_constant */ PyObject *cstr; PyObject *rval; /* constant is "NaN", "Infinity", or "-Infinity" */ cstr = PyUnicode_InternFromString(constant); if (cstr == NULL) return NULL; /* rval = parse_constant(constant) */ rval = PyObject_CallFunctionObjArgs(s->parse_constant, cstr, NULL); idx += PyUnicode_GET_SIZE(cstr); Py_DECREF(cstr); *next_idx_ptr = idx; return rval; } static PyObject * _match_number_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t start, Py_ssize_t *next_idx_ptr) { /* Read a JSON number from PyUnicode pystr. idx is the index of the first character of the number *next_idx_ptr is a return-by-reference index to the first character after the number. Returns a new PyObject representation of that number: PyInt, PyLong, or PyFloat. May return other types if parse_int or parse_float are set */ Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr); Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1; Py_ssize_t idx = start; int is_float = 0; PyObject *rval; PyObject *numstr = NULL; PyObject *custom_func; /* read a sign if it's there, make sure it's not the end of the string */ if (str[idx] == '-') { idx++; if (idx > end_idx) { PyErr_SetNone(PyExc_StopIteration); return NULL; } } /* read as many integer digits as we find as long as it doesn't start with 0 */ if (str[idx] >= '1' && str[idx] <= '9') { idx++; while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++; } /* if it starts with 0 we only expect one integer digit */ else if (str[idx] == '0') { idx++; } /* no integer digits, error */ else { PyErr_SetNone(PyExc_StopIteration); return NULL; } /* if the next char is '.' followed by a digit then read all float digits */ if (idx < end_idx && str[idx] == '.' && str[idx + 1] >= '0' && str[idx + 1] <= '9') { is_float = 1; idx += 2; while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++; } /* if the next char is 'e' or 'E' then maybe read the exponent (or backtrack) */ if (idx < end_idx && (str[idx] == 'e' || str[idx] == 'E')) { Py_ssize_t e_start = idx; idx++; /* read an exponent sign if present */ if (idx < end_idx && (str[idx] == '-' || str[idx] == '+')) idx++; /* read all digits */ while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++; /* if we got a digit, then parse as float. if not, backtrack */ if (str[idx - 1] >= '0' && str[idx - 1] <= '9') { is_float = 1; } else { idx = e_start; } } if (is_float && s->parse_float != (PyObject *)&PyFloat_Type) custom_func = s->parse_float; else if (!is_float && s->parse_int != (PyObject *) &PyLong_Type) custom_func = s->parse_int; else custom_func = NULL; if (custom_func) { /* copy the section we determined to be a number */ numstr = PyUnicode_FromUnicode(&str[start], idx - start); if (numstr == NULL) return NULL; rval = PyObject_CallFunctionObjArgs(custom_func, numstr, NULL); } else { Py_ssize_t i, n; char *buf; /* Straight conversion to ASCII, to avoid costly conversion of decimal unicode digits (which cannot appear here) */ n = idx - start; numstr = PyBytes_FromStringAndSize(NULL, n); if (numstr == NULL) return NULL; buf = PyBytes_AS_STRING(numstr); for (i = 0; i < n; i++) { buf[i] = (char) str[i + start]; } if (is_float) rval = PyFloat_FromString(numstr); else rval = PyLong_FromString(buf, NULL, 10); } Py_DECREF(numstr); *next_idx_ptr = idx; return rval; } static PyObject * scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) { /* Read one JSON term (of any kind) from PyUnicode pystr. idx is the index of the first character of the term *next_idx_ptr is a return-by-reference index to the first character after the number. Returns a new PyObject representation of the term. */ PyObject *res; Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr); Py_ssize_t length = PyUnicode_GET_SIZE(pystr); if (idx >= length) { PyErr_SetNone(PyExc_StopIteration); return NULL; } switch (str[idx]) { case '"': /* string */ return scanstring_unicode(pystr, idx + 1, PyObject_IsTrue(s->strict), next_idx_ptr); case '{': /* object */ if (Py_EnterRecursiveCall(" while decoding a JSON object " "from a unicode string")) return NULL; res = _parse_object_unicode(s, pystr, idx + 1, next_idx_ptr); Py_LeaveRecursiveCall(); return res; case '[': /* array */ if (Py_EnterRecursiveCall(" while decoding a JSON array " "from a unicode string")) return NULL; res = _parse_array_unicode(s, pystr, idx + 1, next_idx_ptr); Py_LeaveRecursiveCall(); return res; case 'n': /* null */ if ((idx + 3 < length) && str[idx + 1] == 'u' && str[idx + 2] == 'l' && str[idx + 3] == 'l') { Py_INCREF(Py_None); *next_idx_ptr = idx + 4; return Py_None; } break; case 't': /* true */ if ((idx + 3 < length) && str[idx + 1] == 'r' && str[idx + 2] == 'u' && str[idx + 3] == 'e') { Py_INCREF(Py_True); *next_idx_ptr = idx + 4; return Py_True; } break; case 'f': /* false */ if ((idx + 4 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'l' && str[idx + 3] == 's' && str[idx + 4] == 'e') { Py_INCREF(Py_False); *next_idx_ptr = idx + 5; return Py_False; } break; case 'N': /* NaN */ if ((idx + 2 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'N') { return _parse_constant(s, "NaN", idx, next_idx_ptr); } break; case 'I': /* Infinity */ if ((idx + 7 < length) && str[idx + 1] == 'n' && str[idx + 2] == 'f' && str[idx + 3] == 'i' && str[idx + 4] == 'n' && str[idx + 5] == 'i' && str[idx + 6] == 't' && str[idx + 7] == 'y') { return _parse_constant(s, "Infinity", idx, next_idx_ptr); } break; case '-': /* -Infinity */ if ((idx + 8 < length) && str[idx + 1] == 'I' && str[idx + 2] == 'n' && str[idx + 3] == 'f' && str[idx + 4] == 'i' && str[idx + 5] == 'n' && str[idx + 6] == 'i' && str[idx + 7] == 't' && str[idx + 8] == 'y') { return _parse_constant(s, "-Infinity", idx, next_idx_ptr); } break; } /* Didn't find a string, object, array, or named constant. Look for a number. */ return _match_number_unicode(s, pystr, idx, next_idx_ptr); } static PyObject * scanner_call(PyObject *self, PyObject *args, PyObject *kwds) { /* Python callable interface to scan_once_{str,unicode} */ PyObject *pystr; PyObject *rval; Py_ssize_t idx; Py_ssize_t next_idx = -1; static char *kwlist[] = {"string", "idx", NULL}; PyScannerObject *s; assert(PyScanner_Check(self)); s = (PyScannerObject *)self; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&:scan_once", kwlist, &pystr, _convertPyInt_AsSsize_t, &idx)) return NULL; if (PyUnicode_Check(pystr)) { rval = scan_once_unicode(s, pystr, idx, &next_idx); } else { PyErr_Format(PyExc_TypeError, "first argument must be a string, not %.80s", Py_TYPE(pystr)->tp_name); return NULL; } PyDict_Clear(s->memo); if (rval == NULL) return NULL; return _build_rval_index_tuple(rval, next_idx); } static PyObject * scanner_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyScannerObject *s; s = (PyScannerObject *)type->tp_alloc(type, 0); if (s != NULL) { s->strict = NULL; s->object_hook = NULL; s->object_pairs_hook = NULL; s->parse_float = NULL; s->parse_int = NULL; s->parse_constant = NULL; } return (PyObject *)s; } static int scanner_init(PyObject *self, PyObject *args, PyObject *kwds) { /* Initialize Scanner object */ PyObject *ctx; static char *kwlist[] = {"context", NULL}; PyScannerObject *s; assert(PyScanner_Check(self)); s = (PyScannerObject *)self; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:make_scanner", kwlist, &ctx)) return -1; if (s->memo == NULL) { s->memo = PyDict_New(); if (s->memo == NULL) goto bail; } /* All of these will fail "gracefully" so we don't need to verify them */ s->strict = PyObject_GetAttrString(ctx, "strict"); if (s->strict == NULL) goto bail; s->object_hook = PyObject_GetAttrString(ctx, "object_hook"); if (s->object_hook == NULL) goto bail; s->object_pairs_hook = PyObject_GetAttrString(ctx, "object_pairs_hook"); if (s->object_pairs_hook == NULL) goto bail; s->parse_float = PyObject_GetAttrString(ctx, "parse_float"); if (s->parse_float == NULL) goto bail; s->parse_int = PyObject_GetAttrString(ctx, "parse_int"); if (s->parse_int == NULL) goto bail; s->parse_constant = PyObject_GetAttrString(ctx, "parse_constant"); if (s->parse_constant == NULL) goto bail; return 0; bail: Py_CLEAR(s->strict); Py_CLEAR(s->object_hook); Py_CLEAR(s->object_pairs_hook); Py_CLEAR(s->parse_float); Py_CLEAR(s->parse_int); Py_CLEAR(s->parse_constant); return -1; } PyDoc_STRVAR(scanner_doc, "JSON scanner object"); static PyTypeObject PyScannerType = { PyVarObject_HEAD_INIT(NULL, 0) "_json.Scanner", /* tp_name */ sizeof(PyScannerObject), /* tp_basicsize */ 0, /* tp_itemsize */ scanner_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ scanner_call, /* tp_call */ 0, /* tp_str */ 0,/* PyObject_GenericGetAttr, */ /* tp_getattro */ 0,/* PyObject_GenericSetAttr, */ /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ scanner_doc, /* tp_doc */ scanner_traverse, /* tp_traverse */ scanner_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ scanner_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ scanner_init, /* tp_init */ 0,/* PyType_GenericAlloc, */ /* tp_alloc */ scanner_new, /* tp_new */ 0,/* PyObject_GC_Del, */ /* tp_free */ }; static PyObject * encoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyEncoderObject *s; s = (PyEncoderObject *)type->tp_alloc(type, 0); if (s != NULL) { s->markers = NULL; s->defaultfn = NULL; s->encoder = NULL; s->indent = NULL; s->key_separator = NULL; s->item_separator = NULL; s->sort_keys = NULL; s->skipkeys = NULL; } return (PyObject *)s; } static int encoder_init(PyObject *self, PyObject *args, PyObject *kwds) { /* initialize Encoder object */ static char *kwlist[] = {"markers", "default", "encoder", "indent", "key_separator", "item_separator", "sort_keys", "skipkeys", "allow_nan", NULL}; PyEncoderObject *s; PyObject *markers, *defaultfn, *encoder, *indent, *key_separator; PyObject *item_separator, *sort_keys, *skipkeys, *allow_nan; assert(PyEncoder_Check(self)); s = (PyEncoderObject *)self; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOOOOO:make_encoder", kwlist, &markers, &defaultfn, &encoder, &indent, &key_separator, &item_separator, &sort_keys, &skipkeys, &allow_nan)) return -1; s->markers = markers; s->defaultfn = defaultfn; s->encoder = encoder; s->indent = indent; s->key_separator = key_separator; s->item_separator = item_separator; s->sort_keys = sort_keys; s->skipkeys = skipkeys; s->fast_encode = (PyCFunction_Check(s->encoder) && PyCFunction_GetFunction(s->encoder) == (PyCFunction)py_encode_basestring_ascii); s->allow_nan = PyObject_IsTrue(allow_nan); Py_INCREF(s->markers); Py_INCREF(s->defaultfn); Py_INCREF(s->encoder); Py_INCREF(s->indent); Py_INCREF(s->key_separator); Py_INCREF(s->item_separator); Py_INCREF(s->sort_keys); Py_INCREF(s->skipkeys); return 0; } static PyObject * encoder_call(PyObject *self, PyObject *args, PyObject *kwds) { /* Python callable interface to encode_listencode_obj */ static char *kwlist[] = {"obj", "_current_indent_level", NULL}; PyObject *obj; PyObject *rval; Py_ssize_t indent_level; PyEncoderObject *s; assert(PyEncoder_Check(self)); s = (PyEncoderObject *)self; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&:_iterencode", kwlist, &obj, _convertPyInt_AsSsize_t, &indent_level)) return NULL; rval = PyList_New(0); if (rval == NULL) return NULL; if (encoder_listencode_obj(s, rval, obj, indent_level)) { Py_DECREF(rval); return NULL; } return rval; } static PyObject * _encoded_const(PyObject *obj) { /* Return the JSON string representation of None, True, False */ if (obj == Py_None) { static PyObject *s_null = NULL; if (s_null == NULL) { s_null = PyUnicode_InternFromString("null"); } Py_INCREF(s_null); return s_null; } else if (obj == Py_True) { static PyObject *s_true = NULL; if (s_true == NULL) { s_true = PyUnicode_InternFromString("true"); } Py_INCREF(s_true); return s_true; } else if (obj == Py_False) { static PyObject *s_false = NULL; if (s_false == NULL) { s_false = PyUnicode_InternFromString("false"); } Py_INCREF(s_false); return s_false; } else { PyErr_SetString(PyExc_ValueError, "not a const"); return NULL; } } static PyObject * encoder_encode_float(PyEncoderObject *s, PyObject *obj) { /* Return the JSON representation of a PyFloat */ double i = PyFloat_AS_DOUBLE(obj); if (!Py_IS_FINITE(i)) { if (!s->allow_nan) { PyErr_SetString(PyExc_ValueError, "Out of range float values are not JSON compliant"); return NULL; } if (i > 0) { return PyUnicode_FromString("Infinity"); } else if (i < 0) { return PyUnicode_FromString("-Infinity"); } else { return PyUnicode_FromString("NaN"); } } /* Use a better float format here? */ return PyObject_Repr(obj); } static PyObject * encoder_encode_string(PyEncoderObject *s, PyObject *obj) { /* Return the JSON representation of a string */ if (s->fast_encode) return py_encode_basestring_ascii(NULL, obj); else return PyObject_CallFunctionObjArgs(s->encoder, obj, NULL); } static int _steal_list_append(PyObject *lst, PyObject *stolen) { /* Append stolen and then decrement its reference count */ int rval = PyList_Append(lst, stolen); Py_DECREF(stolen); return rval; } static int encoder_listencode_obj(PyEncoderObject *s, PyObject *rval, PyObject *obj, Py_ssize_t indent_level) { /* Encode Python object obj to a JSON term, rval is a PyList */ PyObject *newobj; int rv; if (obj == Py_None || obj == Py_True || obj == Py_False) { PyObject *cstr = _encoded_const(obj); if (cstr == NULL) return -1; return _steal_list_append(rval, cstr); } else if (PyUnicode_Check(obj)) { PyObject *encoded = encoder_encode_string(s, obj); if (encoded == NULL) return -1; return _steal_list_append(rval, encoded); } else if (PyLong_Check(obj)) { PyObject *encoded = PyObject_Str(obj); if (encoded == NULL) return -1; return _steal_list_append(rval, encoded); } else if (PyFloat_Check(obj)) { PyObject *encoded = encoder_encode_float(s, obj); if (encoded == NULL) return -1; return _steal_list_append(rval, encoded); } else if (PyList_Check(obj) || PyTuple_Check(obj)) { if (Py_EnterRecursiveCall(" while encoding a JSON object")) return -1; rv = encoder_listencode_list(s, rval, obj, indent_level); Py_LeaveRecursiveCall(); return rv; } else if (PyDict_Check(obj)) { if (Py_EnterRecursiveCall(" while encoding a JSON object")) return -1; rv = encoder_listencode_dict(s, rval, obj, indent_level); Py_LeaveRecursiveCall(); return rv; } else { PyObject *ident = NULL; if (s->markers != Py_None) { int has_key; ident = PyLong_FromVoidPtr(obj); if (ident == NULL) return -1; has_key = PyDict_Contains(s->markers, ident); if (has_key) { if (has_key != -1) PyErr_SetString(PyExc_ValueError, "Circular reference detected"); Py_DECREF(ident); return -1; } if (PyDict_SetItem(s->markers, ident, obj)) { Py_DECREF(ident); return -1; } } newobj = PyObject_CallFunctionObjArgs(s->defaultfn, obj, NULL); if (newobj == NULL) { Py_XDECREF(ident); return -1; } if (Py_EnterRecursiveCall(" while encoding a JSON object")) return -1; rv = encoder_listencode_obj(s, rval, newobj, indent_level); Py_LeaveRecursiveCall(); Py_DECREF(newobj); if (rv) { Py_XDECREF(ident); return -1; } if (ident != NULL) { if (PyDict_DelItem(s->markers, ident)) { Py_XDECREF(ident); return -1; } Py_XDECREF(ident); } return rv; } } static int encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ssize_t indent_level) { /* Encode Python dict dct a JSON term, rval is a PyList */ static PyObject *open_dict = NULL; static PyObject *close_dict = NULL; static PyObject *empty_dict = NULL; PyObject *kstr = NULL; PyObject *ident = NULL; PyObject *it = NULL; PyObject *items; PyObject *item = NULL; int skipkeys; Py_ssize_t idx; if (open_dict == NULL || close_dict == NULL || empty_dict == NULL) { open_dict = PyUnicode_InternFromString("{"); close_dict = PyUnicode_InternFromString("}"); empty_dict = PyUnicode_InternFromString("{}"); if (open_dict == NULL || close_dict == NULL || empty_dict == NULL) return -1; } if (Py_SIZE(dct) == 0) return PyList_Append(rval, empty_dict); if (s->markers != Py_None) { int has_key; ident = PyLong_FromVoidPtr(dct); if (ident == NULL) goto bail; has_key = PyDict_Contains(s->markers, ident); if (has_key) { if (has_key != -1) PyErr_SetString(PyExc_ValueError, "Circular reference detected"); goto bail; } if (PyDict_SetItem(s->markers, ident, dct)) { goto bail; } } if (PyList_Append(rval, open_dict)) goto bail; if (s->indent != Py_None) { /* TODO: DOES NOT RUN */ indent_level += 1; /* newline_indent = '\n' + (' ' * (_indent * _current_indent_level)) separator = _item_separator + newline_indent buf += newline_indent */ } if (PyObject_IsTrue(s->sort_keys)) { /* First sort the keys then replace them with (key, value) tuples. */ Py_ssize_t i, nitems; items = PyMapping_Keys(dct); if (items == NULL) goto bail; if (!PyList_Check(items)) { PyErr_SetString(PyExc_ValueError, "keys must return list"); goto bail; } if (PyList_Sort(items) < 0) goto bail; nitems = PyList_GET_SIZE(items); for (i = 0; i < nitems; i++) { PyObject *key, *value; key = PyList_GET_ITEM(items, i); value = PyDict_GetItem(dct, key); item = PyTuple_Pack(2, key, value); if (item == NULL) goto bail; PyList_SET_ITEM(items, i, item); Py_DECREF(key); } } else { items = PyMapping_Items(dct); } if (items == NULL) goto bail; it = PyObject_GetIter(items); Py_DECREF(items); if (it == NULL) goto bail; skipkeys = PyObject_IsTrue(s->skipkeys); idx = 0; while ((item = PyIter_Next(it)) != NULL) { PyObject *encoded, *key, *value; if (!PyTuple_Check(item) || Py_SIZE(item) != 2) { PyErr_SetString(PyExc_ValueError, "items must return 2-tuples"); goto bail; } key = PyTuple_GET_ITEM(item, 0); if (PyUnicode_Check(key)) { Py_INCREF(key); kstr = key; } else if (PyFloat_Check(key)) { kstr = encoder_encode_float(s, key); if (kstr == NULL) goto bail; } else if (key == Py_True || key == Py_False || key == Py_None) { /* This must come before the PyLong_Check because True and False are also 1 and 0.*/ kstr = _encoded_const(key); if (kstr == NULL) goto bail; } else if (PyLong_Check(key)) { kstr = PyObject_Str(key); if (kstr == NULL) goto bail; } else if (skipkeys) { Py_DECREF(item); continue; } else { /* TODO: include repr of key */ PyErr_SetString(PyExc_TypeError, "keys must be a string"); goto bail; } if (idx) { if (PyList_Append(rval, s->item_separator)) goto bail; } encoded = encoder_encode_string(s, kstr); Py_CLEAR(kstr); if (encoded == NULL) goto bail; if (PyList_Append(rval, encoded)) { Py_DECREF(encoded); goto bail; } Py_DECREF(encoded); if (PyList_Append(rval, s->key_separator)) goto bail; value = PyTuple_GET_ITEM(item, 1); if (encoder_listencode_obj(s, rval, value, indent_level)) goto bail; idx += 1; Py_DECREF(item); } if (PyErr_Occurred()) goto bail; Py_CLEAR(it); if (ident != NULL) { if (PyDict_DelItem(s->markers, ident)) goto bail; Py_CLEAR(ident); } /* TODO DOES NOT RUN; dead code if (s->indent != Py_None) { indent_level -= 1; yield '\n' + (' ' * (_indent * _current_indent_level)) }*/ if (PyList_Append(rval, close_dict)) goto bail; return 0; bail: Py_XDECREF(it); Py_XDECREF(item); Py_XDECREF(kstr); Py_XDECREF(ident); return -1; } static int encoder_listencode_list(PyEncoderObject *s, PyObject *rval, PyObject *seq, Py_ssize_t indent_level) { /* Encode Python list seq to a JSON term, rval is a PyList */ static PyObject *open_array = NULL; static PyObject *close_array = NULL; static PyObject *empty_array = NULL; PyObject *ident = NULL; PyObject *s_fast = NULL; Py_ssize_t num_items; PyObject **seq_items; Py_ssize_t i; if (open_array == NULL || close_array == NULL || empty_array == NULL) { open_array = PyUnicode_InternFromString("["); close_array = PyUnicode_InternFromString("]"); empty_array = PyUnicode_InternFromString("[]"); if (open_array == NULL || close_array == NULL || empty_array == NULL) return -1; } ident = NULL; s_fast = PySequence_Fast(seq, "_iterencode_list needs a sequence"); if (s_fast == NULL) return -1; num_items = PySequence_Fast_GET_SIZE(s_fast); if (num_items == 0) { Py_DECREF(s_fast); return PyList_Append(rval, empty_array); } if (s->markers != Py_None) { int has_key; ident = PyLong_FromVoidPtr(seq); if (ident == NULL) goto bail; has_key = PyDict_Contains(s->markers, ident); if (has_key) { if (has_key != -1) PyErr_SetString(PyExc_ValueError, "Circular reference detected"); goto bail; } if (PyDict_SetItem(s->markers, ident, seq)) { goto bail; } } seq_items = PySequence_Fast_ITEMS(s_fast); if (PyList_Append(rval, open_array)) goto bail; if (s->indent != Py_None) { /* TODO: DOES NOT RUN */ indent_level += 1; /* newline_indent = '\n' + (' ' * (_indent * _current_indent_level)) separator = _item_separator + newline_indent buf += newline_indent */ } for (i = 0; i < num_items; i++) { PyObject *obj = seq_items[i]; if (i) { if (PyList_Append(rval, s->item_separator)) goto bail; } if (encoder_listencode_obj(s, rval, obj, indent_level)) goto bail; } if (ident != NULL) { if (PyDict_DelItem(s->markers, ident)) goto bail; Py_CLEAR(ident); } /* TODO: DOES NOT RUN if (s->indent != Py_None) { indent_level -= 1; yield '\n' + (' ' * (_indent * _current_indent_level)) }*/ if (PyList_Append(rval, close_array)) goto bail; Py_DECREF(s_fast); return 0; bail: Py_XDECREF(ident); Py_DECREF(s_fast); return -1; } static void encoder_dealloc(PyObject *self) { /* Deallocate Encoder */ encoder_clear(self); Py_TYPE(self)->tp_free(self); } static int encoder_traverse(PyObject *self, visitproc visit, void *arg) { PyEncoderObject *s; assert(PyEncoder_Check(self)); s = (PyEncoderObject *)self; Py_VISIT(s->markers); Py_VISIT(s->defaultfn); Py_VISIT(s->encoder); Py_VISIT(s->indent); Py_VISIT(s->key_separator); Py_VISIT(s->item_separator); Py_VISIT(s->sort_keys); Py_VISIT(s->skipkeys); return 0; } static int encoder_clear(PyObject *self) { /* Deallocate Encoder */ PyEncoderObject *s; assert(PyEncoder_Check(self)); s = (PyEncoderObject *)self; Py_CLEAR(s->markers); Py_CLEAR(s->defaultfn); Py_CLEAR(s->encoder); Py_CLEAR(s->indent); Py_CLEAR(s->key_separator); Py_CLEAR(s->item_separator); Py_CLEAR(s->sort_keys); Py_CLEAR(s->skipkeys); return 0; } PyDoc_STRVAR(encoder_doc, "_iterencode(obj, _current_indent_level) -> iterable"); static PyTypeObject PyEncoderType = { PyVarObject_HEAD_INIT(NULL, 0) "_json.Encoder", /* tp_name */ sizeof(PyEncoderObject), /* tp_basicsize */ 0, /* tp_itemsize */ encoder_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ encoder_call, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ encoder_doc, /* tp_doc */ encoder_traverse, /* tp_traverse */ encoder_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ encoder_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ encoder_init, /* tp_init */ 0, /* tp_alloc */ encoder_new, /* tp_new */ 0, /* tp_free */ }; static PyMethodDef speedups_methods[] = { {"encode_basestring_ascii", (PyCFunction)py_encode_basestring_ascii, METH_O, pydoc_encode_basestring_ascii}, {"scanstring", (PyCFunction)py_scanstring, METH_VARARGS, pydoc_scanstring}, {NULL, NULL, 0, NULL} }; PyDoc_STRVAR(module_doc, "json speedups\n"); static struct PyModuleDef jsonmodule = { PyModuleDef_HEAD_INIT, "_json", module_doc, -1, speedups_methods, NULL, NULL, NULL, NULL }; PyObject* PyInit__json(void) { PyObject *m = PyModule_Create(&jsonmodule); if (!m) return NULL; PyScannerType.tp_new = PyType_GenericNew; if (PyType_Ready(&PyScannerType) < 0) goto fail; PyEncoderType.tp_new = PyType_GenericNew; if (PyType_Ready(&PyEncoderType) < 0) goto fail; Py_INCREF((PyObject*)&PyScannerType); if (PyModule_AddObject(m, "make_scanner", (PyObject*)&PyScannerType) < 0) { Py_DECREF((PyObject*)&PyScannerType); goto fail; } Py_INCREF((PyObject*)&PyEncoderType); if (PyModule_AddObject(m, "make_encoder", (PyObject*)&PyEncoderType) < 0) { Py_DECREF((PyObject*)&PyEncoderType); goto fail; } return m; fail: Py_DECREF(m); return NULL; }
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/python_70019-70023.c
manybugs_data_92
/* $Id$ * * tiff2pdf - converts a TIFF image to a PDF document * * Copyright (c) 2003 Ross Finlayson * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the name of * Ross Finlayson may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Ross Finlayson. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL ROSS FINLAYSON BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ #include "tif_config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <time.h> #include <errno.h> #if HAVE_UNISTD_H # include <unistd.h> #endif #ifdef HAVE_FCNTL_H # include <fcntl.h> #endif #ifdef HAVE_IO_H # include <io.h> #endif #ifdef NEED_LIBPORT # include "libport.h" #endif #include "tiffiop.h" #include "tiffio.h" #ifndef HAVE_GETOPT extern int getopt(int, char**, char*); #endif #ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 #endif #ifndef EXIT_FAILURE # define EXIT_FAILURE 1 #endif #define TIFF2PDF_MODULE "tiff2pdf" #define PS_UNIT_SIZE 72.0F /* This type is of PDF color spaces. */ typedef enum { T2P_CS_BILEVEL = 0x01, /* Bilevel, black and white */ T2P_CS_GRAY = 0x02, /* Single channel */ T2P_CS_RGB = 0x04, /* Three channel tristimulus RGB */ T2P_CS_CMYK = 0x08, /* Four channel CMYK print inkset */ T2P_CS_LAB = 0x10, /* Three channel L*a*b* color space */ T2P_CS_PALETTE = 0x1000,/* One of the above with a color map */ T2P_CS_CALGRAY = 0x20, /* Calibrated single channel */ T2P_CS_CALRGB = 0x40, /* Calibrated three channel tristimulus RGB */ T2P_CS_ICCBASED = 0x80 /* ICC profile color specification */ } t2p_cs_t; /* This type is of PDF compression types. */ typedef enum{ T2P_COMPRESS_NONE=0x00 #ifdef CCITT_SUPPORT , T2P_COMPRESS_G4=0x01 #endif #if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT) , T2P_COMPRESS_JPEG=0x02 #endif #ifdef ZIP_SUPPORT , T2P_COMPRESS_ZIP=0x04 #endif } t2p_compress_t; /* This type is whether TIFF image data can be used in PDF without transcoding. */ typedef enum{ T2P_TRANSCODE_RAW=0x01, /* The raw data from the input can be used without recompressing */ T2P_TRANSCODE_ENCODE=0x02 /* The data from the input is perhaps unencoded and reencoded */ } t2p_transcode_t; /* This type is of information about the data samples of the input image. */ typedef enum{ T2P_SAMPLE_NOTHING=0x0000, /* The unencoded samples are normal for the output colorspace */ T2P_SAMPLE_ABGR_TO_RGB=0x0001, /* The unencoded samples are the result of ReadRGBAImage */ T2P_SAMPLE_RGBA_TO_RGB=0x0002, /* The unencoded samples are contiguous RGBA */ T2P_SAMPLE_RGBAA_TO_RGB=0x0004, /* The unencoded samples are RGBA with premultiplied alpha */ T2P_SAMPLE_YCBCR_TO_RGB=0x0008, T2P_SAMPLE_YCBCR_TO_LAB=0x0010, T2P_SAMPLE_REALIZE_PALETTE=0x0020, /* The unencoded samples are indexes into the color map */ T2P_SAMPLE_SIGNED_TO_UNSIGNED=0x0040, /* The unencoded samples are signed instead of unsignd */ T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED=0x0040, /* The L*a*b* samples have a* and b* signed */ T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG=0x0100 /* The unencoded samples are separate instead of contiguous */ } t2p_sample_t; /* This type is of error status of the T2P struct. */ typedef enum{ T2P_ERR_OK = 0, /* This is the value of t2p->t2p_error when there is no error */ T2P_ERR_ERROR = 1 /* This is the value of t2p->t2p_error when there was an error */ } t2p_err_t; /* This struct defines a logical page of a TIFF. */ typedef struct { tdir_t page_directory; uint32 page_number; ttile_t page_tilecount; uint32 page_extra; } T2P_PAGE; /* This struct defines a PDF rectangle's coordinates. */ typedef struct { float x1; float y1; float x2; float y2; float mat[9]; } T2P_BOX; /* This struct defines a tile of a PDF. */ typedef struct { T2P_BOX tile_box; } T2P_TILE; /* This struct defines information about the tiles on a PDF page. */ typedef struct { ttile_t tiles_tilecount; uint32 tiles_tilewidth; uint32 tiles_tilelength; uint32 tiles_tilecountx; uint32 tiles_tilecounty; uint32 tiles_edgetilewidth; uint32 tiles_edgetilelength; T2P_TILE* tiles_tiles; } T2P_TILES; /* This struct is the context of a function to generate PDF from a TIFF. */ typedef struct { t2p_err_t t2p_error; T2P_PAGE* tiff_pages; T2P_TILES* tiff_tiles; tdir_t tiff_pagecount; uint16 tiff_compression; uint16 tiff_photometric; uint16 tiff_fillorder; uint16 tiff_bitspersample; uint16 tiff_samplesperpixel; uint16 tiff_planar; uint32 tiff_width; uint32 tiff_length; float tiff_xres; float tiff_yres; uint16 tiff_orientation; toff_t tiff_dataoffset; tsize_t tiff_datasize; uint16 tiff_resunit; uint16 pdf_centimeters; uint16 pdf_overrideres; uint16 pdf_overridepagesize; float pdf_defaultxres; float pdf_defaultyres; float pdf_xres; float pdf_yres; float pdf_defaultpagewidth; float pdf_defaultpagelength; float pdf_pagewidth; float pdf_pagelength; float pdf_imagewidth; float pdf_imagelength; T2P_BOX pdf_mediabox; T2P_BOX pdf_imagebox; uint16 pdf_majorversion; uint16 pdf_minorversion; uint32 pdf_catalog; uint32 pdf_pages; uint32 pdf_info; uint32 pdf_palettecs; uint16 pdf_fitwindow; uint32 pdf_startxref; #define TIFF2PDF_FILEID_SIZE 33 char pdf_fileid[TIFF2PDF_FILEID_SIZE]; #define TIFF2PDF_DATETIME_SIZE 17 char pdf_datetime[TIFF2PDF_DATETIME_SIZE]; #define TIFF2PDF_CREATOR_SIZE 512 char pdf_creator[TIFF2PDF_CREATOR_SIZE]; #define TIFF2PDF_AUTHOR_SIZE 512 char pdf_author[TIFF2PDF_AUTHOR_SIZE]; #define TIFF2PDF_TITLE_SIZE 512 char pdf_title[TIFF2PDF_TITLE_SIZE]; #define TIFF2PDF_SUBJECT_SIZE 512 char pdf_subject[TIFF2PDF_SUBJECT_SIZE]; #define TIFF2PDF_KEYWORDS_SIZE 512 char pdf_keywords[TIFF2PDF_KEYWORDS_SIZE]; t2p_cs_t pdf_colorspace; uint16 pdf_colorspace_invert; uint16 pdf_switchdecode; uint16 pdf_palettesize; unsigned char* pdf_palette; int pdf_labrange[4]; t2p_compress_t pdf_defaultcompression; uint16 pdf_defaultcompressionquality; t2p_compress_t pdf_compression; uint16 pdf_compressionquality; uint16 pdf_nopassthrough; t2p_transcode_t pdf_transcode; t2p_sample_t pdf_sample; uint32* pdf_xrefoffsets; uint32 pdf_xrefcount; tdir_t pdf_page; #ifdef OJPEG_SUPPORT tdata_t pdf_ojpegdata; uint32 pdf_ojpegdatalength; uint32 pdf_ojpegiflength; #endif float tiff_whitechromaticities[2]; float tiff_primarychromaticities[6]; float tiff_referenceblackwhite[2]; float* tiff_transferfunction[3]; int pdf_image_interpolate; /* 0 (default) : do not interpolate, 1 : interpolate */ uint16 tiff_transferfunctioncount; uint32 pdf_icccs; uint32 tiff_iccprofilelength; tdata_t tiff_iccprofile; /* fields for custom read/write procedures */ FILE *outputfile; int outputdisable; tsize_t outputwritten; } T2P; /* These functions are called by main. */ void tiff2pdf_usage(void); int tiff2pdf_match_paper_size(float*, float*, char*); /* These functions are used to generate a PDF from a TIFF. */ #ifdef __cplusplus extern "C" { #endif T2P* t2p_init(void); void t2p_validate(T2P*); tsize_t t2p_write_pdf(T2P*, TIFF*, TIFF*); void t2p_free(T2P*); #ifdef __cplusplus } #endif void t2p_read_tiff_init(T2P*, TIFF*); int t2p_cmp_t2p_page(const void*, const void*); void t2p_read_tiff_data(T2P*, TIFF*); void t2p_read_tiff_size(T2P*, TIFF*); void t2p_read_tiff_size_tile(T2P*, TIFF*, ttile_t); int t2p_tile_is_right_edge(T2P_TILES, ttile_t); int t2p_tile_is_bottom_edge(T2P_TILES, ttile_t); int t2p_tile_is_edge(T2P_TILES, ttile_t); int t2p_tile_is_corner_edge(T2P_TILES, ttile_t); tsize_t t2p_readwrite_pdf_image(T2P*, TIFF*, TIFF*); tsize_t t2p_readwrite_pdf_image_tile(T2P*, TIFF*, TIFF*, ttile_t); #ifdef OJPEG_SUPPORT int t2p_process_ojpeg_tables(T2P*, TIFF*); #endif #ifdef JPEG_SUPPORT int t2p_process_jpeg_strip(unsigned char*, tsize_t*, unsigned char*, tsize_t*, tstrip_t, uint32); #endif void t2p_tile_collapse_left(tdata_t, tsize_t, uint32, uint32, uint32); void t2p_write_advance_directory(T2P*, TIFF*); tsize_t t2p_sample_planar_separate_to_contig(T2P*, unsigned char*, unsigned char*, tsize_t); tsize_t t2p_sample_realize_palette(T2P*, unsigned char*); tsize_t t2p_sample_abgr_to_rgb(tdata_t, uint32); tsize_t t2p_sample_rgba_to_rgb(tdata_t, uint32); tsize_t t2p_sample_rgbaa_to_rgb(tdata_t, uint32); tsize_t t2p_sample_lab_signed_to_unsigned(tdata_t, uint32); tsize_t t2p_write_pdf_header(T2P*, TIFF*); tsize_t t2p_write_pdf_obj_start(uint32, TIFF*); tsize_t t2p_write_pdf_obj_end(TIFF*); tsize_t t2p_write_pdf_name(unsigned char*, TIFF*); tsize_t t2p_write_pdf_string(char*, TIFF*); tsize_t t2p_write_pdf_stream(tdata_t, tsize_t, TIFF*); tsize_t t2p_write_pdf_stream_start(TIFF*); tsize_t t2p_write_pdf_stream_end(TIFF*); tsize_t t2p_write_pdf_stream_dict(tsize_t, uint32, TIFF*); tsize_t t2p_write_pdf_stream_dict_start(TIFF*); tsize_t t2p_write_pdf_stream_dict_end(TIFF*); tsize_t t2p_write_pdf_stream_length(tsize_t, TIFF*); tsize_t t2p_write_pdf_catalog(T2P*, TIFF*); tsize_t t2p_write_pdf_info(T2P*, TIFF*, TIFF*); void t2p_pdf_currenttime(T2P*); void t2p_pdf_tifftime(T2P*, TIFF*); tsize_t t2p_write_pdf_pages(T2P*, TIFF*); tsize_t t2p_write_pdf_page(uint32, T2P*, TIFF*); void t2p_compose_pdf_page(T2P*); void t2p_compose_pdf_page_orient(T2P_BOX*, uint16); void t2p_compose_pdf_page_orient_flip(T2P_BOX*, uint16); tsize_t t2p_write_pdf_page_content(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_stream_dict(ttile_t, T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_cs(T2P*, TIFF*); tsize_t t2p_write_pdf_transfer(T2P*, TIFF*); tsize_t t2p_write_pdf_transfer_dict(T2P*, TIFF*, uint16); tsize_t t2p_write_pdf_transfer_stream(T2P*, TIFF*, uint16); tsize_t t2p_write_pdf_xobject_calcs(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_icccs(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_icccs_dict(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_icccs_stream(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_cs_stream(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_decode(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t, T2P*, TIFF*); tsize_t t2p_write_pdf_xreftable(T2P*, TIFF*); tsize_t t2p_write_pdf_trailer(T2P*, TIFF*); static void t2p_disable(TIFF *tif) { T2P *t2p = (T2P*) TIFFClientdata(tif); t2p->outputdisable = 1; } static void t2p_enable(TIFF *tif) { T2P *t2p = (T2P*) TIFFClientdata(tif); t2p->outputdisable = 0; } /* * Procs for TIFFClientOpen */ static tmsize_t t2pReadFile(TIFF *tif, tdata_t data, tmsize_t size) { thandle_t client = TIFFClientdata(tif); TIFFReadWriteProc proc = TIFFGetReadProc(tif); if (proc) return proc(client, data, size); return -1; } static tmsize_t t2pWriteFile(TIFF *tif, tdata_t data, tmsize_t size) { thandle_t client = TIFFClientdata(tif); TIFFReadWriteProc proc = TIFFGetWriteProc(tif); if (proc) return proc(client, data, size); return -1; } static uint64 t2pSeekFile(TIFF *tif, toff_t offset, int whence) { thandle_t client = TIFFClientdata(tif); TIFFSeekProc proc = TIFFGetSeekProc(tif); if (proc) return proc(client, offset, whence); return -1; } static tmsize_t t2p_readproc(thandle_t handle, tdata_t data, tmsize_t size) { (void) handle, (void) data, (void) size; return -1; } static tmsize_t t2p_writeproc(thandle_t handle, tdata_t data, tmsize_t size) { T2P *t2p = (T2P*) handle; if (t2p->outputdisable <= 0 && t2p->outputfile) { tsize_t written = fwrite(data, 1, size, t2p->outputfile); t2p->outputwritten += written; return written; } return size; } static uint64 t2p_seekproc(thandle_t handle, uint64 offset, int whence) { T2P *t2p = (T2P*) handle; if (t2p->outputdisable <= 0 && t2p->outputfile) return fseek(t2p->outputfile, (long) offset, whence); return offset; } static int t2p_closeproc(thandle_t handle) { (void) handle; return 0; } static uint64 t2p_sizeproc(thandle_t handle) { (void) handle; return -1; } static int t2p_mapproc(thandle_t handle, void **data, toff_t *offset) { (void) handle, (void) data, (void) offset; return -1; } static void t2p_unmapproc(thandle_t handle, void *data, toff_t offset) { (void) handle, (void) data, (void) offset; } /* This is the main function. The program converts one TIFF file to one PDF file, including multiple page TIFF files, tiled TIFF files, black and white. grayscale, and color TIFF files that contain data of TIFF photometric interpretations of bilevel, grayscale, RGB, YCbCr, CMYK separation, and ICC L*a*b* as supported by libtiff and PDF. If you have multiple TIFF files to convert into one PDF file then use tiffcp or other program to concatenate the files into a multiple page TIFF file. If the input TIFF file is of huge dimensions (greater than 10000 pixels height or width) convert the input image to a tiled TIFF if it is not already. The standard output is standard output. Set the output file name with the "-o output.pdf" option. All black and white files are compressed into a single strip CCITT G4 Fax compressed PDF, unless tiled, where tiled black and white images are compressed into tiled CCITT G4 Fax compressed PDF, libtiff CCITT support is assumed. Color and grayscale data can be compressed using either JPEG compression, ITU-T T.81, or Zip/Deflate LZ77 compression, per PNG 1.2 and RFC 1951. Set the compression type using the -j or -z options. JPEG compression support requires that libtiff be configured with JPEG support, and Zip/Deflate compression support requires that libtiff is configured with Zip support, in tiffconf.h. Use only one or the other of -j and -z. The -q option sets the image compression quality, that is 1-100 with libjpeg JPEG compression and one of 1, 10, 11, 12, 13, 14, or 15 for PNG group compression predictor methods, add 100, 200, ..., 900 to set zlib compression quality 1-9. PNG Group differencing predictor methods are not currently implemented. If the input TIFF contains single strip CCITT G4 Fax compressed information, then that is written to the PDF file without transcoding, unless the options of no compression and no passthrough are set, -d and -n. If the input TIFF contains JPEG or single strip Zip/Deflate compressed information, and they are configured, then that is written to the PDF file without transcoding, unless the options of no compression and no passthrough are set. The default page size upon which the TIFF image is placed is determined by the resolution and extent of the image data. Default values for the TIFF image resolution can be set using the -x and -y options. The page size can be set using the -p option for paper size, or -w and -l for paper width and length, then each page of the TIFF image is centered on its page. The distance unit for default resolution and page width and length can be set by the -u option, the default unit is inch. Various items of the output document information can be set with the -e, -c, -a, -t, -s, and -k tags. Setting the argument of the option to "" for these tags causes the relevant document information field to be not written. Some of the document information values otherwise get their information from the input TIFF image, the software, author, document name, and image description. The output PDF file conforms to the PDF 1.1 specification or PDF 1.2 if using Zip/Deflate compression. The Portable Document Format (PDF) specification is copyrighted by Adobe Systems, Incorporated. Todos derechos reservados. Here is a listing of the usage example and the options to the tiff2pdf program that is part of the libtiff distribution. Options followed by a colon have a required argument. usage: tiff2pdf [options] input.tif options: -o: output to file name -j: compress with JPEG (requires libjpeg configured with libtiff) -z: compress with Zip/Deflate (requires zlib configured with libtiff) -q: compression quality -n: no compressed data passthrough -d: do not compress (decompress) -i: invert colors -u: set distance unit, 'i' for inch, 'm' for centimeter -x: set x resolution default -y: set y resolution default -w: width in units -l: length in units -r: 'd' for resolution default, 'o' for resolution override -p: paper size, eg "letter", "legal", "a4" -f: set pdf "fit window" user preference -b: set PDF "Interpolate" user preference -e: date, overrides image or current date/time default, YYYYMMDDHHMMSS -c: creator, overrides image software default -a: author, overrides image artist default -t: title, overrides image document name default -s: subject, overrides image image description default -k: keywords -h: usage examples: tiff2pdf -o output.pdf input.tiff The above example would generate the file output.pdf from input.tiff. tiff2pdf input.tiff The above example would generate PDF output from input.tiff and write it to standard output. tiff2pdf -j -p letter -o output.pdf input.tiff The above example would generate the file output.pdf from input.tiff, putting the image pages on a letter sized page, compressing the output with JPEG. Please report bugs through: http://bugzilla.remotesensing.org/buglist.cgi?product=libtiff See also libtiff.3t, tiffcp. */ int main(int argc, char** argv){ extern char *optarg; extern int optind; const char *outfilename = NULL; T2P *t2p = NULL; TIFF *input = NULL, *output = NULL; tsize_t written = 0; int c, ret = EXIT_SUCCESS; t2p = t2p_init(); if (t2p == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't initialize context"); goto fail; } while (argv && (c = getopt(argc, argv, "o:q:u:x:y:w:l:r:p:e:c:a:t:s:k:jzndifbh")) != -1){ switch (c) { case 'o': outfilename = optarg; break; #ifdef JPEG_SUPPORT case 'j': t2p->pdf_defaultcompression=T2P_COMPRESS_JPEG; break; #endif #ifndef JPEG_SUPPORT case 'j': TIFFWarning( TIFF2PDF_MODULE, "JPEG support in libtiff required for JPEG compression, ignoring option"); break; #endif #ifdef ZIP_SUPPORT case 'z': t2p->pdf_defaultcompression=T2P_COMPRESS_ZIP; break; #endif #ifndef ZIP_SUPPORT case 'z': TIFFWarning( TIFF2PDF_MODULE, "Zip support in libtiff required for Zip compression, ignoring option"); break; #endif case 'q': t2p->pdf_defaultcompressionquality=atoi(optarg); break; case 'n': t2p->pdf_nopassthrough=1; break; case 'd': t2p->pdf_defaultcompression=T2P_COMPRESS_NONE; break; case 'u': if(optarg[0]=='m'){ t2p->pdf_centimeters=1; } break; case 'x': t2p->pdf_defaultxres = (float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'y': t2p->pdf_defaultyres = (float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'w': t2p->pdf_overridepagesize=1; t2p->pdf_defaultpagewidth = ((float)atof(optarg) * PS_UNIT_SIZE) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'l': t2p->pdf_overridepagesize=1; t2p->pdf_defaultpagelength = ((float)atof(optarg) * PS_UNIT_SIZE) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'r': if(optarg[0]=='o'){ t2p->pdf_overrideres=1; } break; case 'p': if(tiff2pdf_match_paper_size( &(t2p->pdf_defaultpagewidth), &(t2p->pdf_defaultpagelength), optarg)){ t2p->pdf_overridepagesize=1; } else { TIFFWarning(TIFF2PDF_MODULE, "Unknown paper size %s, ignoring option", optarg); } break; case 'i': t2p->pdf_colorspace_invert=1; break; case 'f': t2p->pdf_fitwindow=1; break; case 'e': if (strlen(optarg) == 0) { t2p->pdf_datetime[0] = '\0'; } else { t2p->pdf_datetime[0] = 'D'; t2p->pdf_datetime[1] = ':'; strncpy(t2p->pdf_datetime + 2, optarg, sizeof(t2p->pdf_datetime) - 3); t2p->pdf_datetime[sizeof(t2p->pdf_datetime) - 1] = '\0'; } break; case 'c': strncpy(t2p->pdf_creator, optarg, sizeof(t2p->pdf_creator) - 1); t2p->pdf_creator[sizeof(t2p->pdf_creator) - 1] = '\0'; break; case 'a': strncpy(t2p->pdf_author, optarg, sizeof(t2p->pdf_author) - 1); t2p->pdf_author[sizeof(t2p->pdf_author) - 1] = '\0'; break; case 't': strncpy(t2p->pdf_title, optarg, sizeof(t2p->pdf_title) - 1); t2p->pdf_title[sizeof(t2p->pdf_title) - 1] = '\0'; break; case 's': strncpy(t2p->pdf_subject, optarg, sizeof(t2p->pdf_subject) - 1); t2p->pdf_subject[sizeof(t2p->pdf_subject) - 1] = '\0'; break; case 'k': strncpy(t2p->pdf_keywords, optarg, sizeof(t2p->pdf_keywords) - 1); t2p->pdf_keywords[sizeof(t2p->pdf_keywords) - 1] = '\0'; break; case 'b': t2p->pdf_image_interpolate = 1; break; case 'h': case '?': tiff2pdf_usage(); goto success; break; } } /* * Input */ if(argc > optind) { input = TIFFOpen(argv[optind++], "r"); if (input==NULL) { TIFFError(TIFF2PDF_MODULE, "Can't open input file %s for reading", argv[optind-1]); goto fail; } } else { TIFFError(TIFF2PDF_MODULE, "No input file specified"); tiff2pdf_usage(); goto fail; } if(argc > optind) { TIFFError(TIFF2PDF_MODULE, "No support for multiple input files"); tiff2pdf_usage(); goto fail; } /* * Output */ t2p->outputdisable = 0; if (outfilename) { t2p->outputfile = fopen(outfilename, "wb"); if (t2p->outputfile == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't open output file %s for writing", outfilename); goto fail; } } else { outfilename = "-"; t2p->outputfile = stdout; } output = TIFFClientOpen(outfilename, "w", (thandle_t) t2p, t2p_readproc, t2p_writeproc, t2p_seekproc, t2p_closeproc, t2p_sizeproc, t2p_mapproc, t2p_unmapproc); if (output == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't initialize output descriptor"); goto fail; } /* * Validate */ t2p_validate(t2p); t2pSeekFile(output, (toff_t) 0, SEEK_SET); /* * Write */ written = t2p_write_pdf(t2p, input, output); if (t2p->t2p_error != 0) { TIFFError(TIFF2PDF_MODULE, "An error occurred creating output PDF file"); goto fail; } fail: ret = EXIT_FAILURE; success: if(input != NULL) TIFFClose(input); if (output != NULL) TIFFClose(output); if (t2p != NULL) t2p_free(t2p); return ret; } void tiff2pdf_usage(){ char* lines[]={ "usage: tiff2pdf [options] input.tiff", "options:", " -o: output to file name", #ifdef JPEG_SUPPORT " -j: compress with JPEG", #endif #ifdef ZIP_SUPPORT " -z: compress with Zip/Deflate", #endif " -q: compression quality", " -n: no compressed data passthrough", " -d: do not compress (decompress)", " -i: invert colors", " -u: set distance unit, 'i' for inch, 'm' for centimeter", " -x: set x resolution default in dots per unit", " -y: set y resolution default in dots per unit", " -w: width in units", " -l: length in units", " -r: 'd' for resolution default, 'o' for resolution override", " -p: paper size, eg \"letter\", \"legal\", \"A4\"", " -f: set PDF \"Fit Window\" user preference", " -e: date, overrides image or current date/time default, YYYYMMDDHHMMSS", " -c: sets document creator, overrides image software default", " -a: sets document author, overrides image artist default", " -t: sets document title, overrides image document name default", " -s: sets document subject, overrides image image description default", " -k: sets document keywords", " -b: set PDF \"Interpolate\" user preference", " -h: usage", NULL }; int i=0; fprintf(stderr, "%s\n\n", TIFFGetVersion()); for (i=0;lines[i]!=NULL;i++){ fprintf(stderr, "%s\n", lines[i]); } return; } int tiff2pdf_match_paper_size(float* width, float* length, char* papersize){ size_t i, len; const char* sizes[]={ "LETTER", "A4", "LEGAL", "EXECUTIVE", "LETTER", "LEGAL", "LEDGER", "TABLOID", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "A10", "A9", "A8", "A7", "A6", "A5", "A4", "A3", "A2", "A1", "A0", "2A0", "4A0", "2A", "4A", "B10", "B9", "B8", "B7", "B6", "B5", "B4", "B3", "B2", "B1", "B0", "JISB10", "JISB9", "JISB8", "JISB7", "JISB6", "JISB5", "JISB4", "JISB3", "JISB2", "JISB1", "JISB0", "C10", "C9", "C8", "C7", "C6", "C5", "C4", "C3", "C2", "C1", "C0", "RA2", "RA1", "RA0", "SRA4", "SRA3", "SRA2", "SRA1", "SRA0", "A3EXTRA", "A4EXTRA", "STATEMENT", "FOLIO", "QUARTO", NULL } ; const int widths[]={ 612, 595, 612, 522, 612,612,792,792, 612,792,1224,1584,2448,2016,792,2016,2448,2880, 74,105,147,210,298,420,595,842,1191,1684,2384,3370,4768,3370,4768, 88,125,176,249,354,499,709,1001,1417,2004,2835, 91,128,181,258,363,516,729,1032,1460,2064,2920, 79,113,162,230,323,459,649,918,1298,1298,2599, 1219,1729,2438,638,907,1276,1814,2551, 914,667, 396, 612, 609, 0 }; const int lengths[]={ 792,842,1008, 756,792,1008,1224,1224, 792,1224,1584,2448,3168,2880,6480,10296,12672,10296, 105,147,210,298,420,595,842,1191,1684,2384,3370,4768,6741,4768,6741, 125,176,249,354,499,709,1001,1417,2004,2835,4008, 128,181,258,363,516,729,1032,1460,2064,2920,4127, 113,162,230,323,459,649,918,1298,1837,1837,3677, 1729,2438,3458,907,1276,1814,2551,3628, 1262,914, 612, 936, 780, 0 }; len=strlen(papersize); for(i=0;i<len;i++){ papersize[i]=toupper(papersize[i]); } for(i=0;sizes[i]!=NULL; i++){ if (strcmp( (const char*)papersize, sizes[i])==0){ *width=(float)widths[i]; *length=(float)lengths[i]; return(1); } } return(0); } /* * This function allocates and initializes a T2P context struct pointer. */ T2P* t2p_init() { T2P* t2p = (T2P*) _TIFFmalloc(sizeof(T2P)); if(t2p==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_init", (unsigned long) sizeof(T2P)); return( (T2P*) NULL ); } _TIFFmemset(t2p, 0x00, sizeof(T2P)); t2p->pdf_majorversion=1; t2p->pdf_minorversion=1; t2p->pdf_defaultxres=300.0; t2p->pdf_defaultyres=300.0; t2p->pdf_defaultpagewidth=612.0; t2p->pdf_defaultpagelength=792.0; t2p->pdf_xrefcount=3; /* Catalog, Info, Pages */ return(t2p); } /* * This function frees a T2P context struct pointer and any allocated data fields of it. */ void t2p_free(T2P* t2p) { int i = 0; if (t2p != NULL) { if(t2p->pdf_xrefoffsets != NULL){ _TIFFfree( (tdata_t) t2p->pdf_xrefoffsets); } if(t2p->tiff_pages != NULL){ _TIFFfree( (tdata_t) t2p->tiff_pages); } for(i=0;i<t2p->tiff_pagecount;i++){ if(t2p->tiff_tiles[i].tiles_tiles != NULL){ _TIFFfree( (tdata_t) t2p->tiff_tiles[i].tiles_tiles); } } if(t2p->tiff_tiles != NULL){ _TIFFfree( (tdata_t) t2p->tiff_tiles); } if(t2p->pdf_palette != NULL){ _TIFFfree( (tdata_t) t2p->pdf_palette); } #ifdef OJPEG_SUPPORT if(t2p->pdf_ojpegdata != NULL){ _TIFFfree( (tdata_t) t2p->pdf_ojpegdata); } #endif _TIFFfree( (tdata_t) t2p ); } return; } /* This function validates the values of a T2P context struct pointer before calling t2p_write_pdf with it. */ void t2p_validate(T2P* t2p){ #ifdef JPEG_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){ if(t2p->pdf_defaultcompressionquality>100 || t2p->pdf_defaultcompressionquality<1){ t2p->pdf_defaultcompressionquality=0; } } #endif #ifdef ZIP_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_ZIP){ uint16 m=t2p->pdf_defaultcompressionquality%100; if(t2p->pdf_defaultcompressionquality/100 > 9 || (m>1 && m<10) || m>15){ t2p->pdf_defaultcompressionquality=0; } if(t2p->pdf_defaultcompressionquality%100 !=0){ t2p->pdf_defaultcompressionquality/=100; t2p->pdf_defaultcompressionquality*=100; TIFFError( TIFF2PDF_MODULE, "PNG Group predictor differencing not implemented, assuming compression quality %u", t2p->pdf_defaultcompressionquality); } t2p->pdf_defaultcompressionquality%=100; if(t2p->pdf_minorversion<2){t2p->pdf_minorversion=2;} } #endif (void)0; return; } /* This function scans the input TIFF file for pages. It attempts to determine which IFD's of the TIFF file contain image document pages. For each, it gathers some information that has to do with the output of the PDF document as a whole. */ void t2p_read_tiff_init(T2P* t2p, TIFF* input){ tdir_t directorycount=0; tdir_t i=0; uint16 pagen=0; uint16 paged=0; uint16 xuint16=0; directorycount=TIFFNumberOfDirectories(input); t2p->tiff_pages = (T2P_PAGE*) _TIFFmalloc(directorycount * sizeof(T2P_PAGE)); if(t2p->tiff_pages==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for tiff_pages array, %s", (unsigned long) directorycount * sizeof(T2P_PAGE), TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } _TIFFmemset( t2p->tiff_pages, 0x00, directorycount * sizeof(T2P_PAGE)); t2p->tiff_tiles = (T2P_TILES*) _TIFFmalloc(directorycount * sizeof(T2P_TILES)); if(t2p->tiff_tiles==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for tiff_tiles array, %s", (unsigned long) directorycount * sizeof(T2P_TILES), TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } _TIFFmemset( t2p->tiff_tiles, 0x00, directorycount * sizeof(T2P_TILES)); for(i=0;i<directorycount;i++){ uint32 subfiletype = 0; if(!TIFFSetDirectory(input, i)){ TIFFError( TIFF2PDF_MODULE, "Can't set directory %u of input file %s", i, TIFFFileName(input)); return; } if(TIFFGetField(input, TIFFTAG_PAGENUMBER, &pagen, &paged)){ if((pagen>paged) && (paged != 0)){ t2p->tiff_pages[t2p->tiff_pagecount].page_number = paged; } else { t2p->tiff_pages[t2p->tiff_pagecount].page_number = pagen; } goto ispage2; } if(TIFFGetField(input, TIFFTAG_SUBFILETYPE, &subfiletype)){ if ( ((subfiletype & FILETYPE_PAGE) != 0) || (subfiletype == 0)){ goto ispage; } else { goto isnotpage; } } if(TIFFGetField(input, TIFFTAG_OSUBFILETYPE, &subfiletype)){ if ((subfiletype == OFILETYPE_IMAGE) || (subfiletype == OFILETYPE_PAGE) || (subfiletype == 0) ){ goto ispage; } else { goto isnotpage; } } ispage: t2p->tiff_pages[t2p->tiff_pagecount].page_number=t2p->tiff_pagecount; ispage2: t2p->tiff_pages[t2p->tiff_pagecount].page_directory=i; if(TIFFIsTiled(input)){ t2p->tiff_pages[t2p->tiff_pagecount].page_tilecount = TIFFNumberOfTiles(input); } t2p->tiff_pagecount++; isnotpage: (void)0; } qsort((void*) t2p->tiff_pages, t2p->tiff_pagecount, sizeof(T2P_PAGE), t2p_cmp_t2p_page); for(i=0;i<t2p->tiff_pagecount;i++){ t2p->pdf_xrefcount += 5; TIFFSetDirectory(input, t2p->tiff_pages[i].page_directory ); if((TIFFGetField(input, TIFFTAG_PHOTOMETRIC, &xuint16) && (xuint16==PHOTOMETRIC_PALETTE)) || TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)) { t2p->tiff_pages[i].page_extra++; t2p->pdf_xrefcount++; } #ifdef ZIP_SUPPORT if (TIFFGetField(input, TIFFTAG_COMPRESSION, &xuint16)) { if( (xuint16== COMPRESSION_DEFLATE || xuint16== COMPRESSION_ADOBE_DEFLATE) && ((t2p->tiff_pages[i].page_tilecount != 0) || TIFFNumberOfStrips(input)==1) && (t2p->pdf_nopassthrough==0) ){ if(t2p->pdf_minorversion<2){t2p->pdf_minorversion=2;} } } #endif if (TIFFGetField(input, TIFFTAG_TRANSFERFUNCTION, &(t2p->tiff_transferfunction[0]), &(t2p->tiff_transferfunction[1]), &(t2p->tiff_transferfunction[2]))) { if(t2p->tiff_transferfunction[1] != t2p->tiff_transferfunction[0]) { t2p->tiff_transferfunctioncount = 3; t2p->tiff_pages[i].page_extra += 4; t2p->pdf_xrefcount += 4; } else { t2p->tiff_transferfunctioncount = 1; t2p->tiff_pages[i].page_extra += 2; t2p->pdf_xrefcount += 2; } if(t2p->pdf_minorversion < 2) t2p->pdf_minorversion = 2; } else { t2p->tiff_transferfunctioncount=0; } if( TIFFGetField( input, TIFFTAG_ICCPROFILE, &(t2p->tiff_iccprofilelength), &(t2p->tiff_iccprofile)) != 0){ t2p->tiff_pages[i].page_extra++; t2p->pdf_xrefcount++; if(t2p->pdf_minorversion<3){t2p->pdf_minorversion=3;} } t2p->tiff_tiles[i].tiles_tilecount= t2p->tiff_pages[i].page_tilecount; if( (TIFFGetField(input, TIFFTAG_PLANARCONFIG, &xuint16) != 0) && (xuint16 == PLANARCONFIG_SEPARATE ) ){ TIFFGetField(input, TIFFTAG_SAMPLESPERPIXEL, &xuint16); t2p->tiff_tiles[i].tiles_tilecount/= xuint16; } if( t2p->tiff_tiles[i].tiles_tilecount > 0){ t2p->pdf_xrefcount += (t2p->tiff_tiles[i].tiles_tilecount -1)*2; TIFFGetField(input, TIFFTAG_TILEWIDTH, &( t2p->tiff_tiles[i].tiles_tilewidth) ); TIFFGetField(input, TIFFTAG_TILELENGTH, &( t2p->tiff_tiles[i].tiles_tilelength) ); t2p->tiff_tiles[i].tiles_tiles = (T2P_TILE*) _TIFFmalloc( t2p->tiff_tiles[i].tiles_tilecount * sizeof(T2P_TILE) ); if( t2p->tiff_tiles[i].tiles_tiles == NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_read_tiff_init, %s", (unsigned long) t2p->tiff_tiles[i].tiles_tilecount * sizeof(T2P_TILE), TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } } } return; } /* * This function is used by qsort to sort a T2P_PAGE* array of page structures * by page number. */ int t2p_cmp_t2p_page(const void* e1, const void* e2){ return( ((T2P_PAGE*)e1)->page_number - ((T2P_PAGE*)e2)->page_number ); } /* This function sets the input directory to the directory of a given page and determines information about the image. It checks the image characteristics to determine if it is possible to convert the image data into a page of PDF output, setting values of the T2P struct for this page. It determines what color space is used in the output PDF to represent the image. It determines if the image can be converted as raw data without requiring transcoding of the image data. */ void t2p_read_tiff_data(T2P* t2p, TIFF* input){ int i=0; uint16* r; uint16* g; uint16* b; uint16* a; uint16 xuint16; uint16* xuint16p; float* xfloatp; t2p->pdf_transcode = T2P_TRANSCODE_ENCODE; t2p->pdf_sample = T2P_SAMPLE_NOTHING; t2p->pdf_switchdecode = t2p->pdf_colorspace_invert; TIFFSetDirectory(input, t2p->tiff_pages[t2p->pdf_page].page_directory); TIFFGetField(input, TIFFTAG_IMAGEWIDTH, &(t2p->tiff_width)); if(t2p->tiff_width == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with zero width", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } TIFFGetField(input, TIFFTAG_IMAGELENGTH, &(t2p->tiff_length)); if(t2p->tiff_length == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with zero length", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } if(TIFFGetField(input, TIFFTAG_COMPRESSION, &(t2p->tiff_compression)) == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with no compression tag", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } if( TIFFIsCODECConfigured(t2p->tiff_compression) == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with compression type %u: not configured", TIFFFileName(input), t2p->tiff_compression ); t2p->t2p_error = T2P_ERR_ERROR; return; } TIFFGetFieldDefaulted(input, TIFFTAG_BITSPERSAMPLE, &(t2p->tiff_bitspersample)); switch(t2p->tiff_bitspersample){ case 1: case 2: case 4: case 8: break; case 0: TIFFWarning( TIFF2PDF_MODULE, "Image %s has 0 bits per sample, assuming 1", TIFFFileName(input)); t2p->tiff_bitspersample=1; break; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with %u bits per sample", TIFFFileName(input), t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } TIFFGetFieldDefaulted(input, TIFFTAG_SAMPLESPERPIXEL, &(t2p->tiff_samplesperpixel)); if(t2p->tiff_samplesperpixel>4){ TIFFError( TIFF2PDF_MODULE, "No support for %s with %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; return; } if(t2p->tiff_samplesperpixel==0){ TIFFWarning( TIFF2PDF_MODULE, "Image %s has 0 samples per pixel, assuming 1", TIFFFileName(input)); t2p->tiff_samplesperpixel=1; } if(TIFFGetField(input, TIFFTAG_SAMPLEFORMAT, &xuint16) != 0 ){ switch(xuint16){ case 0: case 1: case 4: break; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with sample format %u", TIFFFileName(input), xuint16); t2p->t2p_error = T2P_ERR_ERROR; return; break; } } TIFFGetFieldDefaulted(input, TIFFTAG_FILLORDER, &(t2p->tiff_fillorder)); if(TIFFGetField(input, TIFFTAG_PHOTOMETRIC, &(t2p->tiff_photometric)) == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with no photometric interpretation tag", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } switch(t2p->tiff_photometric){ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: if (t2p->tiff_bitspersample==1){ t2p->pdf_colorspace=T2P_CS_BILEVEL; if(t2p->tiff_photometric==PHOTOMETRIC_MINISWHITE){ t2p->pdf_switchdecode ^= 1; } } else { t2p->pdf_colorspace=T2P_CS_GRAY; if(t2p->tiff_photometric==PHOTOMETRIC_MINISWHITE){ t2p->pdf_switchdecode ^= 1; } } break; case PHOTOMETRIC_RGB: t2p->pdf_colorspace=T2P_CS_RGB; if(t2p->tiff_samplesperpixel == 3){ break; } if(TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)){ if(xuint16==1) goto photometric_palette; } if(t2p->tiff_samplesperpixel > 3) { if(t2p->tiff_samplesperpixel == 4) { t2p->pdf_colorspace = T2P_CS_RGB; if(TIFFGetField(input, TIFFTAG_EXTRASAMPLES, &xuint16, &xuint16p) && xuint16 == 1) { if(xuint16p[0] == EXTRASAMPLE_ASSOCALPHA){ t2p->pdf_sample=T2P_SAMPLE_RGBAA_TO_RGB; break; } if(xuint16p[0] == EXTRASAMPLE_UNASSALPHA){ t2p->pdf_sample=T2P_SAMPLE_RGBA_TO_RGB; break; } TIFFWarning( TIFF2PDF_MODULE, "RGB image %s has 4 samples per pixel, assuming RGBA", TIFFFileName(input)); break; } t2p->pdf_colorspace=T2P_CS_CMYK; t2p->pdf_switchdecode ^= 1; TIFFWarning( TIFF2PDF_MODULE, "RGB image %s has 4 samples per pixel, assuming inverse CMYK", TIFFFileName(input)); break; } else { TIFFError( TIFF2PDF_MODULE, "No support for RGB image %s with %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; break; } } else { TIFFError( TIFF2PDF_MODULE, "No support for RGB image %s with %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; break; } case PHOTOMETRIC_PALETTE: photometric_palette: if(t2p->tiff_samplesperpixel!=1){ TIFFError( TIFF2PDF_MODULE, "No support for palettized image %s with not one sample per pixel", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_colorspace=T2P_CS_RGB | T2P_CS_PALETTE; t2p->pdf_palettesize=0x0001<<t2p->tiff_bitspersample; if(!TIFFGetField(input, TIFFTAG_COLORMAP, &r, &g, &b)){ TIFFError( TIFF2PDF_MODULE, "Palettized image %s has no color map", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } if(t2p->pdf_palette != NULL){ _TIFFfree(t2p->pdf_palette); t2p->pdf_palette=NULL; } t2p->pdf_palette = (unsigned char*) _TIFFmalloc(t2p->pdf_palettesize*3); if(t2p->pdf_palette==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_read_tiff_image, %s", t2p->pdf_palettesize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } for(i=0;i<t2p->pdf_palettesize;i++){ t2p->pdf_palette[(i*3)] = (unsigned char) (r[i]>>8); t2p->pdf_palette[(i*3)+1]= (unsigned char) (g[i]>>8); t2p->pdf_palette[(i*3)+2]= (unsigned char) (b[i]>>8); } t2p->pdf_palettesize *= 3; break; case PHOTOMETRIC_SEPARATED: if(TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)){ if(xuint16==1){ goto photometric_palette_cmyk; } } if( TIFFGetField(input, TIFFTAG_INKSET, &xuint16) ){ if(xuint16 != INKSET_CMYK){ TIFFError( TIFF2PDF_MODULE, "No support for %s because its inkset is not CMYK", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } } if(t2p->tiff_samplesperpixel==4){ t2p->pdf_colorspace=T2P_CS_CMYK; } else { TIFFError( TIFF2PDF_MODULE, "No support for %s because it has %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; return; } break; photometric_palette_cmyk: if(t2p->tiff_samplesperpixel!=1){ TIFFError( TIFF2PDF_MODULE, "No support for palettized CMYK image %s with not one sample per pixel", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_colorspace=T2P_CS_CMYK | T2P_CS_PALETTE; t2p->pdf_palettesize=0x0001<<t2p->tiff_bitspersample; if(!TIFFGetField(input, TIFFTAG_COLORMAP, &r, &g, &b, &a)){ TIFFError( TIFF2PDF_MODULE, "Palettized image %s has no color map", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } if(t2p->pdf_palette != NULL){ _TIFFfree(t2p->pdf_palette); t2p->pdf_palette=NULL; } t2p->pdf_palette = (unsigned char*) _TIFFmalloc(t2p->pdf_palettesize*4); if(t2p->pdf_palette==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_read_tiff_image, %s", t2p->pdf_palettesize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } for(i=0;i<t2p->pdf_palettesize;i++){ t2p->pdf_palette[(i*4)] = (unsigned char) (r[i]>>8); t2p->pdf_palette[(i*4)+1]= (unsigned char) (g[i]>>8); t2p->pdf_palette[(i*4)+2]= (unsigned char) (b[i]>>8); t2p->pdf_palette[(i*4)+3]= (unsigned char) (a[i]>>8); } t2p->pdf_palettesize *= 4; break; case PHOTOMETRIC_YCBCR: t2p->pdf_colorspace=T2P_CS_RGB; if(t2p->tiff_samplesperpixel==1){ t2p->pdf_colorspace=T2P_CS_GRAY; t2p->tiff_photometric=PHOTOMETRIC_MINISBLACK; break; } t2p->pdf_sample=T2P_SAMPLE_YCBCR_TO_RGB; #ifdef JPEG_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){ t2p->pdf_sample=T2P_SAMPLE_NOTHING; } #endif break; case PHOTOMETRIC_CIELAB: t2p->pdf_labrange[0]= -127; t2p->pdf_labrange[1]= 127; t2p->pdf_labrange[2]= -127; t2p->pdf_labrange[3]= 127; t2p->pdf_sample=T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED; t2p->pdf_colorspace=T2P_CS_LAB; break; case PHOTOMETRIC_ICCLAB: t2p->pdf_labrange[0]= 0; t2p->pdf_labrange[1]= 255; t2p->pdf_labrange[2]= 0; t2p->pdf_labrange[3]= 255; t2p->pdf_colorspace=T2P_CS_LAB; break; case PHOTOMETRIC_ITULAB: t2p->pdf_labrange[0]=-85; t2p->pdf_labrange[1]=85; t2p->pdf_labrange[2]=-75; t2p->pdf_labrange[3]=124; t2p->pdf_sample=T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED; t2p->pdf_colorspace=T2P_CS_LAB; break; case PHOTOMETRIC_LOGL: case PHOTOMETRIC_LOGLUV: TIFFError( TIFF2PDF_MODULE, "No support for %s with photometric interpretation LogL/LogLuv", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with photometric interpretation %u", TIFFFileName(input), t2p->tiff_photometric); t2p->t2p_error = T2P_ERR_ERROR; return; } if(TIFFGetField(input, TIFFTAG_PLANARCONFIG, &(t2p->tiff_planar))){ switch(t2p->tiff_planar){ case 0: TIFFWarning( TIFF2PDF_MODULE, "Image %s has planar configuration 0, assuming 1", TIFFFileName(input)); t2p->tiff_planar=PLANARCONFIG_CONTIG; case PLANARCONFIG_CONTIG: break; case PLANARCONFIG_SEPARATE: t2p->pdf_sample=T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG; if(t2p->tiff_bitspersample!=8){ TIFFError( TIFF2PDF_MODULE, "No support for %s with separated planar configuration and %u bits per sample", TIFFFileName(input), t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } break; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with planar configuration %u", TIFFFileName(input), t2p->tiff_planar); t2p->t2p_error = T2P_ERR_ERROR; return; } } TIFFGetFieldDefaulted(input, TIFFTAG_ORIENTATION, &(t2p->tiff_orientation)); if(t2p->tiff_orientation>8){ TIFFWarning(TIFF2PDF_MODULE, "Image %s has orientation %u, assuming 0", TIFFFileName(input), t2p->tiff_orientation); t2p->tiff_orientation=0; } if(TIFFGetField(input, TIFFTAG_XRESOLUTION, &(t2p->tiff_xres) ) == 0){ t2p->tiff_xres=0.0; } if(TIFFGetField(input, TIFFTAG_YRESOLUTION, &(t2p->tiff_yres) ) == 0){ t2p->tiff_yres=0.0; } TIFFGetFieldDefaulted(input, TIFFTAG_RESOLUTIONUNIT, &(t2p->tiff_resunit)); if(t2p->tiff_resunit == RESUNIT_CENTIMETER) { t2p->tiff_xres *= 2.54F; t2p->tiff_yres *= 2.54F; } else if (t2p->tiff_resunit != RESUNIT_INCH && t2p->pdf_centimeters != 0) { t2p->tiff_xres *= 2.54F; t2p->tiff_yres *= 2.54F; } t2p_compose_pdf_page(t2p); t2p->pdf_transcode = T2P_TRANSCODE_ENCODE; if(t2p->pdf_nopassthrough==0){ #ifdef CCITT_SUPPORT if(t2p->tiff_compression==COMPRESSION_CCITTFAX4 ){ if(TIFFIsTiled(input) || (TIFFNumberOfStrips(input)==1) ){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_G4; } } #endif #ifdef ZIP_SUPPORT if(t2p->tiff_compression== COMPRESSION_ADOBE_DEFLATE || t2p->tiff_compression==COMPRESSION_DEFLATE){ if(TIFFIsTiled(input) || (TIFFNumberOfStrips(input)==1) ){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_ZIP; } } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_OJPEG){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_JPEG; t2p_process_ojpeg_tables(t2p, input); } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_JPEG){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_JPEG; } #endif (void)0; } if(t2p->pdf_transcode!=T2P_TRANSCODE_RAW){ t2p->pdf_compression = t2p->pdf_defaultcompression; } #ifdef JPEG_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){ if(t2p->pdf_colorspace & T2P_CS_PALETTE){ t2p->pdf_sample|=T2P_SAMPLE_REALIZE_PALETTE; t2p->pdf_colorspace ^= T2P_CS_PALETTE; t2p->tiff_pages[t2p->pdf_page].page_extra--; } } if(t2p->tiff_compression==COMPRESSION_JPEG){ if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ TIFFError( TIFF2PDF_MODULE, "No support for %s with JPEG compression and separated planar configuration", TIFFFileName(input)); t2p->t2p_error=T2P_ERR_ERROR; return; } } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_OJPEG){ if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ TIFFError( TIFF2PDF_MODULE, "No support for %s with OJPEG compression and separated planar configuration", TIFFFileName(input)); t2p->t2p_error=T2P_ERR_ERROR; return; } } #endif if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){ if(t2p->pdf_colorspace & T2P_CS_CMYK){ t2p->tiff_samplesperpixel=4; t2p->tiff_photometric=PHOTOMETRIC_SEPARATED; } else { t2p->tiff_samplesperpixel=3; t2p->tiff_photometric=PHOTOMETRIC_RGB; } } if (TIFFGetField(input, TIFFTAG_TRANSFERFUNCTION, &(t2p->tiff_transferfunction[0]), &(t2p->tiff_transferfunction[1]), &(t2p->tiff_transferfunction[2]))) { if(t2p->tiff_transferfunction[1] != t2p->tiff_transferfunction[0]) { t2p->tiff_transferfunctioncount=3; } else { t2p->tiff_transferfunctioncount=1; } } else { t2p->tiff_transferfunctioncount=0; } if(TIFFGetField(input, TIFFTAG_WHITEPOINT, &xfloatp)!=0){ t2p->tiff_whitechromaticities[0]=xfloatp[0]; t2p->tiff_whitechromaticities[1]=xfloatp[1]; if(t2p->pdf_colorspace & T2P_CS_GRAY){ t2p->pdf_colorspace |= T2P_CS_CALGRAY; } if(t2p->pdf_colorspace & T2P_CS_RGB){ t2p->pdf_colorspace |= T2P_CS_CALRGB; } } if(TIFFGetField(input, TIFFTAG_PRIMARYCHROMATICITIES, &xfloatp)!=0){ t2p->tiff_primarychromaticities[0]=xfloatp[0]; t2p->tiff_primarychromaticities[1]=xfloatp[1]; t2p->tiff_primarychromaticities[2]=xfloatp[2]; t2p->tiff_primarychromaticities[3]=xfloatp[3]; t2p->tiff_primarychromaticities[4]=xfloatp[4]; t2p->tiff_primarychromaticities[5]=xfloatp[5]; if(t2p->pdf_colorspace & T2P_CS_RGB){ t2p->pdf_colorspace |= T2P_CS_CALRGB; } } if(t2p->pdf_colorspace & T2P_CS_LAB){ if(TIFFGetField(input, TIFFTAG_WHITEPOINT, &xfloatp) != 0){ t2p->tiff_whitechromaticities[0]=xfloatp[0]; t2p->tiff_whitechromaticities[1]=xfloatp[1]; } else { t2p->tiff_whitechromaticities[0]=0.3457F; /* 0.3127F; */ t2p->tiff_whitechromaticities[1]=0.3585F; /* 0.3290F; */ } } if(TIFFGetField(input, TIFFTAG_ICCPROFILE, &(t2p->tiff_iccprofilelength), &(t2p->tiff_iccprofile))!=0){ t2p->pdf_colorspace |= T2P_CS_ICCBASED; } else { t2p->tiff_iccprofilelength=0; t2p->tiff_iccprofile=NULL; } #ifdef CCITT_SUPPORT if( t2p->tiff_bitspersample==1 && t2p->tiff_samplesperpixel==1){ t2p->pdf_compression = T2P_COMPRESS_G4; } #endif return; } /* This function returns the necessary size of a data buffer to contain the raw or uncompressed image data from the input TIFF for a page. */ void t2p_read_tiff_size(T2P* t2p, TIFF* input){ uint64* sbc=NULL; #if defined(JPEG_SUPPORT) || defined (OJPEG_SUPPORT) unsigned char* jpt=NULL; tstrip_t i=0; tstrip_t stripcount=0; #endif #ifdef OJPEG_SUPPORT tsize_t k = 0; #endif if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4 ){ TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); t2p->tiff_datasize=(tmsize_t)sbc[0]; return; } #endif #ifdef ZIP_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_ZIP){ TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); t2p->tiff_datasize=(tmsize_t)sbc[0]; return; } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG){ if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){ TIFFError(TIFF2PDF_MODULE, "Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ k += sbc[i]; } if(TIFFGetField(input, TIFFTAG_JPEGIFOFFSET, &(t2p->tiff_dataoffset))){ if(t2p->tiff_dataoffset != 0){ if(TIFFGetField(input, TIFFTAG_JPEGIFBYTECOUNT, &(t2p->tiff_datasize))!=0){ if(t2p->tiff_datasize < k) { t2p->pdf_ojpegiflength=t2p->tiff_datasize; t2p->tiff_datasize+=k; t2p->tiff_datasize+=6; t2p->tiff_datasize+=2*stripcount; TIFFWarning(TIFF2PDF_MODULE, "Input file %s has short JPEG interchange file byte count", TIFFFileName(input)); return; } return; }else { TIFFError(TIFF2PDF_MODULE, "Input file %s missing field: TIFFTAG_JPEGIFBYTECOUNT", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } } } t2p->tiff_datasize+=k; t2p->tiff_datasize+=2*stripcount; t2p->tiff_datasize+=2048; return; } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG) { uint32 count = 0; if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0 ){ if(count > 4){ t2p->tiff_datasize += count; t2p->tiff_datasize -= 2; /* don't use EOI of header */ } } else { t2p->tiff_datasize = 2; /* SOI for first strip */ } stripcount=TIFFNumberOfStrips(input); if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){ TIFFError(TIFF2PDF_MODULE, "Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } for(i=0;i<stripcount;i++){ t2p->tiff_datasize += sbc[i]; t2p->tiff_datasize -=4; /* don't use SOI or EOI of strip */ } t2p->tiff_datasize +=2; /* use EOI of last strip */ return; } #endif (void) 0; } t2p->tiff_datasize=TIFFScanlineSize(input) * t2p->tiff_length; if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ t2p->tiff_datasize*= t2p->tiff_samplesperpixel; } return; } /* This function returns the necessary size of a data buffer to contain the raw or uncompressed image data from the input TIFF for a tile of a page. */ void t2p_read_tiff_size_tile(T2P* t2p, TIFF* input, ttile_t tile){ uint64* tbc = NULL; uint16 edge=0; #ifdef JPEG_SUPPORT unsigned char* jpt; #endif edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile); edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile); if(t2p->pdf_transcode==T2P_TRANSCODE_RAW){ if(edge #if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT) && !(t2p->pdf_compression==T2P_COMPRESS_JPEG) #endif ){ t2p->tiff_datasize=TIFFTileSize(input); return; } else { TIFFGetField(input, TIFFTAG_TILEBYTECOUNTS, &tbc); t2p->tiff_datasize=(tmsize_t)tbc[tile]; #ifdef OJPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_OJPEG){ t2p->tiff_datasize+=2048; return; } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_JPEG) { uint32 count = 0; if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt)!=0){ if(count > 4){ t2p->tiff_datasize += count; t2p->tiff_datasize -= 2; /* don't use EOI of header or SOI of tile */ } } } #endif return; } } t2p->tiff_datasize=TIFFTileSize(input); if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ t2p->tiff_datasize*= t2p->tiff_samplesperpixel; } return; } /* * This functions returns a non-zero value when the tile is on the right edge * and does not have full imaged tile width. */ int t2p_tile_is_right_edge(T2P_TILES tiles, ttile_t tile){ if( ((tile+1) % tiles.tiles_tilecountx == 0) && (tiles.tiles_edgetilewidth != 0) ){ return(1); } else { return(0); } } /* * This functions returns a non-zero value when the tile is on the bottom edge * and does not have full imaged tile length. */ int t2p_tile_is_bottom_edge(T2P_TILES tiles, ttile_t tile){ if( ((tile+1) > (tiles.tiles_tilecount-tiles.tiles_tilecountx) ) && (tiles.tiles_edgetilelength != 0) ){ return(1); } else { return(0); } } /* * This function returns a non-zero value when the tile is a right edge tile * or a bottom edge tile. */ int t2p_tile_is_edge(T2P_TILES tiles, ttile_t tile){ return(t2p_tile_is_right_edge(tiles, tile) | t2p_tile_is_bottom_edge(tiles, tile) ); } /* This function returns a non-zero value when the tile is a right edge tile and a bottom edge tile. */ int t2p_tile_is_corner_edge(T2P_TILES tiles, ttile_t tile){ return(t2p_tile_is_right_edge(tiles, tile) & t2p_tile_is_bottom_edge(tiles, tile) ); } /* This function reads the raster image data from the input TIFF for an image and writes the data to the output PDF XObject image dictionary stream. It returns the amount written or zero on error. */ tsize_t t2p_readwrite_pdf_image(T2P* t2p, TIFF* input, TIFF* output){ tsize_t written=0; unsigned char* buffer=NULL; unsigned char* samplebuffer=NULL; tsize_t bufferoffset=0; tsize_t samplebufferoffset=0; tsize_t read=0; tstrip_t i=0; tstrip_t j=0; tstrip_t stripcount=0; tsize_t stripsize=0; tsize_t sepstripcount=0; tsize_t sepstripsize=0; #ifdef OJPEG_SUPPORT toff_t inputoffset=0; uint16 h_samp=1; uint16 v_samp=1; uint16 ri=1; uint32 rows=0; #endif #ifdef JPEG_SUPPORT unsigned char* jpt; float* xfloatp; uint64* sbc; unsigned char* stripbuffer; tsize_t striplength=0; uint32 max_striplength=0; #endif if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if (buffer == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ /* * make sure is lsb-to-msb * bit-endianness fill order */ TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif #ifdef ZIP_SUPPORT if (t2p->pdf_compression == T2P_COMPRESS_ZIP) { buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB) { TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG) { if(t2p->tiff_dataoffset != 0) { buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); if(t2p->pdf_ojpegiflength==0){ inputoffset=t2pSeekFile(input, 0, SEEK_CUR); t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); t2pReadFile(input, (tdata_t) buffer, t2p->tiff_datasize); t2pSeekFile(input, inputoffset, SEEK_SET); t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } else { inputoffset=t2pSeekFile(input, 0, SEEK_CUR); t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); bufferoffset = t2pReadFile(input, (tdata_t) buffer, t2p->pdf_ojpegiflength); t2p->pdf_ojpegiflength = 0; t2pSeekFile(input, inputoffset, SEEK_SET); TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp); buffer[bufferoffset++]= 0xff; buffer[bufferoffset++]= 0xdd; buffer[bufferoffset++]= 0x00; buffer[bufferoffset++]= 0x04; h_samp*=8; v_samp*=8; ri=(t2p->tiff_width+h_samp-1) / h_samp; TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows); ri*=(rows+v_samp-1)/v_samp; buffer[bufferoffset++]= (ri>>8) & 0xff; buffer[bufferoffset++]= ri & 0xff; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0 ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } } else { if(! t2p->pdf_ojpegdata){ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with bad tables", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); _TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength); bufferoffset=t2p->pdf_ojpegdatalength; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } if( ! ( (buffer[bufferoffset-1]==0xd9) && (buffer[bufferoffset-2]==0xff) ) ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with no JPEG File Interchange offset", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } return(t2p->tiff_datasize); } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG) { uint32 count = 0; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); if (TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) { if(count > 4) { _TIFFmemcpy(buffer, jpt, count); bufferoffset += count - 2; } } stripcount=TIFFNumberOfStrips(input); TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); for(i=0;i<stripcount;i++){ if(sbc[i]>max_striplength) max_striplength=sbc[i]; } stripbuffer = (unsigned char*) _TIFFmalloc(max_striplength); if(stripbuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", max_striplength, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } for(i=0;i<stripcount;i++){ striplength=TIFFReadRawStrip(input, i, (tdata_t) stripbuffer, -1); if(!t2p_process_jpeg_strip( stripbuffer, &striplength, buffer, &bufferoffset, i, t2p->tiff_length)){ TIFFError(TIFF2PDF_MODULE, "Can't process JPEG data in input file %s", TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(stripbuffer); _TIFFfree(buffer); return(bufferoffset); } #endif (void)0; } if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], stripsize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } } else { if(t2p->pdf_sample & T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){ sepstripsize=TIFFStripSize(input); sepstripcount=TIFFNumberOfStrips(input); stripsize=sepstripsize*t2p->tiff_samplesperpixel; stripcount=sepstripcount/t2p->tiff_samplesperpixel; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); samplebuffer = (unsigned char*) _TIFFmalloc(stripsize); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } for(i=0;i<stripcount;i++){ samplebufferoffset=0; for(j=0;j<t2p->tiff_samplesperpixel;j++){ read = TIFFReadEncodedStrip(input, i + j*stripcount, (tdata_t) &(samplebuffer[samplebufferoffset]), sepstripsize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i + j*stripcount, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } samplebufferoffset+=read; } t2p_sample_planar_separate_to_contig( t2p, &(buffer[bufferoffset]), samplebuffer, samplebufferoffset); bufferoffset+=samplebufferoffset; } _TIFFfree(samplebuffer); goto dataready; } buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], stripsize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){ samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t) buffer, t2p->tiff_datasize * t2p->tiff_samplesperpixel); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); } else { buffer=samplebuffer; t2p->tiff_datasize *= t2p->tiff_samplesperpixel; } t2p_sample_realize_palette(t2p, buffer); } if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgba_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){ samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length*4); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } else { buffer=samplebuffer; } if(!TIFFReadRGBAImageOriented( input, t2p->tiff_width, t2p->tiff_length, (uint32*)buffer, ORIENTATION_TOPLEFT, 0)){ TIFFError(TIFF2PDF_MODULE, "Can't use TIFFReadRGBAImageOriented to extract RGB image from %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } t2p->tiff_datasize=t2p_sample_abgr_to_rgb( (tdata_t) buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){ t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } } dataready: t2p_disable(output); TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric); TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample); TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel); TIFFSetField(output, TIFFTAG_IMAGEWIDTH, t2p->tiff_width); TIFFSetField(output, TIFFTAG_IMAGELENGTH, t2p->tiff_length); TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_length); TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB); switch(t2p->pdf_compression){ case T2P_COMPRESS_NONE: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE); break; #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4); break; #endif #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: if(t2p->tiff_photometric==PHOTOMETRIC_YCBCR) { uint16 hor = 0, ver = 0; if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver) !=0 ) { if(hor != 0 && ver != 0){ TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver); } } if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){ TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp); } } if(TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG)==0){ TIFFError(TIFF2PDF_MODULE, "Unable to use JPEG compression for input %s and output %s", TIFFFileName(input), TIFFFileName(output)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){ TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){ TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW); } } if(t2p->pdf_colorspace & T2P_CS_GRAY){ (void)0; } if(t2p->pdf_colorspace & T2P_CS_CMYK){ (void)0; } if(t2p->pdf_defaultcompressionquality != 0){ TIFFSetField(output, TIFFTAG_JPEGQUALITY, t2p->pdf_defaultcompressionquality); } break; #endif #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE); if(t2p->pdf_defaultcompressionquality%100 != 0){ TIFFSetField(output, TIFFTAG_PREDICTOR, t2p->pdf_defaultcompressionquality % 100); } if(t2p->pdf_defaultcompressionquality/100 != 0){ TIFFSetField(output, TIFFTAG_ZIPQUALITY, (t2p->pdf_defaultcompressionquality / 100)); } break; #endif default: break; } t2p_enable(output); t2p->outputwritten = 0; #ifdef JPEG_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_JPEG && t2p->tiff_photometric == PHOTOMETRIC_YCBCR){ bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, stripsize * stripcount); } else #endif { bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, t2p->tiff_datasize); } if (buffer != NULL) { _TIFFfree(buffer); buffer=NULL; } if (bufferoffset == (tsize_t)-1) { TIFFError(TIFF2PDF_MODULE, "Error writing encoded strip to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } written = t2p->outputwritten; return(written); } /* * This function reads the raster image data from the input TIFF for an image * tile and writes the data to the output PDF XObject image dictionary stream * for the tile. It returns the amount written or zero on error. */ tsize_t t2p_readwrite_pdf_image_tile(T2P* t2p, TIFF* input, TIFF* output, ttile_t tile){ uint16 edge=0; tsize_t written=0; unsigned char* buffer=NULL; tsize_t bufferoffset=0; unsigned char* samplebuffer=NULL; tsize_t samplebufferoffset=0; tsize_t read=0; uint16 i=0; ttile_t tilecount=0; tsize_t tilesize=0; ttile_t septilecount=0; tsize_t septilesize=0; #ifdef JPEG_SUPPORT unsigned char* jpt; float* xfloatp; uint32 xuint32=0; #endif edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile); edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile); if( (t2p->pdf_transcode == T2P_TRANSCODE_RAW) && ((edge == 0) #if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT) || (t2p->pdf_compression == T2P_COMPRESS_JPEG) #endif ) ){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4){ buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif #ifdef ZIP_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_ZIP){ buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG){ if(! t2p->pdf_ojpegdata){ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with " "bad tables", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } buffer=(unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } _TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength); if(edge!=0){ if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){ buffer[7]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength >> 8) & 0xff; buffer[8]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength ) & 0xff; } if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){ buffer[9]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth >> 8) & 0xff; buffer[10]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth ) & 0xff; } } bufferoffset=t2p->pdf_ojpegdatalength; bufferoffset+=TIFFReadRawTile(input, tile, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); ((unsigned char*)buffer)[bufferoffset++]=0xff; ((unsigned char*)buffer)[bufferoffset++]=0xd9; t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG){ unsigned char table_end[2]; uint32 count = 0; buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) { if (count > 0) { _TIFFmemcpy(buffer, jpt, count); bufferoffset += count - 2; table_end[0] = buffer[bufferoffset-2]; table_end[1] = buffer[bufferoffset-1]; } if (count > 0) { xuint32 = bufferoffset; bufferoffset += TIFFReadRawTile( input, tile, (tdata_t) &(((unsigned char*)buffer)[bufferoffset-2]), -1); buffer[xuint32-2]=table_end[0]; buffer[xuint32-1]=table_end[1]; } else { bufferoffset += TIFFReadRawTile( input, tile, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } #endif (void)0; } if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for " "t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } read = TIFFReadEncodedTile( input, tile, (tdata_t) &buffer[bufferoffset], t2p->tiff_datasize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding tile %u of %s", tile, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } } else { if(t2p->pdf_sample == T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){ septilesize=TIFFTileSize(input); septilecount=TIFFNumberOfTiles(input); tilesize=septilesize*t2p->tiff_samplesperpixel; tilecount=septilecount/t2p->tiff_samplesperpixel; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } samplebuffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } samplebufferoffset=0; for(i=0;i<t2p->tiff_samplesperpixel;i++){ read = TIFFReadEncodedTile(input, tile + i*tilecount, (tdata_t) &(samplebuffer[samplebufferoffset]), septilesize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding tile %u of %s", tile + i*tilecount, TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } samplebufferoffset+=read; } t2p_sample_planar_separate_to_contig( t2p, &(buffer[bufferoffset]), samplebuffer, samplebufferoffset); bufferoffset+=samplebufferoffset; _TIFFfree(samplebuffer); } if(buffer==NULL){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } read = TIFFReadEncodedTile( input, tile, (tdata_t) &buffer[bufferoffset], t2p->tiff_datasize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding tile %u of %s", tile, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } } if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgba_to_rgb( (tdata_t)buffer, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth *t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb( (tdata_t)buffer, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth *t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){ TIFFError(TIFF2PDF_MODULE, "No support for YCbCr to RGB in tile for %s", TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){ t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned( (tdata_t)buffer, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth *t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } } if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) != 0){ t2p_tile_collapse_left( buffer, TIFFTileRowSize(input), t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth, t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } t2p_disable(output); TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric); TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample); TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel); if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){ TIFFSetField( output, TIFFTAG_IMAGEWIDTH, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth); } else { TIFFSetField( output, TIFFTAG_IMAGEWIDTH, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth); } if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){ TIFFSetField( output, TIFFTAG_IMAGELENGTH, t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); TIFFSetField( output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } else { TIFFSetField( output, TIFFTAG_IMAGELENGTH, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); TIFFSetField( output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); } TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB); switch(t2p->pdf_compression){ case T2P_COMPRESS_NONE: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE); break; #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4); break; #endif #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: if (t2p->tiff_photometric==PHOTOMETRIC_YCBCR) { uint16 hor = 0, ver = 0; if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver)!=0) { if (hor != 0 && ver != 0) { TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver); } } if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){ TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp); } } TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG); TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); /* JPEGTABLESMODE_NONE */ if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){ TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){ TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW); } } if(t2p->pdf_colorspace & T2P_CS_GRAY){ (void)0; } if(t2p->pdf_colorspace & T2P_CS_CMYK){ (void)0; } if(t2p->pdf_defaultcompressionquality != 0){ TIFFSetField(output, TIFFTAG_JPEGQUALITY, t2p->pdf_defaultcompressionquality); } break; #endif #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE); if(t2p->pdf_defaultcompressionquality%100 != 0){ TIFFSetField(output, TIFFTAG_PREDICTOR, t2p->pdf_defaultcompressionquality % 100); } if(t2p->pdf_defaultcompressionquality/100 != 0){ TIFFSetField(output, TIFFTAG_ZIPQUALITY, (t2p->pdf_defaultcompressionquality / 100)); } break; #endif default: break; } t2p_enable(output); t2p->outputwritten = 0; bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t) 0, buffer, TIFFStripSize(output)); if (buffer != NULL) { _TIFFfree(buffer); buffer = NULL; } if (bufferoffset == -1) { TIFFError(TIFF2PDF_MODULE, "Error writing encoded tile to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } written = t2p->outputwritten; return(written); } #ifdef OJPEG_SUPPORT int t2p_process_ojpeg_tables(T2P* t2p, TIFF* input){ uint16 proc=0; void* q; uint32 q_length=0; void* dc; uint32 dc_length=0; void* ac; uint32 ac_length=0; uint16* lp; uint16* pt; uint16 h_samp=1; uint16 v_samp=1; unsigned char* ojpegdata; uint16 table_count; uint32 offset_table; uint32 offset_ms_l; uint32 code_count; uint32 i=0; uint32 dest=0; uint16 ri=0; uint32 rows=0; if(!TIFFGetField(input, TIFFTAG_JPEGPROC, &proc)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGProc field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(proc!=JPEGPROC_BASELINE && proc!=JPEGPROC_LOSSLESS){ TIFFError(TIFF2PDF_MODULE, "Bad JPEGProc field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(!TIFFGetField(input, TIFFTAG_JPEGQTABLES, &q_length, &q)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGQTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(q_length < (64U * t2p->tiff_samplesperpixel)){ TIFFError(TIFF2PDF_MODULE, "Bad JPEGQTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(!TIFFGetField(input, TIFFTAG_JPEGDCTABLES, &dc_length, &dc)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGDCTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(proc==JPEGPROC_BASELINE){ if(!TIFFGetField(input, TIFFTAG_JPEGACTABLES, &ac_length, &ac)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGACTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } else { if(!TIFFGetField(input, TIFFTAG_JPEGLOSSLESSPREDICTORS, &lp)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGLosslessPredictors field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(!TIFFGetField(input, TIFFTAG_JPEGPOINTTRANSFORM, &pt)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGPointTransform field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } if(!TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp)){ h_samp=1; v_samp=1; } if(t2p->pdf_ojpegdata != NULL){ _TIFFfree(t2p->pdf_ojpegdata); t2p->pdf_ojpegdata=NULL; } t2p->pdf_ojpegdata = _TIFFmalloc(2048); if(t2p->pdf_ojpegdata == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_process_ojpeg_tables, %s", 2048, TIFFFileName(input)); return(0); } _TIFFmemset(t2p->pdf_ojpegdata, 0x00, 2048); t2p->pdf_ojpegdatalength = 0; table_count=t2p->tiff_samplesperpixel; if(proc==JPEGPROC_BASELINE){ if(table_count>2) table_count=2; } ojpegdata=(unsigned char*)t2p->pdf_ojpegdata; ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xd8; ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; if(proc==JPEGPROC_BASELINE){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xc0; } else { ojpegdata[t2p->pdf_ojpegdatalength++]=0xc3; } ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=(8 + 3*t2p->tiff_samplesperpixel); ojpegdata[t2p->pdf_ojpegdatalength++]=(t2p->tiff_bitspersample & 0xff); if(TIFFIsTiled(input)){ ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength ) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth ) & 0xff; } else { ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_length >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_length ) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_width >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_width ) & 0xff; } ojpegdata[t2p->pdf_ojpegdatalength++]=(t2p->tiff_samplesperpixel & 0xff); for(i=0;i<t2p->tiff_samplesperpixel;i++){ ojpegdata[t2p->pdf_ojpegdatalength++]=i; if(i==0){ ojpegdata[t2p->pdf_ojpegdatalength] |= h_samp<<4 & 0xf0;; ojpegdata[t2p->pdf_ojpegdatalength++] |= v_samp & 0x0f; } else { ojpegdata[t2p->pdf_ojpegdatalength++]= 0x11; } ojpegdata[t2p->pdf_ojpegdatalength++]=i; } for(dest=0;dest<t2p->tiff_samplesperpixel;dest++){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xdb; ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=0x43; ojpegdata[t2p->pdf_ojpegdatalength++]=dest; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength++]), &(((unsigned char*)q)[64*dest]), 64); t2p->pdf_ojpegdatalength+=64; } offset_table=0; for(dest=0;dest<table_count;dest++){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xc4; offset_ms_l=t2p->pdf_ojpegdatalength; t2p->pdf_ojpegdatalength+=2; ojpegdata[t2p->pdf_ojpegdatalength++]=dest & 0x0f; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)dc)[offset_table]), 16); code_count=0; offset_table+=16; for(i=0;i<16;i++){ code_count+=ojpegdata[t2p->pdf_ojpegdatalength++]; } ojpegdata[offset_ms_l]=((19+code_count)>>8) & 0xff; ojpegdata[offset_ms_l+1]=(19+code_count) & 0xff; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)dc)[offset_table]), code_count); offset_table+=code_count; t2p->pdf_ojpegdatalength+=code_count; } if(proc==JPEGPROC_BASELINE){ offset_table=0; for(dest=0;dest<table_count;dest++){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xc4; offset_ms_l=t2p->pdf_ojpegdatalength; t2p->pdf_ojpegdatalength+=2; ojpegdata[t2p->pdf_ojpegdatalength] |= 0x10; ojpegdata[t2p->pdf_ojpegdatalength++] |=dest & 0x0f; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)ac)[offset_table]), 16); code_count=0; offset_table+=16; for(i=0;i<16;i++){ code_count+=ojpegdata[t2p->pdf_ojpegdatalength++]; } ojpegdata[offset_ms_l]=((19+code_count)>>8) & 0xff; ojpegdata[offset_ms_l+1]=(19+code_count) & 0xff; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)ac)[offset_table]), code_count); offset_table+=code_count; t2p->pdf_ojpegdatalength+=code_count; } } if(TIFFNumberOfStrips(input)>1){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xdd; ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=0x04; h_samp*=8; v_samp*=8; ri=(t2p->tiff_width+h_samp-1) / h_samp; TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows); ri*=(rows+v_samp-1)/v_samp; ojpegdata[t2p->pdf_ojpegdatalength++]= (ri>>8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= ri & 0xff; } ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xda; ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=(6 + 2*t2p->tiff_samplesperpixel); ojpegdata[t2p->pdf_ojpegdatalength++]=t2p->tiff_samplesperpixel & 0xff; for(i=0;i<t2p->tiff_samplesperpixel;i++){ ojpegdata[t2p->pdf_ojpegdatalength++]= i & 0xff; if(proc==JPEGPROC_BASELINE){ ojpegdata[t2p->pdf_ojpegdatalength] |= ( ( (i>(table_count-1U)) ? (table_count-1U) : i) << 4U) & 0xf0; ojpegdata[t2p->pdf_ojpegdatalength++] |= ( (i>(table_count-1U)) ? (table_count-1U) : i) & 0x0f; } else { ojpegdata[t2p->pdf_ojpegdatalength++] = (i << 4) & 0xf0; } } if(proc==JPEGPROC_BASELINE){ t2p->pdf_ojpegdatalength++; ojpegdata[t2p->pdf_ojpegdatalength++]=0x3f; t2p->pdf_ojpegdatalength++; } else { ojpegdata[t2p->pdf_ojpegdatalength++]= (lp[0] & 0xff); t2p->pdf_ojpegdatalength++; ojpegdata[t2p->pdf_ojpegdatalength++]= (pt[0] & 0x0f); } return(1); } #endif #ifdef JPEG_SUPPORT int t2p_process_jpeg_strip( unsigned char* strip, tsize_t* striplength, unsigned char* buffer, tsize_t* bufferoffset, tstrip_t no, uint32 height){ tsize_t i=0; uint16 ri =0; uint16 v_samp=1; uint16 h_samp=1; int j=0; i++; while(i<(*striplength)){ switch( strip[i] ){ case 0xd8: /* SOI - start of image */ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), 2); *bufferoffset+=2; i+=2; break; case 0xc0: case 0xc1: case 0xc3: case 0xc9: case 0xca: if(no==0){ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), strip[i+2]+2); for(j=0;j<buffer[*bufferoffset+9];j++){ if( (buffer[*bufferoffset+11+(2*j)]>>4) > h_samp) h_samp = (buffer[*bufferoffset+11+(2*j)]>>4); if( (buffer[*bufferoffset+11+(2*j)] & 0x0f) > v_samp) v_samp = (buffer[*bufferoffset+11+(2*j)] & 0x0f); } v_samp*=8; h_samp*=8; ri=((( ((uint16)(buffer[*bufferoffset+5])<<8) | (uint16)(buffer[*bufferoffset+6]) )+v_samp-1)/ v_samp); ri*=((( ((uint16)(buffer[*bufferoffset+7])<<8) | (uint16)(buffer[*bufferoffset+8]) )+h_samp-1)/ h_samp); buffer[*bufferoffset+5]= (unsigned char) ((height>>8) & 0xff); buffer[*bufferoffset+6]= (unsigned char) (height & 0xff); *bufferoffset+=strip[i+2]+2; i+=strip[i+2]+2; buffer[(*bufferoffset)++]=0xff; buffer[(*bufferoffset)++]=0xdd; buffer[(*bufferoffset)++]=0x00; buffer[(*bufferoffset)++]=0x04; buffer[(*bufferoffset)++]=(ri >> 8) & 0xff; buffer[(*bufferoffset)++]= ri & 0xff; } else { i+=strip[i+2]+2; } break; case 0xc4: case 0xdb: _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), strip[i+2]+2); *bufferoffset+=strip[i+2]+2; i+=strip[i+2]+2; break; case 0xda: if(no==0){ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), strip[i+2]+2); *bufferoffset+=strip[i+2]+2; i+=strip[i+2]+2; } else { buffer[(*bufferoffset)++]=0xff; buffer[(*bufferoffset)++]= (unsigned char)(0xd0 | ((no-1)%8)); i+=strip[i+2]+2; } _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), (*striplength)-i-1); *bufferoffset+=(*striplength)-i-1; return(1); default: i+=strip[i+2]+2; } } return(0); } #endif /* This functions converts a tilewidth x tilelength buffer of samples into an edgetilewidth x tilelength buffer of samples. */ void t2p_tile_collapse_left( tdata_t buffer, tsize_t scanwidth, uint32 tilewidth, uint32 edgetilewidth, uint32 tilelength){ uint32 i=0; tsize_t edgescanwidth=0; edgescanwidth = (scanwidth * edgetilewidth + (tilewidth - 1))/ tilewidth; for(i=i;i<tilelength;i++){ _TIFFmemcpy( &(((char*)buffer)[edgescanwidth*i]), &(((char*)buffer)[scanwidth*i]), edgescanwidth); } return; } /* * This function calls TIFFWriteDirectory on the output after blanking its * output by replacing the read, write, and seek procedures with empty * implementations, then it replaces the original implementations. */ void t2p_write_advance_directory(T2P* t2p, TIFF* output) { t2p_disable(output); if(!TIFFWriteDirectory(output)){ TIFFError(TIFF2PDF_MODULE, "Error writing virtual directory to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p_enable(output); return; } tsize_t t2p_sample_planar_separate_to_contig( T2P* t2p, unsigned char* buffer, unsigned char* samplebuffer, tsize_t samplebuffersize){ tsize_t stride=0; tsize_t i=0; tsize_t j=0; stride=samplebuffersize/t2p->tiff_samplesperpixel; for(i=0;i<stride;i++){ for(j=0;j<t2p->tiff_samplesperpixel;j++){ buffer[i*t2p->tiff_samplesperpixel + j] = samplebuffer[i + j*stride]; } } return(samplebuffersize); } tsize_t t2p_sample_realize_palette(T2P* t2p, unsigned char* buffer){ uint32 sample_count=0; uint16 component_count=0; uint32 palette_offset=0; uint32 sample_offset=0; uint32 i=0; uint32 j=0; sample_count=t2p->tiff_width*t2p->tiff_length; component_count=t2p->tiff_samplesperpixel; for(i=sample_count;i>0;i--){ palette_offset=buffer[i-1] * component_count; sample_offset= (i-1) * component_count; for(j=0;j<component_count;j++){ buffer[sample_offset+j]=t2p->pdf_palette[palette_offset+j]; } } return(0); } /* This functions converts in place a buffer of ABGR interleaved data into RGB interleaved data, discarding A. */ tsize_t t2p_sample_abgr_to_rgb(tdata_t data, uint32 samplecount) { uint32 i=0; uint32 sample=0; for(i=0;i<samplecount;i++){ sample=((uint32*)data)[i]; ((char*)data)[i*3]= (char) (sample & 0xff); ((char*)data)[i*3+1]= (char) ((sample>>8) & 0xff); ((char*)data)[i*3+2]= (char) ((sample>>16) & 0xff); } return(i*3); } /* * This functions converts in place a buffer of RGBA interleaved data * into RGB interleaved data, discarding A. */ tsize_t t2p_sample_rgbaa_to_rgb(tdata_t data, uint32 samplecount) { uint32 i; for(i = 0; i < samplecount; i++) memcpy((uint8*)data + i * 3, (uint8*)data + i * 4, 3); return(i * 3); } /* * This functions converts in place a buffer of RGBA interleaved data * into RGB interleaved data, adding 255-A to each component sample. */ tsize_t t2p_sample_rgba_to_rgb(tdata_t data, uint32 samplecount) { uint32 i = 0; uint32 sample = 0; uint8 alpha = 0; for (i = 0; i < samplecount; i++) { sample=((uint32*)data)[i]; alpha=(uint8)((255 - (sample & 0xff))); ((uint8 *)data)[i * 3] = (uint8) ((sample >> 24) & 0xff) + alpha; ((uint8 *)data)[i * 3 + 1] = (uint8) ((sample >> 16) & 0xff) + alpha; ((uint8 *)data)[i * 3 + 2] = (uint8) ((sample >> 8) & 0xff) + alpha; } return (i * 3); } /* This function converts the a and b samples of Lab data from signed to unsigned. */ tsize_t t2p_sample_lab_signed_to_unsigned(tdata_t buffer, uint32 samplecount){ uint32 i=0; for(i=0;i<samplecount;i++){ if( (((unsigned char*)buffer)[(i*3)+1] & 0x80) !=0){ ((unsigned char*)buffer)[(i*3)+1] = (unsigned char)(0x80 + ((char*)buffer)[(i*3)+1]); } else { ((unsigned char*)buffer)[(i*3)+1] |= 0x80; } if( (((unsigned char*)buffer)[(i*3)+2] & 0x80) !=0){ ((unsigned char*)buffer)[(i*3)+2] = (unsigned char)(0x80 + ((char*)buffer)[(i*3)+2]); } else { ((unsigned char*)buffer)[(i*3)+2] |= 0x80; } } return(samplecount*3); } /* This function writes the PDF header to output. */ tsize_t t2p_write_pdf_header(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; buflen=sprintf(buffer, "%%PDF-%u.%u ", t2p->pdf_majorversion&0xff, t2p->pdf_minorversion&0xff); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t)"\n%\342\343\317\323\n", 7); return(written); } /* This function writes the beginning of a PDF object to output. */ tsize_t t2p_write_pdf_obj_start(uint32 number, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; buflen=sprintf(buffer, "%lu", (unsigned long)number); written += t2pWriteFile(output, (tdata_t) buffer, buflen ); written += t2pWriteFile(output, (tdata_t) " 0 obj\n", 7); return(written); } /* This function writes the end of a PDF object to output. */ tsize_t t2p_write_pdf_obj_end(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "endobj\n", 7); return(written); } /* This function writes a PDF name object to output. */ tsize_t t2p_write_pdf_name(unsigned char* name, TIFF* output){ tsize_t written=0; uint32 i=0; char buffer[64]; uint16 nextchar=0; size_t namelen=0; namelen = strlen((char *)name); if (namelen>126) { namelen=126; } written += t2pWriteFile(output, (tdata_t) "/", 1); for (i=0;i<namelen;i++){ if ( ((unsigned char)name[i]) < 0x21){ sprintf(buffer, "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); nextchar=1; } if ( ((unsigned char)name[i]) > 0x7E){ sprintf(buffer, "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); nextchar=1; } if (nextchar==0){ switch (name[i]){ case 0x23: sprintf(buffer, "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x25: sprintf(buffer, "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x28: sprintf(buffer, "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x29: sprintf(buffer, "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x2F: sprintf(buffer, "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x3C: sprintf(buffer, "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x3E: sprintf(buffer, "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x5B: sprintf(buffer, "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x5D: sprintf(buffer, "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x7B: sprintf(buffer, "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x7D: sprintf(buffer, "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; default: written += t2pWriteFile(output, (tdata_t) &name[i], 1); } } nextchar=0; } written += t2pWriteFile(output, (tdata_t) " ", 1); return(written); } /* * This function writes a PDF string object to output. */ tsize_t t2p_write_pdf_string(char* pdfstr, TIFF* output) { tsize_t written = 0; uint32 i = 0; char buffer[64]; size_t len = 0; len = strlen(pdfstr); written += t2pWriteFile(output, (tdata_t) "(", 1); for (i=0; i<len; i++) { if((pdfstr[i]&0x80) || (pdfstr[i]==127) || (pdfstr[i]<32)){ snprintf(buffer, sizeof(buffer), "\\%.3hho", pdfstr[i]); written += t2pWriteFile(output, (tdata_t)buffer, 4); } else { switch (pdfstr[i]){ case 0x08: written += t2pWriteFile(output, (tdata_t) "\\b", 2); break; case 0x09: written += t2pWriteFile(output, (tdata_t) "\\t", 2); break; case 0x0A: written += t2pWriteFile(output, (tdata_t) "\\n", 2); break; case 0x0C: written += t2pWriteFile(output, (tdata_t) "\\f", 2); break; case 0x0D: written += t2pWriteFile(output, (tdata_t) "\\r", 2); break; case 0x28: written += t2pWriteFile(output, (tdata_t) "\\(", 2); break; case 0x29: written += t2pWriteFile(output, (tdata_t) "\\)", 2); break; case 0x5C: written += t2pWriteFile(output, (tdata_t) "\\\\", 2); break; default: written += t2pWriteFile(output, (tdata_t) &pdfstr[i], 1); } } } written += t2pWriteFile(output, (tdata_t) ") ", 1); return(written); } /* This function writes a buffer of data to output. */ tsize_t t2p_write_pdf_stream(tdata_t buffer, tsize_t len, TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) buffer, len); return(written); } /* This functions writes the beginning of a PDF stream to output. */ tsize_t t2p_write_pdf_stream_start(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "stream\n", 7); return(written); } /* This function writes the end of a PDF stream to output. */ tsize_t t2p_write_pdf_stream_end(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "\nendstream\n", 11); return(written); } /* This function writes a stream dictionary for a PDF stream to output. */ tsize_t t2p_write_pdf_stream_dict(tsize_t len, uint32 number, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "/Length ", 8); if(len!=0){ written += t2p_write_pdf_stream_length(len, output); } else { buflen=sprintf(buffer, "%lu", (unsigned long)number); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); } return(written); } /* This functions writes the beginning of a PDF stream dictionary to output. */ tsize_t t2p_write_pdf_stream_dict_start(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "<< \n", 4); return(written); } /* This function writes the end of a PDF stream dictionary to output. */ tsize_t t2p_write_pdf_stream_dict_end(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) " >>\n", 4); return(written); } /* This function writes a number to output. */ tsize_t t2p_write_pdf_stream_length(tsize_t len, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; buflen=sprintf(buffer, "%lu", (unsigned long)len); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n", 1); return(written); } /* * This function writes the PDF Catalog structure to output. */ tsize_t t2p_write_pdf_catalog(T2P* t2p, TIFF* output) { tsize_t written = 0; char buffer[16]; int buflen = 0; written += t2pWriteFile(output, (tdata_t)"<< \n/Type /Catalog \n/Pages ", 27); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_pages); written += t2pWriteFile(output, (tdata_t) buffer, TIFFmin((size_t)buflen, sizeof(buffer) - 1)); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); if(t2p->pdf_fitwindow){ written += t2pWriteFile(output, (tdata_t) "/ViewerPreferences <</FitWindow true>>\n", 39); } written += t2pWriteFile(output, (tdata_t)">>\n", 3); return(written); } /* This function writes the PDF Info structure to output. */ tsize_t t2p_write_pdf_info(T2P* t2p, TIFF* input, TIFF* output) { tsize_t written = 0; char* info; char buffer[512]; if(t2p->pdf_datetime[0] == '\0') t2p_pdf_tifftime(t2p, input); if (strlen(t2p->pdf_datetime) > 0) { written += t2pWriteFile(output, (tdata_t) "<< \n/CreationDate ", 18); written += t2p_write_pdf_string(t2p->pdf_datetime, output); written += t2pWriteFile(output, (tdata_t) "\n/ModDate ", 10); written += t2p_write_pdf_string(t2p->pdf_datetime, output); } written += t2pWriteFile(output, (tdata_t) "\n/Producer ", 11); _TIFFmemset((tdata_t)buffer, 0x00, sizeof(buffer)); snprintf(buffer, sizeof(buffer), "libtiff / tiff2pdf - %d", TIFFLIB_VERSION); written += t2p_write_pdf_string(buffer, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); if (t2p->pdf_creator[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Creator ", 9); written += t2p_write_pdf_string(t2p->pdf_creator, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if (TIFFGetField(input, TIFFTAG_SOFTWARE, &info) != 0 && info) { if(strlen(info) >= sizeof(t2p->pdf_creator)) info[sizeof(t2p->pdf_creator) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) "/Creator ", 9); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_author[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Author ", 8); written += t2p_write_pdf_string(t2p->pdf_author, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if ((TIFFGetField(input, TIFFTAG_ARTIST, &info) != 0 || TIFFGetField(input, TIFFTAG_COPYRIGHT, &info) != 0) && info) { if (strlen(info) >= sizeof(t2p->pdf_author)) info[sizeof(t2p->pdf_author) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) "/Author ", 8); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_title[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Title ", 7); written += t2p_write_pdf_string(t2p->pdf_title, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if (TIFFGetField(input, TIFFTAG_DOCUMENTNAME, &info) != 0){ if(strlen(info) > 511) { info[512] = '\0'; } written += t2pWriteFile(output, (tdata_t) "/Title ", 7); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_subject[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Subject ", 9); written += t2p_write_pdf_string(t2p->pdf_subject, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if (TIFFGetField(input, TIFFTAG_IMAGEDESCRIPTION, &info) != 0 && info) { if (strlen(info) >= sizeof(t2p->pdf_subject)) info[sizeof(t2p->pdf_subject) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) "/Subject ", 9); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_keywords[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Keywords ", 10); written += t2p_write_pdf_string(t2p->pdf_keywords, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } written += t2pWriteFile(output, (tdata_t) ">> \n", 4); return(written); } /* * This function fills a string of a T2P struct with the current time as a PDF * date string, it is called by t2p_pdf_tifftime. */ void t2p_pdf_currenttime(T2P* t2p) { struct tm* currenttime; time_t timenow; if (time(&timenow) == (time_t) -1) { TIFFError(TIFF2PDF_MODULE, "Can't get the current time: %s", strerror(errno)); timenow = (time_t) 0; } currenttime = localtime(&timenow); snprintf(t2p->pdf_datetime, sizeof(t2p->pdf_datetime), "D:%.4d%.2d%.2d%.2d%.2d%.2d", (currenttime->tm_year + 1900) % 65536, (currenttime->tm_mon + 1) % 256, (currenttime->tm_mday) % 256, (currenttime->tm_hour) % 256, (currenttime->tm_min) % 256, (currenttime->tm_sec) % 256); return; } /* * This function fills a string of a T2P struct with the date and time of a * TIFF file if it exists or the current time as a PDF date string. */ void t2p_pdf_tifftime(T2P* t2p, TIFF* input) { char* datetime; if (TIFFGetField(input, TIFFTAG_DATETIME, &datetime) != 0 && (strlen(datetime) >= 19) ){ t2p->pdf_datetime[0]='D'; t2p->pdf_datetime[1]=':'; t2p->pdf_datetime[2]=datetime[0]; t2p->pdf_datetime[3]=datetime[1]; t2p->pdf_datetime[4]=datetime[2]; t2p->pdf_datetime[5]=datetime[3]; t2p->pdf_datetime[6]=datetime[5]; t2p->pdf_datetime[7]=datetime[6]; t2p->pdf_datetime[8]=datetime[8]; t2p->pdf_datetime[9]=datetime[9]; t2p->pdf_datetime[10]=datetime[11]; t2p->pdf_datetime[11]=datetime[12]; t2p->pdf_datetime[12]=datetime[14]; t2p->pdf_datetime[13]=datetime[15]; t2p->pdf_datetime[14]=datetime[17]; t2p->pdf_datetime[15]=datetime[18]; t2p->pdf_datetime[16] = '\0'; } else { t2p_pdf_currenttime(t2p); } return; } /* * This function writes a PDF Pages Tree structure to output. */ tsize_t t2p_write_pdf_pages(T2P* t2p, TIFF* output) { tsize_t written=0; tdir_t i=0; char buffer[16]; int buflen=0; int page=0; written += t2pWriteFile(output, (tdata_t) "<< \n/Type /Pages \n/Kids [ ", 26); page = t2p->pdf_pages+1; for (i=0;i<t2p->tiff_pagecount;i++){ buflen=sprintf(buffer, "%d", page); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); if ( ((i+1)%8)==0 ) { written += t2pWriteFile(output, (tdata_t) "\n", 1); } page +=3; page += t2p->tiff_pages[i].page_extra; if(t2p->tiff_pages[i].page_tilecount>0){ page += (2 * t2p->tiff_pages[i].page_tilecount); } else { page +=2; } } written += t2pWriteFile(output, (tdata_t) "] \n/Count ", 10); _TIFFmemset(buffer, 0x00, 16); buflen=sprintf(buffer, "%d", t2p->tiff_pagecount); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " \n>> \n", 6); return(written); } /* This function writes a PDF Page structure to output. */ tsize_t t2p_write_pdf_page(uint32 object, T2P* t2p, TIFF* output){ unsigned int i=0; tsize_t written=0; char buffer[16]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "<<\n/Type /Page \n/Parent ", 24); buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_pages); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); written += t2pWriteFile(output, (tdata_t) "/MediaBox [", 11); buflen=sprintf(buffer, "%.4f",t2p->pdf_mediabox.x1); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen=sprintf(buffer, "%.4f",t2p->pdf_mediabox.y1); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen=sprintf(buffer, "%.4f",t2p->pdf_mediabox.x2); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen=sprintf(buffer, "%.4f",t2p->pdf_mediabox.y2); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "] \n", 3); written += t2pWriteFile(output, (tdata_t) "/Contents ", 10); buflen=sprintf(buffer, "%lu", (unsigned long)(object + 1)); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); written += t2pWriteFile(output, (tdata_t) "/Resources << \n", 15); if( t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount != 0 ){ written += t2pWriteFile(output, (tdata_t) "/XObject <<\n", 12); for(i=0;i<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount;i++){ written += t2pWriteFile(output, (tdata_t) "/Im", 3); buflen = sprintf(buffer, "%u", t2p->pdf_page+1); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "_", 1); buflen = sprintf(buffer, "%u", i+1); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen = sprintf( buffer, "%lu", (unsigned long)(object+3+(2*i)+t2p->tiff_pages[t2p->pdf_page].page_extra)); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); if(i%4==3){ written += t2pWriteFile(output, (tdata_t) "\n", 1); } } written += t2pWriteFile(output, (tdata_t) ">>\n", 3); } else { written += t2pWriteFile(output, (tdata_t) "/XObject <<\n", 12); written += t2pWriteFile(output, (tdata_t) "/Im", 3); buflen = sprintf(buffer, "%u", t2p->pdf_page+1); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen = sprintf( buffer, "%lu", (unsigned long)(object+3+(2*i)+t2p->tiff_pages[t2p->pdf_page].page_extra)); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); written += t2pWriteFile(output, (tdata_t) ">>\n", 3); } if(t2p->tiff_transferfunctioncount != 0) { written += t2pWriteFile(output, (tdata_t) "/ExtGState <<", 13); t2pWriteFile(output, (tdata_t) "/GS1 ", 5); buflen = sprintf( buffer, "%lu", (unsigned long)(object + 3)); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); written += t2pWriteFile(output, (tdata_t) ">> \n", 4); } written += t2pWriteFile(output, (tdata_t) "/ProcSet [ ", 11); if(t2p->pdf_colorspace == T2P_CS_BILEVEL || t2p->pdf_colorspace == T2P_CS_GRAY ){ written += t2pWriteFile(output, (tdata_t) "/ImageB ", 8); } else { written += t2pWriteFile(output, (tdata_t) "/ImageC ", 8); if(t2p->pdf_colorspace & T2P_CS_PALETTE){ written += t2pWriteFile(output, (tdata_t) "/ImageI ", 8); } } written += t2pWriteFile(output, (tdata_t) "]\n>>\n>>\n", 8); return(written); } /* This function composes the page size and image and tile locations on a page. */ void t2p_compose_pdf_page(T2P* t2p){ uint32 i=0; uint32 i2=0; T2P_TILE* tiles=NULL; T2P_BOX* boxp=NULL; uint32 tilecountx=0; uint32 tilecounty=0; uint32 tilewidth=0; uint32 tilelength=0; int istiled=0; float f=0; t2p->pdf_xres = t2p->tiff_xres; t2p->pdf_yres = t2p->tiff_yres; if(t2p->pdf_overrideres) { t2p->pdf_xres = t2p->pdf_defaultxres; t2p->pdf_yres = t2p->pdf_defaultyres; } if(t2p->pdf_xres == 0.0) t2p->pdf_xres = t2p->pdf_defaultxres; if(t2p->pdf_yres == 0.0) t2p->pdf_yres = t2p->pdf_defaultyres; if (t2p->tiff_resunit != RESUNIT_CENTIMETER /* RESUNIT_NONE and */ && t2p->tiff_resunit != RESUNIT_INCH) { /* other cases */ t2p->pdf_imagewidth = ((float)(t2p->tiff_width))/t2p->pdf_xres; t2p->pdf_imagelength = ((float)(t2p->tiff_length))/t2p->pdf_yres; } else { t2p->pdf_imagewidth = ((float)(t2p->tiff_width))*PS_UNIT_SIZE/t2p->pdf_xres; t2p->pdf_imagelength = ((float)(t2p->tiff_length))*PS_UNIT_SIZE/t2p->pdf_yres; } if(t2p->pdf_overridepagesize != 0) { t2p->pdf_pagewidth = t2p->pdf_defaultpagewidth; t2p->pdf_pagelength = t2p->pdf_defaultpagelength; } else { t2p->pdf_pagewidth = t2p->pdf_imagewidth; t2p->pdf_pagelength = t2p->pdf_imagelength; } t2p->pdf_mediabox.x1=0.0; t2p->pdf_mediabox.y1=0.0; t2p->pdf_mediabox.x2=t2p->pdf_pagewidth; t2p->pdf_mediabox.y2=t2p->pdf_pagelength; t2p->pdf_imagebox.x1=0.0; t2p->pdf_imagebox.y1=0.0; t2p->pdf_imagebox.x2=t2p->pdf_imagewidth; t2p->pdf_imagebox.y2=t2p->pdf_imagelength; if(t2p->pdf_overridepagesize!=0){ t2p->pdf_imagebox.x1+=((t2p->pdf_pagewidth-t2p->pdf_imagewidth)/2.0F); t2p->pdf_imagebox.y1+=((t2p->pdf_pagelength-t2p->pdf_imagelength)/2.0F); t2p->pdf_imagebox.x2+=((t2p->pdf_pagewidth-t2p->pdf_imagewidth)/2.0F); t2p->pdf_imagebox.y2+=((t2p->pdf_pagelength-t2p->pdf_imagelength)/2.0F); } if(t2p->tiff_orientation > 4){ f=t2p->pdf_mediabox.x2; t2p->pdf_mediabox.x2=t2p->pdf_mediabox.y2; t2p->pdf_mediabox.y2=f; } istiled=((t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount==0) ? 0 : 1; if(istiled==0){ t2p_compose_pdf_page_orient(&(t2p->pdf_imagebox), t2p->tiff_orientation); return; } else { tilewidth=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilewidth; tilelength=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilelength; tilecountx=(t2p->tiff_width + tilewidth -1)/ tilewidth; (t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecountx=tilecountx; tilecounty=(t2p->tiff_length + tilelength -1)/ tilelength; (t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecounty=tilecounty; (t2p->tiff_tiles[t2p->pdf_page]).tiles_edgetilewidth= t2p->tiff_width % tilewidth; (t2p->tiff_tiles[t2p->pdf_page]).tiles_edgetilelength= t2p->tiff_length % tilelength; tiles=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tiles; for(i2=0;i2<tilecounty-1;i2++){ for(i=0;i<tilecountx-1;i++){ boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * (i+1) * tilewidth) / (float)t2p->tiff_width); boxp->y1 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * (i2+1) * tilelength) / (float)t2p->tiff_length); boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x2; boxp->y1 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * (i2+1) * tilelength) / (float)t2p->tiff_length); boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } for(i=0;i<tilecountx-1;i++){ boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * (i+1) * tilewidth) / (float)t2p->tiff_width); boxp->y1 = t2p->pdf_imagebox.y1; boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x2; boxp->y1 = t2p->pdf_imagebox.y1; boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } if(t2p->tiff_orientation==0 || t2p->tiff_orientation==1){ for(i=0;i<(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount;i++){ t2p_compose_pdf_page_orient( &(tiles[i].tile_box) , 0); } return; } for(i=0;i<(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount;i++){ boxp=&(tiles[i].tile_box); boxp->x1 -= t2p->pdf_imagebox.x1; boxp->x2 -= t2p->pdf_imagebox.x1; boxp->y1 -= t2p->pdf_imagebox.y1; boxp->y2 -= t2p->pdf_imagebox.y1; if(t2p->tiff_orientation==2 || t2p->tiff_orientation==3){ boxp->x1 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x1; boxp->x2 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x2; } if(t2p->tiff_orientation==3 || t2p->tiff_orientation==4){ boxp->y1 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y1; boxp->y2 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y2; } if(t2p->tiff_orientation==8 || t2p->tiff_orientation==5){ boxp->y1 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y1; boxp->y2 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y2; } if(t2p->tiff_orientation==5 || t2p->tiff_orientation==6){ boxp->x1 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x1; boxp->x2 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x2; } if(t2p->tiff_orientation > 4){ f=boxp->x1; boxp->x1 = boxp->y1; boxp->y1 = f; f=boxp->x2; boxp->x2 = boxp->y2; boxp->y2 = f; t2p_compose_pdf_page_orient_flip(boxp, t2p->tiff_orientation); } else { t2p_compose_pdf_page_orient(boxp, t2p->tiff_orientation); } } return; } void t2p_compose_pdf_page_orient(T2P_BOX* boxp, uint16 orientation){ float m1[9]; float f=0.0; if( boxp->x1 > boxp->x2){ f=boxp->x1; boxp->x1=boxp->x2; boxp->x2 = f; } if( boxp->y1 > boxp->y2){ f=boxp->y1; boxp->y1=boxp->y2; boxp->y2 = f; } boxp->mat[0]=m1[0]=boxp->x2-boxp->x1; boxp->mat[1]=m1[1]=0.0; boxp->mat[2]=m1[2]=0.0; boxp->mat[3]=m1[3]=0.0; boxp->mat[4]=m1[4]=boxp->y2-boxp->y1; boxp->mat[5]=m1[5]=0.0; boxp->mat[6]=m1[6]=boxp->x1; boxp->mat[7]=m1[7]=boxp->y1; boxp->mat[8]=m1[8]=1.0; switch(orientation){ case 0: case 1: break; case 2: boxp->mat[0]=0.0F-m1[0]; boxp->mat[6]+=m1[0]; break; case 3: boxp->mat[0]=0.0F-m1[0]; boxp->mat[4]=0.0F-m1[4]; boxp->mat[6]+=m1[0]; boxp->mat[7]+=m1[4]; break; case 4: boxp->mat[4]=0.0F-m1[4]; boxp->mat[7]+=m1[4]; break; case 5: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[0]; boxp->mat[3]=0.0F-m1[4]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[4]; boxp->mat[7]+=m1[0]; break; case 6: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[0]; boxp->mat[3]=m1[4]; boxp->mat[4]=0.0F; boxp->mat[7]+=m1[0]; break; case 7: boxp->mat[0]=0.0F; boxp->mat[1]=m1[0]; boxp->mat[3]=m1[4]; boxp->mat[4]=0.0F; break; case 8: boxp->mat[0]=0.0F; boxp->mat[1]=m1[0]; boxp->mat[3]=0.0F-m1[4]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[4]; break; } return; } void t2p_compose_pdf_page_orient_flip(T2P_BOX* boxp, uint16 orientation){ float m1[9]; float f=0.0; if( boxp->x1 > boxp->x2){ f=boxp->x1; boxp->x1=boxp->x2; boxp->x2 = f; } if( boxp->y1 > boxp->y2){ f=boxp->y1; boxp->y1=boxp->y2; boxp->y2 = f; } boxp->mat[0]=m1[0]=boxp->x2-boxp->x1; boxp->mat[1]=m1[1]=0.0F; boxp->mat[2]=m1[2]=0.0F; boxp->mat[3]=m1[3]=0.0F; boxp->mat[4]=m1[4]=boxp->y2-boxp->y1; boxp->mat[5]=m1[5]=0.0F; boxp->mat[6]=m1[6]=boxp->x1; boxp->mat[7]=m1[7]=boxp->y1; boxp->mat[8]=m1[8]=1.0F; switch(orientation){ case 5: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[4]; boxp->mat[3]=0.0F-m1[0]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[0]; boxp->mat[7]+=m1[4]; break; case 6: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[4]; boxp->mat[3]=m1[0]; boxp->mat[4]=0.0F; boxp->mat[7]+=m1[4]; break; case 7: boxp->mat[0]=0.0F; boxp->mat[1]=m1[4]; boxp->mat[3]=m1[0]; boxp->mat[4]=0.0F; break; case 8: boxp->mat[0]=0.0F; boxp->mat[1]=m1[4]; boxp->mat[3]=0.0F-m1[0]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[0]; break; } return; } /* This function writes a PDF Contents stream to output. */ tsize_t t2p_write_pdf_page_content_stream(T2P* t2p, TIFF* output){ tsize_t written=0; ttile_t i=0; char buffer[512]; int buflen=0; T2P_BOX box; if(t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount>0){ for(i=0;i<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount; i++){ box=t2p->tiff_tiles[t2p->pdf_page].tiles_tiles[i].tile_box; buflen=sprintf(buffer, "q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%d_%ld Do Q\n", t2p->tiff_transferfunctioncount?"/GS1 gs ":"", box.mat[0], box.mat[1], box.mat[3], box.mat[4], box.mat[6], box.mat[7], t2p->pdf_page + 1, (long)(i + 1)); written += t2p_write_pdf_stream(buffer, buflen, output); } } else { box=t2p->pdf_imagebox; buflen=sprintf(buffer, "q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%d Do Q\n", t2p->tiff_transferfunctioncount?"/GS1 gs ":"", box.mat[0], box.mat[1], box.mat[3], box.mat[4], box.mat[6], box.mat[7], t2p->pdf_page+1); written += t2p_write_pdf_stream(buffer, buflen, output); } return(written); } /* This function writes a PDF Image XObject stream dictionary to output. */ tsize_t t2p_write_pdf_xobject_stream_dict(ttile_t tile, T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; written += t2p_write_pdf_stream_dict(0, t2p->pdf_xrefcount+1, output); written += t2pWriteFile(output, (tdata_t) "/Type /XObject \n/Subtype /Image \n/Name /Im", 42); buflen=sprintf(buffer, "%u", t2p->pdf_page+1); written += t2pWriteFile(output, (tdata_t) buffer, buflen); if(tile != 0){ written += t2pWriteFile(output, (tdata_t) "_", 1); buflen=sprintf(buffer, "%lu", (unsigned long)tile); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } written += t2pWriteFile(output, (tdata_t) "\n/Width ", 8); _TIFFmemset((tdata_t)buffer, 0x00, 16); if(tile==0){ buflen=sprintf(buffer, "%lu", (unsigned long)t2p->tiff_width); } else { if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)!=0){ buflen=sprintf( buffer, "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth); } else { buflen=sprintf( buffer, "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth); } } written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n/Height ", 9); _TIFFmemset((tdata_t)buffer, 0x00, 16); if(tile==0){ buflen=sprintf(buffer, "%lu", (unsigned long)t2p->tiff_length); } else { if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)!=0){ buflen=sprintf( buffer, "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); } else { buflen=sprintf( buffer, "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } } written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n/BitsPerComponent ", 19); _TIFFmemset((tdata_t)buffer, 0x00, 16); buflen=sprintf(buffer, "%u", t2p->tiff_bitspersample); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n/ColorSpace ", 13); written += t2p_write_pdf_xobject_cs(t2p, output); if (t2p->pdf_image_interpolate) written += t2pWriteFile(output, (tdata_t) "\n/Interpolate true", 18); if( (t2p->pdf_switchdecode != 0) #ifdef CCITT_SUPPORT && ! (t2p->pdf_colorspace == T2P_CS_BILEVEL && t2p->pdf_compression == T2P_COMPRESS_G4) #endif ){ written += t2p_write_pdf_xobject_decode(t2p, output); } written += t2p_write_pdf_xobject_stream_filter(tile, t2p, output); return(written); } /* * This function writes a PDF Image XObject Colorspace name to output. */ tsize_t t2p_write_pdf_xobject_cs(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[128]; int buflen=0; float X_W=1.0; float Y_W=1.0; float Z_W=1.0; if( (t2p->pdf_colorspace & T2P_CS_ICCBASED) != 0){ written += t2p_write_pdf_xobject_icccs(t2p, output); return(written); } if( (t2p->pdf_colorspace & T2P_CS_PALETTE) != 0){ written += t2pWriteFile(output, (tdata_t) "[ /Indexed ", 11); t2p->pdf_colorspace ^= T2P_CS_PALETTE; written += t2p_write_pdf_xobject_cs(t2p, output); t2p->pdf_colorspace |= T2P_CS_PALETTE; buflen=sprintf(buffer, "%u", (0x0001 << t2p->tiff_bitspersample)-1 ); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); _TIFFmemset(buffer, 0x00, 16); buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_palettecs ); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ]\n", 7); return(written); } if(t2p->pdf_colorspace & T2P_CS_BILEVEL){ written += t2pWriteFile(output, (tdata_t) "/DeviceGray \n", 13); } if(t2p->pdf_colorspace & T2P_CS_GRAY){ if(t2p->pdf_colorspace & T2P_CS_CALGRAY){ written += t2p_write_pdf_xobject_calcs(t2p, output); } else { written += t2pWriteFile(output, (tdata_t) "/DeviceGray \n", 13); } } if(t2p->pdf_colorspace & T2P_CS_RGB){ if(t2p->pdf_colorspace & T2P_CS_CALRGB){ written += t2p_write_pdf_xobject_calcs(t2p, output); } else { written += t2pWriteFile(output, (tdata_t) "/DeviceRGB \n", 12); } } if(t2p->pdf_colorspace & T2P_CS_CMYK){ written += t2pWriteFile(output, (tdata_t) "/DeviceCMYK \n", 13); } if(t2p->pdf_colorspace & T2P_CS_LAB){ written += t2pWriteFile(output, (tdata_t) "[/Lab << \n", 10); written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12); X_W = t2p->tiff_whitechromaticities[0]; Y_W = t2p->tiff_whitechromaticities[1]; Z_W = 1.0F - (X_W + Y_W); X_W /= Y_W; Z_W /= Y_W; Y_W = 1.0F; buflen=sprintf(buffer, "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W); written += t2pWriteFile(output, (tdata_t) buffer, buflen); X_W = 0.3457F; /* 0.3127F; */ /* D50, commented D65 */ Y_W = 0.3585F; /* 0.3290F; */ Z_W = 1.0F - (X_W + Y_W); X_W /= Y_W; Z_W /= Y_W; Y_W = 1.0F; buflen=sprintf(buffer, "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Range ", 7); buflen=sprintf(buffer, "[%d %d %d %d] \n", t2p->pdf_labrange[0], t2p->pdf_labrange[1], t2p->pdf_labrange[2], t2p->pdf_labrange[3]); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) ">>] \n", 5); } return(written); } tsize_t t2p_write_pdf_transfer(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "<< /Type /ExtGState \n/TR ", 25); if(t2p->tiff_transferfunctioncount == 1){ buflen=sprintf(buffer, "%lu", (unsigned long)(t2p->pdf_xrefcount + 1)); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); } else { written += t2pWriteFile(output, (tdata_t) "[ ", 2); buflen=sprintf(buffer, "%lu", (unsigned long)(t2p->pdf_xrefcount + 1)); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); buflen=sprintf(buffer, "%lu", (unsigned long)(t2p->pdf_xrefcount + 2)); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); buflen=sprintf(buffer, "%lu", (unsigned long)(t2p->pdf_xrefcount + 3)); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); written += t2pWriteFile(output, (tdata_t) "/Identity ] ", 12); } written += t2pWriteFile(output, (tdata_t) " >> \n", 5); return(written); } tsize_t t2p_write_pdf_transfer_dict(T2P* t2p, TIFF* output, uint16 i){ tsize_t written=0; char buffer[32]; int buflen=0; (void)i; /* XXX */ written += t2pWriteFile(output, (tdata_t) "/FunctionType 0 \n", 17); written += t2pWriteFile(output, (tdata_t) "/Domain [0.0 1.0] \n", 19); written += t2pWriteFile(output, (tdata_t) "/Range [0.0 1.0] \n", 18); buflen=sprintf(buffer, "/Size [%u] \n", (1<<t2p->tiff_bitspersample)); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/BitsPerSample 16 \n", 19); written += t2p_write_pdf_stream_dict(((tsize_t)1)<<(t2p->tiff_bitspersample+1), 0, output); return(written); } tsize_t t2p_write_pdf_transfer_stream(T2P* t2p, TIFF* output, uint16 i){ tsize_t written=0; written += t2p_write_pdf_stream( t2p->tiff_transferfunction[i], (((tsize_t)1)<<(t2p->tiff_bitspersample+1)), output); return(written); } /* This function writes a PDF Image XObject Colorspace array to output. */ tsize_t t2p_write_pdf_xobject_calcs(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[128]; int buflen=0; float X_W=0.0; float Y_W=0.0; float Z_W=0.0; float X_R=0.0; float Y_R=0.0; float Z_R=0.0; float X_G=0.0; float Y_G=0.0; float Z_G=0.0; float X_B=0.0; float Y_B=0.0; float Z_B=0.0; float x_w=0.0; float y_w=0.0; float z_w=0.0; float x_r=0.0; float y_r=0.0; float x_g=0.0; float y_g=0.0; float x_b=0.0; float y_b=0.0; float R=1.0; float G=1.0; float B=1.0; written += t2pWriteFile(output, (tdata_t) "[", 1); if(t2p->pdf_colorspace & T2P_CS_CALGRAY){ written += t2pWriteFile(output, (tdata_t) "/CalGray ", 9); X_W = t2p->tiff_whitechromaticities[0]; Y_W = t2p->tiff_whitechromaticities[1]; Z_W = 1.0F - (X_W + Y_W); X_W /= Y_W; Z_W /= Y_W; Y_W = 1.0F; } if(t2p->pdf_colorspace & T2P_CS_CALRGB){ written += t2pWriteFile(output, (tdata_t) "/CalRGB ", 8); x_w = t2p->tiff_whitechromaticities[0]; y_w = t2p->tiff_whitechromaticities[1]; x_r = t2p->tiff_primarychromaticities[0]; y_r = t2p->tiff_primarychromaticities[1]; x_g = t2p->tiff_primarychromaticities[2]; y_g = t2p->tiff_primarychromaticities[3]; x_b = t2p->tiff_primarychromaticities[4]; y_b = t2p->tiff_primarychromaticities[5]; z_w = y_w * ((x_g - x_b)*y_r - (x_r-x_b)*y_g + (x_r-x_g)*y_b); Y_R = (y_r/R) * ((x_g-x_b)*y_w - (x_w-x_b)*y_g + (x_w-x_g)*y_b) / z_w; X_R = Y_R * x_r / y_r; Z_R = Y_R * (((1-x_r)/y_r)-1); Y_G = ((0.0F-(y_g))/G) * ((x_r-x_b)*y_w - (x_w-x_b)*y_r + (x_w-x_r)*y_b) / z_w; X_G = Y_G * x_g / y_g; Z_G = Y_G * (((1-x_g)/y_g)-1); Y_B = (y_b/B) * ((x_r-x_g)*y_w - (x_w-x_g)*y_r + (x_w-x_r)*y_g) / z_w; X_B = Y_B * x_b / y_b; Z_B = Y_B * (((1-x_b)/y_b)-1); X_W = (X_R * R) + (X_G * G) + (X_B * B); Y_W = (Y_R * R) + (Y_G * G) + (Y_B * B); Z_W = (Z_R * R) + (Z_G * G) + (Z_B * B); X_W /= Y_W; Z_W /= Y_W; Y_W = 1.0; } written += t2pWriteFile(output, (tdata_t) "<< \n", 4); if(t2p->pdf_colorspace & T2P_CS_CALGRAY){ written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12); buflen=sprintf(buffer, "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Gamma 2.2 \n", 12); } if(t2p->pdf_colorspace & T2P_CS_CALRGB){ written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12); buflen=sprintf(buffer, "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Matrix ", 8); buflen=sprintf(buffer, "[%.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f] \n", X_R, Y_R, Z_R, X_G, Y_G, Z_G, X_B, Y_B, Z_B); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Gamma [2.2 2.2 2.2] \n", 22); } written += t2pWriteFile(output, (tdata_t) ">>] \n", 5); return(written); } /* This function writes a PDF Image XObject Colorspace array to output. */ tsize_t t2p_write_pdf_xobject_icccs(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "[/ICCBased ", 11); buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_icccs); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R] \n", 7); return(written); } tsize_t t2p_write_pdf_xobject_icccs_dict(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "/N ", 3); buflen=sprintf(buffer, "%u \n", t2p->tiff_samplesperpixel); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Alternate ", 11); t2p->pdf_colorspace ^= T2P_CS_ICCBASED; written += t2p_write_pdf_xobject_cs(t2p, output); t2p->pdf_colorspace |= T2P_CS_ICCBASED; written += t2p_write_pdf_stream_dict(t2p->tiff_iccprofilelength, 0, output); return(written); } tsize_t t2p_write_pdf_xobject_icccs_stream(T2P* t2p, TIFF* output){ tsize_t written=0; written += t2p_write_pdf_stream( (tdata_t) t2p->tiff_iccprofile, (tsize_t) t2p->tiff_iccprofilelength, output); return(written); } /* This function writes a palette stream for an indexed color space to output. */ tsize_t t2p_write_pdf_xobject_palettecs_stream(T2P* t2p, TIFF* output){ tsize_t written=0; written += t2p_write_pdf_stream( (tdata_t) t2p->pdf_palette, (tsize_t) t2p->pdf_palettesize, output); return(written); } /* This function writes a PDF Image XObject Decode array to output. */ tsize_t t2p_write_pdf_xobject_decode(T2P* t2p, TIFF* output){ tsize_t written=0; int i=0; written += t2pWriteFile(output, (tdata_t) "/Decode [ ", 10); for (i=0;i<t2p->tiff_samplesperpixel;i++){ written += t2pWriteFile(output, (tdata_t) "1 0 ", 4); } written += t2pWriteFile(output, (tdata_t) "]\n", 2); return(written); } /* This function writes a PDF Image XObject stream filter name and parameters to output. */ tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t tile, T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; if(t2p->pdf_compression==T2P_COMPRESS_NONE){ return(written); } written += t2pWriteFile(output, (tdata_t) "/Filter ", 8); switch(t2p->pdf_compression){ #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: written += t2pWriteFile(output, (tdata_t) "/CCITTFaxDecode ", 16); written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13); written += t2pWriteFile(output, (tdata_t) "<< /K -1 ", 9); if(tile==0){ written += t2pWriteFile(output, (tdata_t) "/Columns ", 9); buflen=sprintf(buffer, "%lu", (unsigned long)t2p->tiff_width); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /Rows ", 7); buflen=sprintf(buffer, "%lu", (unsigned long)t2p->tiff_length); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } else { if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){ written += t2pWriteFile(output, (tdata_t) "/Columns ", 9); buflen=sprintf( buffer, "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } else { written += t2pWriteFile(output, (tdata_t) "/Columns ", 9); buflen=sprintf( buffer, "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){ written += t2pWriteFile(output, (tdata_t) " /Rows ", 7); buflen=sprintf( buffer, "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } else { written += t2pWriteFile(output, (tdata_t) " /Rows ", 7); buflen=sprintf( buffer, "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } } if(t2p->pdf_switchdecode == 0){ written += t2pWriteFile(output, (tdata_t) " /BlackIs1 true ", 16); } written += t2pWriteFile(output, (tdata_t) ">>\n", 3); break; #endif #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: written += t2pWriteFile(output, (tdata_t) "/DCTDecode ", 11); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR) { written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13); written += t2pWriteFile(output, (tdata_t) "<< /ColorTransform 0 >>\n", 24); } break; #endif #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: written += t2pWriteFile(output, (tdata_t) "/FlateDecode ", 13); if(t2p->pdf_compressionquality%100){ written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13); written += t2pWriteFile(output, (tdata_t) "<< /Predictor ", 14); _TIFFmemset(buffer, 0x00, 16); buflen=sprintf(buffer, "%u", t2p->pdf_compressionquality%100); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /Columns ", 10); _TIFFmemset(buffer, 0x00, 16); buflen = sprintf(buffer, "%lu", (unsigned long)t2p->tiff_width); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /Colors ", 9); _TIFFmemset(buffer, 0x00, 16); buflen=sprintf(buffer, "%u", t2p->tiff_samplesperpixel); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /BitsPerComponent ", 19); _TIFFmemset(buffer, 0x00, 16); buflen=sprintf(buffer, "%u", t2p->tiff_bitspersample); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) ">>\n", 3); } break; #endif default: break; } return(written); } /* This function writes a PDF xref table to output. */ tsize_t t2p_write_pdf_xreftable(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[21]; int buflen=0; uint32 i=0; written += t2pWriteFile(output, (tdata_t) "xref\n0 ", 7); buflen=sprintf(buffer, "%lu", (unsigned long)(t2p->pdf_xrefcount + 1)); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " \n0000000000 65535 f \n", 22); for (i=0;i<t2p->pdf_xrefcount;i++){ sprintf(buffer, "%.10lu 00000 n \n", (unsigned long)t2p->pdf_xrefoffsets[i]); written += t2pWriteFile(output, (tdata_t) buffer, 20); } return(written); } /* * This function writes a PDF trailer to output. */ tsize_t t2p_write_pdf_trailer(T2P* t2p, TIFF* output) { tsize_t written = 0; char buffer[32]; int buflen = 0; size_t i = 0; for (i = 0; i < sizeof(t2p->pdf_fileid) - 8; i += 8) snprintf(t2p->pdf_fileid + i, 9, "%.8X", rand()); written += t2pWriteFile(output, (tdata_t) "trailer\n<<\n/Size ", 17); buflen = sprintf(buffer, "%lu", (unsigned long)(t2p->pdf_xrefcount+1)); written += t2pWriteFile(output, (tdata_t) buffer, buflen); _TIFFmemset(buffer, 0x00, 32); written += t2pWriteFile(output, (tdata_t) "\n/Root ", 7); buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_catalog); written += t2pWriteFile(output, (tdata_t) buffer, buflen); _TIFFmemset(buffer, 0x00, 32); written += t2pWriteFile(output, (tdata_t) " 0 R \n/Info ", 12); buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_info); written += t2pWriteFile(output, (tdata_t) buffer, buflen); _TIFFmemset(buffer, 0x00, 32); written += t2pWriteFile(output, (tdata_t) " 0 R \n/ID[<", 11); written += t2pWriteFile(output, (tdata_t) t2p->pdf_fileid, sizeof(t2p->pdf_fileid) - 1); written += t2pWriteFile(output, (tdata_t) "><", 2); written += t2pWriteFile(output, (tdata_t) t2p->pdf_fileid, sizeof(t2p->pdf_fileid) - 1); written += t2pWriteFile(output, (tdata_t) ">]\n>>\nstartxref\n", 16); buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_startxref); written += t2pWriteFile(output, (tdata_t) buffer, buflen); _TIFFmemset(buffer, 0x00, 32); written += t2pWriteFile(output, (tdata_t) "\n%%EOF\n", 7); return(written); } /* This function writes a PDF to a file given a pointer to a TIFF. The idea with using a TIFF* as output for a PDF file is that the file can be created with TIFFClientOpen for memory-mapped use within the TIFF library, and TIFFWriteEncodedStrip can be used to write compressed data to the output. The output is not actually a TIFF file, it is a PDF file. This function uses only t2pWriteFile and TIFFWriteEncodedStrip to write to the output TIFF file. When libtiff would otherwise be writing data to the output file, the write procedure of the TIFF structure is replaced with an empty implementation. The first argument to the function is an initialized and validated T2P context struct pointer. The second argument to the function is the TIFF* that is the input that has been opened for reading and no other functions have been called upon it. The third argument to the function is the TIFF* that is the output that has been opened for writing. It has to be opened so that it hasn't written any data to the output. If the output is seekable then it's OK to seek to the beginning of the file. The function only writes to the output PDF and does not seek. See the example usage in the main() function. TIFF* output = TIFFOpen("output.pdf", "w"); assert(output != NULL); if(output->tif_seekproc != NULL){ t2pSeekFile(output, (toff_t) 0, SEEK_SET); } This function returns the file size of the output PDF file. On error it returns zero and the t2p->t2p_error variable is set to T2P_ERR_ERROR. After this function completes, call t2p_free on t2p, TIFFClose on input, and TIFFClose on output. */ tsize_t t2p_write_pdf(T2P* t2p, TIFF* input, TIFF* output){ tsize_t written=0; ttile_t i2=0; tsize_t streamlen=0; uint16 i=0; t2p_read_tiff_init(t2p, input); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} t2p->pdf_xrefoffsets= (uint32*) _TIFFmalloc(t2p->pdf_xrefcount * sizeof(uint32) ); if(t2p->pdf_xrefoffsets==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_write_pdf", (unsigned int) (t2p->pdf_xrefcount * sizeof(uint32)) ); return(written); } t2p->pdf_xrefcount=0; t2p->pdf_catalog=1; t2p->pdf_info=2; t2p->pdf_pages=3; written += t2p_write_pdf_header(t2p, output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_catalog=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_catalog(t2p, output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_info=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_info(t2p, input, output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_pages=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_pages(t2p, output); written += t2p_write_pdf_obj_end(output); for(t2p->pdf_page=0;t2p->pdf_page<t2p->tiff_pagecount;t2p->pdf_page++){ t2p_read_tiff_data(t2p, input); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_page(t2p->pdf_xrefcount, t2p, output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_stream_dict(0, t2p->pdf_xrefcount+1, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; written += t2p_write_pdf_page_content_stream(t2p, output); streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_length(streamlen, output); written += t2p_write_pdf_obj_end(output); if(t2p->tiff_transferfunctioncount != 0){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_transfer(t2p, output); written += t2p_write_pdf_obj_end(output); for(i=0; i < t2p->tiff_transferfunctioncount; i++){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_transfer_dict(t2p, output, i); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; written += t2p_write_pdf_transfer_stream(t2p, output, i); streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); } } if( (t2p->pdf_colorspace & T2P_CS_PALETTE) != 0){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_palettecs=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_stream_dict(t2p->pdf_palettesize, 0, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; written += t2p_write_pdf_xobject_palettecs_stream(t2p, output); streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); } if( (t2p->pdf_colorspace & T2P_CS_ICCBASED) != 0){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_icccs=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_xobject_icccs_dict(t2p, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; written += t2p_write_pdf_xobject_icccs_stream(t2p, output); streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); } if(t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount !=0){ for(i2=0;i2<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount;i2++){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_xobject_stream_dict( i2+1, t2p, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; t2p_read_tiff_size_tile(t2p, input, i2); written += t2p_readwrite_pdf_image_tile(t2p, input, output, i2); t2p_write_advance_directory(t2p, output); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_length(streamlen, output); written += t2p_write_pdf_obj_end(output); } } else { t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_xobject_stream_dict( 0, t2p, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; t2p_read_tiff_size(t2p, input); written += t2p_readwrite_pdf_image(t2p, input, output); t2p_write_advance_directory(t2p, output); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_length(streamlen, output); written += t2p_write_pdf_obj_end(output); } } t2p->pdf_startxref = written; written += t2p_write_pdf_xreftable(t2p, output); written += t2p_write_pdf_trailer(t2p, output); t2p_disable(output); return(written); } /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */ /* $Id$ * * tiff2pdf - converts a TIFF image to a PDF document * * Copyright (c) 2003 Ross Finlayson * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the name of * Ross Finlayson may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Ross Finlayson. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL ROSS FINLAYSON BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ #include "tif_config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <time.h> #include <errno.h> #if HAVE_UNISTD_H # include <unistd.h> #endif #ifdef HAVE_FCNTL_H # include <fcntl.h> #endif #ifdef HAVE_IO_H # include <io.h> #endif #ifdef NEED_LIBPORT # include "libport.h" #endif #include "tiffiop.h" #include "tiffio.h" #ifndef HAVE_GETOPT extern int getopt(int, char**, char*); #endif #ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 #endif #ifndef EXIT_FAILURE # define EXIT_FAILURE 1 #endif #define TIFF2PDF_MODULE "tiff2pdf" #define PS_UNIT_SIZE 72.0F /* This type is of PDF color spaces. */ typedef enum { T2P_CS_BILEVEL = 0x01, /* Bilevel, black and white */ T2P_CS_GRAY = 0x02, /* Single channel */ T2P_CS_RGB = 0x04, /* Three channel tristimulus RGB */ T2P_CS_CMYK = 0x08, /* Four channel CMYK print inkset */ T2P_CS_LAB = 0x10, /* Three channel L*a*b* color space */ T2P_CS_PALETTE = 0x1000,/* One of the above with a color map */ T2P_CS_CALGRAY = 0x20, /* Calibrated single channel */ T2P_CS_CALRGB = 0x40, /* Calibrated three channel tristimulus RGB */ T2P_CS_ICCBASED = 0x80 /* ICC profile color specification */ } t2p_cs_t; /* This type is of PDF compression types. */ typedef enum{ T2P_COMPRESS_NONE=0x00 #ifdef CCITT_SUPPORT , T2P_COMPRESS_G4=0x01 #endif #if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT) , T2P_COMPRESS_JPEG=0x02 #endif #ifdef ZIP_SUPPORT , T2P_COMPRESS_ZIP=0x04 #endif } t2p_compress_t; /* This type is whether TIFF image data can be used in PDF without transcoding. */ typedef enum{ T2P_TRANSCODE_RAW=0x01, /* The raw data from the input can be used without recompressing */ T2P_TRANSCODE_ENCODE=0x02 /* The data from the input is perhaps unencoded and reencoded */ } t2p_transcode_t; /* This type is of information about the data samples of the input image. */ typedef enum{ T2P_SAMPLE_NOTHING=0x0000, /* The unencoded samples are normal for the output colorspace */ T2P_SAMPLE_ABGR_TO_RGB=0x0001, /* The unencoded samples are the result of ReadRGBAImage */ T2P_SAMPLE_RGBA_TO_RGB=0x0002, /* The unencoded samples are contiguous RGBA */ T2P_SAMPLE_RGBAA_TO_RGB=0x0004, /* The unencoded samples are RGBA with premultiplied alpha */ T2P_SAMPLE_YCBCR_TO_RGB=0x0008, T2P_SAMPLE_YCBCR_TO_LAB=0x0010, T2P_SAMPLE_REALIZE_PALETTE=0x0020, /* The unencoded samples are indexes into the color map */ T2P_SAMPLE_SIGNED_TO_UNSIGNED=0x0040, /* The unencoded samples are signed instead of unsignd */ T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED=0x0040, /* The L*a*b* samples have a* and b* signed */ T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG=0x0100 /* The unencoded samples are separate instead of contiguous */ } t2p_sample_t; /* This type is of error status of the T2P struct. */ typedef enum{ T2P_ERR_OK = 0, /* This is the value of t2p->t2p_error when there is no error */ T2P_ERR_ERROR = 1 /* This is the value of t2p->t2p_error when there was an error */ } t2p_err_t; /* This struct defines a logical page of a TIFF. */ typedef struct { tdir_t page_directory; uint32 page_number; ttile_t page_tilecount; uint32 page_extra; } T2P_PAGE; /* This struct defines a PDF rectangle's coordinates. */ typedef struct { float x1; float y1; float x2; float y2; float mat[9]; } T2P_BOX; /* This struct defines a tile of a PDF. */ typedef struct { T2P_BOX tile_box; } T2P_TILE; /* This struct defines information about the tiles on a PDF page. */ typedef struct { ttile_t tiles_tilecount; uint32 tiles_tilewidth; uint32 tiles_tilelength; uint32 tiles_tilecountx; uint32 tiles_tilecounty; uint32 tiles_edgetilewidth; uint32 tiles_edgetilelength; T2P_TILE* tiles_tiles; } T2P_TILES; /* This struct is the context of a function to generate PDF from a TIFF. */ typedef struct { t2p_err_t t2p_error; T2P_PAGE* tiff_pages; T2P_TILES* tiff_tiles; tdir_t tiff_pagecount; uint16 tiff_compression; uint16 tiff_photometric; uint16 tiff_fillorder; uint16 tiff_bitspersample; uint16 tiff_samplesperpixel; uint16 tiff_planar; uint32 tiff_width; uint32 tiff_length; float tiff_xres; float tiff_yres; uint16 tiff_orientation; toff_t tiff_dataoffset; tsize_t tiff_datasize; uint16 tiff_resunit; uint16 pdf_centimeters; uint16 pdf_overrideres; uint16 pdf_overridepagesize; float pdf_defaultxres; float pdf_defaultyres; float pdf_xres; float pdf_yres; float pdf_defaultpagewidth; float pdf_defaultpagelength; float pdf_pagewidth; float pdf_pagelength; float pdf_imagewidth; float pdf_imagelength; T2P_BOX pdf_mediabox; T2P_BOX pdf_imagebox; uint16 pdf_majorversion; uint16 pdf_minorversion; uint32 pdf_catalog; uint32 pdf_pages; uint32 pdf_info; uint32 pdf_palettecs; uint16 pdf_fitwindow; uint32 pdf_startxref; #define TIFF2PDF_FILEID_SIZE 33 char pdf_fileid[TIFF2PDF_FILEID_SIZE]; #define TIFF2PDF_DATETIME_SIZE 17 char pdf_datetime[TIFF2PDF_DATETIME_SIZE]; #define TIFF2PDF_CREATOR_SIZE 512 char pdf_creator[TIFF2PDF_CREATOR_SIZE]; #define TIFF2PDF_AUTHOR_SIZE 512 char pdf_author[TIFF2PDF_AUTHOR_SIZE]; #define TIFF2PDF_TITLE_SIZE 512 char pdf_title[TIFF2PDF_TITLE_SIZE]; #define TIFF2PDF_SUBJECT_SIZE 512 char pdf_subject[TIFF2PDF_SUBJECT_SIZE]; #define TIFF2PDF_KEYWORDS_SIZE 512 char pdf_keywords[TIFF2PDF_KEYWORDS_SIZE]; t2p_cs_t pdf_colorspace; uint16 pdf_colorspace_invert; uint16 pdf_switchdecode; uint16 pdf_palettesize; unsigned char* pdf_palette; int pdf_labrange[4]; t2p_compress_t pdf_defaultcompression; uint16 pdf_defaultcompressionquality; t2p_compress_t pdf_compression; uint16 pdf_compressionquality; uint16 pdf_nopassthrough; t2p_transcode_t pdf_transcode; t2p_sample_t pdf_sample; uint32* pdf_xrefoffsets; uint32 pdf_xrefcount; tdir_t pdf_page; #ifdef OJPEG_SUPPORT tdata_t pdf_ojpegdata; uint32 pdf_ojpegdatalength; uint32 pdf_ojpegiflength; #endif float tiff_whitechromaticities[2]; float tiff_primarychromaticities[6]; float tiff_referenceblackwhite[2]; float* tiff_transferfunction[3]; int pdf_image_interpolate; /* 0 (default) : do not interpolate, 1 : interpolate */ uint16 tiff_transferfunctioncount; uint32 pdf_icccs; uint32 tiff_iccprofilelength; tdata_t tiff_iccprofile; /* fields for custom read/write procedures */ FILE *outputfile; int outputdisable; tsize_t outputwritten; } T2P; /* These functions are called by main. */ void tiff2pdf_usage(void); int tiff2pdf_match_paper_size(float*, float*, char*); /* These functions are used to generate a PDF from a TIFF. */ #ifdef __cplusplus extern "C" { #endif T2P* t2p_init(void); void t2p_validate(T2P*); tsize_t t2p_write_pdf(T2P*, TIFF*, TIFF*); void t2p_free(T2P*); #ifdef __cplusplus } #endif void t2p_read_tiff_init(T2P*, TIFF*); int t2p_cmp_t2p_page(const void*, const void*); void t2p_read_tiff_data(T2P*, TIFF*); void t2p_read_tiff_size(T2P*, TIFF*); void t2p_read_tiff_size_tile(T2P*, TIFF*, ttile_t); int t2p_tile_is_right_edge(T2P_TILES, ttile_t); int t2p_tile_is_bottom_edge(T2P_TILES, ttile_t); int t2p_tile_is_edge(T2P_TILES, ttile_t); int t2p_tile_is_corner_edge(T2P_TILES, ttile_t); tsize_t t2p_readwrite_pdf_image(T2P*, TIFF*, TIFF*); tsize_t t2p_readwrite_pdf_image_tile(T2P*, TIFF*, TIFF*, ttile_t); #ifdef OJPEG_SUPPORT int t2p_process_ojpeg_tables(T2P*, TIFF*); #endif #ifdef JPEG_SUPPORT int t2p_process_jpeg_strip(unsigned char*, tsize_t*, unsigned char*, tsize_t*, tstrip_t, uint32); #endif void t2p_tile_collapse_left(tdata_t, tsize_t, uint32, uint32, uint32); void t2p_write_advance_directory(T2P*, TIFF*); tsize_t t2p_sample_planar_separate_to_contig(T2P*, unsigned char*, unsigned char*, tsize_t); tsize_t t2p_sample_realize_palette(T2P*, unsigned char*); tsize_t t2p_sample_abgr_to_rgb(tdata_t, uint32); tsize_t t2p_sample_rgba_to_rgb(tdata_t, uint32); tsize_t t2p_sample_rgbaa_to_rgb(tdata_t, uint32); tsize_t t2p_sample_lab_signed_to_unsigned(tdata_t, uint32); tsize_t t2p_write_pdf_header(T2P*, TIFF*); tsize_t t2p_write_pdf_obj_start(uint32, TIFF*); tsize_t t2p_write_pdf_obj_end(TIFF*); tsize_t t2p_write_pdf_name(unsigned char*, TIFF*); tsize_t t2p_write_pdf_string(char*, TIFF*); tsize_t t2p_write_pdf_stream(tdata_t, tsize_t, TIFF*); tsize_t t2p_write_pdf_stream_start(TIFF*); tsize_t t2p_write_pdf_stream_end(TIFF*); tsize_t t2p_write_pdf_stream_dict(tsize_t, uint32, TIFF*); tsize_t t2p_write_pdf_stream_dict_start(TIFF*); tsize_t t2p_write_pdf_stream_dict_end(TIFF*); tsize_t t2p_write_pdf_stream_length(tsize_t, TIFF*); tsize_t t2p_write_pdf_catalog(T2P*, TIFF*); tsize_t t2p_write_pdf_info(T2P*, TIFF*, TIFF*); void t2p_pdf_currenttime(T2P*); void t2p_pdf_tifftime(T2P*, TIFF*); tsize_t t2p_write_pdf_pages(T2P*, TIFF*); tsize_t t2p_write_pdf_page(uint32, T2P*, TIFF*); void t2p_compose_pdf_page(T2P*); void t2p_compose_pdf_page_orient(T2P_BOX*, uint16); void t2p_compose_pdf_page_orient_flip(T2P_BOX*, uint16); tsize_t t2p_write_pdf_page_content(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_stream_dict(ttile_t, T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_cs(T2P*, TIFF*); tsize_t t2p_write_pdf_transfer(T2P*, TIFF*); tsize_t t2p_write_pdf_transfer_dict(T2P*, TIFF*, uint16); tsize_t t2p_write_pdf_transfer_stream(T2P*, TIFF*, uint16); tsize_t t2p_write_pdf_xobject_calcs(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_icccs(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_icccs_dict(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_icccs_stream(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_cs_stream(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_decode(T2P*, TIFF*); tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t, T2P*, TIFF*); tsize_t t2p_write_pdf_xreftable(T2P*, TIFF*); tsize_t t2p_write_pdf_trailer(T2P*, TIFF*); static void t2p_disable(TIFF *tif) { T2P *t2p = (T2P*) TIFFClientdata(tif); t2p->outputdisable = 1; } static void t2p_enable(TIFF *tif) { T2P *t2p = (T2P*) TIFFClientdata(tif); t2p->outputdisable = 0; } /* * Procs for TIFFClientOpen */ static tmsize_t t2pReadFile(TIFF *tif, tdata_t data, tmsize_t size) { thandle_t client = TIFFClientdata(tif); TIFFReadWriteProc proc = TIFFGetReadProc(tif); if (proc) return proc(client, data, size); return -1; } static tmsize_t t2pWriteFile(TIFF *tif, tdata_t data, tmsize_t size) { thandle_t client = TIFFClientdata(tif); TIFFReadWriteProc proc = TIFFGetWriteProc(tif); if (proc) return proc(client, data, size); return -1; } static uint64 t2pSeekFile(TIFF *tif, toff_t offset, int whence) { thandle_t client = TIFFClientdata(tif); TIFFSeekProc proc = TIFFGetSeekProc(tif); if (proc) return proc(client, offset, whence); return -1; } static tmsize_t t2p_readproc(thandle_t handle, tdata_t data, tmsize_t size) { (void) handle, (void) data, (void) size; return -1; } static tmsize_t t2p_writeproc(thandle_t handle, tdata_t data, tmsize_t size) { T2P *t2p = (T2P*) handle; if (t2p->outputdisable <= 0 && t2p->outputfile) { tsize_t written = fwrite(data, 1, size, t2p->outputfile); t2p->outputwritten += written; return written; } return size; } static uint64 t2p_seekproc(thandle_t handle, uint64 offset, int whence) { T2P *t2p = (T2P*) handle; if (t2p->outputdisable <= 0 && t2p->outputfile) return fseek(t2p->outputfile, (long) offset, whence); return offset; } static int t2p_closeproc(thandle_t handle) { (void) handle; return 0; } static uint64 t2p_sizeproc(thandle_t handle) { (void) handle; return -1; } static int t2p_mapproc(thandle_t handle, void **data, toff_t *offset) { (void) handle, (void) data, (void) offset; return -1; } static void t2p_unmapproc(thandle_t handle, void *data, toff_t offset) { (void) handle, (void) data, (void) offset; } /* This is the main function. The program converts one TIFF file to one PDF file, including multiple page TIFF files, tiled TIFF files, black and white. grayscale, and color TIFF files that contain data of TIFF photometric interpretations of bilevel, grayscale, RGB, YCbCr, CMYK separation, and ICC L*a*b* as supported by libtiff and PDF. If you have multiple TIFF files to convert into one PDF file then use tiffcp or other program to concatenate the files into a multiple page TIFF file. If the input TIFF file is of huge dimensions (greater than 10000 pixels height or width) convert the input image to a tiled TIFF if it is not already. The standard output is standard output. Set the output file name with the "-o output.pdf" option. All black and white files are compressed into a single strip CCITT G4 Fax compressed PDF, unless tiled, where tiled black and white images are compressed into tiled CCITT G4 Fax compressed PDF, libtiff CCITT support is assumed. Color and grayscale data can be compressed using either JPEG compression, ITU-T T.81, or Zip/Deflate LZ77 compression, per PNG 1.2 and RFC 1951. Set the compression type using the -j or -z options. JPEG compression support requires that libtiff be configured with JPEG support, and Zip/Deflate compression support requires that libtiff is configured with Zip support, in tiffconf.h. Use only one or the other of -j and -z. The -q option sets the image compression quality, that is 1-100 with libjpeg JPEG compression and one of 1, 10, 11, 12, 13, 14, or 15 for PNG group compression predictor methods, add 100, 200, ..., 900 to set zlib compression quality 1-9. PNG Group differencing predictor methods are not currently implemented. If the input TIFF contains single strip CCITT G4 Fax compressed information, then that is written to the PDF file without transcoding, unless the options of no compression and no passthrough are set, -d and -n. If the input TIFF contains JPEG or single strip Zip/Deflate compressed information, and they are configured, then that is written to the PDF file without transcoding, unless the options of no compression and no passthrough are set. The default page size upon which the TIFF image is placed is determined by the resolution and extent of the image data. Default values for the TIFF image resolution can be set using the -x and -y options. The page size can be set using the -p option for paper size, or -w and -l for paper width and length, then each page of the TIFF image is centered on its page. The distance unit for default resolution and page width and length can be set by the -u option, the default unit is inch. Various items of the output document information can be set with the -e, -c, -a, -t, -s, and -k tags. Setting the argument of the option to "" for these tags causes the relevant document information field to be not written. Some of the document information values otherwise get their information from the input TIFF image, the software, author, document name, and image description. The output PDF file conforms to the PDF 1.1 specification or PDF 1.2 if using Zip/Deflate compression. The Portable Document Format (PDF) specification is copyrighted by Adobe Systems, Incorporated. Todos derechos reservados. Here is a listing of the usage example and the options to the tiff2pdf program that is part of the libtiff distribution. Options followed by a colon have a required argument. usage: tiff2pdf [options] input.tif options: -o: output to file name -j: compress with JPEG (requires libjpeg configured with libtiff) -z: compress with Zip/Deflate (requires zlib configured with libtiff) -q: compression quality -n: no compressed data passthrough -d: do not compress (decompress) -i: invert colors -u: set distance unit, 'i' for inch, 'm' for centimeter -x: set x resolution default -y: set y resolution default -w: width in units -l: length in units -r: 'd' for resolution default, 'o' for resolution override -p: paper size, eg "letter", "legal", "a4" -f: set pdf "fit window" user preference -b: set PDF "Interpolate" user preference -e: date, overrides image or current date/time default, YYYYMMDDHHMMSS -c: creator, overrides image software default -a: author, overrides image artist default -t: title, overrides image document name default -s: subject, overrides image image description default -k: keywords -h: usage examples: tiff2pdf -o output.pdf input.tiff The above example would generate the file output.pdf from input.tiff. tiff2pdf input.tiff The above example would generate PDF output from input.tiff and write it to standard output. tiff2pdf -j -p letter -o output.pdf input.tiff The above example would generate the file output.pdf from input.tiff, putting the image pages on a letter sized page, compressing the output with JPEG. Please report bugs through: http://bugzilla.remotesensing.org/buglist.cgi?product=libtiff See also libtiff.3t, tiffcp. */ int main(int argc, char** argv){ extern char *optarg; extern int optind; const char *outfilename = NULL; T2P *t2p = NULL; TIFF *input = NULL, *output = NULL; tsize_t written = 0; int c, ret = EXIT_SUCCESS; t2p = t2p_init(); if (t2p == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't initialize context"); goto fail; } while (argv && (c = getopt(argc, argv, "o:q:u:x:y:w:l:r:p:e:c:a:t:s:k:jzndifbh")) != -1){ switch (c) { case 'o': outfilename = optarg; break; #ifdef JPEG_SUPPORT case 'j': t2p->pdf_defaultcompression=T2P_COMPRESS_JPEG; break; #endif #ifndef JPEG_SUPPORT case 'j': TIFFWarning( TIFF2PDF_MODULE, "JPEG support in libtiff required for JPEG compression, ignoring option"); break; #endif #ifdef ZIP_SUPPORT case 'z': t2p->pdf_defaultcompression=T2P_COMPRESS_ZIP; break; #endif #ifndef ZIP_SUPPORT case 'z': TIFFWarning( TIFF2PDF_MODULE, "Zip support in libtiff required for Zip compression, ignoring option"); break; #endif case 'q': t2p->pdf_defaultcompressionquality=atoi(optarg); break; case 'n': t2p->pdf_nopassthrough=1; break; case 'd': t2p->pdf_defaultcompression=T2P_COMPRESS_NONE; break; case 'u': if(optarg[0]=='m'){ t2p->pdf_centimeters=1; } break; case 'x': t2p->pdf_defaultxres = (float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'y': t2p->pdf_defaultyres = (float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'w': t2p->pdf_overridepagesize=1; t2p->pdf_defaultpagewidth = ((float)atof(optarg) * PS_UNIT_SIZE) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'l': t2p->pdf_overridepagesize=1; t2p->pdf_defaultpagelength = ((float)atof(optarg) * PS_UNIT_SIZE) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'r': if(optarg[0]=='o'){ t2p->pdf_overrideres=1; } break; case 'p': if(tiff2pdf_match_paper_size( &(t2p->pdf_defaultpagewidth), &(t2p->pdf_defaultpagelength), optarg)){ t2p->pdf_overridepagesize=1; } else { TIFFWarning(TIFF2PDF_MODULE, "Unknown paper size %s, ignoring option", optarg); } break; case 'i': t2p->pdf_colorspace_invert=1; break; case 'f': t2p->pdf_fitwindow=1; break; case 'e': if (strlen(optarg) == 0) { t2p->pdf_datetime[0] = '\0'; } else { t2p->pdf_datetime[0] = 'D'; t2p->pdf_datetime[1] = ':'; strncpy(t2p->pdf_datetime + 2, optarg, sizeof(t2p->pdf_datetime) - 3); t2p->pdf_datetime[sizeof(t2p->pdf_datetime) - 1] = '\0'; } break; case 'c': strncpy(t2p->pdf_creator, optarg, sizeof(t2p->pdf_creator) - 1); t2p->pdf_creator[sizeof(t2p->pdf_creator) - 1] = '\0'; break; case 'a': strncpy(t2p->pdf_author, optarg, sizeof(t2p->pdf_author) - 1); t2p->pdf_author[sizeof(t2p->pdf_author) - 1] = '\0'; break; case 't': strncpy(t2p->pdf_title, optarg, sizeof(t2p->pdf_title) - 1); t2p->pdf_title[sizeof(t2p->pdf_title) - 1] = '\0'; break; case 's': strncpy(t2p->pdf_subject, optarg, sizeof(t2p->pdf_subject) - 1); t2p->pdf_subject[sizeof(t2p->pdf_subject) - 1] = '\0'; break; case 'k': strncpy(t2p->pdf_keywords, optarg, sizeof(t2p->pdf_keywords) - 1); t2p->pdf_keywords[sizeof(t2p->pdf_keywords) - 1] = '\0'; break; case 'b': t2p->pdf_image_interpolate = 1; break; case 'h': case '?': tiff2pdf_usage(); goto success; break; } } /* * Input */ if(argc > optind) { input = TIFFOpen(argv[optind++], "r"); if (input==NULL) { TIFFError(TIFF2PDF_MODULE, "Can't open input file %s for reading", argv[optind-1]); goto fail; } } else { TIFFError(TIFF2PDF_MODULE, "No input file specified"); tiff2pdf_usage(); goto fail; } if(argc > optind) { TIFFError(TIFF2PDF_MODULE, "No support for multiple input files"); tiff2pdf_usage(); goto fail; } /* * Output */ t2p->outputdisable = 0; if (outfilename) { t2p->outputfile = fopen(outfilename, "wb"); if (t2p->outputfile == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't open output file %s for writing", outfilename); goto fail; } } else { outfilename = "-"; t2p->outputfile = stdout; } output = TIFFClientOpen(outfilename, "w", (thandle_t) t2p, t2p_readproc, t2p_writeproc, t2p_seekproc, t2p_closeproc, t2p_sizeproc, t2p_mapproc, t2p_unmapproc); if (output == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't initialize output descriptor"); goto fail; } /* * Validate */ t2p_validate(t2p); t2pSeekFile(output, (toff_t) 0, SEEK_SET); /* * Write */ written = t2p_write_pdf(t2p, input, output); if (t2p->t2p_error != 0) { TIFFError(TIFF2PDF_MODULE, "An error occurred creating output PDF file"); goto fail; } goto success; fail: ret = EXIT_FAILURE; success: if(input != NULL) TIFFClose(input); if (output != NULL) TIFFClose(output); if (t2p != NULL) t2p_free(t2p); return ret; } void tiff2pdf_usage(){ char* lines[]={ "usage: tiff2pdf [options] input.tiff", "options:", " -o: output to file name", #ifdef JPEG_SUPPORT " -j: compress with JPEG", #endif #ifdef ZIP_SUPPORT " -z: compress with Zip/Deflate", #endif " -q: compression quality", " -n: no compressed data passthrough", " -d: do not compress (decompress)", " -i: invert colors", " -u: set distance unit, 'i' for inch, 'm' for centimeter", " -x: set x resolution default in dots per unit", " -y: set y resolution default in dots per unit", " -w: width in units", " -l: length in units", " -r: 'd' for resolution default, 'o' for resolution override", " -p: paper size, eg \"letter\", \"legal\", \"A4\"", " -f: set PDF \"Fit Window\" user preference", " -e: date, overrides image or current date/time default, YYYYMMDDHHMMSS", " -c: sets document creator, overrides image software default", " -a: sets document author, overrides image artist default", " -t: sets document title, overrides image document name default", " -s: sets document subject, overrides image image description default", " -k: sets document keywords", " -b: set PDF \"Interpolate\" user preference", " -h: usage", NULL }; int i=0; fprintf(stderr, "%s\n\n", TIFFGetVersion()); for (i=0;lines[i]!=NULL;i++){ fprintf(stderr, "%s\n", lines[i]); } return; } int tiff2pdf_match_paper_size(float* width, float* length, char* papersize){ size_t i, len; const char* sizes[]={ "LETTER", "A4", "LEGAL", "EXECUTIVE", "LETTER", "LEGAL", "LEDGER", "TABLOID", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "A10", "A9", "A8", "A7", "A6", "A5", "A4", "A3", "A2", "A1", "A0", "2A0", "4A0", "2A", "4A", "B10", "B9", "B8", "B7", "B6", "B5", "B4", "B3", "B2", "B1", "B0", "JISB10", "JISB9", "JISB8", "JISB7", "JISB6", "JISB5", "JISB4", "JISB3", "JISB2", "JISB1", "JISB0", "C10", "C9", "C8", "C7", "C6", "C5", "C4", "C3", "C2", "C1", "C0", "RA2", "RA1", "RA0", "SRA4", "SRA3", "SRA2", "SRA1", "SRA0", "A3EXTRA", "A4EXTRA", "STATEMENT", "FOLIO", "QUARTO", NULL } ; const int widths[]={ 612, 595, 612, 522, 612,612,792,792, 612,792,1224,1584,2448,2016,792,2016,2448,2880, 74,105,147,210,298,420,595,842,1191,1684,2384,3370,4768,3370,4768, 88,125,176,249,354,499,709,1001,1417,2004,2835, 91,128,181,258,363,516,729,1032,1460,2064,2920, 79,113,162,230,323,459,649,918,1298,1298,2599, 1219,1729,2438,638,907,1276,1814,2551, 914,667, 396, 612, 609, 0 }; const int lengths[]={ 792,842,1008, 756,792,1008,1224,1224, 792,1224,1584,2448,3168,2880,6480,10296,12672,10296, 105,147,210,298,420,595,842,1191,1684,2384,3370,4768,6741,4768,6741, 125,176,249,354,499,709,1001,1417,2004,2835,4008, 128,181,258,363,516,729,1032,1460,2064,2920,4127, 113,162,230,323,459,649,918,1298,1837,1837,3677, 1729,2438,3458,907,1276,1814,2551,3628, 1262,914, 612, 936, 780, 0 }; len=strlen(papersize); for(i=0;i<len;i++){ papersize[i]=toupper(papersize[i]); } for(i=0;sizes[i]!=NULL; i++){ if (strcmp( (const char*)papersize, sizes[i])==0){ *width=(float)widths[i]; *length=(float)lengths[i]; return(1); } } return(0); } /* * This function allocates and initializes a T2P context struct pointer. */ T2P* t2p_init() { T2P* t2p = (T2P*) _TIFFmalloc(sizeof(T2P)); if(t2p==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_init", (unsigned long) sizeof(T2P)); return( (T2P*) NULL ); } _TIFFmemset(t2p, 0x00, sizeof(T2P)); t2p->pdf_majorversion=1; t2p->pdf_minorversion=1; t2p->pdf_defaultxres=300.0; t2p->pdf_defaultyres=300.0; t2p->pdf_defaultpagewidth=612.0; t2p->pdf_defaultpagelength=792.0; t2p->pdf_xrefcount=3; /* Catalog, Info, Pages */ return(t2p); } /* * This function frees a T2P context struct pointer and any allocated data fields of it. */ void t2p_free(T2P* t2p) { int i = 0; if (t2p != NULL) { if(t2p->pdf_xrefoffsets != NULL){ _TIFFfree( (tdata_t) t2p->pdf_xrefoffsets); } if(t2p->tiff_pages != NULL){ _TIFFfree( (tdata_t) t2p->tiff_pages); } for(i=0;i<t2p->tiff_pagecount;i++){ if(t2p->tiff_tiles[i].tiles_tiles != NULL){ _TIFFfree( (tdata_t) t2p->tiff_tiles[i].tiles_tiles); } } if(t2p->tiff_tiles != NULL){ _TIFFfree( (tdata_t) t2p->tiff_tiles); } if(t2p->pdf_palette != NULL){ _TIFFfree( (tdata_t) t2p->pdf_palette); } #ifdef OJPEG_SUPPORT if(t2p->pdf_ojpegdata != NULL){ _TIFFfree( (tdata_t) t2p->pdf_ojpegdata); } #endif _TIFFfree( (tdata_t) t2p ); } return; } /* This function validates the values of a T2P context struct pointer before calling t2p_write_pdf with it. */ void t2p_validate(T2P* t2p){ #ifdef JPEG_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){ if(t2p->pdf_defaultcompressionquality>100 || t2p->pdf_defaultcompressionquality<1){ t2p->pdf_defaultcompressionquality=0; } } #endif #ifdef ZIP_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_ZIP){ uint16 m=t2p->pdf_defaultcompressionquality%100; if(t2p->pdf_defaultcompressionquality/100 > 9 || (m>1 && m<10) || m>15){ t2p->pdf_defaultcompressionquality=0; } if(t2p->pdf_defaultcompressionquality%100 !=0){ t2p->pdf_defaultcompressionquality/=100; t2p->pdf_defaultcompressionquality*=100; TIFFError( TIFF2PDF_MODULE, "PNG Group predictor differencing not implemented, assuming compression quality %u", t2p->pdf_defaultcompressionquality); } t2p->pdf_defaultcompressionquality%=100; if(t2p->pdf_minorversion<2){t2p->pdf_minorversion=2;} } #endif (void)0; return; } /* This function scans the input TIFF file for pages. It attempts to determine which IFD's of the TIFF file contain image document pages. For each, it gathers some information that has to do with the output of the PDF document as a whole. */ void t2p_read_tiff_init(T2P* t2p, TIFF* input){ tdir_t directorycount=0; tdir_t i=0; uint16 pagen=0; uint16 paged=0; uint16 xuint16=0; directorycount=TIFFNumberOfDirectories(input); t2p->tiff_pages = (T2P_PAGE*) _TIFFmalloc(directorycount * sizeof(T2P_PAGE)); if(t2p->tiff_pages==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for tiff_pages array, %s", (unsigned long) directorycount * sizeof(T2P_PAGE), TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } _TIFFmemset( t2p->tiff_pages, 0x00, directorycount * sizeof(T2P_PAGE)); t2p->tiff_tiles = (T2P_TILES*) _TIFFmalloc(directorycount * sizeof(T2P_TILES)); if(t2p->tiff_tiles==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for tiff_tiles array, %s", (unsigned long) directorycount * sizeof(T2P_TILES), TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } _TIFFmemset( t2p->tiff_tiles, 0x00, directorycount * sizeof(T2P_TILES)); for(i=0;i<directorycount;i++){ uint32 subfiletype = 0; if(!TIFFSetDirectory(input, i)){ TIFFError( TIFF2PDF_MODULE, "Can't set directory %u of input file %s", i, TIFFFileName(input)); return; } if(TIFFGetField(input, TIFFTAG_PAGENUMBER, &pagen, &paged)){ if((pagen>paged) && (paged != 0)){ t2p->tiff_pages[t2p->tiff_pagecount].page_number = paged; } else { t2p->tiff_pages[t2p->tiff_pagecount].page_number = pagen; } goto ispage2; } if(TIFFGetField(input, TIFFTAG_SUBFILETYPE, &subfiletype)){ if ( ((subfiletype & FILETYPE_PAGE) != 0) || (subfiletype == 0)){ goto ispage; } else { goto isnotpage; } } if(TIFFGetField(input, TIFFTAG_OSUBFILETYPE, &subfiletype)){ if ((subfiletype == OFILETYPE_IMAGE) || (subfiletype == OFILETYPE_PAGE) || (subfiletype == 0) ){ goto ispage; } else { goto isnotpage; } } ispage: t2p->tiff_pages[t2p->tiff_pagecount].page_number=t2p->tiff_pagecount; ispage2: t2p->tiff_pages[t2p->tiff_pagecount].page_directory=i; if(TIFFIsTiled(input)){ t2p->tiff_pages[t2p->tiff_pagecount].page_tilecount = TIFFNumberOfTiles(input); } t2p->tiff_pagecount++; isnotpage: (void)0; } qsort((void*) t2p->tiff_pages, t2p->tiff_pagecount, sizeof(T2P_PAGE), t2p_cmp_t2p_page); for(i=0;i<t2p->tiff_pagecount;i++){ t2p->pdf_xrefcount += 5; TIFFSetDirectory(input, t2p->tiff_pages[i].page_directory ); if((TIFFGetField(input, TIFFTAG_PHOTOMETRIC, &xuint16) && (xuint16==PHOTOMETRIC_PALETTE)) || TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)) { t2p->tiff_pages[i].page_extra++; t2p->pdf_xrefcount++; } #ifdef ZIP_SUPPORT if (TIFFGetField(input, TIFFTAG_COMPRESSION, &xuint16)) { if( (xuint16== COMPRESSION_DEFLATE || xuint16== COMPRESSION_ADOBE_DEFLATE) && ((t2p->tiff_pages[i].page_tilecount != 0) || TIFFNumberOfStrips(input)==1) && (t2p->pdf_nopassthrough==0) ){ if(t2p->pdf_minorversion<2){t2p->pdf_minorversion=2;} } } #endif if (TIFFGetField(input, TIFFTAG_TRANSFERFUNCTION, &(t2p->tiff_transferfunction[0]), &(t2p->tiff_transferfunction[1]), &(t2p->tiff_transferfunction[2]))) { if(t2p->tiff_transferfunction[1] != t2p->tiff_transferfunction[0]) { t2p->tiff_transferfunctioncount = 3; t2p->tiff_pages[i].page_extra += 4; t2p->pdf_xrefcount += 4; } else { t2p->tiff_transferfunctioncount = 1; t2p->tiff_pages[i].page_extra += 2; t2p->pdf_xrefcount += 2; } if(t2p->pdf_minorversion < 2) t2p->pdf_minorversion = 2; } else { t2p->tiff_transferfunctioncount=0; } if( TIFFGetField( input, TIFFTAG_ICCPROFILE, &(t2p->tiff_iccprofilelength), &(t2p->tiff_iccprofile)) != 0){ t2p->tiff_pages[i].page_extra++; t2p->pdf_xrefcount++; if(t2p->pdf_minorversion<3){t2p->pdf_minorversion=3;} } t2p->tiff_tiles[i].tiles_tilecount= t2p->tiff_pages[i].page_tilecount; if( (TIFFGetField(input, TIFFTAG_PLANARCONFIG, &xuint16) != 0) && (xuint16 == PLANARCONFIG_SEPARATE ) ){ TIFFGetField(input, TIFFTAG_SAMPLESPERPIXEL, &xuint16); t2p->tiff_tiles[i].tiles_tilecount/= xuint16; } if( t2p->tiff_tiles[i].tiles_tilecount > 0){ t2p->pdf_xrefcount += (t2p->tiff_tiles[i].tiles_tilecount -1)*2; TIFFGetField(input, TIFFTAG_TILEWIDTH, &( t2p->tiff_tiles[i].tiles_tilewidth) ); TIFFGetField(input, TIFFTAG_TILELENGTH, &( t2p->tiff_tiles[i].tiles_tilelength) ); t2p->tiff_tiles[i].tiles_tiles = (T2P_TILE*) _TIFFmalloc( t2p->tiff_tiles[i].tiles_tilecount * sizeof(T2P_TILE) ); if( t2p->tiff_tiles[i].tiles_tiles == NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_read_tiff_init, %s", (unsigned long) t2p->tiff_tiles[i].tiles_tilecount * sizeof(T2P_TILE), TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } } } return; } /* * This function is used by qsort to sort a T2P_PAGE* array of page structures * by page number. */ int t2p_cmp_t2p_page(const void* e1, const void* e2){ return( ((T2P_PAGE*)e1)->page_number - ((T2P_PAGE*)e2)->page_number ); } /* This function sets the input directory to the directory of a given page and determines information about the image. It checks the image characteristics to determine if it is possible to convert the image data into a page of PDF output, setting values of the T2P struct for this page. It determines what color space is used in the output PDF to represent the image. It determines if the image can be converted as raw data without requiring transcoding of the image data. */ void t2p_read_tiff_data(T2P* t2p, TIFF* input){ int i=0; uint16* r; uint16* g; uint16* b; uint16* a; uint16 xuint16; uint16* xuint16p; float* xfloatp; t2p->pdf_transcode = T2P_TRANSCODE_ENCODE; t2p->pdf_sample = T2P_SAMPLE_NOTHING; t2p->pdf_switchdecode = t2p->pdf_colorspace_invert; TIFFSetDirectory(input, t2p->tiff_pages[t2p->pdf_page].page_directory); TIFFGetField(input, TIFFTAG_IMAGEWIDTH, &(t2p->tiff_width)); if(t2p->tiff_width == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with zero width", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } TIFFGetField(input, TIFFTAG_IMAGELENGTH, &(t2p->tiff_length)); if(t2p->tiff_length == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with zero length", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } if(TIFFGetField(input, TIFFTAG_COMPRESSION, &(t2p->tiff_compression)) == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with no compression tag", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } if( TIFFIsCODECConfigured(t2p->tiff_compression) == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with compression type %u: not configured", TIFFFileName(input), t2p->tiff_compression ); t2p->t2p_error = T2P_ERR_ERROR; return; } TIFFGetFieldDefaulted(input, TIFFTAG_BITSPERSAMPLE, &(t2p->tiff_bitspersample)); switch(t2p->tiff_bitspersample){ case 1: case 2: case 4: case 8: break; case 0: TIFFWarning( TIFF2PDF_MODULE, "Image %s has 0 bits per sample, assuming 1", TIFFFileName(input)); t2p->tiff_bitspersample=1; break; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with %u bits per sample", TIFFFileName(input), t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } TIFFGetFieldDefaulted(input, TIFFTAG_SAMPLESPERPIXEL, &(t2p->tiff_samplesperpixel)); if(t2p->tiff_samplesperpixel>4){ TIFFError( TIFF2PDF_MODULE, "No support for %s with %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; return; } if(t2p->tiff_samplesperpixel==0){ TIFFWarning( TIFF2PDF_MODULE, "Image %s has 0 samples per pixel, assuming 1", TIFFFileName(input)); t2p->tiff_samplesperpixel=1; } if(TIFFGetField(input, TIFFTAG_SAMPLEFORMAT, &xuint16) != 0 ){ switch(xuint16){ case 0: case 1: case 4: break; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with sample format %u", TIFFFileName(input), xuint16); t2p->t2p_error = T2P_ERR_ERROR; return; break; } } TIFFGetFieldDefaulted(input, TIFFTAG_FILLORDER, &(t2p->tiff_fillorder)); if(TIFFGetField(input, TIFFTAG_PHOTOMETRIC, &(t2p->tiff_photometric)) == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with no photometric interpretation tag", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } switch(t2p->tiff_photometric){ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: if (t2p->tiff_bitspersample==1){ t2p->pdf_colorspace=T2P_CS_BILEVEL; if(t2p->tiff_photometric==PHOTOMETRIC_MINISWHITE){ t2p->pdf_switchdecode ^= 1; } } else { t2p->pdf_colorspace=T2P_CS_GRAY; if(t2p->tiff_photometric==PHOTOMETRIC_MINISWHITE){ t2p->pdf_switchdecode ^= 1; } } break; case PHOTOMETRIC_RGB: t2p->pdf_colorspace=T2P_CS_RGB; if(t2p->tiff_samplesperpixel == 3){ break; } if(TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)){ if(xuint16==1) goto photometric_palette; } if(t2p->tiff_samplesperpixel > 3) { if(t2p->tiff_samplesperpixel == 4) { t2p->pdf_colorspace = T2P_CS_RGB; if(TIFFGetField(input, TIFFTAG_EXTRASAMPLES, &xuint16, &xuint16p) && xuint16 == 1) { if(xuint16p[0] == EXTRASAMPLE_ASSOCALPHA){ t2p->pdf_sample=T2P_SAMPLE_RGBAA_TO_RGB; break; } if(xuint16p[0] == EXTRASAMPLE_UNASSALPHA){ t2p->pdf_sample=T2P_SAMPLE_RGBA_TO_RGB; break; } TIFFWarning( TIFF2PDF_MODULE, "RGB image %s has 4 samples per pixel, assuming RGBA", TIFFFileName(input)); break; } t2p->pdf_colorspace=T2P_CS_CMYK; t2p->pdf_switchdecode ^= 1; TIFFWarning( TIFF2PDF_MODULE, "RGB image %s has 4 samples per pixel, assuming inverse CMYK", TIFFFileName(input)); break; } else { TIFFError( TIFF2PDF_MODULE, "No support for RGB image %s with %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; break; } } else { TIFFError( TIFF2PDF_MODULE, "No support for RGB image %s with %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; break; } case PHOTOMETRIC_PALETTE: photometric_palette: if(t2p->tiff_samplesperpixel!=1){ TIFFError( TIFF2PDF_MODULE, "No support for palettized image %s with not one sample per pixel", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_colorspace=T2P_CS_RGB | T2P_CS_PALETTE; t2p->pdf_palettesize=0x0001<<t2p->tiff_bitspersample; if(!TIFFGetField(input, TIFFTAG_COLORMAP, &r, &g, &b)){ TIFFError( TIFF2PDF_MODULE, "Palettized image %s has no color map", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } if(t2p->pdf_palette != NULL){ _TIFFfree(t2p->pdf_palette); t2p->pdf_palette=NULL; } t2p->pdf_palette = (unsigned char*) _TIFFmalloc(t2p->pdf_palettesize*3); if(t2p->pdf_palette==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_read_tiff_image, %s", t2p->pdf_palettesize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } for(i=0;i<t2p->pdf_palettesize;i++){ t2p->pdf_palette[(i*3)] = (unsigned char) (r[i]>>8); t2p->pdf_palette[(i*3)+1]= (unsigned char) (g[i]>>8); t2p->pdf_palette[(i*3)+2]= (unsigned char) (b[i]>>8); } t2p->pdf_palettesize *= 3; break; case PHOTOMETRIC_SEPARATED: if(TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)){ if(xuint16==1){ goto photometric_palette_cmyk; } } if( TIFFGetField(input, TIFFTAG_INKSET, &xuint16) ){ if(xuint16 != INKSET_CMYK){ TIFFError( TIFF2PDF_MODULE, "No support for %s because its inkset is not CMYK", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } } if(t2p->tiff_samplesperpixel==4){ t2p->pdf_colorspace=T2P_CS_CMYK; } else { TIFFError( TIFF2PDF_MODULE, "No support for %s because it has %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; return; } break; photometric_palette_cmyk: if(t2p->tiff_samplesperpixel!=1){ TIFFError( TIFF2PDF_MODULE, "No support for palettized CMYK image %s with not one sample per pixel", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_colorspace=T2P_CS_CMYK | T2P_CS_PALETTE; t2p->pdf_palettesize=0x0001<<t2p->tiff_bitspersample; if(!TIFFGetField(input, TIFFTAG_COLORMAP, &r, &g, &b, &a)){ TIFFError( TIFF2PDF_MODULE, "Palettized image %s has no color map", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } if(t2p->pdf_palette != NULL){ _TIFFfree(t2p->pdf_palette); t2p->pdf_palette=NULL; } t2p->pdf_palette = (unsigned char*) _TIFFmalloc(t2p->pdf_palettesize*4); if(t2p->pdf_palette==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_read_tiff_image, %s", t2p->pdf_palettesize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } for(i=0;i<t2p->pdf_palettesize;i++){ t2p->pdf_palette[(i*4)] = (unsigned char) (r[i]>>8); t2p->pdf_palette[(i*4)+1]= (unsigned char) (g[i]>>8); t2p->pdf_palette[(i*4)+2]= (unsigned char) (b[i]>>8); t2p->pdf_palette[(i*4)+3]= (unsigned char) (a[i]>>8); } t2p->pdf_palettesize *= 4; break; case PHOTOMETRIC_YCBCR: t2p->pdf_colorspace=T2P_CS_RGB; if(t2p->tiff_samplesperpixel==1){ t2p->pdf_colorspace=T2P_CS_GRAY; t2p->tiff_photometric=PHOTOMETRIC_MINISBLACK; break; } t2p->pdf_sample=T2P_SAMPLE_YCBCR_TO_RGB; #ifdef JPEG_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){ t2p->pdf_sample=T2P_SAMPLE_NOTHING; } #endif break; case PHOTOMETRIC_CIELAB: t2p->pdf_labrange[0]= -127; t2p->pdf_labrange[1]= 127; t2p->pdf_labrange[2]= -127; t2p->pdf_labrange[3]= 127; t2p->pdf_sample=T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED; t2p->pdf_colorspace=T2P_CS_LAB; break; case PHOTOMETRIC_ICCLAB: t2p->pdf_labrange[0]= 0; t2p->pdf_labrange[1]= 255; t2p->pdf_labrange[2]= 0; t2p->pdf_labrange[3]= 255; t2p->pdf_colorspace=T2P_CS_LAB; break; case PHOTOMETRIC_ITULAB: t2p->pdf_labrange[0]=-85; t2p->pdf_labrange[1]=85; t2p->pdf_labrange[2]=-75; t2p->pdf_labrange[3]=124; t2p->pdf_sample=T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED; t2p->pdf_colorspace=T2P_CS_LAB; break; case PHOTOMETRIC_LOGL: case PHOTOMETRIC_LOGLUV: TIFFError( TIFF2PDF_MODULE, "No support for %s with photometric interpretation LogL/LogLuv", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with photometric interpretation %u", TIFFFileName(input), t2p->tiff_photometric); t2p->t2p_error = T2P_ERR_ERROR; return; } if(TIFFGetField(input, TIFFTAG_PLANARCONFIG, &(t2p->tiff_planar))){ switch(t2p->tiff_planar){ case 0: TIFFWarning( TIFF2PDF_MODULE, "Image %s has planar configuration 0, assuming 1", TIFFFileName(input)); t2p->tiff_planar=PLANARCONFIG_CONTIG; case PLANARCONFIG_CONTIG: break; case PLANARCONFIG_SEPARATE: t2p->pdf_sample=T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG; if(t2p->tiff_bitspersample!=8){ TIFFError( TIFF2PDF_MODULE, "No support for %s with separated planar configuration and %u bits per sample", TIFFFileName(input), t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } break; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with planar configuration %u", TIFFFileName(input), t2p->tiff_planar); t2p->t2p_error = T2P_ERR_ERROR; return; } } TIFFGetFieldDefaulted(input, TIFFTAG_ORIENTATION, &(t2p->tiff_orientation)); if(t2p->tiff_orientation>8){ TIFFWarning(TIFF2PDF_MODULE, "Image %s has orientation %u, assuming 0", TIFFFileName(input), t2p->tiff_orientation); t2p->tiff_orientation=0; } if(TIFFGetField(input, TIFFTAG_XRESOLUTION, &(t2p->tiff_xres) ) == 0){ t2p->tiff_xres=0.0; } if(TIFFGetField(input, TIFFTAG_YRESOLUTION, &(t2p->tiff_yres) ) == 0){ t2p->tiff_yres=0.0; } TIFFGetFieldDefaulted(input, TIFFTAG_RESOLUTIONUNIT, &(t2p->tiff_resunit)); if(t2p->tiff_resunit == RESUNIT_CENTIMETER) { t2p->tiff_xres *= 2.54F; t2p->tiff_yres *= 2.54F; } else if (t2p->tiff_resunit != RESUNIT_INCH && t2p->pdf_centimeters != 0) { t2p->tiff_xres *= 2.54F; t2p->tiff_yres *= 2.54F; } t2p_compose_pdf_page(t2p); t2p->pdf_transcode = T2P_TRANSCODE_ENCODE; if(t2p->pdf_nopassthrough==0){ #ifdef CCITT_SUPPORT if(t2p->tiff_compression==COMPRESSION_CCITTFAX4 ){ if(TIFFIsTiled(input) || (TIFFNumberOfStrips(input)==1) ){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_G4; } } #endif #ifdef ZIP_SUPPORT if(t2p->tiff_compression== COMPRESSION_ADOBE_DEFLATE || t2p->tiff_compression==COMPRESSION_DEFLATE){ if(TIFFIsTiled(input) || (TIFFNumberOfStrips(input)==1) ){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_ZIP; } } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_OJPEG){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_JPEG; t2p_process_ojpeg_tables(t2p, input); } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_JPEG){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_JPEG; } #endif (void)0; } if(t2p->pdf_transcode!=T2P_TRANSCODE_RAW){ t2p->pdf_compression = t2p->pdf_defaultcompression; } #ifdef JPEG_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){ if(t2p->pdf_colorspace & T2P_CS_PALETTE){ t2p->pdf_sample|=T2P_SAMPLE_REALIZE_PALETTE; t2p->pdf_colorspace ^= T2P_CS_PALETTE; t2p->tiff_pages[t2p->pdf_page].page_extra--; } } if(t2p->tiff_compression==COMPRESSION_JPEG){ if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ TIFFError( TIFF2PDF_MODULE, "No support for %s with JPEG compression and separated planar configuration", TIFFFileName(input)); t2p->t2p_error=T2P_ERR_ERROR; return; } } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_OJPEG){ if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ TIFFError( TIFF2PDF_MODULE, "No support for %s with OJPEG compression and separated planar configuration", TIFFFileName(input)); t2p->t2p_error=T2P_ERR_ERROR; return; } } #endif if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){ if(t2p->pdf_colorspace & T2P_CS_CMYK){ t2p->tiff_samplesperpixel=4; t2p->tiff_photometric=PHOTOMETRIC_SEPARATED; } else { t2p->tiff_samplesperpixel=3; t2p->tiff_photometric=PHOTOMETRIC_RGB; } } if (TIFFGetField(input, TIFFTAG_TRANSFERFUNCTION, &(t2p->tiff_transferfunction[0]), &(t2p->tiff_transferfunction[1]), &(t2p->tiff_transferfunction[2]))) { if(t2p->tiff_transferfunction[1] != t2p->tiff_transferfunction[0]) { t2p->tiff_transferfunctioncount=3; } else { t2p->tiff_transferfunctioncount=1; } } else { t2p->tiff_transferfunctioncount=0; } if(TIFFGetField(input, TIFFTAG_WHITEPOINT, &xfloatp)!=0){ t2p->tiff_whitechromaticities[0]=xfloatp[0]; t2p->tiff_whitechromaticities[1]=xfloatp[1]; if(t2p->pdf_colorspace & T2P_CS_GRAY){ t2p->pdf_colorspace |= T2P_CS_CALGRAY; } if(t2p->pdf_colorspace & T2P_CS_RGB){ t2p->pdf_colorspace |= T2P_CS_CALRGB; } } if(TIFFGetField(input, TIFFTAG_PRIMARYCHROMATICITIES, &xfloatp)!=0){ t2p->tiff_primarychromaticities[0]=xfloatp[0]; t2p->tiff_primarychromaticities[1]=xfloatp[1]; t2p->tiff_primarychromaticities[2]=xfloatp[2]; t2p->tiff_primarychromaticities[3]=xfloatp[3]; t2p->tiff_primarychromaticities[4]=xfloatp[4]; t2p->tiff_primarychromaticities[5]=xfloatp[5]; if(t2p->pdf_colorspace & T2P_CS_RGB){ t2p->pdf_colorspace |= T2P_CS_CALRGB; } } if(t2p->pdf_colorspace & T2P_CS_LAB){ if(TIFFGetField(input, TIFFTAG_WHITEPOINT, &xfloatp) != 0){ t2p->tiff_whitechromaticities[0]=xfloatp[0]; t2p->tiff_whitechromaticities[1]=xfloatp[1]; } else { t2p->tiff_whitechromaticities[0]=0.3457F; /* 0.3127F; */ t2p->tiff_whitechromaticities[1]=0.3585F; /* 0.3290F; */ } } if(TIFFGetField(input, TIFFTAG_ICCPROFILE, &(t2p->tiff_iccprofilelength), &(t2p->tiff_iccprofile))!=0){ t2p->pdf_colorspace |= T2P_CS_ICCBASED; } else { t2p->tiff_iccprofilelength=0; t2p->tiff_iccprofile=NULL; } #ifdef CCITT_SUPPORT if( t2p->tiff_bitspersample==1 && t2p->tiff_samplesperpixel==1){ t2p->pdf_compression = T2P_COMPRESS_G4; } #endif return; } /* This function returns the necessary size of a data buffer to contain the raw or uncompressed image data from the input TIFF for a page. */ void t2p_read_tiff_size(T2P* t2p, TIFF* input){ uint64* sbc=NULL; #if defined(JPEG_SUPPORT) || defined (OJPEG_SUPPORT) unsigned char* jpt=NULL; tstrip_t i=0; tstrip_t stripcount=0; #endif #ifdef OJPEG_SUPPORT tsize_t k = 0; #endif if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4 ){ TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); t2p->tiff_datasize=(tmsize_t)sbc[0]; return; } #endif #ifdef ZIP_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_ZIP){ TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); t2p->tiff_datasize=(tmsize_t)sbc[0]; return; } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG){ if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){ TIFFError(TIFF2PDF_MODULE, "Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ k += sbc[i]; } if(TIFFGetField(input, TIFFTAG_JPEGIFOFFSET, &(t2p->tiff_dataoffset))){ if(t2p->tiff_dataoffset != 0){ if(TIFFGetField(input, TIFFTAG_JPEGIFBYTECOUNT, &(t2p->tiff_datasize))!=0){ if(t2p->tiff_datasize < k) { t2p->pdf_ojpegiflength=t2p->tiff_datasize; t2p->tiff_datasize+=k; t2p->tiff_datasize+=6; t2p->tiff_datasize+=2*stripcount; TIFFWarning(TIFF2PDF_MODULE, "Input file %s has short JPEG interchange file byte count", TIFFFileName(input)); return; } return; }else { TIFFError(TIFF2PDF_MODULE, "Input file %s missing field: TIFFTAG_JPEGIFBYTECOUNT", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } } } t2p->tiff_datasize+=k; t2p->tiff_datasize+=2*stripcount; t2p->tiff_datasize+=2048; return; } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG) { uint32 count = 0; if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0 ){ if(count > 4){ t2p->tiff_datasize += count; t2p->tiff_datasize -= 2; /* don't use EOI of header */ } } else { t2p->tiff_datasize = 2; /* SOI for first strip */ } stripcount=TIFFNumberOfStrips(input); if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){ TIFFError(TIFF2PDF_MODULE, "Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } for(i=0;i<stripcount;i++){ t2p->tiff_datasize += sbc[i]; t2p->tiff_datasize -=4; /* don't use SOI or EOI of strip */ } t2p->tiff_datasize +=2; /* use EOI of last strip */ return; } #endif (void) 0; } t2p->tiff_datasize=TIFFScanlineSize(input) * t2p->tiff_length; if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ t2p->tiff_datasize*= t2p->tiff_samplesperpixel; } return; } /* This function returns the necessary size of a data buffer to contain the raw or uncompressed image data from the input TIFF for a tile of a page. */ void t2p_read_tiff_size_tile(T2P* t2p, TIFF* input, ttile_t tile){ uint64* tbc = NULL; uint16 edge=0; #ifdef JPEG_SUPPORT unsigned char* jpt; #endif edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile); edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile); if(t2p->pdf_transcode==T2P_TRANSCODE_RAW){ if(edge #if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT) && !(t2p->pdf_compression==T2P_COMPRESS_JPEG) #endif ){ t2p->tiff_datasize=TIFFTileSize(input); return; } else { TIFFGetField(input, TIFFTAG_TILEBYTECOUNTS, &tbc); t2p->tiff_datasize=(tmsize_t)tbc[tile]; #ifdef OJPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_OJPEG){ t2p->tiff_datasize+=2048; return; } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_JPEG) { uint32 count = 0; if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt)!=0){ if(count > 4){ t2p->tiff_datasize += count; t2p->tiff_datasize -= 2; /* don't use EOI of header or SOI of tile */ } } } #endif return; } } t2p->tiff_datasize=TIFFTileSize(input); if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ t2p->tiff_datasize*= t2p->tiff_samplesperpixel; } return; } /* * This functions returns a non-zero value when the tile is on the right edge * and does not have full imaged tile width. */ int t2p_tile_is_right_edge(T2P_TILES tiles, ttile_t tile){ if( ((tile+1) % tiles.tiles_tilecountx == 0) && (tiles.tiles_edgetilewidth != 0) ){ return(1); } else { return(0); } } /* * This functions returns a non-zero value when the tile is on the bottom edge * and does not have full imaged tile length. */ int t2p_tile_is_bottom_edge(T2P_TILES tiles, ttile_t tile){ if( ((tile+1) > (tiles.tiles_tilecount-tiles.tiles_tilecountx) ) && (tiles.tiles_edgetilelength != 0) ){ return(1); } else { return(0); } } /* * This function returns a non-zero value when the tile is a right edge tile * or a bottom edge tile. */ int t2p_tile_is_edge(T2P_TILES tiles, ttile_t tile){ return(t2p_tile_is_right_edge(tiles, tile) | t2p_tile_is_bottom_edge(tiles, tile) ); } /* This function returns a non-zero value when the tile is a right edge tile and a bottom edge tile. */ int t2p_tile_is_corner_edge(T2P_TILES tiles, ttile_t tile){ return(t2p_tile_is_right_edge(tiles, tile) & t2p_tile_is_bottom_edge(tiles, tile) ); } /* This function reads the raster image data from the input TIFF for an image and writes the data to the output PDF XObject image dictionary stream. It returns the amount written or zero on error. */ tsize_t t2p_readwrite_pdf_image(T2P* t2p, TIFF* input, TIFF* output){ tsize_t written=0; unsigned char* buffer=NULL; unsigned char* samplebuffer=NULL; tsize_t bufferoffset=0; tsize_t samplebufferoffset=0; tsize_t read=0; tstrip_t i=0; tstrip_t j=0; tstrip_t stripcount=0; tsize_t stripsize=0; tsize_t sepstripcount=0; tsize_t sepstripsize=0; #ifdef OJPEG_SUPPORT toff_t inputoffset=0; uint16 h_samp=1; uint16 v_samp=1; uint16 ri=1; uint32 rows=0; #endif #ifdef JPEG_SUPPORT unsigned char* jpt; float* xfloatp; uint64* sbc; unsigned char* stripbuffer; tsize_t striplength=0; uint32 max_striplength=0; #endif if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if (buffer == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ /* * make sure is lsb-to-msb * bit-endianness fill order */ TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif #ifdef ZIP_SUPPORT if (t2p->pdf_compression == T2P_COMPRESS_ZIP) { buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB) { TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG) { if(t2p->tiff_dataoffset != 0) { buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); if(t2p->pdf_ojpegiflength==0){ inputoffset=t2pSeekFile(input, 0, SEEK_CUR); t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); t2pReadFile(input, (tdata_t) buffer, t2p->tiff_datasize); t2pSeekFile(input, inputoffset, SEEK_SET); t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } else { inputoffset=t2pSeekFile(input, 0, SEEK_CUR); t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); bufferoffset = t2pReadFile(input, (tdata_t) buffer, t2p->pdf_ojpegiflength); t2p->pdf_ojpegiflength = 0; t2pSeekFile(input, inputoffset, SEEK_SET); TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp); buffer[bufferoffset++]= 0xff; buffer[bufferoffset++]= 0xdd; buffer[bufferoffset++]= 0x00; buffer[bufferoffset++]= 0x04; h_samp*=8; v_samp*=8; ri=(t2p->tiff_width+h_samp-1) / h_samp; TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows); ri*=(rows+v_samp-1)/v_samp; buffer[bufferoffset++]= (ri>>8) & 0xff; buffer[bufferoffset++]= ri & 0xff; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0 ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } } else { if(! t2p->pdf_ojpegdata){ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with bad tables", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); _TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength); bufferoffset=t2p->pdf_ojpegdatalength; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } if( ! ( (buffer[bufferoffset-1]==0xd9) && (buffer[bufferoffset-2]==0xff) ) ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with no JPEG File Interchange offset", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } return(t2p->tiff_datasize); } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG) { uint32 count = 0; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); if (TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) { if(count > 4) { _TIFFmemcpy(buffer, jpt, count); bufferoffset += count - 2; } } stripcount=TIFFNumberOfStrips(input); TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); for(i=0;i<stripcount;i++){ if(sbc[i]>max_striplength) max_striplength=sbc[i]; } stripbuffer = (unsigned char*) _TIFFmalloc(max_striplength); if(stripbuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", max_striplength, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } for(i=0;i<stripcount;i++){ striplength=TIFFReadRawStrip(input, i, (tdata_t) stripbuffer, -1); if(!t2p_process_jpeg_strip( stripbuffer, &striplength, buffer, &bufferoffset, i, t2p->tiff_length)){ TIFFError(TIFF2PDF_MODULE, "Can't process JPEG data in input file %s", TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(stripbuffer); _TIFFfree(buffer); return(bufferoffset); } #endif (void)0; } if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], stripsize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } } else { if(t2p->pdf_sample & T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){ sepstripsize=TIFFStripSize(input); sepstripcount=TIFFNumberOfStrips(input); stripsize=sepstripsize*t2p->tiff_samplesperpixel; stripcount=sepstripcount/t2p->tiff_samplesperpixel; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); samplebuffer = (unsigned char*) _TIFFmalloc(stripsize); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } for(i=0;i<stripcount;i++){ samplebufferoffset=0; for(j=0;j<t2p->tiff_samplesperpixel;j++){ read = TIFFReadEncodedStrip(input, i + j*stripcount, (tdata_t) &(samplebuffer[samplebufferoffset]), sepstripsize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i + j*stripcount, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } samplebufferoffset+=read; } t2p_sample_planar_separate_to_contig( t2p, &(buffer[bufferoffset]), samplebuffer, samplebufferoffset); bufferoffset+=samplebufferoffset; } _TIFFfree(samplebuffer); goto dataready; } buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], stripsize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){ samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t) buffer, t2p->tiff_datasize * t2p->tiff_samplesperpixel); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); } else { buffer=samplebuffer; t2p->tiff_datasize *= t2p->tiff_samplesperpixel; } t2p_sample_realize_palette(t2p, buffer); } if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgba_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){ samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length*4); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } else { buffer=samplebuffer; } if(!TIFFReadRGBAImageOriented( input, t2p->tiff_width, t2p->tiff_length, (uint32*)buffer, ORIENTATION_TOPLEFT, 0)){ TIFFError(TIFF2PDF_MODULE, "Can't use TIFFReadRGBAImageOriented to extract RGB image from %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } t2p->tiff_datasize=t2p_sample_abgr_to_rgb( (tdata_t) buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){ t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } } dataready: t2p_disable(output); TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric); TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample); TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel); TIFFSetField(output, TIFFTAG_IMAGEWIDTH, t2p->tiff_width); TIFFSetField(output, TIFFTAG_IMAGELENGTH, t2p->tiff_length); TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_length); TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB); switch(t2p->pdf_compression){ case T2P_COMPRESS_NONE: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE); break; #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4); break; #endif #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: if(t2p->tiff_photometric==PHOTOMETRIC_YCBCR) { uint16 hor = 0, ver = 0; if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver) !=0 ) { if(hor != 0 && ver != 0){ TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver); } } if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){ TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp); } } if(TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG)==0){ TIFFError(TIFF2PDF_MODULE, "Unable to use JPEG compression for input %s and output %s", TIFFFileName(input), TIFFFileName(output)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){ TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){ TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW); } } if(t2p->pdf_colorspace & T2P_CS_GRAY){ (void)0; } if(t2p->pdf_colorspace & T2P_CS_CMYK){ (void)0; } if(t2p->pdf_defaultcompressionquality != 0){ TIFFSetField(output, TIFFTAG_JPEGQUALITY, t2p->pdf_defaultcompressionquality); } break; #endif #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE); if(t2p->pdf_defaultcompressionquality%100 != 0){ TIFFSetField(output, TIFFTAG_PREDICTOR, t2p->pdf_defaultcompressionquality % 100); } if(t2p->pdf_defaultcompressionquality/100 != 0){ TIFFSetField(output, TIFFTAG_ZIPQUALITY, (t2p->pdf_defaultcompressionquality / 100)); } break; #endif default: break; } t2p_enable(output); t2p->outputwritten = 0; #ifdef JPEG_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_JPEG && t2p->tiff_photometric == PHOTOMETRIC_YCBCR){ bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, stripsize * stripcount); } else #endif { bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, t2p->tiff_datasize); } if (buffer != NULL) { _TIFFfree(buffer); buffer=NULL; } if (bufferoffset == (tsize_t)-1) { TIFFError(TIFF2PDF_MODULE, "Error writing encoded strip to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } written = t2p->outputwritten; return(written); } /* * This function reads the raster image data from the input TIFF for an image * tile and writes the data to the output PDF XObject image dictionary stream * for the tile. It returns the amount written or zero on error. */ tsize_t t2p_readwrite_pdf_image_tile(T2P* t2p, TIFF* input, TIFF* output, ttile_t tile){ uint16 edge=0; tsize_t written=0; unsigned char* buffer=NULL; tsize_t bufferoffset=0; unsigned char* samplebuffer=NULL; tsize_t samplebufferoffset=0; tsize_t read=0; uint16 i=0; ttile_t tilecount=0; tsize_t tilesize=0; ttile_t septilecount=0; tsize_t septilesize=0; #ifdef JPEG_SUPPORT unsigned char* jpt; float* xfloatp; uint32 xuint32=0; #endif edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile); edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile); if( (t2p->pdf_transcode == T2P_TRANSCODE_RAW) && ((edge == 0) #if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT) || (t2p->pdf_compression == T2P_COMPRESS_JPEG) #endif ) ){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4){ buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif #ifdef ZIP_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_ZIP){ buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG){ if(! t2p->pdf_ojpegdata){ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with " "bad tables", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } buffer=(unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } _TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength); if(edge!=0){ if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){ buffer[7]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength >> 8) & 0xff; buffer[8]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength ) & 0xff; } if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){ buffer[9]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth >> 8) & 0xff; buffer[10]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth ) & 0xff; } } bufferoffset=t2p->pdf_ojpegdatalength; bufferoffset+=TIFFReadRawTile(input, tile, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); ((unsigned char*)buffer)[bufferoffset++]=0xff; ((unsigned char*)buffer)[bufferoffset++]=0xd9; t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG){ unsigned char table_end[2]; uint32 count = 0; buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) { if (count > 0) { _TIFFmemcpy(buffer, jpt, count); bufferoffset += count - 2; table_end[0] = buffer[bufferoffset-2]; table_end[1] = buffer[bufferoffset-1]; } if (count > 0) { xuint32 = bufferoffset; bufferoffset += TIFFReadRawTile( input, tile, (tdata_t) &(((unsigned char*)buffer)[bufferoffset-2]), -1); buffer[xuint32-2]=table_end[0]; buffer[xuint32-1]=table_end[1]; } else { bufferoffset += TIFFReadRawTile( input, tile, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } #endif (void)0; } if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for " "t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } read = TIFFReadEncodedTile( input, tile, (tdata_t) &buffer[bufferoffset], t2p->tiff_datasize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding tile %u of %s", tile, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } } else { if(t2p->pdf_sample == T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){ septilesize=TIFFTileSize(input); septilecount=TIFFNumberOfTiles(input); tilesize=septilesize*t2p->tiff_samplesperpixel; tilecount=septilecount/t2p->tiff_samplesperpixel; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } samplebuffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } samplebufferoffset=0; for(i=0;i<t2p->tiff_samplesperpixel;i++){ read = TIFFReadEncodedTile(input, tile + i*tilecount, (tdata_t) &(samplebuffer[samplebufferoffset]), septilesize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding tile %u of %s", tile + i*tilecount, TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } samplebufferoffset+=read; } t2p_sample_planar_separate_to_contig( t2p, &(buffer[bufferoffset]), samplebuffer, samplebufferoffset); bufferoffset+=samplebufferoffset; _TIFFfree(samplebuffer); } if(buffer==NULL){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } read = TIFFReadEncodedTile( input, tile, (tdata_t) &buffer[bufferoffset], t2p->tiff_datasize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding tile %u of %s", tile, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } } if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgba_to_rgb( (tdata_t)buffer, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth *t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb( (tdata_t)buffer, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth *t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){ TIFFError(TIFF2PDF_MODULE, "No support for YCbCr to RGB in tile for %s", TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){ t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned( (tdata_t)buffer, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth *t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } } if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) != 0){ t2p_tile_collapse_left( buffer, TIFFTileRowSize(input), t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth, t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } t2p_disable(output); TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric); TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample); TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel); if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){ TIFFSetField( output, TIFFTAG_IMAGEWIDTH, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth); } else { TIFFSetField( output, TIFFTAG_IMAGEWIDTH, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth); } if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){ TIFFSetField( output, TIFFTAG_IMAGELENGTH, t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); TIFFSetField( output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } else { TIFFSetField( output, TIFFTAG_IMAGELENGTH, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); TIFFSetField( output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); } TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB); switch(t2p->pdf_compression){ case T2P_COMPRESS_NONE: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE); break; #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4); break; #endif #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: if (t2p->tiff_photometric==PHOTOMETRIC_YCBCR) { uint16 hor = 0, ver = 0; if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver)!=0) { if (hor != 0 && ver != 0) { TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver); } } if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){ TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp); } } TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG); TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); /* JPEGTABLESMODE_NONE */ if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){ TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){ TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW); } } if(t2p->pdf_colorspace & T2P_CS_GRAY){ (void)0; } if(t2p->pdf_colorspace & T2P_CS_CMYK){ (void)0; } if(t2p->pdf_defaultcompressionquality != 0){ TIFFSetField(output, TIFFTAG_JPEGQUALITY, t2p->pdf_defaultcompressionquality); } break; #endif #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE); if(t2p->pdf_defaultcompressionquality%100 != 0){ TIFFSetField(output, TIFFTAG_PREDICTOR, t2p->pdf_defaultcompressionquality % 100); } if(t2p->pdf_defaultcompressionquality/100 != 0){ TIFFSetField(output, TIFFTAG_ZIPQUALITY, (t2p->pdf_defaultcompressionquality / 100)); } break; #endif default: break; } t2p_enable(output); t2p->outputwritten = 0; bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t) 0, buffer, TIFFStripSize(output)); if (buffer != NULL) { _TIFFfree(buffer); buffer = NULL; } if (bufferoffset == -1) { TIFFError(TIFF2PDF_MODULE, "Error writing encoded tile to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } written = t2p->outputwritten; return(written); } #ifdef OJPEG_SUPPORT int t2p_process_ojpeg_tables(T2P* t2p, TIFF* input){ uint16 proc=0; void* q; uint32 q_length=0; void* dc; uint32 dc_length=0; void* ac; uint32 ac_length=0; uint16* lp; uint16* pt; uint16 h_samp=1; uint16 v_samp=1; unsigned char* ojpegdata; uint16 table_count; uint32 offset_table; uint32 offset_ms_l; uint32 code_count; uint32 i=0; uint32 dest=0; uint16 ri=0; uint32 rows=0; if(!TIFFGetField(input, TIFFTAG_JPEGPROC, &proc)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGProc field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(proc!=JPEGPROC_BASELINE && proc!=JPEGPROC_LOSSLESS){ TIFFError(TIFF2PDF_MODULE, "Bad JPEGProc field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(!TIFFGetField(input, TIFFTAG_JPEGQTABLES, &q_length, &q)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGQTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(q_length < (64U * t2p->tiff_samplesperpixel)){ TIFFError(TIFF2PDF_MODULE, "Bad JPEGQTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(!TIFFGetField(input, TIFFTAG_JPEGDCTABLES, &dc_length, &dc)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGDCTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(proc==JPEGPROC_BASELINE){ if(!TIFFGetField(input, TIFFTAG_JPEGACTABLES, &ac_length, &ac)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGACTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } else { if(!TIFFGetField(input, TIFFTAG_JPEGLOSSLESSPREDICTORS, &lp)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGLosslessPredictors field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(!TIFFGetField(input, TIFFTAG_JPEGPOINTTRANSFORM, &pt)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGPointTransform field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } if(!TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp)){ h_samp=1; v_samp=1; } if(t2p->pdf_ojpegdata != NULL){ _TIFFfree(t2p->pdf_ojpegdata); t2p->pdf_ojpegdata=NULL; } t2p->pdf_ojpegdata = _TIFFmalloc(2048); if(t2p->pdf_ojpegdata == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_process_ojpeg_tables, %s", 2048, TIFFFileName(input)); return(0); } _TIFFmemset(t2p->pdf_ojpegdata, 0x00, 2048); t2p->pdf_ojpegdatalength = 0; table_count=t2p->tiff_samplesperpixel; if(proc==JPEGPROC_BASELINE){ if(table_count>2) table_count=2; } ojpegdata=(unsigned char*)t2p->pdf_ojpegdata; ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xd8; ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; if(proc==JPEGPROC_BASELINE){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xc0; } else { ojpegdata[t2p->pdf_ojpegdatalength++]=0xc3; } ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=(8 + 3*t2p->tiff_samplesperpixel); ojpegdata[t2p->pdf_ojpegdatalength++]=(t2p->tiff_bitspersample & 0xff); if(TIFFIsTiled(input)){ ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength ) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth ) & 0xff; } else { ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_length >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_length ) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_width >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_width ) & 0xff; } ojpegdata[t2p->pdf_ojpegdatalength++]=(t2p->tiff_samplesperpixel & 0xff); for(i=0;i<t2p->tiff_samplesperpixel;i++){ ojpegdata[t2p->pdf_ojpegdatalength++]=i; if(i==0){ ojpegdata[t2p->pdf_ojpegdatalength] |= h_samp<<4 & 0xf0;; ojpegdata[t2p->pdf_ojpegdatalength++] |= v_samp & 0x0f; } else { ojpegdata[t2p->pdf_ojpegdatalength++]= 0x11; } ojpegdata[t2p->pdf_ojpegdatalength++]=i; } for(dest=0;dest<t2p->tiff_samplesperpixel;dest++){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xdb; ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=0x43; ojpegdata[t2p->pdf_ojpegdatalength++]=dest; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength++]), &(((unsigned char*)q)[64*dest]), 64); t2p->pdf_ojpegdatalength+=64; } offset_table=0; for(dest=0;dest<table_count;dest++){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xc4; offset_ms_l=t2p->pdf_ojpegdatalength; t2p->pdf_ojpegdatalength+=2; ojpegdata[t2p->pdf_ojpegdatalength++]=dest & 0x0f; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)dc)[offset_table]), 16); code_count=0; offset_table+=16; for(i=0;i<16;i++){ code_count+=ojpegdata[t2p->pdf_ojpegdatalength++]; } ojpegdata[offset_ms_l]=((19+code_count)>>8) & 0xff; ojpegdata[offset_ms_l+1]=(19+code_count) & 0xff; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)dc)[offset_table]), code_count); offset_table+=code_count; t2p->pdf_ojpegdatalength+=code_count; } if(proc==JPEGPROC_BASELINE){ offset_table=0; for(dest=0;dest<table_count;dest++){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xc4; offset_ms_l=t2p->pdf_ojpegdatalength; t2p->pdf_ojpegdatalength+=2; ojpegdata[t2p->pdf_ojpegdatalength] |= 0x10; ojpegdata[t2p->pdf_ojpegdatalength++] |=dest & 0x0f; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)ac)[offset_table]), 16); code_count=0; offset_table+=16; for(i=0;i<16;i++){ code_count+=ojpegdata[t2p->pdf_ojpegdatalength++]; } ojpegdata[offset_ms_l]=((19+code_count)>>8) & 0xff; ojpegdata[offset_ms_l+1]=(19+code_count) & 0xff; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)ac)[offset_table]), code_count); offset_table+=code_count; t2p->pdf_ojpegdatalength+=code_count; } } if(TIFFNumberOfStrips(input)>1){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xdd; ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=0x04; h_samp*=8; v_samp*=8; ri=(t2p->tiff_width+h_samp-1) / h_samp; TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows); ri*=(rows+v_samp-1)/v_samp; ojpegdata[t2p->pdf_ojpegdatalength++]= (ri>>8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= ri & 0xff; } ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xda; ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=(6 + 2*t2p->tiff_samplesperpixel); ojpegdata[t2p->pdf_ojpegdatalength++]=t2p->tiff_samplesperpixel & 0xff; for(i=0;i<t2p->tiff_samplesperpixel;i++){ ojpegdata[t2p->pdf_ojpegdatalength++]= i & 0xff; if(proc==JPEGPROC_BASELINE){ ojpegdata[t2p->pdf_ojpegdatalength] |= ( ( (i>(table_count-1U)) ? (table_count-1U) : i) << 4U) & 0xf0; ojpegdata[t2p->pdf_ojpegdatalength++] |= ( (i>(table_count-1U)) ? (table_count-1U) : i) & 0x0f; } else { ojpegdata[t2p->pdf_ojpegdatalength++] = (i << 4) & 0xf0; } } if(proc==JPEGPROC_BASELINE){ t2p->pdf_ojpegdatalength++; ojpegdata[t2p->pdf_ojpegdatalength++]=0x3f; t2p->pdf_ojpegdatalength++; } else { ojpegdata[t2p->pdf_ojpegdatalength++]= (lp[0] & 0xff); t2p->pdf_ojpegdatalength++; ojpegdata[t2p->pdf_ojpegdatalength++]= (pt[0] & 0x0f); } return(1); } #endif #ifdef JPEG_SUPPORT int t2p_process_jpeg_strip( unsigned char* strip, tsize_t* striplength, unsigned char* buffer, tsize_t* bufferoffset, tstrip_t no, uint32 height){ tsize_t i=0; uint16 ri =0; uint16 v_samp=1; uint16 h_samp=1; int j=0; i++; while(i<(*striplength)){ switch( strip[i] ){ case 0xd8: /* SOI - start of image */ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), 2); *bufferoffset+=2; i+=2; break; case 0xc0: case 0xc1: case 0xc3: case 0xc9: case 0xca: if(no==0){ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), strip[i+2]+2); for(j=0;j<buffer[*bufferoffset+9];j++){ if( (buffer[*bufferoffset+11+(2*j)]>>4) > h_samp) h_samp = (buffer[*bufferoffset+11+(2*j)]>>4); if( (buffer[*bufferoffset+11+(2*j)] & 0x0f) > v_samp) v_samp = (buffer[*bufferoffset+11+(2*j)] & 0x0f); } v_samp*=8; h_samp*=8; ri=((( ((uint16)(buffer[*bufferoffset+5])<<8) | (uint16)(buffer[*bufferoffset+6]) )+v_samp-1)/ v_samp); ri*=((( ((uint16)(buffer[*bufferoffset+7])<<8) | (uint16)(buffer[*bufferoffset+8]) )+h_samp-1)/ h_samp); buffer[*bufferoffset+5]= (unsigned char) ((height>>8) & 0xff); buffer[*bufferoffset+6]= (unsigned char) (height & 0xff); *bufferoffset+=strip[i+2]+2; i+=strip[i+2]+2; buffer[(*bufferoffset)++]=0xff; buffer[(*bufferoffset)++]=0xdd; buffer[(*bufferoffset)++]=0x00; buffer[(*bufferoffset)++]=0x04; buffer[(*bufferoffset)++]=(ri >> 8) & 0xff; buffer[(*bufferoffset)++]= ri & 0xff; } else { i+=strip[i+2]+2; } break; case 0xc4: case 0xdb: _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), strip[i+2]+2); *bufferoffset+=strip[i+2]+2; i+=strip[i+2]+2; break; case 0xda: if(no==0){ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), strip[i+2]+2); *bufferoffset+=strip[i+2]+2; i+=strip[i+2]+2; } else { buffer[(*bufferoffset)++]=0xff; buffer[(*bufferoffset)++]= (unsigned char)(0xd0 | ((no-1)%8)); i+=strip[i+2]+2; } _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), (*striplength)-i-1); *bufferoffset+=(*striplength)-i-1; return(1); default: i+=strip[i+2]+2; } } return(0); } #endif /* This functions converts a tilewidth x tilelength buffer of samples into an edgetilewidth x tilelength buffer of samples. */ void t2p_tile_collapse_left( tdata_t buffer, tsize_t scanwidth, uint32 tilewidth, uint32 edgetilewidth, uint32 tilelength){ uint32 i=0; tsize_t edgescanwidth=0; edgescanwidth = (scanwidth * edgetilewidth + (tilewidth - 1))/ tilewidth; for(i=i;i<tilelength;i++){ _TIFFmemcpy( &(((char*)buffer)[edgescanwidth*i]), &(((char*)buffer)[scanwidth*i]), edgescanwidth); } return; } /* * This function calls TIFFWriteDirectory on the output after blanking its * output by replacing the read, write, and seek procedures with empty * implementations, then it replaces the original implementations. */ void t2p_write_advance_directory(T2P* t2p, TIFF* output) { t2p_disable(output); if(!TIFFWriteDirectory(output)){ TIFFError(TIFF2PDF_MODULE, "Error writing virtual directory to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p_enable(output); return; } tsize_t t2p_sample_planar_separate_to_contig( T2P* t2p, unsigned char* buffer, unsigned char* samplebuffer, tsize_t samplebuffersize){ tsize_t stride=0; tsize_t i=0; tsize_t j=0; stride=samplebuffersize/t2p->tiff_samplesperpixel; for(i=0;i<stride;i++){ for(j=0;j<t2p->tiff_samplesperpixel;j++){ buffer[i*t2p->tiff_samplesperpixel + j] = samplebuffer[i + j*stride]; } } return(samplebuffersize); } tsize_t t2p_sample_realize_palette(T2P* t2p, unsigned char* buffer){ uint32 sample_count=0; uint16 component_count=0; uint32 palette_offset=0; uint32 sample_offset=0; uint32 i=0; uint32 j=0; sample_count=t2p->tiff_width*t2p->tiff_length; component_count=t2p->tiff_samplesperpixel; for(i=sample_count;i>0;i--){ palette_offset=buffer[i-1] * component_count; sample_offset= (i-1) * component_count; for(j=0;j<component_count;j++){ buffer[sample_offset+j]=t2p->pdf_palette[palette_offset+j]; } } return(0); } /* This functions converts in place a buffer of ABGR interleaved data into RGB interleaved data, discarding A. */ tsize_t t2p_sample_abgr_to_rgb(tdata_t data, uint32 samplecount) { uint32 i=0; uint32 sample=0; for(i=0;i<samplecount;i++){ sample=((uint32*)data)[i]; ((char*)data)[i*3]= (char) (sample & 0xff); ((char*)data)[i*3+1]= (char) ((sample>>8) & 0xff); ((char*)data)[i*3+2]= (char) ((sample>>16) & 0xff); } return(i*3); } /* * This functions converts in place a buffer of RGBA interleaved data * into RGB interleaved data, discarding A. */ tsize_t t2p_sample_rgbaa_to_rgb(tdata_t data, uint32 samplecount) { uint32 i; for(i = 0; i < samplecount; i++) memcpy((uint8*)data + i * 3, (uint8*)data + i * 4, 3); return(i * 3); } /* * This functions converts in place a buffer of RGBA interleaved data * into RGB interleaved data, adding 255-A to each component sample. */ tsize_t t2p_sample_rgba_to_rgb(tdata_t data, uint32 samplecount) { uint32 i = 0; uint32 sample = 0; uint8 alpha = 0; for (i = 0; i < samplecount; i++) { sample=((uint32*)data)[i]; alpha=(uint8)((255 - (sample & 0xff))); ((uint8 *)data)[i * 3] = (uint8) ((sample >> 24) & 0xff) + alpha; ((uint8 *)data)[i * 3 + 1] = (uint8) ((sample >> 16) & 0xff) + alpha; ((uint8 *)data)[i * 3 + 2] = (uint8) ((sample >> 8) & 0xff) + alpha; } return (i * 3); } /* This function converts the a and b samples of Lab data from signed to unsigned. */ tsize_t t2p_sample_lab_signed_to_unsigned(tdata_t buffer, uint32 samplecount){ uint32 i=0; for(i=0;i<samplecount;i++){ if( (((unsigned char*)buffer)[(i*3)+1] & 0x80) !=0){ ((unsigned char*)buffer)[(i*3)+1] = (unsigned char)(0x80 + ((char*)buffer)[(i*3)+1]); } else { ((unsigned char*)buffer)[(i*3)+1] |= 0x80; } if( (((unsigned char*)buffer)[(i*3)+2] & 0x80) !=0){ ((unsigned char*)buffer)[(i*3)+2] = (unsigned char)(0x80 + ((char*)buffer)[(i*3)+2]); } else { ((unsigned char*)buffer)[(i*3)+2] |= 0x80; } } return(samplecount*3); } /* This function writes the PDF header to output. */ tsize_t t2p_write_pdf_header(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; buflen=sprintf(buffer, "%%PDF-%u.%u ", t2p->pdf_majorversion&0xff, t2p->pdf_minorversion&0xff); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t)"\n%\342\343\317\323\n", 7); return(written); } /* This function writes the beginning of a PDF object to output. */ tsize_t t2p_write_pdf_obj_start(uint32 number, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; buflen=sprintf(buffer, "%lu", (unsigned long)number); written += t2pWriteFile(output, (tdata_t) buffer, buflen ); written += t2pWriteFile(output, (tdata_t) " 0 obj\n", 7); return(written); } /* This function writes the end of a PDF object to output. */ tsize_t t2p_write_pdf_obj_end(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "endobj\n", 7); return(written); } /* This function writes a PDF name object to output. */ tsize_t t2p_write_pdf_name(unsigned char* name, TIFF* output){ tsize_t written=0; uint32 i=0; char buffer[64]; uint16 nextchar=0; size_t namelen=0; namelen = strlen((char *)name); if (namelen>126) { namelen=126; } written += t2pWriteFile(output, (tdata_t) "/", 1); for (i=0;i<namelen;i++){ if ( ((unsigned char)name[i]) < 0x21){ sprintf(buffer, "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); nextchar=1; } if ( ((unsigned char)name[i]) > 0x7E){ sprintf(buffer, "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); nextchar=1; } if (nextchar==0){ switch (name[i]){ case 0x23: sprintf(buffer, "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x25: sprintf(buffer, "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x28: sprintf(buffer, "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x29: sprintf(buffer, "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x2F: sprintf(buffer, "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x3C: sprintf(buffer, "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x3E: sprintf(buffer, "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x5B: sprintf(buffer, "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x5D: sprintf(buffer, "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x7B: sprintf(buffer, "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; case 0x7D: sprintf(buffer, "#%.2X", name[i]); buffer[sizeof(buffer) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) buffer, 3); break; default: written += t2pWriteFile(output, (tdata_t) &name[i], 1); } } nextchar=0; } written += t2pWriteFile(output, (tdata_t) " ", 1); return(written); } /* * This function writes a PDF string object to output. */ tsize_t t2p_write_pdf_string(char* pdfstr, TIFF* output) { tsize_t written = 0; uint32 i = 0; char buffer[64]; size_t len = 0; len = strlen(pdfstr); written += t2pWriteFile(output, (tdata_t) "(", 1); for (i=0; i<len; i++) { if((pdfstr[i]&0x80) || (pdfstr[i]==127) || (pdfstr[i]<32)){ snprintf(buffer, sizeof(buffer), "\\%.3hho", pdfstr[i]); written += t2pWriteFile(output, (tdata_t)buffer, 4); } else { switch (pdfstr[i]){ case 0x08: written += t2pWriteFile(output, (tdata_t) "\\b", 2); break; case 0x09: written += t2pWriteFile(output, (tdata_t) "\\t", 2); break; case 0x0A: written += t2pWriteFile(output, (tdata_t) "\\n", 2); break; case 0x0C: written += t2pWriteFile(output, (tdata_t) "\\f", 2); break; case 0x0D: written += t2pWriteFile(output, (tdata_t) "\\r", 2); break; case 0x28: written += t2pWriteFile(output, (tdata_t) "\\(", 2); break; case 0x29: written += t2pWriteFile(output, (tdata_t) "\\)", 2); break; case 0x5C: written += t2pWriteFile(output, (tdata_t) "\\\\", 2); break; default: written += t2pWriteFile(output, (tdata_t) &pdfstr[i], 1); } } } written += t2pWriteFile(output, (tdata_t) ") ", 1); return(written); } /* This function writes a buffer of data to output. */ tsize_t t2p_write_pdf_stream(tdata_t buffer, tsize_t len, TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) buffer, len); return(written); } /* This functions writes the beginning of a PDF stream to output. */ tsize_t t2p_write_pdf_stream_start(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "stream\n", 7); return(written); } /* This function writes the end of a PDF stream to output. */ tsize_t t2p_write_pdf_stream_end(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "\nendstream\n", 11); return(written); } /* This function writes a stream dictionary for a PDF stream to output. */ tsize_t t2p_write_pdf_stream_dict(tsize_t len, uint32 number, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "/Length ", 8); if(len!=0){ written += t2p_write_pdf_stream_length(len, output); } else { buflen=sprintf(buffer, "%lu", (unsigned long)number); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); } return(written); } /* This functions writes the beginning of a PDF stream dictionary to output. */ tsize_t t2p_write_pdf_stream_dict_start(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) "<< \n", 4); return(written); } /* This function writes the end of a PDF stream dictionary to output. */ tsize_t t2p_write_pdf_stream_dict_end(TIFF* output){ tsize_t written=0; written += t2pWriteFile(output, (tdata_t) " >>\n", 4); return(written); } /* This function writes a number to output. */ tsize_t t2p_write_pdf_stream_length(tsize_t len, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; buflen=sprintf(buffer, "%lu", (unsigned long)len); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n", 1); return(written); } /* * This function writes the PDF Catalog structure to output. */ tsize_t t2p_write_pdf_catalog(T2P* t2p, TIFF* output) { tsize_t written = 0; char buffer[16]; int buflen = 0; written += t2pWriteFile(output, (tdata_t)"<< \n/Type /Catalog \n/Pages ", 27); buflen = snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)t2p->pdf_pages); written += t2pWriteFile(output, (tdata_t) buffer, TIFFmin((size_t)buflen, sizeof(buffer) - 1)); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); if(t2p->pdf_fitwindow){ written += t2pWriteFile(output, (tdata_t) "/ViewerPreferences <</FitWindow true>>\n", 39); } written += t2pWriteFile(output, (tdata_t)">>\n", 3); return(written); } /* This function writes the PDF Info structure to output. */ tsize_t t2p_write_pdf_info(T2P* t2p, TIFF* input, TIFF* output) { tsize_t written = 0; char* info; char buffer[512]; if(t2p->pdf_datetime[0] == '\0') t2p_pdf_tifftime(t2p, input); if (strlen(t2p->pdf_datetime) > 0) { written += t2pWriteFile(output, (tdata_t) "<< \n/CreationDate ", 18); written += t2p_write_pdf_string(t2p->pdf_datetime, output); written += t2pWriteFile(output, (tdata_t) "\n/ModDate ", 10); written += t2p_write_pdf_string(t2p->pdf_datetime, output); } written += t2pWriteFile(output, (tdata_t) "\n/Producer ", 11); _TIFFmemset((tdata_t)buffer, 0x00, sizeof(buffer)); snprintf(buffer, sizeof(buffer), "libtiff / tiff2pdf - %d", TIFFLIB_VERSION); written += t2p_write_pdf_string(buffer, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); if (t2p->pdf_creator[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Creator ", 9); written += t2p_write_pdf_string(t2p->pdf_creator, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if (TIFFGetField(input, TIFFTAG_SOFTWARE, &info) != 0 && info) { if(strlen(info) >= sizeof(t2p->pdf_creator)) info[sizeof(t2p->pdf_creator) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) "/Creator ", 9); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_author[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Author ", 8); written += t2p_write_pdf_string(t2p->pdf_author, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if ((TIFFGetField(input, TIFFTAG_ARTIST, &info) != 0 || TIFFGetField(input, TIFFTAG_COPYRIGHT, &info) != 0) && info) { if (strlen(info) >= sizeof(t2p->pdf_author)) info[sizeof(t2p->pdf_author) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) "/Author ", 8); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_title[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Title ", 7); written += t2p_write_pdf_string(t2p->pdf_title, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if (TIFFGetField(input, TIFFTAG_DOCUMENTNAME, &info) != 0){ if(strlen(info) > 511) { info[512] = '\0'; } written += t2pWriteFile(output, (tdata_t) "/Title ", 7); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_subject[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Subject ", 9); written += t2p_write_pdf_string(t2p->pdf_subject, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } else { if (TIFFGetField(input, TIFFTAG_IMAGEDESCRIPTION, &info) != 0 && info) { if (strlen(info) >= sizeof(t2p->pdf_subject)) info[sizeof(t2p->pdf_subject) - 1] = '\0'; written += t2pWriteFile(output, (tdata_t) "/Subject ", 9); written += t2p_write_pdf_string(info, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } } if (t2p->pdf_keywords[0] != '\0') { written += t2pWriteFile(output, (tdata_t) "/Keywords ", 10); written += t2p_write_pdf_string(t2p->pdf_keywords, output); written += t2pWriteFile(output, (tdata_t) "\n", 1); } written += t2pWriteFile(output, (tdata_t) ">> \n", 4); return(written); } /* * This function fills a string of a T2P struct with the current time as a PDF * date string, it is called by t2p_pdf_tifftime. */ void t2p_pdf_currenttime(T2P* t2p) { struct tm* currenttime; time_t timenow; if (time(&timenow) == (time_t) -1) { TIFFError(TIFF2PDF_MODULE, "Can't get the current time: %s", strerror(errno)); timenow = (time_t) 0; } currenttime = localtime(&timenow); snprintf(t2p->pdf_datetime, sizeof(t2p->pdf_datetime), "D:%.4d%.2d%.2d%.2d%.2d%.2d", (currenttime->tm_year + 1900) % 65536, (currenttime->tm_mon + 1) % 256, (currenttime->tm_mday) % 256, (currenttime->tm_hour) % 256, (currenttime->tm_min) % 256, (currenttime->tm_sec) % 256); return; } /* * This function fills a string of a T2P struct with the date and time of a * TIFF file if it exists or the current time as a PDF date string. */ void t2p_pdf_tifftime(T2P* t2p, TIFF* input) { char* datetime; if (TIFFGetField(input, TIFFTAG_DATETIME, &datetime) != 0 && (strlen(datetime) >= 19) ){ t2p->pdf_datetime[0]='D'; t2p->pdf_datetime[1]=':'; t2p->pdf_datetime[2]=datetime[0]; t2p->pdf_datetime[3]=datetime[1]; t2p->pdf_datetime[4]=datetime[2]; t2p->pdf_datetime[5]=datetime[3]; t2p->pdf_datetime[6]=datetime[5]; t2p->pdf_datetime[7]=datetime[6]; t2p->pdf_datetime[8]=datetime[8]; t2p->pdf_datetime[9]=datetime[9]; t2p->pdf_datetime[10]=datetime[11]; t2p->pdf_datetime[11]=datetime[12]; t2p->pdf_datetime[12]=datetime[14]; t2p->pdf_datetime[13]=datetime[15]; t2p->pdf_datetime[14]=datetime[17]; t2p->pdf_datetime[15]=datetime[18]; t2p->pdf_datetime[16] = '\0'; } else { t2p_pdf_currenttime(t2p); } return; } /* * This function writes a PDF Pages Tree structure to output. */ tsize_t t2p_write_pdf_pages(T2P* t2p, TIFF* output) { tsize_t written=0; tdir_t i=0; char buffer[16]; int buflen=0; int page=0; written += t2pWriteFile(output, (tdata_t) "<< \n/Type /Pages \n/Kids [ ", 26); page = t2p->pdf_pages+1; for (i=0;i<t2p->tiff_pagecount;i++){ buflen=sprintf(buffer, "%d", page); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); if ( ((i+1)%8)==0 ) { written += t2pWriteFile(output, (tdata_t) "\n", 1); } page +=3; page += t2p->tiff_pages[i].page_extra; if(t2p->tiff_pages[i].page_tilecount>0){ page += (2 * t2p->tiff_pages[i].page_tilecount); } else { page +=2; } } written += t2pWriteFile(output, (tdata_t) "] \n/Count ", 10); _TIFFmemset(buffer, 0x00, 16); buflen=sprintf(buffer, "%d", t2p->tiff_pagecount); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " \n>> \n", 6); return(written); } /* This function writes a PDF Page structure to output. */ tsize_t t2p_write_pdf_page(uint32 object, T2P* t2p, TIFF* output){ unsigned int i=0; tsize_t written=0; char buffer[16]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "<<\n/Type /Page \n/Parent ", 24); buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_pages); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); written += t2pWriteFile(output, (tdata_t) "/MediaBox [", 11); buflen=sprintf(buffer, "%.4f",t2p->pdf_mediabox.x1); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen=sprintf(buffer, "%.4f",t2p->pdf_mediabox.y1); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen=sprintf(buffer, "%.4f",t2p->pdf_mediabox.x2); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen=sprintf(buffer, "%.4f",t2p->pdf_mediabox.y2); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "] \n", 3); written += t2pWriteFile(output, (tdata_t) "/Contents ", 10); buflen=sprintf(buffer, "%lu", (unsigned long)(object + 1)); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R \n", 6); written += t2pWriteFile(output, (tdata_t) "/Resources << \n", 15); if( t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount != 0 ){ written += t2pWriteFile(output, (tdata_t) "/XObject <<\n", 12); for(i=0;i<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount;i++){ written += t2pWriteFile(output, (tdata_t) "/Im", 3); buflen = sprintf(buffer, "%u", t2p->pdf_page+1); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "_", 1); buflen = sprintf(buffer, "%u", i+1); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen = sprintf( buffer, "%lu", (unsigned long)(object+3+(2*i)+t2p->tiff_pages[t2p->pdf_page].page_extra)); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); if(i%4==3){ written += t2pWriteFile(output, (tdata_t) "\n", 1); } } written += t2pWriteFile(output, (tdata_t) ">>\n", 3); } else { written += t2pWriteFile(output, (tdata_t) "/XObject <<\n", 12); written += t2pWriteFile(output, (tdata_t) "/Im", 3); buflen = sprintf(buffer, "%u", t2p->pdf_page+1); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); buflen = sprintf( buffer, "%lu", (unsigned long)(object+3+(2*i)+t2p->tiff_pages[t2p->pdf_page].page_extra)); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); written += t2pWriteFile(output, (tdata_t) ">>\n", 3); } if(t2p->tiff_transferfunctioncount != 0) { written += t2pWriteFile(output, (tdata_t) "/ExtGState <<", 13); t2pWriteFile(output, (tdata_t) "/GS1 ", 5); buflen = sprintf( buffer, "%lu", (unsigned long)(object + 3)); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); written += t2pWriteFile(output, (tdata_t) ">> \n", 4); } written += t2pWriteFile(output, (tdata_t) "/ProcSet [ ", 11); if(t2p->pdf_colorspace == T2P_CS_BILEVEL || t2p->pdf_colorspace == T2P_CS_GRAY ){ written += t2pWriteFile(output, (tdata_t) "/ImageB ", 8); } else { written += t2pWriteFile(output, (tdata_t) "/ImageC ", 8); if(t2p->pdf_colorspace & T2P_CS_PALETTE){ written += t2pWriteFile(output, (tdata_t) "/ImageI ", 8); } } written += t2pWriteFile(output, (tdata_t) "]\n>>\n>>\n", 8); return(written); } /* This function composes the page size and image and tile locations on a page. */ void t2p_compose_pdf_page(T2P* t2p){ uint32 i=0; uint32 i2=0; T2P_TILE* tiles=NULL; T2P_BOX* boxp=NULL; uint32 tilecountx=0; uint32 tilecounty=0; uint32 tilewidth=0; uint32 tilelength=0; int istiled=0; float f=0; t2p->pdf_xres = t2p->tiff_xres; t2p->pdf_yres = t2p->tiff_yres; if(t2p->pdf_overrideres) { t2p->pdf_xres = t2p->pdf_defaultxres; t2p->pdf_yres = t2p->pdf_defaultyres; } if(t2p->pdf_xres == 0.0) t2p->pdf_xres = t2p->pdf_defaultxres; if(t2p->pdf_yres == 0.0) t2p->pdf_yres = t2p->pdf_defaultyres; if (t2p->tiff_resunit != RESUNIT_CENTIMETER /* RESUNIT_NONE and */ && t2p->tiff_resunit != RESUNIT_INCH) { /* other cases */ t2p->pdf_imagewidth = ((float)(t2p->tiff_width))/t2p->pdf_xres; t2p->pdf_imagelength = ((float)(t2p->tiff_length))/t2p->pdf_yres; } else { t2p->pdf_imagewidth = ((float)(t2p->tiff_width))*PS_UNIT_SIZE/t2p->pdf_xres; t2p->pdf_imagelength = ((float)(t2p->tiff_length))*PS_UNIT_SIZE/t2p->pdf_yres; } if(t2p->pdf_overridepagesize != 0) { t2p->pdf_pagewidth = t2p->pdf_defaultpagewidth; t2p->pdf_pagelength = t2p->pdf_defaultpagelength; } else { t2p->pdf_pagewidth = t2p->pdf_imagewidth; t2p->pdf_pagelength = t2p->pdf_imagelength; } t2p->pdf_mediabox.x1=0.0; t2p->pdf_mediabox.y1=0.0; t2p->pdf_mediabox.x2=t2p->pdf_pagewidth; t2p->pdf_mediabox.y2=t2p->pdf_pagelength; t2p->pdf_imagebox.x1=0.0; t2p->pdf_imagebox.y1=0.0; t2p->pdf_imagebox.x2=t2p->pdf_imagewidth; t2p->pdf_imagebox.y2=t2p->pdf_imagelength; if(t2p->pdf_overridepagesize!=0){ t2p->pdf_imagebox.x1+=((t2p->pdf_pagewidth-t2p->pdf_imagewidth)/2.0F); t2p->pdf_imagebox.y1+=((t2p->pdf_pagelength-t2p->pdf_imagelength)/2.0F); t2p->pdf_imagebox.x2+=((t2p->pdf_pagewidth-t2p->pdf_imagewidth)/2.0F); t2p->pdf_imagebox.y2+=((t2p->pdf_pagelength-t2p->pdf_imagelength)/2.0F); } if(t2p->tiff_orientation > 4){ f=t2p->pdf_mediabox.x2; t2p->pdf_mediabox.x2=t2p->pdf_mediabox.y2; t2p->pdf_mediabox.y2=f; } istiled=((t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount==0) ? 0 : 1; if(istiled==0){ t2p_compose_pdf_page_orient(&(t2p->pdf_imagebox), t2p->tiff_orientation); return; } else { tilewidth=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilewidth; tilelength=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilelength; tilecountx=(t2p->tiff_width + tilewidth -1)/ tilewidth; (t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecountx=tilecountx; tilecounty=(t2p->tiff_length + tilelength -1)/ tilelength; (t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecounty=tilecounty; (t2p->tiff_tiles[t2p->pdf_page]).tiles_edgetilewidth= t2p->tiff_width % tilewidth; (t2p->tiff_tiles[t2p->pdf_page]).tiles_edgetilelength= t2p->tiff_length % tilelength; tiles=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tiles; for(i2=0;i2<tilecounty-1;i2++){ for(i=0;i<tilecountx-1;i++){ boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * (i+1) * tilewidth) / (float)t2p->tiff_width); boxp->y1 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * (i2+1) * tilelength) / (float)t2p->tiff_length); boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x2; boxp->y1 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * (i2+1) * tilelength) / (float)t2p->tiff_length); boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } for(i=0;i<tilecountx-1;i++){ boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * (i+1) * tilewidth) / (float)t2p->tiff_width); boxp->y1 = t2p->pdf_imagebox.y1; boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x2; boxp->y1 = t2p->pdf_imagebox.y1; boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } if(t2p->tiff_orientation==0 || t2p->tiff_orientation==1){ for(i=0;i<(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount;i++){ t2p_compose_pdf_page_orient( &(tiles[i].tile_box) , 0); } return; } for(i=0;i<(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount;i++){ boxp=&(tiles[i].tile_box); boxp->x1 -= t2p->pdf_imagebox.x1; boxp->x2 -= t2p->pdf_imagebox.x1; boxp->y1 -= t2p->pdf_imagebox.y1; boxp->y2 -= t2p->pdf_imagebox.y1; if(t2p->tiff_orientation==2 || t2p->tiff_orientation==3){ boxp->x1 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x1; boxp->x2 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x2; } if(t2p->tiff_orientation==3 || t2p->tiff_orientation==4){ boxp->y1 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y1; boxp->y2 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y2; } if(t2p->tiff_orientation==8 || t2p->tiff_orientation==5){ boxp->y1 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y1; boxp->y2 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y2; } if(t2p->tiff_orientation==5 || t2p->tiff_orientation==6){ boxp->x1 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x1; boxp->x2 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x2; } if(t2p->tiff_orientation > 4){ f=boxp->x1; boxp->x1 = boxp->y1; boxp->y1 = f; f=boxp->x2; boxp->x2 = boxp->y2; boxp->y2 = f; t2p_compose_pdf_page_orient_flip(boxp, t2p->tiff_orientation); } else { t2p_compose_pdf_page_orient(boxp, t2p->tiff_orientation); } } return; } void t2p_compose_pdf_page_orient(T2P_BOX* boxp, uint16 orientation){ float m1[9]; float f=0.0; if( boxp->x1 > boxp->x2){ f=boxp->x1; boxp->x1=boxp->x2; boxp->x2 = f; } if( boxp->y1 > boxp->y2){ f=boxp->y1; boxp->y1=boxp->y2; boxp->y2 = f; } boxp->mat[0]=m1[0]=boxp->x2-boxp->x1; boxp->mat[1]=m1[1]=0.0; boxp->mat[2]=m1[2]=0.0; boxp->mat[3]=m1[3]=0.0; boxp->mat[4]=m1[4]=boxp->y2-boxp->y1; boxp->mat[5]=m1[5]=0.0; boxp->mat[6]=m1[6]=boxp->x1; boxp->mat[7]=m1[7]=boxp->y1; boxp->mat[8]=m1[8]=1.0; switch(orientation){ case 0: case 1: break; case 2: boxp->mat[0]=0.0F-m1[0]; boxp->mat[6]+=m1[0]; break; case 3: boxp->mat[0]=0.0F-m1[0]; boxp->mat[4]=0.0F-m1[4]; boxp->mat[6]+=m1[0]; boxp->mat[7]+=m1[4]; break; case 4: boxp->mat[4]=0.0F-m1[4]; boxp->mat[7]+=m1[4]; break; case 5: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[0]; boxp->mat[3]=0.0F-m1[4]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[4]; boxp->mat[7]+=m1[0]; break; case 6: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[0]; boxp->mat[3]=m1[4]; boxp->mat[4]=0.0F; boxp->mat[7]+=m1[0]; break; case 7: boxp->mat[0]=0.0F; boxp->mat[1]=m1[0]; boxp->mat[3]=m1[4]; boxp->mat[4]=0.0F; break; case 8: boxp->mat[0]=0.0F; boxp->mat[1]=m1[0]; boxp->mat[3]=0.0F-m1[4]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[4]; break; } return; } void t2p_compose_pdf_page_orient_flip(T2P_BOX* boxp, uint16 orientation){ float m1[9]; float f=0.0; if( boxp->x1 > boxp->x2){ f=boxp->x1; boxp->x1=boxp->x2; boxp->x2 = f; } if( boxp->y1 > boxp->y2){ f=boxp->y1; boxp->y1=boxp->y2; boxp->y2 = f; } boxp->mat[0]=m1[0]=boxp->x2-boxp->x1; boxp->mat[1]=m1[1]=0.0F; boxp->mat[2]=m1[2]=0.0F; boxp->mat[3]=m1[3]=0.0F; boxp->mat[4]=m1[4]=boxp->y2-boxp->y1; boxp->mat[5]=m1[5]=0.0F; boxp->mat[6]=m1[6]=boxp->x1; boxp->mat[7]=m1[7]=boxp->y1; boxp->mat[8]=m1[8]=1.0F; switch(orientation){ case 5: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[4]; boxp->mat[3]=0.0F-m1[0]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[0]; boxp->mat[7]+=m1[4]; break; case 6: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[4]; boxp->mat[3]=m1[0]; boxp->mat[4]=0.0F; boxp->mat[7]+=m1[4]; break; case 7: boxp->mat[0]=0.0F; boxp->mat[1]=m1[4]; boxp->mat[3]=m1[0]; boxp->mat[4]=0.0F; break; case 8: boxp->mat[0]=0.0F; boxp->mat[1]=m1[4]; boxp->mat[3]=0.0F-m1[0]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[0]; break; } return; } /* This function writes a PDF Contents stream to output. */ tsize_t t2p_write_pdf_page_content_stream(T2P* t2p, TIFF* output){ tsize_t written=0; ttile_t i=0; char buffer[512]; int buflen=0; T2P_BOX box; if(t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount>0){ for(i=0;i<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount; i++){ box=t2p->tiff_tiles[t2p->pdf_page].tiles_tiles[i].tile_box; buflen=sprintf(buffer, "q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%d_%ld Do Q\n", t2p->tiff_transferfunctioncount?"/GS1 gs ":"", box.mat[0], box.mat[1], box.mat[3], box.mat[4], box.mat[6], box.mat[7], t2p->pdf_page + 1, (long)(i + 1)); written += t2p_write_pdf_stream(buffer, buflen, output); } } else { box=t2p->pdf_imagebox; buflen=sprintf(buffer, "q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%d Do Q\n", t2p->tiff_transferfunctioncount?"/GS1 gs ":"", box.mat[0], box.mat[1], box.mat[3], box.mat[4], box.mat[6], box.mat[7], t2p->pdf_page+1); written += t2p_write_pdf_stream(buffer, buflen, output); } return(written); } /* This function writes a PDF Image XObject stream dictionary to output. */ tsize_t t2p_write_pdf_xobject_stream_dict(ttile_t tile, T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; written += t2p_write_pdf_stream_dict(0, t2p->pdf_xrefcount+1, output); written += t2pWriteFile(output, (tdata_t) "/Type /XObject \n/Subtype /Image \n/Name /Im", 42); buflen=sprintf(buffer, "%u", t2p->pdf_page+1); written += t2pWriteFile(output, (tdata_t) buffer, buflen); if(tile != 0){ written += t2pWriteFile(output, (tdata_t) "_", 1); buflen=sprintf(buffer, "%lu", (unsigned long)tile); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } written += t2pWriteFile(output, (tdata_t) "\n/Width ", 8); _TIFFmemset((tdata_t)buffer, 0x00, 16); if(tile==0){ buflen=sprintf(buffer, "%lu", (unsigned long)t2p->tiff_width); } else { if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)!=0){ buflen=sprintf( buffer, "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth); } else { buflen=sprintf( buffer, "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth); } } written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n/Height ", 9); _TIFFmemset((tdata_t)buffer, 0x00, 16); if(tile==0){ buflen=sprintf(buffer, "%lu", (unsigned long)t2p->tiff_length); } else { if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)!=0){ buflen=sprintf( buffer, "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); } else { buflen=sprintf( buffer, "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } } written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n/BitsPerComponent ", 19); _TIFFmemset((tdata_t)buffer, 0x00, 16); buflen=sprintf(buffer, "%u", t2p->tiff_bitspersample); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "\n/ColorSpace ", 13); written += t2p_write_pdf_xobject_cs(t2p, output); if (t2p->pdf_image_interpolate) written += t2pWriteFile(output, (tdata_t) "\n/Interpolate true", 18); if( (t2p->pdf_switchdecode != 0) #ifdef CCITT_SUPPORT && ! (t2p->pdf_colorspace == T2P_CS_BILEVEL && t2p->pdf_compression == T2P_COMPRESS_G4) #endif ){ written += t2p_write_pdf_xobject_decode(t2p, output); } written += t2p_write_pdf_xobject_stream_filter(tile, t2p, output); return(written); } /* * This function writes a PDF Image XObject Colorspace name to output. */ tsize_t t2p_write_pdf_xobject_cs(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[128]; int buflen=0; float X_W=1.0; float Y_W=1.0; float Z_W=1.0; if( (t2p->pdf_colorspace & T2P_CS_ICCBASED) != 0){ written += t2p_write_pdf_xobject_icccs(t2p, output); return(written); } if( (t2p->pdf_colorspace & T2P_CS_PALETTE) != 0){ written += t2pWriteFile(output, (tdata_t) "[ /Indexed ", 11); t2p->pdf_colorspace ^= T2P_CS_PALETTE; written += t2p_write_pdf_xobject_cs(t2p, output); t2p->pdf_colorspace |= T2P_CS_PALETTE; buflen=sprintf(buffer, "%u", (0x0001 << t2p->tiff_bitspersample)-1 ); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " ", 1); _TIFFmemset(buffer, 0x00, 16); buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_palettecs ); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ]\n", 7); return(written); } if(t2p->pdf_colorspace & T2P_CS_BILEVEL){ written += t2pWriteFile(output, (tdata_t) "/DeviceGray \n", 13); } if(t2p->pdf_colorspace & T2P_CS_GRAY){ if(t2p->pdf_colorspace & T2P_CS_CALGRAY){ written += t2p_write_pdf_xobject_calcs(t2p, output); } else { written += t2pWriteFile(output, (tdata_t) "/DeviceGray \n", 13); } } if(t2p->pdf_colorspace & T2P_CS_RGB){ if(t2p->pdf_colorspace & T2P_CS_CALRGB){ written += t2p_write_pdf_xobject_calcs(t2p, output); } else { written += t2pWriteFile(output, (tdata_t) "/DeviceRGB \n", 12); } } if(t2p->pdf_colorspace & T2P_CS_CMYK){ written += t2pWriteFile(output, (tdata_t) "/DeviceCMYK \n", 13); } if(t2p->pdf_colorspace & T2P_CS_LAB){ written += t2pWriteFile(output, (tdata_t) "[/Lab << \n", 10); written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12); X_W = t2p->tiff_whitechromaticities[0]; Y_W = t2p->tiff_whitechromaticities[1]; Z_W = 1.0F - (X_W + Y_W); X_W /= Y_W; Z_W /= Y_W; Y_W = 1.0F; buflen=sprintf(buffer, "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W); written += t2pWriteFile(output, (tdata_t) buffer, buflen); X_W = 0.3457F; /* 0.3127F; */ /* D50, commented D65 */ Y_W = 0.3585F; /* 0.3290F; */ Z_W = 1.0F - (X_W + Y_W); X_W /= Y_W; Z_W /= Y_W; Y_W = 1.0F; buflen=sprintf(buffer, "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Range ", 7); buflen=sprintf(buffer, "[%d %d %d %d] \n", t2p->pdf_labrange[0], t2p->pdf_labrange[1], t2p->pdf_labrange[2], t2p->pdf_labrange[3]); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) ">>] \n", 5); } return(written); } tsize_t t2p_write_pdf_transfer(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "<< /Type /ExtGState \n/TR ", 25); if(t2p->tiff_transferfunctioncount == 1){ buflen=sprintf(buffer, "%lu", (unsigned long)(t2p->pdf_xrefcount + 1)); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); } else { written += t2pWriteFile(output, (tdata_t) "[ ", 2); buflen=sprintf(buffer, "%lu", (unsigned long)(t2p->pdf_xrefcount + 1)); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); buflen=sprintf(buffer, "%lu", (unsigned long)(t2p->pdf_xrefcount + 2)); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); buflen=sprintf(buffer, "%lu", (unsigned long)(t2p->pdf_xrefcount + 3)); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R ", 5); written += t2pWriteFile(output, (tdata_t) "/Identity ] ", 12); } written += t2pWriteFile(output, (tdata_t) " >> \n", 5); return(written); } tsize_t t2p_write_pdf_transfer_dict(T2P* t2p, TIFF* output, uint16 i){ tsize_t written=0; char buffer[32]; int buflen=0; (void)i; /* XXX */ written += t2pWriteFile(output, (tdata_t) "/FunctionType 0 \n", 17); written += t2pWriteFile(output, (tdata_t) "/Domain [0.0 1.0] \n", 19); written += t2pWriteFile(output, (tdata_t) "/Range [0.0 1.0] \n", 18); buflen=sprintf(buffer, "/Size [%u] \n", (1<<t2p->tiff_bitspersample)); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/BitsPerSample 16 \n", 19); written += t2p_write_pdf_stream_dict(((tsize_t)1)<<(t2p->tiff_bitspersample+1), 0, output); return(written); } tsize_t t2p_write_pdf_transfer_stream(T2P* t2p, TIFF* output, uint16 i){ tsize_t written=0; written += t2p_write_pdf_stream( t2p->tiff_transferfunction[i], (((tsize_t)1)<<(t2p->tiff_bitspersample+1)), output); return(written); } /* This function writes a PDF Image XObject Colorspace array to output. */ tsize_t t2p_write_pdf_xobject_calcs(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[128]; int buflen=0; float X_W=0.0; float Y_W=0.0; float Z_W=0.0; float X_R=0.0; float Y_R=0.0; float Z_R=0.0; float X_G=0.0; float Y_G=0.0; float Z_G=0.0; float X_B=0.0; float Y_B=0.0; float Z_B=0.0; float x_w=0.0; float y_w=0.0; float z_w=0.0; float x_r=0.0; float y_r=0.0; float x_g=0.0; float y_g=0.0; float x_b=0.0; float y_b=0.0; float R=1.0; float G=1.0; float B=1.0; written += t2pWriteFile(output, (tdata_t) "[", 1); if(t2p->pdf_colorspace & T2P_CS_CALGRAY){ written += t2pWriteFile(output, (tdata_t) "/CalGray ", 9); X_W = t2p->tiff_whitechromaticities[0]; Y_W = t2p->tiff_whitechromaticities[1]; Z_W = 1.0F - (X_W + Y_W); X_W /= Y_W; Z_W /= Y_W; Y_W = 1.0F; } if(t2p->pdf_colorspace & T2P_CS_CALRGB){ written += t2pWriteFile(output, (tdata_t) "/CalRGB ", 8); x_w = t2p->tiff_whitechromaticities[0]; y_w = t2p->tiff_whitechromaticities[1]; x_r = t2p->tiff_primarychromaticities[0]; y_r = t2p->tiff_primarychromaticities[1]; x_g = t2p->tiff_primarychromaticities[2]; y_g = t2p->tiff_primarychromaticities[3]; x_b = t2p->tiff_primarychromaticities[4]; y_b = t2p->tiff_primarychromaticities[5]; z_w = y_w * ((x_g - x_b)*y_r - (x_r-x_b)*y_g + (x_r-x_g)*y_b); Y_R = (y_r/R) * ((x_g-x_b)*y_w - (x_w-x_b)*y_g + (x_w-x_g)*y_b) / z_w; X_R = Y_R * x_r / y_r; Z_R = Y_R * (((1-x_r)/y_r)-1); Y_G = ((0.0F-(y_g))/G) * ((x_r-x_b)*y_w - (x_w-x_b)*y_r + (x_w-x_r)*y_b) / z_w; X_G = Y_G * x_g / y_g; Z_G = Y_G * (((1-x_g)/y_g)-1); Y_B = (y_b/B) * ((x_r-x_g)*y_w - (x_w-x_g)*y_r + (x_w-x_r)*y_g) / z_w; X_B = Y_B * x_b / y_b; Z_B = Y_B * (((1-x_b)/y_b)-1); X_W = (X_R * R) + (X_G * G) + (X_B * B); Y_W = (Y_R * R) + (Y_G * G) + (Y_B * B); Z_W = (Z_R * R) + (Z_G * G) + (Z_B * B); X_W /= Y_W; Z_W /= Y_W; Y_W = 1.0; } written += t2pWriteFile(output, (tdata_t) "<< \n", 4); if(t2p->pdf_colorspace & T2P_CS_CALGRAY){ written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12); buflen=sprintf(buffer, "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Gamma 2.2 \n", 12); } if(t2p->pdf_colorspace & T2P_CS_CALRGB){ written += t2pWriteFile(output, (tdata_t) "/WhitePoint ", 12); buflen=sprintf(buffer, "[%.4f %.4f %.4f] \n", X_W, Y_W, Z_W); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Matrix ", 8); buflen=sprintf(buffer, "[%.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f] \n", X_R, Y_R, Z_R, X_G, Y_G, Z_G, X_B, Y_B, Z_B); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Gamma [2.2 2.2 2.2] \n", 22); } written += t2pWriteFile(output, (tdata_t) ">>] \n", 5); return(written); } /* This function writes a PDF Image XObject Colorspace array to output. */ tsize_t t2p_write_pdf_xobject_icccs(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "[/ICCBased ", 11); buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_icccs); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " 0 R] \n", 7); return(written); } tsize_t t2p_write_pdf_xobject_icccs_dict(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; written += t2pWriteFile(output, (tdata_t) "/N ", 3); buflen=sprintf(buffer, "%u \n", t2p->tiff_samplesperpixel); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) "/Alternate ", 11); t2p->pdf_colorspace ^= T2P_CS_ICCBASED; written += t2p_write_pdf_xobject_cs(t2p, output); t2p->pdf_colorspace |= T2P_CS_ICCBASED; written += t2p_write_pdf_stream_dict(t2p->tiff_iccprofilelength, 0, output); return(written); } tsize_t t2p_write_pdf_xobject_icccs_stream(T2P* t2p, TIFF* output){ tsize_t written=0; written += t2p_write_pdf_stream( (tdata_t) t2p->tiff_iccprofile, (tsize_t) t2p->tiff_iccprofilelength, output); return(written); } /* This function writes a palette stream for an indexed color space to output. */ tsize_t t2p_write_pdf_xobject_palettecs_stream(T2P* t2p, TIFF* output){ tsize_t written=0; written += t2p_write_pdf_stream( (tdata_t) t2p->pdf_palette, (tsize_t) t2p->pdf_palettesize, output); return(written); } /* This function writes a PDF Image XObject Decode array to output. */ tsize_t t2p_write_pdf_xobject_decode(T2P* t2p, TIFF* output){ tsize_t written=0; int i=0; written += t2pWriteFile(output, (tdata_t) "/Decode [ ", 10); for (i=0;i<t2p->tiff_samplesperpixel;i++){ written += t2pWriteFile(output, (tdata_t) "1 0 ", 4); } written += t2pWriteFile(output, (tdata_t) "]\n", 2); return(written); } /* This function writes a PDF Image XObject stream filter name and parameters to output. */ tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t tile, T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; if(t2p->pdf_compression==T2P_COMPRESS_NONE){ return(written); } written += t2pWriteFile(output, (tdata_t) "/Filter ", 8); switch(t2p->pdf_compression){ #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: written += t2pWriteFile(output, (tdata_t) "/CCITTFaxDecode ", 16); written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13); written += t2pWriteFile(output, (tdata_t) "<< /K -1 ", 9); if(tile==0){ written += t2pWriteFile(output, (tdata_t) "/Columns ", 9); buflen=sprintf(buffer, "%lu", (unsigned long)t2p->tiff_width); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /Rows ", 7); buflen=sprintf(buffer, "%lu", (unsigned long)t2p->tiff_length); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } else { if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){ written += t2pWriteFile(output, (tdata_t) "/Columns ", 9); buflen=sprintf( buffer, "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } else { written += t2pWriteFile(output, (tdata_t) "/Columns ", 9); buflen=sprintf( buffer, "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){ written += t2pWriteFile(output, (tdata_t) " /Rows ", 7); buflen=sprintf( buffer, "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } else { written += t2pWriteFile(output, (tdata_t) " /Rows ", 7); buflen=sprintf( buffer, "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); written += t2pWriteFile(output, (tdata_t) buffer, buflen); } } if(t2p->pdf_switchdecode == 0){ written += t2pWriteFile(output, (tdata_t) " /BlackIs1 true ", 16); } written += t2pWriteFile(output, (tdata_t) ">>\n", 3); break; #endif #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: written += t2pWriteFile(output, (tdata_t) "/DCTDecode ", 11); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR) { written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13); written += t2pWriteFile(output, (tdata_t) "<< /ColorTransform 0 >>\n", 24); } break; #endif #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: written += t2pWriteFile(output, (tdata_t) "/FlateDecode ", 13); if(t2p->pdf_compressionquality%100){ written += t2pWriteFile(output, (tdata_t) "/DecodeParms ", 13); written += t2pWriteFile(output, (tdata_t) "<< /Predictor ", 14); _TIFFmemset(buffer, 0x00, 16); buflen=sprintf(buffer, "%u", t2p->pdf_compressionquality%100); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /Columns ", 10); _TIFFmemset(buffer, 0x00, 16); buflen = sprintf(buffer, "%lu", (unsigned long)t2p->tiff_width); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /Colors ", 9); _TIFFmemset(buffer, 0x00, 16); buflen=sprintf(buffer, "%u", t2p->tiff_samplesperpixel); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " /BitsPerComponent ", 19); _TIFFmemset(buffer, 0x00, 16); buflen=sprintf(buffer, "%u", t2p->tiff_bitspersample); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) ">>\n", 3); } break; #endif default: break; } return(written); } /* This function writes a PDF xref table to output. */ tsize_t t2p_write_pdf_xreftable(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[21]; int buflen=0; uint32 i=0; written += t2pWriteFile(output, (tdata_t) "xref\n0 ", 7); buflen=sprintf(buffer, "%lu", (unsigned long)(t2p->pdf_xrefcount + 1)); written += t2pWriteFile(output, (tdata_t) buffer, buflen); written += t2pWriteFile(output, (tdata_t) " \n0000000000 65535 f \n", 22); for (i=0;i<t2p->pdf_xrefcount;i++){ sprintf(buffer, "%.10lu 00000 n \n", (unsigned long)t2p->pdf_xrefoffsets[i]); written += t2pWriteFile(output, (tdata_t) buffer, 20); } return(written); } /* * This function writes a PDF trailer to output. */ tsize_t t2p_write_pdf_trailer(T2P* t2p, TIFF* output) { tsize_t written = 0; char buffer[32]; int buflen = 0; size_t i = 0; for (i = 0; i < sizeof(t2p->pdf_fileid) - 8; i += 8) snprintf(t2p->pdf_fileid + i, 9, "%.8X", rand()); written += t2pWriteFile(output, (tdata_t) "trailer\n<<\n/Size ", 17); buflen = sprintf(buffer, "%lu", (unsigned long)(t2p->pdf_xrefcount+1)); written += t2pWriteFile(output, (tdata_t) buffer, buflen); _TIFFmemset(buffer, 0x00, 32); written += t2pWriteFile(output, (tdata_t) "\n/Root ", 7); buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_catalog); written += t2pWriteFile(output, (tdata_t) buffer, buflen); _TIFFmemset(buffer, 0x00, 32); written += t2pWriteFile(output, (tdata_t) " 0 R \n/Info ", 12); buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_info); written += t2pWriteFile(output, (tdata_t) buffer, buflen); _TIFFmemset(buffer, 0x00, 32); written += t2pWriteFile(output, (tdata_t) " 0 R \n/ID[<", 11); written += t2pWriteFile(output, (tdata_t) t2p->pdf_fileid, sizeof(t2p->pdf_fileid) - 1); written += t2pWriteFile(output, (tdata_t) "><", 2); written += t2pWriteFile(output, (tdata_t) t2p->pdf_fileid, sizeof(t2p->pdf_fileid) - 1); written += t2pWriteFile(output, (tdata_t) ">]\n>>\nstartxref\n", 16); buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_startxref); written += t2pWriteFile(output, (tdata_t) buffer, buflen); _TIFFmemset(buffer, 0x00, 32); written += t2pWriteFile(output, (tdata_t) "\n%%EOF\n", 7); return(written); } /* This function writes a PDF to a file given a pointer to a TIFF. The idea with using a TIFF* as output for a PDF file is that the file can be created with TIFFClientOpen for memory-mapped use within the TIFF library, and TIFFWriteEncodedStrip can be used to write compressed data to the output. The output is not actually a TIFF file, it is a PDF file. This function uses only t2pWriteFile and TIFFWriteEncodedStrip to write to the output TIFF file. When libtiff would otherwise be writing data to the output file, the write procedure of the TIFF structure is replaced with an empty implementation. The first argument to the function is an initialized and validated T2P context struct pointer. The second argument to the function is the TIFF* that is the input that has been opened for reading and no other functions have been called upon it. The third argument to the function is the TIFF* that is the output that has been opened for writing. It has to be opened so that it hasn't written any data to the output. If the output is seekable then it's OK to seek to the beginning of the file. The function only writes to the output PDF and does not seek. See the example usage in the main() function. TIFF* output = TIFFOpen("output.pdf", "w"); assert(output != NULL); if(output->tif_seekproc != NULL){ t2pSeekFile(output, (toff_t) 0, SEEK_SET); } This function returns the file size of the output PDF file. On error it returns zero and the t2p->t2p_error variable is set to T2P_ERR_ERROR. After this function completes, call t2p_free on t2p, TIFFClose on input, and TIFFClose on output. */ tsize_t t2p_write_pdf(T2P* t2p, TIFF* input, TIFF* output){ tsize_t written=0; ttile_t i2=0; tsize_t streamlen=0; uint16 i=0; t2p_read_tiff_init(t2p, input); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} t2p->pdf_xrefoffsets= (uint32*) _TIFFmalloc(t2p->pdf_xrefcount * sizeof(uint32) ); if(t2p->pdf_xrefoffsets==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_write_pdf", (unsigned int) (t2p->pdf_xrefcount * sizeof(uint32)) ); return(written); } t2p->pdf_xrefcount=0; t2p->pdf_catalog=1; t2p->pdf_info=2; t2p->pdf_pages=3; written += t2p_write_pdf_header(t2p, output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_catalog=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_catalog(t2p, output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_info=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_info(t2p, input, output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_pages=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_pages(t2p, output); written += t2p_write_pdf_obj_end(output); for(t2p->pdf_page=0;t2p->pdf_page<t2p->tiff_pagecount;t2p->pdf_page++){ t2p_read_tiff_data(t2p, input); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_page(t2p->pdf_xrefcount, t2p, output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_stream_dict(0, t2p->pdf_xrefcount+1, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; written += t2p_write_pdf_page_content_stream(t2p, output); streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_length(streamlen, output); written += t2p_write_pdf_obj_end(output); if(t2p->tiff_transferfunctioncount != 0){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_transfer(t2p, output); written += t2p_write_pdf_obj_end(output); for(i=0; i < t2p->tiff_transferfunctioncount; i++){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_transfer_dict(t2p, output, i); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; written += t2p_write_pdf_transfer_stream(t2p, output, i); streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); } } if( (t2p->pdf_colorspace & T2P_CS_PALETTE) != 0){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_palettecs=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_stream_dict(t2p->pdf_palettesize, 0, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; written += t2p_write_pdf_xobject_palettecs_stream(t2p, output); streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); } if( (t2p->pdf_colorspace & T2P_CS_ICCBASED) != 0){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_icccs=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_xobject_icccs_dict(t2p, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; written += t2p_write_pdf_xobject_icccs_stream(t2p, output); streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); } if(t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount !=0){ for(i2=0;i2<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount;i2++){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_xobject_stream_dict( i2+1, t2p, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; t2p_read_tiff_size_tile(t2p, input, i2); written += t2p_readwrite_pdf_image_tile(t2p, input, output, i2); t2p_write_advance_directory(t2p, output); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_length(streamlen, output); written += t2p_write_pdf_obj_end(output); } } else { t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_xobject_stream_dict( 0, t2p, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; t2p_read_tiff_size(t2p, input); written += t2p_readwrite_pdf_image(t2p, input, output); t2p_write_advance_directory(t2p, output); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_length(streamlen, output); written += t2p_write_pdf_obj_end(output); } } t2p->pdf_startxref = written; written += t2p_write_pdf_xreftable(t2p, output); written += t2p_write_pdf_trailer(t2p, output); t2p_disable(output); return(written); } /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/libtiff_2010-11-27-eb326f9-eec7ec0.c
manybugs_data_93
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2012 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Marcus Boerger <[email protected]> | | Sterling Hughes <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "zend.h" #include "zend_API.h" #include "zend_builtin_functions.h" #include "zend_interfaces.h" #include "zend_exceptions.h" #include "zend_vm.h" #include "zend_dtrace.h" zend_class_entry *default_exception_ce; zend_class_entry *error_exception_ce; static zend_object_handlers default_exception_handlers; ZEND_API void (*zend_throw_exception_hook)(zval *ex TSRMLS_DC); void zend_exception_set_previous(zval *exception, zval *add_previous TSRMLS_DC) { zval *previous; if (exception == add_previous || !add_previous || !exception) { return; } if (Z_TYPE_P(add_previous) != IS_OBJECT && !instanceof_function(Z_OBJCE_P(add_previous), default_exception_ce TSRMLS_CC)) { zend_error(E_ERROR, "Cannot set non exception as previous exception"); return; } while (exception && exception != add_previous && Z_OBJ_HANDLE_P(exception) != Z_OBJ_HANDLE_P(add_previous)) { previous = zend_read_property(default_exception_ce, exception, "previous", sizeof("previous")-1, 1 TSRMLS_CC); if (Z_TYPE_P(previous) == IS_NULL) { zend_update_property(default_exception_ce, exception, "previous", sizeof("previous")-1, add_previous TSRMLS_CC); Z_DELREF_P(add_previous); return; } exception = previous; } } void zend_exception_save(TSRMLS_D) /* {{{ */ { if (EG(prev_exception)) { zend_exception_set_previous(EG(exception), EG(prev_exception) TSRMLS_CC); } if (EG(exception)) { EG(prev_exception) = EG(exception); } EG(exception) = NULL; } /* }}} */ void zend_exception_restore(TSRMLS_D) /* {{{ */ { if (EG(prev_exception)) { if (EG(exception)) { zend_exception_set_previous(EG(exception), EG(prev_exception) TSRMLS_CC); } else { EG(exception) = EG(prev_exception); } EG(prev_exception) = NULL; } } /* }}} */ void zend_throw_exception_internal(zval *exception TSRMLS_DC) /* {{{ */ { #ifdef HAVE_DTRACE if (DTRACE_EXCEPTION_THROWN_ENABLED()) { char *classname; int name_len; if (exception != NULL) { zend_get_object_classname(exception, &classname, &name_len TSRMLS_CC); DTRACE_EXCEPTION_THROWN(classname); } else { DTRACE_EXCEPTION_THROWN(NULL); } } #endif /* HAVE_DTRACE */ if (exception != NULL) { zval *previous = EG(exception); zend_exception_set_previous(exception, EG(exception) TSRMLS_CC); EG(exception) = exception; if (previous) { return; } } if (!EG(current_execute_data)) { if(EG(exception)) { zend_exception_error(EG(exception), E_ERROR TSRMLS_CC); } zend_error(E_ERROR, "Exception thrown without a stack frame"); } if (zend_throw_exception_hook) { zend_throw_exception_hook(exception TSRMLS_CC); } if (EG(current_execute_data)->opline == NULL || (EG(current_execute_data)->opline+1)->opcode == ZEND_HANDLE_EXCEPTION) { /* no need to rethrow the exception */ return; } EG(opline_before_exception) = EG(current_execute_data)->opline; EG(current_execute_data)->opline = EG(exception_op); } /* }}} */ ZEND_API void zend_clear_exception(TSRMLS_D) /* {{{ */ { if (EG(prev_exception)) { zval_ptr_dtor(&EG(prev_exception)); EG(prev_exception) = NULL; } if (!EG(exception)) { return; } zval_ptr_dtor(&EG(exception)); EG(exception) = NULL; EG(current_execute_data)->opline = EG(opline_before_exception); #if ZEND_DEBUG EG(opline_before_exception) = NULL; #endif } /* }}} */ static zend_object_value zend_default_exception_new_ex(zend_class_entry *class_type, int skip_top_traces TSRMLS_DC) /* {{{ */ { zval obj; zend_object *object; zval *trace; Z_OBJVAL(obj) = zend_objects_new(&object, class_type TSRMLS_CC); Z_OBJ_HT(obj) = &default_exception_handlers; object_properties_init(object, class_type); ALLOC_ZVAL(trace); Z_UNSET_ISREF_P(trace); Z_SET_REFCOUNT_P(trace, 0); zend_fetch_debug_backtrace(trace, skip_top_traces, 0, 0 TSRMLS_CC); zend_update_property_string(default_exception_ce, &obj, "file", sizeof("file")-1, zend_get_executed_filename(TSRMLS_C) TSRMLS_CC); zend_update_property_long(default_exception_ce, &obj, "line", sizeof("line")-1, zend_get_executed_lineno(TSRMLS_C) TSRMLS_CC); zend_update_property(default_exception_ce, &obj, "trace", sizeof("trace")-1, trace TSRMLS_CC); return Z_OBJVAL(obj); } /* }}} */ static zend_object_value zend_default_exception_new(zend_class_entry *class_type TSRMLS_DC) /* {{{ */ { return zend_default_exception_new_ex(class_type, 0 TSRMLS_CC); } /* }}} */ static zend_object_value zend_error_exception_new(zend_class_entry *class_type TSRMLS_DC) /* {{{ */ { return zend_default_exception_new_ex(class_type, 2 TSRMLS_CC); } /* }}} */ /* {{{ proto Exception Exception::__clone() Clone the exception object */ ZEND_METHOD(exception, __clone) { /* Should never be executable */ zend_throw_exception(NULL, "Cannot clone object using __clone()", 0 TSRMLS_CC); } /* }}} */ /* {{{ proto Exception::__construct(string message, int code [, Exception previous]) Exception constructor */ ZEND_METHOD(exception, __construct) { char *message = NULL; long code = 0; zval *object, *previous = NULL; int argc = ZEND_NUM_ARGS(), message_len; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "|slO!", &message, &message_len, &code, &previous, default_exception_ce) == FAILURE) { zend_error(E_ERROR, "Wrong parameters for Exception([string $exception [, long $code [, Exception $previous = NULL]]])"); } object = getThis(); if (message) { zend_update_property_string(default_exception_ce, object, "message", sizeof("message")-1, message TSRMLS_CC); } if (code) { zend_update_property_long(default_exception_ce, object, "code", sizeof("code")-1, code TSRMLS_CC); } if (previous) { zend_update_property(default_exception_ce, object, "previous", sizeof("previous")-1, previous TSRMLS_CC); } } /* }}} */ /* {{{ proto ErrorException::__construct(string message, int code, int severity [, string filename [, int lineno [, Exception previous]]]) ErrorException constructor */ ZEND_METHOD(error_exception, __construct) { char *message = NULL, *filename = NULL; long code = 0, severity = E_ERROR, lineno; zval *object, *previous = NULL; int argc = ZEND_NUM_ARGS(), message_len, filename_len; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "|sllslO!", &message, &message_len, &code, &severity, &filename, &filename_len, &lineno, &previous, default_exception_ce) == FAILURE) { zend_error(E_ERROR, "Wrong parameters for ErrorException([string $exception [, long $code, [ long $severity, [ string $filename, [ long $lineno [, Exception $previous = NULL]]]]]])"); } object = getThis(); if (message) { zend_update_property_string(default_exception_ce, object, "message", sizeof("message")-1, message TSRMLS_CC); } if (code) { zend_update_property_long(default_exception_ce, object, "code", sizeof("code")-1, code TSRMLS_CC); } if (previous) { zend_update_property(default_exception_ce, object, "previous", sizeof("previous")-1, previous TSRMLS_CC); } zend_update_property_long(default_exception_ce, object, "severity", sizeof("severity")-1, severity TSRMLS_CC); if (argc >= 4) { zend_update_property_string(default_exception_ce, object, "file", sizeof("file")-1, filename TSRMLS_CC); if (argc < 5) { lineno = 0; /* invalidate lineno */ } zend_update_property_long(default_exception_ce, object, "line", sizeof("line")-1, lineno TSRMLS_CC); } } /* }}} */ #define DEFAULT_0_PARAMS \ if (zend_parse_parameters_none() == FAILURE) { \ return; \ } static void _default_exception_get_entry(zval *object, char *name, int name_len, zval *return_value TSRMLS_DC) /* {{{ */ { zval *value; value = zend_read_property(default_exception_ce, object, name, name_len, 0 TSRMLS_CC); *return_value = *value; zval_copy_ctor(return_value); INIT_PZVAL(return_value); } /* }}} */ /* {{{ proto string Exception::getFile() Get the file in which the exception occurred */ ZEND_METHOD(exception, getFile) { DEFAULT_0_PARAMS; _default_exception_get_entry(getThis(), "file", sizeof("file")-1, return_value TSRMLS_CC); } /* }}} */ /* {{{ proto int Exception::getLine() Get the line in which the exception occurred */ ZEND_METHOD(exception, getLine) { DEFAULT_0_PARAMS; _default_exception_get_entry(getThis(), "line", sizeof("line")-1, return_value TSRMLS_CC); } /* }}} */ /* {{{ proto string Exception::getMessage() Get the exception message */ ZEND_METHOD(exception, getMessage) { DEFAULT_0_PARAMS; _default_exception_get_entry(getThis(), "message", sizeof("message")-1, return_value TSRMLS_CC); } /* }}} */ /* {{{ proto int Exception::getCode() Get the exception code */ ZEND_METHOD(exception, getCode) { DEFAULT_0_PARAMS; _default_exception_get_entry(getThis(), "code", sizeof("code")-1, return_value TSRMLS_CC); } /* }}} */ /* {{{ proto array Exception::getTrace() Get the stack trace for the location in which the exception occurred */ ZEND_METHOD(exception, getTrace) { DEFAULT_0_PARAMS; _default_exception_get_entry(getThis(), "trace", sizeof("trace")-1, return_value TSRMLS_CC); } /* }}} */ /* {{{ proto int ErrorException::getSeverity() Get the exception severity */ ZEND_METHOD(error_exception, getSeverity) { DEFAULT_0_PARAMS; _default_exception_get_entry(getThis(), "severity", sizeof("severity")-1, return_value TSRMLS_CC); } /* }}} */ /* {{{ gettraceasstring() macros */ #define TRACE_APPEND_CHR(chr) \ *str = (char*)erealloc(*str, *len + 1 + 1); \ (*str)[(*len)++] = chr #define TRACE_APPEND_STRL(val, vallen) \ { \ int l = vallen; \ *str = (char*)erealloc(*str, *len + l + 1); \ memcpy((*str) + *len, val, l); \ *len += l; \ } #define TRACE_APPEND_STR(val) \ TRACE_APPEND_STRL(val, sizeof(val)-1) #define TRACE_APPEND_KEY(key) \ if (zend_hash_find(ht, key, sizeof(key), (void**)&tmp) == SUCCESS) { \ TRACE_APPEND_STRL(Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp)); \ } /* }}} */ static int _build_trace_args(zval **arg TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { char **str; int *len; str = va_arg(args, char**); len = va_arg(args, int*); /* the trivial way would be to do: * conver_to_string_ex(arg); * append it and kill the now tmp arg. * but that could cause some E_NOTICE and also damn long lines. */ switch (Z_TYPE_PP(arg)) { case IS_NULL: TRACE_APPEND_STR("NULL, "); break; case IS_STRING: { int l_added; TRACE_APPEND_CHR('\''); if (Z_STRLEN_PP(arg) > 15) { TRACE_APPEND_STRL(Z_STRVAL_PP(arg), 15); TRACE_APPEND_STR("...', "); l_added = 15 + 6 + 1; /* +1 because of while (--l_added) */ } else { l_added = Z_STRLEN_PP(arg); TRACE_APPEND_STRL(Z_STRVAL_PP(arg), l_added); TRACE_APPEND_STR("', "); l_added += 3 + 1; } while (--l_added) { if ((*str)[*len - l_added] < 32) { (*str)[*len - l_added] = '?'; } } break; } case IS_BOOL: if (Z_LVAL_PP(arg)) { TRACE_APPEND_STR("true, "); } else { TRACE_APPEND_STR("false, "); } break; case IS_RESOURCE: TRACE_APPEND_STR("Resource id #"); /* break; */ case IS_LONG: { long lval = Z_LVAL_PP(arg); char s_tmp[MAX_LENGTH_OF_LONG + 1]; int l_tmp = zend_sprintf(s_tmp, "%ld", lval); /* SAFE */ TRACE_APPEND_STRL(s_tmp, l_tmp); TRACE_APPEND_STR(", "); break; } case IS_DOUBLE: { double dval = Z_DVAL_PP(arg); char *s_tmp; int l_tmp; s_tmp = emalloc(MAX_LENGTH_OF_DOUBLE + EG(precision) + 1); l_tmp = zend_sprintf(s_tmp, "%.*G", (int) EG(precision), dval); /* SAFE */ TRACE_APPEND_STRL(s_tmp, l_tmp); /* %G already handles removing trailing zeros from the fractional part, yay */ efree(s_tmp); TRACE_APPEND_STR(", "); break; } case IS_ARRAY: TRACE_APPEND_STR("Array, "); break; case IS_OBJECT: { const char *class_name; zend_uint class_name_len; int dup; TRACE_APPEND_STR("Object("); dup = zend_get_object_classname(*arg, &class_name, &class_name_len TSRMLS_CC); TRACE_APPEND_STRL(class_name, class_name_len); if(!dup) { efree((char*)class_name); } TRACE_APPEND_STR("), "); break; } default: break; } return ZEND_HASH_APPLY_KEEP; } /* }}} */ static int _build_trace_string(zval **frame TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { char *s_tmp, **str; int *len, *num; long line; HashTable *ht = Z_ARRVAL_PP(frame); zval **file, **tmp; str = va_arg(args, char**); len = va_arg(args, int*); num = va_arg(args, int*); s_tmp = emalloc(1 + MAX_LENGTH_OF_LONG + 1 + 1); sprintf(s_tmp, "#%d ", (*num)++); TRACE_APPEND_STRL(s_tmp, strlen(s_tmp)); efree(s_tmp); if (zend_hash_find(ht, "file", sizeof("file"), (void**)&file) == SUCCESS) { if (zend_hash_find(ht, "line", sizeof("line"), (void**)&tmp) == SUCCESS) { line = Z_LVAL_PP(tmp); } else { line = 0; } s_tmp = emalloc(Z_STRLEN_PP(file) + MAX_LENGTH_OF_LONG + 4 + 1); sprintf(s_tmp, "%s(%ld): ", Z_STRVAL_PP(file), line); TRACE_APPEND_STRL(s_tmp, strlen(s_tmp)); efree(s_tmp); } else { TRACE_APPEND_STR("[internal function]: "); } TRACE_APPEND_KEY("class"); TRACE_APPEND_KEY("type"); TRACE_APPEND_KEY("function"); TRACE_APPEND_CHR('('); if (zend_hash_find(ht, "args", sizeof("args"), (void**)&tmp) == SUCCESS) { int last_len = *len; zend_hash_apply_with_arguments(Z_ARRVAL_PP(tmp) TSRMLS_CC, (apply_func_args_t)_build_trace_args, 2, str, len); if (last_len != *len) { *len -= 2; /* remove last ', ' */ } } TRACE_APPEND_STR(")\n"); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* {{{ proto string Exception::getTraceAsString() Obtain the backtrace for the exception as a string (instead of an array) */ ZEND_METHOD(exception, getTraceAsString) { zval *trace; char *res, **str, *s_tmp; int res_len = 0, *len = &res_len, num = 0; DEFAULT_0_PARAMS; res = estrdup(""); str = &res; trace = zend_read_property(default_exception_ce, getThis(), "trace", sizeof("trace")-1, 1 TSRMLS_CC); zend_hash_apply_with_arguments(Z_ARRVAL_P(trace) TSRMLS_CC, (apply_func_args_t)_build_trace_string, 3, str, len, &num); s_tmp = emalloc(1 + MAX_LENGTH_OF_LONG + 7 + 1); sprintf(s_tmp, "#%d {main}", num); TRACE_APPEND_STRL(s_tmp, strlen(s_tmp)); efree(s_tmp); res[res_len] = '\0'; RETURN_STRINGL(res, res_len, 0); } /* }}} */ /* {{{ proto string Exception::getPrevious() Return previous Exception or NULL. */ ZEND_METHOD(exception, getPrevious) { zval *previous; DEFAULT_0_PARAMS; previous = zend_read_property(default_exception_ce, getThis(), "previous", sizeof("previous")-1, 1 TSRMLS_CC); RETURN_ZVAL(previous, 1, 0); } int zend_spprintf(char **message, int max_len, char *format, ...) /* {{{ */ { va_list arg; int len; va_start(arg, format); len = zend_vspprintf(message, max_len, format, arg); va_end(arg); return len; } /* }}} */ /* {{{ proto string Exception::__toString() Obtain the string representation of the Exception object */ ZEND_METHOD(exception, __toString) { zval message, file, line, *trace, *exception; char *str, *prev_str; int len = 0; zend_fcall_info fci; zval fname; DEFAULT_0_PARAMS; str = estrndup("", 0); exception = getThis(); ZVAL_STRINGL(&fname, "gettraceasstring", sizeof("gettraceasstring")-1, 1); while (exception && Z_TYPE_P(exception) == IS_OBJECT) { prev_str = str; _default_exception_get_entry(exception, "message", sizeof("message")-1, &message TSRMLS_CC); _default_exception_get_entry(exception, "file", sizeof("file")-1, &file TSRMLS_CC); _default_exception_get_entry(exception, "line", sizeof("line")-1, &line TSRMLS_CC); convert_to_string(&message); convert_to_string(&file); convert_to_long(&line); fci.size = sizeof(fci); fci.function_table = &Z_OBJCE_P(exception)->function_table; fci.function_name = &fname; fci.symbol_table = NULL; fci.object_ptr = exception; fci.retval_ptr_ptr = &trace; fci.param_count = 0; fci.params = NULL; fci.no_separation = 1; zend_call_function(&fci, NULL TSRMLS_CC); if (Z_TYPE_P(trace) != IS_STRING) { zval_ptr_dtor(&trace); trace = NULL; } if (Z_STRLEN(message) > 0) { len = zend_spprintf(&str, 0, "exception '%s' with message '%s' in %s:%ld\nStack trace:\n%s%s%s", Z_OBJCE_P(exception)->name, Z_STRVAL(message), Z_STRVAL(file), Z_LVAL(line), (trace && Z_STRLEN_P(trace)) ? Z_STRVAL_P(trace) : "#0 {main}\n", len ? "\n\nNext " : "", prev_str); } else { len = zend_spprintf(&str, 0, "exception '%s' in %s:%ld\nStack trace:\n%s%s%s", Z_OBJCE_P(exception)->name, Z_STRVAL(file), Z_LVAL(line), (trace && Z_STRLEN_P(trace)) ? Z_STRVAL_P(trace) : "#0 {main}\n", len ? "\n\nNext " : "", prev_str); } efree(prev_str); zval_dtor(&message); zval_dtor(&file); zval_dtor(&line); exception = zend_read_property(default_exception_ce, exception, "previous", sizeof("previous")-1, 0 TSRMLS_CC); if (trace) { zval_ptr_dtor(&trace); } } zval_dtor(&fname); /* We store the result in the private property string so we can access * the result in uncaught exception handlers without memleaks. */ zend_update_property_string(default_exception_ce, getThis(), "string", sizeof("string")-1, str TSRMLS_CC); RETURN_STRINGL(str, len, 0); } /* }}} */ /* {{{ internal structs */ /* All functions that may be used in uncaught exception handlers must be final * and must not throw exceptions. Otherwise we would need a facility to handle * such exceptions in that handler. * Also all getXY() methods are final because thy serve as read only access to * their corresponding properties, no more, no less. If after all you need to * override somthing then it is method __toString(). * And never try to change the state of exceptions and never implement anything * that gives the user anything to accomplish this. */ ZEND_BEGIN_ARG_INFO_EX(arginfo_exception___construct, 0, 0, 0) ZEND_ARG_INFO(0, message) ZEND_ARG_INFO(0, code) ZEND_ARG_INFO(0, previous) ZEND_END_ARG_INFO() const static zend_function_entry default_exception_functions[] = { ZEND_ME(exception, __clone, NULL, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL) ZEND_ME(exception, __construct, arginfo_exception___construct, ZEND_ACC_PUBLIC) ZEND_ME(exception, getMessage, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL) ZEND_ME(exception, getCode, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL) ZEND_ME(exception, getFile, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL) ZEND_ME(exception, getLine, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL) ZEND_ME(exception, getTrace, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL) ZEND_ME(exception, getPrevious, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL) ZEND_ME(exception, getTraceAsString, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL) ZEND_ME(exception, __toString, NULL, 0) {NULL, NULL, NULL} }; ZEND_BEGIN_ARG_INFO_EX(arginfo_error_exception___construct, 0, 0, 0) ZEND_ARG_INFO(0, message) ZEND_ARG_INFO(0, code) ZEND_ARG_INFO(0, severity) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, lineno) ZEND_ARG_INFO(0, previous) ZEND_END_ARG_INFO() static const zend_function_entry error_exception_functions[] = { ZEND_ME(error_exception, __construct, arginfo_error_exception___construct, ZEND_ACC_PUBLIC) ZEND_ME(error_exception, getSeverity, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL) {NULL, NULL, NULL} }; /* }}} */ void zend_register_default_exception(TSRMLS_D) /* {{{ */ { zend_class_entry ce; INIT_CLASS_ENTRY(ce, "Exception", default_exception_functions); default_exception_ce = zend_register_internal_class(&ce TSRMLS_CC); default_exception_ce->create_object = zend_default_exception_new; memcpy(&default_exception_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); default_exception_handlers.clone_obj = NULL; zend_declare_property_string(default_exception_ce, "message", sizeof("message")-1, "", ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_string(default_exception_ce, "string", sizeof("string")-1, "", ZEND_ACC_PRIVATE TSRMLS_CC); zend_declare_property_long(default_exception_ce, "code", sizeof("code")-1, 0, ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(default_exception_ce, "file", sizeof("file")-1, ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(default_exception_ce, "line", sizeof("line")-1, ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(default_exception_ce, "trace", sizeof("trace")-1, ZEND_ACC_PRIVATE TSRMLS_CC); zend_declare_property_null(default_exception_ce, "previous", sizeof("previous")-1, ZEND_ACC_PRIVATE TSRMLS_CC); INIT_CLASS_ENTRY(ce, "ErrorException", error_exception_functions); error_exception_ce = zend_register_internal_class_ex(&ce, default_exception_ce, NULL TSRMLS_CC); error_exception_ce->create_object = zend_error_exception_new; zend_declare_property_long(error_exception_ce, "severity", sizeof("severity")-1, E_ERROR, ZEND_ACC_PROTECTED TSRMLS_CC); } /* }}} */ ZEND_API zend_class_entry *zend_exception_get_default(TSRMLS_D) /* {{{ */ { return default_exception_ce; } /* }}} */ ZEND_API zend_class_entry *zend_get_error_exception(TSRMLS_D) /* {{{ */ { return error_exception_ce; } /* }}} */ ZEND_API zval * zend_throw_exception(zend_class_entry *exception_ce, char *message, long code TSRMLS_DC) /* {{{ */ { zval *ex; MAKE_STD_ZVAL(ex); if (exception_ce) { if (!instanceof_function(exception_ce, default_exception_ce TSRMLS_CC)) { zend_error(E_NOTICE, "Exceptions must be derived from the Exception base class"); exception_ce = default_exception_ce; } } else { exception_ce = default_exception_ce; } object_init_ex(ex, exception_ce); if (message) { zend_update_property_string(default_exception_ce, ex, "message", sizeof("message")-1, message TSRMLS_CC); } if (code) { zend_update_property_long(default_exception_ce, ex, "code", sizeof("code")-1, code TSRMLS_CC); } zend_throw_exception_internal(ex TSRMLS_CC); return ex; } /* }}} */ ZEND_API zval * zend_throw_exception_ex(zend_class_entry *exception_ce, long code TSRMLS_DC, char *format, ...) /* {{{ */ { va_list arg; char *message; zval *zexception; va_start(arg, format); zend_vspprintf(&message, 0, format, arg); va_end(arg); zexception = zend_throw_exception(exception_ce, message, code TSRMLS_CC); efree(message); return zexception; } /* }}} */ ZEND_API zval * zend_throw_error_exception(zend_class_entry *exception_ce, char *message, long code, int severity TSRMLS_DC) /* {{{ */ { zval *ex = zend_throw_exception(exception_ce, message, code TSRMLS_CC); zend_update_property_long(default_exception_ce, ex, "severity", sizeof("severity")-1, severity TSRMLS_CC); return ex; } /* }}} */ static void zend_error_va(int type, const char *file, uint lineno, const char *format, ...) /* {{{ */ { va_list args; va_start(args, format); zend_error_cb(type, file, lineno, format, args); va_end(args); } /* }}} */ /* This function doesn't return if it uses E_ERROR */ ZEND_API void zend_exception_error(zval *exception, int severity TSRMLS_DC) /* {{{ */ { zend_class_entry *ce_exception = Z_OBJCE_P(exception); if (instanceof_function(ce_exception, default_exception_ce TSRMLS_CC)) { zval *str, *file, *line; EG(exception) = NULL; zend_call_method_with_0_params(&exception, ce_exception, NULL, "__tostring", &str); if (!EG(exception)) { if (Z_TYPE_P(str) != IS_STRING) { zend_error(E_WARNING, "%s::__toString() must return a string", ce_exception->name); } else { zend_update_property_string(default_exception_ce, exception, "string", sizeof("string")-1, EG(exception) ? ce_exception->name : Z_STRVAL_P(str) TSRMLS_CC); } } zval_ptr_dtor(&str); if (EG(exception)) { /* do the best we can to inform about the inner exception */ if (instanceof_function(ce_exception, default_exception_ce TSRMLS_CC)) { file = zend_read_property(default_exception_ce, EG(exception), "file", sizeof("file")-1, 1 TSRMLS_CC); line = zend_read_property(default_exception_ce, EG(exception), "line", sizeof("line")-1, 1 TSRMLS_CC); } else { file = NULL; line = NULL; } zend_error_va(E_WARNING, file ? Z_STRVAL_P(file) : NULL, line ? Z_LVAL_P(line) : 0, "Uncaught %s in exception handling during call to %s::__tostring()", Z_OBJCE_P(EG(exception))->name, ce_exception->name); } str = zend_read_property(default_exception_ce, exception, "string", sizeof("string")-1, 1 TSRMLS_CC); file = zend_read_property(default_exception_ce, exception, "file", sizeof("file")-1, 1 TSRMLS_CC); line = zend_read_property(default_exception_ce, exception, "line", sizeof("line")-1, 1 TSRMLS_CC); zend_error_va(severity, Z_STRVAL_P(file), Z_LVAL_P(line), "Uncaught %s\n thrown", Z_STRVAL_P(str)); } else { zend_error(severity, "Uncaught exception '%s'", ce_exception->name); } } /* }}} */ ZEND_API void zend_throw_exception_object(zval *exception TSRMLS_DC) /* {{{ */ { zend_class_entry *exception_ce; if (exception == NULL || Z_TYPE_P(exception) != IS_OBJECT) { zend_error(E_ERROR, "Need to supply an object when throwing an exception"); } exception_ce = Z_OBJCE_P(exception); if (!exception_ce || !instanceof_function(exception_ce, default_exception_ce TSRMLS_CC)) { zend_error(E_ERROR, "Exceptions must be valid objects derived from the Exception base class"); } zend_throw_exception_internal(exception TSRMLS_CC); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */ /* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2012 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend 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.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Marcus Boerger <[email protected]> | | Sterling Hughes <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "zend.h" #include "zend_API.h" #include "zend_builtin_functions.h" #include "zend_interfaces.h" #include "zend_exceptions.h" #include "zend_vm.h" #include "zend_dtrace.h" zend_class_entry *default_exception_ce; zend_class_entry *error_exception_ce; static zend_object_handlers default_exception_handlers; ZEND_API void (*zend_throw_exception_hook)(zval *ex TSRMLS_DC); void zend_exception_set_previous(zval *exception, zval *add_previous TSRMLS_DC) { zval *previous; if (exception == add_previous || !add_previous || !exception) { return; } if (Z_TYPE_P(add_previous) != IS_OBJECT && !instanceof_function(Z_OBJCE_P(add_previous), default_exception_ce TSRMLS_CC)) { zend_error(E_ERROR, "Cannot set non exception as previous exception"); return; } while (exception && exception != add_previous && Z_OBJ_HANDLE_P(exception) != Z_OBJ_HANDLE_P(add_previous)) { previous = zend_read_property(default_exception_ce, exception, "previous", sizeof("previous")-1, 1 TSRMLS_CC); if (Z_TYPE_P(previous) == IS_NULL) { zend_update_property(default_exception_ce, exception, "previous", sizeof("previous")-1, add_previous TSRMLS_CC); Z_DELREF_P(add_previous); return; } exception = previous; } } void zend_exception_save(TSRMLS_D) /* {{{ */ { if (EG(prev_exception)) { zend_exception_set_previous(EG(exception), EG(prev_exception) TSRMLS_CC); } if (EG(exception)) { EG(prev_exception) = EG(exception); } EG(exception) = NULL; } /* }}} */ void zend_exception_restore(TSRMLS_D) /* {{{ */ { if (EG(prev_exception)) { if (EG(exception)) { zend_exception_set_previous(EG(exception), EG(prev_exception) TSRMLS_CC); } else { EG(exception) = EG(prev_exception); } EG(prev_exception) = NULL; } } /* }}} */ void zend_throw_exception_internal(zval *exception TSRMLS_DC) /* {{{ */ { #ifdef HAVE_DTRACE if (DTRACE_EXCEPTION_THROWN_ENABLED()) { char *classname; int name_len; if (exception != NULL) { zend_get_object_classname(exception, &classname, &name_len TSRMLS_CC); DTRACE_EXCEPTION_THROWN(classname); } else { DTRACE_EXCEPTION_THROWN(NULL); } } #endif /* HAVE_DTRACE */ if (exception != NULL) { zval *previous = EG(exception); zend_exception_set_previous(exception, EG(exception) TSRMLS_CC); EG(exception) = exception; if (previous) { return; } } if (!EG(current_execute_data)) { if(EG(exception)) { zend_exception_error(EG(exception), E_ERROR TSRMLS_CC); } zend_error(E_ERROR, "Exception thrown without a stack frame"); } if (zend_throw_exception_hook) { zend_throw_exception_hook(exception TSRMLS_CC); } if (EG(current_execute_data)->opline == NULL || (EG(current_execute_data)->opline+1)->opcode == ZEND_HANDLE_EXCEPTION) { /* no need to rethrow the exception */ return; } EG(opline_before_exception) = EG(current_execute_data)->opline; EG(current_execute_data)->opline = EG(exception_op); } /* }}} */ ZEND_API void zend_clear_exception(TSRMLS_D) /* {{{ */ { if (EG(prev_exception)) { zval_ptr_dtor(&EG(prev_exception)); EG(prev_exception) = NULL; } if (!EG(exception)) { return; } zval_ptr_dtor(&EG(exception)); EG(exception) = NULL; EG(current_execute_data)->opline = EG(opline_before_exception); #if ZEND_DEBUG EG(opline_before_exception) = NULL; #endif } /* }}} */ static zend_object_value zend_default_exception_new_ex(zend_class_entry *class_type, int skip_top_traces TSRMLS_DC) /* {{{ */ { zval obj; zend_object *object; zval *trace; Z_OBJVAL(obj) = zend_objects_new(&object, class_type TSRMLS_CC); Z_OBJ_HT(obj) = &default_exception_handlers; object_properties_init(object, class_type); ALLOC_ZVAL(trace); Z_UNSET_ISREF_P(trace); Z_SET_REFCOUNT_P(trace, 0); zend_fetch_debug_backtrace(trace, skip_top_traces, 0, 0 TSRMLS_CC); zend_update_property_string(default_exception_ce, &obj, "file", sizeof("file")-1, zend_get_executed_filename(TSRMLS_C) TSRMLS_CC); zend_update_property_long(default_exception_ce, &obj, "line", sizeof("line")-1, zend_get_executed_lineno(TSRMLS_C) TSRMLS_CC); zend_update_property(default_exception_ce, &obj, "trace", sizeof("trace")-1, trace TSRMLS_CC); return Z_OBJVAL(obj); } /* }}} */ static zend_object_value zend_default_exception_new(zend_class_entry *class_type TSRMLS_DC) /* {{{ */ { return zend_default_exception_new_ex(class_type, 0 TSRMLS_CC); } /* }}} */ static zend_object_value zend_error_exception_new(zend_class_entry *class_type TSRMLS_DC) /* {{{ */ { return zend_default_exception_new_ex(class_type, 2 TSRMLS_CC); } /* }}} */ /* {{{ proto Exception Exception::__clone() Clone the exception object */ ZEND_METHOD(exception, __clone) { /* Should never be executable */ zend_throw_exception(NULL, "Cannot clone object using __clone()", 0 TSRMLS_CC); } /* }}} */ /* {{{ proto Exception::__construct(string message, int code [, Exception previous]) Exception constructor */ ZEND_METHOD(exception, __construct) { char *message = NULL; long code = 0; zval *object, *previous = NULL; int argc = ZEND_NUM_ARGS(), message_len; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "|slO!", &message, &message_len, &code, &previous, default_exception_ce) == FAILURE) { zend_error(E_ERROR, "Wrong parameters for Exception([string $exception [, long $code [, Exception $previous = NULL]]])"); } object = getThis(); if (message) { zend_update_property_stringl(default_exception_ce, object, "message", sizeof("message")-1, message, message_len TSRMLS_CC); } if (code) { zend_update_property_long(default_exception_ce, object, "code", sizeof("code")-1, code TSRMLS_CC); } if (previous) { zend_update_property(default_exception_ce, object, "previous", sizeof("previous")-1, previous TSRMLS_CC); } } /* }}} */ /* {{{ proto ErrorException::__construct(string message, int code, int severity [, string filename [, int lineno [, Exception previous]]]) ErrorException constructor */ ZEND_METHOD(error_exception, __construct) { char *message = NULL, *filename = NULL; long code = 0, severity = E_ERROR, lineno; zval *object, *previous = NULL; int argc = ZEND_NUM_ARGS(), message_len, filename_len; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "|sllslO!", &message, &message_len, &code, &severity, &filename, &filename_len, &lineno, &previous, default_exception_ce) == FAILURE) { zend_error(E_ERROR, "Wrong parameters for ErrorException([string $exception [, long $code, [ long $severity, [ string $filename, [ long $lineno [, Exception $previous = NULL]]]]]])"); } object = getThis(); if (message) { zend_update_property_string(default_exception_ce, object, "message", sizeof("message")-1, message TSRMLS_CC); } if (code) { zend_update_property_long(default_exception_ce, object, "code", sizeof("code")-1, code TSRMLS_CC); } if (previous) { zend_update_property(default_exception_ce, object, "previous", sizeof("previous")-1, previous TSRMLS_CC); } zend_update_property_long(default_exception_ce, object, "severity", sizeof("severity")-1, severity TSRMLS_CC); if (argc >= 4) { zend_update_property_string(default_exception_ce, object, "file", sizeof("file")-1, filename TSRMLS_CC); if (argc < 5) { lineno = 0; /* invalidate lineno */ } zend_update_property_long(default_exception_ce, object, "line", sizeof("line")-1, lineno TSRMLS_CC); } } /* }}} */ #define DEFAULT_0_PARAMS \ if (zend_parse_parameters_none() == FAILURE) { \ return; \ } static void _default_exception_get_entry(zval *object, char *name, int name_len, zval *return_value TSRMLS_DC) /* {{{ */ { zval *value; value = zend_read_property(default_exception_ce, object, name, name_len, 0 TSRMLS_CC); *return_value = *value; zval_copy_ctor(return_value); INIT_PZVAL(return_value); } /* }}} */ /* {{{ proto string Exception::getFile() Get the file in which the exception occurred */ ZEND_METHOD(exception, getFile) { DEFAULT_0_PARAMS; _default_exception_get_entry(getThis(), "file", sizeof("file")-1, return_value TSRMLS_CC); } /* }}} */ /* {{{ proto int Exception::getLine() Get the line in which the exception occurred */ ZEND_METHOD(exception, getLine) { DEFAULT_0_PARAMS; _default_exception_get_entry(getThis(), "line", sizeof("line")-1, return_value TSRMLS_CC); } /* }}} */ /* {{{ proto string Exception::getMessage() Get the exception message */ ZEND_METHOD(exception, getMessage) { DEFAULT_0_PARAMS; _default_exception_get_entry(getThis(), "message", sizeof("message")-1, return_value TSRMLS_CC); } /* }}} */ /* {{{ proto int Exception::getCode() Get the exception code */ ZEND_METHOD(exception, getCode) { DEFAULT_0_PARAMS; _default_exception_get_entry(getThis(), "code", sizeof("code")-1, return_value TSRMLS_CC); } /* }}} */ /* {{{ proto array Exception::getTrace() Get the stack trace for the location in which the exception occurred */ ZEND_METHOD(exception, getTrace) { DEFAULT_0_PARAMS; _default_exception_get_entry(getThis(), "trace", sizeof("trace")-1, return_value TSRMLS_CC); } /* }}} */ /* {{{ proto int ErrorException::getSeverity() Get the exception severity */ ZEND_METHOD(error_exception, getSeverity) { DEFAULT_0_PARAMS; _default_exception_get_entry(getThis(), "severity", sizeof("severity")-1, return_value TSRMLS_CC); } /* }}} */ /* {{{ gettraceasstring() macros */ #define TRACE_APPEND_CHR(chr) \ *str = (char*)erealloc(*str, *len + 1 + 1); \ (*str)[(*len)++] = chr #define TRACE_APPEND_STRL(val, vallen) \ { \ int l = vallen; \ *str = (char*)erealloc(*str, *len + l + 1); \ memcpy((*str) + *len, val, l); \ *len += l; \ } #define TRACE_APPEND_STR(val) \ TRACE_APPEND_STRL(val, sizeof(val)-1) #define TRACE_APPEND_KEY(key) \ if (zend_hash_find(ht, key, sizeof(key), (void**)&tmp) == SUCCESS) { \ TRACE_APPEND_STRL(Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp)); \ } /* }}} */ static int _build_trace_args(zval **arg TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { char **str; int *len; str = va_arg(args, char**); len = va_arg(args, int*); /* the trivial way would be to do: * conver_to_string_ex(arg); * append it and kill the now tmp arg. * but that could cause some E_NOTICE and also damn long lines. */ switch (Z_TYPE_PP(arg)) { case IS_NULL: TRACE_APPEND_STR("NULL, "); break; case IS_STRING: { int l_added; TRACE_APPEND_CHR('\''); if (Z_STRLEN_PP(arg) > 15) { TRACE_APPEND_STRL(Z_STRVAL_PP(arg), 15); TRACE_APPEND_STR("...', "); l_added = 15 + 6 + 1; /* +1 because of while (--l_added) */ } else { l_added = Z_STRLEN_PP(arg); TRACE_APPEND_STRL(Z_STRVAL_PP(arg), l_added); TRACE_APPEND_STR("', "); l_added += 3 + 1; } while (--l_added) { if ((*str)[*len - l_added] < 32) { (*str)[*len - l_added] = '?'; } } break; } case IS_BOOL: if (Z_LVAL_PP(arg)) { TRACE_APPEND_STR("true, "); } else { TRACE_APPEND_STR("false, "); } break; case IS_RESOURCE: TRACE_APPEND_STR("Resource id #"); /* break; */ case IS_LONG: { long lval = Z_LVAL_PP(arg); char s_tmp[MAX_LENGTH_OF_LONG + 1]; int l_tmp = zend_sprintf(s_tmp, "%ld", lval); /* SAFE */ TRACE_APPEND_STRL(s_tmp, l_tmp); TRACE_APPEND_STR(", "); break; } case IS_DOUBLE: { double dval = Z_DVAL_PP(arg); char *s_tmp; int l_tmp; s_tmp = emalloc(MAX_LENGTH_OF_DOUBLE + EG(precision) + 1); l_tmp = zend_sprintf(s_tmp, "%.*G", (int) EG(precision), dval); /* SAFE */ TRACE_APPEND_STRL(s_tmp, l_tmp); /* %G already handles removing trailing zeros from the fractional part, yay */ efree(s_tmp); TRACE_APPEND_STR(", "); break; } case IS_ARRAY: TRACE_APPEND_STR("Array, "); break; case IS_OBJECT: { const char *class_name; zend_uint class_name_len; int dup; TRACE_APPEND_STR("Object("); dup = zend_get_object_classname(*arg, &class_name, &class_name_len TSRMLS_CC); TRACE_APPEND_STRL(class_name, class_name_len); if(!dup) { efree((char*)class_name); } TRACE_APPEND_STR("), "); break; } default: break; } return ZEND_HASH_APPLY_KEEP; } /* }}} */ static int _build_trace_string(zval **frame TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { char *s_tmp, **str; int *len, *num; long line; HashTable *ht = Z_ARRVAL_PP(frame); zval **file, **tmp; str = va_arg(args, char**); len = va_arg(args, int*); num = va_arg(args, int*); s_tmp = emalloc(1 + MAX_LENGTH_OF_LONG + 1 + 1); sprintf(s_tmp, "#%d ", (*num)++); TRACE_APPEND_STRL(s_tmp, strlen(s_tmp)); efree(s_tmp); if (zend_hash_find(ht, "file", sizeof("file"), (void**)&file) == SUCCESS) { if (zend_hash_find(ht, "line", sizeof("line"), (void**)&tmp) == SUCCESS) { line = Z_LVAL_PP(tmp); } else { line = 0; } s_tmp = emalloc(Z_STRLEN_PP(file) + MAX_LENGTH_OF_LONG + 4 + 1); sprintf(s_tmp, "%s(%ld): ", Z_STRVAL_PP(file), line); TRACE_APPEND_STRL(s_tmp, strlen(s_tmp)); efree(s_tmp); } else { TRACE_APPEND_STR("[internal function]: "); } TRACE_APPEND_KEY("class"); TRACE_APPEND_KEY("type"); TRACE_APPEND_KEY("function"); TRACE_APPEND_CHR('('); if (zend_hash_find(ht, "args", sizeof("args"), (void**)&tmp) == SUCCESS) { int last_len = *len; zend_hash_apply_with_arguments(Z_ARRVAL_PP(tmp) TSRMLS_CC, (apply_func_args_t)_build_trace_args, 2, str, len); if (last_len != *len) { *len -= 2; /* remove last ', ' */ } } TRACE_APPEND_STR(")\n"); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* {{{ proto string Exception::getTraceAsString() Obtain the backtrace for the exception as a string (instead of an array) */ ZEND_METHOD(exception, getTraceAsString) { zval *trace; char *res, **str, *s_tmp; int res_len = 0, *len = &res_len, num = 0; DEFAULT_0_PARAMS; res = estrdup(""); str = &res; trace = zend_read_property(default_exception_ce, getThis(), "trace", sizeof("trace")-1, 1 TSRMLS_CC); zend_hash_apply_with_arguments(Z_ARRVAL_P(trace) TSRMLS_CC, (apply_func_args_t)_build_trace_string, 3, str, len, &num); s_tmp = emalloc(1 + MAX_LENGTH_OF_LONG + 7 + 1); sprintf(s_tmp, "#%d {main}", num); TRACE_APPEND_STRL(s_tmp, strlen(s_tmp)); efree(s_tmp); res[res_len] = '\0'; RETURN_STRINGL(res, res_len, 0); } /* }}} */ /* {{{ proto string Exception::getPrevious() Return previous Exception or NULL. */ ZEND_METHOD(exception, getPrevious) { zval *previous; DEFAULT_0_PARAMS; previous = zend_read_property(default_exception_ce, getThis(), "previous", sizeof("previous")-1, 1 TSRMLS_CC); RETURN_ZVAL(previous, 1, 0); } int zend_spprintf(char **message, int max_len, char *format, ...) /* {{{ */ { va_list arg; int len; va_start(arg, format); len = zend_vspprintf(message, max_len, format, arg); va_end(arg); return len; } /* }}} */ /* {{{ proto string Exception::__toString() Obtain the string representation of the Exception object */ ZEND_METHOD(exception, __toString) { zval message, file, line, *trace, *exception; char *str, *prev_str; int len = 0; zend_fcall_info fci; zval fname; DEFAULT_0_PARAMS; str = estrndup("", 0); exception = getThis(); ZVAL_STRINGL(&fname, "gettraceasstring", sizeof("gettraceasstring")-1, 1); while (exception && Z_TYPE_P(exception) == IS_OBJECT) { prev_str = str; _default_exception_get_entry(exception, "message", sizeof("message")-1, &message TSRMLS_CC); _default_exception_get_entry(exception, "file", sizeof("file")-1, &file TSRMLS_CC); _default_exception_get_entry(exception, "line", sizeof("line")-1, &line TSRMLS_CC); convert_to_string(&message); convert_to_string(&file); convert_to_long(&line); fci.size = sizeof(fci); fci.function_table = &Z_OBJCE_P(exception)->function_table; fci.function_name = &fname; fci.symbol_table = NULL; fci.object_ptr = exception; fci.retval_ptr_ptr = &trace; fci.param_count = 0; fci.params = NULL; fci.no_separation = 1; zend_call_function(&fci, NULL TSRMLS_CC); if (Z_TYPE_P(trace) != IS_STRING) { zval_ptr_dtor(&trace); trace = NULL; } if (Z_STRLEN(message) > 0) { len = zend_spprintf(&str, 0, "exception '%s' with message '%s' in %s:%ld\nStack trace:\n%s%s%s", Z_OBJCE_P(exception)->name, Z_STRVAL(message), Z_STRVAL(file), Z_LVAL(line), (trace && Z_STRLEN_P(trace)) ? Z_STRVAL_P(trace) : "#0 {main}\n", len ? "\n\nNext " : "", prev_str); } else { len = zend_spprintf(&str, 0, "exception '%s' in %s:%ld\nStack trace:\n%s%s%s", Z_OBJCE_P(exception)->name, Z_STRVAL(file), Z_LVAL(line), (trace && Z_STRLEN_P(trace)) ? Z_STRVAL_P(trace) : "#0 {main}\n", len ? "\n\nNext " : "", prev_str); } efree(prev_str); zval_dtor(&message); zval_dtor(&file); zval_dtor(&line); exception = zend_read_property(default_exception_ce, exception, "previous", sizeof("previous")-1, 0 TSRMLS_CC); if (trace) { zval_ptr_dtor(&trace); } } zval_dtor(&fname); /* We store the result in the private property string so we can access * the result in uncaught exception handlers without memleaks. */ zend_update_property_string(default_exception_ce, getThis(), "string", sizeof("string")-1, str TSRMLS_CC); RETURN_STRINGL(str, len, 0); } /* }}} */ /* {{{ internal structs */ /* All functions that may be used in uncaught exception handlers must be final * and must not throw exceptions. Otherwise we would need a facility to handle * such exceptions in that handler. * Also all getXY() methods are final because thy serve as read only access to * their corresponding properties, no more, no less. If after all you need to * override somthing then it is method __toString(). * And never try to change the state of exceptions and never implement anything * that gives the user anything to accomplish this. */ ZEND_BEGIN_ARG_INFO_EX(arginfo_exception___construct, 0, 0, 0) ZEND_ARG_INFO(0, message) ZEND_ARG_INFO(0, code) ZEND_ARG_INFO(0, previous) ZEND_END_ARG_INFO() const static zend_function_entry default_exception_functions[] = { ZEND_ME(exception, __clone, NULL, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL) ZEND_ME(exception, __construct, arginfo_exception___construct, ZEND_ACC_PUBLIC) ZEND_ME(exception, getMessage, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL) ZEND_ME(exception, getCode, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL) ZEND_ME(exception, getFile, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL) ZEND_ME(exception, getLine, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL) ZEND_ME(exception, getTrace, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL) ZEND_ME(exception, getPrevious, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL) ZEND_ME(exception, getTraceAsString, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL) ZEND_ME(exception, __toString, NULL, 0) {NULL, NULL, NULL} }; ZEND_BEGIN_ARG_INFO_EX(arginfo_error_exception___construct, 0, 0, 0) ZEND_ARG_INFO(0, message) ZEND_ARG_INFO(0, code) ZEND_ARG_INFO(0, severity) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, lineno) ZEND_ARG_INFO(0, previous) ZEND_END_ARG_INFO() static const zend_function_entry error_exception_functions[] = { ZEND_ME(error_exception, __construct, arginfo_error_exception___construct, ZEND_ACC_PUBLIC) ZEND_ME(error_exception, getSeverity, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL) {NULL, NULL, NULL} }; /* }}} */ void zend_register_default_exception(TSRMLS_D) /* {{{ */ { zend_class_entry ce; INIT_CLASS_ENTRY(ce, "Exception", default_exception_functions); default_exception_ce = zend_register_internal_class(&ce TSRMLS_CC); default_exception_ce->create_object = zend_default_exception_new; memcpy(&default_exception_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); default_exception_handlers.clone_obj = NULL; zend_declare_property_string(default_exception_ce, "message", sizeof("message")-1, "", ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_string(default_exception_ce, "string", sizeof("string")-1, "", ZEND_ACC_PRIVATE TSRMLS_CC); zend_declare_property_long(default_exception_ce, "code", sizeof("code")-1, 0, ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(default_exception_ce, "file", sizeof("file")-1, ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(default_exception_ce, "line", sizeof("line")-1, ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(default_exception_ce, "trace", sizeof("trace")-1, ZEND_ACC_PRIVATE TSRMLS_CC); zend_declare_property_null(default_exception_ce, "previous", sizeof("previous")-1, ZEND_ACC_PRIVATE TSRMLS_CC); INIT_CLASS_ENTRY(ce, "ErrorException", error_exception_functions); error_exception_ce = zend_register_internal_class_ex(&ce, default_exception_ce, NULL TSRMLS_CC); error_exception_ce->create_object = zend_error_exception_new; zend_declare_property_long(error_exception_ce, "severity", sizeof("severity")-1, E_ERROR, ZEND_ACC_PROTECTED TSRMLS_CC); } /* }}} */ ZEND_API zend_class_entry *zend_exception_get_default(TSRMLS_D) /* {{{ */ { return default_exception_ce; } /* }}} */ ZEND_API zend_class_entry *zend_get_error_exception(TSRMLS_D) /* {{{ */ { return error_exception_ce; } /* }}} */ ZEND_API zval * zend_throw_exception(zend_class_entry *exception_ce, char *message, long code TSRMLS_DC) /* {{{ */ { zval *ex; MAKE_STD_ZVAL(ex); if (exception_ce) { if (!instanceof_function(exception_ce, default_exception_ce TSRMLS_CC)) { zend_error(E_NOTICE, "Exceptions must be derived from the Exception base class"); exception_ce = default_exception_ce; } } else { exception_ce = default_exception_ce; } object_init_ex(ex, exception_ce); if (message) { zend_update_property_string(default_exception_ce, ex, "message", sizeof("message")-1, message TSRMLS_CC); } if (code) { zend_update_property_long(default_exception_ce, ex, "code", sizeof("code")-1, code TSRMLS_CC); } zend_throw_exception_internal(ex TSRMLS_CC); return ex; } /* }}} */ ZEND_API zval * zend_throw_exception_ex(zend_class_entry *exception_ce, long code TSRMLS_DC, char *format, ...) /* {{{ */ { va_list arg; char *message; zval *zexception; va_start(arg, format); zend_vspprintf(&message, 0, format, arg); va_end(arg); zexception = zend_throw_exception(exception_ce, message, code TSRMLS_CC); efree(message); return zexception; } /* }}} */ ZEND_API zval * zend_throw_error_exception(zend_class_entry *exception_ce, char *message, long code, int severity TSRMLS_DC) /* {{{ */ { zval *ex = zend_throw_exception(exception_ce, message, code TSRMLS_CC); zend_update_property_long(default_exception_ce, ex, "severity", sizeof("severity")-1, severity TSRMLS_CC); return ex; } /* }}} */ static void zend_error_va(int type, const char *file, uint lineno, const char *format, ...) /* {{{ */ { va_list args; va_start(args, format); zend_error_cb(type, file, lineno, format, args); va_end(args); } /* }}} */ /* This function doesn't return if it uses E_ERROR */ ZEND_API void zend_exception_error(zval *exception, int severity TSRMLS_DC) /* {{{ */ { zend_class_entry *ce_exception = Z_OBJCE_P(exception); if (instanceof_function(ce_exception, default_exception_ce TSRMLS_CC)) { zval *str, *file, *line; EG(exception) = NULL; zend_call_method_with_0_params(&exception, ce_exception, NULL, "__tostring", &str); if (!EG(exception)) { if (Z_TYPE_P(str) != IS_STRING) { zend_error(E_WARNING, "%s::__toString() must return a string", ce_exception->name); } else { zend_update_property_string(default_exception_ce, exception, "string", sizeof("string")-1, EG(exception) ? ce_exception->name : Z_STRVAL_P(str) TSRMLS_CC); } } zval_ptr_dtor(&str); if (EG(exception)) { /* do the best we can to inform about the inner exception */ if (instanceof_function(ce_exception, default_exception_ce TSRMLS_CC)) { file = zend_read_property(default_exception_ce, EG(exception), "file", sizeof("file")-1, 1 TSRMLS_CC); line = zend_read_property(default_exception_ce, EG(exception), "line", sizeof("line")-1, 1 TSRMLS_CC); } else { file = NULL; line = NULL; } zend_error_va(E_WARNING, file ? Z_STRVAL_P(file) : NULL, line ? Z_LVAL_P(line) : 0, "Uncaught %s in exception handling during call to %s::__tostring()", Z_OBJCE_P(EG(exception))->name, ce_exception->name); } str = zend_read_property(default_exception_ce, exception, "string", sizeof("string")-1, 1 TSRMLS_CC); file = zend_read_property(default_exception_ce, exception, "file", sizeof("file")-1, 1 TSRMLS_CC); line = zend_read_property(default_exception_ce, exception, "line", sizeof("line")-1, 1 TSRMLS_CC); zend_error_va(severity, Z_STRVAL_P(file), Z_LVAL_P(line), "Uncaught %s\n thrown", Z_STRVAL_P(str)); } else { zend_error(severity, "Uncaught exception '%s'", ce_exception->name); } } /* }}} */ ZEND_API void zend_throw_exception_object(zval *exception TSRMLS_DC) /* {{{ */ { zend_class_entry *exception_ce; if (exception == NULL || Z_TYPE_P(exception) != IS_OBJECT) { zend_error(E_ERROR, "Need to supply an object when throwing an exception"); } exception_ce = Z_OBJCE_P(exception); if (!exception_ce || !instanceof_function(exception_ce, default_exception_ce TSRMLS_CC)) { zend_error(E_ERROR, "Exceptions must be valid objects derived from the Exception base class"); } zend_throw_exception_internal(exception TSRMLS_CC); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2012-03-11-3954743813-d4f05fbffc.c
manybugs_data_94
/* +----------------------------------------------------------------------+ | phar php single-file executable PHP extension | +----------------------------------------------------------------------+ | Copyright (c) 2005-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Gregory Beaver <[email protected]> | | Marcus Boerger <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #define PHAR_MAIN 1 #include "phar_internal.h" #include "SAPI.h" #include "func_interceptors.h" static void destroy_phar_data(void *pDest); ZEND_DECLARE_MODULE_GLOBALS(phar) #if PHP_VERSION_ID >= 50300 char *(*phar_save_resolve_path)(const char *filename, int filename_len TSRMLS_DC); #endif /** * set's phar->is_writeable based on the current INI value */ static int phar_set_writeable_bit(void *pDest, void *argument TSRMLS_DC) /* {{{ */ { zend_bool keep = *(zend_bool *)argument; phar_archive_data *phar = *(phar_archive_data **)pDest; if (!phar->is_data) { phar->is_writeable = !keep; } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* if the original value is 0 (disabled), then allow setting/unsetting at will. Otherwise only allow 1 (enabled), and error on disabling */ ZEND_INI_MH(phar_ini_modify_handler) /* {{{ */ { zend_bool old, ini; if (entry->name_length == 14) { old = PHAR_G(readonly_orig); } else { old = PHAR_G(require_hash_orig); } if (new_value_length == 2 && !strcasecmp("on", new_value)) { ini = (zend_bool) 1; } else if (new_value_length == 3 && !strcasecmp("yes", new_value)) { ini = (zend_bool) 1; } else if (new_value_length == 4 && !strcasecmp("true", new_value)) { ini = (zend_bool) 1; } else { ini = (zend_bool) atoi(new_value); } /* do not allow unsetting in runtime */ if (stage == ZEND_INI_STAGE_STARTUP) { if (entry->name_length == 14) { PHAR_G(readonly_orig) = ini; } else { PHAR_G(require_hash_orig) = ini; } } else if (old && !ini) { return FAILURE; } if (entry->name_length == 14) { PHAR_G(readonly) = ini; if (PHAR_GLOBALS->request_init && PHAR_GLOBALS->phar_fname_map.arBuckets) { zend_hash_apply_with_argument(&(PHAR_GLOBALS->phar_fname_map), phar_set_writeable_bit, (void *)&ini TSRMLS_CC); } } else { PHAR_G(require_hash) = ini; } return SUCCESS; } /* }}}*/ /* this global stores the global cached pre-parsed manifests */ HashTable cached_phars; HashTable cached_alias; static void phar_split_cache_list(TSRMLS_D) /* {{{ */ { char *tmp; char *key, *lasts, *end; char ds[2]; phar_archive_data *phar; uint i = 0; if (!PHAR_GLOBALS->cache_list || !(PHAR_GLOBALS->cache_list[0])) { return; } ds[0] = DEFAULT_DIR_SEPARATOR; ds[1] = '\0'; tmp = estrdup(PHAR_GLOBALS->cache_list); /* fake request startup */ PHAR_GLOBALS->request_init = 1; if (zend_hash_init(&EG(regular_list), 0, NULL, NULL, 0) == SUCCESS) { EG(regular_list).nNextFreeElement=1; /* we don't want resource id 0 */ } PHAR_G(has_bz2) = zend_hash_exists(&module_registry, "bz2", sizeof("bz2")); PHAR_G(has_zlib) = zend_hash_exists(&module_registry, "zlib", sizeof("zlib")); /* these two are dummies and will be destroyed later */ zend_hash_init(&cached_phars, sizeof(phar_archive_data*), zend_get_hash_value, destroy_phar_data, 1); zend_hash_init(&cached_alias, sizeof(phar_archive_data*), zend_get_hash_value, NULL, 1); /* these two are real and will be copied over cached_phars/cached_alias later */ zend_hash_init(&(PHAR_GLOBALS->phar_fname_map), sizeof(phar_archive_data*), zend_get_hash_value, destroy_phar_data, 1); zend_hash_init(&(PHAR_GLOBALS->phar_alias_map), sizeof(phar_archive_data*), zend_get_hash_value, NULL, 1); PHAR_GLOBALS->manifest_cached = 1; PHAR_GLOBALS->persist = 1; for (key = php_strtok_r(tmp, ds, &lasts); key; key = php_strtok_r(NULL, ds, &lasts)) { end = strchr(key, DEFAULT_DIR_SEPARATOR); if (end) { if (SUCCESS == phar_open_from_filename(key, end - key, NULL, 0, 0, &phar, NULL TSRMLS_CC)) { finish_up: phar->phar_pos = i++; php_stream_close(phar->fp); phar->fp = NULL; } else { finish_error: PHAR_GLOBALS->persist = 0; PHAR_GLOBALS->manifest_cached = 0; efree(tmp); zend_hash_destroy(&(PHAR_G(phar_fname_map))); PHAR_GLOBALS->phar_fname_map.arBuckets = 0; zend_hash_destroy(&(PHAR_G(phar_alias_map))); PHAR_GLOBALS->phar_alias_map.arBuckets = 0; zend_hash_destroy(&cached_phars); zend_hash_destroy(&cached_alias); zend_hash_graceful_reverse_destroy(&EG(regular_list)); memset(&EG(regular_list), 0, sizeof(HashTable)); /* free cached manifests */ PHAR_GLOBALS->request_init = 0; return; } } else { if (SUCCESS == phar_open_from_filename(key, strlen(key), NULL, 0, 0, &phar, NULL TSRMLS_CC)) { goto finish_up; } else { goto finish_error; } } } PHAR_GLOBALS->persist = 0; PHAR_GLOBALS->request_init = 0; /* destroy dummy values from before */ zend_hash_destroy(&cached_phars); zend_hash_destroy(&cached_alias); cached_phars = PHAR_GLOBALS->phar_fname_map; cached_alias = PHAR_GLOBALS->phar_alias_map; PHAR_GLOBALS->phar_fname_map.arBuckets = 0; PHAR_GLOBALS->phar_alias_map.arBuckets = 0; zend_hash_graceful_reverse_destroy(&EG(regular_list)); memset(&EG(regular_list), 0, sizeof(HashTable)); efree(tmp); } /* }}} */ ZEND_INI_MH(phar_ini_cache_list) /* {{{ */ { PHAR_G(cache_list) = new_value; if (stage == ZEND_INI_STAGE_STARTUP) { phar_split_cache_list(TSRMLS_C); } return SUCCESS; } /* }}} */ PHP_INI_BEGIN() STD_PHP_INI_BOOLEAN( "phar.readonly", "1", PHP_INI_ALL, phar_ini_modify_handler, readonly, zend_phar_globals, phar_globals) STD_PHP_INI_BOOLEAN( "phar.require_hash", "1", PHP_INI_ALL, phar_ini_modify_handler, require_hash, zend_phar_globals, phar_globals) STD_PHP_INI_ENTRY("phar.cache_list", "", PHP_INI_SYSTEM, phar_ini_cache_list, cache_list, zend_phar_globals, phar_globals) PHP_INI_END() /** * When all uses of a phar have been concluded, this frees the manifest * and the phar slot */ void phar_destroy_phar_data(phar_archive_data *phar TSRMLS_DC) /* {{{ */ { if (phar->alias && phar->alias != phar->fname) { pefree(phar->alias, phar->is_persistent); phar->alias = NULL; } if (phar->fname) { pefree(phar->fname, phar->is_persistent); phar->fname = NULL; } if (phar->signature) { pefree(phar->signature, phar->is_persistent); phar->signature = NULL; } if (phar->manifest.arBuckets) { zend_hash_destroy(&phar->manifest); phar->manifest.arBuckets = NULL; } if (phar->mounted_dirs.arBuckets) { zend_hash_destroy(&phar->mounted_dirs); phar->mounted_dirs.arBuckets = NULL; } if (phar->virtual_dirs.arBuckets) { zend_hash_destroy(&phar->virtual_dirs); phar->virtual_dirs.arBuckets = NULL; } if (phar->metadata) { if (phar->is_persistent) { if (phar->metadata_len) { /* for zip comments that are strings */ free(phar->metadata); } else { zval_internal_ptr_dtor(&phar->metadata); } } else { zval_ptr_dtor(&phar->metadata); } phar->metadata_len = 0; phar->metadata = 0; } if (phar->fp) { php_stream_close(phar->fp); phar->fp = 0; } if (phar->ufp) { php_stream_close(phar->ufp); phar->ufp = 0; } pefree(phar, phar->is_persistent); } /* }}}*/ /** * Delete refcount and destruct if needed. On destruct return 1 else 0. */ int phar_archive_delref(phar_archive_data *phar TSRMLS_DC) /* {{{ */ { if (phar->is_persistent) { return 0; } if (--phar->refcount < 0) { if (PHAR_GLOBALS->request_done || zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), phar->fname, phar->fname_len) != SUCCESS) { phar_destroy_phar_data(phar TSRMLS_CC); } return 1; } else if (!phar->refcount) { /* invalidate phar cache */ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; if (phar->fp && !(phar->flags & PHAR_FILE_COMPRESSION_MASK)) { /* close open file handle - allows removal or rename of the file on windows, which has greedy locking only close if the archive was not already compressed. If it was compressed, then the fp does not refer to the original file */ php_stream_close(phar->fp); phar->fp = NULL; } if (!zend_hash_num_elements(&phar->manifest)) { /* this is a new phar that has perhaps had an alias/metadata set, but has never been flushed */ if (zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), phar->fname, phar->fname_len) != SUCCESS) { phar_destroy_phar_data(phar TSRMLS_CC); } return 1; } } return 0; } /* }}}*/ /** * Destroy phar's in shutdown, here we don't care about aliases */ static void destroy_phar_data_only(void *pDest) /* {{{ */ { phar_archive_data *phar_data = *(phar_archive_data **) pDest; TSRMLS_FETCH(); if (EG(exception) || --phar_data->refcount < 0) { phar_destroy_phar_data(phar_data TSRMLS_CC); } } /* }}}*/ /** * Delete aliases to phar's that got kicked out of the global table */ static int phar_unalias_apply(void *pDest, void *argument TSRMLS_DC) /* {{{ */ { return *(void**)pDest == argument ? ZEND_HASH_APPLY_REMOVE : ZEND_HASH_APPLY_KEEP; } /* }}} */ /** * Delete aliases to phar's that got kicked out of the global table */ static int phar_tmpclose_apply(void *pDest TSRMLS_DC) /* {{{ */ { phar_entry_info *entry = (phar_entry_info *) pDest; if (entry->fp_type != PHAR_TMP) { return ZEND_HASH_APPLY_KEEP; } if (entry->fp && !entry->fp_refcount) { php_stream_close(entry->fp); entry->fp = NULL; } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /** * Filename map destructor */ static void destroy_phar_data(void *pDest) /* {{{ */ { phar_archive_data *phar_data = *(phar_archive_data **) pDest; TSRMLS_FETCH(); if (PHAR_GLOBALS->request_ends) { /* first, iterate over the manifest and close all PHAR_TMP entry fp handles, this prevents unnecessary unfreed stream resources */ zend_hash_apply(&(phar_data->manifest), phar_tmpclose_apply TSRMLS_CC); destroy_phar_data_only(pDest); return; } zend_hash_apply_with_argument(&(PHAR_GLOBALS->phar_alias_map), phar_unalias_apply, phar_data TSRMLS_CC); if (--phar_data->refcount < 0) { phar_destroy_phar_data(phar_data TSRMLS_CC); } } /* }}}*/ /** * destructor for the manifest hash, frees each file's entry */ void destroy_phar_manifest_entry(void *pDest) /* {{{ */ { phar_entry_info *entry = (phar_entry_info *)pDest; TSRMLS_FETCH(); if (entry->cfp) { php_stream_close(entry->cfp); entry->cfp = 0; } if (entry->fp) { php_stream_close(entry->fp); entry->fp = 0; } if (entry->metadata) { if (entry->is_persistent) { if (entry->metadata_len) { /* for zip comments that are strings */ free(entry->metadata); } else { zval_internal_ptr_dtor(&entry->metadata); } } else { zval_ptr_dtor(&entry->metadata); } entry->metadata_len = 0; entry->metadata = 0; } if (entry->metadata_str.c) { smart_str_free(&entry->metadata_str); entry->metadata_str.c = 0; } pefree(entry->filename, entry->is_persistent); if (entry->link) { pefree(entry->link, entry->is_persistent); entry->link = 0; } if (entry->tmp) { pefree(entry->tmp, entry->is_persistent); entry->tmp = 0; } } /* }}} */ int phar_entry_delref(phar_entry_data *idata TSRMLS_DC) /* {{{ */ { int ret = 0; if (idata->internal_file && !idata->internal_file->is_persistent) { if (--idata->internal_file->fp_refcount < 0) { idata->internal_file->fp_refcount = 0; } if (idata->fp && idata->fp != idata->phar->fp && idata->fp != idata->phar->ufp && idata->fp != idata->internal_file->fp) { php_stream_close(idata->fp); } /* if phar_get_or_create_entry_data returns a sub-directory, we have to free it */ if (idata->internal_file->is_temp_dir) { destroy_phar_manifest_entry((void *)idata->internal_file); efree(idata->internal_file); } } phar_archive_delref(idata->phar TSRMLS_CC); efree(idata); return ret; } /* }}} */ /** * Removes an entry, either by actually removing it or by marking it. */ void phar_entry_remove(phar_entry_data *idata, char **error TSRMLS_DC) /* {{{ */ { phar_archive_data *phar; phar = idata->phar; if (idata->internal_file->fp_refcount < 2) { if (idata->fp && idata->fp != idata->phar->fp && idata->fp != idata->phar->ufp && idata->fp != idata->internal_file->fp) { php_stream_close(idata->fp); } zend_hash_del(&idata->phar->manifest, idata->internal_file->filename, idata->internal_file->filename_len); idata->phar->refcount--; efree(idata); } else { idata->internal_file->is_deleted = 1; phar_entry_delref(idata TSRMLS_CC); } if (!phar->donotflush) { phar_flush(phar, 0, 0, 0, error TSRMLS_CC); } } /* }}} */ #define MAPPHAR_ALLOC_FAIL(msg) \ if (fp) {\ php_stream_close(fp);\ }\ if (error) {\ spprintf(error, 0, msg, fname);\ }\ return FAILURE; #define MAPPHAR_FAIL(msg) \ efree(savebuf);\ if (mydata) {\ phar_destroy_phar_data(mydata TSRMLS_CC);\ }\ if (signature) {\ pefree(signature, PHAR_G(persist));\ }\ MAPPHAR_ALLOC_FAIL(msg) #ifdef WORDS_BIGENDIAN # define PHAR_GET_32(buffer, var) \ var = ((((unsigned char*)(buffer))[3]) << 24) \ | ((((unsigned char*)(buffer))[2]) << 16) \ | ((((unsigned char*)(buffer))[1]) << 8) \ | (((unsigned char*)(buffer))[0]); \ (buffer) += 4 # define PHAR_GET_16(buffer, var) \ var = ((((unsigned char*)(buffer))[1]) << 8) \ | (((unsigned char*)(buffer))[0]); \ (buffer) += 2 #else # define PHAR_GET_32(buffer, var) \ memcpy(&var, buffer, sizeof(var)); \ buffer += 4 # define PHAR_GET_16(buffer, var) \ var = *(php_uint16*)(buffer); \ buffer += 2 #endif #define PHAR_ZIP_16(var) ((php_uint16)((((php_uint16)var[0]) & 0xff) | \ (((php_uint16)var[1]) & 0xff) << 8)) #define PHAR_ZIP_32(var) ((php_uint32)((((php_uint32)var[0]) & 0xff) | \ (((php_uint32)var[1]) & 0xff) << 8 | \ (((php_uint32)var[2]) & 0xff) << 16 | \ (((php_uint32)var[3]) & 0xff) << 24)) /** * Open an already loaded phar */ int phar_open_parsed_phar(char *fname, int fname_len, char *alias, int alias_len, int is_data, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { phar_archive_data *phar; #ifdef PHP_WIN32 char *unixfname; #endif if (error) { *error = NULL; } #ifdef PHP_WIN32 unixfname = estrndup(fname, fname_len); phar_unixify_path_separators(unixfname, fname_len); if (SUCCESS == phar_get_archive(&phar, unixfname, fname_len, alias, alias_len, error TSRMLS_CC) && ((alias && fname_len == phar->fname_len && !strncmp(unixfname, phar->fname, fname_len)) || !alias) ) { phar_entry_info *stub; efree(unixfname); #else if (SUCCESS == phar_get_archive(&phar, fname, fname_len, alias, alias_len, error TSRMLS_CC) && ((alias && fname_len == phar->fname_len && !strncmp(fname, phar->fname, fname_len)) || !alias) ) { phar_entry_info *stub; #endif /* logic above is as follows: If an explicit alias was requested, ensure the filename passed in matches the phar's filename. If no alias was passed in, then it can match either and be valid */ if (!is_data) { /* prevent any ".phar" without a stub getting through */ if (!phar->halt_offset && !phar->is_brandnew && (phar->is_tar || phar->is_zip)) { if (PHAR_G(readonly) && FAILURE == zend_hash_find(&(phar->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1, (void **)&stub)) { if (error) { spprintf(error, 0, "'%s' is not a phar archive. Use PharData::__construct() for a standard zip or tar archive", fname); } return FAILURE; } } } if (pphar) { *pphar = phar; } return SUCCESS; } else { #ifdef PHP_WIN32 efree(unixfname); #endif if (pphar) { *pphar = NULL; } if (phar && error && !(options & REPORT_ERRORS)) { efree(error); } return FAILURE; } } /* }}}*/ /** * Parse out metadata from the manifest for a single file * * Meta-data is in this format: * [len32][data...] * * data is the serialized zval */ int phar_parse_metadata(char **buffer, zval **metadata, int zip_metadata_len TSRMLS_DC) /* {{{ */ { const unsigned char *p; php_uint32 buf_len; php_unserialize_data_t var_hash; if (!zip_metadata_len) { PHAR_GET_32(*buffer, buf_len); } else { buf_len = zip_metadata_len; } if (buf_len) { ALLOC_ZVAL(*metadata); INIT_ZVAL(**metadata); p = (const unsigned char*) *buffer; PHP_VAR_UNSERIALIZE_INIT(var_hash); if (!php_var_unserialize(metadata, &p, p + buf_len, &var_hash TSRMLS_CC)) { PHP_VAR_UNSERIALIZE_DESTROY(var_hash); zval_ptr_dtor(metadata); *metadata = NULL; return FAILURE; } PHP_VAR_UNSERIALIZE_DESTROY(var_hash); if (PHAR_G(persist)) { /* lazy init metadata */ zval_ptr_dtor(metadata); *metadata = (zval *) pemalloc(buf_len, 1); memcpy(*metadata, *buffer, buf_len); *buffer += buf_len; return SUCCESS; } } else { *metadata = NULL; } if (!zip_metadata_len) { *buffer += buf_len; } return SUCCESS; } /* }}}*/ /** * Does not check for a previously opened phar in the cache. * * Parse a new one and add it to the cache, returning either SUCCESS or * FAILURE, and setting pphar to the pointer to the manifest entry * * This is used by phar_open_from_filename to process the manifest, but can be called * directly. */ static int phar_parse_pharfile(php_stream *fp, char *fname, int fname_len, char *alias, int alias_len, long halt_offset, phar_archive_data** pphar, php_uint32 compression, char **error TSRMLS_DC) /* {{{ */ { char b32[4], *buffer, *endbuffer, *savebuf; phar_archive_data *mydata = NULL; phar_entry_info entry; php_uint32 manifest_len, manifest_count, manifest_flags, manifest_index, tmp_len, sig_flags; php_uint16 manifest_ver; long offset; int sig_len, register_alias = 0, temp_alias = 0; char *signature = NULL; if (pphar) { *pphar = NULL; } if (error) { *error = NULL; } /* check for ?>\n and increment accordingly */ if (-1 == php_stream_seek(fp, halt_offset, SEEK_SET)) { MAPPHAR_ALLOC_FAIL("cannot seek to __HALT_COMPILER(); location in phar \"%s\"") } buffer = b32; if (3 != php_stream_read(fp, buffer, 3)) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at stub end)") } if ((*buffer == ' ' || *buffer == '\n') && *(buffer + 1) == '?' && *(buffer + 2) == '>') { int nextchar; halt_offset += 3; if (EOF == (nextchar = php_stream_getc(fp))) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at stub end)") } if ((char) nextchar == '\r') { /* if we have an \r we require an \n as well */ if (EOF == (nextchar = php_stream_getc(fp)) || (char)nextchar != '\n') { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at stub end)") } ++halt_offset; } if ((char) nextchar == '\n') { ++halt_offset; } } /* make sure we are at the right location to read the manifest */ if (-1 == php_stream_seek(fp, halt_offset, SEEK_SET)) { MAPPHAR_ALLOC_FAIL("cannot seek to __HALT_COMPILER(); location in phar \"%s\"") } /* read in manifest */ buffer = b32; if (4 != php_stream_read(fp, buffer, 4)) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at manifest length)") } PHAR_GET_32(buffer, manifest_len); if (manifest_len > 1048576 * 100) { /* prevent serious memory issues by limiting manifest to at most 100 MB in length */ MAPPHAR_ALLOC_FAIL("manifest cannot be larger than 100 MB in phar \"%s\"") } buffer = (char *)emalloc(manifest_len); savebuf = buffer; endbuffer = buffer + manifest_len; if (manifest_len < 10 || manifest_len != php_stream_read(fp, buffer, manifest_len)) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest header)") } /* extract the number of entries */ PHAR_GET_32(buffer, manifest_count); if (manifest_count == 0) { MAPPHAR_FAIL("in phar \"%s\", manifest claims to have zero entries. Phars must have at least 1 entry"); } /* extract API version, lowest nibble currently unused */ manifest_ver = (((unsigned char)buffer[0]) << 8) + ((unsigned char)buffer[1]); buffer += 2; if ((manifest_ver & PHAR_API_VER_MASK) < PHAR_API_MIN_READ) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" is API version %1.u.%1.u.%1.u, and cannot be processed", fname, manifest_ver >> 12, (manifest_ver >> 8) & 0xF, (manifest_ver >> 4) & 0x0F); } return FAILURE; } PHAR_GET_32(buffer, manifest_flags); manifest_flags &= ~PHAR_HDR_COMPRESSION_MASK; manifest_flags &= ~PHAR_FILE_COMPRESSION_MASK; /* remember whether this entire phar was compressed with gz/bzip2 */ manifest_flags |= compression; /* The lowest nibble contains the phar wide flags. The compression flags can */ /* be ignored on reading because it is being generated anyways. */ if (manifest_flags & PHAR_HDR_SIGNATURE) { char sig_buf[8], *sig_ptr = sig_buf; off_t read_len; size_t end_of_phar; if (-1 == php_stream_seek(fp, -8, SEEK_END) || (read_len = php_stream_tell(fp)) < 20 || 8 != php_stream_read(fp, sig_buf, 8) || memcmp(sig_buf+4, "GBMB", 4)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } PHAR_GET_32(sig_ptr, sig_flags); switch(sig_flags) { case PHAR_SIG_OPENSSL: { php_uint32 signature_len; char *sig; off_t whence; /* we store the signature followed by the signature length */ if (-1 == php_stream_seek(fp, -12, SEEK_CUR) || 4 != php_stream_read(fp, sig_buf, 4)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" openssl signature length could not be read", fname); } return FAILURE; } sig_ptr = sig_buf; PHAR_GET_32(sig_ptr, signature_len); sig = (char *) emalloc(signature_len); whence = signature_len + 4; whence = -whence; if (-1 == php_stream_seek(fp, whence, SEEK_CUR) || !(end_of_phar = php_stream_tell(fp)) || signature_len != php_stream_read(fp, sig, signature_len)) { efree(savebuf); efree(sig); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" openssl signature could not be read", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, end_of_phar, PHAR_SIG_OPENSSL, sig, signature_len, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); efree(sig); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" openssl signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } efree(sig); } break; #if PHAR_HASH_OK case PHAR_SIG_SHA512: { unsigned char digest[64]; php_stream_seek(fp, -(8 + 64), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_SHA512, (char *)digest, 64, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" SHA512 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } case PHAR_SIG_SHA256: { unsigned char digest[32]; php_stream_seek(fp, -(8 + 32), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_SHA256, (char *)digest, 32, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" SHA256 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } #else case PHAR_SIG_SHA512: case PHAR_SIG_SHA256: efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a unsupported signature", fname); } return FAILURE; #endif case PHAR_SIG_SHA1: { unsigned char digest[20]; php_stream_seek(fp, -(8 + 20), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_SHA1, (char *)digest, 20, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" SHA1 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } case PHAR_SIG_MD5: { unsigned char digest[16]; php_stream_seek(fp, -(8 + 16), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_MD5, (char *)digest, 16, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" MD5 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } default: efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken or unsupported signature", fname); } return FAILURE; } } else if (PHAR_G(require_hash)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" does not have a signature", fname); } return FAILURE; } else { sig_flags = 0; sig_len = 0; } /* extract alias */ PHAR_GET_32(buffer, tmp_len); if (buffer + tmp_len > endbuffer) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (buffer overrun)"); } if (manifest_len < 10 + tmp_len) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest header)") } /* tmp_len = 0 says alias length is 0, which means the alias is not stored in the phar */ if (tmp_len) { /* if the alias is stored we enforce it (implicit overrides explicit) */ if (alias && alias_len && (alias_len != (int)tmp_len || strncmp(alias, buffer, tmp_len))) { buffer[tmp_len] = '\0'; php_stream_close(fp); if (signature) { efree(signature); } if (error) { spprintf(error, 0, "cannot load phar \"%s\" with implicit alias \"%s\" under different alias \"%s\"", fname, buffer, alias); } efree(savebuf); return FAILURE; } alias_len = tmp_len; alias = buffer; buffer += tmp_len; register_alias = 1; } else if (!alias_len || !alias) { /* if we neither have an explicit nor an implicit alias, we use the filename */ alias = NULL; alias_len = 0; register_alias = 0; } else if (alias_len) { register_alias = 1; temp_alias = 1; } /* we have 5 32-bit items plus 1 byte at least */ if (manifest_count > ((manifest_len - 10 - tmp_len) / (5 * 4 + 1))) { /* prevent serious memory issues */ MAPPHAR_FAIL("internal corruption of phar \"%s\" (too many manifest entries for size of manifest)") } mydata = pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist)); mydata->is_persistent = PHAR_G(persist); /* check whether we have meta data, zero check works regardless of byte order */ if (mydata->is_persistent) { PHAR_GET_32(buffer, mydata->metadata_len); if (phar_parse_metadata(&buffer, &mydata->metadata, mydata->metadata_len TSRMLS_CC) == FAILURE) { MAPPHAR_FAIL("unable to read phar metadata in .phar file \"%s\""); } } else { if (phar_parse_metadata(&buffer, &mydata->metadata, 0 TSRMLS_CC) == FAILURE) { MAPPHAR_FAIL("unable to read phar metadata in .phar file \"%s\""); } } /* set up our manifest */ zend_hash_init(&mydata->manifest, manifest_count, zend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)mydata->is_persistent); zend_hash_init(&mydata->mounted_dirs, 5, zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); zend_hash_init(&mydata->virtual_dirs, manifest_count * 2, zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); mydata->fname = pestrndup(fname, fname_len, mydata->is_persistent); #ifdef PHP_WIN32 phar_unixify_path_separators(mydata->fname, fname_len); #endif mydata->fname_len = fname_len; offset = halt_offset + manifest_len + 4; memset(&entry, 0, sizeof(phar_entry_info)); entry.phar = mydata; entry.fp_type = PHAR_FP; entry.is_persistent = mydata->is_persistent; for (manifest_index = 0; manifest_index < manifest_count; ++manifest_index) { if (buffer + 4 > endbuffer) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest entry)") } PHAR_GET_32(buffer, entry.filename_len); if (entry.filename_len == 0) { MAPPHAR_FAIL("zero-length filename encountered in phar \"%s\""); } if (entry.is_persistent) { entry.manifest_pos = manifest_index; } if (buffer + entry.filename_len + 20 > endbuffer) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest entry)"); } if ((manifest_ver & PHAR_API_VER_MASK) >= PHAR_API_MIN_DIR && buffer[entry.filename_len - 1] == '/') { entry.is_dir = 1; } else { entry.is_dir = 0; } phar_add_virtual_dirs(mydata, buffer, entry.filename_len TSRMLS_CC); entry.filename = pestrndup(buffer, entry.filename_len, entry.is_persistent); buffer += entry.filename_len; PHAR_GET_32(buffer, entry.uncompressed_filesize); PHAR_GET_32(buffer, entry.timestamp); if (offset == halt_offset + (int)manifest_len + 4) { mydata->min_timestamp = entry.timestamp; mydata->max_timestamp = entry.timestamp; } else { if (mydata->min_timestamp > entry.timestamp) { mydata->min_timestamp = entry.timestamp; } else if (mydata->max_timestamp < entry.timestamp) { mydata->max_timestamp = entry.timestamp; } } PHAR_GET_32(buffer, entry.compressed_filesize); PHAR_GET_32(buffer, entry.crc32); PHAR_GET_32(buffer, entry.flags); if (entry.is_dir) { entry.filename_len--; entry.flags |= PHAR_ENT_PERM_DEF_DIR; } if (entry.is_persistent) { PHAR_GET_32(buffer, entry.metadata_len); if (!entry.metadata_len) buffer -= 4; if (phar_parse_metadata(&buffer, &entry.metadata, entry.metadata_len TSRMLS_CC) == FAILURE) { pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("unable to read file metadata in .phar file \"%s\""); } } else { if (phar_parse_metadata(&buffer, &entry.metadata, 0 TSRMLS_CC) == FAILURE) { pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("unable to read file metadata in .phar file \"%s\""); } } entry.offset = entry.offset_abs = offset; offset += entry.compressed_filesize; switch (entry.flags & PHAR_ENT_COMPRESSION_MASK) { case PHAR_ENT_COMPRESSED_GZ: if (!PHAR_G(has_zlib)) { if (entry.metadata) { if (entry.is_persistent) { free(entry.metadata); } else { zval_ptr_dtor(&entry.metadata); } } pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("zlib extension is required for gz compressed .phar file \"%s\""); } break; case PHAR_ENT_COMPRESSED_BZ2: if (!PHAR_G(has_bz2)) { if (entry.metadata) { if (entry.is_persistent) { free(entry.metadata); } else { zval_ptr_dtor(&entry.metadata); } } pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("bz2 extension is required for bzip2 compressed .phar file \"%s\""); } break; default: if (entry.uncompressed_filesize != entry.compressed_filesize) { if (entry.metadata) { if (entry.is_persistent) { free(entry.metadata); } else { zval_ptr_dtor(&entry.metadata); } } pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("internal corruption of phar \"%s\" (compressed and uncompressed size does not match for uncompressed entry)"); } break; } manifest_flags |= (entry.flags & PHAR_ENT_COMPRESSION_MASK); /* if signature matched, no need to check CRC32 for each file */ entry.is_crc_checked = (manifest_flags & PHAR_HDR_SIGNATURE ? 1 : 0); phar_set_inode(&entry TSRMLS_CC); zend_hash_add(&mydata->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info), NULL); } snprintf(mydata->version, sizeof(mydata->version), "%u.%u.%u", manifest_ver >> 12, (manifest_ver >> 8) & 0xF, (manifest_ver >> 4) & 0xF); mydata->internal_file_start = halt_offset + manifest_len + 4; mydata->halt_offset = halt_offset; mydata->flags = manifest_flags; endbuffer = strrchr(mydata->fname, '/'); if (endbuffer) { mydata->ext = memchr(endbuffer, '.', (mydata->fname + fname_len) - endbuffer); if (mydata->ext == endbuffer) { mydata->ext = memchr(endbuffer + 1, '.', (mydata->fname + fname_len) - endbuffer - 1); } if (mydata->ext) { mydata->ext_len = (mydata->fname + mydata->fname_len) - mydata->ext; } } mydata->alias = alias ? pestrndup(alias, alias_len, mydata->is_persistent) : pestrndup(mydata->fname, fname_len, mydata->is_persistent); mydata->alias_len = alias ? alias_len : fname_len; mydata->sig_flags = sig_flags; mydata->fp = fp; mydata->sig_len = sig_len; mydata->signature = signature; phar_request_initialize(TSRMLS_C); if (register_alias) { phar_archive_data **fd_ptr; mydata->is_temporary_alias = temp_alias; if (!phar_validate_alias(mydata->alias, mydata->alias_len)) { signature = NULL; fp = NULL; MAPPHAR_FAIL("Cannot open archive \"%s\", invalid alias"); } if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) { if (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) { signature = NULL; fp = NULL; MAPPHAR_FAIL("Cannot open archive \"%s\", alias is already in use by existing archive"); } } zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&mydata, sizeof(phar_archive_data*), NULL); } else { mydata->is_temporary_alias = 1; } zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len, (void*)&mydata, sizeof(phar_archive_data*), NULL); efree(savebuf); if (pphar) { *pphar = mydata; } return SUCCESS; } /* }}} */ /** * Create or open a phar for writing */ int phar_open_or_create_filename(char *fname, int fname_len, char *alias, int alias_len, int is_data, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { const char *ext_str, *z; char *my_error; int ext_len; phar_archive_data **test, *unused = NULL; test = &unused; if (error) { *error = NULL; } /* first try to open an existing file */ if (phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, !is_data, 0, 1 TSRMLS_CC) == SUCCESS) { goto check_file; } /* next try to create a new file */ if (FAILURE == phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, !is_data, 1, 1 TSRMLS_CC)) { if (error) { if (ext_len == -2) { spprintf(error, 0, "Cannot create a phar archive from a URL like \"%s\". Phar objects can only be created from local files", fname); } else { spprintf(error, 0, "Cannot create phar '%s', file extension (or combination) not recognised or the directory does not exist", fname); } } return FAILURE; } check_file: if (phar_open_parsed_phar(fname, fname_len, alias, alias_len, is_data, options, test, &my_error TSRMLS_CC) == SUCCESS) { if (pphar) { *pphar = *test; } if ((*test)->is_data && !(*test)->is_tar && !(*test)->is_zip) { if (error) { spprintf(error, 0, "Cannot open '%s' as a PharData object. Use Phar::__construct() for executable archives", fname); } return FAILURE; } if (PHAR_G(readonly) && !(*test)->is_data && ((*test)->is_tar || (*test)->is_zip)) { phar_entry_info *stub; if (FAILURE == zend_hash_find(&((*test)->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1, (void **)&stub)) { spprintf(error, 0, "'%s' is not a phar archive. Use PharData::__construct() for a standard zip or tar archive", fname); return FAILURE; } } if (!PHAR_G(readonly) || (*test)->is_data) { (*test)->is_writeable = 1; } return SUCCESS; } else if (my_error) { if (error) { *error = my_error; } else { efree(my_error); } return FAILURE; } if (ext_len > 3 && (z = memchr(ext_str, 'z', ext_len)) && ((ext_str + ext_len) - z >= 2) && !memcmp(z + 1, "ip", 2)) { /* assume zip-based phar */ return phar_open_or_create_zip(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC); } if (ext_len > 3 && (z = memchr(ext_str, 't', ext_len)) && ((ext_str + ext_len) - z >= 2) && !memcmp(z + 1, "ar", 2)) { /* assume tar-based phar */ return phar_open_or_create_tar(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC); } return phar_create_or_parse_filename(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC); } /* }}} */ int phar_create_or_parse_filename(char *fname, int fname_len, char *alias, int alias_len, int is_data, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { phar_archive_data *mydata; php_stream *fp; char *actual = NULL, *p; if (!pphar) { pphar = &mydata; } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { return FAILURE; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { return FAILURE; } /* first open readonly so it won't be created if not present */ fp = php_stream_open_wrapper(fname, "rb", IGNORE_URL|STREAM_MUST_SEEK|0, &actual); if (actual) { fname = actual; fname_len = strlen(actual); } if (fp) { if (phar_open_from_fp(fp, fname, fname_len, alias, alias_len, options, pphar, is_data, error TSRMLS_CC) == SUCCESS) { if ((*pphar)->is_data || !PHAR_G(readonly)) { (*pphar)->is_writeable = 1; } if (actual) { efree(actual); } return SUCCESS; } else { /* file exists, but is either corrupt or not a phar archive */ if (actual) { efree(actual); } return FAILURE; } } if (actual) { efree(actual); } if (PHAR_G(readonly) && !is_data) { if (options & REPORT_ERRORS) { if (error) { spprintf(error, 0, "creating archive \"%s\" disabled by the php.ini setting phar.readonly", fname); } } return FAILURE; } /* set up our manifest */ mydata = ecalloc(1, sizeof(phar_archive_data)); mydata->fname = expand_filepath(fname, NULL TSRMLS_CC); fname_len = strlen(mydata->fname); #ifdef PHP_WIN32 phar_unixify_path_separators(mydata->fname, fname_len); #endif p = strrchr(mydata->fname, '/'); if (p) { mydata->ext = memchr(p, '.', (mydata->fname + fname_len) - p); if (mydata->ext == p) { mydata->ext = memchr(p + 1, '.', (mydata->fname + fname_len) - p - 1); } if (mydata->ext) { mydata->ext_len = (mydata->fname + fname_len) - mydata->ext; } } if (pphar) { *pphar = mydata; } zend_hash_init(&mydata->manifest, sizeof(phar_entry_info), zend_get_hash_value, destroy_phar_manifest_entry, 0); zend_hash_init(&mydata->mounted_dirs, sizeof(char *), zend_get_hash_value, NULL, 0); zend_hash_init(&mydata->virtual_dirs, sizeof(char *), zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); mydata->fname_len = fname_len; snprintf(mydata->version, sizeof(mydata->version), "%s", PHP_PHAR_API_VERSION); mydata->is_temporary_alias = alias ? 0 : 1; mydata->internal_file_start = -1; mydata->fp = NULL; mydata->is_writeable = 1; mydata->is_brandnew = 1; phar_request_initialize(TSRMLS_C); zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len, (void*)&mydata, sizeof(phar_archive_data*), NULL); if (is_data) { alias = NULL; alias_len = 0; mydata->is_data = 1; /* assume tar format, PharData can specify other */ mydata->is_tar = 1; } else { phar_archive_data **fd_ptr; if (alias && SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) { if (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) { if (error) { spprintf(error, 4096, "phar error: phar \"%s\" cannot set alias \"%s\", already in use by another phar archive", mydata->fname, alias); } zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len); if (pphar) { *pphar = NULL; } return FAILURE; } } mydata->alias = alias ? estrndup(alias, alias_len) : estrndup(mydata->fname, fname_len); mydata->alias_len = alias ? alias_len : fname_len; } if (alias_len && alias) { if (FAILURE == zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&mydata, sizeof(phar_archive_data*), NULL)) { if (options & REPORT_ERRORS) { if (error) { spprintf(error, 0, "archive \"%s\" cannot be associated with alias \"%s\", already in use", fname, alias); } } zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len); if (pphar) { *pphar = NULL; } return FAILURE; } } return SUCCESS; } /* }}}*/ /** * Return an already opened filename. * * Or scan a phar file for the required __HALT_COMPILER(); ?> token and verify * that the manifest is proper, then pass it to phar_parse_pharfile(). SUCCESS * or FAILURE is returned and pphar is set to a pointer to the phar's manifest */ int phar_open_from_filename(char *fname, int fname_len, char *alias, int alias_len, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { php_stream *fp; char *actual; int ret, is_data = 0; if (error) { *error = NULL; } if (!strstr(fname, ".phar")) { is_data = 1; } if (phar_open_parsed_phar(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC) == SUCCESS) { return SUCCESS; } else if (error && *error) { return FAILURE; } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { return FAILURE; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { return FAILURE; } fp = php_stream_open_wrapper(fname, "rb", IGNORE_URL|STREAM_MUST_SEEK, &actual); if (!fp) { if (options & REPORT_ERRORS) { if (error) { spprintf(error, 0, "unable to open phar for reading \"%s\"", fname); } } if (actual) { efree(actual); } return FAILURE; } if (actual) { fname = actual; fname_len = strlen(actual); } ret = phar_open_from_fp(fp, fname, fname_len, alias, alias_len, options, pphar, is_data, error TSRMLS_CC); if (actual) { efree(actual); } return ret; } /* }}}*/ static inline char *phar_strnstr(const char *buf, int buf_len, const char *search, int search_len) /* {{{ */ { const char *c; int so_far = 0; if (buf_len < search_len) { return NULL; } c = buf - 1; do { if (!(c = memchr(c + 1, search[0], buf_len - search_len - so_far))) { return (char *) NULL; } so_far = c - buf; if (so_far >= (buf_len - search_len)) { return (char *) NULL; } if (!memcmp(c, search, search_len)) { return (char *) c; } } while (1); } /* }}} */ /** * Scan an open fp for the required __HALT_COMPILER(); ?> token and verify * that the manifest is proper, then pass it to phar_parse_pharfile(). SUCCESS * or FAILURE is returned and pphar is set to a pointer to the phar's manifest */ static int phar_open_from_fp(php_stream* fp, char *fname, int fname_len, char *alias, int alias_len, int options, phar_archive_data** pphar, int is_data, char **error TSRMLS_DC) /* {{{ */ { const char token[] = "__HALT_COMPILER();"; const char zip_magic[] = "PK\x03\x04"; const char gz_magic[] = "\x1f\x8b\x08"; const char bz_magic[] = "BZh"; char *pos, test = '\0'; const int window_size = 1024 + sizeof(token); char buffer[1024 + sizeof(token)]; /* a 1024 byte window + the size of the halt_compiler token (moving window) */ const long readsize = sizeof(buffer) - sizeof(token); const long tokenlen = sizeof(token) - 1; long halt_offset; size_t got; php_uint32 compression = PHAR_FILE_COMPRESSED_NONE; if (error) { *error = NULL; } if (-1 == php_stream_rewind(fp)) { MAPPHAR_ALLOC_FAIL("cannot rewind phar \"%s\"") } buffer[sizeof(buffer)-1] = '\0'; memset(buffer, 32, sizeof(token)); halt_offset = 0; /* Maybe it's better to compile the file instead of just searching, */ /* but we only want the offset. So we want a .re scanner to find it. */ while(!php_stream_eof(fp)) { if ((got = php_stream_read(fp, buffer+tokenlen, readsize)) < (size_t) tokenlen) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated entry)") } if (!test) { test = '\1'; pos = buffer+tokenlen; if (!memcmp(pos, gz_magic, 3)) { char err = 0; php_stream_filter *filter; php_stream *temp; /* to properly decompress, we have to tell zlib to look for a zlib or gzip header */ zval filterparams; if (!PHAR_G(has_zlib)) { MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\" to temporary file, enable zlib extension in php.ini") } array_init(&filterparams); /* this is defined in zlib's zconf.h */ #ifndef MAX_WBITS #define MAX_WBITS 15 #endif add_assoc_long(&filterparams, "window", MAX_WBITS + 32); /* entire file is gzip-compressed, uncompress to temporary file */ if (!(temp = php_stream_fopen_tmpfile())) { MAPPHAR_ALLOC_FAIL("unable to create temporary file for decompression of gzipped phar archive \"%s\"") } php_stream_rewind(fp); filter = php_stream_filter_create("zlib.inflate", &filterparams, php_stream_is_persistent(fp) TSRMLS_CC); if (!filter) { err = 1; add_assoc_long(&filterparams, "window", MAX_WBITS); filter = php_stream_filter_create("zlib.inflate", &filterparams, php_stream_is_persistent(fp) TSRMLS_CC); zval_dtor(&filterparams); if (!filter) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\", ext/zlib is buggy in PHP versions older than 5.2.6") } } else { zval_dtor(&filterparams); } php_stream_filter_append(&temp->writefilters, filter); if (SUCCESS != phar_stream_copy_to_stream(fp, temp, PHP_STREAM_COPY_ALL, NULL)) { if (err) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\", ext/zlib is buggy in PHP versions older than 5.2.6") } php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\" to temporary file") } php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(fp); fp = temp; php_stream_rewind(fp); compression = PHAR_FILE_COMPRESSED_GZ; /* now, start over */ test = '\0'; continue; } else if (!memcmp(pos, bz_magic, 3)) { php_stream_filter *filter; php_stream *temp; if (!PHAR_G(has_bz2)) { MAPPHAR_ALLOC_FAIL("unable to decompress bzipped phar archive \"%s\" to temporary file, enable bz2 extension in php.ini") } /* entire file is bzip-compressed, uncompress to temporary file */ if (!(temp = php_stream_fopen_tmpfile())) { MAPPHAR_ALLOC_FAIL("unable to create temporary file for decompression of bzipped phar archive \"%s\"") } php_stream_rewind(fp); filter = php_stream_filter_create("bzip2.decompress", NULL, php_stream_is_persistent(fp) TSRMLS_CC); if (!filter) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress bzipped phar archive \"%s\", filter creation failed") } php_stream_filter_append(&temp->writefilters, filter); if (SUCCESS != phar_stream_copy_to_stream(fp, temp, PHP_STREAM_COPY_ALL, NULL)) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress bzipped phar archive \"%s\" to temporary file") } php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(fp); fp = temp; php_stream_rewind(fp); compression = PHAR_FILE_COMPRESSED_BZ2; /* now, start over */ test = '\0'; continue; } if (!memcmp(pos, zip_magic, 4)) { php_stream_seek(fp, 0, SEEK_END); return phar_parse_zipfile(fp, fname, fname_len, alias, alias_len, pphar, error TSRMLS_CC); } if (got > 512) { if (phar_is_tar(pos, fname)) { php_stream_rewind(fp); return phar_parse_tarfile(fp, fname, fname_len, alias, alias_len, pphar, is_data, compression, error TSRMLS_CC); } } } if (got > 0 && (pos = phar_strnstr(buffer, got + sizeof(token), token, sizeof(token)-1)) != NULL) { halt_offset += (pos - buffer); /* no -tokenlen+tokenlen here */ return phar_parse_pharfile(fp, fname, fname_len, alias, alias_len, halt_offset, pphar, compression, error TSRMLS_CC); } halt_offset += got; memmove(buffer, buffer + window_size, tokenlen); /* move the memory buffer by the size of the window */ } MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (__HALT_COMPILER(); not found)") } /* }}} */ /* * given the location of the file extension and the start of the file path, * determine the end of the portion of the path (i.e. /path/to/file.ext/blah * grabs "/path/to/file.ext" as does the straight /path/to/file.ext), * stat it to determine if it exists. * if so, check to see if it is a directory and fail if so * if not, check to see if its dirname() exists (i.e. "/path/to") and is a directory * succeed if we are creating the file, otherwise fail. */ static int phar_analyze_path(const char *fname, const char *ext, int ext_len, int for_create TSRMLS_DC) /* {{{ */ { php_stream_statbuf ssb; char *realpath; char *filename = estrndup(fname, (ext - fname) + ext_len); if ((realpath = expand_filepath(filename, NULL TSRMLS_CC))) { #ifdef PHP_WIN32 phar_unixify_path_separators(realpath, strlen(realpath)); #endif if (zend_hash_exists(&(PHAR_GLOBALS->phar_fname_map), realpath, strlen(realpath))) { efree(realpath); efree(filename); return SUCCESS; } if (PHAR_G(manifest_cached) && zend_hash_exists(&cached_phars, realpath, strlen(realpath))) { efree(realpath); efree(filename); return SUCCESS; } efree(realpath); } if (SUCCESS == php_stream_stat_path((char *) filename, &ssb)) { efree(filename); if (ssb.sb.st_mode & S_IFDIR) { return FAILURE; } if (for_create == 1) { return FAILURE; } return SUCCESS; } else { char *slash; if (!for_create) { efree(filename); return FAILURE; } slash = (char *) strrchr(filename, '/'); if (slash) { *slash = '\0'; } if (SUCCESS != php_stream_stat_path((char *) filename, &ssb)) { if (!slash) { if (!(realpath = expand_filepath(filename, NULL TSRMLS_CC))) { efree(filename); return FAILURE; } #ifdef PHP_WIN32 phar_unixify_path_separators(realpath, strlen(realpath)); #endif slash = strstr(realpath, filename) + ((ext - fname) + ext_len); *slash = '\0'; slash = strrchr(realpath, '/'); if (slash) { *slash = '\0'; } else { efree(realpath); efree(filename); return FAILURE; } if (SUCCESS != php_stream_stat_path(realpath, &ssb)) { efree(realpath); efree(filename); return FAILURE; } efree(realpath); if (ssb.sb.st_mode & S_IFDIR) { efree(filename); return SUCCESS; } } efree(filename); return FAILURE; } efree(filename); if (ssb.sb.st_mode & S_IFDIR) { return SUCCESS; } return FAILURE; } } /* }}} */ /* check for ".phar" in extension */ static int phar_check_str(const char *fname, const char *ext_str, int ext_len, int executable, int for_create TSRMLS_DC) /* {{{ */ { char test[51]; const char *pos; if (ext_len >= 50) { return FAILURE; } if (executable == 1) { /* copy "." as well */ memcpy(test, ext_str - 1, ext_len + 1); test[ext_len + 1] = '\0'; /* executable phars must contain ".phar" as a valid extension (phar://.pharmy/oops is invalid) */ /* (phar://hi/there/.phar/oops is also invalid) */ pos = strstr(test, ".phar"); if (pos && (*(pos - 1) != '/') && (pos += 5) && (*pos == '\0' || *pos == '/' || *pos == '.')) { return phar_analyze_path(fname, ext_str, ext_len, for_create TSRMLS_CC); } else { return FAILURE; } } /* data phars need only contain a single non-"." to be valid */ if (!executable) { pos = strstr(ext_str, ".phar"); if (!(pos && (*(pos - 1) != '/') && (pos += 5) && (*pos == '\0' || *pos == '/' || *pos == '.')) && *(ext_str + 1) != '.' && *(ext_str + 1) != '/' && *(ext_str + 1) != '\0') { return phar_analyze_path(fname, ext_str, ext_len, for_create TSRMLS_CC); } } else { if (*(ext_str + 1) != '.' && *(ext_str + 1) != '/' && *(ext_str + 1) != '\0') { return phar_analyze_path(fname, ext_str, ext_len, for_create TSRMLS_CC); } } return FAILURE; } /* }}} */ /* * if executable is 1, only returns SUCCESS if the extension is one of the tar/zip .phar extensions * if executable is 0, it returns SUCCESS only if the filename does *not* contain ".phar" anywhere, and treats * the first extension as the filename extension * * if an extension is found, it sets ext_str to the location of the file extension in filename, * and ext_len to the length of the extension. * for urls like "phar://alias/oops" it instead sets ext_len to -1 and returns FAILURE, which tells * the calling function to use "alias" as the phar alias * * the last parameter should be set to tell the thing to assume that filename is the full path, and only to check the * extension rules, not to iterate. */ int phar_detect_phar_fname_ext(const char *filename, int filename_len, const char **ext_str, int *ext_len, int executable, int for_create, int is_complete TSRMLS_DC) /* {{{ */ { const char *pos, *slash; *ext_str = NULL; *ext_len = 0; if (!filename_len || filename_len == 1) { return FAILURE; } phar_request_initialize(TSRMLS_C); /* first check for alias in first segment */ pos = memchr(filename, '/', filename_len); if (pos && pos != filename) { /* check for url like http:// or phar:// */ if (*(pos - 1) == ':' && (pos - filename) < filename_len - 1 && *(pos + 1) == '/') { *ext_len = -2; *ext_str = NULL; return FAILURE; } if (zend_hash_exists(&(PHAR_GLOBALS->phar_alias_map), (char *) filename, pos - filename)) { *ext_str = pos; *ext_len = -1; return FAILURE; } if (PHAR_G(manifest_cached) && zend_hash_exists(&cached_alias, (char *) filename, pos - filename)) { *ext_str = pos; *ext_len = -1; return FAILURE; } } if (zend_hash_num_elements(&(PHAR_GLOBALS->phar_fname_map)) || PHAR_G(manifest_cached)) { phar_archive_data **pphar; if (is_complete) { if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), (char *) filename, filename_len, (void **)&pphar)) { *ext_str = filename + (filename_len - (*pphar)->ext_len); woohoo: *ext_len = (*pphar)->ext_len; if (executable == 2) { return SUCCESS; } if (executable == 1 && !(*pphar)->is_data) { return SUCCESS; } if (!executable && (*pphar)->is_data) { return SUCCESS; } return FAILURE; } if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, (char *) filename, filename_len, (void **)&pphar)) { *ext_str = filename + (filename_len - (*pphar)->ext_len); goto woohoo; } } else { phar_zstr key; char *str_key; uint keylen; ulong unused; zend_hash_internal_pointer_reset(&(PHAR_GLOBALS->phar_fname_map)); while (FAILURE != zend_hash_has_more_elements(&(PHAR_GLOBALS->phar_fname_map))) { if (HASH_KEY_NON_EXISTANT == zend_hash_get_current_key_ex(&(PHAR_GLOBALS->phar_fname_map), &key, &keylen, &unused, 0, NULL)) { break; } PHAR_STR(key, str_key); if (keylen > (uint) filename_len) { zend_hash_move_forward(&(PHAR_GLOBALS->phar_fname_map)); PHAR_STR_FREE(str_key); continue; } if (!memcmp(filename, str_key, keylen) && ((uint)filename_len == keylen || filename[keylen] == '/' || filename[keylen] == '\0')) { PHAR_STR_FREE(str_key); if (FAILURE == zend_hash_get_current_data(&(PHAR_GLOBALS->phar_fname_map), (void **) &pphar)) { break; } *ext_str = filename + (keylen - (*pphar)->ext_len); goto woohoo; } PHAR_STR_FREE(str_key); zend_hash_move_forward(&(PHAR_GLOBALS->phar_fname_map)); } if (PHAR_G(manifest_cached)) { zend_hash_internal_pointer_reset(&cached_phars); while (FAILURE != zend_hash_has_more_elements(&cached_phars)) { if (HASH_KEY_NON_EXISTANT == zend_hash_get_current_key_ex(&cached_phars, &key, &keylen, &unused, 0, NULL)) { break; } PHAR_STR(key, str_key); if (keylen > (uint) filename_len) { zend_hash_move_forward(&cached_phars); PHAR_STR_FREE(str_key); continue; } if (!memcmp(filename, str_key, keylen) && ((uint)filename_len == keylen || filename[keylen] == '/' || filename[keylen] == '\0')) { PHAR_STR_FREE(str_key); if (FAILURE == zend_hash_get_current_data(&cached_phars, (void **) &pphar)) { break; } *ext_str = filename + (keylen - (*pphar)->ext_len); goto woohoo; } PHAR_STR_FREE(str_key); zend_hash_move_forward(&cached_phars); } } } } pos = memchr(filename + 1, '.', filename_len); next_extension: if (!pos) { return FAILURE; } while (pos != filename && (*(pos - 1) == '/' || *(pos - 1) == '\0')) { pos = memchr(pos + 1, '.', filename_len - (pos - filename) + 1); if (!pos) { return FAILURE; } } slash = memchr(pos, '/', filename_len - (pos - filename)); if (!slash) { /* this is a url like "phar://blah.phar" with no directory */ *ext_str = pos; *ext_len = strlen(pos); /* file extension must contain "phar" */ switch (phar_check_str(filename, *ext_str, *ext_len, executable, for_create TSRMLS_CC)) { case SUCCESS: return SUCCESS; case FAILURE: /* we are at the end of the string, so we fail */ return FAILURE; } } /* we've found an extension that ends at a directory separator */ *ext_str = pos; *ext_len = slash - pos; switch (phar_check_str(filename, *ext_str, *ext_len, executable, for_create TSRMLS_CC)) { case SUCCESS: return SUCCESS; case FAILURE: /* look for more extensions */ pos = strchr(pos + 1, '.'); if (pos) { *ext_str = NULL; *ext_len = 0; } goto next_extension; } return FAILURE; } /* }}} */ static int php_check_dots(const char *element, int n) /* {{{ */ { for(n--; n >= 0; --n) { if (element[n] != '.') { return 1; } } return 0; } /* }}} */ #define IS_DIRECTORY_UP(element, len) \ (len >= 2 && !php_check_dots(element, len)) #define IS_DIRECTORY_CURRENT(element, len) \ (len == 1 && element[0] == '.') #define IS_BACKSLASH(c) ((c) == '/') #ifdef COMPILE_DL_PHAR /* stupid-ass non-extern declaration in tsrm_strtok.h breaks dumbass MS compiler */ static inline int in_character_class(char ch, const char *delim) /* {{{ */ { while (*delim) { if (*delim == ch) { return 1; } ++delim; } return 0; } /* }}} */ char *tsrm_strtok_r(char *s, const char *delim, char **last) /* {{{ */ { char *token; if (s == NULL) { s = *last; } while (*s && in_character_class(*s, delim)) { ++s; } if (!*s) { return NULL; } token = s; while (*s && !in_character_class(*s, delim)) { ++s; } if (!*s) { *last = s; } else { *s = '\0'; *last = s + 1; } return token; } /* }}} */ #endif /** * Remove .. and . references within a phar filename */ char *phar_fix_filepath(char *path, int *new_len, int use_cwd TSRMLS_DC) /* {{{ */ { char newpath[MAXPATHLEN]; int newpath_len; char *ptr; char *tok; int ptr_length, path_length = *new_len; if (PHAR_G(cwd_len) && use_cwd && path_length > 2 && path[0] == '.' && path[1] == '/') { newpath_len = PHAR_G(cwd_len); memcpy(newpath, PHAR_G(cwd), newpath_len); } else { newpath[0] = '/'; newpath_len = 1; } ptr = path; if (*ptr == '/') { ++ptr; } tok = ptr; do { ptr = memchr(ptr, '/', path_length - (ptr - path)); } while (ptr && ptr - tok == 0 && *ptr == '/' && ++ptr && ++tok); if (!ptr && (path_length - (tok - path))) { switch (path_length - (tok - path)) { case 1: if (*tok == '.') { efree(path); *new_len = 1; return estrndup("/", 1); } break; case 2: if (tok[0] == '.' && tok[1] == '.') { efree(path); *new_len = 1; return estrndup("/", 1); } } return path; } while (ptr) { ptr_length = ptr - tok; last_time: if (IS_DIRECTORY_UP(tok, ptr_length)) { #define PREVIOUS newpath[newpath_len - 1] while (newpath_len > 1 && !IS_BACKSLASH(PREVIOUS)) { newpath_len--; } if (newpath[0] != '/') { newpath[newpath_len] = '\0'; } else if (newpath_len > 1) { --newpath_len; } } else if (!IS_DIRECTORY_CURRENT(tok, ptr_length)) { if (newpath_len > 1) { newpath[newpath_len++] = '/'; memcpy(newpath + newpath_len, tok, ptr_length+1); } else { memcpy(newpath + newpath_len, tok, ptr_length+1); } newpath_len += ptr_length; } if (ptr == path + path_length) { break; } tok = ++ptr; do { ptr = memchr(ptr, '/', path_length - (ptr - path)); } while (ptr && ptr - tok == 0 && *ptr == '/' && ++ptr && ++tok); if (!ptr && (path_length - (tok - path))) { ptr_length = path_length - (tok - path); ptr = path + path_length; goto last_time; } } efree(path); *new_len = newpath_len; return estrndup(newpath, newpath_len); } /* }}} */ /** * Process a phar stream name, ensuring we can handle any of: * * - whatever.phar * - whatever.phar.gz * - whatever.phar.bz2 * - whatever.phar.php * * Optionally the name might start with 'phar://' * * This is used by phar_parse_url() */ int phar_split_fname(char *filename, int filename_len, char **arch, int *arch_len, char **entry, int *entry_len, int executable, int for_create TSRMLS_DC) /* {{{ */ { const char *ext_str; #ifdef PHP_WIN32 char *save; #endif int ext_len, free_filename = 0; if (!strncasecmp(filename, "phar://", 7)) { filename += 7; filename_len -= 7; } ext_len = 0; #ifdef PHP_WIN32 free_filename = 1; save = filename; filename = estrndup(filename, filename_len); phar_unixify_path_separators(filename, filename_len); #endif if (phar_detect_phar_fname_ext(filename, filename_len, &ext_str, &ext_len, executable, for_create, 0 TSRMLS_CC) == FAILURE) { if (ext_len != -1) { if (!ext_str) { /* no / detected, restore arch for error message */ #ifdef PHP_WIN32 *arch = save; #else *arch = filename; #endif } if (free_filename) { efree(filename); } return FAILURE; } ext_len = 0; /* no extension detected - instead we are dealing with an alias */ } *arch_len = ext_str - filename + ext_len; *arch = estrndup(filename, *arch_len); if (ext_str[ext_len]) { *entry_len = filename_len - *arch_len; *entry = estrndup(ext_str+ext_len, *entry_len); #ifdef PHP_WIN32 phar_unixify_path_separators(*entry, *entry_len); #endif *entry = phar_fix_filepath(*entry, entry_len, 0 TSRMLS_CC); } else { *entry_len = 1; *entry = estrndup("/", 1); } if (free_filename) { efree(filename); } return SUCCESS; } /* }}} */ /** * Invoked when a user calls Phar::mapPhar() from within an executing .phar * to set up its manifest directly */ int phar_open_executed_filename(char *alias, int alias_len, char **error TSRMLS_DC) /* {{{ */ { char *fname; zval *halt_constant; php_stream *fp; int fname_len; char *actual = NULL; int ret; if (error) { *error = NULL; } fname = (char*)zend_get_executed_filename(TSRMLS_C); fname_len = strlen(fname); if (phar_open_parsed_phar(fname, fname_len, alias, alias_len, 0, REPORT_ERRORS, NULL, 0 TSRMLS_CC) == SUCCESS) { return SUCCESS; } if (!strcmp(fname, "[no active file]")) { if (error) { spprintf(error, 0, "cannot initialize a phar outside of PHP execution"); } return FAILURE; } MAKE_STD_ZVAL(halt_constant); if (0 == zend_get_constant("__COMPILER_HALT_OFFSET__", 24, halt_constant TSRMLS_CC)) { FREE_ZVAL(halt_constant); if (error) { spprintf(error, 0, "__HALT_COMPILER(); must be declared in a phar"); } return FAILURE; } FREE_ZVAL(halt_constant); #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { return FAILURE; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { return FAILURE; } fp = php_stream_open_wrapper(fname, "rb", IGNORE_URL|STREAM_MUST_SEEK|REPORT_ERRORS, &actual); if (!fp) { if (error) { spprintf(error, 0, "unable to open phar for reading \"%s\"", fname); } if (actual) { efree(actual); } return FAILURE; } if (actual) { fname = actual; fname_len = strlen(actual); } ret = phar_open_from_fp(fp, fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, 0, error TSRMLS_CC); if (actual) { efree(actual); } return ret; } /* }}} */ /** * Validate the CRC32 of a file opened from within the phar */ int phar_postprocess_file(phar_entry_data *idata, php_uint32 crc32, char **error, int process_zip TSRMLS_DC) /* {{{ */ { php_uint32 crc = ~0; int len = idata->internal_file->uncompressed_filesize; php_stream *fp = idata->fp; phar_entry_info *entry = idata->internal_file; if (error) { *error = NULL; } if (entry->is_zip && process_zip > 0) { /* verify local file header */ phar_zip_file_header local; phar_zip_data_desc desc; if (SUCCESS != phar_open_archive_fp(idata->phar TSRMLS_CC)) { spprintf(error, 0, "phar error: unable to open zip-based phar archive \"%s\" to verify local file header for file \"%s\"", idata->phar->fname, entry->filename); return FAILURE; } php_stream_seek(phar_get_entrypfp(idata->internal_file TSRMLS_CC), entry->header_offset, SEEK_SET); if (sizeof(local) != php_stream_read(phar_get_entrypfp(idata->internal_file TSRMLS_CC), (char *) &local, sizeof(local))) { spprintf(error, 0, "phar error: internal corruption of zip-based phar \"%s\" (cannot read local file header for file \"%s\")", idata->phar->fname, entry->filename); return FAILURE; } /* check for data descriptor */ if (((PHAR_ZIP_16(local.flags)) & 0x8) == 0x8) { php_stream_seek(phar_get_entrypfp(idata->internal_file TSRMLS_CC), entry->header_offset + sizeof(local) + PHAR_ZIP_16(local.filename_len) + PHAR_ZIP_16(local.extra_len) + entry->compressed_filesize, SEEK_SET); if (sizeof(desc) != php_stream_read(phar_get_entrypfp(idata->internal_file TSRMLS_CC), (char *) &desc, sizeof(desc))) { spprintf(error, 0, "phar error: internal corruption of zip-based phar \"%s\" (cannot read local data descriptor for file \"%s\")", idata->phar->fname, entry->filename); return FAILURE; } if (desc.signature[0] == 'P' && desc.signature[1] == 'K') { memcpy(&(local.crc32), &(desc.crc32), 12); } else { /* old data descriptors have no signature */ memcpy(&(local.crc32), &desc, 12); } } /* verify local header */ if (entry->filename_len != PHAR_ZIP_16(local.filename_len) || entry->crc32 != PHAR_ZIP_32(local.crc32) || entry->uncompressed_filesize != PHAR_ZIP_32(local.uncompsize) || entry->compressed_filesize != PHAR_ZIP_32(local.compsize)) { spprintf(error, 0, "phar error: internal corruption of zip-based phar \"%s\" (local header of file \"%s\" does not match central directory)", idata->phar->fname, entry->filename); return FAILURE; } /* construct actual offset to file start - local extra_len can be different from central extra_len */ entry->offset = entry->offset_abs = sizeof(local) + entry->header_offset + PHAR_ZIP_16(local.filename_len) + PHAR_ZIP_16(local.extra_len); if (idata->zero && idata->zero != entry->offset_abs) { idata->zero = entry->offset_abs; } } if (process_zip == 1) { return SUCCESS; } php_stream_seek(fp, idata->zero, SEEK_SET); while (len--) { CRC32(crc, php_stream_getc(fp)); } php_stream_seek(fp, idata->zero, SEEK_SET); if (~crc == crc32) { entry->is_crc_checked = 1; return SUCCESS; } else { spprintf(error, 0, "phar error: internal corruption of phar \"%s\" (crc32 mismatch on file \"%s\")", idata->phar->fname, entry->filename); return FAILURE; } } /* }}} */ static inline void phar_set_32(char *buffer, int var) /* {{{ */ { #ifdef WORDS_BIGENDIAN *((buffer) + 3) = (unsigned char) (((var) >> 24) & 0xFF); *((buffer) + 2) = (unsigned char) (((var) >> 16) & 0xFF); *((buffer) + 1) = (unsigned char) (((var) >> 8) & 0xFF); *((buffer) + 0) = (unsigned char) ((var) & 0xFF); #else memcpy(buffer, &var, sizeof(var)); #endif } /* }}} */ static int phar_flush_clean_deleted_apply(void *data TSRMLS_DC) /* {{{ */ { phar_entry_info *entry = (phar_entry_info *)data; if (entry->fp_refcount <= 0 && entry->is_deleted) { return ZEND_HASH_APPLY_REMOVE; } else { return ZEND_HASH_APPLY_KEEP; } } /* }}} */ #include "stub.h" char *phar_create_default_stub(const char *index_php, const char *web_index, size_t *len, char **error TSRMLS_DC) /* {{{ */ { char *stub = NULL; int index_len, web_len; size_t dummy; if (!len) { len = &dummy; } if (error) { *error = NULL; } if (!index_php) { index_php = "index.php"; } if (!web_index) { web_index = "index.php"; } index_len = strlen(index_php); web_len = strlen(web_index); if (index_len > 400) { /* ridiculous size not allowed for index.php startup filename */ if (error) { spprintf(error, 0, "Illegal filename passed in for stub creation, was %d characters long, and only 400 or less is allowed", index_len); return NULL; } } if (web_len > 400) { /* ridiculous size not allowed for index.php startup filename */ if (error) { spprintf(error, 0, "Illegal web filename passed in for stub creation, was %d characters long, and only 400 or less is allowed", web_len); return NULL; } } phar_get_stub(index_php, web_index, len, &stub, index_len+1, web_len+1 TSRMLS_CC); return stub; } /* }}} */ /** * Save phar contents to disk * * user_stub contains either a string, or a resource pointer, if len is a negative length. * user_stub and len should be both 0 if the default or existing stub should be used */ int phar_flush(phar_archive_data *phar, char *user_stub, long len, int convert, char **error TSRMLS_DC) /* {{{ */ { char halt_stub[] = "__HALT_COMPILER();"; char *newstub, *tmp; phar_entry_info *entry, *newentry; int halt_offset, restore_alias_len, global_flags = 0, closeoldfile; char *pos, has_dirs = 0; char manifest[18], entry_buffer[24]; off_t manifest_ftell; long offset; size_t wrote; php_uint32 manifest_len, mytime, loc, new_manifest_count; php_uint32 newcrc32; php_stream *file, *oldfile, *newfile, *stubfile; php_stream_filter *filter; php_serialize_data_t metadata_hash; smart_str main_metadata_str = {0}; int free_user_stub, free_fp = 1, free_ufp = 1; if (phar->is_persistent) { if (error) { spprintf(error, 0, "internal error: attempt to flush cached zip-based phar \"%s\"", phar->fname); } return EOF; } if (error) { *error = NULL; } if (!zend_hash_num_elements(&phar->manifest) && !user_stub) { return EOF; } zend_hash_clean(&phar->virtual_dirs); if (phar->is_zip) { return phar_zip_flush(phar, user_stub, len, convert, error TSRMLS_CC); } if (phar->is_tar) { return phar_tar_flush(phar, user_stub, len, convert, error TSRMLS_CC); } if (PHAR_G(readonly)) { return EOF; } if (phar->fp && !phar->is_brandnew) { oldfile = phar->fp; closeoldfile = 0; php_stream_rewind(oldfile); } else { oldfile = php_stream_open_wrapper(phar->fname, "rb", 0, NULL); closeoldfile = oldfile != NULL; } newfile = php_stream_fopen_tmpfile(); if (!newfile) { if (error) { spprintf(error, 0, "unable to create temporary file"); } if (closeoldfile) { php_stream_close(oldfile); } return EOF; } if (user_stub) { if (len < 0) { /* resource passed in */ if (!(php_stream_from_zval_no_verify(stubfile, (zval **)user_stub))) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to access resource to copy stub to new phar \"%s\"", phar->fname); } return EOF; } if (len == -1) { len = PHP_STREAM_COPY_ALL; } else { len = -len; } user_stub = 0; #if PHP_MAJOR_VERSION >= 6 if (!(len = php_stream_copy_to_mem(stubfile, (void **) &user_stub, len, 0)) || !user_stub) { #else if (!(len = php_stream_copy_to_mem(stubfile, &user_stub, len, 0)) || !user_stub) { #endif if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to read resource to copy stub to new phar \"%s\"", phar->fname); } return EOF; } free_user_stub = 1; } else { free_user_stub = 0; } tmp = estrndup(user_stub, len); if ((pos = php_stristr(tmp, halt_stub, len, sizeof(halt_stub) - 1)) == NULL) { efree(tmp); if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "illegal stub for phar \"%s\"", phar->fname); } if (free_user_stub) { efree(user_stub); } return EOF; } pos = user_stub + (pos - tmp); efree(tmp); len = pos - user_stub + 18; if ((size_t)len != php_stream_write(newfile, user_stub, len) || 5 != php_stream_write(newfile, " ?>\r\n", 5)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to create stub from string in new phar \"%s\"", phar->fname); } if (free_user_stub) { efree(user_stub); } return EOF; } phar->halt_offset = len + 5; if (free_user_stub) { efree(user_stub); } } else { size_t written; if (!user_stub && phar->halt_offset && oldfile && !phar->is_brandnew) { phar_stream_copy_to_stream(oldfile, newfile, phar->halt_offset, &written); newstub = NULL; } else { /* this is either a brand new phar or a default stub overwrite */ newstub = phar_create_default_stub(NULL, NULL, &(phar->halt_offset), NULL TSRMLS_CC); written = php_stream_write(newfile, newstub, phar->halt_offset); } if (phar->halt_offset != written) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { if (newstub) { spprintf(error, 0, "unable to create stub in new phar \"%s\"", phar->fname); } else { spprintf(error, 0, "unable to copy stub of old phar to new phar \"%s\"", phar->fname); } } if (newstub) { efree(newstub); } return EOF; } if (newstub) { efree(newstub); } } manifest_ftell = php_stream_tell(newfile); halt_offset = manifest_ftell; /* Check whether we can get rid of some of the deleted entries which are * unused. However some might still be in use so even after this clean-up * we need to skip entries marked is_deleted. */ zend_hash_apply(&phar->manifest, phar_flush_clean_deleted_apply TSRMLS_CC); /* compress as necessary, calculate crcs, serialize meta-data, manifest size, and file sizes */ main_metadata_str.c = 0; if (phar->metadata) { PHP_VAR_SERIALIZE_INIT(metadata_hash); php_var_serialize(&main_metadata_str, &phar->metadata, &metadata_hash TSRMLS_CC); PHP_VAR_SERIALIZE_DESTROY(metadata_hash); } else { main_metadata_str.len = 0; } new_manifest_count = 0; offset = 0; for (zend_hash_internal_pointer_reset(&phar->manifest); zend_hash_has_more_elements(&phar->manifest) == SUCCESS; zend_hash_move_forward(&phar->manifest)) { if (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) { continue; } if (entry->cfp) { /* did we forget to get rid of cfp last time? */ php_stream_close(entry->cfp); entry->cfp = 0; } if (entry->is_deleted || entry->is_mounted) { /* remove this from the new phar */ continue; } if (!entry->is_modified && entry->fp_refcount) { /* open file pointers refer to this fp, do not free the stream */ switch (entry->fp_type) { case PHAR_FP: free_fp = 0; break; case PHAR_UFP: free_ufp = 0; default: break; } } /* after excluding deleted files, calculate manifest size in bytes and number of entries */ ++new_manifest_count; phar_add_virtual_dirs(phar, entry->filename, entry->filename_len TSRMLS_CC); if (entry->is_dir) { /* we use this to calculate API version, 1.1.1 is used for phars with directories */ has_dirs = 1; } if (entry->metadata) { if (entry->metadata_str.c) { smart_str_free(&entry->metadata_str); } entry->metadata_str.c = 0; entry->metadata_str.len = 0; PHP_VAR_SERIALIZE_INIT(metadata_hash); php_var_serialize(&entry->metadata_str, &entry->metadata, &metadata_hash TSRMLS_CC); PHP_VAR_SERIALIZE_DESTROY(metadata_hash); } else { if (entry->metadata_str.c) { smart_str_free(&entry->metadata_str); } entry->metadata_str.c = 0; entry->metadata_str.len = 0; } /* 32 bits for filename length, length of filename, manifest + metadata, and add 1 for trailing / if a directory */ offset += 4 + entry->filename_len + sizeof(entry_buffer) + entry->metadata_str.len + (entry->is_dir ? 1 : 0); /* compress and rehash as necessary */ if ((oldfile && !entry->is_modified) || entry->is_dir) { if (entry->fp_type == PHAR_UFP) { /* reset so we can copy the compressed data over */ entry->fp_type = PHAR_FP; } continue; } if (!phar_get_efp(entry, 0 TSRMLS_CC)) { /* re-open internal file pointer just-in-time */ newentry = phar_open_jit(phar, entry, error TSRMLS_CC); if (!newentry) { /* major problem re-opening, so we ignore this file and the error */ efree(*error); *error = NULL; continue; } entry = newentry; } file = phar_get_efp(entry, 0 TSRMLS_CC); if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 1 TSRMLS_CC)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } newcrc32 = ~0; mytime = entry->uncompressed_filesize; for (loc = 0;loc < mytime; ++loc) { CRC32(newcrc32, php_stream_getc(file)); } entry->crc32 = ~newcrc32; entry->is_crc_checked = 1; if (!(entry->flags & PHAR_ENT_COMPRESSION_MASK)) { /* not compressed */ entry->compressed_filesize = entry->uncompressed_filesize; continue; } filter = php_stream_filter_create(phar_compress_filter(entry, 0), NULL, 0 TSRMLS_CC); if (!filter) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (entry->flags & PHAR_ENT_COMPRESSED_GZ) { if (error) { spprintf(error, 0, "unable to gzip compress file \"%s\" to new phar \"%s\"", entry->filename, phar->fname); } } else { if (error) { spprintf(error, 0, "unable to bzip2 compress file \"%s\" to new phar \"%s\"", entry->filename, phar->fname); } } return EOF; } /* create new file that holds the compressed version */ /* work around inability to specify freedom in write and strictness in read count */ entry->cfp = php_stream_fopen_tmpfile(); if (!entry->cfp) { if (error) { spprintf(error, 0, "unable to create temporary file"); } if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); return EOF; } php_stream_flush(file); if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 0 TSRMLS_CC)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } php_stream_filter_append((&entry->cfp->writefilters), filter); if (SUCCESS != phar_stream_copy_to_stream(file, entry->cfp, entry->uncompressed_filesize, NULL)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to copy compressed file contents of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } php_stream_filter_flush(filter, 1); php_stream_flush(entry->cfp); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_seek(entry->cfp, 0, SEEK_END); entry->compressed_filesize = (php_uint32) php_stream_tell(entry->cfp); /* generate crc on compressed file */ php_stream_rewind(entry->cfp); entry->old_flags = entry->flags; entry->is_modified = 1; global_flags |= (entry->flags & PHAR_ENT_COMPRESSION_MASK); } global_flags |= PHAR_HDR_SIGNATURE; /* write out manifest pre-header */ /* 4: manifest length * 4: manifest entry count * 2: phar version * 4: phar global flags * 4: alias length * ?: the alias itself * 4: phar metadata length * ?: phar metadata */ restore_alias_len = phar->alias_len; if (phar->is_temporary_alias) { phar->alias_len = 0; } manifest_len = offset + phar->alias_len + sizeof(manifest) + main_metadata_str.len; phar_set_32(manifest, manifest_len); phar_set_32(manifest+4, new_manifest_count); if (has_dirs) { *(manifest + 8) = (unsigned char) (((PHAR_API_VERSION) >> 8) & 0xFF); *(manifest + 9) = (unsigned char) (((PHAR_API_VERSION) & 0xF0)); } else { *(manifest + 8) = (unsigned char) (((PHAR_API_VERSION_NODIR) >> 8) & 0xFF); *(manifest + 9) = (unsigned char) (((PHAR_API_VERSION_NODIR) & 0xF0)); } phar_set_32(manifest+10, global_flags); phar_set_32(manifest+14, phar->alias_len); /* write the manifest header */ if (sizeof(manifest) != php_stream_write(newfile, manifest, sizeof(manifest)) || (size_t)phar->alias_len != php_stream_write(newfile, phar->alias, phar->alias_len)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); phar->alias_len = restore_alias_len; if (error) { spprintf(error, 0, "unable to write manifest header of new phar \"%s\"", phar->fname); } return EOF; } phar->alias_len = restore_alias_len; phar_set_32(manifest, main_metadata_str.len); if (4 != php_stream_write(newfile, manifest, 4) || (main_metadata_str.len && main_metadata_str.len != php_stream_write(newfile, main_metadata_str.c, main_metadata_str.len))) { smart_str_free(&main_metadata_str); if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); phar->alias_len = restore_alias_len; if (error) { spprintf(error, 0, "unable to write manifest meta-data of new phar \"%s\"", phar->fname); } return EOF; } smart_str_free(&main_metadata_str); /* re-calculate the manifest location to simplify later code */ manifest_ftell = php_stream_tell(newfile); /* now write the manifest */ for (zend_hash_internal_pointer_reset(&phar->manifest); zend_hash_has_more_elements(&phar->manifest) == SUCCESS; zend_hash_move_forward(&phar->manifest)) { if (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) { continue; } if (entry->is_deleted || entry->is_mounted) { /* remove this from the new phar if deleted, ignore if mounted */ continue; } if (entry->is_dir) { /* add 1 for trailing slash */ phar_set_32(entry_buffer, entry->filename_len + 1); } else { phar_set_32(entry_buffer, entry->filename_len); } if (4 != php_stream_write(newfile, entry_buffer, 4) || entry->filename_len != php_stream_write(newfile, entry->filename, entry->filename_len) || (entry->is_dir && 1 != php_stream_write(newfile, "/", 1))) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { if (entry->is_dir) { spprintf(error, 0, "unable to write filename of directory \"%s\" to manifest of new phar \"%s\"", entry->filename, phar->fname); } else { spprintf(error, 0, "unable to write filename of file \"%s\" to manifest of new phar \"%s\"", entry->filename, phar->fname); } } return EOF; } /* set the manifest meta-data: 4: uncompressed filesize 4: creation timestamp 4: compressed filesize 4: crc32 4: flags 4: metadata-len +: metadata */ mytime = time(NULL); phar_set_32(entry_buffer, entry->uncompressed_filesize); phar_set_32(entry_buffer+4, mytime); phar_set_32(entry_buffer+8, entry->compressed_filesize); phar_set_32(entry_buffer+12, entry->crc32); phar_set_32(entry_buffer+16, entry->flags); phar_set_32(entry_buffer+20, entry->metadata_str.len); if (sizeof(entry_buffer) != php_stream_write(newfile, entry_buffer, sizeof(entry_buffer)) || entry->metadata_str.len != php_stream_write(newfile, entry->metadata_str.c, entry->metadata_str.len)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to write temporary manifest of file \"%s\" to manifest of new phar \"%s\"", entry->filename, phar->fname); } return EOF; } } /* now copy the actual file data to the new phar */ offset = php_stream_tell(newfile); for (zend_hash_internal_pointer_reset(&phar->manifest); zend_hash_has_more_elements(&phar->manifest) == SUCCESS; zend_hash_move_forward(&phar->manifest)) { if (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) { continue; } if (entry->is_deleted || entry->is_dir || entry->is_mounted) { continue; } if (entry->cfp) { file = entry->cfp; php_stream_rewind(file); } else { file = phar_get_efp(entry, 0 TSRMLS_CC); if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 0 TSRMLS_CC)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } } if (!file) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } /* this will have changed for all files that have either changed compression or been modified */ entry->offset = entry->offset_abs = offset; offset += entry->compressed_filesize; if (phar_stream_copy_to_stream(file, newfile, entry->compressed_filesize, &wrote) == FAILURE) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to write contents of file \"%s\" to new phar \"%s\"", entry->filename, phar->fname); } return EOF; } entry->is_modified = 0; if (entry->cfp) { php_stream_close(entry->cfp); entry->cfp = NULL; } if (entry->fp_type == PHAR_MOD) { /* this fp is in use by a phar_entry_data returned by phar_get_entry_data, it will be closed when the phar_entry_data is phar_entry_delref'ed */ if (entry->fp_refcount == 0 && entry->fp != phar->fp && entry->fp != phar->ufp) { php_stream_close(entry->fp); } entry->fp = NULL; entry->fp_type = PHAR_FP; } else if (entry->fp_type == PHAR_UFP) { entry->fp_type = PHAR_FP; } } /* append signature */ if (global_flags & PHAR_HDR_SIGNATURE) { char sig_buf[4]; php_stream_rewind(newfile); if (phar->signature) { efree(phar->signature); phar->signature = NULL; } switch(phar->sig_flags) { #ifndef PHAR_HASH_OK case PHAR_SIG_SHA512: case PHAR_SIG_SHA256: if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to write contents of file \"%s\" to new phar \"%s\" with requested hash type", entry->filename, phar->fname); } return EOF; #endif default: { char *digest = NULL; int digest_len; if (FAILURE == phar_create_signature(phar, newfile, &digest, &digest_len, error TSRMLS_CC)) { if (error) { char *save = *error; spprintf(error, 0, "phar error: unable to write signature: %s", save); efree(save); } if (digest) { efree(digest); } if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); return EOF; } php_stream_write(newfile, digest, digest_len); efree(digest); if (phar->sig_flags == PHAR_SIG_OPENSSL) { phar_set_32(sig_buf, digest_len); php_stream_write(newfile, sig_buf, 4); } break; } } phar_set_32(sig_buf, phar->sig_flags); php_stream_write(newfile, sig_buf, 4); php_stream_write(newfile, "GBMB", 4); } /* finally, close the temp file, rename the original phar, move the temp to the old phar, unlink the old phar, and reload it into memory */ if (phar->fp && free_fp) { php_stream_close(phar->fp); } if (phar->ufp) { if (free_ufp) { php_stream_close(phar->ufp); } phar->ufp = NULL; } if (closeoldfile) { php_stream_close(oldfile); } phar->internal_file_start = halt_offset + manifest_len + 4; phar->halt_offset = halt_offset; phar->is_brandnew = 0; php_stream_rewind(newfile); if (phar->donotflush) { /* deferred flush */ phar->fp = newfile; } else { phar->fp = php_stream_open_wrapper(phar->fname, "w+b", IGNORE_URL|STREAM_MUST_SEEK|REPORT_ERRORS, NULL); if (!phar->fp) { phar->fp = newfile; if (error) { spprintf(error, 4096, "unable to open new phar \"%s\" for writing", phar->fname); } return EOF; } if (phar->flags & PHAR_FILE_COMPRESSED_GZ) { /* to properly compress, we have to tell zlib to add a zlib header */ zval filterparams; array_init(&filterparams); add_assoc_long(&filterparams, "window", MAX_WBITS+16); filter = php_stream_filter_create("zlib.deflate", &filterparams, php_stream_is_persistent(phar->fp) TSRMLS_CC); zval_dtor(&filterparams); if (!filter) { if (error) { spprintf(error, 4096, "unable to compress all contents of phar \"%s\" using zlib, PHP versions older than 5.2.6 have a buggy zlib", phar->fname); } return EOF; } php_stream_filter_append(&phar->fp->writefilters, filter); phar_stream_copy_to_stream(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL); php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(phar->fp); /* use the temp stream as our base */ phar->fp = newfile; } else if (phar->flags & PHAR_FILE_COMPRESSED_BZ2) { filter = php_stream_filter_create("bzip2.compress", NULL, php_stream_is_persistent(phar->fp) TSRMLS_CC); php_stream_filter_append(&phar->fp->writefilters, filter); phar_stream_copy_to_stream(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL); php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(phar->fp); /* use the temp stream as our base */ phar->fp = newfile; } else { phar_stream_copy_to_stream(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL); /* we could also reopen the file in "rb" mode but there is no need for that */ php_stream_close(newfile); } } if (-1 == php_stream_seek(phar->fp, phar->halt_offset, SEEK_SET)) { if (error) { spprintf(error, 0, "unable to seek to __HALT_COMPILER(); in new phar \"%s\"", phar->fname); } return EOF; } return EOF; } /* }}} */ #ifdef COMPILE_DL_PHAR ZEND_GET_MODULE(phar) #endif /* {{{ phar_functions[] * * Every user visible function must have an entry in phar_functions[]. */ zend_function_entry phar_functions[] = { PHP_FE_END }; /* }}}*/ static size_t phar_zend_stream_reader(void *handle, char *buf, size_t len TSRMLS_DC) /* {{{ */ { return php_stream_read(phar_get_pharfp((phar_archive_data*)handle TSRMLS_CC), buf, len); } /* }}} */ #if PHP_VERSION_ID >= 50300 static size_t phar_zend_stream_fsizer(void *handle TSRMLS_DC) /* {{{ */ { return ((phar_archive_data*)handle)->halt_offset + 32; } /* }}} */ #else /* PHP_VERSION_ID */ static long phar_stream_fteller_for_zend(void *handle TSRMLS_DC) /* {{{ */ { return (long)php_stream_tell(phar_get_pharfp((phar_archive_data*)handle TSRMLS_CC)); } /* }}} */ #endif zend_op_array *(*phar_orig_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); #if PHP_VERSION_ID >= 50300 #define phar_orig_zend_open zend_stream_open_function static char *phar_resolve_path(const char *filename, int filename_len TSRMLS_DC) { return phar_find_in_include_path((char *) filename, filename_len, NULL TSRMLS_CC); } #else int (*phar_orig_zend_open)(const char *filename, zend_file_handle *handle TSRMLS_DC); #endif static zend_op_array *phar_compile_file(zend_file_handle *file_handle, int type TSRMLS_DC) /* {{{ */ { zend_op_array *res; char *name = NULL; int failed; phar_archive_data *phar; if (!file_handle || !file_handle->filename) { return phar_orig_compile_file(file_handle, type TSRMLS_CC); } if (strstr(file_handle->filename, ".phar") && !strstr(file_handle->filename, "://")) { if (SUCCESS == phar_open_from_filename((char*)file_handle->filename, strlen(file_handle->filename), NULL, 0, 0, &phar, NULL TSRMLS_CC)) { if (phar->is_zip || phar->is_tar) { zend_file_handle f = *file_handle; /* zip or tar-based phar */ spprintf(&name, 4096, "phar://%s/%s", file_handle->filename, ".phar/stub.php"); if (SUCCESS == phar_orig_zend_open((const char *)name, file_handle TSRMLS_CC)) { efree(name); name = NULL; file_handle->filename = f.filename; if (file_handle->opened_path) { efree(file_handle->opened_path); } file_handle->opened_path = f.opened_path; file_handle->free_filename = f.free_filename; } else { *file_handle = f; } } else if (phar->flags & PHAR_FILE_COMPRESSION_MASK) { /* compressed phar */ #if PHP_VERSION_ID >= 50300 file_handle->type = ZEND_HANDLE_STREAM; /* we do our own reading directly from the phar, don't change the next line */ file_handle->handle.stream.handle = phar; file_handle->handle.stream.reader = phar_zend_stream_reader; file_handle->handle.stream.closer = NULL; file_handle->handle.stream.fsizer = phar_zend_stream_fsizer; file_handle->handle.stream.isatty = 0; phar->is_persistent ? php_stream_rewind(PHAR_GLOBALS->cached_fp[phar->phar_pos].fp) : php_stream_rewind(phar->fp); memset(&file_handle->handle.stream.mmap, 0, sizeof(file_handle->handle.stream.mmap)); #else /* PHP_VERSION_ID */ file_handle->type = ZEND_HANDLE_STREAM; /* we do our own reading directly from the phar, don't change the next line */ file_handle->handle.stream.handle = phar; file_handle->handle.stream.reader = phar_zend_stream_reader; file_handle->handle.stream.closer = NULL; /* don't close - let phar handle this one */ file_handle->handle.stream.fteller = phar_stream_fteller_for_zend; file_handle->handle.stream.interactive = 0; phar->is_persistent ? php_stream_rewind(PHAR_GLOBALS->cached_fp[phar->phar_pos].fp) : php_stream_rewind(phar->fp); #endif } } } zend_try { failed = 0; res = phar_orig_compile_file(file_handle, type TSRMLS_CC); } zend_catch { failed = 1; res = NULL; } zend_end_try(); if (name) { efree(name); } if (failed) { zend_bailout(); } return res; } /* }}} */ #if PHP_VERSION_ID < 50300 int phar_zend_open(const char *filename, zend_file_handle *handle TSRMLS_DC) /* {{{ */ { char *arch, *entry; int arch_len, entry_len; /* this code is obsoleted in php 5.3 */ entry = (char *) filename; if (!IS_ABSOLUTE_PATH(entry, strlen(entry)) && !strstr(entry, "://")) { phar_archive_data **pphar = NULL; char *fname; int fname_len; fname = (char*)zend_get_executed_filename(TSRMLS_C); fname_len = strlen(fname); if (fname_len > 7 && !strncasecmp(fname, "phar://", 7)) { if (SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 1, 0 TSRMLS_CC)) { zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), arch, arch_len, (void **) &pphar); if (!pphar && PHAR_G(manifest_cached)) { zend_hash_find(&cached_phars, arch, arch_len, (void **) &pphar); } efree(arch); efree(entry); } } /* retrieving an include within the current directory, so use this if possible */ if (!(entry = phar_find_in_include_path((char *) filename, strlen(filename), NULL TSRMLS_CC))) { /* this file is not in the phar, use the original path */ goto skip_phar; } if (SUCCESS == phar_orig_zend_open(entry, handle TSRMLS_CC)) { if (!handle->opened_path) { handle->opened_path = entry; } if (entry != filename) { handle->free_filename = 1; } return SUCCESS; } if (entry != filename) { efree(entry); } return FAILURE; } skip_phar: return phar_orig_zend_open(filename, handle TSRMLS_CC); } /* }}} */ #endif typedef zend_op_array* (zend_compile_t)(zend_file_handle*, int TSRMLS_DC); typedef zend_compile_t* (compile_hook)(zend_compile_t *ptr); PHP_GINIT_FUNCTION(phar) /* {{{ */ { phar_mime_type mime; memset(phar_globals, 0, sizeof(zend_phar_globals)); phar_globals->readonly = 1; zend_hash_init(&phar_globals->mime_types, 0, NULL, NULL, 1); #define PHAR_SET_MIME(mimetype, ret, fileext) \ mime.mime = mimetype; \ mime.len = sizeof((mimetype))+1; \ mime.type = ret; \ zend_hash_add(&phar_globals->mime_types, fileext, sizeof(fileext)-1, (void *)&mime, sizeof(phar_mime_type), NULL); \ PHAR_SET_MIME("text/html", PHAR_MIME_PHPS, "phps") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "c") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "cc") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "cpp") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "c++") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "dtd") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "h") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "log") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "rng") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "txt") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "xsd") PHAR_SET_MIME("", PHAR_MIME_PHP, "php") PHAR_SET_MIME("", PHAR_MIME_PHP, "inc") PHAR_SET_MIME("video/avi", PHAR_MIME_OTHER, "avi") PHAR_SET_MIME("image/bmp", PHAR_MIME_OTHER, "bmp") PHAR_SET_MIME("text/css", PHAR_MIME_OTHER, "css") PHAR_SET_MIME("image/gif", PHAR_MIME_OTHER, "gif") PHAR_SET_MIME("text/html", PHAR_MIME_OTHER, "htm") PHAR_SET_MIME("text/html", PHAR_MIME_OTHER, "html") PHAR_SET_MIME("text/html", PHAR_MIME_OTHER, "htmls") PHAR_SET_MIME("image/x-ico", PHAR_MIME_OTHER, "ico") PHAR_SET_MIME("image/jpeg", PHAR_MIME_OTHER, "jpe") PHAR_SET_MIME("image/jpeg", PHAR_MIME_OTHER, "jpg") PHAR_SET_MIME("image/jpeg", PHAR_MIME_OTHER, "jpeg") PHAR_SET_MIME("application/x-javascript", PHAR_MIME_OTHER, "js") PHAR_SET_MIME("audio/midi", PHAR_MIME_OTHER, "midi") PHAR_SET_MIME("audio/midi", PHAR_MIME_OTHER, "mid") PHAR_SET_MIME("audio/mod", PHAR_MIME_OTHER, "mod") PHAR_SET_MIME("movie/quicktime", PHAR_MIME_OTHER, "mov") PHAR_SET_MIME("audio/mp3", PHAR_MIME_OTHER, "mp3") PHAR_SET_MIME("video/mpeg", PHAR_MIME_OTHER, "mpg") PHAR_SET_MIME("video/mpeg", PHAR_MIME_OTHER, "mpeg") PHAR_SET_MIME("application/pdf", PHAR_MIME_OTHER, "pdf") PHAR_SET_MIME("image/png", PHAR_MIME_OTHER, "png") PHAR_SET_MIME("application/shockwave-flash", PHAR_MIME_OTHER, "swf") PHAR_SET_MIME("image/tiff", PHAR_MIME_OTHER, "tif") PHAR_SET_MIME("image/tiff", PHAR_MIME_OTHER, "tiff") PHAR_SET_MIME("audio/wav", PHAR_MIME_OTHER, "wav") PHAR_SET_MIME("image/xbm", PHAR_MIME_OTHER, "xbm") PHAR_SET_MIME("text/xml", PHAR_MIME_OTHER, "xml") phar_restore_orig_functions(TSRMLS_C); } /* }}} */ PHP_GSHUTDOWN_FUNCTION(phar) /* {{{ */ { zend_hash_destroy(&phar_globals->mime_types); } /* }}} */ PHP_MINIT_FUNCTION(phar) /* {{{ */ { REGISTER_INI_ENTRIES(); phar_orig_compile_file = zend_compile_file; zend_compile_file = phar_compile_file; #if PHP_VERSION_ID >= 50300 phar_save_resolve_path = zend_resolve_path; zend_resolve_path = phar_resolve_path; #else phar_orig_zend_open = zend_stream_open_function; zend_stream_open_function = phar_zend_open; #endif phar_object_init(TSRMLS_C); phar_intercept_functions_init(TSRMLS_C); phar_save_orig_functions(TSRMLS_C); return php_register_url_stream_wrapper("phar", &php_stream_phar_wrapper TSRMLS_CC); } /* }}} */ PHP_MSHUTDOWN_FUNCTION(phar) /* {{{ */ { php_unregister_url_stream_wrapper("phar" TSRMLS_CC); phar_intercept_functions_shutdown(TSRMLS_C); if (zend_compile_file == phar_compile_file) { zend_compile_file = phar_orig_compile_file; } #if PHP_VERSION_ID < 50300 if (zend_stream_open_function == phar_zend_open) { zend_stream_open_function = phar_orig_zend_open; } #endif if (PHAR_G(manifest_cached)) { zend_hash_destroy(&(cached_phars)); zend_hash_destroy(&(cached_alias)); } return SUCCESS; } /* }}} */ void phar_request_initialize(TSRMLS_D) /* {{{ */ { if (!PHAR_GLOBALS->request_init) { PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; PHAR_G(has_bz2) = zend_hash_exists(&module_registry, "bz2", sizeof("bz2")); PHAR_G(has_zlib) = zend_hash_exists(&module_registry, "zlib", sizeof("zlib")); PHAR_GLOBALS->request_init = 1; PHAR_GLOBALS->request_ends = 0; PHAR_GLOBALS->request_done = 0; zend_hash_init(&(PHAR_GLOBALS->phar_fname_map), 5, zend_get_hash_value, destroy_phar_data, 0); zend_hash_init(&(PHAR_GLOBALS->phar_persist_map), 5, zend_get_hash_value, NULL, 0); zend_hash_init(&(PHAR_GLOBALS->phar_alias_map), 5, zend_get_hash_value, NULL, 0); if (PHAR_G(manifest_cached)) { phar_archive_data **pphar; phar_entry_fp *stuff = (phar_entry_fp *) ecalloc(zend_hash_num_elements(&cached_phars), sizeof(phar_entry_fp)); for (zend_hash_internal_pointer_reset(&cached_phars); zend_hash_get_current_data(&cached_phars, (void **)&pphar) == SUCCESS; zend_hash_move_forward(&cached_phars)) { stuff[pphar[0]->phar_pos].manifest = (phar_entry_fp_info *) ecalloc( zend_hash_num_elements(&(pphar[0]->manifest)), sizeof(phar_entry_fp_info)); } PHAR_GLOBALS->cached_fp = stuff; } PHAR_GLOBALS->phar_SERVER_mung_list = 0; PHAR_G(cwd) = NULL; PHAR_G(cwd_len) = 0; PHAR_G(cwd_init) = 0; } } /* }}} */ PHP_RSHUTDOWN_FUNCTION(phar) /* {{{ */ { int i; PHAR_GLOBALS->request_ends = 1; if (PHAR_GLOBALS->request_init) { phar_release_functions(TSRMLS_C); zend_hash_destroy(&(PHAR_GLOBALS->phar_alias_map)); PHAR_GLOBALS->phar_alias_map.arBuckets = NULL; zend_hash_destroy(&(PHAR_GLOBALS->phar_fname_map)); PHAR_GLOBALS->phar_fname_map.arBuckets = NULL; zend_hash_destroy(&(PHAR_GLOBALS->phar_persist_map)); PHAR_GLOBALS->phar_persist_map.arBuckets = NULL; PHAR_GLOBALS->phar_SERVER_mung_list = 0; if (PHAR_GLOBALS->cached_fp) { for (i = 0; i < zend_hash_num_elements(&cached_phars); ++i) { if (PHAR_GLOBALS->cached_fp[i].fp) { php_stream_close(PHAR_GLOBALS->cached_fp[i].fp); } if (PHAR_GLOBALS->cached_fp[i].ufp) { php_stream_close(PHAR_GLOBALS->cached_fp[i].ufp); } efree(PHAR_GLOBALS->cached_fp[i].manifest); } efree(PHAR_GLOBALS->cached_fp); PHAR_GLOBALS->cached_fp = 0; } PHAR_GLOBALS->request_init = 0; if (PHAR_G(cwd)) { efree(PHAR_G(cwd)); } PHAR_G(cwd) = NULL; PHAR_G(cwd_len) = 0; PHAR_G(cwd_init) = 0; } PHAR_GLOBALS->request_done = 1; return SUCCESS; } /* }}} */ PHP_MINFO_FUNCTION(phar) /* {{{ */ { phar_request_initialize(TSRMLS_C); php_info_print_table_start(); php_info_print_table_header(2, "Phar: PHP Archive support", "enabled"); php_info_print_table_row(2, "Phar EXT version", PHP_PHAR_VERSION); php_info_print_table_row(2, "Phar API version", PHP_PHAR_API_VERSION); php_info_print_table_row(2, "SVN revision", "$Revision$"); php_info_print_table_row(2, "Phar-based phar archives", "enabled"); php_info_print_table_row(2, "Tar-based phar archives", "enabled"); php_info_print_table_row(2, "ZIP-based phar archives", "enabled"); if (PHAR_G(has_zlib)) { php_info_print_table_row(2, "gzip compression", "enabled"); } else { php_info_print_table_row(2, "gzip compression", "disabled (install ext/zlib)"); } if (PHAR_G(has_bz2)) { php_info_print_table_row(2, "bzip2 compression", "enabled"); } else { php_info_print_table_row(2, "bzip2 compression", "disabled (install pecl/bz2)"); } #ifdef PHAR_HAVE_OPENSSL php_info_print_table_row(2, "Native OpenSSL support", "enabled"); #else if (zend_hash_exists(&module_registry, "openssl", sizeof("openssl"))) { php_info_print_table_row(2, "OpenSSL support", "enabled"); } else { php_info_print_table_row(2, "OpenSSL support", "disabled (install ext/openssl)"); } #endif php_info_print_table_end(); php_info_print_box_start(0); PUTS("Phar based on pear/PHP_Archive, original concept by Davey Shafik."); PUTS(!sapi_module.phpinfo_as_text?"<br />":"\n"); PUTS("Phar fully realized by Gregory Beaver and Marcus Boerger."); PUTS(!sapi_module.phpinfo_as_text?"<br />":"\n"); PUTS("Portions of tar implementation Copyright (c) 2003-2009 Tim Kientzle."); php_info_print_box_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ /* {{{ phar_module_entry */ static const zend_module_dep phar_deps[] = { ZEND_MOD_OPTIONAL("apc") ZEND_MOD_OPTIONAL("bz2") ZEND_MOD_OPTIONAL("openssl") ZEND_MOD_OPTIONAL("zlib") ZEND_MOD_OPTIONAL("standard") #if defined(HAVE_HASH) && !defined(COMPILE_DL_HASH) ZEND_MOD_REQUIRED("hash") #endif #if HAVE_SPL ZEND_MOD_REQUIRED("spl") #endif ZEND_MOD_END }; zend_module_entry phar_module_entry = { STANDARD_MODULE_HEADER_EX, NULL, phar_deps, "Phar", phar_functions, PHP_MINIT(phar), PHP_MSHUTDOWN(phar), NULL, PHP_RSHUTDOWN(phar), PHP_MINFO(phar), PHP_PHAR_VERSION, PHP_MODULE_GLOBALS(phar), /* globals descriptor */ PHP_GINIT(phar), /* globals ctor */ PHP_GSHUTDOWN(phar), /* globals dtor */ NULL, /* post deactivate */ STANDARD_MODULE_PROPERTIES_EX }; /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | phar php single-file executable PHP extension | +----------------------------------------------------------------------+ | Copyright (c) 2005-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Gregory Beaver <[email protected]> | | Marcus Boerger <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #define PHAR_MAIN 1 #include "phar_internal.h" #include "SAPI.h" #include "func_interceptors.h" static void destroy_phar_data(void *pDest); ZEND_DECLARE_MODULE_GLOBALS(phar) #if PHP_VERSION_ID >= 50300 char *(*phar_save_resolve_path)(const char *filename, int filename_len TSRMLS_DC); #endif /** * set's phar->is_writeable based on the current INI value */ static int phar_set_writeable_bit(void *pDest, void *argument TSRMLS_DC) /* {{{ */ { zend_bool keep = *(zend_bool *)argument; phar_archive_data *phar = *(phar_archive_data **)pDest; if (!phar->is_data) { phar->is_writeable = !keep; } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* if the original value is 0 (disabled), then allow setting/unsetting at will. Otherwise only allow 1 (enabled), and error on disabling */ ZEND_INI_MH(phar_ini_modify_handler) /* {{{ */ { zend_bool old, ini; if (entry->name_length == 14) { old = PHAR_G(readonly_orig); } else { old = PHAR_G(require_hash_orig); } if (new_value_length == 2 && !strcasecmp("on", new_value)) { ini = (zend_bool) 1; } else if (new_value_length == 3 && !strcasecmp("yes", new_value)) { ini = (zend_bool) 1; } else if (new_value_length == 4 && !strcasecmp("true", new_value)) { ini = (zend_bool) 1; } else { ini = (zend_bool) atoi(new_value); } /* do not allow unsetting in runtime */ if (stage == ZEND_INI_STAGE_STARTUP) { if (entry->name_length == 14) { PHAR_G(readonly_orig) = ini; } else { PHAR_G(require_hash_orig) = ini; } } else if (old && !ini) { return FAILURE; } if (entry->name_length == 14) { PHAR_G(readonly) = ini; if (PHAR_GLOBALS->request_init && PHAR_GLOBALS->phar_fname_map.arBuckets) { zend_hash_apply_with_argument(&(PHAR_GLOBALS->phar_fname_map), phar_set_writeable_bit, (void *)&ini TSRMLS_CC); } } else { PHAR_G(require_hash) = ini; } return SUCCESS; } /* }}}*/ /* this global stores the global cached pre-parsed manifests */ HashTable cached_phars; HashTable cached_alias; static void phar_split_cache_list(TSRMLS_D) /* {{{ */ { char *tmp; char *key, *lasts, *end; char ds[2]; phar_archive_data *phar; uint i = 0; if (!PHAR_GLOBALS->cache_list || !(PHAR_GLOBALS->cache_list[0])) { return; } ds[0] = DEFAULT_DIR_SEPARATOR; ds[1] = '\0'; tmp = estrdup(PHAR_GLOBALS->cache_list); /* fake request startup */ PHAR_GLOBALS->request_init = 1; if (zend_hash_init(&EG(regular_list), 0, NULL, NULL, 0) == SUCCESS) { EG(regular_list).nNextFreeElement=1; /* we don't want resource id 0 */ } PHAR_G(has_bz2) = zend_hash_exists(&module_registry, "bz2", sizeof("bz2")); PHAR_G(has_zlib) = zend_hash_exists(&module_registry, "zlib", sizeof("zlib")); /* these two are dummies and will be destroyed later */ zend_hash_init(&cached_phars, sizeof(phar_archive_data*), zend_get_hash_value, destroy_phar_data, 1); zend_hash_init(&cached_alias, sizeof(phar_archive_data*), zend_get_hash_value, NULL, 1); /* these two are real and will be copied over cached_phars/cached_alias later */ zend_hash_init(&(PHAR_GLOBALS->phar_fname_map), sizeof(phar_archive_data*), zend_get_hash_value, destroy_phar_data, 1); zend_hash_init(&(PHAR_GLOBALS->phar_alias_map), sizeof(phar_archive_data*), zend_get_hash_value, NULL, 1); PHAR_GLOBALS->manifest_cached = 1; PHAR_GLOBALS->persist = 1; for (key = php_strtok_r(tmp, ds, &lasts); key; key = php_strtok_r(NULL, ds, &lasts)) { end = strchr(key, DEFAULT_DIR_SEPARATOR); if (end) { if (SUCCESS == phar_open_from_filename(key, end - key, NULL, 0, 0, &phar, NULL TSRMLS_CC)) { finish_up: phar->phar_pos = i++; php_stream_close(phar->fp); phar->fp = NULL; } else { finish_error: PHAR_GLOBALS->persist = 0; PHAR_GLOBALS->manifest_cached = 0; efree(tmp); zend_hash_destroy(&(PHAR_G(phar_fname_map))); PHAR_GLOBALS->phar_fname_map.arBuckets = 0; zend_hash_destroy(&(PHAR_G(phar_alias_map))); PHAR_GLOBALS->phar_alias_map.arBuckets = 0; zend_hash_destroy(&cached_phars); zend_hash_destroy(&cached_alias); zend_hash_graceful_reverse_destroy(&EG(regular_list)); memset(&EG(regular_list), 0, sizeof(HashTable)); /* free cached manifests */ PHAR_GLOBALS->request_init = 0; return; } } else { if (SUCCESS == phar_open_from_filename(key, strlen(key), NULL, 0, 0, &phar, NULL TSRMLS_CC)) { goto finish_up; } else { goto finish_error; } } } PHAR_GLOBALS->persist = 0; PHAR_GLOBALS->request_init = 0; /* destroy dummy values from before */ zend_hash_destroy(&cached_phars); zend_hash_destroy(&cached_alias); cached_phars = PHAR_GLOBALS->phar_fname_map; cached_alias = PHAR_GLOBALS->phar_alias_map; PHAR_GLOBALS->phar_fname_map.arBuckets = 0; PHAR_GLOBALS->phar_alias_map.arBuckets = 0; zend_hash_graceful_reverse_destroy(&EG(regular_list)); memset(&EG(regular_list), 0, sizeof(HashTable)); efree(tmp); } /* }}} */ ZEND_INI_MH(phar_ini_cache_list) /* {{{ */ { PHAR_G(cache_list) = new_value; if (stage == ZEND_INI_STAGE_STARTUP) { phar_split_cache_list(TSRMLS_C); } return SUCCESS; } /* }}} */ PHP_INI_BEGIN() STD_PHP_INI_BOOLEAN( "phar.readonly", "1", PHP_INI_ALL, phar_ini_modify_handler, readonly, zend_phar_globals, phar_globals) STD_PHP_INI_BOOLEAN( "phar.require_hash", "1", PHP_INI_ALL, phar_ini_modify_handler, require_hash, zend_phar_globals, phar_globals) STD_PHP_INI_ENTRY("phar.cache_list", "", PHP_INI_SYSTEM, phar_ini_cache_list, cache_list, zend_phar_globals, phar_globals) PHP_INI_END() /** * When all uses of a phar have been concluded, this frees the manifest * and the phar slot */ void phar_destroy_phar_data(phar_archive_data *phar TSRMLS_DC) /* {{{ */ { if (phar->alias && phar->alias != phar->fname) { pefree(phar->alias, phar->is_persistent); phar->alias = NULL; } if (phar->fname) { pefree(phar->fname, phar->is_persistent); phar->fname = NULL; } if (phar->signature) { pefree(phar->signature, phar->is_persistent); phar->signature = NULL; } if (phar->manifest.arBuckets) { zend_hash_destroy(&phar->manifest); phar->manifest.arBuckets = NULL; } if (phar->mounted_dirs.arBuckets) { zend_hash_destroy(&phar->mounted_dirs); phar->mounted_dirs.arBuckets = NULL; } if (phar->virtual_dirs.arBuckets) { zend_hash_destroy(&phar->virtual_dirs); phar->virtual_dirs.arBuckets = NULL; } if (phar->metadata) { if (phar->is_persistent) { if (phar->metadata_len) { /* for zip comments that are strings */ free(phar->metadata); } else { zval_internal_ptr_dtor(&phar->metadata); } } else { zval_ptr_dtor(&phar->metadata); } phar->metadata_len = 0; phar->metadata = 0; } if (phar->fp) { php_stream_close(phar->fp); phar->fp = 0; } if (phar->ufp) { php_stream_close(phar->ufp); phar->ufp = 0; } pefree(phar, phar->is_persistent); } /* }}}*/ /** * Delete refcount and destruct if needed. On destruct return 1 else 0. */ int phar_archive_delref(phar_archive_data *phar TSRMLS_DC) /* {{{ */ { if (phar->is_persistent) { return 0; } if (--phar->refcount < 0) { if (PHAR_GLOBALS->request_done || zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), phar->fname, phar->fname_len) != SUCCESS) { phar_destroy_phar_data(phar TSRMLS_CC); } return 1; } else if (!phar->refcount) { /* invalidate phar cache */ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; if (phar->fp && !(phar->flags & PHAR_FILE_COMPRESSION_MASK)) { /* close open file handle - allows removal or rename of the file on windows, which has greedy locking only close if the archive was not already compressed. If it was compressed, then the fp does not refer to the original file */ php_stream_close(phar->fp); phar->fp = NULL; } if (!zend_hash_num_elements(&phar->manifest)) { /* this is a new phar that has perhaps had an alias/metadata set, but has never been flushed */ if (zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), phar->fname, phar->fname_len) != SUCCESS) { phar_destroy_phar_data(phar TSRMLS_CC); } return 1; } } return 0; } /* }}}*/ /** * Destroy phar's in shutdown, here we don't care about aliases */ static void destroy_phar_data_only(void *pDest) /* {{{ */ { phar_archive_data *phar_data = *(phar_archive_data **) pDest; TSRMLS_FETCH(); if (EG(exception) || --phar_data->refcount < 0) { phar_destroy_phar_data(phar_data TSRMLS_CC); } } /* }}}*/ /** * Delete aliases to phar's that got kicked out of the global table */ static int phar_unalias_apply(void *pDest, void *argument TSRMLS_DC) /* {{{ */ { return *(void**)pDest == argument ? ZEND_HASH_APPLY_REMOVE : ZEND_HASH_APPLY_KEEP; } /* }}} */ /** * Delete aliases to phar's that got kicked out of the global table */ static int phar_tmpclose_apply(void *pDest TSRMLS_DC) /* {{{ */ { phar_entry_info *entry = (phar_entry_info *) pDest; if (entry->fp_type != PHAR_TMP) { return ZEND_HASH_APPLY_KEEP; } if (entry->fp && !entry->fp_refcount) { php_stream_close(entry->fp); entry->fp = NULL; } return ZEND_HASH_APPLY_KEEP; } /* }}} */ /** * Filename map destructor */ static void destroy_phar_data(void *pDest) /* {{{ */ { phar_archive_data *phar_data = *(phar_archive_data **) pDest; TSRMLS_FETCH(); if (PHAR_GLOBALS->request_ends) { /* first, iterate over the manifest and close all PHAR_TMP entry fp handles, this prevents unnecessary unfreed stream resources */ zend_hash_apply(&(phar_data->manifest), phar_tmpclose_apply TSRMLS_CC); destroy_phar_data_only(pDest); return; } zend_hash_apply_with_argument(&(PHAR_GLOBALS->phar_alias_map), phar_unalias_apply, phar_data TSRMLS_CC); if (--phar_data->refcount < 0) { phar_destroy_phar_data(phar_data TSRMLS_CC); } } /* }}}*/ /** * destructor for the manifest hash, frees each file's entry */ void destroy_phar_manifest_entry(void *pDest) /* {{{ */ { phar_entry_info *entry = (phar_entry_info *)pDest; TSRMLS_FETCH(); if (entry->cfp) { php_stream_close(entry->cfp); entry->cfp = 0; } if (entry->fp) { php_stream_close(entry->fp); entry->fp = 0; } if (entry->metadata) { if (entry->is_persistent) { if (entry->metadata_len) { /* for zip comments that are strings */ free(entry->metadata); } else { zval_internal_ptr_dtor(&entry->metadata); } } else { zval_ptr_dtor(&entry->metadata); } entry->metadata_len = 0; entry->metadata = 0; } if (entry->metadata_str.c) { smart_str_free(&entry->metadata_str); entry->metadata_str.c = 0; } pefree(entry->filename, entry->is_persistent); if (entry->link) { pefree(entry->link, entry->is_persistent); entry->link = 0; } if (entry->tmp) { pefree(entry->tmp, entry->is_persistent); entry->tmp = 0; } } /* }}} */ int phar_entry_delref(phar_entry_data *idata TSRMLS_DC) /* {{{ */ { int ret = 0; if (idata->internal_file && !idata->internal_file->is_persistent) { if (--idata->internal_file->fp_refcount < 0) { idata->internal_file->fp_refcount = 0; } if (idata->fp && idata->fp != idata->phar->fp && idata->fp != idata->phar->ufp && idata->fp != idata->internal_file->fp) { php_stream_close(idata->fp); } /* if phar_get_or_create_entry_data returns a sub-directory, we have to free it */ if (idata->internal_file->is_temp_dir) { destroy_phar_manifest_entry((void *)idata->internal_file); efree(idata->internal_file); } } phar_archive_delref(idata->phar TSRMLS_CC); efree(idata); return ret; } /* }}} */ /** * Removes an entry, either by actually removing it or by marking it. */ void phar_entry_remove(phar_entry_data *idata, char **error TSRMLS_DC) /* {{{ */ { phar_archive_data *phar; phar = idata->phar; if (idata->internal_file->fp_refcount < 2) { if (idata->fp && idata->fp != idata->phar->fp && idata->fp != idata->phar->ufp && idata->fp != idata->internal_file->fp) { php_stream_close(idata->fp); } zend_hash_del(&idata->phar->manifest, idata->internal_file->filename, idata->internal_file->filename_len); idata->phar->refcount--; efree(idata); } else { idata->internal_file->is_deleted = 1; phar_entry_delref(idata TSRMLS_CC); } if (!phar->donotflush) { phar_flush(phar, 0, 0, 0, error TSRMLS_CC); } } /* }}} */ #define MAPPHAR_ALLOC_FAIL(msg) \ if (fp) {\ php_stream_close(fp);\ }\ if (error) {\ spprintf(error, 0, msg, fname);\ }\ return FAILURE; #define MAPPHAR_FAIL(msg) \ efree(savebuf);\ if (mydata) {\ phar_destroy_phar_data(mydata TSRMLS_CC);\ }\ if (signature) {\ pefree(signature, PHAR_G(persist));\ }\ MAPPHAR_ALLOC_FAIL(msg) #ifdef WORDS_BIGENDIAN # define PHAR_GET_32(buffer, var) \ var = ((((unsigned char*)(buffer))[3]) << 24) \ | ((((unsigned char*)(buffer))[2]) << 16) \ | ((((unsigned char*)(buffer))[1]) << 8) \ | (((unsigned char*)(buffer))[0]); \ (buffer) += 4 # define PHAR_GET_16(buffer, var) \ var = ((((unsigned char*)(buffer))[1]) << 8) \ | (((unsigned char*)(buffer))[0]); \ (buffer) += 2 #else # define PHAR_GET_32(buffer, var) \ memcpy(&var, buffer, sizeof(var)); \ buffer += 4 # define PHAR_GET_16(buffer, var) \ var = *(php_uint16*)(buffer); \ buffer += 2 #endif #define PHAR_ZIP_16(var) ((php_uint16)((((php_uint16)var[0]) & 0xff) | \ (((php_uint16)var[1]) & 0xff) << 8)) #define PHAR_ZIP_32(var) ((php_uint32)((((php_uint32)var[0]) & 0xff) | \ (((php_uint32)var[1]) & 0xff) << 8 | \ (((php_uint32)var[2]) & 0xff) << 16 | \ (((php_uint32)var[3]) & 0xff) << 24)) /** * Open an already loaded phar */ int phar_open_parsed_phar(char *fname, int fname_len, char *alias, int alias_len, int is_data, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { phar_archive_data *phar; #ifdef PHP_WIN32 char *unixfname; #endif if (error) { *error = NULL; } #ifdef PHP_WIN32 unixfname = estrndup(fname, fname_len); phar_unixify_path_separators(unixfname, fname_len); if (SUCCESS == phar_get_archive(&phar, unixfname, fname_len, alias, alias_len, error TSRMLS_CC) && ((alias && fname_len == phar->fname_len && !strncmp(unixfname, phar->fname, fname_len)) || !alias) ) { phar_entry_info *stub; efree(unixfname); #else if (SUCCESS == phar_get_archive(&phar, fname, fname_len, alias, alias_len, error TSRMLS_CC) && ((alias && fname_len == phar->fname_len && !strncmp(fname, phar->fname, fname_len)) || !alias) ) { phar_entry_info *stub; #endif /* logic above is as follows: If an explicit alias was requested, ensure the filename passed in matches the phar's filename. If no alias was passed in, then it can match either and be valid */ if (!is_data) { /* prevent any ".phar" without a stub getting through */ if (!phar->halt_offset && !phar->is_brandnew && (phar->is_tar || phar->is_zip)) { if (PHAR_G(readonly) && FAILURE == zend_hash_find(&(phar->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1, (void **)&stub)) { if (error) { spprintf(error, 0, "'%s' is not a phar archive. Use PharData::__construct() for a standard zip or tar archive", fname); } return FAILURE; } } } if (pphar) { *pphar = phar; } return SUCCESS; } else { #ifdef PHP_WIN32 efree(unixfname); #endif if (pphar) { *pphar = NULL; } if (phar && error && !(options & REPORT_ERRORS)) { efree(error); } return FAILURE; } } /* }}}*/ /** * Parse out metadata from the manifest for a single file * * Meta-data is in this format: * [len32][data...] * * data is the serialized zval */ int phar_parse_metadata(char **buffer, zval **metadata, int zip_metadata_len TSRMLS_DC) /* {{{ */ { const unsigned char *p; php_uint32 buf_len; php_unserialize_data_t var_hash; if (!zip_metadata_len) { PHAR_GET_32(*buffer, buf_len); } else { buf_len = zip_metadata_len; } if (buf_len) { ALLOC_ZVAL(*metadata); INIT_ZVAL(**metadata); p = (const unsigned char*) *buffer; PHP_VAR_UNSERIALIZE_INIT(var_hash); if (!php_var_unserialize(metadata, &p, p + buf_len, &var_hash TSRMLS_CC)) { PHP_VAR_UNSERIALIZE_DESTROY(var_hash); zval_ptr_dtor(metadata); *metadata = NULL; return FAILURE; } PHP_VAR_UNSERIALIZE_DESTROY(var_hash); if (PHAR_G(persist)) { /* lazy init metadata */ zval_ptr_dtor(metadata); *metadata = (zval *) pemalloc(buf_len, 1); memcpy(*metadata, *buffer, buf_len); *buffer += buf_len; return SUCCESS; } } else { *metadata = NULL; } if (!zip_metadata_len) { *buffer += buf_len; } return SUCCESS; } /* }}}*/ /** * Does not check for a previously opened phar in the cache. * * Parse a new one and add it to the cache, returning either SUCCESS or * FAILURE, and setting pphar to the pointer to the manifest entry * * This is used by phar_open_from_filename to process the manifest, but can be called * directly. */ static int phar_parse_pharfile(php_stream *fp, char *fname, int fname_len, char *alias, int alias_len, long halt_offset, phar_archive_data** pphar, php_uint32 compression, char **error TSRMLS_DC) /* {{{ */ { char b32[4], *buffer, *endbuffer, *savebuf; phar_archive_data *mydata = NULL; phar_entry_info entry; php_uint32 manifest_len, manifest_count, manifest_flags, manifest_index, tmp_len, sig_flags; php_uint16 manifest_ver; long offset; int sig_len, register_alias = 0, temp_alias = 0; char *signature = NULL; if (pphar) { *pphar = NULL; } if (error) { *error = NULL; } /* check for ?>\n and increment accordingly */ if (-1 == php_stream_seek(fp, halt_offset, SEEK_SET)) { MAPPHAR_ALLOC_FAIL("cannot seek to __HALT_COMPILER(); location in phar \"%s\"") } buffer = b32; if (3 != php_stream_read(fp, buffer, 3)) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at stub end)") } if ((*buffer == ' ' || *buffer == '\n') && *(buffer + 1) == '?' && *(buffer + 2) == '>') { int nextchar; halt_offset += 3; if (EOF == (nextchar = php_stream_getc(fp))) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at stub end)") } if ((char) nextchar == '\r') { /* if we have an \r we require an \n as well */ if (EOF == (nextchar = php_stream_getc(fp)) || (char)nextchar != '\n') { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at stub end)") } ++halt_offset; } if ((char) nextchar == '\n') { ++halt_offset; } } /* make sure we are at the right location to read the manifest */ if (-1 == php_stream_seek(fp, halt_offset, SEEK_SET)) { MAPPHAR_ALLOC_FAIL("cannot seek to __HALT_COMPILER(); location in phar \"%s\"") } /* read in manifest */ buffer = b32; if (4 != php_stream_read(fp, buffer, 4)) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated manifest at manifest length)") } PHAR_GET_32(buffer, manifest_len); if (manifest_len > 1048576 * 100) { /* prevent serious memory issues by limiting manifest to at most 100 MB in length */ MAPPHAR_ALLOC_FAIL("manifest cannot be larger than 100 MB in phar \"%s\"") } buffer = (char *)emalloc(manifest_len); savebuf = buffer; endbuffer = buffer + manifest_len; if (manifest_len < 10 || manifest_len != php_stream_read(fp, buffer, manifest_len)) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest header)") } /* extract the number of entries */ PHAR_GET_32(buffer, manifest_count); if (manifest_count == 0) { MAPPHAR_FAIL("in phar \"%s\", manifest claims to have zero entries. Phars must have at least 1 entry"); } /* extract API version, lowest nibble currently unused */ manifest_ver = (((unsigned char)buffer[0]) << 8) + ((unsigned char)buffer[1]); buffer += 2; if ((manifest_ver & PHAR_API_VER_MASK) < PHAR_API_MIN_READ) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" is API version %1.u.%1.u.%1.u, and cannot be processed", fname, manifest_ver >> 12, (manifest_ver >> 8) & 0xF, (manifest_ver >> 4) & 0x0F); } return FAILURE; } PHAR_GET_32(buffer, manifest_flags); manifest_flags &= ~PHAR_HDR_COMPRESSION_MASK; manifest_flags &= ~PHAR_FILE_COMPRESSION_MASK; /* remember whether this entire phar was compressed with gz/bzip2 */ manifest_flags |= compression; /* The lowest nibble contains the phar wide flags. The compression flags can */ /* be ignored on reading because it is being generated anyways. */ if (manifest_flags & PHAR_HDR_SIGNATURE) { char sig_buf[8], *sig_ptr = sig_buf; off_t read_len; size_t end_of_phar; if (-1 == php_stream_seek(fp, -8, SEEK_END) || (read_len = php_stream_tell(fp)) < 20 || 8 != php_stream_read(fp, sig_buf, 8) || memcmp(sig_buf+4, "GBMB", 4)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } PHAR_GET_32(sig_ptr, sig_flags); switch(sig_flags) { case PHAR_SIG_OPENSSL: { php_uint32 signature_len; char *sig; off_t whence; /* we store the signature followed by the signature length */ if (-1 == php_stream_seek(fp, -12, SEEK_CUR) || 4 != php_stream_read(fp, sig_buf, 4)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" openssl signature length could not be read", fname); } return FAILURE; } sig_ptr = sig_buf; PHAR_GET_32(sig_ptr, signature_len); sig = (char *) emalloc(signature_len); whence = signature_len + 4; whence = -whence; if (-1 == php_stream_seek(fp, whence, SEEK_CUR) || !(end_of_phar = php_stream_tell(fp)) || signature_len != php_stream_read(fp, sig, signature_len)) { efree(savebuf); efree(sig); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" openssl signature could not be read", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, end_of_phar, PHAR_SIG_OPENSSL, sig, signature_len, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); efree(sig); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" openssl signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } efree(sig); } break; #if PHAR_HASH_OK case PHAR_SIG_SHA512: { unsigned char digest[64]; php_stream_seek(fp, -(8 + 64), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_SHA512, (char *)digest, 64, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" SHA512 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } case PHAR_SIG_SHA256: { unsigned char digest[32]; php_stream_seek(fp, -(8 + 32), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_SHA256, (char *)digest, 32, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" SHA256 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } #else case PHAR_SIG_SHA512: case PHAR_SIG_SHA256: efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a unsupported signature", fname); } return FAILURE; #endif case PHAR_SIG_SHA1: { unsigned char digest[20]; php_stream_seek(fp, -(8 + 20), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_SHA1, (char *)digest, 20, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" SHA1 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } case PHAR_SIG_MD5: { unsigned char digest[16]; php_stream_seek(fp, -(8 + 16), SEEK_END); read_len = php_stream_tell(fp); if (php_stream_read(fp, (char*)digest, sizeof(digest)) != sizeof(digest)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken signature", fname); } return FAILURE; } if (FAILURE == phar_verify_signature(fp, read_len, PHAR_SIG_MD5, (char *)digest, 16, fname, &signature, &sig_len, error TSRMLS_CC)) { efree(savebuf); php_stream_close(fp); if (error) { char *save = *error; spprintf(error, 0, "phar \"%s\" MD5 signature could not be verified: %s", fname, *error); efree(save); } return FAILURE; } break; } default: efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" has a broken or unsupported signature", fname); } return FAILURE; } } else if (PHAR_G(require_hash)) { efree(savebuf); php_stream_close(fp); if (error) { spprintf(error, 0, "phar \"%s\" does not have a signature", fname); } return FAILURE; } else { sig_flags = 0; sig_len = 0; } /* extract alias */ PHAR_GET_32(buffer, tmp_len); if (buffer + tmp_len > endbuffer) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (buffer overrun)"); } if (manifest_len < 10 + tmp_len) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest header)") } /* tmp_len = 0 says alias length is 0, which means the alias is not stored in the phar */ if (tmp_len) { /* if the alias is stored we enforce it (implicit overrides explicit) */ if (alias && alias_len && (alias_len != (int)tmp_len || strncmp(alias, buffer, tmp_len))) { buffer[tmp_len] = '\0'; php_stream_close(fp); if (signature) { efree(signature); } if (error) { spprintf(error, 0, "cannot load phar \"%s\" with implicit alias \"%s\" under different alias \"%s\"", fname, buffer, alias); } efree(savebuf); return FAILURE; } alias_len = tmp_len; alias = buffer; buffer += tmp_len; register_alias = 1; } else if (!alias_len || !alias) { /* if we neither have an explicit nor an implicit alias, we use the filename */ alias = NULL; alias_len = 0; register_alias = 0; } else if (alias_len) { register_alias = 1; temp_alias = 1; } /* we have 5 32-bit items plus 1 byte at least */ if (manifest_count > ((manifest_len - 10 - tmp_len) / (5 * 4 + 1))) { /* prevent serious memory issues */ MAPPHAR_FAIL("internal corruption of phar \"%s\" (too many manifest entries for size of manifest)") } mydata = pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist)); mydata->is_persistent = PHAR_G(persist); /* check whether we have meta data, zero check works regardless of byte order */ if (mydata->is_persistent) { PHAR_GET_32(buffer, mydata->metadata_len); if (phar_parse_metadata(&buffer, &mydata->metadata, mydata->metadata_len TSRMLS_CC) == FAILURE) { MAPPHAR_FAIL("unable to read phar metadata in .phar file \"%s\""); } } else { if (phar_parse_metadata(&buffer, &mydata->metadata, 0 TSRMLS_CC) == FAILURE) { MAPPHAR_FAIL("unable to read phar metadata in .phar file \"%s\""); } } /* set up our manifest */ zend_hash_init(&mydata->manifest, manifest_count, zend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)mydata->is_persistent); zend_hash_init(&mydata->mounted_dirs, 5, zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); zend_hash_init(&mydata->virtual_dirs, manifest_count * 2, zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); mydata->fname = pestrndup(fname, fname_len, mydata->is_persistent); #ifdef PHP_WIN32 phar_unixify_path_separators(mydata->fname, fname_len); #endif mydata->fname_len = fname_len; offset = halt_offset + manifest_len + 4; memset(&entry, 0, sizeof(phar_entry_info)); entry.phar = mydata; entry.fp_type = PHAR_FP; entry.is_persistent = mydata->is_persistent; for (manifest_index = 0; manifest_index < manifest_count; ++manifest_index) { if (buffer + 4 > endbuffer) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest entry)") } PHAR_GET_32(buffer, entry.filename_len); if (entry.filename_len == 0) { MAPPHAR_FAIL("zero-length filename encountered in phar \"%s\""); } if (entry.is_persistent) { entry.manifest_pos = manifest_index; } if (buffer + entry.filename_len + 20 > endbuffer) { MAPPHAR_FAIL("internal corruption of phar \"%s\" (truncated manifest entry)"); } if ((manifest_ver & PHAR_API_VER_MASK) >= PHAR_API_MIN_DIR && buffer[entry.filename_len - 1] == '/') { entry.is_dir = 1; } else { entry.is_dir = 0; } phar_add_virtual_dirs(mydata, buffer, entry.filename_len TSRMLS_CC); entry.filename = pestrndup(buffer, entry.filename_len, entry.is_persistent); buffer += entry.filename_len; PHAR_GET_32(buffer, entry.uncompressed_filesize); PHAR_GET_32(buffer, entry.timestamp); if (offset == halt_offset + (int)manifest_len + 4) { mydata->min_timestamp = entry.timestamp; mydata->max_timestamp = entry.timestamp; } else { if (mydata->min_timestamp > entry.timestamp) { mydata->min_timestamp = entry.timestamp; } else if (mydata->max_timestamp < entry.timestamp) { mydata->max_timestamp = entry.timestamp; } } PHAR_GET_32(buffer, entry.compressed_filesize); PHAR_GET_32(buffer, entry.crc32); PHAR_GET_32(buffer, entry.flags); if (entry.is_dir) { entry.filename_len--; entry.flags |= PHAR_ENT_PERM_DEF_DIR; } if (entry.is_persistent) { PHAR_GET_32(buffer, entry.metadata_len); if (!entry.metadata_len) buffer -= 4; if (phar_parse_metadata(&buffer, &entry.metadata, entry.metadata_len TSRMLS_CC) == FAILURE) { pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("unable to read file metadata in .phar file \"%s\""); } } else { if (phar_parse_metadata(&buffer, &entry.metadata, 0 TSRMLS_CC) == FAILURE) { pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("unable to read file metadata in .phar file \"%s\""); } } entry.offset = entry.offset_abs = offset; offset += entry.compressed_filesize; switch (entry.flags & PHAR_ENT_COMPRESSION_MASK) { case PHAR_ENT_COMPRESSED_GZ: if (!PHAR_G(has_zlib)) { if (entry.metadata) { if (entry.is_persistent) { free(entry.metadata); } else { zval_ptr_dtor(&entry.metadata); } } pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("zlib extension is required for gz compressed .phar file \"%s\""); } break; case PHAR_ENT_COMPRESSED_BZ2: if (!PHAR_G(has_bz2)) { if (entry.metadata) { if (entry.is_persistent) { free(entry.metadata); } else { zval_ptr_dtor(&entry.metadata); } } pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("bz2 extension is required for bzip2 compressed .phar file \"%s\""); } break; default: if (entry.uncompressed_filesize != entry.compressed_filesize) { if (entry.metadata) { if (entry.is_persistent) { free(entry.metadata); } else { zval_ptr_dtor(&entry.metadata); } } pefree(entry.filename, entry.is_persistent); MAPPHAR_FAIL("internal corruption of phar \"%s\" (compressed and uncompressed size does not match for uncompressed entry)"); } break; } manifest_flags |= (entry.flags & PHAR_ENT_COMPRESSION_MASK); /* if signature matched, no need to check CRC32 for each file */ entry.is_crc_checked = (manifest_flags & PHAR_HDR_SIGNATURE ? 1 : 0); phar_set_inode(&entry TSRMLS_CC); zend_hash_add(&mydata->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info), NULL); } snprintf(mydata->version, sizeof(mydata->version), "%u.%u.%u", manifest_ver >> 12, (manifest_ver >> 8) & 0xF, (manifest_ver >> 4) & 0xF); mydata->internal_file_start = halt_offset + manifest_len + 4; mydata->halt_offset = halt_offset; mydata->flags = manifest_flags; endbuffer = strrchr(mydata->fname, '/'); if (endbuffer) { mydata->ext = memchr(endbuffer, '.', (mydata->fname + fname_len) - endbuffer); if (mydata->ext == endbuffer) { mydata->ext = memchr(endbuffer + 1, '.', (mydata->fname + fname_len) - endbuffer - 1); } if (mydata->ext) { mydata->ext_len = (mydata->fname + mydata->fname_len) - mydata->ext; } } mydata->alias = alias ? pestrndup(alias, alias_len, mydata->is_persistent) : pestrndup(mydata->fname, fname_len, mydata->is_persistent); mydata->alias_len = alias ? alias_len : fname_len; mydata->sig_flags = sig_flags; mydata->fp = fp; mydata->sig_len = sig_len; mydata->signature = signature; phar_request_initialize(TSRMLS_C); if (register_alias) { phar_archive_data **fd_ptr; mydata->is_temporary_alias = temp_alias; if (!phar_validate_alias(mydata->alias, mydata->alias_len)) { signature = NULL; fp = NULL; MAPPHAR_FAIL("Cannot open archive \"%s\", invalid alias"); } if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) { if (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) { signature = NULL; fp = NULL; MAPPHAR_FAIL("Cannot open archive \"%s\", alias is already in use by existing archive"); } } zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&mydata, sizeof(phar_archive_data*), NULL); } else { mydata->is_temporary_alias = 1; } zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len, (void*)&mydata, sizeof(phar_archive_data*), NULL); efree(savebuf); if (pphar) { *pphar = mydata; } return SUCCESS; } /* }}} */ /** * Create or open a phar for writing */ int phar_open_or_create_filename(char *fname, int fname_len, char *alias, int alias_len, int is_data, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { const char *ext_str, *z; char *my_error; int ext_len; phar_archive_data **test, *unused = NULL; test = &unused; if (error) { *error = NULL; } /* first try to open an existing file */ if (phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, !is_data, 0, 1 TSRMLS_CC) == SUCCESS) { goto check_file; } /* next try to create a new file */ if (FAILURE == phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, !is_data, 1, 1 TSRMLS_CC)) { if (error) { if (ext_len == -2) { spprintf(error, 0, "Cannot create a phar archive from a URL like \"%s\". Phar objects can only be created from local files", fname); } else { spprintf(error, 0, "Cannot create phar '%s', file extension (or combination) not recognised or the directory does not exist", fname); } } return FAILURE; } check_file: if (phar_open_parsed_phar(fname, fname_len, alias, alias_len, is_data, options, test, &my_error TSRMLS_CC) == SUCCESS) { if (pphar) { *pphar = *test; } if ((*test)->is_data && !(*test)->is_tar && !(*test)->is_zip) { if (error) { spprintf(error, 0, "Cannot open '%s' as a PharData object. Use Phar::__construct() for executable archives", fname); } return FAILURE; } if (PHAR_G(readonly) && !(*test)->is_data && ((*test)->is_tar || (*test)->is_zip)) { phar_entry_info *stub; if (FAILURE == zend_hash_find(&((*test)->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1, (void **)&stub)) { spprintf(error, 0, "'%s' is not a phar archive. Use PharData::__construct() for a standard zip or tar archive", fname); return FAILURE; } } if (!PHAR_G(readonly) || (*test)->is_data) { (*test)->is_writeable = 1; } return SUCCESS; } else if (my_error) { if (error) { *error = my_error; } else { efree(my_error); } return FAILURE; } if (ext_len > 3 && (z = memchr(ext_str, 'z', ext_len)) && ((ext_str + ext_len) - z >= 2) && !memcmp(z + 1, "ip", 2)) { /* assume zip-based phar */ return phar_open_or_create_zip(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC); } if (ext_len > 3 && (z = memchr(ext_str, 't', ext_len)) && ((ext_str + ext_len) - z >= 2) && !memcmp(z + 1, "ar", 2)) { /* assume tar-based phar */ return phar_open_or_create_tar(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC); } return phar_create_or_parse_filename(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC); } /* }}} */ int phar_create_or_parse_filename(char *fname, int fname_len, char *alias, int alias_len, int is_data, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { phar_archive_data *mydata; php_stream *fp; char *actual = NULL, *p; if (!pphar) { pphar = &mydata; } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { return FAILURE; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { return FAILURE; } /* first open readonly so it won't be created if not present */ fp = php_stream_open_wrapper(fname, "rb", IGNORE_URL|STREAM_MUST_SEEK|0, &actual); if (actual) { fname = actual; fname_len = strlen(actual); } if (fp) { if (phar_open_from_fp(fp, fname, fname_len, alias, alias_len, options, pphar, is_data, error TSRMLS_CC) == SUCCESS) { if ((*pphar)->is_data || !PHAR_G(readonly)) { (*pphar)->is_writeable = 1; } if (actual) { efree(actual); } return SUCCESS; } else { /* file exists, but is either corrupt or not a phar archive */ if (actual) { efree(actual); } return FAILURE; } } if (actual) { efree(actual); } if (PHAR_G(readonly) && !is_data) { if (options & REPORT_ERRORS) { if (error) { spprintf(error, 0, "creating archive \"%s\" disabled by the php.ini setting phar.readonly", fname); } } return FAILURE; } /* set up our manifest */ mydata = ecalloc(1, sizeof(phar_archive_data)); mydata->fname = expand_filepath(fname, NULL TSRMLS_CC); fname_len = strlen(mydata->fname); #ifdef PHP_WIN32 phar_unixify_path_separators(mydata->fname, fname_len); #endif p = strrchr(mydata->fname, '/'); if (p) { mydata->ext = memchr(p, '.', (mydata->fname + fname_len) - p); if (mydata->ext == p) { mydata->ext = memchr(p + 1, '.', (mydata->fname + fname_len) - p - 1); } if (mydata->ext) { mydata->ext_len = (mydata->fname + fname_len) - mydata->ext; } } if (pphar) { *pphar = mydata; } zend_hash_init(&mydata->manifest, sizeof(phar_entry_info), zend_get_hash_value, destroy_phar_manifest_entry, 0); zend_hash_init(&mydata->mounted_dirs, sizeof(char *), zend_get_hash_value, NULL, 0); zend_hash_init(&mydata->virtual_dirs, sizeof(char *), zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent); mydata->fname_len = fname_len; snprintf(mydata->version, sizeof(mydata->version), "%s", PHP_PHAR_API_VERSION); mydata->is_temporary_alias = alias ? 0 : 1; mydata->internal_file_start = -1; mydata->fp = NULL; mydata->is_writeable = 1; mydata->is_brandnew = 1; phar_request_initialize(TSRMLS_C); zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len, (void*)&mydata, sizeof(phar_archive_data*), NULL); if (is_data) { alias = NULL; alias_len = 0; mydata->is_data = 1; /* assume tar format, PharData can specify other */ mydata->is_tar = 1; } else { phar_archive_data **fd_ptr; if (alias && SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) { if (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) { if (error) { spprintf(error, 4096, "phar error: phar \"%s\" cannot set alias \"%s\", already in use by another phar archive", mydata->fname, alias); } zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len); if (pphar) { *pphar = NULL; } return FAILURE; } } mydata->alias = alias ? estrndup(alias, alias_len) : estrndup(mydata->fname, fname_len); mydata->alias_len = alias ? alias_len : fname_len; } if (alias_len && alias) { if (FAILURE == zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&mydata, sizeof(phar_archive_data*), NULL)) { if (options & REPORT_ERRORS) { if (error) { spprintf(error, 0, "archive \"%s\" cannot be associated with alias \"%s\", already in use", fname, alias); } } zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len); if (pphar) { *pphar = NULL; } return FAILURE; } } return SUCCESS; } /* }}}*/ /** * Return an already opened filename. * * Or scan a phar file for the required __HALT_COMPILER(); ?> token and verify * that the manifest is proper, then pass it to phar_parse_pharfile(). SUCCESS * or FAILURE is returned and pphar is set to a pointer to the phar's manifest */ int phar_open_from_filename(char *fname, int fname_len, char *alias, int alias_len, int options, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */ { php_stream *fp; char *actual; int ret, is_data = 0; if (error) { *error = NULL; } if (!strstr(fname, ".phar")) { is_data = 1; } if (phar_open_parsed_phar(fname, fname_len, alias, alias_len, is_data, options, pphar, error TSRMLS_CC) == SUCCESS) { return SUCCESS; } else if (error && *error) { return FAILURE; } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { return FAILURE; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { return FAILURE; } fp = php_stream_open_wrapper(fname, "rb", IGNORE_URL|STREAM_MUST_SEEK, &actual); if (!fp) { if (options & REPORT_ERRORS) { if (error) { spprintf(error, 0, "unable to open phar for reading \"%s\"", fname); } } if (actual) { efree(actual); } return FAILURE; } if (actual) { fname = actual; fname_len = strlen(actual); } ret = phar_open_from_fp(fp, fname, fname_len, alias, alias_len, options, pphar, is_data, error TSRMLS_CC); if (actual) { efree(actual); } return ret; } /* }}}*/ static inline char *phar_strnstr(const char *buf, int buf_len, const char *search, int search_len) /* {{{ */ { const char *c; int so_far = 0; if (buf_len < search_len) { return NULL; } c = buf - 1; do { if (!(c = memchr(c + 1, search[0], buf_len - search_len - so_far))) { return (char *) NULL; } so_far = c - buf; if (so_far >= (buf_len - search_len)) { return (char *) NULL; } if (!memcmp(c, search, search_len)) { return (char *) c; } } while (1); } /* }}} */ /** * Scan an open fp for the required __HALT_COMPILER(); ?> token and verify * that the manifest is proper, then pass it to phar_parse_pharfile(). SUCCESS * or FAILURE is returned and pphar is set to a pointer to the phar's manifest */ static int phar_open_from_fp(php_stream* fp, char *fname, int fname_len, char *alias, int alias_len, int options, phar_archive_data** pphar, int is_data, char **error TSRMLS_DC) /* {{{ */ { const char token[] = "__HALT_COMPILER();"; const char zip_magic[] = "PK\x03\x04"; const char gz_magic[] = "\x1f\x8b\x08"; const char bz_magic[] = "BZh"; char *pos, test = '\0'; const int window_size = 1024; char buffer[window_size + sizeof(token)]; /* a 1024 byte window + the size of the halt_compiler token (moving window) */ const long readsize = sizeof(buffer) - sizeof(token); const long tokenlen = sizeof(token) - 1; long halt_offset; size_t got; php_uint32 compression = PHAR_FILE_COMPRESSED_NONE; if (error) { *error = NULL; } if (-1 == php_stream_rewind(fp)) { MAPPHAR_ALLOC_FAIL("cannot rewind phar \"%s\"") } buffer[sizeof(buffer)-1] = '\0'; memset(buffer, 32, sizeof(token)); halt_offset = 0; /* Maybe it's better to compile the file instead of just searching, */ /* but we only want the offset. So we want a .re scanner to find it. */ while(!php_stream_eof(fp)) { if ((got = php_stream_read(fp, buffer+tokenlen, readsize)) < (size_t) tokenlen) { MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (truncated entry)") } if (!test) { test = '\1'; pos = buffer+tokenlen; if (!memcmp(pos, gz_magic, 3)) { char err = 0; php_stream_filter *filter; php_stream *temp; /* to properly decompress, we have to tell zlib to look for a zlib or gzip header */ zval filterparams; if (!PHAR_G(has_zlib)) { MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\" to temporary file, enable zlib extension in php.ini") } array_init(&filterparams); /* this is defined in zlib's zconf.h */ #ifndef MAX_WBITS #define MAX_WBITS 15 #endif add_assoc_long(&filterparams, "window", MAX_WBITS + 32); /* entire file is gzip-compressed, uncompress to temporary file */ if (!(temp = php_stream_fopen_tmpfile())) { MAPPHAR_ALLOC_FAIL("unable to create temporary file for decompression of gzipped phar archive \"%s\"") } php_stream_rewind(fp); filter = php_stream_filter_create("zlib.inflate", &filterparams, php_stream_is_persistent(fp) TSRMLS_CC); if (!filter) { err = 1; add_assoc_long(&filterparams, "window", MAX_WBITS); filter = php_stream_filter_create("zlib.inflate", &filterparams, php_stream_is_persistent(fp) TSRMLS_CC); zval_dtor(&filterparams); if (!filter) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\", ext/zlib is buggy in PHP versions older than 5.2.6") } } else { zval_dtor(&filterparams); } php_stream_filter_append(&temp->writefilters, filter); if (SUCCESS != phar_stream_copy_to_stream(fp, temp, PHP_STREAM_COPY_ALL, NULL)) { if (err) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\", ext/zlib is buggy in PHP versions older than 5.2.6") } php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress gzipped phar archive \"%s\" to temporary file") } php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(fp); fp = temp; php_stream_rewind(fp); compression = PHAR_FILE_COMPRESSED_GZ; /* now, start over */ test = '\0'; continue; } else if (!memcmp(pos, bz_magic, 3)) { php_stream_filter *filter; php_stream *temp; if (!PHAR_G(has_bz2)) { MAPPHAR_ALLOC_FAIL("unable to decompress bzipped phar archive \"%s\" to temporary file, enable bz2 extension in php.ini") } /* entire file is bzip-compressed, uncompress to temporary file */ if (!(temp = php_stream_fopen_tmpfile())) { MAPPHAR_ALLOC_FAIL("unable to create temporary file for decompression of bzipped phar archive \"%s\"") } php_stream_rewind(fp); filter = php_stream_filter_create("bzip2.decompress", NULL, php_stream_is_persistent(fp) TSRMLS_CC); if (!filter) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress bzipped phar archive \"%s\", filter creation failed") } php_stream_filter_append(&temp->writefilters, filter); if (SUCCESS != phar_stream_copy_to_stream(fp, temp, PHP_STREAM_COPY_ALL, NULL)) { php_stream_close(temp); MAPPHAR_ALLOC_FAIL("unable to decompress bzipped phar archive \"%s\" to temporary file") } php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(fp); fp = temp; php_stream_rewind(fp); compression = PHAR_FILE_COMPRESSED_BZ2; /* now, start over */ test = '\0'; continue; } if (!memcmp(pos, zip_magic, 4)) { php_stream_seek(fp, 0, SEEK_END); return phar_parse_zipfile(fp, fname, fname_len, alias, alias_len, pphar, error TSRMLS_CC); } if (got > 512) { if (phar_is_tar(pos, fname)) { php_stream_rewind(fp); return phar_parse_tarfile(fp, fname, fname_len, alias, alias_len, pphar, is_data, compression, error TSRMLS_CC); } } } if (got > 0 && (pos = phar_strnstr(buffer, got + sizeof(token), token, sizeof(token)-1)) != NULL) { halt_offset += (pos - buffer); /* no -tokenlen+tokenlen here */ return phar_parse_pharfile(fp, fname, fname_len, alias, alias_len, halt_offset, pphar, compression, error TSRMLS_CC); } halt_offset += got; memmove(buffer, buffer + window_size, tokenlen); /* move the memory buffer by the size of the window */ } MAPPHAR_ALLOC_FAIL("internal corruption of phar \"%s\" (__HALT_COMPILER(); not found)") } /* }}} */ /* * given the location of the file extension and the start of the file path, * determine the end of the portion of the path (i.e. /path/to/file.ext/blah * grabs "/path/to/file.ext" as does the straight /path/to/file.ext), * stat it to determine if it exists. * if so, check to see if it is a directory and fail if so * if not, check to see if its dirname() exists (i.e. "/path/to") and is a directory * succeed if we are creating the file, otherwise fail. */ static int phar_analyze_path(const char *fname, const char *ext, int ext_len, int for_create TSRMLS_DC) /* {{{ */ { php_stream_statbuf ssb; char *realpath; char *filename = estrndup(fname, (ext - fname) + ext_len); if ((realpath = expand_filepath(filename, NULL TSRMLS_CC))) { #ifdef PHP_WIN32 phar_unixify_path_separators(realpath, strlen(realpath)); #endif if (zend_hash_exists(&(PHAR_GLOBALS->phar_fname_map), realpath, strlen(realpath))) { efree(realpath); efree(filename); return SUCCESS; } if (PHAR_G(manifest_cached) && zend_hash_exists(&cached_phars, realpath, strlen(realpath))) { efree(realpath); efree(filename); return SUCCESS; } efree(realpath); } if (SUCCESS == php_stream_stat_path((char *) filename, &ssb)) { efree(filename); if (ssb.sb.st_mode & S_IFDIR) { return FAILURE; } if (for_create == 1) { return FAILURE; } return SUCCESS; } else { char *slash; if (!for_create) { efree(filename); return FAILURE; } slash = (char *) strrchr(filename, '/'); if (slash) { *slash = '\0'; } if (SUCCESS != php_stream_stat_path((char *) filename, &ssb)) { if (!slash) { if (!(realpath = expand_filepath(filename, NULL TSRMLS_CC))) { efree(filename); return FAILURE; } #ifdef PHP_WIN32 phar_unixify_path_separators(realpath, strlen(realpath)); #endif slash = strstr(realpath, filename) + ((ext - fname) + ext_len); *slash = '\0'; slash = strrchr(realpath, '/'); if (slash) { *slash = '\0'; } else { efree(realpath); efree(filename); return FAILURE; } if (SUCCESS != php_stream_stat_path(realpath, &ssb)) { efree(realpath); efree(filename); return FAILURE; } efree(realpath); if (ssb.sb.st_mode & S_IFDIR) { efree(filename); return SUCCESS; } } efree(filename); return FAILURE; } efree(filename); if (ssb.sb.st_mode & S_IFDIR) { return SUCCESS; } return FAILURE; } } /* }}} */ /* check for ".phar" in extension */ static int phar_check_str(const char *fname, const char *ext_str, int ext_len, int executable, int for_create TSRMLS_DC) /* {{{ */ { char test[51]; const char *pos; if (ext_len >= 50) { return FAILURE; } if (executable == 1) { /* copy "." as well */ memcpy(test, ext_str - 1, ext_len + 1); test[ext_len + 1] = '\0'; /* executable phars must contain ".phar" as a valid extension (phar://.pharmy/oops is invalid) */ /* (phar://hi/there/.phar/oops is also invalid) */ pos = strstr(test, ".phar"); if (pos && (*(pos - 1) != '/') && (pos += 5) && (*pos == '\0' || *pos == '/' || *pos == '.')) { return phar_analyze_path(fname, ext_str, ext_len, for_create TSRMLS_CC); } else { return FAILURE; } } /* data phars need only contain a single non-"." to be valid */ if (!executable) { pos = strstr(ext_str, ".phar"); if (!(pos && (*(pos - 1) != '/') && (pos += 5) && (*pos == '\0' || *pos == '/' || *pos == '.')) && *(ext_str + 1) != '.' && *(ext_str + 1) != '/' && *(ext_str + 1) != '\0') { return phar_analyze_path(fname, ext_str, ext_len, for_create TSRMLS_CC); } } else { if (*(ext_str + 1) != '.' && *(ext_str + 1) != '/' && *(ext_str + 1) != '\0') { return phar_analyze_path(fname, ext_str, ext_len, for_create TSRMLS_CC); } } return FAILURE; } /* }}} */ /* * if executable is 1, only returns SUCCESS if the extension is one of the tar/zip .phar extensions * if executable is 0, it returns SUCCESS only if the filename does *not* contain ".phar" anywhere, and treats * the first extension as the filename extension * * if an extension is found, it sets ext_str to the location of the file extension in filename, * and ext_len to the length of the extension. * for urls like "phar://alias/oops" it instead sets ext_len to -1 and returns FAILURE, which tells * the calling function to use "alias" as the phar alias * * the last parameter should be set to tell the thing to assume that filename is the full path, and only to check the * extension rules, not to iterate. */ int phar_detect_phar_fname_ext(const char *filename, int filename_len, const char **ext_str, int *ext_len, int executable, int for_create, int is_complete TSRMLS_DC) /* {{{ */ { const char *pos, *slash; *ext_str = NULL; *ext_len = 0; if (!filename_len || filename_len == 1) { return FAILURE; } phar_request_initialize(TSRMLS_C); /* first check for alias in first segment */ pos = memchr(filename, '/', filename_len); if (pos && pos != filename) { /* check for url like http:// or phar:// */ if (*(pos - 1) == ':' && (pos - filename) < filename_len - 1 && *(pos + 1) == '/') { *ext_len = -2; *ext_str = NULL; return FAILURE; } if (zend_hash_exists(&(PHAR_GLOBALS->phar_alias_map), (char *) filename, pos - filename)) { *ext_str = pos; *ext_len = -1; return FAILURE; } if (PHAR_G(manifest_cached) && zend_hash_exists(&cached_alias, (char *) filename, pos - filename)) { *ext_str = pos; *ext_len = -1; return FAILURE; } } if (zend_hash_num_elements(&(PHAR_GLOBALS->phar_fname_map)) || PHAR_G(manifest_cached)) { phar_archive_data **pphar; if (is_complete) { if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), (char *) filename, filename_len, (void **)&pphar)) { *ext_str = filename + (filename_len - (*pphar)->ext_len); woohoo: *ext_len = (*pphar)->ext_len; if (executable == 2) { return SUCCESS; } if (executable == 1 && !(*pphar)->is_data) { return SUCCESS; } if (!executable && (*pphar)->is_data) { return SUCCESS; } return FAILURE; } if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, (char *) filename, filename_len, (void **)&pphar)) { *ext_str = filename + (filename_len - (*pphar)->ext_len); goto woohoo; } } else { phar_zstr key; char *str_key; uint keylen; ulong unused; zend_hash_internal_pointer_reset(&(PHAR_GLOBALS->phar_fname_map)); while (FAILURE != zend_hash_has_more_elements(&(PHAR_GLOBALS->phar_fname_map))) { if (HASH_KEY_NON_EXISTANT == zend_hash_get_current_key_ex(&(PHAR_GLOBALS->phar_fname_map), &key, &keylen, &unused, 0, NULL)) { break; } PHAR_STR(key, str_key); if (keylen > (uint) filename_len) { zend_hash_move_forward(&(PHAR_GLOBALS->phar_fname_map)); PHAR_STR_FREE(str_key); continue; } if (!memcmp(filename, str_key, keylen) && ((uint)filename_len == keylen || filename[keylen] == '/' || filename[keylen] == '\0')) { PHAR_STR_FREE(str_key); if (FAILURE == zend_hash_get_current_data(&(PHAR_GLOBALS->phar_fname_map), (void **) &pphar)) { break; } *ext_str = filename + (keylen - (*pphar)->ext_len); goto woohoo; } PHAR_STR_FREE(str_key); zend_hash_move_forward(&(PHAR_GLOBALS->phar_fname_map)); } if (PHAR_G(manifest_cached)) { zend_hash_internal_pointer_reset(&cached_phars); while (FAILURE != zend_hash_has_more_elements(&cached_phars)) { if (HASH_KEY_NON_EXISTANT == zend_hash_get_current_key_ex(&cached_phars, &key, &keylen, &unused, 0, NULL)) { break; } PHAR_STR(key, str_key); if (keylen > (uint) filename_len) { zend_hash_move_forward(&cached_phars); PHAR_STR_FREE(str_key); continue; } if (!memcmp(filename, str_key, keylen) && ((uint)filename_len == keylen || filename[keylen] == '/' || filename[keylen] == '\0')) { PHAR_STR_FREE(str_key); if (FAILURE == zend_hash_get_current_data(&cached_phars, (void **) &pphar)) { break; } *ext_str = filename + (keylen - (*pphar)->ext_len); goto woohoo; } PHAR_STR_FREE(str_key); zend_hash_move_forward(&cached_phars); } } } } pos = memchr(filename + 1, '.', filename_len); next_extension: if (!pos) { return FAILURE; } while (pos != filename && (*(pos - 1) == '/' || *(pos - 1) == '\0')) { pos = memchr(pos + 1, '.', filename_len - (pos - filename) + 1); if (!pos) { return FAILURE; } } slash = memchr(pos, '/', filename_len - (pos - filename)); if (!slash) { /* this is a url like "phar://blah.phar" with no directory */ *ext_str = pos; *ext_len = strlen(pos); /* file extension must contain "phar" */ switch (phar_check_str(filename, *ext_str, *ext_len, executable, for_create TSRMLS_CC)) { case SUCCESS: return SUCCESS; case FAILURE: /* we are at the end of the string, so we fail */ return FAILURE; } } /* we've found an extension that ends at a directory separator */ *ext_str = pos; *ext_len = slash - pos; switch (phar_check_str(filename, *ext_str, *ext_len, executable, for_create TSRMLS_CC)) { case SUCCESS: return SUCCESS; case FAILURE: /* look for more extensions */ pos = strchr(pos + 1, '.'); if (pos) { *ext_str = NULL; *ext_len = 0; } goto next_extension; } return FAILURE; } /* }}} */ static int php_check_dots(const char *element, int n) /* {{{ */ { for(n--; n >= 0; --n) { if (element[n] != '.') { return 1; } } return 0; } /* }}} */ #define IS_DIRECTORY_UP(element, len) \ (len >= 2 && !php_check_dots(element, len)) #define IS_DIRECTORY_CURRENT(element, len) \ (len == 1 && element[0] == '.') #define IS_BACKSLASH(c) ((c) == '/') #ifdef COMPILE_DL_PHAR /* stupid-ass non-extern declaration in tsrm_strtok.h breaks dumbass MS compiler */ static inline int in_character_class(char ch, const char *delim) /* {{{ */ { while (*delim) { if (*delim == ch) { return 1; } ++delim; } return 0; } /* }}} */ char *tsrm_strtok_r(char *s, const char *delim, char **last) /* {{{ */ { char *token; if (s == NULL) { s = *last; } while (*s && in_character_class(*s, delim)) { ++s; } if (!*s) { return NULL; } token = s; while (*s && !in_character_class(*s, delim)) { ++s; } if (!*s) { *last = s; } else { *s = '\0'; *last = s + 1; } return token; } /* }}} */ #endif /** * Remove .. and . references within a phar filename */ char *phar_fix_filepath(char *path, int *new_len, int use_cwd TSRMLS_DC) /* {{{ */ { char newpath[MAXPATHLEN]; int newpath_len; char *ptr; char *tok; int ptr_length, path_length = *new_len; if (PHAR_G(cwd_len) && use_cwd && path_length > 2 && path[0] == '.' && path[1] == '/') { newpath_len = PHAR_G(cwd_len); memcpy(newpath, PHAR_G(cwd), newpath_len); } else { newpath[0] = '/'; newpath_len = 1; } ptr = path; if (*ptr == '/') { ++ptr; } tok = ptr; do { ptr = memchr(ptr, '/', path_length - (ptr - path)); } while (ptr && ptr - tok == 0 && *ptr == '/' && ++ptr && ++tok); if (!ptr && (path_length - (tok - path))) { switch (path_length - (tok - path)) { case 1: if (*tok == '.') { efree(path); *new_len = 1; return estrndup("/", 1); } break; case 2: if (tok[0] == '.' && tok[1] == '.') { efree(path); *new_len = 1; return estrndup("/", 1); } } return path; } while (ptr) { ptr_length = ptr - tok; last_time: if (IS_DIRECTORY_UP(tok, ptr_length)) { #define PREVIOUS newpath[newpath_len - 1] while (newpath_len > 1 && !IS_BACKSLASH(PREVIOUS)) { newpath_len--; } if (newpath[0] != '/') { newpath[newpath_len] = '\0'; } else if (newpath_len > 1) { --newpath_len; } } else if (!IS_DIRECTORY_CURRENT(tok, ptr_length)) { if (newpath_len > 1) { newpath[newpath_len++] = '/'; memcpy(newpath + newpath_len, tok, ptr_length+1); } else { memcpy(newpath + newpath_len, tok, ptr_length+1); } newpath_len += ptr_length; } if (ptr == path + path_length) { break; } tok = ++ptr; do { ptr = memchr(ptr, '/', path_length - (ptr - path)); } while (ptr && ptr - tok == 0 && *ptr == '/' && ++ptr && ++tok); if (!ptr && (path_length - (tok - path))) { ptr_length = path_length - (tok - path); ptr = path + path_length; goto last_time; } } efree(path); *new_len = newpath_len; return estrndup(newpath, newpath_len); } /* }}} */ /** * Process a phar stream name, ensuring we can handle any of: * * - whatever.phar * - whatever.phar.gz * - whatever.phar.bz2 * - whatever.phar.php * * Optionally the name might start with 'phar://' * * This is used by phar_parse_url() */ int phar_split_fname(char *filename, int filename_len, char **arch, int *arch_len, char **entry, int *entry_len, int executable, int for_create TSRMLS_DC) /* {{{ */ { const char *ext_str; #ifdef PHP_WIN32 char *save; #endif int ext_len, free_filename = 0; if (!strncasecmp(filename, "phar://", 7)) { filename += 7; filename_len -= 7; } ext_len = 0; #ifdef PHP_WIN32 free_filename = 1; save = filename; filename = estrndup(filename, filename_len); phar_unixify_path_separators(filename, filename_len); #endif if (phar_detect_phar_fname_ext(filename, filename_len, &ext_str, &ext_len, executable, for_create, 0 TSRMLS_CC) == FAILURE) { if (ext_len != -1) { if (!ext_str) { /* no / detected, restore arch for error message */ #ifdef PHP_WIN32 *arch = save; #else *arch = filename; #endif } if (free_filename) { efree(filename); } return FAILURE; } ext_len = 0; /* no extension detected - instead we are dealing with an alias */ } *arch_len = ext_str - filename + ext_len; *arch = estrndup(filename, *arch_len); if (ext_str[ext_len]) { *entry_len = filename_len - *arch_len; *entry = estrndup(ext_str+ext_len, *entry_len); #ifdef PHP_WIN32 phar_unixify_path_separators(*entry, *entry_len); #endif *entry = phar_fix_filepath(*entry, entry_len, 0 TSRMLS_CC); } else { *entry_len = 1; *entry = estrndup("/", 1); } if (free_filename) { efree(filename); } return SUCCESS; } /* }}} */ /** * Invoked when a user calls Phar::mapPhar() from within an executing .phar * to set up its manifest directly */ int phar_open_executed_filename(char *alias, int alias_len, char **error TSRMLS_DC) /* {{{ */ { char *fname; zval *halt_constant; php_stream *fp; int fname_len; char *actual = NULL; int ret; if (error) { *error = NULL; } fname = (char*)zend_get_executed_filename(TSRMLS_C); fname_len = strlen(fname); if (phar_open_parsed_phar(fname, fname_len, alias, alias_len, 0, REPORT_ERRORS, NULL, 0 TSRMLS_CC) == SUCCESS) { return SUCCESS; } if (!strcmp(fname, "[no active file]")) { if (error) { spprintf(error, 0, "cannot initialize a phar outside of PHP execution"); } return FAILURE; } MAKE_STD_ZVAL(halt_constant); if (0 == zend_get_constant("__COMPILER_HALT_OFFSET__", 24, halt_constant TSRMLS_CC)) { FREE_ZVAL(halt_constant); if (error) { spprintf(error, 0, "__HALT_COMPILER(); must be declared in a phar"); } return FAILURE; } FREE_ZVAL(halt_constant); #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { return FAILURE; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { return FAILURE; } fp = php_stream_open_wrapper(fname, "rb", IGNORE_URL|STREAM_MUST_SEEK|REPORT_ERRORS, &actual); if (!fp) { if (error) { spprintf(error, 0, "unable to open phar for reading \"%s\"", fname); } if (actual) { efree(actual); } return FAILURE; } if (actual) { fname = actual; fname_len = strlen(actual); } ret = phar_open_from_fp(fp, fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, 0, error TSRMLS_CC); if (actual) { efree(actual); } return ret; } /* }}} */ /** * Validate the CRC32 of a file opened from within the phar */ int phar_postprocess_file(phar_entry_data *idata, php_uint32 crc32, char **error, int process_zip TSRMLS_DC) /* {{{ */ { php_uint32 crc = ~0; int len = idata->internal_file->uncompressed_filesize; php_stream *fp = idata->fp; phar_entry_info *entry = idata->internal_file; if (error) { *error = NULL; } if (entry->is_zip && process_zip > 0) { /* verify local file header */ phar_zip_file_header local; phar_zip_data_desc desc; if (SUCCESS != phar_open_archive_fp(idata->phar TSRMLS_CC)) { spprintf(error, 0, "phar error: unable to open zip-based phar archive \"%s\" to verify local file header for file \"%s\"", idata->phar->fname, entry->filename); return FAILURE; } php_stream_seek(phar_get_entrypfp(idata->internal_file TSRMLS_CC), entry->header_offset, SEEK_SET); if (sizeof(local) != php_stream_read(phar_get_entrypfp(idata->internal_file TSRMLS_CC), (char *) &local, sizeof(local))) { spprintf(error, 0, "phar error: internal corruption of zip-based phar \"%s\" (cannot read local file header for file \"%s\")", idata->phar->fname, entry->filename); return FAILURE; } /* check for data descriptor */ if (((PHAR_ZIP_16(local.flags)) & 0x8) == 0x8) { php_stream_seek(phar_get_entrypfp(idata->internal_file TSRMLS_CC), entry->header_offset + sizeof(local) + PHAR_ZIP_16(local.filename_len) + PHAR_ZIP_16(local.extra_len) + entry->compressed_filesize, SEEK_SET); if (sizeof(desc) != php_stream_read(phar_get_entrypfp(idata->internal_file TSRMLS_CC), (char *) &desc, sizeof(desc))) { spprintf(error, 0, "phar error: internal corruption of zip-based phar \"%s\" (cannot read local data descriptor for file \"%s\")", idata->phar->fname, entry->filename); return FAILURE; } if (desc.signature[0] == 'P' && desc.signature[1] == 'K') { memcpy(&(local.crc32), &(desc.crc32), 12); } else { /* old data descriptors have no signature */ memcpy(&(local.crc32), &desc, 12); } } /* verify local header */ if (entry->filename_len != PHAR_ZIP_16(local.filename_len) || entry->crc32 != PHAR_ZIP_32(local.crc32) || entry->uncompressed_filesize != PHAR_ZIP_32(local.uncompsize) || entry->compressed_filesize != PHAR_ZIP_32(local.compsize)) { spprintf(error, 0, "phar error: internal corruption of zip-based phar \"%s\" (local header of file \"%s\" does not match central directory)", idata->phar->fname, entry->filename); return FAILURE; } /* construct actual offset to file start - local extra_len can be different from central extra_len */ entry->offset = entry->offset_abs = sizeof(local) + entry->header_offset + PHAR_ZIP_16(local.filename_len) + PHAR_ZIP_16(local.extra_len); if (idata->zero && idata->zero != entry->offset_abs) { idata->zero = entry->offset_abs; } } if (process_zip == 1) { return SUCCESS; } php_stream_seek(fp, idata->zero, SEEK_SET); while (len--) { CRC32(crc, php_stream_getc(fp)); } php_stream_seek(fp, idata->zero, SEEK_SET); if (~crc == crc32) { entry->is_crc_checked = 1; return SUCCESS; } else { spprintf(error, 0, "phar error: internal corruption of phar \"%s\" (crc32 mismatch on file \"%s\")", idata->phar->fname, entry->filename); return FAILURE; } } /* }}} */ static inline void phar_set_32(char *buffer, int var) /* {{{ */ { #ifdef WORDS_BIGENDIAN *((buffer) + 3) = (unsigned char) (((var) >> 24) & 0xFF); *((buffer) + 2) = (unsigned char) (((var) >> 16) & 0xFF); *((buffer) + 1) = (unsigned char) (((var) >> 8) & 0xFF); *((buffer) + 0) = (unsigned char) ((var) & 0xFF); #else memcpy(buffer, &var, sizeof(var)); #endif } /* }}} */ static int phar_flush_clean_deleted_apply(void *data TSRMLS_DC) /* {{{ */ { phar_entry_info *entry = (phar_entry_info *)data; if (entry->fp_refcount <= 0 && entry->is_deleted) { return ZEND_HASH_APPLY_REMOVE; } else { return ZEND_HASH_APPLY_KEEP; } } /* }}} */ #include "stub.h" char *phar_create_default_stub(const char *index_php, const char *web_index, size_t *len, char **error TSRMLS_DC) /* {{{ */ { char *stub = NULL; int index_len, web_len; size_t dummy; if (!len) { len = &dummy; } if (error) { *error = NULL; } if (!index_php) { index_php = "index.php"; } if (!web_index) { web_index = "index.php"; } index_len = strlen(index_php); web_len = strlen(web_index); if (index_len > 400) { /* ridiculous size not allowed for index.php startup filename */ if (error) { spprintf(error, 0, "Illegal filename passed in for stub creation, was %d characters long, and only 400 or less is allowed", index_len); return NULL; } } if (web_len > 400) { /* ridiculous size not allowed for index.php startup filename */ if (error) { spprintf(error, 0, "Illegal web filename passed in for stub creation, was %d characters long, and only 400 or less is allowed", web_len); return NULL; } } phar_get_stub(index_php, web_index, len, &stub, index_len+1, web_len+1 TSRMLS_CC); return stub; } /* }}} */ /** * Save phar contents to disk * * user_stub contains either a string, or a resource pointer, if len is a negative length. * user_stub and len should be both 0 if the default or existing stub should be used */ int phar_flush(phar_archive_data *phar, char *user_stub, long len, int convert, char **error TSRMLS_DC) /* {{{ */ { char halt_stub[] = "__HALT_COMPILER();"; char *newstub, *tmp; phar_entry_info *entry, *newentry; int halt_offset, restore_alias_len, global_flags = 0, closeoldfile; char *pos, has_dirs = 0; char manifest[18], entry_buffer[24]; off_t manifest_ftell; long offset; size_t wrote; php_uint32 manifest_len, mytime, loc, new_manifest_count; php_uint32 newcrc32; php_stream *file, *oldfile, *newfile, *stubfile; php_stream_filter *filter; php_serialize_data_t metadata_hash; smart_str main_metadata_str = {0}; int free_user_stub, free_fp = 1, free_ufp = 1; if (phar->is_persistent) { if (error) { spprintf(error, 0, "internal error: attempt to flush cached zip-based phar \"%s\"", phar->fname); } return EOF; } if (error) { *error = NULL; } if (!zend_hash_num_elements(&phar->manifest) && !user_stub) { return EOF; } zend_hash_clean(&phar->virtual_dirs); if (phar->is_zip) { return phar_zip_flush(phar, user_stub, len, convert, error TSRMLS_CC); } if (phar->is_tar) { return phar_tar_flush(phar, user_stub, len, convert, error TSRMLS_CC); } if (PHAR_G(readonly)) { return EOF; } if (phar->fp && !phar->is_brandnew) { oldfile = phar->fp; closeoldfile = 0; php_stream_rewind(oldfile); } else { oldfile = php_stream_open_wrapper(phar->fname, "rb", 0, NULL); closeoldfile = oldfile != NULL; } newfile = php_stream_fopen_tmpfile(); if (!newfile) { if (error) { spprintf(error, 0, "unable to create temporary file"); } if (closeoldfile) { php_stream_close(oldfile); } return EOF; } if (user_stub) { if (len < 0) { /* resource passed in */ if (!(php_stream_from_zval_no_verify(stubfile, (zval **)user_stub))) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to access resource to copy stub to new phar \"%s\"", phar->fname); } return EOF; } if (len == -1) { len = PHP_STREAM_COPY_ALL; } else { len = -len; } user_stub = 0; #if PHP_MAJOR_VERSION >= 6 if (!(len = php_stream_copy_to_mem(stubfile, (void **) &user_stub, len, 0)) || !user_stub) { #else if (!(len = php_stream_copy_to_mem(stubfile, &user_stub, len, 0)) || !user_stub) { #endif if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to read resource to copy stub to new phar \"%s\"", phar->fname); } return EOF; } free_user_stub = 1; } else { free_user_stub = 0; } tmp = estrndup(user_stub, len); if ((pos = php_stristr(tmp, halt_stub, len, sizeof(halt_stub) - 1)) == NULL) { efree(tmp); if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "illegal stub for phar \"%s\"", phar->fname); } if (free_user_stub) { efree(user_stub); } return EOF; } pos = user_stub + (pos - tmp); efree(tmp); len = pos - user_stub + 18; if ((size_t)len != php_stream_write(newfile, user_stub, len) || 5 != php_stream_write(newfile, " ?>\r\n", 5)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to create stub from string in new phar \"%s\"", phar->fname); } if (free_user_stub) { efree(user_stub); } return EOF; } phar->halt_offset = len + 5; if (free_user_stub) { efree(user_stub); } } else { size_t written; if (!user_stub && phar->halt_offset && oldfile && !phar->is_brandnew) { phar_stream_copy_to_stream(oldfile, newfile, phar->halt_offset, &written); newstub = NULL; } else { /* this is either a brand new phar or a default stub overwrite */ newstub = phar_create_default_stub(NULL, NULL, &(phar->halt_offset), NULL TSRMLS_CC); written = php_stream_write(newfile, newstub, phar->halt_offset); } if (phar->halt_offset != written) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { if (newstub) { spprintf(error, 0, "unable to create stub in new phar \"%s\"", phar->fname); } else { spprintf(error, 0, "unable to copy stub of old phar to new phar \"%s\"", phar->fname); } } if (newstub) { efree(newstub); } return EOF; } if (newstub) { efree(newstub); } } manifest_ftell = php_stream_tell(newfile); halt_offset = manifest_ftell; /* Check whether we can get rid of some of the deleted entries which are * unused. However some might still be in use so even after this clean-up * we need to skip entries marked is_deleted. */ zend_hash_apply(&phar->manifest, phar_flush_clean_deleted_apply TSRMLS_CC); /* compress as necessary, calculate crcs, serialize meta-data, manifest size, and file sizes */ main_metadata_str.c = 0; if (phar->metadata) { PHP_VAR_SERIALIZE_INIT(metadata_hash); php_var_serialize(&main_metadata_str, &phar->metadata, &metadata_hash TSRMLS_CC); PHP_VAR_SERIALIZE_DESTROY(metadata_hash); } else { main_metadata_str.len = 0; } new_manifest_count = 0; offset = 0; for (zend_hash_internal_pointer_reset(&phar->manifest); zend_hash_has_more_elements(&phar->manifest) == SUCCESS; zend_hash_move_forward(&phar->manifest)) { if (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) { continue; } if (entry->cfp) { /* did we forget to get rid of cfp last time? */ php_stream_close(entry->cfp); entry->cfp = 0; } if (entry->is_deleted || entry->is_mounted) { /* remove this from the new phar */ continue; } if (!entry->is_modified && entry->fp_refcount) { /* open file pointers refer to this fp, do not free the stream */ switch (entry->fp_type) { case PHAR_FP: free_fp = 0; break; case PHAR_UFP: free_ufp = 0; default: break; } } /* after excluding deleted files, calculate manifest size in bytes and number of entries */ ++new_manifest_count; phar_add_virtual_dirs(phar, entry->filename, entry->filename_len TSRMLS_CC); if (entry->is_dir) { /* we use this to calculate API version, 1.1.1 is used for phars with directories */ has_dirs = 1; } if (entry->metadata) { if (entry->metadata_str.c) { smart_str_free(&entry->metadata_str); } entry->metadata_str.c = 0; entry->metadata_str.len = 0; PHP_VAR_SERIALIZE_INIT(metadata_hash); php_var_serialize(&entry->metadata_str, &entry->metadata, &metadata_hash TSRMLS_CC); PHP_VAR_SERIALIZE_DESTROY(metadata_hash); } else { if (entry->metadata_str.c) { smart_str_free(&entry->metadata_str); } entry->metadata_str.c = 0; entry->metadata_str.len = 0; } /* 32 bits for filename length, length of filename, manifest + metadata, and add 1 for trailing / if a directory */ offset += 4 + entry->filename_len + sizeof(entry_buffer) + entry->metadata_str.len + (entry->is_dir ? 1 : 0); /* compress and rehash as necessary */ if ((oldfile && !entry->is_modified) || entry->is_dir) { if (entry->fp_type == PHAR_UFP) { /* reset so we can copy the compressed data over */ entry->fp_type = PHAR_FP; } continue; } if (!phar_get_efp(entry, 0 TSRMLS_CC)) { /* re-open internal file pointer just-in-time */ newentry = phar_open_jit(phar, entry, error TSRMLS_CC); if (!newentry) { /* major problem re-opening, so we ignore this file and the error */ efree(*error); *error = NULL; continue; } entry = newentry; } file = phar_get_efp(entry, 0 TSRMLS_CC); if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 1 TSRMLS_CC)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } newcrc32 = ~0; mytime = entry->uncompressed_filesize; for (loc = 0;loc < mytime; ++loc) { CRC32(newcrc32, php_stream_getc(file)); } entry->crc32 = ~newcrc32; entry->is_crc_checked = 1; if (!(entry->flags & PHAR_ENT_COMPRESSION_MASK)) { /* not compressed */ entry->compressed_filesize = entry->uncompressed_filesize; continue; } filter = php_stream_filter_create(phar_compress_filter(entry, 0), NULL, 0 TSRMLS_CC); if (!filter) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (entry->flags & PHAR_ENT_COMPRESSED_GZ) { if (error) { spprintf(error, 0, "unable to gzip compress file \"%s\" to new phar \"%s\"", entry->filename, phar->fname); } } else { if (error) { spprintf(error, 0, "unable to bzip2 compress file \"%s\" to new phar \"%s\"", entry->filename, phar->fname); } } return EOF; } /* create new file that holds the compressed version */ /* work around inability to specify freedom in write and strictness in read count */ entry->cfp = php_stream_fopen_tmpfile(); if (!entry->cfp) { if (error) { spprintf(error, 0, "unable to create temporary file"); } if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); return EOF; } php_stream_flush(file); if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 0 TSRMLS_CC)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } php_stream_filter_append((&entry->cfp->writefilters), filter); if (SUCCESS != phar_stream_copy_to_stream(file, entry->cfp, entry->uncompressed_filesize, NULL)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to copy compressed file contents of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } php_stream_filter_flush(filter, 1); php_stream_flush(entry->cfp); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_seek(entry->cfp, 0, SEEK_END); entry->compressed_filesize = (php_uint32) php_stream_tell(entry->cfp); /* generate crc on compressed file */ php_stream_rewind(entry->cfp); entry->old_flags = entry->flags; entry->is_modified = 1; global_flags |= (entry->flags & PHAR_ENT_COMPRESSION_MASK); } global_flags |= PHAR_HDR_SIGNATURE; /* write out manifest pre-header */ /* 4: manifest length * 4: manifest entry count * 2: phar version * 4: phar global flags * 4: alias length * ?: the alias itself * 4: phar metadata length * ?: phar metadata */ restore_alias_len = phar->alias_len; if (phar->is_temporary_alias) { phar->alias_len = 0; } manifest_len = offset + phar->alias_len + sizeof(manifest) + main_metadata_str.len; phar_set_32(manifest, manifest_len); phar_set_32(manifest+4, new_manifest_count); if (has_dirs) { *(manifest + 8) = (unsigned char) (((PHAR_API_VERSION) >> 8) & 0xFF); *(manifest + 9) = (unsigned char) (((PHAR_API_VERSION) & 0xF0)); } else { *(manifest + 8) = (unsigned char) (((PHAR_API_VERSION_NODIR) >> 8) & 0xFF); *(manifest + 9) = (unsigned char) (((PHAR_API_VERSION_NODIR) & 0xF0)); } phar_set_32(manifest+10, global_flags); phar_set_32(manifest+14, phar->alias_len); /* write the manifest header */ if (sizeof(manifest) != php_stream_write(newfile, manifest, sizeof(manifest)) || (size_t)phar->alias_len != php_stream_write(newfile, phar->alias, phar->alias_len)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); phar->alias_len = restore_alias_len; if (error) { spprintf(error, 0, "unable to write manifest header of new phar \"%s\"", phar->fname); } return EOF; } phar->alias_len = restore_alias_len; phar_set_32(manifest, main_metadata_str.len); if (4 != php_stream_write(newfile, manifest, 4) || (main_metadata_str.len && main_metadata_str.len != php_stream_write(newfile, main_metadata_str.c, main_metadata_str.len))) { smart_str_free(&main_metadata_str); if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); phar->alias_len = restore_alias_len; if (error) { spprintf(error, 0, "unable to write manifest meta-data of new phar \"%s\"", phar->fname); } return EOF; } smart_str_free(&main_metadata_str); /* re-calculate the manifest location to simplify later code */ manifest_ftell = php_stream_tell(newfile); /* now write the manifest */ for (zend_hash_internal_pointer_reset(&phar->manifest); zend_hash_has_more_elements(&phar->manifest) == SUCCESS; zend_hash_move_forward(&phar->manifest)) { if (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) { continue; } if (entry->is_deleted || entry->is_mounted) { /* remove this from the new phar if deleted, ignore if mounted */ continue; } if (entry->is_dir) { /* add 1 for trailing slash */ phar_set_32(entry_buffer, entry->filename_len + 1); } else { phar_set_32(entry_buffer, entry->filename_len); } if (4 != php_stream_write(newfile, entry_buffer, 4) || entry->filename_len != php_stream_write(newfile, entry->filename, entry->filename_len) || (entry->is_dir && 1 != php_stream_write(newfile, "/", 1))) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { if (entry->is_dir) { spprintf(error, 0, "unable to write filename of directory \"%s\" to manifest of new phar \"%s\"", entry->filename, phar->fname); } else { spprintf(error, 0, "unable to write filename of file \"%s\" to manifest of new phar \"%s\"", entry->filename, phar->fname); } } return EOF; } /* set the manifest meta-data: 4: uncompressed filesize 4: creation timestamp 4: compressed filesize 4: crc32 4: flags 4: metadata-len +: metadata */ mytime = time(NULL); phar_set_32(entry_buffer, entry->uncompressed_filesize); phar_set_32(entry_buffer+4, mytime); phar_set_32(entry_buffer+8, entry->compressed_filesize); phar_set_32(entry_buffer+12, entry->crc32); phar_set_32(entry_buffer+16, entry->flags); phar_set_32(entry_buffer+20, entry->metadata_str.len); if (sizeof(entry_buffer) != php_stream_write(newfile, entry_buffer, sizeof(entry_buffer)) || entry->metadata_str.len != php_stream_write(newfile, entry->metadata_str.c, entry->metadata_str.len)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to write temporary manifest of file \"%s\" to manifest of new phar \"%s\"", entry->filename, phar->fname); } return EOF; } } /* now copy the actual file data to the new phar */ offset = php_stream_tell(newfile); for (zend_hash_internal_pointer_reset(&phar->manifest); zend_hash_has_more_elements(&phar->manifest) == SUCCESS; zend_hash_move_forward(&phar->manifest)) { if (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) { continue; } if (entry->is_deleted || entry->is_dir || entry->is_mounted) { continue; } if (entry->cfp) { file = entry->cfp; php_stream_rewind(file); } else { file = phar_get_efp(entry, 0 TSRMLS_CC); if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 0 TSRMLS_CC)) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } } if (!file) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to seek to start of file \"%s\" while creating new phar \"%s\"", entry->filename, phar->fname); } return EOF; } /* this will have changed for all files that have either changed compression or been modified */ entry->offset = entry->offset_abs = offset; offset += entry->compressed_filesize; if (phar_stream_copy_to_stream(file, newfile, entry->compressed_filesize, &wrote) == FAILURE) { if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to write contents of file \"%s\" to new phar \"%s\"", entry->filename, phar->fname); } return EOF; } entry->is_modified = 0; if (entry->cfp) { php_stream_close(entry->cfp); entry->cfp = NULL; } if (entry->fp_type == PHAR_MOD) { /* this fp is in use by a phar_entry_data returned by phar_get_entry_data, it will be closed when the phar_entry_data is phar_entry_delref'ed */ if (entry->fp_refcount == 0 && entry->fp != phar->fp && entry->fp != phar->ufp) { php_stream_close(entry->fp); } entry->fp = NULL; entry->fp_type = PHAR_FP; } else if (entry->fp_type == PHAR_UFP) { entry->fp_type = PHAR_FP; } } /* append signature */ if (global_flags & PHAR_HDR_SIGNATURE) { char sig_buf[4]; php_stream_rewind(newfile); if (phar->signature) { efree(phar->signature); phar->signature = NULL; } switch(phar->sig_flags) { #ifndef PHAR_HASH_OK case PHAR_SIG_SHA512: case PHAR_SIG_SHA256: if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); if (error) { spprintf(error, 0, "unable to write contents of file \"%s\" to new phar \"%s\" with requested hash type", entry->filename, phar->fname); } return EOF; #endif default: { char *digest = NULL; int digest_len; if (FAILURE == phar_create_signature(phar, newfile, &digest, &digest_len, error TSRMLS_CC)) { if (error) { char *save = *error; spprintf(error, 0, "phar error: unable to write signature: %s", save); efree(save); } if (digest) { efree(digest); } if (closeoldfile) { php_stream_close(oldfile); } php_stream_close(newfile); return EOF; } php_stream_write(newfile, digest, digest_len); efree(digest); if (phar->sig_flags == PHAR_SIG_OPENSSL) { phar_set_32(sig_buf, digest_len); php_stream_write(newfile, sig_buf, 4); } break; } } phar_set_32(sig_buf, phar->sig_flags); php_stream_write(newfile, sig_buf, 4); php_stream_write(newfile, "GBMB", 4); } /* finally, close the temp file, rename the original phar, move the temp to the old phar, unlink the old phar, and reload it into memory */ if (phar->fp && free_fp) { php_stream_close(phar->fp); } if (phar->ufp) { if (free_ufp) { php_stream_close(phar->ufp); } phar->ufp = NULL; } if (closeoldfile) { php_stream_close(oldfile); } phar->internal_file_start = halt_offset + manifest_len + 4; phar->halt_offset = halt_offset; phar->is_brandnew = 0; php_stream_rewind(newfile); if (phar->donotflush) { /* deferred flush */ phar->fp = newfile; } else { phar->fp = php_stream_open_wrapper(phar->fname, "w+b", IGNORE_URL|STREAM_MUST_SEEK|REPORT_ERRORS, NULL); if (!phar->fp) { phar->fp = newfile; if (error) { spprintf(error, 4096, "unable to open new phar \"%s\" for writing", phar->fname); } return EOF; } if (phar->flags & PHAR_FILE_COMPRESSED_GZ) { /* to properly compress, we have to tell zlib to add a zlib header */ zval filterparams; array_init(&filterparams); add_assoc_long(&filterparams, "window", MAX_WBITS+16); filter = php_stream_filter_create("zlib.deflate", &filterparams, php_stream_is_persistent(phar->fp) TSRMLS_CC); zval_dtor(&filterparams); if (!filter) { if (error) { spprintf(error, 4096, "unable to compress all contents of phar \"%s\" using zlib, PHP versions older than 5.2.6 have a buggy zlib", phar->fname); } return EOF; } php_stream_filter_append(&phar->fp->writefilters, filter); phar_stream_copy_to_stream(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL); php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(phar->fp); /* use the temp stream as our base */ phar->fp = newfile; } else if (phar->flags & PHAR_FILE_COMPRESSED_BZ2) { filter = php_stream_filter_create("bzip2.compress", NULL, php_stream_is_persistent(phar->fp) TSRMLS_CC); php_stream_filter_append(&phar->fp->writefilters, filter); phar_stream_copy_to_stream(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL); php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1 TSRMLS_CC); php_stream_close(phar->fp); /* use the temp stream as our base */ phar->fp = newfile; } else { phar_stream_copy_to_stream(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL); /* we could also reopen the file in "rb" mode but there is no need for that */ php_stream_close(newfile); } } if (-1 == php_stream_seek(phar->fp, phar->halt_offset, SEEK_SET)) { if (error) { spprintf(error, 0, "unable to seek to __HALT_COMPILER(); in new phar \"%s\"", phar->fname); } return EOF; } return EOF; } /* }}} */ #ifdef COMPILE_DL_PHAR ZEND_GET_MODULE(phar) #endif /* {{{ phar_functions[] * * Every user visible function must have an entry in phar_functions[]. */ zend_function_entry phar_functions[] = { PHP_FE_END }; /* }}}*/ static size_t phar_zend_stream_reader(void *handle, char *buf, size_t len TSRMLS_DC) /* {{{ */ { return php_stream_read(phar_get_pharfp((phar_archive_data*)handle TSRMLS_CC), buf, len); } /* }}} */ #if PHP_VERSION_ID >= 50300 static size_t phar_zend_stream_fsizer(void *handle TSRMLS_DC) /* {{{ */ { return ((phar_archive_data*)handle)->halt_offset + 32; } /* }}} */ #else /* PHP_VERSION_ID */ static long phar_stream_fteller_for_zend(void *handle TSRMLS_DC) /* {{{ */ { return (long)php_stream_tell(phar_get_pharfp((phar_archive_data*)handle TSRMLS_CC)); } /* }}} */ #endif zend_op_array *(*phar_orig_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC); #if PHP_VERSION_ID >= 50300 #define phar_orig_zend_open zend_stream_open_function static char *phar_resolve_path(const char *filename, int filename_len TSRMLS_DC) { return phar_find_in_include_path((char *) filename, filename_len, NULL TSRMLS_CC); } #else int (*phar_orig_zend_open)(const char *filename, zend_file_handle *handle TSRMLS_DC); #endif static zend_op_array *phar_compile_file(zend_file_handle *file_handle, int type TSRMLS_DC) /* {{{ */ { zend_op_array *res; char *name = NULL; int failed; phar_archive_data *phar; if (!file_handle || !file_handle->filename) { return phar_orig_compile_file(file_handle, type TSRMLS_CC); } if (strstr(file_handle->filename, ".phar") && !strstr(file_handle->filename, "://")) { if (SUCCESS == phar_open_from_filename((char*)file_handle->filename, strlen(file_handle->filename), NULL, 0, 0, &phar, NULL TSRMLS_CC)) { if (phar->is_zip || phar->is_tar) { zend_file_handle f = *file_handle; /* zip or tar-based phar */ spprintf(&name, 4096, "phar://%s/%s", file_handle->filename, ".phar/stub.php"); if (SUCCESS == phar_orig_zend_open((const char *)name, file_handle TSRMLS_CC)) { efree(name); name = NULL; file_handle->filename = f.filename; if (file_handle->opened_path) { efree(file_handle->opened_path); } file_handle->opened_path = f.opened_path; file_handle->free_filename = f.free_filename; } else { *file_handle = f; } } else if (phar->flags & PHAR_FILE_COMPRESSION_MASK) { /* compressed phar */ #if PHP_VERSION_ID >= 50300 file_handle->type = ZEND_HANDLE_STREAM; /* we do our own reading directly from the phar, don't change the next line */ file_handle->handle.stream.handle = phar; file_handle->handle.stream.reader = phar_zend_stream_reader; file_handle->handle.stream.closer = NULL; file_handle->handle.stream.fsizer = phar_zend_stream_fsizer; file_handle->handle.stream.isatty = 0; phar->is_persistent ? php_stream_rewind(PHAR_GLOBALS->cached_fp[phar->phar_pos].fp) : php_stream_rewind(phar->fp); memset(&file_handle->handle.stream.mmap, 0, sizeof(file_handle->handle.stream.mmap)); #else /* PHP_VERSION_ID */ file_handle->type = ZEND_HANDLE_STREAM; /* we do our own reading directly from the phar, don't change the next line */ file_handle->handle.stream.handle = phar; file_handle->handle.stream.reader = phar_zend_stream_reader; file_handle->handle.stream.closer = NULL; /* don't close - let phar handle this one */ file_handle->handle.stream.fteller = phar_stream_fteller_for_zend; file_handle->handle.stream.interactive = 0; phar->is_persistent ? php_stream_rewind(PHAR_GLOBALS->cached_fp[phar->phar_pos].fp) : php_stream_rewind(phar->fp); #endif } } } zend_try { failed = 0; res = phar_orig_compile_file(file_handle, type TSRMLS_CC); } zend_catch { failed = 1; res = NULL; } zend_end_try(); if (name) { efree(name); } if (failed) { zend_bailout(); } return res; } /* }}} */ #if PHP_VERSION_ID < 50300 int phar_zend_open(const char *filename, zend_file_handle *handle TSRMLS_DC) /* {{{ */ { char *arch, *entry; int arch_len, entry_len; /* this code is obsoleted in php 5.3 */ entry = (char *) filename; if (!IS_ABSOLUTE_PATH(entry, strlen(entry)) && !strstr(entry, "://")) { phar_archive_data **pphar = NULL; char *fname; int fname_len; fname = (char*)zend_get_executed_filename(TSRMLS_C); fname_len = strlen(fname); if (fname_len > 7 && !strncasecmp(fname, "phar://", 7)) { if (SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 1, 0 TSRMLS_CC)) { zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), arch, arch_len, (void **) &pphar); if (!pphar && PHAR_G(manifest_cached)) { zend_hash_find(&cached_phars, arch, arch_len, (void **) &pphar); } efree(arch); efree(entry); } } /* retrieving an include within the current directory, so use this if possible */ if (!(entry = phar_find_in_include_path((char *) filename, strlen(filename), NULL TSRMLS_CC))) { /* this file is not in the phar, use the original path */ goto skip_phar; } if (SUCCESS == phar_orig_zend_open(entry, handle TSRMLS_CC)) { if (!handle->opened_path) { handle->opened_path = entry; } if (entry != filename) { handle->free_filename = 1; } return SUCCESS; } if (entry != filename) { efree(entry); } return FAILURE; } skip_phar: return phar_orig_zend_open(filename, handle TSRMLS_CC); } /* }}} */ #endif typedef zend_op_array* (zend_compile_t)(zend_file_handle*, int TSRMLS_DC); typedef zend_compile_t* (compile_hook)(zend_compile_t *ptr); PHP_GINIT_FUNCTION(phar) /* {{{ */ { phar_mime_type mime; memset(phar_globals, 0, sizeof(zend_phar_globals)); phar_globals->readonly = 1; zend_hash_init(&phar_globals->mime_types, 0, NULL, NULL, 1); #define PHAR_SET_MIME(mimetype, ret, fileext) \ mime.mime = mimetype; \ mime.len = sizeof((mimetype))+1; \ mime.type = ret; \ zend_hash_add(&phar_globals->mime_types, fileext, sizeof(fileext)-1, (void *)&mime, sizeof(phar_mime_type), NULL); \ PHAR_SET_MIME("text/html", PHAR_MIME_PHPS, "phps") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "c") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "cc") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "cpp") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "c++") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "dtd") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "h") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "log") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "rng") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "txt") PHAR_SET_MIME("text/plain", PHAR_MIME_OTHER, "xsd") PHAR_SET_MIME("", PHAR_MIME_PHP, "php") PHAR_SET_MIME("", PHAR_MIME_PHP, "inc") PHAR_SET_MIME("video/avi", PHAR_MIME_OTHER, "avi") PHAR_SET_MIME("image/bmp", PHAR_MIME_OTHER, "bmp") PHAR_SET_MIME("text/css", PHAR_MIME_OTHER, "css") PHAR_SET_MIME("image/gif", PHAR_MIME_OTHER, "gif") PHAR_SET_MIME("text/html", PHAR_MIME_OTHER, "htm") PHAR_SET_MIME("text/html", PHAR_MIME_OTHER, "html") PHAR_SET_MIME("text/html", PHAR_MIME_OTHER, "htmls") PHAR_SET_MIME("image/x-ico", PHAR_MIME_OTHER, "ico") PHAR_SET_MIME("image/jpeg", PHAR_MIME_OTHER, "jpe") PHAR_SET_MIME("image/jpeg", PHAR_MIME_OTHER, "jpg") PHAR_SET_MIME("image/jpeg", PHAR_MIME_OTHER, "jpeg") PHAR_SET_MIME("application/x-javascript", PHAR_MIME_OTHER, "js") PHAR_SET_MIME("audio/midi", PHAR_MIME_OTHER, "midi") PHAR_SET_MIME("audio/midi", PHAR_MIME_OTHER, "mid") PHAR_SET_MIME("audio/mod", PHAR_MIME_OTHER, "mod") PHAR_SET_MIME("movie/quicktime", PHAR_MIME_OTHER, "mov") PHAR_SET_MIME("audio/mp3", PHAR_MIME_OTHER, "mp3") PHAR_SET_MIME("video/mpeg", PHAR_MIME_OTHER, "mpg") PHAR_SET_MIME("video/mpeg", PHAR_MIME_OTHER, "mpeg") PHAR_SET_MIME("application/pdf", PHAR_MIME_OTHER, "pdf") PHAR_SET_MIME("image/png", PHAR_MIME_OTHER, "png") PHAR_SET_MIME("application/shockwave-flash", PHAR_MIME_OTHER, "swf") PHAR_SET_MIME("image/tiff", PHAR_MIME_OTHER, "tif") PHAR_SET_MIME("image/tiff", PHAR_MIME_OTHER, "tiff") PHAR_SET_MIME("audio/wav", PHAR_MIME_OTHER, "wav") PHAR_SET_MIME("image/xbm", PHAR_MIME_OTHER, "xbm") PHAR_SET_MIME("text/xml", PHAR_MIME_OTHER, "xml") phar_restore_orig_functions(TSRMLS_C); } /* }}} */ PHP_GSHUTDOWN_FUNCTION(phar) /* {{{ */ { zend_hash_destroy(&phar_globals->mime_types); } /* }}} */ PHP_MINIT_FUNCTION(phar) /* {{{ */ { REGISTER_INI_ENTRIES(); phar_orig_compile_file = zend_compile_file; zend_compile_file = phar_compile_file; #if PHP_VERSION_ID >= 50300 phar_save_resolve_path = zend_resolve_path; zend_resolve_path = phar_resolve_path; #else phar_orig_zend_open = zend_stream_open_function; zend_stream_open_function = phar_zend_open; #endif phar_object_init(TSRMLS_C); phar_intercept_functions_init(TSRMLS_C); phar_save_orig_functions(TSRMLS_C); return php_register_url_stream_wrapper("phar", &php_stream_phar_wrapper TSRMLS_CC); } /* }}} */ PHP_MSHUTDOWN_FUNCTION(phar) /* {{{ */ { php_unregister_url_stream_wrapper("phar" TSRMLS_CC); phar_intercept_functions_shutdown(TSRMLS_C); if (zend_compile_file == phar_compile_file) { zend_compile_file = phar_orig_compile_file; } #if PHP_VERSION_ID < 50300 if (zend_stream_open_function == phar_zend_open) { zend_stream_open_function = phar_orig_zend_open; } #endif if (PHAR_G(manifest_cached)) { zend_hash_destroy(&(cached_phars)); zend_hash_destroy(&(cached_alias)); } return SUCCESS; } /* }}} */ void phar_request_initialize(TSRMLS_D) /* {{{ */ { if (!PHAR_GLOBALS->request_init) { PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; PHAR_G(has_bz2) = zend_hash_exists(&module_registry, "bz2", sizeof("bz2")); PHAR_G(has_zlib) = zend_hash_exists(&module_registry, "zlib", sizeof("zlib")); PHAR_GLOBALS->request_init = 1; PHAR_GLOBALS->request_ends = 0; PHAR_GLOBALS->request_done = 0; zend_hash_init(&(PHAR_GLOBALS->phar_fname_map), 5, zend_get_hash_value, destroy_phar_data, 0); zend_hash_init(&(PHAR_GLOBALS->phar_persist_map), 5, zend_get_hash_value, NULL, 0); zend_hash_init(&(PHAR_GLOBALS->phar_alias_map), 5, zend_get_hash_value, NULL, 0); if (PHAR_G(manifest_cached)) { phar_archive_data **pphar; phar_entry_fp *stuff = (phar_entry_fp *) ecalloc(zend_hash_num_elements(&cached_phars), sizeof(phar_entry_fp)); for (zend_hash_internal_pointer_reset(&cached_phars); zend_hash_get_current_data(&cached_phars, (void **)&pphar) == SUCCESS; zend_hash_move_forward(&cached_phars)) { stuff[pphar[0]->phar_pos].manifest = (phar_entry_fp_info *) ecalloc( zend_hash_num_elements(&(pphar[0]->manifest)), sizeof(phar_entry_fp_info)); } PHAR_GLOBALS->cached_fp = stuff; } PHAR_GLOBALS->phar_SERVER_mung_list = 0; PHAR_G(cwd) = NULL; PHAR_G(cwd_len) = 0; PHAR_G(cwd_init) = 0; } } /* }}} */ PHP_RSHUTDOWN_FUNCTION(phar) /* {{{ */ { int i; PHAR_GLOBALS->request_ends = 1; if (PHAR_GLOBALS->request_init) { phar_release_functions(TSRMLS_C); zend_hash_destroy(&(PHAR_GLOBALS->phar_alias_map)); PHAR_GLOBALS->phar_alias_map.arBuckets = NULL; zend_hash_destroy(&(PHAR_GLOBALS->phar_fname_map)); PHAR_GLOBALS->phar_fname_map.arBuckets = NULL; zend_hash_destroy(&(PHAR_GLOBALS->phar_persist_map)); PHAR_GLOBALS->phar_persist_map.arBuckets = NULL; PHAR_GLOBALS->phar_SERVER_mung_list = 0; if (PHAR_GLOBALS->cached_fp) { for (i = 0; i < zend_hash_num_elements(&cached_phars); ++i) { if (PHAR_GLOBALS->cached_fp[i].fp) { php_stream_close(PHAR_GLOBALS->cached_fp[i].fp); } if (PHAR_GLOBALS->cached_fp[i].ufp) { php_stream_close(PHAR_GLOBALS->cached_fp[i].ufp); } efree(PHAR_GLOBALS->cached_fp[i].manifest); } efree(PHAR_GLOBALS->cached_fp); PHAR_GLOBALS->cached_fp = 0; } PHAR_GLOBALS->request_init = 0; if (PHAR_G(cwd)) { efree(PHAR_G(cwd)); } PHAR_G(cwd) = NULL; PHAR_G(cwd_len) = 0; PHAR_G(cwd_init) = 0; } PHAR_GLOBALS->request_done = 1; return SUCCESS; } /* }}} */ PHP_MINFO_FUNCTION(phar) /* {{{ */ { phar_request_initialize(TSRMLS_C); php_info_print_table_start(); php_info_print_table_header(2, "Phar: PHP Archive support", "enabled"); php_info_print_table_row(2, "Phar EXT version", PHP_PHAR_VERSION); php_info_print_table_row(2, "Phar API version", PHP_PHAR_API_VERSION); php_info_print_table_row(2, "SVN revision", "$Revision$"); php_info_print_table_row(2, "Phar-based phar archives", "enabled"); php_info_print_table_row(2, "Tar-based phar archives", "enabled"); php_info_print_table_row(2, "ZIP-based phar archives", "enabled"); if (PHAR_G(has_zlib)) { php_info_print_table_row(2, "gzip compression", "enabled"); } else { php_info_print_table_row(2, "gzip compression", "disabled (install ext/zlib)"); } if (PHAR_G(has_bz2)) { php_info_print_table_row(2, "bzip2 compression", "enabled"); } else { php_info_print_table_row(2, "bzip2 compression", "disabled (install pecl/bz2)"); } #ifdef PHAR_HAVE_OPENSSL php_info_print_table_row(2, "Native OpenSSL support", "enabled"); #else if (zend_hash_exists(&module_registry, "openssl", sizeof("openssl"))) { php_info_print_table_row(2, "OpenSSL support", "enabled"); } else { php_info_print_table_row(2, "OpenSSL support", "disabled (install ext/openssl)"); } #endif php_info_print_table_end(); php_info_print_box_start(0); PUTS("Phar based on pear/PHP_Archive, original concept by Davey Shafik."); PUTS(!sapi_module.phpinfo_as_text?"<br />":"\n"); PUTS("Phar fully realized by Gregory Beaver and Marcus Boerger."); PUTS(!sapi_module.phpinfo_as_text?"<br />":"\n"); PUTS("Portions of tar implementation Copyright (c) 2003-2009 Tim Kientzle."); php_info_print_box_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ /* {{{ phar_module_entry */ static const zend_module_dep phar_deps[] = { ZEND_MOD_OPTIONAL("apc") ZEND_MOD_OPTIONAL("bz2") ZEND_MOD_OPTIONAL("openssl") ZEND_MOD_OPTIONAL("zlib") ZEND_MOD_OPTIONAL("standard") #if defined(HAVE_HASH) && !defined(COMPILE_DL_HASH) ZEND_MOD_REQUIRED("hash") #endif #if HAVE_SPL ZEND_MOD_REQUIRED("spl") #endif ZEND_MOD_END }; zend_module_entry phar_module_entry = { STANDARD_MODULE_HEADER_EX, NULL, phar_deps, "Phar", phar_functions, PHP_MINIT(phar), PHP_MSHUTDOWN(phar), NULL, PHP_RSHUTDOWN(phar), PHP_MINFO(phar), PHP_PHAR_VERSION, PHP_MODULE_GLOBALS(phar), /* globals descriptor */ PHP_GINIT(phar), /* globals ctor */ PHP_GSHUTDOWN(phar), /* globals dtor */ NULL, /* post deactivate */ STANDARD_MODULE_PROPERTIES_EX }; /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-11-19-eeba0b5681-d3b20b4058.c
manybugs_data_95
/* Generated by re2c 0.13.5 on Mon May 31 11:07:50 2010 */ #line 1 "ext/standard/url_scanner_ex.re" /* +----------------------------------------------------------------------+ | PHP Version 6 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2006 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Sascha Schumann <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "php.h" #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_LIMITS_H #include <limits.h> #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include "php_ini.h" #include "php_globals.h" #define STATE_TAG SOME_OTHER_STATE_TAG #include "basic_functions.h" #include "url.h" #undef STATE_TAG #define url_scanner url_scanner_ex #include "php_smart_str.h" static PHP_INI_MH(OnUpdateTags) { url_adapt_state_ex_t *ctx; char *key; char *lasts; char *tmp; ctx = &BG(url_adapt_state_ex); tmp = estrndup(new_value, new_value_length); if (ctx->tags) zend_hash_destroy(ctx->tags); else ctx->tags = malloc(sizeof(HashTable)); zend_hash_init(ctx->tags, 0, NULL, NULL, 1); for (key = php_strtok_r(tmp, ",", &lasts); key; key = php_strtok_r(NULL, ",", &lasts)) { char *val; val = strchr(key, '='); if (val) { char *q; int keylen; *val++ = '\0'; for (q = key; *q; q++) *q = tolower(*q); keylen = q - key; /* key is stored withOUT NUL val is stored WITH NUL */ zend_hash_add(ctx->tags, key, keylen, val, strlen(val)+1, NULL); } } efree(tmp); return SUCCESS; } PHP_INI_BEGIN() STD_PHP_INI_ENTRY("url_rewriter.tags", "a=href,area=href,frame=src,form=,fieldset=", PHP_INI_ALL, OnUpdateTags, url_adapt_state_ex, php_basic_globals, basic_globals) PHP_INI_END() #line 98 "ext/standard/url_scanner_ex.re" #define YYFILL(n) goto done #define YYCTYPE unsigned char #define YYCURSOR p #define YYLIMIT q #define YYMARKER r static inline void append_modified_url(smart_str *url, smart_str *dest, smart_str *url_app, const char *separator) { register const char *p, *q; const char *bash = NULL; const char *sep = "?"; q = (p = url->c) + url->len; scan: #line 114 "ext/standard/url_scanner_ex.c" { YYCTYPE yych; static const unsigned char yybm[] = { 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 128, 128, 128, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yybm[0+yych] & 128) { goto yy8; } if (yych <= '9') goto yy6; if (yych >= ';') goto yy4; ++YYCURSOR; #line 116 "ext/standard/url_scanner_ex.re" { smart_str_append(dest, url); return; } #line 162 "ext/standard/url_scanner_ex.c" yy4: ++YYCURSOR; #line 117 "ext/standard/url_scanner_ex.re" { sep = separator; goto scan; } #line 167 "ext/standard/url_scanner_ex.c" yy6: ++YYCURSOR; #line 118 "ext/standard/url_scanner_ex.re" { bash = p - 1; goto done; } #line 172 "ext/standard/url_scanner_ex.c" yy8: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yybm[0+yych] & 128) { goto yy8; } #line 119 "ext/standard/url_scanner_ex.re" { goto scan; } #line 182 "ext/standard/url_scanner_ex.c" } #line 120 "ext/standard/url_scanner_ex.re" done: /* Don't modify URLs of the format "#mark" */ if (bash && bash - url->c == 0) { smart_str_append(dest, url); return; } if (bash) smart_str_appendl(dest, url->c, bash - url->c); else smart_str_append(dest, url); smart_str_appends(dest, sep); smart_str_append(dest, url_app); if (bash) smart_str_appendl(dest, bash, q - bash); } #undef YYFILL #undef YYCTYPE #undef YYCURSOR #undef YYLIMIT #undef YYMARKER static inline void tag_arg(url_adapt_state_ex_t *ctx, char quotes, char type TSRMLS_DC) { char f = 0; if (strncasecmp(ctx->arg.c, ctx->lookup_data, ctx->arg.len) == 0) f = 1; if (quotes) smart_str_appendc(&ctx->result, type); if (f) { append_modified_url(&ctx->val, &ctx->result, &ctx->url_app, PG(arg_separator).output); } else { smart_str_append(&ctx->result, &ctx->val); } if (quotes) smart_str_appendc(&ctx->result, type); } enum { STATE_PLAIN = 0, STATE_TAG, STATE_NEXT_ARG, STATE_ARG, STATE_BEFORE_VAL, STATE_VAL }; #define YYFILL(n) goto stop #define YYCTYPE unsigned char #define YYCURSOR xp #define YYLIMIT end #define YYMARKER q #define STATE ctx->state #define STD_PARA url_adapt_state_ex_t *ctx, char *start, char *YYCURSOR TSRMLS_DC #define STD_ARGS ctx, start, xp TSRMLS_CC #if SCANNER_DEBUG #define scdebug(x) printf x #else #define scdebug(x) #endif static inline void passthru(STD_PARA) { scdebug(("appending %d chars, starting with %c\n", YYCURSOR-start, *start)); smart_str_appendl(&ctx->result, start, YYCURSOR - start); } /* * This function appends a hidden input field after a <form> or * <fieldset>. The latter is important for XHTML. */ static void handle_form(STD_PARA) { int doit = 0; if (ctx->form_app.len > 0) { switch (ctx->tag.len) { case sizeof("form") - 1: if (!strncasecmp(ctx->tag.c, "form", sizeof("form") - 1)) { doit = 1; } if (doit && ctx->val.c && ctx->lookup_data && *ctx->lookup_data) { char *e, *p = zend_memnstr(ctx->val.c, "://", sizeof("://") - 1, ctx->val.c + ctx->val.len); if (p) { e = memchr(p, '/', (ctx->val.c + ctx->val.len) - p); if (!e) { e = ctx->val.c + ctx->val.len; } if ((e - p) && strncasecmp(p, ctx->lookup_data, (e - p))) { doit = 0; } } } break; case sizeof("fieldset") - 1: if (!strncasecmp(ctx->tag.c, "fieldset", sizeof("fieldset") - 1)) { doit = 1; } break; } if (doit) smart_str_append(&ctx->result, &ctx->form_app); } } /* * HANDLE_TAG copies the HTML Tag and checks whether we * have that tag in our table. If we might modify it, * we continue to scan the tag, otherwise we simply copy the complete * HTML stuff to the result buffer. */ static inline void handle_tag(STD_PARA) { int ok = 0; unsigned int i; ctx->tag.len = 0; smart_str_appendl(&ctx->tag, start, YYCURSOR - start); for (i = 0; i < ctx->tag.len; i++) ctx->tag.c[i] = tolower((int)(unsigned char)ctx->tag.c[i]); if (zend_hash_find(ctx->tags, ctx->tag.c, ctx->tag.len, (void **) &ctx->lookup_data) == SUCCESS) ok = 1; STATE = ok ? STATE_NEXT_ARG : STATE_PLAIN; } static inline void handle_arg(STD_PARA) { ctx->arg.len = 0; smart_str_appendl(&ctx->arg, start, YYCURSOR - start); } static inline void handle_val(STD_PARA, char quotes, char type) { smart_str_setl(&ctx->val, start + quotes, YYCURSOR - start - quotes * 2); tag_arg(ctx, quotes, type TSRMLS_CC); } static inline void xx_mainloop(url_adapt_state_ex_t *ctx, const char *newdata, size_t newlen TSRMLS_DC) { char *end, *q; char *xp; char *start; int rest; smart_str_appendl(&ctx->buf, newdata, newlen); YYCURSOR = ctx->buf.c; YYLIMIT = ctx->buf.c + ctx->buf.len; switch (STATE) { case STATE_PLAIN: goto state_plain; case STATE_TAG: goto state_tag; case STATE_NEXT_ARG: goto state_next_arg; case STATE_ARG: goto state_arg; case STATE_BEFORE_VAL: goto state_before_val; case STATE_VAL: goto state_val; } state_plain_begin: STATE = STATE_PLAIN; state_plain: start = YYCURSOR; #line 364 "ext/standard/url_scanner_ex.c" { YYCTYPE yych; static const unsigned char yybm[] = { 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yybm[0+yych] & 128) { goto yy15; } ++YYCURSOR; #line 299 "ext/standard/url_scanner_ex.re" { passthru(STD_ARGS); STATE = STATE_TAG; goto state_tag; } #line 409 "ext/standard/url_scanner_ex.c" yy15: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yybm[0+yych] & 128) { goto yy15; } #line 300 "ext/standard/url_scanner_ex.re" { passthru(STD_ARGS); goto state_plain; } #line 419 "ext/standard/url_scanner_ex.c" } #line 301 "ext/standard/url_scanner_ex.re" state_tag: start = YYCURSOR; #line 427 "ext/standard/url_scanner_ex.c" { YYCTYPE yych; static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych <= '@') { if (yych != ':') goto yy22; } else { if (yych <= 'Z') goto yy20; if (yych <= '`') goto yy22; if (yych >= '{') goto yy22; } yy20: ++YYCURSOR; yych = *YYCURSOR; goto yy25; yy21: #line 306 "ext/standard/url_scanner_ex.re" { handle_tag(STD_ARGS); /* Sets STATE */; passthru(STD_ARGS); if (STATE == STATE_PLAIN) goto state_plain; else goto state_next_arg; } #line 480 "ext/standard/url_scanner_ex.c" yy22: ++YYCURSOR; #line 307 "ext/standard/url_scanner_ex.re" { passthru(STD_ARGS); goto state_plain_begin; } #line 485 "ext/standard/url_scanner_ex.c" yy24: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; yy25: if (yybm[0+yych] & 128) { goto yy24; } goto yy21; } #line 308 "ext/standard/url_scanner_ex.re" state_next_arg_begin: STATE = STATE_NEXT_ARG; state_next_arg: start = YYCURSOR; #line 505 "ext/standard/url_scanner_ex.c" { YYCTYPE yych; static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych <= ' ') { if (yych <= '\f') { if (yych <= 0x08) goto yy34; if (yych <= '\v') goto yy30; goto yy34; } else { if (yych <= '\r') goto yy30; if (yych <= 0x1F) goto yy34; goto yy30; } } else { if (yych <= '@') { if (yych != '>') goto yy34; } else { if (yych <= 'Z') goto yy32; if (yych <= '`') goto yy34; if (yych <= 'z') goto yy32; goto yy34; } } ++YYCURSOR; #line 316 "ext/standard/url_scanner_ex.re" { passthru(STD_ARGS); handle_form(STD_ARGS); goto state_plain_begin; } #line 567 "ext/standard/url_scanner_ex.c" yy30: ++YYCURSOR; yych = *YYCURSOR; goto yy37; yy31: #line 317 "ext/standard/url_scanner_ex.re" { passthru(STD_ARGS); goto state_next_arg; } #line 575 "ext/standard/url_scanner_ex.c" yy32: ++YYCURSOR; #line 318 "ext/standard/url_scanner_ex.re" { --YYCURSOR; STATE = STATE_ARG; goto state_arg; } #line 580 "ext/standard/url_scanner_ex.c" yy34: ++YYCURSOR; #line 319 "ext/standard/url_scanner_ex.re" { passthru(STD_ARGS); goto state_plain_begin; } #line 585 "ext/standard/url_scanner_ex.c" yy36: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; yy37: if (yybm[0+yych] & 128) { goto yy36; } goto yy31; } #line 320 "ext/standard/url_scanner_ex.re" state_arg: start = YYCURSOR; #line 602 "ext/standard/url_scanner_ex.c" { YYCTYPE yych; static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych <= '@') goto yy42; if (yych <= 'Z') goto yy40; if (yych <= '`') goto yy42; if (yych >= '{') goto yy42; yy40: ++YYCURSOR; yych = *YYCURSOR; goto yy45; yy41: #line 325 "ext/standard/url_scanner_ex.re" { passthru(STD_ARGS); handle_arg(STD_ARGS); STATE = STATE_BEFORE_VAL; goto state_before_val; } #line 652 "ext/standard/url_scanner_ex.c" yy42: ++YYCURSOR; #line 326 "ext/standard/url_scanner_ex.re" { passthru(STD_ARGS); STATE = STATE_NEXT_ARG; goto state_next_arg; } #line 657 "ext/standard/url_scanner_ex.c" yy44: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; yy45: if (yybm[0+yych] & 128) { goto yy44; } goto yy41; } #line 327 "ext/standard/url_scanner_ex.re" state_before_val: start = YYCURSOR; #line 674 "ext/standard/url_scanner_ex.c" { YYCTYPE yych; static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych == ' ') goto yy48; if (yych == '=') goto yy50; goto yy52; yy48: yych = *(YYMARKER = ++YYCURSOR); if (yych == ' ') goto yy55; if (yych == '=') goto yy53; yy49: #line 333 "ext/standard/url_scanner_ex.re" { --YYCURSOR; goto state_next_arg_begin; } #line 723 "ext/standard/url_scanner_ex.c" yy50: ++YYCURSOR; yych = *YYCURSOR; goto yy54; yy51: #line 332 "ext/standard/url_scanner_ex.re" { passthru(STD_ARGS); STATE = STATE_VAL; goto state_val; } #line 731 "ext/standard/url_scanner_ex.c" yy52: yych = *++YYCURSOR; goto yy49; yy53: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; yy54: if (yybm[0+yych] & 128) { goto yy53; } goto yy51; yy55: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yych == ' ') goto yy55; if (yych == '=') goto yy53; YYCURSOR = YYMARKER; goto yy49; } #line 334 "ext/standard/url_scanner_ex.re" state_val: start = YYCURSOR; #line 760 "ext/standard/url_scanner_ex.c" { YYCTYPE yych; static const unsigned char yybm[] = { 248, 248, 248, 248, 248, 248, 248, 248, 248, 160, 160, 248, 248, 160, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 160, 248, 56, 248, 248, 248, 248, 200, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 0, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, }; if ((YYLIMIT - YYCURSOR) < 3) YYFILL(3); yych = *YYCURSOR; if (yych <= ' ') { if (yych <= '\f') { if (yych <= 0x08) goto yy63; if (yych <= '\n') goto yy64; goto yy63; } else { if (yych <= '\r') goto yy64; if (yych <= 0x1F) goto yy63; goto yy64; } } else { if (yych <= '&') { if (yych != '"') goto yy63; } else { if (yych <= '\'') goto yy62; if (yych == '>') goto yy64; goto yy63; } } yych = *(YYMARKER = ++YYCURSOR); goto yy77; yy61: #line 342 "ext/standard/url_scanner_ex.re" { handle_val(STD_ARGS, 0, ' '); goto state_next_arg_begin; } #line 823 "ext/standard/url_scanner_ex.c" yy62: yych = *(YYMARKER = ++YYCURSOR); goto yy69; yy63: yych = *++YYCURSOR; goto yy67; yy64: ++YYCURSOR; #line 343 "ext/standard/url_scanner_ex.re" { passthru(STD_ARGS); goto state_next_arg_begin; } #line 834 "ext/standard/url_scanner_ex.c" yy66: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; yy67: if (yybm[0+yych] & 8) { goto yy66; } goto yy61; yy68: YYMARKER = ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; yy69: if (yybm[0+yych] & 16) { goto yy68; } if (yych <= '&') goto yy72; if (yych >= '(') goto yy61; ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 8) { goto yy66; } yy71: #line 341 "ext/standard/url_scanner_ex.re" { handle_val(STD_ARGS, 1, '\''); goto state_next_arg_begin; } #line 861 "ext/standard/url_scanner_ex.c" yy72: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yybm[0+yych] & 32) { goto yy72; } if (yych <= '=') goto yy75; yy74: YYCURSOR = YYMARKER; goto yy61; yy75: yych = *++YYCURSOR; goto yy71; yy76: YYMARKER = ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; yy77: if (yybm[0+yych] & 64) { goto yy76; } if (yych <= '!') goto yy80; if (yych >= '#') goto yy61; ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 8) { goto yy66; } yy79: #line 340 "ext/standard/url_scanner_ex.re" { handle_val(STD_ARGS, 1, '"'); goto state_next_arg_begin; } #line 893 "ext/standard/url_scanner_ex.c" yy80: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yybm[0+yych] & 128) { goto yy80; } if (yych >= '>') goto yy74; ++YYCURSOR; yych = *YYCURSOR; goto yy79; } #line 344 "ext/standard/url_scanner_ex.re" stop: rest = YYLIMIT - start; scdebug(("stopped in state %d at pos %d (%d:%c) %d\n", STATE, YYCURSOR - ctx->buf.c, *YYCURSOR, *YYCURSOR, rest)); /* XXX: Crash avoidance. Need to work with reporter to figure out what goes wrong */ if (rest < 0) rest = 0; if (rest) memmove(ctx->buf.c, start, rest); ctx->buf.len = rest; } char *php_url_scanner_adapt_single_url(const char *url, size_t urllen, const char *name, const char *value, size_t *newlen TSRMLS_DC) { smart_str surl = {0}; smart_str buf = {0}; smart_str url_app = {0}; smart_str_setl(&surl, url, urllen); smart_str_appends(&url_app, name); smart_str_appendc(&url_app, '='); smart_str_appends(&url_app, value); append_modified_url(&surl, &buf, &url_app, PG(arg_separator).output); smart_str_0(&buf); if (newlen) *newlen = buf.len; smart_str_free(&url_app); return buf.c; } static char *url_adapt_ext(const char *src, size_t srclen, size_t *newlen, zend_bool do_flush TSRMLS_DC) { url_adapt_state_ex_t *ctx; char *retval; ctx = &BG(url_adapt_state_ex); xx_mainloop(ctx, src, srclen TSRMLS_CC); *newlen = ctx->result.len; if (!ctx->result.c) { smart_str_appendl(&ctx->result, "", 0); } smart_str_0(&ctx->result); if (do_flush) { smart_str_appendl(&ctx->result, ctx->buf.c, ctx->buf.len); *newlen += ctx->buf.len; smart_str_free(&ctx->buf); } retval = ctx->result.c; ctx->result.c = NULL; ctx->result.len = 0; return retval; } static int php_url_scanner_ex_activate(TSRMLS_D) { url_adapt_state_ex_t *ctx; ctx = &BG(url_adapt_state_ex); memset(ctx, 0, ((size_t) &((url_adapt_state_ex_t *)0)->tags)); return SUCCESS; } static int php_url_scanner_ex_deactivate(TSRMLS_D) { url_adapt_state_ex_t *ctx; ctx = &BG(url_adapt_state_ex); smart_str_free(&ctx->result); smart_str_free(&ctx->buf); smart_str_free(&ctx->tag); smart_str_free(&ctx->arg); return SUCCESS; } static void php_url_scanner_output_handler(char *output, uint output_len, char **handled_output, uint *handled_output_len, int mode TSRMLS_DC) { size_t len; if (BG(url_adapt_state_ex).url_app.len != 0) { *handled_output = url_adapt_ext(output, output_len, &len, (zend_bool) (mode & (PHP_OUTPUT_HANDLER_END | PHP_OUTPUT_HANDLER_CONT | PHP_OUTPUT_HANDLER_FLUSH | PHP_OUTPUT_HANDLER_FINAL) ? 1 : 0) TSRMLS_CC); if (sizeof(uint) < sizeof(size_t)) { if (len > UINT_MAX) len = UINT_MAX; } *handled_output_len = len; } else if (BG(url_adapt_state_ex).url_app.len == 0) { url_adapt_state_ex_t *ctx = &BG(url_adapt_state_ex); if (ctx->buf.len) { smart_str_appendl(&ctx->result, ctx->buf.c, ctx->buf.len); smart_str_appendl(&ctx->result, output, output_len); *handled_output = ctx->result.c; *handled_output_len = ctx->buf.len + output_len; ctx->result.c = NULL; ctx->result.len = 0; smart_str_free(&ctx->buf); } else { *handled_output = NULL; } } else { *handled_output = NULL; } } PHPAPI int php_url_scanner_add_var(char *name, int name_len, char *value, int value_len, int urlencode TSRMLS_DC) { char *encoded; int encoded_len; smart_str val; if (! BG(url_adapt_state_ex).active) { php_url_scanner_ex_activate(TSRMLS_C); php_output_start_internal(ZEND_STRL("URL-Rewriter"), php_url_scanner_output_handler, 0, PHP_OUTPUT_HANDLER_STDFLAGS TSRMLS_CC); BG(url_adapt_state_ex).active = 1; } if (BG(url_adapt_state_ex).url_app.len != 0) { smart_str_appends(&BG(url_adapt_state_ex).url_app, PG(arg_separator).output); } if (urlencode) { encoded = php_url_encode(value, value_len, &encoded_len); smart_str_setl(&val, encoded, encoded_len); } else { smart_str_setl(&val, value, value_len); } smart_str_appendl(&BG(url_adapt_state_ex).url_app, name, name_len); smart_str_appendc(&BG(url_adapt_state_ex).url_app, '='); smart_str_append(&BG(url_adapt_state_ex).url_app, &val); smart_str_appends(&BG(url_adapt_state_ex).form_app, "<input type=\"hidden\" name=\""); smart_str_appendl(&BG(url_adapt_state_ex).form_app, name, name_len); smart_str_appends(&BG(url_adapt_state_ex).form_app, "\" value=\""); smart_str_append(&BG(url_adapt_state_ex).form_app, &val); smart_str_appends(&BG(url_adapt_state_ex).form_app, "\" />"); if (urlencode) efree(encoded); return SUCCESS; } PHPAPI int php_url_scanner_reset_vars(TSRMLS_D) { BG(url_adapt_state_ex).form_app.len = 0; BG(url_adapt_state_ex).url_app.len = 0; return SUCCESS; } PHP_MINIT_FUNCTION(url_scanner) { BG(url_adapt_state_ex).tags = NULL; BG(url_adapt_state_ex).form_app.c = BG(url_adapt_state_ex).url_app.c = 0; BG(url_adapt_state_ex).form_app.len = BG(url_adapt_state_ex).url_app.len = 0; REGISTER_INI_ENTRIES(); return SUCCESS; } PHP_MSHUTDOWN_FUNCTION(url_scanner) { UNREGISTER_INI_ENTRIES(); return SUCCESS; } PHP_RINIT_FUNCTION(url_scanner) { BG(url_adapt_state_ex).active = 0; return SUCCESS; } PHP_RSHUTDOWN_FUNCTION(url_scanner) { if (BG(url_adapt_state_ex).active) { php_url_scanner_ex_deactivate(TSRMLS_C); BG(url_adapt_state_ex).active = 0; } smart_str_free(&BG(url_adapt_state_ex).form_app); smart_str_free(&BG(url_adapt_state_ex).url_app); return SUCCESS; } /* Generated by re2c 0.13.5 on Mon May 23 12:29:55 2011 */ #line 1 "ext/standard/url_scanner_ex.re" /* +----------------------------------------------------------------------+ | PHP Version 6 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2006 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Sascha Schumann <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "php.h" #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_LIMITS_H #include <limits.h> #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include "php_ini.h" #include "php_globals.h" #define STATE_TAG SOME_OTHER_STATE_TAG #include "basic_functions.h" #include "url.h" #undef STATE_TAG #define url_scanner url_scanner_ex #include "php_smart_str.h" static PHP_INI_MH(OnUpdateTags) { url_adapt_state_ex_t *ctx; char *key; char *lasts; char *tmp; ctx = &BG(url_adapt_state_ex); tmp = estrndup(new_value, new_value_length); if (ctx->tags) zend_hash_destroy(ctx->tags); else ctx->tags = malloc(sizeof(HashTable)); zend_hash_init(ctx->tags, 0, NULL, NULL, 1); for (key = php_strtok_r(tmp, ",", &lasts); key; key = php_strtok_r(NULL, ",", &lasts)) { char *val; val = strchr(key, '='); if (val) { char *q; int keylen; *val++ = '\0'; for (q = key; *q; q++) *q = tolower(*q); keylen = q - key; /* key is stored withOUT NUL val is stored WITH NUL */ zend_hash_add(ctx->tags, key, keylen, val, strlen(val)+1, NULL); } } efree(tmp); return SUCCESS; } PHP_INI_BEGIN() STD_PHP_INI_ENTRY("url_rewriter.tags", "a=href,area=href,frame=src,form=,fieldset=", PHP_INI_ALL, OnUpdateTags, url_adapt_state_ex, php_basic_globals, basic_globals) PHP_INI_END() #line 98 "ext/standard/url_scanner_ex.re" #define YYFILL(n) goto done #define YYCTYPE unsigned char #define YYCURSOR p #define YYLIMIT q #define YYMARKER r static inline void append_modified_url(smart_str *url, smart_str *dest, smart_str *url_app, const char *separator) { register const char *p, *q; const char *bash = NULL; const char *sep = "?"; q = (p = url->c) + url->len; scan: #line 114 "ext/standard/url_scanner_ex.c" { YYCTYPE yych; static const unsigned char yybm[] = { 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 128, 128, 128, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yybm[0+yych] & 128) { goto yy8; } if (yych <= '9') goto yy6; if (yych >= ';') goto yy4; ++YYCURSOR; #line 116 "ext/standard/url_scanner_ex.re" { smart_str_append(dest, url); return; } #line 162 "ext/standard/url_scanner_ex.c" yy4: ++YYCURSOR; #line 117 "ext/standard/url_scanner_ex.re" { sep = separator; goto scan; } #line 167 "ext/standard/url_scanner_ex.c" yy6: ++YYCURSOR; #line 118 "ext/standard/url_scanner_ex.re" { bash = p - 1; goto done; } #line 172 "ext/standard/url_scanner_ex.c" yy8: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yybm[0+yych] & 128) { goto yy8; } #line 119 "ext/standard/url_scanner_ex.re" { goto scan; } #line 182 "ext/standard/url_scanner_ex.c" } #line 120 "ext/standard/url_scanner_ex.re" done: /* Don't modify URLs of the format "#mark" */ if (bash && bash - url->c == 0) { smart_str_append(dest, url); return; } if (bash) smart_str_appendl(dest, url->c, bash - url->c); else smart_str_append(dest, url); smart_str_appends(dest, sep); smart_str_append(dest, url_app); if (bash) smart_str_appendl(dest, bash, q - bash); } #undef YYFILL #undef YYCTYPE #undef YYCURSOR #undef YYLIMIT #undef YYMARKER static inline void tag_arg(url_adapt_state_ex_t *ctx, char quotes, char type TSRMLS_DC) { char f = 0; if (strncasecmp(ctx->arg.c, ctx->lookup_data, ctx->arg.len) == 0) f = 1; if (quotes) smart_str_appendc(&ctx->result, type); if (f) { append_modified_url(&ctx->val, &ctx->result, &ctx->url_app, PG(arg_separator).output); } else { smart_str_append(&ctx->result, &ctx->val); } if (quotes) smart_str_appendc(&ctx->result, type); } enum { STATE_PLAIN = 0, STATE_TAG, STATE_NEXT_ARG, STATE_ARG, STATE_BEFORE_VAL, STATE_VAL }; #define YYFILL(n) goto stop #define YYCTYPE unsigned char #define YYCURSOR xp #define YYLIMIT end #define YYMARKER q #define STATE ctx->state #define STD_PARA url_adapt_state_ex_t *ctx, char *start, char *YYCURSOR TSRMLS_DC #define STD_ARGS ctx, start, xp TSRMLS_CC #if SCANNER_DEBUG #define scdebug(x) printf x #else #define scdebug(x) #endif static inline void passthru(STD_PARA) { scdebug(("appending %d chars, starting with %c\n", YYCURSOR-start, *start)); smart_str_appendl(&ctx->result, start, YYCURSOR - start); } /* * This function appends a hidden input field after a <form> or * <fieldset>. The latter is important for XHTML. */ static void handle_form(STD_PARA) { int doit = 0; if (ctx->form_app.len > 0) { switch (ctx->tag.len) { case sizeof("form") - 1: if (!strncasecmp(ctx->tag.c, "form", sizeof("form") - 1)) { doit = 1; } if (doit && ctx->val.c && ctx->lookup_data && *ctx->lookup_data) { char *e, *p = zend_memnstr(ctx->val.c, "://", sizeof("://") - 1, ctx->val.c + ctx->val.len); if (p) { e = memchr(p, '/', (ctx->val.c + ctx->val.len) - p); if (!e) { e = ctx->val.c + ctx->val.len; } if ((e - p) && strncasecmp(p, ctx->lookup_data, (e - p))) { doit = 0; } } } break; case sizeof("fieldset") - 1: if (!strncasecmp(ctx->tag.c, "fieldset", sizeof("fieldset") - 1)) { doit = 1; } break; } if (doit) smart_str_append(&ctx->result, &ctx->form_app); } } /* * HANDLE_TAG copies the HTML Tag and checks whether we * have that tag in our table. If we might modify it, * we continue to scan the tag, otherwise we simply copy the complete * HTML stuff to the result buffer. */ static inline void handle_tag(STD_PARA) { int ok = 0; unsigned int i; ctx->tag.len = 0; smart_str_appendl(&ctx->tag, start, YYCURSOR - start); for (i = 0; i < ctx->tag.len; i++) ctx->tag.c[i] = tolower((int)(unsigned char)ctx->tag.c[i]); if (zend_hash_find(ctx->tags, ctx->tag.c, ctx->tag.len, (void **) &ctx->lookup_data) == SUCCESS) ok = 1; STATE = ok ? STATE_NEXT_ARG : STATE_PLAIN; } static inline void handle_arg(STD_PARA) { ctx->arg.len = 0; smart_str_appendl(&ctx->arg, start, YYCURSOR - start); } static inline void handle_val(STD_PARA, char quotes, char type) { smart_str_setl(&ctx->val, start + quotes, YYCURSOR - start - quotes * 2); tag_arg(ctx, quotes, type TSRMLS_CC); } static inline void xx_mainloop(url_adapt_state_ex_t *ctx, const char *newdata, size_t newlen TSRMLS_DC) { char *end, *q; char *xp; char *start; int rest; smart_str_appendl(&ctx->buf, newdata, newlen); YYCURSOR = ctx->buf.c; YYLIMIT = ctx->buf.c + ctx->buf.len; switch (STATE) { case STATE_PLAIN: goto state_plain; case STATE_TAG: goto state_tag; case STATE_NEXT_ARG: goto state_next_arg; case STATE_ARG: goto state_arg; case STATE_BEFORE_VAL: goto state_before_val; case STATE_VAL: goto state_val; } state_plain_begin: STATE = STATE_PLAIN; state_plain: start = YYCURSOR; #line 364 "ext/standard/url_scanner_ex.c" { YYCTYPE yych; static const unsigned char yybm[] = { 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yybm[0+yych] & 128) { goto yy15; } ++YYCURSOR; #line 299 "ext/standard/url_scanner_ex.re" { passthru(STD_ARGS); STATE = STATE_TAG; goto state_tag; } #line 409 "ext/standard/url_scanner_ex.c" yy15: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yybm[0+yych] & 128) { goto yy15; } #line 300 "ext/standard/url_scanner_ex.re" { passthru(STD_ARGS); goto state_plain; } #line 419 "ext/standard/url_scanner_ex.c" } #line 301 "ext/standard/url_scanner_ex.re" state_tag: start = YYCURSOR; #line 427 "ext/standard/url_scanner_ex.c" { YYCTYPE yych; static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych <= '@') { if (yych != ':') goto yy22; } else { if (yych <= 'Z') goto yy20; if (yych <= '`') goto yy22; if (yych >= '{') goto yy22; } yy20: ++YYCURSOR; yych = *YYCURSOR; goto yy25; yy21: #line 306 "ext/standard/url_scanner_ex.re" { handle_tag(STD_ARGS); /* Sets STATE */; passthru(STD_ARGS); if (STATE == STATE_PLAIN) goto state_plain; else goto state_next_arg; } #line 480 "ext/standard/url_scanner_ex.c" yy22: ++YYCURSOR; #line 307 "ext/standard/url_scanner_ex.re" { passthru(STD_ARGS); goto state_plain_begin; } #line 485 "ext/standard/url_scanner_ex.c" yy24: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; yy25: if (yybm[0+yych] & 128) { goto yy24; } goto yy21; } #line 308 "ext/standard/url_scanner_ex.re" state_next_arg_begin: STATE = STATE_NEXT_ARG; state_next_arg: start = YYCURSOR; #line 505 "ext/standard/url_scanner_ex.c" { YYCTYPE yych; static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych <= ' ') { if (yych <= '\f') { if (yych <= 0x08) goto yy34; if (yych <= '\v') goto yy30; goto yy34; } else { if (yych <= '\r') goto yy30; if (yych <= 0x1F) goto yy34; goto yy30; } } else { if (yych <= '@') { if (yych != '>') goto yy34; } else { if (yych <= 'Z') goto yy32; if (yych <= '`') goto yy34; if (yych <= 'z') goto yy32; goto yy34; } } ++YYCURSOR; #line 316 "ext/standard/url_scanner_ex.re" { passthru(STD_ARGS); handle_form(STD_ARGS); goto state_plain_begin; } #line 567 "ext/standard/url_scanner_ex.c" yy30: ++YYCURSOR; yych = *YYCURSOR; goto yy37; yy31: #line 317 "ext/standard/url_scanner_ex.re" { passthru(STD_ARGS); goto state_next_arg; } #line 575 "ext/standard/url_scanner_ex.c" yy32: ++YYCURSOR; #line 318 "ext/standard/url_scanner_ex.re" { --YYCURSOR; STATE = STATE_ARG; goto state_arg; } #line 580 "ext/standard/url_scanner_ex.c" yy34: ++YYCURSOR; #line 319 "ext/standard/url_scanner_ex.re" { passthru(STD_ARGS); goto state_plain_begin; } #line 585 "ext/standard/url_scanner_ex.c" yy36: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; yy37: if (yybm[0+yych] & 128) { goto yy36; } goto yy31; } #line 320 "ext/standard/url_scanner_ex.re" state_arg: start = YYCURSOR; #line 602 "ext/standard/url_scanner_ex.c" { YYCTYPE yych; static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych <= '@') goto yy42; if (yych <= 'Z') goto yy40; if (yych <= '`') goto yy42; if (yych >= '{') goto yy42; yy40: ++YYCURSOR; yych = *YYCURSOR; goto yy45; yy41: #line 325 "ext/standard/url_scanner_ex.re" { passthru(STD_ARGS); handle_arg(STD_ARGS); STATE = STATE_BEFORE_VAL; goto state_before_val; } #line 652 "ext/standard/url_scanner_ex.c" yy42: ++YYCURSOR; #line 326 "ext/standard/url_scanner_ex.re" { passthru(STD_ARGS); STATE = STATE_NEXT_ARG; goto state_next_arg; } #line 657 "ext/standard/url_scanner_ex.c" yy44: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; yy45: if (yybm[0+yych] & 128) { goto yy44; } goto yy41; } #line 327 "ext/standard/url_scanner_ex.re" state_before_val: start = YYCURSOR; #line 674 "ext/standard/url_scanner_ex.c" { YYCTYPE yych; static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych == ' ') goto yy48; if (yych == '=') goto yy50; goto yy52; yy48: yych = *(YYMARKER = ++YYCURSOR); if (yych == ' ') goto yy55; if (yych == '=') goto yy53; yy49: #line 333 "ext/standard/url_scanner_ex.re" { --YYCURSOR; goto state_next_arg_begin; } #line 723 "ext/standard/url_scanner_ex.c" yy50: ++YYCURSOR; yych = *YYCURSOR; goto yy54; yy51: #line 332 "ext/standard/url_scanner_ex.re" { passthru(STD_ARGS); STATE = STATE_VAL; goto state_val; } #line 731 "ext/standard/url_scanner_ex.c" yy52: yych = *++YYCURSOR; goto yy49; yy53: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; yy54: if (yybm[0+yych] & 128) { goto yy53; } goto yy51; yy55: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yych == ' ') goto yy55; if (yych == '=') goto yy53; YYCURSOR = YYMARKER; goto yy49; } #line 334 "ext/standard/url_scanner_ex.re" state_val: start = YYCURSOR; #line 760 "ext/standard/url_scanner_ex.c" { YYCTYPE yych; static const unsigned char yybm[] = { 248, 248, 248, 248, 248, 248, 248, 248, 248, 160, 160, 248, 248, 160, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 160, 248, 56, 248, 248, 248, 248, 200, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 0, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, 248, }; if ((YYLIMIT - YYCURSOR) < 3) YYFILL(3); yych = *YYCURSOR; if (yych <= ' ') { if (yych <= '\f') { if (yych <= 0x08) goto yy63; if (yych <= '\n') goto yy64; goto yy63; } else { if (yych <= '\r') goto yy64; if (yych <= 0x1F) goto yy63; goto yy64; } } else { if (yych <= '&') { if (yych != '"') goto yy63; } else { if (yych <= '\'') goto yy62; if (yych == '>') goto yy64; goto yy63; } } yych = *(YYMARKER = ++YYCURSOR); goto yy77; yy61: #line 342 "ext/standard/url_scanner_ex.re" { handle_val(STD_ARGS, 0, ' '); goto state_next_arg_begin; } #line 823 "ext/standard/url_scanner_ex.c" yy62: yych = *(YYMARKER = ++YYCURSOR); goto yy69; yy63: yych = *++YYCURSOR; goto yy67; yy64: ++YYCURSOR; #line 343 "ext/standard/url_scanner_ex.re" { passthru(STD_ARGS); goto state_next_arg_begin; } #line 834 "ext/standard/url_scanner_ex.c" yy66: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; yy67: if (yybm[0+yych] & 8) { goto yy66; } goto yy61; yy68: YYMARKER = ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; yy69: if (yybm[0+yych] & 16) { goto yy68; } if (yych <= '&') goto yy72; if (yych >= '(') goto yy61; ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 8) { goto yy66; } yy71: #line 341 "ext/standard/url_scanner_ex.re" { handle_val(STD_ARGS, 1, '\''); goto state_next_arg_begin; } #line 861 "ext/standard/url_scanner_ex.c" yy72: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yybm[0+yych] & 32) { goto yy72; } if (yych <= '=') goto yy75; yy74: YYCURSOR = YYMARKER; goto yy61; yy75: yych = *++YYCURSOR; goto yy71; yy76: YYMARKER = ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; yy77: if (yybm[0+yych] & 64) { goto yy76; } if (yych <= '!') goto yy80; if (yych >= '#') goto yy61; ++YYCURSOR; if (yybm[0+(yych = *YYCURSOR)] & 8) { goto yy66; } yy79: #line 340 "ext/standard/url_scanner_ex.re" { handle_val(STD_ARGS, 1, '"'); goto state_next_arg_begin; } #line 893 "ext/standard/url_scanner_ex.c" yy80: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yybm[0+yych] & 128) { goto yy80; } if (yych >= '>') goto yy74; ++YYCURSOR; yych = *YYCURSOR; goto yy79; } #line 344 "ext/standard/url_scanner_ex.re" stop: rest = YYLIMIT - start; scdebug(("stopped in state %d at pos %d (%d:%c) %d\n", STATE, YYCURSOR - ctx->buf.c, *YYCURSOR, *YYCURSOR, rest)); /* XXX: Crash avoidance. Need to work with reporter to figure out what goes wrong */ if (rest < 0) rest = 0; if (rest) memmove(ctx->buf.c, start, rest); ctx->buf.len = rest; } char *php_url_scanner_adapt_single_url(const char *url, size_t urllen, const char *name, const char *value, size_t *newlen TSRMLS_DC) { smart_str surl = {0}; smart_str buf = {0}; smart_str url_app = {0}; smart_str_setl(&surl, url, urllen); smart_str_appends(&url_app, name); smart_str_appendc(&url_app, '='); smart_str_appends(&url_app, value); append_modified_url(&surl, &buf, &url_app, PG(arg_separator).output); smart_str_0(&buf); if (newlen) *newlen = buf.len; smart_str_free(&url_app); return buf.c; } static char *url_adapt_ext(const char *src, size_t srclen, size_t *newlen, zend_bool do_flush TSRMLS_DC) { url_adapt_state_ex_t *ctx; char *retval; ctx = &BG(url_adapt_state_ex); xx_mainloop(ctx, src, srclen TSRMLS_CC); *newlen = ctx->result.len; if (!ctx->result.c) { smart_str_appendl(&ctx->result, "", 0); } smart_str_0(&ctx->result); if (do_flush) { smart_str_appendl(&ctx->result, ctx->buf.c, ctx->buf.len); *newlen += ctx->buf.len; smart_str_free(&ctx->buf); } retval = ctx->result.c; ctx->result.c = NULL; ctx->result.len = 0; return retval; } static int php_url_scanner_ex_activate(TSRMLS_D) { url_adapt_state_ex_t *ctx; ctx = &BG(url_adapt_state_ex); memset(ctx, 0, ((size_t) &((url_adapt_state_ex_t *)0)->tags)); return SUCCESS; } static int php_url_scanner_ex_deactivate(TSRMLS_D) { url_adapt_state_ex_t *ctx; ctx = &BG(url_adapt_state_ex); smart_str_free(&ctx->result); smart_str_free(&ctx->buf); smart_str_free(&ctx->tag); smart_str_free(&ctx->arg); return SUCCESS; } static void php_url_scanner_output_handler(char *output, uint output_len, char **handled_output, uint *handled_output_len, int mode TSRMLS_DC) { size_t len; if (BG(url_adapt_state_ex).url_app.len != 0) { *handled_output = url_adapt_ext(output, output_len, &len, (zend_bool) (mode & (PHP_OUTPUT_HANDLER_END | PHP_OUTPUT_HANDLER_CONT | PHP_OUTPUT_HANDLER_FLUSH | PHP_OUTPUT_HANDLER_FINAL) ? 1 : 0) TSRMLS_CC); if (sizeof(uint) < sizeof(size_t)) { if (len > UINT_MAX) len = UINT_MAX; } *handled_output_len = len; } else if (BG(url_adapt_state_ex).url_app.len == 0) { url_adapt_state_ex_t *ctx = &BG(url_adapt_state_ex); if (ctx->buf.len) { smart_str_appendl(&ctx->result, ctx->buf.c, ctx->buf.len); smart_str_appendl(&ctx->result, output, output_len); *handled_output = ctx->result.c; *handled_output_len = ctx->buf.len + output_len; ctx->result.c = NULL; ctx->result.len = 0; smart_str_free(&ctx->buf); } else { *handled_output = estrndup(output, *handled_output_len = output_len); } } else { *handled_output = NULL; } } PHPAPI int php_url_scanner_add_var(char *name, int name_len, char *value, int value_len, int urlencode TSRMLS_DC) { char *encoded; int encoded_len; smart_str val; if (! BG(url_adapt_state_ex).active) { php_url_scanner_ex_activate(TSRMLS_C); php_output_start_internal(ZEND_STRL("URL-Rewriter"), php_url_scanner_output_handler, 0, PHP_OUTPUT_HANDLER_STDFLAGS TSRMLS_CC); BG(url_adapt_state_ex).active = 1; } if (BG(url_adapt_state_ex).url_app.len != 0) { smart_str_appends(&BG(url_adapt_state_ex).url_app, PG(arg_separator).output); } if (urlencode) { encoded = php_url_encode(value, value_len, &encoded_len); smart_str_setl(&val, encoded, encoded_len); } else { smart_str_setl(&val, value, value_len); } smart_str_appendl(&BG(url_adapt_state_ex).url_app, name, name_len); smart_str_appendc(&BG(url_adapt_state_ex).url_app, '='); smart_str_append(&BG(url_adapt_state_ex).url_app, &val); smart_str_appends(&BG(url_adapt_state_ex).form_app, "<input type=\"hidden\" name=\""); smart_str_appendl(&BG(url_adapt_state_ex).form_app, name, name_len); smart_str_appends(&BG(url_adapt_state_ex).form_app, "\" value=\""); smart_str_append(&BG(url_adapt_state_ex).form_app, &val); smart_str_appends(&BG(url_adapt_state_ex).form_app, "\" />"); if (urlencode) efree(encoded); return SUCCESS; } PHPAPI int php_url_scanner_reset_vars(TSRMLS_D) { BG(url_adapt_state_ex).form_app.len = 0; BG(url_adapt_state_ex).url_app.len = 0; return SUCCESS; } PHP_MINIT_FUNCTION(url_scanner) { BG(url_adapt_state_ex).tags = NULL; BG(url_adapt_state_ex).form_app.c = BG(url_adapt_state_ex).url_app.c = 0; BG(url_adapt_state_ex).form_app.len = BG(url_adapt_state_ex).url_app.len = 0; REGISTER_INI_ENTRIES(); return SUCCESS; } PHP_MSHUTDOWN_FUNCTION(url_scanner) { UNREGISTER_INI_ENTRIES(); return SUCCESS; } PHP_RINIT_FUNCTION(url_scanner) { BG(url_adapt_state_ex).active = 0; return SUCCESS; } PHP_RSHUTDOWN_FUNCTION(url_scanner) { if (BG(url_adapt_state_ex).active) { php_url_scanner_ex_deactivate(TSRMLS_C); BG(url_adapt_state_ex).active = 0; } smart_str_free(&BG(url_adapt_state_ex).form_app); smart_str_free(&BG(url_adapt_state_ex).url_app); return SUCCESS; }
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-05-24-b60f6774dc-1056c57fa9.c
manybugs_data_96
/* * libfb - FreeBASIC's runtime library * Copyright (C) 2004-2010 The FreeBASIC development team. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * As a special exception, the copyright holders of this library give * you permission to link this library with independent modules to * produce an executable, regardless of the license terms of these * independent modules, and to copy and distribute the resulting * executable under terms of your choice, provided that you also meet, * for each linked independent module, the terms and conditions of the * license of that module. An independent module is a module which is * not derived from or based on this library. If you modify this library, * you may extend this exception to your version of the library, but * you are not obligated to do so. If you do not wish to do so, delete * this exception statement from your version. */ /* * str_midassign.c -- mid$ statement * * chng: oct/2004 written [v1ctor] * */ #include <stdlib.h> #include <string.h> #include "fb.h" /*:::::*/ FBCALL void fb_StrAssignMid ( FBSTRING *dst, int start, int len, FBSTRING *src ) { int src_len, dst_len; FB_STRLOCK(); if( (dst == NULL) || (dst->data == NULL) || (FB_STRSIZE( dst ) == 0) ) { fb_hStrDelTemp_NoLock( src ); fb_hStrDelTemp_NoLock( dst ); FB_STRUNLOCK(); return; } if( (src == NULL) || (src->data == NULL) || (FB_STRSIZE( src ) == 0) ) { fb_hStrDelTemp_NoLock( src ); fb_hStrDelTemp_NoLock( dst ); FB_STRUNLOCK(); return ; } src_len = FB_STRSIZE( src ); dst_len = FB_STRSIZE( dst ); if( (start > 0) && (start <= dst_len) ) { --start; if( (len < 1) || (len > src_len) ) len = src_len; if( start + len > dst_len ) len = (dst_len - start); memcpy( dst->data + start, src->data, len ); } /* del if temp */ fb_hStrDelTemp_NoLock( src ); fb_hStrDelTemp_NoLock( dst ); FB_STRUNLOCK(); } /* * libfb - FreeBASIC's runtime library * Copyright (C) 2004-2010 The FreeBASIC development team. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * As a special exception, the copyright holders of this library give * you permission to link this library with independent modules to * produce an executable, regardless of the license terms of these * independent modules, and to copy and distribute the resulting * executable under terms of your choice, provided that you also meet, * for each linked independent module, the terms and conditions of the * license of that module. An independent module is a module which is * not derived from or based on this library. If you modify this library, * you may extend this exception to your version of the library, but * you are not obligated to do so. If you do not wish to do so, delete * this exception statement from your version. */ /* * str_midassign.c -- mid$ statement * * chng: oct/2004 written [v1ctor] * */ #include <stdlib.h> #include <string.h> #include "fb.h" /*:::::*/ FBCALL void fb_StrAssignMid ( FBSTRING *dst, int start, int len, FBSTRING *src ) { int src_len, dst_len; FB_STRLOCK(); if( (dst == NULL) || (dst->data == NULL) || (FB_STRSIZE( dst ) == 0) ) { fb_hStrDelTemp_NoLock( src ); fb_hStrDelTemp_NoLock( dst ); FB_STRUNLOCK(); return; } if( (src == NULL) || (src->data == NULL) || (FB_STRSIZE( src ) == 0) ) { fb_hStrDelTemp_NoLock( src ); fb_hStrDelTemp_NoLock( dst ); FB_STRUNLOCK(); return ; } src_len = FB_STRSIZE( src ); dst_len = FB_STRSIZE( dst ); if( (start > 0) && (start <= dst_len) && (len != 0) ) { --start; if( (len < 0) || (len > src_len) ) len = src_len; if( start + len > dst_len ) len = (dst_len - start); memcpy( dst->data + start, src->data, len ); } /* del if temp */ fb_hStrDelTemp_NoLock( src ); fb_hStrDelTemp_NoLock( dst ); FB_STRUNLOCK(); }
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/fbc_5458-5459.c
manybugs_data_97
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Derick Rethans <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "php.h" #include "php_streams.h" #include "php_main.h" #include "php_globals.h" #include "php_ini.h" #include "ext/standard/info.h" #include "ext/standard/php_versioning.h" #include "ext/standard/php_math.h" #include "php_date.h" #include "zend_interfaces.h" #include "lib/timelib.h" #include <time.h> #ifdef PHP_WIN32 static __inline __int64 php_date_llabs( __int64 i ) { return i >= 0? i: -i; } #elif defined(__GNUC__) && __GNUC__ < 3 static __inline __int64_t php_date_llabs( __int64_t i ) { return i >= 0 ? i : -i; } #else static inline long long php_date_llabs( long long i ) { return i >= 0 ? i : -i; } #endif /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_date, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_gmdate, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_idate, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strtotime, 0, 0, 1) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, now) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mktime, 0, 0, 0) ZEND_ARG_INFO(0, hour) ZEND_ARG_INFO(0, min) ZEND_ARG_INFO(0, sec) ZEND_ARG_INFO(0, mon) ZEND_ARG_INFO(0, day) ZEND_ARG_INFO(0, year) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_gmmktime, 0, 0, 0) ZEND_ARG_INFO(0, hour) ZEND_ARG_INFO(0, min) ZEND_ARG_INFO(0, sec) ZEND_ARG_INFO(0, mon) ZEND_ARG_INFO(0, day) ZEND_ARG_INFO(0, year) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_checkdate, 0) ZEND_ARG_INFO(0, month) ZEND_ARG_INFO(0, day) ZEND_ARG_INFO(0, year) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strftime, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_gmstrftime, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_time, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_localtime, 0, 0, 0) ZEND_ARG_INFO(0, timestamp) ZEND_ARG_INFO(0, associative_array) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_getdate, 0, 0, 0) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_default_timezone_set, 0) ZEND_ARG_INFO(0, timezone_identifier) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_default_timezone_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_sunrise, 0, 0, 1) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, latitude) ZEND_ARG_INFO(0, longitude) ZEND_ARG_INFO(0, zenith) ZEND_ARG_INFO(0, gmt_offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_sunset, 0, 0, 1) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, latitude) ZEND_ARG_INFO(0, longitude) ZEND_ARG_INFO(0, zenith) ZEND_ARG_INFO(0, gmt_offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_sun_info, 0) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, latitude) ZEND_ARG_INFO(0, longitude) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_create, 0, 0, 0) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_create_from_format, 0, 0, 2) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_parse, 0, 0, 1) ZEND_ARG_INFO(0, date) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_parse_from_format, 0, 0, 2) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, date) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_get_last_errors, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_format, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_format, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_modify, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, modify) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_modify, 0, 0, 1) ZEND_ARG_INFO(0, modify) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_add, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, interval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_add, 0, 0, 1) ZEND_ARG_INFO(0, interval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_sub, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, interval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_sub, 0, 0, 1) ZEND_ARG_INFO(0, interval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_timezone_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_method_timezone_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_timezone_set, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, timezone) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_timezone_set, 0, 0, 1) ZEND_ARG_INFO(0, timezone) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_offset_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_method_offset_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_diff, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, object2) ZEND_ARG_INFO(0, absolute) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_diff, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, absolute) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_time_set, 0, 0, 3) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, hour) ZEND_ARG_INFO(0, minute) ZEND_ARG_INFO(0, second) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_time_set, 0, 0, 2) ZEND_ARG_INFO(0, hour) ZEND_ARG_INFO(0, minute) ZEND_ARG_INFO(0, second) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_date_set, 0, 0, 4) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, year) ZEND_ARG_INFO(0, month) ZEND_ARG_INFO(0, day) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_date_set, 0, 0, 3) ZEND_ARG_INFO(0, year) ZEND_ARG_INFO(0, month) ZEND_ARG_INFO(0, day) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_isodate_set, 0, 0, 3) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, year) ZEND_ARG_INFO(0, week) ZEND_ARG_INFO(0, day) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_isodate_set, 0, 0, 2) ZEND_ARG_INFO(0, year) ZEND_ARG_INFO(0, week) ZEND_ARG_INFO(0, day) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_timestamp_set, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, unixtimestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_timestamp_set, 0, 0, 1) ZEND_ARG_INFO(0, unixtimestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_timestamp_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_method_timestamp_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_open, 0, 0, 1) ZEND_ARG_INFO(0, timezone) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_name_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_method_name_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_name_from_abbr, 0, 0, 1) ZEND_ARG_INFO(0, abbr) ZEND_ARG_INFO(0, gmtoffset) ZEND_ARG_INFO(0, isdst) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_offset_get, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, datetime) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_method_offset_get, 0, 0, 1) ZEND_ARG_INFO(0, datetime) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_transitions_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, timestamp_begin) ZEND_ARG_INFO(0, timestamp_end) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_method_transitions_get, 0) ZEND_ARG_INFO(0, timestamp_begin) ZEND_ARG_INFO(0, timestamp_end) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_location_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_method_location_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_identifiers_list, 0, 0, 0) ZEND_ARG_INFO(0, what) ZEND_ARG_INFO(0, country) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_abbreviations_list, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_version_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_interval_create_from_date_string, 0, 0, 1) ZEND_ARG_INFO(0, time) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_interval_format, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_method_interval_format, 0) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_period_construct, 0, 0, 3) ZEND_ARG_INFO(0, start) ZEND_ARG_INFO(0, interval) ZEND_ARG_INFO(0, end) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_interval_construct, 0, 0, 0) ZEND_ARG_INFO(0, interval_spec) ZEND_END_ARG_INFO() /* }}} */ /* {{{ Function table */ const zend_function_entry date_functions[] = { PHP_FE(strtotime, arginfo_strtotime) PHP_FE(date, arginfo_date) PHP_FE(idate, arginfo_idate) PHP_FE(gmdate, arginfo_gmdate) PHP_FE(mktime, arginfo_mktime) PHP_FE(gmmktime, arginfo_gmmktime) PHP_FE(checkdate, arginfo_checkdate) #ifdef HAVE_STRFTIME PHP_FE(strftime, arginfo_strftime) PHP_FE(gmstrftime, arginfo_gmstrftime) #endif PHP_FE(time, arginfo_time) PHP_FE(localtime, arginfo_localtime) PHP_FE(getdate, arginfo_getdate) /* Advanced Interface */ PHP_FE(date_create, arginfo_date_create) PHP_FE(date_create_from_format, arginfo_date_create_from_format) PHP_FE(date_parse, arginfo_date_parse) PHP_FE(date_parse_from_format, arginfo_date_parse_from_format) PHP_FE(date_get_last_errors, arginfo_date_get_last_errors) PHP_FE(date_format, arginfo_date_format) PHP_FE(date_modify, arginfo_date_modify) PHP_FE(date_add, arginfo_date_add) PHP_FE(date_sub, arginfo_date_sub) PHP_FE(date_timezone_get, arginfo_date_timezone_get) PHP_FE(date_timezone_set, arginfo_date_timezone_set) PHP_FE(date_offset_get, arginfo_date_offset_get) PHP_FE(date_diff, arginfo_date_diff) PHP_FE(date_time_set, arginfo_date_time_set) PHP_FE(date_date_set, arginfo_date_date_set) PHP_FE(date_isodate_set, arginfo_date_isodate_set) PHP_FE(date_timestamp_set, arginfo_date_timestamp_set) PHP_FE(date_timestamp_get, arginfo_date_timestamp_get) PHP_FE(timezone_open, arginfo_timezone_open) PHP_FE(timezone_name_get, arginfo_timezone_name_get) PHP_FE(timezone_name_from_abbr, arginfo_timezone_name_from_abbr) PHP_FE(timezone_offset_get, arginfo_timezone_offset_get) PHP_FE(timezone_transitions_get, arginfo_timezone_transitions_get) PHP_FE(timezone_location_get, arginfo_timezone_location_get) PHP_FE(timezone_identifiers_list, arginfo_timezone_identifiers_list) PHP_FE(timezone_abbreviations_list, arginfo_timezone_abbreviations_list) PHP_FE(timezone_version_get, arginfo_timezone_version_get) PHP_FE(date_interval_create_from_date_string, arginfo_date_interval_create_from_date_string) PHP_FE(date_interval_format, arginfo_date_interval_format) /* Options and Configuration */ PHP_FE(date_default_timezone_set, arginfo_date_default_timezone_set) PHP_FE(date_default_timezone_get, arginfo_date_default_timezone_get) /* Astronomical functions */ PHP_FE(date_sunrise, arginfo_date_sunrise) PHP_FE(date_sunset, arginfo_date_sunset) PHP_FE(date_sun_info, arginfo_date_sun_info) {NULL, NULL, NULL} }; const zend_function_entry date_funcs_date[] = { PHP_ME(DateTime, __construct, arginfo_date_create, ZEND_ACC_CTOR|ZEND_ACC_PUBLIC) PHP_ME(DateTime, __wakeup, NULL, ZEND_ACC_PUBLIC) PHP_ME(DateTime, __set_state, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_ME_MAPPING(createFromFormat, date_create_from_format, arginfo_date_create_from_format, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_ME_MAPPING(getLastErrors, date_get_last_errors, arginfo_date_get_last_errors, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_ME_MAPPING(format, date_format, arginfo_date_method_format, 0) PHP_ME_MAPPING(modify, date_modify, arginfo_date_method_modify, 0) PHP_ME_MAPPING(add, date_add, arginfo_date_method_add, 0) PHP_ME_MAPPING(sub, date_sub, arginfo_date_method_sub, 0) PHP_ME_MAPPING(getTimezone, date_timezone_get, arginfo_date_method_timezone_get, 0) PHP_ME_MAPPING(setTimezone, date_timezone_set, arginfo_date_method_timezone_set, 0) PHP_ME_MAPPING(getOffset, date_offset_get, arginfo_date_method_offset_get, 0) PHP_ME_MAPPING(setTime, date_time_set, arginfo_date_method_time_set, 0) PHP_ME_MAPPING(setDate, date_date_set, arginfo_date_method_date_set, 0) PHP_ME_MAPPING(setISODate, date_isodate_set, arginfo_date_method_isodate_set, 0) PHP_ME_MAPPING(setTimestamp, date_timestamp_set, arginfo_date_method_timestamp_set, 0) PHP_ME_MAPPING(getTimestamp, date_timestamp_get, arginfo_date_method_timestamp_get, 0) PHP_ME_MAPPING(diff, date_diff, arginfo_date_method_diff, 0) {NULL, NULL, NULL} }; const zend_function_entry date_funcs_timezone[] = { PHP_ME(DateTimeZone, __construct, arginfo_timezone_open, ZEND_ACC_CTOR|ZEND_ACC_PUBLIC) PHP_ME_MAPPING(getName, timezone_name_get, arginfo_timezone_method_name_get, 0) PHP_ME_MAPPING(getOffset, timezone_offset_get, arginfo_timezone_method_offset_get, 0) PHP_ME_MAPPING(getTransitions, timezone_transitions_get, arginfo_timezone_method_transitions_get, 0) PHP_ME_MAPPING(getLocation, timezone_location_get, arginfo_timezone_method_location_get, 0) PHP_ME_MAPPING(listAbbreviations, timezone_abbreviations_list, arginfo_timezone_abbreviations_list, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_ME_MAPPING(listIdentifiers, timezone_identifiers_list, arginfo_timezone_identifiers_list, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) {NULL, NULL, NULL} }; const zend_function_entry date_funcs_interval[] = { PHP_ME(DateInterval, __construct, arginfo_date_interval_construct, ZEND_ACC_CTOR|ZEND_ACC_PUBLIC) PHP_ME_MAPPING(format, date_interval_format, arginfo_date_method_interval_format, 0) PHP_ME_MAPPING(createFromDateString, date_interval_create_from_date_string, arginfo_date_interval_create_from_date_string, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) {NULL, NULL, NULL} }; const zend_function_entry date_funcs_period[] = { PHP_ME(DatePeriod, __construct, arginfo_date_period_construct, ZEND_ACC_CTOR|ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; static char* guess_timezone(const timelib_tzdb *tzdb TSRMLS_DC); static void date_register_classes(TSRMLS_D); /* }}} */ ZEND_DECLARE_MODULE_GLOBALS(date) static PHP_GINIT_FUNCTION(date); /* True global */ timelib_tzdb *php_date_global_timezone_db; int php_date_global_timezone_db_enabled; #define DATE_DEFAULT_LATITUDE "31.7667" #define DATE_DEFAULT_LONGITUDE "35.2333" /* on 90'35; common sunset declaration (start of sun body appear) */ #define DATE_SUNSET_ZENITH "90.583333" /* on 90'35; common sunrise declaration (sun body disappeared) */ #define DATE_SUNRISE_ZENITH "90.583333" /* {{{ INI Settings */ PHP_INI_BEGIN() STD_PHP_INI_ENTRY("date.timezone", "", PHP_INI_ALL, OnUpdateString, default_timezone, zend_date_globals, date_globals) PHP_INI_ENTRY("date.default_latitude", DATE_DEFAULT_LATITUDE, PHP_INI_ALL, NULL) PHP_INI_ENTRY("date.default_longitude", DATE_DEFAULT_LONGITUDE, PHP_INI_ALL, NULL) PHP_INI_ENTRY("date.sunset_zenith", DATE_SUNSET_ZENITH, PHP_INI_ALL, NULL) PHP_INI_ENTRY("date.sunrise_zenith", DATE_SUNRISE_ZENITH, PHP_INI_ALL, NULL) PHP_INI_END() /* }}} */ zend_class_entry *date_ce_date, *date_ce_timezone, *date_ce_interval, *date_ce_period; PHPAPI zend_class_entry *php_date_get_date_ce(void) { return date_ce_date; } PHPAPI zend_class_entry *php_date_get_timezone_ce(void) { return date_ce_timezone; } static zend_object_handlers date_object_handlers_date; static zend_object_handlers date_object_handlers_timezone; static zend_object_handlers date_object_handlers_interval; static zend_object_handlers date_object_handlers_period; #define DATE_SET_CONTEXT \ zval *object; \ object = getThis(); \ #define DATE_FETCH_OBJECT \ php_date_obj *obj; \ DATE_SET_CONTEXT; \ if (object) { \ if (zend_parse_parameters_none() == FAILURE) { \ return; \ } \ } else { \ if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, NULL, "O", &object, date_ce_date) == FAILURE) { \ RETURN_FALSE; \ } \ } \ obj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); \ #define DATE_CHECK_INITIALIZED(member, class_name) \ if (!(member)) { \ php_error_docref(NULL TSRMLS_CC, E_WARNING, "The " #class_name " object has not been correctly initialized by its constructor"); \ RETURN_FALSE; \ } static void date_object_free_storage_date(void *object TSRMLS_DC); static void date_object_free_storage_timezone(void *object TSRMLS_DC); static void date_object_free_storage_interval(void *object TSRMLS_DC); static void date_object_free_storage_period(void *object TSRMLS_DC); static zend_object_value date_object_new_date(zend_class_entry *class_type TSRMLS_DC); static zend_object_value date_object_new_timezone(zend_class_entry *class_type TSRMLS_DC); static zend_object_value date_object_new_interval(zend_class_entry *class_type TSRMLS_DC); static zend_object_value date_object_new_period(zend_class_entry *class_type TSRMLS_DC); static zend_object_value date_object_clone_date(zval *this_ptr TSRMLS_DC); static zend_object_value date_object_clone_timezone(zval *this_ptr TSRMLS_DC); static zend_object_value date_object_clone_interval(zval *this_ptr TSRMLS_DC); static zend_object_value date_object_clone_period(zval *this_ptr TSRMLS_DC); static int date_object_compare_date(zval *d1, zval *d2 TSRMLS_DC); static HashTable *date_object_get_properties(zval *object TSRMLS_DC); static HashTable *date_object_get_properties_interval(zval *object TSRMLS_DC); zval *date_interval_read_property(zval *object, zval *member, int type, const zend_literal *key TSRMLS_DC); void date_interval_write_property(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC); /* {{{ Module struct */ zend_module_entry date_module_entry = { STANDARD_MODULE_HEADER_EX, NULL, NULL, "date", /* extension name */ date_functions, /* function list */ PHP_MINIT(date), /* process startup */ PHP_MSHUTDOWN(date), /* process shutdown */ PHP_RINIT(date), /* request startup */ PHP_RSHUTDOWN(date), /* request shutdown */ PHP_MINFO(date), /* extension info */ PHP_VERSION, /* extension version */ PHP_MODULE_GLOBALS(date), /* globals descriptor */ PHP_GINIT(date), /* globals ctor */ NULL, /* globals dtor */ NULL, /* post deactivate */ STANDARD_MODULE_PROPERTIES_EX }; /* }}} */ /* {{{ PHP_GINIT_FUNCTION */ static PHP_GINIT_FUNCTION(date) { date_globals->default_timezone = NULL; date_globals->timezone = NULL; date_globals->tzcache = NULL; } /* }}} */ static void _php_date_tzinfo_dtor(void *tzinfo) { timelib_tzinfo **tzi = (timelib_tzinfo **)tzinfo; timelib_tzinfo_dtor(*tzi); } /* {{{ PHP_RINIT_FUNCTION */ PHP_RINIT_FUNCTION(date) { if (DATEG(timezone)) { efree(DATEG(timezone)); } DATEG(timezone) = NULL; DATEG(tzcache) = NULL; DATEG(last_errors) = NULL; return SUCCESS; } /* }}} */ /* {{{ PHP_RSHUTDOWN_FUNCTION */ PHP_RSHUTDOWN_FUNCTION(date) { if (DATEG(timezone)) { efree(DATEG(timezone)); } DATEG(timezone) = NULL; if(DATEG(tzcache)) { zend_hash_destroy(DATEG(tzcache)); FREE_HASHTABLE(DATEG(tzcache)); DATEG(tzcache) = NULL; } if (DATEG(last_errors)) { timelib_error_container_dtor(DATEG(last_errors)); DATEG(last_errors) = NULL; } return SUCCESS; } /* }}} */ #define DATE_TIMEZONEDB php_date_global_timezone_db ? php_date_global_timezone_db : timelib_builtin_db() /* * RFC822, Section 5.1: http://www.ietf.org/rfc/rfc822.txt * date-time = [ day "," ] date time ; dd mm yy hh:mm:ss zzz * day = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" * date = 1*2DIGIT month 2DIGIT ; day month year e.g. 20 Jun 82 * month = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec" * time = hour zone ; ANSI and Military * hour = 2DIGIT ":" 2DIGIT [":" 2DIGIT] ; 00:00:00 - 23:59:59 * zone = "UT" / "GMT" / "EST" / "EDT" / "CST" / "CDT" / "MST" / "MDT" / "PST" / "PDT" / 1ALPHA / ( ("+" / "-") 4DIGIT ) */ #define DATE_FORMAT_RFC822 "D, d M y H:i:s O" /* * RFC850, Section 2.1.4: http://www.ietf.org/rfc/rfc850.txt * Format must be acceptable both to the ARPANET and to the getdate routine. * One format that is acceptable to both is Weekday, DD-Mon-YY HH:MM:SS TIMEZONE * TIMEZONE can be any timezone name (3 or more letters) */ #define DATE_FORMAT_RFC850 "l, d-M-y H:i:s T" /* * RFC1036, Section 2.1.2: http://www.ietf.org/rfc/rfc1036.txt * Its format must be acceptable both in RFC-822 and to the getdate(3) * Wdy, DD Mon YY HH:MM:SS TIMEZONE * There is no hope of having a complete list of timezones. Universal * Time (GMT), the North American timezones (PST, PDT, MST, MDT, CST, * CDT, EST, EDT) and the +/-hhmm offset specifed in RFC-822 should be supported. */ #define DATE_FORMAT_RFC1036 "D, d M y H:i:s O" /* * RFC1123, Section 5.2.14: http://www.ietf.org/rfc/rfc1123.txt * RFC-822 Date and Time Specification: RFC-822 Section 5 * The syntax for the date is hereby changed to: date = 1*2DIGIT month 2*4DIGIT */ #define DATE_FORMAT_RFC1123 "D, d M Y H:i:s O" /* * RFC2822, Section 3.3: http://www.ietf.org/rfc/rfc2822.txt * FWS = ([*WSP CRLF] 1*WSP) / ; Folding white space * CFWS = *([FWS] comment) (([FWS] comment) / FWS) * * date-time = [ day-of-week "," ] date FWS time [CFWS] * day-of-week = ([FWS] day-name) * day-name = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" * date = day month year * year = 4*DIGIT * month = (FWS month-name FWS) * month-name = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec" * day = ([FWS] 1*2DIGIT) * time = time-of-day FWS zone * time-of-day = hour ":" minute [ ":" second ] * hour = 2DIGIT * minute = 2DIGIT * second = 2DIGIT * zone = (( "+" / "-" ) 4DIGIT) */ #define DATE_FORMAT_RFC2822 "D, d M Y H:i:s O" /* * RFC3339, Section 5.6: http://www.ietf.org/rfc/rfc3339.txt * date-fullyear = 4DIGIT * date-month = 2DIGIT ; 01-12 * date-mday = 2DIGIT ; 01-28, 01-29, 01-30, 01-31 based on month/year * * time-hour = 2DIGIT ; 00-23 * time-minute = 2DIGIT ; 00-59 * time-second = 2DIGIT ; 00-58, 00-59, 00-60 based on leap second rules * * time-secfrac = "." 1*DIGIT * time-numoffset = ("+" / "-") time-hour ":" time-minute * time-offset = "Z" / time-numoffset * * partial-time = time-hour ":" time-minute ":" time-second [time-secfrac] * full-date = date-fullyear "-" date-month "-" date-mday * full-time = partial-time time-offset * * date-time = full-date "T" full-time */ #define DATE_FORMAT_RFC3339 "Y-m-d\\TH:i:sP" #define DATE_FORMAT_ISO8601 "Y-m-d\\TH:i:sO" #define DATE_TZ_ERRMSG \ "It is not safe to rely on the system's timezone settings. You are " \ "*required* to use the date.timezone setting or the " \ "date_default_timezone_set() function. In case you used any of those " \ "methods and you are still getting this warning, you most likely " \ "misspelled the timezone identifier. " #define SUNFUNCS_RET_TIMESTAMP 0 #define SUNFUNCS_RET_STRING 1 #define SUNFUNCS_RET_DOUBLE 2 /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(date) { REGISTER_INI_ENTRIES(); date_register_classes(TSRMLS_C); /* * RFC4287, Section 3.3: http://www.ietf.org/rfc/rfc4287.txt * A Date construct is an element whose content MUST conform to the * "date-time" production in [RFC3339]. In addition, an uppercase "T" * character MUST be used to separate date and time, and an uppercase * "Z" character MUST be present in the absence of a numeric time zone offset. */ REGISTER_STRING_CONSTANT("DATE_ATOM", DATE_FORMAT_RFC3339, CONST_CS | CONST_PERSISTENT); /* * Preliminary specification: http://wp.netscape.com/newsref/std/cookie_spec.html * "This is based on RFC 822, RFC 850, RFC 1036, and RFC 1123, * with the variations that the only legal time zone is GMT * and the separators between the elements of the date must be dashes." */ REGISTER_STRING_CONSTANT("DATE_COOKIE", DATE_FORMAT_RFC850, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_ISO8601", DATE_FORMAT_ISO8601, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC822", DATE_FORMAT_RFC822, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC850", DATE_FORMAT_RFC850, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC1036", DATE_FORMAT_RFC1036, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC1123", DATE_FORMAT_RFC1123, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC2822", DATE_FORMAT_RFC2822, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC3339", DATE_FORMAT_RFC3339, CONST_CS | CONST_PERSISTENT); /* * RSS 2.0 Specification: http://blogs.law.harvard.edu/tech/rss * "All date-times in RSS conform to the Date and Time Specification of RFC 822, * with the exception that the year may be expressed with two characters or four characters (four preferred)" */ REGISTER_STRING_CONSTANT("DATE_RSS", DATE_FORMAT_RFC1123, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_W3C", DATE_FORMAT_RFC3339, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SUNFUNCS_RET_TIMESTAMP", SUNFUNCS_RET_TIMESTAMP, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SUNFUNCS_RET_STRING", SUNFUNCS_RET_STRING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SUNFUNCS_RET_DOUBLE", SUNFUNCS_RET_DOUBLE, CONST_CS | CONST_PERSISTENT); php_date_global_timezone_db = NULL; php_date_global_timezone_db_enabled = 0; DATEG(last_errors) = NULL; return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ PHP_MSHUTDOWN_FUNCTION(date) { UNREGISTER_INI_ENTRIES(); if (DATEG(last_errors)) { timelib_error_container_dtor(DATEG(last_errors)); } return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(date) { const timelib_tzdb *tzdb = DATE_TIMEZONEDB; php_info_print_table_start(); php_info_print_table_row(2, "date/time support", "enabled"); php_info_print_table_row(2, "\"Olson\" Timezone Database Version", tzdb->version); php_info_print_table_row(2, "Timezone Database", php_date_global_timezone_db_enabled ? "external" : "internal"); php_info_print_table_row(2, "Default timezone", guess_timezone(tzdb TSRMLS_CC)); php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ /* {{{ Timezone Cache functions */ static timelib_tzinfo *php_date_parse_tzfile(char *formal_tzname, const timelib_tzdb *tzdb TSRMLS_DC) { timelib_tzinfo *tzi, **ptzi; if(!DATEG(tzcache)) { ALLOC_HASHTABLE(DATEG(tzcache)); zend_hash_init(DATEG(tzcache), 4, NULL, _php_date_tzinfo_dtor, 0); } if (zend_hash_find(DATEG(tzcache), formal_tzname, strlen(formal_tzname) + 1, (void **) &ptzi) == SUCCESS) { return *ptzi; } tzi = timelib_parse_tzfile(formal_tzname, tzdb); if (tzi) { zend_hash_add(DATEG(tzcache), formal_tzname, strlen(formal_tzname) + 1, (void *) &tzi, sizeof(timelib_tzinfo*), NULL); } return tzi; } /* }}} */ /* {{{ Helper functions */ static char* guess_timezone(const timelib_tzdb *tzdb TSRMLS_DC) { char *env; /* Checking configure timezone */ if (DATEG(timezone) && (strlen(DATEG(timezone)) > 0)) { return DATEG(timezone); } /* Check environment variable */ env = getenv("TZ"); if (env && *env && timelib_timezone_id_is_valid(env, tzdb)) { return env; } /* Check config setting for default timezone */ if (!DATEG(default_timezone)) { /* Special case: ext/date wasn't initialized yet */ zval ztz; if (SUCCESS == zend_get_configuration_directive("date.timezone", sizeof("date.timezone"), &ztz) && Z_TYPE(ztz) == IS_STRING && Z_STRLEN(ztz) > 0 && timelib_timezone_id_is_valid(Z_STRVAL(ztz), tzdb)) { return Z_STRVAL(ztz); } } else if (*DATEG(default_timezone) && timelib_timezone_id_is_valid(DATEG(default_timezone), tzdb)) { return DATEG(default_timezone); } #if HAVE_TM_ZONE /* Try to guess timezone from system information */ { struct tm *ta, tmbuf; time_t the_time; char *tzid = NULL; the_time = time(NULL); ta = php_localtime_r(&the_time, &tmbuf); if (ta) { tzid = timelib_timezone_id_from_abbr(ta->tm_zone, ta->tm_gmtoff, ta->tm_isdst); } if (! tzid) { tzid = "UTC"; } php_error_docref(NULL TSRMLS_CC, E_WARNING, DATE_TZ_ERRMSG "We selected '%s' for '%s/%.1f/%s' instead", tzid, ta ? ta->tm_zone : "Unknown", ta ? (float) (ta->tm_gmtoff / 3600) : 0, ta ? (ta->tm_isdst ? "DST" : "no DST") : "Unknown"); return tzid; } #endif #ifdef PHP_WIN32 { char *tzid; TIME_ZONE_INFORMATION tzi; switch (GetTimeZoneInformation(&tzi)) { /* DST in effect */ case TIME_ZONE_ID_DAYLIGHT: /* If user has disabled DST in the control panel, Windows returns 0 here */ if (tzi.DaylightBias == 0) { goto php_win_std_time; } tzid = timelib_timezone_id_from_abbr("", (tzi.Bias + tzi.DaylightBias) * -60, 1); if (! tzid) { tzid = "UTC"; } php_error_docref(NULL TSRMLS_CC, E_WARNING, DATE_TZ_ERRMSG "We selected '%s' for '%.1f/DST' instead", tzid, ((tzi.Bias + tzi.DaylightBias) / -60.0)); break; /* no DST or not in effect */ case TIME_ZONE_ID_UNKNOWN: case TIME_ZONE_ID_STANDARD: default: php_win_std_time: tzid = timelib_timezone_id_from_abbr("", (tzi.Bias + tzi.StandardBias) * -60, 0); if (! tzid) { tzid = "UTC"; } php_error_docref(NULL TSRMLS_CC, E_WARNING, DATE_TZ_ERRMSG "We selected '%s' for '%.1f/no DST' instead", tzid, ((tzi.Bias + tzi.StandardBias) / -60.0)); break; } return tzid; } #elif defined(NETWARE) /* Try to guess timezone from system information */ { char *tzid = timelib_timezone_id_from_abbr("", ((_timezone * -1) + (daylightOffset * daylightOnOff)), daylightOnOff); if (tzid) { return tzid; } } #endif /* Fallback to UTC */ php_error_docref(NULL TSRMLS_CC, E_WARNING, DATE_TZ_ERRMSG "We had to select 'UTC' because your platform doesn't provide functionality for the guessing algorithm"); return "UTC"; } PHPAPI timelib_tzinfo *get_timezone_info(TSRMLS_D) { char *tz; timelib_tzinfo *tzi; tz = guess_timezone(DATE_TIMEZONEDB TSRMLS_CC); tzi = php_date_parse_tzfile(tz, DATE_TIMEZONEDB TSRMLS_CC); if (! tzi) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Timezone database is corrupt - this should *never* happen!"); } return tzi; } /* }}} */ /* {{{ date() and gmdate() data */ #include "ext/standard/php_smart_str.h" static char *mon_full_names[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; static char *mon_short_names[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; static char *day_full_names[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; static char *day_short_names[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; static char *english_suffix(timelib_sll number) { if (number >= 10 && number <= 19) { return "th"; } else { switch (number % 10) { case 1: return "st"; case 2: return "nd"; case 3: return "rd"; } } return "th"; } /* }}} */ /* {{{ day of week helpers */ char *php_date_full_day_name(timelib_sll y, timelib_sll m, timelib_sll d) { timelib_sll day_of_week = timelib_day_of_week(y, m, d); if (day_of_week < 0) { return "Unknown"; } return day_full_names[day_of_week]; } char *php_date_short_day_name(timelib_sll y, timelib_sll m, timelib_sll d) { timelib_sll day_of_week = timelib_day_of_week(y, m, d); if (day_of_week < 0) { return "Unknown"; } return day_short_names[day_of_week]; } /* }}} */ /* {{{ date_format - (gm)date helper */ static char *date_format(char *format, int format_len, timelib_time *t, int localtime) { smart_str string = {0}; int i, length; char buffer[97]; timelib_time_offset *offset = NULL; timelib_sll isoweek, isoyear; int rfc_colon; if (!format_len) { return estrdup(""); } if (localtime) { if (t->zone_type == TIMELIB_ZONETYPE_ABBR) { offset = timelib_time_offset_ctor(); offset->offset = (t->z - (t->dst * 60)) * -60; offset->leap_secs = 0; offset->is_dst = t->dst; offset->abbr = strdup(t->tz_abbr); } else if (t->zone_type == TIMELIB_ZONETYPE_OFFSET) { offset = timelib_time_offset_ctor(); offset->offset = (t->z) * -60; offset->leap_secs = 0; offset->is_dst = 0; offset->abbr = malloc(9); /* GMT�xxxx\0 */ snprintf(offset->abbr, 9, "GMT%c%02d%02d", localtime ? ((offset->offset < 0) ? '-' : '+') : '+', localtime ? abs(offset->offset / 3600) : 0, localtime ? abs((offset->offset % 3600) / 60) : 0 ); } else { offset = timelib_get_time_zone_info(t->sse, t->tz_info); } } timelib_isoweek_from_date(t->y, t->m, t->d, &isoweek, &isoyear); for (i = 0; i < format_len; i++) { rfc_colon = 0; switch (format[i]) { /* day */ case 'd': length = slprintf(buffer, 32, "%02d", (int) t->d); break; case 'D': length = slprintf(buffer, 32, "%s", php_date_short_day_name(t->y, t->m, t->d)); break; case 'j': length = slprintf(buffer, 32, "%d", (int) t->d); break; case 'l': length = slprintf(buffer, 32, "%s", php_date_full_day_name(t->y, t->m, t->d)); break; case 'S': length = slprintf(buffer, 32, "%s", english_suffix(t->d)); break; case 'w': length = slprintf(buffer, 32, "%d", (int) timelib_day_of_week(t->y, t->m, t->d)); break; case 'N': length = slprintf(buffer, 32, "%d", (int) timelib_iso_day_of_week(t->y, t->m, t->d)); break; case 'z': length = slprintf(buffer, 32, "%d", (int) timelib_day_of_year(t->y, t->m, t->d)); break; /* week */ case 'W': length = slprintf(buffer, 32, "%02d", (int) isoweek); break; /* iso weeknr */ case 'o': length = slprintf(buffer, 32, "%d", (int) isoyear); break; /* iso year */ /* month */ case 'F': length = slprintf(buffer, 32, "%s", mon_full_names[t->m - 1]); break; case 'm': length = slprintf(buffer, 32, "%02d", (int) t->m); break; case 'M': length = slprintf(buffer, 32, "%s", mon_short_names[t->m - 1]); break; case 'n': length = slprintf(buffer, 32, "%d", (int) t->m); break; case 't': length = slprintf(buffer, 32, "%d", (int) timelib_days_in_month(t->y, t->m)); break; /* year */ case 'L': length = slprintf(buffer, 32, "%d", timelib_is_leap((int) t->y)); break; case 'y': length = slprintf(buffer, 32, "%02d", (int) t->y % 100); break; case 'Y': length = slprintf(buffer, 32, "%s%04lld", t->y < 0 ? "-" : "", php_date_llabs((timelib_sll) t->y)); break; /* time */ case 'a': length = slprintf(buffer, 32, "%s", t->h >= 12 ? "pm" : "am"); break; case 'A': length = slprintf(buffer, 32, "%s", t->h >= 12 ? "PM" : "AM"); break; case 'B': { int retval = (((((long)t->sse)-(((long)t->sse) - ((((long)t->sse) % 86400) + 3600))) * 10) / 864); while (retval < 0) { retval += 1000; } retval = retval % 1000; length = slprintf(buffer, 32, "%03d", retval); break; } case 'g': length = slprintf(buffer, 32, "%d", (t->h % 12) ? (int) t->h % 12 : 12); break; case 'G': length = slprintf(buffer, 32, "%d", (int) t->h); break; case 'h': length = slprintf(buffer, 32, "%02d", (t->h % 12) ? (int) t->h % 12 : 12); break; case 'H': length = slprintf(buffer, 32, "%02d", (int) t->h); break; case 'i': length = slprintf(buffer, 32, "%02d", (int) t->i); break; case 's': length = slprintf(buffer, 32, "%02d", (int) t->s); break; case 'u': length = slprintf(buffer, 32, "%06d", (int) floor(t->f * 1000000)); break; /* timezone */ case 'I': length = slprintf(buffer, 32, "%d", localtime ? offset->is_dst : 0); break; case 'P': rfc_colon = 1; /* break intentionally missing */ case 'O': length = slprintf(buffer, 32, "%c%02d%s%02d", localtime ? ((offset->offset < 0) ? '-' : '+') : '+', localtime ? abs(offset->offset / 3600) : 0, rfc_colon ? ":" : "", localtime ? abs((offset->offset % 3600) / 60) : 0 ); break; case 'T': length = slprintf(buffer, 32, "%s", localtime ? offset->abbr : "GMT"); break; case 'e': if (!localtime) { length = slprintf(buffer, 32, "%s", "UTC"); } else { switch (t->zone_type) { case TIMELIB_ZONETYPE_ID: length = slprintf(buffer, 32, "%s", t->tz_info->name); break; case TIMELIB_ZONETYPE_ABBR: length = slprintf(buffer, 32, "%s", offset->abbr); break; case TIMELIB_ZONETYPE_OFFSET: length = slprintf(buffer, 32, "%c%02d:%02d", ((offset->offset < 0) ? '-' : '+'), abs(offset->offset / 3600), abs((offset->offset % 3600) / 60) ); break; } } break; case 'Z': length = slprintf(buffer, 32, "%d", localtime ? offset->offset : 0); break; /* full date/time */ case 'c': length = slprintf(buffer, 96, "%04d-%02d-%02dT%02d:%02d:%02d%c%02d:%02d", (int) t->y, (int) t->m, (int) t->d, (int) t->h, (int) t->i, (int) t->s, localtime ? ((offset->offset < 0) ? '-' : '+') : '+', localtime ? abs(offset->offset / 3600) : 0, localtime ? abs((offset->offset % 3600) / 60) : 0 ); break; case 'r': length = slprintf(buffer, 96, "%3s, %02d %3s %04d %02d:%02d:%02d %c%02d%02d", php_date_short_day_name(t->y, t->m, t->d), (int) t->d, mon_short_names[t->m - 1], (int) t->y, (int) t->h, (int) t->i, (int) t->s, localtime ? ((offset->offset < 0) ? '-' : '+') : '+', localtime ? abs(offset->offset / 3600) : 0, localtime ? abs((offset->offset % 3600) / 60) : 0 ); break; case 'U': length = slprintf(buffer, 32, "%lld", (timelib_sll) t->sse); break; case '\\': if (i < format_len) i++; /* break intentionally missing */ default: buffer[0] = format[i]; buffer[1] = '\0'; length = 1; break; } smart_str_appendl(&string, buffer, length); } smart_str_0(&string); if (localtime) { timelib_time_offset_dtor(offset); } return string.c; } static void php_date(INTERNAL_FUNCTION_PARAMETERS, int localtime) { char *format; int format_len; long ts; char *string; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &format, &format_len, &ts) == FAILURE) { RETURN_FALSE; } if (ZEND_NUM_ARGS() == 1) { ts = time(NULL); } string = php_format_date(format, format_len, ts, localtime TSRMLS_CC); RETVAL_STRING(string, 0); } /* }}} */ PHPAPI char *php_format_date(char *format, int format_len, time_t ts, int localtime TSRMLS_DC) /* {{{ */ { timelib_time *t; timelib_tzinfo *tzi; char *string; t = timelib_time_ctor(); if (localtime) { tzi = get_timezone_info(TSRMLS_C); t->tz_info = tzi; t->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(t, ts); } else { tzi = NULL; timelib_unixtime2gmt(t, ts); } string = date_format(format, format_len, t, localtime); timelib_time_dtor(t); return string; } /* }}} */ /* {{{ php_idate */ PHPAPI int php_idate(char format, time_t ts, int localtime TSRMLS_DC) { timelib_time *t; timelib_tzinfo *tzi; int retval = -1; timelib_time_offset *offset = NULL; timelib_sll isoweek, isoyear; t = timelib_time_ctor(); if (!localtime) { tzi = get_timezone_info(TSRMLS_C); t->tz_info = tzi; t->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(t, ts); } else { tzi = NULL; timelib_unixtime2gmt(t, ts); } if (!localtime) { if (t->zone_type == TIMELIB_ZONETYPE_ABBR) { offset = timelib_time_offset_ctor(); offset->offset = (t->z - (t->dst * 60)) * -60; offset->leap_secs = 0; offset->is_dst = t->dst; offset->abbr = strdup(t->tz_abbr); } else if (t->zone_type == TIMELIB_ZONETYPE_OFFSET) { offset = timelib_time_offset_ctor(); offset->offset = (t->z - (t->dst * 60)) * -60; offset->leap_secs = 0; offset->is_dst = t->dst; offset->abbr = malloc(9); /* GMT�xxxx\0 */ snprintf(offset->abbr, 9, "GMT%c%02d%02d", !localtime ? ((offset->offset < 0) ? '-' : '+') : '+', !localtime ? abs(offset->offset / 3600) : 0, !localtime ? abs((offset->offset % 3600) / 60) : 0 ); } else { offset = timelib_get_time_zone_info(t->sse, t->tz_info); } } timelib_isoweek_from_date(t->y, t->m, t->d, &isoweek, &isoyear); switch (format) { /* day */ case 'd': case 'j': retval = (int) t->d; break; case 'w': retval = (int) timelib_day_of_week(t->y, t->m, t->d); break; case 'z': retval = (int) timelib_day_of_year(t->y, t->m, t->d); break; /* week */ case 'W': retval = (int) isoweek; break; /* iso weeknr */ /* month */ case 'm': case 'n': retval = (int) t->m; break; case 't': retval = (int) timelib_days_in_month(t->y, t->m); break; /* year */ case 'L': retval = (int) timelib_is_leap((int) t->y); break; case 'y': retval = (int) (t->y % 100); break; case 'Y': retval = (int) t->y; break; /* Swatch Beat a.k.a. Internet Time */ case 'B': retval = (((((long)t->sse)-(((long)t->sse) - ((((long)t->sse) % 86400) + 3600))) * 10) / 864); while (retval < 0) { retval += 1000; } retval = retval % 1000; break; /* time */ case 'g': case 'h': retval = (int) ((t->h % 12) ? (int) t->h % 12 : 12); break; case 'H': case 'G': retval = (int) t->h; break; case 'i': retval = (int) t->i; break; case 's': retval = (int) t->s; break; /* timezone */ case 'I': retval = (int) (!localtime ? offset->is_dst : 0); break; case 'Z': retval = (int) (!localtime ? offset->offset : 0); break; case 'U': retval = (int) t->sse; break; } if (!localtime) { timelib_time_offset_dtor(offset); } timelib_time_dtor(t); return retval; } /* }}} */ /* {{{ proto string date(string format [, long timestamp]) Format a local date/time */ PHP_FUNCTION(date) { php_date(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto string gmdate(string format [, long timestamp]) Format a GMT date/time */ PHP_FUNCTION(gmdate) { php_date(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto int idate(string format [, int timestamp]) Format a local time/date as integer */ PHP_FUNCTION(idate) { char *format; int format_len; long ts = 0; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &format, &format_len, &ts) == FAILURE) { RETURN_FALSE; } if (format_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "idate format is one char"); RETURN_FALSE; } if (ZEND_NUM_ARGS() == 1) { ts = time(NULL); } ret = php_idate(format[0], ts, 0 TSRMLS_CC); if (ret == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unrecognized date format token."); RETURN_FALSE; } RETURN_LONG(ret); } /* }}} */ /* {{{ php_date_set_tzdb - NOT THREADSAFE */ PHPAPI void php_date_set_tzdb(timelib_tzdb *tzdb) { const timelib_tzdb *builtin = timelib_builtin_db(); if (php_version_compare(tzdb->version, builtin->version) > 0) { php_date_global_timezone_db = tzdb; php_date_global_timezone_db_enabled = 1; } } /* }}} */ /* {{{ php_parse_date: Backwards compability function */ PHPAPI signed long php_parse_date(char *string, signed long *now) { timelib_time *parsed_time; timelib_error_container *error = NULL; int error2; signed long retval; parsed_time = timelib_strtotime(string, strlen(string), &error, DATE_TIMEZONEDB); if (error->error_count) { timelib_error_container_dtor(error); return -1; } timelib_error_container_dtor(error); timelib_update_ts(parsed_time, NULL); retval = timelib_date_to_int(parsed_time, &error2); timelib_time_dtor(parsed_time); if (error2) { return -1; } return retval; } /* }}} */ /* {{{ proto int strtotime(string time [, int now ]) Convert string representation of date and time to a timestamp */ PHP_FUNCTION(strtotime) { char *times, *initial_ts; int time_len, error1, error2; struct timelib_error_container *error; long preset_ts = 0, ts; timelib_time *t, *now; timelib_tzinfo *tzi; tzi = get_timezone_info(TSRMLS_C); if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "sl", &times, &time_len, &preset_ts) != FAILURE) { /* We have an initial timestamp */ now = timelib_time_ctor(); initial_ts = emalloc(25); snprintf(initial_ts, 24, "@%ld UTC", preset_ts); t = timelib_strtotime(initial_ts, strlen(initial_ts), NULL, DATE_TIMEZONEDB); /* we ignore the error here, as this should never fail */ timelib_update_ts(t, tzi); now->tz_info = tzi; now->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(now, t->sse); timelib_time_dtor(t); efree(initial_ts); } else if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &times, &time_len, &preset_ts) != FAILURE) { /* We have no initial timestamp */ now = timelib_time_ctor(); now->tz_info = tzi; now->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(now, (timelib_sll) time(NULL)); } else { RETURN_FALSE; } if (!time_len) { timelib_time_dtor(now); RETURN_FALSE; } t = timelib_strtotime(times, time_len, &error, DATE_TIMEZONEDB); error1 = error->error_count; timelib_error_container_dtor(error); timelib_fill_holes(t, now, TIMELIB_NO_CLONE); timelib_update_ts(t, tzi); ts = timelib_date_to_int(t, &error2); timelib_time_dtor(now); timelib_time_dtor(t); if (error1 || error2) { RETURN_FALSE; } else { RETURN_LONG(ts); } } /* }}} */ /* {{{ php_mktime - (gm)mktime helper */ PHPAPI void php_mktime(INTERNAL_FUNCTION_PARAMETERS, int gmt) { long hou = 0, min = 0, sec = 0, mon = 0, day = 0, yea = 0, dst = -1; timelib_time *now; timelib_tzinfo *tzi = NULL; long ts, adjust_seconds = 0; int error; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lllllll", &hou, &min, &sec, &mon, &day, &yea, &dst) == FAILURE) { RETURN_FALSE; } /* Initialize structure with current time */ now = timelib_time_ctor(); if (gmt) { timelib_unixtime2gmt(now, (timelib_sll) time(NULL)); } else { tzi = get_timezone_info(TSRMLS_C); now->tz_info = tzi; now->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(now, (timelib_sll) time(NULL)); } /* Fill in the new data */ switch (ZEND_NUM_ARGS()) { case 7: /* break intentionally missing */ case 6: if (yea >= 0 && yea < 70) { yea += 2000; } else if (yea >= 70 && yea <= 100) { yea += 1900; } now->y = yea; /* break intentionally missing again */ case 5: now->d = day; /* break missing intentionally here too */ case 4: now->m = mon; /* and here */ case 3: now->s = sec; /* yup, this break isn't here on purpose too */ case 2: now->i = min; /* last intentionally missing break */ case 1: now->h = hou; break; default: php_error_docref(NULL TSRMLS_CC, E_STRICT, "You should be using the time() function instead"); } /* Update the timestamp */ if (gmt) { timelib_update_ts(now, NULL); } else { timelib_update_ts(now, tzi); } /* Support for the deprecated is_dst parameter */ if (dst != -1) { php_error_docref(NULL TSRMLS_CC, E_DEPRECATED, "The is_dst parameter is deprecated"); if (gmt) { /* GMT never uses DST */ if (dst == 1) { adjust_seconds = -3600; } } else { /* Figure out is_dst for current TS */ timelib_time_offset *tmp_offset; tmp_offset = timelib_get_time_zone_info(now->sse, tzi); if (dst == 1 && tmp_offset->is_dst == 0) { adjust_seconds = -3600; } if (dst == 0 && tmp_offset->is_dst == 1) { adjust_seconds = +3600; } timelib_time_offset_dtor(tmp_offset); } } /* Clean up and return */ ts = timelib_date_to_int(now, &error); ts += adjust_seconds; timelib_time_dtor(now); if (error) { RETURN_FALSE; } else { RETURN_LONG(ts); } } /* }}} */ /* {{{ proto int mktime([int hour [, int min [, int sec [, int mon [, int day [, int year]]]]]]) Get UNIX timestamp for a date */ PHP_FUNCTION(mktime) { php_mktime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto int gmmktime([int hour [, int min [, int sec [, int mon [, int day [, int year]]]]]]) Get UNIX timestamp for a GMT date */ PHP_FUNCTION(gmmktime) { php_mktime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto bool checkdate(int month, int day, int year) Returns true(1) if it is a valid date in gregorian calendar */ PHP_FUNCTION(checkdate) { long m, d, y; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lll", &m, &d, &y) == FAILURE) { RETURN_FALSE; } if (y < 1 || y > 32767 || !timelib_valid_date(y, m, d)) { RETURN_FALSE; } RETURN_TRUE; /* True : This month, day, year arguments are valid */ } /* }}} */ #ifdef HAVE_STRFTIME /* {{{ php_strftime - (gm)strftime helper */ PHPAPI void php_strftime(INTERNAL_FUNCTION_PARAMETERS, int gmt) { char *format, *buf; int format_len; long timestamp = 0; struct tm ta; int max_reallocs = 5; size_t buf_len = 64, real_len; timelib_time *ts; timelib_tzinfo *tzi; timelib_time_offset *offset = NULL; timestamp = (long) time(NULL); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &format, &format_len, &timestamp) == FAILURE) { RETURN_FALSE; } if (format_len == 0) { RETURN_FALSE; } ts = timelib_time_ctor(); if (gmt) { tzi = NULL; timelib_unixtime2gmt(ts, (timelib_sll) timestamp); } else { tzi = get_timezone_info(TSRMLS_C); ts->tz_info = tzi; ts->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(ts, (timelib_sll) timestamp); } ta.tm_sec = ts->s; ta.tm_min = ts->i; ta.tm_hour = ts->h; ta.tm_mday = ts->d; ta.tm_mon = ts->m - 1; ta.tm_year = ts->y - 1900; ta.tm_wday = timelib_day_of_week(ts->y, ts->m, ts->d); ta.tm_yday = timelib_day_of_year(ts->y, ts->m, ts->d); if (gmt) { ta.tm_isdst = 0; #if HAVE_TM_GMTOFF ta.tm_gmtoff = 0; #endif #if HAVE_TM_ZONE ta.tm_zone = "GMT"; #endif } else { offset = timelib_get_time_zone_info(timestamp, tzi); ta.tm_isdst = offset->is_dst; #if HAVE_TM_GMTOFF ta.tm_gmtoff = offset->offset; #endif #if HAVE_TM_ZONE ta.tm_zone = offset->abbr; #endif } buf = (char *) emalloc(buf_len); while ((real_len=strftime(buf, buf_len, format, &ta))==buf_len || real_len==0) { buf_len *= 2; buf = (char *) erealloc(buf, buf_len); if (!--max_reallocs) { break; } } timelib_time_dtor(ts); if (!gmt) { timelib_time_offset_dtor(offset); } if (real_len && real_len != buf_len) { buf = (char *) erealloc(buf, real_len + 1); RETURN_STRINGL(buf, real_len, 0); } efree(buf); RETURN_FALSE; } /* }}} */ /* {{{ proto string strftime(string format [, int timestamp]) Format a local time/date according to locale settings */ PHP_FUNCTION(strftime) { php_strftime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto string gmstrftime(string format [, int timestamp]) Format a GMT/UCT time/date according to locale settings */ PHP_FUNCTION(gmstrftime) { php_strftime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ #endif /* {{{ proto int time(void) Return current UNIX timestamp */ PHP_FUNCTION(time) { RETURN_LONG((long)time(NULL)); } /* }}} */ /* {{{ proto array localtime([int timestamp [, bool associative_array]]) Returns the results of the C system call localtime as an associative array if the associative_array argument is set to 1 other wise it is a regular array */ PHP_FUNCTION(localtime) { long timestamp = (long)time(NULL); zend_bool associative = 0; timelib_tzinfo *tzi; timelib_time *ts; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lb", &timestamp, &associative) == FAILURE) { RETURN_FALSE; } tzi = get_timezone_info(TSRMLS_C); ts = timelib_time_ctor(); ts->tz_info = tzi; ts->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(ts, (timelib_sll) timestamp); array_init(return_value); if (associative) { add_assoc_long(return_value, "tm_sec", ts->s); add_assoc_long(return_value, "tm_min", ts->i); add_assoc_long(return_value, "tm_hour", ts->h); add_assoc_long(return_value, "tm_mday", ts->d); add_assoc_long(return_value, "tm_mon", ts->m - 1); add_assoc_long(return_value, "tm_year", ts->y - 1900); add_assoc_long(return_value, "tm_wday", timelib_day_of_week(ts->y, ts->m, ts->d)); add_assoc_long(return_value, "tm_yday", timelib_day_of_year(ts->y, ts->m, ts->d)); add_assoc_long(return_value, "tm_isdst", ts->dst); } else { add_next_index_long(return_value, ts->s); add_next_index_long(return_value, ts->i); add_next_index_long(return_value, ts->h); add_next_index_long(return_value, ts->d); add_next_index_long(return_value, ts->m - 1); add_next_index_long(return_value, ts->y- 1900); add_next_index_long(return_value, timelib_day_of_week(ts->y, ts->m, ts->d)); add_next_index_long(return_value, timelib_day_of_year(ts->y, ts->m, ts->d)); add_next_index_long(return_value, ts->dst); } timelib_time_dtor(ts); } /* }}} */ /* {{{ proto array getdate([int timestamp]) Get date/time information */ PHP_FUNCTION(getdate) { long timestamp = (long)time(NULL); timelib_tzinfo *tzi; timelib_time *ts; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &timestamp) == FAILURE) { RETURN_FALSE; } tzi = get_timezone_info(TSRMLS_C); ts = timelib_time_ctor(); ts->tz_info = tzi; ts->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(ts, (timelib_sll) timestamp); array_init(return_value); add_assoc_long(return_value, "seconds", ts->s); add_assoc_long(return_value, "minutes", ts->i); add_assoc_long(return_value, "hours", ts->h); add_assoc_long(return_value, "mday", ts->d); add_assoc_long(return_value, "wday", timelib_day_of_week(ts->y, ts->m, ts->d)); add_assoc_long(return_value, "mon", ts->m); add_assoc_long(return_value, "year", ts->y); add_assoc_long(return_value, "yday", timelib_day_of_year(ts->y, ts->m, ts->d)); add_assoc_string(return_value, "weekday", php_date_full_day_name(ts->y, ts->m, ts->d), 1); add_assoc_string(return_value, "month", mon_full_names[ts->m - 1], 1); add_index_long(return_value, 0, timestamp); timelib_time_dtor(ts); } /* }}} */ #define PHP_DATE_TIMEZONE_GROUP_AFRICA 0x0001 #define PHP_DATE_TIMEZONE_GROUP_AMERICA 0x0002 #define PHP_DATE_TIMEZONE_GROUP_ANTARCTICA 0x0004 #define PHP_DATE_TIMEZONE_GROUP_ARCTIC 0x0008 #define PHP_DATE_TIMEZONE_GROUP_ASIA 0x0010 #define PHP_DATE_TIMEZONE_GROUP_ATLANTIC 0x0020 #define PHP_DATE_TIMEZONE_GROUP_AUSTRALIA 0x0040 #define PHP_DATE_TIMEZONE_GROUP_EUROPE 0x0080 #define PHP_DATE_TIMEZONE_GROUP_INDIAN 0x0100 #define PHP_DATE_TIMEZONE_GROUP_PACIFIC 0x0200 #define PHP_DATE_TIMEZONE_GROUP_UTC 0x0400 #define PHP_DATE_TIMEZONE_GROUP_ALL 0x07FF #define PHP_DATE_TIMEZONE_GROUP_ALL_W_BC 0x0FFF #define PHP_DATE_TIMEZONE_PER_COUNTRY 0x1000 #define PHP_DATE_PERIOD_EXCLUDE_START_DATE 0x0001 /* define an overloaded iterator structure */ typedef struct { zend_object_iterator intern; zval *date_period_zval; zval *current; php_period_obj *object; int current_index; } date_period_it; /* {{{ date_period_it_invalidate_current */ static void date_period_it_invalidate_current(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; if (iterator->current) { zval_ptr_dtor(&iterator->current); iterator->current = NULL; } } /* }}} */ /* {{{ date_period_it_dtor */ static void date_period_it_dtor(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; date_period_it_invalidate_current(iter TSRMLS_CC); zval_ptr_dtor(&iterator->date_period_zval); efree(iterator); } /* }}} */ /* {{{ date_period_it_has_more */ static int date_period_it_has_more(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; php_period_obj *object = iterator->object; timelib_time *it_time = object->current; /* apply modification if it's not the first iteration */ if (!object->include_start_date || iterator->current_index > 0) { it_time->have_relative = 1; it_time->relative = *object->interval; it_time->sse_uptodate = 0; timelib_update_ts(it_time, NULL); timelib_update_from_sse(it_time); } if (object->end) { return object->current->sse < object->end->sse ? SUCCESS : FAILURE; } else { return (iterator->current_index < object->recurrences) ? SUCCESS : FAILURE; } } /* }}} */ /* {{{ date_period_it_current_data */ static void date_period_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; php_period_obj *object = iterator->object; timelib_time *it_time = object->current; php_date_obj *newdateobj; /* Create new object */ MAKE_STD_ZVAL(iterator->current); php_date_instantiate(date_ce_date, iterator->current TSRMLS_CC); newdateobj = (php_date_obj *) zend_object_store_get_object(iterator->current TSRMLS_CC); newdateobj->time = timelib_time_ctor(); *newdateobj->time = *it_time; if (it_time->tz_abbr) { newdateobj->time->tz_abbr = strdup(it_time->tz_abbr); } if (it_time->tz_info) { newdateobj->time->tz_info = it_time->tz_info; } *data = &iterator->current; } /* }}} */ /* {{{ date_period_it_current_key */ static int date_period_it_current_key(zend_object_iterator *iter, char **str_key, uint *str_key_len, ulong *int_key TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; *int_key = iterator->current_index; return HASH_KEY_IS_LONG; } /* }}} */ /* {{{ date_period_it_move_forward */ static void date_period_it_move_forward(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; iterator->current_index++; date_period_it_invalidate_current(iter TSRMLS_CC); } /* }}} */ /* {{{ date_period_it_rewind */ static void date_period_it_rewind(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; iterator->current_index = 0; if (iterator->object->current) { timelib_time_dtor(iterator->object->current); } iterator->object->current = timelib_time_clone(iterator->object->start); date_period_it_invalidate_current(iter TSRMLS_CC); } /* }}} */ /* iterator handler table */ zend_object_iterator_funcs date_period_it_funcs = { date_period_it_dtor, date_period_it_has_more, date_period_it_current_data, date_period_it_current_key, date_period_it_move_forward, date_period_it_rewind, date_period_it_invalidate_current }; zend_object_iterator *date_object_period_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) { date_period_it *iterator = emalloc(sizeof(date_period_it)); php_period_obj *dpobj = (php_period_obj *)zend_object_store_get_object(object TSRMLS_CC); if (by_ref) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } Z_ADDREF_P(object); iterator->intern.data = (void*) dpobj; iterator->intern.funcs = &date_period_it_funcs; iterator->date_period_zval = object; iterator->object = dpobj; iterator->current = NULL; return (zend_object_iterator*)iterator; } static void date_register_classes(TSRMLS_D) { zend_class_entry ce_date, ce_timezone, ce_interval, ce_period; INIT_CLASS_ENTRY(ce_date, "DateTime", date_funcs_date); ce_date.create_object = date_object_new_date; date_ce_date = zend_register_internal_class_ex(&ce_date, NULL, NULL TSRMLS_CC); memcpy(&date_object_handlers_date, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); date_object_handlers_date.clone_obj = date_object_clone_date; date_object_handlers_date.compare_objects = date_object_compare_date; date_object_handlers_date.get_properties = date_object_get_properties; #define REGISTER_DATE_CLASS_CONST_STRING(const_name, value) \ zend_declare_class_constant_stringl(date_ce_date, const_name, sizeof(const_name)-1, value, sizeof(value)-1 TSRMLS_CC); REGISTER_DATE_CLASS_CONST_STRING("ATOM", DATE_FORMAT_RFC3339); REGISTER_DATE_CLASS_CONST_STRING("COOKIE", DATE_FORMAT_RFC850); REGISTER_DATE_CLASS_CONST_STRING("ISO8601", DATE_FORMAT_ISO8601); REGISTER_DATE_CLASS_CONST_STRING("RFC822", DATE_FORMAT_RFC822); REGISTER_DATE_CLASS_CONST_STRING("RFC850", DATE_FORMAT_RFC850); REGISTER_DATE_CLASS_CONST_STRING("RFC1036", DATE_FORMAT_RFC1036); REGISTER_DATE_CLASS_CONST_STRING("RFC1123", DATE_FORMAT_RFC1123); REGISTER_DATE_CLASS_CONST_STRING("RFC2822", DATE_FORMAT_RFC2822); REGISTER_DATE_CLASS_CONST_STRING("RFC3339", DATE_FORMAT_RFC3339); REGISTER_DATE_CLASS_CONST_STRING("RSS", DATE_FORMAT_RFC1123); REGISTER_DATE_CLASS_CONST_STRING("W3C", DATE_FORMAT_RFC3339); INIT_CLASS_ENTRY(ce_timezone, "DateTimeZone", date_funcs_timezone); ce_timezone.create_object = date_object_new_timezone; date_ce_timezone = zend_register_internal_class_ex(&ce_timezone, NULL, NULL TSRMLS_CC); memcpy(&date_object_handlers_timezone, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); date_object_handlers_timezone.clone_obj = date_object_clone_timezone; #define REGISTER_TIMEZONE_CLASS_CONST_STRING(const_name, value) \ zend_declare_class_constant_long(date_ce_timezone, const_name, sizeof(const_name)-1, value TSRMLS_CC); REGISTER_TIMEZONE_CLASS_CONST_STRING("AFRICA", PHP_DATE_TIMEZONE_GROUP_AFRICA); REGISTER_TIMEZONE_CLASS_CONST_STRING("AMERICA", PHP_DATE_TIMEZONE_GROUP_AMERICA); REGISTER_TIMEZONE_CLASS_CONST_STRING("ANTARCTICA", PHP_DATE_TIMEZONE_GROUP_ANTARCTICA); REGISTER_TIMEZONE_CLASS_CONST_STRING("ARCTIC", PHP_DATE_TIMEZONE_GROUP_ARCTIC); REGISTER_TIMEZONE_CLASS_CONST_STRING("ASIA", PHP_DATE_TIMEZONE_GROUP_ASIA); REGISTER_TIMEZONE_CLASS_CONST_STRING("ATLANTIC", PHP_DATE_TIMEZONE_GROUP_ATLANTIC); REGISTER_TIMEZONE_CLASS_CONST_STRING("AUSTRALIA", PHP_DATE_TIMEZONE_GROUP_AUSTRALIA); REGISTER_TIMEZONE_CLASS_CONST_STRING("EUROPE", PHP_DATE_TIMEZONE_GROUP_EUROPE); REGISTER_TIMEZONE_CLASS_CONST_STRING("INDIAN", PHP_DATE_TIMEZONE_GROUP_INDIAN); REGISTER_TIMEZONE_CLASS_CONST_STRING("PACIFIC", PHP_DATE_TIMEZONE_GROUP_PACIFIC); REGISTER_TIMEZONE_CLASS_CONST_STRING("UTC", PHP_DATE_TIMEZONE_GROUP_UTC); REGISTER_TIMEZONE_CLASS_CONST_STRING("ALL", PHP_DATE_TIMEZONE_GROUP_ALL); REGISTER_TIMEZONE_CLASS_CONST_STRING("ALL_WITH_BC", PHP_DATE_TIMEZONE_GROUP_ALL_W_BC); REGISTER_TIMEZONE_CLASS_CONST_STRING("PER_COUNTRY", PHP_DATE_TIMEZONE_PER_COUNTRY); INIT_CLASS_ENTRY(ce_interval, "DateInterval", date_funcs_interval); ce_interval.create_object = date_object_new_interval; date_ce_interval = zend_register_internal_class_ex(&ce_interval, NULL, NULL TSRMLS_CC); memcpy(&date_object_handlers_interval, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); date_object_handlers_interval.clone_obj = date_object_clone_interval; date_object_handlers_interval.read_property = date_interval_read_property; date_object_handlers_interval.write_property = date_interval_write_property; date_object_handlers_interval.get_properties = date_object_get_properties_interval; date_object_handlers_interval.get_property_ptr_ptr = NULL; INIT_CLASS_ENTRY(ce_period, "DatePeriod", date_funcs_period); ce_period.create_object = date_object_new_period; date_ce_period = zend_register_internal_class_ex(&ce_period, NULL, NULL TSRMLS_CC); date_ce_period->get_iterator = date_object_period_get_iterator; date_ce_period->iterator_funcs.funcs = &date_period_it_funcs; zend_class_implements(date_ce_period TSRMLS_CC, 1, zend_ce_traversable); memcpy(&date_object_handlers_period, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); date_object_handlers_period.clone_obj = date_object_clone_period; #define REGISTER_PERIOD_CLASS_CONST_STRING(const_name, value) \ zend_declare_class_constant_long(date_ce_period, const_name, sizeof(const_name)-1, value TSRMLS_CC); REGISTER_PERIOD_CLASS_CONST_STRING("EXCLUDE_START_DATE", PHP_DATE_PERIOD_EXCLUDE_START_DATE); } static inline zend_object_value date_object_new_date_ex(zend_class_entry *class_type, php_date_obj **ptr TSRMLS_DC) { php_date_obj *intern; zend_object_value retval; intern = emalloc(sizeof(php_date_obj)); memset(intern, 0, sizeof(php_date_obj)); if (ptr) { *ptr = intern; } zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) date_object_free_storage_date, NULL TSRMLS_CC); retval.handlers = &date_object_handlers_date; return retval; } static zend_object_value date_object_new_date(zend_class_entry *class_type TSRMLS_DC) { return date_object_new_date_ex(class_type, NULL TSRMLS_CC); } static zend_object_value date_object_clone_date(zval *this_ptr TSRMLS_DC) { php_date_obj *new_obj = NULL; php_date_obj *old_obj = (php_date_obj *) zend_object_store_get_object(this_ptr TSRMLS_CC); zend_object_value new_ov = date_object_new_date_ex(old_obj->std.ce, &new_obj TSRMLS_CC); zend_objects_clone_members(&new_obj->std, new_ov, &old_obj->std, Z_OBJ_HANDLE_P(this_ptr) TSRMLS_CC); /* this should probably moved to a new `timelib_time *timelime_time_clone(timelib_time *)` */ new_obj->time = timelib_time_ctor(); *new_obj->time = *old_obj->time; if (old_obj->time->tz_abbr) { new_obj->time->tz_abbr = strdup(old_obj->time->tz_abbr); } if (old_obj->time->tz_info) { new_obj->time->tz_info = old_obj->time->tz_info; } return new_ov; } static int date_object_compare_date(zval *d1, zval *d2 TSRMLS_DC) { if (Z_TYPE_P(d1) == IS_OBJECT && Z_TYPE_P(d2) == IS_OBJECT && instanceof_function(Z_OBJCE_P(d1), date_ce_date TSRMLS_CC) && instanceof_function(Z_OBJCE_P(d2), date_ce_date TSRMLS_CC)) { php_date_obj *o1 = zend_object_store_get_object(d1 TSRMLS_CC); php_date_obj *o2 = zend_object_store_get_object(d2 TSRMLS_CC); if (!o1->time->sse_uptodate) { timelib_update_ts(o1->time, o1->time->tz_info); } if (!o2->time->sse_uptodate) { timelib_update_ts(o2->time, o2->time->tz_info); } return (o1->time->sse == o2->time->sse) ? 0 : ((o1->time->sse < o2->time->sse) ? -1 : 1); } return 1; } static HashTable *date_object_get_properties(zval *object TSRMLS_DC) { HashTable *props; zval *zv; php_date_obj *dateobj; dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); props = zend_std_get_properties(object TSRMLS_CC); if (!dateobj->time || GC_G(gc_active)) { return props; } /* first we add the date and time in ISO format */ MAKE_STD_ZVAL(zv); ZVAL_STRING(zv, date_format("Y-m-d H:i:s", 12, dateobj->time, 1), 0); zend_hash_update(props, "date", 5, &zv, sizeof(zval), NULL); /* then we add the timezone name (or similar) */ if (dateobj->time->is_localtime) { MAKE_STD_ZVAL(zv); ZVAL_LONG(zv, dateobj->time->zone_type); zend_hash_update(props, "timezone_type", 14, &zv, sizeof(zval), NULL); MAKE_STD_ZVAL(zv); switch (dateobj->time->zone_type) { case TIMELIB_ZONETYPE_ID: ZVAL_STRING(zv, dateobj->time->tz_info->name, 1); break; case TIMELIB_ZONETYPE_OFFSET: { char *tmpstr = emalloc(sizeof("UTC+05:00")); timelib_sll utc_offset = dateobj->time->z; snprintf(tmpstr, sizeof("+05:00"), "%c%02d:%02d", utc_offset > 0 ? '-' : '+', abs(utc_offset / 60), abs((utc_offset % 60))); ZVAL_STRING(zv, tmpstr, 0); } break; case TIMELIB_ZONETYPE_ABBR: ZVAL_STRING(zv, dateobj->time->tz_abbr, 1); break; } zend_hash_update(props, "timezone", 9, &zv, sizeof(zval), NULL); } return props; } static inline zend_object_value date_object_new_timezone_ex(zend_class_entry *class_type, php_timezone_obj **ptr TSRMLS_DC) { php_timezone_obj *intern; zend_object_value retval; intern = emalloc(sizeof(php_timezone_obj)); memset(intern, 0, sizeof(php_timezone_obj)); if (ptr) { *ptr = intern; } zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) date_object_free_storage_timezone, NULL TSRMLS_CC); retval.handlers = &date_object_handlers_timezone; return retval; } static zend_object_value date_object_new_timezone(zend_class_entry *class_type TSRMLS_DC) { return date_object_new_timezone_ex(class_type, NULL TSRMLS_CC); } static zend_object_value date_object_clone_timezone(zval *this_ptr TSRMLS_DC) { php_timezone_obj *new_obj = NULL; php_timezone_obj *old_obj = (php_timezone_obj *) zend_object_store_get_object(this_ptr TSRMLS_CC); zend_object_value new_ov = date_object_new_timezone_ex(old_obj->std.ce, &new_obj TSRMLS_CC); zend_objects_clone_members(&new_obj->std, new_ov, &old_obj->std, Z_OBJ_HANDLE_P(this_ptr) TSRMLS_CC); new_obj->type = old_obj->type; new_obj->initialized = 1; switch (new_obj->type) { case TIMELIB_ZONETYPE_ID: new_obj->tzi.tz = old_obj->tzi.tz; break; case TIMELIB_ZONETYPE_OFFSET: new_obj->tzi.utc_offset = old_obj->tzi.utc_offset; break; case TIMELIB_ZONETYPE_ABBR: new_obj->tzi.z.utc_offset = old_obj->tzi.z.utc_offset; new_obj->tzi.z.dst = old_obj->tzi.z.dst; new_obj->tzi.z.abbr = old_obj->tzi.z.abbr; break; } return new_ov; } static inline zend_object_value date_object_new_interval_ex(zend_class_entry *class_type, php_interval_obj **ptr TSRMLS_DC) { php_interval_obj *intern; zend_object_value retval; intern = emalloc(sizeof(php_interval_obj)); memset(intern, 0, sizeof(php_interval_obj)); if (ptr) { *ptr = intern; } zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) date_object_free_storage_interval, NULL TSRMLS_CC); retval.handlers = &date_object_handlers_interval; return retval; } static zend_object_value date_object_new_interval(zend_class_entry *class_type TSRMLS_DC) { return date_object_new_interval_ex(class_type, NULL TSRMLS_CC); } static zend_object_value date_object_clone_interval(zval *this_ptr TSRMLS_DC) { php_interval_obj *new_obj = NULL; php_interval_obj *old_obj = (php_interval_obj *) zend_object_store_get_object(this_ptr TSRMLS_CC); zend_object_value new_ov = date_object_new_interval_ex(old_obj->std.ce, &new_obj TSRMLS_CC); zend_objects_clone_members(&new_obj->std, new_ov, &old_obj->std, Z_OBJ_HANDLE_P(this_ptr) TSRMLS_CC); /** FIX ME ADD CLONE STUFF **/ return new_ov; } static HashTable *date_object_get_properties_interval(zval *object TSRMLS_DC) { HashTable *props; zval *zv; php_interval_obj *intervalobj; intervalobj = (php_interval_obj *) zend_object_store_get_object(object TSRMLS_CC); props = zend_std_get_properties(object TSRMLS_CC); if (!intervalobj->initialized || GC_G(gc_active)) { return props; } #define PHP_DATE_INTERVAL_ADD_PROPERTY(n,f) \ MAKE_STD_ZVAL(zv); \ ZVAL_LONG(zv, intervalobj->diff->f); \ zend_hash_update(props, n, strlen(n) + 1, &zv, sizeof(zval), NULL); PHP_DATE_INTERVAL_ADD_PROPERTY("y", y); PHP_DATE_INTERVAL_ADD_PROPERTY("m", m); PHP_DATE_INTERVAL_ADD_PROPERTY("d", d); PHP_DATE_INTERVAL_ADD_PROPERTY("h", h); PHP_DATE_INTERVAL_ADD_PROPERTY("i", i); PHP_DATE_INTERVAL_ADD_PROPERTY("s", s); PHP_DATE_INTERVAL_ADD_PROPERTY("invert", invert); if (intervalobj->diff->days != -99999) { PHP_DATE_INTERVAL_ADD_PROPERTY("days", days); } else { MAKE_STD_ZVAL(zv); ZVAL_FALSE(zv); zend_hash_update(props, "days", 5, &zv, sizeof(zval), NULL); } return props; } static inline zend_object_value date_object_new_period_ex(zend_class_entry *class_type, php_period_obj **ptr TSRMLS_DC) { php_period_obj *intern; zend_object_value retval; intern = emalloc(sizeof(php_period_obj)); memset(intern, 0, sizeof(php_period_obj)); if (ptr) { *ptr = intern; } zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) date_object_free_storage_period, NULL TSRMLS_CC); retval.handlers = &date_object_handlers_period; return retval; } static zend_object_value date_object_new_period(zend_class_entry *class_type TSRMLS_DC) { return date_object_new_period_ex(class_type, NULL TSRMLS_CC); } static zend_object_value date_object_clone_period(zval *this_ptr TSRMLS_DC) { php_period_obj *new_obj = NULL; php_period_obj *old_obj = (php_period_obj *) zend_object_store_get_object(this_ptr TSRMLS_CC); zend_object_value new_ov = date_object_new_period_ex(old_obj->std.ce, &new_obj TSRMLS_CC); zend_objects_clone_members(&new_obj->std, new_ov, &old_obj->std, Z_OBJ_HANDLE_P(this_ptr) TSRMLS_CC); /** FIX ME ADD CLONE STUFF **/ return new_ov; } static void date_object_free_storage_date(void *object TSRMLS_DC) { php_date_obj *intern = (php_date_obj *)object; if (intern->time) { timelib_time_dtor(intern->time); } zend_object_std_dtor(&intern->std TSRMLS_CC); efree(object); } static void date_object_free_storage_timezone(void *object TSRMLS_DC) { php_timezone_obj *intern = (php_timezone_obj *)object; if (intern->type == TIMELIB_ZONETYPE_ABBR) { free(intern->tzi.z.abbr); } zend_object_std_dtor(&intern->std TSRMLS_CC); efree(object); } static void date_object_free_storage_interval(void *object TSRMLS_DC) { php_interval_obj *intern = (php_interval_obj *)object; timelib_rel_time_dtor(intern->diff); zend_object_std_dtor(&intern->std TSRMLS_CC); efree(object); } static void date_object_free_storage_period(void *object TSRMLS_DC) { php_period_obj *intern = (php_period_obj *)object; if (intern->start) { timelib_time_dtor(intern->start); } if (intern->current) { timelib_time_dtor(intern->current); } if (intern->end) { timelib_time_dtor(intern->end); } timelib_rel_time_dtor(intern->interval); zend_object_std_dtor(&intern->std TSRMLS_CC); efree(object); } /* Advanced Interface */ PHPAPI zval *php_date_instantiate(zend_class_entry *pce, zval *object TSRMLS_DC) { Z_TYPE_P(object) = IS_OBJECT; object_init_ex(object, pce); Z_SET_REFCOUNT_P(object, 1); Z_UNSET_ISREF_P(object); return object; } /* Helper function used to store the latest found warnings and errors while * parsing, from either strtotime or parse_from_format. */ static void update_errors_warnings(timelib_error_container *last_errors TSRMLS_DC) { if (DATEG(last_errors)) { timelib_error_container_dtor(DATEG(last_errors)); DATEG(last_errors) = NULL; } DATEG(last_errors) = last_errors; } PHPAPI int php_date_initialize(php_date_obj *dateobj, /*const*/ char *time_str, int time_str_len, char *format, zval *timezone_object, int ctor TSRMLS_DC) { timelib_time *now; timelib_tzinfo *tzi; timelib_error_container *err = NULL; int type = TIMELIB_ZONETYPE_ID, new_dst; char *new_abbr; timelib_sll new_offset; if (dateobj->time) { timelib_time_dtor(dateobj->time); } if (format) { dateobj->time = timelib_parse_from_format(format, time_str_len ? time_str : "", time_str_len ? time_str_len : 0, &err, DATE_TIMEZONEDB); } else { dateobj->time = timelib_strtotime(time_str_len ? time_str : "now", time_str_len ? time_str_len : sizeof("now") -1, &err, DATE_TIMEZONEDB); } /* update last errors and warnings */ update_errors_warnings(err TSRMLS_CC); if (ctor && err && err->error_count) { /* spit out the first library error message, at least */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse time string (%s) at position %d (%c): %s", time_str, err->error_messages[0].position, err->error_messages[0].character, err->error_messages[0].message); } if (err && err->error_count) { return 0; } if (timezone_object) { php_timezone_obj *tzobj; tzobj = (php_timezone_obj *) zend_object_store_get_object(timezone_object TSRMLS_CC); switch (tzobj->type) { case TIMELIB_ZONETYPE_ID: tzi = tzobj->tzi.tz; break; case TIMELIB_ZONETYPE_OFFSET: new_offset = tzobj->tzi.utc_offset; break; case TIMELIB_ZONETYPE_ABBR: new_offset = tzobj->tzi.z.utc_offset; new_dst = tzobj->tzi.z.dst; new_abbr = strdup(tzobj->tzi.z.abbr); break; } type = tzobj->type; } else if (dateobj->time->tz_info) { tzi = dateobj->time->tz_info; } else { tzi = get_timezone_info(TSRMLS_C); } now = timelib_time_ctor(); now->zone_type = type; switch (type) { case TIMELIB_ZONETYPE_ID: now->tz_info = tzi; break; case TIMELIB_ZONETYPE_OFFSET: now->z = new_offset; break; case TIMELIB_ZONETYPE_ABBR: now->z = new_offset; now->dst = new_dst; now->tz_abbr = new_abbr; break; } timelib_unixtime2local(now, (timelib_sll) time(NULL)); timelib_fill_holes(dateobj->time, now, TIMELIB_NO_CLONE); timelib_update_ts(dateobj->time, tzi); dateobj->time->have_relative = 0; timelib_time_dtor(now); return 1; } /* {{{ proto DateTime date_create([string time[, DateTimeZone object]]) Returns new DateTime object */ PHP_FUNCTION(date_create) { zval *timezone_object = NULL; char *time_str = NULL; int time_str_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sO!", &time_str, &time_str_len, &timezone_object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } php_date_instantiate(date_ce_date, return_value TSRMLS_CC); if (!php_date_initialize(zend_object_store_get_object(return_value TSRMLS_CC), time_str, time_str_len, NULL, timezone_object, 0 TSRMLS_CC)) { RETURN_FALSE; } } /* }}} */ /* {{{ proto DateTime date_create_from_format(string format, string time[, DateTimeZone object]) Returns new DateTime object formatted according to the specified format */ PHP_FUNCTION(date_create_from_format) { zval *timezone_object = NULL; char *time_str = NULL, *format_str = NULL; int time_str_len = 0, format_str_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|O", &format_str, &format_str_len, &time_str, &time_str_len, &timezone_object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } php_date_instantiate(date_ce_date, return_value TSRMLS_CC); if (!php_date_initialize(zend_object_store_get_object(return_value TSRMLS_CC), time_str, time_str_len, format_str, timezone_object, 0 TSRMLS_CC)) { RETURN_FALSE; } } /* }}} */ /* {{{ proto DateTime::__construct([string time[, DateTimeZone object]]) Creates new DateTime object */ PHP_METHOD(DateTime, __construct) { zval *timezone_object = NULL; char *time_str = NULL; int time_str_len = 0; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sO!", &time_str, &time_str_len, &timezone_object, date_ce_timezone)) { php_date_initialize(zend_object_store_get_object(getThis() TSRMLS_CC), time_str, time_str_len, NULL, timezone_object, 1 TSRMLS_CC); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ static int php_date_initialize_from_hash(zval **return_value, php_date_obj **dateobj, HashTable *myht TSRMLS_DC) { zval **z_date = NULL; zval **z_timezone = NULL; zval **z_timezone_type = NULL; zval *tmp_obj = NULL; timelib_tzinfo *tzi; php_timezone_obj *tzobj; if (zend_hash_find(myht, "date", 5, (void**) &z_date) == SUCCESS) { convert_to_string(*z_date); if (zend_hash_find(myht, "timezone_type", 14, (void**) &z_timezone_type) == SUCCESS) { convert_to_long(*z_timezone_type); if (zend_hash_find(myht, "timezone", 9, (void**) &z_timezone) == SUCCESS) { convert_to_string(*z_timezone); switch (Z_LVAL_PP(z_timezone_type)) { case TIMELIB_ZONETYPE_OFFSET: case TIMELIB_ZONETYPE_ABBR: { char *tmp = emalloc(Z_STRLEN_PP(z_date) + Z_STRLEN_PP(z_timezone) + 2); snprintf(tmp, Z_STRLEN_PP(z_date) + Z_STRLEN_PP(z_timezone) + 2, "%s %s", Z_STRVAL_PP(z_date), Z_STRVAL_PP(z_timezone)); php_date_initialize(*dateobj, tmp, Z_STRLEN_PP(z_date) + Z_STRLEN_PP(z_timezone) + 1, NULL, NULL, 0 TSRMLS_CC); efree(tmp); return 1; } case TIMELIB_ZONETYPE_ID: convert_to_string(*z_timezone); tzi = php_date_parse_tzfile(Z_STRVAL_PP(z_timezone), DATE_TIMEZONEDB TSRMLS_CC); ALLOC_INIT_ZVAL(tmp_obj); tzobj = zend_object_store_get_object(php_date_instantiate(date_ce_timezone, tmp_obj TSRMLS_CC) TSRMLS_CC); tzobj->type = TIMELIB_ZONETYPE_ID; tzobj->tzi.tz = tzi; tzobj->initialized = 1; php_date_initialize(*dateobj, Z_STRVAL_PP(z_date), Z_STRLEN_PP(z_date), NULL, tmp_obj, 0 TSRMLS_CC); zval_ptr_dtor(&tmp_obj); return 1; } } } } return 0; } /* {{{ proto DateTime::__set_state() */ PHP_METHOD(DateTime, __set_state) { php_date_obj *dateobj; zval *array; HashTable *myht; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) { RETURN_FALSE; } myht = HASH_OF(array); php_date_instantiate(date_ce_date, return_value TSRMLS_CC); dateobj = (php_date_obj *) zend_object_store_get_object(return_value TSRMLS_CC); php_date_initialize_from_hash(&return_value, &dateobj, myht TSRMLS_CC); } /* }}} */ /* {{{ proto DateTime::__wakeup() */ PHP_METHOD(DateTime, __wakeup) { zval *object = getThis(); php_date_obj *dateobj; HashTable *myht; dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); myht = Z_OBJPROP_P(object); php_date_initialize_from_hash(&return_value, &dateobj, myht TSRMLS_CC); } /* }}} */ /* Helper function used to add an associative array of warnings and errors to a zval */ static void zval_from_error_container(zval *z, timelib_error_container *error) { int i; zval *element; add_assoc_long(z, "warning_count", error->warning_count); MAKE_STD_ZVAL(element); array_init(element); for (i = 0; i < error->warning_count; i++) { add_index_string(element, error->warning_messages[i].position, error->warning_messages[i].message, 1); } add_assoc_zval(z, "warnings", element); add_assoc_long(z, "error_count", error->error_count); MAKE_STD_ZVAL(element); array_init(element); for (i = 0; i < error->error_count; i++) { add_index_string(element, error->error_messages[i].position, error->error_messages[i].message, 1); } add_assoc_zval(z, "errors", element); } /* {{{ proto array date_get_last_errors() Returns the warnings and errors found while parsing a date/time string. */ PHP_FUNCTION(date_get_last_errors) { if (DATEG(last_errors)) { array_init(return_value); zval_from_error_container(return_value, DATEG(last_errors)); } else { RETURN_FALSE; } } /* }}} */ void php_date_do_return_parsed_time(INTERNAL_FUNCTION_PARAMETERS, timelib_time *parsed_time, struct timelib_error_container *error) { zval *element; array_init(return_value); #define PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(name, elem) \ if (parsed_time->elem == -99999) { \ add_assoc_bool(return_value, #name, 0); \ } else { \ add_assoc_long(return_value, #name, parsed_time->elem); \ } PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(year, y); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(month, m); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(day, d); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(hour, h); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(minute, i); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(second, s); if (parsed_time->f == -99999) { add_assoc_bool(return_value, "fraction", 0); } else { add_assoc_double(return_value, "fraction", parsed_time->f); } zval_from_error_container(return_value, error); timelib_error_container_dtor(error); add_assoc_bool(return_value, "is_localtime", parsed_time->is_localtime); if (parsed_time->is_localtime) { PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(zone_type, zone_type); switch (parsed_time->zone_type) { case TIMELIB_ZONETYPE_OFFSET: PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(zone, z); add_assoc_bool(return_value, "is_dst", parsed_time->dst); break; case TIMELIB_ZONETYPE_ID: if (parsed_time->tz_abbr) { add_assoc_string(return_value, "tz_abbr", parsed_time->tz_abbr, 1); } if (parsed_time->tz_info) { add_assoc_string(return_value, "tz_id", parsed_time->tz_info->name, 1); } break; case TIMELIB_ZONETYPE_ABBR: PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(zone, z); add_assoc_bool(return_value, "is_dst", parsed_time->dst); add_assoc_string(return_value, "tz_abbr", parsed_time->tz_abbr, 1); break; } } if (parsed_time->have_relative) { MAKE_STD_ZVAL(element); array_init(element); add_assoc_long(element, "year", parsed_time->relative.y); add_assoc_long(element, "month", parsed_time->relative.m); add_assoc_long(element, "day", parsed_time->relative.d); add_assoc_long(element, "hour", parsed_time->relative.h); add_assoc_long(element, "minute", parsed_time->relative.i); add_assoc_long(element, "second", parsed_time->relative.s); if (parsed_time->relative.have_weekday_relative) { add_assoc_long(element, "weekday", parsed_time->relative.weekday); } if (parsed_time->relative.have_special_relative && (parsed_time->relative.special.type == TIMELIB_SPECIAL_WEEKDAY)) { add_assoc_long(element, "weekdays", parsed_time->relative.special.amount); } if (parsed_time->relative.first_last_day_of) { add_assoc_bool(element, parsed_time->relative.first_last_day_of == 1 ? "first_day_of_month" : "last_day_of_month", 1); } add_assoc_zval(return_value, "relative", element); } timelib_time_dtor(parsed_time); } /* {{{ proto array date_parse(string date) Returns associative array with detailed info about given date */ PHP_FUNCTION(date_parse) { char *date; int date_len; struct timelib_error_container *error; timelib_time *parsed_time; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &date, &date_len) == FAILURE) { RETURN_FALSE; } parsed_time = timelib_strtotime(date, date_len, &error, DATE_TIMEZONEDB); php_date_do_return_parsed_time(INTERNAL_FUNCTION_PARAM_PASSTHRU, parsed_time, error); } /* }}} */ /* {{{ proto array date_parse_from_format(string format, string date) Returns associative array with detailed info about given date */ PHP_FUNCTION(date_parse_from_format) { char *date, *format; int date_len, format_len; struct timelib_error_container *error; timelib_time *parsed_time; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &format, &format_len, &date, &date_len) == FAILURE) { RETURN_FALSE; } parsed_time = timelib_parse_from_format(format, date, date_len, &error, DATE_TIMEZONEDB); php_date_do_return_parsed_time(INTERNAL_FUNCTION_PARAM_PASSTHRU, parsed_time, error); } /* }}} */ /* {{{ proto string date_format(DateTime object, string format) Returns date formatted according to given format */ PHP_FUNCTION(date_format) { zval *object; php_date_obj *dateobj; char *format; int format_len; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, date_ce_date, &format, &format_len) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); RETURN_STRING(date_format(format, format_len, dateobj->time, dateobj->time->is_localtime), 0); } /* }}} */ /* {{{ proto DateTime date_modify(DateTime object, string modify) Alters the timestamp. */ PHP_FUNCTION(date_modify) { zval *object; php_date_obj *dateobj; char *modify; int modify_len; timelib_time *tmp_time; timelib_error_container *err = NULL; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, date_ce_date, &modify, &modify_len) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); tmp_time = timelib_strtotime(modify, modify_len, &err, DATE_TIMEZONEDB); /* update last errors and warnings */ update_errors_warnings(err TSRMLS_CC); if (err && err->error_count) { /* spit out the first library error message, at least */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse time string (%s) at position %d (%c): %s", modify, err->error_messages[0].position, err->error_messages[0].character, err->error_messages[0].message); timelib_time_dtor(tmp_time); RETURN_FALSE; } memcpy(&dateobj->time->relative, &tmp_time->relative, sizeof(struct timelib_rel_time)); dateobj->time->have_relative = tmp_time->have_relative; dateobj->time->sse_uptodate = 0; if (tmp_time->y != -99999) { dateobj->time->y = tmp_time->y; } if (tmp_time->m != -99999) { dateobj->time->m = tmp_time->m; } if (tmp_time->d != -99999) { dateobj->time->d = tmp_time->d; } if (tmp_time->h != -99999) { dateobj->time->h = tmp_time->h; if (tmp_time->i != -99999) { dateobj->time->i = tmp_time->i; if (tmp_time->s != -99999) { dateobj->time->s = tmp_time->s; } else { dateobj->time->s = 0; } } else { dateobj->time->i = 0; dateobj->time->s = 0; } } timelib_time_dtor(tmp_time); timelib_update_ts(dateobj->time, NULL); timelib_update_from_sse(dateobj->time); dateobj->time->have_relative = 0; RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_add(DateTime object, DateInterval interval) Adds an interval to the current date in object. */ PHP_FUNCTION(date_add) { zval *object, *interval; php_date_obj *dateobj; php_interval_obj *intobj; int bias = 1; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &object, date_ce_date, &interval, date_ce_interval) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); intobj = (php_interval_obj *) zend_object_store_get_object(interval TSRMLS_CC); DATE_CHECK_INITIALIZED(intobj->initialized, DateInterval); if (intobj->diff->have_weekday_relative || intobj->diff->have_special_relative) { memcpy(&dateobj->time->relative, intobj->diff, sizeof(struct timelib_rel_time)); } else { if (intobj->diff->invert) { bias = -1; } dateobj->time->relative.y = intobj->diff->y * bias; dateobj->time->relative.m = intobj->diff->m * bias; dateobj->time->relative.d = intobj->diff->d * bias; dateobj->time->relative.h = intobj->diff->h * bias; dateobj->time->relative.i = intobj->diff->i * bias; dateobj->time->relative.s = intobj->diff->s * bias; dateobj->time->relative.weekday = 0; dateobj->time->relative.have_weekday_relative = 0; } dateobj->time->have_relative = 1; dateobj->time->sse_uptodate = 0; timelib_update_ts(dateobj->time, NULL); timelib_update_from_sse(dateobj->time); dateobj->time->have_relative = 0; RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_sub(DateTime object, DateInterval interval) Subtracts an interval to the current date in object. */ PHP_FUNCTION(date_sub) { zval *object, *interval; php_date_obj *dateobj; php_interval_obj *intobj; int bias = 1; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &object, date_ce_date, &interval, date_ce_interval) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); intobj = (php_interval_obj *) zend_object_store_get_object(interval TSRMLS_CC); DATE_CHECK_INITIALIZED(intobj->initialized, DateInterval); if (intobj->diff->have_special_relative) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Only non-special relative time specifications are supported for subtraction"); return; } if (intobj->diff->invert) { bias = -1; } dateobj->time->relative.y = 0 - (intobj->diff->y * bias); dateobj->time->relative.m = 0 - (intobj->diff->m * bias); dateobj->time->relative.d = 0 - (intobj->diff->d * bias); dateobj->time->relative.h = 0 - (intobj->diff->h * bias); dateobj->time->relative.i = 0 - (intobj->diff->i * bias); dateobj->time->relative.s = 0 - (intobj->diff->s * bias); dateobj->time->have_relative = 1; dateobj->time->relative.weekday = 0; dateobj->time->relative.have_weekday_relative = 0; dateobj->time->sse_uptodate = 0; timelib_update_ts(dateobj->time, NULL); timelib_update_from_sse(dateobj->time); dateobj->time->have_relative = 0; RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTimeZone date_timezone_get(DateTime object) Return new DateTimeZone object relative to give DateTime */ PHP_FUNCTION(date_timezone_get) { zval *object; php_date_obj *dateobj; php_timezone_obj *tzobj; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_date) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); if (dateobj->time->is_localtime/* && dateobj->time->tz_info*/) { php_date_instantiate(date_ce_timezone, return_value TSRMLS_CC); tzobj = (php_timezone_obj *) zend_object_store_get_object(return_value TSRMLS_CC); tzobj->initialized = 1; tzobj->type = dateobj->time->zone_type; switch (dateobj->time->zone_type) { case TIMELIB_ZONETYPE_ID: tzobj->tzi.tz = dateobj->time->tz_info; break; case TIMELIB_ZONETYPE_OFFSET: tzobj->tzi.utc_offset = dateobj->time->z; break; case TIMELIB_ZONETYPE_ABBR: tzobj->tzi.z.utc_offset = dateobj->time->z; tzobj->tzi.z.dst = dateobj->time->dst; tzobj->tzi.z.abbr = strdup(dateobj->time->tz_abbr); break; } } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto DateTime date_timezone_set(DateTime object, DateTimeZone object) Sets the timezone for the DateTime object. */ PHP_FUNCTION(date_timezone_set) { zval *object; zval *timezone_object; php_date_obj *dateobj; php_timezone_obj *tzobj; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &object, date_ce_date, &timezone_object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); tzobj = (php_timezone_obj *) zend_object_store_get_object(timezone_object TSRMLS_CC); if (tzobj->type != TIMELIB_ZONETYPE_ID) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can only do this for zones with ID for now"); return; } timelib_set_timezone(dateobj->time, tzobj->tzi.tz); timelib_unixtime2local(dateobj->time, dateobj->time->sse); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto long date_offset_get(DateTime object) Returns the DST offset. */ PHP_FUNCTION(date_offset_get) { zval *object; php_date_obj *dateobj; timelib_time_offset *offset; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_date) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); if (dateobj->time->is_localtime/* && dateobj->time->tz_info*/) { switch (dateobj->time->zone_type) { case TIMELIB_ZONETYPE_ID: offset = timelib_get_time_zone_info(dateobj->time->sse, dateobj->time->tz_info); RETVAL_LONG(offset->offset); timelib_time_offset_dtor(offset); break; case TIMELIB_ZONETYPE_OFFSET: RETVAL_LONG(dateobj->time->z * -60); break; case TIMELIB_ZONETYPE_ABBR: RETVAL_LONG((dateobj->time->z - (60 * dateobj->time->dst)) * -60); break; } return; } else { RETURN_LONG(0); } } /* }}} */ /* {{{ proto DateTime date_time_set(DateTime object, long hour, long minute[, long second]) Sets the time. */ PHP_FUNCTION(date_time_set) { zval *object; php_date_obj *dateobj; long h, i, s = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oll|l", &object, date_ce_date, &h, &i, &s) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); dateobj->time->h = h; dateobj->time->i = i; dateobj->time->s = s; timelib_update_ts(dateobj->time, NULL); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_date_set(DateTime object, long year, long month, long day) Sets the date. */ PHP_FUNCTION(date_date_set) { zval *object; php_date_obj *dateobj; long y, m, d; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Olll", &object, date_ce_date, &y, &m, &d) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); dateobj->time->y = y; dateobj->time->m = m; dateobj->time->d = d; timelib_update_ts(dateobj->time, NULL); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_isodate_set(DateTime object, long year, long week[, long day]) Sets the ISO date. */ PHP_FUNCTION(date_isodate_set) { zval *object; php_date_obj *dateobj; long y, w, d = 1; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oll|l", &object, date_ce_date, &y, &w, &d) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); dateobj->time->y = y; dateobj->time->m = 1; dateobj->time->d = 1; dateobj->time->relative.d = timelib_daynr_from_weeknr(y, w, d); dateobj->time->have_relative = 1; timelib_update_ts(dateobj->time, NULL); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_timestamp_set(DateTime object, long unixTimestamp) Sets the date and time based on an Unix timestamp. */ PHP_FUNCTION(date_timestamp_set) { zval *object; php_date_obj *dateobj; long timestamp; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Ol", &object, date_ce_date, &timestamp) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); timelib_unixtime2local(dateobj->time, (timelib_sll)timestamp); timelib_update_ts(dateobj->time, NULL); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto long date_timestamp_get(DateTime object) Gets the Unix timestamp. */ PHP_FUNCTION(date_timestamp_get) { zval *object; php_date_obj *dateobj; long timestamp; int error; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_date) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); timelib_update_ts(dateobj->time, NULL); timestamp = timelib_date_to_int(dateobj->time, &error); if (error) { RETURN_FALSE; } else { RETVAL_LONG(timestamp); } } /* }}} */ /* {{{ proto DateInterval date_diff(DateTime object [, bool absolute]) Returns the difference between two DateTime objects. */ PHP_FUNCTION(date_diff) { zval *object1, *object2; php_date_obj *dateobj1, *dateobj2; php_interval_obj *interval; long absolute = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO|l", &object1, date_ce_date, &object2, date_ce_date, &absolute) == FAILURE) { RETURN_FALSE; } dateobj1 = (php_date_obj *) zend_object_store_get_object(object1 TSRMLS_CC); dateobj2 = (php_date_obj *) zend_object_store_get_object(object2 TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj1->time, DateTime); DATE_CHECK_INITIALIZED(dateobj2->time, DateTime); timelib_update_ts(dateobj1->time, NULL); timelib_update_ts(dateobj2->time, NULL); php_date_instantiate(date_ce_interval, return_value TSRMLS_CC); interval = zend_object_store_get_object(return_value TSRMLS_CC); interval->diff = timelib_diff(dateobj1->time, dateobj2->time); if (absolute) { interval->diff->invert = 0; } interval->initialized = 1; } /* }}} */ static int timezone_initialize(timelib_tzinfo **tzi, /*const*/ char *tz TSRMLS_DC) { char *tzid; *tzi = NULL; if ((tzid = timelib_timezone_id_from_abbr(tz, -1, 0))) { *tzi = php_date_parse_tzfile(tzid, DATE_TIMEZONEDB TSRMLS_CC); } else { *tzi = php_date_parse_tzfile(tz, DATE_TIMEZONEDB TSRMLS_CC); } if (*tzi) { return SUCCESS; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown or bad timezone (%s)", tz); return FAILURE; } } /* {{{ proto DateTimeZone timezone_open(string timezone) Returns new DateTimeZone object */ PHP_FUNCTION(timezone_open) { char *tz; int tz_len; timelib_tzinfo *tzi = NULL; php_timezone_obj *tzobj; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &tz, &tz_len) == FAILURE) { RETURN_FALSE; } if (SUCCESS != timezone_initialize(&tzi, tz TSRMLS_CC)) { RETURN_FALSE; } tzobj = zend_object_store_get_object(php_date_instantiate(date_ce_timezone, return_value TSRMLS_CC) TSRMLS_CC); tzobj->type = TIMELIB_ZONETYPE_ID; tzobj->tzi.tz = tzi; tzobj->initialized = 1; } /* }}} */ /* {{{ proto DateTimeZone::__construct(string timezone) Creates new DateTimeZone object. */ PHP_METHOD(DateTimeZone, __construct) { char *tz; int tz_len; timelib_tzinfo *tzi = NULL; php_timezone_obj *tzobj; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &tz, &tz_len)) { if (SUCCESS == timezone_initialize(&tzi, tz TSRMLS_CC)) { tzobj = zend_object_store_get_object(getThis() TSRMLS_CC); tzobj->type = TIMELIB_ZONETYPE_ID; tzobj->tzi.tz = tzi; tzobj->initialized = 1; } else { ZVAL_NULL(getThis()); } } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto string timezone_name_get(DateTimeZone object) Returns the name of the timezone. */ PHP_FUNCTION(timezone_name_get) { zval *object; php_timezone_obj *tzobj; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } tzobj = (php_timezone_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(tzobj->initialized, DateTimeZone); switch (tzobj->type) { case TIMELIB_ZONETYPE_ID: RETURN_STRING(tzobj->tzi.tz->name, 1); break; case TIMELIB_ZONETYPE_OFFSET: { char *tmpstr = emalloc(sizeof("UTC+05:00")); timelib_sll utc_offset = tzobj->tzi.utc_offset; snprintf(tmpstr, sizeof("+05:00"), "%c%02d:%02d", utc_offset > 0 ? '-' : '+', abs(utc_offset / 60), abs((utc_offset % 60))); RETURN_STRING(tmpstr, 0); } break; case TIMELIB_ZONETYPE_ABBR: RETURN_STRING(tzobj->tzi.z.abbr, 1); break; } } /* }}} */ /* {{{ proto string timezone_name_from_abbr(string abbr[, long gmtOffset[, long isdst]]) Returns the timezone name from abbrevation */ PHP_FUNCTION(timezone_name_from_abbr) { char *abbr; char *tzid; int abbr_len; long gmtoffset = -1; long isdst = -1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ll", &abbr, &abbr_len, &gmtoffset, &isdst) == FAILURE) { RETURN_FALSE; } tzid = timelib_timezone_id_from_abbr(abbr, gmtoffset, isdst); if (tzid) { RETURN_STRING(tzid, 1); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto long timezone_offset_get(DateTimeZone object, DateTime object) Returns the timezone offset. */ PHP_FUNCTION(timezone_offset_get) { zval *object, *dateobject; php_timezone_obj *tzobj; php_date_obj *dateobj; timelib_time_offset *offset; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &object, date_ce_timezone, &dateobject, date_ce_date) == FAILURE) { RETURN_FALSE; } tzobj = (php_timezone_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(tzobj->initialized, DateTimeZone); dateobj = (php_date_obj *) zend_object_store_get_object(dateobject TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); switch (tzobj->type) { case TIMELIB_ZONETYPE_ID: offset = timelib_get_time_zone_info(dateobj->time->sse, tzobj->tzi.tz); RETVAL_LONG(offset->offset); timelib_time_offset_dtor(offset); break; case TIMELIB_ZONETYPE_OFFSET: RETURN_LONG(tzobj->tzi.utc_offset * -60); break; case TIMELIB_ZONETYPE_ABBR: RETURN_LONG((tzobj->tzi.z.utc_offset - (tzobj->tzi.z.dst*60)) * -60); break; } } /* }}} */ /* {{{ proto array timezone_transitions_get(DateTimeZone object [, long timestamp_begin [, long timestamp_end ]]) Returns numerically indexed array containing associative array for all transitions in the specified range for the timezone. */ PHP_FUNCTION(timezone_transitions_get) { zval *object, *element; php_timezone_obj *tzobj; unsigned int i, begin = 0, found; long timestamp_begin = LONG_MIN, timestamp_end = LONG_MAX; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|ll", &object, date_ce_timezone, &timestamp_begin, &timestamp_end) == FAILURE) { RETURN_FALSE; } tzobj = (php_timezone_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(tzobj->initialized, DateTimeZone); if (tzobj->type != TIMELIB_ZONETYPE_ID) { RETURN_FALSE; } #define add_nominal() \ MAKE_STD_ZVAL(element); \ array_init(element); \ add_assoc_long(element, "ts", timestamp_begin); \ add_assoc_string(element, "time", php_format_date(DATE_FORMAT_ISO8601, 13, timestamp_begin, 0 TSRMLS_CC), 0); \ add_assoc_long(element, "offset", tzobj->tzi.tz->type[0].offset); \ add_assoc_bool(element, "isdst", tzobj->tzi.tz->type[0].isdst); \ add_assoc_string(element, "abbr", &tzobj->tzi.tz->timezone_abbr[tzobj->tzi.tz->type[0].abbr_idx], 1); \ add_next_index_zval(return_value, element); #define add(i,ts) \ MAKE_STD_ZVAL(element); \ array_init(element); \ add_assoc_long(element, "ts", ts); \ add_assoc_string(element, "time", php_format_date(DATE_FORMAT_ISO8601, 13, ts, 0 TSRMLS_CC), 0); \ add_assoc_long(element, "offset", tzobj->tzi.tz->type[tzobj->tzi.tz->trans_idx[i]].offset); \ add_assoc_bool(element, "isdst", tzobj->tzi.tz->type[tzobj->tzi.tz->trans_idx[i]].isdst); \ add_assoc_string(element, "abbr", &tzobj->tzi.tz->timezone_abbr[tzobj->tzi.tz->type[tzobj->tzi.tz->trans_idx[i]].abbr_idx], 1); \ add_next_index_zval(return_value, element); #define add_last() add(tzobj->tzi.tz->timecnt - 1, timestamp_begin) array_init(return_value); if (timestamp_begin == LONG_MIN) { add_nominal(); begin = 0; found = 1; } else { begin = 0; found = 0; if (tzobj->tzi.tz->timecnt > 0) { do { if (tzobj->tzi.tz->trans[begin] > timestamp_begin) { if (begin > 0) { add(begin - 1, timestamp_begin); } else { add_nominal(); } found = 1; break; } begin++; } while (begin < tzobj->tzi.tz->timecnt); } } if (!found) { if (tzobj->tzi.tz->timecnt > 0) { add_last(); } else { add_nominal(); } } else { for (i = begin; i < tzobj->tzi.tz->timecnt; ++i) { if (tzobj->tzi.tz->trans[i] < timestamp_end) { add(i, tzobj->tzi.tz->trans[i]); } } } } /* }}} */ /* {{{ proto array timezone_location_get() Returns location information for a timezone, including country code, latitude/longitude and comments */ PHP_FUNCTION(timezone_location_get) { zval *object; php_timezone_obj *tzobj; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } tzobj = (php_timezone_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(tzobj->initialized, DateTimeZone); if (tzobj->type != TIMELIB_ZONETYPE_ID) { RETURN_FALSE; } array_init(return_value); add_assoc_string(return_value, "country_code", tzobj->tzi.tz->location.country_code, 1); add_assoc_double(return_value, "latitude", tzobj->tzi.tz->location.latitude); add_assoc_double(return_value, "longitude", tzobj->tzi.tz->location.longitude); add_assoc_string(return_value, "comments", tzobj->tzi.tz->location.comments, 1); } /* }}} */ static int date_interval_initialize(timelib_rel_time **rt, /*const*/ char *format, int format_length TSRMLS_DC) { timelib_time *b = NULL, *e = NULL; timelib_rel_time *p = NULL; int r = 0; int retval = 0; struct timelib_error_container *errors; timelib_strtointerval(format, format_length, &b, &e, &p, &r, &errors); if (errors->error_count > 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown or bad format (%s)", format); retval = FAILURE; } else { *rt = p; retval = SUCCESS; } timelib_error_container_dtor(errors); return retval; } /* {{{ date_interval_read_property */ zval *date_interval_read_property(zval *object, zval *member, int type, const zend_literal *key TSRMLS_DC) { php_interval_obj *obj; zval *retval; zval tmp_member; timelib_sll value = -1; if (member->type != IS_STRING) { tmp_member = *member; zval_copy_ctor(&tmp_member); convert_to_string(&tmp_member); member = &tmp_member; } obj = (php_interval_obj *)zend_objects_get_address(object TSRMLS_CC); #define GET_VALUE_FROM_STRUCT(n,m) \ if (strcmp(Z_STRVAL_P(member), m) == 0) { \ value = obj->diff->n; \ break; \ } do { GET_VALUE_FROM_STRUCT(y, "y"); GET_VALUE_FROM_STRUCT(m, "m"); GET_VALUE_FROM_STRUCT(d, "d"); GET_VALUE_FROM_STRUCT(h, "h"); GET_VALUE_FROM_STRUCT(i, "i"); GET_VALUE_FROM_STRUCT(s, "s"); GET_VALUE_FROM_STRUCT(invert, "invert"); GET_VALUE_FROM_STRUCT(days, "days"); /* didn't find any */ retval = (zend_get_std_object_handlers())->read_property(object, member, type, key TSRMLS_CC); if (member == &tmp_member) { zval_dtor(member); } return retval; } while(0); ALLOC_INIT_ZVAL(retval); Z_SET_REFCOUNT_P(retval, 0); ZVAL_LONG(retval, value); if (member == &tmp_member) { zval_dtor(member); } return retval; } /* }}} */ /* {{{ date_interval_write_property */ void date_interval_write_property(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC) { php_interval_obj *obj; zval tmp_member, tmp_value; if (member->type != IS_STRING) { tmp_member = *member; zval_copy_ctor(&tmp_member); convert_to_string(&tmp_member); member = &tmp_member; } obj = (php_interval_obj *)zend_objects_get_address(object TSRMLS_CC); #define SET_VALUE_FROM_STRUCT(n,m) \ if (strcmp(Z_STRVAL_P(member), m) == 0) { \ if (value->type != IS_LONG) { \ tmp_value = *value; \ zval_copy_ctor(&tmp_value); \ convert_to_long(&tmp_value); \ value = &tmp_value; \ } \ obj->diff->n = Z_LVAL_P(value); \ if (value == &tmp_value) { \ zval_dtor(value); \ } \ break; \ } do { SET_VALUE_FROM_STRUCT(y, "y"); SET_VALUE_FROM_STRUCT(m, "m"); SET_VALUE_FROM_STRUCT(d, "d"); SET_VALUE_FROM_STRUCT(h, "h"); SET_VALUE_FROM_STRUCT(i, "i"); SET_VALUE_FROM_STRUCT(s, "s"); SET_VALUE_FROM_STRUCT(invert, "invert"); /* didn't find any */ (zend_get_std_object_handlers())->write_property(object, member, value, key TSRMLS_CC); } while(0); if (member == &tmp_member) { zval_dtor(member); } } /* }}} */ /* {{{ proto DateInterval::__construct([string interval_spec]) Creates new DateInterval object. */ PHP_METHOD(DateInterval, __construct) { char *interval_string = NULL; int interval_string_length; php_interval_obj *diobj; timelib_rel_time *reltime; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &interval_string, &interval_string_length) == SUCCESS) { if (date_interval_initialize(&reltime, interval_string, interval_string_length TSRMLS_CC) == SUCCESS) { diobj = zend_object_store_get_object(getThis() TSRMLS_CC); diobj->diff = reltime; diobj->initialized = 1; } else { ZVAL_NULL(getThis()); } } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto DateInterval date_interval_create_from_date_string(string time) Uses the normal date parsers and sets up a DateInterval from the relative parts of the parsed string */ PHP_FUNCTION(date_interval_create_from_date_string) { char *time_str = NULL; int time_str_len = 0; timelib_time *time; timelib_error_container *err = NULL; php_interval_obj *diobj; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &time_str, &time_str_len) == FAILURE) { RETURN_FALSE; } php_date_instantiate(date_ce_interval, return_value TSRMLS_CC); time = timelib_strtotime(time_str, time_str_len, &err, DATE_TIMEZONEDB); diobj = (php_interval_obj *) zend_object_store_get_object(return_value TSRMLS_CC); diobj->diff = timelib_rel_time_clone(&time->relative); diobj->initialized = 1; timelib_time_dtor(time); timelib_error_container_dtor(err); } /* }}} */ /* {{{ date_interval_format - */ static char *date_interval_format(char *format, int format_len, timelib_rel_time *t) { smart_str string = {0}; int i, length, have_format_spec = 0; char buffer[33]; if (!format_len) { return estrdup(""); } for (i = 0; i < format_len; i++) { if (have_format_spec) { switch (format[i]) { case 'Y': length = slprintf(buffer, 32, "%02d", (int) t->y); break; case 'y': length = slprintf(buffer, 32, "%d", (int) t->y); break; case 'M': length = slprintf(buffer, 32, "%02d", (int) t->m); break; case 'm': length = slprintf(buffer, 32, "%d", (int) t->m); break; case 'D': length = slprintf(buffer, 32, "%02d", (int) t->d); break; case 'd': length = slprintf(buffer, 32, "%d", (int) t->d); break; case 'H': length = slprintf(buffer, 32, "%02d", (int) t->h); break; case 'h': length = slprintf(buffer, 32, "%d", (int) t->h); break; case 'I': length = slprintf(buffer, 32, "%02d", (int) t->i); break; case 'i': length = slprintf(buffer, 32, "%d", (int) t->i); break; case 'S': length = slprintf(buffer, 32, "%02d", (int) t->s); break; case 's': length = slprintf(buffer, 32, "%d", (int) t->s); break; case 'a': { if ((int) t->days != -99999) { length = slprintf(buffer, 32, "%d", (int) t->days); } else { length = slprintf(buffer, 32, "(unknown)"); } } break; case 'r': length = slprintf(buffer, 32, "%s", t->invert ? "-" : ""); break; case 'R': length = slprintf(buffer, 32, "%c", t->invert ? '-' : '+'); break; case '%': length = slprintf(buffer, 32, "%%"); break; default: buffer[0] = '%'; buffer[1] = format[i]; buffer[2] = '\0'; length = 2; break; } smart_str_appendl(&string, buffer, length); have_format_spec = 0; } else { if (format[i] == '%') { have_format_spec = 1; } else { smart_str_appendc(&string, format[i]); } } } smart_str_0(&string); return string.c; } /* }}} */ /* {{{ proto string date_interval_format(DateInterval object, string format) Formats the interval. */ PHP_FUNCTION(date_interval_format) { zval *object; php_interval_obj *diobj; char *format; int format_len; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, date_ce_interval, &format, &format_len) == FAILURE) { RETURN_FALSE; } diobj = (php_interval_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(diobj->initialized, DateInterval); RETURN_STRING(date_interval_format(format, format_len, diobj->diff), 0); } /* }}} */ static int date_period_initialize(timelib_time **st, timelib_time **et, timelib_rel_time **d, long *recurrences, /*const*/ char *format, int format_length TSRMLS_DC) { timelib_time *b = NULL, *e = NULL; timelib_rel_time *p = NULL; int r = 0; int retval = 0; struct timelib_error_container *errors; timelib_strtointerval(format, format_length, &b, &e, &p, &r, &errors); if (errors->error_count > 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown or bad format (%s)", format); retval = FAILURE; } else { *st = b; *et = e; *d = p; *recurrences = r; retval = SUCCESS; } timelib_error_container_dtor(errors); return retval; } /* {{{ proto DatePeriod::__construct(DateTime $start, DateInterval $interval, int recurrences|DateTime $end) Creates new DatePeriod object. */ PHP_METHOD(DatePeriod, __construct) { php_period_obj *dpobj; php_date_obj *dateobj; php_interval_obj *intobj; zval *start, *end = NULL, *interval; long recurrences = 0, options = 0; char *isostr = NULL; int isostr_len = 0; timelib_time *clone; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "OOl|l", &start, date_ce_date, &interval, date_ce_interval, &recurrences, &options) == FAILURE) { if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "OOO|l", &start, date_ce_date, &interval, date_ce_interval, &end, date_ce_date, &options) == FAILURE) { if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &isostr, &isostr_len, &options) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "This constructor accepts either (DateTime, DateInterval, int) OR (DateTime, DateInterval, DateTime) OR (string) as arguments."); zend_restore_error_handling(&error_handling TSRMLS_CC); return; } } } dpobj = zend_object_store_get_object(getThis() TSRMLS_CC); dpobj->current = NULL; if (isostr_len) { date_period_initialize(&(dpobj->start), &(dpobj->end), &(dpobj->interval), &recurrences, isostr, isostr_len TSRMLS_CC); if (dpobj->start == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The ISO interval '%s' did not contain a start date.", isostr); } if (dpobj->interval == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The ISO interval '%s' did not contain an interval.", isostr); } if (dpobj->end == NULL && recurrences == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The ISO interval '%s' did not contain an end date or a recurrence count.", isostr); } if (dpobj->start) { timelib_update_ts(dpobj->start, NULL); } if (dpobj->end) { timelib_update_ts(dpobj->end, NULL); } } else { /* init */ intobj = (php_interval_obj *) zend_object_store_get_object(interval TSRMLS_CC); /* start date */ dateobj = (php_date_obj *) zend_object_store_get_object(start TSRMLS_CC); clone = timelib_time_ctor(); memcpy(clone, dateobj->time, sizeof(timelib_time)); if (dateobj->time->tz_abbr) { clone->tz_abbr = strdup(dateobj->time->tz_abbr); } if (dateobj->time->tz_info) { clone->tz_info = dateobj->time->tz_info; } dpobj->start = clone; /* interval */ dpobj->interval = timelib_rel_time_clone(intobj->diff); /* end date */ if (end) { dateobj = (php_date_obj *) zend_object_store_get_object(end TSRMLS_CC); clone = timelib_time_clone(dateobj->time); dpobj->end = clone; } } /* options */ dpobj->include_start_date = !(options & PHP_DATE_PERIOD_EXCLUDE_START_DATE); /* recurrrences */ dpobj->recurrences = recurrences + dpobj->include_start_date; dpobj->initialized = 1; zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ static int check_id_allowed(char *id, long what) { if (what & PHP_DATE_TIMEZONE_GROUP_AFRICA && strncasecmp(id, "Africa/", 7) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_AMERICA && strncasecmp(id, "America/", 8) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_ANTARCTICA && strncasecmp(id, "Antarctica/", 11) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_ARCTIC && strncasecmp(id, "Arctic/", 7) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_ASIA && strncasecmp(id, "Asia/", 5) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_ATLANTIC && strncasecmp(id, "Atlantic/", 9) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_AUSTRALIA && strncasecmp(id, "Australia/", 10) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_EUROPE && strncasecmp(id, "Europe/", 7) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_INDIAN && strncasecmp(id, "Indian/", 7) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_PACIFIC && strncasecmp(id, "Pacific/", 8) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_UTC && strncasecmp(id, "UTC", 3) == 0) return 1; return 0; } /* {{{ proto array timezone_identifiers_list([long what[, string country]]) Returns numerically index array with all timezone identifiers. */ PHP_FUNCTION(timezone_identifiers_list) { const timelib_tzdb *tzdb; const timelib_tzdb_index_entry *table; int i, item_count; long what = PHP_DATE_TIMEZONE_GROUP_ALL; char *option = NULL; int option_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|ls", &what, &option, &option_len) == FAILURE) { RETURN_FALSE; } /* Extra validation */ if (what == PHP_DATE_TIMEZONE_PER_COUNTRY && option_len != 2) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "A two-letter ISO 3166-1 compatible country code is expected"); RETURN_FALSE; } tzdb = DATE_TIMEZONEDB; item_count = tzdb->index_size; table = tzdb->index; array_init(return_value); for (i = 0; i < item_count; ++i) { if (what == PHP_DATE_TIMEZONE_PER_COUNTRY) { if (tzdb->data[table[i].pos + 5] == option[0] && tzdb->data[table[i].pos + 6] == option[1]) { add_next_index_string(return_value, table[i].id, 1); } } else if (what == PHP_DATE_TIMEZONE_GROUP_ALL_W_BC || (check_id_allowed(table[i].id, what) && (tzdb->data[table[i].pos + 4] == '\1'))) { add_next_index_string(return_value, table[i].id, 1); } }; } /* }}} */ /* {{{ proto array timezone_version_get() Returns the Olson database version number. */ PHP_FUNCTION(timezone_version_get) { const timelib_tzdb *tzdb; tzdb = DATE_TIMEZONEDB; RETURN_STRING(tzdb->version, 1); } /* }}} */ /* {{{ proto array timezone_abbreviations_list() Returns associative array containing dst, offset and the timezone name */ PHP_FUNCTION(timezone_abbreviations_list) { const timelib_tz_lookup_table *table, *entry; zval *element, **abbr_array_pp, *abbr_array; table = timelib_timezone_abbreviations_list(); array_init(return_value); entry = table; do { MAKE_STD_ZVAL(element); array_init(element); add_assoc_bool(element, "dst", entry->type); add_assoc_long(element, "offset", entry->gmtoffset); if (entry->full_tz_name) { add_assoc_string(element, "timezone_id", entry->full_tz_name, 1); } else { add_assoc_null(element, "timezone_id"); } if (zend_hash_find(HASH_OF(return_value), entry->name, strlen(entry->name) + 1, (void **) &abbr_array_pp) == FAILURE) { MAKE_STD_ZVAL(abbr_array); array_init(abbr_array); add_assoc_zval(return_value, entry->name, abbr_array); } else { abbr_array = *abbr_array_pp; } add_next_index_zval(abbr_array, element); entry++; } while (entry->name); } /* }}} */ /* {{{ proto bool date_default_timezone_set(string timezone_identifier) Sets the default timezone used by all date/time functions in a script */ PHP_FUNCTION(date_default_timezone_set) { char *zone; int zone_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &zone, &zone_len) == FAILURE) { RETURN_FALSE; } if (!timelib_timezone_id_is_valid(zone, DATE_TIMEZONEDB)) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Timezone ID '%s' is invalid", zone); RETURN_FALSE; } if (DATEG(timezone)) { efree(DATEG(timezone)); DATEG(timezone) = NULL; } DATEG(timezone) = estrndup(zone, zone_len); RETURN_TRUE; } /* }}} */ /* {{{ proto string date_default_timezone_get() Gets the default timezone used by all date/time functions in a script */ PHP_FUNCTION(date_default_timezone_get) { timelib_tzinfo *default_tz; default_tz = get_timezone_info(TSRMLS_C); RETVAL_STRING(default_tz->name, 1); } /* }}} */ /* {{{ php_do_date_sunrise_sunset * Common for date_sunrise() and date_sunset() functions */ static void php_do_date_sunrise_sunset(INTERNAL_FUNCTION_PARAMETERS, int calc_sunset) { double latitude = 0.0, longitude = 0.0, zenith = 0.0, gmt_offset = 0, altitude; double h_rise, h_set, N; timelib_sll rise, set, transit; long time, retformat = 0; int rs; timelib_time *t; timelib_tzinfo *tzi; char *retstr; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|ldddd", &time, &retformat, &latitude, &longitude, &zenith, &gmt_offset) == FAILURE) { RETURN_FALSE; } switch (ZEND_NUM_ARGS()) { case 1: retformat = SUNFUNCS_RET_STRING; case 2: latitude = INI_FLT("date.default_latitude"); case 3: longitude = INI_FLT("date.default_longitude"); case 4: if (calc_sunset) { zenith = INI_FLT("date.sunset_zenith"); } else { zenith = INI_FLT("date.sunrise_zenith"); } case 5: case 6: break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "invalid format"); RETURN_FALSE; break; } if (retformat != SUNFUNCS_RET_TIMESTAMP && retformat != SUNFUNCS_RET_STRING && retformat != SUNFUNCS_RET_DOUBLE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Wrong return format given, pick one of SUNFUNCS_RET_TIMESTAMP, SUNFUNCS_RET_STRING or SUNFUNCS_RET_DOUBLE"); RETURN_FALSE; } altitude = 90 - zenith; /* Initialize time struct */ t = timelib_time_ctor(); tzi = get_timezone_info(TSRMLS_C); t->tz_info = tzi; t->zone_type = TIMELIB_ZONETYPE_ID; if (ZEND_NUM_ARGS() <= 5) { gmt_offset = timelib_get_current_offset(t) / 3600; } timelib_unixtime2local(t, time); rs = timelib_astro_rise_set_altitude(t, longitude, latitude, altitude, 1, &h_rise, &h_set, &rise, &set, &transit); timelib_time_dtor(t); if (rs != 0) { RETURN_FALSE; } if (retformat == SUNFUNCS_RET_TIMESTAMP) { RETURN_LONG(calc_sunset ? set : rise); } N = (calc_sunset ? h_set : h_rise) + gmt_offset; if (N > 24 || N < 0) { N -= floor(N / 24) * 24; } switch (retformat) { case SUNFUNCS_RET_STRING: spprintf(&retstr, 0, "%02d:%02d", (int) N, (int) (60 * (N - (int) N))); RETURN_STRINGL(retstr, 5, 0); break; case SUNFUNCS_RET_DOUBLE: RETURN_DOUBLE(N); break; } } /* }}} */ /* {{{ proto mixed date_sunrise(mixed time [, int format [, float latitude [, float longitude [, float zenith [, float gmt_offset]]]]]) Returns time of sunrise for a given day and location */ PHP_FUNCTION(date_sunrise) { php_do_date_sunrise_sunset(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto mixed date_sunset(mixed time [, int format [, float latitude [, float longitude [, float zenith [, float gmt_offset]]]]]) Returns time of sunset for a given day and location */ PHP_FUNCTION(date_sunset) { php_do_date_sunrise_sunset(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto array date_sun_info(long time, float latitude, float longitude) Returns an array with information about sun set/rise and twilight begin/end */ PHP_FUNCTION(date_sun_info) { long time; double latitude, longitude; timelib_time *t, *t2; timelib_tzinfo *tzi; int rs; timelib_sll rise, set, transit; int dummy; double ddummy; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ldd", &time, &latitude, &longitude) == FAILURE) { RETURN_FALSE; } /* Initialize time struct */ t = timelib_time_ctor(); tzi = get_timezone_info(TSRMLS_C); t->tz_info = tzi; t->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(t, time); /* Setup */ t2 = timelib_time_ctor(); array_init(return_value); /* Get sun up/down and transit */ rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -35.0/60, 1, &ddummy, &ddummy, &rise, &set, &transit); switch (rs) { case -1: /* always below */ add_assoc_bool(return_value, "sunrise", 0); add_assoc_bool(return_value, "sunset", 0); break; case 1: /* always above */ add_assoc_bool(return_value, "sunrise", 1); add_assoc_bool(return_value, "sunset", 1); break; default: t2->sse = rise; add_assoc_long(return_value, "sunrise", timelib_date_to_int(t2, &dummy)); t2->sse = set; add_assoc_long(return_value, "sunset", timelib_date_to_int(t2, &dummy)); } t2->sse = transit; add_assoc_long(return_value, "transit", timelib_date_to_int(t2, &dummy)); /* Get civil twilight */ rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -6.0, 0, &ddummy, &ddummy, &rise, &set, &transit); switch (rs) { case -1: /* always below */ add_assoc_bool(return_value, "civil_twilight_begin", 0); add_assoc_bool(return_value, "civil_twilight_end", 0); break; case 1: /* always above */ add_assoc_bool(return_value, "civil_twilight_begin", 1); add_assoc_bool(return_value, "civil_twilight_end", 1); break; default: t2->sse = rise; add_assoc_long(return_value, "civil_twilight_begin", timelib_date_to_int(t2, &dummy)); t2->sse = set; add_assoc_long(return_value, "civil_twilight_end", timelib_date_to_int(t2, &dummy)); } /* Get nautical twilight */ rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -12.0, 0, &ddummy, &ddummy, &rise, &set, &transit); switch (rs) { case -1: /* always below */ add_assoc_bool(return_value, "nautical_twilight_begin", 0); add_assoc_bool(return_value, "nautical_twilight_end", 0); break; case 1: /* always above */ add_assoc_bool(return_value, "nautical_twilight_begin", 1); add_assoc_bool(return_value, "nautical_twilight_end", 1); break; default: t2->sse = rise; add_assoc_long(return_value, "nautical_twilight_begin", timelib_date_to_int(t2, &dummy)); t2->sse = set; add_assoc_long(return_value, "nautical_twilight_end", timelib_date_to_int(t2, &dummy)); } /* Get astronomical twilight */ rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -18.0, 0, &ddummy, &ddummy, &rise, &set, &transit); switch (rs) { case -1: /* always below */ add_assoc_bool(return_value, "astronomical_twilight_begin", 0); add_assoc_bool(return_value, "astronomical_twilight_end", 0); break; case 1: /* always above */ add_assoc_bool(return_value, "astronomical_twilight_begin", 1); add_assoc_bool(return_value, "astronomical_twilight_end", 1); break; default: t2->sse = rise; add_assoc_long(return_value, "astronomical_twilight_begin", timelib_date_to_int(t2, &dummy)); t2->sse = set; add_assoc_long(return_value, "astronomical_twilight_end", timelib_date_to_int(t2, &dummy)); } timelib_time_dtor(t); timelib_time_dtor(t2); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: fdm=marker * vim: noet sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Derick Rethans <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "php.h" #include "php_streams.h" #include "php_main.h" #include "php_globals.h" #include "php_ini.h" #include "ext/standard/info.h" #include "ext/standard/php_versioning.h" #include "ext/standard/php_math.h" #include "php_date.h" #include "zend_interfaces.h" #include "lib/timelib.h" #include <time.h> #ifdef PHP_WIN32 static __inline __int64 php_date_llabs( __int64 i ) { return i >= 0? i: -i; } #elif defined(__GNUC__) && __GNUC__ < 3 static __inline __int64_t php_date_llabs( __int64_t i ) { return i >= 0 ? i : -i; } #else static inline long long php_date_llabs( long long i ) { return i >= 0 ? i : -i; } #endif /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_date, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_gmdate, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_idate, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strtotime, 0, 0, 1) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, now) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mktime, 0, 0, 0) ZEND_ARG_INFO(0, hour) ZEND_ARG_INFO(0, min) ZEND_ARG_INFO(0, sec) ZEND_ARG_INFO(0, mon) ZEND_ARG_INFO(0, day) ZEND_ARG_INFO(0, year) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_gmmktime, 0, 0, 0) ZEND_ARG_INFO(0, hour) ZEND_ARG_INFO(0, min) ZEND_ARG_INFO(0, sec) ZEND_ARG_INFO(0, mon) ZEND_ARG_INFO(0, day) ZEND_ARG_INFO(0, year) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_checkdate, 0) ZEND_ARG_INFO(0, month) ZEND_ARG_INFO(0, day) ZEND_ARG_INFO(0, year) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_strftime, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_gmstrftime, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_time, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_localtime, 0, 0, 0) ZEND_ARG_INFO(0, timestamp) ZEND_ARG_INFO(0, associative_array) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_getdate, 0, 0, 0) ZEND_ARG_INFO(0, timestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_default_timezone_set, 0) ZEND_ARG_INFO(0, timezone_identifier) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_default_timezone_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_sunrise, 0, 0, 1) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, latitude) ZEND_ARG_INFO(0, longitude) ZEND_ARG_INFO(0, zenith) ZEND_ARG_INFO(0, gmt_offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_sunset, 0, 0, 1) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, latitude) ZEND_ARG_INFO(0, longitude) ZEND_ARG_INFO(0, zenith) ZEND_ARG_INFO(0, gmt_offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_sun_info, 0) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, latitude) ZEND_ARG_INFO(0, longitude) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_create, 0, 0, 0) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_create_from_format, 0, 0, 2) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, time) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_parse, 0, 0, 1) ZEND_ARG_INFO(0, date) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_parse_from_format, 0, 0, 2) ZEND_ARG_INFO(0, format) ZEND_ARG_INFO(0, date) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_get_last_errors, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_format, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_format, 0, 0, 1) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_modify, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, modify) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_modify, 0, 0, 1) ZEND_ARG_INFO(0, modify) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_add, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, interval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_add, 0, 0, 1) ZEND_ARG_INFO(0, interval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_sub, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, interval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_sub, 0, 0, 1) ZEND_ARG_INFO(0, interval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_timezone_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_method_timezone_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_timezone_set, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, timezone) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_timezone_set, 0, 0, 1) ZEND_ARG_INFO(0, timezone) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_offset_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_method_offset_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_diff, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, object2) ZEND_ARG_INFO(0, absolute) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_diff, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, absolute) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_time_set, 0, 0, 3) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, hour) ZEND_ARG_INFO(0, minute) ZEND_ARG_INFO(0, second) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_time_set, 0, 0, 2) ZEND_ARG_INFO(0, hour) ZEND_ARG_INFO(0, minute) ZEND_ARG_INFO(0, second) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_date_set, 0, 0, 4) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, year) ZEND_ARG_INFO(0, month) ZEND_ARG_INFO(0, day) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_date_set, 0, 0, 3) ZEND_ARG_INFO(0, year) ZEND_ARG_INFO(0, month) ZEND_ARG_INFO(0, day) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_isodate_set, 0, 0, 3) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, year) ZEND_ARG_INFO(0, week) ZEND_ARG_INFO(0, day) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_isodate_set, 0, 0, 2) ZEND_ARG_INFO(0, year) ZEND_ARG_INFO(0, week) ZEND_ARG_INFO(0, day) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_timestamp_set, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, unixtimestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_method_timestamp_set, 0, 0, 1) ZEND_ARG_INFO(0, unixtimestamp) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_timestamp_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_method_timestamp_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_open, 0, 0, 1) ZEND_ARG_INFO(0, timezone) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_name_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_method_name_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_name_from_abbr, 0, 0, 1) ZEND_ARG_INFO(0, abbr) ZEND_ARG_INFO(0, gmtoffset) ZEND_ARG_INFO(0, isdst) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_offset_get, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, datetime) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_method_offset_get, 0, 0, 1) ZEND_ARG_INFO(0, datetime) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_transitions_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, timestamp_begin) ZEND_ARG_INFO(0, timestamp_end) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_method_transitions_get, 0) ZEND_ARG_INFO(0, timestamp_begin) ZEND_ARG_INFO(0, timestamp_end) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_location_get, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_method_location_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_timezone_identifiers_list, 0, 0, 0) ZEND_ARG_INFO(0, what) ZEND_ARG_INFO(0, country) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_abbreviations_list, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_timezone_version_get, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_interval_create_from_date_string, 0, 0, 1) ZEND_ARG_INFO(0, time) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_interval_format, 0, 0, 2) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_date_method_interval_format, 0) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_period_construct, 0, 0, 3) ZEND_ARG_INFO(0, start) ZEND_ARG_INFO(0, interval) ZEND_ARG_INFO(0, end) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_date_interval_construct, 0, 0, 0) ZEND_ARG_INFO(0, interval_spec) ZEND_END_ARG_INFO() /* }}} */ /* {{{ Function table */ const zend_function_entry date_functions[] = { PHP_FE(strtotime, arginfo_strtotime) PHP_FE(date, arginfo_date) PHP_FE(idate, arginfo_idate) PHP_FE(gmdate, arginfo_gmdate) PHP_FE(mktime, arginfo_mktime) PHP_FE(gmmktime, arginfo_gmmktime) PHP_FE(checkdate, arginfo_checkdate) #ifdef HAVE_STRFTIME PHP_FE(strftime, arginfo_strftime) PHP_FE(gmstrftime, arginfo_gmstrftime) #endif PHP_FE(time, arginfo_time) PHP_FE(localtime, arginfo_localtime) PHP_FE(getdate, arginfo_getdate) /* Advanced Interface */ PHP_FE(date_create, arginfo_date_create) PHP_FE(date_create_from_format, arginfo_date_create_from_format) PHP_FE(date_parse, arginfo_date_parse) PHP_FE(date_parse_from_format, arginfo_date_parse_from_format) PHP_FE(date_get_last_errors, arginfo_date_get_last_errors) PHP_FE(date_format, arginfo_date_format) PHP_FE(date_modify, arginfo_date_modify) PHP_FE(date_add, arginfo_date_add) PHP_FE(date_sub, arginfo_date_sub) PHP_FE(date_timezone_get, arginfo_date_timezone_get) PHP_FE(date_timezone_set, arginfo_date_timezone_set) PHP_FE(date_offset_get, arginfo_date_offset_get) PHP_FE(date_diff, arginfo_date_diff) PHP_FE(date_time_set, arginfo_date_time_set) PHP_FE(date_date_set, arginfo_date_date_set) PHP_FE(date_isodate_set, arginfo_date_isodate_set) PHP_FE(date_timestamp_set, arginfo_date_timestamp_set) PHP_FE(date_timestamp_get, arginfo_date_timestamp_get) PHP_FE(timezone_open, arginfo_timezone_open) PHP_FE(timezone_name_get, arginfo_timezone_name_get) PHP_FE(timezone_name_from_abbr, arginfo_timezone_name_from_abbr) PHP_FE(timezone_offset_get, arginfo_timezone_offset_get) PHP_FE(timezone_transitions_get, arginfo_timezone_transitions_get) PHP_FE(timezone_location_get, arginfo_timezone_location_get) PHP_FE(timezone_identifiers_list, arginfo_timezone_identifiers_list) PHP_FE(timezone_abbreviations_list, arginfo_timezone_abbreviations_list) PHP_FE(timezone_version_get, arginfo_timezone_version_get) PHP_FE(date_interval_create_from_date_string, arginfo_date_interval_create_from_date_string) PHP_FE(date_interval_format, arginfo_date_interval_format) /* Options and Configuration */ PHP_FE(date_default_timezone_set, arginfo_date_default_timezone_set) PHP_FE(date_default_timezone_get, arginfo_date_default_timezone_get) /* Astronomical functions */ PHP_FE(date_sunrise, arginfo_date_sunrise) PHP_FE(date_sunset, arginfo_date_sunset) PHP_FE(date_sun_info, arginfo_date_sun_info) {NULL, NULL, NULL} }; const zend_function_entry date_funcs_date[] = { PHP_ME(DateTime, __construct, arginfo_date_create, ZEND_ACC_CTOR|ZEND_ACC_PUBLIC) PHP_ME(DateTime, __wakeup, NULL, ZEND_ACC_PUBLIC) PHP_ME(DateTime, __set_state, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_ME_MAPPING(createFromFormat, date_create_from_format, arginfo_date_create_from_format, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_ME_MAPPING(getLastErrors, date_get_last_errors, arginfo_date_get_last_errors, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_ME_MAPPING(format, date_format, arginfo_date_method_format, 0) PHP_ME_MAPPING(modify, date_modify, arginfo_date_method_modify, 0) PHP_ME_MAPPING(add, date_add, arginfo_date_method_add, 0) PHP_ME_MAPPING(sub, date_sub, arginfo_date_method_sub, 0) PHP_ME_MAPPING(getTimezone, date_timezone_get, arginfo_date_method_timezone_get, 0) PHP_ME_MAPPING(setTimezone, date_timezone_set, arginfo_date_method_timezone_set, 0) PHP_ME_MAPPING(getOffset, date_offset_get, arginfo_date_method_offset_get, 0) PHP_ME_MAPPING(setTime, date_time_set, arginfo_date_method_time_set, 0) PHP_ME_MAPPING(setDate, date_date_set, arginfo_date_method_date_set, 0) PHP_ME_MAPPING(setISODate, date_isodate_set, arginfo_date_method_isodate_set, 0) PHP_ME_MAPPING(setTimestamp, date_timestamp_set, arginfo_date_method_timestamp_set, 0) PHP_ME_MAPPING(getTimestamp, date_timestamp_get, arginfo_date_method_timestamp_get, 0) PHP_ME_MAPPING(diff, date_diff, arginfo_date_method_diff, 0) {NULL, NULL, NULL} }; const zend_function_entry date_funcs_timezone[] = { PHP_ME(DateTimeZone, __construct, arginfo_timezone_open, ZEND_ACC_CTOR|ZEND_ACC_PUBLIC) PHP_ME_MAPPING(getName, timezone_name_get, arginfo_timezone_method_name_get, 0) PHP_ME_MAPPING(getOffset, timezone_offset_get, arginfo_timezone_method_offset_get, 0) PHP_ME_MAPPING(getTransitions, timezone_transitions_get, arginfo_timezone_method_transitions_get, 0) PHP_ME_MAPPING(getLocation, timezone_location_get, arginfo_timezone_method_location_get, 0) PHP_ME_MAPPING(listAbbreviations, timezone_abbreviations_list, arginfo_timezone_abbreviations_list, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_ME_MAPPING(listIdentifiers, timezone_identifiers_list, arginfo_timezone_identifiers_list, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) {NULL, NULL, NULL} }; const zend_function_entry date_funcs_interval[] = { PHP_ME(DateInterval, __construct, arginfo_date_interval_construct, ZEND_ACC_CTOR|ZEND_ACC_PUBLIC) PHP_ME_MAPPING(format, date_interval_format, arginfo_date_method_interval_format, 0) PHP_ME_MAPPING(createFromDateString, date_interval_create_from_date_string, arginfo_date_interval_create_from_date_string, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) {NULL, NULL, NULL} }; const zend_function_entry date_funcs_period[] = { PHP_ME(DatePeriod, __construct, arginfo_date_period_construct, ZEND_ACC_CTOR|ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; static char* guess_timezone(const timelib_tzdb *tzdb TSRMLS_DC); static void date_register_classes(TSRMLS_D); /* }}} */ ZEND_DECLARE_MODULE_GLOBALS(date) static PHP_GINIT_FUNCTION(date); /* True global */ timelib_tzdb *php_date_global_timezone_db; int php_date_global_timezone_db_enabled; #define DATE_DEFAULT_LATITUDE "31.7667" #define DATE_DEFAULT_LONGITUDE "35.2333" /* on 90'35; common sunset declaration (start of sun body appear) */ #define DATE_SUNSET_ZENITH "90.583333" /* on 90'35; common sunrise declaration (sun body disappeared) */ #define DATE_SUNRISE_ZENITH "90.583333" /* {{{ INI Settings */ PHP_INI_BEGIN() STD_PHP_INI_ENTRY("date.timezone", "", PHP_INI_ALL, OnUpdateString, default_timezone, zend_date_globals, date_globals) PHP_INI_ENTRY("date.default_latitude", DATE_DEFAULT_LATITUDE, PHP_INI_ALL, NULL) PHP_INI_ENTRY("date.default_longitude", DATE_DEFAULT_LONGITUDE, PHP_INI_ALL, NULL) PHP_INI_ENTRY("date.sunset_zenith", DATE_SUNSET_ZENITH, PHP_INI_ALL, NULL) PHP_INI_ENTRY("date.sunrise_zenith", DATE_SUNRISE_ZENITH, PHP_INI_ALL, NULL) PHP_INI_END() /* }}} */ zend_class_entry *date_ce_date, *date_ce_timezone, *date_ce_interval, *date_ce_period; PHPAPI zend_class_entry *php_date_get_date_ce(void) { return date_ce_date; } PHPAPI zend_class_entry *php_date_get_timezone_ce(void) { return date_ce_timezone; } static zend_object_handlers date_object_handlers_date; static zend_object_handlers date_object_handlers_timezone; static zend_object_handlers date_object_handlers_interval; static zend_object_handlers date_object_handlers_period; #define DATE_SET_CONTEXT \ zval *object; \ object = getThis(); \ #define DATE_FETCH_OBJECT \ php_date_obj *obj; \ DATE_SET_CONTEXT; \ if (object) { \ if (zend_parse_parameters_none() == FAILURE) { \ return; \ } \ } else { \ if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, NULL, "O", &object, date_ce_date) == FAILURE) { \ RETURN_FALSE; \ } \ } \ obj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); \ #define DATE_CHECK_INITIALIZED(member, class_name) \ if (!(member)) { \ php_error_docref(NULL TSRMLS_CC, E_WARNING, "The " #class_name " object has not been correctly initialized by its constructor"); \ RETURN_FALSE; \ } static void date_object_free_storage_date(void *object TSRMLS_DC); static void date_object_free_storage_timezone(void *object TSRMLS_DC); static void date_object_free_storage_interval(void *object TSRMLS_DC); static void date_object_free_storage_period(void *object TSRMLS_DC); static zend_object_value date_object_new_date(zend_class_entry *class_type TSRMLS_DC); static zend_object_value date_object_new_timezone(zend_class_entry *class_type TSRMLS_DC); static zend_object_value date_object_new_interval(zend_class_entry *class_type TSRMLS_DC); static zend_object_value date_object_new_period(zend_class_entry *class_type TSRMLS_DC); static zend_object_value date_object_clone_date(zval *this_ptr TSRMLS_DC); static zend_object_value date_object_clone_timezone(zval *this_ptr TSRMLS_DC); static zend_object_value date_object_clone_interval(zval *this_ptr TSRMLS_DC); static zend_object_value date_object_clone_period(zval *this_ptr TSRMLS_DC); static int date_object_compare_date(zval *d1, zval *d2 TSRMLS_DC); static HashTable *date_object_get_properties(zval *object TSRMLS_DC); static HashTable *date_object_get_properties_interval(zval *object TSRMLS_DC); zval *date_interval_read_property(zval *object, zval *member, int type, const zend_literal *key TSRMLS_DC); void date_interval_write_property(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC); /* {{{ Module struct */ zend_module_entry date_module_entry = { STANDARD_MODULE_HEADER_EX, NULL, NULL, "date", /* extension name */ date_functions, /* function list */ PHP_MINIT(date), /* process startup */ PHP_MSHUTDOWN(date), /* process shutdown */ PHP_RINIT(date), /* request startup */ PHP_RSHUTDOWN(date), /* request shutdown */ PHP_MINFO(date), /* extension info */ PHP_VERSION, /* extension version */ PHP_MODULE_GLOBALS(date), /* globals descriptor */ PHP_GINIT(date), /* globals ctor */ NULL, /* globals dtor */ NULL, /* post deactivate */ STANDARD_MODULE_PROPERTIES_EX }; /* }}} */ /* {{{ PHP_GINIT_FUNCTION */ static PHP_GINIT_FUNCTION(date) { date_globals->default_timezone = NULL; date_globals->timezone = NULL; date_globals->tzcache = NULL; } /* }}} */ static void _php_date_tzinfo_dtor(void *tzinfo) { timelib_tzinfo **tzi = (timelib_tzinfo **)tzinfo; timelib_tzinfo_dtor(*tzi); } /* {{{ PHP_RINIT_FUNCTION */ PHP_RINIT_FUNCTION(date) { if (DATEG(timezone)) { efree(DATEG(timezone)); } DATEG(timezone) = NULL; DATEG(tzcache) = NULL; DATEG(last_errors) = NULL; return SUCCESS; } /* }}} */ /* {{{ PHP_RSHUTDOWN_FUNCTION */ PHP_RSHUTDOWN_FUNCTION(date) { if (DATEG(timezone)) { efree(DATEG(timezone)); } DATEG(timezone) = NULL; if(DATEG(tzcache)) { zend_hash_destroy(DATEG(tzcache)); FREE_HASHTABLE(DATEG(tzcache)); DATEG(tzcache) = NULL; } if (DATEG(last_errors)) { timelib_error_container_dtor(DATEG(last_errors)); DATEG(last_errors) = NULL; } return SUCCESS; } /* }}} */ #define DATE_TIMEZONEDB php_date_global_timezone_db ? php_date_global_timezone_db : timelib_builtin_db() /* * RFC822, Section 5.1: http://www.ietf.org/rfc/rfc822.txt * date-time = [ day "," ] date time ; dd mm yy hh:mm:ss zzz * day = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" * date = 1*2DIGIT month 2DIGIT ; day month year e.g. 20 Jun 82 * month = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec" * time = hour zone ; ANSI and Military * hour = 2DIGIT ":" 2DIGIT [":" 2DIGIT] ; 00:00:00 - 23:59:59 * zone = "UT" / "GMT" / "EST" / "EDT" / "CST" / "CDT" / "MST" / "MDT" / "PST" / "PDT" / 1ALPHA / ( ("+" / "-") 4DIGIT ) */ #define DATE_FORMAT_RFC822 "D, d M y H:i:s O" /* * RFC850, Section 2.1.4: http://www.ietf.org/rfc/rfc850.txt * Format must be acceptable both to the ARPANET and to the getdate routine. * One format that is acceptable to both is Weekday, DD-Mon-YY HH:MM:SS TIMEZONE * TIMEZONE can be any timezone name (3 or more letters) */ #define DATE_FORMAT_RFC850 "l, d-M-y H:i:s T" /* * RFC1036, Section 2.1.2: http://www.ietf.org/rfc/rfc1036.txt * Its format must be acceptable both in RFC-822 and to the getdate(3) * Wdy, DD Mon YY HH:MM:SS TIMEZONE * There is no hope of having a complete list of timezones. Universal * Time (GMT), the North American timezones (PST, PDT, MST, MDT, CST, * CDT, EST, EDT) and the +/-hhmm offset specifed in RFC-822 should be supported. */ #define DATE_FORMAT_RFC1036 "D, d M y H:i:s O" /* * RFC1123, Section 5.2.14: http://www.ietf.org/rfc/rfc1123.txt * RFC-822 Date and Time Specification: RFC-822 Section 5 * The syntax for the date is hereby changed to: date = 1*2DIGIT month 2*4DIGIT */ #define DATE_FORMAT_RFC1123 "D, d M Y H:i:s O" /* * RFC2822, Section 3.3: http://www.ietf.org/rfc/rfc2822.txt * FWS = ([*WSP CRLF] 1*WSP) / ; Folding white space * CFWS = *([FWS] comment) (([FWS] comment) / FWS) * * date-time = [ day-of-week "," ] date FWS time [CFWS] * day-of-week = ([FWS] day-name) * day-name = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" * date = day month year * year = 4*DIGIT * month = (FWS month-name FWS) * month-name = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec" * day = ([FWS] 1*2DIGIT) * time = time-of-day FWS zone * time-of-day = hour ":" minute [ ":" second ] * hour = 2DIGIT * minute = 2DIGIT * second = 2DIGIT * zone = (( "+" / "-" ) 4DIGIT) */ #define DATE_FORMAT_RFC2822 "D, d M Y H:i:s O" /* * RFC3339, Section 5.6: http://www.ietf.org/rfc/rfc3339.txt * date-fullyear = 4DIGIT * date-month = 2DIGIT ; 01-12 * date-mday = 2DIGIT ; 01-28, 01-29, 01-30, 01-31 based on month/year * * time-hour = 2DIGIT ; 00-23 * time-minute = 2DIGIT ; 00-59 * time-second = 2DIGIT ; 00-58, 00-59, 00-60 based on leap second rules * * time-secfrac = "." 1*DIGIT * time-numoffset = ("+" / "-") time-hour ":" time-minute * time-offset = "Z" / time-numoffset * * partial-time = time-hour ":" time-minute ":" time-second [time-secfrac] * full-date = date-fullyear "-" date-month "-" date-mday * full-time = partial-time time-offset * * date-time = full-date "T" full-time */ #define DATE_FORMAT_RFC3339 "Y-m-d\\TH:i:sP" #define DATE_FORMAT_ISO8601 "Y-m-d\\TH:i:sO" #define DATE_TZ_ERRMSG \ "It is not safe to rely on the system's timezone settings. You are " \ "*required* to use the date.timezone setting or the " \ "date_default_timezone_set() function. In case you used any of those " \ "methods and you are still getting this warning, you most likely " \ "misspelled the timezone identifier. " #define SUNFUNCS_RET_TIMESTAMP 0 #define SUNFUNCS_RET_STRING 1 #define SUNFUNCS_RET_DOUBLE 2 /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(date) { REGISTER_INI_ENTRIES(); date_register_classes(TSRMLS_C); /* * RFC4287, Section 3.3: http://www.ietf.org/rfc/rfc4287.txt * A Date construct is an element whose content MUST conform to the * "date-time" production in [RFC3339]. In addition, an uppercase "T" * character MUST be used to separate date and time, and an uppercase * "Z" character MUST be present in the absence of a numeric time zone offset. */ REGISTER_STRING_CONSTANT("DATE_ATOM", DATE_FORMAT_RFC3339, CONST_CS | CONST_PERSISTENT); /* * Preliminary specification: http://wp.netscape.com/newsref/std/cookie_spec.html * "This is based on RFC 822, RFC 850, RFC 1036, and RFC 1123, * with the variations that the only legal time zone is GMT * and the separators between the elements of the date must be dashes." */ REGISTER_STRING_CONSTANT("DATE_COOKIE", DATE_FORMAT_RFC850, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_ISO8601", DATE_FORMAT_ISO8601, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC822", DATE_FORMAT_RFC822, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC850", DATE_FORMAT_RFC850, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC1036", DATE_FORMAT_RFC1036, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC1123", DATE_FORMAT_RFC1123, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC2822", DATE_FORMAT_RFC2822, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_RFC3339", DATE_FORMAT_RFC3339, CONST_CS | CONST_PERSISTENT); /* * RSS 2.0 Specification: http://blogs.law.harvard.edu/tech/rss * "All date-times in RSS conform to the Date and Time Specification of RFC 822, * with the exception that the year may be expressed with two characters or four characters (four preferred)" */ REGISTER_STRING_CONSTANT("DATE_RSS", DATE_FORMAT_RFC1123, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("DATE_W3C", DATE_FORMAT_RFC3339, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SUNFUNCS_RET_TIMESTAMP", SUNFUNCS_RET_TIMESTAMP, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SUNFUNCS_RET_STRING", SUNFUNCS_RET_STRING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("SUNFUNCS_RET_DOUBLE", SUNFUNCS_RET_DOUBLE, CONST_CS | CONST_PERSISTENT); php_date_global_timezone_db = NULL; php_date_global_timezone_db_enabled = 0; DATEG(last_errors) = NULL; return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ PHP_MSHUTDOWN_FUNCTION(date) { UNREGISTER_INI_ENTRIES(); if (DATEG(last_errors)) { timelib_error_container_dtor(DATEG(last_errors)); } return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(date) { const timelib_tzdb *tzdb = DATE_TIMEZONEDB; php_info_print_table_start(); php_info_print_table_row(2, "date/time support", "enabled"); php_info_print_table_row(2, "\"Olson\" Timezone Database Version", tzdb->version); php_info_print_table_row(2, "Timezone Database", php_date_global_timezone_db_enabled ? "external" : "internal"); php_info_print_table_row(2, "Default timezone", guess_timezone(tzdb TSRMLS_CC)); php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ /* {{{ Timezone Cache functions */ static timelib_tzinfo *php_date_parse_tzfile(char *formal_tzname, const timelib_tzdb *tzdb TSRMLS_DC) { timelib_tzinfo *tzi, **ptzi; if(!DATEG(tzcache)) { ALLOC_HASHTABLE(DATEG(tzcache)); zend_hash_init(DATEG(tzcache), 4, NULL, _php_date_tzinfo_dtor, 0); } if (zend_hash_find(DATEG(tzcache), formal_tzname, strlen(formal_tzname) + 1, (void **) &ptzi) == SUCCESS) { return *ptzi; } tzi = timelib_parse_tzfile(formal_tzname, tzdb); if (tzi) { zend_hash_add(DATEG(tzcache), formal_tzname, strlen(formal_tzname) + 1, (void *) &tzi, sizeof(timelib_tzinfo*), NULL); } return tzi; } /* }}} */ /* {{{ Helper functions */ static char* guess_timezone(const timelib_tzdb *tzdb TSRMLS_DC) { char *env; /* Checking configure timezone */ if (DATEG(timezone) && (strlen(DATEG(timezone)) > 0)) { return DATEG(timezone); } /* Check environment variable */ env = getenv("TZ"); if (env && *env && timelib_timezone_id_is_valid(env, tzdb)) { return env; } /* Check config setting for default timezone */ if (!DATEG(default_timezone)) { /* Special case: ext/date wasn't initialized yet */ zval ztz; if (SUCCESS == zend_get_configuration_directive("date.timezone", sizeof("date.timezone"), &ztz) && Z_TYPE(ztz) == IS_STRING && Z_STRLEN(ztz) > 0 && timelib_timezone_id_is_valid(Z_STRVAL(ztz), tzdb)) { return Z_STRVAL(ztz); } } else if (*DATEG(default_timezone) && timelib_timezone_id_is_valid(DATEG(default_timezone), tzdb)) { return DATEG(default_timezone); } #if HAVE_TM_ZONE /* Try to guess timezone from system information */ { struct tm *ta, tmbuf; time_t the_time; char *tzid = NULL; the_time = time(NULL); ta = php_localtime_r(&the_time, &tmbuf); if (ta) { tzid = timelib_timezone_id_from_abbr(ta->tm_zone, ta->tm_gmtoff, ta->tm_isdst); } if (! tzid) { tzid = "UTC"; } php_error_docref(NULL TSRMLS_CC, E_WARNING, DATE_TZ_ERRMSG "We selected '%s' for '%s/%.1f/%s' instead", tzid, ta ? ta->tm_zone : "Unknown", ta ? (float) (ta->tm_gmtoff / 3600) : 0, ta ? (ta->tm_isdst ? "DST" : "no DST") : "Unknown"); return tzid; } #endif #ifdef PHP_WIN32 { char *tzid; TIME_ZONE_INFORMATION tzi; switch (GetTimeZoneInformation(&tzi)) { /* DST in effect */ case TIME_ZONE_ID_DAYLIGHT: /* If user has disabled DST in the control panel, Windows returns 0 here */ if (tzi.DaylightBias == 0) { goto php_win_std_time; } tzid = timelib_timezone_id_from_abbr("", (tzi.Bias + tzi.DaylightBias) * -60, 1); if (! tzid) { tzid = "UTC"; } php_error_docref(NULL TSRMLS_CC, E_WARNING, DATE_TZ_ERRMSG "We selected '%s' for '%.1f/DST' instead", tzid, ((tzi.Bias + tzi.DaylightBias) / -60.0)); break; /* no DST or not in effect */ case TIME_ZONE_ID_UNKNOWN: case TIME_ZONE_ID_STANDARD: default: php_win_std_time: tzid = timelib_timezone_id_from_abbr("", (tzi.Bias + tzi.StandardBias) * -60, 0); if (! tzid) { tzid = "UTC"; } php_error_docref(NULL TSRMLS_CC, E_WARNING, DATE_TZ_ERRMSG "We selected '%s' for '%.1f/no DST' instead", tzid, ((tzi.Bias + tzi.StandardBias) / -60.0)); break; } return tzid; } #elif defined(NETWARE) /* Try to guess timezone from system information */ { char *tzid = timelib_timezone_id_from_abbr("", ((_timezone * -1) + (daylightOffset * daylightOnOff)), daylightOnOff); if (tzid) { return tzid; } } #endif /* Fallback to UTC */ php_error_docref(NULL TSRMLS_CC, E_WARNING, DATE_TZ_ERRMSG "We had to select 'UTC' because your platform doesn't provide functionality for the guessing algorithm"); return "UTC"; } PHPAPI timelib_tzinfo *get_timezone_info(TSRMLS_D) { char *tz; timelib_tzinfo *tzi; tz = guess_timezone(DATE_TIMEZONEDB TSRMLS_CC); tzi = php_date_parse_tzfile(tz, DATE_TIMEZONEDB TSRMLS_CC); if (! tzi) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Timezone database is corrupt - this should *never* happen!"); } return tzi; } /* }}} */ /* {{{ date() and gmdate() data */ #include "ext/standard/php_smart_str.h" static char *mon_full_names[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; static char *mon_short_names[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; static char *day_full_names[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; static char *day_short_names[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; static char *english_suffix(timelib_sll number) { if (number >= 10 && number <= 19) { return "th"; } else { switch (number % 10) { case 1: return "st"; case 2: return "nd"; case 3: return "rd"; } } return "th"; } /* }}} */ /* {{{ day of week helpers */ char *php_date_full_day_name(timelib_sll y, timelib_sll m, timelib_sll d) { timelib_sll day_of_week = timelib_day_of_week(y, m, d); if (day_of_week < 0) { return "Unknown"; } return day_full_names[day_of_week]; } char *php_date_short_day_name(timelib_sll y, timelib_sll m, timelib_sll d) { timelib_sll day_of_week = timelib_day_of_week(y, m, d); if (day_of_week < 0) { return "Unknown"; } return day_short_names[day_of_week]; } /* }}} */ /* {{{ date_format - (gm)date helper */ static char *date_format(char *format, int format_len, timelib_time *t, int localtime) { smart_str string = {0}; int i, length; char buffer[97]; timelib_time_offset *offset = NULL; timelib_sll isoweek, isoyear; int rfc_colon; if (!format_len) { return estrdup(""); } if (localtime) { if (t->zone_type == TIMELIB_ZONETYPE_ABBR) { offset = timelib_time_offset_ctor(); offset->offset = (t->z - (t->dst * 60)) * -60; offset->leap_secs = 0; offset->is_dst = t->dst; offset->abbr = strdup(t->tz_abbr); } else if (t->zone_type == TIMELIB_ZONETYPE_OFFSET) { offset = timelib_time_offset_ctor(); offset->offset = (t->z) * -60; offset->leap_secs = 0; offset->is_dst = 0; offset->abbr = malloc(9); /* GMT�xxxx\0 */ snprintf(offset->abbr, 9, "GMT%c%02d%02d", localtime ? ((offset->offset < 0) ? '-' : '+') : '+', localtime ? abs(offset->offset / 3600) : 0, localtime ? abs((offset->offset % 3600) / 60) : 0 ); } else { offset = timelib_get_time_zone_info(t->sse, t->tz_info); } } timelib_isoweek_from_date(t->y, t->m, t->d, &isoweek, &isoyear); for (i = 0; i < format_len; i++) { rfc_colon = 0; switch (format[i]) { /* day */ case 'd': length = slprintf(buffer, 32, "%02d", (int) t->d); break; case 'D': length = slprintf(buffer, 32, "%s", php_date_short_day_name(t->y, t->m, t->d)); break; case 'j': length = slprintf(buffer, 32, "%d", (int) t->d); break; case 'l': length = slprintf(buffer, 32, "%s", php_date_full_day_name(t->y, t->m, t->d)); break; case 'S': length = slprintf(buffer, 32, "%s", english_suffix(t->d)); break; case 'w': length = slprintf(buffer, 32, "%d", (int) timelib_day_of_week(t->y, t->m, t->d)); break; case 'N': length = slprintf(buffer, 32, "%d", (int) timelib_iso_day_of_week(t->y, t->m, t->d)); break; case 'z': length = slprintf(buffer, 32, "%d", (int) timelib_day_of_year(t->y, t->m, t->d)); break; /* week */ case 'W': length = slprintf(buffer, 32, "%02d", (int) isoweek); break; /* iso weeknr */ case 'o': length = slprintf(buffer, 32, "%d", (int) isoyear); break; /* iso year */ /* month */ case 'F': length = slprintf(buffer, 32, "%s", mon_full_names[t->m - 1]); break; case 'm': length = slprintf(buffer, 32, "%02d", (int) t->m); break; case 'M': length = slprintf(buffer, 32, "%s", mon_short_names[t->m - 1]); break; case 'n': length = slprintf(buffer, 32, "%d", (int) t->m); break; case 't': length = slprintf(buffer, 32, "%d", (int) timelib_days_in_month(t->y, t->m)); break; /* year */ case 'L': length = slprintf(buffer, 32, "%d", timelib_is_leap((int) t->y)); break; case 'y': length = slprintf(buffer, 32, "%02d", (int) t->y % 100); break; case 'Y': length = slprintf(buffer, 32, "%s%04lld", t->y < 0 ? "-" : "", php_date_llabs((timelib_sll) t->y)); break; /* time */ case 'a': length = slprintf(buffer, 32, "%s", t->h >= 12 ? "pm" : "am"); break; case 'A': length = slprintf(buffer, 32, "%s", t->h >= 12 ? "PM" : "AM"); break; case 'B': { int retval = (((((long)t->sse)-(((long)t->sse) - ((((long)t->sse) % 86400) + 3600))) * 10) / 864); while (retval < 0) { retval += 1000; } retval = retval % 1000; length = slprintf(buffer, 32, "%03d", retval); break; } case 'g': length = slprintf(buffer, 32, "%d", (t->h % 12) ? (int) t->h % 12 : 12); break; case 'G': length = slprintf(buffer, 32, "%d", (int) t->h); break; case 'h': length = slprintf(buffer, 32, "%02d", (t->h % 12) ? (int) t->h % 12 : 12); break; case 'H': length = slprintf(buffer, 32, "%02d", (int) t->h); break; case 'i': length = slprintf(buffer, 32, "%02d", (int) t->i); break; case 's': length = slprintf(buffer, 32, "%02d", (int) t->s); break; case 'u': length = slprintf(buffer, 32, "%06d", (int) floor(t->f * 1000000)); break; /* timezone */ case 'I': length = slprintf(buffer, 32, "%d", localtime ? offset->is_dst : 0); break; case 'P': rfc_colon = 1; /* break intentionally missing */ case 'O': length = slprintf(buffer, 32, "%c%02d%s%02d", localtime ? ((offset->offset < 0) ? '-' : '+') : '+', localtime ? abs(offset->offset / 3600) : 0, rfc_colon ? ":" : "", localtime ? abs((offset->offset % 3600) / 60) : 0 ); break; case 'T': length = slprintf(buffer, 32, "%s", localtime ? offset->abbr : "GMT"); break; case 'e': if (!localtime) { length = slprintf(buffer, 32, "%s", "UTC"); } else { switch (t->zone_type) { case TIMELIB_ZONETYPE_ID: length = slprintf(buffer, 32, "%s", t->tz_info->name); break; case TIMELIB_ZONETYPE_ABBR: length = slprintf(buffer, 32, "%s", offset->abbr); break; case TIMELIB_ZONETYPE_OFFSET: length = slprintf(buffer, 32, "%c%02d:%02d", ((offset->offset < 0) ? '-' : '+'), abs(offset->offset / 3600), abs((offset->offset % 3600) / 60) ); break; } } break; case 'Z': length = slprintf(buffer, 32, "%d", localtime ? offset->offset : 0); break; /* full date/time */ case 'c': length = slprintf(buffer, 96, "%04d-%02d-%02dT%02d:%02d:%02d%c%02d:%02d", (int) t->y, (int) t->m, (int) t->d, (int) t->h, (int) t->i, (int) t->s, localtime ? ((offset->offset < 0) ? '-' : '+') : '+', localtime ? abs(offset->offset / 3600) : 0, localtime ? abs((offset->offset % 3600) / 60) : 0 ); break; case 'r': length = slprintf(buffer, 96, "%3s, %02d %3s %04d %02d:%02d:%02d %c%02d%02d", php_date_short_day_name(t->y, t->m, t->d), (int) t->d, mon_short_names[t->m - 1], (int) t->y, (int) t->h, (int) t->i, (int) t->s, localtime ? ((offset->offset < 0) ? '-' : '+') : '+', localtime ? abs(offset->offset / 3600) : 0, localtime ? abs((offset->offset % 3600) / 60) : 0 ); break; case 'U': length = slprintf(buffer, 32, "%lld", (timelib_sll) t->sse); break; case '\\': if (i < format_len) i++; /* break intentionally missing */ default: buffer[0] = format[i]; buffer[1] = '\0'; length = 1; break; } smart_str_appendl(&string, buffer, length); } smart_str_0(&string); if (localtime) { timelib_time_offset_dtor(offset); } return string.c; } static void php_date(INTERNAL_FUNCTION_PARAMETERS, int localtime) { char *format; int format_len; long ts; char *string; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &format, &format_len, &ts) == FAILURE) { RETURN_FALSE; } if (ZEND_NUM_ARGS() == 1) { ts = time(NULL); } string = php_format_date(format, format_len, ts, localtime TSRMLS_CC); RETVAL_STRING(string, 0); } /* }}} */ PHPAPI char *php_format_date(char *format, int format_len, time_t ts, int localtime TSRMLS_DC) /* {{{ */ { timelib_time *t; timelib_tzinfo *tzi; char *string; t = timelib_time_ctor(); if (localtime) { tzi = get_timezone_info(TSRMLS_C); t->tz_info = tzi; t->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(t, ts); } else { tzi = NULL; timelib_unixtime2gmt(t, ts); } string = date_format(format, format_len, t, localtime); timelib_time_dtor(t); return string; } /* }}} */ /* {{{ php_idate */ PHPAPI int php_idate(char format, time_t ts, int localtime TSRMLS_DC) { timelib_time *t; timelib_tzinfo *tzi; int retval = -1; timelib_time_offset *offset = NULL; timelib_sll isoweek, isoyear; t = timelib_time_ctor(); if (!localtime) { tzi = get_timezone_info(TSRMLS_C); t->tz_info = tzi; t->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(t, ts); } else { tzi = NULL; timelib_unixtime2gmt(t, ts); } if (!localtime) { if (t->zone_type == TIMELIB_ZONETYPE_ABBR) { offset = timelib_time_offset_ctor(); offset->offset = (t->z - (t->dst * 60)) * -60; offset->leap_secs = 0; offset->is_dst = t->dst; offset->abbr = strdup(t->tz_abbr); } else if (t->zone_type == TIMELIB_ZONETYPE_OFFSET) { offset = timelib_time_offset_ctor(); offset->offset = (t->z - (t->dst * 60)) * -60; offset->leap_secs = 0; offset->is_dst = t->dst; offset->abbr = malloc(9); /* GMT�xxxx\0 */ snprintf(offset->abbr, 9, "GMT%c%02d%02d", !localtime ? ((offset->offset < 0) ? '-' : '+') : '+', !localtime ? abs(offset->offset / 3600) : 0, !localtime ? abs((offset->offset % 3600) / 60) : 0 ); } else { offset = timelib_get_time_zone_info(t->sse, t->tz_info); } } timelib_isoweek_from_date(t->y, t->m, t->d, &isoweek, &isoyear); switch (format) { /* day */ case 'd': case 'j': retval = (int) t->d; break; case 'w': retval = (int) timelib_day_of_week(t->y, t->m, t->d); break; case 'z': retval = (int) timelib_day_of_year(t->y, t->m, t->d); break; /* week */ case 'W': retval = (int) isoweek; break; /* iso weeknr */ /* month */ case 'm': case 'n': retval = (int) t->m; break; case 't': retval = (int) timelib_days_in_month(t->y, t->m); break; /* year */ case 'L': retval = (int) timelib_is_leap((int) t->y); break; case 'y': retval = (int) (t->y % 100); break; case 'Y': retval = (int) t->y; break; /* Swatch Beat a.k.a. Internet Time */ case 'B': retval = (((((long)t->sse)-(((long)t->sse) - ((((long)t->sse) % 86400) + 3600))) * 10) / 864); while (retval < 0) { retval += 1000; } retval = retval % 1000; break; /* time */ case 'g': case 'h': retval = (int) ((t->h % 12) ? (int) t->h % 12 : 12); break; case 'H': case 'G': retval = (int) t->h; break; case 'i': retval = (int) t->i; break; case 's': retval = (int) t->s; break; /* timezone */ case 'I': retval = (int) (!localtime ? offset->is_dst : 0); break; case 'Z': retval = (int) (!localtime ? offset->offset : 0); break; case 'U': retval = (int) t->sse; break; } if (!localtime) { timelib_time_offset_dtor(offset); } timelib_time_dtor(t); return retval; } /* }}} */ /* {{{ proto string date(string format [, long timestamp]) Format a local date/time */ PHP_FUNCTION(date) { php_date(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto string gmdate(string format [, long timestamp]) Format a GMT date/time */ PHP_FUNCTION(gmdate) { php_date(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto int idate(string format [, int timestamp]) Format a local time/date as integer */ PHP_FUNCTION(idate) { char *format; int format_len; long ts = 0; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &format, &format_len, &ts) == FAILURE) { RETURN_FALSE; } if (format_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "idate format is one char"); RETURN_FALSE; } if (ZEND_NUM_ARGS() == 1) { ts = time(NULL); } ret = php_idate(format[0], ts, 0 TSRMLS_CC); if (ret == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unrecognized date format token."); RETURN_FALSE; } RETURN_LONG(ret); } /* }}} */ /* {{{ php_date_set_tzdb - NOT THREADSAFE */ PHPAPI void php_date_set_tzdb(timelib_tzdb *tzdb) { const timelib_tzdb *builtin = timelib_builtin_db(); if (php_version_compare(tzdb->version, builtin->version) > 0) { php_date_global_timezone_db = tzdb; php_date_global_timezone_db_enabled = 1; } } /* }}} */ /* {{{ php_parse_date: Backwards compability function */ PHPAPI signed long php_parse_date(char *string, signed long *now) { timelib_time *parsed_time; timelib_error_container *error = NULL; int error2; signed long retval; parsed_time = timelib_strtotime(string, strlen(string), &error, DATE_TIMEZONEDB); if (error->error_count) { timelib_error_container_dtor(error); return -1; } timelib_error_container_dtor(error); timelib_update_ts(parsed_time, NULL); retval = timelib_date_to_int(parsed_time, &error2); timelib_time_dtor(parsed_time); if (error2) { return -1; } return retval; } /* }}} */ /* {{{ proto int strtotime(string time [, int now ]) Convert string representation of date and time to a timestamp */ PHP_FUNCTION(strtotime) { char *times, *initial_ts; int time_len, error1, error2; struct timelib_error_container *error; long preset_ts = 0, ts; timelib_time *t, *now; timelib_tzinfo *tzi; tzi = get_timezone_info(TSRMLS_C); if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "sl", &times, &time_len, &preset_ts) != FAILURE) { /* We have an initial timestamp */ now = timelib_time_ctor(); initial_ts = emalloc(25); snprintf(initial_ts, 24, "@%ld UTC", preset_ts); t = timelib_strtotime(initial_ts, strlen(initial_ts), NULL, DATE_TIMEZONEDB); /* we ignore the error here, as this should never fail */ timelib_update_ts(t, tzi); now->tz_info = tzi; now->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(now, t->sse); timelib_time_dtor(t); efree(initial_ts); } else if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &times, &time_len, &preset_ts) != FAILURE) { /* We have no initial timestamp */ now = timelib_time_ctor(); now->tz_info = tzi; now->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(now, (timelib_sll) time(NULL)); } else { RETURN_FALSE; } if (!time_len) { timelib_time_dtor(now); RETURN_FALSE; } t = timelib_strtotime(times, time_len, &error, DATE_TIMEZONEDB); error1 = error->error_count; timelib_error_container_dtor(error); timelib_fill_holes(t, now, TIMELIB_NO_CLONE); timelib_update_ts(t, tzi); ts = timelib_date_to_int(t, &error2); timelib_time_dtor(now); timelib_time_dtor(t); if (error1 || error2) { RETURN_FALSE; } else { RETURN_LONG(ts); } } /* }}} */ /* {{{ php_mktime - (gm)mktime helper */ PHPAPI void php_mktime(INTERNAL_FUNCTION_PARAMETERS, int gmt) { long hou = 0, min = 0, sec = 0, mon = 0, day = 0, yea = 0, dst = -1; timelib_time *now; timelib_tzinfo *tzi = NULL; long ts, adjust_seconds = 0; int error; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lllllll", &hou, &min, &sec, &mon, &day, &yea, &dst) == FAILURE) { RETURN_FALSE; } /* Initialize structure with current time */ now = timelib_time_ctor(); if (gmt) { timelib_unixtime2gmt(now, (timelib_sll) time(NULL)); } else { tzi = get_timezone_info(TSRMLS_C); now->tz_info = tzi; now->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(now, (timelib_sll) time(NULL)); } /* Fill in the new data */ switch (ZEND_NUM_ARGS()) { case 7: /* break intentionally missing */ case 6: if (yea >= 0 && yea < 70) { yea += 2000; } else if (yea >= 70 && yea <= 100) { yea += 1900; } now->y = yea; /* break intentionally missing again */ case 5: now->d = day; /* break missing intentionally here too */ case 4: now->m = mon; /* and here */ case 3: now->s = sec; /* yup, this break isn't here on purpose too */ case 2: now->i = min; /* last intentionally missing break */ case 1: now->h = hou; break; default: php_error_docref(NULL TSRMLS_CC, E_STRICT, "You should be using the time() function instead"); } /* Update the timestamp */ if (gmt) { timelib_update_ts(now, NULL); } else { timelib_update_ts(now, tzi); } /* Support for the deprecated is_dst parameter */ if (dst != -1) { php_error_docref(NULL TSRMLS_CC, E_DEPRECATED, "The is_dst parameter is deprecated"); if (gmt) { /* GMT never uses DST */ if (dst == 1) { adjust_seconds = -3600; } } else { /* Figure out is_dst for current TS */ timelib_time_offset *tmp_offset; tmp_offset = timelib_get_time_zone_info(now->sse, tzi); if (dst == 1 && tmp_offset->is_dst == 0) { adjust_seconds = -3600; } if (dst == 0 && tmp_offset->is_dst == 1) { adjust_seconds = +3600; } timelib_time_offset_dtor(tmp_offset); } } /* Clean up and return */ ts = timelib_date_to_int(now, &error); ts += adjust_seconds; timelib_time_dtor(now); if (error) { RETURN_FALSE; } else { RETURN_LONG(ts); } } /* }}} */ /* {{{ proto int mktime([int hour [, int min [, int sec [, int mon [, int day [, int year]]]]]]) Get UNIX timestamp for a date */ PHP_FUNCTION(mktime) { php_mktime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto int gmmktime([int hour [, int min [, int sec [, int mon [, int day [, int year]]]]]]) Get UNIX timestamp for a GMT date */ PHP_FUNCTION(gmmktime) { php_mktime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto bool checkdate(int month, int day, int year) Returns true(1) if it is a valid date in gregorian calendar */ PHP_FUNCTION(checkdate) { long m, d, y; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lll", &m, &d, &y) == FAILURE) { RETURN_FALSE; } if (y < 1 || y > 32767 || !timelib_valid_date(y, m, d)) { RETURN_FALSE; } RETURN_TRUE; /* True : This month, day, year arguments are valid */ } /* }}} */ #ifdef HAVE_STRFTIME /* {{{ php_strftime - (gm)strftime helper */ PHPAPI void php_strftime(INTERNAL_FUNCTION_PARAMETERS, int gmt) { char *format, *buf; int format_len; long timestamp = 0; struct tm ta; int max_reallocs = 5; size_t buf_len = 64, real_len; timelib_time *ts; timelib_tzinfo *tzi; timelib_time_offset *offset = NULL; timestamp = (long) time(NULL); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &format, &format_len, &timestamp) == FAILURE) { RETURN_FALSE; } if (format_len == 0) { RETURN_FALSE; } ts = timelib_time_ctor(); if (gmt) { tzi = NULL; timelib_unixtime2gmt(ts, (timelib_sll) timestamp); } else { tzi = get_timezone_info(TSRMLS_C); ts->tz_info = tzi; ts->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(ts, (timelib_sll) timestamp); } ta.tm_sec = ts->s; ta.tm_min = ts->i; ta.tm_hour = ts->h; ta.tm_mday = ts->d; ta.tm_mon = ts->m - 1; ta.tm_year = ts->y - 1900; ta.tm_wday = timelib_day_of_week(ts->y, ts->m, ts->d); ta.tm_yday = timelib_day_of_year(ts->y, ts->m, ts->d); if (gmt) { ta.tm_isdst = 0; #if HAVE_TM_GMTOFF ta.tm_gmtoff = 0; #endif #if HAVE_TM_ZONE ta.tm_zone = "GMT"; #endif } else { offset = timelib_get_time_zone_info(timestamp, tzi); ta.tm_isdst = offset->is_dst; #if HAVE_TM_GMTOFF ta.tm_gmtoff = offset->offset; #endif #if HAVE_TM_ZONE ta.tm_zone = offset->abbr; #endif } buf = (char *) emalloc(buf_len); while ((real_len=strftime(buf, buf_len, format, &ta))==buf_len || real_len==0) { buf_len *= 2; buf = (char *) erealloc(buf, buf_len); if (!--max_reallocs) { break; } } timelib_time_dtor(ts); if (!gmt) { timelib_time_offset_dtor(offset); } if (real_len && real_len != buf_len) { buf = (char *) erealloc(buf, real_len + 1); RETURN_STRINGL(buf, real_len, 0); } efree(buf); RETURN_FALSE; } /* }}} */ /* {{{ proto string strftime(string format [, int timestamp]) Format a local time/date according to locale settings */ PHP_FUNCTION(strftime) { php_strftime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto string gmstrftime(string format [, int timestamp]) Format a GMT/UCT time/date according to locale settings */ PHP_FUNCTION(gmstrftime) { php_strftime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ #endif /* {{{ proto int time(void) Return current UNIX timestamp */ PHP_FUNCTION(time) { RETURN_LONG((long)time(NULL)); } /* }}} */ /* {{{ proto array localtime([int timestamp [, bool associative_array]]) Returns the results of the C system call localtime as an associative array if the associative_array argument is set to 1 other wise it is a regular array */ PHP_FUNCTION(localtime) { long timestamp = (long)time(NULL); zend_bool associative = 0; timelib_tzinfo *tzi; timelib_time *ts; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lb", &timestamp, &associative) == FAILURE) { RETURN_FALSE; } tzi = get_timezone_info(TSRMLS_C); ts = timelib_time_ctor(); ts->tz_info = tzi; ts->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(ts, (timelib_sll) timestamp); array_init(return_value); if (associative) { add_assoc_long(return_value, "tm_sec", ts->s); add_assoc_long(return_value, "tm_min", ts->i); add_assoc_long(return_value, "tm_hour", ts->h); add_assoc_long(return_value, "tm_mday", ts->d); add_assoc_long(return_value, "tm_mon", ts->m - 1); add_assoc_long(return_value, "tm_year", ts->y - 1900); add_assoc_long(return_value, "tm_wday", timelib_day_of_week(ts->y, ts->m, ts->d)); add_assoc_long(return_value, "tm_yday", timelib_day_of_year(ts->y, ts->m, ts->d)); add_assoc_long(return_value, "tm_isdst", ts->dst); } else { add_next_index_long(return_value, ts->s); add_next_index_long(return_value, ts->i); add_next_index_long(return_value, ts->h); add_next_index_long(return_value, ts->d); add_next_index_long(return_value, ts->m - 1); add_next_index_long(return_value, ts->y- 1900); add_next_index_long(return_value, timelib_day_of_week(ts->y, ts->m, ts->d)); add_next_index_long(return_value, timelib_day_of_year(ts->y, ts->m, ts->d)); add_next_index_long(return_value, ts->dst); } timelib_time_dtor(ts); } /* }}} */ /* {{{ proto array getdate([int timestamp]) Get date/time information */ PHP_FUNCTION(getdate) { long timestamp = (long)time(NULL); timelib_tzinfo *tzi; timelib_time *ts; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &timestamp) == FAILURE) { RETURN_FALSE; } tzi = get_timezone_info(TSRMLS_C); ts = timelib_time_ctor(); ts->tz_info = tzi; ts->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(ts, (timelib_sll) timestamp); array_init(return_value); add_assoc_long(return_value, "seconds", ts->s); add_assoc_long(return_value, "minutes", ts->i); add_assoc_long(return_value, "hours", ts->h); add_assoc_long(return_value, "mday", ts->d); add_assoc_long(return_value, "wday", timelib_day_of_week(ts->y, ts->m, ts->d)); add_assoc_long(return_value, "mon", ts->m); add_assoc_long(return_value, "year", ts->y); add_assoc_long(return_value, "yday", timelib_day_of_year(ts->y, ts->m, ts->d)); add_assoc_string(return_value, "weekday", php_date_full_day_name(ts->y, ts->m, ts->d), 1); add_assoc_string(return_value, "month", mon_full_names[ts->m - 1], 1); add_index_long(return_value, 0, timestamp); timelib_time_dtor(ts); } /* }}} */ #define PHP_DATE_TIMEZONE_GROUP_AFRICA 0x0001 #define PHP_DATE_TIMEZONE_GROUP_AMERICA 0x0002 #define PHP_DATE_TIMEZONE_GROUP_ANTARCTICA 0x0004 #define PHP_DATE_TIMEZONE_GROUP_ARCTIC 0x0008 #define PHP_DATE_TIMEZONE_GROUP_ASIA 0x0010 #define PHP_DATE_TIMEZONE_GROUP_ATLANTIC 0x0020 #define PHP_DATE_TIMEZONE_GROUP_AUSTRALIA 0x0040 #define PHP_DATE_TIMEZONE_GROUP_EUROPE 0x0080 #define PHP_DATE_TIMEZONE_GROUP_INDIAN 0x0100 #define PHP_DATE_TIMEZONE_GROUP_PACIFIC 0x0200 #define PHP_DATE_TIMEZONE_GROUP_UTC 0x0400 #define PHP_DATE_TIMEZONE_GROUP_ALL 0x07FF #define PHP_DATE_TIMEZONE_GROUP_ALL_W_BC 0x0FFF #define PHP_DATE_TIMEZONE_PER_COUNTRY 0x1000 #define PHP_DATE_PERIOD_EXCLUDE_START_DATE 0x0001 /* define an overloaded iterator structure */ typedef struct { zend_object_iterator intern; zval *date_period_zval; zval *current; php_period_obj *object; int current_index; } date_period_it; /* {{{ date_period_it_invalidate_current */ static void date_period_it_invalidate_current(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; if (iterator->current) { zval_ptr_dtor(&iterator->current); iterator->current = NULL; } } /* }}} */ /* {{{ date_period_it_dtor */ static void date_period_it_dtor(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; date_period_it_invalidate_current(iter TSRMLS_CC); zval_ptr_dtor(&iterator->date_period_zval); efree(iterator); } /* }}} */ /* {{{ date_period_it_has_more */ static int date_period_it_has_more(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; php_period_obj *object = iterator->object; timelib_time *it_time = object->current; /* apply modification if it's not the first iteration */ if (!object->include_start_date || iterator->current_index > 0) { it_time->have_relative = 1; it_time->relative = *object->interval; it_time->sse_uptodate = 0; timelib_update_ts(it_time, NULL); timelib_update_from_sse(it_time); } if (object->end) { return object->current->sse < object->end->sse ? SUCCESS : FAILURE; } else { return (iterator->current_index < object->recurrences) ? SUCCESS : FAILURE; } } /* }}} */ /* {{{ date_period_it_current_data */ static void date_period_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; php_period_obj *object = iterator->object; timelib_time *it_time = object->current; php_date_obj *newdateobj; /* Create new object */ MAKE_STD_ZVAL(iterator->current); php_date_instantiate(date_ce_date, iterator->current TSRMLS_CC); newdateobj = (php_date_obj *) zend_object_store_get_object(iterator->current TSRMLS_CC); newdateobj->time = timelib_time_ctor(); *newdateobj->time = *it_time; if (it_time->tz_abbr) { newdateobj->time->tz_abbr = strdup(it_time->tz_abbr); } if (it_time->tz_info) { newdateobj->time->tz_info = it_time->tz_info; } *data = &iterator->current; } /* }}} */ /* {{{ date_period_it_current_key */ static int date_period_it_current_key(zend_object_iterator *iter, char **str_key, uint *str_key_len, ulong *int_key TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; *int_key = iterator->current_index; return HASH_KEY_IS_LONG; } /* }}} */ /* {{{ date_period_it_move_forward */ static void date_period_it_move_forward(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; iterator->current_index++; date_period_it_invalidate_current(iter TSRMLS_CC); } /* }}} */ /* {{{ date_period_it_rewind */ static void date_period_it_rewind(zend_object_iterator *iter TSRMLS_DC) { date_period_it *iterator = (date_period_it *)iter; iterator->current_index = 0; if (iterator->object->current) { timelib_time_dtor(iterator->object->current); } iterator->object->current = timelib_time_clone(iterator->object->start); date_period_it_invalidate_current(iter TSRMLS_CC); } /* }}} */ /* iterator handler table */ zend_object_iterator_funcs date_period_it_funcs = { date_period_it_dtor, date_period_it_has_more, date_period_it_current_data, date_period_it_current_key, date_period_it_move_forward, date_period_it_rewind, date_period_it_invalidate_current }; zend_object_iterator *date_object_period_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) { date_period_it *iterator = emalloc(sizeof(date_period_it)); php_period_obj *dpobj = (php_period_obj *)zend_object_store_get_object(object TSRMLS_CC); if (by_ref) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } Z_ADDREF_P(object); iterator->intern.data = (void*) dpobj; iterator->intern.funcs = &date_period_it_funcs; iterator->date_period_zval = object; iterator->object = dpobj; iterator->current = NULL; return (zend_object_iterator*)iterator; } static void date_register_classes(TSRMLS_D) { zend_class_entry ce_date, ce_timezone, ce_interval, ce_period; INIT_CLASS_ENTRY(ce_date, "DateTime", date_funcs_date); ce_date.create_object = date_object_new_date; date_ce_date = zend_register_internal_class_ex(&ce_date, NULL, NULL TSRMLS_CC); memcpy(&date_object_handlers_date, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); date_object_handlers_date.clone_obj = date_object_clone_date; date_object_handlers_date.compare_objects = date_object_compare_date; date_object_handlers_date.get_properties = date_object_get_properties; #define REGISTER_DATE_CLASS_CONST_STRING(const_name, value) \ zend_declare_class_constant_stringl(date_ce_date, const_name, sizeof(const_name)-1, value, sizeof(value)-1 TSRMLS_CC); REGISTER_DATE_CLASS_CONST_STRING("ATOM", DATE_FORMAT_RFC3339); REGISTER_DATE_CLASS_CONST_STRING("COOKIE", DATE_FORMAT_RFC850); REGISTER_DATE_CLASS_CONST_STRING("ISO8601", DATE_FORMAT_ISO8601); REGISTER_DATE_CLASS_CONST_STRING("RFC822", DATE_FORMAT_RFC822); REGISTER_DATE_CLASS_CONST_STRING("RFC850", DATE_FORMAT_RFC850); REGISTER_DATE_CLASS_CONST_STRING("RFC1036", DATE_FORMAT_RFC1036); REGISTER_DATE_CLASS_CONST_STRING("RFC1123", DATE_FORMAT_RFC1123); REGISTER_DATE_CLASS_CONST_STRING("RFC2822", DATE_FORMAT_RFC2822); REGISTER_DATE_CLASS_CONST_STRING("RFC3339", DATE_FORMAT_RFC3339); REGISTER_DATE_CLASS_CONST_STRING("RSS", DATE_FORMAT_RFC1123); REGISTER_DATE_CLASS_CONST_STRING("W3C", DATE_FORMAT_RFC3339); INIT_CLASS_ENTRY(ce_timezone, "DateTimeZone", date_funcs_timezone); ce_timezone.create_object = date_object_new_timezone; date_ce_timezone = zend_register_internal_class_ex(&ce_timezone, NULL, NULL TSRMLS_CC); memcpy(&date_object_handlers_timezone, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); date_object_handlers_timezone.clone_obj = date_object_clone_timezone; #define REGISTER_TIMEZONE_CLASS_CONST_STRING(const_name, value) \ zend_declare_class_constant_long(date_ce_timezone, const_name, sizeof(const_name)-1, value TSRMLS_CC); REGISTER_TIMEZONE_CLASS_CONST_STRING("AFRICA", PHP_DATE_TIMEZONE_GROUP_AFRICA); REGISTER_TIMEZONE_CLASS_CONST_STRING("AMERICA", PHP_DATE_TIMEZONE_GROUP_AMERICA); REGISTER_TIMEZONE_CLASS_CONST_STRING("ANTARCTICA", PHP_DATE_TIMEZONE_GROUP_ANTARCTICA); REGISTER_TIMEZONE_CLASS_CONST_STRING("ARCTIC", PHP_DATE_TIMEZONE_GROUP_ARCTIC); REGISTER_TIMEZONE_CLASS_CONST_STRING("ASIA", PHP_DATE_TIMEZONE_GROUP_ASIA); REGISTER_TIMEZONE_CLASS_CONST_STRING("ATLANTIC", PHP_DATE_TIMEZONE_GROUP_ATLANTIC); REGISTER_TIMEZONE_CLASS_CONST_STRING("AUSTRALIA", PHP_DATE_TIMEZONE_GROUP_AUSTRALIA); REGISTER_TIMEZONE_CLASS_CONST_STRING("EUROPE", PHP_DATE_TIMEZONE_GROUP_EUROPE); REGISTER_TIMEZONE_CLASS_CONST_STRING("INDIAN", PHP_DATE_TIMEZONE_GROUP_INDIAN); REGISTER_TIMEZONE_CLASS_CONST_STRING("PACIFIC", PHP_DATE_TIMEZONE_GROUP_PACIFIC); REGISTER_TIMEZONE_CLASS_CONST_STRING("UTC", PHP_DATE_TIMEZONE_GROUP_UTC); REGISTER_TIMEZONE_CLASS_CONST_STRING("ALL", PHP_DATE_TIMEZONE_GROUP_ALL); REGISTER_TIMEZONE_CLASS_CONST_STRING("ALL_WITH_BC", PHP_DATE_TIMEZONE_GROUP_ALL_W_BC); REGISTER_TIMEZONE_CLASS_CONST_STRING("PER_COUNTRY", PHP_DATE_TIMEZONE_PER_COUNTRY); INIT_CLASS_ENTRY(ce_interval, "DateInterval", date_funcs_interval); ce_interval.create_object = date_object_new_interval; date_ce_interval = zend_register_internal_class_ex(&ce_interval, NULL, NULL TSRMLS_CC); memcpy(&date_object_handlers_interval, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); date_object_handlers_interval.clone_obj = date_object_clone_interval; date_object_handlers_interval.read_property = date_interval_read_property; date_object_handlers_interval.write_property = date_interval_write_property; date_object_handlers_interval.get_properties = date_object_get_properties_interval; date_object_handlers_interval.get_property_ptr_ptr = NULL; INIT_CLASS_ENTRY(ce_period, "DatePeriod", date_funcs_period); ce_period.create_object = date_object_new_period; date_ce_period = zend_register_internal_class_ex(&ce_period, NULL, NULL TSRMLS_CC); date_ce_period->get_iterator = date_object_period_get_iterator; date_ce_period->iterator_funcs.funcs = &date_period_it_funcs; zend_class_implements(date_ce_period TSRMLS_CC, 1, zend_ce_traversable); memcpy(&date_object_handlers_period, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); date_object_handlers_period.clone_obj = date_object_clone_period; #define REGISTER_PERIOD_CLASS_CONST_STRING(const_name, value) \ zend_declare_class_constant_long(date_ce_period, const_name, sizeof(const_name)-1, value TSRMLS_CC); REGISTER_PERIOD_CLASS_CONST_STRING("EXCLUDE_START_DATE", PHP_DATE_PERIOD_EXCLUDE_START_DATE); } static inline zend_object_value date_object_new_date_ex(zend_class_entry *class_type, php_date_obj **ptr TSRMLS_DC) { php_date_obj *intern; zend_object_value retval; intern = emalloc(sizeof(php_date_obj)); memset(intern, 0, sizeof(php_date_obj)); if (ptr) { *ptr = intern; } zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) date_object_free_storage_date, NULL TSRMLS_CC); retval.handlers = &date_object_handlers_date; return retval; } static zend_object_value date_object_new_date(zend_class_entry *class_type TSRMLS_DC) { return date_object_new_date_ex(class_type, NULL TSRMLS_CC); } static zend_object_value date_object_clone_date(zval *this_ptr TSRMLS_DC) { php_date_obj *new_obj = NULL; php_date_obj *old_obj = (php_date_obj *) zend_object_store_get_object(this_ptr TSRMLS_CC); zend_object_value new_ov = date_object_new_date_ex(old_obj->std.ce, &new_obj TSRMLS_CC); zend_objects_clone_members(&new_obj->std, new_ov, &old_obj->std, Z_OBJ_HANDLE_P(this_ptr) TSRMLS_CC); /* this should probably moved to a new `timelib_time *timelime_time_clone(timelib_time *)` */ new_obj->time = timelib_time_ctor(); *new_obj->time = *old_obj->time; if (old_obj->time->tz_abbr) { new_obj->time->tz_abbr = strdup(old_obj->time->tz_abbr); } if (old_obj->time->tz_info) { new_obj->time->tz_info = old_obj->time->tz_info; } return new_ov; } static int date_object_compare_date(zval *d1, zval *d2 TSRMLS_DC) { if (Z_TYPE_P(d1) == IS_OBJECT && Z_TYPE_P(d2) == IS_OBJECT && instanceof_function(Z_OBJCE_P(d1), date_ce_date TSRMLS_CC) && instanceof_function(Z_OBJCE_P(d2), date_ce_date TSRMLS_CC)) { php_date_obj *o1 = zend_object_store_get_object(d1 TSRMLS_CC); php_date_obj *o2 = zend_object_store_get_object(d2 TSRMLS_CC); if (!o1->time->sse_uptodate) { timelib_update_ts(o1->time, o1->time->tz_info); } if (!o2->time->sse_uptodate) { timelib_update_ts(o2->time, o2->time->tz_info); } return (o1->time->sse == o2->time->sse) ? 0 : ((o1->time->sse < o2->time->sse) ? -1 : 1); } return 1; } static HashTable *date_object_get_properties(zval *object TSRMLS_DC) { HashTable *props; zval *zv; php_date_obj *dateobj; dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); props = zend_std_get_properties(object TSRMLS_CC); if (!dateobj->time || GC_G(gc_active)) { return props; } /* first we add the date and time in ISO format */ MAKE_STD_ZVAL(zv); ZVAL_STRING(zv, date_format("Y-m-d H:i:s", 12, dateobj->time, 1), 0); zend_hash_update(props, "date", 5, &zv, sizeof(zval), NULL); /* then we add the timezone name (or similar) */ if (dateobj->time->is_localtime) { MAKE_STD_ZVAL(zv); ZVAL_LONG(zv, dateobj->time->zone_type); zend_hash_update(props, "timezone_type", 14, &zv, sizeof(zval), NULL); MAKE_STD_ZVAL(zv); switch (dateobj->time->zone_type) { case TIMELIB_ZONETYPE_ID: ZVAL_STRING(zv, dateobj->time->tz_info->name, 1); break; case TIMELIB_ZONETYPE_OFFSET: { char *tmpstr = emalloc(sizeof("UTC+05:00")); timelib_sll utc_offset = dateobj->time->z; snprintf(tmpstr, sizeof("+05:00"), "%c%02d:%02d", utc_offset > 0 ? '-' : '+', abs(utc_offset / 60), abs((utc_offset % 60))); ZVAL_STRING(zv, tmpstr, 0); } break; case TIMELIB_ZONETYPE_ABBR: ZVAL_STRING(zv, dateobj->time->tz_abbr, 1); break; } zend_hash_update(props, "timezone", 9, &zv, sizeof(zval), NULL); } return props; } static inline zend_object_value date_object_new_timezone_ex(zend_class_entry *class_type, php_timezone_obj **ptr TSRMLS_DC) { php_timezone_obj *intern; zend_object_value retval; intern = emalloc(sizeof(php_timezone_obj)); memset(intern, 0, sizeof(php_timezone_obj)); if (ptr) { *ptr = intern; } zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) date_object_free_storage_timezone, NULL TSRMLS_CC); retval.handlers = &date_object_handlers_timezone; return retval; } static zend_object_value date_object_new_timezone(zend_class_entry *class_type TSRMLS_DC) { return date_object_new_timezone_ex(class_type, NULL TSRMLS_CC); } static zend_object_value date_object_clone_timezone(zval *this_ptr TSRMLS_DC) { php_timezone_obj *new_obj = NULL; php_timezone_obj *old_obj = (php_timezone_obj *) zend_object_store_get_object(this_ptr TSRMLS_CC); zend_object_value new_ov = date_object_new_timezone_ex(old_obj->std.ce, &new_obj TSRMLS_CC); zend_objects_clone_members(&new_obj->std, new_ov, &old_obj->std, Z_OBJ_HANDLE_P(this_ptr) TSRMLS_CC); new_obj->type = old_obj->type; new_obj->initialized = 1; switch (new_obj->type) { case TIMELIB_ZONETYPE_ID: new_obj->tzi.tz = old_obj->tzi.tz; break; case TIMELIB_ZONETYPE_OFFSET: new_obj->tzi.utc_offset = old_obj->tzi.utc_offset; break; case TIMELIB_ZONETYPE_ABBR: new_obj->tzi.z.utc_offset = old_obj->tzi.z.utc_offset; new_obj->tzi.z.dst = old_obj->tzi.z.dst; new_obj->tzi.z.abbr = old_obj->tzi.z.abbr; break; } return new_ov; } static inline zend_object_value date_object_new_interval_ex(zend_class_entry *class_type, php_interval_obj **ptr TSRMLS_DC) { php_interval_obj *intern; zend_object_value retval; intern = emalloc(sizeof(php_interval_obj)); memset(intern, 0, sizeof(php_interval_obj)); if (ptr) { *ptr = intern; } zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) date_object_free_storage_interval, NULL TSRMLS_CC); retval.handlers = &date_object_handlers_interval; return retval; } static zend_object_value date_object_new_interval(zend_class_entry *class_type TSRMLS_DC) { return date_object_new_interval_ex(class_type, NULL TSRMLS_CC); } static zend_object_value date_object_clone_interval(zval *this_ptr TSRMLS_DC) { php_interval_obj *new_obj = NULL; php_interval_obj *old_obj = (php_interval_obj *) zend_object_store_get_object(this_ptr TSRMLS_CC); zend_object_value new_ov = date_object_new_interval_ex(old_obj->std.ce, &new_obj TSRMLS_CC); zend_objects_clone_members(&new_obj->std, new_ov, &old_obj->std, Z_OBJ_HANDLE_P(this_ptr) TSRMLS_CC); /** FIX ME ADD CLONE STUFF **/ return new_ov; } static HashTable *date_object_get_properties_interval(zval *object TSRMLS_DC) { HashTable *props; zval *zv; php_interval_obj *intervalobj; intervalobj = (php_interval_obj *) zend_object_store_get_object(object TSRMLS_CC); props = zend_std_get_properties(object TSRMLS_CC); if (!intervalobj->initialized || GC_G(gc_active)) { return props; } #define PHP_DATE_INTERVAL_ADD_PROPERTY(n,f) \ MAKE_STD_ZVAL(zv); \ ZVAL_LONG(zv, intervalobj->diff->f); \ zend_hash_update(props, n, strlen(n) + 1, &zv, sizeof(zval), NULL); PHP_DATE_INTERVAL_ADD_PROPERTY("y", y); PHP_DATE_INTERVAL_ADD_PROPERTY("m", m); PHP_DATE_INTERVAL_ADD_PROPERTY("d", d); PHP_DATE_INTERVAL_ADD_PROPERTY("h", h); PHP_DATE_INTERVAL_ADD_PROPERTY("i", i); PHP_DATE_INTERVAL_ADD_PROPERTY("s", s); PHP_DATE_INTERVAL_ADD_PROPERTY("invert", invert); if (intervalobj->diff->days != -99999) { PHP_DATE_INTERVAL_ADD_PROPERTY("days", days); } else { MAKE_STD_ZVAL(zv); ZVAL_FALSE(zv); zend_hash_update(props, "days", 5, &zv, sizeof(zval), NULL); } return props; } static inline zend_object_value date_object_new_period_ex(zend_class_entry *class_type, php_period_obj **ptr TSRMLS_DC) { php_period_obj *intern; zend_object_value retval; intern = emalloc(sizeof(php_period_obj)); memset(intern, 0, sizeof(php_period_obj)); if (ptr) { *ptr = intern; } zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) date_object_free_storage_period, NULL TSRMLS_CC); retval.handlers = &date_object_handlers_period; return retval; } static zend_object_value date_object_new_period(zend_class_entry *class_type TSRMLS_DC) { return date_object_new_period_ex(class_type, NULL TSRMLS_CC); } static zend_object_value date_object_clone_period(zval *this_ptr TSRMLS_DC) { php_period_obj *new_obj = NULL; php_period_obj *old_obj = (php_period_obj *) zend_object_store_get_object(this_ptr TSRMLS_CC); zend_object_value new_ov = date_object_new_period_ex(old_obj->std.ce, &new_obj TSRMLS_CC); zend_objects_clone_members(&new_obj->std, new_ov, &old_obj->std, Z_OBJ_HANDLE_P(this_ptr) TSRMLS_CC); /** FIX ME ADD CLONE STUFF **/ return new_ov; } static void date_object_free_storage_date(void *object TSRMLS_DC) { php_date_obj *intern = (php_date_obj *)object; if (intern->time) { timelib_time_dtor(intern->time); } zend_object_std_dtor(&intern->std TSRMLS_CC); efree(object); } static void date_object_free_storage_timezone(void *object TSRMLS_DC) { php_timezone_obj *intern = (php_timezone_obj *)object; if (intern->type == TIMELIB_ZONETYPE_ABBR) { free(intern->tzi.z.abbr); } zend_object_std_dtor(&intern->std TSRMLS_CC); efree(object); } static void date_object_free_storage_interval(void *object TSRMLS_DC) { php_interval_obj *intern = (php_interval_obj *)object; timelib_rel_time_dtor(intern->diff); zend_object_std_dtor(&intern->std TSRMLS_CC); efree(object); } static void date_object_free_storage_period(void *object TSRMLS_DC) { php_period_obj *intern = (php_period_obj *)object; if (intern->start) { timelib_time_dtor(intern->start); } if (intern->current) { timelib_time_dtor(intern->current); } if (intern->end) { timelib_time_dtor(intern->end); } timelib_rel_time_dtor(intern->interval); zend_object_std_dtor(&intern->std TSRMLS_CC); efree(object); } /* Advanced Interface */ PHPAPI zval *php_date_instantiate(zend_class_entry *pce, zval *object TSRMLS_DC) { Z_TYPE_P(object) = IS_OBJECT; object_init_ex(object, pce); Z_SET_REFCOUNT_P(object, 1); Z_UNSET_ISREF_P(object); return object; } /* Helper function used to store the latest found warnings and errors while * parsing, from either strtotime or parse_from_format. */ static void update_errors_warnings(timelib_error_container *last_errors TSRMLS_DC) { if (DATEG(last_errors)) { timelib_error_container_dtor(DATEG(last_errors)); DATEG(last_errors) = NULL; } DATEG(last_errors) = last_errors; } PHPAPI int php_date_initialize(php_date_obj *dateobj, /*const*/ char *time_str, int time_str_len, char *format, zval *timezone_object, int ctor TSRMLS_DC) { timelib_time *now; timelib_tzinfo *tzi; timelib_error_container *err = NULL; int type = TIMELIB_ZONETYPE_ID, new_dst; char *new_abbr; timelib_sll new_offset; if (dateobj->time) { timelib_time_dtor(dateobj->time); } if (format) { dateobj->time = timelib_parse_from_format(format, time_str_len ? time_str : "", time_str_len ? time_str_len : 0, &err, DATE_TIMEZONEDB); } else { dateobj->time = timelib_strtotime(time_str_len ? time_str : "now", time_str_len ? time_str_len : sizeof("now") -1, &err, DATE_TIMEZONEDB); } /* update last errors and warnings */ update_errors_warnings(err TSRMLS_CC); if (ctor && err && err->error_count) { /* spit out the first library error message, at least */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse time string (%s) at position %d (%c): %s", time_str, err->error_messages[0].position, err->error_messages[0].character, err->error_messages[0].message); } if (err && err->error_count) { return 0; } if (timezone_object) { php_timezone_obj *tzobj; tzobj = (php_timezone_obj *) zend_object_store_get_object(timezone_object TSRMLS_CC); switch (tzobj->type) { case TIMELIB_ZONETYPE_ID: tzi = tzobj->tzi.tz; break; case TIMELIB_ZONETYPE_OFFSET: new_offset = tzobj->tzi.utc_offset; break; case TIMELIB_ZONETYPE_ABBR: new_offset = tzobj->tzi.z.utc_offset; new_dst = tzobj->tzi.z.dst; new_abbr = strdup(tzobj->tzi.z.abbr); break; } type = tzobj->type; } else if (dateobj->time->tz_info) { tzi = dateobj->time->tz_info; } else { tzi = get_timezone_info(TSRMLS_C); } now = timelib_time_ctor(); now->zone_type = type; switch (type) { case TIMELIB_ZONETYPE_ID: now->tz_info = tzi; break; case TIMELIB_ZONETYPE_OFFSET: now->z = new_offset; break; case TIMELIB_ZONETYPE_ABBR: now->z = new_offset; now->dst = new_dst; now->tz_abbr = new_abbr; break; } timelib_unixtime2local(now, (timelib_sll) time(NULL)); timelib_fill_holes(dateobj->time, now, TIMELIB_NO_CLONE); timelib_update_ts(dateobj->time, tzi); dateobj->time->have_relative = 0; timelib_time_dtor(now); return 1; } /* {{{ proto DateTime date_create([string time[, DateTimeZone object]]) Returns new DateTime object */ PHP_FUNCTION(date_create) { zval *timezone_object = NULL; char *time_str = NULL; int time_str_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sO!", &time_str, &time_str_len, &timezone_object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } php_date_instantiate(date_ce_date, return_value TSRMLS_CC); if (!php_date_initialize(zend_object_store_get_object(return_value TSRMLS_CC), time_str, time_str_len, NULL, timezone_object, 0 TSRMLS_CC)) { RETURN_FALSE; } } /* }}} */ /* {{{ proto DateTime date_create_from_format(string format, string time[, DateTimeZone object]) Returns new DateTime object formatted according to the specified format */ PHP_FUNCTION(date_create_from_format) { zval *timezone_object = NULL; char *time_str = NULL, *format_str = NULL; int time_str_len = 0, format_str_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|O", &format_str, &format_str_len, &time_str, &time_str_len, &timezone_object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } php_date_instantiate(date_ce_date, return_value TSRMLS_CC); if (!php_date_initialize(zend_object_store_get_object(return_value TSRMLS_CC), time_str, time_str_len, format_str, timezone_object, 0 TSRMLS_CC)) { RETURN_FALSE; } } /* }}} */ /* {{{ proto DateTime::__construct([string time[, DateTimeZone object]]) Creates new DateTime object */ PHP_METHOD(DateTime, __construct) { zval *timezone_object = NULL; char *time_str = NULL; int time_str_len = 0; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sO!", &time_str, &time_str_len, &timezone_object, date_ce_timezone)) { php_date_initialize(zend_object_store_get_object(getThis() TSRMLS_CC), time_str, time_str_len, NULL, timezone_object, 1 TSRMLS_CC); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ static int php_date_initialize_from_hash(zval **return_value, php_date_obj **dateobj, HashTable *myht TSRMLS_DC) { zval **z_date = NULL; zval **z_timezone = NULL; zval **z_timezone_type = NULL; zval *tmp_obj = NULL; timelib_tzinfo *tzi; php_timezone_obj *tzobj; if (zend_hash_find(myht, "date", 5, (void**) &z_date) == SUCCESS) { convert_to_string(*z_date); if (zend_hash_find(myht, "timezone_type", 14, (void**) &z_timezone_type) == SUCCESS) { convert_to_long(*z_timezone_type); if (zend_hash_find(myht, "timezone", 9, (void**) &z_timezone) == SUCCESS) { convert_to_string(*z_timezone); switch (Z_LVAL_PP(z_timezone_type)) { case TIMELIB_ZONETYPE_OFFSET: case TIMELIB_ZONETYPE_ABBR: { char *tmp = emalloc(Z_STRLEN_PP(z_date) + Z_STRLEN_PP(z_timezone) + 2); snprintf(tmp, Z_STRLEN_PP(z_date) + Z_STRLEN_PP(z_timezone) + 2, "%s %s", Z_STRVAL_PP(z_date), Z_STRVAL_PP(z_timezone)); php_date_initialize(*dateobj, tmp, Z_STRLEN_PP(z_date) + Z_STRLEN_PP(z_timezone) + 1, NULL, NULL, 0 TSRMLS_CC); efree(tmp); return 1; } case TIMELIB_ZONETYPE_ID: convert_to_string(*z_timezone); tzi = php_date_parse_tzfile(Z_STRVAL_PP(z_timezone), DATE_TIMEZONEDB TSRMLS_CC); ALLOC_INIT_ZVAL(tmp_obj); tzobj = zend_object_store_get_object(php_date_instantiate(date_ce_timezone, tmp_obj TSRMLS_CC) TSRMLS_CC); tzobj->type = TIMELIB_ZONETYPE_ID; tzobj->tzi.tz = tzi; tzobj->initialized = 1; php_date_initialize(*dateobj, Z_STRVAL_PP(z_date), Z_STRLEN_PP(z_date), NULL, tmp_obj, 0 TSRMLS_CC); zval_ptr_dtor(&tmp_obj); return 1; } } } } return 0; } /* {{{ proto DateTime::__set_state() */ PHP_METHOD(DateTime, __set_state) { php_date_obj *dateobj; zval *array; HashTable *myht; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) { RETURN_FALSE; } myht = HASH_OF(array); php_date_instantiate(date_ce_date, return_value TSRMLS_CC); dateobj = (php_date_obj *) zend_object_store_get_object(return_value TSRMLS_CC); php_date_initialize_from_hash(&return_value, &dateobj, myht TSRMLS_CC); } /* }}} */ /* {{{ proto DateTime::__wakeup() */ PHP_METHOD(DateTime, __wakeup) { zval *object = getThis(); php_date_obj *dateobj; HashTable *myht; dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); myht = Z_OBJPROP_P(object); php_date_initialize_from_hash(&return_value, &dateobj, myht TSRMLS_CC); } /* }}} */ /* Helper function used to add an associative array of warnings and errors to a zval */ static void zval_from_error_container(zval *z, timelib_error_container *error) { int i; zval *element; add_assoc_long(z, "warning_count", error->warning_count); MAKE_STD_ZVAL(element); array_init(element); for (i = 0; i < error->warning_count; i++) { add_index_string(element, error->warning_messages[i].position, error->warning_messages[i].message, 1); } add_assoc_zval(z, "warnings", element); add_assoc_long(z, "error_count", error->error_count); MAKE_STD_ZVAL(element); array_init(element); for (i = 0; i < error->error_count; i++) { add_index_string(element, error->error_messages[i].position, error->error_messages[i].message, 1); } add_assoc_zval(z, "errors", element); } /* {{{ proto array date_get_last_errors() Returns the warnings and errors found while parsing a date/time string. */ PHP_FUNCTION(date_get_last_errors) { if (DATEG(last_errors)) { array_init(return_value); zval_from_error_container(return_value, DATEG(last_errors)); } else { RETURN_FALSE; } } /* }}} */ void php_date_do_return_parsed_time(INTERNAL_FUNCTION_PARAMETERS, timelib_time *parsed_time, struct timelib_error_container *error) { zval *element; array_init(return_value); #define PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(name, elem) \ if (parsed_time->elem == -99999) { \ add_assoc_bool(return_value, #name, 0); \ } else { \ add_assoc_long(return_value, #name, parsed_time->elem); \ } PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(year, y); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(month, m); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(day, d); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(hour, h); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(minute, i); PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(second, s); if (parsed_time->f == -99999) { add_assoc_bool(return_value, "fraction", 0); } else { add_assoc_double(return_value, "fraction", parsed_time->f); } zval_from_error_container(return_value, error); timelib_error_container_dtor(error); add_assoc_bool(return_value, "is_localtime", parsed_time->is_localtime); if (parsed_time->is_localtime) { PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(zone_type, zone_type); switch (parsed_time->zone_type) { case TIMELIB_ZONETYPE_OFFSET: PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(zone, z); add_assoc_bool(return_value, "is_dst", parsed_time->dst); break; case TIMELIB_ZONETYPE_ID: if (parsed_time->tz_abbr) { add_assoc_string(return_value, "tz_abbr", parsed_time->tz_abbr, 1); } if (parsed_time->tz_info) { add_assoc_string(return_value, "tz_id", parsed_time->tz_info->name, 1); } break; case TIMELIB_ZONETYPE_ABBR: PHP_DATE_PARSE_DATE_SET_TIME_ELEMENT(zone, z); add_assoc_bool(return_value, "is_dst", parsed_time->dst); add_assoc_string(return_value, "tz_abbr", parsed_time->tz_abbr, 1); break; } } if (parsed_time->have_relative) { MAKE_STD_ZVAL(element); array_init(element); add_assoc_long(element, "year", parsed_time->relative.y); add_assoc_long(element, "month", parsed_time->relative.m); add_assoc_long(element, "day", parsed_time->relative.d); add_assoc_long(element, "hour", parsed_time->relative.h); add_assoc_long(element, "minute", parsed_time->relative.i); add_assoc_long(element, "second", parsed_time->relative.s); if (parsed_time->relative.have_weekday_relative) { add_assoc_long(element, "weekday", parsed_time->relative.weekday); } if (parsed_time->relative.have_special_relative && (parsed_time->relative.special.type == TIMELIB_SPECIAL_WEEKDAY)) { add_assoc_long(element, "weekdays", parsed_time->relative.special.amount); } if (parsed_time->relative.first_last_day_of) { add_assoc_bool(element, parsed_time->relative.first_last_day_of == 1 ? "first_day_of_month" : "last_day_of_month", 1); } add_assoc_zval(return_value, "relative", element); } timelib_time_dtor(parsed_time); } /* {{{ proto array date_parse(string date) Returns associative array with detailed info about given date */ PHP_FUNCTION(date_parse) { char *date; int date_len; struct timelib_error_container *error; timelib_time *parsed_time; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &date, &date_len) == FAILURE) { RETURN_FALSE; } parsed_time = timelib_strtotime(date, date_len, &error, DATE_TIMEZONEDB); php_date_do_return_parsed_time(INTERNAL_FUNCTION_PARAM_PASSTHRU, parsed_time, error); } /* }}} */ /* {{{ proto array date_parse_from_format(string format, string date) Returns associative array with detailed info about given date */ PHP_FUNCTION(date_parse_from_format) { char *date, *format; int date_len, format_len; struct timelib_error_container *error; timelib_time *parsed_time; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &format, &format_len, &date, &date_len) == FAILURE) { RETURN_FALSE; } parsed_time = timelib_parse_from_format(format, date, date_len, &error, DATE_TIMEZONEDB); php_date_do_return_parsed_time(INTERNAL_FUNCTION_PARAM_PASSTHRU, parsed_time, error); } /* }}} */ /* {{{ proto string date_format(DateTime object, string format) Returns date formatted according to given format */ PHP_FUNCTION(date_format) { zval *object; php_date_obj *dateobj; char *format; int format_len; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, date_ce_date, &format, &format_len) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); RETURN_STRING(date_format(format, format_len, dateobj->time, dateobj->time->is_localtime), 0); } /* }}} */ /* {{{ proto DateTime date_modify(DateTime object, string modify) Alters the timestamp. */ PHP_FUNCTION(date_modify) { zval *object; php_date_obj *dateobj; char *modify; int modify_len; timelib_time *tmp_time; timelib_error_container *err = NULL; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, date_ce_date, &modify, &modify_len) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); tmp_time = timelib_strtotime(modify, modify_len, &err, DATE_TIMEZONEDB); /* update last errors and warnings */ update_errors_warnings(err TSRMLS_CC); if (err && err->error_count) { /* spit out the first library error message, at least */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse time string (%s) at position %d (%c): %s", modify, err->error_messages[0].position, err->error_messages[0].character, err->error_messages[0].message); timelib_time_dtor(tmp_time); RETURN_FALSE; } memcpy(&dateobj->time->relative, &tmp_time->relative, sizeof(struct timelib_rel_time)); dateobj->time->have_relative = tmp_time->have_relative; dateobj->time->sse_uptodate = 0; if (tmp_time->y != -99999) { dateobj->time->y = tmp_time->y; } if (tmp_time->m != -99999) { dateobj->time->m = tmp_time->m; } if (tmp_time->d != -99999) { dateobj->time->d = tmp_time->d; } if (tmp_time->h != -99999) { dateobj->time->h = tmp_time->h; if (tmp_time->i != -99999) { dateobj->time->i = tmp_time->i; if (tmp_time->s != -99999) { dateobj->time->s = tmp_time->s; } else { dateobj->time->s = 0; } } else { dateobj->time->i = 0; dateobj->time->s = 0; } } timelib_time_dtor(tmp_time); timelib_update_ts(dateobj->time, NULL); timelib_update_from_sse(dateobj->time); dateobj->time->have_relative = 0; RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_add(DateTime object, DateInterval interval) Adds an interval to the current date in object. */ PHP_FUNCTION(date_add) { zval *object, *interval; php_date_obj *dateobj; php_interval_obj *intobj; int bias = 1; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &object, date_ce_date, &interval, date_ce_interval) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); intobj = (php_interval_obj *) zend_object_store_get_object(interval TSRMLS_CC); DATE_CHECK_INITIALIZED(intobj->initialized, DateInterval); if (intobj->diff->have_weekday_relative || intobj->diff->have_special_relative) { memcpy(&dateobj->time->relative, intobj->diff, sizeof(struct timelib_rel_time)); } else { if (intobj->diff->invert) { bias = -1; } dateobj->time->relative.y = intobj->diff->y * bias; dateobj->time->relative.m = intobj->diff->m * bias; dateobj->time->relative.d = intobj->diff->d * bias; dateobj->time->relative.h = intobj->diff->h * bias; dateobj->time->relative.i = intobj->diff->i * bias; dateobj->time->relative.s = intobj->diff->s * bias; dateobj->time->relative.weekday = 0; dateobj->time->relative.have_weekday_relative = 0; } dateobj->time->have_relative = 1; dateobj->time->sse_uptodate = 0; timelib_update_ts(dateobj->time, NULL); timelib_update_from_sse(dateobj->time); dateobj->time->have_relative = 0; RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_sub(DateTime object, DateInterval interval) Subtracts an interval to the current date in object. */ PHP_FUNCTION(date_sub) { zval *object, *interval; php_date_obj *dateobj; php_interval_obj *intobj; int bias = 1; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &object, date_ce_date, &interval, date_ce_interval) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); intobj = (php_interval_obj *) zend_object_store_get_object(interval TSRMLS_CC); DATE_CHECK_INITIALIZED(intobj->initialized, DateInterval); if (intobj->diff->have_special_relative) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Only non-special relative time specifications are supported for subtraction"); return; } if (intobj->diff->invert) { bias = -1; } dateobj->time->relative.y = 0 - (intobj->diff->y * bias); dateobj->time->relative.m = 0 - (intobj->diff->m * bias); dateobj->time->relative.d = 0 - (intobj->diff->d * bias); dateobj->time->relative.h = 0 - (intobj->diff->h * bias); dateobj->time->relative.i = 0 - (intobj->diff->i * bias); dateobj->time->relative.s = 0 - (intobj->diff->s * bias); dateobj->time->have_relative = 1; dateobj->time->relative.weekday = 0; dateobj->time->relative.have_weekday_relative = 0; dateobj->time->sse_uptodate = 0; timelib_update_ts(dateobj->time, NULL); timelib_update_from_sse(dateobj->time); dateobj->time->have_relative = 0; RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTimeZone date_timezone_get(DateTime object) Return new DateTimeZone object relative to give DateTime */ PHP_FUNCTION(date_timezone_get) { zval *object; php_date_obj *dateobj; php_timezone_obj *tzobj; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_date) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); if (dateobj->time->is_localtime/* && dateobj->time->tz_info*/) { php_date_instantiate(date_ce_timezone, return_value TSRMLS_CC); tzobj = (php_timezone_obj *) zend_object_store_get_object(return_value TSRMLS_CC); tzobj->initialized = 1; tzobj->type = dateobj->time->zone_type; switch (dateobj->time->zone_type) { case TIMELIB_ZONETYPE_ID: tzobj->tzi.tz = dateobj->time->tz_info; break; case TIMELIB_ZONETYPE_OFFSET: tzobj->tzi.utc_offset = dateobj->time->z; break; case TIMELIB_ZONETYPE_ABBR: tzobj->tzi.z.utc_offset = dateobj->time->z; tzobj->tzi.z.dst = dateobj->time->dst; tzobj->tzi.z.abbr = strdup(dateobj->time->tz_abbr); break; } } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto DateTime date_timezone_set(DateTime object, DateTimeZone object) Sets the timezone for the DateTime object. */ PHP_FUNCTION(date_timezone_set) { zval *object; zval *timezone_object; php_date_obj *dateobj; php_timezone_obj *tzobj; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &object, date_ce_date, &timezone_object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); tzobj = (php_timezone_obj *) zend_object_store_get_object(timezone_object TSRMLS_CC); if (tzobj->type != TIMELIB_ZONETYPE_ID) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can only do this for zones with ID for now"); return; } timelib_set_timezone(dateobj->time, tzobj->tzi.tz); timelib_unixtime2local(dateobj->time, dateobj->time->sse); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto long date_offset_get(DateTime object) Returns the DST offset. */ PHP_FUNCTION(date_offset_get) { zval *object; php_date_obj *dateobj; timelib_time_offset *offset; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_date) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); if (dateobj->time->is_localtime/* && dateobj->time->tz_info*/) { switch (dateobj->time->zone_type) { case TIMELIB_ZONETYPE_ID: offset = timelib_get_time_zone_info(dateobj->time->sse, dateobj->time->tz_info); RETVAL_LONG(offset->offset); timelib_time_offset_dtor(offset); break; case TIMELIB_ZONETYPE_OFFSET: RETVAL_LONG(dateobj->time->z * -60); break; case TIMELIB_ZONETYPE_ABBR: RETVAL_LONG((dateobj->time->z - (60 * dateobj->time->dst)) * -60); break; } return; } else { RETURN_LONG(0); } } /* }}} */ /* {{{ proto DateTime date_time_set(DateTime object, long hour, long minute[, long second]) Sets the time. */ PHP_FUNCTION(date_time_set) { zval *object; php_date_obj *dateobj; long h, i, s = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oll|l", &object, date_ce_date, &h, &i, &s) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); dateobj->time->h = h; dateobj->time->i = i; dateobj->time->s = s; timelib_update_ts(dateobj->time, NULL); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_date_set(DateTime object, long year, long month, long day) Sets the date. */ PHP_FUNCTION(date_date_set) { zval *object; php_date_obj *dateobj; long y, m, d; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Olll", &object, date_ce_date, &y, &m, &d) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); dateobj->time->y = y; dateobj->time->m = m; dateobj->time->d = d; timelib_update_ts(dateobj->time, NULL); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_isodate_set(DateTime object, long year, long week[, long day]) Sets the ISO date. */ PHP_FUNCTION(date_isodate_set) { zval *object; php_date_obj *dateobj; long y, w, d = 1; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Oll|l", &object, date_ce_date, &y, &w, &d) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); dateobj->time->y = y; dateobj->time->m = 1; dateobj->time->d = 1; dateobj->time->relative.d = timelib_daynr_from_weeknr(y, w, d); dateobj->time->have_relative = 1; timelib_update_ts(dateobj->time, NULL); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto DateTime date_timestamp_set(DateTime object, long unixTimestamp) Sets the date and time based on an Unix timestamp. */ PHP_FUNCTION(date_timestamp_set) { zval *object; php_date_obj *dateobj; long timestamp; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Ol", &object, date_ce_date, &timestamp) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); timelib_unixtime2local(dateobj->time, (timelib_sll)timestamp); timelib_update_ts(dateobj->time, NULL); RETURN_ZVAL(object, 1, 0); } /* }}} */ /* {{{ proto long date_timestamp_get(DateTime object) Gets the Unix timestamp. */ PHP_FUNCTION(date_timestamp_get) { zval *object; php_date_obj *dateobj; long timestamp; int error; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_date) == FAILURE) { RETURN_FALSE; } dateobj = (php_date_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); timelib_update_ts(dateobj->time, NULL); timestamp = timelib_date_to_int(dateobj->time, &error); if (error) { RETURN_FALSE; } else { RETVAL_LONG(timestamp); } } /* }}} */ /* {{{ proto DateInterval date_diff(DateTime object [, bool absolute]) Returns the difference between two DateTime objects. */ PHP_FUNCTION(date_diff) { zval *object1, *object2; php_date_obj *dateobj1, *dateobj2; php_interval_obj *interval; long absolute = 0; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO|l", &object1, date_ce_date, &object2, date_ce_date, &absolute) == FAILURE) { RETURN_FALSE; } dateobj1 = (php_date_obj *) zend_object_store_get_object(object1 TSRMLS_CC); dateobj2 = (php_date_obj *) zend_object_store_get_object(object2 TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj1->time, DateTime); DATE_CHECK_INITIALIZED(dateobj2->time, DateTime); timelib_update_ts(dateobj1->time, NULL); timelib_update_ts(dateobj2->time, NULL); php_date_instantiate(date_ce_interval, return_value TSRMLS_CC); interval = zend_object_store_get_object(return_value TSRMLS_CC); interval->diff = timelib_diff(dateobj1->time, dateobj2->time); if (absolute) { interval->diff->invert = 0; } interval->initialized = 1; } /* }}} */ static int timezone_initialize(timelib_tzinfo **tzi, /*const*/ char *tz TSRMLS_DC) { char *tzid; *tzi = NULL; if ((tzid = timelib_timezone_id_from_abbr(tz, -1, 0))) { *tzi = php_date_parse_tzfile(tzid, DATE_TIMEZONEDB TSRMLS_CC); } else { *tzi = php_date_parse_tzfile(tz, DATE_TIMEZONEDB TSRMLS_CC); } if (*tzi) { return SUCCESS; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown or bad timezone (%s)", tz); return FAILURE; } } /* {{{ proto DateTimeZone timezone_open(string timezone) Returns new DateTimeZone object */ PHP_FUNCTION(timezone_open) { char *tz; int tz_len; timelib_tzinfo *tzi = NULL; php_timezone_obj *tzobj; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &tz, &tz_len) == FAILURE) { RETURN_FALSE; } if (SUCCESS != timezone_initialize(&tzi, tz TSRMLS_CC)) { RETURN_FALSE; } tzobj = zend_object_store_get_object(php_date_instantiate(date_ce_timezone, return_value TSRMLS_CC) TSRMLS_CC); tzobj->type = TIMELIB_ZONETYPE_ID; tzobj->tzi.tz = tzi; tzobj->initialized = 1; } /* }}} */ /* {{{ proto DateTimeZone::__construct(string timezone) Creates new DateTimeZone object. */ PHP_METHOD(DateTimeZone, __construct) { char *tz; int tz_len; timelib_tzinfo *tzi = NULL; php_timezone_obj *tzobj; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &tz, &tz_len)) { if (SUCCESS == timezone_initialize(&tzi, tz TSRMLS_CC)) { tzobj = zend_object_store_get_object(getThis() TSRMLS_CC); tzobj->type = TIMELIB_ZONETYPE_ID; tzobj->tzi.tz = tzi; tzobj->initialized = 1; } else { ZVAL_NULL(getThis()); } } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto string timezone_name_get(DateTimeZone object) Returns the name of the timezone. */ PHP_FUNCTION(timezone_name_get) { zval *object; php_timezone_obj *tzobj; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } tzobj = (php_timezone_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(tzobj->initialized, DateTimeZone); switch (tzobj->type) { case TIMELIB_ZONETYPE_ID: RETURN_STRING(tzobj->tzi.tz->name, 1); break; case TIMELIB_ZONETYPE_OFFSET: { char *tmpstr = emalloc(sizeof("UTC+05:00")); timelib_sll utc_offset = tzobj->tzi.utc_offset; snprintf(tmpstr, sizeof("+05:00"), "%c%02d:%02d", utc_offset > 0 ? '-' : '+', abs(utc_offset / 60), abs((utc_offset % 60))); RETURN_STRING(tmpstr, 0); } break; case TIMELIB_ZONETYPE_ABBR: RETURN_STRING(tzobj->tzi.z.abbr, 1); break; } } /* }}} */ /* {{{ proto string timezone_name_from_abbr(string abbr[, long gmtOffset[, long isdst]]) Returns the timezone name from abbrevation */ PHP_FUNCTION(timezone_name_from_abbr) { char *abbr; char *tzid; int abbr_len; long gmtoffset = -1; long isdst = -1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ll", &abbr, &abbr_len, &gmtoffset, &isdst) == FAILURE) { RETURN_FALSE; } tzid = timelib_timezone_id_from_abbr(abbr, gmtoffset, isdst); if (tzid) { RETURN_STRING(tzid, 1); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto long timezone_offset_get(DateTimeZone object, DateTime object) Returns the timezone offset. */ PHP_FUNCTION(timezone_offset_get) { zval *object, *dateobject; php_timezone_obj *tzobj; php_date_obj *dateobj; timelib_time_offset *offset; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "OO", &object, date_ce_timezone, &dateobject, date_ce_date) == FAILURE) { RETURN_FALSE; } tzobj = (php_timezone_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(tzobj->initialized, DateTimeZone); dateobj = (php_date_obj *) zend_object_store_get_object(dateobject TSRMLS_CC); DATE_CHECK_INITIALIZED(dateobj->time, DateTime); switch (tzobj->type) { case TIMELIB_ZONETYPE_ID: offset = timelib_get_time_zone_info(dateobj->time->sse, tzobj->tzi.tz); RETVAL_LONG(offset->offset); timelib_time_offset_dtor(offset); break; case TIMELIB_ZONETYPE_OFFSET: RETURN_LONG(tzobj->tzi.utc_offset * -60); break; case TIMELIB_ZONETYPE_ABBR: RETURN_LONG((tzobj->tzi.z.utc_offset - (tzobj->tzi.z.dst*60)) * -60); break; } } /* }}} */ /* {{{ proto array timezone_transitions_get(DateTimeZone object [, long timestamp_begin [, long timestamp_end ]]) Returns numerically indexed array containing associative array for all transitions in the specified range for the timezone. */ PHP_FUNCTION(timezone_transitions_get) { zval *object, *element; php_timezone_obj *tzobj; unsigned int i, begin = 0, found; long timestamp_begin = LONG_MIN, timestamp_end = LONG_MAX; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|ll", &object, date_ce_timezone, &timestamp_begin, &timestamp_end) == FAILURE) { RETURN_FALSE; } tzobj = (php_timezone_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(tzobj->initialized, DateTimeZone); if (tzobj->type != TIMELIB_ZONETYPE_ID) { RETURN_FALSE; } #define add_nominal() \ MAKE_STD_ZVAL(element); \ array_init(element); \ add_assoc_long(element, "ts", timestamp_begin); \ add_assoc_string(element, "time", php_format_date(DATE_FORMAT_ISO8601, 13, timestamp_begin, 0 TSRMLS_CC), 0); \ add_assoc_long(element, "offset", tzobj->tzi.tz->type[0].offset); \ add_assoc_bool(element, "isdst", tzobj->tzi.tz->type[0].isdst); \ add_assoc_string(element, "abbr", &tzobj->tzi.tz->timezone_abbr[tzobj->tzi.tz->type[0].abbr_idx], 1); \ add_next_index_zval(return_value, element); #define add(i,ts) \ MAKE_STD_ZVAL(element); \ array_init(element); \ add_assoc_long(element, "ts", ts); \ add_assoc_string(element, "time", php_format_date(DATE_FORMAT_ISO8601, 13, ts, 0 TSRMLS_CC), 0); \ add_assoc_long(element, "offset", tzobj->tzi.tz->type[tzobj->tzi.tz->trans_idx[i]].offset); \ add_assoc_bool(element, "isdst", tzobj->tzi.tz->type[tzobj->tzi.tz->trans_idx[i]].isdst); \ add_assoc_string(element, "abbr", &tzobj->tzi.tz->timezone_abbr[tzobj->tzi.tz->type[tzobj->tzi.tz->trans_idx[i]].abbr_idx], 1); \ add_next_index_zval(return_value, element); #define add_last() add(tzobj->tzi.tz->timecnt - 1, timestamp_begin) array_init(return_value); if (timestamp_begin == LONG_MIN) { add_nominal(); begin = 0; found = 1; } else { begin = 0; found = 0; if (tzobj->tzi.tz->timecnt > 0) { do { if (tzobj->tzi.tz->trans[begin] > timestamp_begin) { if (begin > 0) { add(begin - 1, timestamp_begin); } else { add_nominal(); } found = 1; break; } begin++; } while (begin < tzobj->tzi.tz->timecnt); } } if (!found) { if (tzobj->tzi.tz->timecnt > 0) { add_last(); } else { add_nominal(); } } else { for (i = begin; i < tzobj->tzi.tz->timecnt; ++i) { if (tzobj->tzi.tz->trans[i] < timestamp_end) { add(i, tzobj->tzi.tz->trans[i]); } } } } /* }}} */ /* {{{ proto array timezone_location_get() Returns location information for a timezone, including country code, latitude/longitude and comments */ PHP_FUNCTION(timezone_location_get) { zval *object; php_timezone_obj *tzobj; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &object, date_ce_timezone) == FAILURE) { RETURN_FALSE; } tzobj = (php_timezone_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(tzobj->initialized, DateTimeZone); if (tzobj->type != TIMELIB_ZONETYPE_ID) { RETURN_FALSE; } array_init(return_value); add_assoc_string(return_value, "country_code", tzobj->tzi.tz->location.country_code, 1); add_assoc_double(return_value, "latitude", tzobj->tzi.tz->location.latitude); add_assoc_double(return_value, "longitude", tzobj->tzi.tz->location.longitude); add_assoc_string(return_value, "comments", tzobj->tzi.tz->location.comments, 1); } /* }}} */ static int date_interval_initialize(timelib_rel_time **rt, /*const*/ char *format, int format_length TSRMLS_DC) { timelib_time *b = NULL, *e = NULL; timelib_rel_time *p = NULL; int r = 0; int retval = 0; struct timelib_error_container *errors; timelib_strtointerval(format, format_length, &b, &e, &p, &r, &errors); if (errors->error_count > 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown or bad format (%s)", format); retval = FAILURE; } else { if(p) { *rt = p; retval = SUCCESS; } else { if(b && e) { timelib_update_ts(b, NULL); timelib_update_ts(e, NULL); *rt = timelib_diff(b, e); retval = SUCCESS; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse interval (%s)", format); retval = FAILURE; } } } timelib_error_container_dtor(errors); return retval; } /* {{{ date_interval_read_property */ zval *date_interval_read_property(zval *object, zval *member, int type, const zend_literal *key TSRMLS_DC) { php_interval_obj *obj; zval *retval; zval tmp_member; timelib_sll value = -1; if (member->type != IS_STRING) { tmp_member = *member; zval_copy_ctor(&tmp_member); convert_to_string(&tmp_member); member = &tmp_member; } obj = (php_interval_obj *)zend_objects_get_address(object TSRMLS_CC); #define GET_VALUE_FROM_STRUCT(n,m) \ if (strcmp(Z_STRVAL_P(member), m) == 0) { \ value = obj->diff->n; \ break; \ } do { GET_VALUE_FROM_STRUCT(y, "y"); GET_VALUE_FROM_STRUCT(m, "m"); GET_VALUE_FROM_STRUCT(d, "d"); GET_VALUE_FROM_STRUCT(h, "h"); GET_VALUE_FROM_STRUCT(i, "i"); GET_VALUE_FROM_STRUCT(s, "s"); GET_VALUE_FROM_STRUCT(invert, "invert"); GET_VALUE_FROM_STRUCT(days, "days"); /* didn't find any */ retval = (zend_get_std_object_handlers())->read_property(object, member, type, key TSRMLS_CC); if (member == &tmp_member) { zval_dtor(member); } return retval; } while(0); ALLOC_INIT_ZVAL(retval); Z_SET_REFCOUNT_P(retval, 0); ZVAL_LONG(retval, value); if (member == &tmp_member) { zval_dtor(member); } return retval; } /* }}} */ /* {{{ date_interval_write_property */ void date_interval_write_property(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC) { php_interval_obj *obj; zval tmp_member, tmp_value; if (member->type != IS_STRING) { tmp_member = *member; zval_copy_ctor(&tmp_member); convert_to_string(&tmp_member); member = &tmp_member; } obj = (php_interval_obj *)zend_objects_get_address(object TSRMLS_CC); #define SET_VALUE_FROM_STRUCT(n,m) \ if (strcmp(Z_STRVAL_P(member), m) == 0) { \ if (value->type != IS_LONG) { \ tmp_value = *value; \ zval_copy_ctor(&tmp_value); \ convert_to_long(&tmp_value); \ value = &tmp_value; \ } \ obj->diff->n = Z_LVAL_P(value); \ if (value == &tmp_value) { \ zval_dtor(value); \ } \ break; \ } do { SET_VALUE_FROM_STRUCT(y, "y"); SET_VALUE_FROM_STRUCT(m, "m"); SET_VALUE_FROM_STRUCT(d, "d"); SET_VALUE_FROM_STRUCT(h, "h"); SET_VALUE_FROM_STRUCT(i, "i"); SET_VALUE_FROM_STRUCT(s, "s"); SET_VALUE_FROM_STRUCT(invert, "invert"); /* didn't find any */ (zend_get_std_object_handlers())->write_property(object, member, value, key TSRMLS_CC); } while(0); if (member == &tmp_member) { zval_dtor(member); } } /* }}} */ /* {{{ proto DateInterval::__construct([string interval_spec]) Creates new DateInterval object. */ PHP_METHOD(DateInterval, __construct) { char *interval_string = NULL; int interval_string_length; php_interval_obj *diobj; timelib_rel_time *reltime; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &interval_string, &interval_string_length) == SUCCESS) { if (date_interval_initialize(&reltime, interval_string, interval_string_length TSRMLS_CC) == SUCCESS) { diobj = zend_object_store_get_object(getThis() TSRMLS_CC); diobj->diff = reltime; diobj->initialized = 1; } else { ZVAL_NULL(getThis()); } } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto DateInterval date_interval_create_from_date_string(string time) Uses the normal date parsers and sets up a DateInterval from the relative parts of the parsed string */ PHP_FUNCTION(date_interval_create_from_date_string) { char *time_str = NULL; int time_str_len = 0; timelib_time *time; timelib_error_container *err = NULL; php_interval_obj *diobj; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &time_str, &time_str_len) == FAILURE) { RETURN_FALSE; } php_date_instantiate(date_ce_interval, return_value TSRMLS_CC); time = timelib_strtotime(time_str, time_str_len, &err, DATE_TIMEZONEDB); diobj = (php_interval_obj *) zend_object_store_get_object(return_value TSRMLS_CC); diobj->diff = timelib_rel_time_clone(&time->relative); diobj->initialized = 1; timelib_time_dtor(time); timelib_error_container_dtor(err); } /* }}} */ /* {{{ date_interval_format - */ static char *date_interval_format(char *format, int format_len, timelib_rel_time *t) { smart_str string = {0}; int i, length, have_format_spec = 0; char buffer[33]; if (!format_len) { return estrdup(""); } for (i = 0; i < format_len; i++) { if (have_format_spec) { switch (format[i]) { case 'Y': length = slprintf(buffer, 32, "%02d", (int) t->y); break; case 'y': length = slprintf(buffer, 32, "%d", (int) t->y); break; case 'M': length = slprintf(buffer, 32, "%02d", (int) t->m); break; case 'm': length = slprintf(buffer, 32, "%d", (int) t->m); break; case 'D': length = slprintf(buffer, 32, "%02d", (int) t->d); break; case 'd': length = slprintf(buffer, 32, "%d", (int) t->d); break; case 'H': length = slprintf(buffer, 32, "%02d", (int) t->h); break; case 'h': length = slprintf(buffer, 32, "%d", (int) t->h); break; case 'I': length = slprintf(buffer, 32, "%02d", (int) t->i); break; case 'i': length = slprintf(buffer, 32, "%d", (int) t->i); break; case 'S': length = slprintf(buffer, 32, "%02d", (int) t->s); break; case 's': length = slprintf(buffer, 32, "%d", (int) t->s); break; case 'a': { if ((int) t->days != -99999) { length = slprintf(buffer, 32, "%d", (int) t->days); } else { length = slprintf(buffer, 32, "(unknown)"); } } break; case 'r': length = slprintf(buffer, 32, "%s", t->invert ? "-" : ""); break; case 'R': length = slprintf(buffer, 32, "%c", t->invert ? '-' : '+'); break; case '%': length = slprintf(buffer, 32, "%%"); break; default: buffer[0] = '%'; buffer[1] = format[i]; buffer[2] = '\0'; length = 2; break; } smart_str_appendl(&string, buffer, length); have_format_spec = 0; } else { if (format[i] == '%') { have_format_spec = 1; } else { smart_str_appendc(&string, format[i]); } } } smart_str_0(&string); return string.c; } /* }}} */ /* {{{ proto string date_interval_format(DateInterval object, string format) Formats the interval. */ PHP_FUNCTION(date_interval_format) { zval *object; php_interval_obj *diobj; char *format; int format_len; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os", &object, date_ce_interval, &format, &format_len) == FAILURE) { RETURN_FALSE; } diobj = (php_interval_obj *) zend_object_store_get_object(object TSRMLS_CC); DATE_CHECK_INITIALIZED(diobj->initialized, DateInterval); RETURN_STRING(date_interval_format(format, format_len, diobj->diff), 0); } /* }}} */ static int date_period_initialize(timelib_time **st, timelib_time **et, timelib_rel_time **d, long *recurrences, /*const*/ char *format, int format_length TSRMLS_DC) { timelib_time *b = NULL, *e = NULL; timelib_rel_time *p = NULL; int r = 0; int retval = 0; struct timelib_error_container *errors; timelib_strtointerval(format, format_length, &b, &e, &p, &r, &errors); if (errors->error_count > 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown or bad format (%s)", format); retval = FAILURE; } else { *st = b; *et = e; *d = p; *recurrences = r; retval = SUCCESS; } timelib_error_container_dtor(errors); return retval; } /* {{{ proto DatePeriod::__construct(DateTime $start, DateInterval $interval, int recurrences|DateTime $end) Creates new DatePeriod object. */ PHP_METHOD(DatePeriod, __construct) { php_period_obj *dpobj; php_date_obj *dateobj; php_interval_obj *intobj; zval *start, *end = NULL, *interval; long recurrences = 0, options = 0; char *isostr = NULL; int isostr_len = 0; timelib_time *clone; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "OOl|l", &start, date_ce_date, &interval, date_ce_interval, &recurrences, &options) == FAILURE) { if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "OOO|l", &start, date_ce_date, &interval, date_ce_interval, &end, date_ce_date, &options) == FAILURE) { if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &isostr, &isostr_len, &options) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "This constructor accepts either (DateTime, DateInterval, int) OR (DateTime, DateInterval, DateTime) OR (string) as arguments."); zend_restore_error_handling(&error_handling TSRMLS_CC); return; } } } dpobj = zend_object_store_get_object(getThis() TSRMLS_CC); dpobj->current = NULL; if (isostr_len) { date_period_initialize(&(dpobj->start), &(dpobj->end), &(dpobj->interval), &recurrences, isostr, isostr_len TSRMLS_CC); if (dpobj->start == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The ISO interval '%s' did not contain a start date.", isostr); } if (dpobj->interval == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The ISO interval '%s' did not contain an interval.", isostr); } if (dpobj->end == NULL && recurrences == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The ISO interval '%s' did not contain an end date or a recurrence count.", isostr); } if (dpobj->start) { timelib_update_ts(dpobj->start, NULL); } if (dpobj->end) { timelib_update_ts(dpobj->end, NULL); } } else { /* init */ intobj = (php_interval_obj *) zend_object_store_get_object(interval TSRMLS_CC); /* start date */ dateobj = (php_date_obj *) zend_object_store_get_object(start TSRMLS_CC); clone = timelib_time_ctor(); memcpy(clone, dateobj->time, sizeof(timelib_time)); if (dateobj->time->tz_abbr) { clone->tz_abbr = strdup(dateobj->time->tz_abbr); } if (dateobj->time->tz_info) { clone->tz_info = dateobj->time->tz_info; } dpobj->start = clone; /* interval */ dpobj->interval = timelib_rel_time_clone(intobj->diff); /* end date */ if (end) { dateobj = (php_date_obj *) zend_object_store_get_object(end TSRMLS_CC); clone = timelib_time_clone(dateobj->time); dpobj->end = clone; } } /* options */ dpobj->include_start_date = !(options & PHP_DATE_PERIOD_EXCLUDE_START_DATE); /* recurrrences */ dpobj->recurrences = recurrences + dpobj->include_start_date; dpobj->initialized = 1; zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ static int check_id_allowed(char *id, long what) { if (what & PHP_DATE_TIMEZONE_GROUP_AFRICA && strncasecmp(id, "Africa/", 7) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_AMERICA && strncasecmp(id, "America/", 8) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_ANTARCTICA && strncasecmp(id, "Antarctica/", 11) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_ARCTIC && strncasecmp(id, "Arctic/", 7) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_ASIA && strncasecmp(id, "Asia/", 5) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_ATLANTIC && strncasecmp(id, "Atlantic/", 9) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_AUSTRALIA && strncasecmp(id, "Australia/", 10) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_EUROPE && strncasecmp(id, "Europe/", 7) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_INDIAN && strncasecmp(id, "Indian/", 7) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_PACIFIC && strncasecmp(id, "Pacific/", 8) == 0) return 1; if (what & PHP_DATE_TIMEZONE_GROUP_UTC && strncasecmp(id, "UTC", 3) == 0) return 1; return 0; } /* {{{ proto array timezone_identifiers_list([long what[, string country]]) Returns numerically index array with all timezone identifiers. */ PHP_FUNCTION(timezone_identifiers_list) { const timelib_tzdb *tzdb; const timelib_tzdb_index_entry *table; int i, item_count; long what = PHP_DATE_TIMEZONE_GROUP_ALL; char *option = NULL; int option_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|ls", &what, &option, &option_len) == FAILURE) { RETURN_FALSE; } /* Extra validation */ if (what == PHP_DATE_TIMEZONE_PER_COUNTRY && option_len != 2) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "A two-letter ISO 3166-1 compatible country code is expected"); RETURN_FALSE; } tzdb = DATE_TIMEZONEDB; item_count = tzdb->index_size; table = tzdb->index; array_init(return_value); for (i = 0; i < item_count; ++i) { if (what == PHP_DATE_TIMEZONE_PER_COUNTRY) { if (tzdb->data[table[i].pos + 5] == option[0] && tzdb->data[table[i].pos + 6] == option[1]) { add_next_index_string(return_value, table[i].id, 1); } } else if (what == PHP_DATE_TIMEZONE_GROUP_ALL_W_BC || (check_id_allowed(table[i].id, what) && (tzdb->data[table[i].pos + 4] == '\1'))) { add_next_index_string(return_value, table[i].id, 1); } }; } /* }}} */ /* {{{ proto array timezone_version_get() Returns the Olson database version number. */ PHP_FUNCTION(timezone_version_get) { const timelib_tzdb *tzdb; tzdb = DATE_TIMEZONEDB; RETURN_STRING(tzdb->version, 1); } /* }}} */ /* {{{ proto array timezone_abbreviations_list() Returns associative array containing dst, offset and the timezone name */ PHP_FUNCTION(timezone_abbreviations_list) { const timelib_tz_lookup_table *table, *entry; zval *element, **abbr_array_pp, *abbr_array; table = timelib_timezone_abbreviations_list(); array_init(return_value); entry = table; do { MAKE_STD_ZVAL(element); array_init(element); add_assoc_bool(element, "dst", entry->type); add_assoc_long(element, "offset", entry->gmtoffset); if (entry->full_tz_name) { add_assoc_string(element, "timezone_id", entry->full_tz_name, 1); } else { add_assoc_null(element, "timezone_id"); } if (zend_hash_find(HASH_OF(return_value), entry->name, strlen(entry->name) + 1, (void **) &abbr_array_pp) == FAILURE) { MAKE_STD_ZVAL(abbr_array); array_init(abbr_array); add_assoc_zval(return_value, entry->name, abbr_array); } else { abbr_array = *abbr_array_pp; } add_next_index_zval(abbr_array, element); entry++; } while (entry->name); } /* }}} */ /* {{{ proto bool date_default_timezone_set(string timezone_identifier) Sets the default timezone used by all date/time functions in a script */ PHP_FUNCTION(date_default_timezone_set) { char *zone; int zone_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &zone, &zone_len) == FAILURE) { RETURN_FALSE; } if (!timelib_timezone_id_is_valid(zone, DATE_TIMEZONEDB)) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Timezone ID '%s' is invalid", zone); RETURN_FALSE; } if (DATEG(timezone)) { efree(DATEG(timezone)); DATEG(timezone) = NULL; } DATEG(timezone) = estrndup(zone, zone_len); RETURN_TRUE; } /* }}} */ /* {{{ proto string date_default_timezone_get() Gets the default timezone used by all date/time functions in a script */ PHP_FUNCTION(date_default_timezone_get) { timelib_tzinfo *default_tz; default_tz = get_timezone_info(TSRMLS_C); RETVAL_STRING(default_tz->name, 1); } /* }}} */ /* {{{ php_do_date_sunrise_sunset * Common for date_sunrise() and date_sunset() functions */ static void php_do_date_sunrise_sunset(INTERNAL_FUNCTION_PARAMETERS, int calc_sunset) { double latitude = 0.0, longitude = 0.0, zenith = 0.0, gmt_offset = 0, altitude; double h_rise, h_set, N; timelib_sll rise, set, transit; long time, retformat = 0; int rs; timelib_time *t; timelib_tzinfo *tzi; char *retstr; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|ldddd", &time, &retformat, &latitude, &longitude, &zenith, &gmt_offset) == FAILURE) { RETURN_FALSE; } switch (ZEND_NUM_ARGS()) { case 1: retformat = SUNFUNCS_RET_STRING; case 2: latitude = INI_FLT("date.default_latitude"); case 3: longitude = INI_FLT("date.default_longitude"); case 4: if (calc_sunset) { zenith = INI_FLT("date.sunset_zenith"); } else { zenith = INI_FLT("date.sunrise_zenith"); } case 5: case 6: break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "invalid format"); RETURN_FALSE; break; } if (retformat != SUNFUNCS_RET_TIMESTAMP && retformat != SUNFUNCS_RET_STRING && retformat != SUNFUNCS_RET_DOUBLE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Wrong return format given, pick one of SUNFUNCS_RET_TIMESTAMP, SUNFUNCS_RET_STRING or SUNFUNCS_RET_DOUBLE"); RETURN_FALSE; } altitude = 90 - zenith; /* Initialize time struct */ t = timelib_time_ctor(); tzi = get_timezone_info(TSRMLS_C); t->tz_info = tzi; t->zone_type = TIMELIB_ZONETYPE_ID; if (ZEND_NUM_ARGS() <= 5) { gmt_offset = timelib_get_current_offset(t) / 3600; } timelib_unixtime2local(t, time); rs = timelib_astro_rise_set_altitude(t, longitude, latitude, altitude, 1, &h_rise, &h_set, &rise, &set, &transit); timelib_time_dtor(t); if (rs != 0) { RETURN_FALSE; } if (retformat == SUNFUNCS_RET_TIMESTAMP) { RETURN_LONG(calc_sunset ? set : rise); } N = (calc_sunset ? h_set : h_rise) + gmt_offset; if (N > 24 || N < 0) { N -= floor(N / 24) * 24; } switch (retformat) { case SUNFUNCS_RET_STRING: spprintf(&retstr, 0, "%02d:%02d", (int) N, (int) (60 * (N - (int) N))); RETURN_STRINGL(retstr, 5, 0); break; case SUNFUNCS_RET_DOUBLE: RETURN_DOUBLE(N); break; } } /* }}} */ /* {{{ proto mixed date_sunrise(mixed time [, int format [, float latitude [, float longitude [, float zenith [, float gmt_offset]]]]]) Returns time of sunrise for a given day and location */ PHP_FUNCTION(date_sunrise) { php_do_date_sunrise_sunset(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto mixed date_sunset(mixed time [, int format [, float latitude [, float longitude [, float zenith [, float gmt_offset]]]]]) Returns time of sunset for a given day and location */ PHP_FUNCTION(date_sunset) { php_do_date_sunrise_sunset(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto array date_sun_info(long time, float latitude, float longitude) Returns an array with information about sun set/rise and twilight begin/end */ PHP_FUNCTION(date_sun_info) { long time; double latitude, longitude; timelib_time *t, *t2; timelib_tzinfo *tzi; int rs; timelib_sll rise, set, transit; int dummy; double ddummy; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ldd", &time, &latitude, &longitude) == FAILURE) { RETURN_FALSE; } /* Initialize time struct */ t = timelib_time_ctor(); tzi = get_timezone_info(TSRMLS_C); t->tz_info = tzi; t->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(t, time); /* Setup */ t2 = timelib_time_ctor(); array_init(return_value); /* Get sun up/down and transit */ rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -35.0/60, 1, &ddummy, &ddummy, &rise, &set, &transit); switch (rs) { case -1: /* always below */ add_assoc_bool(return_value, "sunrise", 0); add_assoc_bool(return_value, "sunset", 0); break; case 1: /* always above */ add_assoc_bool(return_value, "sunrise", 1); add_assoc_bool(return_value, "sunset", 1); break; default: t2->sse = rise; add_assoc_long(return_value, "sunrise", timelib_date_to_int(t2, &dummy)); t2->sse = set; add_assoc_long(return_value, "sunset", timelib_date_to_int(t2, &dummy)); } t2->sse = transit; add_assoc_long(return_value, "transit", timelib_date_to_int(t2, &dummy)); /* Get civil twilight */ rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -6.0, 0, &ddummy, &ddummy, &rise, &set, &transit); switch (rs) { case -1: /* always below */ add_assoc_bool(return_value, "civil_twilight_begin", 0); add_assoc_bool(return_value, "civil_twilight_end", 0); break; case 1: /* always above */ add_assoc_bool(return_value, "civil_twilight_begin", 1); add_assoc_bool(return_value, "civil_twilight_end", 1); break; default: t2->sse = rise; add_assoc_long(return_value, "civil_twilight_begin", timelib_date_to_int(t2, &dummy)); t2->sse = set; add_assoc_long(return_value, "civil_twilight_end", timelib_date_to_int(t2, &dummy)); } /* Get nautical twilight */ rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -12.0, 0, &ddummy, &ddummy, &rise, &set, &transit); switch (rs) { case -1: /* always below */ add_assoc_bool(return_value, "nautical_twilight_begin", 0); add_assoc_bool(return_value, "nautical_twilight_end", 0); break; case 1: /* always above */ add_assoc_bool(return_value, "nautical_twilight_begin", 1); add_assoc_bool(return_value, "nautical_twilight_end", 1); break; default: t2->sse = rise; add_assoc_long(return_value, "nautical_twilight_begin", timelib_date_to_int(t2, &dummy)); t2->sse = set; add_assoc_long(return_value, "nautical_twilight_end", timelib_date_to_int(t2, &dummy)); } /* Get astronomical twilight */ rs = timelib_astro_rise_set_altitude(t, longitude, latitude, -18.0, 0, &ddummy, &ddummy, &rise, &set, &transit); switch (rs) { case -1: /* always below */ add_assoc_bool(return_value, "astronomical_twilight_begin", 0); add_assoc_bool(return_value, "astronomical_twilight_end", 0); break; case 1: /* always above */ add_assoc_bool(return_value, "astronomical_twilight_begin", 1); add_assoc_bool(return_value, "astronomical_twilight_end", 1); break; default: t2->sse = rise; add_assoc_long(return_value, "astronomical_twilight_begin", timelib_date_to_int(t2, &dummy)); t2->sse = set; add_assoc_long(return_value, "astronomical_twilight_end", timelib_date_to_int(t2, &dummy)); } timelib_time_dtor(t); timelib_time_dtor(t2); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: fdm=marker * vim: noet sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-01-29-147382033a-5bb0a44e06.c
manybugs_data_98
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2012 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Marcus Boerger <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" #include "ext/standard/php_var.h" #include "ext/standard/php_smart_str.h" #include "zend_interfaces.h" #include "zend_exceptions.h" #include "php_spl.h" #include "spl_functions.h" #include "spl_engine.h" #include "spl_iterators.h" #include "spl_array.h" #include "spl_exceptions.h" zend_object_handlers spl_handler_ArrayObject; PHPAPI zend_class_entry *spl_ce_ArrayObject; zend_object_handlers spl_handler_ArrayIterator; PHPAPI zend_class_entry *spl_ce_ArrayIterator; PHPAPI zend_class_entry *spl_ce_RecursiveArrayIterator; #define SPL_ARRAY_STD_PROP_LIST 0x00000001 #define SPL_ARRAY_ARRAY_AS_PROPS 0x00000002 #define SPL_ARRAY_CHILD_ARRAYS_ONLY 0x00000004 #define SPL_ARRAY_OVERLOADED_REWIND 0x00010000 #define SPL_ARRAY_OVERLOADED_VALID 0x00020000 #define SPL_ARRAY_OVERLOADED_KEY 0x00040000 #define SPL_ARRAY_OVERLOADED_CURRENT 0x00080000 #define SPL_ARRAY_OVERLOADED_NEXT 0x00100000 #define SPL_ARRAY_IS_REF 0x01000000 #define SPL_ARRAY_IS_SELF 0x02000000 #define SPL_ARRAY_USE_OTHER 0x04000000 #define SPL_ARRAY_INT_MASK 0xFFFF0000 #define SPL_ARRAY_CLONE_MASK 0x0300FFFF typedef struct _spl_array_object { zend_object std; zval *array; zval *retval; HashPosition pos; ulong pos_h; int ar_flags; int is_self; zend_function *fptr_offset_get; zend_function *fptr_offset_set; zend_function *fptr_offset_has; zend_function *fptr_offset_del; zend_function *fptr_count; zend_class_entry* ce_get_iterator; HashTable *debug_info; unsigned char nApplyCount; } spl_array_object; static inline HashTable *spl_array_get_hash_table(spl_array_object* intern, int check_std_props TSRMLS_DC) { /* {{{ */ if ((intern->ar_flags & SPL_ARRAY_IS_SELF) != 0) { if (!intern->std.properties) { rebuild_object_properties(&intern->std); } return intern->std.properties; } else if ((intern->ar_flags & SPL_ARRAY_USE_OTHER) && (check_std_props == 0 || (intern->ar_flags & SPL_ARRAY_STD_PROP_LIST) == 0) && Z_TYPE_P(intern->array) == IS_OBJECT) { spl_array_object *other = (spl_array_object*)zend_object_store_get_object(intern->array TSRMLS_CC); return spl_array_get_hash_table(other, check_std_props TSRMLS_CC); } else if ((intern->ar_flags & ((check_std_props ? SPL_ARRAY_STD_PROP_LIST : 0) | SPL_ARRAY_IS_SELF)) != 0) { if (!intern->std.properties) { rebuild_object_properties(&intern->std); } return intern->std.properties; } else { return HASH_OF(intern->array); } } /* }}} */ static void spl_array_rewind(spl_array_object *intern TSRMLS_DC); static void spl_array_update_pos(spl_array_object* intern) /* {{{ */ { Bucket *pos = intern->pos; if (pos != NULL) { intern->pos_h = pos->h; } } /* }}} */ static void spl_array_set_pos(spl_array_object* intern, HashPosition pos) /* {{{ */ { intern->pos = pos; spl_array_update_pos(intern); } /* }}} */ SPL_API int spl_hash_verify_pos_ex(spl_array_object * intern, HashTable * ht TSRMLS_DC) /* {{{ */ { Bucket *p; /* IS_CONSISTENT(ht);*/ /* HASH_PROTECT_RECURSION(ht);*/ p = ht->arBuckets[intern->pos_h & ht->nTableMask]; while (p != NULL) { if (p == intern->pos) { return SUCCESS; } p = p->pNext; } /* HASH_UNPROTECT_RECURSION(ht); */ spl_array_rewind(intern TSRMLS_CC); return FAILURE; } /* }}} */ SPL_API int spl_hash_verify_pos(spl_array_object * intern TSRMLS_DC) /* {{{ */ { HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); return spl_hash_verify_pos_ex(intern, ht TSRMLS_CC); } /* }}} */ /* {{{ spl_array_object_free_storage */ static void spl_array_object_free_storage(void *object TSRMLS_DC) { spl_array_object *intern = (spl_array_object *)object; zend_object_std_dtor(&intern->std TSRMLS_CC); zval_ptr_dtor(&intern->array); zval_ptr_dtor(&intern->retval); if (intern->debug_info != NULL) { zend_hash_destroy(intern->debug_info); efree(intern->debug_info); } efree(object); } /* }}} */ zend_object_iterator *spl_array_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC); /* {{{ spl_array_object_new_ex */ static zend_object_value spl_array_object_new_ex(zend_class_entry *class_type, spl_array_object **obj, zval *orig, int clone_orig TSRMLS_DC) { zend_object_value retval; spl_array_object *intern; zval *tmp; zend_class_entry * parent = class_type; int inherited = 0; intern = emalloc(sizeof(spl_array_object)); memset(intern, 0, sizeof(spl_array_object)); *obj = intern; ALLOC_INIT_ZVAL(intern->retval); zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); intern->ar_flags = 0; intern->debug_info = NULL; intern->ce_get_iterator = spl_ce_ArrayIterator; if (orig) { spl_array_object *other = (spl_array_object*)zend_object_store_get_object(orig TSRMLS_CC); intern->ar_flags &= ~ SPL_ARRAY_CLONE_MASK; intern->ar_flags |= (other->ar_flags & SPL_ARRAY_CLONE_MASK); intern->ce_get_iterator = other->ce_get_iterator; if (clone_orig) { intern->array = other->array; if (Z_OBJ_HT_P(orig) == &spl_handler_ArrayObject) { MAKE_STD_ZVAL(intern->array); array_init(intern->array); zend_hash_copy(HASH_OF(intern->array), HASH_OF(other->array), (copy_ctor_func_t) zval_add_ref, &tmp, sizeof(zval*)); } if (Z_OBJ_HT_P(orig) == &spl_handler_ArrayIterator) { Z_ADDREF_P(other->array); } } else { intern->array = orig; Z_ADDREF_P(intern->array); intern->ar_flags |= SPL_ARRAY_IS_REF | SPL_ARRAY_USE_OTHER; } } else { MAKE_STD_ZVAL(intern->array); array_init(intern->array); intern->ar_flags &= ~SPL_ARRAY_IS_REF; } retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) spl_array_object_free_storage, NULL TSRMLS_CC); while (parent) { if (parent == spl_ce_ArrayIterator || parent == spl_ce_RecursiveArrayIterator) { retval.handlers = &spl_handler_ArrayIterator; class_type->get_iterator = spl_array_get_iterator; break; } else if (parent == spl_ce_ArrayObject) { retval.handlers = &spl_handler_ArrayObject; break; } parent = parent->parent; inherited = 1; } if (!parent) { /* this must never happen */ php_error_docref(NULL TSRMLS_CC, E_COMPILE_ERROR, "Internal compiler error, Class is not child of ArrayObject or ArrayIterator"); } if (inherited) { zend_hash_find(&class_type->function_table, "offsetget", sizeof("offsetget"), (void **) &intern->fptr_offset_get); if (intern->fptr_offset_get->common.scope == parent) { intern->fptr_offset_get = NULL; } zend_hash_find(&class_type->function_table, "offsetset", sizeof("offsetset"), (void **) &intern->fptr_offset_set); if (intern->fptr_offset_set->common.scope == parent) { intern->fptr_offset_set = NULL; } zend_hash_find(&class_type->function_table, "offsetexists", sizeof("offsetexists"), (void **) &intern->fptr_offset_has); if (intern->fptr_offset_has->common.scope == parent) { intern->fptr_offset_has = NULL; } zend_hash_find(&class_type->function_table, "offsetunset", sizeof("offsetunset"), (void **) &intern->fptr_offset_del); if (intern->fptr_offset_del->common.scope == parent) { intern->fptr_offset_del = NULL; } zend_hash_find(&class_type->function_table, "count", sizeof("count"), (void **) &intern->fptr_count); if (intern->fptr_count->common.scope == parent) { intern->fptr_count = NULL; } } /* Cache iterator functions if ArrayIterator or derived. Check current's */ /* cache since only current is always required */ if (retval.handlers == &spl_handler_ArrayIterator) { if (!class_type->iterator_funcs.zf_current) { zend_hash_find(&class_type->function_table, "rewind", sizeof("rewind"), (void **) &class_type->iterator_funcs.zf_rewind); zend_hash_find(&class_type->function_table, "valid", sizeof("valid"), (void **) &class_type->iterator_funcs.zf_valid); zend_hash_find(&class_type->function_table, "key", sizeof("key"), (void **) &class_type->iterator_funcs.zf_key); zend_hash_find(&class_type->function_table, "current", sizeof("current"), (void **) &class_type->iterator_funcs.zf_current); zend_hash_find(&class_type->function_table, "next", sizeof("next"), (void **) &class_type->iterator_funcs.zf_next); } if (inherited) { if (class_type->iterator_funcs.zf_rewind->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_REWIND; if (class_type->iterator_funcs.zf_valid->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_VALID; if (class_type->iterator_funcs.zf_key->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_KEY; if (class_type->iterator_funcs.zf_current->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_CURRENT; if (class_type->iterator_funcs.zf_next->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_NEXT; } } spl_array_rewind(intern TSRMLS_CC); return retval; } /* }}} */ /* {{{ spl_array_object_new */ static zend_object_value spl_array_object_new(zend_class_entry *class_type TSRMLS_DC) { spl_array_object *tmp; return spl_array_object_new_ex(class_type, &tmp, NULL, 0 TSRMLS_CC); } /* }}} */ /* {{{ spl_array_object_clone */ static zend_object_value spl_array_object_clone(zval *zobject TSRMLS_DC) { zend_object_value new_obj_val; zend_object *old_object; zend_object *new_object; zend_object_handle handle = Z_OBJ_HANDLE_P(zobject); spl_array_object *intern; old_object = zend_objects_get_address(zobject TSRMLS_CC); new_obj_val = spl_array_object_new_ex(old_object->ce, &intern, zobject, 1 TSRMLS_CC); new_object = &intern->std; zend_objects_clone_members(new_object, new_obj_val, old_object, handle TSRMLS_CC); return new_obj_val; } /* }}} */ static zval **spl_array_get_dimension_ptr_ptr(int check_inherited, zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); zval **retval; long index; HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); /* We cannot get the pointer pointer so we don't allow it here for now if (check_inherited && intern->fptr_offset_get) { return zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_get, "offsetGet", NULL, offset); }*/ if (!offset) { return &EG(uninitialized_zval_ptr); } if ((type == BP_VAR_W || type == BP_VAR_RW) && (ht->nApplyCount > 0)) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return &EG(uninitialized_zval_ptr);; } switch(Z_TYPE_P(offset)) { case IS_STRING: if (zend_symtable_find(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void **) &retval) == FAILURE) { if (type == BP_VAR_W || type == BP_VAR_RW) { zval *value; ALLOC_INIT_ZVAL(value); zend_symtable_update(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void**)&value, sizeof(void*), NULL); if (zend_symtable_find(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void **) &retval) != FAILURE) { return retval; } else { return &EG(uninitialized_zval_ptr); } } else { zend_error(E_NOTICE, "Undefined index: %s", Z_STRVAL_P(offset)); return &EG(uninitialized_zval_ptr); } } else { return retval; } case IS_DOUBLE: case IS_RESOURCE: case IS_BOOL: case IS_LONG: if (offset->type == IS_DOUBLE) { index = (long)Z_DVAL_P(offset); } else { index = Z_LVAL_P(offset); } if (zend_hash_index_find(ht, index, (void **) &retval) == FAILURE) { if (type == BP_VAR_W || type == BP_VAR_RW) { zval *value; ALLOC_INIT_ZVAL(value); zend_hash_index_update(ht, index, (void**)&value, sizeof(void*), NULL); if (zend_hash_index_find(ht, index, (void **) &retval) != FAILURE) { return retval; } else { return &EG(uninitialized_zval_ptr); } } else { zend_error(E_NOTICE, "Undefined offset: %ld", index); return &EG(uninitialized_zval_ptr); } } else { return retval; } break; default: zend_error(E_WARNING, "Illegal offset type"); return &EG(uninitialized_zval_ptr); } } /* }}} */ static zval *spl_array_read_dimension_ex(int check_inherited, zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */ { zval **ret; if (check_inherited) { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (intern->fptr_offset_get) { zval *rv; SEPARATE_ARG_IF_REF(offset); zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_get, "offsetGet", &rv, offset); zval_ptr_dtor(&offset); if (rv) { zval_ptr_dtor(&intern->retval); MAKE_STD_ZVAL(intern->retval); ZVAL_ZVAL(intern->retval, rv, 1, 1); return intern->retval; } return EG(uninitialized_zval_ptr); } } ret = spl_array_get_dimension_ptr_ptr(check_inherited, object, offset, type TSRMLS_CC); /* When in a write context, * ZE has to be fooled into thinking this is in a reference set * by separating (if necessary) and returning as an is_ref=1 zval (even if refcount == 1) */ if ((type == BP_VAR_W || type == BP_VAR_RW) && !Z_ISREF_PP(ret)) { if (Z_REFCOUNT_PP(ret) > 1) { zval *newval; /* Separate */ MAKE_STD_ZVAL(newval); *newval = **ret; zval_copy_ctor(newval); Z_SET_REFCOUNT_P(newval, 1); /* Replace */ Z_DELREF_PP(ret); *ret = newval; } Z_SET_ISREF_PP(ret); } return *ret; } /* }}} */ static zval *spl_array_read_dimension(zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */ { return spl_array_read_dimension_ex(1, object, offset, type TSRMLS_CC); } /* }}} */ static void spl_array_write_dimension_ex(int check_inherited, zval *object, zval *offset, zval *value TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); long index; HashTable *ht; if (check_inherited && intern->fptr_offset_set) { if (!offset) { ALLOC_INIT_ZVAL(offset); } else { SEPARATE_ARG_IF_REF(offset); } zend_call_method_with_2_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_set, "offsetSet", NULL, offset, value); zval_ptr_dtor(&offset); return; } if (!offset) { ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (ht->nApplyCount > 0) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return; } Z_ADDREF_P(value); zend_hash_next_index_insert(ht, (void**)&value, sizeof(void*), NULL); return; } switch(Z_TYPE_P(offset)) { case IS_STRING: ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (ht->nApplyCount > 0) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return; } Z_ADDREF_P(value); zend_symtable_update(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void**)&value, sizeof(void*), NULL); return; case IS_DOUBLE: case IS_RESOURCE: case IS_BOOL: case IS_LONG: ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (ht->nApplyCount > 0) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return; } if (offset->type == IS_DOUBLE) { index = (long)Z_DVAL_P(offset); } else { index = Z_LVAL_P(offset); } Z_ADDREF_P(value); zend_hash_index_update(ht, index, (void**)&value, sizeof(void*), NULL); return; case IS_NULL: ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (ht->nApplyCount > 0) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return; } Z_ADDREF_P(value); zend_hash_next_index_insert(ht, (void**)&value, sizeof(void*), NULL); return; default: zend_error(E_WARNING, "Illegal offset type"); return; } } /* }}} */ static void spl_array_write_dimension(zval *object, zval *offset, zval *value TSRMLS_DC) /* {{{ */ { spl_array_write_dimension_ex(1, object, offset, value TSRMLS_CC); } /* }}} */ static void spl_array_unset_dimension_ex(int check_inherited, zval *object, zval *offset TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); long index; HashTable *ht; if (check_inherited && intern->fptr_offset_del) { SEPARATE_ARG_IF_REF(offset); zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_del, "offsetUnset", NULL, offset); zval_ptr_dtor(&offset); return; } switch(Z_TYPE_P(offset)) { case IS_STRING: ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (ht->nApplyCount > 0) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return; } if (ht == &EG(symbol_table)) { if (zend_delete_global_variable(Z_STRVAL_P(offset), Z_STRLEN_P(offset) TSRMLS_CC)) { zend_error(E_NOTICE,"Undefined index: %s", Z_STRVAL_P(offset)); } } else { if (zend_symtable_del(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1) == FAILURE) { zend_error(E_NOTICE,"Undefined index: %s", Z_STRVAL_P(offset)); } else { spl_array_object *obj = intern; while (1) { if ((obj->ar_flags & SPL_ARRAY_IS_SELF) != 0) { break; } else if (Z_TYPE_P(obj->array) == IS_OBJECT) { if ((obj->ar_flags & SPL_ARRAY_USE_OTHER) == 0) { obj = (spl_array_object*)zend_object_store_get_object(obj->array TSRMLS_CC); break; } else { obj = (spl_array_object*)zend_object_store_get_object(obj->array TSRMLS_CC); } } else { obj = NULL; break; } } if (obj) { zend_property_info *property_info = zend_get_property_info(obj->std.ce, offset, 1 TSRMLS_CC); if (property_info && (property_info->flags & ZEND_ACC_STATIC) == 0 && property_info->offset >= 0) { obj->std.properties_table[property_info->offset] = NULL; } } } } break; case IS_DOUBLE: case IS_RESOURCE: case IS_BOOL: case IS_LONG: if (offset->type == IS_DOUBLE) { index = (long)Z_DVAL_P(offset); } else { index = Z_LVAL_P(offset); } ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (ht->nApplyCount > 0) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return; } if (zend_hash_index_del(ht, index) == FAILURE) { zend_error(E_NOTICE,"Undefined offset: %ld", Z_LVAL_P(offset)); } break; default: zend_error(E_WARNING, "Illegal offset type"); return; } spl_hash_verify_pos(intern TSRMLS_CC); /* call rewind on FAILURE */ } /* }}} */ static void spl_array_unset_dimension(zval *object, zval *offset TSRMLS_DC) /* {{{ */ { spl_array_unset_dimension_ex(1, object, offset TSRMLS_CC); } /* }}} */ static int spl_array_has_dimension_ex(int check_inherited, zval *object, zval *offset, int check_empty TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); long index; zval *rv, **tmp; if (check_inherited && intern->fptr_offset_has) { SEPARATE_ARG_IF_REF(offset); zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_has, "offsetExists", &rv, offset); zval_ptr_dtor(&offset); if (rv && zend_is_true(rv)) { zval_ptr_dtor(&rv); return 1; } if (rv) { zval_ptr_dtor(&rv); } return 0; } switch(Z_TYPE_P(offset)) { case IS_STRING: if (check_empty) { if (zend_symtable_find(spl_array_get_hash_table(intern, 0 TSRMLS_CC), Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void **) &tmp) != FAILURE) { switch (check_empty) { case 0: return Z_TYPE_PP(tmp) != IS_NULL; case 2: return 1; default: return zend_is_true(*tmp); } } return 0; } else { return zend_symtable_exists(spl_array_get_hash_table(intern, 0 TSRMLS_CC), Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1); } case IS_DOUBLE: case IS_RESOURCE: case IS_BOOL: case IS_LONG: if (offset->type == IS_DOUBLE) { index = (long)Z_DVAL_P(offset); } else { index = Z_LVAL_P(offset); } if (check_empty) { HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_hash_index_find(ht, index, (void **)&tmp) != FAILURE) { switch (check_empty) { case 0: return Z_TYPE_PP(tmp) != IS_NULL; case 2: return 1; default: return zend_is_true(*tmp); } } return 0; } else { return zend_hash_index_exists(spl_array_get_hash_table(intern, 0 TSRMLS_CC), index); } default: zend_error(E_WARNING, "Illegal offset type"); } return 0; } /* }}} */ static int spl_array_has_dimension(zval *object, zval *offset, int check_empty TSRMLS_DC) /* {{{ */ { return spl_array_has_dimension_ex(1, object, offset, check_empty TSRMLS_CC); } /* }}} */ /* {{{ proto bool ArrayObject::offsetExists(mixed $index) proto bool ArrayIterator::offsetExists(mixed $index) Returns whether the requested $index exists. */ SPL_METHOD(Array, offsetExists) { zval *index; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &index) == FAILURE) { return; } RETURN_BOOL(spl_array_has_dimension_ex(0, getThis(), index, 0 TSRMLS_CC)); } /* }}} */ /* {{{ proto mixed ArrayObject::offsetGet(mixed $index) proto mixed ArrayIterator::offsetGet(mixed $index) Returns the value at the specified $index. */ SPL_METHOD(Array, offsetGet) { zval *index, *value; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &index) == FAILURE) { return; } value = spl_array_read_dimension_ex(0, getThis(), index, BP_VAR_R TSRMLS_CC); RETURN_ZVAL(value, 1, 0); } /* }}} */ /* {{{ proto void ArrayObject::offsetSet(mixed $index, mixed $newval) proto void ArrayIterator::offsetSet(mixed $index, mixed $newval) Sets the value at the specified $index to $newval. */ SPL_METHOD(Array, offsetSet) { zval *index, *value; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &index, &value) == FAILURE) { return; } spl_array_write_dimension_ex(0, getThis(), index, value TSRMLS_CC); } /* }}} */ void spl_array_iterator_append(zval *object, zval *append_value TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } if (Z_TYPE_P(intern->array) == IS_OBJECT) { php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "Cannot append properties to objects, use %s::offsetSet() instead", Z_OBJCE_P(object)->name); return; } spl_array_write_dimension(object, NULL, append_value TSRMLS_CC); if (!intern->pos) { spl_array_set_pos(intern, aht->pListTail); } } /* }}} */ /* {{{ proto void ArrayObject::append(mixed $newval) proto void ArrayIterator::append(mixed $newval) Appends the value (cannot be called for objects). */ SPL_METHOD(Array, append) { zval *value; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &value) == FAILURE) { return; } spl_array_iterator_append(getThis(), value TSRMLS_CC); } /* }}} */ /* {{{ proto void ArrayObject::offsetUnset(mixed $index) proto void ArrayIterator::offsetUnset(mixed $index) Unsets the value at the specified $index. */ SPL_METHOD(Array, offsetUnset) { zval *index; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &index) == FAILURE) { return; } spl_array_unset_dimension_ex(0, getThis(), index TSRMLS_CC); } /* }}} */ /* {{{ proto array ArrayObject::getArrayCopy() proto array ArrayIterator::getArrayCopy() Return a copy of the contained array */ SPL_METHOD(Array, getArrayCopy) { zval *object = getThis(), *tmp; spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); array_init(return_value); zend_hash_copy(HASH_OF(return_value), spl_array_get_hash_table(intern, 0 TSRMLS_CC), (copy_ctor_func_t) zval_add_ref, &tmp, sizeof(zval*)); } /* }}} */ static HashTable *spl_array_get_properties(zval *object TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *result; if (intern->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Nesting level too deep - recursive dependency?"); } intern->nApplyCount++; result = spl_array_get_hash_table(intern, 1 TSRMLS_CC); intern->nApplyCount--; return result; } /* }}} */ static HashTable* spl_array_get_debug_info(zval *obj, int *is_temp TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(obj TSRMLS_CC); zval *tmp, *storage; int name_len; char *zname; zend_class_entry *base; *is_temp = 0; if (!intern->std.properties) { rebuild_object_properties(&intern->std); } if (HASH_OF(intern->array) == intern->std.properties) { return intern->std.properties; } else { if (intern->debug_info == NULL) { ALLOC_HASHTABLE(intern->debug_info); ZEND_INIT_SYMTABLE_EX(intern->debug_info, zend_hash_num_elements(intern->std.properties) + 1, 0); } if (intern->debug_info->nApplyCount == 0) { zend_hash_clean(intern->debug_info); zend_hash_copy(intern->debug_info, intern->std.properties, (copy_ctor_func_t) zval_add_ref, (void *) &tmp, sizeof(zval *)); storage = intern->array; zval_add_ref(&storage); base = (Z_OBJ_HT_P(obj) == &spl_handler_ArrayIterator) ? spl_ce_ArrayIterator : spl_ce_ArrayObject; zname = spl_gen_private_prop_name(base, "storage", sizeof("storage")-1, &name_len TSRMLS_CC); zend_symtable_update(intern->debug_info, zname, name_len+1, &storage, sizeof(zval *), NULL); efree(zname); } return intern->debug_info; } } /* }}} */ static zval *spl_array_read_property(zval *object, zval *member, int type, const zend_literal *key TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0 && !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) { return spl_array_read_dimension(object, member, type TSRMLS_CC); } return std_object_handlers.read_property(object, member, type, key TSRMLS_CC); } /* }}} */ static void spl_array_write_property(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0 && !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) { spl_array_write_dimension(object, member, value TSRMLS_CC); return; } std_object_handlers.write_property(object, member, value, key TSRMLS_CC); } /* }}} */ static zval **spl_array_get_property_ptr_ptr(zval *object, zval *member, const zend_literal *key TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0 && !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) { return spl_array_get_dimension_ptr_ptr(1, object, member, BP_VAR_RW TSRMLS_CC); } return std_object_handlers.get_property_ptr_ptr(object, member, key TSRMLS_CC); } /* }}} */ static int spl_array_has_property(zval *object, zval *member, int has_set_exists, const zend_literal *key TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0 && !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) { return spl_array_has_dimension(object, member, has_set_exists TSRMLS_CC); } return std_object_handlers.has_property(object, member, has_set_exists, key TSRMLS_CC); } /* }}} */ static void spl_array_unset_property(zval *object, zval *member, const zend_literal *key TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0 && !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) { spl_array_unset_dimension(object, member TSRMLS_CC); spl_array_rewind(intern TSRMLS_CC); /* because deletion might invalidate position */ return; } std_object_handlers.unset_property(object, member, key TSRMLS_CC); } /* }}} */ static int spl_array_compare_objects(zval *o1, zval *o2 TSRMLS_DC) /* {{{ */ { HashTable *ht1, *ht2; spl_array_object *intern1, *intern2; int result = 0; zval temp_zv; intern1 = (spl_array_object*)zend_object_store_get_object(o1 TSRMLS_CC); intern2 = (spl_array_object*)zend_object_store_get_object(o2 TSRMLS_CC); ht1 = spl_array_get_hash_table(intern1, 0 TSRMLS_CC); ht2 = spl_array_get_hash_table(intern2, 0 TSRMLS_CC); zend_compare_symbol_tables(&temp_zv, ht1, ht2 TSRMLS_CC); result = (int)Z_LVAL(temp_zv); /* if we just compared std.properties, don't do it again */ if (result == 0 && !(ht1 == intern1->std.properties && ht2 == intern2->std.properties)) { result = std_object_handlers.compare_objects(o1, o2 TSRMLS_CC); } return result; } /* }}} */ static int spl_array_skip_protected(spl_array_object *intern, HashTable *aht TSRMLS_DC) /* {{{ */ { char *string_key; uint string_length; ulong num_key; if (Z_TYPE_P(intern->array) == IS_OBJECT) { do { if (zend_hash_get_current_key_ex(aht, &string_key, &string_length, &num_key, 0, &intern->pos) == HASH_KEY_IS_STRING) { if (!string_length || string_key[0]) { return SUCCESS; } } else { return SUCCESS; } if (zend_hash_has_more_elements_ex(aht, &intern->pos) != SUCCESS) { return FAILURE; } zend_hash_move_forward_ex(aht, &intern->pos); spl_array_update_pos(intern); } while (1); } return FAILURE; } /* }}} */ static int spl_array_next_no_verify(spl_array_object *intern, HashTable *aht TSRMLS_DC) /* {{{ */ { zend_hash_move_forward_ex(aht, &intern->pos); spl_array_update_pos(intern); if (Z_TYPE_P(intern->array) == IS_OBJECT) { return spl_array_skip_protected(intern, aht TSRMLS_CC); } else { return zend_hash_has_more_elements_ex(aht, &intern->pos); } } /* }}} */ static int spl_array_next_ex(spl_array_object *intern, HashTable *aht TSRMLS_DC) /* {{{ */ { if ((intern->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(intern, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and internal position is no longer valid"); return FAILURE; } return spl_array_next_no_verify(intern, aht TSRMLS_CC); } /* }}} */ static int spl_array_next(spl_array_object *intern TSRMLS_DC) /* {{{ */ { HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); return spl_array_next_ex(intern, aht TSRMLS_CC); } /* }}} */ /* define an overloaded iterator structure */ typedef struct { zend_user_iterator intern; spl_array_object *object; } spl_array_it; static void spl_array_it_dtor(zend_object_iterator *iter TSRMLS_DC) /* {{{ */ { spl_array_it *iterator = (spl_array_it *)iter; zend_user_it_invalidate_current(iter TSRMLS_CC); zval_ptr_dtor((zval**)&iterator->intern.it.data); efree(iterator); } /* }}} */ static int spl_array_it_valid(zend_object_iterator *iter TSRMLS_DC) /* {{{ */ { spl_array_it *iterator = (spl_array_it *)iter; spl_array_object *object = iterator->object; HashTable *aht = spl_array_get_hash_table(object, 0 TSRMLS_CC); if (object->ar_flags & SPL_ARRAY_OVERLOADED_VALID) { return zend_user_it_valid(iter TSRMLS_CC); } else { if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::valid(): Array was modified outside object and is no longer an array"); return FAILURE; } if (object->pos && (object->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(object, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::valid(): Array was modified outside object and internal position is no longer valid"); return FAILURE; } else { return zend_hash_has_more_elements_ex(aht, &object->pos); } } } /* }}} */ static void spl_array_it_get_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC) /* {{{ */ { spl_array_it *iterator = (spl_array_it *)iter; spl_array_object *object = iterator->object; HashTable *aht = spl_array_get_hash_table(object, 0 TSRMLS_CC); if (object->ar_flags & SPL_ARRAY_OVERLOADED_CURRENT) { zend_user_it_get_current_data(iter, data TSRMLS_CC); } else { if (zend_hash_get_current_data_ex(aht, (void**)data, &object->pos) == FAILURE) { *data = NULL; } } } /* }}} */ static int spl_array_it_get_current_key(zend_object_iterator *iter, char **str_key, uint *str_key_len, ulong *int_key TSRMLS_DC) /* {{{ */ { spl_array_it *iterator = (spl_array_it *)iter; spl_array_object *object = iterator->object; HashTable *aht = spl_array_get_hash_table(object, 0 TSRMLS_CC); if (object->ar_flags & SPL_ARRAY_OVERLOADED_KEY) { return zend_user_it_get_current_key(iter, str_key, str_key_len, int_key TSRMLS_CC); } else { if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::current(): Array was modified outside object and is no longer an array"); return HASH_KEY_NON_EXISTANT; } if ((object->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(object, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::current(): Array was modified outside object and internal position is no longer valid"); return HASH_KEY_NON_EXISTANT; } return zend_hash_get_current_key_ex(aht, str_key, str_key_len, int_key, 1, &object->pos); } } /* }}} */ static void spl_array_it_move_forward(zend_object_iterator *iter TSRMLS_DC) /* {{{ */ { spl_array_it *iterator = (spl_array_it *)iter; spl_array_object *object = iterator->object; HashTable *aht = spl_array_get_hash_table(object, 0 TSRMLS_CC); if (object->ar_flags & SPL_ARRAY_OVERLOADED_NEXT) { zend_user_it_move_forward(iter TSRMLS_CC); } else { zend_user_it_invalidate_current(iter TSRMLS_CC); if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::current(): Array was modified outside object and is no longer an array"); return; } if ((object->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(object, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::next(): Array was modified outside object and internal position is no longer valid"); } else { spl_array_next_no_verify(object, aht TSRMLS_CC); } } } /* }}} */ static void spl_array_rewind_ex(spl_array_object *intern, HashTable *aht TSRMLS_DC) /* {{{ */ { zend_hash_internal_pointer_reset_ex(aht, &intern->pos); spl_array_update_pos(intern); spl_array_skip_protected(intern, aht TSRMLS_CC); } /* }}} */ static void spl_array_rewind(spl_array_object *intern TSRMLS_DC) /* {{{ */ { HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::rewind(): Array was modified outside object and is no longer an array"); return; } spl_array_rewind_ex(intern, aht TSRMLS_CC); } /* }}} */ static void spl_array_it_rewind(zend_object_iterator *iter TSRMLS_DC) /* {{{ */ { spl_array_it *iterator = (spl_array_it *)iter; spl_array_object *object = iterator->object; if (object->ar_flags & SPL_ARRAY_OVERLOADED_REWIND) { zend_user_it_rewind(iter TSRMLS_CC); } else { zend_user_it_invalidate_current(iter TSRMLS_CC); spl_array_rewind(object TSRMLS_CC); } } /* }}} */ /* {{{ spl_array_set_array */ static void spl_array_set_array(zval *object, spl_array_object *intern, zval **array, long ar_flags, int just_array TSRMLS_DC) { if (Z_TYPE_PP(array) == IS_ARRAY) { SEPARATE_ZVAL_IF_NOT_REF(array); } if (Z_TYPE_PP(array) == IS_OBJECT && (Z_OBJ_HT_PP(array) == &spl_handler_ArrayObject || Z_OBJ_HT_PP(array) == &spl_handler_ArrayIterator)) { zval_ptr_dtor(&intern->array); if (just_array) { spl_array_object *other = (spl_array_object*)zend_object_store_get_object(*array TSRMLS_CC); ar_flags = other->ar_flags & ~SPL_ARRAY_INT_MASK; } ar_flags |= SPL_ARRAY_USE_OTHER; intern->array = *array; } else { if (Z_TYPE_PP(array) != IS_OBJECT && Z_TYPE_PP(array) != IS_ARRAY) { zend_throw_exception(spl_ce_InvalidArgumentException, "Passed variable is not an array or object, using empty array instead", 0 TSRMLS_CC); return; } zval_ptr_dtor(&intern->array); intern->array = *array; } if (object == *array) { intern->ar_flags |= SPL_ARRAY_IS_SELF; intern->ar_flags &= ~SPL_ARRAY_USE_OTHER; } else { intern->ar_flags &= ~SPL_ARRAY_IS_SELF; } intern->ar_flags |= ar_flags; Z_ADDREF_P(intern->array); if (Z_TYPE_PP(array) == IS_OBJECT) { zend_object_get_properties_t handler = Z_OBJ_HANDLER_PP(array, get_properties); if ((handler != std_object_handlers.get_properties && handler != spl_array_get_properties) || !spl_array_get_hash_table(intern, 0 TSRMLS_CC)) { zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0 TSRMLS_CC, "Overloaded object of type %s is not compatible with %s", Z_OBJCE_PP(array)->name, intern->std.ce->name); } } spl_array_rewind(intern TSRMLS_CC); } /* }}} */ /* iterator handler table */ zend_object_iterator_funcs spl_array_it_funcs = { spl_array_it_dtor, spl_array_it_valid, spl_array_it_get_current_data, spl_array_it_get_current_key, spl_array_it_move_forward, spl_array_it_rewind }; zend_object_iterator *spl_array_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) /* {{{ */ { spl_array_it *iterator; spl_array_object *array_object = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (by_ref && (array_object->ar_flags & SPL_ARRAY_OVERLOADED_CURRENT)) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } iterator = emalloc(sizeof(spl_array_it)); Z_ADDREF_P(object); iterator->intern.it.data = (void*)object; iterator->intern.it.funcs = &spl_array_it_funcs; iterator->intern.ce = ce; iterator->intern.value = NULL; iterator->object = array_object; return (zend_object_iterator*)iterator; } /* }}} */ /* {{{ proto void ArrayObject::__construct(array|object ar = array() [, int flags = 0 [, string iterator_class = "ArrayIterator"]]) proto void ArrayIterator::__construct(array|object ar = array() [, int flags = 0]) Constructs a new array iterator from a path. */ SPL_METHOD(Array, __construct) { zval *object = getThis(); spl_array_object *intern; zval **array; long ar_flags = 0; zend_class_entry *ce_get_iterator = spl_ce_Iterator; zend_error_handling error_handling; if (ZEND_NUM_ARGS() == 0) { return; /* nothing to do */ } zend_replace_error_handling(EH_THROW, spl_ce_InvalidArgumentException, &error_handling TSRMLS_CC); intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z|lC", &array, &ar_flags, &ce_get_iterator) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (ZEND_NUM_ARGS() > 2) { intern->ce_get_iterator = ce_get_iterator; } ar_flags &= ~SPL_ARRAY_INT_MASK; spl_array_set_array(object, intern, array, ar_flags, ZEND_NUM_ARGS() == 1 TSRMLS_CC); zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void ArrayObject::setIteratorClass(string iterator_class) Set the class used in getIterator. */ SPL_METHOD(Array, setIteratorClass) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); zend_class_entry * ce_get_iterator = spl_ce_Iterator; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "C", &ce_get_iterator) == FAILURE) { return; } intern->ce_get_iterator = ce_get_iterator; } /* }}} */ /* {{{ proto string ArrayObject::getIteratorClass() Get the class used in getIterator. */ SPL_METHOD(Array, getIteratorClass) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_STRING(intern->ce_get_iterator->name, 1); } /* }}} */ /* {{{ proto int ArrayObject::getFlags() Get flags */ SPL_METHOD(Array, getFlags) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(intern->ar_flags & ~SPL_ARRAY_INT_MASK); } /* }}} */ /* {{{ proto void ArrayObject::setFlags(int flags) Set flags */ SPL_METHOD(Array, setFlags) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); long ar_flags = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &ar_flags) == FAILURE) { return; } intern->ar_flags = (intern->ar_flags & SPL_ARRAY_INT_MASK) | (ar_flags & ~SPL_ARRAY_INT_MASK); } /* }}} */ /* {{{ proto Array|Object ArrayObject::exchangeArray(Array|Object ar = array()) Replace the referenced array or object with a new one and return the old one (right now copy - to be changed) */ SPL_METHOD(Array, exchangeArray) { zval *object = getThis(), *tmp, **array; spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); array_init(return_value); zend_hash_copy(HASH_OF(return_value), spl_array_get_hash_table(intern, 0 TSRMLS_CC), (copy_ctor_func_t) zval_add_ref, &tmp, sizeof(zval*)); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z", &array) == FAILURE) { return; } spl_array_set_array(object, intern, array, 0L, 1 TSRMLS_CC); } /* }}} */ /* {{{ proto ArrayIterator ArrayObject::getIterator() Create a new iterator from a ArrayObject instance */ SPL_METHOD(Array, getIterator) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); spl_array_object *iterator; HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } return_value->type = IS_OBJECT; return_value->value.obj = spl_array_object_new_ex(intern->ce_get_iterator, &iterator, object, 0 TSRMLS_CC); Z_SET_REFCOUNT_P(return_value, 1); Z_SET_ISREF_P(return_value); } /* }}} */ /* {{{ proto void ArrayIterator::rewind() Rewind array back to the start */ SPL_METHOD(Array, rewind) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } spl_array_rewind(intern TSRMLS_CC); } /* }}} */ /* {{{ proto void ArrayIterator::seek(int $position) Seek to position. */ SPL_METHOD(Array, seek) { long opos, position; zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); int result; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &position) == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } opos = position; if (position >= 0) { /* negative values are not supported */ spl_array_rewind(intern TSRMLS_CC); result = SUCCESS; while (position-- > 0 && (result = spl_array_next(intern TSRMLS_CC)) == SUCCESS); if (result == SUCCESS && zend_hash_has_more_elements_ex(aht, &intern->pos) == SUCCESS) { return; /* ok */ } } zend_throw_exception_ex(spl_ce_OutOfBoundsException, 0 TSRMLS_CC, "Seek position %ld is out of range", opos); } /* }}} */ int static spl_array_object_count_elements_helper(spl_array_object *intern, long *count TSRMLS_DC) /* {{{ */ { HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); HashPosition pos; if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); *count = 0; return FAILURE; } if (Z_TYPE_P(intern->array) == IS_OBJECT) { /* We need to store the 'pos' since we'll modify it in the functions * we're going to call and which do not support 'pos' as parameter. */ pos = intern->pos; *count = 0; spl_array_rewind(intern TSRMLS_CC); while(intern->pos && spl_array_next(intern TSRMLS_CC) == SUCCESS) { (*count)++; } spl_array_set_pos(intern, pos); return SUCCESS; } else { *count = zend_hash_num_elements(aht); return SUCCESS; } } /* }}} */ int spl_array_object_count_elements(zval *object, long *count TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (intern->fptr_count) { zval *rv; zend_call_method_with_0_params(&object, intern->std.ce, &intern->fptr_count, "count", &rv); if (rv) { zval_ptr_dtor(&intern->retval); MAKE_STD_ZVAL(intern->retval); ZVAL_ZVAL(intern->retval, rv, 1, 1); convert_to_long(intern->retval); *count = (long) Z_LVAL_P(intern->retval); return SUCCESS; } *count = 0; return FAILURE; } return spl_array_object_count_elements_helper(intern, count TSRMLS_CC); } /* }}} */ /* {{{ proto int ArrayObject::count() proto int ArrayIterator::count() Return the number of elements in the Iterator. */ SPL_METHOD(Array, count) { long count; spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } spl_array_object_count_elements_helper(intern, &count TSRMLS_CC); RETURN_LONG(count); } /* }}} */ static void spl_array_method(INTERNAL_FUNCTION_PARAMETERS, char *fname, int fname_len, int use_arg) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(getThis() TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); zval *tmp, *arg; zval *retval_ptr = NULL; MAKE_STD_ZVAL(tmp); Z_TYPE_P(tmp) = IS_ARRAY; Z_ARRVAL_P(tmp) = aht; if (use_arg) { if (ZEND_NUM_ARGS() != 1 || zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "z", &arg) == FAILURE) { Z_TYPE_P(tmp) = IS_NULL; zval_ptr_dtor(&tmp); zend_throw_exception(spl_ce_BadMethodCallException, "Function expects exactly one argument", 0 TSRMLS_CC); return; } aht->nApplyCount++; zend_call_method(NULL, NULL, NULL, fname, fname_len, &retval_ptr, 2, tmp, arg TSRMLS_CC); aht->nApplyCount--; } else { aht->nApplyCount++; zend_call_method(NULL, NULL, NULL, fname, fname_len, &retval_ptr, 1, tmp, NULL TSRMLS_CC); aht->nApplyCount--; } Z_TYPE_P(tmp) = IS_NULL; /* we want to destroy the zval, not the hashtable */ zval_ptr_dtor(&tmp); if (retval_ptr) { COPY_PZVAL_TO_ZVAL(*return_value, retval_ptr); } } /* }}} */ #define SPL_ARRAY_METHOD(cname, fname, use_arg) \ SPL_METHOD(cname, fname) \ { \ spl_array_method(INTERNAL_FUNCTION_PARAM_PASSTHRU, #fname, sizeof(#fname)-1, use_arg); \ } /* {{{ proto int ArrayObject::asort() proto int ArrayIterator::asort() Sort the entries by values. */ SPL_ARRAY_METHOD(Array, asort, 0) /* }}} */ /* {{{ proto int ArrayObject::ksort() proto int ArrayIterator::ksort() Sort the entries by key. */ SPL_ARRAY_METHOD(Array, ksort, 0) /* }}} */ /* {{{ proto int ArrayObject::uasort(callback cmp_function) proto int ArrayIterator::uasort(callback cmp_function) Sort the entries by values user defined function. */ SPL_ARRAY_METHOD(Array, uasort, 1) /* }}} */ /* {{{ proto int ArrayObject::uksort(callback cmp_function) proto int ArrayIterator::uksort(callback cmp_function) Sort the entries by key using user defined function. */ SPL_ARRAY_METHOD(Array, uksort, 1) /* }}} */ /* {{{ proto int ArrayObject::natsort() proto int ArrayIterator::natsort() Sort the entries by values using "natural order" algorithm. */ SPL_ARRAY_METHOD(Array, natsort, 0) /* }}} */ /* {{{ proto int ArrayObject::natcasesort() proto int ArrayIterator::natcasesort() Sort the entries by key using case insensitive "natural order" algorithm. */ SPL_ARRAY_METHOD(Array, natcasesort, 0) /* }}} */ /* {{{ proto mixed|NULL ArrayIterator::current() Return current array entry */ SPL_METHOD(Array, current) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); zval **entry; HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } if ((intern->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(intern, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and internal position is no longer valid"); return; } if (zend_hash_get_current_data_ex(aht, (void **) &entry, &intern->pos) == FAILURE) { return; } RETVAL_ZVAL(*entry, 1, 0); } /* }}} */ /* {{{ proto mixed|NULL ArrayIterator::key() Return current array key */ SPL_METHOD(Array, key) { if (zend_parse_parameters_none() == FAILURE) { return; } spl_array_iterator_key(getThis(), return_value TSRMLS_CC); } /* }}} */ void spl_array_iterator_key(zval *object, zval *return_value TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); char *string_key; uint string_length; ulong num_key; HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } if ((intern->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(intern, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and internal position is no longer valid"); return; } switch (zend_hash_get_current_key_ex(aht, &string_key, &string_length, &num_key, 1, &intern->pos)) { case HASH_KEY_IS_STRING: RETVAL_STRINGL(string_key, string_length - 1, 0); break; case HASH_KEY_IS_LONG: RETVAL_LONG(num_key); break; case HASH_KEY_NON_EXISTANT: return; } } /* }}} */ /* {{{ proto void ArrayIterator::next() Move to next entry */ SPL_METHOD(Array, next) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } spl_array_next_ex(intern, aht TSRMLS_CC); } /* }}} */ /* {{{ proto bool ArrayIterator::valid() Check whether array contains more entries */ SPL_METHOD(Array, valid) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } if (intern->pos && (intern->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(intern, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and internal position is no longer valid"); RETURN_FALSE; } else { RETURN_BOOL(zend_hash_has_more_elements_ex(aht, &intern->pos) == SUCCESS); } } /* }}} */ /* {{{ proto bool RecursiveArrayIterator::hasChildren() Check whether current element has children (e.g. is an array) */ SPL_METHOD(Array, hasChildren) { zval *object = getThis(), **entry; spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); RETURN_FALSE; } if ((intern->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(intern, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and internal position is no longer valid"); RETURN_FALSE; } if (zend_hash_get_current_data_ex(aht, (void **) &entry, &intern->pos) == FAILURE) { RETURN_FALSE; } RETURN_BOOL(Z_TYPE_PP(entry) == IS_ARRAY || (Z_TYPE_PP(entry) == IS_OBJECT && (intern->ar_flags & SPL_ARRAY_CHILD_ARRAYS_ONLY) == 0)); } /* }}} */ /* {{{ proto object RecursiveArrayIterator::getChildren() Create a sub iterator for the current element (same class as $this) */ SPL_METHOD(Array, getChildren) { zval *object = getThis(), **entry, *flags; spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } if ((intern->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(intern, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and internal position is no longer valid"); return; } if (zend_hash_get_current_data_ex(aht, (void **) &entry, &intern->pos) == FAILURE) { return; } if (Z_TYPE_PP(entry) == IS_OBJECT) { if ((intern->ar_flags & SPL_ARRAY_CHILD_ARRAYS_ONLY) != 0) { return; } if (instanceof_function(Z_OBJCE_PP(entry), Z_OBJCE_P(getThis()) TSRMLS_CC)) { RETURN_ZVAL(*entry, 0, 0); } } MAKE_STD_ZVAL(flags); ZVAL_LONG(flags, SPL_ARRAY_USE_OTHER | intern->ar_flags); spl_instantiate_arg_ex2(Z_OBJCE_P(getThis()), &return_value, 0, *entry, flags TSRMLS_CC); zval_ptr_dtor(&flags); } /* }}} */ /* {{{ proto string ArrayObject::serialize() Serialize the object */ SPL_METHOD(Array, serialize) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); zval members, *pmembers; php_serialize_data_t var_hash; smart_str buf = {0}; zval *flags; if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } PHP_VAR_SERIALIZE_INIT(var_hash); MAKE_STD_ZVAL(flags); ZVAL_LONG(flags, (intern->ar_flags & SPL_ARRAY_CLONE_MASK)); /* storage */ smart_str_appendl(&buf, "x:", 2); php_var_serialize(&buf, &flags, &var_hash TSRMLS_CC); zval_ptr_dtor(&flags); if (!(intern->ar_flags & SPL_ARRAY_IS_SELF)) { php_var_serialize(&buf, &intern->array, &var_hash TSRMLS_CC); smart_str_appendc(&buf, ';'); } /* members */ smart_str_appendl(&buf, "m:", 2); INIT_PZVAL(&members); if (!intern->std.properties) { rebuild_object_properties(&intern->std); } Z_ARRVAL(members) = intern->std.properties; Z_TYPE(members) = IS_ARRAY; pmembers = &members; php_var_serialize(&buf, &pmembers, &var_hash TSRMLS_CC); /* finishes the string */ /* done */ PHP_VAR_SERIALIZE_DESTROY(var_hash); if (buf.c) { RETURN_STRINGL(buf.c, buf.len, 0); } RETURN_NULL(); } /* }}} */ /* {{{ proto void ArrayObject::unserialize(string serialized) * unserialize the object */ SPL_METHOD(Array, unserialize) { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *buf; int buf_len; const unsigned char *p, *s; php_unserialize_data_t var_hash; zval *pmembers, *pflags = NULL; long flags; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &buf, &buf_len) == FAILURE) { return; } if (buf_len == 0) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Empty serialized string cannot be empty"); return; } /* storage */ s = p = (const unsigned char*)buf; PHP_VAR_UNSERIALIZE_INIT(var_hash); if (*p!= 'x' || *++p != ':') { goto outexcept; } ++p; ALLOC_INIT_ZVAL(pflags); if (!php_var_unserialize(&pflags, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pflags) != IS_LONG) { zval_ptr_dtor(&pflags); goto outexcept; } --p; /* for ';' */ flags = Z_LVAL_P(pflags); zval_ptr_dtor(&pflags); /* flags needs to be verified and we also need to verify whether the next * thing we get is ';'. After that we require an 'm' or somethign else * where 'm' stands for members and anything else should be an array. If * neither 'a' or 'm' follows we have an error. */ if (*p != ';') { goto outexcept; } ++p; if (*p!='m') { if (*p!='a' && *p!='O' && *p!='C') { goto outexcept; } intern->ar_flags &= ~SPL_ARRAY_CLONE_MASK; intern->ar_flags |= flags & SPL_ARRAY_CLONE_MASK; zval_ptr_dtor(&intern->array); ALLOC_INIT_ZVAL(intern->array); if (!php_var_unserialize(&intern->array, &p, s + buf_len, &var_hash TSRMLS_CC)) { goto outexcept; } } if (*p != ';') { goto outexcept; } ++p; /* members */ if (*p!= 'm' || *++p != ':') { goto outexcept; } ++p; ALLOC_INIT_ZVAL(pmembers); if (!php_var_unserialize(&pmembers, &p, s + buf_len, &var_hash TSRMLS_CC)) { zval_ptr_dtor(&pmembers); goto outexcept; } /* copy members */ if (!intern->std.properties) { rebuild_object_properties(&intern->std); } zend_hash_copy(intern->std.properties, Z_ARRVAL_P(pmembers), (copy_ctor_func_t) zval_add_ref, (void *) NULL, sizeof(zval *)); zval_ptr_dtor(&pmembers); /* done reading $serialized */ PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return; outexcept: PHP_VAR_UNSERIALIZE_DESTROY(var_hash); zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Error at offset %ld of %d bytes", (long)((char*)p - buf), buf_len); return; } /* }}} */ /* {{{ arginfo and function tbale */ ZEND_BEGIN_ARG_INFO(arginfo_array___construct, 0) ZEND_ARG_INFO(0, array) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_offsetGet, 0, 0, 1) ZEND_ARG_INFO(0, index) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_offsetSet, 0, 0, 2) ZEND_ARG_INFO(0, index) ZEND_ARG_INFO(0, newval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_append, 0) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_seek, 0) ZEND_ARG_INFO(0, position) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_exchangeArray, 0) ZEND_ARG_INFO(0, array) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_setFlags, 0) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_setIteratorClass, 0) ZEND_ARG_INFO(0, iteratorClass) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_uXsort, 0) ZEND_ARG_INFO(0, cmp_function) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO(arginfo_array_unserialize, 0) ZEND_ARG_INFO(0, serialized) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO(arginfo_array_void, 0) ZEND_END_ARG_INFO() static const zend_function_entry spl_funcs_ArrayObject[] = { SPL_ME(Array, __construct, arginfo_array___construct, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetExists, arginfo_array_offsetGet, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetGet, arginfo_array_offsetGet, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetSet, arginfo_array_offsetSet, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetUnset, arginfo_array_offsetGet, ZEND_ACC_PUBLIC) SPL_ME(Array, append, arginfo_array_append, ZEND_ACC_PUBLIC) SPL_ME(Array, getArrayCopy, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, count, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, getFlags, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, setFlags, arginfo_array_setFlags, ZEND_ACC_PUBLIC) SPL_ME(Array, asort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, ksort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, uasort, arginfo_array_uXsort, ZEND_ACC_PUBLIC) SPL_ME(Array, uksort, arginfo_array_uXsort, ZEND_ACC_PUBLIC) SPL_ME(Array, natsort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, natcasesort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, unserialize, arginfo_array_unserialize, ZEND_ACC_PUBLIC) SPL_ME(Array, serialize, arginfo_array_void, ZEND_ACC_PUBLIC) /* ArrayObject specific */ SPL_ME(Array, getIterator, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, exchangeArray, arginfo_array_exchangeArray, ZEND_ACC_PUBLIC) SPL_ME(Array, setIteratorClass, arginfo_array_setIteratorClass, ZEND_ACC_PUBLIC) SPL_ME(Array, getIteratorClass, arginfo_array_void, ZEND_ACC_PUBLIC) PHP_FE_END }; static const zend_function_entry spl_funcs_ArrayIterator[] = { SPL_ME(Array, __construct, arginfo_array___construct, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetExists, arginfo_array_offsetGet, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetGet, arginfo_array_offsetGet, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetSet, arginfo_array_offsetSet, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetUnset, arginfo_array_offsetGet, ZEND_ACC_PUBLIC) SPL_ME(Array, append, arginfo_array_append, ZEND_ACC_PUBLIC) SPL_ME(Array, getArrayCopy, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, count, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, getFlags, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, setFlags, arginfo_array_setFlags, ZEND_ACC_PUBLIC) SPL_ME(Array, asort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, ksort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, uasort, arginfo_array_uXsort, ZEND_ACC_PUBLIC) SPL_ME(Array, uksort, arginfo_array_uXsort, ZEND_ACC_PUBLIC) SPL_ME(Array, natsort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, natcasesort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, unserialize, arginfo_array_unserialize, ZEND_ACC_PUBLIC) SPL_ME(Array, serialize, arginfo_array_void, ZEND_ACC_PUBLIC) /* ArrayIterator specific */ SPL_ME(Array, rewind, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, current, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, key, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, next, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, valid, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, seek, arginfo_array_seek, ZEND_ACC_PUBLIC) PHP_FE_END }; static const zend_function_entry spl_funcs_RecursiveArrayIterator[] = { SPL_ME(Array, hasChildren, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, getChildren, arginfo_array_void, ZEND_ACC_PUBLIC) PHP_FE_END }; /* }}} */ /* {{{ PHP_MINIT_FUNCTION(spl_array) */ PHP_MINIT_FUNCTION(spl_array) { REGISTER_SPL_STD_CLASS_EX(ArrayObject, spl_array_object_new, spl_funcs_ArrayObject); REGISTER_SPL_IMPLEMENTS(ArrayObject, Aggregate); REGISTER_SPL_IMPLEMENTS(ArrayObject, ArrayAccess); REGISTER_SPL_IMPLEMENTS(ArrayObject, Serializable); memcpy(&spl_handler_ArrayObject, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); spl_handler_ArrayObject.clone_obj = spl_array_object_clone; spl_handler_ArrayObject.read_dimension = spl_array_read_dimension; spl_handler_ArrayObject.write_dimension = spl_array_write_dimension; spl_handler_ArrayObject.unset_dimension = spl_array_unset_dimension; spl_handler_ArrayObject.has_dimension = spl_array_has_dimension; spl_handler_ArrayObject.count_elements = spl_array_object_count_elements; spl_handler_ArrayObject.get_properties = spl_array_get_properties; spl_handler_ArrayObject.get_debug_info = spl_array_get_debug_info; spl_handler_ArrayObject.read_property = spl_array_read_property; spl_handler_ArrayObject.write_property = spl_array_write_property; spl_handler_ArrayObject.get_property_ptr_ptr = spl_array_get_property_ptr_ptr; spl_handler_ArrayObject.has_property = spl_array_has_property; spl_handler_ArrayObject.unset_property = spl_array_unset_property; spl_handler_ArrayObject.compare_objects = spl_array_compare_objects; REGISTER_SPL_STD_CLASS_EX(ArrayIterator, spl_array_object_new, spl_funcs_ArrayIterator); REGISTER_SPL_IMPLEMENTS(ArrayIterator, Iterator); REGISTER_SPL_IMPLEMENTS(ArrayIterator, ArrayAccess); REGISTER_SPL_IMPLEMENTS(ArrayIterator, SeekableIterator); REGISTER_SPL_IMPLEMENTS(ArrayIterator, Serializable); memcpy(&spl_handler_ArrayIterator, &spl_handler_ArrayObject, sizeof(zend_object_handlers)); spl_ce_ArrayIterator->get_iterator = spl_array_get_iterator; REGISTER_SPL_SUB_CLASS_EX(RecursiveArrayIterator, ArrayIterator, spl_array_object_new, spl_funcs_RecursiveArrayIterator); REGISTER_SPL_IMPLEMENTS(RecursiveArrayIterator, RecursiveIterator); spl_ce_RecursiveArrayIterator->get_iterator = spl_array_get_iterator; REGISTER_SPL_IMPLEMENTS(ArrayObject, Countable); REGISTER_SPL_IMPLEMENTS(ArrayIterator, Countable); REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, "STD_PROP_LIST", SPL_ARRAY_STD_PROP_LIST); REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, "ARRAY_AS_PROPS", SPL_ARRAY_ARRAY_AS_PROPS); REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "STD_PROP_LIST", SPL_ARRAY_STD_PROP_LIST); REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "ARRAY_AS_PROPS", SPL_ARRAY_ARRAY_AS_PROPS); REGISTER_SPL_CLASS_CONST_LONG(RecursiveArrayIterator, "CHILD_ARRAYS_ONLY", SPL_ARRAY_CHILD_ARRAYS_ONLY); return SUCCESS; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: fdm=marker * vim: noet sw=4 ts=4 */ /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2012 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Marcus Boerger <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" #include "ext/standard/php_var.h" #include "ext/standard/php_smart_str.h" #include "zend_interfaces.h" #include "zend_exceptions.h" #include "php_spl.h" #include "spl_functions.h" #include "spl_engine.h" #include "spl_iterators.h" #include "spl_array.h" #include "spl_exceptions.h" zend_object_handlers spl_handler_ArrayObject; PHPAPI zend_class_entry *spl_ce_ArrayObject; zend_object_handlers spl_handler_ArrayIterator; PHPAPI zend_class_entry *spl_ce_ArrayIterator; PHPAPI zend_class_entry *spl_ce_RecursiveArrayIterator; #define SPL_ARRAY_STD_PROP_LIST 0x00000001 #define SPL_ARRAY_ARRAY_AS_PROPS 0x00000002 #define SPL_ARRAY_CHILD_ARRAYS_ONLY 0x00000004 #define SPL_ARRAY_OVERLOADED_REWIND 0x00010000 #define SPL_ARRAY_OVERLOADED_VALID 0x00020000 #define SPL_ARRAY_OVERLOADED_KEY 0x00040000 #define SPL_ARRAY_OVERLOADED_CURRENT 0x00080000 #define SPL_ARRAY_OVERLOADED_NEXT 0x00100000 #define SPL_ARRAY_IS_REF 0x01000000 #define SPL_ARRAY_IS_SELF 0x02000000 #define SPL_ARRAY_USE_OTHER 0x04000000 #define SPL_ARRAY_INT_MASK 0xFFFF0000 #define SPL_ARRAY_CLONE_MASK 0x0300FFFF typedef struct _spl_array_object { zend_object std; zval *array; zval *retval; HashPosition pos; ulong pos_h; int ar_flags; int is_self; zend_function *fptr_offset_get; zend_function *fptr_offset_set; zend_function *fptr_offset_has; zend_function *fptr_offset_del; zend_function *fptr_count; zend_class_entry* ce_get_iterator; HashTable *debug_info; unsigned char nApplyCount; } spl_array_object; static inline HashTable *spl_array_get_hash_table(spl_array_object* intern, int check_std_props TSRMLS_DC) { /* {{{ */ if ((intern->ar_flags & SPL_ARRAY_IS_SELF) != 0) { if (!intern->std.properties) { rebuild_object_properties(&intern->std); } return intern->std.properties; } else if ((intern->ar_flags & SPL_ARRAY_USE_OTHER) && (check_std_props == 0 || (intern->ar_flags & SPL_ARRAY_STD_PROP_LIST) == 0) && Z_TYPE_P(intern->array) == IS_OBJECT) { spl_array_object *other = (spl_array_object*)zend_object_store_get_object(intern->array TSRMLS_CC); return spl_array_get_hash_table(other, check_std_props TSRMLS_CC); } else if ((intern->ar_flags & ((check_std_props ? SPL_ARRAY_STD_PROP_LIST : 0) | SPL_ARRAY_IS_SELF)) != 0) { if (!intern->std.properties) { rebuild_object_properties(&intern->std); } return intern->std.properties; } else { return HASH_OF(intern->array); } } /* }}} */ static void spl_array_rewind(spl_array_object *intern TSRMLS_DC); static void spl_array_update_pos(spl_array_object* intern) /* {{{ */ { Bucket *pos = intern->pos; if (pos != NULL) { intern->pos_h = pos->h; } } /* }}} */ static void spl_array_set_pos(spl_array_object* intern, HashPosition pos) /* {{{ */ { intern->pos = pos; spl_array_update_pos(intern); } /* }}} */ SPL_API int spl_hash_verify_pos_ex(spl_array_object * intern, HashTable * ht TSRMLS_DC) /* {{{ */ { Bucket *p; /* IS_CONSISTENT(ht);*/ /* HASH_PROTECT_RECURSION(ht);*/ p = ht->arBuckets[intern->pos_h & ht->nTableMask]; while (p != NULL) { if (p == intern->pos) { return SUCCESS; } p = p->pNext; } /* HASH_UNPROTECT_RECURSION(ht); */ spl_array_rewind(intern TSRMLS_CC); return FAILURE; } /* }}} */ SPL_API int spl_hash_verify_pos(spl_array_object * intern TSRMLS_DC) /* {{{ */ { HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); return spl_hash_verify_pos_ex(intern, ht TSRMLS_CC); } /* }}} */ /* {{{ spl_array_object_free_storage */ static void spl_array_object_free_storage(void *object TSRMLS_DC) { spl_array_object *intern = (spl_array_object *)object; zend_object_std_dtor(&intern->std TSRMLS_CC); zval_ptr_dtor(&intern->array); zval_ptr_dtor(&intern->retval); if (intern->debug_info != NULL) { zend_hash_destroy(intern->debug_info); efree(intern->debug_info); } efree(object); } /* }}} */ zend_object_iterator *spl_array_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC); /* {{{ spl_array_object_new_ex */ static zend_object_value spl_array_object_new_ex(zend_class_entry *class_type, spl_array_object **obj, zval *orig, int clone_orig TSRMLS_DC) { zend_object_value retval; spl_array_object *intern; zval *tmp; zend_class_entry * parent = class_type; int inherited = 0; intern = emalloc(sizeof(spl_array_object)); memset(intern, 0, sizeof(spl_array_object)); *obj = intern; ALLOC_INIT_ZVAL(intern->retval); zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); intern->ar_flags = 0; intern->debug_info = NULL; intern->ce_get_iterator = spl_ce_ArrayIterator; if (orig) { spl_array_object *other = (spl_array_object*)zend_object_store_get_object(orig TSRMLS_CC); intern->ar_flags &= ~ SPL_ARRAY_CLONE_MASK; intern->ar_flags |= (other->ar_flags & SPL_ARRAY_CLONE_MASK); intern->ce_get_iterator = other->ce_get_iterator; if (clone_orig) { intern->array = other->array; if (Z_OBJ_HT_P(orig) == &spl_handler_ArrayObject) { MAKE_STD_ZVAL(intern->array); array_init(intern->array); zend_hash_copy(HASH_OF(intern->array), HASH_OF(other->array), (copy_ctor_func_t) zval_add_ref, &tmp, sizeof(zval*)); } if (Z_OBJ_HT_P(orig) == &spl_handler_ArrayIterator) { Z_ADDREF_P(other->array); } } else { intern->array = orig; Z_ADDREF_P(intern->array); intern->ar_flags |= SPL_ARRAY_IS_REF | SPL_ARRAY_USE_OTHER; } } else { MAKE_STD_ZVAL(intern->array); array_init(intern->array); intern->ar_flags &= ~SPL_ARRAY_IS_REF; } retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) spl_array_object_free_storage, NULL TSRMLS_CC); while (parent) { if (parent == spl_ce_ArrayIterator || parent == spl_ce_RecursiveArrayIterator) { retval.handlers = &spl_handler_ArrayIterator; class_type->get_iterator = spl_array_get_iterator; break; } else if (parent == spl_ce_ArrayObject) { retval.handlers = &spl_handler_ArrayObject; break; } parent = parent->parent; inherited = 1; } if (!parent) { /* this must never happen */ php_error_docref(NULL TSRMLS_CC, E_COMPILE_ERROR, "Internal compiler error, Class is not child of ArrayObject or ArrayIterator"); } if (inherited) { zend_hash_find(&class_type->function_table, "offsetget", sizeof("offsetget"), (void **) &intern->fptr_offset_get); if (intern->fptr_offset_get->common.scope == parent) { intern->fptr_offset_get = NULL; } zend_hash_find(&class_type->function_table, "offsetset", sizeof("offsetset"), (void **) &intern->fptr_offset_set); if (intern->fptr_offset_set->common.scope == parent) { intern->fptr_offset_set = NULL; } zend_hash_find(&class_type->function_table, "offsetexists", sizeof("offsetexists"), (void **) &intern->fptr_offset_has); if (intern->fptr_offset_has->common.scope == parent) { intern->fptr_offset_has = NULL; } zend_hash_find(&class_type->function_table, "offsetunset", sizeof("offsetunset"), (void **) &intern->fptr_offset_del); if (intern->fptr_offset_del->common.scope == parent) { intern->fptr_offset_del = NULL; } zend_hash_find(&class_type->function_table, "count", sizeof("count"), (void **) &intern->fptr_count); if (intern->fptr_count->common.scope == parent) { intern->fptr_count = NULL; } } /* Cache iterator functions if ArrayIterator or derived. Check current's */ /* cache since only current is always required */ if (retval.handlers == &spl_handler_ArrayIterator) { if (!class_type->iterator_funcs.zf_current) { zend_hash_find(&class_type->function_table, "rewind", sizeof("rewind"), (void **) &class_type->iterator_funcs.zf_rewind); zend_hash_find(&class_type->function_table, "valid", sizeof("valid"), (void **) &class_type->iterator_funcs.zf_valid); zend_hash_find(&class_type->function_table, "key", sizeof("key"), (void **) &class_type->iterator_funcs.zf_key); zend_hash_find(&class_type->function_table, "current", sizeof("current"), (void **) &class_type->iterator_funcs.zf_current); zend_hash_find(&class_type->function_table, "next", sizeof("next"), (void **) &class_type->iterator_funcs.zf_next); } if (inherited) { if (class_type->iterator_funcs.zf_rewind->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_REWIND; if (class_type->iterator_funcs.zf_valid->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_VALID; if (class_type->iterator_funcs.zf_key->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_KEY; if (class_type->iterator_funcs.zf_current->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_CURRENT; if (class_type->iterator_funcs.zf_next->common.scope != parent) intern->ar_flags |= SPL_ARRAY_OVERLOADED_NEXT; } } spl_array_rewind(intern TSRMLS_CC); return retval; } /* }}} */ /* {{{ spl_array_object_new */ static zend_object_value spl_array_object_new(zend_class_entry *class_type TSRMLS_DC) { spl_array_object *tmp; return spl_array_object_new_ex(class_type, &tmp, NULL, 0 TSRMLS_CC); } /* }}} */ /* {{{ spl_array_object_clone */ static zend_object_value spl_array_object_clone(zval *zobject TSRMLS_DC) { zend_object_value new_obj_val; zend_object *old_object; zend_object *new_object; zend_object_handle handle = Z_OBJ_HANDLE_P(zobject); spl_array_object *intern; old_object = zend_objects_get_address(zobject TSRMLS_CC); new_obj_val = spl_array_object_new_ex(old_object->ce, &intern, zobject, 1 TSRMLS_CC); new_object = &intern->std; zend_objects_clone_members(new_object, new_obj_val, old_object, handle TSRMLS_CC); return new_obj_val; } /* }}} */ static zval **spl_array_get_dimension_ptr_ptr(int check_inherited, zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); zval **retval; long index; HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); /* We cannot get the pointer pointer so we don't allow it here for now if (check_inherited && intern->fptr_offset_get) { return zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_get, "offsetGet", NULL, offset); }*/ if (!offset) { return &EG(uninitialized_zval_ptr); } if ((type == BP_VAR_W || type == BP_VAR_RW) && (ht->nApplyCount > 0)) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return &EG(uninitialized_zval_ptr);; } switch(Z_TYPE_P(offset)) { case IS_STRING: if (zend_symtable_find(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void **) &retval) == FAILURE) { if (type == BP_VAR_W || type == BP_VAR_RW) { zval *value; ALLOC_INIT_ZVAL(value); zend_symtable_update(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void**)&value, sizeof(void*), NULL); if (zend_symtable_find(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void **) &retval) != FAILURE) { return retval; } else { return &EG(uninitialized_zval_ptr); } } else { zend_error(E_NOTICE, "Undefined index: %s", Z_STRVAL_P(offset)); return &EG(uninitialized_zval_ptr); } } else { return retval; } case IS_DOUBLE: case IS_RESOURCE: case IS_BOOL: case IS_LONG: if (offset->type == IS_DOUBLE) { index = (long)Z_DVAL_P(offset); } else { index = Z_LVAL_P(offset); } if (zend_hash_index_find(ht, index, (void **) &retval) == FAILURE) { if (type == BP_VAR_W || type == BP_VAR_RW) { zval *value; ALLOC_INIT_ZVAL(value); zend_hash_index_update(ht, index, (void**)&value, sizeof(void*), NULL); if (zend_hash_index_find(ht, index, (void **) &retval) != FAILURE) { return retval; } else { return &EG(uninitialized_zval_ptr); } } else { zend_error(E_NOTICE, "Undefined offset: %ld", index); return &EG(uninitialized_zval_ptr); } } else { return retval; } break; default: zend_error(E_WARNING, "Illegal offset type"); return &EG(uninitialized_zval_ptr); } } /* }}} */ static zval *spl_array_read_dimension_ex(int check_inherited, zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */ { zval **ret; if (check_inherited) { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (intern->fptr_offset_get) { zval *rv; SEPARATE_ARG_IF_REF(offset); zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_get, "offsetGet", &rv, offset); zval_ptr_dtor(&offset); if (rv) { zval_ptr_dtor(&intern->retval); MAKE_STD_ZVAL(intern->retval); ZVAL_ZVAL(intern->retval, rv, 1, 1); return intern->retval; } return EG(uninitialized_zval_ptr); } } ret = spl_array_get_dimension_ptr_ptr(check_inherited, object, offset, type TSRMLS_CC); /* When in a write context, * ZE has to be fooled into thinking this is in a reference set * by separating (if necessary) and returning as an is_ref=1 zval (even if refcount == 1) */ if ((type == BP_VAR_W || type == BP_VAR_RW) && !Z_ISREF_PP(ret)) { if (Z_REFCOUNT_PP(ret) > 1) { zval *newval; /* Separate */ MAKE_STD_ZVAL(newval); *newval = **ret; zval_copy_ctor(newval); Z_SET_REFCOUNT_P(newval, 1); /* Replace */ Z_DELREF_PP(ret); *ret = newval; } Z_SET_ISREF_PP(ret); } return *ret; } /* }}} */ static zval *spl_array_read_dimension(zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */ { return spl_array_read_dimension_ex(1, object, offset, type TSRMLS_CC); } /* }}} */ static void spl_array_write_dimension_ex(int check_inherited, zval *object, zval *offset, zval *value TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); long index; HashTable *ht; if (check_inherited && intern->fptr_offset_set) { if (!offset) { ALLOC_INIT_ZVAL(offset); } else { SEPARATE_ARG_IF_REF(offset); } zend_call_method_with_2_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_set, "offsetSet", NULL, offset, value); zval_ptr_dtor(&offset); return; } if (!offset) { ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (ht->nApplyCount > 0) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return; } Z_ADDREF_P(value); zend_hash_next_index_insert(ht, (void**)&value, sizeof(void*), NULL); return; } switch(Z_TYPE_P(offset)) { case IS_STRING: ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (ht->nApplyCount > 0) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return; } Z_ADDREF_P(value); zend_symtable_update(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void**)&value, sizeof(void*), NULL); return; case IS_DOUBLE: case IS_RESOURCE: case IS_BOOL: case IS_LONG: ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (ht->nApplyCount > 0) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return; } if (offset->type == IS_DOUBLE) { index = (long)Z_DVAL_P(offset); } else { index = Z_LVAL_P(offset); } Z_ADDREF_P(value); zend_hash_index_update(ht, index, (void**)&value, sizeof(void*), NULL); return; case IS_NULL: ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (ht->nApplyCount > 0) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return; } Z_ADDREF_P(value); zend_hash_next_index_insert(ht, (void**)&value, sizeof(void*), NULL); return; default: zend_error(E_WARNING, "Illegal offset type"); return; } } /* }}} */ static void spl_array_write_dimension(zval *object, zval *offset, zval *value TSRMLS_DC) /* {{{ */ { spl_array_write_dimension_ex(1, object, offset, value TSRMLS_CC); } /* }}} */ static void spl_array_unset_dimension_ex(int check_inherited, zval *object, zval *offset TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); long index; HashTable *ht; if (check_inherited && intern->fptr_offset_del) { SEPARATE_ARG_IF_REF(offset); zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_del, "offsetUnset", NULL, offset); zval_ptr_dtor(&offset); return; } switch(Z_TYPE_P(offset)) { case IS_STRING: ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (ht->nApplyCount > 0) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return; } if (ht == &EG(symbol_table)) { if (zend_delete_global_variable(Z_STRVAL_P(offset), Z_STRLEN_P(offset) TSRMLS_CC)) { zend_error(E_NOTICE,"Undefined index: %s", Z_STRVAL_P(offset)); } } else { if (zend_symtable_del(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1) == FAILURE) { zend_error(E_NOTICE,"Undefined index: %s", Z_STRVAL_P(offset)); } else { spl_array_object *obj = intern; while (1) { if ((obj->ar_flags & SPL_ARRAY_IS_SELF) != 0) { break; } else if (Z_TYPE_P(obj->array) == IS_OBJECT) { if ((obj->ar_flags & SPL_ARRAY_USE_OTHER) == 0) { obj = (spl_array_object*)zend_object_store_get_object(obj->array TSRMLS_CC); break; } else { obj = (spl_array_object*)zend_object_store_get_object(obj->array TSRMLS_CC); } } else { obj = NULL; break; } } if (obj) { zend_property_info *property_info = zend_get_property_info(obj->std.ce, offset, 1 TSRMLS_CC); if (property_info && (property_info->flags & ZEND_ACC_STATIC) == 0 && property_info->offset >= 0) { obj->std.properties_table[property_info->offset] = NULL; } } } } break; case IS_DOUBLE: case IS_RESOURCE: case IS_BOOL: case IS_LONG: if (offset->type == IS_DOUBLE) { index = (long)Z_DVAL_P(offset); } else { index = Z_LVAL_P(offset); } ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (ht->nApplyCount > 0) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return; } if (zend_hash_index_del(ht, index) == FAILURE) { zend_error(E_NOTICE,"Undefined offset: %ld", Z_LVAL_P(offset)); } break; default: zend_error(E_WARNING, "Illegal offset type"); return; } spl_hash_verify_pos(intern TSRMLS_CC); /* call rewind on FAILURE */ } /* }}} */ static void spl_array_unset_dimension(zval *object, zval *offset TSRMLS_DC) /* {{{ */ { spl_array_unset_dimension_ex(1, object, offset TSRMLS_CC); } /* }}} */ static int spl_array_has_dimension_ex(int check_inherited, zval *object, zval *offset, int check_empty TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); long index; zval *rv, **tmp; if (check_inherited && intern->fptr_offset_has) { SEPARATE_ARG_IF_REF(offset); zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_has, "offsetExists", &rv, offset); zval_ptr_dtor(&offset); if (rv && zend_is_true(rv)) { zval_ptr_dtor(&rv); return 1; } if (rv) { zval_ptr_dtor(&rv); } return 0; } switch(Z_TYPE_P(offset)) { case IS_STRING: { HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_symtable_find(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void **) &tmp) != FAILURE) { switch (check_empty) { case 0: return Z_TYPE_PP(tmp) != IS_NULL; case 2: return 1; default: return zend_is_true(*tmp); } } } return 0; case IS_DOUBLE: case IS_RESOURCE: case IS_BOOL: case IS_LONG: { HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (offset->type == IS_DOUBLE) { index = (long)Z_DVAL_P(offset); } else { index = Z_LVAL_P(offset); } if (zend_hash_index_find(ht, index, (void **)&tmp) != FAILURE) { switch (check_empty) { case 0: return Z_TYPE_PP(tmp) != IS_NULL; case 2: return 1; default: return zend_is_true(*tmp); } } return 0; } default: zend_error(E_WARNING, "Illegal offset type"); } return 0; } /* }}} */ static int spl_array_has_dimension(zval *object, zval *offset, int check_empty TSRMLS_DC) /* {{{ */ { return spl_array_has_dimension_ex(1, object, offset, check_empty TSRMLS_CC); } /* }}} */ /* {{{ proto bool ArrayObject::offsetExists(mixed $index) proto bool ArrayIterator::offsetExists(mixed $index) Returns whether the requested $index exists. */ SPL_METHOD(Array, offsetExists) { zval *index; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &index) == FAILURE) { return; } RETURN_BOOL(spl_array_has_dimension_ex(0, getThis(), index, 0 TSRMLS_CC)); } /* }}} */ /* {{{ proto mixed ArrayObject::offsetGet(mixed $index) proto mixed ArrayIterator::offsetGet(mixed $index) Returns the value at the specified $index. */ SPL_METHOD(Array, offsetGet) { zval *index, *value; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &index) == FAILURE) { return; } value = spl_array_read_dimension_ex(0, getThis(), index, BP_VAR_R TSRMLS_CC); RETURN_ZVAL(value, 1, 0); } /* }}} */ /* {{{ proto void ArrayObject::offsetSet(mixed $index, mixed $newval) proto void ArrayIterator::offsetSet(mixed $index, mixed $newval) Sets the value at the specified $index to $newval. */ SPL_METHOD(Array, offsetSet) { zval *index, *value; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &index, &value) == FAILURE) { return; } spl_array_write_dimension_ex(0, getThis(), index, value TSRMLS_CC); } /* }}} */ void spl_array_iterator_append(zval *object, zval *append_value TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } if (Z_TYPE_P(intern->array) == IS_OBJECT) { php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "Cannot append properties to objects, use %s::offsetSet() instead", Z_OBJCE_P(object)->name); return; } spl_array_write_dimension(object, NULL, append_value TSRMLS_CC); if (!intern->pos) { spl_array_set_pos(intern, aht->pListTail); } } /* }}} */ /* {{{ proto void ArrayObject::append(mixed $newval) proto void ArrayIterator::append(mixed $newval) Appends the value (cannot be called for objects). */ SPL_METHOD(Array, append) { zval *value; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &value) == FAILURE) { return; } spl_array_iterator_append(getThis(), value TSRMLS_CC); } /* }}} */ /* {{{ proto void ArrayObject::offsetUnset(mixed $index) proto void ArrayIterator::offsetUnset(mixed $index) Unsets the value at the specified $index. */ SPL_METHOD(Array, offsetUnset) { zval *index; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &index) == FAILURE) { return; } spl_array_unset_dimension_ex(0, getThis(), index TSRMLS_CC); } /* }}} */ /* {{{ proto array ArrayObject::getArrayCopy() proto array ArrayIterator::getArrayCopy() Return a copy of the contained array */ SPL_METHOD(Array, getArrayCopy) { zval *object = getThis(), *tmp; spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); array_init(return_value); zend_hash_copy(HASH_OF(return_value), spl_array_get_hash_table(intern, 0 TSRMLS_CC), (copy_ctor_func_t) zval_add_ref, &tmp, sizeof(zval*)); } /* }}} */ static HashTable *spl_array_get_properties(zval *object TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *result; if (intern->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Nesting level too deep - recursive dependency?"); } intern->nApplyCount++; result = spl_array_get_hash_table(intern, 1 TSRMLS_CC); intern->nApplyCount--; return result; } /* }}} */ static HashTable* spl_array_get_debug_info(zval *obj, int *is_temp TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(obj TSRMLS_CC); zval *tmp, *storage; int name_len; char *zname; zend_class_entry *base; *is_temp = 0; if (!intern->std.properties) { rebuild_object_properties(&intern->std); } if (HASH_OF(intern->array) == intern->std.properties) { return intern->std.properties; } else { if (intern->debug_info == NULL) { ALLOC_HASHTABLE(intern->debug_info); ZEND_INIT_SYMTABLE_EX(intern->debug_info, zend_hash_num_elements(intern->std.properties) + 1, 0); } if (intern->debug_info->nApplyCount == 0) { zend_hash_clean(intern->debug_info); zend_hash_copy(intern->debug_info, intern->std.properties, (copy_ctor_func_t) zval_add_ref, (void *) &tmp, sizeof(zval *)); storage = intern->array; zval_add_ref(&storage); base = (Z_OBJ_HT_P(obj) == &spl_handler_ArrayIterator) ? spl_ce_ArrayIterator : spl_ce_ArrayObject; zname = spl_gen_private_prop_name(base, "storage", sizeof("storage")-1, &name_len TSRMLS_CC); zend_symtable_update(intern->debug_info, zname, name_len+1, &storage, sizeof(zval *), NULL); efree(zname); } return intern->debug_info; } } /* }}} */ static zval *spl_array_read_property(zval *object, zval *member, int type, const zend_literal *key TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0 && !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) { return spl_array_read_dimension(object, member, type TSRMLS_CC); } return std_object_handlers.read_property(object, member, type, key TSRMLS_CC); } /* }}} */ static void spl_array_write_property(zval *object, zval *member, zval *value, const zend_literal *key TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0 && !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) { spl_array_write_dimension(object, member, value TSRMLS_CC); return; } std_object_handlers.write_property(object, member, value, key TSRMLS_CC); } /* }}} */ static zval **spl_array_get_property_ptr_ptr(zval *object, zval *member, const zend_literal *key TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0 && !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) { return spl_array_get_dimension_ptr_ptr(1, object, member, BP_VAR_RW TSRMLS_CC); } return std_object_handlers.get_property_ptr_ptr(object, member, key TSRMLS_CC); } /* }}} */ static int spl_array_has_property(zval *object, zval *member, int has_set_exists, const zend_literal *key TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0 && !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) { return spl_array_has_dimension(object, member, has_set_exists TSRMLS_CC); } return std_object_handlers.has_property(object, member, has_set_exists, key TSRMLS_CC); } /* }}} */ static void spl_array_unset_property(zval *object, zval *member, const zend_literal *key TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if ((intern->ar_flags & SPL_ARRAY_ARRAY_AS_PROPS) != 0 && !std_object_handlers.has_property(object, member, 2, key TSRMLS_CC)) { spl_array_unset_dimension(object, member TSRMLS_CC); spl_array_rewind(intern TSRMLS_CC); /* because deletion might invalidate position */ return; } std_object_handlers.unset_property(object, member, key TSRMLS_CC); } /* }}} */ static int spl_array_compare_objects(zval *o1, zval *o2 TSRMLS_DC) /* {{{ */ { HashTable *ht1, *ht2; spl_array_object *intern1, *intern2; int result = 0; zval temp_zv; intern1 = (spl_array_object*)zend_object_store_get_object(o1 TSRMLS_CC); intern2 = (spl_array_object*)zend_object_store_get_object(o2 TSRMLS_CC); ht1 = spl_array_get_hash_table(intern1, 0 TSRMLS_CC); ht2 = spl_array_get_hash_table(intern2, 0 TSRMLS_CC); zend_compare_symbol_tables(&temp_zv, ht1, ht2 TSRMLS_CC); result = (int)Z_LVAL(temp_zv); /* if we just compared std.properties, don't do it again */ if (result == 0 && !(ht1 == intern1->std.properties && ht2 == intern2->std.properties)) { result = std_object_handlers.compare_objects(o1, o2 TSRMLS_CC); } return result; } /* }}} */ static int spl_array_skip_protected(spl_array_object *intern, HashTable *aht TSRMLS_DC) /* {{{ */ { char *string_key; uint string_length; ulong num_key; if (Z_TYPE_P(intern->array) == IS_OBJECT) { do { if (zend_hash_get_current_key_ex(aht, &string_key, &string_length, &num_key, 0, &intern->pos) == HASH_KEY_IS_STRING) { if (!string_length || string_key[0]) { return SUCCESS; } } else { return SUCCESS; } if (zend_hash_has_more_elements_ex(aht, &intern->pos) != SUCCESS) { return FAILURE; } zend_hash_move_forward_ex(aht, &intern->pos); spl_array_update_pos(intern); } while (1); } return FAILURE; } /* }}} */ static int spl_array_next_no_verify(spl_array_object *intern, HashTable *aht TSRMLS_DC) /* {{{ */ { zend_hash_move_forward_ex(aht, &intern->pos); spl_array_update_pos(intern); if (Z_TYPE_P(intern->array) == IS_OBJECT) { return spl_array_skip_protected(intern, aht TSRMLS_CC); } else { return zend_hash_has_more_elements_ex(aht, &intern->pos); } } /* }}} */ static int spl_array_next_ex(spl_array_object *intern, HashTable *aht TSRMLS_DC) /* {{{ */ { if ((intern->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(intern, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and internal position is no longer valid"); return FAILURE; } return spl_array_next_no_verify(intern, aht TSRMLS_CC); } /* }}} */ static int spl_array_next(spl_array_object *intern TSRMLS_DC) /* {{{ */ { HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); return spl_array_next_ex(intern, aht TSRMLS_CC); } /* }}} */ /* define an overloaded iterator structure */ typedef struct { zend_user_iterator intern; spl_array_object *object; } spl_array_it; static void spl_array_it_dtor(zend_object_iterator *iter TSRMLS_DC) /* {{{ */ { spl_array_it *iterator = (spl_array_it *)iter; zend_user_it_invalidate_current(iter TSRMLS_CC); zval_ptr_dtor((zval**)&iterator->intern.it.data); efree(iterator); } /* }}} */ static int spl_array_it_valid(zend_object_iterator *iter TSRMLS_DC) /* {{{ */ { spl_array_it *iterator = (spl_array_it *)iter; spl_array_object *object = iterator->object; HashTable *aht = spl_array_get_hash_table(object, 0 TSRMLS_CC); if (object->ar_flags & SPL_ARRAY_OVERLOADED_VALID) { return zend_user_it_valid(iter TSRMLS_CC); } else { if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::valid(): Array was modified outside object and is no longer an array"); return FAILURE; } if (object->pos && (object->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(object, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::valid(): Array was modified outside object and internal position is no longer valid"); return FAILURE; } else { return zend_hash_has_more_elements_ex(aht, &object->pos); } } } /* }}} */ static void spl_array_it_get_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC) /* {{{ */ { spl_array_it *iterator = (spl_array_it *)iter; spl_array_object *object = iterator->object; HashTable *aht = spl_array_get_hash_table(object, 0 TSRMLS_CC); if (object->ar_flags & SPL_ARRAY_OVERLOADED_CURRENT) { zend_user_it_get_current_data(iter, data TSRMLS_CC); } else { if (zend_hash_get_current_data_ex(aht, (void**)data, &object->pos) == FAILURE) { *data = NULL; } } } /* }}} */ static int spl_array_it_get_current_key(zend_object_iterator *iter, char **str_key, uint *str_key_len, ulong *int_key TSRMLS_DC) /* {{{ */ { spl_array_it *iterator = (spl_array_it *)iter; spl_array_object *object = iterator->object; HashTable *aht = spl_array_get_hash_table(object, 0 TSRMLS_CC); if (object->ar_flags & SPL_ARRAY_OVERLOADED_KEY) { return zend_user_it_get_current_key(iter, str_key, str_key_len, int_key TSRMLS_CC); } else { if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::current(): Array was modified outside object and is no longer an array"); return HASH_KEY_NON_EXISTANT; } if ((object->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(object, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::current(): Array was modified outside object and internal position is no longer valid"); return HASH_KEY_NON_EXISTANT; } return zend_hash_get_current_key_ex(aht, str_key, str_key_len, int_key, 1, &object->pos); } } /* }}} */ static void spl_array_it_move_forward(zend_object_iterator *iter TSRMLS_DC) /* {{{ */ { spl_array_it *iterator = (spl_array_it *)iter; spl_array_object *object = iterator->object; HashTable *aht = spl_array_get_hash_table(object, 0 TSRMLS_CC); if (object->ar_flags & SPL_ARRAY_OVERLOADED_NEXT) { zend_user_it_move_forward(iter TSRMLS_CC); } else { zend_user_it_invalidate_current(iter TSRMLS_CC); if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::current(): Array was modified outside object and is no longer an array"); return; } if ((object->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(object, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::next(): Array was modified outside object and internal position is no longer valid"); } else { spl_array_next_no_verify(object, aht TSRMLS_CC); } } } /* }}} */ static void spl_array_rewind_ex(spl_array_object *intern, HashTable *aht TSRMLS_DC) /* {{{ */ { zend_hash_internal_pointer_reset_ex(aht, &intern->pos); spl_array_update_pos(intern); spl_array_skip_protected(intern, aht TSRMLS_CC); } /* }}} */ static void spl_array_rewind(spl_array_object *intern TSRMLS_DC) /* {{{ */ { HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ArrayIterator::rewind(): Array was modified outside object and is no longer an array"); return; } spl_array_rewind_ex(intern, aht TSRMLS_CC); } /* }}} */ static void spl_array_it_rewind(zend_object_iterator *iter TSRMLS_DC) /* {{{ */ { spl_array_it *iterator = (spl_array_it *)iter; spl_array_object *object = iterator->object; if (object->ar_flags & SPL_ARRAY_OVERLOADED_REWIND) { zend_user_it_rewind(iter TSRMLS_CC); } else { zend_user_it_invalidate_current(iter TSRMLS_CC); spl_array_rewind(object TSRMLS_CC); } } /* }}} */ /* {{{ spl_array_set_array */ static void spl_array_set_array(zval *object, spl_array_object *intern, zval **array, long ar_flags, int just_array TSRMLS_DC) { if (Z_TYPE_PP(array) == IS_ARRAY) { SEPARATE_ZVAL_IF_NOT_REF(array); } if (Z_TYPE_PP(array) == IS_OBJECT && (Z_OBJ_HT_PP(array) == &spl_handler_ArrayObject || Z_OBJ_HT_PP(array) == &spl_handler_ArrayIterator)) { zval_ptr_dtor(&intern->array); if (just_array) { spl_array_object *other = (spl_array_object*)zend_object_store_get_object(*array TSRMLS_CC); ar_flags = other->ar_flags & ~SPL_ARRAY_INT_MASK; } ar_flags |= SPL_ARRAY_USE_OTHER; intern->array = *array; } else { if (Z_TYPE_PP(array) != IS_OBJECT && Z_TYPE_PP(array) != IS_ARRAY) { zend_throw_exception(spl_ce_InvalidArgumentException, "Passed variable is not an array or object, using empty array instead", 0 TSRMLS_CC); return; } zval_ptr_dtor(&intern->array); intern->array = *array; } if (object == *array) { intern->ar_flags |= SPL_ARRAY_IS_SELF; intern->ar_flags &= ~SPL_ARRAY_USE_OTHER; } else { intern->ar_flags &= ~SPL_ARRAY_IS_SELF; } intern->ar_flags |= ar_flags; Z_ADDREF_P(intern->array); if (Z_TYPE_PP(array) == IS_OBJECT) { zend_object_get_properties_t handler = Z_OBJ_HANDLER_PP(array, get_properties); if ((handler != std_object_handlers.get_properties && handler != spl_array_get_properties) || !spl_array_get_hash_table(intern, 0 TSRMLS_CC)) { zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0 TSRMLS_CC, "Overloaded object of type %s is not compatible with %s", Z_OBJCE_PP(array)->name, intern->std.ce->name); } } spl_array_rewind(intern TSRMLS_CC); } /* }}} */ /* iterator handler table */ zend_object_iterator_funcs spl_array_it_funcs = { spl_array_it_dtor, spl_array_it_valid, spl_array_it_get_current_data, spl_array_it_get_current_key, spl_array_it_move_forward, spl_array_it_rewind }; zend_object_iterator *spl_array_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) /* {{{ */ { spl_array_it *iterator; spl_array_object *array_object = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (by_ref && (array_object->ar_flags & SPL_ARRAY_OVERLOADED_CURRENT)) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } iterator = emalloc(sizeof(spl_array_it)); Z_ADDREF_P(object); iterator->intern.it.data = (void*)object; iterator->intern.it.funcs = &spl_array_it_funcs; iterator->intern.ce = ce; iterator->intern.value = NULL; iterator->object = array_object; return (zend_object_iterator*)iterator; } /* }}} */ /* {{{ proto void ArrayObject::__construct(array|object ar = array() [, int flags = 0 [, string iterator_class = "ArrayIterator"]]) proto void ArrayIterator::__construct(array|object ar = array() [, int flags = 0]) Constructs a new array iterator from a path. */ SPL_METHOD(Array, __construct) { zval *object = getThis(); spl_array_object *intern; zval **array; long ar_flags = 0; zend_class_entry *ce_get_iterator = spl_ce_Iterator; zend_error_handling error_handling; if (ZEND_NUM_ARGS() == 0) { return; /* nothing to do */ } zend_replace_error_handling(EH_THROW, spl_ce_InvalidArgumentException, &error_handling TSRMLS_CC); intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z|lC", &array, &ar_flags, &ce_get_iterator) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (ZEND_NUM_ARGS() > 2) { intern->ce_get_iterator = ce_get_iterator; } ar_flags &= ~SPL_ARRAY_INT_MASK; spl_array_set_array(object, intern, array, ar_flags, ZEND_NUM_ARGS() == 1 TSRMLS_CC); zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void ArrayObject::setIteratorClass(string iterator_class) Set the class used in getIterator. */ SPL_METHOD(Array, setIteratorClass) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); zend_class_entry * ce_get_iterator = spl_ce_Iterator; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "C", &ce_get_iterator) == FAILURE) { return; } intern->ce_get_iterator = ce_get_iterator; } /* }}} */ /* {{{ proto string ArrayObject::getIteratorClass() Get the class used in getIterator. */ SPL_METHOD(Array, getIteratorClass) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_STRING(intern->ce_get_iterator->name, 1); } /* }}} */ /* {{{ proto int ArrayObject::getFlags() Get flags */ SPL_METHOD(Array, getFlags) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(intern->ar_flags & ~SPL_ARRAY_INT_MASK); } /* }}} */ /* {{{ proto void ArrayObject::setFlags(int flags) Set flags */ SPL_METHOD(Array, setFlags) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); long ar_flags = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &ar_flags) == FAILURE) { return; } intern->ar_flags = (intern->ar_flags & SPL_ARRAY_INT_MASK) | (ar_flags & ~SPL_ARRAY_INT_MASK); } /* }}} */ /* {{{ proto Array|Object ArrayObject::exchangeArray(Array|Object ar = array()) Replace the referenced array or object with a new one and return the old one (right now copy - to be changed) */ SPL_METHOD(Array, exchangeArray) { zval *object = getThis(), *tmp, **array; spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); array_init(return_value); zend_hash_copy(HASH_OF(return_value), spl_array_get_hash_table(intern, 0 TSRMLS_CC), (copy_ctor_func_t) zval_add_ref, &tmp, sizeof(zval*)); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z", &array) == FAILURE) { return; } spl_array_set_array(object, intern, array, 0L, 1 TSRMLS_CC); } /* }}} */ /* {{{ proto ArrayIterator ArrayObject::getIterator() Create a new iterator from a ArrayObject instance */ SPL_METHOD(Array, getIterator) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); spl_array_object *iterator; HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } return_value->type = IS_OBJECT; return_value->value.obj = spl_array_object_new_ex(intern->ce_get_iterator, &iterator, object, 0 TSRMLS_CC); Z_SET_REFCOUNT_P(return_value, 1); Z_SET_ISREF_P(return_value); } /* }}} */ /* {{{ proto void ArrayIterator::rewind() Rewind array back to the start */ SPL_METHOD(Array, rewind) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } spl_array_rewind(intern TSRMLS_CC); } /* }}} */ /* {{{ proto void ArrayIterator::seek(int $position) Seek to position. */ SPL_METHOD(Array, seek) { long opos, position; zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); int result; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &position) == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } opos = position; if (position >= 0) { /* negative values are not supported */ spl_array_rewind(intern TSRMLS_CC); result = SUCCESS; while (position-- > 0 && (result = spl_array_next(intern TSRMLS_CC)) == SUCCESS); if (result == SUCCESS && zend_hash_has_more_elements_ex(aht, &intern->pos) == SUCCESS) { return; /* ok */ } } zend_throw_exception_ex(spl_ce_OutOfBoundsException, 0 TSRMLS_CC, "Seek position %ld is out of range", opos); } /* }}} */ int static spl_array_object_count_elements_helper(spl_array_object *intern, long *count TSRMLS_DC) /* {{{ */ { HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); HashPosition pos; if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); *count = 0; return FAILURE; } if (Z_TYPE_P(intern->array) == IS_OBJECT) { /* We need to store the 'pos' since we'll modify it in the functions * we're going to call and which do not support 'pos' as parameter. */ pos = intern->pos; *count = 0; spl_array_rewind(intern TSRMLS_CC); while(intern->pos && spl_array_next(intern TSRMLS_CC) == SUCCESS) { (*count)++; } spl_array_set_pos(intern, pos); return SUCCESS; } else { *count = zend_hash_num_elements(aht); return SUCCESS; } } /* }}} */ int spl_array_object_count_elements(zval *object, long *count TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); if (intern->fptr_count) { zval *rv; zend_call_method_with_0_params(&object, intern->std.ce, &intern->fptr_count, "count", &rv); if (rv) { zval_ptr_dtor(&intern->retval); MAKE_STD_ZVAL(intern->retval); ZVAL_ZVAL(intern->retval, rv, 1, 1); convert_to_long(intern->retval); *count = (long) Z_LVAL_P(intern->retval); return SUCCESS; } *count = 0; return FAILURE; } return spl_array_object_count_elements_helper(intern, count TSRMLS_CC); } /* }}} */ /* {{{ proto int ArrayObject::count() proto int ArrayIterator::count() Return the number of elements in the Iterator. */ SPL_METHOD(Array, count) { long count; spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } spl_array_object_count_elements_helper(intern, &count TSRMLS_CC); RETURN_LONG(count); } /* }}} */ static void spl_array_method(INTERNAL_FUNCTION_PARAMETERS, char *fname, int fname_len, int use_arg) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(getThis() TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); zval *tmp, *arg; zval *retval_ptr = NULL; MAKE_STD_ZVAL(tmp); Z_TYPE_P(tmp) = IS_ARRAY; Z_ARRVAL_P(tmp) = aht; if (use_arg) { if (ZEND_NUM_ARGS() != 1 || zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "z", &arg) == FAILURE) { Z_TYPE_P(tmp) = IS_NULL; zval_ptr_dtor(&tmp); zend_throw_exception(spl_ce_BadMethodCallException, "Function expects exactly one argument", 0 TSRMLS_CC); return; } aht->nApplyCount++; zend_call_method(NULL, NULL, NULL, fname, fname_len, &retval_ptr, 2, tmp, arg TSRMLS_CC); aht->nApplyCount--; } else { aht->nApplyCount++; zend_call_method(NULL, NULL, NULL, fname, fname_len, &retval_ptr, 1, tmp, NULL TSRMLS_CC); aht->nApplyCount--; } Z_TYPE_P(tmp) = IS_NULL; /* we want to destroy the zval, not the hashtable */ zval_ptr_dtor(&tmp); if (retval_ptr) { COPY_PZVAL_TO_ZVAL(*return_value, retval_ptr); } } /* }}} */ #define SPL_ARRAY_METHOD(cname, fname, use_arg) \ SPL_METHOD(cname, fname) \ { \ spl_array_method(INTERNAL_FUNCTION_PARAM_PASSTHRU, #fname, sizeof(#fname)-1, use_arg); \ } /* {{{ proto int ArrayObject::asort() proto int ArrayIterator::asort() Sort the entries by values. */ SPL_ARRAY_METHOD(Array, asort, 0) /* }}} */ /* {{{ proto int ArrayObject::ksort() proto int ArrayIterator::ksort() Sort the entries by key. */ SPL_ARRAY_METHOD(Array, ksort, 0) /* }}} */ /* {{{ proto int ArrayObject::uasort(callback cmp_function) proto int ArrayIterator::uasort(callback cmp_function) Sort the entries by values user defined function. */ SPL_ARRAY_METHOD(Array, uasort, 1) /* }}} */ /* {{{ proto int ArrayObject::uksort(callback cmp_function) proto int ArrayIterator::uksort(callback cmp_function) Sort the entries by key using user defined function. */ SPL_ARRAY_METHOD(Array, uksort, 1) /* }}} */ /* {{{ proto int ArrayObject::natsort() proto int ArrayIterator::natsort() Sort the entries by values using "natural order" algorithm. */ SPL_ARRAY_METHOD(Array, natsort, 0) /* }}} */ /* {{{ proto int ArrayObject::natcasesort() proto int ArrayIterator::natcasesort() Sort the entries by key using case insensitive "natural order" algorithm. */ SPL_ARRAY_METHOD(Array, natcasesort, 0) /* }}} */ /* {{{ proto mixed|NULL ArrayIterator::current() Return current array entry */ SPL_METHOD(Array, current) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); zval **entry; HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } if ((intern->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(intern, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and internal position is no longer valid"); return; } if (zend_hash_get_current_data_ex(aht, (void **) &entry, &intern->pos) == FAILURE) { return; } RETVAL_ZVAL(*entry, 1, 0); } /* }}} */ /* {{{ proto mixed|NULL ArrayIterator::key() Return current array key */ SPL_METHOD(Array, key) { if (zend_parse_parameters_none() == FAILURE) { return; } spl_array_iterator_key(getThis(), return_value TSRMLS_CC); } /* }}} */ void spl_array_iterator_key(zval *object, zval *return_value TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); char *string_key; uint string_length; ulong num_key; HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } if ((intern->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(intern, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and internal position is no longer valid"); return; } switch (zend_hash_get_current_key_ex(aht, &string_key, &string_length, &num_key, 1, &intern->pos)) { case HASH_KEY_IS_STRING: RETVAL_STRINGL(string_key, string_length - 1, 0); break; case HASH_KEY_IS_LONG: RETVAL_LONG(num_key); break; case HASH_KEY_NON_EXISTANT: return; } } /* }}} */ /* {{{ proto void ArrayIterator::next() Move to next entry */ SPL_METHOD(Array, next) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } spl_array_next_ex(intern, aht TSRMLS_CC); } /* }}} */ /* {{{ proto bool ArrayIterator::valid() Check whether array contains more entries */ SPL_METHOD(Array, valid) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } if (intern->pos && (intern->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(intern, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and internal position is no longer valid"); RETURN_FALSE; } else { RETURN_BOOL(zend_hash_has_more_elements_ex(aht, &intern->pos) == SUCCESS); } } /* }}} */ /* {{{ proto bool RecursiveArrayIterator::hasChildren() Check whether current element has children (e.g. is an array) */ SPL_METHOD(Array, hasChildren) { zval *object = getThis(), **entry; spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); RETURN_FALSE; } if ((intern->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(intern, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and internal position is no longer valid"); RETURN_FALSE; } if (zend_hash_get_current_data_ex(aht, (void **) &entry, &intern->pos) == FAILURE) { RETURN_FALSE; } RETURN_BOOL(Z_TYPE_PP(entry) == IS_ARRAY || (Z_TYPE_PP(entry) == IS_OBJECT && (intern->ar_flags & SPL_ARRAY_CHILD_ARRAYS_ONLY) == 0)); } /* }}} */ /* {{{ proto object RecursiveArrayIterator::getChildren() Create a sub iterator for the current element (same class as $this) */ SPL_METHOD(Array, getChildren) { zval *object = getThis(), **entry, *flags; spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } if ((intern->ar_flags & SPL_ARRAY_IS_REF) && spl_hash_verify_pos_ex(intern, aht TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and internal position is no longer valid"); return; } if (zend_hash_get_current_data_ex(aht, (void **) &entry, &intern->pos) == FAILURE) { return; } if (Z_TYPE_PP(entry) == IS_OBJECT) { if ((intern->ar_flags & SPL_ARRAY_CHILD_ARRAYS_ONLY) != 0) { return; } if (instanceof_function(Z_OBJCE_PP(entry), Z_OBJCE_P(getThis()) TSRMLS_CC)) { RETURN_ZVAL(*entry, 0, 0); } } MAKE_STD_ZVAL(flags); ZVAL_LONG(flags, SPL_ARRAY_USE_OTHER | intern->ar_flags); spl_instantiate_arg_ex2(Z_OBJCE_P(getThis()), &return_value, 0, *entry, flags TSRMLS_CC); zval_ptr_dtor(&flags); } /* }}} */ /* {{{ proto string ArrayObject::serialize() Serialize the object */ SPL_METHOD(Array, serialize) { zval *object = getThis(); spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); zval members, *pmembers; php_serialize_data_t var_hash; smart_str buf = {0}; zval *flags; if (zend_parse_parameters_none() == FAILURE) { return; } if (!aht) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Array was modified outside object and is no longer an array"); return; } PHP_VAR_SERIALIZE_INIT(var_hash); MAKE_STD_ZVAL(flags); ZVAL_LONG(flags, (intern->ar_flags & SPL_ARRAY_CLONE_MASK)); /* storage */ smart_str_appendl(&buf, "x:", 2); php_var_serialize(&buf, &flags, &var_hash TSRMLS_CC); zval_ptr_dtor(&flags); if (!(intern->ar_flags & SPL_ARRAY_IS_SELF)) { php_var_serialize(&buf, &intern->array, &var_hash TSRMLS_CC); smart_str_appendc(&buf, ';'); } /* members */ smart_str_appendl(&buf, "m:", 2); INIT_PZVAL(&members); if (!intern->std.properties) { rebuild_object_properties(&intern->std); } Z_ARRVAL(members) = intern->std.properties; Z_TYPE(members) = IS_ARRAY; pmembers = &members; php_var_serialize(&buf, &pmembers, &var_hash TSRMLS_CC); /* finishes the string */ /* done */ PHP_VAR_SERIALIZE_DESTROY(var_hash); if (buf.c) { RETURN_STRINGL(buf.c, buf.len, 0); } RETURN_NULL(); } /* }}} */ /* {{{ proto void ArrayObject::unserialize(string serialized) * unserialize the object */ SPL_METHOD(Array, unserialize) { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *buf; int buf_len; const unsigned char *p, *s; php_unserialize_data_t var_hash; zval *pmembers, *pflags = NULL; long flags; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &buf, &buf_len) == FAILURE) { return; } if (buf_len == 0) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Empty serialized string cannot be empty"); return; } /* storage */ s = p = (const unsigned char*)buf; PHP_VAR_UNSERIALIZE_INIT(var_hash); if (*p!= 'x' || *++p != ':') { goto outexcept; } ++p; ALLOC_INIT_ZVAL(pflags); if (!php_var_unserialize(&pflags, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pflags) != IS_LONG) { zval_ptr_dtor(&pflags); goto outexcept; } --p; /* for ';' */ flags = Z_LVAL_P(pflags); zval_ptr_dtor(&pflags); /* flags needs to be verified and we also need to verify whether the next * thing we get is ';'. After that we require an 'm' or somethign else * where 'm' stands for members and anything else should be an array. If * neither 'a' or 'm' follows we have an error. */ if (*p != ';') { goto outexcept; } ++p; if (*p!='m') { if (*p!='a' && *p!='O' && *p!='C') { goto outexcept; } intern->ar_flags &= ~SPL_ARRAY_CLONE_MASK; intern->ar_flags |= flags & SPL_ARRAY_CLONE_MASK; zval_ptr_dtor(&intern->array); ALLOC_INIT_ZVAL(intern->array); if (!php_var_unserialize(&intern->array, &p, s + buf_len, &var_hash TSRMLS_CC)) { goto outexcept; } } if (*p != ';') { goto outexcept; } ++p; /* members */ if (*p!= 'm' || *++p != ':') { goto outexcept; } ++p; ALLOC_INIT_ZVAL(pmembers); if (!php_var_unserialize(&pmembers, &p, s + buf_len, &var_hash TSRMLS_CC)) { zval_ptr_dtor(&pmembers); goto outexcept; } /* copy members */ if (!intern->std.properties) { rebuild_object_properties(&intern->std); } zend_hash_copy(intern->std.properties, Z_ARRVAL_P(pmembers), (copy_ctor_func_t) zval_add_ref, (void *) NULL, sizeof(zval *)); zval_ptr_dtor(&pmembers); /* done reading $serialized */ PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return; outexcept: PHP_VAR_UNSERIALIZE_DESTROY(var_hash); zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Error at offset %ld of %d bytes", (long)((char*)p - buf), buf_len); return; } /* }}} */ /* {{{ arginfo and function tbale */ ZEND_BEGIN_ARG_INFO(arginfo_array___construct, 0) ZEND_ARG_INFO(0, array) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_offsetGet, 0, 0, 1) ZEND_ARG_INFO(0, index) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_array_offsetSet, 0, 0, 2) ZEND_ARG_INFO(0, index) ZEND_ARG_INFO(0, newval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_append, 0) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_seek, 0) ZEND_ARG_INFO(0, position) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_exchangeArray, 0) ZEND_ARG_INFO(0, array) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_setFlags, 0) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_setIteratorClass, 0) ZEND_ARG_INFO(0, iteratorClass) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_array_uXsort, 0) ZEND_ARG_INFO(0, cmp_function) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO(arginfo_array_unserialize, 0) ZEND_ARG_INFO(0, serialized) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO(arginfo_array_void, 0) ZEND_END_ARG_INFO() static const zend_function_entry spl_funcs_ArrayObject[] = { SPL_ME(Array, __construct, arginfo_array___construct, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetExists, arginfo_array_offsetGet, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetGet, arginfo_array_offsetGet, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetSet, arginfo_array_offsetSet, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetUnset, arginfo_array_offsetGet, ZEND_ACC_PUBLIC) SPL_ME(Array, append, arginfo_array_append, ZEND_ACC_PUBLIC) SPL_ME(Array, getArrayCopy, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, count, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, getFlags, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, setFlags, arginfo_array_setFlags, ZEND_ACC_PUBLIC) SPL_ME(Array, asort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, ksort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, uasort, arginfo_array_uXsort, ZEND_ACC_PUBLIC) SPL_ME(Array, uksort, arginfo_array_uXsort, ZEND_ACC_PUBLIC) SPL_ME(Array, natsort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, natcasesort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, unserialize, arginfo_array_unserialize, ZEND_ACC_PUBLIC) SPL_ME(Array, serialize, arginfo_array_void, ZEND_ACC_PUBLIC) /* ArrayObject specific */ SPL_ME(Array, getIterator, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, exchangeArray, arginfo_array_exchangeArray, ZEND_ACC_PUBLIC) SPL_ME(Array, setIteratorClass, arginfo_array_setIteratorClass, ZEND_ACC_PUBLIC) SPL_ME(Array, getIteratorClass, arginfo_array_void, ZEND_ACC_PUBLIC) PHP_FE_END }; static const zend_function_entry spl_funcs_ArrayIterator[] = { SPL_ME(Array, __construct, arginfo_array___construct, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetExists, arginfo_array_offsetGet, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetGet, arginfo_array_offsetGet, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetSet, arginfo_array_offsetSet, ZEND_ACC_PUBLIC) SPL_ME(Array, offsetUnset, arginfo_array_offsetGet, ZEND_ACC_PUBLIC) SPL_ME(Array, append, arginfo_array_append, ZEND_ACC_PUBLIC) SPL_ME(Array, getArrayCopy, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, count, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, getFlags, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, setFlags, arginfo_array_setFlags, ZEND_ACC_PUBLIC) SPL_ME(Array, asort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, ksort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, uasort, arginfo_array_uXsort, ZEND_ACC_PUBLIC) SPL_ME(Array, uksort, arginfo_array_uXsort, ZEND_ACC_PUBLIC) SPL_ME(Array, natsort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, natcasesort, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, unserialize, arginfo_array_unserialize, ZEND_ACC_PUBLIC) SPL_ME(Array, serialize, arginfo_array_void, ZEND_ACC_PUBLIC) /* ArrayIterator specific */ SPL_ME(Array, rewind, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, current, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, key, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, next, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, valid, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, seek, arginfo_array_seek, ZEND_ACC_PUBLIC) PHP_FE_END }; static const zend_function_entry spl_funcs_RecursiveArrayIterator[] = { SPL_ME(Array, hasChildren, arginfo_array_void, ZEND_ACC_PUBLIC) SPL_ME(Array, getChildren, arginfo_array_void, ZEND_ACC_PUBLIC) PHP_FE_END }; /* }}} */ /* {{{ PHP_MINIT_FUNCTION(spl_array) */ PHP_MINIT_FUNCTION(spl_array) { REGISTER_SPL_STD_CLASS_EX(ArrayObject, spl_array_object_new, spl_funcs_ArrayObject); REGISTER_SPL_IMPLEMENTS(ArrayObject, Aggregate); REGISTER_SPL_IMPLEMENTS(ArrayObject, ArrayAccess); REGISTER_SPL_IMPLEMENTS(ArrayObject, Serializable); memcpy(&spl_handler_ArrayObject, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); spl_handler_ArrayObject.clone_obj = spl_array_object_clone; spl_handler_ArrayObject.read_dimension = spl_array_read_dimension; spl_handler_ArrayObject.write_dimension = spl_array_write_dimension; spl_handler_ArrayObject.unset_dimension = spl_array_unset_dimension; spl_handler_ArrayObject.has_dimension = spl_array_has_dimension; spl_handler_ArrayObject.count_elements = spl_array_object_count_elements; spl_handler_ArrayObject.get_properties = spl_array_get_properties; spl_handler_ArrayObject.get_debug_info = spl_array_get_debug_info; spl_handler_ArrayObject.read_property = spl_array_read_property; spl_handler_ArrayObject.write_property = spl_array_write_property; spl_handler_ArrayObject.get_property_ptr_ptr = spl_array_get_property_ptr_ptr; spl_handler_ArrayObject.has_property = spl_array_has_property; spl_handler_ArrayObject.unset_property = spl_array_unset_property; spl_handler_ArrayObject.compare_objects = spl_array_compare_objects; REGISTER_SPL_STD_CLASS_EX(ArrayIterator, spl_array_object_new, spl_funcs_ArrayIterator); REGISTER_SPL_IMPLEMENTS(ArrayIterator, Iterator); REGISTER_SPL_IMPLEMENTS(ArrayIterator, ArrayAccess); REGISTER_SPL_IMPLEMENTS(ArrayIterator, SeekableIterator); REGISTER_SPL_IMPLEMENTS(ArrayIterator, Serializable); memcpy(&spl_handler_ArrayIterator, &spl_handler_ArrayObject, sizeof(zend_object_handlers)); spl_ce_ArrayIterator->get_iterator = spl_array_get_iterator; REGISTER_SPL_SUB_CLASS_EX(RecursiveArrayIterator, ArrayIterator, spl_array_object_new, spl_funcs_RecursiveArrayIterator); REGISTER_SPL_IMPLEMENTS(RecursiveArrayIterator, RecursiveIterator); spl_ce_RecursiveArrayIterator->get_iterator = spl_array_get_iterator; REGISTER_SPL_IMPLEMENTS(ArrayObject, Countable); REGISTER_SPL_IMPLEMENTS(ArrayIterator, Countable); REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, "STD_PROP_LIST", SPL_ARRAY_STD_PROP_LIST); REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, "ARRAY_AS_PROPS", SPL_ARRAY_ARRAY_AS_PROPS); REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "STD_PROP_LIST", SPL_ARRAY_STD_PROP_LIST); REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, "ARRAY_AS_PROPS", SPL_ARRAY_ARRAY_AS_PROPS); REGISTER_SPL_CLASS_CONST_LONG(RecursiveArrayIterator, "CHILD_ARRAYS_ONLY", SPL_ARRAY_CHILD_ARRAYS_ONLY); return SUCCESS; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: fdm=marker * vim: noet sw=4 ts=4 */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2012-03-10-23e65a9dcc-e6ec1fb166.c
manybugs_data_99
/* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library. * * Core Directory Tag Support. */ #include "tiffiop.h" #include <stdlib.h> /* * NOTE: THIS ARRAY IS ASSUMED TO BE SORTED BY TAG. * * NOTE: The second field (field_readcount) and third field (field_writecount) * sometimes use the values TIFF_VARIABLE (-1), TIFF_VARIABLE2 (-3) * and TIFFTAG_SPP (-2). The macros should be used but would throw off * the formatting of the code, so please interprete the -1, -2 and -3 * values accordingly. */ static TIFFFieldArray tiffFieldArray; static TIFFFieldArray exifFieldArray; static TIFFField tiffFields[] = { { TIFFTAG_SUBFILETYPE, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_SUBFILETYPE, 1, 0, "SubfileType", NULL }, { TIFFTAG_OSUBFILETYPE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_SUBFILETYPE, 1, 0, "OldSubfileType", NULL }, { TIFFTAG_IMAGEWIDTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_IMAGEDIMENSIONS, 0, 0, "ImageWidth", NULL }, { TIFFTAG_IMAGELENGTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_IMAGEDIMENSIONS, 1, 0, "ImageLength", NULL }, { TIFFTAG_BITSPERSAMPLE, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_BITSPERSAMPLE, 0, 0, "BitsPerSample", NULL }, { TIFFTAG_COMPRESSION, -1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_COMPRESSION, 0, 0, "Compression", NULL }, { TIFFTAG_PHOTOMETRIC, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_PHOTOMETRIC, 0, 0, "PhotometricInterpretation", NULL }, { TIFFTAG_THRESHHOLDING, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_THRESHHOLDING, 1, 0, "Threshholding", NULL }, { TIFFTAG_CELLWIDTH, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 1, 0, "CellWidth", NULL }, { TIFFTAG_CELLLENGTH, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 1, 0, "CellLength", NULL }, { TIFFTAG_FILLORDER, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_FILLORDER, 0, 0, "FillOrder", NULL }, { TIFFTAG_DOCUMENTNAME, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "DocumentName", NULL }, { TIFFTAG_IMAGEDESCRIPTION, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ImageDescription", NULL }, { TIFFTAG_MAKE, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Make", NULL }, { TIFFTAG_MODEL, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Model", NULL }, { TIFFTAG_STRIPOFFSETS, -1, -1, TIFF_LONG8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_STRIPOFFSETS, 0, 0, "StripOffsets", NULL }, { TIFFTAG_ORIENTATION, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_ORIENTATION, 0, 0, "Orientation", NULL }, { TIFFTAG_SAMPLESPERPIXEL, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_SAMPLESPERPIXEL, 0, 0, "SamplesPerPixel", NULL }, { TIFFTAG_ROWSPERSTRIP, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_ROWSPERSTRIP, 0, 0, "RowsPerStrip", NULL }, { TIFFTAG_STRIPBYTECOUNTS, -1, -1, TIFF_LONG8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_STRIPBYTECOUNTS, 0, 0, "StripByteCounts", NULL }, { TIFFTAG_MINSAMPLEVALUE, -2, -1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_MINSAMPLEVALUE, 1, 0, "MinSampleValue", NULL }, { TIFFTAG_MAXSAMPLEVALUE, -2, -1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_MAXSAMPLEVALUE, 1, 0, "MaxSampleValue", NULL }, { TIFFTAG_XRESOLUTION, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_RESOLUTION, 1, 0, "XResolution", NULL }, { TIFFTAG_YRESOLUTION, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_RESOLUTION, 1, 0, "YResolution", NULL }, { TIFFTAG_PLANARCONFIG, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_PLANARCONFIG, 0, 0, "PlanarConfiguration", NULL }, { TIFFTAG_PAGENAME, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "PageName", NULL }, { TIFFTAG_XPOSITION, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_POSITION, 1, 0, "XPosition", NULL }, { TIFFTAG_YPOSITION, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_POSITION, 1, 0, "YPosition", NULL }, { TIFFTAG_FREEOFFSETS, -1, -1, TIFF_LONG8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 0, 0, "FreeOffsets", NULL }, { TIFFTAG_FREEBYTECOUNTS, -1, -1, TIFF_LONG8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 0, 0, "FreeByteCounts", NULL }, { TIFFTAG_GRAYRESPONSEUNIT, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 1, 0, "GrayResponseUnit", NULL }, { TIFFTAG_GRAYRESPONSECURVE, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 1, 0, "GrayResponseCurve", NULL }, { TIFFTAG_RESOLUTIONUNIT, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_RESOLUTIONUNIT, 1, 0, "ResolutionUnit", NULL }, { TIFFTAG_PAGENUMBER, 2, 2, TIFF_SHORT, 0, TIFF_SETGET_UINT16_PAIR, TIFF_SETGET_UNDEFINED, FIELD_PAGENUMBER, 1, 0, "PageNumber", NULL }, { TIFFTAG_COLORRESPONSEUNIT, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 1, 0, "ColorResponseUnit", NULL }, { TIFFTAG_TRANSFERFUNCTION, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_OTHER, TIFF_SETGET_UNDEFINED, FIELD_TRANSFERFUNCTION, 1, 0, "TransferFunction", NULL }, { TIFFTAG_SOFTWARE, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Software", NULL }, { TIFFTAG_DATETIME, 20, 20, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "DateTime", NULL }, { TIFFTAG_ARTIST, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Artist", NULL }, { TIFFTAG_HOSTCOMPUTER, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "HostComputer", NULL }, { TIFFTAG_WHITEPOINT, 2, 2, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "WhitePoint", NULL }, { TIFFTAG_PRIMARYCHROMATICITIES, 6, 6, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "PrimaryChromaticities", NULL }, { TIFFTAG_COLORMAP, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_OTHER, TIFF_SETGET_UNDEFINED, FIELD_COLORMAP, 1, 0, "ColorMap", NULL }, { TIFFTAG_HALFTONEHINTS, 2, 2, TIFF_SHORT, 0, TIFF_SETGET_UINT16_PAIR, TIFF_SETGET_UNDEFINED, FIELD_HALFTONEHINTS, 1, 0, "HalftoneHints", NULL }, { TIFFTAG_TILEWIDTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_TILEDIMENSIONS, 0, 0, "TileWidth", NULL }, { TIFFTAG_TILELENGTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_TILEDIMENSIONS, 0, 0, "TileLength", NULL }, { TIFFTAG_TILEOFFSETS, -1, 1, TIFF_LONG8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_STRIPOFFSETS, 0, 0, "TileOffsets", NULL }, { TIFFTAG_TILEBYTECOUNTS, -1, 1, TIFF_LONG8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_STRIPBYTECOUNTS, 0, 0, "TileByteCounts", NULL }, { TIFFTAG_SUBIFD, -1, -1, TIFF_IFD8, 0, TIFF_SETGET_C16_IFD8, TIFF_SETGET_UNDEFINED, FIELD_SUBIFD, 1, 1, "SubIFD", &tiffFieldArray }, { TIFFTAG_INKSET, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "InkSet", NULL }, { TIFFTAG_INKNAMES, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_C16_ASCII, TIFF_SETGET_UNDEFINED, FIELD_INKNAMES, 1, 1, "InkNames", NULL }, { TIFFTAG_NUMBEROFINKS, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "NumberOfInks", NULL }, { TIFFTAG_DOTRANGE, 2, 2, TIFF_SHORT, 0, TIFF_SETGET_UINT16_PAIR, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "DotRange", NULL }, { TIFFTAG_TARGETPRINTER, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "TargetPrinter", NULL }, { TIFFTAG_EXTRASAMPLES, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_C16_UINT16, TIFF_SETGET_UNDEFINED, FIELD_EXTRASAMPLES, 0, 1, "ExtraSamples", NULL }, { TIFFTAG_SAMPLEFORMAT, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_SAMPLEFORMAT, 0, 0, "SampleFormat", NULL }, { TIFFTAG_SMINSAMPLEVALUE, -2, -1, TIFF_ANY, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_SMINSAMPLEVALUE, 1, 0, "SMinSampleValue", NULL }, { TIFFTAG_SMAXSAMPLEVALUE, -2, -1, TIFF_ANY, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_SMAXSAMPLEVALUE, 1, 0, "SMaxSampleValue", NULL }, { TIFFTAG_CLIPPATH, -1, -3, TIFF_BYTE, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ClipPath", NULL }, { TIFFTAG_XCLIPPATHUNITS, 1, 1, TIFF_SLONG, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "XClipPathUnits", NULL }, { TIFFTAG_XCLIPPATHUNITS, 1, 1, TIFF_SBYTE, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "XClipPathUnits", NULL }, { TIFFTAG_YCLIPPATHUNITS, 1, 1, TIFF_SLONG, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "YClipPathUnits", NULL }, { TIFFTAG_YCBCRCOEFFICIENTS, 3, 3, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "YCbCrCoefficients", NULL }, { TIFFTAG_YCBCRSUBSAMPLING, 2, 2, TIFF_SHORT, 0, TIFF_SETGET_UINT16_PAIR, TIFF_SETGET_UNDEFINED, FIELD_YCBCRSUBSAMPLING, 0, 0, "YCbCrSubsampling", NULL }, { TIFFTAG_YCBCRPOSITIONING, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_YCBCRPOSITIONING, 0, 0, "YCbCrPositioning", NULL }, { TIFFTAG_REFERENCEBLACKWHITE, 6, 6, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ReferenceBlackWhite", NULL }, { TIFFTAG_XMLPACKET, -3, -3, TIFF_BYTE, 0, TIFF_SETGET_C32_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "XMLPacket", NULL }, /* begin SGI tags */ { TIFFTAG_MATTEING, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_EXTRASAMPLES, 0, 0, "Matteing", NULL }, { TIFFTAG_DATATYPE, -2, -1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_SAMPLEFORMAT, 0, 0, "DataType", NULL }, { TIFFTAG_IMAGEDEPTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_IMAGEDEPTH, 0, 0, "ImageDepth", NULL }, { TIFFTAG_TILEDEPTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_TILEDEPTH, 0, 0, "TileDepth", NULL }, /* end SGI tags */ /* begin Pixar tags */ { TIFFTAG_PIXAR_IMAGEFULLWIDTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ImageFullWidth", NULL }, { TIFFTAG_PIXAR_IMAGEFULLLENGTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ImageFullLength", NULL }, { TIFFTAG_PIXAR_TEXTUREFORMAT, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "TextureFormat", NULL }, { TIFFTAG_PIXAR_WRAPMODES, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "TextureWrapModes", NULL }, { TIFFTAG_PIXAR_FOVCOT, 1, 1, TIFF_FLOAT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FieldOfViewCotangent", NULL }, { TIFFTAG_PIXAR_MATRIX_WORLDTOSCREEN, 16, 16, TIFF_FLOAT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "MatrixWorldToScreen", NULL }, { TIFFTAG_PIXAR_MATRIX_WORLDTOCAMERA, 16, 16, TIFF_FLOAT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "MatrixWorldToCamera", NULL }, { TIFFTAG_COPYRIGHT, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Copyright", NULL }, /* end Pixar tags */ { TIFFTAG_RICHTIFFIPTC, -3, -3, TIFF_LONG, 0, TIFF_SETGET_C32_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "RichTIFFIPTC", NULL }, { TIFFTAG_PHOTOSHOP, -3, -3, TIFF_BYTE, 0, TIFF_SETGET_C32_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "Photoshop", NULL }, { TIFFTAG_EXIFIFD, 1, 1, TIFF_IFD8, 0, TIFF_SETGET_IFD8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "EXIFIFDOffset", &exifFieldArray }, { TIFFTAG_ICCPROFILE, -3, -3, TIFF_UNDEFINED, 0, TIFF_SETGET_C32_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ICC Profile", NULL }, { TIFFTAG_GPSIFD, 1, 1, TIFF_IFD8, 0, TIFF_SETGET_IFD8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "GPSIFDOffset", NULL }, { TIFFTAG_FAXRECVPARAMS, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UINT32, FIELD_CUSTOM, TRUE, FALSE, "FaxRecvParams", NULL }, { TIFFTAG_FAXSUBADDRESS, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_ASCII, FIELD_CUSTOM, TRUE, FALSE, "FaxSubAddress", NULL }, { TIFFTAG_FAXRECVTIME, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UINT32, FIELD_CUSTOM, TRUE, FALSE, "FaxRecvTime", NULL }, { TIFFTAG_FAXDCS, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_ASCII, FIELD_CUSTOM, TRUE, FALSE, "FaxDcs", NULL }, { TIFFTAG_STONITS, 1, 1, TIFF_DOUBLE, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "StoNits", NULL }, { TIFFTAG_INTEROPERABILITYIFD, 1, 1, TIFF_IFD8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "InteroperabilityIFDOffset", NULL }, /* begin DNG tags */ { TIFFTAG_DNGVERSION, 4, 4, TIFF_BYTE, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "DNGVersion", NULL }, { TIFFTAG_DNGBACKWARDVERSION, 4, 4, TIFF_BYTE, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "DNGBackwardVersion", NULL }, { TIFFTAG_UNIQUECAMERAMODEL, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "UniqueCameraModel", NULL }, { TIFFTAG_LOCALIZEDCAMERAMODEL, -1, -1, TIFF_BYTE, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "LocalizedCameraModel", NULL }, { TIFFTAG_CFAPLANECOLOR, -1, -1, TIFF_BYTE, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "CFAPlaneColor", NULL }, { TIFFTAG_CFALAYOUT, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "CFALayout", NULL }, { TIFFTAG_LINEARIZATIONTABLE, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_C16_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "LinearizationTable", NULL }, { TIFFTAG_BLACKLEVELREPEATDIM, 2, 2, TIFF_SHORT, 0, TIFF_SETGET_C0_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "BlackLevelRepeatDim", NULL }, { TIFFTAG_BLACKLEVEL, -1, -1, TIFF_RATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "BlackLevel", NULL }, { TIFFTAG_BLACKLEVELDELTAH, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "BlackLevelDeltaH", NULL }, { TIFFTAG_BLACKLEVELDELTAV, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "BlackLevelDeltaV", NULL }, { TIFFTAG_WHITELEVEL, -1, -1, TIFF_LONG, 0, TIFF_SETGET_C16_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "WhiteLevel", NULL }, { TIFFTAG_DEFAULTSCALE, 2, 2, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "DefaultScale", NULL }, { TIFFTAG_BESTQUALITYSCALE, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "BestQualityScale", NULL }, { TIFFTAG_DEFAULTCROPORIGIN, 2, 2, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "DefaultCropOrigin", NULL }, { TIFFTAG_DEFAULTCROPSIZE, 2, 2, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "DefaultCropSize", NULL }, { TIFFTAG_COLORMATRIX1, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ColorMatrix1", NULL }, { TIFFTAG_COLORMATRIX2, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ColorMatrix2", NULL }, { TIFFTAG_CAMERACALIBRATION1, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "CameraCalibration1", NULL }, { TIFFTAG_CAMERACALIBRATION2, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "CameraCalibration2", NULL }, { TIFFTAG_REDUCTIONMATRIX1, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ReductionMatrix1", NULL }, { TIFFTAG_REDUCTIONMATRIX2, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ReductionMatrix2", NULL }, { TIFFTAG_ANALOGBALANCE, -1, -1, TIFF_RATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "AnalogBalance", NULL }, { TIFFTAG_ASSHOTNEUTRAL, -1, -1, TIFF_RATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "AsShotNeutral", NULL }, { TIFFTAG_ASSHOTWHITEXY, 2, 2, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "AsShotWhiteXY", NULL }, { TIFFTAG_BASELINEEXPOSURE, 1, 1, TIFF_SRATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "BaselineExposure", NULL }, { TIFFTAG_BASELINENOISE, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "BaselineNoise", NULL }, { TIFFTAG_BASELINESHARPNESS, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "BaselineSharpness", NULL }, { TIFFTAG_BAYERGREENSPLIT, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "BayerGreenSplit", NULL }, { TIFFTAG_LINEARRESPONSELIMIT, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "LinearResponseLimit", NULL }, { TIFFTAG_CAMERASERIALNUMBER, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "CameraSerialNumber", NULL }, { TIFFTAG_LENSINFO, 4, 4, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "LensInfo", NULL }, { TIFFTAG_CHROMABLURRADIUS, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "ChromaBlurRadius", NULL }, { TIFFTAG_ANTIALIASSTRENGTH, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "AntiAliasStrength", NULL }, { TIFFTAG_SHADOWSCALE, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "ShadowScale", NULL }, { TIFFTAG_DNGPRIVATEDATA, -1, -1, TIFF_BYTE, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "DNGPrivateData", NULL }, { TIFFTAG_MAKERNOTESAFETY, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "MakerNoteSafety", NULL }, { TIFFTAG_CALIBRATIONILLUMINANT1, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "CalibrationIlluminant1", NULL }, { TIFFTAG_CALIBRATIONILLUMINANT2, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "CalibrationIlluminant2", NULL }, { TIFFTAG_RAWDATAUNIQUEID, 16, 16, TIFF_BYTE, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "RawDataUniqueID", NULL }, { TIFFTAG_ORIGINALRAWFILENAME, -1, -1, TIFF_BYTE, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "OriginalRawFileName", NULL }, { TIFFTAG_ORIGINALRAWFILEDATA, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "OriginalRawFileData", NULL }, { TIFFTAG_ACTIVEAREA, 4, 4, TIFF_LONG, 0, TIFF_SETGET_C0_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "ActiveArea", NULL }, { TIFFTAG_MASKEDAREAS, -1, -1, TIFF_LONG, 0, TIFF_SETGET_C16_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "MaskedAreas", NULL }, { TIFFTAG_ASSHOTICCPROFILE, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "AsShotICCProfile", NULL }, { TIFFTAG_ASSHOTPREPROFILEMATRIX, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "AsShotPreProfileMatrix", NULL }, { TIFFTAG_CURRENTICCPROFILE, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "CurrentICCProfile", NULL }, { TIFFTAG_CURRENTPREPROFILEMATRIX, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "CurrentPreProfileMatrix", NULL }, /* end DNG tags */ }; static TIFFField exifFields[] = { { EXIFTAG_EXPOSURETIME, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ExposureTime", NULL }, { EXIFTAG_FNUMBER, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FNumber", NULL }, { EXIFTAG_EXPOSUREPROGRAM, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ExposureProgram", NULL }, { EXIFTAG_SPECTRALSENSITIVITY, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SpectralSensitivity", NULL }, { EXIFTAG_ISOSPEEDRATINGS, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_C16_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "ISOSpeedRatings", NULL }, { EXIFTAG_OECF, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "OptoelectricConversionFactor", NULL }, { EXIFTAG_EXIFVERSION, 4, 4, TIFF_UNDEFINED, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ExifVersion", NULL }, { EXIFTAG_DATETIMEORIGINAL, 20, 20, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "DateTimeOriginal", NULL }, { EXIFTAG_DATETIMEDIGITIZED, 20, 20, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "DateTimeDigitized", NULL }, { EXIFTAG_COMPONENTSCONFIGURATION, 4, 4, TIFF_UNDEFINED, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ComponentsConfiguration", NULL }, { EXIFTAG_COMPRESSEDBITSPERPIXEL, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "CompressedBitsPerPixel", NULL }, { EXIFTAG_SHUTTERSPEEDVALUE, 1, 1, TIFF_SRATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ShutterSpeedValue", NULL }, { EXIFTAG_APERTUREVALUE, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ApertureValue", NULL }, { EXIFTAG_BRIGHTNESSVALUE, 1, 1, TIFF_SRATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "BrightnessValue", NULL }, { EXIFTAG_EXPOSUREBIASVALUE, 1, 1, TIFF_SRATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ExposureBiasValue", NULL }, { EXIFTAG_MAXAPERTUREVALUE, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "MaxApertureValue", NULL }, { EXIFTAG_SUBJECTDISTANCE, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SubjectDistance", NULL }, { EXIFTAG_METERINGMODE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "MeteringMode", NULL }, { EXIFTAG_LIGHTSOURCE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "LightSource", NULL }, { EXIFTAG_FLASH, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Flash", NULL }, { EXIFTAG_FOCALLENGTH, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FocalLength", NULL }, { EXIFTAG_SUBJECTAREA, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_C16_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "SubjectArea", NULL }, { EXIFTAG_MAKERNOTE, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "MakerNote", NULL }, { EXIFTAG_USERCOMMENT, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "UserComment", NULL }, { EXIFTAG_SUBSECTIME, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SubSecTime", NULL }, { EXIFTAG_SUBSECTIMEORIGINAL, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SubSecTimeOriginal", NULL }, { EXIFTAG_SUBSECTIMEDIGITIZED, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SubSecTimeDigitized", NULL }, { EXIFTAG_FLASHPIXVERSION, 4, 4, TIFF_UNDEFINED, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FlashpixVersion", NULL }, { EXIFTAG_COLORSPACE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ColorSpace", NULL }, { EXIFTAG_PIXELXDIMENSION, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "PixelXDimension", NULL }, { EXIFTAG_PIXELYDIMENSION, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "PixelYDimension", NULL }, { EXIFTAG_RELATEDSOUNDFILE, 13, 13, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "RelatedSoundFile", NULL }, { EXIFTAG_FLASHENERGY, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FlashEnergy", NULL }, { EXIFTAG_SPATIALFREQUENCYRESPONSE, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "SpatialFrequencyResponse", NULL }, { EXIFTAG_FOCALPLANEXRESOLUTION, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FocalPlaneXResolution", NULL }, { EXIFTAG_FOCALPLANEYRESOLUTION, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FocalPlaneYResolution", NULL }, { EXIFTAG_FOCALPLANERESOLUTIONUNIT, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FocalPlaneResolutionUnit", NULL }, { EXIFTAG_SUBJECTLOCATION, 2, 2, TIFF_SHORT, 0, TIFF_SETGET_C0_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SubjectLocation", NULL }, { EXIFTAG_EXPOSUREINDEX, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ExposureIndex", NULL }, { EXIFTAG_SENSINGMETHOD, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SensingMethod", NULL }, { EXIFTAG_FILESOURCE, 1, 1, TIFF_UNDEFINED, 0, TIFF_SETGET_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FileSource", NULL }, { EXIFTAG_SCENETYPE, 1, 1, TIFF_UNDEFINED, 0, TIFF_SETGET_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SceneType", NULL }, { EXIFTAG_CFAPATTERN, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "CFAPattern", NULL }, { EXIFTAG_CUSTOMRENDERED, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "CustomRendered", NULL }, { EXIFTAG_EXPOSUREMODE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ExposureMode", NULL }, { EXIFTAG_WHITEBALANCE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "WhiteBalance", NULL }, { EXIFTAG_DIGITALZOOMRATIO, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "DigitalZoomRatio", NULL }, { EXIFTAG_FOCALLENGTHIN35MMFILM, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FocalLengthIn35mmFilm", NULL }, { EXIFTAG_SCENECAPTURETYPE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SceneCaptureType", NULL }, { EXIFTAG_GAINCONTROL, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "GainControl", NULL }, { EXIFTAG_CONTRAST, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Contrast", NULL }, { EXIFTAG_SATURATION, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Saturation", NULL }, { EXIFTAG_SHARPNESS, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Sharpness", NULL }, { EXIFTAG_DEVICESETTINGDESCRIPTION, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "DeviceSettingDescription", NULL }, { EXIFTAG_SUBJECTDISTANCERANGE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SubjectDistanceRange", NULL }, { EXIFTAG_IMAGEUNIQUEID, 33, 33, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ImageUniqueID", NULL } }; static TIFFFieldArray tiffFieldArray = { tfiatImage, 0, TIFFArrayCount(tiffFields), tiffFields }; static TIFFFieldArray exifFieldArray = { tfiatExif, 0, TIFFArrayCount(exifFields), exifFields }; const TIFFFieldArray* _TIFFGetFields(void) { return(&tiffFieldArray); } const TIFFFieldArray* _TIFFGetExifFields(void) { return(&exifFieldArray); } void _TIFFSetupFields(TIFF* tif, const TIFFFieldArray* fieldarray) { if (tif->tif_fields && tif->tif_nfields > 0) { uint32 i; for (i = 0; i < tif->tif_nfields; i++) { TIFFField *fld = tif->tif_fields[i]; if (fld->field_bit == FIELD_CUSTOM && strncmp("Tag ", fld->field_name, 4) == 0) { _TIFFfree(fld->field_name); _TIFFfree(fld); } } _TIFFfree(tif->tif_fields); tif->tif_fields = NULL; tif->tif_nfields = 0; } if (!_TIFFMergeFields(tif, fieldarray->fields, fieldarray->count)) { TIFFErrorExt(tif->tif_clientdata, "_TIFFSetupFields", "Setting up field info failed"); } } static int tagCompare(const void* a, const void* b) { const TIFFField* ta = *(const TIFFField**) a; const TIFFField* tb = *(const TIFFField**) b; /* NB: be careful of return values for 16-bit platforms */ if (ta->field_tag != tb->field_tag) return (int)ta->field_tag - (int)tb->field_tag; else return (ta->field_type == TIFF_ANY) ? 0 : ((int)tb->field_type - (int)ta->field_type); } static int tagNameCompare(const void* a, const void* b) { const TIFFField* ta = *(const TIFFField**) a; const TIFFField* tb = *(const TIFFField**) b; int ret = strcmp(ta->field_name, tb->field_name); if (ret) return ret; else return (ta->field_type == TIFF_ANY) ? 0 : ((int)tb->field_type - (int)ta->field_type); } int _TIFFMergeFields(TIFF* tif, const TIFFField info[], uint32 n) { static const char module[] = "_TIFFMergeFields"; static const char reason[] = "for fields array"; TIFFField** tp; uint32 i; tif->tif_foundfield = NULL; if (tif->tif_fields && tif->tif_nfields > 0) { tif->tif_fields = (TIFFField**) _TIFFCheckRealloc(tif, tif->tif_fields, (tif->tif_nfields + n), sizeof(TIFFField *), reason); } else { tif->tif_fields = (TIFFField **) _TIFFCheckMalloc(tif, n, sizeof(TIFFField *), reason); } if (!tif->tif_fields) { TIFFErrorExt(tif->tif_clientdata, module, "Failed to allocate fields array"); return 0; } tp = tif->tif_fields + tif->tif_nfields; for (i = 0; i < n; i++) { const TIFFField *fip = TIFFFindField(tif, info[i].field_tag, TIFF_ANY); /* only add definitions that aren't already present */ if (!fip) { tif->tif_fields[tif->tif_nfields] = (TIFFField *) (info+i); tif->tif_nfields++; } } /* Sort the field info by tag number */ qsort(tif->tif_fields, tif->tif_nfields, sizeof(TIFFField *), tagCompare); return n; } void _TIFFPrintFieldInfo(TIFF* tif, FILE* fd) { uint32 i; fprintf(fd, "%s: \n", tif->tif_name); for (i = 0; i < tif->tif_nfields; i++) { const TIFFField* fip = tif->tif_fields[i]; fprintf(fd, "field[%2d] %5lu, %2d, %2d, %d, %2d, %5s, %5s, %s\n" , (int)i , (unsigned long) fip->field_tag , fip->field_readcount, fip->field_writecount , fip->field_type , fip->field_bit , fip->field_oktochange ? "TRUE" : "FALSE" , fip->field_passcount ? "TRUE" : "FALSE" , fip->field_name ); } } /* * Return size of TIFFDataType in bytes */ int TIFFDataWidth(TIFFDataType type) { switch(type) { case 0: /* nothing */ case TIFF_BYTE: case TIFF_ASCII: case TIFF_SBYTE: case TIFF_UNDEFINED: return 1; case TIFF_SHORT: case TIFF_SSHORT: return 2; case TIFF_LONG: case TIFF_SLONG: case TIFF_FLOAT: case TIFF_IFD: return 4; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_DOUBLE: case TIFF_LONG8: case TIFF_SLONG8: case TIFF_IFD8: return 8; default: return 0; /* will return 0 for unknown types */ } } /* * Return size of TIFFDataType in bytes. * * XXX: We need a separate function to determine the space needed * to store the value. For TIFF_RATIONAL values TIFFDataWidth() returns 8, * but we use 4-byte float to represent rationals. */ int _TIFFDataSize(TIFFDataType type) { switch (type) { case TIFF_BYTE: case TIFF_SBYTE: case TIFF_ASCII: case TIFF_UNDEFINED: return 1; case TIFF_SHORT: case TIFF_SSHORT: return 2; case TIFF_LONG: case TIFF_SLONG: case TIFF_FLOAT: case TIFF_IFD: case TIFF_RATIONAL: case TIFF_SRATIONAL: return 4; case TIFF_DOUBLE: case TIFF_LONG8: case TIFF_SLONG8: case TIFF_IFD8: return 8; default: return 0; } } const TIFFField* TIFFFindField(TIFF* tif, uint32 tag, TIFFDataType dt) { TIFFField key = {0, 0, 0, TIFF_NOTYPE, 0, 0, 0, 0, 0, 0, NULL, NULL}; TIFFField* pkey = &key; const TIFFField **ret; if (tif->tif_foundfield && tif->tif_foundfield->field_tag == tag && (dt == TIFF_ANY || dt == tif->tif_foundfield->field_type)) return tif->tif_foundfield; /* If we are invoked with no field information, then just return. */ if (!tif->tif_fields) return NULL; /* NB: use sorted search (e.g. binary search) */ key.field_tag = tag; key.field_type = dt; ret = (const TIFFField **) bsearch(&pkey, tif->tif_fields, tif->tif_nfields, sizeof(TIFFField *), tagCompare); return tif->tif_foundfield = (ret ? *ret : NULL); } const TIFFField* _TIFFFindFieldByName(TIFF* tif, const char *field_name, TIFFDataType dt) { TIFFField key = {0, 0, 0, TIFF_NOTYPE, 0, 0, 0, 0, 0, 0, NULL, NULL}; TIFFField* pkey = &key; const TIFFField **ret; if (tif->tif_foundfield && streq(tif->tif_foundfield->field_name, field_name) && (dt == TIFF_ANY || dt == tif->tif_foundfield->field_type)) return (tif->tif_foundfield); /* If we are invoked with no field information, then just return. */ if (!tif->tif_fields) return NULL; /* NB: use sorted search (e.g. binary search) */ key.field_name = (char *)field_name; key.field_type = dt; ret = (const TIFFField **) lfind(&pkey, tif->tif_fields, &tif->tif_nfields, sizeof(TIFFField *), tagNameCompare); return tif->tif_foundfield = (ret ? *ret : NULL); } const TIFFField* TIFFFieldWithTag(TIFF* tif, uint32 tag) { const TIFFField* fip = TIFFFindField(tif, tag, TIFF_ANY); if (!fip) { TIFFErrorExt(tif->tif_clientdata, "TIFFFieldWithTag", "Internal error, unknown tag 0x%x", (unsigned int) tag); assert(fip != NULL); /*NOTREACHED*/ } return (fip); } const TIFFField* TIFFFieldWithName(TIFF* tif, const char *field_name) { const TIFFField* fip = _TIFFFindFieldByName(tif, field_name, TIFF_ANY); if (!fip) { TIFFErrorExt(tif->tif_clientdata, "TIFFFieldWithName", "Internal error, unknown tag %s", field_name); assert(fip != NULL); /*NOTREACHED*/ } return (fip); } const TIFFField* _TIFFFindOrRegisterField(TIFF *tif, uint32 tag, TIFFDataType dt) { const TIFFField *fld; fld = TIFFFindField(tif, tag, dt); if (fld == NULL) { fld = _TIFFCreateAnonField(tif, tag, dt); if (!_TIFFMergeFields(tif, fld, 1)) return NULL; } return fld; } TIFFField* _TIFFCreateAnonField(TIFF *tif, uint32 tag, TIFFDataType field_type) { TIFFField *fld; (void) tif; fld = (TIFFField *) _TIFFmalloc(sizeof (TIFFField)); if (fld == NULL) return NULL; _TIFFmemset(fld, 0, sizeof(TIFFField)); fld->field_tag = tag; fld->field_readcount = TIFF_VARIABLE2; fld->field_writecount = TIFF_VARIABLE2; fld->field_type = field_type; fld->reserved = 0; switch (field_type) { case TIFF_BYTE: case TIFF_UNDEFINED: fld->set_field_type = TIFF_SETGET_C32_UINT8; fld->get_field_type = TIFF_SETGET_C32_UINT8; break; case TIFF_ASCII: fld->set_field_type = TIFF_SETGET_C32_ASCII; fld->get_field_type = TIFF_SETGET_C32_ASCII; break; case TIFF_SHORT: fld->set_field_type = TIFF_SETGET_C32_UINT16; fld->get_field_type = TIFF_SETGET_C32_UINT16; break; case TIFF_LONG: fld->set_field_type = TIFF_SETGET_C32_UINT32; fld->get_field_type = TIFF_SETGET_C32_UINT32; break; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: fld->set_field_type = TIFF_SETGET_C32_FLOAT; fld->get_field_type = TIFF_SETGET_C32_FLOAT; break; case TIFF_SBYTE: fld->set_field_type = TIFF_SETGET_C32_SINT8; fld->get_field_type = TIFF_SETGET_C32_SINT8; break; case TIFF_SSHORT: fld->set_field_type = TIFF_SETGET_C32_SINT16; fld->get_field_type = TIFF_SETGET_C32_SINT16; break; case TIFF_SLONG: fld->set_field_type = TIFF_SETGET_C32_SINT32; fld->get_field_type = TIFF_SETGET_C32_SINT32; break; case TIFF_DOUBLE: fld->set_field_type = TIFF_SETGET_C32_DOUBLE; fld->get_field_type = TIFF_SETGET_C32_DOUBLE; break; case TIFF_IFD: case TIFF_IFD8: fld->set_field_type = TIFF_SETGET_C32_IFD8; fld->get_field_type = TIFF_SETGET_C32_IFD8; break; case TIFF_LONG8: fld->set_field_type = TIFF_SETGET_C32_UINT64; fld->get_field_type = TIFF_SETGET_C32_UINT64; break; case TIFF_SLONG8: fld->set_field_type = TIFF_SETGET_C32_SINT64; fld->get_field_type = TIFF_SETGET_C32_SINT64; break; default: fld->set_field_type = TIFF_SETGET_UNDEFINED; fld->get_field_type = TIFF_SETGET_UNDEFINED; break; } fld->field_bit = FIELD_CUSTOM; fld->field_oktochange = TRUE; fld->field_passcount = TRUE; fld->field_name = (char *) _TIFFmalloc(32); if (fld->field_name == NULL) { _TIFFfree(fld); return NULL; } fld->field_subfields = NULL; /* * note that this name is a special sign to TIFFClose() and * _TIFFSetupFields() to free the field */ sprintf(fld->field_name, "Tag %d", (int) tag); return fld; } /**************************************************************************** * O B S O L E T E D I N T E R F A C E S * * Don't use this stuff in your applications, it may be removed in the future * libtiff versions. ****************************************************************************/ static TIFFSetGetFieldType _TIFFSetGetType(TIFFDataType type, short count, unsigned char passcount) { if (type == TIFF_ASCII && count == TIFF_VARIABLE && passcount == 0) return TIFF_SETGET_ASCII; else if (count == 1 && passcount == 0) { switch (type) { case TIFF_BYTE: case TIFF_UNDEFINED: return TIFF_SETGET_UINT8; case TIFF_ASCII: return TIFF_SETGET_ASCII; case TIFF_SHORT: return TIFF_SETGET_UINT16; case TIFF_LONG: return TIFF_SETGET_UINT32; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: return TIFF_SETGET_FLOAT; case TIFF_SBYTE: return TIFF_SETGET_SINT8; case TIFF_SSHORT: return TIFF_SETGET_SINT16; case TIFF_SLONG: return TIFF_SETGET_SINT32; case TIFF_DOUBLE: return TIFF_SETGET_DOUBLE; case TIFF_IFD: case TIFF_IFD8: return TIFF_SETGET_IFD8; case TIFF_LONG8: return TIFF_SETGET_UINT64; case TIFF_SLONG8: return TIFF_SETGET_SINT64; default: return TIFF_SETGET_UNDEFINED; } } else if (count >= 1 && passcount == 0) { switch (type) { case TIFF_BYTE: case TIFF_UNDEFINED: return TIFF_SETGET_C0_UINT8; case TIFF_ASCII: return TIFF_SETGET_C0_ASCII; case TIFF_SHORT: return TIFF_SETGET_C0_UINT16; case TIFF_LONG: return TIFF_SETGET_C0_UINT32; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: return TIFF_SETGET_C0_FLOAT; case TIFF_SBYTE: return TIFF_SETGET_C0_SINT8; case TIFF_SSHORT: return TIFF_SETGET_C0_SINT16; case TIFF_SLONG: return TIFF_SETGET_C0_SINT32; case TIFF_DOUBLE: return TIFF_SETGET_C0_DOUBLE; case TIFF_IFD: case TIFF_IFD8: return TIFF_SETGET_C0_IFD8; case TIFF_LONG8: return TIFF_SETGET_C0_UINT64; case TIFF_SLONG8: return TIFF_SETGET_C0_SINT64; default: return TIFF_SETGET_UNDEFINED; } } else if (count == TIFF_VARIABLE && passcount == 1) { switch (type) { case TIFF_BYTE: case TIFF_UNDEFINED: return TIFF_SETGET_C16_UINT8; case TIFF_ASCII: return TIFF_SETGET_C16_ASCII; case TIFF_SHORT: return TIFF_SETGET_C16_UINT16; case TIFF_LONG: return TIFF_SETGET_C16_UINT32; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: return TIFF_SETGET_C16_FLOAT; case TIFF_SBYTE: return TIFF_SETGET_C16_SINT8; case TIFF_SSHORT: return TIFF_SETGET_C16_SINT16; case TIFF_SLONG: return TIFF_SETGET_C16_SINT32; case TIFF_DOUBLE: return TIFF_SETGET_C16_DOUBLE; case TIFF_IFD: case TIFF_IFD8: return TIFF_SETGET_C16_IFD8; case TIFF_LONG8: return TIFF_SETGET_C16_UINT64; case TIFF_SLONG8: return TIFF_SETGET_C16_SINT64; default: return TIFF_SETGET_UNDEFINED; } } else if (count == TIFF_VARIABLE2 && passcount == 1) { switch (type) { case TIFF_BYTE: case TIFF_UNDEFINED: return TIFF_SETGET_C32_UINT8; case TIFF_ASCII: return TIFF_SETGET_C32_ASCII; case TIFF_SHORT: return TIFF_SETGET_C32_UINT16; case TIFF_LONG: return TIFF_SETGET_C32_UINT32; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: return TIFF_SETGET_C32_FLOAT; case TIFF_SBYTE: return TIFF_SETGET_C32_SINT8; case TIFF_SSHORT: return TIFF_SETGET_C32_SINT16; case TIFF_SLONG: return TIFF_SETGET_C32_SINT32; case TIFF_DOUBLE: return TIFF_SETGET_C32_DOUBLE; case TIFF_IFD: case TIFF_IFD8: return TIFF_SETGET_C32_IFD8; case TIFF_LONG8: return TIFF_SETGET_C32_UINT64; case TIFF_SLONG8: return TIFF_SETGET_C32_SINT64; default: return TIFF_SETGET_UNDEFINED; } } return TIFF_SETGET_UNDEFINED; } int TIFFMergeFieldInfo(TIFF* tif, const TIFFFieldInfo info[], uint32 n) { static const char module[] = "TIFFMergeFieldInfo"; static const char reason[] = "for fields array"; TIFFField *tp; size_t nfields; uint32 i; if (tif->tif_nfieldscompat > 0) { tif->tif_fieldscompat = (TIFFFieldArray *) _TIFFCheckRealloc(tif, tif->tif_fieldscompat, tif->tif_nfieldscompat + 1, sizeof(TIFFFieldArray), reason); } else { tif->tif_fieldscompat = (TIFFFieldArray *) _TIFFCheckMalloc(tif, 1, sizeof(TIFFFieldArray), reason); } if (!tif->tif_fieldscompat) { TIFFErrorExt(tif->tif_clientdata, module, "Failed to allocate fields array"); return -1; } nfields = tif->tif_nfieldscompat++; tif->tif_fieldscompat[nfields].type = tfiatOther; tif->tif_fieldscompat[nfields].allocated_size = n; tif->tif_fieldscompat[nfields].count = n; tif->tif_fieldscompat[nfields].fields = (TIFFField *)_TIFFCheckMalloc(tif, n, sizeof(TIFFField), reason); if (!tif->tif_fieldscompat[nfields].fields) { TIFFErrorExt(tif->tif_clientdata, module, "Failed to allocate fields array"); return -1; } tp = tif->tif_fieldscompat[nfields].fields; for (i = 0; i < n; i++) { tp->field_tag = info[i].field_tag; tp->field_readcount = info[i].field_readcount; tp->field_writecount = info[i].field_writecount; tp->field_type = info[i].field_type; tp->reserved = 0; tp->set_field_type = _TIFFSetGetType(info[i].field_type, info[i].field_readcount, info[i].field_passcount); tp->get_field_type = _TIFFSetGetType(info[i].field_type, info[i].field_readcount, info[i].field_passcount); tp->field_bit = info[i].field_bit; tp->field_oktochange = info[i].field_oktochange; tp->field_passcount = info[i].field_passcount; tp->field_name = info[i].field_name; tp->field_subfields = NULL; tp++; } if (!_TIFFMergeFields(tif, tif->tif_fieldscompat[nfields].fields, n)) { TIFFErrorExt(tif->tif_clientdata, module, "Setting up field info failed"); return -1; } return 0; } const TIFFFieldInfo* TIFFFindFieldInfoByName(TIFF* tif, const char *field_name, TIFFDataType dt) { #if 0 TIFFFieldInfo key = {0, 0, 0, TIFF_NOTYPE, 0, 0, 0, 0, 0, 0, NULL, NULL}; TIFFFieldInfo* pkey = &key; const TIFFFieldInfo **ret; if (tif->tif_foundfield && streq(tif->tif_foundfield->field_name, field_name) && (dt == TIFF_ANY || dt == tif->tif_foundfield->field_type)) return (tif->tif_foundfield); /* If we are invoked with no field information, then just return. */ if ( !tif->tif_fields ) { return NULL; } /* NB: use sorted search (e.g. binary search) */ key.field_name = (char *)field_name; key.field_type = dt; ret = (const TIFFFieldInfo **) lfind(&pkey, tif->tif_fields, &tif->tif_nfields, sizeof(TIFFFieldInfo *), tagNameCompare); return tif->tif_foundfield = (ret ? *ret : NULL); #endif return NULL; } const TIFFFieldInfo* TIFFFindFieldInfo(TIFF* tif, uint32 tag, TIFFDataType dt) { #if 0 TIFFFieldInfo key = {0, 0, 0, TIFF_NOTYPE, 0, 0, 0, 0, 0, 0, NULL, NULL}; TIFFFieldInfo* pkey = &key; const TIFFFieldInfo **ret; if (tif->tif_foundfield && tif->tif_foundfield->field_tag == tag && (dt == TIFF_ANY || dt == tif->tif_foundfield->field_type)) return tif->tif_foundfield; /* If we are invoked with no field information, then just return. */ if ( !tif->tif_fields ) { return NULL; } /* NB: use sorted search (e.g. binary search) */ key.field_tag = tag; key.field_type = dt; ret = (const TIFFFieldInfo **) bsearch(&pkey, tif->tif_fields, tif->tif_nfields, sizeof(TIFFFieldInfo *), tagCompare); return tif->tif_foundfield = (ret ? *ret : NULL); #endif return NULL; } /* vim: set ts=8 sts=8 sw=8 noet: */ /* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library. * * Core Directory Tag Support. */ #include "tiffiop.h" #include <stdlib.h> /* * NOTE: THIS ARRAY IS ASSUMED TO BE SORTED BY TAG. * * NOTE: The second field (field_readcount) and third field (field_writecount) * sometimes use the values TIFF_VARIABLE (-1), TIFF_VARIABLE2 (-3) * and TIFFTAG_SPP (-2). The macros should be used but would throw off * the formatting of the code, so please interprete the -1, -2 and -3 * values accordingly. */ static TIFFFieldArray tiffFieldArray; static TIFFFieldArray exifFieldArray; static TIFFField tiffFields[] = { { TIFFTAG_SUBFILETYPE, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_SUBFILETYPE, 1, 0, "SubfileType", NULL }, { TIFFTAG_OSUBFILETYPE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_SUBFILETYPE, 1, 0, "OldSubfileType", NULL }, { TIFFTAG_IMAGEWIDTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_IMAGEDIMENSIONS, 0, 0, "ImageWidth", NULL }, { TIFFTAG_IMAGELENGTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_IMAGEDIMENSIONS, 1, 0, "ImageLength", NULL }, { TIFFTAG_BITSPERSAMPLE, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_BITSPERSAMPLE, 0, 0, "BitsPerSample", NULL }, { TIFFTAG_COMPRESSION, -1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_COMPRESSION, 0, 0, "Compression", NULL }, { TIFFTAG_PHOTOMETRIC, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_PHOTOMETRIC, 0, 0, "PhotometricInterpretation", NULL }, { TIFFTAG_THRESHHOLDING, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_THRESHHOLDING, 1, 0, "Threshholding", NULL }, { TIFFTAG_CELLWIDTH, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 1, 0, "CellWidth", NULL }, { TIFFTAG_CELLLENGTH, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 1, 0, "CellLength", NULL }, { TIFFTAG_FILLORDER, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_FILLORDER, 0, 0, "FillOrder", NULL }, { TIFFTAG_DOCUMENTNAME, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "DocumentName", NULL }, { TIFFTAG_IMAGEDESCRIPTION, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ImageDescription", NULL }, { TIFFTAG_MAKE, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Make", NULL }, { TIFFTAG_MODEL, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Model", NULL }, { TIFFTAG_STRIPOFFSETS, -1, -1, TIFF_LONG8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_STRIPOFFSETS, 0, 0, "StripOffsets", NULL }, { TIFFTAG_ORIENTATION, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_ORIENTATION, 0, 0, "Orientation", NULL }, { TIFFTAG_SAMPLESPERPIXEL, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_SAMPLESPERPIXEL, 0, 0, "SamplesPerPixel", NULL }, { TIFFTAG_ROWSPERSTRIP, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_ROWSPERSTRIP, 0, 0, "RowsPerStrip", NULL }, { TIFFTAG_STRIPBYTECOUNTS, -1, -1, TIFF_LONG8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_STRIPBYTECOUNTS, 0, 0, "StripByteCounts", NULL }, { TIFFTAG_MINSAMPLEVALUE, -2, -1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_MINSAMPLEVALUE, 1, 0, "MinSampleValue", NULL }, { TIFFTAG_MAXSAMPLEVALUE, -2, -1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_MAXSAMPLEVALUE, 1, 0, "MaxSampleValue", NULL }, { TIFFTAG_XRESOLUTION, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_RESOLUTION, 1, 0, "XResolution", NULL }, { TIFFTAG_YRESOLUTION, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_RESOLUTION, 1, 0, "YResolution", NULL }, { TIFFTAG_PLANARCONFIG, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_PLANARCONFIG, 0, 0, "PlanarConfiguration", NULL }, { TIFFTAG_PAGENAME, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "PageName", NULL }, { TIFFTAG_XPOSITION, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_POSITION, 1, 0, "XPosition", NULL }, { TIFFTAG_YPOSITION, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_POSITION, 1, 0, "YPosition", NULL }, { TIFFTAG_FREEOFFSETS, -1, -1, TIFF_LONG8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 0, 0, "FreeOffsets", NULL }, { TIFFTAG_FREEBYTECOUNTS, -1, -1, TIFF_LONG8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 0, 0, "FreeByteCounts", NULL }, { TIFFTAG_GRAYRESPONSEUNIT, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 1, 0, "GrayResponseUnit", NULL }, { TIFFTAG_GRAYRESPONSECURVE, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 1, 0, "GrayResponseCurve", NULL }, { TIFFTAG_RESOLUTIONUNIT, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_RESOLUTIONUNIT, 1, 0, "ResolutionUnit", NULL }, { TIFFTAG_PAGENUMBER, 2, 2, TIFF_SHORT, 0, TIFF_SETGET_UINT16_PAIR, TIFF_SETGET_UNDEFINED, FIELD_PAGENUMBER, 1, 0, "PageNumber", NULL }, { TIFFTAG_COLORRESPONSEUNIT, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_IGNORE, 1, 0, "ColorResponseUnit", NULL }, { TIFFTAG_TRANSFERFUNCTION, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_OTHER, TIFF_SETGET_UNDEFINED, FIELD_TRANSFERFUNCTION, 1, 0, "TransferFunction", NULL }, { TIFFTAG_SOFTWARE, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Software", NULL }, { TIFFTAG_DATETIME, 20, 20, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "DateTime", NULL }, { TIFFTAG_ARTIST, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Artist", NULL }, { TIFFTAG_HOSTCOMPUTER, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "HostComputer", NULL }, { TIFFTAG_WHITEPOINT, 2, 2, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "WhitePoint", NULL }, { TIFFTAG_PRIMARYCHROMATICITIES, 6, 6, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "PrimaryChromaticities", NULL }, { TIFFTAG_COLORMAP, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_OTHER, TIFF_SETGET_UNDEFINED, FIELD_COLORMAP, 1, 0, "ColorMap", NULL }, { TIFFTAG_HALFTONEHINTS, 2, 2, TIFF_SHORT, 0, TIFF_SETGET_UINT16_PAIR, TIFF_SETGET_UNDEFINED, FIELD_HALFTONEHINTS, 1, 0, "HalftoneHints", NULL }, { TIFFTAG_TILEWIDTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_TILEDIMENSIONS, 0, 0, "TileWidth", NULL }, { TIFFTAG_TILELENGTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_TILEDIMENSIONS, 0, 0, "TileLength", NULL }, { TIFFTAG_TILEOFFSETS, -1, 1, TIFF_LONG8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_STRIPOFFSETS, 0, 0, "TileOffsets", NULL }, { TIFFTAG_TILEBYTECOUNTS, -1, 1, TIFF_LONG8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_STRIPBYTECOUNTS, 0, 0, "TileByteCounts", NULL }, { TIFFTAG_SUBIFD, -1, -1, TIFF_IFD8, 0, TIFF_SETGET_C16_IFD8, TIFF_SETGET_UNDEFINED, FIELD_SUBIFD, 1, 1, "SubIFD", &tiffFieldArray }, { TIFFTAG_INKSET, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "InkSet", NULL }, { TIFFTAG_INKNAMES, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_C16_ASCII, TIFF_SETGET_UNDEFINED, FIELD_INKNAMES, 1, 1, "InkNames", NULL }, { TIFFTAG_NUMBEROFINKS, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "NumberOfInks", NULL }, { TIFFTAG_DOTRANGE, 2, 2, TIFF_SHORT, 0, TIFF_SETGET_UINT16_PAIR, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "DotRange", NULL }, { TIFFTAG_TARGETPRINTER, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "TargetPrinter", NULL }, { TIFFTAG_EXTRASAMPLES, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_C16_UINT16, TIFF_SETGET_UNDEFINED, FIELD_EXTRASAMPLES, 0, 1, "ExtraSamples", NULL }, { TIFFTAG_SAMPLEFORMAT, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_SAMPLEFORMAT, 0, 0, "SampleFormat", NULL }, { TIFFTAG_SMINSAMPLEVALUE, -2, -1, TIFF_ANY, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_SMINSAMPLEVALUE, 1, 0, "SMinSampleValue", NULL }, { TIFFTAG_SMAXSAMPLEVALUE, -2, -1, TIFF_ANY, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_SMAXSAMPLEVALUE, 1, 0, "SMaxSampleValue", NULL }, { TIFFTAG_CLIPPATH, -1, -3, TIFF_BYTE, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ClipPath", NULL }, { TIFFTAG_XCLIPPATHUNITS, 1, 1, TIFF_SLONG, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "XClipPathUnits", NULL }, { TIFFTAG_XCLIPPATHUNITS, 1, 1, TIFF_SBYTE, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "XClipPathUnits", NULL }, { TIFFTAG_YCLIPPATHUNITS, 1, 1, TIFF_SLONG, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "YClipPathUnits", NULL }, { TIFFTAG_YCBCRCOEFFICIENTS, 3, 3, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "YCbCrCoefficients", NULL }, { TIFFTAG_YCBCRSUBSAMPLING, 2, 2, TIFF_SHORT, 0, TIFF_SETGET_UINT16_PAIR, TIFF_SETGET_UNDEFINED, FIELD_YCBCRSUBSAMPLING, 0, 0, "YCbCrSubsampling", NULL }, { TIFFTAG_YCBCRPOSITIONING, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_YCBCRPOSITIONING, 0, 0, "YCbCrPositioning", NULL }, { TIFFTAG_REFERENCEBLACKWHITE, 6, 6, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ReferenceBlackWhite", NULL }, { TIFFTAG_XMLPACKET, -3, -3, TIFF_BYTE, 0, TIFF_SETGET_C32_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "XMLPacket", NULL }, /* begin SGI tags */ { TIFFTAG_MATTEING, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_EXTRASAMPLES, 0, 0, "Matteing", NULL }, { TIFFTAG_DATATYPE, -2, -1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_SAMPLEFORMAT, 0, 0, "DataType", NULL }, { TIFFTAG_IMAGEDEPTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_IMAGEDEPTH, 0, 0, "ImageDepth", NULL }, { TIFFTAG_TILEDEPTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_TILEDEPTH, 0, 0, "TileDepth", NULL }, /* end SGI tags */ /* begin Pixar tags */ { TIFFTAG_PIXAR_IMAGEFULLWIDTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ImageFullWidth", NULL }, { TIFFTAG_PIXAR_IMAGEFULLLENGTH, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ImageFullLength", NULL }, { TIFFTAG_PIXAR_TEXTUREFORMAT, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "TextureFormat", NULL }, { TIFFTAG_PIXAR_WRAPMODES, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "TextureWrapModes", NULL }, { TIFFTAG_PIXAR_FOVCOT, 1, 1, TIFF_FLOAT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FieldOfViewCotangent", NULL }, { TIFFTAG_PIXAR_MATRIX_WORLDTOSCREEN, 16, 16, TIFF_FLOAT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "MatrixWorldToScreen", NULL }, { TIFFTAG_PIXAR_MATRIX_WORLDTOCAMERA, 16, 16, TIFF_FLOAT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "MatrixWorldToCamera", NULL }, { TIFFTAG_COPYRIGHT, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Copyright", NULL }, /* end Pixar tags */ { TIFFTAG_RICHTIFFIPTC, -3, -3, TIFF_LONG, 0, TIFF_SETGET_C32_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "RichTIFFIPTC", NULL }, { TIFFTAG_PHOTOSHOP, -3, -3, TIFF_BYTE, 0, TIFF_SETGET_C32_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "Photoshop", NULL }, { TIFFTAG_EXIFIFD, 1, 1, TIFF_IFD8, 0, TIFF_SETGET_IFD8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "EXIFIFDOffset", &exifFieldArray }, { TIFFTAG_ICCPROFILE, -3, -3, TIFF_UNDEFINED, 0, TIFF_SETGET_C32_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ICC Profile", NULL }, { TIFFTAG_GPSIFD, 1, 1, TIFF_IFD8, 0, TIFF_SETGET_IFD8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "GPSIFDOffset", NULL }, { TIFFTAG_FAXRECVPARAMS, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UINT32, FIELD_CUSTOM, TRUE, FALSE, "FaxRecvParams", NULL }, { TIFFTAG_FAXSUBADDRESS, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_ASCII, FIELD_CUSTOM, TRUE, FALSE, "FaxSubAddress", NULL }, { TIFFTAG_FAXRECVTIME, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UINT32, FIELD_CUSTOM, TRUE, FALSE, "FaxRecvTime", NULL }, { TIFFTAG_FAXDCS, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_ASCII, FIELD_CUSTOM, TRUE, FALSE, "FaxDcs", NULL }, { TIFFTAG_STONITS, 1, 1, TIFF_DOUBLE, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "StoNits", NULL }, { TIFFTAG_INTEROPERABILITYIFD, 1, 1, TIFF_IFD8, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "InteroperabilityIFDOffset", NULL }, /* begin DNG tags */ { TIFFTAG_DNGVERSION, 4, 4, TIFF_BYTE, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "DNGVersion", NULL }, { TIFFTAG_DNGBACKWARDVERSION, 4, 4, TIFF_BYTE, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "DNGBackwardVersion", NULL }, { TIFFTAG_UNIQUECAMERAMODEL, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "UniqueCameraModel", NULL }, { TIFFTAG_LOCALIZEDCAMERAMODEL, -1, -1, TIFF_BYTE, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "LocalizedCameraModel", NULL }, { TIFFTAG_CFAPLANECOLOR, -1, -1, TIFF_BYTE, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "CFAPlaneColor", NULL }, { TIFFTAG_CFALAYOUT, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "CFALayout", NULL }, { TIFFTAG_LINEARIZATIONTABLE, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_C16_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "LinearizationTable", NULL }, { TIFFTAG_BLACKLEVELREPEATDIM, 2, 2, TIFF_SHORT, 0, TIFF_SETGET_C0_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "BlackLevelRepeatDim", NULL }, { TIFFTAG_BLACKLEVEL, -1, -1, TIFF_RATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "BlackLevel", NULL }, { TIFFTAG_BLACKLEVELDELTAH, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "BlackLevelDeltaH", NULL }, { TIFFTAG_BLACKLEVELDELTAV, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "BlackLevelDeltaV", NULL }, { TIFFTAG_WHITELEVEL, -1, -1, TIFF_LONG, 0, TIFF_SETGET_C16_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "WhiteLevel", NULL }, { TIFFTAG_DEFAULTSCALE, 2, 2, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "DefaultScale", NULL }, { TIFFTAG_BESTQUALITYSCALE, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "BestQualityScale", NULL }, { TIFFTAG_DEFAULTCROPORIGIN, 2, 2, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "DefaultCropOrigin", NULL }, { TIFFTAG_DEFAULTCROPSIZE, 2, 2, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "DefaultCropSize", NULL }, { TIFFTAG_COLORMATRIX1, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ColorMatrix1", NULL }, { TIFFTAG_COLORMATRIX2, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ColorMatrix2", NULL }, { TIFFTAG_CAMERACALIBRATION1, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "CameraCalibration1", NULL }, { TIFFTAG_CAMERACALIBRATION2, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "CameraCalibration2", NULL }, { TIFFTAG_REDUCTIONMATRIX1, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ReductionMatrix1", NULL }, { TIFFTAG_REDUCTIONMATRIX2, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ReductionMatrix2", NULL }, { TIFFTAG_ANALOGBALANCE, -1, -1, TIFF_RATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "AnalogBalance", NULL }, { TIFFTAG_ASSHOTNEUTRAL, -1, -1, TIFF_RATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "AsShotNeutral", NULL }, { TIFFTAG_ASSHOTWHITEXY, 2, 2, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "AsShotWhiteXY", NULL }, { TIFFTAG_BASELINEEXPOSURE, 1, 1, TIFF_SRATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "BaselineExposure", NULL }, { TIFFTAG_BASELINENOISE, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "BaselineNoise", NULL }, { TIFFTAG_BASELINESHARPNESS, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "BaselineSharpness", NULL }, { TIFFTAG_BAYERGREENSPLIT, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "BayerGreenSplit", NULL }, { TIFFTAG_LINEARRESPONSELIMIT, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "LinearResponseLimit", NULL }, { TIFFTAG_CAMERASERIALNUMBER, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "CameraSerialNumber", NULL }, { TIFFTAG_LENSINFO, 4, 4, TIFF_RATIONAL, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "LensInfo", NULL }, { TIFFTAG_CHROMABLURRADIUS, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "ChromaBlurRadius", NULL }, { TIFFTAG_ANTIALIASSTRENGTH, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "AntiAliasStrength", NULL }, { TIFFTAG_SHADOWSCALE, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "ShadowScale", NULL }, { TIFFTAG_DNGPRIVATEDATA, -1, -1, TIFF_BYTE, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "DNGPrivateData", NULL }, { TIFFTAG_MAKERNOTESAFETY, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "MakerNoteSafety", NULL }, { TIFFTAG_CALIBRATIONILLUMINANT1, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "CalibrationIlluminant1", NULL }, { TIFFTAG_CALIBRATIONILLUMINANT2, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "CalibrationIlluminant2", NULL }, { TIFFTAG_RAWDATAUNIQUEID, 16, 16, TIFF_BYTE, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "RawDataUniqueID", NULL }, { TIFFTAG_ORIGINALRAWFILENAME, -1, -1, TIFF_BYTE, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "OriginalRawFileName", NULL }, { TIFFTAG_ORIGINALRAWFILEDATA, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "OriginalRawFileData", NULL }, { TIFFTAG_ACTIVEAREA, 4, 4, TIFF_LONG, 0, TIFF_SETGET_C0_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "ActiveArea", NULL }, { TIFFTAG_MASKEDAREAS, -1, -1, TIFF_LONG, 0, TIFF_SETGET_C16_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "MaskedAreas", NULL }, { TIFFTAG_ASSHOTICCPROFILE, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "AsShotICCProfile", NULL }, { TIFFTAG_ASSHOTPREPROFILEMATRIX, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "AsShotPreProfileMatrix", NULL }, { TIFFTAG_CURRENTICCPROFILE, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "CurrentICCProfile", NULL }, { TIFFTAG_CURRENTPREPROFILEMATRIX, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "CurrentPreProfileMatrix", NULL }, /* end DNG tags */ }; static TIFFField exifFields[] = { { EXIFTAG_EXPOSURETIME, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ExposureTime", NULL }, { EXIFTAG_FNUMBER, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FNumber", NULL }, { EXIFTAG_EXPOSUREPROGRAM, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ExposureProgram", NULL }, { EXIFTAG_SPECTRALSENSITIVITY, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SpectralSensitivity", NULL }, { EXIFTAG_ISOSPEEDRATINGS, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_C16_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "ISOSpeedRatings", NULL }, { EXIFTAG_OECF, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "OptoelectricConversionFactor", NULL }, { EXIFTAG_EXIFVERSION, 4, 4, TIFF_UNDEFINED, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ExifVersion", NULL }, { EXIFTAG_DATETIMEORIGINAL, 20, 20, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "DateTimeOriginal", NULL }, { EXIFTAG_DATETIMEDIGITIZED, 20, 20, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "DateTimeDigitized", NULL }, { EXIFTAG_COMPONENTSCONFIGURATION, 4, 4, TIFF_UNDEFINED, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ComponentsConfiguration", NULL }, { EXIFTAG_COMPRESSEDBITSPERPIXEL, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "CompressedBitsPerPixel", NULL }, { EXIFTAG_SHUTTERSPEEDVALUE, 1, 1, TIFF_SRATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ShutterSpeedValue", NULL }, { EXIFTAG_APERTUREVALUE, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ApertureValue", NULL }, { EXIFTAG_BRIGHTNESSVALUE, 1, 1, TIFF_SRATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "BrightnessValue", NULL }, { EXIFTAG_EXPOSUREBIASVALUE, 1, 1, TIFF_SRATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ExposureBiasValue", NULL }, { EXIFTAG_MAXAPERTUREVALUE, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "MaxApertureValue", NULL }, { EXIFTAG_SUBJECTDISTANCE, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SubjectDistance", NULL }, { EXIFTAG_METERINGMODE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "MeteringMode", NULL }, { EXIFTAG_LIGHTSOURCE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "LightSource", NULL }, { EXIFTAG_FLASH, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Flash", NULL }, { EXIFTAG_FOCALLENGTH, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FocalLength", NULL }, { EXIFTAG_SUBJECTAREA, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_C16_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "SubjectArea", NULL }, { EXIFTAG_MAKERNOTE, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "MakerNote", NULL }, { EXIFTAG_USERCOMMENT, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "UserComment", NULL }, { EXIFTAG_SUBSECTIME, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SubSecTime", NULL }, { EXIFTAG_SUBSECTIMEORIGINAL, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SubSecTimeOriginal", NULL }, { EXIFTAG_SUBSECTIMEDIGITIZED, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SubSecTimeDigitized", NULL }, { EXIFTAG_FLASHPIXVERSION, 4, 4, TIFF_UNDEFINED, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FlashpixVersion", NULL }, { EXIFTAG_COLORSPACE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ColorSpace", NULL }, { EXIFTAG_PIXELXDIMENSION, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "PixelXDimension", NULL }, { EXIFTAG_PIXELYDIMENSION, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "PixelYDimension", NULL }, { EXIFTAG_RELATEDSOUNDFILE, 13, 13, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "RelatedSoundFile", NULL }, { EXIFTAG_FLASHENERGY, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FlashEnergy", NULL }, { EXIFTAG_SPATIALFREQUENCYRESPONSE, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "SpatialFrequencyResponse", NULL }, { EXIFTAG_FOCALPLANEXRESOLUTION, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FocalPlaneXResolution", NULL }, { EXIFTAG_FOCALPLANEYRESOLUTION, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FocalPlaneYResolution", NULL }, { EXIFTAG_FOCALPLANERESOLUTIONUNIT, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FocalPlaneResolutionUnit", NULL }, { EXIFTAG_SUBJECTLOCATION, 2, 2, TIFF_SHORT, 0, TIFF_SETGET_C0_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SubjectLocation", NULL }, { EXIFTAG_EXPOSUREINDEX, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ExposureIndex", NULL }, { EXIFTAG_SENSINGMETHOD, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SensingMethod", NULL }, { EXIFTAG_FILESOURCE, 1, 1, TIFF_UNDEFINED, 0, TIFF_SETGET_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FileSource", NULL }, { EXIFTAG_SCENETYPE, 1, 1, TIFF_UNDEFINED, 0, TIFF_SETGET_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SceneType", NULL }, { EXIFTAG_CFAPATTERN, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "CFAPattern", NULL }, { EXIFTAG_CUSTOMRENDERED, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "CustomRendered", NULL }, { EXIFTAG_EXPOSUREMODE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ExposureMode", NULL }, { EXIFTAG_WHITEBALANCE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "WhiteBalance", NULL }, { EXIFTAG_DIGITALZOOMRATIO, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "DigitalZoomRatio", NULL }, { EXIFTAG_FOCALLENGTHIN35MMFILM, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FocalLengthIn35mmFilm", NULL }, { EXIFTAG_SCENECAPTURETYPE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SceneCaptureType", NULL }, { EXIFTAG_GAINCONTROL, 1, 1, TIFF_RATIONAL, 0, TIFF_SETGET_DOUBLE, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "GainControl", NULL }, { EXIFTAG_CONTRAST, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Contrast", NULL }, { EXIFTAG_SATURATION, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Saturation", NULL }, { EXIFTAG_SHARPNESS, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Sharpness", NULL }, { EXIFTAG_DEVICESETTINGDESCRIPTION, -1, -1, TIFF_UNDEFINED, 0, TIFF_SETGET_C16_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 1, "DeviceSettingDescription", NULL }, { EXIFTAG_SUBJECTDISTANCERANGE, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "SubjectDistanceRange", NULL }, { EXIFTAG_IMAGEUNIQUEID, 33, 33, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "ImageUniqueID", NULL } }; static TIFFFieldArray tiffFieldArray = { tfiatImage, 0, TIFFArrayCount(tiffFields), tiffFields }; static TIFFFieldArray exifFieldArray = { tfiatExif, 0, TIFFArrayCount(exifFields), exifFields }; const TIFFFieldArray* _TIFFGetFields(void) { return(&tiffFieldArray); } const TIFFFieldArray* _TIFFGetExifFields(void) { return(&exifFieldArray); } void _TIFFSetupFields(TIFF* tif, const TIFFFieldArray* fieldarray) { if (tif->tif_fields && tif->tif_nfields > 0) { uint32 i; for (i = 0; i < tif->tif_nfields; i++) { TIFFField *fld = tif->tif_fields[i]; if (fld->field_bit == FIELD_CUSTOM && strncmp("Tag ", fld->field_name, 4) == 0) { _TIFFfree(fld->field_name); _TIFFfree(fld); } } _TIFFfree(tif->tif_fields); tif->tif_fields = NULL; tif->tif_nfields = 0; } if (!_TIFFMergeFields(tif, fieldarray->fields, fieldarray->count)) { TIFFErrorExt(tif->tif_clientdata, "_TIFFSetupFields", "Setting up field info failed"); } } static int tagCompare(const void* a, const void* b) { const TIFFField* ta = *(const TIFFField**) a; const TIFFField* tb = *(const TIFFField**) b; /* NB: be careful of return values for 16-bit platforms */ if (ta->field_tag != tb->field_tag) return (int)ta->field_tag - (int)tb->field_tag; else return (ta->field_type == TIFF_ANY) ? 0 : ((int)tb->field_type - (int)ta->field_type); } static int tagNameCompare(const void* a, const void* b) { const TIFFField* ta = *(const TIFFField**) a; const TIFFField* tb = *(const TIFFField**) b; int ret = strcmp(ta->field_name, tb->field_name); if (ret) return ret; else return (ta->field_type == TIFF_ANY) ? 0 : ((int)tb->field_type - (int)ta->field_type); } int _TIFFMergeFields(TIFF* tif, const TIFFField info[], uint32 n) { static const char module[] = "_TIFFMergeFields"; static const char reason[] = "for fields array"; TIFFField** tp; uint32 i; tif->tif_foundfield = NULL; if (tif->tif_fields && tif->tif_nfields > 0) { tif->tif_fields = (TIFFField**) _TIFFCheckRealloc(tif, tif->tif_fields, (tif->tif_nfields + n), sizeof(TIFFField *), reason); } else { tif->tif_fields = (TIFFField **) _TIFFCheckMalloc(tif, n, sizeof(TIFFField *), reason); } if (!tif->tif_fields) { TIFFErrorExt(tif->tif_clientdata, module, "Failed to allocate fields array"); return 0; } tp = tif->tif_fields + tif->tif_nfields; for (i = 0; i < n; i++) { const TIFFField *fip = TIFFFindField(tif, info[i].field_tag, TIFF_ANY); /* only add definitions that aren't already present */ if (!fip) { tif->tif_fields[tif->tif_nfields] = (TIFFField *) (info+i); tif->tif_nfields++; } } /* Sort the field info by tag number */ qsort(tif->tif_fields, tif->tif_nfields, sizeof(TIFFField *), tagCompare); return n; } void _TIFFPrintFieldInfo(TIFF* tif, FILE* fd) { uint32 i; fprintf(fd, "%s: \n", tif->tif_name); for (i = 0; i < tif->tif_nfields; i++) { const TIFFField* fip = tif->tif_fields[i]; fprintf(fd, "field[%2d] %5lu, %2d, %2d, %d, %2d, %5s, %5s, %s\n" , (int)i , (unsigned long) fip->field_tag , fip->field_readcount, fip->field_writecount , fip->field_type , fip->field_bit , fip->field_oktochange ? "TRUE" : "FALSE" , fip->field_passcount ? "TRUE" : "FALSE" , fip->field_name ); } } /* * Return size of TIFFDataType in bytes */ int TIFFDataWidth(TIFFDataType type) { switch(type) { case 0: /* nothing */ case TIFF_BYTE: case TIFF_ASCII: case TIFF_SBYTE: case TIFF_UNDEFINED: return 1; case TIFF_SHORT: case TIFF_SSHORT: return 2; case TIFF_LONG: case TIFF_SLONG: case TIFF_FLOAT: case TIFF_IFD: return 4; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_DOUBLE: case TIFF_LONG8: case TIFF_SLONG8: case TIFF_IFD8: return 8; default: return 0; /* will return 0 for unknown types */ } } /* * Return size of TIFFDataType in bytes. * * XXX: We need a separate function to determine the space needed * to store the value. For TIFF_RATIONAL values TIFFDataWidth() returns 8, * but we use 4-byte float to represent rationals. */ int _TIFFDataSize(TIFFDataType type) { switch (type) { case TIFF_BYTE: case TIFF_SBYTE: case TIFF_ASCII: case TIFF_UNDEFINED: return 1; case TIFF_SHORT: case TIFF_SSHORT: return 2; case TIFF_LONG: case TIFF_SLONG: case TIFF_FLOAT: case TIFF_IFD: case TIFF_RATIONAL: case TIFF_SRATIONAL: return 4; case TIFF_DOUBLE: case TIFF_LONG8: case TIFF_SLONG8: case TIFF_IFD8: return 8; default: return 0; } } const TIFFField* TIFFFindField(TIFF* tif, uint32 tag, TIFFDataType dt) { TIFFField key = {0, 0, 0, TIFF_NOTYPE, 0, 0, 0, 0, 0, 0, NULL, NULL}; TIFFField* pkey = &key; const TIFFField **ret; if (tif->tif_foundfield && tif->tif_foundfield->field_tag == tag && (dt == TIFF_ANY || dt == tif->tif_foundfield->field_type)) return tif->tif_foundfield; /* If we are invoked with no field information, then just return. */ if (!tif->tif_fields) return NULL; /* NB: use sorted search (e.g. binary search) */ key.field_tag = tag; key.field_type = dt; ret = (const TIFFField **) bsearch(&pkey, tif->tif_fields, tif->tif_nfields, sizeof(TIFFField *), tagCompare); return tif->tif_foundfield = (ret ? *ret : NULL); } const TIFFField* _TIFFFindFieldByName(TIFF* tif, const char *field_name, TIFFDataType dt) { TIFFField key = {0, 0, 0, TIFF_NOTYPE, 0, 0, 0, 0, 0, 0, NULL, NULL}; TIFFField* pkey = &key; const TIFFField **ret; if (tif->tif_foundfield && streq(tif->tif_foundfield->field_name, field_name) && (dt == TIFF_ANY || dt == tif->tif_foundfield->field_type)) return (tif->tif_foundfield); /* If we are invoked with no field information, then just return. */ if (!tif->tif_fields) return NULL; /* NB: use sorted search (e.g. binary search) */ key.field_name = (char *)field_name; key.field_type = dt; ret = (const TIFFField **) lfind(&pkey, tif->tif_fields, &tif->tif_nfields, sizeof(TIFFField *), tagNameCompare); return tif->tif_foundfield = (ret ? *ret : NULL); } const TIFFField* TIFFFieldWithTag(TIFF* tif, uint32 tag) { const TIFFField* fip = TIFFFindField(tif, tag, TIFF_ANY); if (!fip) { TIFFErrorExt(tif->tif_clientdata, "TIFFFieldWithTag", "Internal error, unknown tag 0x%x", (unsigned int) tag); assert(fip != NULL); /*NOTREACHED*/ } return (fip); } const TIFFField* TIFFFieldWithName(TIFF* tif, const char *field_name) { const TIFFField* fip = _TIFFFindFieldByName(tif, field_name, TIFF_ANY); if (!fip) { TIFFErrorExt(tif->tif_clientdata, "TIFFFieldWithName", "Internal error, unknown tag %s", field_name); assert(fip != NULL); /*NOTREACHED*/ } return (fip); } const TIFFField* _TIFFFindOrRegisterField(TIFF *tif, uint32 tag, TIFFDataType dt) { const TIFFField *fld; fld = TIFFFindField(tif, tag, dt); if (fld == NULL) { fld = _TIFFCreateAnonField(tif, tag, dt); if (!_TIFFMergeFields(tif, fld, 1)) return NULL; } return fld; } TIFFField* _TIFFCreateAnonField(TIFF *tif, uint32 tag, TIFFDataType field_type) { TIFFField *fld; (void) tif; fld = (TIFFField *) _TIFFmalloc(sizeof (TIFFField)); if (fld == NULL) return NULL; _TIFFmemset(fld, 0, sizeof(TIFFField)); fld->field_tag = tag; fld->field_readcount = TIFF_VARIABLE2; fld->field_writecount = TIFF_VARIABLE2; fld->field_type = field_type; fld->reserved = 0; switch (field_type) { case TIFF_BYTE: case TIFF_UNDEFINED: fld->set_field_type = TIFF_SETGET_C32_UINT8; fld->get_field_type = TIFF_SETGET_C32_UINT8; break; case TIFF_ASCII: fld->set_field_type = TIFF_SETGET_C32_ASCII; fld->get_field_type = TIFF_SETGET_C32_ASCII; break; case TIFF_SHORT: fld->set_field_type = TIFF_SETGET_C32_UINT16; fld->get_field_type = TIFF_SETGET_C32_UINT16; break; case TIFF_LONG: fld->set_field_type = TIFF_SETGET_C32_UINT32; fld->get_field_type = TIFF_SETGET_C32_UINT32; break; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: fld->set_field_type = TIFF_SETGET_C32_FLOAT; fld->get_field_type = TIFF_SETGET_C32_FLOAT; break; case TIFF_SBYTE: fld->set_field_type = TIFF_SETGET_C32_SINT8; fld->get_field_type = TIFF_SETGET_C32_SINT8; break; case TIFF_SSHORT: fld->set_field_type = TIFF_SETGET_C32_SINT16; fld->get_field_type = TIFF_SETGET_C32_SINT16; break; case TIFF_SLONG: fld->set_field_type = TIFF_SETGET_C32_SINT32; fld->get_field_type = TIFF_SETGET_C32_SINT32; break; case TIFF_DOUBLE: fld->set_field_type = TIFF_SETGET_C32_DOUBLE; fld->get_field_type = TIFF_SETGET_C32_DOUBLE; break; case TIFF_IFD: case TIFF_IFD8: fld->set_field_type = TIFF_SETGET_C32_IFD8; fld->get_field_type = TIFF_SETGET_C32_IFD8; break; case TIFF_LONG8: fld->set_field_type = TIFF_SETGET_C32_UINT64; fld->get_field_type = TIFF_SETGET_C32_UINT64; break; case TIFF_SLONG8: fld->set_field_type = TIFF_SETGET_C32_SINT64; fld->get_field_type = TIFF_SETGET_C32_SINT64; break; default: fld->set_field_type = TIFF_SETGET_UNDEFINED; fld->get_field_type = TIFF_SETGET_UNDEFINED; break; } fld->field_bit = FIELD_CUSTOM; fld->field_oktochange = TRUE; fld->field_passcount = TRUE; fld->field_name = (char *) _TIFFmalloc(32); if (fld->field_name == NULL) { _TIFFfree(fld); return NULL; } fld->field_subfields = NULL; /* * note that this name is a special sign to TIFFClose() and * _TIFFSetupFields() to free the field */ sprintf(fld->field_name, "Tag %d", (int) tag); return fld; } /**************************************************************************** * O B S O L E T E D I N T E R F A C E S * * Don't use this stuff in your applications, it may be removed in the future * libtiff versions. ****************************************************************************/ static TIFFSetGetFieldType _TIFFSetGetType(TIFFDataType type, short count, unsigned char passcount) { if (type == TIFF_ASCII && count == TIFF_VARIABLE && passcount == 0) return TIFF_SETGET_ASCII; else if (count == 1 && passcount == 0) { switch (type) { case TIFF_BYTE: case TIFF_UNDEFINED: return TIFF_SETGET_UINT8; case TIFF_ASCII: return TIFF_SETGET_ASCII; case TIFF_SHORT: return TIFF_SETGET_UINT16; case TIFF_LONG: return TIFF_SETGET_UINT32; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: return TIFF_SETGET_FLOAT; case TIFF_SBYTE: return TIFF_SETGET_SINT8; case TIFF_SSHORT: return TIFF_SETGET_SINT16; case TIFF_SLONG: return TIFF_SETGET_SINT32; case TIFF_DOUBLE: return TIFF_SETGET_DOUBLE; case TIFF_IFD: case TIFF_IFD8: return TIFF_SETGET_IFD8; case TIFF_LONG8: return TIFF_SETGET_UINT64; case TIFF_SLONG8: return TIFF_SETGET_SINT64; default: return TIFF_SETGET_UNDEFINED; } } else if (count >= 1 && passcount == 0) { switch (type) { case TIFF_BYTE: case TIFF_UNDEFINED: return TIFF_SETGET_C0_UINT8; case TIFF_ASCII: return TIFF_SETGET_C0_ASCII; case TIFF_SHORT: return TIFF_SETGET_C0_UINT16; case TIFF_LONG: return TIFF_SETGET_C0_UINT32; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: return TIFF_SETGET_C0_FLOAT; case TIFF_SBYTE: return TIFF_SETGET_C0_SINT8; case TIFF_SSHORT: return TIFF_SETGET_C0_SINT16; case TIFF_SLONG: return TIFF_SETGET_C0_SINT32; case TIFF_DOUBLE: return TIFF_SETGET_C0_DOUBLE; case TIFF_IFD: case TIFF_IFD8: return TIFF_SETGET_C0_IFD8; case TIFF_LONG8: return TIFF_SETGET_C0_UINT64; case TIFF_SLONG8: return TIFF_SETGET_C0_SINT64; default: return TIFF_SETGET_UNDEFINED; } } else if (count == TIFF_VARIABLE && passcount == 1) { switch (type) { case TIFF_BYTE: case TIFF_UNDEFINED: return TIFF_SETGET_C16_UINT8; case TIFF_ASCII: return TIFF_SETGET_C16_ASCII; case TIFF_SHORT: return TIFF_SETGET_C16_UINT16; case TIFF_LONG: return TIFF_SETGET_C16_UINT32; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: return TIFF_SETGET_C16_FLOAT; case TIFF_SBYTE: return TIFF_SETGET_C16_SINT8; case TIFF_SSHORT: return TIFF_SETGET_C16_SINT16; case TIFF_SLONG: return TIFF_SETGET_C16_SINT32; case TIFF_DOUBLE: return TIFF_SETGET_C16_DOUBLE; case TIFF_IFD: case TIFF_IFD8: return TIFF_SETGET_C16_IFD8; case TIFF_LONG8: return TIFF_SETGET_C16_UINT64; case TIFF_SLONG8: return TIFF_SETGET_C16_SINT64; default: return TIFF_SETGET_UNDEFINED; } } else if (count == TIFF_VARIABLE2 && passcount == 1) { switch (type) { case TIFF_BYTE: case TIFF_UNDEFINED: return TIFF_SETGET_C32_UINT8; case TIFF_ASCII: return TIFF_SETGET_C32_ASCII; case TIFF_SHORT: return TIFF_SETGET_C32_UINT16; case TIFF_LONG: return TIFF_SETGET_C32_UINT32; case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: return TIFF_SETGET_C32_FLOAT; case TIFF_SBYTE: return TIFF_SETGET_C32_SINT8; case TIFF_SSHORT: return TIFF_SETGET_C32_SINT16; case TIFF_SLONG: return TIFF_SETGET_C32_SINT32; case TIFF_DOUBLE: return TIFF_SETGET_C32_DOUBLE; case TIFF_IFD: case TIFF_IFD8: return TIFF_SETGET_C32_IFD8; case TIFF_LONG8: return TIFF_SETGET_C32_UINT64; case TIFF_SLONG8: return TIFF_SETGET_C32_SINT64; default: return TIFF_SETGET_UNDEFINED; } } return TIFF_SETGET_UNDEFINED; } int TIFFMergeFieldInfo(TIFF* tif, const TIFFFieldInfo info[], uint32 n) { static const char module[] = "TIFFMergeFieldInfo"; static const char reason[] = "for fields array"; TIFFField *tp; size_t nfields; uint32 i; if (tif->tif_nfieldscompat > 0) { tif->tif_fieldscompat = (TIFFFieldArray *) _TIFFCheckRealloc(tif, tif->tif_fieldscompat, tif->tif_nfieldscompat + 1, sizeof(TIFFFieldArray), reason); } else { tif->tif_fieldscompat = (TIFFFieldArray *) _TIFFCheckMalloc(tif, 1, sizeof(TIFFFieldArray), reason); } if (!tif->tif_fieldscompat) { TIFFErrorExt(tif->tif_clientdata, module, "Failed to allocate fields array"); return -1; } nfields = tif->tif_nfieldscompat++; tif->tif_fieldscompat[nfields].type = tfiatOther; tif->tif_fieldscompat[nfields].allocated_size = n; tif->tif_fieldscompat[nfields].count = n; tif->tif_fieldscompat[nfields].fields = (TIFFField *)_TIFFCheckMalloc(tif, n, sizeof(TIFFField), reason); if (!tif->tif_fieldscompat[nfields].fields) { TIFFErrorExt(tif->tif_clientdata, module, "Failed to allocate fields array"); return -1; } tp = tif->tif_fieldscompat[nfields].fields; for (i = 0; i < n; i++) { tp->field_tag = info[i].field_tag; tp->field_readcount = info[i].field_readcount; tp->field_writecount = info[i].field_writecount; tp->field_type = info[i].field_type; tp->reserved = 0; tp->set_field_type = _TIFFSetGetType(info[i].field_type, info[i].field_readcount, info[i].field_passcount); tp->get_field_type = _TIFFSetGetType(info[i].field_type, info[i].field_readcount, info[i].field_passcount); tp->field_bit = info[i].field_bit; tp->field_oktochange = info[i].field_oktochange; tp->field_passcount = info[i].field_passcount; tp->field_name = info[i].field_name; tp->field_subfields = NULL; tp++; } if (!_TIFFMergeFields(tif, tif->tif_fieldscompat[nfields].fields, n)) { TIFFErrorExt(tif->tif_clientdata, module, "Setting up field info failed"); return -1; } return 0; } const TIFFFieldInfo* TIFFFindFieldInfoByName(TIFF* tif, const char *field_name, TIFFDataType dt) { #if 0 TIFFFieldInfo key = {0, 0, 0, TIFF_NOTYPE, 0, 0, 0, 0, 0, 0, NULL, NULL}; TIFFFieldInfo* pkey = &key; const TIFFFieldInfo **ret; if (tif->tif_foundfield && streq(tif->tif_foundfield->field_name, field_name) && (dt == TIFF_ANY || dt == tif->tif_foundfield->field_type)) return (tif->tif_foundfield); /* If we are invoked with no field information, then just return. */ if ( !tif->tif_fields ) { return NULL; } /* NB: use sorted search (e.g. binary search) */ key.field_name = (char *)field_name; key.field_type = dt; ret = (const TIFFFieldInfo **) lfind(&pkey, tif->tif_fields, &tif->tif_nfields, sizeof(TIFFFieldInfo *), tagNameCompare); return tif->tif_foundfield = (ret ? *ret : NULL); #endif return NULL; } const TIFFFieldInfo* TIFFFindFieldInfo(TIFF* tif, uint32 tag, TIFFDataType dt) { #if 0 TIFFFieldInfo key = {0, 0, 0, TIFF_NOTYPE, 0, 0, 0, 0, 0, 0, NULL, NULL}; TIFFFieldInfo* pkey = &key; const TIFFFieldInfo **ret; if (tif->tif_foundfield && tif->tif_foundfield->field_tag == tag && (dt == TIFF_ANY || dt == tif->tif_foundfield->field_type)) return tif->tif_foundfield; /* If we are invoked with no field information, then just return. */ if ( !tif->tif_fields ) { return NULL; } /* NB: use sorted search (e.g. binary search) */ key.field_tag = tag; key.field_type = dt; ret = (const TIFFFieldInfo **) bsearch(&pkey, tif->tif_fields, tif->tif_nfields, sizeof(TIFFFieldInfo *), tagCompare); return tif->tif_foundfield = (ret ? *ret : NULL); #endif return NULL; } /* vim: set ts=8 sts=8 sw=8 noet: */
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/libtiff_2008-04-15-2e8b2f1-0d27dc0.c
manybugs_data_100
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Wez Furlong <[email protected]> | | Sara Golemon <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "php.h" #include "php_globals.h" #include "ext/standard/file.h" #include "ext/standard/flock_compat.h" #ifdef HAVE_SYS_FILE_H #include <sys/file.h> #endif static int le_protocols; struct php_user_stream_wrapper { char * protoname; char * classname; zend_class_entry *ce; php_stream_wrapper wrapper; }; static php_stream *user_wrapper_opener(php_stream_wrapper *wrapper, char *filename, char *mode, int options, char **opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC); static int user_wrapper_stat_url(php_stream_wrapper *wrapper, char *url, int flags, php_stream_statbuf *ssb, php_stream_context *context TSRMLS_DC); static int user_wrapper_unlink(php_stream_wrapper *wrapper, char *url, int options, php_stream_context *context TSRMLS_DC); static int user_wrapper_rename(php_stream_wrapper *wrapper, char *url_from, char *url_to, int options, php_stream_context *context TSRMLS_DC); static int user_wrapper_mkdir(php_stream_wrapper *wrapper, char *url, int mode, int options, php_stream_context *context TSRMLS_DC); static int user_wrapper_rmdir(php_stream_wrapper *wrapper, char *url, int options, php_stream_context *context TSRMLS_DC); static php_stream *user_wrapper_opendir(php_stream_wrapper *wrapper, char *filename, char *mode, int options, char **opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC); static php_stream_wrapper_ops user_stream_wops = { user_wrapper_opener, NULL, /* close - the streams themselves know how */ NULL, /* stat - the streams themselves know how */ user_wrapper_stat_url, user_wrapper_opendir, "user-space", user_wrapper_unlink, user_wrapper_rename, user_wrapper_mkdir, user_wrapper_rmdir }; static void stream_wrapper_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC) { struct php_user_stream_wrapper * uwrap = (struct php_user_stream_wrapper*)rsrc->ptr; efree(uwrap->protoname); efree(uwrap->classname); efree(uwrap); } PHP_MINIT_FUNCTION(user_streams) { le_protocols = zend_register_list_destructors_ex(stream_wrapper_dtor, NULL, "stream factory", 0); if (le_protocols == FAILURE) return FAILURE; REGISTER_LONG_CONSTANT("STREAM_USE_PATH", USE_PATH, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_IGNORE_URL", IGNORE_URL, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_REPORT_ERRORS", REPORT_ERRORS, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_MUST_SEEK", STREAM_MUST_SEEK, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_URL_STAT_LINK", PHP_STREAM_URL_STAT_LINK, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_URL_STAT_QUIET", PHP_STREAM_URL_STAT_QUIET, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_MKDIR_RECURSIVE", PHP_STREAM_MKDIR_RECURSIVE, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_IS_URL", PHP_STREAM_IS_URL, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_OPTION_BLOCKING", PHP_STREAM_OPTION_BLOCKING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_OPTION_READ_TIMEOUT", PHP_STREAM_OPTION_READ_TIMEOUT, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_OPTION_READ_BUFFER", PHP_STREAM_OPTION_READ_BUFFER, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_OPTION_WRITE_BUFFER", PHP_STREAM_OPTION_WRITE_BUFFER, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_BUFFER_NONE", PHP_STREAM_BUFFER_NONE, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_BUFFER_LINE", PHP_STREAM_BUFFER_LINE, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_BUFFER_FULL", PHP_STREAM_BUFFER_FULL, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_CAST_AS_STREAM", PHP_STREAM_AS_STDIO, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_CAST_FOR_SELECT", PHP_STREAM_AS_FD_FOR_SELECT, CONST_CS|CONST_PERSISTENT); return SUCCESS; } struct _php_userstream_data { struct php_user_stream_wrapper * wrapper; zval * object; }; typedef struct _php_userstream_data php_userstream_data_t; /* names of methods */ #define USERSTREAM_OPEN "stream_open" #define USERSTREAM_CLOSE "stream_close" #define USERSTREAM_READ "stream_read" #define USERSTREAM_WRITE "stream_write" #define USERSTREAM_FLUSH "stream_flush" #define USERSTREAM_SEEK "stream_seek" #define USERSTREAM_TELL "stream_tell" #define USERSTREAM_EOF "stream_eof" #define USERSTREAM_STAT "stream_stat" #define USERSTREAM_STATURL "url_stat" #define USERSTREAM_UNLINK "unlink" #define USERSTREAM_RENAME "rename" #define USERSTREAM_MKDIR "mkdir" #define USERSTREAM_RMDIR "rmdir" #define USERSTREAM_DIR_OPEN "dir_opendir" #define USERSTREAM_DIR_READ "dir_readdir" #define USERSTREAM_DIR_REWIND "dir_rewinddir" #define USERSTREAM_DIR_CLOSE "dir_closedir" #define USERSTREAM_LOCK "stream_lock" #define USERSTREAM_CAST "stream_cast" #define USERSTREAM_SET_OPTION "stream_set_option" /* {{{ class should have methods like these: function stream_open($path, $mode, $options, &$opened_path) { return true/false; } function stream_read($count) { return false on error; else return string; } function stream_write($data) { return false on error; else return count written; } function stream_close() { } function stream_flush() { return true/false; } function stream_seek($offset, $whence) { return true/false; } function stream_tell() { return (int)$position; } function stream_eof() { return true/false; } function stream_stat() { return array( just like that returned by fstat() ); } function stream_cast($castas) { if ($castas == STREAM_CAST_FOR_SELECT) { return $this->underlying_stream; } return false; } function stream_set_option($option, $arg1, $arg2) { switch($option) { case STREAM_OPTION_BLOCKING: $blocking = $arg1; ... case STREAM_OPTION_READ_TIMEOUT: $sec = $arg1; $usec = $arg2; ... case STREAM_OPTION_WRITE_BUFFER: $mode = $arg1; $size = $arg2; ... default: return false; } } function url_stat(string $url, int $flags) { return array( just like that returned by stat() ); } function unlink(string $url) { return true / false; } function rename(string $from, string $to) { return true / false; } function mkdir($dir, $mode, $options) { return true / false; } function rmdir($dir, $options) { return true / false; } function dir_opendir(string $url, int $options) { return true / false; } function dir_readdir() { return string next filename in dir ; } function dir_closedir() { release dir related resources; } function dir_rewinddir() { reset to start of dir list; } function stream_lock($operation) { return true / false; } }}} **/ static php_stream *user_wrapper_opener(php_stream_wrapper *wrapper, char *filename, char *mode, int options, char **opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC) { struct php_user_stream_wrapper *uwrap = (struct php_user_stream_wrapper*)wrapper->abstract; php_userstream_data_t *us; zval *zfilename, *zmode, *zopened, *zoptions, *zretval = NULL, *zfuncname; zval **args[4]; int call_result; php_stream *stream = NULL; zend_bool old_in_user_include; /* Try to catch bad usage without preventing flexibility */ if (FG(user_stream_current_filename) != NULL && strcmp(filename, FG(user_stream_current_filename)) == 0) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "infinite recursion prevented"); return NULL; } FG(user_stream_current_filename) = filename; /* if the user stream was registered as local and we are in include context, we add allow_url_include restrictions to allow_url_fopen ones */ /* we need only is_url == 0 here since if is_url == 1 and remote wrappers were restricted we wouldn't get here */ old_in_user_include = PG(in_user_include); if(uwrap->wrapper.is_url == 0 && (options & STREAM_OPEN_FOR_INCLUDE) && !PG(allow_url_include)) { PG(in_user_include) = 1; } us = emalloc(sizeof(*us)); us->wrapper = uwrap; /* create an instance of our class */ ALLOC_ZVAL(us->object); object_init_ex(us->object, uwrap->ce); Z_SET_REFCOUNT_P(us->object, 1); Z_SET_ISREF_P(us->object); if (uwrap->ce->constructor) { zend_fcall_info fci; zend_fcall_info_cache fcc; zval *retval_ptr; fci.size = sizeof(fci); fci.function_table = &uwrap->ce->function_table; fci.function_name = NULL; fci.symbol_table = NULL; fci.object_ptr = us->object; fci.retval_ptr_ptr = &retval_ptr; fci.param_count = 0; fci.params = NULL; fci.no_separation = 1; fcc.initialized = 1; fcc.function_handler = uwrap->ce->constructor; fcc.calling_scope = EG(scope); fcc.called_scope = Z_OBJCE_P(us->object); fcc.object_ptr = us->object; if (zend_call_function(&fci, &fcc TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not execute %s::%s()", uwrap->ce->name, uwrap->ce->constructor->common.function_name); zval_dtor(us->object); FREE_ZVAL(us->object); efree(us); FG(user_stream_current_filename) = NULL; PG(in_user_include) = old_in_user_include; return NULL; } else { if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } } } if (context) { add_property_resource(us->object, "context", context->rsrc_id); zend_list_addref(context->rsrc_id); } else { add_property_null(us->object, "context"); } /* call it's stream_open method - set up params first */ MAKE_STD_ZVAL(zfilename); ZVAL_STRING(zfilename, filename, 1); args[0] = &zfilename; MAKE_STD_ZVAL(zmode); ZVAL_STRING(zmode, mode, 1); args[1] = &zmode; MAKE_STD_ZVAL(zoptions); ZVAL_LONG(zoptions, options); args[2] = &zoptions; MAKE_STD_ZVAL(zopened); Z_SET_REFCOUNT_P(zopened, 1); Z_SET_ISREF_P(zopened); ZVAL_NULL(zopened); args[3] = &zopened; MAKE_STD_ZVAL(zfuncname); ZVAL_STRING(zfuncname, USERSTREAM_OPEN, 1); call_result = call_user_function_ex(NULL, &us->object, zfuncname, &zretval, 4, args, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && zretval != NULL && zval_is_true(zretval)) { /* the stream is now open! */ stream = php_stream_alloc_rel(&php_stream_userspace_ops, us, 0, mode); /* if the opened path is set, copy it out */ if (Z_TYPE_P(zopened) == IS_STRING && opened_path) { *opened_path = estrndup(Z_STRVAL_P(zopened), Z_STRLEN_P(zopened)); } /* set wrapper data to be a reference to our object */ stream->wrapperdata = us->object; zval_add_ref(&stream->wrapperdata); } else { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "\"%s::" USERSTREAM_OPEN "\" call failed", us->wrapper->classname); } /* destroy everything else */ if (stream == NULL) { zval_ptr_dtor(&us->object); efree(us); } if (zretval) zval_ptr_dtor(&zretval); zval_ptr_dtor(&zfuncname); zval_ptr_dtor(&zopened); zval_ptr_dtor(&zoptions); zval_ptr_dtor(&zmode); zval_ptr_dtor(&zfilename); FG(user_stream_current_filename) = NULL; PG(in_user_include) = old_in_user_include; return stream; } static php_stream *user_wrapper_opendir(php_stream_wrapper *wrapper, char *filename, char *mode, int options, char **opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC) { struct php_user_stream_wrapper *uwrap = (struct php_user_stream_wrapper*)wrapper->abstract; php_userstream_data_t *us; zval *zfilename, *zoptions, *zretval = NULL, *zfuncname; zval **args[2]; int call_result; php_stream *stream = NULL; /* Try to catch bad usage without preventing flexibility */ if (FG(user_stream_current_filename) != NULL && strcmp(filename, FG(user_stream_current_filename)) == 0) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "infinite recursion prevented"); return NULL; } FG(user_stream_current_filename) = filename; us = emalloc(sizeof(*us)); us->wrapper = uwrap; /* create an instance of our class */ ALLOC_ZVAL(us->object); object_init_ex(us->object, uwrap->ce); Z_SET_REFCOUNT_P(us->object, 1); Z_SET_ISREF_P(us->object); if (context) { add_property_resource(us->object, "context", context->rsrc_id); zend_list_addref(context->rsrc_id); } else { add_property_null(us->object, "context"); } /* call it's dir_open method - set up params first */ MAKE_STD_ZVAL(zfilename); ZVAL_STRING(zfilename, filename, 1); args[0] = &zfilename; MAKE_STD_ZVAL(zoptions); ZVAL_LONG(zoptions, options); args[1] = &zoptions; MAKE_STD_ZVAL(zfuncname); ZVAL_STRING(zfuncname, USERSTREAM_DIR_OPEN, 1); call_result = call_user_function_ex(NULL, &us->object, zfuncname, &zretval, 2, args, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && zretval != NULL && zval_is_true(zretval)) { /* the stream is now open! */ stream = php_stream_alloc_rel(&php_stream_userspace_dir_ops, us, 0, mode); /* set wrapper data to be a reference to our object */ stream->wrapperdata = us->object; zval_add_ref(&stream->wrapperdata); } else { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "\"%s::" USERSTREAM_DIR_OPEN "\" call failed", us->wrapper->classname); } /* destroy everything else */ if (stream == NULL) { zval_ptr_dtor(&us->object); efree(us); } if (zretval) zval_ptr_dtor(&zretval); zval_ptr_dtor(&zfuncname); zval_ptr_dtor(&zoptions); zval_ptr_dtor(&zfilename); FG(user_stream_current_filename) = NULL; return stream; } /* {{{ proto bool stream_wrapper_register(string protocol, string classname[, integer flags]) Registers a custom URL protocol handler class */ PHP_FUNCTION(stream_wrapper_register) { char *protocol, *classname; int protocol_len, classname_len; struct php_user_stream_wrapper * uwrap; int rsrc_id; long flags = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|l", &protocol, &protocol_len, &classname, &classname_len, &flags) == FAILURE) { RETURN_FALSE; } uwrap = (struct php_user_stream_wrapper *)ecalloc(1, sizeof(*uwrap)); uwrap->protoname = estrndup(protocol, protocol_len); uwrap->classname = estrndup(classname, classname_len); uwrap->wrapper.wops = &user_stream_wops; uwrap->wrapper.abstract = uwrap; uwrap->wrapper.is_url = ((flags & PHP_STREAM_IS_URL) != 0); rsrc_id = ZEND_REGISTER_RESOURCE(NULL, uwrap, le_protocols); if (zend_lookup_class(uwrap->classname, classname_len, (zend_class_entry***)&uwrap->ce TSRMLS_CC) == SUCCESS) { uwrap->ce = *(zend_class_entry**)uwrap->ce; if (php_register_url_stream_wrapper_volatile(protocol, &uwrap->wrapper TSRMLS_CC) == SUCCESS) { RETURN_TRUE; } else { /* We failed. But why? */ if (zend_hash_exists(php_stream_get_url_stream_wrappers_hash(), protocol, protocol_len + 1)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Protocol %s:// is already defined.", protocol); } else { /* Hash doesn't exist so it must have been an invalid protocol scheme */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid protocol scheme specified. Unable to register wrapper class %s to %s://", classname, protocol); } } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "class '%s' is undefined", classname); } zend_list_delete(rsrc_id); RETURN_FALSE; } /* }}} */ /* {{{ proto bool stream_wrapper_unregister(string protocol) Unregister a wrapper for the life of the current request. */ PHP_FUNCTION(stream_wrapper_unregister) { char *protocol; int protocol_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &protocol, &protocol_len) == FAILURE) { RETURN_FALSE; } if (php_unregister_url_stream_wrapper_volatile(protocol TSRMLS_CC) == FAILURE) { /* We failed */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to unregister protocol %s://", protocol); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool stream_wrapper_restore(string protocol) Restore the original protocol handler, overriding if necessary */ PHP_FUNCTION(stream_wrapper_restore) { char *protocol; int protocol_len; php_stream_wrapper **wrapperpp = NULL, *wrapper; HashTable *global_wrapper_hash; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &protocol, &protocol_len) == FAILURE) { RETURN_FALSE; } global_wrapper_hash = php_stream_get_url_stream_wrappers_hash_global(); if (php_stream_get_url_stream_wrappers_hash() == global_wrapper_hash) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "%s:// was never changed, nothing to restore", protocol); RETURN_TRUE; } if ((zend_hash_find(global_wrapper_hash, protocol, protocol_len + 1, (void**)&wrapperpp) == FAILURE) || !wrapperpp) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s:// never existed, nothing to restore", protocol); RETURN_FALSE; } /* next line might delete the pointer that wrapperpp points at, so deref it now */ wrapper = *wrapperpp; /* A failure here could be okay given that the protocol might have been merely unregistered */ php_unregister_url_stream_wrapper_volatile(protocol TSRMLS_CC); if (php_register_url_stream_wrapper_volatile(protocol, wrapper TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to restore original %s:// wrapper", protocol); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ static size_t php_userstreamop_write(php_stream *stream, const char *buf, size_t count TSRMLS_DC) { zval func_name; zval *retval = NULL; int call_result; php_userstream_data_t *us = (php_userstream_data_t *)stream->abstract; zval **args[1]; zval *zbufptr; size_t didwrite = 0; assert(us != NULL); ZVAL_STRINGL(&func_name, USERSTREAM_WRITE, sizeof(USERSTREAM_WRITE)-1, 0); MAKE_STD_ZVAL(zbufptr); ZVAL_STRINGL(zbufptr, (char*)buf, count, 1);; args[0] = &zbufptr; call_result = call_user_function_ex(NULL, &us->object, &func_name, &retval, 1, args, 0, NULL TSRMLS_CC); zval_ptr_dtor(&zbufptr); didwrite = 0; if (call_result == SUCCESS && retval != NULL) { convert_to_long(retval); didwrite = Z_LVAL_P(retval); } else if (call_result == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_WRITE " is not implemented!", us->wrapper->classname); } /* don't allow strange buffer overruns due to bogus return */ if (didwrite > count) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_WRITE " wrote %ld bytes more data than requested (%ld written, %ld max)", us->wrapper->classname, (long)(didwrite - count), (long)didwrite, (long)count); didwrite = count; } if (retval) zval_ptr_dtor(&retval); return didwrite; } static size_t php_userstreamop_read(php_stream *stream, char *buf, size_t count TSRMLS_DC) { zval func_name; zval *retval = NULL; zval **args[1]; int call_result; size_t didread = 0; php_userstream_data_t *us = (php_userstream_data_t *)stream->abstract; zval *zcount; assert(us != NULL); ZVAL_STRINGL(&func_name, USERSTREAM_READ, sizeof(USERSTREAM_READ)-1, 0); MAKE_STD_ZVAL(zcount); ZVAL_LONG(zcount, count); args[0] = &zcount; call_result = call_user_function_ex(NULL, &us->object, &func_name, &retval, 1, args, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && retval != NULL) { convert_to_string(retval); didread = Z_STRLEN_P(retval); if (didread > count) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_READ " - read %ld bytes more data than requested (%ld read, %ld max) - excess data will be lost", us->wrapper->classname, (long)(didread - count), (long)didread, (long)count); didread = count; } if (didread > 0) memcpy(buf, Z_STRVAL_P(retval), didread); } else if (call_result == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_READ " is not implemented!", us->wrapper->classname); } zval_ptr_dtor(&zcount); if (retval) { zval_ptr_dtor(&retval); retval = NULL; } /* since the user stream has no way of setting the eof flag directly, we need to ask it if we hit eof */ ZVAL_STRINGL(&func_name, USERSTREAM_EOF, sizeof(USERSTREAM_EOF)-1, 0); call_result = call_user_function_ex(NULL, &us->object, &func_name, &retval, 0, NULL, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && retval != NULL && zval_is_true(retval)) { stream->eof = 1; } else if (call_result == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_EOF " is not implemented! Assuming EOF", us->wrapper->classname); stream->eof = 1; } if (retval) { zval_ptr_dtor(&retval); retval = NULL; } return didread; } static int php_userstreamop_close(php_stream *stream, int close_handle TSRMLS_DC) { zval func_name; zval *retval = NULL; php_userstream_data_t *us = (php_userstream_data_t *)stream->abstract; assert(us != NULL); ZVAL_STRINGL(&func_name, USERSTREAM_CLOSE, sizeof(USERSTREAM_CLOSE)-1, 0); call_user_function_ex(NULL, &us->object, &func_name, &retval, 0, NULL, 0, NULL TSRMLS_CC); if (retval) zval_ptr_dtor(&retval); zval_ptr_dtor(&us->object); efree(us); return 0; } static int php_userstreamop_flush(php_stream *stream TSRMLS_DC) { zval func_name; zval *retval = NULL; int call_result; php_userstream_data_t *us = (php_userstream_data_t *)stream->abstract; assert(us != NULL); ZVAL_STRINGL(&func_name, USERSTREAM_FLUSH, sizeof(USERSTREAM_FLUSH)-1, 0); call_result = call_user_function_ex(NULL, &us->object, &func_name, &retval, 0, NULL, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && retval != NULL && zval_is_true(retval)) call_result = 0; else call_result = -1; if (retval) zval_ptr_dtor(&retval); return call_result; } static int php_userstreamop_seek(php_stream *stream, off_t offset, int whence, off_t *newoffs TSRMLS_DC) { zval func_name; zval *retval = NULL; int call_result, ret; php_userstream_data_t *us = (php_userstream_data_t *)stream->abstract; zval **args[2]; zval *zoffs, *zwhence; assert(us != NULL); ZVAL_STRINGL(&func_name, USERSTREAM_SEEK, sizeof(USERSTREAM_SEEK)-1, 0); MAKE_STD_ZVAL(zoffs); ZVAL_LONG(zoffs, offset); args[0] = &zoffs; MAKE_STD_ZVAL(zwhence); ZVAL_LONG(zwhence, whence); args[1] = &zwhence; call_result = call_user_function_ex(NULL, &us->object, &func_name, &retval, 2, args, 0, NULL TSRMLS_CC); zval_ptr_dtor(&zoffs); zval_ptr_dtor(&zwhence); if (call_result == FAILURE) { /* stream_seek is not implemented, so disable seeks for this stream */ stream->flags |= PHP_STREAM_FLAG_NO_SEEK; /* there should be no retval to clean up */ if (retval) zval_ptr_dtor(&retval); return -1; } else if (call_result == SUCCESS && retval != NULL && zval_is_true(retval)) { ret = 0; } else { ret = -1; } if (retval) { zval_ptr_dtor(&retval); retval = NULL; } if (ret) { return ret; } /* now determine where we are */ ZVAL_STRINGL(&func_name, USERSTREAM_TELL, sizeof(USERSTREAM_TELL)-1, 0); call_result = call_user_function_ex(NULL, &us->object, &func_name, &retval, 0, NULL, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && retval != NULL && Z_TYPE_P(retval) == IS_LONG) { *newoffs = Z_LVAL_P(retval); ret = 0; } else if (call_result == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_TELL " is not implemented!", us->wrapper->classname); ret = -1; } else { ret = -1; } if (retval) { zval_ptr_dtor(&retval); } return ret; } /* parse the return value from one of the stat functions and store the * relevant fields into the statbuf provided */ static int statbuf_from_array(zval *array, php_stream_statbuf *ssb TSRMLS_DC) { zval **elem; #define STAT_PROP_ENTRY_EX(name, name2) \ if (SUCCESS == zend_hash_find(Z_ARRVAL_P(array), #name, sizeof(#name), (void**)&elem)) { \ convert_to_long(*elem); \ ssb->sb.st_##name2 = Z_LVAL_PP(elem); \ } #define STAT_PROP_ENTRY(name) STAT_PROP_ENTRY_EX(name,name) STAT_PROP_ENTRY(dev); STAT_PROP_ENTRY(ino); STAT_PROP_ENTRY(mode); STAT_PROP_ENTRY(nlink); STAT_PROP_ENTRY(uid); STAT_PROP_ENTRY(gid); #if HAVE_ST_RDEV STAT_PROP_ENTRY(rdev); #endif STAT_PROP_ENTRY(size); #ifdef NETWARE STAT_PROP_ENTRY_EX(atime, atime.tv_sec); STAT_PROP_ENTRY_EX(mtime, mtime.tv_sec); STAT_PROP_ENTRY_EX(ctime, ctime.tv_sec); #else STAT_PROP_ENTRY(atime); STAT_PROP_ENTRY(mtime); STAT_PROP_ENTRY(ctime); #endif #ifdef HAVE_ST_BLKSIZE STAT_PROP_ENTRY(blksize); #endif #ifdef HAVE_ST_BLOCKS STAT_PROP_ENTRY(blocks); #endif #undef STAT_PROP_ENTRY #undef STAT_PROP_ENTRY_EX return SUCCESS; } static int php_userstreamop_stat(php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC) { zval func_name; zval *retval = NULL; int call_result; php_userstream_data_t *us = (php_userstream_data_t *)stream->abstract; int ret = -1; ZVAL_STRINGL(&func_name, USERSTREAM_STAT, sizeof(USERSTREAM_STAT)-1, 0); call_result = call_user_function_ex(NULL, &us->object, &func_name, &retval, 0, NULL, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && retval != NULL && Z_TYPE_P(retval) == IS_ARRAY) { if (SUCCESS == statbuf_from_array(retval, ssb TSRMLS_CC)) ret = 0; } else { if (call_result == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_STAT " is not implemented!", us->wrapper->classname); } } if (retval) zval_ptr_dtor(&retval); return ret; } static int php_userstreamop_set_option(php_stream *stream, int option, int value, void *ptrparam TSRMLS_DC) { zval func_name; zval *retval = NULL; int call_result; php_userstream_data_t *us = (php_userstream_data_t *)stream->abstract; int ret = -1; zval *zvalue = NULL; zval **args[3]; switch (option) { case PHP_STREAM_OPTION_CHECK_LIVENESS: ZVAL_STRINGL(&func_name, USERSTREAM_EOF, sizeof(USERSTREAM_EOF)-1, 0); call_result = call_user_function_ex(NULL, &us->object, &func_name, &retval, 0, NULL, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && retval != NULL && Z_TYPE_P(retval) == IS_BOOL) { ret = zval_is_true(retval) ? PHP_STREAM_OPTION_RETURN_ERR : PHP_STREAM_OPTION_RETURN_OK; } else { ret = PHP_STREAM_OPTION_RETURN_ERR; php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_EOF " is not implemented! Assuming EOF", us->wrapper->classname); } break; case PHP_STREAM_OPTION_LOCKING: MAKE_STD_ZVAL(zvalue); ZVAL_LONG(zvalue, 0); if (value & LOCK_NB) { Z_LVAL_P(zvalue) |= PHP_LOCK_NB; } switch(value & ~LOCK_NB) { case LOCK_SH: Z_LVAL_P(zvalue) |= PHP_LOCK_SH; break; case LOCK_EX: Z_LVAL_P(zvalue) |= PHP_LOCK_EX; break; case LOCK_UN: Z_LVAL_P(zvalue) |= PHP_LOCK_UN; break; } args[0] = &zvalue; /* TODO wouldblock */ ZVAL_STRINGL(&func_name, USERSTREAM_LOCK, sizeof(USERSTREAM_LOCK)-1, 0); call_result = call_user_function_ex(NULL, &us->object, &func_name, &retval, 1, args, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && retval != NULL && Z_TYPE_P(retval) == IS_BOOL) { ret = !Z_LVAL_P(retval); } else if (call_result == FAILURE) { if (value == 0) { /* lock support test (TODO: more check) */ ret = 0; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_LOCK " is not implemented!", us->wrapper->classname); } } break; case PHP_STREAM_OPTION_READ_BUFFER: case PHP_STREAM_OPTION_WRITE_BUFFER: case PHP_STREAM_OPTION_READ_TIMEOUT: case PHP_STREAM_OPTION_BLOCKING: { zval *zoption = NULL; zval *zptrparam = NULL; ZVAL_STRINGL(&func_name, USERSTREAM_SET_OPTION, sizeof(USERSTREAM_SET_OPTION)-1, 0); ALLOC_INIT_ZVAL(zoption); ZVAL_LONG(zoption, option); ALLOC_INIT_ZVAL(zvalue); ALLOC_INIT_ZVAL(zptrparam); args[0] = &zoption; args[1] = &zvalue; args[2] = &zptrparam; switch(option) { case PHP_STREAM_OPTION_READ_BUFFER: case PHP_STREAM_OPTION_WRITE_BUFFER: ZVAL_LONG(zvalue, value); if (ptrparam) { ZVAL_LONG(zptrparam, *(long *)ptrparam); } else { ZVAL_LONG(zptrparam, BUFSIZ); } break; case PHP_STREAM_OPTION_READ_TIMEOUT: { struct timeval tv = *(struct timeval*)ptrparam; ZVAL_LONG(zvalue, tv.tv_sec); ZVAL_LONG(zptrparam, tv.tv_usec); break; } case PHP_STREAM_OPTION_BLOCKING: ZVAL_LONG(zvalue, value); break; default: break; } call_result = call_user_function_ex(NULL, &us->object, &func_name, &retval, 3, args, 0, NULL TSRMLS_CC); do { if (call_result == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_SET_OPTION " is not implemented!", us->wrapper->classname); break; } if (retval && zend_is_true(retval)) { ret = PHP_STREAM_OPTION_RETURN_OK; } } while (0); if (zoption) { zval_ptr_dtor(&zoption); } if (zptrparam) { zval_ptr_dtor(&zptrparam); } break; } } /* clean up */ if (retval) { zval_ptr_dtor(&retval); } if (zvalue) { zval_ptr_dtor(&zvalue); } return ret; } static int user_wrapper_unlink(php_stream_wrapper *wrapper, char *url, int options, php_stream_context *context TSRMLS_DC) { struct php_user_stream_wrapper *uwrap = (struct php_user_stream_wrapper*)wrapper->abstract; zval *zfilename, *zfuncname, *zretval; zval **args[1]; int call_result; zval *object; int ret = 0; /* create an instance of our class */ ALLOC_ZVAL(object); object_init_ex(object, uwrap->ce); Z_SET_REFCOUNT_P(object, 1); Z_SET_ISREF_P(object); if (context) { add_property_resource(object, "context", context->rsrc_id); zend_list_addref(context->rsrc_id); } else { add_property_null(object, "context"); } /* call the unlink method */ MAKE_STD_ZVAL(zfilename); ZVAL_STRING(zfilename, url, 1); args[0] = &zfilename; MAKE_STD_ZVAL(zfuncname); ZVAL_STRING(zfuncname, USERSTREAM_UNLINK, 1); call_result = call_user_function_ex(NULL, &object, zfuncname, &zretval, 1, args, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && zretval && Z_TYPE_P(zretval) == IS_BOOL) { ret = Z_LVAL_P(zretval); } else if (call_result == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_UNLINK " is not implemented!", uwrap->classname); } /* clean up */ zval_ptr_dtor(&object); if (zretval) zval_ptr_dtor(&zretval); zval_ptr_dtor(&zfuncname); zval_ptr_dtor(&zfilename); return ret; } static int user_wrapper_rename(php_stream_wrapper *wrapper, char *url_from, char *url_to, int options, php_stream_context *context TSRMLS_DC) { struct php_user_stream_wrapper *uwrap = (struct php_user_stream_wrapper*)wrapper->abstract; zval *zold_name, *znew_name, *zfuncname, *zretval; zval **args[2]; int call_result; zval *object; int ret = 0; /* create an instance of our class */ ALLOC_ZVAL(object); object_init_ex(object, uwrap->ce); Z_SET_REFCOUNT_P(object, 1); Z_SET_ISREF_P(object); if (context) { add_property_resource(object, "context", context->rsrc_id); zend_list_addref(context->rsrc_id); } else { add_property_null(object, "context"); } /* call the rename method */ MAKE_STD_ZVAL(zold_name); ZVAL_STRING(zold_name, url_from, 1); args[0] = &zold_name; MAKE_STD_ZVAL(znew_name); ZVAL_STRING(znew_name, url_to, 1); args[1] = &znew_name; MAKE_STD_ZVAL(zfuncname); ZVAL_STRING(zfuncname, USERSTREAM_RENAME, 1); call_result = call_user_function_ex(NULL, &object, zfuncname, &zretval, 2, args, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && zretval && Z_TYPE_P(zretval) == IS_BOOL) { ret = Z_LVAL_P(zretval); } else if (call_result == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_RENAME " is not implemented!", uwrap->classname); } /* clean up */ zval_ptr_dtor(&object); if (zretval) zval_ptr_dtor(&zretval); zval_ptr_dtor(&zfuncname); zval_ptr_dtor(&zold_name); zval_ptr_dtor(&znew_name); return ret; } static int user_wrapper_mkdir(php_stream_wrapper *wrapper, char *url, int mode, int options, php_stream_context *context TSRMLS_DC) { struct php_user_stream_wrapper *uwrap = (struct php_user_stream_wrapper*)wrapper->abstract; zval *zfilename, *zmode, *zoptions, *zfuncname, *zretval; zval **args[3]; int call_result; zval *object; int ret = 0; /* create an instance of our class */ ALLOC_ZVAL(object); object_init_ex(object, uwrap->ce); Z_SET_REFCOUNT_P(object, 1); Z_SET_ISREF_P(object); if (context) { add_property_resource(object, "context", context->rsrc_id); zend_list_addref(context->rsrc_id); } else { add_property_null(object, "context"); } /* call the mkdir method */ MAKE_STD_ZVAL(zfilename); ZVAL_STRING(zfilename, url, 1); args[0] = &zfilename; MAKE_STD_ZVAL(zmode); ZVAL_LONG(zmode, mode); args[1] = &zmode; MAKE_STD_ZVAL(zoptions); ZVAL_LONG(zoptions, options); args[2] = &zoptions; MAKE_STD_ZVAL(zfuncname); ZVAL_STRING(zfuncname, USERSTREAM_MKDIR, 1); call_result = call_user_function_ex(NULL, &object, zfuncname, &zretval, 3, args, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && zretval && Z_TYPE_P(zretval) == IS_BOOL) { ret = Z_LVAL_P(zretval); } else if (call_result == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_MKDIR " is not implemented!", uwrap->classname); } /* clean up */ zval_ptr_dtor(&object); if (zretval) { zval_ptr_dtor(&zretval); } zval_ptr_dtor(&zfuncname); zval_ptr_dtor(&zfilename); zval_ptr_dtor(&zmode); zval_ptr_dtor(&zoptions); return ret; } static int user_wrapper_rmdir(php_stream_wrapper *wrapper, char *url, int options, php_stream_context *context TSRMLS_DC) { struct php_user_stream_wrapper *uwrap = (struct php_user_stream_wrapper*)wrapper->abstract; zval *zfilename, *zoptions, *zfuncname, *zretval; zval **args[3]; int call_result; zval *object; int ret = 0; /* create an instance of our class */ ALLOC_ZVAL(object); object_init_ex(object, uwrap->ce); Z_SET_REFCOUNT_P(object, 1); Z_SET_ISREF_P(object); if (context) { add_property_resource(object, "context", context->rsrc_id); zend_list_addref(context->rsrc_id); } else { add_property_null(object, "context"); } /* call the rmdir method */ MAKE_STD_ZVAL(zfilename); ZVAL_STRING(zfilename, url, 1); args[0] = &zfilename; MAKE_STD_ZVAL(zoptions); ZVAL_LONG(zoptions, options); args[1] = &zoptions; MAKE_STD_ZVAL(zfuncname); ZVAL_STRING(zfuncname, USERSTREAM_RMDIR, 1); call_result = call_user_function_ex(NULL, &object, zfuncname, &zretval, 2, args, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && zretval && Z_TYPE_P(zretval) == IS_BOOL) { ret = Z_LVAL_P(zretval); } else if (call_result == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_RMDIR " is not implemented!", uwrap->classname); } /* clean up */ zval_ptr_dtor(&object); if (zretval) { zval_ptr_dtor(&zretval); } zval_ptr_dtor(&zfuncname); zval_ptr_dtor(&zfilename); zval_ptr_dtor(&zoptions); return ret; } static int user_wrapper_stat_url(php_stream_wrapper *wrapper, char *url, int flags, php_stream_statbuf *ssb, php_stream_context *context TSRMLS_DC) { struct php_user_stream_wrapper *uwrap = (struct php_user_stream_wrapper*)wrapper->abstract; zval *zfilename, *zfuncname, *zretval, *zflags; zval **args[2]; int call_result; zval *object; int ret = -1; /* create an instance of our class */ ALLOC_ZVAL(object); object_init_ex(object, uwrap->ce); Z_SET_REFCOUNT_P(object, 1); Z_SET_ISREF_P(object); if (context) { add_property_resource(object, "context", context->rsrc_id); zend_list_addref(context->rsrc_id); } else { add_property_null(object, "context"); } /* call it's stat_url method - set up params first */ MAKE_STD_ZVAL(zfilename); ZVAL_STRING(zfilename, url, 1); args[0] = &zfilename; MAKE_STD_ZVAL(zflags); ZVAL_LONG(zflags, flags); args[1] = &zflags; MAKE_STD_ZVAL(zfuncname); ZVAL_STRING(zfuncname, USERSTREAM_STATURL, 1); call_result = call_user_function_ex(NULL, &object, zfuncname, &zretval, 2, args, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && zretval != NULL && Z_TYPE_P(zretval) == IS_ARRAY) { /* We got the info we needed */ if (SUCCESS == statbuf_from_array(zretval, ssb TSRMLS_CC)) ret = 0; } else { if (call_result == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_STATURL " is not implemented!", uwrap->classname); } } /* clean up */ zval_ptr_dtor(&object); if (zretval) zval_ptr_dtor(&zretval); zval_ptr_dtor(&zfuncname); zval_ptr_dtor(&zfilename); zval_ptr_dtor(&zflags); return ret; } static size_t php_userstreamop_readdir(php_stream *stream, char *buf, size_t count TSRMLS_DC) { zval func_name; zval *retval = NULL; int call_result; size_t didread = 0; php_userstream_data_t *us = (php_userstream_data_t *)stream->abstract; php_stream_dirent *ent = (php_stream_dirent*)buf; /* avoid problems if someone mis-uses the stream */ if (count != sizeof(php_stream_dirent)) return 0; ZVAL_STRINGL(&func_name, USERSTREAM_DIR_READ, sizeof(USERSTREAM_DIR_READ)-1, 0); call_result = call_user_function_ex(NULL, &us->object, &func_name, &retval, 0, NULL, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && retval != NULL && Z_TYPE_P(retval) != IS_BOOL) { convert_to_string(retval); PHP_STRLCPY(ent->d_name, Z_STRVAL_P(retval), sizeof(ent->d_name), Z_STRLEN_P(retval)); didread = sizeof(php_stream_dirent); } else if (call_result == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_DIR_READ " is not implemented!", us->wrapper->classname); } if (retval) zval_ptr_dtor(&retval); return didread; } static int php_userstreamop_closedir(php_stream *stream, int close_handle TSRMLS_DC) { zval func_name; zval *retval = NULL; php_userstream_data_t *us = (php_userstream_data_t *)stream->abstract; assert(us != NULL); ZVAL_STRINGL(&func_name, USERSTREAM_DIR_CLOSE, sizeof(USERSTREAM_DIR_CLOSE)-1, 0); call_user_function_ex(NULL, &us->object, &func_name, &retval, 0, NULL, 0, NULL TSRMLS_CC); if (retval) zval_ptr_dtor(&retval); zval_ptr_dtor(&us->object); efree(us); return 0; } static int php_userstreamop_rewinddir(php_stream *stream, off_t offset, int whence, off_t *newoffs TSRMLS_DC) { zval func_name; zval *retval = NULL; php_userstream_data_t *us = (php_userstream_data_t *)stream->abstract; ZVAL_STRINGL(&func_name, USERSTREAM_DIR_REWIND, sizeof(USERSTREAM_DIR_REWIND)-1, 0); call_user_function_ex(NULL, &us->object, &func_name, &retval, 0, NULL, 0, NULL TSRMLS_CC); if (retval) zval_ptr_dtor(&retval); return 0; } static int php_userstreamop_cast(php_stream *stream, int castas, void **retptr TSRMLS_DC) { php_userstream_data_t *us = (php_userstream_data_t *)stream->abstract; zval func_name; zval *retval = NULL; zval *zcastas = NULL; zval **args[1]; php_stream * intstream = NULL; int call_result; int ret = FAILURE; ZVAL_STRINGL(&func_name, USERSTREAM_CAST, sizeof(USERSTREAM_CAST)-1, 0); ALLOC_INIT_ZVAL(zcastas); switch(castas) { case PHP_STREAM_AS_FD_FOR_SELECT: ZVAL_LONG(zcastas, PHP_STREAM_AS_FD_FOR_SELECT); break; default: ZVAL_LONG(zcastas, PHP_STREAM_AS_STDIO); break; } args[0] = &zcastas; call_result = call_user_function_ex(NULL, &us->object, &func_name, &retval, 1, args, 0, NULL TSRMLS_CC); do { if (call_result == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_CAST " is not implemented!", us->wrapper->classname); break; } if (retval == NULL || !zend_is_true(retval)) { break; } php_stream_from_zval_no_verify(intstream, &retval); if (!intstream) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_CAST " must return a stream resource", us->wrapper->classname); break; } if (intstream == stream) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_CAST " must not return itself", us->wrapper->classname); intstream = NULL; break; } ret = php_stream_cast(intstream, castas, retptr, 1); } while (0); if (retval) { zval_ptr_dtor(&retval); } if (zcastas) { zval_ptr_dtor(&zcastas); } return ret; } php_stream_ops php_stream_userspace_ops = { php_userstreamop_write, php_userstreamop_read, php_userstreamop_close, php_userstreamop_flush, "user-space", php_userstreamop_seek, php_userstreamop_cast, php_userstreamop_stat, php_userstreamop_set_option, }; php_stream_ops php_stream_userspace_dir_ops = { NULL, /* write */ php_userstreamop_readdir, php_userstreamop_closedir, NULL, /* flush */ "user-space-dir", php_userstreamop_rewinddir, NULL, /* cast */ NULL, /* stat */ NULL /* set_option */ }; /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2011 The PHP Group | +----------------------------------------------------------------------+ | 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 | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Wez Furlong <[email protected]> | | Sara Golemon <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "php.h" #include "php_globals.h" #include "ext/standard/file.h" #include "ext/standard/flock_compat.h" #ifdef HAVE_SYS_FILE_H #include <sys/file.h> #endif static int le_protocols; struct php_user_stream_wrapper { char * protoname; char * classname; zend_class_entry *ce; php_stream_wrapper wrapper; }; static php_stream *user_wrapper_opener(php_stream_wrapper *wrapper, char *filename, char *mode, int options, char **opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC); static int user_wrapper_stat_url(php_stream_wrapper *wrapper, char *url, int flags, php_stream_statbuf *ssb, php_stream_context *context TSRMLS_DC); static int user_wrapper_unlink(php_stream_wrapper *wrapper, char *url, int options, php_stream_context *context TSRMLS_DC); static int user_wrapper_rename(php_stream_wrapper *wrapper, char *url_from, char *url_to, int options, php_stream_context *context TSRMLS_DC); static int user_wrapper_mkdir(php_stream_wrapper *wrapper, char *url, int mode, int options, php_stream_context *context TSRMLS_DC); static int user_wrapper_rmdir(php_stream_wrapper *wrapper, char *url, int options, php_stream_context *context TSRMLS_DC); static php_stream *user_wrapper_opendir(php_stream_wrapper *wrapper, char *filename, char *mode, int options, char **opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC); static php_stream_wrapper_ops user_stream_wops = { user_wrapper_opener, NULL, /* close - the streams themselves know how */ NULL, /* stat - the streams themselves know how */ user_wrapper_stat_url, user_wrapper_opendir, "user-space", user_wrapper_unlink, user_wrapper_rename, user_wrapper_mkdir, user_wrapper_rmdir }; static void stream_wrapper_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC) { struct php_user_stream_wrapper * uwrap = (struct php_user_stream_wrapper*)rsrc->ptr; efree(uwrap->protoname); efree(uwrap->classname); efree(uwrap); } PHP_MINIT_FUNCTION(user_streams) { le_protocols = zend_register_list_destructors_ex(stream_wrapper_dtor, NULL, "stream factory", 0); if (le_protocols == FAILURE) return FAILURE; REGISTER_LONG_CONSTANT("STREAM_USE_PATH", USE_PATH, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_IGNORE_URL", IGNORE_URL, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_REPORT_ERRORS", REPORT_ERRORS, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_MUST_SEEK", STREAM_MUST_SEEK, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_URL_STAT_LINK", PHP_STREAM_URL_STAT_LINK, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_URL_STAT_QUIET", PHP_STREAM_URL_STAT_QUIET, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_MKDIR_RECURSIVE", PHP_STREAM_MKDIR_RECURSIVE, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_IS_URL", PHP_STREAM_IS_URL, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_OPTION_BLOCKING", PHP_STREAM_OPTION_BLOCKING, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_OPTION_READ_TIMEOUT", PHP_STREAM_OPTION_READ_TIMEOUT, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_OPTION_READ_BUFFER", PHP_STREAM_OPTION_READ_BUFFER, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_OPTION_WRITE_BUFFER", PHP_STREAM_OPTION_WRITE_BUFFER, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_BUFFER_NONE", PHP_STREAM_BUFFER_NONE, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_BUFFER_LINE", PHP_STREAM_BUFFER_LINE, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_BUFFER_FULL", PHP_STREAM_BUFFER_FULL, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_CAST_AS_STREAM", PHP_STREAM_AS_STDIO, CONST_CS|CONST_PERSISTENT); REGISTER_LONG_CONSTANT("STREAM_CAST_FOR_SELECT", PHP_STREAM_AS_FD_FOR_SELECT, CONST_CS|CONST_PERSISTENT); return SUCCESS; } struct _php_userstream_data { struct php_user_stream_wrapper * wrapper; zval * object; }; typedef struct _php_userstream_data php_userstream_data_t; /* names of methods */ #define USERSTREAM_OPEN "stream_open" #define USERSTREAM_CLOSE "stream_close" #define USERSTREAM_READ "stream_read" #define USERSTREAM_WRITE "stream_write" #define USERSTREAM_FLUSH "stream_flush" #define USERSTREAM_SEEK "stream_seek" #define USERSTREAM_TELL "stream_tell" #define USERSTREAM_EOF "stream_eof" #define USERSTREAM_STAT "stream_stat" #define USERSTREAM_STATURL "url_stat" #define USERSTREAM_UNLINK "unlink" #define USERSTREAM_RENAME "rename" #define USERSTREAM_MKDIR "mkdir" #define USERSTREAM_RMDIR "rmdir" #define USERSTREAM_DIR_OPEN "dir_opendir" #define USERSTREAM_DIR_READ "dir_readdir" #define USERSTREAM_DIR_REWIND "dir_rewinddir" #define USERSTREAM_DIR_CLOSE "dir_closedir" #define USERSTREAM_LOCK "stream_lock" #define USERSTREAM_CAST "stream_cast" #define USERSTREAM_SET_OPTION "stream_set_option" /* {{{ class should have methods like these: function stream_open($path, $mode, $options, &$opened_path) { return true/false; } function stream_read($count) { return false on error; else return string; } function stream_write($data) { return false on error; else return count written; } function stream_close() { } function stream_flush() { return true/false; } function stream_seek($offset, $whence) { return true/false; } function stream_tell() { return (int)$position; } function stream_eof() { return true/false; } function stream_stat() { return array( just like that returned by fstat() ); } function stream_cast($castas) { if ($castas == STREAM_CAST_FOR_SELECT) { return $this->underlying_stream; } return false; } function stream_set_option($option, $arg1, $arg2) { switch($option) { case STREAM_OPTION_BLOCKING: $blocking = $arg1; ... case STREAM_OPTION_READ_TIMEOUT: $sec = $arg1; $usec = $arg2; ... case STREAM_OPTION_WRITE_BUFFER: $mode = $arg1; $size = $arg2; ... default: return false; } } function url_stat(string $url, int $flags) { return array( just like that returned by stat() ); } function unlink(string $url) { return true / false; } function rename(string $from, string $to) { return true / false; } function mkdir($dir, $mode, $options) { return true / false; } function rmdir($dir, $options) { return true / false; } function dir_opendir(string $url, int $options) { return true / false; } function dir_readdir() { return string next filename in dir ; } function dir_closedir() { release dir related resources; } function dir_rewinddir() { reset to start of dir list; } function stream_lock($operation) { return true / false; } }}} **/ static php_stream *user_wrapper_opener(php_stream_wrapper *wrapper, char *filename, char *mode, int options, char **opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC) { struct php_user_stream_wrapper *uwrap = (struct php_user_stream_wrapper*)wrapper->abstract; php_userstream_data_t *us; zval *zfilename, *zmode, *zopened, *zoptions, *zretval = NULL, *zfuncname; zval **args[4]; int call_result; php_stream *stream = NULL; zend_bool old_in_user_include; /* Try to catch bad usage without preventing flexibility */ if (FG(user_stream_current_filename) != NULL && strcmp(filename, FG(user_stream_current_filename)) == 0) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "infinite recursion prevented"); return NULL; } FG(user_stream_current_filename) = filename; /* if the user stream was registered as local and we are in include context, we add allow_url_include restrictions to allow_url_fopen ones */ /* we need only is_url == 0 here since if is_url == 1 and remote wrappers were restricted we wouldn't get here */ old_in_user_include = PG(in_user_include); if(uwrap->wrapper.is_url == 0 && (options & STREAM_OPEN_FOR_INCLUDE) && !PG(allow_url_include)) { PG(in_user_include) = 1; } us = emalloc(sizeof(*us)); us->wrapper = uwrap; /* create an instance of our class */ ALLOC_ZVAL(us->object); object_init_ex(us->object, uwrap->ce); Z_SET_REFCOUNT_P(us->object, 1); Z_SET_ISREF_P(us->object); if (uwrap->ce->constructor) { zend_fcall_info fci; zend_fcall_info_cache fcc; zval *retval_ptr; fci.size = sizeof(fci); fci.function_table = &uwrap->ce->function_table; fci.function_name = NULL; fci.symbol_table = NULL; fci.object_ptr = us->object; fci.retval_ptr_ptr = &retval_ptr; fci.param_count = 0; fci.params = NULL; fci.no_separation = 1; fcc.initialized = 1; fcc.function_handler = uwrap->ce->constructor; fcc.calling_scope = EG(scope); fcc.called_scope = Z_OBJCE_P(us->object); fcc.object_ptr = us->object; if (zend_call_function(&fci, &fcc TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not execute %s::%s()", uwrap->ce->name, uwrap->ce->constructor->common.function_name); zval_dtor(us->object); FREE_ZVAL(us->object); efree(us); FG(user_stream_current_filename) = NULL; PG(in_user_include) = old_in_user_include; return NULL; } else { if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } } } if (context) { add_property_resource(us->object, "context", context->rsrc_id); zend_list_addref(context->rsrc_id); } else { add_property_null(us->object, "context"); } /* call it's stream_open method - set up params first */ MAKE_STD_ZVAL(zfilename); ZVAL_STRING(zfilename, filename, 1); args[0] = &zfilename; MAKE_STD_ZVAL(zmode); ZVAL_STRING(zmode, mode, 1); args[1] = &zmode; MAKE_STD_ZVAL(zoptions); ZVAL_LONG(zoptions, options); args[2] = &zoptions; MAKE_STD_ZVAL(zopened); Z_SET_REFCOUNT_P(zopened, 1); Z_SET_ISREF_P(zopened); ZVAL_NULL(zopened); args[3] = &zopened; MAKE_STD_ZVAL(zfuncname); ZVAL_STRING(zfuncname, USERSTREAM_OPEN, 1); call_result = call_user_function_ex(NULL, &us->object, zfuncname, &zretval, 4, args, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && zretval != NULL && zval_is_true(zretval)) { /* the stream is now open! */ stream = php_stream_alloc_rel(&php_stream_userspace_ops, us, 0, mode); /* if the opened path is set, copy it out */ if (Z_TYPE_P(zopened) == IS_STRING && opened_path) { *opened_path = estrndup(Z_STRVAL_P(zopened), Z_STRLEN_P(zopened)); } /* set wrapper data to be a reference to our object */ stream->wrapperdata = us->object; zval_add_ref(&stream->wrapperdata); } else { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "\"%s::" USERSTREAM_OPEN "\" call failed", us->wrapper->classname); } /* destroy everything else */ if (stream == NULL) { zval_ptr_dtor(&us->object); efree(us); } if (zretval) zval_ptr_dtor(&zretval); zval_ptr_dtor(&zfuncname); zval_ptr_dtor(&zopened); zval_ptr_dtor(&zoptions); zval_ptr_dtor(&zmode); zval_ptr_dtor(&zfilename); FG(user_stream_current_filename) = NULL; PG(in_user_include) = old_in_user_include; return stream; } static php_stream *user_wrapper_opendir(php_stream_wrapper *wrapper, char *filename, char *mode, int options, char **opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC) { struct php_user_stream_wrapper *uwrap = (struct php_user_stream_wrapper*)wrapper->abstract; php_userstream_data_t *us; zval *zfilename, *zoptions, *zretval = NULL, *zfuncname; zval **args[2]; int call_result; php_stream *stream = NULL; /* Try to catch bad usage without preventing flexibility */ if (FG(user_stream_current_filename) != NULL && strcmp(filename, FG(user_stream_current_filename)) == 0) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "infinite recursion prevented"); return NULL; } FG(user_stream_current_filename) = filename; us = emalloc(sizeof(*us)); us->wrapper = uwrap; /* create an instance of our class */ ALLOC_ZVAL(us->object); object_init_ex(us->object, uwrap->ce); Z_SET_REFCOUNT_P(us->object, 1); Z_SET_ISREF_P(us->object); if (context) { add_property_resource(us->object, "context", context->rsrc_id); zend_list_addref(context->rsrc_id); } else { add_property_null(us->object, "context"); } /* call it's dir_open method - set up params first */ MAKE_STD_ZVAL(zfilename); ZVAL_STRING(zfilename, filename, 1); args[0] = &zfilename; MAKE_STD_ZVAL(zoptions); ZVAL_LONG(zoptions, options); args[1] = &zoptions; MAKE_STD_ZVAL(zfuncname); ZVAL_STRING(zfuncname, USERSTREAM_DIR_OPEN, 1); call_result = call_user_function_ex(NULL, &us->object, zfuncname, &zretval, 2, args, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && zretval != NULL && zval_is_true(zretval)) { /* the stream is now open! */ stream = php_stream_alloc_rel(&php_stream_userspace_dir_ops, us, 0, mode); /* set wrapper data to be a reference to our object */ stream->wrapperdata = us->object; zval_add_ref(&stream->wrapperdata); } else { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "\"%s::" USERSTREAM_DIR_OPEN "\" call failed", us->wrapper->classname); } /* destroy everything else */ if (stream == NULL) { zval_ptr_dtor(&us->object); efree(us); } if (zretval) zval_ptr_dtor(&zretval); zval_ptr_dtor(&zfuncname); zval_ptr_dtor(&zoptions); zval_ptr_dtor(&zfilename); FG(user_stream_current_filename) = NULL; return stream; } /* {{{ proto bool stream_wrapper_register(string protocol, string classname[, integer flags]) Registers a custom URL protocol handler class */ PHP_FUNCTION(stream_wrapper_register) { char *protocol, *classname; int protocol_len, classname_len; struct php_user_stream_wrapper * uwrap; int rsrc_id; long flags = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|l", &protocol, &protocol_len, &classname, &classname_len, &flags) == FAILURE) { RETURN_FALSE; } uwrap = (struct php_user_stream_wrapper *)ecalloc(1, sizeof(*uwrap)); uwrap->protoname = estrndup(protocol, protocol_len); uwrap->classname = estrndup(classname, classname_len); uwrap->wrapper.wops = &user_stream_wops; uwrap->wrapper.abstract = uwrap; uwrap->wrapper.is_url = ((flags & PHP_STREAM_IS_URL) != 0); rsrc_id = ZEND_REGISTER_RESOURCE(NULL, uwrap, le_protocols); if (zend_lookup_class(uwrap->classname, classname_len, (zend_class_entry***)&uwrap->ce TSRMLS_CC) == SUCCESS) { uwrap->ce = *(zend_class_entry**)uwrap->ce; if (php_register_url_stream_wrapper_volatile(protocol, &uwrap->wrapper TSRMLS_CC) == SUCCESS) { RETURN_TRUE; } else { /* We failed. But why? */ if (zend_hash_exists(php_stream_get_url_stream_wrappers_hash(), protocol, protocol_len + 1)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Protocol %s:// is already defined.", protocol); } else { /* Hash doesn't exist so it must have been an invalid protocol scheme */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid protocol scheme specified. Unable to register wrapper class %s to %s://", classname, protocol); } } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "class '%s' is undefined", classname); } zend_list_delete(rsrc_id); RETURN_FALSE; } /* }}} */ /* {{{ proto bool stream_wrapper_unregister(string protocol) Unregister a wrapper for the life of the current request. */ PHP_FUNCTION(stream_wrapper_unregister) { char *protocol; int protocol_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &protocol, &protocol_len) == FAILURE) { RETURN_FALSE; } if (php_unregister_url_stream_wrapper_volatile(protocol TSRMLS_CC) == FAILURE) { /* We failed */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to unregister protocol %s://", protocol); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool stream_wrapper_restore(string protocol) Restore the original protocol handler, overriding if necessary */ PHP_FUNCTION(stream_wrapper_restore) { char *protocol; int protocol_len; php_stream_wrapper **wrapperpp = NULL, *wrapper; HashTable *global_wrapper_hash; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &protocol, &protocol_len) == FAILURE) { RETURN_FALSE; } global_wrapper_hash = php_stream_get_url_stream_wrappers_hash_global(); if (php_stream_get_url_stream_wrappers_hash() == global_wrapper_hash) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "%s:// was never changed, nothing to restore", protocol); RETURN_TRUE; } if ((zend_hash_find(global_wrapper_hash, protocol, protocol_len + 1, (void**)&wrapperpp) == FAILURE) || !wrapperpp) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s:// never existed, nothing to restore", protocol); RETURN_FALSE; } /* next line might delete the pointer that wrapperpp points at, so deref it now */ wrapper = *wrapperpp; /* A failure here could be okay given that the protocol might have been merely unregistered */ php_unregister_url_stream_wrapper_volatile(protocol TSRMLS_CC); if (php_register_url_stream_wrapper_volatile(protocol, wrapper TSRMLS_CC) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to restore original %s:// wrapper", protocol); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ static size_t php_userstreamop_write(php_stream *stream, const char *buf, size_t count TSRMLS_DC) { zval func_name; zval *retval = NULL; int call_result; php_userstream_data_t *us = (php_userstream_data_t *)stream->abstract; zval **args[1]; zval *zbufptr; size_t didwrite = 0; assert(us != NULL); ZVAL_STRINGL(&func_name, USERSTREAM_WRITE, sizeof(USERSTREAM_WRITE)-1, 0); MAKE_STD_ZVAL(zbufptr); ZVAL_STRINGL(zbufptr, (char*)buf, count, 1);; args[0] = &zbufptr; call_result = call_user_function_ex(NULL, &us->object, &func_name, &retval, 1, args, 0, NULL TSRMLS_CC); zval_ptr_dtor(&zbufptr); didwrite = 0; if (call_result == SUCCESS && retval != NULL) { convert_to_long(retval); didwrite = Z_LVAL_P(retval); } else if (call_result == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_WRITE " is not implemented!", us->wrapper->classname); } /* don't allow strange buffer overruns due to bogus return */ if (didwrite > count) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_WRITE " wrote %ld bytes more data than requested (%ld written, %ld max)", us->wrapper->classname, (long)(didwrite - count), (long)didwrite, (long)count); didwrite = count; } if (retval) zval_ptr_dtor(&retval); return didwrite; } static size_t php_userstreamop_read(php_stream *stream, char *buf, size_t count TSRMLS_DC) { zval func_name; zval *retval = NULL; zval **args[1]; int call_result; size_t didread = 0; php_userstream_data_t *us = (php_userstream_data_t *)stream->abstract; zval *zcount; assert(us != NULL); ZVAL_STRINGL(&func_name, USERSTREAM_READ, sizeof(USERSTREAM_READ)-1, 0); MAKE_STD_ZVAL(zcount); ZVAL_LONG(zcount, count); args[0] = &zcount; call_result = call_user_function_ex(NULL, &us->object, &func_name, &retval, 1, args, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && retval != NULL) { convert_to_string(retval); didread = Z_STRLEN_P(retval); if (didread > count) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_READ " - read %ld bytes more data than requested (%ld read, %ld max) - excess data will be lost", us->wrapper->classname, (long)(didread - count), (long)didread, (long)count); didread = count; } if (didread > 0) memcpy(buf, Z_STRVAL_P(retval), didread); } else if (call_result == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_READ " is not implemented!", us->wrapper->classname); } zval_ptr_dtor(&zcount); if (retval) { zval_ptr_dtor(&retval); retval = NULL; } /* since the user stream has no way of setting the eof flag directly, we need to ask it if we hit eof */ ZVAL_STRINGL(&func_name, USERSTREAM_EOF, sizeof(USERSTREAM_EOF)-1, 0); call_result = call_user_function_ex(NULL, &us->object, &func_name, &retval, 0, NULL, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && retval != NULL && zval_is_true(retval)) { stream->eof = 1; } else if (call_result == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_EOF " is not implemented! Assuming EOF", us->wrapper->classname); stream->eof = 1; } if (retval) { zval_ptr_dtor(&retval); retval = NULL; } return didread; } static int php_userstreamop_close(php_stream *stream, int close_handle TSRMLS_DC) { zval func_name; zval *retval = NULL; php_userstream_data_t *us = (php_userstream_data_t *)stream->abstract; assert(us != NULL); ZVAL_STRINGL(&func_name, USERSTREAM_CLOSE, sizeof(USERSTREAM_CLOSE)-1, 0); call_user_function_ex(NULL, &us->object, &func_name, &retval, 0, NULL, 0, NULL TSRMLS_CC); if (retval) zval_ptr_dtor(&retval); zval_ptr_dtor(&us->object); efree(us); return 0; } static int php_userstreamop_flush(php_stream *stream TSRMLS_DC) { zval func_name; zval *retval = NULL; int call_result; php_userstream_data_t *us = (php_userstream_data_t *)stream->abstract; assert(us != NULL); ZVAL_STRINGL(&func_name, USERSTREAM_FLUSH, sizeof(USERSTREAM_FLUSH)-1, 0); call_result = call_user_function_ex(NULL, &us->object, &func_name, &retval, 0, NULL, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && retval != NULL && zval_is_true(retval)) call_result = 0; else call_result = -1; if (retval) zval_ptr_dtor(&retval); return call_result; } static int php_userstreamop_seek(php_stream *stream, off_t offset, int whence, off_t *newoffs TSRMLS_DC) { zval func_name; zval *retval = NULL; int call_result, ret; php_userstream_data_t *us = (php_userstream_data_t *)stream->abstract; zval **args[2]; zval *zoffs, *zwhence; assert(us != NULL); ZVAL_STRINGL(&func_name, USERSTREAM_SEEK, sizeof(USERSTREAM_SEEK)-1, 0); MAKE_STD_ZVAL(zoffs); ZVAL_LONG(zoffs, offset); args[0] = &zoffs; MAKE_STD_ZVAL(zwhence); ZVAL_LONG(zwhence, whence); args[1] = &zwhence; call_result = call_user_function_ex(NULL, &us->object, &func_name, &retval, 2, args, 0, NULL TSRMLS_CC); zval_ptr_dtor(&zoffs); zval_ptr_dtor(&zwhence); if (call_result == FAILURE) { /* stream_seek is not implemented, so disable seeks for this stream */ stream->flags |= PHP_STREAM_FLAG_NO_SEEK; /* there should be no retval to clean up */ if (retval) zval_ptr_dtor(&retval); return -1; } else if (call_result == SUCCESS && retval != NULL && zval_is_true(retval)) { ret = 0; } else { ret = -1; } if (retval) { zval_ptr_dtor(&retval); retval = NULL; } if (ret) { return ret; } /* now determine where we are */ ZVAL_STRINGL(&func_name, USERSTREAM_TELL, sizeof(USERSTREAM_TELL)-1, 0); call_result = call_user_function_ex(NULL, &us->object, &func_name, &retval, 0, NULL, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && retval != NULL && Z_TYPE_P(retval) == IS_LONG) { *newoffs = Z_LVAL_P(retval); ret = 0; } else if (call_result == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_TELL " is not implemented!", us->wrapper->classname); ret = -1; } else { ret = -1; } if (retval) { zval_ptr_dtor(&retval); } return ret; } /* parse the return value from one of the stat functions and store the * relevant fields into the statbuf provided */ static int statbuf_from_array(zval *array, php_stream_statbuf *ssb TSRMLS_DC) { zval **elem; #define STAT_PROP_ENTRY_EX(name, name2) \ if (SUCCESS == zend_hash_find(Z_ARRVAL_P(array), #name, sizeof(#name), (void**)&elem)) { \ SEPARATE_ZVAL(elem); \ convert_to_long(*elem); \ ssb->sb.st_##name2 = Z_LVAL_PP(elem); \ } #define STAT_PROP_ENTRY(name) STAT_PROP_ENTRY_EX(name,name) STAT_PROP_ENTRY(dev); STAT_PROP_ENTRY(ino); STAT_PROP_ENTRY(mode); STAT_PROP_ENTRY(nlink); STAT_PROP_ENTRY(uid); STAT_PROP_ENTRY(gid); #if HAVE_ST_RDEV STAT_PROP_ENTRY(rdev); #endif STAT_PROP_ENTRY(size); #ifdef NETWARE STAT_PROP_ENTRY_EX(atime, atime.tv_sec); STAT_PROP_ENTRY_EX(mtime, mtime.tv_sec); STAT_PROP_ENTRY_EX(ctime, ctime.tv_sec); #else STAT_PROP_ENTRY(atime); STAT_PROP_ENTRY(mtime); STAT_PROP_ENTRY(ctime); #endif #ifdef HAVE_ST_BLKSIZE STAT_PROP_ENTRY(blksize); #endif #ifdef HAVE_ST_BLOCKS STAT_PROP_ENTRY(blocks); #endif #undef STAT_PROP_ENTRY #undef STAT_PROP_ENTRY_EX return SUCCESS; } static int php_userstreamop_stat(php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC) { zval func_name; zval *retval = NULL; int call_result; php_userstream_data_t *us = (php_userstream_data_t *)stream->abstract; int ret = -1; ZVAL_STRINGL(&func_name, USERSTREAM_STAT, sizeof(USERSTREAM_STAT)-1, 0); call_result = call_user_function_ex(NULL, &us->object, &func_name, &retval, 0, NULL, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && retval != NULL && Z_TYPE_P(retval) == IS_ARRAY) { if (SUCCESS == statbuf_from_array(retval, ssb TSRMLS_CC)) ret = 0; } else { if (call_result == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_STAT " is not implemented!", us->wrapper->classname); } } if (retval) zval_ptr_dtor(&retval); return ret; } static int php_userstreamop_set_option(php_stream *stream, int option, int value, void *ptrparam TSRMLS_DC) { zval func_name; zval *retval = NULL; int call_result; php_userstream_data_t *us = (php_userstream_data_t *)stream->abstract; int ret = -1; zval *zvalue = NULL; zval **args[3]; switch (option) { case PHP_STREAM_OPTION_CHECK_LIVENESS: ZVAL_STRINGL(&func_name, USERSTREAM_EOF, sizeof(USERSTREAM_EOF)-1, 0); call_result = call_user_function_ex(NULL, &us->object, &func_name, &retval, 0, NULL, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && retval != NULL && Z_TYPE_P(retval) == IS_BOOL) { ret = zval_is_true(retval) ? PHP_STREAM_OPTION_RETURN_ERR : PHP_STREAM_OPTION_RETURN_OK; } else { ret = PHP_STREAM_OPTION_RETURN_ERR; php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_EOF " is not implemented! Assuming EOF", us->wrapper->classname); } break; case PHP_STREAM_OPTION_LOCKING: MAKE_STD_ZVAL(zvalue); ZVAL_LONG(zvalue, 0); if (value & LOCK_NB) { Z_LVAL_P(zvalue) |= PHP_LOCK_NB; } switch(value & ~LOCK_NB) { case LOCK_SH: Z_LVAL_P(zvalue) |= PHP_LOCK_SH; break; case LOCK_EX: Z_LVAL_P(zvalue) |= PHP_LOCK_EX; break; case LOCK_UN: Z_LVAL_P(zvalue) |= PHP_LOCK_UN; break; } args[0] = &zvalue; /* TODO wouldblock */ ZVAL_STRINGL(&func_name, USERSTREAM_LOCK, sizeof(USERSTREAM_LOCK)-1, 0); call_result = call_user_function_ex(NULL, &us->object, &func_name, &retval, 1, args, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && retval != NULL && Z_TYPE_P(retval) == IS_BOOL) { ret = !Z_LVAL_P(retval); } else if (call_result == FAILURE) { if (value == 0) { /* lock support test (TODO: more check) */ ret = 0; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_LOCK " is not implemented!", us->wrapper->classname); } } break; case PHP_STREAM_OPTION_READ_BUFFER: case PHP_STREAM_OPTION_WRITE_BUFFER: case PHP_STREAM_OPTION_READ_TIMEOUT: case PHP_STREAM_OPTION_BLOCKING: { zval *zoption = NULL; zval *zptrparam = NULL; ZVAL_STRINGL(&func_name, USERSTREAM_SET_OPTION, sizeof(USERSTREAM_SET_OPTION)-1, 0); ALLOC_INIT_ZVAL(zoption); ZVAL_LONG(zoption, option); ALLOC_INIT_ZVAL(zvalue); ALLOC_INIT_ZVAL(zptrparam); args[0] = &zoption; args[1] = &zvalue; args[2] = &zptrparam; switch(option) { case PHP_STREAM_OPTION_READ_BUFFER: case PHP_STREAM_OPTION_WRITE_BUFFER: ZVAL_LONG(zvalue, value); if (ptrparam) { ZVAL_LONG(zptrparam, *(long *)ptrparam); } else { ZVAL_LONG(zptrparam, BUFSIZ); } break; case PHP_STREAM_OPTION_READ_TIMEOUT: { struct timeval tv = *(struct timeval*)ptrparam; ZVAL_LONG(zvalue, tv.tv_sec); ZVAL_LONG(zptrparam, tv.tv_usec); break; } case PHP_STREAM_OPTION_BLOCKING: ZVAL_LONG(zvalue, value); break; default: break; } call_result = call_user_function_ex(NULL, &us->object, &func_name, &retval, 3, args, 0, NULL TSRMLS_CC); do { if (call_result == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_SET_OPTION " is not implemented!", us->wrapper->classname); break; } if (retval && zend_is_true(retval)) { ret = PHP_STREAM_OPTION_RETURN_OK; } } while (0); if (zoption) { zval_ptr_dtor(&zoption); } if (zptrparam) { zval_ptr_dtor(&zptrparam); } break; } } /* clean up */ if (retval) { zval_ptr_dtor(&retval); } if (zvalue) { zval_ptr_dtor(&zvalue); } return ret; } static int user_wrapper_unlink(php_stream_wrapper *wrapper, char *url, int options, php_stream_context *context TSRMLS_DC) { struct php_user_stream_wrapper *uwrap = (struct php_user_stream_wrapper*)wrapper->abstract; zval *zfilename, *zfuncname, *zretval; zval **args[1]; int call_result; zval *object; int ret = 0; /* create an instance of our class */ ALLOC_ZVAL(object); object_init_ex(object, uwrap->ce); Z_SET_REFCOUNT_P(object, 1); Z_SET_ISREF_P(object); if (context) { add_property_resource(object, "context", context->rsrc_id); zend_list_addref(context->rsrc_id); } else { add_property_null(object, "context"); } /* call the unlink method */ MAKE_STD_ZVAL(zfilename); ZVAL_STRING(zfilename, url, 1); args[0] = &zfilename; MAKE_STD_ZVAL(zfuncname); ZVAL_STRING(zfuncname, USERSTREAM_UNLINK, 1); call_result = call_user_function_ex(NULL, &object, zfuncname, &zretval, 1, args, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && zretval && Z_TYPE_P(zretval) == IS_BOOL) { ret = Z_LVAL_P(zretval); } else if (call_result == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_UNLINK " is not implemented!", uwrap->classname); } /* clean up */ zval_ptr_dtor(&object); if (zretval) zval_ptr_dtor(&zretval); zval_ptr_dtor(&zfuncname); zval_ptr_dtor(&zfilename); return ret; } static int user_wrapper_rename(php_stream_wrapper *wrapper, char *url_from, char *url_to, int options, php_stream_context *context TSRMLS_DC) { struct php_user_stream_wrapper *uwrap = (struct php_user_stream_wrapper*)wrapper->abstract; zval *zold_name, *znew_name, *zfuncname, *zretval; zval **args[2]; int call_result; zval *object; int ret = 0; /* create an instance of our class */ ALLOC_ZVAL(object); object_init_ex(object, uwrap->ce); Z_SET_REFCOUNT_P(object, 1); Z_SET_ISREF_P(object); if (context) { add_property_resource(object, "context", context->rsrc_id); zend_list_addref(context->rsrc_id); } else { add_property_null(object, "context"); } /* call the rename method */ MAKE_STD_ZVAL(zold_name); ZVAL_STRING(zold_name, url_from, 1); args[0] = &zold_name; MAKE_STD_ZVAL(znew_name); ZVAL_STRING(znew_name, url_to, 1); args[1] = &znew_name; MAKE_STD_ZVAL(zfuncname); ZVAL_STRING(zfuncname, USERSTREAM_RENAME, 1); call_result = call_user_function_ex(NULL, &object, zfuncname, &zretval, 2, args, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && zretval && Z_TYPE_P(zretval) == IS_BOOL) { ret = Z_LVAL_P(zretval); } else if (call_result == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_RENAME " is not implemented!", uwrap->classname); } /* clean up */ zval_ptr_dtor(&object); if (zretval) zval_ptr_dtor(&zretval); zval_ptr_dtor(&zfuncname); zval_ptr_dtor(&zold_name); zval_ptr_dtor(&znew_name); return ret; } static int user_wrapper_mkdir(php_stream_wrapper *wrapper, char *url, int mode, int options, php_stream_context *context TSRMLS_DC) { struct php_user_stream_wrapper *uwrap = (struct php_user_stream_wrapper*)wrapper->abstract; zval *zfilename, *zmode, *zoptions, *zfuncname, *zretval; zval **args[3]; int call_result; zval *object; int ret = 0; /* create an instance of our class */ ALLOC_ZVAL(object); object_init_ex(object, uwrap->ce); Z_SET_REFCOUNT_P(object, 1); Z_SET_ISREF_P(object); if (context) { add_property_resource(object, "context", context->rsrc_id); zend_list_addref(context->rsrc_id); } else { add_property_null(object, "context"); } /* call the mkdir method */ MAKE_STD_ZVAL(zfilename); ZVAL_STRING(zfilename, url, 1); args[0] = &zfilename; MAKE_STD_ZVAL(zmode); ZVAL_LONG(zmode, mode); args[1] = &zmode; MAKE_STD_ZVAL(zoptions); ZVAL_LONG(zoptions, options); args[2] = &zoptions; MAKE_STD_ZVAL(zfuncname); ZVAL_STRING(zfuncname, USERSTREAM_MKDIR, 1); call_result = call_user_function_ex(NULL, &object, zfuncname, &zretval, 3, args, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && zretval && Z_TYPE_P(zretval) == IS_BOOL) { ret = Z_LVAL_P(zretval); } else if (call_result == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_MKDIR " is not implemented!", uwrap->classname); } /* clean up */ zval_ptr_dtor(&object); if (zretval) { zval_ptr_dtor(&zretval); } zval_ptr_dtor(&zfuncname); zval_ptr_dtor(&zfilename); zval_ptr_dtor(&zmode); zval_ptr_dtor(&zoptions); return ret; } static int user_wrapper_rmdir(php_stream_wrapper *wrapper, char *url, int options, php_stream_context *context TSRMLS_DC) { struct php_user_stream_wrapper *uwrap = (struct php_user_stream_wrapper*)wrapper->abstract; zval *zfilename, *zoptions, *zfuncname, *zretval; zval **args[3]; int call_result; zval *object; int ret = 0; /* create an instance of our class */ ALLOC_ZVAL(object); object_init_ex(object, uwrap->ce); Z_SET_REFCOUNT_P(object, 1); Z_SET_ISREF_P(object); if (context) { add_property_resource(object, "context", context->rsrc_id); zend_list_addref(context->rsrc_id); } else { add_property_null(object, "context"); } /* call the rmdir method */ MAKE_STD_ZVAL(zfilename); ZVAL_STRING(zfilename, url, 1); args[0] = &zfilename; MAKE_STD_ZVAL(zoptions); ZVAL_LONG(zoptions, options); args[1] = &zoptions; MAKE_STD_ZVAL(zfuncname); ZVAL_STRING(zfuncname, USERSTREAM_RMDIR, 1); call_result = call_user_function_ex(NULL, &object, zfuncname, &zretval, 2, args, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && zretval && Z_TYPE_P(zretval) == IS_BOOL) { ret = Z_LVAL_P(zretval); } else if (call_result == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_RMDIR " is not implemented!", uwrap->classname); } /* clean up */ zval_ptr_dtor(&object); if (zretval) { zval_ptr_dtor(&zretval); } zval_ptr_dtor(&zfuncname); zval_ptr_dtor(&zfilename); zval_ptr_dtor(&zoptions); return ret; } static int user_wrapper_stat_url(php_stream_wrapper *wrapper, char *url, int flags, php_stream_statbuf *ssb, php_stream_context *context TSRMLS_DC) { struct php_user_stream_wrapper *uwrap = (struct php_user_stream_wrapper*)wrapper->abstract; zval *zfilename, *zfuncname, *zretval, *zflags; zval **args[2]; int call_result; zval *object; int ret = -1; /* create an instance of our class */ ALLOC_ZVAL(object); object_init_ex(object, uwrap->ce); Z_SET_REFCOUNT_P(object, 1); Z_SET_ISREF_P(object); if (context) { add_property_resource(object, "context", context->rsrc_id); zend_list_addref(context->rsrc_id); } else { add_property_null(object, "context"); } /* call it's stat_url method - set up params first */ MAKE_STD_ZVAL(zfilename); ZVAL_STRING(zfilename, url, 1); args[0] = &zfilename; MAKE_STD_ZVAL(zflags); ZVAL_LONG(zflags, flags); args[1] = &zflags; MAKE_STD_ZVAL(zfuncname); ZVAL_STRING(zfuncname, USERSTREAM_STATURL, 1); call_result = call_user_function_ex(NULL, &object, zfuncname, &zretval, 2, args, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && zretval != NULL && Z_TYPE_P(zretval) == IS_ARRAY) { /* We got the info we needed */ if (SUCCESS == statbuf_from_array(zretval, ssb TSRMLS_CC)) ret = 0; } else { if (call_result == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_STATURL " is not implemented!", uwrap->classname); } } /* clean up */ zval_ptr_dtor(&object); if (zretval) zval_ptr_dtor(&zretval); zval_ptr_dtor(&zfuncname); zval_ptr_dtor(&zfilename); zval_ptr_dtor(&zflags); return ret; } static size_t php_userstreamop_readdir(php_stream *stream, char *buf, size_t count TSRMLS_DC) { zval func_name; zval *retval = NULL; int call_result; size_t didread = 0; php_userstream_data_t *us = (php_userstream_data_t *)stream->abstract; php_stream_dirent *ent = (php_stream_dirent*)buf; /* avoid problems if someone mis-uses the stream */ if (count != sizeof(php_stream_dirent)) return 0; ZVAL_STRINGL(&func_name, USERSTREAM_DIR_READ, sizeof(USERSTREAM_DIR_READ)-1, 0); call_result = call_user_function_ex(NULL, &us->object, &func_name, &retval, 0, NULL, 0, NULL TSRMLS_CC); if (call_result == SUCCESS && retval != NULL && Z_TYPE_P(retval) != IS_BOOL) { convert_to_string(retval); PHP_STRLCPY(ent->d_name, Z_STRVAL_P(retval), sizeof(ent->d_name), Z_STRLEN_P(retval)); didread = sizeof(php_stream_dirent); } else if (call_result == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_DIR_READ " is not implemented!", us->wrapper->classname); } if (retval) zval_ptr_dtor(&retval); return didread; } static int php_userstreamop_closedir(php_stream *stream, int close_handle TSRMLS_DC) { zval func_name; zval *retval = NULL; php_userstream_data_t *us = (php_userstream_data_t *)stream->abstract; assert(us != NULL); ZVAL_STRINGL(&func_name, USERSTREAM_DIR_CLOSE, sizeof(USERSTREAM_DIR_CLOSE)-1, 0); call_user_function_ex(NULL, &us->object, &func_name, &retval, 0, NULL, 0, NULL TSRMLS_CC); if (retval) zval_ptr_dtor(&retval); zval_ptr_dtor(&us->object); efree(us); return 0; } static int php_userstreamop_rewinddir(php_stream *stream, off_t offset, int whence, off_t *newoffs TSRMLS_DC) { zval func_name; zval *retval = NULL; php_userstream_data_t *us = (php_userstream_data_t *)stream->abstract; ZVAL_STRINGL(&func_name, USERSTREAM_DIR_REWIND, sizeof(USERSTREAM_DIR_REWIND)-1, 0); call_user_function_ex(NULL, &us->object, &func_name, &retval, 0, NULL, 0, NULL TSRMLS_CC); if (retval) zval_ptr_dtor(&retval); return 0; } static int php_userstreamop_cast(php_stream *stream, int castas, void **retptr TSRMLS_DC) { php_userstream_data_t *us = (php_userstream_data_t *)stream->abstract; zval func_name; zval *retval = NULL; zval *zcastas = NULL; zval **args[1]; php_stream * intstream = NULL; int call_result; int ret = FAILURE; ZVAL_STRINGL(&func_name, USERSTREAM_CAST, sizeof(USERSTREAM_CAST)-1, 0); ALLOC_INIT_ZVAL(zcastas); switch(castas) { case PHP_STREAM_AS_FD_FOR_SELECT: ZVAL_LONG(zcastas, PHP_STREAM_AS_FD_FOR_SELECT); break; default: ZVAL_LONG(zcastas, PHP_STREAM_AS_STDIO); break; } args[0] = &zcastas; call_result = call_user_function_ex(NULL, &us->object, &func_name, &retval, 1, args, 0, NULL TSRMLS_CC); do { if (call_result == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_CAST " is not implemented!", us->wrapper->classname); break; } if (retval == NULL || !zend_is_true(retval)) { break; } php_stream_from_zval_no_verify(intstream, &retval); if (!intstream) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_CAST " must return a stream resource", us->wrapper->classname); break; } if (intstream == stream) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s::" USERSTREAM_CAST " must not return itself", us->wrapper->classname); intstream = NULL; break; } ret = php_stream_cast(intstream, castas, retptr, 1); } while (0); if (retval) { zval_ptr_dtor(&retval); } if (zcastas) { zval_ptr_dtor(&zcastas); } return ret; } php_stream_ops php_stream_userspace_ops = { php_userstreamop_write, php_userstreamop_read, php_userstreamop_close, php_userstreamop_flush, "user-space", php_userstreamop_seek, php_userstreamop_cast, php_userstreamop_stat, php_userstreamop_set_option, }; php_stream_ops php_stream_userspace_dir_ops = { NULL, /* write */ php_userstreamop_readdir, php_userstreamop_closedir, NULL, /* flush */ "user-space-dir", php_userstreamop_rewinddir, NULL, /* cast */ NULL, /* stat */ NULL /* set_option */ };
Defects4J/APR_LLMs/code/LLM_repair/ManyBugs/buggy_programs/php_2011-02-01-01745fa657-1f49902999.c